diff --git a/.classpath b/.classpath deleted file mode 100644 index 3238145f4..000000000 --- a/.classpath +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/.project b/.project deleted file mode 100644 index 274051f30..000000000 --- a/.project +++ /dev/null @@ -1,18 +0,0 @@ - - - ApachePOI - - - - - - org.eclipse.jdt.core.javabuilder - - - - - - org.sonar.ide.eclipse.core.sonarNature - org.eclipse.jdt.core.javanature - - diff --git a/.settings/org.eclipse.core.resources.prefs b/.settings/org.eclipse.core.resources.prefs deleted file mode 100644 index 4824b8026..000000000 --- a/.settings/org.eclipse.core.resources.prefs +++ /dev/null @@ -1,2 +0,0 @@ -eclipse.preferences.version=1 -encoding/=UTF-8 diff --git a/.settings/org.eclipse.jdt.core.prefs b/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index d79262b1d..000000000 --- a/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,397 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.jdt.core.codeComplete.argumentPrefixes= -org.eclipse.jdt.core.codeComplete.argumentSuffixes= -org.eclipse.jdt.core.codeComplete.fieldPrefixes= -org.eclipse.jdt.core.codeComplete.fieldSuffixes= -org.eclipse.jdt.core.codeComplete.localPrefixes= -org.eclipse.jdt.core.codeComplete.localSuffixes= -org.eclipse.jdt.core.codeComplete.staticFieldPrefixes= -org.eclipse.jdt.core.codeComplete.staticFieldSuffixes= -org.eclipse.jdt.core.codeComplete.staticFinalFieldPrefixes= -org.eclipse.jdt.core.codeComplete.staticFinalFieldSuffixes= -org.eclipse.jdt.core.compiler.annotation.inheritNullAnnotations=disabled -org.eclipse.jdt.core.compiler.annotation.missingNonNullByDefaultAnnotation=ignore -org.eclipse.jdt.core.compiler.annotation.nonnull=org.eclipse.jdt.annotation.NonNull -org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=org.eclipse.jdt.annotation.NonNullByDefault -org.eclipse.jdt.core.compiler.annotation.nullable=org.eclipse.jdt.annotation.Nullable -org.eclipse.jdt.core.compiler.annotation.nullanalysis=disabled -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 -org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.6 -org.eclipse.jdt.core.compiler.debug.lineNumber=generate -org.eclipse.jdt.core.compiler.debug.localVariable=generate -org.eclipse.jdt.core.compiler.debug.sourceFile=generate -org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.autoboxing=ignore -org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning -org.eclipse.jdt.core.compiler.problem.deadCode=warning -org.eclipse.jdt.core.compiler.problem.deprecation=warning -org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled -org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled -org.eclipse.jdt.core.compiler.problem.discouragedReference=warning -org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable=ignore -org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore -org.eclipse.jdt.core.compiler.problem.fatalOptionalError=disabled -org.eclipse.jdt.core.compiler.problem.fieldHiding=ignore -org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning -org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning -org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning -org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning -org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=disabled -org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning -org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=warning -org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore -org.eclipse.jdt.core.compiler.problem.localVariableHiding=ignore -org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning -org.eclipse.jdt.core.compiler.problem.missingDefaultCase=ignore -org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore -org.eclipse.jdt.core.compiler.problem.missingEnumCaseDespiteDefault=disabled -org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=warning -org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore -org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled -org.eclipse.jdt.core.compiler.problem.missingSerialVersion=ignore -org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore -org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning -org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning -org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore -org.eclipse.jdt.core.compiler.problem.nonnullParameterAnnotationDropped=warning -org.eclipse.jdt.core.compiler.problem.nonnullTypeVariableFromLegacyInvocation=warning -org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=error -org.eclipse.jdt.core.compiler.problem.nullReference=warning -org.eclipse.jdt.core.compiler.problem.nullSpecViolation=error -org.eclipse.jdt.core.compiler.problem.nullUncheckedConversion=warning -org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning -org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore -org.eclipse.jdt.core.compiler.problem.pessimisticNullAnalysisForFreeTypeVariables=warning -org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore -org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore -org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=ignore -org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning -org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation=warning -org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore -org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=ignore -org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore -org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore -org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore -org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled -org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning -org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=disabled -org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled -org.eclipse.jdt.core.compiler.problem.syntacticNullAnalysisForFields=disabled -org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore -org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning -org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=enabled -org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning -org.eclipse.jdt.core.compiler.problem.unclosedCloseable=warning -org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore -org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=ignore -org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore -org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=warning -org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled -org.eclipse.jdt.core.compiler.problem.unusedExceptionParameter=ignore -org.eclipse.jdt.core.compiler.problem.unusedImport=warning -org.eclipse.jdt.core.compiler.problem.unusedLabel=warning -org.eclipse.jdt.core.compiler.problem.unusedLocal=warning -org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=ignore -org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore -org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled -org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled -org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled -org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning -org.eclipse.jdt.core.compiler.problem.unusedTypeParameter=ignore -org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning -org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning -org.eclipse.jdt.core.compiler.source=1.6 -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_lambda_body=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_after_type_annotation=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_lambda_arrow=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_lambda_arrow=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=false -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 diff --git a/.settings/org.eclipse.jdt.ui.prefs b/.settings/org.eclipse.jdt.ui.prefs deleted file mode 100644 index 5227bd285..000000000 --- a/.settings/org.eclipse.jdt.ui.prefs +++ /dev/null @@ -1,131 +0,0 @@ -cleanup.add_default_serial_version_id=true -cleanup.add_generated_serial_version_id=false -cleanup.add_missing_annotations=true -cleanup.add_missing_deprecated_annotations=true -cleanup.add_missing_methods=false -cleanup.add_missing_nls_tags=false -cleanup.add_missing_override_annotations=true -cleanup.add_missing_override_annotations_interface_methods=true -cleanup.add_serial_version_id=false -cleanup.always_use_blocks=true -cleanup.always_use_parentheses_in_expressions=false -cleanup.always_use_this_for_non_static_field_access=false -cleanup.always_use_this_for_non_static_method_access=false -cleanup.convert_functional_interfaces=false -cleanup.convert_to_enhanced_for_loop=false -cleanup.correct_indentation=false -cleanup.format_source_code=false -cleanup.format_source_code_changes_only=false -cleanup.insert_inferred_type_arguments=false -cleanup.make_local_variable_final=true -cleanup.make_parameters_final=false -cleanup.make_private_fields_final=true -cleanup.make_type_abstract_if_missing_method=false -cleanup.make_variable_declarations_final=false -cleanup.never_use_blocks=false -cleanup.never_use_parentheses_in_expressions=true -cleanup.organize_imports=false -cleanup.qualify_static_field_accesses_with_declaring_class=false -cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true -cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true -cleanup.qualify_static_member_accesses_with_declaring_class=true -cleanup.qualify_static_method_accesses_with_declaring_class=false -cleanup.remove_private_constructors=true -cleanup.remove_redundant_type_arguments=true -cleanup.remove_trailing_whitespaces=false -cleanup.remove_trailing_whitespaces_all=true -cleanup.remove_trailing_whitespaces_ignore_empty=false -cleanup.remove_unnecessary_casts=true -cleanup.remove_unnecessary_nls_tags=true -cleanup.remove_unused_imports=true -cleanup.remove_unused_local_variables=false -cleanup.remove_unused_private_fields=true -cleanup.remove_unused_private_members=false -cleanup.remove_unused_private_methods=true -cleanup.remove_unused_private_types=true -cleanup.sort_members=false -cleanup.sort_members_all=false -cleanup.use_anonymous_class_creation=false -cleanup.use_blocks=false -cleanup.use_blocks_only_for_return_and_throw=false -cleanup.use_lambda=true -cleanup.use_parentheses_in_expressions=false -cleanup.use_this_for_non_static_field_access=false -cleanup.use_this_for_non_static_field_access_only_if_necessary=true -cleanup.use_this_for_non_static_method_access=false -cleanup.use_this_for_non_static_method_access_only_if_necessary=true -cleanup.use_type_arguments=false -cleanup_profile=_Apache POI -cleanup_settings_version=2 -eclipse.preferences.version=1 -editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=false -formatter_profile=_Apache POI -formatter_settings_version=12 -org.eclipse.jdt.ui.exception.name=e -org.eclipse.jdt.ui.gettersetter.use.is=true -org.eclipse.jdt.ui.ignorelowercasenames=true -org.eclipse.jdt.ui.importorder=java;javax;org;com; -org.eclipse.jdt.ui.javadoc=false -org.eclipse.jdt.ui.keywordthis=false -org.eclipse.jdt.ui.ondemandthreshold=20 -org.eclipse.jdt.ui.overrideannotation=false -org.eclipse.jdt.ui.staticondemandthreshold=10 -org.eclipse.jdt.ui.text.custom_code_templates= -sp_cleanup.add_default_serial_version_id=true -sp_cleanup.add_generated_serial_version_id=false -sp_cleanup.add_missing_annotations=true -sp_cleanup.add_missing_deprecated_annotations=true -sp_cleanup.add_missing_methods=false -sp_cleanup.add_missing_nls_tags=false -sp_cleanup.add_missing_override_annotations=true -sp_cleanup.add_missing_override_annotations_interface_methods=true -sp_cleanup.add_serial_version_id=false -sp_cleanup.always_use_blocks=true -sp_cleanup.always_use_parentheses_in_expressions=false -sp_cleanup.always_use_this_for_non_static_field_access=false -sp_cleanup.always_use_this_for_non_static_method_access=false -sp_cleanup.convert_functional_interfaces=false -sp_cleanup.convert_to_enhanced_for_loop=true -sp_cleanup.correct_indentation=false -sp_cleanup.format_source_code=false -sp_cleanup.format_source_code_changes_only=false -sp_cleanup.insert_inferred_type_arguments=false -sp_cleanup.make_local_variable_final=false -sp_cleanup.make_parameters_final=false -sp_cleanup.make_private_fields_final=true -sp_cleanup.make_type_abstract_if_missing_method=false -sp_cleanup.make_variable_declarations_final=false -sp_cleanup.never_use_blocks=false -sp_cleanup.never_use_parentheses_in_expressions=true -sp_cleanup.on_save_use_additional_actions=false -sp_cleanup.organize_imports=false -sp_cleanup.qualify_static_field_accesses_with_declaring_class=false -sp_cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true -sp_cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true -sp_cleanup.qualify_static_member_accesses_with_declaring_class=false -sp_cleanup.qualify_static_method_accesses_with_declaring_class=false -sp_cleanup.remove_private_constructors=true -sp_cleanup.remove_redundant_type_arguments=false -sp_cleanup.remove_trailing_whitespaces=false -sp_cleanup.remove_trailing_whitespaces_all=true -sp_cleanup.remove_trailing_whitespaces_ignore_empty=false -sp_cleanup.remove_unnecessary_casts=true -sp_cleanup.remove_unnecessary_nls_tags=false -sp_cleanup.remove_unused_imports=true -sp_cleanup.remove_unused_local_variables=false -sp_cleanup.remove_unused_private_fields=true -sp_cleanup.remove_unused_private_members=false -sp_cleanup.remove_unused_private_methods=true -sp_cleanup.remove_unused_private_types=true -sp_cleanup.sort_members=false -sp_cleanup.sort_members_all=false -sp_cleanup.use_anonymous_class_creation=false -sp_cleanup.use_blocks=true -sp_cleanup.use_blocks_only_for_return_and_throw=false -sp_cleanup.use_lambda=false -sp_cleanup.use_parentheses_in_expressions=false -sp_cleanup.use_this_for_non_static_field_access=false -sp_cleanup.use_this_for_non_static_field_access_only_if_necessary=true -sp_cleanup.use_this_for_non_static_method_access=false -sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=true -sp_cleanup.use_type_arguments=false diff --git a/.settings/org.moreunit.core.prefs b/.settings/org.moreunit.core.prefs deleted file mode 100644 index efd9d77f2..000000000 --- a/.settings/org.moreunit.core.prefs +++ /dev/null @@ -1,4 +0,0 @@ -eclipse.preferences.version=1 -org.moreunit.core.anyLanguage.srcFolderPathTemplate=${srcProject} -org.moreunit.core.anyLanguage.testFileNameTemplate=${srcFile}Test -org.moreunit.core.anyLanguage.testFolderPathTemplate=${srcProject} diff --git a/.settings/org.moreunit.prefs b/.settings/org.moreunit.prefs deleted file mode 100644 index 659afaf8c..000000000 --- a/.settings/org.moreunit.prefs +++ /dev/null @@ -1,4 +0,0 @@ -eclipse.preferences.version=1 -org.moreunit.preferences.version=2 -org.moreunit.unitsourcefolder=ApachePOI\:src/java\:ApachePOI\:src/testcases\#ApachePOI\:src/java\:ApachePOI\:src/ooxml/testcases\#ApachePOI\:src/java\:ApachePOI\:src/scratchpad/testcases\#ApachePOI\:src/java\:ApachePOI\:src/excelant/testcases\#ApachePOI\:src/java\:ApachePOI\:src/integrationtest -org.moreunit.useprojectsettings=true diff --git a/KEYS b/KEYS deleted file mode 100644 index 5926e7c28..000000000 --- a/KEYS +++ /dev/null @@ -1,2495 +0,0 @@ -This file contains the PGP keys of various developers. - -Users: pgp < KEYS - gpg --import KEYS -Developers: - gpg --list-key and append it to this file. - gpg -a --export and append it to this file. - - (gpg --list-key - && gpg --armor --export ) >> this file. - -Since the KEYS may be needed to check signatures for archived -releases, it is important that all keys that have ever been used -to sign releases are retained in the file. Entries should only -be added, not removed. -To keep the KEYS file manageable, it's recommended to only add -the keys of committers who have signed releases. -https://www.apache.org/dev/release-signing#keys-policy -https://people.apache.org/keys/ - - -pub 1024D/12DAE9BE 2004-01-25 Glen Stampoultzis -sig 3 12DAE9BE 2004-01-25 Glen Stampoultzis -sub 1024g/2BBB28EA 2004-01-25 -sig 12DAE9BE 2004-01-25 Glen Stampoultzis - ------BEGIN PGP PUBLIC KEY BLOCK----- -Version: GnuPG v1.2.2 (Cygwin) - -mQGiBEATU6gRBACo3iUkfku4/G2q8ldWFiiCekHK5oqx0U1N6fyO+Xgs+6V6btEZ -drF2DUCyto6ig4FJT81L34HUQ6l9bPnpa4nNsl2EMBknY42LjmC55x7Q5rsQbiRj -+2JkoQJk2Jc3hneuh4Wsv49stOCDQMOV5BtjZs31t7rr+wuKPMkIw/Nf1wCgngI9 -ZWFyLxspoi9bL1/xBID18jsD/RxGBep4F8HwXEdHTeHnmjEuJSlYhmAKQ6Fd7bdb -ex16a54Gsg7fVD0rIIsytzVUACQMi7V6tmE4Wf/XaY7+ma5w4gCsxUCIeujU4Y7i -WUDwtlTkr2IudmoxSIDDpS12NPZqCP7PbU2RK+KwnnITjs80a+QlHYaO9te7HVcL -F6YIA/9YZkYp5TpoMO1ISnlv0gXMcIaznbNMoRgeXZHvYyEvy014jArHmG41LVBj -6TnBHFLQi4xA7Ql98oIgfszaRr/9GshvoL6Iu1x1SoV7dMrqFBC6e2JD9N/IgBtZ -EGg7US3nIJnlCjJSIkXKfPJL4FyYWwt6IEZcF6Mi/USsyLA6wrQkR2xlbiBTdGFt -cG91bHR6aXMgPGdsZW5zQGFwYWNoZS5vcmc+iFsEExECABsFAkATU6gGCwkIBwMC -AxUCAwMWAgECHgECF4AACgkQONrI4hLa6b48RgCaAqQg0wtiOQ8jqX6S7tZi1OMg -CQAAn2Ty1d/UdGLqlGkCPMkaB6otTMhZuQENBEATU6kQBADUbn5pT2D8vi64RU5E -SeTn/rNzLglJ4nzoOfeIcHm7p3hppjT0Q1YbHvdOSaigYApzxoiSf+0Mt8NSCfDf -B/wjfndHlrcdPkiJi4fBkQHihcuJtEgOkAwXfSJ+MUXG+fEgEuGdYm7tNV3n/eOY -gn9Vzs/LofrQ7nY3+WkNOUia/wADBwQAnqZ4wPm0VY/fjCWJ34wvSfPk6Qg8m502 -MfHIGY/UZ+BY5DK3iQR8hrIu6FU0tn0qoF7PCNehOtd2cR9kA7I2gyfaVR8JY2Ek -F18jungrNRrNuNx3rJeUD6ViQjC44K4vf6y8CkxmkHTmB9ZC2+uGdMeOdDvbck/u -JA+XB2tykJWIRgQYEQIABgUCQBNTqQAKCRA42sjiEtrpvpy3AJ4trdVLGCzJwB2R -Z/zxD3xBnTdY5QCeNUdw2VcsrzAF541sawFRxOmL3eY= -=la1N ------END PGP PUBLIC KEY BLOCK----- - - -pub 1024D/4CEED75F 2004-03-24 [expires: 2010-01-01] -uid Nick Burch -uid Nick Burch -sub 1024g/5E0E1748 2004-03-24 - ------BEGIN PGP PUBLIC KEY BLOCK----- -Version: GnuPG v1.4.9 (GNU/Linux) - -mQGiBEBhnKkRBACOPYQoULwS4a37UsNiinwqJ+2XVMal5FQyMOc6hNneyvdau4cO -oSNgdEkNtAN9fecSh06wke9mFBR9iVD4QpCqiRk8s20lr4QAFw4urxbe6iOf/Ytr -q7I0t3/zpzx4MuzwvN7ffPaE5EzE6F3ryQDkSulMeLzDbdRSZIezocDyQwCgpKTA -UtpUwP38GH81VCtbEWfEJpMD/jraHQdr4KXnv7iIvGtOLbODrmgfGfZYPsGoJlHl -+IIFdTfRCbUNc1Mh9/vcP45bnX62Crsp2JuDxZo8Dq4buE77pZ/Yw1aaIzhHBGcP -YlIvLz/S2WCZxKyNrIE86WK/DlMAXoHAJigErD+X1UYLNVb0+u5MeHN+FF0yLMS4 -9Cp4A/wJznIOc7sO+L6psNNUWSu1G9TAPo6QRu/6CTaYHMy8uMzovjrlYF9bjZFe -9TVJUkHYMv2tsthZ7eWG0jAyHabvn1XgCDRjJcs10FZ6obIU5BDaJLjaxMU+u91k -F/AiO1zStA9wuasITcurU3BF4f/ZywJXwVDFvpYUh0xV1pK0qrQfTmljayBCdXJj -aCA8bmlja0BnYWdyYXZhcnIub3JnPohlBBMRAgAdBQJAYZypBQkJZgGABQsHCgME -AxUDAgMWAgECF4AAEgkQ9cJgFkzu118HZUdQRwABASjeAKCXv83+hBN7PMqx9Ate -13EN+mCsNQCfSWj1wVXl3vKBZizH3yQzDDl6yuGIRgQQEQIABgUCQGGc+wAKCRDI -h7WuwLlVejPLAKDoFiCmPsApgl99/Sgbi5+GD6pXXACeLQyS8rg+rz7zOagcMJ+T -XdY87wKIRgQQEQIABgUCQGGeNwAKCRB4Ma11Ja7RdocaAKDVs5beITXLa/9rW5r8 -Qptyhzp1dwCfVxgAMgL00Muh6gSnk7MI23xUgpmJAJUDBRBAYf1wIBRZzICIOAEB -AcEcA/9fO1E2pj1QSOZiX53ngKxF+Vxo8XfuBxbplXQaN2/acUsOGZVp8r5oo+3w -0qzn7YLXpStlnFz40UAjAWJBPtYTnzGR3twpChZRDTRrmaGVAssG+DuJwHBdsC4D -W5QisDTRFg+lyZ5d7bI/H+ckbXma+7BRwPtG0rRXK67O1p3lo4hGBBARAgAGBQJA -YfNUAAoJEEPSiApOm1UCnSIAnjg0phq4MhuzTnBoHoHIbqO7Jj5+AKCQ9HC/d/gO -Hitfw2bcjHMKSwgDeIhMBBARAgAMBQJEEDtmBYMFt2LDAAoJEGao+or0Qx8mutAA -nR8OikkgQDLxBxdaFtFHtsc09lR+AJ48A1Nkex+ZNl0VAEgWLqqoFVkWDIhiBBMR -AgAaBQsHCgMEAxUDAgMWAgECF4ACGQEFAkaCzIEAEgdlR1BHAAEBCRD1wmAWTO7X -X4ExAJ91jwqu1pGuK21TBKNtW+ennH9ppACdGrI/+kN/rkWMAsNgU+uJbjDE7YeI -cwQQEQIAMwUCRBBGKQWDAeEzgCYaaHR0cDovL3d3dy5jYWNlcnQub3JnL2luZGV4 -LnBocD9pZD0xMAAKCRDSuw0BZdD9WK2kAJ9QCMJBHbpzbL+Fh503iw+o1ByNnwCf -f+UFND1piZvaF5XybwKoQ5Wu/NuIRgQTEQIABgUCREvNBQAKCRBghaOGQ6aJantc -AJ9QGBq5kkoI5vMhXi9LKx6b3HdETgCfXVqP43fiL+uQ7VsByLpVLDjFlFOIRgQQ -EQIABgUCRKP0UwAKCRA39o/1AVr8iho4AKDZ1rVmNXD2KAHHJZshHvwGpRz3VwCg -5Z7hpclWyw3OkKaz/G4T08lIhxaIRgQQEQIABgUCRKfNKwAKCRDVM051sTE94iuk -AJ4h3TVd62OH3GpfbNku1tT3XJcvVgCgtSV/04an+u0VSRADSRq/5uBNDeGIRgQQ -EQIABgUCRKkt2wAKCRAyyeTONkLLS6iUAJ97ELvsa6Wlmg5UCsa4AAephiEDFwCg -n0YHqUwx2bVWL1elR53bTWaqEqKIRgQQEQIABgUCRKquQwAKCRA1i6ozUPlhFmyZ -AJ0ajTr1w6VG+Rp8j9MwbziOKQIVrgCeID7Mg0N3mDFE414J21I6As5ad4uIRgQQ -EQIABgUCRKrPUQAKCRD7N9pAMy5jzVa+AJ44NFxehfXUyS5Fwkx5g58Qznv1zACf -arUp2KPdpN0vu5ppqNsFs3F1IfOIRgQQEQIABgUCRQ+CKwAKCRCyvrxAFSkkr6Fg -AJ9RvBUJ4WpvI5sY50PPCQQDrOW0CQCbB9HoxMfs6zZFF0Rm0h8IZ9ONzZyITAQQ -EQIADAUCRKMCVQWDBSSb1AAKCRCUUEP1NcEA8Hd1AJ4sVLyTaUk7hNmxCMO0KmAI -IAJQ5ACdEyi6yNEOsuQrmZ8fvtl8CYp+E/OITAQQEQIADAUCRKON0QWDBSQQWAAK -CRAtIatlZUYbeVBwAJ0YCGDcAhRSdD7iHbqONN4ZJsEeqACcCus5Mck12rdUNuH3 -INWTm5MmX0eITAQQEQIADAUCRKRJ+AWDBSNUMQAKCRArfoLnQ+8hHytfAJ0busES -2PyWxOkyRidcllRSX0rLsQCeKcKHsQjCn6fd/nV7VN/9pwAJRfKITAQREQIADAUC -RKMbGAWDBSSDEQAKCRBWDQhh7n3HTviwAJwKn/we6Khznqlq3svyYn6Z/6FZsQCg -3acpog5M5TXkneKEoml3q9TjmC6ITAQREQIADAUCRKMbKAWDBSSDAQAKCRDKcp1i -YD1PVH7JAJ9M7kVdEF8mLbkjpe9YwHiytkn/HACfa9YGteCB615GB2umE8N5FrIF -uSyITAQTEQIADAUCRKOpaQWDBSP0wAAKCRDdumS6LDEtL8KaAJ91mvnnKJ1sP/tW -8V5ZH9pmVXLy0QCgiZnT7s9rsdAAO7wY/gqctT9rDrGITAQTEQIADAUCRKOpdwWD -BSP0sgAKCRBQjq7FMC2laILDAJsH0OlzaG31pD6ciEJdzzyn8R6kDQCgqY0Wp4Cz -qVRVeZDacRKj13J3fMSITAQTEQIADAUCRKYBJgWDBSGdAwAKCRBMBCgYMRo95cNi -AKC7fFzLCq2StE07S6rzg6qlF2tS8gCcCvoT7YvhqabHSuph+hbrF2KmabWInAQQ -AQIABgUCRKkt6gAKCRA34/Rf7mXjIWs5A/9xV456Fiy+QelbGJ79sHIPl5Kn8VEK -MuWvR+dknShRg88XdrGshMFrX+t2enDxr2upL3R8CA+eVDC/0yRj8SLbvn6nfEOJ -qS8eYKkggdDtWU5nbb4BZvBKAXlddAOsZSFD/h6qw6Rl3ZiDTHOJKjq9Tip/Y9uH -MpdxkKBNS1bqJ4iiBBMBAgAMBQJEo6lgBYMFI/TJAAoJEJrNPMCpn3XdHO0D/jpi -VLkyBXm9pyAaVk+pwEswGiGSheHuJWlkBZDOrMFjM1JKJVb5AQ/VNwxNCmvayrWx -jQEUXCR7eCT3Cp83Xh5YbbdEw9SHkgL7wEtGsK5zYbvtbWt7691P7hf0nuOwCOHM -0oYTtRvwtEPvhwyfh/sSaMrCB40dHcER3Ah8pQBmiEYEEBECAAYFAkY44mwACgkQ -FUWz/uIi3k9ExACePdDgJJIIbFmHOlKsujJWTC/qrA4An0uHorCRVAz8+kKQZgIx -5NqYTsZYiEYEEBECAAYFAkY451cACgkQY9CtrpESA+RUtQCePtNKg8jbrN3ueYjS -trawh3G5lDIAnAnQ/v9Ma/qv5wr9XMDqy1J0HmSfiEYEEBECAAYFAkY8i3YACgkQ -mHDv8/EvYHJ7FwCdEWzRg49FioAHJYyA4aGaBq+E6qAAn1EJYuOIapCkdTNtgSdO -VED8qNk9iEYEExECAAYFAkY9n+AACgkQLrlGgoiBdALMyQCgnKtTU45W/5/onEQw -vmelpzjD3kQAoLbovb7PYL17191lNkhqXQwPfhx4iEYEEBECAAYFAkY99HEACgkQ -oHLU0ENYxYSPdgCeL76rvCWZZS54TQdBEdmUjVTRSLQAoIxh3bzlylWpbwcoX7cF -vXWH7H0OiEYEEBECAAYFAkY+A8sACgkQAqWmBQt+bPrESACfa1xOCw7mLohF9UT8 -LPrwfLiBoUcAoJ5wZPWEgX48CYqq1AgvCU/sno/AiEYEExECAAYFAkY9sPQACgkQ -4eHysJkO1KoEBACfWIcYHg2ATN2RHfro75oc3UUjGU8An108ccnwGPCSlBy/hMD/ -/5FNUMpCiEYEEBECAAYFAkY+FSQACgkQVCINLMh0FVwjQgCff9ekxXn5ThZg1Jh8 -6BI6ijHxqTMAnjNNj/bANMs8/qMqNIMaXt+U+4zViEYEEBECAAYFAkY+FTcACgkQ -Pipvwl8piCQrNwCfUmbCJLjfK96uCHgFoCyRwxj/F2wAoLwy5kBVlUE5lRZeIHt0 -WkMi3TYuiHEEEBECADEFAkZIxWEqHEhlbm5pbmcgU2NobWllZGVoYXVzZW4gPGhw -c0BpbnRlcm1ldGEuZGU+AAoJEDKGTkGchSIrm6oAn2N1GZofPwqJQR/Q3UeE90Lt -/Vf0AJ0QjqyO+yEKrIGxCnwBgXSy+6AjJYhGBBARAgAGBQJGOPRmAAoJEHPdjBYB -UwI1Km0AoIa21wJevepbT/5TPll7QJECGD7kAKCdCWkWAzDVYslcO5Ph4dzwScxD -T4hGBBARAgAGBQJGQPXcAAoJEA9FCiZiEL/A1PwAn3LhRkQs08VQQlFARFK34dt+ -R6l1AJ9rYqkIQ8HyRW4hNkoqBGrEBhf+SYhGBBARAgAGBQJGRhEFAAoJEKIRWuFf -a4tymwAAoNT4GmHKozQ6hH9VS+4LSLwYJTeIAKDgpVB3iBZ3YfLsP3dSUFXS59A1 -zohGBBARAgAGBQJEow8CAAoJEMuuvjmkbEyhuz4AoJP5fyaw7b51/Rxj2T3ErVFi -L63EAJ4zUAt6oDiAYcGM8aIPpdTbHj4gZ4hGBBARAgAGBQJGTENCAAoJEB8hI8Nr -2HKg3BsAoLG2CWQCFOdb7dp+CEm3F1srkOUxAJ4wxo52iD70bLDz1Ic+zxWYNwwL -oYhGBBARAgAGBQJGUm0/AAoJEDLB1u8PFDvByzoAoLey7JpjuwxQEbJcsf30OR4+ -DUCQAJ96lZ1+sFa5/uS86DqtEzYZXfxqY4hoBBMRAgAgBQkJZgGABQsHCgMEAxUD -AgMWAgECF4AFAkQQQhkCGQEAEgdlR1BHAAEBCRD1wmAWTO7XX5UOAJsHKnihLRiV -svMt6Iwss6k9ZkqAmwCeMz7aSaQp088fLrL6c/5cdEsM/haIRgQQEQIABgUCRl7U -3wAKCRCahtfM0arqYE0OAKCcCVPPi6ffL/SlJaVRYL6k3xhinACglATLwd4moxdf -ZMJABjncPlX4P9qIRgQQEQIABgUCRqVKAQAKCRA5vlGhCEyRE0svAJ9pJVwmNOqp -ltECGy6d65RrZGnSeQCeNQ/r+SK4BWuC+a9LunFXLXg4KZuIRgQQEQIABgUCRq3L -OwAKCRAzzWczr17EUo37AKDDROCi7WMPHymORd8X1I87WSRlrwCeJtcghuuOz9rZ -hQe5ByqdzSuCRy+IYgQTEQIAGgULBwoDBAMVAwIDFgIBAheAAhkBBQJHYW1qABIH -ZUdQRwABAQkQ9cJgFkzu11+WUACeIhfw6jEXCkbuMfGSdCsodaPnWYkAoJw+G8jG -If3bd0jQg/QW/AqrlVjPiEYEEhECAAYFAkf9LD4ACgkQi5YpQ/wkPzw7tQCfdDjJ -ZTmP0ZAzsMmTHSQEHiiu0tQAniAq3s1bshQPtH3TPfJGIuxkrmgaiGsEExECACsF -Akf9JskkGmh0dHBzOi8vd3d3LmNhY2VydC5vcmcvY3BzLnBocCNwNS4yAAoJEH9Y -T55N2dHEV3EAninabeLlvGJ3Wt98u4g8kaKBcnGyAKC2wa4tnUZmkIXtpNoOZuoo -1nac+4hGBBARAgAGBQJH/UV2AAoJEJA4TZo1x+lCZ2gAoK8UmpEcOcsdzAJdabmC -ZB4IqOAyAKDXFVEr6z/OE7H/WDExzjhdLWzatYhGBBARAgAGBQJH/cTeAAoJEBg4 -H9dLG+aY4d4AoMts+aAWK7LfgBsTvqqqPogrAv2sAJ0fSkPBoE1EFWiHrH16eSVa -wqnfXYhGBBARAgAGBQJH/k7HAAoJEP1viMYh0KcbFO8AoKLGi3vvTxj7BwDrAxiw -AcCLIqQtAKCjuo95uLA2prqo3ka5tGp4ffQgTohGBBMRAgAGBQJH/guEAAoJEIEv -IIXC1Qv79jgAoITINhmKDZneFsQl6VlZTHpNEAjZAJ0dwAKhbQARulL+l94nzkgW -23uAJoicBBABAgAGBQJH/k1hAAoJEDGmPZbsFAuBNcUD/36NVaC/kXiu24JZKq7n -ZWEk7qLa212rRIRxJwAZJKta0ov68dyO1CPgm9e9zgValGLcN52JPCA4kcA6dMar -MPqk9wWB6Pb6UfAM940Sk92AU/W29lRwaWhyMh1fC1twHELqW6VpNy5mNnhR4dXv -tvaNMkMjq32sQCCFidLAtTgHiEYEEBECAAYFAkUPgjEACgkQsr68QBUpJK+5zACg -oAz0aq1OrUoq/dnzhr7Z3XUanvAAoJrqRNBuE+n38oXZTi1oJ+k6qDbsiEYEEBEC -AAYFAkY44nIACgkQFUWz/uIi3k+VgwCfV+TKT3qn1PBzfALIPO3DMNpeMFkAnjsn -B4L1Tgl/LCRcYEH/fGkDW6JRiEYEEBECAAYFAkY451wACgkQY9CtrpESA+SZ5wCZ -AdCisYSpjSXFMlrhHDUeW7/BhCgAnjehPdZrqLC3DvP5gDpqdBPT3pS0iEYEEBEC -AAYFAkf/TFUACgkQPJpCBAwIhbSGwQCePTdVbRJtPyhsAAEKYzSu2pUOKEAAnRKO -vEhP5ZOWQLM85ZfRNVdlmNmGiEYEEBECAAYFAkgFPukACgkQjqOwaEx2V/ERfACe -MUKrZm8MAyt21NIdwCjDMigcXFwAoLp14Kws4vz+LprDCcJtjBv9O3gZiEYEEBEC -AAYFAkgPSo8ACgkQGGHDIsVgFLLczACeLNnpzZRTHXiIV2V0bM2nFI5ZELIAoNG7 -VqZlLd8CQZ46kRabdF/Wo1lMiEYEEBEIAAYFAkoEAQwACgkQwOq+CPYjp6vPtQCc -DCOVFKt7nwos4X8xQ7mIKtISPxIAnRZ1O2ohl/Yf8vjkaQBDOCYGQROwiEYEExEC -AAYFAkgJ8B4ACgkQ3oDmVhn5KRhdZgCgjmpf2g5P/76QN0uQ6AoCRB+g3sEAn1rb -byYCJYZTVm7UBTDmx8lvYFxSiEkEEBECAAkFAkicZZICBwAACgkQpHjEe8toN4bP -igCgw07F8KB86KuNxDSUeNi7ofke50UAnRGaC7wlGB+J084g5xpebaCu4h4piF4E -ExECAB4CGyMGCwkIBwMCAxUCAwMWAgECHgECF4AFAkaCzIUACgkQ9cJgFkzu11+k -QgCfb/FwMf0C2WOU/feUvPG8x1mqDJkAn2e/lNVAcx0c+iyuo59vBJ2zAbtQiG8E -ExECACcCF4ACGQEFCwkIBwMFFQoJCAsFFgIDAQACHgEFAksVNmcFCQrceCYAEgdl -R1BHAAEBCRD1wmAWTO7XX4LkAJ4/1h41iGzV1TC9yA2fKqgarsIOJQCfWNllqdJJ -VcS2DKwoxnrO19Cq/j2IcgQQEQIAMgUCSAtk1yscQmVybmQgRm9uZGVybWFubiAo -QVNGKSA8YmVybmRmQGFwYWNoZS5vcmc+AAoJELOX3RpTbavtE7IAn30QKKf3CDm/ -zE+wuKMPv9GywgyOAJ0Xc07ZuVYHWy+zUmyalUUTgMjFYoiiBBMBAgAMBQJEo6lg -BYMFI/TJAAoJEJrNPMCpn3XdHO0D/jpiVLkyBXm9pyAaVk+pwEswGiGSheHuJWlk -BZDOrMFjM1JKJVb///////////////////////////////////////////////// -//////////////////////////////////////////////////////////////// -////////iMoEEBECAIoFAkgDeRkfHEppbSBKYWdpZWxza2kgPGppbUBhcGFjaGUu -b3JnPiAcSmltIEphZ2llbHNraSA8amltQGphZ3VORVQuY29tPh8cSmltIEphZ2ll -bHNraSA8amltQGppbWphZy5jb20+IhxKaW0gSmFnaWVsc2tpIDxqaW1qQGNvdmFs -ZW50Lm5ldD4ACgkQizpgHwjJdeUxJACfa18wFcsXHhn+iqVupgy4TL5xuHsAn3bi -2H5OV7TTP0LqaEkZ53Bv/4/KiQEcBBABAgAGBQJICJ7zAAoJEBllhVDDEQYR4rsI -ANYOyVHLcQ+e/DVhYu7cDwM7sCFQxuXD45QgljCOA1B5VBCHD8D6J5LmjD+jYLTC -mwypEH4OPzCtYzlepdq2tr3aMloLRpCbbmkv6g7Ap3bc9ocmjic4TKDJSHogZ5GL -7KvMKNvGfB5STxkau0V/RY72dZFTymKWhy+7ovee7sRwQ9FZty4vdlMwy7IwE45C -HACblt4Sr4yhkHJQzI9qSLDXJ/z1Aclz+B+r+eFLijUNzGzDi4GfrFEsZNJmvP8Q -y870RY/IW1/6ESvhEiBhRAsSkOUg/MCetXc4rXmCYl6z4raHmFc7KCJiR0Jpuik/ -iPIvlI/xuvP7EPIaNRU7eaGJAhwEEAECAAYFAkhEBG8ACgkQGT8YCrVdmXdOLhAA -tnh567oUERY1k0xSh/eZu1ZnTCelRxZRBQox8x+4yqUYCVhkme+qclxNxEgSArCT -9w1cZgSvs7nxG4xzyK+O0kyrRfpYipHtDar9M4zbYiRs69pe2dS4ZaMvzozH9XrB -2tSwlrO7AHSyLurCPeHLhrU/EQ43B/ICm78ZIOrpMi4MFQjJhDjA52NVpG5ksusY -GAl14zWg4iX/srpEpwP41JTTI9MhSSS/81+UBihr6cprvP51BjysYCrwQjRjpo1B -EYiUa4O3Bcjeuye3YcJ3wv2lC7Xl8g/8y7BBo4npOrstVLNRXakWIuMCpi+tndYm -qrVKBqWBjkuKkzrw8dUYfs7xf2Pg4NfQNg8IjYgtocAHp9gv8Gjv6Bwspd8I96Lz -06hxLuPgzJ3vWRYr5HeolLOdbibkGxc+G7MBXSDyc0l3jmeoIYWjZpH4/ofLI1Gs -XwNr7Tyx+vVo3uwSarxo8s0Jny+WsBcGIstfnRqlf7hwhXxOINKid1aNpOy75QbD -bZ1PT8QTxzL2ydSxVlO/FduB9I9eWEp8/u65axQyjb2WcsmNW5B/PkPp9Qa6tg5T -TtUH2h1FGMPsD4ac8R46EyXwBFz7/5i4kb7vV3Egf0sa9COrGE3Q07cUdguh0Ku3 -GF3mrffy8/NUzMxG2IrYmK1vSBARk9slREmc0fvOsGS0HE5pY2sgQnVyY2ggPG5p -Y2tAYXBhY2hlLm9yZz6IXgQTEQIAHgIbIwYLCQgHAwIDFQIDAxYCAQIeAQIXgAUC -RoLMhQAKCRD1wmAWTO7XX6RCAJ9v8XAx/QLZY5T995S88bzHWaoMmQCfZ7+U1UBz -HRz6LK6jn28EnbMBu1CITAQQEQIADAUCRBA7ZgWDBbdiwwAKCRBmqPqK9EMfJjr6 -AJ9FwtGlQgcpWEduud3+AZG2sbtutwCeLvVMa/2tK4aFNaPF4NQWhxQQLrOIcwQQ -EQIAMwUCRBBGKQWDAeEzgCYaaHR0cDovL3d3dy5jYWNlcnQub3JnL2luZGV4LnBo -cD9pZD0xMAAKCRDSuw0BZdD9WLC4AKCHTJJJ8aK6ozLNbGzaF2jumWx9zwCbBTaW -tC+3EHcOAQCQDxJvyWyNOtCIRgQTEQIABgUCREvNDQAKCRBghaOGQ6aJauc/AKCk -Tym6ExTuynqqgyjUGf64SvSCRgCgiM9BjXX1llh/GplOrLsX9pR7F7mIRgQQEQIA -BgUCRKP0UwAKCRA39o/1AVr8iho4AKDZ1rVmNXD2KAHHJZshHvwGpRz3VwCg5Z7h -pclWyw3OkKaz/G4T08lIhxaIRgQQEQIABgUCRKP0VAAKCRA39o/1AVr8iv7vAKDm -8vafCQje4clfIK8zMM9p49iXZgCgs0yNw4/TKBiLOivD9EYbg/2AdRaIRgQQEQIA -BgUCRKfNMgAKCRDVM051sTE94gSBAKCuLDG2Y+1QIc3laYplWyMHXyhsjACgju2+ -lpq9xGv1M+b5PYdAhDFm0vyIRgQQEQIABgUCRKkt2wAKCRAyyeTONkLLS6iUAJ97 -ELvsa6Wlmg5UCsa4AAephiEDFwCgn0YHqUwx2bVWL1elR53bTWaqEqKIRgQQEQIA -BgUCRKkt3AAKCRAyyeTONkLLS8u0AKCVHlUT9Z1DNo0a4e4Kd0dF1w9D/QCfdD4p -fO7Q7Mj85WYli/d8Hj8fHeSIRgQQEQIABgUCRKquQwAKCRA1i6ozUPlhFmyZAJ0a -jTr1w6VG+Rp8j9MwbziOKQIVrgCeID7Mg0N3mDFE414J21I6As5ad4uIRgQQEQIA -BgUCRKquRwAKCRA1i6ozUPlhFuGVAJ9tFzH7Ps/aLNuIZDKyYEu86ZHDNQCePZ/6 -g83Q7/umflsLEDmjwJWGVc6IRgQQEQIABgUCRKrPUQAKCRD7N9pAMy5jzVa+AJ44 -NFxehfXUyS5Fwkx5g58Qznv1zACfarUp2KPdpN0vu5ppqNsFs3F1IfOIRgQQEQIA -BgUCRKrPVQAKCRD7N9pAMy5jzVG3AJ9ijwFqX09n3y1DRB5oTYaKrnbpEQCfW6Pe -rlHB+pr/LOsVFXBBjazXFWyIRgQQEQIABgUCRQ+CMQAKCRCyvrxAFSkkr7nMAKCg -DPRqrU6tSir92fOGvtnddRqe8ACgmupE0G4T6ffyhdlOLWgn6TqoNuyITAQQEQIA -DAUCRKMCVQWDBSSb1AAKCRCUUEP1NcEA8PHWAKDTxu78kl7H4II+e7zf+J3elYsh -9QCfV2hd9pGysjeTnQvGd9d+sHdWlSiITAQQEQIADAUCRKON0QWDBSQQWAAKCRAt -IatlZUYbeaNPAKCBhlOXXBp70dXL1rK0EQKXbBAW3gCeLI2XEHubbA+0QsuW5Txc -imxGOuuITAQQEQIADAUCRKRJ+AWDBSNUMQAKCRArfoLnQ+8hH+HCAJ99jqLaljMH -/0r+xQwPStGcdFi10wCfcGFifDf1/kNoeRGhrqLV2gxIVgGITAQREQIADAUCRKMb -GAWDBSSDEQAKCRBWDQhh7n3HThrjAJ9TRkel0blwKVBdskNlFU9UfkwkSgCfanH+ -p7oU6n/ZSYI5IGiC47crml2ITAQREQIADAUCRKMbGAWDBSSDEQAKCRBWDQhh7n3H -TviwAJwKn/we6Khznqlq3svyYn6Z/6FZsQCg3acpog5M5TXkneKEoml3q9TjmC6I -TAQREQIADAUCRKMbKAWDBSSDAQAKCRDKcp1iYD1PVH7JAJ9M7kVdEF8mLbkjpe9Y -wHiytkn/HACfa9YGteCB615GB2umE8N5FrIFuSyITAQREQIADAUCRKMbKAWDBSSD -AQAKCRDKcp1iYD1PVN3rAJ9N1tyJKWm1F9vL8ZL5XNGNepUToQCgs5VQVYaWpUD/ -yMYfZJGVo9iMb1+ITAQTEQIADAUCRKOpaQWDBSP0wAAKCRDdumS6LDEtLxzJAKD7 -xSTQm2ISTPu81XyR0FKCzW6KEwCfQqQmq1WwHfpPbCiQH1rm2Nx9/bCITAQTEQIA -DAUCRKOpdwWDBSP0sgAKCRBQjq7FMC2laGkcAJ9RpqozM8POhvOxFelODFK23OIE -sQCgm4nREEmun8CuTh4wwnSOigN+oVSITAQTEQIADAUCRKYBJgWDBSGdAwAKCRBM -BCgYMRo95cNiAKC7fFzLCq2StE07S6rzg6qlF2tS8gCcCvoT7YvhqabHSuph+hbr -F2KmabWITAQTEQIADAUCRKYBJgWDBSGdAwAKCRBMBCgYMRo95dDjAKCe1C9PugyI -om1OSp1h8NexosdYKQCfdrvNdRnQQAOwUKynG2FNT+uvnNeIYAQTEQIAIAUJCWYB -gAULBwoDBAMVAwIDFgIBAheABQJEEEIZAhkBAAoJEPXCYBZM7tdflQ4AmwcqeKEt -GJWy8y3ojCyzqT1mSoCbAJ4zPtpJpCnTzx8usvpz/lx0Swz+FoicBBABAgAGBQJE -qS3qAAoJEDfj9F/uZeMhazkD/3FXjnoWLL5B6VsYnv2wcg+XkqfxUQoy5a9H52Sd -KFGDzxd2sayEwWtf63Z6cPGva6kvdHwID55UML/TJGPxItu+fqd8Q4mpLx5gqSCB -0O1ZTmdtvgFm8EoBeV10A6xlIUP+HqrDpGXdmINMc4kqOr1OKn9j24cyl3GQoE1L -VuoniJwEEAECAAYFAkSpLeoACgkQN+P0X+5l4yHqQgQApwmwLY1GIuEUdhjFdSNL -itGjmhScR2WtVcc9B8ycqiHwdp1slM2JpiI8ywPZQvGiSlrZjpydYUm2ZuMrfm0f -3HVqDdGU/PBouKdomQvH18RSlj/IGGh+Vawo+RZdAYwT1Uz1uE/Ufr/p0hwiJw9/ -m22NxkzXhT/a5ffYHnlWy5uIogQTAQIADAUCRKOpYAWDBSP0yQAKCRCazTzAqZ91 -3XTiA/4ghbGL8OrQXctihIJr+7TZL4WnBVeWNvkkQQn/6nlKj+ESN2jwSw1mKLBT -jJldAbvRYfrmmgjys55Qu5UajovVO7nM2AZgPIFQi1M84m0zuaKZ08oIZchXjSfL -tFU18FsubAqvyEP0ZzIkQq4Ei6NDC1VxIDUFECRZxl2L1R69qIhGBBARAgAGBQJG -OOJsAAoJEBVFs/7iIt5PRMQAnj3Q4CSSCGxZhzpSrLoyVkwv6qwOAJ9Lh6KwkVQM -/PpCkGYCMeTamE7GWIhGBBARAgAGBQJGOOJyAAoJEBVFs/7iIt5PlYMAn1fkyk96 -p9Twc3wCyDztwzDaXjBZAJ47JweC9U4JfywkXGBB/3xpA1uiUYhGBBARAgAGBQJG -OOdXAAoJEGPQra6REgPkVLUAnj7TSoPI26zd7nmI0ra2sIdxuZQyAJwJ0P7/TGv6 -r+cK/VzA6stSdB5kn4hGBBARAgAGBQJGOOdcAAoJEGPQra6REgPkmecAmQHQorGE -qY0lxTJa4Rw1Hlu/wYQoAJ43oT3Wa6iwtw7z+YA6anQT096UtIhGBBARAgAGBQJG -PIt2AAoJEJhw7/PxL2ByFlMAn0ObZB//ygm5IRIrBEedKao+1fHLAJ0SE2jSlD2d -QrM9ZOTjhk69d1zLu4hGBBMRAgAGBQJGPZ/gAAoJEC65RoKIgXQCbh8An2T3UfcJ -aOBD2PxeO1jB02rsZO7YAKCfxHO8P9bgiQ1PiTYkJG7mv3Ve1IhGBBARAgAGBQJG -PfRxAAoJEKBy1NBDWMWEj3YAni++q7wlmWUueE0HQRHZlI1U0Ui0AKCMYd285cpV -qW8HKF+3Bb11h+x9DohGBBARAgAGBQJGPfRzAAoJEKBy1NBDWMWE+ggAoIQn9ssN -M+ielErvMV86t7NzFjF6AJ40Qvweaacehp2LDVPRqwI45CC6rIhGBBARAgAGBQJG -PgPLAAoJEAKlpgULfmz6CbAAoJj7TA2PSbwAV6mIxDJ5S2szAU6IAJ9ZvPJF4Xbo -RyamzXJuBmqvAzNUrIhGBBARAgAGBQJGPgPLAAoJEAKlpgULfmz6xEgAn2tcTgsO -5i6IRfVE/Cz68Hy4gaFHAKCecGT1hIF+PAmKqtQILwlP7J6PwIhGBBMRAgAGBQJG -PbD0AAoJEOHh8rCZDtSqBAQAn1iHGB4NgEzdkR366O+aHN1FIxlPAJ9dPHHJ8Bjw -kpQcv4TA//+RTVDKQohGBBMRAgAGBQJGPbD7AAoJEOHh8rCZDtSqE/EAn2eZe8Bm -9tEOD3TVq9uUFI6jWPekAJ9WBbUrwzBgcwPLkqwBkbB+5F2J74hFBBARAgAGBQJG -PhUtAAoJEFQiDSzIdBVc264AmOfhnlKk+Ln1yGp5KH/2jao0/E8AoKdc2kxlZ3AS -b3ev8mkt07CTmbxhiHEEEBECADEFAkZIxWEqHEhlbm5pbmcgU2NobWllZGVoYXVz -ZW4gPGhwc0BpbnRlcm1ldGEuZGU+AAoJEDKGTkGchSIrm6oAn2N1GZofPwqJQR/Q -3UeE90Lt/Vf0AJ0QjqyO+yEKrIGxCnwBgXSy+6AjJYhGBBARAgAGBQJGQPXcAAoJ -EA9FCiZiEL/AQakAnAnGA4d9aoF9ULf/XXv+DL6D1x88AJ44p8T/4+a7KdXmRHSF -oKlO+flPO4hGBBARAgAGBQJGQPXcAAoJEA9FCiZiEL/A1PwAn3LhRkQs08VQQlFA -RFK34dt+R6l1AJ9rYqkIQ8HyRW4hNkoqBGrEBhf+SYhGBBARAgAGBQJGRhEMAAoJ -EKIRWuFfa4ty1j0AoN4A23s1qAmCu6prVzPxgwTQEwDWAJ0Yu+TVfAK4yd7+Bt5O -iLl2CefS+ohGBBMRAgAGBQJGPZ/gAAoJEC65RoKIgXQCzMkAoJyrU1OOVv+f6JxE -ML5npac4w95EAKC26L2+z2C9e9fdZTZIal0MD34ceIhGBBARAgAGBQJEow8FAAoJ -EMuuvjmkbEyhJBYAoMrzBmjYbeIUnFGs4fWrefAS8IMcAJ9oDOjlH7YiCY8JVq1z -6jPcw4nDCIhGBBARAgAGBQJGTENCAAoJEB8hI8Nr2HKgpGMAnjSWEkAVSXLFQ+dR -D6iptacCBEN9AKCvoFa15NhmreLXEXFVVF297ZcL2IhGBBARAgAGBQJGTENCAAoJ -EB8hI8Nr2HKg3BsAoLG2CWQCFOdb7dp+CEm3F1srkOUxAJ4wxo52iD70bLDz1Ic+ -zxWYNwwLoYhGBBARAgAGBQJGUm0/AAoJEDLB1u8PFDvBVdgAnApoExYfK52LGHDP -BVFnVICqOxsVAKCiOZg2IETKtbaNJMq8s6VIxuU41YhkBBMRAgAkBQJEDXF+Ahsj -BQkJZgGABgsJCAcDAgMVAgMDFgIBAh4BAheAAAoJEPXCYBZM7tdfe9YAniX3VLEq -LKdM+LUFpmTEAcx0TYt1AKCAKSb/vNAIQB9V53ir6lh0GepeXIhGBBARAgAGBQJG -XtTfAAoJEJqG18zRqupgB9gAn2pvBZD96AHWbRO1LglVVoImpYDTAJ9/PnueQo3f -ANGfjL6Ky3YhPc90vYhGBBARAgAGBQJGXtTfAAoJEJqG18zRqupgTQ4AoJwJU8+L -p98v9KUlpVFgvqTfGGKcAKCUBMvB3iajF19kwkAGOdw+Vfg/2ohGBBARAgAGBQJG -pUoDAAoJEDm+UaEITJETPccAn1toaclGPSaJ4Lyxiarj66eh/simAKC7kxmfF9pi -2YPPHUF9h7AFYE6lH4hGBBARAgAGBQJGrcs/AAoJEDPNZzOvXsRSXF0AoM3+o0ta -CMlQsPVNrWR3Q1oCdQNZAKCSDcyBFTomrWQjr3qU8Njz5cBr3YheBBMRAgAeAhsj -BgsJCAcDAgMVAgMDFgIBAh4BAheABQJHYW1tAAoJEPXCYBZM7tdf84MAoIf/NewT -tz5S1FV/I4PLOE9Uu95RAJ9iJFOqoGqFnClrlj0BnOOtEyK0AYhGBBIRAgAGBQJH -/SxCAAoJEIuWKUP8JD88O7YAn0RrApjTMPoApGlA2K8asendTgDVAJ0exP17HNvi -RetossL2IoT3RFDp9ohrBBMRAgArBQJH/SbLJBpodHRwczovL3d3dy5jYWNlcnQu -b3JnL2Nwcy5waHAjcDUuMgAKCRB/WE+eTdnRxFivAJsHddxj4My03ph50YCpYou1 -rV5CgQCbBI1k1KOhStMeAatumKxHl6uBGvaIRgQQEQIABgUCR/1FdgAKCRCQOE2a -NcfpQmdoAKCvFJqRHDnLHcwCXWm5gmQeCKjgMgCg1xVRK+s/zhOx/1gxMc44XS1s -2rWIRgQQEQIABgUCR/1FdgAKCRCQOE2aNcfpQvxRAJ450WRlG9019v/H7Z8NUDA2 -iPWuGgCeO8drcUcRvka4Nf+rBx54f0vPxROIRgQQEQIABgUCR/29+wAKCRBz3YwW -AVMCNQonAKCD5WyYnjhCbYoiH1kECtaZ+SwDWwCeJceq6Cx/ezn3guilX54oPv6q -zGOIRgQQEQIABgUCR/3E4wAKCRAYOB/XSxvmmBSiAKCt+n9yBVnsWcYz1/pxDgNB -sqMTSwCdEWY2/bqHvX4pnNmz5NJgjsaywqeIRgQQEQIABgUCR/5OxwAKCRD9b4jG -IdCnG3KAAKCnX6lv3Lp2seZjIpTfNBvm7ot69QCg6gdaH92+hllrNo1I4aYoEnAu -qcOIRgQTEQIABgUCR/4LhwAKCRCBLyCFwtUL+9hlAJ4sUdJVdkc5Bo52Qvl61mMj -RQ2LgwCaArN7TVN/mpHlK1B+sZ07WOAWMvGInAQQAQIABgUCR/5NYQAKCRAxpj2W -7BQLgWl6A/9Ir/CmmvJ5OIgsALH2hdoLieerdOvd0IUv6Ymu6Hd2UFJQRxcvuKlp -dbxuW9Rd82LIHxhQ/2qwdMrENF21vwDqp0tB6pyeqU9E1DM0/ON07BGYYmFvOqK5 -LaN4chgt0QmnTWit49WdivDd+ry3K2efE3VWD+YoDlS1EKUWbc0EUohGBBARAgAG -BQJH/0xVAAoJEDyaQgQMCIW0I7oAn24xvOl5noE/TQby/Kr5XxDf2GWBAJ49Ti4Q -o3iB+2j5JCeaMYYa0CHC9YhGBBARAgAGBQJIBT7pAAoJEI6jsGhMdlfxEXwAnjFC -q2ZvDAMrdtTSHcAowzIoHFxcAKC6deCsLOL8/i6awwnCbYwb/Tt4GYhGBBARAgAG -BQJIBT7pAAoJEI6jsGhMdlfxk5AAn0lc4Rfm9HIFB0iWqRzehNsNcrDSAJ9Teb/0 -V5Zn15NtvtEPb2Oy353ZvYhGBBARAgAGBQJID0rtAAoJEBhhwyLFYBSyASIAn2uq -5Nb+RDXubzlSM/RT2zKyrg6EAJ9OyRlc/Fzax3pOyX1CFKFLoTnhpohGBBARCAAG -BQJKBAEMAAoJEMDqvgj2I6erNW4An2cy0Lld/cf75SPfDLO92LFZt2wKAJwIR6xX -JUBgvWBbGBQZKGhXh7It/ohGBBMRAgAGBQJICfAfAAoJEN6A5lYZ+SkYw4QAn3Y2 -5DbJ/qb/xnXQHgdWtVXpez89AKCoAO3juvgHNvk7TjQjsDH2dMXS1ohMBBARAgAM -BQJEowJVBYMFJJvUAAoJEJRQQ/U1wQDwd3UAnixUvJNpSTuE2bEIw7QqYAggAlDk -AJ0TKLrI0Q6y5CuZnx++2XwJin4T84hMBBARAgAMBQJEo43RBYMFJBBYAAoJEC0h -q2VlRht5UHAAnRgIYNwCFFJ0PuIduo403hkmwR6oAJwK6zkxyTXat1Q24fcg1ZOb -kyZfR4hMBBMRAgAMBQJEo6lpBYMFI/TAAAoJEN26ZLosMS0vwpoAn3Wa+econWw/ -+1bxXlkf2mZVcvLRAKCJmdPuz2ux0AA7vBj+Cpy1P2sOsYhMBBMRAgAMBQJEo6l3 -BYMFI/SyAAoJEFCOrsUwLaVogsMAmwfQ6XNobfWkPpyIQl3PPKfxHqQNAKCpjRan -gLOpVFV5kNpxEqPXcnd8xIhnBBMRAgAnAhsjAh4BAheABQsJCAcDBRUKCQgLBRYC -AwEABQJLFTZqBQkK3HgmAAoJEPXCYBZM7tdfuJoAnRtou2khXTC6XAJ28xvsR4Ji -1h/QAJ48KdVtZKn2j4gUN9Anm+EckLctvohyBBARAgAyBQJIC2TXKxxCZXJuZCBG -b25kZXJtYW5uIChBU0YpIDxiZXJuZGZAYXBhY2hlLm9yZz4ACgkQs5fdGlNtq+0T -sgCffRAop/cIOb/MT7C4ow+/0bLCDI4AnRdzTtm5VgdbL7NSbJqVRROAyMViiKIE -EwECAAwFAkSjqWAFgwUj9MkACgkQms08wKmfdd0c7QP+OmJUuTIFeb2nIBpWT6nA -SzAaIZKF4e4laWQFkM6swWMzUkolVvkBD9U3DE0Ka9rKtbGNARRcJHt4JPcKnzde -Hlhtt0TD1IeSAvvAS0awrnNhu+1ta3vr3U/uF/Se47AI4czShhO1G/C0Q++HDJ+H -+xJoysIHjR0dwRHcCHylAGaIygQQEQIAigUCSAN5GR8cSmltIEphZ2llbHNraSA8 -amltQGFwYWNoZS5vcmc+IBxKaW0gSmFnaWVsc2tpIDxqaW1AamFndU5FVC5jb20+ -HxxKaW0gSmFnaWVsc2tpIDxqaW1AamltamFnLmNvbT4iHEppbSBKYWdpZWxza2kg -PGppbWpAY292YWxlbnQubmV0PgAKCRCLOmAfCMl15TEkAJ9rXzAVyxceGf6KpW6m -DLhMvnG4ewCfduLYfk5XtNM/QupoSRnncG//j8qJARwEEAECAAYFAkgInvMACgkQ -GWWFUMMRBhHAhggAu4x4MuU3QKtLUUhaIYMl58gIfvODPYLZRlOXvm6mIgI9zEYW -mwJ9wugIzSNlufKOahoqwOoTCFL5sdR7ExzZamNZFAwR80hQYKibGIadp0jFhne0 -MgMVMxm69bnVt6mmJjHroHVuPyjNEJvKHqxD0dvzdBjT7jqzCEsaduK0RV7fRy9M -9d6uFRoCOrjLWhdNvCH3+D3GSVJPP88M2ghOd5L/DBij77rFF6ZeXe89D8vfyq0W -lQZYh5/gkMIE3ZL1FfxYmCCgOeYSa3I1Qa6grwM4S+JBymd9+3JtzpLoAgNBxM+P -BG71Ss12xVxATwPw9SueYyFkEeSVnFAWAW2oeYkCHAQQAQIABgUCSEQEbwAKCRAZ -PxgKtV2ZdyvuEADIaZ/6lr5QL+aYDA+hqojD6fm7jQqobeAGq9e5n41EbcggEcYf -VSaHh6KUJ/nWwM61FSiA3q4Juo/JWLAU6KF4rsSfB6fHTar5N8h0kSJGGENEIqM1 -rNHwaVwqenhI9OUbJxBaKUXb/m+zIY3O4cgTtEy85uUxgDcZe+ATNT7AQOhJkWgm -GnEafJ/VCYCIsuV+aHbFqtGd1IN7NYFKKpcyVNloeXjz7n2hKe8T6Bp4RhSbGjLA -fDySukHNQDEaf4cgQr9XKaCIti15AFs+3p7beQMusMXgjKiBWaFgC6ptLsGqDgo7 -36NIyPzSsb/C/XZbebuFsyKyzxWEArlo0wzc8BZsjAfbbXvcOHqcJKi3qwFK2q/T -m9N0Fv08h0fTh/kLIuZcCY5vr57SKZxzndZSCxsm6GJMYEaX0IfzgbA1JllDWgMV -GTmAahO+pCnScYFswiftRdW5BY3+aH2+61HgLZmQwhpbnYvU4bWy/Y5xjUQoLZ9N -2QBgYH/z4FPg/jlLYQHlMTollG9EbteNLjACCuYXnKXHUsgFSJKSo09KK17wqlDp -BljARzdsF3XEfgMPfOsLQzG8gkK3OuY0NCw3uK57oiwInJL9DYJomQR71Bua+Opl -BqLn3HG4NyaLuosUeLw4x54ixFDkLD25GcUGsdseJhGh6kq+/0zf0BSesrkBDQRA -YZyuEAQAjlaXJffYOFtdSmqYmxHHSAxAnWxEtT7JQP+eYvmITOJJVLZiNCP6/smn -WBvmUduWVkyND0Yg4/L8tcQF7ZHtOg+Xz9tOM/9ojBs9K7C5Iiyt385hbzyO14jZ -DMa3/IJO4nsRq0aXuAIYw8g6f3yuYkG3xR8kb1RtSB4HBZxBF4MAAwUD/0GMHXYP -nrmwdoRGP+qLLypqTchAQWxc7JTMVpFLC9O6NAxtkuYiLB5EE7eMcfO9lYWEEOKH -TOqNYSTZwe3+N3v5+P1oRLT08ge9Ue2vF3FQfzs/4rSDvWhQIrgXypHRGGkd6rhc -yIf2Lh+Czc9UCdm3oQptczMGTXNRqAHa2YbkiFQEGBECAAwFAkBhnK4FCQlmAYAA -EgkQ9cJgFkzu118HZUdQRwABASqQAKCJnWqgmo4RHeb55WKcuvatypqlawCgiAop -7VhXP77oefACKJXYKwyHiCSITgQYEQIABgUCR2FtmQASB2VHUEcAAQEJEPXCYBZM -7tdfP7oAn23vRtAJ0vDIniIXqfsRPnpsO62YAKCEyvgx95NgRj2n1WMrKw2RPO2W -Mw== -=8rmt ------END PGP PUBLIC KEY BLOCK----- - - -pub 8192R/D84E41AE 2009-05-08 -uid Nick Burch -uid Nick Burch -sub 8192R/18C4CB00 2009-05-08 -sub 8192R/7092622C 2009-05-08 - ------BEGIN PGP PUBLIC KEY BLOCK----- -Version: GnuPG v1.4.9 (GNU/Linux) - -mQQNBEoELHkBIAC0A5jg65W9e4W/w2lAO/vG6OkbXwOaMRF+frCgqDPIkkVU7AeF -O30xmuPpRR3ZSfbvOvOdEm4RygyxHRHgl6WUKGF6aRk3U9gxD6xfTl3n+va2U16q -Qf3lDpB1/H3QfZST3wGTtn2yIRYcbFzqz/e3GfIEKDmPHEQDhgHNDjXBU1sBnWk7 -GugPUrYbfikHzfjfVhEXNr6WdzKFpPKt9tW1oDhspGFxg3A6cgWtJhlGutb7QBTO -gQ+KeQvhNEfEAMo74rhC/6Lj1evshoJf42AOk00IlI1c12JIQY9ZEAwjbrn/592g -CrbSlQkzmh/bMeKX5qJHHE+RiknzzpOXLIicqD2uJxN+uY1WT+js2AytoF67U4k6 -+kJJiftkKgOZDml/BlgWNLAFio7D6kjl9DppcsmbYUmNF1gH/prpvA7w3uzmluso -XzyMA9LGPTg3UBN1x85D2KUAc9O1plbBi+RgBL+v7ON9oxNHS4orwcxdR7LHDxEO -oW+a4TGgN1mCvK7hgSZ9OtKMu/VoLuXSh565b9IF8QY80rESqyThSuaC+s73wjJT -0MADvmhgWsq9q5GdVxvG3m3B56wbq2Xb0Vmn7wxUVl5ASSgiHGPyAu0PP4JVSGJJ -mv0HLnAyVBWYn2Wo1+O2ac39exwkBQXWdT7hv7pnuVvqix7lKkPqxbOF5w/HBqaG -arOUQM+I+Z9XhdK1htZ92rgz0uI9BEjg0hHm+XDlLGwHHFC23HEjKrqVd7OEbE7g -b8qGse/PIjTOeDHa4xjHD5PfBMfvOIdNxvtu1Wc+GWrtJm2BllPJwN/YxtQp5nu1 -ZV8+cHGJAZ2DYfihNzZrtzoEcSBG+nCErkqQS97B9cQHh8Iu2OkNVY3ABPjEghKt -gs5H+B4foohiD6X/6hNSCzgLJ4VTxGBojUAFsL2TqX/gVgnhcvZHXwv66QBf7Tyc -zyDgEj0soqsc5kkZq2Fn4voXDVzUmviXjZCXQYmoRTsZFhe2bnlpW9i7tMIM04TU -soM/FB5LV3Em7b2olt0j9ctaLRTEnJu3hGMPFpcmKYv4R2gBM/kT2JBDAZIhyljl -iI+VpqFT8YHnHKD8gkhXL8pRHKhbFpi8RgGKV0uRZjJllJy7F5YQQrptgOb7obhR -R56H8+avh91Qyj8Lj4pG5479m5ltRW6AeYbCX1J+GcG0ekmVVmXRzc7UOZ7oP8Xs -oa1EzEFS9pCLxWBSb9sMm4uqeAPDOK+gnyhPBOk9OIsESpTxda9Jw2sBRmy+hIRI -N1maGfHXGoEotxRmZ4wLMlBzWjOoZCfpbZgJhawNkwNvJVnwpPkdFS3KxMrBFa6u -2GSSFEl+08OEFGVvLU5wiiEck3L0s7y8BBEfABEBAAG0HE5pY2sgQnVyY2ggPG5p -Y2tAYXBhY2hlLm9yZz6JBDYEEwEIACAFAkoELa0CGwMGCwkIBwMCBBUCCAMEFgID -AQIeAQIXgAAKCRCKr4jW2E5Brq5FH/4ryVlBMELqMG+FbVWQa5S0WMRaZ7iZ4jyO -rwbmYeXwg68WaiuoN5DVt0JaA8qD07q0YDFtKcZ3UxJDJ7NHhOTQyTiXUSjFyLWH -6Qtv6whBHnJxOIxEdFArxutIQsgOw0iRvGmOR3qov8+NWhmZstwcX1ERRa9f47YQ -aV8lILrDuc5IMaOkVYGngwI+k6MQ26HbzD6H8YNJOFYUxRK0mdM2O1vbqboQNK7+ -ltoEk8EwSdfTRiWmUoSmGJAE/yoqIYG+DVOCwew8xaCiaQltcHU9nldyyJvLl/GC -pRY/hoZymti+b9oXqH9ZQZ+K8374Ehn7dHa6A6GXt9W6G+LsqyP+tvNLOa1wf4uZ -ag1YauH7riXkkIX0jAwiikvM31egFUbWHRS7dHqiMyBbTowHrdEvDD+wMo9eJJ2b -Ce2Xn4pwjXgppnzUBjj+t7zm9wvAw9FsK9lZ5M20x9qjWPx0L921Tj3DWBRnEr13 -Z3gdpv/d1ByZfPA2WGh+zKr8yxOAA3Qml+cdZltEQNMrKEoPcTOaI57WEHZw8wjV -FNQEIUQit97kAeXKYE9gQAuk3ew7saabsBCjfXi3yIRwHqoPdcI1iBub6QA5jxrl -/fEPcAJv+pV7uCTtXv7HjFoo4/mQSLxYB5tg2YsBXMGXCGHaI4E2Bj4c9Ai2A7tu -UGoIE4+WfeN7yH6SjcfH54Im1QSh4MHTrcI8D7MEUNEwpJ2fjG6+5Wa+yx88vnNY -Pq31UMB6UGGF/5W6RO47OjsdGSVgHB3POwEuPDCPORALZTXh1GspraGAfwbhHyIs -j2CkQ9sR7A23OYJSgGR4lte7Ve5SsC2a0R8kn/AHS7F1bPq3WVnY2Sw2d5XBBupw -2zWQJANi0ie61pbqa5T1ySG+tzIJmkqwEt6E4i9Mku9hZrs1KAGC8mgRrZlhVK1B -ee3JKL3acpHe/vIq0CWRZeBV0jD4rP1s7vf3CsUdYoBkycSTOaHG42yDmER6jG+v -FYAD3Mf7z+6Xp3GXmBYhEkFo7llc3kyQ/lRAqzhYwj6lbYO+SanTAOe8GLzPoxRC -snIvkzEZFAEdEa/mDnRm+jtCgBnpVi5wVmj5RqnUE2mdMuyEwaV33lgEum1EHeXg -IkyrPsqETjGh8YntN0pyesl4Q4MubTn6Av4jbSXt9Of66viw3BP4Lthxv7b1Rh58 -HkSUrxSwyRojXlVGiWqgc/cGs0YBaTpsZSIgqYQnEUpQZKQZWSGtbSeXlDqZCRiN -3Hx5eMLysc1Kl7EPt4nseZRdt/uqgvn+CuZym6VWg1MlAdoJ5Rnc4mkQhFM1v+bV -knAc40CddFCY/YZ4nSbGwoUGdTCgy/OKeLUdL5Qs9TP4vgRZYyRciEYEEBEIAAYF -AkoEMPsACgkQ9cJgFkzu11+QpwCfTnrrGd8BVgF9t08+W9aL++BoBVcAoKGNMzwr -BNipD6R9dSck/fwSrckLiEYEEBECAAYFAkoERU4ACgkQ1TNOdbExPeJyXQCfdZg0 -oS8dfOiE2WAhAGT6lwz6rg4AnjY9DDcwDgq2OQ6+v2c3BfClTb/riEYEEBECAAYF -AkqhhAoACgkQYzuFKFF44qXqNACdHXtNK+o2I8IBn5jJTyBKYGgW4REAoMH+wJBJ -/t4s1WWRY5/a64x7r/SOiEYEEBECAAYFAkr7BScACgkQEy5J1OQe3H5R4ACePe6O -kKfKNZ6Ldq0ivre+1pWfbjMAoI6XDzq6JRlOENrK4LtutGYELNv5iEYEEBECAAYF -Akr8hPcACgkQyceSTlEEfWZVYgCgkZp3OkShIFxOm3mreN2v2T2UUtAAn2CuwqHK -6jITsLhbN0ej8uuFa9UxiEYEEBEKAAYFAkrzvA8ACgkQmx/anzwGIjESHwCfdjfj -xeExb4avvsl2g+uWfUaDt2AAnAvUTw4mA5qrQG7QFukF3WuzzefoiQIcBBABCAAG -BQJK814HAAoJEIWPxMT0OFajVtgP+QFkTX5/+15HJd6EEfKf6L4+Fox11JCgc8sI -E9uizJYBUikjwM5PYQ3WYiRoAUmbY8vu+c9iRNKrCYQ3Xzd+JE5CYR3lrR3XqxdB -icdMoQsr7IfV2dAUgp+AkMmMNSlhtsRyXwSamfW+LoXjXT21N+SawNhICEiWMfEy -8poNdKuB87kFZdQjnbB7C2Rs0cEMFJVqKXtwBNPaE8vGL2+m4BTLlZrg4T0TrC4L -iPaizxAy4X/TmEuWWqXjEmdgIzULZSQJ//gnBDlJ9ldoO2ZdaALPJJGPTx7XsiSW -ptbmbl6M0NczjqgWh402a/g4A+2Uty1NkOjKdS4kH7zkkkAIV3p8166u2Tr8YGsV -4ktqXWNt6KV0pVi9d1VE6kwiy9cNGAMLfCcsyo7sGK7JNXaUzjvo7M/orZdetGuA -ipmJc3JygB2LmTcASPYp6pMMLZJIhIFGx3CZ6qp5SINzX5uEw+NSpnibXWhk+8YV -wgd10yVqAXqZBFaQr5cTKzioqqHWqJnhaDuEs594EKaUo8TC7AsJJyIl2OWOqO08 -YaTjaOc58Ahyu1UrRIrL1dGrifF0THSqxMx1TkKq792Srtq2U+OvfjSmg3rs1v62 -TXNORwXNVFqcoExK3JH+YJyc2in4b+55qsndrRl5U3NA+v9ZDE9e1+NOPbz5io5/ -bd2N4E5xiQIcBBABCgAGBQJK8zm4AAoJEDF8bfg8dwXPh1gQAJ4tALW+m9CAyzin -VhNQI9grw+N6e5QkbDTPFM6/AKcZcytUZ7wlh7qaTWUC8eQXi7Wt2oEHvOMy/Qp4 -yw8awWaIANzKS4yU8hW/iwfTsWLHU/685IpJJrP70BMDCTbbyOUuDE20/DSRqIeT -YVjq+h2zgdHivJXaJAJLUoEGR28RefSyOlzK9rGGyYL8PYkQQuJkfb63uUscwdDI -kjUeqKpwWMUEX33SC4AahNfy5BrzbAK4L8IdrVCtgSHi3s3z9aWxzYyDcIdL7wkY -/47LXbdnAWpxtIvgGTvyiWDnGDCbKDY3UlwM7yAid3jF/RiIme7FksHlK7/UtbI4 -/a8get3xETX8r6ZMBZOuRs3iczK/VZI8OLIWHw+7VfUshd4y1BJDb78QP3b9hZWY -UhGBHa0kcz1pCfvswzT02xupc28X5/Ye6CinbXwFW2wh8GKkqkdN2Ni3b/inIFDj -jSuELFX+NVV3UhTlu4XGftyVwOD7m+CeTRtjLPzMdXxt7jrtillWu2cUOpvxu9pa -zk/UgfBYZS3ZKksaOK13krRXGCpBp4vR17Z2WQycXAPEJiAF6t1Ip30l9cU3bZsm -rQhpP8+nxrqekhH30aVSdv1zLlOyPA8X+foTnRTn/A5+P+JEEpLuGLdyT9Tm1Orb -Z3TW1GbcR/qLEEKHdRw42Qk5GOXOiQIcBBABCgAGBQJK82DJAAoJEJmgMCnd+hme -RiYP/3+oOsn2JiNvF5yq2Q+5XWg/B333XY6Ab/dSUg85c21M0RDGk0r2/ZvlS/Ie -Z/ijcm0LUQv+bYgP5DjnKX2QEm1GJYEhOvRfOw1vY+mZfC+bj2WV/nTRo2wnc7Ig -5XZdr/rqLoTlEdealwQdv6fjoocJ3d0r9vDfZl4YC3ueNW1WATmTPJqLrbm6L3it -v3xeW6rARr6zUhWkYRE/3h1/Io6LbU6VIqASsIXwtNn5Cxxkf7fjfvkzPpTU5V7g -JPhC9e0+/U5qXRi9bsLGqhC2Twf9SwdtX3pRtc1CZIl1ux72YZNoEnF3bGBCr1ZA -yvJJR43SobEgIqZkx4ykOJA7LHgNuz7Q8lehhtpyocYPuTFbZSKUnuBIO64qjiYt -OMp7C2GraFuVO9z9gxLPcCQKjDiDS7f2HuAv4YGQW7GDssO4V9/NnxM8WbtMjO+N -xuVcb7YFrQPJBlCINvk1ThJgsbrXPVa8IP9NWUCn9tQj4whno+/Mqmenlw+iiX+L -LeOs2NnJ+FI+9TUQuf4/aX5uTRM2yV6wl9tj6Wny+bejJxUaZOXvs7YBN6G0UW/Q -cMFV0GXQlhfEG2LXA62mVRgXC9LcpOtJDeXrR/tzUA12VFEqnhpqx06NGzWIj+bg -K3WH3PUA1jMJZqhScMT6xJqR733G74ufXC6IjzSJkY5CJ4UhiQIcBBABCgAGBQJK -87rxAAoJECBchnPcdCx8HroQAMuKTK6tUNzN8a2TQ+LBI+pF2adOkY4kqO6cyJb4 -2VqYapTCmbaDBxw+10MW3pZxAh0WJKXrMJZMA48cKTowwsa7kDBuzDllQQO+DH5n -4OFvNnmtqvnnHBJuWEN9mWaSLf5KcpWFp5dnqqkVRYn1SFQqX1QSI7yUZUQ19Kfx -ocGiPy3EZM+xyxlTxzBjIAST7ywsrSP8/VPsYSehwOv/XL9qXeJk5fRsWezm4CF6 -Nqv+vcOjXVqsRB8KflEDuUk/1lfGcBrnClqoJXxLK04YujxgFTzPQy/CbtIIqsbM -q/qr2H8RyBuwhT3rA8guNBmZmS/DHA26wH9ieefQKX/zJclO+GGUoJSlsiKRLV2W -Ultw11MWwLMzvPm9fjk+btx7v/eUcIH9MldOo1ovIuQhtPXCpdbOUdIh/0drGf6T -86KhjRD2l6UKbiJ8WZKtBg+eDNf8CmLpENxBN9V1wf+MLHbmjg6oudq+yNbjrOYF -AIDs4lbn/2oUJjiyxMnOCh7MitRq4arSZDr1d/SzavchCMueaowh5hCUG08J3ZQz -ZYFppQ9MbD9ctnBzFeBbHobIQeSHERhwrdE1GeioM1AItodVKHphASIPBJHI1O8w -INXsh6xSYPdnDwwy1RvUiFjIcEpO5eEjjsAhuOpgnxer99b0WK5totjE48NIXWow -JZXjiQIcBBABCgAGBQJK+J4mAAoJEBDAHFovYFnnA7kP/2IyYgAF6n/RehprPXAX -dPPPG3yP4/xksAOl2IQR+6HEt9pwU9AZu2Ha8vumnXnohX6CAxbT96JhObBMCQny -O4EPFOZ/9dCGJRz6hFtac2es91r31vIPapYcN/Lkq3XC8kOQOalJwT3MG+7gnIPe -gk0H+bfG10wQ89Pm/jm6U9jNvG81ZMeRkolQx46piS+xletRVagNN6f+jaUQZeyL -hkq1F4WUgrFWBNqJkvjIgtyyU6e0/Q9FnbxFL8pz8qayP+DnABoeC5ZpjfPqRzhb -4XPWK0bRRg0KJ1JcVGlTq+TslSsdyinvbWqQjLhAAcIQztIFzvw9KTPAkUNigKV6 -ubec4gFMVwtC4SN6LuWIedy9iQvutALhbZ9VkwF5LGWc9DTPOKB23DLHR5vBaEPo -rEaQDXWZ3UwZS7LJrlPcNy5+7/PhGwz3Ws9P0efdT8Bd+z6J3VeMgpZnifV5T+ZB -CtbQ0vbFf63+rD9kDE/hE8yO5UoLfvNZF3xXf16tHsGr2IMFfDaaEEcQx8mSZkuJ -kGirf0KqfQcg/KM5bHOnx4XlgrcQEX+WK2zrIdFA/G68aFv+lBMIuEkuH6dEg4xC -RC47xNCFBL0POGGYd3504EHRmQMRloom3kapkb1YOS5pdVoOq+H5WiRb+qvq4aMt -/wiK0FYCXZsxy/OSuuqieJvviQIcBBABCgAGBQJK+J44AAoJEDGBeFpSfIEki88P -/1JuTI2vnOwNzphUVZ5kIueHy7uTJEji+FqtoK//eDy/49JWxSJZ42bgN6oFBhGF -GY/cGxRzB/iqgudJ0FQ+uJJxNp3fMnFBSsriquNy1/TNaquuTRme5e9UQ6yDF4pD -NjI0Cr5i88nD5RhWqCldpJ6cEBxzchx2FwtA0jGXNb32YXLSTYReAkOvS9ogaqsm -+FYYL7Yy+6cVn4JHRCtjY7Zw9LsMfsVKwXVAvlxvVY/aDEHUMemQC4XCHDKonemV -SyeUpdWhdL9UlltecscoYvyNKAnrgiCND1Mpl460XH3q9RKrfl0N2aLBk1+b5x1b -+BrK/u4KMklXRbi5S6pZQak4gWplQ2C532DY4xDiVzRMvobEaJxVF2rUA+KT5EHw -r6xyVxj/GAWFuMxIOLbgndLt0i0hbeVBXtf56BZvRSC4O8C+MHSNT986O+nUjCGn -OxKDGoK/c+0DIgVEuLUGsRjTdvS7Vrvi8vs5f1gAcZeuDvaLoLMnen1CHJagYMFL -7xNgJRy2Jtr1fKyA+7aRYkNidV4ozKjp40pyOuboIKUPgAnJfnXscmo3htoSI8I+ -Ygu9AfGQmROuZbT2FOQEo5BCydmUlnbfZWBUtf2c6gTqJ4pizypCk/FT76u6OdWh -zkglEXAMvyS+nBFmm8eGJKfRkhHi4b59GbmM6tM3AnX8iQIcBBABCgAGBQJK+zWG -AAoJEDWVOV6z2OG6DFsP/j4ntteVJIovS5/ZSKf9hvYkxqxJteXIfilqqe+y+lkR -AJZVtT8L8GrVJYIBPadvBBI6ok5PuwTB82blWyobOh5Qwzj1ZMNbgKtXnWVBm7oz -ZQE6Qm9gvlnwLy1qjCSsNMRa9w6qkALAQL/0g1j5Y1i4G50bqUy5Urbq2P/UhzDq -lsOP1/0GjvdPgiy1WhuMmZvpwuOXPQT/33WjiKfRtiQoU2B9nhsm4rxEuvD3hgxm -/aHwShjJMB7saXFjYOQM+8wcHFR9NV27pn9df+rdaZivm44dU/TieqFYVBw7/bLw -p2wj76xc1/QKK29r+6WYtZbVLE61JCTT6sjlxmGa3a3UWj9V+uhUANvpUrtXa708 -ZQ9xowaJ9rxeif2KeiO/F07jS5BMRIMHu4JXSKwSmwF6xpfL4DPJKD8oQGUtpK6j -UuijLZjZzGA5Csy/OC7IzFq47PeDBuXekWTiCQrwUBQRfU+KJi0+xOKVyfZECCH2 -6kIsau3Z2DJbaRbWNEHqUXrpiQiiJVRuiRitrm9ZReBvNK5ApVs8CoHGqZCJV1vW -WE5WJgoeGeTl3iq+vdpCmAYEmeFuTCGN0ByNJ4m+GzEm9SKnkVPfy6OHnX6QOUEk -K48z9+RAlQ6LF0kNL3lfDHbJoQvJ2meQUNbUvXPHsoQkQ5WGyo/EXTlo5zhbtQ4T -iQJ+BBABAgBoBQJLDN5oIBxTYW5kZXIgVGVtbWUgPHNhbmRlckB0ZW1tZS5uZXQ+ -IhxTYW5kZXIgVGVtbWUgPHNjdGVtbWVAYXBhY2hlLm9yZz4dHFNhbmRlciBUZW1t -ZSA8c2FuZGVyQG1lLmNvbT4ACgkQm7hjsPUbuIpmcg//cupmIq7H7z1n3ttnshpT -U6h1RD7vZvsRwW1ei/g06xog8h6OQXFVmMDuQqFp8cxHFlCGF1C8vklYv2a3b+fZ -AC8SPh91VpHu1pvMQx+hXRtmZM1KasxSv+uYWGOiJooKYj6upP3B8Oz1GAqFsJyO -toBKn2FcnI17faU5ATPp3ZR4KMWHDvh6Q+NlaVkhBzJz7bVe4qR1TvHBP3l+gRnp -UV4BnsginWv71kz+msMXWlEWoCd2LuI02xOaTIRWxkVMmTdsWSh7G7iYjGp141AD -fbYRN8fvntg3JW3L26OXyHQdZHx9zB2PiBrqhBsCln0lfi9lxjN8HY39PcZsLDZJ -7PH6QYxBr6wfpipzdO3kvmdDWxO2OKJRwF1PN/YhyIl3NW3o57XZbzdqY46eOoxg -J4LYkemXs7405ePfPvHYPqihyO7iyE3qmG2JeSbupHAkR5t2GjtahTuI1p3h1eXm -M9+fRP2qJwmxrVb8clhIzotSXbx+P/W7JaQDOnyPfIQvfdTIqlxk2YqOyKWt3RMG -2Cl5YR5gYM8vNAcFAb0upi51kd9aP0FkThUNEbdiAqCjA6cplV7HcmMnqpdjXusK -6ekTQ53C0Zvgx+/oJoKQNtPQSobnIqlE/5wC+iRkfeMKFZ0QQYTExnxboSsIHr66 -iPo6N99MkDsAkwRdabCO/WyJBDcEEwEIACECGwMCHgECF4AFAkoEQTQFCwkIBwMF -FQoJCAsFFgIDAQAACgkQiq+I1thOQa4Ghh//bW7IOcCGkShncJIvG+B3WM5/o/24 -h4cJtAKr+L5l/SXpf7ImMSpcI1PGxHk76KZjIaeCDtDNvUr79Lj/aC4oGzCbdGJe -weX5Q6/xJZ/EFwzp1g9g5Bu6BuL5oJeKDFIRgJPyUkvndYoONyzwucbHCmdEhfuZ -V8Ekipq+XWP2LsAtR7vlBDLFdLHjqrrHokaGySaAavIJwLp5WhHRZHs2AUwt5Qp9 -QyREdQhVzNJyfLkm/BfHqSbJbot2l5FrJ0EGwG9ZDA3+vkiAQk1O5FmGSScI+kYl -dE5amDWRptG9jWZWGgG00gfZo2dZxhmJ9Gj7oqKTN+mZfIGk4P27lwIEG4K+p5xL -L2mT36cMrx/8LD+wi7sGoNkMlF+qo1AGNIyHXaQKviy0KO11CTV4tcX+ZfOSe2yU -0b0KqFOyMd6MA8pdv1kqkPBhkZTVvLmcZapXrSAYTgZ2urQIKJ7Gyw+Tb1VjQtbY -4zJbis3AKcCs4pIcoNzU7pXBO18/ATMtIlpLWq/HXeVyibX24peUdjbJPZb0wtE5 -fPecNjM8vykztlZTDtkWn9xE0x9lJdGopY+GK0pE9aG9DDzsr/IHAajf05MgpGEv -3+usLoxQ9mdg3Ud9BDkeftyA1vYTKaPb+E7Yj9WZynBlYnTSP/DWC2SoncGQTPim -4TRJsaH3ygt/Xc5gJ16Q9Uc2reRV0veX1/7pdqQqM7eqj/+7hCmnZ17qBvYFhwN7 -XVUft2V9INMWHDw5Is3NiA3PbQpLeDZbD7HFakKwH71idb+NB+/nNTM9ERK0YRPK -In6Ac0FuCG+CVEfDGl3Tvnejlnw28XpKAEjyOC4ouXZBkZ60RAnRGYNXpW2etWnU -ErSmJ68+k6okHpi+6OMF3B/PH9864vzjOW5LcHsY+ntvITABKnhX85Dl5Nbi6lU9 -QL3bjMPU5WkNqPVNYPMpvdK7R3cyU94KvCwdzNKscE+5S0CU0kcZtmUye2jjSD0w -UbDkVt7R77E4Am+6QlNwDTgYqIYViIXLNDOZK5ISYagJ+ZlKtGbLhcI+HpcbLjsQ -Hxbi/gW/JCM8id/Fh6F4cbtpCz1mWsxRpEslwMpl6XhZC87mqBPI/8KMa/NyjGjX -8zKJW5TOZ+/VJA+E5+Fwh24oPyNJOtjEYW2tXv/FnVZ7y/lX/xhkYCM9BYZyP516 -p+2xqU+ieU4Z6VLdeil69lVDi1NgigYXF8D4TXnYxXhxab6u+WCCCeC/M2fxYn9n -aZ0xSh+LSjXaQ8MK6KBv60Sqeh+rxASAouRteH0YcrQ2fTQWt0KaaEMTwkp7uBQg -12rYIDnZ6kf0FjH2dyHpkBBbPE+qOvj/Oi9cJRgnYN5jSCgj1dZ7GmZEm7QfTmlj -ayBCdXJjaCA8bmlja0BnYWdyYXZhcnIub3JnPokENgQTAQgAIAUCSgQseQIbAwYL -CQgHAwIEFQIIAwQWAgMBAh4BAheAAAoJEIqviNbYTkGu3Vsf/RLJj2GzT2OpJLje -UFRY27aGbQSqJOYhKz8yHwSWNtdZNSURjSlV3icitj1PVEyptdstrgYyKeZpdUzH -L+CmfKr9yhqFsfv3JY2DM4nnhbmDb+PRq04MtlbTeCMRLXmsu5z/I4qd4EIJzrG3 -kmOBCbO1Q+BkaShwP/zQPaThICOrHNS/5FyoTdDyVZWUgCG90MD0hA9Hd3L+BsRh -ka1wRAR0xN1Qn4aLDRYhh2sZb4LrMvh2V1YOOKsUuvlv2ABtS4F+i4kua/TbDp9t -5m8tOJkZfTWbtMSiVcL/uYSgFEq7a3ck7Xi2kbe/guQlGqJcVK+RCj1/3qyW64Iv -liPwDmjArtzFaPiEGjH8POScrimyalNbx4WyLOtU/Jic9rFymt3hHE5WtPX4OF2l -ielpkyPgtCLiLJMrXcUW/GwreWvDOiCLUhXQ9clXTh6duKfJq6TxYvtdIbEIex9k -Oxd4NayBqoP4YEkLlybyzDWZi+q4HE44gx3S3FqX+VJThk9G7W0eyN04kM2Z/Yd8 -yPYx8evv9mwN4+YfRLjWmCcg+XzekW1Q0c9/BD3Is1axqRy4+e1Z12rrcg8QiXE7 -sy/a1PlHTAfwNnNolRpzRflpLIseZ/7kOGIQm5BCmh+8Saoq8cjMIVadDu2r5W69 -dJVDna3lK8vEd+Vax/luywSYSnhiB5kOv5Oq7jgvXi9c70PH9X+x6mxtACD8KoAN -Ccffi8X/ABbyil8U3k6opUEcX5aF/csmvI2vMsR0u41YFwLZN4+M3Ww4FYen2i6z -mLvCuNt346GrXMno0MX8ZH13cKb/bY/wgcFQTxBoaIypkxzzWjx0GEHtletnBNwV -pjAtrOMQk7/NvUXOoVEG2uQO05IErogspv8fW5+o5KK7x+tOZaNC5FnFJHx7hb/c -vgz9fJxv/hbFmAcF3rN1HnmpmklCfvniaB7xeD6Ddcf7ATXI6CQasqaiwjhN8/0r -pcsB52h9T07BPLLsj1vyIAueNKjsGfL2Yb6zO092hGV3WQ4+PoKOW9gr1tyeS4id -3bBHBWfHnFtW3+mWMZFArryuBm3cNEV/4nApZrFyhoQH8o5SEqLFgsMjg6ASO3kr -jtwHAVUqDOUVC/CoAM3nQFrExvoeuYrv7cII4q4MATnJPtwcrvbuikjqtCNddaaI -c3YtmyLjEaaP9oiFGFCy0ZMm30CMflpm09i6R+1pbqoeUx1lJjnvLV5cy4WDqH1S -4Uz2E+oVbnmQKxYqy+ZKJC6nUj2ZxRzD1vrKnN0RNQlOXcA0oomwpt8M8YlHACKj -fenxMiJ/x1Ih8h6pRkPuNHghgM+lZlGbGijaeueWYkK7Xr45R2RaSj6mxC6nJvyl -JqX/DDyIRgQQEQgABgUCSgQw+wAKCRD1wmAWTO7XX0+QAJsEWE4s0i3hIk6z2iTr -3+aGT3rNVwCcCgXLmSRklbh9kfiHvBesBsZsSHiIRgQQEQIABgUCSgRFRAAKCRDV -M051sTE94nTfAJ9jCZrnvqVJo0tA/7PdmvLcNFwiOQCfQ9zvp5X2V1DlsIwWiOKC -Sh/CvPaIRgQQEQIABgUCSqGECgAKCRBjO4UoUXjipTLVAKDenG1e5ezGLHhyGLYp -UumBmW8bDACeLk2jnCExhcXc8DvA59mQUV+F33CIRgQQEQIABgUCSvsFJwAKCRAT -LknU5B7cfrndAJ0aaFg2t0tU8CGSEToroSUVLgrXywCgjUiXCowy3s3xdtEhl3wg -4zqEijmIRgQQEQIABgUCSvyE9wAKCRDJx5JOUQR9ZniWAJ420lKnPDZmdDFU9qdn -EGfBT0yK9QCfQiP5mzqfGo1KhgmZc2PStbVfMlWIRgQQEQoABgUCSvO8DwAKCRCb -H9qfPAYiMdz1AKDbRUifshBTo9sSZxzd5Lvlfq6nkACfcnWjGlZd+EstKn5SM8ph -xTafHquJAhwEEAEIAAYFAkrzXgcACgkQhY/ExPQ4VqN4EA//YzVYinjJyD2sh1fe -3kv2I8f7XgcDYgN5k3LIEKAmwUzk89z7dMwtykqICS9Jj/bVI14Jnmc43YueHFmZ -XklLr5923B/CbrLakd00Y0AQX4X6z/JPL+mYwdgxuHZSc2udbR2r8cPf603k3+xy -xlJ6PJIk2nzweYB9H/yMKcpfJ5UhZqX+oQd4t3KKmq7Kx0h0ezagFtdT4cZaTG/j -XXJ5pkYXfX+rQtOMvOEmMNvlkiMYemygbKefhW9gLAiLr4gKuL7ViqqQSi+FCm6Q -3o87Xp874qQXxWRIdmw/0Pm75Q0vZSm4t5gsW2G4ha2zx+wmqPtNEam8qlx4pe+i -QoIRreCv1DnNvzXyEzObEQ7HldxHECFFWMSAoVWFZ+If8dJ3fkKEcTDKlCcq+TAh -mYqLm5Mc+bgNhbXh/4Ptapi7aM0R6OLHexc5Ik542e/42aj0xpsJTcggxR+erJoI -tF1ZBVWIBwFKC5Ec5pwMgc0AAIU09+IgAOwtaAsRloAXZXx6oB6nqJA5JS1435gQ -aj3ROCULyM+pjggp4XqccDsxWCt1yituhxHCpcCNQD8V73235+D71EgSoX7UKJS4 -xxkxnL4+jaYB8PIh7DZ5pmBvN/bb3RhHk2VOCdcz5J+HEP/FrvNdvwik3OnXxzFQ -be2mkMFZC7FHjlJ88ir8x4JIVfqJAhwEEAEKAAYFAkrzOb4ACgkQMXxt+Dx3Bc/T -Qw/9Gv4v7Y87zOzYoJzmKvmK012AE05MkxC8bjTDvzV5XH/Tr2mHE+5blOQgPvJp -BeZI7qRYMC98+BOg8yPfweaiOADsCO+CV6obNcTRbmBNiGeFplrWSSR4GB0ZB0Yy -74QJLrI8zig267oxrpO+b3KSV+Q3Juz/Qx6Rhpm7EyB4JuVjGG75oYi1l3yAPTfU -NTTTA6i9gbPTGiMd5wQcsgRUN9nv37JSNhP8xz4GUtUmxDKdaSVo6JiR0HvbgecT -hzN42t+9P351SMDiMOsAV/o5Cr0WMRqXOJi36bUyLeY61AwTQuohkzjLKHm/MQuv -0R/9rZ8fnIk/F27OSjkFM0w4vrraST0yOJB6xdSK2WB21TNp8JRncp1c4UsUjLIj -Knu9Rq15FDJ0/dvCbv/B+Gy+x735rvhy8jLTurthndC3vwpBhlEThXhGah6TkkRL -Y3exXZM2Dew3f4cbEKNVS6/4CAf9WsstGAFLcQyR4gDBTeRQF2UDyFnHxOnq9HgW -G4MwlScv94vd7hE+zuX+76n3Dyqlc5roHQPFFkRncTP+FTCclNph5eh2ssNyqwtl -AoGKpqv5zJU/lebs2nH/x7GpLIqSNp4cJwDHpAkBMpaBQV27DbpXF+WfI2lxTxIE -2IYGMZmRDAlKDmbBMs9Oqk3ChLQETEVEDT8viZD0NFvjWMmJAhwEEAEKAAYFAkrz -YMgACgkQmaAwKd36GZ60ZRAApqsfylg4CRZsFqaql9nWJU0QVud+L56F2PaUwxWi -3MrqroocXxeM37so2Vg/LDm/pRFQWZ9kWkPOZcEvvO50ztz7n7T76Q/y221B9pb7 -54BKAWr7xVCuHQgMNKQaiblbgLtgQvJ2BNInCw2tkJrEzoTMpkGShdPlBpUrYsuO -Wn4499LcDzS0p6B2NXRgALlKjoWKZu4vbCLAbf/oeXH0MAHvpbsOZzvpSon5YoXM -mM/Wcrrrlw2rsKJZ+9baojcn6tyKtnDCJEmm2xuOxO3cOvQFqrhXIZfO7gaI0j+G -yH+eyrsoLJJI2fLT6CVqlSgmR4gx7d55ccHQMobwD18YrQDXczlazoBzinrV9uBr -G9uO29zD8KSrTZfM54o6JATwu9UASThob1ovhUy8GqDE1d8gcZy2iwep3i86ptfU -sqq+9mgar1J/3o8iV+mxxhmcQpPTnA5qPiSoIsnvfsUf5XkccxByiEM/CWP52IOG -hErgTb7LJOcrCwcU5Wm174r04m0D7B5YyTYWa/znL7siCrn9wQ+DrE6S4vBwsNP+ -NiNxCjFMG8NT3+UPblp7oryrSW0XNyHVWpRy79Z6k7aAllgW+n3d0j7+TzRAnrrS -gAt4o1eGwCsSIjWWS5jcHELfPLWn0nugTqruXTOAx8anHkdzghgSWn1TXRFeP454 -y8qJAhwEEAEKAAYFAkrzuvEACgkQIFyGc9x0LHzx6BAA53K7EaCVX0X9l2Jh7ys6 -28otsX+gWZjVAAzM4fJu4NxcQB77geV0HR1w8+9thE4FZG4v0TM7Ye+7OurxRASl -dUVv29qC4JuSL+YnknjD8/UJdVfhqu/VSTESIOsoEUYHBJquy1NHK+FI2Un7NQFF -Ebf4KyY+N7XQpVsROko+iHB0p6tOR8//8UpgtnQ29wgrXdOCCyTVDDNwAkL81q6q -qXKvI9UJvPuKyjkWcxPW+NYK/n7ubp/rfk5LqUOJi6dn+XIkAWI0PHXcsRj26Rqe -FMTP2zFoV+sSpUksloJG/EZaQ+UHSJxs1ZKiiixuf0n7H8WFNERFtjs00leo/ha6 -0KdwqeiLIRhavtVNQSfWYIkjLEAIgl0XGp3Wem8HK6yxM+20mdIHwS3gIvAxB6xj -cbNBjHLmJL52SbEOxuQZPpGZ9+nQXY+KUAN1z4cAEAbbQu6yP/EOFutuJdl0W9ct -9+DtHYOWEQvGuZMirSzU5ApF3JT2Svezq0FcF9JmAROu3kQ1AI1wS1FrvmFTEFDC -16Hl7IyVA088QA+UgnTmC6QDd4XbPo4k2pSuL1XP5+mMlmuKEHjZQv5vUfm5nTBS -GiPMAqcS6ggoMQV3LTLQxx1AwYHZwIR+mRKx3uMAvm0xqd7qnLEbyda1vM5hX8G6 -brbmRk+973k8XOl7aSlaEAOJAhwEEAEKAAYFAkr4niYACgkQEMAcWi9gWec4fQ// -QUMBiunb/qCNoON7b+jdb2GfRFivs0zRFkOKxUMJAzwkcjj8D8ruoaseL+QzUpxa -thWkmoXBmSGc4cBxxB2pFgyITtYvGmQxEmwMBYRx0SEoprEUCfC0lUVdq6JRXb3D -MJ91y8HwKkkKjqOtXeSKMJBGxe4k6qb3FP/ddqvyt+fN7axxANgqeY/JhhAXT4Ph -ivbgAdiqU6ToW90qJxyVlLlj1H8AkSeis0vjJo0sIzis813ftVLgjvYOlXZSLcpW -xsXTYr+Nv1+T9dOF9FoMS4LQzZvf056lEwE58+5O+xbPGniD7o5FyJu8KyV6ptj3 -5ldLx/GK/ervKR8nUr/L8Al5jhnsr3XDgdSUMLsBJ79KHMI5lwAVblQ7Ol0GLmyy -3t2rsMxDDxJEACPrNm0/0HxZUkGL6uX9lXm+Q7TuJ9RmXyU/DTHuDmhsOusw+g+x -XJWXZuIgcdoDo2PJTwq9pV9QDo9GgM4c8HB9kgqlstWsqbtcrZ3d9UXBYUpbZEks -5HcLd4RuWZO57iutSNWwNkbsGtPrmvfiVndzx1BNDv3AIUl1HVUTCtZICluYdQuM -a2mJgNR35ylA7kFRvbGu0beD9PfWxFyFusEWhnuNiDfB6NMSu/VszIWR6hutM6QI -x80bSDVyDhBp5v+OAQeE1n/uV9Kjft2cuDf55lKH3FOJAhwEEAEKAAYFAkr4njgA -CgkQMYF4WlJ8gSTBQQ/+Lbvk4+gH0I1FmZhvgipVy2qMRCivTsRhsRtXU3AlZYyX -Y2mCtx+DvrL7z6EYAuguXEJUIrihcJPmJ3hiKMjUDovLzZ6rLojqkMR1NN7k2nVw -7YEvCRyq9MMH8Cy5jGiQvH5q2oqY8xM6L4+ZEpvl4KCI4W9JBsNmF2ynJ1K+m90Q -TZnyDSUkMqKk4KofyjfCBRNTrOylM5aT+EavEFfE6W1k5nQOnNO1MuvxHrHxC4Sm -cqWVdVMrSGZN5Xx5/j/0WiHGtCv/4r3l9N/nfqW7hVmDuSoPGV2ZoCKuHKFYUetI -3+vv3teOOsiG/weyD6/T0ysM/PkFNAEaOU917DUGKbLB+T5qrA7Ijrf7FwIiJW0N -7SW08ihADqEXmgILW6zE1SdMZEBYDZHSZOJzQARKOg/RYkiaov3khNm3cu3BlysT -zx7XW05sTshtSSFkjvXBcNlEVsijTiv3aSFEOWEJiGlE4231e6nwqyyt1rwF8w0V -AoVp01tylK9B6S2mzR4u+3bdte34ugh77PYAd0nqrNToKMgoDwLOR5JvFTH5jYGL -YMOnN647EAoLEHjWpqpsbO5M8nhlPRkzb6XfZcSutWgbNKNhlAsDyBvggAAPI1Bz -FnGjDiFIDxxT4f5NDgvfkAq3dqydLSpqLWbWcmkHFLpq73yy0vQM3iyeYME8Os6J -AhwEEAEKAAYFAkr7NYYACgkQNZU5XrPY4brIeBAAvCmtrm/GQq76lEcN926ZgC0z -gSFUlYJeslyuPJv3rBqRKVvlO9O3npbmpBWTjZH6RdNU9SSUyszToOb/Q59fGL/h -ADeAJWP2pdvmvAGu2MvLxQmOqQTxABFa9iFcwLSztyC8BW7Sj8AaqeCB/6iclkpn -cBDB8nZeY3RPOJVT66WFMaEhCL6/SpM7ix02wcDlTPyUNUMCOL9grPsMqVkSjWPT -tOqrE3a/n9MDzrWuWsw9tQsD+vVp3SVjZ7W5yLroQbmrGBKhcK4boDwtUHJCqVYC -Ivn8ExoZ9x056MEb67LSiFn5S4tBRtjpc3H9d9MTjuzDdP2WgL+CUHPuGJ8bbNyu -4LpTWfiCQu8DcFFxHzsuIjYCST696STXiePxKqMVWqst8BQIISUpdj7y0dRKY6No -l9KDtyQ/YiB83+A8PLqnet1z5Kvs3R1jOd3NRhfskHWIBfwzK6lI6iJmGH1UwXHX -GUJfD5b/ocaJpR8GWGNVp4REqUKbRJSEXBhXAwF/nWZXwtVYVoakNk5TrgPnBQwE -i2usNehJDXyaRr4lWHnmLO9dLDx5ou9JsuZeTj7Ct1jRHKSOrP5iSPhSFpaoKuhw -sS+cOwpNifgbYVVSy6hCHZx5dG6Xbc1A0/nSl531BMAFUrAjs5z2rbpcJJyO4sTu -nG0YTZwh2gw3a8foShmJAn4EEAECAGgFAksM3mggHFNhbmRlciBUZW1tZSA8c2Fu -ZGVyQHRlbW1lLm5ldD4iHFNhbmRlciBUZW1tZSA8c2N0ZW1tZUBhcGFjaGUub3Jn -Ph0cU2FuZGVyIFRlbW1lIDxzYW5kZXJAbWUuY29tPgAKCRCbuGOw9Ru4imZyD/9y -6mYirsfvPWfe22eyGlNTqHVEPu9m+xHBbV6L+DTrGiDyHo5BcVWYwO5CoWnxzEcW -UIYXULy+SVi/Zrdv59kALxI+H3VWke7Wm8xDH6FdG2ZkzUpqzFK/65hYY6Imigpi -Pq6k/cHw7PUYCoWwnI62gEqfYVycjXt9pTkBM+ndlHgoxYcO+HpD42VpWSEHMnPt -tV7ipHVO8cE/eX6BGelRXgGeyCKda/vWTP6awxdaURagJ3Yu4jTbE5pMhFbGRUyZ -N2xZKHsbuJiManXjUAN9thE3x++e2Dclbcvbo5fIdB1kfH3MHY+IGuqEGwKWfSV+ -L2XGM3wdjf09xmwsNkns8fpBjEGvrB+mKnN07eS+Z0NbE7Y4olHAXU839iHIiXc1 -bejntdlvN2pjjp46jGAngtiR6ZezvjTl498+8dg+qKHI7uLITeqYbYl5Ju6kcCRH -m3YaO1qFO4jWneHV5eYz359E/aonCbGtVvxyWEjOi1JdvH4/9bslpAM6fI98hC99 -1MiqXGTZio7Ipa3dEwbYKXlhHmBgzy80BwUBvS6mLnWR31o/QWROFQ0Rt2ICoKMD -pymVXsdyYyeql2Ne6wrp6RNDncLRm+DH7+gmgpA209BKhuciqUT/nAL6JGR94woV -nRBBhMTGfFuhKwgevrqI+jo330yQOwCTBF1psI79bIkEOgQTAQgAJAIbAwIeAQIX -gAULCQgHAwUVCgkICwUWAgMBAAUCSgRBcwIZAQAKCRCKr4jW2E5BruD9H/0Tm++Q -wXxDbUCVU2jPGcrWhUlb0MH/hShduYc9Pw7TkR4KidPdssSMEeGDfUdgSpLjMiYD -Dj1DQAgBuJUyvpdR42176BypRfCPSmCgTMyeVErA+9nBp5UcVLT0XlZyDa5nU8XB -fXrZizmfrSlsz/CtjulNI9YvICvn7E+xeTXDM9WC1I/A1l48I7QMo6mtzn3cbnzV -rwE8/ap69P4z6NVTcrhkukoEJJ7uDRFtio3O4Sw7zAO+rseNLBa4uAbh6n1m6nyX -4nGiP4D5cPAUHPZt6ROgjh/od6qFOHGOa3G7UMhoiNzK+e3ce8rn1cpFbxEdoEpM -atsOej7hnsH7xFD1mqu8KcUohskgFKY1QHG+Auz9TRp8ThuDpGRvDZXHt6mONlo1 -WdTdA9vNNzzkr+yVMibxPyXMZBXBoJiK1MRCvsVwhKy6hhAGKBtBfNeLkbgSwGXO -mlFp4r5sWjfNmWnqSIFtvI0u6GhsmiveCiLbcSiiSKVGEkih3108yy2CD5wUjPoE -S62R+6CSiA9XCw+eucabhft8DSi3qXUJF5qswSPcqA4tKjOGlBUYwf1MfukdXAh1 -YnA7TEOLw+iRC5akkWXtn6uwOFmexP/4N6dvzlIuRYMgTG6hNwuoorF1cROv7BkH -VcLEqIwZN3aUnaLWz969wYY6SVMzh/6G8fuynAsSWWwHXFdRj9k1VNjPiN3dVYLB -fuUI5OOt8EsiSDgGmGJoWpnD3uHkoYfLAjnwwx0ilQHi9X79sCIZdyjgAYftsED0 -cPvi4b7fOhlWjPbL4ycSsaXmHvYTVpt1I7oKt9IJRdMEaivFxjWp+h2JK2JJ7fNJ -V/41GP3v/dmUt3zz/ai89h6cD0L0eXvcb7g39WU9Z+lTRv1Zbr/aZKRM2twl7iBJ -8dMygXwmSJNIkt9MVmklr3pxzcgtMBf3MzFJJbgaWmKg6ZQM4o37xlesijVrEX0s -jbyvrR81f18GyB9SXsMjEV5zkuE86UbxoUqtmxYKefVzbCpugo/PYkhaPgk04Tox -JH+zZLYYNH3yqt4RmwN4F6KHhh2BrQIFhKNHPrd7Hd9WEZ58fZOFcqKzWEtUZ4DX -46jJvcSyO1EsD6xLpVMzZU9J+H23IkLqmnAokijjyC0LYZzuVlxdEHRM1iTOF2mL -b6iMr8wLAqoyrmHI0Vu/Sd3amreBj4aRRTcOxriTSBUbE0EeQ+E/6MvkjF1qO4vR -DaSfrl25Mry4y917V/lDExkVVZkAz4wnpTlFYOKDxDtDs00ZaC4N/1buJRDwQoa6 -p0f/oW5f1obEqsDA6KEazSC9aikIE67++guj75vhryPgFo1XR8JNaApFiwshtZzx -mjXHrlG7i1Lt5FtwuQQNBEoELeEBIADZVO2q6wIlvBr+TTW8jfqO0cZuqo4Prk5y -4q1oMrXI3yl84VJ1s1+gTY7g9OEcb3SJPX9T7DRWj83p7GyVGVxr7flnQD2jCtTo -lejmuhvp5l+oDES8rIFfc039+HesBX9mjR3aBqYubWLefawnkxi7q7gdqFoFJNSv -w5MfHw9tLMUzF54NxsLaUHc4IQtginqchM7e6C+38BjEYhpK6wiRvfbkp2k9z+w2 -AwNY9vjw2MbOtjYxXNNL3cK+IUPBEXqxvsXsm8dLwJhU/AGYSvUgZIUAjyqpDure -hPYSmCmVeloZvlYBdzMJUEtMtmPgOuB/nkFjKQALFvxbt5IeQmQyc48UWmcgCza/ -LJn4/cqA6DjEnN9fM9LCT9Y8d9NwIeE5N94vQkvQjGYuaWL/URv1wp0UC40sDCo7 -PfwcKl8v/+O6mbq1u+qNjMCvU9AT5g7y+AEf+yv/SWlihe81v5H4vcO3H6Oi/l1n -yCMEcvktX56WgAITgNZs2GQyL2+GEfYx9BATz4X0IfA6WFStrLJrAc92MZv89i6Y -seOsBwVhg/aCuIHb8D0Ukmu35x0usSarP4522u0j+Lqt0eqPOfhEnpGpha+NtuaD -XjvwBKJ0Pe+9ZsdH/7AIX8CIXwpS7u8M24Ibqaro7AFPZWLLL6P65jXKe98AtZfX -h3xoGx7SbiC6EDRrQmRpVsGX/tCo6sQGKhWpaiCecpeDOHoOa0po3ABx8jipzBTT -qS+B6P+TAUOSuMvQWp271PwX0mFNG51sF2Xe7XnxtQCZPK3S9ML7LiwmF9cN4tBw -8zmvC0vGYsp1ajHbq7brmGzXFOZ48ISGGzSHYEj1Uff2DRXsvxUktDY9ba/7319K -nactywtzuZqbjpqFO9+SU0v9btDr7ap9jfuYIepy1bNHs5Z1v/Ig3ZlDwjD7NwYh -/xr6Pe8oT/mw9iEIlPH4bXqNAExw6JjKn6B/R2h/LOHP/liu552sBr48ynLnoIH7 -jORoPcNPJGASRpGgM9F6ZqOo8qizLFLniP3VQztMamMFj791o4qvgjp/oxhTRuYo -3p7HwfLZ6N6cpjtL3rMtQEstartLwGsVpxYqvDkQaMYcbwphnnmuYXQCUIDPoYNK -LTi+0rcgIYaGT6czPo2fbN93TovkCMxXHScwor1wGfkDCsd+PrvdyoyNOlUYP8dM -kM3iGmUTA8h49rA6E9a7Hp1+F75XrfgyDeGX02WlXl/wByByxdNAszlLfXuWzHKm -mWSRLDEEFUyDG/ub9WKXO9kOm4aYjn6RmU9jUx5ypIg43DVlUrnh2RdHyYDy3kwU -UBcZbdLp++y1J34THRZ+53+uEcvE8+kV614+LI2zMyWLDr0vyWvXABEBAAGJCD4E -GAEIAAkFAkoELeECGwIEKQkQiq+I1thOQa7DXSAEGQEIAAYFAkoELeEACgkQ72am -4xjEywDFFR//WNNReLoLcWc4xZxas533Hfk8gHm88bXes/cJ3sF9Vwq212rDpK6A -NrMcU27TfSl6F4aH49DZt0WwLysPJysKcL9ssgcn8PeVUW2U59apa3X/xtm03Gqz -suwqgRwWapfulFF/gl55+ZZCl/mvHgiQ9bdhnT99xiuYV3b/D6iGg+MKjEsYOkNd -9PirbwwXbvC48tnPA+XezMIQsggsk1852I3cLfRi/X8qNDkZ/DzzVoD+qTpccCR1 -Iw09iADo95TdCUjubu27WW3Zhesly9/J/AzbcSB85pvX3EhlV7EoN7xHvgJMiAHi -KYBD2myUOv/+XuA0zB9Z/mp1yiSH+jQntd8UMSH2gK8ykBtWM+R0mbuBZ6nTovZD -K92Mh3DgpB7YeU6iuubtXrbNlXJOVziUl4J+4I9QVyjQeLUDJXKnJ+j3QlW1kN5g -9tGbo/I6stYGJZ4DP8yzy6lD6sww51YYwI+hB2QKjf8NWupphim5whrVW58UWrIs -lVpKJOMzXmlHKlKRaLUXzkkRlKB7I4BS440MErIVBlkOtGXB1gVbfNgQAPtypN+D -EFfZHvwt4THIPsBFptbcIw3VQQf3cbzLxjkqDdSz8uc0cGBMc+lb2/BeJoGKtUhB -6jt8rxE1tDhjOL1pTPi2300pSHnLUtjZsXyMvUrTkNA2AqwIBFmWBU92Zid5TDWs -1uebs7GoW4qdeHGkCHTDlcqy44/9XJHe0fxXx0bau+cx73hI93VV62KyHP2WyhON -We+jWkB6XS4/Vt26RyvsQUUggf/PyKu3zSz4O+vpdy6kW56KbglCWWSyjDlng012 -TP0TRXpjRh5/B2anIi4DWwvYGd+5bCd6Cn2YD19wVKmG6wfUcMW49l6mgLUPQO11 -TCbaT94Pn9+0qREkUJZ9gDaFKBj5ssXxvVLZDWe28v5pM52Fz4E4IUlpc11RfAKg -x8AUc7fNuz14AFwkzIrXinBPcRT4c+etMc2bNAbU1mf219tG5Ag8fDLS/IGuNaHy -UodaqzthLV+sg6W9XacC9TQSGslLOOwAMy7N34JQ7iapzdCN62pFeWP9B7jF27pM -WKuYwvBewC4tOBw5OH7QyrPSNEwIRHL8QxZ3j+ySBEQ8KVs3GfJsATRuvQckf76M -8GaOFfBD3usFHq8WQ8vhAotUgYvRyxrUuQJ7nQX0ivHOly9NIRpdl7S9rVOsuhR2 -yUL0TPuQw/Wn4+rA79HyFNxBuEg753GbHJMCPlYwnK3lnquLLJhQyOtX/1TIT7hS -C+koXMpfBskft85vl4DejSZSYmWxfxU4ctVyvZwtEvOewUzfSAgNSwIrTHYooyAe -uE+W37vUg2en8yKlZZLkel/4lWV98sQrPDVAIACgKu7YqUeumQTpDTlgGrWk2fls -G25Qcnu0T7sywY7CKPjU3O4ZsZ1mu+fdIxlcmutIrRqra4FyRaSRBxplE1HCUjI2 -J5B57zGKYP77B0EeO3ThJHsT4D/E+wyi3wJ2Wp68cgvooj9hXvaDIHOj5Eu7TdTp -ksFtmxVa3stc06EiGc+9ZIH5mk+pO7heybOeXEXttFvs/8NEQwffhyz48W92jOGt -53+iS4+2faH+xio9hYHQLOgLJ7GMBGrSQ0sYBvRGvQZOlijjbMNsi9Fo1ffZB4Ks -XdtKRufvfq6Dhw0/1ZkIAdFLxMVZ3DXsGOHQi+SU9c2Px1zvRTAyLTpT7LaB43Ti -MWLDKmRXLFbFQJpzm23HuFONPbfRYJYk/J/QaEWT1tSSpI48KYao0vz7tfkxsQkh -k9lM0g/rq6YrtPZDZxVvZRncAyjMB3gaNHw8Pf/f78eTWsBKsuDWlbOsT+NpQZ+C -qN5r/zj3FpPXbdlu/3/u4fZKJCGF3IrqqJmGnDyx8lUCqwzfLIZ0xesKHJ2IxsyA -C1RGp5cWSTIEHarvqKbIHJI3c02gA94IqxerwzH+5A+RLCX7encDbyGyRLP7mrva -C3zxNJfFIjojB1W+MkH5mjQZY/h5G71dsWIOZlvm33paB17XjcUsAJ2ER/+rqlb5 -V/fw8xoB2HxuN7hFNgvkABww6HTRlM0Oq7I+ZtN0bnw0k1OmYgN6w9DPFGx4PZa+ -LmBpTgVudfHLe8jFF8Prw1/Nhc16B8EEaUkaXfdiahlx9By8Zh+fRvYKvP3ZD1S+ -8PaNgLQQ2I/l0GhbLnwFT0dd/D4jz2SrF/OLxwjSWeKFHdmuDkk5Ky5aPMKoFTdB -z66t1HpU6AqmNjClN+0TRTXZe4iCOcwsgMu68BDIeUElLr36qt/Hl66Abp0sY+fp -/YOSME0SQZ11Hvs7gAdkGINKV9xpXxNPtNEeINQg8w7IC7tFqPv67zVZ87+/xrCn -1PsVCfvfdh1SF594+FviqaTolL8HGR2KAPVGsUt122CQRuXu5gRNrAGxwKHtb88m -9iWPNLba7FDZUZARL0HRThpeF/T8hKABG68aIpZ761QgX/7MptCZAxuvz3h02OT6 -b0B4atxy1QdK/7AHYKsyLP7U8GGT5OL2O7kokcsiDaJa+k2FQ8HIlZ3l8CAJgYTd -DC+QxhyRn01pR+eTK6alymfMcCHT1/bsXPSW8ca112/z3zUg8eDkkImR/vIFaG6o -KBZB0iag+L2veU3uIXqHC/CW8ox2jOJyjTjApsAp5VU6XTQza/fRgPZzgWlhnxja -ospUWdghpt/4LWZfwUrsgCQJsWVN/KR+7tmR3u1rPm46qf+0QAe80v47QEJEuQQN -BEoELp8BIAC9Xd6Jo/GoT8pa+DzdcgNRr9rIU6u/VhObpc3eIz3uenXlGz9/91Vg -HbuxSY3nqIllxvuNWboC6RPnTrDvieOUIik22J06DYiXklbc9rlEKy4nB2Gu6njK -hrrNtD7V2YqL988xtfGh2SzuTP5LTaAZFS2CpJthdT/QbxiE2QJmjAfjPEdpkgDC -0rcpB2nISDpJn2LmZVDYhuKLBDyG95SdwhBapL1puFnQMQ1P9mUMpIDtYadz/X37 -wgORHa+a2k1es2qXTRo5LRlUs/N7cqfjgCwCSvZLZIcQ8r2ik+KCOHqYYrRu8G7f -qn9ipJcM8u1M3G2zkrUorzHBpn2jP0e+ChulkacIIv9Cd7Pdl56V3/y4t9dkpdGL -E+9HWSRxn4nPVCNI2j2bGyT6cSZtEnfeiHj2pmsBIfg9w7n4oSPQwtNLkDwxp+Fv -UYrbehD3gB1M4Mx6b0+7ZyZptk1PY2I9eRbOpTiqSTLY/dQhe2L5aYZ6vDPl0I6j -tkcWDuVnxcFIREWBEw7tqpHn/IhQy9xNMQu3GvrFlCyP6XiXtZZATDl6EPgY52C7 -0689jEnky2mpvViza3h253vJOEuGb26BKQ/Qov+Pukdp4q8NMOby8VVGcjKrhTtM -QBRCuKruOzMBtdcNP5uKUPsnykVpG7Uvqy9vFps1Ff6LW7Sj07y/7MVlv8wDKdZW -SSiqyGM9YiWL/lIfFUqHw967j3LlKjtMgYWqtE915GWOYWbkXPE6M0YdyzwUyTi2 -oWYbPMjTJmOe1FGGpW5rNhAISSn1a8xngjmt+eKCbJJCzReLzGeuA3A1Vh0G51jy -ge9Tr3KM7mSJ5kcNQVaxwLEIZTn+nef7wnvfWEmDKHtjmtzwja5BlZzss3I1l+Zf -akjBLcqM31mWjjiBjtzU49/91Ubwf5tHvV0yWcvRO4nCgB5rxitrCtOqB7PfS8SV -jMs9ItpT6ZGW034tfWoinz6LiaSQq+dsmW764gxcprjMI9z7K3ikP+n8B//oFShm -rR5jLYy1nUWq2KfLwFKO481KjUcF72bDzSpqYcrniyzqFkUGItTJ/Y8LneCBZSSA -uMjaVJNujNhDHJJlJ1nDXysDBPnwsIZnPUVvpJvEfKmoxvpVol4FHm7Uuuy+ZjuS -qsbzKXhsfM/5ai/fSvo1Rr1kHPwm7Iyhlem/CXGKzsSc47SNWLrnnnEbuuXprbfL -fxZ1NfFQPAgkOuk+v6TbJFXb/94SiO+qEh8yuYVBweQ8bWY6BgydZXwsznHh9+aJ -I9jPbBaLMoC01bBgCDid57ljKIxWYm0Vv9fKAD8hoEQG6caAQxcQqHEpxeAMFwW8 -fAc4I/obmkpMLL2krOkfzstRcv6aJD5jABEBAAGJBB8EGAEIAAkFAkoELp8CGwwA -CgkQiq+I1thOQa44JiAAnrvDJCUU8Yj6m67hYYEiS0bjcpagMnt42isVuSCmHU4B -aSJQtAEC+gqw+kbNuOITJSk7ONZf8TI3BSAEq9EloqdloOV3+/xlT9zPz9vy0u0K -2nbQN8SWNk5mjo4QPtmd44eqeYFShx3A5iLXT327oOwaU1ocDk36dE+0n/ia8SzB -eRSDm9aCB+boY+Nf1Ze4f3E7fLQEw6/Do69/fQWvOgXZQ0r9vnO43rQFY/Rukcrg -FX46fuiiNvTKI8V/uwtwd29xFl1pDpFfYgggIfdK43AxxazQkrxIRf1/X94w4T6q -7GMJ6RWSiPcQJRJ1Ci7EoJqXbK7d6g6JDX70aTL6ZBLH+TxOYGWAmZjgftNH/DkA -S2KhPdK350qZERlG+h/nw8q66Q09K5quGRIZ9zcKz0vBrIv8tTlcpux22midjcvm -edvr63qgoySJDB4t5+iVBQfaicpR7jVaJDD+XYeMc4EMf59izjGLc9UCiyH2Btb6 -N8P/3wJ/JjIqZ6f+vpJ0H5t8HDq/566MYN2Wg0il7SgrlimbXfCLqLAgaLkVlDqy -6lJvNHhWW+gjzl9IGawOlC/v4ciX+/poixulXiJIKPcIDb4SwQ4DT21TuX7fF2uK -tWFcMTgDBpQGF36kP9ViY7WjZTUGlsmeKBV9ugeaf4MhhaqxT6WgALTOrLuC2GwP -8O7L0Wq/269HzwUDxiFGyUywB5Cwiig4b6lgLoArnPYHJyAq+MwTgw25homK+Mnr -jjA02YbjronTTJ78orHxw8hx3VtQbSsMu25PdOqvpomamlTlq9ex5jHkUKL8B4Q2 -JFD7sL1cTHYISZn1DL1djlv4FIR5c4HdGWDBLCqI/n4wv4cWfnfkElbOatyTpWDY -IeWWqBeE/wqjB+HsYR6p+ImpDvSHk0F1ilytTZ6pgWKVkFj34fNu5yQ+fVxx3ERm -dxJDbMMzmqtnB9tRWJBs0If0o17JktN3iba6Jcpk//isPaBiP92+TLX3EImaDQRr -ZmgdL1Q/0JIXvi0mGV7Lfb7SBrEFdYGWF9kI3EREGyLj9Hl6CGwMwbnPBsuAmZwX -phgoJj9UwTM/VNYLremXwrCCGWwzC1l7v17klCVWVjDmZsAZz10szf07WhNuS/Eg -C6wFTnl6s5/Fr9JcNK3n0raGjcFPPmt/YNJYlrfWDmBzXACkTFY1POdyHGTjCQP+ -qJWKuYRVfKjosiSGDrSMA6QsHXOCfvzlT8jWACu0qEbcXJCEyCXnenJJSIw5VO4E -paQ/2mXqEbMbgUlwODFRp0ly0zRQiRlLU4Du+ZMTmiJy2Clvh81BNGZaZf2uV5fS -BRp49fNc4LZVJoOM5B8Z5hQ5U4iMkljJcdToI5W/QA== -=p2JK ------END PGP PUBLIC KEY BLOCK----- - - -pub 1024D/84B5A42E 2003-01-02 -uid Rainer Klute -uid Rainer Klute -uid Rainer Klute -uid Rainer Klute -sub 1024g/F1090E28 2003-01-02 - ------BEGIN PGP PUBLIC KEY BLOCK----- -Version: GnuPG v1.4.2 (GNU/Linux) - -mQGiBD4T++ERBADHIT28sBr2bmkqNoZBj2jOaTG4GKS/4cMxI0Jr6kkuO2PYuOQc -PoK0X7D6u48SMJX01d2oMVoEAeysmvuwkux3bw5rtcHZqQFfRtFV20n37RN/tkKY -SvkHYB6ifhGfghcAvRFYXaIxolexdblUhJlGQc2ZTDLKqtTaQsc5axRvdwCg9DPw -Sr06VUMVWXerGfLJUzE8i+ED+wWgT7/0ypt0rhZTf5wgMWjyXJ5QelaeROiWoVqR -6GWZiN65kFDG1e8y+pEfvp1JUxz0f+RVhREomdfw001CuI19cRaN1mHbY0nMLEzf -PMJgpJ3by8A3n0/fpsW72LVXRdGL94bYbY6XcHWYZDcT02zb4yap2GneEHry/Jgp -sZS9A/93qOeNZD87uQKOXZi/a32VETr4aNQclsRhRUtzkUIJNklPxjwNbYLY2CdS -N5gO3rR7e/dgdvq6ivd/xkQXyqqIe+i+OFIoV5Ur8b3+WQha5mednLryh6UbTIk5 -1hQUQDiKRtWA31rRlyKHMJBMZLPjpQOLqxxMpZNut/fNKTo7+rQkUmFpbmVyIEts -dXRlIDxyYWluZXIua2x1dGVAYXJjb3IuZGU+iF4EExECAB4FAkR8IpMCGyMGCwkI -BwMCAxUCAwMWAgECHgECF4AACgkQU0NGFYS1pC44cQCfTjPeJm8+4pDss9jrP86F -A4iE8BkAoLuEAaDOfQvBeT3u2QpMpVRT50wliEYEExECAAYFAkUHCvkACgkQY/UP -uSC5JsIYjgCgj2Y4MTf6IjxyJIentadTAxGSTRMAoJ1BvGa3LSy+rliiktyn+94w -MOcKiEYEEBECAAYFAkURkHUACgkQlM+NQ5LdW0tnewCggA77IG1Ns1ISxlCaorGv -+bgslV8AoLq9HtGgsiuxxdc0r8+3LRYhrf0utB9SYWluZXIgS2x1dGUgPGtsdXRl -QGFwYWNoZS5vcmc+iF4EExECAB4FAkL4/hgCGyMGCwkIBwMCAxUCAwMWAgECHgEC -F4AACgkQU0NGFYS1pC4cYQCcDTDDS7uRbXnvez+uZhGrEZlXUJwAoNX/GgTq1vZW -gxMWf2vPEO6IDhhUiEYEExECAAYFAkL9kd4ACgkQyFGoreGTVbonBACfepLmeRA1 -jslInl1sCByn8/cO51IAnjCnyfMFY0kTLZWK9bi2kVJJCogbiEYEExECAAYFAkUH -CvkACgkQY/UPuSC5JsKw9wCg3ahE1gb0Jxf3NMcYYi9ww6TKMcAAn2Js4AoO/Ss7 -8XOV+09ZaYvO2km4iEYEEBECAAYFAkURkHsACgkQlM+NQ5LdW0sE9gCgoabl0JSe -X3aXkkO9Ud6UOHaDWaYAn0ZQqf7t/fb5GMVmlDMnT8omAsQVtCJSYWluZXIgS2x1 -dGUgPHJhaW5lci5rbHV0ZUBnbXguZGU+iGEEExECACECGyMGCwkIBwMCAxUCAwMW -AgECHgECF4AFAkV3u4gCGQEACgkQU0NGFYS1pC5xrgCfQjByS4KWDDSpZ19ueCjg -dQr1uUEAoL8U+/gRJtG6Doh615dcO0QslINfiEYEExECAAYFAkL9keUACgkQyFGo -reGTVbodnACfdsIKmkq80XuOT3i1keFCaRIlXzcAoL13+rjtfhm92Q1IKB3m9cih -DHN+iEYEExECAAYFAkUHCvkACgkQY/UPuSC5JsI5ZgCeJTPavF1zdAfMGlmvkKcs -ePjlVpoAoMlRD6SeOF9O7m/xfeSxiI9OoreQiEYEEBECAAYFAkURkHsACgkQlM+N -Q5LdW0saYQCffjiXMP8G10ds7N2HNStVb++PTx4AniuSrYMcn+jA9pKlWaBBBAn7 -9mL5tCRSYWluZXIgS2x1dGUgPGtsdXRlQHJhaW5lci1rbHV0ZS5kZT6IVwQTEQIA -FwUCPhP74QULBwoDBAMVAwIDFgIBAheAAAoJEFNDRhWEtaQuju4An36nIBKzMpzA -rH2FQvFp2oWnhV6gAKCyVnUiRGz0VwsLkrEVxxgpqg8o/YhGBBMRAgAGBQJC/ZHl -AAoJEMhRqK3hk1W6dLEAoJyrrxDfMBbVLqo/os4wz/WOHmNSAKDEa6hOmBnfKk2X -5rA0F7ArAa8ggYhGBBARAgAGBQJC+Q75AAoJEO+sVzojurMr87YAoIZp9qeer38f -47KVVYFMAwO1TLkSAJ94LbmF8B98/ih2Z1BJaGBQtmBqBohGBBMRAgAGBQJFBwr5 -AAoJEGP1D7kguSbCXRcAoLaeuDGAbIkPf/PZJv0Uxf9CJxA+AJ0TbAOoaPwk4HKo -rOw6+mgH+ekRWYhGBBARAgAGBQJFEZB7AAoJEJTPjUOS3VtL3ZcAnjCFahSecBBS -kFnk6bhnkRCRHNrhAKCbMAJqK4O00zdRyaqbbI5XAFDHYrkBDQQ+E/vjEAQAhzT8 -TzjRECMxye0XlxeRn96HLlr9omOp4iagwDieoKePhKHU0OGaTYo/k0HISy32nTdS -ZyFg6inlz4UB6odhLp1vj5GtMXbpH5MAz7WyIWcfm2uXujRpZzg7cb6NHSPYDamf -09QxybFXcc19UBLkawrJDPszwY5kgB5A70CVOZsAAwUD/R41zgJToLPexypUNz01 -97/2Do1dQuySyuyUCmriv9O6sa2Vi3XIbwZImnHIqvIwu5Q/lEVBrZk4X6BRu+hq -Flm6R0z9n4WtMyFlSxUJan11xPy5rFHxu2Zpk8ciwSLrT5Dl1EqNwLvBFgZZ/L+r -/PLM0if+zVI5dbZQdmzsFpaxiEYEGBECAAYFAj4T++MACgkQU0NGFYS1pC5ExACe -PsnsMnIHlxboIe4iFG7JOxG7GwUAniGlU9WWfXiPl2deXWnB9kY35Bu5 -=JOCc ------END PGP PUBLIC KEY BLOCK----- - - -pub 1024D/F5BB52CD 2007-06-18 -uid Yegor Kozlov -uid Yegor Kozlov -uid Yegor Kozlov -sub 4096g/7B45A98A 2007-06-18 - ------BEGIN PGP PUBLIC KEY BLOCK----- -Version: GnuPG v1.4.11 (GNU/Linux) - -mQGiBEZ2p+oRBACNjPpUsJ6ZXK72LZCEnd+eWLBtsAbf9Gm7+NSxvxCZCdIcJZIR -OVji/IHKa9BfsI3F3nZ2381k0Ri2qK6ZDVRZFLCFxmUjwC/oVReDNiOFVHVNZkR8 -GBhc0QLxIQ/Gq6UUOu7hj6IAcaGS+oFKP5fPuSZi7qvVd7I1UXaqqJP8ewCgokfw -xMgkbnchyx8qqfWQyQ8SSIMD/32VLN5n0juPyrQ9X1N1Vw6qka4avF/9HG3EN9pc -MQi4uA90RnQPJ4LJ1cg5a0nsUcctqi+kHsa58/Fd555ZTf8sWGVhsdHeBv2YcwpM -kqw96Wka2C1CUrsGNsAVYmTvCWyAgPJWv+Ytsn2idzIWLhyqgAVqr7bqEjiv+tr6 -aTyKA/40RzPaZNmCfWrEZUMcN02P99sm5pP0M+1w59Uvj4HssjCfM4yffp7CNMhO -1UuXdoZMAvv2G1L8OcwPoxBqN1reo1VgjAf5LZalas8EzyOZpWWerkzpeCld9V62 -WwpTEDgcVq14jjtYFYmrtlb/WJVCqoj/oq16BbeAleNBVL6hLLQfWWVnb3IgS296 -bG92IDx5ZWdvckBhcGFjaGUub3JnPohgBBMRAgAgAhsDBgsJCAcDAgQVAggDBBYC -AwECHgECF4AFAlCzcM8ACgkQaTQKAvW7Us1kDACfRKl+wh0gYan5rCwGIYAjOzm9 -tmsAn1QOozU3kRgrub7EDmhksis5n7MsiEUEEBECAAYFAkc7x+4ACgkQW5aAEOBP -mol+QQCcDkcA+ygeInykabJt3OPNjLBTZKMAlRLRUjiw+fn+EfbdEFyW63TfXB6I -RgQQEQIABgUCRz0HjQAKCRAAvma0h4AibqjJAJ4sKQhpZkutP88QtqFWWRrNnDSv -fACgp31ekx2zqtzY3Tq6yKP+v2xuEwqIRgQQEQIABgUCRz0V8AAKCRAs1qgDIEbQ -9boCAKCkVGjldjCwV0YW+dgE+yCgL+28hwCgn01O53q/6MkCfs9nCtYVgbW8VJOI -RgQQEQIABgUCRz0o6AAKCRARiOjcOrhZi+uuAKCqwy43KpAnxC4jU0yIbGnpNTN8 -sgCfcQ+Y0SlvcxqUCIyB+LPZonfRl++IRgQQEQIABgUCRz9hcwAKCRA5Nfoub9Be -SaJgAJ9sT7R+x3QhNmsYlKAGtX3c2AOr7QCfSmicLEpwn/f92NrNwAAVqnHU6DqI -RgQQEQIABgUCR0CEpgAKCRDW3fAx61H7unL8AKClE3l8U6VhHVvdunLLhV/o8zYF -CwCdHpdz/WddsQt823V70tEeidwQ5HWIcQQQEQIAMQUCRzzQpSocSGVubmluZyBT -Y2htaWVkZWhhdXNlbiA8aHBzQGludGVybWV0YS5kZT4ACgkQMoZOQZyFIisNbwCd -EsXeA27pCnLPTRZpyi2Hp9zAA1cAn0mTL9QX9Uo2ppraETrCw3Xet9sIiQEcBBAB -AgAGBQJHPLrfAAoJEBllhVDDEQYR5LYIAI7ae+p5SDF6aybdOEKbzMiPCe/bpGO4 -QTfHq+lCGctkOIvcvwIFFheqm97LEqFjzgASGaJYSLqUwtQl0zFbYh2HxcaTiK9X -UrVL4cTBn+v5ae3I4zYXipKHOEM1B3yiFrObwLze6lAN3bKti9iXBaGrD/H5aFk1 -zaU0XhNpBFpDYcdMsmVjhumL5nCGA4Qd3jjvnotMj6LE0NFTm6x4QB+fHqPzjaaj -Rq2rjrTfBxBatOpb6MyZf0+cxxO/cBmslay+0b921cJ6UsuXGkzRzgIg9Va2smc6 -bgDDs/NhOjJG0NmKVZ1+ZTE5GjlyLknN1PHLtwR2A1aZz9yurDUQCDOIRgQQEQIA -BgUCR0CUbgAKCRA39o/1AVr8iuVFAJ4+m5BfqHq7LDAdQom/8gLTApNsOgCg0w0H -exbhIr7AjBfMYPnPDXtLJj2IRgQQEQIABgUCR0MbcAAKCRDtTu+wac7rG0RdAJ4s -BbRjTnDMDbvzbjs1+b2QA5UK0ACdHuQBnVCBDbaTuIG+XzQa3hUHalKIRgQQEQIA -BgUCR1arcwAKCRATLknU5B7cfr+wAKCHUgF99Y0sf1To4026XDo1GUw+fgCfQdtq -KughaQa7Yo0SQwUiE5fgCqCIRgQQEQIABgUCR2echwAKCRBAwqscHOF+3CE+AKCF -KpSGvHMUK0K41YfosMS/weK+dACfeYMblBKZ68lu6WdR2r4IKGRjx0SIRgQQEQIA -BgUCSAilXwAKCRChYGPsuM4wbtPsAJ9WSWjYZmDFkRRuA+ltNmG+kVvIVACdHf4G -74oalm4osHwCpMCkDfeMqXaIRgQQEQIABgUCSBOggAAKCRAPRQomYhC/wDS0AKCO -AzYQsUZ+10RZb1k+fxRguQ8TWgCfalShzaPGRwdb7Ocyvql7lt0WFu+IRgQQEQIA -BgUCSvyGtgAKCRDJx5JOUQR9ZhxbAJ0R4Qvl/Fv7CzcyamdZYCTDttYEFwCeIvSX -l/wkFYbdBsboh9Z6TnccEpCIRgQTEQIABgUCR0E9xwAKCRDtsQWJb5Ui2IMBAJ4h -Skr1sOJkaSqbgT8w3TEF8QNlKwCeMcBfh7GzdPh7sPEcyomSCfxcft6IZQQTEQIA -JgUCRnan6gIbAwUJCWYBgAYLCQgHAwIEFQIIAwQWAgMBAh4BAheAAAoJEGk0CgL1 -u1LNshsAn2jXy5dYyq9PyYGlQJOqgmml/uQDAJjQQ+lRwxOxIrpQjWZtqGQe9TOG -iKkEEBECAGkFAkdDlCggHFNhbmRlciBUZW1tZSA8c2FuZGVyQHRlbW1lLm5ldD4i -HFNhbmRlciBUZW1tZSA8c2N0ZW1tZUBhcGFjaGUub3JnPh4cU2FuZGVyIFRlbW1l -IDxzYW5kZXJAbWFjLmNvbT4ACgkQsr68QBUpJK8WCACg2n+RmlCWI8XD1gdOb+Qb -6KRLe9EAoPq6F2PJ4XDmi2Fklu0pawNYsfMpiQIcBBABCAAGBQJK82JzAAoJEIWP -xMT0OFaj8UEP/jO9SpC9Na0wzL3lV2AUm+CBq1gXhpAr6ThSystevEQzmLIVanNd -EH2MsaUCbmvp/3NCrljeekyUdras8aqLyT1RcIuf1bo6r4UcwecA9DrukBO+zmD1 -kPl8gOR9s8PLe4+I0KLQPDY2i/4A6vq1ayYwBVhKUmXqCZW03cpTcgObuMfHyaUd -fQ82A8Qx2e94ckTnWrX5yFGt1yy8s34JvDv2GQT1Ski8ghG37vOlNGZI0H2MjBY6 -kZYJNf8ZNGMz/oWzHB7YtEEJYO/eSiOASK6Pd0ENWrYWbtg/84XaHmpJsjMPjbA0 -Zr5s8UjHLcXIFjwXGYbx/Pe+DkYxKsld7AwAmnYezUouSL2yQ9tZmO+UCEwjmANs -wN5UgEopykF9rqIBWWkFkMpLPA8JYlHhPjuim710crHusD1dYXF3KbcGl6SMVM2U -cqVvZiop2hTIjqpfISPMZtp9hRkcswz00TuPUmAx/D2PhQuUvA+Vw8gPviDJHkUk -79K9qcniu/nf9VCTaYosJ+IR6XVAEOUydLPzlcMNPctcwL17nExVXCu5GDnXZJz3 -TwIPeSIW0XswY7MakX2dxULTmv0NkO3ogdu4vzK0DtQdTJD4VFllXq0x2gMK9k2H -AVmRznU7WEDbRumePWS+dtr8hm+Du9FEDyZ7G3Jd47VAn3ANV/skWjACiQIcBBAB -CgAGBQJK+zeMAAoJEDWVOV6z2OG6688QALtQBTR5TbYHyJflc8lzwue6vqnwoOpE -xoicT3jANlMVctg2sTgXBNCFIf+7qi89YSdpQWJUPxdALJDoj9fy/hWbTbde4bQZ -fDbCfDelcAVXryBr9gE4WxxcBx29XdODAAlQGup/no5UvsMsL21KSdQgp9LpKxMW -Srhz40LyGJQNC0vyMzzNrJTAJMJ1ewRt8cTu/8xxNvCjg5ALPUOZqy+ZD5V4DLNT -jBLi7uVEU6KKht0KKCd2GE0QwJD716QllokpDcS2FAHul/DkocgLc1nwgkgZbPIB -wAeW/Rmx+g9ayCwAx3kjlrgdUy9NDXQloK6TlscyqfK3zf3pvv+vG/6dJuTclxaN -d5ISp36jZamg3t9hinFoZUEm2Cyc6kWlVojhy8Mu0DoOcfhH6uBYjPwdoP6wZZTZ -6NVLPKzEYCPYNZ7Y8ELCujl6xFWRjzzqk+sNOKOCugZHqS1AVNZJsg4dkqXq44AN -Kil8feC6Mu3JONTf6DbwqsLcgVHQ5WDczzdj09SWOO9hVAOOI3AOwyXLS3VPrylx -rbSWeXzsBlHM3YfjNe791RbmpRU3lW3/4dRF6p6HdL6pPKIpmZ0FDrrzOUtXRdQu -W/vDk0cRSD/ZZyzMqytTZx9tBUPMlN/unb8LQq9t/w/2oAivCu/1XmXVX8GpXIcZ -Da/YciQe+alPiQIcBBABCgAGBQJLJTVyAAoJEDF8bfg8dwXPoowQAKvQoxgs7kGR -R1AlxdLUlg+CwyEP2fXUnEdNKTeFUCMVB13jcPQfcHZfUDKwd/wBZFqA5IpyIyoE -GO9o6jnVy080qWTE1Y3bDTRVZYUumt2ZO0l7gPruZ9bu8TuZtXx1H6y9uJ8fIU82 -ha4OseEzduB43AweQkBkUkPmXfbTF0yzU0kEVABH93hn4zFq+E4PTpqF2KAH6+X+ -CuWzNwpE0whflgmir79OqVUpFHXJ94tOK1/Fiepvq3PmUdJdf0o1fiH0rb0EobkH -fe61/DlvUgAqYfenDfsRAbv2SpcVoPSMMLPA47byyZRT76+VKtlsgSFfKelAvB4Y -n29HvxOPC85mdKhSlkQCpYXsLJBJqItXND1g2MhSvRjTsxoWZzi9wQOtWMbaefOU -ZiLblz1diPL86hdf3Yyb2kuRpbVq3U8XKmUJ+F85e0yQ9/qlLKVd2Pfm2oLL+tOu -6W88IFhumcrT9R86AOCS1B7Biz7H5/KpyLEdYpuOeQQqLhVgy82YLc8g5C9SfJhQ -raoraSOuto6HdTxMemSd1MUqDQhMKQixNWKQ+hEs0BB1o7BjFO6KF7KPud6TN3t8 -cUyfrna1OhbpJPnrlNrzdXSPKWh1gCuRI2EaokOeSCviL36nnFkTPeTtrASDAraV -pZ9abN4OYL4JHwK5QpIDW6kQed4GMvHOiQJ+BBABAgBoBQJLDN5oIBxTYW5kZXIg -VGVtbWUgPHNhbmRlckB0ZW1tZS5uZXQ+IhxTYW5kZXIgVGVtbWUgPHNjdGVtbWVA -YXBhY2hlLm9yZz4dHFNhbmRlciBUZW1tZSA8c2FuZGVyQG1lLmNvbT4ACgkQm7hj -sPUbuIrJ+A//XYCi43ISP+krVXnOFbXO61jTloIilYeg1nMMtSZwAJtP6kaBeZVl -DeFiYJFUOiZfJIy4Ull3eMI29EVsi46Porc3/o6lpMvOFcs+zSpqcmoxEPmQtbmR -yLZawC6xmCPO+Hs41MeqPhEq16M4rMZn7KejUu16Ujs54W1Us0H7CXGHI8Ic7/9m -PZB7jHD+iCirYOB/CeZp4xubR9rJYUn/IhdRlMmK59VOh10www7CSSMcW0/7FaZ1 -60D1jS9/Ad5pGT7I8V8KdUVDtXNeEfxlloCuxmt+3lDFL3Ee02mhy656qTxV6B32 -/qYYeg+OU0zP9IKD1SVITzRx6rahzX/vVVFIma8YlkCjvsVZlTZKJ/xz1cuHJeKE -72r1HVoi6ywsCItxVjwrJD4QQJdNPGIjh97gDwkrOBCkYiTia2xNyH1Wchpj64Kh -+fBRoRGxcdoF2ZhyOUzGMdtmtzy7OwrckPtWJeZ5nnM32EzAIakugQq7rSmXBS+J -0/E/KrouejsOWzMMQrHjVS1keuowF6+PJtWyZgzH0fbi8SZ2Ym/yabv5zVb5OTOL -siUCdPA2zAU1jBkE9htIHqIakFYDnfUNbEAmWMYnEtxY8wr4fDgOTIZ84qZN8A+g -qnvkzoc9kN3kVq0WCZw/KNxtKMcJMFij1kg0ISMwmbcmKfH/b9jXgAeJBBwEEAEI -AAYFAkr+G9cACgkQiq+I1thOQa6GvB/8D29GySol2rtkm1MFd4UoJl0h/WV0cVkv -UhH8G5rcwntyjK48nf//hiNKjEY/Uchi1Ai7GJU8klvEYzDm4SVauBEERTxaDQhP -FvKQeKqpAGVaeID3C8puaTHwlOUB+e+yFXVeCxRZswbs+fEP5YvT4JmMuSpu0RDO -oC8Q9cONssqgfTM1uedCVuN2NGnLHRUKAkAH0q+fQTyN4oBZiVuMRTQ2Py0uVOt1 -WV1mtOudmivJ1CxJ+34CokcmUbvnxPnGLxi7HZN1sQgxQqNHFR2N7SjLn4O5NBSj -m+AID5dKOIAnW/Urv8Ek4j+kM3oaxES9+OWZbZWxeoKTIsNtT7Q58XOpuRnD/DtH -P/q9FsOlm4u6NhKyKF7EPeEu4z/WTemoXDF6LHN/8QCDV4cZ7wfC95eIyuh5PT7g -4vsZD7J9tq2jWCZvwWOxGmuX8E9HIqXZgEzcEq+2rOJpCZYtHS1MilzXuhp9ak4L -VmhSAL49d1t/IHwyDvBByB/F3FItiKYf+SAiKNq68cTgwvY/m5hcOJJEfnyr5ho2 -EV5rdwu3HLISnykNUXUizylrBhuql6Hnj42UKd1UdMyAe/uTe0NPYZKwRl3xWxpT -g7yB72jO/mT+rlAsOu8R/EIC9iF2OaGkUY6BV99xEoW7m2KBuAauAmh1Z5H3ZY9/ -D9ubL21XEGyFb0I8IUor+gu5HVk4/LqcI2Fj1DO+83vbTicYsTJrPY4Bb1zhRrje -vwNmZHBshQYoWFUJA3C89OHG+biTn2uKnleKMhvv4ZIr/WoENkyGimfSos9ZTQ3g -/1kKxOCY5yGW61SMmD00JjHIMg7gZjjuI/KKzbGr6kjsA1zMGB9rxIcy434wdauu -VnaD8Ld8kLcuk5myWh8cgjE6XsVG4H2lIBp8FXwHNZv9RWhglV1B1VooYyErxthe -FPMTmSGd0y+cou6tm46H0qclNg6Lg2qshXggkf4ONamE1vmGh/8XI8vX6Y1NQbwL -yFElQx3caaN+04Yxzws/Gh+JpaLNsqR2an7DgwOWmbKuguSkcjNyI77tOsCXmc2j -v3aHJH40enUmRZlcMKL7bI4w6vEOXWULiHEbO0/XBhi0lqtqoMfwh6FkTthEMxhY -6cfZPIb9uO1V5pdHGz3F6p5rRHmNuRgbOik5xDHJ91cavEKZue/1WMaZmGGtz2l7 -eCdFxDqmhW5apOA90JRR+b/8ga+JI9bnynpOrs8tgalsLmXUJRfqQTTAoghEReVS -P8iA3SoL0ovKhD8aeaVoy80IyQZkzMzd4rMNmXhaxBJycrPyT/sWOE23QBqKBZW0 -xZjKrFuLGOf88hD9Wvgj9rNs5lmBZ1dDUjWtGAVdvdN5+NOtBlCi2rQlWWVnb3Ig -S296bG92IDx5ZWdvci5rb3psb3ZAZ21haWwuY29tPohgBBMRAgAgAhsDBgsJCAcD -AgQVAggDBBYCAwECHgECF4AFAlCzcMcACgkQaTQKAvW7Us0kWgCfe3LGW7t+o2Pg -mB4XjmQuhdVMIjMAn0ugRyWGr+J48hkZWoH15r5qBDCGiEYEEBECAAYFAkc7x+kA -CgkQW5aAEOBPmok4+wCggbJpCeaTzQ8cORgx3nvaF52hrmoAn2WJluH7qjuvJ68y -t9kaLuPm/wa2iEYEEBECAAYFAkc81RkACgkQr9WcwWXV45qWYACeN1qluJ4cGMN+ -1vLRSMjmWCGzFKYAnRO/7iuMiM/3CJPQ85mEdlNZJ6MiiEYEEBECAAYFAkc9B40A -CgkQAL5mtIeAIm677gCgnFp8wUVuMss0cgb86rttjL5vbHMAn1kEGh+sANT9Kd+m -ofcGpryQPyFCiEYEEBECAAYFAkc9Cx8ACgkQwT0w2KecbhhHPgCgtQXQrZ7Tbq3w -cDTQWnVIZSIluPkAnAvzwLC4JL7y/5QyhoUoGCT31XYviEYEEBECAAYFAkc9FfAA -CgkQLNaoAyBG0PX0bwCfWGjRnBwSDVTaJzCjBcVXA3KOKdgAnjeg2zn/QpGP8akq -rIYYg727GBQUiEYEEBECAAYFAkc/YXMACgkQOTX6Lm/QXkmLoQCdHkNDnW3yQCSE -m/7AZsq5KAKp5GwAniCHiB/ZXHDpWJw9dlKhUxoh0o1oiEYEEBECAAYFAkdAhJwA -CgkQ1t3wMetR+7qRCACcDpGP2wZcL2DPIDR5LZbEpJZBTz0AnAjTjRjWOtXgsHty -eY7UP2m6ybGNiHEEEBECADEFAkc80KUqHEhlbm5pbmcgU2NobWllZGVoYXVzZW4g -PGhwc0BpbnRlcm1ldGEuZGU+AAoJEDKGTkGchSIrDW8AnRLF3gNu6Qpyz00Wacot -h6fcwANXAJ9Jky/UF/VKNqaa2hE6wsN13rfbCIkBHAQQAQIABgUCRzy63wAKCRAZ -ZYVQwxEGEXrwCACrKhlffitTUkp+mk7XCdZPMBeiGbhd/Xj0V5L/MdhErUE1XI2P -k9JAS8h/I6CjmfAzS71I2eLxUzb7yYb9vn+5ZRTXreQoqYMmPxENbkgi+1C6L1Wx -PgCxI4uZHY3WmAZDyES5rKNaAYT+zAgiH0b/5PUToybBZsKRUo5lADiS6pGOJBXN -BaboQQot5uV3ZDq84A4/okRa/+wt4gxzhUR6E0b5SiUzTkZyfBGV1N7QyLC0Ws35 -UyPo57D7JJYuhkwL3Wal/kUdLcOuul5Eq2EZ6m4FwngOvtMaXvJ8A8FyI0T1ttW6 -n9D9vBRbLINsTI7RrD4Nv7Sdah51VxxshljpiEYEEBECAAYFAkdAlGsACgkQN/aP -9QFa/IpMIQCgyLBVj9zl4fth6W7rTwSKpb6UvxUAoLq0SiiARb1R7GtgnR7eoQx2 -zEgBiEYEEBECAAYFAkdDBRcACgkQsOAY/LO02Ytt5wCfcvC5zL6PYmwzEhZA9NkL -RDx73B8AoI+U7IGaCZ6DdcGuKI+rqBIe5JVPiEYEEBECAAYFAkdDG3AACgkQ7U7v -sGnO6xtUEQCeKDMqBM34QGCzvPnyrNZxYbB8md8An0r1hU0ldenY8AtuRXvGdPGt -TDENiEYEEBECAAYFAkdWq3MACgkQEy5J1OQe3H5NjwCfW8JyfNbz/Chm3wcjCljG -Hy2IsTcAoJXof3FdnHhYVh39HHAltAe6s014iEYEEBECAAYFAkdnnIcACgkQQMKr -HBzhftx7cQCcCqNzs1uy7ph9bzjm9CluyoqTjlwAoJPUbx7MGjJSc1U/97S0cRmY -ODcqiEYEEBECAAYFAkgIpV8ACgkQoWBj7LjOMG5enACeLvCCM639HjYKCXtK9Qjm -PBZgebEAn3Dx6np/KjXT/uMMYa31Y6l8cezNiEYEEBECAAYFAkgToIAACgkQD0UK -JmIQv8BTHgCeK7P55Hu/64pwXyirPRs06lGh6UQAoMF3ulXYzJ/PNqFGSHm7YTz8 -q58uiEYEEBECAAYFAkr8hrYACgkQyceSTlEEfWaXsACglYTSo8g5908jpIw36+e8 -8pYitsYAn2pUJR+lGXzWRDYYlmYUupU1zJtJiEYEExECAAYFAkdBPccACgkQ7bEF -iW+VIti5hQCffUJo0Y8mHOunsflJVIW3gJAYd7wAoIX/ypbPbFvfRrgy47b3h6FO -cvj2iGYEExECACYFAkcc6X8CGwMFCQlmAYAGCwkIBwMCBBUCCAMEFgIDAQIeAQIX -gAAKCRBpNAoC9btSzRUVAJsGGkGTv9wasU3v1KSCnKoGDq21wQCdEfFFDsI5Phz2 -bUYFaKsO5owE+kGIqQQQEQIAaQUCR0OUKCAcU2FuZGVyIFRlbW1lIDxzYW5kZXJA -dGVtbWUubmV0PiIcU2FuZGVyIFRlbW1lIDxzY3RlbW1lQGFwYWNoZS5vcmc+HhxT -YW5kZXIgVGVtbWUgPHNhbmRlckBtYWMuY29tPgAKCRCyvrxAFSkkrxYIAKDaf5Ga -UJYjxcPWB05v5BvopEt70QCg+roXY8nhcOaLYWSW7SlrA1ix8ymJAhwEEAEIAAYF -AkrzYnIACgkQhY/ExPQ4VqOg5g//VGrYeZ5+2y/V0G1Pk8Zwxbp1uquEHYitgHWb -zHSP54kFiD5QnQCui8p7P3j6oW1JVEMOfWaT1QZ3KSRbqh1RLirB7nNmKfq3ybro -7/0c3Rw9lDR6aHAgkdduReV8LSy6zae9Cz3ykYdPEuWF5hCtkc70t2fVSVRC6w1R -pUq30g9L5wUF+2PUW5j3FljBqf+7STOqTDFkLLlnVhlsN5q6K+WPrY8MTZxeapfE -mzGSyN+/T6BXL+WdPkZY/F+Pya48RFLbcjIuznLs2wdkylIi/oQZpUATRE6w0sHy -fZ5pQuuFNRPNmC7WH+wmKGcb9kF2D/QMdYO1cuvkh+uJzzlDtBe86BrNBLM6wnRF -7dffECwzkNFXRp7WLrH25ummxXtHtSe9YZ06fbQeC5jFjE4yMZUzLy5QNUse2/4e -m3MNa3S2LkvdmcpDvoAj0F0vjHYauG5QscE9jCyS9hkYOW/83yoS4/E3/mVQW5Tq -J4C82K+mKpoFwYnsIxdtGduF1fOuQPuxiIbBkj9xE8V/vYR1VkYTOzTkQ+YT/+hU -hF7NBgUo4eqMEoYRk4Sh8UgwZKis/ibpOIjt8XA4R2sM7AsOXmdT5UxMBXnOP9yB -d98e9H/e7VOSnCTSvwMoPktYsDEVqqkpAS6hc9vtT7acxft8GxPwiSn/3PgR2YwL -D1G1zFyJAhwEEAEKAAYFAkr7N4oACgkQNZU5XrPY4boSVA//b2WBz+m9OOPknvkz -laphU9lWkafA0zfBwazviHp+HIKoi2UjuAfkVG7vbt0AMX2RLLS9EHIb/WwBJwYO -wleld7tf58ykMAqdNTyWaP5crHiMTTw9dcK1Q1uujP+i5wgvI0Br424apW62R2mM -1INJ9WNtzrb1Ze5hONsaP2NYop7keRimbpumt1EpH9lIU7wNdwjbVoSrF43FXlvf -Rw/itT0sYSwSIAKuhs8NpmUlRpz+hGr5bqy9GZu6JkTcZH81dz3LcQDBGV5UM+zc -AKLRLoxsu/hkioGCdNy3xAbkE8RpZPwyiwBvzh7awvfAvziHSKPzahxRaKepaPod -dTrz6A38VbwAY7RXoB+fOiCVLpxm5zHUCbDsi248vSfFJg+IHvfVbWDgborU5bHw -8wJC2gkiMEOUryO/Cfqw5Ezxr9Wl0Izw27p6J7LP+T7f6UTBwU1FZeF8WU0WolGi -E77PCVKD+b6hkOtzAYLyLkz+EBhynYg3Ny2aDWLeiwNGhjExFBOl+D1/2rRfshUz -Y+nkviOVsLV80pC3T1MiDk+1WB2/F2cah6XSXtswVPAXMYpiEt2VBH/a0M7bEi+y -n9yNLbuBxfgoRVTZe+OaqncYjuadPR3xUB3Oega8HJju7DaCZHAKzjfGrybt2fMi -tQRp1Ctp24Gcy49HHJDM8pj3JzqJAhwEEAEKAAYFAkslNWMACgkQMXxt+Dx3Bc/g -OhAAoJT6RrqPfSUiY1p/rsR+aBXfTQjp2kxAz4YsWpFZQpcloBO7vAUhcuRYUiA4 -t65KCMC9XpMfaYNRfWBSsg+F0B3xfP6bXUPdLl/xK8rjv627jdFKLMVn/DUPaLj0 -1YFhuUXkYAuNyWNMBD3ZrmQv97DR0jG/VNqgP6PxtRujUM8lON7KthYKLrerESCK -ll0MFPBrL+Fn8COOURx0QVtQPQF1Ho87Y/go2MJ4afuDlXqojr3/Ipkaol2Cbf+L -6rbqZsK4L1tYHygTVorXi2U1oHQpRYP7Id91aZ7svUBm9RC/RagiYf4uR0T4iILR -/mPAELEq0FR4BZLRK/e4J1qdAG4CtxG+nvgZDgh7YBzi5udYeVJnsOkWZcyxkRLm -fchNV4Y9Az4PxfXSFOi2BMyf+wui0pkEmJeaYY9SWkj8x3g2xmttPW86/LWI3i+T -0MffEVH4d0tMZNiDlqSWaGN9uOMEYKYxG8pd97SEdAwub7JQnnod+Qg7YoCMB8gE -X5xuBqcT+A4f+ic3cqTTm41iks6qcDq8eoFeCTuhfEra4xInRJJnCMC4XNvdn/Mj -aTV9bVjR/ansjO3T2Nkkg3Hx0SiB6bFoTx5N+cMnj34mZ/YVeufQ8c35CRT+WOX8 -hB4NFK8ynJgrYUerwdl3B3RxtpIp2RMhzYCJb8kh/1Kez2GJAn4EEAECAGgFAksM -3mggHFNhbmRlciBUZW1tZSA8c2FuZGVyQHRlbW1lLm5ldD4iHFNhbmRlciBUZW1t -ZSA8c2N0ZW1tZUBhcGFjaGUub3JnPh0cU2FuZGVyIFRlbW1lIDxzYW5kZXJAbWUu -Y29tPgAKCRCbuGOw9Ru4isn4D/9dgKLjchI/6StVec4Vtc7rWNOWgiKVh6DWcwy1 -JnAAm0/qRoF5lWUN4WJgkVQ6Jl8kjLhSWXd4wjb0RWyLjo+itzf+jqWky84Vyz7N -KmpyajEQ+ZC1uZHItlrALrGYI874ezjUx6o+ESrXozisxmfsp6NS7XpSOznhbVSz -QfsJcYcjwhzv/2Y9kHuMcP6IKKtg4H8J5mnjG5tH2slhSf8iF1GUyYrn1U6HXTDD -DsJJIxxbT/sVpnXrQPWNL38B3mkZPsjxXwp1RUO1c14R/GWWgK7Ga37eUMUvcR7T -aaHLrnqpPFXoHfb+phh6D45TTM/0goPVJUhPNHHqtqHNf+9VUUiZrxiWQKO+xVmV -Nkon/HPVy4cl4oTvavUdWiLrLCwIi3FWPCskPhBAl008YiOH3uAPCSs4EKRiJOJr -bE3IfVZyGmPrgqH58FGhEbFx2gXZmHI5TMYx22a3PLs7CtyQ+1Yl5nmeczfYTMAh -qS6BCrutKZcFL4nT8T8qui56Ow5bMwxCseNVLWR66jAXr48m1bJmDMfR9uLxJnZi -b/Jpu/nNVvk5M4uyJQJ08DbMBTWMGQT2G0geohqQVgOd9Q1sQCZYxicS3FjzCvh8 -OA5Mhnzipk3wD6Cqe+TOhz2Q3eRWrRYJnD8o3G0oxwkwWKPWSDQhIzCZtyYp8f9v -2NeAB4kEHAQQAQgABgUCSv4b1wAKCRCKr4jW2E5BrsSWH/9oDkhCGlWC+d6crrXK -cM9KpjdCHeoanuuouISDjXoYGivNVocFeBtGEjihBP6dlL4BUukxmmIsG6RnYlzb -xIXTyvJ3AZqsLnG+NIPEpMev/4x8JziEvbk0XQG9R5gksyJCoR1V7B7wXd+PLszn -Gl6pFXCp6IzXlRRWUPfqWhY9JCi1WXbU++jHX+VlYelJFU00bzMJKqB40fS2HICm -3DxZjuyLJrF00BZNslhzNRqdqAPrHbzQwdQfCAi2QWFYiU6Xe8V4YtcYC/H+d9lz -VePWbdvhkrNX4LA2WNYZ0vFeaENL4N2q+kkc7bnk9iTes4rnjZxPQeENuM4YK3fO -Ra0GAsAuXsNtmkRoc0Q/5FxsbXtibwX7alj7a/CFXpNrQqf4IT1bQBfhOv61dbe6 -Ior1IMpqibvTdyDlNxqy/3mw6rsKFhCvu6YcY6i4W/+sNBdpN8ndtDlQ6MMoE7UL -Swjtg3WtdLrFkdUBuJ8mwXwqsggJR3vu4ayVqRP05VNlG0+DECIafsrpBuolNZ6j -s6Nn1g1gCayunFiFjIpL4Tu4c8Ba5n6jtKHWGwGBbD1oCP9rrQdlIHnp4Q2aj5Td -5K3QA4tGeeE+s2H7WQSrwKFYezFF87eC5P1rwcqDeyMx913ncDEhUGb2H7NS2XIK -8Qn7djV8xQe/l74DQjdkQYB88IXdFEbSszROtv/hcc/mIjWXYBWdQKcraJ+vZEoE -hRJYDwii5xUVWz7vVUKuOEIv32il/CXITLZNn676/GxctBIAwcLQsNeVwPvan34Z -I0HaCX/Bn8saaNw+7o0tZfzahiq8C+QV2GAeVyB+W95Smrj82DimNGqpdBth8wKd -9ALr2PkoWdIVOkZGfCSlB/1dX3xGyZ1DYhwgpHlzXH+ZLSIt2z5HiKlX3lhKGxGD -bce4yEMRkvkx9LdVieB6SNWTSkfQafFBbvBeOCdHOa9I3/s+WnWxBqTHGAEUxEzF -SIKlmC5AhhuuthgSbStGU+2O2P3ONZoCPlNrRYom6/v3Bzxa9UBQ6d6qnui2aBGM -HCEiGe2q0vcKQUXm9L8vzCf9iuzsz45KzBzNUtW6xHW0Ky1LjDtT2oH2LiEUKW35 -/iHAkdv5Yyn2skukMjqymLf0tfAsHNIiLqtAhZIVrNOACb7IvTUbiOcjAyDXiCAW -VQX42ld5j8etsHJXck0AzF+/dKIHlVildIkemoCD67wcLo/7GCZZgtRMrTVXFNsy -rW3Tw3zopcmN4Sm+rInyAAsRXuwtF2NbxQnn4m+u6dhsFVCblkSqkA+VGsz+T4kR -hsEsaRUrjInTU9DxKGC6hF7/TesmD9A7Rxulr2oHtoBfKfq9cXX0EnYBK0+lSAUe -WaSktB1ZZWdvciBLb3psb3YgPHllZ29yQGRpbm9tLnJ1PohgBBMRAgAgAhsDBgsJ -CAcDAgQVAggDBBYCAwECHgECF4AFAlCzcM8ACgkQaTQKAvW7Us1/igCfRzTQRiqs -5fpVO1jFXvQpzT9pmi0AnRlrGgPoOIdqM5EKPXkyzkWSzcgIiEYEEBECAAYFAkc7 -x+4ACgkQW5aAEOBPmonL8wCfS5rtAC749vL6FpC+YUBfLJIQeJgAoIYMe7gjxF3i -+zmJJdhnC4bSf20biEYEEBECAAYFAkc9B40ACgkQAL5mtIeAIm6QrACfYUNdfqrs -63mko5/lIlriZyyUgEEAoITeW+CQ0anB1wPDZu4MfH+AOSTriEYEEBECAAYFAkc9 -FfAACgkQLNaoAyBG0PW7pwCdGao21jiEoKBoEYup9X8HayPo9w4AoIpFQuabehJx -aeySgrig5TCglgsDiEYEEBECAAYFAkc9KOgACgkQEYjo3Dq4WYsKqQCggoh1CiIT -Zw14pFY/5GFkgGxJd6MAnA9KmCnJi5MUo1OSzEGlVkSyr0rIiEYEEBECAAYFAkc/ -YXMACgkQOTX6Lm/QXknhFACfdtlRhfz92Z696fqwCiq43966eKkAnR5qnQLxRETQ -LaEzjoQvlV5WPcLeiEYEEBECAAYFAkdAhKYACgkQ1t3wMetR+7q/aQCfd8Js41Xt -YOMSsiDMSbRGeejhawEAnjwMLdiIhV3z88/iEYg0NPtIwb4xiHEEEBECADEFAkc8 -0KUqHEhlbm5pbmcgU2NobWllZGVoYXVzZW4gPGhwc0BpbnRlcm1ldGEuZGU+AAoJ -EDKGTkGchSIrDW8AnRLF3gNu6Qpyz00Wacoth6fcwANXAJ9Jky/UF/VKNqaa2hE6 -wsN13rfbCIkBHAQQAQIABgUCRzy63wAKCRAZZYVQwxEGEf13CACgbMOUvzMV0LWr -9L8dL5+TJrWzukGzn1u0QkiS1pivR9xE0+cQPdSawZ9FkSoYXGm7fLs2z8BNP4Q7 -vT3ZsTpunyEnzY9GRu9850RstY6sN8VorAyWhiyJu9JUe9zEdL5DGbCm2udAajV2 -Asg0hR211CkAf9mkw46YN4KvS+P/oAUseU5bO0u9NrnKHp0WTGfntMhzgl2TMhEi -ijZWWGOOMnzdyFaPve2vuIB3p0mQmdS6eG1O2lf+fVnwhI1tnZi3FMhr6TV17fb1 -r7ya9kdWOpL5s/Uj7E57+dUjixorCX41QDi31cPMLNGisy3eGqFJKS4yySMYSDU6 -afpC2cNaiEYEEBECAAYFAkdAlG4ACgkQN/aP9QFa/IpoEgCg0wCejp7xt8XTqmUd -uqTAgR8mOo0AnR/bKM0/tEoBALIJkkdm3GYijGDciEYEEBECAAYFAkdDG3AACgkQ -7U7vsGnO6xs/cACgnAi8cqIhJtE00J4g9srhXDFUVJQAnjC/kDy2g36oLOtwzzEO -FjTCDjwSiEYEEBECAAYFAkdWq3MACgkQEy5J1OQe3H6SZQCdHoUxaiAD9VxJtZ1j -9Y34L/8+Wm8An1046xZYFH3N7rVYY9zaL5PRjf3diEYEEBECAAYFAkdnnIcACgkQ -QMKrHBzhftwYbgCfbQPf3QIxDwiYjo+QgQid929TDlgAn3P54V1Xgg93mt7TvVzu -YHY6G9ZZiEYEEBECAAYFAkgIpV8ACgkQoWBj7LjOMG4bdwCeJp6pEj/RQqchTKMG -d8YIPYbGvYIAn26PiUKXScFxB4D0BlyQ9LG2rYcriEYEEBECAAYFAkgToIAACgkQ -D0UKJmIQv8BTHgCeK7P55Hu/64pwXyirPRs06lGh6UQAoMF3ulXYzJ/PNqFGSHm7 -YTz8q58uiEYEEBECAAYFAkgToIAACgkQD0UKJmIQv8BXPwCcDLNCzMocXBb63gGA -q81RiUuVuUcAoLRoqK7+ofE8wHExNGdV56tlsgkqiEYEEBECAAYFAkr8hrYACgkQ -yceSTlEEfWbEQgCfdmT1g9iwAP71zMvCl8JV0ZHP55AAnj99S2pvBgAF9Iay0Ac7 -1k422flWiEYEExECAAYFAkdBPccACgkQ7bEFiW+VIth9NwCbBUIhpl1FQue+LThR -KyZfr8LjL0wAoLTW6rcst1NQit4HapOqvjypxaqJiGYEExECACYFAkah6OYCGwMF -CQlmAYAGCwkIBwMCBBUCCAMEFgIDAQIeAQIXgAAKCRBpNAoC9btSzYtHAJ45cKwY -tOEtQLDggb5bfNMu1gB8OACfUAofp3+GRcPD7GMJIBfbdzM+7pKIqQQQEQIAaQUC -R0OUKCAcU2FuZGVyIFRlbW1lIDxzYW5kZXJAdGVtbWUubmV0PiIcU2FuZGVyIFRl -bW1lIDxzY3RlbW1lQGFwYWNoZS5vcmc+HhxTYW5kZXIgVGVtbWUgPHNhbmRlckBt -YWMuY29tPgAKCRCyvrxAFSkkrxYIAKDaf5GaUJYjxcPWB05v5BvopEt70QCg+roX -Y8nhcOaLYWSW7SlrA1ix8ymJAhwEEAEIAAYFAkrzYnIACgkQhY/ExPQ4VqOMUw/9 -EG0BVSF44bFzG5PEFSVThr8ZtGCnuUNirRBHgrB6SVL0bRrlB/sk55kYKe9bCgmG -tjcj5/F1nmboZ8ZGISM8Kzl6Yxghsnk8xH6SEhMFtRutKlxtWac8txgVuiWpJpC2 -87i5/SlCFaGxS9U273pqNurlXMTYPzNsYvBLKuNds86Woe5mN51WnfrOSJcHJOpz -74FIkyT28I10yxpa5iAFSanTbup4SyNQlFUdAw4tkKl40Lz8ijzAnWYeaZHgBTnI -nEynYgBU7abXws4j03MB4m7ZbpbPOqjZhmXRtUXNDuykFlnQV3o0jsOzT45OuCh4 -GOjI/s4GW7ot1rb9+mSB8bwqsAgw0tGdyrcRmXqgThKoDjR3h3YRED2QHUHfT66p -pHj8cPN26FlJSUlCiLaUfo8a94SUOP3Xqy2EyB7337AL+51JG699M0zpTMX2Ym4m -1dp0XdbhST8xGLTN+Acy1LThUx7dP0MlWoy2DIbQjANQx2sc6FvyipL0xax5qE/n -TDUiYeQdfIn+kVtEERUwhiS9/M582h4Zsvde/Cb363ggMoF8sUdD4LSVBjKjRpu2 -zHpuuVCp4hfGAhhfB3FhzRSWRgx7eYAVHGJh9Hba60LlyB+MJ7blsQeXnsEuElBH -agvrH9VyhPLIzDapOrJu9VGhORBV+sdrNCAx1LpIgzaJAhwEEAEKAAYFAkr7N4sA -CgkQNZU5XrPY4bprYw//bf8ZeGLXZBCCxyeQxC7u8CT0BrOOWmHTtxJoH/MHk4tj -Dr5QS9d7UstAcXZ1WKh+K9f/9G8xBYdLPXOOWwLHvsr5UoG8HSccyGjti2XUz/8+ -dU0XfgjfyVEE0+/3qMtilIH8wI/GO+oJoWt4v8pQpRDGLrXFVOUrdYx3JT9UQxRK -sFye5uHzM4C7yjOPEohz2bIxRNZfshyq0QTbCw4StFhziWDQgsKkuCZWJlbAg9pG -YXwiPaZKR7tuNhdavVtJMYqru8cl7tc7G9TAVEggM2gGFtdwTTIBLa8wKQzlfVgf -RHEaDfW9nuRZl2ci39P4ld5z69vN63V5qB76dR+w47G6w8+owuLqeL4RzMl/zI3Z -LCTTjDG6sksxMgQzYiojO8JKvK1IrHyNKJP9n+aEP3g/mMX8X+gRfpprfpjNKzd6 -ILfYqYm3q9h3rLBX9r49c0Ovdh4hjb8nr6BLYAmTqeb8uO2ZowpRafzYo4Ql+SDJ -VaXI3CRqKDTQ/zfbJtj7XvMcwwRa1j+PwsmpMUVLNEY6IXe7inXTxM5UuzIxtBq2 -kEjDgrcZLW/UY+vIN8+cVBdpThqQDaJOvs/RWDRKR9BVZkm1Zwtnhe9MouzQNFaw -Tb99vcdiPPwJbB17YK/ZXNnCgOAd9/I4tG8BCBmqE1iphKAOOgOSN3gBe84mC6+J -AhwEEAEKAAYFAkslNXEACgkQMXxt+Dx3Bc/kWxAAgb/nsHB5FtsJeVbBTdf9ggsb -d5nj4kzUfsesRlfEVluelP4/y6SWOoWZd27jmXLI+7oy7IFZzbM81Xy5E39mWWHu -mVd5k3h/BtHnh3kBoFpdCKJGTGaLTAG12oSd+FUb3BWWPg6cn1L7ZBcYe9aqucge -Y3fXqH4JUsOPP+v96MnjSVDinjirVJmXRPB2Uh0rMYSpq8YFT1VKagx1maiabi6X -4pv5hWN1+YvOtsbAhwd/CGJUo8sgM3B00GhaS+39WeWXkAMXX0maxEqC8wRYIhOV -/8yEwQ4T7MqhTa1SHqoAD4uJjOpfAtChxv7HJNIuXiI/yW5uUOUrxabV7VUM9WYB -cxthJOkqdG1Bu9bDihacJDY8QRugfp5O+eBLKngbTZ/b8UNJ2PmvjinvYT2Eu9rO -wEtm/Y4EtYffa8JyBlwdPc1TDKZUZ9iYCYtcOKJZxkxYpasl0dz29KWbR9RCyiZ6 -XLXcDfcqAIFxCH099t5vtTYIpPRJAY0qcP/NTIgZFXwcwCXndexZVAY3EfxcZijF -VSlZklgx0lcxnCRTyQRw5uMLMA0Tzn32VgwelT5GsYtoO+tgJFjClF4XD1uvTl71 -bI13adZCqDGjtoQTYFWgpP1c4qwMG8LfpfMReGwgBgkLJ/yYYVkzXK5T/aRPV5ec -N07rylZZYSUNlgUw9zKJAn4EEAECAGgFAksM3mggHFNhbmRlciBUZW1tZSA8c2Fu -ZGVyQHRlbW1lLm5ldD4iHFNhbmRlciBUZW1tZSA8c2N0ZW1tZUBhcGFjaGUub3Jn -Ph0cU2FuZGVyIFRlbW1lIDxzYW5kZXJAbWUuY29tPgAKCRCbuGOw9Ru4isn4D/9d -gKLjchI/6StVec4Vtc7rWNOWgiKVh6DWcwy1JnAAm0/qRoF5lWUN4WJgkVQ6Jl8k -jLhSWXd4wjb0RWyLjo+itzf+jqWky84Vyz7NKmpyajEQ+ZC1uZHItlrALrGYI874 -ezjUx6o+ESrXozisxmfsp6NS7XpSOznhbVSzQfsJcYcjwhzv/2Y9kHuMcP6IKKtg -4H8J5mnjG5tH2slhSf8iF1GUyYrn1U6HXTDDDsJJIxxbT/sVpnXrQPWNL38B3mkZ -PsjxXwp1RUO1c14R/GWWgK7Ga37eUMUvcR7TaaHLrnqpPFXoHfb+phh6D45TTM/0 -goPVJUhPNHHqtqHNf+9VUUiZrxiWQKO+xVmVNkon/HPVy4cl4oTvavUdWiLrLCwI -i3FWPCskPhBAl008YiOH3uAPCSs4EKRiJOJrbE3IfVZyGmPrgqH58FGhEbFx2gXZ -mHI5TMYx22a3PLs7CtyQ+1Yl5nmeczfYTMAhqS6BCrutKZcFL4nT8T8qui56Ow5b -MwxCseNVLWR66jAXr48m1bJmDMfR9uLxJnZib/Jpu/nNVvk5M4uyJQJ08DbMBTWM -GQT2G0geohqQVgOd9Q1sQCZYxicS3FjzCvh8OA5Mhnzipk3wD6Cqe+TOhz2Q3eRW -rRYJnD8o3G0oxwkwWKPWSDQhIzCZtyYp8f9v2NeAB4kEHAQQAQgABgUCSv4b1wAK -CRCKr4jW2E5BrmKCH/4q0o88i+g59u+Fj6dg83l8PBdRqTepFhQveT9XxINcWpTb -bQB7R0GdrdJukuyehz4yU/pPSRizzHBWGneDLEx2dMVzDOCGyfacpwT0FB+Je9Xj -E+hfyytvwWF+Gz7hrQ1Rkr4d1RGoLOnBJb+EIsty88XjCO7rBpE344DQEDIb4dIo -0+EGf3131JXyIJLSKuVD58X6vFiF6bfr4KXAfL2z5vzm/UMhBf9jKHgKgqbNrqYG -O4Natw2hTRRovHKI/7AxRvXE8JoqQK0kldrxTlp1ht6hg/DrIwznc6FHIh/yzEo5 -4ulm19PNLwfwVnfB2mT+TcPDX6/ISNaPQIzXRY29G/oGzm0X3Y9R5u3LF1kf0nte -OOeMnlEx7zJvBT1lIRLKJBs1lUMwgMhCUGYLbEgxd6xj0Coo+Qizko5xzHewpjeB -Hh7Swrq2Nw6wkP4RIfiRVILtSlZ79x7JF9x3ioBcdBalY5H91sRD6PUtu1N86FjK -7ZbkB/fW+5rUnM5ZrUXaRByCMUunYMTM6e0jNkaub3DLg80mYN/2uSbIVLrqclpv -fDoUvwO5ePUsevg/FANtNjr6tO85PXl1XfastF9FlLe8niOIzQ6unPvCecuONPN7 -lvUv7ZdvloUzAxBNeDBSVCbFiAmZVq8+2z5/gO6AWD6Mor53IT9W1T4gOpu0n4U7 -8Ih/Op/HP42ctjhw80505VjiMesIVolrRF201aqrnQdp5nxaUNhWN6LtMUoanPbZ -0YPBHO3wpmI1eV3JME0szThMpvTQtsVQ6je8g9JtICrk2Tr7QDc9CvZojTpWQfXz -+c2K4nudmAsytWg1RSUOzrL/EJiyeh8JzuPMMnHSRX5jjR0zBvuy12RuWjXZmllb -hqzCyRYAn+R+v7noF0teKc/72yJtMNX5qVlmHd5TtfWBUdiEdxKR5avuJEvesaIp -L7h4AC9THnVY8NVp/QAvCbK5llHes86e/hDVSIuWyAVHFpfeU0zRT7IqZFlbFFo3 -+gSh6zQZ7ZyoYF1bndQtRDEapmpOIvjfaDjJJVyiH0HuCKuzMOpeXlcNLP2A/uUO -AETMyQzkaR02JwraPPbwpLz/5sR32+wztGBr0WBHy8DfZnQ1Kr8s5DcvIrcMmBXZ -94f59sTZIIHGUiA3+aKL/gtS3tV7GrbAbLq9BmaXC0wJ3SBaGYMlvC+7151Vp7YD -5t+JNyzjrAzIOd+LhFd3Qj0lOdSXyWR++vradOBAfjWbnUqgbA2QFYp+ftqeiVT/ -Zd7+C/Y8ZU4h3CYs5DZOML+Jz7K4uKmFjZ+M6MAvSqHrnv7SomHLQraP2asnG3lE -MQ3J1n2MFYmzbGi36SADsU+Xxqbld5EX5yLD6WHvuQQNBEZ2qJYQEAColB8p5fyU -wbsCLeaX6uSDxG2ShSXxtsKlb77PfNYz//9V0zyrybOLRfZ5DEiFcdyuFUAp8swX -Qm0+62bWws6dpcs1dYkOxYt9JIchxIyLuK3z5Qobsm9F0eBdBoVch73bzmVHF5lG -h0u/9YegTqakSor8jkr0Je65tqxBL/jTBGSTT7T+7OSnMqoT9AP9XDiELqqBhuwK -2W/BLxLIhmhmpD6E1qIwUNzogADMrvLi6N8ol+6M/8OQYp5ZQpimlkl8i2tATD52 -bpy/37RR4hhTNKTpU4J/MeEEggsmmpQdfW1Gl/8u0QoW3p6kpSEwDaPbwjwhMjVD -8FOCSfc4GI9vFq307QosudNVmoElZ0OluKiv+oHfYM7FdAKpwOA1K4By2nP8Sd49 -lzRtCyghN1nNErsxuMncZ7cDX+YT4qfhfd998GO+teZQ98iM8tLpCozsh2JifA6H -USWCi2L6iiq6+Pz5z/D4l/eA+PES9cirUX3bpZ0rMcOxTdqYcizlYgjOYT9gUJow -EXwrN79by2teQTqgkdmXFEyglm9KWX09JR7F6sEq8UzbHpBJaxA3PUx+sP2qFu3A -CsltcnvY/KSUImE/YLYxR0wFspftC6UeqqRgByTZUxHHS/uO/DV5Oxu8aaNtxURE -bxuDJozgHbYd6B4dXCtOzUM1/onjDtFObwADBQ/7BUDDXIh8RRFDguozqFR29VAl -ncXNp1fWW48jPa7baj/FJayKt4J3CkgjYoQ/ddo6qccRzpTs/ws0vGPNDGFa5GQN -5/0GqWmd46e9vJ/HJQLuc49HQ0ooMGkg0uKMu3BKNo4PJ4mUwKD8uQEh4pXicblJ -pEOYAeUPQhiNkrdFhHrwXMFiMiasmYVeIGZZ2NENfJ1sq8f/0DMryMHpjs5kav6U -CC3I1lkMOxFdvWPe6UoAOZy0PESdyqXOn39j+BFRreRDQhLWO7QECaDH6zj/0f4z -y/yaCBPcdm5ynisi91JV8wNmxAMq9cj16h3YXRlDMvWDBAqv0b7M1ev43aOmdSwf -pxBolLEv+WxNigV768g/m/7RijVH9kjai5zI892M3DcEngLbaVGGBOMTLFtQn3aJ -AjIie6fUVT+fILbzX6j7AquadatTZHHTzT3GnlU+TYgxdTrvcHJQiB3sTxBVeJ21 -hzd2kqiBuUjkB59NYx30zbKx60wAK6ZLnKPSDrVa844s+LXKj5elnEQOFj5BV1Y1 -0Fg8bam2Lcx4EDyk2k3QzuuMqsFfNgJGIc5HiWww5jHw4eiNtxOowWNY0D8ZxnH/ -uiI/7++rWqwb0RNGauvteHtB1LWcWU16QWKefX2ft65pXzVXr2QGWeVHUUd8wEL+ -r9PuSL9rSjXlKBfuis2ISQQYEQIACQIbDAUCULNzJAAKCRBpNAoC9btSzY9XAKCA -0b+mUJ4D7fOjxuCCKhZXFLLfqACgh2XP1ylDq9w/Bdn0/KSV7Nkqq0E= -=x7FB ------END PGP PUBLIC KEY BLOCK----- - - -pub 4096R/3C7705CF 2009-11-05 -uid David Fisher -uid David Fisher -uid David Fisher -sub 4096R/CB372680 2009-11-05 - ------BEGIN PGP PUBLIC KEY BLOCK----- -Version: GnuPG/MacGPG2 v2.0.12 (Darwin) - -mQINBErzNZ0BEADBZhY4T2tcnILY+OaZMfy5AOPx+c81qyhe/fN1ym0kgCD/iCQ2 -ORLE12YY2JWFR16Q9THmQzBX+oqBpDRMlXpGm6X5DuZ21ZCQ2A06QwhpMA9zILpo -z2m4QQ/boiOWgj1ztUFjwd1c+VMvqSF9OLP3rrDiOTaKElLwDWV5DhW2nhronjnO -84EbM/5JB3TeFOhLcoMPMMeUZipSiJdMowAqGIha/q5xW1DrE9u8d7gZ9QzjndEP -EutUszt53NaG0L3mi0CQK+bu6ddWwiUCXBijRLq2TA8rlJptDgTHIQZF2Zbo9001 -ZD+1EvRrRyc9lghnJBmluAT/cyM/2HQUejHkR7hhIon3wp82OgM6sleSIyBLdt7h -tnFR0N+vSUacMnr62m7skZ/MjyW838Otel7IgJpq3eNCm+m+eegRMQDLe28lk/8/ -8flIaQl1LexcSAr3jSRYD67+RdmN9UsE/y+OcOgTclJTBRFV1/ptBXuZeC8HgJJ4 -BuluwmZ7S3jP5wqvqm3cOIhlbkJic3Os6weAcYGLpruDLUhPn2hZfPiOX7B0Y9aC -3X/0EiFGXR+GLx6xgAx0xV17S5SSk/lfsT2e5lAt0/jxd0b3x8E2/MRB9pD2nFx/ -pSpfPkivRkDpo7ioqZdGZa0YNVk6i67jFaehnpq/+PBzdetmJwcHHcr+AwARAQAB -tCVEYXZpZCBGaXNoZXIgPGRmaXNoZXJAam1sYWZmZXJ0eS5jb20+iQI3BBMBCgAh -BQJK8zaGAhsDBQsJCAcDBRUKCQgLBRYCAwEAAh4BAheAAAoJEDF8bfg8dwXPWEwP -/19bXw6m5QzXjS74vdRcYQ2lB3zH+r8zdPSA4P0Kr/Mou9PeXAWzNP7IQvi8nU1N -zIEyQgErj26ARsaNdk9FTevr4e/vU/JsbEit48YKSOIrAxINCohAJ9lwUC4FqqLS -ShvZycXyRpyDDlhbENQg2MFLvZhau33iEVCtPJm6yyGJ8IZnQBb17gI8SkPKHT7b -Syvp6NVxFP+/ML1mvdJA+B307X0x8ZeXGWMphT3zPkPsoFZDU+zvMwPJA63295qQ -oxiUvgJuOQGUhdtdyjPflremYrD2nIx9tHUi5vDSydOIO9O+fsodwWYaNXNaXQUq -XzwkhZhE2ihbzyqA92hNAGy5N25xB6jXmMOwVnei8BdtsRZQIyCqZ9BBqluabnCZ -I7559eKjJtHDrgzMZXZdcu8xjqECslYeFB3wAFH7t2I29X0D8l/fxMGIl1d45w+7 -nJIiz0uCb1H6X5C1ZhWMwWgDCPN2Ij8aGBoY92DgB4LVQeUd7mQquExP3a122BAa -xX5gyKLErO++2VdNrX2XXLi6d0DZoaDZKE8qUdtIcxpGIypvnhaqLcb/PadjWN7r -vvyAXVmNH0JviRRyIzc1HJAcKv2m+2BTz4w7MixpZMjdJWbd+jrEdornnqZkrUwQ -UCVc30XcenaU2DGA7LDX38YAvQ8deha9F+eiCDZLDcl3iQQcBBABCAAGBQJK8zjw -AAoJEIqviNbYTkGuN1If+wT97beyUm5emTdpGt3Ae21wVwA/bXvi0YSDRkKM+Sbz -NspqLQZ9JM9WZb8+hQv2blIJ2v7+P7FwB8cXwWbrDWA8ESBKw0PYSxTkaibuiN7D -8Ys+qNkcWRvCgJBrSkUU9b8t6dqKCDdZjwQxzfjn/Xu7927rJC9O0rpCmMRT78m5 -kLH9ae7OSE6vzILGz1u6jzfw86e8TJHVxMO66XVlZyEcytCBdc11dVlWEFZEDN2T -QSZG1QQlckBKwEKaYSvGYNoQEOPeZADLxSDdi/LuuY2Ag7SHfWkOVZvhURt8iNKD -o4OsKEfVHRxZaMqMFZaX7Jf9b4ACyz6245CdISGFs/xAlst+c9T91DDL7gAUZjpr -Zy9ZMWIECZs+ti9NEskOZmcZWMscCGg7oZkzGCYECPRxttatAZsBQLg6e0kMIQ8s -5sBH7YxlW/TgYDphNmsem2hQkbGeI61BiSjWsVycXNOSZdguWISs7fTzZAA1VhTx -a5yz3TNzxKapykA1i21YZJuSstKzHmW2T3jLTDDG6/O7Zt/yWtZNSV6FfpbYVXC3 -B6GyCQEbLugVMDoRpF+BmbeUVui/KoNaiBgmkNWFVXajQr+36D3friy9jRLWKlX7 -OcKl3uro/fubya07jfwQWMb0ZNBorsOIDsPttLLbRcufNq6uqnmBZMrZ/LhRZ7Xc -sh4DfnYOefWpW9Moc7tKU+RfIzudpUxZnk4oHGWggXwHp75s1rRoI2EyAakiQYz+ -Z6pfKvlXYlGqX3b07+L9MxqFUcChCID6WOenYt2Uqq7dtn1CvybFAgE/ANZE1O7w -ruiJd5RATgY/FfA9NXvKAim1DlUL0FitIo1KiuZyePXjXvvFuK4TTQupRqmKmXxe -c0iiora7Dbn59EQvJ1yHrG6qYZQJiHbv8bXNdGPA+q4Kz3ggDEKovdhW8jL1utdo -URptx/TDmui5CF8sIUxPsOJvhDF0BwSA4Mv5IlTj3vZboHeEORANY6JCdIMZkWDT -GneIdApO08bmfMaakZ2BdUcjWqzlUuiFQUdk92eHwCMVqgR/7yFZKXCpR2eXv9FR -KjoIDNFaahu9EjgXKXz/LamLE2YjuLqdz3At/eQiZLCMyow4DJu4XLveRxqw5MmF -dYEleXk+hfAnEcoAaaU9XaFbQezR9xg3wQgTas2O3WDSAhOYSWC7rQ9V75hujWN+ -Dn5RW5S7PWYfn0oM+TAOBO+W3EZSoqep5EiptX7PcjLd8FpAgn+hoy/urQbLoslH -VjdrXZNzJXEIRDPPPp6s5bMCMO76l1E0nJlabVLHzkbC052fDg0M7MP9iBK3tidi -hd/w+Nj/GOMi6gkRXuthzv8OZQOIsXdf1XZ2w/NBEEO0HkRhdmlkIEZpc2hlciA8 -d2F2ZUBhcGFjaGUub3JnPokCNwQTAQoAIQUCSvM1nQIbAwULCQgHAwUVCgkICwUW -AgMBAAIeAQIXgAAKCRAxfG34PHcFz7mgEACo73C7eGcOpo5dcqacym+Bb/yGOiF8 -cT1pgxeSCw5s21jkhrScqCwRko+j6T40zQa7m8j+BZ2LSawHa+fw8GeUtgReWcyK -B+x5J4iGHBpIMxcDRCCNDlAhg+WhLFCfCEQOrInU0KR1CdUQCfw7q6aycDooCg4j -44z7FuirPzam+lOPicvGozFFaJZaUYO2xtgZu14r2bnd7cbq/mv8TeHMTCSX5O0O -ohehkze6CP8jVP0h1N7zADuOqgj+EXh2Wp13CxYbc31jpsCBMA8XIgF3uN6zL8BM -POaqs2dLOWaJsKFq22AOy1PuWhPMZ35fIBydhs3H3m3lEvI+oLcYheqI6QgChIzS -+NKeOX6VelbWjbFI5kBrJuoRVk/Sf2CZJY8qq9dCAOcSfmxUvr+1udH9cn4JuwjE -XrtVTNdI/mtRdAnQ60fhPUgw09z292oeNcgYnmwBJdNIi+Dj/lDX8i+4eaP+gA7w -3wBbSKwgb2VBQ8Gwpb9QsoWUYQxrpi2Z2XwIkDQeIA91j8sLsj6/RZlPsYgM306k -adkO0t46aq7Vh1hUdgQQI2cEMhn4dN+Nc6J60AbquSVMq5PngP5uxrLbfCwcIC47 -zfTVN8K2XfzzpPC3dCWiMp6mdV1M7w7s7IBxH9r742kBX9NyjrB7eEkIUz5HGt4n -0UD5ZIzRonkRiYkEHAQQAQgABgUCSvM48AAKCRCKr4jW2E5BrhT0H/9w8sW1WLpB -jR0MKbY4zeHP5pATxXog0GtANzV4UWaVA5N8jE1f3GTJzpXfc1mSckKSFXtu7ldS -bud66asoZAwOFr1x9gnynGpSlP5jNqIa7VVEvI3XUH16qPWM0a9lDCUSTPV0pN4L -89eThd8HVVs1ff+HEbpn+SQSch9b/bwGfgfZrzs/uX6FYfkEzkiiFge7jkrhKJpg -Cs5ZzgtYT1BmvXcJWeSJUpu/+wOjNEArWPxtvULBcMi2Miaq3Uw3r+TgpC5xFEhS -s03BczA1E4D0HfESk0z+TOLQHyxhOSscjxnzIBjgGCTpqZ6v+bsZID03bIuI7PJY -C2+EwHjokY46WJm9/DHOZ2nb5f7vWjr2NDHhC+Qfl8/3B+1YBxTmv0dsOaI+OZRY -v1te4QKc0ebWc9yWMuX4BkI0gitxd6VNWVTaXU89p8hSUEEKYzkXZ3VKxBfmr3Sg -c84kQEAtpzmvFuCdFky7SB8Ju859wfUvuP+IkYBmY2bJdDuDryO391xebduGeib7 -YCe4Q+yei6fWWHRDh/PWZ0+WazRmfirvaiD+RU5rFUrXzpiVz2Ir9E6azkFAaISi -DxGOKBge+0CTFK8wxyMMytZLLdGAntw7yHbyd0ziWzbdIoWwclCsOeW+eqFtN/fk -LcIjLS+e9Pm2RJUsCKv/0Cwf7F7GH93nDUhKTN19j3gq7BfDnHV1pPh4gJKPa14Z -f1dwSpZj4gN53derP4JKZLmUkFA2kEVmjQhWsTZ+5uup6I8o+x6tmhEdlhk+2IVL -rNUdLnHmeFZzzNogvMK0rcaIdEYCAXES0bu+tY/ib01bvqgQyzMk5Go0HKtFwpNt -mQ2mrrGUqe/QAhWVVfE+JJxPcC57HiwuaREN53/vccndHi8CfsB6tqlfjsCImvIC -0aaE7ThXLJTiBrvoidgpc23sCeC1KjQj1qFyzEmsfAmtyTsxei7mprfY754o6c0l -PXs59ZfiJ/jOzEzP8abNmq9JYQ4P7f/vwKAtbvxS4Zodi4OW/ZatUXzOUm8hWHml -Yo+sOr5F9Bfrqp+tTqRxMGgh6C9vwTW2bqI6RnQ6KaDMxkknyPODZ/oZRc2awswC -DKkHt0fpfijN+s9w+ppGPebGtol69RW88rT1XcKh7uDigZuMaaoXohnMrIB1lHp8 -1/RMog+6whzWN4rZLn9Jbj7rulX0eS9S/xW/3Ug3OLafdVaNpQIbgm43/qDPgC9v -2n+Vt3BLtMzxw/KEWiIi1bew84sh/5RSJXI3lapZfVz2uUIRnuuDrr3sYJvmw16o -wq9Og5mnZNPzyOwvbgj5v0eZhmQFC4493FF7B/FRMi2u8adZN3PxqIuaPjQO3bJv -kfwh4c6oX/ustCREYXZpZCBGaXNoZXIgPGRhdmUyd2F2ZUBjb21jYXN0Lm5ldD6J -AjcEEwEKACEFAkrzNsECGwMFCwkIBwMFFQoJCAsFFgIDAQACHgECF4AACgkQMXxt -+Dx3Bc+IPA/+K4Wu2chy+544orDFxfb50Yej8u3fCGHG/Di3fltpxWpN/QRbBwzH -wkRhhp5yH7p3cVMeJnhWPfP5ZROOU8TYdCF2M9vApF8cNoOCeLt941O7dj0rE9gI -hqDOVEXZ0rfG/AM7s3MHNFoTMWoeBJdneH8W06NOkP89ABwf/Rf41khpgsDBw+9s -3v0/CW1c1ZdY5WKbjIoUBFq4V1JQfwyTArdMsOsGwONmIYGLcA6h1FEi93bCpRnD -crDG2aFN9OHguHWMUb7ru4bpKERjUzpLhX8fPE9xEXjIegM9c2t9dkTcWgQg7EcK -kaFjn7FqNah/26b6PnHOAQi9TdLPlrPVxoTpCrS2bGAtL6AtsSTqEtc5eDHA+gHo -Mdtut9Yw8FW0rVyDllXM1EyWNGBfPCpFFNDCW2QTrmS0dXTN+S7N5ZsZI5lpqQ2Q -4DHNyVQt614RPPuC3Z3xtZdu9i5+npHGstXRYc70zVwxOR+oqzeTlmOsq6C8OdIp -qXHxKjZgYXFcnhdzEolzwWQUAVPw7pCXQ0zAnpY84XTJ0/QYLuJdji6FNpzUlTmG -Uf1lIRzC4TKU2HIAZN+YJszG7qjAbVmJVWB3ZvvcfoxDqGiY9oCsJ5H9K7GOhXGU -HKrHyJQAbLuo0HABWnZ/3t04gUyXjAYEF3RVwimw/TNDAy5IkjUQhVmJBBwEEAEI -AAYFAkrzOPAACgkQiq+I1thOQa5kiyAAs9bnjt2z0pAW0id16P5XyiJURSRYqeuA -4ayI2Ohib8/hP+7ukefiMba29VNMAUzjDqdVklBlxyJoDGRg5WYrSc5VQpZbloSo -IzaGYeuEijRcyOD7f5M3bZuquoYDG3dViPp808w7fc74zIVKAFKsOh3zgv0UKcuJ -KwycZL7WZY87e454++P4A7s2sfhrWQk/NFsHxDGpIk7vX2KHkcGiNsVj7W0DCdHg -WZtJfcQqJwOlQEHJqKQ/m7qayFzX7VFNi5UTs0fFfBTx5ydbOfATt1Kqvc1qmHlF -VGoRFmg7wqa+ERBuwis9LnwckHsejx1pYmywLT3hjoXCtl9EaT/CEiLIatv9Q/op -23ZJ1nlqY4WEYW7eWA1pgrtaKCbHp5b421ig73oOZcyyfFCMsNN30OSlyXG6tmiz -XZB2A/U99Ev8+Sgb6yh0CyO2VslZtdMUmsOoJEiKu+H9PyoYLv+1VHFSDn38qNQL -tQOna+I1CKEBtfopw7niHMlKophmHoVYFHoQ1RYhA4RLR+3tdAFszVM6/sJejW20 -41s0am8Ssddl8lnHbXxldnPNO7XMKQWP+8NIxoGfLcNjBQlkQVm141z9YsQmMG5Q -Bg3C4R3IhXGZ3R0PmsGqCpWrZCaFdmRzfRbisB8HbSU2RX2W7I2Dx2DAjDs1nzQ3 -RYQlnTMneJhwERBs13zbTvu1stCrUl5AvoPiH1B/t7JQukV1aTj/7+EXoipCAYYj -BvvJqczVKIuIqH/HW7vZvml+4mefkXwrRqG6fshE1vp1eK99cW0edUjND72ftLnn -wnu8Hs8ps/G8krDa9yjHEcWTuaZE3SZjoBuFjlD8q8VdSqSwMRXjaYQoVJOE06UL -tMXfy5AG9mQnZzzeHXP+h/RHGgldyFQ6uzHzfs85rqubk0ZMo7PK6iQbEXmpqkLa -xpLrc8C+UTt1R9MsLY5SLX/fcvq+AfMIqCE4VYCtmEfQcCm6u2oAhRfzJzXISv7z -cZbUJuP6CjQlICqEyj1RmUFbg7SkUrW6Kszy+/MZ11pw3yQkfL2su+5Z/UcRDrKS -n2gXZa4tv7ygiA4JPpZWyhroReWySb6sSPIbq2EpyLhb63ukFPGxTBKSg3sv3w3V -EYG82Ss054MNf4D9S1MtSjHWL6RTGId0Ln90woj/N504h9oCIUMM0vVlIj/c+TaB -mTg1at96NTYpC5oCGnI9J/G0DEYPrKipH4alJ+F8CosVdLscMSpRHnjOXMs7Rcpo -tdxQR8csDzhdPQlfM/JlMp/PVEgGoTv0El8QQWIUp7dGC33i9U6PUUiyDXq9Gm+Z -0/nH2/tz58JTIscdAEF1VlikrgLT4AuP0vJlWzRKKmR+zpHgCeFon7kCDQRK8zWd -ARAAn/mG90gdj8EjngWqmBu0/hYfL5kdTkFHeeY3OKReQkaOxhxpdxrDP2kepVkp -B57QQ3ul2CNu/Zv6hy1MCU0ML0Qh1av/VSWlEbRfPBTgbTwu32WXDnewNloEoTvy -Oz5ZShhgFyo97ULOeh9HpjVPSqRh6nX8DWlSiVDgpPlOmU3nNBck0UD0AEj/pf57 -ANtvDO0EEB7Bp4CmSbR6YNSaTOm5AvlpR7pBjYmBBbtAn5ovpN868vGWoquOIhMy -9z9CW5LPDKbn6Ci5mHXGgmlJV7OEQIeqJ6hkh2zsqqxVRzo5Nc6YShcW/pqX80Kx -5mLOOstIxjx15YUc088roBtnSNnDu8/oynJv9W85HBzBG+P7zuma+WthGN2i2LyV -VZaA9VUEQcFLtYiv65GSMUIMj5H9HsjOJJ6kw+x19MFWbHVBSSSroZ9iZduhRXTE -fmnNu1rtYPOrZub9Eh5SOm18h88k/9uPmnj/8kDsPTCouuNLHWl4yFWcV5D5u3Vy -lQg0A6wXxDazahvQu40B9z52pQXq33m4OZQ18F7Z8l7stw8zRKVakPp1BrngghsC -iR7HCAkh1FA7IWSGvDD6/YOOgIBfMOQC2DnG9WhTpR0m0XpfQdDwqN9n/lx2tj3Z -grT1fJ2pK8VUwWNPvjGbtCou3baVZiIUKVE1ciQSucHTst0AEQEAAYkCHwQYAQoA -CQUCSvM1nQIbDAAKCRAxfG34PHcFz3e2D/47+jDJ8OW4WH+wIzs4c1SKJTrcOcgy -MlTbOu+FV9iOuxpnTXaVgzRRhBg2JkZxpkg1aDAzJEqf6XIzCEeanNmYzUJ+cCc+ -YItpQvgAmlGH929XBSJ9g1ErS20sTbExDzJQuxtdjoVPa2ocECVsEhAuW7n/JUfZ -FRuQtx8San37CEze+nySB5uAfFt5AQ7ZxK3W/57xE/DMRLxvyjwVgMPOPpkZ7P3Z -KphNZ9VjPJjtgZE73fIOJ9D2VZzVlmyCeMASXp46UHIzjLcHSXvpXY/9CcP4wAy4 -fBHcw4liNzf9KP4sX7VhlAxs/7rTMN8uOBTmf3rpnMQ67m3hL//4rrPIUQUreVXq -iAgH3V0ZkkhgYUdyrv1G1qfrnlMnRB3xIJQLo4fAoy1+fjSV8Rl+pLjB4iB01eLB -4su8sdC1obzy5wxjwNOKwYAOiAn9BuO3HzB4X4Cou7Lb2mCu7WF9pei5f+rpn69P -cqdkk1qkXTmmZJU3VFS8+ZPthLIKvhiAJWKoOd7iidNgw9kfzkWKDID34qCz3gZ5 -1u4N0B1/a89+tinnZd6JarDjK2F2yILxeafPHZ4iEhAGpjhJ+krBtmmD9RsPgmPq -jtjkQxGn9HwWZPKxNPu8wwpL/ewSamc3No3lW8qoauaoc/aH+3SJ9W2Q2go+2ZYg -ThwM1UqUgNRjNg== -=nttW ------END PGP PUBLIC KEY BLOCK----- - - -pub 1024D/D1F99590 2006-09-08 -uid Josh Micich (Software engineer) -uid Josh Micich (POI Contributor) -uid Josh Micich (Australian software engineer) -uid Josh Micich (Australian software engineer) -sub 2048g/5979F244 2006-09-08 - ------BEGIN PGP PUBLIC KEY BLOCK----- -Version: GnuPG v1.4.9 (GNU/Linux) - -mQGiBEUB+2cRBACXiwHbncLW3UfHBiKXjisziEeDOxEqNAe7JWkuaN6YEsI6MWrc -iCov5fegHMD51wmSukjty/ic9c0c6bZudaRRarIMQ618vRYrjAIO0RUPawA6nGfw -x/oLnuRaClgFL56YexkynC7qLZWGlgttbOuNIKkg4y0nDpC7mAw4lYKS/wCg1o7U -R7MEk3Rkk6cDaSAFpCt/i0sD/Ayf7LG5sj8TkXDm5sQNclNOBkJ2KFXzv1zFZ+mb -a5769Vd6nu+cj0UjRsYtq1hI0uXWiz+0twJ7XjAmAVNU4KEbmKixQkTwoN5PlDa1 -GXVfbQisCGzfx5vA4VRVGYt6zoCWWzOxxWBD3S+Z4itQrY+jgMvgqa89qhpHo0qw -CxrtA/42JoEK/zXb5qgbsrg3OebuT2NK2lDBmFRbbuHF73VhLSnTy253/ppsgvCY -eNBwC9QuoRYOWTQV3q+oI8w/enEKegN6QritBDZXw7aKb+QFt0+OZ292tLGqxkBu -rppVqYdcUHLiOI6PWZMkMwqwIiODlI36+T8c+yf7gRkseHLZH7QvSm9zaCBNaWNp -Y2ggKFBPSSBDb250cmlidXRvcikgPGpvc2hAYXBhY2hlLm9yZz6IYAQTEQIAIAUC -SBYNwAIbAwYLCQgHAwIEFQIIAwQWAgMBAh4BAheAAAoJEIYLvubR+ZWQaWgAnRSN -H8v5hqExDJ9pGzAcxu2g2xtPAJ9JlcazJqcWKvlPt2iP5VT4Ht8hookCfgQQAQIA -aAUCSwzeZyAcU2FuZGVyIFRlbW1lIDxzYW5kZXJAdGVtbWUubmV0PiIcU2FuZGVy -IFRlbW1lIDxzY3RlbW1lQGFwYWNoZS5vcmc+HRxTYW5kZXIgVGVtbWUgPHNhbmRl -ckBtZS5jb20+AAoJEJu4Y7D1G7iKnSsQAKhxZFxWXRjGRIrQBL1lxPiMJkE2IsYr -Z84CvdhzP/SyJTUpjvk4tdruxFtGxgiO7VITFnHR0KMi70ErUxcvIqYBYtOHDabp -Iic501Ix/Q9MOg0BmPpco2i2m8ZzUXa+KGC6NLht3m5r6bG6qKlfvodzZnbOr7nV -V6G5tVHaZQGEfOvMgUQf2z2q/5+XkiDDmJiaatfYrrA5H21tSs74GOCEwxHCZVqp -Y6w61APYWG7t0cMpfcXSJjsn/VCjviXV3DIVkQZU8uf+U6wiJNCMgaVPSm0gIHZM -qNndzGMYycfzUQp1/wPZxFQLylx39XsNC6HHUdgwtl6OZz0klLtp40tJyBgKz6Q0 -ij28NNuX5fLturfCDk+GB9kT4PNzNixgEW0aHF2pfhfW5KPlOYAn787t80MorXxA -8nEi8fty66HFaRwwAuNPJjxMMOwgfpZMh3IkoFtCLzX81A4/8ISYftPGvA+ka15T -h/KpuX2vpUKR1EsKHy/nAaUFRG2aDd0AjkwmC817Oma4urirYme1UchG50A/WKRT -BEm9YpFxoEvfc0fecy8KT2zkHFH5+mvGPyk6goOqgoqyVjuNhka+sco5yDKyNLDo -HaIKLyaGMlYFmLTN7fmBSBj4WTWcHtQBPcuQNLuszqu/Ib49+bAdJK0Ac6y7osYF -veclSVx9rj01iQQcBBABCAAGBQJLFDYfAAoJEIqviNbYTkGuD6If/3Zin5nJwrf6 -EbYJfJiGaLZPBxDaBIriiR0Xa8qy7bsNAoOlLmyhX6SK3i/ZNcr1qvQvArPnul5+ -AtdWTH/eRq2je13qNHQzy006pUkvdQ4t4MhnS1faUUvBlwHTyNYu1uiKcGOGX7Y6 -XfsZIpH7ReMLRc7jasVsOJysNBToXasIpTz8Rg0/vKMfe7RinvsOFgyvk7eoM5LV -s6D/z1gKTmTrs5t/j0EEYYLbCeAT7eHYGCtjM9SVQG9cVCXybqpQSs/mgUopXGFk -qhfFvIstvIh8FmXQJ/riWmWt8jh5xSkAH86SM/SmWbJ/8rmiOhTB8xwT74g+CJAl -8kqSgoWu2QcQ7Dmm5+fRvbbf5Tkk2fcyrBChMO+MWFBvVaaZZRefB38d+ilP5cTE -xxlmDN7s0EKIaObo5RLtlmX+DG8WUNNty228R4dMuQ6IyXf9GFjujr7o2Hi/kqBH -8CLH1dFt4fpUe92hMlvv48mqolIu+s0LOEf1u2likatd9x6IDIaR6SJFINTb5tzF -QR4Hm6/smvsY9u3ArJUEPG46giA0lOB4KUif1zsrRDGTl3AZALlXcUOY9Zxk/LVe -PIFjrly9VhnXJd9kQRp9QRY+4Ogwe2XGLwVqkgmr0udCUpV7AAKrwSajGbMMNLZW -+j/7fYwedrxubO4Cd24EaP5qZGfhYJmzIVjbR6z3UpH7k9CUjiCQdbRKHMoFr+Yr -xBf2sRUwtdhR3/hR5CaVYIWT9/cEGtQI2WUeOLJelPYUPNq1JOrlTXsUvy6Zu+Z5 -onokpqizBJK9QQVSjpuN7TYBlOPeFVd/lJMWgEOqiPDJQLqX0IkOpqQAEWcVINwE -Ng4cqaCaXmt5398glk8j2waJuJcfzSJUFmZ7E0ItKrKprnw6QoX1OmU5s4nYsqoc -3d29SEqiGkgwY7TLB3kZGvPF1LGAqe51keSixxY2MrQw/pzlU36wdpVJXe7qpgNn -bbqv6Tw/SEa2ixWsQFUYpt+U48RPdHpdkpUmPu8yimZOOKZ/ghUmmo5HVtSPQiRm -Ry54khdi66ZWXz7rJ5GQmJWimigKiV5ix2wQNNeoclcO7jhI8mzLlGC4pVrME4F2 -azEbkL85lubNJvFWVIt+K+ngBeQmjfO8IYmENowtAZT0HsUdjot60Y2EhH/U7GoD -IEhysjNIXQSTsGk9/Gk8wiAnTfO6hBu2qM9snvvODI9fOZxGCxmQ5tODDdB/LiQI -cUBHaOcQs+dp70sh/E6v5pWH2FGAoPwx8fG2QctVn6fsT6yg2sqJ2dzNCTsJUSnt -fpfcqD7Tiq6frec6Nmj/zV+YUFOoIp7ppWMM7PRA1HvcY8g/B0KJsyfb412/UC74 -NDido3J0t560NUpvc2ggTWljaWNoIChTb2Z0d2FyZSBlbmdpbmVlcikgPGpvc2hA -Z2lsZGVkdHJlZS5jb20+iGAEExECACAFAkgWDtMCGwMGCwkIBwMCBBUCCAMEFgID -AQIeAQIXgAAKCRCGC77m0fmVkHvRAJwPCMlYxFQUTXFNR21qRQnBu/c7zQCfTtLK -FpwL2KCgeO/3J1UWZZx+1CqJAn4EEAECAGgFAksM3mcgHFNhbmRlciBUZW1tZSA8 -c2FuZGVyQHRlbW1lLm5ldD4iHFNhbmRlciBUZW1tZSA8c2N0ZW1tZUBhcGFjaGUu -b3JnPh0cU2FuZGVyIFRlbW1lIDxzYW5kZXJAbWUuY29tPgAKCRCbuGOw9Ru4ip0r -EACocWRcVl0YxkSK0AS9ZcT4jCZBNiLGK2fOAr3Ycz/0siU1KY75OLXa7sRbRsYI -ju1SExZx0dCjIu9BK1MXLyKmAWLThw2m6SInOdNSMf0PTDoNAZj6XKNotpvGc1F2 -vihgujS4bd5ua+mxuqipX76Hc2Z2zq+51VehubVR2mUBhHzrzIFEH9s9qv+fl5Ig -w5iYmmrX2K6wOR9tbUrO+BjghMMRwmVaqWOsOtQD2Fhu7dHDKX3F0iY7J/1Qo74l -1dwyFZEGVPLn/lOsIiTQjIGlT0ptICB2TKjZ3cxjGMnH81EKdf8D2cRUC8pcd/V7 -DQuhx1HYMLZejmc9JJS7aeNLScgYCs+kNIo9vDTbl+Xy7bq3wg5PhgfZE+DzczYs -YBFtGhxdqX4X1uSj5TmAJ+/O7fNDKK18QPJxIvH7cuuhxWkcMALjTyY8TDDsIH6W -TIdyJKBbQi81/NQOP/CEmH7TxrwPpGteU4fyqbl9r6VCkdRLCh8v5wGlBURtmg3d -AI5MJgvNezpmuLq4q2JntVHIRudAP1ikUwRJvWKRcaBL33NH3nMvCk9s5BxR+fpr -xj8pOoKDqoKKslY7jYZGvrHKOcgysjSw6B2iCi8mhjJWBZi0ze35gUgY+Fk1nB7U -AT3LkDS7rM6rvyG+PfmwHSStAHOsu6LGBb3nJUlcfa49NYkEHAQQAQgABgUCSxQ2 -HwAKCRCKr4jW2E5BrnZbH/9WDwkyzVozA6uCQpqY8a3oqibtLnJgYQYetviHx7YS -+2rWfXrBP4opLIGcI8twdtuvCanxdoH5eyFzlirYmXAglgB7DTJlweSnUJEQpXIc -VAcrRqg5yY01qxPOfMA/1oR4dEPHg1rk6dHWjMgXXWRZ8v3lzuvKXxdSWD3ktQp2 -BYV/RYdcsLM+Y9mR8d50di41HwucoV+RY6LcaeddLIzMrcLoxLNqbS6DTlQL5m2z -LSJvok9W1wtt2qSxWAFgHZjGwm68MukPumwEm7+XafQLDka9/EihirLn9trcqDj1 -KlLqzxkj/ptTxZowEpBpOdpdWyK7Zk4RNhPdqbdXECkWpGqvddQXTCGs/65JdmiB -3dotYr9n6gHotxh3GUi2pHNdw44nCwlmpyRYYgOTpyyD2lSP5Zak0NiPahmhPf4p -mmtXIrhAHi+tlM8yp6mbo5mhcbK3+1RQZ/t47IOCpFRkZoZCYeFB6CJRnpoR8QNt -fl0VoL0+gAbl1orvLf/d0C/5EqAFdT+7ZyIb/hAM2epKRgV2GaJcIMO3DC3acJfK -9+jMtWZ0+5bZ7Ld2Cr6vlfaHrew6L7GKHVZBwsqbOeMFfKU+RuAw6KNIHyALzPDx -cmSWRDcjNmsnEBP03JYT+/P5Cl3oG7i/GIiBKJkqApyaKAkclCKXCRnIc9/9E84j -EpNcqVb18O+irr+NTUmgd2vIBk9xhxcPrys0d7DAoVKkJHq7YQxfthwA23cfEZSw -w8bZIoTcqE9wjWlZDH0J8OBtsXHKD+vnbFSm4015XxqfUlFyq5hBPMGP9EwyjM/9 -LepHzOT8UStDtY6oaSqU/P9+GZq3l/sza9IRcSZmzBYY0ixEZ5sCPMBsZjiQltBn -k0NzY4k1uZfg1v0WpS/tpSlFtgB6bSCtUyU31f7Chy+jjXM0GmMfvnRX6d1yqA2I -PKsvLVBMBLbZ49lXLt12cUgmej9QALMRWRbcIO+MS3LBf4FjhE3KfVNMFdW4Ltp4 -yqsBWPLPVwqixuH5GckYe2O7Ewk59BeplrXiavgsyK4I2BAB1O7Vt1JrChjYQRVd -YGtP3BCkCT2A0WmyHjNBGhyjD/aCOpGqfq8Ain0z4pTF0Sm6RBIrBd0n1xal7nFH -LfFKfDRkV+qLCoQ7kueJYwNv1TPIeCRd2IGd2UfJPjoO0uJBPRA7l+jCZrS6OXkd -VOWJ/cX89Au4E+VSuQOkTz2dnEzmz5Y1RgzkW69DaxF85Id5aBVLZtwpW5ZAPApd -ZOzUkubFWl0V8hRzvCueG31KhQX4x2mXY/Hvb0ep7o7purDpBtAhU1ECLz/EYS3Q -4952rUy7rDBV9H7qVvGgu/6xWFmUiUnysGUSZ4jTib0jtEJKb3NoIE1pY2ljaCAo -QXVzdHJhbGlhbiBzb2Z0d2FyZSBlbmdpbmVlcikgPGpvc2gubWljaWNoQGdtYWls -LmNvbT6IYAQTEQIAIAUCSBYFAgIbAwYLCQgHAwIEFQIIAwQWAgMBAh4BAheAAAoJ -EIYLvubR+ZWQedYAn1TlCzBv16k6YxFD6UPjKfG9p1qBAKDN7OCk8bZvxamBpfPF -htCxBn5NgokCfgQQAQIAaAUCSwzeZyAcU2FuZGVyIFRlbW1lIDxzYW5kZXJAdGVt -bWUubmV0PiIcU2FuZGVyIFRlbW1lIDxzY3RlbW1lQGFwYWNoZS5vcmc+HRxTYW5k -ZXIgVGVtbWUgPHNhbmRlckBtZS5jb20+AAoJEJu4Y7D1G7iKnSsQAKhxZFxWXRjG -RIrQBL1lxPiMJkE2IsYrZ84CvdhzP/SyJTUpjvk4tdruxFtGxgiO7VITFnHR0KMi -70ErUxcvIqYBYtOHDabpIic501Ix/Q9MOg0BmPpco2i2m8ZzUXa+KGC6NLht3m5r -6bG6qKlfvodzZnbOr7nVV6G5tVHaZQGEfOvMgUQf2z2q/5+XkiDDmJiaatfYrrA5 -H21tSs74GOCEwxHCZVqpY6w61APYWG7t0cMpfcXSJjsn/VCjviXV3DIVkQZU8uf+ -U6wiJNCMgaVPSm0gIHZMqNndzGMYycfzUQp1/wPZxFQLylx39XsNC6HHUdgwtl6O -Zz0klLtp40tJyBgKz6Q0ij28NNuX5fLturfCDk+GB9kT4PNzNixgEW0aHF2pfhfW -5KPlOYAn787t80MorXxA8nEi8fty66HFaRwwAuNPJjxMMOwgfpZMh3IkoFtCLzX8 -1A4/8ISYftPGvA+ka15Th/KpuX2vpUKR1EsKHy/nAaUFRG2aDd0AjkwmC817Oma4 -urirYme1UchG50A/WKRTBEm9YpFxoEvfc0fecy8KT2zkHFH5+mvGPyk6goOqgoqy -VjuNhka+sco5yDKyNLDoHaIKLyaGMlYFmLTN7fmBSBj4WTWcHtQBPcuQNLuszqu/ -Ib49+bAdJK0Ac6y7osYFveclSVx9rj01iQQcBBABCAAGBQJLFDYfAAoJEIqviNbY -TkGuB9UgAJKvaMoAGjiHObVeIXnsohpQIjKfs0nMVj+uItqVQqdPKdeko6xA9NSN -O47PuiCDOP99b2Sinzd0l7T2SF6O52uymVNJbYOqdYkTaqAMXY98Koq8EKJhThXz -naHrAZP1vgtSWUIsAaiHe6yOhdyNNkwzjneYLRgnICvSBEpJiXPg5FYujIKXKrxM -i1meQ7UbXxR0COj5LHVxJlI5ZqcVlAGdAkzr7TXEnDsWa5ToHz+X60Yt92GtwhBl -gcgbX5QpgX15hHuIMrTJbrrvBuphMI3xdu4FRxJKJsNDkc4VTrroDGA7aqlCAsOa -4bCpWBUy5TEZg0iGy86bg6lAkV9hvMZjqEU2V4OXuGnmwOQcAunpQw60Fkk1uJEu -+IYyZdkPC2pcHoHa0NONeKbCvgLvjHVgUj7KxXYhE9+pehfg0x09uQ3nPXhY7QJ8 -z2Ru2iVwssHwhKiLUlRcgyv0HTZaPKF7kMcWf48dN8vz+wFxcd2AMxEwuVYtcgeK -nMimTG5KL6fboyT327ylFr1aiJd8fBjbO+lSUqVJN+WHZ+FpeMW7sRSlw0BG5jFc -t0wkAkDjKBwWUQ4YnjgIZGSbD7JRqG7GRz6LrBOqHLmXsb1HTUAEkL2KlFm0ImnN -9C33EseYd8v5QW/iXLtcawC3fAVqQcnqRZEmbua6C/I7hcGD42/Cb1NLmiMdnJ3H -nN7N+eglK7VWsrsnoLUVYIj+8NeStPkP8f0tUbsLVGyT4Lz6I5oUvQpanhYAVrg2 -76poqtPRAHdQt5WA0hyZoibeMHeriZGo6gGkspnQrjYTqyCK07vZH2QwVOxVppLp -N7duWkUTFqWovmRTnL7XMKTkdl5ssZ0whXPcmRLkB1PQz2PVU/c9vcIPsLehGMl+ -6RWldzTb4hMUhx07fScNx7iBAuW14oBXMpuXRKtG+nw+HJmQCRrqHgAVgO10ekTP -qYt72lhPhhMHfWjVU/oO9FflDkMrHEiVHX3MC9z47Es4Junu+EQ7LWA+rHthn0Io -wllvXTX2BcuxRu9y1zlEwPSiS97Jw55ieAKcVz/RpAoDD1eAzQp9+t6W6BIFmrMD -mMToDqMr8hDGXDlL2GNjTXqqyApvEXBZNywg2HknIN65wvUnxDBx0k847xTPpp7e -t/mMJucYQK/ZDCb+DEfukuq+4OA/Sem64Qq7xfGXNJiWheN3mKXrhXeSDLWs0zya -d9yZ9JAVGXvnuWFMPEV0zU/xWbQlwxuo0Bs6ycH+BqeHvicig/VaMbaRAIwWfHNV -8vRHyzDQpRlCBinQUc8gGeWPRyAqQh+uUNGf3D5lVK5QhAE/hzzNB5J2u75doEqJ -mfnFchXQBUcH5QaA11FWLIjEtbsACcW0Qkpvc2ggTWljaWNoIChBdXN0cmFsaWFu -IHNvZnR3YXJlIGVuZ2luZWVyKSA8am9zaF9taWNpY2hAeWFob28uY29tPohgBBMR -AgAgBQJFAftnAhsDBgsJCAcDAgQVAggDBBYCAwECHgECF4AACgkQhgu+5tH5lZAS -bACgzdpXuT9bzU+ogdc1FfUPGo5PgMgAn04+PeVIXHjJNGwMnwcmAqhoQnYaiQJ+ -BBABAgBoBQJLDN5nIBxTYW5kZXIgVGVtbWUgPHNhbmRlckB0ZW1tZS5uZXQ+IhxT -YW5kZXIgVGVtbWUgPHNjdGVtbWVAYXBhY2hlLm9yZz4dHFNhbmRlciBUZW1tZSA8 -c2FuZGVyQG1lLmNvbT4ACgkQm7hjsPUbuIqdKxAAqHFkXFZdGMZEitAEvWXE+Iwm -QTYixitnzgK92HM/9LIlNSmO+Ti12u7EW0bGCI7tUhMWcdHQoyLvQStTFy8ipgFi -04cNpukiJznTUjH9D0w6DQGY+lyjaLabxnNRdr4oYLo0uG3ebmvpsbqoqV++h3Nm -ds6vudVXobm1UdplAYR868yBRB/bPar/n5eSIMOYmJpq19iusDkfbW1KzvgY4ITD -EcJlWqljrDrUA9hYbu3Rwyl9xdImOyf9UKO+JdXcMhWRBlTy5/5TrCIk0IyBpU9K -bSAgdkyo2d3MYxjJx/NRCnX/A9nEVAvKXHf1ew0LocdR2DC2Xo5nPSSUu2njS0nI -GArPpDSKPbw025fl8u26t8IOT4YH2RPg83M2LGARbRocXal+F9bko+U5gCfvzu3z -QyitfEDycSLx+3LrocVpHDAC408mPEww7CB+lkyHciSgW0IvNfzUDj/whJh+08a8 -D6RrXlOH8qm5fa+lQpHUSwofL+cBpQVEbZoN3QCOTCYLzXs6Zri6uKtiZ7VRyEbn -QD9YpFMESb1ikXGgS99zR95zLwpPbOQcUfn6a8Y/KTqCg6qCirJWO42GRr6xyjnI -MrI0sOgdogovJoYyVgWYtM3t+YFIGPhZNZwe1AE9y5A0u6zOq78hvj35sB0krQBz -rLuixgW95yVJXH2uPTWJBBwEEAEIAAYFAksUNh8ACgkQiq+I1thOQa4ivCAAj2Ai -cKuzJ1jZFY8uGBdw6FKripnfdpA49M9avUpw9kcnf3pQueN91CZdkmYFjlvdpNjj -+HtWzY3KvmMuhNF4Bm5LyGGXOSBq0hH0Mv1Ce5Fwbo4do7JgaAIUFflKOksd2Ff5 -RHHpFts2X8NfLxHpTsUp00ni3VH3EcEFX+8HtKslR+izCrOZ6wvzDWw13Wv58skV -NfuFP/YmeA0ra+GNPT00DQa/GK37ykP3ayPUoMyzAEqlReiJxeMXQOZt/UvMFHyY -DV0De/aR14VNRB6KWxyRAcmyRbct2t56Pk7KO8guxF5zSmX6AJfTIUGTRJ8OUIBo -2pvysT82wNbcq/77dTfGz/trZ/DJNKQP0Q7P2mtmwvVtEbcy6NrqK4X+AD+ZsVYA -X9TdTb3XLE5nd+Pp0DudOdtuJQIv73hWoKbInbL/6FAx1d1uSjwbQeqDdDvUM5mT -QatnYuzHKSQkdVsA2SljaOnTeAnD15bFqF5Ebu8YZharywtK50QWDv+pUFF2KWn6 -pYbHRYdLrpaI7+mP9wolaBMNtbc5e2q4DgIm1ITrihDV70jT2cS10U43rkr9zMWv -ESIUXMS4/aUyFitmFW30b+YRe6JbCxmCqdRhCodqLPn4BWH+cK0G718wN8n/vHPF -Yt0JoR+k4+xuiVUpk9zTGkFzItWobrVAftfZCh0X/Z46Z4aZGwzY0ZH+9W1ZmJij -ipwVsNlXIPowiBboh3VfihcR0pBVeU5+D8xcitHAO3HIYF3/57KucuSRnFwsLFD/ -x2tlSwtBoVj2fE+WEcCwgU/hXr5DkMT+QIV29o+cbgmnbdeVWmxphWXBRBcxU+5V -fV/2yEKn7JcybOH6C3T1mZkg1pDgzKvfzm9LvlIqojjFXrRh4EgCCom0MpMNB73F -a4R7Cf5XOzkGJi70RtzvfBjNXUxfEU5KNZ0Eg3mvCg2gJovZvquiJB1t8MBVbZEg -RCS5IEvYTZxPmmP+fgdFNah1ebJELyTeB0roOvL977dixpp1nnhXEvzaIdelR7xa -DPTBx7G9To8Phqte2FnRAHQOWGpaU6N423BUtNCqOlgfkjk50QLQYuUz2/D5KXMV -XcPTPUM3EwSQPwdyW+TN5x9jjn4ZBh/f0OI/IP8Fm5xTxTcIGDSu/cBxBTzyuAIj -9xQwTsIyeXio2lhAFS+N7zlc96SNmIKUKSwFoI+l+JzSR+5594TCouKg1rccsP8R -d9p7qbHbaUB4Pa4TUizwqfZRbOJtbmJIc2Mm0TDq7J7vblHXeudY10gvsNWffn2P -dGkzSq8rEYJ3whePF1j/f/SrGK/TPnMlHkkvbSw/dGcg9ItSI6gE7wNqR4K/m5Tn -LXVgiE0Htl4QPo4MOrkCDQRFAft+EAgAmPNAsOAG7MLnz0cLQJHJDlWZIzavFZyd -DrzueYsBja8XC0rkaM5mljUVb37deH8NR884sWQuzRN2Xfr9FIK+Qz5oZAeWv7Bv -xCAJ4JAe+/6UmdfvVuVUhJ/HFWgRu0U2gA0uEx1+9u8OsJ1LkKuYoZIVdtiqqlge -B5UY77tlmcMPsMBTwIB3ER3DOm0ayzegXIlqkPnKGeU9VdmwimkAqrqxyFmqVPNj -PZTTJH8vzTxCQGLQn/g7LKQiFAJwW7Oc6iP4jQCt+HRcH/5moeXvj0jMkZNGYwJ+ -iHdaC8ZZemDc6fxkkQVn79AqZBfmJ/g7QwMYqUcd6S6387/ARV/arwADBQf+LQ8q -7xqICLqTVaaJvgvs/JsTVNysl/79jfjiiozggJ+WamxY/zf/Nzivtf990ZQBnS/4 -2V/Nhv/LNJuUwhqx4Huw6kEVClWI6c6Upt3vZ3rTBIzvIhNgqXcHCrMX2oiCVPcj -MFQkUZf9XOmM6iPhQkVztXcyjB2lJQDhDdfrRISC8PfHF9pZk8/mdkx4QNs9IpX4 -EMxRXaR9NIinxg+bvV+xxfsfFr5n8T8rL9GaaZtOYHeGr+guZ/fTtqdCwjPDYgJO -PdXSV5JqYEYLigXpTEEd/ZUJl12nSOAOKYrRnsqXqfD+TlxcwqlNs4otlz0CQjDQ -gSbPwyNwr1ivwMe63ohJBBgRAgAJBQJFAft+AhsMAAoJEIYLvubR+ZWQWrsAni4F -oW69heOcb/0dIMNOOo3dVYe9AKCnMWg/qUv18zXtCMDq4UQzAEGZyA== -=1wCP ------END PGP PUBLIC KEY BLOCK----- -pub 3072R/97EDDE66 2013-07-29 -uid tallison (apache_distro_keys) - ------BEGIN PGP PUBLIC KEY BLOCK----- -Version: GnuPG v2.0.14 (GNU/Linux) - -mQGNBFH2rQ0BDAC2DQ5+8uTR+mG26y+M3jl01EXQOtGCIZIqRYnQgz8cC/4/SQhK -Nn8SwEMQXElgPMs7GAhXBGnCQJWAcatO1dd3/r4bMWiLJ+5vQumujgFJlavUqN+v -PAAsRWncoVUwZGZFVCz+tnIzA5dDk7tVXJcfgkcvATb+XcsPX3x5R7uq8f9AkTE1 -KmRGA9UrvS0gG/GpHw40eUgrv0KY6uFBSJDRCRv0UXVJ7+P/cU3qTDCZ9BteXI1L -udLbfz98x8l16DBehffLM+Cf4HvBuRnzeTpEWLvuSZb71Vht0nJ4oLw1zgeKCFZI -dhioIXrF+F8gL6W5FNmAAd2sgi9gfPr5A56dbLFYILyoY4q25txX6W9UQ0fXqjxv -CDpaOGrc4N5TZrI0qbMz6xWfE66F1eavBl0/Z5IFFQ5EXKUidn9Rbch3cKGGs4YT -dPcz7vHks0ZmOWnl0e3gzDP/WedQyVNDOhGmB704FZ/wrz9M1gWqKOtPPLscys6n -MAL+pKXbiST86JsAEQEAAbQzdGFsbGlzb24gKGFwYWNoZV9kaXN0cm9fa2V5cykg -PHRhbGxpc29uQGFwYWNoZS5vcmc+iQG5BBMBAgAjBQJR9q0NAhsPBwsJCAcDAgEG -FQgCCQoLBBYCAwECHgECF4AACgkQfLHiapft3mZwTAv/U0B6bjC/LwTcDo2UWkgJ -nC1H9AZvEhe/JElqE1gN53N6VZedPu93YZAWDwaoU4HQrfPCghpKLGxJsjoz85ON -8D2fmbzjgSjfpTBp8rxYi941A7TxvI+ogrLWJ5W7ZDi8v7e1xOeQiewblr2ELaZg -bxDFA8snbau3RdCixWgFBpPgYcttgOhAcaDSyIsG0U5rquAae0/IqJxZrV13WK84 -yqtNaMMN8F3Kk/RVYg7aOlzB+LMuWrcaz/sXjDfKyz94eTr5liI/g8FazdiJ4lQK -QdyyMrB5wzP1zujy54Zfhv1Wad/9THX0YvQNd5SvuIHstL4dwI9jQMGifUC09Y0l -jCEo8mdDGZXOqtq97+2mdxcPNFaDjw+T3yCNuvgTqYhEqht9AeVeYDhjI9QJTjcP -ZwsmQlmiAOZwPUv6ML9YghnXsmUFAFalq94DaRvPhCZRwt2ZcC8b36J/37HRu5Pq -v1vqRTcvl7xy7+ZRS9mEiq77/GrxbB8WPx22F5YufHra -=zVcc ------END PGP PUBLIC KEY BLOCK----- -pub 4096R/E1EE085F 2009-11-05 - Key fingerprint = 0186 F8B2 4C5B C02C 94A0 E0E4 86F7 5E83 E1EE 085F -uid Uwe Schindler (CODE SIGNING KEY) -sub 4096R/39B38462 2013-07-22 - ------BEGIN PGP PUBLIC KEY BLOCK----- -Version: GnuPG v2.0.19 (FreeBSD) - -mQINBErzSRABEADXae0zl0Bgh82XTF5ioznJM9uctS2op/+/uilHKcmGsILQ66GI -+cy4MH2tKNULp5wah0mXE8k16EkaKPIunXggFto015L4Y/7vsY24LhmzI6jiweEy -lsq1P5bi7RQyJmmr0JDQ70uD2i3zIHMjqLKgvOMmhXnOnstCEQR0xPauEkkcHyY9 -fSZkpoD+c/i+1NvElX8/pgf3Gx9gs2jSgVJ4eREuvTm3j4ro+D6oYRbdSFHn7+RH -1GF3Dm4pgB9b/QQVgOSOQGrn0OGyn6zGDbc06JyOQ6EdzLQv1bzl0agLO0/wVGwt -r63HSf9C1Fy5PmcLqP3A7e9vMJ6NYCYhfj/kXdg2YyiW9MrkD30aHg97Gpqy3/jI -emSmu0tqVqeFADS4iNXyxnpPO7pNorGmyYvAN8ONHbSyX2zL9RusEIvAbgPWZ2sd -5UpwSg5iw1tBNjpbprPgcRzNgdOnlKYvHcfETvVM3a0g9pf5/2buMCKijrWi6nTk -tJ9F1xXuVKCzY++AyQaZIDnk6m+bOPxUWvcIPdqxrm3IGzUcHAU26bD8nvWAKStD -sIlf/9C/+Wa4wQW6R7Q6NGZBa09K8MRAuesNbannvczSoCKS0npTLfAJX7KjNh0+ -ycagnocbhln1I8RuRmvSMbTD4npX7rdUmDFGyTQvT7WmOUbn99NC5arpfwARAQAB -tDhVd2UgU2NoaW5kbGVyIChDT0RFIFNJR05JTkcgS0VZKSA8dXNjaGluZGxlckBh -cGFjaGUub3JnPohGBBARAgAGBQJK86kyAAoJEDyaQgQMCIW0RmcAnRKLDze5E2VN -4votoLcv0C9vLHf4AKCunu6IrkDzqdKh5ToeR8xK4qcjB4kCHAQQAQIABgUCSvOp -EAAKCRCZKv7uwJ+1RsenD/9nw6J+Y6t2CYbDXFupqtsx6A940HLOAP53KmMM5La8 -x9e8dsF3ABByX5vhPMMJqR6QD6S1ZiADNtQcHxx5AXd19tnW49fDofHvn6Qzeeno -MAJjzUvfsubsbpk2B53jZ8M7mBx6xaVoLoBsap9gw17FdnYYIAr52bk2MGd9lS9Q -yQC5P1v8erNCuOxnC7vcYv6LpbpB8N96eFS9qNa6dn3jjbHxcrzmVmaCQZqsi+H+ -SNekZYCynmlbjRa/c6+yAO9avnYwtFWCLGTgKILNdzeBI/9c1NnSreRqKKVb6dDm -jTELUEp8jXD6CzpaRPfwkNq92pimwujD38720Tu51CMn98ilqI5K8kI/dxF/XKnq -KvrZLjOYEEyTZG8ksQVBziMyawzKl1RPPH1Gxf/rrYo1QCyLvLskJaryPIBzGX2S -TEcF3oOKv5oSBafMnnRMBhOn8EQsW6HYBTzuNzKGCAtyS5jpfl5ISwjXyraCH7f0 -EbjkFuAUYvwEr8vMYnX0zfZKdS4I6ScyfmJM58D2sLCWdB17bgZULpL0zE6dcUCY -bWp8Y0RBjm6pPzFalo3ChvEZkZQtAGA30H92L6ykhVd8Jf9VcVkOcvB1T7V7Jdnz -QQlTm72c25z0hrADDjEZ1C4/c45qjC5sFXYeKR/5czeAne5Uj2598wP8cSorzvmw -gYkCHAQQAQoABgUCSvNYmwAKCRCBeuHdMi1+ypZAD/9O/oQeeSVSXst9rvEStYq/ -oohtlkfS1qhBMmlw6dUHL4szh13IpWNzLVEQr2qphNAzfYhlddKN7acWzhpEGf/z -wi3lX5jmwG+Jxk7BzR+t1Lsm6dEJ7IxMZPMuEFX+29oDb+LGON7nviYY6Uw1/F61 -CBfrzaqqyqwk/TauYMePpiuPc7EhMC3NfxFfvB2TgGQD75MfqBUah/n9C94sZ1+O -ijf5owaGX/0YSN+wkCZ3xd79JSWZLf6jvzudpxOCMc60tDfWrMGvlaax0n+ThhOe -h5NtvLwjHW5STMHklx5nZSaqilXGm5A9AgBNmd6LOJlgXvg2A8XiZ/aWRM04AEgm -mBwsrCWCWsHqtZ9w1PIKOH08P8DfQ3lg+m9VDCIfutGEhlrblLNFLErBTJrI3jjl -srt0umxoDawc2cT+3mc6PnNLCbk4HmKLGIN93aR5sesfMtrIXSf/2T4SwGFolZn3 -8H4zn5dcMb6hYw7jlsHsvJeAirXYe8YFuenT5nMF7XEzp1otnmafZYdFdlu8Lt51 -+IHHNGoK3OwG1ySGLw+LmE1p0EF4Dbvs5xpABx+iKBPW4HDxOFAJZiSS7PkaTxAM -AVv/dFeUVtfwn5GCugT1tI1/+jz034Z1BhGigRr6LdtGuTynDGjwrSdFLxmy1jPK -6DFL/Ojvfp3tsOHgfFiCYokCHAQQAQoABgUCSvNYwAAKCRCKincf/gRZZkbbD/0e -SunGQr7t2o9ZLnRGHPRTTmV1uNKTjni5OsL56QEmeyIzbh0/rPstl47ei1vNPFK9 -SdsSu/Rte+kTdn/DbPI8jOG2gLaFYY767LRCVlL5cV/GGVWI2Wjk48mjvhhP2sqA -sUXqit/xe8MiWiuTm/GQ7x4/hCyLbbDmBmSqe3kvjtvcrprjTOliJnVLy5FcPtO4 -n8d0l8hS3Hrmy9a4BELrDsh9dE7Fh1gykZpycNzp0Gy0UVDoOfcA4yVYerqDxHFj -QkTaGDK/Div6+aMn0//dT5QBwX2YPYE3eI24fsYNd0sLeKGwsE+EH6hyX2XKqh3c -ObwZTq2ADsr2Nb0U2uxfHDYECtL/ztu9BERmFFSGsVGbDnrEcCik3zrbg7MS7QWd -yacdQ/RSp5EPtbbJEiZ/iVteHpPMlEHW5X6shae7hUKUsqKIZ0QMSQKWBRfPk7F5 -WQgGpVAbn1efFo7NJWtr6yC+B90fNgXiV71XAYTLYpX3mhHZoJl0Mkz1EjQvsaXV -TF11S9T5SmIXWKlf/u0qtP30n6uCraOl32K8MxZ9feJSotSzUvAUhiopNH9yb+m7 -PZi/zWS9BJDMEl2oER001VqsUE6WIUqUhStQERnILHauVJd/aMzEPJiQu3/xMvuS -xF8fvS6KLDRFiUUXX3XUKeXrJzzREdk9sGjoVqQlvIkCHAQQAQoABgUCSvRlvwAK -CRCI4nyiDtdjP4V5D/0YfBumC822QRdVRfqGq3YP5Fujep/papNfilAX3Dz3gM6F -VEBDjR4qaUgv+5Ek3mdkmgK/BiTOFm5picYqWATjlRXInOjItSglztDkdG6+N6eq -Se+nj61oZ1CVexiFmnOfOtqMd1YOprUlrWTQdnnlvX0RxhqXazWubPzK2i+VjUst -Nk6Youl8j2fbSjbfEsN0Lyygcta7kUK9PR8TsLcJ9yhueIxsEHbXM74rOaEMlTqf -qGNHdwsi+bSrYDhaRq4WhkhgmBOIDyGtpxUwuhT88vm2G1rPZDUMgLU9w/b+drYg -hmRL0krWq1bQNPQE5RpQamJh7HOpnhtmOLOMnk4lOUl0N65MR1blGqwjn7WcDIxu -UjQoe+5QYQoYC+jJiv2EpZXGz7Qim25qbmQ4fYvw03I2YEXH3SNfLBCAk04CIkG2 -OBAdS+eZVTjaeQh1U0fM/eh59weZyUftslmEgL9MLqg3ha++Na/KH0jE5nEDKkSI -lpiCj0ntNbVmlzgRdb9p3nGlMFWz4in7wnP17+GUWASVM9yXGT+izTFdNIhO70Wy -NN6ZN1ac83V2AegiQPll6Gj0K2aEi/tcVT4eJE4bjDCYQmVZQdfNic0GZMVb6bhE -OuBmDb0NYnBtnDwuzUPnQYD+UAAY6UqrC/M57SJmFHKDcpG0eXknK8spAQObt4kC -HAQQAQoABgUCSvRqAwAKCRCI0z2G2EVkLRZhEACWKu1hOXz3PBbgQLWG1RR0NDhG -o8ACnGAGIXN+NIGRwAm16QDlBEEqP7jYiYQfOD/QEXa1LThRzb88ij4bpvFIRhtL -ERmDJ4/QNmClLJBdPvlmP1lIkQIimX3yktk6XMHmAFr2/132xtC7qd3Ft7OGYWqg -G13/83JgREO2XuLItaYIPhNpvmI+5j8YhJpQ/fdRnsS7VILU0PVftQR+Pix9vnjt -dvAjw/TvubWLf0CtpavId8Z48fev1ar0SALA5lqIcwoyqWytfrFgt8uSbW+tqeKy -coKH/VXaOOl6VlMHPHPAQ1GIfwWkAiGM8dFolt5A9gjSI2f15SucRYg+tw/Mkepm -vT9wqmg2Eb4zXSX+WtYnKTw+j0w8VJO9YJt9yZBPWPxyCeF6dHeHjmS7EbuxxRLE -OcZe/h+Br6YJMyd0V75jKB71R4NUsORgUdYaQaIG+amjm5RNDb1lNcJvmdm+aMd+ -B4G7OZq8k+RZdwOHMl9W+BIC+mVUTRCyISMmn1UWCmvCCkJlzDVOHXDlBY7B7Zq7 -/APzoTPfPUFBuO7VGVeUlAVw3OTepFuFccXcFSi6fca7YHHP3KcHRDSC5jpZ8fTJ -MS0JQUY5I0Gkr6t7UgFfT5JadfMASyJdmmQwURQCdS3acCpbwwBIxHPbW7d1rLRf -KwG2itgmoV9Y+bhXsIkCNwQTAQoAIQUCSvNJEAIbAwULCQgHAwUVCgkICwUWAgMB -AAIeAQIXgAAKCRCG916D4e4IX+kwD/wKF4tKQHOhUEjMt8jQBrUoyXX5eDLDAA9B -CAAvCVRAejV8aLqJHNnHRhY48Zt4pfIVo0j74Tr0kwLl0xR1kgnVUG3a6nZUsK48 -iQg6jNJxMKXq217gKZdM4S3u84DRXiZKj4tAtAviaEVz6AXcg7xfsEoOn4DpArB0 -KzBM0Y/3D2tOSyFflFcPlefn0F+Uxx3SstXVhkBUkKOym6eRnLmgFBXW+d6bYkXw -O5f+dkLHsIB1PRwJVraXQwGCooSyUM5cidXg+QCJLHR9Q2WHReKEKAM8Ujm7976E -pOV+Pr18NYF7TF/UUNE9ZpLkiLoe7lqnwnLBkVQ0YsLNfqMrK6ReFlKvofzC1raK -usFwxKuTXXeI2yMH7/ywsEF3Kwz7SdMZOkmKyM0coRntf8spgof6pf6Hwwv/8RBo -AJofZrXbwgrHyWSVXJiDxNQ+QCLvVRhQOTb+J3lwhzEFdAXeJLHOvbXMlE2g/8JH -HaQzyA3pQkGMJ9I2r5OKcM6VGZH+jDFD2jjiuznbNCDLp99E657yixtJQOTC/VJs -xeLlMwQh53U6yxR0GxdPdfxiQX+ZrwgvXN+95WZWXmOPIrmkMv9Sx0wU6pTjcNF1 -6/rNw5lr1Fr90TGpStiuYio1hfLL7UpiQ7Uu2ehxp8eofGy/72XTFS9XqNp1Bz9u -XVjPr6D+vIkCHAQQAQoABgUCUe3BigAKCRAyN1o534K0v6nKD/wKv6VdlCtBjOP8 -W8h6y/xPEbyln8I1CLOfHSSXm1Gj4ARqi5aQdKBHjEY9JTR6zQ2EZ7dX2j6dHcEs -iXKURfYje7pg6ux21tKvb/oE/J6xskwMtSrYvIQaBdh5zv0m9QG7NSAbhyWXWgSu -jN/nzbGmKZlECkUtxazMKTaHltZm4ButAqR3Cy+XfTSUiynFKi/uqeuT6sf5SF5C -tdCdMKO3TF7TbYdWQDmETz5y5fOaZvWTrbbn6uCeofvT9/Hfr77fKMnvunaHoKfr -l4vka/6phLkuX5nmAFHGRH5jIpSXEk7kYJY6hGm4eWkBo2U8QHOhiygkmKuk0w1B -KChUSlRo2W9AfWbMIbzVZPyeSEsXC+fSM3UjqVeUrdv/uMAYpftL/FxL49w8Bmm8 -eozYkhmfmpTQe2envIipK8BKuiWnkBufjN1+WHcVxPDNGI/OWhyQJJ5+juHEz+UW -TDzHbtQDXGaLEa2ZlJbEIpFID2y+9cv3f4IBIPgZzAGQc3v5RcH5KevemLNWkV4B -1roEguYwNaWJsrX/PSaTdtRdk2iy2ipJKpkzemLuoguULiyoIe9WvRafyNqcs9ll -76XE525oMCz7XKjLEWNHsFerCNulUOz6fyYQSCN6d0OZh+wnd96oLpvKiiyepsQt -4uXoscdHwVD+DvdJufHBPeCo34UZQIkCHwQwAQoACQUCUe3XFgIdAAAKCRAyN1o5 -34K0v7EpEACJvrQdkaRsthUlCTgNHub7jL0G+lmK0vNt/DsaH26B4tpciCkRPmFl -fd/+MSyU4eRESzRKcWnX5LklKfaWjDNvhLXc84yedVJsqtJxKTgOfwU/gHt8+OvM -IHsZu95jY1wCXXDYojZPgg1/3HG4G6qdAhydwLLytiZnqaYgYdvUXH5WTr1EzjZQ -KakQwkhjTDIiz2zvbaWqZj5TWmTO4jHlCEkyO/kfv7Op0jeqmqZyRj1PItami6hH -g1kL2aFsuSqxZL3rn9v/KeAnMu0bcw/25Tji/IWObAWG2mOOYVx1LUIqk+jwep1k -1wlFLXM7S42JWG2sIOvOH7XtOB1k/jmxoP5qFBErdMyHmLAK0Wl3ksYDYo7dqW1d -DDpFtWr/F4v9HFNzDGiOPna0I0vOGhfWXumaLLgMHsdY+Uhr8WxBs0tSYBZQ4YFp -YK/MxCFP63w34BISQOjXWkggFH28vdJ66FSh/m+iVg4gmcgOQggZxgPoQYMGlUkQ -mmFupLKS/h3SLTfx54SOvlS9Hs5zhv6rX+gnklYmWuFyO7b/rx3VUzH6SgXYalNt -ajtMUcp2W5LB5ZS7DONhC5RjREQvdYYEIzYHPzfkmiUB7Zp2QR+VuvAcscvhedX/ -j0P10CmrT71PwZl1yJWRuvHMbzliP/xwIS5o+59Vci/ekZq7pdOG9oheBBMRCAAG -BQJTHd1BAAoJEHZPGRZQ1jTc9YcA/RbKPFmF1rZMEvIOWHeYWLiBB4IfwY13ZmG9 -0vlyIcG1AP9ciUtklPZjy9fGcQ06r+pEai61QCXvSUJBU+4dcopOfokBnAQTAQIA -BgUCUx3dGgAKCRCDZaeFsBQ/ToVEC/sHiBUIqFZREJprBZdHIKqc2WfxAOuD78qZ -OpxFE9/3eEm4ROH5XdRXdkl4P2SRoToCCAPkr9IVZaZhulwpub2yLkzzOnhfi9LZ -p6PSporQP1Nf9+OUq52BqRmLn2/mocaJ1WDrjSj6RbySysv8zAW69aMO2Y4wRCSX -lTI2U9dd8+VDRdWYKtufxdlDmt/ioSIfKNJUZYBZ1CFTMg6BwvrmTG5ZHQLGd3HN -cT4c4OglfGx1AgWyeURgOtgJ7csc4ykO9DVOZ88KkE+ysjfCiNra6RzrLjrABLOI -MRhCVqDZwR8FqcIETaZf/0Sr+sno8kls13iljiZOP3nDmkycu8e9pTweRQ5YV5ps -rf3/9SDeTtPqHGhlb6wdy+lO2HYpZtx39lzd0NLt7+rdLYJNgEmVixnJUcVK8t2l -GU9CMp3STJvWgzmudWSulDOL/eKq0b2LJUPtSmyS9QUIGx8seu3kQ8hqqL61CL3T -vb/LPctXeYgr/7/XUCEd5IaQyBv+uC25Ag0EUe3DZwEQAKOsnsKa0kMxTfm0hE4M -Zj3N7cA6KmE//9c45+uLQ8DEvQ0m0jEriuyUFkjY+RInGGX18YQnuATOaw6ZpVlK -U3YZC8dePDsbRIos0z1RRNzqVm9UMR1QpL1qzJwezyOKxOuoURaPzpoLYC6cux6E -Fdk085FDmT1qpB9CpPyVnK4DcfbKlxIearbnafahrx/5ittD1rkM53JJln/tO7Je -FCoIgHS7SD1vxs7XXM/3LrFzbdZuLtZttJHbjXr++xfc2bKV7ySpkyefi9cgku2x -JhSBVNEy6JU6fPzGQ1Iz0xqiwDk7CHBr3hnI/WKsL1QfKcrqhW6fwKGEmYLO5vWw -6pzngID5egm9gnzQSFCme9Kh4uCqAlFV9V1twC2CvW9th+hx4nmWpKzpNV4SbFD2 -IEwYDFJbrJTaacmiMFjq3OZir1mMI1K85EwY7pmlyZkn+QaFqE3+HKi70CoLroZ0 -1/nlD47BbzRsZeCFDw3C2U2vlwu2/kdH/NBfTrP+h+JSYBtzg8Dm4NfQJEh7bLo8 -r1wgGBTlhUmJAZPTIiZ3r3cne4yVf/VhxadcdtIPfcJn7HLDItf++ZTFQyoLw4Vn -sZJVQrjBUtzs6amJ7KT9Ai2oU5nXhE5Cs5w5cD6p5gql+RQ8pRqEM7TufN1GnV5s -R3cDU9a3yJK+i02wcT7Fvt5LABEBAAGJAh8EGAEKAAkFAlHtw2cCGwwACgkQhvde -g+HuCF8KgQ/7BzKiS+bZ9L8OEl4KJZbO3R600D82QIk0f2MGdEymavX6QpzX3/mX -v2E2xetQUjrA+tYMIXwKO8Z6u8derrouhkZmJSOrMlSxsYgndIkLmeAtKKDUYnuv -X6R5YuzTPxOE1IGMDpt0EsE00/O6i39ZW3FRWCmea4NQ2pwntJi1OVh+jZnFXIN2 -NdZydNqGvOVH0Oc4D7JRtMImpLSIyElccPywUR2/zOyjWLeELtJnch5YF/hH6m6p -nDMyhOpq2KuDg4axLeTBDY0LQ+2dxgIqoJJN/gRv9Tfaxjpkl9et4Jw4L2J+UoZn -jkkwoRvYOtZc8/qxjVEEPe8HMkV9JPZ08DZhcOxeSmrStcJ4hY+MT28yEW4rqa5L -pRj98A4Be7kRMRH1za94cUa4TPR1KaquR087gKI4qtgUAG1gWtG2VVto+tl1naaR -a0sfHTE+9BMBMtuJtFRVsLqEZUBokOKH1Wzi1oYCa3LO4LoZjGW29XbQhowIjBXx -OJIYr3ZP42ZYO2HEHttemIOmRpM3To8QeooPRW5h1wCZhV440DtXnvbqHqKcYwTp -W45jdvBkYoPdQtS+8Vy+q0997zobctz8i5hfXzxg51/IuSU4uNtgr26XapsoLDur -7PoqJGZ6UdBVwyb0qZqs6KLGQkEyJ8358ivjJsjxUR8diK027wWnW/s= -=/Vu1 ------END PGP PUBLIC KEY BLOCK----- - -pub rsa2048/26062CE3 2014-08-17 [expires: 2018-08-21] -uid [ultimate] Andreas Beeker -uid [ultimate] Andreas Beeker (kiwiwings) -sub rsa2048/EE864ED6 2014-08-17 [expires: 2018-08-21] - ------BEGIN PGP PUBLIC KEY BLOCK----- -Version: GnuPG v2 - -mQENBFPwtjQBCADWg7jYCGq+QFGfB8nLLQs/WEw4XJiAY9q65qWX1clNuVgTF9Nn -ABBOy4KiSDR9XWmARZlC2trKfdoFEnNJ6EnFkLhOjzZKiy4jkyxCctKfbV+sMzCm -ODjjNQtn+nYmOu7a8Xg3g3vTnikkuHZqWvK0O0VYouW/p1NHelUejQbOPuUKukD1 -omzskuYgteTZ9Jn8efJMIymg9dGubuvN4HvUdEO0/u6K2MCZjIqNEPeqWIuZXeMb -+4nGv2r0jSQAU94g3hueooqbUf+Mk2+H5O1d/h2Cii9qVvi6gELdVw9H+5Ir9AFc -ynsmvxrPIxraBMPgrXmvPFOTlqlizyFv2O7pABEBAAG0JUFuZHJlYXMgQmVla2Vy -IDxraXdpd2luZ3NAYXBhY2hlLm9yZz6JAUEEEwECACsCGwMGCwkIBwMCBhUIAgkK -CwQWAgMBAh4BAheAAhkBBQJXuYpTBQkHizsfAAoJEKk+HEsmBizjNa0H/AjJPguQ -WIn9AV/jstRN4OPM6eY7VUMG1DYoABRQSVsksPki5jZii0bI9VB3AUFgfXj0y6qk -CwQyKCJwZjcP3JuciJ5brQr/7D12hoTkYSCzCaECIpMoB7HWCpdoFusrgU2PUUwJ -i8xBTC+sLxIn3h5abTU68tnynCYhlA0mJ8zZ8CTvQJyEjidY1UgSohXClG2k/mo7 -z/IyW16x4dlpdkNfiBhL2v/5Ol7Vuz9g1lXvWvMdNQZ2PVK6w5dmCziCkih/qRgK -SUzn65ASEKiCN7afzUkCTdzrI71r3rOkJtlT1NWn2RAv6xT6AuhCPZzH2I3ImuFI -mkUKYhKzRN6AdmCJAT4EEwECACgFAlPxECkCGwMFCQPCZwAGCwkIBwMCBhUIAgkK -CwQWAgMBAh4BAheAAAoJEKk+HEsmBizjvfYIALS1vlaqN/f7/YzpnOwlH2Wo4jpI -jBrG7SqcdVQk3NGsXTXzzq5p7uTTzpEJW8ReZLGeYaTzqh1vH97uAPR6wL3GjHMZ -F2jkC0wSHXxvh9Gyrdx3LA8NSO+BAG9ZfD6OGklsl7tFFEplLpfR1EsAKfbi0bAY -86SfVwTmCQfFStoSTzg8qLr3OcJQtqw85XVfjrFTaPjY36/RcLcXVmAVN6y8E+E7 -019qP30afGkvw+ZbIq8qbxJItObMuhn5xdI0YaMm2yudCfm2aGYSCnkrgNfuWzH6 -WZ8n1fv45TGBUd2R6zPr13eH73AG1WXpapoD45yf/TFavRfnknU6xb7U3ZK0MkFu -ZHJlYXMgQmVla2VyIChraXdpd2luZ3MpIDxhbmRyZWFzLmJlZWtlckBnbXguZGU+ -iQE+BBMBAgAoAhsDBgsJCAcDAgYVCAIJCgsEFgIDAQIeAQIXgAUCV7mKXAUJB4s7 -HwAKCRCpPhxLJgYs4zheCACgc3m2FH5kmXtYO44BdYYwdV2dyLMCxvVl7GUWqJF8 -wKmDWlUxBwrpzDBQXpmHyb+rqX/kvfEkH2wb9TZwginLecbZbMKubNUWUqGJBHQo -CaV8o6L/iEUJa5NXzY2OJCp32CHsmpefYkU+WgAnmTVe8Se7JEmJeu+2OfStV5m6 -zVK5xzlciYSc29LpA3dsv5hxE6YZ8kJBJaFyv2AvVzaouSR7nPNrdw3/jXaOz+Hb -VpP/CEf5IdvF/o37sv8o7WWcH1AjvMdGQNp6Zr5Te2E35V8PmpqLH4Z8W0/PXij2 -67i565JZc1Kmpqxm59jg1vs2X7rHNn0k+r9BFiCQC1LKiQIcBBABCgAGBQJV5hIJ -AAoJEOGWdUUnufY1qh8P/03uvjuU1V9UZY9t/4J/K0wbU8Re9c/HfgmJrCn+wvDI -OtxpOg3m07ZoIrosYEA2CIm+kLCYuNbzGSz6ZPZlpoq5FvxzO9OAYMO76r3ktxUw -Snbxd9TCkjCCQ8RMxT/JGDBU77nAJPyhCUZF2/SyrXnexloNP9TR/IDQZNOXzlxR -gu+zIrpl/ihfqxozqXYFIlhlP+k3GhiQt6e5yw+bLRiJZPR+NLzS4vfTeYEvWT2d -tQJ8FFyJF2HypiVcFFF0AwskiVRR9xxkdbONeJ0DnOHfRmnStfl14EDXUNDZ34Qn -IgMkw8vydc1GeQQE44BZYlN1d4J/h6eSji5Ftex1nbRuTeesXg5AzAHi/zWn8dRU -KCdKxjjn+t7k1SQEK1+h6Ja+CwBTZpHWpHPEbFzVSTXcoC0qU+QULD9eq1Av4OTi -Bnrf1/qYGZas6K0KYL84ZTH7JAZtgkXrn1sDiOMEMB8Hdqpw57wPaSt/6mbtmkCd -bCTWigBIWSY9FGfSTZdRk/KoIIK+VqxCPkS++RQ5ltwwq7Y6rcEsMFdUwMWc3hCD -Qu9C+djVRZrsSo6nLUGKGjoKYb1xmcqr03VquVVH36XNRmy3TC/8RqSstP/Q4dtx -a0bgqi+iu9vwLVUWtgLSQJr2OxTcU640DlVCJdvqTfS4SUP5Zht1HOkVzh3l3KiM -uQENBFPwtjQBCACln6mHC8Js3T3KJgNydimOCAFhLmS4e0ur03Y1nckB9zB/pMTL -ulDgtZwWSin3Kd40VZDyKi6mqOp5ldz6AsZ2CSx1GfI9iVhfuFqOaiBLqpNpdvf9 -nGL9OVoy1SdwTXgnboiIFtbTG3sVwD4x4qTRbmT22Ln/mIAICR2wxFBkzpbIQ7Mf -R/zEgRh2VlRUUrWUsnYdOh0xfxuYgsnPCjpTY8hvEno3H6kzXKmj2GQJtawMVs5b -Ro/GCM9lBBR/PAhB65ACzLmUUSsxjlmjZw0tCcOufg1RyAF/l6YVw1UOJaqXBfSP -eZkLQBj9p8VNpasX/acIfpEaZLE8QhoO11ajABEBAAGJASUEGAECAA8CGwwFAle5 -inIFCQeLOz4ACgkQqT4cSyYGLOMvsAf+J2EyV9+GNqT8UmEU6OFnw/sdR1oE+vZ9 -fe4mifAfjQ+SKYf+MS0lU3lTuwcQKwFklePoYsvJEO7jNEgjTQ+zKiDSlV5yufSn -Idy8+sCYygPn5fSjGdRaMpCCfs5xrljLUPK5U8+vjeteRJW0o2/wmsYdHRz6A74B -kRq8kYu1M8VgZ6JD1YI/mp0mHTTB+H69/DNo6cA+7W/CibeTrffbJ35+OXGsJxqJ -b/QH/4lqsceNJtJThkHPQeM18R7/4t7Vhb5htOk2eB7coKzdYRKpHMzkm7elm8bI -uwsky9+6hIUMKD5hhc8G7g9lWOLSXCeNRUdqWTOfZaU5KOK70kKUeQ== -=PCbZ ------END PGP PUBLIC KEY BLOCK----- - -pub 4096R/B4812553 2014-02-26 [expires: 2019-02-25] -uid David North -uid David North (Oxford CompSoc) -uid David North (ASF Committer ID) - - ------BEGIN PGP PUBLIC KEY BLOCK----- -Version: GnuPG v1 - -mQINBFMOLVsBEADW2N1bQ6GFDDSbC+IKggdS/lwhaEo5Av4Z5B2es83A43boyJZ1 -bn9xfd5TriHubI6VBgjbuB0peoCZye3PzEz9cfZYXsPiAqZngWk95or0N+vwrGoI -9gJM6aBYjE06fxHZRTAi4ADPLW5sV0bT230/u1xpqg1lcko5eGV5sAjI9HaVdfvR -68gQdNVK6TciOeM2EQcTHlRd8D9D2/XTp9aCFynNaFoKmBTOsc+VlczmIgd+1jzW -qWcaGTkEtZKzAxUfxlWgO0xHjs3H4CGqtWWCqj8W1alkwIVHBeXIwHDoHlbmkXok -65jfeQd9tWzTHGXETU7bBbxksbwRlrJrutgolLW+/v9F1je2aG/BKMwOLjF7dk8+ -gvSKlu4PwoItGN0qraWsqAGDR4/bWLihqPluW+pUL544li702DUeZiVxFEb22yDb -p2oWdFafEFhQz4FxRCam/4bfVt6bGLGE8GEd1jeahgmpkIAcbAoI9UOFAVaoSWFv -AqYphVfONeZz7MMIcNlyHth5VAvQQF7/uBWCsNtlvBtVirR+nis+eEwoNRDwYx3N -OKu1GTFPMMHUauB0ORD2ywsFQkIjDbnQMNhwQoC49bs46vCusBb42qmOpjP0viVs -qGI3Ae78F4KEBpa5AVbYRbbicOPeV/tRrHFWMyXmH312898j29qO57e+awARAQAB -tB5EYXZpZCBOb3J0aCA8ZGF2aWRAZG5vcnRoLm5ldD6JAkAEEwEIACoCGwMFCQlm -AYAFCwkIBwMFFQoJCAsFFgIDAQACHgECF4AFAlMOL4ECGQEACgkQ+bj6w7SBJVML -Mg//To6EADRjfp11ZGu3cARitfx67276xAkt017sxw76LBzHoF60RtPjcRBBRCYk -0P1URdip6nC2M7Ol151YdTUIfKNWDRzAUVgpWrGfUIRPUgClyO2boTijblS3heZS -gCKz9x3WwRn5elR3Qf6u/wZGIuHBjmh9Jwoa/c6G6ikIoLjoUvXBWR53FlLIpHIF -/q6mzwhXdCwohDsfDI7ckSuSv5yMJsYLZRpEKB3zLgWo4CQP6edaewBd0bVb/Uzy -/5aeolwEfwoNSJ2J4+tQ39U1vxPr1NLEALNl4qW4Gn2fSACnWyEjDHrLltDvolU/ -iLXjgb//9ge93vZUfZmH6vPkrt4TzOfar4wLHTgiEX8nKaOwiMU72wgSL1DLJgry -udf0zSIYDldm/Wy4ggywd/mSyp4oWR3pJFI926CyiQrnA4fSxKrE3yI4Pm5kZNBM -5fhDwtPEtp4F/7kLxGK6MCxyeL94x9QnZdp4FHyRcO3XCCMhfAKT3qLiuHpTiNOt -mOu3Ea1DsEVbSOw+gJzqEZN2ruB8z9DsOxNxlLsdW+sSQRSNgErnLlBLlkXpSawB -imhbwfOHKqZ6eoEqz9ufbrJjIkOEDbIbW93hpyG7zdKSkKsXLR9HbOZ7kgMgzPVi -KNAhc7axmvps55Jx7aXP7G+8c9d8iWhuwD9MemqvhRKyzeeJAj0EEwEIACcFAlMO -LVsCGwMFCQlmAYAFCwkIBwMFFQoJCAsFFgIDAQACHgECF4AACgkQ+bj6w7SBJVPR -6A/9Gk3J6BV0IPuybnmxrkKUicPsIoXgRnzU9LF2TIC6mYJBjb3Tllw0kahsTwLa -vfXEEk971zushOUH/z/wLLgrQ8rzJq3RfbvWRMz9BurIJYGWCnkkINr+lURV0Od1 -IzilZlLuCWCh+WS8w4sJuoziF71Ick3Pf0DCpPIte6PMqBWerrbmXlRfYZgP+vrH -JZ6ZHUEkOVawuY91QRW5HKsM/8RDwgLP7zvXtt7BaVey0XW9pRVQM0fzYzW9wufc -B9DMQeampdXv2R3iXVDQRo86zCRo+7UrqEpBGNXBNhWozucw5eidJo28U+76fWng -7rpDrOPSOUWcg/IfWDrm+zrPyjX/9sFuyjP2w+/dsxmerYk4yXYOQaVHJYaBgAO4 -O11WsjhZZ0bvYgxqJjHs9WGfg7ZfuobzIK2Pl1ZwU0lAcePwuHTBTBFlI6wUxmhG -KM2V8vZUMopxUSw3AE4lWZV756ST8Tc9cVVllBg9eRGHdFN2NKullRzTvLMuUwLc -IGkL6h7VrPmQUhgjyHO4mWgE0or4bm7pHRjP+1D+dxTlr/OZUAiCMgxaBo749Mas -zgvDqcxJOtH/9J3dUeTzN8C1RoKPQPv1znmJ3OgpOKs0cNz1qNIQGQkYasl4awq3 -nPz7QUqcKeZgy/6KIInOPJ8ys2+R54hFhOj/NUBBZID8EX+IRgQQEQIABgUCUw4x -bwAKCRA7Ok8Kx55balZeAJ99U3htpjHcxLxLS9lkGT2+YiBIdgCbBLVVwOBCU7qt -mdHezw/Xp2oxxNKIRgQQEQgABgUCUxNB9AAKCRCgJ0huCLbaUCjLAJ9Iht8ctGWu -SiDFxodDIHmyJ2z8wACbBDGyGhDA5TVJphdJm9Qo1LYKgc2JBBwEEAEKAAYFAlMT -McUACgkQsAucyC163ywE0CAAtVzeWwkCwf5ISyWjXosLnbxohXvmq7uh6bdTVoxW -d1V882pi1UAxU/UZFhb7NSvLaz/hr6+WK0wldl27BF74d6j5rE/3r47KVeOEUuAw -g/J/tLEfzhWtficG13qnLWyf/iTyP6fCIaFRNHL5PK6Br8xZHS0YF9zRHaCutwTm -MHV5KinKktgA6Su7YmGwB3f1lirXxUa+RiGAkvg8tIs8Hn+V2x+FDD22QgW4FDh4 -CFYrzz8NsUiIkYawlIHQdnCkQqiFii7MZOG+EsJ86P0lfYbfJfxEY+4nI737YfXH -SCiWjDTiZG0Hkvrx3qbt0L+Ixydn3oGkrfP+ZngPBj6n7QkALAUFBA34+cylobOD -jb1nKGM32iqPx50GpaS3KH3WmqqXaR2+6SbUUdZvmwac6vQvtRRfEhVtWB9irXUS -wn218Ki2EgprAHwrsvLeMJYoR1U9v1UvSrFj5qtiagJYecxDhsM6ozHmcB2PKdE1 -VkIv2vPRzVsfuWeEFnPOSOODsV1Zu00AfceotvAEZd+VdXNkJ3MfWEy7VT52FnG7 -FntzqDXxGkYZLxK6zn0Qh6udvRz65Q3G0nd+USkAmhEBMTr1/La1LfMAibyUyiyL -0bTRHkjXQc8SpibduFzpcWyrMELVqt1PXgaqtujcjVoHwo00NgJIedBosHVuGBXW -PpUQx2DkTnIUn5Qkncf8SpgCCGFs6Z3qwcqrc6Pb1Sg6XQ6GpMTYMZO0yaLdSSrS -vl6wdiJAzvlP1haafInnNFAo6qgaGNgdiSr1r+SpYycFHORCdqimLax5ggOxh1Y+ -V5uZxDDvOSJQUNKO8bDfREke6gIsNRCj7hRutz9F2K566pu5Tn9UAiv1ZfqYxBub -+mkjkctRw61DlqHepJkY1KQTLBphVM9CAADzWPKGRVZtjeYyLNPBap2GbciBQgzr -/2UCCWAGraxpniCizgkFRPRFaOSp4p0p8DozR3/7xftLPXNgudUbRjxNlRX+uPj4 -0jSEJT1Yrc1/hKgOWvmP13WTbT9/8F2tT+Gd8DTLHa2pXMePOX/dPmF7g7IiEUo9 -Pmci3gFMd0MU1+tgjGZlFs771MZUBnq9rrsX6K5PcikE+UV354mTuF/GdL5Qvwbn -7DQ0Z88FQ4jTatPucEghTLnO9ahB+5ZlE9ri5hWTKRMZNkX0KlCcgcNpPTJ9Ya3e -vWUnuhPHmxq7jD0Fc8VLjiKMWSMMiqTrxdgit41ocZinCH54JKtYb41lsH55rx9q -8crmWdsIKC/Dru7h0MXQW0iU92eMOxiCbXuwNqnzYxWkhjjydhUXmOcufgzfh9Ry -S8zBC/rw5AkhmuMEZK9Ksskt7SvDPqdd0209JrHt+SA8G4kCHAQQAQIABgUCUxDx -+gAKCRC9U3Jvvaau2NoJEACzaTZ8rR1F8+pIy+JdUfQxmZ80CI2CMCjUt+WieiRz -3ZH2sgKqwx4T0c53n8938cwXmwdh5xG17sGWDS8VpXUQ3eq8nHPbc12zJFOWM+Ix -fUIT6zapz18m9x4BjfP78QovU5OyqeE0KtvfwXNvp0OjdoEs70WCaGdmAAcpOd1N -Einz71DOtDcvRdS7A6jqUwfohemu2iPGj7gvUoykb5gg3Nql4K1zQg+Ymo9RH8Bu -MA+ebOvwaRaozi9q1Gjg5erXsN+H9TivoMwRiAHdlfeETuGWTFJl0EhtXMHiUjpz -fA6UsR8LgRMehar8rcsWRY2x8oH6L7Wf2JLc+XnZhAe6wKij5BlbJrJBZc7FcoMJ -KqxGlgLnMDXL5nmHfaIxiJUU6qe9DSRvGyMB1rr9xxeHp3s9DVR8G6Zaub6ufa7k -8lfCKbJBru5UD/FrWPMNztiG8fgRg9krmU41ZgvhT5ksZmH5rcFgK7IOowiN9Bxg -tAclbURX6uNc8CYmWVkR1f+zFS2ChPEebyK+R/VZm0WH3Rz6tacWUtzxr1GryLUU -wTmxGnyXflD9ySAkjEO60NdwUpofeX9qMzza/sJPpxZsGmy3PHByS/AhK7wnPSlH -52o9BTVqwY9b6B+oOnswjccgoNyQmtQu84CnGlUKG0y40ho3F1DCHH/l4jrYaxsY -J4kCHAQQAQIABgUCUxHKygAKCRDABX5xTWlPsl7XEADlAVK6EiOs88azKcH6h/uY -luxi8F97MOEcyjKrfliRxc5Wt2Ry417ngVelhrIzZPoUi4iT8znazQ+GQWBHS1SY -51AEqPN0wrbLpMnhM7cHOZ+Yh8za/G8mIpXCInrsFoDsGTm6jBuwhsmD80HJ8ctq -7DTxrxEfklPuKmQ0ZgbH4wwEmTeU8pzzLlBe9yiDOYVXscG6xffPp6Jml+H2buAb -B7zZKD/yXuNKgs7AonMLrA6d297wslMAZd9lZ67jmLvWLUhd7LGaA2xVNO2+5yNx -gMXrdL0wY6NdUY+yy/48b8izD4Hxc0+7wfnZgeND2tgg3av+hbX0sRbIoP7uZgrl -JKuYuHpgmzQ0Y4eoMklWiWl1o7A8d/vVPuGSOztXUhlQF4nKfEAyn9pFyu4UXjfu -NueBTQl8Hqii/wN2nMk9vZz2xFN2bnsqvIhjnMA2yoQl5bs576yj8Rbji9eK4ZUg -WMAkuOkB675DX5rYrXUnDNo3aBS96NQG4CbG/jaM5i0a+ClVg9tVboGksBJZRzUs -lUQxo8AXS+h74iipJrokigsrq20jO2t/WdxRdxduXu5IOs+hB6ae81JjjHjTFNDu -uteDnnLNG1dBfebw/RkH3cjp+lsvnAks/mINStMoPEH7/Obvzuku32UvAxglkY47 -QSCJfS4QpkD4G/NUvNFhVokCHAQTAQIABgUCUx5jgwAKCRCtltamwB49Z5zGD/9G -Is/hfe5iQrSP9NFNChQjaeafjprCMfi30glYsaXM3y2rrXZJh7zKAvOhYcZwbWK2 -+9meRzuMX2P2iG3WZ7iyaoPALb1WpPlSQef34g3SJRV1UDVKwYpkJSZCsqIX1bhB -sr4qjY7pN46B7GX7RrGl79qDy/CUzLciJ1bX/BiB4L3+ls4qrrfomO3+r10ngqzT -MMmn5hjVWE1BDcuViKYwhW0u/HcTulIVkIp3+Vs6nX54d7nG45YHdmBeLPA5fEFv -Xe3Q3Q0YwK4r/bZwEqlg2GVg5npYIB7SB7MbU1znuHJvyUpTeO0z8lNWjYjKFedb -YmO/tQSoJ82GQt9HMaENKxKP4Tk8Wr3SV3y177nD8+6jFWJQZ8lqsQ/GxZukFWPV -0Eo9dRsQx5v+B5h2213hK4YcOhJaiVtBggUodIKiGz8sW89V2L8EATMb3lAJsvPu -FiQkuQDOhDlbqAj0yQfyBxKmKCHOfAJ2Q3aYBhvFFXho+DBnPjS9r3QfL1z3UYNc -Y8tCT9Um+MX6h/2iAodpxtu4xqHd2PavOxLsOA0IFKIcSNOp731VaMPdptgCOoCk -r7JL7PrH+7QwBPQzCr74rQhiTfuDd1vbmgJGm/D/MuPX5+KemVqOiE+o6xotCb6Y -KqAWu9CqW2m2L8QuD4hNR9NV+StJWmmNaCoOOXZQXIkCHAQTAQIABgUCUx5k3gAK -CRAObqOOk0fwLFbMEACNkB4OlOW32GFzalq6uf2vmG9H99+/pBiKyGKvc50obLwK -x4g8RM/dH6zduHUZ/uJJ08Qvx5h53JVYPOdxk7cXvWVnFJXRQNqgRotOLj9r8Hpa -Rijh4GrTDXeVrNY1rw+Okw7v2iyNwWQDVOkAzrg/fZ5cZRp9e2Ti0cN4COcGJVQJ -lHYfa13GuiSUSdc2OisYiQZWXdT8SnjHLb5cL6GRgmDDhOC/FISiu1L+LFIsyXoZ -9pzFY/43sGTmZJjFnudoxEQHuXmbQZ4Z6o0yAncU2bow0QEQQ/949z4GHNcbXduz -eXBWXO0kA6z4Lu8YLBk9ihrka3kw1Y4VtvIuWQDuLV7DR/k3/YHZzUUvzGH3c8Vn -+DTK5f/dp2TrK63Py+x4/7E62V9uk/VB+TVy0E6vic0Tk3+KMGUHsVWGZiYXYnso -ZpVw7/2vMmiPxai35RMe/yi8r7pAYrQc6su9o/WMS1Hxhp3VPa/g4S/mBfk8jse3 -tHof6ZTYAG7t3FhxVGXgHRYa0nnmHf9bLtNOHrAJ4M07z1VB5wMkFJ491nf05oVr -cyBA3swvliwAilskCfJFFy1yttnOlYY1hLVq7fUAoMfjux9BZglXlmCPp5HlaT2t -rF6VThREOAI8/Es/zrYAgntLuPFLJcYvjqPEChttT8I0H5KlzoSMfHZybsyW04hG -BBMRAgAGBQJTHmQGAAoJECKBkcFWfiwXbtEAoNyetrXS29ORsTlasGUPwumYgHaa -AKCv7Ky87jcPLoQHLp5ugFOyMAXKc4kCHAQTAQIABgUCUx5kQwAKCRAo9QGWxDgC -6wDkEADFhTXNCEedftkHSLl6GxWCGEi1qI418U+cn01hRCtIY0nVjzGYJaxHamtD -2cepVSDDdIeXj9C4mcy3na0/mME7+H/tLuZiOv5d5rFIIK6gODmE/69LrCGSLJL/ -1ULCQMqQ8IcKDEkZTmStEKJZPvE/lPmfjn1XGf5gC8zbTg59hN6op/bRuQpQHsIi -LNn7jEW4X65Ygig/HcRK0Xj6iTEjPc0ITMthLPG5XHUjMeRt+syc65Hl+Q18zwsX -i6bjp/DKLgDUdLvmXdBSxmsDZgZjJtfE5C/C0Yom/VpVesXCWCZqe++GT/K95dSq -pZbu0DSVKtrSTqglRJf3gPeVwQUFixjj/tynZHiO/7cZq0pazRrX2qM2ZZB1hkhZ -VkISzBMUFC8YPkbVDKVYisyUJLdUEKdSB18RcX/ZxLUOsYTo3CsUIwoTH6aL4yQB -C8rB0OkbJeaZbU/3dlHnycAas4ze6hzvEdiYyb2jrg37qbJwg0CPDevsNkLu/Ie/ -6BqqXcLszWS52aNcyLMPTpjvQIC2gV1f450chsiw9yeMUtsgVFXADO6+8zM1io9B -1dtEjRXvaiI3jD/jqV+g8TV1i411NHw5sW9c/Jx0UuXDa7gmb6+6VvavIHCF0pLL -FKUCMmoFePtp0dvdqN1Ysv1RBn7GKl4GGImE0dh5T8pPlXc57IhGBBMRAgAGBQJT -HmRrAAoJEFk2rKVTkFoB0E0Aniydu8kZjiaob6/OT9hYtOkLaQRqAKCD+l2caV7i -J/SkLCBgY2relojE2YkCGwQQAQIABgUCVGuZsAAKCRAXscp9ZAiVKMxYD/iZPK6P -qwHxzEuQjquo8f9f0q1RkX4AZa1j5hvXcqAddUa3HpihHDFnW0UDpptlyonryxUE -imhD9a22/eIsCz4sF8gAgrp9b1gRBJmJMvtRgVHaFn1u02/5IEvRj7JsWgVXzWFU -yh9zLaiQtcpfvfFzmdZKtZ3hl0TGl8NFMLxUsownR2tx0iuc8r+NpzzKpxQeXlYS -98DrDLjE3AKVSZcc8DUBTlwhCZLiXEaQjAKXW+Mxfg8C2E4hQIAsqLWhj8PRQEpG -w9F0Wdrh9w4ePsKKnzsIaprkRve3vzEuDLvmHV+9DQd/sh+C5W1LjL4h+vC0eXhd -42lIWrfgOhai2rrwgfSNEFnMAsB1zdWcwMgVSP97sSVfyrqMlDJWXuW8v2KR36ws -zZnqVPsgQk0Uy53mItUnWblgabSb/udVa+ZI6NeOv1bMGMgKaFqXCn6aHD1X1/E3 -0XtCy2dE6reTAU0zNaRc9ZJOLvxJj8ymP+pUqzkvxLMWAuqpCKsM6YNFlCFkzdfO -LHxhqGp68jKPUfuG7z6yRkgDZF84k55SUK7td8lHmJpbeiL1+N8Sm9CujQ+TEAbA -ZFAQjonwnzXWxzI4N+1TWM8BbhLmFpG814JNxyswYdmps6pdKCWHi8zC60dYZ6Mw -IQZfNWpkeLh7W44NuSJ7pIXuSfEaFCKXX+RwiQIcBBABAgAGBQJV1VPTAAoJEB7i -/Oc/14DWS60P/j/c9/0Fi9O2WsDjCqHge7pAt55/CNiP/ZpVY5VFJKTuWOA90+zM -cLz4By5jUDMz3W/CQFA85Bv6sEwID7ClhahLg4UMM3kn5YyLPIpXjT4i02rsLqFU -tFb40vOlJ1LU1UdpSNVJP3nDNrrg46Ialadycmc1jB5EnoloFC3Qu6QkxcFyxJoR -hDkrU/QJnaWc/6ln8UmLPkVspfXX8PPoy7YcWzS0e6DXc18dBWCigef9tJe1p3B9 -hD1Xyjnd/oSJSkDJFcdD+8A+zdRFqaLNQx1AZJW7UGBNSbaQN9LU+0DSuJVeblU9 -Oo7y9YbemAXLMeemwdkf+EaOmhrtAmfoVMXKyQpE80wQxGIRQC1qYwGgzwwPodsW -yb+v/nfntWEXP+XJFJlcHKYaWClsyd2sGl0WASBTv0VesElYa08lkS3/JEyiDhZx -U2N1Mzngp56P4P7hTGCsKHQ2wKhL1t+ba6pc5wqdNNJEICZmodxgJuVVLq40pjGB -qs+93NZiVTaKIMBZyhrQ6R1e9KoHOSCkh0izCPgsBaiDUno7zU3JTBRI2wB9yQDa -9Hg6flkLWsX9dVn/DPz5ZreplOSjjNc7Q/mGjCW5EdJ+VmfQWSyqBhymINdNYAhU -q/1cZKR6qFd/khYwUvUikXh/xjj9f1653o48R07S6VKy+RLRPjlaI3xYiQQcBBAB -CAAGBQJWDon4AAoJEIqviNbYTkGu1uEf/3scwbutNTY3Q+8vAAEt8z0l4Cbtodbt -m8FjgpYGTod0ZaoUGCylGs9/TGO5bs/yC1w0el8NGlSnr3r2NgYlXXTTyRI4HPtm -vwnYRrC3IEnHWFcyjdgoNwhR83M3n3Pit7OybAlXcm4FrdLZXvjVxrbbzMqjOW+W -yO3cBhVxBhZvIVNeQcSxbZJVJJTj51+NFfTUewkXxZf2Rk0iuGj1I+qcf5x9u0Zd -j8dY4s/BTJ05Nam5RMx6buKUqWa7ob0rmRDoNSs8AWEYQ6bYK4OXa5jba6DnNHwu -CuwwGDeE5bUXqqr41GHk+ACjvFN12uO0O82gIKHTffJYVK6iJC7G5mHSteB9B3rS -6/IRpfRw1w5RX7sDCkhFNWCkHeEurect0YjVBwANuT0nWgGlNEwgrUxRBODe4mwC -c7M+Db9OQGBpeLivGVa+UXBUf84sBGw61zmqKJJ/tdp0XlunEsNr8btcRHKg3t/C -v84XjxG8MDmWdizTVN1qF4NCrISrb4N3rW+CbSfEtLhUAN4r/1a5J5DfVAAEDArt -S17B1zJl9umiQV3nH2r4RImvHzWRnfH0rPTM28XxeE5lDglxD5GHWtNF8iwPboSi -Y0CTIocH7Y4SAJqYm3c/gUGyUBlddsJK17SBzO6CWt2bguSQoNvf9O7Mm+/V0n8F -BKyWgNidyOq7q16RGv7GV4peZxLgIg3e3THLtKgV1FqnaHdLuQ6vudTEzfz0s3tF -GsVwVhUSQLW5k6dDFvE+zdygULUgRlWGeWteITTLiU0jHlRTadPvU63zf5kkl5sQ -/xLpLHAWoHiPpSd/DdlLMNJrKFE2CuXGzttV81+/Cd+jY38czD6yHy5nho6awHCP -NhWKCrRIRVKJ/Z3mhcwRRQ85ro1yzD4G4QBN+lEU0Rm8uqvCX7gywa0i6zMRw1L1 -r4/VMS1PKe5p3kJnJgZ1jMa1jd1Aqg/5WwO9by0SF85pL/2AZs5ldn5XyqsbNxXg -VEh4XDJqecD07gRPtSCoM/uTR8Ns6lMkgstNNHJCnv+BCKN9A0ACwTvLrfGXPW0c -RTDDBz/KDL/BPU/E52Z90hr0qUDgI+CZF429+y+DFcdnxVkth804pgVpP1x/DnGL -bC/teg8HBmGTI1QL3e7j5DrLHvLfm+VV3K5+FDsAN5bf2VoGHsCOsoLWXdnFJAiU -SVVsKRippiiv18Or+taPY4pV9IkwDnktXvllcpZr7LAsCnltK8L3flh8/NVt7eGQ -APFz+Iw6tt+zaN7cH32ntfBZCZGYJTKZYGoYesRYVSf/tDqOW2w98OPtVxyq+h/L -pSldmvWRxS5IELCc+FND6TxGPG0VI5/5sooEimZKu9EVXwhXDnj8TnW0ikRhdmlk -IE5vcnRoIChPeGZvcmQgQ29tcFNvYykgKEkgZG9uJ3QgdXNlIHRoaXMgYWRkcmVz -cyBtdWNoLCBhbmQgaXQgcm91dGVzIHRvIHRoZSBzYW1lIG1haWxib3ggYXMgbXkg -bWFpbiB1c2VyIElELikgPG5vcnRoQG94LmNvbXBzb2MubmV0PokCPQQTAQgAJwUC -Uw4uPgIbAwUJCWYBgAULCQgHAwUVCgkICwUWAgMBAAIeAQIXgAAKCRD5uPrDtIEl -UxNfD/4+qee7EHu8GmT+tJ66cSZn6qGzCcCqNrMMt7uAEA9lcph7p8h0G7Rxmk9z -V2qUpRjuzs4BQH96AXqcdkjsix7d+rU8mCHVkpce0m/m0N0gdnsfrwf7V/4nE4EM -MAh2FuvayiCgFGR5jG+oTgfihm3Y22njvhOFThEdSMdohUzy46j1/bG/LSEJQZQc -+z2UzyXb3cvAC3BMwyq6dTPBdBOddxm/7gB98GJHjfy7UUWLNErGJWwVlqcBZ3Nb -gSzldKl5Jliyqh9HreKVi6SNhhFRiOq0A6oKHfiEd1QKnZ50Q0bRqVKMd1535PUf -xa0UBFOKHJvsN3mgw/XADqkjOGEpeX15IxeqmYW89usWIPR2U56z+C5jqybL7PRL -cGV1R76+oXXyGEgekgI0+s9zfnhWDSGCezHegcphwPu4wBL+8ms5R8lX7EVKPJId -p29f1TXQGW/2XXyy7ZsBPuzuCjTh4SV4pcnBo9VphlRVpYWZ31ZhrLQag2DxoqOR -7sWPxy8+GaGfmAeVuPr0EGi3t41wcsQBi+GOI7mQEFhGfSyQQ9G+DFqnB10b71WS -lhaLfghfuQLZzXJpAC4ZAKKjrjWiuJsH08PBTaCa+vkvvRd7GTF9PomHwvdC6vSB -ycooNG6qr0scAB6fXfUOkv4G/aqZi5RvbVzLUlhUEOlufuPYCohGBBARAgAGBQJT -DjFvAAoJEDs6TwrHnltqa2UAoLdEl0H8Kx3D6CdsiaNahUaz4TzJAKCl4wN6tADv -Y/LhKLqqCkMRYWE6EIhGBBARCAAGBQJTE0H0AAoJEKAnSG4IttpQlc4AnjHzmN6G -1BWIlXZaa15G49Cb1orpAJ4sDg2ZYQtajVf5h7J/mJU8feOn7okEHAQQAQoABgUC -UxMxxQAKCRCwC5zILXrfLDzkH/9LUrAoIgoCWmpE/jH/zXlu1mUMwWvW97hWQWhK -IICJBO2t5iUqq3ohryygCkeC9IWYIWjVLSrbbWiEiVbYC3gFUpRVaqTCYTMY/64i -YjwnON9FaR9m6TJfBi0BsNpoqfqcfWY/yAixpXdjmMzuZx9wtlWmJcT/5RW+50aO -LGic3fsGyAdX72Wn8AUgyzSsf5iXS1EWlh8BYIHA/dlU7PI9u03WBUpzctcyE84F -80b7uScXMjVvR6iv8T7S89dnilkSSdG26WWL/3kwTRaTMVu/PR/HwBUBhaQnK2oM -X+AiyOIKrkU0BhYD/sJPTk2n/eDkhtNJx4f5vLAcD8EfU8Z/7Nvx50hGHMqLsZu1 -webSQdKJFOcYSEOrLkVEPLxY4jjcozDWANXYSFLrs2zigxraDXRFmLNMMUiFB6Jr -LEziKtjPPQyZa+vhIwL6NT4fXjQzHMP5V5kJuk9MGAWgwBlXlE7hsboGI8Vnhsoa -Rdoq15ZxHZnrGTIutyatXU5DDq0oOyWpQmciBuvh5DLw+aApn5ZmLuLfRhlTrac7 -PMrwVGAFzFQtsXhAXcv9PbzasEzpgDnyl1sFNBnxFCbmCyXfOG0gLktU8xgcC2ab -11ClmCuutGEljMk4K15Im4iHXW9srRvpMctfePPJuaB561wHMjTWBdICGdzNDAmc -SO/FEDzhuWTXMAVtnIiPmH35cacIsaa6lhfnIqgn4hDK88mfrI7VxzWAxPfSMIrj -JGkZyr2ykMRPEH2T+gK1he7h1vQu+qEiyJViEHOFrnHjhbHA7KycwJVxJZKj1evg -eTJxvGy3C9lWtpP2jHL0AiMknplLye0I0ZSh/F5I92iPLPoH4tdeuA4/GHnIdUfq -8N8VDOANMhJM87go1YG84zDYheFxI0pnOaTxRAE4dMJD8/K7nZJv0wM/x3yc8J9X -FmOI77Y+m4metov7OB4GUg6bWYsxl6VglfIoXtuQTzJ5oG2YJHpuCqlGwgC7D3XD -FNcbT8HeiKJVbdZeL07rXXJwXhi+OUHlugAL23tzFLYxcUUTvlmHxrPUu4SSCr7+ -kkEJ/i/4hfGsLeTHEuY4+C7WI9W4OKC+JZt+10B4tD1uxBJC/SNH7+MZDPJCWXEe -rlqvjMpQGHFGWR7iMcYpQ5LJjOddDAIaUKC8pYtpjZYyOs+6Hm8BZsMpG85GW2j0 -mCv6lwPsfwezXfzR4TR6UFxi2Uc7SYxJfrrJyeOE1EsrMxQdkzD5Q7aaFRXT719C -Z8ZHm7j33r66yK7SQvb3HbTuAE3tEoNnT9dW5TNdoe5LytjR+G5KPYLVYhRwLLyx -O9H21bOewIbnwaw/31/KWu8G0qDe9MuOzIGhkWx8PNWaO9W4iQIcBBABAgAGBQJT -EPH6AAoJEL1Tcm+9pq7Yfw8P/j6DiZUpyUcohyuOMq+YHhjuKo5w14j82fkcHynl -XPX0B6RgNYFslf4rE9jHum62jl80BKXsswAVs23Y9WY0nbAE7cO51rTB4eigiIQq -bxosY1bDYGNBiTBMkqes7sTQjUWRfE4HJlB0AyyEgu2F9FRn6Mna43IeAKBTbxM2 -g9JReCl8Dl7kqdAXcsXRi4UUdKY4WwICYw7nD9VtXBnG+yP/QIxbiasgGMG9xHvM -SEMj9x5+HNdxTQkLqU5q7Jxrs25izbK2paoHzfA1dDTMFkjxf6UHeay0qfWR0Lpq -NF0zhU+fb0eThvGqJFb0iMv6maeboFaJMlXcbeCK+ny2xu0jvuWst8T9FSKcQ7Xp -AkKzShRyBjbWfRoVpajdzxUDtOGsC8g2LAfCJL/kLkV+l8jNQFw4lcxqqZF29Anp -SvGPpH8/3amPh1lFiDiIkWXsEnxV4bZ5wdoT93lUH2vnZJEK0IByR4sNSYPr3EXi -TaRinCp/0WDA/k3oP73NmQvx6qi2sigR+tzh3klrc/n0ajdPDo/vXnIhLJOs36q8 -dIKcfD5yJgQM3px9V6iaL3epTnbTZlggYMWpbNihj0A7uuTYIhiS6XXiN6rk2b7w -RmO2CGD7UAOpLTSiOiot/EgyY0oOhDH4xvY9FSIlhsDozOxfkkIOTv43mBHXNuuq -qDWBiQIcBBABAgAGBQJTEcrKAAoJEMAFfnFNaU+yhjcP/2wNF5GVUYGJnoVCSFFW -O/lW/XqZ6/T2hEeKcrUcMrqB18471Ra+xU2iLupOKWVjt2ynhsCcW+67T8UbnxwP -QsOoniDMU7plGqVS09VPXjlJq1Ri6Fe/XH/6kAruYihWd0y+mVwSM/6YmXZHYb+k -ZUN0lEn4BLwwYto75JHkhNTC8OWWDauvsdOfHC9PiYzMqjMVaUzT1wUxTUtjKyiH -tgmXAwxzISvs9zsP4byvopJAkDY81Vx4IgKIS80534GwFC4S4BDeqcF9DYevobJO -2QYpu73pvwKNX5TZyF8EV72Xa6VWG03Zf5HAtW5gcUGKmD2g6EtnZweNNI9X3r46 -Jp35RimVO59CmG6aMdrUV4fozWWAHtwA3EF0ZtjxkVzTC1tiQIWCxSNIWVhLgBtV -xOt2VC8QrfpaxA4/W5Wz+luwIOAf50q1EA99TNKt7yCyXKP2ga7KqdOwjIKlq9Js -vT1Q88HFARSwB2W84KynwqldPj/gNFwm+8xV4G1gcesTInWgh1Yl3nybhGWzvUK5 -zo4IlBiQsmpaRsW16ACuqhVgRc+NcI/TMGQZuWxkormjmv2bq0MNvOpqZKDQB9CA -OFu9Ya2M9cuPjRUH1wgnye0FjK4UA7riWUrWpZLwGUJKKyZbHsRxWlcive6YI8Yj -9prj9L2GV+sWo4aZnL7X4/WxiQIcBBMBAgAGBQJTHmOFAAoJEK2W1qbAHj1n8o0P -/iRTZ+tlSSXYZcX8M7nCPzCT72czzOSGoLoEw7yq4m+I1bQGGXg5jiPBWOJqxjBw -+mkPJlZb1YACmsQIIju3z2Zu9EL8HooiX2fnDqMKCD+MAhNn5hqMEyZnF0P6bwFz -jucOneJC5uxYzOW8D4454lZzQWeVy/j07OlpTeAAPnZ69lPKumNEnbOSCAvElWak -5BWaod2D8YaJwkdWRKhh8PI7UgCgBCTM3U5lEHH3zXFriEIsgXwM64ELpF75KB6V -Vw4Nh7Z0xCcNC6GB96gNM7pFp/ZQN19hxXW1sRnA7n5RXWw9tGF/K7Y9ilNhahx4 -M+7xLEpNEVtIalfxnHbQ8yQuw9ivz6JjhVyIs4nbwIrCihTqsab8s0ZO0pHKZ3uh -qUeIzgMn/+9URxnc/lfrrrJNuBnyfxSL3koREZKZJBuv9VuxOK9Rp4vTQ6fYjEvz -uP7fWCMAL/zMb+K3/l/wxGjPIOXZHaTTnA9m2Dy/jxC5qspstHh/Mjl+VX0mqZzK -fpMdJeZQl+19j5wYcyT9LEK3OkvjD+/tPuecrMPs+5Y9V3soYnQDvTXbcDmZvDUq -9pB8Qmi3BbxibV8FoW/bUD6LPsquYaRarwjzIWmIi6+NMXnp4kunoAzpd74rubG8 -ImefzTodPWp7yIVGvJsZ5oaguPUri9smfEWhTXC6bkmYiQIcBBMBAgAGBQJTHmTf -AAoJEA5uo46TR/As0JMP/2K8PauF88ChDkpKRpd0A8e6DWN1iRkJTIrxcmXuEzXI -UrBEMSOlhk5vkgBKjYO5K8HmjKzWV9ZpiYzQuBIvY42G+l2ysrbXL3R0fmj4MzzW -GFVLEpDK9c6aDbgbxcmtyj7LTfWIMd2yM18kfkf85YhNOoq4MqZ5xCzdnjzNMP1W -vdKSZWVa3Km2VzX0nOEzkUtggfdnOjWqYPIW0xbuH4fVGSSBYf4QhC7Sgt48Q5OQ -o1xmbx7X6qdyBOZx0fQtCv2WidZ1HW1vR0HTQ5RrmmbMVpWqYAdgj8aZQ7IQga6I -ABvg3klhMrERkDHEQuRpNtWEabOHz2aq3224UjCMPNj2+CHnQQz7tdA+qTp3CbZG -5/FTdv+54RQ1DJaKPc+gkIFlgTuoKwsvybGT4osxKayaCUkHvtMmbVcTsLjcIGlN -cy/sxWeMiJtWnopV+wQy0vsD+YYhJkdbG4SAbxXgLAz15dTeOdV2DrJe9i7Uk3/v -6p5s1EPlIb1rvWddBThsSw21iwL4VwXYGELgmVYwTfY7uRG54GsbbQ7tSVsKKk89 -0DAQBBbioc+U7s9CJzcCpSa+nmi/IDHMzBeSQxgM12jnx6H5KuyLS44Uxc/jxsFA -twb9vX88EpdpU2UERk/LHOjySnsOHf6BUew0nTwdxJJ/n8TEmDXXXBOpUj2BESN7 -iEYEExECAAYFAlMeZAgACgkQIoGRwVZ+LBfDXwCcCE1Pw66YHItX96ADCWi+7jHo -H14AoMNRBrelaNwfVEMFCBjnqexGY/d8iQIcBBMBAgAGBQJTHmREAAoJECj1AZbE -OALrr1gP+wb8XGlTavHxqOENZGi7tLpWRw5z0uqg2OaCSWoIN1XNilvQzJN5hAHq -2SSsKsfRKJU8CJXTnzZTUBLmK6OjEESh6pQshA4I6O0OxQWlRKJYEo3vlvhIhAZ1 -SNlFKVbZakSLOc4h7D3MWhYWdSC7Y5rqYIcRfxEmvmGernjXGbBJqGfCgsLs7ZnN -mO2yehLQYLcjY9hbdFlLlVvaqEYy6vbd4YzJyrG53o8BUv2wet21oWmRd3FFNNzF -2Jwcxhxrvzdleb4iTKBBN8DznR7O3YR4XwNxhP+vdDR6pMHGBMRok5TIOh4MBtpl -S1LDR0QBw4TnPB8/bbZZh1dNp4YmPofJnLJbf8Euf1Knx3OxzQzEjONJNaKEToPc -qT0Vcr4BkSXic/NqHkaggDtBLIQhCxBY6OFxTpDjLLUAKez7aeVk/YhaxuiUgyB8 -9cKkZPRJbSUXtsYi9HJmd12e8igo+Lm6+2j3Cirpr7oIPqsXuR2DyPbqaPFVzKxf -RP4CNvYNYIQCNgVEG/AjTgctlPijClVAsswTR/wYg64jp9iAZHidctv2huu+NTZZ -7f/pKGq+YPI1If/EnTmoiwZ6a6GKwCTtFGtk8ymEHA/0GHG82WOPO6QhZ3pySQRB -7rUOLGPJgVxwPtvgLjNOFF9uq3Avr1+ZQ9v/DOzht+o/BTZVq/rJiEYEExECAAYF -AlMeZGwACgkQWTaspVOQWgF41QCdFHvQARQXT30+2UboMa2BmersAksAoLx085Xb -vOExlzwn4qqB2jsf4cTNiQIcBBABAgAGBQJUa5mwAAoJEBexyn1kCJUoCS0P/iEN -xgmgMxAxurVoClx+XcYMOiFJ2qmq4CKAY1dnUOONVwh7T2acRH7bR9k4JgzB6bNx -zOqMyPs4H3rVsrJkbhkNpDre8E9YhrhnWXy7SeZCnVsDGXkFgacV6C4AiByfltAY -3wQbeC4QQ6rPci0Mb5E5fpVSK1GMlBwBz8xVi+TcXt+WdG31aUA6WwExb/EAVpdq -aUAEAfb4g9h8J5l9YSWl0OXjTG4f8wHljOxoGpE57NqQOH1HXvZKd5sWCJt6oEa0 -jBpnUq+e8ptY+4Jlln8O7JMySCEAqCntTbya1HbFnS0yxPmyNeBlMwOhydHfOSAx -4PDw0AKlgPdDkYRLlnZMiZdfM1uJGWaRxlTBIQSFoPawbafmjbw4eJ2dSr0utGN9 -PuofXLgKFtO+kXzddTns63KpcQNq/xE5EDiAw4qjIt5B/k8RzhCGlI5s4phP5pxo -mWlzwjsEqCPL+a6o7+ZaR0pEyQ3CaUAQ+kjXrWATYttF93hSq1qKRVR1DMW4SO3S -w5+rbrvqT8Obm5szHVc+4X51L17qTA9R8uz1tysjJkeuEdbHSdbsSaD8ZWy4xvNp -ZhLEFazk9+gyRH9+X9uDgg3OgYqJaXdbpMBB2BjCXPOU5LLjsRNeOyTR5EAjNvA3 -wThKP4UdSpYEBWr21TUY7JxZo/73ma7FnJBJNYoJiQIcBBABAgAGBQJV1VPTAAoJ -EB7i/Oc/14DWHpoP/1YA1rfaNWSDN8E3sc7oPSwhA2cd3dwgot7by3igrU06JS6N -ejpwVQ4KJxHYbzK9qZ49paJsj+fKt09Vc+Zzf5anHi3my32W/8i2fI5qdcTaFk8r -nmvaBBHMDmxfvOm8cb2qAH84sAGSuku4GbbQ0x5ye0dSjL7odViOunAk5kD9d2rg -ZuEYYDQB5JypWpCRf7CQ8sT4cooed7kN7WlI42U7rKXmUkunNuvuPZVy6Q+W1ZiT -xWGI9y2m0hpJKhANxukoqEcZuXWFGx6uDKjpc51YDAe4hMORFP92sWslL9+YMkor -RYxJLa8NZ03f/Arlzi0zinUJBbmr1PFgJLWnqIOBnhTBpvLr0mHurQnUzmCl8LdH -cGVDGQrT8fUr4WqMhQ+55RxiCFJ6cp7A726l8TDD4V7PzfwVx27lTxShJe6jd5Vm -vpxGQVoyXESox1kZRXU1WKnARHbs0dGA3Y5WcvkfiMgL93+gUfyiX7J7eafr/fFv -NpXyVbnG53zR+lnH+6MPX9Br9Mhw/PjTAQZxwdlHuie8m/DB7Eec6CKdpWDuMTNw -a/7z3kMGc0Sj2HAyKLkjrswB0N92OMgiJyNFmZtWUZdkefGQGkbY3XWoaIVYuG67 -I8apAUi+HZMLx8OgrGA2JkslalTVY/ZKEaIh6SVeib4BbxHoxvFENdDzHxUStDJE -YXZpZCBOb3J0aCAoQVNGIENvbW1pdHRlciBJRCkgPGRub3J0aEBhcGFjaGUub3Jn -PokCPQQTAQgAJwUCVW77SQIbAwUJCWYBgAULCQgHAwUVCgkICwUWAgMBAAIeAQIX -gAAKCRD5uPrDtIElU902D/wKqTNBOGlLH9tYR517p6z4Na9XOmk2LDAz/LRfbgRs -5tABEY5zrQGqHQZycY7+gCPwOvlCjO61SYXVmIRFf8FIFN1C98YO1aPgjiN/utu6 -wWiq6UXwQIBaOIXnzEuDrns2lW15XFuZEpO0uAMfsFFNoKzGCqO3/aONZ/cuE71C -qiwNgFnqLXT1pKA19KtDBgdGLSpADnRinS0ukiju51yvcY1llLvUyEFLB+ybA/S0 -QGEjlZwOSBFjQhfVUamBqk7p/BGoHY054EjndqnjJmrhGFzZD6RlLS/ZSqD/jYl8 -pqysrOGQvY9Aj7R3usVq2Cwjrne+Khuj1j/cvTwmr67qy3SG00ujdcfEozC9XoJd -UFYDqfKU4aMufMD+xGSmQrGFInXGS3O0+ufTHt421xdKrq1lNb64eZ2Nd8vICuWq -AhU7Gi0ulE+MjUkBxifCS/TQpa1WrOkwYqbDKg7VA6d4cTnbFuHH/J88Eru5kdde -0xvjgd7cJ9kzQl+HuBnBW77qTlZlO4TKwEFO40vzrDFtIHA1EHIjFUvrgWLpSx29 -vMTtQmYWiHKB6j2bJlGAosRiOdZ6WWxqgSSAnU+zVFzPI48ltV5TQ9A9Zaf6lWqq -OBDETrNpG74l9W4zIdAzdKeajK5l9yIJWsl3gQeH5Ctyrh+vO8UWaQHux3HT/8mn -u4hKBBARAgAKBQJVcC7lAwUBeAAKCRA7Ok8Kx55bahHvAKCToUw7xgzwWERRuQ/S -odkGNYKeIQCcDeeCw5UgRXOZm60QKU/C5j7xGvCJAhwEEAECAAYFAlXVU9MACgkQ -HuL85z/XgNYPcQ/9HBjF1ChWaubKJkS/pfo+I22aPEClEqyG8lJXxQUq1V78VS+i -ZFFztyRH0w4RezwD/5j1/mYw9RjTdw1me8y+NgAIKfKYzAR57V68vjTzAdN4jrl4 -XixWUCsgMyOxKURtaMdDqzpugBsN1RhV2Mo0tEGiQF35vn6dY/qAOkR7+jyGZDv/ -tLX7qg/+5XaRydbvhuR18xO8mmbZizVSUZLQeZ+wi+65uvFRnyJ61lkR3UPl7Ch4 -cFOIZ08Ll1NKhnZ7d0/GUrByouiwGK+N7+QaKZOCU10XIsHOOV8T+1xDzJ/oXGnK -Hr8tKPO2aSvURsG3RM291gQZqMjlp/fYvYg21+CeP4AydSMkYz1SPH5QSrax1Df0 -hJ4MkephCD2dg3IEcyh0aBkvpYYzEvoqHmLje5aAtsI+xponjrlkWG3Af+QbR1DK -j6AbquNSvOeJPRjS5wB/W0rc9e+tVWK0nxdUSmcl/jqnghnIxcKkgK52MZkIBysd -ykhLjsSZs2lJ1fxCNB/i8dOn10rMO+YVbYQa+hARSnpNcwLL4rCHk+JwMJ4+Ol4Z -ssfMiYPyTrPKBIRXoJKVI8s7DxgbnUiKotfQnnAAY/CG7OTEEBfgL3WboIV8oKMm -dKtStYjSf4IEVMPXo6O1mrXnMBWQeZTCNA7ZBG1ehKMHLQQYV05NoEBuYGqJBBwE -EAEIAAYFAlYOifgACgkQiq+I1thOQa7rcCAAsUZ1X2imVX98slb5xJ0ep6+HfzLF -K5zj6nEmoFMBm8LeCW+eQyeyH0rHIt2LDs5Pj1Ne+W8C+fwGgT+PzAy2iCEZgTPO -2UJfpy9nmV93mPn7MLK8c7u+FvqHrE2sGcTvOQNwujGyQ/YPU+fnneYKRbAcUz8k -bX3w6T2SYAAp3OWfRP3c+FUVPOxdsN99xDifdAzYmwrXbYr1GPGai3MQLvGE00UB -xoqCb0fCtAHpiWW3U/c/BvzM8WHRhFseHP9Do3tt5q3O9h5reRNIq7d+OXpkDRZU -GJ9dviZSVeS6+s46VXOr0liZkqWhdFy+ZJsXoIxt+yyHejI1y7KQUu4dJo4NoFyE -vgtRa15wjsOEfFRacCVeaMJ989eFQ+F1kb5LeI6xwm4CShV1SBy2pEoz+EpU7ezj -xi96PAm6kCgoaZMIgIdaWuN1uJmQsmvYK6tlr9M49YqkaFzSHFNVKc9sCw7BBT14 -jEQLKdcHZDCis42+1FnBMIVn6rTp906EkiumrHwC9YIKCUHPW83Rne6NXuT6/wmw -ho3Qiy6ob2wFFBjIlbspsZepDmBWSTX4Ej7OVzcJ5r4PXlus+wbbDob37eCzZ2ms -sASGac6d26/zRMVzMNUDmmMmpIn2qCuzqJBYOc9h5RfKfJ7pP4Erda7NIN0PTat4 -HnXFeluIjDQT9YlTVgzznq9R0el50hW35dVrRRlK+bBTV8YLgzOimDSCk4G7hgCA -XWnAQWRU4CTEoJCo6PwnrVxc6NKQIVuNTeIxPCqFrP0lWvCnW+nE5fTQk1MdpRlm -JPRk0q2QxXRgBv7piJSdDBCtxmGlI8w1hhwg5SGDj2KCGNo9nQt1Ouf43Bwla0VI -Fi13lLHrXjUC0/HJZub73zGi4Esjj6aOAllufbMTPquAH1YR1gbQuHLq+cmbzoKc -Kjitifzo/9e0WZmn7ki4SYZsjFZg7OIyNNx1N/qe/ph38VeEqNvOoM0qsvxjMusK -V+qclVqQxGHx9i3nmuXXBDjj8HkbDfBYAwXr6SbfarEYwmqs/Nv9YxnlPO5xvVFU -Fb5GTbUKhneTfnHHUDppjv6A48vRNt9AT1b3vuB24zqN0khpxVUqPsV1J8yyGMvk -umRUnNd7vPgBVsLaX9Bxwdva66OdP2rhk8YKHWHg4kVvNSFv5+Qc8T5uUXS1MMSr -d4uUT/9TvCQRrD+olffOjQ65NPbgi/GIo1XdqviyztdswaBtN8l7gP4GPBVkBLYm -KFXldmmze14EWRZZQ/gP9a9fvakKoZT4/b/r4NbKtyRcYiuucZMHd/BKTyEiy/mT -LOG5VZbg5WcWG5ZY08ibnQikfXMdQeZuA0+SjvzA3TrLY260wAkCrjZQl7kCDQRT -Di1bARAAw5bYX8BELxBpyjb1OcK9m3OrqzMyBagynF3W986L6LoSJ8UBwcMR3IEh -rYJb9AyH3OlFBqY7zaIg4L3AGZw3iK4GLhkffCXEAB+4QxLB2yY9V9lAKA4NmuWQ -Iav/huAedflUYWLCXNlRQN6Z8jOV4ih3sXMdnbMg/FRBsyY+uJL9zFSvLrfl9nRj -lhGWCr0AnOJ/SE2fHs+dmKbFXHSFUEA4mYNxzj+y3djAq8KoS4qBokMk0TzZYTlr -0qV2A+1B3KSbLFooyd6G31vxK3iVmQFJ3P3QmFKPUY+wM2Xzy6L4G4huAZahsBhV -b2BjaH+U/3kwzVg210EB1zKMZ7hGEDpP4kPl7OeKQjkQg7JvTMf0KJUM7QJlUfu2 -4a0nAFVpFINO1R015HiTrFzMWNYGZGvef16f4kP8utg83lvo/kJ/9ILliFUPqxxo -Ip1AU4E4KUQrFrZ2vl67/smCzIkJrIB1mGwe+mHSsxWdtIrkN6mJECMlGvJeIm8U -4Pg9tEDKhoDblxJFuNhU31Mt0yEKcFk2iXnP8DFPpkfYToKZy+UV9UTpSG9kV+YX -vMdMXG9T95PiR133EllxjUj7L7lvObcu4oh7lb3gOk8npp5vIFfauvk5esreMguO -yT5mh/SfGTdI44pyssGGzR21sDyC/sBghblz2IqOX1fyLcKJKNUAEQEAAYkCJQQY -AQgADwUCUw4tWwIbDAUJCWYBgAAKCRD5uPrDtIElU17gEADGZKidcCE3GiFymVMp -mlm/OrNTT73Y8YiPoPXuskPLXw3UMjrttTVcOMixHk4L8mScrae4kqKaEjKYMlm/ -5vZUsoRkX4tbgfM9Ox0R0czLNbtaywC5AZKceYQtqCRSdcuTXbNtyJ66By03zLYf -15+5Mve2X0BGRH82zgyFWDM/7ZdyU5ZXTh9rwYtb10LQwbNlAm8yTabOz/a9Xv+/ -W97chFmp4sOamSZlI1Ol0He1SYUBEqpJ268ic582o8hxGF5XPZPCGCFGfCTMkegn -0GT6sJOFTpAspm/yjht/pgo8yRjnP6XpL1Bd/fe82rAhQOfmrFrJPyRHPv8ZIKEn -23BdVV+VvlVNM/kVU1Q2MNjEK4cE+UJSKw6WseOT+Nh/yVff4kWJQxk34zvBkhqQ -d7hLJGMwQdZQKcL6I5sw/Qon4OhAkrXQeqFqH0j6IlmTyfZaRiniS3pBLAWL6DhB -otDpvJVsF5gDkk9OKRAmWltWAqsqvQItqh0fLCuWhoDqVb575YyXH1Pa3XezVdA3 -EzdaedFhgyH+cRyC1zDuZlEvqHnl6tI099dxW9ujRv6KKeD8es62MrjFTSXKkaVC -Vdx9BwyvRFo0Ay/gTGAjNCPfyMzM1rD1rnYEwrNkXzTn2xAXhV+shW3Z5lnJFRrz -hAj1He6be0CGjU5FRo60TI4mfw== -=yNIU ------END PGP PUBLIC KEY BLOCK----- -pub 4096R/27B9F635 2015-06-22 -uid Dominik Stadler -sub 4096R/EF9D5EA6 2015-06-22 ------BEGIN PGP PUBLIC KEY BLOCK----- -Version: GnuPG v1 - -mQINBFWIY8gBEACj8cTCDwLduEQpiO2M1qL+/aMtct7IN9l0BIV9bL1oILyRBdi3 -3DHzP07GWLlr0LaRu/uUQuNVKy5ZIF237qn5BJoQnMQuZ2oQPDbaWdg8XkTJJ8pH -kBQfsV5CmConjBJmV1rPCSbNbwYl+3fstIRybqgIjt9AK1xPxss4BUtbwSRzP4R2 -OblNfJ2WiD2/BLD/cw5GiBIMnH6LYc4tSoEdnZEv07RJUcTXs547wfCGMfOZLjps -TRLpCQsTnpWV0X7Y7P9m62OUPEs6XIYJptY/Kv7LaEm8A5SSdTOfe0/SusIa2AR0 -ASb9zAwmuPLLNWhPiHKvXeWmxOgr//tpftvtRGlYYkXq6VbvLyhcjRSPiv1Rqx+W -byvduNzRgJfSXIwfOIuAo8w/aNebZw6v2JDQYsx+P8KIxWO+MEY3XnzRIKEbK5mW -vxIIhZhzXi+CkAYV3gSvHISDiYmw3/wJBerTO5Fs4cBIqMWfszTXJOYsPhyTF8Kl -gOawyq7+kpyil0xRAZ9c0Zq+dwrny/q8Jw22MtWxt0gP1Q2bYoLdNhLQ4NzMGAvQ -2eo0loXwR88cB1LsBHhBfUYnRbw9MXPMaBH0oHdqb+Zm1XvVJMv2xpBM7jt8LxA0 -rWkAg65tv70jTa5NM2eSda2qRMpVCY5VIvCcoEmGvnnZUA4l81um2Y+MdwARAQAB -tCNEb21pbmlrIFN0YWRsZXIgPGNlbnRpY0BhcGFjaGUub3JnPokCNwQTAQoAIQUC -VYhjyAIbAwULCQgHAwUVCgkICwUWAgMBAAIeAQIXgAAKCRDhlnVFJ7n2Na4PD/9H -GZuGda4QN1IOFc67RSVoLj1fPgKcEiu6zzarzMGChKsdxoo0ZhmyKaAh5/JZn9nh -YlHDi1zpIjbDLEwEqr6qXjaJz2fw50BGX7yamM7pFvtNglu1KfyDLogYFDIDktaa -nHtRUgsTXDL116YfoiJlucRqv/7sTCQC2bsuDaS8jmq5Q+9tVELrivxvHfDqnb9f -+yH9HoFW6lQAPyVHVfpB0nDvmWx3twXjatrNiU+Xp+sGsfHtxD2YUjyft0diw1H+ -1U03FJGG344dUS5ZY9L/IBvIaZU+ovMSjpXshlZRZURzlN1FJljB1YkQgHEdjWHz -9Ur0boQyyMZb3pYc4hINfLChoQoOlENM05LZE1G+x6aug4EGEWnKQsBfVqu4AwgB -zQkaStHnNrmtIlEWzQtz/CZeiWpC0zXwi4gdiu/Vk+XOZE0YPxjLsFVIpK+m4B/I -9VmlXodgUkOcmU99EkmXbR6G74OPYphtlRXRnZVcLSlTKfQitZH96/XBHoQ+k+e7 -uODYS9Zyfq5bFzbCmXLieOTQZUAKL9xv5CH9x4aOcCNeSr6JIlIo8UA4QvP9QkBz -At4H4F2a80TUZtB54MwydKRInKlCdneZRJgEw2aHNuzuc8CeNxBxQ0sXtPRRjs4+ -bKHc89iggbhQCrJBijlV62jrXlVLqDTaNjOkQn20lrkCDQRViGPIARAAnDyvkbv9 -45FwvG4qU2haI3K5DG4KBUgtnuioaK0aF+GrExkIO/kjR574VTcCyTr8PBbYImOx -YNaxn9QVG9tLlISworLscur79XVcayxkI3OWFzmAkjtlgrGiymTDmIofIXIh6O6H -NkwOCkfYV2KcTO+UAf5O+DOPi+YH+Wr83GlbxRSqM6XMIXSkva3wPFWXaAmwCi1/ -JeUyEMdLWkEUfNPA53+1cq7SQEMSzdwEfazovOd4MUzQBoIDYbRdio/UBvTw/sQM -BpKkjrDqa/Z7am0+TjgmyzJVLtfivgKP8/oluwwNa4OJQNNp4kSqmB64I7YXd9dj -3FjdaVXB6E8BqOxubN9MDBGy59YOkQW6eeYYWH8zRz8BlaynieslPxZjBeEgQOS8 -ow7RRzyALU4BWrD2WBYu8Po9qr26r0NhzwNtSGt8zeB2rK+FMoKIR/EEJUqKgdWR -e/8ase0Uy70NQPqTwcZRDYaDvdvfK5YafIVODwUu1ojHqkRdPuRH5UpNdaCBk3kU -0P8yTb8/qTBee3kLvkxspaMH1kgmUSWwsR7vip7Mra/fTCLZJPhJdpuPxHgd3MtO -CgTNROlubFhHcrhjOkVTWNfoNbi1zaYZI70mzMasA4cqxMCkzhHDt61ChQa0u7Jf -kIcGBZe11QeTMmQkUoK+Z+/RR185fPtbb6EAEQEAAYkCHwQYAQoACQUCVYhjyAIb -DAAKCRDhlnVFJ7n2NV6jD/9qaa+oFiMEZ6QPdk0dc9cwTkVth267i05AxGoIu5IG -nLlxTWfKLudSaOlmlvj/ToOHCGxtqMkiOQ/r2zNOvm5A/SSzoxF5tW33kq9qTXvO -HC7OAGIlEWqUN38iiooOwX94LqTDQnQhJSAQgvLOnETY7L/G2RwWTNBNAVmSZQlo -ZHyB+eidQ2K1xPmqs7jygbI2Evgu+fy0HUkHP/pSR18E9Ed4NAn69F8T/FNBu1tx -Jiiq2L6T4cY34NWJSVTkzNeN1bKihkiw8xli7GsMAx/M13vXHVslmAf+t7Qmf5wU -EGiSxO/v9KrkJ0J70TxJ8aSuw2WpmeFD/Yvxg5RmAyvOksKd4qhPUDc1S4a1mIYw -UnpC3ToqTaFhQrC+C4V7aDD2Z2WSe1sUWEWxebTzpx7jO8Ewk6Wrc8GR/EkLEkxy -wB572tirOBouppxcUK/y2HyRfMMye550Ky8XSXnEf8BBEQCHSE8qRFNewY/ilZse -VpGw5vPPmG9LUEuFjNS+cjSacaT0/42O6V/31LKuKPmXw6rH1jo0QJbXRorX+9nD -LeC3Q0DhbExabeoz+Y20AlxvkVhOL6DlTqKPZA5iyBXBvFB/u5Bm//82FKJHiPjj -sFK2ZjwJ3yfYEsRZQYi45odzWfHA0Ca2NMsdjmRTk/N7AeaknX5KOFIvFqdZndOE -kg== -=rPGm ------END PGP PUBLIC KEY BLOCK----- -pub 4096R/5350373C 2015-11-29 [expires: 2020-11-27] -uid David North -uid David North (ASF) -uid David North (OU CompSoc) -sub 4096R/FA3ADDC2 2015-11-29 [expires: 2020-11-27] -sub 4096R/03DB0978 2015-11-29 [expires: 2020-11-27] -sub 4096R/F8F92E4A 2015-11-29 [expires: 2020-11-27] - ------BEGIN PGP PUBLIC KEY BLOCK----- -Version: GnuPG v1 - -mQINBFZbMhABEADSUrZOMTO1k4M12D0GzbLpvaVpXKGn6ulGt6TirGDCGrtvVZmQ -mxbe97TxGN0AqGJHZMOjvEUiUKaCHUQU1dS/qyIA5F3Oxui4IrEAj8R9gBhBvpVE -2oEHQZVYo6YrJTLJIjnVsb0RTWiL4hDGpHjcXrwBimbBT03+62UJGaxmT/pIDgxZ -i1aamnIJIEV3/2H/8BOxVIIsp5qQT5XL65nve1+5D2P9PJYtEVtVUYFnqOBqIKz2 -T7/1TbyINqMTsqtEpqjBB/RWwiX0jSIsAPcGBMRO/xDfaU9TILwcjNc0tCSpn8xr -Mn0fawkJZPj2hAwAifoX+Ryp50bYlgLiOJQE7iS6dp5RMj0au/qOuZDKLfCDXbpn -Ob0pMFyI8j7pYx8SDUfcXwTgdVK8aAgZPGwhhJQmHkaCCPcx4PxXt+7V/8u8xmoB -1bTpNPw3KiIS4AyP+m0XaZvPnDawxYWO2Ap7YowcAIjNBTvIf1J1jaoUR+RNPI5t -IZlPG+wz7adSubPyF2WTvQJriekBBo+a98e3MpZsqpJfcv3pJQVe8BTTqOOQBKHI -n97MSzBZQ/MznBiaqdm1NKFt/d+fQAE/C/Cqe1WJtgDhPigUoRQxooYIaae6rB99 -pTe+T2NXXGPL7oX47+K6EZ36AhpGMUMXtYCIP3cTneHI6c0BnmKC/mTvfwARAQAB -tB5EYXZpZCBOb3J0aCA8ZGF2aWRAZG5vcnRoLm5ldD6JAkIEEwEIACwCGwMFCQlm -AYAHCwkIBwMCAQYVCAIJCgsEFgIDAQIeAQIXgAUCVlsyWAIZAQAKCRDn6itTU1A3 -POhtEACA8tbeARBnYsUWH08HMQksEGsiysA7JOk1RlwchcYcKUPnuFA6N3bJxWv8 -LtPkP5jaEil6H59CrkXvzbU3fZAlfqdsOlTKZJl4hDht06bdB8dbGknEh2qKGoO4 -QdblIPuPhyqZwn+pM0CuzP8hhh8BdLqqJHb7aVL9Pv6nH/ZDMd4RlEuVJonQ9UIk -HD44oLx5ivdrwPOE1Y9Bwn44/AqBsDCGY5REkq5OHS5eohY1eGNBBejmf8g4gEHo -FWwnGyBmlnwfGiMdw45WAc+PXezjuanUIuDSCDz4GiTvVwja5QT/eWEmwAReKT2X -Vs3Dp+DBsG1TsSF+5hE/WIxFZs22kfQJBhShPK3+T//8i0IfEORMfnp2PNR3hZ6W -ED33cu9IkuVjsbVRWunuFp1hLRq3GiVeGpYFezqtJ+YdEgy0CQh39QcDi3UAyChI -6z+MMAO0cNAeBQD1bw+kJdccoDD87YI0R+w/dEoybxHQWlBIzwtkuG++Jvdx3miu -BBSv8bXTHg247BQKAbRbb0XxyDp6pxREP9aIgXsbjpWKNU9I/GoefmjTBwdqv22h -zp3lZpxZcJstyplIcRq/IkOj3Qt7Yb1yfztIHfRpYySlhOVMcreay9V+PC50yEHu -lioo3fzAWyNcxt2Vb+DHUEC0axNR8giuTSCzDhqqWG9lHtFMVYhGBBARAgAGBQJW -XZNKAAoJEDs6TwrHnltqQyAAoNE1UYWq3t5c+nucIwE7piAvUZk4AJ0bJaTV7QU0 -k3sd96ihjYn0oPiA07QlRGF2aWQgTm9ydGggKEFTRikgPGRub3J0aEBhcGFjaGUu -b3JnPokCPgQTAQIAKAUCVlsyNwIbAwUJCWYBgAYLCQgHAwIGFQgCCQoLBBYCAwEC -HgECF4AACgkQ5+orU1NQNzx5sRAApoRGzIxnykyf6rgS63ONFweFj4oD2/b/9Qwx -u8/UN9xoeUtfiuNE3n+4XDdDGjrwtKSL5qXF2tCn2wZgk7ptPcwyuJPGeytQrYpK -oqQP5VQjtfXvXyO2T9oKIxAeYFEw8ZXqCGn+hrdFAQJjGW/Eb4QQRv5rWKFAqptS -eA2IE0lkK2ador5U/bo7gPgiJu132af9VCotyo5Eamg+y0S4aNPnDMxADhljnq7U -0TFzQbzhcwmFruJxklF2nl1GbDfE+NVKzxlMBNMRUa8lLoxlWYeGGqPSAIt2ux53 -2nYkD2GL2twH62w84qIZuQ0+nsV+xoEwpXUMOOJHI+sOoD1ZrbEKNvfToS+uBSIv -0d7INXBROfhhXN2fNCK7e7Pkcn8bxuCDSNPzQQVUPnMFobnGYRiP98QErNG7pwyS -JjA8Y92MlFOg0SCr5Iy0GhOwPYKkBlqA4W0WhztS3+OeVmOGl/gXt8PZOV3XH0zG -qIjz9cuAxVaaBKz7/ZrghT2QKj0nu+msjPf1f0TzVdMP8osPKNTiL2JaDQCF/mfA -Q9B7MB9sI0YH46ifOPFFo6PrzaOvXGY8ObEuKpmiQB0BqOsuBhMLFQiH+OcXfcq6 -xwYxw4otXyF1iKhPPlp6YkTy+ICm6MoWSR1XMh+qLU6UuggtK5LK00QZq4kuD37v -Uxe5MR+IRgQQEQIABgUCVl2TSgAKCRA7Ok8Kx55bakvPAKCpbM3av9KV+7OCprWp -mTvMX4JTxgCgiRG4rXVGfcgwJ/1q79I9OA0MS1K0L0RhdmlkIE5vcnRoIChPVSBD -b21wU29jKSA8bm9ydGhAb3guY29tcHNvYy5uZXQ+iQI+BBMBAgAoBQJWWzJNAhsD -BQkJZgGABgsJCAcDAgYVCAIJCgsEFgIDAQIeAQIXgAAKCRDn6itTU1A3PBdRD/sF -QC4xH7qPv2cnPOry/qXSeVUW9iFsXDfKgiLDtryqxVw878E9Q0HLZfDUO97a+s4r -hH3hh6S9N4OVvJcoYX146Z1UQyV6KJBHLNcp0kXkEL/oOB0oEZDVw9StWdmuIx0w -0Ki/y/0jOKJaIfTWQy5T8AFIW32R8tQIdIwUr+N52mv4WiI/CibQ1xKo+oyvB4HM -Q2xNbSklSZOdnU9m81lotl6n9Ce6Phz7JoIE1NBjC8j14lZ41tbG6OYtr5UysOnH -dhGlM5DYDS6mOdXgeIXGxk6CbphYCapAiXOS/bhKmxBknJcoLcsgBhcmpM0FciNo -eyj7Rr+Viy0XGr4PU73IxbHx5auqqjvfHR/w+C5m1T/nS+5YpsMr1DtEy44Pctay -8oriMAgMcFz4PPqjpuYjubPAnpFM73QjzVLhKzHL9xodiUe6ycdV6zdUiWOOt9go -ZFVU5FpdvjrPWL3e4CTk1keOwFHP5w5LJ1PeZrKxdxMZQgoJIcH7pRNk/gAmpdDL -pF5diLp/ooAONOJMhVu0nfO8tErPwQgi6RuPjX23UtuTnAJlNTFTpP5LdTYRR4n+ -zCkb8C6ER2AkCA4VukscPjqEyv4+BmIqh2JZsnXZulTLKgqyxKP3leXxcfU6R8qZ -rTUIl+KG7805t/DPstAjn4QWQNQ74JKWYXtc7dPo/YhGBBARAgAGBQJWXZNKAAoJ -EDs6TwrHnltqn9MAoID72eIkZsu6YLQ8tyydTAa7GfuSAKDUu9QLb07OfvsbPqLM -DFbLxR74/LkCDQRWWzL0ARAA19834eY8CDheNnTu9G5l+CPLDMNV84akh0uxxuis -s7z7cgAeGkqeQnwMExqgam4J3ss1JAGfJZlVh/Aow6OYFIApWvszsieQXiYw9pi5 -/wC0Z+zgiciUMInhcvNTeWBS/xhnuYnVjN5TIyvxz2VJVK8iQiS9GBe/wR1MDqPq -REP61rb+xhdaHBhYr74roVRpNUOPB9I+4/AFUG5XMFs4YjjIb8kgCszTBFri6Hay -Ol2qtvD/ATth0lg229mPLzvZJmg7xkNGhtxiFaLZjbzni9pIMrsUlSAIhj7jyY+7 -RYrJzXwGOPdoo/BUdZETivXXxv5ZQzyJw5nqIJQmWBstGa7i3IonSTmJZSpCE6K5 -EkAHwksFxEvGCDnBdgDkXvCdiVA3guy6jQ+8D8H1R/6EoC7vUWk9wWwx6PLACFql -RSQzegap8iDhQ9o8feXMXkS585tPQN4j1CWWvzCahheaXrifM+9yza2l8nWyIDQx -V02AQYDEb65Twqrk/7LbJQvJ8oq24ScgRL8EFZunyEDvlFpBzGsZTahBhenIpME5 -jSff9OVt4kTuYYke+Q14+Ob/WzlgJtF3e2UyV1Xm+FUGsL5TDS8VgfPYJZeUSnEn -bhhv9bMlFFR+4HB/bWqJ58VVNUUoIc+D6ZuNT56YnJJ6DLXi1Es8qpx50gC1mM4s -1wUAEQEAAYkERAQYAQgADwUCVlsy9AIbAgUJCWYBgAIpCRDn6itTU1A3PMFdIAQZ -AQgABgUCVlsy9AAKCRBSfrgz+jrdwpaBD/9FjGA7RESbwpUAimzfhrRi7hBpUoiz -MCrrDKsjTByP/InXlR1O8127PkZQQaO3j3PL1ww1NWWr+qkct6N91DaooIjLKTR2 -7zcEKEQtv6k632uJSY53GiUi/UFXcVPKj6B+XyNiUytbCkfAyVPrY6H0kK8YNVzG -M9i0AB7RZ3gH2xaEZuOCYHNe7K3HLy023OcXSuiuU+mxYgBMOphq73uvlCL7TwHA -ym7BTagartTMGNFoLpUbYCbbHBHAkXTqF2ppWqfu/StmXN6kmzwOhYwdpcSJNrsv -V8Prf5rKVXJtpvq5t1Ux559NBX+CtrwwyshQbjR/BZhiyUZqvbQbBEorLU1mLvKM -VmT03h+Ha0K8GKDygJr15uwx1X/9wdsZr6do+OD2tM/dQzBJf/TPi28mLZ1HiR1h -LaYM1Ipn9ah6xPGdT8cpL7EM7st0fsDsmO1rU+/Jvfhdee7q/vfdQZkp/9e0YHRY -cygITVCurNGERUibjEtpjyjrztUDkVgDkc73OYOFtrR3ScrbleBSguWkx+wzUxnK -HaLCy+nDv2qVu9A4sSrJrOITDZih8mdl6Xzp3+iX9I1+Qg2pwKG1wKbgtLWFqvZs -IpOzP172I3G79zXV3Ka0jzQQjNnl/+W5AmBt2/Jw4M7V7xxVfXibrQS6tmrEWhcX -P5pMNwhRf1bvB1eQEACWYe3gIyEFT4KBrAhsfQI69X52Ex+CyeKzrUZRPisxrdEr -hnUHgBUm2XHvhS8xODlMj/EnNEg9aH/dXVvzFcSz0D+dGVDNWCN+bia2G7UVWyd/ -XG8DzRrmXvMQLkhfSl2ZL/d85PVL4HlYV0rJrqjquP/VndsRPjG5zTIfU7Gly7V5 -YpA8eUz5u8BQsGLsIMVg/0tzBJfSJU+RTQ2TL5B4sbStBzl9YzsmjQqdhQY1VX9+ -RmDtc/Nrqv7c8T4k1NzHUrb4qS6E9angSXOP3ZcDLsRPvAj1APyxEUV2RtXFngU0 -2ew9M/Ie9fEx5hU6T6HMjTFgcfnpF6NN466Aed/OuU5yaezqWfNr+an/Plg+6xUK -WoSKqq7x6o3Q3hk6fRu9sgPMgtmZYmBXvt93b14Hgzmhha81uKr5cURTYTiXERtX -SfJxarMfkZGyf4E2ABMHiI4zSJHF75rlHJEkNbGXiULXzzDBn6QK5iWiBRpVa6ID -YY2io6mDz0Ajcm2j+bcUMcIuqhqgPIUqNaxrCvOY4YKkqbmMpKMTxF/mOPoevg56 -3quK2yTATv/lbTvO/RFEos4ZQEG+4bsQ8gkzFlp1WUTisANCdYEWe4I3vkCmCCJx -lqhZJ01CVgzszeNTFKZkdYNsWx086pw6O1fCKrnhtoUK45dww/5lSH77qdple7kC -DQRWWzMOARAA51G7/MV+tpBeOMN+q/CRbGvEq105U1VVx0EoAFPi/Supa8PTA9o7 -cE+gdQX3OAkKpWV8d/evDtv7E6zERqEkf0D1KaPVPCJKIU1ffvfnRxe5Za0wPbAT -MMczgwSlLocoY8vEt1OwCp2yECNovRVigwAVdr4jfHQDaR1uAD1tGJgTTqr+vDA5 -xOtaF04LHqbZHV/bcWxBwK2STqtFn6RbZCfTDulcv9JNESr3Adxi426S68+qtPbC -5RUzERyGSaFmo5NelvV1Lbx8bYMs2By1VHed7YXtZbEK2djVNP6S8VlnzW43kkvr -1F5pNcFdOE5AD3YWMHdDdRXN8bDMhwwbKU6eeDzKnHr6hoAMEtiEE+ZP3mpkE6Sn -n3SnhIgrS7rlPZxrWpJ9Q9Eohy2XSdOZD/KImohJ7Afk6ni6MaqxfIZdAFu+f9C/ -8WgTXLT4mtd5sghro++KnH+PDIVDezQ26JJTadYcOzKaTyadoiZCttWnTZLmeYNw -m+RXRUm8hyQa58ZGPwGmdUTJyPJgHUxyjeSU/QG4mAGEXfeQzAAo56la2Hb3Kjg9 -jMjvtMD9XwqtWHJd63ih6VtXaIcyhHXFyA23YDDeodSA/2yT3Kg8tB1zNGU6xOYK -4s7wAo+mNJpCGr2nAIXj+oIFrKIGyM5qykGt23kEumLLqQd9l956ResAEQEAAYkC -JQQYAQgADwUCVlszDgIbDAUJCWYBgAAKCRDn6itTU1A3PK5qEACm21RTMohM+bnD -RyYmKz7g0Pjz+vmFtEW3YC4GoZBNSFyDP9B3WoxV37FGj6sUWkfCEXpby9OivSXA -upYxq4BYWJ7tIEb4wBsEbHaUxh81xyf4/bFu2RBSHofx/vEapvsBPqa3fTcS/mR4 -HPNez7PugSiwO9F9BUezP5G/TmrevOQI2XWSJwK7UoAyHzkqvN5inpjX6YOuiC0w -fZBy6vAcGoV+lQpRHh3cAX4bJ+BoB/hT4ZwGkA6YCaLv5MrhPLU3EqSfn5bnt6Fr -nLNYyCrsocGP6NfIMIxhbszayr+5Wt4xX/+wg0GA8xNy8ULHDoJJFjk+4BPrnvnX -/DJN4XM1o7L44SySOtSqHEHZJccQMXcaBFWHlI1HdI4C0DYASRq2a7hFVJuGFKuk -cGAjq2zKdBlFGQS5ZJkdzUDsAqgrlR/zRWACdPIo/0O+ZBkpI3K3tb35xksPa4Ch -WEaFEHHNp7X2TYIguxCSlQajtw3UggXUNj3NzQP3CkHxCHeuD0/3Ng/yBUhSlLqH -86BTd4NVNsMuc7+Od/o6Etatf+08fcKrWySLbJ6gyIxIRRiBlIMhYG5EhEs9izot -xmXPEC99X5upAYcl8wepXmAT6uS//HEeq1gLWhJ84t1m72XCgzsH8izR9EYsPuTB -XXtguDEwNLGck2RdUfmzGUpNOddyLLkCDQRWWzMoARAAthdLiAzdoDfFjS3PpbQu -aJYsPt2Lv8UyCPBx2QVl0I6ynY5U4RDnygRKtvOGupkqKwR8W3fzreFKPsJNlZ7c -Z1dKLImKXzw+DPvr+L7kKnW/F5i8hFtHgdMvqNRvty0COGtuvnU/oJ2mHi0hukvm -Y7jEZbx5M/t5dY2THtg88fn0+VppvL+LKzdNSpmiBX7EyrjIpBrS3MDts2ikhMF8 -ME2yDk1JVRdvWAMHW6Rgn4uhymrF7wbR3Gtgw3INqp1f2pBBNE2L4PbQchgqHEl7 -ikypcahU6ehsMmuGR2ueLoNF44j6qWJfCnSP5asaJ6sZJRpI2HYS0mtg60SsT52P -0iut++OOxi85sJtTwvGNFlU8/oLDRMTriHSreHV0ufw0qifO3McHQjSZ9Wx1ka+l -d+ewnPFvPpxxjXIpMxw9OGOL++pyztf3G7or85ewzogR47rtFZJ5g73AHKnMHcL1 -X12LXOVvpPfLuEFDJ7q4aLwvxehiTzHGq1ARYRQHrOJnyUE2KYerD/Aqa2imX/gE -dEgw01uZkhgP9H4DaM2h0RLCWJ4LaFamce9cdWZsYibeJwr+alRP29Q3klwx9CIw -FawUftThv3j59ZJQi0bnkIN9/NDXBkwxQGvbyWv0x6yLmtIzRNXdCHzNUnTbCh5V -Vyt9C6owqCf464+L69vOJYMAEQEAAYkCJQQYAQgADwUCVlszKAIbIAUJCWYBgAAK -CRDn6itTU1A3PJEEEAC5bvKxKzkw85IDvMGDKVviQ0V+JGriEouslFB1A1voVS+D -ulhXdpvmVGSKWB7B38fO2lcyImnqV+TDEA4pa2MX2hYRN6SeFtSs2aS51Iziqhve -3uCs96t2zAr/pKl72yTcK/qA8Zz6Why17pksDWMlwkWncFGWQNPp9Zn0Vz6DF2RS -JawZtdccHy0VfA2yx2XtvIoQMIGYT8LHu+uUFzbI3kWofUwSxNUeAaAuCWgYXJrT -D3WpZ7xcGN8MH3laxq8UQlYuBGtqmZwc4eSddY2bayP2+cT+5pihekvhPO9hrQfP -Db/Xg4A+gRsek1gkCjWGT8peoPm5TWahdEMLEYAyWirfFa2fFHkq199sTjOWAolI -D0vVW7l2M0I6dFiZwoYyQL0feUcvFKEe3i1k/684hhYQcWWaVnW+GbwsWIQ7Nrb+ -uoJ8D7JTt7K2VM8y3LFiSzWCl5aFMFQKc+H1youb47GnzlU9R9OjKVt7g7japSB4 -UmbnPdwhYsr8QYOq2KxKo/Wl1A2k+pL85qdJdnS+lXzl7nS3MlDNLRzk/1Hg+IKo -cCRRHYCeAZDU5UMxi0nonfT+060i2rLPSd7o0bstG7gb1pD99rKxL57M7uy+WBnk -YobtRLhWHvHyWS4dKqiteeTwAqG2ZFOq98KCu1LXMKj42HqwOtB3L23HlhqVyA== -=8e4G ------END PGP PUBLIC KEY BLOCK----- -pub 4096R/8BABDD6C 2015-10-10 [expires: 2017-10-09] -uid Javen O'Neal -uid Javen O'Neal -sub 4096R/309424B4 2015-10-10 [expires: 2017-10-09] - ------BEGIN PGP PUBLIC KEY BLOCK----- -Version: GnuPG v2.0.22 (GNU/Linux) - -mQINBFYZkgYBEAC28IT8XHE4bm5iXgL7COy7hmh8FS67hwfnEV08rm3f8tflYxe+ -tYdRUI8y5UIFJyX2138GsV7sjV+pBiEq02xEU5pl2/AfXF+GmtW7ErS2Tk4iQ0id -SEcnyvim5LtaFYyMjYC1mzr0MaiJqWHjw6Lxjjep3s40coAkauRIcnJQ0s1YQIqk -BPlAl0rDILE8Lix+IVokUxTizh9popwDW0T/z6gzdKDeE5FPeKYWPvs34bKwe2vm -KqL2qmBh3Tk7MbtKYD79pGzYkNSyVmfWIDTjc++lNmDWYt0QN6YlaXoV4ZCAbLk+ -raHU+5aKduZNnP25FnwTyt/Xm4Pl8RdROBzsmese2UuYrfsPaZrZkhhekE7Ttjk1 -EqTob/LmgR7KSwWGT6Y9PAyROIs50yw5T7wMjdz0+C9SUZHK5lhPnFawyamWM1de -Y/f5vEvbI2Xap614bg6EPObPSQh/1r6J+7EmrbSqRE0W8FlSK2cWmB8l724lBG9f -Y5bma/F5g8eL4xcOGkaw2VCBu3i/IRUoHBP1ndkAQfIHmlGlWFc9u6PtmFyZHJJ7 -Boks8g8M9aOcUvO+K/+gBWzGXO8n/NG10iItX9ubSFbvXCKJgK7cFXDdC8F/uHXO -vfDSTrwBffm7Czyxx8AgDHxGMysNCe5Pet7bU6bZL4ANnCPfMhgN7pp5bQARAQAB -tCBKYXZlbiBPJ05lYWwgPG9uZWFsakBhcGFjaGUub3JnPokCPwQTAQIAKQUCV+cS -OwIbAwUJA8GMagcLCQgHAwIBBhUIAgkKCwQWAgMBAh4BAheAAAoJEOZnesaLq91s -DN4P/36DX8zeM8PK9x9lb3DogipXefiMyWOZb+p64Ah6iFIxDoTNP+meG3eiQP11 -T02TeI8tZKG6kuFM6fQb3GE6g/2TgHeWnrhek2KfHbOh6/nWvrAnsaEiu+vIBIFL -kiO0ydtu1DdNjWB0PR3bcnxF1GOX38cx37SjMR3n/eaIFnHqENzHNZgZ0sv38pYt -c0FDeoqpO89aAiCi+IWuLAhYFzU+GFdHxteFMtYGYDe5iI4EHjciIO4/Mq9MyQce -rYS/ADCJV0SWS+mPk3czKRdpklZiRoOqSiZcyTUJ7H2NFcdQuYjpLlmNvt0c95bR -fxaOhFWSSvZzkcZXr4u82VDc0rSvXW1q2vFZpbYJq7uDQZpBlkLBwlZ9gDaXHa6Y -5JB7RGWMmA+mfwSmfKxfCR0HdTldNsSic20bUlJjVjKkZR+Mco5SmAW0nb1OkpD7 -lDCx6x8aunuFbf2SGnIZxtGxm31rXE7bTib4wE5X9EECLfg9hTJxPdDqvKfRBVBQ -ZVtPdq3jzyh6CxM/bygfmUjqdP91hS+wfXYq1W7d4e8EphkCiqdMXgclFEbdGp8e -+8BDvbCIchLzZ5wOxL4Ntwo4bL2Zn0IJ/K6K1WoOnMzq+6xWZOGRJ28v8go2VqO/ -o0zWgSm6zEz2kAE9s9Y1by0xL40byg0AdJzG4h1cRPOsYeB0tCNKYXZlbiBPJ05l -YWwgPGphdmVub25lYWxAZ21haWwuY29tPokCQQQTAQIAKwIbAwUJA8GMagYLCQgH -AwIGFQgCCQoLBBYCAwECHgECF4AFAlfnEmUCGQEACgkQ5md6xour3WzZxBAAjLkr -z4Roxig47WGax6ppGqIGLTNEPPvNluIgtwZYfTW6MrzQIquju4o0QEIb8mOW9uke -LnR284t/5CU36EuVan0wWYwrwIJWtbZGz14GgtHsRyErllmYWKa0aYJ3kgY8JuNT -bK40g9RlrdLsYntwFlWQB9rL4nBPoWVWRllWOMcbhdF6/p9r2EmKO/CsTYdfolEh -dKdEtSgshQgvZxfgalanqb69/zc81RLpUQ0q1uiedrN0ghNd1+XCXeopKeeAoW9Y -LOIlQ3ALz9t+A3w4Ft5h3RZBHPwSPAgRv4fDv3y016rnPSna6wC5atlW9b1jxcnS -myP3kNcAXJDWwpQmMwYG8NJGCANwYRUNGcXlMvYbMpmuYHqc7kf+AbkG3H8Z1ktJ -jfwK8aw2ZX/AlINIQZ7fVJLDOkMapbjApUNOc7UoXx9Z8qXiVDizisRCJxy2Kj9h -pR+XMIwgPwCTgmQ+W+hQ50h7S4H9VVSfEe+H/+k6kHhRxEAZq5NGIzC7Mh8xvyHa -EII5tAS8fQwfnJ75URITUp2Vrdry5aDEZ90AIlYiQVuhUwFeNimjKOr8i9Zse7JC -MucIcmBsvwThVn22e6x14cNfc4KwqcWSQvxMuzqejHq4WTMf9Ln15G7nVMulyUTZ -hfJ4Spr45BEr+4UDMNqwIRQdIMXHa+JZGs3Nj7SJAhwEEwEKAAYFAlYaCkgACgkQ -ykkN1QqzdQMHbBAAm6Y0PaDBlhiYd+nCaxpNJGG0h2F/2nPLXNaGdTQSICD8B97i -J1Hvio0mEHnkbbm6e2s0rvxervgy4BuxgwzWgguaLQsALgyGpY2pHzsQAVQVVq6H -PQdwSOy731oO7R7CeJB/UIT02ne5WnLxxUN1e4qYLHp0+QFXOd4TPuTwPEG/Gewr -EVJN4C2k373eSsWwvXCBYe5UDLqPHrVTYnyU8uFmi4yOMbmIyyb1x7At6adc8FWQ -DQQt/0YElDe3m4Xmco4OMBem8i7QFchinhLIZPwNCR4aGrhbQYuq7C8JOWjEGFg8 -k322fOwAEopr3+dHemToGde5j2u7JnatAeu7CwNVMY4Z9s/wUChP7gXlNenKIgeD -hUsG9RroqpXTLKmjz+2fSCGT5o2rBgwRnwpTcDaFWZlVzb1r/KQxTRsEkvDfSU1Y -jixoqFJYBj/2fhl1EPF7gb5WK8tBZ8PqhPaJwXAynzSGEG6QLbYwxCoKfVvl8PZj -SGg4Dmca6QpUskYwuiMMZhJJDNxKn5t2NZFEilZVaITRtNxtyRm2xvbcPXsSjAdo -VXCqKX777rfPryPW4Yjw55a7uaQQe3M6d4ndgVP491tGBMfBTHa7hKei/R1S106C -2R+rrE3o42WnhM3AarlWRqaHzuJQuofAjtRv19Ibk6ahK/qFuZBBFAWnUiSJARwE -EAECAAYFAldOVSMACgkQ28vfLzZwP7I7OQgAnDlCoagIdBNHxGAPieZt5bJTj8Mv -DtoxOAJtUjbJPTu5iw23pi2b83xmYCNQQkJ86IiSX56kILr9SP1uscChjM8aqwBK -H5vMWAzHxdbTNFrjmCm/NAF+6ArFi5snlWf3phLPUIdhNhGA4jhklWMuy6rflujy -BCgtZSh0VbaU/02ir3/QXBc331VN+qbXoCxD8lFagj0rg4GLCWFFCPJUeAr/SmIp -v28UIVNDUI9lyCB4G3utjBhDpo0LHv+X+AXkD5V9kwZBE5NzahL/3AWjm9B9Vqb1 -JO1PVYv7sXqG25+xRMJssnsoGQYH75LSwoau3Yo1l8J35LOLYPUQfO9NYokCPgQT -AQIAKAUCVhmSBgIbAwUJA8GMagYLCQgHAwIGFQgCCQoLBBYCAwECHgECF4AACgkQ -5md6xour3WxiVxAAkN6x14p905j7NUB0Ky/p3da9KeIp5uAyTR/CcE9pLvvdSMyd -xH8nE35EyHT84l7/yQHQ0wXxAFilBSGBt3C6Sth8J+11zxesUeDmJ1dX2Z0xRFz+ -qO7MBJ2ccU9pK20niPgaKuBBZsDoye9wKtli2UxOCid26CeLs5Y1gAcPuY9Hmzh3 -FnGhzrI5dP0HcE9lQXKA04vqviT1hxd+LlleCij1ItQR0ZYhV7z4SZp66vEfnh/R -mtaC5L0ZFfoAartLSVX6a16dQDqbLy/ukecQeQ2qWo+IkNQe+p23GR1FihBZeHxC -G+L9igu/cFgRLubMqHelwVCwL12Uazb2tG2zAnaTi5WgU0urvLqMRCuyQ40KlQ4h -ly6oOEKWcwGBhfTD+baBsHLfrVdikz4IiV8+7oQsb/xyuQEz66FYLptDpX3obgRR -ls0xjJ1YlZsmFg/NCJaAoPILBnS8wpbQp+T8yf9YcfczsMs9wALtM2rkLZqS6dn0 -yBekDL3ZsuiS7Ot6WM351nKCvDtpe1hF4CAkE2xhCLdRyvDHmbq4vBf0nyAvzTCI -hUzgQeUKDDjxcmH1yxGNXswlfllqK6QkI9HnV/AuTI6nEjlBRNmtLg7SijHmuAZd -+X8Sy/CibqCgY0J51FlylH+Cx8qQUaUB81KKimCohTejzrfUm3xUOvautFG5Ag0E -VhmSBgEQAOQbxM1ZydIHIlnKx6LEmQdujX7Ns60NxrGdhLLHoJusuTutjTEt50Ex -MHhn/PjYVeK1JU/gTh0fPM7il9xwj+cUBbOtBQ+E2sVXXMSBMj93+6ivLBVesq27 -R3ls63EMKHGcyYsIqHafBG9EvBwHBj+UNG3qKyEZv/NaX6UUoEYrvI4yx+z+ahew -K5RMAZ1qNUqtZfsDlKW3SF3rgRBBmVWowim1G6tB0HVor4YRA/iHwH6WIu04QqzG -A0uQpvptVJ0i1Hd9SoXisJUsovXSRTqj7+eFbILGywbvM2NYwF52lW9jbz3gu/Hb -O3uPY0xdshW/8F92FZRXzuMMv3O6I5SaVRRJE2oJVJHtteEpyrbkCqhaLzkSiNxf -sqzOw03gYICnxSDY3fqKBRKq84DMbiXbv4DwqeXWZXR2Yhs85Rn5cgoNqg5oyNwy -PlQOfqZzoiDle3SWs41pCM2po1tGgZXkeRqNedRI9V+c8ZacOrTPnjRL0Ae475n4 -EFP3Ajur7UaXRe57AiSn4B30E5/D0HC0SeeRWacFeAHJ8WGvf6wXNGoAmtJL+TRJ -iSqNVjZ1EhuwYJpjUgPEfesXyCc5U6qkHMHcn0rXVteG4mrn0/191CPtfamxpDM9 -hhTZ0WEbwFRwC41QQnRCO6EQfkPwZLC9BtSSuRVCI30617HiOFwDABEBAAGJAiUE -GAECAA8FAlYZkgYCGwwFCQPBjGoACgkQ5md6xour3WwC1Q//QnYoOLfPiSI/NVI6 -agjCECNdtpUfdiGy7sEH3FYpNQGu8LDahcmTsxxcp2LeXjZIhuJt/dRPAMC/teQq -ihZvdz5iuYwqg8I7ZtZh+qxqxvjwOwtKnELpoMpZyK81v4C2oLQAzNdMC18QTBt+ -L3RSMDdnPJ92GsCoYSGdLT0Jy16l/ShUQZ85EFUEjzFEDVnlLKpfZoqVCIULe0nj -NCyNY6txc6X4uChCB5ZtsLaHgUTm0I+wb+AX0wbEDELyldzkbfVPTxbCMQgkPx0E -W7ufcM3wx9sGT9I3FNOqZKHa8xq08be7z6OJZlsuw1NfeWG+UF9f6KZjH/zxIdtY -IDoVReAU5g/LfOQTHXpg+7eArlf/hVh57uFjPJxdh8wqKfFzIVSoksCwv3w3Hrca -7eh7Po46U6Tt6icWInBUthvOja0CgDojw+mm3GKvGMif/9YZXY/RHcc3t2CQDp/c -Shzcaly9QYj0eDujTQj7XFd/AAwdj8YWA4Ha2Peh4/oK4ugt7pKwt51MvYzSYDel -NFTn1hbTXTcj21i2/C9I6oqIhKt8c+St6Tge7PkGjq5BRqvY2L/IJmS5TmSerciL -bpjAhwE2YmGQ7oB+3V798HtAmceRNf8AY0GWrZswJlg7xUn+WJNwQ9uIHI1fxYHx -2Nr+AmDDs6ZOEI5zhwxioePw/Cg= -=9lKb ------END PGP PUBLIC KEY BLOCK----- diff --git a/build.gradle b/build.gradle deleted file mode 100644 index 4acabe0f1..000000000 --- a/build.gradle +++ /dev/null @@ -1,314 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -buildscript { - repositories { - maven { url "https://plugins.gradle.org/m2/" } - } - - dependencies { - classpath 'me.champeau.gradle:japicmp-gradle-plugin:0.1.2' - classpath "org.sonarsource.scanner.gradle:sonarqube-gradle-plugin:2.2.1" - } -} - -// Only add the plugin for Sonar if enabled as it requires Java 8 -if (project.hasProperty('enableSonar')) { - println 'Enabling Sonar support' - apply plugin: "org.sonarqube" -} - -// For help converting an Ant build to a Gradle build, see -// https://docs.gradle.org/current/userguide/ant.html - -ant.importBuild 'build.xml' - -/** - -Define properties for all projects, including this one - -*/ -allprojects { - apply plugin: 'eclipse' - - task wrapper(type: Wrapper) { - gradleVersion = '3.4.1' - } - - task adjustWrapperPropertiesFile { - doLast { - ant.replaceregexp(match:'^#.*', replace:'', flags:'g', byline:true) { - fileset(dir: project.projectDir, includes: 'gradle/wrapper/gradle-wrapper.properties') - } - new File(project.projectDir, 'gradle/wrapper/gradle-wrapper.properties').with { it.text = it.readLines().findAll { it }.sort().join('\n') } - ant.fixcrlf(file: 'gradle/wrapper/gradle-wrapper.properties', eol: 'lf') - } - } - wrapper.finalizedBy adjustWrapperPropertiesFile -} - -/** - -Define things that are only necessary in sub-projects, but not in the master-project itself - -*/ -subprojects { - //Put instructions for each sub project, but not the master - apply plugin: 'java' - apply plugin: 'jacoco' - - // See https://github.com/melix/japicmp-gradle-plugin - apply plugin: 'me.champeau.gradle.japicmp' - - version = '3.16-beta3' - ext { - japicmpversion = '3.15' - } - - tasks.withType(JavaCompile) { - options.encoding = 'UTF-8' - } - - sourceCompatibility = 1.6 - - repositories { - mavenCentral() - } - - jar { - manifest { - attributes 'Implementation-Title': 'Apache POI', 'Implementation-Version': version - } - } - - test { - // Exclude some tests that are not actually tests or do not run cleanly on purpose - exclude '**/BaseTestBorderStyle.class' - exclude '**/BaseTestCellUtil.class' - exclude '**/TestUnfixedBugs.class' - exclude '**/TestOneFile.class' - - systemProperties = System.properties - - // set heap size for the test JVM(s) - minHeapSize = "128m" - maxHeapSize = "768m" - - // show standard out and standard error of the test JVM(s) on the console - //testLogging.showStandardStreams = true - - // http://forums.gradle.org/gradle/topics/jacoco_related_failure_in_multiproject_build - systemProperties['user.dir'] = workingDir - - systemProperties['POI.testdata.path'] = '../../test-data' - //systemProperties['user.language'] = 'en' - //systemProperties['user.country'] = 'US' - } - - test.beforeSuite { TestDescriptor suite -> - System.setProperty('user.language', 'en') - System.setProperty('user.country', 'US') - } - - jacoco { - toolVersion = '0.7.8' - } - - // ensure the build-dir exists - projectDir.mkdirs() - - if (project.hasProperty('enableSonar')) { - sonarqube { - properties { - // as we currently use build// as project-basedir, we need to tell Sonar to use - // the root-folder as "basedir" for the projects - property "sonar.projectBaseDir", "$projectDir/../.." - } - } - } -} - -project('main') { - sourceSets.main.java.srcDirs = ['../../src/java'] - sourceSets.main.resources.srcDirs = ['../../src/resources/main'] - sourceSets.test.java.srcDirs = ['../../src/testcases'] - - dependencies { - compile 'commons-codec:commons-codec:1.10' - compile 'commons-logging:commons-logging:1.2' - compile 'org.apache.commons:commons-collections4:4.1' - - testCompile 'junit:junit:4.12' - } - - // Create a separate jar for test-code to depend on it in other projects - // See http://stackoverflow.com/questions/5144325/gradle-test-dependency - task testJar(type: Jar, dependsOn: testClasses) { - baseName = "test-${project.archivesBaseName}" - from sourceSets.test.output - } - - configurations { - tests - } - - artifacts { - tests testJar - } - - // TOOD: we should not duplicate this task in each project, but I did not figure out how to inject the artifactId for each project - task japicmp(type: me.champeau.gradle.ArtifactJapicmpTask, dependsOn: jar) { - baseline = 'org.apache.poi:poi:' + japicmpversion + '@jar' - to = jar.archivePath - onlyModified = true - onlyBinaryIncompatibleModified = true - failOnModification = false - txtOutputFile = file("$buildDir/reports/japi.txt") - htmlOutputFile = file("$buildDir/reports/japi.html") - } -} - -project('ooxml') { - sourceSets.main.java.srcDirs = ['../../src/ooxml/java'] - sourceSets.main.resources.srcDirs = ['../../src/ooxml/resources', '../../src/resources/ooxml'] - sourceSets.test.java.srcDirs = ['../../src/ooxml/testcases'] - - // for now import the ant-task for building the jars from build.xml - // we need to rename the tasks as e.g. task "jar" conflicts with :ooxml:jar - ant.importBuild('../../build.xml') { antTargetName -> - 'ant-' + antTargetName - } - compileJava.dependsOn 'ant-compile-ooxml-xsds' - - dependencies { - compile 'org.apache.xmlbeans:xmlbeans:2.6.0' - compile 'org.apache.commons:commons-collections4:4.1' - compile 'org.apache.santuario:xmlsec:2.0.6' - compile 'org.bouncycastle:bcpkix-jdk15on:1.54' - compile 'com.github.virtuald:curvesapi:1.04' - - // for ooxml-lite, should we move this somewhere else? - compile 'junit:junit:4.12' - - compile project(':main') - compile project(':scratchpad') // TODO: get rid of this dependency! - compile files('../../ooxml-lib/ooxml-schemas-1.3.jar') - compile files('../../ooxml-lib/ooxml-security-1.1.jar') - - testCompile 'junit:junit:4.12' - testCompile project(path: ':main', configuration: 'tests') - } - - // TOOD: we should not duplicate this task in each project, but I did not figure out how to inject the artifactId for each project - task japicmp(type: me.champeau.gradle.ArtifactJapicmpTask, dependsOn: jar) { - baseline = 'org.apache.poi:poi-ooxml:' + japicmpversion + '@jar' - to = jar.archivePath - onlyModified = true - onlyBinaryIncompatibleModified = true - failOnModification = false - txtOutputFile = file("$buildDir/reports/japi.txt") - htmlOutputFile = file("$buildDir/reports/japi.html") - } -} - -project('examples') { - sourceSets.main.java.srcDirs = ['../../src/examples/src'] - - dependencies { - compile project(':main') - compile project(':ooxml') - } -} - - -project('excelant') { - sourceSets.main.java.srcDirs = ['../../src/excelant/java'] - sourceSets.main.resources.srcDirs = ['../../src/excelant/resources'] - sourceSets.test.java.srcDirs = ['../../src/excelant/testcases'] - - dependencies { - compile 'org.apache.ant:ant:1.9.4' - - compile project(':main') - compile project(':ooxml') - - testCompile project(path: ':main', configuration: 'tests') - } - - // TOOD: we should not duplicate this task in each project, but I did not figure out how to inject the artifactId for each project - task japicmp(type: me.champeau.gradle.ArtifactJapicmpTask, dependsOn: jar) { - baseline = 'org.apache.poi:poi-excelant:' + japicmpversion + '@jar' - to = jar.archivePath - onlyModified = true - onlyBinaryIncompatibleModified = true - failOnModification = false - txtOutputFile = file("$buildDir/reports/japi.txt") - htmlOutputFile = file("$buildDir/reports/japi.html") - } -} - -project('integrationtest') { - sourceSets.test.java.srcDirs = ['../../src/integrationtest'] - - dependencies { - compile 'org.apache.ant:ant:1.9.4' - - compile project(':main') - compile project(':ooxml') - compile project(':scratchpad') - compile project(':examples') - - testCompile 'junit:junit:4.12' - } - - test { - // exclude these from the normal test-run - exclude '**/TestAllFiles.class' - exclude '**/*FileHandler.class' - exclude '**/RecordsStresser.class' - } - - task integrationTest(type: Test) { - // these are just tests used during development of more test-code - exclude '**/*FileHandler.class' - exclude '**/RecordStresser.class' - } -} - -project('scratchpad') { - sourceSets.main.java.srcDirs = ['../../src/scratchpad/src'] - sourceSets.main.resources.srcDirs = ['../../src/resources/scratchpad'] - sourceSets.test.java.srcDirs = ['../../src/scratchpad/testcases'] - - dependencies { - compile project(':main') - // cyclic-dependency here: compile project(':ooxml') - - testCompile 'junit:junit:4.12' - testCompile project(path: ':main', configuration: 'tests') - } - - // TOOD: we should not duplicate this task in each project, but I did not figure out how to inject the artifactId for each project - task japicmp(type: me.champeau.gradle.ArtifactJapicmpTask, dependsOn: jar) { - baseline = 'org.apache.poi:poi-scratchpad:' + japicmpversion + '@jar' - to = jar.archivePath - onlyModified = true - onlyBinaryIncompatibleModified = true - failOnModification = false - txtOutputFile = file("$buildDir/reports/japi.txt") - htmlOutputFile = file("$buildDir/reports/japi.html") - } -} diff --git a/build.xml b/build.xml deleted file mode 100644 index 4edd09dc1..000000000 --- a/build.xml +++ /dev/null @@ -1,2766 +0,0 @@ - - - - - - The Apache POI project Ant build. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - project.setProperty(attributes.get("name"), attributes.get("value")); - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - This is POI ${version.id} - Java Version ${ant.java.version}/${java.version} - Timestamp ${DSTAMP} - The main targets of interest are: - - clean Erase all build work products (ie. everything in the build directory) - - compile Compile all files from main, ooxml and scratchpad - - test Run all unit tests from main, ooxml and scratchpad - - jar Produce jar files - - jar-src Produce source-jar files - - assemble Produce the zipped distribution files - - site Generate all documentation (Requires Apache Forrest) - - dist Create a distribution (Requires Apache Forrest) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - var rel = ("REL_"+project.getProperty("version.id")).toUpperCase().replace(/\W/g,"_"); - if (rel.search(/BETA/) == -1) rel += "_FINAL"; - project.setProperty("RELEASE_TAG", rel); - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - org.apache.xmlbeans.XmlBeans.getContextTypeLoader() - org.apache.poi.POIXMLTypeLoader - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Please install Apache Forrest (see - <https://forrest.apache.org/index.html>) and set the - FORREST_HOME environment variable! - - - - - - - - - - - - - - - - - - - Broken links: - - - - - - - - - - - - - - - - - - - - - - - - - - POI API Documentation]]> - - Copyright ${tstamp.year} The Apache Software Foundation or - its licensors, as applicable.]]> - - - DDF - Dreadful Drawing Format - - - - HPSF - Horrible Property Set Format - - - - - SS - Common Spreadsheet Format - - - - HSSF - Horrible Spreadsheet Format - - - - XSSF - Open Office XML Spreadsheet Format - - - - - SL - Common Slideshow Format - - - - HSLF - Horrible Slideshow Format - - - - XSLF - Open Office XML Slideshow Format - - - - - HWPF - Horrible Word Processor Format - - - - XWPF - Open Office XML Word Processor Format - - - - - HDGF - Horrible Diagram Format - - - - XDGF - Open Office XML Diagram Format - - - - - POIFS - POI File System - - - - Utilities - - - - Examples - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Maven POMs are located in ${dist.dir} - Use ant dist-nexus to deploy the artifacts in the remote repository - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Creating Maven POMs - - - Distribution located in ${dist.dir} - Use "ant dist-checksum" to create md5/sha1 checksums and GPG signatures - - - - - - - - - - - - - - - - - - - - - Maven ant tasks not found. - Please make sure the maven-ant-tasks jar is in ANT_HOME/lib, or made - available to Ant using other mechanisms like -lib or CLASSPATH. - - You can download the Maven Ant Tasks from https://maven.apache.org/ant-tasks/download.html - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ${rat.reportcontent} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - org.apache.poi - @{artifactId} - - ${version.id} - ${version.id} - - ${version.id} - - ${lastUpdated} - -]]> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - var relCurr = new String(project.getProperty("version.id")); - var relNext = relCurr.replace(/[0-9]+$/, function(lastNum){ return new String(new Number(lastNum)+1); }); - if (relNext.search(/beta/i) == -1) relNext += "-beta1"; - project.setProperty("rel_next", relNext); - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - var bytes = Number(attributes.get("bytes")); - var mega = String((bytes/(1024.0*1024.0)).toFixed(2)); - project.setProperty(attributes.get("property"), mega); - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ${rel_date} - POI ${version.id} available -

The Apache POI team is pleased to announce the release of ${version.id}. - Featured are a handful of new areas of functionality and numerous bug fixes.

-

A summary of changes is available in the - Release Notes. - A full list of changes is available in the change log. - People interested should also follow the dev list - to track progress.

-

- The POI source release as well as the pre-built binary deployment packages are listed below. - Pre-built versions of all POI components - are available in the central Maven repository under Group ID "org.apache.poi" and Version - "${version.id}". -

-
Binary Distribution -
    -
  • poi-bin-${version.id}-${file_date}.tar.gz - (${bin-tar-size} MB, signature (.asc)) -
    - MD5 checksum: - ${bin-tar-md5} -
    - SHA1 checksum: - ${bin-tar-sha1} -
  • -
  • poi-bin-${version.id}-${file_date}.zip - (${bin-zip-size} MB, signature (.asc)) -
    - MD5 checksum: - ${bin-zip-md5} -
    - SHA1 checksum: - ${bin-zip-sha1} -
  • -
-
-
Source Distribution -
    -
  • poi-src-${version.id}-${file_date}.tar.gz - (${src-tar-size} MB, signature (.asc)) -
    - MD5 checksum: - ${src-tar-md5} -
    - SHA1 checksum: - ${src-tar-sha1} -
  • -
  • poi-src-${version.id}-${file_date}.zip - (${src-zip-size} MB, signature (.asc)) -
    - MD5 checksum: - ${src-zip-md5} -
    - SHA1 checksum: - ${src-zip-sha1} -
  • -
-
- -]]>
-
-
diff --git a/doap_POI.rdf b/doap_POI.rdf deleted file mode 100644 index c88f10f75..000000000 --- a/doap_POI.rdf +++ /dev/null @@ -1,142 +0,0 @@ - - - - - - 2006-01-26 - - Apache POI - - - Java API To Access Microsoft Document File Formats - APIs for manipulating various file formats based upon Open Office XML (ECMA-376) and Microsoft's OLE 2 Compound Document formats using pure Java. Apache POI is your Java Excel, Word and PowerPoint solution. We have a complete API for porting other OOXML and OLE 2 Compound Document formats and welcome others to participate. - - - - Java - - - - - Apache POI 3.15 - 2016-09-21 - 3.15 - - - - - Apache POI 3.14 - 2016-03-05 - 3.14 - - - - - Apache POI 3.13 - 2015-09-29 - 3.13 - - - - - Apache POI 3.12 - 2015-05-11 - 3.12 - - - - - Apache POI 3.11 - 2014-12-21 - 3.11 - - - - - Apache POI 3.10.1 - 2014-08-18 - 3.10.1 - - - - - Apache POI 3.10 - 2014-02-08 - 3.10 - - - - - Apache POI 3.9 - 2012-12-03 - 3.9 - - - - - Apache POI 3.8 - 2012-03-26 - 3.8 - - - - - Apache POI 3.7 - 2010-10-29 - 3.7 - - - - - Apache POI 3.6 - 2009-12-14 - 3.6 - - - - - Apache POI 3.5 - 2009-09-28 - 3.5 - - - - - Apache POI 3.2 - 2008-10-19 - 3.2 - - - - - - - - - - - POI Committers - - - - - diff --git a/jenkins/create_jobs.groovy b/jenkins/create_jobs.groovy deleted file mode 100644 index 0b2958b9b..000000000 --- a/jenkins/create_jobs.groovy +++ /dev/null @@ -1,339 +0,0 @@ -// This script is used as input to the Jenkins Job DSL plugin to create all the build-jobs that -// Apache POI uses on the public Jenkins instance at https://builds.apache.org/view/POI/ -// -// See https://github.com/jenkinsci/job-dsl-plugin/wiki for information about the DSL, you can -// use http://job-dsl.herokuapp.com/ to validate the code before checkin -// - -def triggerSundays = ''' -# only run this once per week on Sundays -H H * * 0 -''' - -def poijobs = [ - [ name: 'POI-DSL-1.6', - // workaround as Sourceforge does not accept any of the SSL ciphers in JDK 6 any more and thus we cannot download this jar - // as part of the Ant build - addShell: 'wget -O lib/findbugs-noUpdateChecks-2.0.3.zip http://downloads.sourceforge.net/project/findbugs/findbugs/2.0.3/findbugs-noUpdateChecks-2.0.3.zip?download=' - ], - [ name: 'POI-DSL-1.8', jdk: '1.8', trigger: 'H */12 * * *' - ], - [ name: 'POI-DSL-OpenJDK', jdk: 'OpenJDK', trigger: 'H */12 * * *', - // H13-H20 (Ubuntu 16.04) do not have OpenJDK 6 installed, see https://issues.apache.org/jira/browse/INFRA-12880 - slaveAdd: '&&!beam1&&!beam2&&!beam3&&!beam4&&!beam5&&!beam6&&!beam7&&!beam8&&!H12&&!H13&&!H14&&!H15&&!H16&&!H17&&!H18&&!H19&&!H20&&!H21&&!H22&&!H23&&!H24&&!qnode1&&!qnode2&&!qnode3&&!ubuntu-eu2&&!ubuntu-eu3&&!ubuntu-us1', - // the JDK is missing on some slaves so builds are unstable - skipcigame: true - ], - [ name: 'POI-DSL-1.9', jdk: '1.9', trigger: triggerSundays, - properties: ['-Dmaxpermsize=-Dthis.is.a.dummy=true', - '-Djava9addmods=--add-modules=java.xml.bind', - '-Djavadoc9addmods=--add-modules=java.xml.bind', - '-Djava9addmodsvalue=-Dsun.reflect.debugModuleAccessChecks=true', - '-Djava9addopens1=--add-opens=java.xml/com.sun.org.apache.xerces.internal.util=ALL-UNNAMED', - '-Djava9addopens2=--add-opens=java.base/java.io=ALL-UNNAMED', - '-Djava9addopens3=--add-opens=java.base/java.nio=ALL-UNNAMED', - '-Djava9addopens4=--add-opens=java.base/java.lang=ALL-UNNAMED', - '-Djava9addopens5=--add-opens=java.base/jdk.internal.ref=ALL-UNNAMED', - '-Djava.locale.providers=JRE,CLDR'], - skipcigame: true - ], - [ name: 'POI-DSL-IBM-JDK', jdk: 'IBMJDK', trigger: triggerSundays, - // some OOXML tests fail with strange XML parsing errors and missing JCE unlimited strength requirements - disabled: true, skipcigame: true - ], - [ name: 'POI-DSL-old-Xerces', trigger: triggerSundays, - shell: 'mkdir -p compile-lib && test -f compile-lib/xercesImpl-2.6.1.jar || wget -O compile-lib/xercesImpl-2.6.1.jar http://repo1.maven.org/maven2/xerces/xercesImpl/2.6.1/xercesImpl-2.6.1.jar\n', - // the property triggers using Xerces as XML Parser and previously showed some exception that can occur - properties: ['-Dadditionaljar=compile-lib/xercesImpl-2.6.1.jar'], - // workaround as Sourceforge does not accept any of the SSL ciphers in JDK 6 any more and thus we cannot download this jar - // as part of the Ant build - addShell: 'wget -O lib/findbugs-noUpdateChecks-2.0.3.zip http://downloads.sourceforge.net/project/findbugs/findbugs/2.0.3/findbugs-noUpdateChecks-2.0.3.zip?download=' - ], - [ name: 'POI-DSL-Maven', trigger: 'H */4 * * *', maven: true - ], - [ name: 'POI-DSL-regenerate-javadoc', trigger: triggerSundays, javadoc: true - ], - [ name: 'POI-DSL-API-Check', jdk: '1.7', trigger: '@daily', apicheck: true - ], - [ name: 'POI-DSL-Gradle', jdk: '1.7', trigger: triggerSundays, email: 'centic@apache.org', gradle: true, - // Gradle will not run any tests if the code is up-to-date, therefore manually mark the files as updated - addShell: 'touch --no-create build/*/build/test-results/TEST-*.xml build/*/build/test-results/test/TEST-*.xml' - ], - [ name: 'POI-DSL-no-scratchpad', trigger: triggerSundays, noScratchpad: true - ], - [ name: 'POI-DSL-SonarQube', jdk: '1.8', trigger: 'H 9 * * *', maven: true, sonar: true - ], - [ name: 'POI-DSL-SonarQube-Gradle', jdk: '1.8', trigger: 'H 9 * * *', gradle: true, sonar: true, skipcigame: true - ], -] - -def svnBase = 'https://svn.apache.org/repos/asf/poi/trunk' -def defaultJdk = '1.6' -def defaultTrigger = 'H/15 * * * *' // check SCM every 60/15 = 4 minutes -def defaultEmail = 'dev@poi.apache.org' -def defaultAnt = 'Ant 1.9.9' -// currently a lot of H?? slaves don't have Ant installed ... -def defaultSlaves = 'ubuntu&&!cloud-slave&&!H15&&!H17&&!H18&&!H24&&!ubuntu-4' - -def jdkMapping = [ - '1.6': 'JDK 1.6 (latest)', - '1.7': 'JDK 1.7 (latest)', - '1.8': 'JDK 1.8 (latest)', - '1.9': 'JDK 9 b156 (early access build) with project Jigsaw', - 'OpenJDK': 'OpenJDK 6 (on Ubuntu only) ', // blank is required here until the name in the Jenkins instance is fixed! - 'IBMJDK': 'IBM 1.8 64-bit (on Ubuntu only)', -] - -poijobs.each { poijob -> - def jdkKey = poijob.jdk ?: defaultJdk - def trigger = poijob.trigger ?: defaultTrigger - def email = poijob.email ?: defaultEmail - def slaves = defaultSlaves + (poijob.slaveAdd ?: '') - - job(poijob.name) { - if (poijob.disabled) { - disabled() - } - - def defaultDesc = ''' - -

-Apache POI - the Java API for Microsoft Documents -

-

-This is an automatically generated Job Config, do not edit it here! -Instead change the Jenkins Job DSL at https://svn.apache.org/repos/asf/poi/trunk/jenkins, -see https://github.com/jenkinsci/job-dsl-plugin/wiki -for more details about the DSL. -

''' - - description( defaultDesc + -(poijob.apicheck ? -''' -

-Sonar reports - -

-API Check POI -API Check POI-OOXML -API Check POI-Excelant -API Check POI-Scratchpad - -

-''' : -''' -

-Findbugs report of latest build - -Sonar reports - -Coverage of latest build -

-''')) - logRotator { - numToKeep(5) - artifactNumToKeep(1) - } - label(slaves) - environmentVariables { - env('LANG', 'en_US.UTF-8') - if(jdkKey == '1.9') { - // when using JDK 9 for running Ant, we need to provide more packages for the forbidden-api-checks task - env('ANT_OPTS', '--add-modules=java.xml.bind') - } - } - wrappers { - timeout { - absolute(180) - abortBuild() - writeDescription('Build was aborted due to timeout') - } - if(poijob.sonar) { - configure { project -> - project / buildWrappers << 'hudson.plugins.sonar.SonarBuildWrapper' {} - } - } - } - jdk(jdkMapping.get(jdkKey)) - scm { - svn(svnBase) { svnNode -> - svnNode / browser(class: 'hudson.scm.browsers.ViewSVN') / - url << 'http://svn.apache.org/viewcvs.cgi/?root=Apache-SVN' - } - } - triggers { - scm(trigger) - } - - def shellcmds = '# show which files are currently modified in the working copy\n' + - 'svn status\n' + - '\n' + - 'echo Java-Home: $JAVA_HOME\n' + - 'ls -al $JAVA_HOME/\n' + - '\n' + - (poijob.shell ?: '') + '\n' + - '# ignore any error message\n' + - 'exit 0\n' - - // Create steps and publishers depending on the type of Job that is selected - if(poijob.maven) { - steps { - shell(shellcmds) - maven { - goals('clean') - rootPOM('sonar/pom.xml') - localRepository(LocalRepositoryLocation.LOCAL_TO_WORKSPACE) - mavenInstallation('maven-3.2.1') - } - /* Currently not done, let's see if it is still necessary: - # Maven-Download fails for strange reasons, try to workaround... - mkdir -p sonar/ooxml-schema-security/target/schemas && wget -O sonar/ooxml-schema-security/target/schemas/xmldsig-core-schema.xsd http://www.w3.org/TR/2002/REC-xmldsig-core-20020212/xmldsig-core-schema.xsd - */ - maven { - if(poijob.sonar) { - goals('compile $SONAR_MAVEN_GOAL -Dsonar.host.url=$SONAR_HOST_URL') - } else { - goals('package') - } - rootPOM('sonar/pom.xml') - mavenOpts('-Xmx2g') - mavenOpts('-Xms256m') - mavenOpts('-XX:MaxPermSize=512m') - mavenOpts('-XX:-OmitStackTraceInFastThrow') - localRepository(LocalRepositoryLocation.LOCAL_TO_WORKSPACE) - mavenInstallation('maven-3.2.1') - } - } - publishers { - if (!poijob.skipcigame) { - configure { project -> - project / publishers << 'hudson.plugins.cigame.GamePublisher' {} - } - } - mailer(email, false, false) - } - } else if (poijob.javadoc) { - steps { - shell(shellcmds) - ant { - targets(['clean', 'javadocs'] + (poijob.properties ?: [])) - prop('coverage.enabled', true) - // Properties did not work, so I had to use targets instead - //properties(poijob.properties ?: '') - antInstallation(defaultAnt) - } - shell('zip -r build/javadocs.zip build/tmp/site/build/site/apidocs') - } - publishers { - if (!poijob.skipcigame) { - configure { project -> - project / publishers << 'hudson.plugins.cigame.GamePublisher' {} - } - } - mailer(email, false, false) - } - } else if (poijob.apicheck) { - steps { - shell(shellcmds) - gradle { - tasks('japicmp') - useWrapper(false) - } - } - publishers { - archiveArtifacts('build/*/build/reports/japi.html') - if (!poijob.skipcigame) { - configure { project -> - project / publishers << 'hudson.plugins.cigame.GamePublisher' {} - } - } - mailer(email, false, false) - } - } else if(poijob.sonar) { - steps { - shell(shellcmds) - gradle { - switches('-PenableSonar') - switches('-Dsonar.host.url=$SONAR_HOST_URL') - tasks('sonarqube') - useWrapper(false) - } - } - publishers { - if (!poijob.skipcigame) { - configure { project -> - project / publishers << 'hudson.plugins.cigame.GamePublisher' {} - } - } - mailer(email, false, false) - } - } else { - steps { - shell(shellcmds) - if(poijob.addShell) { - shell(poijob.addShell) - } - // For Jobs that should still have the default set of publishers we can configure different steps here - if(poijob.gradle) { - gradle { - tasks('check') - useWrapper(false) - } - } else if (poijob.noScratchpad) { - ant { - targets(['clean', 'compile-all'] + (poijob.properties ?: [])) - prop('coverage.enabled', true) - antInstallation(defaultAnt) - } - ant { - targets(['-Dscratchpad.ignore=true', 'jacocotask', 'test-all', 'testcoveragereport'] + (poijob.properties ?: [])) - prop('coverage.enabled', true) - antInstallation(defaultAnt) - } - } else { - ant { - targets(['clean', 'jenkins'] + (poijob.properties ?: [])) - prop('coverage.enabled', true) - // Properties did not work, so I had to use targets instead - //properties(poijob.properties ?: '') - antInstallation(defaultAnt) - } - ant { - targets(['run'] + (poijob.properties ?: [])) - buildFile('src/integrationtest/build.xml') - // Properties did not work, so I had to use targets instead - //properties(poijob.properties ?: '') - antInstallation(defaultAnt) - } - } - } - publishers { - findbugs('build/findbugs.xml', false) { - healthLimits(3, 20) - thresholdLimit('low') - defaultEncoding('UTF-8') - } - // in archive, junit and jacoco publishers, matches beneath build/*/build/... are for Gradle-build results - archiveArtifacts('build/dist/*.tar.gz,build/findbugs.html,build/coverage/**,build/integration-test-results/**,ooxml-lib/**,build/*/build/libs/*.jar') - warnings(['Java Compiler (javac)', 'JavaDoc Tool'], null) { - resolveRelativePaths() - } - archiveJunit('build/ooxml-test-results/*.xml,build/scratchpad-test-results/*.xml,build/test-results/*.xml,build/excelant-test-results/*.xml,build/integration-test-results/*.xml,build/*/build/test-results/test/TEST-*.xml,build/*/build/test-results/TEST-*.xml') { - testDataPublishers { - publishTestStabilityData() - } - } - jacocoCodeCoverage { - classPattern('build/classes,build/excelant-classes,build/ooxml-classes,build/scratchpad-classes,build/*/build/classes') - execPattern('build/*.exec,build/*/build/jacoco/*.exec') - sourcePattern('src/java,src/excelant/java,src/ooxml/java,src/scratchpad/src') - exclusionPattern('com/microsoft/**,org/openxmlformats/**,org/etsi/**,org/w3/**,schemaorg*/**,schemasMicrosoft*/**,org/apache/poi/hdf/model/hdftypes/definitions/*.class,org/apache/poi/hwpf/model/types/*.class,org/apache/poi/hssf/usermodel/DummyGraphics2d.class,org/apache/poi/sl/draw/binding/*.class') - } - - if (!poijob.skipcigame) { - configure { project -> - project / publishers << 'hudson.plugins.cigame.GamePublisher' {} - } - } - mailer(email, false, false) - } - } - } -} diff --git a/maven/multisign.sh b/maven/multisign.sh deleted file mode 100755 index 1ba8c91f4..000000000 --- a/maven/multisign.sh +++ /dev/null @@ -1,54 +0,0 @@ -#! /bin/sh -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# create md5 checksums and gpg signatures - -echo "If you use gpg2 you need to set GPG_BIN accordingly" - -GPG_BIN=gpg - -stty -echo -echo "enter your GPG passphrase" -read passphrase -stty echo - -# Do we have md5sum and sha1sum? -# (We can use openssl if not, but the files it produces aren't as nice) -which md5sum > /dev/null -LACKING_MD5SUM=$? -which sha1sum > /dev/null -LACKING_SHA1SUM=$? - -for i in *; do - echo "" - echo Signing $i - echo $passphrase | $GPG_BIN --passphrase-fd 0 --output $i.asc --detach-sig --armor $i - $GPG_BIN --verify $i.asc $i - echo Hashing $i - - if [ "$LACKING_MD5SUM" = "1" ]; then - openssl md5 < $i > $i.md5 - else - md5sum $i > $i.md5 - fi - - if [ "$LACKING_SHA1SUM" = "1" ]; then - openssl sha1 < $i > $i.sha1 - else - sha1sum $i > $i.sha1 - fi -done diff --git a/maven/mvn-deploy.sh b/maven/mvn-deploy.sh deleted file mode 100755 index a66936a13..000000000 --- a/maven/mvn-deploy.sh +++ /dev/null @@ -1,62 +0,0 @@ -#! /bin/sh -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Shell script to deploy POI artifacts in a maven repository. -# -# Note, You should configure your settings.xml and add a server with id=apache-releases: -# -# -# apache-releases -# apacheId -# mySecurePassw0rd -# -# -# -# -# apache-releases -# -# -# -# -# -# -# Usage: -# 1. ant dist -# 2. cd build/dist -# 3. ./mvn-deploy.sh - -M2_REPOSITORY=https://repository.apache.org/service/local/staging/deploy/maven2 - -VERSION=@VERSION@ -DSTAMP=@DSTAMP@ - -for artifactId in poi poi-scratchpad poi-ooxml poi-examples poi-ooxml-schemas poi-excelant -do - SENDS="-Dfile=$artifactId-$VERSION-$DSTAMP.jar" - SENDS="$SENDS -DpomFile=$artifactId-$VERSION.pom" - if [ -r $artifactId-$VERSION-sources-$DSTAMP.jar ]; then - SENDS="$SENDS -Dsources=$artifactId-$VERSION-sources-$DSTAMP.jar" - fi - if [ -r $artifactId-$VERSION-javadocs-$DSTAMP.jar ]; then - SENDS="$SENDS -Djavadoc=$artifactId-$VERSION-javadocs-$DSTAMP.jar" - fi - - mvn gpg:sign-and-deploy-file \ - -DrepositoryId=apache-releases -P apache-releases \ - -Durl=$M2_REPOSITORY \ - $SENDS -done diff --git a/maven/ooxml-schemas.pom b/maven/ooxml-schemas.pom deleted file mode 100644 index da49544ae..000000000 --- a/maven/ooxml-schemas.pom +++ /dev/null @@ -1,70 +0,0 @@ - - - - - - 4.0.0 - org.apache.poi - ooxml-schemas - @VERSION@ - jar - OOXML schemas - XmlBeans generated from the Ecma supplied xsds: - http://www.ecma-international.org/publications/files/ECMA-ST/Office%20Open%20XML%20Part%204%20(DOCX).zip - http://poi.apache.org/ - - - - POI Users List - user-subscribe@poi.apache.org - user-unsubscribe@poi.apache.org - http://mail-archives.apache.org/mod_mbox/poi-user/ - - - POI Developer List - dev-subscribe@poi.apache.org - dev-unsubscribe@poi.apache.org - http://mail-archives.apache.org/mod_mbox/poi-dev/ - - - - - - The Apache Software License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0.txt - repo - - - - - Apache Software Foundation - http://www.apache.org/ - - - - - org.apache.xmlbeans - xmlbeans - 2.3.0 - - - diff --git a/maven/ooxml-security.pom b/maven/ooxml-security.pom deleted file mode 100644 index de9112e21..000000000 --- a/maven/ooxml-security.pom +++ /dev/null @@ -1,79 +0,0 @@ - - - - - - 4.0.0 - org.apache.poi - ooxml-security - @VERSION@ - jar - OOXML security - - XmlBeans generated from various supplied xsds for encryption and signing: - http://msdn.microsoft.com/en-us/library/dd925810(v=office.12).aspx - http://www.ecma-international.org/publications/files/ECMA-ST/Office%20Open%20XML%201st%20edition%20Part%202%20(PDF).zip - http://www.w3.org/TR/2002/REC-xmldsig-core-20020212/xmldsig-core-schema.xsd - http://uri.etsi.org/01903/v1.3.2/XAdES.xsd - http://uri.etsi.org/01903/v1.4.1/XAdESv141.xsd - http://dublincore.org/schemas/xmls/qdc/2003/04/02/dc.xsd - http://dublincore.org/schemas/xmls/qdc/2003/04/02/dcterms.xsd - http://dublincore.org/schemas/xmls/qdc/2003/04/02/dcmitype.xsd - - http://poi.apache.org/ - - - - POI Users List - user-subscribe@poi.apache.org - user-unsubscribe@poi.apache.org - http://mail-archives.apache.org/mod_mbox/poi-user/ - - - POI Developer List - dev-subscribe@poi.apache.org - dev-unsubscribe@poi.apache.org - http://mail-archives.apache.org/mod_mbox/poi-dev/ - - - - - - The Apache Software License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0.txt - repo - - - - - Apache Software Foundation - http://www.apache.org/ - - - - - org.apache.xmlbeans - xmlbeans - 2.3.0 - - - diff --git a/maven/poi-examples.pom b/maven/poi-examples.pom deleted file mode 100644 index 249f2500f..000000000 --- a/maven/poi-examples.pom +++ /dev/null @@ -1,78 +0,0 @@ - - - - - - 4.0.0 - org.apache.poi - poi-examples - @VERSION@ - jar - Apache POI - http://poi.apache.org/ - Apache POI Examples - - - - POI Users List - user-subscribe@poi.apache.org - user-unsubscribe@poi.apache.org - http://mail-archives.apache.org/mod_mbox/poi-user/ - - - POI Developer List - dev-subscribe@poi.apache.org - dev-unsubscribe@poi.apache.org - http://mail-archives.apache.org/mod_mbox/poi-dev/ - - - - - - The Apache Software License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0.txt - - - - - Apache Software Foundation - http://www.apache.org/ - - - - - org.apache.poi - poi - @VERSION@ - - - org.apache.poi - poi-scratchpad - @VERSION@ - - - org.apache.poi - poi-ooxml - @VERSION@ - - - diff --git a/maven/poi-excelant.pom b/maven/poi-excelant.pom deleted file mode 100644 index 6b23e4a12..000000000 --- a/maven/poi-excelant.pom +++ /dev/null @@ -1,78 +0,0 @@ - - - - - - 4.0.0 - org.apache.poi - poi-excelant - @VERSION@ - jar - Apache POI - http://poi.apache.org/ - Apache POI Excel Ant Tasks - - - - POI Users List - user-subscribe@poi.apache.org - user-unsubscribe@poi.apache.org - http://mail-archives.apache.org/mod_mbox/poi-user/ - - - POI Developer List - dev-subscribe@poi.apache.org - dev-unsubscribe@poi.apache.org - http://mail-archives.apache.org/mod_mbox/poi-dev/ - - - - - - The Apache Software License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0.txt - - - - - Apache Software Foundation - http://www.apache.org/ - - - - - org.apache.poi - poi - @VERSION@ - - - org.apache.poi - poi-ooxml - @VERSION@ - - - org.apache.ant - ant - 1.8.2 - - - diff --git a/maven/poi-ooxml-schemas.pom b/maven/poi-ooxml-schemas.pom deleted file mode 100644 index baf531d54..000000000 --- a/maven/poi-ooxml-schemas.pom +++ /dev/null @@ -1,68 +0,0 @@ - - - - - - 4.0.0 - org.apache.poi - poi-ooxml-schemas - @VERSION@ - jar - Apache POI - http://poi.apache.org/ - Apache POI - Java API To Access Microsoft Format Files - - - - POI Users List - user-subscribe@poi.apache.org - user-unsubscribe@poi.apache.org - http://mail-archives.apache.org/mod_mbox/poi-user/ - - - POI Developer List - dev-subscribe@poi.apache.org - dev-unsubscribe@poi.apache.org - http://mail-archives.apache.org/mod_mbox/poi-dev/ - - - - - - The Apache Software License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0.txt - - - - - Apache Software Foundation - http://www.apache.org/ - - - - - org.apache.xmlbeans - xmlbeans - 2.6.0 - - - diff --git a/maven/poi-ooxml.pom b/maven/poi-ooxml.pom deleted file mode 100644 index 0f3cdb1d5..000000000 --- a/maven/poi-ooxml.pom +++ /dev/null @@ -1,78 +0,0 @@ - - - - - - 4.0.0 - org.apache.poi - poi-ooxml - @VERSION@ - jar - Apache POI - http://poi.apache.org/ - Apache POI - Java API To Access Microsoft Format Files - - - - POI Users List - user-subscribe@poi.apache.org - user-unsubscribe@poi.apache.org - http://mail-archives.apache.org/mod_mbox/poi-user/ - - - POI Developer List - dev-subscribe@poi.apache.org - dev-unsubscribe@poi.apache.org - http://mail-archives.apache.org/mod_mbox/poi-dev/ - - - - - - The Apache Software License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0.txt - - - - - Apache Software Foundation - http://www.apache.org/ - - - - - org.apache.poi - poi - @VERSION@ - - - org.apache.poi - poi-ooxml-schemas - @VERSION@ - - - com.github.virtuald - curvesapi - 1.04 - - - diff --git a/maven/poi-scratchpad.pom b/maven/poi-scratchpad.pom deleted file mode 100644 index d1b4392de..000000000 --- a/maven/poi-scratchpad.pom +++ /dev/null @@ -1,68 +0,0 @@ - - - - - - 4.0.0 - org.apache.poi - poi-scratchpad - @VERSION@ - jar - Apache POI - http://poi.apache.org/ - Apache POI - Java API To Access Microsoft Format Files - - - - POI Users List - user-subscribe@poi.apache.org - user-unsubscribe@poi.apache.org - http://mail-archives.apache.org/mod_mbox/poi-user/ - - - POI Developer List - dev-subscribe@poi.apache.org - dev-unsubscribe@poi.apache.org - http://mail-archives.apache.org/mod_mbox/poi-dev/ - - - - - - The Apache Software License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0.txt - - - - - Apache Software Foundation - http://www.apache.org/ - - - - - org.apache.poi - poi - @VERSION@ - - - diff --git a/maven/poi.pom b/maven/poi.pom deleted file mode 100644 index efd24cfe0..000000000 --- a/maven/poi.pom +++ /dev/null @@ -1,101 +0,0 @@ - - - - - - 4.0.0 - org.apache.poi - poi - @VERSION@ - jar - Apache POI - http://poi.apache.org/ - Apache POI - Java API To Access Microsoft Format Files - - - - POI Users List - user-subscribe@poi.apache.org - user-unsubscribe@poi.apache.org - http://mail-archives.apache.org/mod_mbox/poi-user/ - - - POI Developer List - dev-subscribe@poi.apache.org - dev-unsubscribe@poi.apache.org - http://mail-archives.apache.org/mod_mbox/poi-dev/ - - - - - - The Apache Software License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0.txt - - - - - Apache Software Foundation - http://www.apache.org/ - - - - - commons-logging - commons-logging - 1.2 - runtime - true - - - log4j - log4j - 1.2.17 - runtime - true - - - commons-codec - commons-codec - 1.10 - - - - org.hamcrest - hamcrest-core - test - 1.3 - - - junit - junit - test - 4.12 - - - org.apache.commons - commons-collections4 - 4.1 - - - - diff --git a/osgi/build.xml b/osgi/build.xml deleted file mode 100644 index 35dd87bcc..000000000 --- a/osgi/build.xml +++ /dev/null @@ -1,67 +0,0 @@ - - - - - - The Apache POI OSGi Bundle System. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/osgi/bundle.info b/osgi/bundle.info deleted file mode 100644 index 1886a0aef..000000000 --- a/osgi/bundle.info +++ /dev/null @@ -1,38 +0,0 @@ -\u001B[1mSYNOPSIS\u001B[0m - ${project.description} - - Original Maven URLs: - \u001B[33mmvn:${pkgGroupId}/poi/${pkgVersion}\u001B[0m - \u001B[33mmvn:${pkgGroupId}/poi-ooxml/${pkgVersion}\u001B[0m - \u001B[33mmvn:${pkgGroupId}/poi-scratchpad/${pkgVersion}\u001B[0m - -\u001B[1mDESCRIPTION\u001B[0m - The Apache POI Project's mission is to create and maintain Java APIs for manipulating various file formats based - upon the Office Open XML standards (OOXML) and Microsoft's OLE 2 Compound Document format (OLE2). In short, you can - read and write MS Excel files using Java. In addition, you can read and write MS Word and MS PowerPoint files using - Java. Apache POI is your Java Excel solution (for Excel 97-2008). We have a complete API for porting other OOXML and - OLE2 formats and welcome others to participate. - - OLE2 files include most Microsoft Office files such as XLS, DOC, and PPT as well as MFC serialization API based file - formats. The project provides APIs for the OLE2 Filesystem (POIFS) and OLE2 Document Properties (HPSF). - - Office OpenXML Format is the new standards based XML file format found in Microsoft Office 2007 and 2008. This - includes XLSX, DOCX and PPTX. The project provides a low level API to support the Open Packaging Conventions using - openxml4j. - - For each MS Office application there exists a component module that attempts to provide a common high level Java api - to both OLE2 and OOXML document formats. This is most developed for Excel workbooks (SS=HSSF+XSSF). Work is - progressing for Word documents (HWPF+XWPF) and PowerPoint presentations (HSLF+XSLF). - - The project has recently added support for Outlook (HSMF). Microsoft opened the specifications to this format in - October 2007. We would welcome contributions. - - There are also projects for Visio (HDGF), TNEF (HMEF), and Publisher (HPBF). - - As a general policy we collaborate as much as possible with other projects to provide this functionality. - Examples include: Cocoon for which there are serializers for HSSF; Open Office.org with whom we collaborate in - documenting the XLS format; and Tika / Lucene, for which we provide format interpretors. - When practical, we donate components directly to those projects for POI-enabling them. - -\u001B[1mSEE ALSO\u001B[0m - \u001B[36mhttp://poi.apache.org/\u001B[0m diff --git a/osgi/pom.xml b/osgi/pom.xml deleted file mode 100644 index 2849467a9..000000000 --- a/osgi/pom.xml +++ /dev/null @@ -1,229 +0,0 @@ - - - - - 4.0.0 - - - org.apache - apache - 10 - - - - org.apache.poi - poi-bundle - bundle - Apache POI OSGi bundle - - OSGi bundle that contains Apache POI, and the dependencies. - - http://poi.apache.org/ - ${poi.version} - - - - 1.6 - 1.6 - 4.4.0 - - - - - ${project.groupId} - poi - ${poi.version} - - - ${project.groupId} - poi-scratchpad - ${poi.version} - - - ${project.groupId} - poi-ooxml - ${poi.version} - - - - - junit - junit - 4.12 - - - org.ops4j.pax.exam - pax-exam-junit4 - ${pax.exam.version} - test - - - org.ops4j.pax.exam - pax-exam-container-native - ${pax.exam.version} - test - - - org.apache.felix - org.apache.felix.framework - 4.6.0 - test - - - org.ops4j.pax.exam - pax-exam-link-assembly - ${pax.exam.version} - test - - - org.ops4j.pax.url - pax-url-aether - 2.3.0 - test - - - javax.inject - javax.inject - 1 - test - - - org.osgi - org.osgi.core - 5.0.0 - provided - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - - org.apache.poi.osgi.Activator - - - poi;inline=true, - poi-scratchpad;inline=true, - poi-ooxml;inline=true, - poi-ooxml-schemas, - xmlbeans - - true - ${project.url} - - org.apache.poi.* - - - !org.junit, - *, - org.apache.xmlbeans.impl.xpath.saxon;resolution:=optional, - org.apache.xmlbeans.impl.xquery.saxon;resolution:=optional, - org.bouncycastle.cert;resolution:=optional, - org.bouncycastle.cert.ocsp;resolution:=optional, - org.bouncycastle.cms.bc;resolution:=optional, - org.bouncycastle.cert.jcajce;resolution:=optional, - org.bouncycastle.operator;resolution:=optional, - org.bouncycastle.operator.bc;resolution:=optional, - org.bouncycastle.tsp;resolution:=optional, - org.openxmlformats.schemas.officeDocument.x2006.math;resolution:=optional, - org.openxmlformats.schemas.schemaLibrary.x2006.main;resolution:=optional, - schemasMicrosoftComOfficePowerpoint;resolution:=optional, - schemasMicrosoftComOfficeWord;resolution:=optional, - - - - - - maven-compiler-plugin - 3.2 - - ${maven.compiler.source} - ${maven.compiler.target} - - - - - - - - java6 - - [1.6,) - - - - - maven-assembly-plugin - - - pre-integration-test - - single - - - test-bundles.xml - test - false - - - - - - maven-failsafe-plugin - 2.10 - - - - integration-test - verify - - - - - - - WARN - - - - - - - - - - - The Apache Software Founation - http://www.apache.org - - - http://svn.apache.org/viewvc/poi/trunk/osgi - scm:svn:http://svn.apache.org/repos/asf/poi/trunk/osgi - scm:svn:https://svn.apache.org/repos/asf/poi/trunk/osgi - - diff --git a/osgi/src/main/java/org/apache/poi/osgi/Activator.java b/osgi/src/main/java/org/apache/poi/osgi/Activator.java deleted file mode 100644 index 2f0212bd4..000000000 --- a/osgi/src/main/java/org/apache/poi/osgi/Activator.java +++ /dev/null @@ -1,28 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.osgi; - -import org.osgi.framework.BundleActivator; -import org.osgi.framework.BundleContext; - -public class Activator implements BundleActivator { - public void start(BundleContext context) throws Exception { - } - public void stop(BundleContext context) throws Exception { - } -} diff --git a/osgi/src/test/java/org/apache/poi/osgi/TestOSGiBundle.java b/osgi/src/test/java/org/apache/poi/osgi/TestOSGiBundle.java deleted file mode 100644 index 738d96b99..000000000 --- a/osgi/src/test/java/org/apache/poi/osgi/TestOSGiBundle.java +++ /dev/null @@ -1,84 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.osgi; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.ops4j.pax.exam.CoreOptions.bundle; -import static org.ops4j.pax.exam.CoreOptions.junitBundles; -import static org.ops4j.pax.exam.CoreOptions.options; - -import javax.inject.Inject; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.net.URISyntaxException; - -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.ops4j.pax.exam.Configuration; -import org.ops4j.pax.exam.Option; -import org.ops4j.pax.exam.junit.PaxExam; -import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy; -import org.ops4j.pax.exam.spi.reactors.PerMethod; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceReference; - -/** - * Test to ensure that all our main formats can create, write - * and read back in, when running under OSGi - */ -@RunWith(PaxExam.class) -@ExamReactorStrategy(PerMethod.class) -public class TestOSGiBundle { - - private final File TARGET = new File("target"); - - @Inject - private BundleContext bc; - - @Configuration - public Option[] configuration() throws IOException, URISyntaxException { - File base = new File(TARGET, "test-bundles"); - return options( - junitBundles(), - bundle(new File(base, "poi-bundle.jar").toURI().toURL().toString())); - } - - @Test - public void testHSSF() throws Exception { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet s = wb.createSheet("OSGi"); - s.createRow(0).createCell(0).setCellValue("With OSGi"); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - wb.write(baos); - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - - wb = new HSSFWorkbook(bais); - assertEquals(1, wb.getNumberOfSheets()); - - s = wb.getSheet("OSGi"); - assertEquals("With OSGi", s.getRow(0).getCell(0).toString()); - } -} diff --git a/osgi/test-bundles.xml b/osgi/test-bundles.xml deleted file mode 100644 index 11502761e..000000000 --- a/osgi/test-bundles.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - bundles - - dir - - false - - - - ${artifact.artifactId}.jar - - org.apache.poi:poi-bundle - - - - diff --git a/patch.xml b/patch.xml deleted file mode 100644 index ed52a91d7..000000000 --- a/patch.xml +++ /dev/null @@ -1,128 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/settings.gradle b/settings.gradle deleted file mode 100644 index de9c7e7cb..000000000 --- a/settings.gradle +++ /dev/null @@ -1,10 +0,0 @@ -rootProject.name = 'poi' - -include 'main', 'ooxml', 'excelant', 'examples', 'scratchpad', 'integrationtest' - -project(':main').projectDir = new File(settingsDir, 'build/main') -project(':ooxml').projectDir = new File(settingsDir, 'build/ooxml') -project(':excelant').projectDir = new File(settingsDir, 'build/excelant') -project(':examples').projectDir = new File(settingsDir, 'build/examples') -project(':scratchpad').projectDir = new File(settingsDir, 'build/scratchpad') -project(':integrationtest').projectDir = new File(settingsDir, 'build/integrationtest') diff --git a/sonar/examples/pom.xml b/sonar/examples/pom.xml deleted file mode 100644 index 9ac334073..000000000 --- a/sonar/examples/pom.xml +++ /dev/null @@ -1,76 +0,0 @@ - - 4.0.0 - - org.apache.poi - poi-parent - 3.16-beta3-SNAPSHOT - - poi-examples - jar - - Apache POI Examples package - - - - - - maven-resources-plugin - ${maven.plugin.resources.version} - - - copy-sources - - generate-sources - - copy-resources - - - ${basedir}/src/main/java - - - ../../src/examples/src - - - - - - - - - maven-clean-plugin - ${maven.plugin.clean.version} - - - - src - false - - - - - - - - - - ${project.groupId} - poi-main - ${project.version} - - - ${project.groupId} - poi-ooxml - ${project.version} - - - - - junit - junit - ${junit.version} - - - diff --git a/sonar/excelant/pom.xml b/sonar/excelant/pom.xml deleted file mode 100644 index 7137c6aec..000000000 --- a/sonar/excelant/pom.xml +++ /dev/null @@ -1,114 +0,0 @@ - - 4.0.0 - - org.apache.poi - poi-parent - 3.16-beta3-SNAPSHOT - - poi-excelant - jar - - Apache POI ExcelAnt package - - - - - - maven-resources-plugin - ${maven.plugin.resources.version} - - - copy-sources - - generate-sources - - copy-resources - - - ${basedir}/src/main/java - - - ../../src/excelant/java - - - - - - copy-resources - - generate-resources - - copy-resources - - - ${basedir}/src/main/resources - - - ../../src/excelant/resources - - - - - - copy-tests - - generate-test-sources - - copy-resources - - - ${basedir}/src/test/java - - - ../../src/excelant/testcases - - - - - - - - - maven-clean-plugin - ${maven.plugin.clean.version} - - - - src - false - - - - - - - - - - ${project.groupId} - poi-main - ${project.version} - - - ${project.groupId} - poi-main - ${project.version} - test-jar - test - - - ${project.groupId} - poi-ooxml - ${project.version} - - - - org.apache.ant - ant - 1.8.2 - - - diff --git a/sonar/main/pom.xml b/sonar/main/pom.xml deleted file mode 100644 index 08b7ca44f..000000000 --- a/sonar/main/pom.xml +++ /dev/null @@ -1,129 +0,0 @@ - - 4.0.0 - - org.apache.poi - poi-parent - 3.16-beta3-SNAPSHOT - - poi-main - jar - - Apache POI Main package - - - - - - maven-resources-plugin - ${maven.plugin.resources.version} - - - copy-sources - generate-sources - - copy-resources - - - ${basedir}/src/main/java - - - ../../src/java - - - - - - copy-resources - generate-resources - - copy-resources - - - ${basedir}/src/main/resources - - - ../../src/resources/main - - - - - - copy-tests - - generate-test-sources - - copy-resources - - - ${basedir}/src/test/java - - - ../../src/testcases - - - - - - - - - - maven-clean-plugin - ${maven.plugin.clean.version} - - - - src - false - - - - - - - - org.apache.maven.plugins - maven-jar-plugin - ${maven.plugin.jar.version} - - - - test-jar - - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - ${maven.plugin.surefire.version} - - @{argLine} -Duser.language=en -Duser.country=US -Xmx1024m -XX:MaxPermSize=256m -XX:-OmitStackTraceInFastThrow - - - - - - - - org.apache.commons - commons-collections4 - 4.1 - - - commons-codec - commons-codec - 1.10 - - - commons-logging - commons-logging - 1.2 - - - diff --git a/sonar/ooxml-schema-encryption/pom.xml b/sonar/ooxml-schema-encryption/pom.xml deleted file mode 100644 index 22fadcf4a..000000000 --- a/sonar/ooxml-schema-encryption/pom.xml +++ /dev/null @@ -1,55 +0,0 @@ - - 4.0.0 - - org.apache.poi - poi-parent - 3.16-beta3-SNAPSHOT - .. - - poi-ooxml-schema-encryption - jar - - Apache POI - Openxmlformats Encryption Schema package - - - - target/generated-sources/* - - - - - - org.apache.maven.plugins - maven-antrun-plugin - ${maven.plugin.antrun.version} - - - unzip-schema - generate-sources - - run - - - - - - - - - - - - - - - - - org.apache.xmlbeans - xmlbeans - ${xmlbeans.version} - - - diff --git a/sonar/ooxml-schema-encryption/xmlbeans.marker b/sonar/ooxml-schema-encryption/xmlbeans.marker deleted file mode 100644 index 2744493ac..000000000 --- a/sonar/ooxml-schema-encryption/xmlbeans.marker +++ /dev/null @@ -1 +0,0 @@ -This purpose of this marker file is solely to activate the xmlbeans maven profile. \ No newline at end of file diff --git a/sonar/ooxml-schema-security/pom.xml b/sonar/ooxml-schema-security/pom.xml deleted file mode 100644 index 8fb1c882f..000000000 --- a/sonar/ooxml-schema-security/pom.xml +++ /dev/null @@ -1,144 +0,0 @@ - - 4.0.0 - - org.apache.poi - poi-parent - 3.16-beta3-SNAPSHOT - .. - - poi-ooxml-schema-security - jar - - Apache POI - Openxmlformats Security-Schema package - - - - target/generated-sources/* - true - true - true - - - - - - - com.googlecode.maven-download-plugin - maven-download-plugin - ${maven.plugin.download.version} - - - install-xsds-part-1 - generate-sources - wget - - http://www.ecma-international.org/publications/files/ECMA-ST/Office%20Open%20XML%201st%20edition%20Part%202%20(PDF).zip - true - c8f0eac388691d5be0d1647146400a10 - - - - install-xsds-part-2 - generate-sources - wget - - target/schemas - http://dublincore.org/schemas/xmls/qdc/2003/04/02/dc.xsd - - - - install-xsds-part-3 - generate-sources - wget - - target/schemas - http://dublincore.org/schemas/xmls/qdc/2003/04/02/dcterms.xsd - - - - install-xsds-part-4 - generate-sources - wget - - target/schemas - http://dublincore.org/schemas/xmls/qdc/2003/04/02/dcmitype.xsd - - - - install-xsds-part-5 - generate-sources - wget - - target/schemas - http://www.w3.org/TR/2002/REC-xmldsig-core-20020212/xmldsig-core-schema.xsd - - - - install-xsds-part-6 - generate-sources - wget - - target/schemas - http://uri.etsi.org/01903/v1.3.2/XAdES.xsd - - - - install-xsds-part-7 - generate-sources - wget - - target/schemas - http://uri.etsi.org/01903/v1.4.1/XAdESv141.xsd - - - - - - - - org.apache.maven.plugins - maven-antrun-plugin - ${maven.plugin.antrun.version} - - - unzip-schema - generate-sources - - run - - - - - - - - - - - - - - - - - - org.apache.xmlbeans - xmlbeans - ${xmlbeans.version} - - - ${project.groupId} - poi-main - ${project.version} - - - ${project.groupId} - poi-scratchpad - ${project.version} - - - diff --git a/sonar/ooxml-schema-security/xmlbeans.marker b/sonar/ooxml-schema-security/xmlbeans.marker deleted file mode 100644 index 2744493ac..000000000 --- a/sonar/ooxml-schema-security/xmlbeans.marker +++ /dev/null @@ -1 +0,0 @@ -This purpose of this marker file is solely to activate the xmlbeans maven profile. \ No newline at end of file diff --git a/sonar/ooxml-schema/pom.xml b/sonar/ooxml-schema/pom.xml deleted file mode 100644 index 6f92d001b..000000000 --- a/sonar/ooxml-schema/pom.xml +++ /dev/null @@ -1,89 +0,0 @@ - - 4.0.0 - - org.apache.poi - poi-parent - 3.16-beta3-SNAPSHOT - .. - - poi-ooxml-schema - jar - - Apache POI - Openxmlformats Schema package - - - - target/generated-sources/* - true - ${basedir}/../../src/ooxml/resources/org/apache/poi/schemas/ooxmlSchemas.xsdconfig - - - - - - - com.googlecode.maven-download-plugin - maven-download-plugin - ${maven.plugin.download.version} - - - download-xsds - generate-sources - - wget - - - http://www.ecma-international.org/publications/files/ECMA-ST/Office%20Open%20XML%201st%20edition%20Part%204%20(PDF).zip - true - abe6bb6e7799e854934b3c634e8bcf7b - - - - - - - org.apache.maven.plugins - maven-antrun-plugin - ${maven.plugin.antrun.version} - - - unzip-schema - generate-sources - - - - - - - - - run - - - - - - - - - - ${project.groupId} - poi-main - ${project.version} - - - ${project.groupId} - poi-scratchpad - ${project.version} - - - org.apache.xmlbeans - xmlbeans - ${xmlbeans.version} - - - diff --git a/sonar/ooxml-schema/xmlbeans.marker b/sonar/ooxml-schema/xmlbeans.marker deleted file mode 100644 index 2744493ac..000000000 --- a/sonar/ooxml-schema/xmlbeans.marker +++ /dev/null @@ -1 +0,0 @@ -This purpose of this marker file is solely to activate the xmlbeans maven profile. \ No newline at end of file diff --git a/sonar/ooxml/pom.xml b/sonar/ooxml/pom.xml deleted file mode 100644 index ecc89573c..000000000 --- a/sonar/ooxml/pom.xml +++ /dev/null @@ -1,165 +0,0 @@ - - 4.0.0 - - org.apache.poi - poi-parent - 3.16-beta3-SNAPSHOT - - poi-ooxml - jar - - Apache POI OOXML package - - - - - - maven-resources-plugin - ${maven.plugin.resources.version} - - - copy-sources - generate-sources - - copy-resources - - - ${basedir}/src/main/java - - - ../../src/ooxml/java - - - - - - copy-resources - generate-resources - - copy-resources - - - ${basedir}/src/main/resources - - - ../../src/resources/ooxml - - - - - - copy-tests - generate-test-sources - - copy-resources - - - ${basedir}/src/test/java - - - ../../src/ooxml/testcases - - - - - - - - - - maven-clean-plugin - ${maven.plugin.clean.version} - - - - src - false - - - build - false - - - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - ${maven.plugin.surefire.version} - - @{argLine} -Duser.language=en -Duser.country=US -Xmx1024m -XX:MaxPermSize=256m -XX:-OmitStackTraceInFastThrow - - - - - - - - ${project.groupId} - poi-ooxml-schema - ${project.version} - - - ${project.groupId} - poi-ooxml-schema-encryption - ${project.version} - - - ${project.groupId} - poi-ooxml-schema-security - ${project.version} - - - ${project.groupId} - poi-main - ${project.version} - - - ${project.groupId} - poi-main - ${project.version} - test-jar - test - - - - org.apache.xmlbeans - xmlbeans - ${xmlbeans.version} - - - - org.bouncycastle - bcpkix-jdk15on - 1.54 - - - org.bouncycastle - bcprov-jdk15on - 1.54 - - - org.apache.santuario - xmlsec - 2.0.5 - - - com.github.virtuald - curvesapi - 1.04 - - - - - junit - junit - ${junit.version} - - - diff --git a/sonar/pom.xml b/sonar/pom.xml deleted file mode 100644 index 02b1fafd5..000000000 --- a/sonar/pom.xml +++ /dev/null @@ -1,277 +0,0 @@ - - 4.0.0 - org.apache.poi - poi-parent - pom - 3.16-beta3-SNAPSHOT - Apache POI - the Java API for Microsoft Documents - Maven build of Apache POI for Sonar checks - http://poi.apache.org/ - - - - POI Users List - user-subscribe@poi.apache.org - user-unsubscribe@poi.apache.org - http://mail-archives.apache.org/mod_mbox/poi-user/ - - - POI Developer List - dev-subscribe@poi.apache.org - dev-unsubscribe@poi.apache.org - http://mail-archives.apache.org/mod_mbox/poi-dev/ - - - - - - The Apache Software License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0.txt - - - - - Apache Software Foundation - http://www.apache.org/ - - - - Bugzilla - https://bz.apache.org/bugzilla/ - - - - scm:svn:http://svn.apache.org/repos/asf/poi/trunk - scm:svn:https://svn.apache.org/repos/asf/poi/trunk - http://svn.apache.org/viewvc/poi - - - - main - ooxml-schema - ooxml-schema-encryption - ooxml-schema-security - ooxml - scratchpad - excelant - examples - - - - ASCII - - true - - - 2.6.0 - 4.12 - 3.0.1 - 3.0.1 - 3.0.0 - 1.1.0 - 1.8 - 2.19.1 - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.5.1 - - 1.6 - 1.6 - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - ${maven.plugin.surefire.version} - - - org.apache.maven.surefire - surefire-junit47 - ${maven.plugin.surefire.version} - - - - - ../../test-data - true - org.apache.poi.util.NullLogger - - - @{argLine} -Duser.language=en -Duser.country=US -Xmx1024m - - **/All*Tests.java - **/TestUnfixedBugs.java - **/TestcaseRecordInputStream.java - **/POITestCase.java - - **/TestWordToConverterSuite*.java - **/TestExcelConverterSuite*.java - - - - - - - org.jacoco - jacoco-maven-plugin - 0.7.8 - - - - - - - junit - junit - ${junit.version} - test - - - - - - - - - - - - - 32bitstuff - - - sun.arch.data.model - 32 - - - - 512m - -Xmx768m -XX:MaxPermSize=128m - - - - - 64bitstuff - - - sun.arch.data.model - 64 - - - - 768m - -Xmx1024m -XX:MaxPermSize=256m - - - - - xmlbean - - xmlbeans.marker - - - - - org.codehaus.mojo - xmlbeans-maven-plugin - 2.3.3 - - - process-sources - - xmlbeans - - - ${basedir}/target/schemas - 1.5 - true - ${xmlbeans.noUpa} - ${xmlbeans.noPvr} - - ${basedir}/../../src/ooxml/resources/org/apache/poi/poifs/crypt/encryptionCertificate.xsdconfig - ${basedir}/../../src/ooxml/resources/org/apache/poi/poifs/crypt/encryptionInfo.xsdconfig - ${basedir}/../../src/ooxml/resources/org/apache/poi/poifs/crypt/encryptionPassword.xsdconfig - ${basedir}/../../src/ooxml/resources/org/apache/poi/schemas/ooxmlSchemas.xsdconfig - - - - - - - - maven-antrun-plugin - ${maven.plugin.antrun.version} - - - copy-xmltype-and-xsdconfig - generate-sources - run - - - - - - - - - - - - - - - - - - - - - - - replace-xmltypeloader - process-sources - run - - - - org.apache.xmlbeans.XmlBeans.getContextTypeLoader() - org.apache.poi.POIXMLTypeLoader - - - - - - remove-xmltypeloader-from-schema-jar - prepare-package - run - - - - - - - - - - - - - - org.apache.xmlbeans - xmlbeans - ${xmlbeans.version} - - - - - diff --git a/sonar/scratchpad/pom.xml b/sonar/scratchpad/pom.xml deleted file mode 100644 index 29353ce94..000000000 --- a/sonar/scratchpad/pom.xml +++ /dev/null @@ -1,109 +0,0 @@ - - 4.0.0 - - org.apache.poi - poi-parent - 3.16-beta3-SNAPSHOT - - poi-scratchpad - jar - - Apache POI Scratchpad package - - - - src/main/java/org/apache/poi/hwpf/model/types/*,src/main/java/org/apache/poi/hdf/model/hdftypes/definitions/* - - - - - - - - maven-resources-plugin - ${maven.plugin.resources.version} - - - copy-sources - - generate-sources - - copy-resources - - - ${basedir}/src/main/java - - - ../../src/scratchpad/src - - - - - - copy-resources - - generate-resources - - copy-resources - - - ${basedir}/src/main/resources - - - ../../src/resources/scratchpad - - - - - - copy-tests - - generate-test-sources - - copy-resources - - - ${basedir}/src/test/java - - - ../../src/scratchpad/testcases - - - - - - - - - maven-clean-plugin - ${maven.plugin.clean.version} - - - - src - false - - - - - - - - - - ${project.groupId} - poi-main - ${project.version} - - - ${project.groupId} - poi-main - ${project.version} - test-jar - test - - - diff --git a/src/contrib/poi-ruby/Makefile b/src/contrib/poi-ruby/Makefile deleted file mode 100644 index a298da329..000000000 --- a/src/contrib/poi-ruby/Makefile +++ /dev/null @@ -1,332 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. - - -# Makefile for building Poi4R -# -# Supported operating systems: Linux, Mac OS X and Windows. -# See INSTALL file for requirements. -# -# Steps to build -# 1. Edit the sections below as documented -# 2. make all -# 3. make install -# -# The install target installs the Poi4R python extension in python's -# site-packages directory. On Mac OS X, it also installs the gcj runtime -# libraries into $(PREFIX)/lib. -# -# To successfully import the Poi4R extension into Ruby, all required -# libraries need to be found. If the locations you chose are non-standard, -# the relevant DYLD_LIBRARY_PATH (Mac OS X), LD_LIBRARY_PATH (Linux), or -# PATH (Windows) need to be set accordingly. -# - - -VERSION=0.1.0 -POI_VER=$(shell grep ' -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "org/apache/poi/hssf/usermodel/HSSFWorkbook.h" -#include "org/apache/poi/hssf/usermodel/HSSFSheet.h" -#include "org/apache/poi/hssf/usermodel/HSSFRow.h" -#include "org/apache/poi/hssf/usermodel/HSSFCell.h" -#include "org/apache/poi/hssf/usermodel/HSSFFont.h" -#include "org/apache/poi/hssf/usermodel/HSSFCellStyle.h" -#include "org/apache/poi/hssf/usermodel/HSSFDataFormat.h" -#include "org/apache/poi/hssf/usermodel/HSSFHeader.h" -#include "org/apache/poi/hssf/usermodel/HSSFFooter.h" -#include "org/apache/poi/RubyOutputStream.h" - - -typedef ::org::apache::poi::hssf::usermodel::HSSFWorkbook *jhworkbook; -typedef ::org::apache::poi::hssf::usermodel::HSSFSheet *jhsheet; -typedef ::org::apache::poi::hssf::usermodel::HSSFRow *jhrow; -typedef ::org::apache::poi::hssf::usermodel::HSSFCell *jhcell; -typedef ::org::apache::poi::hssf::usermodel::HSSFCellStyle *jhcellstyle; -typedef ::org::apache::poi::hssf::usermodel::HSSFFont *jhfont; -typedef ::org::apache::poi::hssf::usermodel::HSSFFooter *jhfooter; -typedef ::org::apache::poi::hssf::usermodel::HSSFHeader *jhheader; -typedef ::org::apache::poi::hssf::usermodel::HSSFDataFormat *jhdataformat; - -typedef ::java::util::Date *jdate; -typedef ::java::util::Calendar *jcalendar; -typedef ::java::io::OutputStream *joutputstream; -typedef ::java::io::InputStream *jinputstream; -typedef ::java::util::Collection *jstringCollection; -typedef ::java::util::Collection *jtermCollection; -typedef ::java::util::Locale *jlocale; -typedef ::java::lang::Comparable *jcomparable; -typedef JArray *jobjectArray; -typedef JArray *jstringArray; - - -static java::lang::Thread *nextThread; -static java::util::HashMap *objects; - - -static void store_reference(jobject object) { - java::lang::Integer *ji =new java::lang::Integer(java::lang::System::identityHashCode(object)); - jobject jo = objects->get(ji); - if (!jo) { - // printf("put object in hash\n"); - objects->put(ji,object); - } -} -static VALUE jo2rv(jobject object, swig_type_info *descriptor) -{ - if (object == NULL) - { - return Qnil; - } - else - { - return SWIG_NewPointerObj((void *) object, descriptor, 0); - } -} -static int cvtptr(VALUE value, void **jo, swig_type_info *info) -{ - if (SWIG_ConvertPtr(value, jo, info, 0) == 0) - return 0; - else - { - return -1; - } -} - -static int rv2jo(VALUE rv, jobject *jo, swig_type_info *descriptor) -{ - if (NIL_P(rv)) - *jo = NULL; - else - { - java::lang::Object *javaObj; - - if (cvtptr(rv, (void **) &javaObj, descriptor) == -1) - return 0; - - *jo = javaObj; - } - - return 1; -} - - -static jstring r2j(VALUE object) -{ - if (NIL_P(object)){ - return NULL; - } - else { - char *ps = STR2CSTR(object); - jstring js = JvNewStringLatin1(ps); - - if (!js) - { - rb_raise(rb_eRuntimeError, "ruby str cannot be converted to java: %s",ps); - } - - return js; - } -} - -VALUE j2r(jstring js) -{ - if (!js) - { - return Qnil; - } - else - { - jint len = JvGetStringUTFLength(js); - char buf[len + 1]; - - JvGetStringUTFRegion(js, 0, len, buf); - buf[len] = '\0'; - - return rb_str_new2(buf); - } -} - -static void free_java_obj(void* arg1) { - jobject object =(jobject) arg1; - java::lang::Integer *ji =new java::lang::Integer(java::lang::System::identityHashCode(object)); - jobject jo = objects->get(ji); - if (jo) { - // printf("removed object from hash\n"); - objects->remove(ji); - } -} - -static void raise_ruby_error(java::lang::Throwable *e) { - java::io::StringWriter *buffer = new java::io::StringWriter(); - java::io::PrintWriter *writer = new java::io::PrintWriter(buffer); - e->printStackTrace(writer); - writer->close(); - jstring message = buffer->toString(); - jint len = JvGetStringUTFLength(message); - char buf[len + 1]; - JvGetStringUTFRegion(message, 0, len, buf); - buf[len] = '\0'; - rb_raise(rb_eRuntimeError, "error calling poi \n %s", buf); -} - -%} - -typedef long jint; -typedef long long jlong; -typedef char jbyte; -typedef float jfloat; -typedef float jdouble; -typedef int jshort; -typedef bool jboolean; - -%typemap(in) SWIGTYPE * { - - if (!rv2jo($input, (jobject *) &$1, $1_descriptor)) - rb_raise(rb_eRuntimeError, "Unrecoverable error in SWIG typemapping"); -} -%typemap(out) SWIGTYPE * { - - $result = jo2rv($1, $1_descriptor); -} - -%typemap(in) org::apache::poi::hssf::usermodel::HSSFWorkbook{ - - if (!rv2jo($input, (jobject *) &$1, - $descriptor(org::apache::poi::hssf::usermodel::HSSFWorkbook *))) - SWIG_fail; -} -%typemap(out) org::apache::poi::hssf::usermodel::HSSFWorkbook { - $result = jo2rv($1, $descriptor(org::apache::poi::hssf::usermodel::HSSFWorkbook *)); -} - -%typemap(in) jhsheet{ - - if (!rv2jo($input, (jobject *) &$1, - $descriptor(org::apache::poi::hssf::usermodel::HSSFSheet *))) - SWIG_fail; -} -%typemap(out) jhsheet { - - $result = jo2rv($1, $descriptor(org::apache::poi::hssf::usermodel::HSSFSheet *)); -} -%typemap(in) jhrow{ - - if (!rv2jo($input, (jobject *) &$1, - $descriptor(org::apache::poi::hssf::usermodel::HSSFRow *))) - SWIG_fail; -} -%typemap(out) jhrow { - - $result = jo2rv($1, $descriptor(org::apache::poi::hssf::usermodel::HSSFRow *)); -} -%typemap(in) jhcell{ - - if (!rv2jo($input, (jobject *) &$1, - $descriptor(org::apache::poi::hssf::usermodel::HSSFCell *))) - SWIG_fail; -} -%typemap(out) jhcell { - - $result = jo2rv($1, $descriptor(org::apache::poi::hssf::usermodel::HSSFCell *)); -} -%typemap(in) jhfont{ - - if (!rv2jo($input, (jobject *) &$1, - $descriptor(org::apache::poi::hssf::usermodel::HSSFFont *))) - rb_raise(rb_eRuntimeError, "Unrecoverable error in SWIG typemapping of HSSFFont"); -} - -%typemap(out) jhfont { - - $result = jo2rv($1, $descriptor(org::apache::poi::hssf::usermodel::HSSFFont *)); -} - -%typemap(in) jhcellstyle{ - - if (!rv2jo($input, (jobject *) &$1, - $descriptor(org::apache::poi::hssf::usermodel::HSSFCellStyle *))) - rb_raise(rb_eRuntimeError, "Unrecoverable error in SWIG typemapping of HSSFCellStyle"); -} -%typemap(out) jhcellstyle { - - $result = jo2rv($1, $descriptor(org::apache::poi::hssf::usermodel::HSSFCellStyle *)); -} -%typemap(in) jhdataformat{ - - if (!rv2jo($input, (jobject *) &$1, - $descriptor(org::apache::poi::hssf::usermodel::HSSFDataFormat *))) - rb_raise(rb_eRuntimeError, "Unrecoverable error in SWIG typemapping of HSSFDataFormat"); -} -%typemap(out) jhdataformat { - - $result = jo2rv($1, $descriptor(org::apache::poi::hssf::usermodel::HSSFDataFormat *)); -} - - -%typemap(in) jstring { - $1 = r2j($input); -} -%typemap(out) jstring { - $result = j2r($1); -} -%typecheck(SWIG_TYPECHECK_STRING) jstring { - $1 = ( NIL_P($input) || TYPE($input)==T_STRING ); -} - -%typemap(in) joutputstream { - - jlong ptr; - if (!rb_respond_to($input, rb_intern("putc"))) rb_raise(rb_eTypeError,"Expected IO"); - *(VALUE *) &ptr = (VALUE) $input; - $1 = new org::apache::poi::RubyOutputStream(ptr); -} -%typemap(in) jcalendar { - $1 = java::util::Calendar::getInstance(); - //$1->setTimeInMillis((long long) NUM2DBL(rb_funcall($input,rb_intern("to_i"),0,NULL))*1000.0); - $1->set(FIX2INT(rb_funcall($input,rb_intern("year"),0,NULL)), - FIX2INT(rb_funcall($input,rb_intern("mon"),0,NULL))-1, - FIX2INT(rb_funcall($input,rb_intern("day"),0,NULL)), - FIX2INT(rb_funcall($input,rb_intern("hour"),0,NULL)), - FIX2INT(rb_funcall($input,rb_intern("min"),0,NULL)), - FIX2INT(rb_funcall($input,rb_intern("sec"),0,NULL)) - ); -} - -%typecheck(SWIG_TYPECHECK_POINTER) jcalendar { - $1 = rb_respond_to($input, rb_intern("asctime")); -} - -%typemap(out) jdate { - jlong t = ((jdate) $1)->getTime(); - //TODO: separate seconds and microsecs - int ts=t/1000; - $result=rb_time_new((time_t) ts, 0 ); -} - - -%freefunc org::apache::poi::hssf::usermodel::HSSFWorkbook "free_java_obj"; - -%exception { - try { - $action - } catch (java::lang::Throwable *e) { - raise_ruby_error(e); - } -} -%exception org::apache::poi::hssf::usermodel::HSSFWorkbook::HSSFWorkbook { - try { - $action - store_reference(result); - } catch (java::lang::Throwable *e) { - raise_ruby_error(e); - } -} - - - - -namespace java { - namespace lang { - class Object { - jstring toString(); - }; -%nodefault; - class System : public Object { - public: - static jstring getProperty(jstring); - static jstring getProperty(jstring, jstring); - static void load(jstring); - static void loadLibrary(jstring); - static void mapLibraryName(jstring); - static void runFinalization(); - static void setProperty(jstring, jstring); - }; -%makedefault; - } - namespace io { -%nodefault; - class InputStream : public ::java::lang::Object { - }; - class OutputStream : public ::java::lang::Object { - }; - -%makedefault; - } - namespace util { - class Date : public ::java::lang::Object { - public: - Date(); - Date(jlong); - void setTime(jlong); - jstring toString(); - }; - } -} - - -namespace org { - namespace apache { - namespace poi { - namespace hssf { - namespace usermodel { -%nodefault; - class HSSFWorkbook : public ::java::lang::Object { - public: - HSSFWorkbook(); - jstring getSheetName(jint); - jint getNumberOfSheets(); - void setSheetOrder(jstring,jint); - void setSheetName(jint,jstring); - void setSheetName(jint,jstring,jshort); - jint getSheetIndex(jstring); - jhsheet createSheet(); - jhsheet cloneSheet(jint); - jhsheet createSheet(jstring); - jhsheet getSheetAt(jint); - jhsheet getSheet(jstring); - void removeSheetAt(jint); - jhcellstyle createCellStyle(); - jhfont createFont(); - jhdataformat createDataFormat(); - void write(joutputstream); - - }; - - class HSSFSheet : public ::java::lang::Object { - public: - jhrow createRow(jint); - jhrow getRow(jint); - jhfooter getFooter(); - jhheader getHeader(); - }; - class HSSFRow : public ::java::lang::Object { - public: - jhcell createCell(jshort); - jhcell getCell(jshort); - //jboolean getProtect(); //only in 2.5 - - }; - class HSSFCell : public ::java::lang::Object { - public: - void setCellValue(jdouble); - void setCellValue(jstring); - void setCellValue(jboolean); - void setCellValue(jcalendar); - void setCellFormula(jstring); - jstring getStringCellValue(); - jdouble getNumericCellValue(); - jdate getDateCellValue(); - jstring getCellFormula(); - jboolean getBooleanCellValue(); - jint getCellType(); - jshort getEncoding(); - void setAsActiveCell(); - - void setCellStyle(jhcellstyle); - void setEncoding(jshort encoding); - - static const jint CELL_TYPE_BLANK; - static const jint CELL_TYPE_BOOLEAN; - static const jint CELL_TYPE_ERROR; - static const jint CELL_TYPE_FORMULA; - static const jint CELL_TYPE_NUMERIC; - static const jint CELL_TYPE_STRING; - - static const jshort ENCODING_COMPRESSED_UNICODE; - static const jshort ENCODING_UTF_16; - }; - class HSSFCellStyle : public ::java::lang::Object { - public: - static const jshort ALIGN_CENTER; - static const jshort ALIGN_CENTER_SELECTION; - static const jshort ALIGN_FILL; - static const jshort ALIGN_GENERAL; - static const jshort ALIGN_JUSTIFY; - static const jshort ALIGN_LEFT; - static const jshort ALIGN_RIGHT; - static const jshort ALT_BARS; - static const jshort BIG_SPOTS; - static const jshort BORDER_DASH_DOT; - static const jshort BORDER_DASH_DOT_DOT; - static const jshort BORDER_DASHED; - static const jshort BORDER_DOTTED; - static const jshort BORDER_DOUBLE; - static const jshort BORDER_HAIR; - static const jshort BORDER_MEDIUM; - static const jshort BORDER_MEDIUM_DASH_DOT; - static const jshort BORDER_MEDIUM_DASH_DOT_DOT; - static const jshort BORDER_MEDIUM_DASHED; - static const jshort BORDER_NONE; - static const jshort BORDER_SLANTED_DASH_DOT; - static const jshort BORDER_THICK; - static const jshort BORDER_THIN; - static const jshort BRICKS; - static const jshort DIAMONDS; - static const jshort FINE_DOTS; - static const jshort NO_FILL; - static const jshort SOLID_FOREGROUND; - static const jshort SPARSE_DOTS; - static const jshort SQUARES; - static const jshort THICK_BACKWARD_DIAG; - static const jshort THICK_FORWARD_DIAG; - static const jshort THICK_HORZ_BANDS; - static const jshort THICK_VERT_BANDS; - static const jshort THIN_BACKWARD_DIAG; - static const jshort THIN_FORWARD_DIAG; - static const jshort THIN_HORZ_BANDS; - static const jshort THIN_VERT_BANDS; - static const jshort VERTICAL_BOTTOM; - static const jshort VERTICAL_CENTER; - static const jshort VERTICAL_JUSTIFY; - static const jshort VERTICAL_TOP; - - jshort getAlignment(); - jshort getBorderBottom(); - jshort getBorderLeft(); - jshort getBorderRight(); - jshort getBorderTop(); - jshort getBottomBorderColor(); - jshort getDataFormat(); - jshort getFillBackgroundColor(); - jshort getFillForegroundColor(); - jshort getFillPattern(); - jshort getFontIndex(); - jboolean getHidden(); - jshort getIndention(); - jshort getIndex(); - jshort getLeftBorderColor(); - jboolean getLocked(); - jshort getRightBorderColor(); - jshort getRotation(); - jshort getTopBorderColor(); - jshort getVerticalAlignment(); - jboolean getWrapText(); - void setAlignment(jshort) ; - void setBorderBottom(jshort ); - void setBorderLeft(jshort ); - void setBorderRight(jshort ); - void setBorderTop(jshort ); - void setBottomBorderColor(jshort ); - void setDataFormat(jshort ); - void setFillBackgroundColor(jshort ); - void setFillForegroundColor(jshort ); - void setFillPattern(jshort ); - void setFont(jhfont ); - void setHidden(jboolean ); - void setIndention(jshort ); - void setLeftBorderColor(jshort ); - void setLocked(jboolean ); - void setRightBorderColor(jshort ); - void setRotation(jshort ); - void setTopBorderColor(jshort ); - void setVerticalAlignment(jshort ); - void setWrapText(jboolean ); - }; - class HSSFDataFormat : public ::java::lang::Object { - public: - static jstring getBuiltinFormat(jshort); - static jshort getBuiltinFormat(jstring); - jstring getFormat(jshort); - jshort getFormat(jstring); - static jint getNumberOfBuiltinBuiltinFormats(); - //TODO static jlist getBuiltinFormats(); - - }; - class HSSFFont : public ::java::lang::Object { - public: - static const jshort BOLDWEIGHT_BOLD; -static const jshort BOLDWEIGHT_NORMAL; -static const jshort COLOR_NORMAL; -static const jshort COLOR_RED; -static const jstring FONT_ARIAL; -static const jshort SS_NONE; -static const jshort SS_SUB; -static const jshort SS_SUPER; -static const jshort U_DOUBLE; -static const jshort U_DOUBLE_ACCOUNTING; -static const jshort U_NONE; -static const jshort U_SINGLE; -static const jshort U_SINGLE_ACCOUNTING; - - jshort getBoldweight(); - jshort getColor(); - jshort getFontHeight(); - jshort getFontHeightInPoints(); - jstring getFontName(); - jshort getIndex(); - jboolean getItalic(); - jboolean getStrikeout(); - jshort getTypeOffset(); - jshort getUnderline(); - void setBoldweight(jshort ); - void setColor(jshort ); - void setFontHeight(jshort ); - void setFontHeightInPoints(jshort ); - void setFontName(jstring ); - void setItalic(jboolean ); - void setStrikeout(jboolean ); - void setTypeOffset(jshort ); - void setUnderline(jshort ); -}; -%makedefault; - } - } - } - } -} - - - - - -%init %{ - - JvCreateJavaVM(NULL); - JvAttachCurrentThread(NULL, NULL); - - nextThread = new java::lang::Thread(); - objects = new java::util::HashMap(); - - java::util::HashMap *props = (java::util::HashMap *) - java::lang::System::getProperties(); - props->put(JvNewStringUTF("inRuby"), objects); - - JvInitClass(&org::apache::poi::hssf::usermodel::HSSFFont::class$); - JvInitClass(&org::apache::poi::hssf::usermodel::HSSFCell::class$); - JvInitClass(&org::apache::poi::hssf::usermodel::HSSFSheet::class$); - JvInitClass(&org::apache::poi::hssf::usermodel::HSSFCellStyle::class$); - -%} - diff --git a/src/contrib/poi-ruby/cpp/RubyIO.cpp b/src/contrib/poi-ruby/cpp/RubyIO.cpp deleted file mode 100644 index d4a4638cf..000000000 --- a/src/contrib/poi-ruby/cpp/RubyIO.cpp +++ /dev/null @@ -1,44 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -#include - -#include "ruby.h" -#include "org/apache/poi/RubyOutputStream.h" - - -/** - * The native functions declared in org.apache.poi.RubyoutputStream - * - * @author aviks - */ - - namespace org { - namespace apache { - namespace poi { - - void RubyOutputStream::close(void) - { - rb_funcall3((VALUE ) rubyIO, rb_intern("close"), 0, NULL); - } - - void RubyOutputStream::write(jint toWrite) - { - rb_funcall((VALUE ) rubyIO, rb_intern("putc"),1,INT2FIX(toWrite)); - } - } - } -} diff --git a/src/contrib/poi-ruby/java/org/apache/poi/RubyOutputStream.java b/src/contrib/poi-ruby/java/org/apache/poi/RubyOutputStream.java deleted file mode 100644 index e23a0a7d3..000000000 --- a/src/contrib/poi-ruby/java/org/apache/poi/RubyOutputStream.java +++ /dev/null @@ -1,62 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - - -package org.apache.poi; - - -import java.io.OutputStream; -import java.io.IOException; - -/** - * @author aviks - * Wrap a java.io.OutputStream around a Ruby IO object - */ - -public class RubyOutputStream extends OutputStream { - - //pointer to native ruby VALUE - protected long rubyIO; - - public RubyOutputStream (long rubyIO) - { - this.rubyIO = rubyIO; -// incRef(); - } - - @Override - protected void finalize() - throws Throwable - { -// decRef(); - } - -// protected native void incRef(); -// protected native void decRef(); - - @Override - public native void close() - throws IOException; - - - /* (non-Javadoc) - * @see java.io.OutputStream#write(int) - */ - @Override - public native void write(int arg0) throws IOException; -} - diff --git a/src/contrib/poi-ruby/tests/tc_base_tests.rb b/src/contrib/poi-ruby/tests/tc_base_tests.rb deleted file mode 100644 index 33492c7ab..000000000 --- a/src/contrib/poi-ruby/tests/tc_base_tests.rb +++ /dev/null @@ -1,100 +0,0 @@ -# ==================================================================== -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ==================================================================== - -require 'test/unit' -require 'release/poi4r' - -class TC_base_tests < Test::Unit::TestCase - - def setup() - end - - def test_get_constant - h=Poi4r::HSSFWorkbook.new - s=h.createSheet("Sheet1") - r=s.createRow(0) - c=r.createCell(0) - assert_equal(3,Poi4r::HSSFCell.CELL_TYPE_BLANK,"Constant CELL_TYPE_BLANK") - end - - def test_base - system("rm test.xls") - h=Poi4r::HSSFWorkbook.new - - #Test Sheet Creation - s=h.createSheet("Sheet1") - s=h.createSheet("Sheet2") - assert_equal(2,h.getNumberOfSheets(),"Number of sheets is 2") - - #Test setting cell values - s=h.getSheetAt(0) - r=s.createRow(0) - c=r.createCell(0) - c.setCellValue(1.5) - assert_equal(c.getNumericCellValue(),1.5,"Numeric Cell Value") - c=r.createCell(1) - c.setCellValue("Ruby") - assert_equal(c.getStringCellValue(),"Ruby","String Cell Value") - #Test error handling - assert_raise (RuntimeError) {c.getNumericCellValue()} - - #Test styles - st = h.createCellStyle() - c=r.createCell(2) - st.setAlignment(Poi4r::HSSFCellStyle.ALIGN_CENTER) - c.setCellStyle(st) - c.setCellValue("centr'd") - - #Date handling - c=r.createCell(3) - t1=Time.now - c.setCellValue(Time.now) - t2= c.getDateCellValue().gmtime - assert_equal(t1.year,t2.year,"year") - assert_equal(t1.mon,t2.mon,"month") - assert_equal(t1.day,t2.day,"day") - assert_equal(t1.hour,t2.hour,"hour") - assert_equal(t1.min,t2.min,"min") - assert_equal(t1.sec,t2.sec,"sec") - st=h.createCellStyle(); - st.setDataFormat(Poi4r::HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm")) - c.setCellStyle(st) - - #Fonts - c=r.createCell(4) - font = h.createFont(); - font.setFontHeightInPoints(24); - font.setFontName("Courier New"); - font.setItalic(true); - font.setStrikeout(true); - style = h.createCellStyle(); - style.setFont(font); - c.setCellValue("This is a test of fonts"); - c.setCellStyle(style); - - #Formulas - c=r.createCell(5) - c.setCellFormula("A1*2") - assert_equal("A1*2",c.getCellFormula,"formula") - - #Test writing - h.write(File.new("test.xls","w")) - assert_nothing_raised {File.new("test.xls","r")} - #h.write(0.1) - end - -end diff --git a/src/contrib/poi-ruby/tests/tc_gc.rb b/src/contrib/poi-ruby/tests/tc_gc.rb deleted file mode 100644 index 82c3c2b13..000000000 --- a/src/contrib/poi-ruby/tests/tc_gc.rb +++ /dev/null @@ -1,32 +0,0 @@ -# ==================================================================== -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ==================================================================== - -require 'test/unit' -require 'release/poi4r' - -class TC_gc < Test::Unit::TestCase - def test_premature_collection - h=Poi4r::HSSFWorkbook.new - h.createSheet("Sheet1"); - 5000.times do - hh=Poi4r::HSSFWorkbook.new - GC.start() - end - assert_equal(1,h.getNumberOfSheets(),"Number of sheets") - end -end - diff --git a/src/contrib/poi-ruby/tests/ts_all.rb b/src/contrib/poi-ruby/tests/ts_all.rb deleted file mode 100644 index ef50ad5d6..000000000 --- a/src/contrib/poi-ruby/tests/ts_all.rb +++ /dev/null @@ -1,20 +0,0 @@ -# ==================================================================== -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ==================================================================== - -require 'test/unit' -require 'tests/tc_base_tests' -require 'tests/tc_gc' diff --git a/src/contrib/testcases/dummy.txt b/src/contrib/testcases/dummy.txt deleted file mode 100644 index e69de29bb..000000000 diff --git a/src/examples/jsp/HSSFExample.jsp b/src/examples/jsp/HSSFExample.jsp deleted file mode 100644 index b641846bd..000000000 --- a/src/examples/jsp/HSSFExample.jsp +++ /dev/null @@ -1,116 +0,0 @@ - -<%@page contentType="text/html" -import="java.io.*,org.apache.poi.poifs.filesystem.POIFSFileSystem,org.apache.poi -.hssf.record.*,org.apache.poi.hssf.model.*,org.apache.poi.hssf.usermodel.*,org.a -pache.poi.hssf.util.*" %> - -Read Excel file - - -An example of using Jakarta POI's HSSF package to read an excel spreadsheet: - - -
-Select an Excel file to read. - -
- -<% - String filename = request.getParameter("xls_filename"); - if (filename != null && !filename.equals("")) { -%> -
You chose the file <%= filename %>. -

It's contents are: -<% - try - { - - // create a poi workbook from the excel spreadsheet file - POIFSFileSystem fs = - new POIFSFileSystem(new FileInputStream(filename)); - HSSFWorkbook wb = new HSSFWorkbook(fs); - - for (int k = 0; k < wb.getNumberOfSheets(); k++) - { -%> -

Sheet <%= k %>
-<% - - HSSFSheet sheet = wb.getSheetAt(k); - int rows = sheet.getPhysicalNumberOfRows(); - - for (int r = 0; r < rows; r++) - { - HSSFRow row = sheet.getRow(r); - if (row != null) { - int cells = row.getPhysicalNumberOfCells(); -%> -
ROW <%= -row.getRowNum() %> -<% - for (short c = 0; c < cells; c++) - { - HSSFCell cell = row.getCell(c); - if (cell != null) { - String value = null; - - switch (cell.getCellType()) - { - - case HSSFCell.CELL_TYPE_FORMULA : - value = "FORMULA "; - break; - - case HSSFCell.CELL_TYPE_NUMERIC : - value = "NUMERIC value=" - + cell.getNumericCellValue -(); - break; - - case HSSFCell.CELL_TYPE_STRING : - value = "STRING value=" - + cell.getStringCellValue(); - break; - - default : - } -%> - <%= "CELL col=" - - + cell.getColumnIndex() - + " VALUE=" + value %> -<% - } - } - } - } - } - } - catch (Exception e) - { -%> - Error occurred: <%= e.getMessage() %> -<% - e.printStackTrace(); - } - - } -%> - - - diff --git a/src/examples/lib/dummy.txt b/src/examples/lib/dummy.txt deleted file mode 100644 index ee37f4519..000000000 --- a/src/examples/lib/dummy.txt +++ /dev/null @@ -1 +0,0 @@ -Dummy file so this directory is not deleted by CVS. It's required for the build. \ No newline at end of file diff --git a/src/examples/src/org/apache/poi/crypt/examples/EncryptionUtils.java b/src/examples/src/org/apache/poi/crypt/examples/EncryptionUtils.java deleted file mode 100644 index c2b795cb5..000000000 --- a/src/examples/src/org/apache/poi/crypt/examples/EncryptionUtils.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.crypt.examples; - -import java.io.InputStream; - -import org.apache.poi.poifs.crypt.Decryptor; -import org.apache.poi.poifs.crypt.EncryptionInfo; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.util.IOUtils; - -public class EncryptionUtils { - private EncryptionUtils() { - } - - public static InputStream decrypt(final InputStream inputStream, final String pwd) throws Exception { - try { - POIFSFileSystem fs = new POIFSFileSystem(inputStream); - EncryptionInfo info = new EncryptionInfo(fs); - Decryptor d = Decryptor.getInstance(info); - if (!d.verifyPassword(pwd)) { - throw new RuntimeException("incorrect password"); - } - return d.getDataStream(fs); - } finally { - IOUtils.closeQuietly(inputStream); - } - } -} diff --git a/src/examples/src/org/apache/poi/examples/util/TempFileUtils.java b/src/examples/src/org/apache/poi/examples/util/TempFileUtils.java deleted file mode 100644 index 5d4f7ab53..000000000 --- a/src/examples/src/org/apache/poi/examples/util/TempFileUtils.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.examples.util; - -import java.io.File; -import java.io.IOException; - -import org.apache.poi.util.TempFile; - -public class TempFileUtils { - private TempFileUtils() { - } - - public static void checkTempFiles() throws IOException { - String tmpDir = System.getProperty(TempFile.JAVA_IO_TMPDIR) + "/poifiles"; - File tempDir = new File(tmpDir); - if(tempDir.exists()) { - String[] tempFiles = tempDir.list(); - if(tempFiles != null && tempFiles.length > 0) { - System.out.println("found files in poi temp dir " + tempDir.getAbsolutePath()); - for(String filename : tempFiles) { - System.out.println("file: " + filename); - } - } - } else { - System.out.println("unable to find poi temp dir"); - } - } -} diff --git a/src/examples/src/org/apache/poi/hpsf/examples/CopyCompare.java b/src/examples/src/org/apache/poi/hpsf/examples/CopyCompare.java deleted file mode 100644 index 1a0ade2af..000000000 --- a/src/examples/src/org/apache/poi/hpsf/examples/CopyCompare.java +++ /dev/null @@ -1,499 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hpsf.examples; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.UnsupportedEncodingException; -import java.util.HashMap; -import java.util.Map; - -import org.apache.poi.hpsf.HPSFRuntimeException; -import org.apache.poi.hpsf.MarkUnsupportedException; -import org.apache.poi.hpsf.MutablePropertySet; -import org.apache.poi.hpsf.NoPropertySetStreamException; -import org.apache.poi.hpsf.PropertySet; -import org.apache.poi.hpsf.PropertySetFactory; -import org.apache.poi.hpsf.Util; -import org.apache.poi.hpsf.WritingNotSupportedException; -import org.apache.poi.poifs.eventfilesystem.POIFSReader; -import org.apache.poi.poifs.eventfilesystem.POIFSReaderEvent; -import org.apache.poi.poifs.eventfilesystem.POIFSReaderListener; -import org.apache.poi.poifs.filesystem.DirectoryEntry; -import org.apache.poi.poifs.filesystem.DocumentEntry; -import org.apache.poi.poifs.filesystem.DocumentInputStream; -import org.apache.poi.poifs.filesystem.Entry; -import org.apache.poi.poifs.filesystem.POIFSDocumentPath; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.util.TempFile; - -/** - *

This class copies a POI file system to a new file and compares the copy - * with the original.

- * - *

Property set streams are copied logically, i.e. the application - * establishes a {@link org.apache.poi.hpsf.PropertySet} of an original property - * set, creates a {@link org.apache.poi.hpsf.MutablePropertySet} from the - * {@link org.apache.poi.hpsf.PropertySet} and writes the - * {@link org.apache.poi.hpsf.MutablePropertySet} to the destination POI file - * system. - Streams which are no property set streams are copied bit by - * bit.

- * - *

The comparison of the POI file systems is done logically. That means that - * the two disk files containing the POI file systems do not need to be - * exactly identical. However, both POI file systems must contain the same - * files, and most of these files must be bitwise identical. Property set - * streams, however, are compared logically: they must have the same sections - * with the same attributs, and the sections must contain the same properties. - * Details like the ordering of the properties do not matter.

- */ -public class CopyCompare -{ - /** - *

Runs the example program. The application expects one or two - * arguments:

- * - *
    - * - *
  1. The first argument is the disk file name of the POI filesystem to - * copy.

  2. - * - *
  3. The second argument is optional. If it is given, it is the name of - * a disk file the copy of the POI filesystem will be written to. If it is - * not given, the copy will be written to a temporary file which will be - * deleted at the end of the program.

  4. - * - *
- * - * @param args Command-line arguments. - * @exception MarkUnsupportedException if a POI document stream does not - * support the mark() operation. - * @exception NoPropertySetStreamException if the application tries to - * create a property set from a POI document stream that is not a property - * set stream. - * @exception IOException if any I/O exception occurs. - * @exception UnsupportedEncodingException if a character encoding is not - * supported. - */ - public static void main(final String[] args) - throws NoPropertySetStreamException, MarkUnsupportedException, - UnsupportedEncodingException, IOException - { - String originalFileName = null; - String copyFileName = null; - - /* Check the command-line arguments. */ - if (args.length == 1) { - originalFileName = args[0]; - File f = TempFile.createTempFile("CopyOfPOIFileSystem-", ".ole2"); - f.deleteOnExit(); - copyFileName = f.getAbsolutePath(); - } else if (args.length == 2) { - originalFileName = args[0]; - copyFileName = args[1]; - } else { - System.err.println("Usage: " + CopyCompare.class.getName() + - "originPOIFS [copyPOIFS]"); - System.exit(1); - } - - /* Read the origin POIFS using the eventing API. The real work is done - * in the class CopyFile which is registered here as a POIFSReader. */ - final POIFSReader r = new POIFSReader(); - final CopyFile cf = new CopyFile(copyFileName); - r.registerListener(cf); - FileInputStream fis = new FileInputStream(originalFileName); - r.read(fis); - fis.close(); - - /* Write the new POIFS to disk. */ - cf.close(); - - /* Read all documents from the original POI file system and compare them - * with the equivalent document from the copy. */ - final POIFSFileSystem opfs = new POIFSFileSystem(new File(originalFileName)); - final POIFSFileSystem cpfs = new POIFSFileSystem(new File(copyFileName)); - - final DirectoryEntry oRoot = opfs.getRoot(); - final DirectoryEntry cRoot = cpfs.getRoot(); - final StringBuffer messages = new StringBuffer(); - if (equal(oRoot, cRoot, messages)) { - System.out.println("Equal"); - } else { - System.out.println("Not equal: " + messages.toString()); - } - cpfs.close(); - opfs.close(); - } - - - - /** - *

Compares two {@link DirectoryEntry} instances of a POI file system. - * The directories must contain the same streams with the same names and - * contents.

- * - * @param d1 The first directory. - * @param d2 The second directory. - * @param msg The method may append human-readable comparison messages to - * this string buffer. - * @return true if the directories are equal, else - * false. - * @exception MarkUnsupportedException if a POI document stream does not - * support the mark() operation. - * @exception NoPropertySetStreamException if the application tries to - * create a property set from a POI document stream that is not a property - * set stream. - * @throws UnsupportedEncodingException - * @exception IOException if any I/O exception occurs. - */ - private static boolean equal(final DirectoryEntry d1, - final DirectoryEntry d2, - final StringBuffer msg) - throws NoPropertySetStreamException, MarkUnsupportedException, - UnsupportedEncodingException, IOException - { - boolean equal = true; - /* Iterate over d1 and compare each entry with its counterpart in d2. */ - for (final Entry e1 : d1) { - final String n1 = e1.getName(); - Entry e2 = null; - try { - e2 = d2.getEntry(n1); - } catch (FileNotFoundException ex) { - msg.append("Document \"" + e1 + "\" exists, document \"" + - e2 + "\" does not.\n"); - equal = false; - break; - } - - if (e1.isDirectoryEntry() && e2.isDirectoryEntry()) { - equal = equal((DirectoryEntry) e1, (DirectoryEntry) e2, msg); - } else if (e1.isDocumentEntry() && e2.isDocumentEntry()) { - equal = equal((DocumentEntry) e1, (DocumentEntry) e2, msg); - } else { - msg.append("One of \"" + e1 + "\" and \"" + e2 + "\" is a " + - "document while the other one is a directory.\n"); - equal = false; - } - } - - /* Iterate over d2 just to make sure that there are no entries in d2 - * that are not in d1. */ - for (final Entry e2 : d2) { - final String n2 = e2.getName(); - Entry e1 = null; - try { - e1 = d1.getEntry(n2); - } catch (FileNotFoundException ex) { - msg.append("Document \"" + e2 + "\" exitsts, document \"" + - e1 + "\" does not.\n"); - equal = false; - break; - } - } - return equal; - } - - - - /** - *

Compares two {@link DocumentEntry} instances of a POI file system. - * Documents that are not property set streams must be bitwise identical. - * Property set streams must be logically equal.

- * - * @param d1 The first document. - * @param d2 The second document. - * @param msg The method may append human-readable comparison messages to - * this string buffer. - * @return true if the documents are equal, else - * false. - * @exception MarkUnsupportedException if a POI document stream does not - * support the mark() operation. - * @exception NoPropertySetStreamException if the application tries to - * create a property set from a POI document stream that is not a property - * set stream. - * @throws UnsupportedEncodingException - * @exception IOException if any I/O exception occurs. - */ - private static boolean equal(final DocumentEntry d1, final DocumentEntry d2, - final StringBuffer msg) - throws NoPropertySetStreamException, MarkUnsupportedException, - UnsupportedEncodingException, IOException - { - final DocumentInputStream dis1 = new DocumentInputStream(d1); - final DocumentInputStream dis2 = new DocumentInputStream(d2); - try { - if (PropertySet.isPropertySetStream(dis1) && - PropertySet.isPropertySetStream(dis2)) { - final PropertySet ps1 = PropertySetFactory.create(dis1); - final PropertySet ps2 = PropertySetFactory.create(dis2); - if (!ps1.equals(ps2)) { - msg.append("Property sets are not equal.\n"); - return false; - } - } else { - int i1, i2; - do { - i1 = dis1.read(); - i2 = dis2.read(); - if (i1 != i2) { - msg.append("Documents are not equal.\n"); - return false; - } - } while (i1 > -1); - } - } finally { - dis2.close(); - dis1.close(); - } - return true; - } - - - - /** - *

This class does all the work. Its method {@link - * #processPOIFSReaderEvent(POIFSReaderEvent)} is called for each file in - * the original POI file system. Except for property set streams it copies - * everything unmodified to the destination POI filesystem. Property set - * streams are copied by creating a new {@link PropertySet} from the - * original property set by using the {@link - * MutablePropertySet#MutablePropertySet(PropertySet)} constructor.

- */ - static class CopyFile implements POIFSReaderListener { - private String dstName; - private OutputStream out; - private POIFSFileSystem poiFs; - - - /** - *

The constructor of a {@link CopyFile} instance creates the target - * POIFS. It also stores the name of the file the POIFS will be written - * to once it is complete.

- * - * @param dstName The name of the disk file the destination POIFS is to - * be written to. - */ - public CopyFile(final String dstName) { - this.dstName = dstName; - poiFs = new POIFSFileSystem(); - } - - - /** - *

The method is called by POI's eventing API for each file in the - * origin POIFS.

- */ - @Override - public void processPOIFSReaderEvent(final POIFSReaderEvent event) { - /* The following declarations are shortcuts for accessing the - * "event" object. */ - final POIFSDocumentPath path = event.getPath(); - final String name = event.getName(); - final DocumentInputStream stream = event.getStream(); - - Throwable t = null; - - try { - /* Find out whether the current document is a property set - * stream or not. */ - if (PropertySet.isPropertySetStream(stream)) { - /* Yes, the current document is a property set stream. - * Let's create a PropertySet instance from it. */ - PropertySet ps = null; - try { - ps = PropertySetFactory.create(stream); - } catch (NoPropertySetStreamException ex) { - /* This exception will not be thrown because we already - * checked above. */ - } - - /* Copy the property set to the destination POI file - * system. */ - copy(poiFs, path, name, ps); - } else { - /* No, the current document is not a property set stream. We - * copy it unmodified to the destination POIFS. */ - copy(poiFs, event.getPath(), event.getName(), stream); - } - } catch (MarkUnsupportedException ex) { - t = ex; - } catch (IOException ex) { - t = ex; - } catch (WritingNotSupportedException ex) { - t = ex; - } - - /* According to the definition of the processPOIFSReaderEvent method - * we cannot pass checked exceptions to the caller. The following - * lines check whether a checked exception occured and throws an - * unchecked exception. The message of that exception is that of - * the underlying checked exception. */ - if (t != null) { - throw new HPSFRuntimeException - ("Could not read file \"" + path + "/" + name + - "\". Reason: " + Util.toString(t)); - } - } - - - - /** - *

Writes a {@link PropertySet} to a POI filesystem.

- * - * @param poiFs The POI filesystem to write to. - * @param path The file's path in the POI filesystem. - * @param name The file's name in the POI filesystem. - * @param ps The property set to write. - * @throws WritingNotSupportedException - * @throws IOException - */ - public void copy(final POIFSFileSystem poiFs, - final POIFSDocumentPath path, - final String name, - final PropertySet ps) - throws WritingNotSupportedException, IOException { - final DirectoryEntry de = getPath(poiFs, path); - final MutablePropertySet mps = new MutablePropertySet(ps); - de.createDocument(name, mps.toInputStream()); - } - - - - /** - *

Copies the bytes from a {@link DocumentInputStream} to a new - * stream in a POI filesystem.

- * - * @param poiFs The POI filesystem to write to. - * @param path The source document's path. - * @param name The source document's name. - * @param stream The stream containing the source document. - * @throws IOException - */ - public void copy(final POIFSFileSystem poiFs, - final POIFSDocumentPath path, - final String name, - final DocumentInputStream stream) - throws IOException { - final DirectoryEntry de = getPath(poiFs, path); - final ByteArrayOutputStream out = new ByteArrayOutputStream(); - int c; - while ((c = stream.read()) != -1) { - out.write(c); - } - stream.close(); - out.close(); - final InputStream in = - new ByteArrayInputStream(out.toByteArray()); - de.createDocument(name, in); - } - - - /** - *

Writes the POI file system to a disk file.

- * - * @throws FileNotFoundException - * @throws IOException - */ - public void close() throws FileNotFoundException, IOException { - out = new FileOutputStream(dstName); - poiFs.writeFilesystem(out); - out.close(); - } - - - - /** Contains the directory paths that have already been created in the - * output POI filesystem and maps them to their corresponding - * {@link org.apache.poi.poifs.filesystem.DirectoryNode}s. */ - private final Map paths = new HashMap(); - - - - /** - *

Ensures that the directory hierarchy for a document in a POI - * fileystem is in place. When a document is to be created somewhere in - * a POI filesystem its directory must be created first. This method - * creates all directories between the POI filesystem root and the - * directory the document should belong to which do not yet exist.

- * - *

Unfortunately POI does not offer a simple method to interrogate - * the POIFS whether a certain child node (file or directory) exists in - * a directory. However, since we always start with an empty POIFS which - * contains the root directory only and since each directory in the - * POIFS is created by this method we can maintain the POIFS's directory - * hierarchy ourselves: The {@link DirectoryEntry} of each directory - * created is stored in a {@link Map}. The directories' path names map - * to the corresponding {@link DirectoryEntry} instances.

- * - * @param poiFs The POI filesystem the directory hierarchy is created - * in, if needed. - * @param path The document's path. This method creates those directory - * components of this hierarchy which do not yet exist. - * @return The directory entry of the document path's parent. The caller - * should use this {@link DirectoryEntry} to create documents in it. - */ - public DirectoryEntry getPath(final POIFSFileSystem poiFs, - final POIFSDocumentPath path) { - try { - /* Check whether this directory has already been created. */ - final String s = path.toString(); - DirectoryEntry de = paths.get(s); - if (de != null) - /* Yes: return the corresponding DirectoryEntry. */ - return de; - - /* No: We have to create the directory - or return the root's - * DirectoryEntry. */ - int l = path.length(); - if (l == 0) { - /* Get the root directory. It does not have to be created - * since it always exists in a POIFS. */ - de = poiFs.getRoot(); - } else { - /* Create a subordinate directory. The first step is to - * ensure that the parent directory exists: */ - de = getPath(poiFs, path.getParent()); - /* Now create the target directory: */ - de = de.createDirectory(path.getComponent - (path.length() - 1)); - } - paths.put(s, de); - return de; - } catch (IOException ex) { - /* This exception will be thrown if the directory already - * exists. However, since we have full control about directory - * creation we can ensure that this will never happen. */ - ex.printStackTrace(System.err); - throw new RuntimeException(ex.toString()); - /* FIXME (2): Replace the previous line by the following once we - * no longer need JDK 1.3 compatibility. */ - // throw new RuntimeException(ex); - } - } - } - -} diff --git a/src/examples/src/org/apache/poi/hpsf/examples/ModifyDocumentSummaryInformation.java b/src/examples/src/org/apache/poi/hpsf/examples/ModifyDocumentSummaryInformation.java deleted file mode 100644 index 81a9594e7..000000000 --- a/src/examples/src/org/apache/poi/hpsf/examples/ModifyDocumentSummaryInformation.java +++ /dev/null @@ -1,173 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hpsf.examples; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.Date; - -import org.apache.poi.hpsf.CustomProperties; -import org.apache.poi.hpsf.DocumentSummaryInformation; -import org.apache.poi.hpsf.MarkUnsupportedException; -import org.apache.poi.hpsf.NoPropertySetStreamException; -import org.apache.poi.hpsf.PropertySetFactory; -import org.apache.poi.hpsf.SummaryInformation; -import org.apache.poi.hpsf.UnexpectedPropertySetTypeException; -import org.apache.poi.hpsf.WritingNotSupportedException; -import org.apache.poi.poifs.filesystem.DirectoryEntry; -import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; - -/** - *

This is a sample application showing how to easily modify properties in - * the summary information and in the document summary information. The - * application reads the name of a POI filesystem from the command line and - * performs the following actions:

- * - *
    - * - *
  • Open the POI filesystem.

  • - * - *
  • Read the summary information.

  • - * - *
  • Read and print the "author" property.

  • - * - *
  • Change the author to "Rainer Klute".

  • - * - *
  • Read the document summary information.

  • - * - *
  • Read and print the "category" property.

  • - * - *
  • Change the category to "POI example".

  • - * - *
  • Read the custom properties (if available).

  • - * - *
  • Insert a new custom property.

  • - * - *
  • Write the custom properties back to the document summary - * information.

  • - * - *
  • Write the summary information to the POI filesystem.

  • - * - *
  • Write the document summary information to the POI filesystem.

  • - * - *
  • Write the POI filesystem back to the original file.

  • - * - * - */ -public class ModifyDocumentSummaryInformation { - - /** - *

    Main method - see class description.

    - * - * @param args The command-line parameters. - * @throws IOException - * @throws MarkUnsupportedException - * @throws NoPropertySetStreamException - * @throws UnexpectedPropertySetTypeException - * @throws WritingNotSupportedException - */ - public static void main(final String[] args) throws IOException, - NoPropertySetStreamException, MarkUnsupportedException, - UnexpectedPropertySetTypeException, WritingNotSupportedException - { - /* Read the name of the POI filesystem to modify from the command line. - * For brevity to boundary check is performed on the command-line - * arguments. */ - File summaryFile = new File(args[0]); - - /* Open the POI filesystem. */ - NPOIFSFileSystem poifs = new NPOIFSFileSystem(summaryFile, false); - - /* Read the summary information. */ - DirectoryEntry dir = poifs.getRoot(); - SummaryInformation si; - try - { - si = (SummaryInformation)PropertySetFactory.create( - dir, SummaryInformation.DEFAULT_STREAM_NAME); - } - catch (FileNotFoundException ex) - { - // There is no summary information yet. We have to create a new one - si = PropertySetFactory.newSummaryInformation(); - } - - /* Change the author to "Rainer Klute". Any former author value will - * be lost. If there has been no author yet, it will be created. */ - si.setAuthor("Rainer Klute"); - System.out.println("Author changed to " + si.getAuthor() + "."); - - - /* Handling the document summary information is analogous to handling - * the summary information. An additional feature, however, are the - * custom properties. */ - - /* Read the document summary information. */ - DocumentSummaryInformation dsi; - try - { - dsi = (DocumentSummaryInformation)PropertySetFactory.create( - dir, DocumentSummaryInformation.DEFAULT_STREAM_NAME); - } - catch (FileNotFoundException ex) - { - /* There is no document summary information yet. We have to create a - * new one. */ - dsi = PropertySetFactory.newDocumentSummaryInformation(); - } - - /* Change the category to "POI example". Any former category value will - * be lost. If there has been no category yet, it will be created. */ - dsi.setCategory("POI example"); - System.out.println("Category changed to " + dsi.getCategory() + "."); - - /* Read the custom properties. If there are no custom properties yet, - * the application has to create a new CustomProperties object. It will - * serve as a container for custom properties. */ - CustomProperties customProperties = dsi.getCustomProperties(); - if (customProperties == null) - customProperties = new CustomProperties(); - - /* Insert some custom properties into the container. */ - customProperties.put("Key 1", "Value 1"); - customProperties.put("Schl\u00fcssel 2", "Wert 2"); - customProperties.put("Sample Number", new Integer(12345)); - customProperties.put("Sample Boolean", Boolean.TRUE); - customProperties.put("Sample Date", new Date()); - - /* Read a custom property. */ - Object value = customProperties.get("Sample Number"); - System.out.println("Custom Sample Number is now " + value); - - /* Write the custom properties back to the document summary - * information. */ - dsi.setCustomProperties(customProperties); - - /* Write the summary information and the document summary information - * to the POI filesystem. */ - si.write(dir, SummaryInformation.DEFAULT_STREAM_NAME); - dsi.write(dir, DocumentSummaryInformation.DEFAULT_STREAM_NAME); - - /* Write the POI filesystem back to the original file. Please note that - * in production code you should take care when write directly to the - * origin, to make sure you don't loose things on error */ - poifs.writeFilesystem(); - poifs.close(); - } -} diff --git a/src/examples/src/org/apache/poi/hpsf/examples/ReadCustomPropertySets.java b/src/examples/src/org/apache/poi/hpsf/examples/ReadCustomPropertySets.java deleted file mode 100644 index 964984211..000000000 --- a/src/examples/src/org/apache/poi/hpsf/examples/ReadCustomPropertySets.java +++ /dev/null @@ -1,135 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hpsf.examples; - -import java.io.FileInputStream; -import java.io.IOException; -import java.util.Iterator; -import java.util.List; - -import org.apache.poi.hpsf.NoPropertySetStreamException; -import org.apache.poi.hpsf.Property; -import org.apache.poi.hpsf.PropertySet; -import org.apache.poi.hpsf.PropertySetFactory; -import org.apache.poi.hpsf.Section; -import org.apache.poi.poifs.eventfilesystem.POIFSReader; -import org.apache.poi.poifs.eventfilesystem.POIFSReaderEvent; -import org.apache.poi.poifs.eventfilesystem.POIFSReaderListener; -import org.apache.poi.util.HexDump; - -/** - *

    Sample application showing how to read a document's custom property set. - * Call it with the document's file name as command-line parameter.

    - * - *

    Explanations can be found in the HPSF HOW-TO.

    - */ -public class ReadCustomPropertySets -{ - - /** - *

    Runs the example program.

    - * - * @param args Command-line arguments (unused). - * @throws IOException if any I/O exception occurs. - */ - public static void main(final String[] args) - throws IOException - { - final String filename = args[0]; - POIFSReader r = new POIFSReader(); - - /* Register a listener for *all* documents. */ - r.registerListener(new MyPOIFSReaderListener()); - r.read(new FileInputStream(filename)); - } - - - static class MyPOIFSReaderListener implements POIFSReaderListener - { - @Override - public void processPOIFSReaderEvent(final POIFSReaderEvent event) - { - PropertySet ps = null; - try - { - ps = PropertySetFactory.create(event.getStream()); - } - catch (NoPropertySetStreamException ex) - { - out("No property set stream: \"" + event.getPath() + - event.getName() + "\""); - return; - } - catch (Exception ex) - { - throw new RuntimeException - ("Property set stream \"" + - event.getPath() + event.getName() + "\": " + ex); - } - - /* Print the name of the property set stream: */ - out("Property set stream \"" + event.getPath() + - event.getName() + "\":"); - - /* Print the number of sections: */ - final long sectionCount = ps.getSectionCount(); - out(" No. of sections: " + sectionCount); - - /* Print the list of sections: */ - List
    sections = ps.getSections(); - int nr = 0; - for (Iterator
    i = sections.iterator(); i.hasNext();) - { - /* Print a single section: */ - Section sec = i.next(); - out(" Section " + nr++ + ":"); - String s = hex(sec.getFormatID().getBytes()); - s = s.substring(0, s.length() - 1); - out(" Format ID: " + s); - - /* Print the number of properties in this section. */ - int propertyCount = sec.getPropertyCount(); - out(" No. of properties: " + propertyCount); - - /* Print the properties: */ - Property[] properties = sec.getProperties(); - for (int i2 = 0; i2 < properties.length; i2++) - { - /* Print a single property: */ - Property p = properties[i2]; - long id = p.getID(); - long type = p.getType(); - Object value = p.getValue(); - out(" Property ID: " + id + ", type: " + type + - ", value: " + value); - } - } - } - } - - static void out(final String msg) - { - System.out.println(msg); - } - - static String hex(final byte[] bytes) - { - return HexDump.dump(bytes, 0L, 0); - } - -} diff --git a/src/examples/src/org/apache/poi/hpsf/examples/ReadTitle.java b/src/examples/src/org/apache/poi/hpsf/examples/ReadTitle.java deleted file mode 100644 index 180544410..000000000 --- a/src/examples/src/org/apache/poi/hpsf/examples/ReadTitle.java +++ /dev/null @@ -1,80 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hpsf.examples; - -import java.io.FileInputStream; -import java.io.IOException; - -import org.apache.poi.hpsf.PropertySetFactory; -import org.apache.poi.hpsf.SummaryInformation; -import org.apache.poi.poifs.eventfilesystem.POIFSReader; -import org.apache.poi.poifs.eventfilesystem.POIFSReaderEvent; -import org.apache.poi.poifs.eventfilesystem.POIFSReaderListener; - -/** - *

    Sample application showing how to read a OLE 2 document's - * title. Call it with the document's file name as command line - * parameter.

    - * - *

    Explanations can be found in the HPSF HOW-TO.

    - */ -public class ReadTitle -{ - /** - *

    Runs the example program.

    - * - * @param args Command-line arguments. The first command-line argument must - * be the name of a POI filesystem to read. - * @throws IOException if any I/O exception occurs. - */ - public static void main(final String[] args) throws IOException - { - final String filename = args[0]; - POIFSReader r = new POIFSReader(); - r.registerListener(new MyPOIFSReaderListener(), - "\005SummaryInformation"); - r.read(new FileInputStream(filename)); - } - - - static class MyPOIFSReaderListener implements POIFSReaderListener - { - @Override - public void processPOIFSReaderEvent(final POIFSReaderEvent event) - { - SummaryInformation si = null; - try - { - si = (SummaryInformation) - PropertySetFactory.create(event.getStream()); - } - catch (Exception ex) - { - throw new RuntimeException - ("Property set stream \"" + - event.getPath() + event.getName() + "\": " + ex); - } - final String title = si.getTitle(); - if (title != null) - System.out.println("Title: \"" + title + "\""); - else - System.out.println("Document has no title."); - } - } - -} diff --git a/src/examples/src/org/apache/poi/hpsf/examples/WriteAuthorAndTitle.java b/src/examples/src/org/apache/poi/hpsf/examples/WriteAuthorAndTitle.java deleted file mode 100644 index b5734c043..000000000 --- a/src/examples/src/org/apache/poi/hpsf/examples/WriteAuthorAndTitle.java +++ /dev/null @@ -1,408 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hpsf.examples; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.HashMap; -import java.util.Map; - -import org.apache.poi.hpsf.HPSFRuntimeException; -import org.apache.poi.hpsf.MarkUnsupportedException; -import org.apache.poi.hpsf.MutablePropertySet; -import org.apache.poi.hpsf.MutableSection; -import org.apache.poi.hpsf.NoPropertySetStreamException; -import org.apache.poi.hpsf.PropertySet; -import org.apache.poi.hpsf.PropertySetFactory; -import org.apache.poi.hpsf.SummaryInformation; -import org.apache.poi.hpsf.Util; -import org.apache.poi.hpsf.Variant; -import org.apache.poi.hpsf.WritingNotSupportedException; -import org.apache.poi.hpsf.wellknown.PropertyIDMap; -import org.apache.poi.poifs.eventfilesystem.POIFSReader; -import org.apache.poi.poifs.eventfilesystem.POIFSReaderEvent; -import org.apache.poi.poifs.eventfilesystem.POIFSReaderListener; -import org.apache.poi.poifs.filesystem.DirectoryEntry; -import org.apache.poi.poifs.filesystem.DocumentInputStream; -import org.apache.poi.poifs.filesystem.POIFSDocumentPath; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; - -/** - *

    This class is a sample application which shows how to write or modify the - * author and title property of an OLE 2 document. This could be done in two - * different ways:

    - * - *
      - * - *
    • The first approach is to open the OLE 2 file as a POI filesystem - * (see class {@link POIFSFileSystem}), read the summary information property - * set (see classes {@link SummaryInformation} and {@link PropertySet}), write - * the author and title properties into it and write the property set back into - * the POI filesystem.

    • - * - *
    • The second approach does not modify the original POI filesystem, but - * instead creates a new one. All documents from the original POIFS are copied - * to the destination POIFS, except for the summary information stream. The - * latter is modified by setting the author and title property before writing - * it to the destination POIFS. It there are several summary information streams - * in the original POIFS - e.g. in subordinate directories - they are modified - * just the same.

    • - * - *
    - * - *

    This sample application takes the second approach. It expects the name of - * the existing POI filesystem's name as its first command-line parameter and - * the name of the output POIFS as the second command-line argument. The - * program then works as described above: It copies nearly all documents - * unmodified from the input POI filesystem to the output POI filesystem. If it - * encounters a summary information stream it reads its properties. Then it sets - * the "author" and "title" properties to new values and writes the modified - * summary information stream into the output file.

    - * - *

    Further explanations can be found in the HPSF HOW-TO.

    - */ -public class WriteAuthorAndTitle -{ - /** - *

    Runs the example program.

    - * - * @param args Command-line arguments. The first command-line argument must - * be the name of a POI filesystem to read. - * @throws IOException if any I/O exception occurs. - */ - public static void main(final String[] args) throws IOException - { - /* Check whether we have exactly two command-line arguments. */ - if (args.length != 2) - { - System.err.println("Usage: " + WriteAuthorAndTitle.class.getName() + - " originPOIFS destinationPOIFS"); - System.exit(1); - } - - /* Read the names of the origin and destination POI filesystems. */ - final String srcName = args[0]; - final String dstName = args[1]; - - /* Read the origin POIFS using the eventing API. The real work is done - * in the class ModifySICopyTheRest which is registered here as a - * POIFSReader. */ - final POIFSReader r = new POIFSReader(); - final ModifySICopyTheRest msrl = new ModifySICopyTheRest(dstName); - r.registerListener(msrl); - FileInputStream fis = new FileInputStream(srcName); - r.read(fis); - fis.close(); - - /* Write the new POIFS to disk. */ - msrl.close(); - } - - - - /** - *

    This class does all the work. As its name implies it modifies a - * summary information property set and copies everything else unmodified - * to the destination POI filesystem. Since an instance of it is registered - * as a {@link POIFSReader} its method {@link - * #processPOIFSReaderEvent(POIFSReaderEvent)} is called for each document - * in the origin POIFS.

    - */ - static class ModifySICopyTheRest implements POIFSReaderListener - { - private String dstName; - private OutputStream out; - private POIFSFileSystem poiFs; - - - /** - *

    The constructor of a {@link ModifySICopyTheRest} instance creates - * the target POIFS. It also stores the name of the file the POIFS will - * be written to once it is complete.

    - * - * @param dstName The name of the disk file the destination POIFS is to - * be written to. - */ - public ModifySICopyTheRest(final String dstName) - { - this.dstName = dstName; - poiFs = new POIFSFileSystem(); - } - - - /** - *

    The method is called by POI's eventing API for each file in the - * origin POIFS.

    - */ - @Override - public void processPOIFSReaderEvent(final POIFSReaderEvent event) - { - /* The following declarations are shortcuts for accessing the - * "event" object. */ - final POIFSDocumentPath path = event.getPath(); - final String name = event.getName(); - final DocumentInputStream stream = event.getStream(); - - Throwable t = null; - - try { - /* Find out whether the current document is a property set - * stream or not. */ - if (PropertySet.isPropertySetStream(stream)) { - try { - /* Yes, the current document is a property set stream. - * Let's create a PropertySet instance from it. */ - PropertySet ps = PropertySetFactory.create(stream); - - /* Now we know that we really have a property set. The next - * step is to find out whether it is a summary information - * or not. */ - if (ps.isSummaryInformation()) { - /* Yes, it is a summary information. We will modify it - * and write the result to the destination POIFS. */ - editSI(poiFs, path, name, ps); - } else { - /* No, it is not a summary information. We don't care - * about its internals and copy it unmodified to the - * destination POIFS. */ - copy(poiFs, path, name, ps); - } - } catch (NoPropertySetStreamException ex) { - /* This exception will not be thrown because we already - * checked above. */ - } - } else { - /* No, the current document is not a property set stream. We - * copy it unmodified to the destination POIFS. */ - copy(poiFs, event.getPath(), event.getName(), stream); - } - } catch (MarkUnsupportedException ex) { - t = ex; - } catch (IOException ex) { - t = ex; - } catch (WritingNotSupportedException ex) { - t = ex; - } - - /* According to the definition of the processPOIFSReaderEvent method - * we cannot pass checked exceptions to the caller. The following - * lines check whether a checked exception occured and throws an - * unchecked exception. The message of that exception is that of - * the underlying checked exception. */ - if (t != null) { - throw new HPSFRuntimeException - ("Could not read file \"" + path + "/" + name + - "\". Reason: " + Util.toString(t)); - } - } - - - /** - *

    Receives a summary information property set modifies (or creates) - * its "author" and "title" properties and writes the result under the - * same path and name as the origin to a destination POI filesystem.

    - * - * @param poiFs The POI filesystem to write to. - * @param path The original (and destination) stream's path. - * @param name The original (and destination) stream's name. - * @param si The property set. It should be a summary information - * property set. - * @throws IOException - * @throws WritingNotSupportedException - */ - public void editSI(final POIFSFileSystem poiFs, - final POIFSDocumentPath path, - final String name, - final PropertySet si) - throws WritingNotSupportedException, IOException - - { - /* Get the directory entry for the target stream. */ - final DirectoryEntry de = getPath(poiFs, path); - - /* Create a mutable property set as a copy of the original read-only - * property set. */ - final MutablePropertySet mps = new MutablePropertySet(si); - - /* Retrieve the section containing the properties to modify. A - * summary information property set contains exactly one section. */ - final MutableSection s = - (MutableSection) mps.getSections().get(0); - - /* Set the properties. */ - s.setProperty(PropertyIDMap.PID_AUTHOR, Variant.VT_LPSTR, - "Rainer Klute"); - s.setProperty(PropertyIDMap.PID_TITLE, Variant.VT_LPWSTR, - "Test"); - - /* Create an input stream containing the bytes the property set - * stream consists of. */ - final InputStream pss = mps.toInputStream(); - - /* Write the property set stream to the POIFS. */ - de.createDocument(name, pss); - } - - - /** - *

    Writes a {@link PropertySet} to a POI filesystem. This method is - * simpler than {@link #editSI} because the origin property set has just - * to be copied.

    - * - * @param poiFs The POI filesystem to write to. - * @param path The file's path in the POI filesystem. - * @param name The file's name in the POI filesystem. - * @param ps The property set to write. - * @throws WritingNotSupportedException - * @throws IOException - */ - public void copy(final POIFSFileSystem poiFs, - final POIFSDocumentPath path, - final String name, - final PropertySet ps) - throws WritingNotSupportedException, IOException - { - final DirectoryEntry de = getPath(poiFs, path); - final MutablePropertySet mps = new MutablePropertySet(ps); - de.createDocument(name, mps.toInputStream()); - } - - - - /** - *

    Copies the bytes from a {@link DocumentInputStream} to a new - * stream in a POI filesystem.

    - * - * @param poiFs The POI filesystem to write to. - * @param path The source document's path. - * @param name The source document's name. - * @param stream The stream containing the source document. - * @throws IOException - */ - public void copy(final POIFSFileSystem poiFs, - final POIFSDocumentPath path, - final String name, - final DocumentInputStream stream) throws IOException - { - final DirectoryEntry de = getPath(poiFs, path); - final ByteArrayOutputStream out = new ByteArrayOutputStream(); - int c; - while ((c = stream.read()) != -1) - out.write(c); - stream.close(); - out.close(); - final InputStream in = - new ByteArrayInputStream(out.toByteArray()); - de.createDocument(name, in); - } - - - /** - *

    Writes the POI file system to a disk file.

    - * - * @throws FileNotFoundException - * @throws IOException - */ - public void close() throws FileNotFoundException, IOException - { - out = new FileOutputStream(dstName); - poiFs.writeFilesystem(out); - out.close(); - } - - - - /** Contains the directory paths that have already been created in the - * output POI filesystem and maps them to their corresponding - * {@link org.apache.poi.poifs.filesystem.DirectoryNode}s. */ - private final Map paths = new HashMap(); - - - - /** - *

    Ensures that the directory hierarchy for a document in a POI - * fileystem is in place. When a document is to be created somewhere in - * a POI filesystem its directory must be created first. This method - * creates all directories between the POI filesystem root and the - * directory the document should belong to which do not yet exist.

    - * - *

    Unfortunately POI does not offer a simple method to interrogate - * the POIFS whether a certain child node (file or directory) exists in - * a directory. However, since we always start with an empty POIFS which - * contains the root directory only and since each directory in the - * POIFS is created by this method we can maintain the POIFS's directory - * hierarchy ourselves: The {@link DirectoryEntry} of each directory - * created is stored in a {@link Map}. The directories' path names map - * to the corresponding {@link DirectoryEntry} instances.

    - * - * @param poiFs The POI filesystem the directory hierarchy is created - * in, if needed. - * @param path The document's path. This method creates those directory - * components of this hierarchy which do not yet exist. - * @return The directory entry of the document path's parent. The caller - * should use this {@link DirectoryEntry} to create documents in it. - */ - public DirectoryEntry getPath(final POIFSFileSystem poiFs, - final POIFSDocumentPath path) - { - try - { - /* Check whether this directory has already been created. */ - final String s = path.toString(); - DirectoryEntry de = paths.get(s); - if (de != null) - /* Yes: return the corresponding DirectoryEntry. */ - return de; - - /* No: We have to create the directory - or return the root's - * DirectoryEntry. */ - int l = path.length(); - if (l == 0) - /* Get the root directory. It does not have to be created - * since it always exists in a POIFS. */ - de = poiFs.getRoot(); - else - { - /* Create a subordinate directory. The first step is to - * ensure that the parent directory exists: */ - de = getPath(poiFs, path.getParent()); - /* Now create the target directory: */ - de = de.createDirectory(path.getComponent - (path.length() - 1)); - } - paths.put(s, de); - return de; - } - catch (IOException ex) - { - /* This exception will be thrown if the directory already - * exists. However, since we have full control about directory - * creation we can ensure that this will never happen. */ - ex.printStackTrace(System.err); - throw new RuntimeException(ex); - } - } - } - -} diff --git a/src/examples/src/org/apache/poi/hpsf/examples/WriteTitle.java b/src/examples/src/org/apache/poi/hpsf/examples/WriteTitle.java deleted file mode 100644 index 4323ce242..000000000 --- a/src/examples/src/org/apache/poi/hpsf/examples/WriteTitle.java +++ /dev/null @@ -1,106 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hpsf.examples; - -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.hpsf.MutableProperty; -import org.apache.poi.hpsf.MutablePropertySet; -import org.apache.poi.hpsf.MutableSection; -import org.apache.poi.hpsf.SummaryInformation; -import org.apache.poi.hpsf.Variant; -import org.apache.poi.hpsf.WritingNotSupportedException; -import org.apache.poi.hpsf.wellknown.PropertyIDMap; -import org.apache.poi.hpsf.wellknown.SectionIDMap; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; - -/** - *

    This class is a simple sample application showing how to create a property - * set and write it to disk.

    - */ -public class WriteTitle -{ - /** - *

    Runs the example program.

    - * - * @param args Command-line arguments. The first and only command-line - * argument is the name of the POI file system to create. - * @throws IOException if any I/O exception occurs. - * @throws WritingNotSupportedException if HPSF does not (yet) support - * writing a certain property type. - */ - public static void main(final String[] args) - throws WritingNotSupportedException, IOException - { - /* Check whether we have exactly one command-line argument. */ - if (args.length != 1) - { - System.err.println("Usage: " + WriteTitle.class.getName() + - "destinationPOIFS"); - System.exit(1); - } - - final String fileName = args[0]; - - /* Create a mutable property set. Initially it contains a single section - * with no properties. */ - final MutablePropertySet mps = new MutablePropertySet(); - - /* Retrieve the section the property set already contains. */ - final MutableSection ms = (MutableSection) mps.getSections().get(0); - - /* Turn the property set into a summary information property. This is - * done by setting the format ID of its first section to - * SectionIDMap.SUMMARY_INFORMATION_ID. */ - ms.setFormatID(SectionIDMap.SUMMARY_INFORMATION_ID); - - /* Create an empty property. */ - final MutableProperty p = new MutableProperty(); - - /* Fill the property with appropriate settings so that it specifies the - * document's title. */ - p.setID(PropertyIDMap.PID_TITLE); - p.setType(Variant.VT_LPWSTR); - p.setValue("Sample title"); - - /* Place the property into the section. */ - ms.setProperty(p); - - /* Create the POI file system the property set is to be written to. */ - final POIFSFileSystem poiFs = new POIFSFileSystem(); - - /* For writing the property set into a POI file system it has to be - * handed over to the POIFS.createDocument() method as an input stream - * which produces the bytes making out the property set stream. */ - final InputStream is = mps.toInputStream(); - - /* Create the summary information property set in the POI file - * system. It is given the default name most (if not all) summary - * information property sets have. */ - poiFs.createDocument(is, SummaryInformation.DEFAULT_STREAM_NAME); - - /* Write the whole POI file system to a disk file. */ - FileOutputStream fos = new FileOutputStream(fileName); - poiFs.writeFilesystem(fos); - fos.close(); - poiFs.close(); - } - -} diff --git a/src/examples/src/org/apache/poi/hslf/examples/ApacheconEU08.java b/src/examples/src/org/apache/poi/hslf/examples/ApacheconEU08.java deleted file mode 100644 index 578c3a679..000000000 --- a/src/examples/src/org/apache/poi/hslf/examples/ApacheconEU08.java +++ /dev/null @@ -1,456 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.examples; - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Font; -import java.awt.Graphics2D; -import java.awt.Rectangle; -import java.awt.geom.Rectangle2D; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.List; - -import org.apache.poi.hslf.usermodel.HSLFSlideShow; -import org.apache.poi.sl.draw.DrawTableShape; -import org.apache.poi.sl.draw.SLGraphics; -import org.apache.poi.sl.usermodel.AutoShape; -import org.apache.poi.sl.usermodel.GroupShape; -import org.apache.poi.sl.usermodel.ShapeType; -import org.apache.poi.sl.usermodel.Slide; -import org.apache.poi.sl.usermodel.SlideShow; -import org.apache.poi.sl.usermodel.TableCell; -import org.apache.poi.sl.usermodel.TableShape; -import org.apache.poi.sl.usermodel.TextBox; -import org.apache.poi.sl.usermodel.TextParagraph; -import org.apache.poi.sl.usermodel.TextRun; -import org.apache.poi.sl.usermodel.TextShape.TextPlaceholder; -import org.apache.poi.sl.usermodel.VerticalAlignment; - -/** - * Presentation for Fast Feather Track on ApacheconEU 2008 - * - * @author Yegor Kozlov - */ -public final class ApacheconEU08 { - - public static void main(String[] args) throws IOException { - SlideShow ppt = new HSLFSlideShow(); - // SlideShow ppt = new XMLSlideShow(); - ppt.setPageSize(new Dimension(720, 540)); - - slide1(ppt); - slide2(ppt); - slide3(ppt); - slide4(ppt); - slide5(ppt); - slide6(ppt); - slide7(ppt); - slide8(ppt); - slide9(ppt); - slide10(ppt); - slide11(ppt); - slide12(ppt); - - String ext = ppt.getClass().getName().contains("HSLF") ? "ppt" : "pptx"; - FileOutputStream out = new FileOutputStream("apachecon_eu_08."+ext); - ppt.write(out); - out.close(); - ppt.close(); - } - - public static void slide1(SlideShow ppt) throws IOException { - Slide slide = ppt.createSlide(); - - TextBox box1 = slide.createTextBox(); - box1.setTextPlaceholder(TextPlaceholder.CENTER_TITLE); - box1.setText("POI-HSLF"); - box1.setAnchor(new Rectangle(54, 78, 612, 115)); - - TextBox box2 = slide.createTextBox(); - box2.setTextPlaceholder(TextPlaceholder.CENTER_BODY); - box2.setText("Java API To Access Microsoft PowerPoint Format Files"); - box2.setAnchor(new Rectangle(108, 204, 504, 138)); - - TextBox box3 = slide.createTextBox(); - box3.getTextParagraphs().get(0).getTextRuns().get(0).setFontSize(32d); - box3.setText( - "Yegor Kozlov\r" + - "yegor - apache - org"); - box3.setHorizontalCentered(true); - box3.setAnchor(new Rectangle(206, 348, 310, 84)); - } - - public static void slide2(SlideShow ppt) throws IOException { - Slide slide = ppt.createSlide(); - - TextBox box1 = slide.createTextBox(); - box1.setTextPlaceholder(TextPlaceholder.TITLE); - box1.setText("What is HSLF?"); - box1.setAnchor(new Rectangle(36, 21, 648, 90)); - - TextBox box2 = slide.createTextBox(); - box2.setTextPlaceholder(TextPlaceholder.BODY); - box2.setText("HorribleSLideshowFormat is the POI Project's pure Java implementation " + - "of the Powerpoint binary file format. \r" + - "POI sub-project since 2005\r" + - "Started by Nick Burch, Yegor Kozlov joined soon after"); - box2.setAnchor(new Rectangle(36, 126, 648, 356)); - } - - public static void slide3(SlideShow ppt) throws IOException { - Slide slide = ppt.createSlide(); - - TextBox box1 = slide.createTextBox(); - box1.setTextPlaceholder(TextPlaceholder.TITLE); - box1.setText("HSLF in a Nutshell"); - box1.setAnchor(new Rectangle(36, 15, 648, 65)); - - TextBox box2 = slide.createTextBox(); - box2.setTextPlaceholder(TextPlaceholder.BODY); - box2.setText( - "HSLF provides a way to read, create and modify MS PowerPoint presentations\r" + - "Pure Java API - you don't need PowerPoint to read and write *.ppt files\r" + - "Comprehensive support of PowerPoint objects\r" + - "Rich text\r" + - "Tables\r" + - "Shapes\r" + - "Pictures\r" + - "Master slides\r" + - "Access to low level data structures" - ); - - List> tp = box2.getTextParagraphs(); - for (int i : new byte[]{0,1,2,8}) { - tp.get(i).getTextRuns().get(0).setFontSize(28d); - } - for (int i : new byte[]{3,4,5,6,7}) { - tp.get(i).getTextRuns().get(0).setFontSize(24d); - tp.get(i).setIndentLevel(1); - } - box2.setAnchor(new Rectangle(36, 80, 648, 400)); - } - - public static void slide4(SlideShow ppt) throws IOException { - Slide slide = ppt.createSlide(); - - String[][] txt1 = { - {"Note"}, - {"This presentation was created programmatically using POI HSLF"} - }; - TableShape table1 = slide.createTable(2, 1); - for (int i = 0; i < txt1.length; i++) { - for (int j = 0; j < txt1[i].length; j++) { - TableCell cell = table1.getCell(i, j); - cell.setText(txt1[i][j]); - TextRun rt = cell.getTextParagraphs().get(0).getTextRuns().get(0); - rt.setFontSize(10d); - rt.setFontFamily("Arial"); - rt.setBold(true); - if(i == 0){ - rt.setFontSize(32d); - rt.setFontColor(Color.white); - cell.setFillColor(new Color(0, 153, 204)); - } else { - rt.setFontSize(28d); - cell.setFillColor(new Color(235, 239, 241)); - } - cell.setVerticalAlignment(VerticalAlignment.MIDDLE); - } - } - - DrawTableShape dts = new DrawTableShape(table1); - dts.setAllBorders(1.0, Color.black); - dts.setOutsideBorders(4.0); - - table1.setColumnWidth(0, 450); - table1.setRowHeight(0, 50); - table1.setRowHeight(1, 80); - - Dimension dim = ppt.getPageSize(); - Rectangle2D oldAnchor = table1.getAnchor(); - table1.setAnchor(new Rectangle2D.Double((dim.width-450)/2d, 100, oldAnchor.getWidth(), oldAnchor.getHeight())); - - TextBox box1 = slide.createTextBox(); - box1.setHorizontalCentered(true); - box1.getTextParagraphs().get(0).getTextRuns().get(0).setFontSize(24d); - box1.setText("The source code is available at\r" + - "http://people.apache.org/~yegor/apachecon_eu08/"); - box1.setAnchor(new Rectangle(80, 356, 553, 65)); - } - - public static void slide5(SlideShow ppt) throws IOException { - Slide slide = ppt.createSlide(); - - TextBox box1 = slide.createTextBox(); - box1.setTextPlaceholder(TextPlaceholder.TITLE); - box1.setText("HSLF in Action - 1\rData Extraction"); - box1.setAnchor(new Rectangle(36, 21, 648, 100)); - - TextBox box2 = slide.createTextBox(); - box2.setTextPlaceholder(TextPlaceholder.BODY); - box2.setText( - "Text from slides and notes\r" + - "Images\r" + - "Shapes and their properties (type, position in the slide, color, font, etc.)"); - box2.setAnchor(new Rectangle(36, 150, 648, 300)); - } - - public static void slide6(SlideShow ppt) throws IOException { - Slide slide = ppt.createSlide(); - - TextBox box1 = slide.createTextBox(); - box1.setTextPlaceholder(TextPlaceholder.TITLE); - box1.setText("HSLF in Action - 2"); - box1.setAnchor(new Rectangle(36, 20, 648, 90)); - - TextBox box2 = slide.createTextBox(); - box2.getTextParagraphs().get(0).getTextRuns().get(0).setFontSize(18d); - box2.setText("Creating a simple presentation from scratch"); - box2.setAnchor(new Rectangle(170, 100, 364, 30)); - - TextBox box3 = slide.createTextBox(); - TextRun rt3 = box3.getTextParagraphs().get(0).getTextRuns().get(0); - rt3.setFontFamily("Courier New"); - rt3.setFontSize(8d); - box3.setText( - "SlideShow ppt = new SlideShow();\u000b" + - "Slide slide = ppt.createSlide();\u000b" + - "\u000b" + - "TextBox box2 = new TextBox();\u000b" + - "box2.setHorizontalAlignment(TextBox.AlignCenter);\u000b" + - "box2.setVerticalAlignment(TextBox.AnchorMiddle);\u000b" + - "box2.getTextRun().setText(\"Java Code\");\u000b" + - "box2.getFill().setForegroundColor(new Color(187, 224, 227));\u000b" + - "box2.setLineColor(Color.black);\u000b" + - "box2.setLineWidth(0.75);\u000b" + - "box2.setAnchor(new Rectangle(66, 243, 170, 170));\u000b" + - "slide.addShape(box2);\u000b" + - "\u000b" + - "TextBox box3 = new TextBox();\u000b" + - "box3.setHorizontalAlignment(TextBox.AlignCenter);\u000b" + - "box3.setVerticalAlignment(TextBox.AnchorMiddle);\u000b" + - "box3.getTextRun().setText(\"*.ppt file\");\u000b" + - "box3.setLineWidth(0.75);\u000b" + - "box3.setLineColor(Color.black);\u000b" + - "box3.getFill().setForegroundColor(new Color(187, 224, 227));\u000b" + - "box3.setAnchor(new Rectangle(473, 243, 170, 170));\u000b" + - "slide.addShape(box3);\u000b" + - "\u000b" + - "AutoShape box4 = new AutoShape(ShapeTypes.Arrow);\u000b" + - "box4.getFill().setForegroundColor(new Color(187, 224, 227));\u000b" + - "box4.setLineWidth(0.75);\u000b" + - "box4.setLineColor(Color.black);\u000b" + - "box4.setAnchor(new Rectangle(253, 288, 198, 85));\u000b" + - "slide.addShape(box4);\u000b" + - "\u000b" + - "FileOutputStream out = new FileOutputStream(\"hslf-demo.ppt\");\u000b" + - "ppt.write(out);\u000b" + - "out.close();"); - box3.setAnchor(new Rectangle(30, 150, 618, 411)); - box3.setHorizontalCentered(true); - } - - public static void slide7(SlideShow ppt) throws IOException { - Slide slide = ppt.createSlide(); - - TextBox box2 = slide.createTextBox(); - box2.setHorizontalCentered(true); - box2.setVerticalAlignment(VerticalAlignment.MIDDLE); - box2.setText("Java Code"); - box2.setFillColor(new Color(187, 224, 227)); - box2.setStrokeStyle(0.75, Color.black); - box2.setAnchor(new Rectangle(66, 243, 170, 170)); - - TextBox box3 = slide.createTextBox(); - box3.setHorizontalCentered(true); - box3.setVerticalAlignment(VerticalAlignment.MIDDLE); - box3.setText("*.ppt file"); - box3.setFillColor(new Color(187, 224, 227)); - box3.setStrokeStyle(0.75, Color.black); - box3.setAnchor(new Rectangle(473, 243, 170, 170)); - - AutoShape box4 = slide.createAutoShape(); - box4.setShapeType(ShapeType.RIGHT_ARROW); - box4.setFillColor(new Color(187, 224, 227)); - box4.setStrokeStyle(0.75, Color.black); - box4.setAnchor(new Rectangle(253, 288, 198, 85)); - } - - public static void slide8(SlideShow ppt) throws IOException { - Slide slide = ppt.createSlide(); - - TextBox box1 = slide.createTextBox(); - box1.setTextPlaceholder(TextPlaceholder.TITLE); - box1.setText("Wait, there is more!"); - box1.setAnchor(new Rectangle(36, 21, 648, 90)); - - TextBox box2 = slide.createTextBox(); - box2.setTextPlaceholder(TextPlaceholder.BODY); - box2.setText( - "Rich text\r" + - "Tables\r" + - "Pictures (JPEG, PNG, BMP, WMF, PICT)\r" + - "Comprehensive formatting features"); - box2.setAnchor(new Rectangle(36, 126, 648, 356)); - } - - public static void slide9(SlideShow ppt) throws IOException { - Slide slide = ppt.createSlide(); - - TextBox box1 = slide.createTextBox(); - box1.setTextPlaceholder(TextPlaceholder.TITLE); - box1.setText("HSLF in Action - 3"); - box1.setAnchor(new Rectangle(36, 20, 648, 50)); - - TextBox box2 = slide.createTextBox(); - box2.getTextParagraphs().get(0).getTextRuns().get(0).setFontSize(18d); - box2.setText("PPGraphics2D: PowerPoint Graphics2D driver"); - box2.setAnchor(new Rectangle(178, 70, 387, 30)); - - TextBox box3 = slide.createTextBox(); - TextRun rt3 = box3.getTextParagraphs().get(0).getTextRuns().get(0); - rt3.setFontFamily("Courier New"); - rt3.setFontSize(8d); - box3.setText( - "//bar chart data. The first value is the bar color, the second is the width\u000b" + - "Object[] def = new Object[]{\u000b" + - " Color.yellow, new Integer(100),\u000b" + - " Color.green, new Integer(150),\u000b" + - " Color.gray, new Integer(75),\u000b" + - " Color.red, new Integer(200),\u000b" + - "};\u000b" + - "\u000b" + - "SlideShow ppt = new SlideShow();\u000b" + - "Slide slide = ppt.createSlide();\u000b" + - "\u000b" + - "ShapeGroup group = new ShapeGroup();\u000b" + - "//define position of the drawing in the slide\u000b" + - "Rectangle bounds = new java.awt.Rectangle(200, 100, 350, 300);\u000b" + - "group.setAnchor(bounds);\u000b" + - "slide.addShape(group);\u000b" + - "Graphics2D graphics = new PPGraphics2D(group);\u000b" + - "\u000b" + - "//draw a simple bar graph\u000b" + - "int x = bounds.x + 50, y = bounds.y + 50;\u000b" + - "graphics.setFont(new Font(\"Arial\", Font.BOLD, 10));\u000b" + - "for (int i = 0, idx = 1; i < def.length; i+=2, idx++) {\u000b" + - " graphics.setColor(Color.black);\u000b" + - " int width = ((Integer)def[i+1]).intValue();\u000b" + - " graphics.drawString(\"Q\" + idx, x-20, y+20);\u000b" + - " graphics.drawString(width + \"%\", x + width + 10, y + 20);\u000b" + - " graphics.setColor((Color)def[i]);\u000b" + - " graphics.fill(new Rectangle(x, y, width, 30));\u000b" + - " y += 40;\u000b" + - "}\u000b" + - "graphics.setColor(Color.black);\u000b" + - "graphics.setFont(new Font(\"Arial\", Font.BOLD, 14));\u000b" + - "graphics.draw(bounds);\u000b" + - "graphics.drawString(\"Performance\", x + 70, y + 40);\u000b" + - "\u000b" + - "FileOutputStream out = new FileOutputStream(\"hslf-demo.ppt\");\u000b" + - "ppt.write(out);\u000b" + - "out.close();"); - box3.setAnchor(new Rectangle(96, 110, 499, 378)); - box3.setHorizontalCentered(true); - } - - public static void slide10(SlideShow ppt) throws IOException { - //bar chart data. The first value is the bar color, the second is the width - Object[] def = new Object[]{ - Color.yellow, 100, - Color.green, 150, - Color.gray, 75, - Color.red, 200, - }; - - Slide slide = ppt.createSlide(); - - GroupShape group = slide.createGroup(); - //define position of the drawing in the slide - Rectangle bounds = new java.awt.Rectangle(200, 100, 350, 300); - group.setAnchor(bounds); - Graphics2D graphics = new SLGraphics(group); - - //draw a simple bar graph - int x = bounds.x + 50, y = bounds.y + 50; - graphics.setFont(new Font("Arial", Font.BOLD, 10)); - for (int i = 0, idx = 1; i < def.length; i+=2, idx++) { - graphics.setColor(Color.black); - int width = ((Integer)def[i+1]).intValue(); - graphics.drawString("Q" + idx, x-20, y+20); - graphics.drawString(width + "%", x + width + 10, y + 20); - graphics.setColor((Color)def[i]); - graphics.fill(new Rectangle(x, y, width, 30)); - y += 40; - } - graphics.setColor(Color.black); - graphics.setFont(new Font("Arial", Font.BOLD, 14)); - graphics.draw(bounds); - graphics.drawString("Performance", x + 70, y + 40); - - } - - public static void slide11(SlideShow ppt) throws IOException { - Slide slide = ppt.createSlide(); - - TextBox box1 = slide.createTextBox(); - box1.setTextPlaceholder(TextPlaceholder.TITLE); - box1.setText("HSLF Development Plans"); - box1.setAnchor(new Rectangle(36, 21, 648, 90)); - - TextBox box2 = slide.createTextBox(); - box2.setTextPlaceholder(TextPlaceholder.BODY); - box2.setText( - "Support for more PowerPoint functionality\r" + - "Rendering slides into java.awt.Graphics2D\r" + - "A way to export slides into images or other formats\r" + - "Integration with Apache FOP - Formatting Objects Processor\r" + - "Transformation of XSL-FO into PPT\r" + - "PPT2PDF transcoder" - ); - - List> tp = box2.getTextParagraphs(); - for (int i : new byte[]{0,1,3}) { - tp.get(i).getTextRuns().get(0).setFontSize(28d); - } - for (int i : new byte[]{2,4,5}) { - tp.get(i).getTextRuns().get(0).setFontSize(24d); - tp.get(i).setIndentLevel(1); - } - - box2.setAnchor(new Rectangle(36, 126, 648, 400)); - } - - public static void slide12(SlideShow ppt) throws IOException { - Slide slide = ppt.createSlide(); - - TextBox box1 = slide.createTextBox(); - box1.setTextPlaceholder(TextPlaceholder.CENTER_TITLE); - box1.setText("Questions?"); - box1.setAnchor(new Rectangle(54, 167, 612, 115)); - - TextBox box2 = slide.createTextBox(); - box2.setTextPlaceholder(TextPlaceholder.CENTER_BODY); - box2.setText( - "http://poi.apache.org/hslf/\r" + - "http://people.apache.org/~yegor"); - box2.setAnchor(new Rectangle(108, 306, 504, 138)); - } -} diff --git a/src/examples/src/org/apache/poi/hslf/examples/BulletsDemo.java b/src/examples/src/org/apache/poi/hslf/examples/BulletsDemo.java deleted file mode 100644 index 199720088..000000000 --- a/src/examples/src/org/apache/poi/hslf/examples/BulletsDemo.java +++ /dev/null @@ -1,63 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.examples; - -import java.io.FileOutputStream; -import java.io.IOException; - -import org.apache.poi.hslf.usermodel.HSLFSlide; -import org.apache.poi.hslf.usermodel.HSLFSlideShow; -import org.apache.poi.hslf.usermodel.HSLFTextBox; -import org.apache.poi.hslf.usermodel.HSLFTextParagraph; - -/** - * How to create a single-level bulleted list - * and change some of the bullet attributes - */ -public final class BulletsDemo { - - public static void main(String[] args) throws IOException { - - HSLFSlideShow ppt = new HSLFSlideShow(); - - HSLFSlide slide = ppt.createSlide(); - - HSLFTextBox shape = new HSLFTextBox(); - HSLFTextParagraph rt = shape.getTextParagraphs().get(0); - rt.getTextRuns().get(0).setFontSize(42d); - rt.setBullet(true); - rt.setIndent(0d); //bullet offset - rt.setLeftMargin(50d); //text offset (should be greater than bullet offset) - rt.setBulletChar('\u263A'); //bullet character - shape.setText( - "January\r" + - "February\r" + - "March\r" + - "April"); - slide.addShape(shape); - - shape.setAnchor(new java.awt.Rectangle(50, 50, 500, 300)); //position of the text box in the slide - slide.addShape(shape); - - FileOutputStream out = new FileOutputStream("bullets.ppt"); - ppt.write(out); - out.close(); - - ppt.close(); - } -} diff --git a/src/examples/src/org/apache/poi/hslf/examples/CreateHyperlink.java b/src/examples/src/org/apache/poi/hslf/examples/CreateHyperlink.java deleted file mode 100644 index fc25afae5..000000000 --- a/src/examples/src/org/apache/poi/hslf/examples/CreateHyperlink.java +++ /dev/null @@ -1,64 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.examples; - -import java.awt.Rectangle; -import java.io.FileOutputStream; -import java.io.IOException; - -import org.apache.poi.hslf.usermodel.HSLFHyperlink; -import org.apache.poi.hslf.usermodel.HSLFSlide; -import org.apache.poi.hslf.usermodel.HSLFSlideShow; -import org.apache.poi.hslf.usermodel.HSLFTextBox; - -/** - * Demonstrates how to create hyperlinks in PowerPoint presentations - */ -public abstract class CreateHyperlink { - - public static void main(String[] args) throws IOException { - HSLFSlideShow ppt = new HSLFSlideShow(); - - HSLFSlide slideA = ppt.createSlide(); - ppt.createSlide(); - HSLFSlide slideC = ppt.createSlide(); - - // link to a URL - HSLFTextBox textBox1 = slideA.createTextBox(); - textBox1.setText("Apache POI"); - textBox1.setAnchor(new Rectangle(100, 100, 200, 50)); - - HSLFHyperlink link1 = textBox1.getTextParagraphs().get(0).getTextRuns().get(0).createHyperlink(); - link1.linkToUrl("http://www.apache.org"); - link1.setLabel(textBox1.getText()); - - // link to another slide - HSLFTextBox textBox2 = slideA.createTextBox(); - textBox2.setText("Go to slide #3"); - textBox2.setAnchor(new Rectangle(100, 300, 200, 50)); - - HSLFHyperlink link2 = textBox2.getTextParagraphs().get(0).getTextRuns().get(0).createHyperlink(); - link2.linkToSlide(slideC); - - FileOutputStream out = new FileOutputStream("hyperlink.ppt"); - ppt.write(out); - out.close(); - - ppt.close(); - } -} diff --git a/src/examples/src/org/apache/poi/hslf/examples/DataExtraction.java b/src/examples/src/org/apache/poi/hslf/examples/DataExtraction.java deleted file mode 100644 index ad71ceff6..000000000 --- a/src/examples/src/org/apache/poi/hslf/examples/DataExtraction.java +++ /dev/null @@ -1,126 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.examples; - -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.InputStream; - -import org.apache.poi.hslf.model.OLEShape; -import org.apache.poi.hslf.usermodel.HSLFObjectData; -import org.apache.poi.hslf.usermodel.HSLFPictureData; -import org.apache.poi.hslf.usermodel.HSLFPictureShape; -import org.apache.poi.hslf.usermodel.HSLFShape; -import org.apache.poi.hslf.usermodel.HSLFSlide; -import org.apache.poi.hslf.usermodel.HSLFSlideShow; -import org.apache.poi.hslf.usermodel.HSLFSoundData; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.hwpf.HWPFDocument; -import org.apache.poi.hwpf.usermodel.Paragraph; -import org.apache.poi.hwpf.usermodel.Range; - -/** - * Demonstrates how you can extract misc embedded data from a ppt file - */ -public final class DataExtraction { - - public static void main(String args[]) throws Exception { - - if (args.length == 0) { - usage(); - return; - } - - FileInputStream is = new FileInputStream(args[0]); - HSLFSlideShow ppt = new HSLFSlideShow(is); - is.close(); - - //extract all sound files embedded in this presentation - HSLFSoundData[] sound = ppt.getSoundData(); - for (int i = 0; i < sound.length; i++) { - String type = sound[i].getSoundType(); //*.wav - String name = sound[i].getSoundName(); //typically file name - byte[] data = sound[i].getData(); //raw bytes - - //save the sound on disk - FileOutputStream out = new FileOutputStream(name + type); - out.write(data); - out.close(); - } - - int oleIdx=-1, picIdx=-1; - for (HSLFSlide slide : ppt.getSlides()) { - //extract embedded OLE documents - for (HSLFShape shape : slide.getShapes()) { - if (shape instanceof OLEShape) { - oleIdx++; - OLEShape ole = (OLEShape) shape; - HSLFObjectData data = ole.getObjectData(); - String name = ole.getInstanceName(); - if ("Worksheet".equals(name)) { - - //read xls - @SuppressWarnings({ "unused", "resource" }) - HSSFWorkbook wb = new HSSFWorkbook(data.getData()); - - } else if ("Document".equals(name)) { - HWPFDocument doc = new HWPFDocument(data.getData()); - //read the word document - Range r = doc.getRange(); - for(int k = 0; k < r.numParagraphs(); k++) { - Paragraph p = r.getParagraph(k); - System.out.println(p.text()); - } - - //save on disk - FileOutputStream out = new FileOutputStream(name + "-("+(oleIdx)+").doc"); - doc.write(out); - out.close(); - doc.close(); - } else { - FileOutputStream out = new FileOutputStream(ole.getProgID() + "-"+(oleIdx+1)+".dat"); - InputStream dis = data.getData(); - byte[] chunk = new byte[2048]; - int count; - while ((count = dis.read(chunk)) >= 0) { - out.write(chunk,0,count); - } - is.close(); - out.close(); - } - } - - //Pictures - else if (shape instanceof HSLFPictureShape) { - picIdx++; - HSLFPictureShape p = (HSLFPictureShape) shape; - HSLFPictureData data = p.getPictureData(); - String ext = data.getType().extension; - FileOutputStream out = new FileOutputStream("pict-" + picIdx + ext); - out.write(data.getData()); - out.close(); - } - } - } - ppt.close(); - } - - private static void usage(){ - System.out.println("Usage: DataExtraction ppt"); - } -} diff --git a/src/examples/src/org/apache/poi/hslf/examples/Graphics2DDemo.java b/src/examples/src/org/apache/poi/hslf/examples/Graphics2DDemo.java deleted file mode 100644 index 53cd53edc..000000000 --- a/src/examples/src/org/apache/poi/hslf/examples/Graphics2DDemo.java +++ /dev/null @@ -1,85 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.examples; - -import java.awt.Color; -import java.awt.Font; -import java.awt.Graphics2D; -import java.awt.Rectangle; -import java.io.FileOutputStream; - -import org.apache.poi.hslf.model.PPGraphics2D; -import org.apache.poi.hslf.usermodel.HSLFGroupShape; -import org.apache.poi.hslf.usermodel.HSLFSlide; -import org.apache.poi.hslf.usermodel.HSLFSlideShow; - -/** - * Demonstrates how to draw into a slide using the HSLF Graphics2D driver. - * - * @author Yegor Kozlov - */ -public final class Graphics2DDemo { - - /** - * A simple bar chart demo - */ - public static void main(String[] args) throws Exception { - HSLFSlideShow ppt = new HSLFSlideShow(); - - //bar chart data. The first value is the bar color, the second is the width - Object[] def = new Object[]{ - Color.yellow, 40, - Color.green, 60, - Color.gray, 30, - Color.red, 80, - }; - - HSLFSlide slide = ppt.createSlide(); - - HSLFGroupShape group = new HSLFGroupShape(); - //define position of the drawing in the slide - Rectangle bounds = new java.awt.Rectangle(200, 100, 350, 300); - group.setAnchor(bounds); - group.setInteriorAnchor(new java.awt.Rectangle(0, 0, 100, 100)); - slide.addShape(group); - Graphics2D graphics = new PPGraphics2D(group); - - //draw a simple bar graph - int x = 10, y = 10; - graphics.setFont(new Font("Arial", Font.BOLD, 10)); - for (int i = 0, idx = 1; i < def.length; i+=2, idx++) { - graphics.setColor(Color.black); - int width = ((Integer)def[i+1]).intValue(); - graphics.drawString("Q" + idx, x-5, y+10); - graphics.drawString(width + "%", x + width+3, y + 10); - graphics.setColor((Color)def[i]); - graphics.fill(new Rectangle(x, y, width, 10)); - y += 15; - } - graphics.setColor(Color.black); - graphics.setFont(new Font("Arial", Font.BOLD, 14)); - graphics.draw(group.getInteriorAnchor()); - graphics.drawString("Performance", x + 30, y + 10); - - FileOutputStream out = new FileOutputStream("hslf-graphics.ppt"); - ppt.write(out); - out.close(); - - ppt.close(); - } -} diff --git a/src/examples/src/org/apache/poi/hslf/examples/HeadersFootersDemo.java b/src/examples/src/org/apache/poi/hslf/examples/HeadersFootersDemo.java deleted file mode 100644 index 3ef5a46ab..000000000 --- a/src/examples/src/org/apache/poi/hslf/examples/HeadersFootersDemo.java +++ /dev/null @@ -1,50 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hslf.examples; - -import java.io.FileOutputStream; -import java.io.IOException; - -import org.apache.poi.hslf.model.HeadersFooters; -import org.apache.poi.hslf.usermodel.HSLFSlideShow; - -/** - * Demonstrates how to set headers / footers - */ -public abstract class HeadersFootersDemo { - public static void main(String[] args) throws IOException { - HSLFSlideShow ppt = new HSLFSlideShow(); - - HeadersFooters slideHeaders = ppt.getSlideHeadersFooters(); - slideHeaders.setFootersText("Created by POI-HSLF"); - slideHeaders.setSlideNumberVisible(true); - slideHeaders.setDateTimeText("custom date time"); - - HeadersFooters notesHeaders = ppt.getNotesHeadersFooters(); - notesHeaders.setFootersText("My notes footers"); - notesHeaders.setHeaderText("My notes header"); - - ppt.createSlide(); - - FileOutputStream out = new FileOutputStream("headers_footers.ppt"); - ppt.write(out); - out.close(); - - ppt.close(); - } - -} diff --git a/src/examples/src/org/apache/poi/hslf/examples/Hyperlinks.java b/src/examples/src/org/apache/poi/hslf/examples/Hyperlinks.java deleted file mode 100644 index 812429295..000000000 --- a/src/examples/src/org/apache/poi/hslf/examples/Hyperlinks.java +++ /dev/null @@ -1,83 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.examples; - -import java.io.FileInputStream; -import java.util.List; -import java.util.Locale; - -import org.apache.poi.hslf.usermodel.HSLFHyperlink; -import org.apache.poi.hslf.usermodel.HSLFShape; -import org.apache.poi.hslf.usermodel.HSLFSimpleShape; -import org.apache.poi.hslf.usermodel.HSLFSlide; -import org.apache.poi.hslf.usermodel.HSLFSlideShow; -import org.apache.poi.hslf.usermodel.HSLFTextParagraph; -import org.apache.poi.hslf.usermodel.HSLFTextRun; - -/** - * Demonstrates how to read hyperlinks from a presentation - * - * @author Yegor Kozlov - */ -public final class Hyperlinks { - - public static void main(String[] args) throws Exception { - for (int i = 0; i < args.length; i++) { - FileInputStream is = new FileInputStream(args[i]); - HSLFSlideShow ppt = new HSLFSlideShow(is); - is.close(); - - for (HSLFSlide slide : ppt.getSlides()) { - System.out.println("\nslide " + slide.getSlideNumber()); - - // read hyperlinks from the slide's text runs - System.out.println("- reading hyperlinks from the text runs"); - for (List paras : slide.getTextParagraphs()) { - for (HSLFTextParagraph para : paras) { - for (HSLFTextRun run : para) { - HSLFHyperlink link = run.getHyperlink(); - if (link != null) { - System.out.println(toStr(link, run.getRawText())); - } - } - } - } - - // in PowerPoint you can assign a hyperlink to a shape without text, - // for example to a Line object. The code below demonstrates how to - // read such hyperlinks - System.out.println("- reading hyperlinks from the slide's shapes"); - for (HSLFShape sh : slide.getShapes()) { - if (sh instanceof HSLFSimpleShape) { - HSLFHyperlink link = ((HSLFSimpleShape)sh).getHyperlink(); - if (link != null) { - System.out.println(toStr(link, null)); - } - } - } - } - ppt.close(); - } - } - - static String toStr(HSLFHyperlink link, String rawText) { - //in ppt end index is inclusive - String formatStr = "title: %1$s, address: %2$s" + (rawText == null ? "" : ", start: %3$s, end: %4$s, substring: %5$s"); - return String.format(Locale.ROOT, formatStr, link.getLabel(), link.getAddress(), link.getStartIndex(), link.getEndIndex(), rawText); - } -} diff --git a/src/examples/src/org/apache/poi/hslf/examples/PPT2PNG.java b/src/examples/src/org/apache/poi/hslf/examples/PPT2PNG.java deleted file mode 100644 index 7979c805c..000000000 --- a/src/examples/src/org/apache/poi/hslf/examples/PPT2PNG.java +++ /dev/null @@ -1,109 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.examples; - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Graphics2D; -import java.awt.RenderingHints; -import java.awt.geom.Rectangle2D; -import java.awt.image.BufferedImage; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; - -import javax.imageio.ImageIO; - -import org.apache.poi.hslf.usermodel.HSLFSlide; -import org.apache.poi.hslf.usermodel.HSLFSlideShow; - -/** - * Demonstrates how you can use HSLF to convert each slide into a PNG image - */ -public final class PPT2PNG { - - public static void main(String args[]) throws IOException { - - if (args.length == 0) { - usage(); - return; - } - - int slidenum = -1; - float scale = 1; - String file = null; - - for (int i = 0; i < args.length; i++) { - if (args[i].startsWith("-")) { - if ("-scale".equals(args[i])){ - scale = Float.parseFloat(args[++i]); - } else if ("-slide".equals(args[i])) { - slidenum = Integer.parseInt(args[++i]); - } - } else { - file = args[i]; - } - } - if(file == null){ - usage(); - return; - } - - FileInputStream is = new FileInputStream(file); - HSLFSlideShow ppt = new HSLFSlideShow(is); - is.close(); - - Dimension pgsize = ppt.getPageSize(); - int width = (int)(pgsize.width*scale); - int height = (int)(pgsize.height*scale); - - for (HSLFSlide slide : ppt.getSlides()) { - if (slidenum != -1 && slidenum != slide.getSlideNumber()) { - continue; - } - - String title = slide.getTitle(); - System.out.println("Rendering slide "+slide.getSlideNumber() + (title == null ? "" : ": " + title)); - - BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); - Graphics2D graphics = img.createGraphics(); - graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); - graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); - graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); - - graphics.setPaint(Color.white); - graphics.fill(new Rectangle2D.Float(0, 0, width, height)); - - graphics.scale((double)width/pgsize.width, (double)height/pgsize.height); - - slide.draw(graphics); - - String fname = file.replaceAll("\\.ppt", "-" + slide.getSlideNumber() + ".png"); - FileOutputStream out = new FileOutputStream(fname); - ImageIO.write(img, "png", out); - out.close(); - } - - ppt.close(); - } - - private static void usage(){ - System.out.println("Usage: PPT2PNG [-scale -slide ] ppt"); - } -} diff --git a/src/examples/src/org/apache/poi/hslf/examples/SoundFinder.java b/src/examples/src/org/apache/poi/hslf/examples/SoundFinder.java deleted file mode 100644 index ec0cec8dc..000000000 --- a/src/examples/src/org/apache/poi/hslf/examples/SoundFinder.java +++ /dev/null @@ -1,66 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hslf.examples; -import java.io.FileInputStream; -import java.io.IOException; - -import org.apache.poi.hslf.record.InteractiveInfoAtom; -import org.apache.poi.hslf.record.RecordTypes; -import org.apache.poi.hslf.usermodel.HSLFShape; -import org.apache.poi.hslf.usermodel.HSLFSlide; -import org.apache.poi.hslf.usermodel.HSLFSlideShow; -import org.apache.poi.hslf.usermodel.HSLFSoundData; - -/** - * For each slide iterate over shapes and found associated sound data. - */ -public class SoundFinder { - public static void main(String[] args) throws IOException { - FileInputStream fis = new FileInputStream(args[0]); - HSLFSlideShow ppt = new HSLFSlideShow(fis); - HSLFSoundData[] sounds = ppt.getSoundData(); - - for (HSLFSlide slide : ppt.getSlides()) { - for (HSLFShape shape : slide.getShapes()) { - int soundRef = getSoundReference(shape); - if(soundRef == -1) continue; - - - System.out.println("Slide["+slide.getSlideNumber()+"], shape["+shape.getShapeId()+"], soundRef: "+soundRef); - System.out.println(" " + sounds[soundRef].getSoundName()); - System.out.println(" " + sounds[soundRef].getSoundType()); - } - } - ppt.close(); - fis.close(); - } - - /** - * Check if a given shape is associated with a sound. - * @return 0-based reference to a sound in the sound collection - * or -1 if the shape is not associated with a sound - */ - protected static int getSoundReference(HSLFShape shape){ - int soundRef = -1; - //dive into the shape container and search for InteractiveInfoAtom - InteractiveInfoAtom info = shape.getClientDataRecord(RecordTypes.InteractiveInfo.typeID); - if (info != null && info.getAction() == InteractiveInfoAtom.ACTION_MEDIA) { - soundRef = info.getSoundRef(); - } - return soundRef; - } -} diff --git a/src/examples/src/org/apache/poi/hslf/examples/TableDemo.java b/src/examples/src/org/apache/poi/hslf/examples/TableDemo.java deleted file mode 100644 index e4ad98dc1..000000000 --- a/src/examples/src/org/apache/poi/hslf/examples/TableDemo.java +++ /dev/null @@ -1,130 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.examples; - -import java.awt.Color; -import java.io.FileOutputStream; - -import org.apache.poi.hslf.usermodel.HSLFSlide; -import org.apache.poi.hslf.usermodel.HSLFSlideShow; -import org.apache.poi.hslf.usermodel.HSLFTable; -import org.apache.poi.hslf.usermodel.HSLFTableCell; -import org.apache.poi.hslf.usermodel.HSLFTextRun; -import org.apache.poi.sl.draw.DrawTableShape; -import org.apache.poi.sl.usermodel.TextParagraph.TextAlign; -import org.apache.poi.sl.usermodel.VerticalAlignment; - -/** - * Demonstrates how to create tables - * - * @author Yegor Kozlov - */ -public final class TableDemo { - - public static void main(String[] args) throws Exception { - - //test data for the first taable - String[][] txt1 = { - {"INPUT FILE", "NUMBER OF RECORDS"}, - {"Item File", "11,559"}, - {"Vendor File", "502"}, - {"Purchase History File - # of PO\u2019s\r(12/01/04 - 05/31/06)", "12,852"}, - {"Purchase History File - # of PO Lines\r(12/01/04 - 05/31/06)", "53,523" }, - {"Total PO History Spend", "$10,172,038"} - }; - - HSLFSlideShow ppt = new HSLFSlideShow(); - - HSLFSlide slide = ppt.createSlide(); - - //six rows, two columns - HSLFTable table1 = slide.createTable(6, 2); - for (int i = 0; i < txt1.length; i++) { - for (int j = 0; j < txt1[i].length; j++) { - HSLFTableCell cell = table1.getCell(i, j); - HSLFTextRun rt = cell.getTextParagraphs().get(0).getTextRuns().get(0); - rt.setFontFamily("Arial"); - rt.setFontSize(10d); - if(i == 0){ - cell.getFill().setForegroundColor(new Color(227, 227, 227)); - } else { - rt.setBold(true); - } - cell.setVerticalAlignment(VerticalAlignment.MIDDLE); - cell.setHorizontalCentered(true); - cell.setText(txt1[i][j]); - } - } - - DrawTableShape dts1 = new DrawTableShape(table1); - dts1.setAllBorders(1.0, Color.black); - - table1.setColumnWidth(0, 300); - table1.setColumnWidth(1, 150); - - int pgWidth = ppt.getPageSize().width; - table1.moveTo((pgWidth - table1.getAnchor().getWidth())/2., 100.); - - //test data for the second taable - String[][] txt2 = { - {"Data Source"}, - {"CAS Internal Metrics - Item Master Summary\r" + - "CAS Internal Metrics - Vendor Summary\r" + - "CAS Internal Metrics - PO History Summary"} - }; - - //two rows, one column - HSLFTable table2 = slide.createTable(2, 1); - for (int i = 0; i < txt2.length; i++) { - for (int j = 0; j < txt2[i].length; j++) { - HSLFTableCell cell = table2.getCell(i, j); - HSLFTextRun rt = cell.getTextParagraphs().get(0).getTextRuns().get(0); - rt.setFontSize(10d); - rt.setFontFamily("Arial"); - if(i == 0){ - cell.getFill().setForegroundColor(new Color(0, 51, 102)); - rt.setFontColor(Color.white); - rt.setBold(true); - rt.setFontSize(14d); - cell.setHorizontalCentered(true); - } else { - rt.getTextParagraph().setBullet(true); - rt.setFontSize(12d); - rt.getTextParagraph().setTextAlign(TextAlign.LEFT); - cell.setHorizontalCentered(false); - } - cell.setVerticalAlignment(VerticalAlignment.MIDDLE); - cell.setText(txt2[i][j]); - } - } - table2.setColumnWidth(0, 300); - table2.setRowHeight(0, 30); - table2.setRowHeight(1, 70); - - DrawTableShape dts2 = new DrawTableShape(table2); - dts2.setOutsideBorders(Color.black, 1.0); - - table2.moveTo(200, 400); - - FileOutputStream out = new FileOutputStream("hslf-table.ppt"); - ppt.write(out); - out.close(); - - ppt.close(); - } -} diff --git a/src/examples/src/org/apache/poi/hsmf/examples/Msg2txt.java b/src/examples/src/org/apache/poi/hsmf/examples/Msg2txt.java deleted file mode 100644 index 9eeba8ce5..000000000 --- a/src/examples/src/org/apache/poi/hsmf/examples/Msg2txt.java +++ /dev/null @@ -1,171 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hsmf.examples; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.io.PrintWriter; - -import org.apache.poi.hsmf.MAPIMessage; -import org.apache.poi.hsmf.datatypes.AttachmentChunks; -import org.apache.poi.hsmf.exceptions.ChunkNotFoundException; - -/** - * Reads one or several Outlook MSG files and for each of them creates - * a text file from available chunks and a directory that contains - * attachments. - * - * @author Bruno Girin - */ -public class Msg2txt { - - /** - * The stem used to create file names for the text file and the directory - * that contains the attachments. - */ - private String fileNameStem; - - /** - * The Outlook MSG file being processed. - */ - private MAPIMessage msg; - - public Msg2txt(String fileName) throws IOException { - fileNameStem = fileName; - if(fileNameStem.endsWith(".msg") || fileNameStem.endsWith(".MSG")) { - fileNameStem = fileNameStem.substring(0, fileNameStem.length() - 4); - } - msg = new MAPIMessage(fileName); - } - - /** - * Processes the message. - * - * @throws IOException if an exception occurs while writing the message out - */ - public void processMessage() throws IOException { - String txtFileName = fileNameStem + ".txt"; - String attDirName = fileNameStem + "-att"; - PrintWriter txtOut = null; - try { - txtOut = new PrintWriter(txtFileName); - try { - String displayFrom = msg.getDisplayFrom(); - txtOut.println("From: "+displayFrom); - } catch (ChunkNotFoundException e) { - // ignore - } - try { - String displayTo = msg.getDisplayTo(); - txtOut.println("To: "+displayTo); - } catch (ChunkNotFoundException e) { - // ignore - } - try { - String displayCC = msg.getDisplayCC(); - txtOut.println("CC: "+displayCC); - } catch (ChunkNotFoundException e) { - // ignore - } - try { - String displayBCC = msg.getDisplayBCC(); - txtOut.println("BCC: "+displayBCC); - } catch (ChunkNotFoundException e) { - // ignore - } - try { - String subject = msg.getSubject(); - txtOut.println("Subject: "+subject); - } catch (ChunkNotFoundException e) { - // ignore - } - try { - String body = msg.getTextBody(); - txtOut.println(body); - } catch (ChunkNotFoundException e) { - System.err.println("No message body"); - } - - AttachmentChunks[] attachments = msg.getAttachmentFiles(); - if(attachments.length > 0) { - File d = new File(attDirName); - if(d.mkdir()) { - for(AttachmentChunks attachment : attachments) { - processAttachment(attachment, d); - } - } else { - System.err.println("Can't create directory "+attDirName); - } - } - } finally { - if(txtOut != null) { - txtOut.close(); - } - } - } - - /** - * Processes a single attachment: reads it from the Outlook MSG file and - * writes it to disk as an individual file. - * - * @param attachment the chunk group describing the attachment - * @param dir the directory in which to write the attachment file - * @throws IOException when any of the file operations fails - */ - public void processAttachment(AttachmentChunks attachment, - File dir) throws IOException { - String fileName = attachment.getAttachFileName().toString(); - if(attachment.getAttachLongFileName() != null) { - fileName = attachment.getAttachLongFileName().toString(); - } - - File f = new File(dir, fileName); - OutputStream fileOut = null; - try { - fileOut = new FileOutputStream(f); - fileOut.write(attachment.getAttachData().getValue()); - } finally { - if(fileOut != null) { - fileOut.close(); - } - } - } - - /** - * Processes the list of arguments as a list of names of Outlook MSG files. - * - * @param args the list of MSG files to process - */ - public static void main(String[] args) { - if(args.length <= 0) { - System.err.println("No files names provided"); - } else { - for(int i = 0; i < args.length; i++) { - try { - Msg2txt processor = new Msg2txt(args[i]); - processor.processMessage(); - } catch (IOException e) { - System.err.println("Could not process "+args[i]+": "+e); - } - } - } - } - -} diff --git a/src/examples/src/org/apache/poi/hssf/eventusermodel/examples/XLS2CSVmra.java b/src/examples/src/org/apache/poi/hssf/eventusermodel/examples/XLS2CSVmra.java deleted file mode 100644 index 610d96174..000000000 --- a/src/examples/src/org/apache/poi/hssf/eventusermodel/examples/XLS2CSVmra.java +++ /dev/null @@ -1,329 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.eventusermodel.examples; - -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.PrintStream; -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.hssf.eventusermodel.EventWorkbookBuilder.SheetRecordCollectingListener; -import org.apache.poi.hssf.eventusermodel.FormatTrackingHSSFListener; -import org.apache.poi.hssf.eventusermodel.HSSFEventFactory; -import org.apache.poi.hssf.eventusermodel.HSSFListener; -import org.apache.poi.hssf.eventusermodel.HSSFRequest; -import org.apache.poi.hssf.eventusermodel.MissingRecordAwareHSSFListener; -import org.apache.poi.hssf.eventusermodel.dummyrecord.LastCellOfRowDummyRecord; -import org.apache.poi.hssf.eventusermodel.dummyrecord.MissingCellDummyRecord; -import org.apache.poi.hssf.model.HSSFFormulaParser; -import org.apache.poi.hssf.record.BOFRecord; -import org.apache.poi.hssf.record.BlankRecord; -import org.apache.poi.hssf.record.BoolErrRecord; -import org.apache.poi.hssf.record.BoundSheetRecord; -import org.apache.poi.hssf.record.FormulaRecord; -import org.apache.poi.hssf.record.LabelRecord; -import org.apache.poi.hssf.record.LabelSSTRecord; -import org.apache.poi.hssf.record.NoteRecord; -import org.apache.poi.hssf.record.NumberRecord; -import org.apache.poi.hssf.record.RKRecord; -import org.apache.poi.hssf.record.Record; -import org.apache.poi.hssf.record.SSTRecord; -import org.apache.poi.hssf.record.StringRecord; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; - -/** - * A XLS -> CSV processor, that uses the MissingRecordAware - * EventModel code to ensure it outputs all columns and rows. - * @author Nick Burch - */ -public class XLS2CSVmra implements HSSFListener { - private int minColumns; - private POIFSFileSystem fs; - private PrintStream output; - - private int lastRowNumber; - private int lastColumnNumber; - - /** Should we output the formula, or the value it has? */ - private boolean outputFormulaValues = true; - - /** For parsing Formulas */ - private SheetRecordCollectingListener workbookBuildingListener; - private HSSFWorkbook stubWorkbook; - - // Records we pick up as we process - private SSTRecord sstRecord; - private FormatTrackingHSSFListener formatListener; - - /** So we known which sheet we're on */ - private int sheetIndex = -1; - private BoundSheetRecord[] orderedBSRs; - private List boundSheetRecords = new ArrayList(); - - // For handling formulas with string results - private int nextRow; - private int nextColumn; - private boolean outputNextStringRecord; - - /** - * Creates a new XLS -> CSV converter - * @param fs The POIFSFileSystem to process - * @param output The PrintStream to output the CSV to - * @param minColumns The minimum number of columns to output, or -1 for no minimum - */ - public XLS2CSVmra(POIFSFileSystem fs, PrintStream output, int minColumns) { - this.fs = fs; - this.output = output; - this.minColumns = minColumns; - } - - /** - * Creates a new XLS -> CSV converter - * @param filename The file to process - * @param minColumns The minimum number of columns to output, or -1 for no minimum - * @throws IOException - * @throws FileNotFoundException - */ - public XLS2CSVmra(String filename, int minColumns) throws IOException, FileNotFoundException { - this( - new POIFSFileSystem(new FileInputStream(filename)), - System.out, minColumns - ); - } - - /** - * Initiates the processing of the XLS file to CSV - */ - public void process() throws IOException { - MissingRecordAwareHSSFListener listener = new MissingRecordAwareHSSFListener(this); - formatListener = new FormatTrackingHSSFListener(listener); - - HSSFEventFactory factory = new HSSFEventFactory(); - HSSFRequest request = new HSSFRequest(); - - if(outputFormulaValues) { - request.addListenerForAllRecords(formatListener); - } else { - workbookBuildingListener = new SheetRecordCollectingListener(formatListener); - request.addListenerForAllRecords(workbookBuildingListener); - } - - factory.processWorkbookEvents(request, fs); - } - - /** - * Main HSSFListener method, processes events, and outputs the - * CSV as the file is processed. - */ - @Override - public void processRecord(Record record) { - int thisRow = -1; - int thisColumn = -1; - String thisStr = null; - - switch (record.getSid()) - { - case BoundSheetRecord.sid: - boundSheetRecords.add((BoundSheetRecord)record); - break; - case BOFRecord.sid: - BOFRecord br = (BOFRecord)record; - if(br.getType() == BOFRecord.TYPE_WORKSHEET) { - // Create sub workbook if required - if(workbookBuildingListener != null && stubWorkbook == null) { - stubWorkbook = workbookBuildingListener.getStubHSSFWorkbook(); - } - - // Output the worksheet name - // Works by ordering the BSRs by the location of - // their BOFRecords, and then knowing that we - // process BOFRecords in byte offset order - sheetIndex++; - if(orderedBSRs == null) { - orderedBSRs = BoundSheetRecord.orderByBofPosition(boundSheetRecords); - } - output.println(); - output.println( - orderedBSRs[sheetIndex].getSheetname() + - " [" + (sheetIndex+1) + "]:" - ); - } - break; - - case SSTRecord.sid: - sstRecord = (SSTRecord) record; - break; - - case BlankRecord.sid: - BlankRecord brec = (BlankRecord) record; - - thisRow = brec.getRow(); - thisColumn = brec.getColumn(); - thisStr = ""; - break; - case BoolErrRecord.sid: - BoolErrRecord berec = (BoolErrRecord) record; - - thisRow = berec.getRow(); - thisColumn = berec.getColumn(); - thisStr = ""; - break; - - case FormulaRecord.sid: - FormulaRecord frec = (FormulaRecord) record; - - thisRow = frec.getRow(); - thisColumn = frec.getColumn(); - - if(outputFormulaValues) { - if(Double.isNaN( frec.getValue() )) { - // Formula result is a string - // This is stored in the next record - outputNextStringRecord = true; - nextRow = frec.getRow(); - nextColumn = frec.getColumn(); - } else { - thisStr = formatListener.formatNumberDateCell(frec); - } - } else { - thisStr = '"' + - HSSFFormulaParser.toFormulaString(stubWorkbook, frec.getParsedExpression()) + '"'; - } - break; - case StringRecord.sid: - if(outputNextStringRecord) { - // String for formula - StringRecord srec = (StringRecord)record; - thisStr = srec.getString(); - thisRow = nextRow; - thisColumn = nextColumn; - outputNextStringRecord = false; - } - break; - - case LabelRecord.sid: - LabelRecord lrec = (LabelRecord) record; - - thisRow = lrec.getRow(); - thisColumn = lrec.getColumn(); - thisStr = '"' + lrec.getValue() + '"'; - break; - case LabelSSTRecord.sid: - LabelSSTRecord lsrec = (LabelSSTRecord) record; - - thisRow = lsrec.getRow(); - thisColumn = lsrec.getColumn(); - if(sstRecord == null) { - thisStr = '"' + "(No SST Record, can't identify string)" + '"'; - } else { - thisStr = '"' + sstRecord.getString(lsrec.getSSTIndex()).toString() + '"'; - } - break; - case NoteRecord.sid: - NoteRecord nrec = (NoteRecord) record; - - thisRow = nrec.getRow(); - thisColumn = nrec.getColumn(); - // TODO: Find object to match nrec.getShapeId() - thisStr = '"' + "(TODO)" + '"'; - break; - case NumberRecord.sid: - NumberRecord numrec = (NumberRecord) record; - - thisRow = numrec.getRow(); - thisColumn = numrec.getColumn(); - - // Format - thisStr = formatListener.formatNumberDateCell(numrec); - break; - case RKRecord.sid: - RKRecord rkrec = (RKRecord) record; - - thisRow = rkrec.getRow(); - thisColumn = rkrec.getColumn(); - thisStr = '"' + "(TODO)" + '"'; - break; - default: - break; - } - - // Handle new row - if(thisRow != -1 && thisRow != lastRowNumber) { - lastColumnNumber = -1; - } - - // Handle missing column - if(record instanceof MissingCellDummyRecord) { - MissingCellDummyRecord mc = (MissingCellDummyRecord)record; - thisRow = mc.getRow(); - thisColumn = mc.getColumn(); - thisStr = ""; - } - - // If we got something to print out, do so - if(thisStr != null) { - if(thisColumn > 0) { - output.print(','); - } - output.print(thisStr); - } - - // Update column and row count - if(thisRow > -1) - lastRowNumber = thisRow; - if(thisColumn > -1) - lastColumnNumber = thisColumn; - - // Handle end of row - if(record instanceof LastCellOfRowDummyRecord) { - // Print out any missing commas if needed - if(minColumns > 0) { - // Columns are 0 based - if(lastColumnNumber == -1) { lastColumnNumber = 0; } - for(int i=lastColumnNumber; i<(minColumns); i++) { - output.print(','); - } - } - - // We're onto a new row - lastColumnNumber = -1; - - // End the row - output.println(); - } - } - - public static void main(String[] args) throws Exception { - if(args.length < 1) { - System.err.println("Use:"); - System.err.println(" XLS2CSVmra [min columns]"); - System.exit(1); - } - - int minColumns = -1; - if(args.length >= 2) { - minColumns = Integer.parseInt(args[1]); - } - - XLS2CSVmra xls2csv = new XLS2CSVmra(args[0], minColumns); - xls2csv.process(); - } -} diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/AddDimensionedImage.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/AddDimensionedImage.java deleted file mode 100644 index 9b86cf779..000000000 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/AddDimensionedImage.java +++ /dev/null @@ -1,944 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - - -package org.apache.poi.hssf.usermodel.examples; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.ByteArrayOutputStream; -import java.io.FileNotFoundException; -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFClientAnchor; -import org.apache.poi.hssf.usermodel.HSSFPatriarch; -import org.apache.poi.ss.usermodel.ClientAnchor.AnchorType; - - -/** - * Demonstrates how to add an image to a worksheet and set that image's size - * to a specific number of milimetres irrespective of the width of the columns - * or height of the rows. Overridden methods are provided so that the location - * of the image - the cells row and column co-ordinates that define the top - * left hand corners of the image - can be identified either in the familiar - * Excel manner - A1 for instance - or using POI's methodolody of a column and - * row index where 0, 0 would indicate cell A1. - * - * The best way to make use of these techniques is to delay adding the image to - * the sheet until all other work has been completed. That way, the sizes of - * all rows and columns will have been adjusted - assuming that step was - * necessary. Even though the anchors type is set to prevent the image moving - * or re-sizing, this setting does not have any effect until the sheet is being - * viewed using the Excel application. - * - * The key to the process is the HSSFClientAnchor class. It accepts eight - * parameters that define, in order; - * - * * How far - in terms of co-ordinate position - the image should be inset - * from the left hand border of a cell. - * * How far - in terms of co-ordinate positions - the image should be inset - * from the from the top of the cell. - * * How far - in terms of co-ordinate positions - the right hand edge of - * the image should protrude into a cell (measured from the cell's left hand - * edge to the image's right hand edge). - * * How far - in terms of co-ordinate positions - the bottm edge of the - * image should protrude into a row (measured from the cell's top edge to - * the image's bottom edge). - * * The index of the column that contains the cell whose top left hand - * corner should be aligned with the top left hand corner of the image. - * * The index of the row that contains the cell whose top left hand corner - * should be aligned with the image's top left hand corner. - * * The index of the column that contains the cell whose top left hand - * corner should be aligned with the image's bottom right hand corner - * * The index number of the row that contains the cell whose top left - * hand corner should be aligned with the images bottom right hand corner. - * - * It can be used to add an image into cell A1, for example, in the following - * manner; - * - * HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0, - * (short)0, 0, (short)1, 1); - * - * The final four parameters determine that the top left hand corner should be - * aligned with the top left hand corner of cell A1 and it's bottom right - * hand corner with the top left hand corner of cell B2. Think of the image as - * being stretched so that it's top left hand corner is aligned with the top - * left hand corner of cell A1 and it's bottom right hand corner is aligned with - * the top left hand corner of cell B1. Interestingly, this would also produce - * the same results; - * - * anchor = new HSSFClientAnchor(0, 0, 1023, 255, - * (short)0, 0, (short)0, 0); - * - * Note that the final four parameters all contain the same value and seem to - * indicate that the images top left hand corner is aligned with the top left - * hand corner of cell A1 and that it's bottom right hand corner is also - * aligned with the top left hand corner of cell A1. Yet, running this code - * would see the image fully occupying cell A1. That is the result of the - * values passed to parameters three and four; these I have referred to as - * determing the images co-ordinates within the cell. They indicate that the - * image should occupy - in order - the full width of the column and the full - * height of the row. - * - * The co-ordinate values shown are the maxima; and they are independent of - * row height/column width and of the font used. Passing 255 will always result - * in the image occupying the full height of the row and passing 1023 will - * always result in the image occupying the full width of the column. They help - * in situations where an image is larger than a column/row and must overlap - * into the next column/row. Using them does mean, however, that it is often - * necessary to perform conversions between Excel's characters units, points, - * pixels and millimetres in order to establish how many rows/columns an image - * should occupy and just what the varous insets ought to be. - * - * Note that the first two parameters of the HSSFClientAchor classes constructor - * are not made use of in the code that follows. It would be fairly trivial - * however to extend these example further and provide methods that would centre - * an image within a cell or allow the user to specify that a plain border a - * fixed number of millimetres wide should wrap around the image. Those first - * two parameters would make this sort of functionality perfectly possible. - * - * Owing to the various conversions used, the actual size of the image may vary - * from that required; testing has so far found this to be in the region of - * plus or minus two millimetres. Most likely by modifying the way the - * calculations are performed - possibly using double(s) throughout and - * rounding the values at the correct point - it is likely that these errors - * could be reduced or removed. - * - * A note concerning Excels' image resizing behaviour. The HSSFClientAnchor - * class contains a method called setAnchorType(int) which can be used to - * determine how Excel will resize an image in reponse to the user increasing - * or decreasing the dimensions of the cell containing the image. There are - * three values that can be passed to this method; 0 = To move and size the - * image with the cell, 2 = To move but don't size the image with the cell, - * 3 = To prevent the image from moving or being resized along with the cell. If - * an image is inserted using this class and placed into a single cell then if - * the setAnchorType(int) method is called and a value of either 0 or 2 passed - * to it, the resultant resizing behaviour may be a surprise. The image will not - * grow in size of the column is made wider or the row higher but it will shrink - * if the columns width or rows height are reduced. - * - * @author Mark Beardsley [msb at apache.org] - * @version 1.00 5th August 2009. - */ -public class AddDimensionedImage { - - // Four constants that determine how - and indeed whether - the rows - // and columns an image may overlie should be expanded to accomodate that - // image. - // Passing EXPAND_ROW will result in the height of a row being increased - // to accomodate the image if it is not already larger. The image will - // be layed across one or more columns. - // Passing EXPAND_COLUMN will result in the width of the column being - // increased to accomodate the image if it is not already larger. The image - // will be layed across one or many rows. - // Passing EXPAND_ROW_AND_COLUMN will result in the height of the row - // bing increased along with the width of the column to accomdate the - // image if either is not already larger. - // Passing OVERLAY_ROW_AND_COLUMN will result in the image being layed - // over one or more rows and columns. No row or column will be resized, - // instead, code will determine how many rows and columns the image should - // overlie. - public static final int EXPAND_ROW = 1; - public static final int EXPAND_COLUMN = 2; - public static final int EXPAND_ROW_AND_COLUMN = 3; - public static final int OVERLAY_ROW_AND_COLUMN = 7; - - /** - * Add an image to a worksheet. - * - * @param cellNumber A String that contains the location of the cell whose - * top left hand corner should be aligned with the top - * left hand corner of the image; for example "A1", "A2" - * etc. This is to support the familiar Excel syntax. - * Whilst images are are not actually inserted into cells - * this provides a convenient method of indicating where - * the image should be positioned on the sheet. - * @param sheet A reference to the sheet that contains the cell referenced - * above. - * @param imageFile A String that encapsulates the name of and path to - * the image that is to be 'inserted into' the sheet. - * @param reqImageWidthMM A primitive double that contains the required - * width of the image in millimetres. - * @param reqImageHeightMM A primitive double that contains the required - * height of the image in millimetres. - * @param resizeBehaviour A primitive int whose value will determine how - * the code should react if the image is larger than - * the cell referenced by the cellNumber parameter. - * Four constants are provided to determine what - * should happen; - * AddDimensionedImage.EXPAND_ROW - * AddDimensionedImage.EXPAND_COLUMN - * AddDimensionedImage.EXPAND_ROW_AND_COLUMN - * AddDimensionedImage.OVERLAY_ROW_AND_COLUMN - * @throws java.io.FileNotFoundException If the file containing the image - * cannot be located. - * @throws java.io.IOException If a problem occurs whilst reading the file - * of image data. - * @throws java.lang.IllegalArgumentException If an invalid value is passed - * to the resizeBehaviour - * parameter. - */ - public void addImageToSheet(String cellNumber, HSSFSheet sheet, - String imageFile, double reqImageWidthMM, double reqImageHeightMM, - int resizeBehaviour) throws IOException, IllegalArgumentException { - // Convert the String into column and row indices then chain the - // call to the overridden addImageToSheet() method. - CellReference cellRef = new CellReference(cellNumber); - this.addImageToSheet(cellRef.getCol(), cellRef.getRow(), sheet, - imageFile, reqImageWidthMM, reqImageHeightMM,resizeBehaviour); - } - - /** - * Add an image to a worksheet. - * - * @param colNumber A primitive int that contains the index number of a - * column on the worksheet; POI column indices are zero - * based. Together with the rowNumber parameter's value, - * this parameter identifies a cell on the worksheet. The - * image's top left hand corner will be aligned with the - * top left hand corner of this cell. - * @param rowNumber A primtive int that contains the index number of a row - * on the worksheet; POI row indices are zero based. - * Together with the rowNumber parameter's value, this - * parameter identifies a cell on the worksheet. The - * image's top left hand corner will be aligned with the - * top left hand corner of this cell. - * @param sheet A reference to the sheet that contains the cell identified - * by the two parameters above. - * @param imageFile A String that encapsulates the name of and path to - * the image that is to be 'inserted into' the sheet. - * @param reqImageWidthMM A primitive double that contains the required - * width of the image in millimetres. - * @param reqImageHeightMM A primitive double that contains the required - * height of the image in millimetres. - * @param resizeBehaviour A primitive int whose value will determine how - * the code should react if the image is larger than - * the cell referenced by the colNumber and - * rowNumber parameters. Four constants are provided - * to determine what should happen; - * AddDimensionedImage.EXPAND_ROW - * AddDimensionedImage.EXPAND_COLUMN - * AddDimensionedImage.EXPAND_ROW_AND_COLUMN - * AddDimensionedImage.OVERLAY_ROW_AND_COLUMN - * @throws java.io.FileNotFoundException If the file containing the image - * cannot be located. - * @throws java.io.IOException If a problem occurs whilst reading the file - * of image data. - * @throws java.lang.IllegalArgumentException If an invalid value is passed - * to the resizeBehaviour - * parameter. - */ - private void addImageToSheet(int colNumber, int rowNumber, HSSFSheet sheet, - String imageFile, double reqImageWidthMM, double reqImageHeightMM, - int resizeBehaviour) throws FileNotFoundException, IOException, - IllegalArgumentException { - HSSFClientAnchor anchor = null; - HSSFPatriarch patriarch = null; - ClientAnchorDetail rowClientAnchorDetail = null; - ClientAnchorDetail colClientAnchorDetail = null; - - // Validate the resizeBehaviour parameter. - if((resizeBehaviour != AddDimensionedImage.EXPAND_COLUMN) && - (resizeBehaviour != AddDimensionedImage.EXPAND_ROW) && - (resizeBehaviour != AddDimensionedImage.EXPAND_ROW_AND_COLUMN) && - (resizeBehaviour != AddDimensionedImage.OVERLAY_ROW_AND_COLUMN)) { - throw new IllegalArgumentException("Invalid value passed to the " + - "resizeBehaviour parameter of AddDimensionedImage.addImageToSheet()"); - } - - // Call methods to calculate how the image and sheet should be - // manipulated to accomodate the image; columns and then rows. - colClientAnchorDetail = this.fitImageToColumns(sheet, colNumber, - reqImageWidthMM, resizeBehaviour); - rowClientAnchorDetail = this.fitImageToRows(sheet, rowNumber, - reqImageHeightMM, resizeBehaviour); - - // Having determined if and how to resize the rows, columns and/or the - // image, create the HSSFClientAnchor object to position the image on - // the worksheet. Note how the two ClientAnchorDetail records are - // interrogated to recover the row/column co-ordinates and any insets. - // The first two parameters are not used currently but could be if the - // need arose to extend the functionality of this code by adding the - // ability to specify that a clear 'border' be placed around the image. - anchor = new HSSFClientAnchor(0, - 0, - colClientAnchorDetail.getInset(), - rowClientAnchorDetail.getInset(), - (short)colClientAnchorDetail.getFromIndex(), - rowClientAnchorDetail.getFromIndex(), - (short)colClientAnchorDetail.getToIndex(), - rowClientAnchorDetail.getToIndex()); - - // For now, set the anchor type to do not move or resize the - // image as the size of the row/column is adjusted. This could easilly - // become another parameter passed to the method. - //anchor.setAnchorType(HSSFClientAnchor.DONT_MOVE_AND_RESIZE); - anchor.setAnchorType(AnchorType.MOVE_AND_RESIZE); - - // Now, add the picture to the workbook. Note that the type is assumed - // to be a JPEG/JPG, this could easily (and should) be parameterised - // however. - //int index = sheet.getWorkbook().addPicture(this.imageToBytes(imageFile), - // HSSFWorkbook.PICTURE_TYPE_JPEG); - int index = sheet.getWorkbook().addPicture(this.imageToBytes(imageFile), HSSFWorkbook.PICTURE_TYPE_PNG); - - // Get the drawing patriarch and create the picture. - patriarch = sheet.createDrawingPatriarch(); - patriarch.createPicture(anchor, index); - } - - /** - * Determines whether the sheets columns should be re-sized to accomodate - * the image, adjusts the columns width if necessary and creates then - * returns a ClientAnchorDetail object that facilitates construction of - * an HSSFClientAnchor that will fix the image on the sheet and establish - * it's size. - * - * @param sheet A reference to the sheet that will 'contain' the image. - * @param colNumber A primtive int that contains the index number of a - * column on the sheet. - * @param reqImageWidthMM A primtive double that contains the required - * width of the image in millimetres - * @param resizeBehaviour A primitve int whose value will indicate how the - * width of the column should be adjusted if the - * required width of the image is greater than the - * width of the column. - * @return An instance of the ClientAnchorDetail class that will contain - * the index number of the column containing the cell whose top - * left hand corner also defines the top left hand corner of the - * image, the index number column containing the cell whose top - * left hand corner also defines the bottom right hand corner of - * the image and an inset that determines how far the right hand - * edge of the image can protrude into the next column - expressed - * as a specific number of co-ordinate positions. - */ - private ClientAnchorDetail fitImageToColumns(HSSFSheet sheet, int colNumber, - double reqImageWidthMM, int resizeBehaviour) { - - double colWidthMM = 0.0D; - double colCoordinatesPerMM = 0.0D; - int pictureWidthCoordinates = 0; - ClientAnchorDetail colClientAnchorDetail = null; - - // Get the colum's width in millimetres - colWidthMM = ConvertImageUnits.widthUnits2Millimetres( - (short)sheet.getColumnWidth(colNumber)); - - // Check that the column's width will accomodate the image at the - // required dimension. If the width of the column is LESS than the - // required width of the image, decide how the application should - // respond - resize the column or overlay the image across one or more - // columns. - if(colWidthMM < reqImageWidthMM) { - - // Should the column's width simply be expanded? - if((resizeBehaviour == AddDimensionedImage.EXPAND_COLUMN) || - (resizeBehaviour == AddDimensionedImage.EXPAND_ROW_AND_COLUMN)) { - // Set the width of the column by converting the required image - // width from millimetres into Excel's column width units. - sheet.setColumnWidth(colNumber, - ConvertImageUnits.millimetres2WidthUnits(reqImageWidthMM)); - // To make the image occupy the full width of the column, convert - // the required width of the image into co-ordinates. This value - // will become the inset for the ClientAnchorDetail class that - // is then instantiated. - colWidthMM = reqImageWidthMM; - colCoordinatesPerMM = ConvertImageUnits.TOTAL_COLUMN_COORDINATE_POSITIONS / - colWidthMM; - pictureWidthCoordinates = (int)(reqImageWidthMM * colCoordinatesPerMM); - colClientAnchorDetail = new ClientAnchorDetail(colNumber, - colNumber, pictureWidthCoordinates); - } - // If the user has chosen to overlay both rows and columns or just - // to expand ONLY the size of the rows, then calculate how to lay - // the image out across one or more columns. - else if ((resizeBehaviour == AddDimensionedImage.OVERLAY_ROW_AND_COLUMN) || - (resizeBehaviour == AddDimensionedImage.EXPAND_ROW)) { - colClientAnchorDetail = this.calculateColumnLocation(sheet, - colNumber, reqImageWidthMM); - } - } - // If the column is wider than the image. - else { - // Mow many co-ordinate positions are there per millimetre? - colCoordinatesPerMM = ConvertImageUnits.TOTAL_COLUMN_COORDINATE_POSITIONS / - colWidthMM; - // Given the width of the image, what should be it's co-ordinate? - pictureWidthCoordinates = (int)(reqImageWidthMM * colCoordinatesPerMM); - colClientAnchorDetail = new ClientAnchorDetail(colNumber, - colNumber, pictureWidthCoordinates); - } - return(colClientAnchorDetail); - } - - /** - * Determines whether the sheet's row should be re-sized to accomodate - * the image, adjusts the rows height if necessary and creates then - * returns a ClientAnchorDetail object that facilitates construction of - * an HSSFClientAnchor that will fix the image on the sheet and establish - * it's size. - * - * @param sheet A reference to the sheet that will 'contain' the image. - * @param rowNumber A primtive int that contains the index number of a - * row on the sheet. - * @param reqImageHeightMM A primtive double that contains the required - * height of the image in millimetres - * @param resizeBehaviour A primitve int whose value will indicate how the - * height of the row should be adjusted if the - * required height of the image is greater than the - * height of the row. - * @return An instance of the ClientAnchorDetail class that will contain - * the index number of the row containing the cell whose top - * left hand corner also defines the top left hand corner of the - * image, the index number of the row containing the cell whose - * top left hand corner also defines the bottom right hand - * corner of the image and an inset that determines how far the - * bottom edge of the image can protrude into the next (lower) - * row - expressed as a specific number of co-ordinate positions. - */ - private ClientAnchorDetail fitImageToRows(HSSFSheet sheet, int rowNumber, - double reqImageHeightMM, int resizeBehaviour) { - HSSFRow row = null; - double rowHeightMM = 0.0D; - double rowCoordinatesPerMM = 0.0D; - int pictureHeightCoordinates = 0; - ClientAnchorDetail rowClientAnchorDetail = null; - - // Get the row and it's height - row = sheet.getRow(rowNumber); - if(row == null) { - // Create row if it does not exist. - row = sheet.createRow(rowNumber); - } - - // Get the row's height in millimetres - rowHeightMM = row.getHeightInPoints() / ConvertImageUnits.POINTS_PER_MILLIMETRE; - - // Check that the row's height will accomodate the image at the required - // dimensions. If the height of the row is LESS than the required height - // of the image, decide how the application should respond - resize the - // row or overlay the image across a series of rows. - if(rowHeightMM < reqImageHeightMM) { - if((resizeBehaviour == AddDimensionedImage.EXPAND_ROW) || - (resizeBehaviour == AddDimensionedImage.EXPAND_ROW_AND_COLUMN)) { - row.setHeightInPoints((float)(reqImageHeightMM * - ConvertImageUnits.POINTS_PER_MILLIMETRE)); - rowHeightMM = reqImageHeightMM; - rowCoordinatesPerMM = ConvertImageUnits.TOTAL_ROW_COORDINATE_POSITIONS / - rowHeightMM; - pictureHeightCoordinates = (int)(reqImageHeightMM * rowCoordinatesPerMM); - rowClientAnchorDetail = new ClientAnchorDetail(rowNumber, - rowNumber, pictureHeightCoordinates); - } - // If the user has chosen to overlay both rows and columns or just - // to expand ONLY the size of the columns, then calculate how to lay - // the image out ver one or more rows. - else if((resizeBehaviour == AddDimensionedImage.OVERLAY_ROW_AND_COLUMN) || - (resizeBehaviour == AddDimensionedImage.EXPAND_COLUMN)) { - rowClientAnchorDetail = this.calculateRowLocation(sheet, - rowNumber, reqImageHeightMM); - } - } - // Else, if the image is smaller than the space available - else { - rowCoordinatesPerMM = ConvertImageUnits.TOTAL_ROW_COORDINATE_POSITIONS / - rowHeightMM; - pictureHeightCoordinates = (int)(reqImageHeightMM * rowCoordinatesPerMM); - rowClientAnchorDetail = new ClientAnchorDetail(rowNumber, - rowNumber, pictureHeightCoordinates); - } - return(rowClientAnchorDetail); - } - - /** - * If the image is to overlie more than one column, calculations need to be - * performed to determine how many columns and whether the image will - * overlie just a part of one column in order to be presented at the - * required size. - * - * @param sheet The sheet that will 'contain' the image. - * @param startingColumn A primitive int whose value is the index of the - * column that contains the cell whose top left hand - * corner should be aligned with the top left hand - * corner of the image. - * @param reqImageWidthMM A primitive double whose value will indicate the - * required width of the image in millimetres. - * @return An instance of the ClientAnchorDetail class that will contain - * the index number of the column containing the cell whose top - * left hand corner also defines the top left hand corner of the - * image, the index number column containing the cell whose top - * left hand corner also defines the bottom right hand corner of - * the image and an inset that determines how far the right hand - * edge of the image can protrude into the next column - expressed - * as a specific number of co-ordinate positions. - */ - private ClientAnchorDetail calculateColumnLocation(HSSFSheet sheet, - int startingColumn, - double reqImageWidthMM) { - ClientAnchorDetail anchorDetail = null; - double totalWidthMM = 0.0D; - double colWidthMM = 0.0D; - double overlapMM = 0.0D; - double coordinatePositionsPerMM = 0.0D; - int toColumn = startingColumn; - int inset = 0; - - // Calculate how many columns the image will have to - // span in order to be presented at the required size. - while(totalWidthMM < reqImageWidthMM) { - colWidthMM = ConvertImageUnits.widthUnits2Millimetres( - (short)(sheet.getColumnWidth(toColumn))); - // Note use of the cell border width constant. Testing with an image - // declared to fit exactly into one column demonstrated that it's - // width was greater than the width of the column the POI returned. - // Further, this difference was a constant value that I am assuming - // related to the cell's borders. Either way, that difference needs - // to be allowed for in this calculation. - totalWidthMM += (colWidthMM + ConvertImageUnits.CELL_BORDER_WIDTH_MILLIMETRES); - toColumn++; - } - // De-crement by one the last column value. - toColumn--; - // Highly unlikely that this will be true but, if the width of a series - // of columns is exactly equal to the required width of the image, then - // simply build a ClientAnchorDetail object with an inset equal to the - // total number of co-ordinate positions available in a column, a - // from column co-ordinate (top left hand corner) equal to the value - // of the startingColumn parameter and a to column co-ordinate equal - // to the toColumn variable. - // - // Convert both values to ints to perform the test. - if((int)totalWidthMM == (int)reqImageWidthMM) { - // A problem could occur if the image is sized to fit into one or - // more columns. If that occurs, the value in the toColumn variable - // will be in error. To overcome this, there are two options, to - // ibcrement the toColumn variable's value by one or to pass the - // total number of co-ordinate positions to the third paramater - // of the ClientAnchorDetail constructor. For no sepcific reason, - // the latter option is used below. - anchorDetail = new ClientAnchorDetail(startingColumn, - toColumn, ConvertImageUnits.TOTAL_COLUMN_COORDINATE_POSITIONS); - } - // In this case, the image will overlap part of another column and it is - // necessary to calculate just how much - this will become the inset - // for the ClientAnchorDetail object. - else { - // Firstly, claculate how much of the image should overlap into - // the next column. - overlapMM = reqImageWidthMM - (totalWidthMM - colWidthMM); - - // When the required size is very close indded to the column size, - // the calcaulation above can produce a negative value. To prevent - // problems occuring in later caculations, this is simply removed - // be setting the overlapMM value to zero. - if(overlapMM < 0) { - overlapMM = 0.0D; - } - - // Next, from the columns width, calculate how many co-ordinate - // positons there are per millimetre - coordinatePositionsPerMM = ConvertImageUnits.TOTAL_COLUMN_COORDINATE_POSITIONS / - colWidthMM; - // From this figure, determine how many co-ordinat positions to - // inset the left hand or bottom edge of the image. - inset = (int)(coordinatePositionsPerMM * overlapMM); - - // Now create the ClientAnchorDetail object, setting the from and to - // columns and the inset. - anchorDetail = new ClientAnchorDetail(startingColumn, toColumn, inset); - } - return(anchorDetail); - } - - /** - * If the image is to overlie more than one rows, calculations need to be - * performed to determine how many rows and whether the image will - * overlie just a part of one row in order to be presented at the - * required size. - * - * @param sheet The sheet that will 'contain' the image. - * @param startingRow A primitive int whose value is the index of the row - * that contains the cell whose top left hand corner - * should be aligned with the top left hand corner of - * the image. - * @param reqImageHeightMM A primitive double whose value will indicate the - * required height of the image in millimetres. - * @return An instance of the ClientAnchorDetail class that will contain - * the index number of the row containing the cell whose top - * left hand corner also defines the top left hand corner of the - * image, the index number of the row containing the cell whose top - * left hand corner also defines the bottom right hand corner of - * the image and an inset that determines how far the bottom edge - * can protrude into the next (lower) row - expressed as a specific - * number of co-ordinate positions. - */ - private ClientAnchorDetail calculateRowLocation(HSSFSheet sheet, - int startingRow, double reqImageHeightMM) { - ClientAnchorDetail clientAnchorDetail = null; - HSSFRow row = null; - double rowHeightMM = 0.0D; - double totalRowHeightMM = 0.0D; - double overlapMM = 0.0D; - double rowCoordinatesPerMM = 0.0D; - int toRow = startingRow; - int inset = 0; - - // Step through the rows in the sheet and accumulate a total of their - // heights. - while(totalRowHeightMM < reqImageHeightMM) { - row = sheet.getRow(toRow); - // Note, if the row does not already exist on the sheet then create - // it here. - if(row == null) { - row = sheet.createRow(toRow); - } - // Get the row's height in millimetres and add to the running total. - rowHeightMM = row.getHeightInPoints() / - ConvertImageUnits.POINTS_PER_MILLIMETRE; - totalRowHeightMM += rowHeightMM; - toRow++; - } - // Owing to the way the loop above works, the rowNumber will have been - // incremented one row too far. Undo that here. - toRow--; - // Check to see whether the image should occupy an exact number of - // rows. If so, build the ClientAnchorDetail record to point - // to those rows and with an inset of the total number of co-ordinate - // position in the row. - // - // To overcome problems that can occur with comparing double values for - // equality, cast both to int(s) to truncate the value; VERY crude and - // I do not really like it!! - if((int)totalRowHeightMM == (int)reqImageHeightMM) { - clientAnchorDetail = new ClientAnchorDetail(startingRow, toRow, - ConvertImageUnits.TOTAL_ROW_COORDINATE_POSITIONS); - } - else { - // Calculate how far the image will project into the next row. Note - // that the height of the last row assessed is subtracted from the - // total height of all rows assessed so far. - overlapMM = reqImageHeightMM - (totalRowHeightMM - rowHeightMM); - - // To prevent an exception being thrown when the required width of - // the image is very close indeed to the column size. - if(overlapMM < 0) { - overlapMM = 0.0D; - } - - rowCoordinatesPerMM = ConvertImageUnits.TOTAL_ROW_COORDINATE_POSITIONS / - rowHeightMM; - inset = (int)(overlapMM * rowCoordinatesPerMM); - clientAnchorDetail = new ClientAnchorDetail(startingRow, - toRow, inset); - } - return(clientAnchorDetail); - } - - /** - * Loads - reads in and converts into an array of byte(s) - an image from - * a named file. - * - * Note: this method should be modified so that the type of the image may - * also be passed to it. Currently, it assumes that all images are - * JPG/JPEG(s). - * - * @param imageFilename A String that encapsulates the path to and name - * of the file that contains the image which is to be - * 'loaded'. - * @return An array of type byte that contains the raw data of the named - * image. - * @throws java.io.FileNotFoundException Thrown if it was not possible to - * open the specified file. - * @throws java.io.IOException Thrown if reading the file failed or was - * interrupted. - */ - private byte[] imageToBytes(String imageFilename) throws IOException { - File imageFile = null; - FileInputStream fis = null; - ByteArrayOutputStream bos = null; - int read = 0; - try { - imageFile = new File(imageFilename); - fis = new FileInputStream(imageFile); - bos = new ByteArrayOutputStream(); - while((read = fis.read()) != -1) { - bos.write(read); - } - return(bos.toByteArray()); - } - finally { - if(fis != null) { - try { - fis.close(); - fis = null; - } - catch(IOException ioEx) { - // Nothing to do here - } - } - } - } - - /** - * The main entry point to the program. It contains code that demonstrates - * one way to use the program. - * - * Note, the code is not restricted to use on new workbooks only. If an - * image is to be inserted into an existing workbook. just open that - * workbook, gat a reference to a sheet and pass that; - * - * AddDimensionedImage addImage = new AddDimensionedImage(); - * - * File file = new File("....... Existing Workbook ......."); - * FileInputStream fis = new FileInputStream(file); - * HSSFWorkbook workbook = new HSSFWorkbook(fis); - * HSSFSheet sheet = workbook.getSheetAt(0); - * addImage.addImageToSheet("C3", sheet, "image.jpg", 30, 20, - * AddDimensionedImage.EXPAND.ROW); - * - * @param args the command line arguments - */ - public static void main(String[] args) { - String imageFile = null; - String outputFile = null; - FileOutputStream fos = null; - HSSFSheet sheet = null; - try { - if(args.length < 2){ - System.err.println("Usage: AddDimensionedImage imageFile outputFile"); - return; - } - imageFile = args[0]; - outputFile = args[1]; - - HSSFWorkbook workbook = new HSSFWorkbook(); - sheet = workbook.createSheet("Picture Test"); - new AddDimensionedImage().addImageToSheet("A1", sheet, - imageFile, 125, 125, - AddDimensionedImage.EXPAND_ROW_AND_COLUMN); - fos = new FileOutputStream(outputFile); - workbook.write(fos); - workbook.close(); - } - catch(FileNotFoundException fnfEx) { - System.out.println("Caught an: " + fnfEx.getClass().getName()); - System.out.println("Message: " + fnfEx.getMessage()); - System.out.println("Stacktrace follows..........."); - fnfEx.printStackTrace(System.out); - } - catch(IOException ioEx) { - System.out.println("Caught an: " + ioEx.getClass().getName()); - System.out.println("Message: " + ioEx.getMessage()); - System.out.println("Stacktrace follows..........."); - ioEx.printStackTrace(System.out); - } - finally { - try { - if(fos != null) { - fos.close(); - fos = null; - } - } catch(IOException ioEx) { - // I G N O R E - } - } - } - - /** - * The HSSFClientAnchor class accepts eight parameters. In order, these are; - * - * * How far the left hand edge of the image is inset from the left hand - * edge of the cell - * * How far the top edge of the image is inset from the top of the cell - * * How far the right hand edge of the image is inset from the left - * hand edge of the cell - * * How far the bottom edge of the image is inset from the top of the - * cell. - * * Together, parameters five and six determine the column and row - * co-ordinates of the cell whose top left hand corner will be aligned - * with the image's top left hand corner. - * * Together, parameter seven and eight determine the column and row - * co-ordinates of the cell whose top left hand corner will be aligned - * with the images bottom right hand corner. - * - * An instance of the ClientAnchorDetail class provides three of the eight - * parameters, one of the co-ordinates for the images top left hand corner, - * one of the co-ordinates for the images bottom right hand corner and - * either how far the image should be inset from the top or the left hand - * edge of the cell. - * - * @author Mark Beardsley [mas at apache.org] - * @version 1.00 5th August 2009. - */ - public class ClientAnchorDetail { - - public int fromIndex = 0; - public int toIndex = 0; - public int inset = 0; - - /** - * Create a new instance of the ClientAnchorDetail class using the - * following parameters. - * - * @param fromIndex A primitive int that contains one of the - * co-ordinates (row or column index) for the top left - * hand corner of the image. - * @param toIndex A primitive int that contains one of the - * co-ordinates (row or column index) for the bottom - * right hand corner of the image. - * @param inset A primitive int that contains a value which indicates - * how far the image should be inset from the top or the - * left hand edge of a cell. - */ - public ClientAnchorDetail(int fromIndex, int toIndex, int inset) { - this.fromIndex = fromIndex; - this.toIndex = toIndex; - this.inset = inset; - } - - /** - * Get one of the number of the column or row that contains the cell - * whose top left hand corner will be aligned with the top left hand - * corner of the image. - * - * @return The value - row or column index - for one of the co-ordinates - * of the top left hand corner of the image. - */ - public int getFromIndex() { - return(this.fromIndex); - } - - /** - * Get one of the number of the column or row that contains the cell - * whose top left hand corner will be aligned with the bottom righ hand - * corner of the image. - * - * @return The value - row or column index - for one of the co-ordinates - * of the bottom right hand corner of the image. - */ - public int getToIndex() { - return(this.toIndex); - } - - /** - * Get the image's offset from the edge of a cell. - * - * @return How far either the right hand or bottom edge of the image is - * inset from the left hand or top edge of a cell. - */ - public int getInset() { - return(this.inset); - } - } - - /** - * Utility methods used to convert Excel's character based column and row - * size measurements into pixels and/or millimetres. The class also contains - * various constants that are required in other calculations. - * - * @author xio[darjino@hotmail.com] - * @version 1.01 30th July 2009. - * Added by Mark Beardsley [msb at apache.org]. - * Additional constants. - * widthUnits2Millimetres() and millimetres2Units() methods. - */ - public static class ConvertImageUnits { - - // Each cell conatins a fixed number of co-ordinate points; this number - // does not vary with row height or column width or with font. These two - // constants are defined below. - public static final int TOTAL_COLUMN_COORDINATE_POSITIONS = 1023; // MB - public static final int TOTAL_ROW_COORDINATE_POSITIONS = 255; // MB - // The resoultion of an image can be expressed as a specific number - // of pixels per inch. Displays and printers differ but 96 pixels per - // inch is an acceptable standard to beging with. - public static final int PIXELS_PER_INCH = 96; // MB - // Cnstants that defines how many pixels and points there are in a - // millimetre. These values are required for the conversion algorithm. - public static final double PIXELS_PER_MILLIMETRES = 3.78; // MB - public static final double POINTS_PER_MILLIMETRE = 2.83; // MB - // The column width returned by HSSF and the width of a picture when - // positioned to exactly cover one cell are different by almost exactly - // 2mm - give or take rounding errors. This constant allows that - // additional amount to be accounted for when calculating how many - // celles the image ought to overlie. - public static final double CELL_BORDER_WIDTH_MILLIMETRES = 2.0D; // MB - public static final short EXCEL_COLUMN_WIDTH_FACTOR = 256; - public static final int UNIT_OFFSET_LENGTH = 7; - public static final int[] UNIT_OFFSET_MAP = new int[] - { 0, 36, 73, 109, 146, 182, 219 }; - - /** - * pixel units to excel width units(units of 1/256th of a character width) - * @param pxs - * @return - */ - public static short pixel2WidthUnits(int pxs) { - short widthUnits = (short) (EXCEL_COLUMN_WIDTH_FACTOR * - (pxs / UNIT_OFFSET_LENGTH)); - widthUnits += UNIT_OFFSET_MAP[(pxs % UNIT_OFFSET_LENGTH)]; - return widthUnits; - } - - /** - * excel width units(units of 1/256th of a character width) to pixel - * units. - * - * @param widthUnits - * @return - */ - public static int widthUnits2Pixel(short widthUnits) { - int pixels = (widthUnits / EXCEL_COLUMN_WIDTH_FACTOR) - * UNIT_OFFSET_LENGTH; - int offsetWidthUnits = widthUnits % EXCEL_COLUMN_WIDTH_FACTOR; - pixels += Math.round(offsetWidthUnits / - ((float) EXCEL_COLUMN_WIDTH_FACTOR / UNIT_OFFSET_LENGTH)); - return pixels; - } - - /** - * Convert Excel's width units into millimetres. - * - * @param widthUnits The width of the column or the height of the - * row in Excel's units. - * @return A primitive double that contains the columns width or rows - * height in millimetres. - */ - public static double widthUnits2Millimetres(short widthUnits) { - return(ConvertImageUnits.widthUnits2Pixel(widthUnits) / - ConvertImageUnits.PIXELS_PER_MILLIMETRES); - } - - /** - * Convert into millimetres Excel's width units.. - * - * @param millimetres A primitive double that contains the columns - * width or rows height in millimetres. - * @return A primitive int that contains the columns width or rows - * height in Excel's units. - */ - public static int millimetres2WidthUnits(double millimetres) { - return(ConvertImageUnits.pixel2WidthUnits((int)(millimetres * - ConvertImageUnits.PIXELS_PER_MILLIMETRES))); - } - } -} \ No newline at end of file diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/Alignment.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/Alignment.java deleted file mode 100644 index 43fb75db1..000000000 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/Alignment.java +++ /dev/null @@ -1,73 +0,0 @@ - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - - -package org.apache.poi.hssf.usermodel.examples; - -import java.io.FileOutputStream; -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFCellStyle; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.HorizontalAlignment; - -/** - * Shows how various alignment options work. - * - * @author Glen Stampoultzis (glens at apache.org) - */ -public class Alignment { - public static void main(String[] args) throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("new sheet"); - HSSFRow row = sheet.createRow(2); - createCell(wb, row, 0, HorizontalAlignment.CENTER); - createCell(wb, row, 1, HorizontalAlignment.CENTER_SELECTION); - createCell(wb, row, 2, HorizontalAlignment.FILL); - createCell(wb, row, 3, HorizontalAlignment.GENERAL); - createCell(wb, row, 4, HorizontalAlignment.JUSTIFY); - createCell(wb, row, 5, HorizontalAlignment.LEFT); - createCell(wb, row, 6, HorizontalAlignment.RIGHT); - - // Write the output to a file - FileOutputStream fileOut = new FileOutputStream("workbook.xls"); - wb.write(fileOut); - fileOut.close(); - - wb.close(); - } - - /** - * Creates a cell and aligns it a certain way. - * - * @param wb the workbook - * @param row the row to create the cell in - * @param column the column number to create the cell in - * @param align the alignment for the cell. - */ - private static void createCell(HSSFWorkbook wb, HSSFRow row, int column, HorizontalAlignment align) { - HSSFCell cell = row.createCell(column); - cell.setCellValue("Align It"); - HSSFCellStyle cellStyle = wb.createCellStyle(); - cellStyle.setAlignment(align); - cell.setCellStyle(cellStyle); - } -} diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/BigExample.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/BigExample.java deleted file mode 100644 index d108214e6..000000000 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/BigExample.java +++ /dev/null @@ -1,175 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel.examples; - -import java.io.FileOutputStream; -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFCellStyle; -import org.apache.poi.hssf.usermodel.HSSFDataFormat; -import org.apache.poi.hssf.usermodel.HSSFFont; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.hssf.util.HSSFColor.HSSFColorPredefined; -import org.apache.poi.ss.usermodel.BorderStyle; -import org.apache.poi.ss.usermodel.FillPatternType; - -/** - * Demonstrates many features of the user API at once. Used in the HOW-TO guide. - */ -public class BigExample { - public static void main(String[] args) throws IOException { - int rownum; - - // create a new file - FileOutputStream out = new FileOutputStream("workbook.xls"); - // create a new workbook - HSSFWorkbook wb = new HSSFWorkbook(); - // create a new sheet - HSSFSheet s = wb.createSheet(); - // declare a row object reference - HSSFRow r = null; - // declare a cell object reference - HSSFCell c = null; - // create 3 cell styles - HSSFCellStyle cs = wb.createCellStyle(); - HSSFCellStyle cs2 = wb.createCellStyle(); - HSSFCellStyle cs3 = wb.createCellStyle(); - // create 2 fonts objects - HSSFFont f = wb.createFont(); - HSSFFont f2 = wb.createFont(); - - //set font 1 to 12 point type - f.setFontHeightInPoints((short) 12); - //make it red - f.setColor(HSSFColorPredefined.RED.getIndex()); - // make it bold - //arial is the default font - f.setBold(true); - - //set font 2 to 10 point type - f2.setFontHeightInPoints((short) 10); - //make it the color at palette index 0xf (white) - f2.setColor(HSSFColorPredefined.WHITE.getIndex()); - //make it bold - f2.setBold(true); - - //set cell stlye - cs.setFont(f); - //set the cell format see HSSFDataFromat for a full list - cs.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0_);[Red]($#,##0)")); - - //set a thin border - cs2.setBorderBottom(BorderStyle.THIN); - //fill w fg fill color - cs2.setFillPattern(FillPatternType.SOLID_FOREGROUND); - // set foreground fill to red - cs2.setFillForegroundColor(HSSFColorPredefined.RED.getIndex()); - - // set the font - cs2.setFont(f2); - - // set the sheet name to HSSF Test - wb.setSheetName(0, "HSSF Test"); - // create a sheet with 300 rows (0-299) - for (rownum = 0; rownum < 300; rownum++) - { - // create a row - r = s.createRow(rownum); - // on every other row - if ((rownum % 2) == 0) - { - // make the row height bigger (in twips - 1/20 of a point) - r.setHeight((short) 0x249); - } - - //r.setRowNum(( short ) rownum); - // create 50 cells (0-49) (the += 2 becomes apparent later - for (int cellnum = 0; cellnum < 50; cellnum += 2) - { - // create a numeric cell - c = r.createCell(cellnum); - // do some goofy math to demonstrate decimals - c.setCellValue(rownum * 10000 + cellnum - + (((double) rownum / 1000) - + ((double) cellnum / 10000))); - - // on every other row - if ((rownum % 2) == 0) - { - // set this cell to the first cell style we defined - c.setCellStyle(cs); - } - - // create a string cell (see why += 2 in the - c = r.createCell(cellnum + 1); - - // set the cell's string value to "TEST" - c.setCellValue("TEST"); - // make this column a bit wider - s.setColumnWidth(cellnum + 1, (int)((50 * 8) / ((double) 1 / 20))); - - // on every other row - if ((rownum % 2) == 0) - { - // set this to the white on red cell style - // we defined above - c.setCellStyle(cs2); - } - - } - } - - //draw a thick black border on the row at the bottom using BLANKS - // advance 2 rows - rownum++; - rownum++; - - r = s.createRow(rownum); - - // define the third style to be the default - // except with a thick black border at the bottom - cs3.setBorderBottom(BorderStyle.THICK); - - //create 50 cells - for (int cellnum =0; cellnum < 50; cellnum++) { - //create a blank type cell (no value) - c = r.createCell(cellnum); - // set it to the thick black border style - c.setCellStyle(cs3); - } - - //end draw thick black border - - - // demonstrate adding/naming and deleting a sheet - // create a sheet, set its title then delete it - wb.createSheet(); - wb.setSheetName(1, "DeletedSheet"); - wb.removeSheetAt(1); - //end deleted sheet - - // write the workbook to the output stream - // close our file (don't blow out our file handles - wb.write(out); - out.close(); - wb.close(); - } -} diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/Borders.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/Borders.java deleted file mode 100644 index 8573f1113..000000000 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/Borders.java +++ /dev/null @@ -1,65 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel.examples; - -import java.io.FileOutputStream; -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFCellStyle; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.hssf.util.HSSFColor.HSSFColorPredefined; -import org.apache.poi.ss.usermodel.BorderStyle; - -/** - * Demonstrates how to create borders around cells. - */ -public class Borders { - public static void main(String[] args) throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("new sheet"); - - // Create a row and put some cells in it. Rows are 0 based. - HSSFRow row = sheet.createRow(1); - - // Create a cell and put a value in it. - HSSFCell cell = row.createCell(1); - cell.setCellValue(4); - - // Style the cell with borders all around. - HSSFCellStyle style = wb.createCellStyle(); - style.setBorderBottom(BorderStyle.THIN); - style.setBottomBorderColor(HSSFColorPredefined.BLACK.getIndex()); - style.setBorderLeft(BorderStyle.THIN); - style.setLeftBorderColor(HSSFColorPredefined.GREEN.getIndex()); - style.setBorderRight(BorderStyle.THIN); - style.setRightBorderColor(HSSFColorPredefined.BLUE.getIndex()); - style.setBorderTop(BorderStyle.MEDIUM_DASHED); - style.setTopBorderColor(HSSFColorPredefined.ORANGE.getIndex()); - cell.setCellStyle(style); - - // Write the output to a file - FileOutputStream fileOut = new FileOutputStream("workbook.xls"); - wb.write(fileOut); - fileOut.close(); - - wb.close(); - } -} diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/CellComments.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/CellComments.java deleted file mode 100644 index 35df7690a..000000000 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/CellComments.java +++ /dev/null @@ -1,106 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel.examples; - -import java.io.FileOutputStream; -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFClientAnchor; -import org.apache.poi.hssf.usermodel.HSSFComment; -import org.apache.poi.hssf.usermodel.HSSFFont; -import org.apache.poi.hssf.usermodel.HSSFPatriarch; -import org.apache.poi.hssf.usermodel.HSSFRichTextString; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.hssf.util.HSSFColor.HSSFColorPredefined; - -/** - * Demonstrates how to work with excel cell comments. - * - *

    - * Excel comment is a kind of a text shape, - * so inserting a comment is very similar to placing a text box in a worksheet - *

    - */ -public class CellComments { - - public static void main(String[] args) throws IOException { - - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("Cell comments in POI HSSF"); - - // Create the drawing patriarch. This is the top level container for all shapes including cell comments. - HSSFPatriarch patr = sheet.createDrawingPatriarch(); - - //create a cell in row 3 - HSSFCell cell1 = sheet.createRow(3).createCell(1); - cell1.setCellValue(new HSSFRichTextString("Hello, World")); - - //anchor defines size and position of the comment in worksheet - HSSFComment comment1 = patr.createComment(new HSSFClientAnchor(0, 0, 0, 0, (short)4, 2, (short) 6, 5)); - - // set text in the comment - comment1.setString(new HSSFRichTextString("We can set comments in POI")); - - //set comment author. - //you can see it in the status bar when moving mouse over the commented cell - comment1.setAuthor("Apache Software Foundation"); - - // The first way to assign comment to a cell is via HSSFCell.setCellComment method - cell1.setCellComment(comment1); - - //create another cell in row 6 - HSSFCell cell2 = sheet.createRow(6).createCell(1); - cell2.setCellValue(36.6); - - - HSSFComment comment2 = patr.createComment(new HSSFClientAnchor(0, 0, 0, 0, (short)4, 8, (short) 6, 11)); - //modify background color of the comment - comment2.setFillColor(204, 236, 255); - - HSSFRichTextString string = new HSSFRichTextString("Normal body temperature"); - - //apply custom font to the text in the comment - HSSFFont font = wb.createFont(); - font.setFontName("Arial"); - font.setFontHeightInPoints((short)10); - font.setBold(true); - font.setColor(HSSFColorPredefined.RED.getIndex()); - string.applyFont(font); - - comment2.setString(string); - comment2.setVisible(true); //by default comments are hidden. This one is always visible. - - comment2.setAuthor("Bill Gates"); - - /** - * The second way to assign comment to a cell is to implicitly specify its row and column. - * Note, it is possible to set row and column of a non-existing cell. - * It works, the comment is visible. - */ - comment2.setRow(6); - comment2.setColumn(1); - - FileOutputStream out = new FileOutputStream("poi_comment.xls"); - wb.write(out); - out.close(); - - wb.close(); - } -} diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/CellTypes.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/CellTypes.java deleted file mode 100644 index 80ced95ac..000000000 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/CellTypes.java +++ /dev/null @@ -1,47 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel.examples; - -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Date; - -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.CellType; - -public class CellTypes { - public static void main(String[] args) throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("new sheet"); - HSSFRow row = sheet.createRow(2); - row.createCell(0).setCellValue(1.1); - row.createCell(1).setCellValue(new Date()); - row.createCell(2).setCellValue("a string"); - row.createCell(3).setCellValue(true); - row.createCell(4).setCellType(CellType.ERROR); - - // Write the output to a file - FileOutputStream fileOut = new FileOutputStream("workbook.xls"); - wb.write(fileOut); - fileOut.close(); - - wb.close(); - } -} diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/CreateCells.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/CreateCells.java deleted file mode 100644 index d2141b050..000000000 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/CreateCells.java +++ /dev/null @@ -1,56 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel.examples; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFCell; - -import java.io.FileOutputStream; -import java.io.IOException; - -/** - * Illustrates how to create cell values. - * - * @author Glen Stampoultzis (glens at apache.org) - */ -public class CreateCells { - public static void main(String[] args) throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("new sheet"); - - // Create a row and put some cells in it. Rows are 0 based. - HSSFRow row = sheet.createRow(0); - // Create a cell and put a value in it. - HSSFCell cell = row.createCell(0); - cell.setCellValue(1); - - // Or do it on one line. - row.createCell(1).setCellValue(1.2); - row.createCell(2).setCellValue("This is a string"); - row.createCell(3).setCellValue(true); - - // Write the output to a file - FileOutputStream fileOut = new FileOutputStream("workbook.xls"); - wb.write(fileOut); - fileOut.close(); - - wb.close(); - } -} diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/CreateDateCells.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/CreateDateCells.java deleted file mode 100644 index 8afe085f1..000000000 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/CreateDateCells.java +++ /dev/null @@ -1,63 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel.examples; - -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Date; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFCellStyle; -import org.apache.poi.hssf.usermodel.HSSFDataFormat; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; - -/** - * An example on how to cells with dates. The important thing to note - * about dates is that they are really normal numeric cells that are - * formatted specially. - */ -public class CreateDateCells { - public static void main(String[] args) throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("new sheet"); - - // Create a row and put some cells in it. Rows are 0 based. - HSSFRow row = sheet.createRow(0); - - // Create a cell and put a date value in it. The first cell is not styled as a date. - HSSFCell cell = row.createCell(0); - cell.setCellValue(new Date()); - - // we style the second cell as a date (and time). It is important to create a new cell style from the workbook - // otherwise you can end up modifying the built in style and effecting not only this cell but other cells. - HSSFCellStyle cellStyle = wb.createCellStyle(); - cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm")); - cell = row.createCell(1); - cell.setCellValue(new Date()); - cell.setCellStyle(cellStyle); - - // Write the output to a file - FileOutputStream fileOut = new FileOutputStream("workbook.xls"); - wb.write(fileOut); - fileOut.close(); - - wb.close(); - } -} diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/EmbeddedObjects.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/EmbeddedObjects.java deleted file mode 100644 index 4f0a707b2..000000000 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/EmbeddedObjects.java +++ /dev/null @@ -1,67 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hssf.usermodel.examples; - -import java.io.Closeable; -import java.io.FileInputStream; - -import org.apache.poi.hslf.usermodel.HSLFSlideShow; -import org.apache.poi.hssf.usermodel.HSSFObjectData; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.hwpf.HWPFDocument; -import org.apache.poi.poifs.filesystem.DirectoryNode; -import org.apache.poi.poifs.filesystem.Entry; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; - -/** - * Demonstrates how you can extract embedded data from a .xls file - */ -public class EmbeddedObjects { - @SuppressWarnings("unused") - public static void main(String[] args) throws Exception { - POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(args[0])); - HSSFWorkbook workbook = new HSSFWorkbook(fs); - for (HSSFObjectData obj : workbook.getAllEmbeddedObjects()) { - //the OLE2 Class Name of the object - String oleName = obj.getOLE2ClassName(); - DirectoryNode dn = (obj.hasDirectoryEntry()) ? (DirectoryNode) obj.getDirectory() : null; - Closeable document = null; - if (oleName.equals("Worksheet")) { - document = new HSSFWorkbook(dn, fs, false); - } else if (oleName.equals("Document")) { - document = new HWPFDocument(dn); - } else if (oleName.equals("Presentation")) { - document = new HSLFSlideShow(dn); - } else { - if(dn != null){ - // The DirectoryEntry is a DocumentNode. Examine its entries to find out what it is - for (Entry entry : dn) { - String name = entry.getName(); - } - } else { - // There is no DirectoryEntry - // Recover the object's data from the HSSFObjectData instance. - byte[] objectData = obj.getObjectData(); - } - } - if (document != null) { - document.close(); - } - } - workbook.close(); - } -} diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/EventExample.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/EventExample.java deleted file mode 100644 index a324b3af4..000000000 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/EventExample.java +++ /dev/null @@ -1,119 +0,0 @@ - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel.examples; - -import org.apache.poi.hssf.eventusermodel.HSSFEventFactory; -import org.apache.poi.hssf.eventusermodel.HSSFListener; -import org.apache.poi.hssf.eventusermodel.HSSFRequest; -import org.apache.poi.hssf.record.*; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; - -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; - -/** - * This example shows how to use the event API for reading a file. - */ -public class EventExample - implements HSSFListener -{ - private SSTRecord sstrec; - - /** - * This method listens for incoming records and handles them as required. - * @param record The record that was found while reading. - */ - @Override - public void processRecord(Record record) - { - switch (record.getSid()) - { - // the BOFRecord can represent either the beginning of a sheet or the workbook - case BOFRecord.sid: - BOFRecord bof = (BOFRecord) record; - if (bof.getType() == BOFRecord.TYPE_WORKBOOK) - { - System.out.println("Encountered workbook"); - // assigned to the class level member - } else if (bof.getType() == BOFRecord.TYPE_WORKSHEET) - { - System.out.println("Encountered sheet reference"); - } - break; - case BoundSheetRecord.sid: - BoundSheetRecord bsr = (BoundSheetRecord) record; - System.out.println("New sheet named: " + bsr.getSheetname()); - break; - case RowRecord.sid: - RowRecord rowrec = (RowRecord) record; - System.out.println("Row found, first column at " - + rowrec.getFirstCol() + " last column at " + rowrec.getLastCol()); - break; - case NumberRecord.sid: - NumberRecord numrec = (NumberRecord) record; - System.out.println("Cell found with value " + numrec.getValue() - + " at row " + numrec.getRow() + " and column " + numrec.getColumn()); - break; - // SSTRecords store a array of unique strings used in Excel. - case SSTRecord.sid: - sstrec = (SSTRecord) record; - for (int k = 0; k < sstrec.getNumUniqueStrings(); k++) - { - System.out.println("String table value " + k + " = " + sstrec.getString(k)); - } - break; - case LabelSSTRecord.sid: - LabelSSTRecord lrec = (LabelSSTRecord) record; - System.out.println("String cell found with value " - + sstrec.getString(lrec.getSSTIndex())); - break; - } - } - - /** - * Read an excel file and spit out what we find. - * - * @param args Expect one argument that is the file to read. - * @throws IOException When there is an error processing the file. - */ - public static void main(String[] args) throws IOException - { - // create a new file input stream with the input file specified - // at the command line - FileInputStream fin = new FileInputStream(args[0]); - // create a new org.apache.poi.poifs.filesystem.Filesystem - POIFSFileSystem poifs = new POIFSFileSystem(fin); - // get the Workbook (excel part) stream in a InputStream - InputStream din = poifs.createDocumentInputStream("Workbook"); - // construct out HSSFRequest object - HSSFRequest req = new HSSFRequest(); - // lazy listen for ALL records with the listener shown above - req.addListenerForAllRecords(new EventExample()); - // create our event factory - HSSFEventFactory factory = new HSSFEventFactory(); - // process our events based on the document input stream - factory.processEvents(req, din); - // once all the events are processed close our file input stream - fin.close(); - // and our document input stream (don't want to leak these!) - din.close(); - System.out.println("done."); - } -} diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/FrillsAndFills.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/FrillsAndFills.java deleted file mode 100644 index 9b05853e4..000000000 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/FrillsAndFills.java +++ /dev/null @@ -1,65 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel.examples; - -import java.io.FileOutputStream; -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFCellStyle; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.hssf.util.HSSFColor.HSSFColorPredefined; -import org.apache.poi.ss.usermodel.FillPatternType; - -/** - * Shows how to use various fills. - */ -public class FrillsAndFills { - public static void main(String[] args) throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("new sheet"); - - // Create a row and put some cells in it. Rows are 0 based. - HSSFRow row = sheet.createRow(1); - - // Aqua background - HSSFCellStyle style = wb.createCellStyle(); - style.setFillBackgroundColor(HSSFColorPredefined.AQUA.getIndex()); - style.setFillPattern(FillPatternType.BIG_SPOTS); - HSSFCell cell = row.createCell(1); - cell.setCellValue("X"); - cell.setCellStyle(style); - - // Orange "foreground", foreground being the fill foreground not the font color. - style = wb.createCellStyle(); - style.setFillForegroundColor(HSSFColorPredefined.ORANGE.getIndex()); - style.setFillPattern(FillPatternType.SOLID_FOREGROUND); - cell = row.createCell(2); - cell.setCellValue("X"); - cell.setCellStyle(style); - - // Write the output to a file - FileOutputStream fileOut = new FileOutputStream("workbook.xls"); - wb.write(fileOut); - fileOut.close(); - - wb.close(); - } -} diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/HSSFReadWrite.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/HSSFReadWrite.java deleted file mode 100644 index 1f56f7ec5..000000000 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/HSSFReadWrite.java +++ /dev/null @@ -1,286 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel.examples; - -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Locale; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFCellStyle; -import org.apache.poi.hssf.usermodel.HSSFDataFormat; -import org.apache.poi.hssf.usermodel.HSSFFont; -import org.apache.poi.hssf.usermodel.HSSFRichTextString; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.BorderStyle; -import org.apache.poi.ss.usermodel.FillPatternType; -import org.apache.poi.ss.util.CellRangeAddress; - -/** - * File for HSSF testing/examples - * - * THIS IS NOT THE MAIN HSSF FILE!! This is a utility for testing functionality. - * It does contain sample API usage that may be educational to regular API - * users. - */ -public final class HSSFReadWrite { - - /** - * creates an {@link HSSFWorkbook} with the specified OS filename. - */ - private static HSSFWorkbook readFile(String filename) throws IOException { - FileInputStream fis = new FileInputStream(filename); - try { - return new HSSFWorkbook(fis); // NOSONAR - should not be closed here - } finally { - fis.close(); - } - } - - /** - * given a filename this outputs a sample sheet with just a set of - * rows/cells. - */ - private static void testCreateSampleSheet(String outputFilename) throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - try { - HSSFSheet s = wb.createSheet(); - HSSFCellStyle cs = wb.createCellStyle(); - HSSFCellStyle cs2 = wb.createCellStyle(); - HSSFCellStyle cs3 = wb.createCellStyle(); - HSSFFont f = wb.createFont(); - HSSFFont f2 = wb.createFont(); - - f.setFontHeightInPoints((short) 12); - f.setColor((short) 0xA); - f.setBold(true); - f2.setFontHeightInPoints((short) 10); - f2.setColor((short) 0xf); - f2.setBold(true); - cs.setFont(f); - cs.setDataFormat(HSSFDataFormat.getBuiltinFormat("($#,##0_);[Red]($#,##0)")); - cs2.setBorderBottom(BorderStyle.THIN); - cs2.setFillPattern(FillPatternType.SOLID_FOREGROUND); - cs2.setFillForegroundColor((short) 0xA); - cs2.setFont(f2); - wb.setSheetName(0, "HSSF Test"); - int rownum; - for (rownum = 0; rownum < 300; rownum++) { - HSSFRow r = s.createRow(rownum); - if ((rownum % 2) == 0) { - r.setHeight((short) 0x249); - } - - for (int cellnum = 0; cellnum < 50; cellnum += 2) { - HSSFCell c = r.createCell(cellnum); - c.setCellValue(rownum * 10000 + cellnum - + (((double) rownum / 1000) + ((double) cellnum / 10000))); - if ((rownum % 2) == 0) { - c.setCellStyle(cs); - } - c = r.createCell(cellnum + 1); - c.setCellValue(new HSSFRichTextString("TEST")); - // 50 characters divided by 1/20th of a point - s.setColumnWidth(cellnum + 1, (int) (50 * 8 / 0.05)); - if ((rownum % 2) == 0) { - c.setCellStyle(cs2); - } - } - } - - // draw a thick black border on the row at the bottom using BLANKS - rownum++; - rownum++; - HSSFRow r = s.createRow(rownum); - cs3.setBorderBottom(BorderStyle.THICK); - for (int cellnum = 0; cellnum < 50; cellnum++) { - HSSFCell c = r.createCell(cellnum); - c.setCellStyle(cs3); - } - s.addMergedRegion(new CellRangeAddress(0, 3, 0, 3)); - s.addMergedRegion(new CellRangeAddress(100, 110, 100, 110)); - - // end draw thick black border - // create a sheet, set its title then delete it - wb.createSheet(); - wb.setSheetName(1, "DeletedSheet"); - wb.removeSheetAt(1); - - // end deleted sheet - FileOutputStream out = new FileOutputStream(outputFilename); - try { - wb.write(out); - } finally { - out.close(); - } - } finally { - wb.close(); - } - } - - /** - * Method main - * - * Given 1 argument takes that as the filename, inputs it and dumps the - * cell values/types out to sys.out.
    - * - * given 2 arguments where the second argument is the word "write" and the - * first is the filename - writes out a sample (test) spreadsheet - * see {@link HSSFReadWrite#testCreateSampleSheet(String)}.
    - * - * given 2 arguments where the first is an input filename and the second - * an output filename (not write), attempts to fully read in the - * spreadsheet and fully write it out.
    - * - * given 3 arguments where the first is an input filename and the second an - * output filename (not write) and the third is "modify1", attempts to read in the - * spreadsheet, deletes rows 0-24, 74-99. Changes cell at row 39, col 3 to - * "MODIFIED CELL" then writes it out. Hence this is "modify test 1". If you - * take the output from the write test, you'll have a valid scenario. - */ - public static void main(String[] args) { - if (args.length < 1) { - System.err.println("At least one argument expected"); - return; - } - - String fileName = args[0]; - try { - if (args.length < 2) { - - HSSFWorkbook wb = HSSFReadWrite.readFile(fileName); - - try { - System.out.println("Data dump:\n"); - - for (int k = 0; k < wb.getNumberOfSheets(); k++) { - HSSFSheet sheet = wb.getSheetAt(k); - int rows = sheet.getPhysicalNumberOfRows(); - System.out.println("Sheet " + k + " \"" + wb.getSheetName(k) + "\" has " + rows - + " row(s)."); - for (int r = 0; r < rows; r++) { - HSSFRow row = sheet.getRow(r); - if (row == null) { - continue; - } - - System.out.println("\nROW " + row.getRowNum() + " has " + row.getPhysicalNumberOfCells() + " cell(s)."); - for (int c = 0; c < row.getLastCellNum(); c++) { - HSSFCell cell = row.getCell(c); - String value; - - if(cell != null) { - switch (cell.getCellTypeEnum()) { - - case FORMULA: - value = "FORMULA value=" + cell.getCellFormula(); - break; - - case NUMERIC: - value = "NUMERIC value=" + cell.getNumericCellValue(); - break; - - case STRING: - value = "STRING value=" + cell.getStringCellValue(); - break; - - case BLANK: - value = ""; - break; - - case BOOLEAN: - value = "BOOLEAN value-" + cell.getBooleanCellValue(); - break; - - case ERROR: - value = "ERROR value=" + cell.getErrorCellValue(); - break; - - default: - value = "UNKNOWN value of type " + cell.getCellTypeEnum(); - } - System.out.println("CELL col=" + cell.getColumnIndex() + " VALUE=" - + value); - } - } - } - } - } finally { - wb.close(); - } - } else if (args.length == 2) { - if (args[1].toLowerCase(Locale.ROOT).equals("write")) { - System.out.println("Write mode"); - long time = System.currentTimeMillis(); - HSSFReadWrite.testCreateSampleSheet(fileName); - - System.out.println("" + (System.currentTimeMillis() - time) - + " ms generation time"); - } else { - System.out.println("readwrite test"); - HSSFWorkbook wb = HSSFReadWrite.readFile(fileName); - try { - FileOutputStream stream = new FileOutputStream(args[1]); - try { - wb.write(stream); - } finally { - stream.close(); - } - } finally { - wb.close(); - } - } - } else if (args.length == 3 && args[2].equalsIgnoreCase("modify1")) { - // delete row 0-24, row 74 - 99 && change cell 3 on row 39 to string "MODIFIED CELL!!" - - HSSFWorkbook wb = HSSFReadWrite.readFile(fileName); - try { - HSSFSheet sheet = wb.getSheetAt(0); - - for (int k = 0; k < 25; k++) { - HSSFRow row = sheet.getRow(k); - - sheet.removeRow(row); - } - for (int k = 74; k < 100; k++) { - HSSFRow row = sheet.getRow(k); - - sheet.removeRow(row); - } - HSSFRow row = sheet.getRow(39); - HSSFCell cell = row.getCell(3); - cell.setCellValue("MODIFIED CELL!!!!!"); - - FileOutputStream stream = new FileOutputStream(args[1]); - try { - wb.write(stream); - } finally { - stream.close(); - } - } finally { - wb.close(); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } -} diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/HyperlinkFormula.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/HyperlinkFormula.java deleted file mode 100644 index 003c09f68..000000000 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/HyperlinkFormula.java +++ /dev/null @@ -1,47 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel.examples; - -import java.io.FileOutputStream; -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.CellType; - -/** - * Test if hyperlink formula, with url that got more than 127 characters, works - */ -public class HyperlinkFormula { - public static void main(String[] args) throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("new sheet"); - HSSFRow row = sheet.createRow(0); - - HSSFCell cell = row.createCell(0); - cell.setCellType(CellType.FORMULA); - cell.setCellFormula("HYPERLINK(\"http://127.0.0.1:8080/toto/truc/index.html?test=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\", \"test\")"); - - FileOutputStream fileOut = new FileOutputStream("workbook.xls"); - wb.write(fileOut); - fileOut.close(); - wb.close(); - } -} diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/Hyperlinks.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/Hyperlinks.java deleted file mode 100644 index 9a71bcd22..000000000 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/Hyperlinks.java +++ /dev/null @@ -1,97 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel.examples; - -import java.io.FileOutputStream; -import java.io.IOException; - -import org.apache.poi.common.usermodel.HyperlinkType; -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFCellStyle; -import org.apache.poi.hssf.usermodel.HSSFCreationHelper; -import org.apache.poi.hssf.usermodel.HSSFFont; -import org.apache.poi.hssf.usermodel.HSSFHyperlink; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.hssf.util.HSSFColor.HSSFColorPredefined; -import org.apache.poi.ss.usermodel.Font; - -/** - * Demonstrates how to create hyperlinks. - */ -public class Hyperlinks { - - public static void main(String[] args) throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFCreationHelper helper = wb.getCreationHelper(); - - //cell style for hyperlinks - //by default hyperlinks are blue and underlined - HSSFCellStyle hlink_style = wb.createCellStyle(); - HSSFFont hlink_font = wb.createFont(); - hlink_font.setUnderline(Font.U_SINGLE); - hlink_font.setColor(HSSFColorPredefined.BLUE.getIndex()); - hlink_style.setFont(hlink_font); - - HSSFCell cell; - HSSFSheet sheet = wb.createSheet("Hyperlinks"); - - //URL - cell = sheet.createRow(0).createCell(0); - cell.setCellValue("URL Link"); - HSSFHyperlink link = helper.createHyperlink(HyperlinkType.URL); - link.setAddress("http://poi.apache.org/"); - cell.setHyperlink(link); - cell.setCellStyle(hlink_style); - - //link to a file in the current directory - cell = sheet.createRow(1).createCell(0); - cell.setCellValue("File Link"); - link = helper.createHyperlink(HyperlinkType.FILE); - link.setAddress("link1.xls"); - cell.setHyperlink(link); - cell.setCellStyle(hlink_style); - - //e-mail link - cell = sheet.createRow(2).createCell(0); - cell.setCellValue("Email Link"); - link = helper.createHyperlink(HyperlinkType.EMAIL); - //note, if subject contains white spaces, make sure they are url-encoded - link.setAddress("mailto:poi@apache.org?subject=Hyperlinks"); - cell.setHyperlink(link); - cell.setCellStyle(hlink_style); - - //link to a place in this workbook - - //create a target sheet and cell - HSSFSheet sheet2 = wb.createSheet("Target Sheet"); - sheet2.createRow(0).createCell(0).setCellValue("Target Cell"); - - cell = sheet.createRow(3).createCell(0); - cell.setCellValue("Worksheet Link"); - link = helper.createHyperlink(HyperlinkType.DOCUMENT); - link.setAddress("'Target Sheet'!A1"); - cell.setHyperlink(link); - cell.setCellStyle(hlink_style); - - FileOutputStream out = new FileOutputStream("hssf-links.xls"); - wb.write(out); - out.close(); - wb.close(); - } -} diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/InCellLists.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/InCellLists.java deleted file mode 100644 index b25044111..000000000 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/InCellLists.java +++ /dev/null @@ -1,553 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - - -package org.apache.poi.hssf.usermodel.examples; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.ArrayList; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFCellStyle; -import org.apache.poi.hssf.usermodel.HSSFDataFormat; -import org.apache.poi.hssf.usermodel.HSSFRichTextString; - -/** - * This class contains code that demonstrates how to insert plain, numbered - * and bulleted lists into an Excel spreadsheet cell. - * - * Look at the code contained in the demonstrateMethodCalls() method. It calls - * other methods that create plain, numbered and bulleted single and - * multi-level lists. The demonstrateMethodCalls() method appears at the top - * of the class definition. - * - * Though different methods are provided to construct single and multi-level - * plain, numbered and bulleted lists, close examination will reveal that they - * are not strictly necessary. If the inputs to the listInCell() and - * multilLevelListInCell() methods are constructed to include the bullet - * character or the item numbers then these methods alone may be sufficient. - * - * @author Mark Beardsley [msb at apache.org] - */ -public class InCellLists { - - // This character looks like a solid, black, loser case letter 'o' - // positioned up from the base line of the text. - private static final char BULLET_CHARACTER = '\u2022'; - - // The tab character - \t - cannot be used to create a tab space - // within a cell as it is rendered as a square. Therefore, four - // spaces are used to simulate that character. - private static final String TAB = " "; - - /** - * Call each of the list creation methods. - * - * @param outputFilename A String that encapsulates the name of and path to - * the Excel spreadsheet file this code will create. - */ - public void demonstrateMethodCalls(String outputFilename) throws IOException { - HSSFWorkbook workbook = new HSSFWorkbook(); - try { - HSSFSheet sheet = workbook.createSheet("In Cell Lists"); - HSSFRow row = sheet.createRow(0); - - // Create a cell at A1 and insert a single, bulleted, item into - // that cell. - HSSFCell cell = row.createCell(0); - this.bulletedItemInCell(workbook, "List Item", cell); - - // Create a cell at A2 and insert a plain list - that is one - // whose items are neither bulleted or numbered - into that cell. - row = sheet.createRow(1); - cell = row.createCell(0); - ArrayList listItems = new ArrayList(); - listItems.add("List Item One."); - listItems.add("List Item Two."); - listItems.add("List Item Three."); - listItems.add("List Item Four."); - this.listInCell(workbook, listItems, cell); - // The row height and cell width are set here to ensure that the - // list may be seen. - row.setHeight((short)1100); - sheet.setColumnWidth(0, 9500); - - // Create a cell at A3 and insert a numbered list into that cell. - // Note that a couple of items have been added to the listItems - // ArrayList - row = sheet.createRow(2); - cell = row.createCell(0); - listItems.add("List Item Five."); - listItems.add("List Item Six."); - this.numberedListInCell(workbook, listItems, cell, 1, 2); - row.setHeight((short)1550); - - // Create a cell at A4 and insert a numbered list into that cell. - // Note that a couple of items have been added to the listItems - // ArrayList - row = sheet.createRow(3); - cell = row.createCell(0); - listItems.add("List Item Seven."); - listItems.add("List Item Eight."); - listItems.add("List Item Nine."); - listItems.add("List Item Ten."); - this.bulletedListInCell(workbook, listItems, cell); - row.setHeight((short)2550); - - // Insert a plain, multi-level list into cell A5. Note that - // the major difference here is that the list items are passed as - // an ArrayList of MultiLevelListItems. Note that an ArrayList - // of instances of an inner class was used here in preference to - // a Hashtable or HashMap as the ArrayList will preserve the - // ordering of the items added to it; the first item added will - // be the first item recovered and the last item added, the last - // item recovered. Alternatively, a LinkedHashMap could be used - // to preserve order. - row = sheet.createRow(4); - cell = row.createCell(0); - ArrayList multiLevelListItems = new ArrayList(); - listItems = new ArrayList(); - listItems.add("ML List Item One - Sub Item One."); - listItems.add("ML List Item One - Sub Item Two."); - listItems.add("ML List Item One - Sub Item Three."); - listItems.add("ML List Item One - Sub Item Four."); - multiLevelListItems.add(new MultiLevelListItem("List Item One.", listItems)); - // Passing either null or an empty ArrayList will signal that - // there are no lower level items associated with the top level - // item - multiLevelListItems.add(new MultiLevelListItem("List Item Two.", null)); - multiLevelListItems.add(new MultiLevelListItem("List Item Three.", null)); - listItems = new ArrayList(); - listItems.add("ML List Item Four - Sub Item One."); - listItems.add("ML List Item Four - Sub Item Two."); - listItems.add("ML List Item Four - Sub Item Three."); - multiLevelListItems.add(new MultiLevelListItem("List Item Four.", listItems)); - this.multiLevelListInCell(workbook, multiLevelListItems, cell); - row.setHeight((short)2800); - - // Insert a numbered multi-level list into cell A6. Note that the - // same ArrayList as constructed for the above plain multi-level - // list example will be re-used - row = sheet.createRow(5); - cell = row.createCell(0); - this.multiLevelNumberedListInCell(workbook, multiLevelListItems, - cell, 1, 1, 1, 2); - row.setHeight((short)2800); - - // Insert a numbered multi-level list into cell A7. Note that the - // same ArrayList as constructed for the plain multi-level list - // example will be re-used - row = sheet.createRow(6); - cell = row.createCell(0); - this.multiLevelBulletedListInCell(workbook, multiLevelListItems, cell); - row.setHeight((short)2800); - - // Save the completed workbook - FileOutputStream fos = new FileOutputStream(new File(outputFilename)); - try { - workbook.write(fos); - } finally { - fos.close(); - } - } - catch(FileNotFoundException fnfEx) { - System.out.println("Caught a: " + fnfEx.getClass().getName()); - System.out.println("Message: " + fnfEx.getMessage()); - System.out.println("Stacktrace follows..........."); - fnfEx.printStackTrace(System.out); - } - catch(IOException ioEx) { - System.out.println("Caught a: " + ioEx.getClass().getName()); - System.out.println("Message: " + ioEx.getMessage()); - System.out.println("Stacktrace follows..........."); - ioEx.printStackTrace(System.out); - } - finally { - workbook.close(); - } - } - - /** - * Inserts a single bulleted item into a cell. - * - * @param workbook A reference to the HSSFWorkbook that 'contains' the - * cell. - * @param listItem An instance of the String class encapsulating the - * items text. - * @param cell An instance of the HSSFCell class that encapsulates a - * reference to the spreadsheet cell into which the list item - * will be written. - */ - public void bulletedItemInCell(HSSFWorkbook workbook, String listItem, HSSFCell cell) { - // A format String must be built to ensure that the contents of the - // cell appear as a bulleted item. - HSSFDataFormat format = workbook.createDataFormat(); - String formatString = InCellLists.BULLET_CHARACTER + " @"; - int formatIndex = format.getFormat(formatString); - - // Construct an HSSFCellStyle and set it's data formt to use the - // object created above. - HSSFCellStyle bulletStyle = workbook.createCellStyle(); - bulletStyle.setDataFormat((short)formatIndex); - - // Set the cells contents and style. - cell.setCellValue(new HSSFRichTextString(listItem)); - cell.setCellStyle(bulletStyle); - } - - /** - * Inserts a list of plain items - that is items that are neither - * numbered or bulleted - into a single cell. - * - * @param workbook A reference to the HSSFWorkbook that 'contains' the - * cell. - * @param listItems An ArrayList whose elements encapsulate the text for - * the list's items. - * @param cell An instance of the HSSFCell class that encapsulates a - * reference to the spreadsheet cell into which the list - * will be written. - */ - public void listInCell(HSSFWorkbook workbook, ArrayList listItems, HSSFCell cell) { - StringBuilder buffer = new StringBuilder(); - HSSFCellStyle wrapStyle = workbook.createCellStyle(); - wrapStyle.setWrapText(true); - for(String listItem : listItems) { - buffer.append(listItem); - buffer.append("\n"); - } - // The StringBuffer's contents are the source for the contents - // of the cell. - cell.setCellValue(new HSSFRichTextString(buffer.toString().trim())); - cell.setCellStyle(wrapStyle); - } - - /** - * Inserts a numbered list into a single cell. - * - * @param workbook A reference to the HSSFWorkbook that 'contains' the - * cell. - * @param listItems An ArrayList whose elements encapsulate the text for - * the lists items. - * @param cell An instance of the HSSFCell class that encapsulates a - * reference to the spreadsheet cell into which the list - * will be written. - * @param startingValue A primitive int containing the number for the first - * item in the list. - * @param increment A primitive int containing the value that should be used - * to calculate subsequent item numbers. - */ - public void numberedListInCell(HSSFWorkbook workbook, - ArrayList listItems, - HSSFCell cell, - int startingValue, - int increment) { - StringBuilder buffer = new StringBuilder(); - int itemNumber = startingValue; - // Note that again, an HSSFCellStye object is required and that - // it's wrap text property should be set to 'true' - HSSFCellStyle wrapStyle = workbook.createCellStyle(); - wrapStyle.setWrapText(true); - // Note that the basic method is identical to the listInCell() method - // with one difference; a number prefixed to the items text. - for(String listItem : listItems) { - buffer.append(itemNumber).append(". "); - buffer.append(listItem); - buffer.append("\n"); - itemNumber += increment; - } - // The StringBuffer's contents are the source for the contents - // of the cell. - cell.setCellValue(new HSSFRichTextString(buffer.toString().trim())); - cell.setCellStyle(wrapStyle); - } - - /** - * Insert a bulleted list into a cell. - * - * @param workbook A reference to the HSSFWorkbook that 'contains' the - * cell. - * @param listItems An ArrayList whose elements encapsulate the text for - * the lists items. - * @param cell An instance of the HSSFCell class that encapsulates a - * reference to the spreadsheet cell into which the list - * will be written. - */ - public void bulletedListInCell(HSSFWorkbook workbook, - ArrayList listItems, - HSSFCell cell) { - StringBuilder buffer = new StringBuilder(); - // Note that again, an HSSFCellStye object is required and that - // it's wrap text property should be set to 'true' - HSSFCellStyle wrapStyle = workbook.createCellStyle(); - wrapStyle.setWrapText(true); - // Note that the basic method is identical to the listInCell() method - // with one difference; the bullet character prefixed to the items text. - for(String listItem : listItems) { - buffer.append(InCellLists.BULLET_CHARACTER + " "); - buffer.append(listItem); - buffer.append("\n"); - } - // The StringBuffer's contents are the source for the contents - // of the cell. - cell.setCellValue(new HSSFRichTextString(buffer.toString().trim())); - cell.setCellStyle(wrapStyle); - } - - /** - * Insert a multi-level list into a cell. - * - * @param workbook A reference to the HSSFWorkbook that 'contains' the - * cell. - * @param multiLevelListItems An ArrayList whose elements contain instances - * of the MultiLevelListItem class. Each element - * encapsulates the text for the high level item - * along with an ArrayList. Each element of this - * ArrayList encapsulates the text for a lower - * level item. - * @param cell An instance of the HSSFCell class that encapsulates a - * reference to the spreadsheet cell into which the list - * will be written. - */ - public void multiLevelListInCell(HSSFWorkbook workbook, - ArrayList multiLevelListItems, - HSSFCell cell) { - StringBuilder buffer = new StringBuilder(); - // Note that again, an HSSFCellStye object is required and that - // it's wrap text property should be set to 'true' - HSSFCellStyle wrapStyle = workbook.createCellStyle(); - wrapStyle.setWrapText(true); - // Step through the ArrayList of MultilLevelListItem instances. - for(MultiLevelListItem multiLevelListItem : multiLevelListItems) { - // For each element in the ArrayList, get the text for the high - // level list item...... - buffer.append(multiLevelListItem.getItemText()); - buffer.append("\n"); - // and then an ArrayList whose elements encapsulate the text - // for the lower level list items. - ArrayList lowerLevelItems = multiLevelListItem.getLowerLevelItems(); - if(!(lowerLevelItems == null) && !(lowerLevelItems.isEmpty())) { - for(String item : lowerLevelItems) { - buffer.append(InCellLists.TAB); - buffer.append(item); - buffer.append("\n"); - } - } - } - // The StringBuffer's contents are the source for the contents - // of the cell. - cell.setCellValue(new HSSFRichTextString(buffer.toString().trim())); - cell.setCellStyle(wrapStyle); - } - - /** - * Insert a multi-level list into a cell. - * - * @param workbook A reference to the HSSFWorkbook that 'contains' the - * cell. - * @param multiLevelListItems An ArrayList whose elements contain instances - * of the MultiLevelListItem class. Each element - * encapsulates the text for the high level item - * along with an ArrayList. Each element of this - * ArrayList encapsulates the text for a lower - * level item. - * @param cell An instance of the HSSFCell class that encapsulates a - * reference to the spreadsheet cell into which the list - * will be written. - * @param highLevelStartingValue A primitive int containing the number - * for the first high level item in the list. - * @param highLevelIncrement A primitive int containing the value that - * should be used to calculate the number of - * subsequent high level item. - * @param lowLevelStartingValue A primitive int will containing the number - * for the first low level item associated - * with a high level item. - * @param lowLevelIncrement A primitive int containing the value that - * should be used to calculate the number of - * subsequent low level item. - */ - public void multiLevelNumberedListInCell(HSSFWorkbook workbook, - ArrayList multiLevelListItems, - HSSFCell cell, - int highLevelStartingValue, - int highLevelIncrement, - int lowLevelStartingValue, - int lowLevelIncrement) { - StringBuilder buffer = new StringBuilder(); - int highLevelItemNumber = highLevelStartingValue; - // Note that again, an HSSFCellStye object is required and that - // it's wrap text property should be set to 'true' - HSSFCellStyle wrapStyle = workbook.createCellStyle(); - wrapStyle.setWrapText(true); - // Step through the ArrayList of MultilLevelListItem instances. - for(MultiLevelListItem multiLevelListItem : multiLevelListItems) { - // For each element in the ArrayList, get the text for the high - // level list item...... - buffer.append(highLevelItemNumber); - buffer.append(". "); - buffer.append(multiLevelListItem.getItemText()); - buffer.append("\n"); - // and then an ArrayList whose elements encapsulate the text - // for the lower level list items. - ArrayList lowerLevelItems = multiLevelListItem.getLowerLevelItems(); - if(!(lowerLevelItems == null) && !(lowerLevelItems.isEmpty())) { - int lowLevelItemNumber = lowLevelStartingValue; - for(String item : lowerLevelItems) { - buffer.append(InCellLists.TAB); - buffer.append(highLevelItemNumber); - buffer.append("."); - buffer.append(lowLevelItemNumber); - buffer.append(" "); - buffer.append(item); - buffer.append("\n"); - lowLevelItemNumber += lowLevelIncrement; - } - } - highLevelItemNumber += highLevelIncrement; - } - // The StringBuffer's contents are the source for the contents - // of the cell. - cell.setCellValue(new HSSFRichTextString(buffer.toString().trim())); - cell.setCellStyle(wrapStyle); - } - - /** - * Insert a bulleted multi-level list into a cell. - * - * @param workbook A reference to the HSSFWorkbook that 'contains' the - * cell. - * @param multiLevelListItems An ArrayList whose elements contain instances - * of the MultiLevelListItem class. Each element - * encapsulates the text for the high level item - * along with an ArrayList. Each element of this - * ArrayList encapsulates the text for a lower - * level item. - * @param cell An instance of the HSSFCell class that encapsulates a - * reference to the spreadsheet cell into which the list - * will be written. - */ - public void multiLevelBulletedListInCell(HSSFWorkbook workbook, - ArrayList multiLevelListItems, - HSSFCell cell) { - StringBuilder buffer = new StringBuilder(); - // Note that again, an HSSFCellStye object is required and that - // it's wrap text property should be set to 'true' - HSSFCellStyle wrapStyle = workbook.createCellStyle(); - wrapStyle.setWrapText(true); - // Step through the ArrayList of MultilLevelListItem instances. - for(MultiLevelListItem multiLevelListItem : multiLevelListItems) { - // For each element in the ArrayList, get the text for the high - // level list item...... - buffer.append(InCellLists.BULLET_CHARACTER); - buffer.append(" "); - buffer.append(multiLevelListItem.getItemText()); - buffer.append("\n"); - // and then an ArrayList whose elements encapsulate the text - // for the lower level list items. - ArrayList lowerLevelItems = multiLevelListItem.getLowerLevelItems(); - if(!(lowerLevelItems == null) && !(lowerLevelItems.isEmpty())) { - for(String item : lowerLevelItems) { - buffer.append(InCellLists.TAB); - buffer.append(InCellLists.BULLET_CHARACTER); - buffer.append(" "); - buffer.append(item); - buffer.append("\n"); - } - } - } - // The StringBuffer's contents are the source for the contents - // of the cell. - cell.setCellValue(new HSSFRichTextString(buffer.toString().trim())); - cell.setCellStyle(wrapStyle); - } - - /** - * The main entry point to the program. Demonstrates how to call the method - * that will create an Excel workbook containing many different sorts of - * lists. - * - * @param args the command line arguments. - */ - public static void main(String[] args) throws IOException { - new InCellLists().demonstrateMethodCalls("Latest In Cell List.xls"); - } - - /** - * An instance of this inner class models an item or element in a - * multi-level list. Each multi-level list item consists of the text for the - * high level items and an ArrayList containing the text for each of the - * associated lower level items. When written into a cell, each multi-level - * list item will have this general appearance. - * - * Item One - * Sub Item One. - * Sub Item Two. - * Item Two - * Sub Item One. - * Sub Item Two. - * etc. - * - * It would be quite possible to modify this class to model much more - * complex list structures descending through two, three or even more - * levels. - */ - public final class MultiLevelListItem { - - private String itemText = null; - private ArrayList lowerLevelItems = null; - - /** - * Create a new instance of the MultiLevelListItem class using the - * following parameters. - * - * @param itemText A String that encapsulates the text for the high - * level list item. - * @param lowerLevelItems An ArrayList whose elements encapsulate the - * text for the associated lower level list - * items. - */ - public MultiLevelListItem(String itemText, ArrayList lowerLevelItems) { - this.itemText = itemText; - this.lowerLevelItems = lowerLevelItems; - } - - /** - * Get the text for the high level list item. - * - * @return A String that encapsulates the text for the high level list - * item. - */ - public String getItemText() { - return(this.itemText); - } - - /** - * Get the text for the associated lower level list items. - * - * @return An ArrayList whose elements each encapsulate the text for a - * single associated lower level list item. - */ - public ArrayList getLowerLevelItems() { - return(this.lowerLevelItems); - } - } -} diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/MergedCells.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/MergedCells.java deleted file mode 100644 index 09d08dd25..000000000 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/MergedCells.java +++ /dev/null @@ -1,49 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel.examples; - -import java.io.FileOutputStream; -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.util.CellRangeAddress; - -/** - * An example of how to merge regions of cells. - */ -public class MergedCells { - public static void main(String[] args) throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("new sheet"); - - HSSFRow row = sheet.createRow(1); - HSSFCell cell = row.createCell(1); - cell.setCellValue("This is a test of merging"); - - sheet.addMergedRegion(new CellRangeAddress(1, 1, 1, 2)); - - // Write the output to a file - FileOutputStream fileOut = new FileOutputStream("workbook.xls"); - wb.write(fileOut); - fileOut.close(); - wb.close(); - } -} diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/NewLinesInCells.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/NewLinesInCells.java deleted file mode 100644 index 00f60c4da..000000000 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/NewLinesInCells.java +++ /dev/null @@ -1,63 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel.examples; - -import java.io.FileOutputStream; -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFCellStyle; -import org.apache.poi.hssf.usermodel.HSSFFont; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.CellType; - -/** - * Demonstrates how to use newlines in cells. - */ -public class NewLinesInCells { - public static void main( String[] args ) throws IOException { - - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet s = wb.createSheet(); - HSSFRow r = null; - HSSFCell c = null; - HSSFCellStyle cs = wb.createCellStyle(); - HSSFFont f2 = wb.createFont(); - - cs = wb.createCellStyle(); - - cs.setFont(f2); - // Word Wrap MUST be turned on - cs.setWrapText(true); - - r = s.createRow(2); - r.setHeight((short) 0x349); - c = r.createCell(2); - c.setCellType(CellType.STRING); - c.setCellValue("Use \n with word wrap on to create a new line"); - c.setCellStyle(cs); - s.setColumnWidth(2, (int) ((50 * 8) / ((double) 1 / 20))); - - FileOutputStream fileOut = new FileOutputStream("workbook.xls"); - wb.write(fileOut); - fileOut.close(); - wb.close(); - } -} diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/NewSheet.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/NewSheet.java deleted file mode 100644 index 495543e49..000000000 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/NewSheet.java +++ /dev/null @@ -1,43 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel.examples; - -import java.io.FileOutputStream; -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.util.WorkbookUtil; - -/** - * Creates a new workbook with a sheet that's been explicitly defined. - */ -public abstract class NewSheet { - public static void main(String[] args) throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - wb.createSheet("new sheet"); - // create with default name - wb.createSheet(); - final String name = "second sheet"; - // setting sheet name later - wb.setSheetName(1, WorkbookUtil.createSafeSheetName(name)); - FileOutputStream fileOut = new FileOutputStream("workbook.xls"); - wb.write(fileOut); - fileOut.close(); - wb.close(); - } -} diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/NewWorkbook.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/NewWorkbook.java deleted file mode 100644 index e6e0e4137..000000000 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/NewWorkbook.java +++ /dev/null @@ -1,38 +0,0 @@ - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - - -package org.apache.poi.hssf.usermodel.examples; - -import java.io.FileOutputStream; -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; - -/** - * This example creates a new blank workbook. This workbook will contain a single blank sheet. - */ -public class NewWorkbook { - public static void main(String[] args) throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - FileOutputStream fileOut = new FileOutputStream("workbook.xls"); - wb.write(fileOut); - fileOut.close(); - wb.close(); - } -} diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/OfficeDrawing.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/OfficeDrawing.java deleted file mode 100644 index 68aafbc7c..000000000 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/OfficeDrawing.java +++ /dev/null @@ -1,322 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel.examples; - -import org.apache.poi.hssf.usermodel.*; -import org.apache.poi.ss.usermodel.ClientAnchor.AnchorType; - -import java.io.*; - -/** - * Demonstrates how to use the office drawing capabilities of POI. - * - * @author Glen Stampoultzis (glens at apache.org) - */ -public class OfficeDrawing { - public static void main(String[] args) throws IOException { - // Create the workbook and sheets. - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet1 = wb.createSheet("new sheet"); - HSSFSheet sheet2 = wb.createSheet("second sheet"); - HSSFSheet sheet3 = wb.createSheet("third sheet"); - HSSFSheet sheet4 = wb.createSheet("fourth sheet"); - HSSFSheet sheet5 = wb.createSheet("fifth sheet"); - - // Draw stuff in them - drawSheet1( sheet1 ); - drawSheet2( sheet2 ); - drawSheet3( sheet3 ); - drawSheet4( sheet4, wb ); - drawSheet5( sheet5, wb ); - - // Write the file out. - FileOutputStream fileOut = new FileOutputStream("workbook.xls"); - wb.write(fileOut); - fileOut.close(); - } - - private static void drawSheet1( HSSFSheet sheet1 ) - { - // Create a row and size one of the cells reasonably large. - HSSFRow row = sheet1.createRow(2); - row.setHeight((short) 2800); - row.createCell(1); - sheet1.setColumnWidth(2, 9000); - - // Create the drawing patriarch. This is the top level container for - // all shapes. - HSSFPatriarch patriarch = sheet1.createDrawingPatriarch(); - - // Draw some lines and an oval. - drawLinesToCenter( patriarch ); - drawManyLines( patriarch ); - drawOval( patriarch ); - drawPolygon( patriarch ); - - // Draw a rectangle. - HSSFSimpleShape rect = patriarch.createSimpleShape( new HSSFClientAnchor(100, 100, 900, 200, (short)0, 0, (short)0, 0) ); - rect.setShapeType(HSSFSimpleShape.OBJECT_TYPE_RECTANGLE); - } - - private static void drawSheet2( HSSFSheet sheet2 ) - { - // Create a row and size one of the cells reasonably large. - HSSFRow row = sheet2.createRow(2); - row.createCell(1); - row.setHeightInPoints(240); - sheet2.setColumnWidth(2, 9000); - - // Create the drawing patriarch. This is the top level container for - // all shapes. This will clear out any existing shapes for that sheet. - HSSFPatriarch patriarch = sheet2.createDrawingPatriarch(); - - // Draw a grid in one of the cells. - drawGrid( patriarch ); - } - - private static void drawSheet3( HSSFSheet sheet3 ) - { - // Create a row and size one of the cells reasonably large - HSSFRow row = sheet3.createRow(2); - row.setHeightInPoints(140); - row.createCell(1); - sheet3.setColumnWidth(2, 9000); - - // Create the drawing patriarch. This is the top level container for - // all shapes. This will clear out any existing shapes for that sheet. - HSSFPatriarch patriarch = sheet3.createDrawingPatriarch(); - - // Create a shape group. - HSSFShapeGroup group = patriarch.createGroup( - new HSSFClientAnchor(0,0,900,200,(short)2,2,(short)2,2)); - - // Create a couple of lines in the group. - HSSFSimpleShape shape1 = group.createShape(new HSSFChildAnchor(3,3,500,500)); - shape1.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE); - ( (HSSFChildAnchor) shape1.getAnchor() ).setAnchor((short)3,3,500,500); - HSSFSimpleShape shape2 = group.createShape(new HSSFChildAnchor((short)1,200,400,600)); - shape2.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE); - - } - - private static void drawSheet4( HSSFSheet sheet4, HSSFWorkbook wb ) - { - // Create the drawing patriarch. This is the top level container for - // all shapes. This will clear out any existing shapes for that sheet. - HSSFPatriarch patriarch = sheet4.createDrawingPatriarch(); - - // Create a couple of textboxes - HSSFTextbox textbox1 = patriarch.createTextbox( - new HSSFClientAnchor(0,0,0,0,(short)1,1,(short)2,2)); - textbox1.setString(new HSSFRichTextString("This is a test") ); - HSSFTextbox textbox2 = patriarch.createTextbox( - new HSSFClientAnchor(0,0,900,100,(short)3,3,(short)3,4)); - textbox2.setString(new HSSFRichTextString("Woo") ); - textbox2.setFillColor(200,0,0); - textbox2.setLineStyle(HSSFSimpleShape.LINESTYLE_DOTGEL); - - // Create third one with some fancy font styling. - HSSFTextbox textbox3 = patriarch.createTextbox( - new HSSFClientAnchor(0,0,900,100,(short)4,4,(short)5,4+1)); - HSSFFont font = wb.createFont(); - font.setItalic(true); - font.setUnderline(HSSFFont.U_DOUBLE); - HSSFRichTextString string = new HSSFRichTextString("Woo!!!"); - string.applyFont(2,5,font); - textbox3.setString(string ); - textbox3.setFillColor(0x08000030); - textbox3.setLineStyle(HSSFSimpleShape.LINESTYLE_NONE); // no line around the textbox. - textbox3.setNoFill(true); // make it transparent - } - - private static void drawSheet5( HSSFSheet sheet5, HSSFWorkbook wb ) throws IOException - { - - // Create the drawing patriarch. This is the top level container for - // all shapes. This will clear out any existing shapes for that sheet. - HSSFPatriarch patriarch = sheet5.createDrawingPatriarch(); - - HSSFClientAnchor anchor; - anchor = new HSSFClientAnchor(0,0,0,255,(short)2,2,(short)4,7); - anchor.setAnchorType( AnchorType.MOVE_DONT_RESIZE ); - patriarch.createPicture(anchor, loadPicture( "src/resources/logos/logoKarmokar4.png", wb )); - - anchor = new HSSFClientAnchor(0,0,0,255,(short)4,2,(short)5,7); - anchor.setAnchorType( AnchorType.MOVE_DONT_RESIZE ); - patriarch.createPicture(anchor, loadPicture( "src/resources/logos/logoKarmokar4edited.png", wb )); - - anchor = new HSSFClientAnchor(0,0,1023,255,(short)6,2,(short)8,7); - anchor.setAnchorType( AnchorType.MOVE_DONT_RESIZE ); - HSSFPicture picture = patriarch.createPicture(anchor, loadPicture( "src/resources/logos/logoKarmokar4s.png", wb )); - //Reset the image to the original size. - picture.resize(); - picture.setLineStyle( HSSFShape.LINESTYLE_DASHDOTGEL ); - - } - - private static int loadPicture( String path, HSSFWorkbook wb ) throws IOException - { - int pictureIndex; - FileInputStream fis = null; - ByteArrayOutputStream bos = null; - try - { - fis = new FileInputStream( path); - bos = new ByteArrayOutputStream( ); - int c; - while ( (c = fis.read()) != -1) - bos.write( c ); - pictureIndex = wb.addPicture( bos.toByteArray(), HSSFWorkbook.PICTURE_TYPE_PNG ); - } - finally - { - if (fis != null) - fis.close(); - if (bos != null) - bos.close(); - } - return pictureIndex; - } - - private static void drawOval( HSSFPatriarch patriarch ) - { - // Create an oval and style to taste. - HSSFClientAnchor a = new HSSFClientAnchor(); - a.setAnchor((short)2, 2, 20, 20, (short) 2, 2, 190, 80); - HSSFSimpleShape s = patriarch.createSimpleShape(a); - s.setShapeType(HSSFSimpleShape.OBJECT_TYPE_OVAL); - s.setLineStyleColor(10,10,10); - s.setFillColor(90,10,200); - s.setLineWidth(HSSFShape.LINEWIDTH_ONE_PT * 3); - s.setLineStyle(HSSFShape.LINESTYLE_DOTSYS); - } - - private static void drawPolygon( HSSFPatriarch patriarch ) - { - // HSSFClientAnchor a = new HSSFClientAnchor( 0, 0, 1023, 255, (short) 2, 2, (short) 3, 3 ); - // HSSFPolygon p = patriarch.createPolygon(a); - // p.setPolygonDrawArea(100,100); - // p.setPoints( new int[]{30, 90, 50}, new int[]{88, 5, 44} ); - - - HSSFClientAnchor a = new HSSFClientAnchor(); - a.setAnchor( (short) 2, 2, 0, 0, (short) 3, 3, 1023, 255 ); - HSSFShapeGroup g = patriarch.createGroup( a ); - g.setCoordinates(0,0,200,200); - HSSFPolygon p1 = g.createPolygon( new HSSFChildAnchor( 0, 0, 200, 200 ) ); - p1.setPolygonDrawArea( 100, 100 ); - p1.setPoints( new int[]{0, 90, 50}, new int[]{5, 5, 44} ); - p1.setFillColor( 0, 255, 0 ); - HSSFPolygon p2 = g.createPolygon( new HSSFChildAnchor( 20, 20, 200, 200 ) ); - p2.setPolygonDrawArea( 200, 200 ); - p2.setPoints( new int[]{120, 20, 150}, new int[]{105, 30, 195} ); - p2.setFillColor( 255, 0, 0 ); - } - - private static void drawManyLines( HSSFPatriarch patriarch ) - { - // Draw bunch of lines - int x1 = 100; - int y1 = 100; - int x2 = 800; - int y2 = 200; - int color = 0; - for (int i = 0; i < 10; i++) - { - HSSFClientAnchor a2 = new HSSFClientAnchor(); - a2.setAnchor((short) 2, 2, x1, y1, (short) 2, 2, x2, y2); - HSSFSimpleShape shape2 = patriarch.createSimpleShape(a2); - shape2.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE); - shape2.setLineStyleColor(color); - y1 -= 10; - y2 -= 10; - color += 30; - } - } - - private static void drawGrid( HSSFPatriarch patriarch ) - { - // This draws a grid of lines. Since the coordinates space fixed at - // 1024 by 256 we use a ratio to get a reasonably square grids. - - double xRatio = 3.22; - double yRatio = 0.6711; - - int x1 = 000; - int y1 = 000; - int x2 = 000; - int y2 = 200; - for (int i = 0; i < 20; i++) - { - HSSFClientAnchor a2 = new HSSFClientAnchor(); - a2.setAnchor((short) 2, 2, (int) ( x1 * xRatio ), (int) ( y1 * yRatio ), - (short) 2, 2, (int) ( x2 * xRatio ), (int) ( y2 * yRatio )); - HSSFSimpleShape shape2 = patriarch.createSimpleShape(a2); - shape2.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE); - - x1 += 10; - x2 += 10; - } - - x1 = 000; - y1 = 000; - x2 = 200; - y2 = 000; - for (int i = 0; i < 20; i++) - { - HSSFClientAnchor a2 = new HSSFClientAnchor(); - a2.setAnchor((short) 2, 2, (int) ( x1 * xRatio ), (int) ( y1 * yRatio ), - (short) 2, 2, (int) ( x2 * xRatio ), (int) ( y2 * yRatio )); - HSSFSimpleShape shape2 = patriarch.createSimpleShape(a2); - shape2.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE); - - y1 += 10; - y2 += 10; - } - } - - private static void drawLinesToCenter( HSSFPatriarch patriarch ) - { - // Draw some lines from and to the corners - { - HSSFClientAnchor a1 = new HSSFClientAnchor(); - a1.setAnchor( (short)2, 2, 0, 0, (short) 2, 2, 512, 128); - HSSFSimpleShape shape1 = patriarch.createSimpleShape(a1); - shape1.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE); - } - { - HSSFClientAnchor a1 = new HSSFClientAnchor(); - a1.setAnchor( (short)2, 2, 512, 128, (short) 2, 2, 1024, 0); - HSSFSimpleShape shape1 = patriarch.createSimpleShape(a1); - shape1.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE); - } - { - HSSFClientAnchor a1 = new HSSFClientAnchor(); - a1.setAnchor( (short)1, 1, 0, 0, (short) 1, 1, 512, 100); - HSSFSimpleShape shape1 = patriarch.createSimpleShape(a1); - shape1.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE); - } - { - HSSFClientAnchor a1 = new HSSFClientAnchor(); - a1.setAnchor( (short)1, 1, 512, 100, (short) 1, 1, 1024, 0); - HSSFSimpleShape shape1 = patriarch.createSimpleShape(a1); - shape1.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE); - } - - } -} diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/OfficeDrawingWithGraphics.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/OfficeDrawingWithGraphics.java deleted file mode 100644 index 301d7ed78..000000000 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/OfficeDrawingWithGraphics.java +++ /dev/null @@ -1,103 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel.examples; - -import org.apache.poi.hssf.usermodel.*; - -import java.awt.*; -import java.io.FileOutputStream; -import java.io.IOException; - -/** - * Demonstrates the use of the EscherGraphics2d library. - * - * @author Glen Stampoultzis (glens at apache.org) - */ -public class OfficeDrawingWithGraphics { - public static void main( String[] args ) throws IOException { - // Create a workbook with one sheet and size the first three somewhat - // larger so we can fit the chemical structure diagram in. - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet( "my drawing" ); - sheet.setColumnWidth(1, 256 * 27); - HSSFRow row1 = sheet.createRow(0); - row1.setHeightInPoints(10 * 15f); - HSSFRow row2 = sheet.createRow(1); - row2.setHeightInPoints(5 * 15f); - HSSFRow row3 = sheet.createRow(2); - row3.setHeightInPoints(10 * 15f); - - // Add some cells so we can test that the anchoring works when we - // sort them. - row1.createCell(0).setCellValue("C"); - row2.createCell(0).setCellValue("A"); - row3.createCell(0).setCellValue("B"); - - // Create the top level drawing patriarch. - HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); - - HSSFClientAnchor a; - HSSFShapeGroup group; - EscherGraphics g; - EscherGraphics2d g2d; - // Anchor entirely within one cell. - a = new HSSFClientAnchor( 0, 0, 1023, 255, (short) 1, 0, (short) 1, 0 ); - group = patriarch.createGroup( a ); - group.setCoordinates( 0, 0, 320, 276 ); - float verticalPointsPerPixel = a.getAnchorHeightInPoints(sheet) / Math.abs(group.getY2() - group.getY1()); - g = new EscherGraphics( group, wb, Color.black, verticalPointsPerPixel ); - g2d = new EscherGraphics2d( g ); - drawStar( g2d ); - - a = new HSSFClientAnchor( 0, 0, 1023, 255, (short) 1, 1, (short) 1, 1 ); - group = patriarch.createGroup( a ); - group.setCoordinates( 0, 0, 640, 276 ); - verticalPointsPerPixel = a.getAnchorHeightInPoints(sheet) / Math.abs(group.getY2() - group.getY1()); -// verticalPixelsPerPoint = (float)Math.abs(group.getY2() - group.getY1()) / a.getAnchorHeightInPoints(sheet); - g = new EscherGraphics( group, wb, Color.black, verticalPointsPerPixel ); - g2d = new EscherGraphics2d( g ); - drawStar( g2d ); - - FileOutputStream out = new FileOutputStream("workbook.xls"); - wb.write(out); - out.close(); - - } - - private static void drawStar( EscherGraphics2d g2d ) - { - g2d.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON ); - for (double i = 0; i < Math.PI; i += 0.1) - { - g2d.setColor( new Color((int)(i * 5343062d) ) ); - int x1 = (int) ( Math.cos(i) * 160.0 ) + 160; - int y1 = (int) ( Math.sin(i) * 138.0 ) + 138; - int x2 = (int) ( -Math.cos(i) * 160.0 ) + 160; - int y2 = (int) ( -Math.sin(i) * 138.0 ) + 138; - g2d.setStroke(new BasicStroke(2)); - g2d.drawLine(x1,y1,x2,y2); - } - g2d.setFont(new Font("SansSerif",Font.BOLD | Font.ITALIC, 20)); - g2d.drawString("EscherGraphics2d",70,100); - g2d.setColor(Color.yellow); - g2d.fillOval( 160-20,138-20,40,40); - g2d.setColor(Color.black); - g2d.fillPolygon(new int[] {-10+160,0+160,10+160,0+160}, new int[] {0+138,10+138,0+138,-10+138}, 4); - g2d.drawPolygon(new int[] {-160+160,0+160,160+160,0+160}, new int[] {0+138,138+138,0+138,-138+138}, 4); - } -} diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/Outlines.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/Outlines.java deleted file mode 100644 index ad93f5e71..000000000 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/Outlines.java +++ /dev/null @@ -1,187 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel.examples; - -import java.io.Closeable; -import java.io.FileOutputStream; -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; - -/** - * Creates outlines. - */ -public class Outlines implements Closeable { - public static void main(String[] args) - throws IOException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { - POILogger LOGGER = POILogFactory.getLogger(Outlines.class); - for (int i=1; i<=13; i++) { - Outlines o = new Outlines(); - try { - String log = (String)Outlines.class.getDeclaredMethod("test"+i).invoke(o); - String filename = "outline"+i+".xls"; - o.writeOut(filename); - LOGGER.log(POILogger.INFO, filename+" written. "+log); - } finally { - o.close(); - } - } - } - - private final HSSFWorkbook wb = new HSSFWorkbook(); - private final HSSFSheet sheet1 = wb.createSheet("new sheet"); - - public void writeOut(String filename) throws IOException { - FileOutputStream fileOut = new FileOutputStream(filename); - try { - wb.write(fileOut); - } finally { - fileOut.close(); - } - } - - @Override - public void close() throws IOException { - wb.close(); - } - - public String test1() { - sheet1.groupColumn(4, 7); - - for (int row = 0; row < 200; row++) { - HSSFRow r = sheet1.createRow(row); - for (int column = 0; column < 200; column++) { - HSSFCell c = r.createCell(column); - c.setCellValue(column); - } - } - return "Two expanded groups."; - } - - public String test2() { - sheet1.groupColumn(2, 10); - sheet1.groupColumn(4, 7); - sheet1.setColumnGroupCollapsed(4, true); - return "Two groups. Inner group collapsed."; - } - - public String test3() { - sheet1.groupColumn(2, 10); - sheet1.groupColumn(4, 7); - sheet1.setColumnGroupCollapsed(4, true); - sheet1.setColumnGroupCollapsed(2, true); - return "Two groups. Both collapsed."; - } - - public String test4() { - sheet1.groupColumn(2, 10); - sheet1.groupColumn(4, 7); - sheet1.setColumnGroupCollapsed(4, true); - sheet1.setColumnGroupCollapsed(2, true); - - sheet1.setColumnGroupCollapsed(4, false); - return "Two groups. Collapsed then inner group expanded."; - } - - public String test5() { - sheet1.groupColumn(2, 10); - sheet1.groupColumn(4, 7); - sheet1.setColumnGroupCollapsed(4, true); - sheet1.setColumnGroupCollapsed(2, true); - - sheet1.setColumnGroupCollapsed(4, false); - sheet1.setColumnGroupCollapsed(3, false); - return "Two groups. Collapsed then reexpanded."; - } - - public String test6() { - sheet1.groupColumn(2, 10); - sheet1.groupColumn(4, 10); - sheet1.setColumnGroupCollapsed(4, true); - sheet1.setColumnGroupCollapsed(2, true); - - sheet1.setColumnGroupCollapsed(3, false); - return "Two groups with matching end points. Second group collapsed."; - } - - public String test7() { - sheet1.groupRow(5, 14); - sheet1.groupRow(7, 10); - return "Row outlines."; - } - - public String test8() { - sheet1.groupRow(5, 14); - sheet1.groupRow(7, 10); - sheet1.setRowGroupCollapsed(7, true); - return "Row outlines. Inner group collapsed."; - } - - public String test9() { - sheet1.groupRow(5, 14); - sheet1.groupRow(7, 10); - sheet1.setRowGroupCollapsed(7, true); - sheet1.setRowGroupCollapsed(5, true); - return "Row outlines. Both collapsed."; - } - - public String test10() { - sheet1.groupRow(5, 14); - sheet1.groupRow(7, 10); - sheet1.setRowGroupCollapsed(7, true); - sheet1.setRowGroupCollapsed(5, true); - sheet1.setRowGroupCollapsed(8, false); - return "Row outlines. Collapsed then inner group expanded."; - } - - public String test11() { - sheet1.groupRow(5, 14); - sheet1.groupRow(7, 10); - sheet1.setRowGroupCollapsed(7, true); - sheet1.setRowGroupCollapsed(5, true); - sheet1.setRowGroupCollapsed(8, false); - sheet1.setRowGroupCollapsed(14, false); - return "Row outlines. Collapsed then expanded."; - } - - public String test12() { - sheet1.groupRow(5, 14); - sheet1.groupRow(7, 14); - sheet1.setRowGroupCollapsed(7, true); - sheet1.setRowGroupCollapsed(5, true); - sheet1.setRowGroupCollapsed(6, false); - return "Row outlines. Two row groups with matching end points. Second group collapsed."; - } - - public String test13() { - sheet1.groupRow(5, 14); - sheet1.groupRow(7, 14); - sheet1.groupRow(16, 19); - - sheet1.groupColumn(4, 7); - sheet1.groupColumn(9, 12); - sheet1.groupColumn(10, 11); - return "Mixed bag."; - } -} diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/ReadWriteWorkbook.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/ReadWriteWorkbook.java deleted file mode 100644 index 2b3553f76..000000000 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/ReadWriteWorkbook.java +++ /dev/null @@ -1,67 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel.examples; - -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.ss.usermodel.CellType; - -/** - * This example demonstrates opening a workbook, modifying it and writing - * the results back out. - * - * @author Glen Stampoultzis (glens at apache.org) - */ -public class ReadWriteWorkbook { - public static void main(String[] args) throws IOException { - FileInputStream fileIn = null; - FileOutputStream fileOut = null; - - try - { - fileIn = new FileInputStream("workbook.xls"); - POIFSFileSystem fs = new POIFSFileSystem(fileIn); - HSSFWorkbook wb = new HSSFWorkbook(fs); - HSSFSheet sheet = wb.getSheetAt(0); - HSSFRow row = sheet.getRow(2); - if (row == null) - row = sheet.createRow(2); - HSSFCell cell = row.getCell(3); - if (cell == null) - cell = row.createCell(3); - cell.setCellType(CellType.STRING); - cell.setCellValue("a test"); - - // Write the output to a file - fileOut = new FileOutputStream("workbookout.xls"); - wb.write(fileOut); - } finally { - if (fileOut != null) - fileOut.close(); - if (fileIn != null) - fileIn.close(); - } - } -} diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/RepeatingRowsAndColumns.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/RepeatingRowsAndColumns.java deleted file mode 100644 index 6ceee7c26..000000000 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/RepeatingRowsAndColumns.java +++ /dev/null @@ -1,64 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel.examples; - -import java.io.FileOutputStream; -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFCellStyle; -import org.apache.poi.hssf.usermodel.HSSFFont; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.util.CellRangeAddress; - -public class RepeatingRowsAndColumns { - public static void main(String[] args) throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet1 = wb.createSheet("first sheet"); - HSSFSheet sheet2 = wb.createSheet("second sheet"); - HSSFSheet sheet3 = wb.createSheet("third sheet"); - - HSSFFont boldFont = wb.createFont(); - boldFont.setFontHeightInPoints((short)22); - boldFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); - - HSSFCellStyle boldStyle = wb.createCellStyle(); - boldStyle.setFont(boldFont); - - HSSFRow row = sheet1.createRow(1); - HSSFCell cell = row.createCell(0); - cell.setCellValue("This quick brown fox"); - cell.setCellStyle(boldStyle); - - // Set the columns to repeat from column 0 to 2 on the first sheet - sheet1.setRepeatingColumns(CellRangeAddress.valueOf("A:C")); - // Set the rows to repeat from row 0 to 2 on the second sheet. - sheet2.setRepeatingRows(CellRangeAddress.valueOf("1:3")); - // Set the the repeating rows and columns on the third sheet. - CellRangeAddress cra = CellRangeAddress.valueOf("D1:E2"); - sheet3.setRepeatingColumns(cra); - sheet3.setRepeatingRows(cra); - - FileOutputStream fileOut = new FileOutputStream("workbook.xls"); - wb.write(fileOut); - fileOut.close(); - wb.close(); - } -} diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/SplitAndFreezePanes.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/SplitAndFreezePanes.java deleted file mode 100644 index 85cba2eb9..000000000 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/SplitAndFreezePanes.java +++ /dev/null @@ -1,51 +0,0 @@ - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - - -package org.apache.poi.hssf.usermodel.examples; - -import java.io.FileOutputStream; -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.Sheet; - -public class SplitAndFreezePanes { - public static void main(String[] args) throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet1 = wb.createSheet("new sheet"); - HSSFSheet sheet2 = wb.createSheet("second sheet"); - HSSFSheet sheet3 = wb.createSheet("third sheet"); - HSSFSheet sheet4 = wb.createSheet("fourth sheet"); - - // Freeze just one row - sheet1.createFreezePane( 0, 1, 0, 1 ); - // Freeze just one column - sheet2.createFreezePane( 1, 0, 1, 0 ); - // Freeze the columns and rows (forget about scrolling position of the lower right quadrant). - sheet3.createFreezePane( 2, 2 ); - // Create a split with the lower left side being the active quadrant - sheet4.createSplitPane( 2000, 2000, 0, 0, Sheet.PANE_LOWER_LEFT ); - - FileOutputStream fileOut = new FileOutputStream("workbook.xls"); - wb.write(fileOut); - fileOut.close(); - wb.close(); - } -} diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/WorkingWithFonts.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/WorkingWithFonts.java deleted file mode 100644 index d3c674a75..000000000 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/WorkingWithFonts.java +++ /dev/null @@ -1,63 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel.examples; - -import java.io.FileOutputStream; -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFCellStyle; -import org.apache.poi.hssf.usermodel.HSSFFont; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; - -/** - * Demonstrates how to create and use fonts. - */ -public class WorkingWithFonts { - public static void main(String[] args) throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("new sheet"); - - // Create a row and put some cells in it. Rows are 0 based. - HSSFRow row = sheet.createRow(1); - - // Create a new font and alter it. - HSSFFont font = wb.createFont(); - font.setFontHeightInPoints((short)24); - font.setFontName("Courier New"); - font.setItalic(true); - font.setStrikeout(true); - - // Fonts are set into a style so create a new one to use. - HSSFCellStyle style = wb.createCellStyle(); - style.setFont(font); - - // Create a cell and put a value in it. - HSSFCell cell = row.createCell(1); - cell.setCellValue("This is a test of fonts"); - cell.setCellStyle(style); - - // Write the output to a file - FileOutputStream fileOut = new FileOutputStream("workbook.xls"); - wb.write(fileOut); - fileOut.close(); - wb.close(); - } -} diff --git a/src/examples/src/org/apache/poi/hssf/usermodel/examples/ZoomSheet.java b/src/examples/src/org/apache/poi/hssf/usermodel/examples/ZoomSheet.java deleted file mode 100644 index f83b5900e..000000000 --- a/src/examples/src/org/apache/poi/hssf/usermodel/examples/ZoomSheet.java +++ /dev/null @@ -1,46 +0,0 @@ - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - - -package org.apache.poi.hssf.usermodel.examples; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.hssf.usermodel.HSSFSheet; - -import java.io.IOException; -import java.io.FileOutputStream; - -/** - * Sets the zoom magnication for a sheet. - * - * @author Glen Stampoultzis (glens at apache.org) - */ -public class ZoomSheet -{ - public static void main(String[] args) - throws IOException - { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet1 = wb.createSheet("new sheet"); - sheet1.setZoom(75); // 75 percent magnification - FileOutputStream fileOut = new FileOutputStream("workbook.xls"); - wb.write(fileOut); - fileOut.close(); - wb.close(); - } -} diff --git a/src/examples/src/org/apache/poi/hssf/view/SVBorder.java b/src/examples/src/org/apache/poi/hssf/view/SVBorder.java deleted file mode 100644 index 273ed07fd..000000000 --- a/src/examples/src/org/apache/poi/hssf/view/SVBorder.java +++ /dev/null @@ -1,553 +0,0 @@ - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.view; - -import java.awt.*; - -import javax.swing.border.AbstractBorder; - -import org.apache.poi.ss.usermodel.BorderStyle; - -/** - * This is an attempt to implement Excel style borders for the SheetViewer. - * Mostly just overrides stuff so the javadoc won't appear here but will - * appear in the generated stuff. - * - * @author Andrew C. Oliver (acoliver at apache dot org) - * @author Jason Height - */ -public class SVBorder extends AbstractBorder { - private Color northColor = null; - private Color eastColor = null; - private Color southColor = null; - private Color westColor = null; - private BorderStyle northBorderType = BorderStyle.NONE; - private BorderStyle eastBorderType = BorderStyle.NONE; - private BorderStyle southBorderType = BorderStyle.NONE; - private BorderStyle westBorderType = BorderStyle.NONE; - private boolean northBorder=false; - private boolean eastBorder=false; - private boolean southBorder=false; - private boolean westBorder=false; - private boolean selected = false; - - public void setBorder(Color northColor, Color eastColor, - Color southColor, Color westColor, - BorderStyle northBorderType, BorderStyle eastBorderType, - BorderStyle southBorderType, BorderStyle westBorderType, - boolean selected) { - this.eastColor = eastColor; - this.southColor = southColor; - this.westColor = westColor; - this.northBorderType = northBorderType; - this.eastBorderType = eastBorderType; - this.southBorderType = southBorderType; - this.westBorderType = westBorderType; - this.northBorder=northBorderType != BorderStyle.NONE; - this.eastBorder=eastBorderType != BorderStyle.NONE; - this.southBorder=southBorderType != BorderStyle.NONE; - this.westBorder=westBorderType != BorderStyle.NONE; - this.selected = selected; - } - - @Override -public void paintBorder(Component c, Graphics g, int x, int y, int width, - int height) { - Color oldColor = g.getColor(); - - - paintSelectedBorder(g, x, y, width, height); - paintNormalBorders(g, x, y, width, height); - paintDottedBorders(g, x, y, width, height); - paintDashedBorders(g, x, y, width, height); - paintDoubleBorders(g, x, y, width, height); - paintDashDotDotBorders(g, x, y, width, height); - - - g.setColor(oldColor); - } - - /** - * Called by paintBorder to paint the border of a selected cell. - * The paramaters are the Graphics object, location and dimensions of the - * cell. - */ - private void paintSelectedBorder(Graphics g, int x, int y, int width, - int height) { - if (selected) { - //Need to setup thickness of 2 - g.setColor(Color.black); - //paint the border - g.drawRect(x,y,width-1,height-1); - - //paint the filled rectangle at the bottom left hand position - g.fillRect(x+width-5, y+height-5, 5, 5); - } - } - - - /** - * Called by paintBorder to paint the various versions of normal line - * borders for a cell. - */ - private void paintNormalBorders(Graphics g, int x, int y, int width, - int height) { - - if (northBorder && - ((northBorderType == BorderStyle.THIN) || - (northBorderType == BorderStyle.MEDIUM) || - (northBorderType == BorderStyle.THICK) - ) - ) { - - int thickness = getThickness(northBorderType); - - g.setColor(northColor); - - for (int k=0; k < thickness; k++) { - g.drawLine(x,y+k,width,y+k); - } - } - - if (eastBorder && - ((eastBorderType == BorderStyle.THIN) || - (eastBorderType == BorderStyle.MEDIUM) || - (eastBorderType == BorderStyle.THICK) - ) - ) { - - int thickness = getThickness(eastBorderType); - - g.setColor(eastColor); - - for (int k=0; k < thickness; k++) { - g.drawLine(width-k,y,width-k,height); - } - } - - if (southBorder && - ((southBorderType == BorderStyle.THIN) || - (southBorderType == BorderStyle.MEDIUM) || - (southBorderType == BorderStyle.THICK) - ) - ) { - - int thickness = getThickness(southBorderType); - - g.setColor(southColor); - for (int k=0; k < thickness; k++) { - g.drawLine(x,height - k,width,height - k); - } - } - - if (westBorder && - ((westBorderType == BorderStyle.THIN) || - (westBorderType == BorderStyle.MEDIUM) || - (westBorderType == BorderStyle.THICK) - ) - ) { - - int thickness = getThickness(westBorderType); - - g.setColor(westColor); - - for (int k=0; k < thickness; k++) { - g.drawLine(x+k,y,x+k,height); - } - } - } - - /** - * Called by paintBorder to paint the dotted line - * borders for a cell. - */ - private void paintDottedBorders(Graphics g, int x, int y, int width, - int height) { - if (northBorder && - northBorderType == BorderStyle.DOTTED) { - int thickness = getThickness(northBorderType); - - g.setColor(northColor); - - for (int k=0; k < thickness; k++) { - for (int xc = x; xc < width; xc=xc+2) { - g.drawLine(xc,y+k,xc,y+k); - } - } - } - - if (eastBorder && - eastBorderType == BorderStyle.DOTTED - ) { - - int thickness = getThickness(eastBorderType); - thickness++; //need for dotted borders to show up east - - g.setColor(eastColor); - - for (int k=0; k < thickness; k++) { - for (int yc=y;yc < height; yc=yc+2) { - g.drawLine(width-k,yc,width-k,yc); - } - } - } - - if (southBorder && - southBorderType == BorderStyle.DOTTED - ) { - - int thickness = getThickness(southBorderType); - thickness++; - g.setColor(southColor); - for (int k=0; k < thickness; k++) { - for (int xc = x; xc < width; xc=xc+2) { - g.drawLine(xc,height-k,xc,height-k); - } - } - } - - if (westBorder && - westBorderType == BorderStyle.DOTTED - ) { - - int thickness = getThickness(westBorderType); -// thickness++; - - g.setColor(westColor); - - for (int k=0; k < thickness; k++) { - for (int yc=y;yc < height; yc=yc+2) { - g.drawLine(x+k,yc,x+k,yc); - } - } - } - } - - /** - * Called by paintBorder to paint the various versions of dotted line - * borders for a cell. - */ - private void paintDashedBorders(Graphics g, int x, int y, int width, - int height) { - if (northBorder && - ((northBorderType == BorderStyle.DASHED) || - (northBorderType == BorderStyle.HAIR)) - ) { - int thickness = getThickness(northBorderType); - - int dashlength = 1; - - if (northBorderType == BorderStyle.DASHED) - dashlength = 2; - - g.setColor(northColor); - - for (int k=0; k < thickness; k++) { - for (int xc = x; xc < width; xc=xc+5) { - g.drawLine(xc,y+k,xc+dashlength,y+k); - } - } - } - - if (eastBorder && - ((eastBorderType == BorderStyle.DASHED) || - (eastBorderType == BorderStyle.HAIR)) - ) { - - int thickness = getThickness(eastBorderType); - thickness++; //need for dotted borders to show up east - - - int dashlength = 1; - - if (eastBorderType == BorderStyle.DASHED) - dashlength = 2; - - g.setColor(eastColor); - - for (int k=0; k < thickness; k++) { - for (int yc=y;yc < height; yc=yc+5) { - g.drawLine(width-k,yc,width-k,yc+dashlength); - } - } - } - - if (southBorder && - ((southBorderType == BorderStyle.DASHED) || - (southBorderType == BorderStyle.HAIR)) - ) { - - int thickness = getThickness(southBorderType); - thickness++; - - int dashlength = 1; - - if (southBorderType == BorderStyle.DASHED) - dashlength = 2; - - g.setColor(southColor); - for (int k=0; k < thickness; k++) { - for (int xc = x; xc < width; xc=xc+5) { - g.drawLine(xc,height-k,xc+dashlength,height-k); - } - } - } - - if (westBorder && - ((westBorderType == BorderStyle.DASHED) || - (westBorderType == BorderStyle.HAIR)) - ) { - - int thickness = getThickness(westBorderType); -// thickness++; - - int dashlength = 1; - - if (westBorderType == BorderStyle.DASHED) - dashlength = 2; - - g.setColor(westColor); - - for (int k=0; k < thickness; k++) { - for (int yc=y;yc < height; yc=yc+5) { - g.drawLine(x+k,yc,x+k,yc+dashlength); - } - } - } - } - - /** - * Called by paintBorder to paint the double line - * borders for a cell. - */ - private void paintDoubleBorders(Graphics g, int x, int y, int width, - int height) { - if (northBorder && - northBorderType == BorderStyle.DOUBLE) { - - g.setColor(northColor); - - int leftx=x; - int rightx=width; - - // if there are borders on the west or east then - // the second line shouldn't cross them - if (westBorder) - leftx = x+3; - - if (eastBorder) - rightx = width-3; - - g.drawLine(x,y,width,y); - g.drawLine(leftx,y+2,rightx,y+2); - } - - if (eastBorder && - eastBorderType == BorderStyle.DOUBLE - ) { - - int thickness = getThickness(eastBorderType); - thickness++; //need for dotted borders to show up east - - g.setColor(eastColor); - - int topy=y; - int bottomy=height; - - if (northBorder) - topy=y+3; - - if (southBorder) - bottomy=height-3; - - g.drawLine(width-1,y,width-1,height); - g.drawLine(width-3,topy,width-3,bottomy); - } - - if (southBorder && - southBorderType == BorderStyle.DOUBLE - ) { - - g.setColor(southColor); - - int leftx=y; - int rightx=width; - - if (westBorder) - leftx=x+3; - - if (eastBorder) - rightx=width-3; - - - g.drawLine(x,height - 1,width,height - 1); - g.drawLine(leftx,height - 3,rightx,height - 3); - } - - if (westBorder && - westBorderType == BorderStyle.DOUBLE - ) { - - int thickness = getThickness(westBorderType); -// thickness++; - - g.setColor(westColor); - - int topy=y; - int bottomy=height-3; - - if (northBorder) - topy=y+2; - - if (southBorder) - bottomy=height-3; - - g.drawLine(x,y,x,height); - g.drawLine(x+2,topy,x+2,bottomy); - } - } - - /** - * Called by paintBorder to paint the various versions of dash dot dot line - * borders for a cell. - */ - private void paintDashDotDotBorders(Graphics g, int x, int y, int width, - int height) { - if (northBorder && - ((northBorderType == BorderStyle.DASH_DOT_DOT) || - (northBorderType == BorderStyle.MEDIUM_DASH_DOT_DOT)) - ) { - int thickness = getThickness(northBorderType); - - g.setColor(northColor); - for (int l=x; l < width;) { - l=l+drawDashDotDot(g, l, y, thickness, true, true); - } - - } - - if (eastBorder && - ((eastBorderType == BorderStyle.DASH_DOT_DOT) || - (eastBorderType == BorderStyle.MEDIUM_DASH_DOT_DOT)) - ) { - - int thickness = getThickness(eastBorderType); - - g.setColor(eastColor); - - for (int l=y;l < height;) { - //System.err.println("drawing east"); - l=l+drawDashDotDot(g,width-1,l,thickness,false,false); - } - } - - if (southBorder && - ((southBorderType == BorderStyle.DASH_DOT_DOT) || - (southBorderType == BorderStyle.MEDIUM_DASH_DOT_DOT)) - ) { - - int thickness = getThickness(southBorderType); - - g.setColor(southColor); - - for (int l=x; l < width;) { - //System.err.println("drawing south"); - l=l+drawDashDotDot(g, l, height-1, thickness, true, false); - } - } - - if (westBorder && - ((westBorderType == BorderStyle.DASH_DOT_DOT) || - (westBorderType == BorderStyle.MEDIUM_DASH_DOT_DOT)) - ) { - - int thickness = getThickness(westBorderType); - - g.setColor(westColor); - - for (int l=y;l < height;) { - //System.err.println("drawing west"); - l=l+drawDashDotDot(g,x,l,thickness,false,true); - } - - } - } - - /** - * Draws one dash dot dot horizontally or vertically with thickness drawn - * incrementally to either the right or left. - * - * @param g graphics object for drawing with - * @param x the x origin of the line - * @param y the y origin of the line - * @param thickness the thickness of the line - * @param horizontal or vertical (true for horizontal) - * @param right/bottom or left/top thickness (true for right or top), - * if true then the x or y origin will be incremented to provide - * thickness, if false, they'll be decremented. For vertical - * borders, x is incremented or decremented, for horizontal its y. - * Just set to true for north and west, and false for east and - * south. - * @returns length - returns the length of the line. - */ - private int drawDashDotDot(Graphics g,int x, int y, int thickness, - boolean horizontal, - boolean rightBottom) { - - for (int t=0; t < thickness; t++) { - if (!rightBottom) { - t = 0 - t; //add negative thickness so we go the other way - //then we'll decrement instead of increment. - } - if (horizontal) { - g.drawLine(x,y+t,x+5,y+t); - g.drawLine(x+8,y+t,x+10,y+t); - g.drawLine(x+13,y+t,x+15,y+t); - } else { - g.drawLine(x+t,y,x+t,y+5); - g.drawLine(x+t,y+8,x+t,y+10); - g.drawLine(x+t,y+13,x+t,y+15); - } - } - return 18; - } - - /** - * @returns the line thickness for a border based on border type - */ - private int getThickness(BorderStyle thickness) { - switch (thickness) { - case DASH_DOT_DOT: - case DASHED: - case HAIR: - return 1; - case THIN: - return 2; - case MEDIUM: - case MEDIUM_DASH_DOT_DOT: - return 3; - case THICK: - return 4; - default: - return 1; - } - } - - -} diff --git a/src/examples/src/org/apache/poi/hssf/view/SVFractionalFormat.java b/src/examples/src/org/apache/poi/hssf/view/SVFractionalFormat.java deleted file mode 100644 index 488419588..000000000 --- a/src/examples/src/org/apache/poi/hssf/view/SVFractionalFormat.java +++ /dev/null @@ -1,224 +0,0 @@ - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - - -package org.apache.poi.hssf.view; - -import java.text.*; - -/** - * This class is used to format cells into their fractional format. - * - * I cant be 100% sure that the same fractional value will be displayed as in - * excel but then again it is a lossy formating mode anyway - * - * @author Jason Height - * @since 15 July 2002 - */ -public class SVFractionalFormat extends Format { - private short ONE_DIGIT = 1; - private short TWO_DIGIT = 2; - private short THREE_DIGIT = 3; - private short UNITS = 4; - private int units = 1; - private short mode = -1; - - /** Constructs a new FractionalFormatter - * - * The formatStr defines how the number will be formatted - * # ?/? Up to one digit - * # ??/?? Up to two digits - * # ???/??? Up to three digits - * # ?/2 In halves - * # ?/4 In quarters - * # ?/8 In eighths - * # ?/16 In sixteenths - * # ?/10 In tenths - * # ?/100 In hundredths - */ - public SVFractionalFormat(String formatStr) { - if ("# ?/?".equals(formatStr)) - mode = ONE_DIGIT; - else if ("# ??/??".equals(formatStr)) - mode = TWO_DIGIT; - else if ("# ???/???".equals(formatStr)) - mode = THREE_DIGIT; - else if ("# ?/2".equals(formatStr)) { - mode = UNITS; - units = 2; - } else if ("# ?/4".equals(formatStr)) { - mode = UNITS; - units = 4; - } else if ("# ?/8".equals(formatStr)) { - mode = UNITS; - units = 8; - } else if ("# ?/16".equals(formatStr)) { - mode = UNITS; - units = 16; - } else if ("# ?/10".equals(formatStr)) { - mode = UNITS; - units = 10; - } else if ("# ?/100".equals(formatStr)) { - mode = UNITS; - units = 100; - } - } - - /** - * Returns a fractional string representation of a double to a maximum denominator size - * - * This code has been translated to java from the following web page. - * http://www.codeproject.com/cpp/fraction.asp - * Originally coded in c++ By Dean Wyant dwyant@mindspring.com - * The code on the web page is freely available. - * - * @param f Description of the Parameter - * @param MaxDen Description of the Parameter - * @return Description of the Return Value - */ - private String format(final double f, final int MaxDen) { - long Whole = (long)f; - int sign = 1; - if (f < 0) { - sign = -1; - } - double Precision = 0.00001; - double AllowedError = Precision; - double d = Math.abs(f); - d -= Whole; - double Frac = d; - double Diff = Frac; - long Num = 1; - long Den = 0; - long A = 0; - long B = 0; - long i = 0; - if (Frac > Precision) { - while (true) { - d = 1.0 / d; - i = (long) (d + Precision); - d -= i; - if (A > 0) { - Num = i * Num + B; - } - Den = (long) (Num / Frac + 0.5); - Diff = Math.abs((double) Num / Den - Frac); - if (Den > MaxDen) { - if (A > 0) { - Num = A; - Den = (long) (Num / Frac + 0.5); - Diff = Math.abs((double) Num / Den - Frac); - } else { - Den = MaxDen; - Num = 1; - Diff = Math.abs((double) Num / Den - Frac); - if (Diff > Frac) { - Num = 0; - Den = 1; - // Keeps final check below from adding 1 and keeps Den from being 0 - Diff = Frac; - } - } - break; - } - if ((Diff <= AllowedError) || (d < Precision)) { - break; - } - Precision = AllowedError / Diff; - // This calcualtion of Precision does not always provide results within - // Allowed Error. It compensates for loss of significant digits that occurs. - // It helps to round the inprecise reciprocal values to i. - B = A; - A = Num; - } - } - if (Num == Den) { - Whole++; - Num = 0; - Den = 0; - } else if (Den == 0) { - Num = 0; - } - if (sign < 0) { - if (Whole == 0) { - Num = -Num; - } else { - Whole = -Whole; - } - } - return new StringBuffer().append(Whole).append(" ").append(Num).append("/").append(Den).toString(); - } - - /** This method formats the double in the units specified. - * The usints could be any number but in this current implementation it is - * halves (2), quaters (4), eigths (8) etc - */ - private String formatUnit(double f, int units) { - long Whole = (long)f; - f -= Whole; - long Num = Math.round(f * units); - - return new StringBuffer().append(Whole).append(" ").append(Num).append("/").append(units).toString(); - } - - public final String format(double val) { - if (mode == ONE_DIGIT) { - return format(val, 9); - } else if (mode == TWO_DIGIT) { - return format(val, 99); - } else if (mode == THREE_DIGIT) { - return format(val, 999); - } else if (mode == UNITS) { - return formatUnit(val , units); - } - throw new RuntimeException("Unexpected Case"); - } - - @Override -public StringBuffer format(Object obj, - StringBuffer toAppendTo, - FieldPosition pos) { - if (obj instanceof Number) { - toAppendTo.append(format(((Number)obj).doubleValue())); - return toAppendTo; - } - throw new IllegalArgumentException("Can only handle Numbers"); - } - - @Override -public Object parseObject(String source, - ParsePosition status) { - //JMH TBD - return null; - } - - @Override -public Object parseObject(String source) - throws ParseException { - //JMH TBD - return null; - } - - @Override -public Object clone() { - //JMH TBD - return null; - } - - -} diff --git a/src/examples/src/org/apache/poi/hssf/view/SVRowHeader.java b/src/examples/src/org/apache/poi/hssf/view/SVRowHeader.java deleted file mode 100644 index 622f50643..000000000 --- a/src/examples/src/org/apache/poi/hssf/view/SVRowHeader.java +++ /dev/null @@ -1,99 +0,0 @@ - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - - - -package org.apache.poi.hssf.view; - -import java.awt.*; -import javax.swing.*; -import javax.swing.table.*; - -import org.apache.poi.hssf.usermodel.*; - -/** - * This class presents the row header to the table. - * - * - * @author Jason Height - */ -public class SVRowHeader extends JList { - /** This model simply returns an integer number up to the number of rows - * that are present in the sheet. - * - */ - private class SVRowHeaderModel extends AbstractListModel { - private HSSFSheet sheet; - - public SVRowHeaderModel(HSSFSheet sheet) { - this.sheet = sheet; - } - - @Override - public int getSize() { - return sheet.getLastRowNum() + 1; - } - @Override - public Object getElementAt(int index) { - return Integer.toString(index+1); - } - } - - /** Renderes the row number*/ - private class RowHeaderRenderer extends JLabel implements ListCellRenderer { - private HSSFSheet sheet; - private int extraHeight; - - RowHeaderRenderer(HSSFSheet sheet, JTable table, int extraHeight) { - this.sheet = sheet; - this.extraHeight = extraHeight; - JTableHeader header = table.getTableHeader(); - setOpaque(true); - setBorder(UIManager.getBorder("TableHeader.cellBorder")); - setHorizontalAlignment(CENTER); - setForeground(header.getForeground()); - setBackground(header.getBackground()); - setFont(header.getFont()); - } - - @Override - public Component getListCellRendererComponent( JList list, - Object value, int index, boolean isSelected, boolean cellHasFocus) { - Dimension d = getPreferredSize(); - HSSFRow row = sheet.getRow(index); - int rowHeight; - if(row == null) { - rowHeight = (int)sheet.getDefaultRowHeightInPoints(); - } else { - rowHeight = (int)row.getHeightInPoints(); - } - d.height = rowHeight+extraHeight; - setPreferredSize(d); - setText((value == null) ? "" : value.toString()); - return this; - } - } - - public SVRowHeader(HSSFSheet sheet, JTable table, int extraHeight) { - ListModel lm = new SVRowHeaderModel(sheet); - this.setModel(lm); - - setFixedCellWidth(50); - setCellRenderer(new RowHeaderRenderer(sheet, table, extraHeight)); - } -} diff --git a/src/examples/src/org/apache/poi/hssf/view/SVSheetTable.java b/src/examples/src/org/apache/poi/hssf/view/SVSheetTable.java deleted file mode 100644 index c9e209087..000000000 --- a/src/examples/src/org/apache/poi/hssf/view/SVSheetTable.java +++ /dev/null @@ -1,261 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hssf.view; - -import java.awt.Color; -import java.awt.Component; -import java.awt.Container; -import java.awt.Dimension; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.RenderingHints; -import java.awt.Toolkit; -import java.awt.event.HierarchyEvent; -import java.awt.event.HierarchyListener; - -import javax.swing.BorderFactory; -import javax.swing.JLabel; -import javax.swing.JScrollPane; -import javax.swing.JTable; -import javax.swing.JViewport; -import javax.swing.ListSelectionModel; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; -import javax.swing.table.JTableHeader; -import javax.swing.table.TableCellRenderer; -import javax.swing.table.TableColumn; -import javax.swing.table.TableColumnModel; -import javax.swing.table.TableModel; -import javax.swing.text.JTextComponent; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.view.brush.PendingPaintings; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.Row; - -/** - * This class is a table that represents the values in a single worksheet. - * - * @author Ken Arnold, Industrious Media LLC - */ -public class SVSheetTable extends JTable { - private final HSSFSheet sheet; - private final PendingPaintings pendingPaintings; - private FormulaDisplayListener formulaListener; - private JScrollPane scroll; - - private static final Color HEADER_BACKGROUND = new Color(235, 235, 235); - - /** - * This field is the magic number to convert from a Character width to a java - * pixel width. - *

    - * When the "normal" font size in a workbook changes, this effects all of the - * heights and widths. Unfortunately there is no way to retrieve this - * information, hence the MAGIC number. - *

    - * This number may only work for the normal style font size of Arial size 10. - */ - private static final int magicCharFactor = 7; - - private class HeaderCell extends JLabel { - private final int row; - - public HeaderCell(Object value, int row) { - super(value.toString(), CENTER); - this.row = row; - setBackground(HEADER_BACKGROUND); - setOpaque(true); - setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY)); - setRowSelectionAllowed(false); - } - - @Override - public Dimension getPreferredSize() { - Dimension d = super.getPreferredSize(); - if (row >= 0) { - d.height = getRowHeight(row); - } - return d; - } - - @Override - public Dimension getMaximumSize() { - Dimension d = super.getMaximumSize(); - if (row >= 0) { - d.height = getRowHeight(row); - } - return d; - } - - @Override - public Dimension getMinimumSize() { - Dimension d = super.getMinimumSize(); - if (row >= 0) { - d.height = getRowHeight(row); - } - return d; - } - } - - private class HeaderCellRenderer implements TableCellRenderer { - @Override - public Component getTableCellRendererComponent(JTable table, Object value, - boolean isSelected, boolean hasFocus, int row, int column) { - - return new HeaderCell(value, row); - } - } - - private class FormulaDisplayListener implements ListSelectionListener { - private final JTextComponent formulaDisplay; - - public FormulaDisplayListener(JTextComponent formulaDisplay) { - this.formulaDisplay = formulaDisplay; - } - - @Override - public void valueChanged(ListSelectionEvent e) { - int row = getSelectedRow(); - int col = getSelectedColumn(); - if (row < 0 || col < 0) { - return; - } - - if (e.getValueIsAdjusting()) { - return; - } - - HSSFCell cell = (HSSFCell) getValueAt(row, col); - String formula = ""; - if (cell != null) { - if (cell.getCellTypeEnum() == CellType.FORMULA) { - formula = cell.getCellFormula(); - } else { - formula = cell.toString(); - } - if (formula == null) - formula = ""; - } - formulaDisplay.setText(formula); - } - } - - public SVSheetTable(HSSFSheet sheet) { - super(new SVTableModel(sheet)); - this.sheet = sheet; - - setIntercellSpacing(new Dimension(0, 0)); - setAutoResizeMode(AUTO_RESIZE_OFF); - JTableHeader header = getTableHeader(); - header.setDefaultRenderer(new HeaderCellRenderer()); - pendingPaintings = new PendingPaintings(this); - - //Set the columns the correct size - TableColumnModel columns = getColumnModel(); - for (int i = 0; i < columns.getColumnCount(); i++) { - TableColumn column = columns.getColumn(i); - int width = sheet.getColumnWidth(i); - //256 is because the width is in 256ths of a character - column.setPreferredWidth(width / 256 * magicCharFactor); - } - - Toolkit t = getToolkit(); - int res = t.getScreenResolution(); - TableModel model = getModel(); - for (int i = 0; i < model.getRowCount(); i++) { - Row row = sheet.getRow(i - sheet.getFirstRowNum()); - if (row != null) { - short h = row.getHeight(); - int height = (int)Math.round(Math.max(1., h / (res / 70. * 20.) + 3.)); - System.out.printf("%d: %d (%d @ %d)%n", i, height, h, res); - setRowHeight(i, height); - } - } - - addHierarchyListener(new HierarchyListener() { - @Override - public void hierarchyChanged(HierarchyEvent e) { - if ((e.getChangeFlags() & HierarchyEvent.PARENT_CHANGED) != 0) { - Container changedParent = e.getChangedParent(); - if (changedParent instanceof JViewport) { - Container grandparent = changedParent.getParent(); - if (grandparent instanceof JScrollPane) { - JScrollPane jScrollPane = (JScrollPane) grandparent; - setupScroll(jScrollPane); - } - } - } - } - }); - } - - public void setupScroll(JScrollPane scroll) { - if (scroll == this.scroll) - return; - - this.scroll = scroll; - if (scroll == null) - return; - - SVRowHeader rowHeader = new SVRowHeader(sheet, this, 0); - scroll.setRowHeaderView(rowHeader); - scroll.setCorner(JScrollPane.UPPER_LEADING_CORNER, headerCell("?")); - } - - public void setFormulaDisplay(JTextComponent formulaDisplay) { - ListSelectionModel rowSelMod = getSelectionModel(); - ListSelectionModel colSelMod = getColumnModel().getSelectionModel(); - - if (formulaDisplay == null) { - rowSelMod.removeListSelectionListener(formulaListener); - colSelMod.removeListSelectionListener(formulaListener); - formulaListener = null; - } - - if (formulaDisplay != null) { - formulaListener = new FormulaDisplayListener(formulaDisplay); - rowSelMod.addListSelectionListener(formulaListener); - colSelMod.addListSelectionListener(formulaListener); - } - } - - public JTextComponent getFormulaDisplay() { - if (formulaListener == null) - return null; - else - return formulaListener.formulaDisplay; - } - - public Component headerCell(String text) { - return new HeaderCell(text, -1); - } - - @Override - public void paintComponent(Graphics g1) { - Graphics2D g = (Graphics2D) g1; - - pendingPaintings.clear(); - - g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, - RenderingHints.VALUE_ANTIALIAS_ON); - super.paintComponent(g); - - pendingPaintings.paint(g); - } -} \ No newline at end of file diff --git a/src/examples/src/org/apache/poi/hssf/view/SVTableCellEditor.java b/src/examples/src/org/apache/poi/hssf/view/SVTableCellEditor.java deleted file mode 100644 index 9db98d95e..000000000 --- a/src/examples/src/org/apache/poi/hssf/view/SVTableCellEditor.java +++ /dev/null @@ -1,212 +0,0 @@ - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.view; - -import static org.apache.poi.hssf.view.SVTableUtils.getAWTColor; - -import java.awt.Color; -import java.awt.Component; -import java.awt.Font; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseEvent; -import java.util.EventObject; - -import javax.swing.AbstractCellEditor; -import javax.swing.JTable; -import javax.swing.JTextField; -import javax.swing.SwingConstants; -import javax.swing.table.TableCellEditor; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFCellStyle; -import org.apache.poi.hssf.usermodel.HSSFFont; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.hssf.util.HSSFColor.HSSFColorPredefined; -import org.apache.poi.ss.usermodel.FillPatternType; - -/** - * Sheet Viewer Table Cell Editor -- not commented via javadoc as it - * nearly completely consists of overridden methods. - * - * @author Jason Height - */ -public class SVTableCellEditor extends AbstractCellEditor implements TableCellEditor, ActionListener { - private static final Color black = getAWTColor(HSSFColorPredefined.BLACK); - private static final Color white = getAWTColor(HSSFColorPredefined.WHITE); - - private HSSFWorkbook wb; - private JTextField editor; - - public SVTableCellEditor(HSSFWorkbook wb) { - this.wb = wb; - this.editor = new JTextField(); - } - - - /** - * Gets the cellEditable attribute of the SVTableCellEditor object - * - * @return The cellEditable value - */ - @Override - public boolean isCellEditable(java.util.EventObject e) { - if (e instanceof MouseEvent) { - return ((MouseEvent) e).getClickCount() >= 2; - } - return false; - } - - - @Override - public boolean shouldSelectCell(EventObject anEvent) { - return true; - } - - - public boolean startCellEditing(EventObject anEvent) { - System.out.println("Start Cell Editing"); - return true; - } - - - @Override - public boolean stopCellEditing() { - System.out.println("Stop Cell Editing"); - fireEditingStopped(); - return true; - } - - - @Override - public void cancelCellEditing() { - System.out.println("Cancel Cell Editing"); - fireEditingCanceled(); - } - - - @Override - public void actionPerformed(ActionEvent e) { - System.out.println("Action performed"); - stopCellEditing(); - } - - - /** - * Gets the cellEditorValue attribute of the SVTableCellEditor object - * - * @return The cellEditorValue value - */ - @Override - public Object getCellEditorValue() { - System.out.println("GetCellEditorValue"); - //JMH Look at when this method is called. Should it return a HSSFCell? - return editor.getText(); - } - - - /** - * Gets the tableCellEditorComponent attribute of the SVTableCellEditor object - * - * @return The tableCellEditorComponent value - */ - @Override - public Component getTableCellEditorComponent(JTable table, Object value, - boolean isSelected, - int row, - int column) { - System.out.println("GetTableCellEditorComponent"); - HSSFCell cell = (HSSFCell) value; - if (cell != null) { - HSSFCellStyle style = cell.getCellStyle(); - HSSFFont f = wb.getFontAt(style.getFontIndex()); - boolean isbold = f.getBold(); - boolean isitalics = f.getItalic(); - - int fontstyle = Font.PLAIN; - - if (isbold) { - fontstyle = Font.BOLD; - } - if (isitalics) { - fontstyle = fontstyle | Font.ITALIC; - } - - int fontheight = f.getFontHeightInPoints(); - if (fontheight == 9) { - fontheight = 10; //fix for stupid ol Windows - } - - Font font = new Font(f.getFontName(),fontstyle,fontheight); - editor.setFont(font); - - if (style.getFillPatternEnum() == FillPatternType.SOLID_FOREGROUND) { - editor.setBackground(getAWTColor(style.getFillForegroundColor(), white)); - } else { - editor.setBackground(white); - } - - editor.setForeground(getAWTColor(f.getColor(), black)); - - - //Set the value that is rendered for the cell - switch (cell.getCellTypeEnum()) { - case BLANK: - editor.setText(""); - break; - case BOOLEAN: - if (cell.getBooleanCellValue()) { - editor.setText("true"); - } else { - editor.setText("false"); - } - break; - case NUMERIC: - editor.setText(Double.toString(cell.getNumericCellValue())); - break; - case STRING: - editor.setText(cell.getRichStringCellValue().getString()); - break; - case FORMULA: - default: - editor.setText("?"); - } - switch (style.getAlignmentEnum()) { - case LEFT: - case JUSTIFY: - case FILL: - editor.setHorizontalAlignment(SwingConstants.LEFT); - break; - case CENTER: - case CENTER_SELECTION: - editor.setHorizontalAlignment(SwingConstants.CENTER); - break; - case GENERAL: - case RIGHT: - editor.setHorizontalAlignment(SwingConstants.RIGHT); - break; - default: - editor.setHorizontalAlignment(SwingConstants.LEFT); - break; - } - - } - return editor; - } -} diff --git a/src/examples/src/org/apache/poi/hssf/view/SVTableCellRenderer.java b/src/examples/src/org/apache/poi/hssf/view/SVTableCellRenderer.java deleted file mode 100644 index 1448c5363..000000000 --- a/src/examples/src/org/apache/poi/hssf/view/SVTableCellRenderer.java +++ /dev/null @@ -1,283 +0,0 @@ - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - - -package org.apache.poi.hssf.view; - -import java.awt.Color; -import java.awt.Component; -import java.awt.Rectangle; -import java.io.Serializable; -import java.text.DecimalFormat; -import java.text.Format; -import java.text.SimpleDateFormat; - -import javax.swing.JLabel; -import javax.swing.JTable; -import javax.swing.SwingConstants; -import javax.swing.UIManager; -import javax.swing.border.Border; -import javax.swing.border.EmptyBorder; -import javax.swing.table.TableCellRenderer; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFCellStyle; -import org.apache.poi.hssf.usermodel.HSSFFont; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.BorderStyle; -import org.apache.poi.ss.usermodel.FillPatternType; - - -/** - * Sheet Viewer Table Cell Render -- not commented via javadoc as it - * nearly completely consists of overridden methods. - * - * @author Andrew C. Oliver - */ -public class SVTableCellRenderer extends JLabel - implements TableCellRenderer, Serializable -{ - protected static Border noFocusBorder = new EmptyBorder(1, 1, 1, 1); - protected SVBorder cellBorder = new SVBorder(); - - - private HSSFWorkbook wb = null; - - /** This class holds the references to the predefined cell formats. - */ - private class CellFormatter { - private Format[] textFormatter; - - private DecimalFormat generalNumberFormat = new DecimalFormat("0"); - - public CellFormatter() { - textFormatter = new Format[0x31]; - - textFormatter[0x01] = new DecimalFormat("0"); - textFormatter[0x02] = new DecimalFormat("0.00"); - textFormatter[0x03] = new DecimalFormat("#,##0"); - textFormatter[0x04] = new DecimalFormat("#,##0.00"); - textFormatter[0x05] = new DecimalFormat("$#,##0;$#,##0"); - textFormatter[0x06] = new DecimalFormat("$#,##0;$#,##0"); - textFormatter[0x07] = new DecimalFormat("$#,##0.00;$#,##0.00"); - textFormatter[0x08] = new DecimalFormat("$#,##0.00;$#,##0.00"); - textFormatter[0x09] = new DecimalFormat("0%"); - textFormatter[0x0A] = new DecimalFormat("0.00%"); - textFormatter[0x0B] = new DecimalFormat("0.00E0"); - textFormatter[0x0C] = new SVFractionalFormat("# ?/?"); - textFormatter[0x0D] = new SVFractionalFormat("# ??/??"); - textFormatter[0x0E] = new SimpleDateFormat("M/d/yy"); - textFormatter[0x0F] = new SimpleDateFormat("d-MMM-yy"); - textFormatter[0x10] = new SimpleDateFormat("d-MMM"); - textFormatter[0x11] = new SimpleDateFormat("MMM-yy"); - textFormatter[0x12] = new SimpleDateFormat("h:mm a"); - textFormatter[0x13] = new SimpleDateFormat("h:mm:ss a"); - textFormatter[0x14] = new SimpleDateFormat("h:mm"); - textFormatter[0x15] = new SimpleDateFormat("h:mm:ss"); - textFormatter[0x16] = new SimpleDateFormat("M/d/yy h:mm"); - // 0x17 - 0x24 reserved for international and undocumented 0x25, "(#,##0_);(#,##0)" - //start at 0x26 - //jmh need to do colour - //"(#,##0_);[Red](#,##0)" - textFormatter[0x26] = new DecimalFormat("#,##0;#,##0"); - //jmh need to do colour - //(#,##0.00_);(#,##0.00) - textFormatter[0x27] = new DecimalFormat("#,##0.00;#,##0.00"); - textFormatter[0x28] = new DecimalFormat("#,##0.00;#,##0.00"); -//?? textFormatter[0x29] = new DecimalFormat("_(*#,##0_);_(*(#,##0);_(* \"-\"_);_(@_)"); -//?? textFormatter[0x2A] = new DecimalFormat("_($*#,##0_);_($*(#,##0);_($* \"-\"_);_(@_)"); -//?? textFormatter[0x2B] = new DecimalFormat("_(*#,##0.00_);_(*(#,##0.00);_(*\"-\"??_);_(@_)"); -//?? textFormatter[0x2C] = new DecimalFormat("_($*#,##0.00_);_($*(#,##0.00);_($*\"-\"??_);_(@_)"); - textFormatter[0x2D] = new SimpleDateFormat("mm:ss"); -//?? textFormatter[0x2E] = new SimpleDateFormat("[h]:mm:ss"); - textFormatter[0x2F] = new SimpleDateFormat("mm:ss.0"); - textFormatter[0x30] = new DecimalFormat("##0.0E0"); - } - - public String format(short index, double value) { - if ( index <= 0 ) - return generalNumberFormat.format(value); - if (textFormatter[index] == null) - throw new RuntimeException("Sorry. I cant handle the format code :"+Integer.toHexString(index)); - if (textFormatter[index] instanceof DecimalFormat) { - return ((DecimalFormat)textFormatter[index]).format(value); - } - if (textFormatter[index] instanceof SVFractionalFormat) { - return ((SVFractionalFormat)textFormatter[index]).format(value); - } - throw new RuntimeException("Sorry. I cant handle a non decimal formatter for a decimal value :"+Integer.toHexString(index)); - } - - public boolean useRedColor(short index, double value) { - return (((index == 0x06)||(index == 0x08)||(index == 0x26) || (index == 0x27)) && (value < 0)); - } - } - - private final CellFormatter cellFormatter = new CellFormatter(); - - public SVTableCellRenderer(HSSFWorkbook wb) { - super(); - setOpaque(true); - setBorder(noFocusBorder); - this.wb = wb; - } - - @Override - public Component getTableCellRendererComponent(JTable table, Object value, - boolean isSelected, boolean hasFocus, int row, int column) { - boolean isBorderSet = false; - - //If the JTables default cell renderer has been setup correctly the - //value will be the HSSFCell that we are trying to render - HSSFCell c = (HSSFCell)value; - - if (c != null) { - HSSFCellStyle s = c.getCellStyle(); - HSSFFont f = wb.getFontAt(s.getFontIndex()); - setFont(SVTableUtils.makeFont(f)); - - if (s.getFillPatternEnum() == FillPatternType.SOLID_FOREGROUND) { - setBackground(SVTableUtils.getAWTColor(s.getFillForegroundColor(), SVTableUtils.white)); - } else setBackground(SVTableUtils.white); - - setForeground(SVTableUtils.getAWTColor(f.getColor(), SVTableUtils.black)); - - cellBorder.setBorder(SVTableUtils.getAWTColor(s.getTopBorderColor(), SVTableUtils.black), - SVTableUtils.getAWTColor(s.getRightBorderColor(), SVTableUtils.black), - SVTableUtils.getAWTColor(s.getBottomBorderColor(), SVTableUtils.black), - SVTableUtils.getAWTColor(s.getLeftBorderColor(), SVTableUtils.black), - s.getBorderTopEnum(), s.getBorderRightEnum(), - s.getBorderBottomEnum(), s.getBorderLeftEnum(), - hasFocus); - setBorder(cellBorder); - isBorderSet=true; - - //Set the value that is rendered for the cell - switch (c.getCellTypeEnum()) { - case BLANK: - setValue(""); - break; - case BOOLEAN: - if (c.getBooleanCellValue()) { - setValue("true"); - } else { - setValue("false"); - } - break; - case NUMERIC: - short format = s.getDataFormat(); - double numericValue = c.getNumericCellValue(); - if (cellFormatter.useRedColor(format, numericValue)) - setForeground(Color.red); - else setForeground(null); - setValue(cellFormatter.format(format, c.getNumericCellValue())); - break; - case STRING: - setValue(c.getRichStringCellValue().getString()); - break; - case FORMULA: - default: - setValue("?"); - } - //Set the text alignment of the cell - switch (s.getAlignmentEnum()) { - case LEFT: - case JUSTIFY: - case FILL: - setHorizontalAlignment(SwingConstants.LEFT); - break; - case CENTER: - case CENTER_SELECTION: - setHorizontalAlignment(SwingConstants.CENTER); - break; - case GENERAL: - case RIGHT: - setHorizontalAlignment(SwingConstants.RIGHT); - break; - default: - setHorizontalAlignment(SwingConstants.LEFT); - break; - } - } else { - setValue(""); - setBackground(SVTableUtils.white); - } - - - if (hasFocus) { - if (!isBorderSet) { - //This is the border to paint when there is no border - //and the cell has focus - cellBorder.setBorder(SVTableUtils.black, - SVTableUtils.black, - SVTableUtils.black, - SVTableUtils.black, - BorderStyle.NONE, - BorderStyle.NONE, - BorderStyle.NONE, - BorderStyle.NONE, - isSelected); - setBorder(cellBorder); - } - if (table.isCellEditable(row, column)) { - setForeground( UIManager.getColor("Table.focusCellForeground") ); - setBackground( UIManager.getColor("Table.focusCellBackground") ); - } - } else if (!isBorderSet) { - setBorder(noFocusBorder); - } - - // ---- begin optimization to avoid painting background ---- - Color back = getBackground(); - boolean colorMatch = (back != null) && ( back.equals(table.getBackground()) ) && table.isOpaque(); - setOpaque(!colorMatch); - // ---- end optimization to aviod painting background ---- - return this; - } - - @Override - public void validate() {} - - @Override - public void revalidate() {} - - @Override - public void repaint(long tm, int x, int y, int width, int height) {} - - @Override - public void repaint(Rectangle r) { } - - @Override - protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) { - // Strings get interned... - if (propertyName=="text") { - super.firePropertyChange(propertyName, oldValue, newValue); - } - } - - @Override - public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) { } - - /** - * Sets the string to either the value or "" if the value is null. - * - */ - protected void setValue(Object value) { - setText((value == null) ? "" : value.toString()); - } -} diff --git a/src/examples/src/org/apache/poi/hssf/view/SVTableModel.java b/src/examples/src/org/apache/poi/hssf/view/SVTableModel.java deleted file mode 100644 index 25ac83fc5..000000000 --- a/src/examples/src/org/apache/poi/hssf/view/SVTableModel.java +++ /dev/null @@ -1,94 +0,0 @@ - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - - - -package org.apache.poi.hssf.view; - -import java.util.Iterator; -import javax.swing.table.*; - -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.hssf.usermodel.HSSFCell; - -/** - * Sheet Viewer Table Model - The model for the Sheet Viewer just overrides things. - * @author Andrew C. Oliver - */ - -public class SVTableModel extends AbstractTableModel { - private HSSFSheet st = null; - int maxcol = 0; - - public SVTableModel(HSSFSheet st, int maxcol) { - this.st = st; - this.maxcol=maxcol; - } - - public SVTableModel(HSSFSheet st) { - this.st = st; - Iterator i = st.rowIterator(); - - while (i.hasNext()) { - HSSFRow row = (HSSFRow)i.next(); - if (maxcol < (row.getLastCellNum()+1)) { - this.maxcol = row.getLastCellNum(); - } - } - } - - - @Override -public int getColumnCount() { - return this.maxcol+1; - } - @Override -public Object getValueAt(int row, int col) { - HSSFRow r = st.getRow(row); - HSSFCell c = null; - if (r != null) { - c = r.getCell(col); - } - return c; - } - @Override -public int getRowCount() { - return st.getLastRowNum() + 1; - } - - @Override -public Class getColumnClass(int c) { - return HSSFCell.class; - } - - @Override -public boolean isCellEditable(int rowIndex, int columnIndex) { - return true; - } - - @Override -public void setValueAt(Object aValue, int rowIndex, int columnIndex) { - if (aValue != null) - System.out.println("SVTableModel.setValueAt. value type = "+aValue.getClass().getName()); - else System.out.println("SVTableModel.setValueAt. value type = null"); - } - - -} diff --git a/src/examples/src/org/apache/poi/hssf/view/SVTableUtils.java b/src/examples/src/org/apache/poi/hssf/view/SVTableUtils.java deleted file mode 100644 index 4ec32944d..000000000 --- a/src/examples/src/org/apache/poi/hssf/view/SVTableUtils.java +++ /dev/null @@ -1,86 +0,0 @@ - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.view; - -import java.awt.Color; -import java.awt.Font; -import java.util.Map; - -import javax.swing.border.Border; -import javax.swing.border.EmptyBorder; - -import org.apache.poi.hssf.usermodel.HSSFFont; -import org.apache.poi.hssf.util.HSSFColor; -import org.apache.poi.hssf.util.HSSFColor.HSSFColorPredefined; - -/** - * SVTableCell Editor and Renderer helper functions. - * - * @author Jason Height - */ -public class SVTableUtils { - private final static Map colors = HSSFColor.getIndexHash(); - /** Description of the Field */ - public final static Color black = getAWTColor(HSSFColorPredefined.BLACK); - /** Description of the Field */ - public final static Color white = getAWTColor(HSSFColorPredefined.WHITE); - /** Description of the Field */ - public static Border noFocusBorder = new EmptyBorder(1, 1, 1, 1); - - - /** - * Creates a new font for a specific cell style - */ - public static Font makeFont(HSSFFont font) { - boolean isbold = font.getBold(); - boolean isitalics = font.getItalic(); - int fontstyle = Font.PLAIN; - if (isbold) { - fontstyle = Font.BOLD; - } - if (isitalics) { - fontstyle = fontstyle | Font.ITALIC; - } - - int fontheight = font.getFontHeightInPoints(); - if (fontheight == 9) { - //fix for stupid ol Windows - fontheight = 10; - } - - return new Font(font.getFontName(), fontstyle, fontheight); - } - - /** This method retrieves the AWT Color representation from the colour hash table - * - */ - /* package */ static final Color getAWTColor(int index, Color deflt) { - HSSFColor clr = colors.get(index); - if (clr == null) { - return deflt; - } - short[] rgb = clr.getTriplet(); - return new Color(rgb[0],rgb[1],rgb[2]); - } - - /* package */ static final Color getAWTColor(HSSFColorPredefined clr) { - short[] rgb = clr.getTriplet(); - return new Color(rgb[0],rgb[1],rgb[2]); - } -} diff --git a/src/examples/src/org/apache/poi/hssf/view/SViewer.java b/src/examples/src/org/apache/poi/hssf/view/SViewer.java deleted file mode 100644 index a32399275..000000000 --- a/src/examples/src/org/apache/poi/hssf/view/SViewer.java +++ /dev/null @@ -1,180 +0,0 @@ - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - - - -package org.apache.poi.hssf.view; - -import java.awt.*; -import java.awt.event.*; -import java.net.*; -import java.io.*; -import javax.swing.*; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; - -/** - * Sheet Viewer - Views XLS files via HSSF. Can be used as an applet with - * filename="" or as a applications (pass the filename as the first parameter). - * Or you can pass it a URL in a "url" parameter when run as an applet or just - * that first parameter must start with http:// and it will guess its a url. I - * only tested it as an applet though, so it probably won't work...you fix it. - * - * @author Andrew C. Oliver - * @author Jason Height - */ -public class SViewer extends JApplet { - private SViewerPanel panel; - boolean isStandalone = false; - String filename = null; - - /**Get a parameter value*/ - public String getParameter(String key, String def) { - return isStandalone ? System.getProperty(key, def) : - (getParameter(key) != null ? getParameter(key) : def); - } - - /**Construct the applet*/ - public SViewer() { - } - - /**Initialize the applet*/ - @Override -public void init() { - try { - jbInit(); - } - catch(Exception e) { - e.printStackTrace(); - System.exit(1); - } - } - - /**Component initialization*/ - private void jbInit() throws Exception { - InputStream i = null; - boolean isurl = false; - if (filename == null) filename = getParameter("filename"); - - if (filename == null || filename.substring(0,7).equals("http://")) { - isurl = true; - if (filename == null) filename = getParameter("url"); - i = getXLSFromURL(filename); - } - - HSSFWorkbook wb = null; - if (isurl) { - wb = constructWorkbook(i); - } else { - wb = constructWorkbook(filename); - } - panel = new SViewerPanel(wb, false); - getContentPane().setLayout(new BorderLayout()); - getContentPane().add(panel, BorderLayout.CENTER); - } - - private HSSFWorkbook constructWorkbook(String filename) throws FileNotFoundException, IOException { - HSSFWorkbook wb = null; - FileInputStream in = new FileInputStream(filename); - wb = new HSSFWorkbook(in); - in.close(); - return wb; - } - - private HSSFWorkbook constructWorkbook(InputStream in) throws IOException { - HSSFWorkbook wb = null; - - wb = new HSSFWorkbook(in); - in.close(); - return wb; - } - - /**Start the applet*/ - @Override -public void start() { - } - /**Stop the applet*/ - @Override -public void stop() { - } - /**Destroy the applet*/ - @Override -public void destroy() { - } - /**Get Applet information*/ - @Override -public String getAppletInfo() { - return "Applet Information"; - } - /**Get parameter info*/ - @Override -public String[][] getParameterInfo() { - return null; - } - - /** - * opens a url and returns an inputstream - * - */ - private InputStream getXLSFromURL(String urlstring) throws MalformedURLException, IOException { - URL url = new URL(urlstring); - URLConnection uc = url.openConnection(); - String field = uc.getHeaderField(0); - for (int i=0;field != null; i++) { - System.out.println(field); - field = uc.getHeaderField(i); - } - BufferedInputStream is = new BufferedInputStream(uc.getInputStream()); - return is; - } - - - /**Main method*/ - public static void main(String[] args) { - if(args.length < 1) { - throw new IllegalArgumentException("A filename to view must be supplied as the first argument, but none was given"); - } - - SViewer applet = new SViewer(); - applet.isStandalone = true; - applet.filename = args[0]; - Frame frame; - frame = new Frame() { - @Override - protected void processWindowEvent(WindowEvent e) { - super.processWindowEvent(e); - if (e.getID() == WindowEvent.WINDOW_CLOSING) { - System.exit(0); - } - } - @Override - public synchronized void setTitle(String title) { - super.setTitle(title); - enableEvents(AWTEvent.WINDOW_EVENT_MASK); - } - }; - frame.setTitle("Applet Frame"); - frame.add(applet, BorderLayout.CENTER); - applet.init(); - applet.start(); - frame.setSize(400,320); - Dimension d = Toolkit.getDefaultToolkit().getScreenSize(); - frame.setLocation((d.width - frame.getSize().width) / 2, (d.height - frame.getSize().height) / 2); - frame.setVisible(true); - } -} diff --git a/src/examples/src/org/apache/poi/hssf/view/SViewerPanel.java b/src/examples/src/org/apache/poi/hssf/view/SViewerPanel.java deleted file mode 100644 index bf1ba4ab7..000000000 --- a/src/examples/src/org/apache/poi/hssf/view/SViewerPanel.java +++ /dev/null @@ -1,303 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.view; - -import java.awt.*; -import java.awt.event.*; -import java.io.*; -import javax.swing.*; -import javax.swing.table.*; - -import org.apache.poi.hssf.usermodel.*; - -/** - * This class presents the sheets to the user. - * - * - * @author Andrew C. Oliver - * @author Jason Height - */ -public class SViewerPanel extends JPanel { - /** This field is the magic number to convert from a Character width to a - * java pixel width. - * - * When the "normal" font size in a workbook changes, this effects all - * of the heights and widths. Unfortunately there is no way to retrieve this - * information, hence the MAGIC number. - * - * This number may only work for the normal style font size of Arial size 10. - * - */ - private static final int magicCharFactor = 7; - /** Reference to the wookbook that is being displayed*/ - /* package */ HSSFWorkbook wb; - /** Reference to the tabs component*/ - /* package */ JTabbedPane sheetPane; - /** Reference to the cell renderer that is used to render all cells*/ - private SVTableCellRenderer cellRenderer; - /** Reference to the cell editor that is used to edit all cells. - * Only constructed if editing is allowed - */ - private SVTableCellEditor cellEditor; - /** Flag indicating if editing is allowed. Otherwise the viewer is in - * view only mode. - */ - private boolean allowEdits; - - /**Construct the representation of the workbook*/ - public SViewerPanel(HSSFWorkbook wb, boolean allowEdits) { - this.wb = wb; - this.allowEdits = allowEdits; - - initialiseGui(); - } - - private void initialiseGui() { - cellRenderer = new SVTableCellRenderer(this.wb); - if (allowEdits) - cellEditor = new SVTableCellEditor(this.wb); - - //Initialise the Panel - sheetPane = new JTabbedPane(JTabbedPane.BOTTOM); - - if (allowEdits) - sheetPane.addMouseListener(createTabListener()); - int sheetCount = wb.getNumberOfSheets(); - for (int i=0; i - * It is up to the parent component to invoke the {@link #paint(Graphics2D)} - * method of this objet at that appropriate time. - * - * @author Ken Arnold, Industrious Media LLC - */ -public class PendingPaintings { - /** - * The name of the client property that holds this object in the parent - * component. - */ - public static final String PENDING_PAINTINGS = - PendingPaintings.class.getSimpleName(); - - private final List paintings; - - /** A single painting description. */ - public static class Painting { - final Stroke stroke; - final Color color; - final Shape shape; - final AffineTransform transform; - - /** - * Creates a new painting description. - * - * @param stroke The stroke to paint. - * @param color The color of the stroke. - * @param shape The shape of the stroke. - * @param transform The transformation matrix to use. - */ - public Painting(Stroke stroke, Color color, Shape shape, - AffineTransform transform) { - - this.color = color; - this.shape = shape; - this.stroke = stroke; - this.transform = transform; - } - - /** - * Draw the painting. - * - * @param g The graphics object to use to draw with. - */ - public void draw(Graphics2D g) { - g.setTransform(transform); - g.setStroke(stroke); - g.setColor(color); - g.draw(shape); - } - } - - /** - * Creates a new object on the given parent. The created object will be - * stored as a client property. - * - * @param parent - */ - public PendingPaintings(JComponent parent) { - paintings = new ArrayList(); - parent.putClientProperty(PENDING_PAINTINGS, this); - } - - /** Drops all pending paintings. */ - public void clear() { - paintings.clear(); - } - - /** - * Paints all pending paintings. Once they have been painted they are - * removed from the list of pending paintings (they aren't pending anymore, - * after all). - * - * @param g The graphics object to draw with. - */ - public void paint(Graphics2D g) { - g.setBackground(Color.CYAN); - AffineTransform origTransform = g.getTransform(); - for (Painting c : paintings) { - c.draw(g); - } - g.setTransform(origTransform); - - clear(); - } - - /** - * Adds a new pending painting to the list on the given component. This - * will find the first ancestor that has a {@link PendingPaintings} client - * property, starting with the component itself. - * - * @param c The component for which the painting is being added. - * @param g The graphics object to draw with. - * @param stroke The stroke to draw. - * @param color The color to draw with. - * @param shape The shape to stroke. - */ - public static void add(JComponent c, Graphics2D g, Stroke stroke, - Color color, Shape shape) { - - add(c, new Painting(stroke, color, shape, g.getTransform())); - } - - /** - * Adds a new pending painting to the list on the given component. This - * will find the first ancestor that has a {@link PendingPaintings} client - * property, starting with the component itself. - * - * @param c The component for which the painting is being added. - * @param newPainting The new painting. - */ - public static void add(JComponent c, Painting newPainting) { - PendingPaintings pending = pendingPaintingsFor(c); - if (pending != null) { - pending.paintings.add(newPainting); - } - } - - /** - * Returns the pending painting object for the given component, if any. This - * is retrieved from the first object found that has a {@link - * #PENDING_PAINTINGS} client property, starting with this component and - * looking up its ancestors (parent, parent's parent, etc.) - *

    - * This allows any descendant of a component that has a {@link - * PendingPaintings} property to add its own pending paintings. - * - * @param c The component for which the painting is being added. - * - * @return The pending painting object for that component, or null - * if there is none. - */ - public static PendingPaintings pendingPaintingsFor(JComponent c) { - for (Component parent = c; - parent != null; - parent = parent.getParent()) { - if (parent instanceof JComponent) { - JComponent jc = (JComponent) parent; - Object pd = jc.getClientProperty(PENDING_PAINTINGS); - if (pd != null) - return (PendingPaintings) pd; - } - } - return null; - } -} \ No newline at end of file diff --git a/src/examples/src/org/apache/poi/hssf/view/brush/package.html b/src/examples/src/org/apache/poi/hssf/view/brush/package.html deleted file mode 100644 index d9819fb66..000000000 --- a/src/examples/src/org/apache/poi/hssf/view/brush/package.html +++ /dev/null @@ -1,26 +0,0 @@ - - - - - -This package contains some brushes that are used when drawing borders for Excel -cells. - - diff --git a/src/examples/src/org/apache/poi/hwpf/Word2Forrest.java b/src/examples/src/org/apache/poi/hwpf/Word2Forrest.java deleted file mode 100644 index 3516b88e8..000000000 --- a/src/examples/src/org/apache/poi/hwpf/Word2Forrest.java +++ /dev/null @@ -1,229 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf; - -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.Writer; -import java.nio.charset.Charset; - -import org.apache.poi.hwpf.model.StyleDescription; -import org.apache.poi.hwpf.model.StyleSheet; -import org.apache.poi.hwpf.usermodel.CharacterRun; -import org.apache.poi.hwpf.usermodel.Paragraph; -import org.apache.poi.hwpf.usermodel.Range; - -public final class Word2Forrest -{ - Writer _out; - HWPFDocument _doc; - - @SuppressWarnings("unused") - public Word2Forrest(HWPFDocument doc, OutputStream stream) throws IOException - { - OutputStreamWriter out = new OutputStreamWriter (stream, Charset.forName("UTF-8")); - _out = out; - _doc = doc; - - init (); - openDocument (); - openBody (); - - Range r = doc.getRange (); - StyleSheet styleSheet = doc.getStyleSheet (); - - int sectionLevel = 0; - int lenParagraph = r.numParagraphs (); - boolean inCode = false; - for (int x = 0; x < lenParagraph; x++) - { - Paragraph p = r.getParagraph (x); - String text = p.text (); - if (text.trim ().length () == 0) - { - continue; - } - StyleDescription paragraphStyle = styleSheet.getStyleDescription (p. - getStyleIndex ()); - String styleName = paragraphStyle.getName(); - if (styleName.startsWith ("Heading")) - { - if (inCode) - { - closeSource(); - inCode = false; - } - - int headerLevel = Integer.parseInt (styleName.substring (8)); - if (headerLevel > sectionLevel) - { - openSection (); - } - else - { - for (int y = 0; y < (sectionLevel - headerLevel) + 1; y++) - { - closeSection (); - } - openSection (); - } - sectionLevel = headerLevel; - openTitle (); - writePlainText (text); - closeTitle (); - } - else - { - int cruns = p.numCharacterRuns (); - CharacterRun run = p.getCharacterRun (0); - String fontName = run.getFontName(); - if (fontName.startsWith ("Courier")) - { - if (!inCode) - { - openSource (); - inCode = true; - } - writePlainText (p.text()); - } - else - { - if (inCode) - { - inCode = false; - closeSource(); - } - openParagraph(); - writePlainText(p.text()); - closeParagraph(); - } - } - } - for (int x = 0; x < sectionLevel; x++) - { - closeSection(); - } - closeBody(); - closeDocument(); - _out.flush(); - - } - - public void init () - throws IOException - { - _out.write ("\r\n"); - _out.write ("\r\n"); - } - - public void openDocument () - throws IOException - { - _out.write ("\r\n"); - } - public void closeDocument () - throws IOException - { - _out.write ("\r\n"); - } - - - public void openBody () - throws IOException - { - _out.write ("\r\n"); - } - - public void closeBody () - throws IOException - { - _out.write ("\r\n"); - } - - - public void openSection () - throws IOException - { - _out.write ("

    "); - - } - - public void closeSection () - throws IOException - { - _out.write ("
    "); - - } - - public void openTitle () - throws IOException - { - _out.write (""); - } - - public void closeTitle () - throws IOException - { - _out.write (""); - } - - public void writePlainText (String text) - throws IOException - { - _out.write (text); - } - - public void openParagraph () - throws IOException - { - _out.write ("

    "); - } - - public void closeParagraph () - throws IOException - { - _out.write ("

    "); - } - - public void openSource () - throws IOException - { - _out.write (""); - } - - - public static void main(String[] args) throws IOException { - InputStream is = new FileInputStream(args[0]); - OutputStream out = new FileOutputStream("test.xml"); - try { - new Word2Forrest(new HWPFDocument(is), out); - } finally { - out.close(); - is.close(); - } - } -} diff --git a/src/examples/src/org/apache/poi/poifs/poibrowser/DocumentDescriptor.java b/src/examples/src/org/apache/poi/poifs/poibrowser/DocumentDescriptor.java deleted file mode 100644 index 247684d1b..000000000 --- a/src/examples/src/org/apache/poi/poifs/poibrowser/DocumentDescriptor.java +++ /dev/null @@ -1,76 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.poibrowser; - -import java.io.*; -import org.apache.poi.poifs.filesystem.*; - -/** - *

    Describes the most important (whatever that is) features of a - * {@link POIFSDocument}.

    - */ -public class DocumentDescriptor -{ - String name; - POIFSDocumentPath path; - DocumentInputStream stream; - - int size; - byte[] bytes; - - - /** - *

    Creates a {@link DocumentDescriptor}.

    - * - * @param name The stream's name. - * - * @param path The stream's path in the POI filesystem hierarchy. - * - * @param stream The stream. - * - * @param nrOfBytes The maximum number of bytes to display in a - * dump starting at the beginning of the stream. - */ - public DocumentDescriptor(final String name, - final POIFSDocumentPath path, - final DocumentInputStream stream, - final int nrOfBytes) - { - this.name = name; - this.path = path; - this.stream = stream; - try - { - size = stream.available(); - if (stream.markSupported()) - { - stream.mark(nrOfBytes); - final byte[] b = new byte[nrOfBytes]; - final int read = stream.read(b, 0, Math.min(size, b.length)); - bytes = new byte[read]; - System.arraycopy(b, 0, bytes, 0, read); - stream.reset(); - } - } - catch (IOException ex) - { - System.out.println(ex); - } - } - -} diff --git a/src/examples/src/org/apache/poi/poifs/poibrowser/DocumentDescriptorRenderer.java b/src/examples/src/org/apache/poi/poifs/poibrowser/DocumentDescriptorRenderer.java deleted file mode 100644 index de1204e77..000000000 --- a/src/examples/src/org/apache/poi/poifs/poibrowser/DocumentDescriptorRenderer.java +++ /dev/null @@ -1,79 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.poibrowser; - -import java.awt.*; -import javax.swing.*; -import javax.swing.tree.*; - -import org.apache.poi.util.HexDump; - -/** - *

    {@link TreeCellRenderer} for a {@link DocumentDescriptor}. The - * renderer is extremly rudimentary since displays only the document's - * name, its size and its fist few bytes.

    - */ -public class DocumentDescriptorRenderer extends DefaultTreeCellRenderer -{ - - @Override - public Component getTreeCellRendererComponent(final JTree tree, - final Object value, - final boolean selectedCell, - final boolean expanded, - final boolean leaf, - final int row, - final boolean hasCellFocus) - { - final DocumentDescriptor d = (DocumentDescriptor) - ((DefaultMutableTreeNode) value).getUserObject(); - final JPanel p = new JPanel(); - final JTextArea text = new JTextArea(); - text.append(renderAsString(d)); - text.setFont(new Font("Monospaced", Font.PLAIN, 10)); - p.add(text); - if (selectedCell) { - Util.invert(text); - } - return p; - } - - - /** - *

    Renders {@link DocumentDescriptor} as a string.

    - */ - protected String renderAsString(final DocumentDescriptor d) - { - final StringBuilder b = new StringBuilder(); - b.append("Name: "); - b.append(d.name); - b.append(" "); - b.append(HexDump.toHex(d.name)); - b.append("\n"); - - b.append("Size: "); - b.append(d.size); - b.append(" bytes\n"); - - b.append("First bytes: "); - b.append(HexDump.toHex(d.bytes)); - - return b.toString(); - } - -} diff --git a/src/examples/src/org/apache/poi/poifs/poibrowser/ExtendableTreeCellRenderer.java b/src/examples/src/org/apache/poi/poifs/poibrowser/ExtendableTreeCellRenderer.java deleted file mode 100644 index dbb759c9c..000000000 --- a/src/examples/src/org/apache/poi/poifs/poibrowser/ExtendableTreeCellRenderer.java +++ /dev/null @@ -1,144 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.poibrowser; - -import java.awt.*; -import javax.swing.*; -import javax.swing.tree.*; -import java.util.*; - -/** - *

    This is a {@link TreeCellRenderer} implementation which is able - * to render arbitrary objects. The {@link ExtendableTreeCellRenderer} - * does not do the rendering itself but instead dispatches to - * class-specific renderers. A class/renderer pair must be registered - * using the {@link #register} method. If a class has no registered - * renderer, the renderer of its closest superclass is used. Since the - * {@link ExtendableTreeCellRenderer} always has a default renderer - * for the {@link Object} class, rendering is always possible. The - * default {@link Object} renderer can be replaced by another renderer - * but it cannot be unregistered.

    - */ -public class ExtendableTreeCellRenderer implements TreeCellRenderer -{ - - /** - *

    Maps classes to renderers.

    - */ - protected Map,TreeCellRenderer> renderers; - - - - public ExtendableTreeCellRenderer() - { - renderers = new HashMap,TreeCellRenderer>(); - register(Object.class, new DefaultTreeCellRenderer() - { - @Override - public Component getTreeCellRendererComponent - (JTree tree, Object value, boolean selectedCell, - boolean expanded, boolean leaf, int row, boolean hasCellFocus) - { - final String s = value.toString(); - final JLabel l = new JLabel(s + " "); - if (selected) - { - Util.invert(l); - l.setOpaque(true); - } - return l; - } - }); - } - - - - /** - *

    Registers a renderer for a class.

    - **/ - public void register(final Class c, final TreeCellRenderer renderer) - { - renderers.put(c, renderer); - } - - - - /** - *

    Unregisters a renderer for a class. The renderer for the - * {@link Object} class cannot be unregistered.

    - */ - public void unregister(final Class c) - { - if (c == Object.class) - throw new IllegalArgumentException - ("Renderer for Object cannot be unregistered."); - renderers.put(c, null); - } - - - - /** - *

    Renders an object in a tree cell depending of the object's - * class.

    - * - * @see TreeCellRenderer#getTreeCellRendererComponent - */ - @Override - public Component getTreeCellRendererComponent - (final JTree tree, final Object value, final boolean selected, - final boolean expanded, final boolean leaf, final int row, - final boolean hasFocus) - { - final String NULL = "null"; - TreeCellRenderer r; - Object userObject; - if (value == null) - userObject = NULL; - else - { - userObject = ((DefaultMutableTreeNode) value).getUserObject(); - if (userObject == null) - userObject = NULL; - } - r = findRenderer(userObject.getClass()); - return r.getTreeCellRendererComponent - (tree, value, selected, expanded, leaf, row, - hasFocus); - } - - - - /** - *

    Find the renderer for the specified class.

    - */ - protected TreeCellRenderer findRenderer(final Class c) - { - final TreeCellRenderer r = renderers.get(c); - if (r != null) - /* The class has a renderer. */ - return r; - - /* The class has no renderer, try the superclass, if any. */ - final Class superclass = c.getSuperclass(); - if (superclass != null) { - return findRenderer(superclass); - } - return null; - } - -} diff --git a/src/examples/src/org/apache/poi/poifs/poibrowser/POIBrowser.java b/src/examples/src/org/apache/poi/poifs/poibrowser/POIBrowser.java deleted file mode 100644 index ec84847d6..000000000 --- a/src/examples/src/org/apache/poi/poifs/poibrowser/POIBrowser.java +++ /dev/null @@ -1,128 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.poibrowser; - -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.io.FileInputStream; -import java.io.IOException; - -import javax.swing.JFrame; -import javax.swing.JScrollPane; -import javax.swing.JTree; -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.DefaultTreeModel; -import javax.swing.tree.MutableTreeNode; - -import org.apache.poi.poifs.eventfilesystem.POIFSReader; - -/** - *

    The main class of the POI Browser. It shows the structure of POI - * filesystems (Microsoft Office documents) in a {@link - * JTree}. Specify their filenames on the command line!

    - * - * @see POIFSReader - */ -@SuppressWarnings("serial") -public class POIBrowser extends JFrame -{ - - /** - *

    The tree's root node must be visible to all methods.

    - */ - protected MutableTreeNode rootNode; - - - - /** - *

    Takes a bunch of file names as command line parameters, - * opens each of them as a POI filesystem and displays their - * internal structures in a {@link JTree}.

    - */ - public static void main(String[] args) - { - new POIBrowser().run(args); - } - - - - protected void run(String[] args) - { - addWindowListener(new WindowAdapter() - { - @Override - public void windowClosing(WindowEvent e) - { - System.exit(0); - } - }); - - /* Create the tree model with a root node. The latter is - * invisible but it must be present because a tree model - * always needs a root. */ - rootNode = new DefaultMutableTreeNode("POI Filesystems"); - DefaultTreeModel treeModel = new DefaultTreeModel(rootNode); - - /* Create the tree UI element. */ - final JTree treeUI = new JTree(treeModel); - getContentPane().add(new JScrollPane(treeUI)); - - /* Add the POI filesystems to the tree. */ - int displayedFiles = 0; - for (int i = 0; i < args.length; i++) - { - final String filename = args[i]; - try { - FileInputStream fis = new FileInputStream(filename); - POIFSReader r = new POIFSReader(); - r.registerListener(new TreeReaderListener(filename, rootNode)); - r.read(fis); - fis.close(); - displayedFiles++; - } catch (IOException ex) { - System.err.println(filename + ": " + ex); - } catch (Exception t) { - System.err.println("Unexpected exception while reading \"" + - filename + "\":"); - t.printStackTrace(System.err); - } - } - - /* Exit if there is no file to display (none specified or only - * files with problems). */ - if (displayedFiles == 0) - { - System.out.println("No POI filesystem(s) to display."); - System.exit(0); - } - - /* Make the tree UI element visible. */ - treeUI.setRootVisible(true); - treeUI.setShowsRootHandles(true); - ExtendableTreeCellRenderer etcr = new ExtendableTreeCellRenderer(); - etcr.register(DocumentDescriptor.class, - new DocumentDescriptorRenderer()); - etcr.register(PropertySetDescriptor.class, - new PropertySetDescriptorRenderer()); - treeUI.setCellRenderer(etcr); - setSize(600, 450); - setTitle("POI Browser 0.09"); - setVisible(true); - } - -} diff --git a/src/examples/src/org/apache/poi/poifs/poibrowser/PropertySetDescriptor.java b/src/examples/src/org/apache/poi/poifs/poibrowser/PropertySetDescriptor.java deleted file mode 100644 index f9658ae03..000000000 --- a/src/examples/src/org/apache/poi/poifs/poibrowser/PropertySetDescriptor.java +++ /dev/null @@ -1,75 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.poibrowser; - -import java.io.IOException; -import java.io.UnsupportedEncodingException; - -import org.apache.poi.hpsf.MarkUnsupportedException; -import org.apache.poi.hpsf.NoPropertySetStreamException; -import org.apache.poi.hpsf.PropertySet; -import org.apache.poi.hpsf.PropertySetFactory; -import org.apache.poi.poifs.filesystem.DocumentInputStream; -import org.apache.poi.poifs.filesystem.POIFSDocumentPath; - -/** - *

    Describes the most important (whatever that is) features of a - * stream containing a {@link PropertySet}.

    - */ -public class PropertySetDescriptor extends DocumentDescriptor -{ - - protected PropertySet propertySet; - - /** - *

    Returns this {@link PropertySetDescriptor}'s {@link - * PropertySet}.

    - */ - public PropertySet getPropertySet() - { - return propertySet; - } - - - - /** - *

    Creates a {@link PropertySetDescriptor} by reading a {@link - * PropertySet} from a {@link DocumentInputStream}.

    - * - * @param name The stream's name. - * - * @param path The stream's path in the POI filesystem hierarchy. - * - * @param stream The stream. - * - * @param nrOfBytesToDump The maximum number of bytes to display in a - * dump starting at the beginning of the stream. - */ - public PropertySetDescriptor(final String name, - final POIFSDocumentPath path, - final DocumentInputStream stream, - final int nrOfBytesToDump) - throws NoPropertySetStreamException, - MarkUnsupportedException, UnsupportedEncodingException, - IOException - { - super(name, path, stream, nrOfBytesToDump); - propertySet = PropertySetFactory.create(stream); - } - -} diff --git a/src/examples/src/org/apache/poi/poifs/poibrowser/PropertySetDescriptorRenderer.java b/src/examples/src/org/apache/poi/poifs/poibrowser/PropertySetDescriptorRenderer.java deleted file mode 100644 index 8ce336f24..000000000 --- a/src/examples/src/org/apache/poi/poifs/poibrowser/PropertySetDescriptorRenderer.java +++ /dev/null @@ -1,170 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.poibrowser; - -import java.awt.Color; -import java.awt.Component; -import java.awt.Font; -import java.util.Iterator; -import java.util.List; - -import javax.swing.JPanel; -import javax.swing.JTextArea; -import javax.swing.JTree; -import javax.swing.tree.DefaultMutableTreeNode; - -import org.apache.poi.hpsf.Property; -import org.apache.poi.hpsf.PropertySet; -import org.apache.poi.hpsf.Section; -import org.apache.poi.hpsf.SummaryInformation; -import org.apache.poi.util.HexDump; - -/** - *

    Renders a {@link PropertySetDescriptor} by more or less dumping - * the stuff into a {@link JTextArea}.

    - */ -public class PropertySetDescriptorRenderer extends DocumentDescriptorRenderer -{ - - @Override - public Component getTreeCellRendererComponent(final JTree tree, - final Object value, - final boolean selectedCell, - final boolean expanded, - final boolean leaf, - final int row, - final boolean hasCellFocus) - { - final PropertySetDescriptor d = (PropertySetDescriptor) - ((DefaultMutableTreeNode) value).getUserObject(); - final PropertySet ps = d.getPropertySet(); - final JPanel p = new JPanel(); - final JTextArea text = new JTextArea(); - text.setBackground(new Color(200, 255, 200)); - text.setFont(new Font("Monospaced", Font.PLAIN, 10)); - text.append(renderAsString(d)); - text.append("\nByte order: "); - text.append(HexDump.toHex((short) ps.getByteOrder())); - text.append("\nFormat: "); - text.append(HexDump.toHex((short) ps.getFormat())); - text.append("\nOS version: "); - text.append(HexDump.toHex(ps.getOSVersion())); - text.append("\nClass ID: "); - text.append(HexDump.toHex(ps.getClassID().getBytes())); - text.append("\nSection count: " + ps.getSectionCount()); - text.append(sectionsToString(ps.getSections())); - p.add(text); - - if (ps instanceof SummaryInformation) - { - /* Use the convenience methods. */ - final SummaryInformation si = (SummaryInformation) ps; - text.append("\n"); - text.append("\nTitle: " + si.getTitle()); - text.append("\nSubject: " + si.getSubject()); - text.append("\nAuthor: " + si.getAuthor()); - text.append("\nKeywords: " + si.getKeywords()); - text.append("\nComments: " + si.getComments()); - text.append("\nTemplate: " + si.getTemplate()); - text.append("\nLast Author: " + si.getLastAuthor()); - text.append("\nRev. Number: " + si.getRevNumber()); - text.append("\nEdit Time: " + si.getEditTime()); - text.append("\nLast Printed: " + si.getLastPrinted()); - text.append("\nCreate Date/Time: " + si.getCreateDateTime()); - text.append("\nLast Save Date/Time: " + si.getLastSaveDateTime()); - text.append("\nPage Count: " + si.getPageCount()); - text.append("\nWord Count: " + si.getWordCount()); - text.append("\nChar Count: " + si.getCharCount()); - // text.append("\nThumbnail: " + si.getThumbnail()); - text.append("\nApplication Name: " + si.getApplicationName()); - text.append("\nSecurity: " + si.getSecurity()); - } - - if (selectedCell) - Util.invert(text); - return p; - } - - - - /** - *

    Returns a string representation of a list of {@link - * Section}s.

    - */ - protected String sectionsToString(final List
    sections) - { - final StringBuffer b = new StringBuffer(); - int count = 1; - for (Iterator
    i = sections.iterator(); i.hasNext();) - { - Section s = i.next(); - String d = toString(s, "Section " + count++); - b.append(d); - } - return b.toString(); - } - - - - /** - *

    Returns a string representation of a {@link Section}.

    - * @param s the section - * @param name the section's name - * @return a string representation of the {@link Section} - */ - protected String toString(final Section s, final String name) - { - final StringBuffer b = new StringBuffer(); - b.append("\n" + name + " Format ID: "); - b.append(HexDump.toHex(s.getFormatID().getBytes())); - b.append("\n" + name + " Offset: " + s.getOffset()); - b.append("\n" + name + " Section size: " + s.getSize()); - b.append("\n" + name + " Property count: " + s.getPropertyCount()); - - final Property[] properties = s.getProperties(); - for (int i = 0; i < properties.length; i++) - { - final Property p = properties[i]; - final long id = p.getID(); - final long type = p.getType(); - final Object value = p.getValue(); - b.append('\n'); - b.append(name); - b.append(", Name: "); - b.append(id); - b.append(" ("); - b.append(s.getPIDString(id)); - b.append("), Type: "); - b.append(type); - b.append(", Value: "); - if (value instanceof byte[]) { - byte[] buf = new byte[4]; - System.arraycopy(value, 0, buf, 0, 4); - b.append(HexDump.toHex(buf)); - b.append(' '); - System.arraycopy(value, ((byte[])value).length - 4, buf, 0, 4); - } else if (value != null) { - b.append(value.toString()); - } else { - b.append("null"); - } - } - return b.toString(); - } - -} diff --git a/src/examples/src/org/apache/poi/poifs/poibrowser/TreeReaderListener.java b/src/examples/src/org/apache/poi/poifs/poibrowser/TreeReaderListener.java deleted file mode 100644 index a1fdc726f..000000000 --- a/src/examples/src/org/apache/poi/poifs/poibrowser/TreeReaderListener.java +++ /dev/null @@ -1,215 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.poibrowser; - -import java.util.HashMap; -import java.util.Map; - -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.MutableTreeNode; - -import org.apache.poi.hpsf.HPSFException; -import org.apache.poi.poifs.eventfilesystem.POIFSReaderEvent; -import org.apache.poi.poifs.eventfilesystem.POIFSReaderListener; -import org.apache.poi.poifs.filesystem.DocumentInputStream; -import org.apache.poi.poifs.filesystem.POIFSDocumentPath; - -/** - *

    Organizes document information in a tree model in order to be - * e.g. displayed in a Swing {@link javax.swing.JTree}. An instance of this - * class is created with a root tree node ({@link MutableTreeNode}) and - * registered as a {@link POIFSReaderListener} with a {@link - * org.apache.poi.poifs.eventfilesystem.POIFSReader}. While the latter processes - * a POI filesystem it calls this class' {@link #processPOIFSReaderEvent} for - * each document it has been registered for. This method appends the document it - * processes at the appropriate position into the tree rooted at the - * above mentioned root tree node.

    - * - *

    The root tree node should be the root tree node of a {@link - * javax.swing.tree.TreeModel}.

    - * - *

    A top-level element in the tree model, i.e. an immediate child - * node of the root node, describes a POI filesystem as such. It is - * suggested to use the file's name (as seen by the operating system) - * but it could be any other string.

    - * - *

    The value of a tree node is a {@link DocumentDescriptor}. Unlike - * a {@link org.apache.poi.poifs.filesystem.POIFSDocument} which may be as heavy - * as many megabytes, an instance of {@link DocumentDescriptor} is a - * light-weight object and contains only some meta-information about a - * document.

    - */ -public class TreeReaderListener implements POIFSReaderListener -{ - - /** - *

    The tree's root node. POI filesystems get attached to this - * node as children.

    - */ - protected MutableTreeNode rootNode; - - /** - *

    Maps filenames and POI document paths to their associated - * tree nodes.

    - */ - protected Map pathToNode; - - /** - *

    The name of the file this {@link TreeReaderListener} - * processes. It is used to identify a top-level element in the - * tree. Alternatively any other string can be used. It is just a - * label which should identify a POI filesystem.

    - */ - protected String filename; - - - - /** - *

    Creates a {@link TreeReaderListener} which should then be - * registered with a - * {@link org.apache.poi.poifs.eventfilesystem.POIFSReader}.

    - * - * @param filename The name of the POI filesystem, i.e. the name - * of the file the POI filesystem resides in. Alternatively any - * other string can be used. - * - * @param rootNode All document information will be attached as - * descendands to this tree node. - */ - public TreeReaderListener(final String filename, - final MutableTreeNode rootNode) - { - this.filename = filename; - this.rootNode = rootNode; - pathToNode = new HashMap(15); // Should be a reasonable guess. - } - - - - /**

    The number of bytes to dump.

    */ - private int nrOfBytes = 50; - - public void setNrOfBytes(final int nrOfBytes) - { - this.nrOfBytes = nrOfBytes; - } - - public int getNrOfBytes() - { - return nrOfBytes; - } - - - - /** - *

    A document in the POI filesystem has been opened for - * reading. This method retrieves properties of the document and - * adds them to a tree model.

    - */ - @Override - public void processPOIFSReaderEvent(final POIFSReaderEvent event) - { - DocumentDescriptor d; - final DocumentInputStream is = event.getStream(); - if (!is.markSupported()) { - throw new UnsupportedOperationException(is.getClass().getName() + - " does not support mark()."); - } - - /* Try do handle this document as a property set. We receive - * an exception if is no property set and handle it as a - * document of some other format. We are not concerned about - * that document's details. */ - try - { - d = new PropertySetDescriptor(event.getName(), event.getPath(), - is, nrOfBytes); - } - catch (HPSFException ex) - { - d = new DocumentDescriptor(event.getName(), event.getPath(), - is, nrOfBytes); - } - catch (Exception t) - { - throw new RuntimeException("Unexpected exception while processing " + event.getName() + " in " + event.getPath(), t); - } - - is.close(); - - final MutableTreeNode parentNode = getNode(d.path, filename, rootNode); - final MutableTreeNode nameNode = new DefaultMutableTreeNode(d.name); - parentNode.insert(nameNode, 0); - final MutableTreeNode dNode = new DefaultMutableTreeNode(d); - nameNode.insert(dNode, 0); - } - - - - /** - *

    Locates the parent node for a document entry in the tree - * model. If the parent node does not yet exist it will be - * created, too. This is done recursively, if needed.

    - * - * @param path The tree node for this path is located. - * - * @param fsName The name of the POI filesystem. This is just a - * string which is displayed in the tree at the top lovel. - * - * @param root The root node. - */ - private MutableTreeNode getNode(final POIFSDocumentPath path, - final String fsName, - final MutableTreeNode root) - { - MutableTreeNode n = pathToNode.get(path); - if (n != null) { - /* Node found in map, just return it. */ - return n; - } - if (path.length() == 0) - { - /* This is the root path of the POI filesystem. Its tree - * node is resp. must be located below the tree node of - * the POI filesystem itself. This is a tree node with the - * POI filesystem's name (this the operating system file's - * name) as its key it the path-to-node map. */ - n = pathToNode.get(fsName); - if (n == null) - { - /* A tree node for the POI filesystem does not yet - * exist. */ - n = new DefaultMutableTreeNode(fsName); - pathToNode.put(fsName, n); - root.insert(n, 0); - } - return n; - } - /* else - The path is somewhere down in the POI filesystem's - * hierarchy. We need the tree node of this path's parent - * and attach our new node to it. */ - final String name = path.getComponent(path.length() - 1); - final POIFSDocumentPath parentPath = path.getParent(); - final MutableTreeNode parentNode = - getNode(parentPath, fsName, root); - n = new DefaultMutableTreeNode(name); - pathToNode.put(path, n); - parentNode.insert(n, 0); - return n; - } -} diff --git a/src/examples/src/org/apache/poi/poifs/poibrowser/Util.java b/src/examples/src/org/apache/poi/poifs/poibrowser/Util.java deleted file mode 100644 index 8e86b1873..000000000 --- a/src/examples/src/org/apache/poi/poifs/poibrowser/Util.java +++ /dev/null @@ -1,41 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.poibrowser; - -import java.awt.*; -import javax.swing.*; - -/** - *

    Contains various (well, just one at the moment) static utility - * methods.

    - */ -public class Util { - - /** - *

    Makes a Swing component inverted by swapping its foreground - * and background colors. Hint: Depending on your needs it might - * also be a good idea to call c.setOpaque(true).

    - */ - public static void invert(JComponent c) { - Color invBackground = c.getForeground(); - Color invForeground = c.getBackground(); - c.setBackground(invBackground); - c.setForeground(invForeground); - } -} - diff --git a/src/examples/src/org/apache/poi/ss/examples/AddDimensionedImage.java b/src/examples/src/org/apache/poi/ss/examples/AddDimensionedImage.java deleted file mode 100644 index 4e644cda8..000000000 --- a/src/examples/src/org/apache/poi/ss/examples/AddDimensionedImage.java +++ /dev/null @@ -1,1025 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - - -package org.apache.poi.ss.examples; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.net.URL; -import java.util.Locale; - -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.ClientAnchor; -import org.apache.poi.ss.usermodel.ClientAnchor.AnchorType; -import org.apache.poi.ss.usermodel.Drawing; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.util.IOUtils; - - -/** - * Demonstrates how to add an image to a worksheet and set that images size - * to a specific number of millimetres irrespective of the width of the columns - * or height of the rows. Overridden methods are provided so that the location - * of the image - the cells row and column coordinates that define the top - * left hand corners of the image - can be identified either in the familiar - * Excel manner - A1 for instance - or using POI's methodology of a column and - * row index where 0, 0 would indicate cell A1. - * - * The best way to make use of these techniques is to delay adding the image to - * the sheet until all other work has been completed. That way, the sizes of - * all rows and columns will have been adjusted - assuming that step was - * necessary. Even though the anchors type is set to prevent the image moving - * or re-sizing, this setting does not have any effect until the sheet is being - * viewed using the Excel application. - * - * The key to the process is the ClientAnchor class. It defines methods that allow - * us to define the location of an image by specifying the following; - * - * * How far - in terms of coordinate positions - the image should be inset - * from the left hand border of a cell. - * * How far - in terms of coordinate positions - the image should be inset - * from the from the top of the cell. - * * How far - in terms of coordinate positions - the right hand edge of - * the image should protrude into a cell (measured from the cells left hand - * edge to the images right hand edge). - * * How far - in terms of coordinate positions - the bottom edge of the - * image should protrude into a row (measured from the cells top edge to - * the images bottom edge). - * * The index of the column that contains the cell whose top left hand - * corner should be aligned with the top left hand corner of the image. - * * The index of the row that contains the cell whose top left hand corner - * should be aligned with the images top left hand corner. - * * The index of the column that contains the cell whose top left hand - * corner should be aligned with the images bottom right hand corner - * * The index number of the row that contains the cell whose top left - * hand corner should be aligned with the images bottom right hand corner. - * - * It can be used to add an image into cell A1, for example, in the following - * manner; - * - * ClientAnchor anchor = sheet.getWorkbook().getCreationHelper().createClientAnchor(); - * - * anchor.setDx1(0); - * anchor.setDy1(0); - * anchor.setDx2(0); - * anchor.setDy2(0); - * anchor.setCol1(0); - * anchor.setRow1(0); - * anchor.setCol2(1); - * anchor.setRow2(1); - * - * Taken together, the first four methods define the locations of the top left - * and bottom right hand corners of the image if you imagine that the image is - * represented by a simple rectangle. The setDx1() and setDy1() methods locate - * the top left hand corner of the image while setDx2() and and Dy2() locate the - * bottom right hand corner of the image. An individual image can be inserted - * into a single cell or is can lie across many cells and the latter four methods - * are used to define just where the image should be positioned. They do this by - * again by identifying where the top left and bottom right hand corners of the - * image should be located but this time in terms of the indexes of the cells - * in which those corners should be located. The setCol1() and setRow1() methods - * together identify the cell that should contain the top left hand corner of - * the image while setCol2() and setRow2() do the same for the images bottom - * right hand corner. - * - * Knowing that, it is possible to look again at the example above and to see - * that the top left hand corner of the image will be located in cell A1 (0, 0) - * and it will be aligned with the very top left hand corner of the cell. Likewise, - * the bottom right hand corner of the image will be located in cell B2 (1, 1) and - * it will again be aligned with the top left hand corner of the cell. This has the - * effect of making the image seem to occupy the whole of cell A1. Interestingly, it - * also has an effect on the images resizing behaviour because testing has - * demonstrated that if the image is wholly contained within one cell and is not - * 'attached' for want of a better word, to a neighbouring cell, then that image - * will not increase in size in response to the user dragging the column wider - * or the cell higher. - * - * The following example demonstrates a slightly different way to insert an - * image into cell A1 and to ensure that it occupies the whole of the cell. This - * is accomplished by specifying the the images bottom right hand corner should be - * aligned with the bottom right hand corner of the cell. It is also a case - * where the image will not increase in size if the user increases the size of - * the enclosing cell - irrespective of the anchors type - but it will reduce in - * size if the cell is made smaller. - * - * ClientAnchor anchor = sheet.getWorkbook().getCreationHelper().createClientAnchor(); - * - * anchor.setDx1(0); - * anchor.setDy1(0); - * anchor.setDx2(1023); - * anchor.setDy2(255); - * anchor.setCol1(0); - * anchor.setRow1(0); - * anchor.setCol2(0); - * anchor.setRow2(0); - * - * Note that the final four method calls all pass the same value and seem to - * indicate that the images top left hand corner is aligned with the top left - * hand corner of cell A1 and that it's bottom right hand corner is also - * aligned with the top left hand corner of cell A1. Yet, running this code - * would see the image fully occupying cell A1. That is the result of the - * values passed to parameters three and four; these I have referred to as - * determining the images coordinates within the cell. They indicate that the - * image should occupy - in order - the full width of the column and the full - * height of the row. - * - * The co-ordinate values shown are the maxima; and they are independent of - * row height/column width and of the font used. Passing 255 will always result - * in the image occupying the full height of the row and passing 1023 will - * always result in the image occupying the full width of the column. They help - * in situations where an image is larger than a column/row and must overlap - * into the next column/row. Using them does mean, however, that it is often - * necessary to perform conversions between Excels characters units, points, - * pixels and millimetres in order to establish how many rows/columns an image - * should occupy and just what the various insets ought to be. - * - * Note that the setDx1(int) and setDy1(int) methods of the ClientAchor class - * are not made use of in the code that follows. It would be fairly trivial - * however to extend this example further and provide methods that would centre - * an image within a cell or allow the user to specify that a plain border a - * fixed number of millimetres wide should wrap around the image. Those first - * two parameters would make this sort of functionality perfectly possible. - * - * Owing to the various conversions used, the actual size of the image may vary - * from that required; testing has so far found this to be in the region of - * plus or minus two millimetres. Most likely by modifying the way the - * calculations are performed - possibly using double(s) throughout and - * rounding the values at the correct point - it is likely that these errors - * could be reduced or removed. - * - * A note concerning Excels image resizing behaviour. The ClientAnchor - * class contains a method called setAnchorType(int) which can be used to - * determine how Excel will resize an image in response to the user increasing - * or decreasing the dimensions of the cell containing the image. There are - * three values that can be passed to this method; 0 = To move and size the - * image with the cell, 2 = To move but don't size the image with the cell, - * 3 = To prevent the image from moving or being resized along with the cell. If - * an image is inserted using this class and placed into a single cell then if - * the setAnchorType(int) method is called and a value of either 0 or 2 passed - * to it, the resultant resizing behaviour may be a surprise. The image will not - * grow in size of the column is made wider or the row higher but it will shrink - * if the columns width or rows height are reduced. - * - * @author Mark Beardsley [msb at apache.org] and Mark Southern [southern at scripps.edu] - * @version 1.00 5th August 2009. - * 2.00 26th February 2010. - * Ported to make use of the the SS usermodel classes. - * Ability to reuse the Drawing Patriarch so that multiple images - * can be inserted without unintentionally erasing earlier images. - * Check on image type added; i.e. jpg, jpeg or png. - * The String used to contain the files name is now converted - * into a URL. - * 2.10 17th May 2012 - * Corrected gross error that occurred when using the code with - * XSSF or SXSSF workbooks. In short, the code did not correctly - * calculate the size of the image(s) owing to the use of EMUs - * within the OOXML file format. That problem has largely been - * corrected although it should be mentioned that images are not - * sized with the same level of accuracy. Discrepancies of up to - * 2mm have been noted in testing. Further investigation will - * continue to rectify this issue. - */ -public class AddDimensionedImage { - - // Four constants that determine how - and indeed whether - the rows - // and columns an image may overlie should be expanded to accomodate that - // image. - // Passing EXPAND_ROW will result in the height of a row being increased - // to accomodate the image if it is not already larger. The image will - // be layed across one or more columns. - // Passing EXPAND_COLUMN will result in the width of the column being - // increased to accomodate the image if it is not already larger. The image - // will be layed across one or many rows. - // Passing EXPAND_ROW_AND_COLUMN will result in the height of the row - // bing increased along with the width of the column to accomdate the - // image if either is not already larger. - // Passing OVERLAY_ROW_AND_COLUMN will result in the image being layed - // over one or more rows and columns. No row or column will be resized, - // instead, code will determine how many rows and columns the image should - // overlie. - public static final int EXPAND_ROW = 1; - public static final int EXPAND_COLUMN = 2; - public static final int EXPAND_ROW_AND_COLUMN = 3; - public static final int OVERLAY_ROW_AND_COLUMN = 7; - - // Modified to support EMU - English Metric Units - used within the OOXML - // workbooks, this multoplier is used to convert between measurements in - // millimetres and in EMUs - private static final int EMU_PER_MM = 36000; - - /** - * Add an image to a worksheet. - * - * @param cellNumber A String that contains the location of the cell whose - * top left hand corner should be aligned with the top - * left hand corner of the image; for example "A1", "A2" - * etc. This is to support the familiar Excel syntax. - * Whilst images are are not actually inserted into cells - * this provides a convenient method of indicating where - * the image should be positioned on the sheet. - * @param sheet A reference to the sheet that contains the cell referenced - * above. - * @param drawing An instance of the DrawingPatriarch class. This is now - * passed into the method where it was, previously, recovered - * from the sheet in order to allow multiple pictures be - * inserted. If the patriarch was not 'cached in this manner - * each time it was created any previously positioned images - * would be simply over-written. - * @param imageFile An instance of the URL class that encapsulates the name - * of and path to the image that is to be 'inserted into' - * the sheet. - * @param reqImageWidthMM A primitive double that contains the required - * width of the image in millimetres. - * @param reqImageHeightMM A primitive double that contains the required - * height of the image in millimetres. - * @param resizeBehaviour A primitive int whose value will determine how - * the code should react if the image is larger than - * the cell referenced by the cellNumber parameter. - * Four constants are provided to determine what - * should happen; - * AddDimensionedImage.EXPAND_ROW - * AddDimensionedImage.EXPAND_COLUMN - * AddDimensionedImage.EXPAND_ROW_AND_COLUMN - * AddDimensionedImage.OVERLAY_ROW_AND_COLUMN - * @throws java.io.FileNotFoundException If the file containing the image - * cannot be located. - * @throws java.io.IOException If a problem occurs whilst reading the file - * of image data. - * @throws java.lang.IllegalArgumentException If an invalid value is passed - * to the resizeBehaviour - * parameter. - */ - public void addImageToSheet(String cellNumber, Sheet sheet, Drawing drawing, - URL imageFile, double reqImageWidthMM, double reqImageHeightMM, - int resizeBehaviour) throws IOException, IllegalArgumentException { - // Convert the String into column and row indices then chain the - // call to the overridden addImageToSheet() method. - CellReference cellRef = new CellReference(cellNumber); - this.addImageToSheet(cellRef.getCol(), cellRef.getRow(), sheet, drawing, - imageFile, reqImageWidthMM, reqImageHeightMM,resizeBehaviour); - } - - /** - * Add an image to a worksheet. - * - * @param colNumber A primitive int that contains the index number of a - * column on the worksheet; POI column indices are zero - * based. Together with the rowNumber parameter's value, - * this parameter identifies a cell on the worksheet. The - * images top left hand corner will be aligned with the - * top left hand corner of this cell. - * @param rowNumber A primitive int that contains the index number of a row - * on the worksheet; POI row indices are zero based. - * Together with the rowNumber parameter's value, this - * parameter identifies a cell on the worksheet. The - * images top left hand corner will be aligned with the - * top left hand corner of this cell. - * @param sheet A reference to the sheet that contains the cell identified - * by the two parameters above. - * @param drawing An instance of the DrawingPatriarch class. This is now - * passed into the method where it was, previously, recovered - * from the sheet in order to allow multiple pictures be - * inserted. If the patriarch was not 'cached in this manner - * each time it was created any previously positioned images - * would be simply over-written. - * @param imageFile An instance of the URL class that encapsulates the name - * of and path to the image that is to be 'inserted into' - * the sheet. - * @param reqImageWidthMM A primitive double that contains the required - * width of the image in millimetres. - * @param reqImageHeightMM A primitive double that contains the required - * height of the image in millimetres. - * @param resizeBehaviour A primitive int whose value will determine how - * the code should react if the image is larger than - * the cell referenced by the colNumber and - * rowNumber parameters. Four constants are provided - * to determine what should happen; - * AddDimensionedImage.EXPAND_ROW - * AddDimensionedImage.EXPAND_COLUMN - * AddDimensionedImage.EXPAND_ROW_AND_COLUMN - * AddDimensionedImage.OVERLAY_ROW_AND_COLUMN - * @throws java.io.FileNotFoundException If the file containing the image - * cannot be located. - * @throws java.io.IOException If a problem occurs whilst reading the file - * of image data. - * @throws java.lang.IllegalArgumentException If an invalid value is passed - * to the resizeBehaviour - * parameter or if the extension - * of the image file indicates that - * it is of a type that cannot - * currently be added to the worksheet. - */ - public void addImageToSheet(int colNumber, int rowNumber, Sheet sheet, Drawing drawing, - URL imageFile, double reqImageWidthMM, double reqImageHeightMM, - int resizeBehaviour) throws IOException, - IllegalArgumentException { - ClientAnchor anchor = null; - ClientAnchorDetail rowClientAnchorDetail = null; - ClientAnchorDetail colClientAnchorDetail = null; - int imageType = 0; - - // Validate the resizeBehaviour parameter. - if((resizeBehaviour != AddDimensionedImage.EXPAND_COLUMN) && - (resizeBehaviour != AddDimensionedImage.EXPAND_ROW) && - (resizeBehaviour != AddDimensionedImage.EXPAND_ROW_AND_COLUMN) && - (resizeBehaviour != AddDimensionedImage.OVERLAY_ROW_AND_COLUMN)) { - throw new IllegalArgumentException("Invalid value passed to the " + - "resizeBehaviour parameter of AddDimensionedImage.addImageToSheet()"); - } - - // Call methods to calculate how the image and sheet should be - // manipulated to accomodate the image; columns and then rows. - colClientAnchorDetail = this.fitImageToColumns(sheet, colNumber, - reqImageWidthMM, resizeBehaviour); - rowClientAnchorDetail = this.fitImageToRows(sheet, rowNumber, - reqImageHeightMM, resizeBehaviour); - - // Having determined if and how to resize the rows, columns and/or the - // image, create the ClientAnchor object to position the image on - // the worksheet. Note how the two ClientAnchorDetail records are - // interrogated to recover the row/column co-ordinates and any insets. - // The first two parameters are not used currently but could be if the - // need arose to extend the functionality of this code by adding the - // ability to specify that a clear 'border' be placed around the image. - anchor = sheet.getWorkbook().getCreationHelper().createClientAnchor(); - - anchor.setDx1(0); - anchor.setDy1(0); - anchor.setDx2(colClientAnchorDetail.getInset()); - anchor.setDy2(rowClientAnchorDetail.getInset()); - anchor.setCol1(colClientAnchorDetail.getFromIndex()); - anchor.setRow1(rowClientAnchorDetail.getFromIndex()); - anchor.setCol2(colClientAnchorDetail.getToIndex()); - anchor.setRow2(rowClientAnchorDetail.getToIndex()); - - // For now, set the anchor type to do not move or resize the - // image as the size of the row/column is adjusted. This could easily - // become another parameter passed to the method. Please read the note - // above regarding the behaviour of image resizing. - anchor.setAnchorType(AnchorType.MOVE_AND_RESIZE); - - // Now, add the picture to the workbook. Note that unlike the similar - // method in the HSSF Examples section, the image type is checked. First, - // the image files location is identified by interrogating the URL passed - // to the method, the images type is identified before it is added to the - // sheet. - String sURL = imageFile.toString().toLowerCase(Locale.ROOT); - if( sURL.endsWith(".png") ) { - imageType = Workbook.PICTURE_TYPE_PNG; - } - else if( sURL.endsWith(".jpg") || sURL.endsWith(".jpeg") ) { - imageType = Workbook.PICTURE_TYPE_JPEG; - } - else { - throw new IllegalArgumentException("Invalid Image file : " + - sURL); - } - int index = sheet.getWorkbook().addPicture( - IOUtils.toByteArray(imageFile.openStream()), imageType); - drawing.createPicture(anchor, index); - } - - /** - * Determines whether the sheets columns should be re-sized to accommodate - * the image, adjusts the columns width if necessary and creates then - * returns a ClientAnchorDetail object that facilitates construction of - * an ClientAnchor that will fix the image on the sheet and establish - * it's size. - * - * @param sheet A reference to the sheet that will 'contain' the image. - * @param colNumber A primitive int that contains the index number of a - * column on the sheet. - * @param reqImageWidthMM A primitive double that contains the required - * width of the image in millimetres - * @param resizeBehaviour A primitive int whose value will indicate how the - * width of the column should be adjusted if the - * required width of the image is greater than the - * width of the column. - * @return An instance of the ClientAnchorDetail class that will contain - * the index number of the column containing the cell whose top - * left hand corner also defines the top left hand corner of the - * image, the index number column containing the cell whose top - * left hand corner also defines the bottom right hand corner of - * the image and an inset that determines how far the right hand - * edge of the image can protrude into the next column - expressed - * as a specific number of coordinate positions. - */ - private ClientAnchorDetail fitImageToColumns(Sheet sheet, int colNumber, - double reqImageWidthMM, int resizeBehaviour) { - - double colWidthMM = 0.0D; - double colCoordinatesPerMM = 0.0D; - int pictureWidthCoordinates = 0; - ClientAnchorDetail colClientAnchorDetail = null; - - // Get the colum's width in millimetres - colWidthMM = ConvertImageUnits.widthUnits2Millimetres( - (short)sheet.getColumnWidth(colNumber)); - - // Check that the column's width will accomodate the image at the - // required dimension. If the width of the column is LESS than the - // required width of the image, decide how the application should - // respond - resize the column or overlay the image across one or more - // columns. - if(colWidthMM < reqImageWidthMM) { - - // Should the column's width simply be expanded? - if((resizeBehaviour == AddDimensionedImage.EXPAND_COLUMN) || - (resizeBehaviour == AddDimensionedImage.EXPAND_ROW_AND_COLUMN)) { - // Set the width of the column by converting the required image - // width from millimetres into Excel's column width units. - sheet.setColumnWidth(colNumber, - ConvertImageUnits.millimetres2WidthUnits(reqImageWidthMM)); - // To make the image occupy the full width of the column, convert - // the required width of the image into co-ordinates. This value - // will become the inset for the ClientAnchorDetail class that - // is then instantiated. - if(sheet instanceof HSSFSheet) { - colWidthMM = reqImageWidthMM; - colCoordinatesPerMM = ConvertImageUnits.TOTAL_COLUMN_COORDINATE_POSITIONS / - colWidthMM; - pictureWidthCoordinates = (int)(reqImageWidthMM * colCoordinatesPerMM); - - } - else { - pictureWidthCoordinates = (int)reqImageWidthMM * AddDimensionedImage.EMU_PER_MM; - } - colClientAnchorDetail = new ClientAnchorDetail(colNumber, - colNumber, pictureWidthCoordinates); - } - // If the user has chosen to overlay both rows and columns or just - // to expand ONLY the size of the rows, then calculate how to lay - // the image out across one or more columns. - else if ((resizeBehaviour == AddDimensionedImage.OVERLAY_ROW_AND_COLUMN) || - (resizeBehaviour == AddDimensionedImage.EXPAND_ROW)) { - colClientAnchorDetail = this.calculateColumnLocation(sheet, - colNumber, reqImageWidthMM); - } - } - // If the column is wider than the image. - else { - if(sheet instanceof HSSFSheet) { - // Mow many co-ordinate positions are there per millimetre? - colCoordinatesPerMM = ConvertImageUnits.TOTAL_COLUMN_COORDINATE_POSITIONS / - colWidthMM; - // Given the width of the image, what should be it's co-ordinate? - pictureWidthCoordinates = (int)(reqImageWidthMM * colCoordinatesPerMM); - } - else { - pictureWidthCoordinates = (int)reqImageWidthMM * - AddDimensionedImage.EMU_PER_MM; - } - colClientAnchorDetail = new ClientAnchorDetail(colNumber, - colNumber, pictureWidthCoordinates); - } - return(colClientAnchorDetail); - } - - /** - * Determines whether the sheets row should be re-sized to accomodate - * the image, adjusts the rows height if necessary and creates then - * returns a ClientAnchorDetail object that facilitates construction of - * a ClientAnchor that will fix the image on the sheet and establish - * it's size. - * - * @param sheet A reference to the sheet that will 'contain' the image. - * @param rowNumber A primitive int that contains the index number of a - * row on the sheet. - * @param reqImageHeightMM A primitive double that contains the required - * height of the image in millimetres - * @param resizeBehaviour A primitive int whose value will indicate how the - * height of the row should be adjusted if the - * required height of the image is greater than the - * height of the row. - * @return An instance of the ClientAnchorDetail class that will contain - * the index number of the row containing the cell whose top - * left hand corner also defines the top left hand corner of the - * image, the index number of the row containing the cell whose - * top left hand corner also defines the bottom right hand - * corner of the image and an inset that determines how far the - * bottom edge of the image can protrude into the next (lower) - * row - expressed as a specific number of coordinate positions. - */ - private ClientAnchorDetail fitImageToRows(Sheet sheet, int rowNumber, - double reqImageHeightMM, int resizeBehaviour) { - Row row = null; - double rowHeightMM = 0.0D; - double rowCoordinatesPerMM = 0.0D; - int pictureHeightCoordinates = 0; - ClientAnchorDetail rowClientAnchorDetail = null; - - // Get the row and it's height - row = sheet.getRow(rowNumber); - if(row == null) { - // Create row if it does not exist. - row = sheet.createRow(rowNumber); - } - - // Get the row's height in millimetres - rowHeightMM = row.getHeightInPoints() / ConvertImageUnits.POINTS_PER_MILLIMETRE; - - // Check that the row's height will accomodate the image at the required - // dimensions. If the height of the row is LESS than the required height - // of the image, decide how the application should respond - resize the - // row or overlay the image across a series of rows. - if(rowHeightMM < reqImageHeightMM) { - if((resizeBehaviour == AddDimensionedImage.EXPAND_ROW) || - (resizeBehaviour == AddDimensionedImage.EXPAND_ROW_AND_COLUMN)) { - row.setHeightInPoints((float)(reqImageHeightMM * - ConvertImageUnits.POINTS_PER_MILLIMETRE)); - if(sheet instanceof HSSFSheet) { - rowHeightMM = reqImageHeightMM; - rowCoordinatesPerMM = ConvertImageUnits.TOTAL_ROW_COORDINATE_POSITIONS / - rowHeightMM; - pictureHeightCoordinates = (int)(reqImageHeightMM * - rowCoordinatesPerMM); - } - else { - pictureHeightCoordinates = (int)(reqImageHeightMM * - AddDimensionedImage.EMU_PER_MM); - } - rowClientAnchorDetail = new ClientAnchorDetail(rowNumber, - rowNumber, pictureHeightCoordinates); - } - // If the user has chosen to overlay both rows and columns or just - // to expand ONLY the size of the columns, then calculate how to lay - // the image out ver one or more rows. - else if((resizeBehaviour == AddDimensionedImage.OVERLAY_ROW_AND_COLUMN) || - (resizeBehaviour == AddDimensionedImage.EXPAND_COLUMN)) { - rowClientAnchorDetail = this.calculateRowLocation(sheet, - rowNumber, reqImageHeightMM); - } - } - // Else, if the image is smaller than the space available - else { - if(sheet instanceof HSSFSheet) { - rowCoordinatesPerMM = ConvertImageUnits.TOTAL_ROW_COORDINATE_POSITIONS / - rowHeightMM; - pictureHeightCoordinates = (int)(reqImageHeightMM * rowCoordinatesPerMM); - } - else { - pictureHeightCoordinates = (int)(reqImageHeightMM * - AddDimensionedImage.EMU_PER_MM); - } - rowClientAnchorDetail = new ClientAnchorDetail(rowNumber, - rowNumber, pictureHeightCoordinates); - } - return(rowClientAnchorDetail); - } - - /** - * If the image is to overlie more than one column, calculations need to be - * performed to determine how many columns and whether the image will - * overlie just a part of one column in order to be presented at the - * required size. - * - * @param sheet The sheet that will 'contain' the image. - * @param startingColumn A primitive int whose value is the index of the - * column that contains the cell whose top left hand - * corner should be aligned with the top left hand - * corner of the image. - * @param reqImageWidthMM A primitive double whose value will indicate the - * required width of the image in millimetres. - * @return An instance of the ClientAnchorDetail class that will contain - * the index number of the column containing the cell whose top - * left hand corner also defines the top left hand corner of the - * image, the index number column containing the cell whose top - * left hand corner also defines the bottom right hand corner of - * the image and an inset that determines how far the right hand - * edge of the image can protrude into the next column - expressed - * as a specific number of coordinate positions. - */ - private ClientAnchorDetail calculateColumnLocation(Sheet sheet, - int startingColumn, - double reqImageWidthMM) { - ClientAnchorDetail anchorDetail = null; - double totalWidthMM = 0.0D; - double colWidthMM = 0.0D; - double overlapMM = 0.0D; - double coordinatePositionsPerMM = 0.0D; - int toColumn = startingColumn; - int inset = 0; - - // Calculate how many columns the image will have to - // span in order to be presented at the required size. - while(totalWidthMM < reqImageWidthMM) { - colWidthMM = ConvertImageUnits.widthUnits2Millimetres( - (short)(sheet.getColumnWidth(toColumn))); - // Note use of the cell border width constant. Testing with an image - // declared to fit exactly into one column demonstrated that it's - // width was greater than the width of the column the POI returned. - // Further, this difference was a constant value that I am assuming - // related to the cell's borders. Either way, that difference needs - // to be allowed for in this calculation. - totalWidthMM += (colWidthMM + ConvertImageUnits.CELL_BORDER_WIDTH_MILLIMETRES); - toColumn++; - } - // De-crement by one the last column value. - toColumn--; - // Highly unlikely that this will be true but, if the width of a series - // of columns is exactly equal to the required width of the image, then - // simply build a ClientAnchorDetail object with an inset equal to the - // total number of co-ordinate positions available in a column, a - // from column co-ordinate (top left hand corner) equal to the value - // of the startingColumn parameter and a to column co-ordinate equal - // to the toColumn variable. - // - // Convert both values to ints to perform the test. - if((int)totalWidthMM == (int)reqImageWidthMM) { - // A problem could occur if the image is sized to fit into one or - // more columns. If that occurs, the value in the toColumn variable - // will be in error. To overcome this, there are two options, to - // ibcrement the toColumn variable's value by one or to pass the - // total number of co-ordinate positions to the third paramater - // of the ClientAnchorDetail constructor. For no sepcific reason, - // the latter option is used below. - if(sheet instanceof HSSFSheet) { - anchorDetail = new ClientAnchorDetail(startingColumn, - toColumn, ConvertImageUnits.TOTAL_COLUMN_COORDINATE_POSITIONS); - } - else { - anchorDetail = new ClientAnchorDetail(startingColumn, - toColumn, (int)reqImageWidthMM * AddDimensionedImage.EMU_PER_MM); - } - } - // In this case, the image will overlap part of another column and it is - // necessary to calculate just how much - this will become the inset - // for the ClientAnchorDetail object. - else { - // Firstly, claculate how much of the image should overlap into - // the next column. - overlapMM = reqImageWidthMM - (totalWidthMM - colWidthMM); - - // When the required size is very close indded to the column size, - // the calcaulation above can produce a negative value. To prevent - // problems occuring in later caculations, this is simply removed - // be setting the overlapMM value to zero. - if(overlapMM < 0) { - overlapMM = 0.0D; - } - - if(sheet instanceof HSSFSheet) { - // Next, from the columns width, calculate how many co-ordinate - // positons there are per millimetre - coordinatePositionsPerMM = ConvertImageUnits.TOTAL_COLUMN_COORDINATE_POSITIONS / - colWidthMM; - // From this figure, determine how many co-ordinat positions to - // inset the left hand or bottom edge of the image. - inset = (int)(coordinatePositionsPerMM * overlapMM); - } - else { - inset = (int)overlapMM * AddDimensionedImage.EMU_PER_MM; - } - - // Now create the ClientAnchorDetail object, setting the from and to - // columns and the inset. - anchorDetail = new ClientAnchorDetail(startingColumn, toColumn, inset); - } - return(anchorDetail); - } - - /** - * If the image is to overlie more than one rows, calculations need to be - * performed to determine how many rows and whether the image will - * overlie just a part of one row in order to be presented at the - * required size. - * - * @param sheet The sheet that will 'contain' the image. - * @param startingRow A primitive int whose value is the index of the row - * that contains the cell whose top left hand corner - * should be aligned with the top left hand corner of - * the image. - * @param reqImageHeightMM A primitive double whose value will indicate the - * required height of the image in millimetres. - * @return An instance of the ClientAnchorDetail class that will contain - * the index number of the row containing the cell whose top - * left hand corner also defines the top left hand corner of the - * image, the index number of the row containing the cell whose top - * left hand corner also defines the bottom right hand corner of - * the image and an inset that determines how far the bottom edge - * can protrude into the next (lower) row - expressed as a specific - * number of co-ordinate positions. - */ - private ClientAnchorDetail calculateRowLocation(Sheet sheet, - int startingRow, double reqImageHeightMM) { - ClientAnchorDetail clientAnchorDetail = null; - Row row = null; - double rowHeightMM = 0.0D; - double totalRowHeightMM = 0.0D; - double overlapMM = 0.0D; - double rowCoordinatesPerMM = 0.0D; - int toRow = startingRow; - int inset = 0; - - // Step through the rows in the sheet and accumulate a total of their - // heights. - while(totalRowHeightMM < reqImageHeightMM) { - row = sheet.getRow(toRow); - // Note, if the row does not already exist on the sheet then create - // it here. - if(row == null) { - row = sheet.createRow(toRow); - } - // Get the row's height in millimetres and add to the running total. - rowHeightMM = row.getHeightInPoints() / - ConvertImageUnits.POINTS_PER_MILLIMETRE; - totalRowHeightMM += rowHeightMM; - toRow++; - } - // Owing to the way the loop above works, the rowNumber will have been - // incremented one row too far. Undo that here. - toRow--; - // Check to see whether the image should occupy an exact number of - // rows. If so, build the ClientAnchorDetail record to point - // to those rows and with an inset of the total number of co-ordinate - // position in the row. - // - // To overcome problems that can occur with comparing double values for - // equality, cast both to int(s) to truncate the value; VERY crude and - // I do not really like it!! - if((int)totalRowHeightMM == (int)reqImageHeightMM) { - if(sheet instanceof HSSFSheet) { - clientAnchorDetail = new ClientAnchorDetail(startingRow, toRow, - ConvertImageUnits.TOTAL_ROW_COORDINATE_POSITIONS); - } - else { - clientAnchorDetail = new ClientAnchorDetail(startingRow, toRow, - (int)reqImageHeightMM * AddDimensionedImage.EMU_PER_MM); - } - } - else { - // Calculate how far the image will project into the next row. Note - // that the height of the last row assessed is subtracted from the - // total height of all rows assessed so far. - overlapMM = reqImageHeightMM - (totalRowHeightMM - rowHeightMM); - - // To prevent an exception being thrown when the required width of - // the image is very close indeed to the column size. - if(overlapMM < 0) { - overlapMM = 0.0D; - } - - if(sheet instanceof HSSFSheet) { - rowCoordinatesPerMM = ConvertImageUnits.TOTAL_ROW_COORDINATE_POSITIONS / - rowHeightMM; - inset = (int)(overlapMM * rowCoordinatesPerMM); - } - else { - inset = (int)overlapMM * AddDimensionedImage.EMU_PER_MM; - } - clientAnchorDetail = new ClientAnchorDetail(startingRow, - toRow, inset); - } - return(clientAnchorDetail); - } - - /** - * The main entry point to the program. It contains code that demonstrates - * one way to use the program. - * - * Note, the code is not restricted to use on new workbooks only. If an - * image is to be inserted into an existing workbook. just open that - * workbook, gat a reference to a sheet and pass that; - * - * AddDimensionedImage addImage = new AddDimensionedImage(); - * - * File file = new File("....... Existing Workbook ......."); - * FileInputStream fis = new FileInputStream(file); - * Workbook workbook = new HSSFWorkbook(fis); - * HSSFSheet sheet = workbook.getSheetAt(0); - * addImage.addImageToSheet("C3", sheet, "image.jpg", 30, 20, - * AddDimensionedImage.EXPAND.ROW); - * - * @param args the command line arguments - */ - public static void main(String[] args) throws IOException { - String imageFile = null; - String outputFile = null; - FileOutputStream fos = null; - Workbook workbook = null; - Sheet sheet = null; - - if(args.length < 2){ - System.err.println("Usage: AddDimensionedImage imageFile outputFile"); - return; - } - workbook = new HSSFWorkbook(); // OR XSSFWorkbook - sheet = workbook.createSheet("Picture Test"); - imageFile = args[0]; - outputFile = args[1]; - new AddDimensionedImage().addImageToSheet("B5", sheet, sheet.createDrawingPatriarch(), - new File(imageFile).toURI().toURL(), 100, 40, - AddDimensionedImage.EXPAND_ROW_AND_COLUMN); - fos = new FileOutputStream(outputFile); - workbook.write(fos); - fos.close(); - workbook.close(); - } - - /** - * The HSSFClientAnchor class accepts eight arguments. In order, these are; - * - * * How far the left hand edge of the image is inset from the left hand - * edge of the cell - * * How far the top edge of the image is inset from the top of the cell - * * How far the right hand edge of the image is inset from the left - * hand edge of the cell - * * How far the bottom edge of the image is inset from the top of the - * cell. - * * Together, arguments five and six determine the column and row - * coordinates of the cell whose top left hand corner will be aligned - * with the images top left hand corner. - * * Together, arguments seven and eight determine the column and row - * coordinates of the cell whose top left hand corner will be aligned - * with the images bottom right hand corner. - * - * An instance of the ClientAnchorDetail class provides three of the eight - * parameters, one of the coordinates for the images top left hand corner, - * one of the coordinates for the images bottom right hand corner and - * either how far the image should be inset from the top or the left hand - * edge of the cell. - * - * @author Mark Beardsley [msb at apache.org] - * @version 1.00 5th August 2009. - */ - public class ClientAnchorDetail { - - public int fromIndex = 0; - public int toIndex = 0; - public int inset = 0; - - /** - * Create a new instance of the ClientAnchorDetail class using the - * following parameters. - * - * @param fromIndex A primitive int that contains one of the - * coordinates (row or column index) for the top left - * hand corner of the image. - * @param toIndex A primitive int that contains one of the - * coordinates (row or column index) for the bottom - * right hand corner of the image. - * @param inset A primitive int that contains a value which indicates - * how far the image should be inset from the top or the - * left hand edge of a cell. - */ - public ClientAnchorDetail(int fromIndex, int toIndex, int inset) { - this.fromIndex = fromIndex; - this.toIndex = toIndex; - this.inset = inset; - } - - /** - * Get one of the number of the column or row that contains the cell - * whose top left hand corner will be aligned with the top left hand - * corner of the image. - * - * @return The value - row or column index - for one of the coordinates - * of the top left hand corner of the image. - */ - public int getFromIndex() { - return(this.fromIndex); - } - - /** - * Get one of the number of the column or row that contains the cell - * whose top left hand corner will be aligned with the bottom right hand - * corner of the image. - * - * @return The value - row or column index - for one of the coordinates - * of the bottom right hand corner of the image. - */ - public int getToIndex() { - return(this.toIndex); - } - - /** - * Get the images offset from the edge of a cell. - * - * @return How far either the right hand or bottom edge of the image is - * inset from the left hand or top edge of a cell. - */ - public int getInset() { - return(this.inset); - } - } - - /** - * Utility methods used to convert Excels character based column and row - * size measurements into pixels and/or millimetres. The class also contains - * various constants that are required in other calculations. - * - * @author xio[darjino@hotmail.com] - * @version 1.01 30th July 2009. - * Added by Mark Beardsley [msb at apache.org]. - * Additional constants. - * widthUnits2Millimetres() and millimetres2Units() methods. - */ - public static class ConvertImageUnits { - - // Each cell conatins a fixed number of co-ordinate points; this number - // does not vary with row height or column width or with font. These two - // constants are defined below. - public static final int TOTAL_COLUMN_COORDINATE_POSITIONS = 1023; // MB - public static final int TOTAL_ROW_COORDINATE_POSITIONS = 255; // MB - // The resoultion of an image can be expressed as a specific number - // of pixels per inch. Displays and printers differ but 96 pixels per - // inch is an acceptable standard to beging with. - public static final int PIXELS_PER_INCH = 96; // MB - // Cnstants that defines how many pixels and points there are in a - // millimetre. These values are required for the conversion algorithm. - public static final double PIXELS_PER_MILLIMETRES = 3.78; // MB - public static final double POINTS_PER_MILLIMETRE = 2.83; // MB - // The column width returned by HSSF and the width of a picture when - // positioned to exactly cover one cell are different by almost exactly - // 2mm - give or take rounding errors. This constant allows that - // additional amount to be accounted for when calculating how many - // celles the image ought to overlie. - public static final double CELL_BORDER_WIDTH_MILLIMETRES = 2.0D; // MB - public static final short EXCEL_COLUMN_WIDTH_FACTOR = 256; - public static final int UNIT_OFFSET_LENGTH = 7; - public static final int[] UNIT_OFFSET_MAP = new int[] - { 0, 36, 73, 109, 146, 182, 219 }; - - /** - * pixel units to excel width units(units of 1/256th of a character width) - * @param pxs - * @return - */ - public static short pixel2WidthUnits(int pxs) { - short widthUnits = (short) (EXCEL_COLUMN_WIDTH_FACTOR * - (pxs / UNIT_OFFSET_LENGTH)); - widthUnits += UNIT_OFFSET_MAP[(pxs % UNIT_OFFSET_LENGTH)]; - return widthUnits; - } - - /** - * excel width units(units of 1/256th of a character width) to pixel - * units. - * - * @param widthUnits - * @return - */ - public static int widthUnits2Pixel(short widthUnits) { - int pixels = (widthUnits / EXCEL_COLUMN_WIDTH_FACTOR) - * UNIT_OFFSET_LENGTH; - int offsetWidthUnits = widthUnits % EXCEL_COLUMN_WIDTH_FACTOR; - pixels += Math.round(offsetWidthUnits / - ((float) EXCEL_COLUMN_WIDTH_FACTOR / UNIT_OFFSET_LENGTH)); - return pixels; - } - - /** - * Convert Excels width units into millimetres. - * - * @param widthUnits The width of the column or the height of the - * row in Excels units. - * @return A primitive double that contains the columns width or rows - * height in millimetres. - */ - public static double widthUnits2Millimetres(short widthUnits) { - return(ConvertImageUnits.widthUnits2Pixel(widthUnits) / - ConvertImageUnits.PIXELS_PER_MILLIMETRES); - } - - /** - * Convert into millimetres Excels width units.. - * - * @param millimetres A primitive double that contains the columns - * width or rows height in millimetres. - * @return A primitive int that contains the columns width or rows - * height in Excels units. - */ - public static int millimetres2WidthUnits(double millimetres) { - return(ConvertImageUnits.pixel2WidthUnits((int)(millimetres * - ConvertImageUnits.PIXELS_PER_MILLIMETRES))); - } - - public static int pointsToPixels(double points) { - return (int) Math.round(points / 72D * PIXELS_PER_INCH); - } - - public static double pointsToMillimeters(double points) { - return points / 72D * 25.4; - } - } -} diff --git a/src/examples/src/org/apache/poi/ss/examples/AligningCells.java b/src/examples/src/org/apache/poi/ss/examples/AligningCells.java deleted file mode 100644 index c767f24d9..000000000 --- a/src/examples/src/org/apache/poi/ss/examples/AligningCells.java +++ /dev/null @@ -1,75 +0,0 @@ -/* ==================================================================== -Licensed to the Apache Software Foundation (ASF) under one or more -contributor license agreements. See the NOTICE file distributed with -this work for additional information regarding copyright ownership. -The ASF licenses this file to You under the Apache License, Version 2.0 -(the "License"); you may not use this file except in compliance with -the License. You may obtain a copy of the License at - -http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -==================================================================== */ -package org.apache.poi.ss.examples; - -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; - -import org.apache.poi.ss.usermodel.*; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -/** - * Shows how various alignment options work. - */ -public class AligningCells { - - public static void main(String[] args) throws IOException { - Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); - - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(2); - row.setHeightInPoints(30); - for (int i = 0; i < 8; i++) { - //column width is set in units of 1/256th of a character width - sheet.setColumnWidth(i, 256 * 15); - } - - createCell(wb, row, 0, HorizontalAlignment.CENTER, VerticalAlignment.BOTTOM); - createCell(wb, row, 1, HorizontalAlignment.CENTER_SELECTION, VerticalAlignment.BOTTOM); - createCell(wb, row, 2, HorizontalAlignment.FILL, VerticalAlignment.CENTER); - createCell(wb, row, 3, HorizontalAlignment.GENERAL, VerticalAlignment.CENTER); - createCell(wb, row, 4, HorizontalAlignment.JUSTIFY, VerticalAlignment.JUSTIFY); - createCell(wb, row, 5, HorizontalAlignment.LEFT, VerticalAlignment.TOP); - createCell(wb, row, 6, HorizontalAlignment.RIGHT, VerticalAlignment.TOP); - - // Write the output to a file - OutputStream fileOut = new FileOutputStream("ss-example-align.xlsx"); - wb.write(fileOut); - fileOut.close(); - - wb.close(); - } - - /** - * Creates a cell and aligns it a certain way. - * - * @param wb the workbook - * @param row the row to create the cell in - * @param column the column number to create the cell in - * @param halign the horizontal alignment for the cell. - */ - private static void createCell(Workbook wb, Row row, int column, HorizontalAlignment halign, VerticalAlignment valign) { - CreationHelper ch = wb.getCreationHelper(); - Cell cell = row.createCell(column); - cell.setCellValue(ch.createRichTextString("Align It")); - CellStyle cellStyle = wb.createCellStyle(); - cellStyle.setAlignment(halign); - cellStyle.setVerticalAlignment(valign); - cell.setCellStyle(cellStyle); - } -} \ No newline at end of file diff --git a/src/examples/src/org/apache/poi/ss/examples/BusinessPlan.java b/src/examples/src/org/apache/poi/ss/examples/BusinessPlan.java deleted file mode 100644 index d263494ec..000000000 --- a/src/examples/src/org/apache/poi/ss/examples/BusinessPlan.java +++ /dev/null @@ -1,330 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.examples; - -import org.apache.poi.xssf.usermodel.*; -import org.apache.poi.ss.usermodel.*; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; - -import java.util.Map; -import java.util.HashMap; -import java.util.Calendar; -import java.io.FileOutputStream; -import java.text.SimpleDateFormat; - -/** - * A business plan demo - * Usage: - * BusinessPlan -xls|xlsx - * - * @author Yegor Kozlov - */ -public class BusinessPlan { - - private static SimpleDateFormat fmt = new SimpleDateFormat("dd-MMM"); - - private static final String[] titles = { - "ID", "Project Name", "Owner", "Days", "Start", "End"}; - - //sample data to fill the sheet. - private static final String[][] data = { - {"1.0", "Marketing Research Tactical Plan", "J. Dow", "70", "9-Jul", null, - "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x"}, - null, - {"1.1", "Scope Definition Phase", "J. Dow", "10", "9-Jul", null, - "x", "x", null, null, null, null, null, null, null, null, null}, - {"1.1.1", "Define research objectives", "J. Dow", "3", "9-Jul", null, - "x", null, null, null, null, null, null, null, null, null, null}, - {"1.1.2", "Define research requirements", "S. Jones", "7", "10-Jul", null, - "x", "x", null, null, null, null, null, null, null, null, null}, - {"1.1.3", "Determine in-house resource or hire vendor", "J. Dow", "2", "15-Jul", null, - "x", "x", null, null, null, null, null, null, null, null, null}, - null, - {"1.2", "Vendor Selection Phase", "J. Dow", "19", "19-Jul", null, - null, "x", "x", "x", "x", null, null, null, null, null, null}, - {"1.2.1", "Define vendor selection criteria", "J. Dow", "3", "19-Jul", null, - null, "x", null, null, null, null, null, null, null, null, null}, - {"1.2.2", "Develop vendor selection questionnaire", "S. Jones, T. Wates", "2", "22-Jul", null, - null, "x", "x", null, null, null, null, null, null, null, null}, - {"1.2.3", "Develop Statement of Work", "S. Jones", "4", "26-Jul", null, - null, null, "x", "x", null, null, null, null, null, null, null}, - {"1.2.4", "Evaluate proposal", "J. Dow, S. Jones", "4", "2-Aug", null, - null, null, null, "x", "x", null, null, null, null, null, null}, - {"1.2.5", "Select vendor", "J. Dow", "1", "6-Aug", null, - null, null, null, null, "x", null, null, null, null, null, null}, - null, - {"1.3", "Research Phase", "G. Lee", "47", "9-Aug", null, - null, null, null, null, "x", "x", "x", "x", "x", "x", "x"}, - {"1.3.1", "Develop market research information needs questionnaire", "G. Lee", "2", "9-Aug", null, - null, null, null, null, "x", null, null, null, null, null, null}, - {"1.3.2", "Interview marketing group for market research needs", "G. Lee", "2", "11-Aug", null, - null, null, null, null, "x", "x", null, null, null, null, null}, - {"1.3.3", "Document information needs", "G. Lee, S. Jones", "1", "13-Aug", null, - null, null, null, null, null, "x", null, null, null, null, null}, - }; - - public static void main(String[] args) throws Exception { - Workbook wb; - - if(args.length > 0 && args[0].equals("-xls")) wb = new HSSFWorkbook(); - else wb = new XSSFWorkbook(); - - Map styles = createStyles(wb); - - Sheet sheet = wb.createSheet("Business Plan"); - - //turn off gridlines - sheet.setDisplayGridlines(false); - sheet.setPrintGridlines(false); - sheet.setFitToPage(true); - sheet.setHorizontallyCenter(true); - PrintSetup printSetup = sheet.getPrintSetup(); - printSetup.setLandscape(true); - - //the following three statements are required only for HSSF - sheet.setAutobreaks(true); - printSetup.setFitHeight((short)1); - printSetup.setFitWidth((short)1); - - //the header row: centered text in 48pt font - Row headerRow = sheet.createRow(0); - headerRow.setHeightInPoints(12.75f); - for (int i = 0; i < titles.length; i++) { - Cell cell = headerRow.createCell(i); - cell.setCellValue(titles[i]); - cell.setCellStyle(styles.get("header")); - } - //columns for 11 weeks starting from 9-Jul - Calendar calendar = Calendar.getInstance(); - int year = calendar.get(Calendar.YEAR); - - calendar.setTime(fmt.parse("9-Jul")); - calendar.set(Calendar.YEAR, year); - for (int i = 0; i < 11; i++) { - Cell cell = headerRow.createCell(titles.length + i); - cell.setCellValue(calendar); - cell.setCellStyle(styles.get("header_date")); - calendar.roll(Calendar.WEEK_OF_YEAR, true); - } - //freeze the first row - sheet.createFreezePane(0, 1); - - Row row; - Cell cell; - int rownum = 1; - for (int i = 0; i < data.length; i++, rownum++) { - row = sheet.createRow(rownum); - if(data[i] == null) continue; - - for (int j = 0; j < data[i].length; j++) { - cell = row.createCell(j); - String styleName; - boolean isHeader = i == 0 || data[i-1] == null; - switch(j){ - case 0: - if(isHeader) { - styleName = "cell_b"; - cell.setCellValue(Double.parseDouble(data[i][j])); - } else { - styleName = "cell_normal"; - cell.setCellValue(data[i][j]); - } - break; - case 1: - if(isHeader) { - styleName = i == 0 ? "cell_h" : "cell_bb"; - } else { - styleName = "cell_indented"; - } - cell.setCellValue(data[i][j]); - break; - case 2: - styleName = isHeader ? "cell_b" : "cell_normal"; - cell.setCellValue(data[i][j]); - break; - case 3: - styleName = isHeader ? "cell_b_centered" : "cell_normal_centered"; - cell.setCellValue(Integer.parseInt(data[i][j])); - break; - case 4: { - calendar.setTime(fmt.parse(data[i][j])); - calendar.set(Calendar.YEAR, year); - cell.setCellValue(calendar); - styleName = isHeader ? "cell_b_date" : "cell_normal_date"; - break; - } - case 5: { - int r = rownum + 1; - String fmla = "IF(AND(D"+r+",E"+r+"),E"+r+"+D"+r+",\"\")"; - cell.setCellFormula(fmla); - styleName = isHeader ? "cell_bg" : "cell_g"; - break; - } - default: - styleName = data[i][j] != null ? "cell_blue" : "cell_normal"; - } - - cell.setCellStyle(styles.get(styleName)); - } - } - - //group rows for each phase, row numbers are 0-based - sheet.groupRow(4, 6); - sheet.groupRow(9, 13); - sheet.groupRow(16, 18); - - //set column widths, the width is measured in units of 1/256th of a character width - sheet.setColumnWidth(0, 256*6); - sheet.setColumnWidth(1, 256*33); - sheet.setColumnWidth(2, 256*20); - sheet.setZoom(75); //75% scale - - - // Write the output to a file - String file = "businessplan.xls"; - if(wb instanceof XSSFWorkbook) file += "x"; - FileOutputStream out = new FileOutputStream(file); - wb.write(out); - out.close(); - - wb.close(); - } - - /** - * create a library of cell styles - */ - private static Map createStyles(Workbook wb){ - Map styles = new HashMap(); - DataFormat df = wb.createDataFormat(); - - CellStyle style; - Font headerFont = wb.createFont(); - headerFont.setBold(true); - style = createBorderedStyle(wb); - style.setAlignment(HorizontalAlignment.CENTER); - style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex()); - style.setFillPattern(FillPatternType.SOLID_FOREGROUND); - style.setFont(headerFont); - styles.put("header", style); - - style = createBorderedStyle(wb); - style.setAlignment(HorizontalAlignment.CENTER); - style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex()); - style.setFillPattern(FillPatternType.SOLID_FOREGROUND); - style.setFont(headerFont); - style.setDataFormat(df.getFormat("d-mmm")); - styles.put("header_date", style); - - Font font1 = wb.createFont(); - font1.setBold(true); - style = createBorderedStyle(wb); - style.setAlignment(HorizontalAlignment.LEFT); - style.setFont(font1); - styles.put("cell_b", style); - - style = createBorderedStyle(wb); - style.setAlignment(HorizontalAlignment.CENTER); - style.setFont(font1); - styles.put("cell_b_centered", style); - - style = createBorderedStyle(wb); - style.setAlignment(HorizontalAlignment.RIGHT); - style.setFont(font1); - style.setDataFormat(df.getFormat("d-mmm")); - styles.put("cell_b_date", style); - - style = createBorderedStyle(wb); - style.setAlignment(HorizontalAlignment.RIGHT); - style.setFont(font1); - style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); - style.setFillPattern(FillPatternType.SOLID_FOREGROUND); - style.setDataFormat(df.getFormat("d-mmm")); - styles.put("cell_g", style); - - Font font2 = wb.createFont(); - font2.setColor(IndexedColors.BLUE.getIndex()); - font2.setBold(true); - style = createBorderedStyle(wb); - style.setAlignment(HorizontalAlignment.LEFT); - style.setFont(font2); - styles.put("cell_bb", style); - - style = createBorderedStyle(wb); - style.setAlignment(HorizontalAlignment.RIGHT); - style.setFont(font1); - style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); - style.setFillPattern(FillPatternType.SOLID_FOREGROUND); - style.setDataFormat(df.getFormat("d-mmm")); - styles.put("cell_bg", style); - - Font font3 = wb.createFont(); - font3.setFontHeightInPoints((short)14); - font3.setColor(IndexedColors.DARK_BLUE.getIndex()); - font3.setBold(true); - style = createBorderedStyle(wb); - style.setAlignment(HorizontalAlignment.LEFT); - style.setFont(font3); - style.setWrapText(true); - styles.put("cell_h", style); - - style = createBorderedStyle(wb); - style.setAlignment(HorizontalAlignment.LEFT); - style.setWrapText(true); - styles.put("cell_normal", style); - - style = createBorderedStyle(wb); - style.setAlignment(HorizontalAlignment.CENTER); - style.setWrapText(true); - styles.put("cell_normal_centered", style); - - style = createBorderedStyle(wb); - style.setAlignment(HorizontalAlignment.RIGHT); - style.setWrapText(true); - style.setDataFormat(df.getFormat("d-mmm")); - styles.put("cell_normal_date", style); - - style = createBorderedStyle(wb); - style.setAlignment(HorizontalAlignment.LEFT); - style.setIndention((short)1); - style.setWrapText(true); - styles.put("cell_indented", style); - - style = createBorderedStyle(wb); - style.setFillForegroundColor(IndexedColors.BLUE.getIndex()); - style.setFillPattern(FillPatternType.SOLID_FOREGROUND); - styles.put("cell_blue", style); - - return styles; - } - - private static CellStyle createBorderedStyle(Workbook wb){ - BorderStyle thin = BorderStyle.THIN; - short black = IndexedColors.BLACK.getIndex(); - - CellStyle style = wb.createCellStyle(); - style.setBorderRight(thin); - style.setRightBorderColor(black); - style.setBorderBottom(thin); - style.setBottomBorderColor(black); - style.setBorderLeft(thin); - style.setLeftBorderColor(black); - style.setBorderTop(thin); - style.setTopBorderColor(black); - return style; - } -} diff --git a/src/examples/src/org/apache/poi/ss/examples/CalendarDemo.java b/src/examples/src/org/apache/poi/ss/examples/CalendarDemo.java deleted file mode 100644 index 4438f22c1..000000000 --- a/src/examples/src/org/apache/poi/ss/examples/CalendarDemo.java +++ /dev/null @@ -1,245 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.examples; - -import org.apache.poi.xssf.usermodel.*; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.usermodel.*; -import org.apache.poi.ss.usermodel.Font; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; - -import java.io.FileOutputStream; -import java.util.Calendar; -import java.util.Map; -import java.util.HashMap; - -/** - * A monthly calendar created using Apache POI. Each month is on a separate sheet. - *
    - * Usage:
    - * CalendarDemo -xls|xlsx 
    - * 
    - * - * @author Yegor Kozlov - */ -public class CalendarDemo { - - private static final String[] days = { - "Sunday", "Monday", "Tuesday", - "Wednesday", "Thursday", "Friday", "Saturday"}; - - private static final String[] months = { - "January", "February", "March","April", "May", "June","July", "August", - "September","October", "November", "December"}; - - public static void main(String[] args) throws Exception { - - Calendar calendar = Calendar.getInstance(); - boolean xlsx = true; - for (int i = 0; i < args.length; i++) { - if(args[i].charAt(0) == '-'){ - xlsx = args[i].equals("-xlsx"); - } else { - calendar.set(Calendar.YEAR, Integer.parseInt(args[i])); - } - } - int year = calendar.get(Calendar.YEAR); - - Workbook wb = xlsx ? new XSSFWorkbook() : new HSSFWorkbook(); - - Map styles = createStyles(wb); - - for (int month = 0; month < 12; month++) { - calendar.set(Calendar.MONTH, month); - calendar.set(Calendar.DAY_OF_MONTH, 1); - //create a sheet for each month - Sheet sheet = wb.createSheet(months[month]); - - //turn off gridlines - sheet.setDisplayGridlines(false); - sheet.setPrintGridlines(false); - sheet.setFitToPage(true); - sheet.setHorizontallyCenter(true); - PrintSetup printSetup = sheet.getPrintSetup(); - printSetup.setLandscape(true); - - //the following three statements are required only for HSSF - sheet.setAutobreaks(true); - printSetup.setFitHeight((short)1); - printSetup.setFitWidth((short)1); - - //the header row: centered text in 48pt font - Row headerRow = sheet.createRow(0); - headerRow.setHeightInPoints(80); - Cell titleCell = headerRow.createCell(0); - titleCell.setCellValue(months[month] + " " + year); - titleCell.setCellStyle(styles.get("title")); - sheet.addMergedRegion(CellRangeAddress.valueOf("$A$1:$N$1")); - - //header with month titles - Row monthRow = sheet.createRow(1); - for (int i = 0; i < days.length; i++) { - //set column widths, the width is measured in units of 1/256th of a character width - sheet.setColumnWidth(i*2, 5*256); //the column is 5 characters wide - sheet.setColumnWidth(i*2 + 1, 13*256); //the column is 13 characters wide - sheet.addMergedRegion(new CellRangeAddress(1, 1, i*2, i*2+1)); - Cell monthCell = monthRow.createCell(i*2); - monthCell.setCellValue(days[i]); - monthCell.setCellStyle(styles.get("month")); - } - - int cnt = 1, day=1; - int rownum = 2; - for (int j = 0; j < 6; j++) { - Row row = sheet.createRow(rownum++); - row.setHeightInPoints(100); - for (int i = 0; i < days.length; i++) { - Cell dayCell_1 = row.createCell(i*2); - Cell dayCell_2 = row.createCell(i*2 + 1); - - int day_of_week = calendar.get(Calendar.DAY_OF_WEEK); - if(cnt >= day_of_week && calendar.get(Calendar.MONTH) == month) { - dayCell_1.setCellValue(day); - calendar.set(Calendar.DAY_OF_MONTH, ++day); - - if(i == 0 || i == days.length-1) { - dayCell_1.setCellStyle(styles.get("weekend_left")); - dayCell_2.setCellStyle(styles.get("weekend_right")); - } else { - dayCell_1.setCellStyle(styles.get("workday_left")); - dayCell_2.setCellStyle(styles.get("workday_right")); - } - } else { - dayCell_1.setCellStyle(styles.get("grey_left")); - dayCell_2.setCellStyle(styles.get("grey_right")); - } - cnt++; - } - if(calendar.get(Calendar.MONTH) > month) break; - } - } - - // Write the output to a file - String file = "calendar.xls"; - if(wb instanceof XSSFWorkbook) file += "x"; - FileOutputStream out = new FileOutputStream(file); - wb.write(out); - out.close(); - - wb.close(); - } - - /** - * cell styles used for formatting calendar sheets - */ - private static Map createStyles(Workbook wb){ - Map styles = new HashMap(); - - short borderColor = IndexedColors.GREY_50_PERCENT.getIndex(); - - CellStyle style; - Font titleFont = wb.createFont(); - titleFont.setFontHeightInPoints((short)48); - titleFont.setColor(IndexedColors.DARK_BLUE.getIndex()); - style = wb.createCellStyle(); - style.setAlignment(HorizontalAlignment.CENTER); - style.setVerticalAlignment(VerticalAlignment.CENTER); - style.setFont(titleFont); - styles.put("title", style); - - Font monthFont = wb.createFont(); - monthFont.setFontHeightInPoints((short)12); - monthFont.setColor(IndexedColors.WHITE.getIndex()); - monthFont.setBold(true); - style = wb.createCellStyle(); - style.setAlignment(HorizontalAlignment.CENTER); - style.setVerticalAlignment(VerticalAlignment.CENTER); - style.setFillForegroundColor(IndexedColors.DARK_BLUE.getIndex()); - style.setFillPattern(FillPatternType.SOLID_FOREGROUND); - style.setFont(monthFont); - styles.put("month", style); - - Font dayFont = wb.createFont(); - dayFont.setFontHeightInPoints((short)14); - dayFont.setBold(true); - style = wb.createCellStyle(); - style.setAlignment(HorizontalAlignment.LEFT); - style.setVerticalAlignment(VerticalAlignment.TOP); - style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex()); - style.setFillPattern(FillPatternType.SOLID_FOREGROUND); - style.setBorderLeft(BorderStyle.THIN); - style.setLeftBorderColor(borderColor); - style.setBorderBottom(BorderStyle.THIN); - style.setBottomBorderColor(borderColor); - style.setFont(dayFont); - styles.put("weekend_left", style); - - style = wb.createCellStyle(); - style.setAlignment(HorizontalAlignment.CENTER); - style.setVerticalAlignment(VerticalAlignment.TOP); - style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex()); - style.setFillPattern(FillPatternType.SOLID_FOREGROUND); - style.setBorderRight(BorderStyle.THIN); - style.setRightBorderColor(borderColor); - style.setBorderBottom(BorderStyle.THIN); - style.setBottomBorderColor(borderColor); - styles.put("weekend_right", style); - - style = wb.createCellStyle(); - style.setAlignment(HorizontalAlignment.LEFT); - style.setVerticalAlignment(VerticalAlignment.TOP); - style.setBorderLeft(BorderStyle.THIN); - style.setFillForegroundColor(IndexedColors.WHITE.getIndex()); - style.setFillPattern(FillPatternType.SOLID_FOREGROUND); - style.setLeftBorderColor(borderColor); - style.setBorderBottom(BorderStyle.THIN); - style.setBottomBorderColor(borderColor); - style.setFont(dayFont); - styles.put("workday_left", style); - - style = wb.createCellStyle(); - style.setAlignment(HorizontalAlignment.CENTER); - style.setVerticalAlignment(VerticalAlignment.TOP); - style.setFillForegroundColor(IndexedColors.WHITE.getIndex()); - style.setFillPattern(FillPatternType.SOLID_FOREGROUND); - style.setBorderRight(BorderStyle.THIN); - style.setRightBorderColor(borderColor); - style.setBorderBottom(BorderStyle.THIN); - style.setBottomBorderColor(borderColor); - styles.put("workday_right", style); - - style = wb.createCellStyle(); - style.setBorderLeft(BorderStyle.THIN); - style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); - style.setFillPattern(FillPatternType.SOLID_FOREGROUND); - style.setBorderBottom(BorderStyle.THIN); - style.setBottomBorderColor(borderColor); - styles.put("grey_left", style); - - style = wb.createCellStyle(); - style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); - style.setFillPattern(FillPatternType.SOLID_FOREGROUND); - style.setBorderRight(BorderStyle.THIN); - style.setRightBorderColor(borderColor); - style.setBorderBottom(BorderStyle.THIN); - style.setBottomBorderColor(borderColor); - styles.put("grey_right", style); - - return styles; - } -} diff --git a/src/examples/src/org/apache/poi/ss/examples/CellStyleDetails.java b/src/examples/src/org/apache/poi/ss/examples/CellStyleDetails.java deleted file mode 100644 index 55b85a291..000000000 --- a/src/examples/src/org/apache/poi/ss/examples/CellStyleDetails.java +++ /dev/null @@ -1,96 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.examples; - -import java.io.File; - -import org.apache.poi.hssf.usermodel.HSSFFont; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.hssf.util.HSSFColor; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.Color; -import org.apache.poi.ss.usermodel.DataFormatter; -import org.apache.poi.ss.usermodel.Font; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.usermodel.WorkbookFactory; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.xssf.usermodel.XSSFColor; -import org.apache.poi.xssf.usermodel.XSSFFont; - -/** - * Demonstrates how to read excel styles for cells - */ -public class CellStyleDetails { - public static void main(String[] args) throws Exception { - if(args.length == 0) { - throw new IllegalArgumentException("Filename must be given"); - } - - Workbook wb = WorkbookFactory.create(new File(args[0])); - DataFormatter formatter = new DataFormatter(); - - for(int sn=0; sn - * Partly based on the code snippets from - * http://www.contextures.com/xlcondformat03.html - *

    - */ -public class ConditionalFormats { - - public static void main(String[] args) throws IOException { - Workbook wb; - - if(args.length > 0 && args[0].equals("-xls")) { - wb = new HSSFWorkbook(); - } else { - wb = new XSSFWorkbook(); - } - - sameCell(wb.createSheet("Same Cell")); - multiCell(wb.createSheet("MultiCell")); - overlapping(wb.createSheet("Overlapping")); - errors(wb.createSheet("Errors")); - hideDupplicates(wb.createSheet("Hide Dups")); - formatDuplicates(wb.createSheet("Duplicates")); - inList(wb.createSheet("In List")); - expiry(wb.createSheet("Expiry")); - shadeAlt(wb.createSheet("Shade Alt")); - shadeBands(wb.createSheet("Shade Bands")); - iconSets(wb.createSheet("Icon Sets")); - colourScales(wb.createSheet("Colour Scales")); - dataBars(wb.createSheet("Data Bars")); - - // Write the output to a file - String file = "cf-poi.xls"; - if(wb instanceof XSSFWorkbook) { - file += "x"; - } - FileOutputStream out = new FileOutputStream(file); - wb.write(out); - out.close(); - System.out.println("Generated: " + file); - wb.close(); - } - - /** - * Highlight cells based on their values - */ - static void sameCell(Sheet sheet) { - sheet.createRow(0).createCell(0).setCellValue(84); - sheet.createRow(1).createCell(0).setCellValue(74); - sheet.createRow(2).createCell(0).setCellValue(50); - sheet.createRow(3).createCell(0).setCellValue(51); - sheet.createRow(4).createCell(0).setCellValue(49); - sheet.createRow(5).createCell(0).setCellValue(41); - - SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting(); - - // Condition 1: Cell Value Is greater than 70 (Blue Fill) - ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule(ComparisonOperator.GT, "70"); - PatternFormatting fill1 = rule1.createPatternFormatting(); - fill1.setFillBackgroundColor(IndexedColors.BLUE.index); - fill1.setFillPattern(PatternFormatting.SOLID_FOREGROUND); - - // Condition 2: Cell Value Is less than 50 (Green Fill) - ConditionalFormattingRule rule2 = sheetCF.createConditionalFormattingRule(ComparisonOperator.LT, "50"); - PatternFormatting fill2 = rule2.createPatternFormatting(); - fill2.setFillBackgroundColor(IndexedColors.GREEN.index); - fill2.setFillPattern(PatternFormatting.SOLID_FOREGROUND); - - CellRangeAddress[] regions = { - CellRangeAddress.valueOf("A1:A6") - }; - - sheetCF.addConditionalFormatting(regions, rule1, rule2); - - sheet.getRow(0).createCell(2).setCellValue("<== Condition 1: Cell Value Is greater than 70 (Blue Fill)"); - sheet.getRow(4).createCell(2).setCellValue("<== Condition 2: Cell Value Is less than 50 (Green Fill)"); - } - - /** - * Highlight multiple cells based on a formula - */ - static void multiCell(Sheet sheet) { - // header row - Row row0 = sheet.createRow(0); - row0.createCell(0).setCellValue("Units"); - row0.createCell(1).setCellValue("Cost"); - row0.createCell(2).setCellValue("Total"); - - Row row1 = sheet.createRow(1); - row1.createCell(0).setCellValue(71); - row1.createCell(1).setCellValue(29); - row1.createCell(2).setCellValue(2059); - - Row row2 = sheet.createRow(2); - row2.createCell(0).setCellValue(85); - row2.createCell(1).setCellValue(29); - row2.createCell(2).setCellValue(2059); - - Row row3 = sheet.createRow(3); - row3.createCell(0).setCellValue(71); - row3.createCell(1).setCellValue(29); - row3.createCell(2).setCellValue(2059); - - SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting(); - - // Condition 1: Formula Is =$B2>75 (Blue Fill) - ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("$A2>75"); - PatternFormatting fill1 = rule1.createPatternFormatting(); - fill1.setFillBackgroundColor(IndexedColors.BLUE.index); - fill1.setFillPattern(PatternFormatting.SOLID_FOREGROUND); - - CellRangeAddress[] regions = { - CellRangeAddress.valueOf("A2:C4") - }; - - sheetCF.addConditionalFormatting(regions, rule1); - - sheet.getRow(2).createCell(4).setCellValue("<== Condition 1: Formula Is =$B2>75 (Blue Fill)"); - } - - /** - * Multiple conditional formatting rules can apply to - * one cell, some combining, some beating others. - * Done in order of the rules added to the - * SheetConditionalFormatting object - */ - static void overlapping(Sheet sheet) { - for (int i=0; i<40; i++) { - int rn = i+1; - Row r = sheet.createRow(i); - r.createCell(0).setCellValue("This is row " + rn + " (" + i + ")"); - String str = ""; - if (rn%2 == 0) { - str = str + "even "; - } - if (rn%3 == 0) { - str = str + "x3 "; - } - if (rn%5 == 0) { - str = str + "x5 "; - } - if (rn%10 == 0) { - str = str + "x10 "; - } - if (str.length() == 0) { - str = "nothing special..."; - } - r.createCell(1).setCellValue("It is " + str); - } - sheet.autoSizeColumn(0); - sheet.autoSizeColumn(1); - - sheet.getRow(1).createCell(3).setCellValue("Even rows are blue"); - sheet.getRow(2).createCell(3).setCellValue("Multiples of 3 have a grey background"); - sheet.getRow(4).createCell(3).setCellValue("Multiples of 5 are bold"); - sheet.getRow(9).createCell(3).setCellValue("Multiples of 10 are red (beats even)"); - - SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting(); - - // Condition 1: Row divides by 10, red (will beat #1) - ConditionalFormattingRule rule1 = - sheetCF.createConditionalFormattingRule("MOD(ROW(),10)=0"); - FontFormatting font1 = rule1.createFontFormatting(); - font1.setFontColorIndex(IndexedColors.RED.index); - - // Condition 2: Row is even, blue - ConditionalFormattingRule rule2 = - sheetCF.createConditionalFormattingRule("MOD(ROW(),2)=0"); - FontFormatting font2 = rule2.createFontFormatting(); - font2.setFontColorIndex(IndexedColors.BLUE.index); - - // Condition 3: Row divides by 5, bold - ConditionalFormattingRule rule3 = - sheetCF.createConditionalFormattingRule("MOD(ROW(),5)=0"); - FontFormatting font3 = rule3.createFontFormatting(); - font3.setFontStyle(false, true); - - // Condition 4: Row divides by 3, grey background - ConditionalFormattingRule rule4 = - sheetCF.createConditionalFormattingRule("MOD(ROW(),3)=0"); - PatternFormatting fill4 = rule4.createPatternFormatting(); - fill4.setFillBackgroundColor(IndexedColors.GREY_25_PERCENT.index); - fill4.setFillPattern(PatternFormatting.SOLID_FOREGROUND); - - // Apply - CellRangeAddress[] regions = { - CellRangeAddress.valueOf("A1:F41") - }; - - sheetCF.addConditionalFormatting(regions, rule1); - sheetCF.addConditionalFormatting(regions, rule2); - sheetCF.addConditionalFormatting(regions, rule3); - sheetCF.addConditionalFormatting(regions, rule4); - } - - /** - * Use Excel conditional formatting to check for errors, - * and change the font colour to match the cell colour. - * In this example, if formula result is #DIV/0! then it will have white font colour. - */ - static void errors(Sheet sheet) { - sheet.createRow(0).createCell(0).setCellValue(84); - sheet.createRow(1).createCell(0).setCellValue(0); - sheet.createRow(2).createCell(0).setCellFormula("ROUND(A1/A2,0)"); - sheet.createRow(3).createCell(0).setCellValue(0); - sheet.createRow(4).createCell(0).setCellFormula("ROUND(A6/A4,0)"); - sheet.createRow(5).createCell(0).setCellValue(41); - - SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting(); - - // Condition 1: Formula Is =ISERROR(C2) (White Font) - ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("ISERROR(A1)"); - FontFormatting font = rule1.createFontFormatting(); - font.setFontColorIndex(IndexedColors.WHITE.index); - - CellRangeAddress[] regions = { - CellRangeAddress.valueOf("A1:A6") - }; - - sheetCF.addConditionalFormatting(regions, rule1); - - sheet.getRow(2).createCell(1).setCellValue("<== The error in this cell is hidden. Condition: Formula Is =ISERROR(C2) (White Font)"); - sheet.getRow(4).createCell(1).setCellValue("<== The error in this cell is hidden. Condition: Formula Is =ISERROR(C2) (White Font)"); - } - - /** - * Use Excel conditional formatting to hide the duplicate values, - * and make the list easier to read. In this example, when the table is sorted by Region, - * the second (and subsequent) occurences of each region name will have white font colour. - */ - static void hideDupplicates(Sheet sheet) { - sheet.createRow(0).createCell(0).setCellValue("City"); - sheet.createRow(1).createCell(0).setCellValue("Boston"); - sheet.createRow(2).createCell(0).setCellValue("Boston"); - sheet.createRow(3).createCell(0).setCellValue("Chicago"); - sheet.createRow(4).createCell(0).setCellValue("Chicago"); - sheet.createRow(5).createCell(0).setCellValue("New York"); - - SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting(); - - // Condition 1: Formula Is =A2=A1 (White Font) - ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("A2=A1"); - FontFormatting font = rule1.createFontFormatting(); - font.setFontColorIndex(IndexedColors.WHITE.index); - - CellRangeAddress[] regions = { - CellRangeAddress.valueOf("A2:A6") - }; - - sheetCF.addConditionalFormatting(regions, rule1); - - sheet.getRow(1).createCell(1).setCellValue("<== the second (and subsequent) " + - "occurences of each region name will have white font colour. " + - "Condition: Formula Is =A2=A1 (White Font)"); - } - - /** - * Use Excel conditional formatting to highlight duplicate entries in a column. - */ - static void formatDuplicates(Sheet sheet) { - sheet.createRow(0).createCell(0).setCellValue("Code"); - sheet.createRow(1).createCell(0).setCellValue(4); - sheet.createRow(2).createCell(0).setCellValue(3); - sheet.createRow(3).createCell(0).setCellValue(6); - sheet.createRow(4).createCell(0).setCellValue(3); - sheet.createRow(5).createCell(0).setCellValue(5); - sheet.createRow(6).createCell(0).setCellValue(8); - sheet.createRow(7).createCell(0).setCellValue(0); - sheet.createRow(8).createCell(0).setCellValue(2); - sheet.createRow(9).createCell(0).setCellValue(8); - sheet.createRow(10).createCell(0).setCellValue(6); - - SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting(); - - // Condition 1: Formula Is =A2=A1 (White Font) - ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("COUNTIF($A$2:$A$11,A2)>1"); - FontFormatting font = rule1.createFontFormatting(); - font.setFontStyle(false, true); - font.setFontColorIndex(IndexedColors.BLUE.index); - - CellRangeAddress[] regions = { - CellRangeAddress.valueOf("A2:A11") - }; - - sheetCF.addConditionalFormatting(regions, rule1); - - sheet.getRow(2).createCell(1).setCellValue("<== Duplicates numbers in the column are highlighted. " + - "Condition: Formula Is =COUNTIF($A$2:$A$11,A2)>1 (Blue Font)"); - } - - /** - * Use Excel conditional formatting to highlight items that are in a list on the worksheet. - */ - static void inList(Sheet sheet) { - sheet.createRow(0).createCell(0).setCellValue("Codes"); - sheet.createRow(1).createCell(0).setCellValue("AA"); - sheet.createRow(2).createCell(0).setCellValue("BB"); - sheet.createRow(3).createCell(0).setCellValue("GG"); - sheet.createRow(4).createCell(0).setCellValue("AA"); - sheet.createRow(5).createCell(0).setCellValue("FF"); - sheet.createRow(6).createCell(0).setCellValue("XX"); - sheet.createRow(7).createCell(0).setCellValue("CC"); - - sheet.getRow(0).createCell(2).setCellValue("Valid"); - sheet.getRow(1).createCell(2).setCellValue("AA"); - sheet.getRow(2).createCell(2).setCellValue("BB"); - sheet.getRow(3).createCell(2).setCellValue("CC"); - - SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting(); - - // Condition 1: Formula Is =A2=A1 (White Font) - ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("COUNTIF($C$2:$C$4,A2)"); - PatternFormatting fill1 = rule1.createPatternFormatting(); - fill1.setFillBackgroundColor(IndexedColors.LIGHT_BLUE.index); - fill1.setFillPattern(PatternFormatting.SOLID_FOREGROUND); - - CellRangeAddress[] regions = { - CellRangeAddress.valueOf("A2:A8") - }; - - sheetCF.addConditionalFormatting(regions, rule1); - - sheet.getRow(2).createCell(3).setCellValue("<== Use Excel conditional formatting to highlight items that are in a list on the worksheet"); - } - - /** - * Use Excel conditional formatting to highlight payments that are due in the next thirty days. - * In this example, Due dates are entered in cells A2:A4. - */ - static void expiry(Sheet sheet) { - CellStyle style = sheet.getWorkbook().createCellStyle(); - style.setDataFormat((short)BuiltinFormats.getBuiltinFormat("d-mmm")); - - sheet.createRow(0).createCell(0).setCellValue("Date"); - sheet.createRow(1).createCell(0).setCellFormula("TODAY()+29"); - sheet.createRow(2).createCell(0).setCellFormula("A2+1"); - sheet.createRow(3).createCell(0).setCellFormula("A3+1"); - - for(int rownum = 1; rownum <= 3; rownum++) { - sheet.getRow(rownum).getCell(0).setCellStyle(style); - } - - SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting(); - - // Condition 1: Formula Is =A2=A1 (White Font) - ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("AND(A2-TODAY()>=0,A2-TODAY()<=30)"); - FontFormatting font = rule1.createFontFormatting(); - font.setFontStyle(false, true); - font.setFontColorIndex(IndexedColors.BLUE.index); - - CellRangeAddress[] regions = { - CellRangeAddress.valueOf("A2:A4") - }; - - sheetCF.addConditionalFormatting(regions, rule1); - - sheet.getRow(0).createCell(1).setCellValue("Dates within the next 30 days are highlighted"); - } - - /** - * Use Excel conditional formatting to shade alternating rows on the worksheet - */ - static void shadeAlt(Sheet sheet) { - SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting(); - - // Condition 1: Formula Is =A2=A1 (White Font) - ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("MOD(ROW(),2)"); - PatternFormatting fill1 = rule1.createPatternFormatting(); - fill1.setFillBackgroundColor(IndexedColors.LIGHT_GREEN.index); - fill1.setFillPattern(PatternFormatting.SOLID_FOREGROUND); - - CellRangeAddress[] regions = { - CellRangeAddress.valueOf("A1:Z100") - }; - - sheetCF.addConditionalFormatting(regions, rule1); - - sheet.createRow(0).createCell(1).setCellValue("Shade Alternating Rows"); - sheet.createRow(1).createCell(1).setCellValue("Condition: Formula Is =MOD(ROW(),2) (Light Green Fill)"); - } - - /** - * You can use Excel conditional formatting to shade bands of rows on the worksheet. - * In this example, 3 rows are shaded light grey, and 3 are left with no shading. - * In the MOD function, the total number of rows in the set of banded rows (6) is entered. - */ - static void shadeBands(Sheet sheet) { - SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting(); - - ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("MOD(ROW(),6)<3"); - PatternFormatting fill1 = rule1.createPatternFormatting(); - fill1.setFillBackgroundColor(IndexedColors.GREY_25_PERCENT.index); - fill1.setFillPattern(PatternFormatting.SOLID_FOREGROUND); - - CellRangeAddress[] regions = { - CellRangeAddress.valueOf("A1:Z100") - }; - - sheetCF.addConditionalFormatting(regions, rule1); - - sheet.createRow(0).createCell(1).setCellValue("Shade Bands of Rows"); - sheet.createRow(1).createCell(1).setCellValue("Condition: Formula Is =MOD(ROW(),6)<2 (Light Grey Fill)"); - } - - /** - * Icon Sets / Multi-States allow you to have icons shown which vary - * based on the values, eg Red traffic light / Yellow traffic light / - * Green traffic light - */ - static void iconSets(Sheet sheet) { - sheet.createRow(0).createCell(0).setCellValue("Icon Sets"); - Row r = sheet.createRow(1); - r.createCell(0).setCellValue("Reds"); - r.createCell(1).setCellValue(0); - r.createCell(2).setCellValue(0); - r.createCell(3).setCellValue(0); - r = sheet.createRow(2); - r.createCell(0).setCellValue("Yellows"); - r.createCell(1).setCellValue(5); - r.createCell(2).setCellValue(5); - r.createCell(3).setCellValue(5); - r = sheet.createRow(3); - r.createCell(0).setCellValue("Greens"); - r.createCell(1).setCellValue(10); - r.createCell(2).setCellValue(10); - r.createCell(3).setCellValue(10); - - SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting(); - - CellRangeAddress[] regions = { CellRangeAddress.valueOf("B1:B4") }; - ConditionalFormattingRule rule1 = - sheetCF.createConditionalFormattingRule(IconSet.GYR_3_TRAFFIC_LIGHTS); - IconMultiStateFormatting im1 = rule1.getMultiStateFormatting(); - im1.getThresholds()[0].setRangeType(RangeType.MIN); - im1.getThresholds()[1].setRangeType(RangeType.PERCENT); - im1.getThresholds()[1].setValue(33d); - im1.getThresholds()[2].setRangeType(RangeType.MAX); - sheetCF.addConditionalFormatting(regions, rule1); - - regions = new CellRangeAddress[] { CellRangeAddress.valueOf("C1:C4") }; - ConditionalFormattingRule rule2 = - sheetCF.createConditionalFormattingRule(IconSet.GYR_3_FLAGS); - IconMultiStateFormatting im2 = rule1.getMultiStateFormatting(); - im2.getThresholds()[0].setRangeType(RangeType.PERCENT); - im2.getThresholds()[0].setValue(0d); - im2.getThresholds()[1].setRangeType(RangeType.PERCENT); - im2.getThresholds()[1].setValue(33d); - im2.getThresholds()[2].setRangeType(RangeType.PERCENT); - im2.getThresholds()[2].setValue(67d); - sheetCF.addConditionalFormatting(regions, rule2); - - regions = new CellRangeAddress[] { CellRangeAddress.valueOf("D1:D4") }; - ConditionalFormattingRule rule3 = - sheetCF.createConditionalFormattingRule(IconSet.GYR_3_SYMBOLS_CIRCLE); - IconMultiStateFormatting im3 = rule1.getMultiStateFormatting(); - im3.setIconOnly(true); - im3.getThresholds()[0].setRangeType(RangeType.MIN); - im3.getThresholds()[1].setRangeType(RangeType.NUMBER); - im3.getThresholds()[1].setValue(3d); - im3.getThresholds()[2].setRangeType(RangeType.NUMBER); - im3.getThresholds()[2].setValue(7d); - sheetCF.addConditionalFormatting(regions, rule3); - } - - /** - * Color Scales / Colour Scales / Colour Gradients allow you shade the - * background colour of the cell based on the values, eg from Red to - * Yellow to Green. - */ - static void colourScales(Sheet sheet) { - sheet.createRow(0).createCell(0).setCellValue("Colour Scales"); - Row r = sheet.createRow(1); - r.createCell(0).setCellValue("Red-Yellow-Green"); - for (int i=1; i<=7; i++) { - r.createCell(i).setCellValue((i-1)*5); - } - r = sheet.createRow(2); - r.createCell(0).setCellValue("Red-White-Blue"); - for (int i=1; i<=9; i++) { - r.createCell(i).setCellValue((i-1)*5); - } - r = sheet.createRow(3); - r.createCell(0).setCellValue("Blue-Green"); - for (int i=1; i<=16; i++) { - r.createCell(i).setCellValue((i-1)); - } - sheet.setColumnWidth(0, 5000); - - SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting(); - - CellRangeAddress[] regions = { CellRangeAddress.valueOf("B2:H2") }; - ConditionalFormattingRule rule1 = - sheetCF.createConditionalFormattingColorScaleRule(); - ColorScaleFormatting cs1 = rule1.getColorScaleFormatting(); - cs1.getThresholds()[0].setRangeType(RangeType.MIN); - cs1.getThresholds()[1].setRangeType(RangeType.PERCENTILE); - cs1.getThresholds()[1].setValue(50d); - cs1.getThresholds()[2].setRangeType(RangeType.MAX); - ((ExtendedColor)cs1.getColors()[0]).setARGBHex("FFF8696B"); - ((ExtendedColor)cs1.getColors()[1]).setARGBHex("FFFFEB84"); - ((ExtendedColor)cs1.getColors()[2]).setARGBHex("FF63BE7B"); - sheetCF.addConditionalFormatting(regions, rule1); - - regions = new CellRangeAddress[] { CellRangeAddress.valueOf("B3:J3") }; - ConditionalFormattingRule rule2 = - sheetCF.createConditionalFormattingColorScaleRule(); - ColorScaleFormatting cs2 = rule2.getColorScaleFormatting(); - cs2.getThresholds()[0].setRangeType(RangeType.MIN); - cs2.getThresholds()[1].setRangeType(RangeType.PERCENTILE); - cs2.getThresholds()[1].setValue(50d); - cs2.getThresholds()[2].setRangeType(RangeType.MAX); - ((ExtendedColor)cs2.getColors()[0]).setARGBHex("FFF8696B"); - ((ExtendedColor)cs2.getColors()[1]).setARGBHex("FFFCFCFF"); - ((ExtendedColor)cs2.getColors()[2]).setARGBHex("FF5A8AC6"); - sheetCF.addConditionalFormatting(regions, rule2); - - regions = new CellRangeAddress[] { CellRangeAddress.valueOf("B4:Q4") }; - ConditionalFormattingRule rule3= - sheetCF.createConditionalFormattingColorScaleRule(); - ColorScaleFormatting cs3 = rule3.getColorScaleFormatting(); - cs3.setNumControlPoints(2); - cs3.getThresholds()[0].setRangeType(RangeType.MIN); - cs3.getThresholds()[1].setRangeType(RangeType.MAX); - ((ExtendedColor)cs3.getColors()[0]).setARGBHex("FF5A8AC6"); - ((ExtendedColor)cs3.getColors()[1]).setARGBHex("FF63BE7B"); - sheetCF.addConditionalFormatting(regions, rule3); - } - - /** - * DataBars / Data-Bars allow you to have bars shown vary - * based on the values, from full to empty - */ - static void dataBars(Sheet sheet) { - sheet.createRow(0).createCell(0).setCellValue("Data Bars"); - Row r = sheet.createRow(1); - r.createCell(1).setCellValue("Green Positive"); - r.createCell(2).setCellValue("Blue Mix"); - r.createCell(3).setCellValue("Red Negative"); - r = sheet.createRow(2); - r.createCell(1).setCellValue(0); - r.createCell(2).setCellValue(0); - r.createCell(3).setCellValue(0); - r = sheet.createRow(3); - r.createCell(1).setCellValue(5); - r.createCell(2).setCellValue(-5); - r.createCell(3).setCellValue(-5); - r = sheet.createRow(4); - r.createCell(1).setCellValue(10); - r.createCell(2).setCellValue(10); - r.createCell(3).setCellValue(-10); - r = sheet.createRow(5); - r.createCell(1).setCellValue(5); - r.createCell(2).setCellValue(5); - r.createCell(3).setCellValue(-5); - r = sheet.createRow(6); - r.createCell(1).setCellValue(20); - r.createCell(2).setCellValue(-10); - r.createCell(3).setCellValue(-20); - sheet.setColumnWidth(0, 3000); - sheet.setColumnWidth(1, 5000); - sheet.setColumnWidth(2, 5000); - sheet.setColumnWidth(3, 5000); - - SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting(); - - ExtendedColor color = sheet.getWorkbook().getCreationHelper().createExtendedColor(); - color.setARGBHex("FF63BE7B"); - CellRangeAddress[] regions = { CellRangeAddress.valueOf("B2:B7") }; - ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule(color); - DataBarFormatting db1 = rule1.getDataBarFormatting(); - db1.getMinThreshold().setRangeType(RangeType.MIN); - db1.getMaxThreshold().setRangeType(RangeType.MAX); - sheetCF.addConditionalFormatting(regions, rule1); - - color = sheet.getWorkbook().getCreationHelper().createExtendedColor(); - color.setARGBHex("FF5A8AC6"); - regions = new CellRangeAddress[] { CellRangeAddress.valueOf("C2:C7") }; - ConditionalFormattingRule rule2 = sheetCF.createConditionalFormattingRule(color); - DataBarFormatting db2 = rule2.getDataBarFormatting(); - db2.getMinThreshold().setRangeType(RangeType.MIN); - db2.getMaxThreshold().setRangeType(RangeType.MAX); - sheetCF.addConditionalFormatting(regions, rule2); - - color = sheet.getWorkbook().getCreationHelper().createExtendedColor(); - color.setARGBHex("FFF8696B"); - regions = new CellRangeAddress[] { CellRangeAddress.valueOf("D2:D7") }; - ConditionalFormattingRule rule3 = sheetCF.createConditionalFormattingRule(color); - DataBarFormatting db3 = rule3.getDataBarFormatting(); - db3.getMinThreshold().setRangeType(RangeType.MIN); - db3.getMaxThreshold().setRangeType(RangeType.MAX); - sheetCF.addConditionalFormatting(regions, rule3); - } -} diff --git a/src/examples/src/org/apache/poi/ss/examples/DrawingBorders.java b/src/examples/src/org/apache/poi/ss/examples/DrawingBorders.java deleted file mode 100644 index 105e73df7..000000000 --- a/src/examples/src/org/apache/poi/ss/examples/DrawingBorders.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.ss.examples; - -import java.io.FileOutputStream; -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.BorderExtent; -import org.apache.poi.ss.usermodel.BorderStyle; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.IndexedColors; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.PropertyTemplate; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -/** - * Excel Border Drawing - examples - * - *

    - * Partly based on the code snippets from - * org.apache.poi.ss.examples.ConditionalFormats - *

    - */ -public class DrawingBorders { - - public static void main(String[] args) throws IOException { - Workbook wb; - - if (args.length > 0 && args[0].equals("-xls")) { - wb = new HSSFWorkbook(); - } else { - wb = new XSSFWorkbook(); - } - - // add a sheet, and put some values into it - Sheet sh1 = wb.createSheet("Sheet1"); - Row r = sh1.createRow(0); - Cell c = r.createCell(1); - c.setCellValue("All Borders Medium Width"); - r = sh1.createRow(4); - c = r.createCell(1); - c.setCellValue("Medium Outside / Thin Inside Borders"); - r = sh1.createRow(8); - c = r.createCell(1); - c.setCellValue("Colored Borders"); - - // draw borders (three 3x3 grids) - PropertyTemplate pt = new PropertyTemplate(); - // #1) these borders will all be medium in default color - pt.drawBorders(new CellRangeAddress(1, 3, 1, 3), - BorderStyle.MEDIUM, BorderExtent.ALL); - // #2) these cells will have medium outside borders and thin inside borders - pt.drawBorders(new CellRangeAddress(5, 7, 1, 3), - BorderStyle.MEDIUM, BorderExtent.OUTSIDE); - pt.drawBorders(new CellRangeAddress(5, 7, 1, 3), BorderStyle.THIN, - BorderExtent.INSIDE); - // #3) these cells will all be medium weight with different colors for the - // outside, inside horizontal, and inside vertical borders. The center - // cell will have no borders. - pt.drawBorders(new CellRangeAddress(9, 11, 1, 3), - BorderStyle.MEDIUM, IndexedColors.RED.getIndex(), - BorderExtent.OUTSIDE); - pt.drawBorders(new CellRangeAddress(9, 11, 1, 3), - BorderStyle.MEDIUM, IndexedColors.BLUE.getIndex(), - BorderExtent.INSIDE_VERTICAL); - pt.drawBorders(new CellRangeAddress(9, 11, 1, 3), - BorderStyle.MEDIUM, IndexedColors.GREEN.getIndex(), - BorderExtent.INSIDE_HORIZONTAL); - pt.drawBorders(new CellRangeAddress(10, 10, 2, 2), - BorderStyle.NONE, - BorderExtent.ALL); - - // apply borders to sheet - pt.applyBorders(sh1); - - // add another sheet and apply the borders to it - Sheet sh2 = wb.createSheet("Sheet2"); - pt.applyBorders(sh2); - - // Write the output to a file - String file = "db-poi.xls"; - if (wb instanceof XSSFWorkbook) - file += "x"; - FileOutputStream out = new FileOutputStream(file); - wb.write(out); - out.close(); - wb.close(); - System.out.println("Generated: " + file); - } - -} diff --git a/src/examples/src/org/apache/poi/ss/examples/ExcelComparator.java b/src/examples/src/org/apache/poi/ss/examples/ExcelComparator.java deleted file mode 100644 index 645e798a0..000000000 --- a/src/examples/src/org/apache/poi/ss/examples/ExcelComparator.java +++ /dev/null @@ -1,614 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.examples; - -import java.io.File; -import java.util.ArrayList; -import java.util.Date; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; - -import org.apache.poi.ss.usermodel.BorderStyle; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.Color; -import org.apache.poi.ss.usermodel.DateUtil; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.usermodel.WorkbookFactory; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.xssf.usermodel.XSSFCell; -import org.apache.poi.xssf.usermodel.XSSFCellStyle; -import org.apache.poi.xssf.usermodel.XSSFColor; - -/** - * Utility to compare Excel File Contents cell by cell for all sheets. - * - *

    This utility will be used to compare Excel File Contents cell by cell for all sheets programmatically.

    - * - *

    Below are the list of Attribute comparison supported in this version.

    - * - *
      - *
    • Cell Alignment
    • - *
    • Cell Border Attributes
    • - *
    • Cell Data
    • - *
    • Cell Data-Type
    • - *
    • Cell Fill Color
    • - *
    • Cell Fill pattern
    • - *
    • Cell Font Attributes
    • - *
    • Cell Font Family
    • - *
    • Cell Font Size
    • - *
    • Cell Protection
    • - *
    • Name of the sheets
    • - *
    • Number of Columns
    • - *
    • Number of Rows
    • - *
    • Number of Sheet
    • - *
    - * - *

    (Some of the above attribute comparison only work for *.xlsx format currently. In future it can be enhanced.)

    - * - *

    Usage:

    - * - *
    - * {@code
    - *  Workbook wb1 = WorkbookFactory.create(new File("workBook1.xls"));
    - *  Workbook wb2 = WorkbookFactory.create(new File("workBook2.xls"));
    - *  List listOfDifferences = ExcelComparator.compare(wb1, wb2);
    - *  for (String differences : listOfDifferences)
    - *      System.out.println(differences);
    - *  System.out.println("DifferenceFound = "+ excelFileDifference.isDifferenceFound);
    - *  }
    - * 
    - */ -public class ExcelComparator { - - private static final String CELL_DATA_DOES_NOT_MATCH = "Cell Data does not Match ::"; - private static final String CELL_FONT_ATTRIBUTES_DOES_NOT_MATCH = "Cell Font Attributes does not Match ::"; - - private static class Locator { - Workbook workbook; - Sheet sheet; - Row row; - Cell cell; - } - - List listOfDifferences = new ArrayList(); - - public static void main(String args[]) throws Exception { - if (args.length != 2 || !(new File(args[0]).exists()) || !(new File(args[1]).exists())) { - System.err.println("java -cp "+ExcelComparator.class.getCanonicalName()+" compare(Workbook wb1, Workbook wb2) { - Locator loc1 = new Locator(); - Locator loc2 = new Locator(); - loc1.workbook = wb1; - loc2.workbook = wb2; - - ExcelComparator excelComparator = new ExcelComparator(); - excelComparator.compareNumberOfSheets(loc1, loc2 ); - excelComparator.compareSheetNames(loc1, loc2); - excelComparator.compareSheetData(loc1, loc2); - - return excelComparator.listOfDifferences; - } - - /** - * Compare data in all sheets. - * - * @param workbook1 the workbook1 - * @param workbook2 the workbook2 - * @param listOfDifferences the list of differences - * @throws ExcelCompareException the excel compare exception - */ - private void compareDataInAllSheets(Locator loc1, Locator loc2) { - for (int i = 0; i < loc1.workbook.getNumberOfSheets(); i++) { - if (loc2.workbook.getNumberOfSheets() <= i) return; - - loc1.sheet = loc1.workbook.getSheetAt(i); - loc2.sheet = loc2.workbook.getSheetAt(i); - - compareDataInSheet(loc1, loc2); - } - } - - private void compareDataInSheet(Locator loc1, Locator loc2) { - for (int j = 0; j < loc1.sheet.getPhysicalNumberOfRows(); j++) { - if (loc2.sheet.getPhysicalNumberOfRows() <= j) return; - - loc1.row = loc1.sheet.getRow(j); - loc2.row = loc2.sheet.getRow(j); - - if ((loc1.row == null) || (loc2.row == null)) { - continue; - } - - compareDataInRow(loc1, loc2); - } - } - - private void compareDataInRow(Locator loc1, Locator loc2) { - for (int k = 0; k < loc1.row.getLastCellNum(); k++) { - if (loc2.row.getPhysicalNumberOfCells() <= k) return; - - loc1.cell = loc1.row.getCell(k); - loc2.cell = loc2.row.getCell(k); - - if ((loc1.cell == null) || (loc2.cell == null)) { - continue; - } - - compareDataInCell(loc1, loc2); - } - } - - private void compareDataInCell(Locator loc1, Locator loc2) { - if (isCellTypeMatches(loc1, loc2)) { - final CellType loc1cellType = loc1.cell.getCellTypeEnum(); - switch(loc1cellType) { - case BLANK: - case STRING: - case ERROR: - isCellContentMatches(loc1,loc2); - break; - case BOOLEAN: - isCellContentMatchesForBoolean(loc1,loc2); - break; - case FORMULA: - isCellContentMatchesForFormula(loc1,loc2); - break; - case NUMERIC: - if (DateUtil.isCellDateFormatted(loc1.cell)) { - isCellContentMatchesForDate(loc1,loc2); - } else { - isCellContentMatchesForNumeric(loc1,loc2); - } - break; - default: - throw new IllegalStateException("Unexpected cell type: " + loc1cellType); - } - } - - isCellFillPatternMatches(loc1,loc2); - isCellAlignmentMatches(loc1,loc2); - isCellHiddenMatches(loc1,loc2); - isCellLockedMatches(loc1,loc2); - isCellFontFamilyMatches(loc1,loc2); - isCellFontSizeMatches(loc1,loc2); - isCellFontBoldMatches(loc1,loc2); - isCellUnderLineMatches(loc1,loc2); - isCellFontItalicsMatches(loc1,loc2); - isCellBorderMatches(loc1,loc2,'t'); - isCellBorderMatches(loc1,loc2,'l'); - isCellBorderMatches(loc1,loc2,'b'); - isCellBorderMatches(loc1,loc2,'r'); - isCellFillBackGroundMatches(loc1,loc2); - } - - /** - * Compare number of columns in sheets. - */ - private void compareNumberOfColumnsInSheets(Locator loc1, Locator loc2) { - for (int i = 0; i < loc1.workbook.getNumberOfSheets(); i++) { - if (loc2.workbook.getNumberOfSheets() <= i) return; - - loc1.sheet = loc1.workbook.getSheetAt(i); - loc2.sheet = loc2.workbook.getSheetAt(i); - - Iterator ri1 = loc1.sheet.rowIterator(); - Iterator ri2 = loc2.sheet.rowIterator(); - - int num1 = (ri1.hasNext()) ? ri1.next().getPhysicalNumberOfCells() : 0; - int num2 = (ri2.hasNext()) ? ri2.next().getPhysicalNumberOfCells() : 0; - - if (num1 != num2) { - String str = String.format(Locale.ROOT, "%s\nworkbook1 -> %s [%d] != workbook2 -> %s [%d]", - "Number Of Columns does not Match ::", - loc1.sheet.getSheetName(), num1, - loc2.sheet.getSheetName(), num2 - ); - listOfDifferences.add(str); - } - } - } - - /** - * Compare number of rows in sheets. - */ - private void compareNumberOfRowsInSheets(Locator loc1, Locator loc2) { - for (int i = 0; i < loc1.workbook.getNumberOfSheets(); i++) { - if (loc2.workbook.getNumberOfSheets() <= i) return; - - loc1.sheet = loc1.workbook.getSheetAt(i); - loc2.sheet = loc2.workbook.getSheetAt(i); - - int num1 = loc1.sheet.getPhysicalNumberOfRows(); - int num2 = loc2.sheet.getPhysicalNumberOfRows(); - - if (num1 != num2) { - String str = String.format(Locale.ROOT, "%s\nworkbook1 -> %s [%d] != workbook2 -> %s [%d]", - "Number Of Rows does not Match ::", - loc1.sheet.getSheetName(), num1, - loc2.sheet.getSheetName(), num2 - ); - listOfDifferences.add(str); - } - } - - } - - /** - * Compare number of sheets. - */ - private void compareNumberOfSheets(Locator loc1, Locator loc2) { - int num1 = loc1.workbook.getNumberOfSheets(); - int num2 = loc2.workbook.getNumberOfSheets(); - if (num1 != num2) { - String str = String.format(Locale.ROOT, "%s\nworkbook1 [%d] != workbook2 [%d]", - "Number of Sheets do not match ::", - num1, num2 - ); - - listOfDifferences.add(str); - - } - } - - /** - * Compare sheet data. - * - * @param workbook1 - * the workbook1 - * @param workbook2 - * the workbook2 - * @param listOfDifferences - * - * @throws ExcelCompareException - * the excel compare exception - */ - private void compareSheetData(Locator loc1, Locator loc2) { - compareNumberOfRowsInSheets(loc1, loc2); - compareNumberOfColumnsInSheets(loc1, loc2); - compareDataInAllSheets(loc1, loc2); - - } - - /** - * Compare sheet names. - */ - private void compareSheetNames(Locator loc1, Locator loc2) { - for (int i = 0; i < loc1.workbook.getNumberOfSheets(); i++) { - String name1 = loc1.workbook.getSheetName(i); - String name2 = (loc2.workbook.getNumberOfSheets() > i) ? loc2.workbook.getSheetName(i) : ""; - - if (!name1.equals(name2)) { - String str = String.format(Locale.ROOT, "%s\nworkbook1 -> %s [%d] != workbook2 -> %s [%d]", - "Name of the sheets do not match ::", name1, i+1, name2, i+1 - ); - listOfDifferences.add(str); - } - } - } - - /** - * Formats the message. - */ - private void addMessage(Locator loc1, Locator loc2, String messageStart, String value1, String value2) { - String str = - String.format(Locale.ROOT, "%s\nworkbook1 -> %s -> %s [%s] != workbook2 -> %s -> %s [%s]", - messageStart, - loc1.sheet.getSheetName(), new CellReference(loc1.cell).formatAsString(), value1, - loc2.sheet.getSheetName(), new CellReference(loc2.cell).formatAsString(), value2 - ); - listOfDifferences.add(str); - } - - /** - * Checks if cell alignment matches. - */ - private void isCellAlignmentMatches(Locator loc1, Locator loc2) { - // TODO: check for NPE - short align1 = loc1.cell.getCellStyle().getAlignment(); - short align2 = loc2.cell.getCellStyle().getAlignment(); - if (align1 != align2) { - addMessage(loc1, loc2, - "Cell Alignment does not Match ::", - Short.toString(align1), - Short.toString(align2) - ); - } - } - - /** - * Checks if cell border bottom matches. - */ - private void isCellBorderMatches(Locator loc1, Locator loc2, char borderSide) { - if (!(loc1.cell instanceof XSSFCell)) return; - XSSFCellStyle style1 = ((XSSFCell)loc1.cell).getCellStyle(); - XSSFCellStyle style2 = ((XSSFCell)loc2.cell).getCellStyle(); - boolean b1, b2; - String borderName; - switch (borderSide) { - case 't': default: - b1 = style1.getBorderTopEnum() == BorderStyle.THIN; - b2 = style2.getBorderTopEnum() == BorderStyle.THIN; - borderName = "TOP"; - break; - case 'b': - b1 = style1.getBorderBottomEnum() == BorderStyle.THIN; - b2 = style2.getBorderBottomEnum() == BorderStyle.THIN; - borderName = "BOTTOM"; - break; - case 'l': - b1 = style1.getBorderLeftEnum() == BorderStyle.THIN; - b2 = style2.getBorderLeftEnum() == BorderStyle.THIN; - borderName = "LEFT"; - break; - case 'r': - b1 = style1.getBorderRightEnum() == BorderStyle.THIN; - b2 = style2.getBorderRightEnum() == BorderStyle.THIN; - borderName = "RIGHT"; - break; - } - if (b1 != b2) { - addMessage(loc1, loc2, - "Cell Border Attributes does not Match ::", - (b1 ? "" : "NOT ")+borderName+" BORDER", - (b2 ? "" : "NOT ")+borderName+" BORDER" - ); - } - } - - /** - * Checks if cell content matches. - */ - private void isCellContentMatches(Locator loc1, Locator loc2) { - // TODO: check for null and non-rich-text cells - String str1 = loc1.cell.getRichStringCellValue().getString(); - String str2 = loc2.cell.getRichStringCellValue().getString(); - if (!str1.equals(str2)) { - addMessage(loc1,loc2,CELL_DATA_DOES_NOT_MATCH,str1,str2); - } - } - - /** - * Checks if cell content matches for boolean. - */ - private void isCellContentMatchesForBoolean(Locator loc1, Locator loc2) { - boolean b1 = loc1.cell.getBooleanCellValue(); - boolean b2 = loc2.cell.getBooleanCellValue(); - if (b1 != b2) { - addMessage(loc1,loc2,CELL_DATA_DOES_NOT_MATCH,Boolean.toString(b1),Boolean.toString(b2)); - } - } - - /** - * Checks if cell content matches for date. - */ - private void isCellContentMatchesForDate(Locator loc1, Locator loc2) { - Date date1 = loc1.cell.getDateCellValue(); - Date date2 = loc2.cell.getDateCellValue(); - if (!date1.equals(date2)) { - addMessage(loc1, loc2, CELL_DATA_DOES_NOT_MATCH, date1.toGMTString(), date2.toGMTString()); - } - } - - - /** - * Checks if cell content matches for formula. - */ - private void isCellContentMatchesForFormula(Locator loc1, Locator loc2) { - // TODO: actually evaluate the formula / NPE checks - String form1 = loc1.cell.getCellFormula(); - String form2 = loc2.cell.getCellFormula(); - if (!form1.equals(form2)) { - addMessage(loc1, loc2, CELL_DATA_DOES_NOT_MATCH, form1, form2); - } - } - - /** - * Checks if cell content matches for numeric. - */ - private void isCellContentMatchesForNumeric(Locator loc1, Locator loc2) { - // TODO: Check for NaN - double num1 = loc1.cell.getNumericCellValue(); - double num2 = loc2.cell.getNumericCellValue(); - if (num1 != num2) { - addMessage(loc1, loc2, CELL_DATA_DOES_NOT_MATCH, Double.toString(num1), Double.toString(num2)); - } - } - - private String getCellFillBackground(Locator loc) { - Color col = loc.cell.getCellStyle().getFillForegroundColorColor(); - return (col instanceof XSSFColor) ? ((XSSFColor)col).getARGBHex() : "NO COLOR"; - } - - /** - * Checks if cell file back ground matches. - */ - private void isCellFillBackGroundMatches(Locator loc1, Locator loc2) { - String col1 = getCellFillBackground(loc1); - String col2 = getCellFillBackground(loc2); - if (!col1.equals(col2)) { - addMessage(loc1, loc2, "Cell Fill Color does not Match ::", col1, col2); - } - } - /** - * Checks if cell fill pattern matches. - */ - private void isCellFillPatternMatches(Locator loc1, Locator loc2) { - // TOOO: Check for NPE - short fill1 = loc1.cell.getCellStyle().getFillPattern(); - short fill2 = loc2.cell.getCellStyle().getFillPattern(); - if (fill1 != fill2) { - addMessage(loc1, loc2, - "Cell Fill pattern does not Match ::", - Short.toString(fill1), - Short.toString(fill2) - ); - } - } - - /** - * Checks if cell font bold matches. - */ - private void isCellFontBoldMatches(Locator loc1, Locator loc2) { - if (!(loc1.cell instanceof XSSFCell)) return; - boolean b1 = ((XSSFCell)loc1.cell).getCellStyle().getFont().getBold(); - boolean b2 = ((XSSFCell)loc2.cell).getCellStyle().getFont().getBold(); - if (b1 != b2) { - addMessage(loc1, loc2, - CELL_FONT_ATTRIBUTES_DOES_NOT_MATCH, - (b1 ? "" : "NOT ")+"BOLD", - (b2 ? "" : "NOT ")+"BOLD" - ); - } - } - - /** - * Checks if cell font family matches. - */ - private void isCellFontFamilyMatches(Locator loc1, Locator loc2) { - // TODO: Check for NPEs - if (!(loc1.cell instanceof XSSFCell)) return; - String family1 = ((XSSFCell)loc1.cell).getCellStyle().getFont().getFontName(); - String family2 = ((XSSFCell)loc2.cell).getCellStyle().getFont().getFontName(); - if (!family1.equals(family2)) { - addMessage(loc1, loc2, "Cell Font Family does not Match ::", family1, family2); - } - } - - /** - * Checks if cell font italics matches. - */ - private void isCellFontItalicsMatches(Locator loc1, Locator loc2) { - if (!(loc1.cell instanceof XSSFCell)) return; - boolean b1 = ((XSSFCell)loc1.cell).getCellStyle().getFont().getItalic(); - boolean b2 = ((XSSFCell)loc2.cell).getCellStyle().getFont().getItalic(); - if (b1 != b2) { - addMessage(loc1, loc2, - CELL_FONT_ATTRIBUTES_DOES_NOT_MATCH, - (b1 ? "" : "NOT ")+"ITALICS", - (b2 ? "" : "NOT ")+"ITALICS" - ); - } - } - - /** - * Checks if cell font size matches. - */ - private void isCellFontSizeMatches(Locator loc1, Locator loc2) { - if (!(loc1.cell instanceof XSSFCell)) return; - short size1 = ((XSSFCell)loc1.cell).getCellStyle().getFont().getFontHeightInPoints(); - short size2 = ((XSSFCell)loc2.cell).getCellStyle().getFont().getFontHeightInPoints(); - if (size1 != size2) { - addMessage(loc1, loc2, - "Cell Font Size does not Match ::", - Short.toString(size1), - Short.toString(size2) - ); - } - } - - /** - * Checks if cell hidden matches. - */ - private void isCellHiddenMatches(Locator loc1, Locator loc2) { - boolean b1 = loc1.cell.getCellStyle().getHidden(); - boolean b2 = loc1.cell.getCellStyle().getHidden(); - if (b1 != b2) { - addMessage(loc1, loc2, - "Cell Visibility does not Match ::", - (b1 ? "" : "NOT ")+"HIDDEN", - (b2 ? "" : "NOT ")+"HIDDEN" - ); - } - } - - /** - * Checks if cell locked matches. - */ - private void isCellLockedMatches(Locator loc1, Locator loc2) { - boolean b1 = loc1.cell.getCellStyle().getLocked(); - boolean b2 = loc1.cell.getCellStyle().getLocked(); - if (b1 != b2) { - addMessage(loc1, loc2, - "Cell Protection does not Match ::", - (b1 ? "" : "NOT ")+"LOCKED", - (b2 ? "" : "NOT ")+"LOCKED" - ); - } - } - - /** - * Checks if cell type matches. - */ - private boolean isCellTypeMatches(Locator loc1, Locator loc2) { - CellType type1 = loc1.cell.getCellTypeEnum(); - CellType type2 = loc2.cell.getCellTypeEnum(); - if (type1 == type2) return true; - addMessage(loc1, loc2, - "Cell Data-Type does not Match in :: ", - type1.name(), type2.name() - ); - return false; - } - - /** - * Checks if cell under line matches. - * - * @param cellWorkBook1 - * the cell work book1 - * @param cellWorkBook2 - * the cell work book2 - * @return true, if cell under line matches - */ - private void isCellUnderLineMatches(Locator loc1, Locator loc2) { - // TOOO: distinguish underline type - if (!(loc1.cell instanceof XSSFCell)) return; - byte b1 = ((XSSFCell)loc1.cell).getCellStyle().getFont().getUnderline(); - byte b2 = ((XSSFCell)loc2.cell).getCellStyle().getFont().getUnderline(); - if (b1 != b2) { - addMessage(loc1, loc2, - CELL_FONT_ATTRIBUTES_DOES_NOT_MATCH, - (b1 == 1 ? "" : "NOT ")+"UNDERLINE", - (b2 == 1 ? "" : "NOT ")+"UNDERLINE" - ); - } - } -} \ No newline at end of file diff --git a/src/examples/src/org/apache/poi/ss/examples/LinkedDropDownLists.java b/src/examples/src/org/apache/poi/ss/examples/LinkedDropDownLists.java deleted file mode 100644 index 8f43b4bf6..000000000 --- a/src/examples/src/org/apache/poi/ss/examples/LinkedDropDownLists.java +++ /dev/null @@ -1,211 +0,0 @@ - /* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - ==================================================================== */ - -package org.apache.poi.ss.examples; -import java.io.FileOutputStream; -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.DataValidation; -import org.apache.poi.ss.usermodel.DataValidationConstraint; -import org.apache.poi.ss.usermodel.DataValidationHelper; -import org.apache.poi.ss.usermodel.Name; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.CellRangeAddressList; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -/** - * Demonstrates one technique that may be used to create linked or dependent - * drop down lists. This refers to a situation in which the selection made - * in one drop down list affects the options that are displayed in the second - * or subsequent drop down list(s). In this example, the value the user selects - * from the down list in cell A1 will affect the values displayed in the linked - * drop down list in cell B1. For the sake of simplicity, the data for the drop - * down lists is included on the same worksheet but this does not have to be the - * case; the data could appear on a separate sheet. If this were done, then the - * names for the regions would have to be different, they would have to include - * the name of the sheet. - * - * There are two keys to this technique. The first is the use of named area or - * regions of cells to hold the data for the drop down lists and the second is - * making use of the INDIRECT() function to convert a name into the addresses - * of the cells it refers to. - * - * Note that whilst this class builds just two linked drop down lists, there is - * nothing to prevent more being created. Quite simply, use the value selected - * by the user in one drop down list to determine what is shown in another and the - * value selected in that drop down list to determine what is shown in a third, - * and so on. Also, note that the data for the drop down lists is contained on - * contained on the same sheet as the validations themselves. This is done simply - * for simplicity and there is nothing to prevent a separate sheet being created - * and used to hold the data. If this is done then problems may be encountered - * if the sheet is opened with OpenOffice Calc. To prevent these problems, it is - * better to include the name of the sheet when calling the setRefersToFormula() - * method. - * - * @author Mark Beardsley [msb at apache.org] - * @version 1.00 30th March 2012 - */ -public class LinkedDropDownLists { - - LinkedDropDownLists(String workbookName) throws IOException { - // Using the ss.usermodel allows this class to support both binary - // and xml based workbooks. The choice of which one to create is - // made by checking the file extension. - Workbook workbook; - if (workbookName.endsWith(".xlsx")) { - workbook = new XSSFWorkbook(); - } else { - workbook = new HSSFWorkbook(); - } - - // Build the sheet that will hold the data for the validations. This - // must be done first as it will create names that are referenced - // later. - Sheet sheet = workbook.createSheet("Linked Validations"); - LinkedDropDownLists.buildDataSheet(sheet); - - // Build the first data validation to occupy cell A1. Note - // that it retrieves it's data from the named area or region called - // CHOICES. Further information about this can be found in the - // static buildDataSheet() method below. - CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0); - DataValidationHelper dvHelper = sheet.getDataValidationHelper(); - DataValidationConstraint dvConstraint = dvHelper.createFormulaListConstraint("CHOICES"); - DataValidation validation = dvHelper.createValidation(dvConstraint, addressList); - sheet.addValidationData(validation); - - // Now, build the linked or dependent drop down list that will - // occupy cell B1. The key to the whole process is the use of the - // INDIRECT() function. In the buildDataSheet(0 method, a series of - // named regions are created and the names of three of them mirror - // the options available to the user in the first drop down list - // (in cell A1). Using the INDIRECT() function makes it possible - // to convert the selection the user makes in that first drop down - // into the addresses of a named region of cells and then to use - // those cells to populate the second drop down list. - addressList = new CellRangeAddressList(0, 0, 1, 1); - dvConstraint = dvHelper.createFormulaListConstraint( - "INDIRECT(UPPER($A$1))"); - validation = dvHelper.createValidation(dvConstraint, addressList); - sheet.addValidationData(validation); - - FileOutputStream fos = new FileOutputStream(workbookName); - workbook.write(fos); - fos.close(); - workbook.close(); - } - - /** - * Called to populate the named areas/regions. The contents of the cells on - * row one will be used to populate the first drop down list. The contents of - * the cells on rows two, three and four will be used to populate the second - * drop down list, just which row will be determined by the choice the user - * makes in the first drop down list. - * - * In all cases, the approach is to create a row, create and populate cells - * with data and then specify a name that identifies those cells. With the - * exception of the first range, the names that are chosen for each range - * of cells are quite important. In short, each of the options the user - * could select in the first drop down list is used as the name for another - * range of cells. Thus, in this example, the user can select either - * 'Animal', 'Vegetable' or 'Mineral' in the first drop down and so the - * sheet contains ranges named 'ANIMAL', 'VEGETABLE' and 'MINERAL'. - * - * @param dataSheet An instance of a class that implements the Sheet Sheet - * interface (HSSFSheet or XSSFSheet). - */ - private static final void buildDataSheet(Sheet dataSheet) { - Row row = null; - Cell cell = null; - Name name = null; - - // The first row will hold the data for the first validation. - row = dataSheet.createRow(10); - cell = row.createCell(0); - cell.setCellValue("Animal"); - cell = row.createCell(1); - cell.setCellValue("Vegetable"); - cell = row.createCell(2); - cell.setCellValue("Mineral"); - name = dataSheet.getWorkbook().createName(); - name.setRefersToFormula("$A$11:$C$11"); - name.setNameName("CHOICES"); - - // The next three rows will hold the data that will be used to - // populate the second, or linked, drop down list. - row = dataSheet.createRow(11); - cell = row.createCell(0); - cell.setCellValue("Lion"); - cell = row.createCell(1); - cell.setCellValue("Tiger"); - cell = row.createCell(2); - cell.setCellValue("Leopard"); - cell = row.createCell(3); - cell.setCellValue("Elephant"); - cell = row.createCell(4); - cell.setCellValue("Eagle"); - cell = row.createCell(5); - cell.setCellValue("Horse"); - cell = row.createCell(6); - cell.setCellValue("Zebra"); - name = dataSheet.getWorkbook().createName(); - name.setRefersToFormula("$A$12:$G$12"); - name.setNameName("ANIMAL"); - - row = dataSheet.createRow(12); - cell = row.createCell(0); - cell.setCellValue("Cabbage"); - cell = row.createCell(1); - cell.setCellValue("Cauliflower"); - cell = row.createCell(2); - cell.setCellValue("Potato"); - cell = row.createCell(3); - cell.setCellValue("Onion"); - cell = row.createCell(4); - cell.setCellValue("Beetroot"); - cell = row.createCell(5); - cell.setCellValue("Asparagus"); - cell = row.createCell(6); - cell.setCellValue("Spinach"); - cell = row.createCell(7); - cell.setCellValue("Chard"); - name = dataSheet.getWorkbook().createName(); - name.setRefersToFormula("$A$13:$H$13"); - name.setNameName("VEGETABLE"); - - row = dataSheet.createRow(13); - cell = row.createCell(0); - cell.setCellValue("Bauxite"); - cell = row.createCell(1); - cell.setCellValue("Quartz"); - cell = row.createCell(2); - cell.setCellValue("Feldspar"); - cell = row.createCell(3); - cell.setCellValue("Shist"); - cell = row.createCell(4); - cell.setCellValue("Shale"); - cell = row.createCell(5); - cell.setCellValue("Mica"); - name = dataSheet.getWorkbook().createName(); - name.setRefersToFormula("$A$14:$F$14"); - name.setNameName("MINERAL"); - } -} diff --git a/src/examples/src/org/apache/poi/ss/examples/LoadEmbedded.java b/src/examples/src/org/apache/poi/ss/examples/LoadEmbedded.java deleted file mode 100644 index 2ad0347f7..000000000 --- a/src/examples/src/org/apache/poi/ss/examples/LoadEmbedded.java +++ /dev/null @@ -1,131 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.examples; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.EncryptedDocumentException; -import org.apache.poi.hslf.usermodel.HSLFSlideShow; -import org.apache.poi.hssf.usermodel.HSSFObjectData; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.hwpf.HWPFDocument; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.exceptions.OpenXML4JException; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.poifs.filesystem.DirectoryNode; -import org.apache.poi.poifs.filesystem.Entry; -import org.apache.poi.sl.usermodel.SlideShow; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.usermodel.WorkbookFactory; -import org.apache.poi.xslf.usermodel.XMLSlideShow; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.apache.poi.xwpf.usermodel.XWPFDocument; -import org.apache.xmlbeans.XmlException; - -/** - * Loads embedded resources from Workbooks. Code taken from the website: - * https://poi.apache.org/spreadsheet/quick-guide.html#Embedded - */ -public class LoadEmbedded { - public static void main(String[] args) throws IOException, EncryptedDocumentException, OpenXML4JException, XmlException { - Workbook wb = WorkbookFactory.create(new File(args[0])); - loadEmbedded(wb); - } - - public static void loadEmbedded(Workbook wb) throws IOException, InvalidFormatException, OpenXML4JException, XmlException { - if (wb instanceof HSSFWorkbook) { - loadEmbedded((HSSFWorkbook)wb); - } - else if (wb instanceof XSSFWorkbook) { - loadEmbedded((XSSFWorkbook)wb); - } - else { - throw new IllegalArgumentException(wb.getClass().getName()); - } - } - - public static void loadEmbedded(HSSFWorkbook workbook) throws IOException { - for (HSSFObjectData obj : workbook.getAllEmbeddedObjects()) { - //the OLE2 Class Name of the object - String oleName = obj.getOLE2ClassName(); - if (oleName.equals("Worksheet")) { - DirectoryNode dn = (DirectoryNode) obj.getDirectory(); - HSSFWorkbook embeddedWorkbook = new HSSFWorkbook(dn, false); - embeddedWorkbook.close(); - } else if (oleName.equals("Document")) { - DirectoryNode dn = (DirectoryNode) obj.getDirectory(); - HWPFDocument embeddedWordDocument = new HWPFDocument(dn); - embeddedWordDocument.close(); - } else if (oleName.equals("Presentation")) { - DirectoryNode dn = (DirectoryNode) obj.getDirectory(); - SlideShow embeddedSlieShow = new HSLFSlideShow(dn); - embeddedSlieShow.close(); - } else { - if(obj.hasDirectoryEntry()){ - // The DirectoryEntry is a DocumentNode. Examine its entries to find out what it is - DirectoryNode dn = (DirectoryNode) obj.getDirectory(); - for (Entry entry : dn) { - //System.out.println(oleName + "." + entry.getName()); - } - } else { - // There is no DirectoryEntry - // Recover the object's data from the HSSFObjectData instance. - byte[] objectData = obj.getObjectData(); - } - } - } - } - - public static void loadEmbedded(XSSFWorkbook workbook) throws IOException, InvalidFormatException, OpenXML4JException, XmlException { - for (PackagePart pPart : workbook.getAllEmbedds()) { - String contentType = pPart.getContentType(); - if (contentType.equals("application/vnd.ms-excel")) { - // Excel Workbook - either binary or OpenXML - HSSFWorkbook embeddedWorkbook = new HSSFWorkbook(pPart.getInputStream()); - embeddedWorkbook.close(); - } else if (contentType.equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) { - // Excel Workbook - OpenXML file format - XSSFWorkbook embeddedWorkbook = new XSSFWorkbook(pPart.getInputStream()); - embeddedWorkbook.close(); - } else if (contentType.equals("application/msword")) { - // Word Document - binary (OLE2CDF) file format - HWPFDocument document = new HWPFDocument(pPart.getInputStream()); - document.close(); - } else if (contentType.equals("application/vnd.openxmlformats-officedocument.wordprocessingml.document")) { - // Word Document - OpenXML file format - XWPFDocument document = new XWPFDocument(pPart.getInputStream()); - document.close(); - } else if (contentType.equals("application/vnd.ms-powerpoint")) { - // PowerPoint Document - binary file format - HSLFSlideShow slideShow = new HSLFSlideShow(pPart.getInputStream()); - slideShow.close(); - } else if (contentType.equals("application/vnd.openxmlformats-officedocument.presentationml.presentation")) { - // PowerPoint Document - OpenXML file format - XMLSlideShow slideShow = new XMLSlideShow(pPart.getInputStream()); - slideShow.close(); - } else { - // Any other type of embedded object. - System.out.println("Unknown Embedded Document: " + contentType); - InputStream inputStream = pPart.getInputStream(); - inputStream.close(); - } - } - } -} diff --git a/src/examples/src/org/apache/poi/ss/examples/LoanCalculator.java b/src/examples/src/org/apache/poi/ss/examples/LoanCalculator.java deleted file mode 100644 index d6375dc43..000000000 --- a/src/examples/src/org/apache/poi/ss/examples/LoanCalculator.java +++ /dev/null @@ -1,305 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.examples; - -import org.apache.poi.xssf.usermodel.*; -import org.apache.poi.ss.usermodel.*; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; - -import java.util.Map; -import java.util.HashMap; -import java.io.FileOutputStream; - -/** - * Simple Loan Calculator. Demonstrates advance usage of cell formulas and named ranges. - * - * Usage: - * LoanCalculator -xls|xlsx - * - * @author Yegor Kozlov - */ -public class LoanCalculator { - - public static void main(String[] args) throws Exception { - Workbook wb; - - if(args.length > 0 && args[0].equals("-xls")) wb = new HSSFWorkbook(); - else wb = new XSSFWorkbook(); - - Map styles = createStyles(wb); - Sheet sheet = wb.createSheet("Loan Calculator"); - sheet.setPrintGridlines(false); - sheet.setDisplayGridlines(false); - - PrintSetup printSetup = sheet.getPrintSetup(); - printSetup.setLandscape(true); - sheet.setFitToPage(true); - sheet.setHorizontallyCenter(true); - - sheet.setColumnWidth(0, 3*256); - sheet.setColumnWidth(1, 3*256); - sheet.setColumnWidth(2, 11*256); - sheet.setColumnWidth(3, 14*256); - sheet.setColumnWidth(4, 14*256); - sheet.setColumnWidth(5, 14*256); - sheet.setColumnWidth(6, 14*256); - - createNames(wb); - - Row titleRow = sheet.createRow(0); - titleRow.setHeightInPoints(35); - for (int i = 1; i <= 7; i++) { - titleRow.createCell(i).setCellStyle(styles.get("title")); - } - Cell titleCell = titleRow.getCell(2); - titleCell.setCellValue("Simple Loan Calculator"); - sheet.addMergedRegion(CellRangeAddress.valueOf("$C$1:$H$1")); - - Row row = sheet.createRow(2); - Cell cell = row.createCell(4); - cell.setCellValue("Enter values"); - cell.setCellStyle(styles.get("item_right")); - - row = sheet.createRow(3); - cell = row.createCell(2); - cell.setCellValue("Loan amount"); - cell.setCellStyle(styles.get("item_left")); - cell = row.createCell(4); - cell.setCellStyle(styles.get("input_$")); - cell.setAsActiveCell(); - - row = sheet.createRow(4); - cell = row.createCell(2); - cell.setCellValue("Annual interest rate"); - cell.setCellStyle(styles.get("item_left")); - cell = row.createCell(4); - cell.setCellStyle(styles.get("input_%")); - - row = sheet.createRow(5); - cell = row.createCell(2); - cell.setCellValue("Loan period in years"); - cell.setCellStyle(styles.get("item_left")); - cell = row.createCell(4); - cell.setCellStyle(styles.get("input_i")); - - row = sheet.createRow(6); - cell = row.createCell(2); - cell.setCellValue("Start date of loan"); - cell.setCellStyle(styles.get("item_left")); - cell = row.createCell(4); - cell.setCellStyle(styles.get("input_d")); - - row = sheet.createRow(8); - cell = row.createCell(2); - cell.setCellValue("Monthly payment"); - cell.setCellStyle(styles.get("item_left")); - cell = row.createCell(4); - cell.setCellFormula("IF(Values_Entered,Monthly_Payment,\"\")"); - cell.setCellStyle(styles.get("formula_$")); - - row = sheet.createRow(9); - cell = row.createCell(2); - cell.setCellValue("Number of payments"); - cell.setCellStyle(styles.get("item_left")); - cell = row.createCell(4); - cell.setCellFormula("IF(Values_Entered,Loan_Years*12,\"\")"); - cell.setCellStyle(styles.get("formula_i")); - - row = sheet.createRow(10); - cell = row.createCell(2); - cell.setCellValue("Total interest"); - cell.setCellStyle(styles.get("item_left")); - cell = row.createCell(4); - cell.setCellFormula("IF(Values_Entered,Total_Cost-Loan_Amount,\"\")"); - cell.setCellStyle(styles.get("formula_$")); - - row = sheet.createRow(11); - cell = row.createCell(2); - cell.setCellValue("Total cost of loan"); - cell.setCellStyle(styles.get("item_left")); - cell = row.createCell(4); - cell.setCellFormula("IF(Values_Entered,Monthly_Payment*Number_of_Payments,\"\")"); - cell.setCellStyle(styles.get("formula_$")); - - - // Write the output to a file - String file = "loan-calculator.xls"; - if(wb instanceof XSSFWorkbook) file += "x"; - FileOutputStream out = new FileOutputStream(file); - wb.write(out); - out.close(); - } - - /** - * cell styles used for formatting calendar sheets - */ - private static Map createStyles(Workbook wb){ - Map styles = new HashMap(); - - CellStyle style; - Font titleFont = wb.createFont(); - titleFont.setFontHeightInPoints((short)14); - titleFont.setFontName("Trebuchet MS"); - style = wb.createCellStyle(); - style.setFont(titleFont); - style.setBorderBottom(BorderStyle.DOTTED); - style.setBottomBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); - styles.put("title", style); - - Font itemFont = wb.createFont(); - itemFont.setFontHeightInPoints((short)9); - itemFont.setFontName("Trebuchet MS"); - style = wb.createCellStyle(); - style.setAlignment(HorizontalAlignment.LEFT); - style.setFont(itemFont); - styles.put("item_left", style); - - style = wb.createCellStyle(); - style.setAlignment(HorizontalAlignment.RIGHT); - style.setFont(itemFont); - styles.put("item_right", style); - - style = wb.createCellStyle(); - style.setAlignment(HorizontalAlignment.RIGHT); - style.setFont(itemFont); - style.setBorderRight(BorderStyle.DOTTED); - style.setRightBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); - style.setBorderBottom(BorderStyle.DOTTED); - style.setBottomBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); - style.setBorderLeft(BorderStyle.DOTTED); - style.setLeftBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); - style.setBorderTop(BorderStyle.DOTTED); - style.setTopBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); - style.setDataFormat(wb.createDataFormat().getFormat("_($* #,##0.00_);_($* (#,##0.00);_($* \"-\"??_);_(@_)")); - styles.put("input_$", style); - - style = wb.createCellStyle(); - style.setAlignment(HorizontalAlignment.RIGHT); - style.setFont(itemFont); - style.setBorderRight(BorderStyle.DOTTED); - style.setRightBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); - style.setBorderBottom(BorderStyle.DOTTED); - style.setBottomBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); - style.setBorderLeft(BorderStyle.DOTTED); - style.setLeftBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); - style.setBorderTop(BorderStyle.DOTTED); - style.setTopBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); - style.setDataFormat(wb.createDataFormat().getFormat("0.000%")); - styles.put("input_%", style); - - style = wb.createCellStyle(); - style.setAlignment(HorizontalAlignment.RIGHT); - style.setFont(itemFont); - style.setBorderRight(BorderStyle.DOTTED); - style.setRightBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); - style.setBorderBottom(BorderStyle.DOTTED); - style.setBottomBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); - style.setBorderLeft(BorderStyle.DOTTED); - style.setLeftBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); - style.setBorderTop(BorderStyle.DOTTED); - style.setTopBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); - style.setDataFormat(wb.createDataFormat().getFormat("0")); - styles.put("input_i", style); - - style = wb.createCellStyle(); - style.setAlignment(HorizontalAlignment.CENTER); - style.setFont(itemFont); - style.setDataFormat(wb.createDataFormat().getFormat("m/d/yy")); - styles.put("input_d", style); - - style = wb.createCellStyle(); - style.setAlignment(HorizontalAlignment.RIGHT); - style.setFont(itemFont); - style.setBorderRight(BorderStyle.DOTTED); - style.setRightBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); - style.setBorderBottom(BorderStyle.DOTTED); - style.setBottomBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); - style.setBorderLeft(BorderStyle.DOTTED); - style.setLeftBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); - style.setBorderTop(BorderStyle.DOTTED); - style.setTopBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); - style.setDataFormat(wb.createDataFormat().getFormat("$##,##0.00")); - style.setBorderBottom(BorderStyle.DOTTED); - style.setBottomBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); - style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); - style.setFillPattern(FillPatternType.SOLID_FOREGROUND); - styles.put("formula_$", style); - - style = wb.createCellStyle(); - style.setAlignment(HorizontalAlignment.RIGHT); - style.setFont(itemFont); - style.setBorderRight(BorderStyle.DOTTED); - style.setRightBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); - style.setBorderBottom(BorderStyle.DOTTED); - style.setBottomBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); - style.setBorderLeft(BorderStyle.DOTTED); - style.setLeftBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); - style.setBorderTop(BorderStyle.DOTTED); - style.setTopBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); - style.setDataFormat(wb.createDataFormat().getFormat("0")); - style.setBorderBottom(BorderStyle.DOTTED); - style.setBottomBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); - style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); - style.setFillPattern(FillPatternType.SOLID_FOREGROUND); - styles.put("formula_i", style); - - return styles; - } - - //define named ranges for the inputs and formulas - public static void createNames(Workbook wb){ - Name name; - - name = wb.createName(); - name.setNameName("Interest_Rate"); - name.setRefersToFormula("'Loan Calculator'!$E$5"); - - name = wb.createName(); - name.setNameName("Loan_Amount"); - name.setRefersToFormula("'Loan Calculator'!$E$4"); - - name = wb.createName(); - name.setNameName("Loan_Start"); - name.setRefersToFormula("'Loan Calculator'!$E$7"); - - name = wb.createName(); - name.setNameName("Loan_Years"); - name.setRefersToFormula("'Loan Calculator'!$E$6"); - - name = wb.createName(); - name.setNameName("Number_of_Payments"); - name.setRefersToFormula("'Loan Calculator'!$E$10"); - - name = wb.createName(); - name.setNameName("Monthly_Payment"); - name.setRefersToFormula("-PMT(Interest_Rate/12,Number_of_Payments,Loan_Amount)"); - - name = wb.createName(); - name.setNameName("Total_Cost"); - name.setRefersToFormula("'Loan Calculator'!$E$12"); - - name = wb.createName(); - name.setNameName("Total_Interest"); - name.setRefersToFormula("'Loan Calculator'!$E$11"); - - name = wb.createName(); - name.setNameName("Values_Entered"); - name.setRefersToFormula("IF(Loan_Amount*Interest_Rate*Loan_Years*Loan_Start>0,1,0)"); - } -} diff --git a/src/examples/src/org/apache/poi/ss/examples/SSPerformanceTest.java b/src/examples/src/org/apache/poi/ss/examples/SSPerformanceTest.java deleted file mode 100644 index 10c3a4a7d..000000000 --- a/src/examples/src/org/apache/poi/ss/examples/SSPerformanceTest.java +++ /dev/null @@ -1,229 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -package org.apache.poi.ss.examples; - -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Calendar; -import java.util.HashMap; -import java.util.Map; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.FillPatternType; -import org.apache.poi.ss.usermodel.Font; -import org.apache.poi.ss.usermodel.HorizontalAlignment; -import org.apache.poi.ss.usermodel.IndexedColors; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.VerticalAlignment; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.xssf.streaming.SXSSFWorkbook; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -public class SSPerformanceTest { - public static void main(String[] args) throws IOException { - if (args.length != 4) usage("need four command arguments"); - - String type = args[0]; - long timeStarted = System.currentTimeMillis(); - Workbook workBook = createWorkbook(type); - boolean isHType = workBook instanceof HSSFWorkbook; - - int rows = parseInt(args[1], "Failed to parse rows value as integer"); - int cols = parseInt(args[2], "Failed to parse cols value as integer"); - boolean saveFile = parseInt(args[3], "Failed to parse saveFile value as integer") != 0; - - addContent(workBook, isHType, rows, cols); - - if (saveFile) { - String fileName = type + "_" + rows + "_" + cols + "." + getFileSuffix(args[0]); - saveFile(workBook, fileName); - } - long timeFinished = System.currentTimeMillis(); - System.out.println("Elapsed " + (timeFinished-timeStarted)/1000 + " seconds"); - - workBook.close(); - } - - private static void addContent(Workbook workBook, boolean isHType, int rows, int cols) { - Map styles = createStyles(workBook); - - Sheet sheet = workBook.createSheet("Main Sheet"); - - Cell headerCell = sheet.createRow(0).createCell(0); - headerCell.setCellValue("Header text is spanned across multiple cells"); - headerCell.setCellStyle(styles.get("header")); - sheet.addMergedRegion(CellRangeAddress.valueOf("$A$1:$F$1")); - - int sheetNo = 0; - int rowIndexInSheet = 1; - double value = 0; - Calendar calendar = Calendar.getInstance(); - for (int rowIndex = 0; rowIndex < rows; rowIndex++) { - if (isHType && sheetNo != rowIndex / 0x10000) { - sheet = workBook.createSheet("Spillover from sheet " + (++sheetNo)); - headerCell.setCellValue("Header text is spanned across multiple cells"); - headerCell.setCellStyle(styles.get("header")); - sheet.addMergedRegion(CellRangeAddress.valueOf("$A$1:$F$1")); - rowIndexInSheet = 1; - } - - Row row = sheet.createRow(rowIndexInSheet); - for (int colIndex = 0; colIndex < cols; colIndex++) { - value = populateCell(styles, value, calendar, rowIndex, row, colIndex); - } - rowIndexInSheet++; - } - } - - private static double populateCell(Map styles, double value, Calendar calendar, int rowIndex, Row row, int colIndex) { - Cell cell = row.createCell(colIndex); - String address = new CellReference(cell).formatAsString(); - switch (colIndex){ - case 0: - // column A: default number format - cell.setCellValue(value++); - break; - case 1: - // column B: #,##0 - cell.setCellValue(value++); - cell.setCellStyle(styles.get("#,##0.00")); - break; - case 2: - // column C: $#,##0.00 - cell.setCellValue(value++); - cell.setCellStyle(styles.get("$#,##0.00")); - break; - case 3: - // column D: red bold text on yellow background - cell.setCellValue(address); - cell.setCellStyle(styles.get("red-bold")); - break; - case 4: - // column E: boolean - // TODO booleans are shown as 1/0 instead of TRUE/FALSE - cell.setCellValue(rowIndex % 2 == 0); - break; - case 5: - // column F: date / time - cell.setCellValue(calendar); - cell.setCellStyle(styles.get("m/d/yyyy")); - calendar.roll(Calendar.DAY_OF_YEAR, -1); - break; - case 6: - // column F: formula - // TODO formulas are not yet supported in SXSSF - //cell.setCellFormula("SUM(A" + (rowIndex+1) + ":E" + (rowIndex+1)+ ")"); - //break; - default: - cell.setCellValue(value++); - break; - } - return value; - } - - private static void saveFile(Workbook workBook, String fileName) { - try { - FileOutputStream out = new FileOutputStream(fileName); - workBook.write(out); - out.close(); - } catch (IOException ioe) { - System.err.println("Error: failed to write to file \"" + fileName + "\", reason=" + ioe.getMessage()); - } - } - - static Map createStyles(Workbook wb) { - Map styles = new HashMap(); - CellStyle style; - - Font headerFont = wb.createFont(); - headerFont.setFontHeightInPoints((short) 14); - headerFont.setBold(true); - style = wb.createCellStyle(); - style.setAlignment(HorizontalAlignment.CENTER); - style.setVerticalAlignment(VerticalAlignment.CENTER); - style.setFont(headerFont); - style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex()); - style.setFillPattern(FillPatternType.SOLID_FOREGROUND); - styles.put("header", style); - - Font monthFont = wb.createFont(); - monthFont.setFontHeightInPoints((short)12); - monthFont.setColor(IndexedColors.RED.getIndex()); - monthFont.setBold(true); - style = wb.createCellStyle(); - style.setAlignment(HorizontalAlignment.CENTER); - style.setVerticalAlignment(VerticalAlignment.CENTER); - style.setFillForegroundColor(IndexedColors.YELLOW.getIndex()); - style.setFillPattern(FillPatternType.SOLID_FOREGROUND); - style.setFont(monthFont); - styles.put("red-bold", style); - - String[] nfmt = {"#,##0.00", "$#,##0.00", "m/d/yyyy"}; - for(String fmt : nfmt){ - style = wb.createCellStyle(); - style.setDataFormat(wb.createDataFormat().getFormat(fmt)); - styles.put(fmt, style); - } - - return styles; - } - - - static void usage(String message) { - System.err.println(message); - System.err.println("usage: java SSPerformanceTest HSSF|XSSF|SXSSF rows cols saveFile (0|1)? "); - System.exit(1); - } - - static Workbook createWorkbook(String type) { - if ("HSSF".equals(type)) - return new HSSFWorkbook(); - else if ("XSSF".equals(type)) - return new XSSFWorkbook(); - else if ("SXSSF".equals(type)) - return new SXSSFWorkbook(); - else - usage("Unknown type \"" + type + "\""); - return null; - } - - static String getFileSuffix(String type) { - if ("HSSF".equals(type)) - return "xls"; - else if ("XSSF".equals(type)) - return "xlsx"; - else if ("SXSSF".equals(type)) - return "xlsx"; - return null; - } - - static int parseInt(String value, String msg) { - try { - return Integer.parseInt(value); - } catch (NumberFormatException e) { - usage(msg); - } - return 0; - } -} diff --git a/src/examples/src/org/apache/poi/ss/examples/TimesheetDemo.java b/src/examples/src/org/apache/poi/ss/examples/TimesheetDemo.java deleted file mode 100644 index 8ef20fe43..000000000 --- a/src/examples/src/org/apache/poi/ss/examples/TimesheetDemo.java +++ /dev/null @@ -1,220 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.examples; - -import org.apache.poi.xssf.usermodel.*; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.usermodel.*; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; - -import java.util.Map; -import java.util.HashMap; -import java.io.FileOutputStream; - -/** - * A weekly timesheet created using Apache POI. - * Usage: - * TimesheetDemo -xls|xlsx - * - * @author Yegor Kozlov - */ -public class TimesheetDemo { - private static final String[] titles = { - "Person", "ID", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun", - "Total\nHrs", "Overtime\nHrs", "Regular\nHrs" - }; - - private static Object[][] sample_data = { - {"Yegor Kozlov", "YK", 5.0, 8.0, 10.0, 5.0, 5.0, 7.0, 6.0}, - {"Gisella Bronzetti", "GB", 4.0, 3.0, 1.0, 3.5, null, null, 4.0}, - }; - - public static void main(String[] args) throws Exception { - Workbook wb; - - if(args.length > 0 && args[0].equals("-xls")) wb = new HSSFWorkbook(); - else wb = new XSSFWorkbook(); - - Map styles = createStyles(wb); - - Sheet sheet = wb.createSheet("Timesheet"); - PrintSetup printSetup = sheet.getPrintSetup(); - printSetup.setLandscape(true); - sheet.setFitToPage(true); - sheet.setHorizontallyCenter(true); - - //title row - Row titleRow = sheet.createRow(0); - titleRow.setHeightInPoints(45); - Cell titleCell = titleRow.createCell(0); - titleCell.setCellValue("Weekly Timesheet"); - titleCell.setCellStyle(styles.get("title")); - sheet.addMergedRegion(CellRangeAddress.valueOf("$A$1:$L$1")); - - //header row - Row headerRow = sheet.createRow(1); - headerRow.setHeightInPoints(40); - Cell headerCell; - for (int i = 0; i < titles.length; i++) { - headerCell = headerRow.createCell(i); - headerCell.setCellValue(titles[i]); - headerCell.setCellStyle(styles.get("header")); - } - - int rownum = 2; - for (int i = 0; i < 10; i++) { - Row row = sheet.createRow(rownum++); - for (int j = 0; j < titles.length; j++) { - Cell cell = row.createCell(j); - if(j == 9){ - //the 10th cell contains sum over week days, e.g. SUM(C3:I3) - String ref = "C" +rownum+ ":I" + rownum; - cell.setCellFormula("SUM("+ref+")"); - cell.setCellStyle(styles.get("formula")); - } else if (j == 11){ - cell.setCellFormula("J" +rownum+ "-K" + rownum); - cell.setCellStyle(styles.get("formula")); - } else { - cell.setCellStyle(styles.get("cell")); - } - } - } - - //row with totals below - Row sumRow = sheet.createRow(rownum++); - sumRow.setHeightInPoints(35); - Cell cell; - cell = sumRow.createCell(0); - cell.setCellStyle(styles.get("formula")); - cell = sumRow.createCell(1); - cell.setCellValue("Total Hrs:"); - cell.setCellStyle(styles.get("formula")); - - for (int j = 2; j < 12; j++) { - cell = sumRow.createCell(j); - String ref = (char)('A' + j) + "3:" + (char)('A' + j) + "12"; - cell.setCellFormula("SUM(" + ref + ")"); - if(j >= 9) cell.setCellStyle(styles.get("formula_2")); - else cell.setCellStyle(styles.get("formula")); - } - rownum++; - sumRow = sheet.createRow(rownum++); - sumRow.setHeightInPoints(25); - cell = sumRow.createCell(0); - cell.setCellValue("Total Regular Hours"); - cell.setCellStyle(styles.get("formula")); - cell = sumRow.createCell(1); - cell.setCellFormula("L13"); - cell.setCellStyle(styles.get("formula_2")); - sumRow = sheet.createRow(rownum++); - sumRow.setHeightInPoints(25); - cell = sumRow.createCell(0); - cell.setCellValue("Total Overtime Hours"); - cell.setCellStyle(styles.get("formula")); - cell = sumRow.createCell(1); - cell.setCellFormula("K13"); - cell.setCellStyle(styles.get("formula_2")); - - //set sample data - for (int i = 0; i < sample_data.length; i++) { - Row row = sheet.getRow(2 + i); - for (int j = 0; j < sample_data[i].length; j++) { - if(sample_data[i][j] == null) continue; - - if(sample_data[i][j] instanceof String) { - row.getCell(j).setCellValue((String)sample_data[i][j]); - } else { - row.getCell(j).setCellValue((Double)sample_data[i][j]); - } - } - } - - //finally set column widths, the width is measured in units of 1/256th of a character width - sheet.setColumnWidth(0, 30*256); //30 characters wide - for (int i = 2; i < 9; i++) { - sheet.setColumnWidth(i, 6*256); //6 characters wide - } - sheet.setColumnWidth(10, 10*256); //10 characters wide - - // Write the output to a file - String file = "timesheet.xls"; - if(wb instanceof XSSFWorkbook) file += "x"; - FileOutputStream out = new FileOutputStream(file); - wb.write(out); - out.close(); - } - - /** - * Create a library of cell styles - */ - private static Map createStyles(Workbook wb){ - Map styles = new HashMap(); - CellStyle style; - Font titleFont = wb.createFont(); - titleFont.setFontHeightInPoints((short)18); - titleFont.setBold(true); - style = wb.createCellStyle(); - style.setAlignment(HorizontalAlignment.CENTER); - style.setVerticalAlignment(VerticalAlignment.CENTER); - style.setFont(titleFont); - styles.put("title", style); - - Font monthFont = wb.createFont(); - monthFont.setFontHeightInPoints((short)11); - monthFont.setColor(IndexedColors.WHITE.getIndex()); - style = wb.createCellStyle(); - style.setAlignment(HorizontalAlignment.CENTER); - style.setVerticalAlignment(VerticalAlignment.CENTER); - style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex()); - style.setFillPattern(FillPatternType.SOLID_FOREGROUND); - style.setFont(monthFont); - style.setWrapText(true); - styles.put("header", style); - - style = wb.createCellStyle(); - style.setAlignment(HorizontalAlignment.CENTER); - style.setWrapText(true); - style.setBorderRight(BorderStyle.THIN); - style.setRightBorderColor(IndexedColors.BLACK.getIndex()); - style.setBorderLeft(BorderStyle.THIN); - style.setLeftBorderColor(IndexedColors.BLACK.getIndex()); - style.setBorderTop(BorderStyle.THIN); - style.setTopBorderColor(IndexedColors.BLACK.getIndex()); - style.setBorderBottom(BorderStyle.THIN); - style.setBottomBorderColor(IndexedColors.BLACK.getIndex()); - styles.put("cell", style); - - style = wb.createCellStyle(); - style.setAlignment(HorizontalAlignment.CENTER); - style.setVerticalAlignment(VerticalAlignment.CENTER); - style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); - style.setFillPattern(FillPatternType.SOLID_FOREGROUND); - style.setDataFormat(wb.createDataFormat().getFormat("0.00")); - styles.put("formula", style); - - style = wb.createCellStyle(); - style.setAlignment(HorizontalAlignment.CENTER); - style.setVerticalAlignment(VerticalAlignment.CENTER); - style.setFillForegroundColor(IndexedColors.GREY_40_PERCENT.getIndex()); - style.setFillPattern(FillPatternType.SOLID_FOREGROUND); - style.setDataFormat(wb.createDataFormat().getFormat("0.00")); - styles.put("formula_2", style); - - return styles; - } -} diff --git a/src/examples/src/org/apache/poi/ss/examples/ToCSV.java b/src/examples/src/org/apache/poi/ss/examples/ToCSV.java deleted file mode 100644 index b6c5ea972..000000000 --- a/src/examples/src/org/apache/poi/ss/examples/ToCSV.java +++ /dev/null @@ -1,774 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.examples; - - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileWriter; -import java.io.FilenameFilter; -import java.io.IOException; -import java.util.ArrayList; - -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.DataFormatter; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.usermodel.WorkbookFactory; - -/** - * Demonstrates one way to convert an Excel spreadsheet into a CSV - * file. This class makes the following assumptions; - * - *
  • 1. Where the Excel workbook contains more that one worksheet, then a single - * CSV file will contain the data from all of the worksheets.
  • - *
  • 2. The data matrix contained in the CSV file will be square. This means that - * the number of fields in each record of the CSV file will match the number - * of cells in the longest row found in the Excel workbook. Any short records - * will be 'padded' with empty fields - an empty field is represented in the - * the CSV file in this way - ,,.
  • - *
  • 3. Empty fields will represent missing cells.
  • - *
  • 4. A record consisting of empty fields will be used to represent an empty row - * in the Excel workbook.
  • - *
    - * Therefore, if the worksheet looked like this; - * - *
    - *  ___________________________________________
    - *     |       |       |       |       |       |
    - *     |   A   |   B   |   C   |   D   |   E   |
    - *  ___|_______|_______|_______|_______|_______|
    - *     |       |       |       |       |       |
    - *   1 |   1   |   2   |   3   |   4   |   5   |
    - *  ___|_______|_______|_______|_______|_______|
    - *     |       |       |       |       |       |
    - *   2 |       |       |       |       |       |
    - *  ___|_______|_______|_______|_______|_______|
    - *     |       |       |       |       |       |
    - *   3 |       |   A   |       |   B   |       |
    - *  ___|_______|_______|_______|_______|_______|
    - *     |       |       |       |       |       |
    - *   4 |       |       |       |       |   Z   |
    - *  ___|_______|_______|_______|_______|_______|
    - *     |       |       |       |       |       |
    - *   5 | 1,400 |       |  250  |       |       |
    - *  ___|_______|_______|_______|_______|_______|
    - *
    - * 
    - * - * Then, the resulting CSV file will contain the following lines (records); - *
    - * 1,2,3,4,5
    - * ,,,,
    - * ,A,,B,
    - * ,,,,Z
    - * "1,400",,250,,
    - * 

    - * Typically, the comma is used to separate each of the fields that, together, - * constitute a single record or line within the CSV file. This is not however - * a hard and fast rule and so this class allows the user to determine which - * character is used as the field separator and assumes the comma if none other - * is specified. - *

    - * If a field contains the separator then it will be escaped. If the file should - * obey Excel's CSV formatting rules, then the field will be surrounded with - * speech marks whilst if it should obey UNIX conventions, each occurrence of - * the separator will be preceded by the backslash character. - *

    - * If a field contains an end of line (EOL) character then it too will be - * escaped. If the file should obey Excel's CSV formatting rules then the field - * will again be surrounded by speech marks. On the other hand, if the file - * should follow UNIX conventions then a single backslash will precede the - * EOL character. There is no single applicable standard for UNIX and some - * appications replace the CR with \r and the LF with \n but this class will - * not do so. - *

    - * If the field contains double quotes then that character will be escaped. It - * seems as though UNIX does not define a standard for this whilst Excel does. - * Should the CSV file have to obey Excel's formmating rules then the speech - * mark character will be escaped with a second set of speech marks. Finally, an - * enclosing set of speah marks will also surround the entire field. Thus, if - * the following line of text appeared in a cell - "Hello" he said - it would - * look like this when converted into a field within a CSV file - """Hello"" he - * said". - *

    - * Finally, it is worth noting that talk of CSV 'standards' is really slightly - * missleading as there is no such thing. It may well be that the code in this - * class has to be modified to produce files to suit a specific application - * or requirement. - *

    - * @author Mark B - * @version 1.00 9th April 2010 - * 1.10 13th April 2010 - Added support for processing all Excel - * workbooks in a folder along with the ability - * to specify a field separator character. - * 2.00 14th April 2010 - Added support for embedded characters; the - * field separator, EOL and double quotes or - * speech marks. In addition, gave the client - * the ability to select how these are handled, - * either obeying Excel's or UNIX formatting - * conventions. - */ -public class ToCSV { - - private Workbook workbook = null; - private ArrayList> csvData = null; - private int maxRowWidth = 0; - private int formattingConvention = 0; - private DataFormatter formatter = null; - private FormulaEvaluator evaluator = null; - private String separator = null; - - private static final String CSV_FILE_EXTENSION = ".csv"; - private static final String DEFAULT_SEPARATOR = ","; - - /** - * Identifies that the CSV file should obey Excel's formatting conventions - * with regard to escaping certain embedded characters - the field separator, - * speech mark and end of line (EOL) character - */ - public static final int EXCEL_STYLE_ESCAPING = 0; - - /** - * Identifies that the CSV file should obey UNIX formatting conventions - * with regard to escaping certain embedded characters - the field separator - * and end of line (EOL) character - */ - public static final int UNIX_STYLE_ESCAPING = 1; - - /** - * Process the contents of a folder, convert the contents of each Excel - * workbook into CSV format and save the resulting file to the specified - * folder using the same name as the original workbook with the .xls or - * .xlsx extension replaced by .csv. This method will ensure that the - * CSV file created contains the comma field separator and that embedded - * characters such as the field separator, the EOL and double quotes are - * escaped in accordance with Excel's convention. - * - * @param strSource An instance of the String class that encapsulates the - * name of and path to either a folder containing those Excel - * workbook(s) or the name of and path to an individual Excel workbook - * that is/are to be converted. - * @param strDestination An instance of the String class encapsulating the - * name of and path to a folder that will contain the resulting CSV - * files. - * @throws java.io.FileNotFoundException Thrown if any file cannot be located - * on the filesystem during processing. - * @throws java.io.IOException Thrown if the filesystem encounters any - * problems during processing. - * @throws java.lang.IllegalArgumentException Thrown if the values passed - * to the strSource parameter refers to a file or folder that does not - * exist or if the value passed to the strDestination paramater refers - * to a folder that does not exist or simply does not refer to a - * folder. - * @throws org.apache.poi.openxml4j.exceptions.InvalidFormatException Thrown - * if the xml markup encountered whilst parsing a SpreadsheetML - * file (.xlsx) is invalid. - */ - public void convertExcelToCSV(String strSource, String strDestination) - throws FileNotFoundException, IOException, - IllegalArgumentException, InvalidFormatException { - - // Simply chain the call to the overloaded convertExcelToCSV(String, - // String, String, int) method, pass the default separator and ensure - // that certain embedded characters are escaped in accordance with - // Excel's formatting conventions - this.convertExcelToCSV(strSource, strDestination, - ToCSV.DEFAULT_SEPARATOR, ToCSV.EXCEL_STYLE_ESCAPING); - } - - /** - * Process the contents of a folder, convert the contents of each Excel - * workbook into CSV format and save the resulting file to the specified - * folder using the same name as the original workbook with the .xls or - * .xlsx extension replaced by .csv. This method allows the client to - * define the field separator but will ensure that embedded characters such - * as the field separator, the EOL and double quotes are escaped in - * accordance with Excel's convention. - * - * @param strSource An instance of the String class that encapsulates the - * name of and path to either a folder containing those Excel - * workbook(s) or the name of and path to an individual Excel workbook - * that is/are to be converted. - * @param strDestination An instance of the String class encapsulating the - * name of and path to a folder that will contain the resulting CSV - * files. - * @param separator An instance of the String class that encapsulates the - * character or characters the client wishes to use as the field - * separator. - * @throws java.io.FileNotFoundException Thrown if any file cannot be located - * on the filesystem during processing. - * @throws java.io.IOException Thrown if the filesystem encounters any - * problems during processing. - * @throws java.lang.IllegalArgumentException Thrown if the values passed - * to the strSource parameter refers to a file or folder that does not - * exist or if the value passed to the strDestination paramater refers - * to a folder that does not exist or simply does not refer to a - * folder. - * @throws org.apache.poi.openxml4j.exceptions.InvalidFormatException Thrown - * if the xml markup encounetered whilst parsing a SpreadsheetML - * file (.xlsx) is invalid. - */ - public void convertExcelToCSV(String strSource, String strDestination, - String separator) - throws FileNotFoundException, IOException, - IllegalArgumentException, InvalidFormatException { - - // Simply chain the call to the overloaded convertExcelToCSV(String, - // String, String, int) method and ensure that certain embedded - // characters are escaped in accordance with Excel's formatting - // conventions - this.convertExcelToCSV(strSource, strDestination, - separator, ToCSV.EXCEL_STYLE_ESCAPING); - } - - /** - * Process the contents of a folder, convert the contents of each Excel - * workbook into CSV format and save the resulting file to the specified - * folder using the same name as the original workbook with the .xls or - * .xlsx extension replaced by .csv - * - * @param strSource An instance of the String class that encapsulates the - * name of and path to either a folder containing those Excel - * workbook(s) or the name of and path to an individual Excel workbook - * that is/are to be converted. - * @param strDestination An instance of the String class encapsulating the name - * of and path to a folder that will contain the resulting CSV files. - * @param formattingConvention A primitive int whose value will determine - * whether certain embedded characters should be escaped in accordance - * with Excel's or UNIX formatting conventions. Two constants are - * defined to support this option; ToCSV.EXCEL_STYLE_ESCAPING and - * ToCSV.UNIX_STYLE_ESCAPING - * @param separator An instance of the String class encapsulating the - * characters or characters that should be used to separate items - * on a line within the CSV file. - * @throws java.io.FileNotFoundException Thrown if any file cannot be located - * on the filesystem during processing. - * @throws java.io.IOException Thrown if the filesystem encounters any - * problems during processing. - * @throws java.lang.IllegalArgumentException Thrown if the values passed - * to the strSource parameter refers to a file or folder that does not - * exist, if the value passed to the strDestination paramater refers - * to a folder that does not exist, if the value passed to the - * strDestination parameter does not refer to a folder or if the - * value passed to the formattingConvention parameter is other than - * one of the values defined by the constants ToCSV.EXCEL_STYLE_ESCAPING - * and ToCSV.UNIX_STYLE_ESCAPING. - * @throws org.apache.poi.openxml4j.exceptions.InvalidFormatException Thrown - * if the xml markup encounetered whilst parsing a SpreadsheetML - * file (.xlsx) is invalid. - */ - public void convertExcelToCSV(String strSource, String strDestination, - String separator, int formattingConvention) - throws FileNotFoundException, IOException, - IllegalArgumentException, InvalidFormatException { - File source = new File(strSource); - File destination = new File(strDestination); - File[] filesList = null; - String destinationFilename = null; - - // Check that the source file/folder exists. - if(!source.exists()) { - throw new IllegalArgumentException("The source for the Excel " + - "file(s) cannot be found."); - } - - // Ensure thaat the folder the user has chosen to save the CSV files - // away into firstly exists and secondly is a folder rather than, for - // instance, a data file. - if(!destination.exists()) { - throw new IllegalArgumentException("The folder/directory for the " + - "converted CSV file(s) does not exist."); - } - if(!destination.isDirectory()) { - throw new IllegalArgumentException("The destination for the CSV " + - "file(s) is not a directory/folder."); - } - - // Ensure the value passed to the formattingConvention parameter is - // within range. - if(formattingConvention != ToCSV.EXCEL_STYLE_ESCAPING && - formattingConvention != ToCSV.UNIX_STYLE_ESCAPING) { - throw new IllegalArgumentException("The value passed to the " + - "formattingConvention parameter is out of range."); - } - - // Copy the spearator character and formatting convention into local - // variables for use in other methods. - this.separator = separator; - this.formattingConvention = formattingConvention; - - // Check to see if the sourceFolder variable holds a reference to - // a file or a folder full of files. - if(source.isDirectory()) { - // Get a list of all of the Excel spreadsheet files (workbooks) in - // the source folder/directory - filesList = source.listFiles(new ExcelFilenameFilter()); - } - else { - // Assume that it must be a file handle - although there are other - // options the code should perhaps check - and store the reference - // into the filesList variable. - filesList = new File[]{source}; - } - - // Step through each of the files in the source folder and for each - // open the workbook, convert it's contents to CSV format and then - // save the resulting file away into the folder specified by the - // contents of the destination variable. Note that the name of the - // csv file will be created by taking the name of the Excel file, - // removing the extension and replacing it with .csv. Note that there - // is one drawback with this approach; if the folder holding the files - // contains two workbooks whose names match but one is a binary file - // (.xls) and the other a SpreadsheetML file (.xlsx), then the names - // for both CSV files will be identical and one CSV file will, - // therefore, over-write the other. - if (filesList != null) { - for(File excelFile : filesList) { - // Open the workbook - this.openWorkbook(excelFile); - - // Convert it's contents into a CSV file - this.convertToCSV(); - - // Build the name of the csv folder from that of the Excel workbook. - // Simply replace the .xls or .xlsx file extension with .csv - destinationFilename = excelFile.getName(); - destinationFilename = destinationFilename.substring( - 0, destinationFilename.lastIndexOf(".")) + - ToCSV.CSV_FILE_EXTENSION; - - // Save the CSV file away using the newly constricted file name - // and to the specified directory. - this.saveCSVFile(new File(destination, destinationFilename)); - } - } - } - - /** - * Open an Excel workbook ready for conversion. - * - * @param file An instance of the File class that encapsulates a handle - * to a valid Excel workbook. Note that the workbook can be in - * either binary (.xls) or SpreadsheetML (.xlsx) format. - * @throws java.io.FileNotFoundException Thrown if the file cannot be located. - * @throws java.io.IOException Thrown if a problem occurs in the file system. - * @throws org.apache.poi.openxml4j.exceptions.InvalidFormatException Thrown - * if invalid xml is found whilst parsing an input SpreadsheetML - * file. - */ - private void openWorkbook(File file) throws FileNotFoundException, - IOException, InvalidFormatException { - FileInputStream fis = null; - try { - System.out.println("Opening workbook [" + file.getName() + "]"); - - fis = new FileInputStream(file); - - // Open the workbook and then create the FormulaEvaluator and - // DataFormatter instances that will be needed to, respectively, - // force evaluation of forumlae found in cells and create a - // formatted String encapsulating the cells contents. - this.workbook = WorkbookFactory.create(fis); - this.evaluator = this.workbook.getCreationHelper().createFormulaEvaluator(); - this.formatter = new DataFormatter(true); - } - finally { - if(fis != null) { - fis.close(); - } - } - } - - /** - * Called to convert the contents of the currently opened workbook into - * a CSV file. - */ - private void convertToCSV() { - Sheet sheet = null; - Row row = null; - int lastRowNum = 0; - this.csvData = new ArrayList>(); - - System.out.println("Converting files contents to CSV format."); - - // Discover how many sheets there are in the workbook.... - int numSheets = this.workbook.getNumberOfSheets(); - - // and then iterate through them. - for(int i = 0; i < numSheets; i++) { - - // Get a reference to a sheet and check to see if it contains - // any rows. - sheet = this.workbook.getSheetAt(i); - if(sheet.getPhysicalNumberOfRows() > 0) { - - // Note down the index number of the bottom-most row and - // then iterate through all of the rows on the sheet starting - // from the very first row - number 1 - even if it is missing. - // Recover a reference to the row and then call another method - // which will strip the data from the cells and build lines - // for inclusion in the resylting CSV file. - lastRowNum = sheet.getLastRowNum(); - for(int j = 0; j <= lastRowNum; j++) { - row = sheet.getRow(j); - this.rowToCSV(row); - } - } - } - } - - /** - * Called to actually save the data recovered from the Excel workbook - * as a CSV file. - * - * @param file An instance of the File class that encapsulates a handle - * referring to the CSV file. - * @throws java.io.FileNotFoundException Thrown if the file cannot be found. - * @throws java.io.IOException Thrown to indicate and error occurred in the - * underylying file system. - */ - private void saveCSVFile(File file) - throws FileNotFoundException, IOException { - FileWriter fw = null; - BufferedWriter bw = null; - ArrayList line = null; - StringBuffer buffer = null; - String csvLineElement = null; - try { - - System.out.println("Saving the CSV file [" + file.getName() + "]"); - - // Open a writer onto the CSV file. - fw = new FileWriter(file); - bw = new BufferedWriter(fw); - - // Step through the elements of the ArrayList that was used to hold - // all of the data recovered from the Excel workbooks' sheets, rows - // and cells. - for(int i = 0; i < this.csvData.size(); i++) { - buffer = new StringBuffer(); - - // Get an element from the ArrayList that contains the data for - // the workbook. This element will itself be an ArrayList - // containing Strings and each String will hold the data recovered - // from a single cell. The for() loop is used to recover elements - // from this 'row' ArrayList one at a time and to write the Strings - // away to a StringBuffer thus assembling a single line for inclusion - // in the CSV file. If a row was empty or if it was short, then - // the ArrayList that contains it's data will also be shorter than - // some of the others. Therefore, it is necessary to check within - // the for loop to ensure that the ArrayList contains data to be - // processed. If it does, then an element will be recovered and - // appended to the StringBuffer. - line = this.csvData.get(i); - for(int j = 0; j < this.maxRowWidth; j++) { - if(line.size() > j) { - csvLineElement = line.get(j); - if(csvLineElement != null) { - buffer.append(this.escapeEmbeddedCharacters( - csvLineElement)); - } - } - if(j < (this.maxRowWidth - 1)) { - buffer.append(this.separator); - } - } - - // Once the line is built, write it away to the CSV file. - bw.write(buffer.toString().trim()); - - // Condition the inclusion of new line characters so as to - // avoid an additional, superfluous, new line at the end of - // the file. - if(i < (this.csvData.size() - 1)) { - bw.newLine(); - } - } - } - finally { - if(bw != null) { - bw.flush(); - bw.close(); - } - } - } - - /** - * Called to convert a row of cells into a line of data that can later be - * output to the CSV file. - * - * @param row An instance of either the HSSFRow or XSSFRow classes that - * encapsulates information about a row of cells recovered from - * an Excel workbook. - */ - private void rowToCSV(Row row) { - Cell cell = null; - int lastCellNum = 0; - ArrayList csvLine = new ArrayList(); - - // Check to ensure that a row was recovered from the sheet as it is - // possible that one or more rows between other populated rows could be - // missing - blank. If the row does contain cells then... - if(row != null) { - - // Get the index for the right most cell on the row and then - // step along the row from left to right recovering the contents - // of each cell, converting that into a formatted String and - // then storing the String into the csvLine ArrayList. - lastCellNum = row.getLastCellNum(); - for(int i = 0; i <= lastCellNum; i++) { - cell = row.getCell(i); - if(cell == null) { - csvLine.add(""); - } - else { - if(cell.getCellTypeEnum() != CellType.FORMULA) { - csvLine.add(this.formatter.formatCellValue(cell)); - } - else { - csvLine.add(this.formatter.formatCellValue(cell, this.evaluator)); - } - } - } - // Make a note of the index number of the right most cell. This value - // will later be used to ensure that the matrix of data in the CSV file - // is square. - if(lastCellNum > this.maxRowWidth) { - this.maxRowWidth = lastCellNum; - } - } - this.csvData.add(csvLine); - } - - /** - * Checks to see whether the field - which consists of the formatted - * contents of an Excel worksheet cell encapsulated within a String - contains - * any embedded characters that must be escaped. The method is able to - * comply with either Excel's or UNIX formatting conventions in the - * following manner; - * - * With regard to UNIX conventions, if the field contains any embedded - * field separator or EOL characters they will each be escaped by prefixing - * a leading backspace character. These are the only changes that have yet - * emerged following some research as being required. - * - * Excel has other embedded character escaping requirements, some that emerged - * from empirical testing, other through research. Firstly, with regards to - * any embedded speech marks ("), each occurrence should be escaped with - * another speech mark and the whole field then surrounded with speech marks. - * Thus if a field holds "Hello" he said then it should be modified - * to appear as """Hello"" he said". Furthermore, if the field - * contains either embedded separator or EOL characters, it should also - * be surrounded with speech marks. As a result 1,400 would become - * "1,400" assuming that the comma is the required field separator. - * This has one consequence in, if a field contains embedded speech marks - * and embedded separator characters, checks for both are not required as the - * additional set of speech marks that should be placed around ay field - * containing embedded speech marks will also account for the embedded - * separator. - * - * It is worth making one further note with regard to embedded EOL - * characters. If the data in a worksheet is exported as a CSV file using - * Excel itself, then the field will be surounded with speech marks. If the - * resulting CSV file is then re-imports into another worksheet, the EOL - * character will result in the original simgle field occupying more than - * one cell. This same 'feature' is replicated in this classes behaviour. - * - * @param field An instance of the String class encapsulating the formatted - * contents of a cell on an Excel worksheet. - * @return A String that encapsulates the formatted contents of that - * Excel worksheet cell but with any embedded separator, EOL or - * speech mark characters correctly escaped. - */ - private String escapeEmbeddedCharacters(String field) { - StringBuffer buffer = null; - - // If the fields contents should be formatted to confrom with Excel's - // convention.... - if(this.formattingConvention == ToCSV.EXCEL_STYLE_ESCAPING) { - - // Firstly, check if there are any speech marks (") in the field; - // each occurrence must be escaped with another set of spech marks - // and then the entire field should be enclosed within another - // set of speech marks. Thus, "Yes" he said would become - // """Yes"" he said" - if(field.contains("\"")) { - buffer = new StringBuffer(field.replaceAll("\"", "\\\"\\\"")); - buffer.insert(0, "\""); - buffer.append("\""); - } - else { - // If the field contains either embedded separator or EOL - // characters, then escape the whole field by surrounding it - // with speech marks. - buffer = new StringBuffer(field); - if((buffer.indexOf(this.separator)) > -1 || - (buffer.indexOf("\n")) > -1) { - buffer.insert(0, "\""); - buffer.append("\""); - } - } - return(buffer.toString().trim()); - } - // The only other formatting convention this class obeys is the UNIX one - // where any occurrence of the field separator or EOL character will - // be escaped by preceding it with a backslash. - else { - if(field.contains(this.separator)) { - field = field.replaceAll(this.separator, ("\\\\" + this.separator)); - } - if(field.contains("\n")) { - field = field.replaceAll("\n", "\\\\\n"); - } - return(field); - } - } - - /** - * The main() method contains code that demonstrates how to use the class. - * - * @param args An array containing zero, one or more elements all of type - * String. Each element will encapsulate an argument specified by the - * user when running the program from the command prompt. - */ - public static void main(String[] args) { - // Check the number of arguments passed to the main method. There - // must be two, three or four; the name of and path to either the folder - // containing the Excel files or an individual Excel workbook that is/are - // to be converted, the name of and path to the folder to which the CSV - // files should be written, - optionally - the separator character - // that should be used to separate individual items (fields) on the - // lines (records) of the CSV file and - again optionally - an integer - // that idicates whether the CSV file ought to obey Excel's or UNIX - // convnetions with regard to formatting fields that contain embedded - // separator, Speech mark or EOL character(s). - // - // Note that the names of the CSV files will be derived from those - // of the Excel file(s). Put simply the .xls or .xlsx extension will be - // replaced with .csv. Therefore, if the source folder contains files - // with matching names but different extensions - Test.xls and Test.xlsx - // for example - then the CSV file generated from one will overwrite - // that generated from the other. - ToCSV converter = null; - boolean converted = true; - long startTime = System.currentTimeMillis(); - try { - converter = new ToCSV(); - if(args.length == 2) { - // Just the Source File/Folder and Destination Folder were - // passed to the main method. - converter.convertExcelToCSV(args[0], args[1]); - } - else if(args.length == 3){ - // The Source File/Folder, Destination Folder and Separator - // were passed to the main method. - converter.convertExcelToCSV(args[0], args[1], args[2]); - } - else if(args.length == 4) { - // The Source File/Folder, Destination Folder, Separator and - // Formatting Convnetion were passed to the main method. - converter.convertExcelToCSV(args[0], args[1], - args[2], Integer.parseInt(args[3])); - } - else { - // None or more than four parameters were passed so display - //a Usage message. - System.out.println("Usage: java ToCSV [Source File/Folder] " + - "[Destination Folder] [Separator] [Formatting Convention]\n" + - "\tSource File/Folder\tThis argument should contain the name of and\n" + - "\t\t\t\tpath to either a single Excel workbook or a\n" + - "\t\t\t\tfolder containing one or more Excel workbooks.\n" + - "\tDestination Folder\tThe name of and path to the folder that the\n" + - "\t\t\t\tCSV files should be written out into. The\n" + - "\t\t\t\tfolder must exist before running the ToCSV\n" + - "\t\t\t\tcode as it will not check for or create it.\n" + - "\tSeparator\t\tOptional. The character or characters that\n" + - "\t\t\t\tshould be used to separate fields in the CSV\n" + - "\t\t\t\trecord. If no value is passed then the comma\n" + - "\t\t\t\twill be assumed.\n" + - "\tFormatting Convention\tOptional. This argument can take one of two\n" + - "\t\t\t\tvalues. Passing 0 (zero) will result in a CSV\n" + - "\t\t\t\tfile that obeys Excel's formatting conventions\n" + - "\t\t\t\twhilst passing 1 (one) will result in a file\n" + - "\t\t\t\tthat obeys UNIX formatting conventions. If no\n" + - "\t\t\t\tvalue is passed, then the CSV file produced\n" + - "\t\t\t\twill obey Excel's formatting conventions."); - converted = false; - } - } - // It is not wise to have such a wide catch clause - Exception is very - // close to being at the top of the inheritance hierarchy - though it - // will suffice for this example as it is really not possible to recover - // easilly from an exceptional set of circumstances at this point in the - // program. It should however, ideally be replaced with one or more - // catch clauses optimised to handle more specific problems. - catch(Exception ex) { - System.out.println("Caught an: " + ex.getClass().getName()); - System.out.println("Message: " + ex.getMessage()); - System.out.println("Stacktrace follows:....."); - ex.printStackTrace(System.out); - converted = false; - } - - if (converted) { - System.out.println("Conversion took " + - (int)((System.currentTimeMillis() - startTime)/1000) + " seconds"); - } - } - - /** - * An instance of this class can be used to control the files returned - * be a call to the listFiles() method when made on an instance of the - * File class and that object refers to a folder/directory - */ - class ExcelFilenameFilter implements FilenameFilter { - - /** - * Determine those files that will be returned by a call to the - * listFiles() method. In this case, the name of the file must end with - * either of the following two extension; '.xls' or '.xlsx'. For the - * future, it is very possible to parameterise this and allow the - * containing class to pass, for example, an array of Strings to this - * class on instantiation. Each element in that array could encapsulate - * a valid file extension - '.xls', '.xlsx', '.xlt', '.xlst', etc. These - * could then be used to control which files were returned by the call - * to the listFiles() method. - * - * @param file An instance of the File class that encapsulates a handle - * referring to the folder/directory that contains the file. - * @param name An instance of the String class that encapsulates the - * name of the file. - * @return A boolean value that indicates whether the file should be - * included in the array retirned by the call to the listFiles() - * method. In this case true will be returned if the name of the - * file ends with either '.xls' or '.xlsx' and false will be - * returned in all other instances. - */ - @Override - public boolean accept(File file, String name) { - return(name.endsWith(".xls") || name.endsWith(".xlsx")); - } - } -} diff --git a/src/examples/src/org/apache/poi/ss/examples/formula/CalculateMortgage.java b/src/examples/src/org/apache/poi/ss/examples/formula/CalculateMortgage.java deleted file mode 100644 index 3d6b4423a..000000000 --- a/src/examples/src/org/apache/poi/ss/examples/formula/CalculateMortgage.java +++ /dev/null @@ -1,94 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.examples.formula; - -import org.apache.poi.ss.formula.OperationEvaluationContext ; -import org.apache.poi.ss.formula.eval.ErrorEval ; -import org.apache.poi.ss.formula.eval.EvaluationException ; -import org.apache.poi.ss.formula.eval.NumberEval ; -import org.apache.poi.ss.formula.eval.OperandResolver ; -import org.apache.poi.ss.formula.eval.ValueEval ; -import org.apache.poi.ss.formula.functions.FreeRefFunction ; - -/** - * A simple user-defined function to calculate principal and interest. - * - * @author Jon Svede ( jon [at] loquatic [dot] com ) - * @author Brian Bush ( brian [dot] bush [at] nrel [dot] gov ) - * - */ -public class CalculateMortgage implements FreeRefFunction { - - @Override - public ValueEval evaluate( ValueEval[] args, OperationEvaluationContext ec ) { - - // verify that we have enough data - if (args.length != 3) { - return ErrorEval.VALUE_INVALID; - } - - // declare doubles for values - double principal, rate, years, result; - try { - // extract values as ValueEval - ValueEval v1 = OperandResolver.getSingleValue( args[0], - ec.getRowIndex(), - ec.getColumnIndex() ) ; - ValueEval v2 = OperandResolver.getSingleValue( args[1], - ec.getRowIndex(), - ec.getColumnIndex() ) ; - ValueEval v3 = OperandResolver.getSingleValue( args[2], - ec.getRowIndex(), - ec.getColumnIndex() ) ; - - // get data as doubles - principal = OperandResolver.coerceValueToDouble( v1 ) ; - rate = OperandResolver.coerceValueToDouble( v2 ) ; - years = OperandResolver.coerceValueToDouble( v3 ) ; - - result = calculateMortgagePayment( principal, rate, years ) ; - System.out.println( "Result = " + result ) ; - - checkValue(result); - - } catch (EvaluationException e) { - return e.getErrorEval(); - } - - return new NumberEval( result ) ; - } - - public double calculateMortgagePayment( double p, double r, double y ) { - double i = r / 12 ; - double n = y * 12 ; - - double principalAndInterest = - p * (( i * Math.pow((1 + i),n ) ) / ( Math.pow((1 + i),n) - 1)) ; - - return principalAndInterest ; - } - /** - * Excel does not support infinities and NaNs, rather, it gives a #NUM! error in these cases - * - * @throws EvaluationException (#NUM!) if result is NaN or Infinity - */ - private void checkValue(double result) throws EvaluationException { - if (Double.isNaN(result) || Double.isInfinite(result)) { - throw new EvaluationException(ErrorEval.NUM_ERROR); - } - } -} diff --git a/src/examples/src/org/apache/poi/ss/examples/formula/CheckFunctionsSupported.java b/src/examples/src/org/apache/poi/ss/examples/formula/CheckFunctionsSupported.java deleted file mode 100644 index cf6c176cc..000000000 --- a/src/examples/src/org/apache/poi/ss/examples/formula/CheckFunctionsSupported.java +++ /dev/null @@ -1,161 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.examples.formula; - -import java.io.File; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeSet; - -import org.apache.poi.ss.formula.eval.NotImplementedException; -import org.apache.poi.ss.formula.eval.NotImplementedFunctionException; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.usermodel.WorkbookFactory; -import org.apache.poi.ss.util.CellReference; - -/** - * Attempts to re-evaluate all the formulas in the workbook, and - * reports what (if any) formula functions used are not (currently) - * supported by Apache POI. - * - *

    This provides examples of how to evaluate formulas in excel - * files using Apache POI, along with how to handle errors whilst - * doing so. - */ -public class CheckFunctionsSupported { - public static void main(String[] args) throws Exception { - if (args.length < 1) { - System.err.println("Use:"); - System.err.println(" CheckFunctionsSupported "); - return; - } - - Workbook wb = WorkbookFactory.create(new File(args[0])); - CheckFunctionsSupported check = new CheckFunctionsSupported(wb); - - // Fetch all the problems - List problems = new ArrayList(); - for (int sn=0; sn unsupportedFunctions = new TreeSet(); - for (FormulaEvaluationProblems p : problems) { - unsupportedFunctions.addAll(p.unsupportedFunctions); - } - if (unsupportedFunctions.isEmpty()) { - System.out.println("There are no unsupported formula functions used"); - } else { - System.out.println("Unsupported formula functions:"); - for (String function : unsupportedFunctions) { - System.out.println(" " + function); - } - System.out.println("Total unsupported functions = " + unsupportedFunctions.size()); - } - - // Report sheet by sheet - for (int sn=0; sn getUnsupportedFunctions(String sheetName) { - return getUnsupportedFunctions(workbook.getSheet(sheetName)); - } - public Set getUnsupportedFunctions(int sheetIndex) { - return getUnsupportedFunctions(workbook.getSheetAt(sheetIndex)); - } - public Set getUnsupportedFunctions(Sheet sheet) { - FormulaEvaluationProblems problems = getEvaluationProblems(sheet); - return problems.unsupportedFunctions; - } - - public FormulaEvaluationProblems getEvaluationProblems(String sheetName) { - return getEvaluationProblems(workbook.getSheet(sheetName)); - } - public FormulaEvaluationProblems getEvaluationProblems(int sheetIndex) { - return getEvaluationProblems(workbook.getSheetAt(sheetIndex)); - } - public FormulaEvaluationProblems getEvaluationProblems(Sheet sheet) { - Set unsupportedFunctions = new HashSet(); - Map unevaluatableCells = new HashMap(); - - for (Row r : sheet) { - for (Cell c : r) { - try { - evaluator.evaluate(c); - } catch (Exception e) { - if (e instanceof NotImplementedException && e.getCause() != null) { - // Has been wrapped with cell details, but we know those - e = (Exception)e.getCause(); - } - - if (e instanceof NotImplementedFunctionException) { - NotImplementedFunctionException nie = (NotImplementedFunctionException)e; - unsupportedFunctions.add(nie.getFunctionName()); - } - unevaluatableCells.put(new CellReference(c), e); - } - } - } - - return new FormulaEvaluationProblems(unsupportedFunctions, unevaluatableCells); - } - - public static class FormulaEvaluationProblems { - /** Which used functions are unsupported by POI at this time */ - public Set unsupportedFunctions; - /** Which cells had unevaluatable formulas, and why? */ - public Map unevaluatableCells; - - protected FormulaEvaluationProblems(Set unsupportedFunctions, - Map unevaluatableCells) { - this.unsupportedFunctions = Collections.unmodifiableSet(unsupportedFunctions); - this.unevaluatableCells = Collections.unmodifiableMap(unevaluatableCells); - } - } -} diff --git a/src/examples/src/org/apache/poi/ss/examples/formula/SettingExternalFunction.java b/src/examples/src/org/apache/poi/ss/examples/formula/SettingExternalFunction.java deleted file mode 100644 index 51f7c0367..000000000 --- a/src/examples/src/org/apache/poi/ss/examples/formula/SettingExternalFunction.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.ss.examples.formula; - -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; - -import org.apache.poi.ss.formula.OperationEvaluationContext; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.ss.formula.functions.FreeRefFunction; -import org.apache.poi.ss.formula.udf.UDFFinder; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -/** - * Demonstrates how to use functions provided by third-party add-ins, e.g. Bloomberg Excel Add-in. - * - * There can be situations when you are not interested in formula evaluation, - * you just need to set the formula and the workbook will be evaluation by the client. - */ -public class SettingExternalFunction { - - /** - * wrap external functions in a plugin - */ - public static class BloombergAddIn implements UDFFinder { - private final Map _functionsByName; - - public BloombergAddIn() { - // dummy function that returns NA - // don't care about the implementation, we are not interested in evaluation - // and this method will never be called - FreeRefFunction NA = new FreeRefFunction() { - @Override - public ValueEval evaluate(ValueEval[] args, OperationEvaluationContext ec) { - return ErrorEval.NA; - } - }; - _functionsByName = new HashMap(); - _functionsByName.put("BDP", NA); - _functionsByName.put("BDH", NA); - _functionsByName.put("BDS", NA); - } - - @Override - public FreeRefFunction findFunction(String name) { - return _functionsByName.get(name.toUpperCase(Locale.ROOT)); - } - - } - - public static void main( String[] args ) throws IOException { - - Workbook wb = new XSSFWorkbook(); // or new HSSFWorkbook() - - // register the add-in - wb.addToolPack(new BloombergAddIn()); - - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - row.createCell(0).setCellFormula("BDP(\"GOOG Equity\",\"CHG_PCT_YTD\")/100"); - row.createCell(1).setCellFormula("BDH(\"goog us equity\",\"EBIT\",\"1/1/2005\",\"12/31/2009\",\"per=cy\",\"curr=USD\") "); - row.createCell(2).setCellFormula("BDS(\"goog us equity\",\"top_20_holders_public_filings\") "); - - FileOutputStream out = new FileOutputStream("bloomberg-demo.xlsx"); - wb.write(out); - out.close(); - - wb.close(); - } - -} diff --git a/src/examples/src/org/apache/poi/ss/examples/formula/UserDefinedFunctionExample.java b/src/examples/src/org/apache/poi/ss/examples/formula/UserDefinedFunctionExample.java deleted file mode 100644 index 394026cdc..000000000 --- a/src/examples/src/org/apache/poi/ss/examples/formula/UserDefinedFunctionExample.java +++ /dev/null @@ -1,81 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.examples.formula; - -import java.io.File ; -import java.io.FileInputStream ; - -import org.apache.poi.ss.formula.functions.FreeRefFunction ; -import org.apache.poi.ss.formula.udf.DefaultUDFFinder ; -import org.apache.poi.ss.formula.udf.UDFFinder ; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellValue; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.usermodel.WorkbookFactory; -import org.apache.poi.ss.util.CellReference ; - - -/** - * An example class of how to invoke a User Defined Function for a given - * XLS instance using POI's UDFFinder implementation. - */ -public class UserDefinedFunctionExample { - - public static void main( String[] args ) throws Exception { - - if( args.length != 2 ) { - System.out.println( "usage: UserDefinedFunctionExample fileName cellId" ) ; - return; - } - - System.out.println( "fileName: " + args[0] ) ; - System.out.println( "cell: " + args[1] ) ; - - File workbookFile = new File( args[0] ) ; - - FileInputStream fis = new FileInputStream(workbookFile); - Workbook workbook = WorkbookFactory.create(fis); - fis.close(); - - String[] functionNames = { "calculatePayment" } ; - FreeRefFunction[] functionImpls = { new CalculateMortgage() } ; - - UDFFinder udfToolpack = new DefaultUDFFinder( functionNames, functionImpls ) ; - - // register the user-defined function in the workbook - workbook.addToolPack(udfToolpack); - - FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator(); - - CellReference cr = new CellReference( args[1] ) ; - String sheetName = cr.getSheetName() ; - Sheet sheet = workbook.getSheet( sheetName ) ; - int rowIdx = cr.getRow() ; - int colIdx = cr.getCol() ; - Row row = sheet.getRow( rowIdx ) ; - Cell cell = row.getCell( colIdx ) ; - - CellValue value = evaluator.evaluate( cell ) ; - - System.out.println("returns value: " + value ) ; - - workbook.close(); - } -} diff --git a/src/examples/src/org/apache/poi/ss/examples/formula/mortgage-calculation.xls b/src/examples/src/org/apache/poi/ss/examples/formula/mortgage-calculation.xls deleted file mode 100644 index 4e71ba8e6..000000000 Binary files a/src/examples/src/org/apache/poi/ss/examples/formula/mortgage-calculation.xls and /dev/null differ diff --git a/src/examples/src/org/apache/poi/ss/examples/html/HSSFHtmlHelper.java b/src/examples/src/org/apache/poi/ss/examples/html/HSSFHtmlHelper.java deleted file mode 100644 index 9955eb30f..000000000 --- a/src/examples/src/org/apache/poi/ss/examples/html/HSSFHtmlHelper.java +++ /dev/null @@ -1,66 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.examples.html; - -import java.util.Formatter; - -import org.apache.poi.hssf.usermodel.HSSFCellStyle; -import org.apache.poi.hssf.usermodel.HSSFPalette; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.hssf.util.HSSFColor; -import org.apache.poi.hssf.util.HSSFColor.HSSFColorPredefined; -import org.apache.poi.ss.usermodel.CellStyle; - -/** - * Implementation of {@link HtmlHelper} for HSSF files. - */ -public class HSSFHtmlHelper implements HtmlHelper { - private final HSSFWorkbook wb; - private final HSSFPalette colors; - - private static final HSSFColor HSSF_AUTO = HSSFColorPredefined.AUTOMATIC.getColor(); - - public HSSFHtmlHelper(HSSFWorkbook wb) { - this.wb = wb; - // If there is no custom palette, then this creates a new one that is - // a copy of the default - colors = wb.getCustomPalette(); - } - - @Override - public void colorStyles(CellStyle style, Formatter out) { - HSSFCellStyle cs = (HSSFCellStyle) style; - out.format(" /* fill pattern = %d */%n", cs.getFillPatternEnum().getCode()); - styleColor(out, "background-color", cs.getFillForegroundColor()); - styleColor(out, "color", cs.getFont(wb).getColor()); - styleColor(out, "border-left-color", cs.getLeftBorderColor()); - styleColor(out, "border-right-color", cs.getRightBorderColor()); - styleColor(out, "border-top-color", cs.getTopBorderColor()); - styleColor(out, "border-bottom-color", cs.getBottomBorderColor()); - } - - private void styleColor(Formatter out, String attr, short index) { - HSSFColor color = colors.getColor(index); - if (index == HSSF_AUTO.getIndex() || color == null) { - out.format(" /* %s: index = %d */%n", attr, index); - } else { - short[] rgb = color.getTriplet(); - out.format(" %s: #%02x%02x%02x; /* index = %d */%n", attr, rgb[0], - rgb[1], rgb[2], index); - } - } -} \ No newline at end of file diff --git a/src/examples/src/org/apache/poi/ss/examples/html/HtmlHelper.java b/src/examples/src/org/apache/poi/ss/examples/html/HtmlHelper.java deleted file mode 100644 index 2cb1a9173..000000000 --- a/src/examples/src/org/apache/poi/ss/examples/html/HtmlHelper.java +++ /dev/null @@ -1,40 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.examples.html; - -import org.apache.poi.ss.usermodel.CellStyle; - -import java.util.Formatter; - -/** - * This interface is used where code wants to be independent of the workbook - * formats. If you are writing such code, you can add a method to this - * interface, and then implement it for both HSSF and XSSF workbooks, letting - * the driving code stay independent of format. - * - * @author Ken Arnold, Industrious Media LLC - */ -public interface HtmlHelper { - /** - * Outputs the appropriate CSS style for the given cell style. - * - * @param style The cell style. - * @param out The place to write the output. - */ - void colorStyles(CellStyle style, Formatter out); -} diff --git a/src/examples/src/org/apache/poi/ss/examples/html/ToHtml.java b/src/examples/src/org/apache/poi/ss/examples/html/ToHtml.java deleted file mode 100644 index 2a7fe69f2..000000000 --- a/src/examples/src/org/apache/poi/ss/examples/html/ToHtml.java +++ /dev/null @@ -1,465 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.examples.html; - -import java.io.BufferedReader; -import java.io.Closeable; -import java.io.FileInputStream; -import java.io.FileWriter; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.PrintWriter; -import java.util.Formatter; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.ss.format.CellFormat; -import org.apache.poi.ss.format.CellFormatResult; -import org.apache.poi.ss.usermodel.BorderStyle; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.Font; -import org.apache.poi.ss.usermodel.HorizontalAlignment; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.VerticalAlignment; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.usermodel.WorkbookFactory; -import org.apache.poi.util.IOUtils; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -/** - * This example shows how to display a spreadsheet in HTML using the classes for - * spreadsheet display. - */ -public class ToHtml { - private final Workbook wb; - private final Appendable output; - private boolean completeHTML; - private Formatter out; - private boolean gotBounds; - private int firstColumn; - private int endColumn; - private HtmlHelper helper; - - private static final String DEFAULTS_CLASS = "excelDefaults"; - private static final String COL_HEAD_CLASS = "colHeader"; - private static final String ROW_HEAD_CLASS = "rowHeader"; - - private static final Map HALIGN = mapFor( - HorizontalAlignment.LEFT, "left", - HorizontalAlignment.CENTER, "center", - HorizontalAlignment.RIGHT, "right", - HorizontalAlignment.FILL, "left", - HorizontalAlignment.JUSTIFY, "left", - HorizontalAlignment.CENTER_SELECTION, "center"); - - private static final Map VALIGN = mapFor( - VerticalAlignment.BOTTOM, "bottom", - VerticalAlignment.CENTER, "middle", - VerticalAlignment.TOP, "top"); - - private static final Map BORDER = mapFor( - BorderStyle.DASH_DOT, "dashed 1pt", - BorderStyle.DASH_DOT_DOT, "dashed 1pt", - BorderStyle.DASHED, "dashed 1pt", - BorderStyle.DOTTED, "dotted 1pt", - BorderStyle.DOUBLE, "double 3pt", - BorderStyle.HAIR, "solid 1px", - BorderStyle.MEDIUM, "solid 2pt", - BorderStyle.MEDIUM_DASH_DOT, "dashed 2pt", - BorderStyle.MEDIUM_DASH_DOT_DOT, "dashed 2pt", - BorderStyle.MEDIUM_DASHED, "dashed 2pt", - BorderStyle.NONE, "none", - BorderStyle.SLANTED_DASH_DOT, "dashed 2pt", - BorderStyle.THICK, "solid 3pt", - BorderStyle.THIN, "dashed 1pt"); - - @SuppressWarnings({"unchecked"}) - private static Map mapFor(Object... mapping) { - Map map = new HashMap(); - for (int i = 0; i < mapping.length; i += 2) { - map.put((K) mapping[i], (V) mapping[i + 1]); - } - return map; - } - - /** - * Creates a new converter to HTML for the given workbook. - * - * @param wb The workbook. - * @param output Where the HTML output will be written. - * - * @return An object for converting the workbook to HTML. - */ - public static ToHtml create(Workbook wb, Appendable output) { - return new ToHtml(wb, output); - } - - /** - * Creates a new converter to HTML for the given workbook. If the path ends - * with ".xlsx" an {@link XSSFWorkbook} will be used; otherwise - * this will use an {@link HSSFWorkbook}. - * - * @param path The file that has the workbook. - * @param output Where the HTML output will be written. - * - * @return An object for converting the workbook to HTML. - */ - public static ToHtml create(String path, Appendable output) - throws IOException { - return create(new FileInputStream(path), output); - } - - /** - * Creates a new converter to HTML for the given workbook. This attempts to - * detect whether the input is XML (so it should create an {@link - * XSSFWorkbook} or not (so it should create an {@link HSSFWorkbook}). - * - * @param in The input stream that has the workbook. - * @param output Where the HTML output will be written. - * - * @return An object for converting the workbook to HTML. - */ - public static ToHtml create(InputStream in, Appendable output) - throws IOException { - try { - Workbook wb = WorkbookFactory.create(in); - return create(wb, output); - } catch (InvalidFormatException e){ - throw new IllegalArgumentException("Cannot create workbook from stream", e); - } - } - - private ToHtml(Workbook wb, Appendable output) { - if (wb == null) { - throw new NullPointerException("wb"); - } - if (output == null) { - throw new NullPointerException("output"); - } - this.wb = wb; - this.output = output; - setupColorMap(); - } - - private void setupColorMap() { - if (wb instanceof HSSFWorkbook) { - helper = new HSSFHtmlHelper((HSSFWorkbook) wb); - } else if (wb instanceof XSSFWorkbook) { - helper = new XSSFHtmlHelper(); - } else { - throw new IllegalArgumentException( - "unknown workbook type: " + wb.getClass().getSimpleName()); - } - } - - /** - * Run this class as a program - * - * @param args The command line arguments. - * - * @throws Exception Exception we don't recover from. - */ - public static void main(String[] args) throws Exception { - if(args.length < 2){ - System.err.println("usage: ToHtml inputWorkbook outputHtmlFile"); - return; - } - - ToHtml toHtml = create(args[0], new PrintWriter(new FileWriter(args[1]))); - toHtml.setCompleteHTML(true); - toHtml.printPage(); - } - - public void setCompleteHTML(boolean completeHTML) { - this.completeHTML = completeHTML; - } - - public void printPage() throws IOException { - try { - ensureOut(); - if (completeHTML) { - out.format( - "%n"); - out.format("%n"); - out.format("%n"); - out.format("%n"); - out.format("%n"); - } - - print(); - - if (completeHTML) { - out.format("%n"); - out.format("%n"); - } - } finally { - IOUtils.closeQuietly(out); - if (output instanceof Closeable) { - IOUtils.closeQuietly((Closeable) output); - } - } - } - - public void print() { - printInlineStyle(); - printSheets(); - } - - private void printInlineStyle() { - //out.format("%n"); - out.format("%n"); - } - - private void ensureOut() { - if (out == null) { - out = new Formatter(output); - } - } - - public void printStyles() { - ensureOut(); - - // First, copy the base css - BufferedReader in = null; - try { - in = new BufferedReader(new InputStreamReader( - getClass().getResourceAsStream("excelStyle.css"))); - String line; - while ((line = in.readLine()) != null) { - out.format("%s%n", line); - } - } catch (IOException e) { - throw new IllegalStateException("Reading standard css", e); - } finally { - IOUtils.closeQuietly(in); - } - - // now add css for each used style - Set seen = new HashSet(); - for (int i = 0; i < wb.getNumberOfSheets(); i++) { - Sheet sheet = wb.getSheetAt(i); - Iterator rows = sheet.rowIterator(); - while (rows.hasNext()) { - Row row = rows.next(); - for (Cell cell : row) { - CellStyle style = cell.getCellStyle(); - if (!seen.contains(style)) { - printStyle(style); - seen.add(style); - } - } - } - } - } - - private void printStyle(CellStyle style) { - out.format(".%s .%s {%n", DEFAULTS_CLASS, styleName(style)); - styleContents(style); - out.format("}%n"); - } - - private void styleContents(CellStyle style) { - styleOut("text-align", style.getAlignmentEnum(), HALIGN); - styleOut("vertical-align", style.getVerticalAlignmentEnum(), VALIGN); - fontStyle(style); - borderStyles(style); - helper.colorStyles(style, out); - } - - private void borderStyles(CellStyle style) { - styleOut("border-left", style.getBorderLeftEnum(), BORDER); - styleOut("border-right", style.getBorderRightEnum(), BORDER); - styleOut("border-top", style.getBorderTopEnum(), BORDER); - styleOut("border-bottom", style.getBorderBottomEnum(), BORDER); - } - - private void fontStyle(CellStyle style) { - Font font = wb.getFontAt(style.getFontIndex()); - - if (font.getBold()) { - out.format(" font-weight: bold;%n"); - } - if (font.getItalic()) { - out.format(" font-style: italic;%n"); - } - - int fontheight = font.getFontHeightInPoints(); - if (fontheight == 9) { - //fix for stupid ol Windows - fontheight = 10; - } - out.format(" font-size: %dpt;%n", fontheight); - - // Font color is handled with the other colors - } - - private String styleName(CellStyle style) { - if (style == null) { - style = wb.getCellStyleAt((short) 0); - } - StringBuilder sb = new StringBuilder(); - Formatter fmt = new Formatter(sb); - try { - fmt.format("style_%02x", style.getIndex()); - return fmt.toString(); - } finally { - fmt.close(); - } - } - - private void styleOut(String attr, K key, Map mapping) { - String value = mapping.get(key); - if (value != null) { - out.format(" %s: %s;%n", attr, value); - } - } - - private static CellType ultimateCellType(Cell c) { - CellType type = c.getCellTypeEnum(); - if (type == CellType.FORMULA) { - type = c.getCachedFormulaResultTypeEnum(); - } - return type; - } - - private void printSheets() { - ensureOut(); - Sheet sheet = wb.getSheetAt(0); - printSheet(sheet); - } - - public void printSheet(Sheet sheet) { - ensureOut(); - out.format("%n", DEFAULTS_CLASS); - printCols(sheet); - printSheetContent(sheet); - out.format("
    %n"); - } - - private void printCols(Sheet sheet) { - out.format("%n"); - ensureColumnBounds(sheet); - for (int i = firstColumn; i < endColumn; i++) { - out.format("%n"); - } - } - - private void ensureColumnBounds(Sheet sheet) { - if (gotBounds) { - return; - } - - Iterator iter = sheet.rowIterator(); - firstColumn = (iter.hasNext() ? Integer.MAX_VALUE : 0); - endColumn = 0; - while (iter.hasNext()) { - Row row = iter.next(); - short firstCell = row.getFirstCellNum(); - if (firstCell >= 0) { - firstColumn = Math.min(firstColumn, firstCell); - endColumn = Math.max(endColumn, row.getLastCellNum()); - } - } - gotBounds = true; - } - - private void printColumnHeads() { - out.format("%n"); - out.format(" %n", COL_HEAD_CLASS); - out.format(" ◊%n", COL_HEAD_CLASS); - //noinspection UnusedDeclaration - StringBuilder colName = new StringBuilder(); - for (int i = firstColumn; i < endColumn; i++) { - colName.setLength(0); - int cnum = i; - do { - colName.insert(0, (char) ('A' + cnum % 26)); - cnum /= 26; - } while (cnum > 0); - out.format(" %s%n", COL_HEAD_CLASS, colName); - } - out.format(" %n"); - out.format("%n"); - } - - private void printSheetContent(Sheet sheet) { - printColumnHeads(); - - out.format("%n"); - Iterator rows = sheet.rowIterator(); - while (rows.hasNext()) { - Row row = rows.next(); - - out.format(" %n"); - out.format(" %d%n", ROW_HEAD_CLASS, - row.getRowNum() + 1); - for (int i = firstColumn; i < endColumn; i++) { - String content = " "; - String attrs = ""; - CellStyle style = null; - if (i >= row.getFirstCellNum() && i < row.getLastCellNum()) { - Cell cell = row.getCell(i); - if (cell != null) { - style = cell.getCellStyle(); - attrs = tagStyle(cell, style); - //Set the value that is rendered for the cell - //also applies the format - CellFormat cf = CellFormat.getInstance( - style.getDataFormatString()); - CellFormatResult result = cf.apply(cell); - content = result.text; - if (content.equals("")) { - content = " "; - } - } - } - out.format(" %s%n", styleName(style), - attrs, content); - } - out.format(" %n"); - } - out.format("%n"); - } - - private String tagStyle(Cell cell, CellStyle style) { - if (style.getAlignmentEnum() == HorizontalAlignment.GENERAL) { - switch (ultimateCellType(cell)) { - case STRING: - return "style=\"text-align: left;\""; - case BOOLEAN: - case ERROR: - return "style=\"text-align: center;\""; - case NUMERIC: - default: - // "right" is the default - break; - } - } - return ""; - } -} \ No newline at end of file diff --git a/src/examples/src/org/apache/poi/ss/examples/html/XSSFHtmlHelper.java b/src/examples/src/org/apache/poi/ss/examples/html/XSSFHtmlHelper.java deleted file mode 100644 index 20a30ed2e..000000000 --- a/src/examples/src/org/apache/poi/ss/examples/html/XSSFHtmlHelper.java +++ /dev/null @@ -1,59 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.examples.html; - -import java.util.Formatter; - -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.xssf.usermodel.XSSFCellStyle; -import org.apache.poi.xssf.usermodel.XSSFColor; - -/** - * Implementation of {@link HtmlHelper} for XSSF files. - * - * @author Ken Arnold, Industrious Media LLC - */ -public class XSSFHtmlHelper implements HtmlHelper { - @Override - public void colorStyles(CellStyle style, Formatter out) { - XSSFCellStyle cs = (XSSFCellStyle) style; - styleColor(out, "background-color", cs.getFillForegroundXSSFColor()); - styleColor(out, "text-color", cs.getFont().getXSSFColor()); - } - - private void styleColor(Formatter out, String attr, XSSFColor color) { - if (color == null || color.isAuto()) { - return; - } - - byte[] rgb = color.getRGB(); - if (rgb == null) { - return; - } - - // This is done twice -- rgba is new with CSS 3, and browser that don't - // support it will ignore the rgba specification and stick with the - // solid color, which is declared first - out.format(" %s: #%02x%02x%02x;%n", attr, rgb[0], rgb[1], rgb[2]); - byte[] argb = color.getARGB(); - if (argb == null) { - return; - } - out.format(" %s: rgba(0x%02x, 0x%02x, 0x%02x, 0x%02x);%n", attr, - argb[3], argb[0], argb[1], argb[2]); - } -} \ No newline at end of file diff --git a/src/examples/src/org/apache/poi/ss/examples/html/excelStyle.css b/src/examples/src/org/apache/poi/ss/examples/html/excelStyle.css deleted file mode 100644 index 1083b637a..000000000 --- a/src/examples/src/org/apache/poi/ss/examples/html/excelStyle.css +++ /dev/null @@ -1,72 +0,0 @@ -/* - ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - ==================================================================== - */ -/* - * This is the default style sheet for html generated by ToHtml - * - * @author Ken Arnold, Industrious Media LLC - */ -.excelDefaults { - background-color: white; - color: black; - text-decoration: none; - direction: ltr; - text-transform: none; - text-indent: 0; - letter-spacing: 0; - word-spacing: 0; - white-space: normal; - unicode-bidi: normal; - vertical-align: 0; - background-image: none; - text-shadow: none; - list-style-image: none; - list-style-type: none; - padding: 0; - margin: 0; - border-collapse: collapse; - white-space: pre; - vertical-align: bottom; - font-style: normal; - font-family: sans-serif; - font-variant: normal; - font-weight: normal; - font-size: 10pt; - text-align: right; -} - -.excelDefaults td { - padding: 1px 5px; - border: 1px solid silver; -} - -.excelDefaults .colHeader { - background-color: silver; - font-weight: bold; - border: 1px solid black; - text-align: center; - padding: 1px 5px; -} - -.excelDefaults .rowHeader { - background-color: silver; - font-weight: bold; - border: 1px solid black; - text-align: right; - padding: 1px 5px; -} diff --git a/src/examples/src/org/apache/poi/ss/examples/html/package.html b/src/examples/src/org/apache/poi/ss/examples/html/package.html deleted file mode 100644 index 1c8e6af5c..000000000 --- a/src/examples/src/org/apache/poi/ss/examples/html/package.html +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - -This package contains an example that uses POI to convert a workbook into -an HTML representation of the data. It can use both XSSF and HSSF workbooks. - - diff --git a/src/examples/src/org/apache/poi/xslf/usermodel/AddVideoToPptx.java.txt b/src/examples/src/org/apache/poi/xslf/usermodel/AddVideoToPptx.java.txt deleted file mode 100644 index 2d32c4d81..000000000 --- a/src/examples/src/org/apache/poi/xslf/usermodel/AddVideoToPptx.java.txt +++ /dev/null @@ -1,251 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xslf.usermodel; - -import java.awt.Rectangle; -import java.awt.image.BufferedImage; -import java.io.ByteArrayOutputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.URL; -import java.text.DecimalFormat; - -import javax.imageio.ImageIO; -import javax.xml.namespace.QName; - -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.opc.PackagePartName; -import org.apache.poi.openxml4j.opc.PackageRelationship; -import org.apache.poi.openxml4j.opc.PackagingURIHelper; -import org.apache.poi.openxml4j.opc.TargetMode; -import org.apache.poi.sl.usermodel.PictureData.PictureType; -import org.apache.xmlbeans.XmlCursor; -import org.openxmlformats.schemas.drawingml.x2006.main.CTHyperlink; -import org.openxmlformats.schemas.officeDocument.x2006.relationships.STRelationshipId; -import org.openxmlformats.schemas.presentationml.x2006.main.CTApplicationNonVisualDrawingProps; -import org.openxmlformats.schemas.presentationml.x2006.main.CTExtension; -import org.openxmlformats.schemas.presentationml.x2006.main.CTPicture; -import org.openxmlformats.schemas.presentationml.x2006.main.CTSlide; -import org.openxmlformats.schemas.presentationml.x2006.main.CTTLCommonMediaNodeData; -import org.openxmlformats.schemas.presentationml.x2006.main.CTTLCommonTimeNodeData; -import org.openxmlformats.schemas.presentationml.x2006.main.CTTimeNodeList; -import org.openxmlformats.schemas.presentationml.x2006.main.STTLTimeIndefinite; -import org.openxmlformats.schemas.presentationml.x2006.main.STTLTimeNodeFillType; -import org.openxmlformats.schemas.presentationml.x2006.main.STTLTimeNodeRestartType; -import org.openxmlformats.schemas.presentationml.x2006.main.STTLTimeNodeType; - -import com.xuggle.mediatool.IMediaReader; -import com.xuggle.mediatool.MediaListenerAdapter; -import com.xuggle.mediatool.ToolFactory; -import com.xuggle.mediatool.event.IVideoPictureEvent; -import com.xuggle.xuggler.Global; -import com.xuggle.xuggler.IContainer; -import com.xuggle.xuggler.io.InputOutputStreamHandler; - -/** - * Adding multiple videos to a slide - * - * need the Xuggler 5.4 jars: - * <repositories> - * <repository> - * <id>xuggle repo</id> - * <url>http://xuggle.googlecode.com/svn/trunk/repo/share/java/</url> - * </repository> - * </repositories> - * ... - * <dependency> - * <groupId>xuggle</groupId> - * <artifactId>xuggle-xuggler</artifactId> - * <version>5.4</version> - * </dependency> - * - * @see Apache POI XSLF Adding movie to the slide - * @see Question about embedded video in PPTX files - */ -public class AddVideoToPptx { - static DecimalFormat df_time = new DecimalFormat("0.####"); - - public static void main(String[] args) throws Exception { - URL video = new URL("http://archive.org/download/test-mpeg/test-mpeg.mpg"); - // URL video = new URL("file:test-mpeg.mpg"); - - XMLSlideShow pptx = new XMLSlideShow(); - - // add video file - String videoFileName = video.getPath().substring(video.getPath().lastIndexOf('/')+1); - PackagePartName partName = PackagingURIHelper.createPartName("/ppt/media/"+videoFileName); - PackagePart part = pptx.getPackage().createPart(partName, "video/mpeg"); - OutputStream partOs = part.getOutputStream(); - InputStream fis = video.openStream(); - byte buf[] = new byte[1024]; - for (int readBytes; (readBytes = fis.read(buf)) != -1; partOs.write(buf, 0, readBytes)); - fis.close(); - partOs.close(); - - XSLFSlide slide1 = pptx.createSlide(); - XSLFPictureShape pv1 = addPreview(pptx, slide1, part, 5, 50, 50); - addVideo(pptx, slide1, part, pv1, 5); - addTimingInfo(slide1, pv1); - XSLFPictureShape pv2 = addPreview(pptx, slide1, part, 9, 50, 250); - addVideo(pptx, slide1, part, pv2, 9); - addTimingInfo(slide1, pv2); - - FileOutputStream fos = new FileOutputStream("pptx-with-video.pptx"); - pptx.write(fos); - fos.close(); - - pptx.close(); - } - - static XSLFPictureShape addPreview(XMLSlideShow pptx, XSLFSlide slide1, PackagePart videoPart, double seconds, int x, int y) throws IOException { - // get preview after 5 sec. - IContainer ic = IContainer.make(); - InputOutputStreamHandler iosh = new InputOutputStreamHandler(videoPart.getInputStream()); - if (ic.open(iosh, IContainer.Type.READ, null) < 0) return null; - - IMediaReader mediaReader = ToolFactory.makeReader(ic); - - // stipulate that we want BufferedImages created in BGR 24bit color space - mediaReader.setBufferedImageTypeToGenerate(BufferedImage.TYPE_3BYTE_BGR); - - ImageSnapListener isl = new ImageSnapListener(seconds); - mediaReader.addListener(isl); - - // read out the contents of the media file and - // dispatch events to the attached listener - while (!isl.hasFired && mediaReader.readPacket() == null) ; - - mediaReader.close(); - ic.close(); - - // add snapshot - BufferedImage image1 = isl.image; - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - ImageIO.write(image1, "jpeg", bos); - XSLFPictureData snap = pptx.addPicture(bos.toByteArray(), PictureType.JPEG); - XSLFPictureShape pic1 = slide1.createPicture(snap); - pic1.setAnchor(new Rectangle(x, y, image1.getWidth(), image1.getHeight())); - return pic1; - } - - static void addVideo(XMLSlideShow pptx, XSLFSlide slide1, PackagePart videoPart, XSLFPictureShape pic1, double seconds) throws IOException { - - // add video shape - PackagePartName partName = videoPart.getPartName(); - PackageRelationship prsEmbed1 = slide1.getPackagePart().addRelationship(partName, TargetMode.INTERNAL, "http://schemas.microsoft.com/office/2007/relationships/media"); - PackageRelationship prsExec1 = slide1.getPackagePart().addRelationship(partName, TargetMode.INTERNAL, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/video"); - CTPicture xpic1 = (CTPicture)pic1.getXmlObject(); - CTHyperlink link1 = xpic1.getNvPicPr().getCNvPr().addNewHlinkClick(); - link1.setId(""); - link1.setAction("ppaction://media"); - - // add video relation - CTApplicationNonVisualDrawingProps nvPr = xpic1.getNvPicPr().getNvPr(); - nvPr.addNewVideoFile().setLink(prsExec1.getId()); - CTExtension ext = nvPr.addNewExtLst().addNewExt(); - // see http://msdn.microsoft.com/en-us/library/dd950140(v=office.12).aspx - ext.setUri("{DAA4B4D4-6D71-4841-9C94-3DE7FCFB9230}"); - String p14Ns = "http://schemas.microsoft.com/office/powerpoint/2010/main"; - XmlCursor cur = ext.newCursor(); - cur.toEndToken(); - cur.beginElement(new QName(p14Ns, "media", "p14")); - cur.insertNamespace("p14", p14Ns); - cur.insertAttributeWithValue(new QName(STRelationshipId.type.getName().getNamespaceURI(), "embed"), prsEmbed1.getId()); - cur.beginElement(new QName(p14Ns, "trim", "p14")); - cur.insertAttributeWithValue("st", df_time.format(seconds*1000.0)); - cur.dispose(); - - } - - static void addTimingInfo(XSLFSlide slide1, XSLFPictureShape pic1) { - // add slide timing information, so video can be controlled - CTSlide xslide = slide1.getXmlObject(); - CTTimeNodeList ctnl; - if (!xslide.isSetTiming()) { - CTTLCommonTimeNodeData ctn = xslide.addNewTiming().addNewTnLst().addNewPar().addNewCTn(); - ctn.setDur(STTLTimeIndefinite.INDEFINITE); - ctn.setRestart(STTLTimeNodeRestartType.NEVER); - ctn.setNodeType(STTLTimeNodeType.TM_ROOT); - ctnl = ctn.addNewChildTnLst(); - } else { - ctnl = xslide.getTiming().getTnLst().getParArray(0).getCTn().getChildTnLst(); - } - - CTTLCommonMediaNodeData cmedia = ctnl.addNewVideo().addNewCMediaNode(); - cmedia.setVol(80000); - CTTLCommonTimeNodeData ctn = cmedia.addNewCTn(); - ctn.setFill(STTLTimeNodeFillType.HOLD); - ctn.setDisplay(false); - ctn.addNewStCondLst().addNewCond().setDelay(STTLTimeIndefinite.INDEFINITE); - cmedia.addNewTgtEl().addNewSpTgt().setSpid(""+pic1.getShapeId()); - } - - - static class ImageSnapListener extends MediaListenerAdapter { - final double SECONDS_BETWEEN_FRAMES; - final long MICRO_SECONDS_BETWEEN_FRAMES; - boolean hasFired = false; - BufferedImage image = null; - - // The video stream index, used to ensure we display frames from one and - // only one video stream from the media container. - int mVideoStreamIndex = -1; - - // Time of last frame write - long mLastPtsWrite = Global.NO_PTS; - - public ImageSnapListener(double seconds) { - SECONDS_BETWEEN_FRAMES = seconds; - MICRO_SECONDS_BETWEEN_FRAMES = - (long)(Global.DEFAULT_PTS_PER_SECOND * SECONDS_BETWEEN_FRAMES); - } - - - @Override - public void onVideoPicture(IVideoPictureEvent event) { - - if (event.getStreamIndex() != mVideoStreamIndex) { - // if the selected video stream id is not yet set, go ahead an - // select this lucky video stream - if (mVideoStreamIndex != -1) return; - mVideoStreamIndex = event.getStreamIndex(); - } - - long evtTS = event.getTimeStamp(); - - // if uninitialized, back date mLastPtsWrite to get the very first frame - if (mLastPtsWrite == Global.NO_PTS) - mLastPtsWrite = Math.max(0, evtTS - MICRO_SECONDS_BETWEEN_FRAMES); - - // if it's time to write the next frame - if (evtTS - mLastPtsWrite >= MICRO_SECONDS_BETWEEN_FRAMES) { - if (!hasFired) { - image = event.getImage(); - hasFired = true; - } - // update last write time - mLastPtsWrite += MICRO_SECONDS_BETWEEN_FRAMES; - } - } - } - -} diff --git a/src/examples/src/org/apache/poi/xslf/usermodel/DataExtraction.java b/src/examples/src/org/apache/poi/xslf/usermodel/DataExtraction.java deleted file mode 100644 index ec8fe2342..000000000 --- a/src/examples/src/org/apache/poi/xslf/usermodel/DataExtraction.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xslf.usermodel; - -import java.awt.Dimension; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.PrintStream; - -import org.apache.poi.openxml4j.exceptions.OpenXML4JException; -import org.apache.poi.openxml4j.opc.PackagePart; - -/** - * Demonstrates how you can extract data from a .pptx file - */ -public final class DataExtraction { - - public static void main(String args[]) throws IOException, OpenXML4JException { - - PrintStream out = System.out; - - if (args.length == 0) { - out.println("Input file is required"); - return; - } - - FileInputStream is = new FileInputStream(args[0]); - XMLSlideShow ppt = new XMLSlideShow(is); - is.close(); - - // Get the document's embedded files. - for (PackagePart p : ppt.getAllEmbedds()) { - String type = p.getContentType(); - // typically file name - String name = p.getPartName().getName(); - out.println("Embedded file ("+type+"): "+name); - - InputStream pIs = p.getInputStream(); - // make sense of the part data - pIs.close(); - - } - - // Get the document's embedded files. - for (XSLFPictureData data : ppt.getPictureData()) { - String type = data.getContentType(); - String name = data.getFileName(); - out.println("Picture ("+type+"): "+name); - - InputStream pIs = data.getInputStream(); - // make sense of the image data - pIs.close(); - } - - // size of the canvas in points - Dimension pageSize = ppt.getPageSize(); - out.println("Pagesize: "+pageSize); - - for(XSLFSlide slide : ppt.getSlides()) { - for(XSLFShape shape : slide){ - if(shape instanceof XSLFTextShape) { - XSLFTextShape txShape = (XSLFTextShape)shape; - out.println(txShape.getText()); - } else if (shape instanceof XSLFPictureShape){ - XSLFPictureShape pShape = (XSLFPictureShape)shape; - XSLFPictureData pData = pShape.getPictureData(); - out.println(pData.getFileName()); - } else { - out.println("Process me: " + shape.getClass()); - } - } - } - - ppt.close(); - } - -} diff --git a/src/examples/src/org/apache/poi/xslf/usermodel/MergePresentations.java b/src/examples/src/org/apache/poi/xslf/usermodel/MergePresentations.java deleted file mode 100644 index 73f195eb7..000000000 --- a/src/examples/src/org/apache/poi/xslf/usermodel/MergePresentations.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xslf.usermodel; - -import java.io.FileInputStream; -import java.io.FileOutputStream; - -/** - * Merge multiple pptx presentations together - * - * @author Yegor Kozlov - */ -public final class MergePresentations { - - public static void main(String args[]) throws Exception { - XMLSlideShow ppt = new XMLSlideShow(); - - for(String arg : args){ - FileInputStream is = new FileInputStream(arg); - XMLSlideShow src = new XMLSlideShow(is); - is.close(); - - for(XSLFSlide srcSlide : src.getSlides()){ - ppt.createSlide().importContent(srcSlide); - } - - src.close(); - } - - FileOutputStream out = new FileOutputStream("merged.pptx"); - ppt.write(out); - out.close(); - - ppt.close(); - } - -} diff --git a/src/examples/src/org/apache/poi/xslf/usermodel/PPTX2SVG.txt b/src/examples/src/org/apache/poi/xslf/usermodel/PPTX2SVG.txt deleted file mode 100644 index dbe089ac3..000000000 --- a/src/examples/src/org/apache/poi/xslf/usermodel/PPTX2SVG.txt +++ /dev/null @@ -1,176 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xslf.usermodel; - -import org.apache.batik.dom.svg.SVGDOMImplementation; -import org.apache.batik.svggen.SVGGraphics2D; -import org.apache.batik.transcoder.wmf.tosvg.WMFPainter; -import org.apache.batik.transcoder.wmf.tosvg.WMFRecordStore; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.w3c.dom.DOMImplementation; -import org.w3c.dom.Document; - -import javax.imageio.ImageIO; -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; -import java.awt.Dimension; -import java.awt.Graphics2D; -import java.awt.geom.Rectangle2D; -import java.awt.image.BufferedImage; -import java.io.DataInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStreamWriter; - -/** - * Convert each slide of a .pptx presentation into SVG - * - * @author Yegor Kozlov - */ -public class PPTX2SVG { - - static void usage() { - System.out.println("Usage: PPTX2SVG "); - } - - public static void main(String[] args) throws Exception { - if (args.length == 0) { - usage(); - return; - } - - String file = args[0]; - - System.out.println("Processing " + file); - - // read the .pptx file - XMLSlideShow ppt = new XMLSlideShow(OPCPackage.open(file)); - - Dimension pgsize = ppt.getPageSize(); - - // convert each slide into a .svg file - XSLFSlide[] slide = ppt.getSlides(); - for (int i = 0; i < slide.length; i++) { - // Create initial SVG DOM - DOMImplementation domImpl = SVGDOMImplementation.getDOMImplementation(); - Document doc = domImpl.createDocument("http://www.w3.org/2000/svg", "svg", null); - //Use Batik SVG Graphics2D driver - SVGGraphics2D graphics = new SVGGraphics2D(doc); - graphics.setRenderingHint(XSLFRenderingHint.IMAGE_RENDERER, new WMFImageRender()); - graphics.setSVGCanvasSize(pgsize); - - String title = slide[i].getTitle(); - System.out.println("Rendering slide " + (i + 1) + (title == null ? "" : ": " + title)); - - // draw stuff. All the heavy-lifting happens here - slide[i].draw(graphics); - - // save the result. - int sep = file.lastIndexOf("."); - String fname = file.substring(0, sep == -1 ? file.length() : sep) + "-" + (i + 1) + ".svg"; - OutputStreamWriter out = - new OutputStreamWriter(new FileOutputStream(fname), "UTF-8"); - DOMSource domSource = new DOMSource(graphics.getRoot()); - StreamResult streamResult = new StreamResult(out); - TransformerFactory tf = TransformerFactory.newInstance(); - Transformer serializer = tf.newTransformer(); - serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); - serializer.setOutputProperty(OutputKeys.INDENT, "yes"); - serializer.transform(domSource, streamResult); - out.flush(); - out.close(); - } - System.out.println("Done"); - } - - /** - * Image renderer with support for .wmf images - */ - static class WMFImageRender extends XSLFImageRendener { - - /** - * Use Apache Batik to render WMF, - * delegate all other types of images to the javax.imageio framework - */ - @Override - public boolean drawImage(Graphics2D graphics, XSLFPictureData data, - Rectangle2D anchor) { - try { - // see what type of image we are - PackagePart part = data.getPackagePart(); - String contentType = part.getContentType(); - if (contentType.equals("image/x-wmf")) { - WMFRecordStore currentStore = new WMFRecordStore(); - currentStore.read(new DataInputStream(part.getInputStream())); - int wmfwidth = currentStore.getWidthPixels(); - float conv = (float) anchor.getWidth() / wmfwidth; - - // Build a painter for the RecordStore - WMFPainter painter = new WMFPainter(currentStore, - (int) anchor.getX(), (int) anchor.getY(), conv); - painter.paint(graphics); - } else { - BufferedImage img = ImageIO.read(data.getPackagePart().getInputStream()); - graphics.drawImage(img, - (int) anchor.getX(), (int) anchor.getY(), - (int) anchor.getWidth(), (int) anchor.getHeight(), null); - } - } catch (Exception e) { - return false; - } - return true; - } - - /** - * Convert data form the supplied package part into a BufferedImage. - * This method is used to create texture paint. - */ - @Override - public BufferedImage readImage(PackagePart packagePart) throws IOException { - String contentType = packagePart.getContentType(); - if (contentType.equals("image/x-wmf")) { - try { - WMFRecordStore currentStore = new WMFRecordStore(); - currentStore.read(new DataInputStream(packagePart.getInputStream())); - int wmfwidth = currentStore.getWidthPixels(); - int wmfheight = currentStore.getHeightPixels(); - - BufferedImage img = new BufferedImage(wmfwidth, wmfheight, BufferedImage.TYPE_INT_RGB); - Graphics2D graphics = img.createGraphics(); - - // Build a painter for the RecordStore - WMFPainter painter = new WMFPainter(currentStore, 0, 0, 1.0f); - painter.paint(graphics); - - return img; - } catch (IOException e) { - return null; - } - } else { - return ImageIO.read(packagePart.getInputStream()); - } - } - - } -} diff --git a/src/examples/src/org/apache/poi/xslf/usermodel/PieChartDemo.java b/src/examples/src/org/apache/poi/xslf/usermodel/PieChartDemo.java deleted file mode 100644 index 4ea36e56e..000000000 --- a/src/examples/src/org/apache/poi/xslf/usermodel/PieChartDemo.java +++ /dev/null @@ -1,165 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xslf.usermodel; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.xssf.usermodel.XSSFRow; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTAxDataSource; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTChart; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTNumData; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTNumDataSource; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTNumVal; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTPieChart; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTPieSer; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTPlotArea; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTSerTx; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTStrData; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTStrVal; - -import java.io.BufferedReader; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.FileReader; -import java.io.OutputStream; - -/** - * Build a pie chart from a template pptx - * - * @author Yegor Kozlov - */ -public class PieChartDemo { - private static void usage(){ - System.out.println("Usage: PieChartDemo "); - System.out.println(" pie-chart-template.pptx template with a pie chart"); - System.out.println(" pie-chart-data.txt the model to set. First line is chart title, " + - "then go pairs {axis-label value}"); - } - - public static void main(String[] args) throws Exception { - if(args.length < 2) { - usage(); - return; - } - - BufferedReader modelReader = new BufferedReader(new FileReader(args[1])); - XMLSlideShow pptx = null; - try { - String chartTitle = modelReader.readLine(); // first line is chart title - - pptx = new XMLSlideShow(new FileInputStream(args[0])); - XSLFSlide slide = pptx.getSlides().get(0); - - // find chart in the slide - XSLFChart chart = null; - for(POIXMLDocumentPart part : slide.getRelations()){ - if(part instanceof XSLFChart){ - chart = (XSLFChart) part; - break; - } - } - - if(chart == null) throw new IllegalStateException("chart not found in the template"); - - // embedded Excel workbook that holds the chart data - POIXMLDocumentPart xlsPart = chart.getRelations().get(0); - XSSFWorkbook wb = new XSSFWorkbook(); - try { - XSSFSheet sheet = wb.createSheet(); - - CTChart ctChart = chart.getCTChart(); - CTPlotArea plotArea = ctChart.getPlotArea(); - - CTPieChart pieChart = plotArea.getPieChartArray(0); - //Pie Chart Series - CTPieSer ser = pieChart.getSerArray(0); - - // Series Text - CTSerTx tx = ser.getTx(); - tx.getStrRef().getStrCache().getPtArray(0).setV(chartTitle); - sheet.createRow(0).createCell(1).setCellValue(chartTitle); - String titleRef = new CellReference(sheet.getSheetName(), 0, 1, true, true).formatAsString(); - tx.getStrRef().setF(titleRef); - - // Category Axis Data - CTAxDataSource cat = ser.getCat(); - CTStrData strData = cat.getStrRef().getStrCache(); - - // Values - CTNumDataSource val = ser.getVal(); - CTNumData numData = val.getNumRef().getNumCache(); - - strData.setPtArray(null); // unset old axis text - numData.setPtArray(null); // unset old values - - // set model - int idx = 0; - int rownum = 1; - String ln; - while((ln = modelReader.readLine()) != null){ - String[] vals = ln.split("\\s+"); - CTNumVal numVal = numData.addNewPt(); - numVal.setIdx(idx); - numVal.setV(vals[1]); - - CTStrVal sVal = strData.addNewPt(); - sVal.setIdx(idx); - sVal.setV(vals[0]); - - idx++; - XSSFRow row = sheet.createRow(rownum++); - row.createCell(0).setCellValue(vals[0]); - row.createCell(1).setCellValue(Double.valueOf(vals[1])); - } - numData.getPtCount().setVal(idx); - strData.getPtCount().setVal(idx); - - String numDataRange = new CellRangeAddress(1, rownum-1, 1, 1).formatAsString(sheet.getSheetName(), true); - val.getNumRef().setF(numDataRange); - String axisDataRange = new CellRangeAddress(1, rownum-1, 0, 0).formatAsString(sheet.getSheetName(), true); - cat.getStrRef().setF(axisDataRange); - - // updated the embedded workbook with the data - OutputStream xlsOut = xlsPart.getPackagePart().getOutputStream(); - try { - wb.write(xlsOut); - } finally { - xlsOut.close(); - } - - // save the result - OutputStream out = new FileOutputStream("pie-chart-demo-output.pptx"); - try { - pptx.write(out); - } finally { - out.close(); - } - } finally { - wb.close(); - } - } finally { - if (pptx != null) pptx.close(); - modelReader.close(); - } - } -} diff --git a/src/examples/src/org/apache/poi/xslf/usermodel/Tutorial1.java b/src/examples/src/org/apache/poi/xslf/usermodel/Tutorial1.java deleted file mode 100644 index 714ebb812..000000000 --- a/src/examples/src/org/apache/poi/xslf/usermodel/Tutorial1.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xslf.usermodel; - -import java.io.FileOutputStream; -import java.io.IOException; - -/** - * Demonstrates how to create slides with predefined layout - * and fill the placeholder shapes - * - * @author Yegor Kozlov - */ -public class Tutorial1 { - - public static void main(String[] args) throws IOException{ - XMLSlideShow ppt = new XMLSlideShow(); - - // XSLFSlide#createSlide() with no arguments creates a blank slide - /*XSLFSlide blankSlide =*/ ppt.createSlide(); - - - XSLFSlideMaster master = ppt.getSlideMasters().get(0); - - XSLFSlideLayout layout1 = master.getLayout(SlideLayout.TITLE); - XSLFSlide slide1 = ppt.createSlide(layout1) ; - XSLFTextShape[] ph1 = slide1.getPlaceholders(); - XSLFTextShape titlePlaceholder1 = ph1[0]; - titlePlaceholder1.setText("This is a title"); - XSLFTextShape subtitlePlaceholder1 = ph1[1]; - subtitlePlaceholder1.setText("this is a subtitle"); - - XSLFSlideLayout layout2 = master.getLayout(SlideLayout.TITLE_AND_CONTENT); - XSLFSlide slide2 = ppt.createSlide(layout2) ; - XSLFTextShape[] ph2 = slide2.getPlaceholders(); - XSLFTextShape titlePlaceholder2 = ph2[0]; - titlePlaceholder2.setText("This is a title"); - XSLFTextShape bodyPlaceholder = ph2[1]; - // we are going to add text by paragraphs. Clear the default placehoder text before that - bodyPlaceholder.clearText(); - XSLFTextParagraph p1 = bodyPlaceholder.addNewTextParagraph(); - p1.setIndentLevel(0); - p1.addNewTextRun().setText("Level1 text"); - XSLFTextParagraph p2 = bodyPlaceholder.addNewTextParagraph(); - p2.setIndentLevel(1); - p2.addNewTextRun().setText("Level2 text"); - XSLFTextParagraph p3 = bodyPlaceholder.addNewTextParagraph(); - p3.setIndentLevel(2); - p3.addNewTextRun().setText("Level3 text"); - - FileOutputStream out = new FileOutputStream("slides.pptx"); - ppt.write(out); - out.close(); - - ppt.close(); - } -} diff --git a/src/examples/src/org/apache/poi/xslf/usermodel/Tutorial2.java b/src/examples/src/org/apache/poi/xslf/usermodel/Tutorial2.java deleted file mode 100644 index 3f1402ae6..000000000 --- a/src/examples/src/org/apache/poi/xslf/usermodel/Tutorial2.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xslf.usermodel; - -import java.awt.Color; -import java.awt.Rectangle; -import java.io.FileOutputStream; -import java.io.IOException; - -/** - * Basic paragraph and text formatting - * - * @author Yegor Kozlov - */ -public class Tutorial2 { - - public static void main(String[] args) throws IOException{ - XMLSlideShow ppt = new XMLSlideShow(); - - XSLFSlide slide1 = ppt.createSlide(); - XSLFTextBox shape1 = slide1.createTextBox(); - // initial height of the text box is 100 pt but - Rectangle anchor = new Rectangle(10, 100, 300, 100); - shape1.setAnchor(anchor); - - XSLFTextParagraph p1 = shape1.addNewTextParagraph(); - XSLFTextRun r1 = p1.addNewTextRun(); - r1.setText("Paragraph Formatting"); - r1.setFontSize(24d); - r1.setFontColor(new Color(85, 142, 213)); - - XSLFTextParagraph p2 = shape1.addNewTextParagraph(); - // If spaceBefore >= 0, then space is a percentage of normal line height. - // If spaceBefore < 0, the absolute value of linespacing is the spacing in points - p2.setSpaceBefore(-20d); // 20 pt from the previous paragraph - p2.setSpaceAfter(300d); // 3 lines after the paragraph - XSLFTextRun r2 = p2.addNewTextRun(); - r2.setText("Paragraph properties apply to all text residing within the corresponding paragraph."); - r2.setFontSize(16d); - - XSLFTextParagraph p3 = shape1.addNewTextParagraph(); - - XSLFTextRun r3 = p3.addNewTextRun(); - r3.setText("Run Formatting"); - r3.setFontSize(24d); - r3.setFontColor(new Color(85, 142, 213)); - - XSLFTextParagraph p4 = shape1.addNewTextParagraph(); - p4.setSpaceBefore(-20d); // 20 pt from the previous paragraph - p4.setSpaceAfter(300d); // 3 lines after the paragraph - XSLFTextRun r4 = p4.addNewTextRun(); - r4.setFontSize(16d); - r4.setText( - "Run level formatting is the most granular property level and allows " + - "for the specifying of all low level text properties. The text run is " + - "what all paragraphs are derived from and thus specifying various " + - "properties per run will allow for a diversely formatted text paragraph."); - - // resize the shape to fit text - shape1.resizeToFitText(); - - FileOutputStream out = new FileOutputStream("text.pptx"); - ppt.write(out); - out.close(); - - ppt.close(); - } -} diff --git a/src/examples/src/org/apache/poi/xslf/usermodel/Tutorial3.java b/src/examples/src/org/apache/poi/xslf/usermodel/Tutorial3.java deleted file mode 100644 index 4cab79d88..000000000 --- a/src/examples/src/org/apache/poi/xslf/usermodel/Tutorial3.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xslf.usermodel; - -import java.awt.Rectangle; -import java.io.FileOutputStream; -import java.io.IOException; - -import org.apache.poi.sl.usermodel.Placeholder; - -/** - * How to set slide title - * - * @author Yegor Kozlov - */ -public class Tutorial3 { - - public static void main(String[] args) throws IOException{ - XMLSlideShow ppt = new XMLSlideShow(); - - XSLFSlide slide = ppt.createSlide(); - - XSLFTextShape titleShape = slide.createTextBox(); - titleShape.setPlaceholder(Placeholder.TITLE); - titleShape.setText("This is a slide title"); - titleShape.setAnchor(new Rectangle(50, 50, 400, 100)); - - FileOutputStream out = new FileOutputStream("title.pptx"); - ppt.write(out); - out.close(); - - ppt.close(); - } -} diff --git a/src/examples/src/org/apache/poi/xslf/usermodel/Tutorial4.java b/src/examples/src/org/apache/poi/xslf/usermodel/Tutorial4.java deleted file mode 100644 index 0cf0fd667..000000000 --- a/src/examples/src/org/apache/poi/xslf/usermodel/Tutorial4.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xslf.usermodel; - -import java.awt.Color; -import java.awt.Rectangle; -import java.io.FileOutputStream; -import java.io.IOException; - -import org.apache.poi.sl.usermodel.TableCell.BorderEdge; -import org.apache.poi.sl.usermodel.TextParagraph.TextAlign; - -/** - * PPTX Tables - * - * @author Yegor Kozlov - */ -public class Tutorial4 { - - public static void main(String[] args) throws IOException{ - XMLSlideShow ppt = new XMLSlideShow(); - - // XSLFSlide#createSlide() with no arguments creates a blank slide - XSLFSlide slide = ppt.createSlide(); - - XSLFTable tbl = slide.createTable(); - tbl.setAnchor(new Rectangle(50, 50, 450, 300)); - - int numColumns = 3; - int numRows = 5; - XSLFTableRow headerRow = tbl.addRow(); - headerRow.setHeight(50); - // header - for(int i = 0; i < numColumns; i++) { - XSLFTableCell th = headerRow.addCell(); - XSLFTextParagraph p = th.addNewTextParagraph(); - p.setTextAlign(TextAlign.CENTER); - XSLFTextRun r = p.addNewTextRun(); - r.setText("Header " + (i+1)); - r.setBold(true); - r.setFontColor(Color.white); - th.setFillColor(new Color(79, 129, 189)); - th.setBorderWidth(BorderEdge.bottom, 2.0); - th.setBorderColor(BorderEdge.bottom, Color.white); - - tbl.setColumnWidth(i, 150); // all columns are equally sized - } - - // rows - - for(int rownum = 0; rownum < numRows; rownum ++){ - XSLFTableRow tr = tbl.addRow(); - tr.setHeight(50); - // header - for(int i = 0; i < numColumns; i++) { - XSLFTableCell cell = tr.addCell(); - XSLFTextParagraph p = cell.addNewTextParagraph(); - XSLFTextRun r = p.addNewTextRun(); - - r.setText("Cell " + (i+1)); - if(rownum % 2 == 0) - cell.setFillColor(new Color(208, 216, 232)); - else - cell.setFillColor(new Color(233, 247, 244)); - - } - - } - - - FileOutputStream out = new FileOutputStream("table.pptx"); - ppt.write(out); - out.close(); - - ppt.close(); - } -} diff --git a/src/examples/src/org/apache/poi/xslf/usermodel/Tutorial5.java b/src/examples/src/org/apache/poi/xslf/usermodel/Tutorial5.java deleted file mode 100644 index 988caee2e..000000000 --- a/src/examples/src/org/apache/poi/xslf/usermodel/Tutorial5.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xslf.usermodel; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; - -import org.apache.poi.sl.usermodel.PictureData.PictureType; - -/** - * Images - * - * @author Yegor Kozlov - */ -public class Tutorial5 { - - public static void main(String[] args) throws IOException{ - XMLSlideShow ppt = new XMLSlideShow(); - - XSLFSlide slide = ppt.createSlide(); - - File img = new File(System.getProperty("POI.testdata.path", "test-data"), "slideshow/clock.jpg"); - XSLFPictureData pictureData = ppt.addPicture(img, PictureType.PNG); - - /*XSLFPictureShape shape =*/ slide.createPicture(pictureData); - - FileOutputStream out = new FileOutputStream("images.pptx"); - ppt.write(out); - out.close(); - - ppt.close(); - } -} diff --git a/src/examples/src/org/apache/poi/xslf/usermodel/Tutorial6.java b/src/examples/src/org/apache/poi/xslf/usermodel/Tutorial6.java deleted file mode 100644 index 020089555..000000000 --- a/src/examples/src/org/apache/poi/xslf/usermodel/Tutorial6.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xslf.usermodel; - -import java.awt.Rectangle; -import java.io.FileOutputStream; -import java.io.IOException; - -/** - * Hyperlinks - * - * @author Yegor Kozlov - */ -public class Tutorial6 { - - public static void main(String[] args) throws IOException{ - XMLSlideShow ppt = new XMLSlideShow(); - - XSLFSlide slide1 = ppt.createSlide(); - XSLFSlide slide2 = ppt.createSlide(); - - XSLFTextBox shape1 = slide1.createTextBox(); - shape1.setAnchor(new Rectangle(50, 50, 200, 50)); - XSLFTextRun r1 = shape1.addNewTextParagraph().addNewTextRun(); - XSLFHyperlink link1 = r1.createHyperlink(); - r1.setText("http://poi.apache.org"); // visible text - link1.setAddress("http://poi.apache.org"); // link address - - XSLFTextBox shape2 = slide1.createTextBox(); - shape2.setAnchor(new Rectangle(300, 50, 200, 50)); - XSLFTextRun r2 = shape2.addNewTextParagraph().addNewTextRun(); - XSLFHyperlink link2 = r2.createHyperlink(); - r2.setText("Go to the second slide"); // visible text - link2.linkToSlide(slide2); // link address - - - - FileOutputStream out = new FileOutputStream("hyperlinks.pptx"); - ppt.write(out); - out.close(); - - ppt.close(); - } -} diff --git a/src/examples/src/org/apache/poi/xslf/usermodel/Tutorial7.java b/src/examples/src/org/apache/poi/xslf/usermodel/Tutorial7.java deleted file mode 100644 index 647fef758..000000000 --- a/src/examples/src/org/apache/poi/xslf/usermodel/Tutorial7.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xslf.usermodel; - -import java.awt.Color; -import java.awt.Rectangle; -import java.io.FileOutputStream; -import java.io.IOException; - -import org.apache.poi.sl.usermodel.AutoNumberingScheme; - -/** - * Bullets and numbering - * - * @author Yegor Kozlov - */ -public class Tutorial7 { - - public static void main(String[] args) throws IOException{ - XMLSlideShow ppt = new XMLSlideShow(); - - XSLFSlide slide = ppt.createSlide(); - XSLFTextBox shape = slide.createTextBox(); - shape.setAnchor(new Rectangle(50, 50, 400, 200)); - - XSLFTextParagraph p1 = shape.addNewTextParagraph(); - p1.setIndentLevel(0); - p1.setBullet(true); - XSLFTextRun r1 = p1.addNewTextRun(); - r1.setText("Bullet1"); - - XSLFTextParagraph p2 = shape.addNewTextParagraph(); - // indentation before text - p2.setLeftMargin(60d); - // the bullet is set 40 pt before the text - p2.setIndent(-40d); - p2.setBullet(true); - // customize bullets - p2.setBulletFontColor(Color.red); - p2.setBulletFont("Wingdings"); - p2.setBulletCharacter("\u0075"); - p2.setIndentLevel(1); - XSLFTextRun r2 = p2.addNewTextRun(); - r2.setText("Bullet2"); - - // the next three paragraphs form an auto-numbered list - XSLFTextParagraph p3 = shape.addNewTextParagraph(); - p3.setBulletAutoNumber(AutoNumberingScheme.alphaLcParenRight, 1); - p3.setIndentLevel(2); - XSLFTextRun r3 = p3.addNewTextRun(); - r3.setText("Numbered List Item - 1"); - - XSLFTextParagraph p4 = shape.addNewTextParagraph(); - p4.setBulletAutoNumber(AutoNumberingScheme.alphaLcParenRight, 2); - p4.setIndentLevel(2); - XSLFTextRun r4 = p4.addNewTextRun(); - r4.setText("Numbered List Item - 2"); - - XSLFTextParagraph p5 = shape.addNewTextParagraph(); - p5.setBulletAutoNumber(AutoNumberingScheme.alphaLcParenRight, 3); - p5.setIndentLevel(2); - XSLFTextRun r5 = p5.addNewTextRun(); - r5.setText("Numbered List Item - 3"); - - shape.resizeToFitText(); - - FileOutputStream out = new FileOutputStream("list.pptx"); - ppt.write(out); - out.close(); - - ppt.close(); - } -} diff --git a/src/examples/src/org/apache/poi/xslf/usermodel/pie-chart-data.txt b/src/examples/src/org/apache/poi/xslf/usermodel/pie-chart-data.txt deleted file mode 100644 index 40b6959c2..000000000 --- a/src/examples/src/org/apache/poi/xslf/usermodel/pie-chart-data.txt +++ /dev/null @@ -1,4 +0,0 @@ -My Chart -First 1.0 -Second 3.0 -Third 4.0 \ No newline at end of file diff --git a/src/examples/src/org/apache/poi/xslf/usermodel/pie-chart-template.pptx b/src/examples/src/org/apache/poi/xslf/usermodel/pie-chart-template.pptx deleted file mode 100644 index 33d28e154..000000000 Binary files a/src/examples/src/org/apache/poi/xslf/usermodel/pie-chart-template.pptx and /dev/null differ diff --git a/src/examples/src/org/apache/poi/xslf/usermodel/tutorial/Step1.java b/src/examples/src/org/apache/poi/xslf/usermodel/tutorial/Step1.java deleted file mode 100644 index 8552ff943..000000000 --- a/src/examples/src/org/apache/poi/xslf/usermodel/tutorial/Step1.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xslf.usermodel.tutorial; - -import java.io.FileInputStream; - -import org.apache.poi.xslf.usermodel.XMLSlideShow; -import org.apache.poi.xslf.usermodel.XSLFShape; -import org.apache.poi.xslf.usermodel.XSLFSlide; -import org.apache.poi.xslf.usermodel.XSLFTextParagraph; -import org.apache.poi.xslf.usermodel.XSLFTextRun; -import org.apache.poi.xslf.usermodel.XSLFTextShape; - -/** - * Reading a .pptx presentation and printing basic shape properties - */ -public class Step1 { - - public static void main(String[] args) throws Exception { - if(args.length == 0) { - System.out.println("Input file is required"); - return; - } - - FileInputStream fis = new FileInputStream(args[0]); - XMLSlideShow ppt = new XMLSlideShow(fis); - fis.close(); - - for(XSLFSlide slide : ppt.getSlides()){ - System.out.println("Title: " + slide.getTitle()); - - for(XSLFShape shape : slide.getShapes()){ - if(shape instanceof XSLFTextShape) { - XSLFTextShape tsh = (XSLFTextShape)shape; - for(XSLFTextParagraph p : tsh){ - System.out.println("Paragraph level: " + p.getIndentLevel()); - for(XSLFTextRun r : p){ - System.out.println(r.getRawText()); - System.out.println(" bold: " + r.isBold()); - System.out.println(" italic: " + r.isItalic()); - System.out.println(" underline: " + r.isUnderlined()); - System.out.println(" font.family: " + r.getFontFamily()); - System.out.println(" font.size: " + r.getFontSize()); - System.out.println(" font.color: " + r.getFontColor()); - } - } - } - } - } - - ppt.close(); - } -} diff --git a/src/examples/src/org/apache/poi/xslf/usermodel/tutorial/Step2.java b/src/examples/src/org/apache/poi/xslf/usermodel/tutorial/Step2.java deleted file mode 100644 index 792f75545..000000000 --- a/src/examples/src/org/apache/poi/xslf/usermodel/tutorial/Step2.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xslf.usermodel.tutorial; - -import org.apache.poi.xslf.usermodel.SlideLayout; -import org.apache.poi.xslf.usermodel.XMLSlideShow; -import org.apache.poi.xslf.usermodel.XSLFSlide; -import org.apache.poi.xslf.usermodel.XSLFSlideLayout; -import org.apache.poi.xslf.usermodel.XSLFSlideMaster; -import org.apache.poi.xslf.usermodel.XSLFTextShape; - -import java.io.FileOutputStream; - -/** - * Create slides from pre-defined slide layouts - */ -public class Step2 { - public static void main(String[] args) throws Exception{ - XMLSlideShow ppt = new XMLSlideShow(); - - // first see what slide layouts are available by default - System.out.println("Available slide layouts:"); - for(XSLFSlideMaster master : ppt.getSlideMasters()){ - for(XSLFSlideLayout layout : master.getSlideLayouts()){ - System.out.println(layout.getType()); - } - } - - // blank slide - /*XSLFSlide blankSlide =*/ ppt.createSlide(); - - XSLFSlideMaster defaultMaster = ppt.getSlideMasters().get(0); - - // title slide - XSLFSlideLayout titleLayout = defaultMaster.getLayout(SlideLayout.TITLE); - XSLFSlide slide1 = ppt.createSlide(titleLayout); - XSLFTextShape title1 = slide1.getPlaceholder(0); - title1.setText("First Title"); - - // title and content - XSLFSlideLayout titleBodyLayout = defaultMaster.getLayout(SlideLayout.TITLE_AND_CONTENT); - XSLFSlide slide2 = ppt.createSlide(titleBodyLayout); - - XSLFTextShape title2 = slide2.getPlaceholder(0); - title2.setText("Second Title"); - - XSLFTextShape body2 = slide2.getPlaceholder(1); - body2.clearText(); // unset any existing text - body2.addNewTextParagraph().addNewTextRun().setText("First paragraph"); - body2.addNewTextParagraph().addNewTextRun().setText("Second paragraph"); - body2.addNewTextParagraph().addNewTextRun().setText("Third paragraph"); - - - - FileOutputStream out = new FileOutputStream("step2.pptx"); - ppt.write(out); - out.close(); - ppt.close(); - } -} diff --git a/src/examples/src/org/apache/poi/xssf/eventusermodel/XLSX2CSV.java b/src/examples/src/org/apache/poi/xssf/eventusermodel/XLSX2CSV.java deleted file mode 100644 index bd537c1d1..000000000 --- a/src/examples/src/org/apache/poi/xssf/eventusermodel/XLSX2CSV.java +++ /dev/null @@ -1,250 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.eventusermodel; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.PrintStream; - -import javax.xml.parsers.ParserConfigurationException; - -import org.apache.poi.openxml4j.exceptions.OpenXML4JException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackageAccess; -import org.apache.poi.ss.usermodel.DataFormatter; -import org.apache.poi.ss.util.CellAddress; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.util.SAXHelper; -import org.apache.poi.xssf.eventusermodel.XSSFSheetXMLHandler.SheetContentsHandler; -import org.apache.poi.xssf.extractor.XSSFEventBasedExcelExtractor; -import org.apache.poi.xssf.model.StylesTable; -import org.apache.poi.xssf.usermodel.XSSFComment; -import org.xml.sax.ContentHandler; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; -import org.xml.sax.XMLReader; - -/** - * A rudimentary XLSX -> CSV processor modeled on the - * POI sample program XLS2CSVmra from the package - * org.apache.poi.hssf.eventusermodel.examples. - * As with the HSSF version, this tries to spot missing - * rows and cells, and output empty entries for them. - *

    - * Data sheets are read using a SAX parser to keep the - * memory footprint relatively small, so this should be - * able to read enormous workbooks. The styles table and - * the shared-string table must be kept in memory. The - * standard POI styles table class is used, but a custom - * (read-only) class is used for the shared string table - * because the standard POI SharedStringsTable grows very - * quickly with the number of unique strings. - *

    - * For a more advanced implementation of SAX event parsing - * of XLSX files, see {@link XSSFEventBasedExcelExtractor} - * and {@link XSSFSheetXMLHandler}. Note that for many cases, - * it may be possible to simply use those with a custom - * {@link SheetContentsHandler} and no SAX code needed of - * your own! - */ -public class XLSX2CSV { - /** - * Uses the XSSF Event SAX helpers to do most of the work - * of parsing the Sheet XML, and outputs the contents - * as a (basic) CSV. - */ - private class SheetToCSV implements SheetContentsHandler { - private boolean firstCellOfRow = false; - private int currentRow = -1; - private int currentCol = -1; - - private void outputMissingRows(int number) { - for (int i=0; i CSV converter - * - * @param pkg The XLSX package to process - * @param output The PrintStream to output the CSV to - * @param minColumns The minimum number of columns to output, or -1 for no minimum - */ - public XLSX2CSV(OPCPackage pkg, PrintStream output, int minColumns) { - this.xlsxPackage = pkg; - this.output = output; - this.minColumns = minColumns; - } - - /** - * Parses and shows the content of one sheet - * using the specified styles and shared-strings tables. - * - * @param styles The table of styles that may be referenced by cells in the sheet - * @param strings The table of strings that may be referenced by cells in the sheet - * @param sheetInputStream The stream to read the sheet-data from. - - * @exception java.io.IOException An IO exception from the parser, - * possibly from a byte stream or character stream - * supplied by the application. - * @throws SAXException if parsing the XML data fails. - */ - public void processSheet( - StylesTable styles, - ReadOnlySharedStringsTable strings, - SheetContentsHandler sheetHandler, - InputStream sheetInputStream) throws IOException, SAXException { - DataFormatter formatter = new DataFormatter(); - InputSource sheetSource = new InputSource(sheetInputStream); - try { - XMLReader sheetParser = SAXHelper.newXMLReader(); - ContentHandler handler = new XSSFSheetXMLHandler( - styles, null, strings, sheetHandler, formatter, false); - sheetParser.setContentHandler(handler); - sheetParser.parse(sheetSource); - } catch(ParserConfigurationException e) { - throw new RuntimeException("SAX parser appears to be broken - " + e.getMessage()); - } - } - - /** - * Initiates the processing of the XLS workbook file to CSV. - * - * @throws IOException If reading the data from the package fails. - * @throws SAXException if parsing the XML data fails. - */ - public void process() throws IOException, OpenXML4JException, SAXException { - ReadOnlySharedStringsTable strings = new ReadOnlySharedStringsTable(this.xlsxPackage); - XSSFReader xssfReader = new XSSFReader(this.xlsxPackage); - StylesTable styles = xssfReader.getStylesTable(); - XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) xssfReader.getSheetsData(); - int index = 0; - while (iter.hasNext()) { - InputStream stream = iter.next(); - String sheetName = iter.getSheetName(); - this.output.println(); - this.output.println(sheetName + " [index=" + index + "]:"); - processSheet(styles, strings, new SheetToCSV(), stream); - stream.close(); - ++index; - } - } - - public static void main(String[] args) throws Exception { - if (args.length < 1) { - System.err.println("Use:"); - System.err.println(" XLSX2CSV [min columns]"); - return; - } - - File xlsxFile = new File(args[0]); - if (!xlsxFile.exists()) { - System.err.println("Not found or not a file: " + xlsxFile.getPath()); - return; - } - - int minColumns = -1; - if (args.length >= 2) - minColumns = Integer.parseInt(args[1]); - - // The package open is instantaneous, as it should be. - OPCPackage p = OPCPackage.open(xlsxFile.getPath(), PackageAccess.READ); - XLSX2CSV xlsx2csv = new XLSX2CSV(p, System.out, minColumns); - xlsx2csv.process(); - p.close(); - } -} diff --git a/src/examples/src/org/apache/poi/xssf/eventusermodel/examples/FromHowTo.java b/src/examples/src/org/apache/poi/xssf/eventusermodel/examples/FromHowTo.java deleted file mode 100644 index 6e35e8cdb..000000000 --- a/src/examples/src/org/apache/poi/xssf/eventusermodel/examples/FromHowTo.java +++ /dev/null @@ -1,168 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.eventusermodel.examples; - -import java.io.InputStream; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.Map; - -import org.apache.poi.openxml4j.opc.PackageAccess; -import org.apache.poi.xssf.eventusermodel.XLSX2CSV; -import org.apache.poi.xssf.eventusermodel.XSSFReader; -import org.apache.poi.xssf.model.SharedStringsTable; -import org.apache.poi.xssf.usermodel.XSSFRichTextString; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.xml.sax.Attributes; -import org.xml.sax.ContentHandler; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; -import org.xml.sax.XMLReader; -import org.xml.sax.helpers.DefaultHandler; -import org.xml.sax.helpers.XMLReaderFactory; - -/** - * XSSF and SAX (Event API) basic example. - * See {@link XLSX2CSV} for a fuller example of doing - * XSLX processing with the XSSF Event code. - */ -public class FromHowTo { - public void processFirstSheet(String filename) throws Exception { - OPCPackage pkg = OPCPackage.open(filename, PackageAccess.READ); - try { - XSSFReader r = new XSSFReader(pkg); - SharedStringsTable sst = r.getSharedStringsTable(); - - XMLReader parser = fetchSheetParser(sst); - - // process the first sheet - InputStream sheet2 = r.getSheetsData().next(); - InputSource sheetSource = new InputSource(sheet2); - parser.parse(sheetSource); - sheet2.close(); - } finally { - pkg.close(); - } - } - - public void processAllSheets(String filename) throws Exception { - OPCPackage pkg = OPCPackage.open(filename, PackageAccess.READ); - try { - XSSFReader r = new XSSFReader(pkg); - SharedStringsTable sst = r.getSharedStringsTable(); - - XMLReader parser = fetchSheetParser(sst); - - Iterator sheets = r.getSheetsData(); - while (sheets.hasNext()) { - System.out.println("Processing new sheet:\n"); - InputStream sheet = sheets.next(); - InputSource sheetSource = new InputSource(sheet); - parser.parse(sheetSource); - sheet.close(); - System.out.println(""); - } - } finally { - pkg.close(); - } - } - - public XMLReader fetchSheetParser(SharedStringsTable sst) throws SAXException { - XMLReader parser = XMLReaderFactory.createXMLReader(); - ContentHandler handler = new SheetHandler(sst); - parser.setContentHandler(handler); - return parser; - } - - /** - * See org.xml.sax.helpers.DefaultHandler javadocs - */ - private static class SheetHandler extends DefaultHandler { - private final SharedStringsTable sst; - private String lastContents; - private boolean nextIsString; - private boolean inlineStr; - private final LruCache lruCache = new LruCache(50); - - private static class LruCache extends LinkedHashMap { - private final int maxEntries; - - public LruCache(final int maxEntries) { - super(maxEntries + 1, 1.0f, true); - this.maxEntries = maxEntries; - } - - @Override - protected boolean removeEldestEntry(final Map.Entry eldest) { - return super.size() > maxEntries; - } - } - - private SheetHandler(SharedStringsTable sst) { - this.sst = sst; - } - - @Override - public void startElement(String uri, String localName, String name, - Attributes attributes) throws SAXException { - // c => cell - if(name.equals("c")) { - // Print the cell reference - System.out.print(attributes.getValue("r") + " - "); - // Figure out if the value is an index in the SST - String cellType = attributes.getValue("t"); - nextIsString = cellType != null && cellType.equals("s"); - inlineStr = cellType != null && cellType.equals("inlineStr"); - } - // Clear contents cache - lastContents = ""; - } - - @Override - public void endElement(String uri, String localName, String name) - throws SAXException { - // Process the last contents as required. - // Do now, as characters() may be called more than once - if(nextIsString) { - Integer idx = Integer.valueOf(lastContents); - lastContents = lruCache.get(idx); - if (lastContents == null && !lruCache.containsKey(idx)) { - lastContents = new XSSFRichTextString(sst.getEntryAt(idx)).toString(); - lruCache.put(idx, lastContents); - } - nextIsString = false; - } - - // v => contents of a cell - // Output after we've seen the string contents - if(name.equals("v") || (inlineStr && name.equals("c"))) { - System.out.println(lastContents); - } - } - - @Override - public void characters(char[] ch, int start, int length) throws SAXException { // NOSONAR - lastContents += new String(ch, start, length); - } - } - - public static void main(String[] args) throws Exception { - FromHowTo howto = new FromHowTo(); - howto.processFirstSheet(args[0]); - howto.processAllSheets(args[0]); - } -} diff --git a/src/examples/src/org/apache/poi/xssf/eventusermodel/examples/LoadPasswordProtectedXlsxStreaming.java b/src/examples/src/org/apache/poi/xssf/eventusermodel/examples/LoadPasswordProtectedXlsxStreaming.java deleted file mode 100644 index 80e4c7320..000000000 --- a/src/examples/src/org/apache/poi/xssf/eventusermodel/examples/LoadPasswordProtectedXlsxStreaming.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xssf.eventusermodel.examples; - -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.crypt.examples.EncryptionUtils; -import org.apache.poi.examples.util.TempFileUtils; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.poifs.crypt.temp.AesZipFileZipEntrySource; -import org.apache.poi.util.IOUtils; -import org.apache.poi.xssf.eventusermodel.XSSFReader; -import org.apache.poi.xssf.eventusermodel.XSSFReader.SheetIterator; - -/** - * An example that loads a password protected workbook and counts the sheets. - * The example highlights how to do this in streaming way. - *

      - *
    • The example demonstrates that all temp files are removed. - *
    • AesZipFileZipEntrySource is used to ensure that temp files are encrypted. - *

    - */ -public class LoadPasswordProtectedXlsxStreaming { - - public static void main(String[] args) throws Exception { - if(args.length != 2) { - throw new IllegalArgumentException("Expected 2 params: filename and password"); - } - TempFileUtils.checkTempFiles(); - String filename = args[0]; - String password = args[1]; - FileInputStream fis = new FileInputStream(filename); - try { - InputStream unencryptedStream = EncryptionUtils.decrypt(fis, password); - try { - printSheetCount(unencryptedStream); - } finally { - IOUtils.closeQuietly(unencryptedStream); - } - } finally { - IOUtils.closeQuietly(fis); - } - TempFileUtils.checkTempFiles(); - } - - public static void printSheetCount(final InputStream inputStream) throws Exception { - AesZipFileZipEntrySource source = AesZipFileZipEntrySource.createZipEntrySource(inputStream); - try { - OPCPackage pkg = OPCPackage.open(source); - try { - XSSFReader reader = new XSSFReader(pkg); - SheetIterator iter = (SheetIterator)reader.getSheetsData(); - int count = 0; - while(iter.hasNext()) { - iter.next(); - count++; - } - System.out.println("sheet count: " + count); - } finally { - IOUtils.closeQuietly(pkg); - } - } finally { - IOUtils.closeQuietly(source); - } - } -} diff --git a/src/examples/src/org/apache/poi/xssf/streaming/examples/HybridStreaming.java b/src/examples/src/org/apache/poi/xssf/streaming/examples/HybridStreaming.java deleted file mode 100644 index 31b5e859f..000000000 --- a/src/examples/src/org/apache/poi/xssf/streaming/examples/HybridStreaming.java +++ /dev/null @@ -1,81 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.streaming.examples; - -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.xssf.eventusermodel.ReadOnlySharedStringsTable; -import org.apache.poi.xssf.eventusermodel.XSSFSheetXMLHandler; -import org.apache.poi.xssf.eventusermodel.XSSFSheetXMLHandler.SheetContentsHandler; -import org.apache.poi.xssf.usermodel.XSSFComment; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTSheet; -import org.xml.sax.SAXException; - -/** - * This demonstrates how a hybrid approach to workbook read can be taken, using - * a mix of traditional XSSF and streaming one particular worksheet (perhaps one - * which is too big for the ordinary DOM parse). - */ -public class HybridStreaming { - - private static final String SHEET_TO_STREAM = "large sheet"; - - public static void main(String[] args) throws IOException, SAXException { - InputStream sourceBytes = new FileInputStream("workbook.xlsx"); - XSSFWorkbook workbook = new XSSFWorkbook(sourceBytes) { - /** Avoid DOM parse of large sheet */ - @Override - public void parseSheet(java.util.Map shIdMap, CTSheet ctSheet) { - if (!SHEET_TO_STREAM.equals(ctSheet.getName())) { - super.parseSheet(shIdMap, ctSheet); - } - } - }; - - // Having avoided a DOM-based parse of the sheet, we can stream it instead. - ReadOnlySharedStringsTable strings = new ReadOnlySharedStringsTable(workbook.getPackage()); - new XSSFSheetXMLHandler(workbook.getStylesSource(), strings, createSheetContentsHandler(), false); - workbook.close(); - sourceBytes.close(); - } - - private static SheetContentsHandler createSheetContentsHandler() { - return new SheetContentsHandler() { - - @Override - public void startRow(int rowNum) { - } - - @Override - public void headerFooter(String text, boolean isHeader, String tagName) { - } - - @Override - public void endRow(int rowNum) { - } - - @Override - public void cell(String cellReference, String formattedValue, XSSFComment comment) { - } - }; - } - -} diff --git a/src/examples/src/org/apache/poi/xssf/streaming/examples/Outlining.java b/src/examples/src/org/apache/poi/xssf/streaming/examples/Outlining.java deleted file mode 100644 index 4c0b35c85..000000000 --- a/src/examples/src/org/apache/poi/xssf/streaming/examples/Outlining.java +++ /dev/null @@ -1,56 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.streaming.examples; - -import java.io.FileOutputStream; -import java.io.IOException; - -import org.apache.poi.xssf.streaming.SXSSFSheet; -import org.apache.poi.xssf.streaming.SXSSFWorkbook; - -public class Outlining { - - public static void main(String[] args) throws IOException { - Outlining o = new Outlining(); - o.collapseRow(); - } - - private void collapseRow() throws IOException { - SXSSFWorkbook wb2 = new SXSSFWorkbook(100); - SXSSFSheet sheet2 = wb2.createSheet("new sheet"); - - int rowCount = 20; - for (int i = 0; i < rowCount; i++) { - sheet2.createRow(i); - } - - sheet2.groupRow(4, 9); - sheet2.groupRow(11, 19); - - sheet2.setRowGroupCollapsed(4, true); - - FileOutputStream fileOut = new FileOutputStream("outlining_collapsed.xlsx"); - try { - wb2.write(fileOut); - } finally { - fileOut.close(); - wb2.dispose(); - wb2.close(); - } - } -} diff --git a/src/examples/src/org/apache/poi/xssf/streaming/examples/SavePasswordProtectedXlsx.java b/src/examples/src/org/apache/poi/xssf/streaming/examples/SavePasswordProtectedXlsx.java deleted file mode 100644 index 79b3293a6..000000000 --- a/src/examples/src/org/apache/poi/xssf/streaming/examples/SavePasswordProtectedXlsx.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xssf.streaming.examples; - -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.security.GeneralSecurityException; - -import org.apache.poi.examples.util.TempFileUtils; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.poifs.crypt.EncryptionInfo; -import org.apache.poi.poifs.crypt.EncryptionMode; -import org.apache.poi.poifs.crypt.Encryptor; -import org.apache.poi.poifs.crypt.temp.EncryptedTempData; -import org.apache.poi.poifs.crypt.temp.SXSSFWorkbookWithCustomZipEntrySource; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.util.IOUtils; -import org.apache.poi.xssf.streaming.SXSSFCell; -import org.apache.poi.xssf.streaming.SXSSFRow; -import org.apache.poi.xssf.streaming.SXSSFSheet; - -/** - * An example that outputs a simple generated workbook that is password protected. - * The example highlights how to do this in streaming way. - *

      - *
    • The example demonstrates that all temp files are removed. - *
    • SXSSFWorkbookWithCustomZipEntrySource extends SXSSFWorkbook to ensure temp files are encrypted. - *

    - */ -public class SavePasswordProtectedXlsx { - - public static void main(String[] args) throws Exception { - if(args.length != 2) { - throw new IllegalArgumentException("Expected 2 params: filename and password"); - } - TempFileUtils.checkTempFiles(); - String filename = args[0]; - String password = args[1]; - SXSSFWorkbookWithCustomZipEntrySource wb = new SXSSFWorkbookWithCustomZipEntrySource(); - try { - for(int i = 0; i < 10; i++) { - SXSSFSheet sheet = wb.createSheet("Sheet" + i); - for(int r = 0; r < 1000; r++) { - SXSSFRow row = sheet.createRow(r); - for(int c = 0; c < 100; c++) { - SXSSFCell cell = row.createCell(c); - cell.setCellValue("abcd"); - } - } - } - EncryptedTempData tempData = new EncryptedTempData(); - try { - wb.write(tempData.getOutputStream()); - save(tempData.getInputStream(), filename, password); - System.out.println("Saved " + filename); - } finally { - tempData.dispose(); - } - } finally { - wb.close(); - wb.dispose(); - } - TempFileUtils.checkTempFiles(); - } - - public static void save(final InputStream inputStream, final String filename, final String pwd) - throws InvalidFormatException, IOException, GeneralSecurityException { - POIFSFileSystem fs = null; - FileOutputStream fos = null; - OPCPackage opc = null; - try { - fs = new POIFSFileSystem(); - EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile); - Encryptor enc = Encryptor.getInstance(info); - enc.confirmPassword(pwd); - opc = OPCPackage.open(inputStream); - fos = new FileOutputStream(filename); - opc.save(enc.getDataStream(fs)); - fs.writeFilesystem(fos); - } finally { - IOUtils.closeQuietly(fos); - IOUtils.closeQuietly(opc); - IOUtils.closeQuietly(fs); - IOUtils.closeQuietly(inputStream); - } - } - -} diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/AligningCells.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/AligningCells.java deleted file mode 100644 index 0bb002fb3..000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/AligningCells.java +++ /dev/null @@ -1,140 +0,0 @@ -/* ==================================================================== -Licensed to the Apache Software Foundation (ASF) under one or more -contributor license agreements. See the NOTICE file distributed with -this work for additional information regarding copyright ownership. -The ASF licenses this file to You under the Apache License, Version 2.0 -(the "License"); you may not use this file except in compliance with -the License. You may obtain a copy of the License at - -http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel.examples; - -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.CreationHelper; -import org.apache.poi.ss.usermodel.HorizontalAlignment; -import org.apache.poi.ss.usermodel.VerticalAlignment; -import org.apache.poi.xssf.usermodel.XSSFCell; -import org.apache.poi.xssf.usermodel.XSSFCellStyle; -import org.apache.poi.xssf.usermodel.XSSFRow; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.impl.CTRowImpl; - -/** - * Shows how various alignment options work. - * - * Modified by Cristian Petrula, Romania on May 26, 2010 - * New method was added centerAcrossSelection to center a column content over - * one selection using {@link HorizontalAlignment#CENTER_SELECTION} - * To create this method example was change for XSSF only and the previous - * AligningCells.java example has been moved into the SS examples folder. - */ -public class AligningCells { - - public static void main(String[] args) throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - - XSSFSheet sheet = wb.createSheet(); - XSSFRow row = sheet.createRow(2); - row.setHeightInPoints(30); - for (int i = 0; i < 8; i++) { - //column width is set in units of 1/256th of a character width - sheet.setColumnWidth(i, 256 * 15); - } - - createCell(wb, row, 0, HorizontalAlignment.CENTER, VerticalAlignment.BOTTOM); - createCell(wb, row, 1, HorizontalAlignment.CENTER_SELECTION, VerticalAlignment.BOTTOM); - createCell(wb, row, 2, HorizontalAlignment.FILL, VerticalAlignment.CENTER); - createCell(wb, row, 3, HorizontalAlignment.GENERAL, VerticalAlignment.CENTER); - createCell(wb, row, 4, HorizontalAlignment.JUSTIFY, VerticalAlignment.JUSTIFY); - createCell(wb, row, 5, HorizontalAlignment.LEFT, VerticalAlignment.TOP); - createCell(wb, row, 6, HorizontalAlignment.RIGHT, VerticalAlignment.TOP); - - //center text over B4, C4, D4 - row = sheet.createRow(3); - centerAcrossSelection(wb, row, 1, 3, VerticalAlignment.CENTER); - - // Write the output to a file - OutputStream fileOut = new FileOutputStream("xssf-align.xlsx"); - wb.write(fileOut); - fileOut.close(); - - wb.close(); - } - - /** - * Creates a cell and aligns it a certain way. - * - * @param wb the workbook - * @param row the row to create the cell in - * @param column the column number to create the cell in - * @param halign the horizontal alignment for the cell. - */ - private static void createCell(XSSFWorkbook wb, XSSFRow row, int column, - HorizontalAlignment halign, VerticalAlignment valign) { - CreationHelper ch = wb.getCreationHelper(); - XSSFCell cell = row.createCell(column); - cell.setCellValue(ch.createRichTextString("Align It")); - CellStyle cellStyle = wb.createCellStyle(); - cellStyle.setAlignment(halign); - cellStyle.setVerticalAlignment(valign); - cell.setCellStyle(cellStyle); - } - - /** - * Center a text over multiple columns using ALIGN_CENTER_SELECTION - * - * @param wb the workbook - * @param row the row to create the cell in - * @param start_column the column number to create the cell in and where the selection starts - * @param end_column the column number where the selection ends - * @param valign the horizontal alignment for the cell. - */ - private static void centerAcrossSelection(XSSFWorkbook wb, XSSFRow row, - int start_column, int end_column, VerticalAlignment valign) { - CreationHelper ch = wb.getCreationHelper(); - - // Create cell style with ALIGN_CENTER_SELECTION - XSSFCellStyle cellStyle = wb.createCellStyle(); - cellStyle.setAlignment(HorizontalAlignment.CENTER_SELECTION); - cellStyle.setVerticalAlignment(valign); - - // Create cells over the selected area - for (int i = start_column; i <= end_column; i++) { - XSSFCell cell = row.createCell(i); - cell.setCellStyle(cellStyle); - } - - // Set value to the first cell - XSSFCell cell = row.getCell(start_column); - cell.setCellValue(ch.createRichTextString("Align It")); - - // Make the selection - CTRowImpl ctRow = (CTRowImpl) row.getCTRow(); - - // Add object with format start_coll:end_coll. For example 1:3 will span from - // cell 1 to cell 3, where the column index starts with 0 - // - // You can add multiple spans for one row - Object span = start_column + ":" + end_column; - - List spanList = new ArrayList(); - spanList.add(span); - - //add spns to the row - ctRow.setSpans(spanList); - } -} diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/BigGridDemo.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/BigGridDemo.java deleted file mode 100644 index 66bb59762..000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/BigGridDemo.java +++ /dev/null @@ -1,300 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.examples; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.Writer; -import java.util.Calendar; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Map; -import java.util.Random; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; -import java.util.zip.ZipOutputStream; - -import org.apache.poi.openxml4j.opc.internal.ZipHelper; -import org.apache.poi.ss.usermodel.DateUtil; -import org.apache.poi.ss.usermodel.FillPatternType; -import org.apache.poi.ss.usermodel.HorizontalAlignment; -import org.apache.poi.ss.usermodel.IndexedColors; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.xssf.usermodel.XSSFCellStyle; -import org.apache.poi.xssf.usermodel.XSSFDataFormat; -import org.apache.poi.xssf.usermodel.XSSFFont; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -/** - * Demonstrates a workaround you can use to generate large workbooks and avoid OutOfMemory exception. - * - * Note - You probably don't want to use this approach any more! POI - * now includes the SXSSF which handles all of this for you, you should - * be using that instead! This code remains mostly for historical interest. - *

    - * See - * http://poi.apache.org/spreadsheet/how-to.html#sxssf. - *

    - * If you really want to use this approach, which is also the one that SXSSF - * does for you, it works as follows: - * - * 1. create a template workbook, create sheets and global objects such as cell styles, number formats, etc. - * 2. create an application that streams data in a text file - * 3. Substitute the sheet in the template with the generated data - * - *

    - * Since 3.8 POI provides a low-memory footprint SXSSF API, which implements - * ths "BigGridDemo" strategy. SXSSF is an API-compatible streaming extension - * of XSSF to be used when very large spreadsheets have to be produced, and - * heap space is limited. SXSSF achieves its low memory footprint by limiting - * access to the rows that are within a sliding window, while XSSF gives access - * to all rows in the document. Older rows that are no longer in the window - * become inaccessible, as they are written to the disk. - *

    - * See - * http://poi.apache.org/spreadsheet/how-to.html#sxssf. - - * - * @author Yegor Kozlov - */ -public class BigGridDemo { - private static final String XML_ENCODING = "UTF-8"; - - public static void main(String[] args) throws Exception { - - // Step 1. Create a template file. Setup sheets and workbook-level objects such as - // cell styles, number formats, etc. - - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet("Big Grid"); - - Map styles = createStyles(wb); - //name of the zip entry holding sheet data, e.g. /xl/worksheets/sheet1.xml - String sheetRef = sheet.getPackagePart().getPartName().getName(); - - //save the template - FileOutputStream os = new FileOutputStream("template.xlsx"); - wb.write(os); - os.close(); - - //Step 2. Generate XML file. - File tmp = File.createTempFile("sheet", ".xml"); - Writer fw = new OutputStreamWriter(new FileOutputStream(tmp), XML_ENCODING); - generate(fw, styles); - fw.close(); - - //Step 3. Substitute the template entry with the generated data - FileOutputStream out = new FileOutputStream("big-grid.xlsx"); - substitute(new File("template.xlsx"), tmp, sheetRef.substring(1), out); - out.close(); - - wb.close(); - } - - /** - * Create a library of cell styles. - */ - private static Map createStyles(XSSFWorkbook wb){ - Map styles = new HashMap(); - XSSFDataFormat fmt = wb.createDataFormat(); - - XSSFCellStyle style1 = wb.createCellStyle(); - style1.setAlignment(HorizontalAlignment.RIGHT); - style1.setDataFormat(fmt.getFormat("0.0%")); - styles.put("percent", style1); - - XSSFCellStyle style2 = wb.createCellStyle(); - style2.setAlignment(HorizontalAlignment.CENTER); - style2.setDataFormat(fmt.getFormat("0.0X")); - styles.put("coeff", style2); - - XSSFCellStyle style3 = wb.createCellStyle(); - style3.setAlignment(HorizontalAlignment.RIGHT); - style3.setDataFormat(fmt.getFormat("$#,##0.00")); - styles.put("currency", style3); - - XSSFCellStyle style4 = wb.createCellStyle(); - style4.setAlignment(HorizontalAlignment.RIGHT); - style4.setDataFormat(fmt.getFormat("mmm dd")); - styles.put("date", style4); - - XSSFCellStyle style5 = wb.createCellStyle(); - XSSFFont headerFont = wb.createFont(); - headerFont.setBold(true); - style5.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); - style5.setFillPattern(FillPatternType.SOLID_FOREGROUND); - style5.setFont(headerFont); - styles.put("header", style5); - - return styles; - } - - private static void generate(Writer out, Map styles) throws Exception { - - Random rnd = new Random(); - Calendar calendar = Calendar.getInstance(); - - SpreadsheetWriter sw = new SpreadsheetWriter(out); - sw.beginSheet(); - - //insert header row - sw.insertRow(0); - int styleIndex = styles.get("header").getIndex(); - sw.createCell(0, "Title", styleIndex); - sw.createCell(1, "% Change", styleIndex); - sw.createCell(2, "Ratio", styleIndex); - sw.createCell(3, "Expenses", styleIndex); - sw.createCell(4, "Date", styleIndex); - - sw.endRow(); - - //write data rows - for (int rownum = 1; rownum < 100000; rownum++) { - sw.insertRow(rownum); - - sw.createCell(0, "Hello, " + rownum + "!"); - sw.createCell(1, (double)rnd.nextInt(100)/100, styles.get("percent").getIndex()); - sw.createCell(2, (double)rnd.nextInt(10)/10, styles.get("coeff").getIndex()); - sw.createCell(3, rnd.nextInt(10000), styles.get("currency").getIndex()); - sw.createCell(4, calendar, styles.get("date").getIndex()); - - sw.endRow(); - - calendar.roll(Calendar.DAY_OF_YEAR, 1); - } - sw.endSheet(); - } - - /** - * - * @param zipfile the template file - * @param tmpfile the XML file with the sheet data - * @param entry the name of the sheet entry to substitute, e.g. xl/worksheets/sheet1.xml - * @param out the stream to write the result to - */ - private static void substitute(File zipfile, File tmpfile, String entry, OutputStream out) throws IOException { - ZipFile zip = ZipHelper.openZipFile(zipfile); - try { - ZipOutputStream zos = new ZipOutputStream(out); - - Enumeration en = zip.entries(); - while (en.hasMoreElements()) { - ZipEntry ze = en.nextElement(); - if(!ze.getName().equals(entry)){ - zos.putNextEntry(new ZipEntry(ze.getName())); - InputStream is = zip.getInputStream(ze); - copyStream(is, zos); - is.close(); - } - } - zos.putNextEntry(new ZipEntry(entry)); - InputStream is = new FileInputStream(tmpfile); - copyStream(is, zos); - is.close(); - - zos.close(); - } finally { - zip.close(); - } - } - - private static void copyStream(InputStream in, OutputStream out) throws IOException { - byte[] chunk = new byte[1024]; - int count; - while ((count = in.read(chunk)) >=0 ) { - out.write(chunk,0,count); - } - } - - /** - * Writes spreadsheet data in a Writer. - * (YK: in future it may evolve in a full-featured API for streaming data in Excel) - */ - public static class SpreadsheetWriter { - private final Writer _out; - private int _rownum; - - public SpreadsheetWriter(Writer out){ - _out = out; - } - - public void beginSheet() throws IOException { - _out.write("" + - "" ); - _out.write("\n"); - } - - public void endSheet() throws IOException { - _out.write(""); - _out.write(""); - } - - /** - * Insert a new row - * - * @param rownum 0-based row number - */ - public void insertRow(int rownum) throws IOException { - _out.write("\n"); - this._rownum = rownum; - } - - /** - * Insert row end marker - */ - public void endRow() throws IOException { - _out.write("\n"); - } - - public void createCell(int columnIndex, String value, int styleIndex) throws IOException { - String ref = new CellReference(_rownum, columnIndex).formatAsString(); - _out.write(""); - _out.write(""+value+""); - _out.write(""); - } - - public void createCell(int columnIndex, String value) throws IOException { - createCell(columnIndex, value, -1); - } - - public void createCell(int columnIndex, double value, int styleIndex) throws IOException { - String ref = new CellReference(_rownum, columnIndex).formatAsString(); - _out.write(""); - _out.write(""+value+""); - _out.write(""); - } - - public void createCell(int columnIndex, double value) throws IOException { - createCell(columnIndex, value, -1); - } - - public void createCell(int columnIndex, Calendar value, int styleIndex) throws IOException { - createCell(columnIndex, DateUtil.getExcelDate(value, false), styleIndex); - } - } -} diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/CalendarDemo.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/CalendarDemo.java deleted file mode 100644 index 48e3fd122..000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/CalendarDemo.java +++ /dev/null @@ -1,230 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.examples; - -import org.apache.poi.xssf.usermodel.*; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.usermodel.*; - -import java.io.FileOutputStream; -import java.util.Calendar; -import java.util.Map; -import java.util.HashMap; - -/** - * A monthly calendar created using Apache POI. Each month is on a separate sheet. - * This is a version of org.apache.poi.ss.examples.CalendarDemo that demonstrates - * some XSSF features not avaiable when using common HSSF-XSSF interfaces. - * - *
    - * Usage:
    - * CalendarDemo 
    - * 
    - * - * @author Yegor Kozlov - */ -public class CalendarDemo { - - private static final String[] days = { - "Sunday", "Monday", "Tuesday", - "Wednesday", "Thursday", "Friday", "Saturday"}; - - private static final String[] months = { - "January", "February", "March","April", "May", "June","July", "August", - "September","October", "November", "December"}; - - public static void main(String[] args) throws Exception { - - Calendar calendar = Calendar.getInstance(); - if(args.length > 0) calendar.set(Calendar.YEAR, Integer.parseInt(args[0])); - - int year = calendar.get(Calendar.YEAR); - - XSSFWorkbook wb = new XSSFWorkbook(); - Map styles = createStyles(wb); - - for (int month = 0; month < 12; month++) { - calendar.set(Calendar.MONTH, month); - calendar.set(Calendar.DAY_OF_MONTH, 1); - //create a sheet for each month - XSSFSheet sheet = wb.createSheet(months[month]); - - //turn off gridlines - sheet.setDisplayGridlines(false); - sheet.setPrintGridlines(false); - XSSFPrintSetup printSetup = sheet.getPrintSetup(); - printSetup.setOrientation(PrintOrientation.LANDSCAPE); - sheet.setFitToPage(true); - sheet.setHorizontallyCenter(true); - - //the header row: centered text in 48pt font - XSSFRow headerRow = sheet.createRow(0); - headerRow.setHeightInPoints(80); - XSSFCell titleCell = headerRow.createCell(0); - titleCell.setCellValue(months[month] + " " + year); - titleCell.setCellStyle(styles.get("title")); - sheet.addMergedRegion(CellRangeAddress.valueOf("$A$1:$N$1")); - - //header with month titles - XSSFRow monthRow = sheet.createRow(1); - for (int i = 0; i < days.length; i++) { - //for compatibility with HSSF we have to set column width in units of 1/256th of a character width - sheet.setColumnWidth(i*2, 5*256); //the column is 5 characters wide - sheet.setColumnWidth(i*2 + 1, 13*256); //the column is 13 characters wide - sheet.addMergedRegion(new CellRangeAddress(1, 1, i*2, i*2+1)); - XSSFCell monthCell = monthRow.createCell(i*2); - monthCell.setCellValue(days[i]); - monthCell.setCellStyle(styles.get("month")); - } - - int cnt = 1, day=1; - int rownum = 2; - for (int j = 0; j < 6; j++) { - XSSFRow row = sheet.createRow(rownum++); - row.setHeightInPoints(100); - for (int i = 0; i < days.length; i++) { - XSSFCell dayCell_1 = row.createCell(i*2); - XSSFCell dayCell_2 = row.createCell(i*2 + 1); - - int day_of_week = calendar.get(Calendar.DAY_OF_WEEK); - if(cnt >= day_of_week && calendar.get(Calendar.MONTH) == month) { - dayCell_1.setCellValue(day); - calendar.set(Calendar.DAY_OF_MONTH, ++day); - - if(i == 0 || i == days.length-1) { - dayCell_1.setCellStyle(styles.get("weekend_left")); - dayCell_2.setCellStyle(styles.get("weekend_right")); - } else { - dayCell_1.setCellStyle(styles.get("workday_left")); - dayCell_2.setCellStyle(styles.get("workday_right")); - } - } else { - dayCell_1.setCellStyle(styles.get("grey_left")); - dayCell_2.setCellStyle(styles.get("grey_right")); - } - cnt++; - } - if(calendar.get(Calendar.MONTH) > month) break; - } - } - - // Write the output to a file - FileOutputStream out = new FileOutputStream("calendar-"+year+".xlsx"); - wb.write(out); - out.close(); - - wb.close(); - } - - /** - * cell styles used for formatting calendar sheets - */ - private static Map createStyles(XSSFWorkbook wb){ - Map styles = new HashMap(); - - XSSFCellStyle style; - XSSFFont titleFont = wb.createFont(); - titleFont.setFontHeightInPoints((short)48); - titleFont.setColor(new XSSFColor(new java.awt.Color(39, 51, 89))); - style = wb.createCellStyle(); - style.setAlignment(HorizontalAlignment.CENTER); - style.setVerticalAlignment(VerticalAlignment.CENTER); - style.setFont(titleFont); - styles.put("title", style); - - XSSFFont monthFont = wb.createFont(); - monthFont.setFontHeightInPoints((short)12); - monthFont.setColor(new XSSFColor(new java.awt.Color(255, 255, 255))); - monthFont.setBold(true); - style = wb.createCellStyle(); - style.setAlignment(HorizontalAlignment.CENTER); - style.setVerticalAlignment(VerticalAlignment.CENTER); - style.setFillForegroundColor(new XSSFColor(new java.awt.Color(39, 51, 89))); - style.setFillPattern(FillPatternType.SOLID_FOREGROUND); - style.setFont(monthFont); - styles.put("month", style); - - XSSFFont dayFont = wb.createFont(); - dayFont.setFontHeightInPoints((short)14); - dayFont.setBold(true); - style = wb.createCellStyle(); - style.setAlignment(HorizontalAlignment.LEFT); - style.setVerticalAlignment(VerticalAlignment.TOP); - style.setFillForegroundColor(new XSSFColor(new java.awt.Color(228, 232, 243))); - style.setFillPattern(FillPatternType.SOLID_FOREGROUND); - style.setBorderLeft(BorderStyle.THIN); - style.setLeftBorderColor(new XSSFColor(new java.awt.Color(39, 51, 89))); - style.setBorderBottom(BorderStyle.THIN); - style.setBottomBorderColor(new XSSFColor(new java.awt.Color(39, 51, 89))); - style.setFont(dayFont); - styles.put("weekend_left", style); - - style = wb.createCellStyle(); - style.setAlignment(HorizontalAlignment.CENTER); - style.setVerticalAlignment(VerticalAlignment.TOP); - style.setFillForegroundColor(new XSSFColor(new java.awt.Color(228, 232, 243))); - style.setFillPattern(FillPatternType.SOLID_FOREGROUND); - style.setBorderRight(BorderStyle.THIN); - style.setRightBorderColor(new XSSFColor(new java.awt.Color(39, 51, 89))); - style.setBorderBottom(BorderStyle.THIN); - style.setBottomBorderColor(new XSSFColor(new java.awt.Color(39, 51, 89))); - styles.put("weekend_right", style); - - style = wb.createCellStyle(); - style.setAlignment(HorizontalAlignment.LEFT); - style.setVerticalAlignment(VerticalAlignment.TOP); - style.setBorderLeft(BorderStyle.THIN); - style.setFillForegroundColor(new XSSFColor(new java.awt.Color(255, 255, 255))); - style.setFillPattern(FillPatternType.SOLID_FOREGROUND); - style.setLeftBorderColor(new XSSFColor(new java.awt.Color(39, 51, 89))); - style.setBorderBottom(BorderStyle.THIN); - style.setBottomBorderColor(new XSSFColor(new java.awt.Color(39, 51, 89))); - style.setFont(dayFont); - styles.put("workday_left", style); - - style = wb.createCellStyle(); - style.setAlignment(HorizontalAlignment.CENTER); - style.setVerticalAlignment(VerticalAlignment.TOP); - style.setFillForegroundColor(new XSSFColor(new java.awt.Color(255, 255, 255))); - style.setFillPattern(FillPatternType.SOLID_FOREGROUND); - style.setBorderRight(BorderStyle.THIN); - style.setRightBorderColor(new XSSFColor(new java.awt.Color(39, 51, 89))); - style.setBorderBottom(BorderStyle.THIN); - style.setBottomBorderColor(new XSSFColor(new java.awt.Color(39, 51, 89))); - styles.put("workday_right", style); - - style = wb.createCellStyle(); - style.setBorderLeft(BorderStyle.THIN); - style.setFillForegroundColor(new XSSFColor(new java.awt.Color(234, 234, 234))); - style.setFillPattern(FillPatternType.SOLID_FOREGROUND); - style.setBorderBottom(BorderStyle.THIN); - style.setBottomBorderColor(new XSSFColor(new java.awt.Color(39, 51, 89))); - styles.put("grey_left", style); - - style = wb.createCellStyle(); - style.setFillForegroundColor(new XSSFColor(new java.awt.Color(234, 234, 234))); - style.setFillPattern(FillPatternType.SOLID_FOREGROUND); - style.setBorderRight(BorderStyle.THIN); - style.setRightBorderColor(new XSSFColor(new java.awt.Color(39, 51, 89))); - style.setBorderBottom(BorderStyle.THIN); - style.setBottomBorderColor(new XSSFColor(new java.awt.Color(39, 51, 89))); - styles.put("grey_right", style); - - return styles; - } -} diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/CellComments.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/CellComments.java deleted file mode 100644 index e2eab81f5..000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/CellComments.java +++ /dev/null @@ -1,90 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel.examples; - -import java.io.FileOutputStream; -import java.io.IOException; - -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.ClientAnchor; -import org.apache.poi.ss.usermodel.Comment; -import org.apache.poi.ss.usermodel.CreationHelper; -import org.apache.poi.ss.usermodel.Drawing; -import org.apache.poi.ss.usermodel.Font; -import org.apache.poi.ss.usermodel.IndexedColors; -import org.apache.poi.ss.usermodel.RichTextString; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.CellAddress; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -/** - * Demonstrates how to work with excel cell comments. - * - *

    - * Excel comment is a kind of a text shape, - * so inserting a comment is very similar to placing a text box in a worksheet - *

    - * - * @author Yegor Kozlov - */ -public class CellComments { - public static void main(String[] args) throws IOException { - Workbook wb = new XSSFWorkbook(); - - CreationHelper factory = wb.getCreationHelper(); - - Sheet sheet = wb.createSheet(); - - Cell cell1 = sheet.createRow(3).createCell(5); - cell1.setCellValue("F4"); - - Drawing drawing = sheet.createDrawingPatriarch(); - - ClientAnchor anchor = factory.createClientAnchor(); - - Comment comment1 = drawing.createCellComment(anchor); - RichTextString str1 = factory.createRichTextString("Hello, World!"); - comment1.setString(str1); - comment1.setAuthor("Apache POI"); - cell1.setCellComment(comment1); - - Cell cell2 = sheet.createRow(2).createCell(2); - cell2.setCellValue("C3"); - - Comment comment2 = drawing.createCellComment(anchor); - RichTextString str2 = factory.createRichTextString("XSSF can set cell comments"); - //apply custom font to the text in the comment - Font font = wb.createFont(); - font.setFontName("Arial"); - font.setFontHeightInPoints((short)14); - font.setBold(true); - font.setColor(IndexedColors.RED.getIndex()); - str2.applyFont(font); - - comment2.setString(str2); - comment2.setAuthor("Apache POI"); - comment2.setAddress(new CellAddress("C3")); - - String fname = "comments.xlsx"; - FileOutputStream out = new FileOutputStream(fname); - wb.write(out); - out.close(); - - wb.close(); - } -} diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/CreateCell.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/CreateCell.java deleted file mode 100644 index b84814f1b..000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/CreateCell.java +++ /dev/null @@ -1,89 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.examples; - -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Date; - -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.CreationHelper; -import org.apache.poi.ss.usermodel.Font; -import org.apache.poi.ss.usermodel.RichTextString; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -/** - * Illustrates how to create cell and set values of different types. - */ -public class CreateCell { - - - public static void main(String[]args) throws IOException { - Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); - CreationHelper creationHelper = wb.getCreationHelper(); - Sheet sheet = wb.createSheet("new sheet"); - - // Create a row and put some cells in it. Rows are 0 based. - Row row = sheet.createRow((short)0); - // Create a cell and put a value in it. - Cell cell = row.createCell((short)0); - cell.setCellValue(1); - - //numeric value - row.createCell(1).setCellValue(1.2); - - //plain string value - row.createCell(2).setCellValue("This is a string cell"); - - //rich text string - RichTextString str = creationHelper.createRichTextString("Apache"); - Font font = wb.createFont(); - font.setItalic(true); - font.setUnderline(Font.U_SINGLE); - str.applyFont(font); - row.createCell(3).setCellValue(str); - - //boolean value - row.createCell(4).setCellValue(true); - - //formula - row.createCell(5).setCellFormula("SUM(A1:B1)"); - - //date - CellStyle style = wb.createCellStyle(); - style.setDataFormat(creationHelper.createDataFormat().getFormat("m/d/yy h:mm")); - cell = row.createCell(6); - cell.setCellValue(new Date()); - cell.setCellStyle(style); - - //hyperlink - row.createCell(7).setCellFormula("SUM(A1:B1)"); - cell.setCellFormula("HYPERLINK(\"http://google.com\",\"Google\")"); - - - // Write the output to a file - FileOutputStream fileOut = new FileOutputStream("ooxml-cell.xlsx"); - wb.write(fileOut); - fileOut.close(); - wb.close(); - } -} diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/CreatePivotTable.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/CreatePivotTable.java deleted file mode 100644 index a855feeda..000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/CreatePivotTable.java +++ /dev/null @@ -1,106 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - ==================================================================== */ -package org.apache.poi.xssf.usermodel.examples; - -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; - -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.DataConsolidateFunction; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.util.AreaReference; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.xssf.usermodel.XSSFPivotTable; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -public class CreatePivotTable { - - public static void main(String[] args) throws FileNotFoundException, IOException, InvalidFormatException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet(); - - //Create some data to build the pivot table on - setCellData(sheet); - - AreaReference source = new AreaReference("A1:D4", SpreadsheetVersion.EXCEL2007); - CellReference position = new CellReference("H5"); - // Create a pivot table on this sheet, with H5 as the top-left cell.. - // The pivot table's data source is on the same sheet in A1:D4 - XSSFPivotTable pivotTable = sheet.createPivotTable(source, position); - //Configure the pivot table - //Use first column as row label - pivotTable.addRowLabel(0); - //Sum up the second column - pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 1); - //Set the third column as filter - pivotTable.addColumnLabel(DataConsolidateFunction.AVERAGE, 2); - //Add filter on forth column - pivotTable.addReportFilter(3); - - FileOutputStream fileOut = new FileOutputStream("ooxml-pivottable.xlsx"); - wb.write(fileOut); - fileOut.close(); - wb.close(); - } - - public static void setCellData(XSSFSheet sheet){ - Row row1 = sheet.createRow(0); - // Create a cell and put a value in it. - Cell cell11 = row1.createCell(0); - cell11.setCellValue("Names"); - Cell cell12 = row1.createCell(1); - cell12.setCellValue("#"); - Cell cell13 = row1.createCell(2); - cell13.setCellValue("%"); - Cell cell14 = row1.createCell(3); - cell14.setCellValue("Human"); - - Row row2 = sheet.createRow(1); - Cell cell21 = row2.createCell(0); - cell21.setCellValue("Jane"); - Cell cell22 = row2.createCell(1); - cell22.setCellValue(10); - Cell cell23 = row2.createCell(2); - cell23.setCellValue(100); - Cell cell24 = row2.createCell(3); - cell24.setCellValue("Yes"); - - Row row3 = sheet.createRow(2); - Cell cell31 = row3.createCell(0); - cell31.setCellValue("Tarzan"); - Cell cell32 = row3.createCell(1); - cell32.setCellValue(5); - Cell cell33 = row3.createCell(2); - cell33.setCellValue(90); - Cell cell34 = row3.createCell(3); - cell34.setCellValue("Yes"); - - Row row4 = sheet.createRow(3); - Cell cell41 = row4.createCell(0); - cell41.setCellValue("Terk"); - Cell cell42 = row4.createCell(1); - cell42.setCellValue(10); - Cell cell43 = row4.createCell(2); - cell43.setCellValue(90); - Cell cell44 = row4.createCell(3); - cell44.setCellValue("No"); - } -} diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/CreateTable.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/CreateTable.java deleted file mode 100644 index 056c67fc3..000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/CreateTable.java +++ /dev/null @@ -1,92 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel.examples; - -import java.io.FileOutputStream; -import java.io.IOException; - -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.AreaReference; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.xssf.usermodel.XSSFCell; -import org.apache.poi.xssf.usermodel.XSSFRow; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFTable; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTable; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTableColumn; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTableColumns; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTableStyleInfo; - -/** - * Demonstrates how to create a simple table using Apache POI. - */ -public class CreateTable { - - public static void main(String[] args) throws IOException { - - Workbook wb = new XSSFWorkbook(); - XSSFSheet sheet = (XSSFSheet) wb.createSheet(); - - //Create - XSSFTable table = sheet.createTable(); - table.setDisplayName("Test"); - CTTable cttable = table.getCTTable(); - - //Style configurations - CTTableStyleInfo style = cttable.addNewTableStyleInfo(); - style.setName("TableStyleMedium2"); - style.setShowColumnStripes(false); - style.setShowRowStripes(true); - - //Set which area the table should be placed in - AreaReference reference = new AreaReference(new CellReference(0, 0), - new CellReference(2,2)); - cttable.setRef(reference.formatAsString()); - cttable.setId(1); - cttable.setName("Test"); - cttable.setTotalsRowCount(1); - - CTTableColumns columns = cttable.addNewTableColumns(); - columns.setCount(3); - CTTableColumn column; - XSSFRow row; - XSSFCell cell; - for(int i=0; i<3; i++) { - //Create column - column = columns.addNewTableColumn(); - column.setName("Column"); - column.setId(i+1); - //Create row - row = sheet.createRow(i); - for(int j=0; j<3; j++) { - //Create cell - cell = row.createCell(j); - if(i == 0) { - cell.setCellValue("Column"+j); - } else { - cell.setCellValue("0"); - } - } - } - - FileOutputStream fileOut = new FileOutputStream("ooxml-table.xlsx"); - wb.write(fileOut); - fileOut.close(); - wb.close(); - } -} diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/CreateUserDefinedDataFormats.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/CreateUserDefinedDataFormats.java deleted file mode 100644 index 4ebaa46fc..000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/CreateUserDefinedDataFormats.java +++ /dev/null @@ -1,68 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.examples; - -import java.io.FileOutputStream; -import java.io.IOException; - -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.DataFormat; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -/** - * How to set user-defined date formats - */ -public class CreateUserDefinedDataFormats { - - - public static void main(String[]args) throws IOException { - Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); - Sheet sheet = wb.createSheet("format sheet"); - CellStyle style; - DataFormat format = wb.createDataFormat(); - Row row; - Cell cell; - short rowNum = 0; - short colNum = 0; - - row = sheet.createRow(rowNum); - cell = row.createCell(colNum); - cell.setCellValue(11111.25); - style = wb.createCellStyle(); - style.setDataFormat(format.getFormat("0.0")); - cell.setCellStyle(style); - - row = sheet.createRow(++rowNum); - cell = row.createCell(colNum); - cell.setCellValue(11111.25); - style = wb.createCellStyle(); - style.setDataFormat(format.getFormat("#,##0.0000")); - cell.setCellStyle(style); - - FileOutputStream fileOut = new FileOutputStream("ooxml_dataFormat.xlsx"); - wb.write(fileOut); - fileOut.close(); - - wb.close(); - } - -} diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/CustomXMLMapping.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/CustomXMLMapping.java deleted file mode 100644 index 9fb6409ae..000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/CustomXMLMapping.java +++ /dev/null @@ -1,45 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel.examples; - -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.xssf.extractor.XSSFExportToXml; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.apache.poi.xssf.usermodel.XSSFMap; - -import java.io.ByteArrayOutputStream; - -/** - * Print all custom XML mappings registered in the given workbook - */ -public class CustomXMLMapping { - - public static void main(String[] args) throws Exception { - OPCPackage pkg = OPCPackage.open(args[0]); - XSSFWorkbook wb = new XSSFWorkbook(pkg); - - for (XSSFMap map : wb.getCustomXMLMappings()) { - XSSFExportToXml exporter = new XSSFExportToXml(map); - - ByteArrayOutputStream os = new ByteArrayOutputStream(); - exporter.exportToXML(os, true); - String xml = os.toString("UTF-8"); - System.out.println(xml); - } - pkg.close(); - } -} diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/EmbeddedObjects.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/EmbeddedObjects.java deleted file mode 100644 index 916c2ec50..000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/EmbeddedObjects.java +++ /dev/null @@ -1,67 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel.examples; - -import java.io.Closeable; -import java.io.InputStream; - -import org.apache.poi.hslf.usermodel.HSLFSlideShow; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.hwpf.HWPFDocument; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.xslf.usermodel.XMLSlideShow; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.apache.poi.xwpf.usermodel.XWPFDocument; - -/** - * Demonstrates how you can extract embedded data from a .xlsx file - */ -public class EmbeddedObjects { - public static void main(String[] args) throws Exception { - XSSFWorkbook workbook = new XSSFWorkbook(args[0]); - for (PackagePart pPart : workbook.getAllEmbedds()) { - String contentType = pPart.getContentType(); - InputStream is = pPart.getInputStream(); - Closeable document; - if (contentType.equals("application/vnd.ms-excel")) { - // Excel Workbook - either binary or OpenXML - document = new HSSFWorkbook(is); - } else if (contentType.equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) { - // Excel Workbook - OpenXML file format - document = new XSSFWorkbook(is); - } else if (contentType.equals("application/msword")) { - // Word Document - binary (OLE2CDF) file format - document = new HWPFDocument(is); - } else if (contentType.equals("application/vnd.openxmlformats-officedocument.wordprocessingml.document")) { - // Word Document - OpenXML file format - document = new XWPFDocument(is); - } else if (contentType.equals("application/vnd.ms-powerpoint")) { - // PowerPoint Document - binary file format - document = new HSLFSlideShow(is); - } else if (contentType.equals("application/vnd.openxmlformats-officedocument.presentationml.presentation")) { - // PowerPoint Document - OpenXML file format - document = new XMLSlideShow(is); - } else { - // Any other type of embedded object. - document = is; - } - document.close(); - is.close(); - } - workbook.close(); - } -} \ No newline at end of file diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/FillsAndColors.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/FillsAndColors.java deleted file mode 100644 index e93d997ed..000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/FillsAndColors.java +++ /dev/null @@ -1,65 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel.examples; - -import java.io.FileOutputStream; -import java.io.IOException; - -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.FillPatternType; -import org.apache.poi.ss.usermodel.IndexedColors; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.xssf.usermodel.XSSFRichTextString; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -/** - * Fills and Colors - */ -public class FillsAndColors { - public static void main(String[] args) throws IOException { - Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); - Sheet sheet = wb.createSheet("new sheet"); - - // Create a row and put some cells in it. Rows are 0 based. - Row row = sheet.createRow(1); - - // Aqua background - CellStyle style = wb.createCellStyle(); - style.setFillBackgroundColor(IndexedColors.AQUA.getIndex()); - style.setFillPattern(FillPatternType.BIG_SPOTS); - Cell cell = row.createCell(1); - cell.setCellValue(new XSSFRichTextString("X")); - cell.setCellStyle(style); - - // Orange "foreground", foreground being the fill foreground not the font color. - style = wb.createCellStyle(); - style.setFillForegroundColor(IndexedColors.ORANGE.getIndex()); - style.setFillPattern(FillPatternType.SOLID_FOREGROUND); - cell = row.createCell(2); - cell.setCellValue(new XSSFRichTextString("X")); - cell.setCellStyle(style); - - // Write the output to a file - FileOutputStream fileOut = new FileOutputStream("fill_colors.xlsx"); - wb.write(fileOut); - fileOut.close(); - wb.close(); - } -} diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/FitSheetToOnePage.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/FitSheetToOnePage.java deleted file mode 100644 index a27ebb863..000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/FitSheetToOnePage.java +++ /dev/null @@ -1,46 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel.examples; - -import java.io.FileOutputStream; -import java.io.IOException; - -import org.apache.poi.ss.usermodel.PrintSetup; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -public class FitSheetToOnePage { - - public static void main(String[]args) throws IOException { - Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); - Sheet sheet = wb.createSheet("format sheet"); - PrintSetup ps = sheet.getPrintSetup(); - - sheet.setAutobreaks(true); - - ps.setFitHeight((short) 1); - ps.setFitWidth((short) 1); - - // Create various cells and rows for spreadsheet. - - FileOutputStream fileOut = new FileOutputStream("fitSheetToOnePage.xlsx"); - wb.write(fileOut); - fileOut.close(); - wb.close(); - } -} diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/HeadersAndFooters.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/HeadersAndFooters.java deleted file mode 100644 index 057a87a77..000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/HeadersAndFooters.java +++ /dev/null @@ -1,85 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel.examples; - -import java.io.FileOutputStream; -import java.io.IOException; - -import org.apache.poi.ss.usermodel.Footer; -import org.apache.poi.ss.usermodel.Header; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -public class HeadersAndFooters { - - - public static void main(String[]args) throws IOException { - Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); - Sheet sheet = wb.createSheet("first-header - format sheet"); - sheet.createRow(0).createCell(0).setCellValue(123); - - //set page numbers in the footer - Footer footer = sheet.getFooter(); - //&P == current page number - //&N == page numbers - footer.setRight("Page &P of &N"); - - - Header firstHeader=((XSSFSheet)sheet).getFirstHeader(); - //&F == workbook file name - firstHeader.setLeft("&F ......... first header"); - - for(int i=0;i<100;i=i+10){ - sheet.createRow(i).createCell(0).setCellValue(123); - } - - - XSSFSheet sheet2 = (XSSFSheet)wb.createSheet("odd header-even footer"); - Header oddHeader=sheet2.getOddHeader(); - //&B == bold - //&E == double underline - //&D == date - oddHeader.setCenter("&B &E oddHeader &D "); - - Footer evenFooter=sheet2.getEvenFooter(); - evenFooter.setRight("even footer &P"); - sheet2.createRow(10).createCell(0).setCellValue("Second sheet with an oddHeader and an evenFooter"); - - for(int i=0;i<200;i=i+10){ - sheet2.createRow(i).createCell(0).setCellValue(123); - } - - XSSFSheet sheet3 = (XSSFSheet)wb.createSheet("odd header- odd footer"); - sheet3.createRow(10).createCell(0).setCellValue("Third sheet with oddHeader and oddFooter"); - Header oddH=sheet3.getOddHeader(); - //&C == centered - oddH.setCenter("centered oddHeader"); - oddH.setLeft("left "); - oddH.setRight("right "); - - Footer oddF=sheet3.getOddFooter(); - oddF.setLeft("Page &P"); - oddF.setRight("Pages &N "); - - FileOutputStream fileOut = new FileOutputStream("headerFooter.xlsx"); - wb.write(fileOut); - fileOut.close(); - wb.close(); - } -} diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/HyperlinkExample.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/HyperlinkExample.java deleted file mode 100644 index bd86e7129..000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/HyperlinkExample.java +++ /dev/null @@ -1,98 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel.examples; - -import java.io.FileOutputStream; -import java.io.IOException; - -import org.apache.poi.common.usermodel.HyperlinkType; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.CreationHelper; -import org.apache.poi.ss.usermodel.Font; -import org.apache.poi.ss.usermodel.Hyperlink; -import org.apache.poi.ss.usermodel.IndexedColors; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -/** - * Demonstrates how to create hyperlinks. - */ -public class HyperlinkExample { - - - public static void main(String[]args) throws IOException { - Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); - CreationHelper createHelper = wb.getCreationHelper(); - - //cell style for hyperlinks - //by default hyperlinks are blue and underlined - CellStyle hlink_style = wb.createCellStyle(); - Font hlink_font = wb.createFont(); - hlink_font.setUnderline(Font.U_SINGLE); - hlink_font.setColor(IndexedColors.BLUE.getIndex()); - hlink_style.setFont(hlink_font); - - Cell cell; - Sheet sheet = wb.createSheet("Hyperlinks"); - //URL - cell = sheet.createRow(0).createCell(0); - cell.setCellValue("URL Link"); - - Hyperlink link = createHelper.createHyperlink(HyperlinkType.URL); - link.setAddress("http://poi.apache.org/"); - cell.setHyperlink(link); - cell.setCellStyle(hlink_style); - - //link to a file in the current directory - cell = sheet.createRow(1).createCell(0); - cell.setCellValue("File Link"); - link = createHelper.createHyperlink(HyperlinkType.FILE); - link.setAddress("link1.xls"); - cell.setHyperlink(link); - cell.setCellStyle(hlink_style); - - //e-mail link - cell = sheet.createRow(2).createCell(0); - cell.setCellValue("Email Link"); - link = createHelper.createHyperlink(HyperlinkType.EMAIL); - //note, if subject contains white spaces, make sure they are url-encoded - link.setAddress("mailto:poi@apache.org?subject=Hyperlinks"); - cell.setHyperlink(link); - cell.setCellStyle(hlink_style); - - //link to a place in this workbook - - //create a target sheet and cell - Sheet sheet2 = wb.createSheet("Target Sheet"); - sheet2.createRow(0).createCell(0).setCellValue("Target Cell"); - - cell = sheet.createRow(3).createCell(0); - cell.setCellValue("Worksheet Link"); - Hyperlink link2 = createHelper.createHyperlink(HyperlinkType.DOCUMENT); - link2.setAddress("'Target Sheet'!A1"); - cell.setHyperlink(link2); - cell.setCellStyle(hlink_style); - - FileOutputStream out = new FileOutputStream("hyperinks.xlsx"); - wb.write(out); - out.close(); - - wb.close(); - } -} diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/IterateCells.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/IterateCells.java deleted file mode 100644 index 2ac609a8a..000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/IterateCells.java +++ /dev/null @@ -1,48 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.examples; - -import java.io.FileInputStream; -import java.io.IOException; - -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -/** - * Iterate over rows and cells - */ -public class IterateCells { - - public static void main(String[] args) throws IOException { - Workbook wb = new XSSFWorkbook(new FileInputStream(args[0])); - for (int i = 0; i < wb.getNumberOfSheets(); i++) { - Sheet sheet = wb.getSheetAt(i); - System.out.println(wb.getSheetName(i)); - for (Row row : sheet) { - System.out.println("rownum: " + row.getRowNum()); - for (Cell cell : row) { - System.out.println(cell.toString()); - } - } - } - wb.close(); - } -} diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/LineChart.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/LineChart.java deleted file mode 100644 index 051af64ec..000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/LineChart.java +++ /dev/null @@ -1,93 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel.examples; - -import java.io.FileOutputStream; -import java.io.IOException; - -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Chart; -import org.apache.poi.ss.usermodel.ClientAnchor; -import org.apache.poi.ss.usermodel.Drawing; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.usermodel.charts.AxisCrosses; -import org.apache.poi.ss.usermodel.charts.AxisPosition; -import org.apache.poi.ss.usermodel.charts.ChartAxis; -import org.apache.poi.ss.usermodel.charts.ChartDataSource; -import org.apache.poi.ss.usermodel.charts.ChartLegend; -import org.apache.poi.ss.usermodel.charts.DataSources; -import org.apache.poi.ss.usermodel.charts.LegendPosition; -import org.apache.poi.ss.usermodel.charts.LineChartData; -import org.apache.poi.ss.usermodel.charts.ValueAxis; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -/** - * Line chart example. - */ -public class LineChart { - - public static void main(String[] args) throws IOException { - Workbook wb = new XSSFWorkbook(); - Sheet sheet = wb.createSheet("linechart"); - final int NUM_OF_ROWS = 3; - final int NUM_OF_COLUMNS = 10; - - // Create a row and put some cells in it. Rows are 0 based. - Row row; - Cell cell; - for (int rowIndex = 0; rowIndex < NUM_OF_ROWS; rowIndex++) { - row = sheet.createRow((short) rowIndex); - for (int colIndex = 0; colIndex < NUM_OF_COLUMNS; colIndex++) { - cell = row.createCell((short) colIndex); - cell.setCellValue(colIndex * (rowIndex + 1)); - } - } - - Drawing drawing = sheet.createDrawingPatriarch(); - ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 10, 15); - - Chart chart = drawing.createChart(anchor); - ChartLegend legend = chart.getOrCreateLegend(); - legend.setPosition(LegendPosition.TOP_RIGHT); - - LineChartData data = chart.getChartDataFactory().createLineChartData(); - - // Use a category axis for the bottom axis. - ChartAxis bottomAxis = chart.getChartAxisFactory().createCategoryAxis(AxisPosition.BOTTOM); - ValueAxis leftAxis = chart.getChartAxisFactory().createValueAxis(AxisPosition.LEFT); - leftAxis.setCrosses(AxisCrosses.AUTO_ZERO); - - ChartDataSource xs = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(0, 0, 0, NUM_OF_COLUMNS - 1)); - ChartDataSource ys1 = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(1, 1, 0, NUM_OF_COLUMNS - 1)); - ChartDataSource ys2 = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(2, 2, 0, NUM_OF_COLUMNS - 1)); - - - data.addSeries(xs, ys1); - data.addSeries(xs, ys2); - - chart.plot(data, bottomAxis, leftAxis); - - // Write the output to a file - FileOutputStream fileOut = new FileOutputStream("ooxml-line-chart.xlsx"); - wb.write(fileOut); - fileOut.close(); - wb.close(); - } -} diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/LoadPasswordProtectedXlsx.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/LoadPasswordProtectedXlsx.java deleted file mode 100644 index da6032f86..000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/LoadPasswordProtectedXlsx.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xssf.usermodel.examples; - -import java.io.FileInputStream; -import java.io.InputStream; - -import org.apache.poi.crypt.examples.EncryptionUtils; -import org.apache.poi.examples.util.TempFileUtils; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.poifs.crypt.temp.AesZipFileZipEntrySource; -import org.apache.poi.util.IOUtils; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -/** - * An example that loads a password protected workbook and counts the sheets. - *

      - *
    • The example demonstrates that all temp files are removed. - *
    • AesZipFileZipEntrySource is used to ensure that temp files are encrypted. - *

    - */ -public class LoadPasswordProtectedXlsx { - - public static void main(String[] args) throws Exception { - if(args.length != 2) { - throw new IllegalArgumentException("Expected 2 params: filename and password"); - } - TempFileUtils.checkTempFiles(); - String filename = args[0]; - String password = args[1]; - FileInputStream fis = new FileInputStream(filename); - try { - InputStream unencryptedStream = EncryptionUtils.decrypt(fis, password); - try { - printSheetCount(unencryptedStream); - } finally { - IOUtils.closeQuietly(unencryptedStream); - } - } finally { - IOUtils.closeQuietly(fis); - } - TempFileUtils.checkTempFiles(); - } - - public static void printSheetCount(final InputStream inputStream) throws Exception { - AesZipFileZipEntrySource source = AesZipFileZipEntrySource.createZipEntrySource(inputStream); - try { - OPCPackage pkg = OPCPackage.open(source); - try { - XSSFWorkbook workbook = new XSSFWorkbook(pkg); - try { - System.out.println("sheet count: " + workbook.getNumberOfSheets()); - } finally { - IOUtils.closeQuietly(workbook); - } - } finally { - IOUtils.closeQuietly(pkg); - } - } finally { - IOUtils.closeQuietly(source); - } - } - -} diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/MergingCells.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/MergingCells.java deleted file mode 100644 index b6bca2e8d..000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/MergingCells.java +++ /dev/null @@ -1,51 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.examples; - -import java.io.FileOutputStream; -import java.io.IOException; - -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.xssf.usermodel.XSSFRichTextString; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -/** - * An example of how to merge regions of cells. - */ -public class MergingCells { - public static void main(String[] args) throws IOException { - Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); - Sheet sheet = wb.createSheet("new sheet"); - - Row row = sheet.createRow((short) 1); - Cell cell = row.createCell((short) 1); - cell.setCellValue(new XSSFRichTextString("This is a test of merging")); - - sheet.addMergedRegion(new CellRangeAddress(1, 1, 1, 2)); - - // Write the output to a file - FileOutputStream fileOut = new FileOutputStream("merging_cells.xlsx"); - wb.write(fileOut); - fileOut.close(); - wb.close(); - } -} diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/NewLinesInCells.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/NewLinesInCells.java deleted file mode 100644 index 35d26918c..000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/NewLinesInCells.java +++ /dev/null @@ -1,59 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel.examples; - -import java.io.FileOutputStream; -import java.io.IOException; - -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -/** - * How to use newlines in cells - */ -public class NewLinesInCells { - - public static void main(String[]args) throws IOException { - Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - - Row row = sheet.createRow(2); - Cell cell = row.createCell(2); - cell.setCellValue("Use \n with word wrap on to create a new line"); - - //to enable newlines you need set a cell styles with wrap=true - CellStyle cs = wb.createCellStyle(); - cs.setWrapText(true); - cell.setCellStyle(cs); - - //increase row height to accomodate two lines of text - row.setHeightInPoints((2*sheet.getDefaultRowHeightInPoints())); - - //adjust column width to fit the content - sheet.autoSizeColumn(2); - - FileOutputStream fileOut = new FileOutputStream("ooxml-newlines.xlsx"); - wb.write(fileOut); - fileOut.close(); - wb.close(); - } - -} diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/Outlining.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/Outlining.java deleted file mode 100644 index f859c9eb5..000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/Outlining.java +++ /dev/null @@ -1,84 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.examples; - -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; - -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -public class Outlining { - - public static void main(String[] args) throws IOException { - Outlining o=new Outlining(); - o.groupRowColumn(); - o.collapseExpandRowColumn(); - } - - - private void groupRowColumn() throws IOException { - Workbook wb = new XSSFWorkbook(); - Sheet sheet1 = wb.createSheet("new sheet"); - - sheet1.groupRow( 5, 14 ); - sheet1.groupRow( 7, 14 ); - sheet1.groupRow( 16, 19 ); - - sheet1.groupColumn( (short)4, (short)7 ); - sheet1.groupColumn( (short)9, (short)12 ); - sheet1.groupColumn( (short)10, (short)11 ); - - OutputStream fileOut = new FileOutputStream("outlining.xlsx"); - try { - wb.write(fileOut); - } finally { - fileOut.close(); - wb.close(); - } - } - - private void collapseExpandRowColumn() throws IOException { - Workbook wb2 = new XSSFWorkbook(); - Sheet sheet2 = wb2.createSheet("new sheet"); - sheet2.groupRow( 5, 14 ); - sheet2.groupRow( 7, 14 ); - sheet2.groupRow( 16, 19 ); - - sheet2.groupColumn( (short)4, (short)7 ); - sheet2.groupColumn( (short)9, (short)12 ); - sheet2.groupColumn( (short)10, (short)11 ); - - - sheet2.setRowGroupCollapsed( 7, true ); - //sheet1.setRowGroupCollapsed(7,false); - - sheet2.setColumnGroupCollapsed( (short)4, true ); - sheet2.setColumnGroupCollapsed( (short)4, false ); - - OutputStream fileOut = new FileOutputStream("outlining_collapsed.xlsx"); - try { - wb2.write(fileOut); - } finally { - fileOut.close(); - wb2.close(); - } - } -} diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/ScatterChart.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/ScatterChart.java deleted file mode 100644 index 8b02eba30..000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/ScatterChart.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xssf.usermodel.examples; - -import java.io.FileOutputStream; -import java.io.IOException; - -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Chart; -import org.apache.poi.ss.usermodel.ClientAnchor; -import org.apache.poi.ss.usermodel.Drawing; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.usermodel.charts.AxisCrosses; -import org.apache.poi.ss.usermodel.charts.AxisPosition; -import org.apache.poi.ss.usermodel.charts.ChartDataSource; -import org.apache.poi.ss.usermodel.charts.ChartLegend; -import org.apache.poi.ss.usermodel.charts.DataSources; -import org.apache.poi.ss.usermodel.charts.LegendPosition; -import org.apache.poi.ss.usermodel.charts.ScatterChartData; -import org.apache.poi.ss.usermodel.charts.ValueAxis; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -/** - * Illustrates how to create a simple scatter chart. - */ -public class ScatterChart { - - public static void main(String[] args) throws IOException { - Workbook wb = new XSSFWorkbook(); - Sheet sheet = wb.createSheet("Sheet 1"); - final int NUM_OF_ROWS = 3; - final int NUM_OF_COLUMNS = 10; - - // Create a row and put some cells in it. Rows are 0 based. - Row row; - Cell cell; - for (int rowIndex = 0; rowIndex < NUM_OF_ROWS; rowIndex++) { - row = sheet.createRow((short) rowIndex); - for (int colIndex = 0; colIndex < NUM_OF_COLUMNS; colIndex++) { - cell = row.createCell((short) colIndex); - cell.setCellValue(colIndex * (rowIndex + 1)); - } - } - - Drawing drawing = sheet.createDrawingPatriarch(); - ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 10, 15); - - Chart chart = drawing.createChart(anchor); - ChartLegend legend = chart.getOrCreateLegend(); - legend.setPosition(LegendPosition.TOP_RIGHT); - - ScatterChartData data = chart.getChartDataFactory().createScatterChartData(); - - ValueAxis bottomAxis = chart.getChartAxisFactory().createValueAxis(AxisPosition.BOTTOM); - ValueAxis leftAxis = chart.getChartAxisFactory().createValueAxis(AxisPosition.LEFT); - leftAxis.setCrosses(AxisCrosses.AUTO_ZERO); - - ChartDataSource xs = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(0, 0, 0, NUM_OF_COLUMNS - 1)); - ChartDataSource ys1 = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(1, 1, 0, NUM_OF_COLUMNS - 1)); - ChartDataSource ys2 = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(2, 2, 0, NUM_OF_COLUMNS - 1)); - - - data.addSerie(xs, ys1); - data.addSerie(xs, ys2); - - chart.plot(data, bottomAxis, leftAxis); - - // Write the output to a file - FileOutputStream fileOut = new FileOutputStream("ooxml-scatter-chart.xlsx"); - wb.write(fileOut); - fileOut.close(); - wb.close(); - } -} diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/SelectedSheet.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/SelectedSheet.java deleted file mode 100644 index 43a6b4847..000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/SelectedSheet.java +++ /dev/null @@ -1,46 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel.examples; - -import java.io.FileOutputStream; -import java.io.IOException; - -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -public abstract class SelectedSheet { - - public static void main(String[]args) throws IOException { - Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); - - wb.createSheet("row sheet"); - wb.createSheet("another sheet"); - Sheet sheet3 = wb.createSheet(" sheet 3 "); - sheet3.setSelected(true); - wb.setActiveSheet(2); - - // Create various cells and rows for spreadsheet. - - FileOutputStream fileOut = new FileOutputStream("selectedSheet.xlsx"); - wb.write(fileOut); - fileOut.close(); - - wb.close(); - } - -} diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/ShiftRows.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/ShiftRows.java deleted file mode 100644 index 5f70b6ab9..000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/ShiftRows.java +++ /dev/null @@ -1,62 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.examples; - -import java.io.FileOutputStream; -import java.io.IOException; - -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -/** - * How to shift rows up or down - */ -public class ShiftRows { - - public static void main(String[]args) throws IOException { - Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); - Sheet sheet = wb.createSheet("Sheet1"); - - Row row1 = sheet.createRow(1); - row1.createCell(0).setCellValue(1); - - Row row2 = sheet.createRow(4); - row2.createCell(1).setCellValue(2); - - Row row3 = sheet.createRow(5); - row3.createCell(2).setCellValue(3); - - Row row4 = sheet.createRow(6); - row4.createCell(3).setCellValue(4); - - Row row5 = sheet.createRow(9); - row5.createCell(4).setCellValue(5); - - // Shift rows 6 - 11 on the spreadsheet to the top (rows 0 - 5) - sheet.shiftRows(5, 10, -4); - - FileOutputStream fileOut = new FileOutputStream("shiftRows.xlsx"); - wb.write(fileOut); - fileOut.close(); - wb.close(); - } - - -} diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/SplitAndFreezePanes.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/SplitAndFreezePanes.java deleted file mode 100644 index 4ea6ea370..000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/SplitAndFreezePanes.java +++ /dev/null @@ -1,52 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.examples; - -import java.io.FileOutputStream; -import java.io.IOException; - -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -/** - * How to set split and freeze panes - */ -public class SplitAndFreezePanes { - public static void main(String[]args) throws IOException { - Workbook wb = new XSSFWorkbook(); - Sheet sheet1 = wb.createSheet("new sheet"); - Sheet sheet2 = wb.createSheet("second sheet"); - Sheet sheet3 = wb.createSheet("third sheet"); - Sheet sheet4 = wb.createSheet("fourth sheet"); - - // Freeze just one row - sheet1.createFreezePane(0, 1, 0, 1); - // Freeze just one column - sheet2.createFreezePane(1, 0, 1, 0); - // Freeze the columns and rows (forget about scrolling position of the lower right quadrant). - sheet3.createFreezePane(2, 2); - // Create a split with the lower left side being the active quadrant - sheet4.createSplitPane(2000, 2000, 0, 0, Sheet.PANE_LOWER_LEFT); - - FileOutputStream fileOut = new FileOutputStream("splitFreezePane.xlsx"); - wb.write(fileOut); - fileOut.close(); - wb.close(); - } -} diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/WorkbookProperties.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/WorkbookProperties.java deleted file mode 100644 index 5911caa6c..000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/WorkbookProperties.java +++ /dev/null @@ -1,65 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.examples; - -import java.io.FileOutputStream; -import java.io.IOException; - -import org.apache.poi.POIXMLProperties; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -/** - * How to set extended and custom properties - */ -public class WorkbookProperties { - - public static void main(String[]args) throws IOException { - - XSSFWorkbook workbook = new XSSFWorkbook(); - workbook.createSheet("Workbook Properties"); - - POIXMLProperties props = workbook.getProperties(); - - /** - * Extended properties are a predefined set of metadata properties - * that are specifically applicable to Office Open XML documents. - * Extended properties consist of 24 simple properties and 3 complex properties stored in the - * part targeted by the relationship of type - */ - POIXMLProperties.ExtendedProperties ext = props.getExtendedProperties(); - ext.getUnderlyingProperties().setCompany("Apache Software Foundation"); - ext.getUnderlyingProperties().setTemplate("XSSF"); - - /** - * Custom properties enable users to define custom metadata properties. - */ - - POIXMLProperties.CustomProperties cust = props.getCustomProperties(); - cust.addProperty("Author", "John Smith"); - cust.addProperty("Year", 2009); - cust.addProperty("Price", 45.50); - cust.addProperty("Available", true); - - FileOutputStream out = new FileOutputStream("workbook.xlsx"); - workbook.write(out); - out.close(); - workbook.close(); - } - - -} \ No newline at end of file diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/WorkingWithBorders.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/WorkingWithBorders.java deleted file mode 100644 index 32b233ce7..000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/WorkingWithBorders.java +++ /dev/null @@ -1,65 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.examples; - -import java.io.FileOutputStream; -import java.io.IOException; - -import org.apache.poi.ss.usermodel.BorderStyle; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.IndexedColors; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -/** - * Working with borders - */ -public class WorkingWithBorders { - public static void main(String[] args) throws IOException { - Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); - Sheet sheet = wb.createSheet("borders"); - - // Create a row and put some cells in it. Rows are 0 based. - Row row = sheet.createRow((short) 1); - - // Create a cell and put a value in it. - Cell cell = row.createCell((short) 1); - cell.setCellValue(4); - - // Style the cell with borders all around. - CellStyle style = wb.createCellStyle(); - style.setBorderBottom(BorderStyle.THIN); - style.setBottomBorderColor(IndexedColors.BLACK.getIndex()); - style.setBorderLeft(BorderStyle.THIN); - style.setLeftBorderColor(IndexedColors.GREEN.getIndex()); - style.setBorderRight(BorderStyle.THIN); - style.setRightBorderColor(IndexedColors.BLUE.getIndex()); - style.setBorderTop(BorderStyle.MEDIUM_DASHED); - style.setTopBorderColor(IndexedColors.BLACK.getIndex()); - cell.setCellStyle(style); - - // Write the output to a file - FileOutputStream fileOut = new FileOutputStream("xssf-borders.xlsx"); - wb.write(fileOut); - fileOut.close(); - wb.close(); - } -} diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/WorkingWithFonts.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/WorkingWithFonts.java deleted file mode 100644 index 993067484..000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/WorkingWithFonts.java +++ /dev/null @@ -1,107 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.examples; - -import java.io.FileOutputStream; -import java.io.IOException; - -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.Font; -import org.apache.poi.ss.usermodel.IndexedColors; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -/** - * Working with Fonts - */ -public class WorkingWithFonts { - public static void main(String[] args) throws IOException { - Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); - Sheet sheet = wb.createSheet("Fonts"); - - Font font0 = wb.createFont(); - font0.setColor(IndexedColors.BROWN.getIndex()); - CellStyle style0 = wb.createCellStyle(); - style0.setFont(font0); - - Font font1 = wb.createFont(); - font1.setFontHeightInPoints((short)14); - font1.setFontName("Courier New"); - font1.setColor(IndexedColors.RED.getIndex()); - CellStyle style1 = wb.createCellStyle(); - style1.setFont(font1); - - Font font2 = wb.createFont(); - font2.setFontHeightInPoints((short)16); - font2.setFontName("Arial"); - font2.setColor(IndexedColors.GREEN.getIndex()); - CellStyle style2 = wb.createCellStyle(); - style2.setFont(font2); - - Font font3 = wb.createFont(); - font3.setFontHeightInPoints((short)18); - font3.setFontName("Times New Roman"); - font3.setColor(IndexedColors.LAVENDER.getIndex()); - CellStyle style3 = wb.createCellStyle(); - style3.setFont(font3); - - Font font4 = wb.createFont(); - font4.setFontHeightInPoints((short)18); - font4.setFontName("Wingdings"); - font4.setColor(IndexedColors.GOLD.getIndex()); - CellStyle style4 = wb.createCellStyle(); - style4.setFont(font4); - - Font font5 = wb.createFont(); - font5.setFontName("Symbol"); - CellStyle style5 = wb.createCellStyle(); - style5.setFont(font5); - - Cell cell0 = sheet.createRow(0).createCell(1); - cell0.setCellValue("Default"); - cell0.setCellStyle(style0); - - Cell cell1 = sheet.createRow(1).createCell(1); - cell1.setCellValue("Courier"); - cell1.setCellStyle(style1); - - Cell cell2 = sheet.createRow(2).createCell(1); - cell2.setCellValue("Arial"); - cell2.setCellStyle(style2); - - Cell cell3 = sheet.createRow(3).createCell(1); - cell3.setCellValue("Times New Roman"); - cell3.setCellStyle(style3); - - Cell cell4 = sheet.createRow(4).createCell(1); - cell4.setCellValue("Wingdings"); - cell4.setCellStyle(style4); - - Cell cell5 = sheet.createRow(5).createCell(1); - cell5.setCellValue("Symbol"); - cell5.setCellStyle(style5); - - // Write the output to a file - FileOutputStream fileOut = new FileOutputStream("xssf-fonts.xlsx"); - wb.write(fileOut); - fileOut.close(); - wb.close(); - } -} diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/WorkingWithPageSetup.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/WorkingWithPageSetup.java deleted file mode 100644 index 25f994f95..000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/WorkingWithPageSetup.java +++ /dev/null @@ -1,83 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel.examples; - -import java.io.FileOutputStream; - -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -/** - * Demonstrates various settings avaiable in the Page Setup dialog - */ -public class WorkingWithPageSetup { - - public static void main(String[]args) throws Exception { - Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); - - /** - * It's possible to set up repeating rows and columns in your printouts by using the setRepeatingRowsAndColumns() function in the Workbook object. - * - * This function Contains 5 parameters: - * The first parameter is the index to the sheet (0 = first sheet). - * The second and third parameters specify the range for the columns to repreat. - * To stop the columns from repeating pass in -1 as the start and end column. - * The fourth and fifth parameters specify the range for the rows to repeat. - * To stop the columns from repeating pass in -1 as the start and end rows. - */ - Sheet sheet1 = wb.createSheet("new sheet"); - Sheet sheet2 = wb.createSheet("second sheet"); - - // Set the columns to repeat from column 0 to 2 on the first sheet - Row row1 = sheet1.createRow(0); - row1.createCell(0).setCellValue(1); - row1.createCell(1).setCellValue(2); - row1.createCell(2).setCellValue(3); - Row row2 = sheet1.createRow(1); - row2.createCell(1).setCellValue(4); - row2.createCell(2).setCellValue(5); - - - Row row3 = sheet2.createRow(1); - row3.createCell(0).setCellValue(2.1); - row3.createCell(4).setCellValue(2.2); - row3.createCell(5).setCellValue(2.3); - Row row4 = sheet2.createRow(2); - row4.createCell(4).setCellValue(2.4); - row4.createCell(5).setCellValue(2.5); - - // Set the columns to repeat from column 0 to 2 on the first sheet - sheet1.setRepeatingColumns(CellRangeAddress.valueOf("A:C")); - // Set the the repeating rows and columns on the second sheet. - CellRangeAddress cra = CellRangeAddress.valueOf("E2:F3"); - sheet2.setRepeatingColumns(cra); - sheet2.setRepeatingRows(cra); - - //set the print area for the first sheet - wb.setPrintArea(0, 1, 2, 0, 3); - - - FileOutputStream fileOut = new FileOutputStream("xssf-printsetup.xlsx"); - wb.write(fileOut); - fileOut.close(); - - wb.close(); - } -} diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/WorkingWithPictures.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/WorkingWithPictures.java deleted file mode 100644 index 34735b7c8..000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/WorkingWithPictures.java +++ /dev/null @@ -1,83 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.examples; - -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import org.apache.poi.ss.usermodel.ClientAnchor; -import org.apache.poi.ss.usermodel.CreationHelper; -import org.apache.poi.ss.usermodel.Drawing; -import org.apache.poi.ss.usermodel.Picture; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.util.IOUtils; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -/** - * Demonstrates how to insert pictures in a SpreadsheetML document - */ -public class WorkingWithPictures { - public static void main(String[] args) throws IOException { - - //create a new workbook - Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); - try { - CreationHelper helper = wb.getCreationHelper(); - - //add a picture in this workbook. - InputStream is = new FileInputStream(args[0]); - byte[] bytes = IOUtils.toByteArray(is); - is.close(); - int pictureIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG); - - //create sheet - Sheet sheet = wb.createSheet(); - - //create drawing - Drawing drawing = sheet.createDrawingPatriarch(); - - //add a picture shape - ClientAnchor anchor = helper.createClientAnchor(); - anchor.setCol1(1); - anchor.setRow1(1); - Picture pict = drawing.createPicture(anchor, pictureIdx); - - //auto-size picture - pict.resize(2); - - //save workbook - String file = "picture.xls"; - if(wb instanceof XSSFWorkbook) - { - file += "x"; // NOSONAR - } - OutputStream fileOut = new FileOutputStream(file); - try { - wb.write(fileOut); - } finally { - fileOut.close(); - } - } finally { - wb.close(); - } - } -} diff --git a/src/examples/src/org/apache/poi/xssf/usermodel/examples/WorkingWithRichText.java b/src/examples/src/org/apache/poi/xssf/usermodel/examples/WorkingWithRichText.java deleted file mode 100644 index f982ea528..000000000 --- a/src/examples/src/org/apache/poi/xssf/usermodel/examples/WorkingWithRichText.java +++ /dev/null @@ -1,68 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.examples; - -import org.apache.poi.xssf.usermodel.*; - -import java.io.FileOutputStream; -import java.io.OutputStream; - -/** - * Demonstrates how to work with rich text - */ -public class WorkingWithRichText { - - public static void main(String[] args) throws Exception { - - XSSFWorkbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); - try { - XSSFSheet sheet = wb.createSheet(); - XSSFRow row = sheet.createRow(2); - - XSSFCell cell = row.createCell(1); - XSSFRichTextString rt = new XSSFRichTextString("The quick brown fox"); - - XSSFFont font1 = wb.createFont(); - font1.setBold(true); - font1.setColor(new XSSFColor(new java.awt.Color(255, 0, 0))); - rt.applyFont(0, 10, font1); - - XSSFFont font2 = wb.createFont(); - font2.setItalic(true); - font2.setUnderline(XSSFFont.U_DOUBLE); - font2.setColor(new XSSFColor(new java.awt.Color(0, 255, 0))); - rt.applyFont(10, 19, font2); - - XSSFFont font3 = wb.createFont(); - font3.setColor(new XSSFColor(new java.awt.Color(0, 0, 255))); - rt.append(" Jumped over the lazy dog", font3); - - cell.setCellValue(rt); - - // Write the output to a file - OutputStream fileOut = new FileOutputStream("xssf-richtext.xlsx"); - try { - wb.write(fileOut); - } finally { - fileOut.close(); - } - } finally { - wb.close(); - } - } -} diff --git a/src/examples/src/org/apache/poi/xwpf/usermodel/examples/BetterHeaderFooterExample.java b/src/examples/src/org/apache/poi/xwpf/usermodel/examples/BetterHeaderFooterExample.java deleted file mode 100644 index d40c4ed0c..000000000 --- a/src/examples/src/org/apache/poi/xwpf/usermodel/examples/BetterHeaderFooterExample.java +++ /dev/null @@ -1,56 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel.examples; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; - -import org.apache.poi.wp.usermodel.HeaderFooterType; -import org.apache.poi.xwpf.usermodel.XWPFDocument; -import org.apache.poi.xwpf.usermodel.XWPFFooter; -import org.apache.poi.xwpf.usermodel.XWPFHeader; -import org.apache.poi.xwpf.usermodel.XWPFParagraph; -import org.apache.poi.xwpf.usermodel.XWPFRun; - -public class BetterHeaderFooterExample { - - public static void main(String[] args) throws IOException { - XWPFDocument doc = new XWPFDocument(); - - XWPFParagraph p = doc.createParagraph(); - - XWPFRun r = p.createRun(); - r.setText("Some Text"); - r.setBold(true); - r = p.createRun(); - r.setText("Goodbye"); - - // create header/footer functions insert an empty paragraph - XWPFHeader head = doc.createHeader(HeaderFooterType.DEFAULT); - head.createParagraph().createRun().setText("header"); - - XWPFFooter foot = doc.createFooter(HeaderFooterType.DEFAULT); - foot.createParagraph().createRun().setText("footer"); - - OutputStream os = new FileOutputStream(new File("header2.docx")); - doc.write(os); - os.close(); - doc.close(); - } -} diff --git a/src/examples/src/org/apache/poi/xwpf/usermodel/examples/HeaderFooterTable.java b/src/examples/src/org/apache/poi/xwpf/usermodel/examples/HeaderFooterTable.java deleted file mode 100644 index a2b9103a4..000000000 --- a/src/examples/src/org/apache/poi/xwpf/usermodel/examples/HeaderFooterTable.java +++ /dev/null @@ -1,105 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel.examples; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.math.BigInteger; - -import org.apache.poi.wp.usermodel.HeaderFooterType; -import org.apache.poi.xwpf.usermodel.XWPFDocument; -import org.apache.poi.xwpf.usermodel.XWPFFooter; -import org.apache.poi.xwpf.usermodel.XWPFHeader; -import org.apache.poi.xwpf.usermodel.XWPFParagraph; -import org.apache.poi.xwpf.usermodel.XWPFRun; -import org.apache.poi.xwpf.usermodel.XWPFTable; -import org.apache.poi.xwpf.usermodel.XWPFTableCell; -import org.apache.poi.xwpf.usermodel.XWPFTableRow; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblGrid; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblGridCol; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblLayoutType; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblPr; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTblLayoutType; - -public class HeaderFooterTable { - - public static void main(String[] args) throws IOException { - XWPFDocument doc = new XWPFDocument(); - - // Create a header with a 1 row, 3 column table - // changes made for issue 57366 allow a new header or footer - // to be created empty. This is a change. You will have to add - // either a paragraph or a table to the header or footer for - // the document to be considered valid. - XWPFHeader hdr = doc.createHeader(HeaderFooterType.DEFAULT); - XWPFTable tbl = hdr.createTable(1, 3); - - // Set the padding around text in the cells to 1/10th of an inch - int pad = (int) (.1 * 1440); - tbl.setCellMargins(pad, pad, pad, pad); - - // Set table width to 6.5 inches in 1440ths of a point - tbl.setWidth((int)(6.5 * 1440)); - // Can not yet set table or cell width properly, tables default to - // autofit layout, and this requires fixed layout - CTTbl ctTbl = tbl.getCTTbl(); - CTTblPr ctTblPr = ctTbl.addNewTblPr(); - CTTblLayoutType layoutType = ctTblPr.addNewTblLayout(); - layoutType.setType(STTblLayoutType.FIXED); - - // Now set up a grid for the table, cells will fit into the grid - // Each cell width is 3120 in 1440ths of an inch, or 1/3rd of 6.5" - BigInteger w = new BigInteger("3120"); - CTTblGrid grid = ctTbl.addNewTblGrid(); - for (int i = 0; i < 3; i++) { - CTTblGridCol gridCol = grid.addNewGridCol(); - gridCol.setW(w); - } - - // Add paragraphs to the cells - XWPFTableRow row = tbl.getRow(0); - XWPFTableCell cell = row.getCell(0); - XWPFParagraph p = cell.getParagraphArray(0); - XWPFRun r = p.createRun(); - r.setText("header left cell"); - - cell = row.getCell(1); - p = cell.getParagraphArray(0); - r = p.createRun(); - r.setText("header center cell"); - - cell = row.getCell(2); - p = cell.getParagraphArray(0); - r = p.createRun(); - r.setText("header right cell"); - - // Create a footer with a Paragraph - XWPFFooter ftr = doc.createFooter(HeaderFooterType.DEFAULT); - p = ftr.createParagraph(); - - r = p.createRun(); - r.setText("footer text"); - - OutputStream os = new FileOutputStream(new File("headertable.docx")); - doc.write(os); - doc.close(); - } - -} diff --git a/src/examples/src/org/apache/poi/xwpf/usermodel/examples/SimpleDocument.java b/src/examples/src/org/apache/poi/xwpf/usermodel/examples/SimpleDocument.java deleted file mode 100644 index 28433c4ed..000000000 --- a/src/examples/src/org/apache/poi/xwpf/usermodel/examples/SimpleDocument.java +++ /dev/null @@ -1,130 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel.examples; - -import java.io.FileOutputStream; - -import org.apache.poi.xwpf.usermodel.Borders; -import org.apache.poi.xwpf.usermodel.BreakClear; -import org.apache.poi.xwpf.usermodel.BreakType; -import org.apache.poi.xwpf.usermodel.LineSpacingRule; -import org.apache.poi.xwpf.usermodel.ParagraphAlignment; -import org.apache.poi.xwpf.usermodel.TextAlignment; -import org.apache.poi.xwpf.usermodel.UnderlinePatterns; -import org.apache.poi.xwpf.usermodel.VerticalAlign; -import org.apache.poi.xwpf.usermodel.XWPFDocument; -import org.apache.poi.xwpf.usermodel.XWPFParagraph; -import org.apache.poi.xwpf.usermodel.XWPFRun; - -/** - * A simple WOrdprocessingML document created by POI XWPF API - */ -public class SimpleDocument { - - public static void main(String[] args) throws Exception { - XWPFDocument doc = new XWPFDocument(); - - XWPFParagraph p1 = doc.createParagraph(); - p1.setAlignment(ParagraphAlignment.CENTER); - p1.setBorderBottom(Borders.DOUBLE); - p1.setBorderTop(Borders.DOUBLE); - - p1.setBorderRight(Borders.DOUBLE); - p1.setBorderLeft(Borders.DOUBLE); - p1.setBorderBetween(Borders.SINGLE); - - p1.setVerticalAlignment(TextAlignment.TOP); - - XWPFRun r1 = p1.createRun(); - r1.setBold(true); - r1.setText("The quick brown fox"); - r1.setBold(true); - r1.setFontFamily("Courier"); - r1.setUnderline(UnderlinePatterns.DOT_DOT_DASH); - r1.setTextPosition(100); - - XWPFParagraph p2 = doc.createParagraph(); - p2.setAlignment(ParagraphAlignment.RIGHT); - - //BORDERS - p2.setBorderBottom(Borders.DOUBLE); - p2.setBorderTop(Borders.DOUBLE); - p2.setBorderRight(Borders.DOUBLE); - p2.setBorderLeft(Borders.DOUBLE); - p2.setBorderBetween(Borders.SINGLE); - - XWPFRun r2 = p2.createRun(); - r2.setText("jumped over the lazy dog"); - r2.setStrikeThrough(true); - r2.setFontSize(20); - - XWPFRun r3 = p2.createRun(); - r3.setText("and went away"); - r3.setStrikeThrough(true); - r3.setFontSize(20); - r3.setSubscript(VerticalAlign.SUPERSCRIPT); - - - XWPFParagraph p3 = doc.createParagraph(); - p3.setWordWrapped(true); - p3.setPageBreak(true); - - //p3.setAlignment(ParagraphAlignment.DISTRIBUTE); - p3.setAlignment(ParagraphAlignment.BOTH); - p3.setSpacingBetween(15, LineSpacingRule.EXACT); - - p3.setIndentationFirstLine(600); - - - XWPFRun r4 = p3.createRun(); - r4.setTextPosition(20); - r4.setText("To be, or not to be: that is the question: " - + "Whether 'tis nobler in the mind to suffer " - + "The slings and arrows of outrageous fortune, " - + "Or to take arms against a sea of troubles, " - + "And by opposing end them? To die: to sleep; "); - r4.addBreak(BreakType.PAGE); - r4.setText("No more; and by a sleep to say we end " - + "The heart-ache and the thousand natural shocks " - + "That flesh is heir to, 'tis a consummation " - + "Devoutly to be wish'd. To die, to sleep; " - + "To sleep: perchance to dream: ay, there's the rub; " - + "......."); - r4.setItalic(true); -//This would imply that this break shall be treated as a simple line break, and break the line after that word: - - XWPFRun r5 = p3.createRun(); - r5.setTextPosition(-10); - r5.setText("For in that sleep of death what dreams may come"); - r5.addCarriageReturn(); - r5.setText("When we have shuffled off this mortal coil," - + "Must give us pause: there's the respect" - + "That makes calamity of so long life;"); - r5.addBreak(); - r5.setText("For who would bear the whips and scorns of time," - + "The oppressor's wrong, the proud man's contumely,"); - - r5.addBreak(BreakClear.ALL); - r5.setText("The pangs of despised love, the law's delay," - + "The insolence of office and the spurns" + "......."); - - FileOutputStream out = new FileOutputStream("simple.docx"); - doc.write(out); - out.close(); - doc.close(); - } -} diff --git a/src/examples/src/org/apache/poi/xwpf/usermodel/examples/SimpleDocumentWithHeader.java b/src/examples/src/org/apache/poi/xwpf/usermodel/examples/SimpleDocumentWithHeader.java deleted file mode 100644 index a798ebd43..000000000 --- a/src/examples/src/org/apache/poi/xwpf/usermodel/examples/SimpleDocumentWithHeader.java +++ /dev/null @@ -1,76 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel.examples; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; - -import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy; -import org.apache.poi.xwpf.usermodel.XWPFDocument; -import org.apache.poi.xwpf.usermodel.XWPFParagraph; -import org.apache.poi.xwpf.usermodel.XWPFRun; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTText; - -/** - * - * @author Richard Ngo - * - */ -public class SimpleDocumentWithHeader { - - private static XWPFParagraph[] pars; - - public static void main(String[] args) { - XWPFDocument doc = new XWPFDocument(); - - XWPFParagraph p = doc.createParagraph(); - - XWPFRun r = p.createRun(); - r.setText("Some Text"); - r.setBold(true); - r = p.createRun(); - r.setText("Goodbye"); - - CTP ctP = CTP.Factory.newInstance(); - CTText t = ctP.addNewR().addNewT(); - t.setStringValue("header"); - pars = new XWPFParagraph[1]; - p = new XWPFParagraph(ctP, doc); - pars[0] = p; - - XWPFHeaderFooterPolicy hfPolicy = doc.createHeaderFooterPolicy(); - hfPolicy.createHeader(XWPFHeaderFooterPolicy.DEFAULT, pars); - - ctP = CTP.Factory.newInstance(); - t = ctP.addNewR().addNewT(); - t.setStringValue("My Footer"); - pars[0] = new XWPFParagraph(ctP, doc); - hfPolicy.createFooter(XWPFHeaderFooterPolicy.DEFAULT, pars); - - try { - OutputStream os = new FileOutputStream(new File("header.docx")); - doc.write(os); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - } -} \ No newline at end of file diff --git a/src/examples/src/org/apache/poi/xwpf/usermodel/examples/SimpleImages.java b/src/examples/src/org/apache/poi/xwpf/usermodel/examples/SimpleImages.java deleted file mode 100644 index 638cf91b1..000000000 --- a/src/examples/src/org/apache/poi/xwpf/usermodel/examples/SimpleImages.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -package org.apache.poi.xwpf.usermodel.examples; - -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; - -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.util.Units; -import org.apache.poi.xwpf.usermodel.BreakType; -import org.apache.poi.xwpf.usermodel.XWPFDocument; -import org.apache.poi.xwpf.usermodel.XWPFParagraph; -import org.apache.poi.xwpf.usermodel.XWPFRun; - -/** - * Demonstrates how to add pictures in a .docx document - */ -public class SimpleImages { - - public static void main(String[] args) throws IOException, InvalidFormatException { - XWPFDocument doc = new XWPFDocument(); - XWPFParagraph p = doc.createParagraph(); - - XWPFRun r = p.createRun(); - - for(String imgFile : args) { - int format; - - if(imgFile.endsWith(".emf")) format = XWPFDocument.PICTURE_TYPE_EMF; - else if(imgFile.endsWith(".wmf")) format = XWPFDocument.PICTURE_TYPE_WMF; - else if(imgFile.endsWith(".pict")) format = XWPFDocument.PICTURE_TYPE_PICT; - else if(imgFile.endsWith(".jpeg") || imgFile.endsWith(".jpg")) format = XWPFDocument.PICTURE_TYPE_JPEG; - else if(imgFile.endsWith(".png")) format = XWPFDocument.PICTURE_TYPE_PNG; - else if(imgFile.endsWith(".dib")) format = XWPFDocument.PICTURE_TYPE_DIB; - else if(imgFile.endsWith(".gif")) format = XWPFDocument.PICTURE_TYPE_GIF; - else if(imgFile.endsWith(".tiff")) format = XWPFDocument.PICTURE_TYPE_TIFF; - else if(imgFile.endsWith(".eps")) format = XWPFDocument.PICTURE_TYPE_EPS; - else if(imgFile.endsWith(".bmp")) format = XWPFDocument.PICTURE_TYPE_BMP; - else if(imgFile.endsWith(".wpg")) format = XWPFDocument.PICTURE_TYPE_WPG; - else { - System.err.println("Unsupported picture: " + imgFile + - ". Expected emf|wmf|pict|jpeg|png|dib|gif|tiff|eps|bmp|wpg"); - continue; - } - - r.setText(imgFile); - r.addBreak(); - r.addPicture(new FileInputStream(imgFile), format, imgFile, Units.toEMU(200), Units.toEMU(200)); // 200x200 pixels - r.addBreak(BreakType.PAGE); - } - - FileOutputStream out = new FileOutputStream("images.docx"); - doc.write(out); - out.close(); - doc.close(); - } - - -} diff --git a/src/examples/src/org/apache/poi/xwpf/usermodel/examples/SimpleTable.java b/src/examples/src/org/apache/poi/xwpf/usermodel/examples/SimpleTable.java deleted file mode 100644 index a3857ff2e..000000000 --- a/src/examples/src/org/apache/poi/xwpf/usermodel/examples/SimpleTable.java +++ /dev/null @@ -1,214 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel.examples; - -import java.io.FileOutputStream; -import java.io.OutputStream; -import java.math.BigInteger; -import java.util.List; - -import org.apache.poi.xwpf.usermodel.ParagraphAlignment; -import org.apache.poi.xwpf.usermodel.UnderlinePatterns; -import org.apache.poi.xwpf.usermodel.XWPFDocument; -import org.apache.poi.xwpf.usermodel.XWPFParagraph; -import org.apache.poi.xwpf.usermodel.XWPFRun; -import org.apache.poi.xwpf.usermodel.XWPFTable; -import org.apache.poi.xwpf.usermodel.XWPFTableCell; -import org.apache.poi.xwpf.usermodel.XWPFTableRow; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTHeight; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTShd; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTString; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblPr; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTcPr; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTrPr; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTVerticalJc; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STShd; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STVerticalJc; - -/** - * This program creates a simple WordprocessingML table using POI XWPF API, and - * a more complex, styled table using both XWPF and ooxml-schema. It's possible - * that not all referenced wordprocessingml classes are defined in - * poi-ooxml-schemas-3.8-beta4. If this is the case, you'll need to use the full - * ooxml-schemas.jar library. - * - * @author gisella bronzetti (original) - * @author Gregg Morris (styled table) - */ -public class SimpleTable { - - public static void main(String[] args) throws Exception { - try { - createSimpleTable(); - } - catch(Exception e) { - System.out.println("Error trying to create simple table."); - throw(e); - } - try { - createStyledTable(); - } - catch(Exception e) { - System.out.println("Error trying to create styled table."); - throw(e); - } - } - - public static void createSimpleTable() throws Exception { - XWPFDocument doc = new XWPFDocument(); - - try { - XWPFTable table = doc.createTable(3, 3); - - table.getRow(1).getCell(1).setText("EXAMPLE OF TABLE"); - - // table cells have a list of paragraphs; there is an initial - // paragraph created when the cell is created. If you create a - // paragraph in the document to put in the cell, it will also - // appear in the document following the table, which is probably - // not the desired result. - XWPFParagraph p1 = table.getRow(0).getCell(0).getParagraphs().get(0); - - XWPFRun r1 = p1.createRun(); - r1.setBold(true); - r1.setText("The quick brown fox"); - r1.setItalic(true); - r1.setFontFamily("Courier"); - r1.setUnderline(UnderlinePatterns.DOT_DOT_DASH); - r1.setTextPosition(100); - - table.getRow(2).getCell(2).setText("only text"); - - OutputStream out = new FileOutputStream("simpleTable.docx"); - try { - doc.write(out); - } finally { - out.close(); - } - } finally { - doc.close(); - } - } - - /** - * Create a table with some row and column styling. I "manually" add the - * style name to the table, but don't check to see if the style actually - * exists in the document. Since I'm creating it from scratch, it obviously - * won't exist. When opened in MS Word, the table style becomes "Normal". - * I manually set alternating row colors. This could be done using Themes, - * but that's left as an exercise for the reader. The cells in the last - * column of the table have 10pt. "Courier" font. - * I make no claims that this is the "right" way to do it, but it worked - * for me. Given the scarcity of XWPF examples, I thought this may prove - * instructive and give you ideas for your own solutions. - - * @throws Exception - */ - public static void createStyledTable() throws Exception { - // Create a new document from scratch - XWPFDocument doc = new XWPFDocument(); - - try { - // -- OR -- - // open an existing empty document with styles already defined - //XWPFDocument doc = new XWPFDocument(new FileInputStream("base_document.docx")); - - // Create a new table with 6 rows and 3 columns - int nRows = 6; - int nCols = 3; - XWPFTable table = doc.createTable(nRows, nCols); - - // Set the table style. If the style is not defined, the table style - // will become "Normal". - CTTblPr tblPr = table.getCTTbl().getTblPr(); - CTString styleStr = tblPr.addNewTblStyle(); - styleStr.setVal("StyledTable"); - - // Get a list of the rows in the table - List rows = table.getRows(); - int rowCt = 0; - int colCt = 0; - for (XWPFTableRow row : rows) { - // get table row properties (trPr) - CTTrPr trPr = row.getCtRow().addNewTrPr(); - // set row height; units = twentieth of a point, 360 = 0.25" - CTHeight ht = trPr.addNewTrHeight(); - ht.setVal(BigInteger.valueOf(360)); - - // get the cells in this row - List cells = row.getTableCells(); - // add content to each cell - for (XWPFTableCell cell : cells) { - // get a table cell properties element (tcPr) - CTTcPr tcpr = cell.getCTTc().addNewTcPr(); - // set vertical alignment to "center" - CTVerticalJc va = tcpr.addNewVAlign(); - va.setVal(STVerticalJc.CENTER); - - // create cell color element - CTShd ctshd = tcpr.addNewShd(); - ctshd.setColor("auto"); - ctshd.setVal(STShd.CLEAR); - if (rowCt == 0) { - // header row - ctshd.setFill("A7BFDE"); - } else if (rowCt % 2 == 0) { - // even row - ctshd.setFill("D3DFEE"); - } else { - // odd row - ctshd.setFill("EDF2F8"); - } - - // get 1st paragraph in cell's paragraph list - XWPFParagraph para = cell.getParagraphs().get(0); - // create a run to contain the content - XWPFRun rh = para.createRun(); - // style cell as desired - if (colCt == nCols - 1) { - // last column is 10pt Courier - rh.setFontSize(10); - rh.setFontFamily("Courier"); - } - if (rowCt == 0) { - // header row - rh.setText("header row, col " + colCt); - rh.setBold(true); - para.setAlignment(ParagraphAlignment.CENTER); - } else { - // other rows - rh.setText("row " + rowCt + ", col " + colCt); - para.setAlignment(ParagraphAlignment.LEFT); - } - colCt++; - } // for cell - colCt = 0; - rowCt++; - } // for row - - // write the file - OutputStream out = new FileOutputStream("styledTable.docx"); - try { - doc.write(out); - } finally { - out.close(); - } - } finally { - doc.close(); - } - } -} diff --git a/src/examples/src/org/apache/poi/xwpf/usermodel/examples/UpdateEmbeddedDoc.java b/src/examples/src/org/apache/poi/xwpf/usermodel/examples/UpdateEmbeddedDoc.java deleted file mode 100644 index 251b4568f..000000000 --- a/src/examples/src/org/apache/poi/xwpf/usermodel/examples/UpdateEmbeddedDoc.java +++ /dev/null @@ -1,201 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xwpf.usermodel.examples; - -import static org.junit.Assert.assertEquals; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.List; - -import org.apache.poi.openxml4j.exceptions.OpenXML4JException; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.usermodel.WorkbookFactory; -import org.apache.poi.util.IOUtils; -import org.apache.poi.xwpf.usermodel.XWPFDocument; - -/** - * Tests whether it is possible to successfully update an Excel workbook that is - * embedded into a WordprocessingML document. Note that the test has currently - * only been conducted with a binary Excel workbook and NOT yet with a - * SpreadsheetML workbook embedded into the document.

    - * - * This code was successfully tested with the following file from the POI test collection: - * http://svn.apache.org/repos/asf/poi/trunk/test-data/document/EmbeddedDocument.docx - */ -public class UpdateEmbeddedDoc { - - private XWPFDocument doc = null; - private File docFile = null; - - private static final int SHEET_NUM = 0; - private static final int ROW_NUM = 0; - private static final int CELL_NUM = 0; - private static final double NEW_VALUE = 100.98D; - private static final String BINARY_EXTENSION = "xls"; - private static final String OPENXML_EXTENSION = "xlsx"; - - /** - * Create a new instance of the UpdateEmbeddedDoc class using the following - * parameters; - * - * @param filename An instance of the String class that encapsulates the name - * of and path to a WordprocessingML Word document that contains an - * embedded binary Excel workbook. - * @throws java.io.FileNotFoundException Thrown if the file cannot be found - * on the underlying file system. - * @throws java.io.IOException Thrown if a problem occurs in the underlying - * file system. - */ - public UpdateEmbeddedDoc(String filename) throws FileNotFoundException, IOException { - this.docFile = new File(filename); - FileInputStream fis = null; - if (!this.docFile.exists()) { - throw new FileNotFoundException("The Word dcoument " + filename + " does not exist."); - } - try { - // Open the Word document file and instantiate the XWPFDocument - // class. - fis = new FileInputStream(this.docFile); - this.doc = new XWPFDocument(fis); - } finally { - IOUtils.closeQuietly(fis); - } - } - - /** - * Called to update the embedded Excel workbook. As the format and structire - * of the workbook are known in advance, all this code attempts to do is - * write a new value into the first cell on the first row of the first - * worksheet. Prior to executing this method, that cell will contain the - * value 1. - * - * @throws org.apache.poi.openxml4j.exceptions.OpenXML4JException - * Rather - * than use the specific classes (HSSF/XSSF) to handle the embedded - * workbook this method uses those defeined in the SS stream. As - * a result, it might be the case that a SpreadsheetML file is - * opened for processing, throwing this exception if that file is - * invalid. - * @throws java.io.IOException Thrown if a problem occurs in the underlying - * file system. - */ - public void updateEmbeddedDoc() throws OpenXML4JException, IOException { - List embeddedDocs = this.doc.getAllEmbedds(); - for (PackagePart pPart : embeddedDocs) { - String ext = pPart.getPartName().getExtension(); - if (BINARY_EXTENSION.equals(ext) || OPENXML_EXTENSION.equals(ext)) { - // Get an InputStream from the package part and pass that - // to the create method of the WorkbookFactory class. Update - // the resulting Workbook and then stream that out again - // using an OutputStream obtained from the same PackagePart. - InputStream is = pPart.getInputStream(); - Workbook workbook = null; - OutputStream os = null; - try { - workbook = WorkbookFactory.create(is); - Sheet sheet = workbook.getSheetAt(SHEET_NUM); - Row row = sheet.getRow(ROW_NUM); - Cell cell = row.getCell(CELL_NUM); - cell.setCellValue(NEW_VALUE); - os = pPart.getOutputStream(); - workbook.write(os); - } finally { - IOUtils.closeQuietly(os); - IOUtils.closeQuietly(workbook); - IOUtils.closeQuietly(is); - } - } - } - - if (!embeddedDocs.isEmpty()) { - // Finally, write the newly modified Word document out to file. - FileOutputStream fos = new FileOutputStream(this.docFile); - this.doc.write(fos); - fos.close(); - } - } - - /** - * Called to test whether or not the embedded workbook was correctly - * updated. This method simply recovers the first cell from the first row - * of the first workbook and tests the value it contains. - *

    - * Note that execution will not continue up to the assertion as the - * embedded workbook is now corrupted and causes an IllegalArgumentException - * with the following message - *

    - * java.lang.IllegalArgumentException: Your InputStream was neither an - * OLE2 stream, nor an OOXML stream - *

    - * to be thrown when the WorkbookFactory.createWorkbook(InputStream) method - * is executed. - * - * @throws org.apache.poi.openxml4j.exceptions.OpenXML4JException - * Rather - * than use the specific classes (HSSF/XSSF) to handle the embedded - * workbook this method uses those defeined in the SS stream. As - * a result, it might be the case that a SpreadsheetML file is - * opened for processing, throwing this exception if that file is - * invalid. - * @throws java.io.IOException Thrown if a problem occurs in the underlying - * file system. - */ - public void checkUpdatedDoc() throws OpenXML4JException, IOException { - for (PackagePart pPart : this.doc.getAllEmbedds()) { - String ext = pPart.getPartName().getExtension(); - if (BINARY_EXTENSION.equals(ext) || OPENXML_EXTENSION.equals(ext)) { - InputStream is = pPart.getInputStream(); - Workbook workbook = null; - try { - workbook = WorkbookFactory.create(is); - Sheet sheet = workbook.getSheetAt(SHEET_NUM); - Row row = sheet.getRow(ROW_NUM); - Cell cell = row.getCell(CELL_NUM); - assertEquals(cell.getNumericCellValue(), NEW_VALUE, 0.0001); - } finally { - IOUtils.closeQuietly(workbook); - IOUtils.closeQuietly(is); - } - } - } - } - - /** - * Code to test updating of the embedded Excel workbook. - * - * @param args - * @throws OpenXML4JException - */ - public static void main(String[] args) throws IOException, OpenXML4JException { - UpdateEmbeddedDoc ued = new UpdateEmbeddedDoc(args[0]); - ued.updateEmbeddedDoc(); - ued.checkUpdatedDoc(); - } -} diff --git a/src/excelant/java/org/apache/poi/ss/excelant/ExcelAntEvaluateCell.java b/src/excelant/java/org/apache/poi/ss/excelant/ExcelAntEvaluateCell.java deleted file mode 100644 index bf1334848..000000000 --- a/src/excelant/java/org/apache/poi/ss/excelant/ExcelAntEvaluateCell.java +++ /dev/null @@ -1,145 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.excelant; - -import org.apache.poi.ss.excelant.util.ExcelAntEvaluationResult; -import org.apache.poi.ss.excelant.util.ExcelAntWorkbookUtil; -import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.Project; -import org.apache.tools.ant.Task; - -/** - * Instances of this class are used to evaluate a single cell. This is usually - * after some values have been set. The evaluation is actually performed - * by a WorkbookUtil instance. The evaluate() method of the WorkbookUtil - * class returns an EvaluationResult which encapsulates the results and - * information from the evaluation. - * - * @author Jon Svede ( jon [at] loquatic [dot] com ) - * @author Brian Bush ( brian [dot] bush [at] nrel [dot] gov ) - - * - */ -public class ExcelAntEvaluateCell extends Task { - - private String cell ; - private double expectedValue ; - private double precision ; - private double precisionToUse ; - private double globalPrecision ; - private boolean requiredToPass = false ; - - - private ExcelAntEvaluationResult result ; - - private ExcelAntWorkbookUtil wbUtil ; - - private boolean showDelta = false ; - - - public ExcelAntEvaluateCell() {} - - protected void setWorkbookUtil( ExcelAntWorkbookUtil wb ) { - wbUtil = wb ; - } - - public void setShowDelta( boolean value ) { - showDelta = value ; - } - - protected boolean showDelta() { - return showDelta ; - } - - public void setCell(String cell) { - this.cell = cell; - } - - public void setRequiredToPass( boolean val ) { - requiredToPass = val ; - } - - protected boolean requiredToPass() { - return requiredToPass ; - } - - public void setExpectedValue(double expectedValue) { - this.expectedValue = expectedValue; - } - - public void setPrecision(double precision) { - this.precision = precision; - } - - protected void setGlobalPrecision( double prec ) { - globalPrecision = prec ; - } - - protected String getCell() { - return cell; - } - - protected double getExpectedValue() { - return expectedValue; - } - - protected double getPrecision() { - return precisionToUse; - } - - @Override - public void execute() throws BuildException { - - precisionToUse = 0 ; - - // if there is a globalPrecision we will use it unless there is also - // precision set at the evaluate level, then we use that. If there - // is not a globalPrecision, we will use the local precision. - log( "test precision = " + precision + "\tglobal precision = " + globalPrecision, Project.MSG_VERBOSE ) ; - if( globalPrecision > 0 ) { - if( precision > 0 ) { - precisionToUse = precision ; - log( "Using evaluate precision of " + precision + " over the " + - "global precision of " + globalPrecision, Project.MSG_VERBOSE ) ; - } else { - precisionToUse = globalPrecision ; - log( "Using global precision of " + globalPrecision, Project.MSG_VERBOSE ) ; - } - } else { - precisionToUse = precision ; - log( "Using evaluate precision of " + precision, Project.MSG_VERBOSE ) ; - } - result = wbUtil.evaluateCell(cell, expectedValue, precisionToUse ) ; - - StringBuilder sb = new StringBuilder() ; - sb.append( "evaluation of cell " ) ; - sb.append( cell ) ; - sb.append( " resulted in " ) ; - sb.append( result.getReturnValue() ) ; - if(showDelta) { - sb.append(" with a delta of ").append(result.getDelta()); - } - - log( sb.toString(), Project.MSG_DEBUG) ; - - } - - public ExcelAntEvaluationResult getResult() { - return result ; - } -} diff --git a/src/excelant/java/org/apache/poi/ss/excelant/ExcelAntHandlerTask.java b/src/excelant/java/org/apache/poi/ss/excelant/ExcelAntHandlerTask.java deleted file mode 100644 index c6baee4f2..000000000 --- a/src/excelant/java/org/apache/poi/ss/excelant/ExcelAntHandlerTask.java +++ /dev/null @@ -1,76 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.excelant; - -import org.apache.poi.ss.excelant.util.ExcelAntWorkbookUtil; -import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.Project; -import org.apache.tools.ant.Task; - -/** - * This is the class that backs the tag in the Ant task. - *

    - * Its purpose is to provide a way to manipulate a workbook in the course - * of an ExcelAnt task. The idea being to model a way for test writers to - * simulate the behaviors of the workbook. - *

    - * Suppose, for example, you have a workbook that has a worksheet that - * reacts to values entered or selected by the user. It's possible in - * Excel to change other cells based on this but this isn't easily possible - * in POI. In ExcelAnt we handle this using the Handler, which is a Java - * class you write to manipulate the workbook. - *

    - * In order to use this tag you must write a class that implements the - * IExcelAntWorkbookHandler interface. After writing the - * class you should package it and it's dependencies into a jar file to - * add as library in your Ant build file. - * - * @author Jon Svede ( jon [at] loquatic [dot] com ) - * @author Brian Bush ( brian [dot] bush [at] nrel [dot] gov ) - * - */ -public class ExcelAntHandlerTask extends Task { - - private String className ; - - private ExcelAntWorkbookUtil wbUtil ; - - public void setClassName( String cName ) { - className = cName ; - } - - protected void setEAWorkbookUtil( ExcelAntWorkbookUtil wkbkUtil ) { - wbUtil = wkbkUtil ; - } - - @Override - public void execute() throws BuildException { - log( "handling the workbook with class " + className, Project.MSG_INFO ) ; - try { - Class clazz = Class.forName( className ) ; - Object handlerObj = clazz.newInstance() ; - if( handlerObj instanceof IExcelAntWorkbookHandler ) { - IExcelAntWorkbookHandler iHandler = (IExcelAntWorkbookHandler)handlerObj ; - iHandler.setWorkbook( wbUtil.getWorkbook() ) ; - iHandler.execute() ; - } - } catch( Exception e ) { - throw new BuildException( e.getMessage(), e ) ; - } - } - } diff --git a/src/excelant/java/org/apache/poi/ss/excelant/ExcelAntPrecision.java b/src/excelant/java/org/apache/poi/ss/excelant/ExcelAntPrecision.java deleted file mode 100644 index 0739ef583..000000000 --- a/src/excelant/java/org/apache/poi/ss/excelant/ExcelAntPrecision.java +++ /dev/null @@ -1,39 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.excelant; - -import org.apache.tools.ant.taskdefs.Typedef; - -/** - * - * @author Jon Svede ( jon [at] loquatic [dot] com ) - * @author Brian Bush ( brian [dot] bush [at] nrel [dot] gov ) - * - */ -public class ExcelAntPrecision extends Typedef { - - private double value ; - - public void setValue( double precision ) { - value = precision ; - } - - public double getValue() { - return value ; - } -} diff --git a/src/excelant/java/org/apache/poi/ss/excelant/ExcelAntSet.java b/src/excelant/java/org/apache/poi/ss/excelant/ExcelAntSet.java deleted file mode 100644 index e62f0623d..000000000 --- a/src/excelant/java/org/apache/poi/ss/excelant/ExcelAntSet.java +++ /dev/null @@ -1,48 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.excelant; - -import org.apache.poi.ss.excelant.util.ExcelAntWorkbookUtil; -import org.apache.tools.ant.Task; - -/** - * - * @author Jon Svede ( jon [at] loquatic [dot] com ) - * @author Brian Bush ( brian [dot] bush [at] nrel [dot] gov ) - * - */ -public abstract class ExcelAntSet extends Task { - - protected String cellStr ; - - protected ExcelAntWorkbookUtil wbUtil ; - - public void setCell( String cellName ) { - cellStr = cellName ; - } - - public String getCell() { - return cellStr ; - } - - - public void setWorkbookUtil( ExcelAntWorkbookUtil wb ) { - wbUtil = wb ; - } - -} diff --git a/src/excelant/java/org/apache/poi/ss/excelant/ExcelAntSetDoubleCell.java b/src/excelant/java/org/apache/poi/ss/excelant/ExcelAntSetDoubleCell.java deleted file mode 100644 index 2451a61e6..000000000 --- a/src/excelant/java/org/apache/poi/ss/excelant/ExcelAntSetDoubleCell.java +++ /dev/null @@ -1,59 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.excelant; - -import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.Project; - -/** - * Class for use in an Ant build script that sets the value of an Excel - * sheet cell using the cell id ('Sheet Name'!cellId). - * - * @author Jon Svede ( jon [at] loquatic [dot] com ) - * @author Brian Bush ( brian [dot] bush [at] nrel [dot] gov ) - * - */ -public class ExcelAntSetDoubleCell extends ExcelAntSet { - private double cellValue; - - public ExcelAntSetDoubleCell() {} - - /** - * Set the value of the specified cell as the double passed in. - * @param value The double-value that should be set when this task is executed. - */ - public void setValue( double value ) { - cellValue = value ; - } - - /** - * Return the cell value as a double. - * @return The double-value of the cell as populated via setValue(), null - * if the value was not set yet. - */ - public double getCellValue() { - return cellValue; - } - - @Override - public void execute() throws BuildException { - wbUtil.setDoubleValue(cellStr, cellValue ) ; - - log( "set cell " + cellStr + " to value " + cellValue + " as double.", Project.MSG_DEBUG ) ; - } -} diff --git a/src/excelant/java/org/apache/poi/ss/excelant/ExcelAntSetFormulaCell.java b/src/excelant/java/org/apache/poi/ss/excelant/ExcelAntSetFormulaCell.java deleted file mode 100644 index 8dc599b10..000000000 --- a/src/excelant/java/org/apache/poi/ss/excelant/ExcelAntSetFormulaCell.java +++ /dev/null @@ -1,53 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.excelant; - -import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.Project; - -/** - * Class for use in an Ant build script that sets the formula of an Excel - * sheet cell using the cell id ('Sheet Name'!cellId). - * - * @author Jon Svede ( jon [at] loquatic [dot] com ) - * @author Brian Bush ( brian [dot] bush [at] nrel [dot] gov ) - * - */ -public class ExcelAntSetFormulaCell extends ExcelAntSet { - - - private String cellValue ; - - public ExcelAntSetFormulaCell() {} - - public void setValue( String value ) { - cellValue = value ; - } - - protected String getCellValue() { - return cellValue; - } - - @Override - public void execute() throws BuildException { - - wbUtil.setFormulaValue( cellStr, cellValue ) ; - - log( "set cell " + cellStr + " to formula " + cellValue, Project.MSG_DEBUG ) ; - } -} diff --git a/src/excelant/java/org/apache/poi/ss/excelant/ExcelAntSetStringCell.java b/src/excelant/java/org/apache/poi/ss/excelant/ExcelAntSetStringCell.java deleted file mode 100644 index e1ab047fb..000000000 --- a/src/excelant/java/org/apache/poi/ss/excelant/ExcelAntSetStringCell.java +++ /dev/null @@ -1,59 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.excelant; - -import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.Project; - -/** - * Class for use in an Ant build script that sets the value of an Excel - * sheet cell using the cell id ('Sheet Name'!cellId). - * - * @author Jon Svede ( jon [at] loquatic [dot] com ) - * @author Brian Bush ( brian [dot] bush [at] nrel [dot] gov ) - * - */ -public class ExcelAntSetStringCell extends ExcelAntSet { - private String stringValue ; - - public ExcelAntSetStringCell() {} - - /** - * Set the value of the cell to the String passed in. - * @param value The string-value that should be set when this task is executed. - */ - public void setValue(String value ) { - stringValue = value ; - } - - /** - * Return the value that will be set into the cell. - * @return The string-value of the cell as populated via setValue(), null - * if the value was not set yet. - */ - public String getCellValue() { - return stringValue; - } - - @Override - public void execute() throws BuildException { - wbUtil.setStringValue(cellStr, stringValue ) ; - - log( "set cell " + cellStr + " to value " + stringValue + " as String.", Project.MSG_DEBUG ) ; - } -} diff --git a/src/excelant/java/org/apache/poi/ss/excelant/ExcelAntTask.java b/src/excelant/java/org/apache/poi/ss/excelant/ExcelAntTask.java deleted file mode 100644 index e9bb072e5..000000000 --- a/src/excelant/java/org/apache/poi/ss/excelant/ExcelAntTask.java +++ /dev/null @@ -1,155 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.excelant; - -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.LinkedList; -import java.util.Locale; - -import org.apache.poi.ss.excelant.util.ExcelAntWorkbookUtil; -import org.apache.poi.ss.excelant.util.ExcelAntWorkbookUtilFactory; -import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.Project; -import org.apache.tools.ant.Task; - -/** - * Ant task class for testing Excel workbook cells. - */ -public class ExcelAntTask extends Task { - - public static final String VERSION = "0.5.0" ; - - private String excelFileName ; - - private boolean failOnError = false ; - - private ExcelAntWorkbookUtil workbookUtil ; - - private ExcelAntPrecision precision ; - - private LinkedList tests ; - private LinkedList functions ; - - public ExcelAntTask() { - tests = new LinkedList() ; - functions = new LinkedList() ; - } - - public void addPrecision( ExcelAntPrecision prec ) { - precision = prec ; - } - - public void setFailOnError( boolean value ) { - failOnError = value ; - } - public void setFileName( String fileName ) { - excelFileName = fileName ; - } - - public void addTest( ExcelAntTest testElement ) { - tests.add( testElement ) ; - } - - public void addUdf( ExcelAntUserDefinedFunction def ) { - functions.add( def ) ; - } - - @Override - public void execute() throws BuildException { - checkClassPath(); - - int totalCount = 0 ; - int successCount = 0 ; - - StringBuilder versionBffr = new StringBuilder() ; - versionBffr.append( "ExcelAnt version " ) ; - versionBffr.append( VERSION ) ; - versionBffr.append( " Copyright 2011" ) ; - SimpleDateFormat sdf = new SimpleDateFormat( "yyyy", Locale.ROOT ) ; - double currYear = Double.parseDouble( sdf.format( new Date() ) ); - if( currYear > 2011 ) { - versionBffr.append( "-" ) ; - versionBffr.append( currYear ) ; - } - log( versionBffr.toString(), Project.MSG_INFO ) ; - - log( "Using input file: " + excelFileName, Project.MSG_INFO ) ; - - workbookUtil = ExcelAntWorkbookUtilFactory.getInstance(excelFileName); - - for (ExcelAntTest test : tests) { - log("executing test: " + test.getName(), Project.MSG_DEBUG); - - if (workbookUtil == null) { - workbookUtil = ExcelAntWorkbookUtilFactory.getInstance(excelFileName); - } - - for (ExcelAntUserDefinedFunction eaUdf : functions) { - try { - workbookUtil.addFunction(eaUdf.getFunctionAlias(), eaUdf.getClassName()); - } catch (Exception e) { - throw new BuildException(e.getMessage(), e); - } - } - test.setWorkbookUtil(workbookUtil); - - if (precision != null && precision.getValue() > 0) { - log("setting precision for the test " + test.getName(), Project.MSG_VERBOSE); - test.setPrecision(precision.getValue()); - } - - test.execute(); - - if (test.didTestPass()) { - successCount++; - } else { - if (failOnError) { - throw new BuildException("Test " + test.getName() + " failed."); - } - } - totalCount++; - - workbookUtil = null; - } - - if( !tests.isEmpty() ) { - log( successCount + "/" + totalCount + " tests passed.", Project.MSG_INFO ); - } - workbookUtil = null; - } - - - /** - * ExcelAnt depends on external libraries not included in the Ant distribution. - * Give user a sensible message if any if the required jars are missing. - */ - private void checkClassPath(){ - try { - Class.forName("org.apache.poi.hssf.usermodel.HSSFWorkbook"); - Class.forName("org.apache.poi.ss.usermodel.WorkbookFactory"); - } catch (Exception e) { - throw new BuildException( - "The for must include poi.jar and poi-ooxml.jar " + - "if not in Ant's own classpath. Processing .xlsx spreadsheets requires " + - "additional poi-ooxml-schemas.jar, xmlbeans.jar" , - e, getLocation()); - } - - } -} diff --git a/src/excelant/java/org/apache/poi/ss/excelant/ExcelAntTest.java b/src/excelant/java/org/apache/poi/ss/excelant/ExcelAntTest.java deleted file mode 100644 index fd8f93091..000000000 --- a/src/excelant/java/org/apache/poi/ss/excelant/ExcelAntTest.java +++ /dev/null @@ -1,221 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.excelant; - -import java.util.Iterator; -import java.util.LinkedList; - -import org.apache.poi.ss.excelant.util.ExcelAntEvaluationResult; -import org.apache.poi.ss.excelant.util.ExcelAntWorkbookUtil; -import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.Project; -import org.apache.tools.ant.Task; - -/** - * This class represents a single test. In order for the test any and all - * ExcelAntEvaluateCell evaluations must pass. Therefore it is recommended - * that you use only 1 evaluator but you can use more if you choose. - * - * @author Jon Svede ( jon [at] loquatic [dot] com ) - * @author Brian Bush ( brian [dot] bush [at] nrel [dot] gov ) - * - */ -public class ExcelAntTest extends Task{ - private LinkedList evaluators; - - private LinkedList testTasks; - - private String name; - - private double globalPrecision; - - private boolean showSuccessDetails = false; - - private boolean showFailureDetail = false; - LinkedList failureMessages; - - - private ExcelAntWorkbookUtil workbookUtil; - - private boolean passed = true; - - - public ExcelAntTest() { - evaluators = new LinkedList(); - failureMessages = new LinkedList(); - testTasks = new LinkedList(); - } - - public void setPrecision( double precision ) { - globalPrecision = precision; - } - - public void setWorkbookUtil( ExcelAntWorkbookUtil wbUtil ) { - workbookUtil = wbUtil; - } - - - public void setShowFailureDetail( boolean value ) { - showFailureDetail = value; - } - - public void setName( String nm ) { - name = nm; - } - - public String getName() { - return name; - } - - public void setShowSuccessDetails( boolean details ) { - showSuccessDetails = details; - } - - public boolean showSuccessDetails() { - return showSuccessDetails; - } - - public void addSetDouble( ExcelAntSetDoubleCell setter ) { - addSetter( setter ); - } - - public void addSetString( ExcelAntSetStringCell setter ){ - addSetter( setter ); - } - - public void addSetFormula( ExcelAntSetFormulaCell setter ) { - addSetter( setter ); - } - - public void addHandler( ExcelAntHandlerTask handler ) { - testTasks.add( handler ); - } - - private void addSetter( ExcelAntSet setter ) { -// setters.add( setter ); - testTasks.add( setter ); - } - - public void addEvaluate( ExcelAntEvaluateCell evaluator ) { -// evaluators.add( evaluator ); - testTasks.add( evaluator ); - } - -// public LinkedList getSetters() { -// return setters; -// } - - protected LinkedList getEvaluators() { - return evaluators; - } - - @Override - public void execute() throws BuildException { - - Iterator taskIt = testTasks.iterator(); - - int testCount = evaluators.size(); - int failureCount = 0; - - // roll over all sub task elements in one loop. This allows the - // ordering of the sub elements to be considered. - while( taskIt.hasNext() ) { - Task task = taskIt.next(); - - // log( task.getClass().getName(), Project.MSG_INFO ); - - if( task instanceof ExcelAntSet ) { - ExcelAntSet set = (ExcelAntSet) task; - set.setWorkbookUtil(workbookUtil); - set.execute(); - } - - if( task instanceof ExcelAntHandlerTask ) { - ExcelAntHandlerTask handler = (ExcelAntHandlerTask)task; - handler.setEAWorkbookUtil(workbookUtil ); - handler.execute(); - } - - if (task instanceof ExcelAntEvaluateCell ) { - ExcelAntEvaluateCell eval = (ExcelAntEvaluateCell)task; - eval.setWorkbookUtil( workbookUtil ); - - if( globalPrecision > 0 ) { - log( "setting globalPrecision to " + globalPrecision + " in the evaluator", Project.MSG_VERBOSE ); - eval.setGlobalPrecision( globalPrecision ); - } - - try { - eval.execute(); - ExcelAntEvaluationResult result = eval.getResult(); - if( result.didTestPass() && - !result.evaluationCompleteWithError()) { - if(showSuccessDetails) { - log("Succeeded when evaluating " + - result.getCellName() + ". It evaluated to " + - result.getReturnValue() + " when the value of " + - eval.getExpectedValue() + " with precision of " + - eval.getPrecision(), Project.MSG_INFO ); - } - } else { - if(showFailureDetail) { - failureMessages.add( "\tFailed to evaluate cell " + - result.getCellName() + ". It evaluated to " + - result.getReturnValue() + " when the value of " + - eval.getExpectedValue() + " with precision of " + - eval.getPrecision() + " was expected." ); - - } - passed = false; - failureCount++; - - if(eval.requiredToPass()) { - throw new BuildException( "\tFailed to evaluate cell " + - result.getCellName() + ". It evaluated to " + - result.getReturnValue() + " when the value of " + - eval.getExpectedValue() + " with precision of " + - eval.getPrecision() + " was expected." ); - } - } - } catch( NullPointerException npe ) { - // this means the cell reference in the test is bad. - log( "Cell assignment " + eval.getCell() + " in test " + getName() + - " appears to point to an empy cell. Please check the " + - " reference in the ant script.", Project.MSG_ERR ); - } - } - } - - if(!passed) { - log( "Test named " + name + " failed because " + failureCount + - " of " + testCount + " evaluations failed to " + - "evaluate correctly.", - Project.MSG_ERR ); - if(showFailureDetail && failureMessages.size() > 0 ) { - for (String failureMessage : failureMessages) { - log(failureMessage, Project.MSG_ERR); - } - } - } - } - - public boolean didTestPass() { - - return passed; - } - } diff --git a/src/excelant/java/org/apache/poi/ss/excelant/ExcelAntUserDefinedFunction.java b/src/excelant/java/org/apache/poi/ss/excelant/ExcelAntUserDefinedFunction.java deleted file mode 100644 index 5c19912b3..000000000 --- a/src/excelant/java/org/apache/poi/ss/excelant/ExcelAntUserDefinedFunction.java +++ /dev/null @@ -1,62 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.excelant; - -import org.apache.tools.ant.taskdefs.Typedef; - -/** - * This class encapsulates the Strings necessary to create the User Defined - * Function instances that will be passed to POI's Evaluator instance. - * - * @author Jon Svede ( jon [at] loquatic [dot] com ) - * @author Brian Bush ( brian [dot] bush [at] nrel [dot] gov ) - * - */ -public class ExcelAntUserDefinedFunction extends Typedef { - - - public String functionAlias ; - - public String className ; - - - public ExcelAntUserDefinedFunction() {} - - protected String getFunctionAlias() { - return functionAlias; - } - - public void setFunctionAlias(String functionAlias) { - this.functionAlias = functionAlias; - } - - protected String getClassName() { - // workaround for IBM JDK assigning the classname to the lowercase instance provided by Definer!?! - // I could not find out why that happens, the wrong assignment seems to be done somewhere deep inside Ant itself - // or even in IBM JDK as Oracle JDK does not have this problem. - if(className == null) { - return getClassname(); - } - - return className; - } - - public void setClassName(String className) { - this.className = className; - } -} diff --git a/src/excelant/java/org/apache/poi/ss/excelant/IExcelAntWorkbookHandler.java b/src/excelant/java/org/apache/poi/ss/excelant/IExcelAntWorkbookHandler.java deleted file mode 100644 index c8db7008d..000000000 --- a/src/excelant/java/org/apache/poi/ss/excelant/IExcelAntWorkbookHandler.java +++ /dev/null @@ -1,42 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.excelant; - -import org.apache.poi.ss.usermodel.Workbook; - - -/** - * In Excel there are many ways to handle manipulating a workbook based - * on some arbitrary user action (onChange, etc). You use this interface - * to create classes that will handle the workbook in whatever manner is needed - * that cannot be handled by POI. - *

    - * For example, suppose that in Excel when you update a cell the workbook - * does some calculations and updates other cells based on that change. In - * ExcelAnt you would set the value of the cell then write your own handler - * then call that from your Ant task after the set task. - * - * @author Jon Svede ( jon [at] loquatic [dot] com ) - * @author Brian Bush ( brian [dot] bush [at] nrel [dot] gov ) - * - */ -public interface IExcelAntWorkbookHandler { - public void setWorkbook( Workbook workbook ) ; - - public void execute() ; -} diff --git a/src/excelant/java/org/apache/poi/ss/excelant/util/ExcelAntEvaluationResult.java b/src/excelant/java/org/apache/poi/ss/excelant/util/ExcelAntEvaluationResult.java deleted file mode 100644 index 4eecd4fae..000000000 --- a/src/excelant/java/org/apache/poi/ss/excelant/util/ExcelAntEvaluationResult.java +++ /dev/null @@ -1,112 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.excelant.util; - -/** - * A simple class that encapsulates information about a cell evaluation - * from POI. - * - * @author Jon Svede (jon [at] loquatic [dot] com) - * @author Brian Bush (brian [dot] bush [at] nrel [dot] gov) - * - */ -public class ExcelAntEvaluationResult { - - /** - * This boolean flag is used to determine if the evaluation completed - * without error. This alone doesn't ensure that the evaluation was - * successful. - */ - private boolean evaluationCompletedWithError ; - - /** - * This boolean flag is used to determine if the result was within - * the specified precision. - */ - private boolean didPass ; - - /** - * This is the actual value returned from the evaluation. - */ - private double returnValue ; - - /** - * Any error message String values that need to be returned. - */ - private String errorMessage ; - - /** - * Stores the absolute value of the delta for this evaluation. - */ - private double actualDelta ; - - /** - * This stores the fully qualified cell name (sheetName!cellId). - */ - private String cellName ; - - - - public ExcelAntEvaluationResult(boolean completedWithError, - boolean passed, - double retValue, - String errMessage, - double delta, - String cellId) { - - evaluationCompletedWithError = completedWithError; - didPass = passed; - returnValue = retValue; - errorMessage = errMessage; - actualDelta = delta ; - cellName = cellId ; - } - - public double getReturnValue() { - return returnValue; - } - - public String getErrorMessage() { - return errorMessage; - } - - public boolean didTestPass() { - return didPass ; - } - - public boolean evaluationCompleteWithError() { - return evaluationCompletedWithError ; - } - - public double getDelta() { - return actualDelta ; - } - - public String getCellName() { - return cellName ; - } - - @Override - public String toString() { - return "ExcelAntEvaluationResult [evaluationCompletedWithError=" - + evaluationCompletedWithError + ", didPass=" + didPass - + ", returnValue=" + returnValue + ", errorMessage=" - + errorMessage + ", actualDelta=" + actualDelta + ", cellName=" - + cellName + "]"; - } -} diff --git a/src/excelant/java/org/apache/poi/ss/excelant/util/ExcelAntWorkbookUtil.java b/src/excelant/java/org/apache/poi/ss/excelant/util/ExcelAntWorkbookUtil.java deleted file mode 100644 index dcb30a84c..000000000 --- a/src/excelant/java/org/apache/poi/ss/excelant/util/ExcelAntWorkbookUtil.java +++ /dev/null @@ -1,386 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.excelant.util; - -import java.io.File; -import java.io.FileInputStream; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.functions.FreeRefFunction; -import org.apache.poi.ss.formula.udf.AggregatingUDFFinder; -import org.apache.poi.ss.formula.udf.DefaultUDFFinder; -import org.apache.poi.ss.formula.udf.UDFFinder; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellValue; -import org.apache.poi.ss.usermodel.FormulaError; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.usermodel.WorkbookFactory; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.Project; -import org.apache.tools.ant.taskdefs.Typedef; - -/** - * A general utility class that abstracts the POI details of loading the - * workbook, accessing and updating cells. - * - * @author Jon Svede (jon [at] loquatic [dot] com) - * @author Brian Bush (brian [dot] bush [at] nrel [dot] gov) - * - */ -public class ExcelAntWorkbookUtil extends Typedef { - - private String excelFileName; - - private Workbook workbook; - - private final Map xlsMacroList = new HashMap(); - - /** - * Constructs an instance using a String that contains the fully qualified - * path of the Excel file. This constructor initializes a Workbook instance - * based on that file name. - * - * @param fName The fully qualified path of the Excel file. - * @throws BuildException If the workbook cannot be loaded. - */ - protected ExcelAntWorkbookUtil(String fName) { - excelFileName = fName; - loadWorkbook(); - - } - - /** - * Constructs an instance based on a Workbook instance. - * - * @param wb The Workbook to use for this instance. - */ - protected ExcelAntWorkbookUtil(Workbook wb) { - workbook = wb; - } - - /** - * Loads the member variable workbook based on the fileName variable. - * @return The opened Workbook-instance - * @throws BuildException If the workbook cannot be loaded. - */ - private Workbook loadWorkbook() { - if (excelFileName == null) { - throw new BuildException("fileName attribute must be set!", getLocation()); - } - - try { - FileInputStream fis = new FileInputStream(excelFileName); - try { - workbook = WorkbookFactory.create(fis); - } finally { - fis.close(); - } - } catch(Exception e) { - throw new BuildException("Cannot load file " + excelFileName - + ". Make sure the path and file permissions are correct.", e); - } - - return workbook; - } - - /** - * Used to add a UDF to the evaluator. - * @param name - * @param clazzName - * @throws ClassNotFoundException - * @throws InstantiationException - * @throws IllegalAccessException - */ - public void addFunction(String name, String clazzName) throws ClassNotFoundException, InstantiationException, IllegalAccessException { - Class clazzInst = Class.forName(clazzName); - Object newInst = clazzInst.newInstance(); - if(newInst instanceof FreeRefFunction) { - addFunction(name, (FreeRefFunction)newInst); - } - - } - - /** - * Updates the internal HashMap of functions with instance and alias passed - * in. - * - * @param name - * @param func - */ - protected void addFunction(String name, FreeRefFunction func) { - xlsMacroList.put(name, func); - } - - /** - * returns a UDFFinder that contains all of the functions added. - * - * @return - */ - protected UDFFinder getFunctions() { - - String[] names = new String[xlsMacroList.size()]; - FreeRefFunction[] functions = new FreeRefFunction[xlsMacroList.size()]; - - int x = 0; - for(Map.Entry entry : xlsMacroList.entrySet()) { - names[x] = entry.getKey(); - functions[x] = entry.getValue(); - } - - UDFFinder udff1 = new DefaultUDFFinder(names, functions); - UDFFinder udff = new AggregatingUDFFinder(udff1); - - return udff; - - } - - /** - * Returns a formula evaluator that is loaded with the functions that - * have been supplied. - * - * @param fileName - * @return - */ - protected FormulaEvaluator getEvaluator(String fileName) { - FormulaEvaluator evaluator; - if (fileName.endsWith(".xlsx")) { - if(xlsMacroList.size() > 0) { - evaluator = XSSFFormulaEvaluator.create((XSSFWorkbook) workbook, - null, - getFunctions()); - } - evaluator = new XSSFFormulaEvaluator((XSSFWorkbook) workbook); - } else { - if(xlsMacroList.size() > 0) { - evaluator = HSSFFormulaEvaluator.create((HSSFWorkbook)workbook, - null, - getFunctions()); - } - - evaluator = new HSSFFormulaEvaluator((HSSFWorkbook) workbook); - } - - return evaluator; - - } - - /** - * Returns the Workbook instance associated with this WorkbookUtil. - * - * @return - */ - public Workbook getWorkbook() { - return workbook; - } - - /** - * Returns the fileName that was used to initialize this instance. May - * return null if the instance was constructed from a Workbook object. - * - * @return - */ - public String getFileName() { - return excelFileName; - } - - /** - * Returns the list of sheet names. - * - * @return - */ - public List getSheets() { - ArrayList sheets = new ArrayList(); - - int sheetCount = workbook.getNumberOfSheets(); - - for(int x=0; x precision) { - evalResults = new ExcelAntEvaluationResult(false, false, - resultOfEval.getNumberValue(), - "Results was out of range based on precision " + " of " - + precision + ". Delta was actually " + delta, delta, cellName); - } else { - evalResults = new ExcelAntEvaluationResult(false, true, - resultOfEval.getNumberValue(), - "Evaluation passed without error within in range.", delta, cellName); - } - } else { - String errorMeaning = null; - try { - errorMeaning = FormulaError.forInt(resultOfEval.getErrorValue()).getString(); - } catch(IllegalArgumentException iae) { - errorMeaning = "unknown error code: " + - Byte.toString(resultOfEval.getErrorValue()); - } - - evalResults = new ExcelAntEvaluationResult(true, false, - resultOfEval.getNumberValue(), - "Evaluation failed due to an evaluation error of " - + resultOfEval.getErrorValue() - + " which is " - + errorMeaning, 0, cellName); - } - - return evalResults; - } - - /** - * Returns a Cell as a String value. - * - * @param cellName - * @return - */ - public String getCellAsString(String cellName) { - Cell cell = getCell(cellName); - return cell.getStringCellValue(); - } - - - /** - * Returns the value of the Cell as a double. - * - * @param cellName - * @return - */ - public double getCellAsDouble(String cellName) { - Cell cell = getCell(cellName); - return cell.getNumericCellValue(); - } - /** - * Returns a cell reference based on a String in standard Excel format - * (SheetName!CellId). This method will create a new cell if the - * requested cell isn't initialized yet. - * - * @param cellName - * @return - */ - private Cell getCell(String cellName) { - CellReference cellRef = new CellReference(cellName); - String sheetName = cellRef.getSheetName(); - Sheet sheet = workbook.getSheet(sheetName); - if(sheet == null) { - throw new BuildException("Sheet not found: " + sheetName); - } - - int rowIdx = cellRef.getRow(); - int colIdx = cellRef.getCol(); - Row row = sheet.getRow(rowIdx); - - if(row == null) { - row = sheet.createRow(rowIdx); - } - - Cell cell = row.getCell(colIdx); - - if(cell == null) { - cell = row.createCell(colIdx); - } - - return cell; - } -} diff --git a/src/excelant/java/org/apache/poi/ss/excelant/util/ExcelAntWorkbookUtilFactory.java b/src/excelant/java/org/apache/poi/ss/excelant/util/ExcelAntWorkbookUtilFactory.java deleted file mode 100644 index 683ac4636..000000000 --- a/src/excelant/java/org/apache/poi/ss/excelant/util/ExcelAntWorkbookUtilFactory.java +++ /dev/null @@ -1,60 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.excelant.util; - -import java.util.HashMap; -import java.util.Map; - - -/** - * This is a factory class maps file names to WorkbookUtil instances. This - * helps ExcelAnt be more efficient when being run many times in an Ant build. - * - * @author Jon Svede (jon [at] loquatic [dot] com) - * @author Brian Bush (brian [dot] bush [at] nrel [dot] gov) - * - */ -public final class ExcelAntWorkbookUtilFactory { - - private static Map workbookUtilMap; - - private ExcelAntWorkbookUtilFactory() { - } - - /** - * Using the fileName, check the internal map to see if an instance - * of the WorkbookUtil exists. If not, then add an instance to the map. - * - * @param fileName The filename to use as key to look for the ExcelAntWorkbookUtil. - * @return An instance of ExcelAntWorkbookUtil associated with the filename or - * a freshly instantiated one if none did exist before. - */ - public static ExcelAntWorkbookUtil getInstance(String fileName) { - if(workbookUtilMap == null) { - workbookUtilMap = new HashMap(); - } - - if(workbookUtilMap.containsKey(fileName)) { - return workbookUtilMap.get(fileName); - } - - ExcelAntWorkbookUtil wbu = new ExcelAntWorkbookUtil(fileName); - workbookUtilMap.put(fileName, wbu); - return wbu; - } -} diff --git a/src/excelant/resources/org/apache/poi/ss/excelant/antlib.xml b/src/excelant/resources/org/apache/poi/ss/excelant/antlib.xml deleted file mode 100644 index af13cc649..000000000 --- a/src/excelant/resources/org/apache/poi/ss/excelant/antlib.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - - - - - - - diff --git a/src/excelant/testcases/org/apache/poi/ss/examples/formula/CalculateMortgageFunction.java b/src/excelant/testcases/org/apache/poi/ss/examples/formula/CalculateMortgageFunction.java deleted file mode 100644 index f1c526bf9..000000000 --- a/src/excelant/testcases/org/apache/poi/ss/examples/formula/CalculateMortgageFunction.java +++ /dev/null @@ -1,96 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.examples.formula; - -import org.apache.poi.ss.formula.OperationEvaluationContext ; -import org.apache.poi.ss.formula.eval.ErrorEval ; -import org.apache.poi.ss.formula.eval.EvaluationException ; -import org.apache.poi.ss.formula.eval.NumberEval ; -import org.apache.poi.ss.formula.eval.OperandResolver ; -import org.apache.poi.ss.formula.eval.ValueEval ; -import org.apache.poi.ss.formula.functions.FreeRefFunction ; - -/** - * A simple user-defined function to calculate principal and interest. - * - * Used by {@link org.apache.poi.ss.excelant.util.TestExcelAntWorkbookUtil}. - * - * @author Jon Svede ( jon [at] loquatic [dot] com ) - * @author Brian Bush ( brian [dot] bush [at] nrel [dot] gov ) - * - */ -public class CalculateMortgageFunction implements FreeRefFunction { - - @Override - public ValueEval evaluate( ValueEval[] args, OperationEvaluationContext ec ) { - - // verify that we have enough data - if (args.length != 3) { - return ErrorEval.VALUE_INVALID; - } - - // declare doubles for values - double principal, rate, years, result; - try { - // extract values as ValueEval - ValueEval v1 = OperandResolver.getSingleValue( args[0], - ec.getRowIndex(), - ec.getColumnIndex() ) ; - ValueEval v2 = OperandResolver.getSingleValue( args[1], - ec.getRowIndex(), - ec.getColumnIndex() ) ; - ValueEval v3 = OperandResolver.getSingleValue( args[2], - ec.getRowIndex(), - ec.getColumnIndex() ) ; - - // get data as doubles - principal = OperandResolver.coerceValueToDouble( v1 ) ; - rate = OperandResolver.coerceValueToDouble( v2 ) ; - years = OperandResolver.coerceValueToDouble( v3 ) ; - - result = calculateMortgagePayment( principal, rate, years ) ; - System.out.println( "Result = " + result ) ; - - checkValue(result); - - } catch (EvaluationException e) { - return e.getErrorEval(); - } - - return new NumberEval( result ) ; - } - - public double calculateMortgagePayment( double p, double r, double y ) { - double i = r / 12 ; - double n = y * 12 ; - - double principalAndInterest = - p * (( i * Math.pow((1 + i),n ) ) / ( Math.pow((1 + i),n) - 1)) ; - - return principalAndInterest ; - } - /** - * Excel does not support infinities and NaNs, rather, it gives a #NUM! error in these cases - * - * @throws EvaluationException (#NUM!) if result is NaN or Infinity - */ - private void checkValue(double result) throws EvaluationException { - if (Double.isNaN(result) || Double.isInfinite(result)) { - throw new EvaluationException(ErrorEval.NUM_ERROR); - } - } -} diff --git a/src/excelant/testcases/org/apache/poi/ss/examples/formula/ExcelAntUserDefinedFunctionTestHelper.java b/src/excelant/testcases/org/apache/poi/ss/examples/formula/ExcelAntUserDefinedFunctionTestHelper.java deleted file mode 100644 index 68e4b6957..000000000 --- a/src/excelant/testcases/org/apache/poi/ss/examples/formula/ExcelAntUserDefinedFunctionTestHelper.java +++ /dev/null @@ -1,36 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.examples.formula; - -import org.apache.poi.ss.excelant.ExcelAntUserDefinedFunction; - -public class ExcelAntUserDefinedFunctionTestHelper extends - ExcelAntUserDefinedFunction { - - @Override - protected String getFunctionAlias() { - // TODO Auto-generated method stub - return super.getFunctionAlias(); - } - - @Override - protected String getClassName() { - // TODO Auto-generated method stub - return super.getClassName(); - } - -} diff --git a/src/excelant/testcases/org/apache/poi/ss/examples/formula/TestExcelAntUserDefinedFunction.java b/src/excelant/testcases/org/apache/poi/ss/examples/formula/TestExcelAntUserDefinedFunction.java deleted file mode 100644 index ad9851ae8..000000000 --- a/src/excelant/testcases/org/apache/poi/ss/examples/formula/TestExcelAntUserDefinedFunction.java +++ /dev/null @@ -1,51 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.examples.formula; - -import junit.framework.TestCase; - -public class TestExcelAntUserDefinedFunction extends TestCase { - - private ExcelAntUserDefinedFunctionTestHelper fixture ; - - @Override - public void setUp() { - fixture = new ExcelAntUserDefinedFunctionTestHelper() ; - } - - public void testSetClassName() { - String className = "simple.class.name" ; - - fixture.setClassName( className ) ; - String value = fixture.getClassName() ; - - assertNotNull( value ) ; - assertEquals( className, value ) ; - } - - public void testSetFunction() { - String functionAlias = "alias" ; - - fixture.setFunctionAlias( functionAlias ) ; - - String alias = fixture.getFunctionAlias() ; - - assertNotNull( alias ) ; - assertEquals( functionAlias, alias ) ; - } - -} diff --git a/src/excelant/testcases/org/apache/poi/ss/excelant/BuildFileTest.java b/src/excelant/testcases/org/apache/poi/ss/excelant/BuildFileTest.java deleted file mode 100644 index ea2bb596c..000000000 --- a/src/excelant/testcases/org/apache/poi/ss/excelant/BuildFileTest.java +++ /dev/null @@ -1,604 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.apache.poi.ss.excelant; - -import java.io.File; -import java.io.PrintStream; -import java.net.URL; - -import junit.framework.TestCase; - -import org.apache.poi.POIDataSamples; -import org.apache.tools.ant.BuildEvent; -import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.BuildListener; -import org.apache.tools.ant.Project; -import org.apache.tools.ant.ProjectHelper; - -/** - * A BuildFileTest is a TestCase which executes targets from an Ant buildfile - * for testing. - *

    - * This class provides a number of utility methods for particular build file - * tests which extend this class. - * - * @see - * http://svn.apache.org/repos/asf/ant/core/trunk/src/tests/junit/org/apache/tools/ant/BuildFileTest.java - */ -public abstract class BuildFileTest extends TestCase { - - protected Project project; - - private StringBuffer logBuffer; - private StringBuffer fullLogBuffer; - private StringBuffer outBuffer; - private StringBuffer errBuffer; - private BuildException buildException; - - /** - * Default constructor for the BuildFileTest object. - */ - public BuildFileTest() { - super(); - } - - /** - * Constructor for the BuildFileTest object. - * - * @param name string to pass up to TestCase constructor - */ - public BuildFileTest(String name) { - super(name); - } - - /** - * Automatically calls the target called "tearDown" - * from the build file tested if it exits. - *

    - * This allows to use Ant tasks directly in the build file - * to clean up after each test. Note that no "setUp" target - * is automatically called, since it's trivial to have a - * test target depend on it. - */ - @Override - protected void tearDown() throws Exception { - if (project == null) { - /* - * Maybe the BuildFileTest was subclassed and there is - * no initialized project. So we could avoid getting a - * NPE. - * If there is an initialized project getTargets() does - * not return null as it is initialized by an empty - * HashSet. - */ - return; - } - final String tearDown = "tearDown"; - if (project.getTargets().containsKey(tearDown)) { - project.executeTarget(tearDown); - } - } - - /** - * run a target, expect for any build exception - * - * @param target target to run - * @param cause information string to reader of report - */ - public void expectBuildException(String target, String cause) { - expectSpecificBuildException(target, cause, null); - } - - /** - * Assert that only the given message has been logged with a - * priority <= INFO when running the given target. - */ - public void expectLog(String target, String log) { - executeTarget(target); - String realLog = getLog(); - assertEquals(log, realLog); - } - - /** - * Assert that the given substring is in the log messages. - */ - public void assertLogContaining(String substring) { - String realLog = getLog(); - assertTrue("expecting log to contain \"" + substring + "\" log was \"" - + realLog + "\"", - realLog.indexOf(substring) >= 0); - } - - /** - * Assert that the given substring is not in the log messages. - */ - public void assertLogNotContaining(String substring) { - String realLog = getLog(); - assertFalse("didn't expect log to contain \"" + substring + "\" log was \"" - + realLog + "\"", - realLog.indexOf(substring) >= 0); - } - - /** - * Assert that the given substring is in the output messages. - * - * @since Ant1.7 - */ - public void assertOutputContaining(String substring) { - assertOutputContaining(null, substring); - } - - /** - * Assert that the given substring is in the output messages. - * - * @param message Print this message if the test fails. Defaults to - * a meaningful text if null is passed. - * @since Ant1.7 - */ - public void assertOutputContaining(String message, String substring) { - String realOutput = getOutput(); - String realMessage = (message != null) - ? message - : "expecting output to contain \"" + substring + "\" output was \"" + realOutput + "\""; - assertTrue(realMessage, realOutput.indexOf(substring) >= 0); - } - - /** - * Assert that the given substring is not in the output messages. - * - * @param message Print this message if the test fails. Defaults to - * a meaningful text if null is passed. - * @since Ant1.7 - */ - public void assertOutputNotContaining(String message, String substring) { - String realOutput = getOutput(); - String realMessage = (message != null) - ? message - : "expecting output to not contain \"" + substring + "\" output was \"" + realOutput + "\""; - assertFalse(realMessage, realOutput.indexOf(substring) >= 0); - } - - /** - * Assert that the given message has been logged with a priority <= INFO when running the - * given target. - */ - public void expectLogContaining(String target, String log) { - executeTarget(target); - assertLogContaining(log); - } - - /** - * Assert that the given message has not been logged with a - * priority <= INFO when running the given target. - */ - public void expectLogNotContaining(String target, String log) { - executeTarget(target); - assertLogNotContaining(log); - } - - /** - * Gets the log the BuildFileTest object. - * Only valid if configureProject() has been called. - * - * @return The log value - * @pre logBuffer!=null - */ - public String getLog() { - return logBuffer.toString(); - } - - /** - * Assert that the given message has been logged with a priority - * >= VERBOSE when running the given target. - */ - public void expectDebuglog(String target, String log) { - executeTarget(target); - String realLog = getFullLog(); - assertEquals(log, realLog); - } - - /** - * Assert that the given substring is in the log messages. - */ - public void assertDebuglogContaining(String substring) { - String realLog = getFullLog(); - assertTrue("expecting debug log to contain \"" + substring - + "\" log was \"" - + realLog + "\"", - realLog.indexOf(substring) >= 0); - } - - /** - * Gets the log the BuildFileTest object. - *

    - * Only valid if configureProject() has been called. - * - * @return The log value - * @pre fullLogBuffer!=null - */ - public String getFullLog() { - return fullLogBuffer.toString(); - } - - /** - * execute the target, verify output matches expectations - * - * @param target target to execute - * @param output output to look for - */ - public void expectOutput(String target, String output) { - executeTarget(target); - String realOutput = getOutput(); - assertEquals(output, realOutput.trim()); - } - - /** - * Executes the target, verify output matches expectations - * and that we got the named error at the end - * - * @param target target to execute - * @param output output to look for - * @param error Description of Parameter - */ - public void expectOutputAndError(String target, String output, String error) { - executeTarget(target); - String realOutput = getOutput(); - assertEquals(output, realOutput); - String realError = getError(); - assertEquals(error, realError); - } - - public String getOutput() { - return cleanBuffer(outBuffer); - } - - public String getError() { - return cleanBuffer(errBuffer); - } - - public BuildException getBuildException() { - return buildException; - } - - private String cleanBuffer(StringBuffer buffer) { - StringBuffer cleanedBuffer = new StringBuffer(); - for (int i = 0; i < buffer.length(); i++) { - char ch = buffer.charAt(i); - if (ch != '\r') { - cleanedBuffer.append(ch); - } - } - return cleanedBuffer.toString(); - } - - /** - * Sets up to run the named project - * - * @param filename name of project file to run - */ - public void configureProject(String filename) throws BuildException { - configureProject(filename, Project.MSG_DEBUG); - } - - /** - * Sets up to run the named project - * - * @param filename name of project file to run - */ - public void configureProject(String filename, int logLevel) - throws BuildException { - logBuffer = new StringBuffer(); - fullLogBuffer = new StringBuffer(); - project = new Project(); - project.init(); - project.setNewProperty("data.dir.name", getDataDir()); - File antFile = new File(System.getProperty("root"), filename); - project.setUserProperty("ant.file", antFile.getAbsolutePath()); - project.addBuildListener(new AntTestListener(logLevel)); - ProjectHelper.configureProject(project, antFile); - } - - /** - * Executes a target we have set up - * - * @param targetName target to run - * @pre configureProject has been called - */ - public void executeTarget(String targetName) { - PrintStream sysOut = System.out; - PrintStream sysErr = System.err; - try { - sysOut.flush(); - sysErr.flush(); - outBuffer = new StringBuffer(); - PrintStream out = new PrintStream(new AntOutputStream(outBuffer)); - System.setOut(out); - errBuffer = new StringBuffer(); - PrintStream err = new PrintStream(new AntOutputStream(errBuffer)); - System.setErr(err); - logBuffer = new StringBuffer(); - fullLogBuffer = new StringBuffer(); - buildException = null; - project.executeTarget(targetName); - } finally { - System.setOut(sysOut); - System.setErr(sysErr); - } - - } - - /** - * Get the project which has been configured for a test. - * - * @return the Project instance for this test. - */ - public Project getProject() { - return project; - } - - /** - * Gets the directory of the project. - * - * @return the base dir of the project - */ - public File getProjectDir() { - return project.getBaseDir(); - } - - /** - * Runs a target, wait for a build exception. - * - * @param target target to run - * @param cause information string to reader of report - * @param msg the message value of the build exception we are waiting - * for set to null for any build exception to be valid - */ - public void expectSpecificBuildException(String target, String cause, String msg) { - try { - executeTarget(target); - } catch (org.apache.tools.ant.BuildException ex) { - buildException = ex; - if ((null != msg) && (!ex.getMessage().equals(msg))) { - fail("Should throw BuildException because '" + cause - + "' with message '" + msg - + "' (actual message '" + ex.getMessage() + "' instead)"); - } - return; - } - fail("Should throw BuildException because: " + cause); - } - - /** - * run a target, expect an exception string - * containing the substring we look for (case sensitive match) - * - * @param target target to run - * @param cause information string to reader of report - * @param contains substring of the build exception to look for - */ - public void expectBuildExceptionContaining(String target, String cause, String contains) { - try { - executeTarget(target); - } catch (org.apache.tools.ant.BuildException ex) { - buildException = ex; - if ((null != contains) && (ex.getMessage().indexOf(contains) == -1)) { - fail("Should throw BuildException because '" + cause + "' with message containing '" + contains + "' (actual message '" + ex.getMessage() + "' instead)"); - } - return; - } - fail("Should throw BuildException because: " + cause); - } - - /** - * call a target, verify property is as expected - * - * @param target build file target - * @param property property name - * @param value expected value - */ - public void expectPropertySet(String target, String property, String value) { - executeTarget(target); - assertPropertyEquals(property, value); - } - - /** - * assert that a property equals a value; comparison is case sensitive. - * - * @param property property name - * @param value expected value - */ - public void assertPropertyEquals(String property, String value) { - String result = project.getProperty(property); - assertEquals("property " + property, value, result); - } - - /** - * assert that a property equals "true". - * - * @param property property name - */ - public void assertPropertySet(String property) { - assertPropertyEquals(property, "true"); - } - - /** - * assert that a property is null. - * - * @param property property name - */ - public void assertPropertyUnset(String property) { - String result = project.getProperty(property); - if (result != null) { - fail("Expected property " + property - + " to be unset, but it is set to the value: " + result); - } - } - - /** - * call a target, verify named property is "true". - * - * @param target build file target - * @param property property name - */ - public void expectPropertySet(String target, String property) { - expectPropertySet(target, property, "true"); - } - - /** - * Call a target, verify property is null. - * - * @param target build file target - * @param property property name - */ - public void expectPropertyUnset(String target, String property) { - expectPropertySet(target, property, null); - } - - /** - * Retrieve a resource from the caller classloader to avoid - * assuming a vm working directory. The resource path must be - * relative to the package name or absolute from the root path. - * - * @param resource the resource to retrieve its url. - * @throws junit.framework.AssertionFailedError - * if the resource is not found. - */ - public URL getResource(String resource) { - URL url = getClass().getResource(resource); - assertNotNull("Could not find resource :" + resource, url); - return url; - } - - public static String getDataDir() { - String dataDirName = System.getProperty(POIDataSamples.TEST_PROPERTY); - return dataDirName == null ? "test-data" : dataDirName; - } - - /** - * an output stream which saves stuff to our buffer. - */ - protected static class AntOutputStream extends java.io.OutputStream { - private StringBuffer buffer; - - public AntOutputStream(StringBuffer buffer) { - this.buffer = buffer; - } - - @Override - public void write(int b) { - buffer.append((char) b); - } - } - - /** - * Our own personal build listener. - */ - private class AntTestListener implements BuildListener { - private int logLevel; - - /** - * Constructs a test listener which will ignore log events - * above the given level. - */ - public AntTestListener(int logLevel) { - this.logLevel = logLevel; - } - - /** - * Fired before any targets are started. - */ - @Override - public void buildStarted(BuildEvent event) { - } - - /** - * Fired after the last target has finished. This event - * will still be thrown if an error occurred during the build. - * - * @see BuildEvent#getException() - */ - @Override - public void buildFinished(BuildEvent event) { - } - - /** - * Fired when a target is started. - * - * @see BuildEvent#getTarget() - */ - @Override - public void targetStarted(BuildEvent event) { - //System.out.println("targetStarted " + event.getTarget().getName()); - } - - /** - * Fired when a target has finished. This event will - * still be thrown if an error occurred during the build. - * - * @see BuildEvent#getException() - */ - @Override - public void targetFinished(BuildEvent event) { - //System.out.println("targetFinished " + event.getTarget().getName()); - } - - /** - * Fired when a task is started. - * - * @see BuildEvent#getTask() - */ - @Override - public void taskStarted(BuildEvent event) { - //System.out.println("taskStarted " + event.getTask().getTaskName()); - } - - /** - * Fired when a task has finished. This event will still - * be throw if an error occurred during the build. - * - * @see BuildEvent#getException() - */ - @Override - public void taskFinished(BuildEvent event) { - //System.out.println("taskFinished " + event.getTask().getTaskName()); - } - - /** - * Fired whenever a message is logged. - * - * @see BuildEvent#getMessage() - * @see BuildEvent#getPriority() - */ - @Override - public void messageLogged(BuildEvent event) { - if (event.getPriority() > logLevel) { - // ignore event - return; - } - - if (event.getPriority() == Project.MSG_INFO || - event.getPriority() == Project.MSG_WARN || - event.getPriority() == Project.MSG_ERR) { - logBuffer.append(event.getMessage()); - } - fullLogBuffer.append(event.getMessage()); - } - } - -} diff --git a/src/excelant/testcases/org/apache/poi/ss/excelant/MockExcelAntWorkbookHandler.java b/src/excelant/testcases/org/apache/poi/ss/excelant/MockExcelAntWorkbookHandler.java deleted file mode 100644 index 6e52e1d4b..000000000 --- a/src/excelant/testcases/org/apache/poi/ss/excelant/MockExcelAntWorkbookHandler.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.apache.poi.ss.excelant; - -import static org.junit.Assert.assertNotNull; - -import org.apache.poi.ss.usermodel.Workbook; - -public class MockExcelAntWorkbookHandler implements IExcelAntWorkbookHandler { - public static boolean executed = false; - public static Workbook workbook = null; - - - @Override - public void setWorkbook(Workbook workbook) { - MockExcelAntWorkbookHandler.workbook = workbook; - } - - @Override - public void execute() { - executed = true; - assertNotNull(workbook); - } -} diff --git a/src/excelant/testcases/org/apache/poi/ss/excelant/TestBuildFile.java b/src/excelant/testcases/org/apache/poi/ss/excelant/TestBuildFile.java deleted file mode 100644 index 7d55c5276..000000000 --- a/src/excelant/testcases/org/apache/poi/ss/excelant/TestBuildFile.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.apache.poi.ss.excelant; - - -/** - * JUnit test for the ExcelAnt tasks. - * Leverages Ant's test framework. - * - * @see - * http://svn.apache.org/repos/asf/ant/core/trunk/src/tests/junit/org/apache/tools/ant/BuildFileTest.java - */ -public class TestBuildFile extends BuildFileTest { - - @Override - public void setUp() { - configureProject(BuildFileTest.getDataDir() + "/../src/excelant/testcases/org/apache/poi/ss/excelant/tests.xml"); - } - - public void testMissingFilename() { - expectSpecificBuildException("test-nofile", "required argument not specified", - "fileName attribute must be set!"); - } - - public void testFileNotFound() { - expectSpecificBuildException("test-filenotfound", "required argument not specified", - "Cannot load file invalid.xls. Make sure the path and file permissions are correct."); - } - - public void testEvaluate() { - executeTarget("test-evaluate"); - assertLogContaining("Using input file: " + BuildFileTest.getDataDir() + "/spreadsheet/excelant.xls"); - assertLogContaining("Succeeded when evaluating 'MortgageCalculator'!$B$4."); - } - - public void testEvaluateNoDetails() { - executeTarget("test-evaluate-nodetails"); - assertLogContaining("Using input file: " + BuildFileTest.getDataDir() + "/spreadsheet/excelant.xls"); - assertLogNotContaining("Succeeded when evaluating 'MortgageCalculator'!$B$4."); - } - - public void testPrecision() { - executeTarget("test-precision"); - - assertLogContaining("Using input file: " + BuildFileTest.getDataDir() + "/spreadsheet/excelant.xls"); - assertLogContaining("Succeeded when evaluating 'MortgageCalculator'!$B$4. " + - "It evaluated to 2285.5761494145563 when the value of 2285.576149 with precision of 1.0E-4"); - assertLogContaining("Succeeded when evaluating 'MortgageCalculator'!$B$4. " + - "It evaluated to 2285.5761494145563 when the value of 2285.576149 with precision of 1.0E-5"); - assertLogContaining("Failed to evaluate cell 'MortgageCalculator'!$B$4. " + - "It evaluated to 2285.5761494145563 when the value of 2285.576149 with precision of 1.0E-10 was expected."); - assertLogContaining("2/3 tests passed"); - } - - public void testPrecisionFail() { - expectSpecificBuildException("test-precision-fails", "precision not matched", - "\tFailed to evaluate cell 'MortgageCalculator'!$B$4. It evaluated to 2285.5761494145563 when the value of 2285.576149 with precision of 1.0E-10 was expected."); - } - - public void testPassOnError() { - executeTarget("test-passonerror"); - } - - public void testFailOnError() { - expectBuildException("test-failonerror", "fail on error"); - assertLogContaining("Using input file: " + BuildFileTest.getDataDir() + "/spreadsheet/excelant.xls"); - assertLogNotContaining("failed because 1 of 0 evaluations failed to evaluate correctly. Failed to evaluate cell 'MortageCalculatorFunction'!$D$3"); - } - - public void testFailOnErrorNoDetails() { - expectBuildException("test-failonerror-nodetails", "fail on error"); - assertLogNotContaining("Using input file: " + BuildFileTest.getDataDir() + "/spreadsheet/excelant.xls"); - assertLogNotContaining("failed because 1 of 0 evaluations failed to evaluate correctly. Failed to evaluate cell 'MortageCalculatorFunction'!$D$3"); - } - - public void testUdf() { - executeTarget("test-udf"); - assertLogContaining("1/1 tests passed"); - } - - public void testSetText() { - executeTarget("test-settext"); - assertLogContaining("1/1 tests passed"); - } - - public void testAddHandler() { - executeTarget("test-addhandler"); - assertLogContaining("Using input file: " + BuildFileTest.getDataDir() + "/spreadsheet/excelant.xls"); - assertLogContaining("Succeeded when evaluating 'MortgageCalculator'!$B$4."); - - assertNotNull("The workbook should have been passed to the handler", MockExcelAntWorkbookHandler.workbook); - assertTrue("The handler should have been executed", MockExcelAntWorkbookHandler.executed); - } - - public void testAddHandlerWrongClass() { - executeTarget("test-addhandler-wrongclass"); - assertLogContaining("Using input file: " + BuildFileTest.getDataDir() + "/spreadsheet/excelant.xls"); - assertLogContaining("Succeeded when evaluating 'MortgageCalculator'!$B$4."); - } - - public void testAddHandlerFails() { - expectSpecificBuildException("test-addhandler-fails", "NullPointException", null); - } -} diff --git a/src/excelant/testcases/org/apache/poi/ss/excelant/TestExcelAntPrecision.java b/src/excelant/testcases/org/apache/poi/ss/excelant/TestExcelAntPrecision.java deleted file mode 100644 index 0c6f9cbf8..000000000 --- a/src/excelant/testcases/org/apache/poi/ss/excelant/TestExcelAntPrecision.java +++ /dev/null @@ -1,48 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.excelant; - -import junit.framework.TestCase; - -public class TestExcelAntPrecision extends TestCase { - - private ExcelAntPrecision fixture ; - - @Override - public void setUp() { - fixture = new ExcelAntPrecision() ; - } - - @Override - public void tearDown() { - fixture = null ; - } - - public void testVerifyPrecision() { - - double value = 1.0E-1 ; - - fixture.setValue( value ) ; - - double result = fixture.getValue() ; - - assertTrue( result > 0 ) ; - - assertEquals( value, result, 0.0 ) ; - } - -} diff --git a/src/excelant/testcases/org/apache/poi/ss/excelant/TestExcelAntSet.java b/src/excelant/testcases/org/apache/poi/ss/excelant/TestExcelAntSet.java deleted file mode 100644 index b59c886ae..000000000 --- a/src/excelant/testcases/org/apache/poi/ss/excelant/TestExcelAntSet.java +++ /dev/null @@ -1,63 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.excelant; - -import junit.framework.TestCase; - -import org.apache.poi.ss.excelant.util.ExcelAntWorkbookUtil; -import org.apache.poi.ss.excelant.util.ExcelAntWorkbookUtilFactory; - -public class TestExcelAntSet extends TestCase { - - - // This is abstract in nature, so we'll use a - // concrete instance to test the set methods. - private ExcelAntSet fixture ; - - private static final String mortgageCalculatorFileName = - BuildFileTest.getDataDir() + "/spreadsheet/mortgage-calculation.xls" ; - - @Override - public void setUp() { - fixture = new ExcelAntSetDoubleCell() ; - } - - @Override - public void tearDown() { - fixture = null ; - } - - public void testSetter() { - String cell = "simpleCellRef!$F$1" ; - - fixture.setCell( cell ) ; - - String cellStr = fixture.getCell() ; - - assertNotNull( cellStr ) ; - assertEquals( cell, cellStr ) ; - } - - public void testSetWorkbookUtil() { - ExcelAntWorkbookUtil util = ExcelAntWorkbookUtilFactory.getInstance( - mortgageCalculatorFileName ) ; - - assertNotNull( util ) ; - - fixture.setWorkbookUtil( util ) ; - } -} diff --git a/src/excelant/testcases/org/apache/poi/ss/excelant/TestExcelAntSetDoubleCell.java b/src/excelant/testcases/org/apache/poi/ss/excelant/TestExcelAntSetDoubleCell.java deleted file mode 100644 index 3d5b11ef4..000000000 --- a/src/excelant/testcases/org/apache/poi/ss/excelant/TestExcelAntSetDoubleCell.java +++ /dev/null @@ -1,66 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.excelant; - -import junit.framework.TestCase; - -import org.apache.poi.ss.excelant.util.ExcelAntWorkbookUtil; -import org.apache.poi.ss.excelant.util.ExcelAntWorkbookUtilFactory; - -public class TestExcelAntSetDoubleCell extends TestCase { - - private ExcelAntSetDoubleCell fixture ; - - private ExcelAntWorkbookUtil util ; - - private static final String mortgageCalculatorFileName = - BuildFileTest.getDataDir() + "/spreadsheet/mortgage-calculation.xls" ; - - @Override - public void setUp() { - fixture = new ExcelAntSetDoubleCell() ; - util = ExcelAntWorkbookUtilFactory.getInstance( - mortgageCalculatorFileName ) ; - fixture.setWorkbookUtil( util ) ; - } - - @Override - public void tearDown() { - fixture = null ; - } - - public void testSetDouble() { - String cellId = "'Sheet3'!$A$1" ; - double testValue = 1.1 ; - - fixture.setCell( cellId ) ; - fixture.setValue( testValue ) ; - - double value = fixture.getCellValue() ; - - assertTrue( value > 0 ) ; - assertEquals( testValue, value, 0.0 ) ; - - fixture.execute() ; - - double setValue = util.getCellAsDouble( cellId ) ; - - assertEquals( setValue, testValue, 0.0 ) ; - } - - -} diff --git a/src/excelant/testcases/org/apache/poi/ss/excelant/tests.xml b/src/excelant/testcases/org/apache/poi/ss/excelant/tests.xml deleted file mode 100644 index d387aab36..000000000 --- a/src/excelant/testcases/org/apache/poi/ss/excelant/tests.xml +++ /dev/null @@ -1,226 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/excelant/testcases/org/apache/poi/ss/excelant/util/ExcelAntWorkbookUtilTestHelper.java b/src/excelant/testcases/org/apache/poi/ss/excelant/util/ExcelAntWorkbookUtilTestHelper.java deleted file mode 100644 index 16189f1d5..000000000 --- a/src/excelant/testcases/org/apache/poi/ss/excelant/util/ExcelAntWorkbookUtilTestHelper.java +++ /dev/null @@ -1,50 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.excelant.util; - -import org.apache.poi.ss.formula.udf.UDFFinder; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Workbook; - -/** - * A helper class to allow testing of protected methods and constructors. - * - * @author jsvede - * - */ -public class ExcelAntWorkbookUtilTestHelper extends ExcelAntWorkbookUtil { - - public ExcelAntWorkbookUtilTestHelper(String fName) { - super(fName); - } - - public ExcelAntWorkbookUtilTestHelper(Workbook wb) { - super(wb); - } - - @Override - public UDFFinder getFunctions() { - return super.getFunctions(); - } - - @Override - public FormulaEvaluator getEvaluator(String excelFileName) { - return super.getEvaluator(excelFileName); - } - - -} diff --git a/src/excelant/testcases/org/apache/poi/ss/excelant/util/TestExcelAntEvaluationResult.java b/src/excelant/testcases/org/apache/poi/ss/excelant/util/TestExcelAntEvaluationResult.java deleted file mode 100644 index 9c9213e52..000000000 --- a/src/excelant/testcases/org/apache/poi/ss/excelant/util/TestExcelAntEvaluationResult.java +++ /dev/null @@ -1,76 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.excelant.util; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class TestExcelAntEvaluationResult { - private ExcelAntEvaluationResult fixture; - - private boolean completedWithError = false; - private boolean passed = false; - private double retValue = 1.1; - private String errMessage = "error message"; - private double delta = 2.2; - private String cellId = "testCell!$F$1"; - - @Before - public void setUp() { - fixture = new ExcelAntEvaluationResult(completedWithError, - passed, - retValue, - errMessage, - delta, - cellId); - } - - @After - public void tearDown() { - fixture = null; - } - - @Test - public void testCompletedWithErrorMessage() { - String errMsg = fixture.getErrorMessage(); - assertNotNull(errMsg); - assertEquals(errMsg, errMessage); - } - - @Test - public void testPassed() { - boolean passedValue = fixture.didTestPass(); - assertEquals(passedValue, passed); - } - - @Test - public void testDelta() { - double deltaValue = fixture.getDelta(); - assertEquals(deltaValue, delta, 0.0); - } - - @Test - public void testCellId() { - String cellIdValue = fixture.getCellName(); - assertNotNull(cellIdValue); - assertEquals(cellIdValue, cellId); - } -} diff --git a/src/excelant/testcases/org/apache/poi/ss/excelant/util/TestExcelAntWorkbookUtil.java b/src/excelant/testcases/org/apache/poi/ss/excelant/util/TestExcelAntWorkbookUtil.java deleted file mode 100644 index bf68c2481..000000000 --- a/src/excelant/testcases/org/apache/poi/ss/excelant/util/TestExcelAntWorkbookUtil.java +++ /dev/null @@ -1,358 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.excelant.util; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.util.Date; -import java.util.List; - -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.ss.examples.formula.CalculateMortgageFunction; -import org.apache.poi.ss.excelant.BuildFileTest; -import org.apache.poi.ss.formula.udf.UDFFinder; -import org.apache.poi.ss.usermodel.DateUtil; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.usermodel.WorkbookFactory; -import org.apache.tools.ant.BuildException; - -import junit.framework.TestCase; - -public class TestExcelAntWorkbookUtil extends TestCase { - - private static final String mortgageCalculatorFileName = - BuildFileTest.getDataDir() + "/spreadsheet/excelant.xls" ; - - private ExcelAntWorkbookUtilTestHelper fixture ; - - - @Override - public void tearDown() { - fixture = null ; - } - - public void testStringConstructor() { - fixture = new ExcelAntWorkbookUtilTestHelper( - mortgageCalculatorFileName); - - assertNotNull(fixture); - } - - public void testLoadNotExistingFile() { - try { - assertNotNull(new ExcelAntWorkbookUtilTestHelper( - "notexistingFile" )); - fail("Should catch exception here"); - } catch (BuildException e) { - assertTrue(e.getMessage().contains("notexistingFile")); - } - } - - public void testWorkbookConstructor() throws InvalidFormatException, IOException { - File workbookFile = new File(mortgageCalculatorFileName); - FileInputStream fis = new FileInputStream(workbookFile); - Workbook workbook = WorkbookFactory.create(fis); - - fixture = new ExcelAntWorkbookUtilTestHelper(workbook); - - assertNotNull(fixture); - } - - public void testAddFunction() { - fixture = new ExcelAntWorkbookUtilTestHelper( - mortgageCalculatorFileName); - - assertNotNull(fixture); - - fixture.addFunction("h2_ZFactor", new CalculateMortgageFunction()); - - UDFFinder functions = fixture.getFunctions(); - - assertNotNull(functions); - assertNotNull(functions.findFunction("h2_ZFactor")); - } - - public void testAddFunctionClassName() throws Exception { - fixture = new ExcelAntWorkbookUtilTestHelper( - mortgageCalculatorFileName); - - assertNotNull(fixture); - - fixture.addFunction("h2_ZFactor", CalculateMortgageFunction.class.getName()); - - UDFFinder functions = fixture.getFunctions(); - - assertNotNull(functions); - assertNotNull(functions.findFunction("h2_ZFactor")); - } - - public void testAddFunctionInvalidClassName() throws Exception { - fixture = new ExcelAntWorkbookUtilTestHelper( - mortgageCalculatorFileName); - - assertNotNull(fixture); - - fixture.addFunction("h2_ZFactor", String.class.getName()); - - UDFFinder functions = fixture.getFunctions(); - - assertNotNull(functions); - assertNull(functions.findFunction("h2_ZFactor")); - } - - public void testGetWorkbook() { - fixture = new ExcelAntWorkbookUtilTestHelper( - mortgageCalculatorFileName); - - assertNotNull(fixture); - - Workbook workbook = fixture.getWorkbook(); - - assertNotNull(workbook); - } - - public void testFileName() { - fixture = new ExcelAntWorkbookUtilTestHelper( - mortgageCalculatorFileName); - - assertNotNull(fixture); - - String fileName = fixture.getFileName(); - - assertNotNull(fileName); - - assertEquals(mortgageCalculatorFileName, fileName); - - } - - public void testGetEvaluator() { - fixture = new ExcelAntWorkbookUtilTestHelper( - mortgageCalculatorFileName); - - FormulaEvaluator evaluator = fixture.getEvaluator( - mortgageCalculatorFileName); - - assertNotNull(evaluator); - } - - public void testGetEvaluatorWithUDF() { - fixture = new ExcelAntWorkbookUtilTestHelper( - mortgageCalculatorFileName); - - fixture.addFunction("h2_ZFactor", new CalculateMortgageFunction()); - - FormulaEvaluator evaluator = fixture.getEvaluator( - mortgageCalculatorFileName); - - assertNotNull(evaluator); - } - - public void testGetEvaluatorXLSX() { - fixture = new ExcelAntWorkbookUtilTestHelper( - BuildFileTest.getDataDir() + "/spreadsheet/sample.xlsx"); - - FormulaEvaluator evaluator = fixture.getEvaluator( - BuildFileTest.getDataDir() + "/spreadsheet/sample.xlsx"); - - assertNotNull(evaluator); - } - - public void testGetEvaluatorXLSXWithFunction() { - fixture = new ExcelAntWorkbookUtilTestHelper( - BuildFileTest.getDataDir() + "/spreadsheet/sample.xlsx"); - - fixture.addFunction("h2_ZFactor", new CalculateMortgageFunction()); - - FormulaEvaluator evaluator = fixture.getEvaluator( - BuildFileTest.getDataDir() + "/spreadsheet/sample.xlsx"); - - assertNotNull(evaluator); - } - - public void testEvaluateCell() { - String cell = "'MortgageCalculator'!B4" ; - double expectedValue = 790.79 ; - double precision = 0.1 ; - - fixture = new ExcelAntWorkbookUtilTestHelper( - mortgageCalculatorFileName); - - ExcelAntEvaluationResult result = fixture.evaluateCell(cell, - expectedValue, - precision); - - //System.out.println(result); - assertTrue("Had:" + result.toString(), result.toString().contains("evaluationCompletedWithError=false")); - assertTrue("Had:" + result.toString(), result.toString().contains("returnValue=790.79")); - assertTrue("Had:" + result.toString(), result.toString().contains("cellName='MortgageCalculator'!B4")); - assertFalse(result.toString().contains("#N/A")); - - assertFalse(result.evaluationCompleteWithError()); - assertTrue(result.didTestPass()); - } - - public void testEvaluateCellFailedPrecision() { - String cell = "'MortgageCalculator'!B4" ; - double expectedValue = 790.79 ; - double precision = 0.0000000000001 ; - - fixture = new ExcelAntWorkbookUtilTestHelper( - mortgageCalculatorFileName); - - ExcelAntEvaluationResult result = fixture.evaluateCell(cell, - expectedValue, - precision); - - //System.out.println(result); - assertTrue("Had:" + result.toString(), result.toString().contains("evaluationCompletedWithError=false")); - assertTrue("Had:" + result.toString(), result.toString().contains("returnValue=790.79")); - assertTrue("Had:" + result.toString(), result.toString().contains("cellName='MortgageCalculator'!B4")); - assertFalse("Should not see an error, but had:" + result.toString(), result.toString().contains("#")); - - assertFalse(result.evaluationCompleteWithError()); - assertFalse(result.didTestPass()); - } - - public void testEvaluateCellWithError() { - String cell = "'ErrorCell'!A1" ; - double expectedValue = 790.79 ; - double precision = 0.1 ; - - fixture = new ExcelAntWorkbookUtilTestHelper( - mortgageCalculatorFileName); - - ExcelAntEvaluationResult result = fixture.evaluateCell(cell, - expectedValue, - precision); - - System.out.println(result); - assertTrue("Had:" + result.toString(), result.toString().contains("evaluationCompletedWithError=true")); - assertTrue("Had:" + result.toString(), result.toString().contains("returnValue=0.0")); - assertTrue("Had:" + result.toString(), result.toString().contains("cellName='ErrorCell'!A1")); - assertTrue("Had:" + result.toString(), result.toString().contains("#N/A")); - - assertTrue(result.evaluationCompleteWithError()); - assertFalse(result.didTestPass()); - } - - public void testGetSheets() { - fixture = new ExcelAntWorkbookUtilTestHelper( - mortgageCalculatorFileName); - - List sheets = fixture.getSheets(); - - assertNotNull(sheets); - assertEquals(sheets.size(), 3); - } - - public void testSetString() { - String cell = "'MortgageCalculator'!C14" ; - String cellValue = "testString" ; - - fixture = new ExcelAntWorkbookUtilTestHelper( - mortgageCalculatorFileName); - - fixture.setStringValue(cell, cellValue); - - String value = fixture.getCellAsString(cell); - - assertNotNull(value); - assertEquals(cellValue, value); - } - - public void testSetNotExistingSheet() { - String cell = "'NotexistingSheet'!C14" ; - - fixture = new ExcelAntWorkbookUtilTestHelper( - mortgageCalculatorFileName); - try { - fixture.setStringValue(cell, "some"); - fail("Should catch exception here"); - } catch (BuildException e) { - assertTrue(e.getMessage().contains("NotexistingSheet")); - } - } - - public void testSetFormula() { - String cell = "'MortgageCalculator'!C14" ; - String cellValue = "SUM(B14:B18)" ; - - fixture = new ExcelAntWorkbookUtilTestHelper( - mortgageCalculatorFileName); - - fixture.setFormulaValue(cell, cellValue); - - double value = fixture.getCellAsDouble(cell); - - assertNotNull(value); - assertEquals(0.0, value); - } - - public void testSetDoubleValue() { - String cell = "'MortgageCalculator'!C14" ; - double cellValue = 1.2; - - fixture = new ExcelAntWorkbookUtilTestHelper( - mortgageCalculatorFileName); - - fixture.setDoubleValue(cell, cellValue); - - Double value = fixture.getCellAsDouble(cell); - - assertNotNull(value); - assertEquals(cellValue, value); - } - - public void testSetDate() { - String cell = "'MortgageCalculator'!C14" ; - Date cellValue = new Date(); - - fixture = new ExcelAntWorkbookUtilTestHelper( - mortgageCalculatorFileName); - - fixture.setDateValue(cell, cellValue); - - double value = fixture.getCellAsDouble(cell); - - assertNotNull(value); - assertEquals(DateUtil.getExcelDate(cellValue, false), value); - } - - public void testGetNonexistingString() { - String cell = "'MortgageCalculator'!C33" ; - - fixture = new ExcelAntWorkbookUtilTestHelper( - mortgageCalculatorFileName); - - String value = fixture.getCellAsString(cell); - - assertEquals("", value); - } - - public void testGetNonexistingDouble() { - String cell = "'MortgageCalculator'!C33" ; - - fixture = new ExcelAntWorkbookUtilTestHelper( - mortgageCalculatorFileName); - - double value = fixture.getCellAsDouble(cell); - - assertEquals(0.0, value); - } -} diff --git a/src/excelant/testcases/org/apache/poi/ss/excelant/util/TestExcelAntWorkbookUtilFactory.java b/src/excelant/testcases/org/apache/poi/ss/excelant/util/TestExcelAntWorkbookUtilFactory.java deleted file mode 100644 index b69449a5f..000000000 --- a/src/excelant/testcases/org/apache/poi/ss/excelant/util/TestExcelAntWorkbookUtilFactory.java +++ /dev/null @@ -1,72 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.excelant.util; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import org.apache.poi.ss.excelant.BuildFileTest; -import org.junit.Test; - - -/** - * Tests for the ExcelAntWorbookUtilFactory. - * - * @author Jon Svede (jon [at] loquatic [dot] com) - * @author Brian Bush (brian [dot] bush [at] nrel [dot] gov) - * - */ -public class TestExcelAntWorkbookUtilFactory { - - private static final String mortgageCalculatorWorkbookFile = - BuildFileTest.getDataDir() + "/spreadsheet/mortgage-calculation.xls" ; - - - /** - * Simple test to determine if the factory properly returns an non-null - * instance of the ExcelAntWorkbookUtil class. - */ - @Test - public void testGetNewWorkbookUtilInstance() { - ExcelAntWorkbookUtil util = ExcelAntWorkbookUtilFactory.getInstance( - mortgageCalculatorWorkbookFile) ; - - assertNotNull(util) ; - } - - - /** - * Test whether or not the factory will properly return the same reference - * to an ExcelAnt WorkbookUtil when two different Strings, that point to - * the same resource, are passed in. - */ - @Test - public void testVerifyEquivalence() { - String sameFileName = BuildFileTest.getDataDir() + "/spreadsheet/mortgage-calculation.xls" ; - - ExcelAntWorkbookUtil util = ExcelAntWorkbookUtilFactory.getInstance( - mortgageCalculatorWorkbookFile) ; - - ExcelAntWorkbookUtil util2 = ExcelAntWorkbookUtilFactory.getInstance( - sameFileName) ; - - assertNotNull(util) ; - assertNotNull(util2) ; - - assertEquals(util, util2) ; - } -} diff --git a/src/integrationtest/build.xml b/src/integrationtest/build.xml deleted file mode 100644 index 6af90e77b..000000000 --- a/src/integrationtest/build.xml +++ /dev/null @@ -1,157 +0,0 @@ - - - - - Test-Ant file which verifies that the Apache POI distribution build sources can be compiled successfully. - -Before running this, you should execute the "assemble" target in the main build.xml to have the packaged files created correctly. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/integrationtest/commons-logging.properties b/src/integrationtest/commons-logging.properties deleted file mode 100644 index 45db0a7a8..000000000 --- a/src/integrationtest/commons-logging.properties +++ /dev/null @@ -1,16 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -log4j.configuration=log4j.properties \ No newline at end of file diff --git a/src/integrationtest/log4j.properties b/src/integrationtest/log4j.properties deleted file mode 100644 index f2aea6851..000000000 --- a/src/integrationtest/log4j.properties +++ /dev/null @@ -1,40 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -log4j.rootLogger=info, R - -log4j.appender.R=org.apache.log4j.RollingFileAppender -log4j.appender.R.File=build/test-integration.log - -log4j.appender.R.MaxFileSize=1000KB -# Keep one backup file -log4j.appender.R.MaxBackupIndex=5 - -log4j.appender.R.layout=org.apache.log4j.PatternLayout -log4j.appender.R.layout.ConversionPattern=%d [%t] %-5p %c - %m%n - -log4j.logger.org.apache.poi.poifs.nio.FileBackedDataSource=ERROR -log4j.logger.org.apache.poi.hdgf.chunks.Chunk=FATAL -log4j.logger.org.apache.poi.hpsf.CodePageString=ERROR -log4j.logger.org.apache.poi.hdgf.chunks.ChunkFactory=ERROR -log4j.logger.org.apache.poi.hslf.model.textproperties.BitMaskTextProp=ERROR -log4j.logger.org.apache.poi.util.JvmBugs=ERROR -log4j.logger.org.apache.poi.hslf.usermodel.HSLFTextParagraph=ERROR -log4j.logger.org.apache.poi.openxml4j.opc.ZipPackage=ERROR -log4j.logger.org.apache.poi.POIDocument=WARN -log4j.logger.org.apache.poi.openxml4j.opc.OPCPackage=ERROR -log4j.logger.org.apache.poi.xssf.usermodel.XSSFWorkbook=ERROR -log4j.logger.org.apache.poi.hslf.usermodel.HSLFGroupShape=WARN -log4j.logger.org.apache.poi.hslf.record.Record=ERROR \ No newline at end of file diff --git a/src/integrationtest/org/apache/poi/HeapDump.java b/src/integrationtest/org/apache/poi/HeapDump.java deleted file mode 100644 index 625527d84..000000000 --- a/src/integrationtest/org/apache/poi/HeapDump.java +++ /dev/null @@ -1,62 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi; - -import com.sun.management.HotSpotDiagnosticMXBean; - -import java.io.IOException; -import java.lang.management.ManagementFactory; - -public class HeapDump { - // This is the name of the HotSpot Diagnostic MBean - private static final String HOTSPOT_BEAN_NAME = - "com.sun.management:type=HotSpotDiagnostic"; - - // field to store the hotspot diagnostic MBean - private static volatile HotSpotDiagnosticMXBean hotspotMBean; - - /** - * Call this method from your application whenever you - * want to dump the heap snapshot into a file. - * - * @param fileName name of the heap dump file - * @param live flag that tells whether to dump - * only the live objects - */ - public static void dumpHeap(String fileName, boolean live) throws IOException { - // initialize hotspot diagnostic MBean - initHotspotMBean(); - hotspotMBean.dumpHeap(fileName, live); - } - - // initialize the hotspot diagnostic MBean field - private static void initHotspotMBean() throws IOException { - if (hotspotMBean == null) { - synchronized (HeapDump.class) { - if (hotspotMBean == null) { - hotspotMBean = getHotspotMBean(); - } - } - } - } - - // get the hotspot diagnostic MBean from the platform MBean server - private static HotSpotDiagnosticMXBean getHotspotMBean() throws IOException { - return ManagementFactory.newPlatformMXBeanProxy(ManagementFactory.getPlatformMBeanServer(), - HOTSPOT_BEAN_NAME, HotSpotDiagnosticMXBean.class); - } -} diff --git a/src/integrationtest/org/apache/poi/TestAllFiles.java b/src/integrationtest/org/apache/poi/TestAllFiles.java deleted file mode 100644 index e61df18ce..000000000 --- a/src/integrationtest/org/apache/poi/TestAllFiles.java +++ /dev/null @@ -1,434 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi; - - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; - -import java.io.BufferedInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; - -import org.apache.poi.stress.AbstractFileHandler; -import org.apache.poi.stress.FileHandler; -import org.apache.poi.stress.HDGFFileHandler; -import org.apache.poi.stress.HMEFFileHandler; -import org.apache.poi.stress.HPBFFileHandler; -import org.apache.poi.stress.HPSFFileHandler; -import org.apache.poi.stress.HSLFFileHandler; -import org.apache.poi.stress.HSMFFileHandler; -import org.apache.poi.stress.HSSFFileHandler; -import org.apache.poi.stress.HWPFFileHandler; -import org.apache.poi.stress.OPCFileHandler; -import org.apache.poi.stress.POIFSFileHandler; -import org.apache.poi.stress.XDGFFileHandler; -import org.apache.poi.stress.XSLFFileHandler; -import org.apache.poi.stress.XSSFBFileHandler; -import org.apache.poi.stress.XSSFFileHandler; -import org.apache.poi.stress.XWPFFileHandler; -import org.apache.tools.ant.DirectoryScanner; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; - -/** - * This is an integration test which performs various actions on all stored test-files and tries - * to reveal problems which are introduced, but not covered (yet) by unit tests. - * - * This test looks for any file under the test-data directory and tries to do some useful - * processing with it based on it's type. - * - * The test is implemented as a junit {@link Parameterized} test, which leads - * to one test-method call for each file (currently around 950 files are handled). - * - * There is a a mapping of extension to implementations of the interface - * {@link FileHandler} which defines how the file is loaded and which actions are - * tried with the file. - * - * The test can be expanded by adding more actions to the FileHandlers, this automatically - * applies the action to any such file in our test-data repository. - * - * There is also a list of files that should actually fail. - * - * Note: It is also a test-failure if a file that is expected to fail now actually works, - * i.e. if a bug was fixed in POI itself, the file should be removed from the expected-failures - * here as well! This is to ensure that files that should not work really do not work, e.g. - * that we do not remove expected sanity checks. - */ -@RunWith(Parameterized.class) -public class TestAllFiles { - - private static final File ROOT_DIR = new File("test-data"); - - static final String[] SCAN_EXCLUDES = new String[] { "**/.svn/**", "lost+found" }; - - // map file extensions to the actual mappers - static final Map HANDLERS = new HashMap(); - static { - // Excel - HANDLERS.put(".xls", new HSSFFileHandler()); - HANDLERS.put(".xlsx", new XSSFFileHandler()); - HANDLERS.put(".xlsm", new XSSFFileHandler()); - HANDLERS.put(".xltx", new XSSFFileHandler()); - HANDLERS.put(".xlsb", new XSSFBFileHandler()); - - // Word - HANDLERS.put(".doc", new HWPFFileHandler()); - HANDLERS.put(".docx", new XWPFFileHandler()); - HANDLERS.put(".dotx", new XWPFFileHandler()); - HANDLERS.put(".docm", new XWPFFileHandler()); - - // OpenXML4J files - HANDLERS.put(".ooxml", new OPCFileHandler()); // OPCPackage - HANDLERS.put(".zip", new OPCFileHandler()); // OPCPackage - - // Powerpoint - HANDLERS.put(".ppt", new HSLFFileHandler()); - HANDLERS.put(".pptx", new XSLFFileHandler()); - HANDLERS.put(".pptm", new XSLFFileHandler()); - HANDLERS.put(".ppsm", new XSLFFileHandler()); - HANDLERS.put(".ppsx", new XSLFFileHandler()); - HANDLERS.put(".thmx", new XSLFFileHandler()); - HANDLERS.put(".potx", new XSLFFileHandler()); - - // Outlook - HANDLERS.put(".msg", new HSMFFileHandler()); - - // Publisher - HANDLERS.put(".pub", new HPBFFileHandler()); - - // Visio - binary - HANDLERS.put(".vsd", new HDGFFileHandler()); - - // Visio - ooxml - HANDLERS.put(".vsdm", new XDGFFileHandler()); - HANDLERS.put(".vsdx", new XDGFFileHandler()); - HANDLERS.put(".vssm", new XDGFFileHandler()); - HANDLERS.put(".vssx", new XDGFFileHandler()); - HANDLERS.put(".vstm", new XDGFFileHandler()); - HANDLERS.put(".vstx", new XDGFFileHandler()); - - // Visio - not handled yet - HANDLERS.put(".vst", new NullFileHandler()); - HANDLERS.put(".vss", new NullFileHandler()); - - // POIFS - HANDLERS.put(".ole2", new POIFSFileHandler()); - - // Microsoft Admin Template? - HANDLERS.put(".adm", new HPSFFileHandler()); - - // Microsoft TNEF - HANDLERS.put(".dat", new HMEFFileHandler()); - - // TODO: are these readable by some of the formats? - HANDLERS.put(".shw", new NullFileHandler()); - HANDLERS.put(".zvi", new NullFileHandler()); - HANDLERS.put(".mpp", new NullFileHandler()); - HANDLERS.put(".qwp", new NullFileHandler()); - HANDLERS.put(".wps", new NullFileHandler()); - HANDLERS.put(".bin", new NullFileHandler()); - HANDLERS.put(".xps", new NullFileHandler()); - HANDLERS.put(".sldprt", new NullFileHandler()); - HANDLERS.put(".mdb", new NullFileHandler()); - HANDLERS.put(".vml", new NullFileHandler()); - - // ignore some file types, images, other formats, ... - HANDLERS.put(".txt", new NullFileHandler()); - HANDLERS.put(".pdf", new NullFileHandler()); - HANDLERS.put(".rtf", new NullFileHandler()); - HANDLERS.put(".gif", new NullFileHandler()); - HANDLERS.put(".html", new NullFileHandler()); - HANDLERS.put(".png", new NullFileHandler()); - HANDLERS.put(".wmf", new NullFileHandler()); - HANDLERS.put(".emf", new NullFileHandler()); - HANDLERS.put(".dib", new NullFileHandler()); - HANDLERS.put(".svg", new NullFileHandler()); - HANDLERS.put(".pict", new NullFileHandler()); - HANDLERS.put(".jpg", new NullFileHandler()); - HANDLERS.put(".jpeg", new NullFileHandler()); - HANDLERS.put(".tif", new NullFileHandler()); - HANDLERS.put(".tiff", new NullFileHandler()); - HANDLERS.put(".wav", new NullFileHandler()); - HANDLERS.put(".pfx", new NullFileHandler()); - HANDLERS.put(".xml", new NullFileHandler()); - HANDLERS.put(".csv", new NullFileHandler()); - HANDLERS.put(".ods", new NullFileHandler()); - // VBA source files - HANDLERS.put(".vba", new NullFileHandler()); - HANDLERS.put(".bas", new NullFileHandler()); - HANDLERS.put(".frm", new NullFileHandler()); - HANDLERS.put(".frx", new NullFileHandler()); //binary - HANDLERS.put(".cls", new NullFileHandler()); - - // map some files without extension - HANDLERS.put("spreadsheet/BigSSTRecord", new NullFileHandler()); - HANDLERS.put("spreadsheet/BigSSTRecord2", new NullFileHandler()); - HANDLERS.put("spreadsheet/BigSSTRecord2CR1", new NullFileHandler()); - HANDLERS.put("spreadsheet/BigSSTRecord2CR2", new NullFileHandler()); - HANDLERS.put("spreadsheet/BigSSTRecord2CR3", new NullFileHandler()); - HANDLERS.put("spreadsheet/BigSSTRecord2CR4", new NullFileHandler()); - HANDLERS.put("spreadsheet/BigSSTRecord2CR5", new NullFileHandler()); - HANDLERS.put("spreadsheet/BigSSTRecord2CR6", new NullFileHandler()); - HANDLERS.put("spreadsheet/BigSSTRecord2CR7", new NullFileHandler()); - HANDLERS.put("spreadsheet/BigSSTRecordCR", new NullFileHandler()); - HANDLERS.put("spreadsheet/test_properties1", new NullFileHandler()); - } - - private static Set unmodifiableHashSet(String... a) { - return Collections.unmodifiableSet(hashSet(a)); - } - private static Set hashSet(String... a) { - return new HashSet(Arrays.asList(a)); - } - - // Old Word Documents where we can at least extract some text - private static final Set OLD_FILES = unmodifiableHashSet( - "document/Bug49933.doc", - "document/Bug51944.doc", - "document/Word6.doc", - "document/Word6_sections.doc", - "document/Word6_sections2.doc", - "document/Word95.doc", - "document/word95err.doc", - "document/Bug60936.doc", - "document/Bug60942.doc", - "document/Bug60942b.doc", - "hpsf/TestMickey.doc", - "document/52117.doc" - ); - - private static final Set EXPECTED_FAILURES = unmodifiableHashSet( - // password protected files - "spreadsheet/password.xls", - "spreadsheet/protected_passtika.xlsx", - "spreadsheet/51832.xls", - "document/PasswordProtected.doc", - "slideshow/Password_Protected-hello.ppt", - "slideshow/Password_Protected-56-hello.ppt", - "slideshow/Password_Protected-np-hello.ppt", - "slideshow/cryptoapi-proc2356.ppt", - //"document/bug53475-password-is-pass.docx", - //"document/bug53475-password-is-solrcell.docx", - "spreadsheet/xor-encryption-abc.xls", - "spreadsheet/35897-type4.xls", - //"poifs/protect.xlsx", - //"poifs/protected_sha512.xlsx", - //"poifs/extenxls_pwd123.xlsx", - //"poifs/protected_agile.docx", - "spreadsheet/58616.xlsx", - "poifs/60320-protected.xlsx", - - // TODO: fails XMLExportTest, is this ok? - "spreadsheet/CustomXMLMapping-singleattributenamespace.xlsx", - "spreadsheet/55864.xlsx", - "spreadsheet/57890.xlsx", - - // TODO: these fail now with some NPE/file read error because we now try to compute every value via Cell.toString()! - "spreadsheet/44958.xls", - "spreadsheet/44958_1.xls", - "spreadsheet/testArraysAndTables.xls", - - // TODO: good to ignore? - "spreadsheet/sample-beta.xlsx", - "document/cpansearch.perl.org_src_tobyink_acme-rundoc-0.001_word-lib_hello_world.docm", - - // This is actually a spreadsheet! - "hpsf/TestRobert_Flaherty.doc", - - // some files that are broken, eg Word 95, ... - "spreadsheet/43493.xls", - "spreadsheet/46904.xls", - "document/Bug50955.doc", - "document/57843.doc", - "slideshow/PPT95.ppt", - "openxml4j/OPCCompliance_CoreProperties_DCTermsNamespaceLimitedUseFAIL.docx", - "openxml4j/OPCCompliance_CoreProperties_DoNotUseCompatibilityMarkupFAIL.docx", - "openxml4j/OPCCompliance_CoreProperties_LimitedXSITypeAttribute_NotPresentFAIL.docx", - "openxml4j/OPCCompliance_CoreProperties_LimitedXSITypeAttribute_PresentWithUnauthorizedValueFAIL.docx", - "openxml4j/OPCCompliance_CoreProperties_OnlyOneCorePropertiesPartFAIL.docx", - "openxml4j/OPCCompliance_CoreProperties_UnauthorizedXMLLangAttributeFAIL.docx", - "openxml4j/OPCCompliance_DerivedPartNameFAIL.docx", - "openxml4j/invalid.xlsx", - "spreadsheet/54764-2.xlsx", // see TestXSSFBugs.bug54764() - "spreadsheet/54764.xlsx", // see TestXSSFBugs.bug54764() - "poifs/unknown_properties.msg", // POIFS properties corrupted - "poifs/only-zero-byte-streams.ole2", // No actual contents - "spreadsheet/poc-xmlbomb.xlsx", // contains xml-entity-expansion - "spreadsheet/poc-xmlbomb-empty.xlsx", // contains xml-entity-expansion - "spreadsheet/poc-shared-strings.xlsx", // contains shared-string-entity-expansion - "spreadsheet/60255_extra_drawingparts.xlsx", // Non-drawing drawing - - // old Excel files, which we only support simple text extraction of - "spreadsheet/testEXCEL_2.xls", - "spreadsheet/testEXCEL_3.xls", - "spreadsheet/testEXCEL_4.xls", - "spreadsheet/testEXCEL_5.xls", - "spreadsheet/testEXCEL_95.xls", - "spreadsheet/59074.xls", - "spreadsheet/60284.xls", - - // OOXML Strict is not yet supported, see bug #57699 - "spreadsheet/SampleSS.strict.xlsx", - "spreadsheet/SimpleStrict.xlsx", - "spreadsheet/sample.strict.xlsx", - "spreadsheet/57914.xlsx", - - // non-TNEF files - "ddf/Container.dat", - "ddf/47143.dat", - - // sheet cloning errors - "spreadsheet/47813.xlsx", - "spreadsheet/56450.xls", - "spreadsheet/OddStyleRecord.xls", - "spreadsheet/WithChartSheet.xlsx", - "spreadsheet/chart_sheet.xlsx", - "spreadsheet/SimpleScatterChart.xlsx" - ); - - private static final Set IGNORED = unmodifiableHashSet( - // need JDK8+ - https://bugs.openjdk.java.net/browse/JDK-8038081 - "slideshow/42474-2.ppt", - // OPC handler works / XSSF handler fails - "spreadsheet/57181.xlsm" - ); - - @Parameters(name="{index}: {0} using {1}") - public static Iterable files() { - DirectoryScanner scanner = new DirectoryScanner(); - scanner.setBasedir(ROOT_DIR); - scanner.setExcludes(SCAN_EXCLUDES); - - scanner.scan(); - - System.out.println("Handling " + scanner.getIncludedFiles().length + " files"); - - List files = new ArrayList(); - for(String file : scanner.getIncludedFiles()) { - file = file.replace('\\', '/'); // ... failures/handlers lookup doesn't work on windows otherwise - if (IGNORED.contains(file)) { - System.out.println("Ignoring " + file); - continue; - } - FileHandler handler = HANDLERS.get(getExtension(file)); - files.add(new Object[] { file, handler }); - - // for some file-types also run OPCFileHandler - if(handler instanceof XSSFFileHandler || - handler instanceof XWPFFileHandler || - handler instanceof XSLFFileHandler || - handler instanceof XDGFFileHandler) { - files.add(new Object[] { file, HANDLERS.get(".ooxml") }); - } - } - - return files; - } - - @SuppressWarnings("DefaultAnnotationParam") - @Parameter(value=0) - public String file; - - @Parameter(value=1) - public FileHandler handler; - - @Test - public void testAllFiles() throws Exception { - System.out.println("Reading " + file + " with " + handler.getClass()); - assertNotNull("Unknown file extension for file: " + file + ": " + getExtension(file), handler); - File inputFile = new File(ROOT_DIR, file); - - try { - InputStream stream = new BufferedInputStream(new FileInputStream(inputFile), 64*1024); - try { - handler.handleFile(stream); - - assertFalse("Expected to fail for file " + file + " and handler " + handler + ", but did not fail!", - OLD_FILES.contains(file)); - } finally { - stream.close(); - } - - handler.handleExtracting(inputFile); - - // special cases where docx-handling breaks, but OPCPackage handling works - boolean ignoredOPC = (file.endsWith(".docx") || file.endsWith(".xlsx") || - file.endsWith(".xlsb") || file.endsWith(".pptx")) && - handler instanceof OPCFileHandler; - - assertFalse("Expected to fail for file " + file + " and handler " + handler + ", but did not fail!", - EXPECTED_FAILURES.contains(file) && !ignoredOPC); - } catch (OldFileFormatException e) { - // for old word files we should still support extracting text - if(OLD_FILES.contains(file)) { - handler.handleExtracting(inputFile); - } else { - // check if we expect failure for this file - if(!EXPECTED_FAILURES.contains(file) && !AbstractFileHandler.EXPECTED_EXTRACTOR_FAILURES.contains(file)) { - System.out.println("Failed: " + file); - throw new Exception("While handling " + file, e); - } - } - } catch (Exception e) { - // check if we expect failure for this file - if(!EXPECTED_FAILURES.contains(file) && !AbstractFileHandler.EXPECTED_EXTRACTOR_FAILURES.contains(file)) { - System.out.println("Failed: " + file); - throw new Exception("While handling " + file, e); - } - } - - // let some file handlers do additional stuff - handler.handleAdditional(inputFile); - } - - static String getExtension(String file) { - int pos = file.lastIndexOf('.'); - if(pos == -1 || pos == file.length()-1) { - return file; - } - - return file.substring(pos).toLowerCase(Locale.ROOT); - } - - private static class NullFileHandler implements FileHandler { - @Override - public void handleFile(InputStream stream) throws Exception { - } - - @Override - public void handleExtracting(File file) throws Exception { - } - - @Override - public void handleAdditional(File file) throws Exception { - } - } -} diff --git a/src/integrationtest/org/apache/poi/hssf/usermodel/RecordsStresser.java b/src/integrationtest/org/apache/poi/hssf/usermodel/RecordsStresser.java deleted file mode 100644 index 1b712f788..000000000 --- a/src/integrationtest/org/apache/poi/hssf/usermodel/RecordsStresser.java +++ /dev/null @@ -1,80 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hssf.usermodel; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.io.FileInputStream; -import java.io.InputStream; -import java.util.List; - -import org.apache.poi.hssf.record.Record; -import org.junit.Test; - -/** - * Needs to be implemented in this package to have access to - * HSSFWorkbook.getWorkbook() - */ -public class RecordsStresser { - public static void handleWorkbook(HSSFWorkbook wb) { - List records = wb.getWorkbook().getRecords(); - for(Record record : records) { - // some Records do not implement clone ?! - // equals instead of instanceof is on purpose here to only skip exactly this class and not any derived ones -// if(record.getClass().equals(InterfaceHdrRecord.class) || -// record.getClass().equals(MMSRecord.class) || -// record.getClass().equals(InterfaceEndRecord.class) || -// record.getClass().equals(WriteAccessRecord.class) || -// record.getClass().equals(CodepageRecord.class) || -// record.getClass().equals(DSFRecord.class)) { -// continue; -// } - try { - Record newRecord = (Record) record.clone(); - - assertEquals("Expecting the same class back from clone(), but had Record of type " + record.getClass() + " and got back a " + newRecord.getClass() + " from clone()", - record.getClass(), newRecord.getClass()); - - byte[] origBytes = record.serialize(); - byte[] newBytes = newRecord.serialize(); - - assertArrayEquals("Record of type " + record.getClass() + " should return the same byte array via the clone() method, but did return a different array", - origBytes, newBytes); - } catch (CloneNotSupportedException e) { - throw new RuntimeException(e); - } catch (RuntimeException e) { - // some Records do not implement clone, ignore those for now - assertTrue(e.getMessage().contains("needs to define a clone method")); - } - } - } - - // a test-case to test this locally without executing the full TestAllFiles - @Test - public void test() throws Exception { - InputStream stream = new FileInputStream("test-data/spreadsheet/15556.xls"); - try { - HSSFWorkbook wb = new HSSFWorkbook(stream); - handleWorkbook(wb); - wb.close(); - } finally { - stream.close(); - } - } -} diff --git a/src/integrationtest/org/apache/poi/stress/AbstractFileHandler.java b/src/integrationtest/org/apache/poi/stress/AbstractFileHandler.java deleted file mode 100644 index 8bd34acda..000000000 --- a/src/integrationtest/org/apache/poi/stress/AbstractFileHandler.java +++ /dev/null @@ -1,142 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.stress; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.HashSet; -import java.util.Set; - -import org.apache.poi.POIOLE2TextExtractor; -import org.apache.poi.POITextExtractor; -import org.apache.poi.extractor.ExtractorFactory; -import org.apache.poi.hpsf.extractor.HPSFPropertiesExtractor; -import org.apache.poi.openxml4j.exceptions.OpenXML4JException; -import org.apache.xmlbeans.XmlException; - -public abstract class AbstractFileHandler implements FileHandler { - public static final Set EXPECTED_EXTRACTOR_FAILURES = new HashSet(); - static { - // password protected files - EXPECTED_EXTRACTOR_FAILURES.add("document/bug53475-password-is-pass.docx"); - EXPECTED_EXTRACTOR_FAILURES.add("poifs/extenxls_pwd123.xlsx"); - EXPECTED_EXTRACTOR_FAILURES.add("poifs/protect.xlsx"); - EXPECTED_EXTRACTOR_FAILURES.add("poifs/protected_agile.docx"); - EXPECTED_EXTRACTOR_FAILURES.add("poifs/protected_sha512.xlsx"); - - // unsupported file-types, no supported OLE2 parts - EXPECTED_EXTRACTOR_FAILURES.add("hmef/quick-winmail.dat"); - EXPECTED_EXTRACTOR_FAILURES.add("hmef/winmail-sample1.dat"); - EXPECTED_EXTRACTOR_FAILURES.add("hmef/bug52400-winmail-simple.dat"); - EXPECTED_EXTRACTOR_FAILURES.add("hmef/bug52400-winmail-with-attachments.dat"); - EXPECTED_EXTRACTOR_FAILURES.add("hpsf/Test0313rur.adm"); - EXPECTED_EXTRACTOR_FAILURES.add("poifs/Notes.ole2"); - } - - @Override - public void handleExtracting(File file) throws Exception { - boolean before = ExtractorFactory.getThreadPrefersEventExtractors(); - try { - ExtractorFactory.setThreadPrefersEventExtractors(true); - handleExtractingInternal(file); - - ExtractorFactory.setThreadPrefersEventExtractors(false); - handleExtractingInternal(file); - } finally { - ExtractorFactory.setThreadPrefersEventExtractors(before); - } - - /* Did fail for some documents with special XML contents... - try { - OOXMLPrettyPrint.main(new String[] { file.getAbsolutePath(), - "/tmp/pretty-" + file.getName() }); - } catch (ZipException e) { - // ignore, not a Zip/OOXML file - }*/ - } - - private void handleExtractingInternal(File file) throws Exception { - long length = file.length(); - long modified = file.lastModified(); - - POITextExtractor extractor = ExtractorFactory.createExtractor(file); - try { - assertNotNull("Should get a POITextExtractor but had none for file " + file, extractor); - - assertNotNull("Should get some text but had none for file " + file, extractor.getText()); - - // also try metadata - @SuppressWarnings("resource") - POITextExtractor metadataExtractor = extractor.getMetadataTextExtractor(); - assertNotNull(metadataExtractor.getText()); - - assertFalse("Expected Extraction to fail for file " + file + " and handler " + this + ", but did not fail!", - EXPECTED_EXTRACTOR_FAILURES.contains(file.getParentFile().getName() + "/" + file.getName())); - - assertEquals("File should not be modified by extractor", length, file.length()); - assertEquals("File should not be modified by extractor", modified, file.lastModified()); - - handleExtractingAsStream(file); - - if(extractor instanceof POIOLE2TextExtractor) { - HPSFPropertiesExtractor hpsfExtractor = new HPSFPropertiesExtractor((POIOLE2TextExtractor)extractor); - try { - assertNotNull(hpsfExtractor.getDocumentSummaryInformationText()); - assertNotNull(hpsfExtractor.getSummaryInformationText()); - String text = hpsfExtractor.getText(); - //System.out.println(text); - assertNotNull(text); - } finally { - hpsfExtractor.close(); - } - } - } catch (IllegalArgumentException e) { - if(!EXPECTED_EXTRACTOR_FAILURES.contains(file.getParentFile().getName() + "/" + file.getName())) { - throw e; - } - } finally { - extractor.close(); - } - } - - private void handleExtractingAsStream(File file) throws IOException, OpenXML4JException, XmlException { - InputStream stream = new FileInputStream(file); - try { - POITextExtractor streamExtractor = ExtractorFactory.createExtractor(stream); - try { - assertNotNull(streamExtractor); - - assertNotNull(streamExtractor.getText()); - } finally { - streamExtractor.close(); - } - } finally { - stream.close(); - } - } - - @Override - public void handleAdditional(File file) throws Exception { - // by default we do nothing here - } -} diff --git a/src/integrationtest/org/apache/poi/stress/FileHandler.java b/src/integrationtest/org/apache/poi/stress/FileHandler.java deleted file mode 100644 index c1888e731..000000000 --- a/src/integrationtest/org/apache/poi/stress/FileHandler.java +++ /dev/null @@ -1,50 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.stress; - -import java.io.File; -import java.io.InputStream; - -/** - * Base interface for the various file types that are - * used in the stress testing. - */ -public interface FileHandler { - /** - * The FileHandler receives a stream ready for reading the - * file and should handle the content that is provided and - * try to read and interpret the data. - * - * Closing is handled by the framework outside this call. - * - * @param stream The input stream to read the file from. - * @throws Exception If an error happens in the file-specific handler - */ - void handleFile(InputStream stream) throws Exception; - - /** - * Ensures that extracting text from the given file - * is returning some text. - */ - void handleExtracting(File file) throws Exception; - - /** - * Allows to perform some additional work, e.g. run - * some of the example applications - */ - void handleAdditional(File file) throws Exception; -} diff --git a/src/integrationtest/org/apache/poi/stress/HDGFFileHandler.java b/src/integrationtest/org/apache/poi/stress/HDGFFileHandler.java deleted file mode 100644 index 758a3ad29..000000000 --- a/src/integrationtest/org/apache/poi/stress/HDGFFileHandler.java +++ /dev/null @@ -1,81 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.stress; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.hdgf.HDGFDiagram; -import org.apache.poi.hdgf.extractor.VisioTextExtractor; -import org.apache.poi.hdgf.streams.Stream; -import org.apache.poi.hdgf.streams.TrailerStream; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.junit.Test; - -public class HDGFFileHandler extends POIFSFileHandler { - @Override - public void handleFile(InputStream stream) throws IOException { - POIFSFileSystem poifs = new POIFSFileSystem(stream); - HDGFDiagram diagram = new HDGFDiagram(poifs); - Stream[] topLevelStreams = diagram.getTopLevelStreams(); - assertNotNull(topLevelStreams); - for(Stream str : topLevelStreams) { - assertTrue(str.getPointer().getLength() >= 0); - } - - TrailerStream trailerStream = diagram.getTrailerStream(); - assertNotNull(trailerStream); - assertTrue(trailerStream.getPointer().getLength() >= 0); - diagram.close(); - poifs.close(); - - // writing is not yet implemented... handlePOIDocument(diagram); - } - - // a test-case to test this locally without executing the full TestAllFiles - @Override - @Test - public void test() throws Exception { - File file = new File("test-data/diagram/44501.vsd"); - - InputStream stream = new FileInputStream(file); - try { - handleFile(stream); - } finally { - stream.close(); - } - - handleExtracting(file); - - stream = new FileInputStream(file); - try { - VisioTextExtractor extractor = new VisioTextExtractor(stream); - try { - assertNotNull(extractor.getText()); - } finally { - extractor.close(); - } - } finally { - stream.close(); - } - } -} diff --git a/src/integrationtest/org/apache/poi/stress/HMEFFileHandler.java b/src/integrationtest/org/apache/poi/stress/HMEFFileHandler.java deleted file mode 100644 index 9f492bf0e..000000000 --- a/src/integrationtest/org/apache/poi/stress/HMEFFileHandler.java +++ /dev/null @@ -1,60 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.stress; - -import static org.junit.Assert.assertNotNull; - -import java.io.FileInputStream; -import java.io.InputStream; - -import org.apache.poi.hmef.HMEFMessage; -import org.apache.poi.hmef.attribute.MAPIAttribute; -import org.apache.poi.hmef.attribute.MAPIStringAttribute; -import org.junit.Test; - -public class HMEFFileHandler extends AbstractFileHandler { - - @Override - public void handleFile(InputStream stream) throws Exception { - HMEFMessage msg = new HMEFMessage(stream); - - // list all properties - StringBuilder props = new StringBuilder(); - for(MAPIAttribute att : msg.getMessageMAPIAttributes()) { - props.append(att.getType()).append(": ").append(MAPIStringAttribute.getAsString( att)).append("\n"); - } - - // there are two test-files that have no body... - if(!msg.getSubject().equals("Testing TNEF Message") && !msg.getSubject().equals("TNEF test message with attachments")) { - assertNotNull("Had: " + msg.getBody() + ", " + msg.getSubject() + ", " + msg.getAttachments() + ": " + props.toString(), - msg.getBody()); - } - assertNotNull("Had: " + msg.getBody() + ", " + msg.getSubject() + ", " + msg.getAttachments() + ": " + props.toString(), - msg.getSubject()); - } - - // a test-case to test this locally without executing the full TestAllFiles - @Test - public void test() throws Exception { - InputStream stream = new FileInputStream("test-data/hmef/quick-winmail.dat"); - try { - handleFile(stream); - } finally { - stream.close(); - } - } -} diff --git a/src/integrationtest/org/apache/poi/stress/HPBFFileHandler.java b/src/integrationtest/org/apache/poi/stress/HPBFFileHandler.java deleted file mode 100644 index 093ef0274..000000000 --- a/src/integrationtest/org/apache/poi/stress/HPBFFileHandler.java +++ /dev/null @@ -1,69 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.stress; - -import static org.junit.Assert.assertNotNull; - -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStream; - -import org.apache.poi.hpbf.HPBFDocument; -import org.apache.poi.hpbf.extractor.PublisherTextExtractor; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.junit.Test; - -public class HPBFFileHandler extends POIFSFileHandler { - @Override - public void handleFile(InputStream stream) throws Exception { - HPBFDocument pub = new HPBFDocument(new POIFSFileSystem(stream)); - assertNotNull(pub.getEscherDelayStm()); - assertNotNull(pub.getMainContents()); - assertNotNull(pub.getQuillContents()); - - // writing is not yet implemented... handlePOIDocument(pub); - } - - // a test-case to test this locally without executing the full TestAllFiles - @Override - @Test - public void test() throws Exception { - File file = new File("test-data/publisher/SampleBrochure.pub"); - - InputStream stream = new FileInputStream(file); - try { - handleFile(stream); - } finally { - stream.close(); - } - - handleExtracting(file); - - stream = new FileInputStream(file); - try { - PublisherTextExtractor extractor = new PublisherTextExtractor(stream); - try { - assertNotNull(extractor.getText()); - } finally { - extractor.close(); - } - } finally { - stream.close(); - } - } - -} diff --git a/src/integrationtest/org/apache/poi/stress/HPSFFileHandler.java b/src/integrationtest/org/apache/poi/stress/HPSFFileHandler.java deleted file mode 100644 index 1f3dc6905..000000000 --- a/src/integrationtest/org/apache/poi/stress/HPSFFileHandler.java +++ /dev/null @@ -1,56 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.stress; - -import static org.junit.Assert.assertNotNull; - -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStream; - -import org.apache.poi.hpsf.HPSFPropertiesOnlyDocument; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.junit.Test; - -public class HPSFFileHandler extends POIFSFileHandler { - @Override - public void handleFile(InputStream stream) throws Exception { - HPSFPropertiesOnlyDocument hpsf = new HPSFPropertiesOnlyDocument(new POIFSFileSystem(stream)); - assertNotNull(hpsf.getDocumentSummaryInformation()); - assertNotNull(hpsf.getSummaryInformation()); - - handlePOIDocument(hpsf); - } - - // a test-case to test this locally without executing the full TestAllFiles - @Override - @Test - public void test() throws Exception { - InputStream stream = new FileInputStream("test-data/hpsf/Test0313rur.adm"); - try { - handleFile(stream); - } finally { - stream.close(); - } - } - - // a test-case to test this locally without executing the full TestAllFiles - @Test - public void testExtractor() throws Exception { - handleExtracting(new File("test-data/hpsf/TestBug44375.xls")); - } -} diff --git a/src/integrationtest/org/apache/poi/stress/HSLFFileHandler.java b/src/integrationtest/org/apache/poi/stress/HSLFFileHandler.java deleted file mode 100644 index b9cff7650..000000000 --- a/src/integrationtest/org/apache/poi/stress/HSLFFileHandler.java +++ /dev/null @@ -1,101 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.stress; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.*; - -import org.apache.poi.hslf.record.Record; -import org.apache.poi.hslf.usermodel.HSLFSlideShow; -import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl; -import org.junit.Test; - -public class HSLFFileHandler extends SlideShowHandler { - @Override - public void handleFile(InputStream stream) throws Exception { - HSLFSlideShowImpl slide = new HSLFSlideShowImpl(stream); - assertNotNull(slide.getCurrentUserAtom()); - assertNotNull(slide.getEmbeddedObjects()); - assertNotNull(slide.getUnderlyingBytes()); - assertNotNull(slide.getPictureData()); - Record[] records = slide.getRecords(); - assertNotNull(records); - for(Record record : records) { - assertNotNull("Found a record which was null", record); - assertTrue(record.getRecordType() >= 0); - } - - handlePOIDocument(slide); - - HSLFSlideShow ss = new HSLFSlideShow(slide); - handleSlideShow(ss); - } - - @Test - public void testOne() throws Exception { - testOneFile(new File("test-data/slideshow/54880_chinese.ppt")); - } - - // a test-case to test this locally without executing the full TestAllFiles - @Override - @Test - public void test() throws Exception { - File[] files = new File("test-data/slideshow/").listFiles(new FilenameFilter() { - @Override - public boolean accept(File dir, String name) { - return name.endsWith(".ppt"); - } - }); - assertNotNull(files); - - System.out.println("Testing " + files.length + " files"); - - for(File file : files) { - try { - testOneFile(file); - } catch (Throwable e) { - e.printStackTrace(); - } - } - } - - private void testOneFile(File file) throws Exception { - System.out.println(file); - - //System.setProperty("org.apache.poi.util.POILogger", "org.apache.poi.util.SystemOutLogger"); - InputStream stream = new FileInputStream(file); - try { - handleFile(stream); - } finally { - stream.close(); - } - - handleExtracting(file); - } - - public static void main(String[] args) throws Exception { - System.setProperty("org.apache.poi.util.POILogger", "org.apache.poi.util.SystemOutLogger"); - InputStream stream = new FileInputStream(args[0]); - try { - new HSLFFileHandler().handleFile(stream); - } finally { - stream.close(); - } - } -} diff --git a/src/integrationtest/org/apache/poi/stress/HSMFFileHandler.java b/src/integrationtest/org/apache/poi/stress/HSMFFileHandler.java deleted file mode 100644 index 1d40e6f4b..000000000 --- a/src/integrationtest/org/apache/poi/stress/HSMFFileHandler.java +++ /dev/null @@ -1,89 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.stress; - -import static org.junit.Assert.assertNotNull; - -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStream; - -import org.apache.poi.hsmf.MAPIMessage; -import org.apache.poi.hsmf.datatypes.AttachmentChunks; -import org.apache.poi.hsmf.datatypes.DirectoryChunk; -import org.junit.Test; - -public class HSMFFileHandler extends POIFSFileHandler { - @Override - public void handleFile(InputStream stream) throws Exception { - MAPIMessage mapi = new MAPIMessage(stream); - assertNotNull(mapi.getAttachmentFiles()); - assertNotNull(mapi.getDisplayBCC()); - assertNotNull(mapi.getMessageDate()); - - AttachmentChunks[] attachments = mapi.getAttachmentFiles(); - - for(AttachmentChunks attachment : attachments) { - - DirectoryChunk chunkDirectory = attachment.getAttachmentDirectory(); - if(chunkDirectory != null) { - MAPIMessage attachmentMSG = chunkDirectory.getAsEmbededMessage(); - assertNotNull(attachmentMSG); - String body = attachmentMSG.getTextBody(); - assertNotNull(body); - } - } - - /* => Writing isn't yet supported... - // write out the file - File file = TempFile.createTempFile("StressTest", ".msg"); - writeToFile(mapi, file); - - MAPIMessage read = new MAPIMessage(file.getAbsolutePath()); - assertNotNull(read.getAttachmentFiles()); - assertNotNull(read.getDisplayBCC()); - assertNotNull(read.getMessageDate()); - */ - - // writing is not yet supported... handlePOIDocument(mapi); - } - -// private void writeToFile(MAPIMessage mapi, File file) -// throws FileNotFoundException, IOException { -// OutputStream stream = new FileOutputStream(file); -// try { -// mapi.write(stream); -// } finally { -// stream.close(); -// } -// } - - // a test-case to test this locally without executing the full TestAllFiles - @Override - @Test - public void test() throws Exception { - File file = new File("test-data/hsmf/logsat.com_signatures_valid.msg"); - InputStream stream = new FileInputStream(file); - try { - handleFile(stream); - } finally { - stream.close(); - } - - handleExtracting(file); - } -} \ No newline at end of file diff --git a/src/integrationtest/org/apache/poi/stress/HSSFFileHandler.java b/src/integrationtest/org/apache/poi/stress/HSSFFileHandler.java deleted file mode 100644 index 2743738eb..000000000 --- a/src/integrationtest/org/apache/poi/stress/HSSFFileHandler.java +++ /dev/null @@ -1,113 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.stress; - -import org.apache.poi.EncryptedDocumentException; -import org.apache.poi.hssf.OldExcelFormatException; -import org.apache.poi.hssf.dev.BiffViewer; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.util.RecordFormatException; -import org.junit.Test; - -import java.io.*; -import java.util.HashSet; -import java.util.Set; - -import static org.junit.Assert.assertFalse; - -public class HSSFFileHandler extends SpreadsheetHandler { - private final POIFSFileHandler delegate = new POIFSFileHandler(); - @Override - public void handleFile(InputStream stream) throws Exception { - HSSFWorkbook wb = new HSSFWorkbook(stream); - handleWorkbook(wb); - - // TODO: some documents fail currently... - // Note - as of Bugzilla 48036 (svn r828244, r828247) POI is capable of evaluating - // IntersectionPtg. However it is still not capable of parsing it. - // So FormulaEvalTestData.xls now contains a few formulas that produce errors here. - //HSSFFormulaEvaluator evaluator = new HSSFFormulaEvaluator(wb); - //evaluator.evaluateAll(); - - delegate.handlePOIDocument(wb); - - // also try to see if some of the Records behave incorrectly - // TODO: still fails on some records... RecordsStresser.handleWorkbook(wb); - } - - private static final Set EXPECTED_ADDITIONAL_FAILURES = new HashSet(); - static { - // encrypted - EXPECTED_ADDITIONAL_FAILURES.add("spreadsheet/35897-type4.xls"); - EXPECTED_ADDITIONAL_FAILURES.add("spreadsheet/xor-encryption-abc.xls"); - EXPECTED_ADDITIONAL_FAILURES.add("spreadsheet/password.xls"); - // broken files - EXPECTED_ADDITIONAL_FAILURES.add("spreadsheet/43493.xls"); - // TODO: ok to ignore? - EXPECTED_ADDITIONAL_FAILURES.add("spreadsheet/50833.xls"); - EXPECTED_ADDITIONAL_FAILURES.add("spreadsheet/51832.xls"); - EXPECTED_ADDITIONAL_FAILURES.add("spreadsheet/XRefCalc.xls"); - } - - @Override - public void handleAdditional(File file) throws Exception { - // redirect stdout as the examples often write lots of text - PrintStream oldOut = System.out; - try { - System.setOut(new PrintStream(new OutputStream() { - @Override - public void write(int b) throws IOException { - } - })); - - BiffViewer.main(new String[]{file.getAbsolutePath()}); - - assertFalse("Expected Extraction to fail for file " + file + " and handler " + this + ", but did not fail!", - EXPECTED_ADDITIONAL_FAILURES.contains(file.getParentFile().getName() + "/" + file.getName())); - } catch (OldExcelFormatException e) { - // old excel formats are not supported here - } catch (EncryptedDocumentException e) { - if(!EXPECTED_ADDITIONAL_FAILURES.contains(file.getParentFile().getName() + "/" + file.getName())) { - throw e; - } - } catch (RecordFormatException e) { - if(!EXPECTED_ADDITIONAL_FAILURES.contains(file.getParentFile().getName() + "/" + file.getName())) { - throw e; - } - } catch (RuntimeException e) { - if(!EXPECTED_ADDITIONAL_FAILURES.contains(file.getParentFile().getName() + "/" + file.getName())) { - throw e; - } - } finally { - System.setOut(oldOut); - } - } - - // a test-case to test this locally without executing the full TestAllFiles - @Test - public void test() throws Exception { - File file = new File("test-data/spreadsheet/49219.xls"); - - InputStream stream = new FileInputStream(file); - try { - handleFile(stream); - } finally { - stream.close(); - } - handleExtracting(file); - } -} \ No newline at end of file diff --git a/src/integrationtest/org/apache/poi/stress/HWPFFileHandler.java b/src/integrationtest/org/apache/poi/stress/HWPFFileHandler.java deleted file mode 100644 index d762598a4..000000000 --- a/src/integrationtest/org/apache/poi/stress/HWPFFileHandler.java +++ /dev/null @@ -1,73 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.stress; - -import static org.junit.Assert.assertNotNull; - -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStream; - -import org.apache.poi.hwpf.HWPFDocument; -import org.apache.poi.hwpf.extractor.WordExtractor; -import org.junit.Test; - -public class HWPFFileHandler extends POIFSFileHandler { - @Override - public void handleFile(InputStream stream) throws Exception { - HWPFDocument doc = new HWPFDocument(stream); - assertNotNull(doc.getBookmarks()); - assertNotNull(doc.getCharacterTable()); - assertNotNull(doc.getEndnotes()); - - handlePOIDocument(doc); - } - - // a test-case to test this locally without executing the full TestAllFiles - @Override - @Test - public void test() throws Exception { - File file = new File("test-data/document/52117.doc"); - - InputStream stream = new FileInputStream(file); - try { - handleFile(stream); - } finally { - stream.close(); - } - - handleExtracting(file); - - stream = new FileInputStream(file); - try { - WordExtractor extractor = new WordExtractor(stream); - try { - assertNotNull(extractor.getText()); - } finally { - extractor.close(); - } - } finally { - stream.close(); - } - } - - @Test - public void testExtractingOld() throws Exception { - File file = new File("test-data/document/52117.doc"); - handleExtracting(file); - } -} diff --git a/src/integrationtest/org/apache/poi/stress/OPCFileHandler.java b/src/integrationtest/org/apache/poi/stress/OPCFileHandler.java deleted file mode 100644 index ca019ae51..000000000 --- a/src/integrationtest/org/apache/poi/stress/OPCFileHandler.java +++ /dev/null @@ -1,77 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.stress; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStream; -import java.io.PushbackInputStream; - -import org.apache.poi.openxml4j.opc.ContentTypes; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.xwpf.usermodel.XWPFRelation; -import org.junit.Test; - -public class OPCFileHandler extends AbstractFileHandler { - @Override - public void handleFile(InputStream stream) throws Exception { - // ignore password protected files - if (POIXMLDocumentHandler.isEncrypted(stream)) return; - - OPCPackage p = OPCPackage.open(stream); - - for (PackagePart part : p.getParts()) { - if (part.getPartName().toString().equals("/docProps/core.xml")) { - assertEquals(ContentTypes.CORE_PROPERTIES_PART, part.getContentType()); - } - if (part.getPartName().toString().equals("/word/document.xml")) { - assertTrue("Expected one of " + XWPFRelation.MACRO_DOCUMENT + ", " + XWPFRelation.DOCUMENT + ", " + XWPFRelation.TEMPLATE + - ", but had " + part.getContentType(), - XWPFRelation.DOCUMENT.getContentType().equals(part.getContentType()) || - XWPFRelation.MACRO_DOCUMENT.getContentType().equals(part.getContentType()) || - XWPFRelation.TEMPLATE.getContentType().equals(part.getContentType())); - } - if (part.getPartName().toString().equals("/word/theme/theme1.xml")) { - assertEquals(XWPFRelation.THEME.getContentType(), part.getContentType()); - } - } - } - - @Override - public void handleExtracting(File file) throws Exception { - // text-extraction is not possible currently for these types of files - } - - // a test-case to test this locally without executing the full TestAllFiles - @Test - public void test() throws Exception { - File file = new File("test-data/diagram/test.vsdx"); - - InputStream stream = new PushbackInputStream(new FileInputStream(file), 100000); - try { - handleFile(stream); - } finally { - stream.close(); - } - - handleExtracting(file); - } -} diff --git a/src/integrationtest/org/apache/poi/stress/POIFSFileHandler.java b/src/integrationtest/org/apache/poi/stress/POIFSFileHandler.java deleted file mode 100644 index 56be0d9ee..000000000 --- a/src/integrationtest/org/apache/poi/stress/POIFSFileHandler.java +++ /dev/null @@ -1,90 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.stress; - -import static org.junit.Assert.assertNotNull; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.POIDocument; -import org.apache.poi.hpsf.extractor.HPSFPropertiesExtractor; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.junit.Test; - -public class POIFSFileHandler extends AbstractFileHandler { - - @Override - public void handleFile(InputStream stream) throws Exception { - POIFSFileSystem fs = new POIFSFileSystem(stream); - try { - handlePOIFSFileSystem(fs); - handleHPSFProperties(fs); - } finally { - fs.close(); - } - } - - private void handleHPSFProperties(POIFSFileSystem fs) throws IOException { - HPSFPropertiesExtractor ext = new HPSFPropertiesExtractor(fs); - try { - // can be null - ext.getDocSummaryInformation(); - ext.getSummaryInformation(); - - assertNotNull(ext.getDocumentSummaryInformationText()); - assertNotNull(ext.getSummaryInformationText()); - assertNotNull(ext.getText()); - } finally { - ext.close(); - } - } - - private void handlePOIFSFileSystem(POIFSFileSystem fs) { - assertNotNull(fs); - assertNotNull(fs.getRoot()); - } - - protected void handlePOIDocument(POIDocument doc) throws Exception { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - doc.write(out); - - ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); - POIFSFileSystem fs = new POIFSFileSystem(in); - handlePOIFSFileSystem(fs); - fs.close(); - } - - // a test-case to test this locally without executing the full TestAllFiles - @Test - public void test() throws Exception { - File file = new File("test-data/poifs/Notes.ole2"); - - InputStream stream = new FileInputStream(file); - try { - handleFile(stream); - } finally { - stream.close(); - } - - //handleExtracting(file); - } -} diff --git a/src/integrationtest/org/apache/poi/stress/POIXMLDocumentHandler.java b/src/integrationtest/org/apache/poi/stress/POIXMLDocumentHandler.java deleted file mode 100644 index 82b3f6d36..000000000 --- a/src/integrationtest/org/apache/poi/stress/POIXMLDocumentHandler.java +++ /dev/null @@ -1,51 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.stress; - -import static org.junit.Assert.assertNotNull; - -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.POIXMLDocument; -import org.apache.poi.poifs.crypt.Decryptor; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; - -public final class POIXMLDocumentHandler { - protected void handlePOIXMLDocument(POIXMLDocument doc) throws Exception { - assertNotNull(doc.getAllEmbedds()); - assertNotNull(doc.getPackage()); - assertNotNull(doc.getPackagePart()); - assertNotNull(doc.getProperties()); - assertNotNull(doc.getRelations()); - } - - protected static boolean isEncrypted(InputStream stream) throws IOException { - if (POIFSFileSystem.hasPOIFSHeader(stream)) { - POIFSFileSystem poifs = new POIFSFileSystem(stream); - try { - if (poifs.getRoot().hasEntry(Decryptor.DEFAULT_POIFS_ENTRY)) { - return true; - } - } finally { - poifs.close(); - } - throw new IOException("Wrong file format or file extension for OO XML file"); - } - return false; - } -} diff --git a/src/integrationtest/org/apache/poi/stress/SlideShowHandler.java b/src/integrationtest/org/apache/poi/stress/SlideShowHandler.java deleted file mode 100644 index 5241b8089..000000000 --- a/src/integrationtest/org/apache/poi/stress/SlideShowHandler.java +++ /dev/null @@ -1,126 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.stress; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.awt.Dimension; -import java.awt.Graphics2D; -import java.awt.RenderingHints; -import java.awt.image.BufferedImage; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -import org.apache.poi.sl.draw.DrawFactory; -import org.apache.poi.sl.usermodel.PictureData; -import org.apache.poi.sl.usermodel.Shape; -import org.apache.poi.sl.usermodel.ShapeContainer; -import org.apache.poi.sl.usermodel.Slide; -import org.apache.poi.sl.usermodel.SlideShow; -import org.apache.poi.sl.usermodel.SlideShowFactory; -import org.apache.poi.sl.usermodel.TextParagraph; -import org.apache.poi.sl.usermodel.TextRun; -import org.apache.poi.sl.usermodel.TextShape; - -public abstract class SlideShowHandler extends POIFSFileHandler { - public void handleSlideShow(SlideShow ss) throws IOException { - renderSlides(ss); - - readContent(ss); - readPictures(ss); - - // write out the file - ByteArrayOutputStream out = writeToArray(ss); - - readContent(ss); - - // read in the written file - SlideShow read = SlideShowFactory.create(new ByteArrayInputStream(out.toByteArray())); - try { - assertNotNull(read); - readContent(read); - } finally { - read.close(); - } - } - - private ByteArrayOutputStream writeToArray(SlideShow ss) throws IOException { - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - try { - ss.write(stream); - } finally { - stream.close(); - } - - return stream; - } - - - private void readContent(SlideShow ss) { - for (Slide s : ss.getSlides()) { - s.getTitle(); - readText(s); - readText(s.getNotes()); - readText(s.getMasterSheet()); - } - } - - private void readText(ShapeContainer sc) { - if (sc == null) return; - for (Shape s : sc) { - if (s instanceof TextShape) { - for (TextParagraph tp : (TextShape)s) { - for (TextRun tr : tp) { - tr.getRawText(); - } - } - } - } - } - - private void readPictures(SlideShow ss) { - for (PictureData pd : ss.getPictureData()) { - Dimension dim = pd.getImageDimension(); - assertTrue(dim.getHeight() >= 0); - assertTrue(dim.getWidth() >= 0); - } - } - - private void renderSlides(SlideShow ss) { - Dimension pgsize = ss.getPageSize(); - - for (Slide s : ss.getSlides()) { - BufferedImage img = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_ARGB); - Graphics2D graphics = img.createGraphics(); - DrawFactory.getInstance(graphics).fixFonts(graphics); - - // default rendering options - graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); - graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); - graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); - - // draw stuff - s.draw(graphics); - - graphics.dispose(); - img.flush(); - } - } -} \ No newline at end of file diff --git a/src/integrationtest/org/apache/poi/stress/SpreadsheetHandler.java b/src/integrationtest/org/apache/poi/stress/SpreadsheetHandler.java deleted file mode 100644 index 854dbf2fb..000000000 --- a/src/integrationtest/org/apache/poi/stress/SpreadsheetHandler.java +++ /dev/null @@ -1,147 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.stress; - -import static org.junit.Assert.assertNotNull; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.ss.extractor.EmbeddedData; -import org.apache.poi.ss.extractor.EmbeddedExtractor; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.usermodel.WorkbookFactory; -import org.apache.poi.util.RecordFormatException; - -public abstract class SpreadsheetHandler extends AbstractFileHandler { - public void handleWorkbook(Workbook wb) throws IOException { - // try to access some of the content - readContent(wb); - - // write out the file - writeToArray(wb); - - // access some more content (we had cases where writing corrupts the data in memory) - readContent(wb); - - // write once more - ByteArrayOutputStream out = writeToArray(wb); - - // read in the written file - Workbook read; - try { - read = WorkbookFactory.create(new ByteArrayInputStream(out.toByteArray())); - } catch (InvalidFormatException e) { - throw new IllegalStateException(e); - } - assertNotNull(read); - - readContent(read); - - extractEmbedded(read); - - modifyContent(read); - - read.close(); - } - - private ByteArrayOutputStream writeToArray(Workbook wb) throws IOException { - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - try { - wb.write(stream); - } finally { - stream.close(); - } - - return stream; - } - - private void readContent(Workbook wb) { - for(int i = 0;i < wb.getNumberOfSheets();i++) { - Sheet sheet = wb.getSheetAt(i); - assertNotNull(wb.getSheet(sheet.getSheetName())); - sheet.groupColumn((short) 4, (short) 5); - sheet.setColumnGroupCollapsed(4, true); - sheet.setColumnGroupCollapsed(4, false); - - // don't do this for very large sheets as it will take a long time - if(sheet.getPhysicalNumberOfRows() > 1000) { - continue; - } - - for(Row row : sheet) { - for(Cell cell : row) { - assertNotNull(cell.toString()); - } - } - } - } - - private void extractEmbedded(Workbook wb) throws IOException { - EmbeddedExtractor ee = new EmbeddedExtractor(); - - for (Sheet s : wb) { - for (EmbeddedData ed : ee.extractAll(s)) { - assertNotNull(ed.getFilename()); - assertNotNull(ed.getEmbeddedData()); - assertNotNull(ed.getShape()); - } - } - } - - private void modifyContent(Workbook wb) { - /* a number of file fail because of various things: udf, unimplemented functions, ... - we would need quite a list of excludes and the large regression tests would probably - take a lot longer to run... - try { - // try to re-compute all formulas to find cases where parsing fails - wb.getCreationHelper().createFormulaEvaluator().evaluateAll(); - } catch (RuntimeException e) { - // only allow a specific exception which indicates that an external - // reference was not found - if(!e.getMessage().contains("Could not resolve external workbook name")) { - throw e; - } - - }*/ - - for (int i=wb.getNumberOfSheets()-1; i>=0; i--) { - try { - wb.cloneSheet(i); - } catch (RecordFormatException e) { - if (e.getCause() instanceof CloneNotSupportedException) { - // ignore me - continue; - } - throw e; - } catch (RuntimeException e) { - if ("Could not find 'internal references' EXTERNALBOOK".equals(e.getMessage()) || - "CountryRecord not found".equals(e.getMessage()) || - "Cannot add more than 65535 shapes".equals(e.getMessage()) ) { - // ignore these here for now - continue; - } - throw e; - } - } - } -} \ No newline at end of file diff --git a/src/integrationtest/org/apache/poi/stress/XDGFFileHandler.java b/src/integrationtest/org/apache/poi/stress/XDGFFileHandler.java deleted file mode 100644 index 9b7d03f8a..000000000 --- a/src/integrationtest/org/apache/poi/stress/XDGFFileHandler.java +++ /dev/null @@ -1,47 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.stress; - -import java.io.InputStream; - -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackageAccess; -import org.apache.poi.xdgf.usermodel.XmlVisioDocument; -import org.junit.Test; - -public class XDGFFileHandler extends AbstractFileHandler { - @Override - public void handleFile(InputStream stream) throws Exception { - // ignore password protected files - if (POIXMLDocumentHandler.isEncrypted(stream)) return; - - XmlVisioDocument doc = new XmlVisioDocument(stream); - new POIXMLDocumentHandler().handlePOIXMLDocument(doc); - } - - // a test-case to test this locally without executing the full TestAllFiles - @Test - public void test() throws Exception { - OPCPackage pkg = OPCPackage.open("test-data/diagram/test.vsdx", PackageAccess.READ); - try { - XmlVisioDocument doc = new XmlVisioDocument(pkg); - new POIXMLDocumentHandler().handlePOIXMLDocument(doc); - } finally { - pkg.close(); - } - } -} \ No newline at end of file diff --git a/src/integrationtest/org/apache/poi/stress/XSLFFileHandler.java b/src/integrationtest/org/apache/poi/stress/XSLFFileHandler.java deleted file mode 100644 index ce5e0c040..000000000 --- a/src/integrationtest/org/apache/poi/stress/XSLFFileHandler.java +++ /dev/null @@ -1,82 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.stress; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStream; - -import org.apache.poi.extractor.ExtractorFactory; -import org.apache.poi.xslf.extractor.XSLFPowerPointExtractor; -import org.apache.poi.xslf.usermodel.XMLSlideShow; -import org.apache.poi.xslf.usermodel.XSLFSlideShow; -import org.junit.Test; - -public class XSLFFileHandler extends SlideShowHandler { - @Override - public void handleFile(InputStream stream) throws Exception { - XMLSlideShow slide = new XMLSlideShow(stream); - XSLFSlideShow slideInner = new XSLFSlideShow(slide.getPackage()); - assertNotNull(slideInner.getPresentation()); - assertNotNull(slideInner.getSlideMasterReferences()); - assertNotNull(slideInner.getSlideReferences()); - - new POIXMLDocumentHandler().handlePOIXMLDocument(slide); - - handleSlideShow(slide); - - slideInner.close(); - slide.close(); - } - - @Override - public void handleExtracting(File file) throws Exception { - super.handleExtracting(file); - - - // additionally try the other getText() methods - - XSLFPowerPointExtractor extractor = (XSLFPowerPointExtractor) ExtractorFactory.createExtractor(file); - try { - assertNotNull(extractor); - - assertNotNull(extractor.getText(true, true, true)); - assertEquals("With all options disabled we should not get text", - "", extractor.getText(false, false, false)); - } finally { - extractor.close(); - } - } - - // a test-case to test this locally without executing the full TestAllFiles - @Override - @Test - public void test() throws Exception { - File file = new File("test-data/slideshow/ae.ac.uaeu.faculty_nafaachbili_GeomLec1.pptx"); - InputStream stream = new FileInputStream(file); - try { - handleFile(stream); - } finally { - stream.close(); - } - - handleExtracting(file); - } -} diff --git a/src/integrationtest/org/apache/poi/stress/XSSFBFileHandler.java b/src/integrationtest/org/apache/poi/stress/XSSFBFileHandler.java deleted file mode 100644 index 0d71de7e8..000000000 --- a/src/integrationtest/org/apache/poi/stress/XSSFBFileHandler.java +++ /dev/null @@ -1,88 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.stress; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackageAccess; -import org.apache.poi.util.IOUtils; -import org.apache.poi.xssf.XLSBUnsupportedException; -import org.apache.poi.xssf.extractor.XSSFBEventBasedExcelExtractor; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -public class XSSFBFileHandler extends AbstractFileHandler { - - static { - //add expected failures here: - AbstractFileHandler.EXPECTED_EXTRACTOR_FAILURES.add("spreadsheet/protected_passtika.xlsb"); - } - - @Override - public void handleFile(InputStream stream) throws Exception { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - IOUtils.copy(stream, out); - - final byte[] bytes = out.toByteArray(); - OPCPackage opcPackage = OPCPackage.open(new ByteArrayInputStream(bytes)); - try { - testOne(opcPackage); - } finally { - opcPackage.close(); - } - - testNotHandledByWorkbookException(OPCPackage.open(new ByteArrayInputStream(bytes))); - } - - private void testNotHandledByWorkbookException(OPCPackage pkg) throws IOException { - try { - new XSSFWorkbook(pkg); - } catch (XLSBUnsupportedException e) { - //this is what we'd expect - //swallow - } - } - - @Override - public void handleExtracting(File file) throws Exception { - OPCPackage pkg = OPCPackage.open(file, PackageAccess.READ); - try { - testOne(pkg); - } finally { - pkg.close(); - } - - pkg = OPCPackage.open(file, PackageAccess.READ); - try { - testNotHandledByWorkbookException(pkg); - } finally { - pkg.close(); - } - } - - private void testOne(OPCPackage pkg) throws Exception { - XSSFBEventBasedExcelExtractor ex = new XSSFBEventBasedExcelExtractor(pkg); - String txt = ex.getText(); - if (txt.length() < 1) { - throw new RuntimeException("Should have gotten some text."); - } - } -} diff --git a/src/integrationtest/org/apache/poi/stress/XSSFFileHandler.java b/src/integrationtest/org/apache/poi/stress/XSSFFileHandler.java deleted file mode 100644 index aa47a7267..000000000 --- a/src/integrationtest/org/apache/poi/stress/XSSFFileHandler.java +++ /dev/null @@ -1,273 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.stress; - -import org.apache.poi.POIXMLException; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.exceptions.OLE2NotOfficeXmlFileException; -import org.apache.poi.openxml4j.exceptions.OpenXML4JException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.util.IOUtils; -import org.apache.poi.xssf.eventusermodel.XLSX2CSV; -import org.apache.poi.xssf.eventusermodel.XSSFReader; -import org.apache.poi.xssf.eventusermodel.examples.FromHowTo; -import org.apache.poi.xssf.extractor.XSSFExportToXml; -import org.apache.poi.xssf.usermodel.XSSFMap; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Test; -import org.xml.sax.SAXException; - -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.TransformerException; -import java.io.*; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Locale; -import java.util.Set; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; - -public class XSSFFileHandler extends SpreadsheetHandler { - @Override - public void handleFile(InputStream stream) throws Exception { - // ignore password protected files - if (POIXMLDocumentHandler.isEncrypted(stream)) return; - - final XSSFWorkbook wb; - - // make sure the potentially large byte-array is freed up quickly again - { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - IOUtils.copy(stream, out); - final byte[] bytes = out.toByteArray(); - - checkXSSFReader(OPCPackage.open(new ByteArrayInputStream(bytes))); - - wb = new XSSFWorkbook(new ByteArrayInputStream(bytes)); - } - - // use the combined handler for HSSF/XSSF - handleWorkbook(wb); - - // TODO: some documents fail currently... - //XSSFFormulaEvaluator evaluator = new XSSFFormulaEvaluator(wb); - //evaluator.evaluateAll(); - - // also verify general POIFS-stuff - new POIXMLDocumentHandler().handlePOIXMLDocument(wb); - - // and finally ensure that exporting to XML works - exportToXML(wb); - - // this allows to trigger a heap-dump at this point to see which memory is still allocated - //HeapDump.dumpHeap("/tmp/poi.hprof", false); - } - - - private void checkXSSFReader(OPCPackage p) throws IOException, OpenXML4JException { - XSSFReader reader = new XSSFReader(p); - - // these can be null... - InputStream sharedStringsData = reader.getSharedStringsData(); - if(sharedStringsData != null) { - sharedStringsData.close(); - } - reader.getSharedStringsTable(); - - InputStream stylesData = reader.getStylesData(); - if(stylesData != null) { - stylesData.close(); - } - reader.getStylesTable(); - - InputStream themesData = reader.getThemesData(); - if(themesData != null) { - themesData.close(); - } - - assertNotNull(reader.getWorkbookData()); - - Iterator sheetsData = reader.getSheetsData(); - while(sheetsData.hasNext()) { - InputStream str = sheetsData.next(); - str.close(); - } - } - - private void exportToXML(XSSFWorkbook wb) throws SAXException, - ParserConfigurationException, TransformerException { - for (XSSFMap map : wb.getCustomXMLMappings()) { - XSSFExportToXml exporter = new XSSFExportToXml(map); - - ByteArrayOutputStream os = new ByteArrayOutputStream(); - exporter.exportToXML(os, true); - } - } - - private static final Set EXPECTED_ADDITIONAL_FAILURES = new HashSet(); - static { - // expected sheet-id not found - // EXPECTED_ADDITIONAL_FAILURES.add("spreadsheet/52348.xlsx"); - // EXPECTED_ADDITIONAL_FAILURES.add("spreadsheet/59021.xlsx"); - // zip-bomb - EXPECTED_ADDITIONAL_FAILURES.add("spreadsheet/54764.xlsx"); - EXPECTED_ADDITIONAL_FAILURES.add("spreadsheet/54764-2.xlsx"); - EXPECTED_ADDITIONAL_FAILURES.add("spreadsheet/54764.xlsx"); - EXPECTED_ADDITIONAL_FAILURES.add("spreadsheet/poc-xmlbomb.xlsx"); - EXPECTED_ADDITIONAL_FAILURES.add("spreadsheet/poc-xmlbomb-empty.xlsx"); - // strict OOXML - EXPECTED_ADDITIONAL_FAILURES.add("spreadsheet/57914.xlsx"); - EXPECTED_ADDITIONAL_FAILURES.add("spreadsheet/SampleSS.strict.xlsx"); - EXPECTED_ADDITIONAL_FAILURES.add("spreadsheet/SimpleStrict.xlsx"); - EXPECTED_ADDITIONAL_FAILURES.add("spreadsheet/sample.strict.xlsx"); - // TODO: good to ignore? - EXPECTED_ADDITIONAL_FAILURES.add("spreadsheet/sample-beta.xlsx"); - - // corrupt/invalid - EXPECTED_ADDITIONAL_FAILURES.add("openxml4j/invalid.xlsx"); - } - - @SuppressWarnings("resource") - @Override - public void handleAdditional(File file) throws Exception { - // redirect stdout as the examples often write lots of text - PrintStream oldOut = System.out; - try { - System.setOut(new NullPrintStream()); - FromHowTo.main(new String[]{file.getAbsolutePath()}); - XLSX2CSV.main(new String[]{file.getAbsolutePath()}); - - assertFalse("Expected Extraction to fail for file " + file + " and handler " + this + ", but did not fail!", - EXPECTED_ADDITIONAL_FAILURES.contains(file.getParentFile().getName() + "/" + file.getName())); - - } catch (OLE2NotOfficeXmlFileException e) { - // we have some files that are not actually OOXML and thus cannot be tested here - } catch (IllegalArgumentException e) { - if(!EXPECTED_ADDITIONAL_FAILURES.contains(file.getParentFile().getName() + "/" + file.getName())) { - throw e; - } - } catch (InvalidFormatException e) { - if(!EXPECTED_ADDITIONAL_FAILURES.contains(file.getParentFile().getName() + "/" + file.getName())) { - throw e; - } - } catch (IOException e) { - if(!EXPECTED_ADDITIONAL_FAILURES.contains(file.getParentFile().getName() + "/" + file.getName())) { - throw e; - } - } catch (POIXMLException e) { - if(!EXPECTED_ADDITIONAL_FAILURES.contains(file.getParentFile().getName() + "/" + file.getName())) { - throw e; - } - } finally { - System.setOut(oldOut); - } - } - - // a test-case to test this locally without executing the full TestAllFiles - @Test - public void test() throws Exception { - File file = new File("test-data/spreadsheet/ref-56737.xlsx"); - - InputStream stream = new BufferedInputStream(new FileInputStream(file)); - try { - handleFile(stream); - } finally { - stream.close(); - } - - handleExtracting(file); - } - - @Test - public void testAdditional() throws Exception { - handleAdditional(new File("test-data/spreadsheet/poc-xmlbomb.xlsx")); - } - - // need to override all methods to omit calls to UTF-handling methods - static class NullPrintStream extends PrintStream { - @SuppressWarnings("resource") - NullPrintStream() { - super(new OutputStream() { - @Override - public void write(int b) {} - @Override - public void write(byte[] b) {} - @Override - public void write(byte[] b, int off, int len) {} - }); - } - @Override - public void write(int b) {} - @Override - public void write(byte[] buf, int off, int len) {} - @Override - public void print(boolean b) {} - @Override - public void print(char c) {} - @Override - public void print(int i) {} - @Override - public void print(long l) {} - @Override - public void print(float f) {} - @Override - public void print(double d) {} - @Override - public void print(char[] s) {} - @Override - public void print(String s) {} - @Override - public void print(Object obj) {} - @Override - public void println() {} - @Override - public void println(boolean x) {} - @Override - public void println(char x) {} - @Override - public void println(int x) {} - @Override - public void println(long x) {} - @Override - public void println(float x) {} - @Override - public void println(double x) {} - @Override - public void println(char[] x) {} - @Override - public void println(String x) {} - @Override - public void println(Object x) {} - @Override - public PrintStream printf(String format, Object... args) { return this; } - @Override - public PrintStream printf(Locale l, String format, Object... args) { return this; } - @Override - public PrintStream format(String format, Object... args) { return this; } - @Override - public PrintStream format(Locale l, String format, Object... args) { return this; } - @Override - public PrintStream append(CharSequence csq) { return this; } - @Override - public PrintStream append(CharSequence csq, int start, int end) { return this; } - @Override - public PrintStream append(char c) { return this; } - @Override - public void write(byte[] b) {} - } -} diff --git a/src/integrationtest/org/apache/poi/stress/XWPFFileHandler.java b/src/integrationtest/org/apache/poi/stress/XWPFFileHandler.java deleted file mode 100644 index c097dc9f7..000000000 --- a/src/integrationtest/org/apache/poi/stress/XWPFFileHandler.java +++ /dev/null @@ -1,53 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.stress; - -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStream; -import java.io.PushbackInputStream; - -import org.apache.poi.xwpf.usermodel.XWPFDocument; -import org.junit.Test; - -public class XWPFFileHandler extends AbstractFileHandler { - @Override - public void handleFile(InputStream stream) throws Exception { - // ignore password protected files - if (POIXMLDocumentHandler.isEncrypted(stream)) return; - - XWPFDocument doc = new XWPFDocument(stream); - - new POIXMLDocumentHandler().handlePOIXMLDocument(doc); - } - - // a test-case to test this locally without executing the full TestAllFiles - @Test - public void test() throws Exception { - File file = new File("test-data/document/51921-Word-Crash067.docx"); - - InputStream stream = new PushbackInputStream(new FileInputStream(file), 100000); - try { - handleFile(stream); - } finally { - stream.close(); - } - - handleExtracting(file); - } - -} \ No newline at end of file diff --git a/src/java/org/apache/poi/dev/RecordGenerator.java b/src/java/org/apache/poi/dev/RecordGenerator.java deleted file mode 100644 index 585003c52..000000000 --- a/src/java/org/apache/poi/dev/RecordGenerator.java +++ /dev/null @@ -1,160 +0,0 @@ - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.dev; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.Locale; -import java.util.Properties; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Result; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.stream.StreamResult; -import javax.xml.transform.stream.StreamSource; - -import org.apache.poi.util.XMLHelper; -import org.w3c.dom.Document; -import org.w3c.dom.Element; - -/** - * Description of the Class - * - *@author andy - *@since May 10, 2002 - */ -public class RecordGenerator { - /** - * The main program for the RecordGenerator class - * - *@param args The command line arguments - *@exception Exception Description of the Exception - */ - public static void main(String[] args) - throws Exception { - // Force load so that we don't start generating records and realise this hasn't compiled yet. - Class.forName("org.apache.poi.generator.FieldIterator"); - - if (args.length != 4) { - System.out.println("Usage:"); - System.out.println(" java org.apache.poi.hssf.util.RecordGenerator RECORD_DEFINTIONS RECORD_STYLES DEST_SRC_PATH TEST_SRC_PATH"); - } else { - generateRecords(args[0], args[1], args[2], args[3]); - } - } - - - private static void generateRecords(String defintionsDir, String recordStyleDir, String destSrcPathDir, String testSrcPathDir) - throws Exception { - File definitionsFiles[] = new File(defintionsDir).listFiles(); - if (definitionsFiles == null) { - System.err.println(defintionsDir+" is not a directory."); - return; - } - - for (File file : definitionsFiles) { - if (file.isFile() && - (file.getName().endsWith("_record.xml") || - file.getName().endsWith("_type.xml") - ) - ) { - // Get record name and package - DocumentBuilderFactory factory = XMLHelper.getDocumentBuilderFactory(); - DocumentBuilder builder = factory.newDocumentBuilder(); - Document document = builder.parse(file); - Element record = document.getDocumentElement(); - String extendstg = record.getElementsByTagName("extends").item(0).getFirstChild().getNodeValue(); - String suffix = record.getElementsByTagName("suffix").item(0).getFirstChild().getNodeValue(); - String recordName = record.getAttributes().getNamedItem("name").getNodeValue(); - String packageName = record.getAttributes().getNamedItem("package").getNodeValue(); - packageName = packageName.replace('.', '/'); - - // Generate record - String destinationPath = destSrcPathDir + "/" + packageName; - File destinationPathFile = new File(destinationPath); - if(!destinationPathFile.mkdirs()) { - throw new IOException("Could not create directory " + destinationPathFile); - } else { - System.out.println("Created destination directory: " + destinationPath); - } - String destinationFilepath = destinationPath + "/" + recordName + suffix + ".java"; - transform(file, new File(destinationFilepath), - new File(recordStyleDir + "/" + extendstg.toLowerCase(Locale.ROOT) + ".xsl")); - System.out.println("Generated " + suffix + ": " + destinationFilepath); - - // Generate test (if not already generated) - destinationPath = testSrcPathDir + "/" + packageName; - destinationPathFile = new File(destinationPath); - if(!destinationPathFile.mkdirs()) { - throw new IOException("Could not create directory " + destinationPathFile); - } else { - System.out.println("Created destination directory: " + destinationPath); - } - destinationFilepath = destinationPath + "/Test" + recordName + suffix + ".java"; - if (!new File(destinationFilepath).exists()) { - String temp = (recordStyleDir + "/" + extendstg.toLowerCase(Locale.ROOT) + "_test.xsl"); - transform(file, new File(destinationFilepath), new File(temp)); - System.out.println("Generated test: " + destinationFilepath); - } else { - System.out.println("Skipped test generation: " + destinationFilepath); - } - } - } - } - - - - /** - *

    Executes an XSL transformation. This process transforms an XML input - * file into a text output file controlled by an XSLT specification.

    - * - * @param in the XML input file - * @param out the text output file - * @param xslt the XSLT specification, i.e. an XSL style sheet - * @throws FileNotFoundException - * @throws TransformerException - */ - private static void transform(final File in, final File out, final File xslt) - throws FileNotFoundException, TransformerException - { - final StreamSource ss = new StreamSource(xslt); - final TransformerFactory tf = TransformerFactory.newInstance(); - final Transformer t; - try - { - t = tf.newTransformer(ss); - } - catch (TransformerException ex) - { - System.err.println("Error compiling XSL style sheet " + xslt); - throw ex; - } - final Properties p = new Properties(); - p.setProperty(OutputKeys.METHOD, "text"); - t.setOutputProperties(p); - final Result result = new StreamResult(out); - t.transform(new StreamSource(in), result); - } - -} diff --git a/src/java/org/apache/poi/extractor/OLE2ExtractorFactory.java b/src/java/org/apache/poi/extractor/OLE2ExtractorFactory.java deleted file mode 100644 index 737e9e351..000000000 --- a/src/java/org/apache/poi/extractor/OLE2ExtractorFactory.java +++ /dev/null @@ -1,270 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.extractor; - -import static org.apache.poi.hssf.model.InternalWorkbook.OLD_WORKBOOK_DIR_ENTRY_NAME; -import static org.apache.poi.hssf.model.InternalWorkbook.WORKBOOK_DIR_ENTRY_NAMES; - -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.apache.poi.POIOLE2TextExtractor; -import org.apache.poi.POITextExtractor; -import org.apache.poi.hssf.OldExcelFormatException; -import org.apache.poi.hssf.extractor.EventBasedExcelExtractor; -import org.apache.poi.hssf.extractor.ExcelExtractor; -import org.apache.poi.poifs.filesystem.DirectoryEntry; -import org.apache.poi.poifs.filesystem.DirectoryNode; -import org.apache.poi.poifs.filesystem.Entry; -import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; -import org.apache.poi.poifs.filesystem.OPOIFSFileSystem; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; - -/** - * Figures out the correct POIOLE2TextExtractor for your supplied - * document, and returns it. - * - *

    Note 1 - will fail for many file formats if the POI Scratchpad jar is - * not present on the runtime classpath

    - *

    Note 2 - for text extractor creation across all formats, use - * {@link org.apache.poi.extractor.ExtractorFactory} contained within - * the OOXML jar.

    - *

    Note 3 - rather than using this, for most cases you would be better - * off switching to Apache Tika instead!

    - */ -@SuppressWarnings("WeakerAccess") -public class OLE2ExtractorFactory { - private static final POILogger LOGGER = POILogFactory.getLogger(OLE2ExtractorFactory.class); - - /** Should this thread prefer event based over usermodel based extractors? */ - private static final ThreadLocal threadPreferEventExtractors = new ThreadLocal() { - @Override - protected Boolean initialValue() { return Boolean.FALSE; } - }; - - /** Should all threads prefer event based over usermodel based extractors? */ - private static Boolean allPreferEventExtractors; - - /** - * Should this thread prefer event based over usermodel based extractors? - * (usermodel extractors tend to be more accurate, but use more memory) - * Default is false. - */ - public static boolean getThreadPrefersEventExtractors() { - return threadPreferEventExtractors.get(); - } - - /** - * Should all threads prefer event based over usermodel based extractors? - * (usermodel extractors tend to be more accurate, but use more memory) - * Default is to use the thread level setting, which defaults to false. - */ - public static Boolean getAllThreadsPreferEventExtractors() { - return allPreferEventExtractors; - } - - /** - * Should this thread prefer event based over usermodel based extractors? - * Will only be used if the All Threads setting is null. - */ - public static void setThreadPrefersEventExtractors(boolean preferEventExtractors) { - threadPreferEventExtractors.set(preferEventExtractors); - } - - /** - * Should all threads prefer event based over usermodel based extractors? - * If set, will take preference over the Thread level setting. - */ - public static void setAllThreadsPreferEventExtractors(Boolean preferEventExtractors) { - allPreferEventExtractors = preferEventExtractors; - } - - /** - * Should this thread use event based extractors is available? - * Checks the all-threads one first, then thread specific. - */ - protected static boolean getPreferEventExtractor() { - if(allPreferEventExtractors != null) { - return allPreferEventExtractors; - } - return threadPreferEventExtractors.get(); - } - - public static POIOLE2TextExtractor createExtractor(POIFSFileSystem fs) throws IOException { - // Only ever an OLE2 one from the root of the FS - return (POIOLE2TextExtractor)createExtractor(fs.getRoot()); - } - public static POIOLE2TextExtractor createExtractor(NPOIFSFileSystem fs) throws IOException { - // Only ever an OLE2 one from the root of the FS - return (POIOLE2TextExtractor)createExtractor(fs.getRoot()); - } - public static POIOLE2TextExtractor createExtractor(OPOIFSFileSystem fs) throws IOException { - // Only ever an OLE2 one from the root of the FS - return (POIOLE2TextExtractor)createExtractor(fs.getRoot()); - } - - public static POITextExtractor createExtractor(InputStream input) throws IOException { - Class cls = getOOXMLClass(); - if (cls != null) { - // Use Reflection to get us the full OOXML-enabled version - try { - Method m = cls.getDeclaredMethod("createExtractor", InputStream.class); - return (POITextExtractor)m.invoke(null, input); - } catch (IllegalArgumentException iae) { - throw iae; - } catch (Exception e) { - throw new IllegalArgumentException("Error creating Extractor for InputStream", e); - } - } else { - // Best hope it's OLE2.... - return createExtractor(new NPOIFSFileSystem(input)); - } - } - - private static Class getOOXMLClass() { - try { - return OLE2ExtractorFactory.class.getClassLoader().loadClass( - "org.apache.poi.extractor.ExtractorFactory" - ); - } catch (ClassNotFoundException e) { - LOGGER.log(POILogger.WARN, "POI OOXML jar missing"); - return null; - } - } - private static Class getScratchpadClass() { - try { - return OLE2ExtractorFactory.class.getClassLoader().loadClass( - "org.apache.poi.extractor.OLE2ScratchpadExtractorFactory" - ); - } catch (ClassNotFoundException e) { - LOGGER.log(POILogger.ERROR, "POI Scratchpad jar missing"); - throw new IllegalStateException("POI Scratchpad jar missing, required for ExtractorFactory"); - } - } - - /** - * Create the Extractor, if possible. Generally needs the Scratchpad jar. - * Note that this won't check for embedded OOXML resources either, use - * {@link org.apache.poi.extractor.ExtractorFactory} for that. - */ - public static POITextExtractor createExtractor(DirectoryNode poifsDir) - throws IOException - { - // Look for certain entries in the stream, to figure it - // out from - for (String workbookName : WORKBOOK_DIR_ENTRY_NAMES) { - if (poifsDir.hasEntry(workbookName)) { - if (getPreferEventExtractor()) { - return new EventBasedExcelExtractor(poifsDir); - } - return new ExcelExtractor(poifsDir); - } - } - if (poifsDir.hasEntry(OLD_WORKBOOK_DIR_ENTRY_NAME)) { - throw new OldExcelFormatException("Old Excel Spreadsheet format (1-95) " - + "found. Please call OldExcelExtractor directly for basic text extraction"); - } - - // Ask Scratchpad, or fail trying - Class cls = getScratchpadClass(); - try { - Method m = cls.getDeclaredMethod("createExtractor", DirectoryNode.class); - POITextExtractor ext = (POITextExtractor)m.invoke(null, poifsDir); - if (ext != null) return ext; - } catch (IllegalArgumentException iae) { - throw iae; - } catch (Exception e) { - throw new IllegalArgumentException("Error creating Scratchpad Extractor", e); - } - - throw new IllegalArgumentException("No supported documents found in the OLE2 stream"); - } - - /** - * Returns an array of text extractors, one for each of - * the embedded documents in the file (if there are any). - * If there are no embedded documents, you'll get back an - * empty array. Otherwise, you'll get one open - * {@link POITextExtractor} for each embedded file. - */ - public static POITextExtractor[] getEmbededDocsTextExtractors(POIOLE2TextExtractor ext) - throws IOException - { - // All the embedded directories we spotted - List dirs = new ArrayList(); - // For anything else not directly held in as a POIFS directory - List nonPOIFS = new ArrayList(); - - // Find all the embedded directories - DirectoryEntry root = ext.getRoot(); - if(root == null) { - throw new IllegalStateException("The extractor didn't know which POIFS it came from!"); - } - - if(ext instanceof ExcelExtractor) { - // These are in MBD... under the root - Iterator it = root.getEntries(); - while(it.hasNext()) { - Entry entry = it.next(); - if(entry.getName().startsWith("MBD")) { - dirs.add(entry); - } - } - } else { - // Ask Scratchpad, or fail trying - Class cls = getScratchpadClass(); - try { - Method m = cls.getDeclaredMethod( - "identifyEmbeddedResources", POIOLE2TextExtractor.class, List.class, List.class); - m.invoke(null, ext, dirs, nonPOIFS); - } catch (Exception e) { - throw new IllegalArgumentException("Error checking for Scratchpad embedded resources", e); - } - } - - // Create the extractors - if(dirs.size() == 0 && nonPOIFS.size() == 0){ - return new POITextExtractor[0]; - } - - ArrayList e = new ArrayList(); - for (Entry dir : dirs) { - e.add(createExtractor( - (DirectoryNode) dir - )); - } - for (InputStream nonPOIF : nonPOIFS) { - try { - e.add(createExtractor(nonPOIF)); - } catch (IllegalArgumentException ie) { - // Ignore, just means it didn't contain - // a format we support as yet - LOGGER.log(POILogger.WARN, ie); - } catch (Exception xe) { - // Ignore, invalid format - LOGGER.log(POILogger.WARN, xe); - } - } - return e.toArray(new POITextExtractor[e.size()]); - } -} diff --git a/src/java/org/apache/poi/sl/draw/BitmapImageRenderer.java b/src/java/org/apache/poi/sl/draw/BitmapImageRenderer.java deleted file mode 100644 index e09054479..000000000 --- a/src/java/org/apache/poi/sl/draw/BitmapImageRenderer.java +++ /dev/null @@ -1,305 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw; - -import java.awt.Dimension; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Insets; -import java.awt.Shape; -import java.awt.geom.AffineTransform; -import java.awt.geom.Rectangle2D; -import java.awt.image.AffineTransformOp; -import java.awt.image.BufferedImage; -import java.awt.image.RescaleOp; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.Iterator; - -import javax.imageio.ImageIO; -import javax.imageio.ImageReadParam; -import javax.imageio.ImageReader; -import javax.imageio.ImageTypeSpecifier; -import javax.imageio.stream.ImageInputStream; -import javax.imageio.stream.MemoryCacheImageInputStream; - -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; - -/** - * For now this class renders only images supported by the javax.imageio.ImageIO framework. - **/ -public class BitmapImageRenderer implements ImageRenderer { - private final static POILogger LOG = POILogFactory.getLogger(ImageRenderer.class); - - protected BufferedImage img; - - @Override - public void loadImage(InputStream data, String contentType) throws IOException { - img = readImage(data, contentType); - } - - @Override - public void loadImage(byte data[], String contentType) throws IOException { - img = readImage(new ByteArrayInputStream(data), contentType); - } - - /** - * Read the image data via ImageIO and optionally try to workaround metadata errors. - * The resulting image is of image type {@link BufferedImage#TYPE_INT_ARGB} - * - * @param data the data stream - * @param contentType the content type - * @return the bufferedImage or null, if there was no image reader for this content type - * @throws IOException thrown if there was an error while processing the image - */ - private static BufferedImage readImage(InputStream data, String contentType) throws IOException { - IOException lastException = null; - BufferedImage img = null; - if (data.markSupported()) { - data.mark(data.available()); - } - - // currently don't use FileCacheImageInputStream, - // because of the risk of filling the file handles (see #59166) - ImageInputStream iis = new MemoryCacheImageInputStream(data); - try { - iis = new MemoryCacheImageInputStream(data); - iis.mark(); - - Iterator iter = ImageIO.getImageReaders(iis); - while (img==null && iter.hasNext()) { - ImageReader reader = iter.next(); - ImageReadParam param = reader.getDefaultReadParam(); - // 0:default mode, 1:fallback mode - for (int mode=0; img==null && mode<3; mode++) { - lastException = null; - try { - iis.reset(); - } catch (IOException e) { - if (data.markSupported()) { - data.reset(); - data.mark(data.available()); - iis.close(); - iis = new MemoryCacheImageInputStream(data); - } else { - // can't restore the input stream, so we need to stop processing here - lastException = e; - break; - } - } - iis.mark(); - - try { - - switch (mode) { - case 0: - reader.setInput(iis, false, true); - img = reader.read(0, param); - break; - case 1: { - // try to load picture in gray scale mode - // fallback mode for invalid image band metadata - // see http://stackoverflow.com/questions/10416378 - Iterator imageTypes = reader.getImageTypes(0); - while (imageTypes.hasNext()) { - ImageTypeSpecifier imageTypeSpecifier = imageTypes.next(); - int bufferedImageType = imageTypeSpecifier.getBufferedImageType(); - if (bufferedImageType == BufferedImage.TYPE_BYTE_GRAY) { - param.setDestinationType(imageTypeSpecifier); - break; - } - } - reader.setInput(iis, false, true); - img = reader.read(0, param); - break; - } - case 2: { - // try to load truncated pictures by supplying a BufferedImage - // and use the processed data up till the point of error - reader.setInput(iis, false, true); - int height = reader.getHeight(0); - int width = reader.getWidth(0); - - Iterator imageTypes = reader.getImageTypes(0); - if (imageTypes.hasNext()) { - ImageTypeSpecifier imageTypeSpecifier = imageTypes.next(); - img = imageTypeSpecifier.createBufferedImage(width, height); - param.setDestination(img); - } else { - lastException = new IOException("unable to load even a truncated version of the image."); - break; - } - - try { - reader.read(0, param); - } finally { - if (img.getType() != BufferedImage.TYPE_INT_ARGB) { - int y = findTruncatedBlackBox(img, width, height); - if (y < height) { - BufferedImage argbImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); - Graphics2D g = argbImg.createGraphics(); - g.clipRect(0, 0, width, y); - g.drawImage(img, 0, 0, null); - g.dispose(); - img.flush(); - img = argbImg; - } - } - } - break; - } - } - - } catch (IOException e) { - if (mode < 2) { - lastException = e; - } - } catch (RuntimeException e) { - if (mode < 2) { - lastException = new IOException("ImageIO runtime exception - "+(mode==0 ? "normal" : "fallback"), e); - } - } - } - reader.dispose(); - } - } finally { - iis.close(); - } - - // If you don't have an image at the end of all readers - if (img == null) { - if (lastException != null) { - // rethrow exception - be aware that the exception source can be in - // multiple locations above ... - throw lastException; - } - LOG.log(POILogger.WARN, "Content-type: "+contentType+" is not support. Image ignored."); - return null; - } - - // add alpha channel - if (img.getType() != BufferedImage.TYPE_INT_ARGB) { - BufferedImage argbImg = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_ARGB); - Graphics g = argbImg.getGraphics(); - g.drawImage(img, 0, 0, null); - g.dispose(); - return argbImg; - } - - return img; - } - - private static int findTruncatedBlackBox(BufferedImage img, int width, int height) { - // scan through the image to find the black box after the truncated data - int h = height-1; - for (; h > 0; h--) { - for (int w = width-1; w > 0; w-=width/10) { - int p = img.getRGB(w, h); - if (p != 0xff000000) { - return h+1; - } - } - } - return 0; - } - - - @Override - public BufferedImage getImage() { - return img; - } - - @Override - public BufferedImage getImage(Dimension dim) { - double w_old = img.getWidth(); - double h_old = img.getHeight(); - BufferedImage scaled = new BufferedImage((int)w_old, (int)h_old, BufferedImage.TYPE_INT_ARGB); - double w_new = dim.getWidth(); - double h_new = dim.getHeight(); - AffineTransform at = new AffineTransform(); - at.scale(w_new/w_old, h_new/h_old); - AffineTransformOp scaleOp = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR); - scaleOp.filter(img, scaled); - return scaled; - } - - @Override - public Dimension getDimension() { - return (img == null) - ? new Dimension(0,0) - : new Dimension(img.getWidth(),img.getHeight()); - } - - @Override - public void setAlpha(double alpha) { - if (img == null) return; - - Dimension dim = getDimension(); - BufferedImage newImg = new BufferedImage((int)dim.getWidth(), (int)dim.getHeight(), BufferedImage.TYPE_INT_ARGB); - Graphics2D g = newImg.createGraphics(); - RescaleOp op = new RescaleOp(new float[]{1.0f, 1.0f, 1.0f, (float)alpha}, new float[]{0,0,0,0}, null); - g.drawImage(img, op, 0, 0); - g.dispose(); - - img = newImg; - } - - - @Override - public boolean drawImage( - Graphics2D graphics, - Rectangle2D anchor) { - return drawImage(graphics, anchor, null); - } - - @Override - public boolean drawImage( - Graphics2D graphics, - Rectangle2D anchor, - Insets clip) { - if (img == null) return false; - - boolean isClipped = true; - if (clip == null) { - isClipped = false; - clip = new Insets(0,0,0,0); - } - - int iw = img.getWidth(); - int ih = img.getHeight(); - - - double cw = (100000-clip.left-clip.right) / 100000.0; - double ch = (100000-clip.top-clip.bottom) / 100000.0; - double sx = anchor.getWidth()/(iw*cw); - double sy = anchor.getHeight()/(ih*ch); - double tx = anchor.getX()-(iw*sx*clip.left/100000.0); - double ty = anchor.getY()-(ih*sy*clip.top/100000.0); - - AffineTransform at = new AffineTransform(sx, 0, 0, sy, tx, ty) ; - - Shape clipOld = graphics.getClip(); - if (isClipped) graphics.clip(anchor.getBounds2D()); - graphics.drawRenderedImage(img, at); - graphics.setClip(clipOld); - - return true; - } -} diff --git a/src/java/org/apache/poi/sl/draw/DrawAutoShape.java b/src/java/org/apache/poi/sl/draw/DrawAutoShape.java deleted file mode 100644 index 5503542a1..000000000 --- a/src/java/org/apache/poi/sl/draw/DrawAutoShape.java +++ /dev/null @@ -1,27 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw; - -import org.apache.poi.sl.usermodel.*; - - -public class DrawAutoShape extends DrawTextShape { - public DrawAutoShape(AutoShape shape) { - super(shape); - } -} diff --git a/src/java/org/apache/poi/sl/draw/DrawBackground.java b/src/java/org/apache/poi/sl/draw/DrawBackground.java deleted file mode 100644 index 1e9d5945b..000000000 --- a/src/java/org/apache/poi/sl/draw/DrawBackground.java +++ /dev/null @@ -1,69 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw; - -import java.awt.Dimension; -import java.awt.Graphics2D; -import java.awt.Paint; -import java.awt.geom.Rectangle2D; - -import org.apache.poi.sl.usermodel.Background; -import org.apache.poi.sl.usermodel.PlaceableShape; -import org.apache.poi.sl.usermodel.ShapeContainer; -import org.apache.poi.sl.usermodel.Sheet; - - -public class DrawBackground extends DrawShape { - public DrawBackground(Background shape) { - super(shape); - } - - @SuppressWarnings("rawtypes") - public void draw(Graphics2D graphics) { - Dimension pg = shape.getSheet().getSlideShow().getPageSize(); - final Rectangle2D anchor = new Rectangle2D.Double(0, 0, pg.getWidth(), pg.getHeight()); - - PlaceableShape ps = new PlaceableShape(){ - public ShapeContainer getParent() { return null; } - public Rectangle2D getAnchor() { return anchor; } - public void setAnchor(Rectangle2D newAnchor) {} - public double getRotation() { return 0; } - public void setRotation(double theta) {} - public void setFlipHorizontal(boolean flip) {} - public void setFlipVertical(boolean flip) {} - public boolean getFlipHorizontal() { return false; } - public boolean getFlipVertical() { return false; } - public Sheet getSheet() { return shape.getSheet(); } - }; - - DrawFactory drawFact = DrawFactory.getInstance(graphics); - DrawPaint dp = drawFact.getPaint(ps); - Paint fill = dp.getPaint(graphics, getShape().getFillStyle().getPaint()); - Rectangle2D anchor2 = getAnchor(graphics, anchor); - - if(fill != null) { - graphics.setRenderingHint(Drawable.GRADIENT_SHAPE, anchor); - graphics.setPaint(fill); - graphics.fill(anchor2); - } - } - - protected Background getShape() { - return (Background)shape; - } -} diff --git a/src/java/org/apache/poi/sl/draw/DrawConnectorShape.java b/src/java/org/apache/poi/sl/draw/DrawConnectorShape.java deleted file mode 100644 index bb973f5f8..000000000 --- a/src/java/org/apache/poi/sl/draw/DrawConnectorShape.java +++ /dev/null @@ -1,26 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw; - -import org.apache.poi.sl.usermodel.ConnectorShape; - -public class DrawConnectorShape extends DrawSimpleShape { - public DrawConnectorShape(ConnectorShape shape) { - super(shape); - } -} diff --git a/src/java/org/apache/poi/sl/draw/DrawFactory.java b/src/java/org/apache/poi/sl/draw/DrawFactory.java deleted file mode 100644 index 53b2bcba7..000000000 --- a/src/java/org/apache/poi/sl/draw/DrawFactory.java +++ /dev/null @@ -1,239 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw; - -import java.awt.Graphics2D; -import java.awt.font.TextLayout; -import java.awt.geom.AffineTransform; -import java.awt.geom.Rectangle2D; -import java.text.AttributedString; -import java.util.HashMap; -import java.util.Map; - -import org.apache.poi.sl.usermodel.Background; -import org.apache.poi.sl.usermodel.ConnectorShape; -import org.apache.poi.sl.usermodel.FreeformShape; -import org.apache.poi.sl.usermodel.GraphicalFrame; -import org.apache.poi.sl.usermodel.GroupShape; -import org.apache.poi.sl.usermodel.MasterSheet; -import org.apache.poi.sl.usermodel.PictureShape; -import org.apache.poi.sl.usermodel.PlaceableShape; -import org.apache.poi.sl.usermodel.Shape; -import org.apache.poi.sl.usermodel.Sheet; -import org.apache.poi.sl.usermodel.Slide; -import org.apache.poi.sl.usermodel.TableShape; -import org.apache.poi.sl.usermodel.TextBox; -import org.apache.poi.sl.usermodel.TextParagraph; -import org.apache.poi.sl.usermodel.TextShape; -import org.apache.poi.util.JvmBugs; - -public class DrawFactory { - protected static final ThreadLocal defaultFactory = new ThreadLocal(); - - /** - * Set a custom draw factory for the current thread. - * This is a fallback, for operations where usercode can't set a graphics context. - * Preferably use the rendering hint {@link Drawable#DRAW_FACTORY} to set the factory. - * - * @param factory - */ - public static void setDefaultFactory(DrawFactory factory) { - defaultFactory.set(factory); - } - - /** - * Returns the DrawFactory, preferably via a graphics instance. - * If graphics is null, the current thread local is checked or - * if it is not set, a new factory is created. - * - * @param graphics the current graphics context or null - * @return the draw factory - */ - public static DrawFactory getInstance(Graphics2D graphics) { - // first try to find the factory over the rendering hint - DrawFactory factory = null; - boolean isHint = false; - if (graphics != null) { - factory = (DrawFactory)graphics.getRenderingHint(Drawable.DRAW_FACTORY); - isHint = (factory != null); - } - // secondly try the thread local default - if (factory == null) { - factory = defaultFactory.get(); - } - // and at last, use the default factory - if (factory == null) { - factory = new DrawFactory(); - } - if (graphics != null && !isHint) { - graphics.setRenderingHint(Drawable.DRAW_FACTORY, factory); - } - return factory; - } - - public Drawable getDrawable(Shape shape) { - if (shape instanceof TextBox) { - return getDrawable((TextBox)shape); - } else if (shape instanceof FreeformShape) { - return getDrawable((FreeformShape)shape); - } else if (shape instanceof TextShape) { - return getDrawable((TextShape)shape); - } else if (shape instanceof TableShape) { - return getDrawable((TableShape)shape); - } else if (shape instanceof GroupShape) { - return getDrawable((GroupShape)shape); - } else if (shape instanceof PictureShape) { - return getDrawable((PictureShape)shape); - } else if (shape instanceof GraphicalFrame) { - return getDrawable((GraphicalFrame)shape); - } else if (shape instanceof Background) { - return getDrawable((Background)shape); - } else if (shape instanceof ConnectorShape) { - return getDrawable((ConnectorShape)shape); - } else if (shape instanceof Slide) { - return getDrawable((Slide)shape); - } else if (shape instanceof MasterSheet) { - return getDrawable((MasterSheet)shape); - } else if (shape instanceof Sheet) { - return getDrawable((Sheet)shape); - } else if (shape.getClass().isAnnotationPresent(DrawNotImplemented.class)) { - return new DrawNothing(shape); - } - - throw new IllegalArgumentException("Unsupported shape type: "+shape.getClass()); - } - - public DrawSlide getDrawable(Slide sheet) { - return new DrawSlide(sheet); - } - - public DrawSheet getDrawable(Sheet sheet) { - return new DrawSheet(sheet); - } - - public DrawMasterSheet getDrawable(MasterSheet sheet) { - return new DrawMasterSheet(sheet); - } - - public DrawTextBox getDrawable(TextBox shape) { - return new DrawTextBox(shape); - } - - public DrawFreeformShape getDrawable(FreeformShape shape) { - return new DrawFreeformShape(shape); - } - - public DrawConnectorShape getDrawable(ConnectorShape shape) { - return new DrawConnectorShape(shape); - } - - public DrawTableShape getDrawable(TableShape shape) { - return new DrawTableShape(shape); - } - - public DrawTextShape getDrawable(TextShape shape) { - return new DrawTextShape(shape); - } - - public DrawGroupShape getDrawable(GroupShape shape) { - return new DrawGroupShape(shape); - } - - public DrawPictureShape getDrawable(PictureShape shape) { - return new DrawPictureShape(shape); - } - - public DrawGraphicalFrame getDrawable(GraphicalFrame shape) { - return new DrawGraphicalFrame(shape); - } - - public DrawTextParagraph getDrawable(TextParagraph paragraph) { - return new DrawTextParagraph(paragraph); - } - - public DrawBackground getDrawable(Background shape) { - return new DrawBackground(shape); - } - - public DrawTextFragment getTextFragment(TextLayout layout, AttributedString str) { - return new DrawTextFragment(layout, str); - } - - public DrawPaint getPaint(PlaceableShape shape) { - return new DrawPaint(shape); - } - - /** - * Convenience method for drawing single shapes. - * For drawing whole slides, use {@link Slide#draw(Graphics2D)} - * - * @param graphics the graphics context to draw to - * @param shape the shape - * @param bounds the bounds within the graphics context to draw to - */ - public void drawShape(Graphics2D graphics, Shape shape, Rectangle2D bounds) { - Rectangle2D shapeBounds = shape.getAnchor(); - if (shapeBounds.isEmpty() || (bounds != null && bounds.isEmpty())) { - return; - } - - AffineTransform txg = (AffineTransform)graphics.getRenderingHint(Drawable.GROUP_TRANSFORM); - AffineTransform tx = new AffineTransform(); - try { - if (bounds != null) { - double scaleX = bounds.getWidth()/shapeBounds.getWidth(); - double scaleY = bounds.getHeight()/shapeBounds.getHeight(); - tx.translate(bounds.getCenterX(), bounds.getCenterY()); - tx.scale(scaleX, scaleY); - tx.translate(-shapeBounds.getCenterX(), -shapeBounds.getCenterY()); - } - graphics.setRenderingHint(Drawable.GROUP_TRANSFORM, tx); - - Drawable d = getDrawable(shape); - d.applyTransform(graphics); - d.draw(graphics); - } finally { - graphics.setRenderingHint(Drawable.GROUP_TRANSFORM, txg); - } - } - - - /** - * Replace font families for Windows JVM 6, which contains a font rendering error. - * This is likely to be removed, when POI upgrades to JDK 7 - * - * @param graphics the graphics context which will contain the font mapping - */ - public void fixFonts(Graphics2D graphics) { - if (!JvmBugs.hasLineBreakMeasurerBug()) return; - @SuppressWarnings("unchecked") - Map fontMap = (Map)graphics.getRenderingHint(Drawable.FONT_MAP); - if (fontMap == null) { - fontMap = new HashMap(); - graphics.setRenderingHint(Drawable.FONT_MAP, fontMap); - } - - String fonts[][] = { { "Calibri", "Lucida Sans" }, { "Cambria", "Lucida Bright" } }; - - for (String f[] : fonts) { - if (!fontMap.containsKey(f[0])) { - fontMap.put(f[0], f[1]); - } - } - } -} \ No newline at end of file diff --git a/src/java/org/apache/poi/sl/draw/DrawFontManager.java b/src/java/org/apache/poi/sl/draw/DrawFontManager.java deleted file mode 100644 index 5b74f8400..000000000 --- a/src/java/org/apache/poi/sl/draw/DrawFontManager.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.sl.draw; - -/** - * Manages fonts when rendering slides. - * - * Use this class to handle unknown / missing fonts or to substitute fonts - */ -public interface DrawFontManager { - - /** - * select a font to be used to paint text - * - * @param typeface the font family as defined in the .pptx file. - * This can be unknown or missing in the graphic environment. - * @param pitchFamily a pitch-and-family, - * see {@link org.apache.poi.hwmf.record.HwmfFont#getFamily()} and - * {@link org.apache.poi.hwmf.record.HwmfFont#getPitch()} - * for how to calculate those (ancient) values - * - * @return the font to be used to paint text - */ - String getRendererableFont(String typeface, int pitchFamily); - - /** - * In case the original font doesn't contain a glyph, use the - * returned fallback font as an alternative - * - * @param typeface the font family as defined in the .pptx file. - * @param pitchFamily a pitch-and-family, - * see {@link org.apache.poi.hwmf.record.HwmfFont#getFamily()} and - * {@link org.apache.poi.hwmf.record.HwmfFont#getPitch()} - * for how to calculate those (ancient) values - * - * @return the font to be used as a fallback for the original typeface - */ - String getFallbackFont(String typeface, int pitchFamily); -} diff --git a/src/java/org/apache/poi/sl/draw/DrawFreeformShape.java b/src/java/org/apache/poi/sl/draw/DrawFreeformShape.java deleted file mode 100644 index de9dd5322..000000000 --- a/src/java/org/apache/poi/sl/draw/DrawFreeformShape.java +++ /dev/null @@ -1,61 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw; - -import java.awt.Graphics2D; -import java.awt.geom.AffineTransform; -import java.awt.geom.Path2D; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import org.apache.poi.sl.draw.geom.Outline; -import org.apache.poi.sl.draw.geom.Path; -import org.apache.poi.sl.usermodel.FillStyle; -import org.apache.poi.sl.usermodel.FreeformShape; -import org.apache.poi.sl.usermodel.StrokeStyle; - -public class DrawFreeformShape extends DrawAutoShape { - public DrawFreeformShape(FreeformShape shape) { - super(shape); - } - - protected Collection computeOutlines(Graphics2D graphics) { - List lst = new ArrayList(); - FreeformShape fsh = getShape(); - Path2D sh = fsh.getPath(); - - AffineTransform tx = (AffineTransform)graphics.getRenderingHint(Drawable.GROUP_TRANSFORM); - if (tx == null) { - tx = new AffineTransform(); - } - - java.awt.Shape canvasShape = tx.createTransformedShape(sh); - - FillStyle fs = fsh.getFillStyle(); - StrokeStyle ss = fsh.getStrokeStyle(); - Path path = new Path(fs != null, ss != null); - lst.add(new Outline(canvasShape, path)); - return lst; - } - - @Override - protected FreeformShape getShape() { - return (FreeformShape)shape; - } -} diff --git a/src/java/org/apache/poi/sl/draw/DrawGraphicalFrame.java b/src/java/org/apache/poi/sl/draw/DrawGraphicalFrame.java deleted file mode 100644 index 0628429f8..000000000 --- a/src/java/org/apache/poi/sl/draw/DrawGraphicalFrame.java +++ /dev/null @@ -1,40 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw; - -import java.awt.Graphics2D; - -import org.apache.poi.sl.usermodel.GraphicalFrame; -import org.apache.poi.sl.usermodel.PictureShape; - - -public class DrawGraphicalFrame extends DrawShape { - - public DrawGraphicalFrame(GraphicalFrame shape) { - super(shape); - } - - public void draw(Graphics2D context) { - PictureShape ps = ((GraphicalFrame)getShape()).getFallbackPicture(); - if (ps == null) { - return; - } - DrawPictureShape dps = DrawFactory.getInstance(context).getDrawable(ps); - dps.draw(context); - } -} diff --git a/src/java/org/apache/poi/sl/draw/DrawGroupShape.java b/src/java/org/apache/poi/sl/draw/DrawGroupShape.java deleted file mode 100644 index 3472d8543..000000000 --- a/src/java/org/apache/poi/sl/draw/DrawGroupShape.java +++ /dev/null @@ -1,75 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw; - -import java.awt.Graphics2D; -import java.awt.geom.AffineTransform; -import java.awt.geom.Rectangle2D; - -import org.apache.poi.sl.usermodel.*; - - -public class DrawGroupShape extends DrawShape { - - public DrawGroupShape(GroupShape shape) { - super(shape); - } - - public void draw(Graphics2D graphics) { - - // the coordinate system of this group of shape - Rectangle2D interior = getShape().getInteriorAnchor(); - // anchor of this group relative to the parent shape - Rectangle2D exterior = getShape().getAnchor(); - - AffineTransform tx = (AffineTransform)graphics.getRenderingHint(Drawable.GROUP_TRANSFORM); - AffineTransform tx0 = new AffineTransform(tx); - - double scaleX = interior.getWidth() == 0. ? 1.0 : exterior.getWidth() / interior.getWidth(); - double scaleY = interior.getHeight() == 0. ? 1.0 : exterior.getHeight() / interior.getHeight(); - - tx.translate(exterior.getX(), exterior.getY()); - tx.scale(scaleX, scaleY); - tx.translate(-interior.getX(), -interior.getY()); - - DrawFactory drawFact = DrawFactory.getInstance(graphics); - AffineTransform at2 = graphics.getTransform(); - - for (Shape child : getShape()) { - // remember the initial transform and restore it after we are done with the drawing - AffineTransform at = graphics.getTransform(); - graphics.setRenderingHint(Drawable.GSAVE, true); - - Drawable draw = drawFact.getDrawable(child); - draw.applyTransform(graphics); - draw.draw(graphics); - - // restore the coordinate system - graphics.setTransform(at); - graphics.setRenderingHint(Drawable.GRESTORE, true); - } - - graphics.setTransform(at2); - graphics.setRenderingHint(Drawable.GROUP_TRANSFORM, tx0); - } - - @Override - protected GroupShape getShape() { - return (GroupShape)shape; - } -} diff --git a/src/java/org/apache/poi/sl/draw/DrawMasterSheet.java b/src/java/org/apache/poi/sl/draw/DrawMasterSheet.java deleted file mode 100644 index 2dbbfef69..000000000 --- a/src/java/org/apache/poi/sl/draw/DrawMasterSheet.java +++ /dev/null @@ -1,53 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw; - -import java.awt.Graphics2D; - -import org.apache.poi.sl.usermodel.MasterSheet; -import org.apache.poi.sl.usermodel.Placeholder; -import org.apache.poi.sl.usermodel.Shape; -import org.apache.poi.sl.usermodel.SimpleShape; -import org.apache.poi.sl.usermodel.Slide; - - -public class DrawMasterSheet extends DrawSheet { - - public DrawMasterSheet(MasterSheet sheet) { - super(sheet); - } - - /** - * Checks if this {@code sheet} displays the specified shape. - * - * Subclasses can override it and skip certain shapes from drawings, - * for instance, slide masters and layouts don't display placeholders - */ - @Override - protected boolean canDraw(Graphics2D graphics, Shape shape) { - Slide slide = (Slide)graphics.getRenderingHint(Drawable.CURRENT_SLIDE); - if (shape instanceof SimpleShape) { - // in XSLF, slidenumber and date shapes aren't marked as placeholders opposed to HSLF - Placeholder ph = ((SimpleShape)shape).getPlaceholder(); - if (ph != null) { - return slide.getDisplayPlaceholder(ph); - } - } - return slide.getFollowMasterGraphics(); - } -} diff --git a/src/java/org/apache/poi/sl/draw/DrawNotImplemented.java b/src/java/org/apache/poi/sl/draw/DrawNotImplemented.java deleted file mode 100644 index 246e8d8a1..000000000 --- a/src/java/org/apache/poi/sl/draw/DrawNotImplemented.java +++ /dev/null @@ -1,35 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw; - -import java.lang.annotation.Documented; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; - -import org.apache.poi.util.Internal; - - -/** - * This is a marker annotation for classes which don't have a defined - * draw implementation. - */ -@Documented -@Retention(RetentionPolicy.RUNTIME) -@Internal -public @interface DrawNotImplemented { -} diff --git a/src/java/org/apache/poi/sl/draw/DrawNothing.java b/src/java/org/apache/poi/sl/draw/DrawNothing.java deleted file mode 100644 index f875da7fc..000000000 --- a/src/java/org/apache/poi/sl/draw/DrawNothing.java +++ /dev/null @@ -1,47 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw; - -import java.awt.Graphics2D; - -import org.apache.poi.sl.usermodel.Shape; - - -public class DrawNothing implements Drawable { - - protected final Shape shape; - - public DrawNothing(Shape shape) { - this.shape = shape; - } - - /** - * Apply 2-D transforms before drawing this shape. This includes rotation and flipping. - * - * @param graphics the graphics whos transform matrix will be modified - */ - public void applyTransform(Graphics2D graphics) { - } - - - public void draw(Graphics2D graphics) { - } - - public void drawContent(Graphics2D context) { - } -} diff --git a/src/java/org/apache/poi/sl/draw/DrawPaint.java b/src/java/org/apache/poi/sl/draw/DrawPaint.java deleted file mode 100644 index 3b1bc1ab8..000000000 --- a/src/java/org/apache/poi/sl/draw/DrawPaint.java +++ /dev/null @@ -1,537 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw; - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Graphics2D; -import java.awt.LinearGradientPaint; -import java.awt.Paint; -import java.awt.RadialGradientPaint; -import java.awt.geom.AffineTransform; -import java.awt.geom.Point2D; -import java.awt.geom.Rectangle2D; -import java.awt.image.BufferedImage; -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.sl.usermodel.ColorStyle; -import org.apache.poi.sl.usermodel.PaintStyle; -import org.apache.poi.sl.usermodel.PaintStyle.GradientPaint; -import org.apache.poi.sl.usermodel.PaintStyle.SolidPaint; -import org.apache.poi.sl.usermodel.PaintStyle.TexturePaint; -import org.apache.poi.sl.usermodel.PlaceableShape; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; - - -/** - * This class handles color transformations. - * - * @see HSL code taken from Java Tips Weblog - */ -public class DrawPaint { - // HSL code is public domain - see https://tips4java.wordpress.com/contact-us/ - - private static final POILogger LOG = POILogFactory.getLogger(DrawPaint.class); - - private static final Color TRANSPARENT = new Color(1f,1f,1f,0f); - - protected PlaceableShape shape; - - public DrawPaint(PlaceableShape shape) { - this.shape = shape; - } - - private static class SimpleSolidPaint implements SolidPaint { - private final ColorStyle solidColor; - - SimpleSolidPaint(final Color color) { - if (color == null) { - throw new NullPointerException("Color needs to be specified"); - } - this.solidColor = new ColorStyle(){ - @Override - public Color getColor() { - return new Color(color.getRed(), color.getGreen(), color.getBlue()); - } - @Override - public int getAlpha() { return (int)Math.round(color.getAlpha()*100000./255.); } - @Override - public int getHueOff() { return -1; } - @Override - public int getHueMod() { return -1; } - @Override - public int getSatOff() { return -1; } - @Override - public int getSatMod() { return -1; } - @Override - public int getLumOff() { return -1; } - @Override - public int getLumMod() { return -1; } - @Override - public int getShade() { return -1; } - @Override - public int getTint() { return -1; } - }; - } - - SimpleSolidPaint(ColorStyle color) { - if (color == null) { - throw new NullPointerException("Color needs to be specified"); - } - this.solidColor = color; - } - - @Override - public ColorStyle getSolidColor() { - return solidColor; - } - } - - public static SolidPaint createSolidPaint(final Color color) { - return (color == null) ? null : new SimpleSolidPaint(color); - } - - public static SolidPaint createSolidPaint(final ColorStyle color) { - return (color == null) ? null : new SimpleSolidPaint(color); - } - - public Paint getPaint(Graphics2D graphics, PaintStyle paint) { - if (paint instanceof SolidPaint) { - return getSolidPaint((SolidPaint)paint, graphics); - } else if (paint instanceof GradientPaint) { - return getGradientPaint((GradientPaint)paint, graphics); - } else if (paint instanceof TexturePaint) { - return getTexturePaint((TexturePaint)paint, graphics); - } - return null; - } - - protected Paint getSolidPaint(SolidPaint fill, Graphics2D graphics) { - return applyColorTransform(fill.getSolidColor()); - } - - protected Paint getGradientPaint(GradientPaint fill, Graphics2D graphics) { - switch (fill.getGradientType()) { - case linear: - return createLinearGradientPaint(fill, graphics); - case circular: - return createRadialGradientPaint(fill, graphics); - case shape: - return createPathGradientPaint(fill, graphics); - default: - throw new UnsupportedOperationException("gradient fill of type "+fill+" not supported."); - } - } - - protected Paint getTexturePaint(TexturePaint fill, Graphics2D graphics) { - InputStream is = fill.getImageData(); - if (is == null) { - return null; - } - assert(graphics != null); - - ImageRenderer renderer = DrawPictureShape.getImageRenderer(graphics, fill.getContentType()); - - try { - try { - renderer.loadImage(is, fill.getContentType()); - } finally { - is.close(); - } - } catch (IOException e) { - LOG.log(POILogger.ERROR, "Can't load image data - using transparent color", e); - return null; - } - - int alpha = fill.getAlpha(); - if (0 <= alpha && alpha < 100000) { - renderer.setAlpha(alpha/100000.f); - } - - Rectangle2D textAnchor = shape.getAnchor(); - BufferedImage image; - if ("image/x-wmf".equals(fill.getContentType())) { - // don't rely on wmf dimensions, use dimension of anchor - // TODO: check pixels vs. points for image dimension - image = renderer.getImage(new Dimension((int)textAnchor.getWidth(), (int)textAnchor.getHeight())); - } else { - image = renderer.getImage(); - } - - if(image == null) { - LOG.log(POILogger.ERROR, "Can't load image data"); - return null; - } - Paint paint = new java.awt.TexturePaint(image, textAnchor); - - return paint; - } - - /** - * Convert color transformations in {@link ColorStyle} to a {@link Color} instance - * - * @see Using Office Open XML to Customize Document Formatting in the 2007 Office System - * @see saturation modulation (satMod) - * @see Office Open XML satMod results in more than 100% saturation - */ - public static Color applyColorTransform(ColorStyle color){ - // TODO: The colors don't match 100% the results of Powerpoint, maybe because we still - // operate in sRGB and not scRGB ... work in progress ... - if (color == null || color.getColor() == null) { - return TRANSPARENT; - } - - Color result = color.getColor(); - - double alpha = getAlpha(result, color); - double hsl[] = RGB2HSL(result); // values are in the range [0..100] (usually ...) - applyHslModOff(hsl, 0, color.getHueMod(), color.getHueOff()); - applyHslModOff(hsl, 1, color.getSatMod(), color.getSatOff()); - applyHslModOff(hsl, 2, color.getLumMod(), color.getLumOff()); - applyShade(hsl, color); - applyTint(hsl, color); - - result = HSL2RGB(hsl[0], hsl[1], hsl[2], alpha); - - return result; - } - - private static double getAlpha(Color c, ColorStyle fc) { - double alpha = c.getAlpha()/255d; - int fcAlpha = fc.getAlpha(); - if (fcAlpha != -1) { - alpha *= fcAlpha/100000d; - } - return Math.min(1, Math.max(0, alpha)); - } - - /** - * Apply the modulation and offset adjustments to the given HSL part - * - * Example for lumMod/lumOff: - * The lumMod value is the percent luminance. A lumMod value of "60000", - * is 60% of the luminance of the original color. - * When the color is a shade of the original theme color, the lumMod - * attribute is the only one of the tags shown here that appears. - * The tag appears after the tag when the color is a - * tint of the original. The lumOff value always equals 1-lumMod, which is used in the tint calculation - * - * Despite having different ways to display the tint and shade percentages, - * all of the programs use the same method to calculate the resulting color. - * Convert the original RGB value to HSL ... and then adjust the luminance (L) - * with one of the following equations before converting the HSL value back to RGB. - * (The % tint in the following equations refers to the tint, themetint, themeshade, - * or lumMod values, as applicable.) - * - * @param hsl the hsl values - * @param hslPart the hsl part to modify [0..2] - * @param mod the modulation adjustment - * @param off the offset adjustment - * @return the modified hsl value - * - */ - private static void applyHslModOff(double hsl[], int hslPart, int mod, int off) { - if (mod == -1) { - mod = 100000; - } - if (off == -1) { - off = 0; - } - if (!(mod == 100000 && off == 0)) { - double fOff = off / 1000d; - double fMod = mod / 100000d; - hsl[hslPart] = hsl[hslPart]*fMod+fOff; - } - } - - /** - * Apply the shade - * - * For a shade, the equation is luminance * %tint. - */ - private static void applyShade(double hsl[], ColorStyle fc) { - int shade = fc.getShade(); - if (shade == -1) { - return; - } - - double fshade = shade / 100000.d; - - hsl[2] *= fshade; - } - - /** - * Apply the tint - * - * For a tint, the equation is luminance * %tint + (1-%tint). - * (Note that 1-%tint is equal to the lumOff value in DrawingML.) - */ - private static void applyTint(double hsl[], ColorStyle fc) { - int tint = fc.getTint(); - if (tint == -1) { - return; - } - - double ftint = tint / 100000.f; - - hsl[2] = hsl[2] * ftint + (100 - ftint*100.); - } - - protected Paint createLinearGradientPaint(GradientPaint fill, Graphics2D graphics) { - // TODO: we need to find the two points for gradient - the problem is, which point at the outline - // do you take? My solution would be to apply the gradient rotation to the shape in reverse - // and then scan the shape for the largest possible horizontal distance - - double angle = fill.getGradientAngle(); - if (!fill.isRotatedWithShape()) { - angle -= shape.getRotation(); - } - - Rectangle2D anchor = DrawShape.getAnchor(graphics, shape); - final double h = anchor.getHeight(), w = anchor.getWidth(), x = anchor.getX(), y = anchor.getY(); - - AffineTransform at = AffineTransform.getRotateInstance(Math.toRadians(angle), anchor.getCenterX(), anchor.getCenterY()); - - double diagonal = Math.sqrt(h * h + w * w); - Point2D p1 = new Point2D.Double(x + w / 2 - diagonal / 2, y + h / 2); - p1 = at.transform(p1, null); - - Point2D p2 = new Point2D.Double(x + w, y + h / 2); - p2 = at.transform(p2, null); - -// snapToAnchor(p1, anchor); -// snapToAnchor(p2, anchor); - - if (p1.equals(p2)) { - // gradient paint on the same point throws an exception ... and doesn't make sense - return null; - } - - float[] fractions = fill.getGradientFractions(); - Color[] colors = new Color[fractions.length]; - - int i = 0; - for (ColorStyle fc : fill.getGradientColors()) { - // if fc is null, use transparent color to get color of background - colors[i++] = (fc == null) ? TRANSPARENT : applyColorTransform(fc); - } - - return new LinearGradientPaint(p1, p2, fractions, colors); - } - - protected Paint createRadialGradientPaint(GradientPaint fill, Graphics2D graphics) { - Rectangle2D anchor = DrawShape.getAnchor(graphics, shape); - - Point2D pCenter = new Point2D.Double(anchor.getX() + anchor.getWidth()/2, - anchor.getY() + anchor.getHeight()/2); - - float radius = (float)Math.max(anchor.getWidth(), anchor.getHeight()); - - float[] fractions = fill.getGradientFractions(); - Color[] colors = new Color[fractions.length]; - - int i=0; - for (ColorStyle fc : fill.getGradientColors()) { - colors[i++] = applyColorTransform(fc); - } - - return new RadialGradientPaint(pCenter, radius, fractions, colors); - } - - protected Paint createPathGradientPaint(GradientPaint fill, Graphics2D graphics) { - // currently we ignore an eventually center setting - - float[] fractions = fill.getGradientFractions(); - Color[] colors = new Color[fractions.length]; - - int i=0; - for (ColorStyle fc : fill.getGradientColors()) { - colors[i++] = applyColorTransform(fc); - } - - return new PathGradientPaint(colors, fractions); - } - - protected void snapToAnchor(Point2D p, Rectangle2D anchor) { - if (p.getX() < anchor.getX()) { - p.setLocation(anchor.getX(), p.getY()); - } else if (p.getX() > (anchor.getX() + anchor.getWidth())) { - p.setLocation(anchor.getX() + anchor.getWidth(), p.getY()); - } - - if (p.getY() < anchor.getY()) { - p.setLocation(p.getX(), anchor.getY()); - } else if (p.getY() > (anchor.getY() + anchor.getHeight())) { - p.setLocation(p.getX(), anchor.getY() + anchor.getHeight()); - } - } - - /** - * Convert HSL values to a RGB Color. - * - * @param h Hue is specified as degrees in the range 0 - 360. - * @param s Saturation is specified as a percentage in the range 1 - 100. - * @param l Luminance is specified as a percentage in the range 1 - 100. - * @param alpha the alpha value between 0 - 1 - * - * @return the RGB Color object - */ - public static Color HSL2RGB(double h, double s, double l, double alpha) { - // we clamp the values, as it possible to come up with more than 100% sat/lum - // (see links in applyColorTransform() for more info) - s = Math.max(0, Math.min(100, s)); - l = Math.max(0, Math.min(100, l)); - - if (alpha <0.0f || alpha > 1.0f) { - String message = "Color parameter outside of expected range - Alpha: " + alpha; - throw new IllegalArgumentException( message ); - } - - // Formula needs all values between 0 - 1. - - h = h % 360.0f; - h /= 360f; - s /= 100f; - l /= 100f; - - double q = (l < 0.5d) - ? l * (1d + s) - : (l + s) - (s * l); - - double p = 2d * l - q; - - double r = Math.max(0, HUE2RGB(p, q, h + (1.0d / 3.0d))); - double g = Math.max(0, HUE2RGB(p, q, h)); - double b = Math.max(0, HUE2RGB(p, q, h - (1.0d / 3.0d))); - - r = Math.min(r, 1.0d); - g = Math.min(g, 1.0d); - b = Math.min(b, 1.0d); - - return new Color((float)r, (float)g, (float)b, (float)alpha); - } - - private static double HUE2RGB(double p, double q, double h) { - if (h < 0d) { - h += 1d; - } - - if (h > 1d) { - h -= 1d; - } - - if (6d * h < 1d) { - return p + ((q - p) * 6d * h); - } - - if (2d * h < 1d) { - return q; - } - - if (3d * h < 2d) { - return p + ( (q - p) * 6d * ((2.0d / 3.0d) - h) ); - } - - return p; - } - - - /** - * Convert a RGB Color to it corresponding HSL values. - * - * @return an array containing the 3 HSL values. - */ - private static double[] RGB2HSL(Color color) - { - // Get RGB values in the range 0 - 1 - - float[] rgb = color.getRGBColorComponents( null ); - double r = rgb[0]; - double g = rgb[1]; - double b = rgb[2]; - - // Minimum and Maximum RGB values are used in the HSL calculations - - double min = Math.min(r, Math.min(g, b)); - double max = Math.max(r, Math.max(g, b)); - - // Calculate the Hue - - double h = 0; - - if (max == min) { - h = 0; - } else if (max == r) { - h = ((60d * (g - b) / (max - min)) + 360d) % 360d; - } else if (max == g) { - h = (60d * (b - r) / (max - min)) + 120d; - } else if (max == b) { - h = (60d * (r - g) / (max - min)) + 240d; - } - - // Calculate the Luminance - - double l = (max + min) / 2d; - - // Calculate the Saturation - - double s = 0; - - if (max == min) { - s = 0; - } else if (l <= .5d) { - s = (max - min) / (max + min); - } else { - s = (max - min) / (2d - max - min); - } - - return new double[] {h, s * 100, l * 100}; - } - - /** - * Convert sRGB float component [0..1] from sRGB to linear RGB [0..100000] - * - * @see Color#getRGBColorComponents(float[]) - */ - public static int srgb2lin(float sRGB) { - // scRGB has a linear gamma of 1.0, scale the AWT-Color which is in sRGB to linear RGB - // see https://en.wikipedia.org/wiki/SRGB (the reverse transformation) - if (sRGB <= 0.04045d) { - return (int)Math.rint(100000d * sRGB / 12.92d); - } else { - return (int)Math.rint(100000d * Math.pow((sRGB + 0.055d) / 1.055d, 2.4d)); - } - } - - /** - * Convert linear RGB [0..100000] to sRGB float component [0..1] - * - * @see Color#getRGBColorComponents(float[]) - */ - public static float lin2srgb(int linRGB) { - // color in percentage is in linear RGB color space, i.e. needs to be gamma corrected for AWT color - // see https://en.wikipedia.org/wiki/SRGB (The forward transformation) - if (linRGB <= 0.0031308d) { - return (float)(linRGB / 100000d * 12.92d); - } else { - return (float)(1.055d * Math.pow(linRGB / 100000d, 1.0d/2.4d) - 0.055d); - } - } -} diff --git a/src/java/org/apache/poi/sl/draw/DrawPictureShape.java b/src/java/org/apache/poi/sl/draw/DrawPictureShape.java deleted file mode 100644 index 2d3764e8a..000000000 --- a/src/java/org/apache/poi/sl/draw/DrawPictureShape.java +++ /dev/null @@ -1,204 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw; - -import java.awt.Dimension; -import java.awt.Graphics2D; -import java.awt.Insets; -import java.awt.geom.Rectangle2D; -import java.io.IOException; - -import org.apache.poi.sl.usermodel.PictureData; -import org.apache.poi.sl.usermodel.PictureData.PictureType; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.sl.usermodel.PictureShape; -import org.apache.poi.sl.usermodel.RectAlign; - - -public class DrawPictureShape extends DrawSimpleShape { - private static final POILogger LOG = POILogFactory.getLogger(DrawPictureShape.class); - private static final String WMF_IMAGE_RENDERER = "org.apache.poi.hwmf.draw.HwmfSLImageRenderer"; - - public DrawPictureShape(PictureShape shape) { - super(shape); - } - - @Override - public void drawContent(Graphics2D graphics) { - PictureData data = getShape().getPictureData(); - if(data == null) return; - - Rectangle2D anchor = getAnchor(graphics, getShape()); - Insets insets = getShape().getClipping(); - - try { - ImageRenderer renderer = getImageRenderer(graphics, data.getContentType()); - renderer.loadImage(data.getData(), data.getContentType()); - renderer.drawImage(graphics, anchor, insets); - } catch (IOException e) { - LOG.log(POILogger.ERROR, "image can't be loaded/rendered.", e); - } - } - - /** - * Returns an ImageRenderer for the PictureData - * - * @param graphics - * @return the image renderer - */ - public static ImageRenderer getImageRenderer(Graphics2D graphics, String contentType) { - ImageRenderer renderer = (ImageRenderer)graphics.getRenderingHint(Drawable.IMAGE_RENDERER); - if (renderer != null) { - return renderer; - } - - if (PictureType.WMF.contentType.equals(contentType)) { - try { - @SuppressWarnings("unchecked") - Class irc = (Class) - Thread.currentThread().getContextClassLoader().loadClass(WMF_IMAGE_RENDERER); - return irc.newInstance(); - } catch (Exception e) { - // WMF image renderer is not on the classpath, continuing with BitmapRenderer - // although this doesn't make much sense ... - LOG.log(POILogger.ERROR, "WMF image renderer is not on the classpath - include poi-scratchpad jar!", e); - } - } - - return new BitmapImageRenderer(); - } - - @Override - protected PictureShape getShape() { - return (PictureShape)shape; - } - - /** - * Resize this picture to the default size. - * - * For PNG and JPEG resizes the image to 100%, - * for other types, if the size can't be determined it will be 200x200 pixels. - */ - public void resize() { - PictureShape ps = getShape(); - Dimension dim = ps.getPictureData().getImageDimension(); - - Rectangle2D origRect = ps.getAnchor(); - double x = origRect.getX(); - double y = origRect.getY(); - double w = dim.getWidth(); - double h = dim.getHeight(); - ps.setAnchor(new Rectangle2D.Double(x, y, w, h)); - } - - - /** - * Fit picture shape into the target rectangle, maintaining the aspect ratio - * and repositioning within the target rectangle with a centered alignment. - * - * @param target The target rectangle - */ - public void resize(Rectangle2D target) { - resize(target, RectAlign.CENTER); - } - - - /** - * Fit picture shape into the target rectangle, maintaining the aspect ratio - * and repositioning within the target rectangle based on the specified - * alignment (gravity). - * - * @param target The target rectangle - * @param align - * The alignment within the target rectangle when resizing. - * A null value corresponds to RectAlign.CENTER - */ - public void resize(Rectangle2D target, RectAlign align) { - PictureShape ps = getShape(); - Dimension dim = ps.getPictureData().getImageDimension(); - if (dim.width <= 0 || dim.height <= 0) { - // nothing useful to be done for this case - ps.setAnchor(target); - return; - } - - double w = target.getWidth(); - double h = target.getHeight(); - - // scaling - double sx = w / dim.width; - double sy = h / dim.height; - - // position adjustments - double dx = 0, dy = 0; - - if (sx > sy) { - // use y-scaling for both, reposition x accordingly - w = sy * dim.width; - dx = target.getWidth() - w; - } else if (sy > sx) { - // use x-scaling for both, reposition y accordingly - h = sx * dim.height; - dy = target.getHeight() - h; - } else { - // uniform scaling, can use target values directly - ps.setAnchor(target); - return; - } - - // the positioning - double x = target.getX(); - double y = target.getY(); - switch (align) { - case TOP: // X=balance, Y=ok - x += dx/2; - break; - case TOP_RIGHT: // X=shift, Y=ok - x += dx; - break; - case RIGHT: // X=shift, Y=balance - x += dx; - y += dy/2; - break; - case BOTTOM_RIGHT: // X=shift, Y=shift - x += dx; - y += dy; - break; - case BOTTOM: // X=balance, Y=shift - x += dx/2; - y += dy; - break; - case BOTTOM_LEFT: // X=ok, Y=shift - y += dy; - break; - case LEFT: // X=ok, Y=balance - y += dy/2; - break; - case TOP_LEFT: // X=ok, Y=ok - /* no-op */ - break; - default: // CENTER: X=balance, Y=balance - x += dx/2; - y += dy/2; - break; - } - - ps.setAnchor(new Rectangle2D.Double(x, y, w, h)); - } -} diff --git a/src/java/org/apache/poi/sl/draw/DrawShape.java b/src/java/org/apache/poi/sl/draw/DrawShape.java deleted file mode 100644 index 6ce586f1a..000000000 --- a/src/java/org/apache/poi/sl/draw/DrawShape.java +++ /dev/null @@ -1,241 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw; - -import java.awt.BasicStroke; -import java.awt.Graphics2D; -import java.awt.geom.AffineTransform; -import java.awt.geom.Rectangle2D; -import java.util.Locale; - -import org.apache.poi.sl.usermodel.PlaceableShape; -import org.apache.poi.sl.usermodel.Shape; -import org.apache.poi.sl.usermodel.StrokeStyle; -import org.apache.poi.sl.usermodel.StrokeStyle.LineCap; -import org.apache.poi.sl.usermodel.StrokeStyle.LineDash; - - -public class DrawShape implements Drawable { - - protected final Shape shape; - - public DrawShape(Shape shape) { - this.shape = shape; - } - - /** - * Sometimes it's necessary to distinguish between XSLF/HSLF for the rendering. - * Use this method on the shape to determine, if we work on the BIFF implementation - * - * @param shape the shape to render - * @return {@code true} if HSLF implementation is used - */ - protected static boolean isHSLF(Shape shape) { - return shape.getClass().getCanonicalName().toLowerCase(Locale.ROOT).contains("hslf"); - } - - /** - * Apply 2-D transforms before drawing this shape. This includes rotation and flipping. - * - * @param graphics the graphics whos transform matrix will be modified - */ - @Override - public void applyTransform(Graphics2D graphics) { - if (!(shape instanceof PlaceableShape)) { - return; - } - - PlaceableShape ps = (PlaceableShape)shape; - final boolean isHSLF = isHSLF(shape); - AffineTransform tx = (AffineTransform)graphics.getRenderingHint(Drawable.GROUP_TRANSFORM); - if (tx == null) { - tx = new AffineTransform(); - } - final Rectangle2D anchor = tx.createTransformedShape(ps.getAnchor()).getBounds2D(); - - char cmds[] = isHSLF ? new char[]{ 'h','v','r' } : new char[]{ 'r','h','v' }; - for (char ch : cmds) { - switch (ch) { - case 'h': - //flip horizontal - if (ps.getFlipHorizontal()) { - graphics.translate(anchor.getX() + anchor.getWidth(), anchor.getY()); - graphics.scale(-1, 1); - graphics.translate(-anchor.getX(), -anchor.getY()); - } - break; - case 'v': - //flip vertical - if (ps.getFlipVertical()) { - graphics.translate(anchor.getX(), anchor.getY() + anchor.getHeight()); - graphics.scale(1, -1); - graphics.translate(-anchor.getX(), -anchor.getY()); - } - break; - case 'r': - // rotation - double rotation = ps.getRotation(); - if (rotation != 0.) { - // PowerPoint rotates shapes relative to the geometric center - double centerX = anchor.getCenterX(); - double centerY = anchor.getCenterY(); - - // normalize rotation - rotation %= 360.; - if (rotation < 0) { - rotation += 360.; - } - - int quadrant = (((int)rotation+45)/90)%4; - double scaleX = 1.0, scaleY = 1.0; - - // scale to bounding box (bug #53176) - if (quadrant == 1 || quadrant == 3) { - // In quadrant 1 and 3, which is basically a shape in a more or less portrait orientation - // (45-135 degrees and 225-315 degrees), we need to first rotate the shape by a multiple - // of 90 degrees and then resize the bounding box to its original bbox. After that we can - // rotate the shape to the exact rotation amount. - // It's strange that you'll need to rotate the shape back and forth again, but you can - // think of it, as if you paint the shape on a canvas. First you rotate the canvas, which might - // be already (differently) scaled, so you can paint the shape in its default orientation - // and later on, turn it around again to compare it with its original size ... - - AffineTransform txs; - if (isHSLF) { - txs = new AffineTransform(tx); - } else { - // this handling is only based on try and error ... not sure why xslf is handled differently. - txs = new AffineTransform(); - txs.translate(centerX, centerY); - txs.rotate(Math.PI/2.); // actually doesn't matter if +/- 90 degrees - txs.translate(-centerX, -centerY); - txs.concatenate(tx); - } - - txs.translate(centerX, centerY); - txs.rotate(Math.PI/2.); - txs.translate(-centerX, -centerY); - - Rectangle2D anchor2 = txs.createTransformedShape(ps.getAnchor()).getBounds2D(); - - scaleX = safeScale(anchor.getWidth(), anchor2.getWidth()); - scaleY = safeScale(anchor.getHeight(), anchor2.getHeight()); - } else { - quadrant = 0; - } - - // transformation is applied reversed ... - graphics.translate(centerX, centerY); - double rot = Math.toRadians(rotation-quadrant*90.); - if (rot != 0) { - graphics.rotate(rot); - } - graphics.scale(scaleX, scaleY); - rot = Math.toRadians(quadrant*90.); - if (rot != 0) { - graphics.rotate(rot); - } - graphics.translate(-centerX, -centerY); - } - break; - default: - throw new RuntimeException("unexpected transform code " + ch); - } - } - } - - private static double safeScale(double dim1, double dim2) { - if (dim1 == 0.) { - return 1; - } - return (dim2 == 0.) ? 1 : dim1/dim2; - } - - @Override - public void draw(Graphics2D graphics) { - } - - @Override - public void drawContent(Graphics2D graphics) { - } - - public static Rectangle2D getAnchor(Graphics2D graphics, PlaceableShape shape) { - return getAnchor(graphics, shape.getAnchor()); - } - - public static Rectangle2D getAnchor(Graphics2D graphics, Rectangle2D anchor) { - if(graphics == null) { - return anchor; - } - - AffineTransform tx = (AffineTransform)graphics.getRenderingHint(Drawable.GROUP_TRANSFORM); - if(tx != null) { - anchor = tx.createTransformedShape(anchor).getBounds2D(); - } - return anchor; - } - - protected Shape getShape() { - return shape; - } - - protected static BasicStroke getStroke(StrokeStyle strokeStyle) { - float lineWidth = (float) strokeStyle.getLineWidth(); - if (lineWidth == 0.0f) { - // Both PowerPoint and OOo draw zero-length lines as 0.25pt - lineWidth = 0.25f; - } - - LineDash lineDash = strokeStyle.getLineDash(); - if (lineDash == null) { - lineDash = LineDash.SOLID; - } - - int dashPatI[] = lineDash.pattern; - final float dash_phase = 0; - float[] dashPatF = null; - if (dashPatI != null) { - dashPatF = new float[dashPatI.length]; - for (int i=0; i sheet; - - public DrawSheet(Sheet sheet) { - this.sheet = sheet; - } - - @Override - public void draw(Graphics2D graphics) { - Dimension dim = sheet.getSlideShow().getPageSize(); - Color whiteTrans = new Color(1f,1f,1f,0f); - graphics.setColor(whiteTrans); - graphics.fillRect(0, 0, (int)dim.getWidth(), (int)dim.getHeight()); - - DrawFactory drawFact = DrawFactory.getInstance(graphics); - MasterSheet master = sheet.getMasterSheet(); - - if(sheet.getFollowMasterGraphics() && master != null) { - Drawable drawer = drawFact.getDrawable(master); - drawer.draw(graphics); - } - - graphics.setRenderingHint(Drawable.GROUP_TRANSFORM, new AffineTransform()); - - for (Shape shape : sheet.getShapes()) { - if(!canDraw(graphics, shape)) { - continue; - } - - // remember the initial transform and restore it after we are done with drawing - AffineTransform at = graphics.getTransform(); - - // concrete implementations can make sense of this hint, - // for example PSGraphics2D or PDFGraphics2D would call gsave() / grestore - graphics.setRenderingHint(Drawable.GSAVE, true); - - // apply rotation and flipping - Drawable drawer = drawFact.getDrawable(shape); - drawer.applyTransform(graphics); - // draw stuff - drawer.draw(graphics); - - // restore the coordinate system - graphics.setTransform(at); - - graphics.setRenderingHint(Drawable.GRESTORE, true); - } - } - - @Override - public void applyTransform(Graphics2D context) { - } - - @Override - public void drawContent(Graphics2D context) { - } - - /** - * Checks if this sheet displays the specified shape. - * - * Subclasses can override it and skip certain shapes from drawings, - * for instance, slide masters and layouts don't display placeholders - */ - protected boolean canDraw(Graphics2D graphics, Shape shape){ - return true; - } -} diff --git a/src/java/org/apache/poi/sl/draw/DrawSimpleShape.java b/src/java/org/apache/poi/sl/draw/DrawSimpleShape.java deleted file mode 100644 index ed52a6c9e..000000000 --- a/src/java/org/apache/poi/sl/draw/DrawSimpleShape.java +++ /dev/null @@ -1,446 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw; - -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.Paint; -import java.awt.geom.AffineTransform; -import java.awt.geom.Ellipse2D; -import java.awt.geom.Path2D; -import java.awt.geom.Rectangle2D; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBElement; -import javax.xml.bind.Unmarshaller; -import javax.xml.stream.EventFilter; -import javax.xml.stream.XMLEventReader; -import javax.xml.stream.XMLInputFactory; -import javax.xml.stream.events.StartElement; -import javax.xml.stream.events.XMLEvent; - -import org.apache.poi.sl.draw.binding.CTCustomGeometry2D; -import org.apache.poi.sl.draw.geom.Context; -import org.apache.poi.sl.draw.geom.CustomGeometry; -import org.apache.poi.sl.draw.geom.Outline; -import org.apache.poi.sl.draw.geom.Path; -import org.apache.poi.sl.usermodel.LineDecoration; -import org.apache.poi.sl.usermodel.LineDecoration.DecorationShape; -import org.apache.poi.sl.usermodel.LineDecoration.DecorationSize; -import org.apache.poi.sl.usermodel.PaintStyle.SolidPaint; -import org.apache.poi.sl.usermodel.Shadow; -import org.apache.poi.sl.usermodel.SimpleShape; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.Units; - - -public class DrawSimpleShape extends DrawShape { - - private static final double DECO_SIZE_POW = 1.5d; - - public DrawSimpleShape(SimpleShape shape) { - super(shape); - } - - @Override - public void draw(Graphics2D graphics) { - DrawPaint drawPaint = DrawFactory.getInstance(graphics).getPaint(getShape()); - Paint fill = drawPaint.getPaint(graphics, getShape().getFillStyle().getPaint()); - Paint line = drawPaint.getPaint(graphics, getShape().getStrokeStyle().getPaint()); - BasicStroke stroke = getStroke(); // the stroke applies both to the shadow and the shape - graphics.setStroke(stroke); - - Collection elems = computeOutlines(graphics); - - // first paint the shadow - drawShadow(graphics, elems, fill, line); - - // then fill the shape interior - if (fill != null) { - graphics.setPaint(fill); - for (Outline o : elems) { - if (o.getPath().isFilled()){ - java.awt.Shape s = o.getOutline(); - graphics.setRenderingHint(Drawable.GRADIENT_SHAPE, s); - graphics.fill(s); - } - } - } - - // then draw any content within this shape (text, image, etc.) - drawContent(graphics); - - // then stroke the shape outline - if(line != null) { - graphics.setPaint(line); - graphics.setStroke(stroke); - for(Outline o : elems){ - if(o.getPath().isStroked()){ - java.awt.Shape s = o.getOutline(); - graphics.setRenderingHint(Drawable.GRADIENT_SHAPE, s); - graphics.draw(s); - } - } - } - - // draw line decorations - drawDecoration(graphics, line, stroke); - } - - protected void drawDecoration(Graphics2D graphics, Paint line, BasicStroke stroke) { - if(line == null) { - return; - } - graphics.setPaint(line); - - List lst = new ArrayList(); - LineDecoration deco = getShape().getLineDecoration(); - Outline head = getHeadDecoration(graphics, deco, stroke); - if (head != null) { - lst.add(head); - } - Outline tail = getTailDecoration(graphics, deco, stroke); - if (tail != null) { - lst.add(tail); - } - - - for(Outline o : lst){ - java.awt.Shape s = o.getOutline(); - Path p = o.getPath(); - graphics.setRenderingHint(Drawable.GRADIENT_SHAPE, s); - - if(p.isFilled()) { - graphics.fill(s); - } - if(p.isStroked()) { - graphics.draw(s); - } - } - } - - protected Outline getTailDecoration(Graphics2D graphics, LineDecoration deco, BasicStroke stroke) { - if (deco == null || stroke == null) { - return null; - } - DecorationSize tailLength = deco.getTailLength(); - if (tailLength == null) { - tailLength = DecorationSize.MEDIUM; - } - DecorationSize tailWidth = deco.getTailWidth(); - if (tailWidth == null) { - tailWidth = DecorationSize.MEDIUM; - } - - double lineWidth = Math.max(2.5, stroke.getLineWidth()); - - Rectangle2D anchor = getAnchor(graphics, getShape()); - double x2 = anchor.getX() + anchor.getWidth(), - y2 = anchor.getY() + anchor.getHeight(); - - double alpha = Math.atan(anchor.getHeight() / anchor.getWidth()); - - AffineTransform at = new AffineTransform(); - java.awt.Shape tailShape = null; - Path p = null; - Rectangle2D bounds; - final double scaleY = Math.pow(DECO_SIZE_POW, tailWidth.ordinal()+1.); - final double scaleX = Math.pow(DECO_SIZE_POW, tailLength.ordinal()+1.); - - DecorationShape tailShapeEnum = deco.getTailShape(); - - if (tailShapeEnum == null) { - return null; - } - - switch (tailShapeEnum) { - case OVAL: - p = new Path(); - tailShape = new Ellipse2D.Double(0, 0, lineWidth * scaleX, lineWidth * scaleY); - bounds = tailShape.getBounds2D(); - at.translate(x2 - bounds.getWidth() / 2, y2 - bounds.getHeight() / 2); - at.rotate(alpha, bounds.getX() + bounds.getWidth() / 2, bounds.getY() + bounds.getHeight() / 2); - break; - case STEALTH: - case ARROW: - p = new Path(false, true); - Path2D.Double arrow = new Path2D.Double(); - arrow.moveTo((-lineWidth * scaleX), (-lineWidth * scaleY / 2)); - arrow.lineTo(0, 0); - arrow.lineTo((-lineWidth * scaleX), (lineWidth * scaleY / 2)); - tailShape = arrow; - at.translate(x2, y2); - at.rotate(alpha); - break; - case TRIANGLE: - p = new Path(); - Path2D.Double triangle = new Path2D.Double(); - triangle.moveTo((-lineWidth * scaleX), (-lineWidth * scaleY / 2)); - triangle.lineTo(0, 0); - triangle.lineTo((-lineWidth * scaleX), (lineWidth * scaleY / 2)); - triangle.closePath(); - tailShape = triangle; - at.translate(x2, y2); - at.rotate(alpha); - break; - default: - break; - } - - if (tailShape != null) { - tailShape = at.createTransformedShape(tailShape); - } - return tailShape == null ? null : new Outline(tailShape, p); - } - - protected Outline getHeadDecoration(Graphics2D graphics, LineDecoration deco, BasicStroke stroke) { - if (deco == null || stroke == null) { - return null; - } - DecorationSize headLength = deco.getHeadLength(); - if (headLength == null) { - headLength = DecorationSize.MEDIUM; - } - DecorationSize headWidth = deco.getHeadWidth(); - if (headWidth == null) { - headWidth = DecorationSize.MEDIUM; - } - - double lineWidth = Math.max(2.5, stroke.getLineWidth()); - - Rectangle2D anchor = getAnchor(graphics, getShape()); - double x1 = anchor.getX(), y1 = anchor.getY(); - - double alpha = Math.atan(anchor.getHeight() / anchor.getWidth()); - - AffineTransform at = new AffineTransform(); - java.awt.Shape headShape = null; - Path p = null; - Rectangle2D bounds; - final double scaleY = Math.pow(DECO_SIZE_POW, headWidth.ordinal()+1.); - final double scaleX = Math.pow(DECO_SIZE_POW, headLength.ordinal()+1.); - DecorationShape headShapeEnum = deco.getHeadShape(); - - if (headShapeEnum == null) { - return null; - } - - switch (headShapeEnum) { - case OVAL: - p = new Path(); - headShape = new Ellipse2D.Double(0, 0, lineWidth * scaleX, lineWidth * scaleY); - bounds = headShape.getBounds2D(); - at.translate(x1 - bounds.getWidth() / 2, y1 - bounds.getHeight() / 2); - at.rotate(alpha, bounds.getX() + bounds.getWidth() / 2, bounds.getY() + bounds.getHeight() / 2); - break; - case STEALTH: - case ARROW: - p = new Path(false, true); - Path2D.Double arrow = new Path2D.Double(); - arrow.moveTo((lineWidth * scaleX), (-lineWidth * scaleY / 2)); - arrow.lineTo(0, 0); - arrow.lineTo((lineWidth * scaleX), (lineWidth * scaleY / 2)); - headShape = arrow; - at.translate(x1, y1); - at.rotate(alpha); - break; - case TRIANGLE: - p = new Path(); - Path2D.Double triangle = new Path2D.Double(); - triangle.moveTo((lineWidth * scaleX), (-lineWidth * scaleY / 2)); - triangle.lineTo(0, 0); - triangle.lineTo((lineWidth * scaleX), (lineWidth * scaleY / 2)); - triangle.closePath(); - headShape = triangle; - at.translate(x1, y1); - at.rotate(alpha); - break; - default: - break; - } - - if (headShape != null) { - headShape = at.createTransformedShape(headShape); - } - return headShape == null ? null : new Outline(headShape, p); - } - - public BasicStroke getStroke() { - return getStroke(getShape().getStrokeStyle()); - } - - protected void drawShadow( - Graphics2D graphics - , Collection outlines - , Paint fill - , Paint line - ) { - Shadow shadow = getShape().getShadow(); - if (shadow == null || (fill == null && line == null)) { - return; - } - - SolidPaint shadowPaint = shadow.getFillStyle(); - Color shadowColor = DrawPaint.applyColorTransform(shadowPaint.getSolidColor()); - - double shapeRotation = getShape().getRotation(); - if(getShape().getFlipVertical()) { - shapeRotation += 180; - } - double angle = shadow.getAngle() - shapeRotation; - double dist = shadow.getDistance(); - double dx = dist * Math.cos(Math.toRadians(angle)); - double dy = dist * Math.sin(Math.toRadians(angle)); - - graphics.translate(dx, dy); - - for(Outline o : outlines){ - java.awt.Shape s = o.getOutline(); - Path p = o.getPath(); - graphics.setRenderingHint(Drawable.GRADIENT_SHAPE, s); - graphics.setPaint(shadowColor); - - if(fill != null && p.isFilled()){ - graphics.fill(s); - } else if (line != null && p.isStroked()) { - graphics.draw(s); - } - } - - graphics.translate(-dx, -dy); - } - - protected static CustomGeometry getCustomGeometry(String name) { - return getCustomGeometry(name, null); - } - - protected static CustomGeometry getCustomGeometry(String name, Graphics2D graphics) { - @SuppressWarnings("unchecked") - Map presets = (graphics == null) - ? null - : (Map)graphics.getRenderingHint(Drawable.PRESET_GEOMETRY_CACHE); - - if (presets == null) { - presets = new HashMap(); - if (graphics != null) { - graphics.setRenderingHint(Drawable.PRESET_GEOMETRY_CACHE, presets); - } - - String packageName = "org.apache.poi.sl.draw.binding"; - InputStream presetIS = Drawable.class.getResourceAsStream("presetShapeDefinitions.xml"); - - // StAX: - EventFilter startElementFilter = new EventFilter() { - @Override - public boolean accept(XMLEvent event) { - return event.isStartElement(); - } - }; - - try { - XMLInputFactory staxFactory = XMLInputFactory.newInstance(); - XMLEventReader staxReader = staxFactory.createXMLEventReader(presetIS); - XMLEventReader staxFiltRd = staxFactory.createFilteredReader(staxReader, startElementFilter); - // Ignore StartElement: - staxFiltRd.nextEvent(); - // JAXB: - JAXBContext jaxbContext = JAXBContext.newInstance(packageName); - Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); - - while (staxFiltRd.peek() != null) { - StartElement evRoot = (StartElement)staxFiltRd.peek(); - String cusName = evRoot.getName().getLocalPart(); - // XMLEvent ev = staxReader.nextEvent(); - JAXBElement el = unmarshaller.unmarshal(staxReader, CTCustomGeometry2D.class); - CTCustomGeometry2D cusGeom = el.getValue(); - - presets.put(cusName, new CustomGeometry(cusGeom)); - } - - staxFiltRd.close(); - staxReader.close(); - } catch (Exception e) { - throw new RuntimeException("Unable to load preset geometries.", e); - } finally { - IOUtils.closeQuietly(presetIS); - } - } - - return presets.get(name); - } - - protected Collection computeOutlines(Graphics2D graphics) { - - List lst = new ArrayList(); - CustomGeometry geom = getShape().getGeometry(); - if(geom == null) { - return lst; - } - - Rectangle2D anchor = getAnchor(graphics, getShape()); - for (Path p : geom) { - - double w = p.getW() == -1 ? anchor.getWidth() * Units.EMU_PER_POINT : p.getW(); - double h = p.getH() == -1 ? anchor.getHeight() * Units.EMU_PER_POINT : p.getH(); - - // the guides in the shape definitions are all defined relative to each other, - // so we build the path starting from (0,0). - final Rectangle2D pathAnchor = new Rectangle2D.Double(0,0,w,h); - - Context ctx = new Context(geom, pathAnchor, getShape()); - - java.awt.Shape gp = p.getPath(ctx); - - // translate the result to the canvas coordinates in points - AffineTransform at = new AffineTransform(); - at.translate(anchor.getX(), anchor.getY()); - - double scaleX, scaleY; - if (p.getW() != -1) { - scaleX = anchor.getWidth() / p.getW(); - } else { - scaleX = 1.0 / Units.EMU_PER_POINT; - } - if (p.getH() != -1) { - scaleY = anchor.getHeight() / p.getH(); - } else { - scaleY = 1.0 / Units.EMU_PER_POINT; - } - - at.scale(scaleX, scaleY); - - java.awt.Shape canvasShape = at.createTransformedShape(gp); - - lst.add(new Outline(canvasShape, p)); - } - - return lst; - } - - @Override - protected SimpleShape getShape() { - return (SimpleShape)shape; - } -} diff --git a/src/java/org/apache/poi/sl/draw/DrawSlide.java b/src/java/org/apache/poi/sl/draw/DrawSlide.java deleted file mode 100644 index 295c58438..000000000 --- a/src/java/org/apache/poi/sl/draw/DrawSlide.java +++ /dev/null @@ -1,44 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw; - -import java.awt.Graphics2D; - -import org.apache.poi.sl.usermodel.*; - - -public class DrawSlide extends DrawSheet { - - public DrawSlide(Slide slide) { - super(slide); - } - - public void draw(Graphics2D graphics) { - graphics.setRenderingHint(Drawable.CURRENT_SLIDE, this.sheet); - - Background bg = sheet.getBackground(); - if(bg != null) { - DrawFactory drawFact = DrawFactory.getInstance(graphics); - Drawable db = drawFact.getDrawable(bg); - db.draw(graphics); - } - - super.draw(graphics); - graphics.setRenderingHint(Drawable.CURRENT_SLIDE, null); - } -} diff --git a/src/java/org/apache/poi/sl/draw/DrawTableShape.java b/src/java/org/apache/poi/sl/draw/DrawTableShape.java deleted file mode 100644 index 905196fc9..000000000 --- a/src/java/org/apache/poi/sl/draw/DrawTableShape.java +++ /dev/null @@ -1,257 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw; - -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.Paint; -import java.awt.geom.Line2D; -import java.awt.geom.Rectangle2D; - -import org.apache.poi.sl.usermodel.GroupShape; -import org.apache.poi.sl.usermodel.StrokeStyle; -import org.apache.poi.sl.usermodel.StrokeStyle.LineCompound; -import org.apache.poi.sl.usermodel.StrokeStyle.LineDash; -import org.apache.poi.sl.usermodel.TableCell; -import org.apache.poi.sl.usermodel.TableCell.BorderEdge; -import org.apache.poi.util.Internal; -import org.apache.poi.sl.usermodel.TableShape; - -public class DrawTableShape extends DrawShape { - /** - * Additional spacing between cells - */ - @Internal - public static final int borderSize = 2; - - public DrawTableShape(TableShape shape) { - super(shape); - } - - protected Drawable getGroupShape(Graphics2D graphics) { - if (shape instanceof GroupShape) { - DrawFactory df = DrawFactory.getInstance(graphics); - return df.getDrawable((GroupShape)shape); - } - return null; - } - - public void applyTransform(Graphics2D graphics) { - Drawable d = getGroupShape(graphics); - if (d != null) { - d.applyTransform(graphics); - } else { - super.applyTransform(graphics); - } - } - - public void draw(Graphics2D graphics) { - Drawable d = getGroupShape(graphics); - if (d != null) { - d.draw(graphics); - return; - } - - TableShape ts = getShape(); - DrawPaint drawPaint = DrawFactory.getInstance(graphics).getPaint(ts); - final int rows = ts.getNumberOfRows(); - final int cols = ts.getNumberOfColumns(); - - // draw background boxes - for (int row=0; row tc = ts.getCell(row, col); - if (tc == null || tc.isMerged()) { - continue; - } - - Paint fillPaint = drawPaint.getPaint(graphics, tc.getFillStyle().getPaint()); - graphics.setPaint(fillPaint); - Rectangle2D cellAnc = tc.getAnchor(); - graphics.fill(cellAnc); - - for (BorderEdge edge : BorderEdge.values()) { - StrokeStyle stroke = tc.getBorderStyle(edge); - if (stroke == null) { - continue; - } - graphics.setStroke(getStroke(stroke)); - Paint linePaint = drawPaint.getPaint(graphics, stroke.getPaint()); - graphics.setPaint(linePaint); - - double x=cellAnc.getX(), y=cellAnc.getY(), w=cellAnc.getWidth(), h=cellAnc.getHeight(); - Line2D line; - switch (edge) { - default: - case bottom: - line = new Line2D.Double(x-borderSize, y+h, x+w+borderSize, y+h); - break; - case left: - line = new Line2D.Double(x, y, x, y+h+borderSize); - break; - case right: - line = new Line2D.Double(x+w, y, x+w, y+h+borderSize); - break; - case top: - line = new Line2D.Double(x-borderSize, y, x+w+borderSize, y); - break; - } - - graphics.draw(line); - } - } - } - - // draw text - drawContent(graphics); - } - - public void drawContent(Graphics2D graphics) { - Drawable d = getGroupShape(graphics); - if (d != null) { - d.drawContent(graphics); - return; - } - - TableShape ts = getShape(); - DrawFactory df = DrawFactory.getInstance(graphics); - - final int rows = ts.getNumberOfRows(); - final int cols = ts.getNumberOfColumns(); - - for (int row=0; row tc = ts.getCell(row, col); - if (tc != null) { - DrawTextShape dts = df.getDrawable(tc); - dts.drawContent(graphics); - } - } - } - } - - @Override - protected TableShape getShape() { - return (TableShape)shape; - } - - /** - * Format the table and apply the specified Line to all cell boundaries, - * both outside and inside. - * An empty args parameter removes the affected border. - * - * @param args a varargs array possible containing {@link Double} (width), - * {@link LineCompound}, {@link Color}, {@link LineDash} - */ - public void setAllBorders(Object... args) { - TableShape table = getShape(); - final int rows = table.getNumberOfRows(); - final int cols = table.getNumberOfColumns(); - - BorderEdge edges[] = { BorderEdge.top, BorderEdge.left, null, null }; - for (int row = 0; row < rows; row++) { - for (int col = 0; col < cols; col++) { - edges[2] = (col == cols - 1) ? BorderEdge.right : null; - edges[3] = (row == rows - 1) ? BorderEdge.bottom : null; - setEdges(table.getCell(row, col), edges, args); - } - } - } - - /** - * Format the outside border using the specified Line object - * An empty args parameter removes the affected border. - * - * @param args a varargs array possible containing {@link Double} (width), - * {@link LineCompound}, {@link Color}, {@link LineDash} - */ - public void setOutsideBorders(Object... args){ - if (args.length == 0) return; - - TableShape table = getShape(); - final int rows = table.getNumberOfRows(); - final int cols = table.getNumberOfColumns(); - - BorderEdge edges[] = new BorderEdge[4]; - for (int row = 0; row < rows; row++) { - for (int col = 0; col < cols; col++) { - edges[0] = (col == 0) ? BorderEdge.left : null; - edges[1] = (col == cols - 1) ? BorderEdge.right : null; - edges[2] = (row == 0) ? BorderEdge.top : null; - edges[3] = (row == rows - 1) ? BorderEdge.bottom : null; - setEdges(table.getCell(row, col), edges, args); - } - } - } - - /** - * Format the inside border using the specified Line object - * An empty args parameter removes the affected border. - * - * @param args a varargs array possible containing {@link Double} (width), - * {@link LineCompound}, {@link Color}, {@link LineDash} - */ - public void setInsideBorders(Object... args) { - if (args.length == 0) return; - - TableShape table = getShape(); - final int rows = table.getNumberOfRows(); - final int cols = table.getNumberOfColumns(); - - BorderEdge edges[] = new BorderEdge[2]; - for (int row = 0; row < rows; row++) { - for (int col = 0; col < cols; col++) { - edges[0] = (col > 0 && col < cols - 1) ? BorderEdge.right : null; - edges[1] = (row > 0 && row < rows - 1) ? BorderEdge.bottom : null; - setEdges(table.getCell(row, col), edges, args); - } - } - } - - /** - * Apply the border attributes (args) to the given cell and edges - * - * @param cell the cell - * @param edges the border edges - * @param args the border attributes - */ - private static void setEdges(TableCell cell, BorderEdge edges[], Object... args) { - if (cell == null) { - return; - } - for (BorderEdge be : edges) { - if (be != null) { - if (args.length == 0) { - cell.removeBorder(be); - } else { - for (Object o : args) { - if (o instanceof Double) { - cell.setBorderWidth(be, (Double)o); - } else if (o instanceof Color) { - cell.setBorderColor(be, (Color)o); - } else if (o instanceof LineDash) { - cell.setBorderDash(be, (LineDash)o); - } else if (o instanceof LineCompound) { - cell.setBorderCompound(be, (LineCompound)o); - } - } - } - } - } - } -} diff --git a/src/java/org/apache/poi/sl/draw/DrawTextBox.java b/src/java/org/apache/poi/sl/draw/DrawTextBox.java deleted file mode 100644 index 1b2b2f444..000000000 --- a/src/java/org/apache/poi/sl/draw/DrawTextBox.java +++ /dev/null @@ -1,26 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw; - -import org.apache.poi.sl.usermodel.*; - -public class DrawTextBox extends DrawAutoShape { - public DrawTextBox(TextBox shape) { - super(shape); - } -} diff --git a/src/java/org/apache/poi/sl/draw/DrawTextFragment.java b/src/java/org/apache/poi/sl/draw/DrawTextFragment.java deleted file mode 100644 index 178983d5e..000000000 --- a/src/java/org/apache/poi/sl/draw/DrawTextFragment.java +++ /dev/null @@ -1,105 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw; - -import java.awt.Graphics2D; -import java.awt.font.TextLayout; -import java.text.*; - -public class DrawTextFragment implements Drawable { - final TextLayout layout; - final AttributedString str; - double x, y; - - public DrawTextFragment(TextLayout layout, AttributedString str) { - this.layout = layout; - this.str = str; - } - - public void setPosition(double x, double y) { - // TODO: replace it, by applyTransform???? - this.x = x; - this.y = y; - } - - public void draw(Graphics2D graphics){ - if(str == null) { - return; - } - - double yBaseline = y + layout.getAscent(); - - Integer textMode = (Integer)graphics.getRenderingHint(Drawable.TEXT_RENDERING_MODE); - if(textMode != null && textMode == Drawable.TEXT_AS_SHAPES){ - layout.draw(graphics, (float)x, (float)yBaseline); - } else { - graphics.drawString(str.getIterator(), (float)x, (float)yBaseline ); - } - } - - public void applyTransform(Graphics2D graphics) { - } - - public void drawContent(Graphics2D graphics) { - } - - public TextLayout getLayout() { - return layout; - } - - public AttributedString getAttributedString() { - return str; - } - - /** - * @return full height of this text run which is sum of ascent, descent and leading - */ - public float getHeight(){ - double h = Math.ceil(layout.getAscent()) + Math.ceil(layout.getDescent()) + layout.getLeading(); - return (float)h; - } - - /** - * - * @return width if this text run - */ - public float getWidth(){ - return layout.getAdvance(); - } - - /** - * - * @return the string to be painted - */ - public String getString(){ - if (str == null) return ""; - - AttributedCharacterIterator it = str.getIterator(); - StringBuilder buf = new StringBuilder(); - for (char c = it.first(); c != CharacterIterator.DONE; c = it.next()) { - buf.append(c); - } - return buf.toString(); - } - - @Override - public String toString(){ - return "[" + getClass().getSimpleName() + "] " + getString(); - } - -} diff --git a/src/java/org/apache/poi/sl/draw/DrawTextParagraph.java b/src/java/org/apache/poi/sl/draw/DrawTextParagraph.java deleted file mode 100644 index d978b3c37..000000000 --- a/src/java/org/apache/poi/sl/draw/DrawTextParagraph.java +++ /dev/null @@ -1,769 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw; - -import java.awt.Dimension; -import java.awt.Font; -import java.awt.Graphics2D; -import java.awt.Paint; -import java.awt.font.FontRenderContext; -import java.awt.font.LineBreakMeasurer; -import java.awt.font.TextAttribute; -import java.awt.font.TextLayout; -import java.awt.geom.Rectangle2D; -import java.io.InvalidObjectException; -import java.text.AttributedCharacterIterator; -import java.text.AttributedCharacterIterator.Attribute; -import java.text.AttributedString; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import org.apache.poi.sl.usermodel.AutoNumberingScheme; -import org.apache.poi.sl.usermodel.Hyperlink; -import org.apache.poi.sl.usermodel.Insets2D; -import org.apache.poi.sl.usermodel.PaintStyle; -import org.apache.poi.sl.usermodel.PlaceableShape; -import org.apache.poi.sl.usermodel.ShapeContainer; -import org.apache.poi.sl.usermodel.Sheet; -import org.apache.poi.sl.usermodel.Slide; -import org.apache.poi.sl.usermodel.TextParagraph; -import org.apache.poi.sl.usermodel.TextParagraph.BulletStyle; -import org.apache.poi.sl.usermodel.TextParagraph.TextAlign; -import org.apache.poi.sl.usermodel.TextRun; -import org.apache.poi.sl.usermodel.TextRun.FieldType; -import org.apache.poi.sl.usermodel.TextRun.TextCap; -import org.apache.poi.sl.usermodel.TextShape; -import org.apache.poi.sl.usermodel.TextShape.TextDirection; -import org.apache.poi.util.StringUtil; -import org.apache.poi.util.Units; - - -public class DrawTextParagraph implements Drawable { - /** Keys for passing hyperlinks to the graphics context */ - public static final XlinkAttribute HYPERLINK_HREF = new XlinkAttribute("href"); - public static final XlinkAttribute HYPERLINK_LABEL = new XlinkAttribute("label"); - - protected TextParagraph paragraph; - double x, y; - protected List lines = new ArrayList(); - protected String rawText; - protected DrawTextFragment bullet; - protected int autoNbrIdx; - - /** - * the highest line in this paragraph. Used for line spacing. - */ - protected double maxLineHeight; - - /** - * Defines an attribute used for storing the hyperlink associated with - * some renderable text. - */ - private static class XlinkAttribute extends Attribute { - - XlinkAttribute(String name) { - super(name); - } - - /** - * Resolves instances being deserialized to the predefined constants. - */ - @Override - protected Object readResolve() throws InvalidObjectException { - if (HYPERLINK_HREF.getName().equals(getName())) { - return HYPERLINK_HREF; - } - if (HYPERLINK_LABEL.getName().equals(getName())) { - return HYPERLINK_LABEL; - } - throw new InvalidObjectException("unknown attribute name"); - } - } - - - public DrawTextParagraph(TextParagraph paragraph) { - this.paragraph = paragraph; - } - - public void setPosition(double x, double y) { - // TODO: replace it, by applyTransform???? - this.x = x; - this.y = y; - } - - public double getY() { - return y; - } - - /** - * Sets the auto numbering index of the handled paragraph - * @param index the auto numbering index - */ - public void setAutoNumberingIdx(int index) { - autoNbrIdx = index; - } - - @Override - public void draw(Graphics2D graphics){ - if (lines.isEmpty()) { - return; - } - - double penY = y; - - boolean firstLine = true; - int indentLevel = paragraph.getIndentLevel(); - Double leftMargin = paragraph.getLeftMargin(); - if (leftMargin == null) { - // if the marL attribute is omitted, then a value of 347663 is implied - leftMargin = Units.toPoints(347663L*indentLevel); - } - Double indent = paragraph.getIndent(); - if (indent == null) { - indent = Units.toPoints(347663L*indentLevel); - } - if (isHSLF()) { - // special handling for HSLF - indent -= leftMargin; - } - -// Double rightMargin = paragraph.getRightMargin(); -// if (rightMargin == null) { -// rightMargin = 0d; -// } - - //The vertical line spacing - Double spacing = paragraph.getLineSpacing(); - if (spacing == null) { - spacing = 100d; - } - - for(DrawTextFragment line : lines){ - double penX; - - if(firstLine) { - if (!isEmptyParagraph()) { - // TODO: find out character style for empty, but bulleted/numbered lines - bullet = getBullet(graphics, line.getAttributedString().getIterator()); - } - - if (bullet != null){ - bullet.setPosition(x+leftMargin+indent, penY); - bullet.draw(graphics); - // don't let text overlay the bullet and advance by the bullet width - double bulletWidth = bullet.getLayout().getAdvance() + 1; - penX = x + Math.max(leftMargin, leftMargin+indent+bulletWidth); - } else { - penX = x + leftMargin; - } - } else { - penX = x + leftMargin; - } - - Rectangle2D anchor = DrawShape.getAnchor(graphics, paragraph.getParentShape()); - // Insets are already applied on DrawTextShape.drawContent - // but (outer) anchor need to be adjusted - Insets2D insets = paragraph.getParentShape().getInsets(); - double leftInset = insets.left; - double rightInset = insets.right; - - TextAlign ta = paragraph.getTextAlign(); - if (ta == null) { - ta = TextAlign.LEFT; - } - switch (ta) { - case CENTER: - penX += (anchor.getWidth() - line.getWidth() - leftInset - rightInset - leftMargin) / 2; - break; - case RIGHT: - penX += (anchor.getWidth() - line.getWidth() - leftInset - rightInset); - break; - default: - break; - } - - line.setPosition(penX, penY); - line.draw(graphics); - - if(spacing > 0) { - // If linespacing >= 0, then linespacing is a percentage of normal line height. - penY += spacing*0.01* line.getHeight(); - } else { - // negative value means absolute spacing in points - penY += -spacing; - } - - firstLine = false; - } - - y = penY - y; - } - - public float getFirstLineHeight() { - return (lines.isEmpty()) ? 0 : lines.get(0).getHeight(); - } - - public float getLastLineHeight() { - return (lines.isEmpty()) ? 0 : lines.get(lines.size()-1).getHeight(); - } - - public boolean isEmptyParagraph() { - return (lines.isEmpty() || rawText.trim().isEmpty()); - } - - @Override - public void applyTransform(Graphics2D graphics) { - } - - @Override - public void drawContent(Graphics2D graphics) { - } - - /** - * break text into lines, each representing a line of text that fits in the wrapping width - * - * @param graphics The drawing context for computing text-lengths. - */ - protected void breakText(Graphics2D graphics){ - lines.clear(); - - DrawFactory fact = DrawFactory.getInstance(graphics); - StringBuilder text = new StringBuilder(); - AttributedString at = getAttributedString(graphics, text); - boolean emptyParagraph = ("".equals(text.toString().trim())); - - AttributedCharacterIterator it = at.getIterator(); - LineBreakMeasurer measurer = new LineBreakMeasurer(it, graphics.getFontRenderContext()); - for (;;) { - int startIndex = measurer.getPosition(); - - double wrappingWidth = getWrappingWidth(lines.size() == 0, graphics) + 1; // add a pixel to compensate rounding errors - // shape width can be smaller that the sum of insets (this was proved by a test file) - if(wrappingWidth < 0) { - wrappingWidth = 1; - } - - int nextBreak = text.indexOf("\n", startIndex + 1); - if (nextBreak == -1) { - nextBreak = it.getEndIndex(); - } - - TextLayout layout = measurer.nextLayout((float)wrappingWidth, nextBreak, true); - if (layout == null) { - // layout can be null if the entire word at the current position - // does not fit within the wrapping width. Try with requireNextWord=false. - layout = measurer.nextLayout((float)wrappingWidth, nextBreak, false); - } - - if(layout == null) { - // exit if can't break any more - break; - } - - int endIndex = measurer.getPosition(); - // skip over new line breaks (we paint 'clear' text runs not starting or ending with \n) - if(endIndex < it.getEndIndex() && text.charAt(endIndex) == '\n'){ - measurer.setPosition(endIndex + 1); - } - - TextAlign hAlign = paragraph.getTextAlign(); - if(hAlign == TextAlign.JUSTIFY || hAlign == TextAlign.JUSTIFY_LOW) { - layout = layout.getJustifiedLayout((float)wrappingWidth); - } - - AttributedString str = (emptyParagraph) - ? null // we will not paint empty paragraphs - : new AttributedString(it, startIndex, endIndex); - DrawTextFragment line = fact.getTextFragment(layout, str); - lines.add(line); - - maxLineHeight = Math.max(maxLineHeight, line.getHeight()); - - if(endIndex == it.getEndIndex()) { - break; - } - } - - rawText = text.toString(); - } - - protected DrawTextFragment getBullet(Graphics2D graphics, AttributedCharacterIterator firstLineAttr) { - BulletStyle bulletStyle = paragraph.getBulletStyle(); - if (bulletStyle == null) { - return null; - } - - String buCharacter; - AutoNumberingScheme ans = bulletStyle.getAutoNumberingScheme(); - if (ans != null) { - buCharacter = ans.format(autoNbrIdx); - } else { - buCharacter = bulletStyle.getBulletCharacter(); - } - if (buCharacter == null) { - return null; - } - - String buFont = bulletStyle.getBulletFont(); - if (buFont == null) { - buFont = paragraph.getDefaultFontFamily(); - } - assert(buFont != null); - - PlaceableShape ps = getParagraphShape(); - PaintStyle fgPaintStyle = bulletStyle.getBulletFontColor(); - Paint fgPaint; - if (fgPaintStyle == null) { - fgPaint = (Paint)firstLineAttr.getAttribute(TextAttribute.FOREGROUND); - } else { - fgPaint = new DrawPaint(ps).getPaint(graphics, fgPaintStyle); - } - - float fontSize = (Float)firstLineAttr.getAttribute(TextAttribute.SIZE); - Double buSz = bulletStyle.getBulletFontSize(); - if (buSz == null) { - buSz = 100d; - } - if (buSz > 0) { - fontSize *= buSz* 0.01; - } else { - fontSize = (float)-buSz; - } - - - AttributedString str = new AttributedString(mapFontCharset(buCharacter,buFont)); - str.addAttribute(TextAttribute.FOREGROUND, fgPaint); - str.addAttribute(TextAttribute.FAMILY, buFont); - str.addAttribute(TextAttribute.SIZE, fontSize); - - TextLayout layout = new TextLayout(str.getIterator(), graphics.getFontRenderContext()); - DrawFactory fact = DrawFactory.getInstance(graphics); - return fact.getTextFragment(layout, str); - } - - protected String getRenderableText(Graphics2D graphics, TextRun tr) { - if (tr.getFieldType() == FieldType.SLIDE_NUMBER) { - Slide slide = (Slide)graphics.getRenderingHint(Drawable.CURRENT_SLIDE); - return (slide == null) ? "" : Integer.toString(slide.getSlideNumber()); - } - StringBuilder buf = new StringBuilder(); - TextCap cap = tr.getTextCap(); - String tabs = null; - for (char c : tr.getRawText().toCharArray()) { - switch (c) { - case '\t': - if (tabs == null) { - tabs = tab2space(tr); - } - buf.append(tabs); - break; - case '\u000b': - buf.append('\n'); - break; - default: - switch (cap) { - case ALL: c = Character.toUpperCase(c); break; - case SMALL: c = Character.toLowerCase(c); break; - case NONE: break; - } - - buf.append(c); - break; - } - } - - return buf.toString(); - } - - /** - * Replace a tab with the effective number of white spaces. - */ - private String tab2space(TextRun tr) { - AttributedString string = new AttributedString(" "); - String fontFamily = tr.getFontFamily(); - if (fontFamily == null) { - fontFamily = "Lucida Sans"; - } - string.addAttribute(TextAttribute.FAMILY, fontFamily); - - Double fs = tr.getFontSize(); - if (fs == null) { - fs = 12d; - } - string.addAttribute(TextAttribute.SIZE, fs.floatValue()); - - TextLayout l = new TextLayout(string.getIterator(), new FontRenderContext(null, true, true)); - double wspace = l.getAdvance(); - - Double tabSz = paragraph.getDefaultTabSize(); - if (tabSz == null) { - tabSz = wspace*4; - } - - int numSpaces = (int)Math.ceil(tabSz / wspace); - StringBuilder buf = new StringBuilder(); - for(int i = 0; i < numSpaces; i++) { - buf.append(' '); - } - return buf.toString(); - } - - - /** - * Returns wrapping width to break lines in this paragraph - * - * @param firstLine whether the first line is breaking - * - * @return wrapping width in points - */ - protected double getWrappingWidth(boolean firstLine, Graphics2D graphics){ - TextShape ts = paragraph.getParentShape(); - - // internal margins for the text box - Insets2D insets = ts.getInsets(); - double leftInset = insets.left; - double rightInset = insets.right; - - int indentLevel = paragraph.getIndentLevel(); - if (indentLevel == -1) { - // default to 0, if indentLevel is not set - indentLevel = 0; - } - Double leftMargin = paragraph.getLeftMargin(); - if (leftMargin == null) { - // if the marL attribute is omitted, then a value of 347663 is implied - leftMargin = Units.toPoints(347663L*(indentLevel+1)); - } - Double indent = paragraph.getIndent(); - if (indent == null) { - indent = Units.toPoints(347663L*indentLevel); - } - Double rightMargin = paragraph.getRightMargin(); - if (rightMargin == null) { - rightMargin = 0d; - } - - Rectangle2D anchor = DrawShape.getAnchor(graphics, ts); - TextDirection textDir = ts.getTextDirection(); - double width; - if (!ts.getWordWrap()) { - Dimension pageDim = ts.getSheet().getSlideShow().getPageSize(); - // if wordWrap == false then we return the advance to the (right) border of the sheet - switch (textDir) { - default: - width = pageDim.getWidth() - anchor.getX(); - break; - case VERTICAL: - width = pageDim.getHeight() - anchor.getX(); - break; - case VERTICAL_270: - width = anchor.getX(); - break; - } - } else { - switch (textDir) { - default: - width = anchor.getWidth() - leftInset - rightInset - leftMargin - rightMargin; - break; - case VERTICAL: - case VERTICAL_270: - width = anchor.getHeight() - leftInset - rightInset - leftMargin - rightMargin; - break; - } - if (firstLine && !isHSLF()) { - if (bullet != null){ - if (indent > 0) { - width -= indent; - } - } else { - if (indent > 0) { - width -= indent; // first line indentation - } else if (indent < 0) { // hanging indentation: the first line start at the left margin - width += leftMargin; - } - } - } - } - - return width; - } - - private static class AttributedStringData { - Attribute attribute; - Object value; - int beginIndex, endIndex; - AttributedStringData(Attribute attribute, Object value, int beginIndex, int endIndex) { - this.attribute = attribute; - this.value = value; - this.beginIndex = beginIndex; - this.endIndex = endIndex; - } - } - - /** - * Helper method for paint style relative to bounds, e.g. gradient paint - */ - @SuppressWarnings("rawtypes") - private PlaceableShape getParagraphShape() { - return new PlaceableShape(){ - @Override - public ShapeContainer getParent() { return null; } - @Override - public Rectangle2D getAnchor() { return paragraph.getParentShape().getAnchor(); } - @Override - public void setAnchor(Rectangle2D anchor) {} - @Override - public double getRotation() { return 0; } - @Override - public void setRotation(double theta) {} - @Override - public void setFlipHorizontal(boolean flip) {} - @Override - public void setFlipVertical(boolean flip) {} - @Override - public boolean getFlipHorizontal() { return false; } - @Override - public boolean getFlipVertical() { return false; } - @Override - public Sheet getSheet() { return paragraph.getParentShape().getSheet(); } - }; - } - - protected AttributedString getAttributedString(Graphics2D graphics, StringBuilder text){ - List attList = new ArrayList(); - if (text == null) { - text = new StringBuilder(); - } - - PlaceableShape ps = getParagraphShape(); - DrawFontManager fontHandler = (DrawFontManager)graphics.getRenderingHint(Drawable.FONT_HANDLER); - @SuppressWarnings("unchecked") - Map fontMap = (Map)graphics.getRenderingHint(Drawable.FONT_MAP); - @SuppressWarnings("unchecked") - Map fallbackMap = (Map)graphics.getRenderingHint(Drawable.FONT_FALLBACK); - - for (TextRun run : paragraph){ - String runText = getRenderableText(graphics, run); - // skip empty runs - if (runText.isEmpty()) { - continue; - } - - // user can pass an custom object to convert fonts - String mappedFont = run.getFontFamily(); - String fallbackFont = Font.SANS_SERIF; - - if (mappedFont == null) { - mappedFont = paragraph.getDefaultFontFamily(); - } - if (mappedFont == null) { - mappedFont = Font.SANS_SERIF; - } - if (fontHandler != null) { - String font = fontHandler.getRendererableFont(mappedFont, run.getPitchAndFamily()); - if (font != null) { - mappedFont = font; - } - font = fontHandler.getFallbackFont(mappedFont, run.getPitchAndFamily()); - if (font != null) { - fallbackFont = font; - } - } else { - mappedFont = getFontWithFallback(fontMap, mappedFont); - fallbackFont = getFontWithFallback(fallbackMap, mappedFont); - } - - runText = mapFontCharset(runText,mappedFont); - int beginIndex = text.length(); - text.append(runText); - int endIndex = text.length(); - - attList.add(new AttributedStringData(TextAttribute.FAMILY, mappedFont, beginIndex, endIndex)); - - PaintStyle fgPaintStyle = run.getFontColor(); - Paint fgPaint = new DrawPaint(ps).getPaint(graphics, fgPaintStyle); - attList.add(new AttributedStringData(TextAttribute.FOREGROUND, fgPaint, beginIndex, endIndex)); - - Double fontSz = run.getFontSize(); - if (fontSz == null) { - fontSz = paragraph.getDefaultFontSize(); - } - attList.add(new AttributedStringData(TextAttribute.SIZE, fontSz.floatValue(), beginIndex, endIndex)); - - if(run.isBold()) { - attList.add(new AttributedStringData(TextAttribute.WEIGHT, TextAttribute.WEIGHT_BOLD, beginIndex, endIndex)); - } - if(run.isItalic()) { - attList.add(new AttributedStringData(TextAttribute.POSTURE, TextAttribute.POSTURE_OBLIQUE, beginIndex, endIndex)); - } - if(run.isUnderlined()) { - attList.add(new AttributedStringData(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON, beginIndex, endIndex)); - attList.add(new AttributedStringData(TextAttribute.INPUT_METHOD_UNDERLINE, TextAttribute.UNDERLINE_LOW_TWO_PIXEL, beginIndex, endIndex)); - } - if(run.isStrikethrough()) { - attList.add(new AttributedStringData(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON, beginIndex, endIndex)); - } - if(run.isSubscript()) { - attList.add(new AttributedStringData(TextAttribute.SUPERSCRIPT, TextAttribute.SUPERSCRIPT_SUB, beginIndex, endIndex)); - } - if(run.isSuperscript()) { - attList.add(new AttributedStringData(TextAttribute.SUPERSCRIPT, TextAttribute.SUPERSCRIPT_SUPER, beginIndex, endIndex)); - } - - Hyperlink hl = run.getHyperlink(); - if (hl != null) { - attList.add(new AttributedStringData(HYPERLINK_HREF, hl.getAddress(), beginIndex, endIndex)); - attList.add(new AttributedStringData(HYPERLINK_LABEL, hl.getLabel(), beginIndex, endIndex)); - } - - int style = (run.isBold() ? Font.BOLD : 0) | (run.isItalic() ? Font.ITALIC : 0); - Font f = new Font(mappedFont, style, (int)Math.rint(fontSz)); - - // check for unsupported characters and add a fallback font for these - char textChr[] = runText.toCharArray(); - int nextEnd = canDisplayUpTo(f, textChr, 0, textChr.length); - int last = nextEnd; - boolean isNextValid = (nextEnd == 0); - while ( nextEnd != -1 && nextEnd <= textChr.length ) { - if (isNextValid) { - nextEnd = canDisplayUpTo(f, textChr, nextEnd, textChr.length); - isNextValid = false; - } else { - if (nextEnd >= textChr.length || f.canDisplay(Character.codePointAt(textChr, nextEnd, textChr.length)) ) { - attList.add(new AttributedStringData(TextAttribute.FAMILY, fallbackFont, beginIndex+last, beginIndex+Math.min(nextEnd,textChr.length))); - if (nextEnd >= textChr.length) { - break; - } - last = nextEnd; - isNextValid = true; - } else { - boolean isHS = Character.isHighSurrogate(textChr[nextEnd]); - nextEnd+=(isHS?2:1); - } - } - } - } - - // ensure that the paragraph contains at least one character - // We need this trick to correctly measure text - if (text.length() == 0) { - Double fontSz = paragraph.getDefaultFontSize(); - text.append(" "); - attList.add(new AttributedStringData(TextAttribute.SIZE, fontSz.floatValue(), 0, 1)); - } - - AttributedString string = new AttributedString(text.toString()); - for (AttributedStringData asd : attList) { - string.addAttribute(asd.attribute, asd.value, asd.beginIndex, asd.endIndex); - } - - return string; - } - - private String getFontWithFallback(Map fontMap, String mappedFont) { - if (fontMap != null) { - if (fontMap.containsKey(mappedFont)) { - mappedFont = fontMap.get(mappedFont); - } else if (fontMap.containsKey("*")) { - mappedFont = fontMap.get("*"); - } - } - return mappedFont; - } - - /** - * @return {@code true} if the HSLF implementation is used - */ - protected boolean isHSLF() { - return DrawShape.isHSLF(paragraph.getParentShape()); - } - - /** - * Map text charset depending on font family. - * Currently this only maps for wingdings font (into unicode private use area) - * - * @param text the raw text - * @param fontFamily the font family - * @return AttributedString with mapped codepoints - * - * @see Drawing exotic fonts in a java applet - * @see StringUtil#mapMsCodepointString(String) - */ - protected String mapFontCharset(String text, String fontFamily) { - // TODO: find a real charset mapping solution instead of hard coding for Wingdings - String attStr = text; - if ("Wingdings".equalsIgnoreCase(fontFamily)) { - // wingdings doesn't contain high-surrogates, so chars are ok - boolean changed = false; - char chrs[] = attStr.toCharArray(); - for (int i=0; i - * - * This is a workaround for the Java 6 implementation of {@link Font#canDisplayUpTo(char[], int, int)} - * - * @param font the font to inspect - * @param text the specified array of {@code char} values - * @param start the specified starting offset (in - * {@code char}s) into the specified array of - * {@code char} values - * @param limit the specified ending offset (in - * {@code char}s) into the specified array of - * {@code char} values - * @return an offset into {@code text} that points - * to the first character in {@code text} that this - * {@code Font} cannot display; or {@code -1} if - * this {@code Font} can display all characters in - * {@code text}. - * - * @see Font.canDisplayUpTo does not work with supplementary characters - */ - protected static int canDisplayUpTo(Font font, char[] text, int start, int limit) { - for (int i = start; i < limit; i++) { - char c = text[i]; - if (font.canDisplay(c)) { - continue; - } - if (!Character.isHighSurrogate(c)) { - return i; - } - if (!font.canDisplay(Character.codePointAt(text, i, limit))) { - return i; - } - i++; - } - return -1; - } -} diff --git a/src/java/org/apache/poi/sl/draw/DrawTextShape.java b/src/java/org/apache/poi/sl/draw/DrawTextShape.java deleted file mode 100644 index 89f85a2f0..000000000 --- a/src/java/org/apache/poi/sl/draw/DrawTextShape.java +++ /dev/null @@ -1,227 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw; - -import java.awt.Graphics2D; -import java.awt.geom.AffineTransform; -import java.awt.geom.Rectangle2D; -import java.awt.image.BufferedImage; -import java.util.Iterator; - -import org.apache.poi.sl.usermodel.Insets2D; -import org.apache.poi.sl.usermodel.PlaceableShape; -import org.apache.poi.sl.usermodel.ShapeContainer; -import org.apache.poi.sl.usermodel.TextParagraph; -import org.apache.poi.sl.usermodel.TextParagraph.BulletStyle; -import org.apache.poi.sl.usermodel.TextRun; -import org.apache.poi.sl.usermodel.TextShape; -import org.apache.poi.sl.usermodel.TextShape.TextDirection; - -public class DrawTextShape extends DrawSimpleShape { - - public DrawTextShape(TextShape shape) { - super(shape); - } - - @Override - public void drawContent(Graphics2D graphics) { - DrawFactory.getInstance(graphics).fixFonts(graphics); - - TextShape s = getShape(); - - Rectangle2D anchor = DrawShape.getAnchor(graphics, s); - Insets2D insets = s.getInsets(); - double x = anchor.getX() + insets.left; - double y = anchor.getY(); - - // remember the initial transform - AffineTransform tx = graphics.getTransform(); - - // Transform of text in flipped shapes is special. - // At this point the flip and rotation transform is already applied - // (see DrawShape#applyTransform ), but we need to restore it to avoid painting "upside down". - // See Bugzilla 54210. - - boolean vertFlip = s.getFlipVertical(); - boolean horzFlip = s.getFlipHorizontal(); - ShapeContainer sc = s.getParent(); - while (sc instanceof PlaceableShape) { - PlaceableShape ps = (PlaceableShape)sc; - vertFlip ^= ps.getFlipVertical(); - horzFlip ^= ps.getFlipHorizontal(); - sc = ps.getParent(); - } - - // Horizontal flipping applies only to shape outline and not to the text in the shape. - // Applying flip second time restores the original not-flipped transform - if (horzFlip ^ vertFlip) { - final double ax = anchor.getX(); - final double ay = anchor.getY(); - graphics.translate(ax + anchor.getWidth(), ay); - graphics.scale(-1, 1); - graphics.translate(-ax, -ay); - } - - Double textRot = s.getTextRotation(); - if (textRot != null && textRot != 0) { - final double cx = anchor.getCenterX(); - final double cy = anchor.getCenterY(); - graphics.translate(cx, cy); - graphics.rotate(Math.toRadians(textRot)); - graphics.translate(-cx, -cy); - } - - // first dry-run to calculate the total height of the text - double textHeight; - - switch (s.getVerticalAlignment()){ - default: - case TOP: - y += insets.top; - break; - case BOTTOM: - textHeight = getTextHeight(graphics); - y += anchor.getHeight() - textHeight - insets.bottom; - break; - case MIDDLE: - textHeight = getTextHeight(graphics); - double delta = anchor.getHeight() - textHeight - insets.top - insets.bottom; - y += insets.top + delta/2; - break; - } - - TextDirection textDir = s.getTextDirection(); - if (textDir == TextDirection.VERTICAL || textDir == TextDirection.VERTICAL_270) { - final double deg = (textDir == TextDirection.VERTICAL) ? 90 : 270; - final double cx = anchor.getCenterX(); - final double cy = anchor.getCenterY(); - graphics.translate(cx, cy); - graphics.rotate(Math.toRadians(deg)); - graphics.translate(-cx, -cy); - - // old top/left edge is now bottom/left or top/right - as we operate on the already - // rotated drawing context, both verticals can be moved in the same direction - final double w = anchor.getWidth(); - final double h = anchor.getHeight(); - final double dx = (w-h)/2d; - graphics.translate(dx,-dx); - } - - drawParagraphs(graphics, x, y); - - // restore the transform - graphics.setTransform(tx); - } - - /** - * paint the paragraphs starting from top left (x,y) - * - * @return the vertical advance, i.e. the cumulative space occupied by the text - */ - public double drawParagraphs(Graphics2D graphics, double x, double y) { - DrawFactory fact = DrawFactory.getInstance(graphics); - - double y0 = y; - //noinspection RedundantCast - @SuppressWarnings("cast") - Iterator> paragraphs = - (Iterator>) getShape().iterator(); - - boolean isFirstLine = true; - for (int autoNbrIdx=0; paragraphs.hasNext(); autoNbrIdx++){ - TextParagraph p = paragraphs.next(); - DrawTextParagraph dp = fact.getDrawable(p); - BulletStyle bs = p.getBulletStyle(); - if (bs == null || bs.getAutoNumberingScheme() == null) { - autoNbrIdx = -1; - } else { - Integer startAt = bs.getAutoNumberingStartAt(); - if (startAt == null) startAt = 1; - // TODO: handle reset auto number indexes - if (startAt > autoNbrIdx) autoNbrIdx = startAt; - } - dp.setAutoNumberingIdx(autoNbrIdx); - dp.breakText(graphics); - - if (!isFirstLine) { - // the amount of vertical white space before the paragraph - Double spaceBefore = p.getSpaceBefore(); - if (spaceBefore == null) spaceBefore = 0d; - if(spaceBefore > 0) { - // positive value means percentage spacing of the height of the first line, e.g. - // the higher the first line, the bigger the space before the paragraph - y += spaceBefore*0.01*dp.getFirstLineHeight(); - } else { - // negative value means the absolute spacing in points - y += -spaceBefore; - } - } - isFirstLine = false; - - dp.setPosition(x, y); - dp.draw(graphics); - y += dp.getY(); - - if (paragraphs.hasNext()) { - Double spaceAfter = p.getSpaceAfter(); - if (spaceAfter == null) spaceAfter = 0d; - if(spaceAfter > 0) { - // positive value means percentage spacing of the height of the last line, e.g. - // the higher the last line, the bigger the space after the paragraph - y += spaceAfter*0.01*dp.getLastLineHeight(); - } else { - // negative value means the absolute spacing in points - y += -spaceAfter; - } - } - } - return y - y0; - } - - /** - * Compute the cumulative height occupied by the text - * - * @return the height in points - */ - public double getTextHeight() { - return getTextHeight(null); - } - - /** - * Compute the cumulative height occupied by the text - * - * @param oldGraphics the graphics context, which properties are to be copied, may be null - * @return the height in points - */ - protected double getTextHeight(Graphics2D oldGraphics) { - // dry-run in a 1x1 image and return the vertical advance - BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB); - Graphics2D graphics = img.createGraphics(); - if (oldGraphics != null) { - graphics.addRenderingHints(oldGraphics.getRenderingHints()); - graphics.setTransform(oldGraphics.getTransform()); - } - DrawFactory.getInstance(graphics).fixFonts(graphics); - return drawParagraphs(graphics, 0, 0); - } - - @Override - protected TextShape getShape() { - return (TextShape)shape; - } -} diff --git a/src/java/org/apache/poi/sl/draw/Drawable.java b/src/java/org/apache/poi/sl/draw/Drawable.java deleted file mode 100644 index 4ec653ae5..000000000 --- a/src/java/org/apache/poi/sl/draw/Drawable.java +++ /dev/null @@ -1,161 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw; - -import java.awt.Graphics2D; -import java.awt.RenderingHints; - -import org.apache.poi.util.Internal; - - -public interface Drawable { - class DrawableHint extends RenderingHints.Key { - protected DrawableHint(int id) { - super(id); - } - - public boolean isCompatibleValue(Object val) { - return true; - } - - public String toString() { - switch (intKey()) { - case 1: return "DRAW_FACTORY"; - case 2: return "GROUP_TRANSFORM"; - case 3: return "IMAGE_RENDERER"; - case 4: return "TEXT_RENDERING_MODE"; - case 5: return "GRADIENT_SHAPE"; - case 6: return "PRESET_GEOMETRY_CACHE"; - case 7: return "FONT_HANDLER"; - case 8: return "FONT_FALLBACK"; - case 9: return "FONT_MAP"; - case 10: return "GSAVE"; - case 11: return "GRESTORE"; - default: return "UNKNOWN_ID "+intKey(); - } - } - } - - /** - * {@link DrawFactory} which will be used to draw objects into this graphics context - */ - DrawableHint DRAW_FACTORY = new DrawableHint(1); - - /** - * Key will be internally used to store affine transformation temporarily within group shapes - */ - @Internal - DrawableHint GROUP_TRANSFORM = new DrawableHint(2); - - /** - * Use a custom image renderer of an instance of {@link ImageRenderer} - */ - DrawableHint IMAGE_RENDERER = new DrawableHint(3); - - /** - * how to render text: - * - * {@link #TEXT_AS_CHARACTERS} (default) means to draw via - * {@link java.awt.Graphics2D#drawString(java.text.AttributedCharacterIterator, float, float)}. - * This mode draws text as characters. Use it if the target graphics writes the actual - * character codes instead of glyph outlines (PDFGraphics2D, SVGGraphics2D, etc.) - * - * {@link #TEXT_AS_SHAPES} means to render via - * {@link java.awt.font.TextLayout#draw(java.awt.Graphics2D, float, float)}. - * This mode draws glyphs as shapes and provides some advanced capabilities such as - * justification and font substitution. Use it if the target graphics is an image. - * - */ - DrawableHint TEXT_RENDERING_MODE = new DrawableHint(4); - - /** - * PathGradientPaint needs the shape to be set. - * It will be achieved through setting it in the rendering hints - */ - DrawableHint GRADIENT_SHAPE = new DrawableHint(5); - - - /** - * Internal key for caching the preset geometries - */ - DrawableHint PRESET_GEOMETRY_CACHE = new DrawableHint(6); - - /** - * draw text via {@link java.awt.Graphics2D#drawString(java.text.AttributedCharacterIterator, float, float)} - */ - int TEXT_AS_CHARACTERS = 1; - - /** - * draw text via {@link java.awt.font.TextLayout#draw(java.awt.Graphics2D, float, float)} - */ - int TEXT_AS_SHAPES = 2; - - /** - * Use this object to resolve unknown / missing fonts when rendering slides. - * The font handler must be of type {@link DrawFontManager}.

    - * - * In case a {@code FONT_HANDLER} is register, {@code FONT_FALLBACK} and {@code FONT_MAP} are ignored - */ - DrawableHint FONT_HANDLER = new DrawableHint(7); - - /** - * Key for a font fallback map of type {@code Map} which maps - * the original font family (key) to the fallback font family (value). - * In case there is also a {@code FONT_MAP} registered, the original font - * is first mapped via the font_map and then the fallback font is determined - */ - DrawableHint FONT_FALLBACK = new DrawableHint(8); - - /** - * Key for a font map of type {@code Map} which maps - * the original font family (key) to the mapped font family (value) - */ - DrawableHint FONT_MAP = new DrawableHint(9); - - DrawableHint GSAVE = new DrawableHint(10); - DrawableHint GRESTORE = new DrawableHint(11); - - /** - * The Common SL Draw API works sometimes cascading, but there are places - * where the current slide context need to be evaluated, e.g. when slide numbers - * are printed. In this situation we need to have a way to access the current slide - */ - DrawableHint CURRENT_SLIDE = new DrawableHint(12); - - - /** - * Apply 2-D transforms before drawing this shape. This includes rotation and flipping. - * - * @param graphics the graphics whos transform matrix will be modified - */ - void applyTransform(Graphics2D graphics); - - /** - * Draw this shape into the supplied canvas - * - * @param graphics the graphics to draw into - */ - void draw(Graphics2D graphics); - - /** - * draw any content within this shape (image, text, etc.). - * - * @param graphics the graphics to draw into - */ - void drawContent(Graphics2D graphics); -} diff --git a/src/java/org/apache/poi/sl/draw/ImageRenderer.java b/src/java/org/apache/poi/sl/draw/ImageRenderer.java deleted file mode 100644 index 7ecc96a96..000000000 --- a/src/java/org/apache/poi/sl/draw/ImageRenderer.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -package org.apache.poi.sl.draw; - -import java.awt.Dimension; -import java.awt.Graphics2D; -import java.awt.Insets; -import java.awt.geom.Rectangle2D; -import java.awt.image.BufferedImage; -import java.io.IOException; -import java.io.InputStream; - -/** - * Classes can implement this interfaces to support other formats, for - * example, use Apache Batik to render WMF, PICT can be rendered using Apple QuickTime API for Java: - * - *

    - * 
    - * public class MyImageRendener implements ImageRendener {
    - *     InputStream data;
    - *
    - *     public boolean drawImage(Graphics2D graphics,Rectangle2D anchor,Insets clip) {
    - *         // draw image
    - *       DataInputStream is = new DataInputStream(data);
    - *       org.apache.batik.transcoder.wmf.tosvg.WMFRecordStore wmfStore =
    - *               new org.apache.batik.transcoder.wmf.tosvg.WMFRecordStore();
    - *       try {
    - *           wmfStore.read(is);
    - *       } catch (IOException e){
    - *           return;
    - *       }
    - *
    - *       float scale = (float)anchor.width/wmfStore.getWidthPixels();
    - *
    - *       org.apache.batik.transcoder.wmf.tosvg.WMFPainter painter =
    - *               new org.apache.batik.transcoder.wmf.tosvg.WMFPainter(wmfStore, 0, 0, scale);
    - *       graphics.translate(anchor.x, anchor.y);
    - *       painter.paint(graphics);
    - *     }
    - *
    - *     public void loadImage(InputStream data, String contentType) throws IOException {
    - *         if ("image/wmf".equals(contentType)) {
    - *             this.data = data;
    - *             // use Apache Batik to handle WMF
    - *         } else {
    - *             super.loadImage(data,contentType);
    - *         }
    - *     }
    - * }
    - * 
    - * 
    - * - * and then pass this class to your instance of java.awt.Graphics2D: - * - *
    - * 
    - * graphics.setRenderingHint(Drawable.IMAGE_RENDERER, new MyImageRendener());
    - * 
    - * 
    - */ -public interface ImageRenderer { - /** - * Load and buffer the image - * - * @param data the raw image stream - * @param contentType the content type - */ - void loadImage(InputStream data, String contentType) throws IOException; - - /** - * Load and buffer the image - * - * @param data the raw image bytes - * @param contentType the content type - */ - void loadImage(byte data[], String contentType) throws IOException; - - /** - * @return the dimension of the buffered image - */ - Dimension getDimension(); - - /** - * @param alpha the alpha [0..1] to be added to the image (possibly already containing an alpha channel) - */ - void setAlpha(double alpha); - - /** - * @return the image as buffered image - */ - BufferedImage getImage(); - - /** - * @param dim the dimension in pixels of the returned image - * @return the image as buffered image - * - * @since POI 3.15-beta2 - */ - BufferedImage getImage(Dimension dim); - - /** - * Render picture data into the supplied graphics - * - * @return true if the picture data was successfully rendered - */ - boolean drawImage(Graphics2D graphics, Rectangle2D anchor); - - /** - * Render picture data into the supplied graphics - * - * @return true if the picture data was successfully rendered - */ - boolean drawImage(Graphics2D graphics, Rectangle2D anchor, Insets clip); -} \ No newline at end of file diff --git a/src/java/org/apache/poi/sl/draw/PathGradientPaint.java b/src/java/org/apache/poi/sl/draw/PathGradientPaint.java deleted file mode 100644 index d4a2a5fa5..000000000 --- a/src/java/org/apache/poi/sl/draw/PathGradientPaint.java +++ /dev/null @@ -1,188 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw; - -import java.awt.*; -import java.awt.MultipleGradientPaint.ColorSpaceType; -import java.awt.MultipleGradientPaint.CycleMethod; -import java.awt.geom.*; -import java.awt.image.*; - -class PathGradientPaint implements Paint { - - // http://asserttrue.blogspot.de/2010/01/how-to-iimplement-custom-paint-in-50.html - protected final Color colors[]; - protected final float fractions[]; - protected final int capStyle; - protected final int joinStyle; - protected final int transparency; - - - public PathGradientPaint(Color colors[], float fractions[]) { - this(colors,fractions,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND); - } - - public PathGradientPaint(Color colors[], float fractions[], int capStyle, int joinStyle) { - this.colors = colors.clone(); - this.fractions = fractions.clone(); - this.capStyle = capStyle; - this.joinStyle = joinStyle; - - // determine transparency - boolean opaque = true; - for (Color c : colors) { - if (c != null) { - opaque = opaque && (c.getAlpha() == 0xff); - } - } - this.transparency = opaque ? OPAQUE : TRANSLUCENT; - } - - public PaintContext createContext(ColorModel cm, - Rectangle deviceBounds, - Rectangle2D userBounds, - AffineTransform transform, - RenderingHints hints) { - return new PathGradientContext(cm, deviceBounds, userBounds, transform, hints); - } - - public int getTransparency() { - return transparency; - } - - class PathGradientContext implements PaintContext { - protected final Rectangle deviceBounds; - protected final Rectangle2D userBounds; - protected final AffineTransform xform; - protected final RenderingHints hints; - - /** - * for POI: the shape will be only known when the subclasses determines the concrete implementation - * in the draw/-content method, so we need to postpone the setting/creation as long as possible - **/ - protected final Shape shape; - protected final PaintContext pCtx; - protected final int gradientSteps; - WritableRaster raster; - - public PathGradientContext( - ColorModel cm - , Rectangle deviceBounds - , Rectangle2D userBounds - , AffineTransform xform - , RenderingHints hints - ) { - shape = (Shape)hints.get(Drawable.GRADIENT_SHAPE); - if (shape == null) { - throw new IllegalPathStateException("PathGradientPaint needs a shape to be set via the rendering hint Drawable.GRADIANT_SHAPE."); - } - - this.deviceBounds = deviceBounds; - this.userBounds = userBounds; - this.xform = xform; - this.hints = hints; - - gradientSteps = getGradientSteps(shape); - - Point2D start = new Point2D.Double(0, 0); - Point2D end = new Point2D.Double(gradientSteps, 0); - LinearGradientPaint gradientPaint = new LinearGradientPaint(start, end, fractions, colors, CycleMethod.NO_CYCLE, ColorSpaceType.SRGB, new AffineTransform()); - - Rectangle bounds = new Rectangle(0, 0, gradientSteps, 1); - pCtx = gradientPaint.createContext(cm, bounds, bounds, new AffineTransform(), hints); - } - - public void dispose() {} - - public ColorModel getColorModel() { - return pCtx.getColorModel(); - } - - public Raster getRaster(int xOffset, int yOffset, int w, int h) { - ColorModel cm = getColorModel(); - if (raster == null) createRaster(); - - // TODO: eventually use caching here - WritableRaster childRaster = cm.createCompatibleWritableRaster(w, h); - Rectangle2D childRect = new Rectangle2D.Double(xOffset, yOffset, w, h); - if (!childRect.intersects(deviceBounds)) { - // usually doesn't happen ... - return childRaster; - } - - Rectangle2D destRect = new Rectangle2D.Double(); - Rectangle2D.intersect(childRect, deviceBounds, destRect); - int dx = (int)(destRect.getX()-deviceBounds.getX()); - int dy = (int)(destRect.getY()-deviceBounds.getY()); - int dw = (int)destRect.getWidth(); - int dh = (int)destRect.getHeight(); - Object data = raster.getDataElements(dx, dy, dw, dh, null); - dx = (int)(destRect.getX()-childRect.getX()); - dy = (int)(destRect.getY()-childRect.getY()); - childRaster.setDataElements(dx, dy, dw, dh, data); - - return childRaster; - } - - protected int getGradientSteps(Shape gradientShape) { - Rectangle rect = gradientShape.getBounds(); - int lower = 1; - int upper = (int)(Math.max(rect.getWidth(),rect.getHeight())/2.0); - while (lower < upper-1) { - int mid = lower + (upper - lower) / 2; - BasicStroke bs = new BasicStroke(mid, capStyle, joinStyle); - Area area = new Area(bs.createStrokedShape(gradientShape)); - if (area.isSingular()) { - upper = mid; - } else { - lower = mid; - } - } - return upper; - } - - - - protected void createRaster() { - ColorModel cm = getColorModel(); - raster = cm.createCompatibleWritableRaster((int)deviceBounds.getWidth(), (int)deviceBounds.getHeight()); - BufferedImage img = new BufferedImage(cm, raster, false, null); - Graphics2D graphics = img.createGraphics(); - graphics.setRenderingHints(hints); - graphics.translate(-deviceBounds.getX(), -deviceBounds.getY()); - graphics.transform(xform); - - Raster img2 = pCtx.getRaster(0, 0, gradientSteps, 1); - int rgb[] = new int[cm.getNumComponents()]; - - for (int i = gradientSteps-1; i>=0; i--) { - img2.getPixel(i, 0, rgb); - Color c = new Color(rgb[0],rgb[1],rgb[2]); - if (rgb.length == 4) { - // it doesn't work to use just a color with transparency ... - graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, rgb[3]/255.0f)); - } - graphics.setStroke(new BasicStroke(i+1, capStyle, joinStyle)); - graphics.setColor(c); - graphics.draw(shape); - } - - graphics.dispose(); - } - } -} diff --git a/src/java/org/apache/poi/sl/draw/SLGraphics.java b/src/java/org/apache/poi/sl/draw/SLGraphics.java deleted file mode 100644 index c9b70cfba..000000000 --- a/src/java/org/apache/poi/sl/draw/SLGraphics.java +++ /dev/null @@ -1,1846 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw; - - -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Composite; -import java.awt.Font; -import java.awt.FontMetrics; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.GraphicsConfiguration; -import java.awt.GraphicsEnvironment; -import java.awt.Image; -import java.awt.Paint; -import java.awt.Rectangle; -import java.awt.RenderingHints; -import java.awt.Shape; -import java.awt.Stroke; -import java.awt.Toolkit; -import java.awt.font.FontRenderContext; -import java.awt.font.GlyphVector; -import java.awt.font.TextLayout; -import java.awt.geom.AffineTransform; -import java.awt.geom.Arc2D; -import java.awt.geom.Ellipse2D; -import java.awt.geom.GeneralPath; -import java.awt.geom.Line2D; -import java.awt.geom.Path2D; -import java.awt.geom.RoundRectangle2D; -import java.awt.image.BufferedImage; -import java.awt.image.BufferedImageOp; -import java.awt.image.ImageObserver; -import java.awt.image.RenderedImage; -import java.awt.image.renderable.RenderableImage; -import java.text.AttributedCharacterIterator; -import java.util.Map; - -import org.apache.poi.sl.usermodel.FreeformShape; -import org.apache.poi.sl.usermodel.GroupShape; -import org.apache.poi.sl.usermodel.Insets2D; -import org.apache.poi.sl.usermodel.SimpleShape; -import org.apache.poi.sl.usermodel.StrokeStyle; -import org.apache.poi.sl.usermodel.TextBox; -import org.apache.poi.sl.usermodel.TextRun; -import org.apache.poi.sl.usermodel.VerticalAlignment; -import org.apache.poi.util.NotImplemented; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.util.SuppressForbidden; - -/** - * Translates Graphics2D calls into PowerPoint. - * - * @author Yegor Kozlov - */ -public final class SLGraphics extends Graphics2D implements Cloneable { - - protected POILogger log = POILogFactory.getLogger(this.getClass()); - - //The ppt object to write into. - private GroupShape _group; - - private AffineTransform _transform; - private Stroke _stroke; - private Paint _paint; - private Font _font; - private Color _foreground; - private Color _background; - private RenderingHints _hints; - - /** - * Construct Java Graphics object which translates graphic calls in ppt drawing layer. - * - * @param group The shape group to write the graphics calls into. - */ - public SLGraphics(GroupShape group){ - this._group = group; - - _transform = new AffineTransform(); - _stroke = new BasicStroke(); - _paint = Color.black; - _font = new Font("Arial", Font.PLAIN, 12); - _background = Color.black; - _foreground = Color.white; - _hints = new RenderingHints(null); - } - - /** - * @return the shape group being used for drawing - */ - public GroupShape getShapeGroup(){ - return _group; - } - - /** - * Gets the current font. - * @return this graphics context's current font. - * @see java.awt.Font - * @see java.awt.Graphics#setFont(Font) - */ - public Font getFont(){ - return _font; - } - - /** - * Sets this graphics context's font to the specified font. - * All subsequent text operations using this graphics context - * use this font. - * @param font the font. - * @see java.awt.Graphics#getFont - * @see java.awt.Graphics#drawString(java.lang.String, int, int) - * @see java.awt.Graphics#drawBytes(byte[], int, int, int, int) - * @see java.awt.Graphics#drawChars(char[], int, int, int, int) - */ - public void setFont(Font font){ - this._font = font; - } - - /** - * Gets this graphics context's current color. - * @return this graphics context's current color. - * @see java.awt.Color - * @see java.awt.Graphics#setColor - */ - public Color getColor(){ - return _foreground; - } - - /** - * Sets this graphics context's current color to the specified - * color. All subsequent graphics operations using this graphics - * context use this specified color. - * @param c the new rendering color. - * @see java.awt.Color - * @see java.awt.Graphics#getColor - */ - public void setColor(Color c) { - setPaint(c); - } - - /** - * Returns the current Stroke in the - * Graphics2D context. - * @return the current Graphics2D Stroke, - * which defines the line style. - * @see #setStroke - */ - public Stroke getStroke(){ - return _stroke; - } - - /** - * Sets the Stroke for the Graphics2D context. - * @param s the Stroke object to be used to stroke a - * Shape during the rendering process - */ - public void setStroke(Stroke s){ - this._stroke = s; - } - - /** - * Returns the current Paint of the - * Graphics2D context. - * @return the current Graphics2D Paint, - * which defines a color or pattern. - * @see #setPaint - * @see java.awt.Graphics#setColor - */ - public Paint getPaint(){ - return _paint; - } - - /** - * Sets the Paint attribute for the - * Graphics2D context. Calling this method - * with a null Paint object does - * not have any effect on the current Paint attribute - * of this Graphics2D. - * @param paint the Paint object to be used to generate - * color during the rendering process, or null - * @see java.awt.Graphics#setColor - */ - public void setPaint(Paint paint){ - if(paint == null) return; - - this._paint = paint; - if (paint instanceof Color) _foreground = (Color)paint; - } - - /** - * Returns a copy of the current Transform in the - * Graphics2D context. - * @return the current AffineTransform in the - * Graphics2D context. - * @see #_transform - * @see #setTransform - */ - public AffineTransform getTransform(){ - return new AffineTransform(_transform); - } - - /** - * Sets the Transform in the Graphics2D - * context. - * @param Tx the AffineTransform object to be used in the - * rendering process - * @see #_transform - * @see AffineTransform - */ - public void setTransform(AffineTransform Tx) { - _transform = new AffineTransform(Tx); - } - - /** - * Strokes the outline of a Shape using the settings of the - * current Graphics2D context. The rendering attributes - * applied include the Clip, Transform, - * Paint, Composite and - * Stroke attributes. - * @param shape the Shape to be rendered - * @see #setStroke - * @see #setPaint - * @see java.awt.Graphics#setColor - * @see #_transform - * @see #setTransform - * @see #clip - * @see #setClip - * @see #setComposite - */ - public void draw(Shape shape){ - Path2D.Double path = new Path2D.Double(_transform.createTransformedShape(shape)); - FreeformShape p = _group.createFreeform(); - p.setPath(path); - p.setFillColor(null); - applyStroke(p); - if (_paint instanceof Color) { - p.setStrokeStyle((Color)_paint); - } - } - - /** - * Renders the text specified by the specified String, - * using the current text attribute state in the Graphics2D context. - * The baseline of the first character is at position - * (xy) in the User Space. - * The rendering attributes applied include the Clip, - * Transform, Paint, Font and - * Composite attributes. For characters in script systems - * such as Hebrew and Arabic, the glyphs can be rendered from right to - * left, in which case the coordinate supplied is the location of the - * leftmost character on the baseline. - * @param s the String to be rendered - * @param x the x coordinate of the location where the - * String should be rendered - * @param y the y coordinate of the location where the - * String should be rendered - * @throws NullPointerException if str is - * null - * @see #setPaint - * @see java.awt.Graphics#setColor - * @see java.awt.Graphics#setFont - * @see #setTransform - * @see #setComposite - * @see #setClip - */ - public void drawString(String s, float x, float y) { - TextBox txt = _group.createTextBox(); - - TextRun rt = txt.getTextParagraphs().get(0).getTextRuns().get(0); - rt.setFontSize((double)_font.getSize()); - rt.setFontFamily(_font.getFamily()); - - if (getColor() != null) rt.setFontColor(DrawPaint.createSolidPaint(getColor())); - if (_font.isBold()) rt.setBold(true); - if (_font.isItalic()) rt.setItalic(true); - - txt.setText(s); - - txt.setInsets(new Insets2D(0,0,0,0)); - txt.setWordWrap(false); - txt.setHorizontalCentered(false); - txt.setVerticalAlignment(VerticalAlignment.MIDDLE); - - - TextLayout layout = new TextLayout(s, _font, getFontRenderContext()); - float ascent = layout.getAscent(); - - float width = (float) Math.floor(layout.getAdvance()); - /** - * Even if top and bottom margins are set to 0 PowerPoint - * always sets extra space between the text and its bounding box. - * - * The approximation height = ascent*2 works good enough in most cases - */ - float height = ascent * 2; - - /* - In powerpoint anchor of a shape is its top left corner. - Java graphics sets string coordinates by the baseline of the first character - so we need to shift up by the height of the textbox - */ - y -= height / 2 + ascent / 2; - - /* - In powerpoint anchor of a shape is its top left corner. - Java graphics sets string coordinates by the baseline of the first character - so we need to shift down by the height of the textbox - */ - txt.setAnchor(new Rectangle((int)x, (int)y, (int)width, (int)height)); - } - - /** - * Fills the interior of a Shape using the settings of the - * Graphics2D context. The rendering attributes applied - * include the Clip, Transform, - * Paint, and Composite. - * @param shape the Shape to be filled - * @see #setPaint - * @see java.awt.Graphics#setColor - * @see #_transform - * @see #setTransform - * @see #setComposite - * @see #clip - * @see #setClip - */ - public void fill(Shape shape){ - Path2D.Double path = new Path2D.Double(_transform.createTransformedShape(shape)); - FreeformShape p = _group.createFreeform(); - p.setPath(path); - applyPaint(p); - p.setStrokeStyle(); //Fills must be "No Line" - } - - /** - * Translates the origin of the graphics context to the point - * (xy) in the current coordinate system. - * Modifies this graphics context so that its new origin corresponds - * to the point (xy) in this graphics context's - * original coordinate system. All coordinates used in subsequent - * rendering operations on this graphics context will be relative - * to this new origin. - * @param x the x coordinate. - * @param y the y coordinate. - */ - public void translate(int x, int y){ - _transform.translate(x, y); - } - - /** - * Intersects the current Clip with the interior of the - * specified Shape and sets the Clip to the - * resulting intersection. The specified Shape is - * transformed with the current Graphics2D - * Transform before being intersected with the current - * Clip. This method is used to make the current - * Clip smaller. - * To make the Clip larger, use setClip. - * The user clip modified by this method is independent of the - * clipping associated with device bounds and visibility. If no clip has - * previously been set, or if the clip has been cleared using - * {@link java.awt.Graphics#setClip(Shape) setClip} with a - * null argument, the specified Shape becomes - * the new user clip. - * @param s the Shape to be intersected with the current - * Clip. If s is null, - * this method clears the current Clip. - */ - @NotImplemented - public void clip(Shape s){ - if (log.check(POILogger.WARN)) { - log.log(POILogger.WARN, "Not implemented"); - } - } - - /** - * Gets the current clipping area. - * This method returns the user clip, which is independent of the - * clipping associated with device bounds and window visibility. - * If no clip has previously been set, or if the clip has been - * cleared using setClip(null), this method returns - * null. - * @return a Shape object representing the - * current clipping area, or null if - * no clip is set. - * @see java.awt.Graphics#getClipBounds() - * @see java.awt.Graphics#clipRect - * @see java.awt.Graphics#setClip(int, int, int, int) - * @see java.awt.Graphics#setClip(Shape) - * @since JDK1.1 - */ - @NotImplemented - public Shape getClip(){ - if (log.check(POILogger.WARN)) { - log.log(POILogger.WARN, "Not implemented"); - } - return null; - } - - /** - * Concatenates the current Graphics2D - * Transform with a scaling transformation - * Subsequent rendering is resized according to the specified scaling - * factors relative to the previous scaling. - * This is equivalent to calling transform(S), where S is an - * AffineTransform represented by the following matrix: - *
    -     *          [   sx   0    0   ]
    -     *          [   0    sy   0   ]
    -     *          [   0    0    1   ]
    -     * 
    - * @param sx the amount by which X coordinates in subsequent - * rendering operations are multiplied relative to previous - * rendering operations. - * @param sy the amount by which Y coordinates in subsequent - * rendering operations are multiplied relative to previous - * rendering operations. - */ - public void scale(double sx, double sy){ - _transform.scale(sx, sy); - } - - /** - * Draws an outlined round-cornered rectangle using this graphics - * context's current color. The left and right edges of the rectangle - * are at x and x + width, - * respectively. The top and bottom edges of the rectangle are at - * y and y + height. - * @param x the x coordinate of the rectangle to be drawn. - * @param y the y coordinate of the rectangle to be drawn. - * @param width the width of the rectangle to be drawn. - * @param height the height of the rectangle to be drawn. - * @param arcWidth the horizontal diameter of the arc - * at the four corners. - * @param arcHeight the vertical diameter of the arc - * at the four corners. - * @see java.awt.Graphics#fillRoundRect - */ - public void drawRoundRect(int x, int y, int width, int height, - int arcWidth, int arcHeight){ - RoundRectangle2D rect = new RoundRectangle2D.Double(x, y, width, height, arcWidth, arcHeight); - draw(rect); - } - - /** - * Draws the text given by the specified string, using this - * graphics context's current font and color. The baseline of the - * first character is at position (xy) in this - * graphics context's coordinate system. - * @param str the string to be drawn. - * @param x the x coordinate. - * @param y the y coordinate. - * @see java.awt.Graphics#drawBytes - * @see java.awt.Graphics#drawChars - */ - public void drawString(String str, int x, int y){ - drawString(str, (float)x, (float)y); - } - - /** - * Fills an oval bounded by the specified rectangle with the - * current color. - * @param x the x coordinate of the upper left corner - * of the oval to be filled. - * @param y the y coordinate of the upper left corner - * of the oval to be filled. - * @param width the width of the oval to be filled. - * @param height the height of the oval to be filled. - * @see java.awt.Graphics#drawOval - */ - public void fillOval(int x, int y, int width, int height){ - Ellipse2D oval = new Ellipse2D.Double(x, y, width, height); - fill(oval); - } - - /** - * Fills the specified rounded corner rectangle with the current color. - * The left and right edges of the rectangle - * are at x and x + width - 1, - * respectively. The top and bottom edges of the rectangle are at - * y and y + height - 1. - * @param x the x coordinate of the rectangle to be filled. - * @param y the y coordinate of the rectangle to be filled. - * @param width the width of the rectangle to be filled. - * @param height the height of the rectangle to be filled. - * @param arcWidth the horizontal diameter - * of the arc at the four corners. - * @param arcHeight the vertical diameter - * of the arc at the four corners. - * @see java.awt.Graphics#drawRoundRect - */ - public void fillRoundRect(int x, int y, int width, int height, - int arcWidth, int arcHeight){ - - RoundRectangle2D rect = new RoundRectangle2D.Double(x, y, width, height, arcWidth, arcHeight); - fill(rect); - } - - /** - * Fills a circular or elliptical arc covering the specified rectangle. - *

    - * The resulting arc begins at startAngle and extends - * for arcAngle degrees. - * Angles are interpreted such that 0 degrees - * is at the 3 o'clock position. - * A positive value indicates a counter-clockwise rotation - * while a negative value indicates a clockwise rotation. - *

    - * The center of the arc is the center of the rectangle whose origin - * is (xy) and whose size is specified by the - * width and height arguments. - *

    - * The resulting arc covers an area - * width + 1 pixels wide - * by height + 1 pixels tall. - *

    - * The angles are specified relative to the non-square extents of - * the bounding rectangle such that 45 degrees always falls on the - * line from the center of the ellipse to the upper right corner of - * the bounding rectangle. As a result, if the bounding rectangle is - * noticeably longer in one axis than the other, the angles to the - * start and end of the arc segment will be skewed farther along the - * longer axis of the bounds. - * @param x the x coordinate of the - * upper-left corner of the arc to be filled. - * @param y the y coordinate of the - * upper-left corner of the arc to be filled. - * @param width the width of the arc to be filled. - * @param height the height of the arc to be filled. - * @param startAngle the beginning angle. - * @param arcAngle the angular extent of the arc, - * relative to the start angle. - * @see java.awt.Graphics#drawArc - */ - public void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle){ - Arc2D arc = new Arc2D.Double(x, y, width, height, startAngle, arcAngle, Arc2D.PIE); - fill(arc); - } - - /** - * Draws the outline of a circular or elliptical arc - * covering the specified rectangle. - *

    - * The resulting arc begins at startAngle and extends - * for arcAngle degrees, using the current color. - * Angles are interpreted such that 0 degrees - * is at the 3 o'clock position. - * A positive value indicates a counter-clockwise rotation - * while a negative value indicates a clockwise rotation. - *

    - * The center of the arc is the center of the rectangle whose origin - * is (xy) and whose size is specified by the - * width and height arguments. - *

    - * The resulting arc covers an area - * width + 1 pixels wide - * by height + 1 pixels tall. - *

    - * The angles are specified relative to the non-square extents of - * the bounding rectangle such that 45 degrees always falls on the - * line from the center of the ellipse to the upper right corner of - * the bounding rectangle. As a result, if the bounding rectangle is - * noticeably longer in one axis than the other, the angles to the - * start and end of the arc segment will be skewed farther along the - * longer axis of the bounds. - * @param x the x coordinate of the - * upper-left corner of the arc to be drawn. - * @param y the y coordinate of the - * upper-left corner of the arc to be drawn. - * @param width the width of the arc to be drawn. - * @param height the height of the arc to be drawn. - * @param startAngle the beginning angle. - * @param arcAngle the angular extent of the arc, - * relative to the start angle. - * @see java.awt.Graphics#fillArc - */ - public void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle) { - Arc2D arc = new Arc2D.Double(x, y, width, height, startAngle, arcAngle, Arc2D.OPEN); - draw(arc); - } - - - /** - * Draws a sequence of connected lines defined by - * arrays of x and y coordinates. - * Each pair of (xy) coordinates defines a point. - * The figure is not closed if the first point - * differs from the last point. - * @param xPoints an array of x points - * @param yPoints an array of y points - * @param nPoints the total number of points - * @see java.awt.Graphics#drawPolygon(int[], int[], int) - * @since JDK1.1 - */ - public void drawPolyline(int[] xPoints, int[] yPoints, - int nPoints){ - if(nPoints > 0){ - GeneralPath path = new GeneralPath(); - path.moveTo(xPoints[0], yPoints[0]); - for(int i=1; ix, y, - * width, and height arguments. - *

    - * The oval covers an area that is - * width + 1 pixels wide - * and height + 1 pixels tall. - * @param x the x coordinate of the upper left - * corner of the oval to be drawn. - * @param y the y coordinate of the upper left - * corner of the oval to be drawn. - * @param width the width of the oval to be drawn. - * @param height the height of the oval to be drawn. - * @see java.awt.Graphics#fillOval - */ - public void drawOval(int x, int y, int width, int height){ - Ellipse2D oval = new Ellipse2D.Double(x, y, width, height); - draw(oval); - } - - /** - * Draws as much of the specified image as is currently available. - * The image is drawn with its top-left corner at - * (xy) in this graphics context's coordinate - * space. Transparent pixels are drawn in the specified - * background color. - *

    - * This operation is equivalent to filling a rectangle of the - * width and height of the specified image with the given color and then - * drawing the image on top of it, but possibly more efficient. - *

    - * This method returns immediately in all cases, even if the - * complete image has not yet been loaded, and it has not been dithered - * and converted for the current output device. - *

    - * If the image has not yet been completely loaded, then - * drawImage returns false. As more of - * the image becomes available, the process that draws the image notifies - * the specified image observer. - * @param img the specified image to be drawn. - * @param x the x coordinate. - * @param y the y coordinate. - * @param bgcolor the background color to paint under the - * non-opaque portions of the image. - * @param observer object to be notified as more of - * the image is converted. - * @see java.awt.Image - * @see java.awt.image.ImageObserver - * @see java.awt.image.ImageObserver#imageUpdate(java.awt.Image, int, int, int, int, int) - */ - @NotImplemented - public boolean drawImage(Image img, int x, int y, - Color bgcolor, - ImageObserver observer){ - if (log.check(POILogger.WARN)) { - log.log(POILogger.WARN, "Not implemented"); - } - - return false; - } - - /** - * Draws as much of the specified image as has already been scaled - * to fit inside the specified rectangle. - *

    - * The image is drawn inside the specified rectangle of this - * graphics context's coordinate space, and is scaled if - * necessary. Transparent pixels are drawn in the specified - * background color. - * This operation is equivalent to filling a rectangle of the - * width and height of the specified image with the given color and then - * drawing the image on top of it, but possibly more efficient. - *

    - * This method returns immediately in all cases, even if the - * entire image has not yet been scaled, dithered, and converted - * for the current output device. - * If the current output representation is not yet complete then - * drawImage returns false. As more of - * the image becomes available, the process that draws the image notifies - * the specified image observer. - *

    - * A scaled version of an image will not necessarily be - * available immediately just because an unscaled version of the - * image has been constructed for this output device. Each size of - * the image may be cached separately and generated from the original - * data in a separate image production sequence. - * @param img the specified image to be drawn. - * @param x the x coordinate. - * @param y the y coordinate. - * @param width the width of the rectangle. - * @param height the height of the rectangle. - * @param bgcolor the background color to paint under the - * non-opaque portions of the image. - * @param observer object to be notified as more of - * the image is converted. - * @see java.awt.Image - * @see java.awt.image.ImageObserver - * @see java.awt.image.ImageObserver#imageUpdate(java.awt.Image, int, int, int, int, int) - */ - @NotImplemented - public boolean drawImage(Image img, int x, int y, - int width, int height, - Color bgcolor, - ImageObserver observer){ - if (log.check(POILogger.WARN)) { - log.log(POILogger.WARN, "Not implemented"); - } - - return false; - } - - - /** - * Draws as much of the specified area of the specified image as is - * currently available, scaling it on the fly to fit inside the - * specified area of the destination drawable surface. Transparent pixels - * do not affect whatever pixels are already there. - *

    - * This method returns immediately in all cases, even if the - * image area to be drawn has not yet been scaled, dithered, and converted - * for the current output device. - * If the current output representation is not yet complete then - * drawImage returns false. As more of - * the image becomes available, the process that draws the image notifies - * the specified image observer. - *

    - * This method always uses the unscaled version of the image - * to render the scaled rectangle and performs the required - * scaling on the fly. It does not use a cached, scaled version - * of the image for this operation. Scaling of the image from source - * to destination is performed such that the first coordinate - * of the source rectangle is mapped to the first coordinate of - * the destination rectangle, and the second source coordinate is - * mapped to the second destination coordinate. The subimage is - * scaled and flipped as needed to preserve those mappings. - * @param img the specified image to be drawn - * @param dx1 the x coordinate of the first corner of the - * destination rectangle. - * @param dy1 the y coordinate of the first corner of the - * destination rectangle. - * @param dx2 the x coordinate of the second corner of the - * destination rectangle. - * @param dy2 the y coordinate of the second corner of the - * destination rectangle. - * @param sx1 the x coordinate of the first corner of the - * source rectangle. - * @param sy1 the y coordinate of the first corner of the - * source rectangle. - * @param sx2 the x coordinate of the second corner of the - * source rectangle. - * @param sy2 the y coordinate of the second corner of the - * source rectangle. - * @param observer object to be notified as more of the image is - * scaled and converted. - * @see java.awt.Image - * @see java.awt.image.ImageObserver - * @see java.awt.image.ImageObserver#imageUpdate(java.awt.Image, int, int, int, int, int) - * @since JDK1.1 - */ - @NotImplemented - public boolean drawImage(Image img, - int dx1, int dy1, int dx2, int dy2, - int sx1, int sy1, int sx2, int sy2, - ImageObserver observer){ - if (log.check(POILogger.WARN)) { - log.log(POILogger.WARN, "Not implemented"); - } - return false; - } - - /** - * Draws as much of the specified area of the specified image as is - * currently available, scaling it on the fly to fit inside the - * specified area of the destination drawable surface. - *

    - * Transparent pixels are drawn in the specified background color. - * This operation is equivalent to filling a rectangle of the - * width and height of the specified image with the given color and then - * drawing the image on top of it, but possibly more efficient. - *

    - * This method returns immediately in all cases, even if the - * image area to be drawn has not yet been scaled, dithered, and converted - * for the current output device. - * If the current output representation is not yet complete then - * drawImage returns false. As more of - * the image becomes available, the process that draws the image notifies - * the specified image observer. - *

    - * This method always uses the unscaled version of the image - * to render the scaled rectangle and performs the required - * scaling on the fly. It does not use a cached, scaled version - * of the image for this operation. Scaling of the image from source - * to destination is performed such that the first coordinate - * of the source rectangle is mapped to the first coordinate of - * the destination rectangle, and the second source coordinate is - * mapped to the second destination coordinate. The subimage is - * scaled and flipped as needed to preserve those mappings. - * @param img the specified image to be drawn - * @param dx1 the x coordinate of the first corner of the - * destination rectangle. - * @param dy1 the y coordinate of the first corner of the - * destination rectangle. - * @param dx2 the x coordinate of the second corner of the - * destination rectangle. - * @param dy2 the y coordinate of the second corner of the - * destination rectangle. - * @param sx1 the x coordinate of the first corner of the - * source rectangle. - * @param sy1 the y coordinate of the first corner of the - * source rectangle. - * @param sx2 the x coordinate of the second corner of the - * source rectangle. - * @param sy2 the y coordinate of the second corner of the - * source rectangle. - * @param bgcolor the background color to paint under the - * non-opaque portions of the image. - * @param observer object to be notified as more of the image is - * scaled and converted. - * @see java.awt.Image - * @see java.awt.image.ImageObserver - * @see java.awt.image.ImageObserver#imageUpdate(java.awt.Image, int, int, int, int, int) - * @since JDK1.1 - */ - @NotImplemented - public boolean drawImage(Image img, - int dx1, int dy1, int dx2, int dy2, - int sx1, int sy1, int sx2, int sy2, - Color bgcolor, - ImageObserver observer){ - if (log.check(POILogger.WARN)) { - log.log(POILogger.WARN, "Not implemented"); - } - return false; - } - - /** - * Draws as much of the specified image as is currently available. - * The image is drawn with its top-left corner at - * (xy) in this graphics context's coordinate - * space. Transparent pixels in the image do not affect whatever - * pixels are already there. - *

    - * This method returns immediately in all cases, even if the - * complete image has not yet been loaded, and it has not been dithered - * and converted for the current output device. - *

    - * If the image has completely loaded and its pixels are - * no longer being changed, then - * drawImage returns true. - * Otherwise, drawImage returns false - * and as more of - * the image becomes available - * or it is time to draw another frame of animation, - * the process that loads the image notifies - * the specified image observer. - * @param img the specified image to be drawn. This method does - * nothing if img is null. - * @param x the x coordinate. - * @param y the y coordinate. - * @param observer object to be notified as more of - * the image is converted. - * @return false if the image pixels are still changing; - * true otherwise. - * @see java.awt.Image - * @see java.awt.image.ImageObserver - * @see java.awt.image.ImageObserver#imageUpdate(java.awt.Image, int, int, int, int, int) - */ - @NotImplemented - public boolean drawImage(Image img, int x, int y, - ImageObserver observer) { - if (log.check(POILogger.WARN)) { - log.log(POILogger.WARN, "Not implemented"); - } - return false; - } - - /** - * Disposes of this graphics context and releases - * any system resources that it is using. - * A Graphics object cannot be used after - * disposehas been called. - *

    - * When a Java program runs, a large number of Graphics - * objects can be created within a short time frame. - * Although the finalization process of the garbage collector - * also disposes of the same system resources, it is preferable - * to manually free the associated resources by calling this - * method rather than to rely on a finalization process which - * may not run to completion for a long period of time. - *

    - * Graphics objects which are provided as arguments to the - * paint and update methods - * of components are automatically released by the system when - * those methods return. For efficiency, programmers should - * call dispose when finished using - * a Graphics object only if it was created - * directly from a component or another Graphics object. - * @see java.awt.Graphics#finalize - * @see java.awt.Component#paint - * @see java.awt.Component#update - * @see java.awt.Component#getGraphics - * @see java.awt.Graphics#create - */ - public void dispose() { - } - - /** - * Draws a line, using the current color, between the points - * (x1, y1) and (x2, y2) - * in this graphics context's coordinate system. - * @param x1 the first point's x coordinate. - * @param y1 the first point's y coordinate. - * @param x2 the second point's x coordinate. - * @param y2 the second point's y coordinate. - */ - public void drawLine(int x1, int y1, int x2, int y2){ - Line2D line = new Line2D.Double(x1, y1, x2, y2); - draw(line); - } - - /** - * Fills a closed polygon defined by - * arrays of x and y coordinates. - *

    - * This method draws the polygon defined by nPoint line - * segments, where the first nPoint - 1 - * line segments are line segments from - * (xPoints[i - 1], yPoints[i - 1]) - * to (xPoints[i], yPoints[i]), for - * 1 ≤ i ≤ nPoints. - * The figure is automatically closed by drawing a line connecting - * the final point to the first point, if those points are different. - *

    - * The area inside the polygon is defined using an - * even-odd fill rule, also known as the alternating rule. - * @param xPoints a an array of x coordinates. - * @param yPoints a an array of y coordinates. - * @param nPoints a the total number of points. - * @see java.awt.Graphics#drawPolygon(int[], int[], int) - */ - public void fillPolygon(int[] xPoints, int[] yPoints, - int nPoints){ - java.awt.Polygon polygon = new java.awt.Polygon(xPoints, yPoints, nPoints); - fill(polygon); - } - - /** - * Fills the specified rectangle. - * The left and right edges of the rectangle are at - * x and x + width - 1. - * The top and bottom edges are at - * y and y + height - 1. - * The resulting rectangle covers an area - * width pixels wide by - * height pixels tall. - * The rectangle is filled using the graphics context's current color. - * @param x the x coordinate - * of the rectangle to be filled. - * @param y the y coordinate - * of the rectangle to be filled. - * @param width the width of the rectangle to be filled. - * @param height the height of the rectangle to be filled. - * @see java.awt.Graphics#clearRect - * @see java.awt.Graphics#drawRect - */ - public void fillRect(int x, int y, int width, int height){ - Rectangle rect = new Rectangle(x, y, width, height); - fill(rect); - } - - /** - * Draws the outline of the specified rectangle. - * The left and right edges of the rectangle are at - * x and x + width. - * The top and bottom edges are at - * y and y + height. - * The rectangle is drawn using the graphics context's current color. - * @param x the x coordinate - * of the rectangle to be drawn. - * @param y the y coordinate - * of the rectangle to be drawn. - * @param width the width of the rectangle to be drawn. - * @param height the height of the rectangle to be drawn. - * @see java.awt.Graphics#fillRect - * @see java.awt.Graphics#clearRect - */ - public void drawRect(int x, int y, int width, int height) { - Rectangle rect = new Rectangle(x, y, width, height); - draw(rect); - } - - /** - * Draws a closed polygon defined by - * arrays of x and y coordinates. - * Each pair of (xy) coordinates defines a point. - *

    - * This method draws the polygon defined by nPoint line - * segments, where the first nPoint - 1 - * line segments are line segments from - * (xPoints[i - 1], yPoints[i - 1]) - * to (xPoints[i], yPoints[i]), for - * 1 ≤ i ≤ nPoints. - * The figure is automatically closed by drawing a line connecting - * the final point to the first point, if those points are different. - * @param xPoints a an array of x coordinates. - * @param yPoints a an array of y coordinates. - * @param nPoints a the total number of points. - * @see java.awt.Graphics#fillPolygon(int[],int[],int) - * @see java.awt.Graphics#drawPolyline - */ - public void drawPolygon(int[] xPoints, int[] yPoints, - int nPoints){ - java.awt.Polygon polygon = new java.awt.Polygon(xPoints, yPoints, nPoints); - draw(polygon); - } - - /** - * Intersects the current clip with the specified rectangle. - * The resulting clipping area is the intersection of the current - * clipping area and the specified rectangle. If there is no - * current clipping area, either because the clip has never been - * set, or the clip has been cleared using setClip(null), - * the specified rectangle becomes the new clip. - * This method sets the user clip, which is independent of the - * clipping associated with device bounds and window visibility. - * This method can only be used to make the current clip smaller. - * To set the current clip larger, use any of the setClip methods. - * Rendering operations have no effect outside of the clipping area. - * @param x the x coordinate of the rectangle to intersect the clip with - * @param y the y coordinate of the rectangle to intersect the clip with - * @param width the width of the rectangle to intersect the clip with - * @param height the height of the rectangle to intersect the clip with - * @see #setClip(int, int, int, int) - * @see #setClip(Shape) - */ - public void clipRect(int x, int y, int width, int height){ - clip(new Rectangle(x, y, width, height)); - } - - /** - * Sets the current clipping area to an arbitrary clip shape. - * Not all objects that implement the Shape - * interface can be used to set the clip. The only - * Shape objects that are guaranteed to be - * supported are Shape objects that are - * obtained via the getClip method and via - * Rectangle objects. This method sets the - * user clip, which is independent of the clipping associated - * with device bounds and window visibility. - * @param clip the Shape to use to set the clip - * @see java.awt.Graphics#getClip() - * @see java.awt.Graphics#clipRect - * @see java.awt.Graphics#setClip(int, int, int, int) - * @since JDK1.1 - */ - @NotImplemented - public void setClip(Shape clip) { - if (log.check(POILogger.WARN)) { - log.log(POILogger.WARN, "Not implemented"); - } - } - - /** - * Returns the bounding rectangle of the current clipping area. - * This method refers to the user clip, which is independent of the - * clipping associated with device bounds and window visibility. - * If no clip has previously been set, or if the clip has been - * cleared using setClip(null), this method returns - * null. - * The coordinates in the rectangle are relative to the coordinate - * system origin of this graphics context. - * @return the bounding rectangle of the current clipping area, - * or null if no clip is set. - * @see java.awt.Graphics#getClip - * @see java.awt.Graphics#clipRect - * @see java.awt.Graphics#setClip(int, int, int, int) - * @see java.awt.Graphics#setClip(Shape) - * @since JDK1.1 - */ - public Rectangle getClipBounds(){ - Shape c = getClip(); - if (c==null) { - return null; - } - return c.getBounds(); - } - - /** - * Draws the text given by the specified iterator, using this - * graphics context's current color. The iterator has to specify a font - * for each character. The baseline of the - * first character is at position (xy) in this - * graphics context's coordinate system. - * @param iterator the iterator whose text is to be drawn - * @param x the x coordinate. - * @param y the y coordinate. - * @see java.awt.Graphics#drawBytes - * @see java.awt.Graphics#drawChars - */ - public void drawString(AttributedCharacterIterator iterator, - int x, int y){ - drawString(iterator, (float)x, (float)y); - } - - /** - * Clears the specified rectangle by filling it with the background - * color of the current drawing surface. This operation does not - * use the current paint mode. - *

    - * Beginning with Java 1.1, the background color - * of offscreen images may be system dependent. Applications should - * use setColor followed by fillRect to - * ensure that an offscreen image is cleared to a specific color. - * @param x the x coordinate of the rectangle to clear. - * @param y the y coordinate of the rectangle to clear. - * @param width the width of the rectangle to clear. - * @param height the height of the rectangle to clear. - * @see java.awt.Graphics#fillRect(int, int, int, int) - * @see java.awt.Graphics#drawRect - * @see java.awt.Graphics#setColor(java.awt.Color) - * @see java.awt.Graphics#setPaintMode - * @see java.awt.Graphics#setXORMode(java.awt.Color) - */ - public void clearRect(int x, int y, int width, int height) { - Paint paint = getPaint(); - setColor(getBackground()); - fillRect(x, y, width, height); - setPaint(paint); - } - - public void copyArea(int x, int y, int width, int height, int dx, int dy) { - } - - /** - * Sets the current clip to the rectangle specified by the given - * coordinates. This method sets the user clip, which is - * independent of the clipping associated with device bounds - * and window visibility. - * Rendering operations have no effect outside of the clipping area. - * @param x the x coordinate of the new clip rectangle. - * @param y the y coordinate of the new clip rectangle. - * @param width the width of the new clip rectangle. - * @param height the height of the new clip rectangle. - * @see java.awt.Graphics#clipRect - * @see java.awt.Graphics#setClip(Shape) - * @since JDK1.1 - */ - public void setClip(int x, int y, int width, int height){ - setClip(new Rectangle(x, y, width, height)); - } - - /** - * Concatenates the current Graphics2D - * Transform with a rotation transform. - * Subsequent rendering is rotated by the specified radians relative - * to the previous origin. - * This is equivalent to calling transform(R), where R is an - * AffineTransform represented by the following matrix: - *

    -     *          [   cos(theta)    -sin(theta)    0   ]
    -     *          [   sin(theta)     cos(theta)    0   ]
    -     *          [       0              0         1   ]
    -     * 
    - * Rotating with a positive angle theta rotates points on the positive - * x axis toward the positive y axis. - * @param theta the angle of rotation in radians - */ - public void rotate(double theta){ - _transform.rotate(theta); - } - - /** - * Concatenates the current Graphics2D - * Transform with a translated rotation - * transform. Subsequent rendering is transformed by a transform - * which is constructed by translating to the specified location, - * rotating by the specified radians, and translating back by the same - * amount as the original translation. This is equivalent to the - * following sequence of calls: - *
    -     *          translate(x, y);
    -     *          rotate(theta);
    -     *          translate(-x, -y);
    -     * 
    - * Rotating with a positive angle theta rotates points on the positive - * x axis toward the positive y axis. - * @param theta the angle of rotation in radians - * @param x x coordinate of the origin of the rotation - * @param y y coordinate of the origin of the rotation - */ - public void rotate(double theta, double x, double y){ - _transform.rotate(theta, x, y); - } - - /** - * Concatenates the current Graphics2D - * Transform with a shearing transform. - * Subsequent renderings are sheared by the specified - * multiplier relative to the previous position. - * This is equivalent to calling transform(SH), where SH - * is an AffineTransform represented by the following - * matrix: - *
    -     *          [   1   shx   0   ]
    -     *          [  shy   1    0   ]
    -     *          [   0    0    1   ]
    -     * 
    - * @param shx the multiplier by which coordinates are shifted in - * the positive X axis direction as a function of their Y coordinate - * @param shy the multiplier by which coordinates are shifted in - * the positive Y axis direction as a function of their X coordinate - */ - public void shear(double shx, double shy){ - _transform.shear(shx, shy); - } - - /** - * Get the rendering context of the Font within this - * Graphics2D context. - * The {@link FontRenderContext} - * encapsulates application hints such as anti-aliasing and - * fractional metrics, as well as target device specific information - * such as dots-per-inch. This information should be provided by the - * application when using objects that perform typographical - * formatting, such as Font and - * TextLayout. This information should also be provided - * by applications that perform their own layout and need accurate - * measurements of various characteristics of glyphs such as advance - * and line height when various rendering hints have been applied to - * the text rendering. - * - * @return a reference to an instance of FontRenderContext. - * @see java.awt.font.FontRenderContext - * @see java.awt.Font#createGlyphVector(FontRenderContext,char[]) - * @see java.awt.font.TextLayout - * @since JDK1.2 - */ - public FontRenderContext getFontRenderContext() { - boolean isAntiAliased = RenderingHints.VALUE_TEXT_ANTIALIAS_ON.equals( - getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING)); - boolean usesFractionalMetrics = RenderingHints.VALUE_FRACTIONALMETRICS_ON.equals( - getRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS)); - - - return new FontRenderContext(new AffineTransform(), isAntiAliased, usesFractionalMetrics); - } - - /** - * Composes an AffineTransform object with the - * Transform in this Graphics2D according - * to the rule last-specified-first-applied. If the current - * Transform is Cx, the result of composition - * with Tx is a new Transform Cx'. Cx' becomes the - * current Transform for this Graphics2D. - * Transforming a point p by the updated Transform Cx' is - * equivalent to first transforming p by Tx and then transforming - * the result by the original Transform Cx. In other - * words, Cx'(p) = Cx(Tx(p)). A copy of the Tx is made, if necessary, - * so further modifications to Tx do not affect rendering. - * @param Tx the AffineTransform object to be composed with - * the current Transform - * @see #setTransform - * @see AffineTransform - */ - public void transform(AffineTransform Tx) { - _transform.concatenate(Tx); - } - - /** - * Renders a BufferedImage that is - * filtered with a - * {@link BufferedImageOp}. - * The rendering attributes applied include the Clip, - * Transform - * and Composite attributes. This is equivalent to: - *
    -     * img1 = op.filter(img, null);
    -     * drawImage(img1, new AffineTransform(1f,0f,0f,1f,x,y), null);
    -     * 
    - * @param img the BufferedImage to be rendered - * @param op the filter to be applied to the image before rendering - * @param x the x coordinate in user space where the image is rendered - * @param y the y coordinate in user space where the image is rendered - * @see #_transform - * @see #setTransform - * @see #setComposite - * @see #clip - * @see #setClip(Shape) - */ - public void drawImage(BufferedImage img, - BufferedImageOp op, - int x, - int y){ - img = op.filter(img, null); - drawImage(img, x, y, null); - } - - /** - * Sets the background color for the Graphics2D context. - * The background color is used for clearing a region. - * When a Graphics2D is constructed for a - * Component, the background color is - * inherited from the Component. Setting the background color - * in the Graphics2D context only affects the subsequent - * clearRect calls and not the background color of the - * Component. To change the background - * of the Component, use appropriate methods of - * the Component. - * @param color the background color that isused in - * subsequent calls to clearRect - * @see #getBackground - * @see java.awt.Graphics#clearRect - */ - public void setBackground(Color color) { - if(color == null) - return; - - _background = color; - } - - /** - * Returns the background color used for clearing a region. - * @return the current Graphics2D Color, - * which defines the background color. - * @see #setBackground - */ - public Color getBackground(){ - return _background; - } - - /** - * Sets the Composite for the Graphics2D context. - * The Composite is used in all drawing methods such as - * drawImage, drawString, draw, - * and fill. It specifies how new pixels are to be combined - * with the existing pixels on the graphics device during the rendering - * process. - *

    If this Graphics2D context is drawing to a - * Component on the display screen and the - * Composite is a custom object rather than an - * instance of the AlphaComposite class, and if - * there is a security manager, its checkPermission - * method is called with an AWTPermission("readDisplayPixels") - * permission. - * - * @param comp the Composite object to be used for rendering - * @throws SecurityException - * if a custom Composite object is being - * used to render to the screen and a security manager - * is set and its checkPermission method - * does not allow the operation. - * @see java.awt.Graphics#setXORMode - * @see java.awt.Graphics#setPaintMode - * @see java.awt.AlphaComposite - */ - @NotImplemented - public void setComposite(Composite comp){ - if (log.check(POILogger.WARN)) { - log.log(POILogger.WARN, "Not implemented"); - } - } - - /** - * Returns the current Composite in the - * Graphics2D context. - * @return the current Graphics2D Composite, - * which defines a compositing style. - * @see #setComposite - */ - @NotImplemented - public Composite getComposite(){ - if (log.check(POILogger.WARN)) { - log.log(POILogger.WARN, "Not implemented"); - } - return null; - } - - /** - * Returns the value of a single preference for the rendering algorithms. - * Hint categories include controls for rendering quality and overall - * time/quality trade-off in the rendering process. Refer to the - * RenderingHints class for definitions of some common - * keys and values. - * @param hintKey the key corresponding to the hint to get. - * @return an object representing the value for the specified hint key. - * Some of the keys and their associated values are defined in the - * RenderingHints class. - * @see RenderingHints - */ - public Object getRenderingHint(RenderingHints.Key hintKey){ - return _hints.get(hintKey); - } - - /** - * Sets the value of a single preference for the rendering algorithms. - * Hint categories include controls for rendering quality and overall - * time/quality trade-off in the rendering process. Refer to the - * RenderingHints class for definitions of some common - * keys and values. - * @param hintKey the key of the hint to be set. - * @param hintValue the value indicating preferences for the specified - * hint category. - * @see RenderingHints - */ - public void setRenderingHint(RenderingHints.Key hintKey, Object hintValue){ - _hints.put(hintKey, hintValue); - } - - - /** - * Renders the text of the specified - * {@link GlyphVector} using - * the Graphics2D context's rendering attributes. - * The rendering attributes applied include the Clip, - * Transform, Paint, and - * Composite attributes. The GlyphVector - * specifies individual glyphs from a {@link Font}. - * The GlyphVector can also contain the glyph positions. - * This is the fastest way to render a set of characters to the - * screen. - * - * @param g the GlyphVector to be rendered - * @param x the x position in user space where the glyphs should be - * rendered - * @param y the y position in user space where the glyphs should be - * rendered - * - * @see java.awt.Font#createGlyphVector(FontRenderContext, char[]) - * @see java.awt.font.GlyphVector - * @see #setPaint - * @see java.awt.Graphics#setColor - * @see #setTransform - * @see #setComposite - * @see #setClip(Shape) - */ - public void drawGlyphVector(GlyphVector g, float x, float y) { - Shape glyphOutline = g.getOutline(x, y); - fill(glyphOutline); - } - - /** - * Returns the device configuration associated with this - * Graphics2D. - * @return the device configuration - */ - public GraphicsConfiguration getDeviceConfiguration() { - return GraphicsEnvironment.getLocalGraphicsEnvironment(). - getDefaultScreenDevice().getDefaultConfiguration(); - } - - /** - * Sets the values of an arbitrary number of preferences for the - * rendering algorithms. - * Only values for the rendering hints that are present in the - * specified Map object are modified. - * All other preferences not present in the specified - * object are left unmodified. - * Hint categories include controls for rendering quality and - * overall time/quality trade-off in the rendering process. - * Refer to the RenderingHints class for definitions of - * some common keys and values. - * @param hints the rendering hints to be set - * @see RenderingHints - */ - public void addRenderingHints(Map hints){ - this._hints.putAll(hints); - } - - /** - * Concatenates the current - * Graphics2D Transform - * with a translation transform. - * Subsequent rendering is translated by the specified - * distance relative to the previous position. - * This is equivalent to calling transform(T), where T is an - * AffineTransform represented by the following matrix: - *

    -     *          [   1    0    tx  ]
    -     *          [   0    1    ty  ]
    -     *          [   0    0    1   ]
    -     * 
    - * @param tx the distance to translate along the x-axis - * @param ty the distance to translate along the y-axis - */ - public void translate(double tx, double ty){ - _transform.translate(tx, ty); - } - - /** - * Renders the text of the specified iterator, using the - * Graphics2D context's current Paint. The - * iterator must specify a font - * for each character. The baseline of the - * first character is at position (xy) in the - * User Space. - * The rendering attributes applied include the Clip, - * Transform, Paint, and - * Composite attributes. - * For characters in script systems such as Hebrew and Arabic, - * the glyphs can be rendered from right to left, in which case the - * coordinate supplied is the location of the leftmost character - * on the baseline. - * @param iterator the iterator whose text is to be rendered - * @param x the x coordinate where the iterator's text is to be - * rendered - * @param y the y coordinate where the iterator's text is to be - * rendered - * @see #setPaint - * @see java.awt.Graphics#setColor - * @see #setTransform - * @see #setComposite - * @see #setClip - */ - @NotImplemented - public void drawString(AttributedCharacterIterator iterator, float x, float y) { - if (log.check(POILogger.WARN)) { - log.log(POILogger.WARN, "Not implemented"); - } - } - - /** - * Checks whether or not the specified Shape intersects - * the specified {@link Rectangle}, which is in device - * space. If onStroke is false, this method checks - * whether or not the interior of the specified Shape - * intersects the specified Rectangle. If - * onStroke is true, this method checks - * whether or not the Stroke of the specified - * Shape outline intersects the specified - * Rectangle. - * The rendering attributes taken into account include the - * Clip, Transform, and Stroke - * attributes. - * @param rect the area in device space to check for a hit - * @param s the Shape to check for a hit - * @param onStroke flag used to choose between testing the - * stroked or the filled shape. If the flag is true, the - * Stroke oultine is tested. If the flag is - * false, the filled Shape is tested. - * @return true if there is a hit; false - * otherwise. - * @see #setStroke - * @see #fill(Shape) - * @see #draw(Shape) - * @see #_transform - * @see #setTransform - * @see #clip - * @see #setClip(Shape) - */ - public boolean hit(Rectangle rect, - Shape s, - boolean onStroke){ - if (onStroke) { - s = getStroke().createStrokedShape(s); - } - - s = getTransform().createTransformedShape(s); - - return s.intersects(rect); - } - - /** - * Gets the preferences for the rendering algorithms. Hint categories - * include controls for rendering quality and overall time/quality - * trade-off in the rendering process. - * Returns all of the hint key/value pairs that were ever specified in - * one operation. Refer to the - * RenderingHints class for definitions of some common - * keys and values. - * @return a reference to an instance of RenderingHints - * that contains the current preferences. - * @see RenderingHints - */ - public RenderingHints getRenderingHints(){ - return _hints; - } - - /** - * Replaces the values of all preferences for the rendering - * algorithms with the specified hints. - * The existing values for all rendering hints are discarded and - * the new set of known hints and values are initialized from the - * specified {@link Map} object. - * Hint categories include controls for rendering quality and - * overall time/quality trade-off in the rendering process. - * Refer to the RenderingHints class for definitions of - * some common keys and values. - * @param hints the rendering hints to be set - * @see RenderingHints - */ - public void setRenderingHints(Map hints){ - this._hints = new RenderingHints(null); - this._hints.putAll(hints); - } - - /** - * Renders an image, applying a transform from image space into user space - * before drawing. - * The transformation from user space into device space is done with - * the current Transform in the Graphics2D. - * The specified transformation is applied to the image before the - * transform attribute in the Graphics2D context is applied. - * The rendering attributes applied include the Clip, - * Transform, and Composite attributes. - * Note that no rendering is done if the specified transform is - * noninvertible. - * @param img the Image to be rendered - * @param xform the transformation from image space into user space - * @param obs the {@link ImageObserver} - * to be notified as more of the Image - * is converted - * @return true if the Image is - * fully loaded and completely rendered; - * false if the Image is still being loaded. - * @see #_transform - * @see #setTransform - * @see #setComposite - * @see #clip - * @see #setClip(Shape) - */ - @NotImplemented - public boolean drawImage(Image img, AffineTransform xform, ImageObserver obs) { - if (log.check(POILogger.WARN)) { - log.log(POILogger.WARN, "Not implemented"); - } - return false; - } - - /** - * Draws as much of the specified image as has already been scaled - * to fit inside the specified rectangle. - *

    - * The image is drawn inside the specified rectangle of this - * graphics context's coordinate space, and is scaled if - * necessary. Transparent pixels do not affect whatever pixels - * are already there. - *

    - * This method returns immediately in all cases, even if the - * entire image has not yet been scaled, dithered, and converted - * for the current output device. - * If the current output representation is not yet complete, then - * drawImage returns false. As more of - * the image becomes available, the process that loads the image notifies - * the image observer by calling its imageUpdate method. - *

    - * A scaled version of an image will not necessarily be - * available immediately just because an unscaled version of the - * image has been constructed for this output device. Each size of - * the image may be cached separately and generated from the original - * data in a separate image production sequence. - * @param img the specified image to be drawn. This method does - * nothing if img is null. - * @param x the x coordinate. - * @param y the y coordinate. - * @param width the width of the rectangle. - * @param height the height of the rectangle. - * @param observer object to be notified as more of - * the image is converted. - * @return false if the image pixels are still changing; - * true otherwise. - * @see java.awt.Image - * @see java.awt.image.ImageObserver - * @see java.awt.image.ImageObserver#imageUpdate(java.awt.Image, int, int, int, int, int) - */ - @NotImplemented - public boolean drawImage(Image img, int x, int y, - int width, int height, - ImageObserver observer) { - if (log.check(POILogger.WARN)) { - log.log(POILogger.WARN, "Not implemented"); - } - return false; - } - - /** - * Creates a new Graphics object that is - * a copy of this Graphics object. - * @return a new graphics context that is a copy of - * this graphics context. - */ - public Graphics create() { - try { - return (Graphics)clone(); - } catch (CloneNotSupportedException e){ - throw new RuntimeException(e); - } - } - - /** - * Gets the font metrics for the specified font. - * @return the font metrics for the specified font. - * @param f the specified font - * @see java.awt.Graphics#getFont - * @see java.awt.FontMetrics - * @see java.awt.Graphics#getFontMetrics() - */ - @SuppressWarnings("deprecation") - @SuppressForbidden - public FontMetrics getFontMetrics(Font f) { - return Toolkit.getDefaultToolkit().getFontMetrics(f); - } - - /** - * Sets the paint mode of this graphics context to alternate between - * this graphics context's current color and the new specified color. - * This specifies that logical pixel operations are performed in the - * XOR mode, which alternates pixels between the current color and - * a specified XOR color. - *

    - * When drawing operations are performed, pixels which are the - * current color are changed to the specified color, and vice versa. - *

    - * Pixels that are of colors other than those two colors are changed - * in an unpredictable but reversible manner; if the same figure is - * drawn twice, then all pixels are restored to their original values. - * @param c1 the XOR alternation color - */ - @NotImplemented - public void setXORMode(Color c1) { - if (log.check(POILogger.WARN)) { - log.log(POILogger.WARN, "Not implemented"); - } - } - - /** - * Sets the paint mode of this graphics context to overwrite the - * destination with this graphics context's current color. - * This sets the logical pixel operation function to the paint or - * overwrite mode. All subsequent rendering operations will - * overwrite the destination with the current color. - */ - @NotImplemented - public void setPaintMode() { - if (log.check(POILogger.WARN)) { - log.log(POILogger.WARN, "Not implemented"); - } - } - - /** - * Renders a - * {@link RenderableImage}, - * applying a transform from image space into user space before drawing. - * The transformation from user space into device space is done with - * the current Transform in the Graphics2D. - * The specified transformation is applied to the image before the - * transform attribute in the Graphics2D context is applied. - * The rendering attributes applied include the Clip, - * Transform, and Composite attributes. Note - * that no rendering is done if the specified transform is - * noninvertible. - *

    - * Rendering hints set on the Graphics2D object might - * be used in rendering the RenderableImage. - * If explicit control is required over specific hints recognized by a - * specific RenderableImage, or if knowledge of which hints - * are used is required, then a RenderedImage should be - * obtained directly from the RenderableImage - * and rendered using - *{@link #drawRenderedImage(RenderedImage, AffineTransform) drawRenderedImage}. - * @param img the image to be rendered. This method does - * nothing if img is null. - * @param xform the transformation from image space into user space - * @see #_transform - * @see #setTransform - * @see #setComposite - * @see #clip - * @see #setClip - * @see #drawRenderedImage - */ - @NotImplemented - public void drawRenderedImage(RenderedImage img, AffineTransform xform) { - if (log.check(POILogger.WARN)) { - log.log(POILogger.WARN, "Not implemented"); - } - } - - /** - * Renders a {@link RenderedImage}, - * applying a transform from image - * space into user space before drawing. - * The transformation from user space into device space is done with - * the current Transform in the Graphics2D. - * The specified transformation is applied to the image before the - * transform attribute in the Graphics2D context is applied. - * The rendering attributes applied include the Clip, - * Transform, and Composite attributes. Note - * that no rendering is done if the specified transform is - * noninvertible. - * @param img the image to be rendered. This method does - * nothing if img is null. - * @param xform the transformation from image space into user space - * @see #_transform - * @see #setTransform - * @see #setComposite - * @see #clip - * @see #setClip - */ - @NotImplemented - public void drawRenderableImage(RenderableImage img, AffineTransform xform) { - if (log.check(POILogger.WARN)) { - log.log(POILogger.WARN, "Not implemented"); - } - } - - protected void applyStroke(SimpleShape shape) { - if (_stroke instanceof BasicStroke){ - BasicStroke bs = (BasicStroke)_stroke; - shape.setStrokeStyle((double)bs.getLineWidth()); - float[] dash = bs.getDashArray(); - if (dash != null) { - //TODO: implement more dashing styles - shape.setStrokeStyle(StrokeStyle.LineDash.DASH); - } - } - } - - protected void applyPaint(SimpleShape shape) { - if (_paint instanceof Color) { - shape.setFillColor((Color)_paint); - } - } -} diff --git a/src/java/org/apache/poi/sl/draw/binding/CTAdjPoint2D.java b/src/java/org/apache/poi/sl/draw/binding/CTAdjPoint2D.java deleted file mode 100644 index 98a9b1822..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/CTAdjPoint2D.java +++ /dev/null @@ -1,109 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for CT_AdjPoint2D complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="CT_AdjPoint2D">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <attribute name="x" use="required" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_AdjCoordinate" />
    - *       <attribute name="y" use="required" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_AdjCoordinate" />
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "CT_AdjPoint2D", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") -public class CTAdjPoint2D { - - @XmlAttribute(required = true) - protected String x; - @XmlAttribute(required = true) - protected String y; - - /** - * Gets the value of the x property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getX() { - return x; - } - - /** - * Sets the value of the x property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setX(String value) { - this.x = value; - } - - public boolean isSetX() { - return (this.x!= null); - } - - /** - * Gets the value of the y property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getY() { - return y; - } - - /** - * Sets the value of the y property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setY(String value) { - this.y = value; - } - - public boolean isSetY() { - return (this.y!= null); - } - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/CTAdjustHandleList.java b/src/java/org/apache/poi/sl/draw/binding/CTAdjustHandleList.java deleted file mode 100644 index 0ca4ce537..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/CTAdjustHandleList.java +++ /dev/null @@ -1,99 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import java.util.ArrayList; -import java.util.List; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlElements; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for CT_AdjustHandleList complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="CT_AdjustHandleList">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <choice maxOccurs="unbounded" minOccurs="0">
    - *         <element name="ahXY" type="{http://schemas.openxmlformats.org/drawingml/2006/main}CT_XYAdjustHandle"/>
    - *         <element name="ahPolar" type="{http://schemas.openxmlformats.org/drawingml/2006/main}CT_PolarAdjustHandle"/>
    - *       </choice>
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "CT_AdjustHandleList", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", propOrder = { - "ahXYOrAhPolar" -}) -public class CTAdjustHandleList { - - @XmlElements({ - @XmlElement(name = "ahXY", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = CTXYAdjustHandle.class), - @XmlElement(name = "ahPolar", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = CTPolarAdjustHandle.class) - }) - protected List ahXYOrAhPolar; - - /** - * Gets the value of the ahXYOrAhPolar property. - * - *

    - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the ahXYOrAhPolar property. - * - *

    - * For example, to add a new item, do as follows: - *

    -     *    getAhXYOrAhPolar().add(newItem);
    -     * 
    - * - * - *

    - * Objects of the following type(s) are allowed in the list - * {@link CTXYAdjustHandle } - * {@link CTPolarAdjustHandle } - * - * - */ - public List getAhXYOrAhPolar() { - if (ahXYOrAhPolar == null) { - ahXYOrAhPolar = new ArrayList(); - } - return this.ahXYOrAhPolar; - } - - public boolean isSetAhXYOrAhPolar() { - return ((this.ahXYOrAhPolar!= null)&&(!this.ahXYOrAhPolar.isEmpty())); - } - - public void unsetAhXYOrAhPolar() { - this.ahXYOrAhPolar = null; - } - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/CTAngle.java b/src/java/org/apache/poi/sl/draw/binding/CTAngle.java deleted file mode 100644 index c1b8fa560..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/CTAngle.java +++ /dev/null @@ -1,70 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for CT_Angle complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="CT_Angle">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <attribute name="val" use="required" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_Angle" />
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "CT_Angle", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") -public class CTAngle { - - @XmlAttribute(required = true) - protected int val; - - /** - * Gets the value of the val property. - * - */ - public int getVal() { - return val; - } - - /** - * Sets the value of the val property. - * - */ - public void setVal(int value) { - this.val = value; - } - - public boolean isSetVal() { - return true; - } - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/CTColor.java b/src/java/org/apache/poi/sl/draw/binding/CTColor.java deleted file mode 100644 index aa92831fe..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/CTColor.java +++ /dev/null @@ -1,237 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for CT_Color complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="CT_Color">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <sequence>
    - *         <group ref="{http://schemas.openxmlformats.org/drawingml/2006/main}EG_ColorChoice"/>
    - *       </sequence>
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "CT_Color", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", propOrder = { - "scrgbClr", - "srgbClr", - "hslClr", - "sysClr", - "schemeClr", - "prstClr" -}) -public class CTColor { - - @XmlElement(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") - protected CTScRgbColor scrgbClr; - @XmlElement(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") - protected CTSRgbColor srgbClr; - @XmlElement(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") - protected CTHslColor hslClr; - @XmlElement(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") - protected CTSystemColor sysClr; - @XmlElement(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") - protected CTSchemeColor schemeClr; - @XmlElement(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") - protected CTPresetColor prstClr; - - /** - * Gets the value of the scrgbClr property. - * - * @return - * possible object is - * {@link CTScRgbColor } - * - */ - public CTScRgbColor getScrgbClr() { - return scrgbClr; - } - - /** - * Sets the value of the scrgbClr property. - * - * @param value - * allowed object is - * {@link CTScRgbColor } - * - */ - public void setScrgbClr(CTScRgbColor value) { - this.scrgbClr = value; - } - - public boolean isSetScrgbClr() { - return (this.scrgbClr!= null); - } - - /** - * Gets the value of the srgbClr property. - * - * @return - * possible object is - * {@link CTSRgbColor } - * - */ - public CTSRgbColor getSrgbClr() { - return srgbClr; - } - - /** - * Sets the value of the srgbClr property. - * - * @param value - * allowed object is - * {@link CTSRgbColor } - * - */ - public void setSrgbClr(CTSRgbColor value) { - this.srgbClr = value; - } - - public boolean isSetSrgbClr() { - return (this.srgbClr!= null); - } - - /** - * Gets the value of the hslClr property. - * - * @return - * possible object is - * {@link CTHslColor } - * - */ - public CTHslColor getHslClr() { - return hslClr; - } - - /** - * Sets the value of the hslClr property. - * - * @param value - * allowed object is - * {@link CTHslColor } - * - */ - public void setHslClr(CTHslColor value) { - this.hslClr = value; - } - - public boolean isSetHslClr() { - return (this.hslClr!= null); - } - - /** - * Gets the value of the sysClr property. - * - * @return - * possible object is - * {@link CTSystemColor } - * - */ - public CTSystemColor getSysClr() { - return sysClr; - } - - /** - * Sets the value of the sysClr property. - * - * @param value - * allowed object is - * {@link CTSystemColor } - * - */ - public void setSysClr(CTSystemColor value) { - this.sysClr = value; - } - - public boolean isSetSysClr() { - return (this.sysClr!= null); - } - - /** - * Gets the value of the schemeClr property. - * - * @return - * possible object is - * {@link CTSchemeColor } - * - */ - public CTSchemeColor getSchemeClr() { - return schemeClr; - } - - /** - * Sets the value of the schemeClr property. - * - * @param value - * allowed object is - * {@link CTSchemeColor } - * - */ - public void setSchemeClr(CTSchemeColor value) { - this.schemeClr = value; - } - - public boolean isSetSchemeClr() { - return (this.schemeClr!= null); - } - - /** - * Gets the value of the prstClr property. - * - * @return - * possible object is - * {@link CTPresetColor } - * - */ - public CTPresetColor getPrstClr() { - return prstClr; - } - - /** - * Sets the value of the prstClr property. - * - * @param value - * allowed object is - * {@link CTPresetColor } - * - */ - public void setPrstClr(CTPresetColor value) { - this.prstClr = value; - } - - public boolean isSetPrstClr() { - return (this.prstClr!= null); - } - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/CTColorMRU.java b/src/java/org/apache/poi/sl/draw/binding/CTColorMRU.java deleted file mode 100644 index e0d281e28..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/CTColorMRU.java +++ /dev/null @@ -1,106 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import java.util.ArrayList; -import java.util.List; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlElements; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for CT_ColorMRU complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="CT_ColorMRU">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <sequence>
    - *         <group ref="{http://schemas.openxmlformats.org/drawingml/2006/main}EG_ColorChoice" maxOccurs="10" minOccurs="0"/>
    - *       </sequence>
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "CT_ColorMRU", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", propOrder = { - "egColorChoice" -}) -public class CTColorMRU { - - @XmlElements({ - @XmlElement(name = "prstClr", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = CTPresetColor.class), - @XmlElement(name = "sysClr", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = CTSystemColor.class), - @XmlElement(name = "hslClr", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = CTHslColor.class), - @XmlElement(name = "srgbClr", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = CTSRgbColor.class), - @XmlElement(name = "scrgbClr", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = CTScRgbColor.class), - @XmlElement(name = "schemeClr", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = CTSchemeColor.class) - }) - protected List egColorChoice; - - /** - * Gets the value of the egColorChoice property. - * - *

    - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the egColorChoice property. - * - *

    - * For example, to add a new item, do as follows: - *

    -     *    getEGColorChoice().add(newItem);
    -     * 
    - * - * - *

    - * Objects of the following type(s) are allowed in the list - * {@link CTPresetColor } - * {@link CTSystemColor } - * {@link CTHslColor } - * {@link CTSRgbColor } - * {@link CTScRgbColor } - * {@link CTSchemeColor } - * - * - */ - public List getEGColorChoice() { - if (egColorChoice == null) { - egColorChoice = new ArrayList(); - } - return this.egColorChoice; - } - - public boolean isSetEGColorChoice() { - return ((this.egColorChoice!= null)&&(!this.egColorChoice.isEmpty())); - } - - public void unsetEGColorChoice() { - this.egColorChoice = null; - } - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/CTComplementTransform.java b/src/java/org/apache/poi/sl/draw/binding/CTComplementTransform.java deleted file mode 100644 index b020a55bd..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/CTComplementTransform.java +++ /dev/null @@ -1,46 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for CT_ComplementTransform complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="CT_ComplementTransform">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "CT_ComplementTransform", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") -public class CTComplementTransform { - - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/CTConnection.java b/src/java/org/apache/poi/sl/draw/binding/CTConnection.java deleted file mode 100644 index 79b924fb4..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/CTConnection.java +++ /dev/null @@ -1,95 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlSchemaType; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for CT_Connection complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="CT_Connection">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <attribute name="id" use="required" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_DrawingElementId" />
    - *       <attribute name="idx" use="required" type="{http://www.w3.org/2001/XMLSchema}unsignedInt" />
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "CT_Connection", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") -public class CTConnection { - - @XmlAttribute(required = true) - protected long id; - @XmlAttribute(required = true) - @XmlSchemaType(name = "unsignedInt") - protected long idx; - - /** - * Gets the value of the id property. - * - */ - public long getId() { - return id; - } - - /** - * Sets the value of the id property. - * - */ - public void setId(long value) { - this.id = value; - } - - public boolean isSetId() { - return true; - } - - /** - * Gets the value of the idx property. - * - */ - public long getIdx() { - return idx; - } - - /** - * Sets the value of the idx property. - * - */ - public void setIdx(long value) { - this.idx = value; - } - - public boolean isSetIdx() { - return true; - } - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/CTConnectionSite.java b/src/java/org/apache/poi/sl/draw/binding/CTConnectionSite.java deleted file mode 100644 index 061d2a1bf..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/CTConnectionSite.java +++ /dev/null @@ -1,114 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for CT_ConnectionSite complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="CT_ConnectionSite">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <sequence>
    - *         <element name="pos" type="{http://schemas.openxmlformats.org/drawingml/2006/main}CT_AdjPoint2D"/>
    - *       </sequence>
    - *       <attribute name="ang" use="required" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_AdjAngle" />
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "CT_ConnectionSite", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", propOrder = { - "pos" -}) -public class CTConnectionSite { - - @XmlElement(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", required = true) - protected CTAdjPoint2D pos; - @XmlAttribute(required = true) - protected String ang; - - /** - * Gets the value of the pos property. - * - * @return - * possible object is - * {@link CTAdjPoint2D } - * - */ - public CTAdjPoint2D getPos() { - return pos; - } - - /** - * Sets the value of the pos property. - * - * @param value - * allowed object is - * {@link CTAdjPoint2D } - * - */ - public void setPos(CTAdjPoint2D value) { - this.pos = value; - } - - public boolean isSetPos() { - return (this.pos!= null); - } - - /** - * Gets the value of the ang property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getAng() { - return ang; - } - - /** - * Sets the value of the ang property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setAng(String value) { - this.ang = value; - } - - public boolean isSetAng() { - return (this.ang!= null); - } - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/CTConnectionSiteList.java b/src/java/org/apache/poi/sl/draw/binding/CTConnectionSiteList.java deleted file mode 100644 index 0ae1ee14e..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/CTConnectionSiteList.java +++ /dev/null @@ -1,93 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import java.util.ArrayList; -import java.util.List; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for CT_ConnectionSiteList complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="CT_ConnectionSiteList">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <sequence>
    - *         <element name="cxn" type="{http://schemas.openxmlformats.org/drawingml/2006/main}CT_ConnectionSite" maxOccurs="unbounded" minOccurs="0"/>
    - *       </sequence>
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "CT_ConnectionSiteList", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", propOrder = { - "cxn" -}) -public class CTConnectionSiteList { - - @XmlElement(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") - protected List cxn; - - /** - * Gets the value of the cxn property. - * - *

    - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the cxn property. - * - *

    - * For example, to add a new item, do as follows: - *

    -     *    getCxn().add(newItem);
    -     * 
    - * - * - *

    - * Objects of the following type(s) are allowed in the list - * {@link CTConnectionSite } - * - * - */ - public List getCxn() { - if (cxn == null) { - cxn = new ArrayList(); - } - return this.cxn; - } - - public boolean isSetCxn() { - return ((this.cxn!= null)&&(!this.cxn.isEmpty())); - } - - public void unsetCxn() { - this.cxn = null; - } - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/CTCustomGeometry2D.java b/src/java/org/apache/poi/sl/draw/binding/CTCustomGeometry2D.java deleted file mode 100644 index 3a8f744fc..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/CTCustomGeometry2D.java +++ /dev/null @@ -1,242 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for CT_CustomGeometry2D complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="CT_CustomGeometry2D">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <sequence>
    - *         <element name="avLst" type="{http://schemas.openxmlformats.org/drawingml/2006/main}CT_GeomGuideList" minOccurs="0"/>
    - *         <element name="gdLst" type="{http://schemas.openxmlformats.org/drawingml/2006/main}CT_GeomGuideList" minOccurs="0"/>
    - *         <element name="ahLst" type="{http://schemas.openxmlformats.org/drawingml/2006/main}CT_AdjustHandleList" minOccurs="0"/>
    - *         <element name="cxnLst" type="{http://schemas.openxmlformats.org/drawingml/2006/main}CT_ConnectionSiteList" minOccurs="0"/>
    - *         <element name="rect" type="{http://schemas.openxmlformats.org/drawingml/2006/main}CT_GeomRect" minOccurs="0"/>
    - *         <element name="pathLst" type="{http://schemas.openxmlformats.org/drawingml/2006/main}CT_Path2DList"/>
    - *       </sequence>
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "CT_CustomGeometry2D", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", propOrder = { - "avLst", - "gdLst", - "ahLst", - "cxnLst", - "rect", - "pathLst" -}) -public class CTCustomGeometry2D { - - @XmlElement(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") - protected CTGeomGuideList avLst; - @XmlElement(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") - protected CTGeomGuideList gdLst; - @XmlElement(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") - protected CTAdjustHandleList ahLst; - @XmlElement(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") - protected CTConnectionSiteList cxnLst; - @XmlElement(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") - protected CTGeomRect rect; - @XmlElement(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", required = true) - protected CTPath2DList pathLst; - - /** - * Gets the value of the avLst property. - * - * @return - * possible object is - * {@link CTGeomGuideList } - * - */ - public CTGeomGuideList getAvLst() { - return avLst; - } - - /** - * Sets the value of the avLst property. - * - * @param value - * allowed object is - * {@link CTGeomGuideList } - * - */ - public void setAvLst(CTGeomGuideList value) { - this.avLst = value; - } - - public boolean isSetAvLst() { - return (this.avLst!= null); - } - - /** - * Gets the value of the gdLst property. - * - * @return - * possible object is - * {@link CTGeomGuideList } - * - */ - public CTGeomGuideList getGdLst() { - return gdLst; - } - - /** - * Sets the value of the gdLst property. - * - * @param value - * allowed object is - * {@link CTGeomGuideList } - * - */ - public void setGdLst(CTGeomGuideList value) { - this.gdLst = value; - } - - public boolean isSetGdLst() { - return (this.gdLst!= null); - } - - /** - * Gets the value of the ahLst property. - * - * @return - * possible object is - * {@link CTAdjustHandleList } - * - */ - public CTAdjustHandleList getAhLst() { - return ahLst; - } - - /** - * Sets the value of the ahLst property. - * - * @param value - * allowed object is - * {@link CTAdjustHandleList } - * - */ - public void setAhLst(CTAdjustHandleList value) { - this.ahLst = value; - } - - public boolean isSetAhLst() { - return (this.ahLst!= null); - } - - /** - * Gets the value of the cxnLst property. - * - * @return - * possible object is - * {@link CTConnectionSiteList } - * - */ - public CTConnectionSiteList getCxnLst() { - return cxnLst; - } - - /** - * Sets the value of the cxnLst property. - * - * @param value - * allowed object is - * {@link CTConnectionSiteList } - * - */ - public void setCxnLst(CTConnectionSiteList value) { - this.cxnLst = value; - } - - public boolean isSetCxnLst() { - return (this.cxnLst!= null); - } - - /** - * Gets the value of the rect property. - * - * @return - * possible object is - * {@link CTGeomRect } - * - */ - public CTGeomRect getRect() { - return rect; - } - - /** - * Sets the value of the rect property. - * - * @param value - * allowed object is - * {@link CTGeomRect } - * - */ - public void setRect(CTGeomRect value) { - this.rect = value; - } - - public boolean isSetRect() { - return (this.rect!= null); - } - - /** - * Gets the value of the pathLst property. - * - * @return - * possible object is - * {@link CTPath2DList } - * - */ - public CTPath2DList getPathLst() { - return pathLst; - } - - /** - * Sets the value of the pathLst property. - * - * @param value - * allowed object is - * {@link CTPath2DList } - * - */ - public void setPathLst(CTPath2DList value) { - this.pathLst = value; - } - - public boolean isSetPathLst() { - return (this.pathLst!= null); - } - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/CTEmbeddedWAVAudioFile.java b/src/java/org/apache/poi/sl/draw/binding/CTEmbeddedWAVAudioFile.java deleted file mode 100644 index 84a4f70ec..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/CTEmbeddedWAVAudioFile.java +++ /dev/null @@ -1,152 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for CT_EmbeddedWAVAudioFile complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="CT_EmbeddedWAVAudioFile">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <attribute ref="{http://schemas.openxmlformats.org/officeDocument/2006/relationships}embed use="required""/>
    - *       <attribute name="name" type="{http://www.w3.org/2001/XMLSchema}string" default="" />
    - *       <attribute name="builtIn" type="{http://www.w3.org/2001/XMLSchema}boolean" default="false" />
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "CT_EmbeddedWAVAudioFile", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") -public class CTEmbeddedWAVAudioFile { - - @XmlAttribute(namespace = "http://schemas.openxmlformats.org/officeDocument/2006/relationships", required = true) - protected String embed; - @XmlAttribute - protected String name; - @XmlAttribute - protected Boolean builtIn; - - /** - * Embedded Audio File Relationship ID - * - * @return - * possible object is - * {@link String } - * - */ - public String getEmbed() { - return embed; - } - - /** - * Sets the value of the embed property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setEmbed(String value) { - this.embed = value; - } - - public boolean isSetEmbed() { - return (this.embed!= null); - } - - /** - * Gets the value of the name property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getName() { - if (name == null) { - return ""; - } else { - return name; - } - } - - /** - * Sets the value of the name property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setName(String value) { - this.name = value; - } - - public boolean isSetName() { - return (this.name!= null); - } - - /** - * Gets the value of the builtIn property. - * - * @return - * possible object is - * {@link Boolean } - * - */ - public boolean isBuiltIn() { - if (builtIn == null) { - return false; - } else { - return builtIn; - } - } - - /** - * Sets the value of the builtIn property. - * - * @param value - * allowed object is - * {@link Boolean } - * - */ - public void setBuiltIn(boolean value) { - this.builtIn = value; - } - - public boolean isSetBuiltIn() { - return (this.builtIn!= null); - } - - public void unsetBuiltIn() { - this.builtIn = null; - } - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/CTFixedPercentage.java b/src/java/org/apache/poi/sl/draw/binding/CTFixedPercentage.java deleted file mode 100644 index 676c7a876..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/CTFixedPercentage.java +++ /dev/null @@ -1,70 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for CT_FixedPercentage complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="CT_FixedPercentage">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <attribute name="val" use="required" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_FixedPercentage" />
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "CT_FixedPercentage", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") -public class CTFixedPercentage { - - @XmlAttribute(required = true) - protected int val; - - /** - * Gets the value of the val property. - * - */ - public int getVal() { - return val; - } - - /** - * Sets the value of the val property. - * - */ - public void setVal(int value) { - this.val = value; - } - - public boolean isSetVal() { - return true; - } - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/CTGammaTransform.java b/src/java/org/apache/poi/sl/draw/binding/CTGammaTransform.java deleted file mode 100644 index d397b1d5d..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/CTGammaTransform.java +++ /dev/null @@ -1,46 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for CT_GammaTransform complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="CT_GammaTransform">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "CT_GammaTransform", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") -public class CTGammaTransform { - - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/CTGeomGuide.java b/src/java/org/apache/poi/sl/draw/binding/CTGeomGuide.java deleted file mode 100644 index c24935600..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/CTGeomGuide.java +++ /dev/null @@ -1,112 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlType; -import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; -import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; - - -/** - *

    Java class for CT_GeomGuide complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="CT_GeomGuide">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <attribute name="name" use="required" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_GeomGuideName" />
    - *       <attribute name="fmla" use="required" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_GeomGuideFormula" />
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "CT_GeomGuide", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") -public class CTGeomGuide { - - @XmlAttribute(required = true) - @XmlJavaTypeAdapter(CollapsedStringAdapter.class) - protected String name; - @XmlAttribute(required = true) - protected String fmla; - - /** - * Gets the value of the name property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getName() { - return name; - } - - /** - * Sets the value of the name property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setName(String value) { - this.name = value; - } - - public boolean isSetName() { - return (this.name!= null); - } - - /** - * Gets the value of the fmla property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getFmla() { - return fmla; - } - - /** - * Sets the value of the fmla property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setFmla(String value) { - this.fmla = value; - } - - public boolean isSetFmla() { - return (this.fmla!= null); - } - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/CTGeomGuideList.java b/src/java/org/apache/poi/sl/draw/binding/CTGeomGuideList.java deleted file mode 100644 index 96886d49b..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/CTGeomGuideList.java +++ /dev/null @@ -1,93 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import java.util.ArrayList; -import java.util.List; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for CT_GeomGuideList complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="CT_GeomGuideList">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <sequence>
    - *         <element name="gd" type="{http://schemas.openxmlformats.org/drawingml/2006/main}CT_GeomGuide" maxOccurs="unbounded" minOccurs="0"/>
    - *       </sequence>
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "CT_GeomGuideList", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", propOrder = { - "gd" -}) -public class CTGeomGuideList { - - @XmlElement(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") - protected List gd; - - /** - * Gets the value of the gd property. - * - *

    - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the gd property. - * - *

    - * For example, to add a new item, do as follows: - *

    -     *    getGd().add(newItem);
    -     * 
    - * - * - *

    - * Objects of the following type(s) are allowed in the list - * {@link CTGeomGuide } - * - * - */ - public List getGd() { - if (gd == null) { - gd = new ArrayList(); - } - return this.gd; - } - - public boolean isSetGd() { - return ((this.gd!= null)&&(!this.gd.isEmpty())); - } - - public void unsetGd() { - this.gd = null; - } - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/CTGeomRect.java b/src/java/org/apache/poi/sl/draw/binding/CTGeomRect.java deleted file mode 100644 index d8b9df8de..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/CTGeomRect.java +++ /dev/null @@ -1,171 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for CT_GeomRect complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="CT_GeomRect">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <attribute name="l" use="required" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_AdjCoordinate" />
    - *       <attribute name="t" use="required" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_AdjCoordinate" />
    - *       <attribute name="r" use="required" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_AdjCoordinate" />
    - *       <attribute name="b" use="required" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_AdjCoordinate" />
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "CT_GeomRect", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") -public class CTGeomRect { - - @XmlAttribute(required = true) - protected String l; - @XmlAttribute(required = true) - protected String t; - @XmlAttribute(required = true) - protected String r; - @XmlAttribute(required = true) - protected String b; - - /** - * Gets the value of the l property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getL() { - return l; - } - - /** - * Sets the value of the l property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setL(String value) { - this.l = value; - } - - public boolean isSetL() { - return (this.l!= null); - } - - /** - * Gets the value of the t property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getT() { - return t; - } - - /** - * Sets the value of the t property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setT(String value) { - this.t = value; - } - - public boolean isSetT() { - return (this.t!= null); - } - - /** - * Gets the value of the r property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getR() { - return r; - } - - /** - * Sets the value of the r property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setR(String value) { - this.r = value; - } - - public boolean isSetR() { - return (this.r!= null); - } - - /** - * Gets the value of the b property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getB() { - return b; - } - - /** - * Sets the value of the b property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setB(String value) { - this.b = value; - } - - public boolean isSetB() { - return (this.b!= null); - } - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/CTGrayscaleTransform.java b/src/java/org/apache/poi/sl/draw/binding/CTGrayscaleTransform.java deleted file mode 100644 index a1359273e..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/CTGrayscaleTransform.java +++ /dev/null @@ -1,46 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for CT_GrayscaleTransform complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="CT_GrayscaleTransform">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "CT_GrayscaleTransform", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") -public class CTGrayscaleTransform { - - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/CTGroupTransform2D.java b/src/java/org/apache/poi/sl/draw/binding/CTGroupTransform2D.java deleted file mode 100644 index 2dafafc88..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/CTGroupTransform2D.java +++ /dev/null @@ -1,296 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for CT_GroupTransform2D complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="CT_GroupTransform2D">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <sequence>
    - *         <element name="off" type="{http://schemas.openxmlformats.org/drawingml/2006/main}CT_Point2D" minOccurs="0"/>
    - *         <element name="ext" type="{http://schemas.openxmlformats.org/drawingml/2006/main}CT_PositiveSize2D" minOccurs="0"/>
    - *         <element name="chOff" type="{http://schemas.openxmlformats.org/drawingml/2006/main}CT_Point2D" minOccurs="0"/>
    - *         <element name="chExt" type="{http://schemas.openxmlformats.org/drawingml/2006/main}CT_PositiveSize2D" minOccurs="0"/>
    - *       </sequence>
    - *       <attribute name="rot" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_Angle" default="0" />
    - *       <attribute name="flipH" type="{http://www.w3.org/2001/XMLSchema}boolean" default="false" />
    - *       <attribute name="flipV" type="{http://www.w3.org/2001/XMLSchema}boolean" default="false" />
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "CT_GroupTransform2D", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", propOrder = { - "off", - "ext", - "chOff", - "chExt" -}) -public class CTGroupTransform2D { - - @XmlElement(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") - protected CTPoint2D off; - @XmlElement(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") - protected CTPositiveSize2D ext; - @XmlElement(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") - protected CTPoint2D chOff; - @XmlElement(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") - protected CTPositiveSize2D chExt; - @XmlAttribute - protected Integer rot; - @XmlAttribute - protected Boolean flipH; - @XmlAttribute - protected Boolean flipV; - - /** - * Gets the value of the off property. - * - * @return - * possible object is - * {@link CTPoint2D } - * - */ - public CTPoint2D getOff() { - return off; - } - - /** - * Sets the value of the off property. - * - * @param value - * allowed object is - * {@link CTPoint2D } - * - */ - public void setOff(CTPoint2D value) { - this.off = value; - } - - public boolean isSetOff() { - return (this.off!= null); - } - - /** - * Gets the value of the ext property. - * - * @return - * possible object is - * {@link CTPositiveSize2D } - * - */ - public CTPositiveSize2D getExt() { - return ext; - } - - /** - * Sets the value of the ext property. - * - * @param value - * allowed object is - * {@link CTPositiveSize2D } - * - */ - public void setExt(CTPositiveSize2D value) { - this.ext = value; - } - - public boolean isSetExt() { - return (this.ext!= null); - } - - /** - * Gets the value of the chOff property. - * - * @return - * possible object is - * {@link CTPoint2D } - * - */ - public CTPoint2D getChOff() { - return chOff; - } - - /** - * Sets the value of the chOff property. - * - * @param value - * allowed object is - * {@link CTPoint2D } - * - */ - public void setChOff(CTPoint2D value) { - this.chOff = value; - } - - public boolean isSetChOff() { - return (this.chOff!= null); - } - - /** - * Gets the value of the chExt property. - * - * @return - * possible object is - * {@link CTPositiveSize2D } - * - */ - public CTPositiveSize2D getChExt() { - return chExt; - } - - /** - * Sets the value of the chExt property. - * - * @param value - * allowed object is - * {@link CTPositiveSize2D } - * - */ - public void setChExt(CTPositiveSize2D value) { - this.chExt = value; - } - - public boolean isSetChExt() { - return (this.chExt!= null); - } - - /** - * Gets the value of the rot property. - * - * @return - * possible object is - * {@link Integer } - * - */ - public int getRot() { - if (rot == null) { - return 0; - } else { - return rot; - } - } - - /** - * Sets the value of the rot property. - * - * @param value - * allowed object is - * {@link Integer } - * - */ - public void setRot(int value) { - this.rot = value; - } - - public boolean isSetRot() { - return (this.rot!= null); - } - - public void unsetRot() { - this.rot = null; - } - - /** - * Gets the value of the flipH property. - * - * @return - * possible object is - * {@link Boolean } - * - */ - public boolean isFlipH() { - if (flipH == null) { - return false; - } else { - return flipH; - } - } - - /** - * Sets the value of the flipH property. - * - * @param value - * allowed object is - * {@link Boolean } - * - */ - public void setFlipH(boolean value) { - this.flipH = value; - } - - public boolean isSetFlipH() { - return (this.flipH!= null); - } - - public void unsetFlipH() { - this.flipH = null; - } - - /** - * Gets the value of the flipV property. - * - * @return - * possible object is - * {@link Boolean } - * - */ - public boolean isFlipV() { - if (flipV == null) { - return false; - } else { - return flipV; - } - } - - /** - * Sets the value of the flipV property. - * - * @param value - * allowed object is - * {@link Boolean } - * - */ - public void setFlipV(boolean value) { - this.flipV = value; - } - - public boolean isSetFlipV() { - return (this.flipV!= null); - } - - public void unsetFlipV() { - this.flipV = null; - } - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/CTHslColor.java b/src/java/org/apache/poi/sl/draw/binding/CTHslColor.java deleted file mode 100644 index 3d9f37607..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/CTHslColor.java +++ /dev/null @@ -1,221 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import java.util.ArrayList; -import java.util.List; -import javax.xml.bind.JAXBElement; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlElementRef; -import javax.xml.bind.annotation.XmlElementRefs; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for CT_HslColor complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="CT_HslColor">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <sequence>
    - *         <group ref="{http://schemas.openxmlformats.org/drawingml/2006/main}EG_ColorTransform" maxOccurs="unbounded" minOccurs="0"/>
    - *       </sequence>
    - *       <attribute name="hue" use="required" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_PositiveFixedAngle" />
    - *       <attribute name="sat" use="required" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_Percentage" />
    - *       <attribute name="lum" use="required" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_Percentage" />
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "CT_HslColor", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", propOrder = { - "egColorTransform" -}) -public class CTHslColor { - - @XmlElementRefs({ - @XmlElementRef(name = "comp", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "satMod", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "tint", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "satOff", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "lum", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "gray", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "gamma", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "inv", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "red", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "alpha", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "greenOff", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "green", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "greenMod", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "blueOff", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "lumMod", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "redOff", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "hueOff", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "invGamma", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "alphaOff", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "hue", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "redMod", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "alphaMod", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "lumOff", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "blue", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "hueMod", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "blueMod", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "sat", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "shade", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class) - }) - protected List> egColorTransform; - @XmlAttribute(required = true) - protected int hue; - @XmlAttribute(required = true) - protected int sat; - @XmlAttribute(required = true) - protected int lum; - - /** - * Gets the value of the egColorTransform property. - * - *

    - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the egColorTransform property. - * - *

    - * For example, to add a new item, do as follows: - *

    -     *    getEGColorTransform().add(newItem);
    -     * 
    - * - * - *

    - * Objects of the following type(s) are allowed in the list - * {@link JAXBElement }{@code <}{@link CTComplementTransform }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPositiveFixedPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTGrayscaleTransform }{@code >} - * {@link JAXBElement }{@code <}{@link CTGammaTransform }{@code >} - * {@link JAXBElement }{@code <}{@link CTInverseTransform }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPositiveFixedPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTAngle }{@code >} - * {@link JAXBElement }{@code <}{@link CTInverseGammaTransform }{@code >} - * {@link JAXBElement }{@code <}{@link CTFixedPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPositiveFixedAngle }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPositivePercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPositivePercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPositiveFixedPercentage }{@code >} - * - * - */ - public List> getEGColorTransform() { - if (egColorTransform == null) { - egColorTransform = new ArrayList>(); - } - return this.egColorTransform; - } - - public boolean isSetEGColorTransform() { - return ((this.egColorTransform!= null)&&(!this.egColorTransform.isEmpty())); - } - - public void unsetEGColorTransform() { - this.egColorTransform = null; - } - - /** - * Gets the value of the hue property. - * - */ - public int getHue() { - return hue; - } - - /** - * Sets the value of the hue property. - * - */ - public void setHue(int value) { - this.hue = value; - } - - public boolean isSetHue() { - return true; - } - - /** - * Gets the value of the sat property. - * - */ - public int getSat() { - return sat; - } - - /** - * Sets the value of the sat property. - * - */ - public void setSat(int value) { - this.sat = value; - } - - public boolean isSetSat() { - return true; - } - - /** - * Gets the value of the lum property. - * - */ - public int getLum() { - return lum; - } - - /** - * Sets the value of the lum property. - * - */ - public void setLum(int value) { - this.lum = value; - } - - public boolean isSetLum() { - return true; - } - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/CTHyperlink.java b/src/java/org/apache/poi/sl/draw/binding/CTHyperlink.java deleted file mode 100644 index 26450ba04..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/CTHyperlink.java +++ /dev/null @@ -1,403 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for CT_Hyperlink complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="CT_Hyperlink">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <sequence>
    - *         <element name="snd" type="{http://schemas.openxmlformats.org/drawingml/2006/main}CT_EmbeddedWAVAudioFile" minOccurs="0"/>
    - *         <element name="extLst" type="{http://schemas.openxmlformats.org/drawingml/2006/main}CT_OfficeArtExtensionList" minOccurs="0"/>
    - *       </sequence>
    - *       <attribute ref="{http://schemas.openxmlformats.org/officeDocument/2006/relationships}id"/>
    - *       <attribute name="invalidUrl" type="{http://www.w3.org/2001/XMLSchema}string" default="" />
    - *       <attribute name="action" type="{http://www.w3.org/2001/XMLSchema}string" default="" />
    - *       <attribute name="tgtFrame" type="{http://www.w3.org/2001/XMLSchema}string" default="" />
    - *       <attribute name="tooltip" type="{http://www.w3.org/2001/XMLSchema}string" default="" />
    - *       <attribute name="history" type="{http://www.w3.org/2001/XMLSchema}boolean" default="true" />
    - *       <attribute name="highlightClick" type="{http://www.w3.org/2001/XMLSchema}boolean" default="false" />
    - *       <attribute name="endSnd" type="{http://www.w3.org/2001/XMLSchema}boolean" default="false" />
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "CT_Hyperlink", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", propOrder = { - "snd", - "extLst" -}) -public class CTHyperlink { - - @XmlElement(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") - protected CTEmbeddedWAVAudioFile snd; - @XmlElement(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") - protected CTOfficeArtExtensionList extLst; - @XmlAttribute(namespace = "http://schemas.openxmlformats.org/officeDocument/2006/relationships") - protected String id; - @XmlAttribute - protected String invalidUrl; - @XmlAttribute - protected String action; - @XmlAttribute - protected String tgtFrame; - @XmlAttribute - protected String tooltip; - @XmlAttribute - protected Boolean history; - @XmlAttribute - protected Boolean highlightClick; - @XmlAttribute - protected Boolean endSnd; - - /** - * Gets the value of the snd property. - * - * @return - * possible object is - * {@link CTEmbeddedWAVAudioFile } - * - */ - public CTEmbeddedWAVAudioFile getSnd() { - return snd; - } - - /** - * Sets the value of the snd property. - * - * @param value - * allowed object is - * {@link CTEmbeddedWAVAudioFile } - * - */ - public void setSnd(CTEmbeddedWAVAudioFile value) { - this.snd = value; - } - - public boolean isSetSnd() { - return (this.snd!= null); - } - - /** - * Gets the value of the extLst property. - * - * @return - * possible object is - * {@link CTOfficeArtExtensionList } - * - */ - public CTOfficeArtExtensionList getExtLst() { - return extLst; - } - - /** - * Sets the value of the extLst property. - * - * @param value - * allowed object is - * {@link CTOfficeArtExtensionList } - * - */ - public void setExtLst(CTOfficeArtExtensionList value) { - this.extLst = value; - } - - public boolean isSetExtLst() { - return (this.extLst!= null); - } - - /** - * Drawing Object Hyperlink Target - * - * @return - * possible object is - * {@link String } - * - */ - public String getId() { - return id; - } - - /** - * Sets the value of the id property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setId(String value) { - this.id = value; - } - - public boolean isSetId() { - return (this.id!= null); - } - - /** - * Gets the value of the invalidUrl property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getInvalidUrl() { - if (invalidUrl == null) { - return ""; - } else { - return invalidUrl; - } - } - - /** - * Sets the value of the invalidUrl property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setInvalidUrl(String value) { - this.invalidUrl = value; - } - - public boolean isSetInvalidUrl() { - return (this.invalidUrl!= null); - } - - /** - * Gets the value of the action property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getAction() { - if (action == null) { - return ""; - } else { - return action; - } - } - - /** - * Sets the value of the action property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setAction(String value) { - this.action = value; - } - - public boolean isSetAction() { - return (this.action!= null); - } - - /** - * Gets the value of the tgtFrame property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getTgtFrame() { - if (tgtFrame == null) { - return ""; - } else { - return tgtFrame; - } - } - - /** - * Sets the value of the tgtFrame property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setTgtFrame(String value) { - this.tgtFrame = value; - } - - public boolean isSetTgtFrame() { - return (this.tgtFrame!= null); - } - - /** - * Gets the value of the tooltip property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getTooltip() { - if (tooltip == null) { - return ""; - } else { - return tooltip; - } - } - - /** - * Sets the value of the tooltip property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setTooltip(String value) { - this.tooltip = value; - } - - public boolean isSetTooltip() { - return (this.tooltip!= null); - } - - /** - * Gets the value of the history property. - * - * @return - * possible object is - * {@link Boolean } - * - */ - public boolean isHistory() { - if (history == null) { - return true; - } else { - return history; - } - } - - /** - * Sets the value of the history property. - * - * @param value - * allowed object is - * {@link Boolean } - * - */ - public void setHistory(boolean value) { - this.history = value; - } - - public boolean isSetHistory() { - return (this.history!= null); - } - - public void unsetHistory() { - this.history = null; - } - - /** - * Gets the value of the highlightClick property. - * - * @return - * possible object is - * {@link Boolean } - * - */ - public boolean isHighlightClick() { - if (highlightClick == null) { - return false; - } else { - return highlightClick; - } - } - - /** - * Sets the value of the highlightClick property. - * - * @param value - * allowed object is - * {@link Boolean } - * - */ - public void setHighlightClick(boolean value) { - this.highlightClick = value; - } - - public boolean isSetHighlightClick() { - return (this.highlightClick!= null); - } - - public void unsetHighlightClick() { - this.highlightClick = null; - } - - /** - * Gets the value of the endSnd property. - * - * @return - * possible object is - * {@link Boolean } - * - */ - public boolean isEndSnd() { - if (endSnd == null) { - return false; - } else { - return endSnd; - } - } - - /** - * Sets the value of the endSnd property. - * - * @param value - * allowed object is - * {@link Boolean } - * - */ - public void setEndSnd(boolean value) { - this.endSnd = value; - } - - public boolean isSetEndSnd() { - return (this.endSnd!= null); - } - - public void unsetEndSnd() { - this.endSnd = null; - } - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/CTInverseGammaTransform.java b/src/java/org/apache/poi/sl/draw/binding/CTInverseGammaTransform.java deleted file mode 100644 index 32c9c7a6d..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/CTInverseGammaTransform.java +++ /dev/null @@ -1,46 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for CT_InverseGammaTransform complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="CT_InverseGammaTransform">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "CT_InverseGammaTransform", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") -public class CTInverseGammaTransform { - - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/CTInverseTransform.java b/src/java/org/apache/poi/sl/draw/binding/CTInverseTransform.java deleted file mode 100644 index a4bbc8f88..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/CTInverseTransform.java +++ /dev/null @@ -1,46 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for CT_InverseTransform complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="CT_InverseTransform">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "CT_InverseTransform", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") -public class CTInverseTransform { - - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/CTOfficeArtExtension.java b/src/java/org/apache/poi/sl/draw/binding/CTOfficeArtExtension.java deleted file mode 100644 index 6b65ddd6c..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/CTOfficeArtExtension.java +++ /dev/null @@ -1,122 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAnyElement; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlSchemaType; -import javax.xml.bind.annotation.XmlType; -import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; -import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; -import org.w3c.dom.Element; - - -/** - *

    Java class for CT_OfficeArtExtension complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="CT_OfficeArtExtension">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <sequence>
    - *         <any processContents='lax'/>
    - *       </sequence>
    - *       <attribute name="uri" type="{http://www.w3.org/2001/XMLSchema}token" />
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "CT_OfficeArtExtension", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", propOrder = { - "any" -}) -public class CTOfficeArtExtension { - - @XmlAnyElement(lax = true) - protected Object any; - @XmlAttribute - @XmlJavaTypeAdapter(CollapsedStringAdapter.class) - @XmlSchemaType(name = "token") - protected String uri; - - /** - * Gets the value of the any property. - * - * @return - * possible object is - * {@link Object } - * {@link Element } - * - */ - public Object getAny() { - return any; - } - - /** - * Sets the value of the any property. - * - * @param value - * allowed object is - * {@link Object } - * {@link Element } - * - */ - public void setAny(Object value) { - this.any = value; - } - - public boolean isSetAny() { - return (this.any!= null); - } - - /** - * Gets the value of the uri property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getUri() { - return uri; - } - - /** - * Sets the value of the uri property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setUri(String value) { - this.uri = value; - } - - public boolean isSetUri() { - return (this.uri!= null); - } - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/CTOfficeArtExtensionList.java b/src/java/org/apache/poi/sl/draw/binding/CTOfficeArtExtensionList.java deleted file mode 100644 index 4dd5021ad..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/CTOfficeArtExtensionList.java +++ /dev/null @@ -1,93 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import java.util.ArrayList; -import java.util.List; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for CT_OfficeArtExtensionList complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="CT_OfficeArtExtensionList">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <sequence>
    - *         <group ref="{http://schemas.openxmlformats.org/drawingml/2006/main}EG_OfficeArtExtensionList"/>
    - *       </sequence>
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "CT_OfficeArtExtensionList", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", propOrder = { - "ext" -}) -public class CTOfficeArtExtensionList { - - @XmlElement(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") - protected List ext; - - /** - * Gets the value of the ext property. - * - *

    - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the ext property. - * - *

    - * For example, to add a new item, do as follows: - *

    -     *    getExt().add(newItem);
    -     * 
    - * - * - *

    - * Objects of the following type(s) are allowed in the list - * {@link CTOfficeArtExtension } - * - * - */ - public List getExt() { - if (ext == null) { - ext = new ArrayList(); - } - return this.ext; - } - - public boolean isSetExt() { - return ((this.ext!= null)&&(!this.ext.isEmpty())); - } - - public void unsetExt() { - this.ext = null; - } - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/CTPath2D.java b/src/java/org/apache/poi/sl/draw/binding/CTPath2D.java deleted file mode 100644 index 6b1ba0272..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/CTPath2D.java +++ /dev/null @@ -1,303 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import java.util.ArrayList; -import java.util.List; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlElements; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for CT_Path2D complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="CT_Path2D">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <choice maxOccurs="unbounded" minOccurs="0">
    - *         <element name="close" type="{http://schemas.openxmlformats.org/drawingml/2006/main}CT_Path2DClose"/>
    - *         <element name="moveTo" type="{http://schemas.openxmlformats.org/drawingml/2006/main}CT_Path2DMoveTo"/>
    - *         <element name="lnTo" type="{http://schemas.openxmlformats.org/drawingml/2006/main}CT_Path2DLineTo"/>
    - *         <element name="arcTo" type="{http://schemas.openxmlformats.org/drawingml/2006/main}CT_Path2DArcTo"/>
    - *         <element name="quadBezTo" type="{http://schemas.openxmlformats.org/drawingml/2006/main}CT_Path2DQuadBezierTo"/>
    - *         <element name="cubicBezTo" type="{http://schemas.openxmlformats.org/drawingml/2006/main}CT_Path2DCubicBezierTo"/>
    - *       </choice>
    - *       <attribute name="w" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_PositiveCoordinate" default="0" />
    - *       <attribute name="h" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_PositiveCoordinate" default="0" />
    - *       <attribute name="fill" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_PathFillMode" default="norm" />
    - *       <attribute name="stroke" type="{http://www.w3.org/2001/XMLSchema}boolean" default="true" />
    - *       <attribute name="extrusionOk" type="{http://www.w3.org/2001/XMLSchema}boolean" default="true" />
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "CT_Path2D", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", propOrder = { - "closeOrMoveToOrLnTo" -}) -public class CTPath2D { - - @XmlElements({ - @XmlElement(name = "lnTo", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = CTPath2DLineTo.class), - @XmlElement(name = "close", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = CTPath2DClose.class), - @XmlElement(name = "cubicBezTo", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = CTPath2DCubicBezierTo.class), - @XmlElement(name = "quadBezTo", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = CTPath2DQuadBezierTo.class), - @XmlElement(name = "arcTo", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = CTPath2DArcTo.class), - @XmlElement(name = "moveTo", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = CTPath2DMoveTo.class) - }) - protected List closeOrMoveToOrLnTo; - @XmlAttribute - protected Long w; - @XmlAttribute - protected Long h; - @XmlAttribute - protected STPathFillMode fill; - @XmlAttribute - protected Boolean stroke; - @XmlAttribute - protected Boolean extrusionOk; - - /** - * Gets the value of the closeOrMoveToOrLnTo property. - * - *

    - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the closeOrMoveToOrLnTo property. - * - *

    - * For example, to add a new item, do as follows: - *

    -     *    getCloseOrMoveToOrLnTo().add(newItem);
    -     * 
    - * - * - *

    - * Objects of the following type(s) are allowed in the list - * {@link CTPath2DLineTo } - * {@link CTPath2DClose } - * {@link CTPath2DCubicBezierTo } - * {@link CTPath2DQuadBezierTo } - * {@link CTPath2DArcTo } - * {@link CTPath2DMoveTo } - * - * - */ - public List getCloseOrMoveToOrLnTo() { - if (closeOrMoveToOrLnTo == null) { - closeOrMoveToOrLnTo = new ArrayList(); - } - return this.closeOrMoveToOrLnTo; - } - - public boolean isSetCloseOrMoveToOrLnTo() { - return ((this.closeOrMoveToOrLnTo!= null)&&(!this.closeOrMoveToOrLnTo.isEmpty())); - } - - public void unsetCloseOrMoveToOrLnTo() { - this.closeOrMoveToOrLnTo = null; - } - - /** - * Gets the value of the w property. - * - * @return - * possible object is - * {@link Long } - * - */ - public long getW() { - if (w == null) { - return 0L; - } else { - return w; - } - } - - /** - * Sets the value of the w property. - * - * @param value - * allowed object is - * {@link Long } - * - */ - public void setW(long value) { - this.w = value; - } - - public boolean isSetW() { - return (this.w!= null); - } - - public void unsetW() { - this.w = null; - } - - /** - * Gets the value of the h property. - * - * @return - * possible object is - * {@link Long } - * - */ - public long getH() { - if (h == null) { - return 0L; - } else { - return h; - } - } - - /** - * Sets the value of the h property. - * - * @param value - * allowed object is - * {@link Long } - * - */ - public void setH(long value) { - this.h = value; - } - - public boolean isSetH() { - return (this.h!= null); - } - - public void unsetH() { - this.h = null; - } - - /** - * Gets the value of the fill property. - * - * @return - * possible object is - * {@link STPathFillMode } - * - */ - public STPathFillMode getFill() { - if (fill == null) { - return STPathFillMode.NORM; - } else { - return fill; - } - } - - /** - * Sets the value of the fill property. - * - * @param value - * allowed object is - * {@link STPathFillMode } - * - */ - public void setFill(STPathFillMode value) { - this.fill = value; - } - - public boolean isSetFill() { - return (this.fill!= null); - } - - /** - * Gets the value of the stroke property. - * - * @return - * possible object is - * {@link Boolean } - * - */ - public boolean isStroke() { - if (stroke == null) { - return true; - } else { - return stroke; - } - } - - /** - * Sets the value of the stroke property. - * - * @param value - * allowed object is - * {@link Boolean } - * - */ - public void setStroke(boolean value) { - this.stroke = value; - } - - public boolean isSetStroke() { - return (this.stroke!= null); - } - - public void unsetStroke() { - this.stroke = null; - } - - /** - * Gets the value of the extrusionOk property. - * - * @return - * possible object is - * {@link Boolean } - * - */ - public boolean isExtrusionOk() { - if (extrusionOk == null) { - return true; - } else { - return extrusionOk; - } - } - - /** - * Sets the value of the extrusionOk property. - * - * @param value - * allowed object is - * {@link Boolean } - * - */ - public void setExtrusionOk(boolean value) { - this.extrusionOk = value; - } - - public boolean isSetExtrusionOk() { - return (this.extrusionOk!= null); - } - - public void unsetExtrusionOk() { - this.extrusionOk = null; - } - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/CTPath2DArcTo.java b/src/java/org/apache/poi/sl/draw/binding/CTPath2DArcTo.java deleted file mode 100644 index 1b12259df..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/CTPath2DArcTo.java +++ /dev/null @@ -1,171 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for CT_Path2DArcTo complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="CT_Path2DArcTo">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <attribute name="wR" use="required" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_AdjCoordinate" />
    - *       <attribute name="hR" use="required" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_AdjCoordinate" />
    - *       <attribute name="stAng" use="required" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_AdjAngle" />
    - *       <attribute name="swAng" use="required" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_AdjAngle" />
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "CT_Path2DArcTo", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") -public class CTPath2DArcTo { - - @XmlAttribute(name = "wR", required = true) - protected String wr; - @XmlAttribute(name = "hR", required = true) - protected String hr; - @XmlAttribute(required = true) - protected String stAng; - @XmlAttribute(required = true) - protected String swAng; - - /** - * Gets the value of the wr property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getWR() { - return wr; - } - - /** - * Sets the value of the wr property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setWR(String value) { - this.wr = value; - } - - public boolean isSetWR() { - return (this.wr!= null); - } - - /** - * Gets the value of the hr property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getHR() { - return hr; - } - - /** - * Sets the value of the hr property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setHR(String value) { - this.hr = value; - } - - public boolean isSetHR() { - return (this.hr!= null); - } - - /** - * Gets the value of the stAng property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getStAng() { - return stAng; - } - - /** - * Sets the value of the stAng property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setStAng(String value) { - this.stAng = value; - } - - public boolean isSetStAng() { - return (this.stAng!= null); - } - - /** - * Gets the value of the swAng property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getSwAng() { - return swAng; - } - - /** - * Sets the value of the swAng property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setSwAng(String value) { - this.swAng = value; - } - - public boolean isSetSwAng() { - return (this.swAng!= null); - } - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/CTPath2DClose.java b/src/java/org/apache/poi/sl/draw/binding/CTPath2DClose.java deleted file mode 100644 index ca9dfebdf..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/CTPath2DClose.java +++ /dev/null @@ -1,46 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for CT_Path2DClose complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="CT_Path2DClose">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "CT_Path2DClose", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") -public class CTPath2DClose { - - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/CTPath2DCubicBezierTo.java b/src/java/org/apache/poi/sl/draw/binding/CTPath2DCubicBezierTo.java deleted file mode 100644 index b6042366f..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/CTPath2DCubicBezierTo.java +++ /dev/null @@ -1,93 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import java.util.ArrayList; -import java.util.List; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for CT_Path2DCubicBezierTo complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="CT_Path2DCubicBezierTo">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <sequence>
    - *         <element name="pt" type="{http://schemas.openxmlformats.org/drawingml/2006/main}CT_AdjPoint2D" maxOccurs="3" minOccurs="3"/>
    - *       </sequence>
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "CT_Path2DCubicBezierTo", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", propOrder = { - "pt" -}) -public class CTPath2DCubicBezierTo { - - @XmlElement(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", required = true) - protected List pt; - - /** - * Gets the value of the pt property. - * - *

    - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the pt property. - * - *

    - * For example, to add a new item, do as follows: - *

    -     *    getPt().add(newItem);
    -     * 
    - * - * - *

    - * Objects of the following type(s) are allowed in the list - * {@link CTAdjPoint2D } - * - * - */ - public List getPt() { - if (pt == null) { - pt = new ArrayList(); - } - return this.pt; - } - - public boolean isSetPt() { - return ((this.pt!= null)&&(!this.pt.isEmpty())); - } - - public void unsetPt() { - this.pt = null; - } - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/CTPath2DLineTo.java b/src/java/org/apache/poi/sl/draw/binding/CTPath2DLineTo.java deleted file mode 100644 index 3512cef7c..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/CTPath2DLineTo.java +++ /dev/null @@ -1,82 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for CT_Path2DLineTo complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="CT_Path2DLineTo">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <sequence>
    - *         <element name="pt" type="{http://schemas.openxmlformats.org/drawingml/2006/main}CT_AdjPoint2D"/>
    - *       </sequence>
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "CT_Path2DLineTo", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", propOrder = { - "pt" -}) -public class CTPath2DLineTo { - - @XmlElement(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", required = true) - protected CTAdjPoint2D pt; - - /** - * Gets the value of the pt property. - * - * @return - * possible object is - * {@link CTAdjPoint2D } - * - */ - public CTAdjPoint2D getPt() { - return pt; - } - - /** - * Sets the value of the pt property. - * - * @param value - * allowed object is - * {@link CTAdjPoint2D } - * - */ - public void setPt(CTAdjPoint2D value) { - this.pt = value; - } - - public boolean isSetPt() { - return (this.pt!= null); - } - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/CTPath2DList.java b/src/java/org/apache/poi/sl/draw/binding/CTPath2DList.java deleted file mode 100644 index 4abc906eb..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/CTPath2DList.java +++ /dev/null @@ -1,93 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import java.util.ArrayList; -import java.util.List; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for CT_Path2DList complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="CT_Path2DList">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <sequence>
    - *         <element name="path" type="{http://schemas.openxmlformats.org/drawingml/2006/main}CT_Path2D" maxOccurs="unbounded" minOccurs="0"/>
    - *       </sequence>
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "CT_Path2DList", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", propOrder = { - "path" -}) -public class CTPath2DList { - - @XmlElement(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") - protected List path; - - /** - * Gets the value of the path property. - * - *

    - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the path property. - * - *

    - * For example, to add a new item, do as follows: - *

    -     *    getPath().add(newItem);
    -     * 
    - * - * - *

    - * Objects of the following type(s) are allowed in the list - * {@link CTPath2D } - * - * - */ - public List getPath() { - if (path == null) { - path = new ArrayList(); - } - return this.path; - } - - public boolean isSetPath() { - return ((this.path!= null)&&(!this.path.isEmpty())); - } - - public void unsetPath() { - this.path = null; - } - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/CTPath2DMoveTo.java b/src/java/org/apache/poi/sl/draw/binding/CTPath2DMoveTo.java deleted file mode 100644 index 25685e710..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/CTPath2DMoveTo.java +++ /dev/null @@ -1,82 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for CT_Path2DMoveTo complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="CT_Path2DMoveTo">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <sequence>
    - *         <element name="pt" type="{http://schemas.openxmlformats.org/drawingml/2006/main}CT_AdjPoint2D"/>
    - *       </sequence>
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "CT_Path2DMoveTo", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", propOrder = { - "pt" -}) -public class CTPath2DMoveTo { - - @XmlElement(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", required = true) - protected CTAdjPoint2D pt; - - /** - * Gets the value of the pt property. - * - * @return - * possible object is - * {@link CTAdjPoint2D } - * - */ - public CTAdjPoint2D getPt() { - return pt; - } - - /** - * Sets the value of the pt property. - * - * @param value - * allowed object is - * {@link CTAdjPoint2D } - * - */ - public void setPt(CTAdjPoint2D value) { - this.pt = value; - } - - public boolean isSetPt() { - return (this.pt!= null); - } - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/CTPath2DQuadBezierTo.java b/src/java/org/apache/poi/sl/draw/binding/CTPath2DQuadBezierTo.java deleted file mode 100644 index 06f308204..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/CTPath2DQuadBezierTo.java +++ /dev/null @@ -1,93 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import java.util.ArrayList; -import java.util.List; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for CT_Path2DQuadBezierTo complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="CT_Path2DQuadBezierTo">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <sequence>
    - *         <element name="pt" type="{http://schemas.openxmlformats.org/drawingml/2006/main}CT_AdjPoint2D" maxOccurs="2" minOccurs="2"/>
    - *       </sequence>
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "CT_Path2DQuadBezierTo", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", propOrder = { - "pt" -}) -public class CTPath2DQuadBezierTo { - - @XmlElement(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", required = true) - protected List pt; - - /** - * Gets the value of the pt property. - * - *

    - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the pt property. - * - *

    - * For example, to add a new item, do as follows: - *

    -     *    getPt().add(newItem);
    -     * 
    - * - * - *

    - * Objects of the following type(s) are allowed in the list - * {@link CTAdjPoint2D } - * - * - */ - public List getPt() { - if (pt == null) { - pt = new ArrayList(); - } - return this.pt; - } - - public boolean isSetPt() { - return ((this.pt!= null)&&(!this.pt.isEmpty())); - } - - public void unsetPt() { - this.pt = null; - } - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/CTPercentage.java b/src/java/org/apache/poi/sl/draw/binding/CTPercentage.java deleted file mode 100644 index b343f3096..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/CTPercentage.java +++ /dev/null @@ -1,70 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for CT_Percentage complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="CT_Percentage">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <attribute name="val" use="required" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_Percentage" />
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "CT_Percentage", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") -public class CTPercentage { - - @XmlAttribute(required = true) - protected int val; - - /** - * Gets the value of the val property. - * - */ - public int getVal() { - return val; - } - - /** - * Sets the value of the val property. - * - */ - public void setVal(int value) { - this.val = value; - } - - public boolean isSetVal() { - return true; - } - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/CTPoint2D.java b/src/java/org/apache/poi/sl/draw/binding/CTPoint2D.java deleted file mode 100644 index 947685ea4..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/CTPoint2D.java +++ /dev/null @@ -1,93 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for CT_Point2D complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="CT_Point2D">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <attribute name="x" use="required" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_Coordinate" />
    - *       <attribute name="y" use="required" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_Coordinate" />
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "CT_Point2D", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") -public class CTPoint2D { - - @XmlAttribute(required = true) - protected long x; - @XmlAttribute(required = true) - protected long y; - - /** - * Gets the value of the x property. - * - */ - public long getX() { - return x; - } - - /** - * Sets the value of the x property. - * - */ - public void setX(long value) { - this.x = value; - } - - public boolean isSetX() { - return true; - } - - /** - * Gets the value of the y property. - * - */ - public long getY() { - return y; - } - - /** - * Sets the value of the y property. - * - */ - public void setY(long value) { - this.y = value; - } - - public boolean isSetY() { - return true; - } - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/CTPoint3D.java b/src/java/org/apache/poi/sl/draw/binding/CTPoint3D.java deleted file mode 100644 index 853bcd375..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/CTPoint3D.java +++ /dev/null @@ -1,116 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for CT_Point3D complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="CT_Point3D">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <attribute name="x" use="required" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_Coordinate" />
    - *       <attribute name="y" use="required" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_Coordinate" />
    - *       <attribute name="z" use="required" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_Coordinate" />
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "CT_Point3D", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") -public class CTPoint3D { - - @XmlAttribute(required = true) - protected long x; - @XmlAttribute(required = true) - protected long y; - @XmlAttribute(required = true) - protected long z; - - /** - * Gets the value of the x property. - * - */ - public long getX() { - return x; - } - - /** - * Sets the value of the x property. - * - */ - public void setX(long value) { - this.x = value; - } - - public boolean isSetX() { - return true; - } - - /** - * Gets the value of the y property. - * - */ - public long getY() { - return y; - } - - /** - * Sets the value of the y property. - * - */ - public void setY(long value) { - this.y = value; - } - - public boolean isSetY() { - return true; - } - - /** - * Gets the value of the z property. - * - */ - public long getZ() { - return z; - } - - /** - * Sets the value of the z property. - * - */ - public void setZ(long value) { - this.z = value; - } - - public boolean isSetZ() { - return true; - } - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/CTPolarAdjustHandle.java b/src/java/org/apache/poi/sl/draw/binding/CTPolarAdjustHandle.java deleted file mode 100644 index 661fe4874..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/CTPolarAdjustHandle.java +++ /dev/null @@ -1,273 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlType; -import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; -import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; - - -/** - *

    Java class for CT_PolarAdjustHandle complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="CT_PolarAdjustHandle">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <sequence>
    - *         <element name="pos" type="{http://schemas.openxmlformats.org/drawingml/2006/main}CT_AdjPoint2D"/>
    - *       </sequence>
    - *       <attribute name="gdRefR" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_GeomGuideName" />
    - *       <attribute name="minR" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_AdjCoordinate" />
    - *       <attribute name="maxR" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_AdjCoordinate" />
    - *       <attribute name="gdRefAng" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_GeomGuideName" />
    - *       <attribute name="minAng" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_AdjAngle" />
    - *       <attribute name="maxAng" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_AdjAngle" />
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "CT_PolarAdjustHandle", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", propOrder = { - "pos" -}) -public class CTPolarAdjustHandle { - - @XmlElement(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", required = true) - protected CTAdjPoint2D pos; - @XmlAttribute - @XmlJavaTypeAdapter(CollapsedStringAdapter.class) - protected String gdRefR; - @XmlAttribute - protected String minR; - @XmlAttribute - protected String maxR; - @XmlAttribute - @XmlJavaTypeAdapter(CollapsedStringAdapter.class) - protected String gdRefAng; - @XmlAttribute - protected String minAng; - @XmlAttribute - protected String maxAng; - - /** - * Gets the value of the pos property. - * - * @return - * possible object is - * {@link CTAdjPoint2D } - * - */ - public CTAdjPoint2D getPos() { - return pos; - } - - /** - * Sets the value of the pos property. - * - * @param value - * allowed object is - * {@link CTAdjPoint2D } - * - */ - public void setPos(CTAdjPoint2D value) { - this.pos = value; - } - - public boolean isSetPos() { - return (this.pos!= null); - } - - /** - * Gets the value of the gdRefR property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getGdRefR() { - return gdRefR; - } - - /** - * Sets the value of the gdRefR property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setGdRefR(String value) { - this.gdRefR = value; - } - - public boolean isSetGdRefR() { - return (this.gdRefR!= null); - } - - /** - * Gets the value of the minR property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getMinR() { - return minR; - } - - /** - * Sets the value of the minR property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setMinR(String value) { - this.minR = value; - } - - public boolean isSetMinR() { - return (this.minR!= null); - } - - /** - * Gets the value of the maxR property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getMaxR() { - return maxR; - } - - /** - * Sets the value of the maxR property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setMaxR(String value) { - this.maxR = value; - } - - public boolean isSetMaxR() { - return (this.maxR!= null); - } - - /** - * Gets the value of the gdRefAng property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getGdRefAng() { - return gdRefAng; - } - - /** - * Sets the value of the gdRefAng property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setGdRefAng(String value) { - this.gdRefAng = value; - } - - public boolean isSetGdRefAng() { - return (this.gdRefAng!= null); - } - - /** - * Gets the value of the minAng property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getMinAng() { - return minAng; - } - - /** - * Sets the value of the minAng property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setMinAng(String value) { - this.minAng = value; - } - - public boolean isSetMinAng() { - return (this.minAng!= null); - } - - /** - * Gets the value of the maxAng property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getMaxAng() { - return maxAng; - } - - /** - * Sets the value of the maxAng property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setMaxAng(String value) { - this.maxAng = value; - } - - public boolean isSetMaxAng() { - return (this.maxAng!= null); - } - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/CTPositiveFixedAngle.java b/src/java/org/apache/poi/sl/draw/binding/CTPositiveFixedAngle.java deleted file mode 100644 index 5c181ced0..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/CTPositiveFixedAngle.java +++ /dev/null @@ -1,70 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for CT_PositiveFixedAngle complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="CT_PositiveFixedAngle">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <attribute name="val" use="required" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_PositiveFixedAngle" />
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "CT_PositiveFixedAngle", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") -public class CTPositiveFixedAngle { - - @XmlAttribute(required = true) - protected int val; - - /** - * Gets the value of the val property. - * - */ - public int getVal() { - return val; - } - - /** - * Sets the value of the val property. - * - */ - public void setVal(int value) { - this.val = value; - } - - public boolean isSetVal() { - return true; - } - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/CTPositiveFixedPercentage.java b/src/java/org/apache/poi/sl/draw/binding/CTPositiveFixedPercentage.java deleted file mode 100644 index 3c60d7f1d..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/CTPositiveFixedPercentage.java +++ /dev/null @@ -1,70 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for CT_PositiveFixedPercentage complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="CT_PositiveFixedPercentage">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <attribute name="val" use="required" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_PositiveFixedPercentage" />
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "CT_PositiveFixedPercentage", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") -public class CTPositiveFixedPercentage { - - @XmlAttribute(required = true) - protected int val; - - /** - * Gets the value of the val property. - * - */ - public int getVal() { - return val; - } - - /** - * Sets the value of the val property. - * - */ - public void setVal(int value) { - this.val = value; - } - - public boolean isSetVal() { - return true; - } - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/CTPositivePercentage.java b/src/java/org/apache/poi/sl/draw/binding/CTPositivePercentage.java deleted file mode 100644 index 60961f6ac..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/CTPositivePercentage.java +++ /dev/null @@ -1,70 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for CT_PositivePercentage complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="CT_PositivePercentage">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <attribute name="val" use="required" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_PositivePercentage" />
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "CT_PositivePercentage", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") -public class CTPositivePercentage { - - @XmlAttribute(required = true) - protected int val; - - /** - * Gets the value of the val property. - * - */ - public int getVal() { - return val; - } - - /** - * Sets the value of the val property. - * - */ - public void setVal(int value) { - this.val = value; - } - - public boolean isSetVal() { - return true; - } - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/CTPositiveSize2D.java b/src/java/org/apache/poi/sl/draw/binding/CTPositiveSize2D.java deleted file mode 100644 index 7ee53eb30..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/CTPositiveSize2D.java +++ /dev/null @@ -1,93 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for CT_PositiveSize2D complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="CT_PositiveSize2D">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <attribute name="cx" use="required" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_PositiveCoordinate" />
    - *       <attribute name="cy" use="required" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_PositiveCoordinate" />
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "CT_PositiveSize2D", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") -public class CTPositiveSize2D { - - @XmlAttribute(required = true) - protected long cx; - @XmlAttribute(required = true) - protected long cy; - - /** - * Gets the value of the cx property. - * - */ - public long getCx() { - return cx; - } - - /** - * Sets the value of the cx property. - * - */ - public void setCx(long value) { - this.cx = value; - } - - public boolean isSetCx() { - return true; - } - - /** - * Gets the value of the cy property. - * - */ - public long getCy() { - return cy; - } - - /** - * Sets the value of the cy property. - * - */ - public void setCy(long value) { - this.cy = value; - } - - public boolean isSetCy() { - return true; - } - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/CTPresetColor.java b/src/java/org/apache/poi/sl/draw/binding/CTPresetColor.java deleted file mode 100644 index b1bc857f5..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/CTPresetColor.java +++ /dev/null @@ -1,183 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import java.util.ArrayList; -import java.util.List; -import javax.xml.bind.JAXBElement; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlElementRef; -import javax.xml.bind.annotation.XmlElementRefs; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for CT_PresetColor complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="CT_PresetColor">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <sequence>
    - *         <group ref="{http://schemas.openxmlformats.org/drawingml/2006/main}EG_ColorTransform" maxOccurs="unbounded" minOccurs="0"/>
    - *       </sequence>
    - *       <attribute name="val" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_PresetColorVal" />
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "CT_PresetColor", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", propOrder = { - "egColorTransform" -}) -public class CTPresetColor { - - @XmlElementRefs({ - @XmlElementRef(name = "shade", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "hue", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "blue", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "satOff", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "alphaMod", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "blueOff", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "green", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "red", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "gray", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "lum", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "invGamma", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "comp", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "lumOff", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "greenOff", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "sat", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "redMod", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "greenMod", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "lumMod", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "alpha", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "alphaOff", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "hueMod", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "inv", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "hueOff", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "gamma", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "tint", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "satMod", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "redOff", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "blueMod", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class) - }) - protected List> egColorTransform; - @XmlAttribute - protected STPresetColorVal val; - - /** - * Gets the value of the egColorTransform property. - * - *

    - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the egColorTransform property. - * - *

    - * For example, to add a new item, do as follows: - *

    -     *    getEGColorTransform().add(newItem);
    -     * 
    - * - * - *

    - * Objects of the following type(s) are allowed in the list - * {@link JAXBElement }{@code <}{@link CTPositiveFixedPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPositiveFixedAngle }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPositivePercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTGrayscaleTransform }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTInverseGammaTransform }{@code >} - * {@link JAXBElement }{@code <}{@link CTComplementTransform }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPositiveFixedPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTFixedPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPositivePercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTInverseTransform }{@code >} - * {@link JAXBElement }{@code <}{@link CTAngle }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTGammaTransform }{@code >} - * {@link JAXBElement }{@code <}{@link CTPositiveFixedPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * - * - */ - public List> getEGColorTransform() { - if (egColorTransform == null) { - egColorTransform = new ArrayList>(); - } - return this.egColorTransform; - } - - public boolean isSetEGColorTransform() { - return ((this.egColorTransform!= null)&&(!this.egColorTransform.isEmpty())); - } - - public void unsetEGColorTransform() { - this.egColorTransform = null; - } - - /** - * Gets the value of the val property. - * - * @return - * possible object is - * {@link STPresetColorVal } - * - */ - public STPresetColorVal getVal() { - return val; - } - - /** - * Sets the value of the val property. - * - * @param value - * allowed object is - * {@link STPresetColorVal } - * - */ - public void setVal(STPresetColorVal value) { - this.val = value; - } - - public boolean isSetVal() { - return (this.val!= null); - } - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/CTPresetGeometry2D.java b/src/java/org/apache/poi/sl/draw/binding/CTPresetGeometry2D.java deleted file mode 100644 index a560e640c..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/CTPresetGeometry2D.java +++ /dev/null @@ -1,114 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for CT_PresetGeometry2D complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="CT_PresetGeometry2D">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <sequence>
    - *         <element name="avLst" type="{http://schemas.openxmlformats.org/drawingml/2006/main}CT_GeomGuideList" minOccurs="0"/>
    - *       </sequence>
    - *       <attribute name="prst" use="required" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_ShapeType" />
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "CT_PresetGeometry2D", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", propOrder = { - "avLst" -}) -public class CTPresetGeometry2D { - - @XmlElement(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") - protected CTGeomGuideList avLst; - @XmlAttribute(required = true) - protected STShapeType prst; - - /** - * Gets the value of the avLst property. - * - * @return - * possible object is - * {@link CTGeomGuideList } - * - */ - public CTGeomGuideList getAvLst() { - return avLst; - } - - /** - * Sets the value of the avLst property. - * - * @param value - * allowed object is - * {@link CTGeomGuideList } - * - */ - public void setAvLst(CTGeomGuideList value) { - this.avLst = value; - } - - public boolean isSetAvLst() { - return (this.avLst!= null); - } - - /** - * Gets the value of the prst property. - * - * @return - * possible object is - * {@link STShapeType } - * - */ - public STShapeType getPrst() { - return prst; - } - - /** - * Sets the value of the prst property. - * - * @param value - * allowed object is - * {@link STShapeType } - * - */ - public void setPrst(STShapeType value) { - this.prst = value; - } - - public boolean isSetPrst() { - return (this.prst!= null); - } - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/CTPresetTextShape.java b/src/java/org/apache/poi/sl/draw/binding/CTPresetTextShape.java deleted file mode 100644 index 052a765d9..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/CTPresetTextShape.java +++ /dev/null @@ -1,114 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for CT_PresetTextShape complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="CT_PresetTextShape">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <sequence>
    - *         <element name="avLst" type="{http://schemas.openxmlformats.org/drawingml/2006/main}CT_GeomGuideList" minOccurs="0"/>
    - *       </sequence>
    - *       <attribute name="prst" use="required" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_TextShapeType" />
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "CT_PresetTextShape", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", propOrder = { - "avLst" -}) -public class CTPresetTextShape { - - @XmlElement(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") - protected CTGeomGuideList avLst; - @XmlAttribute(required = true) - protected STTextShapeType prst; - - /** - * Gets the value of the avLst property. - * - * @return - * possible object is - * {@link CTGeomGuideList } - * - */ - public CTGeomGuideList getAvLst() { - return avLst; - } - - /** - * Sets the value of the avLst property. - * - * @param value - * allowed object is - * {@link CTGeomGuideList } - * - */ - public void setAvLst(CTGeomGuideList value) { - this.avLst = value; - } - - public boolean isSetAvLst() { - return (this.avLst!= null); - } - - /** - * Gets the value of the prst property. - * - * @return - * possible object is - * {@link STTextShapeType } - * - */ - public STTextShapeType getPrst() { - return prst; - } - - /** - * Sets the value of the prst property. - * - * @param value - * allowed object is - * {@link STTextShapeType } - * - */ - public void setPrst(STTextShapeType value) { - this.prst = value; - } - - public boolean isSetPrst() { - return (this.prst!= null); - } - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/CTRatio.java b/src/java/org/apache/poi/sl/draw/binding/CTRatio.java deleted file mode 100644 index 05df06b7a..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/CTRatio.java +++ /dev/null @@ -1,93 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for CT_Ratio complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="CT_Ratio">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <attribute name="n" use="required" type="{http://www.w3.org/2001/XMLSchema}long" />
    - *       <attribute name="d" use="required" type="{http://www.w3.org/2001/XMLSchema}long" />
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "CT_Ratio", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") -public class CTRatio { - - @XmlAttribute(required = true) - protected long n; - @XmlAttribute(required = true) - protected long d; - - /** - * Gets the value of the n property. - * - */ - public long getN() { - return n; - } - - /** - * Sets the value of the n property. - * - */ - public void setN(long value) { - this.n = value; - } - - public boolean isSetN() { - return true; - } - - /** - * Gets the value of the d property. - * - */ - public long getD() { - return d; - } - - /** - * Sets the value of the d property. - * - */ - public void setD(long value) { - this.d = value; - } - - public boolean isSetD() { - return true; - } - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/CTRelativeRect.java b/src/java/org/apache/poi/sl/draw/binding/CTRelativeRect.java deleted file mode 100644 index ed340ed2d..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/CTRelativeRect.java +++ /dev/null @@ -1,203 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for CT_RelativeRect complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="CT_RelativeRect">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <attribute name="l" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_Percentage" default="0" />
    - *       <attribute name="t" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_Percentage" default="0" />
    - *       <attribute name="r" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_Percentage" default="0" />
    - *       <attribute name="b" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_Percentage" default="0" />
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "CT_RelativeRect", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") -public class CTRelativeRect { - - @XmlAttribute - protected Integer l; - @XmlAttribute - protected Integer t; - @XmlAttribute - protected Integer r; - @XmlAttribute - protected Integer b; - - /** - * Gets the value of the l property. - * - * @return - * possible object is - * {@link Integer } - * - */ - public int getL() { - if (l == null) { - return 0; - } else { - return l; - } - } - - /** - * Sets the value of the l property. - * - * @param value - * allowed object is - * {@link Integer } - * - */ - public void setL(int value) { - this.l = value; - } - - public boolean isSetL() { - return (this.l!= null); - } - - public void unsetL() { - this.l = null; - } - - /** - * Gets the value of the t property. - * - * @return - * possible object is - * {@link Integer } - * - */ - public int getT() { - if (t == null) { - return 0; - } else { - return t; - } - } - - /** - * Sets the value of the t property. - * - * @param value - * allowed object is - * {@link Integer } - * - */ - public void setT(int value) { - this.t = value; - } - - public boolean isSetT() { - return (this.t!= null); - } - - public void unsetT() { - this.t = null; - } - - /** - * Gets the value of the r property. - * - * @return - * possible object is - * {@link Integer } - * - */ - public int getR() { - if (r == null) { - return 0; - } else { - return r; - } - } - - /** - * Sets the value of the r property. - * - * @param value - * allowed object is - * {@link Integer } - * - */ - public void setR(int value) { - this.r = value; - } - - public boolean isSetR() { - return (this.r!= null); - } - - public void unsetR() { - this.r = null; - } - - /** - * Gets the value of the b property. - * - * @return - * possible object is - * {@link Integer } - * - */ - public int getB() { - if (b == null) { - return 0; - } else { - return b; - } - } - - /** - * Sets the value of the b property. - * - * @param value - * allowed object is - * {@link Integer } - * - */ - public void setB(int value) { - this.b = value; - } - - public boolean isSetB() { - return (this.b!= null); - } - - public void unsetB() { - this.b = null; - } - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/CTSRgbColor.java b/src/java/org/apache/poi/sl/draw/binding/CTSRgbColor.java deleted file mode 100644 index be4d49b27..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/CTSRgbColor.java +++ /dev/null @@ -1,186 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import java.util.ArrayList; -import java.util.List; -import javax.xml.bind.JAXBElement; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlElementRef; -import javax.xml.bind.annotation.XmlElementRefs; -import javax.xml.bind.annotation.XmlType; -import javax.xml.bind.annotation.adapters.HexBinaryAdapter; -import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; - - -/** - *

    Java class for CT_SRgbColor complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="CT_SRgbColor">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <sequence>
    - *         <group ref="{http://schemas.openxmlformats.org/drawingml/2006/main}EG_ColorTransform" maxOccurs="unbounded" minOccurs="0"/>
    - *       </sequence>
    - *       <attribute name="val" use="required" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_HexBinary3" />
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "CT_SRgbColor", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", propOrder = { - "egColorTransform" -}) -public class CTSRgbColor { - - @XmlElementRefs({ - @XmlElementRef(name = "shade", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "blueOff", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "invGamma", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "redOff", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "lumOff", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "blueMod", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "hueMod", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "redMod", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "alpha", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "inv", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "red", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "hueOff", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "alphaMod", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "alphaOff", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "green", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "gray", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "sat", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "blue", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "lum", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "hue", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "gamma", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "tint", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "satMod", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "lumMod", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "greenOff", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "comp", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "satOff", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "greenMod", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class) - }) - protected List> egColorTransform; - @XmlAttribute(required = true) - @XmlJavaTypeAdapter(HexBinaryAdapter.class) - protected byte[] val; - - /** - * Gets the value of the egColorTransform property. - * - *

    - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the egColorTransform property. - * - *

    - * For example, to add a new item, do as follows: - *

    -     *    getEGColorTransform().add(newItem);
    -     * 
    - * - * - *

    - * Objects of the following type(s) are allowed in the list - * {@link JAXBElement }{@code <}{@link CTPositiveFixedPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTInverseGammaTransform }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPositivePercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPositiveFixedPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTInverseTransform }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTAngle }{@code >} - * {@link JAXBElement }{@code <}{@link CTPositivePercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTFixedPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTGrayscaleTransform }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPositiveFixedAngle }{@code >} - * {@link JAXBElement }{@code <}{@link CTGammaTransform }{@code >} - * {@link JAXBElement }{@code <}{@link CTPositiveFixedPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTComplementTransform }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * - * - */ - public List> getEGColorTransform() { - if (egColorTransform == null) { - egColorTransform = new ArrayList>(); - } - return this.egColorTransform; - } - - public boolean isSetEGColorTransform() { - return ((this.egColorTransform!= null)&&(!this.egColorTransform.isEmpty())); - } - - public void unsetEGColorTransform() { - this.egColorTransform = null; - } - - /** - * Gets the value of the val property. - * - * @return - * possible object is - * {@link String } - * - */ - public byte[] getVal() { - return val; - } - - /** - * Sets the value of the val property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setVal(byte[] value) { - this.val = (value != null) ? value.clone() : null; - } - - public boolean isSetVal() { - return (this.val!= null); - } - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/CTScRgbColor.java b/src/java/org/apache/poi/sl/draw/binding/CTScRgbColor.java deleted file mode 100644 index 7e8292149..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/CTScRgbColor.java +++ /dev/null @@ -1,221 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import java.util.ArrayList; -import java.util.List; -import javax.xml.bind.JAXBElement; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlElementRef; -import javax.xml.bind.annotation.XmlElementRefs; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for CT_ScRgbColor complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="CT_ScRgbColor">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <sequence>
    - *         <group ref="{http://schemas.openxmlformats.org/drawingml/2006/main}EG_ColorTransform" maxOccurs="unbounded" minOccurs="0"/>
    - *       </sequence>
    - *       <attribute name="r" use="required" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_Percentage" />
    - *       <attribute name="g" use="required" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_Percentage" />
    - *       <attribute name="b" use="required" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_Percentage" />
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "CT_ScRgbColor", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", propOrder = { - "egColorTransform" -}) -public class CTScRgbColor { - - @XmlElementRefs({ - @XmlElementRef(name = "sat", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "lumOff", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "lumMod", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "satMod", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "gray", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "tint", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "alphaMod", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "gamma", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "blue", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "alphaOff", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "comp", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "shade", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "redOff", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "red", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "satOff", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "blueOff", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "green", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "hue", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "greenOff", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "alpha", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "lum", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "inv", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "hueOff", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "invGamma", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "greenMod", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "redMod", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "hueMod", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "blueMod", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class) - }) - protected List> egColorTransform; - @XmlAttribute(required = true) - protected int r; - @XmlAttribute(required = true) - protected int g; - @XmlAttribute(required = true) - protected int b; - - /** - * Gets the value of the egColorTransform property. - * - *

    - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the egColorTransform property. - * - *

    - * For example, to add a new item, do as follows: - *

    -     *    getEGColorTransform().add(newItem);
    -     * 
    - * - * - *

    - * Objects of the following type(s) are allowed in the list - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTGrayscaleTransform }{@code >} - * {@link JAXBElement }{@code <}{@link CTPositiveFixedPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPositivePercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTGammaTransform }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTFixedPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTComplementTransform }{@code >} - * {@link JAXBElement }{@code <}{@link CTPositiveFixedPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPositiveFixedAngle }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPositiveFixedPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTInverseTransform }{@code >} - * {@link JAXBElement }{@code <}{@link CTAngle }{@code >} - * {@link JAXBElement }{@code <}{@link CTInverseGammaTransform }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPositivePercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * - * - */ - public List> getEGColorTransform() { - if (egColorTransform == null) { - egColorTransform = new ArrayList>(); - } - return this.egColorTransform; - } - - public boolean isSetEGColorTransform() { - return ((this.egColorTransform!= null)&&(!this.egColorTransform.isEmpty())); - } - - public void unsetEGColorTransform() { - this.egColorTransform = null; - } - - /** - * Gets the value of the r property. - * - */ - public int getR() { - return r; - } - - /** - * Sets the value of the r property. - * - */ - public void setR(int value) { - this.r = value; - } - - public boolean isSetR() { - return true; - } - - /** - * Gets the value of the g property. - * - */ - public int getG() { - return g; - } - - /** - * Sets the value of the g property. - * - */ - public void setG(int value) { - this.g = value; - } - - public boolean isSetG() { - return true; - } - - /** - * Gets the value of the b property. - * - */ - public int getB() { - return b; - } - - /** - * Sets the value of the b property. - * - */ - public void setB(int value) { - this.b = value; - } - - public boolean isSetB() { - return true; - } - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/CTScale2D.java b/src/java/org/apache/poi/sl/draw/binding/CTScale2D.java deleted file mode 100644 index ed94b74ad..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/CTScale2D.java +++ /dev/null @@ -1,114 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for CT_Scale2D complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="CT_Scale2D">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <sequence>
    - *         <element name="sx" type="{http://schemas.openxmlformats.org/drawingml/2006/main}CT_Ratio"/>
    - *         <element name="sy" type="{http://schemas.openxmlformats.org/drawingml/2006/main}CT_Ratio"/>
    - *       </sequence>
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "CT_Scale2D", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", propOrder = { - "sx", - "sy" -}) -public class CTScale2D { - - @XmlElement(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", required = true) - protected CTRatio sx; - @XmlElement(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", required = true) - protected CTRatio sy; - - /** - * Gets the value of the sx property. - * - * @return - * possible object is - * {@link CTRatio } - * - */ - public CTRatio getSx() { - return sx; - } - - /** - * Sets the value of the sx property. - * - * @param value - * allowed object is - * {@link CTRatio } - * - */ - public void setSx(CTRatio value) { - this.sx = value; - } - - public boolean isSetSx() { - return (this.sx!= null); - } - - /** - * Gets the value of the sy property. - * - * @return - * possible object is - * {@link CTRatio } - * - */ - public CTRatio getSy() { - return sy; - } - - /** - * Sets the value of the sy property. - * - * @param value - * allowed object is - * {@link CTRatio } - * - */ - public void setSy(CTRatio value) { - this.sy = value; - } - - public boolean isSetSy() { - return (this.sy!= null); - } - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/CTSchemeColor.java b/src/java/org/apache/poi/sl/draw/binding/CTSchemeColor.java deleted file mode 100644 index fcafd606f..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/CTSchemeColor.java +++ /dev/null @@ -1,183 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import java.util.ArrayList; -import java.util.List; -import javax.xml.bind.JAXBElement; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlElementRef; -import javax.xml.bind.annotation.XmlElementRefs; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for CT_SchemeColor complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="CT_SchemeColor">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <sequence>
    - *         <group ref="{http://schemas.openxmlformats.org/drawingml/2006/main}EG_ColorTransform" maxOccurs="unbounded" minOccurs="0"/>
    - *       </sequence>
    - *       <attribute name="val" use="required" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_SchemeColorVal" />
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "CT_SchemeColor", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", propOrder = { - "egColorTransform" -}) -public class CTSchemeColor { - - @XmlElementRefs({ - @XmlElementRef(name = "redMod", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "redOff", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "comp", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "sat", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "satMod", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "gray", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "tint", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "alpha", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "red", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "greenOff", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "greenMod", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "blue", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "inv", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "lumOff", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "blueMod", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "hueMod", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "hueOff", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "gamma", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "alphaMod", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "green", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "alphaOff", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "hue", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "lum", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "blueOff", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "lumMod", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "shade", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "satOff", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "invGamma", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class) - }) - protected List> egColorTransform; - @XmlAttribute(required = true) - protected STSchemeColorVal val; - - /** - * Gets the value of the egColorTransform property. - * - *

    - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the egColorTransform property. - * - *

    - * For example, to add a new item, do as follows: - *

    -     *    getEGColorTransform().add(newItem);
    -     * 
    - * - * - *

    - * Objects of the following type(s) are allowed in the list - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTComplementTransform }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTGrayscaleTransform }{@code >} - * {@link JAXBElement }{@code <}{@link CTPositiveFixedPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPositiveFixedPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTInverseTransform }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPositivePercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTAngle }{@code >} - * {@link JAXBElement }{@code <}{@link CTGammaTransform }{@code >} - * {@link JAXBElement }{@code <}{@link CTPositivePercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTFixedPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPositiveFixedAngle }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTInverseGammaTransform }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPositiveFixedPercentage }{@code >} - * - * - */ - public List> getEGColorTransform() { - if (egColorTransform == null) { - egColorTransform = new ArrayList>(); - } - return this.egColorTransform; - } - - public boolean isSetEGColorTransform() { - return ((this.egColorTransform!= null)&&(!this.egColorTransform.isEmpty())); - } - - public void unsetEGColorTransform() { - this.egColorTransform = null; - } - - /** - * Gets the value of the val property. - * - * @return - * possible object is - * {@link STSchemeColorVal } - * - */ - public STSchemeColorVal getVal() { - return val; - } - - /** - * Sets the value of the val property. - * - * @param value - * allowed object is - * {@link STSchemeColorVal } - * - */ - public void setVal(STSchemeColorVal value) { - this.val = value; - } - - public boolean isSetVal() { - return (this.val!= null); - } - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/CTSphereCoords.java b/src/java/org/apache/poi/sl/draw/binding/CTSphereCoords.java deleted file mode 100644 index 4921935ab..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/CTSphereCoords.java +++ /dev/null @@ -1,116 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for CT_SphereCoords complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="CT_SphereCoords">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <attribute name="lat" use="required" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_PositiveFixedAngle" />
    - *       <attribute name="lon" use="required" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_PositiveFixedAngle" />
    - *       <attribute name="rev" use="required" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_PositiveFixedAngle" />
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "CT_SphereCoords", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") -public class CTSphereCoords { - - @XmlAttribute(required = true) - protected int lat; - @XmlAttribute(required = true) - protected int lon; - @XmlAttribute(required = true) - protected int rev; - - /** - * Gets the value of the lat property. - * - */ - public int getLat() { - return lat; - } - - /** - * Sets the value of the lat property. - * - */ - public void setLat(int value) { - this.lat = value; - } - - public boolean isSetLat() { - return true; - } - - /** - * Gets the value of the lon property. - * - */ - public int getLon() { - return lon; - } - - /** - * Sets the value of the lon property. - * - */ - public void setLon(int value) { - this.lon = value; - } - - public boolean isSetLon() { - return true; - } - - /** - * Gets the value of the rev property. - * - */ - public int getRev() { - return rev; - } - - /** - * Sets the value of the rev property. - * - */ - public void setRev(int value) { - this.rev = value; - } - - public boolean isSetRev() { - return true; - } - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/CTSystemColor.java b/src/java/org/apache/poi/sl/draw/binding/CTSystemColor.java deleted file mode 100644 index b5657ff21..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/CTSystemColor.java +++ /dev/null @@ -1,219 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import java.util.ArrayList; -import java.util.List; -import javax.xml.bind.JAXBElement; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlElementRef; -import javax.xml.bind.annotation.XmlElementRefs; -import javax.xml.bind.annotation.XmlType; -import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; -import javax.xml.bind.annotation.adapters.HexBinaryAdapter; -import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; - - -/** - *

    Java class for CT_SystemColor complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="CT_SystemColor">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <sequence>
    - *         <group ref="{http://schemas.openxmlformats.org/drawingml/2006/main}EG_ColorTransform" maxOccurs="unbounded" minOccurs="0"/>
    - *       </sequence>
    - *       <attribute name="val" use="required" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_SystemColorVal" />
    - *       <attribute name="lastClr" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_HexBinary3" />
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "CT_SystemColor", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", propOrder = { - "egColorTransform" -}) -public class CTSystemColor { - - @XmlElementRefs({ - @XmlElementRef(name = "gray", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "green", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "shade", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "blueOff", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "lumMod", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "alphaMod", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "redMod", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "blue", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "sat", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "alphaOff", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "red", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "greenOff", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "hueMod", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "satOff", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "gamma", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "redOff", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "hue", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "satMod", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "lum", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "comp", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "invGamma", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "hueOff", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "alpha", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "greenMod", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "inv", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "blueMod", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "tint", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class), - @XmlElementRef(name = "lumOff", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", type = JAXBElement.class) - }) - protected List> egColorTransform; - @XmlAttribute(required = true) - @XmlJavaTypeAdapter(CollapsedStringAdapter.class) - protected String val; - @XmlAttribute - @XmlJavaTypeAdapter(HexBinaryAdapter.class) - protected byte[] lastClr; - - /** - * Gets the value of the egColorTransform property. - * - *

    - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the egColorTransform property. - * - *

    - * For example, to add a new item, do as follows: - *

    -     *    getEGColorTransform().add(newItem);
    -     * 
    - * - * - *

    - * Objects of the following type(s) are allowed in the list - * {@link JAXBElement }{@code <}{@link CTGrayscaleTransform }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPositiveFixedPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPositivePercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTFixedPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPositivePercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTGammaTransform }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPositiveFixedAngle }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTComplementTransform }{@code >} - * {@link JAXBElement }{@code <}{@link CTInverseGammaTransform }{@code >} - * {@link JAXBElement }{@code <}{@link CTAngle }{@code >} - * {@link JAXBElement }{@code <}{@link CTPositiveFixedPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTInverseTransform }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPositiveFixedPercentage }{@code >} - * {@link JAXBElement }{@code <}{@link CTPercentage }{@code >} - * - * - */ - public List> getEGColorTransform() { - if (egColorTransform == null) { - egColorTransform = new ArrayList>(); - } - return this.egColorTransform; - } - - public boolean isSetEGColorTransform() { - return ((this.egColorTransform!= null)&&(!this.egColorTransform.isEmpty())); - } - - public void unsetEGColorTransform() { - this.egColorTransform = null; - } - - /** - * Gets the value of the val property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getVal() { - return val; - } - - /** - * Sets the value of the val property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setVal(String value) { - this.val = value; - } - - public boolean isSetVal() { - return (this.val!= null); - } - - /** - * Gets the value of the lastClr property. - * - * @return - * possible object is - * {@link String } - * - */ - public byte[] getLastClr() { - return lastClr; - } - - /** - * Sets the value of the lastClr property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setLastClr(byte[] value) { - this.lastClr = (value != null) ? value.clone() : null; - } - - public boolean isSetLastClr() { - return (this.lastClr!= null); - } - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/CTTransform2D.java b/src/java/org/apache/poi/sl/draw/binding/CTTransform2D.java deleted file mode 100644 index efe57bc08..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/CTTransform2D.java +++ /dev/null @@ -1,232 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for CT_Transform2D complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="CT_Transform2D">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <sequence>
    - *         <element name="off" type="{http://schemas.openxmlformats.org/drawingml/2006/main}CT_Point2D" minOccurs="0"/>
    - *         <element name="ext" type="{http://schemas.openxmlformats.org/drawingml/2006/main}CT_PositiveSize2D" minOccurs="0"/>
    - *       </sequence>
    - *       <attribute name="rot" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_Angle" default="0" />
    - *       <attribute name="flipH" type="{http://www.w3.org/2001/XMLSchema}boolean" default="false" />
    - *       <attribute name="flipV" type="{http://www.w3.org/2001/XMLSchema}boolean" default="false" />
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "CT_Transform2D", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", propOrder = { - "off", - "ext" -}) -public class CTTransform2D { - - @XmlElement(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") - protected CTPoint2D off; - @XmlElement(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") - protected CTPositiveSize2D ext; - @XmlAttribute - protected Integer rot; - @XmlAttribute - protected Boolean flipH; - @XmlAttribute - protected Boolean flipV; - - /** - * Gets the value of the off property. - * - * @return - * possible object is - * {@link CTPoint2D } - * - */ - public CTPoint2D getOff() { - return off; - } - - /** - * Sets the value of the off property. - * - * @param value - * allowed object is - * {@link CTPoint2D } - * - */ - public void setOff(CTPoint2D value) { - this.off = value; - } - - public boolean isSetOff() { - return (this.off!= null); - } - - /** - * Gets the value of the ext property. - * - * @return - * possible object is - * {@link CTPositiveSize2D } - * - */ - public CTPositiveSize2D getExt() { - return ext; - } - - /** - * Sets the value of the ext property. - * - * @param value - * allowed object is - * {@link CTPositiveSize2D } - * - */ - public void setExt(CTPositiveSize2D value) { - this.ext = value; - } - - public boolean isSetExt() { - return (this.ext!= null); - } - - /** - * Gets the value of the rot property. - * - * @return - * possible object is - * {@link Integer } - * - */ - public int getRot() { - if (rot == null) { - return 0; - } else { - return rot; - } - } - - /** - * Sets the value of the rot property. - * - * @param value - * allowed object is - * {@link Integer } - * - */ - public void setRot(int value) { - this.rot = value; - } - - public boolean isSetRot() { - return (this.rot!= null); - } - - public void unsetRot() { - this.rot = null; - } - - /** - * Gets the value of the flipH property. - * - * @return - * possible object is - * {@link Boolean } - * - */ - public boolean isFlipH() { - if (flipH == null) { - return false; - } else { - return flipH; - } - } - - /** - * Sets the value of the flipH property. - * - * @param value - * allowed object is - * {@link Boolean } - * - */ - public void setFlipH(boolean value) { - this.flipH = value; - } - - public boolean isSetFlipH() { - return (this.flipH!= null); - } - - public void unsetFlipH() { - this.flipH = null; - } - - /** - * Gets the value of the flipV property. - * - * @return - * possible object is - * {@link Boolean } - * - */ - public boolean isFlipV() { - if (flipV == null) { - return false; - } else { - return flipV; - } - } - - /** - * Sets the value of the flipV property. - * - * @param value - * allowed object is - * {@link Boolean } - * - */ - public void setFlipV(boolean value) { - this.flipV = value; - } - - public boolean isSetFlipV() { - return (this.flipV!= null); - } - - public void unsetFlipV() { - this.flipV = null; - } - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/CTVector3D.java b/src/java/org/apache/poi/sl/draw/binding/CTVector3D.java deleted file mode 100644 index cd97d6bc9..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/CTVector3D.java +++ /dev/null @@ -1,116 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for CT_Vector3D complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="CT_Vector3D">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <attribute name="dx" use="required" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_Coordinate" />
    - *       <attribute name="dy" use="required" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_Coordinate" />
    - *       <attribute name="dz" use="required" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_Coordinate" />
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "CT_Vector3D", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") -public class CTVector3D { - - @XmlAttribute(required = true) - protected long dx; - @XmlAttribute(required = true) - protected long dy; - @XmlAttribute(required = true) - protected long dz; - - /** - * Gets the value of the dx property. - * - */ - public long getDx() { - return dx; - } - - /** - * Sets the value of the dx property. - * - */ - public void setDx(long value) { - this.dx = value; - } - - public boolean isSetDx() { - return true; - } - - /** - * Gets the value of the dy property. - * - */ - public long getDy() { - return dy; - } - - /** - * Sets the value of the dy property. - * - */ - public void setDy(long value) { - this.dy = value; - } - - public boolean isSetDy() { - return true; - } - - /** - * Gets the value of the dz property. - * - */ - public long getDz() { - return dz; - } - - /** - * Sets the value of the dz property. - * - */ - public void setDz(long value) { - this.dz = value; - } - - public boolean isSetDz() { - return true; - } - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/CTXYAdjustHandle.java b/src/java/org/apache/poi/sl/draw/binding/CTXYAdjustHandle.java deleted file mode 100644 index 2942bb9ee..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/CTXYAdjustHandle.java +++ /dev/null @@ -1,273 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlType; -import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; -import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; - - -/** - *

    Java class for CT_XYAdjustHandle complex type. - * - *

    The following schema fragment specifies the expected content contained within this class. - * - *

    - * <complexType name="CT_XYAdjustHandle">
    - *   <complexContent>
    - *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
    - *       <sequence>
    - *         <element name="pos" type="{http://schemas.openxmlformats.org/drawingml/2006/main}CT_AdjPoint2D"/>
    - *       </sequence>
    - *       <attribute name="gdRefX" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_GeomGuideName" />
    - *       <attribute name="minX" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_AdjCoordinate" />
    - *       <attribute name="maxX" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_AdjCoordinate" />
    - *       <attribute name="gdRefY" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_GeomGuideName" />
    - *       <attribute name="minY" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_AdjCoordinate" />
    - *       <attribute name="maxY" type="{http://schemas.openxmlformats.org/drawingml/2006/main}ST_AdjCoordinate" />
    - *     </restriction>
    - *   </complexContent>
    - * </complexType>
    - * 
    - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "CT_XYAdjustHandle", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", propOrder = { - "pos" -}) -public class CTXYAdjustHandle { - - @XmlElement(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", required = true) - protected CTAdjPoint2D pos; - @XmlAttribute - @XmlJavaTypeAdapter(CollapsedStringAdapter.class) - protected String gdRefX; - @XmlAttribute - protected String minX; - @XmlAttribute - protected String maxX; - @XmlAttribute - @XmlJavaTypeAdapter(CollapsedStringAdapter.class) - protected String gdRefY; - @XmlAttribute - protected String minY; - @XmlAttribute - protected String maxY; - - /** - * Gets the value of the pos property. - * - * @return - * possible object is - * {@link CTAdjPoint2D } - * - */ - public CTAdjPoint2D getPos() { - return pos; - } - - /** - * Sets the value of the pos property. - * - * @param value - * allowed object is - * {@link CTAdjPoint2D } - * - */ - public void setPos(CTAdjPoint2D value) { - this.pos = value; - } - - public boolean isSetPos() { - return (this.pos!= null); - } - - /** - * Gets the value of the gdRefX property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getGdRefX() { - return gdRefX; - } - - /** - * Sets the value of the gdRefX property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setGdRefX(String value) { - this.gdRefX = value; - } - - public boolean isSetGdRefX() { - return (this.gdRefX!= null); - } - - /** - * Gets the value of the minX property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getMinX() { - return minX; - } - - /** - * Sets the value of the minX property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setMinX(String value) { - this.minX = value; - } - - public boolean isSetMinX() { - return (this.minX!= null); - } - - /** - * Gets the value of the maxX property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getMaxX() { - return maxX; - } - - /** - * Sets the value of the maxX property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setMaxX(String value) { - this.maxX = value; - } - - public boolean isSetMaxX() { - return (this.maxX!= null); - } - - /** - * Gets the value of the gdRefY property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getGdRefY() { - return gdRefY; - } - - /** - * Sets the value of the gdRefY property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setGdRefY(String value) { - this.gdRefY = value; - } - - public boolean isSetGdRefY() { - return (this.gdRefY!= null); - } - - /** - * Gets the value of the minY property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getMinY() { - return minY; - } - - /** - * Sets the value of the minY property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setMinY(String value) { - this.minY = value; - } - - public boolean isSetMinY() { - return (this.minY!= null); - } - - /** - * Gets the value of the maxY property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getMaxY() { - return maxY; - } - - /** - * Sets the value of the maxY property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setMaxY(String value) { - this.maxY = value; - } - - public boolean isSetMaxY() { - return (this.maxY!= null); - } - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/ObjectFactory.java b/src/java/org/apache/poi/sl/draw/binding/ObjectFactory.java deleted file mode 100644 index 1a2e14db3..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/ObjectFactory.java +++ /dev/null @@ -1,2023 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import javax.xml.bind.JAXBElement; -import javax.xml.bind.annotation.XmlElementDecl; -import javax.xml.bind.annotation.XmlRegistry; -import javax.xml.namespace.QName; - - -/** - * This object contains factory methods for each - * Java content interface and Java element interface - * generated in the org.apache.poi.sl.draw.binding package. - *

    An ObjectFactory allows you to programatically - * construct new instances of the Java representation - * for XML content. The Java representation of XML - * content can consist of schema derived interfaces - * and classes representing the binding of schema - * type definitions, element declarations and model - * groups. Factory methods for each of these are - * provided in this class. - * - */ -@XmlRegistry -public class ObjectFactory { - - private final static QName _CTSRgbColorAlpha_QNAME = new QName("http://schemas.openxmlformats.org/drawingml/2006/main", "alpha"); - private final static QName _CTSRgbColorLum_QNAME = new QName("http://schemas.openxmlformats.org/drawingml/2006/main", "lum"); - private final static QName _CTSRgbColorGamma_QNAME = new QName("http://schemas.openxmlformats.org/drawingml/2006/main", "gamma"); - private final static QName _CTSRgbColorInvGamma_QNAME = new QName("http://schemas.openxmlformats.org/drawingml/2006/main", "invGamma"); - private final static QName _CTSRgbColorRedOff_QNAME = new QName("http://schemas.openxmlformats.org/drawingml/2006/main", "redOff"); - private final static QName _CTSRgbColorAlphaMod_QNAME = new QName("http://schemas.openxmlformats.org/drawingml/2006/main", "alphaMod"); - private final static QName _CTSRgbColorAlphaOff_QNAME = new QName("http://schemas.openxmlformats.org/drawingml/2006/main", "alphaOff"); - private final static QName _CTSRgbColorGreenOff_QNAME = new QName("http://schemas.openxmlformats.org/drawingml/2006/main", "greenOff"); - private final static QName _CTSRgbColorRedMod_QNAME = new QName("http://schemas.openxmlformats.org/drawingml/2006/main", "redMod"); - private final static QName _CTSRgbColorHue_QNAME = new QName("http://schemas.openxmlformats.org/drawingml/2006/main", "hue"); - private final static QName _CTSRgbColorSatOff_QNAME = new QName("http://schemas.openxmlformats.org/drawingml/2006/main", "satOff"); - private final static QName _CTSRgbColorGreenMod_QNAME = new QName("http://schemas.openxmlformats.org/drawingml/2006/main", "greenMod"); - private final static QName _CTSRgbColorSat_QNAME = new QName("http://schemas.openxmlformats.org/drawingml/2006/main", "sat"); - private final static QName _CTSRgbColorBlue_QNAME = new QName("http://schemas.openxmlformats.org/drawingml/2006/main", "blue"); - private final static QName _CTSRgbColorRed_QNAME = new QName("http://schemas.openxmlformats.org/drawingml/2006/main", "red"); - private final static QName _CTSRgbColorSatMod_QNAME = new QName("http://schemas.openxmlformats.org/drawingml/2006/main", "satMod"); - private final static QName _CTSRgbColorHueOff_QNAME = new QName("http://schemas.openxmlformats.org/drawingml/2006/main", "hueOff"); - private final static QName _CTSRgbColorBlueMod_QNAME = new QName("http://schemas.openxmlformats.org/drawingml/2006/main", "blueMod"); - private final static QName _CTSRgbColorShade_QNAME = new QName("http://schemas.openxmlformats.org/drawingml/2006/main", "shade"); - private final static QName _CTSRgbColorLumMod_QNAME = new QName("http://schemas.openxmlformats.org/drawingml/2006/main", "lumMod"); - private final static QName _CTSRgbColorInv_QNAME = new QName("http://schemas.openxmlformats.org/drawingml/2006/main", "inv"); - private final static QName _CTSRgbColorLumOff_QNAME = new QName("http://schemas.openxmlformats.org/drawingml/2006/main", "lumOff"); - private final static QName _CTSRgbColorTint_QNAME = new QName("http://schemas.openxmlformats.org/drawingml/2006/main", "tint"); - private final static QName _CTSRgbColorGreen_QNAME = new QName("http://schemas.openxmlformats.org/drawingml/2006/main", "green"); - private final static QName _CTSRgbColorComp_QNAME = new QName("http://schemas.openxmlformats.org/drawingml/2006/main", "comp"); - private final static QName _CTSRgbColorBlueOff_QNAME = new QName("http://schemas.openxmlformats.org/drawingml/2006/main", "blueOff"); - private final static QName _CTSRgbColorHueMod_QNAME = new QName("http://schemas.openxmlformats.org/drawingml/2006/main", "hueMod"); - private final static QName _CTSRgbColorGray_QNAME = new QName("http://schemas.openxmlformats.org/drawingml/2006/main", "gray"); - - /** - * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.apache.poi.sl.draw.binding - * - */ - public ObjectFactory() { - } - - /** - * Create an instance of {@link CTPositiveSize2D } - * - */ - public CTPositiveSize2D createCTPositiveSize2D() { - return new CTPositiveSize2D(); - } - - /** - * Create an instance of {@link CTSphereCoords } - * - */ - public CTSphereCoords createCTSphereCoords() { - return new CTSphereCoords(); - } - - /** - * Create an instance of {@link CTPositivePercentage } - * - */ - public CTPositivePercentage createCTPositivePercentage() { - return new CTPositivePercentage(); - } - - /** - * Create an instance of {@link CTAdjPoint2D } - * - */ - public CTAdjPoint2D createCTAdjPoint2D() { - return new CTAdjPoint2D(); - } - - /** - * Create an instance of {@link CTPath2DCubicBezierTo } - * - */ - public CTPath2DCubicBezierTo createCTPath2DCubicBezierTo() { - return new CTPath2DCubicBezierTo(); - } - - /** - * Create an instance of {@link CTEmbeddedWAVAudioFile } - * - */ - public CTEmbeddedWAVAudioFile createCTEmbeddedWAVAudioFile() { - return new CTEmbeddedWAVAudioFile(); - } - - /** - * Create an instance of {@link CTPresetGeometry2D } - * - */ - public CTPresetGeometry2D createCTPresetGeometry2D() { - return new CTPresetGeometry2D(); - } - - /** - * Create an instance of {@link CTSchemeColor } - * - */ - public CTSchemeColor createCTSchemeColor() { - return new CTSchemeColor(); - } - - /** - * Create an instance of {@link CTInverseTransform } - * - */ - public CTInverseTransform createCTInverseTransform() { - return new CTInverseTransform(); - } - - /** - * Create an instance of {@link CTScRgbColor } - * - */ - public CTScRgbColor createCTScRgbColor() { - return new CTScRgbColor(); - } - - /** - * Create an instance of {@link CTPositiveFixedAngle } - * - */ - public CTPositiveFixedAngle createCTPositiveFixedAngle() { - return new CTPositiveFixedAngle(); - } - - /** - * Create an instance of {@link CTInverseGammaTransform } - * - */ - public CTInverseGammaTransform createCTInverseGammaTransform() { - return new CTInverseGammaTransform(); - } - - /** - * Create an instance of {@link CTColorMRU } - * - */ - public CTColorMRU createCTColorMRU() { - return new CTColorMRU(); - } - - /** - * Create an instance of {@link CTPath2DArcTo } - * - */ - public CTPath2DArcTo createCTPath2DArcTo() { - return new CTPath2DArcTo(); - } - - /** - * Create an instance of {@link CTSystemColor } - * - */ - public CTSystemColor createCTSystemColor() { - return new CTSystemColor(); - } - - /** - * Create an instance of {@link CTGroupTransform2D } - * - */ - public CTGroupTransform2D createCTGroupTransform2D() { - return new CTGroupTransform2D(); - } - - /** - * Create an instance of {@link CTPoint2D } - * - */ - public CTPoint2D createCTPoint2D() { - return new CTPoint2D(); - } - - /** - * Create an instance of {@link CTGeomRect } - * - */ - public CTGeomRect createCTGeomRect() { - return new CTGeomRect(); - } - - /** - * Create an instance of {@link CTScale2D } - * - */ - public CTScale2D createCTScale2D() { - return new CTScale2D(); - } - - /** - * Create an instance of {@link CTGeomGuide } - * - */ - public CTGeomGuide createCTGeomGuide() { - return new CTGeomGuide(); - } - - /** - * Create an instance of {@link CTXYAdjustHandle } - * - */ - public CTXYAdjustHandle createCTXYAdjustHandle() { - return new CTXYAdjustHandle(); - } - - /** - * Create an instance of {@link CTCustomGeometry2D } - * - */ - public CTCustomGeometry2D createCTCustomGeometry2D() { - return new CTCustomGeometry2D(); - } - - /** - * Create an instance of {@link CTOfficeArtExtension } - * - */ - public CTOfficeArtExtension createCTOfficeArtExtension() { - return new CTOfficeArtExtension(); - } - - /** - * Create an instance of {@link CTGrayscaleTransform } - * - */ - public CTGrayscaleTransform createCTGrayscaleTransform() { - return new CTGrayscaleTransform(); - } - - /** - * Create an instance of {@link CTPath2DClose } - * - */ - public CTPath2DClose createCTPath2DClose() { - return new CTPath2DClose(); - } - - /** - * Create an instance of {@link CTComplementTransform } - * - */ - public CTComplementTransform createCTComplementTransform() { - return new CTComplementTransform(); - } - - /** - * Create an instance of {@link CTPoint3D } - * - */ - public CTPoint3D createCTPoint3D() { - return new CTPoint3D(); - } - - /** - * Create an instance of {@link CTPositiveFixedPercentage } - * - */ - public CTPositiveFixedPercentage createCTPositiveFixedPercentage() { - return new CTPositiveFixedPercentage(); - } - - /** - * Create an instance of {@link CTPath2D } - * - */ - public CTPath2D createCTPath2D() { - return new CTPath2D(); - } - - /** - * Create an instance of {@link CTAdjustHandleList } - * - */ - public CTAdjustHandleList createCTAdjustHandleList() { - return new CTAdjustHandleList(); - } - - /** - * Create an instance of {@link CTConnectionSiteList } - * - */ - public CTConnectionSiteList createCTConnectionSiteList() { - return new CTConnectionSiteList(); - } - - /** - * Create an instance of {@link CTPresetTextShape } - * - */ - public CTPresetTextShape createCTPresetTextShape() { - return new CTPresetTextShape(); - } - - /** - * Create an instance of {@link CTSRgbColor } - * - */ - public CTSRgbColor createCTSRgbColor() { - return new CTSRgbColor(); - } - - /** - * Create an instance of {@link CTPath2DMoveTo } - * - */ - public CTPath2DMoveTo createCTPath2DMoveTo() { - return new CTPath2DMoveTo(); - } - - /** - * Create an instance of {@link CTRelativeRect } - * - */ - public CTRelativeRect createCTRelativeRect() { - return new CTRelativeRect(); - } - - /** - * Create an instance of {@link CTPath2DList } - * - */ - public CTPath2DList createCTPath2DList() { - return new CTPath2DList(); - } - - /** - * Create an instance of {@link CTPolarAdjustHandle } - * - */ - public CTPolarAdjustHandle createCTPolarAdjustHandle() { - return new CTPolarAdjustHandle(); - } - - /** - * Create an instance of {@link CTPercentage } - * - */ - public CTPercentage createCTPercentage() { - return new CTPercentage(); - } - - /** - * Create an instance of {@link CTHslColor } - * - */ - public CTHslColor createCTHslColor() { - return new CTHslColor(); - } - - /** - * Create an instance of {@link CTRatio } - * - */ - public CTRatio createCTRatio() { - return new CTRatio(); - } - - /** - * Create an instance of {@link CTGeomGuideList } - * - */ - public CTGeomGuideList createCTGeomGuideList() { - return new CTGeomGuideList(); - } - - /** - * Create an instance of {@link CTTransform2D } - * - */ - public CTTransform2D createCTTransform2D() { - return new CTTransform2D(); - } - - /** - * Create an instance of {@link CTGammaTransform } - * - */ - public CTGammaTransform createCTGammaTransform() { - return new CTGammaTransform(); - } - - /** - * Create an instance of {@link CTPath2DQuadBezierTo } - * - */ - public CTPath2DQuadBezierTo createCTPath2DQuadBezierTo() { - return new CTPath2DQuadBezierTo(); - } - - /** - * Create an instance of {@link CTAngle } - * - */ - public CTAngle createCTAngle() { - return new CTAngle(); - } - - /** - * Create an instance of {@link CTConnectionSite } - * - */ - public CTConnectionSite createCTConnectionSite() { - return new CTConnectionSite(); - } - - /** - * Create an instance of {@link CTHyperlink } - * - */ - public CTHyperlink createCTHyperlink() { - return new CTHyperlink(); - } - - /** - * Create an instance of {@link CTFixedPercentage } - * - */ - public CTFixedPercentage createCTFixedPercentage() { - return new CTFixedPercentage(); - } - - /** - * Create an instance of {@link CTPath2DLineTo } - * - */ - public CTPath2DLineTo createCTPath2DLineTo() { - return new CTPath2DLineTo(); - } - - /** - * Create an instance of {@link CTColor } - * - */ - public CTColor createCTColor() { - return new CTColor(); - } - - /** - * Create an instance of {@link CTPresetColor } - * - */ - public CTPresetColor createCTPresetColor() { - return new CTPresetColor(); - } - - /** - * Create an instance of {@link CTVector3D } - * - */ - public CTVector3D createCTVector3D() { - return new CTVector3D(); - } - - /** - * Create an instance of {@link CTOfficeArtExtensionList } - * - */ - public CTOfficeArtExtensionList createCTOfficeArtExtensionList() { - return new CTOfficeArtExtensionList(); - } - - /** - * Create an instance of {@link CTConnection } - * - */ - public CTConnection createCTConnection() { - return new CTConnection(); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPositiveFixedPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "alpha", scope = CTSRgbColor.class) - public JAXBElement createCTSRgbColorAlpha(CTPositiveFixedPercentage value) { - return new JAXBElement(_CTSRgbColorAlpha_QNAME, CTPositiveFixedPercentage.class, CTSRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "lum", scope = CTSRgbColor.class) - public JAXBElement createCTSRgbColorLum(CTPercentage value) { - return new JAXBElement(_CTSRgbColorLum_QNAME, CTPercentage.class, CTSRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTGammaTransform }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "gamma", scope = CTSRgbColor.class) - public JAXBElement createCTSRgbColorGamma(CTGammaTransform value) { - return new JAXBElement(_CTSRgbColorGamma_QNAME, CTGammaTransform.class, CTSRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTInverseGammaTransform }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "invGamma", scope = CTSRgbColor.class) - public JAXBElement createCTSRgbColorInvGamma(CTInverseGammaTransform value) { - return new JAXBElement(_CTSRgbColorInvGamma_QNAME, CTInverseGammaTransform.class, CTSRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "redOff", scope = CTSRgbColor.class) - public JAXBElement createCTSRgbColorRedOff(CTPercentage value) { - return new JAXBElement(_CTSRgbColorRedOff_QNAME, CTPercentage.class, CTSRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPositivePercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "alphaMod", scope = CTSRgbColor.class) - public JAXBElement createCTSRgbColorAlphaMod(CTPositivePercentage value) { - return new JAXBElement(_CTSRgbColorAlphaMod_QNAME, CTPositivePercentage.class, CTSRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTFixedPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "alphaOff", scope = CTSRgbColor.class) - public JAXBElement createCTSRgbColorAlphaOff(CTFixedPercentage value) { - return new JAXBElement(_CTSRgbColorAlphaOff_QNAME, CTFixedPercentage.class, CTSRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "greenOff", scope = CTSRgbColor.class) - public JAXBElement createCTSRgbColorGreenOff(CTPercentage value) { - return new JAXBElement(_CTSRgbColorGreenOff_QNAME, CTPercentage.class, CTSRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "redMod", scope = CTSRgbColor.class) - public JAXBElement createCTSRgbColorRedMod(CTPercentage value) { - return new JAXBElement(_CTSRgbColorRedMod_QNAME, CTPercentage.class, CTSRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPositiveFixedAngle }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "hue", scope = CTSRgbColor.class) - public JAXBElement createCTSRgbColorHue(CTPositiveFixedAngle value) { - return new JAXBElement(_CTSRgbColorHue_QNAME, CTPositiveFixedAngle.class, CTSRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "satOff", scope = CTSRgbColor.class) - public JAXBElement createCTSRgbColorSatOff(CTPercentage value) { - return new JAXBElement(_CTSRgbColorSatOff_QNAME, CTPercentage.class, CTSRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "greenMod", scope = CTSRgbColor.class) - public JAXBElement createCTSRgbColorGreenMod(CTPercentage value) { - return new JAXBElement(_CTSRgbColorGreenMod_QNAME, CTPercentage.class, CTSRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "sat", scope = CTSRgbColor.class) - public JAXBElement createCTSRgbColorSat(CTPercentage value) { - return new JAXBElement(_CTSRgbColorSat_QNAME, CTPercentage.class, CTSRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "blue", scope = CTSRgbColor.class) - public JAXBElement createCTSRgbColorBlue(CTPercentage value) { - return new JAXBElement(_CTSRgbColorBlue_QNAME, CTPercentage.class, CTSRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "red", scope = CTSRgbColor.class) - public JAXBElement createCTSRgbColorRed(CTPercentage value) { - return new JAXBElement(_CTSRgbColorRed_QNAME, CTPercentage.class, CTSRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "satMod", scope = CTSRgbColor.class) - public JAXBElement createCTSRgbColorSatMod(CTPercentage value) { - return new JAXBElement(_CTSRgbColorSatMod_QNAME, CTPercentage.class, CTSRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTAngle }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "hueOff", scope = CTSRgbColor.class) - public JAXBElement createCTSRgbColorHueOff(CTAngle value) { - return new JAXBElement(_CTSRgbColorHueOff_QNAME, CTAngle.class, CTSRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "blueMod", scope = CTSRgbColor.class) - public JAXBElement createCTSRgbColorBlueMod(CTPercentage value) { - return new JAXBElement(_CTSRgbColorBlueMod_QNAME, CTPercentage.class, CTSRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPositiveFixedPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "shade", scope = CTSRgbColor.class) - public JAXBElement createCTSRgbColorShade(CTPositiveFixedPercentage value) { - return new JAXBElement(_CTSRgbColorShade_QNAME, CTPositiveFixedPercentage.class, CTSRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "lumMod", scope = CTSRgbColor.class) - public JAXBElement createCTSRgbColorLumMod(CTPercentage value) { - return new JAXBElement(_CTSRgbColorLumMod_QNAME, CTPercentage.class, CTSRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTInverseTransform }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "inv", scope = CTSRgbColor.class) - public JAXBElement createCTSRgbColorInv(CTInverseTransform value) { - return new JAXBElement(_CTSRgbColorInv_QNAME, CTInverseTransform.class, CTSRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "lumOff", scope = CTSRgbColor.class) - public JAXBElement createCTSRgbColorLumOff(CTPercentage value) { - return new JAXBElement(_CTSRgbColorLumOff_QNAME, CTPercentage.class, CTSRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPositiveFixedPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "tint", scope = CTSRgbColor.class) - public JAXBElement createCTSRgbColorTint(CTPositiveFixedPercentage value) { - return new JAXBElement(_CTSRgbColorTint_QNAME, CTPositiveFixedPercentage.class, CTSRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "green", scope = CTSRgbColor.class) - public JAXBElement createCTSRgbColorGreen(CTPercentage value) { - return new JAXBElement(_CTSRgbColorGreen_QNAME, CTPercentage.class, CTSRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTComplementTransform }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "comp", scope = CTSRgbColor.class) - public JAXBElement createCTSRgbColorComp(CTComplementTransform value) { - return new JAXBElement(_CTSRgbColorComp_QNAME, CTComplementTransform.class, CTSRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "blueOff", scope = CTSRgbColor.class) - public JAXBElement createCTSRgbColorBlueOff(CTPercentage value) { - return new JAXBElement(_CTSRgbColorBlueOff_QNAME, CTPercentage.class, CTSRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPositivePercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "hueMod", scope = CTSRgbColor.class) - public JAXBElement createCTSRgbColorHueMod(CTPositivePercentage value) { - return new JAXBElement(_CTSRgbColorHueMod_QNAME, CTPositivePercentage.class, CTSRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTGrayscaleTransform }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "gray", scope = CTSRgbColor.class) - public JAXBElement createCTSRgbColorGray(CTGrayscaleTransform value) { - return new JAXBElement(_CTSRgbColorGray_QNAME, CTGrayscaleTransform.class, CTSRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "lum", scope = CTSystemColor.class) - public JAXBElement createCTSystemColorLum(CTPercentage value) { - return new JAXBElement(_CTSRgbColorLum_QNAME, CTPercentage.class, CTSystemColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPositiveFixedPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "alpha", scope = CTSystemColor.class) - public JAXBElement createCTSystemColorAlpha(CTPositiveFixedPercentage value) { - return new JAXBElement(_CTSRgbColorAlpha_QNAME, CTPositiveFixedPercentage.class, CTSystemColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTGammaTransform }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "gamma", scope = CTSystemColor.class) - public JAXBElement createCTSystemColorGamma(CTGammaTransform value) { - return new JAXBElement(_CTSRgbColorGamma_QNAME, CTGammaTransform.class, CTSystemColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTInverseGammaTransform }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "invGamma", scope = CTSystemColor.class) - public JAXBElement createCTSystemColorInvGamma(CTInverseGammaTransform value) { - return new JAXBElement(_CTSRgbColorInvGamma_QNAME, CTInverseGammaTransform.class, CTSystemColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPositivePercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "alphaMod", scope = CTSystemColor.class) - public JAXBElement createCTSystemColorAlphaMod(CTPositivePercentage value) { - return new JAXBElement(_CTSRgbColorAlphaMod_QNAME, CTPositivePercentage.class, CTSystemColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "redOff", scope = CTSystemColor.class) - public JAXBElement createCTSystemColorRedOff(CTPercentage value) { - return new JAXBElement(_CTSRgbColorRedOff_QNAME, CTPercentage.class, CTSystemColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTFixedPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "alphaOff", scope = CTSystemColor.class) - public JAXBElement createCTSystemColorAlphaOff(CTFixedPercentage value) { - return new JAXBElement(_CTSRgbColorAlphaOff_QNAME, CTFixedPercentage.class, CTSystemColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "greenOff", scope = CTSystemColor.class) - public JAXBElement createCTSystemColorGreenOff(CTPercentage value) { - return new JAXBElement(_CTSRgbColorGreenOff_QNAME, CTPercentage.class, CTSystemColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "redMod", scope = CTSystemColor.class) - public JAXBElement createCTSystemColorRedMod(CTPercentage value) { - return new JAXBElement(_CTSRgbColorRedMod_QNAME, CTPercentage.class, CTSystemColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPositiveFixedAngle }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "hue", scope = CTSystemColor.class) - public JAXBElement createCTSystemColorHue(CTPositiveFixedAngle value) { - return new JAXBElement(_CTSRgbColorHue_QNAME, CTPositiveFixedAngle.class, CTSystemColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "satOff", scope = CTSystemColor.class) - public JAXBElement createCTSystemColorSatOff(CTPercentage value) { - return new JAXBElement(_CTSRgbColorSatOff_QNAME, CTPercentage.class, CTSystemColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "greenMod", scope = CTSystemColor.class) - public JAXBElement createCTSystemColorGreenMod(CTPercentage value) { - return new JAXBElement(_CTSRgbColorGreenMod_QNAME, CTPercentage.class, CTSystemColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "blue", scope = CTSystemColor.class) - public JAXBElement createCTSystemColorBlue(CTPercentage value) { - return new JAXBElement(_CTSRgbColorBlue_QNAME, CTPercentage.class, CTSystemColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "sat", scope = CTSystemColor.class) - public JAXBElement createCTSystemColorSat(CTPercentage value) { - return new JAXBElement(_CTSRgbColorSat_QNAME, CTPercentage.class, CTSystemColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "red", scope = CTSystemColor.class) - public JAXBElement createCTSystemColorRed(CTPercentage value) { - return new JAXBElement(_CTSRgbColorRed_QNAME, CTPercentage.class, CTSystemColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "satMod", scope = CTSystemColor.class) - public JAXBElement createCTSystemColorSatMod(CTPercentage value) { - return new JAXBElement(_CTSRgbColorSatMod_QNAME, CTPercentage.class, CTSystemColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "blueMod", scope = CTSystemColor.class) - public JAXBElement createCTSystemColorBlueMod(CTPercentage value) { - return new JAXBElement(_CTSRgbColorBlueMod_QNAME, CTPercentage.class, CTSystemColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTAngle }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "hueOff", scope = CTSystemColor.class) - public JAXBElement createCTSystemColorHueOff(CTAngle value) { - return new JAXBElement(_CTSRgbColorHueOff_QNAME, CTAngle.class, CTSystemColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPositiveFixedPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "shade", scope = CTSystemColor.class) - public JAXBElement createCTSystemColorShade(CTPositiveFixedPercentage value) { - return new JAXBElement(_CTSRgbColorShade_QNAME, CTPositiveFixedPercentage.class, CTSystemColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "lumMod", scope = CTSystemColor.class) - public JAXBElement createCTSystemColorLumMod(CTPercentage value) { - return new JAXBElement(_CTSRgbColorLumMod_QNAME, CTPercentage.class, CTSystemColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTInverseTransform }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "inv", scope = CTSystemColor.class) - public JAXBElement createCTSystemColorInv(CTInverseTransform value) { - return new JAXBElement(_CTSRgbColorInv_QNAME, CTInverseTransform.class, CTSystemColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "lumOff", scope = CTSystemColor.class) - public JAXBElement createCTSystemColorLumOff(CTPercentage value) { - return new JAXBElement(_CTSRgbColorLumOff_QNAME, CTPercentage.class, CTSystemColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPositiveFixedPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "tint", scope = CTSystemColor.class) - public JAXBElement createCTSystemColorTint(CTPositiveFixedPercentage value) { - return new JAXBElement(_CTSRgbColorTint_QNAME, CTPositiveFixedPercentage.class, CTSystemColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "green", scope = CTSystemColor.class) - public JAXBElement createCTSystemColorGreen(CTPercentage value) { - return new JAXBElement(_CTSRgbColorGreen_QNAME, CTPercentage.class, CTSystemColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTComplementTransform }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "comp", scope = CTSystemColor.class) - public JAXBElement createCTSystemColorComp(CTComplementTransform value) { - return new JAXBElement(_CTSRgbColorComp_QNAME, CTComplementTransform.class, CTSystemColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "blueOff", scope = CTSystemColor.class) - public JAXBElement createCTSystemColorBlueOff(CTPercentage value) { - return new JAXBElement(_CTSRgbColorBlueOff_QNAME, CTPercentage.class, CTSystemColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPositivePercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "hueMod", scope = CTSystemColor.class) - public JAXBElement createCTSystemColorHueMod(CTPositivePercentage value) { - return new JAXBElement(_CTSRgbColorHueMod_QNAME, CTPositivePercentage.class, CTSystemColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTGrayscaleTransform }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "gray", scope = CTSystemColor.class) - public JAXBElement createCTSystemColorGray(CTGrayscaleTransform value) { - return new JAXBElement(_CTSRgbColorGray_QNAME, CTGrayscaleTransform.class, CTSystemColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "lum", scope = CTSchemeColor.class) - public JAXBElement createCTSchemeColorLum(CTPercentage value) { - return new JAXBElement(_CTSRgbColorLum_QNAME, CTPercentage.class, CTSchemeColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPositiveFixedPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "alpha", scope = CTSchemeColor.class) - public JAXBElement createCTSchemeColorAlpha(CTPositiveFixedPercentage value) { - return new JAXBElement(_CTSRgbColorAlpha_QNAME, CTPositiveFixedPercentage.class, CTSchemeColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTGammaTransform }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "gamma", scope = CTSchemeColor.class) - public JAXBElement createCTSchemeColorGamma(CTGammaTransform value) { - return new JAXBElement(_CTSRgbColorGamma_QNAME, CTGammaTransform.class, CTSchemeColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTInverseGammaTransform }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "invGamma", scope = CTSchemeColor.class) - public JAXBElement createCTSchemeColorInvGamma(CTInverseGammaTransform value) { - return new JAXBElement(_CTSRgbColorInvGamma_QNAME, CTInverseGammaTransform.class, CTSchemeColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "redOff", scope = CTSchemeColor.class) - public JAXBElement createCTSchemeColorRedOff(CTPercentage value) { - return new JAXBElement(_CTSRgbColorRedOff_QNAME, CTPercentage.class, CTSchemeColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPositivePercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "alphaMod", scope = CTSchemeColor.class) - public JAXBElement createCTSchemeColorAlphaMod(CTPositivePercentage value) { - return new JAXBElement(_CTSRgbColorAlphaMod_QNAME, CTPositivePercentage.class, CTSchemeColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTFixedPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "alphaOff", scope = CTSchemeColor.class) - public JAXBElement createCTSchemeColorAlphaOff(CTFixedPercentage value) { - return new JAXBElement(_CTSRgbColorAlphaOff_QNAME, CTFixedPercentage.class, CTSchemeColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "greenOff", scope = CTSchemeColor.class) - public JAXBElement createCTSchemeColorGreenOff(CTPercentage value) { - return new JAXBElement(_CTSRgbColorGreenOff_QNAME, CTPercentage.class, CTSchemeColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPositiveFixedAngle }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "hue", scope = CTSchemeColor.class) - public JAXBElement createCTSchemeColorHue(CTPositiveFixedAngle value) { - return new JAXBElement(_CTSRgbColorHue_QNAME, CTPositiveFixedAngle.class, CTSchemeColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "redMod", scope = CTSchemeColor.class) - public JAXBElement createCTSchemeColorRedMod(CTPercentage value) { - return new JAXBElement(_CTSRgbColorRedMod_QNAME, CTPercentage.class, CTSchemeColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "satOff", scope = CTSchemeColor.class) - public JAXBElement createCTSchemeColorSatOff(CTPercentage value) { - return new JAXBElement(_CTSRgbColorSatOff_QNAME, CTPercentage.class, CTSchemeColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "greenMod", scope = CTSchemeColor.class) - public JAXBElement createCTSchemeColorGreenMod(CTPercentage value) { - return new JAXBElement(_CTSRgbColorGreenMod_QNAME, CTPercentage.class, CTSchemeColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "blue", scope = CTSchemeColor.class) - public JAXBElement createCTSchemeColorBlue(CTPercentage value) { - return new JAXBElement(_CTSRgbColorBlue_QNAME, CTPercentage.class, CTSchemeColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "sat", scope = CTSchemeColor.class) - public JAXBElement createCTSchemeColorSat(CTPercentage value) { - return new JAXBElement(_CTSRgbColorSat_QNAME, CTPercentage.class, CTSchemeColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "red", scope = CTSchemeColor.class) - public JAXBElement createCTSchemeColorRed(CTPercentage value) { - return new JAXBElement(_CTSRgbColorRed_QNAME, CTPercentage.class, CTSchemeColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "satMod", scope = CTSchemeColor.class) - public JAXBElement createCTSchemeColorSatMod(CTPercentage value) { - return new JAXBElement(_CTSRgbColorSatMod_QNAME, CTPercentage.class, CTSchemeColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTAngle }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "hueOff", scope = CTSchemeColor.class) - public JAXBElement createCTSchemeColorHueOff(CTAngle value) { - return new JAXBElement(_CTSRgbColorHueOff_QNAME, CTAngle.class, CTSchemeColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "blueMod", scope = CTSchemeColor.class) - public JAXBElement createCTSchemeColorBlueMod(CTPercentage value) { - return new JAXBElement(_CTSRgbColorBlueMod_QNAME, CTPercentage.class, CTSchemeColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPositiveFixedPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "shade", scope = CTSchemeColor.class) - public JAXBElement createCTSchemeColorShade(CTPositiveFixedPercentage value) { - return new JAXBElement(_CTSRgbColorShade_QNAME, CTPositiveFixedPercentage.class, CTSchemeColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "lumMod", scope = CTSchemeColor.class) - public JAXBElement createCTSchemeColorLumMod(CTPercentage value) { - return new JAXBElement(_CTSRgbColorLumMod_QNAME, CTPercentage.class, CTSchemeColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTInverseTransform }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "inv", scope = CTSchemeColor.class) - public JAXBElement createCTSchemeColorInv(CTInverseTransform value) { - return new JAXBElement(_CTSRgbColorInv_QNAME, CTInverseTransform.class, CTSchemeColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "lumOff", scope = CTSchemeColor.class) - public JAXBElement createCTSchemeColorLumOff(CTPercentage value) { - return new JAXBElement(_CTSRgbColorLumOff_QNAME, CTPercentage.class, CTSchemeColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPositiveFixedPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "tint", scope = CTSchemeColor.class) - public JAXBElement createCTSchemeColorTint(CTPositiveFixedPercentage value) { - return new JAXBElement(_CTSRgbColorTint_QNAME, CTPositiveFixedPercentage.class, CTSchemeColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "green", scope = CTSchemeColor.class) - public JAXBElement createCTSchemeColorGreen(CTPercentage value) { - return new JAXBElement(_CTSRgbColorGreen_QNAME, CTPercentage.class, CTSchemeColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTComplementTransform }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "comp", scope = CTSchemeColor.class) - public JAXBElement createCTSchemeColorComp(CTComplementTransform value) { - return new JAXBElement(_CTSRgbColorComp_QNAME, CTComplementTransform.class, CTSchemeColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "blueOff", scope = CTSchemeColor.class) - public JAXBElement createCTSchemeColorBlueOff(CTPercentage value) { - return new JAXBElement(_CTSRgbColorBlueOff_QNAME, CTPercentage.class, CTSchemeColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPositivePercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "hueMod", scope = CTSchemeColor.class) - public JAXBElement createCTSchemeColorHueMod(CTPositivePercentage value) { - return new JAXBElement(_CTSRgbColorHueMod_QNAME, CTPositivePercentage.class, CTSchemeColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTGrayscaleTransform }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "gray", scope = CTSchemeColor.class) - public JAXBElement createCTSchemeColorGray(CTGrayscaleTransform value) { - return new JAXBElement(_CTSRgbColorGray_QNAME, CTGrayscaleTransform.class, CTSchemeColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "lum", scope = CTScRgbColor.class) - public JAXBElement createCTScRgbColorLum(CTPercentage value) { - return new JAXBElement(_CTSRgbColorLum_QNAME, CTPercentage.class, CTScRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPositiveFixedPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "alpha", scope = CTScRgbColor.class) - public JAXBElement createCTScRgbColorAlpha(CTPositiveFixedPercentage value) { - return new JAXBElement(_CTSRgbColorAlpha_QNAME, CTPositiveFixedPercentage.class, CTScRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTGammaTransform }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "gamma", scope = CTScRgbColor.class) - public JAXBElement createCTScRgbColorGamma(CTGammaTransform value) { - return new JAXBElement(_CTSRgbColorGamma_QNAME, CTGammaTransform.class, CTScRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTInverseGammaTransform }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "invGamma", scope = CTScRgbColor.class) - public JAXBElement createCTScRgbColorInvGamma(CTInverseGammaTransform value) { - return new JAXBElement(_CTSRgbColorInvGamma_QNAME, CTInverseGammaTransform.class, CTScRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "redOff", scope = CTScRgbColor.class) - public JAXBElement createCTScRgbColorRedOff(CTPercentage value) { - return new JAXBElement(_CTSRgbColorRedOff_QNAME, CTPercentage.class, CTScRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPositivePercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "alphaMod", scope = CTScRgbColor.class) - public JAXBElement createCTScRgbColorAlphaMod(CTPositivePercentage value) { - return new JAXBElement(_CTSRgbColorAlphaMod_QNAME, CTPositivePercentage.class, CTScRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTFixedPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "alphaOff", scope = CTScRgbColor.class) - public JAXBElement createCTScRgbColorAlphaOff(CTFixedPercentage value) { - return new JAXBElement(_CTSRgbColorAlphaOff_QNAME, CTFixedPercentage.class, CTScRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "greenOff", scope = CTScRgbColor.class) - public JAXBElement createCTScRgbColorGreenOff(CTPercentage value) { - return new JAXBElement(_CTSRgbColorGreenOff_QNAME, CTPercentage.class, CTScRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPositiveFixedAngle }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "hue", scope = CTScRgbColor.class) - public JAXBElement createCTScRgbColorHue(CTPositiveFixedAngle value) { - return new JAXBElement(_CTSRgbColorHue_QNAME, CTPositiveFixedAngle.class, CTScRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "redMod", scope = CTScRgbColor.class) - public JAXBElement createCTScRgbColorRedMod(CTPercentage value) { - return new JAXBElement(_CTSRgbColorRedMod_QNAME, CTPercentage.class, CTScRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "satOff", scope = CTScRgbColor.class) - public JAXBElement createCTScRgbColorSatOff(CTPercentage value) { - return new JAXBElement(_CTSRgbColorSatOff_QNAME, CTPercentage.class, CTScRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "greenMod", scope = CTScRgbColor.class) - public JAXBElement createCTScRgbColorGreenMod(CTPercentage value) { - return new JAXBElement(_CTSRgbColorGreenMod_QNAME, CTPercentage.class, CTScRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "sat", scope = CTScRgbColor.class) - public JAXBElement createCTScRgbColorSat(CTPercentage value) { - return new JAXBElement(_CTSRgbColorSat_QNAME, CTPercentage.class, CTScRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "blue", scope = CTScRgbColor.class) - public JAXBElement createCTScRgbColorBlue(CTPercentage value) { - return new JAXBElement(_CTSRgbColorBlue_QNAME, CTPercentage.class, CTScRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "red", scope = CTScRgbColor.class) - public JAXBElement createCTScRgbColorRed(CTPercentage value) { - return new JAXBElement(_CTSRgbColorRed_QNAME, CTPercentage.class, CTScRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "satMod", scope = CTScRgbColor.class) - public JAXBElement createCTScRgbColorSatMod(CTPercentage value) { - return new JAXBElement(_CTSRgbColorSatMod_QNAME, CTPercentage.class, CTScRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTAngle }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "hueOff", scope = CTScRgbColor.class) - public JAXBElement createCTScRgbColorHueOff(CTAngle value) { - return new JAXBElement(_CTSRgbColorHueOff_QNAME, CTAngle.class, CTScRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "blueMod", scope = CTScRgbColor.class) - public JAXBElement createCTScRgbColorBlueMod(CTPercentage value) { - return new JAXBElement(_CTSRgbColorBlueMod_QNAME, CTPercentage.class, CTScRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPositiveFixedPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "shade", scope = CTScRgbColor.class) - public JAXBElement createCTScRgbColorShade(CTPositiveFixedPercentage value) { - return new JAXBElement(_CTSRgbColorShade_QNAME, CTPositiveFixedPercentage.class, CTScRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "lumMod", scope = CTScRgbColor.class) - public JAXBElement createCTScRgbColorLumMod(CTPercentage value) { - return new JAXBElement(_CTSRgbColorLumMod_QNAME, CTPercentage.class, CTScRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTInverseTransform }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "inv", scope = CTScRgbColor.class) - public JAXBElement createCTScRgbColorInv(CTInverseTransform value) { - return new JAXBElement(_CTSRgbColorInv_QNAME, CTInverseTransform.class, CTScRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "lumOff", scope = CTScRgbColor.class) - public JAXBElement createCTScRgbColorLumOff(CTPercentage value) { - return new JAXBElement(_CTSRgbColorLumOff_QNAME, CTPercentage.class, CTScRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPositiveFixedPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "tint", scope = CTScRgbColor.class) - public JAXBElement createCTScRgbColorTint(CTPositiveFixedPercentage value) { - return new JAXBElement(_CTSRgbColorTint_QNAME, CTPositiveFixedPercentage.class, CTScRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "green", scope = CTScRgbColor.class) - public JAXBElement createCTScRgbColorGreen(CTPercentage value) { - return new JAXBElement(_CTSRgbColorGreen_QNAME, CTPercentage.class, CTScRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTComplementTransform }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "comp", scope = CTScRgbColor.class) - public JAXBElement createCTScRgbColorComp(CTComplementTransform value) { - return new JAXBElement(_CTSRgbColorComp_QNAME, CTComplementTransform.class, CTScRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "blueOff", scope = CTScRgbColor.class) - public JAXBElement createCTScRgbColorBlueOff(CTPercentage value) { - return new JAXBElement(_CTSRgbColorBlueOff_QNAME, CTPercentage.class, CTScRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPositivePercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "hueMod", scope = CTScRgbColor.class) - public JAXBElement createCTScRgbColorHueMod(CTPositivePercentage value) { - return new JAXBElement(_CTSRgbColorHueMod_QNAME, CTPositivePercentage.class, CTScRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTGrayscaleTransform }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "gray", scope = CTScRgbColor.class) - public JAXBElement createCTScRgbColorGray(CTGrayscaleTransform value) { - return new JAXBElement(_CTSRgbColorGray_QNAME, CTGrayscaleTransform.class, CTScRgbColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPositiveFixedPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "alpha", scope = CTHslColor.class) - public JAXBElement createCTHslColorAlpha(CTPositiveFixedPercentage value) { - return new JAXBElement(_CTSRgbColorAlpha_QNAME, CTPositiveFixedPercentage.class, CTHslColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "lum", scope = CTHslColor.class) - public JAXBElement createCTHslColorLum(CTPercentage value) { - return new JAXBElement(_CTSRgbColorLum_QNAME, CTPercentage.class, CTHslColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTGammaTransform }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "gamma", scope = CTHslColor.class) - public JAXBElement createCTHslColorGamma(CTGammaTransform value) { - return new JAXBElement(_CTSRgbColorGamma_QNAME, CTGammaTransform.class, CTHslColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTInverseGammaTransform }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "invGamma", scope = CTHslColor.class) - public JAXBElement createCTHslColorInvGamma(CTInverseGammaTransform value) { - return new JAXBElement(_CTSRgbColorInvGamma_QNAME, CTInverseGammaTransform.class, CTHslColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPositivePercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "alphaMod", scope = CTHslColor.class) - public JAXBElement createCTHslColorAlphaMod(CTPositivePercentage value) { - return new JAXBElement(_CTSRgbColorAlphaMod_QNAME, CTPositivePercentage.class, CTHslColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "redOff", scope = CTHslColor.class) - public JAXBElement createCTHslColorRedOff(CTPercentage value) { - return new JAXBElement(_CTSRgbColorRedOff_QNAME, CTPercentage.class, CTHslColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTFixedPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "alphaOff", scope = CTHslColor.class) - public JAXBElement createCTHslColorAlphaOff(CTFixedPercentage value) { - return new JAXBElement(_CTSRgbColorAlphaOff_QNAME, CTFixedPercentage.class, CTHslColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "greenOff", scope = CTHslColor.class) - public JAXBElement createCTHslColorGreenOff(CTPercentage value) { - return new JAXBElement(_CTSRgbColorGreenOff_QNAME, CTPercentage.class, CTHslColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPositiveFixedAngle }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "hue", scope = CTHslColor.class) - public JAXBElement createCTHslColorHue(CTPositiveFixedAngle value) { - return new JAXBElement(_CTSRgbColorHue_QNAME, CTPositiveFixedAngle.class, CTHslColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "redMod", scope = CTHslColor.class) - public JAXBElement createCTHslColorRedMod(CTPercentage value) { - return new JAXBElement(_CTSRgbColorRedMod_QNAME, CTPercentage.class, CTHslColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "satOff", scope = CTHslColor.class) - public JAXBElement createCTHslColorSatOff(CTPercentage value) { - return new JAXBElement(_CTSRgbColorSatOff_QNAME, CTPercentage.class, CTHslColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "greenMod", scope = CTHslColor.class) - public JAXBElement createCTHslColorGreenMod(CTPercentage value) { - return new JAXBElement(_CTSRgbColorGreenMod_QNAME, CTPercentage.class, CTHslColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "blue", scope = CTHslColor.class) - public JAXBElement createCTHslColorBlue(CTPercentage value) { - return new JAXBElement(_CTSRgbColorBlue_QNAME, CTPercentage.class, CTHslColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "sat", scope = CTHslColor.class) - public JAXBElement createCTHslColorSat(CTPercentage value) { - return new JAXBElement(_CTSRgbColorSat_QNAME, CTPercentage.class, CTHslColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "red", scope = CTHslColor.class) - public JAXBElement createCTHslColorRed(CTPercentage value) { - return new JAXBElement(_CTSRgbColorRed_QNAME, CTPercentage.class, CTHslColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "satMod", scope = CTHslColor.class) - public JAXBElement createCTHslColorSatMod(CTPercentage value) { - return new JAXBElement(_CTSRgbColorSatMod_QNAME, CTPercentage.class, CTHslColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "blueMod", scope = CTHslColor.class) - public JAXBElement createCTHslColorBlueMod(CTPercentage value) { - return new JAXBElement(_CTSRgbColorBlueMod_QNAME, CTPercentage.class, CTHslColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTAngle }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "hueOff", scope = CTHslColor.class) - public JAXBElement createCTHslColorHueOff(CTAngle value) { - return new JAXBElement(_CTSRgbColorHueOff_QNAME, CTAngle.class, CTHslColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPositiveFixedPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "shade", scope = CTHslColor.class) - public JAXBElement createCTHslColorShade(CTPositiveFixedPercentage value) { - return new JAXBElement(_CTSRgbColorShade_QNAME, CTPositiveFixedPercentage.class, CTHslColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "lumMod", scope = CTHslColor.class) - public JAXBElement createCTHslColorLumMod(CTPercentage value) { - return new JAXBElement(_CTSRgbColorLumMod_QNAME, CTPercentage.class, CTHslColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTInverseTransform }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "inv", scope = CTHslColor.class) - public JAXBElement createCTHslColorInv(CTInverseTransform value) { - return new JAXBElement(_CTSRgbColorInv_QNAME, CTInverseTransform.class, CTHslColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "lumOff", scope = CTHslColor.class) - public JAXBElement createCTHslColorLumOff(CTPercentage value) { - return new JAXBElement(_CTSRgbColorLumOff_QNAME, CTPercentage.class, CTHslColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPositiveFixedPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "tint", scope = CTHslColor.class) - public JAXBElement createCTHslColorTint(CTPositiveFixedPercentage value) { - return new JAXBElement(_CTSRgbColorTint_QNAME, CTPositiveFixedPercentage.class, CTHslColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "green", scope = CTHslColor.class) - public JAXBElement createCTHslColorGreen(CTPercentage value) { - return new JAXBElement(_CTSRgbColorGreen_QNAME, CTPercentage.class, CTHslColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTComplementTransform }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "comp", scope = CTHslColor.class) - public JAXBElement createCTHslColorComp(CTComplementTransform value) { - return new JAXBElement(_CTSRgbColorComp_QNAME, CTComplementTransform.class, CTHslColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "blueOff", scope = CTHslColor.class) - public JAXBElement createCTHslColorBlueOff(CTPercentage value) { - return new JAXBElement(_CTSRgbColorBlueOff_QNAME, CTPercentage.class, CTHslColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPositivePercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "hueMod", scope = CTHslColor.class) - public JAXBElement createCTHslColorHueMod(CTPositivePercentage value) { - return new JAXBElement(_CTSRgbColorHueMod_QNAME, CTPositivePercentage.class, CTHslColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTGrayscaleTransform }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "gray", scope = CTHslColor.class) - public JAXBElement createCTHslColorGray(CTGrayscaleTransform value) { - return new JAXBElement(_CTSRgbColorGray_QNAME, CTGrayscaleTransform.class, CTHslColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "lum", scope = CTPresetColor.class) - public JAXBElement createCTPresetColorLum(CTPercentage value) { - return new JAXBElement(_CTSRgbColorLum_QNAME, CTPercentage.class, CTPresetColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPositiveFixedPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "alpha", scope = CTPresetColor.class) - public JAXBElement createCTPresetColorAlpha(CTPositiveFixedPercentage value) { - return new JAXBElement(_CTSRgbColorAlpha_QNAME, CTPositiveFixedPercentage.class, CTPresetColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTGammaTransform }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "gamma", scope = CTPresetColor.class) - public JAXBElement createCTPresetColorGamma(CTGammaTransform value) { - return new JAXBElement(_CTSRgbColorGamma_QNAME, CTGammaTransform.class, CTPresetColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTInverseGammaTransform }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "invGamma", scope = CTPresetColor.class) - public JAXBElement createCTPresetColorInvGamma(CTInverseGammaTransform value) { - return new JAXBElement(_CTSRgbColorInvGamma_QNAME, CTInverseGammaTransform.class, CTPresetColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "redOff", scope = CTPresetColor.class) - public JAXBElement createCTPresetColorRedOff(CTPercentage value) { - return new JAXBElement(_CTSRgbColorRedOff_QNAME, CTPercentage.class, CTPresetColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPositivePercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "alphaMod", scope = CTPresetColor.class) - public JAXBElement createCTPresetColorAlphaMod(CTPositivePercentage value) { - return new JAXBElement(_CTSRgbColorAlphaMod_QNAME, CTPositivePercentage.class, CTPresetColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTFixedPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "alphaOff", scope = CTPresetColor.class) - public JAXBElement createCTPresetColorAlphaOff(CTFixedPercentage value) { - return new JAXBElement(_CTSRgbColorAlphaOff_QNAME, CTFixedPercentage.class, CTPresetColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "greenOff", scope = CTPresetColor.class) - public JAXBElement createCTPresetColorGreenOff(CTPercentage value) { - return new JAXBElement(_CTSRgbColorGreenOff_QNAME, CTPercentage.class, CTPresetColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPositiveFixedAngle }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "hue", scope = CTPresetColor.class) - public JAXBElement createCTPresetColorHue(CTPositiveFixedAngle value) { - return new JAXBElement(_CTSRgbColorHue_QNAME, CTPositiveFixedAngle.class, CTPresetColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "redMod", scope = CTPresetColor.class) - public JAXBElement createCTPresetColorRedMod(CTPercentage value) { - return new JAXBElement(_CTSRgbColorRedMod_QNAME, CTPercentage.class, CTPresetColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "satOff", scope = CTPresetColor.class) - public JAXBElement createCTPresetColorSatOff(CTPercentage value) { - return new JAXBElement(_CTSRgbColorSatOff_QNAME, CTPercentage.class, CTPresetColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "greenMod", scope = CTPresetColor.class) - public JAXBElement createCTPresetColorGreenMod(CTPercentage value) { - return new JAXBElement(_CTSRgbColorGreenMod_QNAME, CTPercentage.class, CTPresetColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "blue", scope = CTPresetColor.class) - public JAXBElement createCTPresetColorBlue(CTPercentage value) { - return new JAXBElement(_CTSRgbColorBlue_QNAME, CTPercentage.class, CTPresetColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "sat", scope = CTPresetColor.class) - public JAXBElement createCTPresetColorSat(CTPercentage value) { - return new JAXBElement(_CTSRgbColorSat_QNAME, CTPercentage.class, CTPresetColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "red", scope = CTPresetColor.class) - public JAXBElement createCTPresetColorRed(CTPercentage value) { - return new JAXBElement(_CTSRgbColorRed_QNAME, CTPercentage.class, CTPresetColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "satMod", scope = CTPresetColor.class) - public JAXBElement createCTPresetColorSatMod(CTPercentage value) { - return new JAXBElement(_CTSRgbColorSatMod_QNAME, CTPercentage.class, CTPresetColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "blueMod", scope = CTPresetColor.class) - public JAXBElement createCTPresetColorBlueMod(CTPercentage value) { - return new JAXBElement(_CTSRgbColorBlueMod_QNAME, CTPercentage.class, CTPresetColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTAngle }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "hueOff", scope = CTPresetColor.class) - public JAXBElement createCTPresetColorHueOff(CTAngle value) { - return new JAXBElement(_CTSRgbColorHueOff_QNAME, CTAngle.class, CTPresetColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPositiveFixedPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "shade", scope = CTPresetColor.class) - public JAXBElement createCTPresetColorShade(CTPositiveFixedPercentage value) { - return new JAXBElement(_CTSRgbColorShade_QNAME, CTPositiveFixedPercentage.class, CTPresetColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "lumMod", scope = CTPresetColor.class) - public JAXBElement createCTPresetColorLumMod(CTPercentage value) { - return new JAXBElement(_CTSRgbColorLumMod_QNAME, CTPercentage.class, CTPresetColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTInverseTransform }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "inv", scope = CTPresetColor.class) - public JAXBElement createCTPresetColorInv(CTInverseTransform value) { - return new JAXBElement(_CTSRgbColorInv_QNAME, CTInverseTransform.class, CTPresetColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "lumOff", scope = CTPresetColor.class) - public JAXBElement createCTPresetColorLumOff(CTPercentage value) { - return new JAXBElement(_CTSRgbColorLumOff_QNAME, CTPercentage.class, CTPresetColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPositiveFixedPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "tint", scope = CTPresetColor.class) - public JAXBElement createCTPresetColorTint(CTPositiveFixedPercentage value) { - return new JAXBElement(_CTSRgbColorTint_QNAME, CTPositiveFixedPercentage.class, CTPresetColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "green", scope = CTPresetColor.class) - public JAXBElement createCTPresetColorGreen(CTPercentage value) { - return new JAXBElement(_CTSRgbColorGreen_QNAME, CTPercentage.class, CTPresetColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTComplementTransform }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "comp", scope = CTPresetColor.class) - public JAXBElement createCTPresetColorComp(CTComplementTransform value) { - return new JAXBElement(_CTSRgbColorComp_QNAME, CTComplementTransform.class, CTPresetColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "blueOff", scope = CTPresetColor.class) - public JAXBElement createCTPresetColorBlueOff(CTPercentage value) { - return new JAXBElement(_CTSRgbColorBlueOff_QNAME, CTPercentage.class, CTPresetColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTPositivePercentage }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "hueMod", scope = CTPresetColor.class) - public JAXBElement createCTPresetColorHueMod(CTPositivePercentage value) { - return new JAXBElement(_CTSRgbColorHueMod_QNAME, CTPositivePercentage.class, CTPresetColor.class, value); - } - - /** - * Create an instance of {@link JAXBElement }{@code <}{@link CTGrayscaleTransform }{@code >}} - * - */ - @XmlElementDecl(namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", name = "gray", scope = CTPresetColor.class) - public JAXBElement createCTPresetColorGray(CTGrayscaleTransform value) { - return new JAXBElement(_CTSRgbColorGray_QNAME, CTGrayscaleTransform.class, CTPresetColor.class, value); - } - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/STBlackWhiteMode.java b/src/java/org/apache/poi/sl/draw/binding/STBlackWhiteMode.java deleted file mode 100644 index 033fe442f..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/STBlackWhiteMode.java +++ /dev/null @@ -1,149 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import javax.xml.bind.annotation.XmlEnum; -import javax.xml.bind.annotation.XmlEnumValue; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for ST_BlackWhiteMode. - * - *

    The following schema fragment specifies the expected content contained within this class. - *

    - *

    - * <simpleType name="ST_BlackWhiteMode">
    - *   <restriction base="{http://www.w3.org/2001/XMLSchema}token">
    - *     <enumeration value="clr"/>
    - *     <enumeration value="auto"/>
    - *     <enumeration value="gray"/>
    - *     <enumeration value="ltGray"/>
    - *     <enumeration value="invGray"/>
    - *     <enumeration value="grayWhite"/>
    - *     <enumeration value="blackGray"/>
    - *     <enumeration value="blackWhite"/>
    - *     <enumeration value="black"/>
    - *     <enumeration value="white"/>
    - *     <enumeration value="hidden"/>
    - *   </restriction>
    - * </simpleType>
    - * 
    - * - */ -@XmlType(name = "ST_BlackWhiteMode", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") -@XmlEnum -public enum STBlackWhiteMode { - - - /** - * Color - * - */ - @XmlEnumValue("clr") - CLR("clr"), - - /** - * Automatic - * - */ - @XmlEnumValue("auto") - AUTO("auto"), - - /** - * Gray - * - */ - @XmlEnumValue("gray") - GRAY("gray"), - - /** - * Light Gray - * - */ - @XmlEnumValue("ltGray") - LT_GRAY("ltGray"), - - /** - * Inverse Gray - * - */ - @XmlEnumValue("invGray") - INV_GRAY("invGray"), - - /** - * Gray and White - * - */ - @XmlEnumValue("grayWhite") - GRAY_WHITE("grayWhite"), - - /** - * Black and Gray - * - */ - @XmlEnumValue("blackGray") - BLACK_GRAY("blackGray"), - - /** - * Black and White - * - */ - @XmlEnumValue("blackWhite") - BLACK_WHITE("blackWhite"), - - /** - * Black - * - */ - @XmlEnumValue("black") - BLACK("black"), - - /** - * White - * - */ - @XmlEnumValue("white") - WHITE("white"), - - /** - * Hidden - * - */ - @XmlEnumValue("hidden") - HIDDEN("hidden"); - private final String value; - - STBlackWhiteMode(String v) { - value = v; - } - - public String value() { - return value; - } - - public static STBlackWhiteMode fromValue(String v) { - for (STBlackWhiteMode c: STBlackWhiteMode.values()) { - if (c.value.equals(v)) { - return c; - } - } - throw new IllegalArgumentException(v); - } - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/STPathFillMode.java b/src/java/org/apache/poi/sl/draw/binding/STPathFillMode.java deleted file mode 100644 index ad610f197..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/STPathFillMode.java +++ /dev/null @@ -1,109 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import javax.xml.bind.annotation.XmlEnum; -import javax.xml.bind.annotation.XmlEnumValue; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for ST_PathFillMode. - * - *

    The following schema fragment specifies the expected content contained within this class. - *

    - *

    - * <simpleType name="ST_PathFillMode">
    - *   <restriction base="{http://www.w3.org/2001/XMLSchema}token">
    - *     <enumeration value="none"/>
    - *     <enumeration value="norm"/>
    - *     <enumeration value="lighten"/>
    - *     <enumeration value="lightenLess"/>
    - *     <enumeration value="darken"/>
    - *     <enumeration value="darkenLess"/>
    - *   </restriction>
    - * </simpleType>
    - * 
    - * - */ -@XmlType(name = "ST_PathFillMode", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") -@XmlEnum -public enum STPathFillMode { - - - /** - * No Path Fill - * - */ - @XmlEnumValue("none") - NONE("none"), - - /** - * Normal Path Fill - * - */ - @XmlEnumValue("norm") - NORM("norm"), - - /** - * Lighten Path Fill - * - */ - @XmlEnumValue("lighten") - LIGHTEN("lighten"), - - /** - * Lighten Path Fill Less - * - */ - @XmlEnumValue("lightenLess") - LIGHTEN_LESS("lightenLess"), - - /** - * Darken Path Fill - * - */ - @XmlEnumValue("darken") - DARKEN("darken"), - - /** - * Darken Path Fill Less - * - */ - @XmlEnumValue("darkenLess") - DARKEN_LESS("darkenLess"); - private final String value; - - STPathFillMode(String v) { - value = v; - } - - public String value() { - return value; - } - - public static STPathFillMode fromValue(String v) { - for (STPathFillMode c: STPathFillMode.values()) { - if (c.value.equals(v)) { - return c; - } - } - throw new IllegalArgumentException(v); - } - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/STPresetColorVal.java b/src/java/org/apache/poi/sl/draw/binding/STPresetColorVal.java deleted file mode 100644 index c4b3f84dd..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/STPresetColorVal.java +++ /dev/null @@ -1,1181 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import javax.xml.bind.annotation.XmlEnum; -import javax.xml.bind.annotation.XmlEnumValue; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for ST_PresetColorVal. - * - *

    The following schema fragment specifies the expected content contained within this class. - *

    - *

    - * <simpleType name="ST_PresetColorVal">
    - *   <restriction base="{http://www.w3.org/2001/XMLSchema}token">
    - *     <enumeration value="aliceBlue"/>
    - *     <enumeration value="antiqueWhite"/>
    - *     <enumeration value="aqua"/>
    - *     <enumeration value="aquamarine"/>
    - *     <enumeration value="azure"/>
    - *     <enumeration value="beige"/>
    - *     <enumeration value="bisque"/>
    - *     <enumeration value="black"/>
    - *     <enumeration value="blanchedAlmond"/>
    - *     <enumeration value="blue"/>
    - *     <enumeration value="blueViolet"/>
    - *     <enumeration value="brown"/>
    - *     <enumeration value="burlyWood"/>
    - *     <enumeration value="cadetBlue"/>
    - *     <enumeration value="chartreuse"/>
    - *     <enumeration value="chocolate"/>
    - *     <enumeration value="coral"/>
    - *     <enumeration value="cornflowerBlue"/>
    - *     <enumeration value="cornsilk"/>
    - *     <enumeration value="crimson"/>
    - *     <enumeration value="cyan"/>
    - *     <enumeration value="dkBlue"/>
    - *     <enumeration value="dkCyan"/>
    - *     <enumeration value="dkGoldenrod"/>
    - *     <enumeration value="dkGray"/>
    - *     <enumeration value="dkGreen"/>
    - *     <enumeration value="dkKhaki"/>
    - *     <enumeration value="dkMagenta"/>
    - *     <enumeration value="dkOliveGreen"/>
    - *     <enumeration value="dkOrange"/>
    - *     <enumeration value="dkOrchid"/>
    - *     <enumeration value="dkRed"/>
    - *     <enumeration value="dkSalmon"/>
    - *     <enumeration value="dkSeaGreen"/>
    - *     <enumeration value="dkSlateBlue"/>
    - *     <enumeration value="dkSlateGray"/>
    - *     <enumeration value="dkTurquoise"/>
    - *     <enumeration value="dkViolet"/>
    - *     <enumeration value="deepPink"/>
    - *     <enumeration value="deepSkyBlue"/>
    - *     <enumeration value="dimGray"/>
    - *     <enumeration value="dodgerBlue"/>
    - *     <enumeration value="firebrick"/>
    - *     <enumeration value="floralWhite"/>
    - *     <enumeration value="forestGreen"/>
    - *     <enumeration value="fuchsia"/>
    - *     <enumeration value="gainsboro"/>
    - *     <enumeration value="ghostWhite"/>
    - *     <enumeration value="gold"/>
    - *     <enumeration value="goldenrod"/>
    - *     <enumeration value="gray"/>
    - *     <enumeration value="green"/>
    - *     <enumeration value="greenYellow"/>
    - *     <enumeration value="honeydew"/>
    - *     <enumeration value="hotPink"/>
    - *     <enumeration value="indianRed"/>
    - *     <enumeration value="indigo"/>
    - *     <enumeration value="ivory"/>
    - *     <enumeration value="khaki"/>
    - *     <enumeration value="lavender"/>
    - *     <enumeration value="lavenderBlush"/>
    - *     <enumeration value="lawnGreen"/>
    - *     <enumeration value="lemonChiffon"/>
    - *     <enumeration value="ltBlue"/>
    - *     <enumeration value="ltCoral"/>
    - *     <enumeration value="ltCyan"/>
    - *     <enumeration value="ltGoldenrodYellow"/>
    - *     <enumeration value="ltGray"/>
    - *     <enumeration value="ltGreen"/>
    - *     <enumeration value="ltPink"/>
    - *     <enumeration value="ltSalmon"/>
    - *     <enumeration value="ltSeaGreen"/>
    - *     <enumeration value="ltSkyBlue"/>
    - *     <enumeration value="ltSlateGray"/>
    - *     <enumeration value="ltSteelBlue"/>
    - *     <enumeration value="ltYellow"/>
    - *     <enumeration value="lime"/>
    - *     <enumeration value="limeGreen"/>
    - *     <enumeration value="linen"/>
    - *     <enumeration value="magenta"/>
    - *     <enumeration value="maroon"/>
    - *     <enumeration value="medAquamarine"/>
    - *     <enumeration value="medBlue"/>
    - *     <enumeration value="medOrchid"/>
    - *     <enumeration value="medPurple"/>
    - *     <enumeration value="medSeaGreen"/>
    - *     <enumeration value="medSlateBlue"/>
    - *     <enumeration value="medSpringGreen"/>
    - *     <enumeration value="medTurquoise"/>
    - *     <enumeration value="medVioletRed"/>
    - *     <enumeration value="midnightBlue"/>
    - *     <enumeration value="mintCream"/>
    - *     <enumeration value="mistyRose"/>
    - *     <enumeration value="moccasin"/>
    - *     <enumeration value="navajoWhite"/>
    - *     <enumeration value="navy"/>
    - *     <enumeration value="oldLace"/>
    - *     <enumeration value="olive"/>
    - *     <enumeration value="oliveDrab"/>
    - *     <enumeration value="orange"/>
    - *     <enumeration value="orangeRed"/>
    - *     <enumeration value="orchid"/>
    - *     <enumeration value="paleGoldenrod"/>
    - *     <enumeration value="paleGreen"/>
    - *     <enumeration value="paleTurquoise"/>
    - *     <enumeration value="paleVioletRed"/>
    - *     <enumeration value="papayaWhip"/>
    - *     <enumeration value="peachPuff"/>
    - *     <enumeration value="peru"/>
    - *     <enumeration value="pink"/>
    - *     <enumeration value="plum"/>
    - *     <enumeration value="powderBlue"/>
    - *     <enumeration value="purple"/>
    - *     <enumeration value="red"/>
    - *     <enumeration value="rosyBrown"/>
    - *     <enumeration value="royalBlue"/>
    - *     <enumeration value="saddleBrown"/>
    - *     <enumeration value="salmon"/>
    - *     <enumeration value="sandyBrown"/>
    - *     <enumeration value="seaGreen"/>
    - *     <enumeration value="seaShell"/>
    - *     <enumeration value="sienna"/>
    - *     <enumeration value="silver"/>
    - *     <enumeration value="skyBlue"/>
    - *     <enumeration value="slateBlue"/>
    - *     <enumeration value="slateGray"/>
    - *     <enumeration value="snow"/>
    - *     <enumeration value="springGreen"/>
    - *     <enumeration value="steelBlue"/>
    - *     <enumeration value="tan"/>
    - *     <enumeration value="teal"/>
    - *     <enumeration value="thistle"/>
    - *     <enumeration value="tomato"/>
    - *     <enumeration value="turquoise"/>
    - *     <enumeration value="violet"/>
    - *     <enumeration value="wheat"/>
    - *     <enumeration value="white"/>
    - *     <enumeration value="whiteSmoke"/>
    - *     <enumeration value="yellow"/>
    - *     <enumeration value="yellowGreen"/>
    - *   </restriction>
    - * </simpleType>
    - * 
    - * - */ -@XmlType(name = "ST_PresetColorVal", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") -@XmlEnum -public enum STPresetColorVal { - - - /** - * Alice Blue Preset Color - * - */ - @XmlEnumValue("aliceBlue") - ALICE_BLUE("aliceBlue"), - - /** - * Antique White Preset Color - * - */ - @XmlEnumValue("antiqueWhite") - ANTIQUE_WHITE("antiqueWhite"), - - /** - * Aqua Preset Color - * - */ - @XmlEnumValue("aqua") - AQUA("aqua"), - - /** - * Aquamarine Preset Color - * - */ - @XmlEnumValue("aquamarine") - AQUAMARINE("aquamarine"), - - /** - * Azure Preset Color - * - */ - @XmlEnumValue("azure") - AZURE("azure"), - - /** - * Beige Preset Color - * - */ - @XmlEnumValue("beige") - BEIGE("beige"), - - /** - * Bisque Preset Color - * - */ - @XmlEnumValue("bisque") - BISQUE("bisque"), - - /** - * Black Preset Color - * - */ - @XmlEnumValue("black") - BLACK("black"), - - /** - * Blanched Almond Preset Color - * - */ - @XmlEnumValue("blanchedAlmond") - BLANCHED_ALMOND("blanchedAlmond"), - - /** - * Blue Preset Color - * - */ - @XmlEnumValue("blue") - BLUE("blue"), - - /** - * Blue Violet Preset Color - * - */ - @XmlEnumValue("blueViolet") - BLUE_VIOLET("blueViolet"), - - /** - * Brown Preset Color - * - */ - @XmlEnumValue("brown") - BROWN("brown"), - - /** - * Burly Wood Preset Color - * - */ - @XmlEnumValue("burlyWood") - BURLY_WOOD("burlyWood"), - - /** - * Cadet Blue Preset Color - * - */ - @XmlEnumValue("cadetBlue") - CADET_BLUE("cadetBlue"), - - /** - * Chartreuse Preset Color - * - */ - @XmlEnumValue("chartreuse") - CHARTREUSE("chartreuse"), - - /** - * Chocolate Preset Color - * - */ - @XmlEnumValue("chocolate") - CHOCOLATE("chocolate"), - - /** - * Coral Preset Color - * - */ - @XmlEnumValue("coral") - CORAL("coral"), - - /** - * Cornflower Blue Preset Color - * - */ - @XmlEnumValue("cornflowerBlue") - CORNFLOWER_BLUE("cornflowerBlue"), - - /** - * Cornsilk Preset Color - * - */ - @XmlEnumValue("cornsilk") - CORNSILK("cornsilk"), - - /** - * Crimson Preset Color - * - */ - @XmlEnumValue("crimson") - CRIMSON("crimson"), - - /** - * Cyan Preset Color - * - */ - @XmlEnumValue("cyan") - CYAN("cyan"), - - /** - * Dark Blue Preset Color - * - */ - @XmlEnumValue("dkBlue") - DK_BLUE("dkBlue"), - - /** - * Dark Cyan Preset Color - * - */ - @XmlEnumValue("dkCyan") - DK_CYAN("dkCyan"), - - /** - * Dark Goldenrod Preset Color - * - */ - @XmlEnumValue("dkGoldenrod") - DK_GOLDENROD("dkGoldenrod"), - - /** - * Dark Gray Preset Color - * - */ - @XmlEnumValue("dkGray") - DK_GRAY("dkGray"), - - /** - * Dark Green Preset Color - * - */ - @XmlEnumValue("dkGreen") - DK_GREEN("dkGreen"), - - /** - * Dark Khaki Preset Color - * - */ - @XmlEnumValue("dkKhaki") - DK_KHAKI("dkKhaki"), - - /** - * Dark Magenta Preset Color - * - */ - @XmlEnumValue("dkMagenta") - DK_MAGENTA("dkMagenta"), - - /** - * Dark Olive Green Preset Color - * - */ - @XmlEnumValue("dkOliveGreen") - DK_OLIVE_GREEN("dkOliveGreen"), - - /** - * Dark Orange Preset Color - * - */ - @XmlEnumValue("dkOrange") - DK_ORANGE("dkOrange"), - - /** - * Dark Orchid Preset Color - * - */ - @XmlEnumValue("dkOrchid") - DK_ORCHID("dkOrchid"), - - /** - * Dark Red Preset Color - * - */ - @XmlEnumValue("dkRed") - DK_RED("dkRed"), - - /** - * Dark Salmon Preset Color - * - */ - @XmlEnumValue("dkSalmon") - DK_SALMON("dkSalmon"), - - /** - * Dark Sea Green Preset Color - * - */ - @XmlEnumValue("dkSeaGreen") - DK_SEA_GREEN("dkSeaGreen"), - - /** - * Dark Slate Blue Preset Color - * - */ - @XmlEnumValue("dkSlateBlue") - DK_SLATE_BLUE("dkSlateBlue"), - - /** - * Dark Slate Gray Preset Color - * - */ - @XmlEnumValue("dkSlateGray") - DK_SLATE_GRAY("dkSlateGray"), - - /** - * Dark Turquoise Preset Color - * - */ - @XmlEnumValue("dkTurquoise") - DK_TURQUOISE("dkTurquoise"), - - /** - * Dark Violet Preset Color - * - */ - @XmlEnumValue("dkViolet") - DK_VIOLET("dkViolet"), - - /** - * Deep Pink Preset Color - * - */ - @XmlEnumValue("deepPink") - DEEP_PINK("deepPink"), - - /** - * Deep Sky Blue Preset Color - * - */ - @XmlEnumValue("deepSkyBlue") - DEEP_SKY_BLUE("deepSkyBlue"), - - /** - * Dim Gray Preset Color - * - */ - @XmlEnumValue("dimGray") - DIM_GRAY("dimGray"), - - /** - * Dodger Blue Preset Color - * - */ - @XmlEnumValue("dodgerBlue") - DODGER_BLUE("dodgerBlue"), - - /** - * Firebrick Preset Color - * - */ - @XmlEnumValue("firebrick") - FIREBRICK("firebrick"), - - /** - * Floral White Preset Color - * - */ - @XmlEnumValue("floralWhite") - FLORAL_WHITE("floralWhite"), - - /** - * Forest Green Preset Color - * - */ - @XmlEnumValue("forestGreen") - FOREST_GREEN("forestGreen"), - - /** - * Fuchsia Preset Color - * - */ - @XmlEnumValue("fuchsia") - FUCHSIA("fuchsia"), - - /** - * Gainsboro Preset Color - * - */ - @XmlEnumValue("gainsboro") - GAINSBORO("gainsboro"), - - /** - * Ghost White Preset Color - * - */ - @XmlEnumValue("ghostWhite") - GHOST_WHITE("ghostWhite"), - - /** - * Gold Preset Color - * - */ - @XmlEnumValue("gold") - GOLD("gold"), - - /** - * Goldenrod Preset Color - * - */ - @XmlEnumValue("goldenrod") - GOLDENROD("goldenrod"), - - /** - * Gray Preset Color - * - */ - @XmlEnumValue("gray") - GRAY("gray"), - - /** - * Green Preset Color - * - */ - @XmlEnumValue("green") - GREEN("green"), - - /** - * Green Yellow Preset Color - * - */ - @XmlEnumValue("greenYellow") - GREEN_YELLOW("greenYellow"), - - /** - * Honeydew Preset Color - * - */ - @XmlEnumValue("honeydew") - HONEYDEW("honeydew"), - - /** - * Hot Pink Preset Color - * - */ - @XmlEnumValue("hotPink") - HOT_PINK("hotPink"), - - /** - * Indian Red Preset Color - * - */ - @XmlEnumValue("indianRed") - INDIAN_RED("indianRed"), - - /** - * Indigo Preset Color - * - */ - @XmlEnumValue("indigo") - INDIGO("indigo"), - - /** - * Ivory Preset Color - * - */ - @XmlEnumValue("ivory") - IVORY("ivory"), - - /** - * Khaki Preset Color - * - */ - @XmlEnumValue("khaki") - KHAKI("khaki"), - - /** - * Lavender Preset Color - * - */ - @XmlEnumValue("lavender") - LAVENDER("lavender"), - - /** - * Lavender Blush Preset Color - * - */ - @XmlEnumValue("lavenderBlush") - LAVENDER_BLUSH("lavenderBlush"), - - /** - * Lawn Green Preset Color - * - */ - @XmlEnumValue("lawnGreen") - LAWN_GREEN("lawnGreen"), - - /** - * Lemon Chiffon Preset Color - * - */ - @XmlEnumValue("lemonChiffon") - LEMON_CHIFFON("lemonChiffon"), - - /** - * Light Blue Preset Color - * - */ - @XmlEnumValue("ltBlue") - LT_BLUE("ltBlue"), - - /** - * Light Coral Preset Color - * - */ - @XmlEnumValue("ltCoral") - LT_CORAL("ltCoral"), - - /** - * Light Cyan Preset Color - * - */ - @XmlEnumValue("ltCyan") - LT_CYAN("ltCyan"), - - /** - * Light Goldenrod Yellow Preset Color - * - */ - @XmlEnumValue("ltGoldenrodYellow") - LT_GOLDENROD_YELLOW("ltGoldenrodYellow"), - - /** - * Light Gray Preset Color - * - */ - @XmlEnumValue("ltGray") - LT_GRAY("ltGray"), - - /** - * Light Green Preset Color - * - */ - @XmlEnumValue("ltGreen") - LT_GREEN("ltGreen"), - - /** - * Light Pink Preset Color - * - */ - @XmlEnumValue("ltPink") - LT_PINK("ltPink"), - - /** - * Light Salmon Preset Color - * - */ - @XmlEnumValue("ltSalmon") - LT_SALMON("ltSalmon"), - - /** - * Light Sea Green Preset Color - * - */ - @XmlEnumValue("ltSeaGreen") - LT_SEA_GREEN("ltSeaGreen"), - - /** - * Light Sky Blue Preset Color - * - */ - @XmlEnumValue("ltSkyBlue") - LT_SKY_BLUE("ltSkyBlue"), - - /** - * Light Slate Gray Preset Color - * - */ - @XmlEnumValue("ltSlateGray") - LT_SLATE_GRAY("ltSlateGray"), - - /** - * Light Steel Blue Preset Color - * - */ - @XmlEnumValue("ltSteelBlue") - LT_STEEL_BLUE("ltSteelBlue"), - - /** - * Light Yellow Preset Color - * - */ - @XmlEnumValue("ltYellow") - LT_YELLOW("ltYellow"), - - /** - * Lime Preset Color - * - */ - @XmlEnumValue("lime") - LIME("lime"), - - /** - * Lime Green Preset Color - * - */ - @XmlEnumValue("limeGreen") - LIME_GREEN("limeGreen"), - - /** - * Linen Preset Color - * - */ - @XmlEnumValue("linen") - LINEN("linen"), - - /** - * Magenta Preset Color - * - */ - @XmlEnumValue("magenta") - MAGENTA("magenta"), - - /** - * Maroon Preset Color - * - */ - @XmlEnumValue("maroon") - MAROON("maroon"), - - /** - * Medium Aquamarine Preset Color - * - */ - @XmlEnumValue("medAquamarine") - MED_AQUAMARINE("medAquamarine"), - - /** - * Medium Blue Preset Color - * - */ - @XmlEnumValue("medBlue") - MED_BLUE("medBlue"), - - /** - * Medium Orchid Preset Color - * - */ - @XmlEnumValue("medOrchid") - MED_ORCHID("medOrchid"), - - /** - * Medium Purple Preset Color - * - */ - @XmlEnumValue("medPurple") - MED_PURPLE("medPurple"), - - /** - * Medium Sea Green Preset Color - * - */ - @XmlEnumValue("medSeaGreen") - MED_SEA_GREEN("medSeaGreen"), - - /** - * Medium Slate Blue Preset Color - * - */ - @XmlEnumValue("medSlateBlue") - MED_SLATE_BLUE("medSlateBlue"), - - /** - * Medium Spring Green Preset Color - * - */ - @XmlEnumValue("medSpringGreen") - MED_SPRING_GREEN("medSpringGreen"), - - /** - * Medium Turquoise Preset Color - * - */ - @XmlEnumValue("medTurquoise") - MED_TURQUOISE("medTurquoise"), - - /** - * Medium Violet Red Preset Color - * - */ - @XmlEnumValue("medVioletRed") - MED_VIOLET_RED("medVioletRed"), - - /** - * Midnight Blue Preset Color - * - */ - @XmlEnumValue("midnightBlue") - MIDNIGHT_BLUE("midnightBlue"), - - /** - * Mint Cream Preset Color - * - */ - @XmlEnumValue("mintCream") - MINT_CREAM("mintCream"), - - /** - * Misty Rose Preset Color - * - */ - @XmlEnumValue("mistyRose") - MISTY_ROSE("mistyRose"), - - /** - * Moccasin Preset Color - * - */ - @XmlEnumValue("moccasin") - MOCCASIN("moccasin"), - - /** - * Navajo White Preset Color - * - */ - @XmlEnumValue("navajoWhite") - NAVAJO_WHITE("navajoWhite"), - - /** - * Navy Preset Color - * - */ - @XmlEnumValue("navy") - NAVY("navy"), - - /** - * Old Lace Preset Color - * - */ - @XmlEnumValue("oldLace") - OLD_LACE("oldLace"), - - /** - * Olive Preset Color - * - */ - @XmlEnumValue("olive") - OLIVE("olive"), - - /** - * Olive Drab Preset Color - * - */ - @XmlEnumValue("oliveDrab") - OLIVE_DRAB("oliveDrab"), - - /** - * Orange Preset Color - * - */ - @XmlEnumValue("orange") - ORANGE("orange"), - - /** - * Orange Red Preset Color - * - */ - @XmlEnumValue("orangeRed") - ORANGE_RED("orangeRed"), - - /** - * Orchid Preset Color - * - */ - @XmlEnumValue("orchid") - ORCHID("orchid"), - - /** - * Pale Goldenrod Preset Color - * - */ - @XmlEnumValue("paleGoldenrod") - PALE_GOLDENROD("paleGoldenrod"), - - /** - * Pale Green Preset Color - * - */ - @XmlEnumValue("paleGreen") - PALE_GREEN("paleGreen"), - - /** - * Pale Turquoise Preset Color - * - */ - @XmlEnumValue("paleTurquoise") - PALE_TURQUOISE("paleTurquoise"), - - /** - * Pale Violet Red Preset Color - * - */ - @XmlEnumValue("paleVioletRed") - PALE_VIOLET_RED("paleVioletRed"), - - /** - * Papaya Whip Preset Color - * - */ - @XmlEnumValue("papayaWhip") - PAPAYA_WHIP("papayaWhip"), - - /** - * Peach Puff Preset Color - * - */ - @XmlEnumValue("peachPuff") - PEACH_PUFF("peachPuff"), - - /** - * Peru Preset Color - * - */ - @XmlEnumValue("peru") - PERU("peru"), - - /** - * Pink Preset Color - * - */ - @XmlEnumValue("pink") - PINK("pink"), - - /** - * Plum Preset Color - * - */ - @XmlEnumValue("plum") - PLUM("plum"), - - /** - * Powder Blue Preset Color - * - */ - @XmlEnumValue("powderBlue") - POWDER_BLUE("powderBlue"), - - /** - * Purple Preset Color - * - */ - @XmlEnumValue("purple") - PURPLE("purple"), - - /** - * Red Preset Color - * - */ - @XmlEnumValue("red") - RED("red"), - - /** - * Rosy Brown Preset Color - * - */ - @XmlEnumValue("rosyBrown") - ROSY_BROWN("rosyBrown"), - - /** - * Royal Blue Preset Color - * - */ - @XmlEnumValue("royalBlue") - ROYAL_BLUE("royalBlue"), - - /** - * Saddle Brown Preset Color - * - */ - @XmlEnumValue("saddleBrown") - SADDLE_BROWN("saddleBrown"), - - /** - * Salmon Preset Color - * - */ - @XmlEnumValue("salmon") - SALMON("salmon"), - - /** - * Sandy Brown Preset Color - * - */ - @XmlEnumValue("sandyBrown") - SANDY_BROWN("sandyBrown"), - - /** - * Sea Green Preset Color - * - */ - @XmlEnumValue("seaGreen") - SEA_GREEN("seaGreen"), - - /** - * Sea Shell Preset Color - * - */ - @XmlEnumValue("seaShell") - SEA_SHELL("seaShell"), - - /** - * Sienna Preset Color - * - */ - @XmlEnumValue("sienna") - SIENNA("sienna"), - - /** - * Silver Preset Color - * - */ - @XmlEnumValue("silver") - SILVER("silver"), - - /** - * Sky Blue Preset Color - * - */ - @XmlEnumValue("skyBlue") - SKY_BLUE("skyBlue"), - - /** - * Slate Blue Preset Color - * - */ - @XmlEnumValue("slateBlue") - SLATE_BLUE("slateBlue"), - - /** - * Slate Gray Preset Color - * - */ - @XmlEnumValue("slateGray") - SLATE_GRAY("slateGray"), - - /** - * Snow Preset Color - * - */ - @XmlEnumValue("snow") - SNOW("snow"), - - /** - * Spring Green Preset Color - * - */ - @XmlEnumValue("springGreen") - SPRING_GREEN("springGreen"), - - /** - * Steel Blue Preset Color - * - */ - @XmlEnumValue("steelBlue") - STEEL_BLUE("steelBlue"), - - /** - * Tan Preset Color - * - */ - @XmlEnumValue("tan") - TAN("tan"), - - /** - * Teal Preset Color - * - */ - @XmlEnumValue("teal") - TEAL("teal"), - - /** - * Thistle Preset Color - * - */ - @XmlEnumValue("thistle") - THISTLE("thistle"), - - /** - * Tomato Preset Color - * - */ - @XmlEnumValue("tomato") - TOMATO("tomato"), - - /** - * Turquoise Preset Color - * - */ - @XmlEnumValue("turquoise") - TURQUOISE("turquoise"), - - /** - * Violet Preset Color - * - */ - @XmlEnumValue("violet") - VIOLET("violet"), - - /** - * Wheat Preset Color - * - */ - @XmlEnumValue("wheat") - WHEAT("wheat"), - - /** - * White Preset Color - * - */ - @XmlEnumValue("white") - WHITE("white"), - - /** - * White Smoke Preset Color - * - */ - @XmlEnumValue("whiteSmoke") - WHITE_SMOKE("whiteSmoke"), - - /** - * Yellow Preset Color - * - */ - @XmlEnumValue("yellow") - YELLOW("yellow"), - - /** - * Yellow Green Preset Color - * - */ - @XmlEnumValue("yellowGreen") - YELLOW_GREEN("yellowGreen"); - private final String value; - - STPresetColorVal(String v) { - value = v; - } - - public String value() { - return value; - } - - public static STPresetColorVal fromValue(String v) { - for (STPresetColorVal c: STPresetColorVal.values()) { - if (c.value.equals(v)) { - return c; - } - } - throw new IllegalArgumentException(v); - } - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/STRectAlignment.java b/src/java/org/apache/poi/sl/draw/binding/STRectAlignment.java deleted file mode 100644 index 4a95ae6ab..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/STRectAlignment.java +++ /dev/null @@ -1,133 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import javax.xml.bind.annotation.XmlEnum; -import javax.xml.bind.annotation.XmlEnumValue; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for ST_RectAlignment. - * - *

    The following schema fragment specifies the expected content contained within this class. - *

    - *

    - * <simpleType name="ST_RectAlignment">
    - *   <restriction base="{http://www.w3.org/2001/XMLSchema}token">
    - *     <enumeration value="tl"/>
    - *     <enumeration value="t"/>
    - *     <enumeration value="tr"/>
    - *     <enumeration value="l"/>
    - *     <enumeration value="ctr"/>
    - *     <enumeration value="r"/>
    - *     <enumeration value="bl"/>
    - *     <enumeration value="b"/>
    - *     <enumeration value="br"/>
    - *   </restriction>
    - * </simpleType>
    - * 
    - * - */ -@XmlType(name = "ST_RectAlignment", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") -@XmlEnum -public enum STRectAlignment { - - - /** - * Rectangle Alignment Enum ( Top Left ) - * - */ - @XmlEnumValue("tl") - TL("tl"), - - /** - * Rectangle Alignment Enum ( Top ) - * - */ - @XmlEnumValue("t") - T("t"), - - /** - * Rectangle Alignment Enum ( Top Right ) - * - */ - @XmlEnumValue("tr") - TR("tr"), - - /** - * Rectangle Alignment Enum ( Left ) - * - */ - @XmlEnumValue("l") - L("l"), - - /** - * Rectangle Alignment Enum ( Center ) - * - */ - @XmlEnumValue("ctr") - CTR("ctr"), - - /** - * Rectangle Alignment Enum ( Right ) - * - */ - @XmlEnumValue("r") - R("r"), - - /** - * Rectangle Alignment Enum ( Bottom Left ) - * - */ - @XmlEnumValue("bl") - BL("bl"), - - /** - * Rectangle Alignment Enum ( Bottom ) - * - */ - @XmlEnumValue("b") - B("b"), - - /** - * Rectangle Alignment Enum ( Bottom Right ) - * - */ - @XmlEnumValue("br") - BR("br"); - private final String value; - - STRectAlignment(String v) { - value = v; - } - - public String value() { - return value; - } - - public static STRectAlignment fromValue(String v) { - for (STRectAlignment c: STRectAlignment.values()) { - if (c.value.equals(v)) { - return c; - } - } - throw new IllegalArgumentException(v); - } - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/STSchemeColorVal.java b/src/java/org/apache/poi/sl/draw/binding/STSchemeColorVal.java deleted file mode 100644 index d7b50ec73..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/STSchemeColorVal.java +++ /dev/null @@ -1,197 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import javax.xml.bind.annotation.XmlEnum; -import javax.xml.bind.annotation.XmlEnumValue; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for ST_SchemeColorVal. - * - *

    The following schema fragment specifies the expected content contained within this class. - *

    - *

    - * <simpleType name="ST_SchemeColorVal">
    - *   <restriction base="{http://www.w3.org/2001/XMLSchema}token">
    - *     <enumeration value="bg1"/>
    - *     <enumeration value="tx1"/>
    - *     <enumeration value="bg2"/>
    - *     <enumeration value="tx2"/>
    - *     <enumeration value="accent1"/>
    - *     <enumeration value="accent2"/>
    - *     <enumeration value="accent3"/>
    - *     <enumeration value="accent4"/>
    - *     <enumeration value="accent5"/>
    - *     <enumeration value="accent6"/>
    - *     <enumeration value="hlink"/>
    - *     <enumeration value="folHlink"/>
    - *     <enumeration value="phClr"/>
    - *     <enumeration value="dk1"/>
    - *     <enumeration value="lt1"/>
    - *     <enumeration value="dk2"/>
    - *     <enumeration value="lt2"/>
    - *   </restriction>
    - * </simpleType>
    - * 
    - * - */ -@XmlType(name = "ST_SchemeColorVal", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") -@XmlEnum -public enum STSchemeColorVal { - - - /** - * Background Color 1 - * - */ - @XmlEnumValue("bg1") - BG_1("bg1"), - - /** - * Text Color 1 - * - */ - @XmlEnumValue("tx1") - TX_1("tx1"), - - /** - * Background Color 2 - * - */ - @XmlEnumValue("bg2") - BG_2("bg2"), - - /** - * Text Color 2 - * - */ - @XmlEnumValue("tx2") - TX_2("tx2"), - - /** - * Accent Color 1 - * - */ - @XmlEnumValue("accent1") - ACCENT_1("accent1"), - - /** - * Accent Color 2 - * - */ - @XmlEnumValue("accent2") - ACCENT_2("accent2"), - - /** - * Accent Color 3 - * - */ - @XmlEnumValue("accent3") - ACCENT_3("accent3"), - - /** - * Accent Color 4 - * - */ - @XmlEnumValue("accent4") - ACCENT_4("accent4"), - - /** - * Accent Color 5 - * - */ - @XmlEnumValue("accent5") - ACCENT_5("accent5"), - - /** - * Accent Color 6 - * - */ - @XmlEnumValue("accent6") - ACCENT_6("accent6"), - - /** - * Hyperlink Color - * - */ - @XmlEnumValue("hlink") - HLINK("hlink"), - - /** - * Followed Hyperlink Color - * - */ - @XmlEnumValue("folHlink") - FOL_HLINK("folHlink"), - - /** - * Style Color - * - */ - @XmlEnumValue("phClr") - PH_CLR("phClr"), - - /** - * Dark Color 1 - * - */ - @XmlEnumValue("dk1") - DK_1("dk1"), - - /** - * Light Color 1 - * - */ - @XmlEnumValue("lt1") - LT_1("lt1"), - - /** - * Dark Color 2 - * - */ - @XmlEnumValue("dk2") - DK_2("dk2"), - - /** - * Light Color 2 - * - */ - @XmlEnumValue("lt2") - LT_2("lt2"); - private final String value; - - STSchemeColorVal(String v) { - value = v; - } - - public String value() { - return value; - } - - public static STSchemeColorVal fromValue(String v) { - for (STSchemeColorVal c: STSchemeColorVal.values()) { - if (c.value.equals(v)) { - return c; - } - } - throw new IllegalArgumentException(v); - } - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/STShapeType.java b/src/java/org/apache/poi/sl/draw/binding/STShapeType.java deleted file mode 100644 index f160ec560..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/STShapeType.java +++ /dev/null @@ -1,1557 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import javax.xml.bind.annotation.XmlEnum; -import javax.xml.bind.annotation.XmlEnumValue; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for ST_ShapeType. - * - *

    The following schema fragment specifies the expected content contained within this class. - *

    - *

    - * <simpleType name="ST_ShapeType">
    - *   <restriction base="{http://www.w3.org/2001/XMLSchema}token">
    - *     <enumeration value="line"/>
    - *     <enumeration value="lineInv"/>
    - *     <enumeration value="triangle"/>
    - *     <enumeration value="rtTriangle"/>
    - *     <enumeration value="rect"/>
    - *     <enumeration value="diamond"/>
    - *     <enumeration value="parallelogram"/>
    - *     <enumeration value="trapezoid"/>
    - *     <enumeration value="nonIsoscelesTrapezoid"/>
    - *     <enumeration value="pentagon"/>
    - *     <enumeration value="hexagon"/>
    - *     <enumeration value="heptagon"/>
    - *     <enumeration value="octagon"/>
    - *     <enumeration value="decagon"/>
    - *     <enumeration value="dodecagon"/>
    - *     <enumeration value="star4"/>
    - *     <enumeration value="star5"/>
    - *     <enumeration value="star6"/>
    - *     <enumeration value="star7"/>
    - *     <enumeration value="star8"/>
    - *     <enumeration value="star10"/>
    - *     <enumeration value="star12"/>
    - *     <enumeration value="star16"/>
    - *     <enumeration value="star24"/>
    - *     <enumeration value="star32"/>
    - *     <enumeration value="roundRect"/>
    - *     <enumeration value="round1Rect"/>
    - *     <enumeration value="round2SameRect"/>
    - *     <enumeration value="round2DiagRect"/>
    - *     <enumeration value="snipRoundRect"/>
    - *     <enumeration value="snip1Rect"/>
    - *     <enumeration value="snip2SameRect"/>
    - *     <enumeration value="snip2DiagRect"/>
    - *     <enumeration value="plaque"/>
    - *     <enumeration value="ellipse"/>
    - *     <enumeration value="teardrop"/>
    - *     <enumeration value="homePlate"/>
    - *     <enumeration value="chevron"/>
    - *     <enumeration value="pieWedge"/>
    - *     <enumeration value="pie"/>
    - *     <enumeration value="blockArc"/>
    - *     <enumeration value="donut"/>
    - *     <enumeration value="noSmoking"/>
    - *     <enumeration value="rightArrow"/>
    - *     <enumeration value="leftArrow"/>
    - *     <enumeration value="upArrow"/>
    - *     <enumeration value="downArrow"/>
    - *     <enumeration value="stripedRightArrow"/>
    - *     <enumeration value="notchedRightArrow"/>
    - *     <enumeration value="bentUpArrow"/>
    - *     <enumeration value="leftRightArrow"/>
    - *     <enumeration value="upDownArrow"/>
    - *     <enumeration value="leftUpArrow"/>
    - *     <enumeration value="leftRightUpArrow"/>
    - *     <enumeration value="quadArrow"/>
    - *     <enumeration value="leftArrowCallout"/>
    - *     <enumeration value="rightArrowCallout"/>
    - *     <enumeration value="upArrowCallout"/>
    - *     <enumeration value="downArrowCallout"/>
    - *     <enumeration value="leftRightArrowCallout"/>
    - *     <enumeration value="upDownArrowCallout"/>
    - *     <enumeration value="quadArrowCallout"/>
    - *     <enumeration value="bentArrow"/>
    - *     <enumeration value="uturnArrow"/>
    - *     <enumeration value="circularArrow"/>
    - *     <enumeration value="leftCircularArrow"/>
    - *     <enumeration value="leftRightCircularArrow"/>
    - *     <enumeration value="curvedRightArrow"/>
    - *     <enumeration value="curvedLeftArrow"/>
    - *     <enumeration value="curvedUpArrow"/>
    - *     <enumeration value="curvedDownArrow"/>
    - *     <enumeration value="swooshArrow"/>
    - *     <enumeration value="cube"/>
    - *     <enumeration value="can"/>
    - *     <enumeration value="lightningBolt"/>
    - *     <enumeration value="heart"/>
    - *     <enumeration value="sun"/>
    - *     <enumeration value="moon"/>
    - *     <enumeration value="smileyFace"/>
    - *     <enumeration value="irregularSeal1"/>
    - *     <enumeration value="irregularSeal2"/>
    - *     <enumeration value="foldedCorner"/>
    - *     <enumeration value="bevel"/>
    - *     <enumeration value="frame"/>
    - *     <enumeration value="halfFrame"/>
    - *     <enumeration value="corner"/>
    - *     <enumeration value="diagStripe"/>
    - *     <enumeration value="chord"/>
    - *     <enumeration value="arc"/>
    - *     <enumeration value="leftBracket"/>
    - *     <enumeration value="rightBracket"/>
    - *     <enumeration value="leftBrace"/>
    - *     <enumeration value="rightBrace"/>
    - *     <enumeration value="bracketPair"/>
    - *     <enumeration value="bracePair"/>
    - *     <enumeration value="straightConnector1"/>
    - *     <enumeration value="bentConnector2"/>
    - *     <enumeration value="bentConnector3"/>
    - *     <enumeration value="bentConnector4"/>
    - *     <enumeration value="bentConnector5"/>
    - *     <enumeration value="curvedConnector2"/>
    - *     <enumeration value="curvedConnector3"/>
    - *     <enumeration value="curvedConnector4"/>
    - *     <enumeration value="curvedConnector5"/>
    - *     <enumeration value="callout1"/>
    - *     <enumeration value="callout2"/>
    - *     <enumeration value="callout3"/>
    - *     <enumeration value="accentCallout1"/>
    - *     <enumeration value="accentCallout2"/>
    - *     <enumeration value="accentCallout3"/>
    - *     <enumeration value="borderCallout1"/>
    - *     <enumeration value="borderCallout2"/>
    - *     <enumeration value="borderCallout3"/>
    - *     <enumeration value="accentBorderCallout1"/>
    - *     <enumeration value="accentBorderCallout2"/>
    - *     <enumeration value="accentBorderCallout3"/>
    - *     <enumeration value="wedgeRectCallout"/>
    - *     <enumeration value="wedgeRoundRectCallout"/>
    - *     <enumeration value="wedgeEllipseCallout"/>
    - *     <enumeration value="cloudCallout"/>
    - *     <enumeration value="cloud"/>
    - *     <enumeration value="ribbon"/>
    - *     <enumeration value="ribbon2"/>
    - *     <enumeration value="ellipseRibbon"/>
    - *     <enumeration value="ellipseRibbon2"/>
    - *     <enumeration value="leftRightRibbon"/>
    - *     <enumeration value="verticalScroll"/>
    - *     <enumeration value="horizontalScroll"/>
    - *     <enumeration value="wave"/>
    - *     <enumeration value="doubleWave"/>
    - *     <enumeration value="plus"/>
    - *     <enumeration value="flowChartProcess"/>
    - *     <enumeration value="flowChartDecision"/>
    - *     <enumeration value="flowChartInputOutput"/>
    - *     <enumeration value="flowChartPredefinedProcess"/>
    - *     <enumeration value="flowChartInternalStorage"/>
    - *     <enumeration value="flowChartDocument"/>
    - *     <enumeration value="flowChartMultidocument"/>
    - *     <enumeration value="flowChartTerminator"/>
    - *     <enumeration value="flowChartPreparation"/>
    - *     <enumeration value="flowChartManualInput"/>
    - *     <enumeration value="flowChartManualOperation"/>
    - *     <enumeration value="flowChartConnector"/>
    - *     <enumeration value="flowChartPunchedCard"/>
    - *     <enumeration value="flowChartPunchedTape"/>
    - *     <enumeration value="flowChartSummingJunction"/>
    - *     <enumeration value="flowChartOr"/>
    - *     <enumeration value="flowChartCollate"/>
    - *     <enumeration value="flowChartSort"/>
    - *     <enumeration value="flowChartExtract"/>
    - *     <enumeration value="flowChartMerge"/>
    - *     <enumeration value="flowChartOfflineStorage"/>
    - *     <enumeration value="flowChartOnlineStorage"/>
    - *     <enumeration value="flowChartMagneticTape"/>
    - *     <enumeration value="flowChartMagneticDisk"/>
    - *     <enumeration value="flowChartMagneticDrum"/>
    - *     <enumeration value="flowChartDisplay"/>
    - *     <enumeration value="flowChartDelay"/>
    - *     <enumeration value="flowChartAlternateProcess"/>
    - *     <enumeration value="flowChartOffpageConnector"/>
    - *     <enumeration value="actionButtonBlank"/>
    - *     <enumeration value="actionButtonHome"/>
    - *     <enumeration value="actionButtonHelp"/>
    - *     <enumeration value="actionButtonInformation"/>
    - *     <enumeration value="actionButtonForwardNext"/>
    - *     <enumeration value="actionButtonBackPrevious"/>
    - *     <enumeration value="actionButtonEnd"/>
    - *     <enumeration value="actionButtonBeginning"/>
    - *     <enumeration value="actionButtonReturn"/>
    - *     <enumeration value="actionButtonDocument"/>
    - *     <enumeration value="actionButtonSound"/>
    - *     <enumeration value="actionButtonMovie"/>
    - *     <enumeration value="gear6"/>
    - *     <enumeration value="gear9"/>
    - *     <enumeration value="funnel"/>
    - *     <enumeration value="mathPlus"/>
    - *     <enumeration value="mathMinus"/>
    - *     <enumeration value="mathMultiply"/>
    - *     <enumeration value="mathDivide"/>
    - *     <enumeration value="mathEqual"/>
    - *     <enumeration value="mathNotEqual"/>
    - *     <enumeration value="cornerTabs"/>
    - *     <enumeration value="squareTabs"/>
    - *     <enumeration value="plaqueTabs"/>
    - *     <enumeration value="chartX"/>
    - *     <enumeration value="chartStar"/>
    - *     <enumeration value="chartPlus"/>
    - *   </restriction>
    - * </simpleType>
    - * 
    - * - */ -@XmlType(name = "ST_ShapeType", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") -@XmlEnum -public enum STShapeType { - - - /** - * Line Shape - * - */ - @XmlEnumValue("line") - LINE("line"), - - /** - * Line Inverse Shape - * - */ - @XmlEnumValue("lineInv") - LINE_INV("lineInv"), - - /** - * Triangle Shape - * - */ - @XmlEnumValue("triangle") - TRIANGLE("triangle"), - - /** - * Right Triangle Shape - * - */ - @XmlEnumValue("rtTriangle") - RT_TRIANGLE("rtTriangle"), - - /** - * Rectangle Shape - * - */ - @XmlEnumValue("rect") - RECT("rect"), - - /** - * Diamond Shape - * - */ - @XmlEnumValue("diamond") - DIAMOND("diamond"), - - /** - * Parallelogram Shape - * - */ - @XmlEnumValue("parallelogram") - PARALLELOGRAM("parallelogram"), - - /** - * Trapezoid Shape - * - */ - @XmlEnumValue("trapezoid") - TRAPEZOID("trapezoid"), - - /** - * Non-Isosceles Trapezoid Shape - * - */ - @XmlEnumValue("nonIsoscelesTrapezoid") - NON_ISOSCELES_TRAPEZOID("nonIsoscelesTrapezoid"), - - /** - * Pentagon Shape - * - */ - @XmlEnumValue("pentagon") - PENTAGON("pentagon"), - - /** - * Hexagon Shape - * - */ - @XmlEnumValue("hexagon") - HEXAGON("hexagon"), - - /** - * Heptagon Shape - * - */ - @XmlEnumValue("heptagon") - HEPTAGON("heptagon"), - - /** - * Octagon Shape - * - */ - @XmlEnumValue("octagon") - OCTAGON("octagon"), - - /** - * Decagon Shape - * - */ - @XmlEnumValue("decagon") - DECAGON("decagon"), - - /** - * Dodecagon Shape - * - */ - @XmlEnumValue("dodecagon") - DODECAGON("dodecagon"), - - /** - * Four Pointed Star Shape - * - */ - @XmlEnumValue("star4") - STAR_4("star4"), - - /** - * Five Pointed Star Shape - * - */ - @XmlEnumValue("star5") - STAR_5("star5"), - - /** - * Six Pointed Star Shape - * - */ - @XmlEnumValue("star6") - STAR_6("star6"), - - /** - * Seven Pointed Star Shape - * - */ - @XmlEnumValue("star7") - STAR_7("star7"), - - /** - * Eight Pointed Star Shape - * - */ - @XmlEnumValue("star8") - STAR_8("star8"), - - /** - * Ten Pointed Star Shape - * - */ - @XmlEnumValue("star10") - STAR_10("star10"), - - /** - * Twelve Pointed Star Shape - * - */ - @XmlEnumValue("star12") - STAR_12("star12"), - - /** - * Sixteen Pointed Star Shape - * - */ - @XmlEnumValue("star16") - STAR_16("star16"), - - /** - * Twenty Four Pointed Star Shape - * - */ - @XmlEnumValue("star24") - STAR_24("star24"), - - /** - * Thirty Two Pointed Star Shape - * - */ - @XmlEnumValue("star32") - STAR_32("star32"), - - /** - * Round Corner Rectangle Shape - * - */ - @XmlEnumValue("roundRect") - ROUND_RECT("roundRect"), - - /** - * One Round Corner Rectangle Shape - * - */ - @XmlEnumValue("round1Rect") - ROUND_1_RECT("round1Rect"), - - /** - * Two Same-side Round Corner Rectangle Shape - * - */ - @XmlEnumValue("round2SameRect") - ROUND_2_SAME_RECT("round2SameRect"), - - /** - * Two Diagonal Round Corner Rectangle Shape - * - */ - @XmlEnumValue("round2DiagRect") - ROUND_2_DIAG_RECT("round2DiagRect"), - - /** - * One Snip One Round Corner Rectangle Shape - * - */ - @XmlEnumValue("snipRoundRect") - SNIP_ROUND_RECT("snipRoundRect"), - - /** - * One Snip Corner Rectangle Shape - * - */ - @XmlEnumValue("snip1Rect") - SNIP_1_RECT("snip1Rect"), - - /** - * Two Same-side Snip Corner Rectangle Shape - * - */ - @XmlEnumValue("snip2SameRect") - SNIP_2_SAME_RECT("snip2SameRect"), - - /** - * Two Diagonal Snip Corner Rectangle Shape - * - */ - @XmlEnumValue("snip2DiagRect") - SNIP_2_DIAG_RECT("snip2DiagRect"), - - /** - * Plaque Shape - * - */ - @XmlEnumValue("plaque") - PLAQUE("plaque"), - - /** - * Ellipse Shape - * - */ - @XmlEnumValue("ellipse") - ELLIPSE("ellipse"), - - /** - * Teardrop Shape - * - */ - @XmlEnumValue("teardrop") - TEARDROP("teardrop"), - - /** - * Home Plate Shape - * - */ - @XmlEnumValue("homePlate") - HOME_PLATE("homePlate"), - - /** - * Chevron Shape - * - */ - @XmlEnumValue("chevron") - CHEVRON("chevron"), - - /** - * Pie Wedge Shape - * - */ - @XmlEnumValue("pieWedge") - PIE_WEDGE("pieWedge"), - - /** - * Pie Shape - * - */ - @XmlEnumValue("pie") - PIE("pie"), - - /** - * Block Arc Shape - * - */ - @XmlEnumValue("blockArc") - BLOCK_ARC("blockArc"), - - /** - * Donut Shape - * - */ - @XmlEnumValue("donut") - DONUT("donut"), - - /** - * No Smoking Shape - * - */ - @XmlEnumValue("noSmoking") - NO_SMOKING("noSmoking"), - - /** - * Right Arrow Shape - * - */ - @XmlEnumValue("rightArrow") - RIGHT_ARROW("rightArrow"), - - /** - * Left Arrow Shape - * - */ - @XmlEnumValue("leftArrow") - LEFT_ARROW("leftArrow"), - - /** - * Up Arrow Shape - * - */ - @XmlEnumValue("upArrow") - UP_ARROW("upArrow"), - - /** - * Down Arrow Shape - * - */ - @XmlEnumValue("downArrow") - DOWN_ARROW("downArrow"), - - /** - * Striped Right Arrow Shape - * - */ - @XmlEnumValue("stripedRightArrow") - STRIPED_RIGHT_ARROW("stripedRightArrow"), - - /** - * Notched Right Arrow Shape - * - */ - @XmlEnumValue("notchedRightArrow") - NOTCHED_RIGHT_ARROW("notchedRightArrow"), - - /** - * Bent Up Arrow Shape - * - */ - @XmlEnumValue("bentUpArrow") - BENT_UP_ARROW("bentUpArrow"), - - /** - * Left Right Arrow Shape - * - */ - @XmlEnumValue("leftRightArrow") - LEFT_RIGHT_ARROW("leftRightArrow"), - - /** - * Up Down Arrow Shape - * - */ - @XmlEnumValue("upDownArrow") - UP_DOWN_ARROW("upDownArrow"), - - /** - * Left Up Arrow Shape - * - */ - @XmlEnumValue("leftUpArrow") - LEFT_UP_ARROW("leftUpArrow"), - - /** - * Left Right Up Arrow Shape - * - */ - @XmlEnumValue("leftRightUpArrow") - LEFT_RIGHT_UP_ARROW("leftRightUpArrow"), - - /** - * Quad-Arrow Shape - * - */ - @XmlEnumValue("quadArrow") - QUAD_ARROW("quadArrow"), - - /** - * Callout Left Arrow Shape - * - */ - @XmlEnumValue("leftArrowCallout") - LEFT_ARROW_CALLOUT("leftArrowCallout"), - - /** - * Callout Right Arrow Shape - * - */ - @XmlEnumValue("rightArrowCallout") - RIGHT_ARROW_CALLOUT("rightArrowCallout"), - - /** - * Callout Up Arrow Shape - * - */ - @XmlEnumValue("upArrowCallout") - UP_ARROW_CALLOUT("upArrowCallout"), - - /** - * Callout Down Arrow Shape - * - */ - @XmlEnumValue("downArrowCallout") - DOWN_ARROW_CALLOUT("downArrowCallout"), - - /** - * Callout Left Right Arrow Shape - * - */ - @XmlEnumValue("leftRightArrowCallout") - LEFT_RIGHT_ARROW_CALLOUT("leftRightArrowCallout"), - - /** - * Callout Up Down Arrow Shape - * - */ - @XmlEnumValue("upDownArrowCallout") - UP_DOWN_ARROW_CALLOUT("upDownArrowCallout"), - - /** - * Callout Quad-Arrow Shape - * - */ - @XmlEnumValue("quadArrowCallout") - QUAD_ARROW_CALLOUT("quadArrowCallout"), - - /** - * Bent Arrow Shape - * - */ - @XmlEnumValue("bentArrow") - BENT_ARROW("bentArrow"), - - /** - * U-Turn Arrow Shape - * - */ - @XmlEnumValue("uturnArrow") - UTURN_ARROW("uturnArrow"), - - /** - * Circular Arrow Shape - * - */ - @XmlEnumValue("circularArrow") - CIRCULAR_ARROW("circularArrow"), - - /** - * Left Circular Arrow Shape - * - */ - @XmlEnumValue("leftCircularArrow") - LEFT_CIRCULAR_ARROW("leftCircularArrow"), - - /** - * Left Right Circular Arrow Shape - * - */ - @XmlEnumValue("leftRightCircularArrow") - LEFT_RIGHT_CIRCULAR_ARROW("leftRightCircularArrow"), - - /** - * Curved Right Arrow Shape - * - */ - @XmlEnumValue("curvedRightArrow") - CURVED_RIGHT_ARROW("curvedRightArrow"), - - /** - * Curved Left Arrow Shape - * - */ - @XmlEnumValue("curvedLeftArrow") - CURVED_LEFT_ARROW("curvedLeftArrow"), - - /** - * Curved Up Arrow Shape - * - */ - @XmlEnumValue("curvedUpArrow") - CURVED_UP_ARROW("curvedUpArrow"), - - /** - * Curved Down Arrow Shape - * - */ - @XmlEnumValue("curvedDownArrow") - CURVED_DOWN_ARROW("curvedDownArrow"), - - /** - * Swoosh Arrow Shape - * - */ - @XmlEnumValue("swooshArrow") - SWOOSH_ARROW("swooshArrow"), - - /** - * Cube Shape - * - */ - @XmlEnumValue("cube") - CUBE("cube"), - - /** - * Can Shape - * - */ - @XmlEnumValue("can") - CAN("can"), - - /** - * Lightning Bolt Shape - * - */ - @XmlEnumValue("lightningBolt") - LIGHTNING_BOLT("lightningBolt"), - - /** - * Heart Shape - * - */ - @XmlEnumValue("heart") - HEART("heart"), - - /** - * Sun Shape - * - */ - @XmlEnumValue("sun") - SUN("sun"), - - /** - * Moon Shape - * - */ - @XmlEnumValue("moon") - MOON("moon"), - - /** - * Smiley Face Shape - * - */ - @XmlEnumValue("smileyFace") - SMILEY_FACE("smileyFace"), - - /** - * Irregular Seal 1 Shape - * - */ - @XmlEnumValue("irregularSeal1") - IRREGULAR_SEAL_1("irregularSeal1"), - - /** - * Irregular Seal 2 Shape - * - */ - @XmlEnumValue("irregularSeal2") - IRREGULAR_SEAL_2("irregularSeal2"), - - /** - * Folded Corner Shape - * - */ - @XmlEnumValue("foldedCorner") - FOLDED_CORNER("foldedCorner"), - - /** - * Bevel Shape - * - */ - @XmlEnumValue("bevel") - BEVEL("bevel"), - - /** - * Frame Shape - * - */ - @XmlEnumValue("frame") - FRAME("frame"), - - /** - * Half Frame Shape - * - */ - @XmlEnumValue("halfFrame") - HALF_FRAME("halfFrame"), - - /** - * Corner Shape - * - */ - @XmlEnumValue("corner") - CORNER("corner"), - - /** - * Diagonal Stripe Shape - * - */ - @XmlEnumValue("diagStripe") - DIAG_STRIPE("diagStripe"), - - /** - * Chord Shape - * - */ - @XmlEnumValue("chord") - CHORD("chord"), - - /** - * Curved Arc Shape - * - */ - @XmlEnumValue("arc") - ARC("arc"), - - /** - * Left Bracket Shape - * - */ - @XmlEnumValue("leftBracket") - LEFT_BRACKET("leftBracket"), - - /** - * Right Bracket Shape - * - */ - @XmlEnumValue("rightBracket") - RIGHT_BRACKET("rightBracket"), - - /** - * Left Brace Shape - * - */ - @XmlEnumValue("leftBrace") - LEFT_BRACE("leftBrace"), - - /** - * Right Brace Shape - * - */ - @XmlEnumValue("rightBrace") - RIGHT_BRACE("rightBrace"), - - /** - * Bracket Pair Shape - * - */ - @XmlEnumValue("bracketPair") - BRACKET_PAIR("bracketPair"), - - /** - * Brace Pair Shape - * - */ - @XmlEnumValue("bracePair") - BRACE_PAIR("bracePair"), - - /** - * Straight Connector 1 Shape - * - */ - @XmlEnumValue("straightConnector1") - STRAIGHT_CONNECTOR_1("straightConnector1"), - - /** - * Bent Connector 2 Shape - * - */ - @XmlEnumValue("bentConnector2") - BENT_CONNECTOR_2("bentConnector2"), - - /** - * Bent Connector 3 Shape - * - */ - @XmlEnumValue("bentConnector3") - BENT_CONNECTOR_3("bentConnector3"), - - /** - * Bent Connector 4 Shape - * - */ - @XmlEnumValue("bentConnector4") - BENT_CONNECTOR_4("bentConnector4"), - - /** - * Bent Connector 5 Shape - * - */ - @XmlEnumValue("bentConnector5") - BENT_CONNECTOR_5("bentConnector5"), - - /** - * Curved Connector 2 Shape - * - */ - @XmlEnumValue("curvedConnector2") - CURVED_CONNECTOR_2("curvedConnector2"), - - /** - * Curved Connector 3 Shape - * - */ - @XmlEnumValue("curvedConnector3") - CURVED_CONNECTOR_3("curvedConnector3"), - - /** - * Curved Connector 4 Shape - * - */ - @XmlEnumValue("curvedConnector4") - CURVED_CONNECTOR_4("curvedConnector4"), - - /** - * Curved Connector 5 Shape - * - */ - @XmlEnumValue("curvedConnector5") - CURVED_CONNECTOR_5("curvedConnector5"), - - /** - * Callout 1 Shape - * - */ - @XmlEnumValue("callout1") - CALLOUT_1("callout1"), - - /** - * Callout 2 Shape - * - */ - @XmlEnumValue("callout2") - CALLOUT_2("callout2"), - - /** - * Callout 3 Shape - * - */ - @XmlEnumValue("callout3") - CALLOUT_3("callout3"), - - /** - * Callout 1 Shape - * - */ - @XmlEnumValue("accentCallout1") - ACCENT_CALLOUT_1("accentCallout1"), - - /** - * Callout 2 Shape - * - */ - @XmlEnumValue("accentCallout2") - ACCENT_CALLOUT_2("accentCallout2"), - - /** - * Callout 3 Shape - * - */ - @XmlEnumValue("accentCallout3") - ACCENT_CALLOUT_3("accentCallout3"), - - /** - * Callout 1 with Border Shape - * - */ - @XmlEnumValue("borderCallout1") - BORDER_CALLOUT_1("borderCallout1"), - - /** - * Callout 2 with Border Shape - * - */ - @XmlEnumValue("borderCallout2") - BORDER_CALLOUT_2("borderCallout2"), - - /** - * Callout 3 with Border Shape - * - */ - @XmlEnumValue("borderCallout3") - BORDER_CALLOUT_3("borderCallout3"), - - /** - * Callout 1 with Border and Accent Shape - * - */ - @XmlEnumValue("accentBorderCallout1") - ACCENT_BORDER_CALLOUT_1("accentBorderCallout1"), - - /** - * Callout 2 with Border and Accent Shape - * - */ - @XmlEnumValue("accentBorderCallout2") - ACCENT_BORDER_CALLOUT_2("accentBorderCallout2"), - - /** - * Callout 3 with Border and Accent Shape - * - */ - @XmlEnumValue("accentBorderCallout3") - ACCENT_BORDER_CALLOUT_3("accentBorderCallout3"), - - /** - * Callout Wedge Rectangle Shape - * - */ - @XmlEnumValue("wedgeRectCallout") - WEDGE_RECT_CALLOUT("wedgeRectCallout"), - - /** - * Callout Wedge Round Rectangle Shape - * - */ - @XmlEnumValue("wedgeRoundRectCallout") - WEDGE_ROUND_RECT_CALLOUT("wedgeRoundRectCallout"), - - /** - * Callout Wedge Ellipse Shape - * - */ - @XmlEnumValue("wedgeEllipseCallout") - WEDGE_ELLIPSE_CALLOUT("wedgeEllipseCallout"), - - /** - * Callout Cloud Shape - * - */ - @XmlEnumValue("cloudCallout") - CLOUD_CALLOUT("cloudCallout"), - - /** - * Cloud Shape - * - */ - @XmlEnumValue("cloud") - CLOUD("cloud"), - - /** - * Ribbon Shape - * - */ - @XmlEnumValue("ribbon") - RIBBON("ribbon"), - - /** - * Ribbon 2 Shape - * - */ - @XmlEnumValue("ribbon2") - RIBBON_2("ribbon2"), - - /** - * Ellipse Ribbon Shape - * - */ - @XmlEnumValue("ellipseRibbon") - ELLIPSE_RIBBON("ellipseRibbon"), - - /** - * Ellipse Ribbon 2 Shape - * - */ - @XmlEnumValue("ellipseRibbon2") - ELLIPSE_RIBBON_2("ellipseRibbon2"), - - /** - * Left Right Ribbon Shape - * - */ - @XmlEnumValue("leftRightRibbon") - LEFT_RIGHT_RIBBON("leftRightRibbon"), - - /** - * Vertical Scroll Shape - * - */ - @XmlEnumValue("verticalScroll") - VERTICAL_SCROLL("verticalScroll"), - - /** - * Horizontal Scroll Shape - * - */ - @XmlEnumValue("horizontalScroll") - HORIZONTAL_SCROLL("horizontalScroll"), - - /** - * Wave Shape - * - */ - @XmlEnumValue("wave") - WAVE("wave"), - - /** - * Double Wave Shape - * - */ - @XmlEnumValue("doubleWave") - DOUBLE_WAVE("doubleWave"), - - /** - * Plus Shape - * - */ - @XmlEnumValue("plus") - PLUS("plus"), - - /** - * Process Flow Shape - * - */ - @XmlEnumValue("flowChartProcess") - FLOW_CHART_PROCESS("flowChartProcess"), - - /** - * Decision Flow Shape - * - */ - @XmlEnumValue("flowChartDecision") - FLOW_CHART_DECISION("flowChartDecision"), - - /** - * Input Output Flow Shape - * - */ - @XmlEnumValue("flowChartInputOutput") - FLOW_CHART_INPUT_OUTPUT("flowChartInputOutput"), - - /** - * Predefined Process Flow Shape - * - */ - @XmlEnumValue("flowChartPredefinedProcess") - FLOW_CHART_PREDEFINED_PROCESS("flowChartPredefinedProcess"), - - /** - * Internal Storage Flow Shape - * - */ - @XmlEnumValue("flowChartInternalStorage") - FLOW_CHART_INTERNAL_STORAGE("flowChartInternalStorage"), - - /** - * Document Flow Shape - * - */ - @XmlEnumValue("flowChartDocument") - FLOW_CHART_DOCUMENT("flowChartDocument"), - - /** - * Multi-Document Flow Shape - * - */ - @XmlEnumValue("flowChartMultidocument") - FLOW_CHART_MULTIDOCUMENT("flowChartMultidocument"), - - /** - * Terminator Flow Shape - * - */ - @XmlEnumValue("flowChartTerminator") - FLOW_CHART_TERMINATOR("flowChartTerminator"), - - /** - * Preparation Flow Shape - * - */ - @XmlEnumValue("flowChartPreparation") - FLOW_CHART_PREPARATION("flowChartPreparation"), - - /** - * Manual Input Flow Shape - * - */ - @XmlEnumValue("flowChartManualInput") - FLOW_CHART_MANUAL_INPUT("flowChartManualInput"), - - /** - * Manual Operation Flow Shape - * - */ - @XmlEnumValue("flowChartManualOperation") - FLOW_CHART_MANUAL_OPERATION("flowChartManualOperation"), - - /** - * Connector Flow Shape - * - */ - @XmlEnumValue("flowChartConnector") - FLOW_CHART_CONNECTOR("flowChartConnector"), - - /** - * Punched Card Flow Shape - * - */ - @XmlEnumValue("flowChartPunchedCard") - FLOW_CHART_PUNCHED_CARD("flowChartPunchedCard"), - - /** - * Punched Tape Flow Shape - * - */ - @XmlEnumValue("flowChartPunchedTape") - FLOW_CHART_PUNCHED_TAPE("flowChartPunchedTape"), - - /** - * Summing Junction Flow Shape - * - */ - @XmlEnumValue("flowChartSummingJunction") - FLOW_CHART_SUMMING_JUNCTION("flowChartSummingJunction"), - - /** - * Or Flow Shape - * - */ - @XmlEnumValue("flowChartOr") - FLOW_CHART_OR("flowChartOr"), - - /** - * Collate Flow Shape - * - */ - @XmlEnumValue("flowChartCollate") - FLOW_CHART_COLLATE("flowChartCollate"), - - /** - * Sort Flow Shape - * - */ - @XmlEnumValue("flowChartSort") - FLOW_CHART_SORT("flowChartSort"), - - /** - * Extract Flow Shape - * - */ - @XmlEnumValue("flowChartExtract") - FLOW_CHART_EXTRACT("flowChartExtract"), - - /** - * Merge Flow Shape - * - */ - @XmlEnumValue("flowChartMerge") - FLOW_CHART_MERGE("flowChartMerge"), - - /** - * Offline Storage Flow Shape - * - */ - @XmlEnumValue("flowChartOfflineStorage") - FLOW_CHART_OFFLINE_STORAGE("flowChartOfflineStorage"), - - /** - * Online Storage Flow Shape - * - */ - @XmlEnumValue("flowChartOnlineStorage") - FLOW_CHART_ONLINE_STORAGE("flowChartOnlineStorage"), - - /** - * Magnetic Tape Flow Shape - * - */ - @XmlEnumValue("flowChartMagneticTape") - FLOW_CHART_MAGNETIC_TAPE("flowChartMagneticTape"), - - /** - * Magnetic Disk Flow Shape - * - */ - @XmlEnumValue("flowChartMagneticDisk") - FLOW_CHART_MAGNETIC_DISK("flowChartMagneticDisk"), - - /** - * Magnetic Drum Flow Shape - * - */ - @XmlEnumValue("flowChartMagneticDrum") - FLOW_CHART_MAGNETIC_DRUM("flowChartMagneticDrum"), - - /** - * Display Flow Shape - * - */ - @XmlEnumValue("flowChartDisplay") - FLOW_CHART_DISPLAY("flowChartDisplay"), - - /** - * Delay Flow Shape - * - */ - @XmlEnumValue("flowChartDelay") - FLOW_CHART_DELAY("flowChartDelay"), - - /** - * Alternate Process Flow Shape - * - */ - @XmlEnumValue("flowChartAlternateProcess") - FLOW_CHART_ALTERNATE_PROCESS("flowChartAlternateProcess"), - - /** - * Off-Page Connector Flow Shape - * - */ - @XmlEnumValue("flowChartOffpageConnector") - FLOW_CHART_OFFPAGE_CONNECTOR("flowChartOffpageConnector"), - - /** - * Blank Button Shape - * - */ - @XmlEnumValue("actionButtonBlank") - ACTION_BUTTON_BLANK("actionButtonBlank"), - - /** - * Home Button Shape - * - */ - @XmlEnumValue("actionButtonHome") - ACTION_BUTTON_HOME("actionButtonHome"), - - /** - * Help Button Shape - * - */ - @XmlEnumValue("actionButtonHelp") - ACTION_BUTTON_HELP("actionButtonHelp"), - - /** - * Information Button Shape - * - */ - @XmlEnumValue("actionButtonInformation") - ACTION_BUTTON_INFORMATION("actionButtonInformation"), - - /** - * Forward or Next Button Shape - * - */ - @XmlEnumValue("actionButtonForwardNext") - ACTION_BUTTON_FORWARD_NEXT("actionButtonForwardNext"), - - /** - * Back or Previous Button Shape - * - */ - @XmlEnumValue("actionButtonBackPrevious") - ACTION_BUTTON_BACK_PREVIOUS("actionButtonBackPrevious"), - - /** - * End Button Shape - * - */ - @XmlEnumValue("actionButtonEnd") - ACTION_BUTTON_END("actionButtonEnd"), - - /** - * Beginning Button Shape - * - */ - @XmlEnumValue("actionButtonBeginning") - ACTION_BUTTON_BEGINNING("actionButtonBeginning"), - - /** - * Return Button Shape - * - */ - @XmlEnumValue("actionButtonReturn") - ACTION_BUTTON_RETURN("actionButtonReturn"), - - /** - * Document Button Shape - * - */ - @XmlEnumValue("actionButtonDocument") - ACTION_BUTTON_DOCUMENT("actionButtonDocument"), - - /** - * Sound Button Shape - * - */ - @XmlEnumValue("actionButtonSound") - ACTION_BUTTON_SOUND("actionButtonSound"), - - /** - * Movie Button Shape - * - */ - @XmlEnumValue("actionButtonMovie") - ACTION_BUTTON_MOVIE("actionButtonMovie"), - - /** - * Gear 6 Shape - * - */ - @XmlEnumValue("gear6") - GEAR_6("gear6"), - - /** - * Gear 9 Shape - * - */ - @XmlEnumValue("gear9") - GEAR_9("gear9"), - - /** - * Funnel Shape - * - */ - @XmlEnumValue("funnel") - FUNNEL("funnel"), - - /** - * Plus Math Shape - * - */ - @XmlEnumValue("mathPlus") - MATH_PLUS("mathPlus"), - - /** - * Minus Math Shape - * - */ - @XmlEnumValue("mathMinus") - MATH_MINUS("mathMinus"), - - /** - * Multiply Math Shape - * - */ - @XmlEnumValue("mathMultiply") - MATH_MULTIPLY("mathMultiply"), - - /** - * Divide Math Shape - * - */ - @XmlEnumValue("mathDivide") - MATH_DIVIDE("mathDivide"), - - /** - * Equal Math Shape - * - */ - @XmlEnumValue("mathEqual") - MATH_EQUAL("mathEqual"), - - /** - * Not Equal Math Shape - * - */ - @XmlEnumValue("mathNotEqual") - MATH_NOT_EQUAL("mathNotEqual"), - - /** - * Corner Tabs Shape - * - */ - @XmlEnumValue("cornerTabs") - CORNER_TABS("cornerTabs"), - - /** - * Square Tabs Shape - * - */ - @XmlEnumValue("squareTabs") - SQUARE_TABS("squareTabs"), - - /** - * Plaque Tabs Shape - * - */ - @XmlEnumValue("plaqueTabs") - PLAQUE_TABS("plaqueTabs"), - - /** - * Chart X Shape - * - */ - @XmlEnumValue("chartX") - CHART_X("chartX"), - - /** - * Chart Star Shape - * - */ - @XmlEnumValue("chartStar") - CHART_STAR("chartStar"), - - /** - * Chart Plus Shape - * - */ - @XmlEnumValue("chartPlus") - CHART_PLUS("chartPlus"); - private final String value; - - STShapeType(String v) { - value = v; - } - - public String value() { - return value; - } - - public static STShapeType fromValue(String v) { - for (STShapeType c: STShapeType.values()) { - if (c.value.equals(v)) { - return c; - } - } - throw new IllegalArgumentException(v); - } - -} diff --git a/src/java/org/apache/poi/sl/draw/binding/STTextShapeType.java b/src/java/org/apache/poi/sl/draw/binding/STTextShapeType.java deleted file mode 100644 index 584d971a5..000000000 --- a/src/java/org/apache/poi/sl/draw/binding/STTextShapeType.java +++ /dev/null @@ -1,389 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.draw.binding; - -import javax.xml.bind.annotation.XmlEnum; -import javax.xml.bind.annotation.XmlEnumValue; -import javax.xml.bind.annotation.XmlType; - - -/** - *

    Java class for ST_TextShapeType. - * - *

    The following schema fragment specifies the expected content contained within this class. - *

    - *

    - * <simpleType name="ST_TextShapeType">
    - *   <restriction base="{http://www.w3.org/2001/XMLSchema}token">
    - *     <enumeration value="textNoShape"/>
    - *     <enumeration value="textPlain"/>
    - *     <enumeration value="textStop"/>
    - *     <enumeration value="textTriangle"/>
    - *     <enumeration value="textTriangleInverted"/>
    - *     <enumeration value="textChevron"/>
    - *     <enumeration value="textChevronInverted"/>
    - *     <enumeration value="textRingInside"/>
    - *     <enumeration value="textRingOutside"/>
    - *     <enumeration value="textArchUp"/>
    - *     <enumeration value="textArchDown"/>
    - *     <enumeration value="textCircle"/>
    - *     <enumeration value="textButton"/>
    - *     <enumeration value="textArchUpPour"/>
    - *     <enumeration value="textArchDownPour"/>
    - *     <enumeration value="textCirclePour"/>
    - *     <enumeration value="textButtonPour"/>
    - *     <enumeration value="textCurveUp"/>
    - *     <enumeration value="textCurveDown"/>
    - *     <enumeration value="textCanUp"/>
    - *     <enumeration value="textCanDown"/>
    - *     <enumeration value="textWave1"/>
    - *     <enumeration value="textWave2"/>
    - *     <enumeration value="textDoubleWave1"/>
    - *     <enumeration value="textWave4"/>
    - *     <enumeration value="textInflate"/>
    - *     <enumeration value="textDeflate"/>
    - *     <enumeration value="textInflateBottom"/>
    - *     <enumeration value="textDeflateBottom"/>
    - *     <enumeration value="textInflateTop"/>
    - *     <enumeration value="textDeflateTop"/>
    - *     <enumeration value="textDeflateInflate"/>
    - *     <enumeration value="textDeflateInflateDeflate"/>
    - *     <enumeration value="textFadeRight"/>
    - *     <enumeration value="textFadeLeft"/>
    - *     <enumeration value="textFadeUp"/>
    - *     <enumeration value="textFadeDown"/>
    - *     <enumeration value="textSlantUp"/>
    - *     <enumeration value="textSlantDown"/>
    - *     <enumeration value="textCascadeUp"/>
    - *     <enumeration value="textCascadeDown"/>
    - *   </restriction>
    - * </simpleType>
    - * 
    - * - */ -@XmlType(name = "ST_TextShapeType", namespace = "http://schemas.openxmlformats.org/drawingml/2006/main") -@XmlEnum -public enum STTextShapeType { - - - /** - * No Text Shape - * - */ - @XmlEnumValue("textNoShape") - TEXT_NO_SHAPE("textNoShape"), - - /** - * Plain Text Shape - * - */ - @XmlEnumValue("textPlain") - TEXT_PLAIN("textPlain"), - - /** - * Stop Sign Text Shape - * - */ - @XmlEnumValue("textStop") - TEXT_STOP("textStop"), - - /** - * Triangle Text Shape - * - */ - @XmlEnumValue("textTriangle") - TEXT_TRIANGLE("textTriangle"), - - /** - * Inverted Triangle Text Shape - * - */ - @XmlEnumValue("textTriangleInverted") - TEXT_TRIANGLE_INVERTED("textTriangleInverted"), - - /** - * Chevron Text Shape - * - */ - @XmlEnumValue("textChevron") - TEXT_CHEVRON("textChevron"), - - /** - * Inverted Chevron Text Shape - * - */ - @XmlEnumValue("textChevronInverted") - TEXT_CHEVRON_INVERTED("textChevronInverted"), - - /** - * Inside Ring Text Shape - * - */ - @XmlEnumValue("textRingInside") - TEXT_RING_INSIDE("textRingInside"), - - /** - * Outside Ring Text Shape - * - */ - @XmlEnumValue("textRingOutside") - TEXT_RING_OUTSIDE("textRingOutside"), - - /** - * Upward Arch Text Shape - * - */ - @XmlEnumValue("textArchUp") - TEXT_ARCH_UP("textArchUp"), - - /** - * Downward Arch Text Shape - * - */ - @XmlEnumValue("textArchDown") - TEXT_ARCH_DOWN("textArchDown"), - - /** - * Circle Text Shape - * - */ - @XmlEnumValue("textCircle") - TEXT_CIRCLE("textCircle"), - - /** - * Button Text Shape - * - */ - @XmlEnumValue("textButton") - TEXT_BUTTON("textButton"), - - /** - * Upward Pour Arch Text Shape - * - */ - @XmlEnumValue("textArchUpPour") - TEXT_ARCH_UP_POUR("textArchUpPour"), - - /** - * Downward Pour Arch Text Shape - * - */ - @XmlEnumValue("textArchDownPour") - TEXT_ARCH_DOWN_POUR("textArchDownPour"), - - /** - * Circle Pour Text Shape - * - */ - @XmlEnumValue("textCirclePour") - TEXT_CIRCLE_POUR("textCirclePour"), - - /** - * Button Pour Text Shape - * - */ - @XmlEnumValue("textButtonPour") - TEXT_BUTTON_POUR("textButtonPour"), - - /** - * Upward Curve Text Shape - * - */ - @XmlEnumValue("textCurveUp") - TEXT_CURVE_UP("textCurveUp"), - - /** - * Downward Curve Text Shape - * - */ - @XmlEnumValue("textCurveDown") - TEXT_CURVE_DOWN("textCurveDown"), - - /** - * Upward Can Text Shape - * - */ - @XmlEnumValue("textCanUp") - TEXT_CAN_UP("textCanUp"), - - /** - * Downward Can Text Shape - * - */ - @XmlEnumValue("textCanDown") - TEXT_CAN_DOWN("textCanDown"), - - /** - * Wave 1 Text Shape - * - */ - @XmlEnumValue("textWave1") - TEXT_WAVE_1("textWave1"), - - /** - * Wave 2 Text Shape - * - */ - @XmlEnumValue("textWave2") - TEXT_WAVE_2("textWave2"), - - /** - * Double Wave 1 Text Shape - * - */ - @XmlEnumValue("textDoubleWave1") - TEXT_DOUBLE_WAVE_1("textDoubleWave1"), - - /** - * Wave 4 Text Shape - * - */ - @XmlEnumValue("textWave4") - TEXT_WAVE_4("textWave4"), - - /** - * Inflate Text Shape - * - */ - @XmlEnumValue("textInflate") - TEXT_INFLATE("textInflate"), - - /** - * Deflate Text Shape - * - */ - @XmlEnumValue("textDeflate") - TEXT_DEFLATE("textDeflate"), - - /** - * Bottom Inflate Text Shape - * - */ - @XmlEnumValue("textInflateBottom") - TEXT_INFLATE_BOTTOM("textInflateBottom"), - - /** - * Bottom Deflate Text Shape - * - */ - @XmlEnumValue("textDeflateBottom") - TEXT_DEFLATE_BOTTOM("textDeflateBottom"), - - /** - * Top Inflate Text Shape - * - */ - @XmlEnumValue("textInflateTop") - TEXT_INFLATE_TOP("textInflateTop"), - - /** - * Top Deflate Text Shape - * - */ - @XmlEnumValue("textDeflateTop") - TEXT_DEFLATE_TOP("textDeflateTop"), - - /** - * Deflate-Inflate Text Shape - * - */ - @XmlEnumValue("textDeflateInflate") - TEXT_DEFLATE_INFLATE("textDeflateInflate"), - - /** - * Deflate-Inflate-Deflate Text Shape - * - */ - @XmlEnumValue("textDeflateInflateDeflate") - TEXT_DEFLATE_INFLATE_DEFLATE("textDeflateInflateDeflate"), - - /** - * Right Fade Text Shape - * - */ - @XmlEnumValue("textFadeRight") - TEXT_FADE_RIGHT("textFadeRight"), - - /** - * Left Fade Text Shape - * - */ - @XmlEnumValue("textFadeLeft") - TEXT_FADE_LEFT("textFadeLeft"), - - /** - * Upward Fade Text Shape - * - */ - @XmlEnumValue("textFadeUp") - TEXT_FADE_UP("textFadeUp"), - - /** - * Downward Fade Text Shape - * - */ - @XmlEnumValue("textFadeDown") - TEXT_FADE_DOWN("textFadeDown"), - - /** - * Upward Slant Text Shape - * - */ - @XmlEnumValue("textSlantUp") - TEXT_SLANT_UP("textSlantUp"), - - /** - * Downward Slant Text Shape - * - */ - @XmlEnumValue("textSlantDown") - TEXT_SLANT_DOWN("textSlantDown"), - - /** - * Upward Cascade Text Shape - * - */ - @XmlEnumValue("textCascadeUp") - TEXT_CASCADE_UP("textCascadeUp"), - - /** - * Downward Cascade Text Shape - * - */ - @XmlEnumValue("textCascadeDown") - TEXT_CASCADE_DOWN("textCascadeDown"); - private final String value; - - STTextShapeType(String v) { - value = v; - } - - public String value() { - return value; - } - - public static STTextShapeType fromValue(String v) { - for (STTextShapeType c: STTextShapeType.values()) { - if (c.value.equals(v)) { - return c; - } - } - throw new IllegalArgumentException(v); - } - -} diff --git a/src/java/org/apache/poi/sl/draw/geom/AbsExpression.java b/src/java/org/apache/poi/sl/draw/geom/AbsExpression.java deleted file mode 100644 index 0f94e14b6..000000000 --- a/src/java/org/apache/poi/sl/draw/geom/AbsExpression.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.sl.draw.geom; - -import java.util.regex.Matcher; - -/** - * Absolute Value Formula - * - * @author Yegor Kozlov - */ -public class AbsExpression implements Expression { - private String arg; - - AbsExpression(Matcher m){ - arg = m.group(1); - } - - public double evaluate(Context ctx){ - double val = ctx.getValue(arg); - return Math.abs(val); - } - -} diff --git a/src/java/org/apache/poi/sl/draw/geom/AddDivideExpression.java b/src/java/org/apache/poi/sl/draw/geom/AddDivideExpression.java deleted file mode 100644 index 2a01de449..000000000 --- a/src/java/org/apache/poi/sl/draw/geom/AddDivideExpression.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.sl.draw.geom; - -import java.util.regex.Matcher; - -/** - * Add Divide Formula - * - * @author Yegor Kozlov - */ -public class AddDivideExpression implements Expression { - private String arg1, arg2, arg3; - - AddDivideExpression(Matcher m){ - arg1 = m.group(1); - arg2 = m.group(2); - arg3 = m.group(3); - } - - public double evaluate(Context ctx){ - double x = ctx.getValue(arg1); - double y = ctx.getValue(arg2); - double z = ctx.getValue(arg3); - return (x + y ) / z; - } - -} diff --git a/src/java/org/apache/poi/sl/draw/geom/AddSubtractExpression.java b/src/java/org/apache/poi/sl/draw/geom/AddSubtractExpression.java deleted file mode 100644 index 5d5f1e635..000000000 --- a/src/java/org/apache/poi/sl/draw/geom/AddSubtractExpression.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.sl.draw.geom; - -import java.util.regex.Matcher; - -/** - * Add Subtract Formula - * - * @author Yegor Kozlov - */ -public class AddSubtractExpression implements Expression { - private String arg1, arg2, arg3; - - AddSubtractExpression(Matcher m){ - arg1 = m.group(1); - arg2 = m.group(2); - arg3 = m.group(3); - } - - public double evaluate(Context ctx){ - double x = ctx.getValue(arg1); - double y = ctx.getValue(arg2); - double z = ctx.getValue(arg3); - return (x + y ) - z; - } - -} diff --git a/src/java/org/apache/poi/sl/draw/geom/AdjustValue.java b/src/java/org/apache/poi/sl/draw/geom/AdjustValue.java deleted file mode 100644 index 8a2f0a456..000000000 --- a/src/java/org/apache/poi/sl/draw/geom/AdjustValue.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.sl.draw.geom; - -import org.apache.poi.sl.draw.binding.CTGeomGuide; - -/** - * Represents a shape adjust values (see section 20.1.9.5 in the spec) - * - * @author Yegor Kozlov - */ -public class AdjustValue extends Guide { - - public AdjustValue(CTGeomGuide gd) { - super(gd.getName(), gd.getFmla()); - } - - @Override - public double evaluate(Context ctx){ - String name = getName(); - Guide adj = ctx.getAdjustValue(name); - if(adj != null) { - return adj.evaluate(ctx); - } - return super.evaluate(ctx); - } - -} diff --git a/src/java/org/apache/poi/sl/draw/geom/ArcTanExpression.java b/src/java/org/apache/poi/sl/draw/geom/ArcTanExpression.java deleted file mode 100644 index 9044e8ad3..000000000 --- a/src/java/org/apache/poi/sl/draw/geom/ArcTanExpression.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.sl.draw.geom; - -import java.util.regex.Matcher; - -/** - * Date: 10/24/11 - * - * @author Yegor Kozlov - */ -public class ArcTanExpression implements Expression { - private String arg1, arg2; - - ArcTanExpression(Matcher m){ - arg1 = m.group(1); - arg2 = m.group(2); - } - - public double evaluate(Context ctx){ - double x = ctx.getValue(arg1); - double y = ctx.getValue(arg2); - return Math.atan(y / x); - } - -} diff --git a/src/java/org/apache/poi/sl/draw/geom/ArcToCommand.java b/src/java/org/apache/poi/sl/draw/geom/ArcToCommand.java deleted file mode 100644 index 18531d7ed..000000000 --- a/src/java/org/apache/poi/sl/draw/geom/ArcToCommand.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.sl.draw.geom; - -import java.awt.geom.Arc2D; -import java.awt.geom.Path2D; -import java.awt.geom.Point2D; - -import org.apache.poi.sl.draw.binding.CTPath2DArcTo; - -/** - * ArcTo command within a shape path in DrawingML: - * - * - * - * Where wr and wh are the height and width radiuses - * of the supposed circle being used to draw the arc. This gives the circle - * a total height of (2 * hR) and a total width of (2 * wR) - * - * stAng is the start angle and swAng is the swing angle - * - * @author Yegor Kozlov - */ -public class ArcToCommand implements PathCommand { - private String hr, wr, stAng, swAng; - - ArcToCommand(CTPath2DArcTo arc){ - hr = arc.getHR().toString(); - wr = arc.getWR().toString(); - stAng = arc.getStAng().toString(); - swAng = arc.getSwAng().toString(); - } - - public void execute(Path2D.Double path, Context ctx){ - double rx = ctx.getValue(wr); - double ry = ctx.getValue(hr); - double start = ctx.getValue(stAng) / 60000; - double extent = ctx.getValue(swAng) / 60000; - Point2D pt = path.getCurrentPoint(); - double x0 = pt.getX() - rx - rx * Math.cos(Math.toRadians(start)); - double y0 = pt.getY() - ry - ry * Math.sin(Math.toRadians(start)); - - Arc2D arc = new Arc2D.Double( - x0, - y0, - 2 * rx, 2 * ry, - -start, -extent, - Arc2D.OPEN); - path.append(arc, true); - } -} diff --git a/src/java/org/apache/poi/sl/draw/geom/ClosePathCommand.java b/src/java/org/apache/poi/sl/draw/geom/ClosePathCommand.java deleted file mode 100644 index 66b35ed58..000000000 --- a/src/java/org/apache/poi/sl/draw/geom/ClosePathCommand.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.sl.draw.geom; - -import java.awt.geom.Path2D; - -/** - * Date: 10/25/11 - * - * @author Yegor Kozlov - */ -public class ClosePathCommand implements PathCommand { - - ClosePathCommand(){ - } - - public void execute(Path2D.Double path, Context ctx){ - path.closePath(); - } -} diff --git a/src/java/org/apache/poi/sl/draw/geom/Context.java b/src/java/org/apache/poi/sl/draw/geom/Context.java deleted file mode 100644 index 8fd5147ed..000000000 --- a/src/java/org/apache/poi/sl/draw/geom/Context.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.sl.draw.geom; - -import java.awt.geom.Rectangle2D; -import java.util.HashMap; -import java.util.Map; - -/** - * Date: 10/24/11 - * - * @author Yegor Kozlov - */ -public class Context { - final Map _ctx = new HashMap(); - final IAdjustableShape _props; - final Rectangle2D _anchor; - - public Context(CustomGeometry geom, Rectangle2D anchor, IAdjustableShape props){ - _props = props; - _anchor = anchor; - for(Guide gd : geom.adjusts) evaluate(gd); - for(Guide gd : geom.guides) evaluate(gd); - } - - public Rectangle2D getShapeAnchor(){ - return _anchor; - } - - public Guide getAdjustValue(String name){ - return _props.getAdjustValue(name); - } - - public double getValue(String key){ - if(key.matches("(\\+|-)?\\d+")){ - return Double.parseDouble(key); - } - - Formula builtIn = Formula.builtInFormulas.get(key); - if(builtIn != null){ - return builtIn.evaluate(this); - } - - if(!_ctx.containsKey(key)) { - throw new RuntimeException("undefined variable: " + key); - } - - return _ctx.get(key); - } - - public double evaluate(Formula fmla){ - double result = fmla.evaluate(this); - String key = fmla.getName(); - if(key != null) _ctx.put(key, result); - return result; - } -} diff --git a/src/java/org/apache/poi/sl/draw/geom/CosExpression.java b/src/java/org/apache/poi/sl/draw/geom/CosExpression.java deleted file mode 100644 index 56373d919..000000000 --- a/src/java/org/apache/poi/sl/draw/geom/CosExpression.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.sl.draw.geom; - -import java.util.regex.Matcher; - -/** - * Date: 10/24/11 - * - * @author Yegor Kozlov - */ -public class CosExpression implements Expression { - private String arg1, arg2; - - CosExpression(Matcher m){ - arg1 = m.group(1); - arg2 = m.group(2); - } - - public double evaluate(Context ctx){ - double x = ctx.getValue(arg1); - double y = ctx.getValue(arg2)/ 60000; - return x * Math.cos(Math.toRadians(y)); - } - -} diff --git a/src/java/org/apache/poi/sl/draw/geom/CosineArcTanExpression.java b/src/java/org/apache/poi/sl/draw/geom/CosineArcTanExpression.java deleted file mode 100644 index 4bed9b72d..000000000 --- a/src/java/org/apache/poi/sl/draw/geom/CosineArcTanExpression.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.sl.draw.geom; - -import java.util.regex.Matcher; - -/** - * Date: 10/24/11 - * - * @author Yegor Kozlov - */ -public class CosineArcTanExpression implements Expression { - private String arg1, arg2, arg3; - - CosineArcTanExpression(Matcher m){ - arg1 = m.group(1); - arg2 = m.group(2); - arg3 = m.group(3); - } - - public double evaluate(Context ctx){ - double x = ctx.getValue(arg1); - double y = ctx.getValue(arg2); - double z = ctx.getValue(arg3); - return x*Math.cos(Math.atan(z / y)); - } - -} diff --git a/src/java/org/apache/poi/sl/draw/geom/CurveToCommand.java b/src/java/org/apache/poi/sl/draw/geom/CurveToCommand.java deleted file mode 100644 index 6c6361aed..000000000 --- a/src/java/org/apache/poi/sl/draw/geom/CurveToCommand.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.sl.draw.geom; - -import java.awt.geom.Path2D; - -import org.apache.poi.sl.draw.binding.CTAdjPoint2D; - -/** - * Date: 10/25/11 - * - * @author Yegor Kozlov - */ -public class CurveToCommand implements PathCommand { - private String arg1, arg2, arg3, arg4, arg5, arg6; - - CurveToCommand(CTAdjPoint2D pt1, CTAdjPoint2D pt2, CTAdjPoint2D pt3){ - arg1 = pt1.getX().toString(); - arg2 = pt1.getY().toString(); - arg3 = pt2.getX().toString(); - arg4 = pt2.getY().toString(); - arg5 = pt3.getX().toString(); - arg6 = pt3.getY().toString(); - } - - public void execute(Path2D.Double path, Context ctx){ - double x1 = ctx.getValue(arg1); - double y1 = ctx.getValue(arg2); - double x2 = ctx.getValue(arg3); - double y2 = ctx.getValue(arg4); - double x3 = ctx.getValue(arg5); - double y3 = ctx.getValue(arg6); - path.curveTo(x1, y1, x2, y2, x3, y3); - } -} diff --git a/src/java/org/apache/poi/sl/draw/geom/CustomGeometry.java b/src/java/org/apache/poi/sl/draw/geom/CustomGeometry.java deleted file mode 100644 index ce1b26c49..000000000 --- a/src/java/org/apache/poi/sl/draw/geom/CustomGeometry.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.sl.draw.geom; - -import java.util.*; - -import org.apache.poi.sl.draw.binding.*; - -/** - * Definition of a custom geometric shape - * - * @author Yegor Kozlov - */ -public class CustomGeometry implements Iterable{ - List adjusts = new ArrayList(); - List guides = new ArrayList(); - List paths = new ArrayList(); - Path textBounds; - - public CustomGeometry(CTCustomGeometry2D geom) { - CTGeomGuideList avLst = geom.getAvLst(); - if(avLst != null) { - for(CTGeomGuide gd : avLst.getGd()){ - adjusts.add(new AdjustValue(gd)); - } - } - - CTGeomGuideList gdLst = geom.getGdLst(); - if(gdLst != null) { - for(CTGeomGuide gd : gdLst.getGd()){ - guides.add(new Guide(gd)); - } - } - - CTPath2DList pathLst = geom.getPathLst(); - if(pathLst != null) { - for(CTPath2D spPath : pathLst.getPath()){ - paths.add(new Path(spPath)); - } - } - - CTGeomRect rect = geom.getRect(); - if(rect != null) { - textBounds = new Path(); - textBounds.addCommand( - new MoveToCommand(rect.getL().toString(), rect.getT().toString())); - textBounds.addCommand( - new LineToCommand(rect.getR().toString(), rect.getT().toString())); - textBounds.addCommand( - new LineToCommand(rect.getR().toString(), rect.getB().toString())); - textBounds.addCommand( - new LineToCommand(rect.getL().toString(), rect.getB().toString())); - textBounds.addCommand( - new ClosePathCommand()); - } - } - - public Iterator iterator() { - return paths.iterator(); - } - - public Path getTextBounds(){ - return textBounds; - } -} diff --git a/src/java/org/apache/poi/sl/draw/geom/Expression.java b/src/java/org/apache/poi/sl/draw/geom/Expression.java deleted file mode 100644 index 2403c85a0..000000000 --- a/src/java/org/apache/poi/sl/draw/geom/Expression.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.sl.draw.geom; - -/** - * Date: 10/24/11 - * - * @author Yegor Kozlov - */ -public interface Expression { - - double evaluate(Context ctx); - -} diff --git a/src/java/org/apache/poi/sl/draw/geom/ExpressionParser.java b/src/java/org/apache/poi/sl/draw/geom/ExpressionParser.java deleted file mode 100644 index 61ab98b8a..000000000 --- a/src/java/org/apache/poi/sl/draw/geom/ExpressionParser.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.sl.draw.geom; - -import java.lang.reflect.Constructor; -import java.util.HashMap; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * A simple regexp-based parser of shape guide formulas in DrawingML - */ -public class ExpressionParser { - private static final Map impls = - new HashMap(); - - private static class ExpressionEntry { - final Pattern regex; - final Constructor con; - ExpressionEntry(String regex, Class cls) - throws SecurityException, NoSuchMethodException { - this.regex = Pattern.compile(regex); - this.con = cls.getDeclaredConstructor(Matcher.class); - impls.put(op(regex), this); - } - } - - static { - try { - new ExpressionEntry("\\*/ +([\\-\\w]+) +([\\-\\w]+) +([\\-\\w]+)", MultiplyDivideExpression.class); - new ExpressionEntry("\\+- +([\\-\\w]+) +([\\-\\w]+) +([\\-\\w]+)( 0)?", AddSubtractExpression.class); - new ExpressionEntry("\\+/ +([\\-\\w]+) +([\\-\\w]+) +([\\-\\w]+)", AddDivideExpression.class); - new ExpressionEntry("\\?: +([\\-\\w]+) +([\\-\\w]+) +([\\-\\w]+)", IfElseExpression.class); - new ExpressionEntry("val +([\\-\\w]+)", LiteralValueExpression.class); - new ExpressionEntry("abs +([\\-\\w]+)", AbsExpression.class); - new ExpressionEntry("sqrt +([\\-\\w]+)", SqrtExpression.class); - new ExpressionEntry("max +([\\-\\w]+) +([\\-\\w]+)", MaxExpression.class); - new ExpressionEntry("min +([\\-\\w]+) +([\\-\\w]+)", MinExpression.class); - new ExpressionEntry("at2 +([\\-\\w]+) +([\\-\\w]+)", ArcTanExpression.class); - new ExpressionEntry("sin +([\\-\\w]+) +([\\-\\w]+)", SinExpression.class); - new ExpressionEntry("cos +([\\-\\w]+) +([\\-\\w]+)", CosExpression.class); - new ExpressionEntry("tan +([\\-\\w]+) +([\\-\\w]+)", TanExpression.class); - new ExpressionEntry("cat2 +([\\-\\w]+) +([\\-\\w]+) +([\\-\\w]+)", CosineArcTanExpression.class); - new ExpressionEntry("sat2 +([\\-\\w]+) +([\\-\\w]+) +([\\-\\w]+)", SinArcTanExpression.class); - new ExpressionEntry("pin +([\\-\\w]+) +([\\-\\w]+) +([\\-\\w]+)", PinExpression.class); - new ExpressionEntry("mod +([\\-\\w]+) +([\\-\\w]+) +([\\-\\w]+)", ModExpression.class); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - private static String op(String str) { - return (str == null || !str.contains(" ")) - ? "" : str.substring(0, str.indexOf(" ")).replace("\\", ""); - } - - public static Expression parse(String str) { - ExpressionEntry ee = impls.get(op(str)); - Matcher m = (ee == null) ? null : ee.regex.matcher(str); - if (m == null || !m.matches()) { - throw new RuntimeException("Unsupported formula: " + str); - } - - try { - return ee.con.newInstance(m); - } catch (Exception e) { - throw new RuntimeException("Unsupported formula: " + str, e); - } - } -} diff --git a/src/java/org/apache/poi/sl/draw/geom/Formula.java b/src/java/org/apache/poi/sl/draw/geom/Formula.java deleted file mode 100644 index 06730ffc4..000000000 --- a/src/java/org/apache/poi/sl/draw/geom/Formula.java +++ /dev/null @@ -1,385 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.sl.draw.geom; - -import java.awt.geom.Rectangle2D; -import java.util.HashMap; -import java.util.Map; - -/** - * A guide formula in DrawingML. - * This is a base class for adjust values, geometric guides and bilt-in guides - * - * @author Yegor Kozlov - */ -public abstract class Formula { - - String getName(){ - return null; - } - - abstract double evaluate(Context ctx); - - static Map builtInFormulas = new HashMap(); - static { - // 3 x 360 / 4 = 270 - builtInFormulas.put("3cd4", new Formula(){ - @Override - double evaluate(Context ctx){ - return 270 * 60000.; - } - - }); - - // 3 x 360 / 8 = 135 - builtInFormulas.put("3cd8", new Formula(){ - @Override - double evaluate(Context ctx){ - return 135 * 60000.; - } - - }); - - // 5 x 360 / 8 = 225 - builtInFormulas.put("5cd8", new Formula(){ - @Override - double evaluate(Context ctx){ - return 270 * 60000.; - } - - }); - - // 7 x 360 / 8 = 315 - builtInFormulas.put("7cd8", new Formula(){ - @Override - double evaluate(Context ctx){ - return 270 * 60000.; - } - - }); - - // bottom - builtInFormulas.put("b", new Formula(){ - @Override - double evaluate(Context ctx){ - Rectangle2D anchor = ctx.getShapeAnchor(); - return anchor.getY() + anchor.getHeight(); - } - - }); - - // 360 / 2 = 180 - builtInFormulas.put("cd2", new Formula(){ - @Override - double evaluate(Context ctx){ - return 180 * 60000.; - } - - }); - - // 360 / 4 = 90 - builtInFormulas.put("cd4", new Formula(){ - @Override - double evaluate(Context ctx){ - return 90 * 60000.; - } - - }); - - // 360 / 8 = 45 - builtInFormulas.put("cd8", new Formula(){ - @Override - double evaluate(Context ctx){ - return 45 * 60000.; - } - - }); - - // horizontal center - builtInFormulas.put("hc", new Formula(){ - @Override - double evaluate(Context ctx){ - Rectangle2D anchor = ctx.getShapeAnchor(); - return anchor.getX() + anchor.getWidth()/2.; - } - - }); - - // height - builtInFormulas.put("h", new Formula(){ - @Override - double evaluate(Context ctx){ - Rectangle2D anchor = ctx.getShapeAnchor(); - return anchor.getHeight(); - } - - }); - - // height / 2 - builtInFormulas.put("hd2", new Formula(){ - @Override - double evaluate(Context ctx){ - Rectangle2D anchor = ctx.getShapeAnchor(); - return anchor.getHeight()/2.; - } - - }); - - // height / 3 - builtInFormulas.put("hd3", new Formula(){ - @Override - double evaluate(Context ctx){ - Rectangle2D anchor = ctx.getShapeAnchor(); - return anchor.getHeight()/3.; - } - - }); - - // height / 4 - builtInFormulas.put("hd4", new Formula(){ - @Override - double evaluate(Context ctx){ - Rectangle2D anchor = ctx.getShapeAnchor(); - return anchor.getHeight()/4.; - } - - }); - - // height / 5 - builtInFormulas.put("hd5", new Formula(){ - @Override - double evaluate(Context ctx){ - Rectangle2D anchor = ctx.getShapeAnchor(); - return anchor.getHeight()/5.; - } - - }); - - // height / 6 - builtInFormulas.put("hd6", new Formula(){ - @Override - double evaluate(Context ctx){ - Rectangle2D anchor = ctx.getShapeAnchor(); - return anchor.getHeight()/6.; - } - - }); - - // height / 8 - builtInFormulas.put("hd8", new Formula(){ - @Override - double evaluate(Context ctx){ - Rectangle2D anchor = ctx.getShapeAnchor(); - return anchor.getHeight()/8.; - } - - }); - - // left - builtInFormulas.put("l", new Formula(){ - @Override - double evaluate(Context ctx){ - Rectangle2D anchor = ctx.getShapeAnchor(); - return anchor.getX(); - } - - }); - - // long side - builtInFormulas.put("ls", new Formula(){ - @Override - double evaluate(Context ctx){ - Rectangle2D anchor = ctx.getShapeAnchor(); - return Math.max(anchor.getWidth(), anchor.getHeight()); - } - - }); - - // right - builtInFormulas.put("r", new Formula(){ - @Override - double evaluate(Context ctx){ - Rectangle2D anchor = ctx.getShapeAnchor(); - return anchor.getX() + anchor.getWidth(); - } - - }); - - // short side - builtInFormulas.put("ss", new Formula(){ - @Override - double evaluate(Context ctx){ - Rectangle2D anchor = ctx.getShapeAnchor(); - return Math.min(anchor.getWidth(), anchor.getHeight()); - } - - }); - - // short side / 2 - builtInFormulas.put("ssd2", new Formula(){ - @Override - double evaluate(Context ctx){ - Rectangle2D anchor = ctx.getShapeAnchor(); - double ss = Math.min(anchor.getWidth(), anchor.getHeight()); - return ss / 2.; - } - }); - - // short side / 4 - builtInFormulas.put("ssd4", new Formula(){ - @Override - double evaluate(Context ctx){ - Rectangle2D anchor = ctx.getShapeAnchor(); - double ss = Math.min(anchor.getWidth(), anchor.getHeight()); - return ss / 4.; - } - }); - - // short side / 6 - builtInFormulas.put("ssd6", new Formula(){ - @Override - double evaluate(Context ctx){ - Rectangle2D anchor = ctx.getShapeAnchor(); - double ss = Math.min(anchor.getWidth(), anchor.getHeight()); - return ss / 6.; - } - }); - - // short side / 8 - builtInFormulas.put("ssd8", new Formula(){ - @Override - double evaluate(Context ctx){ - Rectangle2D anchor = ctx.getShapeAnchor(); - double ss = Math.min(anchor.getWidth(), anchor.getHeight()); - return ss / 8.; - } - }); - - // short side / 16 - builtInFormulas.put("ssd16", new Formula(){ - @Override - double evaluate(Context ctx){ - Rectangle2D anchor = ctx.getShapeAnchor(); - double ss = Math.min(anchor.getWidth(), anchor.getHeight()); - return ss / 16.; - } - }); - - // short side / 32 - builtInFormulas.put("ssd32", new Formula(){ - @Override - double evaluate(Context ctx){ - Rectangle2D anchor = ctx.getShapeAnchor(); - double ss = Math.min(anchor.getWidth(), anchor.getHeight()); - return ss / 32.; - } - }); - - // top - builtInFormulas.put("t", new Formula(){ - @Override - double evaluate(Context ctx){ - return ctx.getShapeAnchor().getY(); - } - }); - - // vertical center - builtInFormulas.put("vc", new Formula(){ - @Override - double evaluate(Context ctx){ - Rectangle2D anchor = ctx.getShapeAnchor(); - return anchor.getY() + anchor.getHeight()/2.; - } - }); - - // width - builtInFormulas.put("w", new Formula(){ - @Override - double evaluate(Context ctx){ - return ctx.getShapeAnchor().getWidth(); - } - }); - - // width / 2 - builtInFormulas.put("wd2", new Formula(){ - @Override - double evaluate(Context ctx){ - return ctx.getShapeAnchor().getWidth()/2.; - } - }); - - // width / 3 - builtInFormulas.put("wd3", new Formula(){ - @Override - double evaluate(Context ctx){ - return ctx.getShapeAnchor().getWidth()/3.; - } - }); - - // width / 4 - builtInFormulas.put("wd4", new Formula(){ - @Override - double evaluate(Context ctx){ - return ctx.getShapeAnchor().getWidth()/4.; - } - }); - - // width / 5 - builtInFormulas.put("wd5", new Formula(){ - @Override - double evaluate(Context ctx){ - return ctx.getShapeAnchor().getWidth()/5.; - } - }); - - // width / 6 - builtInFormulas.put("wd6", new Formula(){ - @Override - double evaluate(Context ctx){ - return ctx.getShapeAnchor().getWidth()/6.; - } - }); - - // width / 8 - builtInFormulas.put("wd8", new Formula(){ - @Override - double evaluate(Context ctx){ - return ctx.getShapeAnchor().getWidth()/8.; - } - }); - - // width / 10 - builtInFormulas.put("wd10", new Formula(){ - @Override - double evaluate(Context ctx){ - return ctx.getShapeAnchor().getWidth()/10.; - } - }); - - // width / 32 - builtInFormulas.put("wd32", new Formula(){ - @Override - double evaluate(Context ctx){ - return ctx.getShapeAnchor().getWidth()/32.; - } - }); - } - -} diff --git a/src/java/org/apache/poi/sl/draw/geom/Guide.java b/src/java/org/apache/poi/sl/draw/geom/Guide.java deleted file mode 100644 index f14213244..000000000 --- a/src/java/org/apache/poi/sl/draw/geom/Guide.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.sl.draw.geom; - -import org.apache.poi.sl.draw.binding.CTGeomGuide; - -/** - * Date: 10/24/11 - * - * @author Yegor Kozlov - */ -public class Guide extends Formula { - private String name, fmla; - private Expression expr; - - public Guide(CTGeomGuide gd) { - this(gd.getName(), gd.getFmla()); - } - - public Guide(String nm, String fm){ - name = nm; - fmla = fm; - expr = ExpressionParser.parse(fm); - } - - - String getName(){ - return name; - } - - String getFormula(){ - return fmla; - } - - @Override - public double evaluate(Context ctx){ - return expr.evaluate(ctx); - } - - -} diff --git a/src/java/org/apache/poi/sl/draw/geom/IAdjustableShape.java b/src/java/org/apache/poi/sl/draw/geom/IAdjustableShape.java deleted file mode 100644 index 920acb82d..000000000 --- a/src/java/org/apache/poi/sl/draw/geom/IAdjustableShape.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.sl.draw.geom; - - -/** - * A bridge to the consumer application. - * - * To get a shape geometry one needs to pass shape bounds and adjust values. - * - * @author Yegor Kozlov - */ -public interface IAdjustableShape { - /** - * - * @param name name of a adjust value, e.g. adj1 - * @return adjust guide defined in the shape or null - */ - Guide getAdjustValue(String name); -} diff --git a/src/java/org/apache/poi/sl/draw/geom/IfElseExpression.java b/src/java/org/apache/poi/sl/draw/geom/IfElseExpression.java deleted file mode 100644 index 443115a78..000000000 --- a/src/java/org/apache/poi/sl/draw/geom/IfElseExpression.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.sl.draw.geom; - -import java.util.regex.Matcher; - -/** - * If Else Formula: - *

    - * Arguments: 3 (fmla="?: x y z") - * Usage: "?: x y z" = if (x > 0), then y = value of this guide, - * else z = value of this guide - *

    - * - * @author Yegor Kozlov - */ -public class IfElseExpression implements Expression { - private String arg1, arg2, arg3; - - IfElseExpression(Matcher m){ - arg1 = m.group(1); - arg2 = m.group(2); - arg3 = m.group(3); - } - - public double evaluate(Context ctx){ - double x = ctx.getValue(arg1); - double y = ctx.getValue(arg2); - double z = ctx.getValue(arg3); - return x > 0 ? y : z; - } - -} diff --git a/src/java/org/apache/poi/sl/draw/geom/LineToCommand.java b/src/java/org/apache/poi/sl/draw/geom/LineToCommand.java deleted file mode 100644 index 7f6e13c54..000000000 --- a/src/java/org/apache/poi/sl/draw/geom/LineToCommand.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.sl.draw.geom; - -import java.awt.geom.Path2D; - -import org.apache.poi.sl.draw.binding.CTAdjPoint2D; - -/** - * Date: 10/25/11 - * - * @author Yegor Kozlov - */ -public class LineToCommand implements PathCommand { - private String arg1, arg2; - - LineToCommand(CTAdjPoint2D pt){ - arg1 = pt.getX().toString(); - arg2 = pt.getY().toString(); - } - - LineToCommand(String s1, String s2){ - arg1 = s1; - arg2 = s2; - } - - public void execute(Path2D.Double path, Context ctx){ - double x = ctx.getValue(arg1); - double y = ctx.getValue(arg2); - path.lineTo(x, y); - } -} diff --git a/src/java/org/apache/poi/sl/draw/geom/LiteralValueExpression.java b/src/java/org/apache/poi/sl/draw/geom/LiteralValueExpression.java deleted file mode 100644 index ab3abc7fd..000000000 --- a/src/java/org/apache/poi/sl/draw/geom/LiteralValueExpression.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.sl.draw.geom; - -import java.util.regex.Matcher; - -/** - * Date: 10/24/11 - * - * @author Yegor Kozlov - */ -public class LiteralValueExpression implements Expression { - private String arg; - - LiteralValueExpression(Matcher m){ - arg = m.group(1); - } - - public double evaluate(Context ctx){ - return ctx.getValue(arg); - } - -} diff --git a/src/java/org/apache/poi/sl/draw/geom/MaxExpression.java b/src/java/org/apache/poi/sl/draw/geom/MaxExpression.java deleted file mode 100644 index 88a9c6047..000000000 --- a/src/java/org/apache/poi/sl/draw/geom/MaxExpression.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.sl.draw.geom; - -import java.util.regex.Matcher; - -/** - * Maximum Value Formula - * - * @author Yegor Kozlov - */ -public class MaxExpression implements Expression { - private String arg1, arg2; - - MaxExpression(Matcher m){ - arg1 = m.group(1); - arg2 = m.group(2); - } - - public double evaluate(Context ctx){ - double x = ctx.getValue(arg1); - double y = ctx.getValue(arg2); - return Math.max(x, y); - } - -} diff --git a/src/java/org/apache/poi/sl/draw/geom/MinExpression.java b/src/java/org/apache/poi/sl/draw/geom/MinExpression.java deleted file mode 100644 index 8c1864c5a..000000000 --- a/src/java/org/apache/poi/sl/draw/geom/MinExpression.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.sl.draw.geom; - -import java.util.regex.Matcher; - -/** - * Minimum Value Formula - * - * @author Yegor Kozlov - */ -public class MinExpression implements Expression { - private String arg1, arg2; - - MinExpression(Matcher m){ - arg1 = m.group(1); - arg2 = m.group(2); - } - - public double evaluate(Context ctx){ - double x = ctx.getValue(arg1); - double y = ctx.getValue(arg2); - return Math.min(x, y); - } - -} diff --git a/src/java/org/apache/poi/sl/draw/geom/ModExpression.java b/src/java/org/apache/poi/sl/draw/geom/ModExpression.java deleted file mode 100644 index ff20fc20f..000000000 --- a/src/java/org/apache/poi/sl/draw/geom/ModExpression.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.sl.draw.geom; - -import java.util.regex.Matcher; - -/** - * Modulo Formula: - *

    - * Arguments: 3 (fmla="mod x y z") - * Usage: "mod x y z" = sqrt(x^2 + b^2 + c^2) = value of this guide - *

    - * - * @author Yegor Kozlov - */ -public class ModExpression implements Expression { - private String arg1, arg2, arg3; - - ModExpression(Matcher m){ - arg1 = m.group(1); - arg2 = m.group(2); - arg3 = m.group(3); - } - - public double evaluate(Context ctx){ - double x = ctx.getValue(arg1); - double y = ctx.getValue(arg2); - double z = ctx.getValue(arg3); - return Math.sqrt(x*x + y*y + z*z); - } - -} diff --git a/src/java/org/apache/poi/sl/draw/geom/MoveToCommand.java b/src/java/org/apache/poi/sl/draw/geom/MoveToCommand.java deleted file mode 100644 index 59c7a8adf..000000000 --- a/src/java/org/apache/poi/sl/draw/geom/MoveToCommand.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.sl.draw.geom; - -import java.awt.geom.Path2D; - -import org.apache.poi.sl.draw.binding.CTAdjPoint2D; - -/** - * Date: 10/25/11 - * - * @author Yegor Kozlov - */ -public class MoveToCommand implements PathCommand { - private String arg1, arg2; - - MoveToCommand(CTAdjPoint2D pt){ - arg1 = pt.getX().toString(); - arg2 = pt.getY().toString(); - } - - MoveToCommand(String s1, String s2){ - arg1 = s1; - arg2 = s2; - } - - public void execute(Path2D.Double path, Context ctx){ - double x = ctx.getValue(arg1); - double y = ctx.getValue(arg2); - path.moveTo(x, y); - } -} diff --git a/src/java/org/apache/poi/sl/draw/geom/MultiplyDivideExpression.java b/src/java/org/apache/poi/sl/draw/geom/MultiplyDivideExpression.java deleted file mode 100644 index 5af0ff12c..000000000 --- a/src/java/org/apache/poi/sl/draw/geom/MultiplyDivideExpression.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.sl.draw.geom; - -import java.util.regex.Matcher; - -/** - * Multiply Divide Formula - * - * @author Yegor Kozlov - */ -public class MultiplyDivideExpression implements Expression { - private String arg1, arg2, arg3; - - MultiplyDivideExpression(Matcher m){ - arg1 = m.group(1); - arg2 = m.group(2); - arg3 = m.group(3); - } - - public double evaluate(Context ctx){ - double x = ctx.getValue(arg1); - double y = ctx.getValue(arg2); - double z = ctx.getValue(arg3); - return (x * y ) / z; - } - -} diff --git a/src/java/org/apache/poi/sl/draw/geom/Outline.java b/src/java/org/apache/poi/sl/draw/geom/Outline.java deleted file mode 100644 index b4ffc4257..000000000 --- a/src/java/org/apache/poi/sl/draw/geom/Outline.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.sl.draw.geom; - -import java.awt.Shape; - -/** -* Date: 11/6/11 -* -* @author Yegor Kozlov -*/ -public class Outline { - private Shape shape; - private Path path; - - public Outline(Shape shape, Path path){ - this.shape = shape; - this.path = path; - } - - public Path getPath(){ - return path; - } - - public Shape getOutline(){ - return shape; - } -} diff --git a/src/java/org/apache/poi/sl/draw/geom/Path.java b/src/java/org/apache/poi/sl/draw/geom/Path.java deleted file mode 100644 index 78590faf0..000000000 --- a/src/java/org/apache/poi/sl/draw/geom/Path.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.sl.draw.geom; - -import java.awt.geom.Path2D; -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.sl.draw.binding.CTAdjPoint2D; -import org.apache.poi.sl.draw.binding.CTPath2D; -import org.apache.poi.sl.draw.binding.CTPath2DArcTo; -import org.apache.poi.sl.draw.binding.CTPath2DClose; -import org.apache.poi.sl.draw.binding.CTPath2DCubicBezierTo; -import org.apache.poi.sl.draw.binding.CTPath2DLineTo; -import org.apache.poi.sl.draw.binding.CTPath2DMoveTo; -import org.apache.poi.sl.draw.binding.CTPath2DQuadBezierTo; -import org.apache.poi.sl.draw.binding.STPathFillMode; - -/** - * Specifies a creation path consisting of a series of moves, lines and curves - * that when combined forms a geometric shape - * - * @author Yegor Kozlov - */ -public class Path { - private final List commands; - boolean _fill, _stroke; - long _w, _h; - - public Path(){ - this(true, true); - } - - public Path(boolean fill, boolean stroke){ - commands = new ArrayList(); - _w = -1; - _h = -1; - _fill = fill; - _stroke = stroke; - } - - public Path(CTPath2D spPath){ - _fill = spPath.getFill() != STPathFillMode.NONE; - _stroke = spPath.isStroke(); - _w = spPath.isSetW() ? spPath.getW() : -1; - _h = spPath.isSetH() ? spPath.getH() : -1; - - commands = new ArrayList(); - - for(Object ch : spPath.getCloseOrMoveToOrLnTo()){ - if(ch instanceof CTPath2DMoveTo){ - CTAdjPoint2D pt = ((CTPath2DMoveTo)ch).getPt(); - commands.add(new MoveToCommand(pt)); - } else if (ch instanceof CTPath2DLineTo){ - CTAdjPoint2D pt = ((CTPath2DLineTo)ch).getPt(); - commands.add(new LineToCommand(pt)); - } else if (ch instanceof CTPath2DArcTo){ - CTPath2DArcTo arc = (CTPath2DArcTo)ch; - commands.add(new ArcToCommand(arc)); - } else if (ch instanceof CTPath2DQuadBezierTo){ - CTPath2DQuadBezierTo bez = ((CTPath2DQuadBezierTo)ch); - CTAdjPoint2D pt1 = bez.getPt().get(0); - CTAdjPoint2D pt2 = bez.getPt().get(1); - commands.add(new QuadToCommand(pt1, pt2)); - } else if (ch instanceof CTPath2DCubicBezierTo){ - CTPath2DCubicBezierTo bez = ((CTPath2DCubicBezierTo)ch); - CTAdjPoint2D pt1 = bez.getPt().get(0); - CTAdjPoint2D pt2 = bez.getPt().get(1); - CTAdjPoint2D pt3 = bez.getPt().get(2); - commands.add(new CurveToCommand(pt1, pt2, pt3)); - } else if (ch instanceof CTPath2DClose){ - commands.add(new ClosePathCommand()); - } else { - throw new IllegalStateException("Unsupported path segment: " + ch); - } - } - } - - public void addCommand(PathCommand cmd){ - commands.add(cmd); - } - - /** - * Convert the internal represenation to java.awt.geom.Path2D - */ - public Path2D.Double getPath(Context ctx) { - Path2D.Double path = new Path2D.Double(); - for(PathCommand cmd : commands) - cmd.execute(path, ctx); - return path; - } - - public boolean isStroked(){ - return _stroke; - } - - public boolean isFilled(){ - return _fill; - } - - public long getW(){ - return _w; - } - - public long getH(){ - return _h; - } -} diff --git a/src/java/org/apache/poi/sl/draw/geom/PathCommand.java b/src/java/org/apache/poi/sl/draw/geom/PathCommand.java deleted file mode 100644 index 41fa21a54..000000000 --- a/src/java/org/apache/poi/sl/draw/geom/PathCommand.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.sl.draw.geom; - -import java.awt.geom.Path2D; - -/** - * A path command in DrawingML. One of: - * - * - arcTo - * - moveTo - * - lineTo - * - cubicBezTo - * - quadBezTo - * - close - * - * - * @author Yegor Kozlov - */ -public interface PathCommand { - /** - * Execute the command an append a segment to the specified path - * - * @param path the path to append the result to - * @param ctx the context to lookup variables - */ - void execute(Path2D.Double path, Context ctx); -} diff --git a/src/java/org/apache/poi/sl/draw/geom/PinExpression.java b/src/java/org/apache/poi/sl/draw/geom/PinExpression.java deleted file mode 100644 index ee0d4e510..000000000 --- a/src/java/org/apache/poi/sl/draw/geom/PinExpression.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.sl.draw.geom; - -import java.util.regex.Matcher; - -/** - * Pin To Formula: - * - * - *

    - * Usage: "pin x y z" = if (y < x), then x = value of this guide - * else if (y > z), then z = value of this guide - * else y = value of this guide - *

    - * - * @author Yegor Kozlov - */ -public class PinExpression implements Expression { - private String arg1, arg2, arg3; - - PinExpression(Matcher m){ - arg1 = m.group(1); - arg2 = m.group(2); - arg3 = m.group(3); - } - - public double evaluate(Context ctx){ - double x = ctx.getValue(arg1); - double y = ctx.getValue(arg2); - double z = ctx.getValue(arg3); - if(y < x) return x; - else if (y > z) return z; - else return y; - } - -} diff --git a/src/java/org/apache/poi/sl/draw/geom/PresetGeometries.java b/src/java/org/apache/poi/sl/draw/geom/PresetGeometries.java deleted file mode 100644 index ad2553fbe..000000000 --- a/src/java/org/apache/poi/sl/draw/geom/PresetGeometries.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.sl.draw.geom; - -import java.io.InputStream; -import java.util.LinkedHashMap; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBElement; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Unmarshaller; -import javax.xml.stream.EventFilter; -import javax.xml.stream.XMLEventReader; -import javax.xml.stream.XMLInputFactory; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamReader; -import javax.xml.stream.events.StartElement; -import javax.xml.stream.events.XMLEvent; - -import org.apache.poi.sl.draw.binding.CTCustomGeometry2D; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; - -/** - * - */ -public class PresetGeometries extends LinkedHashMap { - private final static POILogger LOG = POILogFactory.getLogger(PresetGeometries.class); - protected final static String BINDING_PACKAGE = "org.apache.poi.sl.draw.binding"; - - protected static PresetGeometries _inst; - - protected PresetGeometries(){} - - @SuppressWarnings("unused") - public void init(InputStream is) throws XMLStreamException, JAXBException { - // StAX: - EventFilter startElementFilter = new EventFilter() { - @Override - public boolean accept(XMLEvent event) { - return event.isStartElement(); - } - }; - - XMLInputFactory staxFactory = XMLInputFactory.newFactory(); - XMLEventReader staxReader = staxFactory.createXMLEventReader(is); - XMLEventReader staxFiltRd = staxFactory.createFilteredReader(staxReader, startElementFilter); - // ignore StartElement: - /* XMLEvent evDoc = */ staxFiltRd.nextEvent(); - // JAXB: - JAXBContext jaxbContext = JAXBContext.newInstance(BINDING_PACKAGE); - Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); - - long cntElem = 0; - while (staxFiltRd.peek() != null) { - StartElement evRoot = (StartElement)staxFiltRd.peek(); - String name = evRoot.getName().getLocalPart(); - JAXBElement el = unmarshaller.unmarshal(staxReader, CTCustomGeometry2D.class); - CTCustomGeometry2D cus = el.getValue(); - cntElem++; - - if(containsKey(name)) { - LOG.log(POILogger.WARN, "Duplicate definition of " + name); - } - put(name, new CustomGeometry(cus)); - } - } - - /** - * Convert a single CustomGeometry object, i.e. from xmlbeans - */ - public static CustomGeometry convertCustomGeometry(XMLStreamReader staxReader) { - try { - JAXBContext jaxbContext = JAXBContext.newInstance(BINDING_PACKAGE); - Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); - JAXBElement el = unmarshaller.unmarshal(staxReader, CTCustomGeometry2D.class); - return new CustomGeometry(el.getValue()); - } catch (JAXBException e) { - LOG.log(POILogger.ERROR, "Unable to parse single custom geometry", e); - return null; - } - } - - public static synchronized PresetGeometries getInstance(){ - if(_inst == null) { - // use a local object first to not assign a partly constructed object - // in case of failure - PresetGeometries lInst = new PresetGeometries(); - try { - InputStream is = PresetGeometries.class. - getResourceAsStream("presetShapeDefinitions.xml"); - try { - lInst.init(is); - } finally { - is.close(); - } - } catch (Exception e){ - throw new RuntimeException(e); - } - _inst = lInst; - } - - return _inst; - } -} diff --git a/src/java/org/apache/poi/sl/draw/geom/QuadToCommand.java b/src/java/org/apache/poi/sl/draw/geom/QuadToCommand.java deleted file mode 100644 index d5e848b5a..000000000 --- a/src/java/org/apache/poi/sl/draw/geom/QuadToCommand.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.sl.draw.geom; - -import java.awt.geom.Path2D; - -import org.apache.poi.sl.draw.binding.CTAdjPoint2D; - -/** - * Date: 10/25/11 - * - * @author Yegor Kozlov - */ -public class QuadToCommand implements PathCommand { - private String arg1, arg2, arg3, arg4; - - QuadToCommand(CTAdjPoint2D pt1, CTAdjPoint2D pt2){ - arg1 = pt1.getX().toString(); - arg2 = pt1.getY().toString(); - arg3 = pt2.getX().toString(); - arg4 = pt2.getY().toString(); - } - - public void execute(Path2D.Double path, Context ctx){ - double x1 = ctx.getValue(arg1); - double y1 = ctx.getValue(arg2); - double x2 = ctx.getValue(arg3); - double y2 = ctx.getValue(arg4); - path.quadTo(x1, y1, x2, y2); - } -} diff --git a/src/java/org/apache/poi/sl/draw/geom/SinArcTanExpression.java b/src/java/org/apache/poi/sl/draw/geom/SinArcTanExpression.java deleted file mode 100644 index e14acb9e6..000000000 --- a/src/java/org/apache/poi/sl/draw/geom/SinArcTanExpression.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.sl.draw.geom; - -import java.util.regex.Matcher; - -/** - * Sine ArcTan Formula: - * - * - *

    - * Arguments: 3 (fmla="sat2 x y z") - * Usage: "sat2 x y z" = (x*sin(arctan(z / y))) = value of this guide - *

    - * - * @author Yegor Kozlov - */ -public class SinArcTanExpression implements Expression { - private String arg1, arg2, arg3; - - SinArcTanExpression(Matcher m){ - arg1 = m.group(1); - arg2 = m.group(2); - arg3 = m.group(3); - } - - public double evaluate(Context ctx){ - double x = ctx.getValue(arg1); - double y = ctx.getValue(arg2); - double z = ctx.getValue(arg3); - return x*Math.sin(Math.atan(z / y)); - } - -} diff --git a/src/java/org/apache/poi/sl/draw/geom/SinExpression.java b/src/java/org/apache/poi/sl/draw/geom/SinExpression.java deleted file mode 100644 index ca0c110ce..000000000 --- a/src/java/org/apache/poi/sl/draw/geom/SinExpression.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.sl.draw.geom; - -import java.util.regex.Matcher; - -/** - * Sine Formula: - * - * - *

    - * Arguments: 2 (fmla="sin x y") - * Usage: "sin x y" = (x * sin( y )) = value of this guide - *

    - * - * @author Yegor Kozlov - */ -public class SinExpression implements Expression { - private String arg1, arg2; - - SinExpression(Matcher m){ - arg1 = m.group(1); - arg2 = m.group(2); - } - - public double evaluate(Context ctx){ - double x = ctx.getValue(arg1); - double y = ctx.getValue(arg2) / 60000; - return x * Math.sin(Math.toRadians(y)); - } - -} diff --git a/src/java/org/apache/poi/sl/draw/geom/SqrtExpression.java b/src/java/org/apache/poi/sl/draw/geom/SqrtExpression.java deleted file mode 100644 index 5cdd67cc5..000000000 --- a/src/java/org/apache/poi/sl/draw/geom/SqrtExpression.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.sl.draw.geom; - -import java.util.regex.Matcher; - -/** - * Square Root Formula: - * - * - *

    - * Arguments: 1 (fmla="sqrt x") - * Usage: "sqrt x" = sqrt(x) = value of this guide - *

    - * @author Yegor Kozlov - */ -public class SqrtExpression implements Expression { - private String arg; - - SqrtExpression(Matcher m){ - arg =m.group(1); - } - - public double evaluate(Context ctx){ - double val = ctx.getValue(arg); - return Math.sqrt(val); - } - -} diff --git a/src/java/org/apache/poi/sl/draw/geom/TanExpression.java b/src/java/org/apache/poi/sl/draw/geom/TanExpression.java deleted file mode 100644 index 7eebdcedf..000000000 --- a/src/java/org/apache/poi/sl/draw/geom/TanExpression.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.sl.draw.geom; - -import java.util.regex.Matcher; - -/** - * Tangent Formula: - * - * - * - *

    - * Arguments: 2 (fmla="tan x y") - * Usage: "tan x y" = (x * tan( y )) = value of this guide - *

    - * - * @author Yegor Kozlov - */ -public class TanExpression implements Expression { - private String arg1, arg2; - - TanExpression(Matcher m){ - arg1 = m.group(1); - arg2 = m.group(2); - } - - public double evaluate(Context ctx){ - double x = ctx.getValue(arg1); - double y = ctx.getValue(arg2); - return x * Math.tan(Math.toRadians(y / 60000)); - } - -} diff --git a/src/java/org/apache/poi/sl/image/ImageHeaderBitmap.java b/src/java/org/apache/poi/sl/image/ImageHeaderBitmap.java deleted file mode 100644 index 3ecc6e55c..000000000 --- a/src/java/org/apache/poi/sl/image/ImageHeaderBitmap.java +++ /dev/null @@ -1,57 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.image; - -import java.awt.Dimension; -import java.awt.image.BufferedImage; -import java.io.ByteArrayInputStream; -import java.io.IOException; - -import javax.imageio.ImageIO; - -import org.apache.poi.util.Internal; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.util.Units; - -@Internal -public class ImageHeaderBitmap { - private static final POILogger LOG = POILogFactory.getLogger(ImageHeaderBitmap.class); - - private final Dimension size; - - public ImageHeaderBitmap(byte data[], int offset) { - BufferedImage img = null; - try { - img = ImageIO.read(new ByteArrayInputStream(data, offset, data.length-offset)); - } catch (IOException e) { - LOG.log(POILogger.WARN, "Can't determine image dimensions", e); - } - // set dummy size, in case of dummy dimension can't be set - size = (img == null) - ? new Dimension(200,200) - : new Dimension( - (int)Units.pixelToPoints(img.getWidth()), - (int)Units.pixelToPoints(img.getHeight()) - ); - } - - public Dimension getSize() { - return size; - } -} diff --git a/src/java/org/apache/poi/sl/image/ImageHeaderEMF.java b/src/java/org/apache/poi/sl/image/ImageHeaderEMF.java deleted file mode 100644 index fc7be14fe..000000000 --- a/src/java/org/apache/poi/sl/image/ImageHeaderEMF.java +++ /dev/null @@ -1,69 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.image; - -import java.awt.Dimension; -import java.awt.Rectangle; - -import org.apache.poi.util.Internal; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.LocaleUtil; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; - -@Internal -public class ImageHeaderEMF { - private static final POILogger LOG = POILogFactory.getLogger(ImageHeaderEMF.class); - - private static final String EMF_SIGNATURE = " EMF"; // 0x464D4520 (LE) - - // rectangular inclusive-inclusive bounds, in device units, of the smallest - // rectangle that can be drawn around the image stored in the metafile. - private final Rectangle deviceBounds; - - public ImageHeaderEMF(final byte data[], final int off) { - int offset = off; - int type = (int)LittleEndian.getUInt(data, offset); offset += 4; - if (type != 1) { - LOG.log(POILogger.WARN, "Invalid EMF picture - invalid type"); - deviceBounds = new Rectangle(0,0,200,200); - return; - } - // ignore header size - offset += 4; - int left = LittleEndian.getInt(data, offset); offset += 4; - int top = LittleEndian.getInt(data, offset); offset += 4; - int right = LittleEndian.getInt(data, offset); offset += 4; - int bottom = LittleEndian.getInt(data, offset); offset += 4; - deviceBounds = new Rectangle(left, top, right-left, bottom-top); - // ignore frame bounds - offset += 16; - String signature = new String(data, offset, EMF_SIGNATURE.length(), LocaleUtil.CHARSET_1252); - if (!EMF_SIGNATURE.equals(signature)) { - LOG.log(POILogger.WARN, "Invalid EMF picture - invalid signature"); - } - } - - public Dimension getSize() { - return deviceBounds.getSize(); - } - - public Rectangle getBounds() { - return deviceBounds; - } -} \ No newline at end of file diff --git a/src/java/org/apache/poi/sl/image/ImageHeaderPICT.java b/src/java/org/apache/poi/sl/image/ImageHeaderPICT.java deleted file mode 100644 index ff121e3e7..000000000 --- a/src/java/org/apache/poi/sl/image/ImageHeaderPICT.java +++ /dev/null @@ -1,103 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.image; - -import java.awt.Dimension; -import java.awt.Rectangle; - -import org.apache.poi.util.Internal; -import org.apache.poi.util.Units; - -@Internal -public class ImageHeaderPICT { - /** - * skip the first 512 bytes - they are MAC specific crap - */ - public static final int PICT_HEADER_OFFSET = 512; - - public static final double DEFAULT_RESOLUTION = Units.POINT_DPI; - - private static final byte V2_HEADER[] = { - 0x00, 0x11, // v2 version opcode - 0x02, (byte)0xFF, // version number of new picture - 0x0C, 0x00, // header opcode - (byte)0xFF, (byte)0xFE, 0x00, 0x00 // pic size dummy - }; - - private final Rectangle bounds; - private final double hRes, vRes; - - public ImageHeaderPICT(byte data[], final int off) { - // http://mirrors.apple2.org.za/apple.cabi.net/Graphics/PICT.and_QT.INFO/PICT.file.format.TI.txt - int offset = off; - // low order 16 bits of picture size - can be ignored - offset += 2; - // rectangular bounding box of picture, at 72 dpi - // rect : 8 bytes (top, left, bottom, right: integer) - int y1 = readUnsignedShort(data, offset); offset += 2; - int x1 = readUnsignedShort(data, offset); offset += 2; - int y2 = readUnsignedShort(data, offset); offset += 2; - int x2 = readUnsignedShort(data, offset); offset += 2; - - // check for version 2 ... otherwise we don't read any further - boolean isV2 = true; - for (byte b : V2_HEADER) { - if (b != data[offset++]) { - isV2 = false; - break; - } - } - - if (isV2) { - // 4 bytes - fixed, horizontal resolution (dpi) of source data - hRes = readFixedPoint(data, offset); offset += 4; - // 4 bytes - fixed, vertical resolution (dpi) of source data - vRes = readFixedPoint(data, offset); offset += 4; - } else { - hRes = DEFAULT_RESOLUTION; - vRes = DEFAULT_RESOLUTION; - } - - bounds = new Rectangle(x1,y1,x2-x1,y2-y1); - } - - public Dimension getSize() { - int height = (int)Math.round(bounds.height*DEFAULT_RESOLUTION/vRes); - int width = (int)Math.round(bounds.width*DEFAULT_RESOLUTION/hRes); - return new Dimension(width, height); - } - - public Rectangle getBounds() { - return bounds; - } - - private static int readUnsignedShort(byte data[], int offset) { - int b0 = data[offset] & 0xFF; - int b1 = data[offset+1] & 0xFF; - return b0 << 8 | b1; - } - - private static double readFixedPoint(byte data[], int offset) { - int b0 = data[offset] & 0xFF; - int b1 = data[offset+1] & 0xFF; - int b2 = data[offset+2] & 0xFF; - int b3 = data[offset+3] & 0xFF; - int i = (b0 << 24) | (b1 << 16) | (b2 << 8) | b3; - return i / (double)0x10000; - } -} diff --git a/src/java/org/apache/poi/sl/image/ImageHeaderWMF.java b/src/java/org/apache/poi/sl/image/ImageHeaderWMF.java deleted file mode 100644 index c3274d97f..000000000 --- a/src/java/org/apache/poi/sl/image/ImageHeaderWMF.java +++ /dev/null @@ -1,155 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.image; - -import java.awt.Dimension; -import java.awt.Rectangle; -import java.io.IOException; -import java.io.OutputStream; - -import org.apache.poi.util.Internal; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.util.Units; - -/** - * Aldus Placeable Metafile header - 22 byte structure before WMF data. - *
      - *
    • int Key; Magic number (always 9AC6CDD7h) - *
    • short Handle; Metafile HANDLE number (always 0) - *
    • short Left; Left coordinate in metafile units - *
    • short Top; Top coordinate in metafile units - *
    • short Right; Right coordinate in metafile units - *
    • short Bottom; Bottom coordinate in metafile units - *
    • short Inch; Number of metafile units per inch - *
    • int Reserved; Reserved (always 0) - *
    • short Checksum; Checksum value for previous 10 shorts - *
    - */ -@Internal -public class ImageHeaderWMF { - - public static final int APMHEADER_KEY = 0x9AC6CDD7; - private static final POILogger LOG = POILogFactory.getLogger(ImageHeaderWMF.class); - - @SuppressWarnings("unused") - private final int handle; - private final int left, top, right, bottom; - - /** - * The number of logical units per inch used to represent the image. - * This value can be used to scale an image. By convention, an image is - * considered to be recorded at 1440 logical units (twips) per inch. - * Thus, a value of 720 specifies that the image SHOULD be rendered at - * twice its normal size, and a value of 2880 specifies that the image - * SHOULD be rendered at half its normal size. - */ - private final int inch; - @SuppressWarnings("unused") - private final int reserved; - private int checksum; - - public ImageHeaderWMF(Rectangle dim) { - handle = 0; - left = dim.x; - top = dim.y; - right = dim.x + dim.width; - bottom = dim.y + dim.height; - inch = Units.POINT_DPI; //default resolution is 72 dpi - reserved = 0; - } - - public ImageHeaderWMF(byte[] data, final int off) { - int offset = off; - int key = LittleEndian.getInt(data, offset); offset += LittleEndian.INT_SIZE; //header key - if (key != APMHEADER_KEY) { - LOG.log(POILogger.WARN, "WMF file doesn't contain a placeable header - ignore parsing"); - handle = 0; - left = 0; - top = 0; - right = 200; - bottom = 200; - inch = Units.POINT_DPI; //default resolution is 72 dpi - reserved = 0; - return; - } - - handle = LittleEndian.getUShort(data, offset); offset += LittleEndian.SHORT_SIZE; - left = LittleEndian.getShort(data, offset); offset += LittleEndian.SHORT_SIZE; - top = LittleEndian.getShort(data, offset); offset += LittleEndian.SHORT_SIZE; - right = LittleEndian.getShort(data, offset); offset += LittleEndian.SHORT_SIZE; - bottom = LittleEndian.getShort(data, offset); offset += LittleEndian.SHORT_SIZE; - - inch = LittleEndian.getUShort(data, offset); offset += LittleEndian.SHORT_SIZE; - reserved = LittleEndian.getInt(data, offset); offset += LittleEndian.INT_SIZE; - - checksum = LittleEndian.getShort(data, offset); offset += LittleEndian.SHORT_SIZE; - if (checksum != getChecksum()){ - LOG.log(POILogger.WARN, "WMF checksum does not match the header data"); - } - } - - /** - * Returns a checksum value for the previous 10 shorts in the header. - * The checksum is calculated by XORing each short value to an initial value of 0: - */ - public int getChecksum(){ - int cs = 0; - cs ^= (APMHEADER_KEY & 0x0000FFFF); - cs ^= ((APMHEADER_KEY & 0xFFFF0000) >> 16); - cs ^= left; - cs ^= top; - cs ^= right; - cs ^= bottom; - cs ^= inch; - return cs; - } - - public void write(OutputStream out) throws IOException { - byte[] header = new byte[22]; - int pos = 0; - LittleEndian.putInt(header, pos, APMHEADER_KEY); pos += LittleEndian.INT_SIZE; //header key - LittleEndian.putUShort(header, pos, 0); pos += LittleEndian.SHORT_SIZE; //hmf - LittleEndian.putUShort(header, pos, left); pos += LittleEndian.SHORT_SIZE; //left - LittleEndian.putUShort(header, pos, top); pos += LittleEndian.SHORT_SIZE; //top - LittleEndian.putUShort(header, pos, right); pos += LittleEndian.SHORT_SIZE; //right - LittleEndian.putUShort(header, pos, bottom); pos += LittleEndian.SHORT_SIZE; //bottom - LittleEndian.putUShort(header, pos, inch); pos += LittleEndian.SHORT_SIZE; //inch - LittleEndian.putInt(header, pos, 0); pos += LittleEndian.INT_SIZE; //reserved - - checksum = getChecksum(); - LittleEndian.putUShort(header, pos, checksum); - - out.write(header); - } - - public Dimension getSize() { - //coefficient to translate from WMF dpi to 72dpi - double coeff = ((double)Units.POINT_DPI)/inch; - return new Dimension((int)Math.round((right-left)*coeff), (int)Math.round((bottom-top)*coeff)); - } - - public Rectangle getBounds() { - return new Rectangle(left, top, right-left, bottom-top); - } - - public int getLength(){ - return 22; - } -} diff --git a/src/java/org/apache/poi/sl/usermodel/AutoNumberingScheme.java b/src/java/org/apache/poi/sl/usermodel/AutoNumberingScheme.java deleted file mode 100644 index 1006134d5..000000000 --- a/src/java/org/apache/poi/sl/usermodel/AutoNumberingScheme.java +++ /dev/null @@ -1,289 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.usermodel; - -import java.util.Locale; - -public enum AutoNumberingScheme { - /** Lowercase alphabetic character enclosed in parentheses. Example: (a), (b), (c), ... */ - alphaLcParenBoth(0x0008, 1), - /** Uppercase alphabetic character enclosed in parentheses. Example: (A), (B), (C), ... */ - alphaUcParenBoth(0x000A, 2), - /** Lowercase alphabetic character followed by a closing parenthesis. Example: a), b), c), ... */ - alphaLcParenRight(0x0009, 3), - /** Uppercase alphabetic character followed by a closing parenthesis. Example: A), B), C), ... */ - alphaUcParenRight(0x000B, 4), - /** Lowercase Latin character followed by a period. Example: a., b., c., ... */ - alphaLcPeriod(0x0000, 5), - /** Uppercase Latin character followed by a period. Example: A., B., C., ... */ - alphaUcPeriod(0x0001, 6), - /** Arabic numeral enclosed in parentheses. Example: (1), (2), (3), ... */ - arabicParenBoth(0x000C, 7), - /** Arabic numeral followed by a closing parenthesis. Example: 1), 2), 3), ... */ - arabicParenRight(0x0002, 8), - /** Arabic numeral followed by a period. Example: 1., 2., 3., ... */ - arabicPeriod(0x0003, 9), - /** Arabic numeral. Example: 1, 2, 3, ... */ - arabicPlain(0x000D, 10), - /** Lowercase Roman numeral enclosed in parentheses. Example: (i), (ii), (iii), ... */ - romanLcParenBoth(0x0004, 11), - /** Uppercase Roman numeral enclosed in parentheses. Example: (I), (II), (III), ... */ - romanUcParenBoth(0x000E, 12), - /** Lowercase Roman numeral followed by a closing parenthesis. Example: i), ii), iii), ... */ - romanLcParenRight(0x0005, 13), - /** Uppercase Roman numeral followed by a closing parenthesis. Example: I), II), III), .... */ - romanUcParenRight(0x000F, 14), - /** Lowercase Roman numeral followed by a period. Example: i., ii., iii., ... */ - romanLcPeriod(0x0006, 15), - /** Uppercase Roman numeral followed by a period. Example: I., II., III., ... */ - romanUcPeriod(0x0007, 16), - /** Double byte circle numbers. */ - circleNumDbPlain(0x0012, 17), - /** Wingdings black circle numbers. */ - circleNumWdBlackPlain(0x0014, 18), - /** Wingdings white circle numbers. */ - circleNumWdWhitePlain(0x0013, 19), - /** Double-byte Arabic numbers with double-byte period. */ - arabicDbPeriod(0x001D, 20), - /** Double-byte Arabic numbers. */ - arabicDbPlain(0x001C, 21), - /** Simplified Chinese with single-byte period. */ - ea1ChsPeriod(0x0011, 22), - /** Simplified Chinese. */ - ea1ChsPlain(0x0010, 23), - /** Traditional Chinese with single-byte period. */ - ea1ChtPeriod(0x0015, 24), - /** Traditional Chinese. */ - ea1ChtPlain(0x0014, 25), - /** Japanese with double-byte period. */ - ea1JpnChsDbPeriod(0x0026, 26), - /** Japanese/Korean. */ - ea1JpnKorPlain(0x001A, 27), - /** Japanese/Korean with single-byte period. */ - ea1JpnKorPeriod(0x001B, 28), - /** Bidi Arabic 1 (AraAlpha) with ANSI minus symbol. */ - arabic1Minus(0x0017, 29), - /** Bidi Arabic 2 (AraAbjad) with ANSI minus symbol. */ - arabic2Minus(0x0018, 30), - /** Bidi Hebrew 2 with ANSI minus symbol. */ - hebrew2Minus(0x0019, 31), - /** Thai alphabetic character followed by a period. */ - thaiAlphaPeriod(0x001E, 32), - /** Thai alphabetic character followed by a closing parenthesis. */ - thaiAlphaParenRight(0x001F, 33), - /** Thai alphabetic character enclosed by parentheses. */ - thaiAlphaParenBoth(0x0020, 34), - /** Thai numeral followed by a period. */ - thaiNumPeriod(0x0021, 35), - /** Thai numeral followed by a closing parenthesis. */ - thaiNumParenRight(0x0022, 36), - /** Thai numeral enclosed in parentheses. */ - thaiNumParenBoth(0x0023, 37), - /** Hindi alphabetic character followed by a period. */ - hindiAlphaPeriod(0x0024, 38), - /** Hindi numeric character followed by a period. */ - hindiNumPeriod(0x0025, 39), - /** Hindi numeric character followed by a closing parenthesis. */ - hindiNumParenRight(0x0027, 40), - /** Hindi alphabetic character followed by a period. */ - hindiAlpha1Period(0x0027, 41); - - public final int nativeId, ooxmlId; - - AutoNumberingScheme(int nativeId, int ooxmlId) { - this.nativeId = nativeId; - this.ooxmlId = ooxmlId; - } - - public static AutoNumberingScheme forNativeID(int nativeId) { - for (AutoNumberingScheme ans : values()) { - if (ans.nativeId == nativeId) return ans; - } - return null; - } - - public static AutoNumberingScheme forOoxmlID(int ooxmlId) { - for (AutoNumberingScheme ans : values()) { - if (ans.ooxmlId == ooxmlId) return ans; - } - return null; - } - - public String getDescription() { - switch (this) { - case alphaLcPeriod : return "Lowercase Latin character followed by a period. Example: a., b., c., ..."; - case alphaUcPeriod : return "Uppercase Latin character followed by a period. Example: A., B., C., ..."; - case arabicParenRight : return "Arabic numeral followed by a closing parenthesis. Example: 1), 2), 3), ..."; - case arabicPeriod : return "Arabic numeral followed by a period. Example: 1., 2., 3., ..."; - case romanLcParenBoth : return "Lowercase Roman numeral enclosed in parentheses. Example: (i), (ii), (iii), ..."; - case romanLcParenRight : return "Lowercase Roman numeral followed by a closing parenthesis. Example: i), ii), iii), ..."; - case romanLcPeriod : return "Lowercase Roman numeral followed by a period. Example: i., ii., iii., ..."; - case romanUcPeriod : return "Uppercase Roman numeral followed by a period. Example: I., II., III., ..."; - case alphaLcParenBoth : return "Lowercase alphabetic character enclosed in parentheses. Example: (a), (b), (c), ..."; - case alphaLcParenRight : return "Lowercase alphabetic character followed by a closing parenthesis. Example: a), b), c), ..."; - case alphaUcParenBoth : return "Uppercase alphabetic character enclosed in parentheses. Example: (A), (B), (C), ..."; - case alphaUcParenRight : return "Uppercase alphabetic character followed by a closing parenthesis. Example: A), B), C), ..."; - case arabicParenBoth : return "Arabic numeral enclosed in parentheses. Example: (1), (2), (3), ..."; - case arabicPlain : return "Arabic numeral. Example: 1, 2, 3, ..."; - case romanUcParenBoth : return "Uppercase Roman numeral enclosed in parentheses. Example: (I), (II), (III), ..."; - case romanUcParenRight : return "Uppercase Roman numeral followed by a closing parenthesis. Example: I), II), III), ..."; - case ea1ChsPlain : return "Simplified Chinese."; - case ea1ChsPeriod : return "Simplified Chinese with single-byte period."; - case circleNumDbPlain : return "Double byte circle numbers."; - case circleNumWdWhitePlain : return "Wingdings white circle numbers."; - case circleNumWdBlackPlain : return "Wingdings black circle numbers."; - case ea1ChtPlain : return "Traditional Chinese."; - case ea1ChtPeriod : return "Traditional Chinese with single-byte period."; - case arabic1Minus : return "Bidi Arabic 1 (AraAlpha) with ANSI minus symbol."; - case arabic2Minus : return "Bidi Arabic 2 (AraAbjad) with ANSI minus symbol."; - case hebrew2Minus : return "Bidi Hebrew 2 with ANSI minus symbol."; - case ea1JpnKorPlain : return "Japanese/Korean."; - case ea1JpnKorPeriod : return "Japanese/Korean with single-byte period."; - case arabicDbPlain : return "Double-byte Arabic numbers."; - case arabicDbPeriod : return "Double-byte Arabic numbers with double-byte period."; - case thaiAlphaPeriod : return "Thai alphabetic character followed by a period."; - case thaiAlphaParenRight : return "Thai alphabetic character followed by a closing parenthesis."; - case thaiAlphaParenBoth : return "Thai alphabetic character enclosed by parentheses."; - case thaiNumPeriod : return "Thai numeral followed by a period."; - case thaiNumParenRight : return "Thai numeral followed by a closing parenthesis."; - case thaiNumParenBoth : return "Thai numeral enclosed in parentheses."; - case hindiAlphaPeriod : return "Hindi alphabetic character followed by a period."; - case hindiNumPeriod : return "Hindi numeric character followed by a period."; - case ea1JpnChsDbPeriod : return "Japanese with double-byte period."; - case hindiNumParenRight : return "Hindi numeric character followed by a closing parenthesis."; - case hindiAlpha1Period : return "Hindi alphabetic character followed by a period."; - default : return "Unknown Numbered Scheme"; - } - } - - public String format(int value) { - String index = formatIndex(value); - String cased = formatCase(index); - String seperated = formatSeperator(cased); - return seperated; - } - - private String formatSeperator(String cased) { - String name = name().toLowerCase(Locale.ROOT); - if (name.contains("plain")) return cased; - if (name.contains("parenright")) return cased+")"; - if (name.contains("parenboth")) return "("+cased+")"; - if (name.contains("period")) return cased+"."; - if (name.contains("minus")) return cased+"-"; // ??? - return cased; - } - - private String formatCase(String index) { - String name = name().toLowerCase(Locale.ROOT); - if (name.contains("lc")) return index.toLowerCase(Locale.ROOT); - if (name.contains("uc")) return index.toUpperCase(Locale.ROOT); - return index; - } - - private static final String ARABIC_LIST = "0123456789"; - private static final String ALPHA_LIST = "abcdefghijklmnopqrstuvwxyz"; - private static final String WINGDINGS_WHITE_LIST = - "\u0080\u0081\u0082\u0083\u0084\u0085\u0086\u0087\u0088\u0089"; - private static final String WINGDINGS_BLACK_LIST = - "\u008B\u008C\u008D\u008E\u008F\u0090\u0091\u0092\u0093\u0094"; - private static final String CIRCLE_DB_LIST = - "\u2776\u2777\u2778\u2779\u277A\u277B\u277C\u277D\u277E"; - - private String formatIndex(int value) { - String name = name().toLowerCase(Locale.ROOT); - if (name.startsWith("roman")) { - return formatRomanIndex(value); - } else if (name.startsWith("arabic") && !name.contains("db")) { - return getIndexedList(value, ARABIC_LIST, false); - } else if (name.startsWith("alpha")) { - return getIndexedList(value, ALPHA_LIST, true); - } else if (name.contains("WdWhite")) { - return (value == 10) ? "\u008A" - : getIndexedList(value, WINGDINGS_WHITE_LIST, false); - } else if (name.contains("WdBlack")) { - return (value == 10) ? "\u0095" - : getIndexedList(value, WINGDINGS_BLACK_LIST, false); - } else if (name.contains("NumDb")) { - return (value == 10) ? "\u277F" - : getIndexedList(value, CIRCLE_DB_LIST, true); - } else { - return "?"; - } - } - - private static String getIndexedList(int val, String list, boolean oneBased) { - StringBuilder sb = new StringBuilder(); - addIndexedChar(val, list, oneBased, sb); - return sb.toString(); - } - - private static void addIndexedChar(int val, String list, boolean oneBased, StringBuilder sb) { - if (oneBased) val -= 1; - final int len = list.length(); - if (val >= len) { - addIndexedChar(val/len, list, oneBased, sb); - } - sb.append(list.charAt(val%len)); - } - - - private String formatRomanIndex(int value) { - //M (1000), CM (900), D (500), CD (400), C (100), XC (90), L (50), XL (40), X (10), IX (9), V (5), IV (4) and I (1). - final int[] VALUES = new int[]{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; - final String[] ROMAN = new String[]{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; - final String conciseList[][] = { - {"XLV", "VL"}, //45 - {"XCV", "VC"}, //95 - {"CDL", "LD"}, //450 - {"CML", "LM"}, //950 - {"CMVC", "LMVL"}, //995 - {"CDXC", "LDXL"}, //490 - {"CDVC", "LDVL"}, //495 - {"CMXC", "LMXL"}, //990 - {"XCIX", "VCIV"}, //99 - {"XLIX", "VLIV"}, //49 - {"XLIX", "IL"}, //49 - {"XCIX", "IC"}, //99 - {"CDXC", "XD"}, //490 - {"CDVC", "XDV"}, //495 - {"CDIC", "XDIX"}, //499 - {"LMVL", "XMV"}, //995 - {"CMIC", "XMIX"}, //999 - {"CMXC", "XM"}, // 990 - {"XDV", "VD"}, //495 - {"XDIX", "VDIV"}, //499 - {"XMV", "VM"}, // 995 - {"XMIX", "VMIV"}, //999 - {"VDIV", "ID"}, //499 - {"VMIV", "IM"} //999 - }; - - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < 13; i++) { - while (value >= VALUES[i]) { - value -= VALUES[i]; - sb.append(ROMAN[i]); - } - } - String result = sb.toString(); - for (String cc[] : conciseList) { - result = result.replace(cc[0], cc[1]); - } - return result; - } -} \ No newline at end of file diff --git a/src/java/org/apache/poi/sl/usermodel/AutoShape.java b/src/java/org/apache/poi/sl/usermodel/AutoShape.java deleted file mode 100644 index 5a77bdae4..000000000 --- a/src/java/org/apache/poi/sl/usermodel/AutoShape.java +++ /dev/null @@ -1,24 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.usermodel; - -public interface AutoShape< - S extends Shape, - P extends TextParagraph -> extends TextShape { -} diff --git a/src/java/org/apache/poi/sl/usermodel/Background.java b/src/java/org/apache/poi/sl/usermodel/Background.java deleted file mode 100644 index 64f3b36a5..000000000 --- a/src/java/org/apache/poi/sl/usermodel/Background.java +++ /dev/null @@ -1,25 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.usermodel; - -public interface Background< - S extends Shape, - P extends TextParagraph -> extends Shape { - FillStyle getFillStyle(); -} diff --git a/src/java/org/apache/poi/sl/usermodel/ColorStyle.java b/src/java/org/apache/poi/sl/usermodel/ColorStyle.java deleted file mode 100644 index da24d1658..000000000 --- a/src/java/org/apache/poi/sl/usermodel/ColorStyle.java +++ /dev/null @@ -1,109 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.usermodel; - -import java.awt.Color; - - -public interface ColorStyle { - Color getColor(); - - /** - * the opacity as expressed by a percentage value - * - * @return opacity in percents in the range [0..100000] - * or -1 if the value is not set - */ - int getAlpha(); - - /** - * the hue shift as expressed by a percentage relative to the input color. - * Be aware that OOXML also returns values greater than 100% - * - * @return hue shift in percents in the range [0..100000] (usually ...) - * or -1 if the value is not set - */ - int getHueOff(); - - /** - * the hue as expressed by a percentage relative to the input color. - * Be aware that OOXML also returns values greater than 100% - * - * @return hue in percents in the range [0..100000] (usually ...) - * or -1 if the value is not set - */ - int getHueMod(); - - /** - * the saturation shift as expressed by a percentage relative to the input color. - * Be aware that OOXML also returns values greater than 100% - * - * @return saturation shift in percents in the range [0..100000] (usually ...) - * or -1 if the value is not set - */ - int getSatOff(); - - /** - * the saturation as expressed by a percentage relative to the input color. - * Be aware that OOXML also returns values greater than 100% - * - * @return saturation in percents in the range [0..100000] (usually ...) - * or -1 if the value is not set - */ - int getSatMod(); - - /** - * the luminance shift as expressed by a percentage relative to the input color. - * Be aware that OOXML also returns values greater than 100% - * - * @return luminance shift in percents in the range [0..100000] (usually ...) - * or -1 if the value is not set - */ - int getLumOff(); - - /** - * the luminance as expressed by a percentage relative to the input color. - * Be aware that OOXML also returns values greater than 100%. - * - * @return luminance in percents in the range [0..100000] (usually ...) - * or -1 if the value is not set - */ - int getLumMod(); - - /** - * specifies a darker version of its input color. - * A 10% shade is 10% of the input color combined with 90% black. - * Be aware that OOXML also returns values greater than 100%. - * - * @return the value of the shade specified as percents in the range [0..100000] (usually ...) - * with 0% indicating minimal shade and 100% indicating maximum - * or -1 if the value is not set - */ - int getShade(); - - /** - * specifies a lighter version of its input color. - * A 10% tint is 10% of the input color combined with 90% white. - * Be aware that OOXML also returns values greater than 100% - * - * @return the value of the tint specified as percents in the range [0..100000] (usually ...) - * with 0% indicating minimal tint and 100% indicating maximum - * or -1 if the value is not set - */ - int getTint(); -} diff --git a/src/java/org/apache/poi/sl/usermodel/ConnectorShape.java b/src/java/org/apache/poi/sl/usermodel/ConnectorShape.java deleted file mode 100644 index e10c7507d..000000000 --- a/src/java/org/apache/poi/sl/usermodel/ConnectorShape.java +++ /dev/null @@ -1,25 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.usermodel; - -public interface ConnectorShape< - S extends Shape, - P extends TextParagraph -> extends SimpleShape { - -} diff --git a/src/java/org/apache/poi/sl/usermodel/FillStyle.java b/src/java/org/apache/poi/sl/usermodel/FillStyle.java deleted file mode 100644 index 59cff8dd4..000000000 --- a/src/java/org/apache/poi/sl/usermodel/FillStyle.java +++ /dev/null @@ -1,22 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.usermodel; - -public interface FillStyle { - PaintStyle getPaint(); -} diff --git a/src/java/org/apache/poi/sl/usermodel/FontCollection.java b/src/java/org/apache/poi/sl/usermodel/FontCollection.java deleted file mode 100644 index 61278f461..000000000 --- a/src/java/org/apache/poi/sl/usermodel/FontCollection.java +++ /dev/null @@ -1,22 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.usermodel; - -public interface FontCollection { - -} diff --git a/src/java/org/apache/poi/sl/usermodel/FreeformShape.java b/src/java/org/apache/poi/sl/usermodel/FreeformShape.java deleted file mode 100644 index c8ada26f2..000000000 --- a/src/java/org/apache/poi/sl/usermodel/FreeformShape.java +++ /dev/null @@ -1,45 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.usermodel; - -import java.awt.geom.Path2D; - -public interface FreeformShape< - S extends Shape, - P extends TextParagraph -> extends AutoShape { - /** - * Gets the shape path. - *

    - * The path is translated in the shape's coordinate system, i.e. - * freeform.getPath().getBounds2D() equals to freeform.getAnchor() - * (small discrepancies are possible due to rounding errors) - *

    - * - * @return the path - */ - Path2D.Double getPath(); - - /** - * Set the shape path - * - * @param path shape outline - * @return the number of points written - */ - int setPath(Path2D.Double path); -} diff --git a/src/java/org/apache/poi/sl/usermodel/GraphicalFrame.java b/src/java/org/apache/poi/sl/usermodel/GraphicalFrame.java deleted file mode 100644 index f8ba1e2c9..000000000 --- a/src/java/org/apache/poi/sl/usermodel/GraphicalFrame.java +++ /dev/null @@ -1,29 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.usermodel; - -public interface GraphicalFrame< - S extends Shape, - P extends TextParagraph -> extends Shape, PlaceableShape { - - /** - * @return a fallback representation as picture shape - */ - PictureShape getFallbackPicture(); -} diff --git a/src/java/org/apache/poi/sl/usermodel/GroupShape.java b/src/java/org/apache/poi/sl/usermodel/GroupShape.java deleted file mode 100644 index a7545a4d4..000000000 --- a/src/java/org/apache/poi/sl/usermodel/GroupShape.java +++ /dev/null @@ -1,42 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.usermodel; - -import java.awt.geom.Rectangle2D; - -public interface GroupShape< - S extends Shape, - P extends TextParagraph -> extends Shape, ShapeContainer, PlaceableShape { - - /** - * Gets the coordinate space of this group. All children are constrained - * to these coordinates. - * - * @return the coordinate space of this group - */ - Rectangle2D getInteriorAnchor(); - - /** - * Sets the coordinate space of this group. All children are constrained - * to these coordinates. - * - * @param anchor the coordinate space of this group - */ - void setInteriorAnchor(Rectangle2D anchor); -} diff --git a/src/java/org/apache/poi/sl/usermodel/Hyperlink.java b/src/java/org/apache/poi/sl/usermodel/Hyperlink.java deleted file mode 100644 index 3c2a9fc28..000000000 --- a/src/java/org/apache/poi/sl/usermodel/Hyperlink.java +++ /dev/null @@ -1,79 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.usermodel; - -/** - * A PowerPoint hyperlink - * @since POI 3.14 beta 2 - */ -public interface Hyperlink< - S extends Shape, - P extends TextParagraph -> extends org.apache.poi.common.usermodel.Hyperlink { - /** - * Link to an email - * - * @param emailAddress the email address - * @since POI 3.14-Beta2 - */ - void linkToEmail(String emailAddress); - - /** - * Link to a web page / URL - * - * @param url the url - * @since POI 3.14-Beta2 - */ - void linkToUrl(String url); - - /** - * Link to a slide in this slideshow - * - * @param slide the linked slide - * @since POI 3.14-Beta2 - */ - void linkToSlide(Slide slide); - - /** - * Link to the next slide (relative from the current) - * - * @since POI 3.14-Beta2 - */ - void linkToNextSlide(); - - /** - * Link to the previous slide (relative from the current) - * - * @since POI 3.14-Beta2 - */ - void linkToPreviousSlide(); - - /** - * Link to the first slide in this slideshow - * - * @since POI 3.14-Beta2 - */ - void linkToFirstSlide(); - - /** - * Link to the last slide in this slideshow - * - * @since POI 3.14-Beta2 - */ - void linkToLastSlide(); -} diff --git a/src/java/org/apache/poi/sl/usermodel/Insets2D.java b/src/java/org/apache/poi/sl/usermodel/Insets2D.java deleted file mode 100644 index 205e4053a..000000000 --- a/src/java/org/apache/poi/sl/usermodel/Insets2D.java +++ /dev/null @@ -1,140 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.usermodel; - -/** - * This is a replacement for {@link java.awt.Insets} which works on doubles - * instead of ints - */ -public final class Insets2D implements Cloneable { - - /** - * The inset from the top. - * This value is added to the Top of the rectangle - * to yield a new location for the Top. - */ - public double top; - - /** - * The inset from the left. - * This value is added to the Left of the rectangle - * to yield a new location for the Left edge. - */ - public double left; - - /** - * The inset from the bottom. - * This value is subtracted from the Bottom of the rectangle - * to yield a new location for the Bottom. - */ - public double bottom; - - /** - * The inset from the right. - * This value is subtracted from the Right of the rectangle - * to yield a new location for the Right edge. - */ - public double right; - - /** - * Creates and initializes a new Insets object with the - * specified top, left, bottom, and right insets. - * @param top the inset from the top. - * @param left the inset from the left. - * @param bottom the inset from the bottom. - * @param right the inset from the right. - */ - public Insets2D(double top, double left, double bottom, double right) { - this.top = top; - this.left = left; - this.bottom = bottom; - this.right = right; - } - - /** - * Set top, left, bottom, and right to the specified values - * - * @param top the inset from the top. - * @param left the inset from the left. - * @param bottom the inset from the bottom. - * @param right the inset from the right. - * @since 1.5 - */ - public void set(double top, double left, double bottom, double right) { - this.top = top; - this.left = left; - this.bottom = bottom; - this.right = right; - } - - /** - * Checks whether two insets objects are equal. Two instances - * of Insets are equal if the four integer values - * of the fields top, left, - * bottom, and right are all equal. - * @return true if the two insets are equal; - * otherwise false. - * @since JDK1.1 - */ - public boolean equals(Object obj) { - if (obj instanceof Insets2D) { - Insets2D insets = (Insets2D)obj; - return ((top == insets.top) && (left == insets.left) && - (bottom == insets.bottom) && (right == insets.right)); - } - return false; - } - - /** - * Returns the hash code for this Insets. - * - * @return a hash code for this Insets. - */ - public int hashCode() { - double sum1 = left + bottom; - double sum2 = right + top; - double val1 = sum1 * (sum1 + 1)/2 + left; - double val2 = sum2 * (sum2 + 1)/2 + top; - double sum3 = val1 + val2; - return (int)(sum3 * (sum3 + 1)/2 + val2); - } - - /** - * Returns a string representation of this Insets object. - * This method is intended to be used only for debugging purposes, and - * the content and format of the returned string may vary between - * implementations. The returned string may be empty but may not be - * null. - * - * @return a string representation of this Insets object. - */ - public String toString() { - return getClass().getName() + "[top=" + top + ",left=" + left + ",bottom=" + bottom + ",right=" + right + "]"; - } - - /** - * Create a copy of this object. - * @return a copy of this Insets2D object. - */ - @Override - public Insets2D clone() { - return new Insets2D(top, left, bottom, right); - } - - -} diff --git a/src/java/org/apache/poi/sl/usermodel/Line.java b/src/java/org/apache/poi/sl/usermodel/Line.java deleted file mode 100644 index e9325c55b..000000000 --- a/src/java/org/apache/poi/sl/usermodel/Line.java +++ /dev/null @@ -1,33 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.usermodel; - -import org.apache.poi.util.Internal; - -/** - * Interface for Lines ... this will be eventually removed, - * so don't depend on it in user classes, but use AutoShape instead! - */ - -@Internal -public interface Line< - S extends Shape, - P extends TextParagraph -> extends AutoShape { - -} diff --git a/src/java/org/apache/poi/sl/usermodel/LineDecoration.java b/src/java/org/apache/poi/sl/usermodel/LineDecoration.java deleted file mode 100644 index 7d78e8040..000000000 --- a/src/java/org/apache/poi/sl/usermodel/LineDecoration.java +++ /dev/null @@ -1,113 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.usermodel; - -public interface LineDecoration { - /** - * Represents the shape decoration that appears at the ends of lines. - */ - enum DecorationShape { - NONE(0,1), - TRIANGLE(1,2), - STEALTH(2,3), - DIAMOND(3,4), - OVAL(4,5), - ARROW(5,6); - - public final int nativeId; - public final int ooxmlId; - - DecorationShape(int nativeId, int ooxmlId) { - this.nativeId = nativeId; - this.ooxmlId = ooxmlId; - } - - public static DecorationShape fromNativeId(int nativeId) { - for (DecorationShape ld : values()) { - if (ld.nativeId == nativeId) return ld; - } - return null; - } - - public static DecorationShape fromOoxmlId(int ooxmlId) { - for (DecorationShape ds : values()) { - if (ds.ooxmlId == ooxmlId) return ds; - } - return null; - } - } - - enum DecorationSize { - SMALL(0, 1), - MEDIUM(1, 2), - LARGE(2, 3); - - public final int nativeId; - public final int ooxmlId; - - DecorationSize(int nativeId, int ooxmlId) { - this.nativeId = nativeId; - this.ooxmlId = ooxmlId; - } - - public static DecorationSize fromNativeId(int nativeId) { - for (DecorationSize ld : values()) { - if (ld.nativeId == nativeId) return ld; - } - return null; - } - - public static DecorationSize fromOoxmlId(int ooxmlId) { - for (DecorationSize ds : values()) { - if (ds.ooxmlId == ooxmlId) return ds; - } - return null; - } - } - - /** - * @return the line start shape - */ - DecorationShape getHeadShape(); - - /** - * @return the width of the start shape - */ - DecorationSize getHeadWidth(); - - /** - * @return the length of the start shape - */ - DecorationSize getHeadLength(); - - /** - * @return the line end shape - */ - DecorationShape getTailShape(); - - /** - * @return the width of the end shape - */ - DecorationSize getTailWidth(); - - /** - * @return the length of the end shape - */ - DecorationSize getTailLength(); - -} diff --git a/src/java/org/apache/poi/sl/usermodel/MasterSheet.java b/src/java/org/apache/poi/sl/usermodel/MasterSheet.java deleted file mode 100644 index fdfcf4380..000000000 --- a/src/java/org/apache/poi/sl/usermodel/MasterSheet.java +++ /dev/null @@ -1,25 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.usermodel; - -public interface MasterSheet< - S extends Shape, - P extends TextParagraph -> extends Sheet { - -} diff --git a/src/java/org/apache/poi/sl/usermodel/Notes.java b/src/java/org/apache/poi/sl/usermodel/Notes.java deleted file mode 100644 index d156e98a7..000000000 --- a/src/java/org/apache/poi/sl/usermodel/Notes.java +++ /dev/null @@ -1,27 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.usermodel; - -import java.util.List; - -public interface Notes< - S extends Shape, - P extends TextParagraph -> extends Sheet { - List> getTextParagraphs(); -} diff --git a/src/java/org/apache/poi/sl/usermodel/PaintStyle.java b/src/java/org/apache/poi/sl/usermodel/PaintStyle.java deleted file mode 100644 index 25651043b..000000000 --- a/src/java/org/apache/poi/sl/usermodel/PaintStyle.java +++ /dev/null @@ -1,59 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.usermodel; - -import java.io.InputStream; - - - -public interface PaintStyle { - - public interface SolidPaint extends PaintStyle { - ColorStyle getSolidColor(); - } - - public interface GradientPaint extends PaintStyle { - enum GradientType { linear, circular, shape } - - /** - * @return the angle of the gradient - */ - double getGradientAngle(); - ColorStyle[] getGradientColors(); - float[] getGradientFractions(); - boolean isRotatedWithShape(); - GradientType getGradientType(); - } - - public interface TexturePaint extends PaintStyle { - /** - * @return the raw image stream - */ - InputStream getImageData(); - - /** - * @return the content type of the image data - */ - String getContentType(); - - /** - * @return the alpha mask in percents [0..100000] - */ - int getAlpha(); - } -} diff --git a/src/java/org/apache/poi/sl/usermodel/PictureData.java b/src/java/org/apache/poi/sl/usermodel/PictureData.java deleted file mode 100644 index 60e6266b7..000000000 --- a/src/java/org/apache/poi/sl/usermodel/PictureData.java +++ /dev/null @@ -1,121 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.usermodel; - -import java.awt.Dimension; -import java.io.IOException; - -public interface PictureData { - - enum PictureType { - /** Extended windows meta file */ - EMF(2,2,"image/x-emf",".emf"), - /** Windows Meta File */ - WMF(3,3,"image/x-wmf",".wmf"), - /** Mac PICT format */ - PICT(4,4,"image/pict",".pict"), // or image/x-pict (for HSLF) ??? - /** JPEG format */ - JPEG(5,5,"image/jpeg",".jpg"), - /** PNG format */ - PNG(6,6,"image/png",".png"), - /** Device independent bitmap */ - DIB(7,7,"image/dib",".dib"), - /** GIF image format */ - GIF(-1,8,"image/gif",".gif"), - /** Tag Image File (.tiff) */ - TIFF(-1,9,"image/tiff",".tif"), - /** Encapsulated Postscript (.eps) */ - EPS(-1,10,"image/x-eps",".eps"), - /** Windows Bitmap (.bmp) */ - BMP(-1,11,"image/x-ms-bmp",".bmp"), - /** WordPerfect graphics (.wpg) */ - WPG(-1,12,"image/x-wpg",".wpg"), - /** Microsoft Windows Media Photo image (.wdp) */ - WDP(-1,13,"image/vnd.ms-photo",".wdp"); - - public final int nativeId, ooxmlId; - public final String contentType,extension; - - PictureType(int nativeId, int ooxmlId,String contentType,String extension) { - this.nativeId = nativeId; - this.ooxmlId = ooxmlId; - this.contentType = contentType; - this.extension = extension; - } - - public static PictureType forNativeID(int nativeId) { - for (PictureType ans : values()) { - if (ans.nativeId == nativeId) return ans; - } - return null; - } - - public static PictureType forOoxmlID(int ooxmlId) { - for (PictureType ans : values()) { - if (ans.ooxmlId == ooxmlId) return ans; - } - return null; - } - } - - - /** - * Returns content type (mime type) of this picture. - * - * @return content type of this picture. - */ - String getContentType(); - - /** - * @return the picture type - */ - PictureType getType(); - - /** - * Returns the binary data of this Picture - * @return picture data - */ - byte[] getData(); - - /** - * Sets the binary picture data - * @param data picture data - */ - void setData(byte[] data) throws IOException; - - /** - * Gets the checksum - the checksum can be of various length - - * mostly it's 8 (XSLF) or 16 (HSLF) bytes long. - * @return the checksum - */ - byte[] getChecksum(); - - /** - * Return the original image dimensions in points - * (for formats supported by BufferedImage). - * - * Will return a Dimension with a default width of 200x200 if the format unsupported. - */ - Dimension getImageDimension(); - - /** - * Return the original image dimensions in pixels - * @see PictureData#getImageDimension() - */ - Dimension getImageDimensionInPixels(); -} \ No newline at end of file diff --git a/src/java/org/apache/poi/sl/usermodel/PictureShape.java b/src/java/org/apache/poi/sl/usermodel/PictureShape.java deleted file mode 100644 index 671a43946..000000000 --- a/src/java/org/apache/poi/sl/usermodel/PictureShape.java +++ /dev/null @@ -1,40 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.usermodel; - -import java.awt.Insets; - -public interface PictureShape< - S extends Shape, - P extends TextParagraph -> extends SimpleShape { - /** - * Returns the picture data for this picture. - * - * @return the picture data for this picture. - */ - PictureData getPictureData(); - - /** - * Returns the clipping values as percent ratio relatively to the image size. - * The clipping are returned as insets converted/scaled to 100000 (=100%). - * - * @return the clipping rectangle, which is given in percent in relation to the image width/height - */ - Insets getClipping(); -} diff --git a/src/java/org/apache/poi/sl/usermodel/PlaceableShape.java b/src/java/org/apache/poi/sl/usermodel/PlaceableShape.java deleted file mode 100644 index da1981a04..000000000 --- a/src/java/org/apache/poi/sl/usermodel/PlaceableShape.java +++ /dev/null @@ -1,92 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.usermodel; - -import java.awt.geom.Rectangle2D; - -public interface PlaceableShape< - S extends Shape, - P extends TextParagraph -> { - ShapeContainer getParent(); - - /** - * @return the sheet this shape belongs to - */ - Sheet getSheet(); - - /** - * @return the position of this shape within the drawing canvas. - * The coordinates are expressed in points - */ - Rectangle2D getAnchor(); - - /** - * @param anchor the position of this shape within the drawing canvas. - * The coordinates are expressed in points - */ - void setAnchor(Rectangle2D anchor); - - /** - * Rotation angle in degrees - *

    - * Positive angles are clockwise (i.e., towards the positive y axis); - * negative angles are counter-clockwise (i.e., towards the negative y axis). - *

    - * - * @return rotation angle in degrees - */ - double getRotation(); - - /** - * Rotate this shape. - *

    - * Positive angles are clockwise (i.e., towards the positive y axis); - * negative angles are counter-clockwise (i.e., towards the negative y axis). - *

    - * - * @param theta the rotation angle in degrees. - */ - void setRotation(double theta); - - /** - * @param flip whether the shape is horizontally flipped - */ - void setFlipHorizontal(boolean flip); - - /** - * Whether the shape is vertically flipped - * - * @param flip whether the shape is vertically flipped - */ - void setFlipVertical(boolean flip); - - /** - * Whether the shape is horizontally flipped - * - * @return whether the shape is horizontally flipped - */ - boolean getFlipHorizontal(); - - /** - * Whether the shape is vertically flipped - * - * @return whether the shape is vertically flipped - */ - boolean getFlipVertical(); -} diff --git a/src/java/org/apache/poi/sl/usermodel/Placeholder.java b/src/java/org/apache/poi/sl/usermodel/Placeholder.java deleted file mode 100644 index 1d7e4c421..000000000 --- a/src/java/org/apache/poi/sl/usermodel/Placeholder.java +++ /dev/null @@ -1,156 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.usermodel; - -public enum Placeholder { - /** - * No placeholder shape. - */ - NONE(0,0,0,0,0), - /** - * Title text placeholder shape. - */ - TITLE(13,1,1,1,1), - /** - * Body text placeholder shape. - */ - BODY(14,2,12,6,2), - /** - * Center title text placeholder shape. - */ - CENTERED_TITLE(15,3,3,3,3), - /** - * Sub-title text placeholder shape. - */ - SUBTITLE(16,4,4,4,4), - /** - * Date placeholder shape. - */ - DATETIME(7,7,7,7,5), - /** - * Slide number placeholder shape. - */ - SLIDE_NUMBER(8,8,8,8,6), - /** - * Footer placeholder shape. - */ - FOOTER(9,9,9,9,7), - /** - * Header placeholder shape. - */ - HEADER(10,10,10,10,8), - /** - * Object placeholder shape. - */ - CONTENT(19,19,19,19,9), - /** - * Graph object placeholder shape. - */ - CHART(20,20,20,20,10), - /** - * Table object placeholder shape. - */ - TABLE(21,21,21,21,11), - /** - * Clipart object placeholder shape. - */ - CLIP_ART(22,22,22,22,12), - /** - * Organization chart object placeholder shape. - */ - DGM(23,23,23,23,13), - /** - * Media object placeholder shape. - */ - MEDIA(24,24,24,24,14), - /** - * Slide image placeholder shape. - */ - SLIDE_IMAGE(11,11,11,5,15), - /** - * Picture object placeholder shape. - */ - PICTURE(26,26,26,26,16), - /** - * Vertical object placeholder shape. - */ - VERTICAL_OBJECT(25,25,25,25,-2), - /** - * Vertical title text placeholder shape. - */ - VERTICAL_TEXT_TITLE(17,17,17,17,-2), - /** - * Vertical body text placeholder shape. - */ - VERTICAL_TEXT_BODY(18,18,18,18,-2) - ; - - public final int nativeSlideId; - public final int nativeSlideMasterId; - public final int nativeNotesId; - public final int nativeNotesMasterId; - public final int ooxmlId; - - Placeholder(int nativeSlideId, int nativeSlideMasterId, int nativeNotesId, int nativeNotesMasterId, int ooxmlId) { - this.nativeSlideId = nativeSlideId; - this.nativeSlideMasterId = nativeSlideMasterId; - this.nativeNotesId = nativeNotesId; - this.nativeNotesMasterId = nativeNotesMasterId; - this.ooxmlId = ooxmlId; - } - - public static Placeholder lookupNativeSlide(int nativeId) { - return lookupNative(nativeId, 0); - } - - public static Placeholder lookupNativeSlideMaster(int nativeId) { - return lookupNative(nativeId, 1); - } - - public static Placeholder lookupNativeNotes(int nativeId) { - return lookupNative(nativeId, 2); - } - - public static Placeholder lookupNativeNotesMaster(int nativeId) { - return lookupNative(nativeId, 3); - } - - - private static Placeholder lookupNative(int nativeId, int type) { - for (Placeholder ph : values()) { - if ( - type == 0 && ph.nativeSlideId == nativeId || - type == 1 && ph.nativeSlideMasterId == nativeId || - type == 2 && ph.nativeNotesId == nativeId || - type == 3 && ph.nativeNotesMasterId == nativeId - ) { - return ph; - } - } - return null; - } - - public static Placeholder lookupOoxml(int ooxmlId) { - for (Placeholder ph : values()) { - if (ph.ooxmlId == ooxmlId) { - return ph; - } - } - return null; - } -} \ No newline at end of file diff --git a/src/java/org/apache/poi/sl/usermodel/PresetColor.java b/src/java/org/apache/poi/sl/usermodel/PresetColor.java deleted file mode 100644 index b5c8e1ad5..000000000 --- a/src/java/org/apache/poi/sl/usermodel/PresetColor.java +++ /dev/null @@ -1,279 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.sl.usermodel; - -import java.awt.Color; -import java.util.HashMap; -import java.util.Map; - -/** - * Preset colors defined in DrawingML aka known/system colors - * - * @see KnownColor Enumeration - * @see Colors Class - */ -public enum PresetColor { - // the order of this enum can be found in the definition of .net System.Drawing.KnownColor enumeration - // or by running the the program in the linked documentation - - // default colors for theme-depending colors taken from ... (last post): - // https://social.technet.microsoft.com/Forums/windows/en-US/ac76cc56-6ff2-4778-b260-8141d7170a3b/windows-7-highlight-text-color-or-selected-text-color-in-aero - - // see ST_SystemColorVal for system color names - - /** The system-defined color of the active window's border. */ - ActiveBorder (0xffb4b4b4, 1, "activeBorder"), - /** The system-defined color of the background of the active window's title bar. */ - ActiveCaption (0xff99b4d1, 2, "activeCaption"), - /** The system-defined color of the text in the active window's title bar. */ - ActiveCaptionText (0xff000000, 3, "captionText"), - /** The application workspace is the area in a multiple-document view that is not being occupied by documents. */ - AppWorkspace (0xffababab, 4, "appWorkspace"), - /** The system-defined face color of a 3-D element. */ - Control (0xfff0f0f0, 5, "btnFace"), - /** The system-defined shadow color of a 3-D element. The shadow color is applied to parts of a 3-D element that face away from the light source. */ - ControlDark (0xff696969, 6, "btnShadow"), - /** The system-defined color that is the dark shadow color of a 3-D element. The dark shadow color is applied to the parts of a 3-D element that are the darkest color. */ - ControlDarkDark (0xff000000, 7, "3dDkShadow"), - /** The system-defined color that is the light color of a 3-D element. The light color is applied to parts of a 3-D element that face the light source. */ - ControlLight (0xffe3e3e3, 8, "btnHighlight"), - /** The system-defined highlight color of a 3-D element. The highlight color is applied to the parts of a 3-D element that are the lightest color. */ - ControlLightLight (0xffe3e3e3, 9, "3dLight"), - /** The system-defined color of text in a 3-D element. */ - ControlText (0xff000000, 10, "btnText"), - /** The system-defined color of the desktop. */ - Desktop (0xff000000, 11, "background"), - /** The system-defined color of dimmed text. Items in a list that are disabled are displayed in dimmed text. */ - GrayText (0xff6d6d6d, 12, "grayText"), - /** The system-defined color of the background of selected items. This includes selected menu items as well as selected text. */ - Highlight (0xff3399ff, 13, "highlight"), - /** The system-defined color of the text of selected items. */ - HighlightText (0xffffffff, 14, "highlightText"), - /** The system-defined color used to designate a hot-tracked item. Single-clicking a hot-tracked item executes the item. */ - HotTrack (0xff0066cc, 15, "hotLight"), - /** The system-defined color of an inactive window's border. */ - InactiveBorder (0xfff4f7fc, 16, "inactiveBorder"), - /** The system-defined color of the background of an inactive window's title bar. */ - InactiveCaption (0xffbfcddb, 17, "inactiveCaption"), - /** The system-defined color of the text in an inactive window's title bar. */ - InactiveCaptionText (0xff000000, 18, "inactiveCaptionText"), - /** The system-defined color of the background of a ToolTip. */ - Info (0xffffffe1, 19, "infoBk"), - /** The system-defined color of the text of a ToolTip. */ - InfoText (0xff000000, 20, "infoText"), - /** The system-defined color of a menu's background. */ - Menu (0xfff0f0f0, 21, "menu"), - /** The system-defined color of a menu's text. */ - MenuText (0xff000000, 22, "menuText"), - /** The system-defined color of the background of a scroll bar. */ - ScrollBar (0xffc8c8c8, 23, "scrollBar"), - /** The system-defined color of the background in the client area of a window. */ - Window (0xffffffff, 24, "window"), - /** The system-defined color of a window frame. */ - WindowFrame (0xff646464, 25, "windowFrame"), - /** The system-defined color of the text in the client area of a window. */ - WindowText (0xff000000, 26, "windowText"), - Transparent (0x00ffffff, 27, null), - AliceBlue (0xfff0f8ff, 28, "aliceBlue"), - AntiqueWhite (0xfffaebd7, 29, "antiqueWhite"), - Aqua (0xff00ffff, 30, "aqua"), - Aquamarine (0xff7fffd4, 31, "aquamarine"), - Azure (0xfff0ffff, 32, "azure"), - Beige (0xfff5f5dc, 33, "beige"), - Bisque (0xffffe4c4, 34, "bisque"), - Black (0xff000000, 35, "black"), - BlanchedAlmond (0xffffebcd, 36, "blanchedAlmond"), - Blue (0xff0000ff, 37, "blue"), - BlueViolet (0xff8a2be2, 38, "blueViolet"), - Brown (0xffa52a2a, 39, "brown"), - BurlyWood (0xffdeb887, 40, "burlyWood"), - CadetBlue (0xff5f9ea0, 41, "cadetBlue"), - Chartreuse (0xff7fff00, 42, "chartreuse"), - Chocolate (0xffd2691e, 43, "chocolate"), - Coral (0xffff7f50, 44, "coral"), - CornflowerBlue (0xff6495ed, 45, "cornflowerBlue"), - Cornsilk (0xfffff8dc, 46, "cornsilk"), - Crimson (0xffdc143c, 47, "crimson"), - Cyan (0xff00ffff, 48, "cyan"), - DarkBlue (0xff00008b, 49, "dkBlue"), - DarkCyan (0xff008b8b, 50, "dkCyan"), - DarkGoldenrod (0xffb8860b, 51, "dkGoldenrod"), - DarkGray (0xffa9a9a9, 52, "dkGray"), - DarkGreen (0xff006400, 53, "dkGreen"), - DarkKhaki (0xffbdb76b, 54, "dkKhaki"), - DarkMagenta (0xff8b008b, 55, "dkMagenta"), - DarkOliveGreen (0xff556b2f, 56, "dkOliveGreen"), - DarkOrange (0xffff8c00, 57, "dkOrange"), - DarkOrchid (0xff9932cc, 58, "dkOrchid"), - DarkRed (0xff8b0000, 59, "dkRed"), - DarkSalmon (0xffe9967a, 60, "dkSalmon"), - DarkSeaGreen (0xff8fbc8b, 61, "dkSeaGreen"), - DarkSlateBlue (0xff483d8b, 62, "dkSlateBlue"), - DarkSlateGray (0xff2f4f4f, 63, "dkSlateGray"), - DarkTurquoise (0xff00ced1, 64, "dkTurquoise"), - DarkViolet (0xff9400d3, 65, "dkViolet"), - DeepPink (0xffff1493, 66, "deepPink"), - DeepSkyBlue (0xff00bfff, 67, "deepSkyBlue"), - DimGray (0xff696969, 68, "dimGray"), - DodgerBlue (0xff1e90ff, 69, "dodgerBlue"), - Firebrick (0xffb22222, 70, "firebrick"), - FloralWhite (0xfffffaf0, 71, "floralWhite"), - ForestGreen (0xff228b22, 72, "forestGreen"), - Fuchsia (0xffff00ff, 73, "fuchsia"), - Gainsboro (0xffdcdcdc, 74, "gainsboro"), - GhostWhite (0xfff8f8ff, 75, "ghostWhite"), - Gold (0xffffd700, 76, "gold"), - Goldenrod (0xffdaa520, 77, "goldenrod"), - Gray (0xff808080, 78, "gray"), - Green (0xff008000, 79, "green"), - GreenYellow (0xffadff2f, 80, "greenYellow"), - Honeydew (0xfff0fff0, 81, "honeydew"), - HotPink (0xffff69b4, 82, "hotPink"), - IndianRed (0xffcd5c5c, 83, "indianRed"), - Indigo (0xff4b0082, 84, "indigo"), - Ivory (0xfffffff0, 85, "ivory"), - Khaki (0xfff0e68c, 86, "khaki"), - Lavender (0xffe6e6fa, 87, "lavender"), - LavenderBlush (0xfffff0f5, 88, "lavenderBlush"), - LawnGreen (0xff7cfc00, 89, "lawnGreen"), - LemonChiffon (0xfffffacd, 90, "lemonChiffon"), - LightBlue (0xffadd8e6, 91, "ltBlue"), - LightCoral (0xfff08080, 92, "ltCoral"), - LightCyan (0xffe0ffff, 93, "ltCyan"), - LightGoldenrodYellow (0xfffafa78, 94, "ltGoldenrodYellow"), - LightGray (0xffd3d3d3, 95, "ltGray"), - LightGreen (0xff90ee90, 96, "ltGreen"), - LightPink (0xffffb6c1, 97, "ltPink"), - LightSalmon (0xffffa07a, 98, "ltSalmon"), - LightSeaGreen (0xff20b2aa, 99, "ltSeaGreen"), - LightSkyBlue (0xff87cefa, 100, "ltSkyBlue"), - LightSlateGray (0xff778899, 101, "ltSlateGray"), - LightSteelBlue (0xffb0c4de, 102, "ltSteelBlue"), - LightYellow (0xffffffe0, 103, "ltYellow"), - Lime (0xff00ff00, 104, "lime"), - LimeGreen (0xff32cd32, 105, "limeGreen"), - Linen (0xfffaf0e6, 106, "linen"), - Magenta (0xffff00ff, 107, "magenta"), - Maroon (0xff800000, 108, "maroon"), - MediumAquamarine (0xff66cdaa, 109, "medAquamarine"), - MediumBlue (0xff0000cd, 110, "medBlue"), - MediumOrchid (0xffba55d3, 111, "medOrchid"), - MediumPurple (0xff9370db, 112, "medPurple"), - MediumSeaGreen (0xff3cb371, 113, "medSeaGreen"), - MediumSlateBlue (0xff7b68ee, 114, "medSlateBlue"), - MediumSpringGreen (0xff00fa9a, 115, "medSpringGreen"), - MediumTurquoise (0xff48d1cc, 116, "medTurquoise"), - MediumVioletRed (0xffc71585, 117, "medVioletRed"), - MidnightBlue (0xff191970, 118, "midnightBlue"), - MintCream (0xfff5fffa, 119, "mintCream"), - MistyRose (0xffffe4e1, 120, "mistyRose"), - Moccasin (0xffffe4b5, 121, "moccasin"), - NavajoWhite (0xffffdead, 122, "navajoWhite"), - Navy (0xff000080, 123, "navy"), - OldLace (0xfffdf5e6, 124, "oldLace"), - Olive (0xff808000, 125, "olive"), - OliveDrab (0xff6b8e23, 126, "oliveDrab"), - Orange (0xffffa500, 127, "orange"), - OrangeRed (0xffff4500, 128, "orangeRed"), - Orchid (0xffda70d6, 129, "orchid"), - PaleGoldenrod (0xffeee8aa, 130, "paleGoldenrod"), - PaleGreen (0xff98fb98, 131, "paleGreen"), - PaleTurquoise (0xffafeeee, 132, "paleTurquoise"), - PaleVioletRed (0xffdb7093, 133, "paleVioletRed"), - PapayaWhip (0xffffefd5, 134, "papayaWhip"), - PeachPuff (0xffffdab9, 135, "peachPuff"), - Peru (0xffcd853f, 136, "peru"), - Pink (0xffffc0cb, 137, "pink"), - Plum (0xffdda0dd, 138, "plum"), - PowderBlue (0xffb0e0e6, 139, "powderBlue"), - Purple (0xff800080, 140, "purple"), - Red (0xffff0000, 141, "red"), - RosyBrown (0xffbc8f8f, 142, "rosyBrown"), - RoyalBlue (0xff4169e1, 143, "royalBlue"), - SaddleBrown (0xff8b4513, 144, "saddleBrown"), - Salmon (0xfffa8072, 145, "salmon"), - SandyBrown (0xfff4a460, 146, "sandyBrown"), - SeaGreen (0xff2e8b57, 147, "seaGreen"), - SeaShell (0xfffff5ee, 148, "seaShell"), - Sienna (0xffa0522d, 149, "sienna"), - Silver (0xffc0c0c0, 150, "silver"), - SkyBlue (0xff87ceeb, 151, "skyBlue"), - SlateBlue (0xff6a5acd, 152, "slateBlue"), - SlateGray (0xff708090, 153, "slateGray"), - Snow (0xfffffafa, 154, "snow"), - SpringGreen (0xff00ff7f, 155, "springGreen"), - SteelBlue (0xff4682b4, 156, "steelBlue"), - Tan (0xffd2b48c, 157, "tan"), - Teal (0xff008080, 158, "teal"), - Thistle (0xffd8bfd8, 159, "thistle"), - Tomato (0xffff6347, 160, "tomato"), - Turquoise (0xff40e0d0, 161, "turquoise"), - Violet (0xffee82ee, 162, "violet"), - Wheat (0xfff5deb3, 163, "wheat"), - White (0xffffffff, 164, "white"), - WhiteSmoke (0xfff5f5f5, 165, "whiteSmoke"), - Yellow (0xffffff00, 166, "yellow"), - YellowGreen (0xff9acd32, 167, "yellowGreen"), - /** The system-defined face color of a 3-D element. */ - ButtonFace (0xfff0f0f0, 168, null), - /** The system-defined color that is the highlight color of a 3-D element. This color is applied to parts of a 3-D element that face the light source. */ - ButtonHighlight (0xffffffff, 169, null), - /** The system-defined color that is the shadow color of a 3-D element. This color is applied to parts of a 3-D element that face away from the light source. */ - ButtonShadow (0xffa0a0a0, 170, null), - /** The system-defined color of the lightest color in the color gradient of an active window's title bar. */ - GradientActiveCaption (0xffb9d1ea, 171, "gradientActiveCaption"), - /** The system-defined color of the lightest color in the color gradient of an inactive window's title bar. */ - GradientInactiveCaption (0xffd7e4f2, 172, "gradientInactiveCaption"), - /** The system-defined color of the background of a menu bar. */ - MenuBar (0xfff0f0f0, 173, "menuBar"), - /** The system-defined color used to highlight menu items when the menu appears as a flat menu. */ - MenuHighlight (0xff3399ff, 174, "menuHighlight") - ; - - public final Color color; - public final int nativeId; - public final String ooxmlId; - - PresetColor(Integer rgb, int nativeId, String ooxmlId) { - this.color = (rgb == null) ? null : new Color(rgb, true); - this.nativeId = nativeId; - this.ooxmlId = ooxmlId; - } - - private static final Map lookupOoxmlId; - - static { - lookupOoxmlId = new HashMap(); - for(PresetColor pc : PresetColor.values()) { - if (pc.ooxmlId != null) { - lookupOoxmlId.put(pc.ooxmlId, pc); - } - } - } - - public static PresetColor valueOfOoxmlId(String ooxmlId) { - return lookupOoxmlId.get(ooxmlId); - } - - public static PresetColor valueOfNativeId(int nativeId) { - PresetColor vals[] = values(); - return (0 < nativeId && nativeId <= vals.length) ? vals[nativeId-1] : null; - } -} diff --git a/src/java/org/apache/poi/sl/usermodel/RectAlign.java b/src/java/org/apache/poi/sl/usermodel/RectAlign.java deleted file mode 100644 index 471043f41..000000000 --- a/src/java/org/apache/poi/sl/usermodel/RectAlign.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -package org.apache.poi.sl.usermodel; - -/** - * Specifies possible rectangle alignment types. - * See org.openxmlformats.schemas.drawingml.x2006.main.STRectAlignment - * - * @see org.apache.poi.sl.draw.binding.STRectAlignment - */ -public enum RectAlign { - /** Top-Left rectangle alignment */ - TOP_LEFT("tl"), - - /** Top rectangle alignment */ - TOP("t"), - - /** Top-Right rectangle alignment */ - TOP_RIGHT("tr"), - - /** Left rectangle alignment */ - LEFT("l"), - - /** Center rectangle alignment */ - CENTER("ctr"), - - /** Right rectangle alignment */ - RIGHT("r"), - - /** Bottom-Left rectangle alignment */ - BOTTOM_LEFT("bl"), - - /** Bottom rectangle alignment */ - BOTTOM("b"), - - /** Bottom-Right rectangle alignment */ - BOTTOM_RIGHT("br"); - - /** The corresponding xml enum value */ - private final String dir; - - private RectAlign(String dir) { - this.dir = dir; - } - - - /** - * The string representation, - * which corresponds to the internal XML enum value - */ - @Override - public String toString() { - return dir; - } - -} - -/* ************************************************************************** */ diff --git a/src/java/org/apache/poi/sl/usermodel/Resources.java b/src/java/org/apache/poi/sl/usermodel/Resources.java deleted file mode 100644 index 96170e50b..000000000 --- a/src/java/org/apache/poi/sl/usermodel/Resources.java +++ /dev/null @@ -1,29 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.usermodel; - -/** - * Common SlideShow resources, such as fonts, pictures - * and multimedia data - */ -public interface Resources { - public FontCollection getFontCollection(); - - public PictureData[] getPictureData(); - public int addPictureData(PictureData pict); -} diff --git a/src/java/org/apache/poi/sl/usermodel/Shadow.java b/src/java/org/apache/poi/sl/usermodel/Shadow.java deleted file mode 100644 index 2c99f32b6..000000000 --- a/src/java/org/apache/poi/sl/usermodel/Shadow.java +++ /dev/null @@ -1,53 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.usermodel; - -import org.apache.poi.sl.usermodel.PaintStyle.SolidPaint; - - - -public interface Shadow< -S extends Shape, -P extends TextParagraph -> { - SimpleShape getShadowParent(); - - /** - * @return the offset of this shadow in points - */ - double getDistance(); - - /** - * - * @return the direction to offset the shadow in angles - */ - double getAngle(); - - /** - * - * @return the blur radius of the shadow - * TODO: figure out how to make sense of this property when rendering shadows - */ - double getBlur(); - - /** - * @return the color of this shadow. - * Depending whether the parent shape is filled or stroked, this color is used to fill or stroke this shadow - */ - SolidPaint getFillStyle(); -} diff --git a/src/java/org/apache/poi/sl/usermodel/Shape.java b/src/java/org/apache/poi/sl/usermodel/Shape.java deleted file mode 100644 index 0115f8b9a..000000000 --- a/src/java/org/apache/poi/sl/usermodel/Shape.java +++ /dev/null @@ -1,50 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.usermodel; - -import java.awt.Graphics2D; -import java.awt.geom.Rectangle2D; - -public interface Shape< - S extends Shape, - P extends TextParagraph -> { - ShapeContainer getParent(); - - /** - * @return the sheet this shape belongs to - */ - Sheet getSheet(); - - /** - * Returns the anchor (the bounding box rectangle) of this shape. - * All coordinates are expressed in points (72 dpi). - * - * @return the anchor of this shape - */ - Rectangle2D getAnchor(); - - /** - * Convenience method to draw a single shape - * - * @param graphics the graphics context - * @param bounds the rectangle to fit the shape to. - * if null, the bounds of the shape are used. - */ - void draw(Graphics2D graphics, Rectangle2D bounds); -} diff --git a/src/java/org/apache/poi/sl/usermodel/ShapeContainer.java b/src/java/org/apache/poi/sl/usermodel/ShapeContainer.java deleted file mode 100644 index 086501b4c..000000000 --- a/src/java/org/apache/poi/sl/usermodel/ShapeContainer.java +++ /dev/null @@ -1,87 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.usermodel; - -import java.util.List; - - -public interface ShapeContainer< - S extends Shape, - P extends TextParagraph -> extends Iterable { - /** - * Returns an list containing all of the elements in this container in proper - * sequence (from first to last element). - * - * @return an list containing all of the elements in this container in proper - * sequence - */ - List getShapes(); - - void addShape(S shape); - - /** - * Removes the specified shape from this sheet, if it is present - * (optional operation). If this sheet does not contain the element, - * it is unchanged. - * - * @param shape the shape to be removed from this sheet, if present - * @return true if this sheet contained the specified element - * @throws IllegalArgumentException if the type of the specified shape - * is incompatible with this sheet (optional) - */ - boolean removeShape(S shape); - - /** - * create a new shape with a predefined geometry and add it to this shape container - */ - AutoShape createAutoShape(); - - /** - * create a new shape with a custom geometry - */ - FreeformShape createFreeform(); - - /** - * create a text box - */ - TextBox createTextBox(); - - /** - * create a connector - */ - ConnectorShape createConnector(); - - /** - * create a group of shapes belonging to this container - */ - GroupShape createGroup(); - - /** - * create a picture belonging to this container - */ - PictureShape createPicture(PictureData pictureData); - - /** - * Create a new Table of the given number of rows and columns - * - * @param numRows the number of rows - * @param numCols the number of columns - */ - TableShape createTable(int numRows, int numCols); -} diff --git a/src/java/org/apache/poi/sl/usermodel/ShapeType.java b/src/java/org/apache/poi/sl/usermodel/ShapeType.java deleted file mode 100644 index b2cb73b0f..000000000 --- a/src/java/org/apache/poi/sl/usermodel/ShapeType.java +++ /dev/null @@ -1,321 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.usermodel; - -/** - * known preset shape geometries in PresentationML - */ -public enum ShapeType { - NOT_PRIMITIVE(-1, 0, "NotPrimitive"), - LINE(1, 20, "Line"), - LINE_INV(2, -1, null), - TRIANGLE(3, 5, "IsocelesTriangle"), - RT_TRIANGLE(4, 6, "RightTriangle"), - RECT(5, 1, "Rectangle"), - DIAMOND(6, 4, "Diamond"), - PARALLELOGRAM(7, 7, "Parallelogram"), - TRAPEZOID(8, 8, "Trapezoid"), - NON_ISOSCELES_TRAPEZOID(9, -1, null), - PENTAGON(10, 56, "Pentagon"), - HEXAGON(11, 9, "Hexagon"), - HEPTAGON(12, -1, null), - OCTAGON(13, 10, "Octagon"), - DECAGON(14, -1, null), - DODECAGON(15, -1, null), - STAR_4(16, 187, "Star4"), - STAR_5(17, 12, "Star"), // aka star in native - STAR_6(18, -1, null), - STAR_7(19, -1, null), - STAR_8(20, 58, "Star8"), - STAR_10(21, -1, null), - STAR_12(22, -1, null), - STAR_16(23, 59, "Star16"), - SEAL(23, 18, "Seal"), // same as star_16, but twice in native - STAR_24(24, 92, "Star24"), - STAR_32(25, 60, "Star32"), - ROUND_RECT(26, 2, "RoundRectangle"), - ROUND_1_RECT(27, -1, null), - ROUND_2_SAME_RECT(28, -1, null), - ROUND_2_DIAG_RECT(29, -1, null), - SNIP_ROUND_RECT(30, -1, null), - SNIP_1_RECT(31, -1, null), - SNIP_2_SAME_RECT(32, -1, null), - SNIP_2_DIAG_RECT(33, -1, null), - PLAQUE(34, 21, "Plaque"), - ELLIPSE(35, 3, "Ellipse"), - TEARDROP(36, -1, null), - HOME_PLATE(37, 15, "HomePlate"), - CHEVRON(38, 55, "Chevron"), - PIE_WEDGE(39, -1, null), - PIE(40, -1, null), - BLOCK_ARC(41, 95, "BlockArc"), - DONUT(42, 23, "Donut"), - NO_SMOKING(43, 57, "NoSmoking"), - RIGHT_ARROW(44, 13, "Arrow"), // aka arrow in native - LEFT_ARROW(45, 66, "LeftArrow"), - UP_ARROW(46, 68, "UpArrow"), - DOWN_ARROW(47, 67, "DownArrow"), - STRIPED_RIGHT_ARROW(48, 93, "StripedRightArrow"), - NOTCHED_RIGHT_ARROW(49, 94, "NotchedRightArrow"), - BENT_UP_ARROW(50, 90, "BentUpArrow"), - LEFT_RIGHT_ARROW(51, 69, "LeftRightArrow"), - UP_DOWN_ARROW(52, 70, "UpDownArrow"), - LEFT_UP_ARROW(53, 89, "LeftUpArrow"), - LEFT_RIGHT_UP_ARROW(54, 182, "LeftRightUpArrow"), - QUAD_ARROW(55, 76, "QuadArrow"), - LEFT_ARROW_CALLOUT(56, 77, "LeftArrowCallout"), - RIGHT_ARROW_CALLOUT(57, 78, "RightArrowCallout"), - UP_ARROW_CALLOUT(58, 79, "UpArrowCallout"), - DOWN_ARROW_CALLOUT(59, 80, "DownArrowCallout"), - LEFT_RIGHT_ARROW_CALLOUT(60, 81, "LeftRightArrowCallout"), - UP_DOWN_ARROW_CALLOUT(61, 82, "UpDownArrowCallout"), - QUAD_ARROW_CALLOUT(62, 83, "QuadArrowCallout"), - BENT_ARROW(63, 91, "BentArrow"), - UTURN_ARROW(64, 101, "UturnArrow"), - CIRCULAR_ARROW(65, 99, "CircularArrow"), - LEFT_CIRCULAR_ARROW(66, -1, null), - LEFT_RIGHT_CIRCULAR_ARROW(67, -1, null), - CURVED_RIGHT_ARROW(68, 102, "CurvedRightArrow"), - CURVED_LEFT_ARROW(69, 103, "CurvedLeftArrow"), - CURVED_UP_ARROW(70, 104, "CurvedUpArrow"), - CURVED_DOWN_ARROW(71, 105, "CurvedDownArrow"), - SWOOSH_ARROW(72, -1, null), - CUBE(73, 16, "Cube"), - CAN(74, 22, "Can"), - LIGHTNING_BOLT(75, 73, "LightningBolt"), - HEART(76, 74, "Heart"), - SUN(77, 183, "Sun"), - MOON(78, 184, "Moon"), - SMILEY_FACE(79, 96, "SmileyFace"), - IRREGULAR_SEAL_1(80, 71, "IrregularSeal1"), - IRREGULAR_SEAL_2(81, 72, "IrregularSeal2"), - FOLDED_CORNER(82, 65, "FoldedCorner"), - BEVEL(83, 84, "Bevel"), - FRAME(84, 75, "PictureFrame"), - HALF_FRAME(85, -1, null), - CORNER(86, -1, null), - DIAG_STRIPE(87, -1, null), - CHORD(88, -1, null), - ARC(89, 19, "Arc"), - LEFT_BRACKET(90, 85, "LeftBracket"), - RIGHT_BRACKET(91, 86, "RightBracket"), - LEFT_BRACE(92, 87, "LeftBrace"), - RIGHT_BRACE(93, 88, "RightBrace"), - BRACKET_PAIR(94, 185, "BracketPair"), - BRACE_PAIR(95, 186, "BracePair"), - STRAIGHT_CONNECTOR_1(96, 32, "StraightConnector1"), - BENT_CONNECTOR_2(97, 33, "BentConnector2"), - BENT_CONNECTOR_3(98, 34, "BentConnector3"), - BENT_CONNECTOR_4(99, 35, "BentConnector4"), - BENT_CONNECTOR_5(100, 36, "BentConnector5"), - CURVED_CONNECTOR_2(101, 37, "CurvedConnector2"), - CURVED_CONNECTOR_3(102, 38, "CurvedConnector3"), - CURVED_CONNECTOR_4(103, 39, "CurvedConnector4"), - CURVED_CONNECTOR_5(104, 40, "CurvedConnector5"), - CALLOUT_1(105, 41, "Callout1"), - CALLOUT_2(106, 42, "Callout2"), - CALLOUT_3(107, 43, "Callout3"), - ACCENT_CALLOUT_1(108, 44, "AccentCallout1"), - ACCENT_CALLOUT_2(109, 45, "AccentCallout2"), - ACCENT_CALLOUT_3(110, 46, "AccentCallout3"), - BORDER_CALLOUT_1(111, 47, "BorderCallout1"), - BORDER_CALLOUT_2(112, 48, "BorderCallout2"), - BORDER_CALLOUT_3(113, 49, "BorderCallout3"), - ACCENT_BORDER_CALLOUT_1(114, 50, "AccentBorderCallout1"), - ACCENT_BORDER_CALLOUT_2(115, 51, "AccentBorderCallout2"), - ACCENT_BORDER_CALLOUT_3(116, 52, "AccentBorderCallout3"), - WEDGE_RECT_CALLOUT(117, 61, "WedgeRectCallout"), - WEDGE_ROUND_RECT_CALLOUT(118, 62, "WedgeRRectCallout"), - WEDGE_ELLIPSE_CALLOUT(119, 63, "WedgeEllipseCallout"), - CLOUD_CALLOUT(120, 106, "CloudCallout"), - CLOUD(121, -1, null), - RIBBON(122, 53, "Ribbon"), - RIBBON_2(123, 54, "Ribbon2"), - ELLIPSE_RIBBON(124, 107, "EllipseRibbon"), - ELLIPSE_RIBBON_2(125, 108, "EllipseRibbon2"), - LEFT_RIGHT_RIBBON(126, -1, null), - VERTICAL_SCROLL(127, 97, "VerticalScroll"), - HORIZONTAL_SCROLL(128, 98, "HorizontalScroll"), - WAVE(129, 64, "Wave"), - DOUBLE_WAVE(130, 188, "DoubleWave"), - PLUS(131, 11, "Plus"), - FLOW_CHART_PROCESS(132, 109, "FlowChartProcess"), - FLOW_CHART_DECISION(133, 110, "FlowChartDecision"), - FLOW_CHART_INPUT_OUTPUT(134, 111, "FlowChartInputOutput"), - FLOW_CHART_PREDEFINED_PROCESS(135, 112, "FlowChartPredefinedProcess"), - FLOW_CHART_INTERNAL_STORAGE(136, 113, "FlowChartInternalStorage"), - FLOW_CHART_DOCUMENT(137, 114, "FlowChartDocument"), - FLOW_CHART_MULTIDOCUMENT(138, 115, "FlowChartMultidocument"), - FLOW_CHART_TERMINATOR(139, 116, "FlowChartTerminator"), - FLOW_CHART_PREPARATION(140, 117, "FlowChartPreparation"), - FLOW_CHART_MANUAL_INPUT(141, 118, "FlowChartManualInput"), - FLOW_CHART_MANUAL_OPERATION(142, 119, "FlowChartManualOperation"), - FLOW_CHART_CONNECTOR(143, 120, "FlowChartConnector"), - FLOW_CHART_PUNCHED_CARD(144, 121, "FlowChartPunchedCard"), - FLOW_CHART_PUNCHED_TAPE(145, 122, "FlowChartPunchedTape"), - FLOW_CHART_SUMMING_JUNCTION(146, 123, "FlowChartSummingJunction"), - FLOW_CHART_OR(147, 124, "FlowChartOr"), - FLOW_CHART_COLLATE(148, 125, "FlowChartCollate"), - FLOW_CHART_SORT(149, 126, "FlowChartSort"), - FLOW_CHART_EXTRACT(150, 127, "FlowChartExtract"), - FLOW_CHART_MERGE(151, 128, "FlowChartMerge"), - FLOW_CHART_OFFLINE_STORAGE(152, 129, "FlowChartOfflineStorage"), - FLOW_CHART_ONLINE_STORAGE(153, 130, "FlowChartOnlineStorage"), - FLOW_CHART_MAGNETIC_TAPE(154, 131, "FlowChartMagneticTape"), - FLOW_CHART_MAGNETIC_DISK(155, 132, "FlowChartMagneticDisk"), - FLOW_CHART_MAGNETIC_DRUM(156, 133, "FlowChartMagneticDrum"), - FLOW_CHART_DISPLAY(157, 134, "FlowChartDisplay"), - FLOW_CHART_DELAY(158, 135, "FlowChartDelay"), - FLOW_CHART_ALTERNATE_PROCESS(159, 176, "FlowChartAlternateProcess"), - FLOW_CHART_OFFPAGE_CONNECTOR(160, 177, "FlowChartOffpageConnector"), - ACTION_BUTTON_BLANK(161, 189, "ActionButtonBlank"), - ACTION_BUTTON_HOME(162, 190, "ActionButtonHome"), - ACTION_BUTTON_HELP(163, 191, "ActionButtonHelp"), - ACTION_BUTTON_INFORMATION(164, 192, "ActionButtonInformation"), - ACTION_BUTTON_FORWARD_NEXT(165, 193, "ActionButtonForwardNext"), - ACTION_BUTTON_BACK_PREVIOUS(166, 194, "ActionButtonBackPrevious"), - ACTION_BUTTON_END(167, 195, "ActionButtonEnd"), - ACTION_BUTTON_BEGINNING(168, 196, "ActionButtonBeginning"), - ACTION_BUTTON_RETURN(169, 197, "ActionButtonReturn"), - ACTION_BUTTON_DOCUMENT(170, 198, "ActionButtonDocument"), - ACTION_BUTTON_SOUND(171, 199, "ActionButtonSound"), - ACTION_BUTTON_MOVIE(172, 200, "ActionButtonMovie"), - GEAR_6(173, -1, null), - GEAR_9(174, -1, null), - FUNNEL(175, -1, null), - MATH_PLUS(176, -1, null), - MATH_MINUS(177, -1, null), - MATH_MULTIPLY(178, -1, null), - MATH_DIVIDE(179, -1, null), - MATH_EQUAL(180, -1, null), - MATH_NOT_EQUAL(181, -1, null), - CORNER_TABS(182, -1, null), - SQUARE_TABS(183, -1, null), - PLAQUE_TABS(184, -1, null), - CHART_X(185, -1, null), - CHART_STAR(186, -1, null), - CHART_PLUS(187, -1, null), - // below are shape types only found in native - NOTCHED_CIRCULAR_ARROW(-1, 100, "NotchedCircularArrow"), - THICK_ARROW(-1, 14, "ThickArrow"), - BALLOON(-1, 17, "Balloon"), - TEXT_SIMPLE(-1, 24, "TextSimple"), - TEXT_OCTAGON(-1, 25, "TextOctagon"), - TEXT_HEXAGON(-1, 26, "TextHexagon"), - TEXT_CURVE(-1, 27, "TextCurve"), - TEXT_WAVE(-1, 28, "TextWave"), - TEXT_RING(-1, 29, "TextRing"), - TEXT_ON_CURVE(-1, 30, "TextOnCurve"), - TEXT_ON_RING(-1, 31, "TextOnRing"), - TEXT_PLAIN_TEXT(-1, 136, "TextPlainText"), - TEXT_STOP(-1, 137, "TextStop"), - TEXT_TRIANGLE(-1, 138, "TextTriangle"), - TEXT_TRIANGLE_INVERTED(-1, 139, "TextTriangleInverted"), - TEXT_CHEVRON(-1, 140, "TextChevron"), - TEXT_CHEVRON_INVERTED(-1, 141, "TextChevronInverted"), - TEXT_RING_INSIDE(-1, 142, "TextRingInside"), - TEXT_RING_OUTSIDE(-1, 143, "TextRingOutside"), - TEXT_ARCH_UP_CURVE(-1, 144, "TextArchUpCurve"), - TEXT_ARCH_DOWN_CURVE(-1, 145, "TextArchDownCurve"), - TEXT_CIRCLE_CURVE(-1, 146, "TextCircleCurve"), - TEXT_BUTTON_CURVE(-1, 147, "TextButtonCurve"), - TEXT_ARCH_UP_POUR(-1, 148, "TextArchUpPour"), - TEXT_ARCH_DOWN_POUR(-1, 149, "TextArchDownPour"), - TEXT_CIRCLE_POUR(-1, 150, "TextCirclePour"), - TEXT_BUTTON_POUR(-1, 151, "TextButtonPour"), - TEXT_CURVE_UP(-1, 152, "TextCurveUp"), - TEXT_CURVE_DOWN(-1, 153, "TextCurveDown"), - TEXT_CASCADE_UP(-1, 154, "TextCascadeUp"), - TEXT_CASCADE_DOWN(-1, 155, "TextCascadeDown"), - TEXT_WAVE_1(-1, 156, "TextWave1"), - TEXT_WAVE_2(-1, 157, "TextWave2"), - TEXT_WAVE_3(-1, 158, "TextWave3"), - TEXT_WAVE_4(-1, 159, "TextWave4"), - TEXT_INFLATE(-1, 160, "TextInflate"), - TEXT_DEFLATE(-1, 161, "TextDeflate"), - TEXT_INFLATE_BOTTOM(-1, 162, "TextInflateBottom"), - TEXT_DEFLATE_BOTTOM(-1, 163, "TextDeflateBottom"), - TEXT_INFLATE_TOP(-1, 164, "TextInflateTop"), - TEXT_DEFLATE_TOP(-1, 165, "TextDeflateTop"), - TEXT_DEFLATE_INFLATE(-1, 166, "TextDeflateInflate"), - TEXT_DEFLATE_INFLATE_DEFLATE(-1, 167, "TextDeflateInflateDeflate"), - TEXT_FADE_RIGHT(-1, 168, "TextFadeRight"), - TEXT_FADE_LEFT(-1, 169, "TextFadeLeft"), - TEXT_FADE_UP(-1, 170, "TextFadeUp"), - TEXT_FADE_DOWN(-1, 171, "TextFadeDown"), - TEXT_SLANT_UP(-1, 172, "TextSlantUp"), - TEXT_SLANT_DOWN(-1, 173, "TextSlantDown"), - TEXT_CAN_UP(-1, 174, "TextCanUp"), - TEXT_CAN_DOWN(-1, 175, "TextCanDown"), - CALLOUT_90(-1, 178, "Callout90"), - ACCENT_CALLOUT_90(-1, 179, "AccentCallout90"), - BORDER_CALLOUT_90(-1, 180, "BorderCallout90"), - ACCENT_BORDER_CALLOUT_90(-1, 181, "AccentBorderCallout90"), - HOST_CONTROL(-1, 201, "HostControl"), - TEXT_BOX(-1, 202, "TextBox") - ; - - /** Preset-ID for XML-based shapes */ - public final int ooxmlId; - - /** Preset-ID for binary-based shapes */ - public final int nativeId; - - /** POI-specific name for the binary-based type */ - public final String nativeName; - - ShapeType(int ooxmlId, int nativeId, String nativeName){ - this.ooxmlId = ooxmlId; - this.nativeId = nativeId; - this.nativeName = nativeName; - } - - /** name of the presetShapeDefinit(i)on entry */ - public String getOoxmlName() { - if (this == SEAL) return STAR_16.getOoxmlName(); - if (ooxmlId == -1) { - return (name().startsWith("TEXT")) ? RECT.getOoxmlName() : null; - } - - StringBuilder sb = new StringBuilder(); - boolean toLower = true; - for (char ch : name().toCharArray()) { - if (ch == '_') { - toLower = false; - continue; - } - sb.append(toLower ? Character.toLowerCase(ch) : Character.toUpperCase(ch)); - toLower = true; - } - - return sb.toString(); - } - - public static ShapeType forId(int id, boolean isOoxmlId){ - // exemption for #60294 - if (!isOoxmlId && id == 0x0FFF) { - return NOT_PRIMITIVE; - } - - for(ShapeType t : values()){ - if((isOoxmlId && t.ooxmlId == id) || - (!isOoxmlId && t.nativeId == id)) return t; - } - throw new IllegalArgumentException("Unknown shape type: " + id); - } -} diff --git a/src/java/org/apache/poi/sl/usermodel/Sheet.java b/src/java/org/apache/poi/sl/usermodel/Sheet.java deleted file mode 100644 index cd2a6f18c..000000000 --- a/src/java/org/apache/poi/sl/usermodel/Sheet.java +++ /dev/null @@ -1,49 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.usermodel; - -import java.awt.Graphics2D; - - -/** - * Common parent of Slides, Notes and Masters - */ -public interface Sheet< - S extends Shape, - P extends TextParagraph -> extends ShapeContainer { - SlideShow getSlideShow(); - - /** - * @return whether shapes on the master sheet should be shown. By default master graphics is turned off. - * Sheets that support the notion of master (slide, slideLayout) should override it and - * check this setting in the sheet XML - */ - boolean getFollowMasterGraphics(); - - MasterSheet getMasterSheet(); - - Background getBackground(); - - /** - * Convenience method to draw a sheet to a graphics context - * - * @param graphics - */ - void draw(Graphics2D graphics); -} diff --git a/src/java/org/apache/poi/sl/usermodel/SimpleShape.java b/src/java/org/apache/poi/sl/usermodel/SimpleShape.java deleted file mode 100644 index aee69fb73..000000000 --- a/src/java/org/apache/poi/sl/usermodel/SimpleShape.java +++ /dev/null @@ -1,106 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.usermodel; - -import java.awt.Color; - -import org.apache.poi.sl.draw.geom.CustomGeometry; -import org.apache.poi.sl.draw.geom.IAdjustableShape; - - -public interface SimpleShape< - S extends Shape, - P extends TextParagraph -> extends Shape, IAdjustableShape, PlaceableShape { - - FillStyle getFillStyle(); - - LineDecoration getLineDecoration(); - - StrokeStyle getStrokeStyle(); - - /** - * Sets the line attributes. - * Possible attributes are Double (width), LineCap, LineDash, LineCompound, Color - * (implementations of PaintStyle aren't yet supported ...) - * - * If no styles are given, the line will be hidden - * - * @param styles the line attributes - */ - void setStrokeStyle(Object... styles); - - CustomGeometry getGeometry(); - - ShapeType getShapeType(); - void setShapeType(ShapeType type); - - /** - * @return the placeholder or null if none is assigned - * @see #setPlaceholder(Placeholder) - */ - Placeholder getPlaceholder(); - - /** - * Specifies that the corresponding shape should be represented by the generating application - * as a placeholder. When a shape is considered a placeholder by the generating application - * it can have special properties to alert the user that they may enter content into the shape. - * - * @param placeholder the placeholder or null to remove the reference to the placeholder - */ - void setPlaceholder(Placeholder placeholder); - - Shadow getShadow(); - - /** - * Returns the solid color fill. - * - * @return solid fill color of null if not set or fill color - * is not solid (pattern or gradient) - */ - Color getFillColor(); - - /** - * Specifies a solid color fill. The shape is filled entirely with the - * specified color. - * - * @param color the solid color fill. The value of null unsets - * the solid fill attribute from the underlying implementation - */ - void setFillColor(Color color); - - /** - * Returns the hyperlink assigned to this shape - * - * @return the hyperlink assigned to this shape - * or null if not found. - * - * @since POI 3.14-Beta1 - */ - Hyperlink getHyperlink(); - - /** - * Creates a hyperlink and asigns it to this shape. - * If the shape has already a hyperlink assigned, return it instead - * - * @return the hyperlink assigned to this shape - * - * @since POI 3.14-Beta1 - */ - Hyperlink createHyperlink(); -} diff --git a/src/java/org/apache/poi/sl/usermodel/Slide.java b/src/java/org/apache/poi/sl/usermodel/Slide.java deleted file mode 100644 index 1f77ba6e5..000000000 --- a/src/java/org/apache/poi/sl/usermodel/Slide.java +++ /dev/null @@ -1,56 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.usermodel; - -public interface Slide< - S extends Shape, - P extends TextParagraph -> extends Sheet { - Notes getNotes(); - void setNotes(Notes notes); - - boolean getFollowMasterBackground(); - void setFollowMasterBackground(boolean follow); - - boolean getFollowMasterColourScheme(); - void setFollowMasterColourScheme(boolean follow); - - boolean getFollowMasterObjects(); - void setFollowMasterObjects(boolean follow); - - /** - * @return the 1-based slide no. - */ - int getSlideNumber(); - - /** - * @return title of this slide or null if title is not set - */ - String getTitle(); - - /** - * In XSLF, slidenumber and date shapes aren't marked as placeholders - * whereas in HSLF they are activated via a HeadersFooter configuration. - * This method is used to generalize that handling. - * - * @param placeholder - * @return {@code true} if the placeholder should be displayed/rendered - * @since POI 3.16-beta2 - */ - boolean getDisplayPlaceholder(Placeholder placeholder); -} diff --git a/src/java/org/apache/poi/sl/usermodel/SlideShow.java b/src/java/org/apache/poi/sl/usermodel/SlideShow.java deleted file mode 100644 index 228925d1c..000000000 --- a/src/java/org/apache/poi/sl/usermodel/SlideShow.java +++ /dev/null @@ -1,121 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.usermodel; - -import java.awt.Dimension; -import java.io.Closeable; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.List; - -import org.apache.poi.sl.usermodel.PictureData.PictureType; - -public interface SlideShow< - S extends Shape, - P extends TextParagraph -> extends Closeable { - Slide createSlide() throws IOException; - - List> getSlides(); - - MasterSheet createMasterSheet() throws IOException; - - /** - * Returns all slide masters. - * This doesn't include notes master and other arbitrary masters. - */ - List> getSlideMasters(); - - Resources getResources(); - - /** - * Returns the current page size - * - * @return the page size - */ - Dimension getPageSize(); - - /** - * Change the current page size - * - * @param pgsize page size (in points) - */ - void setPageSize(Dimension pgsize); - - /** - * Returns all Pictures of this slideshow. - * The returned {@link List} is unmodifiable. - * @return a {@link List} of {@link PictureData}. - */ - List getPictureData(); - - /** - * Adds a picture to the presentation. - * - * @param pictureData The bytes of the picture - * @param format The format of the picture. - * - * @return the picture data reference. - */ - PictureData addPicture(byte[] pictureData, PictureType format) throws IOException; - - /** - * Adds a picture to the presentation. - * - * @param is The stream to read the image from - * @param format The format of the picture. - * - * @return the picture data reference. - * @since 3.15 beta 1 - */ - PictureData addPicture(InputStream is, PictureType format) throws IOException; - - /** - * Adds a picture to the presentation. - * - * @param pict The file containing the image to add - * @param format The format of the picture. - * - * @return the picture data reference - * @since 3.15 beta 1 - */ - PictureData addPicture(File pict, PictureType format) throws IOException; - - /** - * check if a picture with this picture data already exists in this presentation - * - * @param pictureData The picture data to find in the SlideShow - * @return {@code null} if picture data is not found in this slideshow - * @since 3.15 beta 3 - */ - PictureData findPictureData(byte[] pictureData); - - /** - * Writes out the slideshow file the is represented by an instance of this - * class - * - * @param out - * The OutputStream to write to. - * @throws IOException - * If there is an unexpected IOException from the passed in - * OutputStream - */ - void write(OutputStream out) throws IOException; -} diff --git a/src/java/org/apache/poi/sl/usermodel/SlideShowFactory.java b/src/java/org/apache/poi/sl/usermodel/SlideShowFactory.java deleted file mode 100644 index 92575d1d6..000000000 --- a/src/java/org/apache/poi/sl/usermodel/SlideShowFactory.java +++ /dev/null @@ -1,265 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.sl.usermodel; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.PushbackInputStream; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -import org.apache.poi.EncryptedDocumentException; -import org.apache.poi.OldFileFormatException; -import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey; -import org.apache.poi.poifs.crypt.Decryptor; -import org.apache.poi.poifs.filesystem.DirectoryNode; -import org.apache.poi.poifs.filesystem.DocumentFactoryHelper; -import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; -import org.apache.poi.poifs.filesystem.OfficeXmlFileException; -import org.apache.poi.util.IOUtils; - -public class SlideShowFactory { - /** - * Creates a SlideShow from the given NPOIFSFileSystem. - * - * @param fs The {@link NPOIFSFileSystem} to read the document from - * - * @return The created SlideShow - * - * @throws IOException if an error occurs while reading the data - */ - public static SlideShow create(NPOIFSFileSystem fs) throws IOException { - return create(fs, null); - } - - /** - * Creates a SlideShow from the given NPOIFSFileSystem, which may - * be password protected - * - * @param fs The {@link NPOIFSFileSystem} to read the document from - * @param password The password that should be used or null if no password is necessary. - * - * @return The created SlideShow - * - * @throws IOException if an error occurs while reading the data - */ - public static SlideShow create(final NPOIFSFileSystem fs, String password) throws IOException { - DirectoryNode root = fs.getRoot(); - - // Encrypted OOXML files go inside OLE2 containers, is this one? - if (root.hasEntry(Decryptor.DEFAULT_POIFS_ENTRY)) { - InputStream stream = null; - try { - stream = DocumentFactoryHelper.getDecryptedStream(fs, password); - - return createXSLFSlideShow(stream); - } finally { - IOUtils.closeQuietly(stream); - } - } - - // If we get here, it isn't an encrypted PPTX file - // So, treat it as a regular HSLF PPT one - if (password != null) { - Biff8EncryptionKey.setCurrentUserPassword(password); - } - try { - return createHSLFSlideShow(fs); - } finally { - Biff8EncryptionKey.setCurrentUserPassword(null); - } - } - - /** - * Creates the appropriate HSLFSlideShow / XMLSlideShow from - * the given InputStream. - * - *

    Your input stream MUST either support mark/reset, or - * be wrapped as a {@link PushbackInputStream}! Note that - * using an {@link InputStream} has a higher memory footprint - * than using a {@link File}.

    - * - *

    Note that in order to properly release resources the - * SlideShow should be closed after use. Note also that loading - * from an InputStream requires more memory than loading - * from a File, so prefer {@link #create(File)} where possible. - * - * @param inp The {@link InputStream} to read data from. - * - * @return The created SlideShow - * - * @throws IOException if an error occurs while reading the data - * @throws EncryptedDocumentException If the SlideShow given is password protected - */ - public static SlideShow create(InputStream inp) throws IOException, EncryptedDocumentException { - return create(inp, null); - } - - /** - * Creates the appropriate HSLFSlideShow / XMLSlideShow from - * the given InputStream, which may be password protected. - *

    Your input stream MUST either support mark/reset, or - * be wrapped as a {@link PushbackInputStream}! Note that - * using an {@link InputStream} has a higher memory footprint - * than using a {@link File}.

    - * - *

    Note that in order to properly release resources the - * SlideShow should be closed after use. Note also that loading - * from an InputStream requires more memory than loading - * from a File, so prefer {@link #create(File)} where possible.

    - * - * @param inp The {@link InputStream} to read data from. - * @param password The password that should be used or null if no password is necessary. - * - * @return The created SlideShow - * - * @throws IOException if an error occurs while reading the data - * @throws EncryptedDocumentException If the wrong password is given for a protected file - */ - public static SlideShow create(InputStream inp, String password) throws IOException, EncryptedDocumentException { - // If clearly doesn't do mark/reset, wrap up - if (! inp.markSupported()) { - inp = new PushbackInputStream(inp, 8); - } - - // Ensure that there is at least some data there - byte[] header8 = IOUtils.peekFirst8Bytes(inp); - - // Try to create - if (NPOIFSFileSystem.hasPOIFSHeader(header8)) { - NPOIFSFileSystem fs = new NPOIFSFileSystem(inp); - return create(fs, password); - } - if (DocumentFactoryHelper.hasOOXMLHeader(inp)) { - return createXSLFSlideShow(inp); - } - throw new IllegalArgumentException("Your InputStream was neither an OLE2 stream, nor an OOXML stream"); - } - - /** - * Creates the appropriate HSLFSlideShow / XMLSlideShow from - * the given File, which must exist and be readable. - *

    Note that in order to properly release resources the - * SlideShow should be closed after use. - * - * @param file The file to read data from. - * - * @return The created SlideShow - * - * @throws IOException if an error occurs while reading the data - * @throws EncryptedDocumentException If the SlideShow given is password protected - */ - public static SlideShow create(File file) throws IOException, EncryptedDocumentException { - return create(file, null); - } - - /** - * Creates the appropriate HSLFSlideShow / XMLSlideShow from - * the given File, which must exist and be readable, and - * may be password protected - *

    Note that in order to properly release resources the - * SlideShow should be closed after use. - * - * @param file The file to read data from. - * @param password The password that should be used or null if no password is necessary. - * - * @return The created SlideShow - * - * @throws IOException if an error occurs while reading the data - * @throws EncryptedDocumentException If the wrong password is given for a protected file - */ - public static SlideShow create(File file, String password) throws IOException, EncryptedDocumentException { - return create(file, password, false); - } - - /** - * Creates the appropriate HSLFSlideShow / XMLSlideShow from - * the given File, which must exist and be readable, and - * may be password protected - *

    Note that in order to properly release resources the - * SlideShow should be closed after use. - * - * @param file The file to read data from. - * @param password The password that should be used or null if no password is necessary. - * @param readOnly If the SlideShow should be opened in read-only mode to avoid writing back - * changes when the document is closed. - * - * @return The created SlideShow - * - * @throws IOException if an error occurs while reading the data - * @throws EncryptedDocumentException If the wrong password is given for a protected file - */ - public static SlideShow create(File file, String password, boolean readOnly) throws IOException, EncryptedDocumentException { - if (!file.exists()) { - throw new FileNotFoundException(file.toString()); - } - - NPOIFSFileSystem fs = null; - try { - fs = new NPOIFSFileSystem(file, readOnly); - return create(fs, password); - } catch(OfficeXmlFileException e) { - IOUtils.closeQuietly(fs); - return createXSLFSlideShow(file, readOnly); - } catch(RuntimeException e) { - IOUtils.closeQuietly(fs); - throw e; - } - } - - protected static SlideShow createHSLFSlideShow(Object... args) throws IOException, EncryptedDocumentException { - return createSlideShow("org.apache.poi.hslf.usermodel.HSLFSlideShowFactory", args); - } - - protected static SlideShow createXSLFSlideShow(Object... args) throws IOException, EncryptedDocumentException { - return createSlideShow("org.apache.poi.xslf.usermodel.XSLFSlideShowFactory", args); - } - - protected static SlideShow createSlideShow(String factoryClass, Object args[]) throws IOException, EncryptedDocumentException { - try { - Class clazz = Thread.currentThread().getContextClassLoader().loadClass(factoryClass); - Class argsClz[] = new Class[args.length]; - int i=0; - for (Object o : args) { - Class c = o.getClass(); - if (Boolean.class.isAssignableFrom(c)) { - c = boolean.class; - } else if (InputStream.class.isAssignableFrom(c)) { - c = InputStream.class; - } - argsClz[i++] = c; - } - Method m = clazz.getMethod("createSlideShow", argsClz); - return (SlideShow)m.invoke(null, args); - } catch (InvocationTargetException e) { - Throwable t = e.getCause(); - if (t instanceof IOException) { - throw (IOException)t; - } else if (t instanceof EncryptedDocumentException) { - throw (EncryptedDocumentException)t; - } else if (t instanceof OldFileFormatException) { - throw (OldFileFormatException)t; - } else { - throw new IOException(t); - } - } catch (Exception e) { - throw new IOException(e); - } - } -} diff --git a/src/java/org/apache/poi/sl/usermodel/StrokeStyle.java b/src/java/org/apache/poi/sl/usermodel/StrokeStyle.java deleted file mode 100644 index be93a994d..000000000 --- a/src/java/org/apache/poi/sl/usermodel/StrokeStyle.java +++ /dev/null @@ -1,147 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.usermodel; - -public interface StrokeStyle { - enum LineCap { - /** Rounded ends */ - ROUND(0,1), - /** Square protrudes by half line width */ - SQUARE(1,2), - /** Line ends at end point*/ - FLAT(2,3); - - public final int nativeId; - public final int ooxmlId; - - LineCap(int nativeId, int ooxmlId) { - this.nativeId = nativeId; - this.ooxmlId = ooxmlId; - } - - public static LineCap fromNativeId(int nativeId) { - for (LineCap ld : values()) { - if (ld.nativeId == nativeId) return ld; - } - return null; - } - - public static LineCap fromOoxmlId(int ooxmlId) { - for (LineCap lc : values()) { - if (lc.ooxmlId == ooxmlId) return lc; - } - return null; - } - } - - /** - * The line dash with pattern. - * The pattern is derived empirically on PowerPoint 2010 and needs to be multiplied - * with actual line width - */ - enum LineDash { - /** Solid (continuous) pen - native 1 */ - SOLID(1, 1, null), - /** square dot style - native 6 */ - DOT(6, 2, 1,1), - /** dash style - native 7 */ - DASH(7, 3, 3,4), - /** dash short dash - native 9*/ - DASH_DOT(9, 5, 4,3,1,3), - /** long dash style - native 8 */ - LG_DASH(8, 4, 8,3), - /** long dash short dash - native 10 */ - LG_DASH_DOT(10, 6, 8,3,1,3), - /** long dash short dash short dash - native 11 */ - LG_DASH_DOT_DOT(11, 7, 8,3,1,3,1,3), - /** PS_DASH system dash style - native 2 */ - SYS_DASH(2, 8, 2,2), - /** PS_DOT system dash style - native 3 */ - SYS_DOT(3, 9, 1,1), - /** PS_DASHDOT system dash style - native 4 */ - SYS_DASH_DOT(4, 10, 2,2,1,1), - /** PS_DASHDOTDOT system dash style / native 5 */ - SYS_DASH_DOT_DOT(5, 11, 2,2,1,1,1,1); - - public final int pattern[]; - public final int nativeId; - public final int ooxmlId; - - LineDash(int nativeId, int ooxmlId, int... pattern) { - this.nativeId = nativeId; - this.ooxmlId = ooxmlId; - this.pattern = (pattern == null || pattern.length == 0) ? null : pattern; - } - - public static LineDash fromNativeId(int nativeId) { - for (LineDash ld : values()) { - if (ld.nativeId == nativeId) return ld; - } - return null; - } - - public static LineDash fromOoxmlId(int ooxmlId) { - for (LineDash ld : values()) { - if (ld.ooxmlId == ooxmlId) return ld; - } - return null; - } - } - - enum LineCompound { - /** Single line (of width lineWidth) - native 0 / ooxml default */ - SINGLE(0, 1), - /** Double lines of equal width - native 1 / ooxml "dbl" */ - DOUBLE(1, 2), - /** Double lines, one thick, one thin - native 2 / ooxml "thickThin" */ - THICK_THIN(2, 3), - /** Double lines, reverse order - native 3 / ooxml "thinThick" */ - THIN_THICK(3, 4), - /** Three lines, thin, thick, thin - native 4 / ooxml "tri" */ - TRIPLE(4, 5); - - public final int nativeId; - public final int ooxmlId; - - LineCompound(int nativeId, int ooxmlId) { - this.nativeId = nativeId; - this.ooxmlId = ooxmlId; - } - - public static LineCompound fromNativeId(int nativeId) { - for (LineCompound lc : values()) { - if (lc.nativeId == nativeId) return lc; - } - return null; - } - - public static LineCompound fromOoxmlId(int ooxmlId) { - for (LineCompound lc : values()) { - if (lc.ooxmlId == ooxmlId) return lc; - } - return null; - } - } - - - PaintStyle getPaint(); - LineCap getLineCap(); - LineDash getLineDash(); - LineCompound getLineCompound(); - double getLineWidth(); -} diff --git a/src/java/org/apache/poi/sl/usermodel/TableCell.java b/src/java/org/apache/poi/sl/usermodel/TableCell.java deleted file mode 100644 index 1543148d7..000000000 --- a/src/java/org/apache/poi/sl/usermodel/TableCell.java +++ /dev/null @@ -1,114 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.usermodel; - -import java.awt.Color; - -import org.apache.poi.sl.usermodel.StrokeStyle.LineCompound; -import org.apache.poi.sl.usermodel.StrokeStyle.LineDash; - -public interface TableCell< - S extends Shape, - P extends TextParagraph -> extends TextShape { - enum BorderEdge { bottom, left, top, right } - - /** - * Return line style of given edge or {@code null} if border is not defined - * - * @param edge the border edge - * @return line style of given edge or {@code null} if border is not defined - */ - StrokeStyle getBorderStyle(BorderEdge edge); - - /** - * Sets the {@link StrokeStyle} of the given border edge. - * A {@code null} property of the style is ignored. - * - * @param edge border edge - * @param style the new stroke style - */ - void setBorderStyle(BorderEdge edge, StrokeStyle style); - - /** - * Convenience method for setting the border width. - * - * @param edge border edge - * @param width the new border width - */ - void setBorderWidth(BorderEdge edge, double width); - - /** - * Convenience method for setting the border color. - * - * @param edge border edge - * @param color the new border color - */ - void setBorderColor(BorderEdge edge, Color color); - - /** - * Convenience method for setting the border line compound. - * - * @param edge border edge - * @param compound the new border line compound - */ - void setBorderCompound(BorderEdge edge, LineCompound compound); - - /** - * Convenience method for setting the border line dash. - * - * @param edge border edge - * @param dash the new border line dash - */ - void setBorderDash(BorderEdge edge, LineDash dash); - - /** - * Remove all line attributes of the given border edge - * - * @param edge the border edge to be cleared - */ - void removeBorder(BorderEdge edge); - - /** - * Get the number of columns to be spanned/merged - * - * @return the grid span - * - * @since POI 3.15-beta2 - */ - int getGridSpan(); - - /** - * Get the number of rows to be spanned/merged - * - * @return the row span - * - * @since POI 3.15-beta2 - */ - int getRowSpan(); - - /** - * Return if this cell is part of a merged cell. The top/left cell of a merged region is not regarded as merged - - * its grid and/or row span is greater than one. - * - * @return true if this a merged cell - * - * @since POI 3.15-beta2 - */ - boolean isMerged(); -} diff --git a/src/java/org/apache/poi/sl/usermodel/TableShape.java b/src/java/org/apache/poi/sl/usermodel/TableShape.java deleted file mode 100644 index 7dbb13f00..000000000 --- a/src/java/org/apache/poi/sl/usermodel/TableShape.java +++ /dev/null @@ -1,80 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.usermodel; - -public interface TableShape< - S extends Shape, - P extends TextParagraph -> extends Shape, PlaceableShape { - /** - * Return the maximum number of columns. - * If the table contains merged cells, the number of columns might be less than the maximum. - * - * @return the maximum number of column - */ - int getNumberOfColumns(); - - /** - * Return the number of rows - * - * @return the row count - */ - int getNumberOfRows(); - - /** - * Gets a cell - * - * @param row the row index (0-based) - * @param col the column index (0-based) - * @return the cell or null if the cell doesn't exists, e.g. when accessing - * a merged cell or if the index is out of bounds - */ - TableCell getCell(int row, int col); - - /** - * Gets the width (in points) of the n-th column - * - * @param idx the column index (0-based) - * @return the width (in points) - */ - double getColumnWidth(int idx); - - /** - * Sets the width (in points) of the n-th column - * - * @param idx the column index (0-based) - * @param width the width (in points) - */ - void setColumnWidth(int idx, double width); - - /** - * Gets the row height - * - * @param row the row index (0-based) - * @return the height (in points) - */ - double getRowHeight(int row); - - /** - * Sets the row height. - * - * @param row the row index (0-based) - * @param height the height to set (in points) - */ - void setRowHeight(int row, double height); -} diff --git a/src/java/org/apache/poi/sl/usermodel/TextBox.java b/src/java/org/apache/poi/sl/usermodel/TextBox.java deleted file mode 100644 index bc6951103..000000000 --- a/src/java/org/apache/poi/sl/usermodel/TextBox.java +++ /dev/null @@ -1,31 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.usermodel; - -/** - * Represents a TextFrame shape in PowerPoint. - *

    - * Contains the text in a text frame as well as the properties and methods - * that control alignment and anchoring of the text. - *

    - */ -public interface TextBox< - S extends Shape, - P extends TextParagraph -> extends AutoShape { -} diff --git a/src/java/org/apache/poi/sl/usermodel/TextParagraph.java b/src/java/org/apache/poi/sl/usermodel/TextParagraph.java deleted file mode 100644 index 1c0913614..000000000 --- a/src/java/org/apache/poi/sl/usermodel/TextParagraph.java +++ /dev/null @@ -1,377 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.usermodel; - -import java.awt.Color; -import java.util.List; - - - -public interface TextParagraph< - S extends Shape, - P extends TextParagraph, - T extends TextRun -> extends Iterable { - - /** - * Specifies a list of text alignment types - */ - public enum TextAlign { - /** - * For horizontal text, left aligned. - * For vertical text, top aligned. - */ - LEFT, - - /** - * For horizontal text, centered. - * For vertical text, middle aligned. - */ - CENTER, - - /** - * For horizontal text, right aligned. - * For vertical text, bottom aligned. - */ - RIGHT, - - /** - * Align text so that it is justified across the whole line. It - * is smart in the sense that it will not justify sentences - * which are short - * - * For horizontal text, flush left and right. - * For vertical text, flush top and bottom. - */ - JUSTIFY, - - /** - * Kashida justify low. - */ - JUSTIFY_LOW, - - /** - * Distribute space between characters. - */ - DIST, - - /** - * Thai distribution justification. - */ - THAI_DIST - } - - /** - * - */ - public enum FontAlign { - AUTO, - - /** - * Characters hang from top of line height. - * Also known as "Hanging" - */ - TOP, - - /** - * Characters centered within line height. - */ - CENTER, - - /** - * Place characters on font baseline. - * Also known as "Roman" - */ - BASELINE, - - /** - * Characters are anchored to the very bottom of a single line. - * This is different than BASELINE because of letters such as "g", "q", and "y". - * Also known as "UpholdFixed" - */ - BOTTOM - } - - public interface BulletStyle { - String getBulletCharacter(); - String getBulletFont(); - - /** - * The bullet point font size - * If bulletFontSize >= 0, then space is a percentage of normal line height. - * If bulletFontSize < 0, the absolute value in points - * - * @return the bullet point font size - */ - Double getBulletFontSize(); - - /** - * Convenience function to set a solid color - */ - void setBulletFontColor(Color color); - - void setBulletFontColor(PaintStyle color); - - /** - * - * @return the color of bullet characters within a given paragraph. - * A {@code null} value means to use the text font color. - */ - PaintStyle getBulletFontColor(); - - AutoNumberingScheme getAutoNumberingScheme(); - /** - * Index (1-based) of the first auto number value, or null if auto numbering scheme - * wasn't assigned. - */ - Integer getAutoNumberingStartAt(); - } - - /** - * The amount of vertical white space before the paragraph - * This may be specified in two different ways, percentage spacing and font point spacing: - *

    - * If spaceBefore >= 0, then space is a percentage of normal line height. - * If spaceBefore < 0, the absolute value in points - *

    - * - * @return the vertical white space before the paragraph, or null if unset - */ - Double getSpaceBefore(); - - /** - * Set the amount of vertical white space that will be present before the paragraph. - * This space is specified in either percentage or points: - *

    - * If spaceBefore >= 0, then space is a percentage of normal line height. - * If spaceBefore < 0, the absolute value of linespacing is the spacing in points - *

    - * Examples: - *
    
    -     *      // The paragraph will be formatted to have a spacing before the paragraph text.
    -     *      // The spacing will be 200% of the size of the largest text on each line
    -     *      paragraph.setSpaceBefore(200);
    -     *
    -     *      // The spacing will be a size of 48 points
    -     *      paragraph.setSpaceBefore(-48.0);
    -     * 
    - * - * @param spaceBefore the vertical white space before the paragraph, null to unset - */ - void setSpaceBefore(Double spaceBefore); - - /** - * The amount of vertical white space after the paragraph - * This may be specified in two different ways, percentage spacing and font point spacing: - *

    - * If spaceBefore >= 0, then space is a percentage of normal line height. - * If spaceBefore < 0, the absolute value of linespacing is the spacing in points - *

    - * - * @return the vertical white space after the paragraph or null, if unset - */ - Double getSpaceAfter(); - - /** - * Set the amount of vertical white space that will be present after the paragraph. - * This space is specified in either percentage or points: - *

    - * If spaceAfter >= 0, then space is a percentage of normal line height. - * If spaceAfter < 0, the absolute value of linespacing is the spacing in points - *

    - * Examples: - *
    
    -     *      // The paragraph will be formatted to have a spacing after the paragraph text.
    -     *      // The spacing will be 200% of the size of the largest text on each line
    -     *      paragraph.setSpaceAfter(200);
    -     *
    -     *      // The spacing will be a size of 48 points
    -     *      paragraph.setSpaceAfter(-48.0);
    -     * 
    - * - * @param spaceAfter the vertical white space after the paragraph, null to unset - */ - public void setSpaceAfter(Double spaceAfter); - - /** - * @return the left margin (in points) of the paragraph or null, if unset - */ - Double getLeftMargin(); - - /** - * Specifies the left margin of the paragraph. This is specified in addition to the text body - * inset and applies only to this text paragraph. That is the text body Inset and the LeftMargin - * attributes are additive with respect to the text position. - * - * @param leftMargin the left margin (in points) or null to unset - */ - void setLeftMargin(Double leftMargin); - - - /** - * Specifies the right margin of the paragraph. This is specified in addition to the text body - * inset and applies only to this text paragraph. That is the text body Inset and the RightMargin - * attributes are additive with respect to the text position. - * - * The right margin is not support and therefore ignored by the HSLF implementation. - * - * @return the right margin (in points) of the paragraph or null, if unset - */ - Double getRightMargin(); - - /** - * @param rightMargin the right margin (in points) of the paragraph - */ - void setRightMargin(Double rightMargin); - - /** - * @return the indent (in points) applied to the first line of text in the paragraph. - * or null, if unset - */ - Double getIndent(); - - /** - * Specifies the indent size that will be applied to the first line of text in the paragraph. - * - * @param indent the indent (in points) applied to the first line of text in the paragraph - */ - void setIndent(Double indent); - - - /** - * @return the text level of this paragraph (0-based). Default is 0. - */ - int getIndentLevel(); - - /** - * Specifies the particular level text properties that this paragraph will follow. - * The value for this attribute formats the text according to the corresponding level - * paragraph properties defined in the SlideMaster. - * - * @param level the level (0 ... 4) - */ - void setIndentLevel(int level); - - /** - * Returns the vertical line spacing that is to be used within a paragraph. - * This may be specified in two different ways, percentage spacing and font point spacing: - *

    - * If linespacing >= 0, then linespacing is a percentage of normal line height. - * If linespacing < 0, the absolute value of linespacing is the spacing in points - *

    - * - * @return the vertical line spacing or null, if unset - */ - Double getLineSpacing(); - - /** - * This element specifies the vertical line spacing that is to be used within a paragraph. - * This may be specified in two different ways, percentage spacing and font point spacing: - *

    - * If linespacing >= 0, then linespacing is a percentage of normal line height - * If linespacing < 0, the absolute value of linespacing is the spacing in points - *

    - * Examples: - *
    
    -     *      // spacing will be 120% of the size of the largest text on each line
    -     *      paragraph.setLineSpacing(120);
    -     *
    -     *      // spacing will be 200% of the size of the largest text on each line
    -     *      paragraph.setLineSpacing(200);
    -     *
    -     *      // spacing will be 48 points
    -     *      paragraph.setLineSpacing(-48.0);
    -     * 
    - * - * @param lineSpacing the vertical line spacing - */ - void setLineSpacing(Double lineSpacing); - - String getDefaultFontFamily(); - - /** - * @return the default font size, in case its not set in the textrun or null, if unset - */ - Double getDefaultFontSize(); - - /** - * Returns the alignment that is applied to the paragraph. - * - * If this attribute is omitted, then null is returned. - * User code can imply the value {@link org.apache.poi.sl.usermodel.TextParagraph.TextAlign#LEFT} then. - * - * @return alignment that is applied to the paragraph - */ - TextAlign getTextAlign(); - - /** - * Specifies the alignment that is to be applied to the paragraph. - * Possible values for this include left, right, centered, justified and distributed, - * see {@link org.apache.poi.sl.usermodel.TextParagraph.TextAlign}. - * - * @param align text align - */ - void setTextAlign(TextAlign align); - - /** - * Returns the font alignment that is applied to the paragraph. - * - * If this attribute is omitted, then null is return, - * user code can imply the a value of {@link FontAlign#AUTO} - * - * @return alignment that is applied to the paragraph - */ - FontAlign getFontAlign(); - - /** - * @return the bullet style of the paragraph, if {@code null} then no bullets are used - */ - BulletStyle getBulletStyle(); - - /** - * Sets the bullet styles. If no styles are given, the bullets are omitted. - * Possible attributes are integer/double (bullet size), Color (bullet color), - * character (bullet character), string (bullet font), AutoNumberingScheme - * - * @param styles - */ - void setBulletStyle(Object... styles); - - /** - * @return the default size for a tab character within this paragraph in points, null if unset - */ - Double getDefaultTabSize(); - - - TextShape getParentShape(); - - /** - * Fetch the text runs that are contained within this block of text - */ - List getTextRuns(); - - /** - * Convenience method to determine if this text paragraph is part of - * the slide header or footer - * - * @return true if this paragraph is part of a header or footer placeholder - * - * @since POI 3.15-beta2 - */ - boolean isHeaderOrFooter(); -} \ No newline at end of file diff --git a/src/java/org/apache/poi/sl/usermodel/TextRun.java b/src/java/org/apache/poi/sl/usermodel/TextRun.java deleted file mode 100644 index 32b9c9933..000000000 --- a/src/java/org/apache/poi/sl/usermodel/TextRun.java +++ /dev/null @@ -1,192 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.usermodel; - -import java.awt.Color; - -import org.apache.poi.sl.usermodel.PaintStyle.SolidPaint; -import org.apache.poi.util.Internal; - -/** - * Some text. - */ -public interface TextRun { - enum TextCap { - NONE, - SMALL, - ALL - } - - enum FieldType { - SLIDE_NUMBER, DATE_TIME - } - - String getRawText(); - void setText(String text); - - TextCap getTextCap(); - - /** - * Returns the font color. - * This usually returns a {@link SolidPaint}, but but also other classes are possible - * - * @return the font color/paint - * - * @see org.apache.poi.sl.draw.DrawPaint#getPaint(java.awt.Graphics2D, PaintStyle) - * @see SolidPaint#getSolidColor() - * @see org.apache.poi.sl.draw.DrawPaint#applyColorTransform(ColorStyle) - */ - PaintStyle getFontColor(); - - /** - * Sets the (solid) font color - convenience function - * - * @param color the color - */ - void setFontColor(Color color); - - /** - * Sets the font color - * - * @param color the color - * - * @see org.apache.poi.sl.draw.DrawPaint#createSolidPaint(Color) - */ - void setFontColor(PaintStyle color); - - - /** - * Returns the font size which is either set directly on this text run or - * given from the slide layout - * - * @return font size in points or null if font size is not set. - */ - Double getFontSize(); - - /** - * Sets the font size directly on this text run, if null is given, the - * font size defaults to the values given from the slide layout - * - * @param fontSize font size in points, if null the underlying fontsize will be unset - */ - void setFontSize(Double fontSize); - - /** - * @return font family or null if not set - */ - String getFontFamily(); - - /** - * Specifies the typeface, or name of the font that is to be used for this text run. - * - * @param typeface the font to apply to this text run. - * The value of null unsets the Typeface attrubute from the underlying xml. - */ - void setFontFamily(String typeface); - - /** - * @return true, if text is bold - */ - boolean isBold(); - - /** - * Sets the bold state - * - * @param bold set to true for bold text, false for normal weight - */ - void setBold(boolean bold); - - /** - * @return true, if text is italic - */ - boolean isItalic(); - - /** - * Sets the italic state - * - * @param italic set to true for italic text, false for non-italics - */ - void setItalic(boolean italic); - - /** - * @return true, if text is underlined - */ - boolean isUnderlined(); - - /** - * Sets the underlined state - * - * @param underlined set to true for underlined text, false for no underlining - */ - void setUnderlined(boolean underlined); - - /** - * @return true, if text is stroked - */ - boolean isStrikethrough(); - - /** - * Sets the strikethrough state - * - * @param stroked set to true for stroked text, false for no stroking - */ - void setStrikethrough(boolean stroked); - - /** - * @return true, if text is sub scripted - */ - boolean isSubscript(); - - /** - * @return true, if text is super scripted - */ - boolean isSuperscript(); - - /** - * @return the pitch and family id or -1 if not applicable - */ - byte getPitchAndFamily(); - - /** - * Return the associated hyperlink - * - * @return the associated hyperlink or null if no hyperlink was set - * - * @since POI 3.14-Beta2 - */ - Hyperlink getHyperlink(); - - - /** - * Creates a new hyperlink and assigns it to this text run. - * If the text run has already a hyperlink assigned, return it instead - * - * @return the associated hyperlink - * - * @since POI 3.14-Beta2 - */ - Hyperlink createHyperlink(); - - /** - * Experimental method to determine the field type, e.g. slide number - * - * @return the field type or {@code null} if text run is not a field - */ - @Internal - FieldType getFieldType(); -} diff --git a/src/java/org/apache/poi/sl/usermodel/TextShape.java b/src/java/org/apache/poi/sl/usermodel/TextShape.java deleted file mode 100644 index a26db81cc..000000000 --- a/src/java/org/apache/poi/sl/usermodel/TextShape.java +++ /dev/null @@ -1,258 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.usermodel; - -import java.util.List; - -public interface TextShape< - S extends Shape, - P extends TextParagraph -> extends SimpleShape, Iterable

    { - /** - * Vertical Text Types - */ - enum TextDirection { - /** - * Horizontal text. This should be default. - */ - HORIZONTAL, - /** - * Vertical orientation. - * (each line is 90 degrees rotated clockwise, so it goes - * from top to bottom; each next line is to the left from - * the previous one). - */ - VERTICAL, - /** - * Vertical orientation. - * (each line is 270 degrees rotated clockwise, so it goes - * from bottom to top; each next line is to the right from - * the previous one). - * For HSLF: always interpreted by Powerpoint as HORIZONTAL. - */ - VERTICAL_270, - /** - * Determines if all of the text is vertical - * ("one letter on top of another"). - * For HSLF: not supported - */ - STACKED - } - - /** - * Specifies alist of auto-fit types. - *

    - * Autofit specofies that a shape should be auto-fit to fully contain the text described within it. - * Auto-fitting is when text within a shape is scaled in order to contain all the text inside - *

    - */ - enum TextAutofit { - /** - * Specifies that text within the text body should not be auto-fit to the bounding box. - * Auto-fitting is when text within a text box is scaled in order to remain inside - * the text box. - */ - NONE, - /** - * Specifies that text within the text body should be normally auto-fit to the bounding box. - * Autofitting is when text within a text box is scaled in order to remain inside the text box. - * - *

    - * Example: Consider the situation where a user is building a diagram and needs - * to have the text for each shape that they are using stay within the bounds of the shape. - * An easy way this might be done is by using NORMAL autofit - *

    - */ - NORMAL, - /** - * Specifies that a shape should be auto-fit to fully contain the text described within it. - * Auto-fitting is when text within a shape is scaled in order to contain all the text inside. - * - *

    - * Example: Consider the situation where a user is building a diagram and needs to have - * the text for each shape that they are using stay within the bounds of the shape. - * An easy way this might be done is by using SHAPE autofit - *

    - */ - SHAPE - } - - /** - * This enum represents a compromise for the handling of - * HSLF run types (see org.apache.poi.hslf.record.TextHeaderAtom) and - * XSLF placeholders (see org.apache.poi.xslf.usermodel.Placeholder). - * When a shape is considered a placeholder by the generating application - * it can have special properties to alert the user that they may enter content into the shape. - * - * This enum and the handling around it may change significantly in future releases - */ - enum TextPlaceholder { - /** Title placeholder shape text */ - TITLE, - /** Body placeholder shape text */ - BODY, - /** Center title placeholder shape text */ - CENTER_TITLE, - /** Center body placeholder shape text */ - CENTER_BODY, - /** Half-sized body placeholder shape text */ - HALF_BODY, - /** Quarter-sized body placeholder shape text */ - QUARTER_BODY, - /** Notes placeholder shape text */ - NOTES, - /** Any other text */ - OTHER - } - - /** - * Returns the text contained in this text frame, which has been made safe - * for printing and other use. - * - * @return the text string for this textbox. - * - * @since POI 3.14-Beta2 - */ - String getText(); - - /** - * Sets (overwrites) the current text. - * Uses the properties of the first paragraph / textrun. - * Text paragraphs are split by \\r or \\n. - * New lines within text run are split by \\u000b - * - * @param text the text string used by this object. - * - * @return the last text run of the - potential split - text - */ - TextRun setText(String text); - - /** - * Adds the supplied text onto the end of the TextParagraphs, - * creating a new RichTextRun for it to sit in. - * - * @param text the text string to be appended. - * @param newParagraph if true, a new paragraph will be added, - * which will contain the added text - * - * @since POI 3.14-Beta1 - */ - TextRun appendText(String text, boolean newParagraph); - - /** - * @return the TextParagraphs for this text box - */ - List> getTextParagraphs(); - - /** - * @return text shape margin - */ - Insets2D getInsets(); - - /** - * Sets the shape margins - * - * @param insets the new shape margins - */ - void setInsets(Insets2D insets); - - /** - * Compute the cumulative height occupied by the text - */ - double getTextHeight(); - - /** - * Returns the type of vertical alignment for the text. - * - * @return the type of vertical alignment - */ - VerticalAlignment getVerticalAlignment(); - - /** - * Sets the type of vertical alignment for the text. - * - * @param vAlign - the type of alignment. - * A {@code null} values unsets this property. - */ - void setVerticalAlignment(VerticalAlignment vAlign); - - /** - * Returns if the text is centered. - * If true and if the individual paragraph settings allow it, - * the whole text block will be displayed centered, i.e. its left and right - * margin will be maximized while still keeping the alignment of the paragraphs - * - * @return true, if the text anchor is horizontal centered - */ - boolean isHorizontalCentered(); - - /** - * Sets if the paragraphs are horizontal centered - * - * @param isCentered true, if the paragraphs are horizontal centered - * A {@code null} values unsets this property. - */ - void setHorizontalCentered(Boolean isCentered); - - /** - * @return whether to wrap words within the bounding rectangle - */ - boolean getWordWrap(); - - /** - * @param wrap whether to wrap words within the bounding rectangle - */ - void setWordWrap(boolean wrap); - - /** - * @return vertical orientation of the text - */ - TextDirection getTextDirection(); - - /** - * sets the vertical orientation - * @param orientation vertical orientation of the text - */ - void setTextDirection(TextDirection orientation); - - /** - * The text rotation can be independent specified from the shape rotation. - * For XSLF this can be an arbitrary degree, for HSLF the degree is given in steps of 90 degrees - * - * @return text rotation in degrees, returns null if no rotation is given - */ - Double getTextRotation(); - - /** - * Sets the text rotation. - * For XSLF this can ben an arbitrary degree, for HSLF the rotation is rounded to next 90 degree step - * - * @param rotation the text rotation, or null to unset the rotation - */ - void setTextRotation(Double rotation); - - /** - * Sets the text placeholder - */ - void setTextPlaceholder(TextPlaceholder placeholder); - - /** - * @return the text placeholder - */ - TextPlaceholder getTextPlaceholder(); -} \ No newline at end of file diff --git a/src/java/org/apache/poi/sl/usermodel/VerticalAlignment.java b/src/java/org/apache/poi/sl/usermodel/VerticalAlignment.java deleted file mode 100644 index f302d8288..000000000 --- a/src/java/org/apache/poi/sl/usermodel/VerticalAlignment.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -package org.apache.poi.sl.usermodel; - -/** - * Specifies a list of available anchoring types for text - * - * - * - * @author Yegor Kozlov - */ -public enum VerticalAlignment { - /** - * Anchor the text at the top of the bounding rectangle - */ - TOP, - - /** - * Anchor the text at the middle of the bounding rectangle - */ - MIDDLE, - - /** - * Anchor the text at the bottom of the bounding rectangle. - */ - BOTTOM, - - /** - * Anchor the text so that it is justified vertically. - *

    - * When text is horizontal, this spaces out the actual lines of - * text and is almost always identical in behavior to - * {@link #DISTRIBUTED} (special case: if only 1 line, then anchored at top). - *

    - *

    - * When text is vertical, then it justifies the letters - * vertically. This is different than {@link #DISTRIBUTED}, - * because in some cases such as very little text in a line, - * it will not justify. - *

    - */ - JUSTIFIED, - - /** - * Anchor the text so that it is distributed vertically. - *

    - * When text is horizontal, this spaces out the actual lines - * of text and is almost always identical in behavior to - * {@link #JUSTIFIED} (special case: if only 1 line, then anchored in middle). - *

    - *

    - * When text is vertical, then it distributes the letters vertically. - * This is different than {@link #JUSTIFIED}, because it always forces distribution - * of the words, even if there are only one or two words in a line. - */ - DISTRIBUTED -} diff --git a/src/java/org/apache/poi/wp/usermodel/CharacterRun.java b/src/java/org/apache/poi/wp/usermodel/CharacterRun.java deleted file mode 100644 index 549ef6779..000000000 --- a/src/java/org/apache/poi/wp/usermodel/CharacterRun.java +++ /dev/null @@ -1,109 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.wp.usermodel; - -/** - * This class represents a run of text that share common properties. - */ -public interface CharacterRun { - boolean isBold(); - void setBold(boolean bold); - - boolean isItalic(); - void setItalic(boolean italic); - - boolean isSmallCaps(); - void setSmallCaps(boolean smallCaps); - - boolean isCapitalized(); - void setCapitalized(boolean caps); - - boolean isStrikeThrough(); - void setStrikeThrough(boolean strike); - boolean isDoubleStrikeThrough(); - void setDoubleStrikethrough(boolean dstrike); - - boolean isShadowed(); - void setShadow(boolean shadow); - - boolean isEmbossed(); - void setEmbossed(boolean emboss); - - boolean isImprinted(); - void setImprinted(boolean imprint); - - int getFontSize(); - void setFontSize(int halfPoints); - - int getCharacterSpacing(); - void setCharacterSpacing(int twips); - - int getKerning(); - void setKerning(int kern); - - boolean isHighlighted(); - - // HWPF has colour indexes, XWPF has a highlight enum with the colours in -// byte getHighlightedColor(); -// void setHighlighted(byte color); - - // HWPF has colour indexes, XWPF colour names -// int getColor(); -// void setColor(int color); - - - /** - * Gets the fonts which shall be used to display the text contents of - * this run. Specifies a font which shall be used to format all "normal" - * characters in the run - * - * @return a string representing the font - */ - String getFontName(); - - /** - * @return The text of the run, including any tabs/spaces/etc - */ - String text(); - - // HWPF uses indexes, XWPF special -// int getUnderlineCode(); -// void setUnderlineCode(int kul); - - // HWPF uses indexes, XWPF special vertical alignments -// short getSubSuperScriptIndex(); -// void setSubSuperScriptIndex(short iss); - - // TODO Review these, and add to XWPFRun if possible -/* - boolean isFldVanished(); - void setFldVanish(boolean fldVanish); - - boolean isOutlined(); - void setOutline(boolean outlined); - - boolean isVanished(); - void setVanished(boolean vanish); - - boolean isMarkedDeleted(); - void markDeleted(boolean mark); - - boolean isMarkedInserted(); - void markInserted(boolean mark); -*/ -} diff --git a/src/java/org/apache/poi/wp/usermodel/HeaderFooterType.java b/src/java/org/apache/poi/wp/usermodel/HeaderFooterType.java deleted file mode 100644 index bca6b6658..000000000 --- a/src/java/org/apache/poi/wp/usermodel/HeaderFooterType.java +++ /dev/null @@ -1,62 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.wp.usermodel; - -/** - * @since POI v3.16 beta 1 - */ -public enum HeaderFooterType { - - /** - * This is the default header or Footer, It is displayed on every page where - * a more specific header or footer is not specified. It is always displayed - * on ODD pages that are not the first page of the section. - */ - DEFAULT(2), - - /** - * This is an even page header or footer, it is displayed on even pages that - * are not the first page of the section. - */ - EVEN(1), - - /** - * This is a first page header or footer It is displayed on the first page - * of the section. - */ - FIRST(3); - - private final int code; - - private HeaderFooterType(int i) { - code = i; - } - - public int toInt() { - return code; - } - - public static HeaderFooterType forInt(int i) { - for (HeaderFooterType type : values()) { - if (type.code == i) { - return type; - } - } - throw new IllegalArgumentException("Invalid HeaderFooterType code: " + i); - } -} diff --git a/src/java/org/apache/poi/wp/usermodel/Paragraph.java b/src/java/org/apache/poi/wp/usermodel/Paragraph.java deleted file mode 100644 index be488a2ef..000000000 --- a/src/java/org/apache/poi/wp/usermodel/Paragraph.java +++ /dev/null @@ -1,145 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.wp.usermodel; - -/** - * This class represents a paragraph, made up of one or more - * runs of text. - */ -public interface Paragraph { - // Tables work very differently between the formats -// public boolean isInTable(); -// public boolean isTableRowEnd(); -// public int getTableLevel(); - - // TODO Implement justifaction in XWPF -// public int getJustification(); -// public void setJustification(byte jc); - - // TODO Expose the different page break related things, - // XWPF currently doesn't have the full set -/* - public boolean keepOnPage(); - public void setKeepOnPage(boolean fKeep); - - public boolean keepWithNext(); - public void setKeepWithNext(boolean fKeepFollow); - - public boolean pageBreakBefore(); - public void setPageBreakBefore(boolean fPageBreak); - - public boolean isSideBySide(); - public void setSideBySide(boolean fSideBySide); -*/ - - public int getIndentFromRight(); - public void setIndentFromRight(int dxaRight); - - public int getIndentFromLeft(); - public void setIndentFromLeft(int dxaLeft); - - public int getFirstLineIndent(); - public void setFirstLineIndent(int first); - -/* - public boolean isLineNotNumbered(); - public void setLineNotNumbered(boolean fNoLnn); - - public boolean isAutoHyphenated(); - public void setAutoHyphenated(boolean autoHyph); - - public boolean isWidowControlled(); - public void setWidowControl(boolean widowControl); - - public int getSpacingBefore(); - public void setSpacingBefore(int before); - - public int getSpacingAfter(); - public void setSpacingAfter(int after); -*/ - - // public LineSpacingDescriptor getLineSpacing(); - // public void setLineSpacing(LineSpacingDescriptor lspd); - - public int getFontAlignment(); - public void setFontAlignment(int align); - - public boolean isWordWrapped(); - public void setWordWrapped(boolean wrap); - -/* - public boolean isVertical(); - public void setVertical(boolean vertical); - - public boolean isBackward(); - public void setBackward(boolean bward); -*/ - - // TODO Make the HWPF and XWPF interface wrappers compatible for these -/* - public BorderCode getTopBorder(); - public void setTopBorder(BorderCode top); - public BorderCode getLeftBorder(); - public void setLeftBorder(BorderCode left); - public BorderCode getBottomBorder(); - public void setBottomBorder(BorderCode bottom); - public BorderCode getRightBorder(); - public void setRightBorder(BorderCode right); - public BorderCode getBarBorder(); - public void setBarBorder(BorderCode bar); - - public ShadingDescriptor getShading(); - public void setShading(ShadingDescriptor shd); -*/ - - /** - * Returns the ilfo, an index to the document's hpllfo, which - * describes the automatic number formatting of the paragraph. - * A value of zero means it isn't numbered. - */ -// public int getIlfo(); - - /** - * Returns the multi-level indent for the paragraph. Will be - * zero for non-list paragraphs, and the first level of any - * list. Subsequent levels in hold values 1-8. - */ -// public int getIlvl(); - - /** - * Returns the heading level (1-8), or 9 if the paragraph - * isn't in a heading style. - */ -// public int getLvl(); - - /** - * Returns number of tabs stops defined for paragraph. Must be >= 0 and <= - * 64. - * - * @return number of tabs stops defined for paragraph. Must be >= 0 and <= - * 64 - */ -// public int getTabStopsNumber(); - - /** - * Returns array of positions of itbdMac tab stops - * - * @return array of positions of itbdMac tab stops - */ -// public int[] getTabStopsPositions(); -} diff --git a/src/models/BlockClassDiagram.pgml b/src/models/BlockClassDiagram.pgml deleted file mode 100644 index 11d979ad4..000000000 --- a/src/models/BlockClassDiagram.pgml +++ /dev/null @@ -1,621 +0,0 @@ - - - - - - - - - - BigBlock - - #BIG_BLOCK_SIZE : int = 512 - +writeData(in stream:OutputStream) -#doWriteData(in stream:OutputStream, in data[]:byte) - - - - - - - HeaderBlock - - -_bat_count : IntegerField --_property_start : IntegerField --_sbat_start : IntegerField = -2 --_xbat_start : IntegerField = -2 --_xbat_count : IntegerField = 0 --_data[ 512 ] : byte - +setBATBlocks(in blockCount:int, in startBlock:int) : BATBlock -+setPropertyStart(in startBlock:int) -+setXBATStart(in startBlock:int) -+Header() -+calculateXBATStorageRequirements(in blockCount:int) : int - - - - - - - PropertyBlock - - -_properties[ 4 ] : Property - +createPropertyBlockArray(in properties:List) : BlockWritable - - - - - - - BATBlock - - -_fields[ 128 ] : IntegerField --_data[ 512 ] : byte - +createBATBlocks(in entries[]:int) : BATBlock -+calculateStorageRequirements(in entryCount:int) : int - - - - - - - DocumentBlock - - -_data[ 512 ] : byte --_bytes_read : int - +DocumentBlock(in stream:InputStream) -+size() : int -+partiallyRead() : boolean - - - - - - - <<Interface>> - BlockWritable - +writeBlocks(in stream:OutputStream) - - - - sourcePortFig="Fig1.0" - destPortFig="Fig0.0" - sourceFigNode="Fig1" - destFigNode="Fig0" - - - - - - - - - - - sourcePortFig="Fig2.0" - destPortFig="Fig0.0" - sourceFigNode="Fig2" - destFigNode="Fig0" - - - - - - - - - - - sourcePortFig="Fig3.0" - destPortFig="Fig0.0" - sourceFigNode="Fig3" - destFigNode="Fig0" - - - - - - - - - - - - sourcePortFig="Fig4.0" - destPortFig="Fig0.0" - sourceFigNode="Fig4" - destFigNode="Fig0" - - - - - - - - - - - sourcePortFig="Fig0.0" - destPortFig="Fig5.0" - sourceFigNode="Fig0" - destFigNode="Fig5" - - - - - - - - - diff --git a/src/models/HSSFOperationalUseCases.pgml b/src/models/HSSFOperationalUseCases.pgml deleted file mode 100644 index fe331fdff..000000000 --- a/src/models/HSSFOperationalUseCases.pgml +++ /dev/null @@ -1,730 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - ClientApps - - - - - - - create HSSF File - - - - - - - write Workbook Entry - - - - - - - write sheet entry - - - - - - - new MUseCase - - - - - - - new MUseCase - - - - - - - new MUseCase - - - - - - - new MUseCase - - - - - - - new MUseCase - - - - - - - new MUseCase - - - - sourcePortFig="Fig0.0" - destPortFig="Fig1.0" - sourceFigNode="Fig0" - destFigNode="Fig1" - - - - - - - - - - - sourcePortFig="Fig1.0" - destPortFig="Fig2.0" - sourceFigNode="Fig1" - destFigNode="Fig2" - - - - - - - - - - - sourcePortFig="Fig0.0" - destPortFig="Fig3.0" - sourceFigNode="Fig0" - destFigNode="Fig3" - - - - - - - - - - - sourcePortFig="Fig0.0" - destPortFig="Fig4.0" - sourceFigNode="Fig0" - destFigNode="Fig4" - - - - - - - - - - - sourcePortFig="Fig0.0" - destPortFig="Fig5.0" - sourceFigNode="Fig0" - destFigNode="Fig5" - - - - - - - - - - - sourcePortFig="Fig0.0" - destPortFig="Fig6.0" - sourceFigNode="Fig0" - destFigNode="Fig6" - - - - - - - - - - - sourcePortFig="Fig0.0" - destPortFig="Fig7.0" - sourceFigNode="Fig0" - destFigNode="Fig7" - - - - - - - - - - - sourcePortFig="Fig0.0" - destPortFig="Fig9.0" - sourceFigNode="Fig0" - destFigNode="Fig9" - - - - - - - - - - - sourcePortFig="Fig0.0" - destPortFig="Fig8.0" - sourceFigNode="Fig0" - destFigNode="Fig8" - - - - - - - - - diff --git a/src/models/HSSFSerializerClassDiagram.pgml b/src/models/HSSFSerializerClassDiagram.pgml deleted file mode 100644 index 474a2bfb0..000000000 --- a/src/models/HSSFSerializerClassDiagram.pgml +++ /dev/null @@ -1,669 +0,0 @@ - - - - - - - - - - POIFSSerializer - - -_output_stream : OutputStream = null --_locator : Locator = null --_open_elements : Stack = new Stack() --_filesystem : Filesystem = new Filesystem() - +startPrefixMapping(in ignoredPrefix:String, in ignoredUri:String) -+endPrefixMapping(in ignoredPrefix:String) -+processingInstruction(in ignoredTarget:String, in ignoredData:String) -+skippedEntity(in ignoredName:String) -+startDTD(in ignoredName:String, in ignoredPublicId:String, in ignoredSystemId:String) -+endDTD() -+startEntity(in ignoredName:String) -+endEntity(in ignoredName:String) -+startCDATA() -+endCDATA() -+comment(in ignoredCh[]:char, in ignoredStart:int, in ignoredLength:int) -+shouldSetContentLength() : boolean -+setOutputStream(in out:OutputStream) -+setDocumentLocator(in locator:Locator) -+startDocument() -+endDocument() -+startElement(in namespaceURI:String, in localName:String, in qName:String, in atts:Attributes) -+endElement(in namespaceURI:String, in localName:String, in qName:String) -+characters(in ch[]:char, in start:int, in length:int) -+ignorableWhitespace(in ch[]:char, in start:int, in length:int) -#getElementProcessorFactory() : ElementProcessorFactory -#doLocalPreEndDocument() -#doLocalPostEndDocument() -#getFilesystem() : Filesystem -#SAXExceptionFactory(in message:String, in e:Exception) : SAXException -#SAXExceptionFactory(in message:String) : SAXException - - - - - - - Attribute - - -_name : String --_value : String - +getName() : String -+getValue() : String -+getValueAsInt() : int -+getValueAsShort() : short -+getValueAsLong() : long -+getValueAsBoolean() : boolean -+Attribute(in name:String, in value:String) - - - - - - - <<Interface>> - ElementProcessor - +initialize(in attributes[]:Attribute, in parent:ElementProcessor, in filesystem:Filesystem) -+acceptCharacters(in data[]:char) -+acceptWhitespaceCharacters(in data[]:char) -+endProcessing() - - - - - - - ElementProcessorFactory - - -_element_processor_map : Map - +createElementProcessor(in name:String) : ElementProcessor -#addElementProcessorProgenitor(in name:String, in progenitor:Object) -#lookupElementProcessorProgenitor(in name:String) : Object -#doCreateElementProcessor(in progenitor:Object) : ElementProcessor -#constructElementProcessor(in progenitor:Constructor) : ElementProcessor -#createNewElementProcessorInstance(in progenitor:Class) : ElementProcessor - - - - - - - HSSFSerializer - - -_element_processor_factory : HSSFElementProcessorFactory - +getMimeType() : String - - - - - - - HSSFElementProcessorFactory - - - - - - - - - - ElementProcessorFactory.CannotCreateElementProcessorException - - - - - - - sourcePortFig="Fig4.0" - destPortFig="Fig0.0" - sourceFigNode="Fig4" - destFigNode="Fig0" - - - - - - - - - - - sourcePortFig="Fig5.0" - destPortFig="Fig3.0" - sourceFigNode="Fig5" - destFigNode="Fig3" - - - - - - - - - - - sourcePortFig="Fig4.0" - destPortFig="Fig5.0" - sourceFigNode="Fig4" - destFigNode="Fig5" - - - - - - - - - diff --git a/src/models/HSSFSerializerUseCases.pgml b/src/models/HSSFSerializerUseCases.pgml deleted file mode 100644 index e7dfc3f10..000000000 --- a/src/models/HSSFSerializerUseCases.pgml +++ /dev/null @@ -1,1049 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - Cocoon - - - - - - - Sends Sax Events - - - - - - - Sends an Ignored Event - - - - - - - Sends and Interrogative Event - - - - - - - Sends Setup Event - - - - - - - Sends Start Document Event - - - - - - - Sends End Document Event - - - - - - - Sends Start Element Event - - - - - - - Sends End Element Event - - - - - - - Sends Raw Data Event - - - - sourcePortFig="Fig9.0" - destPortFig="Fig1.0" - sourceFigNode="Fig9" - destFigNode="Fig1" - - - - - - - <<extends>> - - - - - sourcePortFig="Fig7.0" - destPortFig="Fig1.0" - sourceFigNode="Fig7" - destFigNode="Fig1" - - - - - - - <<extends>> - - - - - sourcePortFig="Fig8.0" - destPortFig="Fig1.0" - sourceFigNode="Fig8" - destFigNode="Fig1" - - - - - - - <<extends>> - - - - - sourcePortFig="Fig6.0" - destPortFig="Fig1.0" - sourceFigNode="Fig6" - destFigNode="Fig1" - - - - - - - <<extends>> - - - - - sourcePortFig="Fig5.0" - destPortFig="Fig1.0" - sourceFigNode="Fig5" - destFigNode="Fig1" - - - - - - - <<extends>> - - - - - sourcePortFig="Fig4.0" - destPortFig="Fig1.0" - sourceFigNode="Fig4" - destFigNode="Fig1" - - - - - - - <<extends>> - - - - - sourcePortFig="Fig3.0" - destPortFig="Fig1.0" - sourceFigNode="Fig3" - destFigNode="Fig1" - - - - - - - <<extends>> - - - - - sourcePortFig="Fig2.0" - destPortFig="Fig1.0" - sourceFigNode="Fig2" - destFigNode="Fig1" - - - - - - - <<extends>> - - - - - sourcePortFig="Fig1.0" - destPortFig="Fig0.0" - sourceFigNode="Fig1" - destFigNode="Fig0" - - - - - - - - - - - sourcePortFig="Fig3.0" - destPortFig="Fig0.0" - sourceFigNode="Fig3" - destFigNode="Fig0" - - - - - - - - - - - sourcePortFig="Fig7.0" - destPortFig="Fig0.0" - sourceFigNode="Fig7" - destFigNode="Fig0" - - - - - - - - - - - sourcePortFig="Fig5.0" - destPortFig="Fig0.0" - sourceFigNode="Fig5" - destFigNode="Fig0" - - - - - - - - - - - sourcePortFig="Fig6.0" - destPortFig="Fig0.0" - sourceFigNode="Fig6" - destFigNode="Fig0" - - - - - - - - - - - sourcePortFig="Fig8.0" - destPortFig="Fig0.0" - sourceFigNode="Fig8" - destFigNode="Fig0" - - - - - - - - - - - sourcePortFig="Fig2.0" - destPortFig="Fig0.0" - sourceFigNode="Fig2" - destFigNode="Fig0" - - - - - - - - - - - sourcePortFig="Fig9.0" - destPortFig="Fig0.0" - sourceFigNode="Fig9" - destFigNode="Fig0" - - - - - - - - - - - sourcePortFig="Fig4.0" - destPortFig="Fig0.0" - sourceFigNode="Fig4" - destFigNode="Fig0" - - - - - - - - - diff --git a/src/models/HSSFUseCases.pgml b/src/models/HSSFUseCases.pgml deleted file mode 100644 index 0bca88408..000000000 --- a/src/models/HSSFUseCases.pgml +++ /dev/null @@ -1,725 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - ClientApps - - - - - - - create HSSF File - - - - - - - read existing HSSF File - - - - - - - write HSSF File - - - - - - - read Workbook Entry - - - - - - - write Workbook Entry - - - - - - - write sheet entry - - - - - - - read Sheet Entry - - - - sourcePortFig="Fig0.0" - destPortFig="Fig1.0" - sourceFigNode="Fig0" - destFigNode="Fig1" - - - - - - - - - - - sourcePortFig="Fig0.0" - destPortFig="Fig2.0" - sourceFigNode="Fig0" - destFigNode="Fig2" - - - - - - - - - - - sourcePortFig="Fig4.0" - destPortFig="Fig2.0" - sourceFigNode="Fig4" - destFigNode="Fig2" - - - - - - - <<extends>> - - - - - sourcePortFig="Fig0.0" - destPortFig="Fig3.0" - sourceFigNode="Fig0" - destFigNode="Fig3" - - - - - - - - - - - sourcePortFig="Fig5.0" - destPortFig="Fig3.0" - sourceFigNode="Fig5" - destFigNode="Fig3" - - - - - - - <<extends>> - - - - - sourcePortFig="Fig3.0" - destPortFig="Fig2.0" - sourceFigNode="Fig3" - destFigNode="Fig2" - - - - - - - <<extends>> - - - - - sourcePortFig="Fig6.0" - destPortFig="Fig3.0" - sourceFigNode="Fig6" - destFigNode="Fig3" - - - - - - - <<extends>> - - - - - sourcePortFig="Fig7.0" - destPortFig="Fig2.0" - sourceFigNode="Fig7" - destFigNode="Fig2" - - - - - - - <<extends>> - - - - - sourcePortFig="Fig3.0" - destPortFig="Fig1.0" - sourceFigNode="Fig3" - destFigNode="Fig1" - - - - - - - <<extends>> - - - diff --git a/src/models/POIFSAddDocument.pgml b/src/models/POIFSAddDocument.pgml deleted file mode 100644 index 211754623..000000000 --- a/src/models/POIFSAddDocument.pgml +++ /dev/null @@ -1,1042 +0,0 @@ - - - - - - - - - - Filesystem : - - - - - - - - - - - - - - - - - - - - - - Document : - - - - - - - - - - - - - - - - - - - - - DocumentProperty : - - - - - - - - - - - - - - - - - - DocumentBlock : - - - - - - - - - - - - - - - - - - PropertyTable : - - - - - - - - - - - - - - - - - - - RootProperty : - - - - - - - - - - - - - - - - : create - - - - - : create (1 .. n) - - - - - : create - - - - - : getDocumentProperty - - - - - : addProperty - - - - - : getRoot - - - - - : addChild - - - - sourcePortFig="Fig0.7" - destPortFig="Fig1.7" - sourceFigNode="Fig0" - destFigNode="Fig1" - - - - - - - - - - - sourcePortFig="Fig1.8" - destPortFig="Fig3.7" - sourceFigNode="Fig1" - destFigNode="Fig3" - - - - - - - - - - - sourcePortFig="Fig1.9" - destPortFig="Fig2.7" - sourceFigNode="Fig1" - destFigNode="Fig2" - - - - - - - - - - - sourcePortFig="Fig0.8" - destPortFig="Fig1.10" - sourceFigNode="Fig0" - destFigNode="Fig1" - - - - - - - - - - - sourcePortFig="Fig0.9" - destPortFig="Fig4.7" - sourceFigNode="Fig0" - destFigNode="Fig4" - - - - - - - - - - - sourcePortFig="Fig0.10" - destPortFig="Fig4.8" - sourceFigNode="Fig0" - destFigNode="Fig4" - - - - - - - - - - - sourcePortFig="Fig0.11" - destPortFig="Fig5.7" - sourceFigNode="Fig0" - destFigNode="Fig5" - - - - - - - - - diff --git a/src/models/POIFSClassDiagram.pgml b/src/models/POIFSClassDiagram.pgml deleted file mode 100644 index 0f20959a3..000000000 --- a/src/models/POIFSClassDiagram.pgml +++ /dev/null @@ -1,1125 +0,0 @@ - - - - - - - - - - Filesystem - - -_property_table : PropertyTable --_header_block : HeaderBlock --_documents : List - +createDocument(in stream:InputStream, in name:String) -+writeFilesystem(in stream:OutputStream) -+Filesystem() - - - - - - - Document - - -_property : DocumentProperty --_blocks[] : DocumentBlock - #getDocumentProperty() : DocumentProperty -#Document(in name:String, in stream:InputStream) - - - - - - - DocumentBlock - - -_data[ 512 ] : byte --_bytes_read : int - +DocumentBlock(in stream:InputStream) -+size() : int -+partiallyRead() : boolean - - - - - - - HeaderBlock - - -_bat_count : IntegerField --_property_start : IntegerField --_sbat_start : IntegerField = -2 --_xbat_start : IntegerField = -2 --_xbat_count : IntegerField = 0 --_data[ 512 ] : byte - +setBATBlocks(in blockCount:int, in startBlock:int) : BATBlock -+setPropertyStart(in startBlock:int) -+setXBATStart(in startBlock:int) -+Header() -+calculateXBATStorageRequirements(in blockCount:int) : int - - - - - - - PropertyTable - - -_properties : List --_blocks[ ] : BlockWritable --_start_block : int - +getRoot() : Directory -+addProperty(in property:Property) -+preWrite() -+PropertyTable() -+getStartBlock() : int - - - - - - - DocumentProperty - - - +DocumentProperty(in name:String, in size:int) - - - - - - - <<Interface>> - BATManaged - +countBlocks() : int -+setStartBlock(in index:int) - - - - - - - <<Interface>> - BlockWritable - +writeBlocks(in stream:OutputStream) - - - - - - - BlockAllocationTable - - -_entries : IntList --_blocks[] : BATBlock - #createBlocks() -#allocateSpace(in blockCount:int) : int -#BlockAllocationTable() -#countBlocks() : int - - - - - - - BATBlock - - -_fields[ 128 ] : IntegerField --_data[ 512 ] : byte - +createBATBlocks(in entries[]:int) : BATBlock -+calculateStorageRequirements(in entryCount:int) : int - - - - sourcePortFig="Fig0.0" - destPortFig="Fig1.0" - sourceFigNode="Fig0" - destFigNode="Fig1" - - - - - - - 0..* - - - - - sourcePortFig="Fig1.0" - destPortFig="Fig2.0" - sourceFigNode="Fig1" - destFigNode="Fig2" - - - - - - - 1..* - - - - - sourcePortFig="Fig0.0" - destPortFig="Fig3.0" - sourceFigNode="Fig0" - destFigNode="Fig3" - - - - - - - - - - - sourcePortFig="Fig0.0" - destPortFig="Fig4.0" - sourceFigNode="Fig0" - destFigNode="Fig4" - - - - - - - - - - - sourcePortFig="Fig1.0" - destPortFig="Fig5.0" - sourceFigNode="Fig1" - destFigNode="Fig5" - - - - - - - - - - - sourcePortFig="Fig4.0" - destPortFig="Fig6.0" - sourceFigNode="Fig4" - destFigNode="Fig6" - - - - - - - - - - - sourcePortFig="Fig1.0" - destPortFig="Fig6.0" - sourceFigNode="Fig1" - destFigNode="Fig6" - - - - - - - - - - - sourcePortFig="Fig1.0" - destPortFig="Fig7.0" - sourceFigNode="Fig1" - destFigNode="Fig7" - - - - - - - - - - - - sourcePortFig="Fig4.0" - destPortFig="Fig7.0" - sourceFigNode="Fig4" - destFigNode="Fig7" - - - - - - - - - - - sourcePortFig="Fig8.0" - destPortFig="Fig7.0" - sourceFigNode="Fig8" - destFigNode="Fig7" - - - - - - - - - - - sourcePortFig="Fig8.0" - destPortFig="Fig9.0" - sourceFigNode="Fig8" - destFigNode="Fig9" - - - - - - - 1..* - - - diff --git a/src/models/POIFSInitialization.pgml b/src/models/POIFSInitialization.pgml deleted file mode 100644 index 3c487567b..000000000 --- a/src/models/POIFSInitialization.pgml +++ /dev/null @@ -1,590 +0,0 @@ - - - - - - - enclosingFig="Fig0" - - - - Filesystem : - - - - - - - - - - - - - - - - enclosingFig="Fig1" - - - - HeaderBlock : - - - - - - - - - - - - - - - enclosingFig="Fig2" - - - - PropertyTable : - - - - - - - - - - - - - - - - enclosingFig="Fig3" - - - - RootProperty : - - - - - - - - - - - - - - - - : create - - - - - : create - - - - - : create - - - - sourcePortFig="Fig0.7" - destPortFig="Fig2.7" - sourceFigNode="Fig0" - destFigNode="Fig2" - - - - - - - - - - - sourcePortFig="Fig2.8" - destPortFig="Fig3.7" - sourceFigNode="Fig2" - destFigNode="Fig3" - - - - - - - - - - - sourcePortFig="Fig0.8" - destPortFig="Fig1.7" - sourceFigNode="Fig0" - destFigNode="Fig1" - - - - - - - - - diff --git a/src/models/POIFSLifeCycle.pgml b/src/models/POIFSLifeCycle.pgml deleted file mode 100644 index 88c431588..000000000 --- a/src/models/POIFSLifeCycle.pgml +++ /dev/null @@ -1,410 +0,0 @@ - - - - - - - - - - (Client Application) : - - - - - - - - - - - - - - - - - - - - Filesystem : - - - - - - - - - - - - - - - - - - : create - - - - - : createDocument - - - - - : writeFileSystem - - - - sourcePortFig="Fig0.7" - destPortFig="Fig1.7" - sourceFigNode="Fig0" - destFigNode="Fig1" - - - - - - - - - - - sourcePortFig="Fig0.8" - destPortFig="Fig1.8" - sourceFigNode="Fig0" - destFigNode="Fig1" - - - - - - - - - - - sourcePortFig="Fig0.9" - destPortFig="Fig1.9" - sourceFigNode="Fig0" - destFigNode="Fig1" - - - - - - - - - diff --git a/src/models/POIFSPropertyTablePreWrite.pgml b/src/models/POIFSPropertyTablePreWrite.pgml deleted file mode 100644 index dba9bb2e8..000000000 --- a/src/models/POIFSPropertyTablePreWrite.pgml +++ /dev/null @@ -1,814 +0,0 @@ - - - - - - - - - - PropertyTable : - - - - - - - - - - - - - - - - - - - - Property : - - - - - - - - - - - - - - - - - - - PropertyBlock : - - - - - - - - - - - - - - - - - - - - PropertyBlock : - - - - - - - - - - - - - - - - - - Property : - - - - - - - - - - - - - - - - : setIndex (for each Property) - - - - - : createPropertyBlockArray - - - - - : create (enough so we have a multiple of 4 properties) - - - - - : create (1 for every 4 properties) - - - - - : preWrite (for each Property) - - - - sourcePortFig="Fig0.7" - destPortFig="Fig1.7" - sourceFigNode="Fig0" - destFigNode="Fig1" - - - - - - - - - - - sourcePortFig="Fig0.8" - destPortFig="Fig2.7" - sourceFigNode="Fig0" - destFigNode="Fig2" - - - - - - - - - - - sourcePortFig="Fig2.8" - destPortFig="Fig4.7" - sourceFigNode="Fig2" - destFigNode="Fig4" - - - - - - - - - - - sourcePortFig="Fig2.9" - destPortFig="Fig3.7" - sourceFigNode="Fig2" - destFigNode="Fig3" - - - - - - - - - - - sourcePortFig="Fig0.9" - destPortFig="Fig1.8" - sourceFigNode="Fig0" - destFigNode="Fig1" - - - - - - - - - diff --git a/src/models/POIFSRootPropertyPreWrite.pgml b/src/models/POIFSRootPropertyPreWrite.pgml deleted file mode 100644 index 829e8d36d..000000000 --- a/src/models/POIFSRootPropertyPreWrite.pgml +++ /dev/null @@ -1,416 +0,0 @@ - - - - - - - enclosingFig="Fig0" - - - - RootProperty : - - - - - - - - - - - - - - - - - - enclosingFig="Fig1" - - - - Property : - - - - - - - - - - - - - - - - - : setNextFile - - - - - : set _child_property - - - - - : setPreviousFile - - - - sourcePortFig="Fig0.7" - destPortFig="Fig1.7" - sourceFigNode="Fig0" - destFigNode="Fig1" - - - - - - - - - - - sourcePortFig="Fig0.8" - destPortFig="Fig0.9" - sourceFigNode="Fig0" - destFigNode="Fig0" - - - - - - - - - - - - - sourcePortFig="Fig0.10" - destPortFig="Fig1.8" - sourceFigNode="Fig0" - destFigNode="Fig1" - - - - - - - - - diff --git a/src/models/POIFSWriteFilesystem.pgml b/src/models/POIFSWriteFilesystem.pgml deleted file mode 100644 index 1a0196527..000000000 --- a/src/models/POIFSWriteFilesystem.pgml +++ /dev/null @@ -1,1258 +0,0 @@ - - - - - - - enclosingFig="Fig0" - - - - Filesystem : - - - - - - - - - - - - - - - - - - - - - - - - enclosingFig="Fig1" - - - - PropertyTable : - - - - - - - - - - - - - - - enclosingFig="Fig2" - - - - BATManaged : - - - - - - - - - - - - - - - - enclosingFig="Fig3" - - - - BlockAllocationTable : - - - - - - - - - - - - - - - - - enclosingFig="Fig4" - - - - HeaderBlock : - - - - - - - - - - - - - - - - - enclosingFig="Fig5" - - - - BlockWritable : - - - - - - - - - - - - - - - - : preWrite - - - - - : countBlocks - - - - - : allocateSpace - - - - - : setStartBlock - - - - - : createBlocks - - - - - : setBatBlocks - - - - - : setPropertyStart - - - - - : writeBlocks - - - - - : create - - - - - : setXBATStart - - - - sourcePortFig="Fig0.7" - destPortFig="Fig1.7" - sourceFigNode="Fig0" - destFigNode="Fig1" - - - - - - - - - - - sourcePortFig="Fig0.8" - destPortFig="Fig2.7" - sourceFigNode="Fig0" - destFigNode="Fig2" - - - - - - - - - - - sourcePortFig="Fig0.9" - destPortFig="Fig3.7" - sourceFigNode="Fig0" - destFigNode="Fig3" - - - - - - - - - - - sourcePortFig="Fig0.10" - destPortFig="Fig2.8" - sourceFigNode="Fig0" - destFigNode="Fig2" - - - - - - - - - - - sourcePortFig="Fig0.11" - destPortFig="Fig3.8" - sourceFigNode="Fig0" - destFigNode="Fig3" - - - - - - - - - - - sourcePortFig="Fig0.12" - destPortFig="Fig4.7" - sourceFigNode="Fig0" - destFigNode="Fig4" - - - - - - - - - - - sourcePortFig="Fig0.13" - destPortFig="Fig4.8" - sourceFigNode="Fig0" - destFigNode="Fig4" - - - - - - - - - - - sourcePortFig="Fig0.14" - destPortFig="Fig5.7" - sourceFigNode="Fig0" - destFigNode="Fig5" - - - - - - - - - - - sourcePortFig="Fig0.15" - destPortFig="Fig3.9" - sourceFigNode="Fig0" - destFigNode="Fig3" - - - - - - - - - - - sourcePortFig="Fig0.16" - destPortFig="Fig4.9" - sourceFigNode="Fig0" - destFigNode="Fig4" - - - - - - - - - diff --git a/src/models/POIUseCases.pgml b/src/models/POIUseCases.pgml deleted file mode 100644 index ee5a00286..000000000 --- a/src/models/POIUseCases.pgml +++ /dev/null @@ -1,1006 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - ClientApps - - - - - - - read existing filesystem - - - - - - - write file system - - - - - - - create new filesystem - - - - - - - read file system directory - - - - - - - read existing file from file system - - - - - - - write new file to file system - - - - - - - delete file from file system - - - - - - - replace file in file system - - - - - - - read file - - - - - - - rename existing file in file system - - - - sourcePortFig="Fig0.0" - destPortFig="Fig1.0" - sourceFigNode="Fig0" - destFigNode="Fig1" - - - - - - - - - - - sourcePortFig="Fig0.0" - destPortFig="Fig2.0" - sourceFigNode="Fig0" - destFigNode="Fig2" - - - - - - - - - - - sourcePortFig="Fig0.0" - destPortFig="Fig3.0" - sourceFigNode="Fig0" - destFigNode="Fig3" - - - - - - - - - - - sourcePortFig="Fig2.0" - destPortFig="Fig1.0" - sourceFigNode="Fig2" - destFigNode="Fig1" - - - - - - - <<includes>> - - - - - sourcePortFig="Fig4.0" - destPortFig="Fig1.0" - sourceFigNode="Fig4" - destFigNode="Fig1" - - - - - - - <<extends>> - - - - - sourcePortFig="Fig5.0" - destPortFig="Fig1.0" - sourceFigNode="Fig5" - destFigNode="Fig1" - - - - - - - <<extends>> - - - - - sourcePortFig="Fig6.0" - destPortFig="Fig2.0" - sourceFigNode="Fig6" - destFigNode="Fig2" - - - - - - - <<extends>> - - - - - sourcePortFig="Fig7.0" - destPortFig="Fig2.0" - sourceFigNode="Fig7" - destFigNode="Fig2" - - - - - - - <<extends>> - - - - - sourcePortFig="Fig8.0" - destPortFig="Fig2.0" - sourceFigNode="Fig8" - destFigNode="Fig2" - - - - - - - <<extends>> - - - - - sourcePortFig="Fig2.0" - destPortFig="Fig3.0" - sourceFigNode="Fig2" - destFigNode="Fig3" - - - - - - - <<extends>> - - - - - sourcePortFig="Fig9.0" - destPortFig="Fig4.0" - sourceFigNode="Fig9" - destFigNode="Fig4" - - - - - - - uses - - - - - sourcePortFig="Fig9.0" - destPortFig="Fig5.0" - sourceFigNode="Fig9" - destFigNode="Fig5" - - - - - - - uses - - - - - sourcePortFig="Fig10.0" - destPortFig="Fig2.0" - sourceFigNode="Fig10" - destFigNode="Fig2" - - - - - - - <<extends>> - - - diff --git a/src/models/PropertyTableClassDiagram.pgml b/src/models/PropertyTableClassDiagram.pgml deleted file mode 100644 index de6ae19bb..000000000 --- a/src/models/PropertyTableClassDiagram.pgml +++ /dev/null @@ -1,818 +0,0 @@ - - - - - - - - - - Property - - -_name : String --_name_size : ShortField --_property_type : ByteField --_storage_type : ByteField --_previous_property : IntegerField --_next_property : IntegerField --_child_property : IntegerField --_seconds_1 : IntegerField --_days_1 : IntegerField --_seconds_2 : IntegerField --_days_2 : IntegerField --_start_block : IntegerField --_size : IntegerField --_raw_data[ 128 ] : byte --_index : int -+PROPERTY_SIZE : int = 128 -#_NO_INDEX : int = -1 -#_DIRECTORY_TYPE : byte = 1 -#_DOCUMENT_TYPE : byte = 2 -#_ROOT_TYPE : byte = 5 -#_BIG_BLOCK_STORAGE : byte = 1 -#_SMALL_BLOCK_STORAGE : byte = 0 --_next_file : File --_previous_file : File - #setIndex(in index:int) -#preWrite() -#getIndex() : int -+setStartBlock(in startBlock:int) -#Property() -#setName(in name:String) -#setPropertyType(in propertyType:byte) -#setStorageType(in storageType:byte) -#setChildProperty(in child:int) -#getChildProperty() : int -#setSize(in size:int) -#shouldUseSmallBlocks() : boolean - - - - - - - RootProperty - - -_children : List - - - - - - - - DocumentProperty - - - +DocumentProperty(in name:String, in size:int) - - - - - - - PropertyBlock - - -_properties[ 4 ] : Property - +createPropertyBlockArray(in properties:List) : BlockWritable - - - - - - - PropertyTable - - -_properties : List --_blocks[ ] : BlockWritable --_start_block : int - +getRoot() : Directory -+addProperty(in property:Property) -+preWrite() -+PropertyTable() -+getStartBlock() : int - - - - - - - <<Interface>> - File - +getNextFile() : File -+setNextFile(in file:File) -+getPreviousFile() : File -+setPreviousFile(in file:File) - - - - - - - <<Interface>> - Directory - +getChildren() : Iterator -+addChild(in property:Property) - - - - sourcePortFig="Fig1.0" - destPortFig="Fig0.0" - sourceFigNode="Fig1" - destFigNode="Fig0" - - - - - - - - - - - sourcePortFig="Fig2.0" - destPortFig="Fig0.0" - sourceFigNode="Fig2" - destFigNode="Fig0" - - - - - - - - - - - sourcePortFig="Fig3.0" - destPortFig="Fig0.0" - sourceFigNode="Fig3" - destFigNode="Fig0" - - - - - - - - - - - sourcePortFig="Fig4.0" - destPortFig="Fig3.0" - sourceFigNode="Fig4" - destFigNode="Fig3" - - - - - - - - 1..* - - - - - sourcePortFig="Fig4.0" - destPortFig="Fig0.0" - sourceFigNode="Fig4" - destFigNode="Fig0" - - - - - - - 1..* - - - - - sourcePortFig="Fig6.0" - destPortFig="Fig5.0" - sourceFigNode="Fig6" - destFigNode="Fig5" - - - - - - - - - - - sourcePortFig="Fig1.0" - destPortFig="Fig6.0" - sourceFigNode="Fig1" - destFigNode="Fig6" - - - - - - - - - - - sourcePortFig="Fig0.0" - destPortFig="Fig5.0" - sourceFigNode="Fig0" - destFigNode="Fig5" - - - - - - - - - diff --git a/src/models/analysismain.pgml b/src/models/analysismain.pgml deleted file mode 100644 index 5e2ca17bd..000000000 --- a/src/models/analysismain.pgml +++ /dev/null @@ -1,210 +0,0 @@ - - - - - - - - - POI - - - - - - - HSSF - - - - - - - HSSFSerializer - - - - - sourcePortFig="Fig2.0" - destPortFig="Fig1.0" - sourceFigNode="Fig2" - destFigNode="Fig1" - - - - - - - - - - - sourcePortFig="Fig1.0" - destPortFig="Fig0.0" - sourceFigNode="Fig1" - destFigNode="Fig0" - - - - - - - - - diff --git a/src/models/poi.argo b/src/models/poi.argo deleted file mode 100644 index 80c189b5b..000000000 --- a/src/models/poi.argo +++ /dev/null @@ -1,127 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - {} - - diff --git a/src/models/poi.xmi b/src/models/poi.xmi deleted file mode 100644 index 5feadacec..000000000 --- a/src/models/poi.xmi +++ /dev/null @@ -1,19132 +0,0 @@ - - - - - - Novosoft UML Library - 0.4.19 - - - - - - project - - - - - - - analysisModel - - - - - - - - - - POI - - - - - - - - - - - - - read existing filesystem - - - - - - - - - - - - - - - create the filesystem - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - read all bytes - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - create a header block from first 512 bytes - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - create blocks from all blocks that are not header,bat or property blocks - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - create bat blocks from bytes that are in bat - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - create property table blocks from bytes starting at header.rootstartblock - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - assign BAT Blocks to the BAT - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - derive property instances from the Property Table Blocks and add them to the property table - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - InputStream - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - write file system - - - - - - - - - - - - - - - - - - - - createFileSystem - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - createHeaderBlock - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - createBlock [until all files have blocks] - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - create a record [until all files have records] - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - create bat block [if need more] - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - create a record [until all files have records] - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - get the bat array info - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - get the extended bat array info - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - set the bat info - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - set the extended bat info - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - create a block [if needed] - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - create a property - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - add the propert to the block - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - write all blocks to stream - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - OutputStream - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - read file system directory - - - - - - - - - - - - - requests directory listing - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - enumerates properties - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - read existing file from file system - - - - - - - - - - - - - gets property from - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - gets property from - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - gets BAT Chain from - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - gets next bat chain element [until all are read] - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - gets bytes [from each block in bat chain] - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - constructs a byte array input stream with file bytes - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - requests file - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - returns input stream - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - PropertyBlock - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ByteArrayInputStream - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - delete file from file system - - - - - - - - - - - - - replace file in file system - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 1 - 1 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - read file - - - - - - - - - - - - - - - - - - - uses - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - uses - - - - - - - - - - - - - - - - - - - - - - - - - - rename existing file in file system - - - - - - - - - - - - - - - - - - - - - - - - - POIFileSystem - - - - - - - - - - - - readFileSystem(InputStream in) - - - - - - - - - - - - - - - - return - - - - - - - - - - - - - - - - - - - - - - - - - Block - - - - - - - - - - - - - - - - - createBlock(byte[] bytes, int offset, int length) - - - - - - - - - - - - - - - - return - - - - - - - - - - - - - - - - - - - - - - - - - HeaderBlock - - - - - - - - - - - - - - - BATBlock - - - - - - - - - - - - - - - PropertyTableBlock - - - - - - - - - - - - - - - Property - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - RootProperty - - - - - - - - - - - - - - - BAT - - - - - - - - - - - - createRecord - - - - - - - - - - - - - - - - return - - - - - - - - - - - bytes - - - - - - - - - - - - - - - - - - - - - - - getBlocks - - - - - - - - - - - - - - - - return - - - - - - - - - - - - - - - - - - - - - - - blocks - - - - - - - - 0 - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void - - - - - - - - - - - PropertyTable - - - - - - - - - - - - createRecord - - - - - - - - - - - - - - - - return - - - - - - - - - - - name - - - - - - - - - - - startBlock - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - DirectoryProperty - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - FileProperty - - - - - - - - - - - - - - - - - - - - - - - - - - - child - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - next - - - - - - - - - - - 0 - 1 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - previous - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - HSSF - - - - - - - - - - - - - - - - ClientApps - - - - - - - - - - create HSSF File - - - - - - - - - - - - - create new filesystem - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - read existing HSSF File - - - - - - - - - - - - - - - write HSSF File - - - - - - - - - - - - - - - - - - read Workbook Entry - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - write Workbook Entry - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - write sheet entry - - - - - - - - - - - - - - - - - - - - - - - - - write new file to file system - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - read Sheet Entry - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - HSSFSerializer - - - - - - - - - - - - - Cocoon - - - - - - - - - - Sends Sax Events - - - - - - - - - - - - - - - - - - - - Sends an Ignored Event - - - - - - - - - - - - - Sends and Interrogative Event - - - - - - - - - - - - - Sends Setup Event - - - - - - - - - - - - - Sends Start Document Event - - - - - - - - - - - - - Sends End Document Event - - - - - - - - - - - - - Sends Start Element Event - - - - - - - - - - - - - Sends End Element Event - - - - - - - - - - - - - Sends Raw Data Event - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - designModel - - - - - - - - - - Property - - - - - - - - - - - - - - - - - - - _name - - - - - - - - - - - - _name_size - - - - - - - - - - - - _property_type - - - - - - - - - - - - _storage_type - - - - - - - - - - - - _previous_property - - - - - - - - - - - - _next_property - - - - - - - - - - - - _child_property - - - - - - - - - - - - _seconds_1 - - - - - - - - - - - - _days_1 - - - - - - - - - - - - _seconds_2 - - - - - - - - - - - - _days_2 - - - - - - - - - - - - _start_block - - - - - - - - - - - - _size - - - - - - - - - - - - _raw_data[ 128 ] - - - - - - - - - - - - _index - - - - - - - - - - - - setIndex - - - - - - - - - - - - - - - - index - - - - - - - - - - - - - - - - - - - - - - - preWrite - - - - - - - - - - - - - - - - - - - - - - - - - - getIndex - - - - - - - - - - - - - - - - return - - - - - - - - - - - - - - - - - - - - - - - setStartBlock - - - - - - - - - - - - - - - - startBlock - - - - - - - - - - - - - - - - - - - - - - - PROPERTY_SIZE - - - - - - - java - 128 - - - - - - - - - - - _NO_INDEX - - - - - - - java - -1 - - - - - - - - - - - _DIRECTORY_TYPE - - - - - - - java - 1 - - - - - - - - - - - _DOCUMENT_TYPE - - - - - - - java - 2 - - - - - - - - - - - _ROOT_TYPE - - - - - - - java - 5 - - - - - - - - - - - _BIG_BLOCK_STORAGE - - - - - - - java - 1 - - - - - - - - - - - _SMALL_BLOCK_STORAGE - - - - - - - java - 0 - - - - - - - - - - - Property - - - - - - - - - - - - - - - - - - - - - - - - - - setName - - - - - - - - - - - - - - - - name - - - - - - - - - - - - - - - - - - - - - - - setPropertyType - - - - - - - - - - - - - - - - propertyType - - - - - - - - - - - - - - - - - - - - - - - setStorageType - - - - - - - - - - - - - - - - storageType - - - - - - - - - - - - - - - - - - - - - - - setChildProperty - - - - - - - - - - - - - - - - child - - - - - - - - - - - - - - - - - - - - - - - getChildProperty - - - - - - - - - - - - - - - - return - - - - - - - - - - - - - - - - - - - - - - - setSize - - - - - - - - - - - - - - - - size - - - - - - - - - - - - - - - - - - - - - - - shouldUseSmallBlocks - - - - - - - - - - - - - - - - return - - - - - - - - - - - - - - - - - - - - - - - _next_file - - - - - - - - - - - - _previous_file - - - - - - - - - - - - - - RootProperty - - - - - - - - - - - - - - - - - - _children - - - - - - - - - - - - - - DocumentProperty - - - - - - - - - - - - - - - DocumentProperty - - - - - - - - - - - - - - - - name - - - - - - - - - - - size - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - PropertyBlock - - - - - - - - - - - - - - - - - - _properties[ 4 ] - - - - - - - - - - - - - createPropertyBlockArray - - - - - - - - - - - - - - - - return - - - - - - - - - - - properties - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - PropertyTable - - - - - - - - - - - - - - - - _properties - - - - - - - - - - - - _blocks[ ] - - - - - - - - - - - - getRoot - - - - - - - - - - - - - - - - return - - - - - - - - - - - - - - - - - - - - - - - addProperty - - - - - - - - - - - - - - - - property - - - - - - - - - - - - - - - - - - - - - - - preWrite - - - - - - - - - - - - - - - - - - - - - - - - - - PropertyTable - - - - - - - - - - - - - - - - - - - - - - - - - - getStartBlock - - - - - - - - - - - - - - - - return - - - - - - - - - - - - - - - - - - - - - - - _start_block - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 1 - -1 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - File - - - - - - - - - - - - - - - - - getNextFile - - - - - - - - - - - - - - - - return - - - - - - - - - - - - - - - - - - - - - - - setNextFile - - - - - - - - - - - - - - - - file - - - - - - - - - - - - - - - - - - - - - - - getPreviousFile - - - - - - - - - - - - - - - - return - - - - - - - - - - - - - - - - - - - - - - - setPreviousFile - - - - - - - - - - - - - - - - file - - - - - - - - - - - - - - - - - - - - - - - - - realize - - - - - - - - - - Directory - - - - - - - - - - - - - - - - - getChildren - - - - - - - - - - - - - - - - return - - - - - - - - - - - - - - - - - - - - - - - addChild - - - - - - - - - - - - - - - - property - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - realize - - - - - - - - - - - - - BigBlock - - - - - - - - - - - - - - - - - - - - - writeData - - - - - - - - - - - - - - - - stream - - - - - - - - - - - - - - - - - - - - - - - BIG_BLOCK_SIZE - - - - - - - java - 512 - - - - - - - - - - - doWriteData - - - - - - - - - - - - - - - - stream - - - - - - - - - - - data[] - - - - - - - - - - - - - - - - - - - - - - - - - HeaderBlock - - - - - - - - - - - - - - - _bat_count - - - - - - - - - - - - _property_start - - - - - - - - - - - - _sbat_start - - - - - - java - -2 - - - - - - - - - - - _xbat_start - - - - - - java - -2 - - - - - - - - - - - _xbat_count - - - - - - java - 0 - - - - - - - - - - - _data[ 512 ] - - - - - - - - - - - - setBATBlocks - - - - - - - - - - - - - - - - blockCount - - - - - - - - - - - startBlock - - - - - - - - - - - return - - - - - - - - - - - - - - - - - - - - - - - setPropertyStart - - - - - - - - - - - - - - - - startBlock - - - - - - - - - - - - - - - - - - - - - - - setXBATStart - - - - - - - - - - - - - - - - startBlock - - - - - - - - - - - - - - - - - - - - - - - Header - - - - - - - - - - - - - - - - - - - - - - - - - - calculateXBATStorageRequirements - - - - - - - - - - - - - - - - return - - - - - - - - - - - blockCount - - - - - - - - - - - - - - - - - - - - - - - - - BATBlock - - - - - - - - - - - - - - - _fields[ 128 ] - - - - - - - - - - - - _data[ 512 ] - - - - - - - - - - - - createBATBlocks - - - - - - - - - - - - - - - - return - - - - - - - - - - - entries[] - - - - - - - - - - - - - - - - - - - - - - - calculateStorageRequirements - - - - - - - - - - - - - - - - return - - - - - - - - - - - entryCount - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Filesystem - - - - - - - - - - - - createDocument - - - - - - - - - - - - - - - - stream - - - - - - - - - - - name - - - - - - - - - - - - - - - - - - - - - - - writeFilesystem - - - - - - - - - - - - - - - - stream - - - - - - - - - - - - - - - - - - - - - - - Filesystem - - - - - - - - - - - - - - - - - - - - - - - - - - _property_table - - - - - - - - - - - - _header_block - - - - - - - - - - - - _documents - - - - - - - - - - - - volatile - true - - - - - - - - - - Document - - - - - - - - - - - - - - - - getDocumentProperty - - - - - - - - - - - - - - - - return - - - - - - - - - - - - - - - - - - - - - - - _property - - - - - - - - - - - - _blocks[] - - - - - - - - - - - - Document - - - - - - - - - - - - - - - - name - - - - - - - - - - - stream - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - DocumentBlock - - - - - - - - - - - - - - - - _data[ 512 ] - - - - - - - - - - - - DocumentBlock - - - - - - - - - - - - - - - - stream - - - - - - - - - - - - - - - - - - - - - - - size - - - - - - - - - - - - - - - - return - - - - - - - - - - - - - - - - - - - - - - - partiallyRead - - - - - - - - - - - - - - - - return - - - - - - - - - - - - - - - - - - - - - - - _bytes_read - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - BATManaged - - - - - - - - - - - - - - - countBlocks - - - - - - - - - - - - - - - - return - - - - - - - - - - - - - - - - - - - - - - - setStartBlock - - - - - - - - - - - - - - - - index - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - realize - - - - - - - - - - - - - - - - - - - - - - - - - realize - - - - - - - - - - - - - realize - - - - - - - - - - - - - - - - - - - - - - realize - - - - - - - - - - - - - BlockWritable - - - - - - - - - - - - - - - - - writeBlocks - - - - - - - - - - - - - - - - stream - - - - - - - - - - - - - - - - - - - - - - - - - realize - - - - - - - - - - realize - - - - - - - - - - - - - - - - - - - - - - realize - - - - - - - - - - - - - - - - - - - - - - - - - realize - - - - - - - - - - - - - - - - - - - - - - - - - realize - - - - - - - - - - - - - BlockAllocationTable - - - - - - - - - - - - - - - createBlocks - - - - - - - - - - - - - - - - - - - - - - - - - - allocateSpace - - - - - - - - - - - - - - - - return - - - - - - - - - - - blockCount - - - - - - - - - - - - - - - - - - - - - - - _entries - - - - - - - - - - - - _blocks[] - - - - - - - - - - - - BlockAllocationTable - - - - - - - - - - - - - - - - - - - - - - - - - - countBlocks - - - - - - - - - - - - - - - - return - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - realize - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - POIFSSerializer - - - - - - - - - - - - - - - startPrefixMapping - - - - - - - - - - - - - - - - ignoredPrefix - - - - - - - - - - - ignoredUri - - - - - - - - - - - - - - - - - - - - - - - endPrefixMapping - - - - - - - - - - - - - - - - ignoredPrefix - - - - - - - - - - - - - - - - - - - - - - - processingInstruction - - - - - - - - - - - - - - - - ignoredTarget - - - - - - - - - - - ignoredData - - - - - - - - - - - - - - - - - - - - - - - skippedEntity - - - - - - - - - - - - - - - - ignoredName - - - - - - - - - - - - - - - - - - - - - - - startDTD - - - - - - - - - - - - - - - - ignoredName - - - - - - - - - - - ignoredPublicId - - - - - - - - - - - ignoredSystemId - - - - - - - - - - - - - - - - - - - - - - - endDTD - - - - - - - - - - - - - - - - - - - - - - - - - - startEntity - - - - - - - - - - - - - - - - ignoredName - - - - - - - - - - - - - - - - - - - - - - - endEntity - - - - - - - - - - - - - - - - ignoredName - - - - - - - - - - - - - - - - - - - - - - - startCDATA - - - - - - - - - - - - - - - - - - - - - - - - - - endCDATA - - - - - - - - - - - - - - - - - - - - - - - - - - comment - - - - - - - - - - - - - - - - ignoredCh[] - - - - - - - - - - - ignoredStart - - - - - - - - - - - ignoredLength - - - - - - - - - - - - - - - - - - - - - - - shouldSetContentLength - - - - - - - - - - - - - - - - return - - - - - - - - - - - - - - - - - - - - - - - setOutputStream - - - - - - - - - - - - - - - - out - - - - - - - - - - - - - - - - - - - - - - - _output_stream - - - - - - java - null - - - - - - - - - - - _locator - - - - - - java - null - - - - - - - - - - - setDocumentLocator - - - - - - - - - - - - - - - - locator - - - - - - - - - - - - - - - - - - - - - - - startDocument - - - - - - - - - - - - - - - - - - - - - - - - - - endDocument - - - - - - - - - - - - - - - - - - - - - - - - - - startElement - - - - - - - - - - - - - - - - namespaceURI - - - - - - - - - - - localName - - - - - - - - - - - qName - - - - - - - - - - - atts - - - - - - - - - - - - - - - - - - - - - - - endElement - - - - - - - - - - - - - - - - namespaceURI - - - - - - - - - - - localName - - - - - - - - - - - qName - - - - - - - - - - - - - - - - - - - - - - - characters - - - - - - - - - - - - - - - - ch[] - - - - - - - - - - - start - - - - - - - - - - - length - - - - - - - - - - - - - - - - - - - - - - - ignorableWhitespace - - - - - - - - - - - - - - - - ch[] - - - - - - - - - - - start - - - - - - - - - - - length - - - - - - - - - - - - - - - - - - - - - - - _open_elements - - - - - - java - new Stack() - - - - - - - - - - - _filesystem - - - - - - java - new Filesystem() - - - - - - - - - - - getElementProcessorFactory - - - - - - - - - - - - - - - - return - - - - - - - - - - - - - - - - - - - - - - - doLocalPreEndDocument - - - - - - - - - - - - - - - - - - - - - - - - - - doLocalPostEndDocument - - - - - - - - - - - - - - - - - - - - - - - - - - getFilesystem - - - - - - - - - - - - - - - - return - - - - - - - - - - - - - - - - - - - - - - - SAXExceptionFactory - - - - - - - - - - - - - - - - return - - - - - - - - - - - message - - - - - - - - - - - e - - - - - - - - - - - - - - - - - - - - - - - SAXExceptionFactory - - - - - - - - - - - - - - - - return - - - - - - - - - - - message - - - - - - - - - - - - - - - - - - - - - - - - - org.xml.sax - - - - - - - - - - Locator - - - - - - - - - - Attributes - - - - - - - - - - SAXException - - - - - - - - - - - - - Attribute - - - - - - - - - - - - _name - - - - - - - - - - - - - _value - - - - - - - - - - - - - getName - - - - - - - - - - - - - - - - return - - - - - - - - - - - - - - - - - - - - - - - getValue - - - - - - - - - - - - - - - - return - - - - - - - - - - - - - - - - - - - - - - - getValueAsInt - - - - - - - - - - - - - - - - return - - - - - - - - - - - - - - - - - - - - - - - getValueAsShort - - - - - - - - - - - - - - - - return - - - - - - - - - - - - - - - - - - - - - - - getValueAsLong - - - - - - - - - - - - - - - - return - - - - - - - - - - - - - - - - - - - - - - - getValueAsBoolean - - - - - - - - - - - - - - - - return - - - - - - - - - - - - - - - - - - - - - - - Attribute - - - - - - - - - - - - - - - - name - - - - - - - - - - - value - - - - - - - - - - - - - - - - - - - - - - - - - ElementProcessor - - - - - - - - - - - initialize - - - - - - - - - - - - - - - - attributes[] - - - - - - - - - - - parent - - - - - - - - - - - filesystem - - - - - - - - - - - - - - - - - - - - - - - acceptCharacters - - - - - - - - - - - - - - - - data[] - - - - - - - - - - - - - - - - - - - - - - - acceptWhitespaceCharacters - - - - - - - - - - - - - - - - data[] - - - - - - - - - - - - - - - - - - - - - - - endProcessing - - - - - - - - - - - - - - - - - - - - - - - - - - - - ElementProcessorFactory - - - - - - - - - - - - - - - _element_processor_map - - - - - - - - - - - - - createElementProcessor - - - - - - - - - - - - - - - - return - - - - - - - - - - - name - - - - - - - - - - - - - - - - - - - - - - - addElementProcessorProgenitor - - - - - - - - - - - - - - - - name - - - - - - - - - - - progenitor - - - - - - - - - - - - - - - - - - - - - - - lookupElementProcessorProgenitor - - - - - - - - - - - - - - - - return - - - - - - - - - - - name - - - - - - - - - - - - - - - - - - - - - - - doCreateElementProcessor - - - - - - - - - - - - - - - - return - - - - - - - - - - - progenitor - - - - - - - - - - - - - - - - - - - - - - - constructElementProcessor - - - - - - - - - - - - - - - - return - - - - - - - - - - - progenitor - - - - - - - - - - - - - - - - - - - - - - - createNewElementProcessorInstance - - - - - - - - - - - - - - - - return - - - - - - - - - - - progenitor - - - - - - - - - - - - - - - - - - - - - - - - - HSSFSerializer - - - - - - - - - - - - - - - _element_processor_factory - - - - - - - - - - - - getMimeType - - - - - - - - - - - - - - - - return - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - HSSFElementProcessorFactory - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ElementProcessorFactory.CannotCreateElementProcessorException - - - - - - - - - - - - - - - - - - - - - - - - - - - includes - - - - - - - - - - - - - extends - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - java - - - - - - - - - - lang - - - - - - - - - - Object - - - - - - - - - - - Integer - - - - - - - - - - - int - - - - - - - - - - String - - - - - - - - - - - Char - - - - - - - - - - - short - - - - - - - - - - byte - - - - - - - - - - Byte - - - - - - - - - - - Short - - - - - - - - - - - boolean - - - - - - - - - - long - - - - - - - - - - double - - - - - - - - - - char - - - - - - - - - - Cloneable - - - - - - - - - - - reflect - - - - - - - - - - Constructor - - - - - - - - - - - - - Class - - - - - - - - - - - Exception - - - - - - - - - - - - - util - - - - - - - - - - Iterator - - - - - - - - - - Collection - - - - - - - - - - List - - - - - - - - - - Vector - - - - - - - - - - - SortedSet - - - - - - - - - - Set - - - - - - - - - - Stack - - - - - - - - - - - Map - - - - - - - - - - - - io - - - - - - - - - - InputStream - - - - - - - - - - - OutputStream - - - - - - - - - - - - - - - util - - - - - - - - - - FixedField - - - - - - - - - - - - - - - - - readFromBytes - - - - - - - - - - - - - - - - return - - - - - - - - - - - data[] - - - - - - - - - - - - - - - - - - - - - - - readFromStream - - - - - - - - - - - - - - - - return - - - - - - - - - - - stream - - - - - - - - - - - - - - - - - - - - - - - writeToBytes - - - - - - - - - - - - - - - - return - - - - - - - - - - - data[] - - - - - - - - - - - - - - - - - - - - - - - toString - - - - - - - - - - - - - - - - return - - - - - - - - - - - - - - - - - - - - - - - - - BitField - - - - - - - - - - - - getValue - - - - - - - - - - - - - - - - return - - - - - - - - - - - holder - - - - - - - - - - - - - - - - - - - - - - - getShortValue - - - - - - - - - - - - - - - - return - - - - - - - - - - - holder - - - - - - - - - - - - - - - - - - - - - - - getRawValue - - - - - - - - - - - - - - - - return - - - - - - - - - - - holder - - - - - - - - - - - - - - - - - - - - - - - getShortRawValue - - - - - - - - - - - - - - - - return - - - - - - - - - - - holder - - - - - - - - - - - - - - - - - - - - - - - isSet - - - - - - - - - - - - - - - - return - - - - - - - - - - - holder - - - - - - - - - - - - - - - - - - - - - - - isAllSet - - - - - - - - - - - - - - - - return - - - - - - - - - - - holder - - - - - - - - - - - - - - - - - - - - - - - setValue - - - - - - - - - - - - - - - - return - - - - - - - - - - - holder - - - - - - - - - - - value - - - - - - - - - - - - - - - - - - - - - - - setShortValue - - - - - - - - - - - - - - - - return - - - - - - - - - - - holder - - - - - - - - - - - value - - - - - - - - - - - - - - - - - - - - - - - clear - - - - - - - - - - - - - - - - return - - - - - - - - - - - holder - - - - - - - - - - - - - - - - - - - - - - - clearShort - - - - - - - - - - - - - - - - return - - - - - - - - - - - holder - - - - - - - - - - - - - - - - - - - - - - - clearByte - - - - - - - - - - - - - - - - return - - - - - - - - - - - holder - - - - - - - - - - - - - - - - - - - - - - - set - - - - - - - - - - - - - - - - return - - - - - - - - - - - holder - - - - - - - - - - - - - - - - - - - - - - - setShort - - - - - - - - - - - - - - - - return - - - - - - - - - - - holder - - - - - - - - - - - - - - - - - - - - - - - setByte - - - - - - - - - - - - - - - - return - - - - - - - - - - - holder - - - - - - - - - - - - - - - - - - - - - - - setBoolean - - - - - - - - - - - - - - - - return - - - - - - - - - - - holder - - - - - - - - - - - flag - - - - - - - - - - - - - - - - - - - - - - - setShortBoolean - - - - - - - - - - - - - - - - return - - - - - - - - - - - holder - - - - - - - - - - - flag - - - - - - - - - - - - - - - - - - - - - - - setByteBoolean - - - - - - - - - - - - - - - - return - - - - - - - - - - - holder - - - - - - - - - - - flag - - - - - - - - - - - - - - - - - - - - - - - - - ByteField - - - - - - - - - - - - - - - get - - - - - - - - - - - - - - - - return - - - - - - - - - - - - - - - - - - - - - - - set - - - - - - - - - - - - - - - - value - - - - - - - - - - - - - - - - - - - - - - - set - - - - - - - - - - - - - - - - value - - - - - - - - - - - data[] - - - - - - - - - - - - - - - - - - - - - - - - - HexDump - - - - - - - - - - - - EOL - - - - - - - - - - - - dump - - - - - - - - - - - - - - - - data[] - - - - - - - - - - - offset - - - - - - - - - - - stream - - - - - - - - - - - index - - - - - - - - - - - - - - - - - - - - - - - - - IntList - - - - - - - - - - - - add - - - - - - - - - - - - - - - - index - - - - - - - - - - - value - - - - - - - - - - - - - - - - - - - - - - - add - - - - - - - - - - - - - - - - return - - - - - - - - - - - value - - - - - - - - - - - - - - - - - - - - - - - addAll - - - - - - - - - - - - - - - - return - - - - - - - - - - - c - - - - - - - - - - - - - - - - - - - - - - - addAll - - - - - - - - - - - - - - - - return - - - - - - - - - - - index - - - - - - - - - - - c - - - - - - - - - - - - - - - - - - - - - - - clear - - - - - - - - - - - - - - - - - - - - - - - - - - contains - - - - - - - - - - - - - - - - return - - - - - - - - - - - o - - - - - - - - - - - - - - - - - - - - - - - containsAll - - - - - - - - - - - - - - - - return - - - - - - - - - - - c - - - - - - - - - - - - - - - - - - - - - - - equals - - - - - - - - - - - - - - - - return - - - - - - - - - - - o - - - - - - - - - - - - - - - - - - - - - - - get - - - - - - - - - - - - - - - - return - - - - - - - - - - - index - - - - - - - - - - - - - - - - - - - - - - - hashCode - - - - - - - - - - - - - - - - return - - - - - - - - - - - - - - - - - - - - - - - indexOf - - - - - - - - - - - - - - - - return - - - - - - - - - - - o - - - - - - - - - - - - - - - - - - - - - - - isEmpty - - - - - - - - - - - - - - - - return - - - - - - - - - - - - - - - - - - - - - - - lastIndexOf - - - - - - - - - - - - - - - - return - - - - - - - - - - - o - - - - - - - - - - - - - - - - - - - - - - - remove - - - - - - - - - - - - - - - - return - - - - - - - - - - - index - - - - - - - - - - - - - - - - - - - - - - - removeValue - - - - - - - - - - - - - - - - return - - - - - - - - - - - o - - - - - - - - - - - - - - - - - - - - - - - removeAll - - - - - - - - - - - - - - - - return - - - - - - - - - - - c - - - - - - - - - - - - - - - - - - - - - - - retainAll - - - - - - - - - - - - - - - - return - - - - - - - - - - - c - - - - - - - - - - - - - - - - - - - - - - - set - - - - - - - - - - - - - - - - return - - - - - - - - - - - index - - - - - - - - - - - element - - - - - - - - - - - - - - - - - - - - - - - size - - - - - - - - - - - - - - - - return - - - - - - - - - - - - - - - - - - - - - - - toArray - - - - - - - - - - - - - - - - return[] - - - - - - - - - - - - - - - - - - - - - - - toArray - - - - - - - - - - - - - - - - return[] - - - - - - - - - - - a[] - - - - - - - - - - - - - - - - - - - - - - - - - LittleEndian - - - - - - - - - - - - BufferUnderrunException - - - - - - - - - - - - - - getShort - - - - - - - - - - - - - - - - return - - - - - - - - - - - data[] - - - - - - - - - - - offset - - - - - - - - - - - - - - - - - - - - - - - getShort - - - - - - - - - - - - - - - - return - - - - - - - - - - - data[] - - - - - - - - - - - - - - - - - - - - - - - getInt - - - - - - - - - - - - - - - - return - - - - - - - - - - - data[] - - - - - - - - - - - offset - - - - - - - - - - - - - - - - - - - - - - - getInt - - - - - - - - - - - - - - - - return - - - - - - - - - - - data[] - - - - - - - - - - - - - - - - - - - - - - - getLong - - - - - - - - - - - - - - - - return - - - - - - - - - - - data[] - - - - - - - - - - - offset - - - - - - - - - - - - - - - - - - - - - - - getDouble - - - - - - - - - - - - - - - - return - - - - - - - - - - - data[] - - - - - - - - - - - offset - - - - - - - - - - - - - - - - - - - - - - - getDouble - - - - - - - - - - - - - - - - return - - - - - - - - - - - data[] - - - - - - - - - - - - - - - - - - - - - - - putShort - - - - - - - - - - - - - - - - data[] - - - - - - - - - - - offset - - - - - - - - - - - value - - - - - - - - - - - - - - - - - - - - - - - putShort - - - - - - - - - - - - - - - - data[] - - - - - - - - - - - value - - - - - - - - - - - - - - - - - - - - - - - getLong - - - - - - - - - - - - - - - - return - - - - - - - - - - - data[] - - - - - - - - - - - - - - - - - - - - - - - putInt - - - - - - - - - - - - - - - - data[] - - - - - - - - - - - offset - - - - - - - - - - - value - - - - - - - - - - - - - - - - - - - - - - - putInt - - - - - - - - - - - - - - - - data[] - - - - - - - - - - - value - - - - - - - - - - - - - - - - - - - - - - - putLong - - - - - - - - - - - - - - - - data[] - - - - - - - - - - - offset - - - - - - - - - - - value - - - - - - - - - - - - - - - - - - - - - - - putLong - - - - - - - - - - - - - - - - data[] - - - - - - - - - - - value - - - - - - - - - - - - - - - - - - - - - - - readShort - - - - - - - - - - - - - - - - return - - - - - - - - - - - stream - - - - - - - - - - - - - - - - - - - - - - - readInt - - - - - - - - - - - - - - - - return - - - - - - - - - - - stream - - - - - - - - - - - - - - - - - - - - - - - readLong - - - - - - - - - - - - - - - - return - - - - - - - - - - - stream - - - - - - - - - - - - - - - - - - - - - - - readFromStream - - - - - - - - - - - - - - - - return [] - - - - - - - - - - - stream - - - - - - - - - - - size - - - - - - - - - - - - - - - - - - - - - - - - - LittleEndianConsts - - - - - - - - - - - - SHORT_SIZE - - - - - - - java - 2 - - - - - - - - - - - INT_SIZE - - - - - - - java - 4 - - - - - - - - - - - LONG_SIZE - - - - - - - java - 8 - - - - - - - - - - - DOUBLE_SIZE - - - - - - - java - 8 - - - - - - - - - - - transient - false - - - - - - - - - - LongField - - - - - - - - - - - - - - - get - - - - - - - - - - - - - - - - return - - - - - - - - - - - - - - - - - - - - - - - set - - - - - - - - - - - - - - - - value - - - - - - - - - - - - - - - - - - - - - - - set - - - - - - - - - - - - - - - - value - - - - - - - - - - - data[] - - - - - - - - - - - - - - - - - - - - - - - - - ShortField - - - - - - - - - - - - - - - get - - - - - - - - - - - - - - - - return - - - - - - - - - - - - - - - - - - - - - - - set - - - - - - - - - - - - - - - - value - - - - - - - - - - - - - - - - - - - - - - - set - - - - - - - - - - - - - - - - value - - - - - - - - - - - data[] - - - - - - - - - - - - - - - - - - - - - - - - - ShortList - - - - - - - - - - - - add - - - - - - - - - - - - - - - - index - - - - - - - - - - - value - - - - - - - - - - - - - - - - - - - - - - - add - - - - - - - - - - - - - - - - value - - - - - - - - - - - - - - - - - - - - - - - addAll - - - - - - - - - - - - - - - - return - - - - - - - - - - - c - - - - - - - - - - - - - - - - - - - - - - - addAll - - - - - - - - - - - - - - - - return - - - - - - - - - - - index - - - - - - - - - - - c - - - - - - - - - - - - - - - - - - - - - - - clear - - - - - - - - - - - - - - - - - - - - - - - - - - contains - - - - - - - - - - - - - - - - return - - - - - - - - - - - o - - - - - - - - - - - - - - - - - - - - - - - containsAll - - - - - - - - - - - - - - - - return - - - - - - - - - - - c - - - - - - - - - - - - - - - - - - - - - - - equals - - - - - - - - - - - - - - - - return - - - - - - - - - - - o - - - - - - - - - - - - - - - - - - - - - - - get - - - - - - - - - - - - - - - - return - - - - - - - - - - - index - - - - - - - - - - - - - - - - - - - - - - - hashCode - - - - - - - - - - - - - - - - return - - - - - - - - - - - - - - - - - - - - - - - indexOf - - - - - - - - - - - - - - - - return - - - - - - - - - - - o - - - - - - - - - - - - - - - - - - - - - - - isEmpty - - - - - - - - - - - - - - - - return - - - - - - - - - - - - - - - - - - - - - - - lastIndexof - - - - - - - - - - - - - - - - return - - - - - - - - - - - o - - - - - - - - - - - - - - - - - - - - - - - remove - - - - - - - - - - - - - - - - return - - - - - - - - - - - index - - - - - - - - - - - - - - - - - - - - - - - removeValue - - - - - - - - - - - - - - - - return - - - - - - - - - - - o - - - - - - - - - - - - - - - - - - - - - - - removeAll - - - - - - - - - - - - - - - - return - - - - - - - - - - - c - - - - - - - - - - - - - - - - - - - - - - - retainAll - - - - - - - - - - - - - - - - return - - - - - - - - - - - c - - - - - - - - - - - - - - - - - - - - - - - set - - - - - - - - - - - - - - - - return - - - - - - - - - - - index - - - - - - - - - - - element - - - - - - - - - - - - - - - - - - - - - - - size - - - - - - - - - - - - - - - - return - - - - - - - - - - - - - - - - - - - - - - - toArray - - - - - - - - - - - - - - - - return[] - - - - - - - - - - - - - - - - - - - - - - - toArray - - - - - - - - - - - - - - - - return [] - - - - - - - - - - - a[] - - - - - - - - - - - - - - - - - - - - - - - - - IntegerField - - - - - - - - - - - - - - - get - - - - - - - - - - - - - - - - return - - - - - - - - - - - - - - - - - - - - - - - set - - - - - - - - - - - - - - - - value - - - - - - - - - - - - - - - - - - - - - - - set - - - - - - - - - - - - - - - - value - - - - - - - - - - - data[] - - - - - - - - - - - - - - - - - - - - - - - - - StringUtil - - - - - - - - - - - - getFromUnicode - - - - - - - - - - - - - - - - return - - - - - - - - - - - string[] - - - - - - - - - - - offset - - - - - - - - - - - len - - - - - - - - - - - - - - - - - - - - - - - getFromUnicode - - - - - - - - - - - - - - - - return - - - - - - - - - - - string[] - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - realize - - - - - - - - - - - - - - - - - - - - - - - - - realize - - - - - - - - - - - - - - - - - - - - - - - - - realize - - - - - - - - - - - - - - - - - - - - - - - - - realize - - - - - - - - - - - - - - - create - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - addProperty - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - addChild - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - create - - - - - - - - - - - create - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - create - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Filesystem - - - - - - - - - - - - - - - - - HeaderBlock - - - - - - - - - - - - - - - PropertyTable - - - - - - - - - - - - - - - - - RootProperty - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - create - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - create - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - create - - - - - - - - - - - create - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - getDocumentProperty - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - getRoot - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - create (multiple) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - create - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Filesystem - - - - - - - - - - - - - - - - - - - - - Document - - - - - - - - - - - - - - - - - - - - - DocumentBlock - - - - - - - - - - - - - DocumentProperty - - - - - - - - - - - - - PropertyTable - - - - - - - - - - - - - - - RootProperty - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - create (1 .. n) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - create - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - getDocumentProperty - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - addProperty - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - getRoot - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - addChild - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - create - - - - - - - - - - - setIndex (for each Property) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - createPropertyBlockArray - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - create (enough so we have a multiple of 4 properties) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - create (1 for every 4 properties) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - preWrite (for each Property) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - setNextFile - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - set _child_property - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - setPreviousFile - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - preWrite - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - countBlocks - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - allocateSpace - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - setStartBlock - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - createBlocks - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - setBatBlocks - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - setPropertyStart - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - writeBlocks - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - create - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - setXBATStart - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - createDocument - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - writeFileSystem - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - create - - - - - - - - - - - Filesystem - - - - - - - - - - - - - - - HeaderBlock - - - - - - - - - - - - - PropertyTable - - - - - - - - - - - - - - - - - RootProperty - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Filesystem - - - - - - - - - - - - - - - - - - - - - Document - - - - - - - - - - - - - - - - - - - - - DocumentProperty - - - - - - - - - - - - - DocumentBlock - - - - - - - - - - - - - PropertyTable - - - - - - - - - - - - - - - RootProperty - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - PropertyTable - - - - - - - - - - - - - - - - - Property - - - - - - - - - - - - - - - PropertyBlock - - - - - - - - - - - - - - - - - - - PropertyBlock - - - - - - - - - - - - - Property - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - RootProperty - - - - - - - - - - - - - - - - - - - - - Property - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Filesystem - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - PropertyTable - - - - - - - - - - - - - BATManaged - - - - - - - - - - - - - - - BlockAllocationTable - - - - - - - - - - - - - - - - - HeaderBlock - - - - - - - - - - - - - - - - - BlockWritable - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - (Client Application) - - - - - - - - - - - - - - - - - Filesystem - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/models/poifsAnalysisClasses.pgml b/src/models/poifsAnalysisClasses.pgml deleted file mode 100644 index 91ae56432..000000000 --- a/src/models/poifsAnalysisClasses.pgml +++ /dev/null @@ -1,1243 +0,0 @@ - - - - - - - - - - POIFileSystem - - - +readFileSystem(InputStream in)() : POIFileSystem - - - - - - - Block - - - +createBlock(byte[] bytes, int offset, int length)() : Block - - - - - - - HeaderBlock - - - - - - - - - - BATBlock - - - - - - - - - - PropertyTableBlock - - - - - - - - - - Property - - - - - - - - - - RootProperty - - - - - - - - - - BAT - - -blocks[0..*] : BATBlock - +createRecord(bytes:Collection) : int -+getBlocks() : Collection - - - - - - - PropertyTable - - - +createRecord(name:String, startBlock:int, :) - - - - - - - DirectoryProperty - - - - - - - - - - FileProperty - - - - - - - sourcePortFig="Fig3.0" - destPortFig="Fig1.0" - sourceFigNode="Fig3" - destFigNode="Fig1" - - - - - - - - - - - sourcePortFig="Fig4.0" - destPortFig="Fig1.0" - sourceFigNode="Fig4" - destFigNode="Fig1" - - - - - - - - - - - sourcePortFig="Fig2.0" - destPortFig="Fig1.0" - sourceFigNode="Fig2" - destFigNode="Fig1" - - - - - - - - - - - sourcePortFig="Fig7.0" - destPortFig="Fig1.0" - sourceFigNode="Fig7" - destFigNode="Fig1" - - - - - - - 0..* - - - - - sourcePortFig="Fig4.0" - destPortFig="Fig5.0" - sourceFigNode="Fig4" - destFigNode="Fig5" - - - - - - - 0..* - - - - - sourcePortFig="Fig9.0" - destPortFig="Fig5.0" - sourceFigNode="Fig9" - destFigNode="Fig5" - - - - - - - - - - - sourcePortFig="Fig6.0" - destPortFig="Fig9.0" - sourceFigNode="Fig6" - destFigNode="Fig9" - - - - - - - - - - - sourcePortFig="Fig10.0" - destPortFig="Fig5.0" - sourceFigNode="Fig10" - destFigNode="Fig5" - - - - - - - - - - - sourcePortFig="Fig9.0" - destPortFig="Fig5.0" - sourceFigNode="Fig9" - destFigNode="Fig5" - - - - - - - child - - - - - sourcePortFig="Fig5.0" - destPortFig="Fig5.0" - sourceFigNode="Fig5" - destFigNode="Fig5" - - - - - - - - - +next - 0..1 - - - - - sourcePortFig="Fig5.0" - destPortFig="Fig5.0" - sourceFigNode="Fig5" - destFigNode="Fig5" - - - - - - - - - 0..1 - previous - - - diff --git a/src/models/projectmain.pgml b/src/models/projectmain.pgml deleted file mode 100644 index e385871f9..000000000 --- a/src/models/projectmain.pgml +++ /dev/null @@ -1,156 +0,0 @@ - - - - - - - - - analysisModel - - - - - - - designModel - - - - - - - util - - - diff --git a/src/models/readFileFromFilesystemSequenceDiagram.pgml b/src/models/readFileFromFilesystemSequenceDiagram.pgml deleted file mode 100644 index e2af7401f..000000000 --- a/src/models/readFileFromFilesystemSequenceDiagram.pgml +++ /dev/null @@ -1,1296 +0,0 @@ - - - - - - - enclosingFig="Fig0" - - - - : ClientApps - - - - - - - - - - - - - - - - enclosingFig="Fig1" - - - - : POIFileSystem - - - - - - - - - - - - - - - - - - - - enclosingFig="Fig2" - - - - : PropertyTable - - - - - - - - - - - - - - - - enclosingFig="Fig3" - - - - PropertyBlock : - - - - - - - - - - - - - - - enclosingFig="Fig4" - - - - : BAT - - - - - - - - - - - - - - - - enclosingFig="Fig5" - - - - : BATBlock - - - - - - - - - - - - - - - enclosingFig="Fig6" - - - - : Block - - - - - - - - - - - - - - - enclosingFig="Fig7" - - - - ByteArrayInputStream : Object - - - - - - - - - - - - - - - - : gets property from - - - - - : gets property from - - - - - : gets BAT Chain from - - - - - : gets next bat chain element [until all are read] - - - - - : gets bytes [from each block in bat chain] - - - - - : constructs a byte array input stream with file bytes - - - - - : requests file - - - - - : returns input stream - - - - sourcePortFig="Fig1.7" - destPortFig="Fig2.7" - sourceFigNode="Fig1" - destFigNode="Fig2" - - - - - - - - - - - sourcePortFig="Fig2.8" - destPortFig="Fig3.7" - sourceFigNode="Fig2" - destFigNode="Fig3" - - - - - - - - - - - sourcePortFig="Fig1.8" - destPortFig="Fig4.7" - sourceFigNode="Fig1" - destFigNode="Fig4" - - - - - - - - - - - sourcePortFig="Fig4.8" - destPortFig="Fig5.7" - sourceFigNode="Fig4" - destFigNode="Fig5" - - - - - - - - - - - sourcePortFig="Fig1.9" - destPortFig="Fig6.7" - sourceFigNode="Fig1" - destFigNode="Fig6" - - - - - - - - - - - sourcePortFig="Fig1.10" - destPortFig="Fig7.7" - sourceFigNode="Fig1" - destFigNode="Fig7" - - - - - - - - - - - sourcePortFig="Fig0.7" - destPortFig="Fig1.11" - sourceFigNode="Fig0" - destFigNode="Fig1" - - - - - - - - - - - sourcePortFig="Fig1.12" - destPortFig="Fig0.8" - sourceFigNode="Fig1" - destFigNode="Fig0" - - - - - - - - - diff --git a/src/models/readFileSystemDirectorySequenceDiagram.pgml b/src/models/readFileSystemDirectorySequenceDiagram.pgml deleted file mode 100644 index 5456e960d..000000000 --- a/src/models/readFileSystemDirectorySequenceDiagram.pgml +++ /dev/null @@ -1,428 +0,0 @@ - - - - - - - - - - : ClientApps - - - - - - - - - - - - - - - - - - : POIFileSystem - - - - - - - - - - - - - - - - - - - : PropertyTable - - - - - - - - - - - - - - - - : requests directory listing - - - - - : enumerates properties - - - - sourcePortFig="Fig0.7" - destPortFig="Fig1.7" - sourceFigNode="Fig0" - destFigNode="Fig1" - - - - - - - - - - - sourcePortFig="Fig1.8" - destPortFig="Fig2.7" - sourceFigNode="Fig1" - destFigNode="Fig2" - - - - - - - - - diff --git a/src/models/readFilesystemSequenceDiagram.pgml b/src/models/readFilesystemSequenceDiagram.pgml deleted file mode 100644 index 5c72dad5a..000000000 --- a/src/models/readFilesystemSequenceDiagram.pgml +++ /dev/null @@ -1,1382 +0,0 @@ - - - - - - - enclosingFig="Fig0" - - - - : ClientApps - - - - - - - - - - - - - - - enclosingFig="Fig1" - - - - : POIFileSystem - - - - - - - - - - - - - - - - - - - - - - - - - InputStream : Object - - - - - - - - - - - - - - - enclosingFig="Fig3" - - - - : HeaderBlock - - - - - - - - - - - - - - - enclosingFig="Fig4" - - - - : Block - - - - - - - - - - - - - - - enclosingFig="Fig5" - - - - : BATBlock - - - - - - - - - - - - - - - - - - : PropertyTableBlock - - - - - - - - - - - - - - - enclosingFig="Fig7" - - - - : BAT - - - - - - - - - - - - - - - - - - : PropertyTable - - - - - - - - - - - - - - - - : create the filesystem - - - - - : read all bytes - - - - - : create a header block from first 512 bytes - - - - - : create blocks from all blocks that are not header,bat or property blocks - - - - - : create bat blocks from bytes that are in bat - - - - - : create property table blocks from bytes starting at header.rootstartblock - - - - - : assign BAT Blocks to the BAT - - - - - : derive property instances from the Property Table Blocks and add them to the property table - - - - sourcePortFig="Fig0.7" - destPortFig="Fig1.7" - sourceFigNode="Fig0" - destFigNode="Fig1" - - - - - - - - - - - sourcePortFig="Fig1.8" - destPortFig="Fig2.7" - sourceFigNode="Fig1" - destFigNode="Fig2" - - - - - - - - - - - sourcePortFig="Fig1.9" - destPortFig="Fig3.7" - sourceFigNode="Fig1" - destFigNode="Fig3" - - - - - - - - - - - sourcePortFig="Fig1.10" - destPortFig="Fig4.7" - sourceFigNode="Fig1" - destFigNode="Fig4" - - - - - - - - - - - sourcePortFig="Fig1.11" - destPortFig="Fig5.7" - sourceFigNode="Fig1" - destFigNode="Fig5" - - - - - - - - - - - sourcePortFig="Fig1.12" - destPortFig="Fig6.7" - sourceFigNode="Fig1" - destFigNode="Fig6" - - - - - - - - - - - sourcePortFig="Fig1.13" - destPortFig="Fig7.7" - sourceFigNode="Fig1" - destFigNode="Fig7" - - - - - - - - - - - sourcePortFig="Fig1.14" - destPortFig="Fig8.7" - sourceFigNode="Fig1" - destFigNode="Fig8" - - - - - - - - - diff --git a/src/models/utilClasses.pgml b/src/models/utilClasses.pgml deleted file mode 100644 index d70dec548..000000000 --- a/src/models/utilClasses.pgml +++ /dev/null @@ -1,1123 +0,0 @@ - - - - - - - - - - <<Interface>> - FixedField - +readFromBytes(in data[]:byte) -+readFromStream(in stream:InputStream) -+writeToBytes(in data[]:byte) -+toString() : String - - - - - - - BitField - - - +getValue(in holder:int) : int -+getShortValue(in holder:Short) : short -+getRawValue(in holder:int) : int -+getShortRawValue(in holder:short) : short -+isSet(in holder:int) : boolean -+isAllSet(in holder:int) : boolean -+setValue(in holder:int, in value:int) : int -+setShortValue(in holder:short, in value:short) : short -+clear(in holder:int) : int -+clearShort(in holder:short) : short -+clearByte(in holder:byte) : byte -+set(in holder:int) : int -+setShort(in holder:short) : short -+setByte(in holder:byte) : byte -+setBoolean(in holder:int, in flag:boolean) : int -+setShortBoolean(in holder:short, in flag:boolean) : short -+setByteBoolean(in holder:byte, in flag:boolean) : byte - - - - - - - ByteField - - - +get() : byte -+set(in value:byte) -+set(in value:byte, in data[]:byte) - - - - - - - HexDump - - +EOL : String - +dump(in data[]:byte, in offset:long, in stream:OutputStream, in index:int) - - - - - - - IntList - - - +add(in index:int, in value:int) -+add(in value:int) : boolean -+addAll(in c:IntList) : boolean -+addAll(in index:int, in c:IntList) : boolean -+clear() -+contains(in o:int) : boolean -+containsAll(in c:IntList) : boolean -+equals(in o:Object) : boolean -+get(in index:int) : int -+hashCode() : int -+indexOf(in o:int) : int -+isEmpty() : boolean -+lastIndexOf(in o:int) : int -+remove(in index:int) : int -+removeValue(in o:int) : boolean -+removeAll(in c:IntList) : boolean -+retainAll(in c:IntList) : boolean -+set(in index:int, in element:int) : int -+size() : int -+toArray() : int -+toArray(in a[]:int) : int - - - - - - - LittleEndian - - - +getShort(in data[]:byte, in offset:int) : short -+getShort(in data[]:byte) : short -+getInt(in data[]:byte, in offset:int) : int -+getInt(in data[]:byte) : int -+getLong(in data[]:byte, in offset:int) : long -+getDouble(in data[]:byte, in offset:int) : double -+getDouble(in data[]:byte) : double -+putShort(in data[]:byte, in offset:int, in value:short) -+putShort(in data[]:byte, in value:short) -+getLong(in data[]:byte) : long -+putInt(in data[]:byte, in offset:int, in value:int) -+putInt(in data[]:byte, in value:int) -+putLong(in data[]:byte, in offset:int, in value:long) -+putLong(in data[]:byte, in value:long) -+readShort(in stream:InputStream) : short -+readInt(in stream:InputStream) : int -+readLong(in stream:InputStream) : long -+readFromStream(in stream:InputStream, in size:int) : byte - - - - - - - LittleEndianConsts - - +SHORT_SIZE : int = 2 -+INT_SIZE : int = 4 -+LONG_SIZE : int = 8 -+DOUBLE_SIZE : int = 8 - - - - - - - - LongField - - - +get() : long -+set(in value:long) -+set(in value:long, in data[]:byte) - - - - - - - ShortField - - - +get() : short -+set(in value:short) -+set(in value:short, in data[]:byte) - - - - - - - ShortList - - - +add(in index:int, in value:short) -+add(in value:short) -+addAll(in c:ShortList) : boolean -+addAll(in index:int, in c:ShortList) : boolean -+clear() -+contains(in o:short) : boolean -+containsAll(in c:ShortList) : boolean -+equals(in o:Object) : boolean -+get(in index:int) : short -+hashCode() : int -+indexOf(in o:short) : int -+isEmpty() : boolean -+lastIndexof(in o:short) : int -+remove(in index:int) : short -+removeValue(in o:short) : boolean -+removeAll(in c:ShortList) : boolean -+retainAll(in return:boolean, in c:ShortList) -+set(in index:int, in element:short) : short -+size() : int -+toArray() : short -+toArray(in a[]:short) : short - - - - - - - IntegerField - - - +get() : int -+set(in value:int) -+set(in value:int, in data[]:byte) - - - - - - - StringUtil - - - +getFromUnicode(in string[]:byte, in offset:int, in len:int) : String -+getFromUnicode(in string[]:byte) : String - - - - sourcePortFig="Fig2.0" - destPortFig="Fig0.0" - sourceFigNode="Fig2" - destFigNode="Fig0" - - - - - - - - - - - sourcePortFig="Fig10.0" - destPortFig="Fig0.0" - sourceFigNode="Fig10" - destFigNode="Fig0" - - - - - - - - - - - - sourcePortFig="Fig7.0" - destPortFig="Fig0.0" - sourceFigNode="Fig7" - destFigNode="Fig0" - - - - - - - - - - - sourcePortFig="Fig8.0" - destPortFig="Fig0.0" - sourceFigNode="Fig8" - destFigNode="Fig0" - - - - - - - - - diff --git a/src/models/writeFilesystemSequenceDiagram.pgml b/src/models/writeFilesystemSequenceDiagram.pgml deleted file mode 100644 index fc5746c26..000000000 --- a/src/models/writeFilesystemSequenceDiagram.pgml +++ /dev/null @@ -1,1892 +0,0 @@ - - - - - - - - - - : ClientApps - - - - - - - - - - - - - - - - enclosingFig="Fig1" - - - - : POIFileSystem - - - - - - - - - - - - - - - - - - - - - - - enclosingFig="Fig2" - - - - : HeaderBlock - - - - - - - - - - - - - - - - - enclosingFig="Fig3" - - - - : Block - - - - - - - - - - - - - - - enclosingFig="Fig4" - - - - : BAT - - - - - - - - - - - - - - - - - - enclosingFig="Fig5" - - - - : BATBlock - - - - - - - - - - - - - - - - - - : PropertyTable - - - - - - - - - - - - - - - - - - enclosingFig="Fig7" - - - - : PropertyTableBlock - - - - - - - - - - - - - - - - enclosingFig="Fig8" - - - - : Property - - - - - - - - - - - - - - - enclosingFig="Fig9" - - - - OutputStream : Object - - - - - - - - - - - - - - - - : createFileSystem - - - - - : createHeaderBlock - - - - - : createBlock [until all files have blocks] - - - - - : create a record [until all files have records] - - - - - : create bat block [if need more] - - - - - : create a record [until all files have records] - - - - - : get the bat array info - - - - - : get the extended bat array info - - - - - : set the bat info - - - - - : set the extended bat info - - - - - : create a block [if needed] - - - - - : create a property - - - - - : add the propert to the block - - - - - : write all blocks to stream - - - - sourcePortFig="Fig0.7" - destPortFig="Fig1.7" - sourceFigNode="Fig0" - destFigNode="Fig1" - - - - - - - - - - - sourcePortFig="Fig1.8" - destPortFig="Fig2.7" - sourceFigNode="Fig1" - destFigNode="Fig2" - - - - - - - - - - - sourcePortFig="Fig1.9" - destPortFig="Fig3.7" - sourceFigNode="Fig1" - destFigNode="Fig3" - - - - - - - - - - - sourcePortFig="Fig1.10" - destPortFig="Fig4.7" - sourceFigNode="Fig1" - destFigNode="Fig4" - - - - - - - - - - - sourcePortFig="Fig4.8" - destPortFig="Fig5.7" - sourceFigNode="Fig4" - destFigNode="Fig5" - - - - - - - - - - - sourcePortFig="Fig1.11" - destPortFig="Fig6.7" - sourceFigNode="Fig1" - destFigNode="Fig6" - - - - - - - - - - - sourcePortFig="Fig1.12" - destPortFig="Fig4.9" - sourceFigNode="Fig1" - destFigNode="Fig4" - - - - - - - - - - - sourcePortFig="Fig1.13" - destPortFig="Fig4.10" - sourceFigNode="Fig1" - destFigNode="Fig4" - - - - - - - - - - - sourcePortFig="Fig1.14" - destPortFig="Fig2.8" - sourceFigNode="Fig1" - destFigNode="Fig2" - - - - - - - - - - - sourcePortFig="Fig1.15" - destPortFig="Fig2.9" - sourceFigNode="Fig1" - destFigNode="Fig2" - - - - - - - - - - - sourcePortFig="Fig6.8" - destPortFig="Fig7.7" - sourceFigNode="Fig6" - destFigNode="Fig7" - - - - - - - - - - - sourcePortFig="Fig6.9" - destPortFig="Fig8.7" - sourceFigNode="Fig6" - destFigNode="Fig8" - - - - - - - - - - - sourcePortFig="Fig6.10" - destPortFig="Fig7.8" - sourceFigNode="Fig6" - destFigNode="Fig7" - - - - - - - - - - - sourcePortFig="Fig0.8" - destPortFig="Fig9.7" - sourceFigNode="Fig0" - destFigNode="Fig9" - - - - - - - - - diff --git a/src/ooxml/java/org/apache/poi/POIXMLDocument.java b/src/ooxml/java/org/apache/poi/POIXMLDocument.java deleted file mode 100644 index 93afa6163..000000000 --- a/src/ooxml/java/org/apache/poi/POIXMLDocument.java +++ /dev/null @@ -1,250 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi; - -import java.io.Closeable; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.exceptions.OpenXML4JException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackageAccess; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.opc.PackageRelationship; -import org.apache.poi.openxml4j.opc.PackageRelationshipCollection; -import org.apache.poi.poifs.filesystem.DocumentFactoryHelper; -import org.apache.xmlbeans.impl.common.SystemCache; - -/** - * This holds the common functionality for all POI OOXML Document classes. - */ -// TODO: implements AutoCloseable in Java 7+ when POI drops support for Java 6. -public abstract class POIXMLDocument extends POIXMLDocumentPart implements Closeable { - public static final String DOCUMENT_CREATOR = "Apache POI"; - - // OLE embeddings relation name - public static final String OLE_OBJECT_REL_TYPE="http://schemas.openxmlformats.org/officeDocument/2006/relationships/oleObject"; - - // Embedded OPC documents relation name - public static final String PACK_OBJECT_REL_TYPE="http://schemas.openxmlformats.org/officeDocument/2006/relationships/package"; - - /** The OPC Package */ - private OPCPackage pkg; - - /** - * The properties of the OPC package, opened as needed - */ - private POIXMLProperties properties; - - protected POIXMLDocument(OPCPackage pkg) { - super(pkg); - init(pkg); - } - - protected POIXMLDocument(OPCPackage pkg, String coreDocumentRel) { - super(pkg, coreDocumentRel); - init(pkg); - } - - private void init(OPCPackage p) { - this.pkg = p; - - // Workaround for XMLBEANS-512 - ensure that when we parse - // the file, we start with a fresh XML Parser each time, - // and avoid the risk of getting a SaxHandler that's in error - SystemCache.get().setSaxLoader(null); - } - - /** - * Wrapper to open a package, which works around shortcomings in java's this() constructor calls - * - * @param path the path to the document - * @return the new OPCPackage - * - * @exception IOException if there was a problem opening the document - */ - public static OPCPackage openPackage(String path) throws IOException { - try { - return OPCPackage.open(path); - } catch (InvalidFormatException e) { - throw new IOException(e.toString(), e); - } - } - - /** - * Get the assigned OPCPackage - * - * @return the assigned OPCPackage - */ - public OPCPackage getPackage() { - return this.pkg; - } - - protected PackagePart getCorePart() { - return getPackagePart(); - } - - /** - * Retrieves all the PackageParts which are defined as relationships of the base document with the - * specified content type. - * - * @param contentType the content type - * - * @return all the base document PackageParts which match the content type - * - * @throws InvalidFormatException when the relationships or the parts contain errors - * - * @see org.apache.poi.xssf.usermodel.XSSFRelation - * @see org.apache.poi.xslf.usermodel.XSLFRelation - * @see org.apache.poi.xwpf.usermodel.XWPFRelation - * @see org.apache.poi.xdgf.usermodel.XDGFRelation - */ - protected PackagePart[] getRelatedByType(String contentType) throws InvalidFormatException { - PackageRelationshipCollection partsC = - getPackagePart().getRelationshipsByType(contentType); - - PackagePart[] parts = new PackagePart[partsC.size()]; - int count = 0; - for (PackageRelationship rel : partsC) { - parts[count] = getPackagePart().getRelatedPart(rel); - count++; - } - return parts; - } - - /** - * Checks that the supplied InputStream (which MUST - * support mark and reset, or be a PushbackInputStream) - * has a OOXML (zip) header at the start of it. - * If your InputStream does not support mark / reset, - * then wrap it in a PushBackInputStream, then be - * sure to always use that, and not the original! - * - * @param inp An InputStream which supports either mark/reset, or is a PushbackInputStream - * @return true, if the InputStream is an ooxml document - * - * @throws IOException if the InputStream can't be read - * - * @deprecated use the method from DocumentFactoryHelper, deprecated as of 3.15-beta1, therefore eligible for removal in 3.17 - */ - @Deprecated - public static boolean hasOOXMLHeader(InputStream inp) throws IOException { - return DocumentFactoryHelper.hasOOXMLHeader(inp); - } - - /** - * Get the document properties. This gives you access to the - * core ooxml properties, and the extended ooxml properties. - * - * @return the document properties - */ - public POIXMLProperties getProperties() { - if(properties == null) { - try { - properties = new POIXMLProperties(pkg); - } catch (Exception e){ - throw new POIXMLException(e); - } - } - return properties; - } - - /** - * Get the document's embedded files. - * - * @return the document's embedded files - * - * @throws OpenXML4JException if the embedded parts can't be determined - */ - public abstract List getAllEmbedds() throws OpenXML4JException; - - protected final void load(POIXMLFactory factory) throws IOException { - Map context = new HashMap(); - try { - read(factory, context); - } catch (OpenXML4JException e){ - throw new POIXMLException(e); - } - onDocumentRead(); - context.clear(); - } - - /** - * Closes the underlying {@link OPCPackage} from which this - * document was read, if there is one - * - *

    Once this has been called, no further - * operations, updates or reads should be performed on the - * document. - * - * @throws IOException for writable packages, if an IO exception occur during the saving process. - */ - @Override - public void close() throws IOException { - if (pkg != null) { - if (pkg.getPackageAccess() == PackageAccess.READ) { - pkg.revert(); - } else { - pkg.close(); - } - pkg = null; - } - } - - /** - * Write out this document to an Outputstream. - * - * Note - if the Document was opened from a {@link File} rather - * than an {@link InputStream}, you must write out to - * a different file, overwriting via an OutputStream isn't possible. - * - * If {@code stream} is a {@link java.io.FileOutputStream} on a networked drive - * or has a high cost/latency associated with each written byte, - * consider wrapping the OutputStream in a {@link java.io.BufferedOutputStream} - * to improve write performance. - * - * @param stream - the java OutputStream you wish to write the file to - * - * @exception IOException if anything can't be written. - */ - @SuppressWarnings("resource") - public final void write(OutputStream stream) throws IOException { - OPCPackage p = getPackage(); - if(p == null) { - throw new IOException("Cannot write data, document seems to have been closed already"); - } - - //force all children to commit their changes into the underlying OOXML Package - // TODO Shouldn't they be committing to the new one instead? - Set context = new HashSet(); - onSave(context); - context.clear(); - - //save extended and custom properties - getProperties().commit(); - - p.save(stream); - } -} diff --git a/src/ooxml/java/org/apache/poi/POIXMLDocumentPart.java b/src/ooxml/java/org/apache/poi/POIXMLDocumentPart.java deleted file mode 100644 index 163ace54a..000000000 --- a/src/ooxml/java/org/apache/poi/POIXMLDocumentPart.java +++ /dev/null @@ -1,697 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi; - -import java.io.IOException; -import java.net.URI; -import java.util.ArrayList; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.exceptions.OpenXML4JException; -import org.apache.poi.openxml4j.exceptions.PartAlreadyExistsException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.opc.PackagePartName; -import org.apache.poi.openxml4j.opc.PackageRelationship; -import org.apache.poi.openxml4j.opc.PackageRelationshipCollection; -import org.apache.poi.openxml4j.opc.PackageRelationshipTypes; -import org.apache.poi.openxml4j.opc.PackagingURIHelper; -import org.apache.poi.openxml4j.opc.TargetMode; -import org.apache.poi.util.Internal; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.xssf.usermodel.XSSFRelation; - -/** - * Represents an entry of a OOXML package. - * - *

    - * Each POIXMLDocumentPart keeps a reference to the underlying a {@link org.apache.poi.openxml4j.opc.PackagePart}. - *

    - */ -public class POIXMLDocumentPart { - private static final POILogger logger = POILogFactory.getLogger(POIXMLDocumentPart.class); - - private String coreDocumentRel = PackageRelationshipTypes.CORE_DOCUMENT; - private PackagePart packagePart; - private POIXMLDocumentPart parent; - private Map relations = new LinkedHashMap(); - - /** - * The RelationPart is a cached relationship between the document, which contains the RelationPart, - * and one of its referenced child document parts. - * The child document parts may only belong to one parent, but it's often referenced by other - * parents too, having varying {@link PackageRelationship#getId() relationship ids} pointing to it. - */ - public static class RelationPart { - private final PackageRelationship relationship; - private final POIXMLDocumentPart documentPart; - - RelationPart(PackageRelationship relationship, POIXMLDocumentPart documentPart) { - this.relationship = relationship; - this.documentPart = documentPart; - } - - /** - * @return the cached relationship, which uniquely identifies this child document part within the parent - */ - public PackageRelationship getRelationship() { - return relationship; - } - - /** - * @param the cast of the caller to a document sub class - * - * @return the child document part - */ - @SuppressWarnings("unchecked") - public T getDocumentPart() { - return (T)documentPart; - } - } - - /** - * Counter that provides the amount of incoming relations from other parts - * to this part. - */ - private int relationCounter = 0; - - int incrementRelationCounter() { - relationCounter++; - return relationCounter; - } - - int decrementRelationCounter() { - relationCounter--; - return relationCounter; - } - - int getRelationCounter() { - return relationCounter; - } - - /** - * Construct POIXMLDocumentPart representing a "core document" package part. - * - * @param pkg the OPCPackage containing this document - */ - public POIXMLDocumentPart(OPCPackage pkg) { - this(pkg, PackageRelationshipTypes.CORE_DOCUMENT); - } - - /** - * Construct POIXMLDocumentPart representing a custom "core document" package part. - * - * @param pkg the OPCPackage containing this document - * @param coreDocumentRel the relation type of this document - */ - public POIXMLDocumentPart(OPCPackage pkg, String coreDocumentRel) { - this(getPartFromOPCPackage(pkg, coreDocumentRel)); - this.coreDocumentRel = coreDocumentRel; - } - - /** - * Creates new POIXMLDocumentPart - called by client code to create new parts from scratch. - * - * @see #createRelationship(POIXMLRelation, POIXMLFactory, int, boolean) - */ - public POIXMLDocumentPart() { - } - - /** - * Creates an POIXMLDocumentPart representing the given package part and relationship. - * Called by {@link #read(POIXMLFactory, java.util.Map)} when reading in an existing file. - * - * @param part - The package part that holds xml data representing this sheet. - * @see #read(POIXMLFactory, java.util.Map) - * - * @since POI 3.14-Beta1 - */ - public POIXMLDocumentPart(PackagePart part) { - this(null, part); - } - - /** - * Creates an POIXMLDocumentPart representing the given package part, relationship and parent - * Called by {@link #read(POIXMLFactory, java.util.Map)} when reading in an existing file. - * - * @param parent - Parent part - * @param part - The package part that holds xml data representing this sheet. - * @see #read(POIXMLFactory, java.util.Map) - * - * @since POI 3.14-Beta1 - */ - public POIXMLDocumentPart(POIXMLDocumentPart parent, PackagePart part) { - this.packagePart = part; - this.parent = parent; - } - - /** - * When you open something like a theme, call this to - * re-base the XML Document onto the core child of the - * current core document - * - * @param pkg the package to be rebased - * - * @throws InvalidFormatException if there was an error in the core document relation - * @throws IllegalStateException if there are more than one core document relations - */ - protected final void rebase(OPCPackage pkg) throws InvalidFormatException { - PackageRelationshipCollection cores = - packagePart.getRelationshipsByType(coreDocumentRel); - if(cores.size() != 1) { - throw new IllegalStateException( - "Tried to rebase using " + coreDocumentRel + - " but found " + cores.size() + " parts of the right type" - ); - } - packagePart = packagePart.getRelatedPart(cores.getRelationship(0)); - } - - /** - * Provides access to the underlying PackagePart - * - * @return the underlying PackagePart - */ - public final PackagePart getPackagePart(){ - return packagePart; - } - - /** - * Returns the list of child relations for this POIXMLDocumentPart - * - * @return child relations - */ - public final List getRelations(){ - List l = new ArrayList(); - for (RelationPart rp : relations.values()) { - l.add(rp.getDocumentPart()); - } - return Collections.unmodifiableList(l); - } - - /** - * Returns the list of child relations for this POIXMLDocumentPart - * - * @return child relations - */ - public final List getRelationParts() { - List l = new ArrayList(relations.values()); - return Collections.unmodifiableList(l); - } - - /** - * Returns the target {@link POIXMLDocumentPart}, where a - * {@link PackageRelationship} is set from the {@link PackagePart} of this - * {@link POIXMLDocumentPart} to the {@link PackagePart} of the target - * {@link POIXMLDocumentPart} with a {@link PackageRelationship#getId()} - * matching the given parameter value. - * - * @param id - * The relation id to look for - * @return the target part of the relation, or null, if none exists - */ - public final POIXMLDocumentPart getRelationById(String id) { - RelationPart rp = relations.get(id); - return (rp == null) ? null : rp.getDocumentPart(); - } - - /** - * Returns the {@link PackageRelationship#getId()} of the - * {@link PackageRelationship}, that sources from the {@link PackagePart} of - * this {@link POIXMLDocumentPart} to the {@link PackagePart} of the given - * parameter value. - * - * @param part - * The {@link POIXMLDocumentPart} for which the according - * relation-id shall be found. - * @return The value of the {@link PackageRelationship#getId()} or null, if - * parts are not related. - */ - public final String getRelationId(POIXMLDocumentPart part) { - for (RelationPart rp : relations.values()) { - if (rp.getDocumentPart() == part) { - return rp.getRelationship().getId(); - } - } - return null; - } - - /** - * Add a new child POIXMLDocumentPart - * - * @param relId the preferred relation id, when null the next free relation id will be used - * @param relationshipType the package relationship type - * @param part the child to add - * - * @return the new RelationPart - * - * @since 3.14-Beta1 - */ - public final RelationPart addRelation(String relId, POIXMLRelation relationshipType, POIXMLDocumentPart part) { - PackageRelationship pr = findExistingRelation(part); - if (pr == null) { - PackagePartName ppn = part.getPackagePart().getPartName(); - String relType = relationshipType.getRelation(); - pr = packagePart.addRelationship(ppn, TargetMode.INTERNAL, relType, relId); - } - addRelation(pr, part); - return new RelationPart(pr, part); - } - - /** - * Add a new child POIXMLDocumentPart - * - * @param pr the relationship of the child - * @param part the child to add - */ - private void addRelation(PackageRelationship pr, POIXMLDocumentPart part) { - relations.put(pr.getId(), new RelationPart(pr,part)); - part.incrementRelationCounter(); - - } - - /** - * Check if the new part was already added before via PackagePart.addRelationship() - * - * @param part to find the relationship for - * @return The existing relationship, or null if there isn't yet one - */ - private PackageRelationship findExistingRelation(POIXMLDocumentPart part) { - String ppn = part.getPackagePart().getPartName().getName(); - try { - for (PackageRelationship pr : packagePart.getRelationships()) { - if (pr.getTargetMode() == TargetMode.EXTERNAL) { - continue; - } - PackagePart pp = packagePart.getRelatedPart(pr); - if (ppn.equals(pp.getPartName().getName())) { - return pr; - } - } - } catch (InvalidFormatException e) { - throw new POIXMLException("invalid package relationships", e); - } - return null; - } - - /** - * Remove the relation to the specified part in this package and remove the - * part, if it is no longer needed. - * - * @param part the part which relation is to be removed from this document - */ - protected final void removeRelation(POIXMLDocumentPart part){ - removeRelation(part,true); - } - - /** - * Remove the relation to the specified part in this package and remove the - * part, if it is no longer needed and flag is set to true. - * - * @param part - * The related part, to which the relation shall be removed. - * @param removeUnusedParts - * true, if the part shall be removed from the package if not - * needed any longer. - * @return true, if the relation was removed - */ - protected final boolean removeRelation(POIXMLDocumentPart part, boolean removeUnusedParts){ - String id = getRelationId(part); - if (id == null) { - // part is not related with this POIXMLDocumentPart - return false; - } - /* decrement usage counter */ - part.decrementRelationCounter(); - /* remove packagepart relationship */ - getPackagePart().removeRelationship(id); - /* remove POIXMLDocument from relations */ - relations.remove(id); - - if (removeUnusedParts) { - /* if last relation to target part was removed, delete according target part */ - if (part.getRelationCounter() == 0) { - try { - part.onDocumentRemove(); - } catch (IOException e) { - throw new POIXMLException(e); - } - getPackagePart().getPackage().removePart(part.getPackagePart()); - } - } - return true; - } - - /** - * Returns the parent POIXMLDocumentPart. All parts except root have not-null parent. - * - * @return the parent POIXMLDocumentPart or null for the root element. - */ - public final POIXMLDocumentPart getParent(){ - return parent; - } - - @Override - public String toString(){ - return packagePart == null ? "" : packagePart.toString(); - } - - /** - * Save the content in the underlying package part. - * Default implementation is empty meaning that the package part is left unmodified. - * - * Sub-classes should override and add logic to marshal the "model" into Ooxml4J. - * - * For example, the code saving a generic XML entry may look as follows: - *
    -     * protected void commit() throws IOException {
    -     *   PackagePart part = getPackagePart();
    -     *   OutputStream out = part.getOutputStream();
    -     *   XmlObject bean = getXmlBean(); //the "model" which holds changes in memory
    -     *   bean.save(out, DEFAULT_XML_OPTIONS);
    -     *   out.close();
    -     * }
    -     * 
    - * - * @throws IOException a subclass may throw an IOException if the changes can't be committed - */ - protected void commit() throws IOException { - - } - - /** - * Save changes in the underlying OOXML package. - * Recursively fires {@link #commit()} for each package part - * - * @param alreadySaved context set containing already visited nodes - * - * @throws IOException a related part may throw an IOException if the changes can't be saved - */ - protected final void onSave(Set alreadySaved) throws IOException{ - // this usually clears out previous content in the part... - prepareForCommit(); - - commit(); - alreadySaved.add(this.getPackagePart()); - for(RelationPart rp : relations.values()){ - POIXMLDocumentPart p = rp.getDocumentPart(); - if (!alreadySaved.contains(p.getPackagePart())) { - p.onSave(alreadySaved); - } - } - } - - /** - * Ensure that a memory based package part does not have lingering data from previous - * commit() calls. - * - * Note: This is overwritten for some objects, as *PictureData seem to store the actual content - * in the part directly without keeping a copy like all others therefore we need to handle them differently. - */ - protected void prepareForCommit() { - PackagePart part = this.getPackagePart(); - if(part != null) { - part.clear(); - } - } - - /** - * Create a new child POIXMLDocumentPart - * - * @param descriptor the part descriptor - * @param factory the factory that will create an instance of the requested relation - * @return the created child POIXMLDocumentPart - * @throws PartAlreadyExistsException - * If rule M1.12 is not verified : Packages shall not contain - * equivalent part names and package implementers shall neither - * create nor recognize packages with equivalent part names. - */ - public final POIXMLDocumentPart createRelationship(POIXMLRelation descriptor, POIXMLFactory factory){ - return createRelationship(descriptor, factory, -1, false).getDocumentPart(); - } - - /** - * Create a new child POIXMLDocumentPart - * - * @param descriptor the part descriptor - * @param factory the factory that will create an instance of the requested relation - * @param idx part number - * @return the created child POIXMLDocumentPart - * @throws PartAlreadyExistsException - * If rule M1.12 is not verified : Packages shall not contain - * equivalent part names and package implementers shall neither - * create nor recognize packages with equivalent part names. - */ - public final POIXMLDocumentPart createRelationship(POIXMLRelation descriptor, POIXMLFactory factory, int idx){ - return createRelationship(descriptor, factory, idx, false).getDocumentPart(); - } - - /** - * Identifies the next available part number for a part of the given type, - * if possible, otherwise -1 if none are available. - * The found (valid) index can then be safely given to - * {@link #createRelationship(POIXMLRelation, POIXMLFactory, int)} or - * {@link #createRelationship(POIXMLRelation, POIXMLFactory, int, boolean)} - * without naming clashes. - * If parts with other types are already claiming a name for this relationship - * type (eg a {@link XSSFRelation#CHART} using the drawing part namespace - * normally used by {@link XSSFRelation#DRAWINGS}), those will be considered - * when finding the next spare number. - * - * @param descriptor The relationship type to find the part number for - * @param minIdx The minimum free index to assign, use -1 for any - * @return The next free part number, or -1 if none available - */ - protected final int getNextPartNumber(POIXMLRelation descriptor, int minIdx) { - OPCPackage pkg = packagePart.getPackage(); - - try { - String name = descriptor.getDefaultFileName(); - if (name.equals(descriptor.getFileName(9999))) { - // Non-index based, check if default is free - PackagePartName ppName = PackagingURIHelper.createPartName(name); - if (pkg.containPart(ppName)) { - // Default name already taken, not index based, nothing free - return -1; - } else { - // Default name free - return 0; - } - } - - // Default to searching from 1, unless they asked for 0+ - int idx = (minIdx < 0) ? 1 : minIdx; - int maxIdx = minIdx + pkg.getParts().size(); - while (idx <= maxIdx) { - name = descriptor.getFileName(idx); - PackagePartName ppName = PackagingURIHelper.createPartName(name); - if (!pkg.containPart(ppName)) { - return idx; - } - idx++; - } - } catch (InvalidFormatException e) { - // Give a general wrapped exception for the problem - throw new POIXMLException(e); - } - return -1; - } - - /** - * Create a new child POIXMLDocumentPart - * - * @param descriptor the part descriptor - * @param factory the factory that will create an instance of the requested relation - * @param idx part number - * @param noRelation if true, then no relationship is added. - * @return the created child POIXMLDocumentPart - * @throws PartAlreadyExistsException - * If rule M1.12 is not verified : Packages shall not contain - * equivalent part names and package implementers shall neither - * create nor recognize packages with equivalent part names. - */ - protected final RelationPart createRelationship(POIXMLRelation descriptor, POIXMLFactory factory, int idx, boolean noRelation){ - try { - PackagePartName ppName = PackagingURIHelper.createPartName(descriptor.getFileName(idx)); - PackageRelationship rel = null; - PackagePart part = packagePart.getPackage().createPart(ppName, descriptor.getContentType()); - if(!noRelation) { - /* only add to relations, if according relationship is being created. */ - rel = packagePart.addRelationship(ppName, TargetMode.INTERNAL, descriptor.getRelation()); - } - POIXMLDocumentPart doc = factory.newDocumentPart(descriptor); - doc.packagePart = part; - doc.parent = this; - if (!noRelation) { - /* only add to relations, if according relationship is being created. */ - addRelation(rel,doc); - } - - return new RelationPart(rel,doc); - } catch (PartAlreadyExistsException pae) { - // Return the specific exception so the user knows - // that the name is already taken - throw pae; - } catch (Exception e){ - // Give a general wrapped exception for the problem - throw new POIXMLException(e); - } - } - - /** - * Iterate through the underlying PackagePart and create child POIXMLFactory instances - * using the specified factory - * - * @param factory the factory object that creates POIXMLFactory instances - * @param context context map containing already visited noted keyed by targetURI - * - * @throws OpenXML4JException thrown when a related part can't be read - */ - protected void read(POIXMLFactory factory, Map context) throws OpenXML4JException { - PackagePart pp = getPackagePart(); - // add mapping a second time, in case of initial caller hasn't done so - POIXMLDocumentPart otherChild = context.put(pp, this); - if (otherChild != null && otherChild != this) { - throw new POIXMLException("Unique PackagePart-POIXMLDocumentPart relation broken!"); - } - - if (!pp.hasRelationships()) return; - - PackageRelationshipCollection rels = packagePart.getRelationships(); - List readLater = new ArrayList(); - - // scan breadth-first, so parent-relations are hopefully the shallowest element - for (PackageRelationship rel : rels) { - if(rel.getTargetMode() == TargetMode.INTERNAL){ - URI uri = rel.getTargetURI(); - - // check for internal references (e.g. '#Sheet1!A1') - PackagePartName relName; - if(uri.getRawFragment() != null) { - relName = PackagingURIHelper.createPartName(uri.getPath()); - } else { - relName = PackagingURIHelper.createPartName(uri); - } - - final PackagePart p = packagePart.getPackage().getPart(relName); - if (p == null) { - logger.log(POILogger.ERROR, "Skipped invalid entry " + rel.getTargetURI()); - continue; - } - - POIXMLDocumentPart childPart = context.get(p); - if (childPart == null) { - childPart = factory.createDocumentPart(this, p); - childPart.parent = this; - // already add child to context, so other children can reference it - context.put(p, childPart); - readLater.add(childPart); - } - - addRelation(rel,childPart); - } - } - - for (POIXMLDocumentPart childPart : readLater) { - childPart.read(factory, context); - } - } - - /** - * Get the PackagePart that is the target of a relationship from this Part. - * - * @param rel The relationship - * @return The target part - * @throws InvalidFormatException thrown if the related part has is erroneous - */ - protected PackagePart getTargetPart(PackageRelationship rel) throws InvalidFormatException { - return getPackagePart().getRelatedPart(rel); - } - - - /** - * Fired when a new package part is created - * - * @throws IOException a subclass may throw an IOException on document creation - */ - protected void onDocumentCreate() throws IOException { - - } - - /** - * Fired when a package part is read - * - * @throws IOException a subclass may throw an IOException when a document is read - */ - protected void onDocumentRead() throws IOException { - - } - - /** - * Fired when a package part is about to be removed from the package - * - * @throws IOException a subclass may throw an IOException when a document is removed - */ - protected void onDocumentRemove() throws IOException { - - } - - /** - * Internal method, do not use! - *

    - * This method only exists to allow access to protected {@link POIXMLDocumentPart#onDocumentRead()} - * from {@link org.apache.poi.xwpf.usermodel.XWPFDocument} without reflection. It should be removed. - * - * @param part the part which is to be read - * - * @throws IOException if the part can't be read - */ - @Internal @Deprecated - public static void _invokeOnDocumentRead(POIXMLDocumentPart part) throws IOException { - part.onDocumentRead(); - } - - /** - * Retrieves the core document part - * - * @since POI 3.14-Beta1 - */ - private static PackagePart getPartFromOPCPackage(OPCPackage pkg, String coreDocumentRel) { - PackageRelationship coreRel = pkg.getRelationshipsByType(coreDocumentRel).getRelationship(0); - - if (coreRel != null) { - PackagePart pp = pkg.getPart(coreRel); - if (pp == null) { - throw new POIXMLException("OOXML file structure broken/invalid - core document '"+coreRel.getTargetURI()+"' not found."); - } - return pp; - } - - coreRel = pkg.getRelationshipsByType(PackageRelationshipTypes.STRICT_CORE_DOCUMENT).getRelationship(0); - if (coreRel != null) { - throw new POIXMLException("Strict OOXML isn't currently supported, please see bug #57699"); - } - - throw new POIXMLException("OOXML file structure broken/invalid - no core document found!"); - } -} diff --git a/src/ooxml/java/org/apache/poi/POIXMLException.java b/src/ooxml/java/org/apache/poi/POIXMLException.java deleted file mode 100644 index 82832ecff..000000000 --- a/src/ooxml/java/org/apache/poi/POIXMLException.java +++ /dev/null @@ -1,70 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi; - -/** - * Indicates a generic OOXML error. - * - * @author Yegor Kozlov - */ -@SuppressWarnings("serial") -public final class POIXMLException extends RuntimeException{ - /** - * Create a new POIXMLException with no - * detail mesage. - */ - public POIXMLException() { - super(); - } - - /** - * Create a new POIXMLException with - * the String specified as an error message. - * - * @param msg The error message for the exception. - */ - public POIXMLException(String msg) { - super(msg); - } - - /** - * Create a new POIXMLException with - * the String specified as an error message and the cause. - * - * @param msg The error message for the exception. - * @param cause the cause (which is saved for later retrieval by the - * {@link #getCause()} method). (A null value is - * permitted, and indicates that the cause is nonexistent or - * unknown.) - */ - public POIXMLException(String msg, Throwable cause) { - super(msg, cause); - } - - /** - * Create a new POIXMLException with - * the specified cause. - * - * @param cause the cause (which is saved for later retrieval by the - * {@link #getCause()} method). (A null value is - * permitted, and indicates that the cause is nonexistent or - * unknown.) - */ - public POIXMLException(Throwable cause) { - super(cause); - } -} diff --git a/src/ooxml/java/org/apache/poi/POIXMLFactory.java b/src/ooxml/java/org/apache/poi/POIXMLFactory.java deleted file mode 100644 index eefa59187..000000000 --- a/src/ooxml/java/org/apache/poi/POIXMLFactory.java +++ /dev/null @@ -1,139 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi; - -import java.lang.reflect.InvocationTargetException; - -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.opc.PackageRelationship; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; - -/** - * Defines a factory API that enables sub-classes to create instances of POIXMLDocumentPart - */ -public abstract class POIXMLFactory { - private static final POILogger LOGGER = POILogFactory.getLogger(POIXMLFactory.class); - - private static final Class[] PARENT_PART = {POIXMLDocumentPart.class, PackagePart.class}; - private static final Class[] ORPHAN_PART = {PackagePart.class}; - - /** - * Create a POIXMLDocumentPart from existing package part and relation. This method is called - * from {@link POIXMLDocument#load(POIXMLFactory)} when parsing a document - * - * @param parent parent part - * @param part the PackagePart representing the created instance - * @return A new instance of a POIXMLDocumentPart. - * - * @since by POI 3.14-Beta1 - */ - public POIXMLDocumentPart createDocumentPart(POIXMLDocumentPart parent, PackagePart part) { - PackageRelationship rel = getPackageRelationship(parent, part); - POIXMLRelation descriptor = getDescriptor(rel.getRelationshipType()); - - if (descriptor == null || descriptor.getRelationClass() == null) { - LOGGER.log(POILogger.DEBUG, "using default POIXMLDocumentPart for " + rel.getRelationshipType()); - return new POIXMLDocumentPart(parent, part); - } - - Class cls = descriptor.getRelationClass(); - try { - try { - return createDocumentPart(cls, PARENT_PART, new Object[]{parent, part}); - } catch (NoSuchMethodException e) { - return createDocumentPart(cls, ORPHAN_PART, new Object[]{part}); - } - } catch (Exception e) { - throw new POIXMLException(e); - } - } - - /** - * Need to delegate instantiation to sub class because of constructor visibility - * - * @param cls the document class to be instantiated - * @param classes the classes of the constructor arguments - * @param values the values of the constructor arguments - * @return the new document / part - * @throws SecurityException thrown if the object can't be instantiated - * @throws NoSuchMethodException thrown if there is no constructor found for the given arguments - * @throws InstantiationException thrown if the object can't be instantiated - * @throws IllegalAccessException thrown if the object can't be instantiated - * @throws InvocationTargetException thrown if the object can't be instantiated - * - * @since POI 3.14-Beta1 - */ - protected abstract POIXMLDocumentPart createDocumentPart - (Class cls, Class[] classes, Object[] values) - throws SecurityException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException; - - /** - * returns the descriptor for the given relationship type - * - * @param relationshipType the relationship type of the descriptor - * @return the descriptor or null if type is unknown - * - * @since POI 3.14-Beta1 - */ - protected abstract POIXMLRelation getDescriptor(String relationshipType); - - /** - * Create a new POIXMLDocumentPart using the supplied descriptor. This method is used when adding new parts - * to a document, for example, when adding a sheet to a workbook, slide to a presentation, etc. - * - * @param descriptor describes the object to create - * @return A new instance of a POIXMLDocumentPart. - */ - public POIXMLDocumentPart newDocumentPart(POIXMLRelation descriptor) { - Class cls = descriptor.getRelationClass(); - try { - return createDocumentPart(cls, null, null); - } catch (Exception e) { - throw new POIXMLException(e); - } - } - - /** - * Retrieves the package relationship of the child part within the parent - * - * @param parent the parent to search for the part - * @param part the part to look for - * - * @return the relationship - * - * @throws POIXMLException if the relations are erroneous or the part is not related - * - * @since POI 3.14-Beta1 - */ - protected PackageRelationship getPackageRelationship(POIXMLDocumentPart parent, PackagePart part) { - try { - String partName = part.getPartName().getName(); - for (PackageRelationship pr : parent.getPackagePart().getRelationships()) { - String packName = pr.getTargetURI().toASCIIString(); - if (packName.equalsIgnoreCase(partName)) { - return pr; - } - } - } catch (InvalidFormatException e) { - throw new POIXMLException("error while determining package relations", e); - } - - throw new POIXMLException("package part isn't a child of the parent document."); - } -} diff --git a/src/ooxml/java/org/apache/poi/POIXMLProperties.java b/src/ooxml/java/org/apache/poi/POIXMLProperties.java deleted file mode 100644 index b956b7ee5..000000000 --- a/src/ooxml/java/org/apache/poi/POIXMLProperties.java +++ /dev/null @@ -1,611 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi; - -import static org.apache.poi.POIXMLTypeLoader.DEFAULT_XML_OPTIONS; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.Date; - -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.exceptions.OpenXML4JException; -import org.apache.poi.openxml4j.opc.ContentTypes; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.opc.PackagePartName; -import org.apache.poi.openxml4j.opc.PackageRelationshipCollection; -import org.apache.poi.openxml4j.opc.PackageRelationshipTypes; -import org.apache.poi.openxml4j.opc.PackagingURIHelper; -import org.apache.poi.openxml4j.opc.StreamHelper; -import org.apache.poi.openxml4j.opc.TargetMode; -import org.apache.poi.openxml4j.opc.internal.PackagePropertiesPart; -import org.apache.poi.openxml4j.util.Nullable; -import org.apache.xmlbeans.XmlException; -import org.openxmlformats.schemas.officeDocument.x2006.customProperties.CTProperty; - -/** - * Wrapper around the three different kinds of OOXML properties - * and metadata a document can have (Core, Extended and Custom), - * as well Thumbnails. - */ -public class POIXMLProperties { - private OPCPackage pkg; - private CoreProperties core; - private ExtendedProperties ext; - private CustomProperties cust; - - private PackagePart extPart; - private PackagePart custPart; - - - private static final org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.PropertiesDocument NEW_EXT_INSTANCE; - private static final org.openxmlformats.schemas.officeDocument.x2006.customProperties.PropertiesDocument NEW_CUST_INSTANCE; - static { - NEW_EXT_INSTANCE = org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.PropertiesDocument.Factory.newInstance(); - NEW_EXT_INSTANCE.addNewProperties(); - - NEW_CUST_INSTANCE = org.openxmlformats.schemas.officeDocument.x2006.customProperties.PropertiesDocument.Factory.newInstance(); - NEW_CUST_INSTANCE.addNewProperties(); - } - - public POIXMLProperties(OPCPackage docPackage) throws IOException, OpenXML4JException, XmlException { - this.pkg = docPackage; - - // Core properties - core = new CoreProperties((PackagePropertiesPart)pkg.getPackageProperties() ); - - // Extended properties - PackageRelationshipCollection extRel = - pkg.getRelationshipsByType(PackageRelationshipTypes.EXTENDED_PROPERTIES); - if(extRel.size() == 1) { - extPart = pkg.getPart( extRel.getRelationship(0)); - org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.PropertiesDocument props = org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.PropertiesDocument.Factory.parse( - extPart.getInputStream(), DEFAULT_XML_OPTIONS - ); - ext = new ExtendedProperties(props); - } else { - extPart = null; - ext = new ExtendedProperties((org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.PropertiesDocument)NEW_EXT_INSTANCE.copy()); - } - - // Custom properties - PackageRelationshipCollection custRel = - pkg.getRelationshipsByType(PackageRelationshipTypes.CUSTOM_PROPERTIES); - if(custRel.size() == 1) { - custPart = pkg.getPart( custRel.getRelationship(0)); - org.openxmlformats.schemas.officeDocument.x2006.customProperties.PropertiesDocument props = org.openxmlformats.schemas.officeDocument.x2006.customProperties.PropertiesDocument.Factory.parse( - custPart.getInputStream(), DEFAULT_XML_OPTIONS - ); - cust = new CustomProperties(props); - } else { - custPart = null; - cust = new CustomProperties((org.openxmlformats.schemas.officeDocument.x2006.customProperties.PropertiesDocument)NEW_CUST_INSTANCE.copy()); - } - } - - /** - * Returns the core document properties - * - * @return the core document properties - */ - public CoreProperties getCoreProperties() { - return core; - } - - /** - * Returns the extended document properties - * - * @return the extended document properties - */ - public ExtendedProperties getExtendedProperties() { - return ext; - } - - /** - * Returns the custom document properties - * - * @return the custom document properties - */ - public CustomProperties getCustomProperties() { - return cust; - } - - /** - * Returns the {@link PackagePart} for the Document - * Thumbnail, or null if there isn't one - * - * @return The Document Thumbnail part or null - */ - protected PackagePart getThumbnailPart() { - PackageRelationshipCollection rels = - pkg.getRelationshipsByType(PackageRelationshipTypes.THUMBNAIL); - if(rels.size() == 1) { - return pkg.getPart(rels.getRelationship(0)); - } - return null; - } - /** - * Returns the name of the Document thumbnail, eg - * thumbnail.jpeg, or null if there - * isn't one. - * - * @return The thumbnail filename, or null - */ - public String getThumbnailFilename() { - PackagePart tPart = getThumbnailPart(); - if (tPart == null) return null; - String name = tPart.getPartName().getName(); - return name.substring(name.lastIndexOf('/')); - } - /** - * Returns the Document thumbnail image data, or {@code null} if there isn't one. - * - * @return The thumbnail data, or null - * - * @throws IOException if the thumbnail can't be read - */ - public InputStream getThumbnailImage() throws IOException { - PackagePart tPart = getThumbnailPart(); - if (tPart == null) return null; - return tPart.getInputStream(); - } - - /** - * Sets the Thumbnail for the document, replacing any existing one. - * - * @param filename The filename for the thumbnail image, eg {@code thumbnail.jpg} - * @param imageData The inputstream to read the thumbnail image from - * - * @throws IOException if the thumbnail can't be written - */ - public void setThumbnail(String filename, InputStream imageData) throws IOException { - PackagePart tPart = getThumbnailPart(); - if (tPart == null) { - // New thumbnail - pkg.addThumbnail(filename, imageData); - } else { - // Change existing - String newType = ContentTypes.getContentTypeFromFileExtension(filename); - if (! newType.equals(tPart.getContentType())) { - throw new IllegalArgumentException("Can't set a Thumbnail of type " + - newType + " when existing one is of a different type " + - tPart.getContentType()); - } - StreamHelper.copyStream(imageData, tPart.getOutputStream()); - } - } - - /** - * Commit changes to the underlying OPC package - * - * @throws IOException if the properties can't be saved - * @throws POIXMLException if the properties are erroneous - */ - public void commit() throws IOException{ - - if(extPart == null && !NEW_EXT_INSTANCE.toString().equals(ext.props.toString())){ - try { - PackagePartName prtname = PackagingURIHelper.createPartName("/docProps/app.xml"); - pkg.addRelationship(prtname, TargetMode.INTERNAL, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties"); - extPart = pkg.createPart(prtname, "application/vnd.openxmlformats-officedocument.extended-properties+xml"); - } catch (InvalidFormatException e){ - throw new POIXMLException(e); - } - } - if(custPart == null && !NEW_CUST_INSTANCE.toString().equals(cust.props.toString())){ - try { - PackagePartName prtname = PackagingURIHelper.createPartName("/docProps/custom.xml"); - pkg.addRelationship(prtname, TargetMode.INTERNAL, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties"); - custPart = pkg.createPart(prtname, "application/vnd.openxmlformats-officedocument.custom-properties+xml"); - } catch (InvalidFormatException e){ - throw new POIXMLException(e); - } - } - if(extPart != null){ - OutputStream out = extPart.getOutputStream(); - if (extPart.getSize() > 0) { - extPart.clear(); - } - ext.props.save(out, DEFAULT_XML_OPTIONS); - out.close(); - } - if(custPart != null){ - OutputStream out = custPart.getOutputStream(); - cust.props.save(out, DEFAULT_XML_OPTIONS); - out.close(); - } - } - - /** - * The core document properties - */ - public static class CoreProperties { - private PackagePropertiesPart part; - private CoreProperties(PackagePropertiesPart part) { - this.part = part; - } - - public String getCategory() { - return part.getCategoryProperty().getValue(); - } - public void setCategory(String category) { - part.setCategoryProperty(category); - } - public String getContentStatus() { - return part.getContentStatusProperty().getValue(); - } - public void setContentStatus(String contentStatus) { - part.setContentStatusProperty(contentStatus); - } - public String getContentType() { - return part.getContentTypeProperty().getValue(); - } - public void setContentType(String contentType) { - part.setContentTypeProperty(contentType); - } - public Date getCreated() { - return part.getCreatedProperty().getValue(); - } - public void setCreated(Nullable date) { - part.setCreatedProperty(date); - } - public void setCreated(String date) { - part.setCreatedProperty(date); - } - public String getCreator() { - return part.getCreatorProperty().getValue(); - } - public void setCreator(String creator) { - part.setCreatorProperty(creator); - } - public String getDescription() { - return part.getDescriptionProperty().getValue(); - } - public void setDescription(String description) { - part.setDescriptionProperty(description); - } - public String getIdentifier() { - return part.getIdentifierProperty().getValue(); - } - public void setIdentifier(String identifier) { - part.setIdentifierProperty(identifier); - } - public String getKeywords() { - return part.getKeywordsProperty().getValue(); - } - public void setKeywords(String keywords) { - part.setKeywordsProperty(keywords); - } - public Date getLastPrinted() { - return part.getLastPrintedProperty().getValue(); - } - public void setLastPrinted(Nullable date) { - part.setLastPrintedProperty(date); - } - public void setLastPrinted(String date) { - part.setLastPrintedProperty(date); - } - /** @since POI 3.15 beta 3 */ - public String getLastModifiedByUser() { - return part.getLastModifiedByProperty().getValue(); - } - /** @since POI 3.15 beta 3 */ - public void setLastModifiedByUser(String user) { - part.setLastModifiedByProperty(user); - } - public Date getModified() { - return part.getModifiedProperty().getValue(); - } - public void setModified(Nullable date) { - part.setModifiedProperty(date); - } - public void setModified(String date) { - part.setModifiedProperty(date); - } - public String getSubject() { - return part.getSubjectProperty().getValue(); - } - public void setSubjectProperty(String subject) { - part.setSubjectProperty(subject); - } - public void setTitle(String title) { - part.setTitleProperty(title); - } - public String getTitle() { - return part.getTitleProperty().getValue(); - } - public String getRevision() { - return part.getRevisionProperty().getValue(); - } - public void setRevision(String revision) { - try { - Long.valueOf(revision); - part.setRevisionProperty(revision); - } - catch (NumberFormatException e) {} - } - - public PackagePropertiesPart getUnderlyingProperties() { - return part; - } - } - - /** - * Extended document properties - */ - public static class ExtendedProperties { - private org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.PropertiesDocument props; - private ExtendedProperties(org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.PropertiesDocument props) { - this.props = props; - } - - public org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.CTProperties getUnderlyingProperties() { - return props.getProperties(); - } - - public String getTemplate() { - if (props.getProperties().isSetTemplate()) { - return props.getProperties().getTemplate(); - } - return null; - } - public String getManager() { - if (props.getProperties().isSetManager()) { - return props.getProperties().getManager(); - } - return null; - } - public String getCompany() { - if (props.getProperties().isSetCompany()) { - return props.getProperties().getCompany(); - } - return null; - } - public String getPresentationFormat() { - if (props.getProperties().isSetPresentationFormat()) { - return props.getProperties().getPresentationFormat(); - } - return null; - } - public String getApplication() { - if (props.getProperties().isSetApplication()) { - return props.getProperties().getApplication(); - } - return null; - } - public String getAppVersion() { - if (props.getProperties().isSetAppVersion()) { - return props.getProperties().getAppVersion(); - } - return null; - } - - public int getPages() { - if (props.getProperties().isSetPages()) { - return props.getProperties().getPages(); - } - return -1; - } - public int getWords() { - if (props.getProperties().isSetWords()) { - return props.getProperties().getWords(); - } - return -1; - } - public int getCharacters() { - if (props.getProperties().isSetCharacters()) { - return props.getProperties().getCharacters(); - } - return -1; - } - public int getCharactersWithSpaces() { - if (props.getProperties().isSetCharactersWithSpaces()) { - return props.getProperties().getCharactersWithSpaces(); - } - return -1; - } - public int getLines() { - if (props.getProperties().isSetLines()) { - return props.getProperties().getLines(); - } - return -1; - } - public int getParagraphs() { - if (props.getProperties().isSetParagraphs()) { - return props.getProperties().getParagraphs(); - } - return -1; - } - public int getSlides() { - if (props.getProperties().isSetSlides()) { - return props.getProperties().getSlides(); - } - return -1; - } - public int getNotes() { - if (props.getProperties().isSetNotes()) { - return props.getProperties().getNotes(); - } - return -1; - } - public int getTotalTime() { - if (props.getProperties().isSetTotalTime()) { - return props.getProperties().getTotalTime(); - } - return -1; - } - public int getHiddenSlides() { - if (props.getProperties().isSetHiddenSlides()) { - return props.getProperties().getHiddenSlides(); - } - return -1; - } - public int getMMClips() { - if (props.getProperties().isSetMMClips()) { - return props.getProperties().getMMClips(); - } - return -1; - } - - public String getHyperlinkBase() { - if (props.getProperties().isSetHyperlinkBase()) { - return props.getProperties().getHyperlinkBase(); - } - return null; - } - } - - /** - * Custom document properties - */ - public static class CustomProperties { - /** - * Each custom property element contains an fmtid attribute - * with the same GUID value ({D5CDD505-2E9C-101B-9397-08002B2CF9AE}). - */ - public static final String FORMAT_ID = "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}"; - - private org.openxmlformats.schemas.officeDocument.x2006.customProperties.PropertiesDocument props; - private CustomProperties(org.openxmlformats.schemas.officeDocument.x2006.customProperties.PropertiesDocument props) { - this.props = props; - } - - public org.openxmlformats.schemas.officeDocument.x2006.customProperties.CTProperties getUnderlyingProperties() { - return props.getProperties(); - } - - /** - * Add a new property - * - * @param name the property name - * @throws IllegalArgumentException if a property with this name already exists - */ - private CTProperty add(String name) { - if(contains(name)) { - throw new IllegalArgumentException("A property with this name " + - "already exists in the custom properties"); - } - - CTProperty p = props.getProperties().addNewProperty(); - int pid = nextPid(); - p.setPid(pid); - p.setFmtid(FORMAT_ID); - p.setName(name); - return p; - } - - /** - * Add a new string property - * - * @param name the property name - * @param value the property value - * - * @throws IllegalArgumentException if a property with this name already exists - */ - public void addProperty(String name, String value){ - CTProperty p = add(name); - p.setLpwstr(value); - } - - /** - * Add a new double property - * - * @param name the property name - * @param value the property value - * - * @throws IllegalArgumentException if a property with this name already exists - */ - public void addProperty(String name, double value){ - CTProperty p = add(name); - p.setR8(value); - } - - /** - * Add a new integer property - * - * @param name the property name - * @param value the property value - * - * @throws IllegalArgumentException if a property with this name already exists - */ - public void addProperty(String name, int value){ - CTProperty p = add(name); - p.setI4(value); - } - - /** - * Add a new boolean property - * - * @param name the property name - * @param value the property value - * - * @throws IllegalArgumentException if a property with this name already exists - */ - public void addProperty(String name, boolean value){ - CTProperty p = add(name); - p.setBool(value); - } - - /** - * Generate next id that uniquely relates a custom property - * - * @return next property id starting with 2 - */ - protected int nextPid() { - int propid = 1; - for(CTProperty p : props.getProperties().getPropertyArray()){ - if(p.getPid() > propid) propid = p.getPid(); - } - return propid + 1; - } - - /** - * Check if a property with this name already exists in the collection of custom properties - * - * @param name the name to check - * @return whether a property with the given name exists in the custom properties - */ - public boolean contains(String name) { - for(CTProperty p : props.getProperties().getPropertyArray()){ - if(p.getName().equals(name)) return true; - } - return false; - } - - /** - * Retrieve the custom property with this name, or null if none exists. - * - * You will need to test the various isSetX methods to work out - * what the type of the property is, before fetching the - * appropriate value for it. - * - * @param name the name of the property to fetch - * - * @return the custom property with this name, or null if none exists - */ - public CTProperty getProperty(String name) { - for(CTProperty p : props.getProperties().getPropertyArray()){ - if(p.getName().equals(name)) { - return p; - } - } - return null; - } - } -} diff --git a/src/ooxml/java/org/apache/poi/POIXMLPropertiesTextExtractor.java b/src/ooxml/java/org/apache/poi/POIXMLPropertiesTextExtractor.java deleted file mode 100644 index b2621ebd1..000000000 --- a/src/ooxml/java/org/apache/poi/POIXMLPropertiesTextExtractor.java +++ /dev/null @@ -1,279 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi; - -import java.math.BigDecimal; -import java.text.DateFormat; -import java.text.DateFormatSymbols; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Locale; - -import org.apache.poi.openxml4j.opc.internal.PackagePropertiesPart; -import org.apache.poi.util.LocaleUtil; -import org.openxmlformats.schemas.officeDocument.x2006.customProperties.CTProperty; - -/** - * A {@link POITextExtractor} for returning the textual - * content of the OOXML file properties, eg author - * and title. - */ -public class POIXMLPropertiesTextExtractor extends POIXMLTextExtractor { - - private final DateFormat dateFormat; - - /** - * Creates a new POIXMLPropertiesTextExtractor for the given open document. - * - * @param doc the given open document - */ - public POIXMLPropertiesTextExtractor(POIXMLDocument doc) { - super(doc); - DateFormatSymbols dfs = DateFormatSymbols.getInstance(Locale.ROOT); - dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", dfs); - dateFormat.setTimeZone(LocaleUtil.TIMEZONE_UTC); - } - - /** - * Creates a new POIXMLPropertiesTextExtractor, for the - * same file that another TextExtractor is already - * working on. - * - * @param otherExtractor the extractor referencing the given file - */ - public POIXMLPropertiesTextExtractor(POIXMLTextExtractor otherExtractor) { - this(otherExtractor.getDocument()); - } - - private void appendIfPresent(StringBuffer text, String thing, boolean value) { - appendIfPresent(text, thing, Boolean.toString(value)); - } - private void appendIfPresent(StringBuffer text, String thing, int value) { - appendIfPresent(text, thing, Integer.toString(value)); - } - private void appendIfPresent(StringBuffer text, String thing, Date value) { - if(value == null) { return; } - appendIfPresent(text, thing, dateFormat.format(value)); - } - private void appendIfPresent(StringBuffer text, String thing, String value) { - if(value == null) { return; } - text.append(thing); - text.append(" = "); - text.append(value); - text.append("\n"); - } - - /** - * Returns the core document properties, eg author - * - * @return the core document properties - */ - @SuppressWarnings("resource") - public String getCorePropertiesText() { - POIXMLDocument document = getDocument(); - if(document == null) { // event based extractor does not have a document - return ""; - } - - StringBuffer text = new StringBuffer(); - PackagePropertiesPart props = - document.getProperties().getCoreProperties().getUnderlyingProperties(); - - appendIfPresent(text, "Category", props.getCategoryProperty().getValue()); - appendIfPresent(text, "Category", props.getCategoryProperty().getValue()); - appendIfPresent(text, "ContentStatus", props.getContentStatusProperty().getValue()); - appendIfPresent(text, "ContentType", props.getContentTypeProperty().getValue()); - appendIfPresent(text, "Created", props.getCreatedProperty().getValue()); - appendIfPresent(text, "CreatedString", props.getCreatedPropertyString()); - appendIfPresent(text, "Creator", props.getCreatorProperty().getValue()); - appendIfPresent(text, "Description", props.getDescriptionProperty().getValue()); - appendIfPresent(text, "Identifier", props.getIdentifierProperty().getValue()); - appendIfPresent(text, "Keywords", props.getKeywordsProperty().getValue()); - appendIfPresent(text, "Language", props.getLanguageProperty().getValue()); - appendIfPresent(text, "LastModifiedBy", props.getLastModifiedByProperty().getValue()); - appendIfPresent(text, "LastPrinted", props.getLastPrintedProperty().getValue()); - appendIfPresent(text, "LastPrintedString", props.getLastPrintedPropertyString()); - appendIfPresent(text, "Modified", props.getModifiedProperty().getValue()); - appendIfPresent(text, "ModifiedString", props.getModifiedPropertyString()); - appendIfPresent(text, "Revision", props.getRevisionProperty().getValue()); - appendIfPresent(text, "Subject", props.getSubjectProperty().getValue()); - appendIfPresent(text, "Title", props.getTitleProperty().getValue()); - appendIfPresent(text, "Version", props.getVersionProperty().getValue()); - - return text.toString(); - } - /** - * Returns the extended document properties, eg application - * - * @return the extended document properties - */ - @SuppressWarnings("resource") - public String getExtendedPropertiesText() { - POIXMLDocument document = getDocument(); - if(document == null) { // event based extractor does not have a document - return ""; - } - - StringBuffer text = new StringBuffer(); - org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.CTProperties - props = document.getProperties().getExtendedProperties().getUnderlyingProperties(); - - appendIfPresent(text, "Application", props.getApplication()); - appendIfPresent(text, "AppVersion", props.getAppVersion()); - appendIfPresent(text, "Characters", props.getCharacters()); - appendIfPresent(text, "CharactersWithSpaces", props.getCharactersWithSpaces()); - appendIfPresent(text, "Company", props.getCompany()); - appendIfPresent(text, "HyperlinkBase", props.getHyperlinkBase()); - appendIfPresent(text, "HyperlinksChanged", props.getHyperlinksChanged()); - appendIfPresent(text, "Lines", props.getLines()); - appendIfPresent(text, "LinksUpToDate", props.getLinksUpToDate()); - appendIfPresent(text, "Manager", props.getManager()); - appendIfPresent(text, "Pages", props.getPages()); - appendIfPresent(text, "Paragraphs", props.getParagraphs()); - appendIfPresent(text, "PresentationFormat", props.getPresentationFormat()); - appendIfPresent(text, "Template", props.getTemplate()); - appendIfPresent(text, "TotalTime", props.getTotalTime()); - - return text.toString(); - } - /** - * Returns the custom document properties, if there are any - * - * @return the custom document properties - */ - @SuppressWarnings({ "resource" }) - public String getCustomPropertiesText() { - POIXMLDocument document = getDocument(); - if(document == null) { // event based extractor does not have a document - return ""; - } - - StringBuilder text = new StringBuilder(); - org.openxmlformats.schemas.officeDocument.x2006.customProperties.CTProperties - props = document.getProperties().getCustomProperties().getUnderlyingProperties(); - - for(CTProperty property : props.getPropertyArray()) { - String val = "(not implemented!)"; - - if (property.isSetLpwstr()) { - val = property.getLpwstr(); - } - else if (property.isSetLpstr()) { - val = property.getLpstr(); - } - else if (property.isSetDate()) { - val = property.getDate().toString(); - } - else if (property.isSetFiletime()) { - val = property.getFiletime().toString(); - } - else if (property.isSetBool()) { - val = Boolean.toString( property.getBool() ); - } - - // Integers - else if (property.isSetI1()) { - val = Integer.toString(property.getI1()); - } - else if (property.isSetI2()) { - val = Integer.toString(property.getI2()); - } - else if (property.isSetI4()) { - val = Integer.toString(property.getI4()); - } - else if (property.isSetI8()) { - val = Long.toString(property.getI8()); - } - else if (property.isSetInt()) { - val = Integer.toString( property.getInt() ); - } - - // Unsigned Integers - else if (property.isSetUi1()) { - val = Integer.toString(property.getUi1()); - } - else if (property.isSetUi2()) { - val = Integer.toString(property.getUi2()); - } - else if (property.isSetUi4()) { - val = Long.toString(property.getUi4()); - } - else if (property.isSetUi8()) { - val = property.getUi8().toString(); - } - else if (property.isSetUint()) { - val = Long.toString(property.getUint()); - } - - // Reals - else if (property.isSetR4()) { - val = Float.toString( property.getR4() ); - } - else if (property.isSetR8()) { - val = Double.toString( property.getR8() ); - } - else if (property.isSetDecimal()) { - BigDecimal d = property.getDecimal(); - if (d == null) { - val = null; - } else { - val = d.toPlainString(); - } - } - - /*else if (property.isSetArray()) { - // TODO Fetch the array values and output - } - else if (property.isSetVector()) { - // TODO Fetch the vector values and output - } - - else if (property.isSetBlob() || property.isSetOblob()) { - // TODO Decode, if possible - } - else if (property.isSetStream() || property.isSetOstream() || - property.isSetVstream()) { - // TODO Decode, if possible - } - else if (property.isSetStorage() || property.isSetOstorage()) { - // TODO Decode, if possible - }*/ - - text.append(property.getName()).append(" = ").append(val).append("\n"); - } - - return text.toString(); - } - - @Override - public String getText() { - try { - return - getCorePropertiesText() + - getExtendedPropertiesText() + - getCustomPropertiesText(); - } catch(Exception e) { - throw new RuntimeException(e); - } - } - - @Override - public POIXMLPropertiesTextExtractor getMetadataTextExtractor() { - throw new IllegalStateException("You already have the Metadata Text Extractor, not recursing!"); - } -} diff --git a/src/ooxml/java/org/apache/poi/POIXMLRelation.java b/src/ooxml/java/org/apache/poi/POIXMLRelation.java deleted file mode 100644 index 571ae5ab7..000000000 --- a/src/ooxml/java/org/apache/poi/POIXMLRelation.java +++ /dev/null @@ -1,170 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Iterator; - -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.opc.PackagePartName; -import org.apache.poi.openxml4j.opc.PackageRelationship; -import org.apache.poi.openxml4j.opc.PackageRelationshipCollection; -import org.apache.poi.openxml4j.opc.PackagingURIHelper; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; - -/** - * Represents a descriptor of a OOXML relation. - */ -public abstract class POIXMLRelation { - - private static final POILogger log = POILogFactory.getLogger(POIXMLRelation.class); - - /** - * Describes the content stored in a part. - */ - private String _type; - - /** - * The kind of connection between a source part and a target part in a package. - */ - private String _relation; - - /** - * The path component of a pack URI. - */ - private String _defaultName; - - /** - * Defines what object is used to construct instances of this relationship - */ - private Class _cls; - - /** - * Instantiates a POIXMLRelation. - * - * @param type content type - * @param rel relationship - * @param defaultName default item name - * @param cls defines what object is used to construct instances of this relationship - */ - public POIXMLRelation(String type, String rel, String defaultName, Class cls) { - _type = type; - _relation = rel; - _defaultName = defaultName; - _cls = cls; - } - - /** - * Instantiates a POIXMLRelation. - * - * @param type content type - * @param rel relationship - * @param defaultName default item name - */ - public POIXMLRelation(String type, String rel, String defaultName) { - this(type, rel, defaultName, null); - } - /** - * Return the content type. Content types define a media type, a subtype, and an - * optional set of parameters, as defined in RFC 2616. - * - * @return the content type - */ - public String getContentType() { - return _type; - } - - /** - * Return the relationship, the kind of connection between a source part and a target part in a package. - * Relationships make the connections between parts directly discoverable without looking at the content - * in the parts, and without altering the parts themselves. - * - * @return the relationship - */ - public String getRelation() { - return _relation; - } - - /** - * Return the default part name. Part names are used to refer to a part in the context of a - * package, typically as part of a URI. - * - * @return the default part name - */ - public String getDefaultFileName() { - return _defaultName; - } - - /** - * Returns the filename for the nth one of these, e.g. /xl/comments4.xml - * - * @param index the suffix for the document type - * @return the filename including the suffix - */ - public String getFileName(int index) { - if(_defaultName.indexOf("#") == -1) { - // Generic filename in all cases - return getDefaultFileName(); - } - return _defaultName.replace("#", Integer.toString(index)); - } - - /** - * Returns the index of the filename within the package for the given part. - * e.g. 4 for /xl/comments4.xml - * - * @param part the part to read the suffix from - * @return the suffix - */ - public Integer getFileNameIndex(POIXMLDocumentPart part) { - String regex = _defaultName.replace("#", "(\\d+)"); - return Integer.valueOf(part.getPackagePart().getPartName().getName().replaceAll(regex, "$1")); - } - - /** - * Return type of the object used to construct instances of this relationship - * - * @return the class of the object used to construct instances of this relation - */ - public Class getRelationClass(){ - return _cls; - } - - /** - * Fetches the InputStream to read the contents, based - * of the specified core part, for which we are defined - * as a suitable relationship - * - * @since 3.16-beta3 - */ - public InputStream getContents(PackagePart corePart) throws IOException, InvalidFormatException { - PackageRelationshipCollection prc = - corePart.getRelationshipsByType(getRelation()); - Iterator it = prc.iterator(); - if(it.hasNext()) { - PackageRelationship rel = it.next(); - PackagePartName relName = PackagingURIHelper.createPartName(rel.getTargetURI()); - PackagePart part = corePart.getPackage().getPart(relName); - return part.getInputStream(); - } - log.log(POILogger.WARN, "No part " + getDefaultFileName() + " found"); - return null; - } -} diff --git a/src/ooxml/java/org/apache/poi/POIXMLTextExtractor.java b/src/ooxml/java/org/apache/poi/POIXMLTextExtractor.java deleted file mode 100644 index 954feb80e..000000000 --- a/src/ooxml/java/org/apache/poi/POIXMLTextExtractor.java +++ /dev/null @@ -1,120 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi; - -import java.io.IOException; - -import org.apache.poi.POIXMLProperties.CoreProperties; -import org.apache.poi.POIXMLProperties.CustomProperties; -import org.apache.poi.POIXMLProperties.ExtendedProperties; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.util.ZipSecureFile; - -public abstract class POIXMLTextExtractor extends POITextExtractor { - /** The POIXMLDocument that's open */ - private final POIXMLDocument _document; - - /** - * Creates a new text extractor for the given document - * - * @param document the document to extract from - */ - public POIXMLTextExtractor(POIXMLDocument document) { - _document = document; - } - - /** - * Returns the core document properties - * - * @return the core document properties - */ - public CoreProperties getCoreProperties() { - return _document.getProperties().getCoreProperties(); - } - /** - * Returns the extended document properties - * - * @return the extended document properties - */ - public ExtendedProperties getExtendedProperties() { - return _document.getProperties().getExtendedProperties(); - } - /** - * Returns the custom document properties - * - * @return the custom document properties - */ - public CustomProperties getCustomProperties() { - return _document.getProperties().getCustomProperties(); - } - - /** - * Returns opened document - * - * @return the opened document - */ - public final POIXMLDocument getDocument() { - return _document; - } - - /** - * Returns the opened OPCPackage that contains the document - * - * @return the opened OPCPackage - */ - public OPCPackage getPackage() { - return _document.getPackage(); - } - - /** - * Returns an OOXML properties text extractor for the - * document properties metadata, such as title and author. - */ - @Override - public POIXMLPropertiesTextExtractor getMetadataTextExtractor() { - return new POIXMLPropertiesTextExtractor(_document); - } - - @Override - public void close() throws IOException { - // e.g. XSSFEventBaseExcelExtractor passes a null-document - if(_document != null) { - @SuppressWarnings("resource") - OPCPackage pkg = _document.getPackage(); - if(pkg != null) { - // revert the package to not re-write the file, which is very likely not wanted for a TextExtractor! - pkg.revert(); - } - } - super.close(); - } - - protected void checkMaxTextSize(StringBuffer text, String string) { - if(string == null) { - return; - } - - int size = text.length() + string.length(); - if(size > ZipSecureFile.getMaxTextSize()) { - throw new IllegalStateException("The text would exceed the max allowed overall size of extracted text. " - + "By default this is prevented as some documents may exhaust available memory and it may indicate that the file is used to inflate memory usage and thus could pose a security risk. " - + "You can adjust this limit via ZipSecureFile.setMaxTextSize() if you need to work with files which have a lot of text. " - + "Size: " + size + ", limit: MAX_TEXT_SIZE: " + ZipSecureFile.getMaxTextSize()); - } - } -} diff --git a/src/ooxml/java/org/apache/poi/POIXMLTypeLoader.java b/src/ooxml/java/org/apache/poi/POIXMLTypeLoader.java deleted file mode 100644 index f11b2d88b..000000000 --- a/src/ooxml/java/org/apache/poi/POIXMLTypeLoader.java +++ /dev/null @@ -1,174 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.Reader; -import java.io.StringReader; -import java.lang.ref.WeakReference; -import java.net.URL; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -import javax.xml.stream.XMLStreamReader; - -import org.apache.poi.util.DocumentHelper; -import org.apache.xmlbeans.SchemaType; -import org.apache.xmlbeans.SchemaTypeLoader; -import org.apache.xmlbeans.XmlBeans; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlOptions; -import org.apache.xmlbeans.xml.stream.XMLInputStream; -import org.apache.xmlbeans.xml.stream.XMLStreamException; -import org.w3c.dom.Document; -import org.w3c.dom.Node; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; - -@SuppressWarnings("deprecation") -public class POIXMLTypeLoader { - - private static ThreadLocal classLoader = new ThreadLocal(); - - public static final XmlOptions DEFAULT_XML_OPTIONS; - static { - DEFAULT_XML_OPTIONS = new XmlOptions(); - DEFAULT_XML_OPTIONS.setSaveOuter(); - DEFAULT_XML_OPTIONS.setUseDefaultNamespace(); - DEFAULT_XML_OPTIONS.setSaveAggressiveNamespaces(); - DEFAULT_XML_OPTIONS.setCharacterEncoding("UTF-8"); - // Piccolo is disabled for POI builts, i.e. JAXP is used for parsing - // so only user code using XmlObject/XmlToken.Factory.parse - // directly can bypass the entity check, which is probably unlikely (... and not within our responsibility :)) - // DEFAULT_XML_OPTIONS.setLoadEntityBytesLimit(4096); - - Map map = new HashMap(); - map.put("http://schemas.openxmlformats.org/drawingml/2006/main", "a"); - map.put("http://schemas.openxmlformats.org/drawingml/2006/chart", "c"); - map.put("http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing", "wp"); - map.put("http://schemas.openxmlformats.org/markup-compatibility/2006", "ve"); - map.put("http://schemas.openxmlformats.org/officeDocument/2006/math", "m"); - map.put("http://schemas.openxmlformats.org/officeDocument/2006/relationships", "r"); - map.put("http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes", "vt"); - map.put("http://schemas.openxmlformats.org/presentationml/2006/main", "p"); - map.put("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w"); - map.put("http://schemas.microsoft.com/office/word/2006/wordml", "wne"); - map.put("urn:schemas-microsoft-com:office:office", "o"); - map.put("urn:schemas-microsoft-com:office:excel", "x"); - map.put("urn:schemas-microsoft-com:office:word", "w10"); - map.put("urn:schemas-microsoft-com:vml", "v"); - DEFAULT_XML_OPTIONS.setSaveSuggestedPrefixes(Collections.unmodifiableMap(map)); - } - - private static XmlOptions getXmlOptions(XmlOptions options) { - return options == null ? DEFAULT_XML_OPTIONS : options; - } - - /** - * Sets the {@link ClassLoader} which is used, when XmlBeans are dynamically instantiated - - * opposed to being loaded by the factory class which is accompanied by each generated XmlBeans interface. - *

    - * This is especially necessary in a context which doesn't guarantee that the current (thread) context - * cassloader has access to all XmlBeans schema definitions (*.xsb) - which is typically in OSGI the case. - *

    - * The classloader will be only set for the current thread in a {@link ThreadLocal}. Although the - * ThreadLocal is implemented via a {@link WeakReference}, it's good style to {@code null} the classloader - * when the user code is finalized. - * - * @param cl the classloader to be used when XmlBeans classes and definitions are looked up - */ - public static void setClassLoader(ClassLoader cl) { - classLoader.set(cl); - } - - private static SchemaTypeLoader getTypeLoader() { - ClassLoader cl = classLoader.get(); - return (cl == null) - ? XmlBeans.getContextTypeLoader() - : XmlBeans.typeLoaderForClassLoader(cl); - } - - public static XmlObject newInstance(SchemaType type, XmlOptions options) { - return getTypeLoader().newInstance(type, getXmlOptions(options)); - } - - public static XmlObject parse(String xmlText, SchemaType type, XmlOptions options) throws XmlException { - try { - return parse(new StringReader(xmlText), type, options); - } catch (IOException e) { - throw new XmlException("Unable to parse xml bean", e); - } - } - - public static XmlObject parse(File file, SchemaType type, XmlOptions options) throws XmlException, IOException { - InputStream is = new FileInputStream(file); - try { - return parse(is, type, options); - } finally { - is.close(); - } - } - - public static XmlObject parse(URL file, SchemaType type, XmlOptions options) throws XmlException, IOException { - InputStream is = file.openStream(); - try { - return parse(is, type, options); - } finally { - is.close(); - } - } - - public static XmlObject parse(InputStream jiois, SchemaType type, XmlOptions options) throws XmlException, IOException { - try { - Document doc = DocumentHelper.readDocument(jiois); - return getTypeLoader().parse(doc.getDocumentElement(), type, getXmlOptions(options)); - } catch (SAXException e) { - throw new IOException("Unable to parse xml bean", e); - } - } - - public static XmlObject parse(XMLStreamReader xsr, SchemaType type, XmlOptions options) throws XmlException { - return getTypeLoader().parse(xsr, type, getXmlOptions(options)); - } - - public static XmlObject parse(Reader jior, SchemaType type, XmlOptions options) throws XmlException, IOException { - try { - Document doc = DocumentHelper.readDocument(new InputSource(jior)); - return getTypeLoader().parse(doc.getDocumentElement(), type, getXmlOptions(options)); - } catch (SAXException e) { - throw new XmlException("Unable to parse xml bean", e); - } - } - - public static XmlObject parse(Node node, SchemaType type, XmlOptions options) throws XmlException { - return getTypeLoader().parse(node, type, getXmlOptions(options)); - } - - public static XmlObject parse(XMLInputStream xis, SchemaType type, XmlOptions options) throws XmlException, XMLStreamException { - return getTypeLoader().parse(xis, type, getXmlOptions(options)); - } - - public static XMLInputStream newValidatingXMLInputStream ( XMLInputStream xis, SchemaType type, XmlOptions options ) throws XmlException, XMLStreamException { - return getTypeLoader().newValidatingXMLInputStream(xis, type, getXmlOptions(options)); - } -} diff --git a/src/ooxml/java/org/apache/poi/dev/OOXMLLister.java b/src/ooxml/java/org/apache/poi/dev/OOXMLLister.java deleted file mode 100644 index b82d92136..000000000 --- a/src/ooxml/java/org/apache/poi/dev/OOXMLLister.java +++ /dev/null @@ -1,152 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.dev; - -import java.io.*; -import java.util.ArrayList; - -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackageAccess; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.opc.PackageRelationship; -import org.apache.poi.openxml4j.opc.PackageRelationshipCollection; - -/** - * Prints out the contents of a OOXML container. - * Useful for seeing what parts are defined, and how - * they're all related to each other. - */ -public class OOXMLLister implements Closeable { - private final OPCPackage container; - private final PrintStream disp; - - public OOXMLLister(OPCPackage container) { - this(container, System.out); - } - public OOXMLLister(OPCPackage container, PrintStream disp) { - this.container = container; - this.disp = disp; - } - - /** - * Figures out how big a given PackagePart is. - * - * @param part the PackagePart - * @return the size of the PackagePart - * - * @throws IOException if the part can't be read - */ - public static long getSize(PackagePart part) throws IOException { - InputStream in = part.getInputStream(); - try { - byte[] b = new byte[8192]; - long size = 0; - int read = 0; - - while(read > -1) { - read = in.read(b); - if(read > 0) { - size += read; - } - } - - return size; - } finally { - in.close(); - } - } - - /** - * Displays information on all the different - * parts of the OOXML file container. - * @throws InvalidFormatException if the package relations are invalid - * @throws IOException if the package can't be read - */ - public void displayParts() throws InvalidFormatException, IOException { - ArrayList parts = container.getParts(); - for (PackagePart part : parts) { - disp.println(part.getPartName()); - disp.println("\t" + part.getContentType()); - - if(! part.getPartName().toString().equals("/docProps/core.xml")) { - disp.println("\t" + getSize(part) + " bytes"); - } - - if(! part.isRelationshipPart()) { - disp.println("\t" + part.getRelationships().size() + " relations"); - for(PackageRelationship rel : part.getRelationships()) { - displayRelation(rel, "\t "); - } - } - } - } - /** - * Displays information on all the different - * relationships between different parts - * of the OOXML file container. - */ - public void displayRelations() { - PackageRelationshipCollection rels = - container.getRelationships(); - for (PackageRelationship rel : rels) { - displayRelation(rel, ""); - } - } - - private void displayRelation(PackageRelationship rel, String indent) { - disp.println(indent+"Relationship:"); - disp.println(indent+"\tFrom: "+ rel.getSourceURI()); - disp.println(indent+"\tTo: " + rel.getTargetURI()); - disp.println(indent+"\tID: " + rel.getId()); - disp.println(indent+"\tMode: " + rel.getTargetMode()); - disp.println(indent+"\tType: " + rel.getRelationshipType()); - } - - @Override - public void close() throws IOException { - container.close(); - } - - public static void main(String[] args) throws IOException, InvalidFormatException { - if(args.length == 0) { - System.err.println("Use:"); - System.err.println("\tjava OOXMLLister "); - System.exit(1); - } - - File f = new File(args[0]); - if(! f.exists()) { - System.err.println("Error, file not found!"); - System.err.println("\t" + f.toString()); - System.exit(2); - } - - OOXMLLister lister = new OOXMLLister( - OPCPackage.open(f.toString(), PackageAccess.READ) - ); - - try { - lister.disp.println(f.toString() + "\n"); - lister.displayParts(); - lister.disp.println(); - lister.displayRelations(); - } finally { - lister.close(); - } - } -} diff --git a/src/ooxml/java/org/apache/poi/dev/OOXMLPrettyPrint.java b/src/ooxml/java/org/apache/poi/dev/OOXMLPrettyPrint.java deleted file mode 100644 index 7d80b7ac2..000000000 --- a/src/ooxml/java/org/apache/poi/dev/OOXMLPrettyPrint.java +++ /dev/null @@ -1,143 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.dev; - -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.util.Enumeration; -import java.util.zip.ZipEntry; -import java.util.zip.ZipException; -import java.util.zip.ZipFile; -import java.util.zip.ZipOutputStream; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Result; -import javax.xml.transform.Source; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; - -import org.apache.poi.openxml4j.opc.internal.ZipHelper; -import org.apache.poi.openxml4j.util.ZipSecureFile; -import org.apache.poi.util.IOUtils; -import org.w3c.dom.Document; -import org.xml.sax.InputSource; - -/** - * Reads a zipped OOXML file and produces a copy with the included - * pretty-printed XML files. - * - * This is useful for comparing OOXML files produced by different tools as the often - * use different formatting of the XML. - */ -public class OOXMLPrettyPrint { - private final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); - private final DocumentBuilder documentBuilder; - - public OOXMLPrettyPrint() throws ParserConfigurationException { - // allow files with much lower inflation rate here as there is no risk of Zip Bomb attacks in this developer tool - ZipSecureFile.setMinInflateRatio(0.00001); - - documentBuilder = documentBuilderFactory.newDocumentBuilder(); - } - - public static void main(String[] args) throws Exception { - if(args.length <= 1 || args.length % 2 != 0) { - System.err.println("Use:"); - System.err.println("\tjava OOXMLPrettyPrint [ ] ..."); - System.exit(1); - } - - for(int i = 0;i < args.length;i+=2) { - File f = new File(args[i]); - if(! f.exists()) { - System.err.println("Error, file not found!"); - System.err.println("\t" + f.toString()); - System.exit(2); - } - - handleFile(f, new File(args[i+1])); - } - System.out.println("Done."); - } - - private static void handleFile(File file, File outFile) throws ZipException, - IOException, TransformerException, ParserConfigurationException { - System.out.println("Reading zip-file " + file + " and writing pretty-printed XML to " + outFile); - - ZipFile zipFile = ZipHelper.openZipFile(file); - try { - ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); - try { - new OOXMLPrettyPrint().handle(zipFile, out); - } finally { - out.close(); - } - } finally { - zipFile.close(); - - System.out.println(); - } - } - - private void handle(ZipFile file, ZipOutputStream out) throws IOException, TransformerException { - Enumeration entries = file.entries(); - while(entries.hasMoreElements()) { - ZipEntry entry = entries.nextElement(); - - String name = entry.getName(); - out.putNextEntry(new ZipEntry(name)); - try { - if(name.endsWith(".xml") || name.endsWith(".rels")) { - Document document = documentBuilder.parse(new InputSource(file.getInputStream(entry))); - document.setXmlStandalone(true); - pretty(document, out, 2); - } else { - System.out.println("Not pretty-printing non-XML file " + name); - IOUtils.copy(file.getInputStream(entry), out); - } - } catch (Exception e) { - throw new IOException("While handling entry " + name, e); - } finally { - out.closeEntry(); - } - System.out.print("."); - } - } - - private static void pretty(Document document, OutputStream outputStream, int indent) throws TransformerException { - TransformerFactory transformerFactory = TransformerFactory.newInstance(); - Transformer transformer = transformerFactory.newTransformer(); - transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); - if (indent > 0) { - // set properties to indent the resulting XML nicely - transformer.setOutputProperty(OutputKeys.INDENT, "yes"); - transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", Integer.toString(indent)); - } - Result result = new StreamResult(outputStream); - Source source = new DOMSource(document); - transformer.transform(source, result); - } -} diff --git a/src/ooxml/java/org/apache/poi/extractor/CommandLineTextExtractor.java b/src/ooxml/java/org/apache/poi/extractor/CommandLineTextExtractor.java deleted file mode 100644 index 264daa028..000000000 --- a/src/ooxml/java/org/apache/poi/extractor/CommandLineTextExtractor.java +++ /dev/null @@ -1,62 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.extractor; - -import java.io.File; - -import org.apache.poi.POITextExtractor; - -/** - * A command line wrapper around {@link ExtractorFactory}, useful - * for when debugging. - */ -public class CommandLineTextExtractor { - public static final String DIVIDER = "======================="; - - public static void main(String[] args) throws Exception { - if(args.length < 1) { - System.err.println("Use:"); - System.err.println(" CommandLineTextExtractor [filename] [filename]"); - System.exit(1); - } - - for (String arg : args) { - System.out.println(DIVIDER); - - File f = new File(arg); - System.out.println(f); - - POITextExtractor extractor = - ExtractorFactory.createExtractor(f); - try { - POITextExtractor metadataExtractor = - extractor.getMetadataTextExtractor(); - - System.out.println(" " + DIVIDER); - String metaData = metadataExtractor.getText(); - System.out.println(metaData); - System.out.println(" " + DIVIDER); - String text = extractor.getText(); - System.out.println(text); - System.out.println(DIVIDER); - System.out.println("Had " + metaData.length() + " characters of metadata and " + text.length() + " characters of text"); - } finally { - extractor.close(); - } - } - } -} diff --git a/src/ooxml/java/org/apache/poi/extractor/ExtractorFactory.java b/src/ooxml/java/org/apache/poi/extractor/ExtractorFactory.java deleted file mode 100644 index faae5bacb..000000000 --- a/src/ooxml/java/org/apache/poi/extractor/ExtractorFactory.java +++ /dev/null @@ -1,400 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.extractor; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.PushbackInputStream; -import java.util.ArrayList; -import java.util.Iterator; - -import org.apache.poi.POIOLE2TextExtractor; -import org.apache.poi.POITextExtractor; -import org.apache.poi.POIXMLTextExtractor; -import org.apache.poi.hsmf.MAPIMessage; -import org.apache.poi.hsmf.datatypes.AttachmentChunks; -import org.apache.poi.hsmf.extractor.OutlookTextExtactor; -import org.apache.poi.hssf.extractor.ExcelExtractor; -import org.apache.poi.hwpf.extractor.WordExtractor; -import org.apache.poi.openxml4j.exceptions.OpenXML4JException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackageAccess; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.opc.PackageRelationshipCollection; -import org.apache.poi.openxml4j.opc.PackageRelationshipTypes; -import org.apache.poi.poifs.filesystem.DirectoryEntry; -import org.apache.poi.poifs.filesystem.DirectoryNode; -import org.apache.poi.poifs.filesystem.DocumentFactoryHelper; -import org.apache.poi.poifs.filesystem.Entry; -import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; -import org.apache.poi.poifs.filesystem.NotOLE2FileException; -import org.apache.poi.poifs.filesystem.OPOIFSFileSystem; -import org.apache.poi.poifs.filesystem.OfficeXmlFileException; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.NotImplemented; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.xdgf.extractor.XDGFVisioExtractor; -import org.apache.poi.xslf.extractor.XSLFPowerPointExtractor; -import org.apache.poi.xslf.usermodel.XSLFRelation; -import org.apache.poi.xslf.usermodel.XSLFSlideShow; -import org.apache.poi.xssf.extractor.XSSFBEventBasedExcelExtractor; -import org.apache.poi.xssf.extractor.XSSFEventBasedExcelExtractor; -import org.apache.poi.xssf.extractor.XSSFExcelExtractor; -import org.apache.poi.xssf.usermodel.XSSFRelation; -import org.apache.poi.xwpf.extractor.XWPFWordExtractor; -import org.apache.poi.xwpf.usermodel.XWPFRelation; -import org.apache.xmlbeans.XmlException; - -/** - * Figures out the correct POITextExtractor for your supplied - * document, and returns it. - * - *

    Note 1 - will fail for many file formats if the POI Scratchpad jar is - * not present on the runtime classpath

    - *

    Note 2 - rather than using this, for most cases you would be better - * off switching to Apache Tika instead!

    - */ -@SuppressWarnings("WeakerAccess") -public class ExtractorFactory { - private static final POILogger logger = POILogFactory.getLogger(ExtractorFactory.class); - - public static final String CORE_DOCUMENT_REL = PackageRelationshipTypes.CORE_DOCUMENT; - protected static final String VISIO_DOCUMENT_REL = PackageRelationshipTypes.VISIO_CORE_DOCUMENT; - protected static final String STRICT_DOCUMENT_REL = PackageRelationshipTypes.STRICT_CORE_DOCUMENT; - - /** - * Should this thread prefer event based over usermodel based extractors? - * (usermodel extractors tend to be more accurate, but use more memory) - * Default is false. - */ - public static boolean getThreadPrefersEventExtractors() { - return OLE2ExtractorFactory.getThreadPrefersEventExtractors(); - } - - /** - * Should all threads prefer event based over usermodel based extractors? - * (usermodel extractors tend to be more accurate, but use more memory) - * Default is to use the thread level setting, which defaults to false. - */ - public static Boolean getAllThreadsPreferEventExtractors() { - return OLE2ExtractorFactory.getAllThreadsPreferEventExtractors(); - } - - /** - * Should this thread prefer event based over usermodel based extractors? - * Will only be used if the All Threads setting is null. - */ - public static void setThreadPrefersEventExtractors(boolean preferEventExtractors) { - OLE2ExtractorFactory.setThreadPrefersEventExtractors(preferEventExtractors); - } - - /** - * Should all threads prefer event based over usermodel based extractors? - * If set, will take preference over the Thread level setting. - */ - public static void setAllThreadsPreferEventExtractors(Boolean preferEventExtractors) { - OLE2ExtractorFactory.setAllThreadsPreferEventExtractors(preferEventExtractors); - } - - /** - * Should this thread use event based extractors is available? - * Checks the all-threads one first, then thread specific. - */ - protected static boolean getPreferEventExtractor() { - return OLE2ExtractorFactory.getPreferEventExtractor(); - } - - public static POITextExtractor createExtractor(File f) throws IOException, OpenXML4JException, XmlException { - NPOIFSFileSystem fs = null; - try { - fs = new NPOIFSFileSystem(f); - POIOLE2TextExtractor extractor = createExtractor(fs); - extractor.setFilesystem(fs); - return extractor; - - } catch (OfficeXmlFileException e) { - // ensure file-handle release - IOUtils.closeQuietly(fs); - return createExtractor(OPCPackage.open(f.toString(), PackageAccess.READ)); - - } catch (NotOLE2FileException ne) { - // ensure file-handle release - IOUtils.closeQuietly(fs); - throw new IllegalArgumentException("Your File was neither an OLE2 file, nor an OOXML file"); - - } catch (OpenXML4JException e) { - // ensure file-handle release - IOUtils.closeQuietly(fs); - throw e; - - } catch (XmlException e) { - // ensure file-handle release - IOUtils.closeQuietly(fs); - throw e; - - } catch (IOException e) { - // ensure file-handle release - IOUtils.closeQuietly(fs); - throw e; - - } catch (RuntimeException e) { - // ensure file-handle release - IOUtils.closeQuietly(fs); - throw e; - } - } - - public static POITextExtractor createExtractor(InputStream inp) throws IOException, OpenXML4JException, XmlException { - // Figure out the kind of stream - // If clearly doesn't do mark/reset, wrap up - if (! inp.markSupported()) { - inp = new PushbackInputStream(inp, 8); - } - - if (NPOIFSFileSystem.hasPOIFSHeader(inp)) { - return createExtractor(new NPOIFSFileSystem(inp)); - } - if (DocumentFactoryHelper.hasOOXMLHeader(inp)) { - return createExtractor(OPCPackage.open(inp)); - } - throw new IllegalArgumentException("Your InputStream was neither an OLE2 stream, nor an OOXML stream"); - } - - /** - * Tries to determine the actual type of file and produces a matching text-extractor for it. - * - * @param pkg An {@link OPCPackage}. - * @return A {@link POIXMLTextExtractor} for the given file. - * @throws IOException If an error occurs while reading the file - * @throws OpenXML4JException If an error parsing the OpenXML file format is found. - * @throws XmlException If an XML parsing error occurs. - * @throws IllegalArgumentException If no matching file type could be found. - */ - public static POIXMLTextExtractor createExtractor(OPCPackage pkg) throws IOException, OpenXML4JException, XmlException { - try { - // Check for the normal Office core document - PackageRelationshipCollection core; - core = pkg.getRelationshipsByType(CORE_DOCUMENT_REL); - - // If nothing was found, try some of the other OOXML-based core types - if (core.size() == 0) { - // Could it be an OOXML-Strict one? - core = pkg.getRelationshipsByType(STRICT_DOCUMENT_REL); - } - if (core.size() == 0) { - // Could it be a visio one? - core = pkg.getRelationshipsByType(VISIO_DOCUMENT_REL); - if (core.size() == 1) - return new XDGFVisioExtractor(pkg); - } - - // Should just be a single core document, complain if not - if (core.size() != 1) { - throw new IllegalArgumentException("Invalid OOXML Package received - expected 1 core document, found " + core.size()); - } - - // Grab the core document part, and try to identify from that - final PackagePart corePart = pkg.getPart(core.getRelationship(0)); - final String contentType = corePart.getContentType(); - - // Is it XSSF? - for (XSSFRelation rel : XSSFExcelExtractor.SUPPORTED_TYPES) { - if ( rel.getContentType().equals( contentType ) ) { - if (getPreferEventExtractor()) { - return new XSSFEventBasedExcelExtractor(pkg); - } - return new XSSFExcelExtractor(pkg); - } - } - - // Is it XWPF? - for (XWPFRelation rel : XWPFWordExtractor.SUPPORTED_TYPES) { - if ( rel.getContentType().equals( contentType ) ) { - return new XWPFWordExtractor(pkg); - } - } - - // Is it XSLF? - for (XSLFRelation rel : XSLFPowerPointExtractor.SUPPORTED_TYPES) { - if ( rel.getContentType().equals( contentType ) ) { - return new XSLFPowerPointExtractor(pkg); - } - } - - // special handling for SlideShow-Theme-files, - if (XSLFRelation.THEME_MANAGER.getContentType().equals(contentType)) { - return new XSLFPowerPointExtractor(new XSLFSlideShow(pkg)); - } - - // How about xlsb? - for (XSSFRelation rel : XSSFBEventBasedExcelExtractor.SUPPORTED_TYPES) { - if (rel.getContentType().equals(contentType)) { - return new XSSFBEventBasedExcelExtractor(pkg); - } - } - - throw new IllegalArgumentException("No supported documents found in the OOXML package (found "+contentType+")"); - - } catch (IOException e) { - // ensure that we close the package again if there is an error opening it, however - // we need to revert the package to not re-write the file via close(), which is very likely not wanted for a TextExtractor! - pkg.revert(); - throw e; - } catch (OpenXML4JException e) { - // ensure that we close the package again if there is an error opening it, however - // we need to revert the package to not re-write the file via close(), which is very likely not wanted for a TextExtractor! - pkg.revert(); - throw e; - } catch (XmlException e) { - // ensure that we close the package again if there is an error opening it, however - // we need to revert the package to not re-write the file via close(), which is very likely not wanted for a TextExtractor! - pkg.revert(); - throw e; - } catch (RuntimeException e) { - // ensure that we close the package again if there is an error opening it, however - // we need to revert the package to not re-write the file via close(), which is very likely not wanted for a TextExtractor! - pkg.revert(); - throw e; - } - } - - public static POIOLE2TextExtractor createExtractor(POIFSFileSystem fs) throws IOException, OpenXML4JException, XmlException { - return OLE2ExtractorFactory.createExtractor(fs); - } - public static POIOLE2TextExtractor createExtractor(NPOIFSFileSystem fs) throws IOException, OpenXML4JException, XmlException { - return OLE2ExtractorFactory.createExtractor(fs); - } - public static POIOLE2TextExtractor createExtractor(OPOIFSFileSystem fs) throws IOException, OpenXML4JException, XmlException { - return OLE2ExtractorFactory.createExtractor(fs); - } - - public static POITextExtractor createExtractor(DirectoryNode poifsDir) throws IOException, OpenXML4JException, XmlException - { - // First, check for OOXML - for (String entryName : poifsDir.getEntryNames()) { - if (entryName.equals("Package")) { - OPCPackage pkg = OPCPackage.open(poifsDir.createDocumentInputStream("Package")); - return createExtractor(pkg); - } - } - - // If not, ask the OLE2 code to check, with Scratchpad if possible - return OLE2ExtractorFactory.createExtractor(poifsDir); - } - - /** - * Returns an array of text extractors, one for each of - * the embedded documents in the file (if there are any). - * If there are no embedded documents, you'll get back an - * empty array. Otherwise, you'll get one open - * {@link POITextExtractor} for each embedded file. - */ - public static POITextExtractor[] getEmbededDocsTextExtractors(POIOLE2TextExtractor ext) throws IOException, OpenXML4JException, XmlException { - // All the embedded directories we spotted - ArrayList dirs = new ArrayList(); - // For anything else not directly held in as a POIFS directory - ArrayList nonPOIFS = new ArrayList(); - - // Find all the embedded directories - DirectoryEntry root = ext.getRoot(); - if (root == null) { - throw new IllegalStateException("The extractor didn't know which POIFS it came from!"); - } - - if (ext instanceof ExcelExtractor) { - // These are in MBD... under the root - Iterator it = root.getEntries(); - while (it.hasNext()) { - Entry entry = it.next(); - if (entry.getName().startsWith("MBD")) { - dirs.add(entry); - } - } - } else if (ext instanceof WordExtractor) { - // These are in ObjectPool -> _... under the root - try { - DirectoryEntry op = (DirectoryEntry) root.getEntry("ObjectPool"); - Iterator it = op.getEntries(); - while (it.hasNext()) { - Entry entry = it.next(); - if (entry.getName().startsWith("_")) { - dirs.add(entry); - } - } - } catch (FileNotFoundException e) { - logger.log(POILogger.INFO, "Ignoring FileNotFoundException while extracting Word document", e.getLocalizedMessage()); - // ignored here - } - //} else if(ext instanceof PowerPointExtractor) { - // Tricky, not stored directly in poifs - // TODO - } else if (ext instanceof OutlookTextExtactor) { - // Stored in the Attachment blocks - MAPIMessage msg = ((OutlookTextExtactor)ext).getMAPIMessage(); - for (AttachmentChunks attachment : msg.getAttachmentFiles()) { - if (attachment.getAttachData() != null) { - byte[] data = attachment.getAttachData().getValue(); - nonPOIFS.add( new ByteArrayInputStream(data) ); - } else if (attachment.getAttachmentDirectory() != null) { - dirs.add(attachment.getAttachmentDirectory().getDirectory()); - } - } - } - - // Create the extractors - if (dirs.size() == 0 && nonPOIFS.size() == 0){ - return new POITextExtractor[0]; - } - - ArrayList textExtractors = new ArrayList(); - for (Entry dir : dirs) { - textExtractors.add(createExtractor((DirectoryNode) dir)); - } - for (InputStream nonPOIF : nonPOIFS) { - try { - textExtractors.add(createExtractor(nonPOIF)); - } catch (IllegalArgumentException e) { - // Ignore, just means it didn't contain - // a format we support as yet - logger.log(POILogger.INFO, "Format not supported yet", e.getLocalizedMessage()); - } catch (XmlException e) { - throw new IOException(e.getMessage(), e); - } catch (OpenXML4JException e) { - throw new IOException(e.getMessage(), e); - } - } - return textExtractors.toArray(new POITextExtractor[textExtractors.size()]); - } - - /** - * Returns an array of text extractors, one for each of - * the embedded documents in the file (if there are any). - * If there are no embedded documents, you'll get back an - * empty array. Otherwise, you'll get one open - * {@link POITextExtractor} for each embedded file. - */ - @NotImplemented - @SuppressWarnings("UnusedParameters") - public static POITextExtractor[] getEmbededDocsTextExtractors(POIXMLTextExtractor ext) { - throw new IllegalStateException("Not yet supported"); - } -} diff --git a/src/ooxml/java/org/apache/poi/openxml4j/exceptions/InvalidFormatException.java b/src/ooxml/java/org/apache/poi/openxml4j/exceptions/InvalidFormatException.java deleted file mode 100644 index 832d47623..000000000 --- a/src/ooxml/java/org/apache/poi/openxml4j/exceptions/InvalidFormatException.java +++ /dev/null @@ -1,30 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.exceptions; - -@SuppressWarnings("serial") -public final class InvalidFormatException extends OpenXML4JException{ - - public InvalidFormatException(String message){ - super(message); - } - - public InvalidFormatException(String message, Throwable cause){ - super(message,cause); - } -} diff --git a/src/ooxml/java/org/apache/poi/openxml4j/exceptions/InvalidOperationException.java b/src/ooxml/java/org/apache/poi/openxml4j/exceptions/InvalidOperationException.java deleted file mode 100644 index 7a8338ed8..000000000 --- a/src/ooxml/java/org/apache/poi/openxml4j/exceptions/InvalidOperationException.java +++ /dev/null @@ -1,32 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.exceptions; - -/** - * Throw when an invalid operation is done. - */ -@SuppressWarnings("serial") -public class InvalidOperationException extends OpenXML4JRuntimeException{ - public InvalidOperationException(String message){ - super(message); - } - - public InvalidOperationException(String message, Throwable reason){ - super(message, reason); - } -} diff --git a/src/ooxml/java/org/apache/poi/openxml4j/exceptions/NotOfficeXmlFileException.java b/src/ooxml/java/org/apache/poi/openxml4j/exceptions/NotOfficeXmlFileException.java deleted file mode 100644 index 901967e20..000000000 --- a/src/ooxml/java/org/apache/poi/openxml4j/exceptions/NotOfficeXmlFileException.java +++ /dev/null @@ -1,29 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.openxml4j.exceptions; - -import org.apache.poi.UnsupportedFileFormatException; - -/** - * This exception is thrown when we try to open a file that doesn't - * seem to actually be an OOXML (Office Open XML) file after all - */ -public class NotOfficeXmlFileException extends UnsupportedFileFormatException { - public NotOfficeXmlFileException(String message) { - super(message); - } -} diff --git a/src/ooxml/java/org/apache/poi/openxml4j/exceptions/ODFNotOfficeXmlFileException.java b/src/ooxml/java/org/apache/poi/openxml4j/exceptions/ODFNotOfficeXmlFileException.java deleted file mode 100644 index 61d8c8cd9..000000000 --- a/src/ooxml/java/org/apache/poi/openxml4j/exceptions/ODFNotOfficeXmlFileException.java +++ /dev/null @@ -1,27 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.openxml4j.exceptions; - -/** - * This exception is thrown when we are given an ODF-based file - * (eg OpenOffice .ods) instead of an actually OOXML (Office Open XML) file - */ -public class ODFNotOfficeXmlFileException extends NotOfficeXmlFileException { - public ODFNotOfficeXmlFileException(String message) { - super(message); - } -} diff --git a/src/ooxml/java/org/apache/poi/openxml4j/exceptions/OLE2NotOfficeXmlFileException.java b/src/ooxml/java/org/apache/poi/openxml4j/exceptions/OLE2NotOfficeXmlFileException.java deleted file mode 100644 index 2f82d1100..000000000 --- a/src/ooxml/java/org/apache/poi/openxml4j/exceptions/OLE2NotOfficeXmlFileException.java +++ /dev/null @@ -1,27 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.openxml4j.exceptions; - -/** - * This exception is thrown when we are given an OLE2-based file - * (eg Excel .xls) instead of an actually OOXML (Office Open XML) file - */ -public class OLE2NotOfficeXmlFileException extends NotOfficeXmlFileException { - public OLE2NotOfficeXmlFileException(String message) { - super(message); - } -} diff --git a/src/ooxml/java/org/apache/poi/openxml4j/exceptions/OpenXML4JException.java b/src/ooxml/java/org/apache/poi/openxml4j/exceptions/OpenXML4JException.java deleted file mode 100644 index 4c7430df5..000000000 --- a/src/ooxml/java/org/apache/poi/openxml4j/exceptions/OpenXML4JException.java +++ /dev/null @@ -1,35 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.exceptions; - -/** - * Global exception throws when a critical error occurs. (this exception is not - * set as Runtime in order to force user to manage the exception in a - * try/catch). - */ -@SuppressWarnings("serial") -public class OpenXML4JException extends Exception { - - public OpenXML4JException(String msg) { - super(msg); - } - - public OpenXML4JException(String msg, Throwable cause) { - super(msg, cause); - } -} diff --git a/src/ooxml/java/org/apache/poi/openxml4j/exceptions/OpenXML4JRuntimeException.java b/src/ooxml/java/org/apache/poi/openxml4j/exceptions/OpenXML4JRuntimeException.java deleted file mode 100644 index 40086aa9f..000000000 --- a/src/ooxml/java/org/apache/poi/openxml4j/exceptions/OpenXML4JRuntimeException.java +++ /dev/null @@ -1,38 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.exceptions; - -/** - * Global exception throws when a critical error occurs (this exception is - * set as Runtime in order not to force the user to manage the exception in a - * try/catch). - * - * @author Julien Chable - * @version 1.0 - */ -@SuppressWarnings("serial") -public class OpenXML4JRuntimeException extends RuntimeException { - - public OpenXML4JRuntimeException(String msg) { - super(msg); - } - - public OpenXML4JRuntimeException(String msg, Throwable reason) { - super(msg, reason); - } -} diff --git a/src/ooxml/java/org/apache/poi/openxml4j/exceptions/PartAlreadyExistsException.java b/src/ooxml/java/org/apache/poi/openxml4j/exceptions/PartAlreadyExistsException.java deleted file mode 100644 index e469ace56..000000000 --- a/src/ooxml/java/org/apache/poi/openxml4j/exceptions/PartAlreadyExistsException.java +++ /dev/null @@ -1,31 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.exceptions; - -import org.apache.poi.openxml4j.opc.PackagePart; - -/** - * Throw when trying to create a {@link PackagePart} but one - * already exists with that name. - */ -@SuppressWarnings("serial") -public final class PartAlreadyExistsException extends InvalidOperationException { - public PartAlreadyExistsException(String message){ - super(message); - } -} diff --git a/src/ooxml/java/org/apache/poi/openxml4j/opc/CertificateEmbeddingOption.java b/src/ooxml/java/org/apache/poi/openxml4j/opc/CertificateEmbeddingOption.java deleted file mode 100644 index cd7b45694..000000000 --- a/src/ooxml/java/org/apache/poi/openxml4j/opc/CertificateEmbeddingOption.java +++ /dev/null @@ -1,32 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc; - -/** - * Specifies the location where the X.509 certificate that is used in signing is stored. - * - * @author Julien Chable - */ -public enum CertificateEmbeddingOption { - /** The certificate is embedded in its own PackagePart. */ - IN_CERTIFICATE_PART, - /** The certificate is embedded in the SignaturePart that is created for the signature being added. */ - IN_SIGNATURE_PART, - /** The certificate in not embedded in the package. */ - NOT_EMBEDDED -} diff --git a/src/ooxml/java/org/apache/poi/openxml4j/opc/CompressionOption.java b/src/ooxml/java/org/apache/poi/openxml4j/opc/CompressionOption.java deleted file mode 100644 index 583b5c51d..000000000 --- a/src/ooxml/java/org/apache/poi/openxml4j/opc/CompressionOption.java +++ /dev/null @@ -1,47 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc; - -import java.util.zip.Deflater; - -/** - * Specifies the compression level for content that is stored in a PackagePart. - * - * @author Julien Chable - * @version 1.0 - */ -public enum CompressionOption { - /** Compression is optimized for performance. */ - FAST(Deflater.BEST_SPEED), - /** Compression is optimized for size. */ - MAXIMUM(Deflater.BEST_COMPRESSION), - /** Compression is optimized for a balance between size and performance. */ - NORMAL(Deflater.DEFAULT_COMPRESSION), - /** Compression is turned off. */ - NOT_COMPRESSED(Deflater.NO_COMPRESSION); - - private final int value; - - CompressionOption(int value) { - this.value = value; - } - - public int value() { - return this.value; - } -} diff --git a/src/ooxml/java/org/apache/poi/openxml4j/opc/ContentTypes.java b/src/ooxml/java/org/apache/poi/openxml4j/opc/ContentTypes.java deleted file mode 100644 index 805a5172a..000000000 --- a/src/ooxml/java/org/apache/poi/openxml4j/opc/ContentTypes.java +++ /dev/null @@ -1,132 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc; - -import java.util.Locale; - -/** - * Open Packaging Convention content types (see Annex F : Standard Namespaces - * and Content Types). - * - * @author CDubettier define some constants, Julien Chable - */ -public final class ContentTypes { - - /* - * Open Packaging Convention (Annex F : Standard Namespaces and Content - * Types) - */ - - /** - * Core Properties part. - */ - public static final String CORE_PROPERTIES_PART = "application/vnd.openxmlformats-package.core-properties+xml"; - - /** - * Digital Signature Certificate part. - */ - public static final String DIGITAL_SIGNATURE_CERTIFICATE_PART = "application/vnd.openxmlformats-package.digital-signature-certificate"; - - /** - * Digital Signature Origin part. - */ - public static final String DIGITAL_SIGNATURE_ORIGIN_PART = "application/vnd.openxmlformats-package.digital-signature-origin"; - - /** - * Digital Signature XML Signature part. - */ - public static final String DIGITAL_SIGNATURE_XML_SIGNATURE_PART = "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml"; - - /** - * Relationships part. - */ - public static final String RELATIONSHIPS_PART = "application/vnd.openxmlformats-package.relationships+xml"; - - /** - * Custom XML part. - */ - public static final String CUSTOM_XML_PART = "application/vnd.openxmlformats-officedocument.customXmlProperties+xml"; - - /** - * Plain old xml. Note - OOXML uses application/xml, and not text/xml! - */ - public static final String PLAIN_OLD_XML = "application/xml"; - - public static final String IMAGE_JPEG = "image/jpeg"; - - public static final String EXTENSION_JPG_1 = "jpg"; - - public static final String EXTENSION_JPG_2 = "jpeg"; - - // image/png ISO/IEC 15948:2003 http://www.libpng.org/pub/png/spec/ - public static final String IMAGE_PNG = "image/png"; - - public static final String EXTENSION_PNG = "png"; - - // image/gif http://www.w3.org/Graphics/GIF/spec-gif89a.txt - public static final String IMAGE_GIF = "image/gif"; - - public static final String EXTENSION_GIF = "gif"; - - /** - * TIFF image format. - * - * @see - * http://partners.adobe.com/public/developer/tiff/index.html#spec - */ - public static final String IMAGE_TIFF = "image/tiff"; - - public static final String EXTENSION_TIFF = "tiff"; - - /** - * Pict image format. - * - * @see - * http://developer.apple.com/documentation/mac/QuickDraw/QuickDraw-2.html - */ - public static final String IMAGE_PICT = "image/pict"; - - public static final String EXTENSION_PICT = "tiff"; - - /** - * XML file. - */ - public static final String XML = "text/xml"; - - public static final String EXTENSION_XML = "xml"; - - public static String getContentTypeFromFileExtension(String filename) { - String extension = filename.substring(filename.lastIndexOf(".") + 1) - .toLowerCase(Locale.ROOT); - if (extension.equals(EXTENSION_JPG_1) - || extension.equals(EXTENSION_JPG_2)) - return IMAGE_JPEG; - else if (extension.equals(EXTENSION_GIF)) - return IMAGE_GIF; - else if (extension.equals(EXTENSION_PICT)) - return IMAGE_PICT; - else if (extension.equals(EXTENSION_PNG)) - return IMAGE_PNG; - else if (extension.equals(EXTENSION_TIFF)) - return IMAGE_TIFF; - else if (extension.equals(EXTENSION_XML)) - return XML; - else - return null; - } -} diff --git a/src/ooxml/java/org/apache/poi/openxml4j/opc/EncryptionOption.java b/src/ooxml/java/org/apache/poi/openxml4j/opc/EncryptionOption.java deleted file mode 100644 index bc994e0f1..000000000 --- a/src/ooxml/java/org/apache/poi/openxml4j/opc/EncryptionOption.java +++ /dev/null @@ -1,29 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc; - -/** - * Specifies the encryption option for parts in a Package. - * - * @author Julien Chable - * @version 0.1 - */ -public enum EncryptionOption { - /** No encryption. */ - NONE -} diff --git a/src/ooxml/java/org/apache/poi/openxml4j/opc/OPCPackage.java b/src/ooxml/java/org/apache/poi/openxml4j/opc/OPCPackage.java deleted file mode 100644 index 6b6c5e85c..000000000 --- a/src/ooxml/java/org/apache/poi/openxml4j/opc/OPCPackage.java +++ /dev/null @@ -1,1689 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc; - -import java.io.ByteArrayOutputStream; -import java.io.Closeable; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.locks.ReentrantReadWriteLock; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.exceptions.InvalidOperationException; -import org.apache.poi.openxml4j.exceptions.OpenXML4JRuntimeException; -import org.apache.poi.openxml4j.exceptions.PartAlreadyExistsException; -import org.apache.poi.openxml4j.opc.internal.ContentType; -import org.apache.poi.openxml4j.opc.internal.ContentTypeManager; -import org.apache.poi.openxml4j.opc.internal.PackagePropertiesPart; -import org.apache.poi.openxml4j.opc.internal.PartMarshaller; -import org.apache.poi.openxml4j.opc.internal.PartUnmarshaller; -import org.apache.poi.openxml4j.opc.internal.ZipContentTypeManager; -import org.apache.poi.openxml4j.opc.internal.marshallers.DefaultMarshaller; -import org.apache.poi.openxml4j.opc.internal.marshallers.ZipPackagePropertiesMarshaller; -import org.apache.poi.openxml4j.opc.internal.unmarshallers.PackagePropertiesUnmarshaller; -import org.apache.poi.openxml4j.opc.internal.unmarshallers.UnmarshallContext; -import org.apache.poi.openxml4j.util.Nullable; -import org.apache.poi.openxml4j.util.ZipEntrySource; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.NotImplemented; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; - -/** - * Represents a container that can store multiple data objects. - */ -public abstract class OPCPackage implements RelationshipSource, Closeable { - - /** - * Logger. - */ - private static final POILogger logger = POILogFactory.getLogger(OPCPackage.class); - - /** - * Default package access. - */ - protected static final PackageAccess defaultPackageAccess = PackageAccess.READ_WRITE; - - /** - * Package access. - */ - private PackageAccess packageAccess; - - /** - * Package parts collection. - */ - protected PackagePartCollection partList; - - /** - * Package relationships. - */ - protected PackageRelationshipCollection relationships; - - /** - * Part marshallers by content type. - */ - protected Map partMarshallers; - - /** - * Default part marshaller. - */ - protected PartMarshaller defaultPartMarshaller; - - /** - * Part unmarshallers by content type. - */ - protected Map partUnmarshallers; - - /** - * Core package properties. - */ - protected PackagePropertiesPart packageProperties; - - /** - * Manage parts content types of this package. - */ - protected ContentTypeManager contentTypeManager; - - /** - * Flag if a modification is done to the document. - */ - protected boolean isDirty = false; - - /** - * File path of this package. - */ - protected String originalPackagePath; - - /** - * Output stream for writing this package. - */ - protected OutputStream output; - - /** - * Constructor. - * - * @param access - * Package access. - */ - OPCPackage(PackageAccess access) { - if (getClass() != ZipPackage.class) { - throw new IllegalArgumentException("PackageBase may not be subclassed"); - } - init(); - this.packageAccess = access; - } - - /** - * Initialize the package instance. - */ - private void init() { - this.partMarshallers = new HashMap(5); - this.partUnmarshallers = new HashMap(2); - - try { - // Add 'default' unmarshaller - this.partUnmarshallers.put(new ContentType( - ContentTypes.CORE_PROPERTIES_PART), - new PackagePropertiesUnmarshaller()); - - // Add default marshaller - this.defaultPartMarshaller = new DefaultMarshaller(); - // TODO Delocalize specialized marshallers - this.partMarshallers.put(new ContentType( - ContentTypes.CORE_PROPERTIES_PART), - new ZipPackagePropertiesMarshaller()); - } catch (InvalidFormatException e) { - // Should never happen - throw new OpenXML4JRuntimeException( - "Package.init() : this exception should never happen, " + - "if you read this message please send a mail to the developers team. : " + - e.getMessage(), - e - ); - } - } - - - /** - * Open a package with read/write permission. - * - * @param path - * The document path. - * @return A Package object, else null. - * @throws InvalidFormatException - * If the specified file doesn't exist, and a parsing error - * occur. - */ - public static OPCPackage open(String path) throws InvalidFormatException { - return open(path, defaultPackageAccess); - } - - /** - * Open a package with read/write permission. - * - * @param file - * The file to open. - * @return A Package object, else null. - * @throws InvalidFormatException - * If the specified file doesn't exist, and a parsing error - * occur. - */ - public static OPCPackage open(File file) throws InvalidFormatException { - return open(file, defaultPackageAccess); - } - - /** - * Open an user provided {@link ZipEntrySource} with read-only permission. - * This method can be used to stream data into POI. - * Opposed to other open variants, the data is read as-is, e.g. there aren't - * any zip-bomb protection put in place. - * - * @param zipEntry the custom source - * @return A Package object - * @throws InvalidFormatException if a parsing error occur. - */ - public static OPCPackage open(ZipEntrySource zipEntry) - throws InvalidFormatException { - OPCPackage pack = new ZipPackage(zipEntry, PackageAccess.READ); - try { - if (pack.partList == null) { - pack.getParts(); - } - // pack.originalPackagePath = file.getAbsolutePath(); - return pack; - } catch (InvalidFormatException e) { - IOUtils.closeQuietly(pack); - throw e; - } catch (RuntimeException e) { - IOUtils.closeQuietly(pack); - throw e; - } - } - - /** - * Open a package. - * - * @param path - * The document path. - * @param access - * PackageBase access. - * @return A PackageBase object, else null. - * @throws InvalidFormatException - * If the specified file doesn't exist, and a parsing error - * occur. - * @throws InvalidOperationException If the zip file cannot be opened. - * @throws InvalidFormatException if the package is not valid. - */ - public static OPCPackage open(String path, PackageAccess access) - throws InvalidFormatException, InvalidOperationException { - if (path == null || "".equals(path.trim())) { - throw new IllegalArgumentException("'path' must be given"); - } - - File file = new File(path); - if (file.exists() && file.isDirectory()) { - throw new IllegalArgumentException("path must not be a directory"); - } - - OPCPackage pack = new ZipPackage(path, access); // NOSONAR - boolean success = false; - if (pack.partList == null && access != PackageAccess.WRITE) { - try { - pack.getParts(); - success = true; - } finally { - if (! success) { - IOUtils.closeQuietly(pack); - } - } - } - - pack.originalPackagePath = new File(path).getAbsolutePath(); - return pack; - } - - /** - * Open a package. - * - * @param file - * The file to open. - * @param access - * PackageBase access. - * @return A PackageBase object, else null. - * @throws InvalidFormatException - * If the specified file doesn't exist, and a parsing error - * occur. - */ - public static OPCPackage open(File file, PackageAccess access) - throws InvalidFormatException { - if (file == null) { - throw new IllegalArgumentException("'file' must be given"); - } - if (file.exists() && file.isDirectory()) { - throw new IllegalArgumentException("file must not be a directory"); - } - - OPCPackage pack = new ZipPackage(file, access); - try { - if (pack.partList == null && access != PackageAccess.WRITE) { - pack.getParts(); - } - pack.originalPackagePath = file.getAbsolutePath(); - return pack; - } catch (InvalidFormatException e) { - IOUtils.closeQuietly(pack); - throw e; - } catch (RuntimeException e) { - IOUtils.closeQuietly(pack); - throw e; - } - } - - /** - * Open a package. - * - * Note - uses quite a bit more memory than {@link #open(String)}, which - * doesn't need to hold the whole zip file in memory, and can take advantage - * of native methods - * - * @param in - * The InputStream to read the package from - * @return A PackageBase object - */ - public static OPCPackage open(InputStream in) throws InvalidFormatException, - IOException { - OPCPackage pack = new ZipPackage(in, PackageAccess.READ_WRITE); - try { - if (pack.partList == null) { - pack.getParts(); - } - } catch (InvalidFormatException e) { - IOUtils.closeQuietly(pack); - throw e; - } catch (RuntimeException e) { - IOUtils.closeQuietly(pack); - throw e; - } - return pack; - } - - /** - * Opens a package if it exists, else it creates one. - * - * @param file - * The file to open or to create. - * @return A newly created package if the specified file does not exist, - * else the package extract from the file. - * @throws InvalidFormatException - * Throws if the specified file exist and is not valid. - */ - public static OPCPackage openOrCreate(File file) throws InvalidFormatException { - if (file.exists()) { - return open(file.getAbsolutePath()); - } else { - return create(file); - } - } - - /** - * Creates a new package. - * - * @param path - * Path of the document. - * @return A newly created PackageBase ready to use. - */ - public static OPCPackage create(String path) { - return create(new File(path)); - } - - /** - * Creates a new package. - * - * @param file - * Path of the document. - * @return A newly created PackageBase ready to use. - */ - public static OPCPackage create(File file) { - if (file == null || (file.exists() && file.isDirectory())) { - throw new IllegalArgumentException("file"); - } - - if (file.exists()) { - throw new InvalidOperationException( - "This package (or file) already exists : use the open() method or delete the file."); - } - - // Creates a new package - OPCPackage pkg = new ZipPackage(); - pkg.originalPackagePath = file.getAbsolutePath(); - - configurePackage(pkg); - return pkg; - } - - public static OPCPackage create(OutputStream output) { - OPCPackage pkg = new ZipPackage(); - pkg.originalPackagePath = null; - pkg.output = output; - - configurePackage(pkg); - return pkg; - } - - private static void configurePackage(OPCPackage pkg) { - try { - // Content type manager - pkg.contentTypeManager = new ZipContentTypeManager(null, pkg); - - // Add default content types for .xml and .rels - pkg.contentTypeManager.addContentType( - PackagingURIHelper.createPartName( - PackagingURIHelper.PACKAGE_RELATIONSHIPS_ROOT_URI), - ContentTypes.RELATIONSHIPS_PART); - pkg.contentTypeManager.addContentType( - PackagingURIHelper.createPartName("/default.xml"), - ContentTypes.PLAIN_OLD_XML); - - // Initialise some PackageBase properties - pkg.packageProperties = new PackagePropertiesPart(pkg, - PackagingURIHelper.CORE_PROPERTIES_PART_NAME); - pkg.packageProperties.setCreatorProperty("Generated by Apache POI OpenXML4J"); - pkg.packageProperties.setCreatedProperty(new Nullable(new Date())); - } catch (InvalidFormatException e) { - // Should never happen - throw new IllegalStateException(e); - } - } - - /** - * Flush the package : save all. - * - * @see #close() - */ - public void flush() { - throwExceptionIfReadOnly(); - - if (this.packageProperties != null) { - this.packageProperties.flush(); - } - - this.flushImpl(); - } - - /** - * Close the open, writable package and save its content. - * - * If your package is open read only, then you should call {@link #revert()} - * when finished with the package. - * - * @throws IOException - * If an IO exception occur during the saving process. - */ - @Override - public void close() throws IOException { - if (this.packageAccess == PackageAccess.READ) { - logger.log(POILogger.WARN, - "The close() method is intended to SAVE a package. This package is open in READ ONLY mode, use the revert() method instead !"); - revert(); - return; - } - if (this.contentTypeManager == null) { - logger.log(POILogger.WARN, - "Unable to call close() on a package that hasn't been fully opened yet"); - revert(); - return; - } - - // Save the content - ReentrantReadWriteLock l = new ReentrantReadWriteLock(); - try { - l.writeLock().lock(); - if (this.originalPackagePath != null - && !"".equals(this.originalPackagePath.trim())) { - File targetFile = new File(this.originalPackagePath); - if (!targetFile.exists() - || !(this.originalPackagePath - .equalsIgnoreCase(targetFile.getAbsolutePath()))) { - // Case of a package created from scratch - save(targetFile); - } else { - closeImpl(); - } - } else if (this.output != null) { - save(this.output); - output.close(); - } - } finally { - l.writeLock().unlock(); - } - - // Clear - this.contentTypeManager.clearAll(); - } - - /** - * Close the package WITHOUT saving its content. Reinitialize this package - * and cancel all changes done to it. - */ - public void revert() { - revertImpl(); - } - - /** - * Add a thumbnail to the package. This method is provided to make easier - * the addition of a thumbnail in a package. You can do the same work by - * using the traditionnal relationship and part mechanism. - * - * @param path The full path to the image file. - */ - public void addThumbnail(String path) throws IOException { - // Check parameter - if (path == null || path.isEmpty()) { - throw new IllegalArgumentException("path"); - } - String name = path.substring(path.lastIndexOf(File.separatorChar) + 1); - - FileInputStream is = new FileInputStream(path); - try { - addThumbnail(name, is); - } finally { - is.close(); - } - } - /** - * Add a thumbnail to the package. This method is provided to make easier - * the addition of a thumbnail in a package. You can do the same work by - * using the traditionnal relationship and part mechanism. - * - * @param filename The full path to the image file. - * @param data the image data - */ - public void addThumbnail(String filename, InputStream data) throws IOException { - // Check parameter - if (filename == null || filename.isEmpty()) { - throw new IllegalArgumentException("filename"); - } - - // Create the thumbnail part name - String contentType = ContentTypes - .getContentTypeFromFileExtension(filename); - PackagePartName thumbnailPartName; - try { - thumbnailPartName = PackagingURIHelper.createPartName("/docProps/" - + filename); - } catch (InvalidFormatException e) { - String partName = "/docProps/thumbnail" + - filename.substring(filename.lastIndexOf(".") + 1); - try { - thumbnailPartName = PackagingURIHelper.createPartName(partName); - } catch (InvalidFormatException e2) { - throw new InvalidOperationException( - "Can't add a thumbnail file named '" + filename + "'", e2); - } - } - - // Check if part already exist - if (this.getPart(thumbnailPartName) != null) { - throw new InvalidOperationException( - "You already add a thumbnail named '" + filename + "'"); - } - - // Add the thumbnail part to this package. - PackagePart thumbnailPart = this.createPart(thumbnailPartName, - contentType, false); - - // Add the relationship between the package and the thumbnail part - this.addRelationship(thumbnailPartName, TargetMode.INTERNAL, - PackageRelationshipTypes.THUMBNAIL); - - // Copy file data to the newly created part - StreamHelper.copyStream(data, thumbnailPart.getOutputStream()); - } - - /** - * Throws an exception if the package access mode is in read only mode - * (PackageAccess.Read). - * - * @throws InvalidOperationException - * Throws if a writing operation is done on a read only package. - * @see org.apache.poi.openxml4j.opc.PackageAccess - */ - void throwExceptionIfReadOnly() throws InvalidOperationException { - if (packageAccess == PackageAccess.READ) { - throw new InvalidOperationException( - "Operation not allowed, document open in read only mode!"); - } - } - - /** - * Throws an exception if the package access mode is in write only mode - * (PackageAccess.Write). This method is call when other methods need write - * right. - * - * @throws InvalidOperationException if a read operation is done on a write only package. - * @see org.apache.poi.openxml4j.opc.PackageAccess - */ - void throwExceptionIfWriteOnly() throws InvalidOperationException { - if (packageAccess == PackageAccess.WRITE) { - throw new InvalidOperationException( - "Operation not allowed, document open in write only mode!"); - } - } - - /** - * Retrieves or creates if none exists, core package property part. - * - * @return The PackageProperties part of this package. - */ - public PackageProperties getPackageProperties() - throws InvalidFormatException { - this.throwExceptionIfWriteOnly(); - // If no properties part has been found then we create one - if (this.packageProperties == null) { - this.packageProperties = new PackagePropertiesPart(this, - PackagingURIHelper.CORE_PROPERTIES_PART_NAME); - } - return this.packageProperties; - } - - /** - * Retrieve a part identified by its name. - * - * @param partName - * Part name of the part to retrieve. - * @return The part with the specified name, else null. - */ - public PackagePart getPart(PackagePartName partName) { - throwExceptionIfWriteOnly(); - - if (partName == null) { - throw new IllegalArgumentException("partName"); - } - - // If the partlist is null, then we parse the package. - if (partList == null) { - try { - getParts(); - } catch (InvalidFormatException e) { - return null; - } - } - return getPartImpl(partName); - } - - /** - * Retrieve parts by content type. - * - * @param contentType - * The content type criteria. - * @return All part associated to the specified content type. - */ - public ArrayList getPartsByContentType(String contentType) { - ArrayList retArr = new ArrayList(); - for (PackagePart part : partList.values()) { - if (part.getContentType().equals(contentType)) { - retArr.add(part); - } - } - Collections.sort(retArr); - return retArr; - } - - /** - * Retrieve parts by relationship type. - * - * @param relationshipType - * Relationship type. - * @return All parts which are the target of a relationship with the - * specified type, if the method can't retrieve relationships from - * the package, then return null. - */ - public ArrayList getPartsByRelationshipType( - String relationshipType) { - if (relationshipType == null) { - throw new IllegalArgumentException("relationshipType"); - } - ArrayList retArr = new ArrayList(); - for (PackageRelationship rel : getRelationshipsByType(relationshipType)) { - PackagePart part = getPart(rel); - if (part != null) { - retArr.add(part); - } - } - Collections.sort(retArr); - return retArr; - } - - /** - * Retrieve parts by name - * - * @param namePattern - * The pattern for matching the names - * @return All parts associated to the specified content type, sorted - * in alphanumerically by the part-name - */ - public List getPartsByName(final Pattern namePattern) { - if (namePattern == null) { - throw new IllegalArgumentException("name pattern must not be null"); - } - Matcher matcher = namePattern.matcher(""); - ArrayList result = new ArrayList(); - for (PackagePart part : partList.values()) { - PackagePartName partName = part.getPartName(); - if (matcher.reset(partName.getName()).matches()) { - result.add(part); - } - } - Collections.sort(result); - return result; - } - - /** - * Get the target part from the specified relationship. - * - * @param partRel - * The part relationship uses to retrieve the part. - */ - public PackagePart getPart(PackageRelationship partRel) { - PackagePart retPart = null; - ensureRelationships(); - for (PackageRelationship rel : relationships) { - if (rel.getRelationshipType().equals(partRel.getRelationshipType())) { - try { - retPart = getPart(PackagingURIHelper.createPartName(rel - .getTargetURI())); - } catch (InvalidFormatException e) { - continue; - } - break; - } - } - return retPart; - } - - /** - * Load the parts of the archive if it has not been done yet. The - * relationships of each part are not loaded. - * - * Note - Rule M4.1 states that there may only ever be one Core - * Properties Part, but Office produced files will sometimes - * have multiple! As Office ignores all but the first, we relax - * Compliance with Rule M4.1, and ignore all others silently too. - * - * @return All this package's parts. - * @throws InvalidFormatException if the package is not valid. - */ - public ArrayList getParts() throws InvalidFormatException { - throwExceptionIfWriteOnly(); - - // If the part list is null, we parse the package to retrieve all parts. - if (partList == null) { - /* Variables use to validate OPC Compliance */ - - // Check rule M4.1 -> A format consumer shall consider more than - // one core properties relationship for a package to be an error - // (We just log it and move on, as real files break this!) - boolean hasCorePropertiesPart = false; - boolean needCorePropertiesPart = true; - - PackagePart[] parts = this.getPartsImpl(); - this.partList = new PackagePartCollection(); - for (PackagePart part : parts) { - if (partList.containsKey(part._partName)) { - throw new InvalidFormatException( - "A part with the name '" + - part._partName + - "' already exist : Packages shall not contain equivalent " + - "part names and package implementers shall neither create " + - "nor recognize packages with equivalent part names. [M1.12]"); - } - - // Check OPC compliance rule M4.1 - if (part.getContentType().equals( - ContentTypes.CORE_PROPERTIES_PART)) { - if (!hasCorePropertiesPart) { - hasCorePropertiesPart = true; - } else { - logger.log(POILogger.WARN, "OPC Compliance error [M4.1]: " + - "there is more than one core properties relationship in the package! " + - "POI will use only the first, but other software may reject this file."); - } - } - - PartUnmarshaller partUnmarshaller = partUnmarshallers.get(part._contentType); - - if (partUnmarshaller != null) { - UnmarshallContext context = new UnmarshallContext(this, - part._partName); - try { - PackagePart unmarshallPart = partUnmarshaller - .unmarshall(context, part.getInputStream()); - partList.put(unmarshallPart._partName, unmarshallPart); - - // Core properties case-- use first CoreProperties part we come across - // and ignore any subsequent ones - if (unmarshallPart instanceof PackagePropertiesPart && - hasCorePropertiesPart && - needCorePropertiesPart) { - this.packageProperties = (PackagePropertiesPart) unmarshallPart; - needCorePropertiesPart = false; - } - } catch (IOException ioe) { - logger.log(POILogger.WARN, "Unmarshall operation : IOException for " - + part._partName); - continue; - } catch (InvalidOperationException invoe) { - throw new InvalidFormatException(invoe.getMessage(), invoe); - } - } else { - try { - partList.put(part._partName, part); - } catch (InvalidOperationException e) { - throw new InvalidFormatException(e.getMessage(), e); - } - } - } - } - ArrayList result = new ArrayList(partList.values()); - java.util.Collections.sort(result); - return result; - } - - /** - * Create and add a part, with the specified name and content type, to the - * package. - * - * @param partName - * Part name. - * @param contentType - * Part content type. - * @return The newly created part. - * @throws PartAlreadyExistsException - * If rule M1.12 is not verified : Packages shall not contain - * equivalent part names and package implementers shall neither - * create nor recognize packages with equivalent part names. - * @see #createPartImpl(PackagePartName, String, boolean) - */ - public PackagePart createPart(PackagePartName partName, String contentType) { - return this.createPart(partName, contentType, true); - } - - /** - * Create and add a part, with the specified name and content type, to the - * package. For general purpose, prefer the overload version of this method - * without the 'loadRelationships' parameter. - * - * @param partName - * Part name. - * @param contentType - * Part content type. - * @param loadRelationships - * Specify if the existing relationship part, if any, logically - * associated to the newly created part will be loaded. - * @return The newly created part. - * @throws PartAlreadyExistsException - * If rule M1.12 is not verified : Packages shall not contain - * equivalent part names and package implementers shall neither - * create nor recognize packages with equivalent part names. - * @see #createPartImpl(PackagePartName, String, boolean) - */ - PackagePart createPart(PackagePartName partName, String contentType, - boolean loadRelationships) { - throwExceptionIfReadOnly(); - if (partName == null) { - throw new IllegalArgumentException("partName"); - } - - if (contentType == null || contentType.equals("")) { - throw new IllegalArgumentException("contentType"); - } - - // Check if the specified part name already exists - if (partList.containsKey(partName) - && !partList.get(partName).isDeleted()) { - throw new PartAlreadyExistsException( - "A part with the name '" + partName.getName() + "'" + - " already exists : Packages shall not contain equivalent part names and package" + - " implementers shall neither create nor recognize packages with equivalent part names. [M1.12]"); - } - - /* Check OPC compliance */ - - // Rule [M4.1]: The format designer shall specify and the format producer - // shall create at most one core properties relationship for a package. - // A format consumer shall consider more than one core properties - // relationship for a package to be an error. If present, the - // relationship shall target the Core Properties part. - // Note - POI will read files with more than one Core Properties, which - // Office sometimes produces, but is strict on generation - if (contentType.equals(ContentTypes.CORE_PROPERTIES_PART)) { - if (this.packageProperties != null) { - throw new InvalidOperationException( - "OPC Compliance error [M4.1]: you try to add more than one core properties relationship in the package !"); - } - } - - /* End check OPC compliance */ - - PackagePart part = this.createPartImpl(partName, contentType, - loadRelationships); - this.contentTypeManager.addContentType(partName, contentType); - this.partList.put(partName, part); - this.isDirty = true; - return part; - } - - /** - * Add a part to the package. - * - * @param partName - * Part name of the part to create. - * @param contentType - * type associated with the file - * @param content - * the contents to add. In order to have faster operation in - * document merge, the data are stored in memory not on a hard - * disk - * - * @return The new part. - * @see #createPart(PackagePartName, String) - */ - public PackagePart createPart(PackagePartName partName, String contentType, - ByteArrayOutputStream content) { - PackagePart addedPart = this.createPart(partName, contentType); - if (addedPart == null) { - return null; - } - // Extract the zip entry content to put it in the part content - if (content != null) { - try { - OutputStream partOutput = addedPart.getOutputStream(); - if (partOutput == null) { - return null; - } - - partOutput.write(content.toByteArray(), 0, content.size()); - partOutput.close(); - - } catch (IOException ioe) { - return null; - } - } else { - return null; - } - return addedPart; - } - - /** - * Add the specified part to the package. If a part already exists in the - * package with the same name as the one specified, then we replace the old - * part by the specified part. - * - * @param part - * The part to add (or replace). - * @return The part added to the package, the same as the one specified. - * @throws InvalidOperationException - * If rule M1.12 is not verified : Packages shall not contain - * equivalent part names and package implementers shall neither - * create nor recognize packages with equivalent part names. - */ - protected PackagePart addPackagePart(PackagePart part) { - throwExceptionIfReadOnly(); - if (part == null) { - throw new IllegalArgumentException("part"); - } - - if (partList.containsKey(part._partName)) { - if (!partList.get(part._partName).isDeleted()) { - throw new InvalidOperationException( - "A part with the name '" - + part._partName.getName() - + "' already exists : Packages shall not contain equivalent part names and package implementers shall neither create nor recognize packages with equivalent part names. [M1.12]"); - } - // If the specified partis flagged as deleted, we make it - // available - part.setDeleted(false); - // and delete the old part to replace it thereafeter - this.partList.remove(part._partName); - } - this.partList.put(part._partName, part); - this.isDirty = true; - return part; - } - - /** - * Remove the specified part in this package. If this part is relationship - * part, then delete all relationships in the source part. - * - * @param part - * The part to remove. If null, skip the action. - * @see #removePart(PackagePartName) - */ - public void removePart(PackagePart part) { - if (part != null) { - removePart(part.getPartName()); - } - } - - /** - * Remove a part in this package. If this part is relationship part, then - * delete all relationships in the source part. - * - * @param partName - * The part name of the part to remove. - */ - public void removePart(PackagePartName partName) { - throwExceptionIfReadOnly(); - if (partName == null || !this.containPart(partName)) { - throw new IllegalArgumentException("partName"); - } - - // Delete the specified part from the package. - if (this.partList.containsKey(partName)) { - this.partList.get(partName).setDeleted(true); - this.removePartImpl(partName); - this.partList.remove(partName); - } else { - this.removePartImpl(partName); - } - - // Delete content type - this.contentTypeManager.removeContentType(partName); - - // If this part is a relationship part, then delete all relationships of - // the source part. - if (partName.isRelationshipPartURI()) { - URI sourceURI = PackagingURIHelper - .getSourcePartUriFromRelationshipPartUri(partName.getURI()); - PackagePartName sourcePartName; - try { - sourcePartName = PackagingURIHelper.createPartName(sourceURI); - } catch (InvalidFormatException e) { - logger - .log(POILogger.ERROR, "Part name URI '" - + sourceURI - + "' is not valid ! This message is not intended to be displayed !"); - return; - } - if (sourcePartName.getURI().equals( - PackagingURIHelper.PACKAGE_ROOT_URI)) { - clearRelationships(); - } else if (containPart(sourcePartName)) { - PackagePart part = getPart(sourcePartName); - if (part != null) { - part.clearRelationships(); - } - } - } - - this.isDirty = true; - } - - /** - * Remove a part from this package as well as its relationship part, if one - * exists, and all parts listed in the relationship part. Be aware that this - * do not delete relationships which target the specified part. - * - * @param partName - * The name of the part to delete. - * @throws InvalidFormatException - * Throws if the associated relationship part of the specified - * part is not valid. - */ - public void removePartRecursive(PackagePartName partName) - throws InvalidFormatException { - // Retrieves relationship part, if one exists - PackagePart relPart = this.partList.get(PackagingURIHelper - .getRelationshipPartName(partName)); - // Retrieves PackagePart object from the package - PackagePart partToRemove = this.partList.get(partName); - - if (relPart != null) { - PackageRelationshipCollection partRels = new PackageRelationshipCollection( - partToRemove); - for (PackageRelationship rel : partRels) { - PackagePartName partNameToRemove = PackagingURIHelper - .createPartName(PackagingURIHelper.resolvePartUri(rel - .getSourceURI(), rel.getTargetURI())); - removePart(partNameToRemove); - } - - // Finally delete its relationship part if one exists - this.removePart(relPart._partName); - } - - // Delete the specified part - this.removePart(partToRemove._partName); - } - - /** - * Delete the part with the specified name and its associated relationships - * part if one exists. Prefer the use of this method to delete a part in the - * package, compare to the remove() methods that don't remove associated - * relationships part. - * - * @param partName - * Name of the part to delete - */ - public void deletePart(PackagePartName partName) { - if (partName == null) { - throw new IllegalArgumentException("partName"); - } - - // Remove the part - this.removePart(partName); - // Remove the relationships part - this.removePart(PackagingURIHelper.getRelationshipPartName(partName)); - } - - /** - * Delete the part with the specified name and all part listed in its - * associated relationships part if one exists. This process is recursively - * apply to all parts in the relationships part of the specified part. - * Prefer the use of this method to delete a part in the package, compare to - * the remove() methods that don't remove associated relationships part. - * - * @param partName - * Name of the part to delete - */ - public void deletePartRecursive(PackagePartName partName) { - if (partName == null || !this.containPart(partName)) { - throw new IllegalArgumentException("partName"); - } - - PackagePart partToDelete = this.getPart(partName); - // Remove the part - this.removePart(partName); - // Remove all relationship parts associated - try { - for (PackageRelationship relationship : partToDelete - .getRelationships()) { - PackagePartName targetPartName = PackagingURIHelper - .createPartName(PackagingURIHelper.resolvePartUri( - partName.getURI(), relationship.getTargetURI())); - this.deletePartRecursive(targetPartName); - } - } catch (InvalidFormatException e) { - logger.log(POILogger.WARN, "An exception occurs while deleting part '" - + partName.getName() - + "'. Some parts may remain in the package. - " - + e.getMessage()); - return; - } - // Remove the relationships part - PackagePartName relationshipPartName = PackagingURIHelper - .getRelationshipPartName(partName); - if (relationshipPartName != null && containPart(relationshipPartName)) { - this.removePart(relationshipPartName); - } - } - - /** - * Check if a part already exists in this package from its name. - * - * @param partName - * Part name to check. - * @return true if the part is logically added to this package, else - * false. - */ - public boolean containPart(PackagePartName partName) { - return (this.getPart(partName) != null); - } - - /** - * Add a relationship to the package (except relationships part). - * - * Check rule M4.1 : The format designer shall specify and the format - * producer shall create at most one core properties relationship for a - * package. A format consumer shall consider more than one core properties - * relationship for a package to be an error. If present, the relationship - * shall target the Core Properties part. - * - * Check rule M1.25: The Relationships part shall not have relationships to - * any other part. Package implementers shall enforce this requirement upon - * the attempt to create such a relationship and shall treat any such - * relationship as invalid. - * - * @param targetPartName - * Target part name. - * @param targetMode - * Target mode, either Internal or External. - * @param relationshipType - * Relationship type. - * @param relID - * ID of the relationship. - * @see PackageRelationshipTypes - */ - @Override - public PackageRelationship addRelationship(PackagePartName targetPartName, - TargetMode targetMode, String relationshipType, String relID) { - /* Check OPC compliance */ - - // Check rule M4.1 : The format designer shall specify and the format - // producer - // shall create at most one core properties relationship for a package. - // A format consumer shall consider more than one core properties - // relationship for a package to be an error. If present, the - // relationship shall target the Core Properties part. - if (relationshipType.equals(PackageRelationshipTypes.CORE_PROPERTIES) - && this.packageProperties != null) { - throw new InvalidOperationException( - "OPC Compliance error [M4.1]: can't add another core properties part ! Use the built-in package method instead."); - } - - /* - * Check rule M1.25: The Relationships part shall not have relationships - * to any other part. Package implementers shall enforce this - * requirement upon the attempt to create such a relationship and shall - * treat any such relationship as invalid. - */ - if (targetPartName.isRelationshipPartURI()) { - throw new InvalidOperationException( - "Rule M1.25: The Relationships part shall not have relationships to any other part."); - } - - /* End OPC compliance */ - - ensureRelationships(); - PackageRelationship retRel = relationships.addRelationship( - targetPartName.getURI(), targetMode, relationshipType, relID); - this.isDirty = true; - return retRel; - } - - /** - * Add a package relationship. - * - * @param targetPartName - * Target part name. - * @param targetMode - * Target mode, either Internal or External. - * @param relationshipType - * Relationship type. - * @see PackageRelationshipTypes - */ - @Override - public PackageRelationship addRelationship(PackagePartName targetPartName, - TargetMode targetMode, String relationshipType) { - return this.addRelationship(targetPartName, targetMode, - relationshipType, null); - } - - /** - * Adds an external relationship to a part (except relationships part). - * - * The targets of external relationships are not subject to the same - * validity checks that internal ones are, as the contents is potentially - * any file, URL or similar. - * - * @param target - * External target of the relationship - * @param relationshipType - * Type of relationship. - * @return The newly created and added relationship - * @see org.apache.poi.openxml4j.opc.RelationshipSource#addExternalRelationship(java.lang.String, - * java.lang.String) - */ - @Override - public PackageRelationship addExternalRelationship(String target, - String relationshipType) { - return addExternalRelationship(target, relationshipType, null); - } - - /** - * Adds an external relationship to a part (except relationships part). - * - * The targets of external relationships are not subject to the same - * validity checks that internal ones are, as the contents is potentially - * any file, URL or similar. - * - * @param target - * External target of the relationship - * @param relationshipType - * Type of relationship. - * @param id - * Relationship unique id. - * @return The newly created and added relationship - * @see org.apache.poi.openxml4j.opc.RelationshipSource#addExternalRelationship(java.lang.String, - * java.lang.String) - */ - @Override - public PackageRelationship addExternalRelationship(String target, - String relationshipType, String id) { - if (target == null) { - throw new IllegalArgumentException("target"); - } - if (relationshipType == null) { - throw new IllegalArgumentException("relationshipType"); - } - - URI targetURI; - try { - targetURI = new URI(target); - } catch (URISyntaxException e) { - throw new IllegalArgumentException("Invalid target - " + e); - } - - ensureRelationships(); - PackageRelationship retRel = relationships.addRelationship(targetURI, - TargetMode.EXTERNAL, relationshipType, id); - this.isDirty = true; - return retRel; - } - - /** - * Delete a relationship from this package. - * - * @param id - * Id of the relationship to delete. - */ - @Override - public void removeRelationship(String id) { - if (relationships != null) { - relationships.removeRelationship(id); - this.isDirty = true; - } - } - - /** - * Retrieves all package relationships. - * - * @return All package relationships of this package. - * @throws InvalidOperationException if a read operation is done on a write only package. - * @see #getRelationshipsHelper(String) - */ - @Override - public PackageRelationshipCollection getRelationships() { - return getRelationshipsHelper(null); - } - - /** - * Retrieves all relationships with the specified type. - * - * @param relationshipType - * The filter specifying the relationship type. - * @return All relationships with the specified relationship type. - */ - @Override - public PackageRelationshipCollection getRelationshipsByType( - String relationshipType) { - throwExceptionIfWriteOnly(); - if (relationshipType == null) { - throw new IllegalArgumentException("relationshipType"); - } - return getRelationshipsHelper(relationshipType); - } - - /** - * Retrieves all relationships with specified id (normally just ine because - * a relationship id is supposed to be unique). - * - * @param id - * Id of the wanted relationship. - */ - private PackageRelationshipCollection getRelationshipsHelper(String id) { - throwExceptionIfWriteOnly(); - ensureRelationships(); - return this.relationships.getRelationships(id); - } - - /** - * Clear package relationships. - */ - @Override - public void clearRelationships() { - if (relationships != null) { - relationships.clear(); - this.isDirty = true; - } - } - - /** - * Ensure that the relationships collection is not null. - */ - public void ensureRelationships() { - if (this.relationships == null) { - try { - this.relationships = new PackageRelationshipCollection(this); - } catch (InvalidFormatException e) { - this.relationships = new PackageRelationshipCollection(); - } - } - } - - /** - * @see org.apache.poi.openxml4j.opc.RelationshipSource#getRelationship(java.lang.String) - */ - @Override - public PackageRelationship getRelationship(String id) { - return this.relationships.getRelationshipByID(id); - } - - /** - * @see org.apache.poi.openxml4j.opc.RelationshipSource#hasRelationships() - */ - @Override - public boolean hasRelationships() { - return (relationships.size() > 0); - } - - /** - * @see org.apache.poi.openxml4j.opc.RelationshipSource#isRelationshipExists(org.apache.poi.openxml4j.opc.PackageRelationship) - */ - @Override - public boolean isRelationshipExists(PackageRelationship rel) { - for (PackageRelationship r : relationships) { - if (r == rel) { - return true; - } - } - return false; - } - - /** - * Add a marshaller. - * - * @param contentType - * The content type to bind to the specified marshaller. - * @param marshaller - * The marshaller to register with the specified content type. - */ - public void addMarshaller(String contentType, PartMarshaller marshaller) { - try { - partMarshallers.put(new ContentType(contentType), marshaller); - } catch (InvalidFormatException e) { - logger.log(POILogger.WARN, "The specified content type is not valid: '" - + e.getMessage() + "'. The marshaller will not be added !"); - } - } - - /** - * Add an unmarshaller. - * - * @param contentType - * The content type to bind to the specified unmarshaller. - * @param unmarshaller - * The unmarshaller to register with the specified content type. - */ - public void addUnmarshaller(String contentType, - PartUnmarshaller unmarshaller) { - try { - partUnmarshallers.put(new ContentType(contentType), unmarshaller); - } catch (InvalidFormatException e) { - logger.log(POILogger.WARN, "The specified content type is not valid: '" - + e.getMessage() - + "'. The unmarshaller will not be added !"); - } - } - - /** - * Remove a marshaller by its content type. - * - * @param contentType - * The content type associated with the marshaller to remove. - */ - public void removeMarshaller(String contentType) { - try { - partMarshallers.remove(new ContentType(contentType)); - } catch (InvalidFormatException e) { - throw new RuntimeException(e); - } - } - - /** - * Remove an unmarshaller by its content type. - * - * @param contentType - * The content type associated with the unmarshaller to remove. - */ - public void removeUnmarshaller(String contentType) { - try { - partUnmarshallers.remove(new ContentType(contentType)); - } catch (InvalidFormatException e) { - throw new RuntimeException(e); - } - } - - /* Accesseurs */ - - /** - * Get the package access mode. - * - * @return the packageAccess The current package access. - */ - public PackageAccess getPackageAccess() { - return packageAccess; - } - - /** - * Validates the package compliance with the OPC specifications. - * - * @return true if the package is valid else false - */ - @NotImplemented - public boolean validatePackage(OPCPackage pkg) throws InvalidFormatException { - throw new InvalidOperationException("Not implemented yet !!!"); - } - - /** - * Save the document in the specified file. - * - * @param targetFile - * Destination file. - * @throws IOException - * Throws if an IO exception occur. - * @see #save(OutputStream) - */ - public void save(File targetFile) throws IOException { - if (targetFile == null) { - throw new IllegalArgumentException("targetFile"); - } - - this.throwExceptionIfReadOnly(); - - // You shouldn't save the the same file, do a close instead - if(targetFile.exists() && - targetFile.getAbsolutePath().equals(this.originalPackagePath)) { - throw new InvalidOperationException( - "You can't call save(File) to save to the currently open " + - "file. To save to the current file, please just call close()" - ); - } - - // Do the save - FileOutputStream fos = null; - try { - fos = new FileOutputStream(targetFile); - this.save(fos); - } finally { - if (fos != null) { - fos.close(); - } - } - } - - /** - * Save the document in the specified output stream. - * - * @param outputStream - * The stream to save the package. - * @see #saveImpl(OutputStream) - */ - public void save(OutputStream outputStream) throws IOException { - throwExceptionIfReadOnly(); - this.saveImpl(outputStream); - } - - /** - * Core method to create a package part. This method must be implemented by - * the subclass. - * - * @param partName - * URI of the part to create. - * @param contentType - * Content type of the part to create. - * @return The newly created package part. - */ - protected abstract PackagePart createPartImpl(PackagePartName partName, - String contentType, boolean loadRelationships); - - /** - * Core method to delete a package part. This method must be implemented by - * the subclass. - * - * @param partName - * The URI of the part to delete. - */ - protected abstract void removePartImpl(PackagePartName partName); - - /** - * Flush the package but not save. - */ - protected abstract void flushImpl(); - - /** - * Close the package and cause a save of the package. - * - */ - protected abstract void closeImpl() throws IOException; - - /** - * Close the package without saving the document. Discard all changes made - * to this package. - */ - protected abstract void revertImpl(); - - /** - * Save the package into the specified output stream. - * - * @param outputStream - * The output stream use to save this package. - */ - protected abstract void saveImpl(OutputStream outputStream) - throws IOException; - - /** - * Get the package part mapped to the specified URI. - * - * @param partName - * The URI of the part to retrieve. - * @return The package part located by the specified URI, else null. - */ - protected abstract PackagePart getPartImpl(PackagePartName partName); - - /** - * Get all parts link to the package. - * - * @return A list of the part owned by the package. - */ - protected abstract PackagePart[] getPartsImpl() - throws InvalidFormatException; - - /** - * Replace a content type in this package. - * - *

    - * A typical scneario to call this method is to rename a template file to the main format, e.g. - * ".dotx" to ".docx" - * ".dotm" to ".docm" - * ".xltx" to ".xlsx" - * ".xltm" to ".xlsm" - * ".potx" to ".pptx" - * ".potm" to ".pptm" - *

    - * For example, a code converting a .xlsm macro workbook to .xlsx would look as follows: - *

    - *

    
    -     *
    -     *     OPCPackage pkg = OPCPackage.open(new FileInputStream("macro-workbook.xlsm"));
    -     *     pkg.replaceContentType(
    -     *         "application/vnd.ms-excel.sheet.macroEnabled.main+xml",
    -     *         "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml");
    -     *
    -     *     FileOutputStream out = new FileOutputStream("workbook.xlsx");
    -     *     pkg.save(out);
    -     *     out.close();
    -     *
    -     *    
    - *

    - * - * @param oldContentType the content type to be replaced - * @param newContentType the replacement - * @return whether replacement was succesfull - * @since POI-3.8 - */ - public boolean replaceContentType(String oldContentType, String newContentType){ - boolean success = false; - ArrayList list = getPartsByContentType(oldContentType); - for (PackagePart packagePart : list) { - if (packagePart.getContentType().equals(oldContentType)) { - PackagePartName partName = packagePart.getPartName(); - contentTypeManager.addContentType(partName, newContentType); - try { - packagePart.setContentType(newContentType); - } catch (InvalidFormatException e) { - throw new OpenXML4JRuntimeException("invalid content type - "+newContentType, e); - } - success = true; - this.isDirty = true; - } - } - return success; - } - - /** - * Add the specified part, and register its content type with the content - * type manager. - * - * @param part - * The part to add. - */ - public void registerPartAndContentType(PackagePart part) { - addPackagePart(part); - this.contentTypeManager.addContentType(part.getPartName(), part.getContentType()); - this.isDirty = true; - } - - /** - * Remove the specified part, and clear its content type from the content - * type manager. - * - * @param partName - * The part name of the part to remove. - */ - public void unregisterPartAndContentType(PackagePartName partName) { - removePart(partName); - this.contentTypeManager.removeContentType(partName); - this.isDirty = true; - } - -} diff --git a/src/ooxml/java/org/apache/poi/openxml4j/opc/PackageAccess.java b/src/ooxml/java/org/apache/poi/openxml4j/opc/PackageAccess.java deleted file mode 100644 index 256882228..000000000 --- a/src/ooxml/java/org/apache/poi/openxml4j/opc/PackageAccess.java +++ /dev/null @@ -1,33 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc; - -/** - * Specifies package access. - * - * @author Julien Chable - * @version 1.0 - */ -public enum PackageAccess { - /** Read only. Write not authorized. */ - READ, - /** Write only. Read not authorized. */ - WRITE, - /** Read and Write mode. */ - READ_WRITE -} diff --git a/src/ooxml/java/org/apache/poi/openxml4j/opc/PackageNamespaces.java b/src/ooxml/java/org/apache/poi/openxml4j/opc/PackageNamespaces.java deleted file mode 100644 index d1adc519f..000000000 --- a/src/ooxml/java/org/apache/poi/openxml4j/opc/PackageNamespaces.java +++ /dev/null @@ -1,52 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc; - -/** - * Open Packaging Convention namespaces URI. - * - * @author Julien Chable - * @version 1.0 - */ -public interface PackageNamespaces { - - /** - * Content Types. - */ - public static final String CONTENT_TYPES = "http://schemas.openxmlformats.org/package/2006/content-types"; - - /** - * Core Properties. - */ - public static final String CORE_PROPERTIES = "http://schemas.openxmlformats.org/package/2006/metadata/core-properties"; - - /** - * Digital Signatures. - */ - public static final String DIGITAL_SIGNATURE = "http://schemas.openxmlformats.org/package/2006/digital-signature"; - - /** - * Relationships. - */ - public static final String RELATIONSHIPS = "http://schemas.openxmlformats.org/package/2006/relationships"; - - /** - * Markup Compatibility. - */ - public static final String MARKUP_COMPATIBILITY = "http://schemas.openxmlformats.org/markup-compatibility/2006"; -} diff --git a/src/ooxml/java/org/apache/poi/openxml4j/opc/PackagePart.java b/src/ooxml/java/org/apache/poi/openxml4j/opc/PackagePart.java deleted file mode 100644 index 641e1bc19..000000000 --- a/src/ooxml/java/org/apache/poi/openxml4j/opc/PackagePart.java +++ /dev/null @@ -1,721 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.URI; -import java.net.URISyntaxException; - -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.exceptions.InvalidOperationException; -import org.apache.poi.openxml4j.exceptions.OpenXML4JException; -import org.apache.poi.openxml4j.opc.internal.ContentType; - -/** - * Provides a base class for parts stored in a Package. - */ -public abstract class PackagePart implements RelationshipSource, Comparable { - - /** - * This part's container. - */ - protected OPCPackage _container; - - /** - * The part name. (required by the specification [M1.1]) - */ - protected PackagePartName _partName; - - /** - * The type of content of this part. (required by the specification [M1.2]) - */ - protected ContentType _contentType; - - /** - * Flag to know if this part is a relationship. - */ - private boolean _isRelationshipPart; - - /** - * Flag to know if this part has been logically deleted. - */ - private boolean _isDeleted; - - /** - * This part's relationships. - */ - private PackageRelationshipCollection _relationships; - - /** - * Constructor. - * - * @param pack - * Parent package. - * @param partName - * The part name, relative to the parent Package root. - * @param contentType - * The content type. - * @throws InvalidFormatException - * If the specified URI is not valid. - */ - protected PackagePart(OPCPackage pack, PackagePartName partName, - ContentType contentType) throws InvalidFormatException { - this(pack, partName, contentType, true); - } - - /** - * Constructor. - * - * @param pack - * Parent package. - * @param partName - * The part name, relative to the parent Package root. - * @param contentType - * The content type. - * @param loadRelationships - * Specify if the relationships will be loaded - * @throws InvalidFormatException - * If the specified URI is not valid. - */ - protected PackagePart(OPCPackage pack, PackagePartName partName, - ContentType contentType, boolean loadRelationships) - throws InvalidFormatException { - _partName = partName; - _contentType = contentType; - _container = pack; - - // Check if this part is a relationship part - _isRelationshipPart = this._partName.isRelationshipPartURI(); - - // Load relationships if any - if (loadRelationships) - loadRelationships(); - } - - /** - * Constructor. - * - * @param pack - * Parent package. - * @param partName - * The part name, relative to the parent Package root. - * @param contentType - * The Multipurpose Internet Mail Extensions (MIME) content type - * of the part's data stream. - */ - public PackagePart(OPCPackage pack, PackagePartName partName, - String contentType) throws InvalidFormatException { - this(pack, partName, new ContentType(contentType)); - } - - /** - * Adds an external relationship to a part (except relationships part). - * - * The targets of external relationships are not subject to the same - * validity checks that internal ones are, as the contents is potentially - * any file, URL or similar. - * - * @param target - * External target of the relationship - * @param relationshipType - * Type of relationship. - * @return The newly created and added relationship - * @see org.apache.poi.openxml4j.opc.RelationshipSource#addExternalRelationship(java.lang.String, - * java.lang.String) - */ - public PackageRelationship addExternalRelationship(String target, - String relationshipType) { - return addExternalRelationship(target, relationshipType, null); - } - - /** - * Adds an external relationship to a part (except relationships part). - * - * The targets of external relationships are not subject to the same - * validity checks that internal ones are, as the contents is potentially - * any file, URL or similar. - * - * @param target - * External target of the relationship - * @param relationshipType - * Type of relationship. - * @param id - * Relationship unique id. - * @return The newly created and added relationship - * @see org.apache.poi.openxml4j.opc.RelationshipSource#addExternalRelationship(java.lang.String, - * java.lang.String) - */ - public PackageRelationship addExternalRelationship(String target, - String relationshipType, String id) { - if (target == null) { - throw new IllegalArgumentException("target is null for type " + relationshipType); - } - if (relationshipType == null) { - throw new IllegalArgumentException("relationshipType"); - } - - if (_relationships == null) { - _relationships = new PackageRelationshipCollection(); - } - - URI targetURI; - try { - targetURI = new URI(target); - } catch (URISyntaxException e) { - throw new IllegalArgumentException("Invalid target - " + e); - } - - return _relationships.addRelationship(targetURI, TargetMode.EXTERNAL, - relationshipType, id); - } - - /** - * Add a relationship to a part (except relationships part). - * - * @param targetPartName - * Name of the target part. This one must be relative to the - * source root directory of the part. - * @param targetMode - * Mode [Internal|External]. - * @param relationshipType - * Type of relationship. - * @return The newly created and added relationship - * @see org.apache.poi.openxml4j.opc.RelationshipSource#addRelationship(org.apache.poi.openxml4j.opc.PackagePartName, - * org.apache.poi.openxml4j.opc.TargetMode, java.lang.String) - */ - public PackageRelationship addRelationship(PackagePartName targetPartName, - TargetMode targetMode, String relationshipType) { - return addRelationship(targetPartName, targetMode, relationshipType, - null); - } - - /** - * Add a relationship to a part (except relationships part). - *

    - * Check rule M1.25: The Relationships part shall not have relationships to - * any other part. Package implementers shall enforce this requirement upon - * the attempt to create such a relationship and shall treat any such - * relationship as invalid. - *

    - * @param targetPartName - * Name of the target part. This one must be relative to the - * source root directory of the part. - * @param targetMode - * Mode [Internal|External]. - * @param relationshipType - * Type of relationship. - * @param id - * Relationship unique id. - * @return The newly created and added relationship - * - * @throws InvalidOperationException - * If a writing operation is done on a read only package or - * invalid nested relations are created. - * @throws IllegalArgumentException if targetPartName, targetMode - * or relationshipType are passed as null - * @see org.apache.poi.openxml4j.opc.RelationshipSource#addRelationship(org.apache.poi.openxml4j.opc.PackagePartName, - * org.apache.poi.openxml4j.opc.TargetMode, java.lang.String, java.lang.String) - */ - public PackageRelationship addRelationship(PackagePartName targetPartName, - TargetMode targetMode, String relationshipType, String id) { - _container.throwExceptionIfReadOnly(); - - if (targetPartName == null) { - throw new IllegalArgumentException("targetPartName"); - } - if (targetMode == null) { - throw new IllegalArgumentException("targetMode"); - } - if (relationshipType == null) { - throw new IllegalArgumentException("relationshipType"); - } - - if (this._isRelationshipPart || targetPartName.isRelationshipPartURI()) { - throw new InvalidOperationException( - "Rule M1.25: The Relationships part shall not have relationships to any other part."); - } - - if (_relationships == null) { - _relationships = new PackageRelationshipCollection(); - } - - return _relationships.addRelationship(targetPartName.getURI(), - targetMode, relationshipType, id); - } - - /** - * Add a relationship to a part (except relationships part). - * - * @param targetURI - * URI the target part. Must be relative to the source root - * directory of the part. - * @param targetMode - * Mode [Internal|External]. - * @param relationshipType - * Type of relationship. - * @return The newly created and added relationship - * @see org.apache.poi.openxml4j.opc.RelationshipSource#addRelationship(org.apache.poi.openxml4j.opc.PackagePartName, - * org.apache.poi.openxml4j.opc.TargetMode, java.lang.String) - */ - public PackageRelationship addRelationship(URI targetURI, - TargetMode targetMode, String relationshipType) { - return addRelationship(targetURI, targetMode, relationshipType, null); - } - - /** - * Add a relationship to a part (except relationships part). - *

    - * Check rule M1.25: The Relationships part shall not have relationships to - * any other part. Package implementers shall enforce this requirement upon - * the attempt to create such a relationship and shall treat any such - * relationship as invalid. - *

    - * @param targetURI - * URI of the target part. Must be relative to the source root - * directory of the part. - * @param targetMode - * Mode [Internal|External]. - * @param relationshipType - * Type of relationship. - * @param id - * Relationship unique id. - * @return The newly created and added relationship - * - * @throws InvalidOperationException - * If the URI point to a relationship part URI. - * @see org.apache.poi.openxml4j.opc.RelationshipSource#addRelationship(org.apache.poi.openxml4j.opc.PackagePartName, - * org.apache.poi.openxml4j.opc.TargetMode, java.lang.String, java.lang.String) - */ - public PackageRelationship addRelationship(URI targetURI, - TargetMode targetMode, String relationshipType, String id) { - _container.throwExceptionIfReadOnly(); - - if (targetURI == null) { - throw new IllegalArgumentException("targetPartName"); - } - if (targetMode == null) { - throw new IllegalArgumentException("targetMode"); - } - if (relationshipType == null) { - throw new IllegalArgumentException("relationshipType"); - } - - // Try to retrieve the target part - - if (this._isRelationshipPart - || PackagingURIHelper.isRelationshipPartURI(targetURI)) { - throw new InvalidOperationException( - "Rule M1.25: The Relationships part shall not have relationships to any other part."); - } - - if (_relationships == null) { - _relationships = new PackageRelationshipCollection(); - } - - return _relationships.addRelationship(targetURI, - targetMode, relationshipType, id); - } - - /** - * @see org.apache.poi.openxml4j.opc.RelationshipSource#clearRelationships() - */ - public void clearRelationships() { - if (_relationships != null) { - _relationships.clear(); - } - } - - /** - * Delete the relationship specified by its id. - * - * @param id - * The ID identified the part to delete. - * @see org.apache.poi.openxml4j.opc.RelationshipSource#removeRelationship(java.lang.String) - */ - public void removeRelationship(String id) { - this._container.throwExceptionIfReadOnly(); - if (this._relationships != null) - this._relationships.removeRelationship(id); - } - - /** - * Retrieve all the relationships attached to this part. - * - * @return This part's relationships. - * @throws InvalidOperationException - * Throws if the package is open en write only mode. - * @see org.apache.poi.openxml4j.opc.RelationshipSource#getRelationships() - */ - public PackageRelationshipCollection getRelationships() - throws InvalidFormatException { - return getRelationshipsCore(null); - } - - /** - * Retrieves a package relationship from its id. - * - * @param id - * ID of the package relationship to retrieve. - * @return The package relationship - * @see org.apache.poi.openxml4j.opc.RelationshipSource#getRelationship(java.lang.String) - */ - public PackageRelationship getRelationship(String id) { - return this._relationships.getRelationshipByID(id); - } - - /** - * Retrieve all relationships attached to this part which have the specified - * type. - * - * @param relationshipType - * Relationship type filter. - * @return All relationships from this part that have the specified type. - * @throws InvalidFormatException - * If an error occurs while parsing the part. - * @throws InvalidOperationException - * If the package is open in write only mode. - * @see org.apache.poi.openxml4j.opc.RelationshipSource#getRelationshipsByType(java.lang.String) - */ - public PackageRelationshipCollection getRelationshipsByType( - String relationshipType) throws InvalidFormatException { - _container.throwExceptionIfWriteOnly(); - - return getRelationshipsCore(relationshipType); - } - - /** - * Implementation of the getRelationships method(). - * - * @param filter - * Relationship type filter. If null then the filter is - * disabled and return all the relationships. - * @return All relationships from this part that have the specified type. - * @throws InvalidFormatException - * Throws if an error occurs during parsing the relationships - * part. - * @throws InvalidOperationException - * Throws if the package is open en write only mode. - * @see #getRelationshipsByType(String) - */ - private PackageRelationshipCollection getRelationshipsCore(String filter) - throws InvalidFormatException { - this._container.throwExceptionIfWriteOnly(); - if (_relationships == null) { - this.throwExceptionIfRelationship(); - _relationships = new PackageRelationshipCollection(this); - } - return new PackageRelationshipCollection(_relationships, filter); - } - - /** - * Knows if the part have any relationships. - * - * @return true if the part have at least one relationship else - * false. - * @see org.apache.poi.openxml4j.opc.RelationshipSource#hasRelationships() - */ - public boolean hasRelationships() { - return (!this._isRelationshipPart && (_relationships != null && _relationships - .size() > 0)); - } - - /** - * Checks if the specified relationship is part of this package part. - * - * @param rel - * The relationship to check. - * @return true if the specified relationship exists in this part, - * else returns false - * @see org.apache.poi.openxml4j.opc.RelationshipSource#isRelationshipExists(org.apache.poi.openxml4j.opc.PackageRelationship) - */ - public boolean isRelationshipExists(PackageRelationship rel) { - for (PackageRelationship r : _relationships) { - if (r == rel) - return true; - } - return false; - } - - /** - * Get the PackagePart that is the target of a relationship. - * - * @param rel A relationship from this part to another one - * @return The target part of the relationship - */ - public PackagePart getRelatedPart(PackageRelationship rel) throws InvalidFormatException { - // Ensure this is one of ours - if(! isRelationshipExists(rel)) { - throw new IllegalArgumentException("Relationship " + rel + " doesn't start with this part " + _partName); - } - - // Get the target URI, excluding any relative fragments - URI target = rel.getTargetURI(); - if(target.getFragment() != null) { - String t = target.toString(); - try { - target = new URI( t.substring(0, t.indexOf('#')) ); - } catch(URISyntaxException e) { - throw new InvalidFormatException("Invalid target URI: " + target); - } - } - - // Turn that into a name, and fetch - PackagePartName relName = PackagingURIHelper.createPartName(target); - PackagePart part = _container.getPart(relName); - if (part == null) { - throw new IllegalArgumentException("No part found for relationship " + rel); - } - return part; - } - - /** - * Get the input stream of this part to read its content. - * - * @return The input stream of the content of this part, else - * null. - * - * @throws IOException If creating the input-stream fails. - */ - public InputStream getInputStream() throws IOException { - InputStream inStream = this.getInputStreamImpl(); - if (inStream == null) { - throw new IOException("Can't obtain the input stream from " - + _partName.getName()); - } - return inStream; - } - - /** - * Get the output stream of this part. If the part is originally embedded in - * Zip package, it'll be transform into a MemoryPackagePart in - * order to write inside (the standard Java API doesn't allow to write in - * the file) - * - * @see org.apache.poi.openxml4j.opc.internal.MemoryPackagePart - */ - public OutputStream getOutputStream() { - OutputStream outStream; - // If this part is a zip package part (read only by design) we convert - // this part into a MemoryPackagePart instance for write purpose. - if (this instanceof ZipPackagePart) { - // Delete logically this part - _container.removePart(this._partName); - - // Create a memory part - PackagePart part = _container.createPart(this._partName, - this._contentType.toString(), false); - if (part == null) { - throw new InvalidOperationException( - "Can't create a temporary part !"); - } - part._relationships = this._relationships; - outStream = part.getOutputStreamImpl(); - } else { - outStream = this.getOutputStreamImpl(); - } - return outStream; - } - - /** - * Throws an exception if this package part is a relationship part. - * - * @throws InvalidOperationException - * If this part is a relationship part. - */ - private void throwExceptionIfRelationship() - throws InvalidOperationException { - if (this._isRelationshipPart) - throw new InvalidOperationException( - "Can do this operation on a relationship part !"); - } - - /** - * Ensure the package relationships collection instance is built. - * - * @throws InvalidFormatException - * Throws if - */ - private void loadRelationships() throws InvalidFormatException { - if (this._relationships == null && !this._isRelationshipPart) { - this.throwExceptionIfRelationship(); - _relationships = new PackageRelationshipCollection(this); - } - } - - /* - * Accessors - */ - - /** - * @return the uri - */ - public PackagePartName getPartName() { - return _partName; - } - - /** - * @return The Content Type of the part - */ - public String getContentType() { - return _contentType.toString(); - } - - /** - * @return The Content Type, including parameters, of the part - */ - public ContentType getContentTypeDetails() { - return _contentType; - } - - /** - * Set the content type. - * - * @param contentType - * the contentType to set - * - * @throws InvalidFormatException - * Throws if the content type is not valid. - * @throws InvalidOperationException - * Throws if you try to change the content type whereas this - * part is already attached to a package. - */ - public void setContentType(String contentType) - throws InvalidFormatException { - if (_container == null) { - _contentType = new ContentType(contentType); - } - else { - _container.unregisterPartAndContentType(_partName); - _contentType = new ContentType(contentType); - _container.registerPartAndContentType(this); - } - } - - public OPCPackage getPackage() { - return _container; - } - - /** - * @return true if this part is a relationship - */ - public boolean isRelationshipPart() { - return this._isRelationshipPart; - } - - /** - * @return true if this part has been logically deleted - */ - public boolean isDeleted() { - return _isDeleted; - } - - /** - * @param isDeleted - * the isDeleted to set - */ - public void setDeleted(boolean isDeleted) { - this._isDeleted = isDeleted; - } - - /** - * @return The length of the part in bytes, or -1 if not known - */ - public long getSize() { - return -1; - } - - @Override - public String toString() { - return "Name: " + this._partName + " - Content Type: " - + this._contentType; - } - - /** - * Compare based on the package part name, using a natural sort order - */ - @Override - public int compareTo(PackagePart other) - { - // NOTE could also throw a NullPointerException() if desired - if (other == null) - return -1; - - return PackagePartName.compare(this._partName, other._partName); - } - - /*-------------- Abstract methods ------------- */ - - /** - * Abstract method that get the input stream of this part. - * - * @exception IOException - * Throws if an IO Exception occur in the implementation - * method. - */ - protected abstract InputStream getInputStreamImpl() throws IOException; - - /** - * Abstract method that get the output stream of this part. - */ - protected abstract OutputStream getOutputStreamImpl(); - - /** - * Save the content of this part and the associated relationships part (if - * this part own at least one relationship) into the specified output - * stream. - * - * @param zos - * Output stream to save this part. - * @throws OpenXML4JException - * If any exception occur. - */ - public abstract boolean save(OutputStream zos) throws OpenXML4JException; - - /** - * Load the content of this part. - * - * @param ios - * The input stream of the content to load. - * @return true if the content has been successfully loaded, else - * false. - * @throws InvalidFormatException - * Throws if the content format is invalid. - */ - public abstract boolean load(InputStream ios) throws InvalidFormatException; - - /** - * Close this part : flush this part, close the input stream and output - * stream. After this method call, the part must be available for packaging. - */ - public abstract void close(); - - /** - * Flush the content of this part. If the input stream and/or output stream - * as in a waiting state to read or write, the must to empty their - * respective buffer. - */ - public abstract void flush(); - - /** - * Allows sub-classes to clean up before new data is added. - */ - public void clear() { - } -} diff --git a/src/ooxml/java/org/apache/poi/openxml4j/opc/PackagePartCollection.java b/src/ooxml/java/org/apache/poi/openxml4j/opc/PackagePartCollection.java deleted file mode 100644 index e4ecbd44b..000000000 --- a/src/ooxml/java/org/apache/poi/openxml4j/opc/PackagePartCollection.java +++ /dev/null @@ -1,81 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc; - -import java.util.ArrayList; -import java.util.TreeMap; - -import org.apache.poi.openxml4j.exceptions.InvalidOperationException; - -/** - * A package part collection. - * - * @author Julien Chable - * @version 0.1 - */ -public final class PackagePartCollection extends - TreeMap { - - private static final long serialVersionUID = 2515031135957635515L; - - /** - * Arraylist use to store this collection part names as string for rule - * M1.11 optimized checking. - */ - private ArrayList registerPartNameStr = new ArrayList(); - - @Override - public Object clone() { - return super.clone(); - } - - /** - * Check rule [M1.11]: a package implementer shall neither create nor - * recognize a part with a part name derived from another part name by - * appending segments to it. - * - * @exception InvalidOperationException - * Throws if you try to add a part with a name derived from - * another part name. - */ - @Override - public PackagePart put(PackagePartName partName, PackagePart part) { - String[] segments = partName.getURI().toASCIIString().split( - PackagingURIHelper.FORWARD_SLASH_STRING); - StringBuffer concatSeg = new StringBuffer(); - for (String seg : segments) { - if (!seg.equals("")) - concatSeg.append(PackagingURIHelper.FORWARD_SLASH_CHAR); - concatSeg.append(seg); - if (this.registerPartNameStr.contains(concatSeg.toString())) { - throw new InvalidOperationException( - "You can't add a part with a part name derived from another part ! [M1.11]"); - } - } - this.registerPartNameStr.add(partName.getName()); - return super.put(partName, part); - } - - @Override - public PackagePart remove(Object key) { - if (key instanceof PackagePartName) { - this.registerPartNameStr.remove(((PackagePartName) key).getName()); - } - return super.remove(key); - } -} diff --git a/src/ooxml/java/org/apache/poi/openxml4j/opc/PackagePartName.java b/src/ooxml/java/org/apache/poi/openxml4j/opc/PackagePartName.java deleted file mode 100644 index 37ee63177..000000000 --- a/src/ooxml/java/org/apache/poi/openxml4j/opc/PackagePartName.java +++ /dev/null @@ -1,615 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc; - -import java.math.BigInteger; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Locale; - -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.exceptions.OpenXML4JRuntimeException; - -/** - * An immutable Open Packaging Convention compliant part name. - * - * @author Julien Chable - * - * @see http://www.ietf.org/rfc/rfc3986.txt - */ -public final class PackagePartName implements Comparable { - - /** - * Part name stored as an URI. - */ - private URI partNameURI; - - /* - * URI Characters definition (RFC 3986) - */ - - /** - * Reserved characters for sub delimitations. - */ - private static String[] RFC3986_PCHAR_SUB_DELIMS = { "!", "$", "&", "'", - "(", ")", "*", "+", ",", ";", "=" }; - - /** - * Unreserved character (+ ALPHA & DIGIT). - */ - private static String[] RFC3986_PCHAR_UNRESERVED_SUP = { "-", ".", "_", "~" }; - - /** - * Authorized reserved characters for pChar. - */ - private static String[] RFC3986_PCHAR_AUTHORIZED_SUP = { ":", "@" }; - - /** - * Flag to know if this part name is from a relationship part name. - */ - private boolean isRelationship; - - /** - * Constructor. Makes a ValidPartName object from a java.net.URI - * - * @param uri - * The URI to validate and to transform into ValidPartName. - * @param checkConformance - * Flag to specify if the contructor have to validate the OPC - * conformance. Must be always true except for - * special URI like '/' which is needed for internal use by - * OpenXML4J but is not valid. - * @throws InvalidFormatException - * Throw if the specified part name is not conform to Open - * Packaging Convention specifications. - * @see java.net.URI - */ - PackagePartName(URI uri, boolean checkConformance) - throws InvalidFormatException { - if (checkConformance) { - throwExceptionIfInvalidPartUri(uri); - } else { - if (!PackagingURIHelper.PACKAGE_ROOT_URI.equals(uri)) { - throw new OpenXML4JRuntimeException( - "OCP conformance must be check for ALL part name except special cases : ['/']"); - } - } - this.partNameURI = uri; - this.isRelationship = isRelationshipPartURI(this.partNameURI); - } - - /** - * Constructor. Makes a ValidPartName object from a String part name. - * - * @param partName - * Part name to valid and to create. - * @param checkConformance - * Flag to specify if the contructor have to validate the OPC - * conformance. Must be always true except for - * special URI like '/' which is needed for internal use by - * OpenXML4J but is not valid. - * @throws InvalidFormatException - * Throw if the specified part name is not conform to Open - * Packaging Convention specifications. - */ - PackagePartName(String partName, boolean checkConformance) - throws InvalidFormatException { - URI partURI; - try { - partURI = new URI(partName); - } catch (URISyntaxException e) { - throw new IllegalArgumentException( - "partName argmument is not a valid OPC part name !"); - } - - if (checkConformance) { - throwExceptionIfInvalidPartUri(partURI); - } else { - if (!PackagingURIHelper.PACKAGE_ROOT_URI.equals(partURI)) { - throw new OpenXML4JRuntimeException( - "OCP conformance must be check for ALL part name except special cases : ['/']"); - } - } - this.partNameURI = partURI; - this.isRelationship = isRelationshipPartURI(this.partNameURI); - } - - /** - * Check if the specified part name is a relationship part name. - * - * @param partUri - * The URI to check. - * @return true if this part name respect the relationship - * part naming convention else false. - */ - private boolean isRelationshipPartURI(URI partUri) { - if (partUri == null) - throw new IllegalArgumentException("partUri"); - - return partUri.getPath().matches( - "^.*/" + PackagingURIHelper.RELATIONSHIP_PART_SEGMENT_NAME + "/.*\\" - + PackagingURIHelper.RELATIONSHIP_PART_EXTENSION_NAME - + "$"); - } - - /** - * Know if this part name is a relationship part name. - * - * @return true if this part name respect the relationship - * part naming convention else false. - */ - public boolean isRelationshipPartURI() { - return this.isRelationship; - } - - /** - * Throws an exception (of any kind) if the specified part name does not - * follow the Open Packaging Convention specifications naming rules. - * - * @param partUri - * The part name to check. - * @throws Exception - * Throws if the part name is invalid. - */ - private static void throwExceptionIfInvalidPartUri(URI partUri) - throws InvalidFormatException { - if (partUri == null) - throw new IllegalArgumentException("partUri"); - // Check if the part name URI is empty [M1.1] - throwExceptionIfEmptyURI(partUri); - - // Check if the part name URI is absolute - throwExceptionIfAbsoluteUri(partUri); - - // Check if the part name URI starts with a forward slash [M1.4] - throwExceptionIfPartNameNotStartsWithForwardSlashChar(partUri); - - // Check if the part name URI ends with a forward slash [M1.5] - throwExceptionIfPartNameEndsWithForwardSlashChar(partUri); - - // Check if the part name does not have empty segments. [M1.3] - // Check if a segment ends with a dot ('.') character. [M1.9] - throwExceptionIfPartNameHaveInvalidSegments(partUri); - } - - /** - * Throws an exception if the specified URI is empty. [M1.1] - * - * @param partURI - * Part URI to check. - * @throws InvalidFormatException - * If the specified URI is empty. - */ - private static void throwExceptionIfEmptyURI(URI partURI) - throws InvalidFormatException { - if (partURI == null) - throw new IllegalArgumentException("partURI"); - - String uriPath = partURI.getPath(); - if (uriPath.length() == 0 - || ((uriPath.length() == 1) && (uriPath.charAt(0) == PackagingURIHelper.FORWARD_SLASH_CHAR))) - throw new InvalidFormatException( - "A part name shall not be empty [M1.1]: " - + partURI.getPath()); - } - - /** - * Throws an exception if the part name has empty segments. [M1.3] - * - * Throws an exception if a segment any characters other than pchar - * characters. [M1.6] - * - * Throws an exception if a segment contain percent-encoded forward slash - * ('/'), or backward slash ('\') characters. [M1.7] - * - * Throws an exception if a segment contain percent-encoded unreserved - * characters. [M1.8] - * - * Throws an exception if the specified part name's segments end with a dot - * ('.') character. [M1.9] - * - * Throws an exception if a segment doesn't include at least one non-dot - * character. [M1.10] - * - * @param partUri - * The part name to check. - * @throws InvalidFormatException - * if the specified URI contain an empty segments or if one the - * segments contained in the part name, ends with a dot ('.') - * character. - */ - private static void throwExceptionIfPartNameHaveInvalidSegments(URI partUri) - throws InvalidFormatException { - if (partUri == null) { - throw new IllegalArgumentException("partUri"); - } - - // Split the URI into several part and analyze each - String[] segments = partUri.toASCIIString().split("/"); - if (segments.length <= 1 || !segments[0].equals("")) - throw new InvalidFormatException( - "A part name shall not have empty segments [M1.3]: " - + partUri.getPath()); - - for (int i = 1; i < segments.length; ++i) { - String seg = segments[i]; - if (seg == null || "".equals(seg)) { - throw new InvalidFormatException( - "A part name shall not have empty segments [M1.3]: " - + partUri.getPath()); - } - - if (seg.endsWith(".")) { - throw new InvalidFormatException( - "A segment shall not end with a dot ('.') character [M1.9]: " - + partUri.getPath()); - } - - if ("".equals(seg.replaceAll("\\\\.", ""))) { - // Normally will never been invoked with the previous - // implementation rule [M1.9] - throw new InvalidFormatException( - "A segment shall include at least one non-dot character. [M1.10]: " - + partUri.getPath()); - } - - // Check for rule M1.6, M1.7, M1.8 - checkPCharCompliance(seg); - } - } - - /** - * Throws an exception if a segment any characters other than pchar - * characters. [M1.6] - * - * Throws an exception if a segment contain percent-encoded forward slash - * ('/'), or backward slash ('\') characters. [M1.7] - * - * Throws an exception if a segment contain percent-encoded unreserved - * characters. [M1.8] - * - * @param segment - * The segment to check - */ - private static void checkPCharCompliance(String segment) - throws InvalidFormatException { - boolean errorFlag; - final int length = segment.length(); - for (int i = 0; i < length; ++i) { - char c = segment.charAt(i); - errorFlag = true; - - /* Check rule M1.6 */ - - // Check for digit or letter - if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') - || (c >= '0' && c <= '9')) { - errorFlag = false; - } else { - // Check "-", ".", "_", "~" - for (int j = 0; j < RFC3986_PCHAR_UNRESERVED_SUP.length; ++j) { - if (c == RFC3986_PCHAR_UNRESERVED_SUP[j].charAt(0)) { - errorFlag = false; - break; - } - } - - // Check ":", "@" - for (int j = 0; errorFlag - && j < RFC3986_PCHAR_AUTHORIZED_SUP.length; ++j) { - if (c == RFC3986_PCHAR_AUTHORIZED_SUP[j].charAt(0)) { - errorFlag = false; - } - } - - // Check "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" - for (int j = 0; errorFlag - && j < RFC3986_PCHAR_SUB_DELIMS.length; ++j) { - if (c == RFC3986_PCHAR_SUB_DELIMS[j].charAt(0)) { - errorFlag = false; - } - } - } - - if (errorFlag && c == '%') { - // We certainly found an encoded character, check for length - // now ( '%' HEXDIGIT HEXDIGIT) - if (((length - i) < 2)) { - throw new InvalidFormatException("The segment " + segment - + " contain invalid encoded character !"); - } - - // If not percent encoded character error occur then reset the - // flag -> the character is valid - errorFlag = false; - - // Decode the encoded character - char decodedChar = (char) Integer.parseInt(segment.substring( - i + 1, i + 3), 16); - i += 2; - - /* Check rule M1.7 */ - if (decodedChar == '/' || decodedChar == '\\') - throw new InvalidFormatException( - "A segment shall not contain percent-encoded forward slash ('/'), or backward slash ('\') characters. [M1.7]"); - - /* Check rule M1.8 */ - - // Check for unreserved character like define in RFC3986 - if ((decodedChar >= 'A' && decodedChar <= 'Z') - || (decodedChar >= 'a' && decodedChar <= 'z') - || (decodedChar >= '0' && decodedChar <= '9')) - errorFlag = true; - - // Check for unreserved character "-", ".", "_", "~" - for (int j = 0; !errorFlag - && j < RFC3986_PCHAR_UNRESERVED_SUP.length; ++j) { - if (c == RFC3986_PCHAR_UNRESERVED_SUP[j].charAt(0)) { - errorFlag = true; - break; - } - } - if (errorFlag) - throw new InvalidFormatException( - "A segment shall not contain percent-encoded unreserved characters. [M1.8]"); - } - - if (errorFlag) - throw new InvalidFormatException( - "A segment shall not hold any characters other than pchar characters. [M1.6]"); - } - } - - /** - * Throws an exception if the specified part name doesn't start with a - * forward slash character '/'. [M1.4] - * - * @param partUri - * The part name to check. - * @throws InvalidFormatException - * If the specified part name doesn't start with a forward slash - * character '/'. - */ - private static void throwExceptionIfPartNameNotStartsWithForwardSlashChar( - URI partUri) throws InvalidFormatException { - String uriPath = partUri.getPath(); - if (uriPath.length() > 0 - && uriPath.charAt(0) != PackagingURIHelper.FORWARD_SLASH_CHAR) - throw new InvalidFormatException( - "A part name shall start with a forward slash ('/') character [M1.4]: " - + partUri.getPath()); - } - - /** - * Throws an exception if the specified part name ends with a forwar slash - * character '/'. [M1.5] - * - * @param partUri - * The part name to check. - * @throws InvalidFormatException - * If the specified part name ends with a forwar slash character - * '/'. - */ - private static void throwExceptionIfPartNameEndsWithForwardSlashChar( - URI partUri) throws InvalidFormatException { - String uriPath = partUri.getPath(); - if (uriPath.length() > 0 - && uriPath.charAt(uriPath.length() - 1) == PackagingURIHelper.FORWARD_SLASH_CHAR) - throw new InvalidFormatException( - "A part name shall not have a forward slash as the last character [M1.5]: " - + partUri.getPath()); - } - - /** - * Throws an exception if the specified URI is absolute. - * - * @param partUri - * The URI to check. - * @throws InvalidFormatException - * Throws if the specified URI is absolute. - */ - private static void throwExceptionIfAbsoluteUri(URI partUri) - throws InvalidFormatException { - if (partUri.isAbsolute()) - throw new InvalidFormatException("Absolute URI forbidden: " - + partUri); - } - - /** - * Compare two part names following the rule M1.12 : - * - * Part name equivalence is determined by comparing part names as - * case-insensitive ASCII strings. Packages shall not contain equivalent - * part names and package implementers shall neither create nor recognize - * packages with equivalent part names. [M1.12] - */ - @Override - public int compareTo(PackagePartName other) - { - // compare with natural sort order - return compare(this, other); - } - - - /** - * Retrieves the extension of the part name if any. If there is no extension - * returns an empty String. Example : '/document/content.xml' => 'xml' - * - * @return The extension of the part name. - */ - public String getExtension() { - String fragment = this.partNameURI.getPath(); - if (fragment.length() > 0) { - int i = fragment.lastIndexOf("."); - if (i > -1) - return fragment.substring(i + 1); - } - return ""; - } - - /** - * Get this part name. - * - * @return The name of this part name. - */ - public String getName() { - return this.partNameURI.toASCIIString(); - } - - /** - * Part name equivalence is determined by comparing part names as - * case-insensitive ASCII strings. Packages shall not contain equivalent - * part names and package implementers shall neither create nor recognize - * packages with equivalent part names. [M1.12] - */ - @Override - public boolean equals(Object other) { - if (other instanceof PackagePartName) { - // String.equals() is compatible with our compareTo(), but cheaper - return this.partNameURI.toASCIIString().toLowerCase(Locale.ROOT).equals - ( - ((PackagePartName) other).partNameURI.toASCIIString().toLowerCase(Locale.ROOT) - ); - } else { - return false; - } - } - - @Override - public int hashCode() { - return this.partNameURI.toASCIIString().toLowerCase(Locale.ROOT).hashCode(); - } - - @Override - public String toString() { - return getName(); - } - - /* Getters and setters */ - - /** - * Part name property getter. - * - * @return This part name URI. - */ - public URI getURI() { - return this.partNameURI; - } - - - /** - * A natural sort order for package part names, consistent with the - * requirements of {@code java.util.Comparator}, but simply implemented - * as a static method. - *

    - * For example, this sorts "file10.png" after "file2.png" (comparing the - * numerical portion), but sorts "File10.png" before "file2.png" - * (lexigraphical sort) - * - *

    - * When comparing part names, the rule M1.12 is followed: - * - * Part name equivalence is determined by comparing part names as - * case-insensitive ASCII strings. Packages shall not contain equivalent - * part names and package implementers shall neither create nor recognize - * packages with equivalent part names. [M1.12] - */ - public static int compare(PackagePartName obj1, PackagePartName obj2) - { - // NOTE could also throw a NullPointerException() if desired - if (obj1 == null) - { - // (null) == (null), (null) < (non-null) - return (obj2 == null ? 0 : -1); - } - else if (obj2 == null) - { - // (non-null) > (null) - return 1; - } - - return compare - ( - obj1.getURI().toASCIIString().toLowerCase(Locale.ROOT), - obj2.getURI().toASCIIString().toLowerCase(Locale.ROOT) - ); - } - - - /** - * A natural sort order for strings, consistent with the - * requirements of {@code java.util.Comparator}, but simply implemented - * as a static method. - *

    - * For example, this sorts "file10.png" after "file2.png" (comparing the - * numerical portion), but sorts "File10.png" before "file2.png" - * (lexigraphical sort) - */ - public static int compare(String str1, String str2) - { - if (str1 == null) - { - // (null) == (null), (null) < (non-null) - return (str2 == null ? 0 : -1); - } - else if (str2 == null) - { - // (non-null) > (null) - return 1; - } - - int len1 = str1.length(); - int len2 = str2.length(); - for (int idx1 = 0, idx2 = 0; idx1 < len1 && idx2 < len2; /*nil*/) - { - char c1 = str1.charAt(idx1++); - char c2 = str2.charAt(idx2++); - - if (Character.isDigit(c1) && Character.isDigit(c2)) - { - int beg1 = idx1 - 1; // undo previous increment - while (idx1 < len1 && Character.isDigit(str1.charAt(idx1))) - { - ++idx1; - } - - int beg2 = idx2 - 1; // undo previous increment - while (idx2 < len2 && Character.isDigit(str2.charAt(idx2))) - { - ++idx2; - } - - // note: BigInteger for extra safety - int cmp = new BigInteger(str1.substring(beg1, idx1)).compareTo - ( - new BigInteger(str2.substring(beg2, idx2)) - ); - if (cmp != 0) return cmp; - } - else if (c1 != c2) - { - return (c1 - c2); - } - } - - return (len1 - len2); - } - -} - -/* ************************************************************************** */ diff --git a/src/ooxml/java/org/apache/poi/openxml4j/opc/PackageProperties.java b/src/ooxml/java/org/apache/poi/openxml4j/opc/PackageProperties.java deleted file mode 100644 index 3013af435..000000000 --- a/src/ooxml/java/org/apache/poi/openxml4j/opc/PackageProperties.java +++ /dev/null @@ -1,227 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc; - -import java.util.Date; - -import org.apache.poi.openxml4j.util.Nullable; - -/** - * Represents the core properties of an OPC package. - * - * @author Julien Chable - * @version 1.0 - * @see org.apache.poi.openxml4j.opc.OPCPackage - */ -public interface PackageProperties { - - /** - * Dublin Core Terms URI. - */ - public final static String NAMESPACE_DCTERMS = "http://purl.org/dc/terms/"; - - /** - * Dublin Core namespace URI. - */ - public final static String NAMESPACE_DC = "http://purl.org/dc/elements/1.1/"; - - /* Getters and setters */ - - /** - * Set the category of the content of this package. - */ - public abstract Nullable getCategoryProperty(); - - /** - * Set the category of the content of this package. - */ - public abstract void setCategoryProperty(String category); - - /** - * Set the status of the content. - */ - public abstract Nullable getContentStatusProperty(); - - /** - * Get the status of the content. - */ - public abstract void setContentStatusProperty(String contentStatus); - - /** - * Get the type of content represented, generally defined by a specific use - * and intended audience. - */ - public abstract Nullable getContentTypeProperty(); - - /** - * Set the type of content represented, generally defined by a specific use - * and intended audience. - */ - public abstract void setContentTypeProperty(String contentType); - - /** - * Get the date of creation of the resource. - */ - public abstract Nullable getCreatedProperty(); - - /** - * Set the date of creation of the resource. - */ - public abstract void setCreatedProperty(String created); - - /** - * Set the date of creation of the resource. - */ - public abstract void setCreatedProperty(Nullable created); - - /** - * Get the entity primarily responsible for making the content of the - * resource. - */ - public abstract Nullable getCreatorProperty(); - - /** - * Set the entity primarily responsible for making the content of the - * resource. - */ - public abstract void setCreatorProperty(String creator); - - /** - * Get the explanation of the content of the resource. - */ - public abstract Nullable getDescriptionProperty(); - - /** - * Set the explanation of the content of the resource. - */ - public abstract void setDescriptionProperty(String description); - - /** - * Get an unambiguous reference to the resource within a given context. - */ - public abstract Nullable getIdentifierProperty(); - - /** - * Set an unambiguous reference to the resource within a given context. - */ - public abstract void setIdentifierProperty(String identifier); - - /** - * Get a delimited set of keywords to support searching and indexing. This - * is typically a list of terms that are not available elsewhere in the - * properties - */ - public abstract Nullable getKeywordsProperty(); - - /** - * Set a delimited set of keywords to support searching and indexing. This - * is typically a list of terms that are not available elsewhere in the - * properties - */ - public abstract void setKeywordsProperty(String keywords); - - /** - * Get the language of the intellectual content of the resource. - */ - public abstract Nullable getLanguageProperty(); - - /** - * Set the language of the intellectual content of the resource. - */ - public abstract void setLanguageProperty(String language); - - /** - * Get the user who performed the last modification. - */ - public abstract Nullable getLastModifiedByProperty(); - - /** - * Set the user who performed the last modification. - */ - public abstract void setLastModifiedByProperty(String lastModifiedBy); - - /** - * Get the date and time of the last printing. - */ - public abstract Nullable getLastPrintedProperty(); - - /** - * Set the date and time of the last printing. - */ - public abstract void setLastPrintedProperty(String lastPrinted); - - /** - * Set the date and time of the last printing. - */ - public abstract void setLastPrintedProperty(Nullable lastPrinted); - - /** - * Get the date on which the resource was changed. - */ - public abstract Nullable getModifiedProperty(); - - /** - * Set the date on which the resource was changed. - */ - public abstract void setModifiedProperty(String modified); - - /** - * Set the date on which the resource was changed. - */ - public abstract void setModifiedProperty(Nullable modified); - - /** - * Get the revision number. - */ - public abstract Nullable getRevisionProperty(); - - /** - * Set the revision number. - */ - public abstract void setRevisionProperty(String revision); - - /** - * Get the topic of the content of the resource. - */ - public abstract Nullable getSubjectProperty(); - - /** - * Set the topic of the content of the resource. - */ - public abstract void setSubjectProperty(String subject); - - /** - * Get the name given to the resource. - */ - public abstract Nullable getTitleProperty(); - - /** - * Set the name given to the resource. - */ - public abstract void setTitleProperty(String title); - - /** - * Get the version number. - */ - public abstract Nullable getVersionProperty(); - - /** - * Set the version number. - */ - public abstract void setVersionProperty(String version); -} diff --git a/src/ooxml/java/org/apache/poi/openxml4j/opc/PackageRelationship.java b/src/ooxml/java/org/apache/poi/openxml4j/opc/PackageRelationship.java deleted file mode 100644 index 90ee15e29..000000000 --- a/src/ooxml/java/org/apache/poi/openxml4j/opc/PackageRelationship.java +++ /dev/null @@ -1,227 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc; - -import java.net.URI; -import java.net.URISyntaxException; - -/** - * A part relationship. - * - * @author Julien Chable - * @version 1.0 - */ -public final class PackageRelationship { - - private static URI containerRelationshipPart; - - static { - try { - containerRelationshipPart = new URI("/_rels/.rels"); - } catch (URISyntaxException e) { - // Do nothing - } - } - - /* XML markup */ - - public static final String ID_ATTRIBUTE_NAME = "Id"; - - public static final String RELATIONSHIPS_TAG_NAME = "Relationships"; - - public static final String RELATIONSHIP_TAG_NAME = "Relationship"; - - public static final String TARGET_ATTRIBUTE_NAME = "Target"; - - public static final String TARGET_MODE_ATTRIBUTE_NAME = "TargetMode"; - - public static final String TYPE_ATTRIBUTE_NAME = "Type"; - - /* End XML markup */ - - /** - * Relation id. - */ - private String id; - - /** - * Reference to the package. - */ - private OPCPackage container; - - /** - * Relationship type - */ - private String relationshipType; - - /** - * Part of this relationship source - */ - private PackagePart source; - - /** - * Targeting mode [Internal|External] - */ - private TargetMode targetMode; - - /** - * Target URI - */ - private URI targetUri; - - /** - * Constructor. - * - * @param pkg - * @param sourcePart - * @param targetUri - * @param targetMode - * @param relationshipType - * @param id - */ - public PackageRelationship(OPCPackage pkg, PackagePart sourcePart, - URI targetUri, TargetMode targetMode, String relationshipType, - String id) { - if (pkg == null) - throw new IllegalArgumentException("pkg"); - if (targetUri == null) - throw new IllegalArgumentException("targetUri"); - if (relationshipType == null) - throw new IllegalArgumentException("relationshipType"); - if (id == null) - throw new IllegalArgumentException("id"); - - this.container = pkg; - this.source = sourcePart; - this.targetUri = targetUri; - this.targetMode = targetMode; - this.relationshipType = relationshipType; - this.id = id; - } - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof PackageRelationship)) { - return false; - } - PackageRelationship rel = (PackageRelationship) obj; - return (this.id.equals(rel.id) - && this.relationshipType.equals(rel.relationshipType) - && (rel.source != null ? rel.source.equals(this.source) : true) - && this.targetMode == rel.targetMode && this.targetUri - .equals(rel.targetUri)); - } - - @Override - public int hashCode() { - return this.id.hashCode() - + this.relationshipType.hashCode() - + (this.source == null ? 0 : this.source.hashCode()) - + this.targetMode.hashCode() - + this.targetUri.hashCode(); - } - - /* Getters */ - - public static URI getContainerPartRelationship() { - return containerRelationshipPart; - } - - /** - * @return the container - */ - public OPCPackage getPackage() { - return container; - } - - /** - * @return the id - */ - public String getId() { - return id; - } - - /** - * @return the relationshipType - */ - public String getRelationshipType() { - return relationshipType; - } - - /** - * @return the source - */ - public PackagePart getSource() { - return source; - } - - /** - * - * @return URL of the source part of this relationship - */ - public URI getSourceURI() { - if (source == null) { - return PackagingURIHelper.PACKAGE_ROOT_URI; - } - return source._partName.getURI(); - } - - /** - * @return the targetMode - */ - public TargetMode getTargetMode() { - return targetMode; - } - - /** - * @return the targetUri - */ - public URI getTargetURI() { - // If it's an external target, we don't - // need to apply our normal validation rules - if(targetMode == TargetMode.EXTERNAL) { - return targetUri; - } - - // Internal target - // If it isn't absolute, resolve it relative - // to ourselves - if (!targetUri.toASCIIString().startsWith("/")) { - // So it's a relative part name, try to resolve it - return PackagingURIHelper.resolvePartUri(getSourceURI(), targetUri); - } - return targetUri; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append(id == null ? "id=null" : "id=" + id); - sb.append(container == null ? " - container=null" : " - container=" - + container.toString()); - sb.append(relationshipType == null ? " - relationshipType=null" - : " - relationshipType=" + relationshipType); - sb.append(source == null ? " - source=null" : " - source=" - + getSourceURI().toASCIIString()); - sb.append(targetUri == null ? " - target=null" : " - target=" - + getTargetURI().toASCIIString()); - sb.append(targetMode == null ? ",targetMode=null" : ",targetMode=" - + targetMode.toString()); - return sb.toString(); - } -} diff --git a/src/ooxml/java/org/apache/poi/openxml4j/opc/PackageRelationshipCollection.java b/src/ooxml/java/org/apache/poi/openxml4j/opc/PackageRelationshipCollection.java deleted file mode 100644 index 640063802..000000000 --- a/src/ooxml/java/org/apache/poi/openxml4j/opc/PackageRelationshipCollection.java +++ /dev/null @@ -1,445 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.openxml4j.opc; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.Locale; -import java.util.TreeMap; - -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.exceptions.InvalidOperationException; -import org.apache.poi.util.DocumentHelper; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.w3c.dom.Attr; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.NodeList; - -/** - * Represents a collection of PackageRelationship elements that are owned by a - * given PackagePart or the Package. - * - * @author Julien Chable, CDubettier - * @version 0.1 - */ -public final class PackageRelationshipCollection implements - Iterable { - - private final static POILogger logger = POILogFactory.getLogger(PackageRelationshipCollection.class); - - /** - * Package relationships ordered by ID. - */ - private TreeMap relationshipsByID; - - /** - * Package relationships ordered by type. - */ - private TreeMap relationshipsByType; - - /** - * This relationshipPart. - */ - private PackagePart relationshipPart; - - /** - * Source part. - */ - private PackagePart sourcePart; - - /** - * This part name. - */ - private PackagePartName partName; - - /** - * Reference to the package. - */ - private OPCPackage container; - - /** - * The ID number of the next rID# to generate, or -1 - * if that is still to be determined. - */ - private int nextRelationshipId = -1; - - /** - * Constructor. - */ - PackageRelationshipCollection() { - relationshipsByID = new TreeMap(); - relationshipsByType = new TreeMap(); - } - - /** - * Copy constructor. - * - * This collection will contain only elements from the specified collection - * for which the type is compatible with the specified relationship type - * filter. - * - * @param coll - * Collection to import. - * @param filter - * Relationship type filter. - */ - public PackageRelationshipCollection(PackageRelationshipCollection coll, - String filter) { - this(); - for (PackageRelationship rel : coll.relationshipsByID.values()) { - if (filter == null || rel.getRelationshipType().equals(filter)) - addRelationship(rel); - } - } - - /** - * Constructor. - */ - public PackageRelationshipCollection(OPCPackage container) - throws InvalidFormatException { - this(container, null); - } - - /** - * Constructor. - * - * @throws InvalidFormatException - * Throws if the format of the content part is invalid. - * - * @throws InvalidOperationException - * Throws if the specified part is a relationship part. - */ - public PackageRelationshipCollection(PackagePart part) - throws InvalidFormatException { - this(part._container, part); - } - - /** - * Constructor. Parse the existing package relationship part if one exists. - * - * @param container - * The parent package. - * @param part - * The part that own this relationships collection. If null - * then this part is considered as the package root. - * @throws InvalidFormatException - * If an error occurs during the parsing of the relatinships - * part fo the specified part. - */ - public PackageRelationshipCollection(OPCPackage container, PackagePart part) - throws InvalidFormatException { - this(); - - if (container == null) - throw new IllegalArgumentException("container needs to be specified"); - - // Check if the specified part is not a relationship part - if (part != null && part.isRelationshipPart()) - throw new IllegalArgumentException("part"); - - this.container = container; - this.sourcePart = part; - this.partName = getRelationshipPartName(part); - if ((container.getPackageAccess() != PackageAccess.WRITE) - && container.containPart(this.partName)) { - relationshipPart = container.getPart(this.partName); - parseRelationshipsPart(relationshipPart); - } - } - - /** - * Get the relationship part name of the specified part. - * - * @param part - * The part . - * @return The relationship part name of the specified part. Be careful, - * only the correct name is returned, this method does not check if - * the part really exist in a package ! - * @throws InvalidOperationException - * Throws if the specified part is a relationship part. - */ - private static PackagePartName getRelationshipPartName(PackagePart part) - throws InvalidOperationException { - PackagePartName partName; - if (part == null) { - partName = PackagingURIHelper.PACKAGE_ROOT_PART_NAME; - } else { - partName = part.getPartName(); - } - return PackagingURIHelper.getRelationshipPartName(partName); - } - - /** - * Add the specified relationship to the collection. - * - * @param relPart - * The relationship to add. - */ - public void addRelationship(PackageRelationship relPart) { - relationshipsByID.put(relPart.getId(), relPart); - relationshipsByType.put(relPart.getRelationshipType(), relPart); - } - - /** - * Add a relationship to the collection. - * - * @param targetUri - * Target URI. - * @param targetMode - * The target mode : INTERNAL or EXTERNAL - * @param relationshipType - * Relationship type. - * @param id - * Relationship ID. - * @return The newly created relationship. - * @see PackageAccess - */ - public PackageRelationship addRelationship(URI targetUri, - TargetMode targetMode, String relationshipType, String id) { - if (id == null) { - // Generate a unique ID is id parameter is null. - if (nextRelationshipId == -1) { - nextRelationshipId = size() + 1; - } - - // Work up until we find a unique number (there could be gaps etc) - do { - id = "rId" + nextRelationshipId++; - } while (relationshipsByID.get(id) != null); - } - - PackageRelationship rel = new PackageRelationship(container, - sourcePart, targetUri, targetMode, relationshipType, id); - relationshipsByID.put(rel.getId(), rel); - relationshipsByType.put(rel.getRelationshipType(), rel); - return rel; - } - - /** - * Remove a relationship by its ID. - * - * @param id - * The relationship ID to remove. - */ - public void removeRelationship(String id) { - if (relationshipsByID != null && relationshipsByType != null) { - PackageRelationship rel = relationshipsByID.get(id); - if (rel != null) { - relationshipsByID.remove(rel.getId()); - relationshipsByType.values().remove(rel); - } - } - } - - /** - * Remove a relationship by its reference. - * - * @param rel - * The relationship to delete. - */ - public void removeRelationship(PackageRelationship rel) { - if (rel == null) - throw new IllegalArgumentException("rel"); - - relationshipsByID.values().remove(rel); - relationshipsByType.values().remove(rel); - } - - /** - * Retrieves a relationship by its index in the collection. - * - * @param index - * Must be a value between [0-relationships_count-1] - */ - public PackageRelationship getRelationship(int index) { - if (index < 0 || index > relationshipsByID.values().size()) - throw new IllegalArgumentException("index"); - - int i = 0; - for (PackageRelationship rel : relationshipsByID.values()) { - if (index == i++) - return rel; - } - - return null; - } - - /** - * Retrieves a package relationship based on its id. - * - * @param id - * ID of the package relationship to retrieve. - * @return The package relationship identified by the specified id. - */ - public PackageRelationship getRelationshipByID(String id) { - return relationshipsByID.get(id); - } - - /** - * Get the numbe rof relationships in the collection. - */ - public int size() { - return relationshipsByID.values().size(); - } - - /** - * Parse the relationship part and add all relationship in this collection. - * - * @param relPart - * The package part to parse. - * @throws InvalidFormatException - * Throws if the relationship part is invalid. - */ - public void parseRelationshipsPart(PackagePart relPart) - throws InvalidFormatException { - try { - logger.log(POILogger.DEBUG, "Parsing relationship: " + relPart.getPartName()); - Document xmlRelationshipsDoc = DocumentHelper.readDocument(relPart.getInputStream()); - - // Browse default types - Element root = xmlRelationshipsDoc.getDocumentElement(); - - // Check OPC compliance M4.1 rule - boolean fCorePropertiesRelationship = false; - - NodeList nodeList = root.getElementsByTagNameNS(PackageNamespaces.RELATIONSHIPS, PackageRelationship.RELATIONSHIP_TAG_NAME); - int nodeCount = nodeList.getLength(); - for (int i = 0; i < nodeCount; i++) { - Element element = (Element)nodeList.item(i); - // Relationship ID - String id = element.getAttribute(PackageRelationship.ID_ATTRIBUTE_NAME); - // Relationship type - String type = element.getAttribute(PackageRelationship.TYPE_ATTRIBUTE_NAME); - - /* Check OPC Compliance */ - // Check Rule M4.1 - if (type.equals(PackageRelationshipTypes.CORE_PROPERTIES)) - if (!fCorePropertiesRelationship) - fCorePropertiesRelationship = true; - else - throw new InvalidFormatException( - "OPC Compliance error [M4.1]: there is more than one core properties relationship in the package !"); - - /* End OPC Compliance */ - - // TargetMode (default value "Internal") - Attr targetModeAttr = element.getAttributeNode(PackageRelationship.TARGET_MODE_ATTRIBUTE_NAME); - TargetMode targetMode = TargetMode.INTERNAL; - if (targetModeAttr != null) { - targetMode = targetModeAttr.getValue().toLowerCase(Locale.ROOT) - .equals("internal") ? TargetMode.INTERNAL - : TargetMode.EXTERNAL; - } - - // Target converted in URI - URI target = PackagingURIHelper.toURI("http://invalid.uri"); // dummy url - String value = element.getAttribute(PackageRelationship.TARGET_ATTRIBUTE_NAME); - try { - // when parsing of the given uri fails, we can either - // ignore this relationship, which leads to IllegalStateException - // later on, or use a dummy value and thus enable processing of the - // package - target = PackagingURIHelper.toURI(value); - } catch (URISyntaxException e) { - logger.log(POILogger.ERROR, "Cannot convert " + value - + " in a valid relationship URI-> dummy-URI used", e); - } - addRelationship(target, targetMode, type, id); - } - } catch (Exception e) { - logger.log(POILogger.ERROR, e); - throw new InvalidFormatException(e.getMessage()); - } - } - - /** - * Retrieves all relations with the specified type. - * - * @param typeFilter - * Relationship type filter. If null then all - * relationships are returned. - * @return All relationships of the type specified by the filter. - */ - public PackageRelationshipCollection getRelationships(String typeFilter) { - return new PackageRelationshipCollection(this, typeFilter); - } - - /** - * Get this collection's iterator. - */ - public Iterator iterator() { - return relationshipsByID.values().iterator(); - } - - /** - * Get an iterator of a collection with all relationship with the specified - * type. - * - * @param typeFilter - * Type filter. - * @return An iterator to a collection containing all relationships with the - * specified type contain in this collection. - */ - public Iterator iterator(String typeFilter) { - ArrayList retArr = new ArrayList(); - for (PackageRelationship rel : relationshipsByID.values()) { - if (rel.getRelationshipType().equals(typeFilter)) - retArr.add(rel); - } - return retArr.iterator(); - } - - /** - * Clear all relationships. - */ - public void clear() { - relationshipsByID.clear(); - relationshipsByType.clear(); - } - - @Override - public String toString() { - String str; - if (relationshipsByID == null) { - str = "relationshipsByID=null"; - } else { - str = relationshipsByID.size() + " relationship(s) = ["; - } - if ((relationshipPart != null) && (relationshipPart._partName != null)) { - str = str + "," + relationshipPart._partName; - } else { - str = str + ",relationshipPart=null"; - } - - // Source of this relationship - if ((sourcePart != null) && (sourcePart._partName != null)) { - str = str + "," + sourcePart._partName; - } else { - str = str + ",sourcePart=null"; - } - if (partName != null) { - str = str + "," + partName; - } else { - str = str + ",uri=null)"; - } - return str + "]"; - } -} diff --git a/src/ooxml/java/org/apache/poi/openxml4j/opc/PackageRelationshipTypes.java b/src/ooxml/java/org/apache/poi/openxml4j/opc/PackageRelationshipTypes.java deleted file mode 100644 index b9cd553ba..000000000 --- a/src/ooxml/java/org/apache/poi/openxml4j/opc/PackageRelationshipTypes.java +++ /dev/null @@ -1,123 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc; - -/** - * Relationship types. - */ -public interface PackageRelationshipTypes { - /** - * Core properties relationship type. - * - *

    - * The standard specifies a source relations ship for the Core File Properties part as follows: - * http://schemas.openxmlformats.org/officedocument/2006/relationships/metadata/core-properties. - *

    - *

    - * Office uses the following source relationship for the Core File Properties part: - * http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties. - *

    - * See 2.1.33 Part 1 Section 15.2.11.1, Core File Properties Part in [MS-OE376].pdf - */ - String CORE_PROPERTIES = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties"; - - /** - * Core properties relationship type as defiend in ECMA 376. - */ - String CORE_PROPERTIES_ECMA376 = "http://schemas.openxmlformats.org/officedocument/2006/relationships/metadata/core-properties"; - - /** - * Namespace of Core properties relationship type as defiend in ECMA 376 - */ - String CORE_PROPERTIES_ECMA376_NS = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"; - - /** - * Digital signature relationship type. - */ - String DIGITAL_SIGNATURE = "http://schemas.openxmlformats.org/package/2006/relationships/digital-signature/signature"; - - /** - * Digital signature certificate relationship type. - */ - String DIGITAL_SIGNATURE_CERTIFICATE = "http://schemas.openxmlformats.org/package/2006/relationships/digital-signature/certificate"; - - /** - * Digital signature origin relationship type. - */ - String DIGITAL_SIGNATURE_ORIGIN = "http://schemas.openxmlformats.org/package/2006/relationships/digital-signature/origin"; - - /** - * Thumbnail relationship type. - */ - String THUMBNAIL = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail"; - - /** - * Extended properties relationship type. - */ - String EXTENDED_PROPERTIES = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties"; - - /** - * Extended properties relationship type for strict ooxml. - */ - String STRICT_EXTENDED_PROPERTIES = "http://purl.oclc.org/ooxml/officeDocument/relationships/extendedProperties"; - - /** - * Custom properties relationship type. - */ - String CUSTOM_PROPERTIES = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties"; - - /** - * Core document relationship type. - */ - String CORE_DOCUMENT = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument"; - - /** - * Core document relationship type for strict ooxml. - */ - String STRICT_CORE_DOCUMENT = "http://purl.oclc.org/ooxml/officeDocument/relationships/officeDocument"; - - /** - * Custom XML relationship type. - */ - String CUSTOM_XML = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXml"; - - /** - * Image type. - */ - String IMAGE_PART = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image"; - - /** - * Hyperlink type. - */ - String HYPERLINK_PART = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink"; - - /** - * Style type. - */ - String STYLE_PART = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles"; - - /** - * External Link to another Document - */ - String EXTERNAL_LINK_PATH = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/externalLinkPath"; - - /** - * Visio 2010 VSDX equivalent of package {@link #CORE_DOCUMENT} - */ - String VISIO_CORE_DOCUMENT = "http://schemas.microsoft.com/visio/2010/relationships/document"; -} diff --git a/src/ooxml/java/org/apache/poi/openxml4j/opc/PackagingURIHelper.java b/src/ooxml/java/org/apache/poi/openxml4j/opc/PackagingURIHelper.java deleted file mode 100644 index f44bf7367..000000000 --- a/src/ooxml/java/org/apache/poi/openxml4j/opc/PackagingURIHelper.java +++ /dev/null @@ -1,776 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc; - -import java.net.URI; -import java.net.URISyntaxException; -import java.nio.ByteBuffer; -import java.nio.charset.Charset; -import java.util.regex.Pattern; - -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.exceptions.InvalidOperationException; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; - -/** - * Helper for part and pack URI. - * - * @author Julien Chable, CDubet, Kim Ung - * @version 0.1 - */ -public final class PackagingURIHelper { - private final static POILogger _logger = POILogFactory.getLogger(PackagingURIHelper.class); - - /** - * Package root URI. - */ - private static URI packageRootUri; - - /** - * Extension name of a relationship part. - */ - public static final String RELATIONSHIP_PART_EXTENSION_NAME; - - /** - * Segment name of a relationship part. - */ - public static final String RELATIONSHIP_PART_SEGMENT_NAME; - - /** - * Segment name of the package properties folder. - */ - public static final String PACKAGE_PROPERTIES_SEGMENT_NAME; - - /** - * Core package properties art name. - */ - public static final String PACKAGE_CORE_PROPERTIES_NAME; - - /** - * Forward slash URI separator. - */ - public static final char FORWARD_SLASH_CHAR; - - /** - * Forward slash URI separator. - */ - public static final String FORWARD_SLASH_STRING; - - /** - * Package relationships part URI - */ - public static final URI PACKAGE_RELATIONSHIPS_ROOT_URI; - - /** - * Package relationships part name. - */ - public static final PackagePartName PACKAGE_RELATIONSHIPS_ROOT_PART_NAME; - - /** - * Core properties part URI. - */ - public static final URI CORE_PROPERTIES_URI; - - /** - * Core properties partname. - */ - public static final PackagePartName CORE_PROPERTIES_PART_NAME; - - /** - * Root package URI. - */ - public static final URI PACKAGE_ROOT_URI; - - /** - * Root package part name. - */ - public static final PackagePartName PACKAGE_ROOT_PART_NAME; - - /* Static initialization */ - static { - RELATIONSHIP_PART_SEGMENT_NAME = "_rels"; - RELATIONSHIP_PART_EXTENSION_NAME = ".rels"; - FORWARD_SLASH_CHAR = '/'; - FORWARD_SLASH_STRING = "/"; - PACKAGE_PROPERTIES_SEGMENT_NAME = "docProps"; - PACKAGE_CORE_PROPERTIES_NAME = "core.xml"; - - // Make URI - URI uriPACKAGE_ROOT_URI = null; - URI uriPACKAGE_RELATIONSHIPS_ROOT_URI = null; - URI uriPACKAGE_PROPERTIES_URI = null; - try { - uriPACKAGE_ROOT_URI = new URI("/"); - uriPACKAGE_RELATIONSHIPS_ROOT_URI = new URI(FORWARD_SLASH_CHAR - + RELATIONSHIP_PART_SEGMENT_NAME + FORWARD_SLASH_CHAR - + RELATIONSHIP_PART_EXTENSION_NAME); - packageRootUri = new URI("/"); - uriPACKAGE_PROPERTIES_URI = new URI(FORWARD_SLASH_CHAR - + PACKAGE_PROPERTIES_SEGMENT_NAME + FORWARD_SLASH_CHAR - + PACKAGE_CORE_PROPERTIES_NAME); - } catch (URISyntaxException e) { - // Should never happen in production as all data are fixed - } - PACKAGE_ROOT_URI = uriPACKAGE_ROOT_URI; - PACKAGE_RELATIONSHIPS_ROOT_URI = uriPACKAGE_RELATIONSHIPS_ROOT_URI; - CORE_PROPERTIES_URI = uriPACKAGE_PROPERTIES_URI; - - // Make part name from previous URI - PackagePartName tmpPACKAGE_ROOT_PART_NAME = null; - PackagePartName tmpPACKAGE_RELATIONSHIPS_ROOT_PART_NAME = null; - PackagePartName tmpCORE_PROPERTIES_URI = null; - try { - tmpPACKAGE_RELATIONSHIPS_ROOT_PART_NAME = createPartName(PACKAGE_RELATIONSHIPS_ROOT_URI); - tmpCORE_PROPERTIES_URI = createPartName(CORE_PROPERTIES_URI); - tmpPACKAGE_ROOT_PART_NAME = new PackagePartName(PACKAGE_ROOT_URI, - false); - } catch (InvalidFormatException e) { - // Should never happen in production as all data are fixed - } - PACKAGE_RELATIONSHIPS_ROOT_PART_NAME = tmpPACKAGE_RELATIONSHIPS_ROOT_PART_NAME; - CORE_PROPERTIES_PART_NAME = tmpCORE_PROPERTIES_URI; - PACKAGE_ROOT_PART_NAME = tmpPACKAGE_ROOT_PART_NAME; - } - - private static final Pattern missingAuthPattern = Pattern.compile("\\w+://"); - - /** - * Gets the URI for the package root. - * - * @return URI of the package root. - */ - public static URI getPackageRootUri() { - return packageRootUri; - } - - /** - * Know if the specified URI is a relationship part name. - * - * @param partUri - * URI to check. - * @return true if the URI false. - */ - public static boolean isRelationshipPartURI(URI partUri) { - if (partUri == null) - throw new IllegalArgumentException("partUri"); - - return partUri.getPath().matches( - ".*" + RELATIONSHIP_PART_SEGMENT_NAME + ".*" - + RELATIONSHIP_PART_EXTENSION_NAME + "$"); - } - - /** - * Get file name from the specified URI. - */ - public static String getFilename(URI uri) { - if (uri != null) { - String path = uri.getPath(); - int len = path.length(); - int num2 = len; - while (--num2 >= 0) { - char ch1 = path.charAt(num2); - if (ch1 == PackagingURIHelper.FORWARD_SLASH_CHAR) - return path.substring(num2 + 1, len); - } - } - return ""; - } - - /** - * Get the file name without the trailing extension. - */ - public static String getFilenameWithoutExtension(URI uri) { - String filename = getFilename(uri); - int dotIndex = filename.lastIndexOf("."); - if (dotIndex == -1) - return filename; - return filename.substring(0, dotIndex); - } - - /** - * Get the directory path from the specified URI. - */ - public static URI getPath(URI uri) { - if (uri != null) { - String path = uri.getPath(); - int len = path.length(); - int num2 = len; - while (--num2 >= 0) { - char ch1 = path.charAt(num2); - if (ch1 == PackagingURIHelper.FORWARD_SLASH_CHAR) { - try { - return new URI(path.substring(0, num2)); - } catch (URISyntaxException e) { - return null; - } - } - } - } - return null; - } - - /** - * Combine two URIs. - * - * @param prefix the prefix URI - * @param suffix the suffix URI - * - * @return the combined URI - */ - public static URI combine(URI prefix, URI suffix) { - URI retUri = null; - try { - retUri = new URI(combine(prefix.getPath(), suffix.getPath())); - } catch (URISyntaxException e) { - throw new IllegalArgumentException( - "Prefix and suffix can't be combine !"); - } - return retUri; - } - - /** - * Combine a string URI with a prefix and a suffix. - */ - public static String combine(String prefix, String suffix) { - if (!prefix.endsWith("" + FORWARD_SLASH_CHAR) - && !suffix.startsWith("" + FORWARD_SLASH_CHAR)) - return prefix + FORWARD_SLASH_CHAR + suffix; - else if ((!prefix.endsWith("" + FORWARD_SLASH_CHAR) - && suffix.startsWith("" + FORWARD_SLASH_CHAR) || (prefix - .endsWith("" + FORWARD_SLASH_CHAR) && !suffix.startsWith("" - + FORWARD_SLASH_CHAR)))) - return prefix + suffix; - else - return ""; - } - - /** - * Fully relativize the source part URI against the target part URI. - * - * @param sourceURI - * The source part URI. - * @param targetURI - * The target part URI. - * @param msCompatible if true then remove leading slash from the relativized URI. - * This flag violates [M1.4]: A part name shall start with a forward slash ('/') character, but - * allows generating URIs compatible with MS Office and OpenOffice. - * @return A fully relativize part name URI ('word/media/image1.gif', - * '/word/document.xml' => 'media/image1.gif') else - * null. - */ - public static URI relativizeURI(URI sourceURI, URI targetURI, boolean msCompatible) { - StringBuilder retVal = new StringBuilder(); - String[] segmentsSource = sourceURI.getPath().split("/", -1); - String[] segmentsTarget = targetURI.getPath().split("/", -1); - - // If the source URI is empty - if (segmentsSource.length == 0) { - throw new IllegalArgumentException( - "Can't relativize an empty source URI !"); - } - - // If target URI is empty - if (segmentsTarget.length == 0) { - throw new IllegalArgumentException( - "Can't relativize an empty target URI !"); - } - - // If the source is the root, then the relativized - // form must actually be an absolute URI - if(sourceURI.toString().equals("/")) { - String path = targetURI.getPath(); - if(msCompatible && path.length() > 0 && path.charAt(0) == '/') { - try { - targetURI = new URI(path.substring(1)); - } catch (Exception e) { - _logger.log(POILogger.WARN, e); - return null; - } - } - return targetURI; - } - - - // Relativize the source URI against the target URI. - // First up, figure out how many steps along we can go - // and still have them be the same - int segmentsTheSame = 0; - for (int i = 0; i < segmentsSource.length && i < segmentsTarget.length; i++) { - if (segmentsSource[i].equals(segmentsTarget[i])) { - // Match so far, good - segmentsTheSame++; - } else { - break; - } - } - - // If we didn't have a good match or at least except a first empty element - if ((segmentsTheSame == 0 || segmentsTheSame == 1) && - segmentsSource[0].equals("") && segmentsTarget[0].equals("")) { - for (int i = 0; i < segmentsSource.length - 2; i++) { - retVal.append("../"); - } - for (int i = 0; i < segmentsTarget.length; i++) { - if (segmentsTarget[i].equals("")) - continue; - retVal.append(segmentsTarget[i]); - if (i != segmentsTarget.length - 1) - retVal.append("/"); - } - - try { - return new URI(retVal.toString()); - } catch (Exception e) { - _logger.log(POILogger.WARN, e); - return null; - } - } - - // Special case for where the two are the same - if (segmentsTheSame == segmentsSource.length - && segmentsTheSame == segmentsTarget.length) { - if(sourceURI.equals(targetURI)){ - // if source and target are the same they should be resolved to the last segment, - // Example: if a slide references itself, e.g. the source URI is - // "/ppt/slides/slide1.xml" and the targetURI is "slide1.xml" then - // this it should be relativized as "slide1.xml", i.e. the last segment. - retVal.append(segmentsSource[segmentsSource.length - 1]); - } else { - retVal.append(""); - } - - } else { - // Matched for so long, but no more - - // Do we need to go up a directory or two from - // the source to get here? - // (If it's all the way up, then don't bother!) - if (segmentsTheSame == 1) { - retVal.append("/"); - } else { - for (int j = segmentsTheSame; j < segmentsSource.length - 1; j++) { - retVal.append("../"); - } - } - - // Now go from here on down - for (int j = segmentsTheSame; j < segmentsTarget.length; j++) { - if (retVal.length() > 0 - && retVal.charAt(retVal.length() - 1) != '/') { - retVal.append("/"); - } - retVal.append(segmentsTarget[j]); - } - } - - // if the target had a fragment then append it to the result - String fragment = targetURI.getRawFragment(); - if (fragment != null) { - retVal.append("#").append(fragment); - } - - try { - return new URI(retVal.toString()); - } catch (Exception e) { - _logger.log(POILogger.WARN, e); - return null; - } - } - - /** - * Fully relativize the source part URI against the target part URI. - * - * @param sourceURI - * The source part URI. - * @param targetURI - * The target part URI. - * @return A fully relativize part name URI ('word/media/image1.gif', - * '/word/document.xml' => 'media/image1.gif') else - * null. - */ - public static URI relativizeURI(URI sourceURI, URI targetURI) { - return relativizeURI(sourceURI, targetURI, false); - } - - /** - * Resolve a source uri against a target. - * - * @param sourcePartUri - * The source URI. - * @param targetUri - * The target URI. - * @return The resolved URI. - */ - public static URI resolvePartUri(URI sourcePartUri, URI targetUri) { - if (sourcePartUri == null || sourcePartUri.isAbsolute()) { - throw new IllegalArgumentException("sourcePartUri invalid - " - + sourcePartUri); - } - - if (targetUri == null || targetUri.isAbsolute()) { - throw new IllegalArgumentException("targetUri invalid - " - + targetUri); - } - - return sourcePartUri.resolve(targetUri); - } - - /** - * Get URI from a string path. - */ - public static URI getURIFromPath(String path) { - URI retUri; - try { - retUri = toURI(path); - } catch (URISyntaxException e) { - throw new IllegalArgumentException("path"); - } - return retUri; - } - - /** - * Get the source part URI from a specified relationships part. - * - * @param relationshipPartUri - * The relationship part use to retrieve the source part. - * @return The source part URI from the specified relationships part. - */ - public static URI getSourcePartUriFromRelationshipPartUri( - URI relationshipPartUri) { - if (relationshipPartUri == null) - throw new IllegalArgumentException( - "Must not be null"); - - if (!isRelationshipPartURI(relationshipPartUri)) - throw new IllegalArgumentException( - "Must be a relationship part"); - - if (relationshipPartUri.compareTo(PACKAGE_RELATIONSHIPS_ROOT_URI) == 0) - return PACKAGE_ROOT_URI; - - String filename = relationshipPartUri.getPath(); - String filenameWithoutExtension = getFilenameWithoutExtension(relationshipPartUri); - filename = filename - .substring(0, ((filename.length() - filenameWithoutExtension - .length()) - RELATIONSHIP_PART_EXTENSION_NAME.length())); - filename = filename.substring(0, filename.length() - - RELATIONSHIP_PART_SEGMENT_NAME.length() - 1); - filename = combine(filename, filenameWithoutExtension); - return getURIFromPath(filename); - } - - /** - * Create an OPC compliant part name by throwing an exception if the URI is - * not valid. - * - * @param partUri - * The part name URI to validate. - * @return A valid part name object, else null. - * @throws InvalidFormatException - * Throws if the specified URI is not OPC compliant. - */ - public static PackagePartName createPartName(URI partUri) - throws InvalidFormatException { - if (partUri == null) - throw new IllegalArgumentException("partName"); - - return new PackagePartName(partUri, true); - } - - /** - * Create an OPC compliant part name. - * - * @param partName - * The part name to validate. - * @return The correspondant part name if valid, else null. - * @throws InvalidFormatException - * Throws if the specified part name is not OPC compliant. - * @see #createPartName(URI) - */ - public static PackagePartName createPartName(String partName) - throws InvalidFormatException { - URI partNameURI; - try { - partNameURI = toURI(partName); - } catch (URISyntaxException e) { - throw new InvalidFormatException(e.getMessage()); - } - return createPartName(partNameURI); - } - - /** - * Create an OPC compliant part name by resolving it using a base part. - * - * @param partName - * The part name to validate. - * @param relativePart - * The relative base part. - * @return The correspondant part name if valid, else null. - * @throws InvalidFormatException - * Throws if the specified part name is not OPC compliant. - * @see #createPartName(URI) - */ - public static PackagePartName createPartName(String partName, - PackagePart relativePart) throws InvalidFormatException { - URI newPartNameURI; - try { - newPartNameURI = resolvePartUri( - relativePart.getPartName().getURI(), new URI(partName)); - } catch (URISyntaxException e) { - throw new InvalidFormatException(e.getMessage()); - } - return createPartName(newPartNameURI); - } - - /** - * Create an OPC compliant part name by resolving it using a base part. - * - * @param partName - * The part name URI to validate. - * @param relativePart - * The relative base part. - * @return The correspondant part name if valid, else null. - * @throws InvalidFormatException - * Throws if the specified part name is not OPC compliant. - * @see #createPartName(URI) - */ - public static PackagePartName createPartName(URI partName, - PackagePart relativePart) throws InvalidFormatException { - URI newPartNameURI = resolvePartUri( - relativePart.getPartName().getURI(), partName); - return createPartName(newPartNameURI); - } - - /** - * Validate a part URI by returning a boolean. - * ([M1.1],[M1.3],[M1.4],[M1.5],[M1.6]) - * - * (OPC Specifications 8.1.1 Part names) : - * - * Part Name Syntax - * - * The part name grammar is defined as follows: - * - * part_name = 1*( "/" segment ) - * - * segment = 1*( pchar ) - * - * - * (pchar is defined in RFC 3986) - * - * @param partUri - * The URI to validate. - * @return true if the URI is valid to the OPC Specifications, else - * false - * - * @see #createPartName(URI) - */ - public static boolean isValidPartName(URI partUri) { - if (partUri == null) - throw new IllegalArgumentException("partUri"); - - try { - createPartName(partUri); - return true; - } catch (Exception e) { - return false; - } - } - - /** - * Decode a URI by converting all percent encoded character into a String - * character. - * - * @param uri - * The URI to decode. - * @return The specified URI in a String with converted percent encoded - * characters. - */ - public static String decodeURI(URI uri) { - StringBuffer retVal = new StringBuffer(); - String uriStr = uri.toASCIIString(); - char c; - final int length = uriStr.length(); - for (int i = 0; i < length; ++i) { - c = uriStr.charAt(i); - if (c == '%') { - // We certainly found an encoded character, check for length - // now ( '%' HEXDIGIT HEXDIGIT) - if (((length - i) < 2)) { - throw new IllegalArgumentException("The uri " + uriStr - + " contain invalid encoded character !"); - } - - // Decode the encoded character - char decodedChar = (char) Integer.parseInt(uriStr.substring( - i + 1, i + 3), 16); - retVal.append(decodedChar); - i += 2; - continue; - } - retVal.append(c); - } - return retVal.toString(); - } - - /** - * Build a part name where the relationship should be stored ((ex - * /word/document.xml -> /word/_rels/document.xml.rels) - * - * @param partName - * Source part URI - * @return the full path (as URI) of the relation file - * @throws InvalidOperationException - * Throws if the specified URI is a relationshp part. - */ - public static PackagePartName getRelationshipPartName( - PackagePartName partName) { - if (partName == null) - throw new IllegalArgumentException("partName"); - - if (PackagingURIHelper.PACKAGE_ROOT_URI.getPath().equals( - partName.getURI().getPath()) ) - return PackagingURIHelper.PACKAGE_RELATIONSHIPS_ROOT_PART_NAME; - - if (partName.isRelationshipPartURI()) - throw new InvalidOperationException("Can't be a relationship part"); - - String fullPath = partName.getURI().getPath(); - String filename = getFilename(partName.getURI()); - fullPath = fullPath.substring(0, fullPath.length() - filename.length()); - fullPath = combine(fullPath, - PackagingURIHelper.RELATIONSHIP_PART_SEGMENT_NAME); - fullPath = combine(fullPath, filename); - fullPath = fullPath - + PackagingURIHelper.RELATIONSHIP_PART_EXTENSION_NAME; - - PackagePartName retPartName; - try { - retPartName = createPartName(fullPath); - } catch (InvalidFormatException e) { - // Should never happen in production as all data are fixed but in - // case of return null: - return null; - } - return retPartName; - } - - /** - * Convert a string to {@link java.net.URI} - * - * If part name is not a valid URI, it is resolved as follows: - *

    - * 1. Percent-encode each open bracket ([) and close bracket (]). - * 2. Percent-encode each percent (%) character that is not followed by a hexadecimal notation of an octet value. - * 3. Un-percent-encode each percent-encoded unreserved character. - * 4. Un-percent-encode each forward slash (/) and back slash (\). - * 5. Convert all back slashes to forward slashes. - * 6. If present in a segment containing non-dot (?.?) characters, remove trailing dot (?.?) characters from each segment. - * 7. Replace each occurrence of multiple consecutive forward slashes (/) with a single forward slash. - * 8. If a single trailing forward slash (/) is present, remove that trailing forward slash. - * 9. Remove complete segments that consist of three or more dots. - * 10. Resolve the relative reference against the base URI of the part holding the Unicode string, as it is defined - * in ?5.2 of RFC 3986. The path component of the resulting absolute URI is the part name. - *

    - * - * @param value the string to be parsed into a URI - * @return the resolved part name that should be OK to construct a URI - * - * TODO YK: for now this method does only (5). Finish the rest. - */ - public static URI toURI(String value) throws URISyntaxException { - //5. Convert all back slashes to forward slashes - if (value.indexOf("\\") != -1) { - value = value.replace('\\', '/'); - } - - // URI fragemnts (those starting with '#') are not encoded - // and may contain white spaces and raw unicode characters - int fragmentIdx = value.indexOf('#'); - if(fragmentIdx != -1){ - String path = value.substring(0, fragmentIdx); - String fragment = value.substring(fragmentIdx + 1); - - value = path + "#" + encode(fragment); - } - - // trailing white spaces must be url-encoded, see Bugzilla 53282 - if(value.length() > 0 ){ - StringBuilder b = new StringBuilder(); - int idx = value.length() - 1; - for(; idx >= 0; idx--){ - char c = value.charAt(idx); - if(Character.isWhitespace(c) || c == '\u00A0') { - b.append(c); - } else { - break; - } - } - if(b.length() > 0){ - value = value.substring(0, idx+1) + encode(b.reverse().toString()); - } - } - - // MS Office can insert URIs with missing authority, e.g. "http://" or "javascript://" - // append a forward slash to avoid parse exception - if(missingAuthPattern.matcher(value).matches()){ - value += "/"; - } - return new URI(value); - } - - /** - * percent-encode white spaces and characters above 0x80. - *

    - * Examples: - * 'Apache POI' --> 'Apache%20POI' - * 'Apache\u0410POI' --> 'Apache%04%10POI' - * - * @param s the string to encode - * @return the encoded string - */ - public static String encode(String s) { - int n = s.length(); - if (n == 0) return s; - - ByteBuffer bb = ByteBuffer.wrap(s.getBytes(Charset.forName("UTF-8"))); - StringBuilder sb = new StringBuilder(); - while (bb.hasRemaining()) { - int b = bb.get() & 0xff; - if (isUnsafe(b)) { - sb.append('%'); - sb.append(hexDigits[(b >> 4) & 0x0F]); - sb.append(hexDigits[(b >> 0) & 0x0F]); - } else { - sb.append((char)b); - } - } - return sb.toString(); - } - - private final static char[] hexDigits = { - '0', '1', '2', '3', '4', '5', '6', '7', - '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' - }; - - private static boolean isUnsafe(int ch) { - return ch > 0x80 || Character.isWhitespace(ch); - } - -} diff --git a/src/ooxml/java/org/apache/poi/openxml4j/opc/RelationshipSource.java b/src/ooxml/java/org/apache/poi/openxml4j/opc/RelationshipSource.java deleted file mode 100644 index 87c424df5..000000000 --- a/src/ooxml/java/org/apache/poi/openxml4j/opc/RelationshipSource.java +++ /dev/null @@ -1,165 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.openxml4j.opc; - -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.exceptions.InvalidOperationException; -import org.apache.poi.openxml4j.exceptions.OpenXML4JException; - -public interface RelationshipSource { - - /** - * Add a relationship to a part (except relationships part). - * - * @param targetPartName - * Name of the target part. This one must be relative to the - * source root directory of the part. - * @param targetMode - * Mode [Internal|External]. - * @param relationshipType - * Type of relationship. - * @return The newly created and added relationship - */ - public abstract PackageRelationship addRelationship( - PackagePartName targetPartName, TargetMode targetMode, - String relationshipType); - - /** - * Add a relationship to a part (except relationships part). - *

    - * Check rule M1.25: The Relationships part shall not have relationships to - * any other part. Package implementers shall enforce this requirement upon - * the attempt to create such a relationship and shall treat any such - * relationship as invalid. - *

    - * @param targetPartName - * Name of the target part. This one must be relative to the - * source root directory of the part. - * @param targetMode - * Mode [Internal|External]. - * @param relationshipType - * Type of relationship. - * @param id - * Relationship unique id. - * @return The newly created and added relationship - * - * @throws InvalidFormatException - * If the URI point to a relationship part URI. - */ - public abstract PackageRelationship addRelationship( - PackagePartName targetPartName, TargetMode targetMode, - String relationshipType, String id); - - /** - * Adds an external relationship to a part - * (except relationships part). - * - * The targets of external relationships are not - * subject to the same validity checks that internal - * ones are, as the contents is potentially - * any file, URL or similar. - * - * @param target External target of the relationship - * @param relationshipType Type of relationship. - * @return The newly created and added relationship - * @see org.apache.poi.openxml4j.opc.RelationshipSource#addExternalRelationship(java.lang.String, java.lang.String) - */ - public PackageRelationship addExternalRelationship(String target, String relationshipType); - - /** - * Adds an external relationship to a part - * (except relationships part). - * - * The targets of external relationships are not - * subject to the same validity checks that internal - * ones are, as the contents is potentially - * any file, URL or similar. - * - * @param target External target of the relationship - * @param relationshipType Type of relationship. - * @param id Relationship unique id. - * @return The newly created and added relationship - * @see org.apache.poi.openxml4j.opc.RelationshipSource#addExternalRelationship(java.lang.String, java.lang.String) - */ - public PackageRelationship addExternalRelationship(String target, String relationshipType, String id); - - /** - * Delete all the relationships attached to this. - */ - public abstract void clearRelationships(); - - /** - * Delete the relationship specified by its id. - * - * @param id - * The ID identified the part to delete. - */ - public abstract void removeRelationship(String id); - - /** - * Retrieve all the relationships attached to this. - * - * @return This part's relationships. - * @throws OpenXML4JException - */ - public abstract PackageRelationshipCollection getRelationships() - throws InvalidFormatException, OpenXML4JException; - - /** - * Retrieves a package relationship from its id. - * - * @param id - * ID of the package relationship to retrieve. - * @return The package relationship - */ - public abstract PackageRelationship getRelationship(String id); - - /** - * Retrieve all relationships attached to this part which have the specified - * type. - * - * @param relationshipType - * Relationship type filter. - * @return All relationships from this part that have the specified type. - * @throws InvalidFormatException - * If an error occurs while parsing the part. - * @throws InvalidOperationException - * If the package is open in write only mode. - */ - public abstract PackageRelationshipCollection getRelationshipsByType( - String relationshipType) throws InvalidFormatException, - IllegalArgumentException, OpenXML4JException; - - /** - * Knows if the part have any relationships. - * - * @return true if the part have at least one relationship else - * false. - */ - public abstract boolean hasRelationships(); - - /** - * Checks if the specified relationship is part of this package part. - * - * @param rel - * The relationship to check. - * @return true if the specified relationship exists in this part, - * else returns false - */ - public abstract boolean isRelationshipExists(PackageRelationship rel); - -} diff --git a/src/ooxml/java/org/apache/poi/openxml4j/opc/StreamHelper.java b/src/ooxml/java/org/apache/poi/openxml4j/opc/StreamHelper.java deleted file mode 100644 index 860d71159..000000000 --- a/src/ooxml/java/org/apache/poi/openxml4j/opc/StreamHelper.java +++ /dev/null @@ -1,108 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc; - -import java.io.FilterOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Result; -import javax.xml.transform.Source; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; - -import org.w3c.dom.Document; - -public final class StreamHelper { - - private StreamHelper() { - // Do nothing - } - - private static final TransformerFactory transformerFactory = TransformerFactory.newInstance(); - - private static synchronized Transformer getIdentityTransformer() throws TransformerException { - return transformerFactory.newTransformer(); - } - - /** - * Save the document object in the specified output stream. - * - * @param xmlContent - * The XML document. - * @param outStream - * The OutputStream in which the XML document will be written. - * @return true if the xml is successfully written in the stream, - * else false. - */ - public static boolean saveXmlInStream(Document xmlContent, - OutputStream outStream) { - try { - Transformer trans = getIdentityTransformer(); - Source xmlSource = new DOMSource(xmlContent); - // prevent close of stream by transformer: - Result outputTarget = new StreamResult(new FilterOutputStream( - outStream) { - @Override - public void write(byte b[], int off, int len) - throws IOException { - out.write(b, off, len); - } - - @Override - public void close() throws IOException { - out.flush(); // only flush, don't close! - } - }); - trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); - trans.setOutputProperty(OutputKeys.INDENT, "yes"); - trans.setOutputProperty(OutputKeys.STANDALONE, "yes"); - trans.transform(xmlSource, outputTarget); - } catch (TransformerException e) { - return false; - } - return true; - } - - /** - * Copy the input stream into the output stream. - * - * @param inStream - * The source stream. - * @param outStream - * The destination stream. - * @return true if the operation succeed, else return false. - */ - public static boolean copyStream(InputStream inStream, OutputStream outStream) { - try { - byte[] buffer = new byte[1024]; - int bytesRead; - while ((bytesRead = inStream.read(buffer)) >= 0) { - outStream.write(buffer, 0, bytesRead); - } - } catch (Exception e) { - return false; - } - return true; - } -} diff --git a/src/ooxml/java/org/apache/poi/openxml4j/opc/TargetMode.java b/src/ooxml/java/org/apache/poi/openxml4j/opc/TargetMode.java deleted file mode 100644 index 59f45f538..000000000 --- a/src/ooxml/java/org/apache/poi/openxml4j/opc/TargetMode.java +++ /dev/null @@ -1,32 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc; - -/** - * Specifies whether the target of a PackageRelationship is inside or outside a - * Package. - * - * @author Julien Chable - * @version 1.0 - */ -public enum TargetMode { - /** The relationship references a part that is inside the package. */ - INTERNAL, - /** The relationship references a resource that is external to the package. */ - EXTERNAL -} diff --git a/src/ooxml/java/org/apache/poi/openxml4j/opc/ZipPackage.java b/src/ooxml/java/org/apache/poi/openxml4j/opc/ZipPackage.java deleted file mode 100644 index 5b9e2141e..000000000 --- a/src/ooxml/java/org/apache/poi/openxml4j/opc/ZipPackage.java +++ /dev/null @@ -1,609 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.Enumeration; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; -import java.util.zip.ZipOutputStream; - -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.exceptions.InvalidOperationException; -import org.apache.poi.openxml4j.exceptions.NotOfficeXmlFileException; -import org.apache.poi.openxml4j.exceptions.ODFNotOfficeXmlFileException; -import org.apache.poi.openxml4j.exceptions.OpenXML4JException; -import org.apache.poi.openxml4j.exceptions.OpenXML4JRuntimeException; -import org.apache.poi.openxml4j.opc.internal.ContentTypeManager; -import org.apache.poi.openxml4j.opc.internal.FileHelper; -import org.apache.poi.openxml4j.opc.internal.MemoryPackagePart; -import org.apache.poi.openxml4j.opc.internal.PartMarshaller; -import org.apache.poi.openxml4j.opc.internal.ZipContentTypeManager; -import org.apache.poi.openxml4j.opc.internal.ZipHelper; -import org.apache.poi.openxml4j.opc.internal.marshallers.ZipPartMarshaller; -import org.apache.poi.openxml4j.util.ZipEntrySource; -import org.apache.poi.openxml4j.util.ZipFileZipEntrySource; -import org.apache.poi.openxml4j.util.ZipInputStreamZipEntrySource; -import org.apache.poi.openxml4j.util.ZipSecureFile.ThresholdInputStream; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.util.TempFile; - -/** - * Physical zip package. - */ -public final class ZipPackage extends OPCPackage { - private static final String MIMETYPE = "mimetype"; - private static final String SETTINGS_XML = "settings.xml"; - - private static final POILogger LOG = POILogFactory.getLogger(ZipPackage.class); - - /** - * Zip archive, as either a file on disk, - * or a stream - */ - private final ZipEntrySource zipArchive; - - /** - * Constructor. Creates a new, empty ZipPackage. - */ - public ZipPackage() { - super(defaultPackageAccess); - this.zipArchive = null; - - try { - this.contentTypeManager = new ZipContentTypeManager(null, this); - } catch (InvalidFormatException e) { - LOG.log(POILogger.WARN,"Could not parse ZipPackage", e); - } - } - - /** - * Constructor. Opens a Zip based Open XML document from - * an InputStream. - * - * @param in - * Zip input stream to load. - * @param access - * The package access mode. - * @throws IllegalArgumentException - * If the specified input stream not an instance of - * ZipInputStream. - * @throws IOException - * if input stream cannot be opened, read, or closed - */ - ZipPackage(InputStream in, PackageAccess access) throws IOException { - super(access); - ThresholdInputStream zis = ZipHelper.openZipStream(in); - try { - this.zipArchive = new ZipInputStreamZipEntrySource(zis); - } catch (final IOException e) { - IOUtils.closeQuietly(zis); - throw new IOException("Failed to read zip entry source", e); - } - } - - /** - * Constructor. Opens a Zip based Open XML document from a file. - * - * @param path - * The path of the file to open or create. - * @param access - * The package access mode. - * @throws InvalidOperationException If the zip file cannot be opened. - */ - ZipPackage(String path, PackageAccess access) throws InvalidOperationException { - this(new File(path), access); - } - - /** - * Constructor. Opens a Zip based Open XML document from a File. - * - * @param file - * The file to open or create. - * @param access - * The package access mode. - * @throws InvalidOperationException If the zip file cannot be opened. - */ - ZipPackage(File file, PackageAccess access) throws InvalidOperationException { - super(access); - - ZipEntrySource ze; - try { - final ZipFile zipFile = ZipHelper.openZipFile(file); // NOSONAR - ze = new ZipFileZipEntrySource(zipFile); - } catch (IOException e) { - // probably not happening with write access - not sure how to handle the default read-write access ... - if (access == PackageAccess.WRITE) { - throw new InvalidOperationException("Can't open the specified file: '" + file + "'", e); - } - LOG.log(POILogger.ERROR, "Error in zip file "+file+" - falling back to stream processing (i.e. ignoring zip central directory)"); - ze = openZipEntrySourceStream(file); - } - this.zipArchive = ze; - } - - private static ZipEntrySource openZipEntrySourceStream(File file) throws InvalidOperationException { - final FileInputStream fis; - // Acquire a resource that is needed to read the next level of openZipEntrySourceStream - try { - // open the file input stream - fis = new FileInputStream(file); // NOSONAR - } catch (final FileNotFoundException e) { - // If the source cannot be acquired, abort (no resources to free at this level) - throw new InvalidOperationException("Can't open the specified file input stream from file: '" + file + "'", e); - } - - // If an error occurs while reading the next level of openZipEntrySourceStream, free the acquired resource - try { - // read from the file input stream - return openZipEntrySourceStream(fis); - } catch (final Exception e) { - // abort: close the file input stream - IOUtils.closeQuietly(fis); - if (e instanceof InvalidOperationException) { - throw (InvalidOperationException)e; - } else { - throw new InvalidOperationException("Failed to read the file input stream from file: '" + file + "'", e); - } - } - } - - private static ZipEntrySource openZipEntrySourceStream(FileInputStream fis) throws InvalidOperationException { - final ThresholdInputStream zis; - // Acquire a resource that is needed to read the next level of openZipEntrySourceStream - try { - // open the zip input stream - zis = ZipHelper.openZipStream(fis); // NOSONAR - } catch (final IOException e) { - // If the source cannot be acquired, abort (no resources to free at this level) - throw new InvalidOperationException("Could not open the file input stream", e); - } - - // If an error occurs while reading the next level of openZipEntrySourceStream, free the acquired resource - try { - // read from the zip input stream - return openZipEntrySourceStream(zis); - } catch (final Exception e) { - // abort: close the zip input stream - IOUtils.closeQuietly(zis); - if (e instanceof InvalidOperationException) { - throw (InvalidOperationException)e; - } else { - throw new InvalidOperationException("Failed to read the zip entry source stream", e); - } - } - } - - private static ZipEntrySource openZipEntrySourceStream(ThresholdInputStream zis) throws InvalidOperationException { - // Acquire the final level resource. If this is acquired successfully, the zip package was read successfully from the input stream - try { - // open the zip entry source stream - return new ZipInputStreamZipEntrySource(zis); - } catch (IOException e) { - throw new InvalidOperationException("Could not open the specified zip entry source stream", e); - } - } - - /** - * Constructor. Opens a Zip based Open XML document from - * a custom ZipEntrySource, typically an open archive - * from another system - * - * @param zipEntry - * Zip data to load. - * @param access - * The package access mode. - */ - ZipPackage(ZipEntrySource zipEntry, PackageAccess access) { - super(access); - this.zipArchive = zipEntry; - } - - /** - * Retrieves the parts from this package. We assume that the package has not - * been yet inspect to retrieve all the parts, this method will open the - * archive and look for all parts contain inside it. If the package part - * list is not empty, it will be emptied. - * - * @return All parts contain in this package. - * @throws InvalidFormatException if the package is not valid. - */ - @Override - protected PackagePart[] getPartsImpl() throws InvalidFormatException { - if (this.partList == null) { - // The package has just been created, we create an empty part - // list. - this.partList = new PackagePartCollection(); - } - - if (this.zipArchive == null) { - return this.partList.values().toArray( - new PackagePart[this.partList.values().size()]); - } - - // First we need to parse the content type part - Enumeration entries = this.zipArchive.getEntries(); - while (entries.hasMoreElements()) { - ZipEntry entry = entries.nextElement(); - if (entry.getName().equalsIgnoreCase( - ContentTypeManager.CONTENT_TYPES_PART_NAME)) { - try { - this.contentTypeManager = new ZipContentTypeManager( - getZipArchive().getInputStream(entry), this); - } catch (IOException e) { - throw new InvalidFormatException(e.getMessage(), e); - } - break; - } - } - - // At this point, we should have loaded the content type part - if (this.contentTypeManager == null) { - // Is it a different Zip-based format? - int numEntries = 0; - boolean hasMimetype = false; - boolean hasSettingsXML = false; - entries = this.zipArchive.getEntries(); - while (entries.hasMoreElements()) { - final ZipEntry entry = entries.nextElement(); - final String name = entry.getName(); - if (MIMETYPE.equals(name)) { - hasMimetype = true; - } - if (SETTINGS_XML.equals(name)) { - hasSettingsXML = true; - } - numEntries++; - } - if (hasMimetype && hasSettingsXML) { - throw new ODFNotOfficeXmlFileException( - "The supplied data appears to be in ODF (Open Document) Format. " + - "Formats like these (eg ODS, ODP) are not supported, try Apache ODFToolkit"); - } - if (numEntries == 0) { - throw new NotOfficeXmlFileException( - "No valid entries or contents found, this is not a valid OOXML " + - "(Office Open XML) file"); - } - - // Fallback exception - throw new InvalidFormatException( - "Package should contain a content type part [M1.13]"); - } - - // Now create all the relationships - // (Need to create relationships before other - // parts, otherwise we might create a part before - // its relationship exists, and then it won't tie up) - entries = this.zipArchive.getEntries(); - while (entries.hasMoreElements()) { - ZipEntry entry = entries.nextElement(); - PackagePartName partName = buildPartName(entry); - if(partName == null) { - continue; - } - - // Only proceed for Relationships at this stage - String contentType = contentTypeManager.getContentType(partName); - if (contentType != null && contentType.equals(ContentTypes.RELATIONSHIPS_PART)) { - try { - PackagePart part = new ZipPackagePart(this, entry, partName, contentType); - partList.put(partName, part); - } catch (InvalidOperationException e) { - throw new InvalidFormatException(e.getMessage(), e); - } - } - } - - // Then we can go through all the other parts - entries = this.zipArchive.getEntries(); - while (entries.hasMoreElements()) { - ZipEntry entry = entries.nextElement(); - PackagePartName partName = buildPartName(entry); - if(partName == null) { - continue; - } - - String contentType = contentTypeManager.getContentType(partName); - if (contentType != null && contentType.equals(ContentTypes.RELATIONSHIPS_PART)) { - // Already handled - } - else if (contentType != null) { - try { - PackagePart part = new ZipPackagePart(this, entry, partName, contentType); - partList.put(partName, part); - } catch (InvalidOperationException e) { - throw new InvalidFormatException(e.getMessage(), e); - } - } else { - throw new InvalidFormatException( - "The part " + partName.getURI().getPath() - + " does not have any content type ! Rule: Package require content types when retrieving a part from a package. [M.1.14]"); - } - } - - return partList.values().toArray(new ZipPackagePart[partList.size()]); - } - - /** - * Builds a PackagePartName for the given ZipEntry, - * or null if it's the content types / invalid part - */ - private PackagePartName buildPartName(ZipEntry entry) { - try { - // We get an error when we parse [Content_Types].xml - // because it's not a valid URI. - if (entry.getName().equalsIgnoreCase( - ContentTypeManager.CONTENT_TYPES_PART_NAME)) { - return null; - } - return PackagingURIHelper.createPartName(ZipHelper - .getOPCNameFromZipItemName(entry.getName())); - } catch (Exception e) { - // We assume we can continue, even in degraded mode ... - LOG.log(POILogger.WARN,"Entry " - + entry.getName() - + " is not valid, so this part won't be add to the package.", e); - return null; - } - } - - /** - * Create a new MemoryPackagePart from the specified URI and content type - * - * - * aram partName The part URI. - * - * @param contentType - * The part content type. - * @return The newly created zip package part, else null. - */ - @Override - protected PackagePart createPartImpl(PackagePartName partName, - String contentType, boolean loadRelationships) { - if (contentType == null) { - throw new IllegalArgumentException("contentType"); - } - - if (partName == null) { - throw new IllegalArgumentException("partName"); - } - - try { - return new MemoryPackagePart(this, partName, contentType, loadRelationships); - } catch (InvalidFormatException e) { - LOG.log(POILogger.WARN, e); - return null; - } - } - - /** - * Delete a part from the package - * - * @throws IllegalArgumentException - * Throws if the part URI is nulll or invalid. - */ - @Override - protected void removePartImpl(PackagePartName partName) { - if (partName == null) { - throw new IllegalArgumentException("partUri"); - } - } - - /** - * Flush the package. Do nothing. - */ - @Override - protected void flushImpl() { - // Do nothing - } - - /** - * Close and save the package. - * - * @see #close() - */ - @Override - protected void closeImpl() throws IOException { - // Flush the package - flush(); - - if (this.originalPackagePath == null || "".equals(this.originalPackagePath)) { - return; - } - - // Save the content - File targetFile = new File(this.originalPackagePath); - if (!targetFile.exists()) { - throw new InvalidOperationException( - "Can't close a package not previously open with the open() method !"); - } - - // Case of a package previously open - String tempFileName = generateTempFileName(FileHelper.getDirectory(targetFile)); - File tempFile = TempFile.createTempFile(tempFileName, ".tmp"); - - // Save the final package to a temporary file - try { - save(tempFile); - } finally { - // Close the current zip file, so we can overwrite it on all platforms - IOUtils.closeQuietly(this.zipArchive); - try { - // Copy the new file over the old one - FileHelper.copyFile(tempFile, targetFile); - } finally { - // Either the save operation succeed or not, we delete the temporary file - if (!tempFile.delete()) { - LOG.log(POILogger.WARN, "The temporary file: '" - + targetFile.getAbsolutePath() - + "' cannot be deleted ! Make sure that no other application use it."); - } - } - } - } - - /** - * Create a unique identifier to be use as a temp file name. - * - * @return A unique identifier use to be use as a temp file name. - */ - private synchronized String generateTempFileName(File directory) { - File tmpFilename; - do { - tmpFilename = new File(directory.getAbsoluteFile() + File.separator - + "OpenXML4J" + System.nanoTime()); - } while (tmpFilename.exists()); - return FileHelper.getFilename(tmpFilename.getAbsoluteFile()); - } - - /** - * Close the package without saving the document. Discard all the changes - * made to this package. - */ - @Override - protected void revertImpl() { - try { - if (this.zipArchive != null) { - this.zipArchive.close(); - } - } catch (IOException e) { - // Do nothing, user dont have to know - } - } - - /** - * Implement the getPart() method to retrieve a part from its URI in the - * current package - * - * - * @see #getPart(PackageRelationship) - */ - @Override - protected PackagePart getPartImpl(PackagePartName partName) { - if (partList.containsKey(partName)) { - return partList.get(partName); - } - return null; - } - - /** - * Save this package into the specified stream - * - * - * @param outputStream - * The stream use to save this package. - * - * @see #save(OutputStream) - */ - @Override - public void saveImpl(OutputStream outputStream) { - // Check that the document was open in write mode - throwExceptionIfReadOnly(); - - final ZipOutputStream zos; - try { - if (!(outputStream instanceof ZipOutputStream)) { - zos = new ZipOutputStream(outputStream); - } else { - zos = (ZipOutputStream) outputStream; - } - - // If the core properties part does not exist in the part list, - // we save it as well - if (this.getPartsByRelationshipType(PackageRelationshipTypes.CORE_PROPERTIES).size() == 0 && - this.getPartsByRelationshipType(PackageRelationshipTypes.CORE_PROPERTIES_ECMA376).size() == 0 ) { - LOG.log(POILogger.DEBUG,"Save core properties part"); - - // Ensure that core properties are added if missing - getPackageProperties(); - // Add core properties to part list ... - addPackagePart(this.packageProperties); - // ... and to add its relationship ... - this.relationships.addRelationship(this.packageProperties - .getPartName().getURI(), TargetMode.INTERNAL, - PackageRelationshipTypes.CORE_PROPERTIES, null); - // ... and the content if it has not been added yet. - if (!this.contentTypeManager - .isContentTypeRegister(ContentTypes.CORE_PROPERTIES_PART)) { - this.contentTypeManager.addContentType( - this.packageProperties.getPartName(), - ContentTypes.CORE_PROPERTIES_PART); - } - } - - // Save package relationships part. - LOG.log(POILogger.DEBUG,"Save package relationships"); - ZipPartMarshaller.marshallRelationshipPart(this.getRelationships(), - PackagingURIHelper.PACKAGE_RELATIONSHIPS_ROOT_PART_NAME, - zos); - - // Save content type part. - LOG.log(POILogger.DEBUG,"Save content types part"); - this.contentTypeManager.save(zos); - - // Save parts. - for (PackagePart part : getParts()) { - // If the part is a relationship part, we don't save it, it's - // the source part that will do the job. - if (part.isRelationshipPart()) { - continue; - } - - final PackagePartName ppn = part.getPartName(); - LOG.log(POILogger.DEBUG,"Save part '" + ZipHelper.getZipItemNameFromOPCName(ppn.getName()) + "'"); - PartMarshaller marshaller = partMarshallers.get(part._contentType); - String errMsg = "The part " + ppn.getURI() + " failed to be saved in the stream with marshaller "; - - if (marshaller != null) { - if (!marshaller.marshall(part, zos)) { - throw new OpenXML4JException(errMsg + marshaller); - } - } else { - if (!defaultPartMarshaller.marshall(part, zos)) { - throw new OpenXML4JException(errMsg + defaultPartMarshaller); - } - } - } - zos.close(); - } catch (OpenXML4JRuntimeException e) { - // no need to wrap this type of Exception - throw e; - } catch (Exception e) { - throw new OpenXML4JRuntimeException( - "Fail to save: an error occurs while saving the package : " - + e.getMessage(), e); - } - } - - /** - * Get the zip archive - * - * @return The zip archive. - */ - public ZipEntrySource getZipArchive() { - return zipArchive; - } -} diff --git a/src/ooxml/java/org/apache/poi/openxml4j/opc/ZipPackagePart.java b/src/ooxml/java/org/apache/poi/openxml4j/opc/ZipPackagePart.java deleted file mode 100644 index 58bbbfe22..000000000 --- a/src/ooxml/java/org/apache/poi/openxml4j/opc/ZipPackagePart.java +++ /dev/null @@ -1,144 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.zip.ZipEntry; - -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.exceptions.InvalidOperationException; -import org.apache.poi.openxml4j.exceptions.OpenXML4JException; -import org.apache.poi.openxml4j.opc.internal.marshallers.ZipPartMarshaller; -import org.apache.poi.util.NotImplemented; - -/** - * Zip implementation of a PackagePart. - * - * @author Julien Chable - * @version 1.0 - * @see PackagePart - */ -public class ZipPackagePart extends PackagePart { - - /** - * The zip entry corresponding to this part. - */ - private ZipEntry zipEntry; - - /** - * Constructor. - * - * @param container - * The container package. - * @param partName - * Part name. - * @param contentType - * Content type. - * @throws InvalidFormatException - * Throws if the content of this part invalid. - */ - public ZipPackagePart(OPCPackage container, PackagePartName partName, - String contentType) throws InvalidFormatException { - super(container, partName, contentType); - } - - /** - * Constructor. - * - * @param container - * The container package. - * @param zipEntry - * The zip entry corresponding to this part. - * @param partName - * The part name. - * @param contentType - * Content type. - * @throws InvalidFormatException - * Throws if the content of this part is invalid. - */ - public ZipPackagePart(OPCPackage container, ZipEntry zipEntry, - PackagePartName partName, String contentType) - throws InvalidFormatException { - super(container, partName, contentType); - this.zipEntry = zipEntry; - } - - /** - * Get the zip entry of this part. - * - * @return The zip entry in the zip structure coresponding to this part. - */ - public ZipEntry getZipArchive() { - return zipEntry; - } - - /** - * Implementation of the getInputStream() which return the inputStream of - * this part zip entry. - * - * @return Input stream of this part zip entry. - */ - @Override - protected InputStream getInputStreamImpl() throws IOException { - // We use the getInputStream() method from java.util.zip.ZipFile - // class which return an InputStream to this part zip entry. - return ((ZipPackage) _container).getZipArchive() - .getInputStream(zipEntry); - } - - /** - * Implementation of the getOutputStream(). Return null. Normally - * will never be called since the MemoryPackage is use instead. - * - * @return null - */ - @Override - protected OutputStream getOutputStreamImpl() { - return null; - } - - @Override - public long getSize() { - return zipEntry.getSize(); - } - - @Override - public boolean save(OutputStream os) throws OpenXML4JException { - return new ZipPartMarshaller().marshall(this, os); - } - - @Override - @NotImplemented - public boolean load(InputStream ios) { - throw new InvalidOperationException("Method not implemented !"); - } - - @Override - @NotImplemented - public void close() { - throw new InvalidOperationException("Method not implemented !"); - } - - @Override - @NotImplemented - public void flush() { - throw new InvalidOperationException("Method not implemented !"); - } -} diff --git a/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/ContentType.java b/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/ContentType.java deleted file mode 100644 index a56e0cdf3..000000000 --- a/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/ContentType.java +++ /dev/null @@ -1,264 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc.internal; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; - -/** - * Represents a immutable MIME ContentType value (RFC 2616 §3.7) - *

    - * media-type = type "/" subtype *( ";" parameter ) type = token
    - * subtype = token
    - *

    - * Rule M1.13 : Package implementers shall only create and only recognize parts - * with a content type; format designers shall specify a content type for each - * part included in the format. Content types for package parts shall fit the - * definition and syntax for media types as specified in RFC 2616, \§3.7. - *

    - * Rule M1.14: Content types shall not use linear white space either between the - * type and subtype or between an attribute and its value. Content types also - * shall not have leading or trailing white spaces. Package implementers shall - * create only such content types and shall require such content types when - * retrieving a part from a package; format designers shall specify only such - * content types for inclusion in the format. - *

    - * @author Julien Chable - * @version 0.1 - * - * @see http://www.ietf.org/rfc/rfc2045.txt - * @see http://www.ietf.org/rfc/rfc2616.txt - */ -public final class ContentType { - - /** - * Type in Type/Subtype. - */ - private final String type; - - /** - * Subtype - */ - private final String subType; - - /** - * Parameters - */ - private final Map parameters; - - /** - * Media type compiled pattern, without parameters - */ - private final static Pattern patternTypeSubType; - /** - * Media type compiled pattern, with parameters. - */ - private final static Pattern patternTypeSubTypeParams; - /** - * Pattern to match on just the parameters part, to work - * around the Java Regexp group capture behaviour - */ - private final static Pattern patternParams; - - static { - /* - * token = 1* - * - * separators = "(" | ")" | "<" | ">" | "@" | "," | ";" | ":" | "\" | - * <"> | "/" | "[" | "]" | "?" | "=" | "{" | "}" | SP | HT - * - * CTL = - * - * CHAR = - */ - String token = "[\\x21-\\x7E&&[^\\(\\)<>@,;:\\\\/\"\\[\\]\\?={}\\x20\\x09]]"; - - /* - * parameter = attribute "=" value - * - * attribute = token - * - * value = token | quoted-string - */ - String parameter = "(" + token + "+)=(\"?" + token + "+\"?)"; - /* - * Pattern for media type. - * - * Don't allow comment, rule M1.15: The package implementer shall - * require a content type that does not include comments and the format - * designer shall specify such a content type. - * - * comment = "(" *( ctext | quoted-pair | comment ) ")" - * - * ctext = - * - * TEXT = - * - * LWS = [CRLF] 1*( SP | HT ) - * - * CR = - * - * LF = - * - * SP = - * - * HT = - * - * quoted-pair = "\" CHAR - */ - - patternTypeSubType = Pattern.compile("^(" + token + "+)/(" + - token + "+)$"); - patternTypeSubTypeParams = Pattern.compile("^(" + token + "+)/(" + - token + "+)(;" + parameter + ")*$"); - patternParams = Pattern.compile(";" + parameter); - } - - /** - * Constructor. Check the input with the RFC 2616 grammar. - * - * @param contentType - * The content type to store. - * @throws InvalidFormatException - * If the specified content type is not valid with RFC 2616. - */ - public ContentType(String contentType) throws InvalidFormatException { - Matcher mMediaType = patternTypeSubType.matcher(contentType); - if (!mMediaType.matches()) { - // How about with parameters? - mMediaType = patternTypeSubTypeParams.matcher(contentType); - } - if (!mMediaType.matches()) { - throw new InvalidFormatException( - "The specified content type '" - + contentType - + "' is not compliant with RFC 2616: malformed content type."); - } - - // Type/subtype - if (mMediaType.groupCount() >= 2) { - this.type = mMediaType.group(1); - this.subType = mMediaType.group(2); - - // Parameters - this.parameters = new HashMap(); - // Java RegExps are unhelpful, and won't do multiple group captures - // See http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html#cg - if (mMediaType.groupCount() >= 5) { - Matcher mParams = patternParams.matcher(contentType.substring(mMediaType.end(2))); - while (mParams.find()) { - this.parameters.put(mParams.group(1), mParams.group(2)); - } - } - } else { - // missing media type and subtype - this.type = ""; - this.subType = ""; - this.parameters = Collections.emptyMap(); - } - } - - /** - * Returns the content type as a string, including parameters - */ - @Override - public final String toString() { - return toString(true); - } - - public final String toString(boolean withParameters) { - StringBuffer retVal = new StringBuffer(); - retVal.append(this.getType()); - retVal.append("/"); - retVal.append(this.getSubType()); - - if (withParameters) { - for (Entry me : parameters.entrySet()) { - retVal.append(";"); - retVal.append(me.getKey()); - retVal.append("="); - retVal.append(me.getValue()); - } - } - return retVal.toString(); - } - - @Override - public boolean equals(Object obj) { - return (!(obj instanceof ContentType)) - || (this.toString().equalsIgnoreCase(obj.toString())); - } - - @Override - public int hashCode() { - return this.toString().hashCode(); - } - - /* Getters */ - - /** - * Get the subtype. - * - * @return The subtype of this content type. - */ - public String getSubType() { - return this.subType; - } - - /** - * Get the type. - * - * @return The type of this content type. - */ - public String getType() { - return this.type; - } - - /** - * Does this content type have any parameters associated with it? - */ - public boolean hasParameters() { - return (parameters != null) && !parameters.isEmpty(); - } - - /** - * Return the parameter keys - */ - public String[] getParameterKeys() { - if (parameters == null) - return new String[0]; - return parameters.keySet().toArray(new String[parameters.size()]); - } - - /** - * Gets the value associated to the specified key. - * - * @param key - * The key of the key/value pair. - * @return The value associated to the specified key. - */ - public String getParameter(String key) { - return parameters.get(key); - } -} diff --git a/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/ContentTypeManager.java b/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/ContentTypeManager.java deleted file mode 100644 index 750f9cd71..000000000 --- a/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/ContentTypeManager.java +++ /dev/null @@ -1,479 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc.internal; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Locale; -import java.util.Map.Entry; -import java.util.TreeMap; - -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.exceptions.InvalidOperationException; -import org.apache.poi.openxml4j.exceptions.OpenXML4JRuntimeException; -import org.apache.poi.openxml4j.opc.*; -import org.apache.poi.util.DocumentHelper; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.NodeList; -import org.xml.sax.SAXException; - -/** - * Manage package content types ([Content_Types].xml part). - * - * @author Julien Chable - */ -public abstract class ContentTypeManager { - - /** - * Content type part name. - */ - public static final String CONTENT_TYPES_PART_NAME = "[Content_Types].xml"; - - /** - * Content type namespace - */ - public static final String TYPES_NAMESPACE_URI = PackageNamespaces.CONTENT_TYPES; - - /* Xml elements in content type part */ - - private static final String TYPES_TAG_NAME = "Types"; - - private static final String DEFAULT_TAG_NAME = "Default"; - - private static final String EXTENSION_ATTRIBUTE_NAME = "Extension"; - - private static final String CONTENT_TYPE_ATTRIBUTE_NAME = "ContentType"; - - private static final String OVERRIDE_TAG_NAME = "Override"; - - private static final String PART_NAME_ATTRIBUTE_NAME = "PartName"; - - /** - * Reference to the package using this content type manager. - */ - protected OPCPackage container; - - /** - * Default content type tree. - */ - private TreeMap defaultContentType; - - /** - * Override content type tree. - */ - private TreeMap overrideContentType; - - /** - * Constructor. Parses the content of the specified input stream. - * - * @param in - * If different of null then the content types part is - * retrieve and parse. - * @throws InvalidFormatException - * If the content types part content is not valid. - */ - public ContentTypeManager(InputStream in, OPCPackage pkg) - throws InvalidFormatException { - this.container = pkg; - this.defaultContentType = new TreeMap(); - if (in != null) { - try { - parseContentTypesFile(in); - } catch (InvalidFormatException e) { - InvalidFormatException ex = new InvalidFormatException("Can't read content types part !"); - - // here it is useful to add the cause to not loose the original stack-trace - ex.initCause(e); - - throw ex; - } - } - } - - /** - * Build association extention-> content type (will be stored in - * [Content_Types].xml) for example ContentType="image/png" Extension="png" - *

    - * [M2.8]: When adding a new part to a package, the package implementer - * shall ensure that a content type for that part is specified in the - * Content Types stream; the package implementer shall perform the steps - * described in §9.1.2.3: - *

    - * 1. Get the extension from the part name by taking the substring to the - * right of the rightmost occurrence of the dot character (.) from the - * rightmost segment. - *

    - * 2. If a part name has no extension, a corresponding Override element - * shall be added to the Content Types stream. - *

    - * 3. Compare the resulting extension with the values specified for the - * Extension attributes of the Default elements in the Content Types stream. - * The comparison shall be case-insensitive ASCII. - *

    - * 4. If there is a Default element with a matching Extension attribute, - * then the content type of the new part shall be compared with the value of - * the ContentType attribute. The comparison might be case-sensitive and - * include every character regardless of the role it plays in the - * content-type grammar of RFC 2616, or it might follow the grammar of RFC - * 2616. - *

    - * a. If the content types match, no further action is required. - *

    - * b. If the content types do not match, a new Override element shall be - * added to the Content Types stream. . - *

    - * 5. If there is no Default element with a matching Extension attribute, a - * new Default element or Override element shall be added to the Content - * Types stream. - *

    - */ - public void addContentType(PackagePartName partName, String contentType) { - boolean defaultCTExists = this.defaultContentType.containsValue(contentType); - String extension = partName.getExtension().toLowerCase(Locale.ROOT); - if ((extension.length() == 0) - || (this.defaultContentType.containsKey(extension) && !defaultCTExists)) - this.addOverrideContentType(partName, contentType); - else if (!defaultCTExists) - this.addDefaultContentType(extension, contentType); - } - - /** - * Add an override content type for a specific part. - * - * @param partName - * Name of the part. - * @param contentType - * Content type of the part. - */ - private void addOverrideContentType(PackagePartName partName, - String contentType) { - if (overrideContentType == null) - overrideContentType = new TreeMap(); - overrideContentType.put(partName, contentType); - } - - /** - * Add a content type associated with the specified extension. - * - * @param extension - * The part name extension to bind to a content type. - * @param contentType - * The content type associated with the specified extension. - */ - private void addDefaultContentType(String extension, String contentType) { - // Remark : Originally the latest parameter was : - // contentType.toLowerCase(). Change due to a request ID 1996748. - defaultContentType.put(extension.toLowerCase(Locale.ROOT), contentType); - } - - /** - *

    - * Delete a content type based on the specified part name. If the specified - * part name is register with an override content type, then this content - * type is remove, else the content type is remove in the default content - * type list if it exists and if no part is associated with it yet. - *

    - * Check rule M2.4: The package implementer shall require that the Content - * Types stream contain one of the following for every part in the package: - * One matching Default element One matching Override element Both a - * matching Default element and a matching Override element, in which case - * the Override element takes precedence. - *

    - * @param partName - * The part URI associated with the override content type to - * delete. - * @exception InvalidOperationException - * Throws if - */ - public void removeContentType(PackagePartName partName) - throws InvalidOperationException { - if (partName == null) - throw new IllegalArgumentException("partName"); - - /* Override content type */ - if (this.overrideContentType != null - && (this.overrideContentType.get(partName) != null)) { - // Remove the override definition for the specified part. - this.overrideContentType.remove(partName); - return; - } - - /* Default content type */ - String extensionToDelete = partName.getExtension(); - boolean deleteDefaultContentTypeFlag = true; - if (this.container != null) { - try { - for (PackagePart part : this.container.getParts()) { - if (!part.getPartName().equals(partName) - && part.getPartName().getExtension() - .equalsIgnoreCase(extensionToDelete)) { - deleteDefaultContentTypeFlag = false; - break; - } - } - } catch (InvalidFormatException e) { - throw new InvalidOperationException(e.getMessage()); - } - } - - // Remove the default content type, no other part use this content type. - if (deleteDefaultContentTypeFlag) { - this.defaultContentType.remove(extensionToDelete); - } - - /* - * Check rule 2.4: The package implementer shall require that the - * Content Types stream contain one of the following for every part in - * the package: One matching Default element One matching Override - * element Both a matching Default element and a matching Override - * element, in which case the Override element takes precedence. - */ - if (this.container != null) { - try { - for (PackagePart part : this.container.getParts()) { - if (!part.getPartName().equals(partName) - && this.getContentType(part.getPartName()) == null) - throw new InvalidOperationException( - "Rule M2.4 is not respected: Nor a default element or override element is associated with the part: " - + part.getPartName().getName()); - } - } catch (InvalidFormatException e) { - throw new InvalidOperationException(e.getMessage()); - } - } - } - - /** - * Check if the specified content type is already register. - * - * @param contentType - * The content type to check. - * @return true if the specified content type is already - * register, then false. - */ - public boolean isContentTypeRegister(String contentType) { - if (contentType == null) - throw new IllegalArgumentException("contentType"); - - return (this.defaultContentType.values().contains(contentType) || (this.overrideContentType != null && this.overrideContentType - .values().contains(contentType))); - } - - /** - * Get the content type for the specified part, if any. - *

    - * Rule [M2.9]: To get the content type of a part, the package implementer - * shall perform the steps described in §9.1.2.4: - *

    - * 1. Compare the part name with the values specified for the PartName - * attribute of the Override elements. The comparison shall be - * case-insensitive ASCII. - *

    - * 2. If there is an Override element with a matching PartName attribute, - * return the value of its ContentType attribute. No further action is - * required. - *

    - * 3. If there is no Override element with a matching PartName attribute, - * then a. Get the extension from the part name by taking the substring to - * the right of the rightmost occurrence of the dot character (.) from the - * rightmost segment. b. Check the Default elements of the Content Types - * stream, comparing the extension with the value of the Extension - * attribute. The comparison shall be case-insensitive ASCII. - *

    - * 4. If there is a Default element with a matching Extension attribute, - * return the value of its ContentType attribute. No further action is - * required. - *

    - * 5. If neither Override nor Default elements with matching attributes are - * found for the specified part name, the implementation shall not map this - * part name to a part. - *

    - * @param partName - * The URI part to check. - * @return The content type associated with the URI (in case of an override - * content type) or the extension (in case of default content type), - * else null. - * - * @exception OpenXML4JRuntimeException - * Throws if the content type manager is not able to find the - * content from an existing part. - */ - public String getContentType(PackagePartName partName) { - if (partName == null) - throw new IllegalArgumentException("partName"); - - if ((this.overrideContentType != null) - && this.overrideContentType.containsKey(partName)) - return this.overrideContentType.get(partName); - - String extension = partName.getExtension().toLowerCase(Locale.ROOT); - if (this.defaultContentType.containsKey(extension)) - return this.defaultContentType.get(extension); - - /* - * [M2.4] : The package implementer shall require that the Content Types - * stream contain one of the following for every part in the package: - * One matching Default element, One matching Override element, Both a - * matching Default element and a matching Override element, in which - * case the Override element takes precedence. - */ - if (this.container != null && this.container.getPart(partName) != null) { - throw new OpenXML4JRuntimeException( - "Rule M2.4 exception : this error should NEVER happen! If you can provide the triggering file, then please raise a bug at https://bz.apache.org/bugzilla/enter_bug.cgi?product=POI and attach the file that triggers it, thanks!"); - } - return null; - } - - /** - * Clear all content types. - */ - public void clearAll() { - this.defaultContentType.clear(); - if (this.overrideContentType != null) - this.overrideContentType.clear(); - } - - /** - * Clear all override content types. - * - */ - public void clearOverrideContentTypes() { - if (this.overrideContentType != null) - this.overrideContentType.clear(); - } - - /** - * Parse the content types part. - * - * @throws InvalidFormatException - * Throws if the content type doesn't exist or the XML format is - * invalid. - */ - private void parseContentTypesFile(InputStream in) - throws InvalidFormatException { - try { - Document xmlContentTypetDoc = DocumentHelper.readDocument(in); - - // Default content types - NodeList defaultTypes = xmlContentTypetDoc.getDocumentElement().getElementsByTagNameNS(TYPES_NAMESPACE_URI, DEFAULT_TAG_NAME); - int defaultTypeCount = defaultTypes.getLength(); - for (int i = 0; i < defaultTypeCount; i++) { - Element element = (Element) defaultTypes.item(i); - String extension = element.getAttribute(EXTENSION_ATTRIBUTE_NAME); - String contentType = element.getAttribute(CONTENT_TYPE_ATTRIBUTE_NAME); - addDefaultContentType(extension, contentType); - } - - // Overriden content types - NodeList overrideTypes = xmlContentTypetDoc.getDocumentElement().getElementsByTagNameNS(TYPES_NAMESPACE_URI, OVERRIDE_TAG_NAME); - int overrideTypeCount = overrideTypes.getLength(); - for (int i = 0; i < overrideTypeCount; i++) { - Element element = (Element) overrideTypes.item(i); - URI uri = new URI(element.getAttribute(PART_NAME_ATTRIBUTE_NAME)); - PackagePartName partName = PackagingURIHelper.createPartName(uri); - String contentType = element.getAttribute(CONTENT_TYPE_ATTRIBUTE_NAME); - addOverrideContentType(partName, contentType); - } - } catch (URISyntaxException urie) { - throw new InvalidFormatException(urie.getMessage()); - } catch (SAXException e) { - throw new InvalidFormatException(e.getMessage()); - } catch (IOException e) { - throw new InvalidFormatException(e.getMessage()); - } - } - - /** - * Save the contents type part. - * - * @param outStream - * The output stream use to save the XML content of the content - * types part. - * @return true if the operation success, else false. - */ - public boolean save(OutputStream outStream) { - Document xmlOutDoc = DocumentHelper.createDocument(); - - // Building namespace - Element typesElem = xmlOutDoc.createElementNS(TYPES_NAMESPACE_URI, TYPES_TAG_NAME); - xmlOutDoc.appendChild(typesElem); - - // Adding default types - for (Entry entry : defaultContentType.entrySet()) { - appendDefaultType(typesElem, entry); - } - - // Adding specific types if any exist - if (overrideContentType != null) { - for (Entry entry : overrideContentType - .entrySet()) { - appendSpecificTypes(typesElem, entry); - } - } - xmlOutDoc.normalize(); - - // Save content in the specified output stream - return this.saveImpl(xmlOutDoc, outStream); - } - - /** - * Use to append specific type XML elements, use by the save() method. - * - * @param root - * XML parent element use to append this override type element. - * @param entry - * The values to append. - * @see #save(java.io.OutputStream) - */ - private void appendSpecificTypes(Element root, - Entry entry) { - Element specificType = root.getOwnerDocument().createElementNS(TYPES_NAMESPACE_URI, OVERRIDE_TAG_NAME); - specificType.setAttribute(PART_NAME_ATTRIBUTE_NAME, entry.getKey().getName()); - specificType.setAttribute(CONTENT_TYPE_ATTRIBUTE_NAME, entry.getValue()); - root.appendChild(specificType); - } - - /** - * Use to append default types XML elements, use by the save() method. - * - * @param root - * XML parent element use to append this default type element. - * @param entry - * The values to append. - * @see #save(java.io.OutputStream) - */ - private void appendDefaultType(Element root, Entry entry) { - Element defaultType = root.getOwnerDocument().createElementNS(TYPES_NAMESPACE_URI, DEFAULT_TAG_NAME); - defaultType.setAttribute(EXTENSION_ATTRIBUTE_NAME, entry.getKey()); - defaultType.setAttribute(CONTENT_TYPE_ATTRIBUTE_NAME, entry.getValue()); - root.appendChild(defaultType); - } - - /** - * Specific implementation of the save method. Call by the save() method, - * call before exiting. - * - * @param out - * The output stream use to write the content type XML. - */ - public abstract boolean saveImpl(Document content, OutputStream out); -} diff --git a/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/FileHelper.java b/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/FileHelper.java deleted file mode 100644 index bf7402ea0..000000000 --- a/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/FileHelper.java +++ /dev/null @@ -1,95 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc.internal; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.nio.channels.FileChannel; - -/** - * Provide useful method to manage file. - * - * @author Julien Chable - * @version 0.1 - */ -public final class FileHelper { - - /** - * Get the directory part of the specified file path. - * - * @param f - * File to process. - * @return The directory path from the specified - */ - public static File getDirectory(File f) { - if (f != null) { - String path = f.getPath(); - int len = path.length(); - int num2 = len; - while (--num2 >= 0) { - char ch1 = path.charAt(num2); - if (ch1 == File.separatorChar) { - return new File(path.substring(0, num2)); - } - } - } - return null; - } - - /** - * Copy a file. - * - * @param in - * The source file. - * @param out - * The target location. - * @throws IOException - * If an I/O error occur. - */ - public static void copyFile(File in, File out) throws IOException { - FileInputStream fis = new FileInputStream(in); - FileOutputStream fos = new FileOutputStream(out); - FileChannel sourceChannel = fis.getChannel(); - FileChannel destinationChannel = fos.getChannel(); - sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); - sourceChannel.close(); - destinationChannel.close(); - fos.close(); - fis.close(); - } - - /** - * Get file name from the specified File object. - */ - public static String getFilename(File file) { - if (file != null) { - String path = file.getPath(); - int len = path.length(); - int num2 = len; - while (--num2 >= 0) { - char ch1 = path.charAt(num2); - if (ch1 == File.separatorChar) - return path.substring(num2 + 1, len); - } - } - return ""; - } - -} diff --git a/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/MemoryPackagePart.java b/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/MemoryPackagePart.java deleted file mode 100644 index f2d8c3115..000000000 --- a/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/MemoryPackagePart.java +++ /dev/null @@ -1,141 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc.internal; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.exceptions.OpenXML4JException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.opc.PackagePartName; -import org.apache.poi.openxml4j.opc.internal.marshallers.ZipPartMarshaller; -import org.apache.poi.util.IOUtils; - -/** - * Memory version of a package part. Use to - * - * @author Julien Chable - * @version 1.0 - */ -public final class MemoryPackagePart extends PackagePart { - - /** - * Storage for the part data. - */ - protected byte[] data; - - /** - * Constructor. - * - * @param pack - * The owner package. - * @param partName - * The part name. - * @param contentType - * The content type. - * @throws InvalidFormatException - * If the specified URI is not OPC compliant. - */ - public MemoryPackagePart(OPCPackage pack, PackagePartName partName, - String contentType) throws InvalidFormatException { - super(pack, partName, contentType); - } - - /** - * Constructor. - * - * @param pack - * The owner package. - * @param partName - * The part name. - * @param contentType - * The content type. - * @param loadRelationships - * Specify if the relationships will be loaded. - * @throws InvalidFormatException - * If the specified URI is not OPC compliant. - */ - public MemoryPackagePart(OPCPackage pack, PackagePartName partName, - String contentType, boolean loadRelationships) - throws InvalidFormatException { - super(pack, partName, new ContentType(contentType), loadRelationships); - } - - @Override - protected InputStream getInputStreamImpl() { - // If this part has been created from scratch and/or the data buffer is - // not - // initialize, so we do it now. - if (data == null) { - data = new byte[0]; - } - return new ByteArrayInputStream(data); - } - - @Override - protected OutputStream getOutputStreamImpl() { - return new MemoryPackagePartOutputStream(this); - } - - @Override - public long getSize() { - return data == null ? 0 : data.length; - } - - @Override - public void clear() { - data = null; - } - - @Override - public boolean save(OutputStream os) throws OpenXML4JException { - return new ZipPartMarshaller().marshall(this, os); - } - - @Override - public boolean load(InputStream ios) throws InvalidFormatException { - // Grab the data - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - try { - IOUtils.copy(ios, baos); - } catch(IOException e) { - throw new InvalidFormatException(e.getMessage()); - } - - // Save it - data = baos.toByteArray(); - - // All done - return true; - } - - @Override - public void close() { - // Do nothing - } - - @Override - public void flush() { - // Do nothing - } -} diff --git a/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/MemoryPackagePartOutputStream.java b/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/MemoryPackagePartOutputStream.java deleted file mode 100644 index cf809d667..000000000 --- a/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/MemoryPackagePartOutputStream.java +++ /dev/null @@ -1,95 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc.internal; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.OutputStream; - -/** - * Build an output stream for MemoryPackagePart. - * - * @author Julien Chable - */ -public final class MemoryPackagePartOutputStream extends OutputStream { - - private MemoryPackagePart _part; - - private ByteArrayOutputStream _buff; - - public MemoryPackagePartOutputStream(MemoryPackagePart part) { - this._part = part; - _buff = new ByteArrayOutputStream(); - } - - @Override - public void write(int b) { - _buff.write(b); - } - - /** - * Close this stream and flush the content. - * @see #flush() - */ - @Override - public void close() throws IOException { - this.flush(); - } - - /** - * Flush this output stream. This method is called by the close() method. - * Warning : don't call this method for output consistency. - * @see #close() - */ - @Override - public void flush() throws IOException { - _buff.flush(); - if (_part.data != null) { - byte[] newArray = new byte[_part.data.length + _buff.size()]; - // copy the previous contents of part.data in newArray - System.arraycopy(_part.data, 0, newArray, 0, _part.data.length); - - // append the newly added data - byte[] buffArr = _buff.toByteArray(); - System.arraycopy(buffArr, 0, newArray, _part.data.length, - buffArr.length); - - // save the result as new data - _part.data = newArray; - } else { - // was empty, just fill it - _part.data = _buff.toByteArray(); - } - - /* - * Clear this streams buffer, in case flush() is called a second time - * Fix bug 1921637 - provided by Rainer Schwarze - */ - _buff.reset(); - } - - @Override - public void write(byte[] b, int off, int len) { - _buff.write(b, off, len); - } - - @Override - public void write(byte[] b) throws IOException { - _buff.write(b); - } -} diff --git a/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/PackagePropertiesPart.java b/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/PackagePropertiesPart.java deleted file mode 100644 index 6fb7f65be..000000000 --- a/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/PackagePropertiesPart.java +++ /dev/null @@ -1,675 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc.internal; - -import java.io.InputStream; -import java.io.OutputStream; -import java.text.ParsePosition; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Locale; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.exceptions.InvalidOperationException; -import org.apache.poi.openxml4j.opc.ContentTypes; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.opc.PackagePartName; -import org.apache.poi.openxml4j.opc.PackageProperties; -import org.apache.poi.openxml4j.util.Nullable; -import org.apache.poi.util.LocaleUtil; - -/** - * Represents the core properties part of a package. - * - * @author Julien Chable - */ -public final class PackagePropertiesPart extends PackagePart implements - PackageProperties { - - public final static String NAMESPACE_DC_URI = "http://purl.org/dc/elements/1.1/"; - - public final static String NAMESPACE_CP_URI = "http://schemas.openxmlformats.org/package/2006/metadata/core-properties"; - - public final static String NAMESPACE_DCTERMS_URI = "http://purl.org/dc/terms/"; - - private final static String DEFAULT_DATEFORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'"; - - private final static String[] DATE_FORMATS = new String[]{ - DEFAULT_DATEFORMAT, - "yyyy-MM-dd'T'HH:mm:ss.SS'Z'", - "yyyy-MM-dd" - }; - - //Had to add this and TIME_ZONE_PAT to handle tz with colons. - //When we move to Java 7, we should be able to add another - //date format to DATE_FORMATS that uses XXX and get rid of this - //and TIME_ZONE_PAT - // TODO Fix this after the Java 7 upgrade - private final String[] TZ_DATE_FORMATS = new String[]{ - "yyyy-MM-dd'T'HH:mm:ssz", - "yyyy-MM-dd'T'HH:mm:ss.Sz", - "yyyy-MM-dd'T'HH:mm:ss.SSz", - "yyyy-MM-dd'T'HH:mm:ss.SSSz", - }; - - private final Pattern TIME_ZONE_PAT = Pattern.compile("([-+]\\d\\d):?(\\d\\d)"); - /** - * Constructor. - * - * @param pack - * Container package. - * @param partName - * Name of this part. - * @throws InvalidFormatException - * Throws if the content is invalid. - */ - public PackagePropertiesPart(OPCPackage pack, PackagePartName partName) - throws InvalidFormatException { - super(pack, partName, ContentTypes.CORE_PROPERTIES_PART); - } - - /** - * A categorization of the content of this package. - * - * [Example: Example values for this property might include: Resume, Letter, - * Financial Forecast, Proposal, Technical Presentation, and so on. This - * value might be used by an application's user interface to facilitate - * navigation of a large set of documents. end example] - */ - protected Nullable category = new Nullable(); - - /** - * The status of the content. - * - * [Example: Values might include "Draft", "Reviewed", and "Final". end - * example] - */ - protected Nullable contentStatus = new Nullable(); - - /** - * The type of content represented, generally defined by a specific use and - * intended audience. - * - * [Example: Values might include "Whitepaper", "Security Bulletin", and - * "Exam". end example] [Note: This property is distinct from MIME content - * types as defined in RFC 2616. end note] - */ - protected Nullable contentType = new Nullable(); - - /** - * Date of creation of the resource. - */ - protected Nullable created = new Nullable(); - - /** - * An entity primarily responsible for making the content of the resource. - */ - protected Nullable creator = new Nullable(); - - /** - * An explanation of the content of the resource. - * - * [Example: Values might include an abstract, table of contents, reference - * to a graphical representation of content, and a free-text account of the - * content. end example] - */ - protected Nullable description = new Nullable(); - - /** - * An unambiguous reference to the resource within a given context. - */ - protected Nullable identifier = new Nullable(); - - /** - * A delimited set of keywords to support searching and indexing. This is - * typically a list of terms that are not available elsewhere in the - * properties. - */ - protected Nullable keywords = new Nullable(); - - /** - * The language of the intellectual content of the resource. - * - * [Note: IETF RFC 3066 provides guidance on encoding to represent - * languages. end note] - */ - protected Nullable language = new Nullable(); - - /** - * The user who performed the last modification. The identification is - * environment-specific. - * - * [Example: A name, email address, or employee ID. end example] It is - * recommended that this value be as concise as possible. - */ - protected Nullable lastModifiedBy = new Nullable(); - - /** - * The date and time of the last printing. - */ - protected Nullable lastPrinted = new Nullable(); - - /** - * Date on which the resource was changed. - */ - protected Nullable modified = new Nullable(); - - /** - * The revision number. - * - * [Example: This value might indicate the number of saves or revisions, - * provided the application updates it after each revision. end example] - */ - protected Nullable revision = new Nullable(); - - /** - * The topic of the content of the resource. - */ - protected Nullable subject = new Nullable(); - - /** - * The name given to the resource. - */ - protected Nullable title = new Nullable(); - - /** - * The version number. This value is set by the user or by the application. - */ - protected Nullable version = new Nullable(); - - /* - * Getters and setters - */ - - /** - * Get the category property. - * - * @see org.apache.poi.openxml4j.opc.PackageProperties#getCategoryProperty() - */ - public Nullable getCategoryProperty() { - return category; - } - - /** - * Get content status. - * - * @see org.apache.poi.openxml4j.opc.PackageProperties#getContentStatusProperty() - */ - public Nullable getContentStatusProperty() { - return contentStatus; - } - - /** - * Get content type. - * - * @see org.apache.poi.openxml4j.opc.PackageProperties#getContentTypeProperty() - */ - public Nullable getContentTypeProperty() { - return contentType; - } - - /** - * Get created date. - * - * @see org.apache.poi.openxml4j.opc.PackageProperties#getCreatedProperty() - */ - public Nullable getCreatedProperty() { - return created; - } - - /** - * Get created date formated into a String. - * - * @return A string representation of the created date. - */ - public String getCreatedPropertyString() { - return getDateValue(created); - } - - /** - * Get creator. - * - * @see org.apache.poi.openxml4j.opc.PackageProperties#getCreatorProperty() - */ - public Nullable getCreatorProperty() { - return creator; - } - - /** - * Get description. - * - * @see org.apache.poi.openxml4j.opc.PackageProperties#getDescriptionProperty() - */ - public Nullable getDescriptionProperty() { - return description; - } - - /** - * Get identifier. - * - * @see org.apache.poi.openxml4j.opc.PackageProperties#getIdentifierProperty() - */ - public Nullable getIdentifierProperty() { - return identifier; - } - - /** - * Get keywords. - * - * @see org.apache.poi.openxml4j.opc.PackageProperties#getKeywordsProperty() - */ - public Nullable getKeywordsProperty() { - return keywords; - } - - /** - * Get the language. - * - * @see org.apache.poi.openxml4j.opc.PackageProperties#getLanguageProperty() - */ - public Nullable getLanguageProperty() { - return language; - } - - /** - * Get the author of last modifications. - * - * @see org.apache.poi.openxml4j.opc.PackageProperties#getLastModifiedByProperty() - */ - public Nullable getLastModifiedByProperty() { - return lastModifiedBy; - } - - /** - * Get last printed date. - * - * @see org.apache.poi.openxml4j.opc.PackageProperties#getLastPrintedProperty() - */ - public Nullable getLastPrintedProperty() { - return lastPrinted; - } - - /** - * Get last printed date formated into a String. - * - * @return A string representation of the last printed date. - */ - public String getLastPrintedPropertyString() { - return getDateValue(lastPrinted); - } - - /** - * Get modified date. - * - * @see org.apache.poi.openxml4j.opc.PackageProperties#getModifiedProperty() - */ - public Nullable getModifiedProperty() { - return modified; - } - - /** - * Get modified date formated into a String. - * - * @return A string representation of the modified date. - */ - public String getModifiedPropertyString() { - if (modified.hasValue()) { - return getDateValue(modified); - } - return getDateValue(new Nullable(new Date())); - } - - /** - * Get revision. - * - * @see org.apache.poi.openxml4j.opc.PackageProperties#getRevisionProperty() - */ - public Nullable getRevisionProperty() { - return revision; - } - - /** - * Get subject. - * - * @see org.apache.poi.openxml4j.opc.PackageProperties#getSubjectProperty() - */ - public Nullable getSubjectProperty() { - return subject; - } - - /** - * Get title. - * - * @see org.apache.poi.openxml4j.opc.PackageProperties#getTitleProperty() - */ - public Nullable getTitleProperty() { - return title; - } - - /** - * Get version. - * - * @see org.apache.poi.openxml4j.opc.PackageProperties#getVersionProperty() - */ - public Nullable getVersionProperty() { - return version; - } - - /** - * Set the category. - * - * @see org.apache.poi.openxml4j.opc.PackageProperties#setCategoryProperty(java.lang.String) - */ - public void setCategoryProperty(String category) { - this.category = setStringValue(category); - } - - /** - * Set the content status. - * - * @see org.apache.poi.openxml4j.opc.PackageProperties#setContentStatusProperty(java.lang.String) - */ - public void setContentStatusProperty(String contentStatus) { - this.contentStatus = setStringValue(contentStatus); - } - - /** - * Set the content type. - * - * @see org.apache.poi.openxml4j.opc.PackageProperties#setContentTypeProperty(java.lang.String) - */ - public void setContentTypeProperty(String contentType) { - this.contentType = setStringValue(contentType); - } - - /** - * Set the created date. - * - * @see org.apache.poi.openxml4j.opc.PackageProperties#setCreatedProperty(org.apache.poi.openxml4j.util.Nullable) - */ - public void setCreatedProperty(String created) { - try { - this.created = setDateValue(created); - } catch (InvalidFormatException e) { - throw new IllegalArgumentException("Date for created could not be parsed: " + created, e); - } - } - - /** - * Set the created date. - * - * @see org.apache.poi.openxml4j.opc.PackageProperties#setCreatedProperty(org.apache.poi.openxml4j.util.Nullable) - */ - public void setCreatedProperty(Nullable created) { - if (created.hasValue()) - this.created = created; - } - - /** - * Set the creator. - * - * @see org.apache.poi.openxml4j.opc.PackageProperties#setCreatorProperty(java.lang.String) - */ - public void setCreatorProperty(String creator) { - this.creator = setStringValue(creator); - } - - /** - * Set the description. - * - * @see org.apache.poi.openxml4j.opc.PackageProperties#setDescriptionProperty(java.lang.String) - */ - public void setDescriptionProperty(String description) { - this.description = setStringValue(description); - } - - /** - * Set identifier. - * - * @see org.apache.poi.openxml4j.opc.PackageProperties#setIdentifierProperty(java.lang.String) - */ - public void setIdentifierProperty(String identifier) { - this.identifier = setStringValue(identifier); - } - - /** - * Set keywords. - * - * @see org.apache.poi.openxml4j.opc.PackageProperties#setKeywordsProperty(java.lang.String) - */ - public void setKeywordsProperty(String keywords) { - this.keywords = setStringValue(keywords); - } - - /** - * Set language. - * - * @see org.apache.poi.openxml4j.opc.PackageProperties#setLanguageProperty(java.lang.String) - */ - public void setLanguageProperty(String language) { - this.language = setStringValue(language); - } - - /** - * Set last modifications author. - * - * @see org.apache.poi.openxml4j.opc.PackageProperties#setLastModifiedByProperty(java.lang.String) - */ - public void setLastModifiedByProperty(String lastModifiedBy) { - this.lastModifiedBy = setStringValue(lastModifiedBy); - } - - /** - * Set last printed date. - * - * @see org.apache.poi.openxml4j.opc.PackageProperties#setLastPrintedProperty(org.apache.poi.openxml4j.util.Nullable) - */ - public void setLastPrintedProperty(String lastPrinted) { - try { - this.lastPrinted = setDateValue(lastPrinted); - } catch (InvalidFormatException e) { - throw new IllegalArgumentException("lastPrinted : " - + e.getLocalizedMessage(), e); - } - } - - /** - * Set last printed date. - * - * @see org.apache.poi.openxml4j.opc.PackageProperties#setLastPrintedProperty(org.apache.poi.openxml4j.util.Nullable) - */ - public void setLastPrintedProperty(Nullable lastPrinted) { - if (lastPrinted.hasValue()) - this.lastPrinted = lastPrinted; - } - - /** - * Set last modification date. - * - * @see org.apache.poi.openxml4j.opc.PackageProperties#setModifiedProperty(org.apache.poi.openxml4j.util.Nullable) - */ - public void setModifiedProperty(String modified) { - try { - this.modified = setDateValue(modified); - } catch (InvalidFormatException e) { - throw new IllegalArgumentException("modified : " - + e.getLocalizedMessage(), e); - } - } - - /** - * Set last modification date. - * - * @see org.apache.poi.openxml4j.opc.PackageProperties#setModifiedProperty(org.apache.poi.openxml4j.util.Nullable) - */ - public void setModifiedProperty(Nullable modified) { - if (modified.hasValue()) - this.modified = modified; - } - - /** - * Set revision. - * - * @see org.apache.poi.openxml4j.opc.PackageProperties#setRevisionProperty(java.lang.String) - */ - public void setRevisionProperty(String revision) { - this.revision = setStringValue(revision); - } - - /** - * Set subject. - * - * @see org.apache.poi.openxml4j.opc.PackageProperties#setSubjectProperty(java.lang.String) - */ - public void setSubjectProperty(String subject) { - this.subject = setStringValue(subject); - } - - /** - * Set title. - * - * @see org.apache.poi.openxml4j.opc.PackageProperties#setTitleProperty(java.lang.String) - */ - public void setTitleProperty(String title) { - this.title = setStringValue(title); - } - - /** - * Set version. - * - * @see org.apache.poi.openxml4j.opc.PackageProperties#setVersionProperty(java.lang.String) - */ - public void setVersionProperty(String version) { - this.version = setStringValue(version); - } - - /** - * Convert a strig value into a Nullable - */ - private Nullable setStringValue(String s) { - if (s == null || s.equals("")) { - return new Nullable(); - } - return new Nullable(s); - } - - /** - * Convert a string value represented a date into a Nullable. - * - * @throws InvalidFormatException - * Throws if the date format isnot valid. - */ - private Nullable setDateValue(String dateStr) throws InvalidFormatException { - if (dateStr == null || dateStr.equals("")) { - return new Nullable(); - } - - Matcher m = TIME_ZONE_PAT.matcher(dateStr); - if (m.find()) { - String dateTzStr = dateStr.substring(0, m.start())+ - m.group(1)+m.group(2); - for (String fStr : TZ_DATE_FORMATS) { - SimpleDateFormat df = new SimpleDateFormat(fStr, Locale.ROOT); - df.setTimeZone(LocaleUtil.TIMEZONE_UTC); - Date d = df.parse(dateTzStr, new ParsePosition(0)); - if (d != null) { - return new Nullable(d); - } - } - } - String dateTzStr = dateStr.endsWith("Z") ? dateStr : (dateStr + "Z"); - for (String fStr : DATE_FORMATS) { - SimpleDateFormat df = new SimpleDateFormat(fStr, Locale.ROOT); - df.setTimeZone(LocaleUtil.TIMEZONE_UTC); - Date d = df.parse(dateTzStr, new ParsePosition(0)); - if (d != null) { - return new Nullable(d); - } - } - //if you're here, no pattern matched, throw exception - StringBuilder sb = new StringBuilder(); - int i = 0; - for (String fStr : TZ_DATE_FORMATS) { - if (i++ > 0) { - sb.append(", "); - } - sb.append(fStr); - } - for (String fStr : DATE_FORMATS) { - sb.append(", ").append(fStr); - } - throw new InvalidFormatException("Date " + dateStr + " not well formatted, " - + "expected format in: "+sb.toString()); - } - - /** - * Convert a Nullable into a String. - * - * @param d - * The Date to convert. - * @return The formated date or null. - * @see java.text.SimpleDateFormat - */ - private String getDateValue(Nullable d) { - if (d == null) { - return ""; - } - Date date = d.getValue(); - if (date == null) { - return ""; - } - - SimpleDateFormat df = new SimpleDateFormat(DEFAULT_DATEFORMAT, Locale.ROOT); - df.setTimeZone(LocaleUtil.TIMEZONE_UTC); - return df.format(date); - } - - @Override - protected InputStream getInputStreamImpl() { - throw new InvalidOperationException("Operation not authorized. This part may only be manipulated using the getters and setters on PackagePropertiesPart"); - } - - @Override - protected OutputStream getOutputStreamImpl() { - throw new InvalidOperationException( - "Can't use output stream to set properties !"); - } - - @Override - public boolean save(OutputStream zos) { - throw new InvalidOperationException("Operation not authorized. This part may only be manipulated using the getters and setters on PackagePropertiesPart"); - } - - @Override - public boolean load(InputStream ios) { - throw new InvalidOperationException("Operation not authorized. This part may only be manipulated using the getters and setters on PackagePropertiesPart"); - } - - @Override - public void close() { - // Do nothing - } - - @Override - public void flush() { - // Do nothing - } -} diff --git a/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/PartMarshaller.java b/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/PartMarshaller.java deleted file mode 100644 index e30d71783..000000000 --- a/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/PartMarshaller.java +++ /dev/null @@ -1,49 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc.internal; - -import java.io.OutputStream; - -import org.apache.poi.openxml4j.exceptions.OpenXML4JException; -import org.apache.poi.openxml4j.opc.PackagePart; - -/** - * Object implemented this interface are considered as part marshaller. A part - * marshaller is responsible to marshall a part in order to be save in a - * package. - * - * @author Julien Chable - * @version 0.1 - */ -public interface PartMarshaller { - - /** - * Save the content of the package in the stream - * - * @param part - * Part to marshall. - * @param out - * The output stream into which the part will be marshall. - * @return false if any marshall error occurs, else true - * @throws OpenXML4JException - * Throws only if any other exceptions are thrown by inner - * methods. - */ - public boolean marshall(PackagePart part, OutputStream out) - throws OpenXML4JException; -} diff --git a/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/PartUnmarshaller.java b/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/PartUnmarshaller.java deleted file mode 100644 index e5487a638..000000000 --- a/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/PartUnmarshaller.java +++ /dev/null @@ -1,50 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc.internal; - -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.exceptions.OpenXML4JException; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.opc.internal.unmarshallers.UnmarshallContext; - -/** - * Object implemented this interface are considered as part unmarshaller. A part - * unmarshaller is responsible to unmarshall a part in order to load it from a - * package. - * - * @author Julien Chable - * @version 0.1 - */ -public interface PartUnmarshaller { - - /** - * Save the content of the package in the stream - * - * @param in - * The input stream from which the part will be unmarshall. - * @return The part freshly unmarshall from the input stream. - * @throws OpenXML4JException - * Throws only if any other exceptions are thrown by inner - * methods. - */ - public PackagePart unmarshall(UnmarshallContext context, InputStream in) - throws InvalidFormatException, IOException; -} diff --git a/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/ZipContentTypeManager.java b/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/ZipContentTypeManager.java deleted file mode 100644 index 70bdb39e1..000000000 --- a/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/ZipContentTypeManager.java +++ /dev/null @@ -1,82 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc.internal; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.zip.ZipEntry; -import java.util.zip.ZipOutputStream; - -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.StreamHelper; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.w3c.dom.Document; - -/** - * Zip implementation of the ContentTypeManager. - * - * @author Julien Chable - * @version 1.0 - * @see ContentTypeManager - */ -public class ZipContentTypeManager extends ContentTypeManager { - private final static POILogger logger = POILogFactory.getLogger(ZipContentTypeManager.class); - - /** - * Delegate constructor to the super constructor. - * - * @param in - * The input stream to parse to fill internal content type - * collections. - * @throws InvalidFormatException - * If the content types part content is not valid. - */ - public ZipContentTypeManager(InputStream in, OPCPackage pkg) - throws InvalidFormatException { - super(in, pkg); - } - - @SuppressWarnings("resource") - @Override - public boolean saveImpl(Document content, OutputStream out) { - ZipOutputStream zos = null; - if (out instanceof ZipOutputStream) - zos = (ZipOutputStream) out; - else - zos = new ZipOutputStream(out); - - ZipEntry partEntry = new ZipEntry(CONTENT_TYPES_PART_NAME); - try { - // Referenced in ZIP - zos.putNextEntry(partEntry); - // Saving data in the ZIP file - if (!StreamHelper.saveXmlInStream(content, zos)) { - return false; - } - zos.closeEntry(); - } catch (IOException ioe) { - logger.log(POILogger.ERROR, "Cannot write: " + CONTENT_TYPES_PART_NAME - + " in Zip !", ioe); - return false; - } - return true; - } -} diff --git a/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/ZipHelper.java b/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/ZipHelper.java deleted file mode 100644 index 9ed602603..000000000 --- a/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/ZipHelper.java +++ /dev/null @@ -1,288 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc.internal; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.PushbackInputStream; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Enumeration; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; -import java.util.zip.ZipInputStream; - -import org.apache.poi.openxml4j.exceptions.NotOfficeXmlFileException; -import org.apache.poi.openxml4j.exceptions.OLE2NotOfficeXmlFileException; -import org.apache.poi.openxml4j.exceptions.OpenXML4JException; -import org.apache.poi.openxml4j.opc.PackageRelationship; -import org.apache.poi.openxml4j.opc.PackageRelationshipTypes; -import org.apache.poi.openxml4j.opc.ZipPackage; -import org.apache.poi.openxml4j.util.ZipSecureFile; -import org.apache.poi.openxml4j.util.ZipSecureFile.ThresholdInputStream; -import org.apache.poi.poifs.common.POIFSConstants; -import org.apache.poi.poifs.storage.HeaderBlockConstants; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.Removal; - -public final class ZipHelper { - /** - * Forward slash use to convert part name between OPC and zip item naming - * conventions. - */ - private final static String FORWARD_SLASH = "/"; - - /** - * Buffer to read data from file. Use big buffer to improve performaces. the - * InputStream class is reading only 8192 bytes per read call (default value - * set by sun) - * - * @deprecated in POI 3.16-beta3, not used anymore - */ - @Deprecated - @Removal(version="3.18") - public static final int READ_WRITE_FILE_BUFFER_SIZE = 8192; - - /** - * Prevent this class to be instancied. - */ - private ZipHelper() { - // Do nothing - } - - /** - * Retrieve the zip entry of the core properties part. - * - * @throws OpenXML4JException - * Throws if internal error occurs. - */ - public static ZipEntry getCorePropertiesZipEntry(ZipPackage pkg) { - PackageRelationship corePropsRel = pkg.getRelationshipsByType( - PackageRelationshipTypes.CORE_PROPERTIES).getRelationship(0); - - if (corePropsRel == null) { - return null; - } - - return new ZipEntry(corePropsRel.getTargetURI().getPath()); - } - - /** - * Retrieve the Zip entry of the content types part. - */ - public static ZipEntry getContentTypeZipEntry(ZipPackage pkg) { - Enumeration entries = pkg.getZipArchive().getEntries(); - - // Enumerate through the Zip entries until we find the one named - // '[Content_Types].xml'. - while (entries.hasMoreElements()) { - ZipEntry entry = entries.nextElement(); - if (entry.getName().equals( - ContentTypeManager.CONTENT_TYPES_PART_NAME)) { - return entry; - } - } - return null; - } - - /** - * Convert a zip name into an OPC name by adding a leading forward slash to - * the specified item name. - * - * @param zipItemName - * Zip item name to convert. - * @return An OPC compliant name. - */ - public static String getOPCNameFromZipItemName(String zipItemName) { - if (zipItemName == null) { - throw new IllegalArgumentException("zipItemName cannot be null"); - } - if (zipItemName.startsWith(FORWARD_SLASH)) { - return zipItemName; - } - return FORWARD_SLASH + zipItemName; - } - - /** - * Convert an OPC item name into a zip item name by removing any leading - * forward slash if it exist. - * - * @param opcItemName - * The OPC item name to convert. - * @return A zip item name without any leading slashes. - */ - public static String getZipItemNameFromOPCName(String opcItemName) { - if (opcItemName == null) { - throw new IllegalArgumentException("opcItemName cannot be null"); - } - - String retVal = opcItemName; - while (retVal.startsWith(FORWARD_SLASH)) { - retVal = retVal.substring(1); - } - return retVal; - } - - /** - * Convert an OPC item name into a zip URI by removing any leading forward - * slash if it exist. - * - * @param opcItemName - * The OPC item name to convert. - * @return A zip URI without any leading slashes. - */ - public static URI getZipURIFromOPCName(String opcItemName) { - if (opcItemName == null) { - throw new IllegalArgumentException("opcItemName"); - } - - String retVal = opcItemName; - while (retVal.startsWith(FORWARD_SLASH)) { - retVal = retVal.substring(1); - } - try { - return new URI(retVal); - } catch (URISyntaxException e) { - return null; - } - } - - /** - * Verifies that the given stream starts with a Zip structure. - * - * Warning - this will consume the first few bytes of the stream, - * you should push-back or reset the stream after use! - */ - public static void verifyZipHeader(InputStream stream) - throws NotOfficeXmlFileException, IOException { - // Grab the first 8 bytes - byte[] data = new byte[8]; - IOUtils.readFully(stream, data); - - // OLE2? - long signature = LittleEndian.getLong(data); - if (signature == HeaderBlockConstants._signature) { - throw new OLE2NotOfficeXmlFileException( - "The supplied data appears to be in the OLE2 Format. " + - "You are calling the part of POI that deals with OOXML "+ - "(Office Open XML) Documents. You need to call a different " + - "part of POI to process this data (eg HSSF instead of XSSF)"); - } - - // Raw XML? - byte[] RAW_XML_FILE_HEADER = POIFSConstants.RAW_XML_FILE_HEADER; - if (data[0] == RAW_XML_FILE_HEADER[0] && - data[1] == RAW_XML_FILE_HEADER[1] && - data[2] == RAW_XML_FILE_HEADER[2] && - data[3] == RAW_XML_FILE_HEADER[3] && - data[4] == RAW_XML_FILE_HEADER[4]) { - throw new NotOfficeXmlFileException( - "The supplied data appears to be a raw XML file. " + - "Formats such as Office 2003 XML are not supported"); - } - - // Don't check for a Zip header, as to maintain backwards - // compatibility we need to let them seek over junk at the - // start before beginning processing. - - // Put things back - if (stream instanceof PushbackInputStream) { - ((PushbackInputStream)stream).unread(data); - } else if (stream.markSupported()) { - stream.reset(); - } else if (stream instanceof FileInputStream) { - // File open check, about to be closed, nothing to do - } else { - // Oh dear... I hope you know what you're doing! - } - } - - private static InputStream prepareToCheckHeader(InputStream stream) { - if (stream instanceof PushbackInputStream) { - return stream; - } - if (stream.markSupported()) { - stream.mark(8); - return stream; - } - return new PushbackInputStream(stream, 8); - } - - /** - * Opens the specified stream as a secure zip - * - * @param stream - * The stream to open. - * @return The zip stream freshly open. - */ - @SuppressWarnings("resource") - public static ThresholdInputStream openZipStream(InputStream stream) throws IOException { - // Peek at the first few bytes to sanity check - InputStream checkedStream = prepareToCheckHeader(stream); - verifyZipHeader(checkedStream); - - // Open as a proper zip stream - InputStream zis = new ZipInputStream(checkedStream); - return ZipSecureFile.addThreshold(zis); - } - - /** - * Opens the specified file as a secure zip, or returns null if no - * such file exists - * - * @param file - * The file to open. - * @return The zip archive freshly open. - * @throws IOException if the zip file cannot be opened or closed to read the header signature - * @throws NotOfficeXmlFileException if stream does not start with zip header signature - */ - public static ZipFile openZipFile(File file) throws IOException, NotOfficeXmlFileException { - if (!file.exists()) { - throw new FileNotFoundException("File does not exist"); - } - if (file.isDirectory()) { - throw new IOException("File is a directory"); - } - - // Peek at the first few bytes to sanity check - FileInputStream input = new FileInputStream(file); - try { - verifyZipHeader(input); - } finally { - input.close(); - } - - // Open as a proper zip file - return new ZipSecureFile(file); - } - - /** - * Retrieve and open as a secure zip file with the specified path. - * - * @param path - * The file path. - * @return The zip archive freshly open. - */ - public static ZipFile openZipFile(String path) throws IOException { - return openZipFile(new File(path)); - } -} diff --git a/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/marshallers/DefaultMarshaller.java b/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/marshallers/DefaultMarshaller.java deleted file mode 100644 index 8cd2f7d24..000000000 --- a/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/marshallers/DefaultMarshaller.java +++ /dev/null @@ -1,45 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc.internal.marshallers; - -import java.io.OutputStream; - -import org.apache.poi.openxml4j.exceptions.OpenXML4JException; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.opc.internal.PartMarshaller; - -/** - * Default marshaller that specified that the part is responsible to marshall its content. - * - * @author Julien Chable - * @version 1.0 - * @see PartMarshaller - */ -public final class DefaultMarshaller implements PartMarshaller { - - /** - * Save part in the output stream by using the save() method of the part. - * - * @throws OpenXML4JException - * If any error occur. - */ - public boolean marshall(PackagePart part, OutputStream out) - throws OpenXML4JException { - return part.save(out); - } -} diff --git a/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/marshallers/PackagePropertiesMarshaller.java b/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/marshallers/PackagePropertiesMarshaller.java deleted file mode 100644 index 7a8f40072..000000000 --- a/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/marshallers/PackagePropertiesMarshaller.java +++ /dev/null @@ -1,272 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc.internal.marshallers; - -import java.io.OutputStream; - -import javax.xml.XMLConstants; -import javax.xml.stream.XMLEventFactory; -import javax.xml.stream.events.Namespace; - -import org.apache.poi.openxml4j.exceptions.OpenXML4JException; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.opc.internal.PackagePropertiesPart; -import org.apache.poi.openxml4j.opc.internal.PartMarshaller; -import org.apache.poi.openxml4j.util.Nullable; -import org.apache.poi.util.DocumentHelper; -import org.w3c.dom.Document; -import org.w3c.dom.Element; - -/** - * Package properties marshaller. - */ -public class PackagePropertiesMarshaller implements PartMarshaller { - private final static Namespace namespaceDC, namespaceCoreProperties, namespaceDcTerms, namespaceXSI; - static { - final XMLEventFactory f = XMLEventFactory.newInstance(); - namespaceDC = f.createNamespace("dc", PackagePropertiesPart.NAMESPACE_DC_URI); - namespaceCoreProperties = f.createNamespace("cp", PackagePropertiesPart.NAMESPACE_CP_URI); - namespaceDcTerms = f.createNamespace("dcterms", PackagePropertiesPart.NAMESPACE_DCTERMS_URI); - namespaceXSI = f.createNamespace("xsi", XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI); - } - - protected static final String KEYWORD_CATEGORY = "category"; - - protected static final String KEYWORD_CONTENT_STATUS = "contentStatus"; - - protected static final String KEYWORD_CONTENT_TYPE = "contentType"; - - protected static final String KEYWORD_CREATED = "created"; - - protected static final String KEYWORD_CREATOR = "creator"; - - protected static final String KEYWORD_DESCRIPTION = "description"; - - protected static final String KEYWORD_IDENTIFIER = "identifier"; - - protected static final String KEYWORD_KEYWORDS = "keywords"; - - protected static final String KEYWORD_LANGUAGE = "language"; - - protected static final String KEYWORD_LAST_MODIFIED_BY = "lastModifiedBy"; - - protected static final String KEYWORD_LAST_PRINTED = "lastPrinted"; - - protected static final String KEYWORD_MODIFIED = "modified"; - - protected static final String KEYWORD_REVISION = "revision"; - - protected static final String KEYWORD_SUBJECT = "subject"; - - protected static final String KEYWORD_TITLE = "title"; - - protected static final String KEYWORD_VERSION = "version"; - - PackagePropertiesPart propsPart; - - // The document - Document xmlDoc = null; - - /** - * Marshall package core properties to an XML document. Always return - * true. - */ - @Override - public boolean marshall(PackagePart part, OutputStream out) - throws OpenXML4JException { - if (!(part instanceof PackagePropertiesPart)) - throw new IllegalArgumentException( - "'part' must be a PackagePropertiesPart instance."); - propsPart = (PackagePropertiesPart) part; - - // Configure the document - xmlDoc = DocumentHelper.createDocument(); - Element rootElem = xmlDoc.createElementNS(namespaceCoreProperties.getNamespaceURI(), - getQName("coreProperties", namespaceCoreProperties)); - DocumentHelper.addNamespaceDeclaration(rootElem, namespaceCoreProperties); - DocumentHelper.addNamespaceDeclaration(rootElem, namespaceDC); - DocumentHelper.addNamespaceDeclaration(rootElem, namespaceDcTerms); - DocumentHelper.addNamespaceDeclaration(rootElem, namespaceXSI); - xmlDoc.appendChild(rootElem); - - addCategory(); - addContentStatus(); - addContentType(); - addCreated(); - addCreator(); - addDescription(); - addIdentifier(); - addKeywords(); - addLanguage(); - addLastModifiedBy(); - addLastPrinted(); - addModified(); - addRevision(); - addSubject(); - addTitle(); - addVersion(); - return true; - } - - /** - * Sets the given element's text content, creating it if necessary. - */ - private Element setElementTextContent(String localName, Namespace namespace, Nullable property) { - return setElementTextContent(localName, namespace, property, property.getValue()); - } - - private String getQName(String localName, Namespace namespace) { - return namespace.getPrefix().isEmpty() ? localName : namespace.getPrefix() + ':' + localName; - } - - private Element setElementTextContent(String localName, Namespace namespace, Nullable property, String propertyValue) { - if (!property.hasValue()) - return null; - - Element root = xmlDoc.getDocumentElement(); - Element elem = (Element) root.getElementsByTagNameNS(namespace.getNamespaceURI(), localName).item(0); - if (elem == null) { - // missing, we add it - elem = xmlDoc.createElementNS(namespace.getNamespaceURI(), getQName(localName, namespace)); - root.appendChild(elem); - } - elem.setTextContent(propertyValue); - return elem; - } - - private Element setElementTextContent(String localName, Namespace namespace, Nullable property, String propertyValue, String xsiType) { - Element element = setElementTextContent(localName, namespace, property, propertyValue); - if (element != null) { - element.setAttributeNS(namespaceXSI.getNamespaceURI(), getQName("type", namespaceXSI), xsiType); - } - return element; - } - - - /** - * Add category property element if needed. - */ - private void addCategory() { - setElementTextContent(KEYWORD_CATEGORY, namespaceCoreProperties, propsPart.getCategoryProperty()); - } - - /** - * Add content status property element if needed. - */ - private void addContentStatus() { - setElementTextContent(KEYWORD_CONTENT_STATUS, namespaceCoreProperties, propsPart.getContentStatusProperty()); - } - - /** - * Add content type property element if needed. - */ - private void addContentType() { - setElementTextContent(KEYWORD_CONTENT_TYPE, namespaceCoreProperties, propsPart.getContentTypeProperty()); - } - - /** - * Add created property element if needed. - */ - private void addCreated() { - setElementTextContent(KEYWORD_CREATED, namespaceDcTerms, propsPart.getCreatedProperty(), - propsPart.getCreatedPropertyString(), "dcterms:W3CDTF"); - } - - /** - * Add creator property element if needed. - */ - private void addCreator() { - setElementTextContent(KEYWORD_CREATOR, namespaceDC, propsPart.getCreatorProperty()); - } - - /** - * Add description property element if needed. - */ - private void addDescription() { - setElementTextContent(KEYWORD_DESCRIPTION, namespaceDC, propsPart.getDescriptionProperty()); - } - - /** - * Add identifier property element if needed. - */ - private void addIdentifier() { - setElementTextContent(KEYWORD_IDENTIFIER, namespaceDC, propsPart.getIdentifierProperty()); - } - - /** - * Add keywords property element if needed. - */ - private void addKeywords() { - setElementTextContent(KEYWORD_KEYWORDS, namespaceCoreProperties, propsPart.getKeywordsProperty()); - } - - /** - * Add language property element if needed. - */ - private void addLanguage() { - setElementTextContent(KEYWORD_LANGUAGE, namespaceDC, propsPart.getLanguageProperty()); - } - - /** - * Add 'last modified by' property if needed. - */ - private void addLastModifiedBy() { - setElementTextContent(KEYWORD_LAST_MODIFIED_BY, namespaceCoreProperties, propsPart.getLastModifiedByProperty()); - } - - /** - * Add 'last printed' property if needed. - * - */ - private void addLastPrinted() { - setElementTextContent(KEYWORD_LAST_PRINTED, namespaceCoreProperties, propsPart.getLastPrintedProperty(), propsPart.getLastPrintedPropertyString()); - } - - /** - * Add modified property element if needed. - */ - private void addModified() { - setElementTextContent(KEYWORD_MODIFIED, namespaceDcTerms, propsPart.getModifiedProperty(), - propsPart.getModifiedPropertyString(), "dcterms:W3CDTF"); - } - - /** - * Add revision property if needed. - */ - private void addRevision() { - setElementTextContent(KEYWORD_REVISION, namespaceCoreProperties, propsPart.getRevisionProperty()); - } - - /** - * Add subject property if needed. - */ - private void addSubject() { - setElementTextContent(KEYWORD_SUBJECT, namespaceDC, propsPart.getSubjectProperty()); - } - - /** - * Add title property if needed. - */ - private void addTitle() { - setElementTextContent(KEYWORD_TITLE, namespaceDC, propsPart.getTitleProperty()); - } - - private void addVersion() { - setElementTextContent(KEYWORD_VERSION, namespaceCoreProperties, propsPart.getVersionProperty()); - } -} diff --git a/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/marshallers/TestZipPackagePropertiesMarshaller.java b/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/marshallers/TestZipPackagePropertiesMarshaller.java deleted file mode 100644 index 4ff321e37..000000000 --- a/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/marshallers/TestZipPackagePropertiesMarshaller.java +++ /dev/null @@ -1,66 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc.internal.marshallers; - -import org.apache.poi.openxml4j.exceptions.OpenXML4JException; -import org.apache.poi.openxml4j.opc.PackagingURIHelper; -import org.apache.poi.openxml4j.opc.internal.PackagePropertiesPart; -import org.apache.poi.openxml4j.opc.internal.PartMarshaller; -import org.junit.Test; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.util.zip.ZipEntry; -import java.util.zip.ZipOutputStream; - -import static org.apache.poi.openxml4j.opc.PackagingURIHelper.PACKAGE_RELATIONSHIPS_ROOT_URI; -import static org.junit.Assert.assertTrue; - -public class TestZipPackagePropertiesMarshaller { - private PartMarshaller marshaller = new ZipPackagePropertiesMarshaller(); - - @Test(expected=IllegalArgumentException.class) - public void nonZipOutputStream() throws OpenXML4JException { - OutputStream notAZipOutputStream = new ByteArrayOutputStream(0); - marshaller.marshall(null, notAZipOutputStream); - } - - @Test - public void withZipOutputStream() throws Exception { - assertTrue(marshaller.marshall(new PackagePropertiesPart(null, PackagingURIHelper.createPartName(PACKAGE_RELATIONSHIPS_ROOT_URI)), - new ZipOutputStream(new ByteArrayOutputStream()))); - } - - @Test - public void writingFails() throws Exception { - assertTrue(marshaller.marshall(new PackagePropertiesPart(null, PackagingURIHelper.createPartName(PACKAGE_RELATIONSHIPS_ROOT_URI)), - new ZipOutputStream(new ByteArrayOutputStream()))); - } - - @Test(expected=OpenXML4JException.class) - public void ioException() throws Exception { - marshaller.marshall(new PackagePropertiesPart(null, PackagingURIHelper.createPartName(PACKAGE_RELATIONSHIPS_ROOT_URI)), - new ZipOutputStream(new ByteArrayOutputStream()) { - @Override - public void putNextEntry(ZipEntry e) throws IOException { - throw new IOException("TestException"); - } - }); - } -} diff --git a/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/marshallers/ZipPackagePropertiesMarshaller.java b/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/marshallers/ZipPackagePropertiesMarshaller.java deleted file mode 100644 index 6b4b21551..000000000 --- a/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/marshallers/ZipPackagePropertiesMarshaller.java +++ /dev/null @@ -1,63 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc.internal.marshallers; - -import java.io.IOException; -import java.io.OutputStream; -import java.util.zip.ZipEntry; -import java.util.zip.ZipOutputStream; - -import org.apache.poi.openxml4j.exceptions.OpenXML4JException; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.opc.StreamHelper; -import org.apache.poi.openxml4j.opc.internal.ZipHelper; - -/** - * Package core properties marshaller specialized for zipped package. - * - * @author Julien Chable - */ -public final class ZipPackagePropertiesMarshaller extends PackagePropertiesMarshaller { - - @Override - public boolean marshall(PackagePart part, OutputStream out) - throws OpenXML4JException { - if (!(out instanceof ZipOutputStream)) { - throw new IllegalArgumentException("ZipOutputStream expected!"); - } - ZipOutputStream zos = (ZipOutputStream) out; - - // Saving the part in the zip file - ZipEntry ctEntry = new ZipEntry(ZipHelper - .getZipItemNameFromOPCName(part.getPartName().getURI() - .toString())); - try { - // Save in ZIP - zos.putNextEntry(ctEntry); // Add entry in ZIP - super.marshall(part, out); // Marshall the properties inside a XML - // Document - if (!StreamHelper.saveXmlInStream(xmlDoc, out)) { - return false; - } - zos.closeEntry(); - } catch (IOException e) { - throw new OpenXML4JException(e.getLocalizedMessage(), e); - } - return true; - } -} diff --git a/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/marshallers/ZipPartMarshaller.java b/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/marshallers/ZipPartMarshaller.java deleted file mode 100644 index 7ef469edc..000000000 --- a/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/marshallers/ZipPartMarshaller.java +++ /dev/null @@ -1,190 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc.internal.marshallers; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.URI; -import java.util.zip.ZipEntry; -import java.util.zip.ZipOutputStream; - -import org.apache.poi.openxml4j.exceptions.OpenXML4JException; -import org.apache.poi.openxml4j.opc.PackageNamespaces; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.opc.PackagePartName; -import org.apache.poi.openxml4j.opc.PackageRelationship; -import org.apache.poi.openxml4j.opc.PackageRelationshipCollection; -import org.apache.poi.openxml4j.opc.PackagingURIHelper; -import org.apache.poi.openxml4j.opc.StreamHelper; -import org.apache.poi.openxml4j.opc.TargetMode; -import org.apache.poi.openxml4j.opc.internal.PartMarshaller; -import org.apache.poi.openxml4j.opc.internal.ZipHelper; -import org.apache.poi.util.DocumentHelper; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.xssf.usermodel.XSSFRelation; -import org.w3c.dom.Document; -import org.w3c.dom.Element; - -/** - * Zip part marshaller. This marshaller is use to save any part in a zip stream. - */ -public final class ZipPartMarshaller implements PartMarshaller { - private final static POILogger logger = POILogFactory.getLogger(ZipPartMarshaller.class); - - /** - * Save the specified part. - * - * @throws OpenXML4JException - * Throws if an internal exception is thrown. - */ - @Override - public boolean marshall(PackagePart part, OutputStream os) - throws OpenXML4JException { - if (!(os instanceof ZipOutputStream)) { - logger.log(POILogger.ERROR,"Unexpected class " + os.getClass().getName()); - throw new OpenXML4JException("ZipOutputStream expected !"); - // Normally should happen only in developement phase, so just throw - // exception - } - - // check if there is anything to save for some parts. We don't do this for all parts as some code - // might depend on empty parts being saved, e.g. some unit tests verify this currently. - if(part.getSize() == 0 && part.getPartName().getName().equals(XSSFRelation.SHARED_STRINGS.getDefaultFileName())) { - return true; - } - - ZipOutputStream zos = (ZipOutputStream) os; - ZipEntry partEntry = new ZipEntry(ZipHelper - .getZipItemNameFromOPCName(part.getPartName().getURI() - .getPath())); - try { - // Create next zip entry - zos.putNextEntry(partEntry); - - // Saving data in the ZIP file - InputStream ins = part.getInputStream(); - byte[] buff = new byte[ZipHelper.READ_WRITE_FILE_BUFFER_SIZE]; - while (ins.available() > 0) { - int resultRead = ins.read(buff); - if (resultRead == -1) { - // End of file reached - break; - } - zos.write(buff, 0, resultRead); - } - zos.closeEntry(); - } catch (IOException ioe) { - logger.log(POILogger.ERROR,"Cannot write: " + part.getPartName() + ": in ZIP", - ioe); - return false; - } - - // Saving relationship part - if (part.hasRelationships()) { - PackagePartName relationshipPartName = PackagingURIHelper - .getRelationshipPartName(part.getPartName()); - - marshallRelationshipPart(part.getRelationships(), - relationshipPartName, zos); - - } - return true; - } - - /** - * Save relationships into the part. - * - * @param rels - * The relationships collection to marshall. - * @param relPartName - * Part name of the relationship part to marshall. - * @param zos - * Zip output stream in which to save the XML content of the - * relationships serialization. - */ - public static boolean marshallRelationshipPart( - PackageRelationshipCollection rels, PackagePartName relPartName, - ZipOutputStream zos) { - // Building xml - Document xmlOutDoc = DocumentHelper.createDocument(); - // make something like - Element root = xmlOutDoc.createElementNS(PackageNamespaces.RELATIONSHIPS, PackageRelationship.RELATIONSHIPS_TAG_NAME); - xmlOutDoc.appendChild(root); - - // - - URI sourcePartURI = PackagingURIHelper - .getSourcePartUriFromRelationshipPartUri(relPartName.getURI()); - - for (PackageRelationship rel : rels) { - // the relationship element - Element relElem = xmlOutDoc.createElementNS(PackageNamespaces.RELATIONSHIPS, PackageRelationship.RELATIONSHIP_TAG_NAME); - root.appendChild(relElem); - - // the relationship ID - relElem.setAttribute(PackageRelationship.ID_ATTRIBUTE_NAME, rel.getId()); - - // the relationship Type - relElem.setAttribute(PackageRelationship.TYPE_ATTRIBUTE_NAME, rel.getRelationshipType()); - - // the relationship Target - String targetValue; - URI uri = rel.getTargetURI(); - if (rel.getTargetMode() == TargetMode.EXTERNAL) { - // Save the target as-is - we don't need to validate it, - // alter it etc - targetValue = uri.toString(); - - // add TargetMode attribute (as it is external link external) - relElem.setAttribute(PackageRelationship.TARGET_MODE_ATTRIBUTE_NAME, "External"); - } else { - URI targetURI = rel.getTargetURI(); - targetValue = PackagingURIHelper.relativizeURI( - sourcePartURI, targetURI, true).toString(); - } - relElem.setAttribute(PackageRelationship.TARGET_ATTRIBUTE_NAME, targetValue); - } - - xmlOutDoc.normalize(); - - // String schemaFilename = Configuration.getPathForXmlSchema()+ - // File.separator + "opc-relationships.xsd"; - - // Save part in zip - ZipEntry ctEntry = new ZipEntry(ZipHelper.getZipURIFromOPCName( - relPartName.getURI().toASCIIString()).getPath()); - try { - zos.putNextEntry(ctEntry); - if (!StreamHelper.saveXmlInStream(xmlOutDoc, zos)) { - return false; - } - zos.closeEntry(); - } catch (IOException e) { - logger.log(POILogger.ERROR,"Cannot create zip entry " + relPartName, e); - return false; - } - return true; // success - } -} diff --git a/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/unmarshallers/PackagePropertiesUnmarshaller.java b/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/unmarshallers/PackagePropertiesUnmarshaller.java deleted file mode 100644 index 0ccbf30e1..000000000 --- a/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/unmarshallers/PackagePropertiesUnmarshaller.java +++ /dev/null @@ -1,293 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc.internal.unmarshallers; - -import java.io.IOException; -import java.io.InputStream; -import java.util.zip.ZipEntry; - -import javax.xml.XMLConstants; - -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.PackageNamespaces; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.opc.PackageProperties; -import org.apache.poi.openxml4j.opc.ZipPackage; -import org.apache.poi.openxml4j.opc.internal.PackagePropertiesPart; -import org.apache.poi.openxml4j.opc.internal.PartUnmarshaller; -import org.apache.poi.openxml4j.opc.internal.ZipHelper; -import org.apache.poi.util.DocumentHelper; -import org.w3c.dom.Attr; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.NamedNodeMap; -import org.w3c.dom.NodeList; -import org.xml.sax.SAXException; - -/** - * Package properties unmarshaller. - * - * @author Julien Chable - */ -public final class PackagePropertiesUnmarshaller implements PartUnmarshaller { - - protected static final String KEYWORD_CATEGORY = "category"; - - protected static final String KEYWORD_CONTENT_STATUS = "contentStatus"; - - protected static final String KEYWORD_CONTENT_TYPE = "contentType"; - - protected static final String KEYWORD_CREATED = "created"; - - protected static final String KEYWORD_CREATOR = "creator"; - - protected static final String KEYWORD_DESCRIPTION = "description"; - - protected static final String KEYWORD_IDENTIFIER = "identifier"; - - protected static final String KEYWORD_KEYWORDS = "keywords"; - - protected static final String KEYWORD_LANGUAGE = "language"; - - protected static final String KEYWORD_LAST_MODIFIED_BY = "lastModifiedBy"; - - protected static final String KEYWORD_LAST_PRINTED = "lastPrinted"; - - protected static final String KEYWORD_MODIFIED = "modified"; - - protected static final String KEYWORD_REVISION = "revision"; - - protected static final String KEYWORD_SUBJECT = "subject"; - - protected static final String KEYWORD_TITLE = "title"; - - protected static final String KEYWORD_VERSION = "version"; - - // TODO Load element with XMLBeans or dynamic table - // TODO Check every element/namespace for compliance - public PackagePart unmarshall(UnmarshallContext context, InputStream in) - throws InvalidFormatException, IOException { - PackagePropertiesPart coreProps = new PackagePropertiesPart(context - .getPackage(), context.getPartName()); - - // If the input stream is null then we try to get it from the - // package. - if (in == null) { - if (context.getZipEntry() != null) { - in = ((ZipPackage) context.getPackage()).getZipArchive() - .getInputStream(context.getZipEntry()); - } else if (context.getPackage() != null) { - // Try to retrieve the part inputstream from the URI - ZipEntry zipEntry = ZipHelper - .getCorePropertiesZipEntry((ZipPackage) context - .getPackage()); - in = ((ZipPackage) context.getPackage()).getZipArchive() - .getInputStream(zipEntry); - } else - throw new IOException( - "Error while trying to get the part input stream."); - } - - Document xmlDoc; - try { - xmlDoc = DocumentHelper.readDocument(in); - - /* Check OPC compliance */ - - // Rule M4.2, M4.3, M4.4 and M4.5/ - checkElementForOPCCompliance(xmlDoc.getDocumentElement()); - - /* End OPC compliance */ - - } catch (SAXException e) { - throw new IOException(e.getMessage()); - } - - coreProps.setCategoryProperty(loadCategory(xmlDoc)); - coreProps.setContentStatusProperty(loadContentStatus(xmlDoc)); - coreProps.setContentTypeProperty(loadContentType(xmlDoc)); - coreProps.setCreatedProperty(loadCreated(xmlDoc)); - coreProps.setCreatorProperty(loadCreator(xmlDoc)); - coreProps.setDescriptionProperty(loadDescription(xmlDoc)); - coreProps.setIdentifierProperty(loadIdentifier(xmlDoc)); - coreProps.setKeywordsProperty(loadKeywords(xmlDoc)); - coreProps.setLanguageProperty(loadLanguage(xmlDoc)); - coreProps.setLastModifiedByProperty(loadLastModifiedBy(xmlDoc)); - coreProps.setLastPrintedProperty(loadLastPrinted(xmlDoc)); - coreProps.setModifiedProperty(loadModified(xmlDoc)); - coreProps.setRevisionProperty(loadRevision(xmlDoc)); - coreProps.setSubjectProperty(loadSubject(xmlDoc)); - coreProps.setTitleProperty(loadTitle(xmlDoc)); - coreProps.setVersionProperty(loadVersion(xmlDoc)); - - return coreProps; - } - - private String readElement(Document xmlDoc, String localName, String namespaceURI) { - Element el = (Element)xmlDoc.getDocumentElement().getElementsByTagNameNS(namespaceURI, localName).item(0); - if (el == null) { - return null; - } - return el.getTextContent(); - } - - private String loadCategory(Document xmlDoc) { - return readElement(xmlDoc, KEYWORD_CATEGORY, PackageNamespaces.CORE_PROPERTIES); - } - - private String loadContentStatus(Document xmlDoc) { - return readElement(xmlDoc, KEYWORD_CONTENT_STATUS, PackageNamespaces.CORE_PROPERTIES); - } - - private String loadContentType(Document xmlDoc) { - return readElement(xmlDoc, KEYWORD_CONTENT_TYPE, PackageNamespaces.CORE_PROPERTIES); - } - - private String loadCreated(Document xmlDoc) { - return readElement(xmlDoc, KEYWORD_CREATED, PackageProperties.NAMESPACE_DCTERMS); - } - - private String loadCreator(Document xmlDoc) { - return readElement(xmlDoc, KEYWORD_CREATOR, PackageProperties.NAMESPACE_DC); - } - - private String loadDescription(Document xmlDoc) { - return readElement(xmlDoc, KEYWORD_DESCRIPTION, PackageProperties.NAMESPACE_DC); - } - - private String loadIdentifier(Document xmlDoc) { - return readElement(xmlDoc, KEYWORD_IDENTIFIER, PackageProperties.NAMESPACE_DC); - } - - private String loadKeywords(Document xmlDoc) { - return readElement(xmlDoc, KEYWORD_KEYWORDS, PackageNamespaces.CORE_PROPERTIES); - } - - private String loadLanguage(Document xmlDoc) { - return readElement(xmlDoc, KEYWORD_LANGUAGE, PackageProperties.NAMESPACE_DC); - } - - private String loadLastModifiedBy(Document xmlDoc) { - return readElement(xmlDoc, KEYWORD_LAST_MODIFIED_BY, PackageNamespaces.CORE_PROPERTIES); - } - - private String loadLastPrinted(Document xmlDoc) { - return readElement(xmlDoc, KEYWORD_LAST_PRINTED, PackageNamespaces.CORE_PROPERTIES); - } - - private String loadModified(Document xmlDoc) { - return readElement(xmlDoc, KEYWORD_MODIFIED, PackageProperties.NAMESPACE_DCTERMS); - } - - private String loadRevision(Document xmlDoc) { - return readElement(xmlDoc, KEYWORD_REVISION, PackageNamespaces.CORE_PROPERTIES); - } - - private String loadSubject(Document xmlDoc) { - return readElement(xmlDoc, KEYWORD_SUBJECT, PackageProperties.NAMESPACE_DC); - } - - private String loadTitle(Document xmlDoc) { - return readElement(xmlDoc, KEYWORD_TITLE, PackageProperties.NAMESPACE_DC); - } - - private String loadVersion(Document xmlDoc) { - return readElement(xmlDoc, KEYWORD_VERSION, PackageNamespaces.CORE_PROPERTIES); - } - - /* OPC Compliance methods */ - - /** - * Check the element for the following OPC compliance rules: - *

    - * Rule M4.2: A format consumer shall consider the use of the Markup - * Compatibility namespace to be an error. - *

    - * Rule M4.3: Producers shall not create a document element that contains - * refinements to the Dublin Core elements, except for the two specified in - * the schema: and Consumers shall - * consider a document element that violates this constraint to be an error. - *

    - * Rule M4.4: Producers shall not create a document element that contains - * the xml:lang attribute. Consumers shall consider a document element that - * violates this constraint to be an error. - *

    - * Rule M4.5: Producers shall not create a document element that contains - * the xsi:type attribute, except for a or - * element where the xsi:type attribute shall be present - * and shall hold the value dcterms:W3CDTF, where dcterms is the namespace - * prefix of the Dublin Core namespace. Consumers shall consider a document - * element that violates this constraint to be an error. - *

    - */ - public void checkElementForOPCCompliance(Element el) - throws InvalidFormatException { - // Check the current element - NamedNodeMap namedNodeMap = el.getAttributes(); - int namedNodeCount = namedNodeMap.getLength(); - for (int i = 0; i < namedNodeCount; i++) { - Attr attr = (Attr)namedNodeMap.item(0); - - if (attr.getNamespaceURI().equals(XMLConstants.XMLNS_ATTRIBUTE_NS_URI)) { - // Rule M4.2 - if (attr.getValue().equals(PackageNamespaces.MARKUP_COMPATIBILITY)) - throw new InvalidFormatException( - "OPC Compliance error [M4.2]: A format consumer shall consider the use of the Markup Compatibility namespace to be an error."); - - } - } - - // Rule M4.3 - String elName = el.getLocalName(); - if (el.getNamespaceURI().equals(PackageProperties.NAMESPACE_DCTERMS)) - if (!(elName.equals(KEYWORD_CREATED) || elName.equals(KEYWORD_MODIFIED))) - throw new InvalidFormatException( - "OPC Compliance error [M4.3]: Producers shall not create a document element that contains refinements to the Dublin Core elements, except for the two specified in the schema: and Consumers shall consider a document element that violates this constraint to be an error."); - - // Rule M4.4 - if (el.getAttributeNodeNS(XMLConstants.XML_NS_URI, "lang") != null) - throw new InvalidFormatException( - "OPC Compliance error [M4.4]: Producers shall not create a document element that contains the xml:lang attribute. Consumers shall consider a document element that violates this constraint to be an error."); - - // Rule M4.5 - if (el.getNamespaceURI().equals(PackageProperties.NAMESPACE_DCTERMS)) { - // DCTerms namespace only use with 'created' and 'modified' elements - if (!(elName.equals(KEYWORD_CREATED) || elName.equals(KEYWORD_MODIFIED))) - throw new InvalidFormatException("Namespace error : " + elName - + " shouldn't have the following naemspace -> " - + PackageProperties.NAMESPACE_DCTERMS); - - // Check for the 'xsi:type' attribute - Attr typeAtt = el.getAttributeNodeNS(XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, "type"); - if (typeAtt == null) - throw new InvalidFormatException("The element '" + elName - + "' must have the 'xsi:type' attribute present !"); - - // Check for the attribute value => 'dcterms:W3CDTF' - if (!typeAtt.getValue().equals(el.getPrefix() + ":W3CDTF")) - throw new InvalidFormatException("The element '" + elName - + "' must have the 'xsi:type' attribute with the value '" + el.getPrefix() + ":W3CDTF', but had '" + typeAtt.getValue() + "' !"); - } - - // Check its children - NodeList childElements = el.getElementsByTagName("*"); - int childElementCount = childElements.getLength(); - for (int i = 0; i < childElementCount; i++) - checkElementForOPCCompliance((Element)childElements.item(i)); - } -} diff --git a/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/unmarshallers/UnmarshallContext.java b/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/unmarshallers/UnmarshallContext.java deleted file mode 100644 index c4e01ca7a..000000000 --- a/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/unmarshallers/UnmarshallContext.java +++ /dev/null @@ -1,96 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc.internal.unmarshallers; - -import java.util.zip.ZipEntry; - -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackagePartName; - -/** - * Context needed for the unmarshall process of a part. This class is immutable. - * - * @author Julien Chable - * @version 1.0 - */ -public final class UnmarshallContext { - - private OPCPackage _package; - - private PackagePartName partName; - - private ZipEntry zipEntry; - - /** - * Constructor. - * - * @param targetPackage - * Container. - * @param partName - * Name of the part to unmarshall. - */ - public UnmarshallContext(OPCPackage targetPackage, PackagePartName partName) { - this._package = targetPackage; - this.partName = partName; - } - - /** - * @return the container - */ - OPCPackage getPackage() { - return _package; - } - - /** - * @param container - * the container to set - */ - public void setPackage(OPCPackage container) { - this._package = container; - } - - /** - * @return the partName - */ - PackagePartName getPartName() { - return partName; - } - - /** - * @param partName - * the partName to set - */ - public void setPartName(PackagePartName partName) { - this.partName = partName; - } - - /** - * @return the zipEntry - */ - ZipEntry getZipEntry() { - return zipEntry; - } - - /** - * @param zipEntry - * the zipEntry to set - */ - public void setZipEntry(ZipEntry zipEntry) { - this.zipEntry = zipEntry; - } -} diff --git a/src/ooxml/java/org/apache/poi/openxml4j/util/Nullable.java b/src/ooxml/java/org/apache/poi/openxml4j/util/Nullable.java deleted file mode 100644 index 8c1a24c86..000000000 --- a/src/ooxml/java/org/apache/poi/openxml4j/util/Nullable.java +++ /dev/null @@ -1,72 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.util; - -/** - * An immutable object that could be defined as null. - * - * @author Julien Chable - * @version 0.9 - */ -public final class Nullable { - - private E value; - - /** - * Constructor. - */ - public Nullable() { - // Do nothing - } - - /** - * Constructor. - * - * @param value - * The value to set to this nullable. - */ - public Nullable(E value) { - this.value = value; - } - - /** - * Get the store value if any. - * - * @return the store value - */ - public E getValue() { - return value; - } - - /** - * Get the status of this nullable. - * - * @return true if the nullable store a value (empty string is - * considered to be a value) else false. - */ - public boolean hasValue() { - return value != null; - } - - /** - * Set the stored value to null. - */ - public void nullify() { - value = null; - } -} diff --git a/src/ooxml/java/org/apache/poi/openxml4j/util/ZipEntrySource.java b/src/ooxml/java/org/apache/poi/openxml4j/util/ZipEntrySource.java deleted file mode 100644 index 8ce82325c..000000000 --- a/src/ooxml/java/org/apache/poi/openxml4j/util/ZipEntrySource.java +++ /dev/null @@ -1,55 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.openxml4j.util; - -import java.io.Closeable; -import java.io.IOException; -import java.io.InputStream; -import java.util.Enumeration; -import java.util.zip.ZipEntry; - -/** - * An Interface to make getting the different bits - * of a Zip File easy. - * Allows you to get at the ZipEntries, without - * needing to worry about ZipFile vs ZipInputStream - * being annoyingly very different. - */ -public interface ZipEntrySource extends Closeable { - /** - * Returns an Enumeration of all the Entries - */ - public Enumeration getEntries(); - - /** - * Returns an InputStream of the decompressed - * data that makes up the entry - */ - public InputStream getInputStream(ZipEntry entry) throws IOException; - - /** - * Indicates we are done with reading, and - * resources may be freed - */ - @Override - public void close() throws IOException; - - /** - * Has close been called already? - */ - public boolean isClosed(); -} diff --git a/src/ooxml/java/org/apache/poi/openxml4j/util/ZipFileZipEntrySource.java b/src/ooxml/java/org/apache/poi/openxml4j/util/ZipFileZipEntrySource.java deleted file mode 100644 index 09317d361..000000000 --- a/src/ooxml/java/org/apache/poi/openxml4j/util/ZipFileZipEntrySource.java +++ /dev/null @@ -1,59 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.openxml4j.util; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Enumeration; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; - -/** - * A ZipEntrySource wrapper around a ZipFile. - * Should be as low in terms of memory as a - * normal ZipFile implementation is. - */ -public class ZipFileZipEntrySource implements ZipEntrySource { - private ZipFile zipArchive; - public ZipFileZipEntrySource(ZipFile zipFile) { - this.zipArchive = zipFile; - } - - public void close() throws IOException { - if(zipArchive != null) { - zipArchive.close(); - } - zipArchive = null; - } - public boolean isClosed() { - return (zipArchive == null); - } - - public Enumeration getEntries() { - if (zipArchive == null) - throw new IllegalStateException("Zip File is closed"); - - return zipArchive.entries(); - } - - public InputStream getInputStream(ZipEntry entry) throws IOException { - if (zipArchive == null) - throw new IllegalStateException("Zip File is closed"); - - return zipArchive.getInputStream(entry); - } -} diff --git a/src/ooxml/java/org/apache/poi/openxml4j/util/ZipInputStreamZipEntrySource.java b/src/ooxml/java/org/apache/poi/openxml4j/util/ZipInputStreamZipEntrySource.java deleted file mode 100644 index 4c2b9df3e..000000000 --- a/src/ooxml/java/org/apache/poi/openxml4j/util/ZipInputStreamZipEntrySource.java +++ /dev/null @@ -1,143 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.openxml4j.util; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.zip.ZipEntry; - -import org.apache.poi.openxml4j.util.ZipSecureFile.ThresholdInputStream; - -/** - * Provides a way to get at all the ZipEntries - * from a ZipInputStream, as many times as required. - * Allows a ZipInputStream to be treated much like - * a ZipFile, for a price in terms of memory. - * Be sure to call {@link #close()} as soon as you're - * done, to free up that memory! - */ -public class ZipInputStreamZipEntrySource implements ZipEntrySource { - private ArrayList zipEntries; - - /** - * Reads all the entries from the ZipInputStream - * into memory, and closes the source stream. - * We'll then eat lots of memory, but be able to - * work with the entries at-will. - */ - public ZipInputStreamZipEntrySource(ThresholdInputStream inp) throws IOException { - zipEntries = new ArrayList(); - - boolean going = true; - while(going) { - ZipEntry zipEntry = inp.getNextEntry(); - if(zipEntry == null) { - going = false; - } else { - FakeZipEntry entry = new FakeZipEntry(zipEntry, inp); - inp.closeEntry(); - - zipEntries.add(entry); - } - } - inp.close(); - } - - public Enumeration getEntries() { - return new EntryEnumerator(); - } - - public InputStream getInputStream(ZipEntry zipEntry) { - assert (zipEntry instanceof FakeZipEntry); - FakeZipEntry entry = (FakeZipEntry)zipEntry; - return entry.getInputStream(); - } - - public void close() { - // Free the memory - zipEntries = null; - } - public boolean isClosed() { - return (zipEntries == null); - } - - /** - * Why oh why oh why are Iterator and Enumeration - * still not compatible? - */ - private class EntryEnumerator implements Enumeration { - private Iterator iterator; - - private EntryEnumerator() { - iterator = zipEntries.iterator(); - } - - public boolean hasMoreElements() { - return iterator.hasNext(); - } - - public ZipEntry nextElement() { - return iterator.next(); - } - } - - /** - * So we can close the real zip entry and still - * effectively work with it. - * Holds the (decompressed!) data in memory, so - * close this as soon as you can! - */ - public static class FakeZipEntry extends ZipEntry { - private byte[] data; - - public FakeZipEntry(ZipEntry entry, InputStream inp) throws IOException { - super(entry.getName()); - - // Grab the de-compressed contents for later - ByteArrayOutputStream baos; - - long entrySize = entry.getSize(); - - if (entrySize !=-1) { - if (entrySize>=Integer.MAX_VALUE) { - throw new IOException("ZIP entry size is too large"); - } - - baos = new ByteArrayOutputStream((int) entrySize); - } else { - baos = new ByteArrayOutputStream(); - } - - byte[] buffer = new byte[4096]; - int read = 0; - while( (read = inp.read(buffer)) != -1 ) { - baos.write(buffer, 0, read); - } - - data = baos.toByteArray(); - } - - public InputStream getInputStream() { - return new ByteArrayInputStream(data); - } - } -} diff --git a/src/ooxml/java/org/apache/poi/openxml4j/util/ZipSecureFile.java b/src/ooxml/java/org/apache/poi/openxml4j/util/ZipSecureFile.java deleted file mode 100644 index 47af1bde7..000000000 --- a/src/ooxml/java/org/apache/poi/openxml4j/util/ZipSecureFile.java +++ /dev/null @@ -1,328 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.util; - -import java.io.File; -import java.io.FilterInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.PushbackInputStream; -import java.lang.reflect.Field; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.util.zip.InflaterInputStream; -import java.util.zip.ZipEntry; -import java.util.zip.ZipException; -import java.util.zip.ZipFile; -import java.util.zip.ZipInputStream; - -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.util.SuppressForbidden; - -/** - * This class wraps a {@link ZipFile} in order to check the - * entries for zip bombs - * while reading the archive. - * If a {@link ZipInputStream} is directly used, the wrapper - * can be applied via {@link #addThreshold(InputStream)}. - * The alert limits can be globally defined via {@link #setMaxEntrySize(long)} - * and {@link #setMinInflateRatio(double)}. - */ -public class ZipSecureFile extends ZipFile { - private static final POILogger LOG = POILogFactory.getLogger(ZipSecureFile.class); - - private static double MIN_INFLATE_RATIO = 0.01d; - private static long MAX_ENTRY_SIZE = 0xFFFFFFFFL; - - // don't alert for expanded sizes smaller than 100k - private final static long GRACE_ENTRY_SIZE = 100*1024L; - - // The default maximum size of extracted text - private static long MAX_TEXT_SIZE = 10*1024*1024L; - - /** - * Sets the ratio between de- and inflated bytes to detect zipbomb. - * It defaults to 1% (= 0.01d), i.e. when the compression is better than - * 1% for any given read package part, the parsing will fail indicating a - * Zip-Bomb. - * - * @param ratio the ratio between de- and inflated bytes to detect zipbomb - */ - public static void setMinInflateRatio(double ratio) { - MIN_INFLATE_RATIO = ratio; - } - - /** - * Returns the current minimum compression rate that is used. - * - * See setMinInflateRatio() for details. - * - * @return The min accepted compression-ratio. - */ - public static double getMinInflateRatio() { - return MIN_INFLATE_RATIO; - } - - /** - * Sets the maximum file size of a single zip entry. It defaults to 4GB, - * i.e. the 32-bit zip format maximum. - * - * This can be used to limit memory consumption and protect against - * security vulnerabilities when documents are provided by users. - * - * @param maxEntrySize the max. file size of a single zip entry - */ - public static void setMaxEntrySize(long maxEntrySize) { - if (maxEntrySize < 0 || maxEntrySize > 0xFFFFFFFFL) { // don't use MAX_ENTRY_SIZE here! - throw new IllegalArgumentException("Max entry size is bounded [0-4GB], but had " + maxEntrySize); - } - MAX_ENTRY_SIZE = maxEntrySize; - } - - /** - * Returns the current maximum allowed uncompressed file size. - * - * See setMaxEntrySize() for details. - * - * @return The max accepted uncompressed file size. - */ - public static long getMaxEntrySize() { - return MAX_ENTRY_SIZE; - } - - /** - * Sets the maximum number of characters of text that are - * extracted before an exception is thrown during extracting - * text from documents. - * - * This can be used to limit memory consumption and protect against - * security vulnerabilities when documents are provided by users. - * - * @param maxTextSize the max. file size of a single zip entry - */ - public static void setMaxTextSize(long maxTextSize) { - if (maxTextSize < 0 || maxTextSize > 0xFFFFFFFFL) { // don't use MAX_ENTRY_SIZE here! - throw new IllegalArgumentException("Max text size is bounded [0-4GB], but had " + maxTextSize); - } - MAX_TEXT_SIZE = maxTextSize; - } - - /** - * Returns the current maximum allowed text size. - * - * See setMaxTextSize() for details. - * - * @return The max accepted text size. - */ - public static long getMaxTextSize() { - return MAX_TEXT_SIZE; - } - - public ZipSecureFile(File file, int mode) throws ZipException, IOException { - super(file, mode); - } - - public ZipSecureFile(File file) throws ZipException, IOException { - super(file); - } - - public ZipSecureFile(String name) throws ZipException, IOException { - super(name); - } - - /** - * Returns an input stream for reading the contents of the specified - * zip file entry. - * - *

    Closing this ZIP file will, in turn, close all input - * streams that have been returned by invocations of this method. - * - * @param entry the zip file entry - * @return the input stream for reading the contents of the specified - * zip file entry. - * @throws ZipException if a ZIP format error has occurred - * @throws IOException if an I/O error has occurred - * @throws IllegalStateException if the zip file has been closed - */ - @Override - @SuppressWarnings("resource") - public InputStream getInputStream(ZipEntry entry) throws IOException { - InputStream zipIS = super.getInputStream(entry); - return addThreshold(zipIS); - } - - public static ThresholdInputStream addThreshold(final InputStream zipIS) throws IOException { - ThresholdInputStream newInner; - if (zipIS instanceof InflaterInputStream) { - newInner = AccessController.doPrivileged(new PrivilegedAction() { // NOSONAR - @Override - @SuppressForbidden("TODO: Fix this to not use reflection (it will break in Java 9)! " + - "Better would be to wrap *before* instead of trying to insert wrapper afterwards.") - public ThresholdInputStream run() { - try { - Field f = FilterInputStream.class.getDeclaredField("in"); - f.setAccessible(true); - InputStream oldInner = (InputStream)f.get(zipIS); - ThresholdInputStream newInner2 = new ThresholdInputStream(oldInner, null); - f.set(zipIS, newInner2); - return newInner2; - } catch (Exception ex) { - LOG.log(POILogger.WARN, "SecurityManager doesn't allow manipulation via reflection for zipbomb detection - continue with original input stream", ex); - } - return null; - } - }); - } else { - // the inner stream is a ZipFileInputStream, i.e. the data wasn't compressed - newInner = null; - } - - return new ThresholdInputStream(zipIS, newInner); - } - - public static class ThresholdInputStream extends PushbackInputStream { - long counter = 0; - ThresholdInputStream cis; - - public ThresholdInputStream(InputStream is, ThresholdInputStream cis) { - super(is,1); - this.cis = cis; - } - - @Override - public int read() throws IOException { - int b = in.read(); - if (b > -1) { - advance(1); - } - return b; - } - - @Override - public int read(byte b[], int off, int len) throws IOException { - int cnt = in.read(b, off, len); - if (cnt > -1) { - advance(cnt); - } - return cnt; - } - - @Override - public long skip(long n) throws IOException { - counter = 0; - return in.skip(n); - } - - @Override - public synchronized void reset() throws IOException { - counter = 0; - in.reset(); - } - - public void advance(int advance) throws IOException { - counter += advance; - - // check the file size first, in case we are working on uncompressed streams - if(counter > MAX_ENTRY_SIZE) { - throw new IOException("Zip bomb detected! The file would exceed the max size of the expanded data in the zip-file. " - + "This may indicates that the file is used to inflate memory usage and thus could pose a security risk. " - + "You can adjust this limit via ZipSecureFile.setMaxEntrySize() if you need to work with files which are very large. " - + "Counter: " + counter + ", cis.counter: " + (cis == null ? 0 : cis.counter) - + "Limits: MAX_ENTRY_SIZE: " + MAX_ENTRY_SIZE); - } - - // no expanded size? - if (cis == null) { - return; - } - - // don't alert for small expanded size - if (counter <= GRACE_ENTRY_SIZE) { - return; - } - - double ratio = (double)cis.counter/(double)counter; - if (ratio >= MIN_INFLATE_RATIO) { - return; - } - - // one of the limits was reached, report it - throw new IOException("Zip bomb detected! The file would exceed the max. ratio of compressed file size to the size of the expanded data. " - + "This may indicate that the file is used to inflate memory usage and thus could pose a security risk. " - + "You can adjust this limit via ZipSecureFile.setMinInflateRatio() if you need to work with files which exceed this limit. " - + "Counter: " + counter + ", cis.counter: " + cis.counter + ", ratio: " + (((double)cis.counter)/counter) - + "Limits: MIN_INFLATE_RATIO: " + MIN_INFLATE_RATIO); - } - - public ZipEntry getNextEntry() throws IOException { - if (!(in instanceof ZipInputStream)) { - throw new UnsupportedOperationException("underlying stream is not a ZipInputStream"); - } - counter = 0; - return ((ZipInputStream)in).getNextEntry(); - } - - public void closeEntry() throws IOException { - if (!(in instanceof ZipInputStream)) { - throw new UnsupportedOperationException("underlying stream is not a ZipInputStream"); - } - counter = 0; - ((ZipInputStream)in).closeEntry(); - } - - @Override - public void unread(int b) throws IOException { - if (!(in instanceof PushbackInputStream)) { - throw new UnsupportedOperationException("underlying stream is not a PushbackInputStream"); - } - if (--counter < 0) { - counter = 0; - } - ((PushbackInputStream)in).unread(b); - } - - @Override - public void unread(byte[] b, int off, int len) throws IOException { - if (!(in instanceof PushbackInputStream)) { - throw new UnsupportedOperationException("underlying stream is not a PushbackInputStream"); - } - counter -= len; - if (--counter < 0) { - counter = 0; - } - ((PushbackInputStream)in).unread(b, off, len); - } - - @Override - @SuppressForbidden("just delegating") - public int available() throws IOException { - return in.available(); - } - - @Override - public boolean markSupported() { - return in.markSupported(); - } - - @Override - public synchronized void mark(int readlimit) { - in.mark(readlimit); - } - } -} diff --git a/src/ooxml/java/org/apache/poi/poifs/crypt/agile/AgileDecryptor.java b/src/ooxml/java/org/apache/poi/poifs/crypt/agile/AgileDecryptor.java deleted file mode 100644 index 0263790df..000000000 --- a/src/ooxml/java/org/apache/poi/poifs/crypt/agile/AgileDecryptor.java +++ /dev/null @@ -1,356 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.poifs.crypt.agile; - -import static org.apache.poi.poifs.crypt.CryptoFunctions.generateIv; -import static org.apache.poi.poifs.crypt.CryptoFunctions.generateKey; -import static org.apache.poi.poifs.crypt.CryptoFunctions.getBlock0; -import static org.apache.poi.poifs.crypt.CryptoFunctions.getCipher; -import static org.apache.poi.poifs.crypt.CryptoFunctions.getMessageDigest; -import static org.apache.poi.poifs.crypt.CryptoFunctions.hashPassword; - -import java.io.IOException; -import java.io.InputStream; -import java.security.GeneralSecurityException; -import java.security.KeyPair; -import java.security.MessageDigest; -import java.security.cert.X509Certificate; -import java.security.spec.AlgorithmParameterSpec; -import java.util.Arrays; - -import javax.crypto.Cipher; -import javax.crypto.Mac; -import javax.crypto.SecretKey; -import javax.crypto.spec.IvParameterSpec; -import javax.crypto.spec.RC2ParameterSpec; -import javax.crypto.spec.SecretKeySpec; - -import org.apache.poi.EncryptedDocumentException; -import org.apache.poi.poifs.crypt.ChainingMode; -import org.apache.poi.poifs.crypt.ChunkedCipherInputStream; -import org.apache.poi.poifs.crypt.CipherAlgorithm; -import org.apache.poi.poifs.crypt.CryptoFunctions; -import org.apache.poi.poifs.crypt.Decryptor; -import org.apache.poi.poifs.crypt.EncryptionHeader; -import org.apache.poi.poifs.crypt.EncryptionInfo; -import org.apache.poi.poifs.crypt.HashAlgorithm; -import org.apache.poi.poifs.crypt.agile.AgileEncryptionVerifier.AgileCertificateEntry; -import org.apache.poi.poifs.filesystem.DirectoryNode; -import org.apache.poi.poifs.filesystem.DocumentInputStream; -import org.apache.poi.util.LittleEndian; - -/** - * Decryptor implementation for Agile Encryption - */ -public class AgileDecryptor extends Decryptor implements Cloneable { - private long _length = -1; - - /* package */ static final byte[] kVerifierInputBlock; - /* package */ static final byte[] kHashedVerifierBlock; - /* package */ static final byte[] kCryptoKeyBlock; - /* package */ static final byte[] kIntegrityKeyBlock; - /* package */ static final byte[] kIntegrityValueBlock; - - static { - kVerifierInputBlock = - new byte[] { (byte)0xfe, (byte)0xa7, (byte)0xd2, (byte)0x76, - (byte)0x3b, (byte)0x4b, (byte)0x9e, (byte)0x79 }; - kHashedVerifierBlock = - new byte[] { (byte)0xd7, (byte)0xaa, (byte)0x0f, (byte)0x6d, - (byte)0x30, (byte)0x61, (byte)0x34, (byte)0x4e }; - kCryptoKeyBlock = - new byte[] { (byte)0x14, (byte)0x6e, (byte)0x0b, (byte)0xe7, - (byte)0xab, (byte)0xac, (byte)0xd0, (byte)0xd6 }; - kIntegrityKeyBlock = - new byte[] { (byte)0x5f, (byte)0xb2, (byte)0xad, (byte)0x01, - (byte)0x0c, (byte)0xb9, (byte)0xe1, (byte)0xf6 }; - kIntegrityValueBlock = - new byte[] { (byte)0xa0, (byte)0x67, (byte)0x7f, (byte)0x02, - (byte)0xb2, (byte)0x2c, (byte)0x84, (byte)0x33 }; - } - - protected AgileDecryptor() { - } - - /** - * set decryption password - */ - @Override - public boolean verifyPassword(String password) throws GeneralSecurityException { - AgileEncryptionVerifier ver = (AgileEncryptionVerifier)getEncryptionInfo().getVerifier(); - AgileEncryptionHeader header = (AgileEncryptionHeader)getEncryptionInfo().getHeader(); - - int blockSize = header.getBlockSize(); - - byte[] pwHash = hashPassword(password, ver.getHashAlgorithm(), ver.getSalt(), ver.getSpinCount()); - - /** - * encryptedVerifierHashInput: This attribute MUST be generated by using the following steps: - * 1. Generate a random array of bytes with the number of bytes used specified by the saltSize - * attribute. - * 2. Generate an encryption key as specified in section 2.3.4.11 by using the user-supplied password, - * the binary byte array used to create the saltValue attribute, and a blockKey byte array - * consisting of the following bytes: 0xfe, 0xa7, 0xd2, 0x76, 0x3b, 0x4b, 0x9e, and 0x79. - * 3. Encrypt the random array of bytes generated in step 1 by using the binary form of the saltValue - * attribute as an initialization vector as specified in section 2.3.4.12. If the array of bytes is not an - * integral multiple of blockSize bytes, pad the array with 0x00 to the next integral multiple of - * blockSize bytes. - * 4. Use base64 to encode the result of step 3. - */ - byte verfierInputEnc[] = hashInput(ver, pwHash, kVerifierInputBlock, ver.getEncryptedVerifier(), Cipher.DECRYPT_MODE); - setVerifier(verfierInputEnc); - MessageDigest hashMD = getMessageDigest(ver.getHashAlgorithm()); - byte[] verifierHash = hashMD.digest(verfierInputEnc); - - /** - * encryptedVerifierHashValue: This attribute MUST be generated by using the following steps: - * 1. Obtain the hash value of the random array of bytes generated in step 1 of the steps for - * encryptedVerifierHashInput. - * 2. Generate an encryption key as specified in section 2.3.4.11 by using the user-supplied password, - * the binary byte array used to create the saltValue attribute, and a blockKey byte array - * consisting of the following bytes: 0xd7, 0xaa, 0x0f, 0x6d, 0x30, 0x61, 0x34, and 0x4e. - * 3. Encrypt the hash value obtained in step 1 by using the binary form of the saltValue attribute as - * an initialization vector as specified in section 2.3.4.12. If hashSize is not an integral multiple of - * blockSize bytes, pad the hash value with 0x00 to an integral multiple of blockSize bytes. - * 4. Use base64 to encode the result of step 3. - */ - byte verifierHashDec[] = hashInput(ver, pwHash, kHashedVerifierBlock, ver.getEncryptedVerifierHash(), Cipher.DECRYPT_MODE); - verifierHashDec = getBlock0(verifierHashDec, ver.getHashAlgorithm().hashSize); - - /** - * encryptedKeyValue: This attribute MUST be generated by using the following steps: - * 1. Generate a random array of bytes that is the same size as specified by the - * Encryptor.KeyData.keyBits attribute of the parent element. - * 2. Generate an encryption key as specified in section 2.3.4.11, using the user-supplied password, - * the binary byte array used to create the saltValue attribute, and a blockKey byte array - * consisting of the following bytes: 0x14, 0x6e, 0x0b, 0xe7, 0xab, 0xac, 0xd0, and 0xd6. - * 3. Encrypt the random array of bytes generated in step 1 by using the binary form of the saltValue - * attribute as an initialization vector as specified in section 2.3.4.12. If the array of bytes is not an - * integral multiple of blockSize bytes, pad the array with 0x00 to an integral multiple of - * blockSize bytes. - * 4. Use base64 to encode the result of step 3. - */ - byte keyspec[] = hashInput(ver, pwHash, kCryptoKeyBlock, ver.getEncryptedKey(), Cipher.DECRYPT_MODE); - keyspec = getBlock0(keyspec, header.getKeySize()/8); - SecretKeySpec secretKey = new SecretKeySpec(keyspec, header.getCipherAlgorithm().jceId); - - /** - * 1. Obtain the intermediate key by decrypting the encryptedKeyValue from a KeyEncryptor - * contained within the KeyEncryptors sequence. Use this key for encryption operations in the - * remaining steps of this section. - * 2. Generate a random array of bytes, known as Salt, of the same length as the value of the - * KeyData.hashSize attribute. - * 3. Encrypt the random array of bytes generated in step 2 by using the binary form of the - * KeyData.saltValue attribute and a blockKey byte array consisting of the following bytes: 0x5f, - * 0xb2, 0xad, 0x01, 0x0c, 0xb9, 0xe1, and 0xf6 used to form an initialization vector as specified in - * section 2.3.4.12. If the array of bytes is not an integral multiple of blockSize bytes, pad the - * array with 0x00 to the next integral multiple of blockSize bytes. - * 4. Assign the encryptedHmacKey attribute to the base64-encoded form of the result of step 3. - */ - byte vec[] = CryptoFunctions.generateIv(header.getHashAlgorithm(), header.getKeySalt(), kIntegrityKeyBlock, blockSize); - CipherAlgorithm cipherAlgo = header.getCipherAlgorithm(); - Cipher cipher = getCipher(secretKey, cipherAlgo, header.getChainingMode(), vec, Cipher.DECRYPT_MODE); - byte hmacKey[] = cipher.doFinal(header.getEncryptedHmacKey()); - hmacKey = getBlock0(hmacKey, header.getHashAlgorithm().hashSize); - - /** - * 5. Generate an HMAC, as specified in [RFC2104], of the encrypted form of the data (message), - * which the DataIntegrity element will verify by using the Salt generated in step 2 as the key. - * Note that the entire EncryptedPackage stream (1), including the StreamSize field, MUST be - * used as the message. - * 6. Encrypt the HMAC as in step 3 by using a blockKey byte array consisting of the following bytes: - * 0xa0, 0x67, 0x7f, 0x02, 0xb2, 0x2c, 0x84, and 0x33. - * 7. Assign the encryptedHmacValue attribute to the base64-encoded form of the result of step 6. - */ - vec = CryptoFunctions.generateIv(header.getHashAlgorithm(), header.getKeySalt(), kIntegrityValueBlock, blockSize); - cipher = getCipher(secretKey, cipherAlgo, ver.getChainingMode(), vec, Cipher.DECRYPT_MODE); - byte hmacValue[] = cipher.doFinal(header.getEncryptedHmacValue()); - hmacValue = getBlock0(hmacValue, header.getHashAlgorithm().hashSize); - - if (Arrays.equals(verifierHashDec, verifierHash)) { - setSecretKey(secretKey); - setIntegrityHmacKey(hmacKey); - setIntegrityHmacValue(hmacValue); - return true; - } else { - return false; - } - } - - /** - * instead of a password, it's also possible to decrypt via certificate. - * Warning: this code is experimental and hasn't been validated - * - * @see Agile encryption with certificates - * - * @param keyPair - * @param x509 - * @return true, when the data can be successfully decrypted with the given private key - * @throws GeneralSecurityException - */ - public boolean verifyPassword(KeyPair keyPair, X509Certificate x509) throws GeneralSecurityException { - AgileEncryptionVerifier ver = (AgileEncryptionVerifier)getEncryptionInfo().getVerifier(); - AgileEncryptionHeader header = (AgileEncryptionHeader)getEncryptionInfo().getHeader(); - HashAlgorithm hashAlgo = header.getHashAlgorithm(); - CipherAlgorithm cipherAlgo = header.getCipherAlgorithm(); - int blockSize = header.getBlockSize(); - - AgileCertificateEntry ace = null; - for (AgileCertificateEntry aceEntry : ver.getCertificates()) { - if (x509.equals(aceEntry.x509)) { - ace = aceEntry; - break; - } - } - if (ace == null) { - return false; - } - - Cipher cipher = Cipher.getInstance("RSA"); - cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate()); - byte keyspec[] = cipher.doFinal(ace.encryptedKey); - SecretKeySpec secretKey = new SecretKeySpec(keyspec, ver.getCipherAlgorithm().jceId); - - Mac x509Hmac = CryptoFunctions.getMac(hashAlgo); - x509Hmac.init(secretKey); - byte certVerifier[] = x509Hmac.doFinal(ace.x509.getEncoded()); - - byte vec[] = CryptoFunctions.generateIv(hashAlgo, header.getKeySalt(), kIntegrityKeyBlock, blockSize); - cipher = getCipher(secretKey, cipherAlgo, header.getChainingMode(), vec, Cipher.DECRYPT_MODE); - byte hmacKey[] = cipher.doFinal(header.getEncryptedHmacKey()); - hmacKey = getBlock0(hmacKey, hashAlgo.hashSize); - - vec = CryptoFunctions.generateIv(hashAlgo, header.getKeySalt(), kIntegrityValueBlock, blockSize); - cipher = getCipher(secretKey, cipherAlgo, header.getChainingMode(), vec, Cipher.DECRYPT_MODE); - byte hmacValue[] = cipher.doFinal(header.getEncryptedHmacValue()); - hmacValue = getBlock0(hmacValue, hashAlgo.hashSize); - - - if (Arrays.equals(ace.certVerifier, certVerifier)) { - setSecretKey(secretKey); - setIntegrityHmacKey(hmacKey); - setIntegrityHmacValue(hmacValue); - return true; - } else { - return false; - } - } - - protected static int getNextBlockSize(int inputLen, int blockSize) { - int fillSize; - for (fillSize=blockSize; fillSize certList = new ArrayList(); - private int keyBits = -1; - private int blockSize = -1; - - public AgileEncryptionVerifier(String descriptor) { - this(AgileEncryptionInfoBuilder.parseDescriptor(descriptor)); - } - - protected AgileEncryptionVerifier(EncryptionDocument ed) { - Iterator encList = ed.getEncryption().getKeyEncryptors().getKeyEncryptorList().iterator(); - CTPasswordKeyEncryptor keyData; - try { - keyData = encList.next().getEncryptedPasswordKey(); - if (keyData == null) { - throw new NullPointerException("encryptedKey not set"); - } - } catch (Exception e) { - throw new EncryptedDocumentException("Unable to parse keyData", e); - } - - int kb = (int)keyData.getKeyBits(); - CipherAlgorithm ca = CipherAlgorithm.fromXmlId(keyData.getCipherAlgorithm().toString(), kb); - setCipherAlgorithm(ca); - - setKeySize(kb); - - int blockSize = keyData.getBlockSize(); - setBlockSize(blockSize); - - int hashSize = keyData.getHashSize(); - - HashAlgorithm ha = HashAlgorithm.fromEcmaId(keyData.getHashAlgorithm().toString()); - setHashAlgorithm(ha); - - if (getHashAlgorithm().hashSize != hashSize) { - throw new EncryptedDocumentException("Unsupported hash algorithm: " + - keyData.getHashAlgorithm() + " @ " + hashSize + " bytes"); - } - - setSpinCount(keyData.getSpinCount()); - setEncryptedVerifier(keyData.getEncryptedVerifierHashInput()); - setSalt(keyData.getSaltValue()); - setEncryptedKey(keyData.getEncryptedKeyValue()); - setEncryptedVerifierHash(keyData.getEncryptedVerifierHashValue()); - - int saltSize = keyData.getSaltSize(); - if (saltSize != getSalt().length) { - throw new EncryptedDocumentException("Invalid salt size"); - } - - switch (keyData.getCipherChaining().intValue()) { - case STCipherChaining.INT_CHAINING_MODE_CBC: - setChainingMode(ChainingMode.cbc); - break; - case STCipherChaining.INT_CHAINING_MODE_CFB: - setChainingMode(ChainingMode.cfb); - break; - default: - throw new EncryptedDocumentException("Unsupported chaining mode - "+keyData.getCipherChaining().toString()); - } - - if (!encList.hasNext()) { - return; - } - - try { - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - while (encList.hasNext()) { - CTCertificateKeyEncryptor certKey = encList.next().getEncryptedCertificateKey(); - AgileCertificateEntry ace = new AgileCertificateEntry(); - ace.certVerifier = certKey.getCertVerifier(); - ace.encryptedKey = certKey.getEncryptedKeyValue(); - ace.x509 = (X509Certificate)cf.generateCertificate(new ByteArrayInputStream(certKey.getX509Certificate())); - certList.add(ace); - } - } catch (GeneralSecurityException e) { - throw new EncryptedDocumentException("can't parse X509 certificate", e); - } - } - - public AgileEncryptionVerifier(CipherAlgorithm cipherAlgorithm, HashAlgorithm hashAlgorithm, int keyBits, int blockSize, ChainingMode chainingMode) { - setCipherAlgorithm(cipherAlgorithm); - setHashAlgorithm(hashAlgorithm); - setChainingMode(chainingMode); - setKeySize(keyBits); - setBlockSize(blockSize); - setSpinCount(100000); // TODO: use parameter - } - - @Override - protected void setSalt(byte salt[]) { - if (salt == null || salt.length != getCipherAlgorithm().blockSize) { - throw new EncryptedDocumentException("invalid verifier salt"); - } - super.setSalt(salt); - } - - // make method visible for this package - @Override - protected void setEncryptedVerifier(byte encryptedVerifier[]) { - super.setEncryptedVerifier(encryptedVerifier); - } - - // make method visible for this package - @Override - protected void setEncryptedVerifierHash(byte encryptedVerifierHash[]) { - super.setEncryptedVerifierHash(encryptedVerifierHash); - } - - // make method visible for this package - @Override - protected void setEncryptedKey(byte[] encryptedKey) { - super.setEncryptedKey(encryptedKey); - } - - public void addCertificate(X509Certificate x509) { - AgileCertificateEntry ace = new AgileCertificateEntry(); - ace.x509 = x509; - certList.add(ace); - } - - public List getCertificates() { - return certList; - } - - @Override - public AgileEncryptionVerifier clone() throws CloneNotSupportedException { - AgileEncryptionVerifier other = (AgileEncryptionVerifier)super.clone(); - // TODO: deep copy of certList - other.certList = new ArrayList(certList); - return other; - } - - - /** - * The keysize (in bits) of the verifier data. This usually equals the keysize of the header, - * but only on a few exceptions, like files generated by Office for Mac, can be - * different. - * - * @return the keysize (in bits) of the verifier. - */ - public int getKeySize() { - return keyBits; - } - - - /** - * The blockSize (in bytes) of the verifier data. - * This usually equals the blocksize of the header. - * - * @return the blockSize (in bytes) of the verifier, - */ - public int getBlockSize() { - return blockSize; - } - - /** - * Sets the keysize (in bits) of the verifier - * - * @param keyBits the keysize (in bits) - */ - protected void setKeySize(int keyBits) { - this.keyBits = keyBits; - for (int allowedBits : getCipherAlgorithm().allowedKeySize) { - if (allowedBits == keyBits) { - return; - } - } - throw new EncryptedDocumentException("KeySize "+keyBits+" not allowed for cipher "+getCipherAlgorithm()); - } - - - /** - * Sets the blockSize (in bytes) of the verifier - * - * @param blockSize the blockSize (in bytes) - */ - protected void setBlockSize(int blockSize) { - this.blockSize = blockSize; - } - - @Override - protected final void setCipherAlgorithm(CipherAlgorithm cipherAlgorithm) { - super.setCipherAlgorithm(cipherAlgorithm); - if (cipherAlgorithm.allowedKeySize.length == 1) { - setKeySize(cipherAlgorithm.defaultKeySize); - } - } -} diff --git a/src/ooxml/java/org/apache/poi/poifs/crypt/agile/AgileEncryptor.java b/src/ooxml/java/org/apache/poi/poifs/crypt/agile/AgileEncryptor.java deleted file mode 100644 index 3ffb81003..000000000 --- a/src/ooxml/java/org/apache/poi/poifs/crypt/agile/AgileEncryptor.java +++ /dev/null @@ -1,460 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.poifs.crypt.agile; - -import static org.apache.poi.poifs.crypt.CryptoFunctions.getBlock0; -import static org.apache.poi.poifs.crypt.CryptoFunctions.getCipher; -import static org.apache.poi.poifs.crypt.CryptoFunctions.getMessageDigest; -import static org.apache.poi.poifs.crypt.CryptoFunctions.hashPassword; -import static org.apache.poi.poifs.crypt.DataSpaceMapUtils.createEncryptionEntry; -import static org.apache.poi.poifs.crypt.agile.AgileDecryptor.getNextBlockSize; -import static org.apache.poi.poifs.crypt.agile.AgileDecryptor.hashInput; -import static org.apache.poi.poifs.crypt.agile.AgileDecryptor.kCryptoKeyBlock; -import static org.apache.poi.poifs.crypt.agile.AgileDecryptor.kHashedVerifierBlock; -import static org.apache.poi.poifs.crypt.agile.AgileDecryptor.kIntegrityKeyBlock; -import static org.apache.poi.poifs.crypt.agile.AgileDecryptor.kIntegrityValueBlock; -import static org.apache.poi.poifs.crypt.agile.AgileDecryptor.kVerifierInputBlock; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.security.GeneralSecurityException; -import java.security.MessageDigest; -import java.security.SecureRandom; -import java.security.cert.CertificateEncodingException; -import java.util.HashMap; -import java.util.Map; -import java.util.Random; - -import javax.crypto.Cipher; -import javax.crypto.Mac; -import javax.crypto.SecretKey; -import javax.crypto.spec.SecretKeySpec; - -import org.apache.poi.EncryptedDocumentException; -import org.apache.poi.poifs.crypt.ChunkedCipherOutputStream; -import org.apache.poi.poifs.crypt.CryptoFunctions; -import org.apache.poi.poifs.crypt.DataSpaceMapUtils; -import org.apache.poi.poifs.crypt.EncryptionInfo; -import org.apache.poi.poifs.crypt.Encryptor; -import org.apache.poi.poifs.crypt.HashAlgorithm; -import org.apache.poi.poifs.crypt.agile.AgileEncryptionVerifier.AgileCertificateEntry; -import org.apache.poi.poifs.crypt.standard.EncryptionRecord; -import org.apache.poi.poifs.filesystem.DirectoryNode; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.LittleEndianByteArrayOutputStream; -import org.apache.poi.util.LittleEndianConsts; -import org.apache.xmlbeans.XmlOptions; - -import com.microsoft.schemas.office.x2006.encryption.CTDataIntegrity; -import com.microsoft.schemas.office.x2006.encryption.CTEncryption; -import com.microsoft.schemas.office.x2006.encryption.CTKeyData; -import com.microsoft.schemas.office.x2006.encryption.CTKeyEncryptor; -import com.microsoft.schemas.office.x2006.encryption.CTKeyEncryptors; -import com.microsoft.schemas.office.x2006.encryption.EncryptionDocument; -import com.microsoft.schemas.office.x2006.encryption.STCipherAlgorithm; -import com.microsoft.schemas.office.x2006.encryption.STCipherChaining; -import com.microsoft.schemas.office.x2006.encryption.STHashAlgorithm; -import com.microsoft.schemas.office.x2006.keyEncryptor.certificate.CTCertificateKeyEncryptor; -import com.microsoft.schemas.office.x2006.keyEncryptor.password.CTPasswordKeyEncryptor; - -public class AgileEncryptor extends Encryptor implements Cloneable { - private byte integritySalt[]; - private byte pwHash[]; - - protected AgileEncryptor() { - } - - @Override - public void confirmPassword(String password) { - // see [MS-OFFCRYPTO] - 2.3.3 EncryptionVerifier - Random r = new SecureRandom(); - AgileEncryptionHeader header = (AgileEncryptionHeader)getEncryptionInfo().getHeader(); - int blockSize = header.getBlockSize(); - int keySize = header.getKeySize()/8; - int hashSize = header.getHashAlgorithm().hashSize; - - byte[] newVerifierSalt = new byte[blockSize] - , newVerifier = new byte[blockSize] - , newKeySalt = new byte[blockSize] - , newKeySpec = new byte[keySize] - , newIntegritySalt = new byte[hashSize]; - r.nextBytes(newVerifierSalt); // blocksize - r.nextBytes(newVerifier); // blocksize - r.nextBytes(newKeySalt); // blocksize - r.nextBytes(newKeySpec); // keysize - r.nextBytes(newIntegritySalt); // hashsize - - confirmPassword(password, newKeySpec, newKeySalt, newVerifierSalt, newVerifier, newIntegritySalt); - } - - @Override - public void confirmPassword(String password, byte keySpec[], byte keySalt[], byte verifier[], byte verifierSalt[], byte integritySalt[]) { - AgileEncryptionVerifier ver = (AgileEncryptionVerifier)getEncryptionInfo().getVerifier(); - AgileEncryptionHeader header = (AgileEncryptionHeader)getEncryptionInfo().getHeader(); - - ver.setSalt(verifierSalt); - header.setKeySalt(keySalt); - - int blockSize = header.getBlockSize(); - - pwHash = hashPassword(password, ver.getHashAlgorithm(), verifierSalt, ver.getSpinCount()); - - /** - * encryptedVerifierHashInput: This attribute MUST be generated by using the following steps: - * 1. Generate a random array of bytes with the number of bytes used specified by the saltSize - * attribute. - * 2. Generate an encryption key as specified in section 2.3.4.11 by using the user-supplied password, - * the binary byte array used to create the saltValue attribute, and a blockKey byte array - * consisting of the following bytes: 0xfe, 0xa7, 0xd2, 0x76, 0x3b, 0x4b, 0x9e, and 0x79. - * 3. Encrypt the random array of bytes generated in step 1 by using the binary form of the saltValue - * attribute as an initialization vector as specified in section 2.3.4.12. If the array of bytes is not an - * integral multiple of blockSize bytes, pad the array with 0x00 to the next integral multiple of - * blockSize bytes. - * 4. Use base64 to encode the result of step 3. - */ - byte encryptedVerifier[] = hashInput(ver, pwHash, kVerifierInputBlock, verifier, Cipher.ENCRYPT_MODE); - ver.setEncryptedVerifier(encryptedVerifier); - - - /** - * encryptedVerifierHashValue: This attribute MUST be generated by using the following steps: - * 1. Obtain the hash value of the random array of bytes generated in step 1 of the steps for - * encryptedVerifierHashInput. - * 2. Generate an encryption key as specified in section 2.3.4.11 by using the user-supplied password, - * the binary byte array used to create the saltValue attribute, and a blockKey byte array - * consisting of the following bytes: 0xd7, 0xaa, 0x0f, 0x6d, 0x30, 0x61, 0x34, and 0x4e. - * 3. Encrypt the hash value obtained in step 1 by using the binary form of the saltValue attribute as - * an initialization vector as specified in section 2.3.4.12. If hashSize is not an integral multiple of - * blockSize bytes, pad the hash value with 0x00 to an integral multiple of blockSize bytes. - * 4. Use base64 to encode the result of step 3. - */ - MessageDigest hashMD = getMessageDigest(ver.getHashAlgorithm()); - byte[] hashedVerifier = hashMD.digest(verifier); - byte encryptedVerifierHash[] = hashInput(ver, pwHash, kHashedVerifierBlock, hashedVerifier, Cipher.ENCRYPT_MODE); - ver.setEncryptedVerifierHash(encryptedVerifierHash); - - /** - * encryptedKeyValue: This attribute MUST be generated by using the following steps: - * 1. Generate a random array of bytes that is the same size as specified by the - * Encryptor.KeyData.keyBits attribute of the parent element. - * 2. Generate an encryption key as specified in section 2.3.4.11, using the user-supplied password, - * the binary byte array used to create the saltValue attribute, and a blockKey byte array - * consisting of the following bytes: 0x14, 0x6e, 0x0b, 0xe7, 0xab, 0xac, 0xd0, and 0xd6. - * 3. Encrypt the random array of bytes generated in step 1 by using the binary form of the saltValue - * attribute as an initialization vector as specified in section 2.3.4.12. If the array of bytes is not an - * integral multiple of blockSize bytes, pad the array with 0x00 to an integral multiple of - * blockSize bytes. - * 4. Use base64 to encode the result of step 3. - */ - byte encryptedKey[] = hashInput(ver, pwHash, kCryptoKeyBlock, keySpec, Cipher.ENCRYPT_MODE); - ver.setEncryptedKey(encryptedKey); - - SecretKey secretKey = new SecretKeySpec(keySpec, header.getCipherAlgorithm().jceId); - setSecretKey(secretKey); - - /* - * 2.3.4.14 DataIntegrity Generation (Agile Encryption) - * - * The DataIntegrity element contained within an Encryption element MUST be generated by using - * the following steps: - * 1. Obtain the intermediate key by decrypting the encryptedKeyValue from a KeyEncryptor - * contained within the KeyEncryptors sequence. Use this key for encryption operations in the - * remaining steps of this section. - * 2. Generate a random array of bytes, known as Salt, of the same length as the value of the - * KeyData.hashSize attribute. - * 3. Encrypt the random array of bytes generated in step 2 by using the binary form of the - * KeyData.saltValue attribute and a blockKey byte array consisting of the following bytes: - * 0x5f, 0xb2, 0xad, 0x01, 0x0c, 0xb9, 0xe1, and 0xf6 used to form an initialization vector as - * specified in section 2.3.4.12. If the array of bytes is not an integral multiple of blockSize - * bytes, pad the array with 0x00 to the next integral multiple of blockSize bytes. - * 4. Assign the encryptedHmacKey attribute to the base64-encoded form of the result of step 3. - * 5. Generate an HMAC, as specified in [RFC2104], of the encrypted form of the data (message), - * which the DataIntegrity element will verify by using the Salt generated in step 2 as the key. - * Note that the entire EncryptedPackage stream (1), including the StreamSize field, MUST be - * used as the message. - * 6. Encrypt the HMAC as in step 3 by using a blockKey byte array consisting of the following bytes: - * 0xa0, 0x67, 0x7f, 0x02, 0xb2, 0x2c, 0x84, and 0x33. - * 7. Assign the encryptedHmacValue attribute to the base64-encoded form of the result of step 6. - */ - this.integritySalt = integritySalt.clone(); - - try { - byte vec[] = CryptoFunctions.generateIv(header.getHashAlgorithm(), header.getKeySalt(), kIntegrityKeyBlock, header.getBlockSize()); - Cipher cipher = getCipher(secretKey, header.getCipherAlgorithm(), header.getChainingMode(), vec, Cipher.ENCRYPT_MODE); - byte hmacKey[] = getBlock0(this.integritySalt, getNextBlockSize(this.integritySalt.length, blockSize)); - byte encryptedHmacKey[] = cipher.doFinal(hmacKey); - header.setEncryptedHmacKey(encryptedHmacKey); - - cipher = Cipher.getInstance("RSA"); - for (AgileCertificateEntry ace : ver.getCertificates()) { - cipher.init(Cipher.ENCRYPT_MODE, ace.x509.getPublicKey()); - ace.encryptedKey = cipher.doFinal(getSecretKey().getEncoded()); - Mac x509Hmac = CryptoFunctions.getMac(header.getHashAlgorithm()); - x509Hmac.init(getSecretKey()); - ace.certVerifier = x509Hmac.doFinal(ace.x509.getEncoded()); - } - } catch (GeneralSecurityException e) { - throw new EncryptedDocumentException(e); - } - } - - @Override - public OutputStream getDataStream(DirectoryNode dir) - throws IOException, GeneralSecurityException { - // TODO: initialize headers - AgileCipherOutputStream countStream = new AgileCipherOutputStream(dir); - return countStream; - } - - /** - * Generate an HMAC, as specified in [RFC2104], of the encrypted form of the data (message), - * which the DataIntegrity element will verify by using the Salt generated in step 2 as the key. - * Note that the entire EncryptedPackage stream (1), including the StreamSize field, MUST be - * used as the message. - * - * Encrypt the HMAC as in step 3 by using a blockKey byte array consisting of the following bytes: - * 0xa0, 0x67, 0x7f, 0x02, 0xb2, 0x2c, 0x84, and 0x33. - **/ - protected void updateIntegrityHMAC(File tmpFile, int oleStreamSize) throws GeneralSecurityException, IOException { - // as the integrity hmac needs to contain the StreamSize, - // it's not possible to calculate it on-the-fly while buffering - // TODO: add stream size parameter to getDataStream() - AgileEncryptionHeader header = (AgileEncryptionHeader)getEncryptionInfo().getHeader(); - int blockSize = header.getBlockSize(); - HashAlgorithm hashAlgo = header.getHashAlgorithm(); - Mac integrityMD = CryptoFunctions.getMac(hashAlgo); - byte hmacKey[] = getBlock0(this.integritySalt, getNextBlockSize(this.integritySalt.length, blockSize)); - integrityMD.init(new SecretKeySpec(hmacKey, hashAlgo.jceHmacId)); - - byte buf[] = new byte[1024]; - LittleEndian.putLong(buf, 0, oleStreamSize); - integrityMD.update(buf, 0, LittleEndianConsts.LONG_SIZE); - - InputStream fis = new FileInputStream(tmpFile); - try { - int readBytes; - while ((readBytes = fis.read(buf)) != -1) { - integrityMD.update(buf, 0, readBytes); - } - } finally { - fis.close(); - } - - byte hmacValue[] = integrityMD.doFinal(); - byte hmacValueFilled[] = getBlock0(hmacValue, getNextBlockSize(hmacValue.length, blockSize)); - - byte iv[] = CryptoFunctions.generateIv(header.getHashAlgorithm(), header.getKeySalt(), kIntegrityValueBlock, blockSize); - Cipher cipher = CryptoFunctions.getCipher(getSecretKey(), header.getCipherAlgorithm(), header.getChainingMode(), iv, Cipher.ENCRYPT_MODE); - byte encryptedHmacValue[] = cipher.doFinal(hmacValueFilled); - - header.setEncryptedHmacValue(encryptedHmacValue); - } - - private final CTKeyEncryptor.Uri.Enum passwordUri = - CTKeyEncryptor.Uri.HTTP_SCHEMAS_MICROSOFT_COM_OFFICE_2006_KEY_ENCRYPTOR_PASSWORD; - private final CTKeyEncryptor.Uri.Enum certificateUri = - CTKeyEncryptor.Uri.HTTP_SCHEMAS_MICROSOFT_COM_OFFICE_2006_KEY_ENCRYPTOR_CERTIFICATE; - - protected EncryptionDocument createEncryptionDocument() { - AgileEncryptionVerifier ver = (AgileEncryptionVerifier)getEncryptionInfo().getVerifier(); - AgileEncryptionHeader header = (AgileEncryptionHeader)getEncryptionInfo().getHeader(); - - EncryptionDocument ed = EncryptionDocument.Factory.newInstance(); - CTEncryption edRoot = ed.addNewEncryption(); - - CTKeyData keyData = edRoot.addNewKeyData(); - CTKeyEncryptors keyEncList = edRoot.addNewKeyEncryptors(); - CTKeyEncryptor keyEnc = keyEncList.addNewKeyEncryptor(); - keyEnc.setUri(passwordUri); - CTPasswordKeyEncryptor keyPass = keyEnc.addNewEncryptedPasswordKey(); - - keyPass.setSpinCount(ver.getSpinCount()); - - keyData.setSaltSize(header.getBlockSize()); - keyPass.setSaltSize(ver.getBlockSize()); - - keyData.setBlockSize(header.getBlockSize()); - keyPass.setBlockSize(ver.getBlockSize()); - - keyData.setKeyBits(header.getKeySize()); - keyPass.setKeyBits(ver.getKeySize()); - - keyData.setHashSize(header.getHashAlgorithm().hashSize); - keyPass.setHashSize(ver.getHashAlgorithm().hashSize); - - // header and verifier have to have the same cipher algorithm - if (!header.getCipherAlgorithm().xmlId.equals(ver.getCipherAlgorithm().xmlId)) { - throw new EncryptedDocumentException("Cipher algorithm of header and verifier have to match"); - } - STCipherAlgorithm.Enum xmlCipherAlgo = STCipherAlgorithm.Enum.forString(header.getCipherAlgorithm().xmlId); - if (xmlCipherAlgo == null) { - throw new EncryptedDocumentException("CipherAlgorithm "+header.getCipherAlgorithm()+" not supported."); - } - keyData.setCipherAlgorithm(xmlCipherAlgo); - keyPass.setCipherAlgorithm(xmlCipherAlgo); - - switch (header.getChainingMode()) { - case cbc: - keyData.setCipherChaining(STCipherChaining.CHAINING_MODE_CBC); - keyPass.setCipherChaining(STCipherChaining.CHAINING_MODE_CBC); - break; - case cfb: - keyData.setCipherChaining(STCipherChaining.CHAINING_MODE_CFB); - keyPass.setCipherChaining(STCipherChaining.CHAINING_MODE_CFB); - break; - default: - throw new EncryptedDocumentException("ChainingMode "+header.getChainingMode()+" not supported."); - } - - keyData.setHashAlgorithm(mapHashAlgorithm(header.getHashAlgorithm())); - keyPass.setHashAlgorithm(mapHashAlgorithm(ver.getHashAlgorithm())); - - keyData.setSaltValue(header.getKeySalt()); - keyPass.setSaltValue(ver.getSalt()); - keyPass.setEncryptedVerifierHashInput(ver.getEncryptedVerifier()); - keyPass.setEncryptedVerifierHashValue(ver.getEncryptedVerifierHash()); - keyPass.setEncryptedKeyValue(ver.getEncryptedKey()); - - CTDataIntegrity hmacData = edRoot.addNewDataIntegrity(); - hmacData.setEncryptedHmacKey(header.getEncryptedHmacKey()); - hmacData.setEncryptedHmacValue(header.getEncryptedHmacValue()); - - for (AgileCertificateEntry ace : ver.getCertificates()) { - keyEnc = keyEncList.addNewKeyEncryptor(); - keyEnc.setUri(certificateUri); - CTCertificateKeyEncryptor certData = keyEnc.addNewEncryptedCertificateKey(); - try { - certData.setX509Certificate(ace.x509.getEncoded()); - } catch (CertificateEncodingException e) { - throw new EncryptedDocumentException(e); - } - certData.setEncryptedKeyValue(ace.encryptedKey); - certData.setCertVerifier(ace.certVerifier); - } - - return ed; - } - - private static STHashAlgorithm.Enum mapHashAlgorithm(HashAlgorithm hashAlgo) { - STHashAlgorithm.Enum xmlHashAlgo = STHashAlgorithm.Enum.forString(hashAlgo.ecmaString); - if (xmlHashAlgo == null) { - throw new EncryptedDocumentException("HashAlgorithm "+hashAlgo+" not supported."); - } - return xmlHashAlgo; - } - - protected void marshallEncryptionDocument(EncryptionDocument ed, LittleEndianByteArrayOutputStream os) { - XmlOptions xo = new XmlOptions(); - xo.setCharacterEncoding("UTF-8"); - Map nsMap = new HashMap(); - nsMap.put(passwordUri.toString(),"p"); - nsMap.put(certificateUri.toString(), "c"); - xo.setUseDefaultNamespace(); - xo.setSaveSuggestedPrefixes(nsMap); - xo.setSaveNamespacesFirst(); - xo.setSaveAggressiveNamespaces(); - - // setting standalone doesn't work with xmlbeans-2.3 & 2.6 - // ed.documentProperties().setStandalone(true); - xo.setSaveNoXmlDecl(); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - try { - bos.write("\r\n".getBytes("UTF-8")); - ed.save(bos, xo); - bos.writeTo(os); - } catch (IOException e) { - throw new EncryptedDocumentException("error marshalling encryption info document", e); - } - } - - protected void createEncryptionInfoEntry(DirectoryNode dir, File tmpFile) - throws IOException, GeneralSecurityException { - DataSpaceMapUtils.addDefaultDataSpace(dir); - - final EncryptionInfo info = getEncryptionInfo(); - - EncryptionRecord er = new EncryptionRecord(){ - @Override - public void write(LittleEndianByteArrayOutputStream bos) { - // EncryptionVersionInfo (4 bytes): A Version structure (section 2.1.4), where - // Version.vMajor MUST be 0x0004 and Version.vMinor MUST be 0x0004 - bos.writeShort(info.getVersionMajor()); - bos.writeShort(info.getVersionMinor()); - // Reserved (4 bytes): A value that MUST be 0x00000040 - bos.writeInt(info.getEncryptionFlags()); - - EncryptionDocument ed = createEncryptionDocument(); - marshallEncryptionDocument(ed, bos); - } - }; - - createEncryptionEntry(dir, "EncryptionInfo", er); - } - - - /** - * 2.3.4.15 Data Encryption (Agile Encryption) - * - * The EncryptedPackage stream (1) MUST be encrypted in 4096-byte segments to facilitate nearly - * random access while allowing CBC modes to be used in the encryption process. - * The initialization vector for the encryption process MUST be obtained by using the zero-based - * segment number as a blockKey and the binary form of the KeyData.saltValue as specified in - * section 2.3.4.12. The block number MUST be represented as a 32-bit unsigned integer. - * Data blocks MUST then be encrypted by using the initialization vector and the intermediate key - * obtained by decrypting the encryptedKeyValue from a KeyEncryptor contained within the - * KeyEncryptors sequence as specified in section 2.3.4.10. The final data block MUST be padded to - * the next integral multiple of the KeyData.blockSize value. Any padding bytes can be used. Note - * that the StreamSize field of the EncryptedPackage field specifies the number of bytes of - * unencrypted data as specified in section 2.3.4.4. - */ - private class AgileCipherOutputStream extends ChunkedCipherOutputStream { - public AgileCipherOutputStream(DirectoryNode dir) throws IOException, GeneralSecurityException { - super(dir, 4096); - } - - @Override - protected Cipher initCipherForBlock(Cipher existing, int block, boolean lastChunk) - throws GeneralSecurityException { - return AgileDecryptor.initCipherForBlock(existing, block, lastChunk, getEncryptionInfo(), getSecretKey(), Cipher.ENCRYPT_MODE); - } - - @Override - protected void calculateChecksum(File fileOut, int oleStreamSize) - throws GeneralSecurityException, IOException { - // integrityHMAC needs to be updated before the encryption document is created - updateIntegrityHMAC(fileOut, oleStreamSize); - } - - @Override - protected void createEncryptionInfoEntry(DirectoryNode dir, File tmpFile) - throws IOException, GeneralSecurityException { - AgileEncryptor.this.createEncryptionInfoEntry(dir, tmpFile); - } - } - - @Override - public AgileEncryptor clone() throws CloneNotSupportedException { - AgileEncryptor other = (AgileEncryptor)super.clone(); - other.integritySalt = (integritySalt == null) ? null : integritySalt.clone(); - other.pwHash = (pwHash == null) ? null : pwHash.clone(); - return other; - } -} diff --git a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/CertificateSecurityException.java b/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/CertificateSecurityException.java deleted file mode 100644 index fab659277..000000000 --- a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/CertificateSecurityException.java +++ /dev/null @@ -1,38 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -/* ==================================================================== - This product contains an ASLv2 licensed version of the OOXML signer - package from the eID Applet project - http://code.google.com/p/eid-applet/source/browse/trunk/README.txt - Copyright (C) 2008-2014 FedICT. - ================================================================= */ - -package org.apache.poi.poifs.crypt.dsig; - -/** - * Exception thrown in case there is something wrong with the incoming eID - * certificate. - * - * @author Frank Cornelis - * - */ -public class CertificateSecurityException extends SecurityException { - - private static final long serialVersionUID = 1L; - -} diff --git a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/DigestInfo.java b/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/DigestInfo.java deleted file mode 100644 index 3771053a0..000000000 --- a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/DigestInfo.java +++ /dev/null @@ -1,56 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -/* ==================================================================== - This product contains an ASLv2 licensed version of the OOXML signer - package from the eID Applet project - http://code.google.com/p/eid-applet/source/browse/trunk/README.txt - Copyright (C) 2008-2014 FedICT. - ================================================================= */ - -package org.apache.poi.poifs.crypt.dsig; - -import java.io.Serializable; - -import org.apache.poi.poifs.crypt.HashAlgorithm; - -/** - * Digest Information data transfer class. - */ -public class DigestInfo implements Serializable { - - private static final long serialVersionUID = 1L; - - /** - * Main constructor. - * - * @param digestValue - * @param hashAlgo - * @param description - */ - public DigestInfo(byte[] digestValue, HashAlgorithm hashAlgo, String description) { - this.digestValue = digestValue.clone(); - this.hashAlgo = hashAlgo; - this.description = description; - } - - public final byte[] digestValue; - - public final String description; - - public final HashAlgorithm hashAlgo; -} diff --git a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/ExpiredCertificateSecurityException.java b/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/ExpiredCertificateSecurityException.java deleted file mode 100644 index fddede242..000000000 --- a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/ExpiredCertificateSecurityException.java +++ /dev/null @@ -1,38 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -/* ==================================================================== - This product contains an ASLv2 licensed version of the OOXML signer - package from the eID Applet project - http://code.google.com/p/eid-applet/source/browse/trunk/README.txt - Copyright (C) 2008-2014 FedICT. - ================================================================= */ - -package org.apache.poi.poifs.crypt.dsig; - -/** - * Exception thrown in case the incoming eID certificate is expired. - * - * @author Frank Cornelis - * - */ -public class ExpiredCertificateSecurityException extends - CertificateSecurityException { - - private static final long serialVersionUID = 1L; - -} diff --git a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/KeyInfoKeySelector.java b/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/KeyInfoKeySelector.java deleted file mode 100644 index f4402dcc8..000000000 --- a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/KeyInfoKeySelector.java +++ /dev/null @@ -1,103 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -/* ==================================================================== - This product contains an ASLv2 licensed version of the OOXML signer - package from the eID Applet project - http://code.google.com/p/eid-applet/source/browse/trunk/README.txt - Copyright (C) 2008-2014 FedICT. - ================================================================= */ - -package org.apache.poi.poifs.crypt.dsig; - -import java.security.Key; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.List; - -import javax.xml.crypto.AlgorithmMethod; -import javax.xml.crypto.KeySelector; -import javax.xml.crypto.KeySelectorException; -import javax.xml.crypto.KeySelectorResult; -import javax.xml.crypto.XMLCryptoContext; -import javax.xml.crypto.XMLStructure; -import javax.xml.crypto.dsig.keyinfo.KeyInfo; -import javax.xml.crypto.dsig.keyinfo.X509Data; - -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; - -/** - * JSR105 key selector implementation using the ds:KeyInfo data of the signature - * itself. - */ -public class KeyInfoKeySelector extends KeySelector implements KeySelectorResult { - - private static final POILogger LOG = POILogFactory.getLogger(KeyInfoKeySelector.class); - - private List certChain = new ArrayList(); - - @SuppressWarnings("unchecked") - @Override - public KeySelectorResult select(KeyInfo keyInfo, Purpose purpose, AlgorithmMethod method, XMLCryptoContext context) throws KeySelectorException { - LOG.log(POILogger.DEBUG, "select key"); - if (null == keyInfo) { - throw new KeySelectorException("no ds:KeyInfo present"); - } - List keyInfoContent = keyInfo.getContent(); - certChain.clear(); - for (XMLStructure keyInfoStructure : keyInfoContent) { - if (!(keyInfoStructure instanceof X509Data)) { - continue; - } - X509Data x509Data = (X509Data) keyInfoStructure; - List x509DataList = x509Data.getContent(); - for (Object x509DataObject : x509DataList) { - if (!(x509DataObject instanceof X509Certificate)) { - continue; - } - X509Certificate certificate = (X509Certificate) x509DataObject; - LOG.log(POILogger.DEBUG, "certificate", certificate.getSubjectX500Principal()); - certChain.add(certificate); - } - } - if (certChain.isEmpty()) { - throw new KeySelectorException("No key found!"); - } - return this; - } - - public Key getKey() { - // The first certificate is presumably the signer. - return certChain.isEmpty() ? null : certChain.get(0).getPublicKey(); - } - - /** - * Gives back the X509 certificate used during the last signature - * verification operation. - * - * @return the certificate which was used to sign the xml content - */ - public X509Certificate getSigner() { - // The first certificate is presumably the signer. - return certChain.isEmpty() ? null : certChain.get(0); - } - - public List getCertChain() { - return certChain; - } -} diff --git a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/OOXMLURIDereferencer.java b/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/OOXMLURIDereferencer.java deleted file mode 100644 index 07711d2b8..000000000 --- a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/OOXMLURIDereferencer.java +++ /dev/null @@ -1,130 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -/* ==================================================================== - This product contains an ASLv2 licensed version of the OOXML signer - package from the eID Applet project - http://code.google.com/p/eid-applet/source/browse/trunk/README.txt - Copyright (C) 2008-2014 FedICT. - ================================================================= */ - -package org.apache.poi.poifs.crypt.dsig; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.URI; -import java.net.URISyntaxException; - -import javax.xml.crypto.Data; -import javax.xml.crypto.OctetStreamData; -import javax.xml.crypto.URIDereferencer; -import javax.xml.crypto.URIReference; -import javax.xml.crypto.URIReferenceException; -import javax.xml.crypto.XMLCryptoContext; - -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.opc.PackagePartName; -import org.apache.poi.openxml4j.opc.PackagingURIHelper; -import org.apache.poi.poifs.crypt.dsig.SignatureConfig.SignatureConfigurable; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; - -/** - * JSR105 URI dereferencer for Office Open XML documents. - */ -public class OOXMLURIDereferencer implements URIDereferencer, SignatureConfigurable { - - private static final POILogger LOG = POILogFactory.getLogger(OOXMLURIDereferencer.class); - - private SignatureConfig signatureConfig; - private URIDereferencer baseUriDereferencer; - - public void setSignatureConfig(SignatureConfig signatureConfig) { - this.signatureConfig = signatureConfig; - } - - public Data dereference(URIReference uriReference, XMLCryptoContext context) throws URIReferenceException { - if (baseUriDereferencer == null) { - baseUriDereferencer = signatureConfig.getSignatureFactory().getURIDereferencer(); - } - - if (null == uriReference) { - throw new NullPointerException("URIReference cannot be null"); - } - if (null == context) { - throw new NullPointerException("XMLCrytoContext cannot be null"); - } - - URI uri; - try { - uri = new URI(uriReference.getURI()); - } catch (URISyntaxException e) { - throw new URIReferenceException("could not URL decode the uri: "+uriReference.getURI(), e); - } - - PackagePart part = findPart(uri); - if (part == null) { - LOG.log(POILogger.DEBUG, "cannot resolve, delegating to base DOM URI dereferencer", uri); - return this.baseUriDereferencer.dereference(uriReference, context); - } - - InputStream dataStream; - try { - dataStream = part.getInputStream(); - - // workaround for office 2007 pretty-printed .rels files - if (part.getPartName().toString().endsWith(".rels")) { - // although xmlsec has an option to ignore line breaks, currently this - // only affects .rels files, so we only modify these - // http://stackoverflow.com/questions/4728300 - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - for (int ch; (ch = dataStream.read()) != -1; ) { - if (ch == 10 || ch == 13) continue; - bos.write(ch); - } - dataStream = new ByteArrayInputStream(bos.toByteArray()); - } - } catch (IOException e) { - throw new URIReferenceException("I/O error: " + e.getMessage(), e); - } - - return new OctetStreamData(dataStream, uri.toString(), null); - } - - private PackagePart findPart(URI uri) { - LOG.log(POILogger.DEBUG, "dereference", uri); - - String path = uri.getPath(); - if (path == null || "".equals(path)) { - LOG.log(POILogger.DEBUG, "illegal part name (expected)", uri); - return null; - } - - PackagePartName ppn; - try { - ppn = PackagingURIHelper.createPartName(path); - } catch (InvalidFormatException e) { - LOG.log(POILogger.WARN, "illegal part name (not expected)", uri); - return null; - } - - return signatureConfig.getOpcPackage().getPart(ppn); - } -} diff --git a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/RevokedCertificateSecurityException.java b/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/RevokedCertificateSecurityException.java deleted file mode 100644 index 58b64dce4..000000000 --- a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/RevokedCertificateSecurityException.java +++ /dev/null @@ -1,38 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -/* ==================================================================== - This product contains an ASLv2 licensed version of the OOXML signer - package from the eID Applet project - http://code.google.com/p/eid-applet/source/browse/trunk/README.txt - Copyright (C) 2008-2014 FedICT. - ================================================================= */ - -package org.apache.poi.poifs.crypt.dsig; - -/** - * Exception thrown in case the incoming eID certificate has been revoked. - * - * @author Frank Cornelis - * - */ -public class RevokedCertificateSecurityException extends - CertificateSecurityException { - - private static final long serialVersionUID = 1L; - -} diff --git a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/SignatureConfig.java b/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/SignatureConfig.java deleted file mode 100644 index fa87be191..000000000 --- a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/SignatureConfig.java +++ /dev/null @@ -1,897 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.crypt.dsig; - -import static org.apache.poi.poifs.crypt.dsig.facets.SignatureFacet.OO_DIGSIG_NS; -import static org.apache.poi.poifs.crypt.dsig.facets.SignatureFacet.XADES_132_NS; - -import java.security.PrivateKey; -import java.security.Provider; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -import javax.xml.crypto.URIDereferencer; -import javax.xml.crypto.dsig.CanonicalizationMethod; -import javax.xml.crypto.dsig.DigestMethod; -import javax.xml.crypto.dsig.XMLSignatureFactory; -import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory; - -import org.apache.poi.EncryptedDocumentException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.poifs.crypt.HashAlgorithm; -import org.apache.poi.poifs.crypt.dsig.facets.KeyInfoSignatureFacet; -import org.apache.poi.poifs.crypt.dsig.facets.OOXMLSignatureFacet; -import org.apache.poi.poifs.crypt.dsig.facets.Office2010SignatureFacet; -import org.apache.poi.poifs.crypt.dsig.facets.SignatureFacet; -import org.apache.poi.poifs.crypt.dsig.facets.XAdESSignatureFacet; -import org.apache.poi.poifs.crypt.dsig.services.RevocationDataService; -import org.apache.poi.poifs.crypt.dsig.services.SignaturePolicyService; -import org.apache.poi.poifs.crypt.dsig.services.TSPTimeStampService; -import org.apache.poi.poifs.crypt.dsig.services.TimeStampService; -import org.apache.poi.poifs.crypt.dsig.services.TimeStampServiceValidator; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.xml.security.signature.XMLSignature; -import org.w3c.dom.events.EventListener; - -/** - * This class bundles the configuration options used for the existing - * signature facets. - * Apart of the thread local members (e.g. opc-package) most values will probably be constant, so - * it might be configured centrally (e.g. by spring) - */ -public class SignatureConfig { - - private static final POILogger LOG = POILogFactory.getLogger(SignatureConfig.class); - - public interface SignatureConfigurable { - void setSignatureConfig(SignatureConfig signatureConfig); - } - - private ThreadLocal opcPackage = new ThreadLocal(); - private ThreadLocal signatureFactory = new ThreadLocal(); - private ThreadLocal keyInfoFactory = new ThreadLocal(); - private ThreadLocal provider = new ThreadLocal(); - - private List signatureFacets = new ArrayList(); - private HashAlgorithm digestAlgo = HashAlgorithm.sha1; - private Date executionTime = new Date(); - private PrivateKey key; - private List signingCertificateChain; - - /** - * the optional signature policy service used for XAdES-EPES. - */ - private SignaturePolicyService signaturePolicyService; - private URIDereferencer uriDereferencer = null; - private String canonicalizationMethod = CanonicalizationMethod.INCLUSIVE; - - private boolean includeEntireCertificateChain = true; - private boolean includeIssuerSerial = false; - private boolean includeKeyValue = false; - - /** - * the time-stamp service used for XAdES-T and XAdES-X. - */ - private TimeStampService tspService = new TSPTimeStampService(); - /** - * timestamp service provider URL - */ - private String tspUrl; - private boolean tspOldProtocol = false; - /** - * if not defined, it's the same as the main digest - */ - private HashAlgorithm tspDigestAlgo = null; - private String tspUser; - private String tspPass; - private TimeStampServiceValidator tspValidator; - /** - * the optional TSP request policy OID. - */ - private String tspRequestPolicy = "1.3.6.1.4.1.13762.3"; - private String userAgent = "POI XmlSign Service TSP Client"; - private String proxyUrl; - - /** - * the optional revocation data service used for XAdES-C and XAdES-X-L. - * When null the signature will be limited to XAdES-T only. - */ - private RevocationDataService revocationDataService; - /** - * if not defined, it's the same as the main digest - */ - private HashAlgorithm xadesDigestAlgo = null; - private String xadesRole = null; - private String xadesSignatureId = "idSignedProperties"; - private boolean xadesSignaturePolicyImplied = true; - private String xadesCanonicalizationMethod = CanonicalizationMethod.EXCLUSIVE; - - /** - * Work-around for Office 2010 IssuerName encoding. - */ - private boolean xadesIssuerNameNoReverseOrder = true; - - /** - * The signature Id attribute value used to create the XML signature. A - * null value will trigger an automatically generated signature Id. - */ - private String packageSignatureId = "idPackageSignature"; - - /** - * Gives back the human-readable description of what the citizen will be - * signing. The default value is "Office OpenXML Document". - */ - private String signatureDescription = "Office OpenXML Document"; - - /** - * The process of signing includes the marshalling of xml structures. - * This also includes the canonicalization. Currently this leads to problems - * with certain namespaces, so this EventListener is used to interfere - * with the marshalling process. - */ - EventListener signatureMarshalListener = null; - - /** - * Map of namespace uris to prefix - * If a mapping is specified, the corresponding elements will be prefixed - */ - Map namespacePrefixes = new HashMap(); - - /** - * Inits and checks the config object. - * If not set previously, complex configuration properties also get - * created/initialized via this initialization call. - * - * @param onlyValidation if true, only a subset of the properties - * is initialized, which are necessary for validation. If false, - * also the other properties needed for signing are been taken care of - */ - protected void init(boolean onlyValidation) { - if (opcPackage == null) { - throw new EncryptedDocumentException("opcPackage is null"); - } - if (uriDereferencer == null) { - uriDereferencer = new OOXMLURIDereferencer(); - } - if (uriDereferencer instanceof SignatureConfigurable) { - ((SignatureConfigurable)uriDereferencer).setSignatureConfig(this); - } - if (namespacePrefixes.isEmpty()) { - /* - * OOo doesn't like ds namespaces so per default prefixing is off. - */ - // namespacePrefixes.put(XML_DIGSIG_NS, ""); - namespacePrefixes.put(OO_DIGSIG_NS, "mdssi"); - namespacePrefixes.put(XADES_132_NS, "xd"); - } - - if (onlyValidation) return; - - if (signatureMarshalListener == null) { - signatureMarshalListener = new SignatureMarshalListener(); - } - - if (signatureMarshalListener instanceof SignatureConfigurable) { - ((SignatureConfigurable)signatureMarshalListener).setSignatureConfig(this); - } - - if (tspService != null) { - tspService.setSignatureConfig(this); - } - - if (signatureFacets.isEmpty()) { - addSignatureFacet(new OOXMLSignatureFacet()); - addSignatureFacet(new KeyInfoSignatureFacet()); - addSignatureFacet(new XAdESSignatureFacet()); - addSignatureFacet(new Office2010SignatureFacet()); - } - - for (SignatureFacet sf : signatureFacets) { - sf.setSignatureConfig(this); - } - } - - /** - * @param signatureFacet the signature facet is appended to facet list - */ - public void addSignatureFacet(SignatureFacet signatureFacet) { - signatureFacets.add(signatureFacet); - } - - /** - * @return the list of facets, may be empty when the config object is not initialized - */ - public List getSignatureFacets() { - return signatureFacets; - } - - /** - * @param signatureFacets the new list of facets - */ - public void setSignatureFacets(List signatureFacets) { - this.signatureFacets = signatureFacets; - } - - /** - * @return the main digest algorithm, defaults to sha-1 - */ - public HashAlgorithm getDigestAlgo() { - return digestAlgo; - } - - /** - * @param digestAlgo the main digest algorithm - */ - public void setDigestAlgo(HashAlgorithm digestAlgo) { - this.digestAlgo = digestAlgo; - } - - /** - * @return the opc package to be used by this thread, stored as thread-local - */ - public OPCPackage getOpcPackage() { - return opcPackage.get(); - } - - /** - * @param opcPackage the opc package to be handled by this thread, stored as thread-local - */ - public void setOpcPackage(OPCPackage opcPackage) { - this.opcPackage.set(opcPackage); - } - - /** - * @return the private key - */ - public PrivateKey getKey() { - return key; - } - - /** - * @param key the private key - */ - public void setKey(PrivateKey key) { - this.key = key; - } - - /** - * @return the certificate chain, index 0 is usually the certificate matching - * the private key - */ - public List getSigningCertificateChain() { - return signingCertificateChain; - } - - /** - * @param signingCertificateChain the certificate chain, index 0 should be - * the certificate matching the private key - */ - public void setSigningCertificateChain( - List signingCertificateChain) { - this.signingCertificateChain = signingCertificateChain; - } - - /** - * @return the time at which the document is signed, also used for the timestamp service. - * defaults to now - */ - public Date getExecutionTime() { - return executionTime; - } - - /** - * @param executionTime sets the time at which the document ought to be signed - */ - public void setExecutionTime(Date executionTime) { - this.executionTime = executionTime; - } - - /** - * @return the service to be used for XAdES-EPES properties. There's no default implementation - */ - public SignaturePolicyService getSignaturePolicyService() { - return signaturePolicyService; - } - - /** - * @param signaturePolicyService the service to be used for XAdES-EPES properties - */ - public void setSignaturePolicyService(SignaturePolicyService signaturePolicyService) { - this.signaturePolicyService = signaturePolicyService; - } - - /** - * @return the dereferencer used for Reference/@URI attributes, defaults to {@link OOXMLURIDereferencer} - */ - public URIDereferencer getUriDereferencer() { - return uriDereferencer; - } - - /** - * @param uriDereferencer the dereferencer used for Reference/@URI attributes - */ - public void setUriDereferencer(URIDereferencer uriDereferencer) { - this.uriDereferencer = uriDereferencer; - } - - /** - * @return Gives back the human-readable description of what the citizen - * will be signing. The default value is "Office OpenXML Document". - */ - public String getSignatureDescription() { - return signatureDescription; - } - - /** - * @param signatureDescription the human-readable description of - * what the citizen will be signing. - */ - public void setSignatureDescription(String signatureDescription) { - this.signatureDescription = signatureDescription; - } - - /** - * @return the default canonicalization method, defaults to INCLUSIVE - */ - public String getCanonicalizationMethod() { - return canonicalizationMethod; - } - - /** - * @param canonicalizationMethod the default canonicalization method - */ - public void setCanonicalizationMethod(String canonicalizationMethod) { - this.canonicalizationMethod = canonicalizationMethod; - } - - /** - * @return The signature Id attribute value used to create the XML signature. - * Defaults to "idPackageSignature" - */ - public String getPackageSignatureId() { - return packageSignatureId; - } - - /** - * @param packageSignatureId The signature Id attribute value used to create the XML signature. - * A null value will trigger an automatically generated signature Id. - */ - public void setPackageSignatureId(String packageSignatureId) { - this.packageSignatureId = nvl(packageSignatureId,"xmldsig-"+UUID.randomUUID()); - } - - /** - * @return the url of the timestamp provider (TSP) - */ - public String getTspUrl() { - return tspUrl; - } - - /** - * @param tspUrl the url of the timestamp provider (TSP) - */ - public void setTspUrl(String tspUrl) { - this.tspUrl = tspUrl; - } - - /** - * @return if true, uses timestamp-request/response mimetype, - * if false, timestamp-query/reply mimetype - */ - public boolean isTspOldProtocol() { - return tspOldProtocol; - } - - /** - * @param tspOldProtocol defines the timestamp-protocol mimetype - * @see #isTspOldProtocol - */ - public void setTspOldProtocol(boolean tspOldProtocol) { - this.tspOldProtocol = tspOldProtocol; - } - - /** - * @return the hash algorithm to be used for the timestamp entry. - * Defaults to the hash algorithm of the main entry - */ - public HashAlgorithm getTspDigestAlgo() { - return nvl(tspDigestAlgo,digestAlgo); - } - - /** - * @param tspDigestAlgo the algorithm to be used for the timestamp entry. - * if null, the hash algorithm of the main entry - */ - public void setTspDigestAlgo(HashAlgorithm tspDigestAlgo) { - this.tspDigestAlgo = tspDigestAlgo; - } - - /** - * @return the proxy url to be used for all communications. - * Currently this affects the timestamp service - */ - public String getProxyUrl() { - return proxyUrl; - } - - /** - * @param proxyUrl the proxy url to be used for all communications. - * Currently this affects the timestamp service - */ - public void setProxyUrl(String proxyUrl) { - this.proxyUrl = proxyUrl; - } - - /** - * @return the timestamp service. Defaults to {@link TSPTimeStampService} - */ - public TimeStampService getTspService() { - return tspService; - } - - /** - * @param tspService the timestamp service - */ - public void setTspService(TimeStampService tspService) { - this.tspService = tspService; - } - - /** - * @return the user id for the timestamp service - currently only basic authorization is supported - */ - public String getTspUser() { - return tspUser; - } - - /** - * @param tspUser the user id for the timestamp service - currently only basic authorization is supported - */ - public void setTspUser(String tspUser) { - this.tspUser = tspUser; - } - - /** - * @return the password for the timestamp service - */ - public String getTspPass() { - return tspPass; - } - - /** - * @param tspPass the password for the timestamp service - */ - public void setTspPass(String tspPass) { - this.tspPass = tspPass; - } - - /** - * @return the validator for the timestamp service (certificate) - */ - public TimeStampServiceValidator getTspValidator() { - return tspValidator; - } - - /** - * @param tspValidator the validator for the timestamp service (certificate) - */ - public void setTspValidator(TimeStampServiceValidator tspValidator) { - this.tspValidator = tspValidator; - } - - /** - * @return the optional revocation data service used for XAdES-C and XAdES-X-L. - * When null the signature will be limited to XAdES-T only. - */ - public RevocationDataService getRevocationDataService() { - return revocationDataService; - } - - /** - * @param revocationDataService the optional revocation data service used for XAdES-C and XAdES-X-L. - * When null the signature will be limited to XAdES-T only. - */ - public void setRevocationDataService(RevocationDataService revocationDataService) { - this.revocationDataService = revocationDataService; - } - - /** - * @return hash algorithm used for XAdES. Defaults to the {@link #getDigestAlgo()} - */ - public HashAlgorithm getXadesDigestAlgo() { - return nvl(xadesDigestAlgo,digestAlgo); - } - - /** - * @param xadesDigestAlgo hash algorithm used for XAdES. - * When null, defaults to {@link #getDigestAlgo()} - */ - public void setXadesDigestAlgo(HashAlgorithm xadesDigestAlgo) { - this.xadesDigestAlgo = xadesDigestAlgo; - } - - /** - * @return the user agent used for http communication (e.g. to the TSP) - */ - public String getUserAgent() { - return userAgent; - } - - /** - * @param userAgent the user agent used for http communication (e.g. to the TSP) - */ - public void setUserAgent(String userAgent) { - this.userAgent = userAgent; - } - - /** - * @return the asn.1 object id for the tsp request policy. - * Defaults to 1.3.6.1.4.1.13762.3 - */ - public String getTspRequestPolicy() { - return tspRequestPolicy; - } - - /** - * @param tspRequestPolicy the asn.1 object id for the tsp request policy. - */ - public void setTspRequestPolicy(String tspRequestPolicy) { - this.tspRequestPolicy = tspRequestPolicy; - } - - /** - * @return true, if the whole certificate chain is included in the signature. - * When false, only the signer cert will be included - */ - public boolean isIncludeEntireCertificateChain() { - return includeEntireCertificateChain; - } - - /** - * @param includeEntireCertificateChain if true, include the whole certificate chain. - * If false, only include the signer cert - */ - public void setIncludeEntireCertificateChain(boolean includeEntireCertificateChain) { - this.includeEntireCertificateChain = includeEntireCertificateChain; - } - - /** - * @return if true, issuer serial number is included - */ - public boolean isIncludeIssuerSerial() { - return includeIssuerSerial; - } - - /** - * @param includeIssuerSerial if true, issuer serial number is included - */ - public void setIncludeIssuerSerial(boolean includeIssuerSerial) { - this.includeIssuerSerial = includeIssuerSerial; - } - - /** - * @return if true, the key value of the public key (certificate) is included - */ - public boolean isIncludeKeyValue() { - return includeKeyValue; - } - - /** - * @param includeKeyValue if true, the key value of the public key (certificate) is included - */ - public void setIncludeKeyValue(boolean includeKeyValue) { - this.includeKeyValue = includeKeyValue; - } - - /** - * @return the xades role element. If null the claimed role element is omitted. - * Defaults to null - */ - public String getXadesRole() { - return xadesRole; - } - - /** - * @param xadesRole the xades role element. If null the claimed role element is omitted. - */ - public void setXadesRole(String xadesRole) { - this.xadesRole = xadesRole; - } - - /** - * @return the Id for the XAdES SignedProperties element. - * Defaults to idSignedProperties - */ - public String getXadesSignatureId() { - return nvl(xadesSignatureId, "idSignedProperties"); - } - - /** - * @param xadesSignatureId the Id for the XAdES SignedProperties element. - * When null defaults to idSignedProperties - */ - public void setXadesSignatureId(String xadesSignatureId) { - this.xadesSignatureId = xadesSignatureId; - } - - /** - * @return when true, include the policy-implied block. - * Defaults to true - */ - public boolean isXadesSignaturePolicyImplied() { - return xadesSignaturePolicyImplied; - } - - /** - * @param xadesSignaturePolicyImplied when true, include the policy-implied block - */ - public void setXadesSignaturePolicyImplied(boolean xadesSignaturePolicyImplied) { - this.xadesSignaturePolicyImplied = xadesSignaturePolicyImplied; - } - - /** - * Make sure the DN is encoded using the same order as present - * within the certificate. This is an Office2010 work-around. - * Should be reverted back. - * - * XXX: not correct according to RFC 4514. - * - * @return when true, the issuer DN is used instead of the issuer X500 principal - */ - public boolean isXadesIssuerNameNoReverseOrder() { - return xadesIssuerNameNoReverseOrder; - } - - /** - * @param xadesIssuerNameNoReverseOrder when true, the issuer DN instead of the issuer X500 prinicpal is used - */ - public void setXadesIssuerNameNoReverseOrder(boolean xadesIssuerNameNoReverseOrder) { - this.xadesIssuerNameNoReverseOrder = xadesIssuerNameNoReverseOrder; - } - - - /** - * @return the event listener which is active while xml structure for - * the signature is created. - * Defaults to {@link SignatureMarshalListener} - */ - public EventListener getSignatureMarshalListener() { - return signatureMarshalListener; - } - - /** - * @param signatureMarshalListener the event listener watching the xml structure - * generation for the signature - */ - public void setSignatureMarshalListener(EventListener signatureMarshalListener) { - this.signatureMarshalListener = signatureMarshalListener; - } - - /** - * @return the map of namespace uri (key) to prefix (value) - */ - public Map getNamespacePrefixes() { - return namespacePrefixes; - } - - /** - * @param namespacePrefixes the map of namespace uri (key) to prefix (value) - */ - public void setNamespacePrefixes(Map namespacePrefixes) { - this.namespacePrefixes = namespacePrefixes; - } - - /** - * helper method for null/default value handling - * @param value - * @param defaultValue - * @return if value is not null, return value otherwise defaultValue - */ - protected static T nvl(T value, T defaultValue) { - return value == null ? defaultValue : value; - } - - /** - * Each digest method has its own IV (initial vector) - * - * @return the IV depending on the main digest method - */ - public byte[] getHashMagic() { - // see https://www.ietf.org/rfc/rfc3110.txt - // RSA/SHA1 SIG Resource Records - byte result[]; - switch (getDigestAlgo()) { - case sha1: result = new byte[] - { 0x30, 0x1f, 0x30, 0x07, 0x06, 0x05, 0x2b, 0x0e - , 0x03, 0x02, 0x1a, 0x04, 0x14 }; - break; - case sha224: result = new byte[] - { 0x30, 0x2b, 0x30, 0x0b, 0x06, 0x09, 0x60, (byte) 0x86 - , 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x04, 0x1c }; - break; - case sha256: result = new byte[] - { 0x30, 0x2f, 0x30, 0x0b, 0x06, 0x09, 0x60, (byte) 0x86 - , 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x04, 0x20 }; - break; - case sha384: result = new byte[] - { 0x30, 0x3f, 0x30, 0x0b, 0x06, 0x09, 0x60, (byte) 0x86 - , 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x04, 0x30 }; - break; - case sha512: result = new byte[] - { 0x30, 0x4f, 0x30, 0x0b, 0x06, 0x09, 0x60, (byte) 0x86 - , 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x04, 0x40 }; - break; - case ripemd128: result = new byte[] - { 0x30, 0x1b, 0x30, 0x07, 0x06, 0x05, 0x2b, 0x24 - , 0x03, 0x02, 0x02, 0x04, 0x10 }; - break; - case ripemd160: result = new byte[] - { 0x30, 0x1f, 0x30, 0x07, 0x06, 0x05, 0x2b, 0x24 - , 0x03, 0x02, 0x01, 0x04, 0x14 }; - break; - // case ripemd256: result = new byte[] - // { 0x30, 0x2b, 0x30, 0x07, 0x06, 0x05, 0x2b, 0x24 - // , 0x03, 0x02, 0x03, 0x04, 0x20 }; - // break; - default: throw new EncryptedDocumentException("Hash algorithm " - +getDigestAlgo()+" not supported for signing."); - } - - return result; - } - - /** - * @return the uri for the signature method, i.e. currently only rsa is - * supported, so it's the rsa variant of the main digest - */ - public String getSignatureMethodUri() { - switch (getDigestAlgo()) { - case sha1: return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1; - case sha224: return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA224; - case sha256: return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA256; - case sha384: return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA384; - case sha512: return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA512; - case ripemd160: return XMLSignature.ALGO_ID_SIGNATURE_RSA_RIPEMD160; - default: throw new EncryptedDocumentException("Hash algorithm " - +getDigestAlgo()+" not supported for signing."); - } - } - - /** - * @return the uri for the main digest - */ - public String getDigestMethodUri() { - return getDigestMethodUri(getDigestAlgo()); - } - - /** - * @param digestAlgo the digest algo, currently only sha* and ripemd160 is supported - * @return the uri for the given digest - */ - public static String getDigestMethodUri(HashAlgorithm digestAlgo) { - switch (digestAlgo) { - case sha1: return DigestMethod.SHA1; - case sha224: return "http://www.w3.org/2001/04/xmldsig-more#sha224"; - case sha256: return DigestMethod.SHA256; - case sha384: return "http://www.w3.org/2001/04/xmldsig-more#sha384"; - case sha512: return DigestMethod.SHA512; - case ripemd160: return DigestMethod.RIPEMD160; - default: throw new EncryptedDocumentException("Hash algorithm " - +digestAlgo+" not supported for signing."); - } - } - - /** - * @param signatureFactory the xml signature factory, saved as thread-local - */ - public void setSignatureFactory(XMLSignatureFactory signatureFactory) { - this.signatureFactory.set(signatureFactory); - } - - /** - * @return the xml signature factory (thread-local) - */ - public XMLSignatureFactory getSignatureFactory() { - XMLSignatureFactory sigFac = signatureFactory.get(); - if (sigFac == null) { - sigFac = XMLSignatureFactory.getInstance("DOM", getProvider()); - setSignatureFactory(sigFac); - } - return sigFac; - } - - /** - * @param keyInfoFactory the key factory, saved as thread-local - */ - public void setKeyInfoFactory(KeyInfoFactory keyInfoFactory) { - this.keyInfoFactory.set(keyInfoFactory); - } - - /** - * @return the key factory (thread-local) - */ - public KeyInfoFactory getKeyInfoFactory() { - KeyInfoFactory keyFac = keyInfoFactory.get(); - if (keyFac == null) { - keyFac = KeyInfoFactory.getInstance("DOM", getProvider()); - setKeyInfoFactory(keyFac); - } - return keyFac; - } - - /** - * This method tests the existence of xml signature provider in the following order: - *

      - *
    • the class pointed to by the system property "jsr105Provider"
    • - *
    • the Santuario xmlsec provider
    • - *
    • the JDK xmlsec provider
    • - *
    - * - * For signing the classes are linked against the Santuario xmlsec, so this might - * only work for validation (not tested). - * - * @return the xml dsig provider - */ - public Provider getProvider() { - Provider prov = provider.get(); - if (prov == null) { - String dsigProviderNames[] = { - System.getProperty("jsr105Provider"), - "org.apache.jcp.xml.dsig.internal.dom.XMLDSigRI", // Santuario xmlsec - "org.jcp.xml.dsig.internal.dom.XMLDSigRI" // JDK xmlsec - }; - for (String pn : dsigProviderNames) { - if (pn == null) continue; - try { - prov = (Provider)Class.forName(pn).newInstance(); - break; - } catch (Exception e) { - LOG.log(POILogger.DEBUG, "XMLDsig-Provider '"+pn+"' can't be found - trying next."); - } - } - } - - if (prov == null) { - throw new RuntimeException("JRE doesn't support default xml signature provider - set jsr105Provider system property!"); - } - - return prov; - } - - /** - * @return the cannonicalization method for XAdES-XL signing. - * Defaults to EXCLUSIVE - * @see javax.xml.crypto.dsig.CanonicalizationMethod - */ - public String getXadesCanonicalizationMethod() { - return xadesCanonicalizationMethod; - } - - /** - * @param xadesCanonicalizationMethod the cannonicalization method for XAdES-XL signing - * @see javax.xml.crypto.dsig.CanonicalizationMethod - */ - public void setXadesCanonicalizationMethod(String xadesCanonicalizationMethod) { - this.xadesCanonicalizationMethod = xadesCanonicalizationMethod; - } -} diff --git a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/SignatureInfo.java b/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/SignatureInfo.java deleted file mode 100644 index d7f648fae..000000000 --- a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/SignatureInfo.java +++ /dev/null @@ -1,701 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -/* ==================================================================== - This product contains an ASLv2 licensed version of the OOXML signer - package from the eID Applet project - http://code.google.com/p/eid-applet/source/browse/trunk/README.txt - Copyright (C) 2008-2014 FedICT. - ================================================================= */ - -package org.apache.poi.poifs.crypt.dsig; - -import static org.apache.poi.POIXMLTypeLoader.DEFAULT_XML_OPTIONS; -import static org.apache.poi.poifs.crypt.dsig.facets.SignatureFacet.XML_DIGSIG_NS; - -import javax.crypto.Cipher; -import javax.xml.crypto.MarshalException; -import javax.xml.crypto.URIDereferencer; -import javax.xml.crypto.XMLStructure; -import javax.xml.crypto.dsig.CanonicalizationMethod; -import javax.xml.crypto.dsig.Manifest; -import javax.xml.crypto.dsig.Reference; -import javax.xml.crypto.dsig.SignatureMethod; -import javax.xml.crypto.dsig.SignedInfo; -import javax.xml.crypto.dsig.XMLObject; -import javax.xml.crypto.dsig.XMLSignContext; -import javax.xml.crypto.dsig.XMLSignature; -import javax.xml.crypto.dsig.XMLSignatureException; -import javax.xml.crypto.dsig.XMLSignatureFactory; -import javax.xml.crypto.dsig.XMLValidateContext; -import javax.xml.crypto.dsig.dom.DOMSignContext; -import javax.xml.crypto.dsig.dom.DOMValidateContext; -import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec; -import javax.xml.xpath.XPath; -import javax.xml.xpath.XPathConstants; -import javax.xml.xpath.XPathExpressionException; -import javax.xml.xpath.XPathFactory; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.OutputStream; -import java.security.GeneralSecurityException; -import java.security.MessageDigest; -import java.security.Provider; -import java.security.Security; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.NoSuchElementException; - -import org.apache.jcp.xml.dsig.internal.dom.DOMReference; -import org.apache.jcp.xml.dsig.internal.dom.DOMSignedInfo; -import org.apache.poi.EncryptedDocumentException; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.ContentTypes; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.opc.PackagePartName; -import org.apache.poi.openxml4j.opc.PackageRelationship; -import org.apache.poi.openxml4j.opc.PackageRelationshipCollection; -import org.apache.poi.openxml4j.opc.PackageRelationshipTypes; -import org.apache.poi.openxml4j.opc.PackagingURIHelper; -import org.apache.poi.openxml4j.opc.TargetMode; -import org.apache.poi.poifs.crypt.ChainingMode; -import org.apache.poi.poifs.crypt.CipherAlgorithm; -import org.apache.poi.poifs.crypt.CryptoFunctions; -import org.apache.poi.poifs.crypt.dsig.SignatureConfig.SignatureConfigurable; -import org.apache.poi.poifs.crypt.dsig.facets.SignatureFacet; -import org.apache.poi.poifs.crypt.dsig.services.RelationshipTransformService; -import org.apache.poi.util.DocumentHelper; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.xml.security.Init; -import org.apache.xml.security.utils.Base64; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlOptions; -import org.w3.x2000.x09.xmldsig.SignatureDocument; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.NodeList; -import org.w3c.dom.events.EventListener; -import org.w3c.dom.events.EventTarget; -import org.xml.sax.SAXException; - - -/** - *

    This class is the default entry point for XML signatures and can be used for - * validating an existing signed office document and signing a office document.

    - * - *

    Validating a signed office document

    - * - *
    - * OPCPackage pkg = OPCPackage.open(..., PackageAccess.READ);
    - * SignatureConfig sic = new SignatureConfig();
    - * sic.setOpcPackage(pkg);
    - * SignatureInfo si = new SignatureInfo();
    - * si.setSignatureConfig(sic);
    - * boolean isValid = si.validate();
    - * ...
    - * 
    - * - *

    Signing an office document

    - * - *
    - * // loading the keystore - pkcs12 is used here, but of course jks & co are also valid
    - * // the keystore needs to contain a private key and it's certificate having a
    - * // 'digitalSignature' key usage
    - * char password[] = "test".toCharArray();
    - * File file = new File("test.pfx");
    - * KeyStore keystore = KeyStore.getInstance("PKCS12");
    - * FileInputStream fis = new FileInputStream(file);
    - * keystore.load(fis, password);
    - * fis.close();
    - * 
    - * // extracting private key and certificate
    - * String alias = "xyz"; // alias of the keystore entry
    - * Key key = keystore.getKey(alias, password);
    - * X509Certificate x509 = (X509Certificate)keystore.getCertificate(alias);
    - * 
    - * // filling the SignatureConfig entries (minimum fields, more options are available ...)
    - * SignatureConfig signatureConfig = new SignatureConfig();
    - * signatureConfig.setKey(keyPair.getPrivate());
    - * signatureConfig.setSigningCertificateChain(Collections.singletonList(x509));
    - * OPCPackage pkg = OPCPackage.open(..., PackageAccess.READ_WRITE);
    - * signatureConfig.setOpcPackage(pkg);
    - * 
    - * // adding the signature document to the package
    - * SignatureInfo si = new SignatureInfo();
    - * si.setSignatureConfig(signatureConfig);
    - * si.confirmSignature();
    - * // optionally verify the generated signature
    - * boolean b = si.verifySignature();
    - * assert (b);
    - * // write the changes back to disc
    - * pkg.close();
    - * 
    - * - *

    Implementation notes:

    - * - *

    Although there's a XML signature implementation in the Oracle JDKs 6 and higher, - * compatibility with IBM JDKs is also in focus (... but maybe not thoroughly tested ...). - * Therefore we are using the Apache Santuario libs (xmlsec) instead of the built-in classes, - * as the compatibility seems to be provided there.

    - * - *

    To use SignatureInfo and its sibling classes, you'll need to have the following libs - * in the classpath:

    - *
      - *
    • BouncyCastle bcpkix and bcprov (tested against 1.54)
    • - *
    • Apache Santuario "xmlsec" (tested against 2.0.5)
    • - *
    • and slf4j-api (tested against 1.7.12)
    • - *
    - */ -public class SignatureInfo implements SignatureConfigurable { - - private static final POILogger LOG = POILogFactory.getLogger(SignatureInfo.class); - private static boolean isInitialized = false; - - private SignatureConfig signatureConfig; - - public class SignaturePart { - private final PackagePart signaturePart; - private X509Certificate signer; - private List certChain; - - private SignaturePart(PackagePart signaturePart) { - this.signaturePart = signaturePart; - } - - /** - * @return the package part containing the signature - */ - public PackagePart getPackagePart() { - return signaturePart; - } - - /** - * @return the signer certificate - */ - public X509Certificate getSigner() { - return signer; - } - - /** - * @return the certificate chain of the signer - */ - public List getCertChain() { - return certChain; - } - - /** - * Helper method for examining the xml signature - * - * @return the xml signature document - * @throws IOException if the xml signature doesn't exist or can't be read - * @throws XmlException if the xml signature is malformed - */ - public SignatureDocument getSignatureDocument() throws IOException, XmlException { - // TODO: check for XXE - return SignatureDocument.Factory.parse(signaturePart.getInputStream(), DEFAULT_XML_OPTIONS); - } - - /** - * @return true, when the xml signature is valid, false otherwise - * - * @throws EncryptedDocumentException if the signature can't be extracted or if its malformed - */ - @SuppressWarnings("unchecked") - public boolean validate() { - KeyInfoKeySelector keySelector = new KeyInfoKeySelector(); - try { - Document doc = DocumentHelper.readDocument(signaturePart.getInputStream()); - XPath xpath = XPathFactory.newInstance().newXPath(); - NodeList nl = (NodeList)xpath.compile("//*[@Id]").evaluate(doc, XPathConstants.NODESET); - final int length = nl.getLength(); - for (int i=0; i)xmlSignature.getSignedInfo().getReferences()) { - SignatureFacet.brokenJvmWorkaround(ref); - } - for (XMLObject xo : (List)xmlSignature.getObjects()) { - for (XMLStructure xs : (List)xo.getContent()) { - if (xs instanceof Manifest) { - for (Reference ref : (List)((Manifest)xs).getReferences()) { - SignatureFacet.brokenJvmWorkaround(ref); - } - } - } - } - - boolean valid = xmlSignature.validate(domValidateContext); - - if (valid) { - signer = keySelector.getSigner(); - certChain = keySelector.getCertChain(); - } - - return valid; - } catch (IOException e) { - String s = "error in reading document"; - LOG.log(POILogger.ERROR, s, e); - throw new EncryptedDocumentException(s, e); - } catch (SAXException e) { - String s = "error in parsing document"; - LOG.log(POILogger.ERROR, s, e); - throw new EncryptedDocumentException(s, e); - } catch (XPathExpressionException e) { - String s = "error in searching document with xpath expression"; - LOG.log(POILogger.ERROR, s, e); - throw new EncryptedDocumentException(s, e); - } catch (MarshalException e) { - String s = "error in unmarshalling the signature"; - LOG.log(POILogger.ERROR, s, e); - throw new EncryptedDocumentException(s, e); - } catch (XMLSignatureException e) { - String s = "error in validating the signature"; - LOG.log(POILogger.ERROR, s, e); - throw new EncryptedDocumentException(s, e); - } - } - } - - /** - * Constructor initializes xml signature environment, if it hasn't been initialized before - */ - public SignatureInfo() { - initXmlProvider(); - } - - /** - * @return the signature config - */ - public SignatureConfig getSignatureConfig() { - return signatureConfig; - } - - /** - * @param signatureConfig the signature config, needs to be set before a SignatureInfo object is used - */ - public void setSignatureConfig(SignatureConfig signatureConfig) { - this.signatureConfig = signatureConfig; - } - - /** - * @return true, if first signature part is valid - */ - public boolean verifySignature() { - // http://www.oracle.com/technetwork/articles/javase/dig-signature-api-140772.html - for (SignaturePart sp : getSignatureParts()){ - // only validate first part - return sp.validate(); - } - return false; - } - - /** - * add the xml signature to the document - * - * @throws XMLSignatureException - * @throws MarshalException - */ - public void confirmSignature() throws XMLSignatureException, MarshalException { - Document document = DocumentHelper.createDocument(); - - // operate - DigestInfo digestInfo = preSign(document, null); - - // setup: key material, signature value - byte[] signatureValue = signDigest(digestInfo.digestValue); - - // operate: postSign - postSign(document, signatureValue); - } - - /** - * Sign (encrypt) the digest with the private key. - * Currently only rsa is supported. - * - * @param digest the hashed input - * @return the encrypted hash - */ - public byte[] signDigest(byte digest[]) { - Cipher cipher = CryptoFunctions.getCipher(signatureConfig.getKey(), CipherAlgorithm.rsa - , ChainingMode.ecb, null, Cipher.ENCRYPT_MODE, "PKCS1Padding"); - - try { - ByteArrayOutputStream digestInfoValueBuf = new ByteArrayOutputStream(); - digestInfoValueBuf.write(signatureConfig.getHashMagic()); - digestInfoValueBuf.write(digest); - byte[] digestInfoValue = digestInfoValueBuf.toByteArray(); - byte[] signatureValue = cipher.doFinal(digestInfoValue); - return signatureValue; - } catch (Exception e) { - throw new EncryptedDocumentException(e); - } - } - - /** - * @return a signature part for each signature document. - * the parts can be validated independently. - */ - public Iterable getSignatureParts() { - signatureConfig.init(true); - return new Iterable() { - public Iterator iterator() { - return new Iterator() { - OPCPackage pkg = signatureConfig.getOpcPackage(); - Iterator sigOrigRels = - pkg.getRelationshipsByType(PackageRelationshipTypes.DIGITAL_SIGNATURE_ORIGIN).iterator(); - Iterator sigRels = null; - PackagePart sigPart = null; - - public boolean hasNext() { - while (sigRels == null || !sigRels.hasNext()) { - if (!sigOrigRels.hasNext()) return false; - sigPart = pkg.getPart(sigOrigRels.next()); - LOG.log(POILogger.DEBUG, "Digital Signature Origin part", sigPart); - try { - sigRels = sigPart.getRelationshipsByType(PackageRelationshipTypes.DIGITAL_SIGNATURE).iterator(); - } catch (InvalidFormatException e) { - LOG.log(POILogger.WARN, "Reference to signature is invalid.", e); - } - } - return true; - } - - public SignaturePart next() { - PackagePart sigRelPart = null; - do { - try { - if (!hasNext()) throw new NoSuchElementException(); - sigRelPart = sigPart.getRelatedPart(sigRels.next()); - LOG.log(POILogger.DEBUG, "XML Signature part", sigRelPart); - } catch (InvalidFormatException e) { - LOG.log(POILogger.WARN, "Reference to signature is invalid.", e); - } - } while (sigPart == null); - return new SignaturePart(sigRelPart); - } - - public void remove() { - throw new UnsupportedOperationException(); - } - }; - } - }; - } - - /** - * Initialize the xml signing environment and the bouncycastle provider - */ - protected static synchronized void initXmlProvider() { - if (isInitialized) return; - isInitialized = true; - - try { - Init.init(); - RelationshipTransformService.registerDsigProvider(); - CryptoFunctions.registerBouncyCastle(); - } catch (Exception e) { - throw new RuntimeException("Xml & BouncyCastle-Provider initialization failed", e); - } - } - - /** - * Helper method for adding informations before the signing. - * Normally {@link #confirmSignature()} is sufficient to be used. - */ - @SuppressWarnings("unchecked") - public DigestInfo preSign(Document document, List digestInfos) - throws XMLSignatureException, MarshalException { - signatureConfig.init(false); - - // it's necessary to explicitly set the mdssi namespace, but the sign() method has no - // normal way to interfere with, so we need to add the namespace under the hand ... - EventTarget target = (EventTarget)document; - EventListener creationListener = signatureConfig.getSignatureMarshalListener(); - if (creationListener != null) { - if (creationListener instanceof SignatureMarshalListener) { - ((SignatureMarshalListener)creationListener).setEventTarget(target); - } - SignatureMarshalListener.setListener(target, creationListener, true); - } - - /* - * Signature context construction. - */ - XMLSignContext xmlSignContext = new DOMSignContext(signatureConfig.getKey(), document); - URIDereferencer uriDereferencer = signatureConfig.getUriDereferencer(); - if (null != uriDereferencer) { - xmlSignContext.setURIDereferencer(uriDereferencer); - } - - for (Map.Entry me : signatureConfig.getNamespacePrefixes().entrySet()) { - xmlSignContext.putNamespacePrefix(me.getKey(), me.getValue()); - } - xmlSignContext.setDefaultNamespacePrefix(""); - // signatureConfig.getNamespacePrefixes().get(XML_DIGSIG_NS)); - - brokenJvmWorkaround(xmlSignContext); - - XMLSignatureFactory signatureFactory = signatureConfig.getSignatureFactory(); - - /* - * Add ds:References that come from signing client local files. - */ - List references = new ArrayList(); - for (DigestInfo digestInfo : safe(digestInfos)) { - byte[] documentDigestValue = digestInfo.digestValue; - - String uri = new File(digestInfo.description).getName(); - Reference reference = SignatureFacet.newReference - (uri, null, null, null, documentDigestValue, signatureConfig); - references.add(reference); - } - - /* - * Invoke the signature facets. - */ - List objects = new ArrayList(); - for (SignatureFacet signatureFacet : signatureConfig.getSignatureFacets()) { - LOG.log(POILogger.DEBUG, "invoking signature facet: " + signatureFacet.getClass().getSimpleName()); - signatureFacet.preSign(document, references, objects); - } - - /* - * ds:SignedInfo - */ - SignedInfo signedInfo; - try { - SignatureMethod signatureMethod = signatureFactory.newSignatureMethod - (signatureConfig.getSignatureMethodUri(), null); - CanonicalizationMethod canonicalizationMethod = signatureFactory - .newCanonicalizationMethod(signatureConfig.getCanonicalizationMethod(), - (C14NMethodParameterSpec) null); - signedInfo = signatureFactory.newSignedInfo( - canonicalizationMethod, signatureMethod, references); - } catch (GeneralSecurityException e) { - throw new XMLSignatureException(e); - } - - /* - * JSR105 ds:Signature creation - */ - String signatureValueId = signatureConfig.getPackageSignatureId() + "-signature-value"; - javax.xml.crypto.dsig.XMLSignature xmlSignature = signatureFactory - .newXMLSignature(signedInfo, null, objects, signatureConfig.getPackageSignatureId(), - signatureValueId); - - /* - * ds:Signature Marshalling. - */ - xmlSignature.sign(xmlSignContext); - - /* - * Completion of undigested ds:References in the ds:Manifests. - */ - for (XMLObject object : objects) { - LOG.log(POILogger.DEBUG, "object java type: " + object.getClass().getName()); - List objectContentList = object.getContent(); - for (XMLStructure objectContent : objectContentList) { - LOG.log(POILogger.DEBUG, "object content java type: " + objectContent.getClass().getName()); - if (!(objectContent instanceof Manifest)) continue; - Manifest manifest = (Manifest) objectContent; - List manifestReferences = manifest.getReferences(); - for (Reference manifestReference : manifestReferences) { - if (manifestReference.getDigestValue() != null) continue; - - DOMReference manifestDOMReference = (DOMReference)manifestReference; - manifestDOMReference.digest(xmlSignContext); - } - } - } - - /* - * Completion of undigested ds:References. - */ - List signedInfoReferences = signedInfo.getReferences(); - for (Reference signedInfoReference : signedInfoReferences) { - DOMReference domReference = (DOMReference)signedInfoReference; - - // ds:Reference with external digest value - if (domReference.getDigestValue() != null) continue; - - domReference.digest(xmlSignContext); - } - - /* - * Calculation of XML signature digest value. - */ - DOMSignedInfo domSignedInfo = (DOMSignedInfo)signedInfo; - ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); - domSignedInfo.canonicalize(xmlSignContext, dataStream); - byte[] octets = dataStream.toByteArray(); - - /* - * TODO: we could be using DigestOutputStream here to optimize memory - * usage. - */ - - MessageDigest md = CryptoFunctions.getMessageDigest(signatureConfig.getDigestAlgo()); - byte[] digestValue = md.digest(octets); - - - String description = signatureConfig.getSignatureDescription(); - return new DigestInfo(digestValue, signatureConfig.getDigestAlgo(), description); - } - - /** - * Helper method for adding informations after the signing. - * Normally {@link #confirmSignature()} is sufficient to be used. - */ - public void postSign(Document document, byte[] signatureValue) - throws MarshalException { - LOG.log(POILogger.DEBUG, "postSign"); - - /* - * Check ds:Signature node. - */ - String signatureId = signatureConfig.getPackageSignatureId(); - if (!signatureId.equals(document.getDocumentElement().getAttribute("Id"))) { - throw new RuntimeException("ds:Signature not found for @Id: " + signatureId); - } - - /* - * Insert signature value into the ds:SignatureValue element - */ - NodeList sigValNl = document.getElementsByTagNameNS(XML_DIGSIG_NS, "SignatureValue"); - if (sigValNl.getLength() != 1) { - throw new RuntimeException("preSign has to be called before postSign"); - } - sigValNl.item(0).setTextContent(Base64.encode(signatureValue)); - - /* - * Allow signature facets to inject their own stuff. - */ - for (SignatureFacet signatureFacet : signatureConfig.getSignatureFacets()) { - signatureFacet.postSign(document); - } - - writeDocument(document); - } - - /** - * Write XML signature into the OPC package - * - * @param document the xml signature document - * @throws MarshalException - */ - protected void writeDocument(Document document) throws MarshalException { - XmlOptions xo = new XmlOptions(); - Map namespaceMap = new HashMap(); - for(Map.Entry entry : signatureConfig.getNamespacePrefixes().entrySet()){ - namespaceMap.put(entry.getValue(), entry.getKey()); - } - xo.setSaveSuggestedPrefixes(namespaceMap); - xo.setUseDefaultNamespace(); - - LOG.log(POILogger.DEBUG, "output signed Office OpenXML document"); - - /* - * Copy the original OOXML content to the signed OOXML package. During - * copying some files need to changed. - */ - OPCPackage pkg = signatureConfig.getOpcPackage(); - - PackagePartName sigPartName, sigsPartName; - try { - // - sigPartName = PackagingURIHelper.createPartName("/_xmlsignatures/sig1.xml"); - // - sigsPartName = PackagingURIHelper.createPartName("/_xmlsignatures/origin.sigs"); - } catch (InvalidFormatException e) { - throw new MarshalException(e); - } - - PackagePart sigPart = pkg.getPart(sigPartName); - if (sigPart == null) { - sigPart = pkg.createPart(sigPartName, ContentTypes.DIGITAL_SIGNATURE_XML_SIGNATURE_PART); - } - - try { - OutputStream os = sigPart.getOutputStream(); - SignatureDocument sigDoc = SignatureDocument.Factory.parse(document, DEFAULT_XML_OPTIONS); - sigDoc.save(os, xo); - os.close(); - } catch (Exception e) { - throw new MarshalException("Unable to write signature document", e); - } - - PackagePart sigsPart = pkg.getPart(sigsPartName); - if (sigsPart == null) { - // touch empty marker file - sigsPart = pkg.createPart(sigsPartName, ContentTypes.DIGITAL_SIGNATURE_ORIGIN_PART); - } - - PackageRelationshipCollection relCol = pkg.getRelationshipsByType(PackageRelationshipTypes.DIGITAL_SIGNATURE_ORIGIN); - for (PackageRelationship pr : relCol) { - pkg.removeRelationship(pr.getId()); - } - pkg.addRelationship(sigsPartName, TargetMode.INTERNAL, PackageRelationshipTypes.DIGITAL_SIGNATURE_ORIGIN); - - sigsPart.addRelationship(sigPartName, TargetMode.INTERNAL, PackageRelationshipTypes.DIGITAL_SIGNATURE); - } - - /** - * Helper method for null lists, which are converted to empty lists - * - * @param other the reference to wrap, if null - * @return if other is null, an empty lists is returned, otherwise other is returned - */ - private static List safe(List other) { - List emptyList = Collections.emptyList(); - return other == null ? emptyList : other; - } - - private void brokenJvmWorkaround(XMLSignContext context) { - // workaround for https://bugzilla.redhat.com/show_bug.cgi?id=1155012 - Provider bcProv = Security.getProvider("BC"); - if (bcProv != null) { - context.setProperty("org.jcp.xml.dsig.internal.dom.SignatureProvider", bcProv); - } - } - - private void brokenJvmWorkaround(XMLValidateContext context) { - // workaround for https://bugzilla.redhat.com/show_bug.cgi?id=1155012 - Provider bcProv = Security.getProvider("BC"); - if (bcProv != null) { - context.setProperty("org.jcp.xml.dsig.internal.dom.SignatureProvider", bcProv); - } - } -} diff --git a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/SignatureMarshalListener.java b/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/SignatureMarshalListener.java deleted file mode 100644 index 3b21eb865..000000000 --- a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/SignatureMarshalListener.java +++ /dev/null @@ -1,92 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.crypt.dsig; - -import static org.apache.poi.poifs.crypt.dsig.facets.SignatureFacet.OO_DIGSIG_NS; -import static org.apache.poi.poifs.crypt.dsig.facets.SignatureFacet.XML_NS; - -import org.apache.poi.poifs.crypt.dsig.SignatureConfig.SignatureConfigurable; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.w3c.dom.events.Event; -import org.w3c.dom.events.EventListener; -import org.w3c.dom.events.EventTarget; -import org.w3c.dom.events.MutationEvent; - -/** - * This listener class is used, to modify the to be digested xml document, - * e.g. to register id attributes or set prefixes for registered namespaces - */ -public class SignatureMarshalListener implements EventListener, SignatureConfigurable { - ThreadLocal target = new ThreadLocal(); - SignatureConfig signatureConfig; - public void setEventTarget(EventTarget target) { - this.target.set(target); - } - - public void handleEvent(Event e) { - if (!(e instanceof MutationEvent)) return; - MutationEvent mutEvt = (MutationEvent)e; - EventTarget et = mutEvt.getTarget(); - if (!(et instanceof Element)) return; - handleElement((Element)et); - } - - public void handleElement(Element el) { - EventTarget target = this.target.get(); - String packageId = signatureConfig.getPackageSignatureId(); - if (el.hasAttribute("Id")) { - el.setIdAttribute("Id", true); - } - - setListener(target, this, false); - if (packageId.equals(el.getAttribute("Id"))) { - el.setAttributeNS(XML_NS, "xmlns:mdssi", OO_DIGSIG_NS); - } - setPrefix(el); - setListener(target, this, true); - } - - // helper method to keep it in one place - public static void setListener(EventTarget target, EventListener listener, boolean enabled) { - String type = "DOMSubtreeModified"; - boolean useCapture = false; - if (enabled) { - target.addEventListener(type, listener, useCapture); - } else { - target.removeEventListener(type, listener, useCapture); - } - } - - protected void setPrefix(Node el) { - String prefix = signatureConfig.getNamespacePrefixes().get(el.getNamespaceURI()); - if (prefix != null && el.getPrefix() == null) { - el.setPrefix(prefix); - } - - NodeList nl = el.getChildNodes(); - for (int i=0; i references - , List objects) - throws XMLSignatureException { - List transforms = new ArrayList(); - Transform envelopedTransform = newTransform(CanonicalizationMethod.ENVELOPED); - transforms.add(envelopedTransform); - Transform exclusiveTransform = newTransform(CanonicalizationMethod.EXCLUSIVE); - transforms.add(exclusiveTransform); - - Reference reference = newReference("", transforms, null, null, null); - references.add(reference); - } -} diff --git a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/facets/KeyInfoSignatureFacet.java b/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/facets/KeyInfoSignatureFacet.java deleted file mode 100644 index 67d18dd28..000000000 --- a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/facets/KeyInfoSignatureFacet.java +++ /dev/null @@ -1,148 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -/* ==================================================================== - This product contains an ASLv2 licensed version of the OOXML signer - package from the eID Applet project - http://code.google.com/p/eid-applet/source/browse/trunk/README.txt - Copyright (C) 2008-2014 FedICT. - ================================================================= */ - -package org.apache.poi.poifs.crypt.dsig.facets; - -import java.security.Key; -import java.security.KeyException; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import javax.xml.crypto.MarshalException; -import javax.xml.crypto.XMLStructure; -import javax.xml.crypto.dom.DOMStructure; -import javax.xml.crypto.dsig.dom.DOMSignContext; -import javax.xml.crypto.dsig.keyinfo.KeyInfo; -import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory; -import javax.xml.crypto.dsig.keyinfo.KeyValue; -import javax.xml.crypto.dsig.keyinfo.X509Data; - -import org.apache.jcp.xml.dsig.internal.dom.DOMKeyInfo; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -/** - * Signature Facet implementation that adds ds:KeyInfo to the XML signature. - * - * @author Frank Cornelis - * - */ -public class KeyInfoSignatureFacet extends SignatureFacet { - - private static final POILogger LOG = POILogFactory.getLogger(KeyInfoSignatureFacet.class); - - @Override - public void postSign(Document document) - throws MarshalException { - LOG.log(POILogger.DEBUG, "postSign"); - - NodeList nl = document.getElementsByTagNameNS(XML_DIGSIG_NS, "Object"); - - /* - * Make sure we insert right after the ds:SignatureValue element, just - * before the first ds:Object element. - */ - Node nextSibling = (nl.getLength() == 0) ? null : nl.item(0); - - /* - * Construct the ds:KeyInfo element using JSR 105. - */ - KeyInfoFactory keyInfoFactory = signatureConfig.getKeyInfoFactory(); - List x509DataObjects = new ArrayList(); - X509Certificate signingCertificate = signatureConfig.getSigningCertificateChain().get(0); - - List keyInfoContent = new ArrayList(); - - if (signatureConfig.isIncludeKeyValue()) { - KeyValue keyValue; - try { - keyValue = keyInfoFactory.newKeyValue(signingCertificate.getPublicKey()); - } catch (KeyException e) { - throw new RuntimeException("key exception: " + e.getMessage(), e); - } - keyInfoContent.add(keyValue); - } - - if (signatureConfig.isIncludeIssuerSerial()) { - x509DataObjects.add(keyInfoFactory.newX509IssuerSerial( - signingCertificate.getIssuerX500Principal().toString(), - signingCertificate.getSerialNumber())); - } - - if (signatureConfig.isIncludeEntireCertificateChain()) { - x509DataObjects.addAll(signatureConfig.getSigningCertificateChain()); - } else { - x509DataObjects.add(signingCertificate); - } - - if (!x509DataObjects.isEmpty()) { - X509Data x509Data = keyInfoFactory.newX509Data(x509DataObjects); - keyInfoContent.add(x509Data); - } - KeyInfo keyInfo = keyInfoFactory.newKeyInfo(keyInfoContent); - DOMKeyInfo domKeyInfo = (DOMKeyInfo)keyInfo; - - Key key = new Key() { - private static final long serialVersionUID = 1L; - - public String getAlgorithm() { - return null; - } - - public byte[] getEncoded() { - return null; - } - - public String getFormat() { - return null; - } - }; - - Element n = document.getDocumentElement(); - DOMSignContext domSignContext = (nextSibling == null) - ? new DOMSignContext(key, n) - : new DOMSignContext(key, n, nextSibling); - for (Map.Entry me : signatureConfig.getNamespacePrefixes().entrySet()) { - domSignContext.putNamespacePrefix(me.getKey(), me.getValue()); - } - - DOMStructure domStructure = new DOMStructure(n); - domKeyInfo.marshal(domStructure, domSignContext); - - // move keyinfo into the right place - if (nextSibling != null) { - NodeList kiNl = document.getElementsByTagNameNS(XML_DIGSIG_NS, "KeyInfo"); - if (kiNl.getLength() != 1) { - throw new RuntimeException("KeyInfo wasn't set"); - } - nextSibling.getParentNode().insertBefore(kiNl.item(0), nextSibling); - } - } -} \ No newline at end of file diff --git a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/facets/OOXMLSignatureFacet.java b/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/facets/OOXMLSignatureFacet.java deleted file mode 100644 index 5affefc07..000000000 --- a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/facets/OOXMLSignatureFacet.java +++ /dev/null @@ -1,475 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -/* ==================================================================== - This product contains an ASLv2 licensed version of the OOXML signer - package from the eID Applet project - http://code.google.com/p/eid-applet/source/browse/trunk/README.txt - Copyright (C) 2008-2014 FedICT. - ================================================================= */ - -package org.apache.poi.poifs.crypt.dsig.facets; - -import java.net.URI; -import java.net.URISyntaxException; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.Set; - -import javax.xml.XMLConstants; -import javax.xml.crypto.XMLStructure; -import javax.xml.crypto.dom.DOMStructure; -import javax.xml.crypto.dsig.CanonicalizationMethod; -import javax.xml.crypto.dsig.Manifest; -import javax.xml.crypto.dsig.Reference; -import javax.xml.crypto.dsig.SignatureProperties; -import javax.xml.crypto.dsig.SignatureProperty; -import javax.xml.crypto.dsig.Transform; -import javax.xml.crypto.dsig.XMLObject; -import javax.xml.crypto.dsig.XMLSignatureException; - -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.ContentTypes; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.opc.PackagePartName; -import org.apache.poi.openxml4j.opc.PackageRelationship; -import org.apache.poi.openxml4j.opc.PackageRelationshipCollection; -import org.apache.poi.openxml4j.opc.PackagingURIHelper; -import org.apache.poi.openxml4j.opc.TargetMode; -import org.apache.poi.poifs.crypt.dsig.services.RelationshipTransformService; -import org.apache.poi.poifs.crypt.dsig.services.RelationshipTransformService.RelationshipTransformParameterSpec; -import org.apache.poi.util.LocaleUtil; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.openxmlformats.schemas.xpackage.x2006.digitalSignature.CTSignatureTime; -import org.openxmlformats.schemas.xpackage.x2006.digitalSignature.SignatureTimeDocument; -import org.w3c.dom.Document; -import org.w3c.dom.Element; - -import com.microsoft.schemas.office.x2006.digsig.CTSignatureInfoV1; -import com.microsoft.schemas.office.x2006.digsig.SignatureInfoV1Document; - -/** - * Office OpenXML Signature Facet implementation. - * - * @author fcorneli - * @see [MS-OFFCRYPTO]: Office Document Cryptography Structure - */ -public class OOXMLSignatureFacet extends SignatureFacet { - - private static final POILogger LOG = POILogFactory.getLogger(OOXMLSignatureFacet.class); - - @Override - public void preSign( - Document document - , List references - , List objects) - throws XMLSignatureException { - LOG.log(POILogger.DEBUG, "pre sign"); - addManifestObject(document, references, objects); - addSignatureInfo(document, references, objects); - } - - protected void addManifestObject( - Document document - , List references - , List objects) - throws XMLSignatureException { - - List manifestReferences = new ArrayList(); - addManifestReferences(manifestReferences); - Manifest manifest = getSignatureFactory().newManifest(manifestReferences); - - String objectId = "idPackageObject"; // really has to be this value. - List objectContent = new ArrayList(); - objectContent.add(manifest); - - addSignatureTime(document, objectContent); - - XMLObject xo = getSignatureFactory().newXMLObject(objectContent, objectId, null, null); - objects.add(xo); - - Reference reference = newReference("#" + objectId, null, XML_DIGSIG_NS+"Object", null, null); - references.add(reference); - } - - @SuppressWarnings("resource") - protected void addManifestReferences(List manifestReferences) - throws XMLSignatureException { - - OPCPackage ooxml = signatureConfig.getOpcPackage(); - List relsEntryNames = ooxml.getPartsByContentType(ContentTypes.RELATIONSHIPS_PART); - - Set digestedPartNames = new HashSet(); - for (PackagePart pp : relsEntryNames) { - String baseUri = pp.getPartName().getName().replaceFirst("(.*)/_rels/.*", "$1"); - - PackageRelationshipCollection prc; - try { - prc = new PackageRelationshipCollection(ooxml); - prc.parseRelationshipsPart(pp); - } catch (InvalidFormatException e) { - throw new XMLSignatureException("Invalid relationship descriptor: "+pp.getPartName().getName(), e); - } - - RelationshipTransformParameterSpec parameterSpec = new RelationshipTransformParameterSpec(); - for (PackageRelationship relationship : prc) { - String relationshipType = relationship.getRelationshipType(); - - /* - * ECMA-376 Part 2 - 3rd edition - * 13.2.4.16 Manifest Element - * "The producer shall not create a Manifest element that references any data outside of the package." - */ - if (TargetMode.EXTERNAL == relationship.getTargetMode()) { - continue; - } - - if (!isSignedRelationship(relationshipType)) continue; - - parameterSpec.addRelationshipReference(relationship.getId()); - - // TODO: find a better way ... - String partName = relationship.getTargetURI().toString(); - if (!partName.startsWith(baseUri)) { - partName = baseUri + partName; - } - try { - partName = new URI(partName).normalize().getPath().replace('\\', '/'); - LOG.log(POILogger.DEBUG, "part name: " + partName); - } catch (URISyntaxException e) { - throw new XMLSignatureException(e); - } - - String contentType; - try { - PackagePartName relName = PackagingURIHelper.createPartName(partName); - PackagePart pp2 = ooxml.getPart(relName); - contentType = pp2.getContentType(); - } catch (InvalidFormatException e) { - throw new XMLSignatureException(e); - } - - if (relationshipType.endsWith("customXml") - && !(contentType.equals("inkml+xml") || contentType.equals("text/xml"))) { - LOG.log(POILogger.DEBUG, "skipping customXml with content type: " + contentType); - continue; - } - - if (!digestedPartNames.contains(partName)) { - // We only digest a part once. - String uri = partName + "?ContentType=" + contentType; - Reference reference = newReference(uri, null, null, null, null); - manifestReferences.add(reference); - digestedPartNames.add(partName); - } - } - - if (parameterSpec.hasSourceIds()) { - List transforms = new ArrayList(); - transforms.add(newTransform(RelationshipTransformService.TRANSFORM_URI, parameterSpec)); - transforms.add(newTransform(CanonicalizationMethod.INCLUSIVE)); - String uri = pp.getPartName().getName() - + "?ContentType=application/vnd.openxmlformats-package.relationships+xml"; - Reference reference = newReference(uri, transforms, null, null, null); - manifestReferences.add(reference); - } - } - } - - - protected void addSignatureTime(Document document, List objectContent) { - /* - * SignatureTime - */ - DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ROOT); - fmt.setTimeZone(LocaleUtil.TIMEZONE_UTC); - String nowStr = fmt.format(signatureConfig.getExecutionTime()); - LOG.log(POILogger.DEBUG, "now: " + nowStr); - - SignatureTimeDocument sigTime = SignatureTimeDocument.Factory.newInstance(); - CTSignatureTime ctTime = sigTime.addNewSignatureTime(); - ctTime.setFormat("YYYY-MM-DDThh:mm:ssTZD"); - ctTime.setValue(nowStr); - - Element n = (Element)document.importNode(ctTime.getDomNode(),true); - List signatureTimeContent = new ArrayList(); - signatureTimeContent.add(new DOMStructure(n)); - SignatureProperty signatureTimeSignatureProperty = getSignatureFactory() - .newSignatureProperty(signatureTimeContent, "#" + signatureConfig.getPackageSignatureId(), - "idSignatureTime"); - List signaturePropertyContent = new ArrayList(); - signaturePropertyContent.add(signatureTimeSignatureProperty); - SignatureProperties signatureProperties = getSignatureFactory() - .newSignatureProperties(signaturePropertyContent, - "id-signature-time-" + signatureConfig.getExecutionTime()); - objectContent.add(signatureProperties); - } - - protected void addSignatureInfo(Document document, - List references, - List objects) - throws XMLSignatureException { - List objectContent = new ArrayList(); - - SignatureInfoV1Document sigV1 = SignatureInfoV1Document.Factory.newInstance(); - CTSignatureInfoV1 ctSigV1 = sigV1.addNewSignatureInfoV1(); - ctSigV1.setManifestHashAlgorithm(signatureConfig.getDigestMethodUri()); - Element n = (Element)document.importNode(ctSigV1.getDomNode(), true); - n.setAttributeNS(XML_NS, XMLConstants.XMLNS_ATTRIBUTE, MS_DIGSIG_NS); - - List signatureInfoContent = new ArrayList(); - signatureInfoContent.add(new DOMStructure(n)); - SignatureProperty signatureInfoSignatureProperty = getSignatureFactory() - .newSignatureProperty(signatureInfoContent, "#" + signatureConfig.getPackageSignatureId(), - "idOfficeV1Details"); - - List signaturePropertyContent = new ArrayList(); - signaturePropertyContent.add(signatureInfoSignatureProperty); - SignatureProperties signatureProperties = getSignatureFactory() - .newSignatureProperties(signaturePropertyContent, null); - objectContent.add(signatureProperties); - - String objectId = "idOfficeObject"; - objects.add(getSignatureFactory().newXMLObject(objectContent, objectId, null, null)); - - Reference reference = newReference("#" + objectId, null, XML_DIGSIG_NS+"Object", null, null); - references.add(reference); - } - - protected static String getRelationshipReferenceURI(String zipEntryName) { - return "/" - + zipEntryName - + "?ContentType=application/vnd.openxmlformats-package.relationships+xml"; - } - - protected static String getResourceReferenceURI(String resourceName, String contentType) { - return "/" + resourceName + "?ContentType=" + contentType; - } - - protected static boolean isSignedRelationship(String relationshipType) { - LOG.log(POILogger.DEBUG, "relationship type: " + relationshipType); - for (String signedTypeExtension : signed) { - if (relationshipType.endsWith(signedTypeExtension)) { - return true; - } - } - if (relationshipType.endsWith("customXml")) { - LOG.log(POILogger.DEBUG, "customXml relationship type"); - return true; - } - return false; - } - - public static final String[] contentTypes = { - /* - * Word - */ - "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml", - "application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml", - "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml", - "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml", - "application/vnd.openxmlformats-officedocument.theme+xml", - "application/vnd.openxmlformats-officedocument.wordprocessingml.webSettings+xml", - "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml", - - /* - * Word 2010 - */ - "application/vnd.ms-word.stylesWithEffects+xml", - - /* - * Excel - */ - "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml", - "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml", - "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml", - "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml", - - /* - * Powerpoint - */ - "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml", - "application/vnd.openxmlformats-officedocument.presentationml.slideLayout+xml", - "application/vnd.openxmlformats-officedocument.presentationml.slideMaster+xml", - "application/vnd.openxmlformats-officedocument.presentationml.slide+xml", - "application/vnd.openxmlformats-officedocument.presentationml.tableStyles+xml", - - /* - * Powerpoint 2010 - */ - "application/vnd.openxmlformats-officedocument.presentationml.viewProps+xml", - "application/vnd.openxmlformats-officedocument.presentationml.presProps+xml" - }; - - /** - * Office 2010 list of signed types (extensions). - */ - public static final String[] signed = { - "powerPivotData", // - "activeXControlBinary", // - "attachedToolbars", // - "connectorXml", // - "downRev", // - "functionPrototypes", // - "graphicFrameDoc", // - "groupShapeXml", // - "ink", // - "keyMapCustomizations", // - "legacyDiagramText", // - "legacyDocTextInfo", // - "officeDocument", // - "pictureXml", // - "shapeXml", // - "smartTags", // - "ui/altText", // - "ui/buttonSize", // - "ui/controlID", // - "ui/description", // - "ui/enabled", // - "ui/extensibility", // - "ui/helperText", // - "ui/imageID", // - "ui/imageMso", // - "ui/keyTip", // - "ui/label", // - "ui/lcid", // - "ui/loud", // - "ui/pressed", // - "ui/progID", // - "ui/ribbonID", // - "ui/showImage", // - "ui/showLabel", // - "ui/supertip", // - "ui/target", // - "ui/text", // - "ui/title", // - "ui/tooltip", // - "ui/userCustomization", // - "ui/visible", // - "userXmlData", // - "vbaProject", // - "wordVbaData", // - "wsSortMap", // - "xlBinaryIndex", // - "xlExternalLinkPath/xlAlternateStartup", // - "xlExternalLinkPath/xlLibrary", // - "xlExternalLinkPath/xlPathMissing", // - "xlExternalLinkPath/xlStartup", // - "xlIntlMacrosheet", // - "xlMacrosheet", // - "customData", // - "diagramDrawing", // - "hdphoto", // - "inkXml", // - "media", // - "slicer", // - "slicerCache", // - "stylesWithEffects", // - "ui/extensibility", // - "chartColorStyle", // - "chartLayout", // - "chartStyle", // - "dictionary", // - "timeline", // - "timelineCache", // - "aFChunk", // - "attachedTemplate", // - "audio", // - "calcChain", // - "chart", // - "chartsheet", // - "chartUserShapes", // - "commentAuthors", // - "comments", // - "connections", // - "control", // - "customProperty", // - "customXml", // - "diagramColors", // - "diagramData", // - "diagramLayout", // - "diagramQuickStyle", // - "dialogsheet", // - "drawing", // - "endnotes", // - "externalLink", // - "externalLinkPath", // - "font", // - "fontTable", // - "footer", // - "footnotes", // - "glossaryDocument", // - "handoutMaster", // - "header", // - "hyperlink", // - "image", // - "mailMergeHeaderSource", // - "mailMergeRecipientData", // - "mailMergeSource", // - "notesMaster", // - "notesSlide", // - "numbering", // - "officeDocument", // - "oleObject", // - "package", // - "pivotCacheDefinition", // - "pivotCacheRecords", // - "pivotTable", // - "presProps", // - "printerSettings", // - "queryTable", // - "recipientData", // - "settings", // - "sharedStrings", // - "sheetMetadata", // - "slide", // - "slideLayout", // - "slideMaster", // - "slideUpdateInfo", // - "slideUpdateUrl", // - "styles", // - "table", // - "tableSingleCells", // - "tableStyles", // - "tags", // - "theme", // - "themeOverride", // - "transform", // - "video", // - "viewProps", // - "volatileDependencies", // - "webSettings", // - "worksheet", // - "xmlMaps", // - "ctrlProp", // - "customData", // - "diagram", // - "diagramColorsHeader", // - "diagramLayoutHeader", // - "diagramQuickStyleHeader", // - "documentParts", // - "slicer", // - "slicerCache", // - "vmlDrawing" // - }; -} \ No newline at end of file diff --git a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/facets/Office2010SignatureFacet.java b/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/facets/Office2010SignatureFacet.java deleted file mode 100644 index 1cd1c6acc..000000000 --- a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/facets/Office2010SignatureFacet.java +++ /dev/null @@ -1,79 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -/* ==================================================================== - This product contains an ASLv2 licensed version of the OOXML signer - package from the eID Applet project - http://code.google.com/p/eid-applet/source/browse/trunk/README.txt - Copyright (C) 2008-2014 FedICT. - ================================================================= */ - -package org.apache.poi.poifs.crypt.dsig.facets; - -import static org.apache.poi.POIXMLTypeLoader.DEFAULT_XML_OPTIONS; - -import javax.xml.crypto.MarshalException; - -import org.apache.xmlbeans.XmlException; -import org.etsi.uri.x01903.v13.QualifyingPropertiesType; -import org.etsi.uri.x01903.v13.UnsignedPropertiesType; -import org.etsi.uri.x01903.v13.UnsignedSignaturePropertiesType; -import org.w3c.dom.Document; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -/** - * Work-around for Office2010 to accept the XAdES-BES/EPES signature. - * - * xades:UnsignedProperties/xades:UnsignedSignatureProperties needs to be - * present. - * - * @author Frank Cornelis - * - */ -public class Office2010SignatureFacet extends SignatureFacet { - - @Override - public void postSign(Document document) - throws MarshalException { - // check for XAdES-BES - NodeList nl = document.getElementsByTagNameNS(XADES_132_NS, "QualifyingProperties"); - if (nl.getLength() != 1) { - throw new MarshalException("no XAdES-BES extension present"); - } - - QualifyingPropertiesType qualProps; - try { - qualProps = QualifyingPropertiesType.Factory.parse(nl.item(0), DEFAULT_XML_OPTIONS); - } catch (XmlException e) { - throw new MarshalException(e); - } - - // create basic XML container structure - UnsignedPropertiesType unsignedProps = qualProps.getUnsignedProperties(); - if (unsignedProps == null) { - unsignedProps = qualProps.addNewUnsignedProperties(); - } - UnsignedSignaturePropertiesType unsignedSigProps = unsignedProps.getUnsignedSignatureProperties(); - if (unsignedSigProps == null) { - /* unsignedSigProps = */ unsignedProps.addNewUnsignedSignatureProperties(); - } - - Node n = document.importNode(qualProps.getDomNode().getFirstChild(), true); - nl.item(0).getParentNode().replaceChild(n, nl.item(0)); - } -} \ No newline at end of file diff --git a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/facets/SignatureFacet.java b/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/facets/SignatureFacet.java deleted file mode 100644 index eec02ad4d..000000000 --- a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/facets/SignatureFacet.java +++ /dev/null @@ -1,190 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -/* ==================================================================== - This product contains an ASLv2 licensed version of the OOXML signer - package from the eID Applet project - http://code.google.com/p/eid-applet/source/browse/trunk/README.txt - Copyright (C) 2008-2014 FedICT. - ================================================================= */ - -package org.apache.poi.poifs.crypt.dsig.facets; - -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.security.AccessController; -import java.security.GeneralSecurityException; -import java.security.MessageDigest; -import java.security.PrivilegedAction; -import java.security.Provider; -import java.security.Security; -import java.util.List; - -import javax.xml.XMLConstants; -import javax.xml.crypto.MarshalException; -import javax.xml.crypto.dsig.DigestMethod; -import javax.xml.crypto.dsig.Reference; -import javax.xml.crypto.dsig.Transform; -import javax.xml.crypto.dsig.XMLObject; -import javax.xml.crypto.dsig.XMLSignature; -import javax.xml.crypto.dsig.XMLSignatureException; -import javax.xml.crypto.dsig.XMLSignatureFactory; -import javax.xml.crypto.dsig.spec.TransformParameterSpec; - -import org.apache.jcp.xml.dsig.internal.dom.DOMDigestMethod; -import org.apache.jcp.xml.dsig.internal.dom.DOMReference; -import org.apache.poi.openxml4j.opc.PackageNamespaces; -import org.apache.poi.poifs.crypt.dsig.SignatureConfig; -import org.apache.poi.poifs.crypt.dsig.SignatureConfig.SignatureConfigurable; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.util.SuppressForbidden; -import org.w3c.dom.Document; - -/** - * JSR105 Signature Facet base class. - */ -public abstract class SignatureFacet implements SignatureConfigurable { - - private static final POILogger LOG = POILogFactory.getLogger(SignatureFacet.class); - - public static final String XML_NS = XMLConstants.XMLNS_ATTRIBUTE_NS_URI; - public static final String XML_DIGSIG_NS = XMLSignature.XMLNS; - public static final String OO_DIGSIG_NS = PackageNamespaces.DIGITAL_SIGNATURE; - public static final String MS_DIGSIG_NS = "http://schemas.microsoft.com/office/2006/digsig"; - public static final String XADES_132_NS = "http://uri.etsi.org/01903/v1.3.2#"; - public static final String XADES_141_NS = "http://uri.etsi.org/01903/v1.4.1#"; - - protected SignatureConfig signatureConfig; - - public void setSignatureConfig(SignatureConfig signatureConfig) { - this.signatureConfig = signatureConfig; - } - - /** - * This method is being invoked by the XML signature service engine during - * pre-sign phase. Via this method a signature facet implementation can add - * signature facets to an XML signature. - * - * @param document the signature document to be used for imports - * @param references list of reference definitions - * @param objects objects to be signed/included in the signature document - * @throws XMLSignatureException - */ - public void preSign( - Document document - , List references - , List objects - ) throws XMLSignatureException { - // empty - } - - /** - * This method is being invoked by the XML signature service engine during - * the post-sign phase. Via this method a signature facet can extend the XML - * signatures with for example key information. - * - * @param document the signature document to be modified - * @throws MarshalException - */ - public void postSign(Document document) throws MarshalException { - // empty - } - - protected XMLSignatureFactory getSignatureFactory() { - return signatureConfig.getSignatureFactory(); - } - - protected Transform newTransform(String canonicalizationMethod) throws XMLSignatureException { - return newTransform(canonicalizationMethod, null); - } - - protected Transform newTransform(String canonicalizationMethod, TransformParameterSpec paramSpec) - throws XMLSignatureException { - try { - return getSignatureFactory().newTransform(canonicalizationMethod, paramSpec); - } catch (GeneralSecurityException e) { - throw new XMLSignatureException("unknown canonicalization method: "+canonicalizationMethod, e); - } - } - - protected Reference newReference(String uri, List transforms, String type, String id, byte digestValue[]) - throws XMLSignatureException { - return newReference(uri, transforms, type, id, digestValue, signatureConfig); - } - - public static Reference newReference( - String uri - , List transforms - , String type - , String id - , byte digestValue[] - , SignatureConfig signatureConfig) - throws XMLSignatureException { - // the references appear in the package signature or the package object - // so we can use the default digest algorithm - String digestMethodUri = signatureConfig.getDigestMethodUri(); - XMLSignatureFactory sigFac = signatureConfig.getSignatureFactory(); - DigestMethod digestMethod; - try { - digestMethod = sigFac.newDigestMethod(digestMethodUri, null); - } catch (GeneralSecurityException e) { - throw new XMLSignatureException("unknown digest method uri: "+digestMethodUri, e); - } - - Reference reference; - if (digestValue == null) { - reference = sigFac.newReference(uri, digestMethod, transforms, type, id); - } else { - reference = sigFac.newReference(uri, digestMethod, transforms, type, id, digestValue); - } - - brokenJvmWorkaround(reference); - - return reference; - } - - // helper method ... will be removed soon - public static void brokenJvmWorkaround(final Reference reference) { - final DigestMethod digestMethod = reference.getDigestMethod(); - final String digestMethodUri = digestMethod.getAlgorithm(); - - final Provider bcProv = Security.getProvider("BC"); - if (bcProv != null && !DigestMethod.SHA1.equals(digestMethodUri)) { - // workaround for https://bugzilla.redhat.com/show_bug.cgi?id=1155012 - // overwrite standard message digest, if a digest <> SHA1 is used - AccessController.doPrivileged(new PrivilegedAction() { - @Override - @SuppressForbidden("Workaround for a bug, needs access to private JDK members (may fail in Java 9): https://bugzilla.redhat.com/show_bug.cgi?id=1155012") - public Void run() { - try { - Method m = DOMDigestMethod.class.getDeclaredMethod("getMessageDigestAlgorithm"); - m.setAccessible(true); - String mdAlgo = (String)m.invoke(digestMethod); - MessageDigest md = MessageDigest.getInstance(mdAlgo, bcProv); - Field f = DOMReference.class.getDeclaredField("md"); - f.setAccessible(true); - f.set(reference, md); - } catch (Exception e) { - LOG.log(POILogger.WARN, "Can't overwrite message digest (workaround for https://bugzilla.redhat.com/show_bug.cgi?id=1155012)", e); - } - return null; // Void - } - }); - } - } -} \ No newline at end of file diff --git a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/facets/XAdESSignatureFacet.java b/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/facets/XAdESSignatureFacet.java deleted file mode 100644 index a556f1f79..000000000 --- a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/facets/XAdESSignatureFacet.java +++ /dev/null @@ -1,286 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -/* ==================================================================== - This product contains an ASLv2 licensed version of the OOXML signer - package from the eID Applet project - http://code.google.com/p/eid-applet/source/browse/trunk/README.txt - Copyright (C) 2008-2014 FedICT. - ================================================================= */ - -package org.apache.poi.poifs.crypt.dsig.facets; - -import java.security.MessageDigest; -import java.security.cert.CertificateEncodingException; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.TimeZone; - -import javax.xml.crypto.XMLStructure; -import javax.xml.crypto.dom.DOMStructure; -import javax.xml.crypto.dsig.CanonicalizationMethod; -import javax.xml.crypto.dsig.Reference; -import javax.xml.crypto.dsig.Transform; -import javax.xml.crypto.dsig.XMLObject; -import javax.xml.crypto.dsig.XMLSignatureException; - -import org.apache.poi.poifs.crypt.CryptoFunctions; -import org.apache.poi.poifs.crypt.HashAlgorithm; -import org.apache.poi.poifs.crypt.dsig.SignatureConfig; -import org.apache.poi.poifs.crypt.dsig.services.SignaturePolicyService; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlString; -import org.etsi.uri.x01903.v13.AnyType; -import org.etsi.uri.x01903.v13.CertIDListType; -import org.etsi.uri.x01903.v13.CertIDType; -import org.etsi.uri.x01903.v13.ClaimedRolesListType; -import org.etsi.uri.x01903.v13.DataObjectFormatType; -import org.etsi.uri.x01903.v13.DigestAlgAndValueType; -import org.etsi.uri.x01903.v13.IdentifierType; -import org.etsi.uri.x01903.v13.ObjectIdentifierType; -import org.etsi.uri.x01903.v13.QualifyingPropertiesDocument; -import org.etsi.uri.x01903.v13.QualifyingPropertiesType; -import org.etsi.uri.x01903.v13.SigPolicyQualifiersListType; -import org.etsi.uri.x01903.v13.SignaturePolicyIdType; -import org.etsi.uri.x01903.v13.SignaturePolicyIdentifierType; -import org.etsi.uri.x01903.v13.SignedDataObjectPropertiesType; -import org.etsi.uri.x01903.v13.SignedPropertiesType; -import org.etsi.uri.x01903.v13.SignedSignaturePropertiesType; -import org.etsi.uri.x01903.v13.SignerRoleType; -import org.w3.x2000.x09.xmldsig.DigestMethodType; -import org.w3.x2000.x09.xmldsig.X509IssuerSerialType; -import org.w3c.dom.Document; -import org.w3c.dom.Element; - -/** - * XAdES Signature Facet. Implements XAdES v1.4.1 which is compatible with XAdES - * v1.3.2. The implemented XAdES format is XAdES-BES/EPES. It's up to another - * part of the signature service to upgrade the XAdES-BES to a XAdES-X-L. - * - * This implementation has been tested against an implementation that - * participated multiple ETSI XAdES plugtests. - * - * @author Frank Cornelis - * @see XAdES - * - */ -public class XAdESSignatureFacet extends SignatureFacet { - - private static final POILogger LOG = POILogFactory.getLogger(XAdESSignatureFacet.class); - - private static final String XADES_TYPE = "http://uri.etsi.org/01903#SignedProperties"; - - private Map dataObjectFormatMimeTypes = new HashMap(); - - - @Override - public void preSign( - Document document - , List references - , List objects) - throws XMLSignatureException { - LOG.log(POILogger.DEBUG, "preSign"); - - // QualifyingProperties - QualifyingPropertiesDocument qualDoc = QualifyingPropertiesDocument.Factory.newInstance(); - QualifyingPropertiesType qualifyingProperties = qualDoc.addNewQualifyingProperties(); - qualifyingProperties.setTarget("#" + signatureConfig.getPackageSignatureId()); - - // SignedProperties - SignedPropertiesType signedProperties = qualifyingProperties.addNewSignedProperties(); - signedProperties.setId(signatureConfig.getXadesSignatureId()); - - // SignedSignatureProperties - SignedSignaturePropertiesType signedSignatureProperties = signedProperties.addNewSignedSignatureProperties(); - - // SigningTime - Calendar xmlGregorianCalendar = Calendar.getInstance(TimeZone.getTimeZone("Z"), Locale.ROOT); - xmlGregorianCalendar.setTime(signatureConfig.getExecutionTime()); - xmlGregorianCalendar.clear(Calendar.MILLISECOND); - signedSignatureProperties.setSigningTime(xmlGregorianCalendar); - - // SigningCertificate - if (signatureConfig.getSigningCertificateChain() == null - || signatureConfig.getSigningCertificateChain().isEmpty()) { - throw new RuntimeException("no signing certificate chain available"); - } - CertIDListType signingCertificates = signedSignatureProperties.addNewSigningCertificate(); - CertIDType certId = signingCertificates.addNewCert(); - X509Certificate certificate = signatureConfig.getSigningCertificateChain().get(0); - setCertID(certId, signatureConfig, signatureConfig.isXadesIssuerNameNoReverseOrder(), certificate); - - // ClaimedRole - String role = signatureConfig.getXadesRole(); - if (role != null && !role.isEmpty()) { - SignerRoleType signerRole = signedSignatureProperties.addNewSignerRole(); - signedSignatureProperties.setSignerRole(signerRole); - ClaimedRolesListType claimedRolesList = signerRole.addNewClaimedRoles(); - AnyType claimedRole = claimedRolesList.addNewClaimedRole(); - XmlString roleString = XmlString.Factory.newInstance(); - roleString.setStringValue(role); - insertXChild(claimedRole, roleString); - } - - // XAdES-EPES - SignaturePolicyService policyService = signatureConfig.getSignaturePolicyService(); - if (policyService != null) { - SignaturePolicyIdentifierType signaturePolicyIdentifier = - signedSignatureProperties.addNewSignaturePolicyIdentifier(); - - SignaturePolicyIdType signaturePolicyId = signaturePolicyIdentifier.addNewSignaturePolicyId(); - - ObjectIdentifierType objectIdentifier = signaturePolicyId.addNewSigPolicyId(); - objectIdentifier.setDescription(policyService.getSignaturePolicyDescription()); - - IdentifierType identifier = objectIdentifier.addNewIdentifier(); - identifier.setStringValue(policyService.getSignaturePolicyIdentifier()); - - byte[] signaturePolicyDocumentData = policyService.getSignaturePolicyDocument(); - DigestAlgAndValueType sigPolicyHash = signaturePolicyId.addNewSigPolicyHash(); - setDigestAlgAndValue(sigPolicyHash, signaturePolicyDocumentData, signatureConfig.getDigestAlgo()); - - String signaturePolicyDownloadUrl = policyService.getSignaturePolicyDownloadUrl(); - if (null != signaturePolicyDownloadUrl) { - SigPolicyQualifiersListType sigPolicyQualifiers = signaturePolicyId.addNewSigPolicyQualifiers(); - AnyType sigPolicyQualifier = sigPolicyQualifiers.addNewSigPolicyQualifier(); - XmlString spUriElement = XmlString.Factory.newInstance(); - spUriElement.setStringValue(signaturePolicyDownloadUrl); - insertXChild(sigPolicyQualifier, spUriElement); - } - } else if (signatureConfig.isXadesSignaturePolicyImplied()) { - SignaturePolicyIdentifierType signaturePolicyIdentifier = - signedSignatureProperties.addNewSignaturePolicyIdentifier(); - signaturePolicyIdentifier.addNewSignaturePolicyImplied(); - } - - // DataObjectFormat - if (!dataObjectFormatMimeTypes.isEmpty()) { - SignedDataObjectPropertiesType signedDataObjectProperties = - signedProperties.addNewSignedDataObjectProperties(); - - List dataObjectFormats = signedDataObjectProperties - .getDataObjectFormatList(); - for (Map.Entry dataObjectFormatMimeType : this.dataObjectFormatMimeTypes - .entrySet()) { - DataObjectFormatType dataObjectFormat = DataObjectFormatType.Factory.newInstance(); - dataObjectFormat.setObjectReference("#" + dataObjectFormatMimeType.getKey()); - dataObjectFormat.setMimeType(dataObjectFormatMimeType.getValue()); - dataObjectFormats.add(dataObjectFormat); - } - } - - // add XAdES ds:Object - List xadesObjectContent = new ArrayList(); - Element qualDocElSrc = (Element)qualifyingProperties.getDomNode(); - Element qualDocEl = (Element)document.importNode(qualDocElSrc, true); - xadesObjectContent.add(new DOMStructure(qualDocEl)); - XMLObject xadesObject = getSignatureFactory().newXMLObject(xadesObjectContent, null, null, null); - objects.add(xadesObject); - - // add XAdES ds:Reference - List transforms = new ArrayList(); - Transform exclusiveTransform = newTransform(CanonicalizationMethod.INCLUSIVE); - transforms.add(exclusiveTransform); - Reference reference = newReference - ("#"+signatureConfig.getXadesSignatureId(), transforms, XADES_TYPE, null, null); - references.add(reference); - } - - /** - * Gives back the JAXB DigestAlgAndValue data structure. - * - * @param digestAlgAndValue the parent for the new digest element - * @param data the data to be digested - * @param digestAlgo the digest algorithm - */ - protected static void setDigestAlgAndValue( - DigestAlgAndValueType digestAlgAndValue, - byte[] data, - HashAlgorithm digestAlgo) { - DigestMethodType digestMethod = digestAlgAndValue.addNewDigestMethod(); - digestMethod.setAlgorithm(SignatureConfig.getDigestMethodUri(digestAlgo)); - - MessageDigest messageDigest = CryptoFunctions.getMessageDigest(digestAlgo); - byte[] digestValue = messageDigest.digest(data); - digestAlgAndValue.setDigestValue(digestValue); - } - - /** - * Gives back the JAXB CertID data structure. - */ - protected static void setCertID - (CertIDType certId, SignatureConfig signatureConfig, boolean issuerNameNoReverseOrder, X509Certificate certificate) { - X509IssuerSerialType issuerSerial = certId.addNewIssuerSerial(); - String issuerName; - if (issuerNameNoReverseOrder) { - /* - * Make sure the DN is encoded using the same order as present - * within the certificate. This is an Office2010 work-around. - * Should be reverted back. - * - * XXX: not correct according to RFC 4514. - */ - // TODO: check if issuerName is different on getTBSCertificate - // issuerName = PrincipalUtil.getIssuerX509Principal(certificate).getName().replace(",", ", "); - issuerName = certificate.getIssuerDN().getName().replace(",", ", "); - } else { - issuerName = certificate.getIssuerX500Principal().toString(); - } - issuerSerial.setX509IssuerName(issuerName); - issuerSerial.setX509SerialNumber(certificate.getSerialNumber()); - - byte[] encodedCertificate; - try { - encodedCertificate = certificate.getEncoded(); - } catch (CertificateEncodingException e) { - throw new RuntimeException("certificate encoding error: " - + e.getMessage(), e); - } - DigestAlgAndValueType certDigest = certId.addNewCertDigest(); - setDigestAlgAndValue(certDigest, encodedCertificate, signatureConfig.getXadesDigestAlgo()); - } - - /** - * Adds a mime-type for the given ds:Reference (referred via its @URI). This - * information is added via the xades:DataObjectFormat element. - * - * @param dsReferenceUri - * @param mimetype - */ - public void addMimeType(String dsReferenceUri, String mimetype) { - this.dataObjectFormatMimeTypes.put(dsReferenceUri, mimetype); - } - - protected static void insertXChild(XmlObject root, XmlObject child) { - XmlCursor rootCursor = root.newCursor(); - rootCursor.toEndToken(); - XmlCursor childCursor = child.newCursor(); - childCursor.toNextToken(); - childCursor.moveXml(rootCursor); - childCursor.dispose(); - rootCursor.dispose(); - } - -} \ No newline at end of file diff --git a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/facets/XAdESXLSignatureFacet.java b/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/facets/XAdESXLSignatureFacet.java deleted file mode 100644 index e7d17b0b1..000000000 --- a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/facets/XAdESXLSignatureFacet.java +++ /dev/null @@ -1,389 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -/* ==================================================================== - This product contains an ASLv2 licensed version of the OOXML signer - package from the eID Applet project - http://code.google.com/p/eid-applet/source/browse/trunk/README.txt - Copyright (C) 2008-2014 FedICT. - ================================================================= */ - -package org.apache.poi.poifs.crypt.dsig.facets; - -import static org.apache.poi.POIXMLTypeLoader.DEFAULT_XML_OPTIONS; -import static org.apache.poi.poifs.crypt.dsig.facets.XAdESSignatureFacet.insertXChild; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.math.BigInteger; -import java.security.cert.CRLException; -import java.security.cert.CertificateEncodingException; -import java.security.cert.CertificateException; -import java.security.cert.CertificateFactory; -import java.security.cert.X509CRL; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Collections; -import java.util.List; -import java.util.Locale; -import java.util.TimeZone; -import java.util.UUID; - -import javax.xml.crypto.MarshalException; - -import org.apache.poi.poifs.crypt.dsig.services.RevocationData; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.xml.security.c14n.Canonicalizer; -import org.apache.xmlbeans.XmlException; -import org.bouncycastle.asn1.ASN1InputStream; -import org.bouncycastle.asn1.ASN1Integer; -import org.bouncycastle.asn1.ASN1OctetString; -import org.bouncycastle.asn1.DERTaggedObject; -import org.bouncycastle.asn1.ocsp.ResponderID; -import org.bouncycastle.asn1.x500.X500Name; -import org.bouncycastle.asn1.x509.Extension; -import org.bouncycastle.cert.ocsp.BasicOCSPResp; -import org.bouncycastle.cert.ocsp.OCSPResp; -import org.bouncycastle.cert.ocsp.RespID; -import org.etsi.uri.x01903.v13.*; -import org.etsi.uri.x01903.v14.ValidationDataType; -import org.w3.x2000.x09.xmldsig.CanonicalizationMethodType; -import org.w3c.dom.Document; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -/** - * XAdES-X-L v1.4.1 signature facet. This signature facet implementation will - * upgrade a given XAdES-BES/EPES signature to XAdES-X-L. - * - * We don't inherit from XAdESSignatureFacet as we also want to be able to use - * this facet out of the context of a signature creation. This signature facet - * assumes that the signature is already XAdES-BES/EPES compliant. - * - * This implementation has been tested against an implementation that - * participated multiple ETSI XAdES plugtests. - * - * @author Frank Cornelis - * @see XAdESSignatureFacet - */ -public class XAdESXLSignatureFacet extends SignatureFacet { - - private static final POILogger LOG = POILogFactory.getLogger(XAdESXLSignatureFacet.class); - - private final CertificateFactory certificateFactory; - - public XAdESXLSignatureFacet() { - try { - this.certificateFactory = CertificateFactory.getInstance("X.509"); - } catch (CertificateException e) { - throw new RuntimeException("X509 JCA error: " + e.getMessage(), e); - } - } - - @Override - public void postSign(Document document) throws MarshalException { - LOG.log(POILogger.DEBUG, "XAdES-X-L post sign phase"); - - QualifyingPropertiesDocument qualDoc = null; - QualifyingPropertiesType qualProps = null; - - // check for XAdES-BES - NodeList qualNl = document.getElementsByTagNameNS(XADES_132_NS, "QualifyingProperties"); - if (qualNl.getLength() == 1) { - try { - qualDoc = QualifyingPropertiesDocument.Factory.parse(qualNl.item(0), DEFAULT_XML_OPTIONS); - } catch (XmlException e) { - throw new MarshalException(e); - } - qualProps = qualDoc.getQualifyingProperties(); - } else { - throw new MarshalException("no XAdES-BES extension present"); - } - - // create basic XML container structure - UnsignedPropertiesType unsignedProps = qualProps.getUnsignedProperties(); - if (unsignedProps == null) { - unsignedProps = qualProps.addNewUnsignedProperties(); - } - UnsignedSignaturePropertiesType unsignedSigProps = unsignedProps.getUnsignedSignatureProperties(); - if (unsignedSigProps == null) { - unsignedSigProps = unsignedProps.addNewUnsignedSignatureProperties(); - } - - - // create the XAdES-T time-stamp - NodeList nlSigVal = document.getElementsByTagNameNS(XML_DIGSIG_NS, "SignatureValue"); - if (nlSigVal.getLength() != 1) { - throw new IllegalArgumentException("SignatureValue is not set."); - } - - RevocationData tsaRevocationDataXadesT = new RevocationData(); - LOG.log(POILogger.DEBUG, "creating XAdES-T time-stamp"); - XAdESTimeStampType signatureTimeStamp = createXAdESTimeStamp - (Collections.singletonList(nlSigVal.item(0)), tsaRevocationDataXadesT); - - // marshal the XAdES-T extension - unsignedSigProps.addNewSignatureTimeStamp().set(signatureTimeStamp); - - // xadesv141::TimeStampValidationData - if (tsaRevocationDataXadesT.hasRevocationDataEntries()) { - ValidationDataType validationData = createValidationData(tsaRevocationDataXadesT); - insertXChild(unsignedSigProps, validationData); - } - - if (signatureConfig.getRevocationDataService() == null) { - /* - * Without revocation data service we cannot construct the XAdES-C - * extension. - */ - return; - } - - // XAdES-C: complete certificate refs - CompleteCertificateRefsType completeCertificateRefs = - unsignedSigProps.addNewCompleteCertificateRefs(); - - CertIDListType certIdList = completeCertificateRefs.addNewCertRefs(); - /* - * We skip the signing certificate itself according to section - * 4.4.3.2 of the XAdES 1.4.1 specification. - */ - List certChain = signatureConfig.getSigningCertificateChain(); - int chainSize = certChain.size(); - if (chainSize > 1) { - for (X509Certificate cert : certChain.subList(1, chainSize)) { - CertIDType certId = certIdList.addNewCert(); - XAdESSignatureFacet.setCertID(certId, signatureConfig, false, cert); - } - } - - // XAdES-C: complete revocation refs - CompleteRevocationRefsType completeRevocationRefs = - unsignedSigProps.addNewCompleteRevocationRefs(); - RevocationData revocationData = signatureConfig.getRevocationDataService() - .getRevocationData(certChain); - if (revocationData.hasCRLs()) { - CRLRefsType crlRefs = completeRevocationRefs.addNewCRLRefs(); - completeRevocationRefs.setCRLRefs(crlRefs); - - for (byte[] encodedCrl : revocationData.getCRLs()) { - CRLRefType crlRef = crlRefs.addNewCRLRef(); - X509CRL crl; - try { - crl = (X509CRL) this.certificateFactory - .generateCRL(new ByteArrayInputStream(encodedCrl)); - } catch (CRLException e) { - throw new RuntimeException("CRL parse error: " - + e.getMessage(), e); - } - - CRLIdentifierType crlIdentifier = crlRef.addNewCRLIdentifier(); - String issuerName = crl.getIssuerDN().getName().replace(",", ", "); - crlIdentifier.setIssuer(issuerName); - Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Z"), Locale.ROOT); - cal.setTime(crl.getThisUpdate()); - crlIdentifier.setIssueTime(cal); - crlIdentifier.setNumber(getCrlNumber(crl)); - - DigestAlgAndValueType digestAlgAndValue = crlRef.addNewDigestAlgAndValue(); - XAdESSignatureFacet.setDigestAlgAndValue(digestAlgAndValue, encodedCrl, signatureConfig.getDigestAlgo()); - } - } - if (revocationData.hasOCSPs()) { - OCSPRefsType ocspRefs = completeRevocationRefs.addNewOCSPRefs(); - for (byte[] ocsp : revocationData.getOCSPs()) { - try { - OCSPRefType ocspRef = ocspRefs.addNewOCSPRef(); - - DigestAlgAndValueType digestAlgAndValue = ocspRef.addNewDigestAlgAndValue(); - XAdESSignatureFacet.setDigestAlgAndValue(digestAlgAndValue, ocsp, signatureConfig.getDigestAlgo()); - - OCSPIdentifierType ocspIdentifier = ocspRef.addNewOCSPIdentifier(); - - OCSPResp ocspResp = new OCSPResp(ocsp); - - BasicOCSPResp basicOcspResp = (BasicOCSPResp)ocspResp.getResponseObject(); - - Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Z"), Locale.ROOT); - cal.setTime(basicOcspResp.getProducedAt()); - ocspIdentifier.setProducedAt(cal); - - ResponderIDType responderId = ocspIdentifier.addNewResponderID(); - - RespID respId = basicOcspResp.getResponderId(); - ResponderID ocspResponderId = respId.toASN1Primitive(); - DERTaggedObject derTaggedObject = (DERTaggedObject)ocspResponderId.toASN1Primitive(); - if (2 == derTaggedObject.getTagNo()) { - ASN1OctetString keyHashOctetString = (ASN1OctetString)derTaggedObject.getObject(); - byte key[] = keyHashOctetString.getOctets(); - responderId.setByKey(key); - } else { - X500Name name = X500Name.getInstance(derTaggedObject.getObject()); - String nameStr = name.toString(); - responderId.setByName(nameStr); - } - } catch (Exception e) { - throw new RuntimeException("OCSP decoding error: " + e.getMessage(), e); - } - } - } - - // marshal XAdES-C - - // XAdES-X Type 1 timestamp - List timeStampNodesXadesX1 = new ArrayList(); - timeStampNodesXadesX1.add(nlSigVal.item(0)); - timeStampNodesXadesX1.add(signatureTimeStamp.getDomNode()); - timeStampNodesXadesX1.add(completeCertificateRefs.getDomNode()); - timeStampNodesXadesX1.add(completeRevocationRefs.getDomNode()); - - RevocationData tsaRevocationDataXadesX1 = new RevocationData(); - LOG.log(POILogger.DEBUG, "creating XAdES-X time-stamp"); - XAdESTimeStampType timeStampXadesX1 = createXAdESTimeStamp - (timeStampNodesXadesX1, tsaRevocationDataXadesX1); - if (tsaRevocationDataXadesX1.hasRevocationDataEntries()) { - ValidationDataType timeStampXadesX1ValidationData = createValidationData(tsaRevocationDataXadesX1); - insertXChild(unsignedSigProps, timeStampXadesX1ValidationData); - } - - // marshal XAdES-X - unsignedSigProps.addNewSigAndRefsTimeStamp().set(timeStampXadesX1); - - // XAdES-X-L - CertificateValuesType certificateValues = unsignedSigProps.addNewCertificateValues(); - for (X509Certificate certificate : certChain) { - EncapsulatedPKIDataType encapsulatedPKIDataType = certificateValues.addNewEncapsulatedX509Certificate(); - try { - encapsulatedPKIDataType.setByteArrayValue(certificate.getEncoded()); - } catch (CertificateEncodingException e) { - throw new RuntimeException("certificate encoding error: " + e.getMessage(), e); - } - } - - RevocationValuesType revocationValues = unsignedSigProps.addNewRevocationValues(); - createRevocationValues(revocationValues, revocationData); - - // marshal XAdES-X-L - Node n = document.importNode(qualProps.getDomNode(), true); - qualNl.item(0).getParentNode().replaceChild(n, qualNl.item(0)); - } - - public static byte[] getC14nValue(List nodeList, String c14nAlgoId) { - ByteArrayOutputStream c14nValue = new ByteArrayOutputStream(); - try { - for (Node node : nodeList) { - /* - * Re-initialize the c14n else the namespaces will get cached - * and will be missing from the c14n resulting nodes. - */ - Canonicalizer c14n = Canonicalizer.getInstance(c14nAlgoId); - c14nValue.write(c14n.canonicalizeSubtree(node)); - } - } catch (RuntimeException e) { - throw e; - } catch (Exception e) { - throw new RuntimeException("c14n error: " + e.getMessage(), e); - } - return c14nValue.toByteArray(); - } - - private BigInteger getCrlNumber(X509CRL crl) { - byte[] crlNumberExtensionValue = crl.getExtensionValue(Extension.cRLNumber.getId()); - if (null == crlNumberExtensionValue) { - return null; - } - - try { - ASN1InputStream asn1IS1 = null, asn1IS2 = null; - try { - asn1IS1 = new ASN1InputStream(crlNumberExtensionValue); - ASN1OctetString octetString = (ASN1OctetString)asn1IS1.readObject(); - byte[] octets = octetString.getOctets(); - asn1IS2 = new ASN1InputStream(octets); - ASN1Integer integer = (ASN1Integer)asn1IS2.readObject(); - return integer.getPositiveValue(); - } finally { - IOUtils.closeQuietly(asn1IS2); - IOUtils.closeQuietly(asn1IS1); - } - } catch (IOException e) { - throw new RuntimeException("I/O error: " + e.getMessage(), e); - } - } - - private XAdESTimeStampType createXAdESTimeStamp( - List nodeList, - RevocationData revocationData) { - byte[] c14nSignatureValueElement = getC14nValue(nodeList, signatureConfig.getXadesCanonicalizationMethod()); - - return createXAdESTimeStamp(c14nSignatureValueElement, revocationData); - } - - private XAdESTimeStampType createXAdESTimeStamp(byte[] data, RevocationData revocationData) { - // create the time-stamp - byte[] timeStampToken; - try { - timeStampToken = signatureConfig.getTspService().timeStamp(data, revocationData); - } catch (Exception e) { - throw new RuntimeException("error while creating a time-stamp: " - + e.getMessage(), e); - } - - // create a XAdES time-stamp container - XAdESTimeStampType xadesTimeStamp = XAdESTimeStampType.Factory.newInstance(); - xadesTimeStamp.setId("time-stamp-" + UUID.randomUUID().toString()); - CanonicalizationMethodType c14nMethod = xadesTimeStamp.addNewCanonicalizationMethod(); - c14nMethod.setAlgorithm(signatureConfig.getXadesCanonicalizationMethod()); - - // embed the time-stamp - EncapsulatedPKIDataType encapsulatedTimeStamp = xadesTimeStamp.addNewEncapsulatedTimeStamp(); - encapsulatedTimeStamp.setByteArrayValue(timeStampToken); - encapsulatedTimeStamp.setId("time-stamp-token-" + UUID.randomUUID().toString()); - - return xadesTimeStamp; - } - - private ValidationDataType createValidationData( - RevocationData revocationData) { - ValidationDataType validationData = ValidationDataType.Factory.newInstance(); - RevocationValuesType revocationValues = validationData.addNewRevocationValues(); - createRevocationValues(revocationValues, revocationData); - return validationData; - } - - private void createRevocationValues( - RevocationValuesType revocationValues, RevocationData revocationData) { - if (revocationData.hasCRLs()) { - CRLValuesType crlValues = revocationValues.addNewCRLValues(); - for (byte[] crl : revocationData.getCRLs()) { - EncapsulatedPKIDataType encapsulatedCrlValue = crlValues.addNewEncapsulatedCRLValue(); - encapsulatedCrlValue.setByteArrayValue(crl); - } - } - if (revocationData.hasOCSPs()) { - OCSPValuesType ocspValues = revocationValues.addNewOCSPValues(); - for (byte[] ocsp : revocationData.getOCSPs()) { - EncapsulatedPKIDataType encapsulatedOcspValue = ocspValues.addNewEncapsulatedOCSPValue(); - encapsulatedOcspValue.setByteArrayValue(ocsp); - } - } - } -} diff --git a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/services/RelationshipTransformService.java b/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/services/RelationshipTransformService.java deleted file mode 100644 index 55518772f..000000000 --- a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/services/RelationshipTransformService.java +++ /dev/null @@ -1,248 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -/* ==================================================================== - This product contains an ASLv2 licensed version of the OOXML signer - package from the eID Applet project - http://code.google.com/p/eid-applet/source/browse/trunk/README.txt - Copyright (C) 2008-2014 FedICT. - ================================================================= */ - -package org.apache.poi.poifs.crypt.dsig.services; - -import static org.apache.poi.POIXMLTypeLoader.DEFAULT_XML_OPTIONS; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.security.InvalidAlgorithmParameterException; -import java.security.Provider; -import java.security.Security; -import java.security.spec.AlgorithmParameterSpec; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.Iterator; -import java.util.List; - -import javax.xml.crypto.Data; -import javax.xml.crypto.MarshalException; -import javax.xml.crypto.OctetStreamData; -import javax.xml.crypto.XMLCryptoContext; -import javax.xml.crypto.XMLStructure; -import javax.xml.crypto.dom.DOMStructure; -import javax.xml.crypto.dsig.TransformException; -import javax.xml.crypto.dsig.TransformService; -import javax.xml.crypto.dsig.spec.TransformParameterSpec; - -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.util.XmlSort; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlOptions; -import org.openxmlformats.schemas.xpackage.x2006.digitalSignature.CTRelationshipReference; -import org.openxmlformats.schemas.xpackage.x2006.digitalSignature.RelationshipReferenceDocument; -import org.openxmlformats.schemas.xpackage.x2006.relationships.CTRelationship; -import org.openxmlformats.schemas.xpackage.x2006.relationships.CTRelationships; -import org.openxmlformats.schemas.xpackage.x2006.relationships.RelationshipsDocument; -import org.openxmlformats.schemas.xpackage.x2006.relationships.STTargetMode; -import org.w3.x2000.x09.xmldsig.TransformDocument; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.Node; - -/** - * JSR105 implementation of the RelationshipTransform transformation. - * - *

    - * Specs: http://openiso.org/Ecma/376/Part2/12.2.4#26 - *

    - */ -public class RelationshipTransformService extends TransformService { - - public static final String TRANSFORM_URI = "http://schemas.openxmlformats.org/package/2006/RelationshipTransform"; - - private final List sourceIds; - - private static final POILogger LOG = POILogFactory.getLogger(RelationshipTransformService.class); - - /** - * Relationship Transform parameter specification class. - */ - public static class RelationshipTransformParameterSpec implements TransformParameterSpec { - List sourceIds = new ArrayList(); - public void addRelationshipReference(String relationshipId) { - sourceIds.add(relationshipId); - } - public boolean hasSourceIds() { - return !sourceIds.isEmpty(); - } - } - - - public RelationshipTransformService() { - super(); - LOG.log(POILogger.DEBUG, "constructor"); - this.sourceIds = new ArrayList(); - } - - /** - * Register the provider for this TransformService - * - * @see javax.xml.crypto.dsig.TransformService - */ - public static synchronized void registerDsigProvider() { - // the xml signature classes will try to find a special TransformerService, - // which is ofcourse unknown to JCE before ... - final String dsigProvider = "POIXmlDsigProvider"; - if (Security.getProperty(dsigProvider) == null) { - Provider p = new Provider(dsigProvider, 1.0, dsigProvider){ - static final long serialVersionUID = 1L; - }; - p.put("TransformService." + TRANSFORM_URI, RelationshipTransformService.class.getName()); - p.put("TransformService." + TRANSFORM_URI + " MechanismType", "DOM"); - Security.addProvider(p); - } - } - - - @Override - public void init(TransformParameterSpec params) throws InvalidAlgorithmParameterException { - LOG.log(POILogger.DEBUG, "init(params)"); - if (!(params instanceof RelationshipTransformParameterSpec)) { - throw new InvalidAlgorithmParameterException(); - } - RelationshipTransformParameterSpec relParams = (RelationshipTransformParameterSpec) params; - for (String sourceId : relParams.sourceIds) { - this.sourceIds.add(sourceId); - } - } - - @Override - public void init(XMLStructure parent, XMLCryptoContext context) throws InvalidAlgorithmParameterException { - LOG.log(POILogger.DEBUG, "init(parent,context)"); - LOG.log(POILogger.DEBUG, "parent java type: " + parent.getClass().getName()); - DOMStructure domParent = (DOMStructure) parent; - Node parentNode = domParent.getNode(); - - try { - TransformDocument transDoc = TransformDocument.Factory.parse(parentNode, DEFAULT_XML_OPTIONS); - XmlObject xoList[] = transDoc.getTransform().selectChildren(RelationshipReferenceDocument.type.getDocumentElementName()); - if (xoList.length == 0) { - LOG.log(POILogger.WARN, "no RelationshipReference/@SourceId parameters present"); - } - for (XmlObject xo : xoList) { - String sourceId = ((CTRelationshipReference)xo).getSourceId(); - LOG.log(POILogger.DEBUG, "sourceId: ", sourceId); - this.sourceIds.add(sourceId); - } - } catch (XmlException e) { - throw new InvalidAlgorithmParameterException(e); - } - } - - @Override - public void marshalParams(XMLStructure parent, XMLCryptoContext context) throws MarshalException { - LOG.log(POILogger.DEBUG, "marshallParams(parent,context)"); - DOMStructure domParent = (DOMStructure) parent; - Element parentNode = (Element)domParent.getNode(); - // parentNode.setAttributeNS(XML_NS, "xmlns:mdssi", XML_DIGSIG_NS); - Document doc = parentNode.getOwnerDocument(); - - for (String sourceId : this.sourceIds) { - RelationshipReferenceDocument relRef = RelationshipReferenceDocument.Factory.newInstance(); - relRef.addNewRelationshipReference().setSourceId(sourceId); - Node n = relRef.getRelationshipReference().getDomNode(); - n = doc.importNode(n, true); - parentNode.appendChild(n); - } - } - - public AlgorithmParameterSpec getParameterSpec() { - LOG.log(POILogger.DEBUG, "getParameterSpec"); - return null; - } - - public Data transform(Data data, XMLCryptoContext context) throws TransformException { - LOG.log(POILogger.DEBUG, "transform(data,context)"); - LOG.log(POILogger.DEBUG, "data java type: " + data.getClass().getName()); - OctetStreamData octetStreamData = (OctetStreamData) data; - LOG.log(POILogger.DEBUG, "URI: " + octetStreamData.getURI()); - InputStream octetStream = octetStreamData.getOctetStream(); - - RelationshipsDocument relDoc; - try { - relDoc = RelationshipsDocument.Factory.parse(octetStream, DEFAULT_XML_OPTIONS); - } catch (Exception e) { - throw new TransformException(e.getMessage(), e); - } - LOG.log(POILogger.DEBUG, "relationships document", relDoc); - - CTRelationships rels = relDoc.getRelationships(); - List relList = rels.getRelationshipList(); - Iterator relIter = rels.getRelationshipList().iterator(); - while (relIter.hasNext()) { - CTRelationship rel = relIter.next(); - /* - * See: ISO/IEC 29500-2:2008(E) - 13.2.4.24 Relationships Transform - * Algorithm. - */ - if (!this.sourceIds.contains(rel.getId())) { - LOG.log(POILogger.DEBUG, "removing element: " + rel.getId()); - relIter.remove(); - } else { - if (!rel.isSetTargetMode()) { - rel.setTargetMode(STTargetMode.INTERNAL); - } - } - } - - // TODO: remove non element nodes ??? - LOG.log(POILogger.DEBUG, "# Relationship elements", relList.size()); - - XmlSort.sort(rels, new Comparator(){ - public int compare(XmlCursor c1, XmlCursor c2) { - String id1 = ((CTRelationship)c1.getObject()).getId(); - String id2 = ((CTRelationship)c2.getObject()).getId(); - return id1.compareTo(id2); - } - }); - - try { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - XmlOptions xo = new XmlOptions(); - xo.setSaveNoXmlDecl(); - relDoc.save(bos, xo); - return new OctetStreamData(new ByteArrayInputStream(bos.toByteArray())); - } catch (IOException e) { - throw new TransformException(e.getMessage(), e); - } - } - - public Data transform(Data data, XMLCryptoContext context, OutputStream os) throws TransformException { - LOG.log(POILogger.DEBUG, "transform(data,context,os)"); - return null; - } - - public boolean isFeatureSupported(String feature) { - LOG.log(POILogger.DEBUG, "isFeatureSupported(feature)"); - return false; - } -} diff --git a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/services/RevocationData.java b/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/services/RevocationData.java deleted file mode 100644 index 66a78e396..000000000 --- a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/services/RevocationData.java +++ /dev/null @@ -1,132 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -/* ==================================================================== - This product contains an ASLv2 licensed version of the OOXML signer - package from the eID Applet project - http://code.google.com/p/eid-applet/source/browse/trunk/README.txt - Copyright (C) 2008-2014 FedICT. - ================================================================= */ - -package org.apache.poi.poifs.crypt.dsig.services; - -import java.security.cert.CRLException; -import java.security.cert.X509CRL; -import java.util.ArrayList; -import java.util.List; - -/** - * Container class for PKI revocation data. - * - * @author Frank Cornelis - * - */ -public class RevocationData { - - private final List crls; - - private final List ocsps; - - /** - * Default constructor. - */ - public RevocationData() { - this.crls = new ArrayList(); - this.ocsps = new ArrayList(); - } - - /** - * Adds a CRL to this revocation data set. - * - * @param encodedCrl - */ - public void addCRL(byte[] encodedCrl) { - this.crls.add(encodedCrl); - } - - /** - * Adds a CRL to this revocation data set. - * - * @param crl - */ - public void addCRL(X509CRL crl) { - byte[] encodedCrl; - try { - encodedCrl = crl.getEncoded(); - } catch (CRLException e) { - throw new IllegalArgumentException("CRL coding error: " - + e.getMessage(), e); - } - addCRL(encodedCrl); - } - - /** - * Adds an OCSP response to this revocation data set. - * - * @param encodedOcsp - */ - public void addOCSP(byte[] encodedOcsp) { - this.ocsps.add(encodedOcsp); - } - - /** - * Gives back a list of all CRLs. - * - * @return a list of all CRLs - */ - public List getCRLs() { - return this.crls; - } - - /** - * Gives back a list of all OCSP responses. - * - * @return a list of all OCSP response - */ - public List getOCSPs() { - return this.ocsps; - } - - /** - * Returns true if this revocation data set holds OCSP - * responses. - * - * @return true if this revocation data set holds OCSP - * responses. - */ - public boolean hasOCSPs() { - return false == this.ocsps.isEmpty(); - } - - /** - * Returns true if this revocation data set holds CRLs. - * - * @return true if this revocation data set holds CRLs. - */ - public boolean hasCRLs() { - return false == this.crls.isEmpty(); - } - - /** - * Returns true if this revocation data is not empty. - * - * @return true if this revocation data is not empty. - */ - public boolean hasRevocationDataEntries() { - return hasOCSPs() || hasCRLs(); - } -} diff --git a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/services/RevocationDataService.java b/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/services/RevocationDataService.java deleted file mode 100644 index ed5ce2991..000000000 --- a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/services/RevocationDataService.java +++ /dev/null @@ -1,47 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -/* ==================================================================== - This product contains an ASLv2 licensed version of the OOXML signer - package from the eID Applet project - http://code.google.com/p/eid-applet/source/browse/trunk/README.txt - Copyright (C) 2008-2014 FedICT. - ================================================================= */ - -package org.apache.poi.poifs.crypt.dsig.services; - -import java.security.cert.X509Certificate; -import java.util.List; - -/** - * Interface for a service that retrieves revocation data about some given - * certificate chain. - * - * @author Frank Cornelis - * - */ -public interface RevocationDataService { - - /** - * Gives back the revocation data corresponding with the given certificate - * chain. - * - * @param certificateChain the certificate chain - * @return the revocation data corresponding with the given certificate chain. - */ - RevocationData getRevocationData(List certificateChain); -} diff --git a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/services/SignaturePolicyService.java b/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/services/SignaturePolicyService.java deleted file mode 100644 index 56fd9ba23..000000000 --- a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/services/SignaturePolicyService.java +++ /dev/null @@ -1,65 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -/* ==================================================================== - This product contains an ASLv2 licensed version of the OOXML signer - package from the eID Applet project - http://code.google.com/p/eid-applet/source/browse/trunk/README.txt - Copyright (C) 2008-2014 FedICT. - ================================================================= */ - -package org.apache.poi.poifs.crypt.dsig.services; - -/** - * Interface for the signature policy service. - * - * @author Frank Cornelis - * - */ -public interface SignaturePolicyService { - - /** - * Gives back the signature policy identifier URI. - * - * @return the signature policy identifier URI. - */ - String getSignaturePolicyIdentifier(); - - /** - * Gives back the short description of the signature policy or - * null if a description is not available. - * - * @return the description, or null. - */ - String getSignaturePolicyDescription(); - - /** - * Gives back the download URL where the signature policy document can be - * found. Can be null in case such a download location does not - * exist. - * - * @return the download URL, or null. - */ - String getSignaturePolicyDownloadUrl(); - - /** - * Gives back the signature policy document. - * - * @return the bytes of the signature policy document. - */ - byte[] getSignaturePolicyDocument(); -} \ No newline at end of file diff --git a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/services/TSPTimeStampService.java b/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/services/TSPTimeStampService.java deleted file mode 100644 index bc3e74455..000000000 --- a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/services/TSPTimeStampService.java +++ /dev/null @@ -1,261 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -/* ==================================================================== - This product contains an ASLv2 licensed version of the OOXML signer - package from the eID Applet project - http://code.google.com/p/eid-applet/source/browse/trunk/README.txt - Copyright (C) 2008-2014 FedICT. - ================================================================= */ - -package org.apache.poi.poifs.crypt.dsig.services; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.math.BigInteger; -import java.net.HttpURLConnection; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.Proxy; -import java.net.URL; -import java.nio.charset.Charset; -import java.security.MessageDigest; -import java.security.SecureRandom; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.xml.bind.DatatypeConverter; - -import org.apache.poi.poifs.crypt.CryptoFunctions; -import org.apache.poi.poifs.crypt.HashAlgorithm; -import org.apache.poi.poifs.crypt.dsig.SignatureConfig; -import org.apache.poi.util.HexDump; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.bouncycastle.asn1.ASN1ObjectIdentifier; -import org.bouncycastle.asn1.cmp.PKIFailureInfo; -import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; -import org.bouncycastle.asn1.x500.X500Name; -import org.bouncycastle.asn1.x509.X509ObjectIdentifiers; -import org.bouncycastle.cert.X509CertificateHolder; -import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; -import org.bouncycastle.cms.DefaultCMSSignatureAlgorithmNameGenerator; -import org.bouncycastle.cms.SignerId; -import org.bouncycastle.cms.SignerInformationVerifier; -import org.bouncycastle.cms.bc.BcRSASignerInfoVerifierBuilder; -import org.bouncycastle.operator.DefaultDigestAlgorithmIdentifierFinder; -import org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder; -import org.bouncycastle.operator.bc.BcDigestCalculatorProvider; -import org.bouncycastle.tsp.TimeStampRequest; -import org.bouncycastle.tsp.TimeStampRequestGenerator; -import org.bouncycastle.tsp.TimeStampResponse; -import org.bouncycastle.tsp.TimeStampToken; - -/** - * A TSP time-stamp service implementation. - * - * @author Frank Cornelis - * - */ -public class TSPTimeStampService implements TimeStampService { - - private static final POILogger LOG = POILogFactory.getLogger(TSPTimeStampService.class); - - private SignatureConfig signatureConfig; - - /** - * Maps the digest algorithm to corresponding OID value. - */ - public ASN1ObjectIdentifier mapDigestAlgoToOID(HashAlgorithm digestAlgo) { - switch (digestAlgo) { - case sha1: return X509ObjectIdentifiers.id_SHA1; - case sha256: return NISTObjectIdentifiers.id_sha256; - case sha384: return NISTObjectIdentifiers.id_sha384; - case sha512: return NISTObjectIdentifiers.id_sha512; - default: - throw new IllegalArgumentException("unsupported digest algo: " + digestAlgo); - } - } - - @SuppressWarnings("unchecked") - public byte[] timeStamp(byte[] data, RevocationData revocationData) - throws Exception { - // digest the message - MessageDigest messageDigest = CryptoFunctions.getMessageDigest(signatureConfig.getTspDigestAlgo()); - byte[] digest = messageDigest.digest(data); - - // generate the TSP request - BigInteger nonce = new BigInteger(128, new SecureRandom()); - TimeStampRequestGenerator requestGenerator = new TimeStampRequestGenerator(); - requestGenerator.setCertReq(true); - String requestPolicy = signatureConfig.getTspRequestPolicy(); - if (requestPolicy != null) { - requestGenerator.setReqPolicy(new ASN1ObjectIdentifier(requestPolicy)); - } - ASN1ObjectIdentifier digestAlgoOid = mapDigestAlgoToOID(signatureConfig.getTspDigestAlgo()); - TimeStampRequest request = requestGenerator.generate(digestAlgoOid, digest, nonce); - byte[] encodedRequest = request.getEncoded(); - - // create the HTTP POST request - Proxy proxy = Proxy.NO_PROXY; - if (signatureConfig.getProxyUrl() != null) { - URL proxyUrl = new URL(signatureConfig.getProxyUrl()); - String host = proxyUrl.getHost(); - int port = proxyUrl.getPort(); - proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(InetAddress.getByName(host), (port == -1 ? 80 : port))); - } - - HttpURLConnection huc = (HttpURLConnection)new URL(signatureConfig.getTspUrl()).openConnection(proxy); - - if (signatureConfig.getTspUser() != null) { - String userPassword = signatureConfig.getTspUser() + ":" + signatureConfig.getTspPass(); - String encoding = DatatypeConverter.printBase64Binary(userPassword.getBytes(Charset.forName("iso-8859-1"))); - huc.setRequestProperty("Authorization", "Basic " + encoding); - } - - huc.setRequestMethod("POST"); - huc.setConnectTimeout(20000); - huc.setReadTimeout(20000); - huc.setDoOutput(true); // also sets method to POST. - huc.setRequestProperty("User-Agent", signatureConfig.getUserAgent()); - huc.setRequestProperty("Content-Type", signatureConfig.isTspOldProtocol() - ? "application/timestamp-request" - : "application/timestamp-query"); // "; charset=ISO-8859-1"); - - OutputStream hucOut = huc.getOutputStream(); - hucOut.write(encodedRequest); - - // invoke TSP service - huc.connect(); - - int statusCode = huc.getResponseCode(); - if (statusCode != 200) { - LOG.log(POILogger.ERROR, "Error contacting TSP server ", signatureConfig.getTspUrl() + - ", had status code " + statusCode + "/" + huc.getResponseMessage()); - throw new IOException("Error contacting TSP server " + signatureConfig.getTspUrl() + - ", had status code " + statusCode + "/" + huc.getResponseMessage()); - } - - // HTTP input validation - String contentType = huc.getHeaderField("Content-Type"); - if (null == contentType) { - throw new RuntimeException("missing Content-Type header"); - } - - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - IOUtils.copy(huc.getInputStream(), bos); - LOG.log(POILogger.DEBUG, "response content: ", HexDump.dump(bos.toByteArray(), 0, 0)); - - if (!contentType.startsWith(signatureConfig.isTspOldProtocol() - ? "application/timestamp-response" - : "application/timestamp-reply" - )) { - throw new RuntimeException("invalid Content-Type: " + contentType + - // dump the first few bytes - ": " + HexDump.dump(bos.toByteArray(), 0, 0, 200)); - } - - if (bos.size() == 0) { - throw new RuntimeException("Content-Length is zero"); - } - - // TSP response parsing and validation - TimeStampResponse timeStampResponse = new TimeStampResponse(bos.toByteArray()); - timeStampResponse.validate(request); - - if (0 != timeStampResponse.getStatus()) { - LOG.log(POILogger.DEBUG, "status: " + timeStampResponse.getStatus()); - LOG.log(POILogger.DEBUG, "status string: " + timeStampResponse.getStatusString()); - PKIFailureInfo failInfo = timeStampResponse.getFailInfo(); - if (null != failInfo) { - LOG.log(POILogger.DEBUG, "fail info int value: " + failInfo.intValue()); - if (/*PKIFailureInfo.unacceptedPolicy*/(1 << 8) == failInfo.intValue()) { - LOG.log(POILogger.DEBUG, "unaccepted policy"); - } - } - throw new RuntimeException("timestamp response status != 0: " - + timeStampResponse.getStatus()); - } - TimeStampToken timeStampToken = timeStampResponse.getTimeStampToken(); - SignerId signerId = timeStampToken.getSID(); - BigInteger signerCertSerialNumber = signerId.getSerialNumber(); - X500Name signerCertIssuer = signerId.getIssuer(); - LOG.log(POILogger.DEBUG, "signer cert serial number: " + signerCertSerialNumber); - LOG.log(POILogger.DEBUG, "signer cert issuer: " + signerCertIssuer); - - // TSP signer certificates retrieval - Collection certificates = timeStampToken.getCertificates().getMatches(null); - - X509CertificateHolder signerCert = null; - Map certificateMap = new HashMap(); - for (X509CertificateHolder certificate : certificates) { - if (signerCertIssuer.equals(certificate.getIssuer()) - && signerCertSerialNumber.equals(certificate.getSerialNumber())) { - signerCert = certificate; - } - certificateMap.put(certificate.getSubject(), certificate); - } - - // TSP signer cert path building - if (signerCert == null) { - throw new RuntimeException("TSP response token has no signer certificate"); - } - List tspCertificateChain = new ArrayList(); - JcaX509CertificateConverter x509converter = new JcaX509CertificateConverter(); - x509converter.setProvider("BC"); - X509CertificateHolder certificate = signerCert; - do { - LOG.log(POILogger.DEBUG, "adding to certificate chain: " + certificate.getSubject()); - tspCertificateChain.add(x509converter.getCertificate(certificate)); - if (certificate.getSubject().equals(certificate.getIssuer())) { - break; - } - certificate = certificateMap.get(certificate.getIssuer()); - } while (null != certificate); - - // verify TSP signer signature - X509CertificateHolder holder = new X509CertificateHolder(tspCertificateChain.get(0).getEncoded()); - DefaultCMSSignatureAlgorithmNameGenerator nameGen = new DefaultCMSSignatureAlgorithmNameGenerator(); - DefaultSignatureAlgorithmIdentifierFinder sigAlgoFinder = new DefaultSignatureAlgorithmIdentifierFinder(); - DefaultDigestAlgorithmIdentifierFinder hashAlgoFinder = new DefaultDigestAlgorithmIdentifierFinder(); - BcDigestCalculatorProvider calculator = new BcDigestCalculatorProvider(); - BcRSASignerInfoVerifierBuilder verifierBuilder = new BcRSASignerInfoVerifierBuilder(nameGen, sigAlgoFinder, hashAlgoFinder, calculator); - SignerInformationVerifier verifier = verifierBuilder.build(holder); - - timeStampToken.validate(verifier); - - // verify TSP signer certificate - if (signatureConfig.getTspValidator() != null) { - signatureConfig.getTspValidator().validate(tspCertificateChain, revocationData); - } - - LOG.log(POILogger.DEBUG, "time-stamp token time: " - + timeStampToken.getTimeStampInfo().getGenTime()); - - return timeStampToken.getEncoded(); - } - - public void setSignatureConfig(SignatureConfig signatureConfig) { - this.signatureConfig = signatureConfig; - } -} \ No newline at end of file diff --git a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/services/TimeStampService.java b/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/services/TimeStampService.java deleted file mode 100644 index ede39ac35..000000000 --- a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/services/TimeStampService.java +++ /dev/null @@ -1,54 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -/* ==================================================================== - This product contains an ASLv2 licensed version of the OOXML signer - package from the eID Applet project - http://code.google.com/p/eid-applet/source/browse/trunk/README.txt - Copyright (C) 2008-2014 FedICT. - ================================================================= */ - -package org.apache.poi.poifs.crypt.dsig.services; - -import org.apache.poi.poifs.crypt.dsig.SignatureConfig.SignatureConfigurable; - - -/** - * Interface for a time-stamp service. - * - * @author Frank Cornelis - * - */ -public interface TimeStampService extends SignatureConfigurable { - - /** - * Gives back the encoded time-stamp token for the given array of data - * bytes. We assume that the time-stamp token itself contains its full - * certificate chain required for proper validation. - * - * @param data - * the data to be time-stamped. - * @param revocationData - * the optional container that needs to be filled up with the - * revocation data used to validate the TSA certificate chain. - * @return the DER encoded time-stamp token. - * @throws Exception - * in case something went wrong. - */ - byte[] timeStamp(byte[] data, RevocationData revocationData) - throws Exception; -} diff --git a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/services/TimeStampServiceValidator.java b/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/services/TimeStampServiceValidator.java deleted file mode 100644 index 0ea5bbdc1..000000000 --- a/src/ooxml/java/org/apache/poi/poifs/crypt/dsig/services/TimeStampServiceValidator.java +++ /dev/null @@ -1,51 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -/* ==================================================================== - This product contains an ASLv2 licensed version of the OOXML signer - package from the eID Applet project - http://code.google.com/p/eid-applet/source/browse/trunk/README.txt - Copyright (C) 2008-2014 FedICT. - ================================================================= */ - -package org.apache.poi.poifs.crypt.dsig.services; - -import java.security.cert.X509Certificate; -import java.util.List; - -/** - * Interface for trust validator of a TSP. - * - * @author Frank Cornelis - * - */ -public interface TimeStampServiceValidator { - - /** - * Validates the given certificate chain. - * - * @param certificateChain - * @param revocationData - * the optional data container that should be filled with - * revocation data that was used to validate the given - * certificate chain. - * @throws Exception - * in case the certificate chain is invalid. - */ - void validate(List certificateChain, - RevocationData revocationData) throws Exception; -} diff --git a/src/ooxml/java/org/apache/poi/poifs/crypt/temp/AesZipFileZipEntrySource.java b/src/ooxml/java/org/apache/poi/poifs/crypt/temp/AesZipFileZipEntrySource.java deleted file mode 100644 index e9c47b418..000000000 --- a/src/ooxml/java/org/apache/poi/poifs/crypt/temp/AesZipFileZipEntrySource.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.poifs.crypt.temp; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.FilterOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.security.GeneralSecurityException; -import java.security.SecureRandom; -import java.util.Enumeration; -import java.util.zip.ZipEntry; -import java.util.zip.ZipException; -import java.util.zip.ZipFile; -import java.util.zip.ZipInputStream; -import java.util.zip.ZipOutputStream; - -import javax.crypto.Cipher; -import javax.crypto.CipherInputStream; -import javax.crypto.CipherOutputStream; -import javax.crypto.spec.SecretKeySpec; - -import org.apache.poi.openxml4j.util.ZipEntrySource; -import org.apache.poi.poifs.crypt.ChainingMode; -import org.apache.poi.poifs.crypt.CipherAlgorithm; -import org.apache.poi.poifs.crypt.CryptoFunctions; -import org.apache.poi.util.Beta; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.util.TempFile; - -/** - * An example ZipEntrySource that has encrypted temp files to ensure that - * sensitive data is not stored in raw format on disk. - */ -@Beta -public class AesZipFileZipEntrySource implements ZipEntrySource { - private static final POILogger LOG = POILogFactory.getLogger(AesZipFileZipEntrySource.class); - - private final File tmpFile; - private final ZipFile zipFile; - private final Cipher ci; - private boolean closed; - - public AesZipFileZipEntrySource(File tmpFile, Cipher ci) throws IOException { - this.tmpFile = tmpFile; - this.zipFile = new ZipFile(tmpFile); - this.ci = ci; - this.closed = false; - } - - /** - * Note: the file sizes are rounded up to the next cipher block size, - * so don't rely on file sizes of these custom encrypted zip file entries! - */ - @Override - public Enumeration getEntries() { - return zipFile.entries(); - } - - @Override - public InputStream getInputStream(ZipEntry entry) throws IOException { - InputStream is = zipFile.getInputStream(entry); - return new CipherInputStream(is, ci); - } - - @Override - public void close() throws IOException { - if(!closed) { - zipFile.close(); - if (!tmpFile.delete()) { - LOG.log(POILogger.WARN, tmpFile.getAbsolutePath()+" can't be removed (or was already removed."); - }; - } - closed = true; - } - - @Override - public boolean isClosed() { - return closed; - } - - public static AesZipFileZipEntrySource createZipEntrySource(InputStream is) throws IOException, GeneralSecurityException { - // generate session key - SecureRandom sr = new SecureRandom(); - byte[] ivBytes = new byte[16], keyBytes = new byte[16]; - sr.nextBytes(ivBytes); - sr.nextBytes(keyBytes); - final File tmpFile = TempFile.createTempFile("protectedXlsx", ".zip"); - copyToFile(is, tmpFile, CipherAlgorithm.aes128, keyBytes, ivBytes); - IOUtils.closeQuietly(is); - return fileToSource(tmpFile, CipherAlgorithm.aes128, keyBytes, ivBytes); - } - - private static void copyToFile(InputStream is, File tmpFile, CipherAlgorithm cipherAlgorithm, byte keyBytes[], byte ivBytes[]) throws IOException, GeneralSecurityException { - SecretKeySpec skeySpec = new SecretKeySpec(keyBytes, cipherAlgorithm.jceId); - Cipher ciEnc = CryptoFunctions.getCipher(skeySpec, cipherAlgorithm, ChainingMode.cbc, ivBytes, Cipher.ENCRYPT_MODE, "PKCS5Padding"); - - ZipInputStream zis = new ZipInputStream(is); - FileOutputStream fos = new FileOutputStream(tmpFile); - ZipOutputStream zos = new ZipOutputStream(fos); - - ZipEntry ze; - while ((ze = zis.getNextEntry()) != null) { - // the cipher output stream pads the data, therefore we can't reuse the ZipEntry with set sizes - // as those will be validated upon close() - ZipEntry zeNew = new ZipEntry(ze.getName()); - zeNew.setComment(ze.getComment()); - zeNew.setExtra(ze.getExtra()); - zeNew.setTime(ze.getTime()); - // zeNew.setMethod(ze.getMethod()); - zos.putNextEntry(zeNew); - FilterOutputStream fos2 = new FilterOutputStream(zos){ - // don't close underlying ZipOutputStream - @Override - public void close() {} - }; - CipherOutputStream cos = new CipherOutputStream(fos2, ciEnc); - IOUtils.copy(zis, cos); - cos.close(); - fos2.close(); - zos.closeEntry(); - zis.closeEntry(); - } - zos.close(); - fos.close(); - zis.close(); - } - - private static AesZipFileZipEntrySource fileToSource(File tmpFile, CipherAlgorithm cipherAlgorithm, byte keyBytes[], byte ivBytes[]) throws ZipException, IOException { - SecretKeySpec skeySpec = new SecretKeySpec(keyBytes, cipherAlgorithm.jceId); - Cipher ciDec = CryptoFunctions.getCipher(skeySpec, cipherAlgorithm, ChainingMode.cbc, ivBytes, Cipher.DECRYPT_MODE, "PKCS5Padding"); - return new AesZipFileZipEntrySource(tmpFile, ciDec); - } - -} \ No newline at end of file diff --git a/src/ooxml/java/org/apache/poi/poifs/crypt/temp/EncryptedTempData.java b/src/ooxml/java/org/apache/poi/poifs/crypt/temp/EncryptedTempData.java deleted file mode 100644 index 7a3981dc5..000000000 --- a/src/ooxml/java/org/apache/poi/poifs/crypt/temp/EncryptedTempData.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.poifs.crypt.temp; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.security.SecureRandom; - -import javax.crypto.Cipher; -import javax.crypto.CipherInputStream; -import javax.crypto.CipherOutputStream; -import javax.crypto.spec.SecretKeySpec; - -import org.apache.poi.poifs.crypt.ChainingMode; -import org.apache.poi.poifs.crypt.CipherAlgorithm; -import org.apache.poi.poifs.crypt.CryptoFunctions; -import org.apache.poi.util.Beta; -import org.apache.poi.util.Internal; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.util.TempFile; - -/** - * EncryptedTempData can be used to buffer binary data in a secure way, by using encrypted temp files. - */ -@Beta -public class EncryptedTempData { - private static POILogger LOG = POILogFactory.getLogger(EncryptedTempData.class); - - private final static CipherAlgorithm cipherAlgorithm = CipherAlgorithm.aes128; - private final SecretKeySpec skeySpec; - private final byte[] ivBytes; - private final File tempFile; - - public EncryptedTempData() throws IOException { - SecureRandom sr = new SecureRandom(); - ivBytes = new byte[16]; - byte[] keyBytes = new byte[16]; - sr.nextBytes(ivBytes); - sr.nextBytes(keyBytes); - skeySpec = new SecretKeySpec(keyBytes, cipherAlgorithm.jceId); - tempFile = TempFile.createTempFile("poi-temp-data", ".tmp"); - } - - public OutputStream getOutputStream() throws IOException { - Cipher ciEnc = CryptoFunctions.getCipher(skeySpec, cipherAlgorithm, ChainingMode.cbc, ivBytes, Cipher.ENCRYPT_MODE, null); - return new CipherOutputStream(new FileOutputStream(tempFile), ciEnc); - } - - public InputStream getInputStream() throws IOException { - Cipher ciDec = CryptoFunctions.getCipher(skeySpec, cipherAlgorithm, ChainingMode.cbc, ivBytes, Cipher.DECRYPT_MODE, null); - return new CipherInputStream(new FileInputStream(tempFile), ciDec); - } - - public void dispose() { - if (!tempFile.delete()) { - LOG.log(POILogger.WARN, tempFile.getAbsolutePath()+" can't be removed (or was already removed."); - } - } -} diff --git a/src/ooxml/java/org/apache/poi/poifs/crypt/temp/SXSSFWorkbookWithCustomZipEntrySource.java b/src/ooxml/java/org/apache/poi/poifs/crypt/temp/SXSSFWorkbookWithCustomZipEntrySource.java deleted file mode 100644 index 54600684e..000000000 --- a/src/ooxml/java/org/apache/poi/poifs/crypt/temp/SXSSFWorkbookWithCustomZipEntrySource.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.poifs.crypt.temp; - -import java.io.IOException; -import java.io.OutputStream; -import java.security.GeneralSecurityException; - -import org.apache.poi.openxml4j.util.ZipEntrySource; -import org.apache.poi.util.Beta; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.xssf.streaming.SXSSFWorkbook; -import org.apache.poi.xssf.streaming.SheetDataWriter; - -@Beta -public class SXSSFWorkbookWithCustomZipEntrySource extends SXSSFWorkbook { - private static final POILogger LOG = POILogFactory.getLogger(SXSSFWorkbookWithCustomZipEntrySource.class); - - public SXSSFWorkbookWithCustomZipEntrySource() { - super(20); - setCompressTempFiles(true); - } - - @Override - public void write(OutputStream stream) throws IOException { - flushSheets(); - EncryptedTempData tempData = new EncryptedTempData(); - ZipEntrySource source = null; - try { - OutputStream os = tempData.getOutputStream(); - try { - getXSSFWorkbook().write(os); - } finally { - IOUtils.closeQuietly(os); - } - // provide ZipEntrySource to poi which decrypts on the fly - source = AesZipFileZipEntrySource.createZipEntrySource(tempData.getInputStream()); - injectData(source, stream); - } catch (GeneralSecurityException e) { - throw new IOException(e); - } finally { - tempData.dispose(); - IOUtils.closeQuietly(source); - } - } - - @Override - protected SheetDataWriter createSheetDataWriter() throws IOException { - //log values to ensure these values are accessible to subclasses - LOG.log(POILogger.INFO, "isCompressTempFiles: " + isCompressTempFiles()); - LOG.log(POILogger.INFO, "SharedStringSource: " + getSharedStringSource()); - return new SheetDataWriterWithDecorator(); - } -} diff --git a/src/ooxml/java/org/apache/poi/poifs/crypt/temp/SheetDataWriterWithDecorator.java b/src/ooxml/java/org/apache/poi/poifs/crypt/temp/SheetDataWriterWithDecorator.java deleted file mode 100644 index 08163ead9..000000000 --- a/src/ooxml/java/org/apache/poi/poifs/crypt/temp/SheetDataWriterWithDecorator.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.poifs.crypt.temp; - -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.security.SecureRandom; - -import javax.crypto.Cipher; -import javax.crypto.CipherInputStream; -import javax.crypto.CipherOutputStream; -import javax.crypto.spec.SecretKeySpec; - -import org.apache.poi.poifs.crypt.ChainingMode; -import org.apache.poi.poifs.crypt.CipherAlgorithm; -import org.apache.poi.poifs.crypt.CryptoFunctions; -import org.apache.poi.util.Beta; -import org.apache.poi.xssf.streaming.SheetDataWriter; - -@Beta -public class SheetDataWriterWithDecorator extends SheetDataWriter { - final static CipherAlgorithm cipherAlgorithm = CipherAlgorithm.aes128; - SecretKeySpec skeySpec; - byte[] ivBytes; - - public SheetDataWriterWithDecorator() throws IOException { - super(); - } - - void init() { - if(skeySpec == null) { - SecureRandom sr = new SecureRandom(); - ivBytes = new byte[16]; - byte[] keyBytes = new byte[16]; - sr.nextBytes(ivBytes); - sr.nextBytes(keyBytes); - skeySpec = new SecretKeySpec(keyBytes, cipherAlgorithm.jceId); - } - } - - @Override - protected OutputStream decorateOutputStream(FileOutputStream fos) { - init(); - Cipher ciEnc = CryptoFunctions.getCipher(skeySpec, cipherAlgorithm, ChainingMode.cbc, ivBytes, Cipher.ENCRYPT_MODE, "PKCS5Padding"); - return new CipherOutputStream(fos, ciEnc); - } - - @Override - protected InputStream decorateInputStream(FileInputStream fis) { - Cipher ciDec = CryptoFunctions.getCipher(skeySpec, cipherAlgorithm, ChainingMode.cbc, ivBytes, Cipher.DECRYPT_MODE, "PKCS5Padding"); - return new CipherInputStream(fis, ciDec); - } -} diff --git a/src/ooxml/java/org/apache/poi/ss/extractor/EmbeddedData.java b/src/ooxml/java/org/apache/poi/ss/extractor/EmbeddedData.java deleted file mode 100644 index 0e598b317..000000000 --- a/src/ooxml/java/org/apache/poi/ss/extractor/EmbeddedData.java +++ /dev/null @@ -1,104 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.extractor; - -import org.apache.poi.ss.usermodel.Shape; - -/** - * A collection of embedded object informations and content - */ -public class EmbeddedData { - private String filename; - private byte[] embeddedData; - private Shape shape; - private String contentType = "binary/octet-stream"; - - public EmbeddedData(String filename, byte[] embeddedData, String contentType) { - setFilename(filename); - setEmbeddedData(embeddedData); - setContentType(contentType); - } - - /** - * @return the filename - */ - public String getFilename() { - return filename; - } - - /** - * Sets the filename - * - * @param filename the filename - */ - public void setFilename(String filename) { - if (filename == null) { - this.filename = "unknown.bin"; - } else { - this.filename = filename.replaceAll("[^/\\\\]*[/\\\\]", "").trim(); - } - } - - /** - * @return the embedded object byte array - */ - public byte[] getEmbeddedData() { - return embeddedData; - } - - /** - * Sets the embedded object as byte array - * - * @param embeddedData the embedded object byte array - */ - public void setEmbeddedData(byte[] embeddedData) { - this.embeddedData = (embeddedData == null) ? null : embeddedData.clone(); - } - - /** - * @return the shape which links to the embedded object - */ - public Shape getShape() { - return shape; - } - - /** - * Sets the shape which links to the embedded object - * - * @param shape the shape - */ - public void setShape(Shape shape) { - this.shape = shape; - } - - /** - * @return the content-/mime-type of the embedded object, the default (if unknown) is {@code binary/octet-stream} - */ - public String getContentType() { - return contentType; - } - - /** - * Sets the content-/mime-type - * - * @param contentType the content-type - */ - public void setContentType(String contentType) { - this.contentType = contentType; - } -} \ No newline at end of file diff --git a/src/ooxml/java/org/apache/poi/ss/extractor/EmbeddedExtractor.java b/src/ooxml/java/org/apache/poi/ss/extractor/EmbeddedExtractor.java deleted file mode 100644 index b2822a509..000000000 --- a/src/ooxml/java/org/apache/poi/ss/extractor/EmbeddedExtractor.java +++ /dev/null @@ -1,425 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.extractor; - -import static org.apache.poi.util.StringUtil.endsWithIgnoreCase; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; - -import org.apache.poi.hpsf.ClassID; -import org.apache.poi.poifs.filesystem.DirectoryNode; -import org.apache.poi.poifs.filesystem.DocumentInputStream; -import org.apache.poi.poifs.filesystem.Entry; -import org.apache.poi.poifs.filesystem.Ole10Native; -import org.apache.poi.poifs.filesystem.Ole10NativeException; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.ss.usermodel.Drawing; -import org.apache.poi.ss.usermodel.ObjectData; -import org.apache.poi.ss.usermodel.Picture; -import org.apache.poi.ss.usermodel.PictureData; -import org.apache.poi.ss.usermodel.Shape; -import org.apache.poi.ss.usermodel.ShapeContainer; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.util.Beta; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.LocaleUtil; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.xssf.usermodel.XSSFObjectData; - -/** - * This extractor class tries to identify various embedded documents within Excel files - * and provide them via a common interface, i.e. the EmbeddedData instances - */ -@Beta -public class EmbeddedExtractor implements Iterable { - private static final POILogger LOG = POILogFactory.getLogger(EmbeddedExtractor.class); - - // contentType - private static final String CONTENT_TYPE_BYTES = "binary/octet-stream"; - private static final String CONTENT_TYPE_PDF = "application/pdf"; - private static final String CONTENT_TYPE_DOC = "application/msword"; - private static final String CONTENT_TYPE_XLS = "application/vnd.ms-excel"; - - /** - * @return the list of known extractors, if you provide custom extractors, override this method - */ - @Override - public Iterator iterator() { - EmbeddedExtractor[] ee = { - new Ole10Extractor(), new PdfExtractor(), new BiffExtractor(), new OOXMLExtractor(), new FsExtractor() - }; - return Arrays.asList(ee).iterator(); - } - - public EmbeddedData extractOne(DirectoryNode src) throws IOException { - for (EmbeddedExtractor ee : this) { - if (ee.canExtract(src)) { - return ee.extract(src); - } - } - return null; - } - - public EmbeddedData extractOne(Picture src) throws IOException { - for (EmbeddedExtractor ee : this) { - if (ee.canExtract(src)) { - return ee.extract(src); - } - } - return null; - } - - public List extractAll(Sheet sheet) throws IOException { - Drawing patriarch = sheet.getDrawingPatriarch(); - if (null == patriarch){ - return Collections.emptyList(); - } - List embeddings = new ArrayList(); - extractAll(patriarch, embeddings); - return embeddings; - } - - protected void extractAll(ShapeContainer parent, List embeddings) throws IOException { - for (Shape shape : parent) { - EmbeddedData data = null; - if (shape instanceof ObjectData) { - ObjectData od = (ObjectData)shape; - try { - if (od.hasDirectoryEntry()) { - data = extractOne((DirectoryNode)od.getDirectory()); - } else { - String contentType = CONTENT_TYPE_BYTES; - if (od instanceof XSSFObjectData) { - contentType = ((XSSFObjectData)od).getObjectPart().getContentType(); - } - data = new EmbeddedData(od.getFileName(), od.getObjectData(), contentType); - } - } catch (Exception e) { - LOG.log(POILogger.WARN, "Entry not found / readable - ignoring OLE embedding", e); - } - } else if (shape instanceof Picture) { - data = extractOne((Picture)shape); - } else if (shape instanceof ShapeContainer) { - extractAll((ShapeContainer)shape, embeddings); - } - - if (data == null) { - continue; - } - - data.setShape(shape); - String filename = data.getFilename(); - String extension = (filename == null || filename.lastIndexOf('.') == -1) ? ".bin" : filename.substring(filename.lastIndexOf('.')); - - // try to find an alternative name - if (filename == null || "".equals(filename) || filename.startsWith("MBD") || filename.startsWith("Root Entry")) { - filename = shape.getShapeName(); - if (filename != null) { - filename += extension; - } - } - // default to dummy name - if (filename == null || "".equals(filename)) { - filename = "picture_" + embeddings.size() + extension; - } - filename = filename.trim(); - data.setFilename(filename); - - embeddings.add(data); - } - } - - - public boolean canExtract(DirectoryNode source) { - return false; - } - - public boolean canExtract(Picture source) { - return false; - } - - protected EmbeddedData extract(DirectoryNode dn) throws IOException { - assert(canExtract(dn)); - POIFSFileSystem dest = new POIFSFileSystem(); - copyNodes(dn, dest.getRoot()); - // start with a reasonable big size - ByteArrayOutputStream bos = new ByteArrayOutputStream(20000); - dest.writeFilesystem(bos); - dest.close(); - - return new EmbeddedData(dn.getName(), bos.toByteArray(), CONTENT_TYPE_BYTES); - } - - protected EmbeddedData extract(Picture source) throws IOException { - return null; - } - - public static class Ole10Extractor extends EmbeddedExtractor { - @Override - public boolean canExtract(DirectoryNode dn) { - ClassID clsId = dn.getStorageClsid(); - return ClassID.OLE10_PACKAGE.equals(clsId); - } - - @Override - public EmbeddedData extract(DirectoryNode dn) throws IOException { - try { - // TODO: inspect the CompObj record for more details, i.e. the content type - Ole10Native ole10 = Ole10Native.createFromEmbeddedOleObject(dn); - return new EmbeddedData(ole10.getFileName(), ole10.getDataBuffer(), CONTENT_TYPE_BYTES); - } catch (Ole10NativeException e) { - throw new IOException(e); - } - } - } - - static class PdfExtractor extends EmbeddedExtractor { - static ClassID PdfClassID = new ClassID("{B801CA65-A1FC-11D0-85AD-444553540000}"); - @Override - public boolean canExtract(DirectoryNode dn) { - ClassID clsId = dn.getStorageClsid(); - return (PdfClassID.equals(clsId) - || dn.hasEntry("CONTENTS")); - } - - @Override - public EmbeddedData extract(DirectoryNode dn) throws IOException { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - InputStream is = dn.createDocumentInputStream("CONTENTS"); - IOUtils.copy(is, bos); - is.close(); - return new EmbeddedData(dn.getName() + ".pdf", bos.toByteArray(), CONTENT_TYPE_PDF); - } - - @Override - public boolean canExtract(Picture source) { - PictureData pd = source.getPictureData(); - return (pd != null && pd.getPictureType() == Workbook.PICTURE_TYPE_EMF); - } - - /** - * Mac Office encodes embedded objects inside the picture, e.g. PDF is part of an EMF. - * If an embedded stream is inside an EMF picture, this method extracts the payload. - * - * @return the embedded data in an EMF picture or null if none is found - */ - @Override - protected EmbeddedData extract(Picture source) throws IOException { - // check for emf+ embedded pdf (poor mans style :( ) - // Mac Excel 2011 embeds pdf files with this method. - PictureData pd = source.getPictureData(); - if (pd != null && pd.getPictureType() != Workbook.PICTURE_TYPE_EMF) { - return null; - } - - // TODO: investigate if this is just an EMF-hack or if other formats are also embedded in EMF - byte pictureBytes[] = pd.getData(); - int idxStart = indexOf(pictureBytes, 0, "%PDF-".getBytes(LocaleUtil.CHARSET_1252)); - if (idxStart == -1) { - return null; - } - - int idxEnd = indexOf(pictureBytes, idxStart, "%%EOF".getBytes(LocaleUtil.CHARSET_1252)); - if (idxEnd == -1) { - return null; - } - - int pictureBytesLen = idxEnd-idxStart+6; - byte[] pdfBytes = new byte[pictureBytesLen]; - System.arraycopy(pictureBytes, idxStart, pdfBytes, 0, pictureBytesLen); - String filename = source.getShapeName().trim(); - if (!endsWithIgnoreCase(filename, ".pdf")) { - filename += ".pdf"; - } - return new EmbeddedData(filename, pdfBytes, CONTENT_TYPE_PDF); - } - - - } - - static class OOXMLExtractor extends EmbeddedExtractor { - @Override - public boolean canExtract(DirectoryNode dn) { - return dn.hasEntry("package"); - } - - @Override - public EmbeddedData extract(DirectoryNode dn) throws IOException { - - ClassID clsId = dn.getStorageClsid(); - - String contentType, ext; - if (ClassID.WORD2007.equals(clsId)) { - ext = ".docx"; - contentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; - } else if (ClassID.WORD2007_MACRO.equals(clsId)) { - ext = ".docm"; - contentType = "application/vnd.ms-word.document.macroEnabled.12"; - } else if (ClassID.EXCEL2007.equals(clsId) || ClassID.EXCEL2003.equals(clsId) || ClassID.EXCEL2010.equals(clsId)) { - ext = ".xlsx"; - contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; - } else if (ClassID.EXCEL2007_MACRO.equals(clsId)) { - ext = ".xlsm"; - contentType = "application/vnd.ms-excel.sheet.macroEnabled.12"; - } else if (ClassID.EXCEL2007_XLSB.equals(clsId)) { - ext = ".xlsb"; - contentType = "application/vnd.ms-excel.sheet.binary.macroEnabled.12"; - } else if (ClassID.POWERPOINT2007.equals(clsId)) { - ext = ".pptx"; - contentType = "application/vnd.openxmlformats-officedocument.presentationml.presentation"; - } else if (ClassID.POWERPOINT2007_MACRO.equals(clsId)) { - ext = ".ppsm"; - contentType = "application/vnd.ms-powerpoint.slideshow.macroEnabled.12"; - } else { - ext = ".zip"; - contentType = "application/zip"; - } - - DocumentInputStream dis = dn.createDocumentInputStream("package"); - byte data[] = IOUtils.toByteArray(dis); - dis.close(); - - return new EmbeddedData(dn.getName()+ext, data, contentType); - } - } - - static class BiffExtractor extends EmbeddedExtractor { - @Override - public boolean canExtract(DirectoryNode dn) { - return canExtractExcel(dn) || canExtractWord(dn); - } - - protected boolean canExtractExcel(DirectoryNode dn) { - ClassID clsId = dn.getStorageClsid(); - return (ClassID.EXCEL95.equals(clsId) - || ClassID.EXCEL97.equals(clsId) - || dn.hasEntry("Workbook") /*...*/); - } - - protected boolean canExtractWord(DirectoryNode dn) { - ClassID clsId = dn.getStorageClsid(); - return (ClassID.WORD95.equals(clsId) - || ClassID.WORD97.equals(clsId) - || dn.hasEntry("WordDocument")); - } - - @Override - public EmbeddedData extract(DirectoryNode dn) throws IOException { - EmbeddedData ed = super.extract(dn); - if (canExtractExcel(dn)) { - ed.setFilename(dn.getName() + ".xls"); - ed.setContentType(CONTENT_TYPE_XLS); - } else if (canExtractWord(dn)) { - ed.setFilename(dn.getName() + ".doc"); - ed.setContentType(CONTENT_TYPE_DOC); - } - - return ed; - } - } - - static class FsExtractor extends EmbeddedExtractor { - @Override - public boolean canExtract(DirectoryNode dn) { - return true; - } - @Override - public EmbeddedData extract(DirectoryNode dn) throws IOException { - EmbeddedData ed = super.extract(dn); - ed.setFilename(dn.getName() + ".ole"); - // TODO: read the content type from CombObj stream - return ed; - } - } - - protected static void copyNodes(DirectoryNode src, DirectoryNode dest) throws IOException { - for (Entry e : src) { - if (e instanceof DirectoryNode) { - DirectoryNode srcDir = (DirectoryNode)e; - DirectoryNode destDir = (DirectoryNode)dest.createDirectory(srcDir.getName()); - destDir.setStorageClsid(srcDir.getStorageClsid()); - copyNodes(srcDir, destDir); - } else { - InputStream is = src.createDocumentInputStream(e); - try { - dest.createDocument(e.getName(), is); - } finally { - is.close(); - } - } - } - } - - - - /** - * Knuth-Morris-Pratt Algorithm for Pattern Matching - * Finds the first occurrence of the pattern in the text. - */ - private static int indexOf(byte[] data, int offset, byte[] pattern) { - int[] failure = computeFailure(pattern); - - int j = 0; - if (data.length == 0) { - return -1; - } - - for (int i = offset; i < data.length; i++) { - while (j > 0 && pattern[j] != data[i]) { - j = failure[j - 1]; - } - if (pattern[j] == data[i]) { j++; } - if (j == pattern.length) { - return i - pattern.length + 1; - } - } - return -1; - } - - /** - * Computes the failure function using a boot-strapping process, - * where the pattern is matched against itself. - */ - private static int[] computeFailure(byte[] pattern) { - int[] failure = new int[pattern.length]; - - int j = 0; - for (int i = 1; i < pattern.length; i++) { - while (j > 0 && pattern[j] != pattern[i]) { - j = failure[j - 1]; - } - if (pattern[j] == pattern[i]) { - j++; - } - failure[i] = j; - } - - return failure; - } - - -} diff --git a/src/ooxml/java/org/apache/poi/ss/usermodel/WorkbookFactory.java b/src/ooxml/java/org/apache/poi/ss/usermodel/WorkbookFactory.java deleted file mode 100644 index 312642ffe..000000000 --- a/src/ooxml/java/org/apache/poi/ss/usermodel/WorkbookFactory.java +++ /dev/null @@ -1,282 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.usermodel; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.PushbackInputStream; - -import org.apache.poi.EmptyFileException; -import org.apache.poi.EncryptedDocumentException; -import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackageAccess; -import org.apache.poi.poifs.crypt.Decryptor; -import org.apache.poi.poifs.filesystem.DirectoryNode; -import org.apache.poi.poifs.filesystem.DocumentFactoryHelper; -import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; -import org.apache.poi.poifs.filesystem.OfficeXmlFileException; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.util.IOUtils; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -/** - * Factory for creating the appropriate kind of Workbook - * (be it {@link HSSFWorkbook} or {@link XSSFWorkbook}), - * by auto-detecting from the supplied input. - */ -public class WorkbookFactory { - /** - * Creates a HSSFWorkbook from the given POIFSFileSystem - *

    Note that in order to properly release resources the - * Workbook should be closed after use. - */ - public static Workbook create(POIFSFileSystem fs) throws IOException { - return new HSSFWorkbook(fs); - } - - /** - * Creates a HSSFWorkbook from the given NPOIFSFileSystem - *

    Note that in order to properly release resources the - * Workbook should be closed after use. - */ - public static Workbook create(NPOIFSFileSystem fs) throws IOException { - try { - return create(fs, null); - } catch (InvalidFormatException e) { - // Special case of OOXML-in-POIFS which is broken - throw new IOException(e); - } - } - - /** - * Creates a Workbook from the given NPOIFSFileSystem, which may - * be password protected - * - * @param fs The {@link NPOIFSFileSystem} to read the document from - * @param password The password that should be used or null if no password is necessary. - * - * @return The created Workbook - * - * @throws IOException if an error occurs while reading the data - * @throws InvalidFormatException if the contents of the file cannot be parsed into a {@link Workbook} - */ - private static Workbook create(final NPOIFSFileSystem fs, String password) throws IOException, InvalidFormatException { - DirectoryNode root = fs.getRoot(); - - // Encrypted OOXML files go inside OLE2 containers, is this one? - if (root.hasEntry(Decryptor.DEFAULT_POIFS_ENTRY)) { - InputStream stream = DocumentFactoryHelper.getDecryptedStream(fs, password); - - OPCPackage pkg = OPCPackage.open(stream); - return create(pkg); - } - - // If we get here, it isn't an encrypted XLSX file - // So, treat it as a regular HSSF XLS one - if (password != null) { - Biff8EncryptionKey.setCurrentUserPassword(password); - } - try { - return new HSSFWorkbook(root, true); - } finally { - Biff8EncryptionKey.setCurrentUserPassword(null); - } - } - - /** - * Creates a XSSFWorkbook from the given OOXML Package - * - *

    Note that in order to properly release resources the - * Workbook should be closed after use.

    - * - * @param pkg The {@link OPCPackage} opened for reading data. - * - * @return The created Workbook - * - * @throws IOException if an error occurs while reading the data - */ - public static Workbook create(OPCPackage pkg) throws IOException { - return new XSSFWorkbook(pkg); - } - - /** - * Creates the appropriate HSSFWorkbook / XSSFWorkbook from - * the given InputStream. - * - *

    Your input stream MUST either support mark/reset, or - * be wrapped as a {@link PushbackInputStream}! Note that - * using an {@link InputStream} has a higher memory footprint - * than using a {@link File}.

    - * - *

    Note that in order to properly release resources the - * Workbook should be closed after use. Note also that loading - * from an InputStream requires more memory than loading - * from a File, so prefer {@link #create(File)} where possible. - * - * @param inp The {@link InputStream} to read data from. - * - * @return The created Workbook - * - * @throws IOException if an error occurs while reading the data - * @throws InvalidFormatException if the contents of the file cannot be parsed into a {@link Workbook} - * @throws EncryptedDocumentException If the workbook given is password protected - */ - public static Workbook create(InputStream inp) throws IOException, InvalidFormatException, EncryptedDocumentException { - return create(inp, null); - } - - /** - * Creates the appropriate HSSFWorkbook / XSSFWorkbook from - * the given InputStream, which may be password protected. - *

    Your input stream MUST either support mark/reset, or - * be wrapped as a {@link PushbackInputStream}! Note that - * using an {@link InputStream} has a higher memory footprint - * than using a {@link File}.

    - * - *

    Note that in order to properly release resources the - * Workbook should be closed after use. Note also that loading - * from an InputStream requires more memory than loading - * from a File, so prefer {@link #create(File)} where possible.

    - * - * @param inp The {@link InputStream} to read data from. - * @param password The password that should be used or null if no password is necessary. - * - * @return The created Workbook - * - * @throws IOException if an error occurs while reading the data - * @throws InvalidFormatException if the contents of the file cannot be parsed into a {@link Workbook} - * @throws EncryptedDocumentException If the wrong password is given for a protected file - * @throws EmptyFileException If an empty stream is given - */ - public static Workbook create(InputStream inp, String password) throws IOException, InvalidFormatException, EncryptedDocumentException { - // If clearly doesn't do mark/reset, wrap up - if (! inp.markSupported()) { - inp = new PushbackInputStream(inp, 8); - } - - // Ensure that there is at least some data there - byte[] header8 = IOUtils.peekFirst8Bytes(inp); - - // Try to create - if (NPOIFSFileSystem.hasPOIFSHeader(header8)) { - NPOIFSFileSystem fs = new NPOIFSFileSystem(inp); - return create(fs, password); - } - if (DocumentFactoryHelper.hasOOXMLHeader(inp)) { - return new XSSFWorkbook(OPCPackage.open(inp)); - } - throw new InvalidFormatException("Your InputStream was neither an OLE2 stream, nor an OOXML stream"); - } - - /** - * Creates the appropriate HSSFWorkbook / XSSFWorkbook from - * the given File, which must exist and be readable. - *

    Note that in order to properly release resources the - * Workbook should be closed after use. - * - * @param file The file to read data from. - * - * @return The created Workbook - * - * @throws IOException if an error occurs while reading the data - * @throws InvalidFormatException if the contents of the file cannot be parsed into a {@link Workbook} - * @throws EncryptedDocumentException If the workbook given is password protected - */ - public static Workbook create(File file) throws IOException, InvalidFormatException, EncryptedDocumentException { - return create(file, null); - } - - /** - * Creates the appropriate HSSFWorkbook / XSSFWorkbook from - * the given File, which must exist and be readable, and - * may be password protected - *

    Note that in order to properly release resources the - * Workbook should be closed after use. - * - * @param file The file to read data from. - * @param password The password that should be used or null if no password is necessary. - * - * @return The created Workbook - * - * @throws IOException if an error occurs while reading the data - * @throws InvalidFormatException if the contents of the file cannot be parsed into a {@link Workbook} - * @throws EncryptedDocumentException If the wrong password is given for a protected file - * @throws EmptyFileException If an empty stream is given - */ - public static Workbook create(File file, String password) throws IOException, InvalidFormatException, EncryptedDocumentException { - return create(file, password, false); - } - - /** - * Creates the appropriate HSSFWorkbook / XSSFWorkbook from - * the given File, which must exist and be readable, and - * may be password protected - *

    Note that in order to properly release resources the - * Workbook should be closed after use. - * - * @param file The file to read data from. - * @param password The password that should be used or null if no password is necessary. - * @param readOnly If the Workbook should be opened in read-only mode to avoid writing back - * changes when the document is closed. - * - * @return The created Workbook - * - * @throws IOException if an error occurs while reading the data - * @throws InvalidFormatException if the contents of the file cannot be parsed into a {@link Workbook} - * @throws EncryptedDocumentException If the wrong password is given for a protected file - * @throws EmptyFileException If an empty stream is given - */ - public static Workbook create(File file, String password, boolean readOnly) throws IOException, InvalidFormatException, EncryptedDocumentException { - if (! file.exists()) { - throw new FileNotFoundException(file.toString()); - } - - try { - NPOIFSFileSystem fs = new NPOIFSFileSystem(file, readOnly); - try { - return create(fs, password); - } catch (RuntimeException e) { - // ensure that the file-handle is closed again - IOUtils.closeQuietly(fs); - throw e; - } - } catch(OfficeXmlFileException e) { - // opening as .xls failed => try opening as .xlsx - OPCPackage pkg = OPCPackage.open(file, readOnly ? PackageAccess.READ : PackageAccess.READ_WRITE); // NOSONAR - try { - return new XSSFWorkbook(pkg); - } catch (Exception ioe) { - // ensure that file handles are closed - use revert() to not re-write the file - pkg.revert(); - // do not pkg.close(); - - if (ioe instanceof IOException) { - throw (IOException)ioe; - } else if (ioe instanceof RuntimeException) { - throw (RuntimeException)ioe; - } else { - throw new IOException(ioe); - } - } - } - } -} diff --git a/src/ooxml/java/org/apache/poi/util/DocumentHelper.java b/src/ooxml/java/org/apache/poi/util/DocumentHelper.java deleted file mode 100644 index f86e60fd9..000000000 --- a/src/ooxml/java/org/apache/poi/util/DocumentHelper.java +++ /dev/null @@ -1,178 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.util; - -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.Method; - -import javax.xml.XMLConstants; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.stream.events.Namespace; - -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.xml.sax.ErrorHandler; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; -import org.xml.sax.SAXParseException; - -public final class DocumentHelper { - private static POILogger logger = POILogFactory.getLogger(DocumentHelper.class); - - private DocumentHelper() {} - - private static class DocHelperErrorHandler implements ErrorHandler { - - public void warning(SAXParseException exception) throws SAXException { - printError(POILogger.WARN, exception); - } - - public void error(SAXParseException exception) throws SAXException { - printError(POILogger.ERROR, exception); - } - - public void fatalError(SAXParseException exception) throws SAXException { - printError(POILogger.FATAL, exception); - throw exception; - } - - /** Prints the error message. */ - private void printError(int type, SAXParseException ex) { - StringBuilder sb = new StringBuilder(); - - String systemId = ex.getSystemId(); - if (systemId != null) { - int index = systemId.lastIndexOf('/'); - if (index != -1) - systemId = systemId.substring(index + 1); - sb.append(systemId); - } - sb.append(':'); - sb.append(ex.getLineNumber()); - sb.append(':'); - sb.append(ex.getColumnNumber()); - sb.append(": "); - sb.append(ex.getMessage()); - - logger.log(type, sb.toString(), ex); - } - } - - /** - * Creates a new document builder, with sensible defaults - * - * @throws IllegalStateException If creating the DocumentBuilder fails, e.g. - * due to {@link ParserConfigurationException}. - */ - public static synchronized DocumentBuilder newDocumentBuilder() { - try { - DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); - documentBuilder.setEntityResolver(SAXHelper.IGNORING_ENTITY_RESOLVER); - documentBuilder.setErrorHandler(new DocHelperErrorHandler()); - return documentBuilder; - } catch (ParserConfigurationException e) { - throw new IllegalStateException("cannot create a DocumentBuilder", e); - } - } - - private static final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); - static { - documentBuilderFactory.setNamespaceAware(true); - documentBuilderFactory.setValidating(false); - trySetSAXFeature(documentBuilderFactory, XMLConstants.FEATURE_SECURE_PROCESSING, true); - trySetXercesSecurityManager(documentBuilderFactory); - } - - private static void trySetSAXFeature(DocumentBuilderFactory dbf, String feature, boolean enabled) { - try { - dbf.setFeature(feature, enabled); - } catch (Exception e) { - logger.log(POILogger.WARN, "SAX Feature unsupported", feature, e); - } catch (AbstractMethodError ame) { - logger.log(POILogger.WARN, "Cannot set SAX feature because outdated XML parser in classpath", feature, ame); - } - } - - private static void trySetXercesSecurityManager(DocumentBuilderFactory dbf) { - // Try built-in JVM one first, standalone if not - for (String securityManagerClassName : new String[] { - "com.sun.org.apache.xerces.internal.util.SecurityManager", - "org.apache.xerces.util.SecurityManager" - }) { - try { - Object mgr = Class.forName(securityManagerClassName).newInstance(); - Method setLimit = mgr.getClass().getMethod("setEntityExpansionLimit", Integer.TYPE); - setLimit.invoke(mgr, 4096); - dbf.setAttribute("http://apache.org/xml/properties/security-manager", mgr); - // Stop once one can be setup without error - return; - } catch (Throwable e) { // NOSONAR - also catch things like NoClassDefError here - logger.log(POILogger.WARN, "SAX Security Manager could not be setup", e); - } - } - } - - /** - * Parses the given stream via the default (sensible) - * DocumentBuilder - * @param inp Stream to read the XML data from - * @return the parsed Document - */ - public static Document readDocument(InputStream inp) throws IOException, SAXException { - return newDocumentBuilder().parse(inp); - } - - /** - * Parses the given stream via the default (sensible) - * DocumentBuilder - * @param inp sax source to read the XML data from - * @return the parsed Document - */ - public static Document readDocument(InputSource inp) throws IOException, SAXException { - return newDocumentBuilder().parse(inp); - } - - // must only be used to create empty documents, do not use it for parsing! - private static final DocumentBuilder documentBuilderSingleton = newDocumentBuilder(); - - /** - * Creates a new DOM Document - */ - public static synchronized Document createDocument() { - return documentBuilderSingleton.newDocument(); - } - - /** - * Adds a namespace declaration attribute to the given element. - */ - public static void addNamespaceDeclaration(Element element, String namespacePrefix, String namespaceURI) { - element.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, - XMLConstants.XMLNS_ATTRIBUTE + ':' + namespacePrefix, - namespaceURI); - } - - /** - * Adds a namespace declaration attribute to the given element. - */ - public static void addNamespaceDeclaration(Element element, Namespace namespace) { - addNamespaceDeclaration(element, namespace.getPrefix(), namespace.getNamespaceURI()); - } -} diff --git a/src/ooxml/java/org/apache/poi/util/IdentifierManager.java b/src/ooxml/java/org/apache/poi/util/IdentifierManager.java deleted file mode 100644 index 88822351f..000000000 --- a/src/ooxml/java/org/apache/poi/util/IdentifierManager.java +++ /dev/null @@ -1,266 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.util; - -import java.util.LinkedList; -import java.util.ListIterator; - -/** - *

    - * 24.08.2009
    - *

    - * - * @author Stefan Stern
    - */ - -public class IdentifierManager { - - public static final long MAX_ID = Long.MAX_VALUE - 1; - - public static final long MIN_ID = 0L; - - /** - * - */ - private final long upperbound; - - /** - * - */ - private final long lowerbound; - - /** - * List of segments of available identifiers - */ - private LinkedList segments; - - /** - * @param lowerbound the lower limit of the id-range to manage. Must be greater than or equal to {@link #MIN_ID}. - * @param upperbound the upper limit of the id-range to manage. Must be less then or equal {@link #MAX_ID}. - */ - public IdentifierManager(long lowerbound, long upperbound) { - if (lowerbound > upperbound) { - throw new IllegalArgumentException("lowerbound must not be greater than upperbound, had " + lowerbound + " and " + upperbound); - } - else if (lowerbound < MIN_ID) { - String message = "lowerbound must be greater than or equal to " + Long.toString(MIN_ID); - throw new IllegalArgumentException(message); - } - else if (upperbound > MAX_ID) { - /* - * while MAX_ID is Long.MAX_VALUE, this check is pointless. But if - * someone subclasses / tweaks the limits, this check is fine. - */ - throw new IllegalArgumentException("upperbound must be less than or equal to " + Long.toString(MAX_ID) + " but had " + upperbound); - } - this.lowerbound = lowerbound; - this.upperbound = upperbound; - this.segments = new LinkedList(); - segments.add(new Segment(lowerbound, upperbound)); - } - - public long reserve(long id) { - if (id < lowerbound || id > upperbound) { - throw new IllegalArgumentException("Value for parameter 'id' was out of bounds, had " + id + ", but should be within [" + lowerbound + ":" + upperbound + "]"); - } - verifyIdentifiersLeft(); - - if (id == upperbound) { - Segment lastSegment = segments.getLast(); - if (lastSegment.end == upperbound) { - lastSegment.end = upperbound - 1; - if (lastSegment.start > lastSegment.end) { - segments.removeLast(); - } - return id; - } - return reserveNew(); - } - - if (id == lowerbound) { - Segment firstSegment = segments.getFirst(); - if (firstSegment.start == lowerbound) { - firstSegment.start = lowerbound + 1; - if (firstSegment.end < firstSegment.start) { - segments.removeFirst(); - } - return id; - } - return reserveNew(); - } - - ListIterator iter = segments.listIterator(); - while (iter.hasNext()) { - Segment segment = iter.next(); - if (segment.end < id) { - continue; - } - else if (segment.start > id) { - break; - } - else if (segment.start == id) { - segment.start = id + 1; - if (segment.end < segment.start) { - iter.remove(); - } - return id; - } - else if (segment.end == id) { - segment.end = id - 1; - if (segment.start > segment.end) { - iter.remove(); - } - return id; - } - else { - iter.add(new Segment(id + 1, segment.end)); - segment.end = id - 1; - return id; - } - } - return reserveNew(); - } - - /** - * @return a new identifier. - * @throws IllegalStateException if no more identifiers are available, then an Exception is raised. - */ - public long reserveNew() { - verifyIdentifiersLeft(); - Segment segment = segments.getFirst(); - long result = segment.start; - segment.start += 1; - if (segment.start > segment.end) { - segments.removeFirst(); - } - return result; - } - - /** - * @param id - * the identifier to release. Must be greater than or equal to - * {@link #lowerbound} and must be less than or equal to {@link #upperbound} - * @return true, if the identifier was reserved and has been successfully - * released, false, if the identifier was not reserved. - */ - public boolean release(long id) { - if (id < lowerbound || id > upperbound) { - throw new IllegalArgumentException("Value for parameter 'id' was out of bounds, had " + id + ", but should be within [" + lowerbound + ":" + upperbound + "]"); - } - - if (id == upperbound) { - Segment lastSegment = segments.getLast(); - if (lastSegment.end == upperbound - 1) { - lastSegment.end = upperbound; - return true; - } else if (lastSegment.end == upperbound) { - return false; - } else { - segments.add(new Segment(upperbound, upperbound)); - return true; - } - } - - if (id == lowerbound) { - Segment firstSegment = segments.getFirst(); - if (firstSegment.start == lowerbound + 1) { - firstSegment.start = lowerbound; - return true; - } else if (firstSegment.start == lowerbound) { - return false; - } else { - segments.addFirst(new Segment(lowerbound, lowerbound)); - return true; - } - } - - long higher = id + 1; - long lower = id - 1; - ListIterator iter = segments.listIterator(); - - while (iter.hasNext()) { - Segment segment = iter.next(); - if (segment.end < lower) { - continue; - } - if (segment.start > higher) { - iter.previous(); - iter.add(new Segment(id, id)); - return true; - } - if (segment.start == higher) { - segment.start = id; - return true; - } - else if (segment.end == lower) { - segment.end = id; - /* check if releasing this elements glues two segments into one */ - if (iter.hasNext()) { - Segment next = iter.next(); - if (next.start == segment.end + 1) { - segment.end = next.end; - iter.remove(); - } - } - return true; - } - else { - /* id was not reserved, return false */ - break; - } - } - return false; - } - - public long getRemainingIdentifiers() { - long result = 0; - for (Segment segment : segments) { - result = result - segment.start; - result = result + segment.end + 1; - } - return result; - } - - /** - * - */ - private void verifyIdentifiersLeft() { - if (segments.isEmpty()) { - throw new IllegalStateException("No identifiers left"); - } - } - - private static class Segment { - - public Segment(long start, long end) { - this.start = start; - this.end = end; - } - - public long start; - public long end; - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - public String toString() { - return "[" + start + "; " + end + "]"; - } - } -} diff --git a/src/ooxml/java/org/apache/poi/util/OOXMLLite.java b/src/ooxml/java/org/apache/poi/util/OOXMLLite.java deleted file mode 100644 index d537a9d3a..000000000 --- a/src/ooxml/java/org/apache/poi/util/OOXMLLite.java +++ /dev/null @@ -1,303 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.util; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.net.URL; -import java.security.AccessController; -import java.security.CodeSource; -import java.security.PrivilegedAction; -import java.security.ProtectionDomain; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Vector; -import java.util.jar.JarEntry; -import java.util.jar.JarFile; -import java.util.regex.Pattern; - -import junit.framework.TestCase; - -import org.junit.Test; -import org.junit.internal.TextListener; -import org.junit.runner.JUnitCore; -import org.junit.runner.Result; - -/** - * Build a 'lite' version of the ooxml-schemas.jar - * - * @author Yegor Kozlov - */ -public final class OOXMLLite { - - /** - * Destination directory to copy filtered classes - */ - private File _destDest; - - /** - * Directory with the compiled ooxml tests - */ - private File _testDir; - - /** - * Reference to the ooxml-schemas.jar - */ - private File _ooxmlJar; - - - OOXMLLite(String dest, String test, String ooxmlJar) { - _destDest = new File(dest); - _testDir = new File(test); - _ooxmlJar = new File(ooxmlJar); - } - - public static void main(String[] args) throws IOException, ClassNotFoundException { - - String dest = null, test = null, ooxml = null; - - for (int i = 0; i < args.length; i++) { - if (args[i].equals("-dest")) dest = args[++i]; - else if (args[i].equals("-test")) test = args[++i]; - else if (args[i].equals("-ooxml")) ooxml = args[++i]; - } - OOXMLLite builder = new OOXMLLite(dest, test, ooxml); - builder.build(); - } - - void build() throws IOException, ClassNotFoundException { - List> lst = new ArrayList>(); - //collect unit tests - String exclude = StringUtil.join("|", - "BaseTestXWorkbook", - "BaseTestXSheet", - "BaseTestXRow", - "BaseTestXCell", - "BaseTestXSSFPivotTable", - "TestSXSSFWorkbook\\$\\d", - "TestUnfixedBugs", - "MemoryUsage", - "TestDataProvider", - "TestDataSamples", - "All.+Tests", - "ZipFileAssert", - "AesZipFileZipEntrySource", - "TempFileRecordingSXSSFWorkbookWithCustomZipEntrySource", - "PkiTestUtils", - "TestCellFormatPart\\$\\d", - "TestSignatureInfo\\$\\d", - "TestCertificateEncryption\\$CertData", - "TestPOIXMLDocument\\$OPCParser", - "TestPOIXMLDocument\\$TestFactory", - "TestXSLFTextParagraph\\$DrawTextParagraphProxy", - "TestXSSFExportToXML\\$\\d", - "TestXSSFExportToXML\\$DummyEntityResolver", - "TestFormulaEvaluatorOnXSSF\\$Result", - "TestFormulaEvaluatorOnXSSF\\$SS", - "TestMultiSheetFormulaEvaluatorOnXSSF\\$Result", - "TestMultiSheetFormulaEvaluatorOnXSSF\\$SS", - "TestXSSFBugs\\$\\d" - ); - System.out.println("Collecting unit tests from " + _testDir); - collectTests(_testDir, _testDir, lst, ".+.class$", ".+(" + exclude + ").class"); - System.out.println("Found " + lst.size() + " classes"); - - //run tests - JUnitCore jUnitCore = new JUnitCore(); - jUnitCore.addListener(new TextListener(System.out)); - Result result = jUnitCore.run(lst.toArray(new Class[lst.size()])); - if (!result.wasSuccessful()) { - throw new RuntimeException("Tests did not succeed, cannot build ooxml-lite jar"); - } - - //see what classes from the ooxml-schemas.jar are loaded - System.out.println("Copying classes to " + _destDest); - Map> classes = getLoadedClasses(_ooxmlJar.getName()); - for (Class cls : classes.values()) { - String className = cls.getName(); - String classRef = className.replace('.', '/') + ".class"; - File destFile = new File(_destDest, classRef); - copyFile(cls.getResourceAsStream('/' + classRef), destFile); - - if(cls.isInterface()){ - /** - * Copy classes and interfaces declared as members of this class - */ - for(Class fc : cls.getDeclaredClasses()){ - className = fc.getName(); - classRef = className.replace('.', '/') + ".class"; - destFile = new File(_destDest, classRef); - copyFile(fc.getResourceAsStream('/' + classRef), destFile); - } - } - } - - //finally copy the compiled .xsb files - System.out.println("Copying .xsb resources"); - JarFile jar = new JarFile(_ooxmlJar); - Pattern p = Pattern.compile("schemaorg_apache_xmlbeans/(system|element)/.*\\.xsb"); - try { - for(Enumeration e = jar.entries(); e.hasMoreElements(); ){ - JarEntry je = e.nextElement(); - if(p.matcher(je.getName()).matches()) { - File destFile = new File(_destDest, je.getName()); - copyFile(jar.getInputStream(je), destFile); - } - } - } finally { - jar.close(); - } - } - - private static boolean checkForTestAnnotation(Class testclass) { - for (Method m : testclass.getDeclaredMethods()) { - if(m.isAnnotationPresent(Test.class)) { - return true; - } - } - - // also check super classes - if(testclass.getSuperclass() != null) { - for (Method m : testclass.getSuperclass().getDeclaredMethods()) { - if(m.isAnnotationPresent(Test.class)) { - return true; - } - } - } - - System.out.println("Class " + testclass.getName() + " does not derive from TestCase and does not have a @Test annotation"); - - // Should we also look at superclasses to find cases - // where we have abstract base classes with derived tests? - // if(checkForTestAnnotation(testclass.getSuperclass())) return true; - - return false; - } - - /** - * Recursively collect classes from the supplied directory - * - * @param arg the directory to search in - * @param out output - * @param ptrn the pattern (regexp) to filter found files - */ - private static void collectTests(File root, File arg, List> out, String ptrn, String exclude) - throws ClassNotFoundException { - if (arg.isDirectory()) { - File files[] = arg.listFiles(); - if (files != null) { - for (File f : files) { - collectTests(root, f, out, ptrn, exclude); - } - } - } else { - String path = arg.getAbsolutePath(); - String prefix = root.getAbsolutePath(); - String cls = path.substring(prefix.length() + 1).replace(File.separator, "."); - if(!cls.matches(ptrn)) return; - if (cls.matches(exclude)) return; - //ignore inner classes defined in tests - if (cls.indexOf('$') != -1) { - System.out.println("Inner class " + cls + " not included"); - return; - } - - cls = cls.replace(".class", ""); - - try { - Class testclass = Class.forName(cls); - if (TestCase.class.isAssignableFrom(testclass) - || checkForTestAnnotation(testclass)) { - out.add(testclass); - } - } catch (Throwable e) { // NOSONAR - System.out.println("Class " + cls + " is not in classpath"); - return; - } - } - } - - /** - * - * @param ptrn the pattern to filter output - * @return the classes loaded by the system class loader keyed by class name - */ - @SuppressWarnings("unchecked") - private static Map> getLoadedClasses(String ptrn) { - // make the field accessible, we defer this from static initialization to here to - // allow JDKs which do not have this field (e.g. IBM JDK) to at least load the class - // without failing, see https://issues.apache.org/bugzilla/show_bug.cgi?id=56550 - final Field _classes = AccessController.doPrivileged(new PrivilegedAction() { - @SuppressForbidden("TODO: Reflection works until Java 8 on Oracle/Sun JDKs, but breaks afterwards (different classloader types, access checks)") - public Field run() { - try { - Field fld = ClassLoader.class.getDeclaredField("classes"); - fld.setAccessible(true); - return fld; - } catch (Exception e) { - throw new RuntimeException(e); - } - - } - }); - - ClassLoader appLoader = ClassLoader.getSystemClassLoader(); - try { - Vector> classes = (Vector>) _classes.get(appLoader); - Map> map = new HashMap>(); - for (Class cls : classes) { - // e.g. proxy-classes, ... - ProtectionDomain pd = cls.getProtectionDomain(); - if (pd == null) continue; - CodeSource cs = pd.getCodeSource(); - if (cs == null) continue; - URL loc = cs.getLocation(); - if (loc == null) continue; - - String jar = loc.toString(); - if(jar.indexOf(ptrn) != -1) map.put(cls.getName(), cls); - } - return map; - } catch (IllegalAccessException e) { - throw new RuntimeException(e); - } - } - - private static void copyFile(InputStream srcStream, File destFile) throws IOException { - File destDirectory = destFile.getParentFile(); - if (!(destDirectory.exists() || destDirectory.mkdirs())) { - throw new RuntimeException("Can't create destination directory: "+destDirectory); - } - ; - OutputStream destStream = new FileOutputStream(destFile); - try { - IOUtils.copy(srcStream, destStream); - } finally { - destStream.close(); - } - } - -} \ No newline at end of file diff --git a/src/ooxml/java/org/apache/poi/util/PackageHelper.java b/src/ooxml/java/org/apache/poi/util/PackageHelper.java deleted file mode 100644 index 884868f1b..000000000 --- a/src/ooxml/java/org/apache/poi/util/PackageHelper.java +++ /dev/null @@ -1,137 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.util; - -import org.apache.poi.openxml4j.opc.*; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.exceptions.OpenXML4JException; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.util.IOUtils; -import org.apache.poi.POIXMLException; - -import java.io.*; -import java.net.URI; - -/** - * Provides handy methods to work with OOXML packages - */ -public final class PackageHelper { - - public static OPCPackage open(InputStream is) throws IOException { - try { - return OPCPackage.open(is); - } catch (InvalidFormatException e){ - throw new POIXMLException(e); - } - } - - /** - * Clone the specified package. - * - * @param pkg the package to clone - * @param file the destination file - * @return the cloned package - */ - public static OPCPackage clone(OPCPackage pkg, File file) throws OpenXML4JException, IOException { - - String path = file.getAbsolutePath(); - - OPCPackage dest = OPCPackage.create(path); - PackageRelationshipCollection rels = pkg.getRelationships(); - for (PackageRelationship rel : rels) { - PackagePart part = pkg.getPart(rel); - PackagePart part_tgt; - if (rel.getRelationshipType().equals(PackageRelationshipTypes.CORE_PROPERTIES)) { - copyProperties(pkg.getPackageProperties(), dest.getPackageProperties()); - continue; - } - dest.addRelationship(part.getPartName(), rel.getTargetMode(), rel.getRelationshipType()); - part_tgt = dest.createPart(part.getPartName(), part.getContentType()); - - OutputStream out = part_tgt.getOutputStream(); - IOUtils.copy(part.getInputStream(), out); - out.close(); - - if(part.hasRelationships()) { - copy(pkg, part, dest, part_tgt); - } - } - dest.close(); - - //the temp file will be deleted when JVM terminates - new File(path).deleteOnExit(); - return OPCPackage.open(path); - } - - /** - * Recursively copy package parts to the destination package - */ - private static void copy(OPCPackage pkg, PackagePart part, OPCPackage tgt, PackagePart part_tgt) throws OpenXML4JException, IOException { - PackageRelationshipCollection rels = part.getRelationships(); - if(rels != null) for (PackageRelationship rel : rels) { - PackagePart p; - if(rel.getTargetMode() == TargetMode.EXTERNAL){ - part_tgt.addExternalRelationship(rel.getTargetURI().toString(), rel.getRelationshipType(), rel.getId()); - //external relations don't have associated package parts - continue; - } - URI uri = rel.getTargetURI(); - - if(uri.getRawFragment() != null) { - part_tgt.addRelationship(uri, rel.getTargetMode(), rel.getRelationshipType(), rel.getId()); - continue; - } - PackagePartName relName = PackagingURIHelper.createPartName(rel.getTargetURI()); - p = pkg.getPart(relName); - part_tgt.addRelationship(p.getPartName(), rel.getTargetMode(), rel.getRelationshipType(), rel.getId()); - - - - - PackagePart dest; - if(!tgt.containPart(p.getPartName())){ - dest = tgt.createPart(p.getPartName(), p.getContentType()); - OutputStream out = dest.getOutputStream(); - IOUtils.copy(p.getInputStream(), out); - out.close(); - copy(pkg, p, tgt, dest); - } - } - } - - /** - * Copy core package properties - * - * @param src source properties - * @param tgt target properties - */ - private static void copyProperties(PackageProperties src, PackageProperties tgt){ - tgt.setCategoryProperty(src.getCategoryProperty().getValue()); - tgt.setContentStatusProperty(src.getContentStatusProperty().getValue()); - tgt.setContentTypeProperty(src.getContentTypeProperty().getValue()); - tgt.setCreatorProperty(src.getCreatorProperty().getValue()); - tgt.setDescriptionProperty(src.getDescriptionProperty().getValue()); - tgt.setIdentifierProperty(src.getIdentifierProperty().getValue()); - tgt.setKeywordsProperty(src.getKeywordsProperty().getValue()); - tgt.setLanguageProperty(src.getLanguageProperty().getValue()); - tgt.setRevisionProperty(src.getRevisionProperty().getValue()); - tgt.setSubjectProperty(src.getSubjectProperty().getValue()); - tgt.setTitleProperty(src.getTitleProperty().getValue()); - tgt.setVersionProperty(src.getVersionProperty().getValue()); - } -} diff --git a/src/ooxml/java/org/apache/poi/util/SAXHelper.java b/src/ooxml/java/org/apache/poi/util/SAXHelper.java deleted file mode 100644 index 41f14fbcc..000000000 --- a/src/ooxml/java/org/apache/poi/util/SAXHelper.java +++ /dev/null @@ -1,102 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.util; - -import java.io.IOException; -import java.io.StringReader; -import java.lang.reflect.Method; -import java.util.concurrent.TimeUnit; - -import javax.xml.XMLConstants; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.parsers.SAXParserFactory; - -import org.xml.sax.EntityResolver; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; -import org.xml.sax.XMLReader; - - -/** - * Provides handy methods for working with SAX parsers and readers - */ -public final class SAXHelper { - private static final POILogger logger = POILogFactory.getLogger(SAXHelper.class); - private static long lastLog; - - private SAXHelper() {} - - /** - * Creates a new SAX XMLReader, with sensible defaults - */ - public static synchronized XMLReader newXMLReader() throws SAXException, ParserConfigurationException { - XMLReader xmlReader = saxFactory.newSAXParser().getXMLReader(); - xmlReader.setEntityResolver(IGNORING_ENTITY_RESOLVER); - trySetSAXFeature(xmlReader, XMLConstants.FEATURE_SECURE_PROCESSING); - trySetXercesSecurityManager(xmlReader); - return xmlReader; - } - - static final EntityResolver IGNORING_ENTITY_RESOLVER = new EntityResolver() { - @Override - public InputSource resolveEntity(String publicId, String systemId) - throws SAXException, IOException { - return new InputSource(new StringReader("")); - } - }; - - private static final SAXParserFactory saxFactory; - static { - saxFactory = SAXParserFactory.newInstance(); - saxFactory.setValidating(false); - saxFactory.setNamespaceAware(true); - } - - private static void trySetSAXFeature(XMLReader xmlReader, String feature) { - try { - xmlReader.setFeature(feature, true); - } catch (Exception e) { - logger.log(POILogger.WARN, "SAX Feature unsupported", feature, e); - } catch (AbstractMethodError ame) { - logger.log(POILogger.WARN, "Cannot set SAX feature because outdated XML parser in classpath", feature, ame); - } - } - - private static void trySetXercesSecurityManager(XMLReader xmlReader) { - // Try built-in JVM one first, standalone if not - for (String securityManagerClassName : new String[] { - "com.sun.org.apache.xerces.internal.util.SecurityManager", - "org.apache.xerces.util.SecurityManager" - }) { - try { - Object mgr = Class.forName(securityManagerClassName).newInstance(); - Method setLimit = mgr.getClass().getMethod("setEntityExpansionLimit", Integer.TYPE); - setLimit.invoke(mgr, 4096); - xmlReader.setProperty("http://apache.org/xml/properties/security-manager", mgr); - // Stop once one can be setup without error - return; - } catch (Throwable e) { // NOSONAR - also catch things like NoClassDefError here - // throttle the log somewhat as it can spam the log otherwise - if(System.currentTimeMillis() > lastLog + TimeUnit.MINUTES.toMillis(5)) { - logger.log(POILogger.WARN, "SAX Security Manager could not be setup [log suppressed for 5 minutes]", e); - lastLog = System.currentTimeMillis(); - } - } - } - } -} diff --git a/src/ooxml/java/org/apache/poi/util/XmlSort.java b/src/ooxml/java/org/apache/poi/util/XmlSort.java deleted file mode 100644 index 09f05fb46..000000000 --- a/src/ooxml/java/org/apache/poi/util/XmlSort.java +++ /dev/null @@ -1,88 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.util; - -import java.util.Comparator; - -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlObject; - -public final class XmlSort { - /** - * Sorts the children of element according to the order indicated by the - * comparator. - * @param element the element whose content is to be sorted. Only element children are sorted, - * attributes are not touched. When elements are reordered, all the text, comments and PIs - * follow the element that they come immediately after. - * @param comp a comparator that is to be used when comparing the QNames of two - * elements. - * @throws IllegalArgumentException if the input XmlObject does not represent - * an element - */ - public static void sort(XmlObject element, Comparator comp) { - XmlCursor headCursor = element.newCursor(); - if (!headCursor.isStart()) { - throw new IllegalStateException("The element parameter must point to a STARTDOC"); - } - // We use insertion sort to minimize the number of swaps, because each swap means - // moving a part of the document - /* headCursor points to the beginning of the list of the already sorted items and - listCursor points to the beginning of the list of unsorted items - At the beginning, headCursor points to the first element and listCursor points to the - second element. The algorithm ends when listCursor cannot be moved to the "next" - element in the unsorted list, i.e. the unsorted list becomes empty */ - boolean moved = headCursor.toFirstChild(); - if (!moved) { - // Cursor was not moved, which means that the given element has no children and - // therefore there is nothing to sort - return; - } - XmlCursor listCursor = headCursor.newCursor(); - boolean moreElements = listCursor.toNextSibling(); - while (moreElements) { - moved = false; - // While we can move the head of the unsorted list, it means that there are still - // items (elements) that need to be sorted - while (headCursor.comparePosition(listCursor) < 0) { - if (comp.compare(headCursor, listCursor) > 0) { - // We have found the position in the sorted list, insert the element and the - // text following the element in the current position - // Move the element - listCursor.moveXml(headCursor); - // Move the text following the element - while (!listCursor.isStart() && !listCursor.isEnd()) - listCursor.moveXml(headCursor); - moreElements = listCursor.isStart(); - moved = true; - break; - } - headCursor.toNextSibling(); - } - if (!moved) { - // Because during the move of a fragment of XML, the listCursor is also moved, in - // case we didn't need to move XML (the new element to be inserted happened to - // be the last one in order), we need to move this cursor - moreElements = listCursor.toNextSibling(); - } - // Reposition the head of the sorted list - headCursor.toParent(); - headCursor.toFirstChild(); - } - } -} - \ No newline at end of file diff --git a/src/ooxml/java/org/apache/poi/xdgf/exceptions/XDGFException.java b/src/ooxml/java/org/apache/poi/xdgf/exceptions/XDGFException.java deleted file mode 100644 index 379877e0d..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/exceptions/XDGFException.java +++ /dev/null @@ -1,53 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xdgf.exceptions; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.POIXMLException; - -public class XDGFException { - - /** - * Creates an error message to be thrown - */ - public static POIXMLException error(String message, Object o) { - return new POIXMLException(o.toString() + ": " + message); - } - - public static POIXMLException error(String message, Object o, Throwable t) { - return new POIXMLException(o.toString() + ": " + message, t); - } - - // - // Use these to wrap error messages coming up so that we have at least - // some idea where the error was located - // - - public static POIXMLException wrap(POIXMLDocumentPart part, - POIXMLException e) { - return new POIXMLException(part.getPackagePart().getPartName() - .toString() - + ": " + e.getMessage(), e.getCause() == null ? e - : e.getCause()); - } - - public static POIXMLException wrap(String where, POIXMLException e) { - return new POIXMLException(where + ": " + e.getMessage(), - e.getCause() == null ? e : e.getCause()); - } -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/extractor/XDGFVisioExtractor.java b/src/ooxml/java/org/apache/poi/xdgf/extractor/XDGFVisioExtractor.java deleted file mode 100644 index 5f474fc73..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/extractor/XDGFVisioExtractor.java +++ /dev/null @@ -1,67 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xdgf.extractor; - -import java.io.IOException; - -import org.apache.poi.POIXMLDocument; -import org.apache.poi.POIXMLTextExtractor; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.xdgf.usermodel.XDGFPage; -import org.apache.poi.xdgf.usermodel.XmlVisioDocument; -import org.apache.poi.xdgf.usermodel.shape.ShapeTextVisitor; - -/** - * Helper class to extract text from an OOXML Visio File - */ -public class XDGFVisioExtractor extends POIXMLTextExtractor { - - protected final XmlVisioDocument document; - - public XDGFVisioExtractor(XmlVisioDocument document) { - super(document); - this.document = document; - } - - public XDGFVisioExtractor(OPCPackage openPackage) throws IOException { - this(new XmlVisioDocument(openPackage)); - } - - public String getText() { - ShapeTextVisitor visitor = new ShapeTextVisitor(); - - for (XDGFPage page: document.getPages()) { - page.getContent().visitShapes(visitor); - } - - return visitor.getText().toString(); - } - - public static void main(String [] args) throws IOException { - if (args.length < 1) { - System.err.println("Use:"); - System.err.println(" XDGFVisioExtractor "); - System.exit(1); - } - POIXMLTextExtractor extractor = - new XDGFVisioExtractor(POIXMLDocument.openPackage( - args[0] - )); - System.out.println(extractor.getText()); - extractor.close(); - } -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/geom/Dimension2dDouble.java b/src/ooxml/java/org/apache/poi/xdgf/geom/Dimension2dDouble.java deleted file mode 100644 index 94b887e04..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/geom/Dimension2dDouble.java +++ /dev/null @@ -1,73 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xdgf.geom; - -import java.awt.geom.Dimension2D; - -public class Dimension2dDouble extends Dimension2D { - - double width; - double height; - - public Dimension2dDouble() { - width = 0d; - height = 0d; - } - - public Dimension2dDouble(double width, double height) { - this.width = width; - this.height = height; - } - - @Override - public double getWidth() { - return width; - } - - @Override - public double getHeight() { - return height; - } - - @Override - public void setSize(double width, double height) { - this.width = width; - this.height = height; - } - - @Override - public boolean equals(Object obj) { - if (obj instanceof Dimension2dDouble) { - Dimension2dDouble other = (Dimension2dDouble) obj; - return width == other.width && height == other.height; - } - - return false; - } - - @Override - public int hashCode() { - double sum = width + height; - return (int) Math.ceil(sum * (sum + 1) / 2 + width); - } - - @Override - public String toString() { - return "Dimension2dDouble[" + width + ", " + height + "]"; - } -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/geom/SplineCollector.java b/src/ooxml/java/org/apache/poi/xdgf/geom/SplineCollector.java deleted file mode 100644 index a977cb627..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/geom/SplineCollector.java +++ /dev/null @@ -1,79 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xdgf.geom; - -import java.awt.geom.Point2D; -import java.util.ArrayList; - -import org.apache.poi.xdgf.usermodel.XDGFShape; -import org.apache.poi.xdgf.usermodel.section.geometry.SplineKnot; -import org.apache.poi.xdgf.usermodel.section.geometry.SplineStart; - -import com.graphbuilder.curve.ControlPath; -import com.graphbuilder.curve.ShapeMultiPath; -import com.graphbuilder.curve.ValueVector; -import com.graphbuilder.geom.PointFactory; - -public class SplineCollector { - - SplineStart _start; - ArrayList _knots = new ArrayList(); - - public SplineCollector(SplineStart start) { - _start = start; - } - - public void addKnot(SplineKnot knot) { - if (!knot.getDel()) - _knots.add(knot); - } - - public void addToPath(java.awt.geom.Path2D.Double path, XDGFShape parent) { - // ok, we have the start, and all knots... do something with this - - Point2D last = path.getCurrentPoint(); - - // create a control path and knots - ControlPath controlPath = new ControlPath(); - ValueVector knots = new ValueVector(_knots.size() + 3); - - double firstKnot = _start.getB(); - double lastKnot = _start.getC(); - int degree = _start.getD(); - - // first/second knot - knots.add(firstKnot); - knots.add(_start.getA()); - - // first/second control point - controlPath.addPoint(PointFactory.create(last.getX(), last.getY())); - controlPath.addPoint(PointFactory.create(_start.getX(), _start.getY())); - - // middle knots/control points - for (SplineKnot knot: _knots) { - knots.add(knot.getA()); - controlPath.addPoint(PointFactory.create(knot.getX(), knot.getY())); - } - - // last knot - knots.add(lastKnot); - - ShapeMultiPath shape = SplineRenderer.createNurbsSpline(controlPath, knots, null, degree); - path.append(shape, true); - } -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/geom/SplineRenderer.java b/src/ooxml/java/org/apache/poi/xdgf/geom/SplineRenderer.java deleted file mode 100644 index c16835604..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/geom/SplineRenderer.java +++ /dev/null @@ -1,69 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xdgf.geom; - -import com.graphbuilder.curve.ControlPath; -import com.graphbuilder.curve.GroupIterator; -import com.graphbuilder.curve.NURBSpline; -import com.graphbuilder.curve.ShapeMultiPath; -import com.graphbuilder.curve.ValueVector; - - -public class SplineRenderer { - - public static ShapeMultiPath createNurbsSpline(ControlPath controlPoints, - ValueVector knots, ValueVector weights, int degree) { - - double firstKnot = knots.get(0); - final int count = knots.size(); - double lastKnot = knots.get(count - 1); - - // scale knots to [0, 1] based on first/last knots - for (int i = 0; i < count; i++) { - knots.set((knots.get(i) - firstKnot) / lastKnot, i); - } - - // if we don't have enough knots, duplicate the last knot until we do - final int knotsToAdd = controlPoints.numPoints() + degree + 1; - for (int i = count; i < knotsToAdd; i++) { - knots.add(1); - } - - GroupIterator gi = new GroupIterator("0:n-1", controlPoints.numPoints()); - - NURBSpline spline = new NURBSpline(controlPoints, gi); - - spline.setDegree(degree); - spline.setKnotVectorType(NURBSpline.NON_UNIFORM); - spline.setKnotVector(knots); - - if (weights == null) { - spline.setUseWeightVector(false); - } else { - spline.setWeightVector(weights); - } - - // now that this is done, add it to the path - ShapeMultiPath shape = new ShapeMultiPath(); - shape.setFlatness(0.01); - - spline.appendTo(shape); - return shape; - } - -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFBaseContents.java b/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFBaseContents.java deleted file mode 100644 index 2d65621f1..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFBaseContents.java +++ /dev/null @@ -1,164 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xdgf.usermodel; - -import java.awt.Graphics2D; -import java.awt.geom.AffineTransform; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.poi.POIXMLException; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.opc.PackageRelationship; -import org.apache.poi.util.Internal; -import org.apache.poi.xdgf.exceptions.XDGFException; -import org.apache.poi.xdgf.usermodel.shape.ShapeRenderer; -import org.apache.poi.xdgf.usermodel.shape.ShapeVisitor; -import org.apache.poi.xdgf.usermodel.shape.exceptions.StopVisiting; -import org.apache.poi.xdgf.xml.XDGFXMLDocumentPart; - -import com.microsoft.schemas.office.visio.x2012.main.ConnectType; -import com.microsoft.schemas.office.visio.x2012.main.PageContentsType; -import com.microsoft.schemas.office.visio.x2012.main.ShapeSheetType; - -/** - * Container of shapes for a page in a Visio diagram. Shapes are not - * necessarily literal shapes in the diagram, but is the term that is - * used to describe the basic elements that make up a Visio diagram. - */ -public class XDGFBaseContents extends XDGFXMLDocumentPart { - - protected PageContentsType _pageContents; - - // shapes without parents - protected List _toplevelShapes = new ArrayList(); - protected Map _shapes = new HashMap(); - protected List _connections = new ArrayList(); - - /** - * @since POI 3.14-Beta1 - */ - public XDGFBaseContents(PackagePart part, XDGFDocument document) { - super(part, document); - } - - @Internal - public PageContentsType getXmlObject() { - return _pageContents; - } - - - @Override - protected void onDocumentRead() { - - if (_pageContents.isSetShapes()) { - for (ShapeSheetType shapeSheet: _pageContents.getShapes().getShapeArray()) { - XDGFShape shape = new XDGFShape(shapeSheet, this, _document); - _toplevelShapes.add(shape); - addToShapeIndex(shape); - } - } - - if (_pageContents.isSetConnects()) { - for (ConnectType connect: _pageContents.getConnects().getConnectArray()) { - - XDGFShape from = _shapes.get(connect.getFromSheet()); - XDGFShape to = _shapes.get(connect.getToSheet()); - - if (from == null) - throw new POIXMLException(this.toString() + "; Connect; Invalid from id: " + connect.getFromSheet()); - - if (to == null) - throw new POIXMLException(this.toString() + "; Connect; Invalid to id: " + connect.getToSheet()); - - _connections.add(new XDGFConnection(connect, from, to)); - } - } - } - - protected void addToShapeIndex(XDGFShape shape) { - _shapes.put(shape.getID(), shape); - - List shapes = shape.getShapes(); - if (shapes == null) - return; - - for (XDGFShape subshape: shapes) - addToShapeIndex(subshape); - } - - // - // API - // - - /** - * Draws the contents of a page onto a Graphics2D object - * - * @param graphics - */ - public void draw(Graphics2D graphics) { - visitShapes(new ShapeRenderer(graphics)); - } - - - public XDGFShape getShapeById(long id) { - return _shapes.get(id); - } - - public Map getShapesMap() { - return Collections.unmodifiableMap(_shapes); - } - - public Collection getShapes() { - return _shapes.values(); - } - - public List getTopLevelShapes() { - return Collections.unmodifiableList(_toplevelShapes); - } - - public List getConnections() { - return Collections.unmodifiableList(_connections); - } - - @Override - public String toString() { - return getPackagePart().getPartName().toString(); - } - - - /** - * Provides iteration over the shapes using the visitor pattern, and provides - * an easy way to convert shape coordinates into global coordinates - */ - public void visitShapes(ShapeVisitor visitor) { - try { - for (XDGFShape shape: _toplevelShapes) { - shape.visitShapes(visitor, new AffineTransform(), 0); - } - } catch (StopVisiting e) { - // intentionally empty - } catch (POIXMLException e) { - throw XDGFException.wrap(this, e); - } - } - -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFCell.java b/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFCell.java deleted file mode 100644 index f7f329184..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFCell.java +++ /dev/null @@ -1,162 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xdgf.usermodel; - -import java.util.Map; - -import org.apache.poi.POIXMLException; -import org.apache.poi.util.Internal; - -import com.microsoft.schemas.office.visio.x2012.main.CellType; - -/** - * There are a lot of different cell types. Cell is really just an attribute of - * the thing that it's attached to. Will probably refactor this once I figure - * out a better way to use them - * - * The various attributes of a Cell are constrained, and are better defined in - * the XSD 1.1 visio schema - * - * Values of a cell are often the result of a formula computation. Luckily for - * you, Visio seems to always write the result to the document file, so unless - * the values change we don't need to recompute the values. - */ -public class XDGFCell { - - public static Boolean maybeGetBoolean(Map cells, - String name) { - XDGFCell cell = cells.get(name); - if (cell == null) - return null; - - if (cell.getValue().equals("0")) - return false; - if (cell.getValue().equals("1")) - return true; - - throw new POIXMLException("Invalid boolean value for '" - + cell.getName() + "'"); - } - - public static Double maybeGetDouble(Map cells, String name) { - XDGFCell cell = cells.get(name); - if (cell != null) - return parseDoubleValue(cell._cell); - return null; - } - - public static Integer maybeGetInteger(Map cells, - String name) { - XDGFCell cell = cells.get(name); - if (cell != null) - return parseIntegerValue(cell._cell); - return null; - } - - public static String maybeGetString(Map cells, String name) { - XDGFCell cell = cells.get(name); - if (cell != null) { - String v = cell._cell.getV(); - if (v.equals("Themed")) - return null; - return v; - } - return null; - } - - public static Double parseDoubleValue(CellType cell) { - try { - return Double.parseDouble(cell.getV()); - } catch (NumberFormatException e) { - if (cell.getV().equals("Themed")) - return null; - throw new POIXMLException("Invalid float value for '" + cell.getN() - + "': " + e); - } - } - - public static Integer parseIntegerValue(CellType cell) { - try { - return Integer.parseInt(cell.getV()); - } catch (NumberFormatException e) { - if (cell.getV().equals("Themed")) - return null; - throw new POIXMLException("Invalid integer value for '" - + cell.getN() + "': " + e); - } - } - - /** - * @param cell - * @return A value converted to inches - */ - public static Double parseVLength(CellType cell) { - try { - return Double.parseDouble(cell.getV()); - } catch (NumberFormatException e) { - if (cell.getV().equals("Themed")) - return null; - throw new POIXMLException("Invalid float value for '" + cell.getN() - + "': " + e); - } - } - - CellType _cell; - - public XDGFCell(CellType cell) { - _cell = cell; - } - - @Internal - protected CellType getXmlObject() { - return _cell; - } - - /** - * Represents the name of the ShapeSheet cell. - */ - public String getName() { - return _cell.getN(); - } - - /** - * Represents the value of the cell. - */ - public String getValue() { - return _cell.getV(); - } - - /** - * Represents the element's formula. This attribute can contain one of the - * following strings: - '(some formula)' if the formula exists locally - No - * Formula if the formula is locally deleted or blocked - Inh if the formula - * is inherited. - */ - public String getFormula() { - return _cell.getF(); - } - - /* - * Indicates that the formula evaluates to an error. The value of E is the - * current value (an error message string); the value of the V attribute is - * the last valid value. - */ - public String getError() { - return _cell.getE(); - } -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFConnection.java b/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFConnection.java deleted file mode 100644 index cc24a41fc..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFConnection.java +++ /dev/null @@ -1,149 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xdgf.usermodel; - -import com.microsoft.schemas.office.visio.x2012.main.ConnectType; - -/** - * Represents connections in a Visio diagram. - * - * Note that just because something appears to be visually connected in a - * document does not mean that the user actually connected the elements. It - * turns out there are a lot of ways that a careless user can neglect to - * properly make connections that will not be recorded in the diagram - * in a machine readable way. - */ -public class XDGFConnection { - - // comments on frompart/topart taken from pkgVisio - - // https://msdn.microsoft.com/en-us/library/ms367611(v=office.12).aspx - - // The following constants declared by the Microsoft Office Visio type - // library show return values for the FromPart property. - // Constant Value - // visConnectFromError -1 - // visFromNone 0 - // visLeftEdge 1 - // visCenterEdge 2 - // visRightEdge 3 - // visBottomEdge 4 - // visMiddleEdge 5 - // visTopEdge 6 - // visBeginX 7 - // visBeginY 8 - // visBegin 9 - // visEndX 10 - // visEndY 11 - // visEnd 12 - // visFromAngle 13 - // visFromPin 14 - // visControlPoint 100 + zero-based row index (for example, visControlPoint - // = 100 if the control point is in row 0; visControlPoint = 101 if the - // control point is in row 1) - - public static final int visConnectFromError = -1; - public static final int visFromNone = 0; - public static final int visLeftEdge = 1; - public static final int visCenterEdge = 2; - public static final int visRightEdge = 3; - public static final int visBottomEdge = 4; - public static final int visMiddleEdge = 5; - public static final int visTopEdge = 6; - public static final int visBeginX = 7; - public static final int visBeginY = 8; - public static final int visBegin = 9; - public static final int visEndX = 10; - public static final int visEndY = 11; - public static final int visEnd = 12; - public static final int visFromAngle = 13; - public static final int visFromPin = 14; - - // The ToPart property identifies the part of a shape to which another - // shape is glued, such as its begin point or endpoint, one of its edges, - // or a connection point. The following constants declared by the Visio type - // library in member VisToParts show possible return values for the ToPart - // property. - // Constant Value - // visConnectToError -1 - // visToNone 0 - // visGuideX 1 - // visGuideY 2 - // visWholeShape 3 - // visGuideIntersect 4 - // visToAngle 7 - // visConnectionPoint 100 + row index of connection point - - public static final int visConnectToError = -1; - public static final int visToNone = 0; - public static final int visGuideX = 1; - public static final int visGuideY = 2; - public static final int visWholeShape = 3; - public static final int visGuideIntersect = 4; - public static final int visToAngle = 7; - - private ConnectType _connect; - private XDGFShape _from; - private XDGFShape _to; - - public XDGFConnection(ConnectType connect, XDGFShape from, XDGFShape to) { - _connect = connect; - _from = from; - _to = to; - } - - public XDGFShape getFromShape() { - return _from; - } - - public XDGFCell getFromCell() { - return _from.getCell(_connect.getFromCell()); - } - - public String getFromCellName() { - return _connect.getFromCell(); - } - - public XDGFShape getToShape() { - return _to; - } - - public String getToCellName() { - return _connect.getToCell(); - } - - // see constants above - public Integer getFromPart() { - if (_connect.isSetFromPart()) - return _connect.getFromPart(); - else - return null; - } - - /** - * The ToPart property identifies the part of a shape to which another - * shape is glued, such as its begin point or endpoint, one of its edges, - * or a connection point. - */ - public Integer getToPart() { - if (_connect.isSetToPart()) - return _connect.getToPart(); - else - return null; - } -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFDocument.java b/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFDocument.java deleted file mode 100644 index ba460cc13..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFDocument.java +++ /dev/null @@ -1,119 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xdgf.usermodel; - -import java.util.HashMap; -import java.util.Map; - -import org.apache.poi.POIXMLException; -import org.apache.poi.util.Internal; - -import com.microsoft.schemas.office.visio.x2012.main.DocumentSettingsType; -import com.microsoft.schemas.office.visio.x2012.main.StyleSheetType; -import com.microsoft.schemas.office.visio.x2012.main.VisioDocumentType; - -/** - * Represents the root document: /visio/document.xml - * - * You're probably actually looking for {@link XmlVisioDocument}, this - * only contains metadata about the root document in the OOXML package. - */ -public class XDGFDocument { - - protected VisioDocumentType _document; - - Map _styleSheets = new HashMap(); - - // defaults - long _defaultFillStyle = 0; - long _defaultGuideStyle = 0; - long _defaultLineStyle = 0; - long _defaultTextStyle = 0; - - - public XDGFDocument(VisioDocumentType document) { - - _document = document; - - if (!_document.isSetDocumentSettings()) - throw new POIXMLException("Document settings not found"); - - DocumentSettingsType docSettings = _document.getDocumentSettings(); - - if (docSettings.isSetDefaultFillStyle()) - _defaultFillStyle = docSettings.getDefaultFillStyle(); - - if (docSettings.isSetDefaultGuideStyle()) - _defaultGuideStyle = docSettings.getDefaultGuideStyle(); - - if (docSettings.isSetDefaultLineStyle()) - _defaultLineStyle = docSettings.getDefaultLineStyle(); - - if (docSettings.isSetDefaultTextStyle()) - _defaultTextStyle = docSettings.getDefaultTextStyle(); - - if (_document.isSetStyleSheets()) { - - for (StyleSheetType styleSheet: _document.getStyleSheets().getStyleSheetArray()) { - _styleSheets.put(styleSheet.getID(), new XDGFStyleSheet(styleSheet, this)); - } - } - } - - - @Internal - public VisioDocumentType getXmlObject() { - return _document; - } - - - public XDGFStyleSheet getStyleById(long id) { - return _styleSheets.get(id); - } - - - public XDGFStyleSheet getDefaultFillStyle() { - XDGFStyleSheet style = getStyleById(_defaultFillStyle); - if (style == null) - throw new POIXMLException("No default fill style found!"); - return style; - } - - public XDGFStyleSheet getDefaultGuideStyle() { - XDGFStyleSheet style = getStyleById(_defaultGuideStyle); - if (style == null) - throw new POIXMLException("No default guide style found!"); - return style; - } - - public XDGFStyleSheet getDefaultLineStyle() { - XDGFStyleSheet style = getStyleById(_defaultLineStyle); - if (style == null) - throw new POIXMLException("No default line style found!"); - return style; - } - - public XDGFStyleSheet getDefaultTextStyle() { - XDGFStyleSheet style = getStyleById(_defaultTextStyle); - if (style == null) - throw new POIXMLException("No default text style found!"); - return style; - } - - -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFFactory.java b/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFFactory.java deleted file mode 100644 index 83ac58ce0..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFFactory.java +++ /dev/null @@ -1,69 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xdgf.usermodel; - -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.POIXMLFactory; -import org.apache.poi.POIXMLRelation; - -/** - * Instantiates sub-classes of POIXMLDocumentPart depending on their relationship type - */ -public class XDGFFactory extends POIXMLFactory { - - private final XDGFDocument document; - - public XDGFFactory(XDGFDocument document) { - this.document = document; - } - - /** - * @since POI 3.14-Beta1 - */ - protected POIXMLRelation getDescriptor(String relationshipType) { - return XDGFRelation.getInstance(relationshipType); - } - - /** - * @since POI 3.14-Beta1 - */ - @Override - protected POIXMLDocumentPart createDocumentPart - (Class cls, Class[] classes, Object[] values) - throws SecurityException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { - Class[] cl; - Object[] vals; - if (classes == null) { - cl = new Class[]{XDGFDocument.class}; - vals = new Object[]{document}; - } else { - cl = new Class[classes.length+1]; - System.arraycopy(classes, 0, cl, 0, classes.length); - cl[classes.length] = XDGFDocument.class; - vals = new Object[values.length+1]; - System.arraycopy(values, 0, vals, 0, values.length); - vals[values.length] = document; - } - - Constructor constructor = cls.getDeclaredConstructor(cl); - return constructor.newInstance(vals); - } -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFMaster.java b/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFMaster.java deleted file mode 100644 index 68c2c8626..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFMaster.java +++ /dev/null @@ -1,70 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xdgf.usermodel; - -import org.apache.poi.util.Internal; - -import com.microsoft.schemas.office.visio.x2012.main.MasterType; - -/** - * Provides the API to work with an underlying master. Typically, each set of - * stencils used in a Visio diagram are found in a separate master for each. - */ -public class XDGFMaster { - - private MasterType _master; - protected XDGFMasterContents _content; - protected XDGFSheet _pageSheet = null; - - public XDGFMaster(MasterType master, XDGFMasterContents content, - XDGFDocument document) { - _master = master; - _content = content; - content.setMaster(this); - - if (master.isSetPageSheet()) - _pageSheet = new XDGFPageSheet(master.getPageSheet(), document); - } - - @Internal - protected MasterType getXmlObject() { - return _master; - } - - @Override - public String toString() { - return ""; - } - - public long getID() { - return _master.getID(); - } - - public String getName() { - return _master.getName(); - } - - public XDGFMasterContents getContent() { - return _content; - } - - public XDGFSheet getPageSheet() { - return _pageSheet; - } - -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFMasterContents.java b/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFMasterContents.java deleted file mode 100644 index 8fd51324a..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFMasterContents.java +++ /dev/null @@ -1,71 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xdgf.usermodel; - -import java.io.IOException; - -import org.apache.poi.POIXMLException; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.xdgf.exceptions.XDGFException; -import org.apache.xmlbeans.XmlException; - -import com.microsoft.schemas.office.visio.x2012.main.MasterContentsDocument; - -/** - * Contains the actual contents of the master/stencil - */ -public class XDGFMasterContents extends XDGFBaseContents { - - protected XDGFMaster _master; - - /** - * @since POI 3.14-Beta1 - */ - public XDGFMasterContents(PackagePart part, XDGFDocument document) { - super(part, document); - } - - @Override - protected void onDocumentRead() { - - try { - - try { - _pageContents = MasterContentsDocument.Factory.parse(getPackagePart().getInputStream()).getMasterContents(); - } catch (XmlException e) { - throw new POIXMLException(e); - } catch (IOException e) { - throw new POIXMLException(e); - } - - super.onDocumentRead(); - - } catch (POIXMLException e) { - throw XDGFException.wrap(this, e); - } - } - - public XDGFMaster getMaster() { - return _master; - } - - protected void setMaster(XDGFMaster master) { - _master = master; - } - -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFMasters.java b/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFMasters.java deleted file mode 100644 index d2f72d4a2..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFMasters.java +++ /dev/null @@ -1,109 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xdgf.usermodel; - -import java.io.IOException; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.POIXMLException; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.util.Internal; -import org.apache.poi.xdgf.exceptions.XDGFException; -import org.apache.poi.xdgf.xml.XDGFXMLDocumentPart; -import org.apache.xmlbeans.XmlException; - -import com.microsoft.schemas.office.visio.x2012.main.MasterType; -import com.microsoft.schemas.office.visio.x2012.main.MastersDocument; -import com.microsoft.schemas.office.visio.x2012.main.MastersType; - -/** - * A collection of masters (typically stencils) in a Visio document - */ -public class XDGFMasters extends XDGFXMLDocumentPart { - - MastersType _mastersObject; - - // key: id of master - protected Map _masters = new HashMap(); - - /** - * @since POI 3.14-Beta1 - */ - public XDGFMasters(PackagePart part, XDGFDocument document) { - super(part, document); - } - - @Internal - protected MastersType getXmlObject() { - return _mastersObject; - } - - @Override - protected void onDocumentRead() { - try { - try { - _mastersObject = MastersDocument.Factory.parse(getPackagePart().getInputStream()).getMasters(); - } catch (XmlException e) { - throw new POIXMLException(e); - } catch (IOException e) { - throw new POIXMLException(e); - } - - Map masterSettings = new HashMap(); - for (MasterType master: _mastersObject.getMasterArray()) { - masterSettings.put(master.getRel().getId(), master); - } - - // create the masters - for (RelationPart rp : getRelationParts()) { - POIXMLDocumentPart part = rp.getDocumentPart(); - - String relId = rp.getRelationship().getId(); - MasterType settings = masterSettings.get(relId); - - if (settings == null) { - throw new POIXMLException("Master relationship for " + relId + " not found"); - } - - if (!(part instanceof XDGFMasterContents)) { - throw new POIXMLException("Unexpected masters relationship for " + relId + ": " + part); - } - - XDGFMasterContents contents = (XDGFMasterContents)part; - contents.onDocumentRead(); - - XDGFMaster master = new XDGFMaster(settings, contents, _document); - _masters.put(master.getID(), master); - } - } catch (POIXMLException e) { - throw XDGFException.wrap(this, e); - } - } - - public Collection getMastersList() { - return Collections.unmodifiableCollection(_masters.values()); - } - - public XDGFMaster getMasterById(long masterId) { - return _masters.get(masterId); - } -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFPage.java b/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFPage.java deleted file mode 100644 index 3bdbd2e1b..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFPage.java +++ /dev/null @@ -1,118 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xdgf.usermodel; - -import java.awt.geom.Point2D; -import java.awt.geom.Rectangle2D; - -import org.apache.poi.POIXMLException; -import org.apache.poi.util.Internal; -import org.apache.poi.xdgf.geom.Dimension2dDouble; - -import com.microsoft.schemas.office.visio.x2012.main.PageType; - -/** - * Provides the API to work with an underlying page - */ -public class XDGFPage { - - private PageType _page; - protected XDGFPageContents _content; - protected XDGFPages _pages; - protected XDGFSheet _pageSheet = null; - - public XDGFPage(PageType page, XDGFPageContents content, - XDGFDocument document, XDGFPages pages) { - _page = page; - _content = content; - _pages = pages; - content.setPage(this); - - if (page.isSetPageSheet()) - _pageSheet = new XDGFPageSheet(page.getPageSheet(), document); - } - - @Internal - protected PageType getXmlObject() { - return _page; - } - - public long getID() { - return _page.getID(); - } - - public String getName() { - return _page.getName(); - } - - public XDGFPageContents getContent() { - return _content; - } - - public XDGFSheet getPageSheet() { - return _pageSheet; - } - - public long getPageNumber() { - return _pages.getPageList().indexOf(this) + 1; - } - - /** - * @return width/height of page - */ - public Dimension2dDouble getPageSize() { - XDGFCell w = _pageSheet.getCell("PageWidth"); - XDGFCell h = _pageSheet.getCell("PageHeight"); - - if (w == null || h == null) - throw new POIXMLException("Cannot determine page size"); - - return new Dimension2dDouble(Double.parseDouble(w.getValue()), - Double.parseDouble(h.getValue())); - } - - /** - * @return origin of coordinate system - */ - public Point2D.Double getPageOffset() { - XDGFCell xoffcell = _pageSheet.getCell("XRulerOrigin"); - XDGFCell yoffcell = _pageSheet.getCell("YRulerOrigin"); - - double xoffset = 0; - double yoffset = 0; - - if (xoffcell != null) - xoffset = Double.parseDouble(xoffcell.getValue()); - - if (xoffcell != null) - yoffset = Double.parseDouble(yoffcell.getValue()); - - return new Point2D.Double(xoffset, yoffset); - } - - /** - * @return bounding box of page - */ - public Rectangle2D getBoundingBox() { - Dimension2dDouble sz = getPageSize(); - Point2D.Double offset = getPageOffset(); - - return new Rectangle2D.Double(-offset.getX(), -offset.getY(), - sz.getWidth(), sz.getHeight()); - } -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFPageContents.java b/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFPageContents.java deleted file mode 100644 index 54cf02f28..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFPageContents.java +++ /dev/null @@ -1,90 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xdgf.usermodel; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.POIXMLException; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.xdgf.exceptions.XDGFException; -import org.apache.xmlbeans.XmlException; - -import com.microsoft.schemas.office.visio.x2012.main.PageContentsDocument; - -public class XDGFPageContents extends XDGFBaseContents { - - protected Map _masters = new HashMap(); - protected XDGFPage _page; - - /** - * @since POI 3.14-Beta1 - */ - public XDGFPageContents(PackagePart part, XDGFDocument document) { - super(part, document); - } - - @Override - protected void onDocumentRead() { - try { - try { - _pageContents = PageContentsDocument.Factory.parse(getPackagePart().getInputStream()).getPageContents(); - } catch (XmlException e) { - throw new POIXMLException(e); - } catch (IOException e) { - throw new POIXMLException(e); - } - - for (POIXMLDocumentPart part: getRelations()) { - if (!(part instanceof XDGFMasterContents)) - continue; - //throw new POIXMLException("Unexpected page relation: " + part); - - XDGFMaster master = ((XDGFMasterContents)part).getMaster(); - _masters.put(master.getID(), master); - } - - super.onDocumentRead(); - - for (XDGFShape shape: _shapes.values()) { - if (shape.isTopmost()) - shape.setupMaster(this, null); - } - - } catch (POIXMLException e) { - throw XDGFException.wrap(this, e); - } - } - - /** - * @return Parent page - */ - public XDGFPage getPage() { - return _page; - } - - protected void setPage(XDGFPage page) { - _page = page; - } - - public XDGFMaster getMasterById(long id) { - return _masters.get(id); - } -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFPageSheet.java b/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFPageSheet.java deleted file mode 100644 index 1d27969fe..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFPageSheet.java +++ /dev/null @@ -1,36 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xdgf.usermodel; - -import com.microsoft.schemas.office.visio.x2012.main.PageSheetType; - -public class XDGFPageSheet extends XDGFSheet { - - PageSheetType _pageSheet; - - public XDGFPageSheet(PageSheetType sheet, XDGFDocument document) { - super(sheet, document); - _pageSheet = sheet; - } - - @Override - PageSheetType getXmlObject() { - return _pageSheet; - } - -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFPages.java b/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFPages.java deleted file mode 100644 index 0ae3a039a..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFPages.java +++ /dev/null @@ -1,101 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xdgf.usermodel; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.POIXMLException; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.util.Internal; -import org.apache.poi.xdgf.exceptions.XDGFException; -import org.apache.poi.xdgf.xml.XDGFXMLDocumentPart; -import org.apache.xmlbeans.XmlException; - -import com.microsoft.schemas.office.visio.x2012.main.PageType; -import com.microsoft.schemas.office.visio.x2012.main.PagesDocument; -import com.microsoft.schemas.office.visio.x2012.main.PagesType; - - -/** - * Contains a list of Page objects (not page content!) - */ -public class XDGFPages extends XDGFXMLDocumentPart { - - PagesType _pagesObject; - - // ordered by page number - List _pages = new ArrayList(); - - /** - * @since POI 3.14-Beta1 - */ - public XDGFPages(PackagePart part, XDGFDocument document) { - super(part, document); - } - - @Internal - PagesType getXmlObject() { - return _pagesObject; - } - - @Override - protected void onDocumentRead() { - try { - try { - _pagesObject = PagesDocument.Factory.parse(getPackagePart().getInputStream()).getPages(); - } catch (XmlException e) { - throw new POIXMLException(e); - } catch (IOException e) { - throw new POIXMLException(e); - } - - // this iteration is ordered by page number - for (PageType pageSettings: _pagesObject.getPageArray()) { - - String relId = pageSettings.getRel().getId(); - - POIXMLDocumentPart pageContentsPart = getRelationById(relId); - if (pageContentsPart == null) - throw new POIXMLException("PageSettings relationship for " + relId + " not found"); - - if (!(pageContentsPart instanceof XDGFPageContents)) - throw new POIXMLException("Unexpected pages relationship for " + relId + ": " + pageContentsPart); - - XDGFPageContents contents = (XDGFPageContents)pageContentsPart; - XDGFPage page = new XDGFPage(pageSettings, contents, _document, this); - - contents.onDocumentRead(); - - _pages.add(page); - } - - } catch (POIXMLException e) { - throw XDGFException.wrap(this, e); - } - } - - /** - * @return A list of pages ordered by page number - */ - public List getPageList() { - return Collections.unmodifiableList(_pages); - } -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFRelation.java b/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFRelation.java deleted file mode 100644 index 3ab1f91d3..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFRelation.java +++ /dev/null @@ -1,84 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xdgf.usermodel; - -import java.util.HashMap; -import java.util.Map; - -import org.apache.poi.POIXMLRelation; -import org.apache.poi.openxml4j.opc.PackageRelationshipTypes; -import org.apache.poi.xdgf.xml.XDGFXMLDocumentPart; - -public class XDGFRelation extends POIXMLRelation { - - /** - * A map to lookup POIXMLRelation by its relation type - */ - private static final Map _table = new HashMap(); - - public static final XDGFRelation DOCUMENT = new XDGFRelation( - "application/vnd.ms-visio.drawing.main+xml", - PackageRelationshipTypes.VISIO_CORE_DOCUMENT, - "/visio/document.xml", null); - - public static final XDGFRelation MASTERS = new XDGFRelation( - "application/vnd.ms-visio.masters+xml", - "http://schemas.microsoft.com/visio/2010/relationships/masters", - "/visio/masters/masters.xml", XDGFMasters.class); - - public static final XDGFRelation MASTER = new XDGFRelation( - "application/vnd.ms-visio.master+xml", - "http://schemas.microsoft.com/visio/2010/relationships/master", - "/visio/masters/master#.xml", XDGFMasterContents.class); - - public static final XDGFRelation IMAGES = new XDGFRelation(null, - PackageRelationshipTypes.IMAGE_PART, null, null // XSSFPictureData.class - ); - - public static final XDGFRelation PAGES = new XDGFRelation( - "application/vnd.ms-visio.pages+xml", - "http://schemas.microsoft.com/visio/2010/relationships/pages", - "/visio/pages/pages.xml", XDGFPages.class); - - public static final XDGFRelation PAGE = new XDGFRelation( - "application/vnd.ms-visio.page+xml", - "http://schemas.microsoft.com/visio/2010/relationships/page", - "/visio/pages/page#.xml", XDGFPageContents.class); - - public static final XDGFRelation WINDOW = new XDGFRelation( - "application/vnd.ms-visio.windows+xml", - "http://schemas.microsoft.com/visio/2010/relationships/windows", - "/visio/windows.xml", null); - - private XDGFRelation(String type, String rel, String defaultName, Class cls) { - super(type, rel, defaultName, cls); - _table.put(rel, this); - } - - /** - * Get POIXMLRelation by relation type - * - * @param rel - * relation type, for example, - * http://schemas.openxmlformats.org/officeDocument/2006/relationships/image - * @return registered POIXMLRelation or null if not found - */ - public static XDGFRelation getInstance(String rel) { - return _table.get(rel); - } -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFShape.java b/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFShape.java deleted file mode 100644 index 42deac4c2..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFShape.java +++ /dev/null @@ -1,932 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xdgf.usermodel; - -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Stroke; -import java.awt.geom.AffineTransform; -import java.awt.geom.Path2D; -import java.awt.geom.Rectangle2D; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Map.Entry; - -import org.apache.poi.POIXMLException; -import org.apache.poi.util.Internal; -import org.apache.poi.xdgf.exceptions.XDGFException; -import org.apache.poi.xdgf.usermodel.section.CombinedIterable; -import org.apache.poi.xdgf.usermodel.section.GeometrySection; -import org.apache.poi.xdgf.usermodel.section.XDGFSection; -import org.apache.poi.xdgf.usermodel.shape.ShapeVisitor; -import org.apache.poi.xdgf.usermodel.shape.exceptions.StopVisitingThisBranch; - -import com.microsoft.schemas.office.visio.x2012.main.ShapeSheetType; -import com.microsoft.schemas.office.visio.x2012.main.TextType; - -/** - * A shape is a collection of Geometry Visualization, Format, Text, Images, and - * Shape Data in a Drawing Page. - */ -public class XDGFShape extends XDGFSheet { - - XDGFBaseContents _parentPage; - XDGFShape _parent; // only non-null if a subshape - - XDGFMaster _master = null; - XDGFShape _masterShape = null; - - XDGFText _text = null; - - // subshapes if they exist - List _shapes = null; - - // properties specific to shapes - - // center of rotation relative to origin of parent - Double _pinX = null; - Double _pinY = null; - - Double _width = null; - Double _height = null; - - // center of rotation relative to self - Double _locPinX = null; - Double _locPinY = null; - - // start x coordinate, relative to parent - // -> one dimensional shapes only - Double _beginX = null; - Double _beginY = null; - - // end x coordinate, relative to parent - // -> one dimensional shapes only - Double _endX = null; - Double _endY = null; - - Double _angle = null; - Double _rotationXAngle = null; - Double _rotationYAngle = null; - Double _rotationZAngle = null; - - // end x coordinate, relative to parent - Boolean _flipX = null; - Boolean _flipY = null; - - // center of text relative to this shape - Double _txtPinX = null; - Double _txtPinY = null; - - // center of text relative to text block - Double _txtLocPinX = null; - Double _txtLocPinY = null; - - Double _txtAngle = null; - - Double _txtWidth = null; - Double _txtHeight = null; - - public XDGFShape(ShapeSheetType shapeSheet, XDGFBaseContents parentPage, - XDGFDocument document) { - this(null, shapeSheet, parentPage, document); - } - - public XDGFShape(XDGFShape parent, ShapeSheetType shapeSheet, - XDGFBaseContents parentPage, XDGFDocument document) { - - super(shapeSheet, document); - - _parent = parent; - _parentPage = parentPage; - - TextType text = shapeSheet.getText(); - if (text != null) - _text = new XDGFText(text, this); - - if (shapeSheet.isSetShapes()) { - _shapes = new ArrayList(); - for (ShapeSheetType shape : shapeSheet.getShapes().getShapeArray()) - _shapes.add(new XDGFShape(this, shape, parentPage, document)); - } - - readProperties(); - } - - @Override - public String toString() { - if (_parentPage instanceof XDGFMasterContents) - return _parentPage + ": "; - else - return ""; - } - - protected void readProperties() { - - _pinX = XDGFCell.maybeGetDouble(_cells, "PinX"); - _pinY = XDGFCell.maybeGetDouble(_cells, "PinY"); - _width = XDGFCell.maybeGetDouble(_cells, "Width"); - _height = XDGFCell.maybeGetDouble(_cells, "Height"); - _locPinX = XDGFCell.maybeGetDouble(_cells, "LocPinX"); - _locPinY = XDGFCell.maybeGetDouble(_cells, "LocPinY"); - _beginX = XDGFCell.maybeGetDouble(_cells, "BeginX"); - _beginY = XDGFCell.maybeGetDouble(_cells, "BeginY"); - _endX = XDGFCell.maybeGetDouble(_cells, "EndX"); - _endY = XDGFCell.maybeGetDouble(_cells, "EndY"); - - _angle = XDGFCell.maybeGetDouble(_cells, "Angle"); - _rotationXAngle = XDGFCell.maybeGetDouble(_cells, "RotationXAngle"); - _rotationYAngle = XDGFCell.maybeGetDouble(_cells, "RotationYAngle"); - _rotationZAngle = XDGFCell.maybeGetDouble(_cells, "RotationZAngle"); - - _flipX = XDGFCell.maybeGetBoolean(_cells, "FlipX"); - _flipY = XDGFCell.maybeGetBoolean(_cells, "FlipY"); - - _txtPinX = XDGFCell.maybeGetDouble(_cells, "TxtPinX"); - _txtPinY = XDGFCell.maybeGetDouble(_cells, "TxtPinY"); - _txtLocPinX = XDGFCell.maybeGetDouble(_cells, "TxtLocPinX"); - _txtLocPinY = XDGFCell.maybeGetDouble(_cells, "TxtLocPinY"); - _txtWidth = XDGFCell.maybeGetDouble(_cells, "TxtWidth"); - _txtHeight = XDGFCell.maybeGetDouble(_cells, "TxtHeight"); - - _txtAngle = XDGFCell.maybeGetDouble(_cells, "TxtAngle"); - } - - /** - * Setup top level shapes - * - * Shapes that have a 'Master' attribute refer to a specific master in the - * page, whereas shapes with a 'MasterShape' attribute refer to a subshape - * of a Master. - */ - protected void setupMaster(XDGFPageContents pageContents, - XDGFMasterContents master) { - - ShapeSheetType obj = getXmlObject(); - - if (obj.isSetMaster()) { - _master = pageContents.getMasterById(obj.getMaster()); - if (_master == null) - throw XDGFException.error("refers to non-existant master " - + obj.getMaster(), this); - - /* - * If a master has one top-level shape, a shape that inherits from - * that master inherits the descendant elements of that master - * shape. If a master has more than one master shape, a shape that - * inherits from that master inherits those master shapes as - * subshapes. - */ - - Collection masterShapes = _master.getContent() - .getTopLevelShapes(); - - switch (masterShapes.size()) { - case 0: - throw XDGFException - .error("Could not retrieve master shape from " - + _master, this); - case 1: - _masterShape = masterShapes.iterator().next(); - break; - default: - break; - } - - } else if (obj.isSetMasterShape()) { - _masterShape = master.getShapeById(obj.getMasterShape()); - if (_masterShape == null) - throw XDGFException.error( - "refers to non-existant master shape " - + obj.getMasterShape(), this); - - } - - setupSectionMasters(); - - if (_shapes != null) { - for (XDGFShape shape : _shapes) { - shape.setupMaster(pageContents, _master == null ? master - : _master.getContent()); - } - } - } - - protected void setupSectionMasters() { - - if (_masterShape == null) - return; - - try { - for (Entry section : _sections.entrySet()) { - XDGFSection master = _masterShape.getSection(section.getKey()); - if (master != null) - section.getValue().setupMaster(master); - } - - for (Entry section : _geometry.entrySet()) { - GeometrySection master = _masterShape.getGeometryByIdx(section - .getKey()); - if (master != null) - section.getValue().setupMaster(master); - } - } catch (POIXMLException e) { - throw XDGFException.wrap(this.toString(), e); - } - } - - @Override - @Internal - public ShapeSheetType getXmlObject() { - return (ShapeSheetType) _sheet; - } - - public long getID() { - return getXmlObject().getID(); - } - - public String getType() { - return getXmlObject().getType(); - } - - public String getTextAsString() { - XDGFText text = getText(); - if (text == null) - return ""; - - return text.getTextContent(); - } - - public boolean hasText() { - return _text != null - || (_masterShape != null && _masterShape._text != null); - } - - @Override - public XDGFCell getCell(String cellName) { - XDGFCell _cell = super.getCell(cellName); - - // if not found, ask the master - if (_cell == null && _masterShape != null) { - _cell = _masterShape.getCell(cellName); - } - - return _cell; - } - - public GeometrySection getGeometryByIdx(long idx) { - return _geometry.get(idx); - } - - /** - * Only available if this shape is a shape group, may be null - */ - // -> May be null - public List getShapes() { - return _shapes; - } - - // unique to this shape on the page? - public String getName() { - String name = getXmlObject().getName(); - if (name == null) - return ""; - return name; - } - - // unique to this shape on the page? - public String getShapeType() { - String type = getXmlObject().getType(); - if (type == null) - return ""; - return type; - } - - // name of the symbol that this was derived from - public String getSymbolName() { - - if (_master == null) - return ""; - - String name = _master.getName(); - if (name == null) - return ""; - - return name; - } - - public XDGFShape getMasterShape() { - return _masterShape; - } - - /** - * @return The parent shape if this is a subshape, null otherwise - */ - public XDGFShape getParentShape() { - return _parent; - } - - public XDGFShape getTopmostParentShape() { - XDGFShape top = null; - if (_parent != null) { - top = _parent.getTopmostParentShape(); - if (top == null) - top = _parent; - } - - return top; - } - - public boolean hasMaster() { - return _master != null; - } - - public boolean hasMasterShape() { - return _masterShape != null; - } - - public boolean hasParent() { - return _parent != null; - } - - public boolean hasShapes() { - return _shapes != null; - } - - public boolean isTopmost() { - return _parent == null; - } - - public boolean isShape1D() { - return getBeginX() != null; - } - - public boolean isDeleted() { - return getXmlObject().isSetDel() ? getXmlObject().getDel() : false; - } - - public XDGFText getText() { - if (_text == null && _masterShape != null) - return _masterShape.getText(); - - return _text; - } - - public Double getPinX() { - if (_pinX == null && _masterShape != null) - return _masterShape.getPinX(); - - if (_pinX == null) - throw XDGFException.error("PinX not set!", this); - - return _pinX; - } - - public Double getPinY() { - if (_pinY == null && _masterShape != null) - return _masterShape.getPinY(); - - if (_pinY == null) - throw XDGFException.error("PinY not specified!", this); - - return _pinY; - } - - public Double getWidth() { - if (_width == null && _masterShape != null) - return _masterShape.getWidth(); - - if (_width == null) - throw XDGFException.error("Width not specified!", this); - - return _width; - } - - public Double getHeight() { - if (_height == null && _masterShape != null) - return _masterShape.getHeight(); - - if (_height == null) - throw XDGFException.error("Height not specified!", this); - - return _height; - } - - public Double getLocPinX() { - if (_locPinX == null && _masterShape != null) - return _masterShape.getLocPinX(); - - if (_locPinX == null) - throw XDGFException.error("LocPinX not specified!", this); - - return _locPinX; - } - - public Double getLocPinY() { - if (_locPinY == null && _masterShape != null) - return _masterShape.getLocPinY(); - - if (_locPinY == null) - throw XDGFException.error("LocPinY not specified!", this); - - return _locPinY; - } - - public Double getBeginX() { - if (_beginX == null && _masterShape != null) - return _masterShape.getBeginX(); - - return _beginX; - } - - public Double getBeginY() { - if (_beginY == null && _masterShape != null) - return _masterShape.getBeginY(); - - return _beginY; - } - - public Double getEndX() { - if (_endX == null && _masterShape != null) - return _masterShape.getEndX(); - - return _endX; - } - - public Double getEndY() { - if (_endY == null && _masterShape != null) - return _masterShape.getEndY(); - - return _endY; - } - - public Double getAngle() { - if (_angle == null && _masterShape != null) - return _masterShape.getAngle(); - - return _angle; - } - - public Boolean getFlipX() { - if (_flipX == null && _masterShape != null) - return _masterShape.getFlipX(); - - return _flipX; - } - - public Boolean getFlipY() { - if (_flipY == null && _masterShape != null) - return _masterShape.getFlipY(); - - return _flipY; - } - - public Double getTxtPinX() { - if (_txtPinX == null && _masterShape != null - && _masterShape._txtPinX != null) - return _masterShape._txtPinX; - - if (_txtPinX == null) - return getWidth() * 0.5; - - return _txtPinX; - } - - public Double getTxtPinY() { - if (_txtLocPinY == null && _masterShape != null - && _masterShape._txtLocPinY != null) - return _masterShape._txtLocPinY; - - if (_txtPinY == null) - return getHeight() * 0.5; - - return _txtPinY; - } - - public Double getTxtLocPinX() { - if (_txtLocPinX == null && _masterShape != null - && _masterShape._txtLocPinX != null) - return _masterShape._txtLocPinX; - - if (_txtLocPinX == null) - return getTxtWidth() * 0.5; - - return _txtLocPinX; - } - - public Double getTxtLocPinY() { - if (_txtLocPinY == null && _masterShape != null - && _masterShape._txtLocPinY != null) - return _masterShape._txtLocPinY; - - if (_txtLocPinY == null) - return getTxtHeight() * 0.5; - - return _txtLocPinY; - } - - public Double getTxtAngle() { - if (_txtAngle == null && _masterShape != null) - return _masterShape.getTxtAngle(); - - return _txtAngle; - } - - public Double getTxtWidth() { - if (_txtWidth == null && _masterShape != null - && _masterShape._txtWidth != null) - return _masterShape._txtWidth; - - if (_txtWidth == null) - return getWidth(); - - return _txtWidth; - } - - public Double getTxtHeight() { - if (_txtHeight == null && _masterShape != null - && _masterShape._txtHeight != null) - return _masterShape._txtHeight; - - if (_txtHeight == null) - return getHeight(); - - return _txtHeight; - } - - @Override - public Integer getLineCap() { - - Integer lineCap = super.getLineCap(); - if (lineCap != null) - return lineCap; - - // get from master - if (_masterShape != null) { - return _masterShape.getLineCap(); - } - - // get default - return _document.getDefaultLineStyle().getLineCap(); - } - - @Override - public Color getLineColor() { - - Color lineColor = super.getLineColor(); - if (lineColor != null) - return lineColor; - - // get from master - if (_masterShape != null) { - return _masterShape.getLineColor(); - } - - // get default - return _document.getDefaultLineStyle().getLineColor(); - } - - @Override - public Integer getLinePattern() { - - Integer linePattern = super.getLinePattern(); - if (linePattern != null) - return linePattern; - - // get from master - if (_masterShape != null) { - return _masterShape.getLinePattern(); - } - - // get default - return _document.getDefaultLineStyle().getLinePattern(); - } - - @Override - public Double getLineWeight() { - - Double lineWeight = super.getLineWeight(); - if (lineWeight != null) - return lineWeight; - - // get from master - if (_masterShape != null) { - return _masterShape.getLineWeight(); - } - - // get default - return _document.getDefaultLineStyle().getLineWeight(); - } - - @Override - public Color getFontColor() { - - Color fontColor = super.getFontColor(); - if (fontColor != null) - return fontColor; - - // get from master - if (_masterShape != null) { - return _masterShape.getFontColor(); - } - - // get default - return _document.getDefaultTextStyle().getFontColor(); - } - - @Override - public Double getFontSize() { - - Double fontSize = super.getFontSize(); - if (fontSize != null) - return fontSize; - - // get from master - if (_masterShape != null) { - return _masterShape.getFontSize(); - } - - // get default - return _document.getDefaultTextStyle().getFontSize(); - } - - public Stroke getStroke() { - - float lineWeight = getLineWeight().floatValue(); - int cap; - int join = BasicStroke.JOIN_MITER; - float miterlimit = 10.0f; - - switch (getLineCap()) { - case 0: - cap = BasicStroke.CAP_ROUND; - break; - case 1: - cap = BasicStroke.CAP_SQUARE; - break; - case 2: - cap = BasicStroke.CAP_BUTT; // TODO: what does extended mean? - break; - default: - throw new POIXMLException("Invalid line cap specified"); - } - - float[] dash = null; - - // these line patterns are just approximations - switch (getLinePattern()) { - case 0: // transparent - break; - case 1: // solid - break; - case 2: - dash = new float[] { 5, 3 }; - break; - case 3: - dash = new float[] { 1, 4 }; - break; - case 4: - dash = new float[] { 6, 3, 1, 3 }; - break; - case 5: - dash = new float[] { 6, 3, 1, 3, 1, 3 }; - break; - case 6: - dash = new float[] { 1, 3, 6, 3, 6, 3 }; - break; - case 7: - dash = new float[] { 15, 3, 6, 3 }; - break; - case 8: - dash = new float[] { 6, 3, 6, 3 }; - break; - case 9: - dash = new float[] { 3, 2 }; - break; - case 10: - dash = new float[] { 1, 2 }; - break; - case 11: - dash = new float[] { 3, 2, 1, 2 }; - break; - case 12: - dash = new float[] { 3, 2, 1, 2, 1 }; - break; - case 13: - dash = new float[] { 1, 2, 3, 2, 3, 2 }; - break; - case 14: - dash = new float[] { 3, 2, 7, 2 }; - break; - case 15: - dash = new float[] { 7, 2, 3, 2, 3, 2 }; - break; - case 16: - dash = new float[] { 12, 6 }; - break; - case 17: - dash = new float[] { 1, 6 }; - break; - case 18: - dash = new float[] { 1, 6, 12, 6 }; - break; - case 19: - dash = new float[] { 1, 6, 1, 6, 12, 6 }; - break; - case 20: - dash = new float[] { 1, 6, 12, 6, 12, 6 }; - break; - case 21: - dash = new float[] { 30, 6, 12, 6 }; - break; - case 22: - dash = new float[] { 30, 6, 12, 6, 12, 6 }; - break; - case 23: - dash = new float[] { 1 }; - break; - case 254: - throw new POIXMLException("Unsupported line pattern value"); - default: - throw new POIXMLException("Invalid line pattern value"); - } - - // dashes are in units of line width - if (dash != null) { - for (int i = 0; i < dash.length; i++) { - dash[i] *= lineWeight; - } - } - - return new BasicStroke(lineWeight, cap, join, miterlimit, dash, 0); - } - - // - // Geometry - // - - public Iterable getGeometrySections() { - return new CombinedIterable(_geometry, - _masterShape != null ? _masterShape._geometry : null); - } - - /** - * @return rectangle in local coordinates - */ - public Rectangle2D.Double getBounds() { - return new Rectangle2D.Double(0, 0, getWidth(), getHeight()); - } - - /** - * @return returns bounds as a path in local coordinates, which is - * userful if you need to transform to global coordinates - * - * Warning: Don't use this for 1d objects, and will fail for - * infinite line objects - */ - public Path2D.Double getBoundsAsPath() { - - Double w = getWidth(); - Double h = getHeight(); - - Path2D.Double bounds = new Path2D.Double(); - bounds.moveTo(0, 0); - bounds.lineTo(w, 0); - bounds.lineTo(w, h); - bounds.lineTo(0, h); - bounds.lineTo(0, 0); - - return bounds; - } - - /** - * @return The outline of the shape in local coordinates - */ - public Path2D.Double getPath() { - for (GeometrySection geoSection : getGeometrySections()) { - if (geoSection.getNoShow() == true) - continue; - - return geoSection.getPath(this); - } - - return null; - } - - /* - * Returns true if the shape has a drawable geometry associated with it - */ - public boolean hasGeometry() { - for (GeometrySection geoSection : getGeometrySections()) { - if (geoSection.getNoShow() == false) - return true; - } - return false; - } - - /** - * Returns a transform that can translate shape-local coordinates to the - * coordinates of its parent shape - */ - protected AffineTransform getParentTransform() { - // TODO: There's probably a better way to do this - AffineTransform tr = new AffineTransform(); - - Double locX = getLocPinX(); - Double locY = getLocPinY(); - Boolean flipX = getFlipX(); - Boolean flipY = getFlipY(); - Double angle = getAngle(); - - tr.translate(-locX, -locY); - - tr.translate(getPinX(), getPinY()); - - // rotate about the origin - if (angle != null && Math.abs(angle) > 0.001) { - tr.rotate(angle, locX, locY); - } - - // flip if necessary - - if (flipX != null && flipX) { - tr.scale(-1, 1); - tr.translate(-getWidth(), 0); - } - - if (flipY != null && flipY) { - tr.scale(1, -1); - tr.translate(0, -getHeight()); - } - - return tr; - } - - /** - * The visitor will first visit this shape, then it's children - * - * This is useful because exceptions will be marked with the shapes as it - * propagates up the shape hierarchy. - */ - public void visitShapes(ShapeVisitor visitor, AffineTransform tr, int level) { - - tr = (AffineTransform) tr.clone(); - tr.concatenate(getParentTransform()); - - try { - if (visitor.accept(this)) - visitor.visit(this, tr, level); - - if (_shapes != null) { - for (XDGFShape shape : _shapes) { - shape.visitShapes(visitor, tr, level + 1); - } - } - } catch (StopVisitingThisBranch e) { - // intentionally empty - } catch (POIXMLException e) { - throw XDGFException.wrap(this.toString(), e); - } - } - - /** - * The visitor will first visit this shape, then it's children. No transform - * is calculated for this visit - * - * This is useful because exceptions will be marked with the shapes as it - * propagates up the shape hierarchy. - */ - public void visitShapes(ShapeVisitor visitor, int level) { - - try { - if (visitor.accept(this)) - visitor.visit(this, null, level); - - if (_shapes != null) { - for (XDGFShape shape : _shapes) { - shape.visitShapes(visitor, level + 1); - } - } - } catch (StopVisitingThisBranch e) { - // intentionally empty - } catch (POIXMLException e) { - throw XDGFException.wrap(this.toString(), e); - } - } - -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFSheet.java b/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFSheet.java deleted file mode 100644 index 1cc807fdf..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFSheet.java +++ /dev/null @@ -1,208 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xdgf.usermodel; - -import java.awt.Color; -import java.util.HashMap; -import java.util.Map; -import java.util.SortedMap; -import java.util.TreeMap; - -import org.apache.poi.POIXMLException; -import org.apache.poi.xdgf.exceptions.XDGFException; -import org.apache.poi.xdgf.usermodel.section.CharacterSection; -import org.apache.poi.xdgf.usermodel.section.GeometrySection; -import org.apache.poi.xdgf.usermodel.section.XDGFSection; - -import com.microsoft.schemas.office.visio.x2012.main.CellType; -import com.microsoft.schemas.office.visio.x2012.main.SectionType; -import com.microsoft.schemas.office.visio.x2012.main.SheetType; - -/** - * A sheet is a collection of properties that specify information for a shape, - * master, drawing page, style, or web drawing. - */ -public abstract class XDGFSheet { - - protected XDGFDocument _document; - protected SheetType _sheet; - - // cells - protected Map _cells = new HashMap(); - - // sections - protected Map _sections = new HashMap(); - - // special: geometry sections (key: index, value: section) - protected SortedMap _geometry = new TreeMap(); - - // special: character section - protected CharacterSection _character = null; - - public XDGFSheet(SheetType sheet, XDGFDocument document) { - try { - _sheet = sheet; - _document = document; - - for (CellType cell: sheet.getCellArray()) { - if (_cells.containsKey(cell.getN())) - throw new POIXMLException("Unexpected duplicate cell " + cell.getN()); // this shouldn't happen - - _cells.put(cell.getN(), new XDGFCell(cell)); - } - - // only geometry sections can have duplicate names - // sections can be found in the master too, if there are no attributes here! - - // no idea if I have a master in this space. go figure. - - for (SectionType section: sheet.getSectionArray()) { - String name = section.getN(); - if (name.equals("Geometry")) { - _geometry.put(section.getIX(), new GeometrySection(section, this)); - } else if (name.equals("Character")) { - _character = new CharacterSection(section, this); - } else { - _sections.put(name, XDGFSection.load(section, this)); - } - } - } catch (POIXMLException e) { - throw XDGFException.wrap(this.toString(), e); - } - } - - abstract SheetType getXmlObject(); - - public XDGFDocument getDocument() { - return _document; - } - - /** - * A cell is really just a setting - * - * @param cellName The particular setting you want - */ - public XDGFCell getCell(String cellName) { - return _cells.get(cellName); - } - - public XDGFSection getSection(String sectionName) { - return _sections.get(sectionName); - } - - public XDGFStyleSheet getLineStyle() { - if (!_sheet.isSetLineStyle()) - return null; - - return _document.getStyleById(_sheet.getLineStyle()); - } - - public XDGFStyleSheet getFillStyle() { - if (!_sheet.isSetFillStyle()) - return null; - - return _document.getStyleById(_sheet.getFillStyle()); - } - - public XDGFStyleSheet getTextStyle() { - if (!_sheet.isSetTextStyle()) - return null; - - return _document.getStyleById(_sheet.getTextStyle()); - } - - public Color getFontColor() { - Color fontColor = null; - - if (_character != null) { - fontColor = _character.getFontColor(); - if (fontColor != null) - return fontColor; - } - - XDGFStyleSheet style = getTextStyle(); - if (style != null) - return style.getFontColor(); - - return null; - } - - public Double getFontSize() { - Double fontSize = null; - - if (_character != null) { - fontSize = _character.getFontSize(); - if (fontSize != null) - return fontSize; - } - - XDGFStyleSheet style = getTextStyle(); - if (style != null) - return style.getFontSize(); - - return null; - } - - public Integer getLineCap() { - Integer lineCap = XDGFCell.maybeGetInteger(_cells, "LineCap"); - if (lineCap != null) - return lineCap; - - XDGFStyleSheet style = getLineStyle(); - if (style != null) - return style.getLineCap(); - - return null; - } - - public Color getLineColor() { - String lineColor = XDGFCell.maybeGetString(_cells, "LineColor"); - if (lineColor != null) - return Color.decode(lineColor); - - XDGFStyleSheet style = getLineStyle(); - if (style != null) - return style.getLineColor(); - - return null; - } - - public Integer getLinePattern() { - Integer linePattern = XDGFCell.maybeGetInteger(_cells, "LinePattern"); - if (linePattern != null) - return linePattern; - - XDGFStyleSheet style = getLineStyle(); - if (style != null) - return style.getLinePattern(); - - return null; - } - - public Double getLineWeight() { - Double lineWeight = XDGFCell.maybeGetDouble(_cells, "LineWeight"); - if (lineWeight != null) - return lineWeight; - - XDGFStyleSheet style = getLineStyle(); - if (style != null) - return style.getLineWeight(); - - return null; - } -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFStyleSheet.java b/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFStyleSheet.java deleted file mode 100644 index 50f61842b..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFStyleSheet.java +++ /dev/null @@ -1,36 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xdgf.usermodel; - -import org.apache.poi.util.Internal; - -import com.microsoft.schemas.office.visio.x2012.main.StyleSheetType; - -public class XDGFStyleSheet extends XDGFSheet { - - public XDGFStyleSheet(StyleSheetType styleSheet, XDGFDocument document) { - super(styleSheet, document); - } - - @Override - @Internal - public StyleSheetType getXmlObject() { - return (StyleSheetType) _sheet; - } - -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFText.java b/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFText.java deleted file mode 100644 index f3b24f905..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/usermodel/XDGFText.java +++ /dev/null @@ -1,166 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xdgf.usermodel; - -import java.awt.Font; -import java.awt.Graphics2D; -import java.awt.font.FontRenderContext; -import java.awt.font.TextLayout; -import java.awt.geom.AffineTransform; -import java.awt.geom.Path2D; -import java.awt.geom.Point2D; -import java.awt.geom.Rectangle2D; - -import org.apache.poi.util.Internal; - -import com.microsoft.schemas.office.visio.x2012.main.TextType; -import com.microsoft.schemas.office.visio.x2012.main.impl.TextTypeImpl; - -public class XDGFText { - - TextType _text; - XDGFShape _parent; - - public XDGFText(TextType text, XDGFShape parent) { - _text = text; - _parent = parent; - } - - @Internal - TextType getXmlObject() { - return _text; - } - - public String getTextContent() { - // casting here is wrong, but there's no other way of getting the value, - // as it doesn't seem to be exposed by complex types (even though this - // is a mixed type) - return ((TextTypeImpl) _text).getStringValue(); - } - - /** - * These are in the shape coordinate system - * - * @see Text Block Coordinate System docs - */ - public Rectangle2D.Double getTextBounds() { - - double txtPinX = _parent.getTxtPinX(); - double txtPinY = _parent.getTxtPinY(); - - double txtLocPinX = _parent.getTxtLocPinX(); - double txtLocPinY = _parent.getTxtLocPinY(); - - double txtWidth = _parent.getTxtWidth(); - double txtHeight = _parent.getTxtHeight(); - - double x = txtPinX - txtLocPinX; - double y = txtPinY - txtLocPinY; - - return new Rectangle2D.Double(x, y, txtWidth, txtHeight); - } - - /** - * @return Text bounds as a path in local coordinates, which is useful - * if you need to transform to global coordinates - */ - public Path2D.Double getBoundsAsPath() { - - Rectangle2D.Double rect = getTextBounds(); - Double w = rect.getWidth(); - Double h = rect.getHeight(); - - Path2D.Double bounds = new Path2D.Double(); - bounds.moveTo(0, 0); - bounds.lineTo(w, 0); - bounds.lineTo(w, h); - bounds.lineTo(0, h); - bounds.lineTo(0, 0); - - return bounds; - } - - /** - * @return Center of text in local coordinates - */ - public Point2D.Double getTextCenter() { - return new Point2D.Double(_parent.getTxtLocPinX(), - _parent.getTxtLocPinY()); - } - - /** - * When calling this to draw text, it assumes graphics is set properly - * to draw in the right style. - */ - public void draw(Graphics2D graphics) { - - String textContent = getTextContent(); - if (textContent.length() == 0) - return; - - Rectangle2D.Double bounds = getTextBounds(); - - String[] lines = textContent.trim().split("\n"); - FontRenderContext frc = graphics.getFontRenderContext(); - Font font = graphics.getFont(); - - AffineTransform oldTr = graphics.getTransform(); - - // visio is in flipped coordinates, so translate the text to be in the - // right place - Boolean flipX = _parent.getFlipX(); - Boolean flipY = _parent.getFlipY(); - - if (flipY == null || !_parent.getFlipY()) { - graphics.translate(bounds.x, bounds.y); - graphics.scale(1, -1); - graphics.translate(0, -bounds.height - + graphics.getFontMetrics().getMaxCharBounds(graphics) - .getHeight()); - } - - if (flipX != null && _parent.getFlipX()) { - graphics.scale(-1, 1); - graphics.translate(-bounds.width, 0); - } - - Double txtAngle = _parent.getTxtAngle(); - if (txtAngle != null && Math.abs(txtAngle) > 0.01) - graphics.rotate(txtAngle); - - float nextY = 0; - for (String line : lines) { - - if (line.length() == 0) - continue; - - TextLayout layout = new TextLayout(line, font, frc); - - if (layout.isLeftToRight()) - layout.draw(graphics, 0, nextY); - else - layout.draw(graphics, - (float) (bounds.width - layout.getAdvance()), nextY); - - nextY += layout.getAscent() + layout.getDescent() - + layout.getLeading(); - } - - graphics.setTransform(oldTr); - } -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/usermodel/XmlVisioDocument.java b/src/ooxml/java/org/apache/poi/xdgf/usermodel/XmlVisioDocument.java deleted file mode 100644 index 879487404..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/usermodel/XmlVisioDocument.java +++ /dev/null @@ -1,134 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xdgf.usermodel; - -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import org.apache.poi.POIXMLDocument; -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.POIXMLException; -import org.apache.poi.openxml4j.exceptions.OpenXML4JException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.opc.PackageRelationshipTypes; -import org.apache.poi.util.PackageHelper; -import org.apache.xmlbeans.XmlException; - -import com.microsoft.schemas.office.visio.x2012.main.VisioDocumentDocument1; -import com.microsoft.schemas.office.visio.x2012.main.VisioDocumentType; - -/** - * This is your high-level starting point for working with Visio XML - * documents (.vsdx). - * - * Currently, only read support has been implemented, and the API is - * not mature and is subject to change. - * - * For more information about the visio XML format (with an XSD 1.0 - * schema), you can find documentation at - * https://msdn.microsoft.com/en-us/library/hh645006(v=office.12).aspx - * - * That document lacks in some areas, but you can find additional - * documentation and an updated XSD 1.1 schema at - * https://msdn.microsoft.com/en-us/library/office/jj684209(v=office.15).aspx - * - * Each provides different details, but the SharePoint reference - * has better documentation and is more useful. - */ -public class XmlVisioDocument extends POIXMLDocument { - - protected XDGFPages _pages; - protected XDGFMasters _masters; - protected XDGFDocument _document; - - public XmlVisioDocument(OPCPackage pkg) throws IOException { - super(pkg, PackageRelationshipTypes.VISIO_CORE_DOCUMENT); - - VisioDocumentType document; - - try { - document = VisioDocumentDocument1.Factory.parse(getPackagePart().getInputStream()).getVisioDocument(); - } catch (XmlException e) { - throw new POIXMLException(e); - } catch (IOException e) { - throw new POIXMLException(e); - } - - _document = new XDGFDocument(document); - - //build a tree of POIXMLDocumentParts, this document being the root - load(new XDGFFactory(_document)); - } - - public XmlVisioDocument(InputStream is) throws IOException { - this(PackageHelper.open(is)); - } - - @Override - protected void onDocumentRead() throws IOException { - - // by the time this gets called, all other document parts should - // have been loaded, so it's safe to build the document structure - - // note that in other onDocumentRead(), relations/etc may not have - // loaded yet, so it's not quite safe - - for (POIXMLDocumentPart part : getRelations()) { - - // organize the document pieces - if (part instanceof XDGFPages) - _pages = (XDGFPages) part; - - else if (part instanceof XDGFMasters) - _masters = (XDGFMasters) part; - } - - if (_masters != null) - _masters.onDocumentRead(); - - _pages.onDocumentRead(); - } - - /** - * Not currently implemented - */ - @Override - public List getAllEmbedds() throws OpenXML4JException { - return new ArrayList(); - } - - // - // Useful public API goes here - // - - /** - * @return pages ordered by page number - */ - public Collection getPages() { - return _pages.getPageList(); - } - - public XDGFStyleSheet getStyleById(long id) { - return _document.getStyleById(id); - } - -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/CharacterSection.java b/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/CharacterSection.java deleted file mode 100644 index 7c1aa3f0c..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/CharacterSection.java +++ /dev/null @@ -1,69 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xdgf.usermodel.section; - -import java.awt.Color; -import java.util.HashMap; -import java.util.Map; - -import org.apache.poi.xdgf.usermodel.XDGFCell; -import org.apache.poi.xdgf.usermodel.XDGFSheet; - -import com.microsoft.schemas.office.visio.x2012.main.CellType; -import com.microsoft.schemas.office.visio.x2012.main.RowType; -import com.microsoft.schemas.office.visio.x2012.main.SectionType; - -public class CharacterSection extends XDGFSection { - - Double _fontSize = null; - Color _fontColor = null; - - Map _characterCells = new HashMap(); - - public CharacterSection(SectionType section, XDGFSheet containingSheet) { - super(section, containingSheet); - - // there aren't cells for this, just a single row - RowType row = section.getRowArray(0); - - for (CellType cell: row.getCellArray()) { - _characterCells.put(cell.getN(), new XDGFCell(cell)); - } - - _fontSize = XDGFCell.maybeGetDouble(_characterCells, "Size"); - - String tmpColor = XDGFCell.maybeGetString(_characterCells, "Color"); - if (tmpColor != null) - _fontColor = Color.decode(tmpColor); - } - - public Double getFontSize() { - return _fontSize; - } - - public Color getFontColor() { - return _fontColor; - } - - @Override - public void setupMaster(XDGFSection section) { - - } - -} - diff --git a/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/CombinedIterable.java b/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/CombinedIterable.java deleted file mode 100644 index d51e9070d..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/CombinedIterable.java +++ /dev/null @@ -1,144 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xdgf.usermodel.section; - -import java.util.Collections; -import java.util.Iterator; -import java.util.Map.Entry; -import java.util.NoSuchElementException; -import java.util.Set; -import java.util.SortedMap; - -/** - * An iterator used to iterate over the base and master items - * - * @param - */ -public class CombinedIterable implements Iterable { - - final SortedMap _baseItems; - final SortedMap _masterItems; - - public CombinedIterable(SortedMap baseItems, - SortedMap masterItems) { - _baseItems = baseItems; - _masterItems = masterItems; - } - - @Override - public Iterator iterator() { - - final Iterator> vmasterI; - - if (_masterItems != null) { - vmasterI = _masterItems.entrySet().iterator(); - } else { - final Set> empty = Collections.emptySet(); - vmasterI = empty.iterator(); - } - - return new Iterator() { - - Long lastI = Long.MIN_VALUE; - - Entry currentBase = null; - Entry currentMaster = null; - - // grab the iterator for both - Iterator> baseI = _baseItems.entrySet().iterator(); - Iterator> masterI = vmasterI; - - @Override - public boolean hasNext() { - return currentBase != null || currentMaster != null - || baseI.hasNext() || masterI.hasNext(); - } - - @Override - public T next() { - - // TODO: This seems far more complex than it needs to be - - long baseIdx = Long.MAX_VALUE; - long masterIdx = Long.MAX_VALUE; - - if (currentBase == null) { - while (baseI.hasNext()) { - currentBase = baseI.next(); - if (currentBase.getKey() > lastI) { - baseIdx = currentBase.getKey(); - break; - } - } - } else { - baseIdx = currentBase.getKey(); - } - - if (currentMaster == null) { - while (masterI.hasNext()) { - currentMaster = masterI.next(); - if (currentMaster.getKey() > lastI) { - masterIdx = currentMaster.getKey(); - break; - } - } - } else { - masterIdx = currentMaster.getKey(); - } - - T val; - - if (currentBase != null) { - - if (baseIdx <= masterIdx) { - lastI = baseIdx; - val = currentBase.getValue(); - - // discard master if same as base - if (masterIdx == baseIdx) { - currentMaster = null; - } - - currentBase = null; - - } else { - lastI = masterIdx; - val = (currentMaster != null) ? currentMaster.getValue() : null; - currentMaster = null; - } - - } else if (currentMaster != null) { - lastI = currentMaster.getKey(); - val = currentMaster.getValue(); - - currentMaster = null; - } else { - throw new NoSuchElementException(); - } - - return val; - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - }; - } - -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/GenericSection.java b/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/GenericSection.java deleted file mode 100644 index b0ecf2051..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/GenericSection.java +++ /dev/null @@ -1,33 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xdgf.usermodel.section; - -import org.apache.poi.xdgf.usermodel.XDGFSheet; - -import com.microsoft.schemas.office.visio.x2012.main.SectionType; - -public class GenericSection extends XDGFSection { - - public GenericSection(SectionType section, XDGFSheet containingSheet) { - super(section, containingSheet); - } - - @Override - public void setupMaster(XDGFSection section) { - } -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/GeometrySection.java b/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/GeometrySection.java deleted file mode 100644 index bc7cdf60b..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/GeometrySection.java +++ /dev/null @@ -1,155 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xdgf.usermodel.section; - -import java.awt.geom.Path2D; -import java.util.Iterator; -import java.util.Map.Entry; -import java.util.SortedMap; -import java.util.TreeMap; - -import org.apache.poi.POIXMLException; -import org.apache.poi.xdgf.geom.SplineCollector; -import org.apache.poi.xdgf.usermodel.XDGFCell; -import org.apache.poi.xdgf.usermodel.XDGFShape; -import org.apache.poi.xdgf.usermodel.XDGFSheet; -import org.apache.poi.xdgf.usermodel.section.geometry.Ellipse; -import org.apache.poi.xdgf.usermodel.section.geometry.GeometryRow; -import org.apache.poi.xdgf.usermodel.section.geometry.GeometryRowFactory; -import org.apache.poi.xdgf.usermodel.section.geometry.InfiniteLine; -import org.apache.poi.xdgf.usermodel.section.geometry.SplineKnot; -import org.apache.poi.xdgf.usermodel.section.geometry.SplineStart; - -import com.microsoft.schemas.office.visio.x2012.main.RowType; -import com.microsoft.schemas.office.visio.x2012.main.SectionType; - -public class GeometrySection extends XDGFSection { - - GeometrySection _master = null; - - // rows - SortedMap _rows = new TreeMap(); - - public GeometrySection(SectionType section, XDGFSheet containingSheet) { - super(section, containingSheet); - - for (RowType row: section.getRowArray()) { - if (_rows.containsKey(row.getIX())) - throw new POIXMLException("Index element '" + row.getIX() + "' already exists"); - - _rows.put(row.getIX(), GeometryRowFactory.load(row)); - } - } - - @Override - public void setupMaster(XDGFSection master) { - - _master = (GeometrySection)master; - - for (Entry entry : _rows.entrySet()) { - GeometryRow masterRow = _master._rows.get(entry.getKey()); - if (masterRow != null) { - try { - entry.getValue().setupMaster(masterRow); - } catch (ClassCastException e) { - // this can happen when a dynamic connector overrides its master's geometry - // .. probably can happen elsewhere too, I imagine. - //throw XDGFException.error("Mismatched geometry section '" + entry.getKey() + "' in master", this, e); - } - } - } - } - - // returns True if this row shouldn't be displayed - public Boolean getNoShow() { - Boolean noShow = XDGFCell.maybeGetBoolean(_cells, "NoShow"); - if (noShow == null) { - if (_master != null) - return _master.getNoShow(); - - return false; - } - - return noShow; - } - - public Iterable getCombinedRows() { - return new CombinedIterable(_rows, - _master == null ? null : _master._rows); - } - - public Path2D.Double getPath(XDGFShape parent) { - - Iterator rows = getCombinedRows().iterator(); - - // special cases - GeometryRow first = rows.next(); - - if (first instanceof Ellipse) { - return ((Ellipse)first).getPath(); - } else if (first instanceof InfiniteLine) { - return ((InfiniteLine)first).getPath(); - } else if (first instanceof SplineStart) { - throw new POIXMLException("SplineStart must be preceded by another type"); - } else { - - // everything else is a path - Path2D.Double path = new Path2D.Double(); - - // dealing with splines makes this more complex - SplineCollector renderer = null; - GeometryRow row; - - while (true) { - - if (first != null) { - row = first; - first = null; - } else { - if (!rows.hasNext()) - break; - row = rows.next(); - } - - if (row instanceof SplineStart) { - if (renderer != null) - throw new POIXMLException("SplineStart found multiple times!"); - renderer = new SplineCollector((SplineStart) row); - } else if (row instanceof SplineKnot) { - if (renderer == null) - throw new POIXMLException("SplineKnot found without SplineStart!"); - renderer.addKnot((SplineKnot) row); - } else { - if (renderer != null) { - renderer.addToPath(path, parent); - renderer = null; - } - - row.addToPath(path, parent); - } - } - - // just in case we end iteration - if (renderer != null) - renderer.addToPath(path, parent); - - return path; - } - } - -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/XDGFSection.java b/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/XDGFSection.java deleted file mode 100644 index 1448a60ba..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/XDGFSection.java +++ /dev/null @@ -1,100 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xdgf.usermodel.section; - -import java.util.HashMap; -import java.util.Map; - -import org.apache.poi.POIXMLException; -import org.apache.poi.util.Internal; -import org.apache.poi.xdgf.usermodel.XDGFCell; -import org.apache.poi.xdgf.usermodel.XDGFSheet; -import org.apache.poi.xdgf.util.ObjectFactory; - -import com.microsoft.schemas.office.visio.x2012.main.CellType; -import com.microsoft.schemas.office.visio.x2012.main.SectionType; - -public abstract class XDGFSection { - - static final ObjectFactory _sectionTypes; - - static { - _sectionTypes = new ObjectFactory(); - try { - _sectionTypes.put("LineGradient", GenericSection.class, SectionType.class, XDGFSheet.class); - _sectionTypes.put("FillGradient", GenericSection.class, SectionType.class, XDGFSheet.class); - _sectionTypes.put("Character", CharacterSection.class, SectionType.class, XDGFSheet.class); - _sectionTypes.put("Paragraph", GenericSection.class, SectionType.class, XDGFSheet.class); - _sectionTypes.put("Tabs", GenericSection.class, SectionType.class, XDGFSheet.class); - _sectionTypes.put("Scratch", GenericSection.class, SectionType.class, XDGFSheet.class); - _sectionTypes.put("Connection", GenericSection.class, SectionType.class, XDGFSheet.class); - _sectionTypes.put("ConnectionABCD", GenericSection.class, SectionType.class, XDGFSheet.class); - _sectionTypes.put("Field", GenericSection.class, SectionType.class, XDGFSheet.class); - _sectionTypes.put("Control", GenericSection.class, SectionType.class, XDGFSheet.class); - _sectionTypes.put("Geometry", GeometrySection.class, SectionType.class, XDGFSheet.class); - _sectionTypes.put("Actions", GenericSection.class, SectionType.class, XDGFSheet.class); - _sectionTypes.put("Layer", GenericSection.class, SectionType.class, XDGFSheet.class); - _sectionTypes.put("User", GenericSection.class, SectionType.class, XDGFSheet.class); - _sectionTypes.put("Property", GenericSection.class, SectionType.class, XDGFSheet.class); - _sectionTypes.put("Hyperlink", GenericSection.class, SectionType.class, XDGFSheet.class); - _sectionTypes.put("Reviewer", GenericSection.class, SectionType.class, XDGFSheet.class); - _sectionTypes.put("Annotation", GenericSection.class, SectionType.class, XDGFSheet.class); - _sectionTypes.put("ActionTag", GenericSection.class, SectionType.class, XDGFSheet.class); - } catch (NoSuchMethodException e) { - throw new POIXMLException("Internal error"); - } catch (SecurityException e) { - throw new POIXMLException("Internal error"); - } - - } - - public static XDGFSection load(SectionType section, XDGFSheet containingSheet) { - return _sectionTypes.load(section.getN(), section, containingSheet); - } - - - protected SectionType _section; - protected XDGFSheet _containingSheet; - - protected Map _cells = new HashMap(); - - - public XDGFSection(SectionType section, XDGFSheet containingSheet) { - _section = section; - _containingSheet = containingSheet; - - // only store cells in the base, not rows -- because rows are handled - // specially for geometry sections - for (CellType cell: section.getCellArray()) { - _cells.put(cell.getN(), new XDGFCell(cell)); - } - } - - @Internal - public SectionType getXmlObject() { - return _section; - } - - @Override - public String toString() { - return "
    "; - } - - public abstract void setupMaster(XDGFSection section); - -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/geometry/ArcTo.java b/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/geometry/ArcTo.java deleted file mode 100644 index fdcce8056..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/geometry/ArcTo.java +++ /dev/null @@ -1,134 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xdgf.usermodel.section.geometry; - -import java.awt.geom.AffineTransform; -import java.awt.geom.Arc2D; -import java.awt.geom.Path2D; -import java.awt.geom.Point2D; - -import org.apache.poi.POIXMLException; -import org.apache.poi.xdgf.usermodel.XDGFCell; -import org.apache.poi.xdgf.usermodel.XDGFShape; - -import com.microsoft.schemas.office.visio.x2012.main.CellType; -import com.microsoft.schemas.office.visio.x2012.main.RowType; - -public class ArcTo implements GeometryRow { - - ArcTo _master = null; - - // The x-coordinate of the ending vertex of an arc. - Double x = null; - - // The y-coordinate of the ending vertex of an arc. - Double y = null; - - // The distance from the arc's midpoint to the midpoint of its chord. - Double a = null; - - Boolean deleted = null; - - // TODO: support formulas - - public ArcTo(RowType row) { - - if (row.isSetDel()) - deleted = row.getDel(); - - for (CellType cell : row.getCellArray()) { - String cellName = cell.getN(); - - if (cellName.equals("X")) { - x = XDGFCell.parseDoubleValue(cell); - } else if (cellName.equals("Y")) { - y = XDGFCell.parseDoubleValue(cell); - } else if (cellName.equals("A")) { - a = XDGFCell.parseDoubleValue(cell); - } else { - throw new POIXMLException("Invalid cell '" + cellName - + "' in ArcTo row"); - } - } - } - - public boolean getDel() { - if (deleted != null) - return deleted; - - if (_master != null) - return _master.getDel(); - - return false; - } - - public Double getX() { - return x == null ? _master.x : x; - } - - public Double getY() { - return y == null ? _master.y : y; - } - - public Double getA() { - return a == null ? _master.a : a; - } - - @Override - public void setupMaster(GeometryRow row) { - _master = (ArcTo) row; - } - - @Override - public void addToPath(Path2D.Double path, XDGFShape parent) { - - if (getDel()) - return; - - Point2D last = path.getCurrentPoint(); - - // intentionally shadowing variables here - double x = getX(); - double y = getY(); - double a = getA(); - - if (a == 0) { - path.lineTo(x, y); - return; - } - - double x0 = last.getX(); - double y0 = last.getY(); - - double chordLength = Math.hypot(y - y0, x - x0); - double radius = (4 * a * a + chordLength * chordLength) - / (8 * Math.abs(a)); - - // center point - double cx = x0 + (x - x0) / 2.0; - double cy = y0 + (y - y0) / 2.0; - - double rotate = Math.atan2(y - cy, x - cx); - - Arc2D arc = new Arc2D.Double(x0, y0 - radius, chordLength, 2 * radius, - 180, x0 < x ? 180 : -180, Arc2D.OPEN); - - path.append(AffineTransform.getRotateInstance(rotate, x0, y0) - .createTransformedShape(arc), true); - } -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/geometry/Ellipse.java b/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/geometry/Ellipse.java deleted file mode 100644 index 01eecdd00..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/geometry/Ellipse.java +++ /dev/null @@ -1,160 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xdgf.usermodel.section.geometry; - -import java.awt.geom.AffineTransform; -import java.awt.geom.Ellipse2D; -import java.awt.geom.Path2D; - -import org.apache.poi.POIXMLException; -import org.apache.poi.xdgf.usermodel.XDGFCell; -import org.apache.poi.xdgf.usermodel.XDGFShape; - -import com.microsoft.schemas.office.visio.x2012.main.CellType; -import com.microsoft.schemas.office.visio.x2012.main.RowType; - -public class Ellipse implements GeometryRow { - - Ellipse _master = null; - - // x coordinate of center point - Double x = null; - // y coordinate of center point - Double y = null; - - // x coordinate of first point on ellipse - Double a = null; - // y coordinate of first point on ellipse - Double b = null; - - // x coordinate of second point on ellipse - Double c = null; - // y coordinate of second point on ellipse - Double d = null; - - Boolean deleted = null; - - // TODO: support formulas - - public Ellipse(RowType row) { - - if (row.isSetDel()) - deleted = row.getDel(); - - for (CellType cell : row.getCellArray()) { - String cellName = cell.getN(); - - if (cellName.equals("X")) { - x = XDGFCell.parseDoubleValue(cell); - } else if (cellName.equals("Y")) { - y = XDGFCell.parseDoubleValue(cell); - } else if (cellName.equals("A")) { - a = XDGFCell.parseDoubleValue(cell); - } else if (cellName.equals("B")) { - b = XDGFCell.parseDoubleValue(cell); - } else if (cellName.equals("C")) { - c = XDGFCell.parseDoubleValue(cell); - } else if (cellName.equals("D")) { - d = XDGFCell.parseDoubleValue(cell); - } else { - throw new POIXMLException("Invalid cell '" + cellName - + "' in Ellipse row"); - } - } - } - - public boolean getDel() { - if (deleted != null) - return deleted; - - if (_master != null) - return _master.getDel(); - - return false; - } - - public Double getX() { - return x == null ? _master.x : x; - } - - public Double getY() { - return y == null ? _master.y : y; - } - - public Double getA() { - return a == null ? _master.a : a; - } - - public Double getB() { - return b == null ? _master.b : b; - } - - public Double getC() { - return c == null ? _master.c : c; - } - - public Double getD() { - return d == null ? _master.d : d; - } - - @Override - public void setupMaster(GeometryRow row) { - _master = (Ellipse) row; - } - - public Path2D.Double getPath() { - - if (getDel()) - return null; - - // intentionally shadowing variables here - double cx = getX(); // center - double cy = getY(); - double a = getA(); // left - double b = getB(); - double c = getC(); // top - double d = getD(); - - // compute radius - double rx = Math.hypot(a - cx, b - cy); - double ry = Math.hypot(c - cx, d - cy); - - // compute angle of ellipse - double angle = (2.0 * Math.PI + (cy > b ? 1.0 : -1.0) - * Math.acos((cx - a) / rx)) - % (2.0 * Math.PI); - - // create ellipse - Ellipse2D.Double ellipse = new Ellipse2D.Double(cx - rx, cy - ry, - rx * 2, ry * 2); - - // create a path, rotate it about its center - Path2D.Double path = new Path2D.Double(ellipse); - - AffineTransform tr = new AffineTransform(); - tr.rotate(angle, cx, cy); - path.transform(tr); - - return path; - } - - @Override - public void addToPath(java.awt.geom.Path2D.Double path, XDGFShape parent) { - throw new POIXMLException("Ellipse elements cannot be part of a path"); - } -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/geometry/EllipticalArcTo.java b/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/geometry/EllipticalArcTo.java deleted file mode 100644 index 02fc5aef4..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/geometry/EllipticalArcTo.java +++ /dev/null @@ -1,246 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xdgf.usermodel.section.geometry; - -import java.awt.geom.AffineTransform; -import java.awt.geom.Arc2D; -import java.awt.geom.Point2D; - -import org.apache.poi.POIXMLException; -import org.apache.poi.xdgf.usermodel.XDGFCell; -import org.apache.poi.xdgf.usermodel.XDGFShape; - -import com.microsoft.schemas.office.visio.x2012.main.CellType; -import com.microsoft.schemas.office.visio.x2012.main.RowType; - -public class EllipticalArcTo implements GeometryRow { - - EllipticalArcTo _master = null; - - // The x-coordinate of the ending vertex on an arc. - Double x = null; - - // The y-coordinate of the ending vertex on an arc. - Double y = null; - - // The x-coordinate of the arc's control point; a point on the arc. The - // control point is best located about halfway between the beginning and - // ending vertices of the arc. Otherwise, the arc may grow to an extreme - // size in order to pass through the control point, with unpredictable - // results. - Double a = null; - - // The y-coordinate of an arc's control point. - Double b = null; - - // The angle of an arc's major axis relative to the x-axis of its parent - // shape. - Double c = null; - - // The ratio of an arc's major axis to its minor axis. Despite the usual - // meaning of these words, the "major" axis does not have to be greater than - // the "minor" axis, so this ratio does not have to be greater than 1. - // Setting this cell to a value less than or equal to 0 or greater than 1000 - // can lead to unpredictable results. - Double d = null; - - Boolean deleted = null; - - // TODO: support formulas - - public EllipticalArcTo(RowType row) { - - if (row.isSetDel()) - deleted = row.getDel(); - - for (CellType cell : row.getCellArray()) { - String cellName = cell.getN(); - - if (cellName.equals("X")) { - x = XDGFCell.parseDoubleValue(cell); - } else if (cellName.equals("Y")) { - y = XDGFCell.parseDoubleValue(cell); - } else if (cellName.equals("A")) { - a = XDGFCell.parseDoubleValue(cell); - } else if (cellName.equals("B")) { - b = XDGFCell.parseDoubleValue(cell); - } else if (cellName.equals("C")) { - c = XDGFCell.parseDoubleValue(cell); - } else if (cellName.equals("D")) { - d = XDGFCell.parseDoubleValue(cell); - } else { - throw new POIXMLException("Invalid cell '" + cellName - + "' in EllipticalArcTo row"); - } - } - } - - public boolean getDel() { - if (deleted != null) - return deleted; - - if (_master != null) - return _master.getDel(); - - return false; - } - - public Double getX() { - return x == null ? _master.x : x; - } - - public Double getY() { - return y == null ? _master.y : y; - } - - public Double getA() { - return a == null ? _master.a : a; - } - - public Double getB() { - return b == null ? _master.b : b; - } - - public Double getC() { - return c == null ? _master.c : c; - } - - public Double getD() { - return d == null ? _master.d : d; - } - - @Override - public void setupMaster(GeometryRow row) { - _master = (EllipticalArcTo) row; - } - - public static int draw = 0; - - @Override - public void addToPath(java.awt.geom.Path2D.Double path, XDGFShape parent) { - - if (getDel()) - return; - - // intentionally shadowing variables here - double x = getX(); - double y = getY(); - double a = getA(); - double b = getB(); - double c = getC(); - double d = getD(); - - createEllipticalArc(x, y, a, b, c, d, path); - } - - public static void createEllipticalArc(double x, double y, double a, - double b, double c, double d, java.awt.geom.Path2D.Double path) { - - // Formula for center of ellipse by Junichi Yoda & nashwaan: - // -> From http://visguy.com/vgforum/index.php?topic=2464.0 - // - // x1,y1 = start; x2,y2 = end; x3,y3 = control point - // - // x0 = - // ((x1-x2)*(x1+x2)*(y2-y3)-(x2-x3)*(x2+x3)*(y1-y2)+D^2*(y1-y2)*(y2-y3)*(y1-y3))/(2*((x1-x2)*(y2-y3)-(x2-x3)*(y1-y2))) - // y0 = - // ((x1-x2)*(x2-x3)*(x1-x3)/D^2+(x2-x3)*(y1-y2)*(y1+y2)-(x1-x2)*(y2-y3)*(y2+y3))/(2*((x2-x3)*(y1-y2)-(x1-x2)*(y2-y3))) - // radii along axis: a = sqrt{ (x1-x0)^2 + (y1-y0)^2 * D^2 } - // - - Point2D last = path.getCurrentPoint(); - double x0 = last.getX(); - double y0 = last.getY(); - - // translate all of the points to the same angle as the ellipse - AffineTransform at = AffineTransform.getRotateInstance(-c); - double[] pts = new double[] { x0, y0, x, y, a, b }; - at.transform(pts, 0, pts, 0, 3); - - x0 = pts[0]; - y0 = pts[1]; - x = pts[2]; - y = pts[3]; - a = pts[4]; - b = pts[5]; - - // nasty math time - - double d2 = d * d; - double cx = ((x0 - x) * (x0 + x) * (y - b) - (x - a) * (x + a) - * (y0 - y) + d2 * (y0 - y) * (y - b) * (y0 - b)) - / (2.0 * ((x0 - x) * (y - b) - (x - a) * (y0 - y))); - double cy = ((x0 - x) * (x - a) * (x0 - a) / d2 + (x - a) * (y0 - y) - * (y0 + y) - (x0 - x) * (y - b) * (y + b)) - / (2.0 * ((x - a) * (y0 - y) - (x0 - x) * (y - b))); - - // calculate radii of ellipse - double rx = Math.sqrt(Math.pow(x0 - cx, 2) + Math.pow(y0 - cy, 2) * d2); - double ry = rx / d; - - // Arc2D requires us to draw an arc from one point to another, so we - // need to calculate the angle of the start point and end point along - // the ellipse - // - Derived from parametric form of ellipse: x = h + a*cos(t); y = k + - // b*sin(t) - - double ctrlAngle = Math.toDegrees(Math.atan2((b - cy) / ry, (a - cx) - / rx)); - double startAngle = Math.toDegrees(Math.atan2((y0 - cy) / ry, (x0 - cx) - / rx)); - double endAngle = Math.toDegrees(Math.atan2((y - cy) / ry, (x - cx) - / rx)); - - double sweep = computeSweep(startAngle, endAngle, ctrlAngle); - - // Now we have enough information to go on. Create the arc. - Arc2D arc = new Arc2D.Double(cx - rx, cy - ry, rx * 2, ry * 2, - -startAngle, sweep, Arc2D.OPEN); - - // rotate the arc back to the original coordinate system - at.setToRotation(c); - path.append(at.createTransformedShape(arc), false); - } - - protected static double computeSweep(double startAngle, double endAngle, - double ctrlAngle) { - double sweep; - - startAngle = (360.0 + startAngle) % 360.0; - endAngle = (360.0 + endAngle) % 360.0; - ctrlAngle = (360.0 + ctrlAngle) % 360.0; - - // different sweeps depending on where the control point is - - if (startAngle < endAngle) { - if (startAngle < ctrlAngle && ctrlAngle < endAngle) { - sweep = startAngle - endAngle; - } else { - sweep = 360 + (startAngle - endAngle); - } - } else { - if (endAngle < ctrlAngle && ctrlAngle < startAngle) { - sweep = startAngle - endAngle; - } else { - sweep = -(360 - (startAngle - endAngle)); - } - } - - return sweep; - } -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/geometry/GeometryRow.java b/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/geometry/GeometryRow.java deleted file mode 100644 index 8ffaef26f..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/geometry/GeometryRow.java +++ /dev/null @@ -1,30 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xdgf.usermodel.section.geometry; - -import java.awt.geom.Path2D; - -import org.apache.poi.xdgf.usermodel.XDGFShape; - -public interface GeometryRow { - - public void setupMaster(GeometryRow row); - - public void addToPath(Path2D.Double path, XDGFShape parent); - -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/geometry/GeometryRowFactory.java b/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/geometry/GeometryRowFactory.java deleted file mode 100644 index 50e85e878..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/geometry/GeometryRowFactory.java +++ /dev/null @@ -1,61 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xdgf.usermodel.section.geometry; - -import org.apache.poi.POIXMLException; -import org.apache.poi.xdgf.util.ObjectFactory; - -import com.microsoft.schemas.office.visio.x2012.main.RowType; - -public class GeometryRowFactory { - - static final ObjectFactory _rowTypes; - - static { - _rowTypes = new ObjectFactory(); - try { - _rowTypes.put("ArcTo", ArcTo.class, RowType.class); - _rowTypes.put("Ellipse", Ellipse.class, RowType.class); - _rowTypes.put("EllipticalArcTo", EllipticalArcTo.class, - RowType.class); - _rowTypes.put("InfiniteLine", InfiniteLine.class, RowType.class); - _rowTypes.put("LineTo", LineTo.class, RowType.class); - _rowTypes.put("MoveTo", MoveTo.class, RowType.class); - _rowTypes.put("NURBSTo", NURBSTo.class, RowType.class); - _rowTypes.put("PolyLineTo", PolyLineTo.class, RowType.class); - _rowTypes.put("RelCubBezTo", RelCubBezTo.class, RowType.class); - _rowTypes.put("RelEllipticalArcTo", RelEllipticalArcTo.class, - RowType.class); - _rowTypes.put("RelLineTo", RelLineTo.class, RowType.class); - _rowTypes.put("RelMoveTo", RelMoveTo.class, RowType.class); - _rowTypes.put("RelQuadBezTo", RelQuadBezTo.class, RowType.class); - _rowTypes.put("SplineKnot", SplineKnot.class, RowType.class); - _rowTypes.put("SplineStart", SplineStart.class, RowType.class); - } catch (NoSuchMethodException e) { - throw new POIXMLException("Internal error", e); - } catch (SecurityException e) { - throw new POIXMLException("Internal error", e); - } - - } - - public static GeometryRow load(RowType row) { - return _rowTypes.load(row.getT(), row); - } - -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/geometry/InfiniteLine.java b/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/geometry/InfiniteLine.java deleted file mode 100644 index 6965c1b89..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/geometry/InfiniteLine.java +++ /dev/null @@ -1,154 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xdgf.usermodel.section.geometry; - -import java.awt.geom.Path2D; - -import org.apache.poi.POIXMLException; -import org.apache.poi.xdgf.usermodel.XDGFCell; -import org.apache.poi.xdgf.usermodel.XDGFShape; - -import com.microsoft.schemas.office.visio.x2012.main.CellType; -import com.microsoft.schemas.office.visio.x2012.main.RowType; - -/** - * Contains the x- and y-coordinates of two points on an infinite line. - */ -public class InfiniteLine implements GeometryRow { - - InfiniteLine _master = null; - - // An x-coordinate of a point on the infinite line; paired with y-coordinate - // represented by the Y cell. - Double x = null; - - // A y-coordinate of a point on the infinite line; paired with x-coordinate - // represented by the X cell. - Double y = null; - - // An x-coordinate of a point on the infinite line; paired with y-coordinate - // represented by the B cell. - Double a = null; - - // A y-coordinate of a point on an infinite line; paired with x-coordinate - // represented by the A cell. - Double b = null; - - Boolean deleted = null; - - // TODO: support formulas - - public InfiniteLine(RowType row) { - - if (row.isSetDel()) - deleted = row.getDel(); - - for (CellType cell : row.getCellArray()) { - String cellName = cell.getN(); - - if (cellName.equals("X")) { - x = XDGFCell.parseDoubleValue(cell); - } else if (cellName.equals("Y")) { - y = XDGFCell.parseDoubleValue(cell); - } else if (cellName.equals("A")) { - a = XDGFCell.parseDoubleValue(cell); - } else if (cellName.equals("B")) { - b = XDGFCell.parseDoubleValue(cell); - } else { - throw new POIXMLException("Invalid cell '" + cellName - + "' in InfiniteLine row"); - } - } - } - - public boolean getDel() { - if (deleted != null) - return deleted; - - if (_master != null) - return _master.getDel(); - - return false; - } - - public Double getX() { - return x == null ? _master.x : x; - } - - public Double getY() { - return y == null ? _master.y : y; - } - - public Double getA() { - return a == null ? _master.a : a; - } - - public Double getB() { - return b == null ? _master.b : b; - } - - @Override - public void setupMaster(GeometryRow row) { - _master = (InfiniteLine) row; - } - - @Override - public void addToPath(java.awt.geom.Path2D.Double path, XDGFShape parent) { - - if (getDel()) - return; - - throw new POIXMLException( - "InfiniteLine elements cannot be part of a path"); - } - - // returns this object as a line that extends between the boundaries of - // the document - public Path2D.Double getPath() { - Path2D.Double path = new Path2D.Double(); - - // this is a bit of a hack, but it works - double max_val = 100000; - - // compute slope.. - double x0 = getX(); - double y0 = getY(); - double x1 = getA(); // second x - double y1 = getB(); // second y - - if (x0 == x1) { - path.moveTo(x0, -max_val); - path.lineTo(x0, max_val); - } else if (y0 == y1) { - path.moveTo(-max_val, y0); - path.lineTo(max_val, y0); - } else { - - // normal case: compute slope/intercept - double m = (y1 - y0) / (x1 - x0); - double c = y0 - m * x0; - - // y = mx + c - - path.moveTo(max_val, m * max_val + c); - path.lineTo(max_val, (max_val - c) / m); - } - - return path; - } -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/geometry/LineTo.java b/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/geometry/LineTo.java deleted file mode 100644 index 93857f09b..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/geometry/LineTo.java +++ /dev/null @@ -1,91 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xdgf.usermodel.section.geometry; - -import org.apache.poi.POIXMLException; -import org.apache.poi.xdgf.usermodel.XDGFCell; -import org.apache.poi.xdgf.usermodel.XDGFShape; - -import com.microsoft.schemas.office.visio.x2012.main.CellType; -import com.microsoft.schemas.office.visio.x2012.main.RowType; - -public class LineTo implements GeometryRow { - - LineTo _master = null; - - Double x = null; - Double y = null; - - Boolean deleted = null; - - // TODO: support formulas - - public LineTo(RowType row) { - - if (row.isSetDel()) - deleted = row.getDel(); - - for (CellType cell : row.getCellArray()) { - String cellName = cell.getN(); - - if (cellName.equals("X")) { - x = XDGFCell.parseDoubleValue(cell); - } else if (cellName.equals("Y")) { - y = XDGFCell.parseDoubleValue(cell); - } else { - throw new POIXMLException("Invalid cell '" + cellName - + "' in LineTo row"); - } - } - } - - @Override - public String toString() { - return "LineTo: x=" + getX() + "; y=" + getY(); - } - - public boolean getDel() { - if (deleted != null) - return deleted; - - if (_master != null) - return _master.getDel(); - - return false; - } - - public Double getX() { - return x == null ? _master.x : x; - } - - public Double getY() { - return y == null ? _master.y : y; - } - - @Override - public void setupMaster(GeometryRow row) { - _master = (LineTo) row; - } - - @Override - public void addToPath(java.awt.geom.Path2D.Double path, XDGFShape parent) { - if (getDel()) - return; - path.lineTo(getX(), getY()); - } -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/geometry/MoveTo.java b/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/geometry/MoveTo.java deleted file mode 100644 index 6dca12b2b..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/geometry/MoveTo.java +++ /dev/null @@ -1,96 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xdgf.usermodel.section.geometry; - -import org.apache.poi.POIXMLException; -import org.apache.poi.xdgf.usermodel.XDGFCell; -import org.apache.poi.xdgf.usermodel.XDGFShape; - -import com.microsoft.schemas.office.visio.x2012.main.CellType; -import com.microsoft.schemas.office.visio.x2012.main.RowType; - -/** - * Contains the x- and y-coordinates of the first vertex of a shape or the x- - * and y-coordinates of the first vertex after a break in a path, relative to - * the height and width of the shape. - */ -public class MoveTo implements GeometryRow { - - MoveTo _master = null; - - Double x = null; - Double y = null; - - Boolean deleted = null; - - // TODO: support formulas - - public MoveTo(RowType row) { - - if (row.isSetDel()) - deleted = row.getDel(); - - for (CellType cell : row.getCellArray()) { - String cellName = cell.getN(); - - if (cellName.equals("X")) { - x = XDGFCell.parseDoubleValue(cell); - } else if (cellName.equals("Y")) { - y = XDGFCell.parseDoubleValue(cell); - } else { - throw new POIXMLException("Invalid cell '" + cellName - + "' in MoveTo row"); - } - } - } - - @Override - public String toString() { - return "MoveTo: x=" + getX() + "; y=" + getY(); - } - - public boolean getDel() { - if (deleted != null) - return deleted; - - if (_master != null) - return _master.getDel(); - - return false; - } - - public Double getX() { - return x == null ? _master.x : x; - } - - public Double getY() { - return y == null ? _master.y : y; - } - - @Override - public void setupMaster(GeometryRow row) { - _master = (MoveTo) row; - } - - @Override - public void addToPath(java.awt.geom.Path2D.Double path, XDGFShape parent) { - if (getDel()) - return; - path.moveTo(getX(), getY()); - } -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/geometry/NURBSTo.java b/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/geometry/NURBSTo.java deleted file mode 100644 index 353d694f9..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/geometry/NURBSTo.java +++ /dev/null @@ -1,214 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xdgf.usermodel.section.geometry; - -import java.awt.geom.Point2D; - -import org.apache.poi.POIXMLException; -import org.apache.poi.xdgf.geom.SplineRenderer; -import org.apache.poi.xdgf.usermodel.XDGFCell; -import org.apache.poi.xdgf.usermodel.XDGFShape; - -import com.graphbuilder.curve.ControlPath; -import com.graphbuilder.curve.ShapeMultiPath; -import com.graphbuilder.curve.ValueVector; -import com.graphbuilder.geom.PointFactory; -import com.microsoft.schemas.office.visio.x2012.main.CellType; -import com.microsoft.schemas.office.visio.x2012.main.RowType; - -public class NURBSTo implements GeometryRow { - - NURBSTo _master = null; - - // The x-coordinate of the last control point of a NURBS. - Double x = null; - - // The y-coordinate of the last control point of a NURBS. - Double y = null; - - // The second to the last knot of the NURBS. - Double a = null; - - // The last weight of the NURBS. - Double b = null; - - // The first knot of the NURBS. - Double c = null; - - // The first weight of the NURBS. - Double d = null; - - // A NURBS formula. - String e = null; - - Boolean deleted = null; - - // TODO: support formulas - - public NURBSTo(RowType row) { - - if (row.isSetDel()) - deleted = row.getDel(); - - for (CellType cell : row.getCellArray()) { - String cellName = cell.getN(); - - if (cellName.equals("X")) { - x = XDGFCell.parseDoubleValue(cell); - } else if (cellName.equals("Y")) { - y = XDGFCell.parseDoubleValue(cell); - } else if (cellName.equals("A")) { - a = XDGFCell.parseDoubleValue(cell); - } else if (cellName.equals("B")) { - b = XDGFCell.parseDoubleValue(cell); - } else if (cellName.equals("C")) { - c = XDGFCell.parseDoubleValue(cell); - } else if (cellName.equals("D")) { - d = XDGFCell.parseDoubleValue(cell); - } else if (cellName.equals("E")) { - e = cell.getV(); - } else { - throw new POIXMLException("Invalid cell '" + cellName - + "' in NURBS row"); - } - } - } - - public boolean getDel() { - if (deleted != null) - return deleted; - - if (_master != null) - return _master.getDel(); - - return false; - } - - public Double getX() { - return x == null ? _master.x : x; - } - - public Double getY() { - return y == null ? _master.y : y; - } - - public Double getA() { - return a == null ? _master.a : a; - } - - public Double getB() { - return b == null ? _master.b : b; - } - - public Double getC() { - return c == null ? _master.c : c; - } - - public Double getD() { - return d == null ? _master.d : d; - } - - public String getE() { - return e == null ? _master.e : e; - } - - @Override - public void setupMaster(GeometryRow row) { - _master = (NURBSTo) row; - } - - @Override - public void addToPath(java.awt.geom.Path2D.Double path, XDGFShape parent) { - if (getDel()) - return; - - Point2D last = path.getCurrentPoint(); - - // A NURBS formula: knotLast, degree, xType, yType, x1, y1, knot1, - // weight1, .. - String formula = getE().trim(); - if (!formula.startsWith("NURBS(") || !formula.endsWith(")")) - throw new POIXMLException("Invalid NURBS formula: " + formula); - - String[] components = formula.substring(6, formula.length() - 1).split( - ","); - - if (components.length < 8) - throw new POIXMLException( - "Invalid NURBS formula (not enough arguments)"); - - if ((components.length - 4) % 4 != 0) - throw new POIXMLException( - "Invalid NURBS formula -- need 4 + n*4 arguments, got " - + components.length); - - double lastControlX = getX(); - double lastControlY = getY(); - double secondToLastKnot = getA(); - double lastWeight = getB(); - double firstKnot = getC(); - double firstWeight = getD(); - - double lastKnot = Double.parseDouble(components[0].trim()); - int degree = Integer.parseInt(components[1].trim()); - int xType = Integer.parseInt(components[2].trim()); - int yType = Integer.parseInt(components[3].trim()); - - double xScale = 1; - double yScale = 1; - - if (xType == 0) - xScale = parent.getWidth(); - if (yType == 0) - yScale = parent.getHeight(); - - // setup first knots/weights/control point - ControlPath controlPath = new ControlPath(); - ValueVector knots = new ValueVector(); - ValueVector weights = new ValueVector(); - - knots.add(firstKnot); - weights.add(firstWeight); - controlPath.addPoint(PointFactory.create(last.getX(), last.getY())); - - // iterate get knots/weights - int sets = (components.length - 4) / 4; - for (int i = 0; i < sets; i++) { - double x1 = Double.parseDouble(components[4 + i * 4 + 0].trim()); - double y1 = Double.parseDouble(components[4 + i * 4 + 1].trim()); - double k = Double.parseDouble(components[4 + i * 4 + 2].trim()); - double w = Double.parseDouble(components[4 + i * 4 + 3].trim()); - - controlPath.addPoint(PointFactory.create(x1 * xScale, y1 * yScale)); - knots.add(k); - weights.add(w); - } - - // last knots/weights/control point - knots.add(secondToLastKnot); - knots.add(lastKnot); - - weights.add(lastWeight); - - controlPath.addPoint(PointFactory.create(lastControlX, lastControlY)); - - ShapeMultiPath shape = SplineRenderer.createNurbsSpline(controlPath, - knots, weights, degree); - path.append(shape, true); - } -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/geometry/PolyLineTo.java b/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/geometry/PolyLineTo.java deleted file mode 100644 index c5f1ba011..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/geometry/PolyLineTo.java +++ /dev/null @@ -1,100 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xdgf.usermodel.section.geometry; - -import org.apache.poi.POIXMLException; -import org.apache.poi.util.NotImplemented; -import org.apache.poi.xdgf.usermodel.XDGFCell; -import org.apache.poi.xdgf.usermodel.XDGFShape; - -import com.microsoft.schemas.office.visio.x2012.main.CellType; -import com.microsoft.schemas.office.visio.x2012.main.RowType; - -public class PolyLineTo implements GeometryRow { - - PolyLineTo _master = null; - - // The x-coordinate of the ending vertex of a polyline. - Double x = null; - - // The y-coordinate of the ending vertex of a polyline. - Double y = null; - - // The polyline formula - String a = null; - - Boolean deleted = null; - - // TODO: support formulas - - public PolyLineTo(RowType row) { - - if (row.isSetDel()) - deleted = row.getDel(); - - for (CellType cell : row.getCellArray()) { - String cellName = cell.getN(); - - if (cellName.equals("X")) { - x = XDGFCell.parseDoubleValue(cell); - } else if (cellName.equals("Y")) { - y = XDGFCell.parseDoubleValue(cell); - } else if (cellName.equals("A")) { - a = cell.getV(); - } else { - throw new POIXMLException("Invalid cell '" + cellName - + "' in ArcTo row"); - } - } - } - - public boolean getDel() { - if (deleted != null) - return deleted; - - if (_master != null) - return _master.getDel(); - - return false; - } - - public Double getX() { - return x == null ? _master.x : x; - } - - public Double getY() { - return y == null ? _master.y : y; - } - - public String getA() { - return a == null ? _master.a : a; - } - - @Override - public void setupMaster(GeometryRow row) { - _master = (PolyLineTo) row; - } - - @Override - @NotImplemented - public void addToPath(java.awt.geom.Path2D.Double path, XDGFShape parent) { - if (getDel()) - return; - throw new POIXMLException("Polyline support not implemented"); - } -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/geometry/RelCubBezTo.java b/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/geometry/RelCubBezTo.java deleted file mode 100644 index 3a419bb50..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/geometry/RelCubBezTo.java +++ /dev/null @@ -1,139 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xdgf.usermodel.section.geometry; - -import org.apache.poi.POIXMLException; -import org.apache.poi.xdgf.usermodel.XDGFCell; -import org.apache.poi.xdgf.usermodel.XDGFShape; - -import com.microsoft.schemas.office.visio.x2012.main.CellType; -import com.microsoft.schemas.office.visio.x2012.main.RowType; - -public class RelCubBezTo implements GeometryRow { - - RelCubBezTo _master = null; - - // The x-coordinate of the ending vertex of a cubic Bezier curve relative to - // the width of the shape. - Double x = null; - - // The y-coordinate of the ending vertex of a cubic Bezier curve relative to - // the height of the shape. - Double y = null; - - // The x-coordinate of the curve's beginning control point relative to the - // shape's width; a point on the arc. The control point is best located - // between the beginning and ending vertices of the arc. - Double a = null; - - // The y-coordinate of a curve's beginning control point relative to the - // shape's height. - Double b = null; - - // The x-coordinate of the curve's ending control point relative to the - // shape's width; a point on the arc. The control point is best located - // between the beginning control point and ending vertices of the arc. - Double c = null; - - // The y-coordinate of a curve's ending control point relative to the - // shape's height. - Double d = null; - - Boolean deleted = null; - - // TODO: support formulas - - public RelCubBezTo(RowType row) { - - if (row.isSetDel()) - deleted = row.getDel(); - - for (CellType cell : row.getCellArray()) { - String cellName = cell.getN(); - - if (cellName.equals("X")) { - x = XDGFCell.parseDoubleValue(cell); - } else if (cellName.equals("Y")) { - y = XDGFCell.parseDoubleValue(cell); - } else if (cellName.equals("A")) { - a = XDGFCell.parseDoubleValue(cell); - } else if (cellName.equals("B")) { - b = XDGFCell.parseDoubleValue(cell); - } else if (cellName.equals("C")) { - c = XDGFCell.parseDoubleValue(cell); - } else if (cellName.equals("D")) { - d = XDGFCell.parseDoubleValue(cell); - } else { - throw new POIXMLException("Invalid cell '" + cellName - + "' in RelCubBezTo row"); - } - } - } - - public boolean getDel() { - if (deleted != null) - return deleted; - - if (_master != null) - return _master.getDel(); - - return false; - } - - public Double getX() { - return x == null ? _master.x : x; - } - - public Double getY() { - return y == null ? _master.y : y; - } - - public Double getA() { - return a == null ? _master.a : a; - } - - public Double getB() { - return b == null ? _master.b : b; - } - - public Double getC() { - return c == null ? _master.c : c; - } - - public Double getD() { - return d == null ? _master.d : d; - } - - @Override - public void setupMaster(GeometryRow row) { - _master = (RelCubBezTo) row; - } - - @Override - public void addToPath(java.awt.geom.Path2D.Double path, XDGFShape parent) { - - if (getDel()) - return; - - double w = parent.getWidth(); - double h = parent.getHeight(); - - path.curveTo(getA() * w, getB() * h, getC() * w, getD() * h, - getX() * w, getY() * h); - } -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/geometry/RelEllipticalArcTo.java b/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/geometry/RelEllipticalArcTo.java deleted file mode 100644 index 9b58406cd..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/geometry/RelEllipticalArcTo.java +++ /dev/null @@ -1,144 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xdgf.usermodel.section.geometry; - -import org.apache.poi.POIXMLException; -import org.apache.poi.xdgf.usermodel.XDGFCell; -import org.apache.poi.xdgf.usermodel.XDGFShape; - -import com.microsoft.schemas.office.visio.x2012.main.CellType; -import com.microsoft.schemas.office.visio.x2012.main.RowType; - -public class RelEllipticalArcTo implements GeometryRow { - - RelEllipticalArcTo _master = null; - - // The x-coordinate of the ending vertex on an arc relative to the width of - // the shape. - Double x = null; - - // The y-coordinate of the ending vertex on an arc relative to the height of - // the shape. - Double y = null; - - // The x-coordinate of the arc's control point relative to the shape's - // width; a point on the arc. - Double a = null; - - // The y-coordinate of an arc's control point relative to the shape's width. - Double b = null; - - // The angle of an arc's major axis relative to the x-axis of its parent. - Double c = null; - - // The ratio of an arc's major axis to its minor axis. Despite the usual - // meaning of these words, the "major" axis does not have to be greater than - // the "minor" axis, so this ratio does not have to be greater than 1. - Double d = null; - - Boolean deleted = null; - - // TODO: support formulas - - public RelEllipticalArcTo(RowType row) { - - if (row.isSetDel()) - deleted = row.getDel(); - - for (CellType cell : row.getCellArray()) { - String cellName = cell.getN(); - - if (cellName.equals("X")) { - x = XDGFCell.parseDoubleValue(cell); - } else if (cellName.equals("Y")) { - y = XDGFCell.parseDoubleValue(cell); - } else if (cellName.equals("A")) { - a = XDGFCell.parseDoubleValue(cell); - } else if (cellName.equals("B")) { - b = XDGFCell.parseDoubleValue(cell); - } else if (cellName.equals("C")) { - c = XDGFCell.parseDoubleValue(cell); - } else if (cellName.equals("D")) { - d = XDGFCell.parseDoubleValue(cell); - } else { - throw new POIXMLException("Invalid cell '" + cellName - + "' in RelEllipticalArcTo row"); - } - } - } - - public boolean getDel() { - if (deleted != null) - return deleted; - - if (_master != null) - return _master.getDel(); - - return false; - } - - public Double getX() { - return x == null ? _master.x : x; - } - - public Double getY() { - return y == null ? _master.y : y; - } - - public Double getA() { - return a == null ? _master.a : a; - } - - public Double getB() { - return b == null ? _master.b : b; - } - - public Double getC() { - return c == null ? _master.c : c; - } - - public Double getD() { - return d == null ? _master.d : d; - } - - @Override - public void setupMaster(GeometryRow row) { - _master = (RelEllipticalArcTo) row; - } - - @Override - public void addToPath(java.awt.geom.Path2D.Double path, XDGFShape parent) { - - if (getDel()) - return; - - double w = parent.getWidth(); - double h = parent.getHeight(); - - // intentionally shadowing variables here - double x = getX() * w; - double y = getY() * h; - double a = getA() * w; - double b = getB() * h; - double c = getC(); - double d = getD(); - - EllipticalArcTo.createEllipticalArc(x, y, a, b, c, d, path); - - } -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/geometry/RelLineTo.java b/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/geometry/RelLineTo.java deleted file mode 100644 index 1886f2059..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/geometry/RelLineTo.java +++ /dev/null @@ -1,92 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xdgf.usermodel.section.geometry; - -import org.apache.poi.POIXMLException; -import org.apache.poi.xdgf.usermodel.XDGFCell; -import org.apache.poi.xdgf.usermodel.XDGFShape; - -import com.microsoft.schemas.office.visio.x2012.main.CellType; -import com.microsoft.schemas.office.visio.x2012.main.RowType; - -/** - * Contains x-and y-coordinates of the ending vertex of a straight line segment - * relative to a shape's width and height. - */ -public class RelLineTo implements GeometryRow { - - RelLineTo _master = null; - - Double x = null; - Double y = null; - - Boolean deleted = null; - - // TODO: support formulas - - public RelLineTo(RowType row) { - - if (row.isSetDel()) - deleted = row.getDel(); - - for (CellType cell : row.getCellArray()) { - String cellName = cell.getN(); - - if (cellName.equals("X")) { - x = XDGFCell.parseDoubleValue(cell); - } else if (cellName.equals("Y")) { - y = XDGFCell.parseDoubleValue(cell); - } else { - throw new POIXMLException("Invalid cell '" + cellName - + "' in RelLineTo row"); - } - } - } - - public boolean getDel() { - if (deleted != null) - return deleted; - - if (_master != null) - return _master.getDel(); - - return false; - } - - public Double getX() { - return x == null ? _master.x : x; - } - - public Double getY() { - return y == null ? _master.y : y; - } - - @Override - public void setupMaster(GeometryRow row) { - _master = (RelLineTo) row; - } - - @Override - public void addToPath(java.awt.geom.Path2D.Double path, XDGFShape parent) { - - if (getDel()) - return; - - path.lineTo(getX() * parent.getWidth(), getY() * parent.getHeight()); - } -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/geometry/RelMoveTo.java b/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/geometry/RelMoveTo.java deleted file mode 100644 index 0b6f51c19..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/geometry/RelMoveTo.java +++ /dev/null @@ -1,88 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xdgf.usermodel.section.geometry; - -import org.apache.poi.POIXMLException; -import org.apache.poi.xdgf.usermodel.XDGFCell; -import org.apache.poi.xdgf.usermodel.XDGFShape; - -import com.microsoft.schemas.office.visio.x2012.main.CellType; -import com.microsoft.schemas.office.visio.x2012.main.RowType; - -public class RelMoveTo implements GeometryRow { - - RelMoveTo _master = null; - - Double x = null; - Double y = null; - - Boolean deleted = null; - - // TODO: support formulas - - public RelMoveTo(RowType row) { - - if (row.isSetDel()) - deleted = row.getDel(); - - for (CellType cell : row.getCellArray()) { - String cellName = cell.getN(); - - if (cellName.equals("X")) { - x = XDGFCell.parseDoubleValue(cell); - } else if (cellName.equals("Y")) { - y = XDGFCell.parseDoubleValue(cell); - } else { - throw new POIXMLException("Invalid cell '" + cellName - + "' in RelMoveTo row"); - } - } - } - - public boolean getDel() { - if (deleted != null) - return deleted; - - if (_master != null) - return _master.getDel(); - - return false; - } - - public Double getX() { - return x == null ? _master.x : x; - } - - public Double getY() { - return y == null ? _master.y : y; - } - - @Override - public void setupMaster(GeometryRow row) { - _master = (RelMoveTo) row; - } - - @Override - public void addToPath(java.awt.geom.Path2D.Double path, XDGFShape parent) { - - if (getDel()) - return; - - path.moveTo(getX() * parent.getWidth(), getY() * parent.getHeight()); - } -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/geometry/RelQuadBezTo.java b/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/geometry/RelQuadBezTo.java deleted file mode 100644 index ecb4a3a43..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/geometry/RelQuadBezTo.java +++ /dev/null @@ -1,122 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xdgf.usermodel.section.geometry; - -import org.apache.poi.POIXMLException; -import org.apache.poi.xdgf.usermodel.XDGFCell; -import org.apache.poi.xdgf.usermodel.XDGFShape; - -import com.microsoft.schemas.office.visio.x2012.main.CellType; -import com.microsoft.schemas.office.visio.x2012.main.RowType; - -/** - * Contains the x- and y-coordinates of the endpoint of a quadratic Bezier curve - * relative to the shape's width and height and the x- and y-coordinates of the - * control point of the curve relative shape's width and height. - */ -public class RelQuadBezTo implements GeometryRow { - - RelQuadBezTo _master = null; - - // The x-coordinate of the ending vertex of a quadratic Bezier curve - // relative to the width of the shape. - Double x = null; - - // The y-coordinate of the ending vertex of a quadratic Bezier curve - // relative to the height of the shape. - Double y = null; - - // The x-coordinate of the curve's control point relative to the shape's - // width; a point on the arc. The control point is best located about - // halfway between the beginning and ending vertices of the arc. - Double a = null; - - // The y-coordinate of a curve's control point relative to the shape's - // height. - Double b = null; - - Boolean deleted = null; - - // TODO: support formulas - - public RelQuadBezTo(RowType row) { - - if (row.isSetDel()) - deleted = row.getDel(); - - for (CellType cell : row.getCellArray()) { - String cellName = cell.getN(); - - if (cellName.equals("X")) { - x = XDGFCell.parseDoubleValue(cell); - } else if (cellName.equals("Y")) { - y = XDGFCell.parseDoubleValue(cell); - } else if (cellName.equals("A")) { - a = XDGFCell.parseDoubleValue(cell); - } else if (cellName.equals("B")) { - b = XDGFCell.parseDoubleValue(cell); - } else { - throw new POIXMLException("Invalid cell '" + cellName - + "' in RelQuadBezTo row"); - } - } - } - - public boolean getDel() { - if (deleted != null) - return deleted; - - if (_master != null) - return _master.getDel(); - - return false; - } - - public Double getX() { - return x == null ? _master.x : x; - } - - public Double getY() { - return y == null ? _master.y : y; - } - - public Double getA() { - return a == null ? _master.a : a; - } - - public Double getB() { - return b == null ? _master.b : b; - } - - @Override - public void setupMaster(GeometryRow row) { - _master = (RelQuadBezTo) row; - } - - @Override - public void addToPath(java.awt.geom.Path2D.Double path, XDGFShape parent) { - - if (getDel()) - return; - - double w = parent.getWidth(); - double h = parent.getHeight(); - - path.quadTo(getA() * w, getB() * h, getX() * w, getY() * h); - } -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/geometry/SplineKnot.java b/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/geometry/SplineKnot.java deleted file mode 100644 index f75490b07..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/geometry/SplineKnot.java +++ /dev/null @@ -1,106 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xdgf.usermodel.section.geometry; - -import org.apache.poi.POIXMLException; -import org.apache.poi.xdgf.usermodel.XDGFCell; -import org.apache.poi.xdgf.usermodel.XDGFShape; - -import com.microsoft.schemas.office.visio.x2012.main.CellType; -import com.microsoft.schemas.office.visio.x2012.main.RowType; - -/** - * Contains x- and y-coordinates for a spline's control point and a spline's - * knot. - */ -public class SplineKnot implements GeometryRow { - - SplineKnot _master = null; - - // The x-coordinate of a control point. - Double x = null; - - // The y-coordinate of a control point. - Double y = null; - - // One of the spline's knots (other than the last one or the first two). - Double a = null; - - Boolean deleted = null; - - // TODO: support formulas - - public SplineKnot(RowType row) { - - if (row.isSetDel()) - deleted = row.getDel(); - - for (CellType cell : row.getCellArray()) { - String cellName = cell.getN(); - - if (cellName.equals("X")) { - x = XDGFCell.parseDoubleValue(cell); - } else if (cellName.equals("Y")) { - y = XDGFCell.parseDoubleValue(cell); - } else if (cellName.equals("A")) { - a = XDGFCell.parseDoubleValue(cell); - } else { - throw new POIXMLException("Invalid cell '" + cellName - + "' in SplineKnot row"); - } - } - } - - public boolean getDel() { - if (deleted != null) - return deleted; - - if (_master != null) - return _master.getDel(); - - return false; - } - - public Double getX() { - return x == null ? _master.x : x; - } - - public Double getY() { - return y == null ? _master.y : y; - } - - public Double getA() { - return a == null ? _master.a : a; - } - - @Override - public void setupMaster(GeometryRow row) { - _master = (SplineKnot) row; - } - - @Override - public void addToPath(java.awt.geom.Path2D.Double path, XDGFShape parent) { - throw new POIXMLException("Error: Use SplineRenderer!"); - } - - @Override - public String toString() { - return "{SplineKnot x=" + getX() + " y=" + getY() + " a=" + getA() - + "}"; - } -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/geometry/SplineStart.java b/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/geometry/SplineStart.java deleted file mode 100644 index 224a36c03..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/usermodel/section/geometry/SplineStart.java +++ /dev/null @@ -1,132 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xdgf.usermodel.section.geometry; - -import org.apache.poi.POIXMLException; -import org.apache.poi.xdgf.usermodel.XDGFCell; -import org.apache.poi.xdgf.usermodel.XDGFShape; - -import com.microsoft.schemas.office.visio.x2012.main.CellType; -import com.microsoft.schemas.office.visio.x2012.main.RowType; - -/** - * Contains x- and y-coordinates for a spline's second control point, its second - * knot, its first knot, the last knot, and the degree of the spline. - */ -public class SplineStart implements GeometryRow { - - SplineStart _master = null; - - // The x-coordinate of a spline's second control point. - Double x = null; - - // The y-coordinate of a spline's second control point. - Double y = null; - - // The second knot of the spline. - Double a = null; - - // The first knot of a spline. - Double b = null; - - // The last knot of a spline. - Double c = null; - - // The degree of a spline (an integer from 1 to 25). - Integer d = null; - - Boolean deleted = null; - - // TODO: support formulas - - public SplineStart(RowType row) { - - if (row.isSetDel()) - deleted = row.getDel(); - - for (CellType cell : row.getCellArray()) { - String cellName = cell.getN(); - - if (cellName.equals("X")) { - x = XDGFCell.parseDoubleValue(cell); - } else if (cellName.equals("Y")) { - y = XDGFCell.parseDoubleValue(cell); - } else if (cellName.equals("A")) { - a = XDGFCell.parseDoubleValue(cell); - } else if (cellName.equals("B")) { - b = XDGFCell.parseDoubleValue(cell); - } else if (cellName.equals("C")) { - c = XDGFCell.parseDoubleValue(cell); - } else if (cellName.equals("D")) { - d = XDGFCell.parseIntegerValue(cell); - } else { - throw new POIXMLException("Invalid cell '" + cellName - + "' in SplineStart row"); - } - } - } - - public boolean getDel() { - if (deleted != null) - return deleted; - - if (_master != null) - return _master.getDel(); - - return false; - } - - public Double getX() { - return x == null ? _master.x : x; - } - - public Double getY() { - return y == null ? _master.y : y; - } - - public Double getA() { - return a == null ? _master.a : a; - } - - public Double getB() { - return b == null ? _master.b : b; - } - - public Double getC() { - return c == null ? _master.c : c; - } - - public Integer getD() { - return d == null ? _master.d : d; - } - - @Override - public void setupMaster(GeometryRow row) { - _master = (SplineStart) row; - } - - @Override - public void addToPath(java.awt.geom.Path2D.Double path, XDGFShape parent) { - throw new POIXMLException("Error: Use SplineRenderer!"); - } - - @Override - public String toString() { - return "{SplineStart x=" + getX() + " y=" + getY() + " a=" + getA() - + " b=" + getB() + " c=" + getC() + " d=" + getD() + "}"; - } -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/usermodel/shape/ShapeDataAcceptor.java b/src/ooxml/java/org/apache/poi/xdgf/usermodel/shape/ShapeDataAcceptor.java deleted file mode 100644 index 57c9cdec9..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/usermodel/shape/ShapeDataAcceptor.java +++ /dev/null @@ -1,65 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xdgf.usermodel.shape; - -import org.apache.poi.xdgf.usermodel.XDGFShape; - -/** - * This acceptor only allows traversal to shapes that have useful data - * associated with them, and tries to elide details that aren't useful when - * analyzing the content of a document. - * - * Useful is subjective of course, and is defined as any of: - * - * - Has non-empty text - Is a 1d shape, such as a line - User specified shapes - * - The outline of stencil objects - TODO - */ -public class ShapeDataAcceptor implements ShapeVisitorAcceptor { - - @Override - public boolean accept(XDGFShape shape) { - - if (shape.isDeleted()) - return false; - - // text is interesting - if (shape.hasText() && shape.getTextAsString().length() != 0) - return true; - - // 1d shapes are interesting, they create connections - if (shape.isShape1D()) - return true; - - // User specified shapes are interesting - if (!shape.hasMaster() && !shape.hasMasterShape()) - return true; - - if (shape.hasMaster() && !shape.hasMasterShape()) - return true; - - // include stencil content, but try to elide stencil interiors - // if (shape.getXmlObject().isSetMaster()) - // return true; - - if (shape.hasMasterShape() && shape.getMasterShape().isTopmost()) - return true; - - return false; - } - -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/usermodel/shape/ShapeDebuggerRenderer.java b/src/ooxml/java/org/apache/poi/xdgf/usermodel/shape/ShapeDebuggerRenderer.java deleted file mode 100644 index d4a010ba2..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/usermodel/shape/ShapeDebuggerRenderer.java +++ /dev/null @@ -1,69 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xdgf.usermodel.shape; - -import java.awt.Font; -import java.awt.Graphics2D; -import java.awt.geom.Path2D; - -import org.apache.poi.xdgf.usermodel.XDGFShape; - -public class ShapeDebuggerRenderer extends ShapeRenderer { - - ShapeVisitorAcceptor _debugAcceptor = null; - - public ShapeDebuggerRenderer() { - super(); - } - - public ShapeDebuggerRenderer(Graphics2D g) { - super(g); - } - - public void setDebugAcceptor(ShapeVisitorAcceptor acceptor) { - _debugAcceptor = acceptor; - } - - @Override - protected Path2D drawPath(XDGFShape shape) { - - Path2D path = super.drawPath(shape); - if (_debugAcceptor == null || _debugAcceptor.accept(shape)) { - - // show numbers to associate shapes with ids.. doesn't always work - Font f = _graphics.getFont(); - _graphics.scale(1, -1); - _graphics.setFont(f.deriveFont(0.05F)); - - String shapeId = "" + shape.getID(); - float shapeOffset = -0.1F; - - if (shape.hasMasterShape()) { - shapeId += " MS:" + shape.getMasterShape().getID(); - shapeOffset -= 0.15F; - } - - _graphics.drawString(shapeId, shapeOffset, 0); - _graphics.setFont(f); - _graphics.scale(1, -1); - } - - return path; - } - -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/usermodel/shape/ShapeRenderer.java b/src/ooxml/java/org/apache/poi/xdgf/usermodel/shape/ShapeRenderer.java deleted file mode 100644 index a6a76642d..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/usermodel/shape/ShapeRenderer.java +++ /dev/null @@ -1,94 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xdgf.usermodel.shape; - -import java.awt.Font; -import java.awt.Graphics2D; -import java.awt.geom.AffineTransform; -import java.awt.geom.Path2D; - -import org.apache.poi.xdgf.usermodel.XDGFShape; -import org.apache.poi.xdgf.usermodel.XDGFText; - -/** - * To use this to render only particular shapes, override it and provide an - * appropriate implementation of getAcceptor() or accept() - */ -public class ShapeRenderer extends ShapeVisitor { - - protected Graphics2D _graphics; - - public ShapeRenderer() { - _graphics = null; - } - - public ShapeRenderer(Graphics2D g) { - _graphics = g; - } - - public void setGraphics(Graphics2D g) { - _graphics = g; - } - - @Override - public void visit(XDGFShape shape, AffineTransform globalTransform, - int level) { - - AffineTransform savedTr = _graphics.getTransform(); - _graphics.transform(globalTransform); - - drawPath(shape); - drawText(shape); - - // we're done, undo the transforms - _graphics.setTransform(savedTr); - } - - protected Path2D drawPath(XDGFShape shape) { - Path2D.Double path = shape.getPath(); - if (path != null) { - - // setup the stroke for this line - - _graphics.setColor(shape.getLineColor()); - _graphics.setStroke(shape.getStroke()); - _graphics.draw(path); - } - - return path; - } - - protected void drawText(XDGFShape shape) { - XDGFText text = shape.getText(); - if (text != null) { - - if (text.getTextContent().equals("Header")) - text.getTextBounds(); - - Font oldFont = _graphics.getFont(); - - _graphics.setFont(oldFont.deriveFont(shape.getFontSize() - .floatValue())); - _graphics.setColor(shape.getFontColor()); - - text.draw(_graphics); - _graphics.setFont(oldFont); - } - } - -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/usermodel/shape/ShapeTextVisitor.java b/src/ooxml/java/org/apache/poi/xdgf/usermodel/shape/ShapeTextVisitor.java deleted file mode 100644 index 9a0f28cf5..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/usermodel/shape/ShapeTextVisitor.java +++ /dev/null @@ -1,57 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xdgf.usermodel.shape; - -import java.awt.geom.AffineTransform; - -import org.apache.poi.xdgf.usermodel.XDGFShape; - -/** - * Only visits text nodes, accumulates text content into a string - * - * The text is returned in arbitrary order, with no regards to - * the location of the text on the page. This may change in the - * future. - */ -public class ShapeTextVisitor extends ShapeVisitor { - - protected StringBuilder text = new StringBuilder(); - - public static class TextAcceptor implements ShapeVisitorAcceptor { - public boolean accept(XDGFShape shape) { - return shape.hasText(); - } - } - - protected ShapeVisitorAcceptor getAcceptor() { - return new TextAcceptor(); - } - - public void visit(XDGFShape shape, AffineTransform globalTransform, - int level) { - text.append(shape.getText().getTextContent().trim()); - text.append('\n'); - } - - /** - * Call this after visitation has completed - */ - public String getText() { - return text.toString(); - } - -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/usermodel/shape/ShapeVisitor.java b/src/ooxml/java/org/apache/poi/xdgf/usermodel/shape/ShapeVisitor.java deleted file mode 100644 index 2e4d89647..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/usermodel/shape/ShapeVisitor.java +++ /dev/null @@ -1,74 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xdgf.usermodel.shape; - -import java.awt.geom.AffineTransform; - -import org.apache.poi.xdgf.usermodel.XDGFShape; - -/** - * Used to iterate through shapes - * - * To change the behavior of a particular visitor, you can override either - * accept() or getAcceptor() [preferred] - * - * If accept() or visit() throw StopVisitingThisBranch, the iteration will not - * visit subshapes of the shape. - */ -public abstract class ShapeVisitor { - - protected ShapeVisitorAcceptor _acceptor; - - public ShapeVisitor() { - _acceptor = getAcceptor(); - } - - /** - * Is only called on construction of the visitor, allows - * mixing visitors and acceptors - */ - protected ShapeVisitorAcceptor getAcceptor() { - return new ShapeVisitorAcceptor() { - @Override - public boolean accept(XDGFShape shape) { - return !shape.isDeleted(); - } - }; - } - - public void setAcceptor(ShapeVisitorAcceptor acceptor) { - _acceptor = acceptor; - } - - public boolean accept(XDGFShape shape) { - return _acceptor.accept(shape); - } - - /** - * @param shape - * Current shape - * @param globalTransform - * A transform that can convert the shapes points to global - * coordinates - * @param level - * Level in the tree (0 is topmost, 1 is next level... - */ - public abstract void visit(XDGFShape shape, - AffineTransform globalTransform, int level); - -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/usermodel/shape/ShapeVisitorAcceptor.java b/src/ooxml/java/org/apache/poi/xdgf/usermodel/shape/ShapeVisitorAcceptor.java deleted file mode 100644 index e50ce11ea..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/usermodel/shape/ShapeVisitorAcceptor.java +++ /dev/null @@ -1,26 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xdgf.usermodel.shape; - -import org.apache.poi.xdgf.usermodel.XDGFShape; - -public interface ShapeVisitorAcceptor { - - public boolean accept(XDGFShape shape); - -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/usermodel/shape/exceptions/StopVisiting.java b/src/ooxml/java/org/apache/poi/xdgf/usermodel/shape/exceptions/StopVisiting.java deleted file mode 100644 index 2a33c4340..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/usermodel/shape/exceptions/StopVisiting.java +++ /dev/null @@ -1,24 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xdgf.usermodel.shape.exceptions; - -public class StopVisiting extends RuntimeException { - - private static final long serialVersionUID = -4651207777092840750L; - -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/usermodel/shape/exceptions/StopVisitingThisBranch.java b/src/ooxml/java/org/apache/poi/xdgf/usermodel/shape/exceptions/StopVisitingThisBranch.java deleted file mode 100644 index eb9e4a620..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/usermodel/shape/exceptions/StopVisitingThisBranch.java +++ /dev/null @@ -1,24 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xdgf.usermodel.shape.exceptions; - -public class StopVisitingThisBranch extends RuntimeException { - - private static final long serialVersionUID = 5262319077534717862L; - -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/util/HierarchyPrinter.java b/src/ooxml/java/org/apache/poi/xdgf/util/HierarchyPrinter.java deleted file mode 100644 index eb9aa9796..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/util/HierarchyPrinter.java +++ /dev/null @@ -1,96 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xdgf.util; - -import java.awt.geom.AffineTransform; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.OutputStream; -import java.io.PrintStream; -import java.io.UnsupportedEncodingException; - -import org.apache.poi.xdgf.usermodel.XDGFPage; -import org.apache.poi.xdgf.usermodel.XDGFShape; -import org.apache.poi.xdgf.usermodel.XmlVisioDocument; -import org.apache.poi.xdgf.usermodel.shape.ShapeVisitor; - -/** - * Debugging tool useful when trying to figure out the hierarchy of the - * shapes in a Visio diagram - */ -public class HierarchyPrinter { - - public static void printHierarchy(XDGFPage page, File outDir) - throws FileNotFoundException, UnsupportedEncodingException { - - File pageFile = new File(outDir, "page" + page.getPageNumber() + "-" - + Util.sanitizeFilename(page.getName()) + ".txt"); - - OutputStream os = new FileOutputStream(pageFile); - PrintStream pos = new PrintStream(os, false, "utf-8"); - - printHierarchy(page, pos); - - pos.close(); - } - - public static void printHierarchy(XDGFPage page, final PrintStream os) { - - page.getContent().visitShapes(new ShapeVisitor() { - - @Override - public void visit(XDGFShape shape, AffineTransform globalTransform, - int level) { - for (int i = 0; i < level; i++) { - os.append(" "); - } - // TODO: write text? - os.println(shape.toString() + " [" + shape.getShapeType() - + ", " + shape.getSymbolName() + "] " - + shape.getMasterShape() + " " - + shape.getTextAsString().trim()); - } - }); - } - - public static void printHierarchy(XmlVisioDocument document, - String outDirname) throws FileNotFoundException, UnsupportedEncodingException { - - File outDir = new File(outDirname); - - for (XDGFPage page : document.getPages()) { - printHierarchy(page, outDir); - } - } - - public static void main(String[] args) throws Exception { - if (args.length != 2) { - System.err.println("Usage: in.vsdx outdir"); - System.exit(1); - } - - String inFilename = args[0]; - String outDir = args[1]; - - XmlVisioDocument doc = new XmlVisioDocument(new FileInputStream( - inFilename)); - printHierarchy(doc, outDir); - } -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/util/ObjectFactory.java b/src/ooxml/java/org/apache/poi/xdgf/util/ObjectFactory.java deleted file mode 100644 index af0253f59..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/util/ObjectFactory.java +++ /dev/null @@ -1,57 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xdgf.util; - -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.util.HashMap; -import java.util.Map; - -import org.apache.poi.POIXMLException; -import org.apache.xmlbeans.XmlObject; - - -public class ObjectFactory { - - Map> _types = new HashMap>(); - - public void put(String typeName, Class cls, Class... varargs) throws NoSuchMethodException, SecurityException { - _types.put(typeName, cls.getDeclaredConstructor(varargs)); - } - - public T load(String name, Object... varargs) { - Constructor constructor = _types.get(name); - if (constructor == null) { - - @SuppressWarnings("unchecked") - X xmlObject = (X) varargs[0]; - - String typeName = xmlObject.schemaType().getName().getLocalPart(); - throw new POIXMLException("Invalid '" + typeName + "' name '" + name + "'"); - } - - try { - return constructor.newInstance(varargs); - } catch (InvocationTargetException e) { - throw new POIXMLException(e.getCause()); - } catch (Exception e) { - throw new POIXMLException(e); - } - } - -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/util/Util.java b/src/ooxml/java/org/apache/poi/xdgf/util/Util.java deleted file mode 100644 index 0e08294c8..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/util/Util.java +++ /dev/null @@ -1,37 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xdgf.util; - -public class Util { - - public static int countLines(String str) { - int lines = 1; - int pos = 0; - while ((pos = str.indexOf("\n", pos) + 1) != 0) { - lines++; - } - return lines; - } - - // this probably isn't 100% correct, so don't use it in security-sensitive - // applications! - // from: http://www.rgagnon.com/javadetails/java-0662.html - public static String sanitizeFilename(String name) { - return name.replaceAll("[:\\\\/*\"?|<>]", "_"); - } -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/util/VsdxToPng.java b/src/ooxml/java/org/apache/poi/xdgf/util/VsdxToPng.java deleted file mode 100644 index 7706ca19e..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/util/VsdxToPng.java +++ /dev/null @@ -1,134 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xdgf.util; - -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.RenderingHints; -import java.awt.image.BufferedImage; -import java.io.*; - -import javax.imageio.ImageIO; - -import org.apache.poi.xdgf.geom.Dimension2dDouble; -import org.apache.poi.xdgf.usermodel.XDGFPage; -import org.apache.poi.xdgf.usermodel.XmlVisioDocument; -import org.apache.poi.xdgf.usermodel.shape.ShapeDebuggerRenderer; -import org.apache.poi.xdgf.usermodel.shape.ShapeRenderer; - -/** - * Converts a Visio diagram to a PNG file. - * - * As more elements and styles are added/supported the output will get - * better, but it's very rough right now. - */ -public class VsdxToPng { - - public static void renderToPng(XDGFPage page, String outFilename, - double scale, ShapeRenderer renderer) throws IOException { - renderToPng(page, new File(outFilename), scale, renderer); - } - - public static void renderToPngDir(XDGFPage page, File outDir, double scale, - ShapeRenderer renderer) throws IOException { - - File pageFile = new File(outDir, "page" + page.getPageNumber() + "-" - + Util.sanitizeFilename(page.getName()) + ".png"); - System.out.println("** Writing image to " + pageFile); - - renderToPng(page, pageFile, scale, renderer); - - } - - public static void renderToPng(XDGFPage page, File outFile, double scale, - ShapeRenderer renderer) throws IOException { - - Dimension2dDouble sz = page.getPageSize(); - - int width = (int) (scale * sz.getWidth()); - int height = (int) (scale * sz.getHeight()); - - BufferedImage img = new BufferedImage(width, height, - BufferedImage.TYPE_INT_RGB); - final Graphics2D graphics = img.createGraphics(); - - // default rendering options - graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, - RenderingHints.VALUE_ANTIALIAS_ON); - graphics.setRenderingHint(RenderingHints.KEY_RENDERING, - RenderingHints.VALUE_RENDER_QUALITY); - graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, - RenderingHints.VALUE_INTERPOLATION_BICUBIC); - graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, - RenderingHints.VALUE_FRACTIONALMETRICS_ON); - - graphics.setColor(Color.black); - graphics.setBackground(Color.white); - graphics.clearRect(0, 0, width, height); - - // Visio's coordinate system is flipped, so flip the image vertically - graphics.translate(0, img.getHeight()); - graphics.scale(scale, -scale); - - // toplevel shapes only - renderer.setGraphics(graphics); - page.getContent().visitShapes(renderer); - - graphics.dispose(); - - OutputStream out = new FileOutputStream(outFile); - try { - ImageIO.write(img, "png", out); - } finally { - out.close(); - } - } - - public static void renderToPng(XmlVisioDocument document, - String outDirname, double scale, ShapeRenderer renderer) - throws IOException { - - File outDir = new File(outDirname); - - for (XDGFPage page : document.getPages()) { - renderToPngDir(page, outDir, scale, renderer); - } - } - - public static void main(String[] args) throws Exception { - if (args.length > 2) { - System.err.println("Usage: [--debug] in.vsdx outdir"); - System.exit(1); - } - - ShapeRenderer renderer = new ShapeRenderer(); - - String inFilename = args[0]; - String pngDir = args[1]; - - if (args[0].equals("--debug")) { - inFilename = args[1]; - pngDir = args[2]; - renderer = new ShapeDebuggerRenderer(); - } - - XmlVisioDocument doc = new XmlVisioDocument(new FileInputStream( - inFilename)); - renderToPng(doc, pngDir, 2000 / 11.0, renderer); - } -} diff --git a/src/ooxml/java/org/apache/poi/xdgf/xml/XDGFXMLDocumentPart.java b/src/ooxml/java/org/apache/poi/xdgf/xml/XDGFXMLDocumentPart.java deleted file mode 100644 index 79e549e00..000000000 --- a/src/ooxml/java/org/apache/poi/xdgf/xml/XDGFXMLDocumentPart.java +++ /dev/null @@ -1,34 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xdgf.xml; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.xdgf.usermodel.XDGFDocument; - -public class XDGFXMLDocumentPart extends POIXMLDocumentPart { - - protected XDGFDocument _document; - - /** - * @since POI 3.14-Beta1 - */ - public XDGFXMLDocumentPart(PackagePart part, XDGFDocument document) { - super(part); - _document = document; - } -} diff --git a/src/ooxml/java/org/apache/poi/xslf/extractor/XSLFPowerPointExtractor.java b/src/ooxml/java/org/apache/poi/xslf/extractor/XSLFPowerPointExtractor.java deleted file mode 100644 index d3ff89613..000000000 --- a/src/ooxml/java/org/apache/poi/xslf/extractor/XSLFPowerPointExtractor.java +++ /dev/null @@ -1,222 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.extractor; - -import java.io.IOException; - -import org.apache.poi.POIXMLTextExtractor; -import org.apache.poi.openxml4j.exceptions.OpenXML4JException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.xslf.usermodel.XMLSlideShow; -import org.apache.poi.xslf.usermodel.XSLFCommentAuthors; -import org.apache.poi.xslf.usermodel.XSLFComments; -import org.apache.poi.xslf.usermodel.XSLFNotes; -import org.apache.poi.xslf.usermodel.XSLFRelation; -import org.apache.poi.xslf.usermodel.XSLFShape; -import org.apache.poi.xslf.usermodel.XSLFShapeContainer; -import org.apache.poi.xslf.usermodel.XSLFSlide; -import org.apache.poi.xslf.usermodel.XSLFSlideLayout; -import org.apache.poi.xslf.usermodel.XSLFSlideMaster; -import org.apache.poi.xslf.usermodel.XSLFSlideShow; -import org.apache.poi.xslf.usermodel.XSLFTable; -import org.apache.poi.xslf.usermodel.XSLFTableCell; -import org.apache.poi.xslf.usermodel.XSLFTableRow; -import org.apache.poi.xslf.usermodel.XSLFTextShape; -import org.apache.xmlbeans.XmlException; -import org.openxmlformats.schemas.presentationml.x2006.main.CTComment; -import org.openxmlformats.schemas.presentationml.x2006.main.CTCommentAuthor; - -public class XSLFPowerPointExtractor extends POIXMLTextExtractor { - public static final XSLFRelation[] SUPPORTED_TYPES = new XSLFRelation[] { - XSLFRelation.MAIN, XSLFRelation.MACRO, XSLFRelation.MACRO_TEMPLATE, - XSLFRelation.PRESENTATIONML, XSLFRelation.PRESENTATIONML_TEMPLATE, - XSLFRelation.PRESENTATION_MACRO - }; - - private XMLSlideShow slideshow; - private boolean slidesByDefault = true; - private boolean notesByDefault = false; - private boolean masterByDefault = false; - - public XSLFPowerPointExtractor(XMLSlideShow slideshow) { - super(slideshow); - this.slideshow = slideshow; - } - public XSLFPowerPointExtractor(XSLFSlideShow slideshow) throws XmlException, IOException { - this(new XMLSlideShow(slideshow.getPackage())); - } - public XSLFPowerPointExtractor(OPCPackage container) throws XmlException, OpenXML4JException, IOException { - this(new XSLFSlideShow(container)); - } - - public static void main(String[] args) throws Exception { - if(args.length < 1) { - System.err.println("Use:"); - System.err.println(" XSLFPowerPointExtractor "); - System.exit(1); - } - POIXMLTextExtractor extractor = - new XSLFPowerPointExtractor( - new XSLFSlideShow(args[0])); - System.out.println(extractor.getText()); - extractor.close(); - } - - /** - * Should a call to getText() return slide text? - * Default is yes - */ - public void setSlidesByDefault(boolean slidesByDefault) { - this.slidesByDefault = slidesByDefault; - } - /** - * Should a call to getText() return notes text? - * Default is no - */ - public void setNotesByDefault(boolean notesByDefault) { - this.notesByDefault = notesByDefault; - } - - /** - * Should a call to getText() return text from master? Default is no - */ - public void setMasterByDefault(boolean masterByDefault) { - this.masterByDefault = masterByDefault; - } - - /** - * Gets the slide text, but not the notes text - */ - @Override - public String getText() { - return getText(slidesByDefault, notesByDefault); - } - - /** - * Gets the requested text from the file - * @param slideText Should we retrieve text from slides? - * @param notesText Should we retrieve text from notes? - */ - public String getText(boolean slideText, boolean notesText) { - return getText(slideText, notesText, masterByDefault); - } - - /** - * Gets the requested text from the file - * - * @param slideText Should we retrieve text from slides? - * @param notesText Should we retrieve text from notes? - * @param masterText Should we retrieve text from master slides? - * - * @return the extracted text - */ - public String getText(boolean slideText, boolean notesText, boolean masterText) { - StringBuilder text = new StringBuilder(); - - for (XSLFSlide slide : slideshow.getSlides()) { - text.append(getText(slide, slideText, notesText, masterText)); - } - - return text.toString(); - } - - /** - * Gets the requested text from the slide - * - * @param slide the slide to retrieve the text from - * @param slideText Should we retrieve text from slides? - * @param notesText Should we retrieve text from notes? - * @param masterText Should we retrieve text from master slides? - * - * @return the extracted text - */ - public static String getText(XSLFSlide slide, boolean slideText, boolean notesText, boolean masterText) { - StringBuilder text = new StringBuilder(); - - XSLFCommentAuthors commentAuthors = slide.getSlideShow().getCommentAuthors(); - - XSLFNotes notes = slide.getNotes(); - XSLFComments comments = slide.getComments(); - XSLFSlideLayout layout = slide.getSlideLayout(); - XSLFSlideMaster master = layout.getSlideMaster(); - - // TODO Do the slide's name - // (Stored in docProps/app.xml) - - // Do the slide's text if requested - if (slideText) { - extractText(slide, false, text); - - // If requested, get text from the master and it's layout - if(masterText) { - assert (layout != null); - extractText(layout, true, text); - assert (master != null); - extractText(master, true, text); - } - - // If the slide has comments, do those too - if (comments != null) { - for (CTComment comment : comments.getCTCommentsList().getCmArray()) { - // Do the author if we can - if (commentAuthors != null) { - CTCommentAuthor author = commentAuthors.getAuthorById(comment.getAuthorId()); - if(author != null) { - text.append(author.getName() + ": "); - } - } - - // Then the comment text, with a new line afterwards - text.append(comment.getText()); - text.append("\n"); - } - } - } - - // Do the notes if requested - if (notesText && notes != null) { - extractText(notes, false, text); - } - - return text.toString(); - } - - private static void extractText(XSLFShapeContainer data, boolean skipPlaceholders, StringBuilder text) { - for (XSLFShape s : data) { - if (s instanceof XSLFShapeContainer) { - extractText((XSLFShapeContainer)s, skipPlaceholders, text); - } else if (s instanceof XSLFTextShape) { - XSLFTextShape ts = (XSLFTextShape)s; - // Skip non-customised placeholder text - if (!(skipPlaceholders && ts.isPlaceholder())) { - text.append(ts.getText()); - text.append("\n"); - } - } else if (s instanceof XSLFTable) { - XSLFTable ts = (XSLFTable)s; - // Skip non-customised placeholder text - for (XSLFTableRow r : ts) { - for (XSLFTableCell c : r) { - text.append(c.getText()); - text.append("\t"); - } - text.append("\n"); - } - } - } - } -} diff --git a/src/ooxml/java/org/apache/poi/xslf/model/CharacterPropertyFetcher.java b/src/ooxml/java/org/apache/poi/xslf/model/CharacterPropertyFetcher.java deleted file mode 100644 index fd8b40fc0..000000000 --- a/src/ooxml/java/org/apache/poi/xslf/model/CharacterPropertyFetcher.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xslf.model; - -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextCharacterProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextParagraphProperties; - -public abstract class CharacterPropertyFetcher extends ParagraphPropertyFetcher { - public CharacterPropertyFetcher(int level) { - super(level); - } - - public boolean fetch(CTTextParagraphProperties props) { - if (props != null && props.isSetDefRPr()) { - return fetch(props.getDefRPr()); - } - - return false; - } - - public abstract boolean fetch(CTTextCharacterProperties props); - -} \ No newline at end of file diff --git a/src/ooxml/java/org/apache/poi/xslf/model/ParagraphPropertyFetcher.java b/src/ooxml/java/org/apache/poi/xslf/model/ParagraphPropertyFetcher.java deleted file mode 100644 index 6085b9d80..000000000 --- a/src/ooxml/java/org/apache/poi/xslf/model/ParagraphPropertyFetcher.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xslf.model; - -import org.apache.poi.xslf.usermodel.XSLFShape; -import org.apache.xmlbeans.XmlObject; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextParagraphProperties; - -/** - * - * @author Yegor Kozlov - */ -public abstract class ParagraphPropertyFetcher extends PropertyFetcher { - int _level; - - public ParagraphPropertyFetcher(int level) { - _level = level; - } - - public boolean fetch(XSLFShape shape) { - - XmlObject[] o = shape.getXmlObject().selectPath( - "declare namespace p='http://schemas.openxmlformats.org/presentationml/2006/main' " + - "declare namespace a='http://schemas.openxmlformats.org/drawingml/2006/main' " + - ".//p:txBody/a:lstStyle/a:lvl" + (_level + 1) + "pPr" - ); - if (o.length == 1) { - CTTextParagraphProperties props = (CTTextParagraphProperties) o[0]; - return fetch(props); - } - return false; - } - - public abstract boolean fetch(CTTextParagraphProperties props); -} \ No newline at end of file diff --git a/src/ooxml/java/org/apache/poi/xslf/model/PropertyFetcher.java b/src/ooxml/java/org/apache/poi/xslf/model/PropertyFetcher.java deleted file mode 100644 index 2875e0345..000000000 --- a/src/ooxml/java/org/apache/poi/xslf/model/PropertyFetcher.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xslf.model; - -import org.apache.poi.util.Internal; -import org.apache.poi.xslf.usermodel.XSLFShape; - -/** - * Used internally to navigate the PresentationML text style hierarchy and fetch properties - * - * @author Yegor Kozlov -*/ -@Internal -public abstract class PropertyFetcher { - private T _value; - - /** - * - * @param shape the shape being examined - * @return true if the desired property was fetched - */ - public abstract boolean fetch(XSLFShape shape); - - public T getValue(){ - return _value; - } - - public void setValue(T val){ - _value = val; - } -} diff --git a/src/ooxml/java/org/apache/poi/xslf/model/TextBodyPropertyFetcher.java b/src/ooxml/java/org/apache/poi/xslf/model/TextBodyPropertyFetcher.java deleted file mode 100644 index 4b1d546e7..000000000 --- a/src/ooxml/java/org/apache/poi/xslf/model/TextBodyPropertyFetcher.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xslf.model; - -import org.apache.poi.xslf.usermodel.XSLFShape; -import org.apache.xmlbeans.XmlObject; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextBodyProperties; - -/** - * Created by IntelliJ IDEA. - * User: yegor - * Date: Oct 21, 2011 - * Time: 1:18:52 PM - * To change this template use File | Settings | File Templates. - */ -public abstract class TextBodyPropertyFetcher extends PropertyFetcher { - - public boolean fetch(XSLFShape shape) { - - XmlObject[] o = shape.getXmlObject().selectPath( - "declare namespace p='http://schemas.openxmlformats.org/presentationml/2006/main' " + - "declare namespace a='http://schemas.openxmlformats.org/drawingml/2006/main' " + - ".//p:txBody/a:bodyPr" - ); - if (o.length == 1) { - CTTextBodyProperties props = (CTTextBodyProperties) o[0]; - return fetch(props); - } - - return false; - } - - public abstract boolean fetch(CTTextBodyProperties props); - -} \ No newline at end of file diff --git a/src/ooxml/java/org/apache/poi/xslf/usermodel/DrawingParagraph.java b/src/ooxml/java/org/apache/poi/xslf/usermodel/DrawingParagraph.java deleted file mode 100644 index 6a6ee3807..000000000 --- a/src/ooxml/java/org/apache/poi/xslf/usermodel/DrawingParagraph.java +++ /dev/null @@ -1,57 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xslf.usermodel; - -import org.apache.poi.util.Removal; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlObject; -import org.openxmlformats.schemas.drawingml.x2006.main.CTRegularTextRun; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextLineBreak; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextParagraph; - -/* - * @deprecated POI 3.16 beta 1. Instead iterate over the shapes/notes of the slides - */ -@Removal(version="3.18") -public class DrawingParagraph { - private final CTTextParagraph p; - - public DrawingParagraph(CTTextParagraph p) { - this.p = p; - } - - public CharSequence getText() { - StringBuilder text = new StringBuilder(); - - XmlCursor c = p.newCursor(); - c.selectPath("./*"); - while (c.toNextSelection()) { - XmlObject o = c.getObject(); - if (o instanceof CTRegularTextRun) { - CTRegularTextRun txrun = (CTRegularTextRun) o; - text.append(txrun.getT()); - } else if (o instanceof CTTextLineBreak) { - text.append('\n'); - } - } - - c.dispose(); - - return text; - } -} diff --git a/src/ooxml/java/org/apache/poi/xslf/usermodel/DrawingTable.java b/src/ooxml/java/org/apache/poi/xslf/usermodel/DrawingTable.java deleted file mode 100644 index b59a5bb23..000000000 --- a/src/ooxml/java/org/apache/poi/xslf/usermodel/DrawingTable.java +++ /dev/null @@ -1,45 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xslf.usermodel; - -import org.apache.poi.util.Removal; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTable; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTableRow; - -/* - * @deprecated POI 3.16 beta 1. use {@link XSLFTable} instead - */ -@Removal(version="3.18") -public class DrawingTable { - private final CTTable table; - - public DrawingTable(CTTable table) { - this.table = table; - } - - public DrawingTableRow[] getRows() { - CTTableRow[] ctTableRows = table.getTrArray(); - DrawingTableRow[] o = new DrawingTableRow[ctTableRows.length]; - - for (int i=0; i { - private static final POILogger LOG = POILogFactory.getLogger(XMLSlideShow.class); - - private CTPresentation _presentation; - private List _slides; - private List _masters; - private List _pictures; - private XSLFTableStyles _tableStyles; - private XSLFNotesMaster _notesMaster; - private XSLFCommentAuthors _commentAuthors; - - public XMLSlideShow() { - this(empty()); - } - - public XMLSlideShow(OPCPackage pkg) { - super(pkg); - - try { - if(getCorePart().getContentType().equals(XSLFRelation.THEME_MANAGER.getContentType())) { - rebase(getPackage()); - } - - //build a tree of POIXMLDocumentParts, this presentation being the root - load(XSLFFactory.getInstance()); - } catch (Exception e){ - throw new POIXMLException(e); - } - } - - public XMLSlideShow(InputStream is) throws IOException { - this(PackageHelper.open(is)); - } - - static OPCPackage empty() { - InputStream is = XMLSlideShow.class.getResourceAsStream("empty.pptx"); - if (is == null) { - throw new POIXMLException("Missing resource 'empty.pptx'"); - } - try { - return OPCPackage.open(is); - } catch (Exception e){ - throw new POIXMLException(e); - } finally { - IOUtils.closeQuietly(is); - } - } - - @Override - protected void onDocumentRead() throws IOException { - try { - PresentationDocument doc = - PresentationDocument.Factory.parse(getCorePart().getInputStream(), DEFAULT_XML_OPTIONS); - _presentation = doc.getPresentation(); - - Map masterMap = new HashMap(); - Map shIdMap = new HashMap(); - for (RelationPart rp : getRelationParts()) { - POIXMLDocumentPart p = rp.getDocumentPart(); - if (p instanceof XSLFSlide) { - shIdMap.put(rp.getRelationship().getId(), (XSLFSlide) p); - } else if (p instanceof XSLFSlideMaster) { - masterMap.put(getRelationId(p), (XSLFSlideMaster) p); - } else if (p instanceof XSLFTableStyles){ - _tableStyles = (XSLFTableStyles)p; - } else if (p instanceof XSLFNotesMaster) { - _notesMaster = (XSLFNotesMaster)p; - } else if (p instanceof XSLFCommentAuthors) { - _commentAuthors = (XSLFCommentAuthors)p; - } - } - - _masters = new ArrayList(masterMap.size()); - for (CTSlideMasterIdListEntry masterId : _presentation.getSldMasterIdLst().getSldMasterIdList()) { - XSLFSlideMaster master = masterMap.get(masterId.getId2()); - _masters.add(master); - } - - _slides = new ArrayList(shIdMap.size()); - if (_presentation.isSetSldIdLst()) { - for (CTSlideIdListEntry slId : _presentation.getSldIdLst().getSldIdList()) { - XSLFSlide sh = shIdMap.get(slId.getId2()); - if (sh == null) { - LOG.log(POILogger.WARN, "Slide with r:id " + slId.getId() + " was defined, but didn't exist in package, skipping"); - continue; - } - _slides.add(sh); - } - } - } catch (XmlException e) { - throw new POIXMLException(e); - } - } - - @Override - protected void commit() throws IOException { - PackagePart part = getPackagePart(); - OutputStream out = part.getOutputStream(); - _presentation.save(out, DEFAULT_XML_OPTIONS); - out.close(); - } - - /** - * Get the document's embedded files. - */ - @Override - public List getAllEmbedds() throws OpenXML4JException { - return Collections.unmodifiableList( - getPackage().getPartsByName(Pattern.compile("/ppt/embeddings/.*?")) - ); - } - - @Override - public List getPictureData() { - if(_pictures == null){ - List mediaParts = getPackage().getPartsByName(Pattern.compile("/ppt/media/.*?")); - _pictures = new ArrayList(mediaParts.size()); - for(PackagePart part : mediaParts){ - XSLFPictureData pd = new XSLFPictureData(part); - pd.setIndex(_pictures.size()); - _pictures.add(pd); - } - } - return Collections.unmodifiableList(_pictures); - } - - /** - * Create a slide and initialize it from the specified layout. - * - * @param layout The layout to use for the new slide. - * @return created slide - */ - public XSLFSlide createSlide(XSLFSlideLayout layout) { - int slideNumber = 256, cnt = 1; - CTSlideIdList slideList; - if (!_presentation.isSetSldIdLst()) { - slideList = _presentation.addNewSldIdLst(); - } else { - slideList = _presentation.getSldIdLst(); - for(CTSlideIdListEntry slideId : slideList.getSldIdArray()){ - slideNumber = (int)Math.max(slideId.getId() + 1, slideNumber); - cnt++; - } - - // Bug 55791: We also need to check that the resulting file name is not already taken - // this can happen when removing/adding slides - while(true) { - String slideName = XSLFRelation.SLIDE.getFileName(cnt); - boolean found = false; - for (POIXMLDocumentPart relation : getRelations()) { - if (relation.getPackagePart() != null && - slideName.equals(relation.getPackagePart().getPartName().getName())) { - // name is taken => try next one - found = true; - break; - } - } - - if(!found && - getPackage().getPartsByName(Pattern.compile(Pattern.quote(slideName))).size() > 0) { - // name is taken => try next one - found = true; - } - - if (!found) { - break; - } - cnt++; - } - } - - RelationPart rp = createRelationship( - XSLFRelation.SLIDE, XSLFFactory.getInstance(), cnt, false); - XSLFSlide slide = rp.getDocumentPart(); - - CTSlideIdListEntry slideId = slideList.addNewSldId(); - slideId.setId(slideNumber); - slideId.setId2(rp.getRelationship().getId()); - - layout.copyLayout(slide); - slide.addRelation(null, XSLFRelation.SLIDE_LAYOUT, layout); - - _slides.add(slide); - return slide; - } - - /** - * Create a blank slide using the default (first) master. - */ - @Override - public XSLFSlide createSlide() { - XSLFSlideMaster sm = _masters.get(0); - XSLFSlideLayout layout = sm.getLayout(SlideLayout.BLANK); - if (layout == null) { - LOG.log(POILogger.WARN, "Blank layout was not found - defaulting to first slide layout in master"); - XSLFSlideLayout sl[] = sm.getSlideLayouts(); - if (sl.length == 0) { - throw new POIXMLException("SlideMaster must contain a SlideLayout."); - } - layout = sl[0]; - } - - return createSlide(layout); - } - - /** - * Return notes slide for the specified slide or create new if it does not exist yet. - */ - public XSLFNotes getNotesSlide(XSLFSlide slide) { - - XSLFNotes notesSlide = slide.getNotes(); - if (notesSlide == null) { - notesSlide = createNotesSlide(slide); - } - - return notesSlide; - } - - /** - * Create a blank notes slide. - */ - private XSLFNotes createNotesSlide(XSLFSlide slide) { - - if (_notesMaster == null) { - createNotesMaster(); - } - - Integer slideIndex = XSLFRelation.SLIDE.getFileNameIndex(slide); - - // Bug 55791: We also need to check that the resulting file name is not already taken - // this can happen when removing/adding slides - while(true) { - String slideName = XSLFRelation.NOTES.getFileName(slideIndex); - boolean found = false; - for (POIXMLDocumentPart relation : getRelations()) { - if (relation.getPackagePart() != null && - slideName.equals(relation.getPackagePart().getPartName().getName())) { - // name is taken => try next one - found = true; - break; - } - } - - if(!found && - getPackage().getPartsByName(Pattern.compile(Pattern.quote(slideName))).size() > 0) { - // name is taken => try next one - found = true; - } - - if (!found) { - break; - } - slideIndex++; - } - - // add notes slide to presentation - XSLFNotes notesSlide = (XSLFNotes) createRelationship - (XSLFRelation.NOTES, XSLFFactory.getInstance(), slideIndex); - // link slide and notes slide with each other - slide.addRelation(null, XSLFRelation.NOTES, notesSlide); - notesSlide.addRelation(null, XSLFRelation.NOTES_MASTER, _notesMaster); - notesSlide.addRelation(null, XSLFRelation.SLIDE, slide); - - notesSlide.importContent(_notesMaster); - - return notesSlide; - } - - /** - * Create a notes master. - */ - public void createNotesMaster() { - RelationPart rp = createRelationship - (XSLFRelation.NOTES_MASTER, XSLFFactory.getInstance(), 1, false); - _notesMaster = rp.getDocumentPart(); - - CTNotesMasterIdList notesMasterIdList = _presentation.addNewNotesMasterIdLst(); - CTNotesMasterIdListEntry notesMasterId = notesMasterIdList.addNewNotesMasterId(); - notesMasterId.setId(rp.getRelationship().getId()); - - Integer themeIndex = 1; - // TODO: check if that list can be replaced by idx = Math.max(idx,themeIdx) - List themeIndexList = new ArrayList(); - for (POIXMLDocumentPart p : getRelations()) { - if (p instanceof XSLFTheme) { - themeIndexList.add(XSLFRelation.THEME.getFileNameIndex(p)); - } - } - - if (!themeIndexList.isEmpty()) { - Boolean found = false; - for (Integer i = 1; i <= themeIndexList.size(); i++) { - if (!themeIndexList.contains(i)) { - found = true; - themeIndex = i; - } - } - if (!found) { - themeIndex = themeIndexList.size() + 1; - } - } - - XSLFTheme theme = (XSLFTheme) createRelationship - (XSLFRelation.THEME, XSLFFactory.getInstance(), themeIndex); - theme.importTheme(getSlides().get(0).getTheme()); - - _notesMaster.addRelation(null, XSLFRelation.THEME, theme); - } - - /** - * Return the Notes Master, if there is one. - * (May not be present if no notes exist) - */ - public XSLFNotesMaster getNotesMaster() { - return _notesMaster; - } - - @Override - public List getSlideMasters() { - return _masters; - } - - /** - * Return all the slides in the slideshow - */ - @Override - public List getSlides() { - return _slides; - } - - /** - * Returns the list of comment authors, if there is one. - * Will only be present if at least one slide has comments on it. - */ - public XSLFCommentAuthors getCommentAuthors() { - return _commentAuthors; - } - - /** - * - * @param newIndex 0-based index of the slide - */ - public void setSlideOrder(XSLFSlide slide, int newIndex){ - int oldIndex = _slides.indexOf(slide); - if(oldIndex == -1) { - throw new IllegalArgumentException("Slide not found"); - } - if (oldIndex == newIndex) { - return; - } - - // fix the usermodel container - _slides.add(newIndex, _slides.remove(oldIndex)); - - // fix ordering in the low-level xml - CTSlideIdList sldIdLst = _presentation.getSldIdLst(); - CTSlideIdListEntry[] entries = sldIdLst.getSldIdArray(); - CTSlideIdListEntry oldEntry = entries[oldIndex]; - if (oldIndex < newIndex) { - System.arraycopy(entries, oldIndex + 1, entries, oldIndex, newIndex - oldIndex); - } else { - System.arraycopy(entries, newIndex, entries, newIndex + 1, oldIndex - newIndex); - } - entries[newIndex] = oldEntry; - sldIdLst.setSldIdArray(entries); - } - - public XSLFSlide removeSlide(int index){ - XSLFSlide slide = _slides.remove(index); - removeRelation(slide); - _presentation.getSldIdLst().removeSldId(index); - return slide; - } - - @Override - public Dimension getPageSize(){ - CTSlideSize sz = _presentation.getSldSz(); - int cx = sz.getCx(); - int cy = sz.getCy(); - return new Dimension((int)Units.toPoints(cx), (int)Units.toPoints(cy)); - } - - @Override - public void setPageSize(Dimension pgSize){ - CTSlideSize sz = CTSlideSize.Factory.newInstance(); - sz.setCx(Units.toEMU(pgSize.getWidth())); - sz.setCy(Units.toEMU(pgSize.getHeight())); - _presentation.setSldSz(sz); - } - - - @Internal - public CTPresentation getCTPresentation(){ - return _presentation; - } - - /** - * Adds a picture to the workbook. - * - * @param pictureData The bytes of the picture - * @param format The format of the picture. - * - * @return the picture data - */ - @Override - public XSLFPictureData addPicture(byte[] pictureData, PictureType format) { - XSLFPictureData img = findPictureData(pictureData); - - if (img != null) { - return img; - } - - int imageNumber = _pictures.size(); - XSLFRelation relType = XSLFPictureData.getRelationForType(format); - if (relType == null) { - throw new IllegalArgumentException("Picture type "+format+" is not supported."); - } - img = (XSLFPictureData) createRelationship(relType, XSLFFactory.getInstance(), imageNumber + 1, true).getDocumentPart(); - img.setIndex(imageNumber); - _pictures.add(img); - try { - OutputStream out = img.getPackagePart().getOutputStream(); - out.write(pictureData); - out.close(); - } catch (IOException e) { - throw new POIXMLException(e); - } - - return img; - } - - - /** - * Adds a picture to the slideshow. - * - * @param is The stream to read image from - * @param format The format of the picture - * - * @return the picture data - * @since 3.15 beta 2 - */ - @Override - public XSLFPictureData addPicture(InputStream is, PictureType format) throws IOException - { - return addPicture(IOUtils.toByteArray(is), format); - } - - - /** - * Adds a picture to the presentation. - * - * @param pict The file containing the image to add - * @param format The format of the picture. - * - * @return the picture data - * @since 3.15 beta 2 - */ - @Override - public XSLFPictureData addPicture(File pict, PictureType format) throws IOException - { - int length = (int) pict.length(); - byte[] data = new byte[length]; - FileInputStream is = new FileInputStream(pict); - try { - IOUtils.readFully(is, data); - } finally { - is.close(); - } - return addPicture(data, format); - } - - - /** - * check if a picture with this picture data already exists in this presentation - * - * @param pictureData The picture data to find in the SlideShow - * @return {@code null} if picture data is not found in this slideshow - * @since 3.15 beta 2 - */ - @Override - public XSLFPictureData findPictureData(byte[] pictureData) { - long checksum = IOUtils.calculateChecksum(pictureData); - byte cs[] = new byte[LittleEndianConsts.LONG_SIZE]; - LittleEndian.putLong(cs,0,checksum); - - for(XSLFPictureData pic : getPictureData()){ - if(Arrays.equals(pic.getChecksum(), cs)) { - return pic; - } - } - return null; - } - - - /** - * Scan the master slides for the first slide layout with the given name. - * - * @param name The layout name (case-insensitive). Cannot be null. - * @return the first layout found or null on failure - */ - public XSLFSlideLayout findLayout(String name) { - for (XSLFSlideMaster master : getSlideMasters()) { - XSLFSlideLayout layout = master.getLayout(name); - if (layout != null) { - return layout; - } - } - return null; - } - - - public XSLFTableStyles getTableStyles(){ - return _tableStyles; - } - - CTTextParagraphProperties getDefaultParagraphStyle(int level) { - XmlObject[] o = _presentation.selectPath( - "declare namespace p='http://schemas.openxmlformats.org/presentationml/2006/main' " + - "declare namespace a='http://schemas.openxmlformats.org/drawingml/2006/main' " + - ".//p:defaultTextStyle/a:lvl" +(level+1)+ "pPr"); - if(o.length == 1){ - return (CTTextParagraphProperties)o[0]; - } - return null; - } - - @Override - public MasterSheet createMasterSheet() throws IOException { - // TODO: implement! - throw new UnsupportedOperationException(); - } - - @Override - public Resources getResources() { - // TODO: implement! - throw new UnsupportedOperationException(); - } -} diff --git a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFAutoShape.java b/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFAutoShape.java deleted file mode 100644 index 9dfa62fa0..000000000 --- a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFAutoShape.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xslf.usermodel; - -import org.apache.poi.sl.usermodel.AutoShape; -import org.apache.poi.util.Beta; -import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPresetGeometry2D; -import org.openxmlformats.schemas.drawingml.x2006.main.CTShapeProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextBody; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextBodyProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextCharacterProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextParagraph; -import org.openxmlformats.schemas.drawingml.x2006.main.STShapeType; -import org.openxmlformats.schemas.drawingml.x2006.main.STTextAlignType; -import org.openxmlformats.schemas.drawingml.x2006.main.STTextAnchoringType; -import org.openxmlformats.schemas.presentationml.x2006.main.CTShape; -import org.openxmlformats.schemas.presentationml.x2006.main.CTShapeNonVisual; - - -/** - * Represents a shape with a preset geometry. - * - * @author Yegor Kozlov - */ -@Beta -public class XSLFAutoShape extends XSLFTextShape - implements AutoShape { - - /*package*/ XSLFAutoShape(CTShape shape, XSLFSheet sheet) { - super(shape, sheet); - } - - /*package*/ - static XSLFAutoShape create(CTShape shape, XSLFSheet sheet) { - if (shape.getSpPr().isSetCustGeom()) { - return new XSLFFreeformShape(shape, sheet); - } else if (shape.getNvSpPr().getCNvSpPr().isSetTxBox()) { - return new XSLFTextBox(shape, sheet); - } else { - return new XSLFAutoShape(shape, sheet); - } - } - - /** - * @param shapeId 1-based shapeId - */ - static CTShape prototype(int shapeId) { - CTShape ct = CTShape.Factory.newInstance(); - CTShapeNonVisual nvSpPr = ct.addNewNvSpPr(); - CTNonVisualDrawingProps cnv = nvSpPr.addNewCNvPr(); - cnv.setName("AutoShape " + shapeId); - cnv.setId(shapeId + 1); - nvSpPr.addNewCNvSpPr(); - nvSpPr.addNewNvPr(); - CTShapeProperties spPr = ct.addNewSpPr(); - CTPresetGeometry2D prst = spPr.addNewPrstGeom(); - prst.setPrst(STShapeType.RECT); - prst.addNewAvLst(); - return ct; - } - - protected static void initTextBody(CTTextBody txBody) { - CTTextBodyProperties bodypr = txBody.addNewBodyPr(); - bodypr.setAnchor(STTextAnchoringType.T); - bodypr.setRtlCol(false); - CTTextParagraph p = txBody.addNewP(); - p.addNewPPr().setAlgn(STTextAlignType.L); - CTTextCharacterProperties endPr = p.addNewEndParaRPr(); - endPr.setLang("en-US"); - endPr.setSz(1100); - p.addNewR().setT(""); - txBody.addNewLstStyle(); - } - - protected CTTextBody getTextBody(boolean create){ - CTShape shape = (CTShape)getXmlObject(); - CTTextBody txBody = shape.getTxBody(); - if (txBody == null && create) { - txBody = shape.addNewTxBody(); - initTextBody(txBody); - } - return txBody; - } - - @Override - public String toString(){ - return "[" + getClass().getSimpleName() + "] " + getShapeName(); - } - -} diff --git a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFBackground.java b/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFBackground.java deleted file mode 100644 index 343f33bae..000000000 --- a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFBackground.java +++ /dev/null @@ -1,112 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xslf.usermodel; - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.geom.Rectangle2D; - -import org.apache.poi.POIXMLException; -import org.apache.poi.sl.usermodel.Background; -import org.apache.poi.sl.usermodel.Placeholder; -import org.apache.xmlbeans.XmlObject; -import org.openxmlformats.schemas.drawingml.x2006.main.CTSolidColorFillProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTransform2D; -import org.openxmlformats.schemas.presentationml.x2006.main.CTBackground; -import org.openxmlformats.schemas.presentationml.x2006.main.CTBackgroundProperties; - -/** - * Background shape - */ -public class XSLFBackground extends XSLFSimpleShape - implements Background { - - /* package */XSLFBackground(CTBackground shape, XSLFSheet sheet) { - super(shape, sheet); - } - - @Override - public Rectangle2D getAnchor(){ - Dimension pg = getSheet().getSlideShow().getPageSize(); - return new Rectangle2D.Double(0, 0, pg.getWidth(), pg.getHeight()); - } - - /** - * background does not have a associated transform, therefore we return null - * - * @param create ignored - * - * @return null - */ - @Override - protected CTTransform2D getXfrm(boolean create) { - return null; - } - - @Override - public void setPlaceholder(Placeholder placeholder) { - // extending XSLFSimpleShape is a bit unlucky ... - throw new POIXMLException("Can't set a placeholder for a background"); - } - - protected CTBackgroundProperties getBgPr(boolean create) { - CTBackground bg = (CTBackground)getXmlObject(); - if (!bg.isSetBgPr() && create) { - if (bg.isSetBgRef()) { - bg.unsetBgRef(); - } - return bg.addNewBgPr(); - } - return bg.getBgPr(); - } - - public void setFillColor(Color color) { - CTBackgroundProperties bgPr = getBgPr(true); - - if (color == null) { - if (bgPr.isSetSolidFill()) { - bgPr.unsetSolidFill(); - } - - if (!bgPr.isSetNoFill()) { - bgPr.addNewNoFill(); - } - } else { - if (bgPr.isSetNoFill()) { - bgPr.unsetNoFill(); - } - - CTSolidColorFillProperties fill = bgPr.isSetSolidFill() ? bgPr.getSolidFill() : bgPr.addNewSolidFill(); - - XSLFColor col = new XSLFColor(fill, getSheet().getTheme(), fill.getSchemeClr()); - col.setColor(color); - } - } - - @Override - protected XmlObject getShapeProperties() { - CTBackground bg = (CTBackground)getXmlObject(); - if (bg.isSetBgPr()) { - return bg.getBgPr(); - } else if (bg.isSetBgRef()) { - return bg.getBgRef(); - } else { - return null; - } - } -} diff --git a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFChart.java b/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFChart.java deleted file mode 100644 index 942c13bea..000000000 --- a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFChart.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xslf.usermodel; - -import static org.apache.poi.POIXMLTypeLoader.DEFAULT_XML_OPTIONS; - -import java.io.IOException; -import java.io.OutputStream; - -import javax.xml.namespace.QName; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.util.Beta; -import org.apache.poi.util.Internal; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlOptions; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTChart; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTChartSpace; -import org.openxmlformats.schemas.drawingml.x2006.chart.ChartSpaceDocument; - -/** - * Represents a Chart in a .pptx presentation - * - * - */ -@Beta -public final class XSLFChart extends POIXMLDocumentPart { - - /** - * Root element of the Chart part - */ - private CTChartSpace chartSpace; - - /** - * The Chart within that - */ - private CTChart chart; - - /** - * Construct a chart from a package part. - * - * @param part the package part holding the chart data, - * the content type must be application/vnd.openxmlformats-officedocument.drawingml.chart+xml - * - * @since POI 3.14-Beta1 - */ - protected XSLFChart(PackagePart part) throws IOException, XmlException { - super(part); - - chartSpace = ChartSpaceDocument.Factory.parse(part.getInputStream(), DEFAULT_XML_OPTIONS).getChartSpace(); - chart = chartSpace.getChart(); - } - - /** - * Return the underlying CTChartSpace bean, the root element of the Chart part. - * - * @return the underlying CTChartSpace bean - */ - @Internal - public CTChartSpace getCTChartSpace(){ - return chartSpace; - } - - /** - * Return the underlying CTChart bean, within the Chart Space - * - * @return the underlying CTChart bean - */ - @Internal - public CTChart getCTChart(){ - return chart; - } - - @Override - protected void commit() throws IOException { - XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS); - xmlOptions.setSaveSyntheticDocumentElement(new QName(CTChartSpace.type.getName().getNamespaceURI(), "chartSpace", "c")); - - PackagePart part = getPackagePart(); - OutputStream out = part.getOutputStream(); - chartSpace.save(out, xmlOptions); - out.close(); - } - - -} diff --git a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFColor.java b/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFColor.java deleted file mode 100644 index d5c40a7cc..000000000 --- a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFColor.java +++ /dev/null @@ -1,496 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -package org.apache.poi.xslf.usermodel; - -import java.awt.Color; - -import org.apache.poi.sl.draw.DrawPaint; -import org.apache.poi.sl.usermodel.ColorStyle; -import org.apache.poi.sl.usermodel.PresetColor; -import org.apache.poi.util.Beta; -import org.apache.poi.util.Internal; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.xmlbeans.XmlObject; -import org.openxmlformats.schemas.drawingml.x2006.main.CTColor; -import org.openxmlformats.schemas.drawingml.x2006.main.CTFontReference; -import org.openxmlformats.schemas.drawingml.x2006.main.CTHslColor; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveFixedPercentage; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPresetColor; -import org.openxmlformats.schemas.drawingml.x2006.main.CTSRgbColor; -import org.openxmlformats.schemas.drawingml.x2006.main.CTScRgbColor; -import org.openxmlformats.schemas.drawingml.x2006.main.CTSchemeColor; -import org.openxmlformats.schemas.drawingml.x2006.main.CTSolidColorFillProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTSystemColor; -import org.w3c.dom.Node; - -/** - * Encapsulates logic to read color definitions from DrawingML and convert them to java.awt.Color - */ -@Beta -@Internal -public class XSLFColor { - private final static POILogger LOGGER = POILogFactory.getLogger(XSLFColor.class); - - private XmlObject _xmlObject; - private Color _color; - private CTSchemeColor _phClr; - - public XSLFColor(XmlObject obj, XSLFTheme theme, CTSchemeColor phClr) { - _xmlObject = obj; - _phClr = phClr; - _color = toColor(obj, theme); - } - - @Internal - public XmlObject getXmlObject() { - return _xmlObject; - } - - /** - * - * @return the displayed color as a Java Color. - * If not color information was found in the supplied xml object then a null is returned. - */ - public Color getColor() { - return DrawPaint.applyColorTransform(getColorStyle()); - } - - public ColorStyle getColorStyle() { - return new ColorStyle() { - @Override - public Color getColor() { - return _color; - } - - @Override - public int getAlpha() { - return getRawValue("alpha"); - } - - @Override - public int getHueOff() { - return getRawValue("hueOff"); - } - - @Override - public int getHueMod() { - return getRawValue("hueMod"); - } - - @Override - public int getSatOff() { - return getRawValue("satOff"); - } - - @Override - public int getSatMod() { - return getRawValue("satMod"); - } - - @Override - public int getLumOff() { - return getRawValue("lumOff"); - } - - @Override - public int getLumMod() { - return getRawValue("lumMod"); - } - - @Override - public int getShade() { - return getRawValue("shade"); - } - - @Override - public int getTint() { - return getRawValue("tint"); - } - }; - } - - Color toColor(XmlObject obj, XSLFTheme theme) { - Color color = null; - for (XmlObject ch : obj.selectPath("*")) { - if (ch instanceof CTHslColor) { - CTHslColor hsl = (CTHslColor)ch; - int h = hsl.getHue2(); - int s = hsl.getSat2(); - int l = hsl.getLum2(); - color = DrawPaint.HSL2RGB(h / 60000d, s / 1000d, l / 1000d, 1d); - } else if (ch instanceof CTPresetColor) { - CTPresetColor prst = (CTPresetColor)ch; - String colorName = prst.getVal().toString(); - PresetColor pc = PresetColor.valueOfOoxmlId(colorName); - if (pc != null) { - color = pc.color; - } - } else if (ch instanceof CTSchemeColor) { - CTSchemeColor schemeColor = (CTSchemeColor)ch; - String colorRef = schemeColor.getVal().toString(); - if(_phClr != null) { - // context color overrides the theme - colorRef = _phClr.getVal().toString(); - } - // find referenced CTColor in the theme and convert it to java.awt.Color via a recursive call - CTColor ctColor = theme.getCTColor(colorRef); - if(ctColor != null) { - color = toColor(ctColor, null); - } - } else if (ch instanceof CTScRgbColor) { - // color in percentage is in linear RGB color space, i.e. needs to be gamma corrected for AWT color - CTScRgbColor scrgb = (CTScRgbColor)ch; - color = new Color(DrawPaint.lin2srgb(scrgb.getR()), DrawPaint.lin2srgb(scrgb.getG()), DrawPaint.lin2srgb(scrgb.getB())); - } else if (ch instanceof CTSRgbColor) { - // color in sRGB color space, i.e. same as AWT Color - CTSRgbColor srgb = (CTSRgbColor)ch; - byte[] val = srgb.getVal(); - color = new Color(0xFF & val[0], 0xFF & val[1], 0xFF & val[2]); - } else if (ch instanceof CTSystemColor) { - CTSystemColor sys = (CTSystemColor)ch; - if(sys.isSetLastClr()) { - byte[] val = sys.getLastClr(); - color = new Color(0xFF & val[0], 0xFF & val[1], 0xFF & val[2]); - } else { - String colorName = sys.getVal().toString(); - PresetColor pc = PresetColor.valueOfOoxmlId(colorName); - if (pc != null) { - color = pc.color; - } - if (color == null) { - color = Color.black; - } - } - } else if (ch instanceof CTFontReference) { - // try next ... - continue; - } else { - throw new IllegalArgumentException("Unexpected color choice: " + ch.getClass()); - } - } - return color; - } - - /** - * Sets the solid color - * - * @param color solid color - */ - @Internal - protected void setColor(Color color) { - if (!(_xmlObject instanceof CTSolidColorFillProperties)) { - LOGGER.log(POILogger.ERROR, "XSLFColor.setColor currently only supports CTSolidColorFillProperties"); - return; - } - CTSolidColorFillProperties fill = (CTSolidColorFillProperties)_xmlObject; - if (fill.isSetSrgbClr()) { - fill.unsetSrgbClr(); - } - - if (fill.isSetScrgbClr()) { - fill.unsetScrgbClr(); - } - - if (fill.isSetHslClr()) { - fill.unsetHslClr(); - } - - if (fill.isSetPrstClr()) { - fill.unsetPrstClr(); - } - - if (fill.isSetSchemeClr()) { - fill.unsetSchemeClr(); - } - - if (fill.isSetSysClr()) { - fill.unsetSysClr(); - } - - float[] rgbaf = color.getRGBComponents(null); - boolean addAlpha = (rgbaf.length == 4 && rgbaf[3] < 1f); - CTPositiveFixedPercentage alphaPct; - - // see office open xml part 4 - 5.1.2.2.30 and 5.1.2.2.32 - if (isInt(rgbaf[0]) && isInt(rgbaf[1]) && isInt(rgbaf[2])) { - // sRGB has a gamma of 2.2 - CTSRgbColor rgb = fill.addNewSrgbClr(); - - byte rgbBytes[] = { (byte)color.getRed(), (byte)color.getGreen(), (byte)color.getBlue() }; - rgb.setVal(rgbBytes); - alphaPct = (addAlpha) ? rgb.addNewAlpha() : null; - } else { - CTScRgbColor rgb = fill.addNewScrgbClr(); - rgb.setR(DrawPaint.srgb2lin(rgbaf[0])); - rgb.setG(DrawPaint.srgb2lin(rgbaf[1])); - rgb.setB(DrawPaint.srgb2lin(rgbaf[2])); - alphaPct = (addAlpha) ? rgb.addNewAlpha() : null; - } - - // alpha (%) - if (alphaPct != null) { - alphaPct.setVal((int)(100000 * rgbaf[3])); - } - } - - /** - * @return true, if this is an integer color value - */ - private static boolean isInt(float f) { - return Math.abs((f*255f) - Math.rint(f*255f)) < 0.00001f; - } - - private int getRawValue(String elem) { - String query = "declare namespace a='http://schemas.openxmlformats.org/drawingml/2006/main' $this//a:" + elem; - - XmlObject[] obj; - - // first ask the context color and if not found, ask the actual color bean - if (_phClr != null){ - obj = _phClr.selectPath(query); - if (obj.length == 1){ - Node attr = obj[0].getDomNode().getAttributes().getNamedItem("val"); - if(attr != null) { - return Integer.parseInt(attr.getNodeValue()); - } - } - } - - obj = _xmlObject.selectPath(query); - if (obj.length == 1){ - Node attr = obj[0].getDomNode().getAttributes().getNamedItem("val"); - if(attr != null) { - return Integer.parseInt(attr.getNodeValue()); - } - } - - return -1; - } - - /** - * Read a perecentage value from the supplied xml bean. - * Example: - * - * - * the returned value is 45 - * - * @return the percentage value in the range [0 .. 100] - */ - private int getPercentageValue(String elem){ - int val = getRawValue(elem); - return (val == -1) ? val : (val / 1000); - } - - private int getAngleValue(String elem){ - int val = getRawValue(elem); - return (val == -1) ? val : (val / 60000); - } - - /** - * the opacity as expressed by a percentage value - * - * @return opacity in percents in the range [0..100] - * or -1 if the value is not set - */ - int getAlpha(){ - return getPercentageValue("alpha"); - } - - /** - * the opacity as expressed by a percentage relative to the input color - * - * @return opacity in percents in the range [0..100] - * or -1 if the value is not set - */ - int getAlphaMod(){ - return getPercentageValue("alphaMod"); - } - - /** - * the opacity as expressed by a percentage offset increase or decrease relative to - * the input color. Increases will never increase the opacity beyond 100%, decreases will - * never decrease the opacity below 0%. - * - * @return opacity shift in percents in the range [0..100] - * or -1 if the value is not set - */ - int getAlphaOff(){ - return getPercentageValue("alphaOff"); - } - - - int getHue(){ - return getAngleValue("hue"); - } - - int getHueMod(){ - return getPercentageValue("hueMod"); - } - - int getHueOff(){ - return getPercentageValue("hueOff"); - } - - /** - * specifies the input color with the specified luminance, - * but with its hue and saturation unchanged. - * - * @return luminance in percents in the range [0..100] - * or -1 if the value is not set - */ - int getLum(){ - return getPercentageValue("lum"); - } - - /** - * the luminance as expressed by a percentage relative to the input color - * - * @return luminance in percents in the range [0..100] - * or -1 if the value is not set - */ - int getLumMod(){ - return getPercentageValue("lumMod"); - } - - /** - * the luminance shift as expressed by a percentage relative to the input color - * - * @return luminance shift in percents in the range [0..100] - * or -1 if the value is not set - */ - int getLumOff(){ - return getPercentageValue("lumOff"); - } - - /** - * specifies the input color with the specified saturation, - * but with its hue and luminance unchanged. - * - * @return saturation in percents in the range [0..100] - * or -1 if the value is not set - */ - int getSat(){ - return getPercentageValue("sat"); - } - - /** - * the saturation as expressed by a percentage relative to the input color - * - * @return saturation in percents in the range [0..100] - * or -1 if the value is not set - */ - int getSatMod(){ - return getPercentageValue("satMod"); - } - - /** - * the saturation shift as expressed by a percentage relative to the input color - * - * @return saturation shift in percents in the range [0..100] - * or -1 if the value is not set - */ - int getSatOff(){ - return getPercentageValue("satOff"); - } - - /** - * specifies the input color with the specific red component, but with the blue and green color - * components unchanged - * - * @return the value of the red component specified as a - * percentage with 0% indicating minimal blue and 100% indicating maximum - * or -1 if the value is not set - */ - int getRed(){ - return getPercentageValue("red"); - } - - int getRedMod(){ - return getPercentageValue("redMod"); - } - - int getRedOff(){ - return getPercentageValue("redOff"); - } - - /** - * specifies the input color with the specific green component, but with the red and blue color - * components unchanged - * - * @return the value of the green component specified as a - * percentage with 0% indicating minimal blue and 100% indicating maximum - * or -1 if the value is not set - */ - int getGreen(){ - return getPercentageValue("green"); - } - - int getGreenMod(){ - return getPercentageValue("greenMod"); - } - - int getGreenOff(){ - return getPercentageValue("greenOff"); - } - - /** - * specifies the input color with the specific blue component, but with the red and green color - * components unchanged - * - * @return the value of the blue component specified as a - * percentage with 0% indicating minimal blue and 100% indicating maximum - * or -1 if the value is not set - */ - int getBlue(){ - return getPercentageValue("blue"); - } - - int getBlueMod(){ - return getPercentageValue("blueMod"); - } - - int getBlueOff(){ - return getPercentageValue("blueOff"); - } - - /** - * specifies a darker version of its input color. - * A 10% shade is 10% of the input color combined with 90% black. - * - * @return the value of the shade specified as a - * percentage with 0% indicating minimal shade and 100% indicating maximum - * or -1 if the value is not set - */ - public int getShade(){ - return getPercentageValue("shade"); - } - - /** - * specifies a lighter version of its input color. - * A 10% tint is 10% of the input color combined with 90% white. - * - * @return the value of the tint specified as a - * percentage with 0% indicating minimal tint and 100% indicating maximum - * or -1 if the value is not set - */ - public int getTint(){ - return getPercentageValue("tint"); - } -} diff --git a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFCommentAuthors.java b/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFCommentAuthors.java deleted file mode 100644 index 61dff5b56..000000000 --- a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFCommentAuthors.java +++ /dev/null @@ -1,73 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xslf.usermodel; - -import static org.apache.poi.POIXMLTypeLoader.DEFAULT_XML_OPTIONS; - -import java.io.IOException; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.util.Beta; -import org.apache.xmlbeans.XmlException; -import org.openxmlformats.schemas.presentationml.x2006.main.CTCommentAuthor; -import org.openxmlformats.schemas.presentationml.x2006.main.CTCommentAuthorList; -import org.openxmlformats.schemas.presentationml.x2006.main.CmAuthorLstDocument; - -@Beta -public class XSLFCommentAuthors extends POIXMLDocumentPart { - private final CTCommentAuthorList _authors; - - /** - * Create a new set of slide comments - */ - XSLFCommentAuthors() { - super(); - CmAuthorLstDocument doc = CmAuthorLstDocument.Factory.newInstance(); - _authors = doc.addNewCmAuthorLst(); - } - - /** - * Construct a SpreadsheetML slide authors from a package part - * - * @param part the package part holding the comment authors data, - * the content type must be application/vnd.openxmlformats-officedocument.commentAuthors+xml - * - * @since POI 3.14-Beta1 - */ - XSLFCommentAuthors(PackagePart part) throws IOException, XmlException { - super(part); - CmAuthorLstDocument doc = - CmAuthorLstDocument.Factory.parse(getPackagePart().getInputStream(), DEFAULT_XML_OPTIONS); - _authors = doc.getCmAuthorLst(); - } - - public CTCommentAuthorList getCTCommentAuthorsList() { - return _authors; - } - - public CTCommentAuthor getAuthorById(long id) { - // TODO Have a map - for (CTCommentAuthor author : _authors.getCmAuthorArray()) { - if (author.getId() == id) { - return author; - } - } - return null; - } -} diff --git a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFComments.java b/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFComments.java deleted file mode 100644 index 04e09c865..000000000 --- a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFComments.java +++ /dev/null @@ -1,72 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xslf.usermodel; - -import static org.apache.poi.POIXMLTypeLoader.DEFAULT_XML_OPTIONS; - -import java.io.IOException; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.util.Beta; -import org.apache.xmlbeans.XmlException; -import org.openxmlformats.schemas.presentationml.x2006.main.CTComment; -import org.openxmlformats.schemas.presentationml.x2006.main.CTCommentList; -import org.openxmlformats.schemas.presentationml.x2006.main.CmLstDocument; - -@Beta -public class XSLFComments extends POIXMLDocumentPart { - private final CTCommentList _comments; - - /** - * Create a new set of slide comments - */ - XSLFComments() { - super(); - CmLstDocument doc = CmLstDocument.Factory.newInstance(); - _comments = doc.addNewCmLst(); - } - - /** - * Construct a SpreadsheetML slide comments from a package part - * - * @param part the package part holding the comments data, - * the content type must be application/vnd.openxmlformats-officedocument.comments+xml - * - * @since POI 3.14-Beta1 - */ - XSLFComments(PackagePart part) throws IOException, XmlException { - super(part); - - CmLstDocument doc = - CmLstDocument.Factory.parse(getPackagePart().getInputStream(), DEFAULT_XML_OPTIONS); - _comments = doc.getCmLst(); - } - - public CTCommentList getCTCommentsList() { - return _comments; - } - - public int getNumberOfComments() { - return _comments.sizeOfCmArray(); - } - - public CTComment getCommentAt(int pos) { - return _comments.getCmArray(pos); - } -} diff --git a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFCommonSlideData.java b/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFCommonSlideData.java deleted file mode 100644 index 2fd336543..000000000 --- a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFCommonSlideData.java +++ /dev/null @@ -1,125 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xslf.usermodel; - -import static org.apache.poi.POIXMLTypeLoader.DEFAULT_XML_OPTIONS; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.apache.poi.POIXMLException; -import org.apache.poi.util.Beta; -import org.apache.poi.util.Removal; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.impl.values.XmlAnyTypeImpl; -import org.openxmlformats.schemas.drawingml.x2006.main.CTGraphicalObjectData; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTable; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextBody; -import org.openxmlformats.schemas.presentationml.x2006.main.CTApplicationNonVisualDrawingProps; -import org.openxmlformats.schemas.presentationml.x2006.main.CTCommonSlideData; -import org.openxmlformats.schemas.presentationml.x2006.main.CTGraphicalObjectFrame; -import org.openxmlformats.schemas.presentationml.x2006.main.CTGroupShape; -import org.openxmlformats.schemas.presentationml.x2006.main.CTShape; - -/* - * @deprecated POI 3.16 beta 1. - iterate over the shapes of a slide instead - */ -@Removal(version="3.18") -@Beta -public class XSLFCommonSlideData { - private final CTCommonSlideData data; - - public XSLFCommonSlideData(CTCommonSlideData data) { - this.data = data; - } - - public List getDrawingText() { - CTGroupShape gs = data.getSpTree(); - - List out = new ArrayList(); - - processShape(gs, out); - - for (CTGroupShape shape : gs.getGrpSpArray()) { - processShape(shape, out); - } - - for (CTGraphicalObjectFrame frame: gs.getGraphicFrameArray()) { - CTGraphicalObjectData data = frame.getGraphic().getGraphicData(); - XmlCursor c = data.newCursor(); - c.selectPath("declare namespace pic='"+CTTable.type.getName().getNamespaceURI()+"' .//pic:tbl"); - - while (c.toNextSelection()) { - XmlObject o = c.getObject(); - - if (o instanceof XmlAnyTypeImpl) { - // Pesky XmlBeans bug - see Bugzilla #49934 - try { - o = CTTable.Factory.parse(o.toString(), DEFAULT_XML_OPTIONS); - } catch (XmlException e) { - throw new POIXMLException(e); - } - } - - if (o instanceof CTTable) { - DrawingTable table = new DrawingTable((CTTable) o); - - for (DrawingTableRow row : table.getRows()) { - for (DrawingTableCell cell : row.getCells()) { - DrawingTextBody textBody = cell.getTextBody(); - out.add(textBody); - } - } - } - } - - c.dispose(); - } - - return out; - } - public List getText() { - List paragraphs = new ArrayList(); - for(DrawingTextBody textBody : getDrawingText()) { - paragraphs.addAll(Arrays.asList(textBody.getParagraphs())); - } - return paragraphs; - } - - private void processShape(CTGroupShape gs, List out) { - for (CTShape shape : gs.getSpArray()) { - CTTextBody ctTextBody = shape.getTxBody(); - if (ctTextBody==null) { - continue; - } - - DrawingTextBody textBody; - CTApplicationNonVisualDrawingProps nvpr = shape.getNvSpPr().getNvPr(); - if(nvpr.isSetPh()) { - textBody = new DrawingTextPlaceholder(ctTextBody, nvpr.getPh()); - } else { - textBody = new DrawingTextBody(ctTextBody); - } - - out.add(textBody); - } - } -} diff --git a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFConnectorShape.java b/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFConnectorShape.java deleted file mode 100644 index c7bf948a9..000000000 --- a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFConnectorShape.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xslf.usermodel; - -import org.apache.poi.POIXMLException; -import org.apache.poi.sl.usermodel.ConnectorShape; -import org.apache.poi.sl.usermodel.Placeholder; -import org.apache.poi.util.Beta; -import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPresetGeometry2D; -import org.openxmlformats.schemas.drawingml.x2006.main.CTShapeProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.STShapeType; -import org.openxmlformats.schemas.presentationml.x2006.main.CTConnector; -import org.openxmlformats.schemas.presentationml.x2006.main.CTConnectorNonVisual; - -/** - * Specifies a connection shape. - * - * @author Yegor Kozlov - */ -@Beta -public class XSLFConnectorShape extends XSLFSimpleShape - implements ConnectorShape { - - /*package*/ XSLFConnectorShape(CTConnector shape, XSLFSheet sheet) { - super(shape, sheet); - } - - /** - * @param shapeId 1-based shapeId - */ - static CTConnector prototype(int shapeId) { - CTConnector ct = CTConnector.Factory.newInstance(); - CTConnectorNonVisual nvSpPr = ct.addNewNvCxnSpPr(); - CTNonVisualDrawingProps cnv = nvSpPr.addNewCNvPr(); - cnv.setName("Connector " + shapeId); - cnv.setId(shapeId + 1); - nvSpPr.addNewCNvCxnSpPr(); - nvSpPr.addNewNvPr(); - CTShapeProperties spPr = ct.addNewSpPr(); - CTPresetGeometry2D prst = spPr.addNewPrstGeom(); - prst.setPrst(STShapeType.LINE); - prst.addNewAvLst(); - /* CTLineProperties ln = */ spPr.addNewLn(); - return ct; - } - - - /** - * YK: shadows of lines are suppressed for now. - */ - @Override - public XSLFShadow getShadow() { - return null; - } - - @Override - public void setPlaceholder(Placeholder placeholder) { - throw new POIXMLException("A connector shape can't be a placeholder."); - } -} \ No newline at end of file diff --git a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFDrawing.java b/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFDrawing.java deleted file mode 100644 index 058507c01..000000000 --- a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFDrawing.java +++ /dev/null @@ -1,113 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.usermodel; - -import java.awt.Color; -import java.awt.geom.Rectangle2D; - -import org.apache.poi.util.Beta; -import org.apache.xmlbeans.XmlObject; -import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps; -import org.openxmlformats.schemas.presentationml.x2006.main.CTConnector; -import org.openxmlformats.schemas.presentationml.x2006.main.CTGraphicalObjectFrame; -import org.openxmlformats.schemas.presentationml.x2006.main.CTGroupShape; -import org.openxmlformats.schemas.presentationml.x2006.main.CTPicture; -import org.openxmlformats.schemas.presentationml.x2006.main.CTShape; - - -/** - * @author Yegor Kozlov - */ -@Beta -public class XSLFDrawing { - private XSLFSheet _sheet; - private int _shapeId = 1; - private CTGroupShape _spTree; - - /*package*/ XSLFDrawing(XSLFSheet sheet, CTGroupShape spTree){ - _sheet = sheet; - _spTree = spTree; - XmlObject[] cNvPr = sheet.getSpTree().selectPath( - "declare namespace p='http://schemas.openxmlformats.org/presentationml/2006/main' .//*/p:cNvPr"); - for(XmlObject o : cNvPr) { - // powerpoint generates AlternateContent elements which cNvPr elements aren't recognized - // ignore them for now - if (o instanceof CTNonVisualDrawingProps) { - CTNonVisualDrawingProps p = (CTNonVisualDrawingProps)o; - _shapeId = (int)Math.max(_shapeId, p.getId()); - } - } - } - - public XSLFAutoShape createAutoShape(){ - CTShape sp = _spTree.addNewSp(); - sp.set(XSLFAutoShape.prototype(_shapeId++)); - XSLFAutoShape shape = new XSLFAutoShape(sp, _sheet); - shape.setAnchor(new Rectangle2D.Double()); - return shape; - } - - public XSLFFreeformShape createFreeform(){ - CTShape sp = _spTree.addNewSp(); - sp.set(XSLFFreeformShape.prototype(_shapeId++)); - XSLFFreeformShape shape = new XSLFFreeformShape(sp, _sheet); - shape.setAnchor(new Rectangle2D.Double()); - return shape; - } - - public XSLFTextBox createTextBox(){ - CTShape sp = _spTree.addNewSp(); - sp.set(XSLFTextBox.prototype(_shapeId++)); - XSLFTextBox shape = new XSLFTextBox(sp, _sheet); - shape.setAnchor(new Rectangle2D.Double()); - return shape; - } - - public XSLFConnectorShape createConnector(){ - CTConnector sp = _spTree.addNewCxnSp(); - sp.set(XSLFConnectorShape.prototype(_shapeId++)); - XSLFConnectorShape shape = new XSLFConnectorShape(sp, _sheet); - shape.setAnchor(new Rectangle2D.Double()); - shape.setLineColor(Color.black); - shape.setLineWidth(0.75); - return shape; - } - - public XSLFGroupShape createGroup(){ - CTGroupShape obj = _spTree.addNewGrpSp(); - obj.set(XSLFGroupShape.prototype(_shapeId++)); - XSLFGroupShape shape = new XSLFGroupShape(obj, _sheet); - shape.setAnchor(new Rectangle2D.Double()); - return shape; - } - - public XSLFPictureShape createPicture(String rel){ - CTPicture obj = _spTree.addNewPic(); - obj.set(XSLFPictureShape.prototype(_shapeId++, rel)); - XSLFPictureShape shape = new XSLFPictureShape(obj, _sheet); - shape.setAnchor(new Rectangle2D.Double()); - return shape; - } - - public XSLFTable createTable(){ - CTGraphicalObjectFrame obj = _spTree.addNewGraphicFrame(); - obj.set(XSLFTable.prototype(_shapeId++)); - XSLFTable shape = new XSLFTable(obj, _sheet); - shape.setAnchor(new Rectangle2D.Double()); - return shape; - } -} diff --git a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFFactory.java b/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFFactory.java deleted file mode 100644 index 897ebaec6..000000000 --- a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFFactory.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xslf.usermodel; - -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.POIXMLFactory; -import org.apache.poi.POIXMLRelation; - -/** - * Instantiates sub-classes of POIXMLDocumentPart depending on their relationship type - */ -public final class XSLFFactory extends POIXMLFactory { - private XSLFFactory(){ - - } - - private static final XSLFFactory inst = new XSLFFactory(); - - public static XSLFFactory getInstance(){ - return inst; - } - - /** - * @since POI 3.14-Beta1 - */ - @Override - protected POIXMLRelation getDescriptor(String relationshipType) { - return XSLFRelation.getInstance(relationshipType); - } - - /** - * @since POI 3.14-Beta1 - */ - @Override - protected POIXMLDocumentPart createDocumentPart - (Class cls, Class[] classes, Object[] values) - throws SecurityException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { - Constructor constructor = cls.getDeclaredConstructor(classes); - return constructor.newInstance(values); - } -} diff --git a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFFreeformShape.java b/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFFreeformShape.java deleted file mode 100644 index e4c02f58d..000000000 --- a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFFreeformShape.java +++ /dev/null @@ -1,209 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xslf.usermodel; - -import java.awt.geom.AffineTransform; -import java.awt.geom.Path2D; -import java.awt.geom.PathIterator; -import java.awt.geom.Rectangle2D; - -import org.apache.poi.sl.usermodel.FreeformShape; -import org.apache.poi.util.Beta; -import org.apache.poi.util.Units; -import org.apache.xmlbeans.XmlObject; -import org.openxmlformats.schemas.drawingml.x2006.main.CTAdjPoint2D; -import org.openxmlformats.schemas.drawingml.x2006.main.CTCustomGeometry2D; -import org.openxmlformats.schemas.drawingml.x2006.main.CTGeomRect; -import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPath2D; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPath2DClose; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPath2DCubicBezierTo; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPath2DLineTo; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPath2DMoveTo; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPath2DQuadBezierTo; -import org.openxmlformats.schemas.drawingml.x2006.main.CTShapeProperties; -import org.openxmlformats.schemas.presentationml.x2006.main.CTShape; -import org.openxmlformats.schemas.presentationml.x2006.main.CTShapeNonVisual; - -/** - * Represents a custom geometric shape. - * This shape will consist of a series of lines and curves described within a creation path. - */ -@Beta -public class XSLFFreeformShape extends XSLFAutoShape - implements FreeformShape { - - /*package*/ XSLFFreeformShape(CTShape shape, XSLFSheet sheet) { - super(shape, sheet); - } - - @Override - public int setPath(Path2D.Double path) { - CTPath2D ctPath = CTPath2D.Factory.newInstance(); - - Rectangle2D bounds = path.getBounds2D(); - int x0 = Units.toEMU(bounds.getX()); - int y0 = Units.toEMU(bounds.getY()); - PathIterator it = path.getPathIterator(new AffineTransform()); - int numPoints = 0; - ctPath.setH(Units.toEMU(bounds.getHeight())); - ctPath.setW(Units.toEMU(bounds.getWidth())); - while (!it.isDone()) { - double[] vals = new double[6]; - int type = it.currentSegment(vals); - switch (type) { - case PathIterator.SEG_MOVETO: - CTAdjPoint2D mv = ctPath.addNewMoveTo().addNewPt(); - mv.setX(Units.toEMU(vals[0]) - x0); - mv.setY(Units.toEMU(vals[1]) - y0); - numPoints++; - break; - case PathIterator.SEG_LINETO: - CTAdjPoint2D ln = ctPath.addNewLnTo().addNewPt(); - ln.setX(Units.toEMU(vals[0]) - x0); - ln.setY(Units.toEMU(vals[1]) - y0); - numPoints++; - break; - case PathIterator.SEG_QUADTO: - CTPath2DQuadBezierTo qbez = ctPath.addNewQuadBezTo(); - CTAdjPoint2D qp1 = qbez.addNewPt(); - qp1.setX(Units.toEMU(vals[0]) - x0); - qp1.setY(Units.toEMU(vals[1]) - y0); - CTAdjPoint2D qp2 = qbez.addNewPt(); - qp2.setX(Units.toEMU(vals[2]) - x0); - qp2.setY(Units.toEMU(vals[3]) - y0); - numPoints += 2; - break; - case PathIterator.SEG_CUBICTO: - CTPath2DCubicBezierTo bez = ctPath.addNewCubicBezTo(); - CTAdjPoint2D p1 = bez.addNewPt(); - p1.setX(Units.toEMU(vals[0]) - x0); - p1.setY(Units.toEMU(vals[1]) - y0); - CTAdjPoint2D p2 = bez.addNewPt(); - p2.setX(Units.toEMU(vals[2]) - x0); - p2.setY(Units.toEMU(vals[3]) - y0); - CTAdjPoint2D p3 = bez.addNewPt(); - p3.setX(Units.toEMU(vals[4]) - x0); - p3.setY(Units.toEMU(vals[5]) - y0); - numPoints += 3; - break; - case PathIterator.SEG_CLOSE: - numPoints++; - ctPath.addNewClose(); - break; - default: - throw new IllegalStateException("Unrecognized path segment type: " + type); - } - it.next(); - } - - XmlObject xo = getShapeProperties(); - if (!(xo instanceof CTShapeProperties)) { - return -1; - } - - ((CTShapeProperties)xo).getCustGeom().getPathLst().setPathArray(new CTPath2D[]{ctPath}); - setAnchor(bounds); - return numPoints; - } - - @Override - public Path2D.Double getPath() { - Path2D.Double path = new Path2D.Double(); - Rectangle2D bounds = getAnchor(); - - XmlObject xo = getShapeProperties(); - if (!(xo instanceof CTShapeProperties)) { - return null; - } - - CTCustomGeometry2D geom = ((CTShapeProperties)xo).getCustGeom(); - for(CTPath2D spPath : geom.getPathLst().getPathArray()){ - double scaleW = bounds.getWidth() / Units.toPoints(spPath.getW()); - double scaleH = bounds.getHeight() / Units.toPoints(spPath.getH()); - for(XmlObject ch : spPath.selectPath("*")){ - if(ch instanceof CTPath2DMoveTo){ - CTAdjPoint2D pt = ((CTPath2DMoveTo)ch).getPt(); - path.moveTo( - (float) (Units.toPoints((Long) pt.getX()) * scaleW), - (float) (Units.toPoints((Long) pt.getY()) * scaleH)); - } else if (ch instanceof CTPath2DLineTo){ - CTAdjPoint2D pt = ((CTPath2DLineTo)ch).getPt(); - path.lineTo((float)Units.toPoints((Long)pt.getX()), - (float)Units.toPoints((Long)pt.getY())); - } else if (ch instanceof CTPath2DQuadBezierTo){ - CTPath2DQuadBezierTo bez = ((CTPath2DQuadBezierTo)ch); - CTAdjPoint2D pt1 = bez.getPtArray(0); - CTAdjPoint2D pt2 = bez.getPtArray(1); - path.quadTo( - (float) (Units.toPoints((Long) pt1.getX()) * scaleW), - (float) (Units.toPoints((Long) pt1.getY()) * scaleH), - (float) (Units.toPoints((Long) pt2.getX()) * scaleW), - (float) (Units.toPoints((Long) pt2.getY()) * scaleH)); - } else if (ch instanceof CTPath2DCubicBezierTo){ - CTPath2DCubicBezierTo bez = ((CTPath2DCubicBezierTo)ch); - CTAdjPoint2D pt1 = bez.getPtArray(0); - CTAdjPoint2D pt2 = bez.getPtArray(1); - CTAdjPoint2D pt3 = bez.getPtArray(2); - path.curveTo( - (float) (Units.toPoints((Long) pt1.getX()) * scaleW), - (float) (Units.toPoints((Long) pt1.getY()) * scaleH), - (float) (Units.toPoints((Long) pt2.getX()) * scaleW), - (float) (Units.toPoints((Long) pt2.getY()) * scaleH), - (float) (Units.toPoints((Long) pt3.getX()) * scaleW), - (float) (Units.toPoints((Long) pt3.getY()) * scaleH)); - } else if (ch instanceof CTPath2DClose){ - path.closePath(); - } - } - } - - // the created path starts at (x=0, y=0). - // The returned path should fit in the bounding rectangle - AffineTransform at = new AffineTransform(); - at.translate(bounds.getX(), bounds.getY()); - return new Path2D.Double(at.createTransformedShape(path)); - } - /** - * @param shapeId 1-based shapeId - */ - static CTShape prototype(int shapeId) { - CTShape ct = CTShape.Factory.newInstance(); - CTShapeNonVisual nvSpPr = ct.addNewNvSpPr(); - CTNonVisualDrawingProps cnv = nvSpPr.addNewCNvPr(); - cnv.setName("Freeform " + shapeId); - cnv.setId(shapeId + 1); - nvSpPr.addNewCNvSpPr(); - nvSpPr.addNewNvPr(); - CTShapeProperties spPr = ct.addNewSpPr(); - CTCustomGeometry2D geom = spPr.addNewCustGeom(); - geom.addNewAvLst(); - geom.addNewGdLst(); - geom.addNewAhLst(); - geom.addNewCxnLst(); - CTGeomRect rect = geom.addNewRect(); - rect.setR("r"); - rect.setB("b"); - rect.setT("t"); - rect.setL("l"); - geom.addNewPathLst(); - return ct; - } -} diff --git a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFGraphicFrame.java b/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFGraphicFrame.java deleted file mode 100644 index 89aae95a2..000000000 --- a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFGraphicFrame.java +++ /dev/null @@ -1,219 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xslf.usermodel; - -import java.awt.geom.Rectangle2D; - -import javax.xml.namespace.QName; - -import org.apache.poi.POIXMLException; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.opc.PackageRelationship; -import org.apache.poi.sl.usermodel.GraphicalFrame; -import org.apache.poi.sl.usermodel.ShapeType; -import org.apache.poi.util.Beta; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.util.Units; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlObject; -import org.openxmlformats.schemas.drawingml.x2006.main.CTGraphicalObjectData; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPoint2D; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTransform2D; -import org.openxmlformats.schemas.presentationml.x2006.main.CTGraphicalObjectFrame; -import org.openxmlformats.schemas.presentationml.x2006.main.CTGroupShape; - -@Beta -public class XSLFGraphicFrame extends XSLFShape implements GraphicalFrame { - private static final POILogger LOG = POILogFactory.getLogger(XSLFGraphicFrame.class); - - /*package*/ XSLFGraphicFrame(CTGraphicalObjectFrame shape, XSLFSheet sheet){ - super(shape,sheet); - } - - public ShapeType getShapeType(){ - throw new UnsupportedOperationException(); - } - - @Override - public Rectangle2D getAnchor(){ - CTTransform2D xfrm = ((CTGraphicalObjectFrame)getXmlObject()).getXfrm(); - CTPoint2D off = xfrm.getOff(); - double x = Units.toPoints(off.getX()); - double y = Units.toPoints(off.getY()); - CTPositiveSize2D ext = xfrm.getExt(); - double cx = Units.toPoints(ext.getCx()); - double cy = Units.toPoints(ext.getCy()); - return new Rectangle2D.Double(x, y, cx, cy); - } - - @Override - public void setAnchor(Rectangle2D anchor){ - CTTransform2D xfrm = ((CTGraphicalObjectFrame)getXmlObject()).getXfrm(); - CTPoint2D off = xfrm.isSetOff() ? xfrm.getOff() : xfrm.addNewOff(); - long x = Units.toEMU(anchor.getX()); - long y = Units.toEMU(anchor.getY()); - off.setX(x); - off.setY(y); - CTPositiveSize2D ext = xfrm.isSetExt() ? xfrm.getExt() : xfrm - .addNewExt(); - long cx = Units.toEMU(anchor.getWidth()); - long cy = Units.toEMU(anchor.getHeight()); - ext.setCx(cx); - ext.setCy(cy); - } - - - static XSLFGraphicFrame create(CTGraphicalObjectFrame shape, XSLFSheet sheet){ - String uri = shape.getGraphic().getGraphicData().getUri(); - if(XSLFTable.TABLE_URI.equals(uri)){ - return new XSLFTable(shape, sheet); - } else { - return new XSLFGraphicFrame(shape, sheet); - } - } - - /** - * Rotate this shape. - *

    - * Positive angles are clockwise (i.e., towards the positive y axis); - * negative angles are counter-clockwise (i.e., towards the negative y axis). - *

    - * - * @param theta the rotation angle in degrees. - */ - public void setRotation(double theta){ - throw new IllegalArgumentException("Operation not supported"); - } - - /** - * Rotation angle in degrees - *

    - * Positive angles are clockwise (i.e., towards the positive y axis); - * negative angles are counter-clockwise (i.e., towards the negative y axis). - *

    - * - * @return rotation angle in degrees - */ - public double getRotation(){ - return 0; - } - - public void setFlipHorizontal(boolean flip){ - throw new IllegalArgumentException("Operation not supported"); - } - - public void setFlipVertical(boolean flip){ - throw new IllegalArgumentException("Operation not supported"); - } - - /** - * Whether the shape is horizontally flipped - * - * @return whether the shape is horizontally flipped - */ - public boolean getFlipHorizontal(){ - return false; - } - - public boolean getFlipVertical(){ - return false; - } - - @Override - void copy(XSLFShape sh){ - super.copy(sh); - - CTGraphicalObjectData data = ((CTGraphicalObjectFrame)getXmlObject()).getGraphic().getGraphicData(); - String uri = data.getUri(); - if(uri.equals("http://schemas.openxmlformats.org/drawingml/2006/diagram")){ - copyDiagram(data, (XSLFGraphicFrame)sh); - } else { - // TODO support other types of objects - - } - } - - // TODO should be moved to a sub-class - private void copyDiagram(CTGraphicalObjectData objData, XSLFGraphicFrame srcShape){ - String xpath = "declare namespace dgm='http://schemas.openxmlformats.org/drawingml/2006/diagram' $this//dgm:relIds"; - XmlObject[] obj = objData.selectPath(xpath); - if(obj != null && obj.length == 1){ - XmlCursor c = obj[0].newCursor(); - - XSLFSheet sheet = srcShape.getSheet(); - try { - String dm = c.getAttributeText(new QName("http://schemas.openxmlformats.org/officeDocument/2006/relationships", "dm")); - PackageRelationship dmRel = sheet.getPackagePart().getRelationship(dm); - PackagePart dmPart = sheet.getPackagePart().getRelatedPart(dmRel); - getSheet().importPart(dmRel, dmPart); - - String lo = c.getAttributeText(new QName("http://schemas.openxmlformats.org/officeDocument/2006/relationships", "lo")); - PackageRelationship loRel = sheet.getPackagePart().getRelationship(lo); - PackagePart loPart = sheet.getPackagePart().getRelatedPart(loRel); - getSheet().importPart(loRel, loPart); - - String qs = c.getAttributeText(new QName("http://schemas.openxmlformats.org/officeDocument/2006/relationships", "qs")); - PackageRelationship qsRel = sheet.getPackagePart().getRelationship(qs); - PackagePart qsPart = sheet.getPackagePart().getRelatedPart(qsRel); - getSheet().importPart(qsRel, qsPart); - - String cs = c.getAttributeText(new QName("http://schemas.openxmlformats.org/officeDocument/2006/relationships", "cs")); - PackageRelationship csRel = sheet.getPackagePart().getRelationship(cs); - PackagePart csPart = sheet.getPackagePart().getRelatedPart(csRel); - getSheet().importPart(csRel, csPart); - - } catch (InvalidFormatException e){ - throw new POIXMLException(e); - } - c.dispose(); - } - } - - @Override - public XSLFPictureShape getFallbackPicture() { - String xquery = - "declare namespace p='http://schemas.openxmlformats.org/presentationml/2006/main'; " - + "declare namespace mc='http://schemas.openxmlformats.org/markup-compatibility/2006' " - + ".//mc:Fallback/*/p:pic" - ; - XmlObject xo = selectProperty(XmlObject.class, xquery); - if (xo == null) { - return null; - } - - CTGroupShape gs; - try { - gs = CTGroupShape.Factory.parse(xo.newDomNode()); - } catch (XmlException e) { - LOG.log(POILogger.WARN, "Can't parse fallback picture stream of graphical frame", e); - return null; - } - - if (gs.sizeOfPicArray() == 0) { - return null; - } - - return new XSLFPictureShape(gs.getPicArray(0), getSheet()); - } -} \ No newline at end of file diff --git a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFGroupShape.java b/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFGroupShape.java deleted file mode 100644 index 7084082f4..000000000 --- a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFGroupShape.java +++ /dev/null @@ -1,406 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xslf.usermodel; - -import java.awt.geom.Rectangle2D; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.opc.PackageRelationship; -import org.apache.poi.openxml4j.opc.TargetMode; -import org.apache.poi.sl.draw.DrawPictureShape; -import org.apache.poi.sl.usermodel.GroupShape; -import org.apache.poi.sl.usermodel.PictureData; -import org.apache.poi.util.Beta; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.util.Units; -import org.apache.xmlbeans.XmlObject; -import org.openxmlformats.schemas.drawingml.x2006.main.CTGroupShapeProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTGroupTransform2D; -import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPoint2D; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D; -import org.openxmlformats.schemas.presentationml.x2006.main.CTConnector; -import org.openxmlformats.schemas.presentationml.x2006.main.CTGraphicalObjectFrame; -import org.openxmlformats.schemas.presentationml.x2006.main.CTGroupShape; -import org.openxmlformats.schemas.presentationml.x2006.main.CTGroupShapeNonVisual; -import org.openxmlformats.schemas.presentationml.x2006.main.CTPicture; -import org.openxmlformats.schemas.presentationml.x2006.main.CTShape; - -/** - * Represents a group shape that consists of many shapes grouped together. - * - * @author Yegor Kozlov - */ -@Beta -public class XSLFGroupShape extends XSLFShape -implements XSLFShapeContainer, GroupShape { - private final static POILogger _logger = POILogFactory.getLogger(XSLFGroupShape.class); - - private final List _shapes; - private final CTGroupShapeProperties _grpSpPr; - private XSLFDrawing _drawing; - - protected XSLFGroupShape(CTGroupShape shape, XSLFSheet sheet){ - super(shape,sheet); - _shapes = XSLFSheet.buildShapes(shape, sheet); - _grpSpPr = shape.getGrpSpPr(); - } - - @Override - protected CTGroupShapeProperties getGrpSpPr() { - return _grpSpPr; - } - - protected CTGroupTransform2D getSafeXfrm() { - CTGroupTransform2D xfrm = getXfrm(); - return (xfrm == null ? getGrpSpPr().addNewXfrm() : xfrm); - } - - protected CTGroupTransform2D getXfrm() { - return getGrpSpPr().getXfrm(); - } - - @Override - public Rectangle2D getAnchor(){ - CTGroupTransform2D xfrm = getXfrm(); - CTPoint2D off = xfrm.getOff(); - double x = Units.toPoints(off.getX()); - double y = Units.toPoints(off.getY()); - CTPositiveSize2D ext = xfrm.getExt(); - double cx = Units.toPoints(ext.getCx()); - double cy = Units.toPoints(ext.getCy()); - return new Rectangle2D.Double(x,y,cx,cy); - } - - @Override - public void setAnchor(Rectangle2D anchor){ - CTGroupTransform2D xfrm = getSafeXfrm(); - CTPoint2D off = xfrm.isSetOff() ? xfrm.getOff() : xfrm.addNewOff(); - long x = Units.toEMU(anchor.getX()); - long y = Units.toEMU(anchor.getY()); - off.setX(x); - off.setY(y); - CTPositiveSize2D ext = xfrm.isSetExt() ? xfrm.getExt() : xfrm.addNewExt(); - long cx = Units.toEMU(anchor.getWidth()); - long cy = Units.toEMU(anchor.getHeight()); - ext.setCx(cx); - ext.setCy(cy); - } - - /** - * - * @return the coordinates of the child extents rectangle - * used for calculations of grouping, scaling, and rotation - * behavior of shapes placed within a group. - */ - @Override - public Rectangle2D getInteriorAnchor(){ - CTGroupTransform2D xfrm = getXfrm(); - CTPoint2D off = xfrm.getChOff(); - double x = Units.toPoints(off.getX()); - double y = Units.toPoints(off.getY()); - CTPositiveSize2D ext = xfrm.getChExt(); - double cx = Units.toPoints(ext.getCx()); - double cy = Units.toPoints(ext.getCy()); - return new Rectangle2D.Double(x, y, cx, cy); - } - - /** - * - * @param anchor the coordinates of the child extents rectangle - * used for calculations of grouping, scaling, and rotation - * behavior of shapes placed within a group. - */ - @Override - public void setInteriorAnchor(Rectangle2D anchor) { - CTGroupTransform2D xfrm = getSafeXfrm(); - CTPoint2D off = xfrm.isSetChOff() ? xfrm.getChOff() : xfrm.addNewChOff(); - long x = Units.toEMU(anchor.getX()); - long y = Units.toEMU(anchor.getY()); - off.setX(x); - off.setY(y); - CTPositiveSize2D ext = xfrm.isSetChExt() ? xfrm.getChExt() : xfrm.addNewChExt(); - long cx = Units.toEMU(anchor.getWidth()); - long cy = Units.toEMU(anchor.getHeight()); - ext.setCx(cx); - ext.setCy(cy); - } - - /** - * @return child shapes contained within this group - */ - @Override - public List getShapes(){ - return _shapes; - } - - /** - * Returns an iterator over the shapes in this sheet - * - * @return an iterator over the shapes in this sheet - */ - @Override - public Iterator iterator(){ - return _shapes.iterator(); - } - - /** - * Remove the specified shape from this group - */ - @Override - public boolean removeShape(XSLFShape xShape) { - XmlObject obj = xShape.getXmlObject(); - CTGroupShape grpSp = (CTGroupShape)getXmlObject(); - if(obj instanceof CTShape){ - grpSp.getSpList().remove(obj); - } else if (obj instanceof CTGroupShape){ - grpSp.getGrpSpList().remove(obj); - } else if (obj instanceof CTConnector){ - grpSp.getCxnSpList().remove(obj); - } else if (obj instanceof CTGraphicalObjectFrame) { - grpSp.getGraphicFrameList().remove(obj); - } else if (obj instanceof CTPicture) { - XSLFPictureShape ps = (XSLFPictureShape)xShape; - XSLFSheet sh = getSheet(); - if (sh != null) { - sh.removePictureRelation(ps); - } - grpSp.getPicList().remove(obj); - } else { - throw new IllegalArgumentException("Unsupported shape: " + xShape); - } - return _shapes.remove(xShape); - } - - /** - * @param shapeId 1-based shapeId - */ - static CTGroupShape prototype(int shapeId) { - CTGroupShape ct = CTGroupShape.Factory.newInstance(); - CTGroupShapeNonVisual nvSpPr = ct.addNewNvGrpSpPr(); - CTNonVisualDrawingProps cnv = nvSpPr.addNewCNvPr(); - cnv.setName("Group " + shapeId); - cnv.setId(shapeId + 1); - - nvSpPr.addNewCNvGrpSpPr(); - nvSpPr.addNewNvPr(); - ct.addNewGrpSpPr(); - return ct; - } - - // shape factory methods - private XSLFDrawing getDrawing(){ - if(_drawing == null) { - _drawing = new XSLFDrawing(getSheet(), (CTGroupShape)getXmlObject()); - } - return _drawing; - } - - @Override - public XSLFAutoShape createAutoShape(){ - XSLFAutoShape sh = getDrawing().createAutoShape(); - _shapes.add(sh); - sh.setParent(this); - return sh; - } - - @Override - public XSLFFreeformShape createFreeform(){ - XSLFFreeformShape sh = getDrawing().createFreeform(); - _shapes.add(sh); - sh.setParent(this); - return sh; - } - - @Override - public XSLFTextBox createTextBox(){ - XSLFTextBox sh = getDrawing().createTextBox(); - _shapes.add(sh); - sh.setParent(this); - return sh; - } - - @Override - public XSLFConnectorShape createConnector(){ - XSLFConnectorShape sh = getDrawing().createConnector(); - _shapes.add(sh); - sh.setParent(this); - return sh; - } - - @Override - public XSLFGroupShape createGroup(){ - XSLFGroupShape sh = getDrawing().createGroup(); - _shapes.add(sh); - sh.setParent(this); - return sh; - } - - @Override - public XSLFPictureShape createPicture(PictureData pictureData){ - if (!(pictureData instanceof XSLFPictureData)) { - throw new IllegalArgumentException("pictureData needs to be of type XSLFPictureData"); - } - XSLFPictureData xPictureData = (XSLFPictureData)pictureData; - PackagePart pic = xPictureData.getPackagePart(); - - PackageRelationship rel = getSheet().getPackagePart().addRelationship( - pic.getPartName(), TargetMode.INTERNAL, XSLFRelation.IMAGES.getRelation()); - - XSLFPictureShape sh = getDrawing().createPicture(rel.getId()); - new DrawPictureShape(sh).resize(); - _shapes.add(sh); - sh.setParent(this); - return sh; - } - - public XSLFTable createTable(){ - XSLFTable sh = getDrawing().createTable(); - _shapes.add(sh); - sh.setParent(this); - return sh; - } - - @Override - public XSLFTable createTable(int numRows, int numCols){ - if (numRows < 1 || numCols < 1) { - throw new IllegalArgumentException("numRows and numCols must be greater than 0"); - } - XSLFTable sh = getDrawing().createTable(); - _shapes.add(sh); - sh.setParent(this); - for (int r=0; r tgtShapes = getShapes(); - List srcShapes = gr.getShapes(); - - // workaround for a call by XSLFSheet.importContent: - // if we have already the same amount of child shapes - // then assume, that we've been called by import content and only need to update the children - if (tgtShapes.size() == srcShapes.size()) { - for(int i = 0; i < tgtShapes.size(); i++){ - XSLFShape s1 = srcShapes.get(i); - XSLFShape s2 = tgtShapes.get(i); - - s2.copy(s1); - } - } else { - // otherwise recreate the shapes from scratch - clear(); - - // recursively update each shape - for(XSLFShape shape : srcShapes) { - XSLFShape newShape; - if (shape instanceof XSLFTextBox) { - newShape = createTextBox(); - } else if (shape instanceof XSLFAutoShape) { - newShape = createAutoShape(); - } else if (shape instanceof XSLFConnectorShape) { - newShape = createConnector(); - } else if (shape instanceof XSLFFreeformShape) { - newShape = createFreeform(); - } else if (shape instanceof XSLFPictureShape) { - XSLFPictureShape p = (XSLFPictureShape)shape; - XSLFPictureData pd = p.getPictureData(); - XSLFPictureData pdNew = getSheet().getSlideShow().addPicture(pd.getData(), pd.getType()); - newShape = createPicture(pdNew); - } else if (shape instanceof XSLFGroupShape) { - newShape = createGroup(); - } else if (shape instanceof XSLFTable) { - newShape = createTable(); - } else { - _logger.log(POILogger.WARN, "copying of class "+shape.getClass()+" not supported."); - continue; - } - - newShape.copy(shape); - } - } - } - - /** - * Removes all of the elements from this container (optional operation). - * The container will be empty after this call returns. - */ - @Override - public void clear() { - List shapes = new ArrayList(getShapes()); - for(XSLFShape shape : shapes){ - removeShape(shape); - } - } - - @Override - public void addShape(XSLFShape shape) { - throw new UnsupportedOperationException( - "Adding a shape from a different container is not supported -" - + " create it from scratch with XSLFGroupShape.create* methods"); - } -} \ No newline at end of file diff --git a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFHyperlink.java b/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFHyperlink.java deleted file mode 100644 index c0e029fed..000000000 --- a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFHyperlink.java +++ /dev/null @@ -1,167 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.usermodel; - -import java.net.URI; - -import org.apache.poi.common.usermodel.HyperlinkType; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.opc.PackagePartName; -import org.apache.poi.openxml4j.opc.PackageRelationship; -import org.apache.poi.openxml4j.opc.TargetMode; -import org.apache.poi.sl.usermodel.Hyperlink; -import org.apache.poi.sl.usermodel.Slide; -import org.apache.poi.util.Internal; -import org.openxmlformats.schemas.drawingml.x2006.main.CTHyperlink; - -public class XSLFHyperlink implements Hyperlink { - final XSLFSheet _sheet; - final CTHyperlink _link; - - XSLFHyperlink(CTHyperlink link, XSLFSheet sheet){ - _sheet = sheet; - _link = link; - } - - @Internal - public CTHyperlink getXmlObject(){ - return _link; - } - - @Override - public void setAddress(String address) { - linkToUrl(address); - } - - @Override - public String getAddress() { - String id = _link.getId(); - if (id == null || "".equals(id)) { - return _link.getAction(); - } - - URI targetURI = _sheet.getPackagePart().getRelationship(id).getTargetURI(); - - return targetURI.toASCIIString(); - } - - @Override - public String getLabel() { - return _link.getTooltip(); - } - - @Override - public void setLabel(String label) { - _link.setTooltip(label); - } - - /* (non-Javadoc) - * @deprecated POI 3.15. Use {@link #getTypeEnum()} instead. - * Will return a HyperlinkType enum in the future - */ - @Override - public int getType() { - return getTypeEnum().getCode(); - } - - @Override - public HyperlinkType getTypeEnum() { - String action = _link.getAction(); - if (action == null) { - action = ""; - } - if (action.equals("ppaction://hlinksldjump") || action.startsWith("ppaction://hlinkshowjump")) { - return HyperlinkType.DOCUMENT; - } - - String address = getAddress(); - if (address == null) { - address = ""; - } - if (address.startsWith("mailto:")) { - return HyperlinkType.EMAIL; - } else { - return HyperlinkType.URL; - } - } - - @Override - public void linkToEmail(String emailAddress) { - linkToExternal("mailto:"+emailAddress); - setLabel(emailAddress); - } - - @Override - public void linkToUrl(String url) { - linkToExternal(url); - setLabel(url); - } - - private void linkToExternal(String url) { - PackagePart thisPP = _sheet.getPackagePart(); - if (_link.isSetId() && !_link.getId().isEmpty()) { - thisPP.removeRelationship(_link.getId()); - } - PackageRelationship rel = thisPP.addExternalRelationship(url, XSLFRelation.HYPERLINK.getRelation()); - _link.setId(rel.getId()); - if (_link.isSetAction()) { - _link.unsetAction(); - } - } - - @Override - public void linkToSlide(Slide slide) { - PackagePart thisPP = _sheet.getPackagePart(); - PackagePartName otherPPN = ((XSLFSheet)slide).getPackagePart().getPartName(); - if (_link.isSetId() && !_link.getId().isEmpty()) { - thisPP.removeRelationship(_link.getId()); - } - PackageRelationship rel = - thisPP.addRelationship(otherPPN, TargetMode.INTERNAL, XSLFRelation.SLIDE.getRelation()); - _link.setId(rel.getId()); - _link.setAction("ppaction://hlinksldjump"); - } - - @Override - public void linkToNextSlide() { - linkToRelativeSlide("nextslide"); - } - - @Override - public void linkToPreviousSlide() { - linkToRelativeSlide("previousslide"); - } - - @Override - public void linkToFirstSlide() { - linkToRelativeSlide("firstslide"); - } - - @Override - public void linkToLastSlide() { - linkToRelativeSlide("lastslide"); - } - - private void linkToRelativeSlide(String jump) { - PackagePart thisPP = _sheet.getPackagePart(); - if (_link.isSetId() && !_link.getId().isEmpty()) { - thisPP.removeRelationship(_link.getId()); - } - _link.setId(""); - _link.setAction("ppaction://hlinkshowjump?jump="+jump); - } -} \ No newline at end of file diff --git a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFLineBreak.java b/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFLineBreak.java deleted file mode 100644 index 9c279b6aa..000000000 --- a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFLineBreak.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xslf.usermodel; - -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextLineBreak; - -class XSLFLineBreak extends XSLFTextRun { - protected XSLFLineBreak(CTTextLineBreak r, XSLFTextParagraph p) { - super(r, p); - } - - public void setText(String text){ - throw new IllegalStateException("You cannot change text of a line break, it is always '\\n'"); - } - -} diff --git a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFMetroShape.java b/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFMetroShape.java deleted file mode 100644 index fdcdbabe7..000000000 --- a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFMetroShape.java +++ /dev/null @@ -1,62 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - - -package org.apache.poi.xslf.usermodel; - -import static org.apache.poi.POIXMLTypeLoader.DEFAULT_XML_OPTIONS; - -import java.io.ByteArrayInputStream; -import java.io.IOException; - -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.opc.PackagePartName; -import org.apache.poi.openxml4j.opc.PackagingURIHelper; -import org.apache.poi.sl.usermodel.Shape; -import org.apache.poi.util.Internal; -import org.apache.xmlbeans.XmlException; -import org.openxmlformats.schemas.presentationml.x2006.main.CTGroupShape; - -/** - * Experimental class for metro blobs, i.e. an alternative escher property - * containing an ooxml representation of the shape. - * This is the helper class for HSLFMetroShape to dive into OOXML classes - */ -@Internal -public class XSLFMetroShape { - /* - * parses the metro bytes to a XSLF shape - */ - public static Shape parseShape(byte metroBytes[]) - throws InvalidFormatException, IOException, XmlException { - PackagePartName shapePN = PackagingURIHelper.createPartName("/drs/shapexml.xml"); - OPCPackage pkg = null; - try { - pkg = OPCPackage.open(new ByteArrayInputStream(metroBytes)); - PackagePart shapePart = pkg.getPart(shapePN); - CTGroupShape gs = CTGroupShape.Factory.parse(shapePart.getInputStream(), DEFAULT_XML_OPTIONS); - XSLFGroupShape xgs = new XSLFGroupShape(gs, null); - return xgs.getShapes().get(0); - } finally { - if (pkg != null) { - pkg.close(); - } - } - } -} diff --git a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFNotes.java b/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFNotes.java deleted file mode 100644 index 5472011c0..000000000 --- a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFNotes.java +++ /dev/null @@ -1,111 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.usermodel; - -import static org.apache.poi.POIXMLTypeLoader.DEFAULT_XML_OPTIONS; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.sl.usermodel.Notes; -import org.apache.poi.util.Beta; -import org.apache.xmlbeans.XmlException; -import org.openxmlformats.schemas.presentationml.x2006.main.CTCommonSlideData; -import org.openxmlformats.schemas.presentationml.x2006.main.CTNotesSlide; -import org.openxmlformats.schemas.presentationml.x2006.main.NotesDocument; - -@Beta -public final class XSLFNotes extends XSLFSheet -implements Notes { - private CTNotesSlide _notes; - - /** - * Create a new notes - */ - XSLFNotes() { - super(); - _notes = prototype(); - setCommonSlideData(_notes.getCSld()); - } - - /** - * Construct a SpreadsheetML notes from a package part - * - * @param part the package part holding the notes data, - * the content type must be application/vnd.openxmlformats-officedocument.notes+xml - * @param rel the package relationship holding this notes, - * the relationship type must be http://schemas.openxmlformats.org/officeDocument/2006/relationships/notes - * - * @since POI 3.14-Beta1 - */ - XSLFNotes(PackagePart part) throws IOException, XmlException { - super(part); - - NotesDocument doc = - NotesDocument.Factory.parse(getPackagePart().getInputStream(), DEFAULT_XML_OPTIONS); - _notes = doc.getNotes(); - setCommonSlideData(_notes.getCSld()); - } - - private static CTNotesSlide prototype(){ - CTNotesSlide ctNotes = CTNotesSlide.Factory.newInstance(); - CTCommonSlideData cSld = ctNotes.addNewCSld(); - cSld.addNewSpTree(); - - return ctNotes; - } - - @Override - public CTNotesSlide getXmlObject() { - return _notes; - } - - @Override - protected String getRootElementName(){ - return "notes"; - } - - @Override - public XSLFTheme getTheme(){ - return getMasterSheet().getTheme(); - } - - @Override - public XSLFNotesMaster getMasterSheet() { - for (POIXMLDocumentPart p : getRelations()) { - if (p instanceof XSLFNotesMaster){ - return (XSLFNotesMaster)p; - } - } - return null; - } - - @Override - public List> getTextParagraphs() { - List> tp = new ArrayList>(); - for (XSLFShape sh : super.getShapes()) { - if (sh instanceof XSLFTextShape) { - XSLFTextShape txt = (XSLFTextShape)sh; - tp.add(txt.getTextParagraphs()); - } - } - return tp; - } -} diff --git a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFNotesMaster.java b/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFNotesMaster.java deleted file mode 100644 index 658047a63..000000000 --- a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFNotesMaster.java +++ /dev/null @@ -1,122 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.usermodel; - -import static org.apache.poi.POIXMLTypeLoader.DEFAULT_XML_OPTIONS; - -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.POIXMLException; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.sl.usermodel.MasterSheet; -import org.apache.poi.util.Beta; -import org.apache.xmlbeans.XmlException; -import org.openxmlformats.schemas.drawingml.x2006.main.CTColorMapping; -import org.openxmlformats.schemas.presentationml.x2006.main.CTNotesMaster; -import org.openxmlformats.schemas.presentationml.x2006.main.NotesMasterDocument; - -/** -* Notes master object associated with this layout. -*

    -* Within a notes master slide are contained all elements -* that describe the objects and their corresponding formatting -* for within a presentation slide. -*

    -*

    -* Within a nodes master slide are two main elements. -* The cSld element specifies the common slide elements such as shapes and -* their attached text bodies. Then the notesStyles element specifies the -* formatting for the text within each of these shapes. -*

    - * - * @author Yegor Kozlov -*/ -@Beta - public class XSLFNotesMaster extends XSLFSheet - implements MasterSheet { - private CTNotesMaster _slide; - private XSLFTheme _theme; - - XSLFNotesMaster() { - super(); - _slide = prototype(); - } - - /** - * @since POI 3.14-Beta1 - */ - protected XSLFNotesMaster(PackagePart part) throws IOException, XmlException { - super(part); - NotesMasterDocument doc = - NotesMasterDocument.Factory.parse(getPackagePart().getInputStream(), DEFAULT_XML_OPTIONS); - _slide = doc.getNotesMaster(); - setCommonSlideData(_slide.getCSld()); - } - - private static CTNotesMaster prototype() { - InputStream is = XSLFNotesMaster.class.getResourceAsStream("notesMaster.xml"); - if (is == null) { - throw new POIXMLException("Missing resource 'notesMaster.xml'"); - } - - try { - try { - NotesMasterDocument doc = NotesMasterDocument.Factory.parse(is, DEFAULT_XML_OPTIONS); - CTNotesMaster slide = doc.getNotesMaster(); - return slide; - } finally { - is.close(); - } - } catch (Exception e) { - throw new POIXMLException("Can't initialize NotesMaster", e); - } - } - - @Override - public CTNotesMaster getXmlObject() { - return _slide; - } - - @Override - protected String getRootElementName(){ - return "notesMaster"; - } - - @Override - public MasterSheet getMasterSheet() { - return null; - } - - @Override - public XSLFTheme getTheme() { - if (_theme == null) { - for (POIXMLDocumentPart p : getRelations()) { - if (p instanceof XSLFTheme) { - _theme = (XSLFTheme) p; - CTColorMapping cmap = _slide.getClrMap(); - if (cmap != null) { - _theme.initColorMap(cmap); - } - break; - } - } - } - return _theme; - } -} \ No newline at end of file diff --git a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFPictureData.java b/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFPictureData.java deleted file mode 100644 index 95abdebf2..000000000 --- a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFPictureData.java +++ /dev/null @@ -1,257 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xslf.usermodel; - -import java.awt.Dimension; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.POIXMLException; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.sl.image.ImageHeaderBitmap; -import org.apache.poi.sl.image.ImageHeaderEMF; -import org.apache.poi.sl.image.ImageHeaderPICT; -import org.apache.poi.sl.image.ImageHeaderWMF; -import org.apache.poi.sl.usermodel.PictureData; -import org.apache.poi.util.Beta; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.LittleEndianConsts; -import org.apache.poi.util.Units; - -/** - * Instantiates sub-classes of POIXMLDocumentPart depending on their relationship type - */ -@Beta -public final class XSLFPictureData extends POIXMLDocumentPart implements PictureData { - private Long checksum = null; - - // original image dimensions (for formats supported by BufferedImage) - private Dimension origSize = null; - private int index = -1; - - /** - * Create a new XSLFGraphicData node - */ - protected XSLFPictureData() { - super(); - } - - /** - * Construct XSLFPictureData from a package part - * - * @param part the package part holding the drawing data - * - * @since POI 3.14-Beta1 - */ - public XSLFPictureData(PackagePart part) { - super(part); - } - - /** - * An InputStream to read the picture data directly - * from the underlying package part - * - * @return InputStream - */ - public InputStream getInputStream() throws IOException { - return getPackagePart().getInputStream(); - } - - /** - * Gets the picture data as a byte array. - * - * You can grab the picture data directly from the underlying package part with the {@link #getInputStream()} method - * - * @return the Picture data. - */ - public byte[] getData() { - try { - return IOUtils.toByteArray(getInputStream()); - } catch (IOException e) { - throw new POIXMLException(e); - } - } - - /** - * Returns the file name of the image, eg image7.jpg . The original filename - * isn't always available, but if it can be found it's likely to be in the - * CTDrawing - */ - public String getFileName() { - String name = getPackagePart().getPartName().getName(); - return name.substring(name.lastIndexOf('/') + 1); - } - - /** - * Suggests a file extension for this image. - * - * @return the file extension. - */ - public String suggestFileExtension() { - return getPackagePart().getPartName().getExtension(); - } - - @Override - public byte[] getChecksum() { - cacheProperties(); - byte cs[] = new byte[LittleEndianConsts.LONG_SIZE]; - LittleEndian.putLong(cs,0,checksum); - return cs; - } - - @Override - public Dimension getImageDimension() { - cacheProperties(); - return origSize; - } - - @Override - public Dimension getImageDimensionInPixels() { - Dimension dim = getImageDimension(); - return new Dimension( - Units.pointsToPixel(dim.getWidth()), - Units.pointsToPixel(dim.getHeight()) - ); - } - - /** - * Determine and cache image properties - */ - protected void cacheProperties() { - if (origSize == null || checksum == null) { - byte data[] = getData(); - checksum = IOUtils.calculateChecksum(data); - - PictureType pt = getType(); - if (pt == null) { - origSize = new Dimension(1,1); - return; - } - - switch (pt) { - case EMF: - origSize = new ImageHeaderEMF(data, 0).getSize(); - break; - case WMF: - // wmf files in pptx usually have their placeable header - // stripped away, so this returns only the dummy size - origSize = new ImageHeaderWMF(data, 0).getSize(); - break; - case PICT: - origSize = new ImageHeaderPICT(data, 0).getSize(); - break; - default: - origSize = new ImageHeaderBitmap(data, 0).getSize(); - break; - } - } - } - - /** - * *PictureData objects store the actual content in the part directly without keeping a - * copy like all others therefore we need to handle them differently. - */ - @Override - protected void prepareForCommit() { - // do not clear the part here - } - - @Override - public String getContentType() { - return getPackagePart().getContentType(); - } - - public void setData(byte[] data) throws IOException { - OutputStream os = getPackagePart().getOutputStream(); - os.write(data); - os.close(); - // recalculate now since we already have the data bytes available anyhow - checksum = IOUtils.calculateChecksum(data); - - origSize = null; // need to recalculate image size - } - - @Override - public PictureType getType() { - String ct = getContentType(); - if (XSLFRelation.IMAGE_EMF.getContentType().equals(ct)) { - return PictureType.EMF; - } else if (XSLFRelation.IMAGE_WMF.getContentType().equals(ct)) { - return PictureType.WMF; - } else if (XSLFRelation.IMAGE_PICT.getContentType().equals(ct)) { - return PictureType.PICT; - } else if (XSLFRelation.IMAGE_JPEG.getContentType().equals(ct)) { - return PictureType.JPEG; - } else if (XSLFRelation.IMAGE_PNG.getContentType().equals(ct)) { - return PictureType.PNG; - } else if (XSLFRelation.IMAGE_DIB.getContentType().equals(ct)) { - return PictureType.DIB; - } else if (XSLFRelation.IMAGE_GIF.getContentType().equals(ct)) { - return PictureType.GIF; - } else if (XSLFRelation.IMAGE_EPS.getContentType().equals(ct)) { - return PictureType.EPS; - } else if (XSLFRelation.IMAGE_BMP.getContentType().equals(ct)) { - return PictureType.BMP; - } else if (XSLFRelation.IMAGE_WPG.getContentType().equals(ct)) { - return PictureType.WPG; - } else if (XSLFRelation.IMAGE_WDP.getContentType().equals(ct)) { - return PictureType.WDP; - } else if (XSLFRelation.IMAGE_TIFF.getContentType().equals(ct)) { - return PictureType.TIFF; - } else { - return null; - } - } - - /* package */ static XSLFRelation getRelationForType(PictureType pt) { - switch (pt) { - case EMF: return XSLFRelation.IMAGE_EMF; - case WMF: return XSLFRelation.IMAGE_WMF; - case PICT: return XSLFRelation.IMAGE_PICT; - case JPEG: return XSLFRelation.IMAGE_JPEG; - case PNG: return XSLFRelation.IMAGE_PNG; - case DIB: return XSLFRelation.IMAGE_DIB; - case GIF: return XSLFRelation.IMAGE_GIF; - case EPS: return XSLFRelation.IMAGE_EPS; - case BMP: return XSLFRelation.IMAGE_BMP; - case WPG: return XSLFRelation.IMAGE_WPG; - case WDP: return XSLFRelation.IMAGE_WDP; - case TIFF: return XSLFRelation.IMAGE_TIFF; - default: return null; - } - } - - /** - * @return the 0-based index of this pictures within the picture parts - */ - public int getIndex() { - return index; - } - - /** - * @param index sets the 0-based index of this pictures within the picture parts - */ - public void setIndex(int index) { - this.index = index; - } -} \ No newline at end of file diff --git a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFPictureShape.java b/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFPictureShape.java deleted file mode 100644 index da3cf45c8..000000000 --- a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFPictureShape.java +++ /dev/null @@ -1,232 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xslf.usermodel; - -import java.awt.Insets; -import java.net.URI; - -import javax.xml.namespace.QName; - -import org.apache.poi.POIXMLException; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.opc.PackageRelationship; -import org.apache.poi.sl.usermodel.PictureShape; -import org.apache.poi.sl.usermodel.Placeholder; -import org.apache.poi.util.Beta; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlObject; -import org.openxmlformats.schemas.drawingml.x2006.main.CTBlip; -import org.openxmlformats.schemas.drawingml.x2006.main.CTBlipFillProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps; -import org.openxmlformats.schemas.drawingml.x2006.main.CTOfficeArtExtension; -import org.openxmlformats.schemas.drawingml.x2006.main.CTOfficeArtExtensionList; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPresetGeometry2D; -import org.openxmlformats.schemas.drawingml.x2006.main.CTRelativeRect; -import org.openxmlformats.schemas.drawingml.x2006.main.CTShapeProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.STShapeType; -import org.openxmlformats.schemas.presentationml.x2006.main.CTApplicationNonVisualDrawingProps; -import org.openxmlformats.schemas.presentationml.x2006.main.CTPicture; -import org.openxmlformats.schemas.presentationml.x2006.main.CTPictureNonVisual; - -/** - * Represents a picture shape - */ -@Beta -public class XSLFPictureShape extends XSLFSimpleShape - implements PictureShape { - private XSLFPictureData _data; - - /*package*/ XSLFPictureShape(CTPicture shape, XSLFSheet sheet) { - super(shape, sheet); - } - - - /** - * @param shapeId 1-based shapeId - * @param rel relationship to the picture data in the ooxml package - */ - static CTPicture prototype(int shapeId, String rel) { - CTPicture ct = CTPicture.Factory.newInstance(); - CTPictureNonVisual nvSpPr = ct.addNewNvPicPr(); - CTNonVisualDrawingProps cnv = nvSpPr.addNewCNvPr(); - cnv.setName("Picture " + shapeId); - cnv.setId(shapeId + 1); - nvSpPr.addNewCNvPicPr().addNewPicLocks().setNoChangeAspect(true); - nvSpPr.addNewNvPr(); - - CTBlipFillProperties blipFill = ct.addNewBlipFill(); - CTBlip blip = blipFill.addNewBlip(); - blip.setEmbed(rel); - blipFill.addNewStretch().addNewFillRect(); - - CTShapeProperties spPr = ct.addNewSpPr(); - CTPresetGeometry2D prst = spPr.addNewPrstGeom(); - prst.setPrst(STShapeType.RECT); - prst.addNewAvLst(); - return ct; - } - - - /** - * Is this an internal picture (image data included within - * the PowerPoint file), or an external linked picture - * (image lives outside)? - */ - public boolean isExternalLinkedPicture() { - if (getBlipId() == null && getBlipLink() != null) { - return true; - } - return false; - } - - /** - * Return the data on the (internal) picture. - * For an external linked picture, will return null - */ - public XSLFPictureData getPictureData() { - if(_data == null){ - String blipId = getBlipId(); - if (blipId == null) return null; - - PackagePart p = getSheet().getPackagePart(); - PackageRelationship rel = p.getRelationship(blipId); - if (rel != null) { - try { - PackagePart imgPart = p.getRelatedPart(rel); - _data = new XSLFPictureData(imgPart); - } - catch (Exception e) { - throw new POIXMLException(e); - } - } - } - return _data; - } - - @Override - public void setPlaceholder(Placeholder placeholder) { - super.setPlaceholder(placeholder); - } - - - /** - * For an external linked picture, return the last-seen - * path to the picture. - * For an internal picture, returns null. - */ - public URI getPictureLink() { - if (getBlipId() != null) { - // Internal picture, nothing to return - return null; - } - - String rId = getBlipLink(); - if (rId == null) { - // No link recorded, nothing we can do - return null; - } - - PackagePart p = getSheet().getPackagePart(); - PackageRelationship rel = p.getRelationship(rId); - if (rel != null) { - return rel.getTargetURI(); - } - return null; - } - - protected CTBlipFillProperties getBlipFill() { - CTPicture ct = (CTPicture)getXmlObject(); - CTBlipFillProperties bfp = ct.getBlipFill(); - if (bfp != null) { - return bfp; - } - - String xquery = - "declare namespace p='http://schemas.openxmlformats.org/presentationml/2006/main'; " - + "declare namespace mc='http://schemas.openxmlformats.org/markup-compatibility/2006' " - + ".//mc:Fallback/p:blipFill" - ; - XmlObject xo = selectProperty(XmlObject.class, xquery); - try { - xo = CTPicture.Factory.parse(xo.getDomNode()); - } catch (XmlException xe) { - return null; - } - return ((CTPicture)xo).getBlipFill(); - } - - protected CTBlip getBlip(){ - return getBlipFill().getBlip(); - } - - protected String getBlipLink(){ - String link = getBlip().getLink(); - if (link.isEmpty()) return null; - return link; - } - - protected String getBlipId(){ - String id = getBlip().getEmbed(); - if (id.isEmpty()) return null; - return id; - } - - @Override - public Insets getClipping(){ - CTRelativeRect r = getBlipFill().getSrcRect(); - return (r == null) ? null : new Insets(r.getT(), r.getL(), r.getB(), r.getR()); - } - - @Override - void copy(XSLFShape sh){ - super.copy(sh); - - XSLFPictureShape p = (XSLFPictureShape)sh; - String blipId = p.getBlipId(); - String relId = getSheet().importBlip(blipId, p.getSheet().getPackagePart()); - - CTPicture ct = (CTPicture)getXmlObject(); - CTBlip blip = getBlipFill().getBlip(); - blip.setEmbed(relId); - - CTApplicationNonVisualDrawingProps nvPr = ct.getNvPicPr().getNvPr(); - if(nvPr.isSetCustDataLst()) { - // discard any custom tags associated with the picture being copied - nvPr.unsetCustDataLst(); - } - if(blip.isSetExtLst()) { - - CTOfficeArtExtensionList extLst = blip.getExtLst(); - for(CTOfficeArtExtension ext : extLst.getExtArray()){ - String xpath = "declare namespace a14='http://schemas.microsoft.com/office/drawing/2010/main' $this//a14:imgProps/a14:imgLayer"; - XmlObject[] obj = ext.selectPath(xpath); - if(obj != null && obj.length == 1){ - XmlCursor c = obj[0].newCursor(); - String id = c.getAttributeText(new QName("http://schemas.openxmlformats.org/officeDocument/2006/relationships", "embed"));//selectPath("declare namespace r='http://schemas.openxmlformats.org/officeDocument/2006/relationships' $this//[@embed]"); - String newId = getSheet().importBlip(id, p.getSheet().getPackagePart()); - c.setAttributeText(new QName("http://schemas.openxmlformats.org/officeDocument/2006/relationships", "embed"), newId); - c.dispose(); - } - } - } - - } -} \ No newline at end of file diff --git a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFPropertiesDelegate.java b/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFPropertiesDelegate.java deleted file mode 100644 index a15d90cc4..000000000 --- a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFPropertiesDelegate.java +++ /dev/null @@ -1,1862 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xslf.usermodel; - -import org.apache.poi.util.Internal; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlObject; -import org.openxmlformats.schemas.drawingml.x2006.main.CTBlipFillProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTCustomGeometry2D; -import org.openxmlformats.schemas.drawingml.x2006.main.CTEffectContainer; -import org.openxmlformats.schemas.drawingml.x2006.main.CTEffectList; -import org.openxmlformats.schemas.drawingml.x2006.main.CTFillProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTGradientFillProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTGroupFillProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTLineProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTNoFillProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPatternFillProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPresetGeometry2D; -import org.openxmlformats.schemas.drawingml.x2006.main.CTShapeProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTSolidColorFillProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTStyleMatrixReference; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTableCellProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextCharacterProperties; -import org.openxmlformats.schemas.presentationml.x2006.main.CTBackgroundProperties; - -/** - * Internal helper class to unify property access. - * - * This class is experimental and not (yet) supposed for public usage. - * Maybe the xml schemas might be enhanced with interfaces to make this class superfluous - * - * @since POI 3.15-beta2 - */ -@Internal -/* package */ class XSLFPropertiesDelegate { - private static final POILogger LOG = POILogFactory.getLogger(XSLFPropertiesDelegate.class); - - - public static XSLFFillProperties getFillDelegate(XmlObject props) { - return getDelegate(XSLFFillProperties.class, props); - } - - public static XSLFGeometryProperties getGeometryDelegate(XmlObject props) { - return getDelegate(XSLFGeometryProperties.class, props); - } - - public static XSLFEffectProperties getEffectDelegate(XmlObject props) { - return getDelegate(XSLFEffectProperties.class, props); - } - - public interface XSLFFillProperties { - /** - * Gets the "noFill" element - */ - CTNoFillProperties getNoFill(); - - /** - * True if has "noFill" element - */ - boolean isSetNoFill(); - - /** - * Sets the "noFill" element - */ - void setNoFill(CTNoFillProperties noFill); - - /** - * Appends and returns a new empty "noFill" element - */ - CTNoFillProperties addNewNoFill(); - - /** - * Unsets the "noFill" element - */ - void unsetNoFill(); - - /** - * Gets the "solidFill" element - */ - CTSolidColorFillProperties getSolidFill(); - - /** - * True if has "solidFill" element - */ - boolean isSetSolidFill(); - - /** - * Sets the "solidFill" element - */ - void setSolidFill(CTSolidColorFillProperties solidFill); - - /** - * Appends and returns a new empty "solidFill" element - */ - CTSolidColorFillProperties addNewSolidFill(); - - /** - * Unsets the "solidFill" element - */ - void unsetSolidFill(); - - /** - * Gets the "gradFill" element - */ - CTGradientFillProperties getGradFill(); - - /** - * True if has "gradFill" element - */ - boolean isSetGradFill(); - - /** - * Sets the "gradFill" element - */ - void setGradFill(CTGradientFillProperties gradFill); - - /** - * Appends and returns a new empty "gradFill" element - */ - CTGradientFillProperties addNewGradFill(); - - /** - * Unsets the "gradFill" element - */ - void unsetGradFill(); - - /** - * Gets the "blipFill" element - */ - CTBlipFillProperties getBlipFill(); - - /** - * True if has "blipFill" element - */ - boolean isSetBlipFill(); - - /** - * Sets the "blipFill" element - */ - void setBlipFill(CTBlipFillProperties blipFill); - - /** - * Appends and returns a new empty "blipFill" element - */ - CTBlipFillProperties addNewBlipFill(); - - /** - * Unsets the "blipFill" element - */ - void unsetBlipFill(); - - /** - * Gets the "pattFill" element - */ - CTPatternFillProperties getPattFill(); - - /** - * True if has "pattFill" element - */ - boolean isSetPattFill(); - - /** - * Sets the "pattFill" element - */ - void setPattFill(CTPatternFillProperties pattFill); - - /** - * Appends and returns a new empty "pattFill" element - */ - CTPatternFillProperties addNewPattFill(); - - /** - * Unsets the "pattFill" element - */ - void unsetPattFill(); - - /** - * Gets the "grpFill" element - */ - CTGroupFillProperties getGrpFill(); - - /** - * True if has "grpFill" element - */ - boolean isSetGrpFill(); - - /** - * Sets the "grpFill" element - */ - void setGrpFill(CTGroupFillProperties grpFill); - - /** - * Appends and returns a new empty "grpFill" element - */ - CTGroupFillProperties addNewGrpFill(); - - /** - * Unsets the "grpFill" element - */ - void unsetGrpFill(); - - /** - * Helper method to unify other properties with style matrix references - * @return true, if this is a matrix style delegate - */ - boolean isSetMatrixStyle(); - - /** - * Helper method to unify other properties with style matrix references - */ - CTStyleMatrixReference getMatrixStyle(); - - /** - * Helper method to choose between fill and line style - * - * @return true, if this applies to a line - */ - boolean isLineStyle(); - } - - public interface XSLFGeometryProperties { - /** - * Gets the "custGeom" element - */ - CTCustomGeometry2D getCustGeom(); - - /** - * True if has "custGeom" element - */ - boolean isSetCustGeom(); - - /** - * Sets the "custGeom" element - */ - void setCustGeom(CTCustomGeometry2D custGeom); - - /** - * Appends and returns a new empty "custGeom" element - */ - CTCustomGeometry2D addNewCustGeom(); - - /** - * Unsets the "custGeom" element - */ - void unsetCustGeom(); - - /** - * Gets the "prstGeom" element - */ - CTPresetGeometry2D getPrstGeom(); - - /** - * True if has "prstGeom" element - */ - boolean isSetPrstGeom(); - - /** - * Sets the "prstGeom" element - */ - void setPrstGeom(CTPresetGeometry2D prstGeom); - - /** - * Appends and returns a new empty "prstGeom" element - */ - CTPresetGeometry2D addNewPrstGeom(); - - /** - * Unsets the "prstGeom" element - */ - void unsetPrstGeom(); - } - - public interface XSLFEffectProperties { - /** - * Gets the "effectLst" element - */ - CTEffectList getEffectLst(); - - /** - * True if has "effectLst" element - */ - boolean isSetEffectLst(); - - /** - * Sets the "effectLst" element - */ - void setEffectLst(CTEffectList effectLst); - - /** - * Appends and returns a new empty "effectLst" element - */ - CTEffectList addNewEffectLst(); - - /** - * Unsets the "effectLst" element - */ - void unsetEffectLst(); - - /** - * Gets the "effectDag" element - */ - CTEffectContainer getEffectDag(); - - /** - * True if has "effectDag" element - */ - boolean isSetEffectDag(); - - /** - * Sets the "effectDag" element - */ - void setEffectDag(CTEffectContainer effectDag); - - /** - * Appends and returns a new empty "effectDag" element - */ - CTEffectContainer addNewEffectDag(); - - /** - * Unsets the "effectDag" element - */ - void unsetEffectDag(); - } - - private static class ShapeDelegate implements XSLFFillProperties, XSLFGeometryProperties, XSLFEffectProperties { - final CTShapeProperties props; - - ShapeDelegate(CTShapeProperties props) { - this.props = props; - } - - @Override - public CTNoFillProperties getNoFill() { - return props.getNoFill(); - } - - @Override - public boolean isSetNoFill() { - return props.isSetNoFill(); - } - - @Override - public void setNoFill(CTNoFillProperties noFill) { - props.setNoFill(noFill); - } - - @Override - public CTNoFillProperties addNewNoFill() { - return props.addNewNoFill(); - } - - @Override - public void unsetNoFill() { - props.unsetNoFill(); - } - - @Override - public CTSolidColorFillProperties getSolidFill() { - return props.getSolidFill(); - } - - @Override - public boolean isSetSolidFill() { - return props.isSetSolidFill(); - } - - @Override - public void setSolidFill(CTSolidColorFillProperties solidFill) { - props.setSolidFill(solidFill); - } - - @Override - public CTSolidColorFillProperties addNewSolidFill() { - return props.addNewSolidFill(); - } - - @Override - public void unsetSolidFill() { - props.unsetSolidFill(); - } - - @Override - public CTGradientFillProperties getGradFill() { - return props.getGradFill(); - } - - @Override - public boolean isSetGradFill() { - return props.isSetGradFill(); - } - - @Override - public void setGradFill(CTGradientFillProperties gradFill) { - props.setGradFill(gradFill); - } - - @Override - public CTGradientFillProperties addNewGradFill() { - return props.addNewGradFill(); - } - - @Override - public void unsetGradFill() { - props.unsetGradFill(); - } - - @Override - public CTBlipFillProperties getBlipFill() { - return props.getBlipFill(); - } - - @Override - public boolean isSetBlipFill() { - return props.isSetBlipFill(); - } - - @Override - public void setBlipFill(CTBlipFillProperties blipFill) { - props.setBlipFill(blipFill); - } - - @Override - public CTBlipFillProperties addNewBlipFill() { - return props.addNewBlipFill(); - } - - @Override - public void unsetBlipFill() { - props.unsetBlipFill(); - } - - @Override - public CTPatternFillProperties getPattFill() { - return props.getPattFill(); - } - - @Override - public boolean isSetPattFill() { - return props.isSetPattFill(); - } - - @Override - public void setPattFill(CTPatternFillProperties pattFill) { - props.setPattFill(pattFill); - } - - @Override - public CTPatternFillProperties addNewPattFill() { - return props.addNewPattFill(); - } - - @Override - public void unsetPattFill() { - props.unsetPattFill(); - } - - @Override - public CTGroupFillProperties getGrpFill() { - return props.getGrpFill(); - } - - @Override - public boolean isSetGrpFill() { - return props.isSetGrpFill(); - } - - @Override - public void setGrpFill(CTGroupFillProperties grpFill) { - props.setGrpFill(grpFill); - } - - @Override - public CTGroupFillProperties addNewGrpFill() { - return props.addNewGrpFill(); - } - - @Override - public void unsetGrpFill() { - props.unsetGrpFill(); - } - - @Override - public CTCustomGeometry2D getCustGeom() { - return props.getCustGeom(); - } - - @Override - public boolean isSetCustGeom() { - return props.isSetCustGeom(); - } - - @Override - public void setCustGeom(CTCustomGeometry2D custGeom) { - props.setCustGeom(custGeom); - } - - @Override - public CTCustomGeometry2D addNewCustGeom() { - return props.addNewCustGeom(); - } - - @Override - public void unsetCustGeom() { - props.unsetCustGeom(); - } - - @Override - public CTPresetGeometry2D getPrstGeom() { - return props.getPrstGeom(); - } - - @Override - public boolean isSetPrstGeom() { - return props.isSetPrstGeom(); - } - - @Override - public void setPrstGeom(CTPresetGeometry2D prstGeom) { - props.setPrstGeom(prstGeom); - } - - @Override - public CTPresetGeometry2D addNewPrstGeom() { - return props.addNewPrstGeom(); - } - - @Override - public void unsetPrstGeom() { - props.unsetPrstGeom(); - } - - @Override - public CTEffectList getEffectLst() { - return props.getEffectLst(); - } - - @Override - public boolean isSetEffectLst() { - return props.isSetEffectLst(); - } - - @Override - public void setEffectLst(CTEffectList effectLst) { - props.setEffectLst(effectLst); - } - - @Override - public CTEffectList addNewEffectLst() { - return props.addNewEffectLst(); - } - - @Override - public void unsetEffectLst() { - props.unsetEffectLst(); - } - - @Override - public CTEffectContainer getEffectDag() { - return props.getEffectDag(); - } - - @Override - public boolean isSetEffectDag() { - return props.isSetEffectDag(); - } - - @Override - public void setEffectDag(CTEffectContainer effectDag) { - props.setEffectDag(effectDag); - } - - @Override - public CTEffectContainer addNewEffectDag() { - return props.addNewEffectDag(); - } - - @Override - public void unsetEffectDag() { - props.unsetEffectDag(); - } - - @Override - public boolean isSetMatrixStyle() { - return false; - } - - @Override - public CTStyleMatrixReference getMatrixStyle() { - return null; - } - - @Override - public boolean isLineStyle() { - return false; - } - } - - private static class BackgroundDelegate implements XSLFFillProperties, XSLFEffectProperties { - final CTBackgroundProperties props; - - BackgroundDelegate(CTBackgroundProperties props) { - this.props = props; - } - - @Override - public CTNoFillProperties getNoFill() { - return props.getNoFill(); - } - - @Override - public boolean isSetNoFill() { - return props.isSetNoFill(); - } - - @Override - public void setNoFill(CTNoFillProperties noFill) { - props.setNoFill(noFill); - } - - @Override - public CTNoFillProperties addNewNoFill() { - return props.addNewNoFill(); - } - - @Override - public void unsetNoFill() { - props.unsetNoFill(); - } - - @Override - public CTSolidColorFillProperties getSolidFill() { - return props.getSolidFill(); - } - - @Override - public boolean isSetSolidFill() { - return props.isSetSolidFill(); - } - - @Override - public void setSolidFill(CTSolidColorFillProperties solidFill) { - props.setSolidFill(solidFill); - } - - @Override - public CTSolidColorFillProperties addNewSolidFill() { - return props.addNewSolidFill(); - } - - @Override - public void unsetSolidFill() { - props.unsetSolidFill(); - } - - @Override - public CTGradientFillProperties getGradFill() { - return props.getGradFill(); - } - - @Override - public boolean isSetGradFill() { - return props.isSetGradFill(); - } - - @Override - public void setGradFill(CTGradientFillProperties gradFill) { - props.setGradFill(gradFill); - } - - @Override - public CTGradientFillProperties addNewGradFill() { - return props.addNewGradFill(); - } - - @Override - public void unsetGradFill() { - props.unsetGradFill(); - } - - @Override - public CTBlipFillProperties getBlipFill() { - return props.getBlipFill(); - } - - @Override - public boolean isSetBlipFill() { - return props.isSetBlipFill(); - } - - @Override - public void setBlipFill(CTBlipFillProperties blipFill) { - props.setBlipFill(blipFill); - } - - @Override - public CTBlipFillProperties addNewBlipFill() { - return props.addNewBlipFill(); - } - - @Override - public void unsetBlipFill() { - props.unsetBlipFill(); - } - - @Override - public CTPatternFillProperties getPattFill() { - return props.getPattFill(); - } - - @Override - public boolean isSetPattFill() { - return props.isSetPattFill(); - } - - @Override - public void setPattFill(CTPatternFillProperties pattFill) { - props.setPattFill(pattFill); - } - - @Override - public CTPatternFillProperties addNewPattFill() { - return props.addNewPattFill(); - } - - @Override - public void unsetPattFill() { - props.unsetPattFill(); - } - - @Override - public CTGroupFillProperties getGrpFill() { - return props.getGrpFill(); - } - - @Override - public boolean isSetGrpFill() { - return props.isSetGrpFill(); - } - - @Override - public void setGrpFill(CTGroupFillProperties grpFill) { - props.setGrpFill(grpFill); - } - - @Override - public CTGroupFillProperties addNewGrpFill() { - return props.addNewGrpFill(); - } - - @Override - public void unsetGrpFill() { - props.unsetGrpFill(); - } - - @Override - public CTEffectList getEffectLst() { - return props.getEffectLst(); - } - - @Override - public boolean isSetEffectLst() { - return props.isSetEffectLst(); - } - - @Override - public void setEffectLst(CTEffectList effectLst) { - props.setEffectLst(effectLst); - } - - @Override - public CTEffectList addNewEffectLst() { - return props.addNewEffectLst(); - } - - @Override - public void unsetEffectLst() { - props.unsetEffectLst(); - } - - @Override - public CTEffectContainer getEffectDag() { - return props.getEffectDag(); - } - - @Override - public boolean isSetEffectDag() { - return props.isSetEffectDag(); - } - - @Override - public void setEffectDag(CTEffectContainer effectDag) { - props.setEffectDag(effectDag); - } - - @Override - public CTEffectContainer addNewEffectDag() { - return props.addNewEffectDag(); - } - - @Override - public void unsetEffectDag() { - props.unsetEffectDag(); - } - - @Override - public boolean isSetMatrixStyle() { - return false; - } - - @Override - public CTStyleMatrixReference getMatrixStyle() { - return null; - } - - @Override - public boolean isLineStyle() { - return false; - } - } - - private static class TableCellDelegate implements XSLFFillProperties { - final CTTableCellProperties props; - - TableCellDelegate(CTTableCellProperties props) { - this.props = props; - } - - @Override - public CTNoFillProperties getNoFill() { - return props.getNoFill(); - } - - @Override - public boolean isSetNoFill() { - return props.isSetNoFill(); - } - - @Override - public void setNoFill(CTNoFillProperties noFill) { - props.setNoFill(noFill); - } - - @Override - public CTNoFillProperties addNewNoFill() { - return props.addNewNoFill(); - } - - @Override - public void unsetNoFill() { - props.unsetNoFill(); - } - - @Override - public CTSolidColorFillProperties getSolidFill() { - return props.getSolidFill(); - } - - @Override - public boolean isSetSolidFill() { - return props.isSetSolidFill(); - } - - @Override - public void setSolidFill(CTSolidColorFillProperties solidFill) { - props.setSolidFill(solidFill); - } - - @Override - public CTSolidColorFillProperties addNewSolidFill() { - return props.addNewSolidFill(); - } - - @Override - public void unsetSolidFill() { - props.unsetSolidFill(); - } - - @Override - public CTGradientFillProperties getGradFill() { - return props.getGradFill(); - } - - @Override - public boolean isSetGradFill() { - return props.isSetGradFill(); - } - - @Override - public void setGradFill(CTGradientFillProperties gradFill) { - props.setGradFill(gradFill); - } - - @Override - public CTGradientFillProperties addNewGradFill() { - return props.addNewGradFill(); - } - - @Override - public void unsetGradFill() { - props.unsetGradFill(); - } - - @Override - public CTBlipFillProperties getBlipFill() { - return props.getBlipFill(); - } - - @Override - public boolean isSetBlipFill() { - return props.isSetBlipFill(); - } - - @Override - public void setBlipFill(CTBlipFillProperties blipFill) { - props.setBlipFill(blipFill); - } - - @Override - public CTBlipFillProperties addNewBlipFill() { - return props.addNewBlipFill(); - } - - @Override - public void unsetBlipFill() { - props.unsetBlipFill(); - } - - @Override - public CTPatternFillProperties getPattFill() { - return props.getPattFill(); - } - - @Override - public boolean isSetPattFill() { - return props.isSetPattFill(); - } - - @Override - public void setPattFill(CTPatternFillProperties pattFill) { - props.setPattFill(pattFill); - } - - @Override - public CTPatternFillProperties addNewPattFill() { - return props.addNewPattFill(); - } - - @Override - public void unsetPattFill() { - props.unsetPattFill(); - } - - @Override - public CTGroupFillProperties getGrpFill() { - return props.getGrpFill(); - } - - @Override - public boolean isSetGrpFill() { - return props.isSetGrpFill(); - } - - @Override - public void setGrpFill(CTGroupFillProperties grpFill) { - props.setGrpFill(grpFill); - } - - @Override - public CTGroupFillProperties addNewGrpFill() { - return props.addNewGrpFill(); - } - - @Override - public void unsetGrpFill() { - props.unsetGrpFill(); - } - - @Override - public boolean isSetMatrixStyle() { - return false; - } - - @Override - public CTStyleMatrixReference getMatrixStyle() { - return null; - } - - @Override - public boolean isLineStyle() { - return false; - } - } - - private static class StyleMatrixDelegate implements XSLFFillProperties { - final CTStyleMatrixReference props; - - StyleMatrixDelegate(CTStyleMatrixReference props) { - this.props = props; - } - - @Override - public CTNoFillProperties getNoFill() { - return null; - } - - @Override - public boolean isSetNoFill() { - return false; - } - - @Override - public void setNoFill(CTNoFillProperties noFill) {} - - @Override - public CTNoFillProperties addNewNoFill() { - return null; - } - - @Override - public void unsetNoFill() {} - - @Override - public CTSolidColorFillProperties getSolidFill() { - return null; - } - - @Override - public boolean isSetSolidFill() { - return false; - } - - @Override - public void setSolidFill(CTSolidColorFillProperties solidFill) {} - - @Override - public CTSolidColorFillProperties addNewSolidFill() { - return null; - } - - @Override - public void unsetSolidFill() {} - - @Override - public CTGradientFillProperties getGradFill() { - return null; - } - - @Override - public boolean isSetGradFill() { - return false; - } - - @Override - public void setGradFill(CTGradientFillProperties gradFill) {} - - @Override - public CTGradientFillProperties addNewGradFill() { - return null; - } - - @Override - public void unsetGradFill() {} - - @Override - public CTBlipFillProperties getBlipFill() { - return null; - } - - @Override - public boolean isSetBlipFill() { - return false; - } - - @Override - public void setBlipFill(CTBlipFillProperties blipFill) {} - - @Override - public CTBlipFillProperties addNewBlipFill() { - return null; - } - - @Override - public void unsetBlipFill() {} - - @Override - public CTPatternFillProperties getPattFill() { - return null; - } - - @Override - public boolean isSetPattFill() { - return false; - } - - @Override - public void setPattFill(CTPatternFillProperties pattFill) {} - - @Override - public CTPatternFillProperties addNewPattFill() { - return null; - } - - @Override - public void unsetPattFill() {} - - @Override - public CTGroupFillProperties getGrpFill() { - return null; - } - - @Override - public boolean isSetGrpFill() { - return false; - } - - @Override - public void setGrpFill(CTGroupFillProperties grpFill) {} - - @Override - public CTGroupFillProperties addNewGrpFill() { - return null; - } - - @Override - public void unsetGrpFill() {} - - - @Override - public boolean isSetMatrixStyle() { - return true; - } - - @Override - public CTStyleMatrixReference getMatrixStyle() { - return props; - } - - @Override - public boolean isLineStyle() { - XmlCursor cur = props.newCursor(); - String name = cur.getName().getLocalPart(); - cur.dispose(); - return "lnRef".equals(name); - } - } - - private static class FillDelegate implements XSLFFillProperties { - final CTFillProperties props; - - FillDelegate(CTFillProperties props) { - this.props = props; - } - - @Override - public CTNoFillProperties getNoFill() { - return props.getNoFill(); - } - - @Override - public boolean isSetNoFill() { - return props.isSetNoFill(); - } - - @Override - public void setNoFill(CTNoFillProperties noFill) { - props.setNoFill(noFill); - } - - @Override - public CTNoFillProperties addNewNoFill() { - return props.addNewNoFill(); - } - - @Override - public void unsetNoFill() { - props.unsetNoFill(); - } - - @Override - public CTSolidColorFillProperties getSolidFill() { - return props.getSolidFill(); - } - - @Override - public boolean isSetSolidFill() { - return props.isSetSolidFill(); - } - - @Override - public void setSolidFill(CTSolidColorFillProperties solidFill) { - props.setSolidFill(solidFill); - } - - @Override - public CTSolidColorFillProperties addNewSolidFill() { - return props.addNewSolidFill(); - } - - @Override - public void unsetSolidFill() { - props.unsetSolidFill(); - } - - @Override - public CTGradientFillProperties getGradFill() { - return props.getGradFill(); - } - - @Override - public boolean isSetGradFill() { - return props.isSetGradFill(); - } - - @Override - public void setGradFill(CTGradientFillProperties gradFill) { - props.setGradFill(gradFill); - } - - @Override - public CTGradientFillProperties addNewGradFill() { - return props.addNewGradFill(); - } - - @Override - public void unsetGradFill() { - props.unsetGradFill(); - } - - @Override - public CTBlipFillProperties getBlipFill() { - return props.getBlipFill(); - } - - @Override - public boolean isSetBlipFill() { - return props.isSetBlipFill(); - } - - @Override - public void setBlipFill(CTBlipFillProperties blipFill) { - props.setBlipFill(blipFill); - } - - @Override - public CTBlipFillProperties addNewBlipFill() { - return props.addNewBlipFill(); - } - - @Override - public void unsetBlipFill() { - props.unsetBlipFill(); - } - - @Override - public CTPatternFillProperties getPattFill() { - return props.getPattFill(); - } - - @Override - public boolean isSetPattFill() { - return props.isSetPattFill(); - } - - @Override - public void setPattFill(CTPatternFillProperties pattFill) { - props.setPattFill(pattFill); - } - - @Override - public CTPatternFillProperties addNewPattFill() { - return props.addNewPattFill(); - } - - @Override - public void unsetPattFill() { - props.unsetPattFill(); - } - - @Override - public CTGroupFillProperties getGrpFill() { - return props.getGrpFill(); - } - - @Override - public boolean isSetGrpFill() { - return props.isSetGrpFill(); - } - - @Override - public void setGrpFill(CTGroupFillProperties grpFill) { - props.setGrpFill(grpFill); - } - - @Override - public CTGroupFillProperties addNewGrpFill() { - return props.addNewGrpFill(); - } - - @Override - public void unsetGrpFill() { - props.unsetGrpFill(); - } - - @Override - public boolean isSetMatrixStyle() { - return false; - } - - @Override - public CTStyleMatrixReference getMatrixStyle() { - return null; - } - - @Override - public boolean isLineStyle() { - return false; - } - } - - private static class FillPartDelegate implements XSLFFillProperties { - final XmlObject props; - - FillPartDelegate(XmlObject props) { - this.props = props; - } - - @Override - public CTNoFillProperties getNoFill() { - return isSetNoFill() ? (CTNoFillProperties)props : null; - } - - @Override - public boolean isSetNoFill() { - return (props instanceof CTNoFillProperties); - } - - @Override - public void setNoFill(CTNoFillProperties noFill) {} - - @Override - public CTNoFillProperties addNewNoFill() { - return null; - } - - @Override - public void unsetNoFill() {} - - @Override - public CTSolidColorFillProperties getSolidFill() { - return isSetSolidFill() ? (CTSolidColorFillProperties)props : null; - } - - @Override - public boolean isSetSolidFill() { - return (props instanceof CTSolidColorFillProperties); - } - - @Override - public void setSolidFill(CTSolidColorFillProperties solidFill) {} - - @Override - public CTSolidColorFillProperties addNewSolidFill() { - return null; - } - - @Override - public void unsetSolidFill() {} - - @Override - public CTGradientFillProperties getGradFill() { - return isSetGradFill() ? (CTGradientFillProperties)props : null; - } - - @Override - public boolean isSetGradFill() { - return (props instanceof CTGradientFillProperties); - } - - @Override - public void setGradFill(CTGradientFillProperties gradFill) {} - - @Override - public CTGradientFillProperties addNewGradFill() { - return null; - } - - @Override - public void unsetGradFill() {} - - @Override - public CTBlipFillProperties getBlipFill() { - return isSetBlipFill() ? (CTBlipFillProperties)props : null; - } - - @Override - public boolean isSetBlipFill() { - return (props instanceof CTBlipFillProperties); - } - - @Override - public void setBlipFill(CTBlipFillProperties blipFill) {} - - @Override - public CTBlipFillProperties addNewBlipFill() { - return null; - } - - @Override - public void unsetBlipFill() {} - - @Override - public CTPatternFillProperties getPattFill() { - return isSetPattFill() ? (CTPatternFillProperties)props : null; - } - - @Override - public boolean isSetPattFill() { - return (props instanceof CTPatternFillProperties); - } - - @Override - public void setPattFill(CTPatternFillProperties pattFill) {} - - @Override - public CTPatternFillProperties addNewPattFill() { - return null; - } - - @Override - public void unsetPattFill() {} - - @Override - public CTGroupFillProperties getGrpFill() { - return isSetGrpFill() ? (CTGroupFillProperties)props : null; - } - - @Override - public boolean isSetGrpFill() { - return (props instanceof CTGroupFillProperties); - } - - @Override - public void setGrpFill(CTGroupFillProperties grpFill) {} - - @Override - public CTGroupFillProperties addNewGrpFill() { - return null; - } - - @Override - public void unsetGrpFill() {} - - @Override - public boolean isSetMatrixStyle() { - return false; - } - - @Override - public CTStyleMatrixReference getMatrixStyle() { - return null; - } - - @Override - public boolean isLineStyle() { - return false; - } - } - - private static class LineStyleDelegate implements XSLFFillProperties { - final CTLineProperties props; - - LineStyleDelegate(CTLineProperties props) { - this.props = props; - } - - @Override - public CTNoFillProperties getNoFill() { - return props.getNoFill(); - } - - @Override - public boolean isSetNoFill() { - return props.isSetNoFill(); - } - - @Override - public void setNoFill(CTNoFillProperties noFill) { - props.setNoFill(noFill); - } - - @Override - public CTNoFillProperties addNewNoFill() { - return props.addNewNoFill(); - } - - @Override - public void unsetNoFill() { - props.unsetNoFill(); - } - - @Override - public CTSolidColorFillProperties getSolidFill() { - return props.getSolidFill(); - } - - @Override - public boolean isSetSolidFill() { - return props.isSetSolidFill(); - } - - @Override - public void setSolidFill(CTSolidColorFillProperties solidFill) { - props.setSolidFill(solidFill); - } - - @Override - public CTSolidColorFillProperties addNewSolidFill() { - return props.addNewSolidFill(); - } - - @Override - public void unsetSolidFill() { - props.unsetSolidFill(); - } - - @Override - public CTGradientFillProperties getGradFill() { - return props.getGradFill(); - } - - @Override - public boolean isSetGradFill() { - return props.isSetGradFill(); - } - - @Override - public void setGradFill(CTGradientFillProperties gradFill) { - props.setGradFill(gradFill); - } - - @Override - public CTGradientFillProperties addNewGradFill() { - return props.addNewGradFill(); - } - - @Override - public void unsetGradFill() { - props.unsetGradFill(); - } - - @Override - public CTBlipFillProperties getBlipFill() { - return null; - } - - @Override - public boolean isSetBlipFill() { - return false; - } - - @Override - public void setBlipFill(CTBlipFillProperties blipFill) {} - - @Override - public CTBlipFillProperties addNewBlipFill() { - return null; - } - - @Override - public void unsetBlipFill() {} - - @Override - public CTPatternFillProperties getPattFill() { - return props.getPattFill(); - } - - @Override - public boolean isSetPattFill() { - return props.isSetPattFill(); - } - - @Override - public void setPattFill(CTPatternFillProperties pattFill) { - props.setPattFill(pattFill); - } - - @Override - public CTPatternFillProperties addNewPattFill() { - return props.addNewPattFill(); - } - - @Override - public void unsetPattFill() { - props.unsetPattFill(); - } - - @Override - public CTGroupFillProperties getGrpFill() { - return null; - } - - @Override - public boolean isSetGrpFill() { - return false; - } - - @Override - public void setGrpFill(CTGroupFillProperties grpFill) {} - - @Override - public CTGroupFillProperties addNewGrpFill() { - return null; - } - - @Override - public void unsetGrpFill() {} - - @Override - public boolean isSetMatrixStyle() { - return false; - } - - @Override - public CTStyleMatrixReference getMatrixStyle() { - return null; - } - - @Override - public boolean isLineStyle() { - return true; - } - } - - private static class TextCharDelegate implements XSLFFillProperties { - final CTTextCharacterProperties props; - - TextCharDelegate(CTTextCharacterProperties props) { - this.props = props; - } - - @Override - public CTNoFillProperties getNoFill() { - return props.getNoFill(); - } - - @Override - public boolean isSetNoFill() { - return props.isSetNoFill(); - } - - @Override - public void setNoFill(CTNoFillProperties noFill) { - props.setNoFill(noFill); - } - - @Override - public CTNoFillProperties addNewNoFill() { - return props.addNewNoFill(); - } - - @Override - public void unsetNoFill() { - props.unsetNoFill(); - } - - @Override - public CTSolidColorFillProperties getSolidFill() { - return props.getSolidFill(); - } - - @Override - public boolean isSetSolidFill() { - return props.isSetSolidFill(); - } - - @Override - public void setSolidFill(CTSolidColorFillProperties solidFill) { - props.setSolidFill(solidFill); - } - - @Override - public CTSolidColorFillProperties addNewSolidFill() { - return props.addNewSolidFill(); - } - - @Override - public void unsetSolidFill() { - props.unsetSolidFill(); - } - - @Override - public CTGradientFillProperties getGradFill() { - return props.getGradFill(); - } - - @Override - public boolean isSetGradFill() { - return props.isSetGradFill(); - } - - @Override - public void setGradFill(CTGradientFillProperties gradFill) { - props.setGradFill(gradFill); - } - - @Override - public CTGradientFillProperties addNewGradFill() { - return props.addNewGradFill(); - } - - @Override - public void unsetGradFill() { - props.unsetGradFill(); - } - - @Override - public CTBlipFillProperties getBlipFill() { - return props.getBlipFill(); - } - - @Override - public boolean isSetBlipFill() { - return props.isSetBlipFill(); - } - - @Override - public void setBlipFill(CTBlipFillProperties blipFill) { - props.setBlipFill(blipFill); - } - - @Override - public CTBlipFillProperties addNewBlipFill() { - return props.addNewBlipFill(); - } - - @Override - public void unsetBlipFill() { - props.unsetBlipFill(); - } - - @Override - public CTPatternFillProperties getPattFill() { - return props.getPattFill(); - } - - @Override - public boolean isSetPattFill() { - return props.isSetPattFill(); - } - - @Override - public void setPattFill(CTPatternFillProperties pattFill) { - props.setPattFill(pattFill); - } - - @Override - public CTPatternFillProperties addNewPattFill() { - return props.addNewPattFill(); - } - - @Override - public void unsetPattFill() { - props.unsetPattFill(); - } - - @Override - public CTGroupFillProperties getGrpFill() { - return props.getGrpFill(); - } - - @Override - public boolean isSetGrpFill() { - return props.isSetGrpFill(); - } - - @Override - public void setGrpFill(CTGroupFillProperties grpFill) { - props.setGrpFill(grpFill); - } - - @Override - public CTGroupFillProperties addNewGrpFill() { - return props.addNewGrpFill(); - } - - @Override - public void unsetGrpFill() { - props.unsetGrpFill(); - } - - @Override - public boolean isSetMatrixStyle() { - return false; - } - - @Override - public CTStyleMatrixReference getMatrixStyle() { - return null; - } - - @Override - public boolean isLineStyle() { - return false; - } - } - - @SuppressWarnings("unchecked") - private static T getDelegate(Class clazz, XmlObject props) { - Object obj = null; - if (props == null) { - return null; - } else if (props instanceof CTShapeProperties) { - obj = new ShapeDelegate((CTShapeProperties)props); - } else if (props instanceof CTBackgroundProperties) { - obj = new BackgroundDelegate((CTBackgroundProperties)props); - } else if (props instanceof CTStyleMatrixReference) { - obj = new StyleMatrixDelegate((CTStyleMatrixReference)props); - } else if (props instanceof CTTableCellProperties) { - obj = new TableCellDelegate((CTTableCellProperties)props); - } else if (props instanceof CTNoFillProperties - || props instanceof CTSolidColorFillProperties - || props instanceof CTGradientFillProperties - || props instanceof CTBlipFillProperties - || props instanceof CTPatternFillProperties - || props instanceof CTGroupFillProperties) { - obj = new FillPartDelegate(props); - } else if (props instanceof CTFillProperties) { - obj = new FillDelegate((CTFillProperties)props); - } else if (props instanceof CTLineProperties) { - obj = new LineStyleDelegate((CTLineProperties)props); - } else if (props instanceof CTTextCharacterProperties) { - obj = new TextCharDelegate((CTTextCharacterProperties)props); - } else { - LOG.log(POILogger.ERROR, props.getClass().toString()+" is an unknown properties type"); - return null; - } - - if (clazz.isInstance(obj)) { - return (T)obj; - } - - LOG.log(POILogger.WARN, obj.getClass().toString()+" doesn't implement "+clazz.toString()); - return null; - } -} diff --git a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFRelation.java b/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFRelation.java deleted file mode 100644 index f3f59b918..000000000 --- a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFRelation.java +++ /dev/null @@ -1,249 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.usermodel; - -import java.util.HashMap; -import java.util.Map; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.POIXMLRelation; -import org.apache.poi.sl.usermodel.PictureData.PictureType; -import org.apache.poi.util.Beta; - -@Beta -public class XSLFRelation extends POIXMLRelation { - - /** - * A map to lookup POIXMLRelation by its relation type - */ - private static final Map _table = new HashMap(); - - public static final XSLFRelation MAIN = new XSLFRelation( - "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml", - null, null, null - ); - - public static final XSLFRelation MACRO = new XSLFRelation( - "application/vnd.ms-powerpoint.slideshow.macroEnabled.main+xml", - null, null, null - ); - - public static final XSLFRelation MACRO_TEMPLATE = new XSLFRelation( - "application/vnd.ms-powerpoint.template.macroEnabled.main+xml", - null, null, null - ); - - public static final XSLFRelation PRESENTATIONML = new XSLFRelation( - "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml", - null, null, null - ); - - public static final XSLFRelation PRESENTATIONML_TEMPLATE = new XSLFRelation( - "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml", - null, null, null - ); - - public static final XSLFRelation PRESENTATION_MACRO = new XSLFRelation( - "application/vnd.ms-powerpoint.presentation.macroEnabled.main+xml", - null, null, null - ); - - public static final XSLFRelation THEME_MANAGER = new XSLFRelation( - "application/vnd.openxmlformats-officedocument.themeManager+xml", - null, null, null - ); - - public static final XSLFRelation NOTES = new XSLFRelation( - "application/vnd.openxmlformats-officedocument.presentationml.notesSlide+xml", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesSlide", - "/ppt/notesSlides/notesSlide#.xml", - XSLFNotes.class - ); - - public static final XSLFRelation SLIDE = new XSLFRelation( - "application/vnd.openxmlformats-officedocument.presentationml.slide+xml", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide", - "/ppt/slides/slide#.xml", - XSLFSlide.class - ); - - public static final XSLFRelation SLIDE_LAYOUT = new XSLFRelation( - "application/vnd.openxmlformats-officedocument.presentationml.slideLayout+xml", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout", - "/ppt/slideLayouts/slideLayout#.xml", - XSLFSlideLayout.class - ); - - public static final XSLFRelation SLIDE_MASTER = new XSLFRelation( - "application/vnd.openxmlformats-officedocument.presentationml.slideMaster+xml", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideMaster", - "/ppt/slideMasters/slideMaster#.xml", - XSLFSlideMaster.class - ); - - public static final XSLFRelation NOTES_MASTER = new XSLFRelation( - "application/vnd.openxmlformats-officedocument.presentationml.notesMaster+xml", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesMaster", - "/ppt/notesMasters/notesMaster#.xml", - XSLFNotesMaster.class - ); - - public static final XSLFRelation COMMENTS = new XSLFRelation( - "application/vnd.openxmlformats-officedocument.presentationml.comments+xml", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments", - "/ppt/comments/comment#.xml", - XSLFComments.class - ); - - public static final XSLFRelation COMMENT_AUTHORS = new XSLFRelation( - "application/vnd.openxmlformats-officedocument.presentationml.commentAuthors+xml", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/commentAuthors", - "/ppt/commentAuthors.xml", - XSLFCommentAuthors.class - ); - - public static final XSLFRelation HYPERLINK = new XSLFRelation( - null, - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink", - null, - null - ); - - public static final XSLFRelation THEME = new XSLFRelation( - "application/vnd.openxmlformats-officedocument.theme+xml", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme", - "/ppt/theme/theme#.xml", - XSLFTheme.class - ); - - public static final XSLFRelation VML_DRAWING = new XSLFRelation( - "application/vnd.openxmlformats-officedocument.vmlDrawing", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing", - "/ppt/drawings/vmlDrawing#.vml", - null - ); - - public static final XSLFRelation CHART = new XSLFRelation( - "application/vnd.openxmlformats-officedocument.drawingml.chart+xml", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart", - "/ppt/charts/chart#.xml", - XSLFChart.class - ); - - public static final XSLFRelation IMAGE_EMF = new XSLFRelation( - PictureType.EMF.contentType, - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", - "/ppt/media/image#.emf", - XSLFPictureData.class - ); - public static final XSLFRelation IMAGE_WMF = new XSLFRelation( - PictureType.WMF.contentType, - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", - "/ppt/media/image#.wmf", - XSLFPictureData.class - ); - public static final XSLFRelation IMAGE_PICT = new XSLFRelation( - PictureType.PICT.contentType, - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", - "/ppt/media/image#.pict", - XSLFPictureData.class - ); - public static final XSLFRelation IMAGE_JPEG = new XSLFRelation( - PictureType.JPEG.contentType, - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", - "/ppt/media/image#.jpeg", - XSLFPictureData.class - ); - public static final XSLFRelation IMAGE_PNG = new XSLFRelation( - PictureType.PNG.contentType, - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", - "/ppt/media/image#.png", - XSLFPictureData.class - ); - public static final XSLFRelation IMAGE_DIB = new XSLFRelation( - PictureType.DIB.contentType, - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", - "/ppt/media/image#.dib", - XSLFPictureData.class - ); - public static final XSLFRelation IMAGE_GIF = new XSLFRelation( - PictureType.GIF.contentType, - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", - "/ppt/media/image#.gif", - XSLFPictureData.class - ); - public static final XSLFRelation IMAGE_TIFF = new XSLFRelation( - PictureType.TIFF.contentType, - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", - "/ppt/media/image#.tiff", - XSLFPictureData.class - ); - public static final XSLFRelation IMAGE_EPS = new XSLFRelation( - PictureType.EPS.contentType, - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", - "/ppt/media/image#.eps", - XSLFPictureData.class - ); - public static final XSLFRelation IMAGE_BMP = new XSLFRelation( - PictureType.BMP.contentType, - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", - "/ppt/media/image#.bmp", - XSLFPictureData.class - ); - public static final XSLFRelation IMAGE_WPG = new XSLFRelation( - PictureType.WPG.contentType, - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", - "/ppt/media/image#.wpg", - XSLFPictureData.class - ); - public static final XSLFRelation IMAGE_WDP = new XSLFRelation( - PictureType.WDP.contentType, - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", - "/ppt/media/image#.wdp", - XSLFPictureData.class - ); - - public static final XSLFRelation IMAGES = new XSLFRelation( - null, - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", - null, - XSLFPictureData.class - ); - - public static final XSLFRelation TABLE_STYLES = new XSLFRelation( - "application/vnd.openxmlformats-officedocument.presentationml.tableStyles+xml", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/tableStyles", - "/ppt/tableStyles.xml", - XSLFTableStyles.class - ); - - private XSLFRelation(String type, String rel, String defaultName, Class cls) { - super(type, rel, defaultName, cls); - _table.put(rel, this); - } - - /** - * Get POIXMLRelation by relation type - * - * @param rel relation type, for example, - * http://schemas.openxmlformats.org/officeDocument/2006/relationships/image - * @return registered POIXMLRelation or null if not found - */ - public static XSLFRelation getInstance(String rel){ - return _table.get(rel); - } -} diff --git a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFShadow.java b/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFShadow.java deleted file mode 100644 index 6ab7711a8..000000000 --- a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFShadow.java +++ /dev/null @@ -1,107 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xslf.usermodel; - -import java.awt.Color; -import java.awt.geom.Rectangle2D; - -import org.apache.poi.sl.draw.DrawPaint; -import org.apache.poi.sl.usermodel.PaintStyle.SolidPaint; -import org.apache.poi.sl.usermodel.Shadow; -import org.apache.poi.util.Units; -import org.openxmlformats.schemas.drawingml.x2006.main.CTOuterShadowEffect; -import org.openxmlformats.schemas.drawingml.x2006.main.CTSchemeColor; - -/** - * Represents a shadow of a shape. For now supports only outer shadows. - * - * @author Yegor Kozlov - */ -public class XSLFShadow extends XSLFShape implements Shadow { - - private XSLFSimpleShape _parent; - - /* package */XSLFShadow(CTOuterShadowEffect shape, XSLFSimpleShape parentShape) { - super(shape, parentShape.getSheet()); - - _parent = parentShape; - } - - @Override - public XSLFSimpleShape getShadowParent() { - return _parent; - } - - @Override - public Rectangle2D getAnchor(){ - return _parent.getAnchor(); - } - - public void setAnchor(Rectangle2D anchor){ - throw new IllegalStateException("You can't set anchor of a shadow"); - } - - /** - * @return the offset of this shadow in points - */ - public double getDistance(){ - CTOuterShadowEffect ct = (CTOuterShadowEffect)getXmlObject(); - return ct.isSetDist() ? Units.toPoints(ct.getDist()) : 0; - } - - /** - * - * @return the direction to offset the shadow in angles - */ - public double getAngle(){ - CTOuterShadowEffect ct = (CTOuterShadowEffect)getXmlObject(); - return ct.isSetDir() ? (double)ct.getDir() / 60000 : 0; - } - - /** - * - * @return the blur radius of the shadow - * TODO: figure out how to make sense of this property when rendering shadows - */ - public double getBlur(){ - CTOuterShadowEffect ct = (CTOuterShadowEffect)getXmlObject(); - return ct.isSetBlurRad() ? Units.toPoints(ct.getBlurRad()) : 0; - } - - /** - * @return the color of this shadow. - * Depending whether the parent shape is filled or stroked, this color is used to fill or stroke this shadow - */ - public Color getFillColor() { - SolidPaint ps = getFillStyle(); - if (ps == null) return null; - Color col = DrawPaint.applyColorTransform(ps.getSolidColor()); - return col; - } - - @Override - public SolidPaint getFillStyle() { - XSLFTheme theme = getSheet().getTheme(); - CTOuterShadowEffect ct = (CTOuterShadowEffect)getXmlObject(); - if(ct == null) return null; - - CTSchemeColor phClr = ct.getSchemeClr(); - final XSLFColor xc = new XSLFColor(ct, theme, phClr); - return DrawPaint.createSolidPaint(xc.getColorStyle()); - } -} \ No newline at end of file diff --git a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFShape.java b/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFShape.java deleted file mode 100644 index 91b5abd63..000000000 --- a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFShape.java +++ /dev/null @@ -1,560 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xslf.usermodel; - -import java.awt.Graphics2D; -import java.awt.geom.Rectangle2D; -import java.io.IOException; -import java.io.InputStream; -import java.util.Arrays; -import java.util.Comparator; - -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.opc.PackageRelationship; -import org.apache.poi.sl.draw.DrawFactory; -import org.apache.poi.sl.draw.DrawPaint; -import org.apache.poi.sl.usermodel.ColorStyle; -import org.apache.poi.sl.usermodel.MasterSheet; -import org.apache.poi.sl.usermodel.PaintStyle; -import org.apache.poi.sl.usermodel.PaintStyle.GradientPaint; -import org.apache.poi.sl.usermodel.PaintStyle.TexturePaint; -import org.apache.poi.sl.usermodel.PlaceableShape; -import org.apache.poi.sl.usermodel.Placeholder; -import org.apache.poi.sl.usermodel.Shape; -import org.apache.poi.util.Beta; -import org.apache.poi.util.Internal; -import org.apache.poi.xslf.model.PropertyFetcher; -import org.apache.poi.xslf.usermodel.XSLFPropertiesDelegate.XSLFFillProperties; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlObject; -import org.openxmlformats.schemas.drawingml.x2006.main.CTBlip; -import org.openxmlformats.schemas.drawingml.x2006.main.CTBlipFillProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTGradientFillProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTGradientStop; -import org.openxmlformats.schemas.drawingml.x2006.main.CTGroupShapeProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps; -import org.openxmlformats.schemas.drawingml.x2006.main.CTSchemeColor; -import org.openxmlformats.schemas.drawingml.x2006.main.CTShapeProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTShapeStyle; -import org.openxmlformats.schemas.drawingml.x2006.main.CTSolidColorFillProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTStyleMatrix; -import org.openxmlformats.schemas.drawingml.x2006.main.CTStyleMatrixReference; -import org.openxmlformats.schemas.drawingml.x2006.main.STPathShadeType; -import org.openxmlformats.schemas.presentationml.x2006.main.CTApplicationNonVisualDrawingProps; -import org.openxmlformats.schemas.presentationml.x2006.main.CTBackgroundProperties; -import org.openxmlformats.schemas.presentationml.x2006.main.CTPlaceholder; -import org.openxmlformats.schemas.presentationml.x2006.main.CTShape; -import org.openxmlformats.schemas.presentationml.x2006.main.STPlaceholderType; - -/** - * Base super-class class for all shapes in PresentationML - */ -@Beta -public abstract class XSLFShape implements Shape { - protected static final String PML_NS = "http://schemas.openxmlformats.org/presentationml/2006/main"; - - private final XmlObject _shape; - private final XSLFSheet _sheet; - private XSLFShapeContainer _parent; - - private CTShapeStyle _spStyle; - private CTNonVisualDrawingProps _nvPr; - private CTPlaceholder _ph; - - protected XSLFShape(XmlObject shape, XSLFSheet sheet) { - _shape = shape; - _sheet = sheet; - } - - /** - * @return the xml bean holding this shape's data - */ - public final XmlObject getXmlObject() { - // it's final because the xslf inheritance hierarchy is not necessary the same as - // the (not existing) xmlbeans hierarchy and subclasses shouldn't narrow it's return value - return _shape; - } - - public XSLFSheet getSheet() { - return _sheet; - } - - /** - * @return human-readable name of this shape, e.g. "Rectange 3" - */ - public String getShapeName(){ - return getCNvPr().getName(); - } - - /** - * Returns a unique identifier for this shape within the current document. - * This ID may be used to assist in uniquely identifying this object so that it can - * be referred to by other parts of the document. - *

    - * If multiple objects within the same document share the same id attribute value, - * then the document shall be considered non-conformant. - *

    - * - * @return unique id of this shape - */ - public int getShapeId() { - return (int)getCNvPr().getId(); - } - - /** - * Set the contents of this shape to be a copy of the source shape. - * This method is called recursively for each shape when merging slides - * - * @param sh the source shape - * @see org.apache.poi.xslf.usermodel.XSLFSlide#importContent(XSLFSheet) - */ - @Internal - void copy(XSLFShape sh) { - if (!getClass().isInstance(sh)) { - throw new IllegalArgumentException( - "Can't copy " + sh.getClass().getSimpleName() + " into " + getClass().getSimpleName()); - } - - if (this instanceof PlaceableShape) { - PlaceableShape ps = (PlaceableShape)this; - ps.setAnchor(sh.getAnchor()); - } - - - } - - public void setParent(XSLFShapeContainer parent) { - this._parent = parent; - } - - public XSLFShapeContainer getParent() { - return this._parent; - } - - protected PaintStyle getFillPaint() { - final XSLFTheme theme = getSheet().getTheme(); - final boolean hasPlaceholder = getPlaceholder() != null; - PropertyFetcher fetcher = new PropertyFetcher() { - public boolean fetch(XSLFShape shape) { - XSLFFillProperties fp = XSLFPropertiesDelegate.getFillDelegate(shape.getShapeProperties()); - if (fp == null) { - return false; - } - - if (fp.isSetNoFill()) { - setValue(null); - return true; - } - - PackagePart pp = shape.getSheet().getPackagePart(); - PaintStyle paint = selectPaint(fp, null, pp, theme, hasPlaceholder); - if (paint != null) { - setValue(paint); - return true; - } - - CTShapeStyle style = shape.getSpStyle(); - if (style != null) { - fp = XSLFPropertiesDelegate.getFillDelegate(style.getFillRef()); - paint = selectPaint(fp, null, pp, theme, hasPlaceholder); - } - if (paint != null) { - setValue(paint); - return true; - } - - - return false; - } - }; - fetchShapeProperty(fetcher); - - return fetcher.getValue(); - } - - protected CTBackgroundProperties getBgPr() { - return getChild(CTBackgroundProperties.class, PML_NS, "bgPr"); - } - - protected CTStyleMatrixReference getBgRef() { - return getChild(CTStyleMatrixReference.class, PML_NS, "bgRef"); - } - - protected CTGroupShapeProperties getGrpSpPr() { - return getChild(CTGroupShapeProperties.class, PML_NS, "grpSpPr"); - } - - protected CTNonVisualDrawingProps getCNvPr() { - if (_nvPr == null) { - String xquery = "declare namespace p='http://schemas.openxmlformats.org/presentationml/2006/main' .//*/p:cNvPr"; - _nvPr = selectProperty(CTNonVisualDrawingProps.class, xquery); - } - return _nvPr; - } - - protected CTShapeStyle getSpStyle() { - if (_spStyle == null) { - _spStyle = getChild(CTShapeStyle.class, PML_NS, "style"); - } - return _spStyle; - } - - /** - * Return direct child objects of this shape - * - * @param childClass the class to cast the properties to - * @param namespace the namespace - usually it is {@code "http://schemas.openxmlformats.org/presentationml/2006/main"} - * @param nodename the node name, without prefix - * @return the properties object or null if it can't be found - */ - @SuppressWarnings("unchecked") - protected T getChild(Class childClass, String namespace, String nodename) { - XmlCursor cur = getXmlObject().newCursor(); - T child = null; - if (cur.toChild(namespace, nodename)) { - child = (T)cur.getObject(); - } - if (cur.toChild("http://schemas.openxmlformats.org/drawingml/2006/main", nodename)) { - child = (T)cur.getObject(); - } - cur.dispose(); - return child; - } - - protected CTPlaceholder getCTPlaceholder() { - if (_ph == null) { - String xquery = "declare namespace p='"+PML_NS+"' .//*/p:nvPr/p:ph"; - _ph = selectProperty(CTPlaceholder.class, xquery); - } - return _ph; - } - - public Placeholder getPlaceholder() { - CTPlaceholder ph = getCTPlaceholder(); - if (ph == null || !(ph.isSetType() || ph.isSetIdx())) { - return null; - } - return Placeholder.lookupOoxml(ph.getType().intValue()); - } - - /** - * Specifies that the corresponding shape should be represented by the generating application - * as a placeholder. When a shape is considered a placeholder by the generating application - * it can have special properties to alert the user that they may enter content into the shape. - * Different types of placeholders are allowed and can be specified by using the placeholder - * type attribute for this element - * - * @param placeholder The shape to use as placeholder or null if no placeholder should be set. - */ - protected void setPlaceholder(Placeholder placeholder) { - String xquery = "declare namespace p='"+PML_NS+"' .//*/p:nvPr"; - CTApplicationNonVisualDrawingProps nv = selectProperty(CTApplicationNonVisualDrawingProps.class, xquery); - if (nv == null) return; - if(placeholder == null) { - if (nv.isSetPh()) nv.unsetPh(); - _ph = null; - } else { - nv.addNewPh().setType(STPlaceholderType.Enum.forInt(placeholder.ooxmlId)); - } - } - - - /** - * As there's no xmlbeans hierarchy, but XSLF works with subclassing, not all - * child classes work with a {@link CTShape} object, but often contain the same - * properties. This method is the generalized form of selecting and casting those - * properties. - * - * @param resultClass the requested result class - * @param xquery the simple (xmlbean) xpath expression to the property - * @return the xml object at the xpath location, or null if not found - */ - @SuppressWarnings("unchecked") - protected T selectProperty(Class resultClass, String xquery) { - XmlObject[] rs = getXmlObject().selectPath(xquery); - if (rs.length == 0) return null; - return (resultClass.isInstance(rs[0])) ? (T)rs[0] : null; - } - - /** - * Walk up the inheritance tree and fetch shape properties.

    - * - * The following order of inheritance is assumed:

    - *

      - *
    1. slide - *
    2. slideLayout - *
    3. slideMaster - *
    - * - * Currently themes and their defaults aren't correctly handled - * - * @param visitor the object that collects the desired property - * @return true if the property was fetched - */ - protected boolean fetchShapeProperty(PropertyFetcher visitor) { - // try shape properties in slide - if (visitor.fetch(this)) { - return true; - } - - CTPlaceholder ph = getCTPlaceholder(); - if (ph == null) { - return false; - } - MasterSheet sm = getSheet().getMasterSheet(); - - // try slide layout - if (sm instanceof XSLFSlideLayout) { - XSLFSlideLayout slideLayout = (XSLFSlideLayout)sm; - XSLFSimpleShape placeholderShape = slideLayout.getPlaceholder(ph); - if (placeholderShape != null && visitor.fetch(placeholderShape)) { - return true; - } - sm = slideLayout.getMasterSheet(); - } - - // try slide master - if (sm instanceof XSLFSlideMaster) { - XSLFSlideMaster master = (XSLFSlideMaster)sm; - int textType = getPlaceholderType(ph); - XSLFSimpleShape masterShape = master.getPlaceholderByType(textType); - if (masterShape != null && visitor.fetch(masterShape)) { - return true; - } - } - - return false; - } - - private static int getPlaceholderType(CTPlaceholder ph) { - if ( !ph.isSetType()) { - return STPlaceholderType.INT_BODY; - } - - switch (ph.getType().intValue()) { - case STPlaceholderType.INT_TITLE: - case STPlaceholderType.INT_CTR_TITLE: - return STPlaceholderType.INT_TITLE; - case STPlaceholderType.INT_FTR: - case STPlaceholderType.INT_SLD_NUM: - case STPlaceholderType.INT_DT: - return ph.getType().intValue(); - default: - return STPlaceholderType.INT_BODY; - } - } - - /** - * Convert shape fill into java.awt.Paint. The result is either Color or - * TexturePaint or GradientPaint or null - * - * @param fp a properties handler specific to the underlying shape properties - * @param phClr context color - * @param parentPart the parent package part. Any external references (images, etc.) are resolved relative to it. - * @param theme the theme for the shape/sheet - * - * @return the applied Paint or null if none was applied - */ - protected static PaintStyle selectPaint(XSLFFillProperties fp, final CTSchemeColor phClr, final PackagePart parentPart, final XSLFTheme theme, boolean hasPlaceholder) { - if (fp == null || fp.isSetNoFill()) { - return null; - } else if (fp.isSetSolidFill()) { - return selectPaint(fp.getSolidFill(), phClr, theme); - } else if (fp.isSetBlipFill()) { - return selectPaint(fp.getBlipFill(), parentPart); - } else if (fp.isSetGradFill()) { - return selectPaint(fp.getGradFill(), phClr, theme); - } else if (fp.isSetMatrixStyle()) { - return selectPaint(fp.getMatrixStyle(), theme, fp.isLineStyle(), hasPlaceholder); - } else { - return null; - } - } - - protected static PaintStyle selectPaint(CTSolidColorFillProperties solidFill, CTSchemeColor phClr, final XSLFTheme theme) { - if (solidFill.isSetSchemeClr()) { - // if there's a reference to the placeholder color, - // stop evaluating further and let the caller select - // the next style inheritance level -// if (STSchemeColorVal.PH_CLR.equals(solidFill.getSchemeClr().getVal())) { -// return null; -// } - if (phClr == null) { - phClr = solidFill.getSchemeClr(); - } - } - final XSLFColor c = new XSLFColor(solidFill, theme, phClr); - return DrawPaint.createSolidPaint(c.getColorStyle()); - } - - protected static PaintStyle selectPaint(final CTBlipFillProperties blipFill, final PackagePart parentPart) { - final CTBlip blip = blipFill.getBlip(); - return new TexturePaint() { - private PackagePart getPart() { - try { - String blipId = blip.getEmbed(); - PackageRelationship rel = parentPart.getRelationship(blipId); - return parentPart.getRelatedPart(rel); - } catch (InvalidFormatException e) { - throw new RuntimeException(e); - } - } - - public InputStream getImageData() { - try { - return getPart().getInputStream(); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - public String getContentType() { - /* TOOD: map content-type */ - return getPart().getContentType(); - } - - public int getAlpha() { - return (blip.sizeOfAlphaModFixArray() > 0) - ? blip.getAlphaModFixArray(0).getAmt() - : 100000; - } - }; - } - - protected static PaintStyle selectPaint(final CTGradientFillProperties gradFill, CTSchemeColor phClr, final XSLFTheme theme) { - - final CTGradientStop[] gs = gradFill.getGsLst().getGsArray(); - - Arrays.sort(gs, new Comparator() { - public int compare(CTGradientStop o1, CTGradientStop o2) { - Integer pos1 = o1.getPos(); - Integer pos2 = o2.getPos(); - return pos1.compareTo(pos2); - } - }); - - final ColorStyle cs[] = new ColorStyle[gs.length]; - final float fractions[] = new float[gs.length]; - - int i=0; - for (CTGradientStop cgs : gs) { - CTSchemeColor phClrCgs = phClr; - if (phClrCgs == null && cgs.isSetSchemeClr()) { - phClrCgs = cgs.getSchemeClr(); - } - cs[i] = new XSLFColor(cgs, theme, phClrCgs).getColorStyle(); - fractions[i] = cgs.getPos() / 100000.f; - i++; - } - - return new GradientPaint() { - - public double getGradientAngle() { - return (gradFill.isSetLin()) - ? gradFill.getLin().getAng() / 60000.d - : 0; - } - - public ColorStyle[] getGradientColors() { - return cs; - } - - public float[] getGradientFractions() { - return fractions; - } - - public boolean isRotatedWithShape() { - return gradFill.getRotWithShape(); - } - - public GradientType getGradientType() { - if (gradFill.isSetLin()) { - return GradientType.linear; - } - - if (gradFill.isSetPath()) { - /* TODO: handle rect path */ - STPathShadeType.Enum ps = gradFill.getPath().getPath(); - if (ps == STPathShadeType.CIRCLE) { - return GradientType.circular; - } else if (ps == STPathShadeType.SHAPE) { - return GradientType.shape; - } - } - - return GradientType.linear; - } - }; - } - - protected static PaintStyle selectPaint(CTStyleMatrixReference fillRef, final XSLFTheme theme, boolean isLineStyle, boolean hasPlaceholder) { - if (fillRef == null) return null; - - // The idx attribute refers to the index of a fill style or - // background fill style within the presentation's style matrix, defined by the fmtScheme element. - // value of 0 or 1000 indicates no background, - // values 1-999 refer to the index of a fill style within the fillStyleLst element - // values 1001 and above refer to the index of a background fill style within the bgFillStyleLst element. - int idx = (int)fillRef.getIdx(); - CTStyleMatrix matrix = theme.getXmlObject().getThemeElements().getFmtScheme(); - final XmlObject styleLst; - int childIdx; - if (idx >= 1 && idx <= 999) { - childIdx = idx-1; - styleLst = (isLineStyle) ? matrix.getLnStyleLst() : matrix.getFillStyleLst(); - } else if (idx >= 1001 ){ - childIdx = idx - 1001; - styleLst = matrix.getBgFillStyleLst(); - } else { - return null; - } - XmlCursor cur = styleLst.newCursor(); - XSLFFillProperties fp = null; - if (cur.toChild(childIdx)) { - fp = XSLFPropertiesDelegate.getFillDelegate(cur.getObject()); - } - cur.dispose(); - - CTSchemeColor phClr = fillRef.getSchemeClr(); - PaintStyle res = selectPaint(fp, phClr, theme.getPackagePart(), theme, hasPlaceholder); - // check for empty placeholder value - // see http://officeopenxml.com/prSlide-color.php - "Color Placeholders within Themes" - if (res != null || hasPlaceholder) { - return res; - } - XSLFColor col = new XSLFColor(fillRef, theme, phClr); - return DrawPaint.createSolidPaint(col.getColorStyle()); - } - - @Override - public void draw(Graphics2D graphics, Rectangle2D bounds) { - DrawFactory.getInstance(graphics).drawShape(graphics, this, bounds); - } - - /** - * Return the shape specific (visual) properties - * - * @return the shape specific properties - */ - protected XmlObject getShapeProperties() { - return getChild(CTShapeProperties.class, PML_NS, "spPr"); - } -} \ No newline at end of file diff --git a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFShapeContainer.java b/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFShapeContainer.java deleted file mode 100644 index ddf832d3d..000000000 --- a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFShapeContainer.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xslf.usermodel; - -import org.apache.poi.sl.usermodel.PictureData; -import org.apache.poi.sl.usermodel.ShapeContainer; - -/** - * Common interface for shape containers, e.g. sheets or groups of shapes - */ -public interface XSLFShapeContainer - extends ShapeContainer { - - @Override - XSLFAutoShape createAutoShape(); - - @Override - XSLFFreeformShape createFreeform(); - - @Override - XSLFTextBox createTextBox(); - - @Override - XSLFConnectorShape createConnector(); - - @Override - XSLFGroupShape createGroup(); - - @Override - XSLFPictureShape createPicture(PictureData pictureData); - - /** - * Removes all of the elements from this container (optional operation). - * The container will be empty after this call returns. - */ - void clear(); -} diff --git a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFSheet.java b/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFSheet.java deleted file mode 100644 index 50f31730d..000000000 --- a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFSheet.java +++ /dev/null @@ -1,610 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.usermodel; - -import static org.apache.poi.POIXMLTypeLoader.DEFAULT_XML_OPTIONS; - -import java.awt.Graphics2D; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import javax.xml.namespace.QName; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.POIXMLException; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.opc.PackagePartName; -import org.apache.poi.openxml4j.opc.PackageRelationship; -import org.apache.poi.openxml4j.opc.TargetMode; -import org.apache.poi.sl.draw.DrawFactory; -import org.apache.poi.sl.draw.DrawPictureShape; -import org.apache.poi.sl.draw.Drawable; -import org.apache.poi.sl.usermodel.PictureData; -import org.apache.poi.sl.usermodel.Placeholder; -import org.apache.poi.sl.usermodel.Sheet; -import org.apache.poi.util.Beta; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.Internal; -import org.apache.poi.util.Removal; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlOptions; -import org.openxmlformats.schemas.presentationml.x2006.main.CTCommonSlideData; -import org.openxmlformats.schemas.presentationml.x2006.main.CTConnector; -import org.openxmlformats.schemas.presentationml.x2006.main.CTGraphicalObjectFrame; -import org.openxmlformats.schemas.presentationml.x2006.main.CTGroupShape; -import org.openxmlformats.schemas.presentationml.x2006.main.CTPicture; -import org.openxmlformats.schemas.presentationml.x2006.main.CTPlaceholder; -import org.openxmlformats.schemas.presentationml.x2006.main.CTShape; - -@Beta -public abstract class XSLFSheet extends POIXMLDocumentPart -implements XSLFShapeContainer, Sheet { - private XSLFCommonSlideData _commonSlideData; - private XSLFDrawing _drawing; - private List _shapes; - private CTGroupShape _spTree; - - private List_placeholders; - private Map _placeholderByIdMap; - private Map _placeholderByTypeMap; - - public XSLFSheet() { - super(); - } - - /** - * @since POI 3.14-Beta1 - */ - public XSLFSheet(PackagePart part) { - super(part); - } - - /** - * @return the XMLSlideShow this sheet belongs to - */ - @Override - public XMLSlideShow getSlideShow() { - POIXMLDocumentPart p = getParent(); - while(p != null) { - if(p instanceof XMLSlideShow){ - return (XMLSlideShow)p; - } - p = p.getParent(); - } - throw new IllegalStateException("SlideShow was not found"); - } - - protected static List buildShapes(CTGroupShape spTree, XSLFSheet sheet){ - List shapes = new ArrayList(); - for(XmlObject ch : spTree.selectPath("*")){ - if(ch instanceof CTShape){ // simple shape - XSLFAutoShape shape = XSLFAutoShape.create((CTShape)ch, sheet); - shapes.add(shape); - } else if (ch instanceof CTGroupShape){ - shapes.add(new XSLFGroupShape((CTGroupShape)ch, sheet)); - } else if (ch instanceof CTConnector){ - shapes.add(new XSLFConnectorShape((CTConnector)ch, sheet)); - } else if (ch instanceof CTPicture){ - shapes.add(new XSLFPictureShape((CTPicture)ch, sheet)); - } else if (ch instanceof CTGraphicalObjectFrame){ - XSLFGraphicFrame shape = XSLFGraphicFrame.create((CTGraphicalObjectFrame)ch, sheet); - shapes.add(shape); - } - } - return shapes; - } - - /** - * @return top-level Xml bean representing this sheet - */ - public abstract XmlObject getXmlObject(); - - /* - * @deprecated POI 3.16 beta 1. use {@link XSLFTable} instead - */ - @Removal(version="3.18") - @Internal - public XSLFCommonSlideData getCommonSlideData() { - return _commonSlideData; - } - - /* - * @deprecated POI 3.16 beta 1. use {@link XSLFTable} instead - */ - @Removal(version="3.18") - protected void setCommonSlideData(CTCommonSlideData data) { - if(data == null) { - _commonSlideData = null; - } else { - _commonSlideData = new XSLFCommonSlideData(data); - } - } - - private XSLFDrawing getDrawing(){ - initDrawingAndShapes(); - return _drawing; - } - - /** - * Returns an array containing all of the shapes in this sheet - * - * @return an array of all shapes in this sheet - */ - @Override - public List getShapes(){ - initDrawingAndShapes(); - return _shapes; - } - - /** - * Helper method for initializing drawing and shapes in one go. - * If they are initialized separately, there's a risk that shapes - * get added twice, e.g. a shape is added to the drawing, then - * buildShapes is called and at last the shape is added to shape list - */ - private void initDrawingAndShapes() { - CTGroupShape cgs = getSpTree(); - if(_drawing == null) { - _drawing = new XSLFDrawing(this, cgs); - } - if (_shapes == null) { - _shapes = buildShapes(cgs, this); - } - } - - // shape factory methods - - @Override - public XSLFAutoShape createAutoShape(){ - XSLFAutoShape sh = getDrawing().createAutoShape(); - getShapes().add(sh); - sh.setParent(this); - return sh; - } - - @Override - public XSLFFreeformShape createFreeform(){ - XSLFFreeformShape sh = getDrawing().createFreeform(); - getShapes().add(sh); - sh.setParent(this); - return sh; - } - - @Override - public XSLFTextBox createTextBox(){ - XSLFTextBox sh = getDrawing().createTextBox(); - getShapes().add(sh); - sh.setParent(this); - return sh; - } - - @Override - public XSLFConnectorShape createConnector(){ - XSLFConnectorShape sh = getDrawing().createConnector(); - getShapes().add(sh); - sh.setParent(this); - return sh; - } - - @Override - public XSLFGroupShape createGroup(){ - XSLFGroupShape sh = getDrawing().createGroup(); - getShapes().add(sh); - sh.setParent(this); - return sh; - } - - @Override - public XSLFPictureShape createPicture(PictureData pictureData){ - if (!(pictureData instanceof XSLFPictureData)) { - throw new IllegalArgumentException("pictureData needs to be of type XSLFPictureData"); - } - XSLFPictureData xPictureData = (XSLFPictureData)pictureData; - PackagePart pic = xPictureData.getPackagePart(); - - RelationPart rp = addRelation(null, XSLFRelation.IMAGES, new XSLFPictureData(pic)); - - XSLFPictureShape sh = getDrawing().createPicture(rp.getRelationship().getId()); - new DrawPictureShape(sh).resize(); - getShapes().add(sh); - sh.setParent(this); - return sh; - } - - public XSLFTable createTable(){ - XSLFTable sh = getDrawing().createTable(); - getShapes().add(sh); - sh.setParent(this); - return sh; - } - - @Override - public XSLFTable createTable(int numRows, int numCols){ - if (numRows < 1 || numCols < 1) { - throw new IllegalArgumentException("numRows and numCols must be greater than 0"); - } - XSLFTable sh = getDrawing().createTable(); - getShapes().add(sh); - sh.setParent(this); - for (int r=0; r iterator(){ - return getShapes().iterator(); - } - - public void addShape(XSLFShape shape) { - throw new UnsupportedOperationException( - "Adding a shape from a different container is not supported -" - + " create it from scratch witht XSLFSheet.create* methods"); - } - - /** - * Removes the specified shape from this sheet, if it is present - * (optional operation). If this sheet does not contain the element, - * it is unchanged. - * - * @param xShape shape to be removed from this sheet, if present - * @return true if this sheet contained the specified element - * @throws IllegalArgumentException if the type of the specified shape - * is incompatible with this sheet (optional) - */ - public boolean removeShape(XSLFShape xShape) { - XmlObject obj = xShape.getXmlObject(); - CTGroupShape spTree = getSpTree(); - if(obj instanceof CTShape){ - spTree.getSpList().remove(obj); - } else if (obj instanceof CTGroupShape) { - spTree.getGrpSpList().remove(obj); - } else if (obj instanceof CTConnector) { - spTree.getCxnSpList().remove(obj); - } else if (obj instanceof CTGraphicalObjectFrame) { - spTree.getGraphicFrameList().remove(obj); - } else if (obj instanceof CTPicture) { - XSLFPictureShape ps = (XSLFPictureShape)xShape; - removePictureRelation(ps); - spTree.getPicList().remove(obj); - } else { - throw new IllegalArgumentException("Unsupported shape: " + xShape); - } - return getShapes().remove(xShape); - } - - /** - * Removes all of the elements from this container (optional operation). - * The container will be empty after this call returns. - */ - public void clear() { - List shapes = new ArrayList(getShapes()); - for(XSLFShape shape : shapes){ - removeShape(shape); - } - } - - protected abstract String getRootElementName(); - - protected CTGroupShape getSpTree(){ - if(_spTree == null) { - XmlObject root = getXmlObject(); - XmlObject[] sp = root.selectPath( - "declare namespace p='http://schemas.openxmlformats.org/presentationml/2006/main' .//*/p:spTree"); - if(sp.length == 0) throw new IllegalStateException("CTGroupShape was not found"); - _spTree = (CTGroupShape)sp[0]; - } - return _spTree; - } - - protected final void commit() throws IOException { - XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS); - String docName = getRootElementName(); - if(docName != null) { - xmlOptions.setSaveSyntheticDocumentElement( - new QName("http://schemas.openxmlformats.org/presentationml/2006/main", docName)); - } - - PackagePart part = getPackagePart(); - OutputStream out = part.getOutputStream(); - getXmlObject().save(out, xmlOptions); - out.close(); - } - - /** - * Set the contents of this sheet to be a copy of the source sheet. - * This method erases any existing shapes and replaces them with - * object from the source sheet. - * - * @param src the source sheet to copy data from - * @return modified 'this' - */ - public XSLFSheet importContent(XSLFSheet src){ - _shapes = null; - _spTree = null; - _drawing = null; - _spTree = null; - _placeholders = null; - - // fix-me: wth would this ever happen to work ... - - - // first copy the source xml - getSpTree().set(src.getSpTree()); - - // recursively update each shape - List tgtShapes = getShapes(); - List srcShapes = src.getShapes(); - for(int i = 0; i < tgtShapes.size(); i++){ - XSLFShape s1 = srcShapes.get(i); - XSLFShape s2 = tgtShapes.get(i); - - s2.copy(s1); - } - return this; - } - - /** - * Append content to this sheet. - * - * @param src the source sheet - * @return modified this. - */ - public XSLFSheet appendContent(XSLFSheet src){ - CTGroupShape spTree = getSpTree(); - int numShapes = getShapes().size(); - - CTGroupShape srcTree = src.getSpTree(); - for(XmlObject ch : srcTree.selectPath("*")){ - if(ch instanceof CTShape){ // simple shape - spTree.addNewSp().set(ch); - } else if (ch instanceof CTGroupShape){ - spTree.addNewGrpSp().set(ch); - } else if (ch instanceof CTConnector){ - spTree.addNewCxnSp().set(ch); - } else if (ch instanceof CTPicture){ - spTree.addNewPic().set(ch); - } else if (ch instanceof CTGraphicalObjectFrame){ - spTree.addNewGraphicFrame().set(ch); - } - } - - _shapes = null; - _spTree = null; - _drawing = null; - _spTree = null; - _placeholders = null; - - // recursively update each shape - List tgtShapes = getShapes(); - List srcShapes = src.getShapes(); - for(int i = 0; i < srcShapes.size(); i++){ - XSLFShape s1 = srcShapes.get(i); - XSLFShape s2 = tgtShapes.get(numShapes + i); - - s2.copy(s1); - } - return this; - } - - /** - * @return theme (shared styles) associated with this theme. - * By default returns null which means that this sheet is theme-less. - * Sheets that support the notion of themes (slides, masters, layouts, etc.) should override this - * method and return the corresponding package part. - */ - XSLFTheme getTheme(){ - return null; - } - - protected XSLFTextShape getTextShapeByType(Placeholder type){ - for(XSLFShape shape : this.getShapes()){ - if(shape instanceof XSLFTextShape) { - XSLFTextShape txt = (XSLFTextShape)shape; - if(txt.getTextType() == type) { - return txt; - } - } - } - return null; - } - - XSLFSimpleShape getPlaceholder(CTPlaceholder ph) { - XSLFSimpleShape shape = null; - if(ph.isSetIdx()) shape = getPlaceholderById((int)ph.getIdx()); - - if (shape == null && ph.isSetType()) { - shape = getPlaceholderByType(ph.getType().intValue()); - } - return shape; - } - - void initPlaceholders() { - if(_placeholders == null) { - _placeholders = new ArrayList(); - _placeholderByIdMap = new HashMap(); - _placeholderByTypeMap = new HashMap(); - - for(XSLFShape sh : getShapes()){ - if(sh instanceof XSLFTextShape){ - XSLFTextShape sShape = (XSLFTextShape)sh; - CTPlaceholder ph = sShape.getCTPlaceholder(); - if(ph != null) { - _placeholders.add(sShape); - if(ph.isSetIdx()) { - int idx = (int)ph.getIdx(); - _placeholderByIdMap.put(idx, sShape); - } - if(ph.isSetType()){ - _placeholderByTypeMap.put(ph.getType().intValue(), sShape); - } - } - } - } - } - } - - XSLFSimpleShape getPlaceholderById(int id) { - initPlaceholders(); - return _placeholderByIdMap.get(id); - } - - XSLFSimpleShape getPlaceholderByType(int ordinal) { - initPlaceholders(); - return _placeholderByTypeMap.get(ordinal); - } - - /** - * - * @param idx 0-based index of a placeholder in the sheet - * @return placeholder - */ - public XSLFTextShape getPlaceholder(int idx) { - initPlaceholders(); - return _placeholders.get(idx); - } - - /** - * - * @return all placeholder shapes in this sheet - */ - public XSLFTextShape[] getPlaceholders() { - initPlaceholders(); - return _placeholders.toArray(new XSLFTextShape[_placeholders.size()]); - } - - /** - * Checks if this sheet displays the specified shape. - * - * Subclasses can override it and skip certain shapes from drawings, - * for instance, slide masters and layouts don't display placeholders - */ - protected boolean canDraw(XSLFShape shape){ - return true; - } - - /** - * - * @return whether shapes on the master sheet should be shown. By default master graphics is turned off. - * Sheets that support the notion of master (slide, slideLayout) should override it and - * check this setting in the sheet XML - */ - public boolean getFollowMasterGraphics(){ - return false; - } - - /** - * @return background for this sheet - */ - @Override - public XSLFBackground getBackground() { - return null; - } - - /** - * Render this sheet into the supplied graphics object - * - * @param graphics - */ - @Override - public void draw(Graphics2D graphics){ - DrawFactory drawFact = DrawFactory.getInstance(graphics); - Drawable draw = drawFact.getDrawable(this); - draw.draw(graphics); - } - - /** - * Import a picture data from another document. - * - * @param blipId ID of the package relationship to retrieve. - * @param packagePart package part containing the data to import - * @return ID of the created relationship - */ - String importBlip(String blipId, PackagePart packagePart) { - PackageRelationship blipRel = packagePart.getRelationship(blipId); - PackagePart blipPart; - try { - blipPart = packagePart.getRelatedPart(blipRel); - } catch (InvalidFormatException e){ - throw new POIXMLException(e); - } - XSLFPictureData data = new XSLFPictureData(blipPart); - - XMLSlideShow ppt = getSlideShow(); - XSLFPictureData pictureData = ppt.addPicture(data.getData(), data.getType()); - PackagePart pic = pictureData.getPackagePart(); - - RelationPart rp = addRelation(blipId, XSLFRelation.IMAGES, new XSLFPictureData(pic)); - - return rp.getRelationship().getId(); - } - - /** - * Import a package part into this sheet. - */ - PackagePart importPart(PackageRelationship srcRel, PackagePart srcPafrt) { - PackagePart destPP = getPackagePart(); - PackagePartName srcPPName = srcPafrt.getPartName(); - - OPCPackage pkg = destPP.getPackage(); - if(pkg.containPart(srcPPName)){ - // already exists - return pkg.getPart(srcPPName); - } - - destPP.addRelationship(srcPPName, TargetMode.INTERNAL, srcRel.getRelationshipType()); - - PackagePart part = pkg.createPart(srcPPName, srcPafrt.getContentType()); - try { - OutputStream out = part.getOutputStream(); - InputStream is = srcPafrt.getInputStream(); - IOUtils.copy(is, out); - is.close(); - out.close(); - } catch (IOException e){ - throw new POIXMLException(e); - } - return part; - } - - /** - * Helper method for sheet and group shapes - * - * @param pictureShape the picture shapes whose relation is to be removed - */ - void removePictureRelation(XSLFPictureShape pictureShape) { - POIXMLDocumentPart pd = getRelationById(pictureShape.getBlipId()); - removeRelation(pd); - } -} \ No newline at end of file diff --git a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFSimpleShape.java b/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFSimpleShape.java deleted file mode 100644 index 19eba48ed..000000000 --- a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFSimpleShape.java +++ /dev/null @@ -1,1142 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xslf.usermodel; - -import java.awt.Color; -import java.awt.geom.Rectangle2D; - -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamReader; - -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.sl.draw.DrawPaint; -import org.apache.poi.sl.draw.geom.CustomGeometry; -import org.apache.poi.sl.draw.geom.Guide; -import org.apache.poi.sl.draw.geom.PresetGeometries; -import org.apache.poi.sl.usermodel.FillStyle; -import org.apache.poi.sl.usermodel.LineDecoration; -import org.apache.poi.sl.usermodel.LineDecoration.DecorationShape; -import org.apache.poi.sl.usermodel.LineDecoration.DecorationSize; -import org.apache.poi.sl.usermodel.PaintStyle; -import org.apache.poi.sl.usermodel.PaintStyle.SolidPaint; -import org.apache.poi.sl.usermodel.Placeholder; -import org.apache.poi.sl.usermodel.ShapeType; -import org.apache.poi.sl.usermodel.SimpleShape; -import org.apache.poi.sl.usermodel.StrokeStyle; -import org.apache.poi.sl.usermodel.StrokeStyle.LineCap; -import org.apache.poi.sl.usermodel.StrokeStyle.LineCompound; -import org.apache.poi.sl.usermodel.StrokeStyle.LineDash; -import org.apache.poi.util.Beta; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.util.Units; -import org.apache.poi.xslf.model.PropertyFetcher; -import org.apache.poi.xslf.usermodel.XSLFPropertiesDelegate.XSLFEffectProperties; -import org.apache.poi.xslf.usermodel.XSLFPropertiesDelegate.XSLFFillProperties; -import org.apache.poi.xslf.usermodel.XSLFPropertiesDelegate.XSLFGeometryProperties; -import org.apache.xmlbeans.XmlObject; -import org.openxmlformats.schemas.drawingml.x2006.main.CTBaseStyles; -import org.openxmlformats.schemas.drawingml.x2006.main.CTBlip; -import org.openxmlformats.schemas.drawingml.x2006.main.CTEffectStyleItem; -import org.openxmlformats.schemas.drawingml.x2006.main.CTGeomGuide; -import org.openxmlformats.schemas.drawingml.x2006.main.CTLineEndProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTLineProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTLineStyleList; -import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps; -import org.openxmlformats.schemas.drawingml.x2006.main.CTOuterShadowEffect; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPoint2D; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPresetGeometry2D; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPresetLineDashProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTSchemeColor; -import org.openxmlformats.schemas.drawingml.x2006.main.CTShapeProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTShapeStyle; -import org.openxmlformats.schemas.drawingml.x2006.main.CTSolidColorFillProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTStyleMatrix; -import org.openxmlformats.schemas.drawingml.x2006.main.CTStyleMatrixReference; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTransform2D; -import org.openxmlformats.schemas.drawingml.x2006.main.STCompoundLine; -import org.openxmlformats.schemas.drawingml.x2006.main.STLineCap; -import org.openxmlformats.schemas.drawingml.x2006.main.STLineEndLength; -import org.openxmlformats.schemas.drawingml.x2006.main.STLineEndType; -import org.openxmlformats.schemas.drawingml.x2006.main.STLineEndWidth; -import org.openxmlformats.schemas.drawingml.x2006.main.STPresetLineDashVal; -import org.openxmlformats.schemas.drawingml.x2006.main.STShapeType; -import org.openxmlformats.schemas.presentationml.x2006.main.CTPlaceholder; - -/** - * Represents a single (non-group) shape in a .pptx slide show - */ -@Beta -public abstract class XSLFSimpleShape extends XSLFShape - implements SimpleShape { - private static CTOuterShadowEffect NO_SHADOW = CTOuterShadowEffect.Factory.newInstance(); - private static final POILogger LOG = POILogFactory.getLogger(XSLFSimpleShape.class); - - /* package */XSLFSimpleShape(XmlObject shape, XSLFSheet sheet) { - super(shape,sheet); - } - - @Override - public void setShapeType(ShapeType type) { - XSLFGeometryProperties gp = XSLFPropertiesDelegate.getGeometryDelegate(getShapeProperties()); - if (gp == null) { - return; - } - if (gp.isSetCustGeom()) { - gp.unsetCustGeom(); - } - CTPresetGeometry2D prst = (gp.isSetPrstGeom()) ? gp.getPrstGeom() : gp.addNewPrstGeom(); - prst.setPrst(STShapeType.Enum.forInt(type.ooxmlId)); - } - - @Override - public ShapeType getShapeType(){ - XSLFGeometryProperties gp = XSLFPropertiesDelegate.getGeometryDelegate(getShapeProperties()); - if (gp != null && gp.isSetPrstGeom()) { - STShapeType.Enum geom = gp.getPrstGeom().getPrst(); - if (geom != null) { - return ShapeType.forId(geom.intValue(), true); - } - } - return null; - } - - protected CTTransform2D getXfrm(boolean create) { - PropertyFetcher fetcher = new PropertyFetcher() { - @Override - public boolean fetch(XSLFShape shape) { - XmlObject xo = shape.getShapeProperties(); - if (xo instanceof CTShapeProperties && ((CTShapeProperties)xo).isSetXfrm()) { - setValue(((CTShapeProperties)xo).getXfrm()); - return true; - } - return false; - } - }; - fetchShapeProperty(fetcher); - - CTTransform2D xfrm = fetcher.getValue(); - if (!create || xfrm != null) { - return xfrm; - } else { - XmlObject xo = getShapeProperties(); - if (xo instanceof CTShapeProperties) { - return ((CTShapeProperties)xo).addNewXfrm(); - } else { - // ... group shapes have their own getXfrm() - LOG.log(POILogger.WARN, getClass().toString()+" doesn't have xfrm element."); - return null; - } - } - } - - @Override - public Rectangle2D getAnchor() { - - CTTransform2D xfrm = getXfrm(false); - if (xfrm == null) { - return null; - } - - CTPoint2D off = xfrm.getOff(); - double x = Units.toPoints(off.getX()); - double y = Units.toPoints(off.getY()); - CTPositiveSize2D ext = xfrm.getExt(); - double cx = Units.toPoints(ext.getCx()); - double cy = Units.toPoints(ext.getCy()); - return new Rectangle2D.Double(x, y, cx, cy); - } - - @Override - public void setAnchor(Rectangle2D anchor) { - CTTransform2D xfrm = getXfrm(true); - if (xfrm == null) { - return; - } - CTPoint2D off = xfrm.isSetOff() ? xfrm.getOff() : xfrm.addNewOff(); - long x = Units.toEMU(anchor.getX()); - long y = Units.toEMU(anchor.getY()); - off.setX(x); - off.setY(y); - CTPositiveSize2D ext = xfrm.isSetExt() ? xfrm.getExt() : xfrm - .addNewExt(); - long cx = Units.toEMU(anchor.getWidth()); - long cy = Units.toEMU(anchor.getHeight()); - ext.setCx(cx); - ext.setCy(cy); - } - - @Override - public void setRotation(double theta) { - CTTransform2D xfrm = getXfrm(true); - if (xfrm != null) { - xfrm.setRot((int) (theta * 60000)); - } - } - - @Override - public double getRotation() { - CTTransform2D xfrm = getXfrm(false); - return (xfrm == null || !xfrm.isSetRot()) ? 0 : (xfrm.getRot() / 60000.d); - } - - @Override - public void setFlipHorizontal(boolean flip) { - CTTransform2D xfrm = getXfrm(true); - if (xfrm != null) { - xfrm.setFlipH(flip); - } - } - - @Override - public void setFlipVertical(boolean flip) { - CTTransform2D xfrm = getXfrm(true); - if (xfrm != null) { - xfrm.setFlipV(flip); - } - } - - @Override - public boolean getFlipHorizontal() { - CTTransform2D xfrm = getXfrm(false); - return (xfrm == null || !xfrm.isSetFlipH()) ? false : xfrm.getFlipH(); - } - - @Override - public boolean getFlipVertical() { - CTTransform2D xfrm = getXfrm(false); - return (xfrm == null || !xfrm.isSetFlipV()) ? false : xfrm.getFlipV(); - } - - - /** - * Get default line properties defined in the theme (if any). - * Used internally to resolve shape properties. - * - * @return line properties from the theme of null - */ - CTLineProperties getDefaultLineProperties() { - CTShapeStyle style = getSpStyle(); - if (style == null) { - return null; - } - CTStyleMatrixReference lnRef = style.getLnRef(); - if (lnRef == null) { - return null; - } - // 1-based index of a line style within the style matrix - int idx = (int)lnRef.getIdx(); - - XSLFTheme theme = getSheet().getTheme(); - if (theme == null) { - return null; - } - CTBaseStyles styles = theme.getXmlObject().getThemeElements(); - if (styles == null) { - return null; - } - CTStyleMatrix styleMatrix = styles.getFmtScheme(); - if (styleMatrix == null) { - return null; - } - CTLineStyleList lineStyles = styleMatrix.getLnStyleLst(); - if (lineStyles == null || lineStyles.sizeOfLnArray() < idx) { - return null; - } - - return lineStyles.getLnArray(idx - 1); - } - - /** - * @param color the color to paint the shape outline. - * A null value turns off the shape outline. - */ - public void setLineColor(Color color) { - CTLineProperties ln = getLn(this, true); - if (ln == null) { - return; - } - - if (ln.isSetSolidFill()) { - ln.unsetSolidFill(); - } - if (ln.isSetGradFill()) { - ln.unsetGradFill(); - } - if (ln.isSetPattFill()) { - ln.unsetPattFill(); - } - if (ln.isSetNoFill()) { - ln.unsetNoFill(); - } - - - if (color == null) { - ln.addNewNoFill(); - } else { - CTSolidColorFillProperties fill = ln.addNewSolidFill(); - XSLFColor col = new XSLFColor(fill, getSheet().getTheme(), fill.getSchemeClr()); - col.setColor(color); - } - } - - /** - * - * @return the color of the shape outline or null - * if outline is turned off - */ - public Color getLineColor() { - PaintStyle ps = getLinePaint(); - if (ps instanceof SolidPaint) { - return ((SolidPaint)ps).getSolidColor().getColor(); - } - return null; - } - - protected PaintStyle getLinePaint() { - XSLFSheet sheet = getSheet(); - final XSLFTheme theme = sheet.getTheme(); - final boolean hasPlaceholder = getPlaceholder() != null; - PropertyFetcher fetcher = new PropertyFetcher() { - @Override - public boolean fetch(XSLFShape shape) { - CTLineProperties spPr = getLn(shape, false); - XSLFFillProperties fp = XSLFPropertiesDelegate.getFillDelegate(spPr); - - if (fp != null && fp.isSetNoFill()) { - setValue(null); - return true; - } - - PackagePart pp = shape.getSheet().getPackagePart(); - PaintStyle paint = selectPaint(fp, null, pp, theme, hasPlaceholder); - if (paint != null) { - setValue(paint); - return true; - } - - CTShapeStyle style = shape.getSpStyle(); - if (style != null) { - fp = XSLFPropertiesDelegate.getFillDelegate(style.getLnRef()); - paint = selectPaint(fp, null, pp, theme, hasPlaceholder); - - // line color was not found, check if it is defined in the theme - if (paint == null) { - paint = getThemePaint(style, pp); - } - } - - if (paint != null) { - setValue(paint); - return true; - } - - return false; - } - - PaintStyle getThemePaint(CTShapeStyle style, PackagePart pp) { - // get a reference to a line style within the style matrix. - CTStyleMatrixReference lnRef = style.getLnRef(); - if (lnRef == null) { - return null; - } - int idx = (int)lnRef.getIdx(); - CTSchemeColor phClr = lnRef.getSchemeClr(); - if(idx <= 0){ - return null; - } - - CTLineProperties props = theme.getXmlObject().getThemeElements().getFmtScheme().getLnStyleLst().getLnArray(idx - 1); - XSLFFillProperties fp = XSLFPropertiesDelegate.getFillDelegate(props); - return selectPaint(fp, phClr, pp, theme, hasPlaceholder); - } - }; - fetchShapeProperty(fetcher); - - return fetcher.getValue(); - } - - /** - * - * @param width line width in points. 0 means no line - */ - public void setLineWidth(double width) { - CTLineProperties lnPr = getLn(this, true); - if (lnPr == null) { - return; - } - - if (width == 0.) { - if (lnPr.isSetW()) { - lnPr.unsetW(); - } - if (!lnPr.isSetNoFill()) { - lnPr.addNewNoFill(); - } - if (lnPr.isSetSolidFill()) { - lnPr.unsetSolidFill(); - } - if (lnPr.isSetGradFill()) { - lnPr.unsetGradFill(); - } - if (lnPr.isSetPattFill()) { - lnPr.unsetPattFill(); - } - } else { - if (lnPr.isSetNoFill()) { - lnPr.unsetNoFill(); - } - - lnPr.setW(Units.toEMU(width)); - } - } - - /** - * @return line width in points. 0 means no line. - */ - public double getLineWidth() { - PropertyFetcher fetcher = new PropertyFetcher() { - @Override - public boolean fetch(XSLFShape shape) { - CTLineProperties ln = getLn(shape, false); - if (ln != null) { - if (ln.isSetNoFill()) { - setValue(0.); - return true; - } - - if (ln.isSetW()) { - setValue(Units.toPoints(ln.getW())); - return true; - } - } - return false; - } - }; - fetchShapeProperty(fetcher); - - double lineWidth = 0; - if (fetcher.getValue() == null) { - CTLineProperties defaultLn = getDefaultLineProperties(); - if (defaultLn != null) { - if (defaultLn.isSetW()) { - lineWidth = Units.toPoints(defaultLn.getW()); - } - } - } else { - lineWidth = fetcher.getValue(); - } - - return lineWidth; - } - - - /** - * @param compound set the line compound style - */ - public void setLineCompound(LineCompound compound) { - CTLineProperties ln = getLn(this, true); - if (ln == null) { - return; - } - if (compound == null) { - if (ln.isSetCmpd()) { - ln.unsetCmpd(); - } - } else { - STCompoundLine.Enum xCmpd; - switch (compound) { - default: - case SINGLE: - xCmpd = STCompoundLine.SNG; - break; - case DOUBLE: - xCmpd = STCompoundLine.DBL; - break; - case THICK_THIN: - xCmpd = STCompoundLine.THICK_THIN; - break; - case THIN_THICK: - xCmpd = STCompoundLine.THIN_THICK; - break; - case TRIPLE: - xCmpd = STCompoundLine.TRI; - break; - } - ln.setCmpd(xCmpd); - } - } - - /** - * @return the line compound - */ - public LineCompound getLineCompound() { - PropertyFetcher fetcher = new PropertyFetcher() { - @Override - public boolean fetch(XSLFShape shape) { - CTLineProperties ln = getLn(shape, false); - if (ln != null) { - STCompoundLine.Enum stCmpd = ln.getCmpd(); - if (stCmpd != null) { - setValue(stCmpd.intValue()); - return true; - } - } - return false; - } - }; - fetchShapeProperty(fetcher); - - Integer cmpd = fetcher.getValue(); - if (cmpd == null) { - CTLineProperties defaultLn = getDefaultLineProperties(); - if (defaultLn != null && defaultLn.isSetCmpd()) { - switch (defaultLn.getCmpd().intValue()) { - default: - case STCompoundLine.INT_SNG: - return LineCompound.SINGLE; - case STCompoundLine.INT_DBL: - return LineCompound.DOUBLE; - case STCompoundLine.INT_THICK_THIN: - return LineCompound.THICK_THIN; - case STCompoundLine.INT_THIN_THICK: - return LineCompound.THIN_THICK; - case STCompoundLine.INT_TRI: - return LineCompound.TRIPLE; - } - } - } - - return null; - } - - /** - * - * @param dash a preset line dashing scheme to stroke thr shape outline - */ - public void setLineDash(LineDash dash) { - CTLineProperties ln = getLn(this, true); - if (ln == null) { - return; - } - if (dash == null) { - if (ln.isSetPrstDash()) { - ln.unsetPrstDash(); - } - } else { - CTPresetLineDashProperties ldp = ln.isSetPrstDash() ? ln.getPrstDash() : ln.addNewPrstDash(); - ldp.setVal(STPresetLineDashVal.Enum.forInt(dash.ooxmlId)); - } - } - - /** - * @return a preset line dashing scheme to stroke the shape outline - */ - public LineDash getLineDash() { - - PropertyFetcher fetcher = new PropertyFetcher() { - @Override - public boolean fetch(XSLFShape shape) { - CTLineProperties ln = getLn(shape, false); - if (ln == null || !ln.isSetPrstDash()) { - return false; - } - - setValue(LineDash.fromOoxmlId(ln.getPrstDash().getVal().intValue())); - return true; - } - }; - fetchShapeProperty(fetcher); - - LineDash dash = fetcher.getValue(); - if (dash == null) { - CTLineProperties defaultLn = getDefaultLineProperties(); - if (defaultLn != null && defaultLn.isSetPrstDash()) { - dash = LineDash.fromOoxmlId(defaultLn.getPrstDash().getVal().intValue()); - } - } - return dash; - } - - /** - * - * @param cap the line end cap style - */ - public void setLineCap(LineCap cap) { - CTLineProperties ln = getLn(this, true); - if (ln == null) { - return; - } - - if (cap == null) { - if (ln.isSetCap()) { - ln.unsetCap(); - } - } else { - ln.setCap(STLineCap.Enum.forInt(cap.ooxmlId)); - } - } - - /** - * - * @return the line end cap style - */ - public LineCap getLineCap() { - PropertyFetcher fetcher = new PropertyFetcher() { - @Override - public boolean fetch(XSLFShape shape) { - CTLineProperties ln = getLn(shape, false); - if (ln != null && ln.isSetCap()) { - setValue(LineCap.fromOoxmlId(ln.getCap().intValue())); - return true; - } - return false; - } - }; - fetchShapeProperty(fetcher); - - LineCap cap = fetcher.getValue(); - if (cap == null) { - CTLineProperties defaultLn = getDefaultLineProperties(); - if (defaultLn != null && defaultLn.isSetCap()) { - cap = LineCap.fromOoxmlId(defaultLn.getCap().intValue()); - } - } - return cap; - } - - @Override - public void setFillColor(Color color) { - XSLFFillProperties fp = XSLFPropertiesDelegate.getFillDelegate(getShapeProperties()); - if (fp == null) { - return; - } - if (color == null) { - if (fp.isSetSolidFill()) { - fp.unsetSolidFill(); - } - - if (fp.isSetGradFill()) { - fp.unsetGradFill(); - } - - if (fp.isSetPattFill()) { - fp.unsetGradFill(); - } - - if (fp.isSetBlipFill()) { - fp.unsetBlipFill(); - } - - if (!fp.isSetNoFill()) { - fp.addNewNoFill(); - } - } else { - if (fp.isSetNoFill()) { - fp.unsetNoFill(); - } - - CTSolidColorFillProperties fill = fp.isSetSolidFill() ? fp.getSolidFill() : fp.addNewSolidFill(); - - XSLFColor col = new XSLFColor(fill, getSheet().getTheme(), fill.getSchemeClr()); - col.setColor(color); - } - } - - @Override - public Color getFillColor() { - PaintStyle ps = getFillPaint(); - if (ps instanceof SolidPaint) { - return DrawPaint.applyColorTransform(((SolidPaint)ps).getSolidColor()); - } - return null; - } - - /** - * @return shadow of this shape or null if shadow is disabled - */ - @Override - public XSLFShadow getShadow() { - PropertyFetcher fetcher = new PropertyFetcher() { - @Override - public boolean fetch(XSLFShape shape) { - XSLFEffectProperties ep = XSLFPropertiesDelegate.getEffectDelegate(shape.getShapeProperties()); - if (ep != null && ep.isSetEffectLst()) { - CTOuterShadowEffect obj = ep.getEffectLst().getOuterShdw(); - setValue(obj == null ? NO_SHADOW : obj); - return true; - } - return false; - } - }; - fetchShapeProperty(fetcher); - - CTOuterShadowEffect obj = fetcher.getValue(); - if (obj == null) { - // fill color was not found, check if it is defined in the theme - CTShapeStyle style = getSpStyle(); - if (style != null && style.getEffectRef() != null) { - // 1-based index of a shadow style within the style matrix - int idx = (int) style.getEffectRef().getIdx(); - if(idx != 0) { - CTStyleMatrix styleMatrix = getSheet().getTheme().getXmlObject().getThemeElements().getFmtScheme(); - CTEffectStyleItem ef = styleMatrix.getEffectStyleLst().getEffectStyleArray(idx - 1); - obj = ef.getEffectLst().getOuterShdw(); - } - } - } - return (obj == null || obj == NO_SHADOW) ? null : new XSLFShadow(obj, this); - } - - /** - * - * @return definition of the shape geometry - */ - @Override - public CustomGeometry getGeometry() { - XSLFGeometryProperties gp = XSLFPropertiesDelegate.getGeometryDelegate(getShapeProperties()); - - if (gp == null) { - return null; - } - - CustomGeometry geom; - PresetGeometries dict = PresetGeometries.getInstance(); - if(gp.isSetPrstGeom()){ - String name = gp.getPrstGeom().getPrst().toString(); - geom = dict.get(name); - if(geom == null) { - throw new IllegalStateException("Unknown shape geometry: " + name + ", available geometries are: " + dict.keySet()); - } - } else if (gp.isSetCustGeom()){ - XMLStreamReader staxReader = gp.getCustGeom().newXMLStreamReader(); - geom = PresetGeometries.convertCustomGeometry(staxReader); - try { - staxReader.close(); - } - catch (XMLStreamException e) { - LOG.log(POILogger.WARN, - "An error occurred while closing a Custom Geometry XML Stream Reader: " + e.getMessage()); - } - } else { - geom = dict.get("rect"); - } - return geom; - } - - @Override - void copy(XSLFShape sh){ - super.copy(sh); - - XSLFSimpleShape s = (XSLFSimpleShape)sh; - - Color srsSolidFill = s.getFillColor(); - Color tgtSoliFill = getFillColor(); - if(srsSolidFill != null && !srsSolidFill.equals(tgtSoliFill)){ - setFillColor(srsSolidFill); - } - - XSLFFillProperties fp = XSLFPropertiesDelegate.getFillDelegate(getShapeProperties()); - if(fp != null && fp.isSetBlipFill()){ - CTBlip blip = fp.getBlipFill().getBlip(); - String blipId = blip.getEmbed(); - - String relId = getSheet().importBlip(blipId, s.getSheet().getPackagePart()); - blip.setEmbed(relId); - } - - Color srcLineColor = s.getLineColor(); - Color tgtLineColor = getLineColor(); - if(srcLineColor != null && !srcLineColor.equals(tgtLineColor)) { - setLineColor(srcLineColor); - } - - double srcLineWidth = s.getLineWidth(); - double tgtLineWidth = getLineWidth(); - if(srcLineWidth != tgtLineWidth) { - setLineWidth(srcLineWidth); - } - - LineDash srcLineDash = s.getLineDash(); - LineDash tgtLineDash = getLineDash(); - if(srcLineDash != null && srcLineDash != tgtLineDash) { - setLineDash(srcLineDash); - } - - LineCap srcLineCap = s.getLineCap(); - LineCap tgtLineCap = getLineCap(); - if(srcLineCap != null && srcLineCap != tgtLineCap) { - setLineCap(srcLineCap); - } - - } - - /** - * Specifies the line end decoration, such as a triangle or arrowhead. - * - * @param style the line end docoration style - */ - public void setLineHeadDecoration(DecorationShape style) { - CTLineProperties ln = getLn(this, true); - if (ln == null) { - return; - } - CTLineEndProperties lnEnd = ln.isSetHeadEnd() ? ln.getHeadEnd() : ln.addNewHeadEnd(); - if (style == null) { - if (lnEnd.isSetType()) { - lnEnd.unsetType(); - } - } else { - lnEnd.setType(STLineEndType.Enum.forInt(style.ooxmlId)); - } - } - - /** - * @return the line end decoration shape - */ - public DecorationShape getLineHeadDecoration() { - CTLineProperties ln = getLn(this, false); - DecorationShape ds = DecorationShape.NONE; - if (ln != null && ln.isSetHeadEnd() && ln.getHeadEnd().isSetType()) { - ds = DecorationShape.fromOoxmlId(ln.getHeadEnd().getType().intValue()); - } - return ds; - } - - /** - * specifies decoration width of the head of a line. - * - * @param style the decoration width - */ - public void setLineHeadWidth(DecorationSize style) { - CTLineProperties ln = getLn(this, true); - if (ln == null) { - return; - } - CTLineEndProperties lnEnd = ln.isSetHeadEnd() ? ln.getHeadEnd() : ln.addNewHeadEnd(); - if (style == null) { - if (lnEnd.isSetW()) { - lnEnd.unsetW(); - } - } else { - lnEnd.setW(STLineEndWidth.Enum.forInt(style.ooxmlId)); - } - } - - /** - * @return the line end decoration width - */ - public DecorationSize getLineHeadWidth() { - CTLineProperties ln = getLn(this, false); - DecorationSize ds = DecorationSize.MEDIUM; - if (ln != null && ln.isSetHeadEnd() && ln.getHeadEnd().isSetW()) { - ds = DecorationSize.fromOoxmlId(ln.getHeadEnd().getW().intValue()); - } - return ds; - } - - /** - * Specifies the line end width in relation to the line width. - */ - public void setLineHeadLength(DecorationSize style) { - CTLineProperties ln = getLn(this, true); - if (ln == null) { - return; - } - - CTLineEndProperties lnEnd = ln.isSetHeadEnd() ? ln.getHeadEnd() : ln.addNewHeadEnd(); - if (style == null) { - if (lnEnd.isSetLen()) { - lnEnd.unsetLen(); - } - } else { - lnEnd.setLen(STLineEndLength.Enum.forInt(style.ooxmlId)); - } - } - - /** - * @return the line end decoration length - */ - public DecorationSize getLineHeadLength() { - CTLineProperties ln = getLn(this, false); - - DecorationSize ds = DecorationSize.MEDIUM; - if (ln != null && ln.isSetHeadEnd() && ln.getHeadEnd().isSetLen()) { - ds = DecorationSize.fromOoxmlId(ln.getHeadEnd().getLen().intValue()); - } - return ds; - } - - /** - * Specifies the line end decoration, such as a triangle or arrowhead. - */ - public void setLineTailDecoration(DecorationShape style) { - CTLineProperties ln = getLn(this, true); - if (ln == null) { - return; - } - - CTLineEndProperties lnEnd = ln.isSetTailEnd() ? ln.getTailEnd() : ln.addNewTailEnd(); - if (style == null) { - if (lnEnd.isSetType()) { - lnEnd.unsetType(); - } - } else { - lnEnd.setType(STLineEndType.Enum.forInt(style.ooxmlId)); - } - } - - /** - * @return the line end decoration shape - */ - public DecorationShape getLineTailDecoration() { - CTLineProperties ln = getLn(this, false); - - DecorationShape ds = DecorationShape.NONE; - if (ln != null && ln.isSetTailEnd() && ln.getTailEnd().isSetType()) { - ds = DecorationShape.fromOoxmlId(ln.getTailEnd().getType().intValue()); - } - return ds; - } - - /** - * specifies decorations which can be added to the tail of a line. - */ - public void setLineTailWidth(DecorationSize style) { - CTLineProperties ln = getLn(this, true); - if (ln == null) { - return; - } - - CTLineEndProperties lnEnd = ln.isSetTailEnd() ? ln.getTailEnd() : ln.addNewTailEnd(); - if (style == null) { - if (lnEnd.isSetW()) { - lnEnd.unsetW(); - } - } else { - lnEnd.setW(STLineEndWidth.Enum.forInt(style.ooxmlId)); - } - } - - /** - * @return the line end decoration width - */ - public DecorationSize getLineTailWidth() { - CTLineProperties ln = getLn(this, false); - DecorationSize ds = DecorationSize.MEDIUM; - if (ln != null && ln.isSetTailEnd() && ln.getTailEnd().isSetW()) { - ds = DecorationSize.fromOoxmlId(ln.getTailEnd().getW().intValue()); - } - return ds; - } - - /** - * Specifies the line end width in relation to the line width. - */ - public void setLineTailLength(DecorationSize style) { - CTLineProperties ln = getLn(this, true); - if (ln == null) { - return; - } - - CTLineEndProperties lnEnd = ln.isSetTailEnd() ? ln.getTailEnd() : ln.addNewTailEnd(); - if (style == null) { - if (lnEnd.isSetLen()) { - lnEnd.unsetLen(); - } - } else { - lnEnd.setLen(STLineEndLength.Enum.forInt(style.ooxmlId)); - } - } - - /** - * @return the line end decoration length - */ - public DecorationSize getLineTailLength() { - CTLineProperties ln = getLn(this, false); - - DecorationSize ds = DecorationSize.MEDIUM; - if (ln != null && ln.isSetTailEnd() && ln.getTailEnd().isSetLen()) { - ds = DecorationSize.fromOoxmlId(ln.getTailEnd().getLen().intValue()); - } - return ds; - } - - public boolean isPlaceholder() { - CTPlaceholder ph = getCTPlaceholder(); - return ph != null; - } - - @Override - public Guide getAdjustValue(String name) { - XSLFGeometryProperties gp = XSLFPropertiesDelegate.getGeometryDelegate(getShapeProperties()); - - if (gp != null && gp.isSetPrstGeom() && gp.getPrstGeom().isSetAvLst()) { - for (CTGeomGuide g : gp.getPrstGeom().getAvLst().getGdArray()) { - if (g.getName().equals(name)) { - return new Guide(g.getName(), g.getFmla()); - } - } - } - - return null; - } - - @Override - public LineDecoration getLineDecoration() { - return new LineDecoration() { - @Override - public DecorationShape getHeadShape() { - return getLineHeadDecoration(); - } - - @Override - public DecorationSize getHeadWidth() { - return getLineHeadWidth(); - } - - @Override - public DecorationSize getHeadLength() { - return getLineHeadLength(); - } - - @Override - public DecorationShape getTailShape() { - return getLineTailDecoration(); - } - - @Override - public DecorationSize getTailWidth() { - return getLineTailWidth(); - } - - @Override - public DecorationSize getTailLength() { - return getLineTailLength(); - } - }; - } - - /** - * fetch shape fill as a java.awt.Paint - * - * @return either Color or GradientPaint or TexturePaint or null - */ - @Override - public FillStyle getFillStyle() { - return new FillStyle() { - @Override - public PaintStyle getPaint() { - return XSLFSimpleShape.this.getFillPaint(); - } - }; - } - - @Override - public StrokeStyle getStrokeStyle() { - return new StrokeStyle() { - @Override - public PaintStyle getPaint() { - return XSLFSimpleShape.this.getLinePaint(); - } - - @Override - public LineCap getLineCap() { - return XSLFSimpleShape.this.getLineCap(); - } - - @Override - public LineDash getLineDash() { - return XSLFSimpleShape.this.getLineDash(); - } - - @Override - public double getLineWidth() { - return XSLFSimpleShape.this.getLineWidth(); - } - - @Override - public LineCompound getLineCompound() { - return XSLFSimpleShape.this.getLineCompound(); - } - - }; - } - - @Override - public void setStrokeStyle(Object... styles) { - if (styles.length == 0) { - // remove stroke - setLineColor(null); - return; - } - - // TODO: handle PaintStyle - for (Object st : styles) { - if (st instanceof Number) { - setLineWidth(((Number)st).doubleValue()); - } else if (st instanceof LineCap) { - setLineCap((LineCap)st); - } else if (st instanceof LineDash) { - setLineDash((LineDash)st); - } else if (st instanceof LineCompound) { - setLineCompound((LineCompound)st); - } else if (st instanceof Color) { - setLineColor((Color)st); - } - } - } - - @Override - public void setPlaceholder(Placeholder placeholder) { - super.setPlaceholder(placeholder); - } - - @Override - public XSLFHyperlink getHyperlink() { - CTNonVisualDrawingProps cNvPr = getCNvPr(); - if (!cNvPr.isSetHlinkClick()) { - return null; - } - return new XSLFHyperlink(cNvPr.getHlinkClick(), getSheet()); - } - - @Override - public XSLFHyperlink createHyperlink() { - XSLFHyperlink hl = getHyperlink(); - if (hl == null) { - CTNonVisualDrawingProps cNvPr = getCNvPr(); - hl = new XSLFHyperlink(cNvPr.addNewHlinkClick(), getSheet()); - } - return hl; - } - - private static CTLineProperties getLn(XSLFShape shape, boolean create) { - XmlObject pr = shape.getShapeProperties(); - if (!(pr instanceof CTShapeProperties)) { - LOG.log(POILogger.WARN, shape.getClass().toString()+" doesn't have line properties"); - return null; - } - - CTShapeProperties spr = (CTShapeProperties)pr; - return (spr.isSetLn() || !create) ? spr.getLn() : spr.addNewLn(); - } -} diff --git a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFSlide.java b/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFSlide.java deleted file mode 100644 index dcd964261..000000000 --- a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFSlide.java +++ /dev/null @@ -1,314 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.usermodel; - -import static org.apache.poi.POIXMLTypeLoader.DEFAULT_XML_OPTIONS; - -import java.awt.Graphics2D; -import java.io.IOException; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.sl.draw.DrawFactory; -import org.apache.poi.sl.draw.Drawable; -import org.apache.poi.sl.usermodel.Notes; -import org.apache.poi.sl.usermodel.Placeholder; -import org.apache.poi.sl.usermodel.Slide; -import org.apache.poi.util.Beta; -import org.apache.poi.util.DocumentHelper; -import org.apache.poi.util.NotImplemented; -import org.apache.xmlbeans.XmlException; -import org.openxmlformats.schemas.drawingml.x2006.main.CTGroupShapeProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTGroupTransform2D; -import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPoint2D; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D; -import org.openxmlformats.schemas.presentationml.x2006.main.CTBackground; -import org.openxmlformats.schemas.presentationml.x2006.main.CTCommonSlideData; -import org.openxmlformats.schemas.presentationml.x2006.main.CTGroupShape; -import org.openxmlformats.schemas.presentationml.x2006.main.CTGroupShapeNonVisual; -import org.openxmlformats.schemas.presentationml.x2006.main.CTSlide; -import org.openxmlformats.schemas.presentationml.x2006.main.SldDocument; -import org.w3c.dom.Document; -import org.xml.sax.SAXException; - -@Beta -public final class XSLFSlide extends XSLFSheet -implements Slide { - private final CTSlide _slide; - private XSLFSlideLayout _layout; - private XSLFComments _comments; - private XSLFNotes _notes; - - /** - * Create a new slide - */ - XSLFSlide() { - super(); - _slide = prototype(); - setCommonSlideData(_slide.getCSld()); - } - - /** - * Construct a SpreadsheetML slide from a package part - * - * @param part the package part holding the slide data, - * the content type must be application/vnd.openxmlformats-officedocument.slide+xml - * - * @since POI 3.14-Beta1 - */ - XSLFSlide(PackagePart part) throws IOException, XmlException { - super(part); - - Document _doc; - try { - _doc = DocumentHelper.readDocument(getPackagePart().getInputStream()); - } catch (SAXException e) { - throw new IOException(e); - } - - SldDocument doc = SldDocument.Factory.parse(_doc, DEFAULT_XML_OPTIONS); - _slide = doc.getSld(); - setCommonSlideData(_slide.getCSld()); - } - - private static CTSlide prototype(){ - CTSlide ctSlide = CTSlide.Factory.newInstance(); - CTCommonSlideData cSld = ctSlide.addNewCSld(); - CTGroupShape spTree = cSld.addNewSpTree(); - - CTGroupShapeNonVisual nvGrpSpPr = spTree.addNewNvGrpSpPr(); - CTNonVisualDrawingProps cnvPr = nvGrpSpPr.addNewCNvPr(); - cnvPr.setId(1); - cnvPr.setName(""); - nvGrpSpPr.addNewCNvGrpSpPr(); - nvGrpSpPr.addNewNvPr(); - - CTGroupShapeProperties grpSpr = spTree.addNewGrpSpPr(); - CTGroupTransform2D xfrm = grpSpr.addNewXfrm(); - CTPoint2D off = xfrm.addNewOff(); - off.setX(0); - off.setY(0); - CTPositiveSize2D ext = xfrm.addNewExt(); - ext.setCx(0); - ext.setCy(0); - CTPoint2D choff = xfrm.addNewChOff(); - choff.setX(0); - choff.setY(0); - CTPositiveSize2D chExt = xfrm.addNewChExt(); - chExt.setCx(0); - chExt.setCy(0); - ctSlide.addNewClrMapOvr().addNewMasterClrMapping(); - return ctSlide; - } - - @Override - public CTSlide getXmlObject() { - return _slide; - } - - @Override - protected String getRootElementName(){ - return "sld"; - } - - public XSLFSlideLayout getMasterSheet(){ - return getSlideLayout(); - } - - public XSLFSlideLayout getSlideLayout(){ - if(_layout == null){ - for (POIXMLDocumentPart p : getRelations()) { - if (p instanceof XSLFSlideLayout){ - _layout = (XSLFSlideLayout)p; - } - } - } - if(_layout == null) { - throw new IllegalArgumentException("SlideLayout was not found for " + this.toString()); - } - return _layout; - } - - public XSLFSlideMaster getSlideMaster(){ - return getSlideLayout().getSlideMaster(); - } - - public XSLFComments getComments() { - if(_comments == null) { - for (POIXMLDocumentPart p : getRelations()) { - if (p instanceof XSLFComments) { - _comments = (XSLFComments)p; - } - } - } - if(_comments == null) { - // This slide lacks comments - // Not all have them, sorry... - return null; - } - return _comments; - } - - public XSLFNotes getNotes() { - if(_notes == null) { - for (POIXMLDocumentPart p : getRelations()) { - if (p instanceof XSLFNotes){ - _notes = (XSLFNotes)p; - } - } - } - if(_notes == null) { - // This slide lacks notes - // Not all have them, sorry... - return null; - } - return _notes; - } - - @Override - public String getTitle(){ - XSLFTextShape txt = getTextShapeByType(Placeholder.TITLE); - return txt == null ? null : txt.getText(); - } - - @Override - public XSLFTheme getTheme(){ - return getSlideLayout().getSlideMaster().getTheme(); - } - - /** - * - * @return the information about background appearance of this slide - */ - @Override - public XSLFBackground getBackground() { - CTBackground bg = _slide.getCSld().getBg(); - if(bg != null) { - return new XSLFBackground(bg, this); - } else { - return getMasterSheet().getBackground(); - } - } - - @Override - public boolean getFollowMasterGraphics(){ - return _slide.getShowMasterSp(); - } - - /** - * - * @param value whether shapes on the master slide should be shown or not. - */ - public void setFollowMasterGraphics(boolean value){ - _slide.setShowMasterSp(value); - } - - - public boolean getFollowMasterObjects() { - return getFollowMasterGraphics(); - } - - public void setFollowMasterObjects(boolean follow) { - setFollowMasterGraphics(follow); - } - - @Override - public XSLFSlide importContent(XSLFSheet src){ - super.importContent(src); - if (!(src instanceof XSLFSlide)) { - return this; - } - - // only copy direct backgrounds - not backgrounds of master sheet - CTBackground bgOther = ((XSLFSlide)src)._slide.getCSld().getBg(); - if (bgOther == null) { - return this; - } - - CTBackground bgThis = _slide.getCSld().getBg(); - // remove existing background - if (bgThis != null) { - if (bgThis.isSetBgPr() && bgThis.getBgPr().isSetBlipFill()) { - String oldId = bgThis.getBgPr().getBlipFill().getBlip().getEmbed(); - removeRelation(getRelationById(oldId)); - } - _slide.getCSld().unsetBg(); - } - - bgThis = (CTBackground)_slide.getCSld().addNewBg().set(bgOther); - - if(bgOther.isSetBgPr() && bgOther.getBgPr().isSetBlipFill()){ - String idOther = bgOther.getBgPr().getBlipFill().getBlip().getEmbed(); - String idThis = importBlip(idOther, src.getPackagePart()); - bgThis.getBgPr().getBlipFill().getBlip().setEmbed(idThis); - - } - - return this; - } - - public boolean getFollowMasterBackground() { - return false; - } - - @NotImplemented - public void setFollowMasterBackground(boolean follow) { - // not implemented ... also not in the specs - throw new UnsupportedOperationException(); - } - - public boolean getFollowMasterColourScheme() { - return false; - } - - @NotImplemented - public void setFollowMasterColourScheme(boolean follow) { - // not implemented ... only for OLE objects in the specs - throw new UnsupportedOperationException(); - } - - @Override - @NotImplemented - public void setNotes(Notes notes) { - assert(notes instanceof XSLFNotes); - // TODO Auto-generated method stub - } - - @Override - public int getSlideNumber() { - int idx = getSlideShow().getSlides().indexOf(this); - return (idx == -1) ? idx : idx+1; - } - - /** - * Render this sheet into the supplied graphics object - * - * @param graphics - */ - @Override - public void draw(Graphics2D graphics){ - DrawFactory drawFact = DrawFactory.getInstance(graphics); - Drawable draw = drawFact.getDrawable(this); - draw.draw(graphics); - } - - @Override - public boolean getDisplayPlaceholder(Placeholder placeholder) { - return false; - } -} diff --git a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFSlideLayout.java b/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFSlideLayout.java deleted file mode 100644 index b4e53f4fe..000000000 --- a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFSlideLayout.java +++ /dev/null @@ -1,169 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.usermodel; - -import static org.apache.poi.POIXMLTypeLoader.DEFAULT_XML_OPTIONS; - -import java.io.IOException; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.sl.usermodel.MasterSheet; -import org.apache.poi.sl.usermodel.Placeholder; -import org.apache.poi.util.Beta; -import org.apache.poi.util.Internal; -import org.apache.xmlbeans.XmlException; -import org.openxmlformats.schemas.presentationml.x2006.main.CTBackground; -import org.openxmlformats.schemas.presentationml.x2006.main.CTPlaceholder; -import org.openxmlformats.schemas.presentationml.x2006.main.CTSlideLayout; -import org.openxmlformats.schemas.presentationml.x2006.main.SldLayoutDocument; - -@Beta -public class XSLFSlideLayout extends XSLFSheet -implements MasterSheet { - private CTSlideLayout _layout; - private XSLFSlideMaster _master; - - XSLFSlideLayout() { - super(); - _layout = CTSlideLayout.Factory.newInstance(); - } - - /** - * @since POI 3.14-Beta1 - */ - public XSLFSlideLayout(PackagePart part) throws IOException, XmlException { - super(part); - SldLayoutDocument doc = - SldLayoutDocument.Factory.parse(getPackagePart().getInputStream(), DEFAULT_XML_OPTIONS); - _layout = doc.getSldLayout(); - setCommonSlideData(_layout.getCSld()); - } - - public String getName() { - return _layout.getCSld().getName(); - } - - /** - * While developing only! - */ - @Internal - public CTSlideLayout getXmlObject() { - return _layout; - } - - @Override - protected String getRootElementName() { - return "sldLayout"; - } - - /** - * Slide master object associated with this layout. - * - * @return slide master. Never null. - * @throws IllegalStateException if slide master was not found - */ - public XSLFSlideMaster getSlideMaster() { - if (_master == null) { - for (POIXMLDocumentPart p : getRelations()) { - if (p instanceof XSLFSlideMaster) { - _master = (XSLFSlideMaster) p; - } - } - } - if (_master == null) { - throw new IllegalStateException("SlideMaster was not found for " + this.toString()); - } - return _master; - } - - @Override - public XSLFSlideMaster getMasterSheet() { - return getSlideMaster(); - } - - @Override - public XSLFTheme getTheme() { - return getSlideMaster().getTheme(); - } - - - @Override - public boolean getFollowMasterGraphics() { - return _layout.getShowMasterSp(); - } - - /** - * Render this sheet into the supplied graphics object - */ - @Override - protected boolean canDraw(XSLFShape shape) { - if (shape instanceof XSLFSimpleShape) { - XSLFSimpleShape txt = (XSLFSimpleShape) shape; - CTPlaceholder ph = txt.getCTPlaceholder(); - if (ph != null) { - return false; - } - } - return true; - } - - - @Override - public XSLFBackground getBackground() { - CTBackground bg = _layout.getCSld().getBg(); - if(bg != null) { - return new XSLFBackground(bg, this); - } else { - return getMasterSheet().getBackground(); - } - } - - /** - * Copy placeholders from this layout to the destination slide - * - * @param slide destination slide - */ - public void copyLayout(XSLFSlide slide) { - for (XSLFShape sh : getShapes()) { - if (sh instanceof XSLFTextShape) { - XSLFTextShape tsh = (XSLFTextShape) sh; - Placeholder ph = tsh.getTextType(); - if (ph == null) continue; - - switch (ph) { - // these are special and not copied by default - case DATETIME: - case SLIDE_NUMBER: - case FOOTER: - break; - default: - slide.getSpTree().addNewSp().set(tsh.getXmlObject().copy()); - } - } - } - } - - /** - * - * @return type of this layout - */ - public SlideLayout getType(){ - int ordinal = _layout.getType().intValue() - 1; - return SlideLayout.values()[ordinal]; - } -} \ No newline at end of file diff --git a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFSlideMaster.java b/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFSlideMaster.java deleted file mode 100644 index eefa79e3b..000000000 --- a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFSlideMaster.java +++ /dev/null @@ -1,207 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.usermodel; - -import static org.apache.poi.POIXMLTypeLoader.DEFAULT_XML_OPTIONS; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.sl.usermodel.MasterSheet; -import org.apache.poi.sl.usermodel.Placeholder; -import org.apache.poi.util.Beta; -import org.apache.xmlbeans.XmlException; -import org.openxmlformats.schemas.drawingml.x2006.main.CTColorMapping; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextListStyle; -import org.openxmlformats.schemas.presentationml.x2006.main.CTBackground; -import org.openxmlformats.schemas.presentationml.x2006.main.CTPlaceholder; -import org.openxmlformats.schemas.presentationml.x2006.main.CTSlideMaster; -import org.openxmlformats.schemas.presentationml.x2006.main.CTSlideMasterTextStyles; -import org.openxmlformats.schemas.presentationml.x2006.main.SldMasterDocument; - -/** -* Slide master object associated with this layout. -*

    -* Within a slide master slide are contained all elements -* that describe the objects and their corresponding formatting -* for within a presentation slide. -*

    -*

    -* Within a slide master slide are two main elements. -* The cSld element specifies the common slide elements such as shapes and -* their attached text bodies. Then the txStyles element specifies the -* formatting for the text within each of these shapes. The other properties -* within a slide master slide specify other properties for within a presentation slide -* such as color information, headers and footers, as well as timing and -* transition information for all corresponding presentation slides. -*

    - * - * @author Yegor Kozlov -*/ -@Beta - public class XSLFSlideMaster extends XSLFSheet - implements MasterSheet { - private CTSlideMaster _slide; - private Map _layouts; - private XSLFTheme _theme; - - XSLFSlideMaster() { - super(); - _slide = CTSlideMaster.Factory.newInstance(); - } - - /** - * @since POI 3.14-Beta1 - */ - protected XSLFSlideMaster(PackagePart part) throws IOException, XmlException { - super(part); - SldMasterDocument doc = - SldMasterDocument.Factory.parse(getPackagePart().getInputStream(), DEFAULT_XML_OPTIONS); - _slide = doc.getSldMaster(); - setCommonSlideData(_slide.getCSld()); - } - - @Override - public CTSlideMaster getXmlObject() { - return _slide; - } - - @Override - protected String getRootElementName(){ - return "sldMaster"; - } - - @Override - public XSLFSlideMaster getMasterSheet() { - return null; - } - - private Map getLayouts(){ - if(_layouts == null){ - _layouts = new HashMap(); - for (POIXMLDocumentPart p : getRelations()) { - if (p instanceof XSLFSlideLayout){ - XSLFSlideLayout layout = (XSLFSlideLayout)p; - _layouts.put(layout.getName().toLowerCase(Locale.ROOT), layout); - } - } - } - return _layouts; - } - - /** - * - * @return all slide layouts referencing this master - */ - public XSLFSlideLayout[] getSlideLayouts() { - return getLayouts().values().toArray(new XSLFSlideLayout[_layouts.size()]); - } - - /** - * Get the slide layout by type. - * - * @param type The layout type. Cannot be null. - * - * @return the layout found or null on failure - */ - public XSLFSlideLayout getLayout(SlideLayout type){ - for(XSLFSlideLayout layout : getLayouts().values()){ - if(layout.getType() == type) { - return layout; - } - } - return null; - } - - /** - * Get the slide layout by name. - * - * @param name The layout name (case-insensitive). Cannot be null. - * - * @return the layout found or null on failure - */ - public XSLFSlideLayout getLayout(String name) { - return getLayouts().get(name.toLowerCase(Locale.ROOT)); - } - - - @Override - public XSLFTheme getTheme(){ - if(_theme == null){ - for (POIXMLDocumentPart p : getRelations()) { - if (p instanceof XSLFTheme){ - _theme = (XSLFTheme)p; - CTColorMapping cmap = _slide.getClrMap(); - if(cmap != null){ - _theme.initColorMap(cmap); - } - break; - } - } - } - return _theme; - } - - protected CTTextListStyle getTextProperties(Placeholder textType) { - CTTextListStyle props; - CTSlideMasterTextStyles txStyles = getXmlObject().getTxStyles(); - switch (textType){ - case TITLE: - case CENTERED_TITLE: - case SUBTITLE: - props = txStyles.getTitleStyle(); - break; - case BODY: - props = txStyles.getBodyStyle(); - break; - default: - props = txStyles.getOtherStyle(); - break; - } - return props; - } - - /** - * Render this sheet into the supplied graphics object - * - */ - @Override - protected boolean canDraw(XSLFShape shape){ - if(shape instanceof XSLFSimpleShape){ - XSLFSimpleShape txt = (XSLFSimpleShape)shape; - CTPlaceholder ph = txt.getCTPlaceholder(); - if(ph != null) { - return false; - } - } - return true; - } - - @Override - public XSLFBackground getBackground() { - CTBackground bg = _slide.getCSld().getBg(); - if(bg != null) { - return new XSLFBackground(bg, this); - } else { - return null; - } - } -} diff --git a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFSlideShow.java b/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFSlideShow.java deleted file mode 100644 index 8a49e3943..000000000 --- a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFSlideShow.java +++ /dev/null @@ -1,263 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.usermodel; - -import static org.apache.poi.POIXMLTypeLoader.DEFAULT_XML_OPTIONS; - -import java.io.IOException; -import java.util.LinkedList; -import java.util.List; - -import org.apache.poi.POIXMLDocument; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.exceptions.OpenXML4JException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.opc.PackageRelationship; -import org.apache.poi.openxml4j.opc.PackageRelationshipCollection; -import org.apache.poi.openxml4j.opc.TargetMode; -import org.apache.poi.util.Internal; -import org.apache.xmlbeans.XmlException; -import org.openxmlformats.schemas.presentationml.x2006.main.CTCommentList; -import org.openxmlformats.schemas.presentationml.x2006.main.CTNotesSlide; -import org.openxmlformats.schemas.presentationml.x2006.main.CTPresentation; -import org.openxmlformats.schemas.presentationml.x2006.main.CTSlide; -import org.openxmlformats.schemas.presentationml.x2006.main.CTSlideIdList; -import org.openxmlformats.schemas.presentationml.x2006.main.CTSlideIdListEntry; -import org.openxmlformats.schemas.presentationml.x2006.main.CTSlideMaster; -import org.openxmlformats.schemas.presentationml.x2006.main.CTSlideMasterIdList; -import org.openxmlformats.schemas.presentationml.x2006.main.CTSlideMasterIdListEntry; -import org.openxmlformats.schemas.presentationml.x2006.main.CmLstDocument; -import org.openxmlformats.schemas.presentationml.x2006.main.NotesDocument; -import org.openxmlformats.schemas.presentationml.x2006.main.PresentationDocument; -import org.openxmlformats.schemas.presentationml.x2006.main.SldDocument; -import org.openxmlformats.schemas.presentationml.x2006.main.SldMasterDocument; - -/** - * Experimental class to do low level processing of pptx files. - * - * Most users should use the higher level {@link XMLSlideShow} instead. - * - * If you are using these low level classes, then you - * will almost certainly need to refer to the OOXML - * specifications from - * http://www.ecma-international.org/publications/standards/Ecma-376.htm - * - * WARNING - APIs expected to change rapidly - */ -public class XSLFSlideShow extends POIXMLDocument { - - private PresentationDocument presentationDoc; - /** - * The embedded OLE2 files in the OPC package - */ - private List embedds; - - public XSLFSlideShow(OPCPackage container) throws OpenXML4JException, IOException, XmlException { - super(container); - - if(getCorePart().getContentType().equals(XSLFRelation.THEME_MANAGER.getContentType())) { - rebase(getPackage()); - } - - presentationDoc = - PresentationDocument.Factory.parse(getCorePart().getInputStream(), DEFAULT_XML_OPTIONS); - - embedds = new LinkedList(); - for (CTSlideIdListEntry ctSlide : getSlideReferences().getSldIdArray()) { - PackagePart corePart = getCorePart(); - PackagePart slidePart = corePart.getRelatedPart(corePart.getRelationship(ctSlide.getId2())); - - for(PackageRelationship rel : slidePart.getRelationshipsByType(OLE_OBJECT_REL_TYPE)) { - if (TargetMode.EXTERNAL == rel.getTargetMode()) { - continue; - } - // TODO: Add this reference to each slide as well - embedds.add(slidePart.getRelatedPart(rel)); - } - - for (PackageRelationship rel : slidePart.getRelationshipsByType(PACK_OBJECT_REL_TYPE)) { - embedds.add(slidePart.getRelatedPart(rel)); - } - } - } - public XSLFSlideShow(String file) throws OpenXML4JException, IOException, XmlException { - this(openPackage(file)); - } - - /** - * Returns the low level presentation base object - */ - @Internal - public CTPresentation getPresentation() { - return presentationDoc.getPresentation(); - } - - /** - * Returns the references from the presentation to its - * slides. - * You'll need these to figure out the slide ordering, - * and to get at the actual slides themselves - */ - @Internal - public CTSlideIdList getSlideReferences() { - if(! getPresentation().isSetSldIdLst()) { - getPresentation().setSldIdLst(CTSlideIdList.Factory.newInstance()); - } - return getPresentation().getSldIdLst(); - } - - /** - * Returns the references from the presentation to its - * slide masters. - * You'll need these to get at the actual slide - * masters themselves - */ - @Internal - public CTSlideMasterIdList getSlideMasterReferences() { - return getPresentation().getSldMasterIdLst(); - } - - public PackagePart getSlideMasterPart(CTSlideMasterIdListEntry master) throws IOException, XmlException { - try { - PackagePart corePart = getCorePart(); - return corePart.getRelatedPart( - corePart.getRelationship(master.getId2()) - ); - } catch(InvalidFormatException e) { - throw new XmlException(e); - } - } - /** - * Returns the low level slide master object from - * the supplied slide master reference - */ - @Internal - public CTSlideMaster getSlideMaster(CTSlideMasterIdListEntry master) throws IOException, XmlException { - PackagePart masterPart = getSlideMasterPart(master); - SldMasterDocument masterDoc = - SldMasterDocument.Factory.parse(masterPart.getInputStream(), DEFAULT_XML_OPTIONS); - return masterDoc.getSldMaster(); - } - - public PackagePart getSlidePart(CTSlideIdListEntry slide) throws IOException, XmlException { - try { - PackagePart corePart = getCorePart(); - return corePart.getRelatedPart(corePart.getRelationship(slide.getId2())); - } catch(InvalidFormatException e) { - throw new XmlException(e); - } - } - /** - * Returns the low level slide object from - * the supplied slide reference - */ - @Internal - public CTSlide getSlide(CTSlideIdListEntry slide) throws IOException, XmlException { - PackagePart slidePart = getSlidePart(slide); - SldDocument slideDoc = - SldDocument.Factory.parse(slidePart.getInputStream(), DEFAULT_XML_OPTIONS); - return slideDoc.getSld(); - } - - /** - * Gets the PackagePart of the notes for the - * given slide, or null if there isn't one. - */ - public PackagePart getNodesPart(CTSlideIdListEntry parentSlide) throws IOException, XmlException { - PackageRelationshipCollection notes; - PackagePart slidePart = getSlidePart(parentSlide); - - try { - notes = slidePart.getRelationshipsByType(XSLFRelation.NOTES.getRelation()); - } catch(InvalidFormatException e) { - throw new IllegalStateException(e); - } - - if(notes.size() == 0) { - // No notes for this slide - return null; - } - if(notes.size() > 1) { - throw new IllegalStateException("Expecting 0 or 1 notes for a slide, but found " + notes.size()); - } - - try { - return slidePart.getRelatedPart(notes.getRelationship(0)); - } catch(InvalidFormatException e) { - throw new IllegalStateException(e); - } - } - /** - * Returns the low level notes object for the given - * slide, as found from the supplied slide reference - */ - @Internal - public CTNotesSlide getNotes(CTSlideIdListEntry slide) throws IOException, XmlException { - PackagePart notesPart = getNodesPart(slide); - if(notesPart == null) - return null; - - NotesDocument notesDoc = - NotesDocument.Factory.parse(notesPart.getInputStream(), DEFAULT_XML_OPTIONS); - - return notesDoc.getNotes(); - } - - /** - * Returns all the comments for the given slide - */ - @Internal - public CTCommentList getSlideComments(CTSlideIdListEntry slide) throws IOException, XmlException { - PackageRelationshipCollection commentRels; - PackagePart slidePart = getSlidePart(slide); - - try { - commentRels = slidePart.getRelationshipsByType(XSLFRelation.COMMENTS.getRelation()); - } catch(InvalidFormatException e) { - throw new IllegalStateException(e); - } - - if(commentRels.size() == 0) { - // No comments for this slide - return null; - } - if(commentRels.size() > 1) { - throw new IllegalStateException("Expecting 0 or 1 comments for a slide, but found " + commentRels.size()); - } - - try { - PackagePart cPart = slidePart.getRelatedPart( - commentRels.getRelationship(0) - ); - CmLstDocument commDoc = - CmLstDocument.Factory.parse(cPart.getInputStream(), DEFAULT_XML_OPTIONS); - return commDoc.getCmLst(); - } catch(InvalidFormatException e) { - throw new IllegalStateException(e); - } - } - - /** - * Get the document's embedded files. - */ - @Override - public List getAllEmbedds() throws OpenXML4JException { - return embedds; - } - -} diff --git a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFSlideShowFactory.java b/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFSlideShowFactory.java deleted file mode 100644 index 71378e70e..000000000 --- a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFSlideShowFactory.java +++ /dev/null @@ -1,100 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xslf.usermodel; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.EncryptedDocumentException; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackageAccess; -import org.apache.poi.sl.usermodel.SlideShow; -import org.apache.poi.sl.usermodel.SlideShowFactory; -import org.apache.poi.util.Internal; - -@Internal -public class XSLFSlideShowFactory extends SlideShowFactory { - - /** - * Creates a XMLSlideShow from the given OOXML Package - * - *

    Note that in order to properly release resources the - * SlideShow should be closed after use.

    - * - * @param pkg The {@link OPCPackage} opened for reading data. - * - * @return The created SlideShow - * - * @throws IOException if an error occurs while reading the data - * @throws InvalidFormatException - */ - public static SlideShow createSlideShow(OPCPackage pkg) throws IOException { - try { - return new XMLSlideShow(pkg); - } catch (IllegalArgumentException ioe) { - // ensure that file handles are closed (use revert() to not re-write the file) - pkg.revert(); - //pkg.close(); - - // rethrow exception - throw ioe; - } - } - - /** - * Creates the XMLSlideShow from the given File, which must exist and be readable. - *

    Note that in order to properly release resources theSlideShow should be closed after use. - * - * @param file The file to read data from. - * @param readOnly If the SlideShow should be opened in read-only mode to avoid writing back - * changes when the document is closed. - * - * @return The created SlideShow - * - * @throws IOException if an error occurs while reading the data - * @throws EncryptedDocumentException If the wrong password is given for a protected file - */ - @SuppressWarnings("resource") - public static SlideShow createSlideShow(File file, boolean readOnly) - throws IOException, InvalidFormatException { - OPCPackage pkg = OPCPackage.open(file, readOnly ? PackageAccess.READ : PackageAccess.READ_WRITE); - return createSlideShow(pkg); - } - - /** - * Creates a XMLSlideShow from the given InputStream - * - *

    Note that in order to properly release resources the - * SlideShow should be closed after use.

    - * - * @param stream The {@link InputStream} to read data from. - * - * @return The created SlideShow - * - * @throws IOException if an error occurs while reading the data - * @throws InvalidFormatException - */ - @SuppressWarnings("resource") - public static SlideShow createSlideShow(InputStream stream) throws IOException, InvalidFormatException { - OPCPackage pkg = OPCPackage.open(stream); - return createSlideShow(pkg); - } - -} diff --git a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFTable.java b/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFTable.java deleted file mode 100644 index 484fa5f66..000000000 --- a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFTable.java +++ /dev/null @@ -1,350 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xslf.usermodel; - -import java.awt.geom.Rectangle2D; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; - -import javax.xml.namespace.QName; - -import org.apache.poi.sl.draw.DrawFactory; -import org.apache.poi.sl.draw.DrawTableShape; -import org.apache.poi.sl.draw.DrawTextShape; -import org.apache.poi.sl.usermodel.TableShape; -import org.apache.poi.util.Internal; -import org.apache.poi.util.Units; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.impl.values.XmlAnyTypeImpl; -import org.openxmlformats.schemas.drawingml.x2006.main.CTGraphicalObjectData; -import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTable; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTableRow; -import org.openxmlformats.schemas.presentationml.x2006.main.CTGraphicalObjectFrame; -import org.openxmlformats.schemas.presentationml.x2006.main.CTGraphicalObjectFrameNonVisual; - -/** - * Represents a table in a .pptx presentation - */ -public class XSLFTable extends XSLFGraphicFrame implements Iterable, - TableShape { - /* package */ static final String TABLE_URI = "http://schemas.openxmlformats.org/drawingml/2006/table"; - /* package */ static final String DRAWINGML_URI = "http://schemas.openxmlformats.org/drawingml/2006/main"; - - private CTTable _table; - private List _rows; - - /*package*/ XSLFTable(CTGraphicalObjectFrame shape, XSLFSheet sheet){ - super(shape, sheet); - - CTGraphicalObjectData god = shape.getGraphic().getGraphicData(); - XmlCursor xc = god.newCursor(); - if (!xc.toChild(DRAWINGML_URI, "tbl")) { - throw new IllegalStateException("a:tbl element was not found in\n " + god); - } - - XmlObject xo = xc.getObject(); - // Pesky XmlBeans bug - see Bugzilla #49934 - // it never happens when using the full ooxml-schemas jar but may happen with the abridged poi-ooxml-schemas - if (xo instanceof XmlAnyTypeImpl){ - String errStr = - "Schemas (*.xsb) for CTTable can't be loaded - usually this happens when OSGI " + - "loading is used and the thread context classloader has no reference to " + - "the xmlbeans classes - use POIXMLTypeLoader.setClassLoader() to set the loader, " + - "e.g. with CTTable.class.getClassLoader()" - ; - throw new IllegalStateException(errStr); - } - _table = (CTTable)xo; - xc.dispose(); - - _rows = new ArrayList(_table.sizeOfTrArray()); - for(CTTableRow row : _table.getTrArray()) { - _rows.add(new XSLFTableRow(row, this)); - } - updateRowColIndexes(); - } - - @Override - public XSLFTableCell getCell(int row, int col) { - List rows = getRows(); - if (row < 0 || rows.size() <= row) { - return null; - } - XSLFTableRow r = rows.get(row); - if (r == null) { - // empty row - return null; - } - List cells = r.getCells(); - if (col < 0 || cells.size() <= col) { - return null; - } - // cell can be potentially empty ... - return cells.get(col); - } - - @Internal - public CTTable getCTTable(){ - return _table; - } - - @Override - public int getNumberOfColumns() { - return _table.getTblGrid().sizeOfGridColArray(); - } - - @Override - public int getNumberOfRows() { - return _table.sizeOfTrArray(); - } - - @Override - public double getColumnWidth(int idx){ - return Units.toPoints( - _table.getTblGrid().getGridColArray(idx).getW()); - } - - @Override - public void setColumnWidth(int idx, double width) { - _table.getTblGrid().getGridColArray(idx).setW(Units.toEMU(width)); - } - - @Override - public double getRowHeight(int row) { - return Units.toPoints(_table.getTrArray(row).getH()); - } - - @Override - public void setRowHeight(int row, double height) { - _table.getTrArray(row).setH(Units.toEMU(height)); - } - - public Iterator iterator(){ - return _rows.iterator(); - } - - public List getRows(){ - return Collections.unmodifiableList(_rows); - } - - public XSLFTableRow addRow(){ - CTTableRow tr = _table.addNewTr(); - XSLFTableRow row = new XSLFTableRow(tr, this); - // default height is 20 points - row.setHeight(20.0); - _rows.add(row); - updateRowColIndexes(); - return row; - } - - static CTGraphicalObjectFrame prototype(int shapeId){ - CTGraphicalObjectFrame frame = CTGraphicalObjectFrame.Factory.newInstance(); - CTGraphicalObjectFrameNonVisual nvGr = frame.addNewNvGraphicFramePr(); - - CTNonVisualDrawingProps cnv = nvGr.addNewCNvPr(); - cnv.setName("Table " + shapeId); - cnv.setId(shapeId + 1); - nvGr.addNewCNvGraphicFramePr().addNewGraphicFrameLocks().setNoGrp(true); - nvGr.addNewNvPr(); - - frame.addNewXfrm(); - CTGraphicalObjectData gr = frame.addNewGraphic().addNewGraphicData(); - XmlCursor grCur = gr.newCursor(); - grCur.toNextToken(); - grCur.beginElement(new QName(DRAWINGML_URI, "tbl")); - - CTTable tbl = CTTable.Factory.newInstance(); - tbl.addNewTblPr(); - tbl.addNewTblGrid(); - XmlCursor tblCur = tbl.newCursor(); - - tblCur.moveXmlContents(grCur); - tblCur.dispose(); - grCur.dispose(); - gr.setUri(TABLE_URI); - return frame; - } - - /** - * Merge cells of a table - */ - public void mergeCells(int firstRow, int lastRow, int firstCol, int lastCol) { - - if(firstRow > lastRow) { - throw new IllegalArgumentException( - "Cannot merge, first row > last row : " - + firstRow + " > " + lastRow - ); - } - - if(firstCol > lastCol) { - throw new IllegalArgumentException( - "Cannot merge, first column > last column : " - + firstCol + " > " + lastCol - ); - } - - int rowSpan = (lastRow - firstRow) + 1; - boolean mergeRowRequired = rowSpan > 1; - - int colSpan = (lastCol - firstCol) + 1; - boolean mergeColumnRequired = colSpan > 1; - - for(int i = firstRow; i <= lastRow; i++) { - - XSLFTableRow row = _rows.get(i); - - for(int colPos = firstCol; colPos <= lastCol; colPos++) { - - XSLFTableCell cell = row.getCells().get(colPos); - - if(mergeRowRequired) { - if(i == firstRow) { - cell.setRowSpan(rowSpan); - } else { - cell.setVMerge(true); - } - } - if(mergeColumnRequired) { - if(colPos == firstCol) { - cell.setGridSpan(colSpan); - } else { - cell.setHMerge(true); - } - } - } - } - } - - /** - * Get assigned TableStyle - * - * @return the assigned TableStyle - * - * @since POI 3.15-beta2 - */ - protected XSLFTableStyle getTableStyle() { - CTTable tab = getCTTable(); - // TODO: support inline table style - if (!tab.isSetTblPr() || !tab.getTblPr().isSetTableStyleId()) { - return null; - } - - String styleId = tab.getTblPr().getTableStyleId(); - XSLFTableStyles styles = getSheet().getSlideShow().getTableStyles(); - for (XSLFTableStyle style : styles.getStyles()) { - if (style.getStyleId().equals(styleId)) { - return style; - } - } - return null; - } - - /* package */ void updateRowColIndexes() { - int rowIdx = 0; - for (XSLFTableRow xr : this) { - int colIdx = 0; - for (XSLFTableCell tc : xr) { - tc.setRowColIndex(rowIdx, colIdx); - colIdx++; - } - rowIdx++; - } - } - - /* package */ void updateCellAnchor() { - int rows = getNumberOfRows(); - int cols = getNumberOfColumns(); - - double colWidths[] = new double[cols]; - double rowHeights[] = new double[rows]; - - for (int row=0; row { - private CTTableCellProperties _tcPr = null; - private final XSLFTable table; - private int row = 0, col = 0; - - /** - * Volatile/temporary anchor - e.g. for rendering - */ - private Rectangle2D anchor = null; - - /*package*/ XSLFTableCell(CTTableCell cell, XSLFTable table){ - super(cell, table.getSheet()); - this.table = table; - } - - @Override - protected CTTextBody getTextBody(boolean create){ - CTTableCell cell = getCell(); - CTTextBody txBody = cell.getTxBody(); - if (txBody == null && create) { - txBody = cell.addNewTxBody(); - XSLFAutoShape.initTextBody(txBody); - } - return txBody; - } - - static CTTableCell prototype() { - CTTableCell cell = CTTableCell.Factory.newInstance(); - CTTableCellProperties pr = cell.addNewTcPr(); - pr.addNewLnL().addNewNoFill(); - pr.addNewLnR().addNewNoFill(); - pr.addNewLnT().addNewNoFill(); - pr.addNewLnB().addNewNoFill(); - return cell; - } - - protected CTTableCellProperties getCellProperties(boolean create) { - if (_tcPr == null) { - CTTableCell cell = getCell(); - _tcPr = cell.getTcPr(); - if (_tcPr == null && create) { - _tcPr = cell.addNewTcPr(); - } - } - return _tcPr; - } - - @Override - public void setLeftInset(double margin){ - CTTableCellProperties pr = getCellProperties(true); - pr.setMarL(Units.toEMU(margin)); - } - - @Override - public void setRightInset(double margin){ - CTTableCellProperties pr = getCellProperties(true); - pr.setMarR(Units.toEMU(margin)); - } - - @Override - public void setTopInset(double margin){ - CTTableCellProperties pr = getCellProperties(true); - pr.setMarT(Units.toEMU(margin)); - } - - @Override - public void setBottomInset(double margin){ - CTTableCellProperties pr = getCellProperties(true); - pr.setMarB(Units.toEMU(margin)); - } - - private CTLineProperties getCTLine(BorderEdge edge, boolean create) { - if (edge == null) { - throw new IllegalArgumentException("BorderEdge needs to be specified."); - } - - CTTableCellProperties pr = getCellProperties(create); - if (pr == null) { - return null; - } - - switch (edge) { - case bottom: - return (pr.isSetLnB()) ? pr.getLnB() : (create ? pr.addNewLnB() : null); - case left: - return (pr.isSetLnL()) ? pr.getLnL() : (create ? pr.addNewLnL() : null); - case top: - return (pr.isSetLnT()) ? pr.getLnT() : (create ? pr.addNewLnT() : null); - case right: - return (pr.isSetLnR()) ? pr.getLnR() : (create ? pr.addNewLnR() : null); - default: - return null; - } - } - - @Override - public void removeBorder(BorderEdge edge) { - CTTableCellProperties pr = getCellProperties(false); - if (pr == null) { - return; - } - switch (edge) { - case bottom: - if (pr.isSetLnB()) { - pr.unsetLnB(); - } - break; - case left: - if (pr.isSetLnL()) { - pr.unsetLnL(); - } - break; - case top: - if (pr.isSetLnT()) { - pr.unsetLnT(); - } - break; - case right: - if (pr.isSetLnR()) { - pr.unsetLnB(); - } - break; - default: - throw new IllegalArgumentException(); - } - } - - @Override - public StrokeStyle getBorderStyle(final BorderEdge edge) { - final Double width = getBorderWidth(edge); - return (width == null) ? null : new StrokeStyle() { - @Override - public PaintStyle getPaint() { - return DrawPaint.createSolidPaint(getBorderColor(edge)); - } - - @Override - public LineCap getLineCap() { - return getBorderCap(edge); - } - - @Override - public LineDash getLineDash() { - return getBorderDash(edge); - } - - @Override - public LineCompound getLineCompound() { - return getBorderCompound(edge); - } - - @Override - public double getLineWidth() { - return width; - } - }; - } - - @Override - public void setBorderStyle(BorderEdge edge, StrokeStyle style) { - if (style == null) { - throw new IllegalArgumentException("StrokeStyle needs to be specified."); - } - - LineCap cap = style.getLineCap(); - if (cap != null) { - setBorderCap(edge, cap); - } - - LineCompound compound = style.getLineCompound(); - if (compound != null) { - setBorderCompound(edge, compound); - } - - LineDash dash = style.getLineDash(); - if (dash != null) { - setBorderDash(edge, dash); - } - - double width = style.getLineWidth(); - setBorderWidth(edge, width); - } - - public Double getBorderWidth(BorderEdge edge) { - CTLineProperties ln = getCTLine(edge, false); - return (ln == null || !ln.isSetW()) ? null : Units.toPoints(ln.getW()); - } - - @Override - public void setBorderWidth(BorderEdge edge, double width) { - CTLineProperties ln = getCTLine(edge, true); - ln.setW(Units.toEMU(width)); - } - - private CTLineProperties setBorderDefaults(BorderEdge edge) { - CTLineProperties ln = getCTLine(edge, true); - if (ln.isSetNoFill()) { - ln.unsetNoFill(); - } - - if(!ln.isSetPrstDash()) { - ln.addNewPrstDash().setVal(STPresetLineDashVal.SOLID); - } - if (!ln.isSetCmpd()) { - ln.setCmpd(STCompoundLine.SNG); - } - if (!ln.isSetAlgn()) { - ln.setAlgn(STPenAlignment.CTR); - } - if (!ln.isSetCap()) { - ln.setCap(STLineCap.FLAT); - } - if (!ln.isSetRound()) { - ln.addNewRound(); - } - - if (!ln.isSetHeadEnd()) { - CTLineEndProperties hd = ln.addNewHeadEnd(); - hd.setType(STLineEndType.NONE); - hd.setW(STLineEndWidth.MED); - hd.setLen(STLineEndLength.MED); - } - - if (!ln.isSetTailEnd()) { - CTLineEndProperties tl = ln.addNewTailEnd(); - tl.setType(STLineEndType.NONE); - tl.setW(STLineEndWidth.MED); - tl.setLen(STLineEndLength.MED); - } - - return ln; - } - - @Override - public void setBorderColor(BorderEdge edge, Color color) { - if (color == null) { - throw new IllegalArgumentException("Colors need to be specified."); - } - - CTLineProperties ln = setBorderDefaults(edge); - CTSolidColorFillProperties fill = ln.addNewSolidFill(); - XSLFColor c = new XSLFColor(fill, getSheet().getTheme(), fill.getSchemeClr()); - c.setColor(color); - } - - public Color getBorderColor(BorderEdge edge) { - CTLineProperties ln = getCTLine(edge, false); - if (ln == null || ln.isSetNoFill() || !ln.isSetSolidFill()) { - return null; - } - - CTSolidColorFillProperties fill = ln.getSolidFill(); - XSLFColor c = new XSLFColor(fill, getSheet().getTheme(), fill.getSchemeClr()); - return c.getColor(); - } - - public LineCompound getBorderCompound(BorderEdge edge) { - CTLineProperties ln = getCTLine(edge, false); - if (ln == null || ln.isSetNoFill() || !ln.isSetSolidFill() || !ln.isSetCmpd()) { - return null; - } - - return LineCompound.fromOoxmlId(ln.getCmpd().intValue()); - } - - @Override - public void setBorderCompound(BorderEdge edge, LineCompound compound) { - if (compound == null) { - throw new IllegalArgumentException("LineCompound need to be specified."); - } - - CTLineProperties ln = setBorderDefaults(edge); - ln.setCmpd(STCompoundLine.Enum.forInt(compound.ooxmlId)); - } - - public LineDash getBorderDash(BorderEdge edge) { - CTLineProperties ln = getCTLine(edge, false); - if (ln == null || ln.isSetNoFill() || !ln.isSetSolidFill() || !ln.isSetPrstDash()) { - return null; - } - - return LineDash.fromOoxmlId(ln.getPrstDash().getVal().intValue()); - } - - @Override - public void setBorderDash(BorderEdge edge, LineDash dash) { - if (dash == null) { - throw new IllegalArgumentException("LineDash need to be specified."); - } - - CTLineProperties ln = setBorderDefaults(edge); - ln.getPrstDash().setVal(STPresetLineDashVal.Enum.forInt(dash.ooxmlId)); - } - - public LineCap getBorderCap(BorderEdge edge) { - CTLineProperties ln = getCTLine(edge, false); - if (ln == null || ln.isSetNoFill() || !ln.isSetSolidFill() || !ln.isSetCap()) { - return null; - } - - return LineCap.fromOoxmlId(ln.getCap().intValue()); - } - - public void setBorderCap(BorderEdge edge, LineCap cap) { - if (cap == null) { - throw new IllegalArgumentException("LineCap need to be specified."); - } - - CTLineProperties ln = setBorderDefaults(edge); - ln.setCap(STLineCap.Enum.forInt(cap.ooxmlId)); - } - - - - /** - * Specifies a solid color fill. The shape is filled entirely with the specified color. - * - * @param color the solid color fill. - * The value of null unsets the solidFIll attribute from the underlying xml - */ - @Override - public void setFillColor(Color color) { - CTTableCellProperties spPr = getCellProperties(true); - if (color == null) { - if(spPr.isSetSolidFill()) { - spPr.unsetSolidFill(); - } - } else { - CTSolidColorFillProperties fill = spPr.isSetSolidFill() ? spPr.getSolidFill() : spPr.addNewSolidFill(); - XSLFColor c = new XSLFColor(fill, getSheet().getTheme(), fill.getSchemeClr()); - c.setColor(color); - } - } - - /** - * - * @return solid fill color of null if not set - */ - @Override - public Color getFillColor(){ - PaintStyle ps = getFillPaint(); - if (ps instanceof SolidPaint) { - ColorStyle cs = ((SolidPaint)ps).getSolidColor(); - return DrawPaint.applyColorTransform(cs); - } - - return null; - } - - @SuppressWarnings("resource") - @Override - public PaintStyle getFillPaint() { - XSLFSheet sheet = getSheet(); - XSLFTheme theme = sheet.getTheme(); - final boolean hasPlaceholder = getPlaceholder() != null; - XmlObject props = getCellProperties(false); - XSLFFillProperties fp = XSLFPropertiesDelegate.getFillDelegate(props); - if (fp != null) { - PaintStyle paint = selectPaint(fp, null, sheet.getPackagePart(), theme, hasPlaceholder); - if (paint != null) { - return paint; - } - } - - CTTablePartStyle tps = getTablePartStyle(null); - if (tps == null || !tps.isSetTcStyle()) { - tps = getTablePartStyle(TablePartStyle.wholeTbl); - if (tps == null || !tps.isSetTcStyle()) { - return null; - } - } - - XMLSlideShow slideShow = sheet.getSlideShow(); - CTTableStyleCellStyle tcStyle = tps.getTcStyle(); - if (tcStyle.isSetFill()) { - props = tcStyle.getFill(); - } else if (tcStyle.isSetFillRef()) { - props = tcStyle.getFillRef(); - } else { - return null; - } - - fp = XSLFPropertiesDelegate.getFillDelegate(props); - if (fp != null) { - PaintStyle paint = XSLFShape.selectPaint(fp, null, slideShow.getPackagePart(), theme, hasPlaceholder); - if (paint != null) { - return paint; - } - } - - return null; - } - - /** - * Retrieves the part style depending on the location of this cell - * - * @param tablePartStyle the part to be returned, usually this is null - * and only set when used as a helper method - * @return the table part style - */ - private CTTablePartStyle getTablePartStyle(TablePartStyle tablePartStyle) { - CTTable ct = table.getCTTable(); - if (!ct.isSetTblPr()) { - return null; - } - - CTTableProperties pr = ct.getTblPr(); - boolean bandRow = (pr.isSetBandRow() && pr.getBandRow()); - boolean firstRow = (pr.isSetFirstRow() && pr.getFirstRow()); - boolean lastRow = (pr.isSetLastRow() && pr.getLastRow()); - boolean bandCol = (pr.isSetBandCol() && pr.getBandCol()); - boolean firstCol = (pr.isSetFirstCol() && pr.getFirstCol()); - boolean lastCol = (pr.isSetLastCol() && pr.getLastCol()); - - TablePartStyle tps; - if (tablePartStyle != null) { - tps = tablePartStyle; - } else if (row == 0 && firstRow) { - tps = TablePartStyle.firstRow; - } else if (row == table.getNumberOfRows()-1 && lastRow) { - tps = TablePartStyle.lastRow; - } else if (col == 0 && firstCol) { - tps = TablePartStyle.firstCol; - } else if (col == table.getNumberOfColumns()-1 && lastCol) { - tps = TablePartStyle.lastCol; - } else { - tps = TablePartStyle.wholeTbl; - - int br = row + (firstRow ? 1 : 0); - int bc = col + (firstCol ? 1 : 0); - if (bandRow && (br & 1) == 0) { - tps = TablePartStyle.band1H; - } else if (bandCol && (bc & 1) == 0) { - tps = TablePartStyle.band1V; - } - } - - XSLFTableStyle tabStyle = table.getTableStyle(); - if (tabStyle == null) { - return null; - } - - CTTablePartStyle part = tabStyle.getTablePartStyle(tps); - return (part == null) ? tabStyle.getTablePartStyle(TablePartStyle.wholeTbl) : part; - } - - void setGridSpan(int gridSpan_) { - getCell().setGridSpan(gridSpan_); - } - - @Override - public int getGridSpan() { - CTTableCell c = getCell(); - return (c.isSetGridSpan()) ? c.getGridSpan() : 1; - } - - void setRowSpan(int rowSpan_) { - getCell().setRowSpan(rowSpan_); - } - - @Override - public int getRowSpan() { - CTTableCell c = getCell(); - return (c.isSetRowSpan()) ? c.getRowSpan() : 1; - } - - void setHMerge(boolean merge_) { - getCell().setHMerge(merge_); - } - - void setVMerge(boolean merge_) { - getCell().setVMerge(merge_); - } - - @Override - public void setVerticalAlignment(VerticalAlignment anchor){ - CTTableCellProperties cellProps = getCellProperties(true); - if(anchor == null) { - if(cellProps.isSetAnchor()) { - cellProps.unsetAnchor(); - } - } else { - cellProps.setAnchor(STTextAnchoringType.Enum.forInt(anchor.ordinal() + 1)); - } - } - - @Override - public VerticalAlignment getVerticalAlignment(){ - CTTableCellProperties cellProps = getCellProperties(false); - - VerticalAlignment align = VerticalAlignment.TOP; - if(cellProps != null && cellProps.isSetAnchor()) { - int ival = cellProps.getAnchor().intValue(); - align = VerticalAlignment.values()[ival - 1]; - } - return align; - } - - /** - * @since POI 3.15-beta2 - */ - @Override - public void setTextDirection(TextDirection orientation) { - CTTableCellProperties cellProps = getCellProperties(true); - if(orientation == null) { - if (cellProps.isSetVert()) { - cellProps.unsetVert(); - } - } else { - STTextVerticalType.Enum vt; - switch (orientation) { - default: - case HORIZONTAL: - vt = STTextVerticalType.HORZ; - break; - case VERTICAL: - vt = STTextVerticalType.VERT; - break; - case VERTICAL_270: - vt = STTextVerticalType.VERT_270; - break; - case STACKED: - vt = STTextVerticalType.WORD_ART_VERT; - break; - } - - cellProps.setVert(vt); - } - } - - /** - * @since POI 3.15-beta2 - */ - @Override - public TextDirection getTextDirection() { - CTTableCellProperties cellProps = getCellProperties(false); - - STTextVerticalType.Enum orientation; - if (cellProps != null && cellProps.isSetVert()) { - orientation = cellProps.getVert(); - } else { - orientation = STTextVerticalType.HORZ; - } - - switch (orientation.intValue()) { - default: - case STTextVerticalType.INT_HORZ: - return TextDirection.HORIZONTAL; - case STTextVerticalType.INT_VERT: - case STTextVerticalType.INT_EA_VERT: - case STTextVerticalType.INT_MONGOLIAN_VERT: - return TextDirection.VERTICAL; - case STTextVerticalType.INT_VERT_270: - return TextDirection.VERTICAL_270; - case STTextVerticalType.INT_WORD_ART_VERT: - case STTextVerticalType.INT_WORD_ART_VERT_RTL: - return TextDirection.STACKED; - } - } - - private CTTableCell getCell() { - return (CTTableCell)getXmlObject(); - } - - /* package */ void setRowColIndex(int row, int col) { - this.row = row; - this.col = col; - } - - /** - * Return a fake-xfrm which is used for calculating the text height - */ - protected CTTransform2D getXfrm() { - Rectangle2D anc = getAnchor(); - CTTransform2D xfrm = CTTransform2D.Factory.newInstance(); - CTPoint2D off = xfrm.addNewOff(); - off.setX(Units.toEMU(anc.getX())); - off.setY(Units.toEMU(anc.getY())); - CTPositiveSize2D size = xfrm.addNewExt(); - size.setCx(Units.toEMU(anc.getWidth())); - size.setCy(Units.toEMU(anc.getHeight())); - return xfrm; - } - - /** - * There's no real anchor for table cells - this method is used to temporarily store the location - * of the cell for a later retrieval, e.g. for rendering - * - * @since POI 3.15-beta2 - */ - @Override - public void setAnchor(Rectangle2D anchor) { - if (this.anchor == null) { - this.anchor = (Rectangle2D)anchor.clone(); - } else { - this.anchor.setRect(anchor); - } - } - - /** - * @since POI 3.15-beta2 - */ - @Override - public Rectangle2D getAnchor() { - if (anchor == null) { - table.updateCellAnchor(); - } - // anchor should be set, after updateCellAnchor is through - assert(anchor != null); - return anchor; - } - - /** - * @since POI 3.15-beta2 - */ - @Override - public boolean isMerged() { - CTTableCell c = getCell(); - return (c.isSetHMerge() && c.getHMerge()) || (c.isSetVMerge() && c.getVMerge()); - } - - /** - * @since POI 3.15-beta2 - */ - @Override - protected XSLFCellTextParagraph newTextParagraph(CTTextParagraph p) { - return new XSLFCellTextParagraph(p, this); - } - - @Override - protected XmlObject getShapeProperties() { - return getCellProperties(false); - } - - /** - * @since POI 3.15-beta2 - */ - private class XSLFCellTextParagraph extends XSLFTextParagraph { - protected XSLFCellTextParagraph(CTTextParagraph p, XSLFTextShape shape) { - super(p, shape); - } - - @Override - protected XSLFCellTextRun newTextRun(CTRegularTextRun r) { - return new XSLFCellTextRun(r, this); - } - } - - /** - * @since POI 3.15-beta2 - */ - private class XSLFCellTextRun extends XSLFTextRun { - protected XSLFCellTextRun(CTRegularTextRun r, XSLFTextParagraph p) { - super(r, p); - } - - @Override - public PaintStyle getFontColor(){ - CTTableStyleTextStyle txStyle = getTextStyle(); - if (txStyle == null) { - return super.getFontColor(); - } - - CTSchemeColor phClr = null; - CTFontReference fontRef = txStyle.getFontRef(); - if (fontRef != null) { - phClr = fontRef.getSchemeClr(); - } - - XSLFTheme theme = getSheet().getTheme(); - final XSLFColor c = new XSLFColor(txStyle, theme, phClr); - return DrawPaint.createSolidPaint(c.getColorStyle()); - } - - @Override - public boolean isBold() { - CTTableStyleTextStyle txStyle = getTextStyle(); - if (txStyle == null) { - return super.isBold(); - } else { - return txStyle.isSetB() && txStyle.getB().intValue() == STOnOffStyleType.INT_ON; - } - } - - @Override - public boolean isItalic() { - CTTableStyleTextStyle txStyle = getTextStyle(); - if (txStyle == null) { - return super.isItalic(); - } else { - return txStyle.isSetI() && txStyle.getI().intValue() == STOnOffStyleType.INT_ON; - } - } - - private CTTableStyleTextStyle getTextStyle() { - CTTablePartStyle tps = getTablePartStyle(null); - if (tps == null || !tps.isSetTcTxStyle()) { - tps = getTablePartStyle(TablePartStyle.wholeTbl); - } - return (tps == null) ? null : tps.getTcTxStyle(); - } - } -} diff --git a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFTableRow.java b/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFTableRow.java deleted file mode 100644 index a49d5a924..000000000 --- a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFTableRow.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xslf.usermodel; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; - -import org.apache.poi.util.Units; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTableCell; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTableRow; - -/** - * Represents a table in a .pptx presentation - */ -public class XSLFTableRow implements Iterable { - private final CTTableRow _row; - private final List _cells; - private final XSLFTable _table; - - /*package*/ XSLFTableRow(CTTableRow row, XSLFTable table){ - _row = row; - _table = table; - CTTableCell[] tcArray = _row.getTcArray(); - _cells = new ArrayList(tcArray.length); - for(CTTableCell cell : tcArray) { - _cells.add(new XSLFTableCell(cell, table)); - } - } - - public CTTableRow getXmlObject(){ - return _row; - } - - public Iterator iterator(){ - return _cells.iterator(); - } - - public List getCells(){ - return Collections.unmodifiableList(_cells); - } - - public double getHeight(){ - return Units.toPoints(_row.getH()); - } - - public void setHeight(double height){ - _row.setH(Units.toEMU(height)); - } - - public XSLFTableCell addCell(){ - CTTableCell c = _row.addNewTc(); - c.set(XSLFTableCell.prototype()); - XSLFTableCell cell = new XSLFTableCell(c, _table); - _cells.add(cell); - - if(_table.getNumberOfColumns() < _row.sizeOfTcArray()) { - _table.getCTTable().getTblGrid().addNewGridCol().setW(Units.toEMU(100.0)); - } - _table.updateRowColIndexes(); - return cell; - } - - /** - * Merge cells of a table row, inclusive. - * Indices are 0-based. - * - * @param firstCol 0-based index of first column to merge, inclusive - * @param lastCol 0-based index of last column to merge, inclusive - */ - public void mergeCells(int firstCol, int lastCol) - { - if (firstCol >= lastCol) { - throw new IllegalArgumentException( - "Cannot merge, first column >= last column : " - + firstCol + " >= " + lastCol - ); - } - - final int colSpan = (lastCol - firstCol) + 1; - - _cells.get(firstCol).setGridSpan(colSpan); - for (final XSLFTableCell cell : _cells.subList(firstCol+1, lastCol+1)) { - cell.setHMerge(true); - } - } - -} diff --git a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFTableStyle.java b/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFTableStyle.java deleted file mode 100644 index b821910ea..000000000 --- a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFTableStyle.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xslf.usermodel; - -import org.openxmlformats.schemas.drawingml.x2006.main.CTTablePartStyle; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTableStyle; - -/** - * Represents a table style in a .pptx presentation - */ -public class XSLFTableStyle { - private CTTableStyle _tblStyle; - - public enum TablePartStyle { - wholeTbl, band1H, band2H, band1V, band2V, firstCol, lastCol, firstRow, lastRow, seCell, swCell, neCell, nwCell; - } - - /*package*/ XSLFTableStyle(CTTableStyle style){ - _tblStyle = style; - } - - public CTTableStyle getXmlObject(){ - return _tblStyle; - } - - public String getStyleName(){ - return _tblStyle.getStyleName(); - } - - public String getStyleId(){ - return _tblStyle.getStyleId(); - } - - /** - * @since POI 3.15-beta2 - */ - protected CTTablePartStyle getTablePartStyle(TablePartStyle tps) { - switch (tps) { - default: - case wholeTbl: - return _tblStyle.getWholeTbl(); - case band1H: - return _tblStyle.getBand1H(); - case band2H: - return _tblStyle.getBand2H(); - case band1V: - return _tblStyle.getBand1V(); - case band2V: - return _tblStyle.getBand2V(); - case firstCol: - return _tblStyle.getFirstCol(); - case lastCol: - return _tblStyle.getLastCol(); - case firstRow: - return _tblStyle.getFirstRow(); - case lastRow: - return _tblStyle.getLastRow(); - case seCell: - return _tblStyle.getSeCell(); - case swCell: - return _tblStyle.getSwCell(); - case neCell: - return _tblStyle.getNeCell(); - case nwCell: - return _tblStyle.getNwCell(); - } - } -} \ No newline at end of file diff --git a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFTableStyles.java b/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFTableStyles.java deleted file mode 100644 index 487b33964..000000000 --- a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFTableStyles.java +++ /dev/null @@ -1,71 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.usermodel; - -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.util.Beta; -import org.apache.xmlbeans.XmlException; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTableStyle; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTableStyleList; -import org.openxmlformats.schemas.drawingml.x2006.main.TblStyleLstDocument; - -@Beta -public class XSLFTableStyles extends POIXMLDocumentPart implements Iterable{ - private CTTableStyleList _tblStyleLst; - private List _styles; - - public XSLFTableStyles(){ - super(); - } - - /** - * @since POI 3.14-Beta1 - */ - public XSLFTableStyles(PackagePart part) throws IOException, XmlException { - super(part); - - InputStream is = getPackagePart().getInputStream(); - TblStyleLstDocument styleDoc = TblStyleLstDocument.Factory.parse(is); - is.close(); - _tblStyleLst = styleDoc.getTblStyleLst(); - CTTableStyle[] tblStyleArray = _tblStyleLst.getTblStyleArray(); - _styles = new ArrayList(tblStyleArray.length); - for(CTTableStyle c : tblStyleArray){ - _styles.add(new XSLFTableStyle(c)); - } - } - - public CTTableStyleList getXmlObject(){ - return _tblStyleLst; - } - - public Iterator iterator(){ - return _styles.iterator(); - } - - public List getStyles(){ - return Collections.unmodifiableList(_styles); - } -} \ No newline at end of file diff --git a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFTextBox.java b/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFTextBox.java deleted file mode 100644 index 2f172d2fd..000000000 --- a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFTextBox.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xslf.usermodel; - -import org.apache.poi.sl.usermodel.TextBox; -import org.apache.poi.util.Beta; -import org.openxmlformats.schemas.drawingml.x2006.main.*; -import org.openxmlformats.schemas.presentationml.x2006.main.CTShape; -import org.openxmlformats.schemas.presentationml.x2006.main.CTShapeNonVisual; - - -/** - * @author Yegor Kozlov - */ -@Beta -public class XSLFTextBox extends XSLFAutoShape - implements TextBox { - - /*package*/ XSLFTextBox(CTShape shape, XSLFSheet sheet){ - super(shape, sheet); - } - - /** - * - * @param shapeId 1-based shapeId - */ - static CTShape prototype(int shapeId){ - CTShape ct = CTShape.Factory.newInstance(); - CTShapeNonVisual nvSpPr = ct.addNewNvSpPr(); - CTNonVisualDrawingProps cnv = nvSpPr.addNewCNvPr(); - cnv.setName("TextBox " + shapeId); - cnv.setId(shapeId + 1); - nvSpPr.addNewCNvSpPr().setTxBox(true); - nvSpPr.addNewNvPr(); - CTShapeProperties spPr = ct.addNewSpPr(); - CTPresetGeometry2D prst = spPr.addNewPrstGeom(); - prst.setPrst(STShapeType.RECT); - prst.addNewAvLst(); - CTTextBody txBody = ct.addNewTxBody(); - XSLFAutoShape.initTextBody(txBody); - - return ct; - } -} \ No newline at end of file diff --git a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFTextParagraph.java b/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFTextParagraph.java deleted file mode 100644 index 0944d542e..000000000 --- a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFTextParagraph.java +++ /dev/null @@ -1,1072 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.usermodel; - -import java.awt.Color; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.apache.poi.sl.draw.DrawPaint; -import org.apache.poi.sl.usermodel.AutoNumberingScheme; -import org.apache.poi.sl.usermodel.PaintStyle; -import org.apache.poi.sl.usermodel.PaintStyle.SolidPaint; -import org.apache.poi.sl.usermodel.TextParagraph; -import org.apache.poi.util.Beta; -import org.apache.poi.util.Internal; -import org.apache.poi.util.Units; -import org.apache.poi.xslf.model.ParagraphPropertyFetcher; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlObject; -import org.openxmlformats.schemas.drawingml.x2006.main.CTColor; -import org.openxmlformats.schemas.drawingml.x2006.main.CTRegularTextRun; -import org.openxmlformats.schemas.drawingml.x2006.main.CTSRgbColor; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextAutonumberBullet; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextBulletSizePercent; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextBulletSizePoint; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextCharBullet; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextCharacterProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextField; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextFont; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextLineBreak; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextNormalAutofit; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextParagraph; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextParagraphProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextSpacing; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextTabStop; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextTabStopList; -import org.openxmlformats.schemas.drawingml.x2006.main.STTextAlignType; -import org.openxmlformats.schemas.drawingml.x2006.main.STTextAutonumberScheme; -import org.openxmlformats.schemas.drawingml.x2006.main.STTextFontAlignType; -import org.openxmlformats.schemas.presentationml.x2006.main.CTPlaceholder; -import org.openxmlformats.schemas.presentationml.x2006.main.STPlaceholderType; - -/** - * Represents a paragraph of text within the containing text body. - * The paragraph is the highest level text separation mechanism. - * - * @since POI-3.8 - */ -@Beta -public class XSLFTextParagraph implements TextParagraph { - private final CTTextParagraph _p; - private final List _runs; - private final XSLFTextShape _shape; - - XSLFTextParagraph(CTTextParagraph p, XSLFTextShape shape){ - _p = p; - _runs = new ArrayList(); - _shape = shape; - - XmlCursor c = _p.newCursor(); - try { - if (c.toFirstChild()) { - do { - XmlObject r = c.getObject(); - if (r instanceof CTTextLineBreak) { - _runs.add(new XSLFLineBreak((CTTextLineBreak)r, this)); - } else if (r instanceof CTRegularTextRun || r instanceof CTTextField) { - _runs.add(new XSLFTextRun(r, this)); - } - } while (c.toNextSibling()); - } - } finally { - c.dispose(); - } - } - - public String getText(){ - StringBuilder out = new StringBuilder(); - for (XSLFTextRun r : _runs) { - out.append(r.getRawText()); - } - return out.toString(); - } - - String getRenderableText(){ - StringBuilder out = new StringBuilder(); - for (XSLFTextRun r : _runs) { - out.append(r.getRenderableText()); - } - return out.toString(); - } - - @Internal - public CTTextParagraph getXmlObject(){ - return _p; - } - - public XSLFTextShape getParentShape() { - return _shape; - - } - - @Override - public List getTextRuns(){ - return _runs; - } - - public Iterator iterator(){ - return _runs.iterator(); - } - - /** - * Add a new run of text - * - * @return a new run of text - */ - public XSLFTextRun addNewTextRun(){ - CTRegularTextRun r = _p.addNewR(); - CTTextCharacterProperties rPr = r.addNewRPr(); - rPr.setLang("en-US"); - XSLFTextRun run = newTextRun(r); - _runs.add(run); - return run; - } - - /** - * Insert a line break - * - * @return text run representing this line break ('\n') - */ - public XSLFTextRun addLineBreak(){ - XSLFLineBreak run = new XSLFLineBreak(_p.addNewBr(), this); - CTTextCharacterProperties brProps = run.getRPr(true); - if(_runs.size() > 0){ - // by default line break has the font size of the last text run - CTTextCharacterProperties prevRun = _runs.get(_runs.size() - 1).getRPr(true); - brProps.set(prevRun); - } - _runs.add(run); - return run; - } - - @Override - public TextAlign getTextAlign(){ - ParagraphPropertyFetcher fetcher = new ParagraphPropertyFetcher(getIndentLevel()){ - public boolean fetch(CTTextParagraphProperties props){ - if(props.isSetAlgn()){ - TextAlign val = TextAlign.values()[props.getAlgn().intValue() - 1]; - setValue(val); - return true; - } - return false; - } - }; - fetchParagraphProperty(fetcher); - return fetcher.getValue(); - } - - @Override - public void setTextAlign(TextAlign align) { - CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr(); - if(align == null) { - if(pr.isSetAlgn()) pr.unsetAlgn(); - } else { - pr.setAlgn(STTextAlignType.Enum.forInt(align.ordinal() + 1)); - } - } - - @Override - public FontAlign getFontAlign(){ - ParagraphPropertyFetcher fetcher = new ParagraphPropertyFetcher(getIndentLevel()){ - public boolean fetch(CTTextParagraphProperties props){ - if(props.isSetFontAlgn()){ - FontAlign val = FontAlign.values()[props.getFontAlgn().intValue() - 1]; - setValue(val); - return true; - } - return false; - } - }; - fetchParagraphProperty(fetcher); - return fetcher.getValue(); - } - - /** - * Specifies the font alignment that is to be applied to the paragraph. - * Possible values for this include auto, top, center, baseline and bottom. - * see {@link org.apache.poi.sl.usermodel.TextParagraph.FontAlign}. - * - * @param align font align - */ - public void setFontAlign(FontAlign align){ - CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr(); - if(align == null) { - if(pr.isSetFontAlgn()) pr.unsetFontAlgn(); - } else { - pr.setFontAlgn(STTextFontAlignType.Enum.forInt(align.ordinal() + 1)); - } - } - - - - /** - * @return the font to be used on bullet characters within a given paragraph - */ - public String getBulletFont(){ - ParagraphPropertyFetcher fetcher = new ParagraphPropertyFetcher(getIndentLevel()){ - public boolean fetch(CTTextParagraphProperties props){ - if(props.isSetBuFont()){ - setValue(props.getBuFont().getTypeface()); - return true; - } - return false; - } - }; - fetchParagraphProperty(fetcher); - return fetcher.getValue(); - } - - public void setBulletFont(String typeface){ - CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr(); - CTTextFont font = pr.isSetBuFont() ? pr.getBuFont() : pr.addNewBuFont(); - font.setTypeface(typeface); - } - - /** - * @return the character to be used in place of the standard bullet point - */ - public String getBulletCharacter(){ - ParagraphPropertyFetcher fetcher = new ParagraphPropertyFetcher(getIndentLevel()){ - public boolean fetch(CTTextParagraphProperties props){ - if(props.isSetBuChar()){ - setValue(props.getBuChar().getChar()); - return true; - } - return false; - } - }; - fetchParagraphProperty(fetcher); - return fetcher.getValue(); - } - - public void setBulletCharacter(String str){ - CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr(); - CTTextCharBullet c = pr.isSetBuChar() ? pr.getBuChar() : pr.addNewBuChar(); - c.setChar(str); - } - - /** - * - * @return the color of bullet characters within a given paragraph. - * A null value means to use the text font color. - */ - public PaintStyle getBulletFontColor(){ - final XSLFTheme theme = getParentShape().getSheet().getTheme(); - ParagraphPropertyFetcher fetcher = new ParagraphPropertyFetcher(getIndentLevel()){ - public boolean fetch(CTTextParagraphProperties props){ - if(props.isSetBuClr()){ - XSLFColor c = new XSLFColor(props.getBuClr(), theme, null); - setValue(c.getColor()); - return true; - } - return false; - } - }; - fetchParagraphProperty(fetcher); - Color col = fetcher.getValue(); - return (col == null) ? null : DrawPaint.createSolidPaint(col); - } - - public void setBulletFontColor(Color color) { - setBulletFontColor(DrawPaint.createSolidPaint(color)); - } - - - /** - * Set the color to be used on bullet characters within a given paragraph. - * - * @param color the bullet color - */ - public void setBulletFontColor(PaintStyle color) { - if (!(color instanceof SolidPaint)) { - throw new IllegalArgumentException("Currently XSLF only supports SolidPaint"); - } - - // TODO: implement setting bullet color to null - SolidPaint sp = (SolidPaint)color; - Color col = DrawPaint.applyColorTransform(sp.getSolidColor()); - - CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr(); - CTColor c = pr.isSetBuClr() ? pr.getBuClr() : pr.addNewBuClr(); - CTSRgbColor clr = c.isSetSrgbClr() ? c.getSrgbClr() : c.addNewSrgbClr(); - clr.setVal(new byte[]{(byte) col.getRed(), (byte) col.getGreen(), (byte) col.getBlue()}); - } - - /** - * Returns the bullet size that is to be used within a paragraph. - * This may be specified in two different ways, percentage spacing and font point spacing: - *

    - * If bulletSize >= 0, then bulletSize is a percentage of the font size. - * If bulletSize < 0, then it specifies the size in points - *

    - * - * @return the bullet size - */ - public Double getBulletFontSize(){ - ParagraphPropertyFetcher fetcher = new ParagraphPropertyFetcher(getIndentLevel()){ - public boolean fetch(CTTextParagraphProperties props){ - if(props.isSetBuSzPct()){ - setValue(props.getBuSzPct().getVal() * 0.001); - return true; - } - if(props.isSetBuSzPts()){ - setValue( - props.getBuSzPts().getVal() * 0.01); - return true; - } - return false; - } - }; - fetchParagraphProperty(fetcher); - return fetcher.getValue(); - } - - /** - * Sets the bullet size that is to be used within a paragraph. - * This may be specified in two different ways, percentage spacing and font point spacing: - *

    - * If bulletSize >= 0, then bulletSize is a percentage of the font size. - * If bulletSize < 0, then it specifies the size in points - *

    - */ - public void setBulletFontSize(double bulletSize){ - CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr(); - - if(bulletSize >= 0) { - CTTextBulletSizePercent pt = pr.isSetBuSzPct() ? pr.getBuSzPct() : pr.addNewBuSzPct(); - pt.setVal((int)(bulletSize*1000)); - if(pr.isSetBuSzPts()) pr.unsetBuSzPts(); - } else { - CTTextBulletSizePoint pt = pr.isSetBuSzPts() ? pr.getBuSzPts() : pr.addNewBuSzPts(); - pt.setVal((int)(-bulletSize*100)); - if(pr.isSetBuSzPct()) pr.unsetBuSzPct(); - } - } - - /** - * @return the auto numbering scheme, or null if not defined - */ - public AutoNumberingScheme getAutoNumberingScheme() { - ParagraphPropertyFetcher fetcher = new ParagraphPropertyFetcher(getIndentLevel()) { - public boolean fetch(CTTextParagraphProperties props) { - if (props.isSetBuAutoNum()) { - AutoNumberingScheme ans = AutoNumberingScheme.forOoxmlID(props.getBuAutoNum().getType().intValue()); - if (ans != null) { - setValue(ans); - return true; - } - } - return false; - } - }; - fetchParagraphProperty(fetcher); - return fetcher.getValue(); - } - - /** - * @return the auto numbering starting number, or null if not defined - */ - public Integer getAutoNumberingStartAt() { - ParagraphPropertyFetcher fetcher = new ParagraphPropertyFetcher(getIndentLevel()) { - public boolean fetch(CTTextParagraphProperties props) { - if (props.isSetBuAutoNum()) { - if (props.getBuAutoNum().isSetStartAt()) { - setValue(props.getBuAutoNum().getStartAt()); - return true; - } - } - return false; - } - }; - fetchParagraphProperty(fetcher); - return fetcher.getValue(); - } - - - @Override - public void setIndent(Double indent){ - if ((indent == null) && !_p.isSetPPr()) return; - CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr(); - if(indent == null) { - if(pr.isSetIndent()) pr.unsetIndent(); - } else { - pr.setIndent(Units.toEMU(indent)); - } - } - - @Override - public Double getIndent() { - - ParagraphPropertyFetcher fetcher = new ParagraphPropertyFetcher(getIndentLevel()){ - public boolean fetch(CTTextParagraphProperties props){ - if(props.isSetIndent()){ - setValue(Units.toPoints(props.getIndent())); - return true; - } - return false; - } - }; - fetchParagraphProperty(fetcher); - - return fetcher.getValue(); - } - - @Override - public void setLeftMargin(Double leftMargin){ - if (leftMargin == null && !_p.isSetPPr()) return; - CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr(); - if (leftMargin == null) { - if(pr.isSetMarL()) pr.unsetMarL(); - } else { - pr.setMarL(Units.toEMU(leftMargin)); - } - - } - - /** - * @return the left margin (in points) of the paragraph, null if unset - */ - @Override - public Double getLeftMargin(){ - ParagraphPropertyFetcher fetcher = new ParagraphPropertyFetcher(getIndentLevel()){ - public boolean fetch(CTTextParagraphProperties props){ - if(props.isSetMarL()){ - double val = Units.toPoints(props.getMarL()); - setValue(val); - return true; - } - return false; - } - }; - fetchParagraphProperty(fetcher); - // if the marL attribute is omitted, then a value of 347663 is implied - return fetcher.getValue(); - } - - @Override - public void setRightMargin(Double rightMargin){ - if (rightMargin == null && !_p.isSetPPr()) return; - CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr(); - if(rightMargin == null) { - if(pr.isSetMarR()) pr.unsetMarR(); - } else { - pr.setMarR(Units.toEMU(rightMargin)); - } - } - - /** - * - * @return the right margin of the paragraph, null if unset - */ - @Override - public Double getRightMargin(){ - ParagraphPropertyFetcher fetcher = new ParagraphPropertyFetcher(getIndentLevel()){ - public boolean fetch(CTTextParagraphProperties props){ - if(props.isSetMarR()){ - double val = Units.toPoints(props.getMarR()); - setValue(val); - return true; - } - return false; - } - }; - fetchParagraphProperty(fetcher); - return fetcher.getValue(); - } - - @Override - public Double getDefaultTabSize(){ - ParagraphPropertyFetcher fetcher = new ParagraphPropertyFetcher(getIndentLevel()){ - public boolean fetch(CTTextParagraphProperties props){ - if(props.isSetDefTabSz()){ - double val = Units.toPoints(props.getDefTabSz()); - setValue(val); - return true; - } - return false; - } - }; - fetchParagraphProperty(fetcher); - return fetcher.getValue(); - } - - public double getTabStop(final int idx){ - ParagraphPropertyFetcher fetcher = new ParagraphPropertyFetcher(getIndentLevel()){ - public boolean fetch(CTTextParagraphProperties props){ - if(props.isSetTabLst()){ - CTTextTabStopList tabStops = props.getTabLst(); - if(idx < tabStops.sizeOfTabArray() ) { - CTTextTabStop ts = tabStops.getTabArray(idx); - double val = Units.toPoints(ts.getPos()); - setValue(val); - return true; - } - } - return false; - } - }; - fetchParagraphProperty(fetcher); - return fetcher.getValue() == null ? 0. : fetcher.getValue(); - } - - public void addTabStop(double value){ - CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr(); - CTTextTabStopList tabStops = pr.isSetTabLst() ? pr.getTabLst() : pr.addNewTabLst(); - tabStops.addNewTab().setPos(Units.toEMU(value)); - } - - @Override - public void setLineSpacing(Double lineSpacing){ - if (lineSpacing == null && !_p.isSetPPr()) return; - CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr(); - if(lineSpacing == null) { - if (pr.isSetLnSpc()) pr.unsetLnSpc(); - } else { - CTTextSpacing spc = (pr.isSetLnSpc()) ? pr.getLnSpc() : pr.addNewLnSpc(); - if (lineSpacing >= 0) { - (spc.isSetSpcPct() ? spc.getSpcPct() : spc.addNewSpcPct()).setVal((int)(lineSpacing*1000)); - if (spc.isSetSpcPts()) spc.unsetSpcPts(); - } else { - (spc.isSetSpcPts() ? spc.getSpcPts() : spc.addNewSpcPts()).setVal((int)(-lineSpacing*100)); - if (spc.isSetSpcPct()) spc.unsetSpcPct(); - } - } - } - - @Override - public Double getLineSpacing(){ - ParagraphPropertyFetcher fetcher = new ParagraphPropertyFetcher(getIndentLevel()){ - public boolean fetch(CTTextParagraphProperties props){ - if(props.isSetLnSpc()){ - CTTextSpacing spc = props.getLnSpc(); - - if(spc.isSetSpcPct()) setValue( spc.getSpcPct().getVal()*0.001 ); - else if (spc.isSetSpcPts()) setValue( -spc.getSpcPts().getVal()*0.01 ); - return true; - } - return false; - } - }; - fetchParagraphProperty(fetcher); - - Double lnSpc = fetcher.getValue(); - if (lnSpc != null && lnSpc > 0) { - // check if the percentage value is scaled - CTTextNormalAutofit normAutofit = getParentShape().getTextBodyPr().getNormAutofit(); - if(normAutofit != null) { - double scale = 1 - (double)normAutofit.getLnSpcReduction() / 100000; - lnSpc *= scale; - } - } - - return lnSpc; - } - - @Override - public void setSpaceBefore(Double spaceBefore){ - if (spaceBefore == null && !_p.isSetPPr()) { - return; - } - - // unset the space before on null input - if (spaceBefore == null) { - if(_p.getPPr().isSetSpcBef()) { - _p.getPPr().unsetSpcBef(); - } - return; - } - - CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr(); - CTTextSpacing spc = CTTextSpacing.Factory.newInstance(); - - if(spaceBefore >= 0) { - spc.addNewSpcPct().setVal((int)(spaceBefore*1000)); - } else { - spc.addNewSpcPts().setVal((int)(-spaceBefore*100)); - } - pr.setSpcBef(spc); - } - - @Override - public Double getSpaceBefore(){ - ParagraphPropertyFetcher fetcher = new ParagraphPropertyFetcher(getIndentLevel()){ - public boolean fetch(CTTextParagraphProperties props){ - if(props.isSetSpcBef()){ - CTTextSpacing spc = props.getSpcBef(); - - if(spc.isSetSpcPct()) setValue( spc.getSpcPct().getVal()*0.001 ); - else if (spc.isSetSpcPts()) setValue( -spc.getSpcPts().getVal()*0.01 ); - return true; - } - return false; - } - }; - fetchParagraphProperty(fetcher); - - return fetcher.getValue(); - } - - @Override - public void setSpaceAfter(Double spaceAfter){ - if (spaceAfter == null && !_p.isSetPPr()) { - return; - } - - // unset the space before on null input - if (spaceAfter == null) { - if(_p.getPPr().isSetSpcAft()) { - _p.getPPr().unsetSpcAft(); - } - return; - } - - CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr(); - CTTextSpacing spc = CTTextSpacing.Factory.newInstance(); - - if(spaceAfter >= 0) { - spc.addNewSpcPct().setVal((int)(spaceAfter*1000)); - } else { - spc.addNewSpcPts().setVal((int)(-spaceAfter*100)); - } - pr.setSpcAft(spc); - } - - @Override - public Double getSpaceAfter(){ - ParagraphPropertyFetcher fetcher = new ParagraphPropertyFetcher(getIndentLevel()){ - public boolean fetch(CTTextParagraphProperties props){ - if(props.isSetSpcAft()){ - CTTextSpacing spc = props.getSpcAft(); - - if(spc.isSetSpcPct()) setValue( spc.getSpcPct().getVal()*0.001 ); - else if (spc.isSetSpcPts()) setValue( -spc.getSpcPts().getVal()*0.01 ); - return true; - } - return false; - } - }; - fetchParagraphProperty(fetcher); - return fetcher.getValue(); - } - - @Override - public void setIndentLevel(int level){ - CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr(); - pr.setLvl(level); - } - - @Override - public int getIndentLevel() { - CTTextParagraphProperties pr = _p.getPPr(); - return (pr == null || !pr.isSetLvl()) ? 0 : pr.getLvl(); - } - - /** - * Returns whether this paragraph has bullets - */ - public boolean isBullet() { - ParagraphPropertyFetcher fetcher = new ParagraphPropertyFetcher(getIndentLevel()){ - public boolean fetch(CTTextParagraphProperties props){ - if(props.isSetBuNone()) { - setValue(false); - return true; - } - if(props.isSetBuFont() || props.isSetBuChar()){ - setValue(true); - return true; - } - return false; - } - }; - fetchParagraphProperty(fetcher); - return fetcher.getValue() == null ? false : fetcher.getValue(); - } - - /** - * - * @param flag whether text in this paragraph has bullets - */ - public void setBullet(boolean flag) { - if(isBullet() == flag) return; - - CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr(); - if(flag) { - pr.addNewBuFont().setTypeface("Arial"); - pr.addNewBuChar().setChar("\u2022"); - } else { - if (pr.isSetBuFont()) pr.unsetBuFont(); - if (pr.isSetBuChar()) pr.unsetBuChar(); - if (pr.isSetBuAutoNum()) pr.unsetBuAutoNum(); - if (pr.isSetBuBlip()) pr.unsetBuBlip(); - if (pr.isSetBuClr()) pr.unsetBuClr(); - if (pr.isSetBuClrTx()) pr.unsetBuClrTx(); - if (pr.isSetBuFont()) pr.unsetBuFont(); - if (pr.isSetBuFontTx()) pr.unsetBuFontTx(); - if (pr.isSetBuSzPct()) pr.unsetBuSzPct(); - if (pr.isSetBuSzPts()) pr.unsetBuSzPts(); - if (pr.isSetBuSzTx()) pr.unsetBuSzTx(); - pr.addNewBuNone(); - } - } - - /** - * Specifies that automatic numbered bullet points should be applied to this paragraph - * - * @param scheme type of auto-numbering - * @param startAt the number that will start number for a given sequence of automatically - numbered bullets (1-based). - */ - public void setBulletAutoNumber(AutoNumberingScheme scheme, int startAt) { - if(startAt < 1) throw new IllegalArgumentException("Start Number must be greater or equal that 1") ; - CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr(); - CTTextAutonumberBullet lst = pr.isSetBuAutoNum() ? pr.getBuAutoNum() : pr.addNewBuAutoNum(); - lst.setType(STTextAutonumberScheme.Enum.forInt(scheme.ooxmlId)); - lst.setStartAt(startAt); - } - - @Override - public String toString(){ - return "[" + getClass() + "]" + getText(); - } - - - /** - * @return master style text paragraph properties, or null if - * there are no master slides or the master slides do not contain a text paragraph - */ - /* package */ CTTextParagraphProperties getDefaultMasterStyle(){ - CTPlaceholder ph = _shape.getCTPlaceholder(); - String defaultStyleSelector; - switch(ph == null ? -1 : ph.getType().intValue()) { - case STPlaceholderType.INT_TITLE: - case STPlaceholderType.INT_CTR_TITLE: - defaultStyleSelector = "titleStyle"; - break; - case -1: // no placeholder means plain text box - case STPlaceholderType.INT_FTR: - case STPlaceholderType.INT_SLD_NUM: - case STPlaceholderType.INT_DT: - defaultStyleSelector = "otherStyle"; - break; - default: - defaultStyleSelector = "bodyStyle"; - break; - } - int level = getIndentLevel(); - - // wind up and find the root master sheet which must be slide master - final String nsPML = "http://schemas.openxmlformats.org/presentationml/2006/main"; - final String nsDML = "http://schemas.openxmlformats.org/drawingml/2006/main"; - XSLFSheet masterSheet = _shape.getSheet(); - for (XSLFSheet m = masterSheet; m != null; m = (XSLFSheet)m.getMasterSheet()) { - masterSheet = m; - XmlObject xo = masterSheet.getXmlObject(); - XmlCursor cur = xo.newCursor(); - try { - cur.push(); - if ((cur.toChild(nsPML, "txStyles") && cur.toChild(nsPML, defaultStyleSelector)) || - (cur.pop() && cur.toChild(nsPML, "notesStyle"))) { - while (level >= 0) { - cur.push(); - if (cur.toChild(nsDML, "lvl" +(level+1)+ "pPr")) { - return (CTTextParagraphProperties)cur.getObject(); - } - cur.pop(); - level--; - } - } - } finally { - cur.dispose(); - } - } - - return null; - } - - private boolean fetchParagraphProperty(ParagraphPropertyFetcher visitor){ - boolean ok = false; - XSLFTextShape shape = getParentShape(); - XSLFSheet sheet = shape.getSheet(); - - if(_p.isSetPPr()) ok = visitor.fetch(_p.getPPr()); - if (ok) return true; - - ok = shape.fetchShapeProperty(visitor); - if (ok) return true; - - - CTPlaceholder ph = shape.getCTPlaceholder(); - if(ph == null){ - // if it is a plain text box then take defaults from presentation.xml - @SuppressWarnings("resource") - XMLSlideShow ppt = sheet.getSlideShow(); - CTTextParagraphProperties themeProps = ppt.getDefaultParagraphStyle(getIndentLevel()); - if (themeProps != null) ok = visitor.fetch(themeProps); - } - if (ok) return true; - - // defaults for placeholders are defined in the slide master - CTTextParagraphProperties defaultProps = getDefaultMasterStyle(); - // TODO: determine master shape - if(defaultProps != null) ok = visitor.fetch(defaultProps); - if (ok) return true; - - return false; - } - - void copy(XSLFTextParagraph other){ - if (other == this) return; - - CTTextParagraph thisP = getXmlObject(); - CTTextParagraph otherP = other.getXmlObject(); - - if (thisP.isSetPPr()) thisP.unsetPPr(); - if (thisP.isSetEndParaRPr()) thisP.unsetEndParaRPr(); - - _runs.clear(); - for (int i=thisP.sizeOfBrArray(); i>0; i--) { - thisP.removeBr(i-1); - } - for (int i=thisP.sizeOfRArray(); i>0; i--) { - thisP.removeR(i-1); - } - for (int i=thisP.sizeOfFldArray(); i>0; i--) { - thisP.removeFld(i-1); - } - - XmlCursor thisC = thisP.newCursor(); - thisC.toEndToken(); - XmlCursor otherC = otherP.newCursor(); - otherC.copyXmlContents(thisC); - otherC.dispose(); - thisC.dispose(); - - List otherRs = other.getTextRuns(); - int i=0; - for(CTRegularTextRun rtr : thisP.getRArray()) { - XSLFTextRun run = newTextRun(rtr); - run.copy(otherRs.get(i++)); - _runs.add(run); - } - - - // set properties again, in case we are based on a different - // template - TextAlign srcAlign = other.getTextAlign(); - if(srcAlign != getTextAlign()){ - setTextAlign(srcAlign); - } - - boolean isBullet = other.isBullet(); - if(isBullet != isBullet()){ - setBullet(isBullet); - if(isBullet) { - String buFont = other.getBulletFont(); - if(buFont != null && !buFont.equals(getBulletFont())){ - setBulletFont(buFont); - } - String buChar = other.getBulletCharacter(); - if(buChar != null && !buChar.equals(getBulletCharacter())){ - setBulletCharacter(buChar); - } - PaintStyle buColor = other.getBulletFontColor(); - if(buColor != null && !buColor.equals(getBulletFontColor())){ - setBulletFontColor(buColor); - } - Double buSize = other.getBulletFontSize(); - if(!doubleEquals(buSize, getBulletFontSize())){ - setBulletFontSize(buSize); - } - } - } - - Double leftMargin = other.getLeftMargin(); - if (!doubleEquals(leftMargin, getLeftMargin())){ - setLeftMargin(leftMargin); - } - - Double indent = other.getIndent(); - if (!doubleEquals(indent, getIndent())) { - setIndent(indent); - } - - Double spaceAfter = other.getSpaceAfter(); - if (!doubleEquals(spaceAfter, getSpaceAfter())) { - setSpaceAfter(spaceAfter); - } - - Double spaceBefore = other.getSpaceBefore(); - if (!doubleEquals(spaceBefore, getSpaceBefore())) { - setSpaceBefore(spaceBefore); - } - - Double lineSpacing = other.getLineSpacing(); - if (!doubleEquals(lineSpacing, getLineSpacing())) { - setLineSpacing(lineSpacing); - } - } - - private static boolean doubleEquals(Double d1, Double d2) { - return (d1 == d2 || (d1 != null && d1.equals(d2))); - } - - @Override - public Double getDefaultFontSize() { - CTTextCharacterProperties endPr = _p.getEndParaRPr(); - if (endPr == null || !endPr.isSetSz()) { - // inherit the font size from the master style - CTTextParagraphProperties masterStyle = getDefaultMasterStyle(); - if (masterStyle != null) { - endPr = masterStyle.getDefRPr(); - } - } - return (endPr == null || !endPr.isSetSz()) ? 12 : (endPr.getSz() / 100.); - } - - @Override - public String getDefaultFontFamily() { - return (_runs.isEmpty() ? "Arial" : _runs.get(0).getFontFamily()); - } - - @Override - public BulletStyle getBulletStyle() { - if (!isBullet()) return null; - return new BulletStyle(){ - @Override - public String getBulletCharacter() { - return XSLFTextParagraph.this.getBulletCharacter(); - } - - @Override - public String getBulletFont() { - return XSLFTextParagraph.this.getBulletFont(); - } - - @Override - public Double getBulletFontSize() { - return XSLFTextParagraph.this.getBulletFontSize(); - } - - @Override - public PaintStyle getBulletFontColor() { - return XSLFTextParagraph.this.getBulletFontColor(); - } - - @Override - public void setBulletFontColor(Color color) { - setBulletFontColor(DrawPaint.createSolidPaint(color)); - } - - @Override - public void setBulletFontColor(PaintStyle color) { - XSLFTextParagraph.this.setBulletFontColor(color); - } - - @Override - public AutoNumberingScheme getAutoNumberingScheme() { - return XSLFTextParagraph.this.getAutoNumberingScheme(); - } - - @Override - public Integer getAutoNumberingStartAt() { - return XSLFTextParagraph.this.getAutoNumberingStartAt(); - } - - }; - } - - @Override - public void setBulletStyle(Object... styles) { - if (styles.length == 0) { - setBullet(false); - } else { - setBullet(true); - for (Object ostyle : styles) { - if (ostyle instanceof Number) { - setBulletFontSize(((Number)ostyle).doubleValue()); - } else if (ostyle instanceof Color) { - setBulletFontColor((Color)ostyle); - } else if (ostyle instanceof Character) { - setBulletCharacter(ostyle.toString()); - } else if (ostyle instanceof String) { - setBulletFont((String)ostyle); - } else if (ostyle instanceof AutoNumberingScheme) { - setBulletAutoNumber((AutoNumberingScheme)ostyle, 0); - } - } - } - } - - /** - * Helper method for appending text and keeping paragraph and character properties. - * The character properties are moved to the end paragraph marker - */ - /* package */ void clearButKeepProperties() { - CTTextParagraph thisP = getXmlObject(); - for (int i=thisP.sizeOfBrArray(); i>0; i--) { - thisP.removeBr(i-1); - } - for (int i=thisP.sizeOfFldArray(); i>0; i--) { - thisP.removeFld(i-1); - } - if (!_runs.isEmpty()) { - int size = _runs.size(); - XSLFTextRun lastRun = _runs.get(size-1); - CTTextCharacterProperties cpOther = lastRun.getRPr(false); - if (cpOther != null) { - if (thisP.isSetEndParaRPr()) { - thisP.unsetEndParaRPr(); - } - CTTextCharacterProperties cp = thisP.addNewEndParaRPr(); - cp.set(cpOther); - } - for (int i=size; i>0; i--) { - thisP.removeR(i-1); - } - _runs.clear(); - } - } - - @Override - public boolean isHeaderOrFooter() { - CTPlaceholder ph = _shape.getCTPlaceholder(); - int phId = (ph == null ? -1 : ph.getType().intValue()); - switch (phId) { - case STPlaceholderType.INT_SLD_NUM: - case STPlaceholderType.INT_DT: - case STPlaceholderType.INT_FTR: - case STPlaceholderType.INT_HDR: - return true; - default: - return false; - } - } - - /** - * Helper method to allow subclasses to provide their own text run - * - * @param r the xml reference - * - * @return a new text paragraph - * - * @since POI 3.15-beta2 - */ - protected XSLFTextRun newTextRun(CTRegularTextRun r) { - return new XSLFTextRun(r, this); - } -} diff --git a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFTextRun.java b/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFTextRun.java deleted file mode 100644 index 8048e59b5..000000000 --- a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFTextRun.java +++ /dev/null @@ -1,629 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.usermodel; - -import java.awt.Color; - -import org.apache.poi.openxml4j.exceptions.OpenXML4JRuntimeException; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.sl.draw.DrawPaint; -import org.apache.poi.sl.usermodel.PaintStyle; -import org.apache.poi.sl.usermodel.PaintStyle.SolidPaint; -import org.apache.poi.sl.usermodel.TextRun; -import org.apache.poi.util.Beta; -import org.apache.poi.xslf.model.CharacterPropertyFetcher; -import org.apache.poi.xslf.usermodel.XSLFPropertiesDelegate.XSLFFillProperties; -import org.apache.xmlbeans.XmlObject; -import org.openxmlformats.schemas.drawingml.x2006.main.CTHyperlink; -import org.openxmlformats.schemas.drawingml.x2006.main.CTRegularTextRun; -import org.openxmlformats.schemas.drawingml.x2006.main.CTSchemeColor; -import org.openxmlformats.schemas.drawingml.x2006.main.CTShapeStyle; -import org.openxmlformats.schemas.drawingml.x2006.main.CTSolidColorFillProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextCharacterProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextField; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextFont; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextLineBreak; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextNormalAutofit; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextParagraphProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.STTextStrikeType; -import org.openxmlformats.schemas.drawingml.x2006.main.STTextUnderlineType; -import org.openxmlformats.schemas.presentationml.x2006.main.CTPlaceholder; - -/** - * Represents a run of text within the containing text body. The run element is the - * lowest level text separation mechanism within a text body. - */ -@Beta -public class XSLFTextRun implements TextRun { - private final XmlObject _r; - private final XSLFTextParagraph _p; - - protected XSLFTextRun(XmlObject r, XSLFTextParagraph p){ - _r = r; - _p = p; - if (!(r instanceof CTRegularTextRun || r instanceof CTTextLineBreak || r instanceof CTTextField)) { - throw new OpenXML4JRuntimeException("unsupported text run of type "+r.getClass()); - } - } - - XSLFTextParagraph getParentParagraph(){ - return _p; - } - - public String getRawText(){ - if (_r instanceof CTTextField) { - return ((CTTextField)_r).getT(); - } else if (_r instanceof CTTextLineBreak) { - return "\n"; - } - return ((CTRegularTextRun)_r).getT(); - } - - String getRenderableText(){ - if (_r instanceof CTTextField) { - CTTextField tf = (CTTextField)_r; - XSLFSheet sheet = _p.getParentShape().getSheet(); - if ("slidenum".equals(tf.getType()) && sheet instanceof XSLFSlide) { - return Integer.toString(((XSLFSlide)sheet).getSlideNumber()); - } - return tf.getT(); - } else if (_r instanceof CTTextLineBreak) { - return "\n"; - } - - - String txt = ((CTRegularTextRun)_r).getT(); - TextCap cap = getTextCap(); - StringBuffer buf = new StringBuffer(); - for(int i = 0; i < txt.length(); i++) { - char c = txt.charAt(i); - if(c == '\t') { - // TODO: finish support for tabs - buf.append(" "); - } else { - switch (cap){ - case ALL: - buf.append(Character.toUpperCase(c)); - break; - case SMALL: - buf.append(Character.toLowerCase(c)); - break; - default: - buf.append(c); - } - } - } - - return buf.toString(); - } - - public void setText(String text){ - if (_r instanceof CTTextField) { - ((CTTextField)_r).setT(text); - } else if (_r instanceof CTTextLineBreak) { - // ignored - return; - } else { - ((CTRegularTextRun)_r).setT(text); - } - } - - /** - * Return the text run xmlbeans object. - * Depending on the type of text run, this can be {@link CTTextField}, - * {@link CTTextLineBreak} or usually a {@link CTRegularTextRun} - * - * @return the xmlbeans object - */ - public XmlObject getXmlObject(){ - return _r; - } - - @Override - public void setFontColor(Color color) { - setFontColor(DrawPaint.createSolidPaint(color)); - } - - @Override - public void setFontColor(PaintStyle color) { - if (!(color instanceof SolidPaint)) { - throw new IllegalArgumentException("Currently only SolidPaint is supported!"); - } - SolidPaint sp = (SolidPaint)color; - Color c = DrawPaint.applyColorTransform(sp.getSolidColor()); - - CTTextCharacterProperties rPr = getRPr(true); - CTSolidColorFillProperties fill = rPr.isSetSolidFill() ? rPr.getSolidFill() : rPr.addNewSolidFill(); - - XSLFColor col = new XSLFColor(fill, getParentParagraph().getParentShape().getSheet().getTheme(), fill.getSchemeClr()); - col.setColor(c); - } - - @Override - public PaintStyle getFontColor(){ - final boolean hasPlaceholder = getParentParagraph().getParentShape().getPlaceholder() != null; - CharacterPropertyFetcher fetcher = new CharacterPropertyFetcher(_p.getIndentLevel()){ - public boolean fetch(CTTextCharacterProperties props){ - if (props == null) { - return false; - } - - XSLFShape shape = _p.getParentShape(); - CTShapeStyle style = shape.getSpStyle(); - CTSchemeColor phClr = null; - if (style != null && style.getFontRef() != null) { - phClr = style.getFontRef().getSchemeClr(); - } - - XSLFFillProperties fp = XSLFPropertiesDelegate.getFillDelegate(props); - XSLFSheet sheet = shape.getSheet(); - PackagePart pp = sheet.getPackagePart(); - XSLFTheme theme = sheet.getTheme(); - PaintStyle ps = XSLFShape.selectPaint(fp, phClr, pp, theme, hasPlaceholder); - - if (ps != null) { - setValue(ps); - return true; - } - - return false; - } - }; - fetchCharacterProperty(fetcher); - return fetcher.getValue(); - } - - @Override - public void setFontSize(Double fontSize){ - CTTextCharacterProperties rPr = getRPr(true); - if(fontSize == null) { - if (rPr.isSetSz()) rPr.unsetSz(); - } else { - if (fontSize < 1.0) { - throw new IllegalArgumentException("Minimum font size is 1pt but was " + fontSize); - } - - rPr.setSz((int)(100*fontSize)); - } - } - - @Override - public Double getFontSize(){ - double scale = 1; - CTTextNormalAutofit afit = getParentParagraph().getParentShape().getTextBodyPr().getNormAutofit(); - if(afit != null) scale = (double)afit.getFontScale() / 100000; - - CharacterPropertyFetcher fetcher = new CharacterPropertyFetcher(_p.getIndentLevel()){ - public boolean fetch(CTTextCharacterProperties props){ - if (props != null && props.isSetSz()) { - setValue(props.getSz()*0.01); - return true; - } - return false; - } - }; - fetchCharacterProperty(fetcher); - return fetcher.getValue() == null ? null : fetcher.getValue()*scale; - } - - /** - * - * @return the spacing between characters within a text run, - * If this attribute is omitted than a value of 0 or no adjustment is assumed. - */ - public double getCharacterSpacing(){ - - CharacterPropertyFetcher fetcher = new CharacterPropertyFetcher(_p.getIndentLevel()){ - public boolean fetch(CTTextCharacterProperties props){ - if (props != null && props.isSetSpc()) { - setValue(props.getSpc()*0.01); - return true; - } - return false; - } - }; - fetchCharacterProperty(fetcher); - return fetcher.getValue() == null ? 0 : fetcher.getValue(); - } - - /** - * Set the spacing between characters within a text run. - *

    - * The spacing is specified in points. Positive values will cause the text to expand, - * negative values to condense. - *

    - * - * @param spc character spacing in points. - */ - public void setCharacterSpacing(double spc){ - CTTextCharacterProperties rPr = getRPr(true); - if(spc == 0.0) { - if(rPr.isSetSpc()) rPr.unsetSpc(); - } else { - rPr.setSpc((int)(100*spc)); - } - } - - @Override - public void setFontFamily(String typeface){ - setFontFamily(typeface, (byte)-1, (byte)-1, false); - } - - public void setFontFamily(String typeface, byte charset, byte pictAndFamily, boolean isSymbol){ - CTTextCharacterProperties rPr = getRPr(true); - - if(typeface == null){ - if(rPr.isSetLatin()) rPr.unsetLatin(); - if(rPr.isSetCs()) rPr.unsetCs(); - if(rPr.isSetSym()) rPr.unsetSym(); - } else { - if(isSymbol){ - CTTextFont font = rPr.isSetSym() ? rPr.getSym() : rPr.addNewSym(); - font.setTypeface(typeface); - } else { - CTTextFont latin = rPr.isSetLatin() ? rPr.getLatin() : rPr.addNewLatin(); - latin.setTypeface(typeface); - if(charset != -1) latin.setCharset(charset); - if(pictAndFamily != -1) latin.setPitchFamily(pictAndFamily); - } - } - } - - @Override - public String getFontFamily(){ - final XSLFTheme theme = _p.getParentShape().getSheet().getTheme(); - - CharacterPropertyFetcher visitor = new CharacterPropertyFetcher(_p.getIndentLevel()){ - public boolean fetch(CTTextCharacterProperties props){ - if (props != null) { - CTTextFont font = props.getLatin(); - if (font != null) { - String typeface = font.getTypeface(); - if("+mj-lt".equals(typeface)) { - typeface = theme.getMajorFont(); - } else if ("+mn-lt".equals(typeface)){ - typeface = theme.getMinorFont(); - } - setValue(typeface); - return true; - } - } - return false; - } - }; - fetchCharacterProperty(visitor); - - return visitor.getValue(); - } - - public byte getPitchAndFamily(){ - // final XSLFTheme theme = _p.getParentShape().getSheet().getTheme(); - - CharacterPropertyFetcher visitor = new CharacterPropertyFetcher(_p.getIndentLevel()){ - public boolean fetch(CTTextCharacterProperties props){ - if (props != null) { - CTTextFont font = props.getLatin(); - if (font != null) { - setValue(font.getPitchFamily()); - return true; - } - } - return false; - } - }; - fetchCharacterProperty(visitor); - - return visitor.getValue() == null ? 0 : visitor.getValue(); - } - - @Override - public void setStrikethrough(boolean strike) { - getRPr(true).setStrike(strike ? STTextStrikeType.SNG_STRIKE : STTextStrikeType.NO_STRIKE); - } - - @Override - public boolean isStrikethrough() { - CharacterPropertyFetcher fetcher = new CharacterPropertyFetcher(_p.getIndentLevel()){ - public boolean fetch(CTTextCharacterProperties props){ - if(props != null && props.isSetStrike()) { - setValue(props.getStrike() != STTextStrikeType.NO_STRIKE); - return true; - } - return false; - } - }; - fetchCharacterProperty(fetcher); - return fetcher.getValue() == null ? false : fetcher.getValue(); - } - - @Override - public boolean isSuperscript() { - CharacterPropertyFetcher fetcher = new CharacterPropertyFetcher(_p.getIndentLevel()){ - public boolean fetch(CTTextCharacterProperties props){ - if (props != null && props.isSetBaseline()) { - setValue(props.getBaseline() > 0); - return true; - } - return false; - } - }; - fetchCharacterProperty(fetcher); - return fetcher.getValue() == null ? false : fetcher.getValue(); - } - - /** - * Set the baseline for both the superscript and subscript fonts. - *

    - * The size is specified using a percentage. - * Positive values indicate superscript, negative values indicate subscript. - *

    - * - * @param baselineOffset - */ - public void setBaselineOffset(double baselineOffset){ - getRPr(true).setBaseline((int) baselineOffset * 1000); - } - - /** - * Set whether the text in this run is formatted as superscript. - * Default base line offset is 30% - * - * @see #setBaselineOffset(double) - */ - public void setSuperscript(boolean flag){ - setBaselineOffset(flag ? 30. : 0.); - } - - /** - * Set whether the text in this run is formatted as subscript. - * Default base line offset is -25%. - * - * @see #setBaselineOffset(double) - */ - public void setSubscript(boolean flag){ - setBaselineOffset(flag ? -25.0 : 0.); - } - - @Override - public boolean isSubscript() { - CharacterPropertyFetcher fetcher = new CharacterPropertyFetcher(_p.getIndentLevel()){ - public boolean fetch(CTTextCharacterProperties props){ - if (props != null && props.isSetBaseline()) { - setValue(props.getBaseline() < 0); - return true; - } - return false; - } - }; - fetchCharacterProperty(fetcher); - return fetcher.getValue() == null ? false : fetcher.getValue(); - } - - /** - * @return whether a run of text will be formatted as a superscript text. Default is false. - */ - public TextCap getTextCap() { - CharacterPropertyFetcher fetcher = new CharacterPropertyFetcher(_p.getIndentLevel()){ - public boolean fetch(CTTextCharacterProperties props){ - if (props != null && props.isSetCap()) { - int idx = props.getCap().intValue() - 1; - setValue(TextCap.values()[idx]); - return true; - } - return false; - } - }; - fetchCharacterProperty(fetcher); - return fetcher.getValue() == null ? TextCap.NONE : fetcher.getValue(); - } - - @Override - public void setBold(boolean bold){ - getRPr(true).setB(bold); - } - - @Override - public boolean isBold(){ - CharacterPropertyFetcher fetcher = new CharacterPropertyFetcher(_p.getIndentLevel()){ - public boolean fetch(CTTextCharacterProperties props){ - if (props != null && props.isSetB()) { - setValue(props.getB()); - return true; - } - return false; - } - }; - fetchCharacterProperty(fetcher); - return fetcher.getValue() == null ? false : fetcher.getValue(); - } - - @Override - public void setItalic(boolean italic){ - getRPr(true).setI(italic); - } - - @Override - public boolean isItalic(){ - CharacterPropertyFetcher fetcher = new CharacterPropertyFetcher(_p.getIndentLevel()){ - public boolean fetch(CTTextCharacterProperties props){ - if (props != null && props.isSetI()) { - setValue(props.getI()); - return true; - } - return false; - } - }; - fetchCharacterProperty(fetcher); - return fetcher.getValue() == null ? false : fetcher.getValue(); - } - - @Override - public void setUnderlined(boolean underline) { - getRPr(true).setU(underline ? STTextUnderlineType.SNG : STTextUnderlineType.NONE); - } - - @Override - public boolean isUnderlined(){ - CharacterPropertyFetcher fetcher = new CharacterPropertyFetcher(_p.getIndentLevel()){ - public boolean fetch(CTTextCharacterProperties props){ - if (props != null && props.isSetU()) { - setValue(props.getU() != STTextUnderlineType.NONE); - return true; - } - return false; - } - }; - fetchCharacterProperty(fetcher); - return fetcher.getValue() == null ? false : fetcher.getValue(); - } - - /** - * Return the character properties - * - * @param create if true, create an empty character properties object if it doesn't exist - * @return the character properties or null if create was false and the properties haven't exist - */ - protected CTTextCharacterProperties getRPr(boolean create) { - if (_r instanceof CTTextField) { - CTTextField tf = (CTTextField)_r; - if (tf.isSetRPr()) { - return tf.getRPr(); - } else if (create) { - return tf.addNewRPr(); - } - } else if (_r instanceof CTTextLineBreak) { - CTTextLineBreak tlb = (CTTextLineBreak)_r; - if (tlb.isSetRPr()) { - return tlb.getRPr(); - } else if (create) { - return tlb.addNewRPr(); - } - } else { - CTRegularTextRun tr = (CTRegularTextRun)_r; - if (tr.isSetRPr()) { - return tr.getRPr(); - } else if (create) { - return tr.addNewRPr(); - } - } - return null; - } - - @Override - public String toString(){ - return "[" + getClass() + "]" + getRawText(); - } - - @Override - public XSLFHyperlink createHyperlink(){ - XSLFHyperlink hl = getHyperlink(); - if (hl != null) { - return hl; - } - - CTTextCharacterProperties rPr = getRPr(true); - return new XSLFHyperlink(rPr.addNewHlinkClick(), _p.getParentShape().getSheet()); - } - - @Override - public XSLFHyperlink getHyperlink(){ - CTTextCharacterProperties rPr = getRPr(false); - if (rPr == null) { - return null; - } - CTHyperlink hl = rPr.getHlinkClick(); - if (hl == null) { - return null; - } - return new XSLFHyperlink(hl, _p.getParentShape().getSheet()); - } - - private boolean fetchCharacterProperty(CharacterPropertyFetcher fetcher){ - XSLFTextShape shape = _p.getParentShape(); - XSLFSheet sheet = shape.getSheet(); - - CTTextCharacterProperties rPr = getRPr(false); - if (rPr != null && fetcher.fetch(rPr)) { - return true; - } - - if (shape.fetchShapeProperty(fetcher)) { - return true; - } - - CTPlaceholder ph = shape.getCTPlaceholder(); - if (ph == null){ - // if it is a plain text box then take defaults from presentation.xml - @SuppressWarnings("resource") - XMLSlideShow ppt = sheet.getSlideShow(); - // TODO: determine master shape - CTTextParagraphProperties themeProps = ppt.getDefaultParagraphStyle(_p.getIndentLevel()); - if (themeProps != null && fetcher.fetch(themeProps)) { - return true; - } - } - - // TODO: determine master shape - CTTextParagraphProperties defaultProps = _p.getDefaultMasterStyle(); - if(defaultProps != null && fetcher.fetch(defaultProps)) { - return true; - } - - return false; - } - - void copy(XSLFTextRun r){ - String srcFontFamily = r.getFontFamily(); - if(srcFontFamily != null && !srcFontFamily.equals(getFontFamily())){ - setFontFamily(srcFontFamily); - } - - PaintStyle srcFontColor = r.getFontColor(); - if(srcFontColor != null && !srcFontColor.equals(getFontColor())){ - setFontColor(srcFontColor); - } - - double srcFontSize = r.getFontSize(); - if(srcFontSize != getFontSize()){ - setFontSize(srcFontSize); - } - - boolean bold = r.isBold(); - if(bold != isBold()) setBold(bold); - - boolean italic = r.isItalic(); - if(italic != isItalic()) setItalic(italic); - - boolean underline = r.isUnderlined(); - if(underline != isUnderlined()) setUnderlined(underline); - - boolean strike = r.isStrikethrough(); - if(strike != isStrikethrough()) setStrikethrough(strike); - } - - - @Override - public FieldType getFieldType() { - if (_r instanceof CTTextField) { - CTTextField tf = (CTTextField)_r; - if ("slidenum".equals(tf.getType())) { - return FieldType.SLIDE_NUMBER; - } - } - return null; - } -} diff --git a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFTextShape.java b/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFTextShape.java deleted file mode 100644 index 91b0869b8..000000000 --- a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFTextShape.java +++ /dev/null @@ -1,690 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xslf.usermodel; - -import java.awt.geom.Rectangle2D; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.apache.poi.POIXMLException; -import org.apache.poi.sl.draw.DrawFactory; -import org.apache.poi.sl.draw.DrawTextShape; -import org.apache.poi.sl.usermodel.Insets2D; -import org.apache.poi.sl.usermodel.Placeholder; -import org.apache.poi.sl.usermodel.TextShape; -import org.apache.poi.sl.usermodel.VerticalAlignment; -import org.apache.poi.util.Beta; -import org.apache.poi.util.Units; -import org.apache.poi.xslf.model.PropertyFetcher; -import org.apache.poi.xslf.model.TextBodyPropertyFetcher; -import org.apache.xmlbeans.XmlObject; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextBody; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextBodyProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextCharacterProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextListStyle; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextParagraph; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextParagraphProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.STTextAnchoringType; -import org.openxmlformats.schemas.drawingml.x2006.main.STTextVerticalType; -import org.openxmlformats.schemas.drawingml.x2006.main.STTextWrappingType; -import org.openxmlformats.schemas.presentationml.x2006.main.CTPlaceholder; - -/** - * Represents a shape that can hold text. - */ -@Beta -public abstract class XSLFTextShape extends XSLFSimpleShape - implements TextShape { - private final List _paragraphs; - - /*package*/ XSLFTextShape(XmlObject shape, XSLFSheet sheet) { - super(shape, sheet); - - _paragraphs = new ArrayList(); - CTTextBody txBody = getTextBody(false); - if (txBody != null) { - for (CTTextParagraph p : txBody.getPArray()) { - _paragraphs.add(newTextParagraph(p)); - } - } - } - - public Iterator iterator(){ - return getTextParagraphs().iterator(); - } - - @Override - public String getText() { - StringBuilder out = new StringBuilder(); - for (XSLFTextParagraph p : _paragraphs) { - if (out.length() > 0) out.append('\n'); - out.append(p.getText()); - } - return out.toString(); - } - - /** - * unset text from this shape - */ - public void clearText(){ - _paragraphs.clear(); - CTTextBody txBody = getTextBody(true); - txBody.setPArray(null); // remove any existing paragraphs - } - - @Override - public XSLFTextRun setText(String text) { - // calling clearText or setting to a new Array leads to a XmlValueDisconnectedException - if (!_paragraphs.isEmpty()) { - CTTextBody txBody = getTextBody(false); - int cntPs = txBody.sizeOfPArray(); - for (int i = cntPs; i > 1; i--) { - txBody.removeP(i-1); - _paragraphs.remove(i-1); - } - - _paragraphs.get(0).clearButKeepProperties(); - } - - return appendText(text, false); - } - - @Override - public XSLFTextRun appendText(String text, boolean newParagraph) { - if (text == null) return null; - - // copy properties from last paragraph / textrun or paragraph end marker - CTTextParagraphProperties otherPPr = null; - CTTextCharacterProperties otherRPr = null; - - boolean firstPara; - XSLFTextParagraph para; - if (_paragraphs.isEmpty()) { - firstPara = false; - para = null; - } else { - firstPara = !newParagraph; - para = _paragraphs.get(_paragraphs.size()-1); - CTTextParagraph ctp = para.getXmlObject(); - otherPPr = ctp.getPPr(); - List runs = para.getTextRuns(); - if (!runs.isEmpty()) { - XSLFTextRun r0 = runs.get(runs.size()-1); - otherRPr = r0.getRPr(false); - if (otherRPr == null) { - otherRPr = ctp.getEndParaRPr(); - } - } - // don't copy endParaRPr to the run in case there aren't any other runs - // this is the case when setText() was called initially - // otherwise the master style will be overridden/ignored - } - - XSLFTextRun run = null; - for (String lineTxt : text.split("\\r\\n?|\\n")) { - if (!firstPara) { - if (para != null) { - CTTextParagraph ctp = para.getXmlObject(); - CTTextCharacterProperties unexpectedRPr = ctp.getEndParaRPr(); - if (unexpectedRPr != null && unexpectedRPr != otherRPr) { - ctp.unsetEndParaRPr(); - } - } - para = addNewTextParagraph(); - if (otherPPr != null) { - para.getXmlObject().setPPr(otherPPr); - } - } - boolean firstRun = true; - for (String runText : lineTxt.split("[\u000b]")) { - if (!firstRun) { - para.addLineBreak(); - } - run = para.addNewTextRun(); - run.setText(runText); - if (otherRPr != null) { - run.getRPr(true).set(otherRPr); - } - firstRun = false; - } - firstPara = false; - } - - assert(run != null); - return run; - } - - @Override - public List getTextParagraphs() { - return _paragraphs; - } - - /** - * add a new paragraph run to this shape - * - * @return created paragraph run - */ - public XSLFTextParagraph addNewTextParagraph() { - CTTextBody txBody = getTextBody(false); - CTTextParagraph p; - if (txBody == null) { - txBody = getTextBody(true); - p = txBody.getPArray(0); - p.removeR(0); - } else { - p = txBody.addNewP(); - } - XSLFTextParagraph paragraph = newTextParagraph(p); - _paragraphs.add(paragraph); - return paragraph; - } - - @Override - public void setVerticalAlignment(VerticalAlignment anchor){ - CTTextBodyProperties bodyPr = getTextBodyPr(true); - if (bodyPr != null) { - if(anchor == null) { - if(bodyPr.isSetAnchor()) bodyPr.unsetAnchor(); - } else { - bodyPr.setAnchor(STTextAnchoringType.Enum.forInt(anchor.ordinal() + 1)); - } - } - } - - @Override - public VerticalAlignment getVerticalAlignment(){ - PropertyFetcher fetcher = new TextBodyPropertyFetcher(){ - public boolean fetch(CTTextBodyProperties props){ - if(props.isSetAnchor()){ - int val = props.getAnchor().intValue(); - setValue(VerticalAlignment.values()[val - 1]); - return true; - } - return false; - } - }; - fetchShapeProperty(fetcher); - return fetcher.getValue() == null ? VerticalAlignment.TOP : fetcher.getValue(); - } - - @Override - public void setHorizontalCentered(Boolean isCentered){ - CTTextBodyProperties bodyPr = getTextBodyPr(true); - if (bodyPr != null) { - if (isCentered == null) { - if (bodyPr.isSetAnchorCtr()) bodyPr.unsetAnchorCtr(); - } else { - bodyPr.setAnchorCtr(isCentered); - } - } - } - - @Override - public boolean isHorizontalCentered(){ - PropertyFetcher fetcher = new TextBodyPropertyFetcher(){ - public boolean fetch(CTTextBodyProperties props){ - if(props.isSetAnchorCtr()){ - setValue(props.getAnchorCtr()); - return true; - } - return false; - } - }; - fetchShapeProperty(fetcher); - return fetcher.getValue() == null ? false : fetcher.getValue(); - } - - @Override - public void setTextDirection(TextDirection orientation){ - CTTextBodyProperties bodyPr = getTextBodyPr(true); - if (bodyPr != null) { - if(orientation == null) { - if(bodyPr.isSetVert()) bodyPr.unsetVert(); - } else { - bodyPr.setVert(STTextVerticalType.Enum.forInt(orientation.ordinal() + 1)); - } - } - } - - @Override - public TextDirection getTextDirection(){ - CTTextBodyProperties bodyPr = getTextBodyPr(); - if (bodyPr != null) { - STTextVerticalType.Enum val = bodyPr.getVert(); - if(val != null) { - switch (val.intValue()) { - default: - case STTextVerticalType.INT_HORZ: - return TextDirection.HORIZONTAL; - case STTextVerticalType.INT_EA_VERT: - case STTextVerticalType.INT_MONGOLIAN_VERT: - case STTextVerticalType.INT_VERT: - return TextDirection.VERTICAL; - case STTextVerticalType.INT_VERT_270: - return TextDirection.VERTICAL_270; - case STTextVerticalType.INT_WORD_ART_VERT_RTL: - case STTextVerticalType.INT_WORD_ART_VERT: - return TextDirection.STACKED; - } - } - } - return TextDirection.HORIZONTAL; - } - - @Override - public Double getTextRotation() { - CTTextBodyProperties bodyPr = getTextBodyPr(); - if (bodyPr != null && bodyPr.isSetRot()) { - return bodyPr.getRot() / 60000.; - } - return null; - } - - @Override - public void setTextRotation(Double rotation) { - CTTextBodyProperties bodyPr = getTextBodyPr(true); - if (bodyPr != null) { - bodyPr.setRot((int)(rotation * 60000.)); - } - } - - - /** - * Returns the distance (in points) between the bottom of the text frame - * and the bottom of the inscribed rectangle of the shape that contains the text. - * - * @return the bottom inset in points - */ - public double getBottomInset(){ - PropertyFetcher fetcher = new TextBodyPropertyFetcher(){ - public boolean fetch(CTTextBodyProperties props){ - if(props.isSetBIns()){ - double val = Units.toPoints(props.getBIns()); - setValue(val); - return true; - } - return false; - } - }; - fetchShapeProperty(fetcher); - // If this attribute is omitted, then a value of 0.05 inches is implied - return fetcher.getValue() == null ? 3.6 : fetcher.getValue(); - } - - /** - * Returns the distance (in points) between the left edge of the text frame - * and the left edge of the inscribed rectangle of the shape that contains - * the text. - * - * @return the left inset in points - */ - public double getLeftInset(){ - PropertyFetcher fetcher = new TextBodyPropertyFetcher(){ - public boolean fetch(CTTextBodyProperties props){ - if(props.isSetLIns()){ - double val = Units.toPoints(props.getLIns()); - setValue(val); - return true; - } - return false; - } - }; - fetchShapeProperty(fetcher); - // If this attribute is omitted, then a value of 0.1 inches is implied - return fetcher.getValue() == null ? 7.2 : fetcher.getValue(); - } - - /** - * Returns the distance (in points) between the right edge of the - * text frame and the right edge of the inscribed rectangle of the shape - * that contains the text. - * - * @return the right inset in points - */ - public double getRightInset(){ - PropertyFetcher fetcher = new TextBodyPropertyFetcher(){ - public boolean fetch(CTTextBodyProperties props){ - if(props.isSetRIns()){ - double val = Units.toPoints(props.getRIns()); - setValue(val); - return true; - } - return false; - } - }; - fetchShapeProperty(fetcher); - // If this attribute is omitted, then a value of 0.1 inches is implied - return fetcher.getValue() == null ? 7.2 : fetcher.getValue(); - } - - /** - * Returns the distance (in points) between the top of the text frame - * and the top of the inscribed rectangle of the shape that contains the text. - * - * @return the top inset in points - */ - public double getTopInset(){ - PropertyFetcher fetcher = new TextBodyPropertyFetcher(){ - public boolean fetch(CTTextBodyProperties props){ - if(props.isSetTIns()){ - double val = Units.toPoints(props.getTIns()); - setValue(val); - return true; - } - return false; - } - }; - fetchShapeProperty(fetcher); - // If this attribute is omitted, then a value of 0.05 inches is implied - return fetcher.getValue() == null ? 3.6 : fetcher.getValue(); - } - - /** - * Sets the bottom margin. - * @see #getBottomInset() - * - * @param margin the bottom margin - */ - public void setBottomInset(double margin){ - CTTextBodyProperties bodyPr = getTextBodyPr(true); - if (bodyPr != null) { - if(margin == -1) bodyPr.unsetBIns(); - else bodyPr.setBIns(Units.toEMU(margin)); - } - } - - /** - * Sets the left margin. - * @see #getLeftInset() - * - * @param margin the left margin - */ - public void setLeftInset(double margin){ - CTTextBodyProperties bodyPr = getTextBodyPr(true); - if (bodyPr != null) { - if(margin == -1) bodyPr.unsetLIns(); - else bodyPr.setLIns(Units.toEMU(margin)); - } - } - - /** - * Sets the right margin. - * @see #getRightInset() - * - * @param margin the right margin - */ - public void setRightInset(double margin){ - CTTextBodyProperties bodyPr = getTextBodyPr(true); - if (bodyPr != null) { - if(margin == -1) bodyPr.unsetRIns(); - else bodyPr.setRIns(Units.toEMU(margin)); - } - } - - /** - * Sets the top margin. - * @see #getTopInset() - * - * @param margin the top margin - */ - public void setTopInset(double margin){ - CTTextBodyProperties bodyPr = getTextBodyPr(true); - if (bodyPr != null) { - if(margin == -1) bodyPr.unsetTIns(); - else bodyPr.setTIns(Units.toEMU(margin)); - } - } - - @Override - public Insets2D getInsets() { - Insets2D insets = new Insets2D(getTopInset(), getLeftInset(), getBottomInset(), getRightInset()); - return insets; - } - - @Override - public void setInsets(Insets2D insets) { - setTopInset(insets.top); - setLeftInset(insets.left); - setBottomInset(insets.bottom); - setRightInset(insets.right); - } - - @Override - public boolean getWordWrap(){ - PropertyFetcher fetcher = new TextBodyPropertyFetcher(){ - public boolean fetch(CTTextBodyProperties props){ - if(props.isSetWrap()){ - setValue(props.getWrap() == STTextWrappingType.SQUARE); - return true; - } - return false; - } - }; - fetchShapeProperty(fetcher); - return fetcher.getValue() == null ? true : fetcher.getValue(); - } - - @Override - public void setWordWrap(boolean wrap){ - CTTextBodyProperties bodyPr = getTextBodyPr(true); - if (bodyPr != null) { - bodyPr.setWrap(wrap ? STTextWrappingType.SQUARE : STTextWrappingType.NONE); - } - } - - /** - * - * Specifies that a shape should be auto-fit to fully contain the text described within it. - * Auto-fitting is when text within a shape is scaled in order to contain all the text inside - * - * @param value type of autofit - */ - public void setTextAutofit(TextAutofit value){ - CTTextBodyProperties bodyPr = getTextBodyPr(true); - if (bodyPr != null) { - if(bodyPr.isSetSpAutoFit()) bodyPr.unsetSpAutoFit(); - if(bodyPr.isSetNoAutofit()) bodyPr.unsetNoAutofit(); - if(bodyPr.isSetNormAutofit()) bodyPr.unsetNormAutofit(); - - switch(value){ - case NONE: bodyPr.addNewNoAutofit(); break; - case NORMAL: bodyPr.addNewNormAutofit(); break; - case SHAPE: bodyPr.addNewSpAutoFit(); break; - } - } - } - - /** - * - * @return type of autofit - */ - public TextAutofit getTextAutofit(){ - CTTextBodyProperties bodyPr = getTextBodyPr(); - if (bodyPr != null) { - if(bodyPr.isSetNoAutofit()) return TextAutofit.NONE; - else if (bodyPr.isSetNormAutofit()) return TextAutofit.NORMAL; - else if (bodyPr.isSetSpAutoFit()) return TextAutofit.SHAPE; - } - return TextAutofit.NORMAL; - } - - protected CTTextBodyProperties getTextBodyPr(){ - return getTextBodyPr(false); - } - - protected CTTextBodyProperties getTextBodyPr(boolean create) { - CTTextBody textBody = getTextBody(create); - if (textBody == null) { - return null; - } - CTTextBodyProperties textBodyPr = textBody.getBodyPr(); - if (textBodyPr == null && create) { - textBodyPr = textBody.addNewBodyPr(); - } - return textBodyPr; - } - - protected abstract CTTextBody getTextBody(boolean create); - - @Override - public void setPlaceholder(Placeholder placeholder) { - super.setPlaceholder(placeholder); - } - - public Placeholder getTextType(){ - CTPlaceholder ph = getCTPlaceholder(); - if (ph == null) return null; - - int val = ph.getType().intValue(); - return Placeholder.lookupOoxml(val); - } - - @Override - public double getTextHeight(){ - DrawFactory drawFact = DrawFactory.getInstance(null); - DrawTextShape dts = drawFact.getDrawable(this); - return dts.getTextHeight(); - } - - /** - * Adjust the size of the shape so it encompasses the text inside it. - * - * @return a Rectangle2D that is the bounds of this shape. - */ - public Rectangle2D resizeToFitText(){ - Rectangle2D anchor = getAnchor(); - if(anchor.getWidth() == 0.) throw new POIXMLException( - "Anchor of the shape was not set."); - double height = getTextHeight(); - height += 1; // add a pixel to compensate rounding errors - - anchor.setRect(anchor.getX(), anchor.getY(), anchor.getWidth(), height); - setAnchor(anchor); - - return anchor; - } - - - @Override - void copy(XSLFShape other){ - super.copy(other); - - XSLFTextShape otherTS = (XSLFTextShape)other; - CTTextBody otherTB = otherTS.getTextBody(false); - CTTextBody thisTB = getTextBody(true); - if (otherTB == null) { - return; - } - - thisTB.setBodyPr((CTTextBodyProperties)otherTB.getBodyPr().copy()); - - if (thisTB.isSetLstStyle()) thisTB.unsetLstStyle(); - if (otherTB.isSetLstStyle()) { - thisTB.setLstStyle((CTTextListStyle)otherTB.getLstStyle().copy()); - } - - boolean srcWordWrap = otherTS.getWordWrap(); - if(srcWordWrap != getWordWrap()){ - setWordWrap(srcWordWrap); - } - - double leftInset = otherTS.getLeftInset(); - if(leftInset != getLeftInset()) { - setLeftInset(leftInset); - } - double rightInset = otherTS.getRightInset(); - if(rightInset != getRightInset()) { - setRightInset(rightInset); - } - double topInset = otherTS.getTopInset(); - if(topInset != getTopInset()) { - setTopInset(topInset); - } - double bottomInset = otherTS.getBottomInset(); - if(bottomInset != getBottomInset()) { - setBottomInset(bottomInset); - } - - VerticalAlignment vAlign = otherTS.getVerticalAlignment(); - if(vAlign != getVerticalAlignment()) { - setVerticalAlignment(vAlign); - } - - clearText(); - - for (XSLFTextParagraph srcP : otherTS.getTextParagraphs()) { - XSLFTextParagraph tgtP = addNewTextParagraph(); - tgtP.copy(srcP); - } - } - - @Override - public void setTextPlaceholder(TextPlaceholder placeholder) { - switch (placeholder) { - default: - case NOTES: - case HALF_BODY: - case QUARTER_BODY: - case BODY: - setPlaceholder(Placeholder.BODY); - break; - case TITLE: - setPlaceholder(Placeholder.TITLE); - break; - case CENTER_BODY: - setPlaceholder(Placeholder.BODY); - setHorizontalCentered(true); - break; - case CENTER_TITLE: - setPlaceholder(Placeholder.CENTERED_TITLE); - break; - case OTHER: - setPlaceholder(Placeholder.CONTENT); - break; - } - } - - @Override - public TextPlaceholder getTextPlaceholder() { - Placeholder ph = getTextType(); - if (ph == null) return TextPlaceholder.BODY; - switch (ph) { - case BODY: return TextPlaceholder.BODY; - case TITLE: return TextPlaceholder.TITLE; - case CENTERED_TITLE: return TextPlaceholder.CENTER_TITLE; - default: - case CONTENT: return TextPlaceholder.OTHER; - } - } - - /** - * Helper method to allow subclasses to provide their own text paragraph - * - * @param p the xml reference - * - * @return a new text paragraph - * - * @since POI 3.15-beta2 - */ - protected XSLFTextParagraph newTextParagraph(CTTextParagraph p) { - return new XSLFTextParagraph(p, this); - } -} \ No newline at end of file diff --git a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFTheme.java b/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFTheme.java deleted file mode 100644 index d3bd3a847..000000000 --- a/src/ooxml/java/org/apache/poi/xslf/usermodel/XSLFTheme.java +++ /dev/null @@ -1,172 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.usermodel; - -import static org.apache.poi.POIXMLTypeLoader.DEFAULT_XML_OPTIONS; - -import java.io.IOException; -import java.io.OutputStream; -import java.util.HashMap; -import java.util.Map; - -import javax.xml.namespace.QName; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.util.Beta; -import org.apache.poi.util.Internal; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlOptions; -import org.openxmlformats.schemas.drawingml.x2006.main.CTBaseStyles; -import org.openxmlformats.schemas.drawingml.x2006.main.CTColor; -import org.openxmlformats.schemas.drawingml.x2006.main.CTColorMapping; -import org.openxmlformats.schemas.drawingml.x2006.main.CTColorScheme; -import org.openxmlformats.schemas.drawingml.x2006.main.CTOfficeStyleSheet; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextParagraphProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.ThemeDocument; - -/** - * A shared style sheet in a .pptx slide show - * - * @author Yegor Kozlov - */ -@Beta -public class XSLFTheme extends POIXMLDocumentPart { - private CTOfficeStyleSheet _theme; - private Map _schemeColors; - - XSLFTheme() { - super(); - _theme = CTOfficeStyleSheet.Factory.newInstance(); - } - - /** - * @since POI 3.14-Beta1 - */ - public XSLFTheme(PackagePart part) throws IOException, XmlException { - super(part); - ThemeDocument doc = - ThemeDocument.Factory.parse(getPackagePart().getInputStream(), DEFAULT_XML_OPTIONS); - _theme = doc.getTheme(); - initialize(); - } - - public void importTheme(XSLFTheme theme) { - _theme = theme.getXmlObject(); - _schemeColors = theme._schemeColors; - } - - private void initialize(){ - CTBaseStyles elems = _theme.getThemeElements(); - CTColorScheme scheme = elems.getClrScheme(); - // The color scheme is responsible for defining a list of twelve colors. - _schemeColors = new HashMap(12); - for(XmlObject o : scheme.selectPath("*")){ - CTColor c = (CTColor)o; - String name = c.getDomNode().getLocalName(); - _schemeColors.put(name, c); - } - } - - /** - * re-map colors - * - * @param cmap color map defined in the master slide referencing this theme - */ - void initColorMap(CTColorMapping cmap) { - _schemeColors.put("bg1", _schemeColors.get(cmap.getBg1().toString())); - _schemeColors.put("bg2", _schemeColors.get(cmap.getBg2().toString())); - _schemeColors.put("tx1", _schemeColors.get(cmap.getTx1().toString())); - _schemeColors.put("tx2", _schemeColors.get(cmap.getTx2().toString())); - } - - /** - * - * @return name of this theme, e.g. "Office Theme" - */ - public String getName(){ - return _theme.getName(); - } - - /** - * Set name of this theme - * - * @param name name of this theme - */ - public void setName(String name){ - _theme.setName(name); - } - - /** - * Get a color from the theme's color scheme by name - * - * @return a theme color or null if not found - */ - CTColor getCTColor(String name){ - return _schemeColors.get(name); - } - - /** - * While developing only! - */ - @Internal - public CTOfficeStyleSheet getXmlObject() { - return _theme; - } - - protected final void commit() throws IOException { - XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS); - xmlOptions.setSaveSyntheticDocumentElement( - new QName("http://schemas.openxmlformats.org/drawingml/2006/main", "theme")); - - PackagePart part = getPackagePart(); - OutputStream out = part.getOutputStream(); - getXmlObject().save(out, xmlOptions); - out.close(); - } - - /** - * @return typeface of the major font to use in a document. - * Typically the major font is used for heading areas of a document. - * - */ - public String getMajorFont(){ - return _theme.getThemeElements().getFontScheme().getMajorFont().getLatin().getTypeface(); - } - - /** - * @return typeface of the minor font to use in a document. - * Typically the monor font is used for normal text or paragraph areas. - * - */ - public String getMinorFont(){ - return _theme.getThemeElements().getFontScheme().getMinorFont().getLatin().getTypeface(); - } - - - CTTextParagraphProperties getDefaultParagraphStyle(){ - XmlObject[] o = _theme.selectPath( - "declare namespace p='http://schemas.openxmlformats.org/presentationml/2006/main' " + - "declare namespace a='http://schemas.openxmlformats.org/drawingml/2006/main' " + - ".//a:objectDefaults/a:spDef/a:lstStyle/a:defPPr"); - if(o.length == 1){ - return (CTTextParagraphProperties)o[0]; - } - return null; - } -} diff --git a/src/ooxml/java/org/apache/poi/xslf/util/PPTX2PNG.java b/src/ooxml/java/org/apache/poi/xslf/util/PPTX2PNG.java deleted file mode 100644 index 31475410d..000000000 --- a/src/ooxml/java/org/apache/poi/xslf/util/PPTX2PNG.java +++ /dev/null @@ -1,214 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xslf.util; - -import java.awt.Dimension; -import java.awt.Graphics2D; -import java.awt.RenderingHints; -import java.awt.image.BufferedImage; -import java.io.File; -import java.util.List; -import java.util.Locale; -import java.util.Set; -import java.util.TreeSet; - -import javax.imageio.ImageIO; - -import org.apache.poi.sl.draw.DrawFactory; -import org.apache.poi.sl.usermodel.Slide; -import org.apache.poi.sl.usermodel.SlideShow; -import org.apache.poi.sl.usermodel.SlideShowFactory; - -/** - * An utility to convert slides of a .pptx slide show to a PNG image - * - * @author Yegor Kozlov - */ -public class PPTX2PNG { - - static void usage(String error){ - String msg = - "Usage: PPTX2PNG [options] \n" + - (error == null ? "" : ("Error: "+error+"\n")) + - "Options:\n" + - " -scale scale factor\n" + - " -slide 1-based index of a slide to render\n" + - " -format png,gif,jpg (,null for testing)" + - " -outdir output directory, defaults to origin of the ppt/pptx file" + - " -quiet do not write to console (for normal processing)"; - - System.out.println(msg); - // no System.exit here, as we also run in junit tests! - } - - public static void main(String[] args) throws Exception { - if (args.length == 0) { - usage(null); - return; - } - - String slidenumStr = "-1"; - float scale = 1; - File file = null; - String format = "png"; - File outdir = null; - boolean quiet = false; - - for (int i = 0; i < args.length; i++) { - if (args[i].startsWith("-")) { - if ("-scale".equals(args[i])) { - scale = Float.parseFloat(args[++i]); - } else if ("-slide".equals(args[i])) { - slidenumStr = args[++i]; - } else if ("-format".equals(args[i])) { - format = args[++i]; - } else if ("-outdir".equals(args[i])) { - outdir = new File(args[++i]); - } else if ("-quiet".equals(args[i])) { - quiet = true; - } - } else { - file = new File(args[i]); - } - } - - if (file == null || !file.exists()) { - usage("File not specified or it doesn't exist"); - return; - } - - if (format == null || !format.matches("^(png|gif|jpg|null)$")) { - usage("Invalid format given"); - return; - } - - if (outdir == null) { - outdir = file.getParentFile(); - } - - if (!"null".equals(format) && (outdir == null || !outdir.exists() || !outdir.isDirectory())) { - usage("Output directory doesn't exist"); - return; - } - - if (scale < 0) { - usage("Invalid scale given"); - return; - } - - if (!quiet) { - System.out.println("Processing " + file); - } - SlideShow ss = SlideShowFactory.create(file, null, true); - try { - List> slides = ss.getSlides(); - - Set slidenum = slideIndexes(slides.size(), slidenumStr); - - if (slidenum.isEmpty()) { - usage("slidenum must be either -1 (for all) or within range: [1.." + slides.size() + "] for " + file); - return; - } - - Dimension pgsize = ss.getPageSize(); - int width = (int) (pgsize.width * scale); - int height = (int) (pgsize.height * scale); - - for (Integer slideNo : slidenum) { - Slide slide = slides.get(slideNo); - String title = slide.getTitle(); - if (!quiet) { - System.out.println("Rendering slide " + slideNo + (title == null ? "" : ": " + title)); - } - - BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); - Graphics2D graphics = img.createGraphics(); - DrawFactory.getInstance(graphics).fixFonts(graphics); - - // default rendering options - graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); - graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); - graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); - - graphics.scale(scale, scale); - - // draw stuff - slide.draw(graphics); - - // save the result - if (!"null".equals(format)) { - String outname = file.getName().replaceFirst(".pptx?", ""); - outname = String.format(Locale.ROOT, "%1$s-%2$04d.%3$s", outname, slideNo, format); - File outfile = new File(outdir, outname); - ImageIO.write(img, format, outfile); - } - - graphics.dispose(); - img.flush(); - } - } finally { - ss.close(); - } - - if (!quiet) { - System.out.println("Done"); - } - } - - private static Set slideIndexes(final int slideCount, String range) { - Set slideIdx = new TreeSet(); - if ("-1".equals(range)) { - for (int i=0; i comments = new TreeMap(); - private Queue commentAddresses = new LinkedList(); - private List authors = new ArrayList(); - - //these are all used only during parsing, and they are mutable! - private int authorId = -1; - private CellAddress cellAddress = null; - private XSSFBCellRange cellRange = null; - private String comment = null; - private StringBuilder authorBuffer = new StringBuilder(); - - - public XSSFBCommentsTable(InputStream is) throws IOException { - super(is); - parse(); - commentAddresses.addAll(comments.keySet()); - } - - @Override - public void handleRecord(int id, byte[] data) throws XSSFBParseException { - XSSFBRecordType recordType = XSSFBRecordType.lookup(id); - switch (recordType) { - case BrtBeginComment: - int offset = 0; - authorId = XSSFBUtils.castToInt(LittleEndian.getUInt(data)); offset += LittleEndian.INT_SIZE; - cellRange = XSSFBCellRange.parse(data, offset, cellRange); - offset+= XSSFBCellRange.length; - //for strict parsing; confirm that firstRow==lastRow and firstCol==colLats (2.4.28) - cellAddress = new CellAddress(cellRange.firstRow, cellRange.firstCol); - break; - case BrtCommentText: - XSSFBRichStr xssfbRichStr = XSSFBRichStr.build(data, 0); - comment = xssfbRichStr.getString(); - break; - case BrtEndComment: - comments.put(cellAddress, new XSSFBComment(cellAddress, authors.get(authorId), comment)); - authorId = -1; - cellAddress = null; - break; - case BrtCommentAuthor: - authorBuffer.setLength(0); - XSSFBUtils.readXLWideString(data, 0, authorBuffer); - authors.add(authorBuffer.toString()); - break; - } - } - - - public Queue getAddresses() { - return commentAddresses; - } - - public XSSFBComment get(CellAddress cellAddress) { - if (cellAddress == null) { - return null; - } - return comments.get(cellAddress); - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/binary/XSSFBHeaderFooter.java b/src/ooxml/java/org/apache/poi/xssf/binary/XSSFBHeaderFooter.java deleted file mode 100644 index 674ed4410..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/binary/XSSFBHeaderFooter.java +++ /dev/null @@ -1,80 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.binary; - -import org.apache.poi.util.Internal; -import org.apache.poi.xssf.usermodel.helpers.HeaderFooterHelper; - -/** - * @since 3.16-beta3 - */ -@Internal -class XSSFBHeaderFooter { - - private static final HeaderFooterHelper HEADER_FOOTER_HELPER = new HeaderFooterHelper(); - - private final String headerFooterTypeLabel; - private final boolean isHeader; - private String rawString; - - - XSSFBHeaderFooter(String headerFooterTypeLabel, boolean isHeader) { - this.headerFooterTypeLabel = headerFooterTypeLabel; - this.isHeader = isHeader; - } - - String getHeaderFooterTypeLabel() { - return headerFooterTypeLabel; - } - - String getRawString() { - return rawString; - } - - String getString() { - StringBuilder sb = new StringBuilder(); - String left = HEADER_FOOTER_HELPER.getLeftSection(rawString); - String center = HEADER_FOOTER_HELPER.getCenterSection(rawString); - String right = HEADER_FOOTER_HELPER.getRightSection(rawString); - if (left != null && left.length() > 0) { - sb.append(left); - } - if (center != null && center.length() > 0) { - if (sb.length() > 0) { - sb.append(" "); - } - sb.append(center); - } - if (right != null && right.length() > 0) { - if (sb.length() > 0) { - sb.append(" "); - } - sb.append(right); - } - return sb.toString(); - } - - void setRawString(String rawString) { - this.rawString = rawString; - } - - boolean isHeader() { - return isHeader; - } - -} diff --git a/src/ooxml/java/org/apache/poi/xssf/binary/XSSFBHeaderFooters.java b/src/ooxml/java/org/apache/poi/xssf/binary/XSSFBHeaderFooters.java deleted file mode 100644 index a0e01832d..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/binary/XSSFBHeaderFooters.java +++ /dev/null @@ -1,91 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.binary; - -import org.apache.poi.util.Internal; - -/** - * @since 3.16-beta3 - */ -@Internal -class XSSFBHeaderFooters { - - public static XSSFBHeaderFooters parse(byte[] data) { - //parse these at some point. - boolean diffOddEven = false; - boolean diffFirst = false; - boolean scaleWDoc = false; - boolean alignMargins = false; - - int offset = 2; - XSSFBHeaderFooters xssfbHeaderFooter = new XSSFBHeaderFooters(); - xssfbHeaderFooter.header = new XSSFBHeaderFooter("header", true); - xssfbHeaderFooter.footer = new XSSFBHeaderFooter("footer", false); - xssfbHeaderFooter.headerEven = new XSSFBHeaderFooter("evenHeader", true); - xssfbHeaderFooter.footerEven = new XSSFBHeaderFooter("evenFooter", false); - xssfbHeaderFooter.headerFirst = new XSSFBHeaderFooter("firstHeader", true); - xssfbHeaderFooter.footerFirst = new XSSFBHeaderFooter("firstFooter", false); - offset += readHeaderFooter(data, offset, xssfbHeaderFooter.header); - offset += readHeaderFooter(data, offset, xssfbHeaderFooter.footer); - offset += readHeaderFooter(data, offset, xssfbHeaderFooter.headerEven); - offset += readHeaderFooter(data, offset, xssfbHeaderFooter.footerEven); - offset += readHeaderFooter(data, offset, xssfbHeaderFooter.headerFirst); - readHeaderFooter(data, offset, xssfbHeaderFooter.footerFirst); - return xssfbHeaderFooter; - } - - private static int readHeaderFooter(byte[] data, int offset, XSSFBHeaderFooter headerFooter) { - if (offset + 4 >= data.length) { - return 0; - } - StringBuilder sb = new StringBuilder(); - int bytesRead = XSSFBUtils.readXLNullableWideString(data, offset, sb); - headerFooter.setRawString(sb.toString()); - return bytesRead; - } - - private XSSFBHeaderFooter header; - private XSSFBHeaderFooter footer; - private XSSFBHeaderFooter headerEven; - private XSSFBHeaderFooter footerEven; - private XSSFBHeaderFooter headerFirst; - private XSSFBHeaderFooter footerFirst; - - public XSSFBHeaderFooter getHeader() { - return header; - } - - public XSSFBHeaderFooter getFooter() { - return footer; - } - - public XSSFBHeaderFooter getHeaderEven() { - return headerEven; - } - - public XSSFBHeaderFooter getFooterEven() { - return footerEven; - } - - public XSSFBHeaderFooter getHeaderFirst() { - return headerFirst; - } - - public XSSFBHeaderFooter getFooterFirst() { - return footerFirst; - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/binary/XSSFBHyperlinksTable.java b/src/ooxml/java/org/apache/poi/xssf/binary/XSSFBHyperlinksTable.java deleted file mode 100644 index 049245f39..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/binary/XSSFBHyperlinksTable.java +++ /dev/null @@ -1,184 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.binary; - -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.BitSet; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; - -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.opc.PackageRelationship; -import org.apache.poi.ss.util.CellAddress; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.CellRangeUtil; -import org.apache.poi.util.Internal; -import org.apache.poi.xssf.usermodel.XSSFRelation; - -/** - * @since 3.16-beta3 - */ -@Internal -public class XSSFBHyperlinksTable { - - private static final BitSet RECORDS = new BitSet(); - - - static { - RECORDS.set(XSSFBRecordType.BrtHLink.getId()); - } - - - private final List hyperlinkRecords = new ArrayList(); - - //cache the relId to hyperlink url from the sheet's .rels - private Map relIdToHyperlink = new HashMap(); - - public XSSFBHyperlinksTable(PackagePart sheetPart) throws IOException { - //load the urls from the sheet .rels - loadUrlsFromSheetRels(sheetPart); - //now load the hyperlinks from the bottom of the sheet - HyperlinkSheetScraper scraper = new HyperlinkSheetScraper(sheetPart.getInputStream()); - scraper.parse(); - } - - /** - * - * @return a map of the hyperlinks. The key is the top left cell address in their CellRange - */ - public Map> getHyperLinks() { - Map> hyperlinkMap = - new TreeMap>(new TopLeftCellAddressComparator()); - for (XSSFHyperlinkRecord hyperlinkRecord : hyperlinkRecords) { - CellAddress cellAddress = new CellAddress(hyperlinkRecord.getCellRangeAddress().getFirstRow(), - hyperlinkRecord.getCellRangeAddress().getFirstColumn()); - List list = hyperlinkMap.get(cellAddress); - if (list == null) { - list = new ArrayList(); - } - list.add(hyperlinkRecord); - hyperlinkMap.put(cellAddress, list); - } - return hyperlinkMap; - } - - - /** - * - * @param cellAddress cell address to find - * @return null if not a hyperlink - */ - public List findHyperlinkRecord(CellAddress cellAddress) { - List overlapping = null; - CellRangeAddress targetCellRangeAddress = new CellRangeAddress(cellAddress.getRow(), - cellAddress.getRow(), - cellAddress.getColumn(), - cellAddress.getColumn()); - for (XSSFHyperlinkRecord record : hyperlinkRecords) { - if (CellRangeUtil.intersect(targetCellRangeAddress, record.getCellRangeAddress()) != CellRangeUtil.NO_INTERSECTION) { - if (overlapping == null) { - overlapping = new ArrayList(); - } - overlapping.add(record); - } - } - return overlapping; - } - - private void loadUrlsFromSheetRels(PackagePart sheetPart) { - try { - for (PackageRelationship rel : sheetPart.getRelationshipsByType(XSSFRelation.SHEET_HYPERLINKS.getRelation())) { - relIdToHyperlink.put(rel.getId(), rel.getTargetURI().toString()); - } - } catch (InvalidFormatException e) { - //swallow - } - } - - private class HyperlinkSheetScraper extends XSSFBParser { - - private XSSFBCellRange hyperlinkCellRange = new XSSFBCellRange(); - private final StringBuilder xlWideStringBuffer = new StringBuilder(); - - HyperlinkSheetScraper(InputStream is) { - super(is, RECORDS); - } - - @Override - public void handleRecord(int recordType, byte[] data) throws XSSFBParseException { - if (recordType != XSSFBRecordType.BrtHLink.getId()) { - return; - } - int offset = 0; - String relId = ""; - String location = ""; - String toolTip = ""; - String display = ""; - - hyperlinkCellRange = XSSFBCellRange.parse(data, offset, hyperlinkCellRange); - offset += XSSFBCellRange.length; - xlWideStringBuffer.setLength(0); - offset += XSSFBUtils.readXLNullableWideString(data, offset, xlWideStringBuffer); - relId = xlWideStringBuffer.toString(); - xlWideStringBuffer.setLength(0); - offset += XSSFBUtils.readXLWideString(data, offset, xlWideStringBuffer); - location = xlWideStringBuffer.toString(); - xlWideStringBuffer.setLength(0); - offset += XSSFBUtils.readXLWideString(data, offset, xlWideStringBuffer); - toolTip = xlWideStringBuffer.toString(); - xlWideStringBuffer.setLength(0); - offset += XSSFBUtils.readXLWideString(data, offset, xlWideStringBuffer); - display = xlWideStringBuffer.toString(); - CellRangeAddress cellRangeAddress = new CellRangeAddress(hyperlinkCellRange.firstRow, hyperlinkCellRange.lastRow, hyperlinkCellRange.firstCol, hyperlinkCellRange.lastCol); - - String url = relIdToHyperlink.get(relId); - if (location == null || location.length() == 0) { - location = url; - } - - hyperlinkRecords.add( - new XSSFHyperlinkRecord(cellRangeAddress, relId, location, toolTip, display) - ); - } - } - - private static class TopLeftCellAddressComparator implements Comparator { - - @Override - public int compare(CellAddress o1, CellAddress o2) { - if (o1.getRow() < o2.getRow()) { - return -1; - } else if (o1.getRow() > o2.getRow()) { - return 1; - } - if (o1.getColumn() < o2.getColumn()) { - return -1; - } else if (o1.getColumn() > o2.getColumn()) { - return 1; - } - return 0; - } - } - -} diff --git a/src/ooxml/java/org/apache/poi/xssf/binary/XSSFBParseException.java b/src/ooxml/java/org/apache/poi/xssf/binary/XSSFBParseException.java deleted file mode 100644 index 7098bbe26..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/binary/XSSFBParseException.java +++ /dev/null @@ -1,30 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.binary; - -/** - * Parse exception while reading an xssfb. - * - * @since 3.16-beta3 - */ -public class XSSFBParseException extends RuntimeException { - - public XSSFBParseException(String msg) { - super(msg); - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/binary/XSSFBParser.java b/src/ooxml/java/org/apache/poi/xssf/binary/XSSFBParser.java deleted file mode 100644 index 4f4fc81ff..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/binary/XSSFBParser.java +++ /dev/null @@ -1,112 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.binary; - -import java.io.IOException; -import java.io.InputStream; -import java.util.BitSet; - -import org.apache.poi.util.Internal; -import org.apache.poi.util.LittleEndianInputStream; - -/** - * Experimental parser for Microsoft's ooxml xlsb format. - * Not thread safe, obviously. Need to create a new one - * for each thread. - * - * @since 3.16-beta3 - */ -@Internal -public abstract class XSSFBParser { - - private final LittleEndianInputStream is; - private final BitSet records; - - public XSSFBParser(InputStream is) { - this.is = new LittleEndianInputStream(is); - records = null; - } - - /** - * - * @param is inputStream - * @param bitSet call {@link #handleRecord(int, byte[])} only on those records in this bitSet - */ - XSSFBParser(InputStream is, BitSet bitSet) { - this.is = new LittleEndianInputStream(is); - records = bitSet; - } - - public void parse() throws IOException { - - while (true) { - int bInt = is.read(); - if (bInt == -1) { - return; - } - readNext((byte) bInt); - } - } - - private void readNext(byte b1) throws IOException { - int recordId = 0; - - //if highest bit == 1 - if ((b1 >> 7 & 1) == 1) { - byte b2 = is.readByte(); - b1 &= ~(1<<7); //unset highest bit - b2 &= ~(1<<7); //unset highest bit (if it exists?) - recordId = ((int)b2 << 7)+(int)b1; - } else { - recordId = (int)b1; - } - - long recordLength = 0; - int i = 0; - boolean halt = false; - while (i < 4 && ! halt) { - byte b = is.readByte(); - halt = (b >> 7 & 1) == 0; //if highest bit !=1 then continue - b &= ~(1<<7); - recordLength += (int)b << (i*7); //multiply by 128^i - i++; - - } - if (records == null || records.get(recordId)) { - //add sanity check for length? - byte[] buff = new byte[(int) recordLength]; - is.readFully(buff); - handleRecord(recordId, buff); - } else { - long length = is.skip(recordLength); - if (length != recordLength) { - throw new XSSFBParseException("End of file reached before expected.\t"+ - "Tried to skip "+recordLength + ", but only skipped "+length); - } - } - } - - //It hurts, hurts, hurts to create a new byte array for every record. - //However, on a large Excel spreadsheet, this parser was 1/3 faster than - //the ooxml sax parser (5 seconds for xssfb and 7.5 seconds for xssf. - //The code is far cleaner to have the parser read all - //of the data rather than having every component promise that it will read - //the correct amount. - abstract public void handleRecord(int recordType, byte[] data) throws XSSFBParseException; - -} diff --git a/src/ooxml/java/org/apache/poi/xssf/binary/XSSFBRecordType.java b/src/ooxml/java/org/apache/poi/xssf/binary/XSSFBRecordType.java deleted file mode 100644 index 354650430..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/binary/XSSFBRecordType.java +++ /dev/null @@ -1,109 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.binary; - -import java.util.HashMap; -import java.util.Map; - -import org.apache.poi.util.Internal; - -/** - * @since 3.16-beta3 - */ -@Internal -public enum XSSFBRecordType { - - BrtCellBlank(1), - BrtCellRk(2), - BrtCellError(3), - BrtCellBool(4), - BrtCellReal(5), - BrtCellSt(6), - BrtCellIsst(7), - BrtFmlaString(8), - BrtFmlaNum(9), - BrtFmlaBool(10), - BrtFmlaError(11), - BrtRowHdr(0), - BrtCellRString(62), - BrtBeginSheet(129), - BrtWsProp(147), - BrtWsDim(148), - BrtColInfo(60), - BrtBeginSheetData(145), - BrtEndSheetData(146), - BrtHLink(494), - BrtBeginHeaderFooter(479), - - //comments - BrtBeginCommentAuthors(630), - BrtEndCommentAuthors(631), - BrtCommentAuthor(632), - BrtBeginComment(635), - BrtCommentText(637), - BrtEndComment(636), - //styles table - BrtXf(47), - BrtFmt(44), - BrtBeginFmts(615), - BrtEndFmts(616), - BrtBeginCellXFs(617), - BrtEndCellXFs(618), - BrtBeginCellStyleXFS(626), - BrtEndCellStyleXFS(627), - - //stored strings table - BrtSstItem(19), //stored strings items - BrtBeginSst(159), //stored strings begin sst - BrtEndSst(160), //stored strings end sst - - BrtBundleSh(156), //defines worksheet in wb part - - //TODO -- implement these as needed - //BrtFileVersion(128), //file version - //BrtWbProp(153), //Workbook prop contains 1904/1900-date based bit - Unimplemented(-1); - - private static final Map TYPE_MAP = - new HashMap(); - - static { - for (XSSFBRecordType type : XSSFBRecordType.values()) { - TYPE_MAP.put(type.getId(), type); - } - } - - private final int id; - - XSSFBRecordType(int id) { - this.id = id; - } - - public int getId() { - return id; - } - - public static XSSFBRecordType lookup(int id) { - XSSFBRecordType type = TYPE_MAP.get(id); - if (type == null) { - return Unimplemented; - } - return type; - } - -} diff --git a/src/ooxml/java/org/apache/poi/xssf/binary/XSSFBRelation.java b/src/ooxml/java/org/apache/poi/xssf/binary/XSSFBRelation.java deleted file mode 100644 index 16cd7a414..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/binary/XSSFBRelation.java +++ /dev/null @@ -1,57 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.binary; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.POIXMLRelation; -import org.apache.poi.openxml4j.opc.PackageRelationshipTypes; -import org.apache.poi.util.Internal; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; - -/** - * Need to have this mirror class of {@link org.apache.poi.xssf.usermodel.XSSFRelation} - * because of conflicts with regular ooxml relations. - * If we failed to break this into a separate class, in the cases of SharedStrings and Styles, - * 2 parts would exist, and "Packages shall not contain equivalent part names..." - *

    - * Also, we need to avoid the possibility of breaking the marshalling process for xml. - */ -@Internal -public class XSSFBRelation extends POIXMLRelation { - private static final POILogger log = POILogFactory.getLogger(XSSFBRelation.class); - - static final XSSFBRelation SHARED_STRINGS_BINARY = new XSSFBRelation( - "application/vnd.ms-excel.sharedStrings", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings", - "/xl/sharedStrings.bin", - null - ); - - public static final XSSFBRelation STYLES_BINARY = new XSSFBRelation( - "application/vnd.ms-excel.styles", - PackageRelationshipTypes.STYLE_PART, - "/xl/styles.bin", - null - ); - - private XSSFBRelation(String type, String rel, String defaultName, Class cls) { - super(type, rel, defaultName, cls); - } - -} diff --git a/src/ooxml/java/org/apache/poi/xssf/binary/XSSFBRichStr.java b/src/ooxml/java/org/apache/poi/xssf/binary/XSSFBRichStr.java deleted file mode 100644 index 7e18a1a4d..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/binary/XSSFBRichStr.java +++ /dev/null @@ -1,50 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.binary; - -import org.apache.poi.util.Internal; - -/** - * @since 3.16-beta3 - */ -@Internal -class XSSFBRichStr { - - public static XSSFBRichStr build(byte[] bytes, int offset) throws XSSFBParseException { - byte first = bytes[offset]; - boolean dwSizeStrRunExists = (first >> 7 & 1) == 1;//first bit == 1? - boolean phoneticExists = (first >> 6 & 1) == 1;//second bit == 1? - StringBuilder sb = new StringBuilder(); - - int read = XSSFBUtils.readXLWideString(bytes, offset+1, sb); - //TODO: parse phonetic strings. - return new XSSFBRichStr(sb.toString(), ""); - } - - private final String string; - private final String phoneticString; - - XSSFBRichStr(String string, String phoneticString) { - this.string = string; - this.phoneticString = phoneticString; - } - - public String getString() { - return string; - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/binary/XSSFBRichTextString.java b/src/ooxml/java/org/apache/poi/xssf/binary/XSSFBRichTextString.java deleted file mode 100644 index 990dd41de..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/binary/XSSFBRichTextString.java +++ /dev/null @@ -1,91 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.binary; - -import org.apache.poi.ss.usermodel.Font; -import org.apache.poi.util.Internal; -import org.apache.poi.util.NotImplemented; -import org.apache.poi.xssf.usermodel.XSSFRichTextString; - -/** - * Wrapper class around String so that we can use it in Comment. - * Nothing has been implemented yet except for {@link #getString()}. - * - * @since 3.16-beta3 - */ -@Internal -class XSSFBRichTextString extends XSSFRichTextString { - - private final String string; - - XSSFBRichTextString(String string) { - this.string = string; - } - - @Override - @NotImplemented - public void applyFont(int startIndex, int endIndex, short fontIndex) { - - } - - @Override - @NotImplemented - public void applyFont(int startIndex, int endIndex, Font font) { - - } - - @Override - @NotImplemented - public void applyFont(Font font) { - - } - - @Override - @NotImplemented - public void clearFormatting() { - - } - - @Override - public String getString() { - return string; - } - - @Override - public int length() { - return string.length(); - } - - @Override - @NotImplemented - public int numFormattingRuns() { - return 0; - } - - @Override - @NotImplemented - public int getIndexOfFormattingRun(int index) { - return 0; - } - - @Override - @NotImplemented - public void applyFont(short fontIndex) { - - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/binary/XSSFBSharedStringsTable.java b/src/ooxml/java/org/apache/poi/xssf/binary/XSSFBSharedStringsTable.java deleted file mode 100644 index 2dc197841..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/binary/XSSFBSharedStringsTable.java +++ /dev/null @@ -1,144 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.binary; - - -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.util.Internal; -import org.apache.poi.util.LittleEndian; -import org.xml.sax.SAXException; - -/** - * @since 3.16-beta3 - */ -@Internal -public class XSSFBSharedStringsTable { - - /** - * An integer representing the total count of strings in the workbook. This count does not - * include any numbers, it counts only the total of text strings in the workbook. - */ - private int count; - - /** - * An integer representing the total count of unique strings in the Shared String Table. - * A string is unique even if it is a copy of another string, but has different formatting applied - * at the character level. - */ - private int uniqueCount; - - /** - * The shared strings table. - */ - private List strings = new ArrayList(); - - /** - * @param pkg The {@link OPCPackage} to use as basis for the shared-strings table. - * @throws IOException If reading the data from the package fails. - * @throws SAXException if parsing the XML data fails. - */ - public XSSFBSharedStringsTable(OPCPackage pkg) - throws IOException, SAXException { - ArrayList parts = - pkg.getPartsByContentType(XSSFBRelation.SHARED_STRINGS_BINARY.getContentType()); - - // Some workbooks have no shared strings table. - if (parts.size() > 0) { - PackagePart sstPart = parts.get(0); - - readFrom(sstPart.getInputStream()); - } - } - - /** - * Like POIXMLDocumentPart constructor - */ - XSSFBSharedStringsTable(PackagePart part) throws IOException, SAXException { - readFrom(part.getInputStream()); - } - - private void readFrom(InputStream inputStream) throws IOException { - SSTBinaryReader reader = new SSTBinaryReader(inputStream); - reader.parse(); - } - - /** - * - * @return a defensive copy of strings - */ - public List getItems() { - List ret = new ArrayList(strings.size()); - ret.addAll(strings); - return ret; - } - - public String getEntryAt(int i) { - return strings.get(i); - } - - /** - * Return an integer representing the total count of strings in the workbook. This count does not - * include any numbers, it counts only the total of text strings in the workbook. - * - * @return the total count of strings in the workbook - */ - public int getCount() { - return this.count; - } - - /** - * Returns an integer representing the total count of unique strings in the Shared String Table. - * A string is unique even if it is a copy of another string, but has different formatting applied - * at the character level. - * - * @return the total count of unique strings in the workbook - */ - public int getUniqueCount() { - return this.uniqueCount; - } - - private class SSTBinaryReader extends XSSFBParser { - - SSTBinaryReader(InputStream is) { - super(is); - } - - @Override - public void handleRecord(int recordType, byte[] data) throws XSSFBParseException { - XSSFBRecordType type = XSSFBRecordType.lookup(recordType); - - switch (type) { - case BrtSstItem: - XSSFBRichStr rstr = XSSFBRichStr.build(data, 0); - strings.add(rstr.getString()); - break; - case BrtBeginSst: - count = XSSFBUtils.castToInt(LittleEndian.getUInt(data,0)); - uniqueCount = XSSFBUtils.castToInt(LittleEndian.getUInt(data, 4)); - break; - } - - } - } - -} diff --git a/src/ooxml/java/org/apache/poi/xssf/binary/XSSFBSheetHandler.java b/src/ooxml/java/org/apache/poi/xssf/binary/XSSFBSheetHandler.java deleted file mode 100644 index def489f12..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/binary/XSSFBSheetHandler.java +++ /dev/null @@ -1,330 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.binary; - - -import java.io.InputStream; -import java.util.Queue; - -import org.apache.poi.ss.usermodel.DataFormatter; -import org.apache.poi.ss.util.CellAddress; -import org.apache.poi.util.Internal; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.xssf.eventusermodel.XSSFSheetXMLHandler; -import org.apache.poi.xssf.usermodel.XSSFComment; -import org.apache.poi.xssf.usermodel.XSSFRichTextString; - -/** - * @since 3.16-beta3 - */ -@Internal -public class XSSFBSheetHandler extends XSSFBParser { - - private static final int CHECK_ALL_ROWS = -1; - - private final XSSFBSharedStringsTable stringsTable; - private final XSSFSheetXMLHandler.SheetContentsHandler handler; - private final XSSFBStylesTable styles; - private final XSSFBCommentsTable comments; - private final DataFormatter dataFormatter; - private final boolean formulasNotResults;//TODO: implement this - - private int lastEndedRow = -1; - private int lastStartedRow = -1; - private int currentRow = 0; - private byte[] rkBuffer = new byte[8]; - private XSSFBCellRange hyperlinkCellRange = null; - private StringBuilder xlWideStringBuffer = new StringBuilder(); - - private final XSSFBCellHeader cellBuffer = new XSSFBCellHeader(); - public XSSFBSheetHandler(InputStream is, - XSSFBStylesTable styles, - XSSFBCommentsTable comments, - XSSFBSharedStringsTable strings, - XSSFSheetXMLHandler.SheetContentsHandler sheetContentsHandler, - DataFormatter dataFormatter, - boolean formulasNotResults) { - super(is); - this.styles = styles; - this.comments = comments; - this.stringsTable = strings; - this.handler = sheetContentsHandler; - this.dataFormatter = dataFormatter; - this.formulasNotResults = formulasNotResults; - } - - @Override - public void handleRecord(int id, byte[] data) throws XSSFBParseException { - XSSFBRecordType type = XSSFBRecordType.lookup(id); - - switch(type) { - case BrtRowHdr: - int rw = XSSFBUtils.castToInt(LittleEndian.getUInt(data, 0)); - if (rw > 0x00100000) {//could make sure this is larger than currentRow, according to spec? - throw new XSSFBParseException("Row number beyond allowable range: "+rw); - } - currentRow = rw; - checkMissedComments(currentRow); - startRow(currentRow); - break; - case BrtCellIsst: - handleBrtCellIsst(data); - break; - case BrtCellSt: //TODO: needs test - handleCellSt(data); - break; - case BrtCellRk: - handleCellRk(data); - break; - case BrtCellReal: - handleCellReal(data); - break; - case BrtCellBool: - handleBoolean(data); - break; - case BrtCellError: - handleCellError(data); - break; - case BrtCellBlank: - beforeCellValue(data);//read cell info and check for missing comments - break; - case BrtFmlaString: - handleFmlaString(data); - break; - case BrtFmlaNum: - handleFmlaNum(data); - break; - case BrtFmlaError: - handleFmlaError(data); - break; - //TODO: All the PCDI and PCDIA - case BrtEndSheetData: - checkMissedComments(CHECK_ALL_ROWS); - endRow(lastStartedRow); - break; - case BrtBeginHeaderFooter: - handleHeaderFooter(data); - break; - } - } - - - private void beforeCellValue(byte[] data) { - XSSFBCellHeader.parse(data, 0, currentRow, cellBuffer); - checkMissedComments(currentRow, cellBuffer.getColNum()); - } - - private void handleCellValue(String formattedValue) { - CellAddress cellAddress = new CellAddress(currentRow, cellBuffer.getColNum()); - XSSFBComment comment = null; - if (comments != null) { - comment = comments.get(cellAddress); - } - handler.cell(cellAddress.formatAsString(), formattedValue, comment); - } - - private void handleFmlaNum(byte[] data) { - beforeCellValue(data); - //xNum - double val = LittleEndian.getDouble(data, XSSFBCellHeader.length); - handleCellValue(formatVal(val, cellBuffer.getStyleIdx())); - } - - private void handleCellSt(byte[] data) { - beforeCellValue(data); - xlWideStringBuffer.setLength(0); - XSSFBUtils.readXLWideString(data, XSSFBCellHeader.length, xlWideStringBuffer); - handleCellValue(xlWideStringBuffer.toString()); - } - - private void handleFmlaString(byte[] data) { - beforeCellValue(data); - xlWideStringBuffer.setLength(0); - XSSFBUtils.readXLWideString(data, XSSFBCellHeader.length, xlWideStringBuffer); - handleCellValue(xlWideStringBuffer.toString()); - } - - private void handleCellError(byte[] data) { - beforeCellValue(data); - //TODO, read byte to figure out the type of error - handleCellValue("ERROR"); - } - - private void handleFmlaError(byte[] data) { - beforeCellValue(data); - //TODO, read byte to figure out the type of error - handleCellValue("ERROR"); - } - - private void handleBoolean(byte[] data) { - beforeCellValue(data); - String formattedVal = (data[XSSFBCellHeader.length] == 1) ? "TRUE" : "FALSE"; - handleCellValue(formattedVal); - } - - private void handleCellReal(byte[] data) { - beforeCellValue(data); - //xNum - double val = LittleEndian.getDouble(data, XSSFBCellHeader.length); - handleCellValue(formatVal(val, cellBuffer.getStyleIdx())); - } - - private void handleCellRk(byte[] data) { - beforeCellValue(data); - double val = rkNumber(data, XSSFBCellHeader.length); - handleCellValue(formatVal(val, cellBuffer.getStyleIdx())); - } - - private String formatVal(double val, int styleIdx) { - String formatString = styles.getNumberFormatString(styleIdx); - short styleIndex = styles.getNumberFormatIndex(styleIdx); - return dataFormatter.formatRawCellContents(val, styleIndex, formatString); - } - - private void handleBrtCellIsst(byte[] data) { - beforeCellValue(data); - int idx = XSSFBUtils.castToInt(LittleEndian.getUInt(data, XSSFBCellHeader.length)); - XSSFRichTextString rtss = new XSSFRichTextString(stringsTable.getEntryAt(idx)); - handleCellValue(rtss.getString()); - } - - - private void handleHeaderFooter(byte[] data) { - XSSFBHeaderFooters headerFooter = XSSFBHeaderFooters.parse(data); - outputHeaderFooter(headerFooter.getHeader()); - outputHeaderFooter(headerFooter.getFooter()); - outputHeaderFooter(headerFooter.getHeaderEven()); - outputHeaderFooter(headerFooter.getFooterEven()); - outputHeaderFooter(headerFooter.getHeaderFirst()); - outputHeaderFooter(headerFooter.getFooterFirst()); - } - - private void outputHeaderFooter(XSSFBHeaderFooter headerFooter) { - String text = headerFooter.getString(); - if (text != null && text.trim().length() > 0) { - handler.headerFooter(text, headerFooter.isHeader(), headerFooter.getHeaderFooterTypeLabel()); - } - } - - - //at start of next cell or end of row, return the cellAddress if it equals currentRow and col - private void checkMissedComments(int currentRow, int colNum) { - if (comments == null) { - return; - } - Queue queue = comments.getAddresses(); - while (queue.size() > 0) { - CellAddress cellAddress = queue.peek(); - if (cellAddress.getRow() == currentRow && cellAddress.getColumn() < colNum) { - cellAddress = queue.remove(); - dumpEmptyCellComment(cellAddress, comments.get(cellAddress)); - } else if (cellAddress.getRow() == currentRow && cellAddress.getColumn() == colNum) { - queue.remove(); - return; - } else if (cellAddress.getRow() == currentRow && cellAddress.getColumn() > colNum) { - return; - } else if (cellAddress.getRow() > currentRow) { - return; - } - } - } - - //check for anything from rows before - private void checkMissedComments(int currentRow) { - if (comments == null) { - return; - } - Queue queue = comments.getAddresses(); - int lastInterpolatedRow = -1; - while (queue.size() > 0) { - CellAddress cellAddress = queue.peek(); - if (currentRow == CHECK_ALL_ROWS || cellAddress.getRow() < currentRow) { - cellAddress = queue.remove(); - if (cellAddress.getRow() != lastInterpolatedRow) { - startRow(cellAddress.getRow()); - } - dumpEmptyCellComment(cellAddress, comments.get(cellAddress)); - lastInterpolatedRow = cellAddress.getRow(); - } else { - break; - } - } - - } - - private void startRow(int row) { - if (row == lastStartedRow) { - return; - } - - if (lastStartedRow != lastEndedRow) { - endRow(lastStartedRow); - } - handler.startRow(row); - lastStartedRow = row; - } - - private void endRow(int row) { - if (lastEndedRow == row) { - return; - } - handler.endRow(row); - lastEndedRow = row; - } - - private void dumpEmptyCellComment(CellAddress cellAddress, XSSFBComment comment) { - handler.cell(cellAddress.formatAsString(), null, comment); - } - - private double rkNumber(byte[] data, int offset) { - //see 2.5.122 for this abomination - byte b0 = data[offset]; - String s = Integer.toString(b0, 2); - boolean numDivBy100 = ((b0 & 1) == 1); // else as is - boolean floatingPoint = ((b0 >> 1 & 1) == 0); // else signed integer - - //unset highest 2 bits - b0 &= ~1; - b0 &= ~(1<<1); - - rkBuffer[4] = b0; - for (int i = 1; i < 4; i++) { - rkBuffer[i+4] = data[offset+i]; - } - double d = 0.0; - if (floatingPoint) { - d = LittleEndian.getDouble(rkBuffer); - } else { - d = LittleEndian.getInt(rkBuffer); - } - d = (numDivBy100) ? d/100 : d; - return d; - } - - /** - * You need to implement this to handle the results - * of the sheet parsing. - */ - public interface SheetContentsHandler extends XSSFSheetXMLHandler.SheetContentsHandler { - /** - * A cell, with the given formatted value (may be null), - * a url (may be null), a toolTip (may be null) - * and possibly a comment (may be null), was encountered */ - void hyperlinkCell(String cellReference, String formattedValue, String url, String toolTip, XSSFComment comment); - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/binary/XSSFBStylesTable.java b/src/ooxml/java/org/apache/poi/xssf/binary/XSSFBStylesTable.java deleted file mode 100644 index 583c9fcec..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/binary/XSSFBStylesTable.java +++ /dev/null @@ -1,112 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.binary; - -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; -import java.util.SortedMap; -import java.util.TreeMap; - -import org.apache.poi.POIXMLException; -import org.apache.poi.ss.usermodel.BuiltinFormats; -import org.apache.poi.util.Internal; - -/** - * This is a very thin shim to gather number formats from styles.bin - * files. - * - * @since 3.16-beta3 - */ -@Internal -public class XSSFBStylesTable extends XSSFBParser { - - private final SortedMap numberFormats = new TreeMap(); - private final List styleIds = new ArrayList(); - - private boolean inCellXFS = false; - private boolean inFmts = false; - public XSSFBStylesTable(InputStream is) throws IOException { - super(is); - parse(); - } - - String getNumberFormatString(int idx) { - short numberFormatIdx = getNumberFormatIndex(idx); - if (numberFormats.containsKey(numberFormatIdx)) { - return numberFormats.get(numberFormatIdx); - } - - return BuiltinFormats.getBuiltinFormat(numberFormatIdx); - } - - short getNumberFormatIndex(int idx) { - return styleIds.get(idx); - } - - @Override - public void handleRecord(int recordType, byte[] data) throws XSSFBParseException { - XSSFBRecordType type = XSSFBRecordType.lookup(recordType); - switch (type) { - case BrtBeginCellXFs: - inCellXFS = true; - break; - case BrtEndCellXFs: - inCellXFS = false; - break; - case BrtXf: - if (inCellXFS) { - handleBrtXFInCellXF(data); - } - break; - case BrtBeginFmts: - inFmts = true; - break; - case BrtEndFmts: - inFmts = false; - break; - case BrtFmt: - if (inFmts) { - handleFormat(data); - } - break; - - } - } - - private void handleFormat(byte[] data) { - int ifmt = data[0] & 0xFF; - if (ifmt > Short.MAX_VALUE) { - throw new POIXMLException("Format id must be a short"); - } - StringBuilder sb = new StringBuilder(); - XSSFBUtils.readXLWideString(data, 2, sb); - String fmt = sb.toString(); - numberFormats.put((short)ifmt, fmt); - } - - private void handleBrtXFInCellXF(byte[] data) { - int ifmtOffset = 2; - //int ifmtLength = 2; - - //numFmtId in xml terms - int ifmt = data[ifmtOffset] & 0xFF;//the second byte is ignored - styleIds.add((short)ifmt); - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/binary/XSSFBUtils.java b/src/ooxml/java/org/apache/poi/xssf/binary/XSSFBUtils.java deleted file mode 100644 index 448e50c0b..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/binary/XSSFBUtils.java +++ /dev/null @@ -1,111 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.binary; - - -import java.nio.charset.Charset; - -import org.apache.poi.POIXMLException; -import org.apache.poi.util.Internal; -import org.apache.poi.util.LittleEndian; - -/** - * @since 3.16-beta3 - */ -@Internal -public class XSSFBUtils { - - /** - * Reads an XLNullableWideString. - * @param data data from which to read - * @param offset in data from which to start - * @param sb buffer to which to write. You must setLength(0) before calling! - * @return number of bytes read - * @throws XSSFBParseException if there was an exception during reading - */ - static int readXLNullableWideString(byte[] data, int offset, StringBuilder sb) throws XSSFBParseException { - long numChars = LittleEndian.getUInt(data, offset); - if (numChars < 0) { - throw new XSSFBParseException("too few chars to read"); - } else if (numChars == 0xFFFFFFFFL) { //this means null value (2.5.166), do not read any bytes!!! - return 0; - } else if (numChars > 0xFFFFFFFFL) { - throw new XSSFBParseException("too many chars to read"); - } - - int numBytes = 2*(int)numChars; - offset += 4; - if (offset+numBytes > data.length) { - throw new XSSFBParseException("trying to read beyond data length:" + - "offset="+offset+", numBytes="+numBytes+", data.length="+data.length); - } - sb.append(new String(data, offset, numBytes, Charset.forName("UTF-16LE"))); - numBytes+=4; - return numBytes; - } - - - /** - * Reads an XLNullableWideString. - * @param data data from which to read - * @param offset in data from which to start - * @param sb buffer to which to write. You must setLength(0) before calling! - * @return number of bytes read - * @throws XSSFBParseException if there was an exception while trying to read the string - */ - public static int readXLWideString(byte[] data, int offset, StringBuilder sb) throws XSSFBParseException { - long numChars = LittleEndian.getUInt(data, offset); - if (numChars < 0) { - throw new XSSFBParseException("too few chars to read"); - } else if (numChars > 0xFFFFFFFFL) { - throw new XSSFBParseException("too many chars to read"); - } - int numBytes = 2*(int)numChars; - offset += 4; - if (offset+numBytes > data.length) { - throw new XSSFBParseException("trying to read beyond data length"); - } - sb.append(new String(data, offset, numBytes, Charset.forName("UTF-16LE"))); - numBytes+=4; - return numBytes; - } - - static int castToInt(long val) { - if (val < Integer.MAX_VALUE && val > Integer.MIN_VALUE) { - return (int)val; - } - throw new POIXMLException("val ("+val+") can't be cast to int"); - } - - static short castToShort(int val) { - if (val < Short.MAX_VALUE && val > Short.MIN_VALUE) { - return (short)val; - } - throw new POIXMLException("val ("+val+") can't be cast to short"); - - } - - //TODO: move to LittleEndian? - static int get24BitInt( byte[] data, int offset) { - int i = offset; - int b0 = data[i++] & 0xFF; - int b1 = data[i++] & 0xFF; - int b2 = data[i] & 0xFF; - return ( b2 << 16 ) + ( b1 << 8 ) + b0; - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/binary/XSSFHyperlinkRecord.java b/src/ooxml/java/org/apache/poi/xssf/binary/XSSFHyperlinkRecord.java deleted file mode 100644 index e2ac4df12..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/binary/XSSFHyperlinkRecord.java +++ /dev/null @@ -1,118 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.binary; - -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.util.Internal; - -/** - * This is a read only record that maintains information about - * a hyperlink. In OOXML land, this information has to be merged - * from 1) the sheet's .rels to get the url and 2) from after the - * sheet data in they hyperlink section. - * - * The {@link #display} is often empty and should be filled from - * the contents of the anchor cell. - * - * @since 3.16-beta3 - */ -@Internal -public class XSSFHyperlinkRecord { - - private final CellRangeAddress cellRangeAddress; - private final String relId; - private String location; - private String toolTip; - private String display; - - XSSFHyperlinkRecord(CellRangeAddress cellRangeAddress, String relId, String location, String toolTip, String display) { - this.cellRangeAddress = cellRangeAddress; - this.relId = relId; - this.location = location; - this.toolTip = toolTip; - this.display = display; - } - - void setLocation(String location) { - this.location = location; - } - - void setToolTip(String toolTip) { - this.toolTip = toolTip; - } - - void setDisplay(String display) { - this.display = display; - } - - CellRangeAddress getCellRangeAddress() { - return cellRangeAddress; - } - - public String getRelId() { - return relId; - } - - public String getLocation() { - return location; - } - - public String getToolTip() { - return toolTip; - } - - public String getDisplay() { - return display; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - XSSFHyperlinkRecord that = (XSSFHyperlinkRecord) o; - - if (cellRangeAddress != null ? !cellRangeAddress.equals(that.cellRangeAddress) : that.cellRangeAddress != null) - return false; - if (relId != null ? !relId.equals(that.relId) : that.relId != null) return false; - if (location != null ? !location.equals(that.location) : that.location != null) return false; - if (toolTip != null ? !toolTip.equals(that.toolTip) : that.toolTip != null) return false; - return display != null ? display.equals(that.display) : that.display == null; - } - - @Override - public int hashCode() { - int result = cellRangeAddress != null ? cellRangeAddress.hashCode() : 0; - result = 31 * result + (relId != null ? relId.hashCode() : 0); - result = 31 * result + (location != null ? location.hashCode() : 0); - result = 31 * result + (toolTip != null ? toolTip.hashCode() : 0); - result = 31 * result + (display != null ? display.hashCode() : 0); - return result; - } - - @Override - public String toString() { - return "XSSFHyperlinkRecord{" + - "cellRangeAddress=" + cellRangeAddress + - ", relId='" + relId + '\'' + - ", location='" + location + '\'' + - ", toolTip='" + toolTip + '\'' + - ", display='" + display + '\'' + - '}'; - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/binary/package.html b/src/ooxml/java/org/apache/poi/xssf/binary/package.html deleted file mode 100644 index 21a30e1df..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/binary/package.html +++ /dev/null @@ -1,44 +0,0 @@ - - - - - - - -

    The org.apache.poi.xssf.binary package includes necessary underlying components -for streaming/read-only processing of xlsb files. -

    -

    - POI does not yet support opening .xlsb files with XSSFWorkbook, but you can read files with XSSFBReader - in org.apache.poi.xssf.eventusermodel. -

    -

    - This feature was added in poi-3.16-beta3 and should be considered experimental. Most classes - have been marked @Internal and the API is subject to change. -

    -

    Related Documentation

    - -For overviews, tutorials, examples, guides, and tool documentation, please see: - - - - diff --git a/src/ooxml/java/org/apache/poi/xssf/dev/XSSFDump.java b/src/ooxml/java/org/apache/poi/xssf/dev/XSSFDump.java deleted file mode 100644 index ffe9d2a73..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/dev/XSSFDump.java +++ /dev/null @@ -1,114 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.dev; - -import static org.apache.poi.POIXMLTypeLoader.DEFAULT_XML_OPTIONS; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.OutputStream; -import java.util.Enumeration; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; - -import org.apache.poi.openxml4j.opc.internal.ZipHelper; -import org.apache.poi.util.DocumentHelper; -import org.apache.poi.util.IOUtils; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlOptions; -import org.w3c.dom.Document; - -/** - * Utility class which dumps the contents of a *.xlsx file into file system. - * - * @author Yegor Kozlov - */ -public final class XSSFDump { - - public static void main(String[] args) throws Exception { - for (int i = 0; i < args.length; i++) { - System.out.println("Dumping " + args[i]); - ZipFile zip = ZipHelper.openZipFile(args[i]); - try { - dump(zip); - } finally { - zip.close(); - } - } - } - - private static void createDirIfMissing(File directory) throws RuntimeException { - if (!directory.exists()) { - boolean dirWasCreated = directory.mkdir(); - if (!dirWasCreated) { - throw new RuntimeException("Unable to create directory: " + directory); - } - } - } - - private static void recursivelyCreateDirIfMissing(File directory) throws RuntimeException { - if (!directory.exists()) { - boolean dirsWereCreated = directory.mkdirs(); - if (!dirsWereCreated) { - throw new RuntimeException("Unable to recursively create directory: " + directory); - } - } - } - - - public static void dump(ZipFile zip) throws Exception { - String zipname = zip.getName(); - int sep = zipname.lastIndexOf('.'); - File root = new File(zipname.substring(0, sep)); - createDirIfMissing(root); - System.out.println("Dumping to directory " + root); - - Enumeration en = zip.entries(); - while (en.hasMoreElements()) { - ZipEntry entry = en.nextElement(); - String name = entry.getName(); - int idx = name.lastIndexOf('/'); - if (idx != -1) { - File bs = new File(root, name.substring(0, idx)); - recursivelyCreateDirIfMissing(bs); - } - - File f = new File(root, entry.getName()); - OutputStream out = new FileOutputStream(f); - try { - if (entry.getName().endsWith(".xml") || entry.getName().endsWith(".vml") || entry.getName().endsWith(".rels")) { - try { - Document doc = DocumentHelper.readDocument(zip.getInputStream(entry)); - XmlObject xml = XmlObject.Factory.parse(doc, DEFAULT_XML_OPTIONS); - XmlOptions options = new XmlOptions(); - options.setSavePrettyPrint(); - xml.save(out, options); - } catch (XmlException e) { - System.err.println("Failed to parse " + entry.getName() + ", dumping raw content"); - IOUtils.copy(zip.getInputStream(entry), out); - } - } else { - IOUtils.copy(zip.getInputStream(entry), out); - } - } finally { - out.close(); - } - } - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/dev/XSSFSave.java b/src/ooxml/java/org/apache/poi/xssf/dev/XSSFSave.java deleted file mode 100644 index 1660f452a..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/dev/XSSFSave.java +++ /dev/null @@ -1,47 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.dev; - -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -import java.io.FileOutputStream; - -/** - * Utility which loads a SpreadsheetML file and saves it back. - * This is a handy tool to investigate read-write round trip safety. - * - * @author Yegor Kozlov - */ -public final class XSSFSave { - public static void main(String[] args) throws Exception { - for (int i = 0; i < args.length; i++) { - OPCPackage pkg = OPCPackage.open(args[i]); - XSSFWorkbook wb = new XSSFWorkbook(pkg); - - int sep = args[i].lastIndexOf('.'); - String outfile = args[i].substring(0, sep) + "-save.xls" + (wb.isMacroEnabled() ? "m" : "x"); - FileOutputStream out = new FileOutputStream(outfile); - wb.write(out); - out.close(); - - pkg.close(); - } - } - -} diff --git a/src/ooxml/java/org/apache/poi/xssf/eventusermodel/ReadOnlySharedStringsTable.java b/src/ooxml/java/org/apache/poi/xssf/eventusermodel/ReadOnlySharedStringsTable.java deleted file mode 100644 index a482049b6..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/eventusermodel/ReadOnlySharedStringsTable.java +++ /dev/null @@ -1,286 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.eventusermodel; - -import static org.apache.poi.xssf.usermodel.XSSFRelation.NS_SPREADSHEETML; - -import javax.xml.parsers.ParserConfigurationException; -import java.io.IOException; -import java.io.InputStream; -import java.io.PushbackInputStream; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.util.SAXHelper; -import org.apache.poi.xssf.usermodel.XSSFRelation; -import org.xml.sax.Attributes; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; -import org.xml.sax.XMLReader; -import org.xml.sax.helpers.DefaultHandler; - -/** - *

    This is a lightweight way to process the Shared Strings - * table. Most of the text cells will reference something - * from in here. - *

    Note that each SI entry can have multiple T elements, if the - * string is made up of bits with different formatting. - *

    Example input: - *

    -<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
    -<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" count="2" uniqueCount="2">
    - <si>
    -   <r>
    -     <rPr>
    -       <b />
    -       <sz val="11" />
    -       <color theme="1" />
    -       <rFont val="Calibri" />
    -       <family val="2" />
    -       <scheme val="minor" />
    -     </rPr>
    -     <t>This:</t>
    -   </r>
    -   <r>
    -     <rPr>
    -       <sz val="11" />
    -       <color theme="1" />
    -       <rFont val="Calibri" />
    -       <family val="2" />
    -       <scheme val="minor" />
    -     </rPr>
    -     <t xml:space="preserve">Causes Problems</t>
    -   </r>
    - </si>
    - <si>
    -   <t>This does not</t>
    - </si>
    -</sst>
    -* 
    - * - */ -public class ReadOnlySharedStringsTable extends DefaultHandler { - - private final boolean includePhoneticRuns; - /** - * An integer representing the total count of strings in the workbook. This count does not - * include any numbers, it counts only the total of text strings in the workbook. - */ - private int count; - - /** - * An integer representing the total count of unique strings in the Shared String Table. - * A string is unique even if it is a copy of another string, but has different formatting applied - * at the character level. - */ - private int uniqueCount; - - /** - * The shared strings table. - */ - private List strings; - - /** - * Map of phonetic strings (if they exist) indexed - * with the integer matching the index in strings - */ - private Map phoneticStrings; - - /** - * Calls {{@link #ReadOnlySharedStringsTable(OPCPackage, boolean)}} with - * a value of true for including phonetic runs - * - * @param pkg The {@link OPCPackage} to use as basis for the shared-strings table. - * @throws IOException If reading the data from the package fails. - * @throws SAXException if parsing the XML data fails. - */ - public ReadOnlySharedStringsTable(OPCPackage pkg) - throws IOException, SAXException { - this(pkg, true); - } - - /** - * - * @param pkg The {@link OPCPackage} to use as basis for the shared-strings table. - * @param includePhoneticRuns whether or not to concatenate phoneticRuns onto the shared string - * @since POI 3.14-Beta3 - * @throws IOException If reading the data from the package fails. - * @throws SAXException if parsing the XML data fails. - */ - public ReadOnlySharedStringsTable(OPCPackage pkg, boolean includePhoneticRuns) - throws IOException, SAXException { - this.includePhoneticRuns = includePhoneticRuns; - ArrayList parts = - pkg.getPartsByContentType(XSSFRelation.SHARED_STRINGS.getContentType()); - - // Some workbooks have no shared strings table. - if (parts.size() > 0) { - PackagePart sstPart = parts.get(0); - readFrom(sstPart.getInputStream()); - } - } - - /** - * Like POIXMLDocumentPart constructor - * - * Calls {@link #ReadOnlySharedStringsTable(PackagePart, boolean)}, with a - * value of true to include phonetic runs. - * - * @since POI 3.14-Beta1 - */ - public ReadOnlySharedStringsTable(PackagePart part) throws IOException, SAXException { - this(part, true); - } - - /** - * Like POIXMLDocumentPart constructor - * - * @since POI 3.14-Beta3 - */ - public ReadOnlySharedStringsTable(PackagePart part, boolean includePhoneticRuns) - throws IOException, SAXException { - this.includePhoneticRuns = includePhoneticRuns; - readFrom(part.getInputStream()); - } - - /** - * Read this shared strings table from an XML file. - * - * @param is The input stream containing the XML document. - * @throws IOException if an error occurs while reading. - * @throws SAXException if parsing the XML data fails. - */ - public void readFrom(InputStream is) throws IOException, SAXException { - // test if the file is empty, otherwise parse it - PushbackInputStream pis = new PushbackInputStream(is, 1); - int emptyTest = pis.read(); - if (emptyTest > -1) { - pis.unread(emptyTest); - InputSource sheetSource = new InputSource(pis); - try { - XMLReader sheetParser = SAXHelper.newXMLReader(); - sheetParser.setContentHandler(this); - sheetParser.parse(sheetSource); - } catch(ParserConfigurationException e) { - throw new RuntimeException("SAX parser appears to be broken - " + e.getMessage()); - } - } - } - - /** - * Return an integer representing the total count of strings in the workbook. This count does not - * include any numbers, it counts only the total of text strings in the workbook. - * - * @return the total count of strings in the workbook - */ - public int getCount() { - return this.count; - } - - /** - * Returns an integer representing the total count of unique strings in the Shared String Table. - * A string is unique even if it is a copy of another string, but has different formatting applied - * at the character level. - * - * @return the total count of unique strings in the workbook - */ - public int getUniqueCount() { - return this.uniqueCount; - } - - /** - * Return the string at a given index. - * Formatting is ignored. - * - * @param idx index of item to return. - * @return the item at the specified position in this Shared String table. - */ - public String getEntryAt(int idx) { - return strings.get(idx); - } - - public List getItems() { - return strings; - } - - //// ContentHandler methods //// - - private StringBuffer characters; - private boolean tIsOpen; - private boolean inRPh; - - public void startElement(String uri, String localName, String name, - Attributes attributes) throws SAXException { - if (uri != null && ! uri.equals(NS_SPREADSHEETML)) { - return; - } - - if ("sst".equals(localName)) { - String count = attributes.getValue("count"); - if(count != null) this.count = Integer.parseInt(count); - String uniqueCount = attributes.getValue("uniqueCount"); - if(uniqueCount != null) this.uniqueCount = Integer.parseInt(uniqueCount); - - this.strings = new ArrayList(this.uniqueCount); - this.phoneticStrings = new HashMap(); - characters = new StringBuffer(); - } else if ("si".equals(localName)) { - characters.setLength(0); - } else if ("t".equals(localName)) { - tIsOpen = true; - } else if ("rPh".equals(localName)) { - inRPh = true; - //append space...this assumes that rPh always comes after regular - if (includePhoneticRuns && characters.length() > 0) { - characters.append(" "); - } - } - } - - public void endElement(String uri, String localName, String name) - throws SAXException { - if (uri != null && ! uri.equals(NS_SPREADSHEETML)) { - return; - } - - if ("si".equals(localName)) { - strings.add(characters.toString()); - } else if ("t".equals(localName)) { - tIsOpen = false; - } else if ("rPh".equals(localName)) { - inRPh = false; - } - } - - /** - * Captures characters only if a t(ext) element is open. - */ - public void characters(char[] ch, int start, int length) - throws SAXException { - if (tIsOpen) { - if (inRPh && includePhoneticRuns) { - characters.append(ch, start, length); - } else if (! inRPh){ - characters.append(ch, start, length); - } - } - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/eventusermodel/XSSFBReader.java b/src/ooxml/java/org/apache/poi/xssf/eventusermodel/XSSFBReader.java deleted file mode 100644 index 825422936..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/eventusermodel/XSSFBReader.java +++ /dev/null @@ -1,218 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.eventusermodel; - -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; - -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.exceptions.OpenXML4JException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.opc.PackagePartName; -import org.apache.poi.openxml4j.opc.PackageRelationship; -import org.apache.poi.openxml4j.opc.PackageRelationshipCollection; -import org.apache.poi.openxml4j.opc.PackagingURIHelper; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.xssf.binary.XSSFBCommentsTable; -import org.apache.poi.xssf.binary.XSSFBParseException; -import org.apache.poi.xssf.binary.XSSFBParser; -import org.apache.poi.xssf.binary.XSSFBRecordType; -import org.apache.poi.xssf.binary.XSSFBRelation; -import org.apache.poi.xssf.binary.XSSFBStylesTable; -import org.apache.poi.xssf.binary.XSSFBUtils; -import org.apache.poi.xssf.model.CommentsTable; -import org.apache.poi.xssf.usermodel.XSSFRelation; - -/** - * Reader for xlsb files. - * - * @since 3.16-beta3 - */ -public class XSSFBReader extends XSSFReader { - - private final static POILogger log = POILogFactory.getLogger(XSSFBReader.class); - - /** - * Creates a new XSSFReader, for the given package - * - * @param pkg opc package - */ - public XSSFBReader(OPCPackage pkg) throws IOException, OpenXML4JException { - super(pkg); - } - - /** - * Returns an Iterator which will let you get at all the - * different Sheets in turn. - * Each sheet's InputStream is only opened when fetched - * from the Iterator. It's up to you to close the - * InputStreams when done with each one. - */ - @Override - public Iterator getSheetsData() throws IOException, InvalidFormatException { - return new SheetIterator(workbookPart); - } - - public XSSFBStylesTable getXSSFBStylesTable() throws IOException { - ArrayList parts = pkg.getPartsByContentType(XSSFBRelation.STYLES_BINARY.getContentType()); - if(parts.size() == 0) return null; - - // Create the Styles Table, and associate the Themes if present - return new XSSFBStylesTable(parts.get(0).getInputStream()); - - } - - - public static class SheetIterator extends XSSFReader.SheetIterator { - - /** - * Construct a new SheetIterator - * - * @param wb package part holding workbook.xml - */ - private SheetIterator(PackagePart wb) throws IOException { - super(wb); - } - - Iterator createSheetIteratorFromWB(PackagePart wb) throws IOException { - SheetRefLoader sheetRefLoader = new SheetRefLoader(wb.getInputStream()); - sheetRefLoader.parse(); - return sheetRefLoader.getSheets().iterator(); - } - - /** - * Not supported by XSSFBReader's SheetIterator. - * Please use {@link #getXSSFBSheetComments()} instead. - * @return nothing, always throws IllegalArgumentException! - */ - @Override - public CommentsTable getSheetComments() { - throw new IllegalArgumentException("Please use getXSSFBSheetComments"); - } - - public XSSFBCommentsTable getXSSFBSheetComments() { - PackagePart sheetPkg = getSheetPart(); - - // Do we have a comments relationship? (Only ever one if so) - try { - PackageRelationshipCollection commentsList = - sheetPkg.getRelationshipsByType(XSSFRelation.SHEET_COMMENTS.getRelation()); - if (commentsList.size() > 0) { - PackageRelationship comments = commentsList.getRelationship(0); - if (comments == null || comments.getTargetURI() == null) { - return null; - } - PackagePartName commentsName = PackagingURIHelper.createPartName(comments.getTargetURI()); - PackagePart commentsPart = sheetPkg.getPackage().getPart(commentsName); - return new XSSFBCommentsTable(commentsPart.getInputStream()); - } - } catch (InvalidFormatException e) { - return null; - } catch (IOException e) { - return null; - } - return null; - } - - } - - private static class SheetRefLoader extends XSSFBParser { - List sheets = new LinkedList(); - - private SheetRefLoader(InputStream is) { - super(is); - } - - @Override - public void handleRecord(int recordType, byte[] data) throws XSSFBParseException { - if (recordType == XSSFBRecordType.BrtBundleSh.getId()) { - addWorksheet(data); - } - } - - private void addWorksheet(byte[] data) { - //try to parse the BrtBundleSh - //if there's an exception, catch it and - //try to figure out if this is one of the old beta-created xlsb files - //or if this is a general exception - try { - tryToAddWorksheet(data); - } catch (XSSFBParseException e) { - if (tryOldFormat(data)) { - log.log(POILogger.WARN, "This file was written with a beta version of Excel. "+ - "POI will try to parse the file as a regular xlsb."); - } else { - throw e; - } - } - } - - private void tryToAddWorksheet(byte[] data) throws XSSFBParseException { - int offset = 0; - //this is the sheet state #2.5.142 - long hsShtat = LittleEndian.getUInt(data, offset); offset += LittleEndian.INT_SIZE; - - long iTabID = LittleEndian.getUInt(data, offset); offset += LittleEndian.INT_SIZE; - //according to #2.4.304 - if (iTabID < 1 || iTabID > 0x0000FFFFL) { - throw new XSSFBParseException("table id out of range: "+iTabID); - } - StringBuilder sb = new StringBuilder(); - offset += XSSFBUtils.readXLWideString(data, offset, sb); - String relId = sb.toString(); sb.setLength(0); - offset += XSSFBUtils.readXLWideString(data, offset, sb); - String name = sb.toString(); - if (relId != null && relId.trim().length() > 0) { - sheets.add(new XSSFSheetRef(relId, name)); - } - } - - private boolean tryOldFormat(byte[] data) throws XSSFBParseException { - //undocumented what is contained in these 8 bytes. - //for the non-beta xlsb files, this would be 4, not 8. - int offset = 8; - long iTabID = LittleEndian.getUInt(data, offset); offset += LittleEndian.INT_SIZE; - if (iTabID < 1 || iTabID > 0x0000FFFFL) { - throw new XSSFBParseException("table id out of range: "+iTabID); - } - StringBuilder sb = new StringBuilder(); - offset += XSSFBUtils.readXLWideString(data, offset, sb); - String relId = sb.toString(); - sb.setLength(0); - offset += XSSFBUtils.readXLWideString(data, offset, sb); - String name = sb.toString(); - if (relId != null && relId.trim().length() > 0) { - sheets.add(new XSSFSheetRef(relId, name)); - } - if (offset == data.length) { - return true; - } - return false; - } - - List getSheets() { - return sheets; - } - } -} \ No newline at end of file diff --git a/src/ooxml/java/org/apache/poi/xssf/eventusermodel/XSSFReader.java b/src/ooxml/java/org/apache/poi/xssf/eventusermodel/XSSFReader.java deleted file mode 100644 index 08dfaa6ff..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/eventusermodel/XSSFReader.java +++ /dev/null @@ -1,430 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.eventusermodel; - -import javax.xml.parsers.ParserConfigurationException; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import org.apache.poi.POIXMLException; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.exceptions.OpenXML4JException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.opc.PackagePartName; -import org.apache.poi.openxml4j.opc.PackageRelationship; -import org.apache.poi.openxml4j.opc.PackageRelationshipCollection; -import org.apache.poi.openxml4j.opc.PackageRelationshipTypes; -import org.apache.poi.openxml4j.opc.PackagingURIHelper; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.util.SAXHelper; -import org.apache.poi.xssf.model.CommentsTable; -import org.apache.poi.xssf.model.SharedStringsTable; -import org.apache.poi.xssf.model.StylesTable; -import org.apache.poi.xssf.model.ThemesTable; -import org.apache.poi.xssf.usermodel.XSSFDrawing; -import org.apache.poi.xssf.usermodel.XSSFRelation; -import org.apache.poi.xssf.usermodel.XSSFShape; -import org.apache.xmlbeans.XmlException; -import org.xml.sax.Attributes; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; -import org.xml.sax.XMLReader; -import org.xml.sax.helpers.DefaultHandler; - -/** - * This class makes it easy to get at individual parts - * of an OOXML .xlsx file, suitable for low memory sax - * parsing or similar. - * It makes up the core part of the EventUserModel support - * for XSSF. - */ -public class XSSFReader { - - private static final POILogger LOGGER = POILogFactory.getLogger(XSSFReader.class); - - protected OPCPackage pkg; - protected PackagePart workbookPart; - - /** - * Creates a new XSSFReader, for the given package - */ - public XSSFReader(OPCPackage pkg) throws IOException, OpenXML4JException { - this.pkg = pkg; - - PackageRelationship coreDocRelationship = this.pkg.getRelationshipsByType( - PackageRelationshipTypes.CORE_DOCUMENT).getRelationship(0); - - // strict OOXML likely not fully supported, see #57699 - // this code is similar to POIXMLDocumentPart.getPartFromOPCPackage(), but I could not combine it - // easily due to different return values - if(coreDocRelationship == null) { - if (this.pkg.getRelationshipsByType( - PackageRelationshipTypes.STRICT_CORE_DOCUMENT).getRelationship(0) != null) { - throw new POIXMLException("Strict OOXML isn't currently supported, please see bug #57699"); - } - - throw new POIXMLException("OOXML file structure broken/invalid - no core document found!"); - } - - // Get the part that holds the workbook - workbookPart = this.pkg.getPart(coreDocRelationship); - } - - - /** - * Opens up the Shared Strings Table, parses it, and - * returns a handy object for working with - * shared strings. - */ - public SharedStringsTable getSharedStringsTable() throws IOException, InvalidFormatException { - ArrayList parts = pkg.getPartsByContentType( XSSFRelation.SHARED_STRINGS.getContentType()); - return parts.size() == 0 ? null : new SharedStringsTable(parts.get(0)); - } - - /** - * Opens up the Styles Table, parses it, and - * returns a handy object for working with cell styles - */ - public StylesTable getStylesTable() throws IOException, InvalidFormatException { - ArrayList parts = pkg.getPartsByContentType( XSSFRelation.STYLES.getContentType()); - if(parts.size() == 0) return null; - - // Create the Styles Table, and associate the Themes if present - StylesTable styles = new StylesTable(parts.get(0)); - parts = pkg.getPartsByContentType( XSSFRelation.THEME.getContentType()); - if(parts.size() != 0) { - styles.setTheme(new ThemesTable(parts.get(0))); - } - return styles; - } - - - - /** - * Returns an InputStream to read the contents of the - * shared strings table. - */ - public InputStream getSharedStringsData() throws IOException, InvalidFormatException { - return XSSFRelation.SHARED_STRINGS.getContents(workbookPart); - } - - /** - * Returns an InputStream to read the contents of the - * styles table. - */ - public InputStream getStylesData() throws IOException, InvalidFormatException { - return XSSFRelation.STYLES.getContents(workbookPart); - } - - /** - * Returns an InputStream to read the contents of the - * themes table. - */ - public InputStream getThemesData() throws IOException, InvalidFormatException { - return XSSFRelation.THEME.getContents(workbookPart); - } - - /** - * Returns an InputStream to read the contents of the - * main Workbook, which contains key overall data for - * the file, including sheet definitions. - */ - public InputStream getWorkbookData() throws IOException, InvalidFormatException { - return workbookPart.getInputStream(); - } - - /** - * Returns an InputStream to read the contents of the - * specified Sheet. - * @param relId The relationId of the sheet, from a r:id on the workbook - */ - public InputStream getSheet(String relId) throws IOException, InvalidFormatException { - PackageRelationship rel = workbookPart.getRelationship(relId); - if(rel == null) { - throw new IllegalArgumentException("No Sheet found with r:id " + relId); - } - - PackagePartName relName = PackagingURIHelper.createPartName(rel.getTargetURI()); - PackagePart sheet = pkg.getPart(relName); - if(sheet == null) { - throw new IllegalArgumentException("No data found for Sheet with r:id " + relId); - } - return sheet.getInputStream(); - } - - /** - * Returns an Iterator which will let you get at all the - * different Sheets in turn. - * Each sheet's InputStream is only opened when fetched - * from the Iterator. It's up to you to close the - * InputStreams when done with each one. - */ - public Iterator getSheetsData() throws IOException, InvalidFormatException { - return new SheetIterator(workbookPart); - } - - /** - * Iterator over sheet data. - */ - public static class SheetIterator implements Iterator { - - /** - * Maps relId and the corresponding PackagePart - */ - private final Map sheetMap; - - /** - * Current sheet reference - */ - XSSFSheetRef xssfSheetRef; - - /** - * Iterator over CTSheet objects, returns sheets in logical order. - * We can't rely on the Ooxml4J's relationship iterator because it returns objects in physical order, - * i.e. as they are stored in the underlying package - */ - final Iterator sheetIterator; - - /** - * Construct a new SheetIterator - * - * @param wb package part holding workbook.xml - */ - SheetIterator(PackagePart wb) throws IOException { - - /** - * The order of sheets is defined by the order of CTSheet elements in workbook.xml - */ - try { - //step 1. Map sheet's relationship Id and the corresponding PackagePart - sheetMap = new HashMap(); - OPCPackage pkg = wb.getPackage(); - String REL_WORKSHEET = XSSFRelation.WORKSHEET.getRelation(); - String REL_CHARTSHEET = XSSFRelation.CHARTSHEET.getRelation(); - for(PackageRelationship rel : wb.getRelationships()){ - String relType = rel.getRelationshipType(); - if (relType.equals(REL_WORKSHEET) || relType.equals(REL_CHARTSHEET)) { - PackagePartName relName = PackagingURIHelper.createPartName(rel.getTargetURI()); - sheetMap.put(rel.getId(), pkg.getPart(relName)); - } - } - //step 2. Read array of CTSheet elements, wrap it in a LinkedList - //and construct an iterator - sheetIterator = createSheetIteratorFromWB(wb); - } catch (InvalidFormatException e){ - throw new POIXMLException(e); - } - } - - Iterator createSheetIteratorFromWB(PackagePart wb) throws IOException { - - XMLSheetRefReader xmlSheetRefReader = new XMLSheetRefReader(); - XMLReader xmlReader = null; - try { - xmlReader = SAXHelper.newXMLReader(); - } catch (ParserConfigurationException e) { - throw new POIXMLException(e); - } catch (SAXException e) { - throw new POIXMLException(e); - } - xmlReader.setContentHandler(xmlSheetRefReader); - try { - xmlReader.parse(new InputSource(wb.getInputStream())); - } catch (SAXException e) { - throw new POIXMLException(e); - } - - List validSheets = new ArrayList(); - for (XSSFSheetRef xssfSheetRef : xmlSheetRefReader.getSheetRefs()) { - //if there's no relationship id, silently skip the sheet - String sheetId = xssfSheetRef.getId(); - if (sheetId != null && sheetId.length() > 0) { - validSheets.add(xssfSheetRef); - } - } - return validSheets.iterator(); - } - - - /** - * Returns true if the iteration has more elements. - * - * @return true if the iterator has more elements. - */ - @Override - public boolean hasNext() { - return sheetIterator.hasNext(); - } - - /** - * Returns input stream of the next sheet in the iteration - * - * @return input stream of the next sheet in the iteration - */ - @Override - public InputStream next() { - xssfSheetRef = sheetIterator.next(); - - String sheetId = xssfSheetRef.getId(); - try { - PackagePart sheetPkg = sheetMap.get(sheetId); - return sheetPkg.getInputStream(); - } catch(IOException e) { - throw new POIXMLException(e); - } - } - - /** - * Returns name of the current sheet - * - * @return name of the current sheet - */ - public String getSheetName() { - return xssfSheetRef.getName(); - } - - /** - * Returns the comments associated with this sheet, - * or null if there aren't any - */ - public CommentsTable getSheetComments() { - PackagePart sheetPkg = getSheetPart(); - - // Do we have a comments relationship? (Only ever one if so) - try { - PackageRelationshipCollection commentsList = - sheetPkg.getRelationshipsByType(XSSFRelation.SHEET_COMMENTS.getRelation()); - if(commentsList.size() > 0) { - PackageRelationship comments = commentsList.getRelationship(0); - PackagePartName commentsName = PackagingURIHelper.createPartName(comments.getTargetURI()); - PackagePart commentsPart = sheetPkg.getPackage().getPart(commentsName); - return new CommentsTable(commentsPart); - } - } catch (InvalidFormatException e) { - return null; - } catch (IOException e) { - return null; - } - return null; - } - - /** - * Returns the shapes associated with this sheet, - * an empty list or null if there is an exception - */ - public List getShapes() { - PackagePart sheetPkg = getSheetPart(); - List shapes= new LinkedList(); - // Do we have a comments relationship? (Only ever one if so) - try { - PackageRelationshipCollection drawingsList = sheetPkg.getRelationshipsByType(XSSFRelation.DRAWINGS.getRelation()); - for (int i = 0; i < drawingsList.size(); i++){ - PackageRelationship drawings = drawingsList.getRelationship(i); - PackagePartName drawingsName = PackagingURIHelper.createPartName(drawings.getTargetURI()); - PackagePart drawingsPart = sheetPkg.getPackage().getPart(drawingsName); - if (drawingsPart == null) { - //parts can go missing; Excel ignores them silently -- TIKA-2134 - LOGGER.log(POILogger.WARN, "Missing drawing: "+drawingsName +". Skipping it."); - continue; - } - XSSFDrawing drawing = new XSSFDrawing(drawingsPart); - for (XSSFShape shape : drawing.getShapes()){ - shapes.add(shape); - } - } - } catch (XmlException e){ - return null; - } catch (InvalidFormatException e) { - return null; - } catch (IOException e) { - return null; - } - return shapes; - } - - public PackagePart getSheetPart() { - String sheetId = xssfSheetRef.getId(); - return sheetMap.get(sheetId); - } - - /** - * We're read only, so remove isn't supported - */ - @Override - public void remove() { - throw new IllegalStateException("Not supported"); - } - } - - protected static final class XSSFSheetRef { - //do we need to store sheetId, too? - private final String id; - private final String name; - - public XSSFSheetRef(String id, String name) { - this.id = id; - this.name = name; - } - - public String getId() { - return id; - } - - public String getName() { - return name; - } - } - - //scrapes sheet reference info and order from workbook.xml - private static class XMLSheetRefReader extends DefaultHandler { - private static final String SHEET = "sheet"; - private static final String ID = "id"; - private static final String NAME = "name"; - - private final List sheetRefs = new LinkedList(); - - @Override - public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException { - if (localName.toLowerCase(Locale.US).equals(SHEET)) { - String name = null; - String id = null; - for (int i = 0; i < attrs.getLength(); i++) { - if (attrs.getLocalName(i).toLowerCase(Locale.US).equals(NAME)) { - name = attrs.getValue(i); - } else if (attrs.getLocalName(i).toLowerCase(Locale.US).equals(ID)) { - id = attrs.getValue(i); - } - sheetRefs.add(new XSSFSheetRef(id, name)); - } - } - } - - List getSheetRefs() { - return Collections.unmodifiableList(sheetRefs); - } - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/eventusermodel/XSSFSheetXMLHandler.java b/src/ooxml/java/org/apache/poi/xssf/eventusermodel/XSSFSheetXMLHandler.java deleted file mode 100644 index 49278d639..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/eventusermodel/XSSFSheetXMLHandler.java +++ /dev/null @@ -1,514 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.eventusermodel; - -import static org.apache.poi.xssf.usermodel.XSSFRelation.NS_SPREADSHEETML; - -import java.util.LinkedList; -import java.util.Queue; - -import org.apache.poi.ss.usermodel.BuiltinFormats; -import org.apache.poi.ss.usermodel.DataFormatter; -import org.apache.poi.ss.util.CellAddress; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.xssf.model.CommentsTable; -import org.apache.poi.xssf.model.StylesTable; -import org.apache.poi.xssf.usermodel.XSSFCellStyle; -import org.apache.poi.xssf.usermodel.XSSFComment; -import org.apache.poi.xssf.usermodel.XSSFRichTextString; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTComment; -import org.xml.sax.Attributes; -import org.xml.sax.SAXException; -import org.xml.sax.helpers.DefaultHandler; - -/** - * This class handles the processing of a sheet#.xml - * sheet part of a XSSF .xlsx file, and generates - * row and cell events for it. - */ -public class XSSFSheetXMLHandler extends DefaultHandler { - private static final POILogger logger = POILogFactory.getLogger(XSSFSheetXMLHandler.class); - - /** - * These are the different kinds of cells we support. - * We keep track of the current one between - * the start and end. - */ - enum xssfDataType { - BOOLEAN, - ERROR, - FORMULA, - INLINE_STRING, - SST_STRING, - NUMBER, - } - - /** - * Table with the styles used for formatting - */ - private StylesTable stylesTable; - - /** - * Table with cell comments - */ - private CommentsTable commentsTable; - - /** - * Read only access to the shared strings table, for looking - * up (most) string cell's contents - */ - private ReadOnlySharedStringsTable sharedStringsTable; - - /** - * Where our text is going - */ - private final SheetContentsHandler output; - - // Set when V start element is seen - private boolean vIsOpen; - // Set when F start element is seen - private boolean fIsOpen; - // Set when an Inline String "is" is seen - private boolean isIsOpen; - // Set when a header/footer element is seen - private boolean hfIsOpen; - - // Set when cell start element is seen; - // used when cell close element is seen. - private xssfDataType nextDataType; - - // Used to format numeric cell values. - private short formatIndex; - private String formatString; - private final DataFormatter formatter; - private int rowNum; - private int nextRowNum; // some sheets do not have rowNums, Excel can read them so we should try to handle them correctly as well - private String cellRef; - private boolean formulasNotResults; - - // Gathers characters as they are seen. - private StringBuffer value = new StringBuffer(); - private StringBuffer formula = new StringBuffer(); - private StringBuffer headerFooter = new StringBuffer(); - - private Queue commentCellRefs; - - /** - * Accepts objects needed while parsing. - * - * @param styles Table of styles - * @param strings Table of shared strings - */ - public XSSFSheetXMLHandler( - StylesTable styles, - CommentsTable comments, - ReadOnlySharedStringsTable strings, - SheetContentsHandler sheetContentsHandler, - DataFormatter dataFormatter, - boolean formulasNotResults) { - this.stylesTable = styles; - this.commentsTable = comments; - this.sharedStringsTable = strings; - this.output = sheetContentsHandler; - this.formulasNotResults = formulasNotResults; - this.nextDataType = xssfDataType.NUMBER; - this.formatter = dataFormatter; - init(); - } - - /** - * Accepts objects needed while parsing. - * - * @param styles Table of styles - * @param strings Table of shared strings - */ - public XSSFSheetXMLHandler( - StylesTable styles, - ReadOnlySharedStringsTable strings, - SheetContentsHandler sheetContentsHandler, - DataFormatter dataFormatter, - boolean formulasNotResults) { - this(styles, null, strings, sheetContentsHandler, dataFormatter, formulasNotResults); - } - - /** - * Accepts objects needed while parsing. - * - * @param styles Table of styles - * @param strings Table of shared strings - */ - public XSSFSheetXMLHandler( - StylesTable styles, - ReadOnlySharedStringsTable strings, - SheetContentsHandler sheetContentsHandler, - boolean formulasNotResults) { - this(styles, strings, sheetContentsHandler, new DataFormatter(), formulasNotResults); - } - - private void init() { - if (commentsTable != null) { - commentCellRefs = new LinkedList(); - //noinspection deprecation - for (CTComment comment : commentsTable.getCTComments().getCommentList().getCommentArray()) { - commentCellRefs.add(new CellAddress(comment.getRef())); - } - } - } - - private boolean isTextTag(String name) { - if("v".equals(name)) { - // Easy, normal v text tag - return true; - } - if("inlineStr".equals(name)) { - // Easy inline string - return true; - } - if("t".equals(name) && isIsOpen) { - // Inline string ... pair - return true; - } - // It isn't a text tag - return false; - } - - @Override - @SuppressWarnings("unused") - public void startElement(String uri, String localName, String qName, - Attributes attributes) throws SAXException { - - if (uri != null && ! uri.equals(NS_SPREADSHEETML)) { - return; - } - - if (isTextTag(localName)) { - vIsOpen = true; - // Clear contents cache - value.setLength(0); - } else if ("is".equals(localName)) { - // Inline string outer tag - isIsOpen = true; - } else if ("f".equals(localName)) { - // Clear contents cache - formula.setLength(0); - - // Mark us as being a formula if not already - if(nextDataType == xssfDataType.NUMBER) { - nextDataType = xssfDataType.FORMULA; - } - - // Decide where to get the formula string from - String type = attributes.getValue("t"); - if(type != null && type.equals("shared")) { - // Is it the one that defines the shared, or uses it? - String ref = attributes.getValue("ref"); - String si = attributes.getValue("si"); - - if(ref != null) { - // This one defines it - // TODO Save it somewhere - fIsOpen = true; - } else { - // This one uses a shared formula - // TODO Retrieve the shared formula and tweak it to - // match the current cell - if(formulasNotResults) { - logger.log(POILogger.WARN, "shared formulas not yet supported!"); - } /*else { - // It's a shared formula, so we can't get at the formula string yet - // However, they don't care about the formula string, so that's ok! - }*/ - } - } else { - fIsOpen = true; - } - } - else if("oddHeader".equals(localName) || "evenHeader".equals(localName) || - "firstHeader".equals(localName) || "firstFooter".equals(localName) || - "oddFooter".equals(localName) || "evenFooter".equals(localName)) { - hfIsOpen = true; - // Clear contents cache - headerFooter.setLength(0); - } - else if("row".equals(localName)) { - String rowNumStr = attributes.getValue("r"); - if(rowNumStr != null) { - rowNum = Integer.parseInt(rowNumStr) - 1; - } else { - rowNum = nextRowNum; - } - output.startRow(rowNum); - } - // c => cell - else if ("c".equals(localName)) { - // Set up defaults. - this.nextDataType = xssfDataType.NUMBER; - this.formatIndex = -1; - this.formatString = null; - cellRef = attributes.getValue("r"); - String cellType = attributes.getValue("t"); - String cellStyleStr = attributes.getValue("s"); - if ("b".equals(cellType)) - nextDataType = xssfDataType.BOOLEAN; - else if ("e".equals(cellType)) - nextDataType = xssfDataType.ERROR; - else if ("inlineStr".equals(cellType)) - nextDataType = xssfDataType.INLINE_STRING; - else if ("s".equals(cellType)) - nextDataType = xssfDataType.SST_STRING; - else if ("str".equals(cellType)) - nextDataType = xssfDataType.FORMULA; - else { - // Number, but almost certainly with a special style or format - XSSFCellStyle style = null; - if (stylesTable != null) { - if (cellStyleStr != null) { - int styleIndex = Integer.parseInt(cellStyleStr); - style = stylesTable.getStyleAt(styleIndex); - } else if (stylesTable.getNumCellStyles() > 0) { - style = stylesTable.getStyleAt(0); - } - } - if (style != null) { - this.formatIndex = style.getDataFormat(); - this.formatString = style.getDataFormatString(); - if (this.formatString == null) - this.formatString = BuiltinFormats.getBuiltinFormat(this.formatIndex); - } - } - } - } - - @Override - public void endElement(String uri, String localName, String qName) - throws SAXException { - - if (uri != null && ! uri.equals(NS_SPREADSHEETML)) { - return; - } - - String thisStr = null; - - // v => contents of a cell - if (isTextTag(localName)) { - vIsOpen = false; - - // Process the value contents as required, now we have it all - switch (nextDataType) { - case BOOLEAN: - char first = value.charAt(0); - thisStr = first == '0' ? "FALSE" : "TRUE"; - break; - - case ERROR: - thisStr = "ERROR:" + value.toString(); - break; - - case FORMULA: - if(formulasNotResults) { - thisStr = formula.toString(); - } else { - String fv = value.toString(); - - if (this.formatString != null) { - try { - // Try to use the value as a formattable number - double d = Double.parseDouble(fv); - thisStr = formatter.formatRawCellContents(d, this.formatIndex, this.formatString); - } catch(NumberFormatException e) { - // Formula is a String result not a Numeric one - thisStr = fv; - } - } else { - // No formatting applied, just do raw value in all cases - thisStr = fv; - } - } - break; - - case INLINE_STRING: - // TODO: Can these ever have formatting on them? - XSSFRichTextString rtsi = new XSSFRichTextString(value.toString()); - thisStr = rtsi.toString(); - break; - - case SST_STRING: - String sstIndex = value.toString(); - try { - int idx = Integer.parseInt(sstIndex); - XSSFRichTextString rtss = new XSSFRichTextString(sharedStringsTable.getEntryAt(idx)); - thisStr = rtss.toString(); - } - catch (NumberFormatException ex) { - logger.log(POILogger.ERROR, "Failed to parse SST index '" + sstIndex, ex); - } - break; - - case NUMBER: - String n = value.toString(); - if (this.formatString != null && n.length() > 0) - thisStr = formatter.formatRawCellContents(Double.parseDouble(n), this.formatIndex, this.formatString); - else - thisStr = n; - break; - - default: - thisStr = "(TODO: Unexpected type: " + nextDataType + ")"; - break; - } - - // Do we have a comment for this cell? - checkForEmptyCellComments(EmptyCellCommentsCheckType.CELL); - XSSFComment comment = commentsTable != null ? commentsTable.findCellComment(new CellAddress(cellRef)) : null; - - // Output - output.cell(cellRef, thisStr, comment); - } else if ("f".equals(localName)) { - fIsOpen = false; - } else if ("is".equals(localName)) { - isIsOpen = false; - } else if ("row".equals(localName)) { - // Handle any "missing" cells which had comments attached - checkForEmptyCellComments(EmptyCellCommentsCheckType.END_OF_ROW); - - // Finish up the row - output.endRow(rowNum); - - // some sheets do not have rowNum set in the XML, Excel can read them so we should try to read them as well - nextRowNum = rowNum + 1; - } else if ("sheetData".equals(localName)) { - // Handle any "missing" cells which had comments attached - checkForEmptyCellComments(EmptyCellCommentsCheckType.END_OF_SHEET_DATA); - } - else if("oddHeader".equals(localName) || "evenHeader".equals(localName) || - "firstHeader".equals(localName)) { - hfIsOpen = false; - output.headerFooter(headerFooter.toString(), true, localName); - } - else if("oddFooter".equals(localName) || "evenFooter".equals(localName) || - "firstFooter".equals(localName)) { - hfIsOpen = false; - output.headerFooter(headerFooter.toString(), false, localName); - } - } - - /** - * Captures characters only if a suitable element is open. - * Originally was just "v"; extended for inlineStr also. - */ - @Override - public void characters(char[] ch, int start, int length) - throws SAXException { - if (vIsOpen) { - value.append(ch, start, length); - } - if (fIsOpen) { - formula.append(ch, start, length); - } - if (hfIsOpen) { - headerFooter.append(ch, start, length); - } - } - - /** - * Do a check for, and output, comments in otherwise empty cells. - */ - private void checkForEmptyCellComments(EmptyCellCommentsCheckType type) { - if (commentCellRefs != null && !commentCellRefs.isEmpty()) { - // If we've reached the end of the sheet data, output any - // comments we haven't yet already handled - if (type == EmptyCellCommentsCheckType.END_OF_SHEET_DATA) { - while (!commentCellRefs.isEmpty()) { - outputEmptyCellComment(commentCellRefs.remove()); - } - return; - } - - // At the end of a row, handle any comments for "missing" rows before us - if (this.cellRef == null) { - if (type == EmptyCellCommentsCheckType.END_OF_ROW) { - while (!commentCellRefs.isEmpty()) { - if (commentCellRefs.peek().getRow() == rowNum) { - outputEmptyCellComment(commentCellRefs.remove()); - } else { - return; - } - } - return; - } else { - throw new IllegalStateException("Cell ref should be null only if there are only empty cells in the row; rowNum: " + rowNum); - } - } - - CellAddress nextCommentCellRef; - do { - CellAddress cellRef = new CellAddress(this.cellRef); - CellAddress peekCellRef = commentCellRefs.peek(); - if (type == EmptyCellCommentsCheckType.CELL && cellRef.equals(peekCellRef)) { - // remove the comment cell ref from the list if we're about to handle it alongside the cell content - commentCellRefs.remove(); - return; - } else { - // fill in any gaps if there are empty cells with comment mixed in with non-empty cells - int comparison = peekCellRef.compareTo(cellRef); - if (comparison > 0 && type == EmptyCellCommentsCheckType.END_OF_ROW && peekCellRef.getRow() <= rowNum) { - nextCommentCellRef = commentCellRefs.remove(); - outputEmptyCellComment(nextCommentCellRef); - } else if (comparison < 0 && type == EmptyCellCommentsCheckType.CELL && peekCellRef.getRow() <= rowNum) { - nextCommentCellRef = commentCellRefs.remove(); - outputEmptyCellComment(nextCommentCellRef); - } else { - nextCommentCellRef = null; - } - } - } while (nextCommentCellRef != null && !commentCellRefs.isEmpty()); - } - } - - - /** - * Output an empty-cell comment. - */ - private void outputEmptyCellComment(CellAddress cellRef) { - XSSFComment comment = commentsTable.findCellComment(cellRef); - output.cell(cellRef.formatAsString(), null, comment); - } - - private enum EmptyCellCommentsCheckType { - CELL, - END_OF_ROW, - END_OF_SHEET_DATA - } - - /** - * You need to implement this to handle the results - * of the sheet parsing. - */ - public interface SheetContentsHandler { - /** A row with the (zero based) row number has started */ - public void startRow(int rowNum); - /** A row with the (zero based) row number has ended */ - public void endRow(int rowNum); - /** - * A cell, with the given formatted value (may be null), - * and possibly a comment (may be null), was encountered */ - public void cell(String cellReference, String formattedValue, XSSFComment comment); - /** A header or footer has been encountered */ - public void headerFooter(String text, boolean isHeader, String tagName); - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/extractor/XSSFBEventBasedExcelExtractor.java b/src/ooxml/java/org/apache/poi/xssf/extractor/XSSFBEventBasedExcelExtractor.java deleted file mode 100644 index 4e2a5c27b..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/extractor/XSSFBEventBasedExcelExtractor.java +++ /dev/null @@ -1,166 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.extractor; - -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.POIXMLTextExtractor; -import org.apache.poi.openxml4j.exceptions.OpenXML4JException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.ss.usermodel.DataFormatter; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.xssf.binary.XSSFBCommentsTable; -import org.apache.poi.xssf.binary.XSSFBHyperlinksTable; -import org.apache.poi.xssf.binary.XSSFBSharedStringsTable; -import org.apache.poi.xssf.binary.XSSFBSheetHandler; -import org.apache.poi.xssf.binary.XSSFBStylesTable; -import org.apache.poi.xssf.eventusermodel.XSSFBReader; -import org.apache.poi.xssf.eventusermodel.XSSFSheetXMLHandler.SheetContentsHandler; -import org.apache.poi.xssf.usermodel.XSSFRelation; -import org.apache.xmlbeans.XmlException; -import org.xml.sax.SAXException; - -/** - * Implementation of a text extractor or xlsb Excel - * files that uses SAX-like binary parsing. - * - * @since 3.16-beta3 - */ -public class XSSFBEventBasedExcelExtractor extends XSSFEventBasedExcelExtractor - implements org.apache.poi.ss.extractor.ExcelExtractor { - - private static final POILogger LOGGER = POILogFactory.getLogger(XSSFBEventBasedExcelExtractor.class); - - public static final XSSFRelation[] SUPPORTED_TYPES = new XSSFRelation[]{ - XSSFRelation.XLSB_BINARY_WORKBOOK - }; - - private boolean handleHyperlinksInCells = false; - - public XSSFBEventBasedExcelExtractor(String path) throws XmlException, OpenXML4JException, IOException { - super(path); - } - - public XSSFBEventBasedExcelExtractor(OPCPackage container) throws XmlException, OpenXML4JException, IOException { - super(container); - } - - public static void main(String[] args) throws Exception { - if (args.length < 1) { - System.err.println("Use:"); - System.err.println(" XSSFBEventBasedExcelExtractor "); - System.exit(1); - } - POIXMLTextExtractor extractor = - new XSSFBEventBasedExcelExtractor(args[0]); - System.out.println(extractor.getText()); - extractor.close(); - } - - public void setHandleHyperlinksInCells(boolean handleHyperlinksInCells) { - this.handleHyperlinksInCells = handleHyperlinksInCells; - } - - /** - * Should we return the formula itself, and not - * the result it produces? Default is false - * This is currently unsupported for xssfb - */ - @Override - public void setFormulasNotResults(boolean formulasNotResults) { - throw new IllegalArgumentException("Not currently supported"); - } - - /** - * Processes the given sheet - */ - public void processSheet( - SheetContentsHandler sheetContentsExtractor, - XSSFBStylesTable styles, - XSSFBCommentsTable comments, - XSSFBSharedStringsTable strings, - InputStream sheetInputStream) - throws IOException, SAXException { - - DataFormatter formatter; - if (getLocale() == null) { - formatter = new DataFormatter(); - } else { - formatter = new DataFormatter(getLocale()); - } - - XSSFBSheetHandler xssfbSheetHandler = new XSSFBSheetHandler( - sheetInputStream, - styles, comments, strings, sheetContentsExtractor, formatter, getFormulasNotResults() - ); - xssfbSheetHandler.parse(); - } - - /** - * Processes the file and returns the text - */ - public String getText() { - try { - XSSFBSharedStringsTable strings = new XSSFBSharedStringsTable(getPackage()); - XSSFBReader xssfbReader = new XSSFBReader(getPackage()); - XSSFBStylesTable styles = xssfbReader.getXSSFBStylesTable(); - XSSFBReader.SheetIterator iter = (XSSFBReader.SheetIterator) xssfbReader.getSheetsData(); - - StringBuffer text = new StringBuffer(); - SheetTextExtractor sheetExtractor = new SheetTextExtractor(); - XSSFBHyperlinksTable hyperlinksTable = null; - while (iter.hasNext()) { - InputStream stream = iter.next(); - if (getIncludeSheetNames()) { - text.append(iter.getSheetName()); - text.append('\n'); - } - if (handleHyperlinksInCells) { - hyperlinksTable = new XSSFBHyperlinksTable(iter.getSheetPart()); - } - XSSFBCommentsTable comments = getIncludeCellComments() ? iter.getXSSFBSheetComments() : null; - processSheet(sheetExtractor, styles, comments, strings, stream); - if (getIncludeHeadersFooters()) { - sheetExtractor.appendHeaderText(text); - } - sheetExtractor.appendCellText(text); - if (getIncludeTextBoxes()) { - processShapes(iter.getShapes(), text); - } - if (getIncludeHeadersFooters()) { - sheetExtractor.appendFooterText(text); - } - sheetExtractor.reset(); - stream.close(); - } - - return text.toString(); - } catch (IOException e) { - LOGGER.log(POILogger.WARN, e); - return null; - } catch (SAXException se) { - LOGGER.log(POILogger.WARN, se); - return null; - } catch (OpenXML4JException o4je) { - LOGGER.log(POILogger.WARN, o4je); - return null; - } - } - -} diff --git a/src/ooxml/java/org/apache/poi/xssf/extractor/XSSFEventBasedExcelExtractor.java b/src/ooxml/java/org/apache/poi/xssf/extractor/XSSFEventBasedExcelExtractor.java deleted file mode 100644 index dd14c6cd0..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/extractor/XSSFEventBasedExcelExtractor.java +++ /dev/null @@ -1,456 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.extractor; - -import javax.xml.parsers.ParserConfigurationException; -import java.io.IOException; -import java.io.InputStream; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import org.apache.poi.POIXMLProperties; -import org.apache.poi.POIXMLProperties.CoreProperties; -import org.apache.poi.POIXMLProperties.CustomProperties; -import org.apache.poi.POIXMLProperties.ExtendedProperties; -import org.apache.poi.POIXMLTextExtractor; -import org.apache.poi.openxml4j.exceptions.OpenXML4JException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.ss.usermodel.DataFormatter; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.util.SAXHelper; -import org.apache.poi.xssf.eventusermodel.ReadOnlySharedStringsTable; -import org.apache.poi.xssf.eventusermodel.XSSFReader; -import org.apache.poi.xssf.eventusermodel.XSSFSheetXMLHandler; -import org.apache.poi.xssf.eventusermodel.XSSFSheetXMLHandler.SheetContentsHandler; -import org.apache.poi.xssf.model.CommentsTable; -import org.apache.poi.xssf.model.StylesTable; -import org.apache.poi.xssf.usermodel.XSSFComment; -import org.apache.poi.xssf.usermodel.XSSFShape; -import org.apache.poi.xssf.usermodel.XSSFSimpleShape; -import org.apache.xmlbeans.XmlException; -import org.xml.sax.ContentHandler; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; -import org.xml.sax.XMLReader; - -/** - * Implementation of a text extractor from OOXML Excel - * files that uses SAX event based parsing. - */ -public class XSSFEventBasedExcelExtractor extends POIXMLTextExtractor - implements org.apache.poi.ss.extractor.ExcelExtractor { - - private static final POILogger LOGGER = POILogFactory.getLogger(XSSFEventBasedExcelExtractor.class); - - private OPCPackage container; - private POIXMLProperties properties; - - private Locale locale; - private boolean includeTextBoxes = true; - private boolean includeSheetNames = true; - private boolean includeCellComments = false; - private boolean includeHeadersFooters = true; - private boolean formulasNotResults = false; - private boolean concatenatePhoneticRuns = true; - - public XSSFEventBasedExcelExtractor(String path) throws XmlException, OpenXML4JException, IOException { - this(OPCPackage.open(path)); - } - public XSSFEventBasedExcelExtractor(OPCPackage container) throws XmlException, OpenXML4JException, IOException { - super(null); - this.container = container; - - properties = new POIXMLProperties(container); - } - - public static void main(String[] args) throws Exception { - if(args.length < 1) { - System.err.println("Use:"); - System.err.println(" XSSFEventBasedExcelExtractor "); - System.exit(1); - } - POIXMLTextExtractor extractor = - new XSSFEventBasedExcelExtractor(args[0]); - System.out.println(extractor.getText()); - extractor.close(); - } - - /** - * Should sheet names be included? Default is true - */ - public void setIncludeSheetNames(boolean includeSheetNames) { - this.includeSheetNames = includeSheetNames; - } - - - /** - * - * @return whether to include sheet names - * - * @since 3.16-beta3 - */ - public boolean getIncludeSheetNames() { - return includeSheetNames; - } - - /** - * Should we return the formula itself, and not - * the result it produces? Default is false - */ - public void setFormulasNotResults(boolean formulasNotResults) { - this.formulasNotResults = formulasNotResults; - } - - /** - * - * @return whether to include formulas but not results - * - * @since 3.16-beta3 - */ - public boolean getFormulasNotResults() { - return formulasNotResults; - } - - /** - * Should headers and footers be included? Default is true - */ - public void setIncludeHeadersFooters(boolean includeHeadersFooters) { - this.includeHeadersFooters = includeHeadersFooters; - } - - /** - * - * @return whether or not to include headers and footers - * - * @since 3.16-beta3 - */ - public boolean getIncludeHeadersFooters() { - return includeHeadersFooters; - } - /** - * Should text from textboxes be included? Default is true - */ - public void setIncludeTextBoxes(boolean includeTextBoxes) { - this.includeTextBoxes = includeTextBoxes; - } - - /** - * - * @return whether or not to extract textboxes - * - * @since 3.16-beta3 - */ - public boolean getIncludeTextBoxes() { - return includeTextBoxes; - } - /** - * Should cell comments be included? Default is false - */ - public void setIncludeCellComments(boolean includeCellComments) { - this.includeCellComments = includeCellComments; - } - - /** - * @return whether cell comments should be included - * - * @since 3.16-beta3 - */ - public boolean getIncludeCellComments() { - return includeCellComments; - } - /** - * Concatenate text from <rPh> text elements in SharedStringsTable - * Default is true; - * @param concatenatePhoneticRuns - */ - public void setConcatenatePhoneticRuns(boolean concatenatePhoneticRuns) { - this.concatenatePhoneticRuns = concatenatePhoneticRuns; - } - public void setLocale(Locale locale) { - this.locale = locale; - } - - /** - * @return locale - * - * @since 3.16-beta3 - */ - public Locale getLocale() { - return locale; - } - /** - * Returns the opened OPCPackage container. - */ - @Override - public OPCPackage getPackage() { - return container; - } - - /** - * Returns the core document properties - */ - @Override - public CoreProperties getCoreProperties() { - return properties.getCoreProperties(); - } - /** - * Returns the extended document properties - */ - @Override - public ExtendedProperties getExtendedProperties() { - return properties.getExtendedProperties(); - } - /** - * Returns the custom document properties - */ - @Override - public CustomProperties getCustomProperties() { - return properties.getCustomProperties(); - } - - - - /** - * Processes the given sheet - */ - public void processSheet( - SheetContentsHandler sheetContentsExtractor, - StylesTable styles, - CommentsTable comments, - ReadOnlySharedStringsTable strings, - InputStream sheetInputStream) - throws IOException, SAXException { - - DataFormatter formatter; - if(locale == null) { - formatter = new DataFormatter(); - } else { - formatter = new DataFormatter(locale); - } - - InputSource sheetSource = new InputSource(sheetInputStream); - try { - XMLReader sheetParser = SAXHelper.newXMLReader(); - ContentHandler handler = new XSSFSheetXMLHandler( - styles, comments, strings, sheetContentsExtractor, formatter, formulasNotResults); - sheetParser.setContentHandler(handler); - sheetParser.parse(sheetSource); - } catch(ParserConfigurationException e) { - throw new RuntimeException("SAX parser appears to be broken - " + e.getMessage()); - } - } - - /** - * Processes the file and returns the text - */ - public String getText() { - try { - ReadOnlySharedStringsTable strings = new ReadOnlySharedStringsTable(container, concatenatePhoneticRuns); - XSSFReader xssfReader = new XSSFReader(container); - StylesTable styles = xssfReader.getStylesTable(); - XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) xssfReader.getSheetsData(); - - StringBuffer text = new StringBuffer(); - SheetTextExtractor sheetExtractor = new SheetTextExtractor(); - - while (iter.hasNext()) { - InputStream stream = iter.next(); - if(includeSheetNames) { - text.append(iter.getSheetName()); - text.append('\n'); - } - CommentsTable comments = includeCellComments ? iter.getSheetComments() : null; - processSheet(sheetExtractor, styles, comments, strings, stream); - if (includeHeadersFooters) { - sheetExtractor.appendHeaderText(text); - } - sheetExtractor.appendCellText(text); - if (includeTextBoxes){ - processShapes(iter.getShapes(), text); - } - if (includeHeadersFooters) { - sheetExtractor.appendFooterText(text); - } - sheetExtractor.reset(); - stream.close(); - } - - return text.toString(); - } catch(IOException e) { - LOGGER.log(POILogger.WARN, e); - return null; - } catch(SAXException se) { - LOGGER.log(POILogger.WARN, se); - return null; - } catch(OpenXML4JException o4je) { - LOGGER.log(POILogger.WARN, o4je); - return null; - } - } - - void processShapes(List shapes, StringBuffer text) { - if (shapes == null){ - return; - } - for (XSSFShape shape : shapes){ - if (shape instanceof XSSFSimpleShape){ - String sText = ((XSSFSimpleShape)shape).getText(); - if (sText != null && sText.length() > 0){ - text.append(sText).append('\n'); - } - } - } - } - @Override - public void close() throws IOException { - if (container != null) { - container.close(); - container = null; - } - super.close(); - } - - protected class SheetTextExtractor implements SheetContentsHandler { - private final StringBuffer output; - private boolean firstCellOfRow; - private final Map headerFooterMap; - - protected SheetTextExtractor() { - this.output = new StringBuffer(); - this.firstCellOfRow = true; - this.headerFooterMap = includeHeadersFooters ? new HashMap() : null; - } - - @Override - public void startRow(int rowNum) { - firstCellOfRow = true; - } - - @Override - public void endRow(int rowNum) { - output.append('\n'); - } - - @Override - public void cell(String cellRef, String formattedValue, XSSFComment comment) { - if(firstCellOfRow) { - firstCellOfRow = false; - } else { - output.append('\t'); - } - if (formattedValue != null) { - checkMaxTextSize(output, formattedValue); - output.append(formattedValue); - } - if (includeCellComments && comment != null) { - String commentText = comment.getString().getString().replace('\n', ' '); - output.append(formattedValue != null ? " Comment by " : "Comment by "); - checkMaxTextSize(output, commentText); - if (commentText.startsWith(comment.getAuthor() + ": ")) { - output.append(commentText); - } else { - output.append(comment.getAuthor()).append(": ").append(commentText); - } - } - } - - @Override - public void headerFooter(String text, boolean isHeader, String tagName) { - if (headerFooterMap != null) { - headerFooterMap.put(tagName, text); - } - } - - /** - * Append the text for the named header or footer if found. - */ - private void appendHeaderFooterText(StringBuffer buffer, String name) { - String text = headerFooterMap.get(name); - if (text != null && text.length() > 0) { - // this is a naive way of handling the left, center, and right - // header and footer delimiters, but it seems to be as good as - // the method used by XSSFExcelExtractor - text = handleHeaderFooterDelimiter(text, "&L"); - text = handleHeaderFooterDelimiter(text, "&C"); - text = handleHeaderFooterDelimiter(text, "&R"); - buffer.append(text).append('\n'); - } - } - /** - * Remove the delimiter if its found at the beginning of the text, - * or replace it with a tab if its in the middle. - */ - private String handleHeaderFooterDelimiter(String text, String delimiter) { - int index = text.indexOf(delimiter); - if (index == 0) { - text = text.substring(2); - } else if (index > 0) { - text = text.substring(0, index) + "\t" + text.substring(index + 2); - } - return text; - } - - - /** - * Append the text for each header type in the same order - * they are appended in XSSFExcelExtractor. - * @see XSSFExcelExtractor#getText() - * @see org.apache.poi.hssf.extractor.ExcelExtractor#_extractHeaderFooter(org.apache.poi.ss.usermodel.HeaderFooter) - */ - void appendHeaderText(StringBuffer buffer) { - appendHeaderFooterText(buffer, "firstHeader"); - appendHeaderFooterText(buffer, "oddHeader"); - appendHeaderFooterText(buffer, "evenHeader"); - } - - /** - * Append the text for each footer type in the same order - * they are appended in XSSFExcelExtractor. - * @see XSSFExcelExtractor#getText() - * @see org.apache.poi.hssf.extractor.ExcelExtractor#_extractHeaderFooter(org.apache.poi.ss.usermodel.HeaderFooter) - */ - void appendFooterText(StringBuffer buffer) { - // append the text for each footer type in the same order - // they are appended in XSSFExcelExtractor - appendHeaderFooterText(buffer, "firstFooter"); - appendHeaderFooterText(buffer, "oddFooter"); - appendHeaderFooterText(buffer, "evenFooter"); - } - - /** - * Append the cell contents we have collected. - */ - void appendCellText(StringBuffer buffer) { - checkMaxTextSize(buffer, output.toString()); - buffer.append(output); - } - - /** - * Reset this SheetTextExtractor for the next sheet. - */ - void reset() { - output.setLength(0); - firstCellOfRow = true; - if (headerFooterMap != null) { - headerFooterMap.clear(); - } - } - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/extractor/XSSFExcelExtractor.java b/src/ooxml/java/org/apache/poi/xssf/extractor/XSSFExcelExtractor.java deleted file mode 100644 index 192d60d71..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/extractor/XSSFExcelExtractor.java +++ /dev/null @@ -1,265 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.extractor; - -import java.io.IOException; -import java.util.Iterator; -import java.util.Locale; - -import org.apache.poi.POIXMLTextExtractor; -import org.apache.poi.hssf.extractor.ExcelExtractor; -import org.apache.poi.openxml4j.exceptions.OpenXML4JException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.Comment; -import org.apache.poi.ss.usermodel.DataFormatter; -import org.apache.poi.ss.usermodel.HeaderFooter; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.xssf.usermodel.XSSFCell; -import org.apache.poi.xssf.usermodel.XSSFDrawing; -import org.apache.poi.xssf.usermodel.XSSFRelation; -import org.apache.poi.xssf.usermodel.XSSFShape; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFSimpleShape; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.apache.xmlbeans.XmlException; - -/** - * Helper class to extract text from an OOXML Excel file - */ -public class XSSFExcelExtractor extends POIXMLTextExtractor - implements org.apache.poi.ss.extractor.ExcelExtractor { - public static final XSSFRelation[] SUPPORTED_TYPES = new XSSFRelation[] { - XSSFRelation.WORKBOOK, XSSFRelation.MACRO_TEMPLATE_WORKBOOK, - XSSFRelation.MACRO_ADDIN_WORKBOOK, XSSFRelation.TEMPLATE_WORKBOOK, - XSSFRelation.MACROS_WORKBOOK - }; - - private Locale locale; - private XSSFWorkbook workbook; - private boolean includeSheetNames = true; - private boolean formulasNotResults = false; - private boolean includeCellComments = false; - private boolean includeHeadersFooters = true; - private boolean includeTextBoxes = true; - - public XSSFExcelExtractor(OPCPackage container) throws XmlException, OpenXML4JException, IOException { - this(new XSSFWorkbook(container)); - } - public XSSFExcelExtractor(XSSFWorkbook workbook) { - super(workbook); - this.workbook = workbook; - } - - public static void main(String[] args) throws Exception { - if(args.length < 1) { - System.err.println("Use:"); - System.err.println(" XSSFExcelExtractor "); - System.exit(1); - } - OPCPackage pkg = OPCPackage.create(args[0]); - POIXMLTextExtractor extractor = new XSSFExcelExtractor(pkg); - try { - System.out.println(extractor.getText()); - } finally { - extractor.close(); - } - } - - /** - * Should sheet names be included? Default is true - */ - public void setIncludeSheetNames(boolean includeSheetNames) { - this.includeSheetNames = includeSheetNames; - } - /** - * Should we return the formula itself, and not - * the result it produces? Default is false - */ - public void setFormulasNotResults(boolean formulasNotResults) { - this.formulasNotResults = formulasNotResults; - } - /** - * Should cell comments be included? Default is false - */ - public void setIncludeCellComments(boolean includeCellComments) { - this.includeCellComments = includeCellComments; - } - /** - * Should headers and footers be included? Default is true - */ - public void setIncludeHeadersFooters(boolean includeHeadersFooters) { - this.includeHeadersFooters = includeHeadersFooters; - } - /** - * Should text within textboxes be included? Default is true - * @param includeTextBoxes - */ - public void setIncludeTextBoxes(boolean includeTextBoxes){ - this.includeTextBoxes = includeTextBoxes; - } - /** - * What Locale should be used for formatting numbers (based - * on the styles applied to the cells) - */ - public void setLocale(Locale locale) { - this.locale = locale; - } - - - /** - * Retrieves the text contents of the file - */ - public String getText() { - DataFormatter formatter; - if(locale == null) { - formatter = new DataFormatter(); - } else { - formatter = new DataFormatter(locale); - } - - StringBuffer text = new StringBuffer(); - for(Sheet sh : workbook) { - XSSFSheet sheet = (XSSFSheet) sh; - if(includeSheetNames) { - text.append(sheet.getSheetName()).append("\n"); - } - - // Header(s), if present - if(includeHeadersFooters) { - text.append( - extractHeaderFooter(sheet.getFirstHeader()) - ); - text.append( - extractHeaderFooter(sheet.getOddHeader()) - ); - text.append( - extractHeaderFooter(sheet.getEvenHeader()) - ); - } - - // Rows and cells - for (Object rawR : sheet) { - Row row = (Row)rawR; - for(Iterator ri = row.cellIterator(); ri.hasNext();) { - Cell cell = ri.next(); - - // Is it a formula one? - if(cell.getCellTypeEnum() == CellType.FORMULA) { - if (formulasNotResults) { - String contents = cell.getCellFormula(); - checkMaxTextSize(text, contents); - text.append(contents); - } else { - if (cell.getCachedFormulaResultTypeEnum() == CellType.STRING) { - handleStringCell(text, cell); - } else { - handleNonStringCell(text, cell, formatter); - } - } - } else if(cell.getCellTypeEnum() == CellType.STRING) { - handleStringCell(text, cell); - } else { - handleNonStringCell(text, cell, formatter); - } - - // Output the comment, if requested and exists - Comment comment = cell.getCellComment(); - if(includeCellComments && comment != null) { - // Replace any newlines with spaces, otherwise it - // breaks the output - String commentText = comment.getString().getString().replace('\n', ' '); - checkMaxTextSize(text, commentText); - text.append(" Comment by ").append(comment.getAuthor()).append(": ").append(commentText); - } - - if(ri.hasNext()) { - text.append("\t"); - } - } - text.append("\n"); - } - - // add textboxes - if (includeTextBoxes){ - XSSFDrawing drawing = sheet.getDrawingPatriarch(); - if (drawing != null) { - for (XSSFShape shape : drawing.getShapes()){ - if (shape instanceof XSSFSimpleShape){ - String boxText = ((XSSFSimpleShape)shape).getText(); - if (boxText.length() > 0){ - text.append(boxText); - text.append('\n'); - } - } - } - } - } - // Finally footer(s), if present - if(includeHeadersFooters) { - text.append( - extractHeaderFooter(sheet.getFirstFooter()) - ); - text.append( - extractHeaderFooter(sheet.getOddFooter()) - ); - text.append( - extractHeaderFooter(sheet.getEvenFooter()) - ); - } - } - - return text.toString(); - } - - private void handleStringCell(StringBuffer text, Cell cell) { - String contents = cell.getRichStringCellValue().getString(); - checkMaxTextSize(text, contents); - text.append(contents); - } - - private void handleNonStringCell(StringBuffer text, Cell cell, DataFormatter formatter) { - CellType type = cell.getCellTypeEnum(); - if (type == CellType.FORMULA) { - type = cell.getCachedFormulaResultTypeEnum(); - } - - if (type == CellType.NUMERIC) { - CellStyle cs = cell.getCellStyle(); - - if (cs != null && cs.getDataFormatString() != null) { - String contents = formatter.formatRawCellContents( - cell.getNumericCellValue(), cs.getDataFormat(), cs.getDataFormatString()); - checkMaxTextSize(text, contents); - text.append(contents); - return; - } - } - - // No supported styling applies to this cell - String contents = ((XSSFCell)cell).getRawValue(); - checkMaxTextSize(text, contents); - text.append( contents ); - } - - private String extractHeaderFooter(HeaderFooter hf) { - return ExcelExtractor._extractHeaderFooter(hf); - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/extractor/XSSFExportToXml.java b/src/ooxml/java/org/apache/poi/xssf/extractor/XSSFExportToXml.java deleted file mode 100644 index 7febd236b..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/extractor/XSSFExportToXml.java +++ /dev/null @@ -1,532 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.extractor; - -import java.io.IOException; -import java.io.OutputStream; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Vector; - -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Source; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; -import javax.xml.validation.Schema; -import javax.xml.validation.SchemaFactory; -import javax.xml.validation.Validator; - -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.DateUtil; -import org.apache.poi.util.DocumentHelper; -import org.apache.poi.util.LocaleUtil; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.xssf.usermodel.XSSFCell; -import org.apache.poi.xssf.usermodel.XSSFMap; -import org.apache.poi.xssf.usermodel.XSSFRow; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFTable; -import org.apache.poi.xssf.usermodel.helpers.XSSFSingleXmlCell; -import org.apache.poi.xssf.usermodel.helpers.XSSFXmlColumnPr; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.NamedNodeMap; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.xml.sax.SAXException; - -/** - * - * Maps an XLSX to an XML according to one of the mapping defined. - * - * - * The output XML Schema must respect this limitations: - * - *
      - *
    • all mandatory elements and attributes must be mapped (enable validation to check this)
    • - * - *
    • no <any> in complex type/element declaration
    • - *
    • no <anyAttribute> attributes declaration
    • - *
    • no recursive structures: recursive structures can't be nested more than one level
    • - *
    • no abstract elements: abstract complex types can be declared but must not be used in elements.
    • - *
    • no mixed content: an element can't contain simple text and child element(s) together
    • - *
    • no <substitutionGroup> in complex type/element declaration
    • - *
    - */ -public class XSSFExportToXml implements Comparator{ - private static final POILogger LOG = POILogFactory.getLogger(XSSFExportToXml.class); - - private XSSFMap map; - - /** - * Creates a new exporter and sets the mapping to be used when generating the XML output document - * - * @param map the mapping rule to be used - */ - public XSSFExportToXml(XSSFMap map) { - this.map = map; - } - - /** - * - * Exports the data in an XML stream - * - * @param os OutputStream in which will contain the output XML - * @param validate if true, validates the XML against the XML Schema - * @throws SAXException If validating the document fails - * @throws TransformerException If transforming the document fails - */ - public void exportToXML(OutputStream os, boolean validate) throws SAXException, TransformerException { - exportToXML(os, "UTF-8", validate); - } - - /** - * Exports the data in an XML stream - * - * @param os OutputStream in which will contain the output XML - * @param encoding the output charset encoding - * @param validate if true, validates the XML against the XML Schema - * @throws SAXException If validating the document fails - * @throws TransformerException If transforming the document fails - */ - public void exportToXML(OutputStream os, String encoding, boolean validate) throws SAXException, TransformerException{ - List singleXMLCells = map.getRelatedSingleXMLCell(); - List tables = map.getRelatedTables(); - - String rootElement = map.getCtMap().getRootElement(); - - Document doc = DocumentHelper.createDocument(); - - final Element root; - - if (isNamespaceDeclared()) { - root = doc.createElementNS(getNamespace(),rootElement); - } else { - root = doc.createElementNS("", rootElement); - } - doc.appendChild(root); - - - List xpaths = new Vector(); - Map singleXmlCellsMappings = new HashMap(); - Map tableMappings = new HashMap(); - - for(XSSFSingleXmlCell simpleXmlCell : singleXMLCells) { - xpaths.add(simpleXmlCell.getXpath()); - singleXmlCellsMappings.put(simpleXmlCell.getXpath(), simpleXmlCell); - } - for(XSSFTable table : tables) { - String commonXPath = table.getCommonXpath(); - xpaths.add(commonXPath); - tableMappings.put(commonXPath, table); - } - - Collections.sort(xpaths,this); - - for(String xpath : xpaths) { - - XSSFSingleXmlCell simpleXmlCell = singleXmlCellsMappings.get(xpath); - XSSFTable table = tableMappings.get(xpath); - - if (!xpath.matches(".*\\[.*")) { - - // Exports elements and attributes mapped with simpleXmlCell - if (simpleXmlCell!=null) { - XSSFCell cell = simpleXmlCell.getReferencedCell(); - if (cell!=null) { - Node currentNode = getNodeByXPath(xpath,doc.getFirstChild(),doc,false); - mapCellOnNode(cell,currentNode); - - //remove nodes which are empty in order to keep the output xml valid - if("".equals(currentNode.getTextContent()) && currentNode.getParentNode() != null) { - currentNode.getParentNode().removeChild(currentNode); - } - } - } - - // Exports elements and attributes mapped with tables - if (table!=null) { - - List tableColumns = table.getXmlColumnPrs(); - - XSSFSheet sheet = table.getXSSFSheet(); - - int startRow = table.getStartCellReference().getRow(); - // In mappings created with Microsoft Excel the first row contains the table header and must be skipped - startRow +=1; - - int endRow = table.getEndCellReference().getRow(); - - for(int i = startRow; i<= endRow; i++) { - XSSFRow row = sheet.getRow(i); - - Node tableRootNode = getNodeByXPath(table.getCommonXpath(),doc.getFirstChild(),doc,true); - - short startColumnIndex = table.getStartCellReference().getCol(); - for(int j = startColumnIndex; j<= table.getEndCellReference().getCol();j++) { - XSSFCell cell = row.getCell(j); - if (cell!=null) { - XSSFXmlColumnPr pointer = tableColumns.get(j-startColumnIndex); - String localXPath = pointer.getLocalXPath(); - Node currentNode = getNodeByXPath(localXPath,tableRootNode,doc,false); - - mapCellOnNode(cell,currentNode); - } - } - } - } - } /*else { - // TODO: implement filtering management in xpath - }*/ - } - - boolean isValid = true; - if (validate) { - isValid =isValid(doc); - } - - if (isValid) { - - ///////////////// - //Output the XML - - //set up a transformer - TransformerFactory transfac = TransformerFactory.newInstance(); - Transformer trans = transfac.newTransformer(); - trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); - trans.setOutputProperty(OutputKeys.INDENT, "yes"); - trans.setOutputProperty(OutputKeys.ENCODING, encoding); - - //create string from xml tree - - StreamResult result = new StreamResult(os); - DOMSource source = new DOMSource(doc); - trans.transform(source, result); - - } - } - - - /** - * Validate the generated XML against the XML Schema associated with the XSSFMap - * - * @param xml the XML to validate - * @return true, if document is valid - * @throws SAXException If validating the document fails - */ - private boolean isValid(Document xml) throws SAXException{ - try{ - String language = "http://www.w3.org/2001/XMLSchema"; - SchemaFactory factory = SchemaFactory.newInstance(language); - - Source source = new DOMSource(map.getSchema()); - Schema schema = factory.newSchema(source); - Validator validator = schema.newValidator(); - validator.validate(new DOMSource(xml)); - - //if no exceptions where raised, the document is valid - return true; - } catch(IOException e) { - LOG.log(POILogger.ERROR, "document is not valid", e); - } - - return false; - } - - - private void mapCellOnNode(XSSFCell cell, Node node) { - - String value =""; - switch (cell.getCellTypeEnum()) { - - case STRING: value = cell.getStringCellValue(); break; - case BOOLEAN: value += cell.getBooleanCellValue(); break; - case ERROR: value = cell.getErrorCellString(); break; - case FORMULA: - if (cell.getCachedFormulaResultTypeEnum() == CellType.STRING) { - value = cell.getStringCellValue(); - } else { - if (DateUtil.isCellDateFormatted(cell)) { - value = getFormattedDate(cell); - } else { - value += cell.getNumericCellValue(); - } - } - break; - - case NUMERIC: - if (DateUtil.isCellDateFormatted(cell)) { - value = getFormattedDate(cell); - } else { - value += cell.getRawValue(); - } - break; - - default: - - } - if (node instanceof Element) { - Element currentElement = (Element) node; - currentElement.setTextContent(value); - } else { - node.setNodeValue(value); - } - } - - private String removeNamespace(String elementName) { - return elementName.matches(".*:.*")?elementName.split(":")[1]:elementName; - } - - private String getFormattedDate(XSSFCell cell) { - DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.ROOT); - sdf.setTimeZone(LocaleUtil.getUserTimeZone()); - return sdf.format(cell.getDateCellValue()); - } - - private Node getNodeByXPath(String xpath,Node rootNode,Document doc,boolean createMultipleInstances) { - String[] xpathTokens = xpath.split("/"); - - - Node currentNode =rootNode; - // The first token is empty, the second is the root node - for(int i =2; i rightIndex) { - return 1; - } - } /*else { - // NOTE: the xpath doesn't match correctly in the schema - }*/ - } - } - - return 0; - } - - private int indexOfElementInComplexType(String elementName,Node complexType) { - if(complexType == null) { - return -1; - } - - NodeList list = complexType.getChildNodes(); - int indexOf = -1; - - for(int i=0; i< list.getLength();i++) { - Node node = list.item(i); - if (node instanceof Element) { - if (node.getLocalName().equals("element")) { - Node element = getNameOrRefElement(node); - if (element.getNodeValue().equals(removeNamespace(elementName))) { - indexOf = i; - break; - } - - } - } - } - return indexOf; - } - - private Node getNameOrRefElement(Node node) { - Node returnNode = node.getAttributes().getNamedItem("name"); - if(returnNode != null) { - return returnNode; - } - - return node.getAttributes().getNamedItem("ref"); - } - - private Node getComplexTypeForElement(String elementName,Node xmlSchema,Node localComplexTypeRootNode) { - String elementNameWithoutNamespace = removeNamespace(elementName); - - String complexTypeName = getComplexTypeNameFromChildren(localComplexTypeRootNode, elementNameWithoutNamespace); - - // Note: we expect that all the complex types are defined at root level - Node complexTypeNode = null; - if (!"".equals(complexTypeName)) { - complexTypeNode = getComplexTypeNodeFromSchemaChildren(xmlSchema, null, complexTypeName); - } - - return complexTypeNode; - } - - private String getComplexTypeNameFromChildren(Node localComplexTypeRootNode, - String elementNameWithoutNamespace) { - if(localComplexTypeRootNode == null) { - return ""; - } - - NodeList list = localComplexTypeRootNode.getChildNodes(); - String complexTypeName = ""; - - for(int i=0; i< list.getLength();i++) { - Node node = list.item(i); - if ( node instanceof Element) { - if (node.getLocalName().equals("element")) { - Node nameAttribute = getNameOrRefElement(node); - if (nameAttribute.getNodeValue().equals(elementNameWithoutNamespace)) { - Node complexTypeAttribute = node.getAttributes().getNamedItem("type"); - if (complexTypeAttribute!=null) { - complexTypeName = complexTypeAttribute.getNodeValue(); - break; - } - } - } - } - } - return complexTypeName; - } - - private Node getComplexTypeNodeFromSchemaChildren(Node xmlSchema, Node complexTypeNode, - String complexTypeName) { - NodeList complexTypeList = xmlSchema.getChildNodes(); - for(int i=0; i< complexTypeList.getLength();i++) { - Node node = complexTypeList.item(i); - if ( node instanceof Element) { - if (node.getLocalName().equals("complexType")) { - Node nameAttribute = getNameOrRefElement(node); - if (nameAttribute.getNodeValue().equals(complexTypeName)) { - - NodeList complexTypeChildList =node.getChildNodes(); - for(int j=0; j - *
  • the input XML must be valid according to the XML Schema used in the mapping
  • - *
  • denormalized table mapping is not supported (see OpenOffice part 4: chapter 3.5.1.7)
  • - *
  • all the namespaces used in the document must be declared in the root node
  • - * - */ -public class XSSFImportFromXML { - - private final XSSFMap _map; - - private static final POILogger logger = POILogFactory.getLogger(XSSFImportFromXML.class); - - public XSSFImportFromXML(XSSFMap map) { - _map = map; - } - - /** - * Imports an XML into the XLSX using the Custom XML mapping defined - * - * @param xmlInputString the XML to import - * @throws SAXException if error occurs during XML parsing - * @throws XPathExpressionException if error occurs during XML navigation - * @throws ParserConfigurationException if there are problems with XML parser configuration - * @throws IOException if there are problems reading the input string - */ - public void importFromXML(String xmlInputString) throws SAXException, XPathExpressionException, IOException { - - DocumentBuilder builder = DocumentHelper.newDocumentBuilder(); - - Document doc = builder.parse(new InputSource(new StringReader(xmlInputString.trim()))); - - List singleXmlCells = _map.getRelatedSingleXMLCell(); - - List tables = _map.getRelatedTables(); - - XPathFactory xpathFactory = XPathFactory.newInstance(); - XPath xpath = xpathFactory.newXPath(); - - // Setting namespace context to XPath - // Assuming that the namespace prefix in the mapping xpath is the - // same as the one used in the document - xpath.setNamespaceContext(new DefaultNamespaceContext(doc)); - - for (XSSFSingleXmlCell singleXmlCell : singleXmlCells) { - - STXmlDataType.Enum xmlDataType = singleXmlCell.getXmlDataType(); - String xpathString = singleXmlCell.getXpath(); - Node result = (Node) xpath.evaluate(xpathString, doc, XPathConstants.NODE); - // result can be null if value is optional (xsd:minOccurs=0), see bugzilla 55864 - if (result != null) { - String textContent = result.getTextContent(); - logger.log(POILogger.DEBUG, "Extracting with xpath " + xpathString + " : value is '" + textContent + "'"); - XSSFCell cell = singleXmlCell.getReferencedCell(); - logger.log(POILogger.DEBUG, "Setting '" + textContent + "' to cell " + cell.getColumnIndex() + "-" + cell.getRowIndex() + " in sheet " - + cell.getSheet().getSheetName()); - setCellValue(textContent, cell, xmlDataType); - } - } - - for (XSSFTable table : tables) { - - String commonXPath = table.getCommonXpath(); - NodeList result = (NodeList) xpath.evaluate(commonXPath, doc, XPathConstants.NODESET); - int rowOffset = table.getStartCellReference().getRow() + 1;// the first row contains the table header - int columnOffset = table.getStartCellReference().getCol() - 1; - - for (int i = 0; i < result.getLength(); i++) { - - // TODO: implement support for denormalized XMLs (see - // OpenOffice part 4: chapter 3.5.1.7) - - Node singleNode = result.item(i).cloneNode(true); - for (XSSFXmlColumnPr xmlColumnPr : table.getXmlColumnPrs()) { - - int localColumnId = (int) xmlColumnPr.getId(); - int rowId = rowOffset + i; - int columnId = columnOffset + localColumnId; - String localXPath = xmlColumnPr.getLocalXPath(); - localXPath = localXPath.substring(localXPath.substring(1).indexOf('/') + 2); - - // TODO: convert the data to the cell format - String value = (String) xpath.evaluate(localXPath, singleNode, XPathConstants.STRING); - logger.log(POILogger.DEBUG, "Extracting with xpath " + localXPath + " : value is '" + value + "'"); - XSSFRow row = table.getXSSFSheet().getRow(rowId); - if (row == null) { - row = table.getXSSFSheet().createRow(rowId); - } - - XSSFCell cell = row.getCell(columnId); - if (cell == null) { - cell = row.createCell(columnId); - } - logger.log(POILogger.DEBUG, "Setting '" + value + "' to cell " + cell.getColumnIndex() + "-" + cell.getRowIndex() + " in sheet " - + table.getXSSFSheet().getSheetName()); - setCellValue(value, cell, xmlColumnPr.getXmlDataType()); - } - } - } - } - - private static enum DataType { - BOOLEAN(STXmlDataType.BOOLEAN), // - DOUBLE(STXmlDataType.DOUBLE), // - INTEGER(STXmlDataType.INT, STXmlDataType.UNSIGNED_INT, STXmlDataType.INTEGER), // - STRING(STXmlDataType.STRING), // - DATE(STXmlDataType.DATE); - - private Set xmlDataTypes; - - private DataType(STXmlDataType.Enum... xmlDataTypes) { - this.xmlDataTypes = new HashSet(Arrays.asList(xmlDataTypes)); - } - - public static DataType getDataType(STXmlDataType.Enum xmlDataType) { - for (DataType dataType : DataType.values()) { - if (dataType.xmlDataTypes.contains(xmlDataType)) { - return dataType; - } - } - return null; - } - } - - private void setCellValue(String value, XSSFCell cell, STXmlDataType.Enum xmlDataType) { - DataType type = DataType.getDataType(xmlDataType); - try { - if (value.isEmpty() || type == null) { - cell.setCellValue((String) null); - } else { - switch (type) { - case BOOLEAN: - cell.setCellValue(Boolean.parseBoolean(value)); - break; - case DOUBLE: - cell.setCellValue(Double.parseDouble(value)); - break; - case INTEGER: - cell.setCellValue(Integer.parseInt(value)); - break; - case DATE: - DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", LocaleUtil.getUserLocale()); - Date date = sdf.parse(value); - cell.setCellValue(date); - if (!DateUtil.isValidExcelDate(cell.getNumericCellValue())) { - cell.setCellValue(value); - } - break; - case STRING: - default: - cell.setCellValue(value.trim()); - break; - } - } - } catch (IllegalArgumentException e) { - throw new IllegalArgumentException(String.format(LocaleUtil.getUserLocale(), "Unable to format value '%s' as %s for cell %s", value, - type, new CellReference(cell).formatAsString())); - } catch (ParseException e) { - throw new IllegalArgumentException(String.format(LocaleUtil.getUserLocale(), "Unable to format value '%s' as %s for cell %s", value, - type, new CellReference(cell).formatAsString())); - } - } - - private static final class DefaultNamespaceContext implements NamespaceContext { - /** - * Node from which to start searching for a xmlns attribute that binds a - * prefix to a namespace. - */ - private final Element _docElem; - - public DefaultNamespaceContext(Document doc) { - _docElem = doc.getDocumentElement(); - } - - @Override - public String getNamespaceURI(String prefix) { - return getNamespaceForPrefix(prefix); - } - - /** - * @param prefix Prefix to resolve. - * @return uri of Namespace that prefix resolves to, or - * null if specified prefix is not bound. - */ - private String getNamespaceForPrefix(String prefix) { - - // Code adapted from Xalan's org.apache.xml.utils.PrefixResolverDefault.getNamespaceForPrefix() - - if (prefix.equals("xml")) { - return "http://www.w3.org/XML/1998/namespace"; - } - - Node parent = _docElem; - - while (parent != null) { - - int type = parent.getNodeType(); - if (type == Node.ELEMENT_NODE) { - if (parent.getNodeName().startsWith(prefix + ":")) { - return parent.getNamespaceURI(); - } - NamedNodeMap nnm = parent.getAttributes(); - - for (int i = 0; i < nnm.getLength(); i++) { - Node attr = nnm.item(i); - String aname = attr.getNodeName(); - boolean isPrefix = aname.startsWith("xmlns:"); - - if (isPrefix || aname.equals("xmlns")) { - int index = aname.indexOf(':'); - String p = isPrefix ? aname.substring(index + 1) : ""; - - if (p.equals(prefix)) { - return attr.getNodeValue(); - } - } - } - } else if (type == Node.ENTITY_REFERENCE_NODE) { - continue; - } else { - break; - } - parent = parent.getParentNode(); - } - - return null; - } - - // Dummy implementation - not used! - @Override - public Iterator getPrefixes(String val) { - return null; - } - - // Dummy implementation - not used! - @Override - public String getPrefix(String uri) { - return null; - } - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/model/CalculationChain.java b/src/ooxml/java/org/apache/poi/xssf/model/CalculationChain.java deleted file mode 100644 index 5e2a980c0..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/model/CalculationChain.java +++ /dev/null @@ -1,105 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.model; - -import static org.apache.poi.POIXMLTypeLoader.DEFAULT_XML_OPTIONS; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.xmlbeans.XmlException; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCalcCell; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCalcChain; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CalcChainDocument; - -/** - * The cells in a workbook can be calculated in different orders depending on various optimizations and - * dependencies. The calculation chain object specifies the order in which the cells in a workbook were last calculated. - * - * @author Yegor Kozlov - */ -public class CalculationChain extends POIXMLDocumentPart { - private CTCalcChain chain; - - public CalculationChain() { - super(); - chain = CTCalcChain.Factory.newInstance(); - } - - /** - * @since POI 3.14-Beta1 - */ - public CalculationChain(PackagePart part) throws IOException { - super(part); - readFrom(part.getInputStream()); - } - - public void readFrom(InputStream is) throws IOException { - try { - CalcChainDocument doc = CalcChainDocument.Factory.parse(is, DEFAULT_XML_OPTIONS); - chain = doc.getCalcChain(); - } catch (XmlException e) { - throw new IOException(e.getLocalizedMessage()); - } - } - public void writeTo(OutputStream out) throws IOException { - CalcChainDocument doc = CalcChainDocument.Factory.newInstance(); - doc.setCalcChain(chain); - doc.save(out, DEFAULT_XML_OPTIONS); - } - - @Override - protected void commit() throws IOException { - PackagePart part = getPackagePart(); - OutputStream out = part.getOutputStream(); - writeTo(out); - out.close(); - } - - - public CTCalcChain getCTCalcChain(){ - return chain; - } - - /** - * Remove a formula reference from the calculation chain - * - * @param sheetId the sheet Id of a sheet the formula belongs to. - * @param ref A1 style reference to the cell containing the formula. - */ - public void removeItem(int sheetId, String ref){ - //sheet Id of a sheet the cell belongs to - int id = -1; - CTCalcCell[] c = chain.getCArray(); - - for (int i = 0; i < c.length; i++){ - //If sheet Id is omitted, it is assumed to be the same as the value of the previous cell. - if(c[i].isSetI()) id = c[i].getI(); - - if(id == sheetId && c[i].getR().equals(ref)){ - if(c[i].isSetI() && i < c.length - 1 && !c[i+1].isSetI()) { - c[i+1].setI(id); - } - chain.removeC(i); - break; - } - } - } -} \ No newline at end of file diff --git a/src/ooxml/java/org/apache/poi/xssf/model/CommentsTable.java b/src/ooxml/java/org/apache/poi/xssf/model/CommentsTable.java deleted file mode 100644 index aca3834e7..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/model/CommentsTable.java +++ /dev/null @@ -1,306 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.model; - -import static org.apache.poi.POIXMLTypeLoader.DEFAULT_XML_OPTIONS; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; -import java.util.TreeMap; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.ss.util.CellAddress; -import org.apache.poi.util.Internal; -import org.apache.poi.xssf.usermodel.XSSFComment; -import org.apache.xmlbeans.XmlException; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTComment; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCommentList; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTComments; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CommentsDocument; - -@Internal -public class CommentsTable extends POIXMLDocumentPart { - public static final String DEFAULT_AUTHOR = ""; - public static final int DEFAULT_AUTHOR_ID = 0; - /** - * Underlying XML Beans CTComment list. - */ - private CTComments comments; - /** - * XML Beans uses a list, which is very slow - * to search, so we wrap things with our own - * map for fast lookup. - */ - private Map commentRefs; - - public CommentsTable() { - super(); - comments = CTComments.Factory.newInstance(); - comments.addNewCommentList(); - comments.addNewAuthors().addAuthor(DEFAULT_AUTHOR); - } - - /** - * @since POI 3.14-Beta1 - */ - public CommentsTable(PackagePart part) throws IOException { - super(part); - readFrom(part.getInputStream()); - } - - public void readFrom(InputStream is) throws IOException { - try { - CommentsDocument doc = CommentsDocument.Factory.parse(is, DEFAULT_XML_OPTIONS); - comments = doc.getComments(); - } catch (XmlException e) { - throw new IOException(e.getLocalizedMessage()); - } - } - public void writeTo(OutputStream out) throws IOException { - CommentsDocument doc = CommentsDocument.Factory.newInstance(); - doc.setComments(comments); - doc.save(out, DEFAULT_XML_OPTIONS); - } - - @Override - protected void commit() throws IOException { - PackagePart part = getPackagePart(); - OutputStream out = part.getOutputStream(); - writeTo(out); - out.close(); - } - - /** - * Called after the reference is updated, so that - * we can reflect that in our cache - * @deprecated 2015-11-23 (circa POI 3.14beta1). Use {@link #referenceUpdated(CellAddress, CTComment)} instead - */ - public void referenceUpdated(String oldReference, CTComment comment) { - referenceUpdated(new CellAddress(oldReference), comment); - } - - /** - * Called after the reference is updated, so that - * we can reflect that in our cache - * @param oldReference the comment to remove from the commentRefs map - * @param comment the comment to replace in the commentRefs map - */ - public void referenceUpdated(CellAddress oldReference, CTComment comment) { - if(commentRefs != null) { - commentRefs.remove(oldReference); - commentRefs.put(new CellAddress(comment.getRef()), comment); - } - } - - public int getNumberOfComments() { - return comments.getCommentList().sizeOfCommentArray(); - } - - public int getNumberOfAuthors() { - return comments.getAuthors().sizeOfAuthorArray(); - } - - public String getAuthor(long authorId) { - return comments.getAuthors().getAuthorArray((int)authorId); - } - - public int findAuthor(String author) { - String[] authorArray = comments.getAuthors().getAuthorArray(); - for (int i = 0 ; i < authorArray.length; i++) { - if (authorArray[i].equals(author)) { - return i; - } - } - return addNewAuthor(author); - } - - /** - * Finds the cell comment at cellAddress, if one exists - * - * @param cellRef the address of the cell to find a comment - * @return cell comment if one exists, otherwise returns null - * @deprecated 2015-11-23 (circa POI 3.14beta1). Use {@link #findCellComment(CellAddress)} instead - */ - public XSSFComment findCellComment(String cellRef) { - return findCellComment(new CellAddress(cellRef)); - } - - /** - * Finds the cell comment at cellAddress, if one exists - * - * @param cellAddress the address of the cell to find a comment - * @return cell comment if one exists, otherwise returns null - */ - public XSSFComment findCellComment(CellAddress cellAddress) { - CTComment ct = getCTComment(cellAddress); - return ct == null ? null : new XSSFComment(this, ct, null); - } - - - /** - * Get the underlying CTComment xmlbean for a comment located at cellRef, if it exists - * - * @param ref the location of the cell comment - * @return CTComment xmlbean if comment exists, otherwise return null. - * @deprecated 2015-11-23 (circa POI 3.14beta1). Use {@link CommentsTable#getCTComment(CellAddress)} instead - */ - @Internal - public CTComment getCTComment(String ref) { - return getCTComment(new CellAddress(ref)); - } - - /** - * Get the underlying CTComment xmlbean for a comment located at cellRef, if it exists - * - * @param cellRef the location of the cell comment - * @return CTComment xmlbean if comment exists, otherwise return null. - */ - @Internal - public CTComment getCTComment(CellAddress cellRef) { - // Create the cache if needed - prepareCTCommentCache(); - - // Return the comment, or null if not known - return commentRefs.get(cellRef); - } - - /** - * Returns all cell comments on this sheet. - * @return A map of each Comment in this sheet, keyed on the cell address where - * the comment is located. - */ - public Map getCellComments() { - prepareCTCommentCache(); - final TreeMap map = new TreeMap(); - - for (final Entry e: commentRefs.entrySet()) { - map.put(e.getKey(), new XSSFComment(this, e.getValue(), null)); - } - - return map; - } - - /** - * Refresh Map commentRefs cache, - * Calls that use the commentRefs cache will perform in O(1) - * time rather than O(n) lookup time for List comments. - */ - private void prepareCTCommentCache() { - // Create the cache if needed - if(commentRefs == null) { - commentRefs = new HashMap(); - for (CTComment comment : comments.getCommentList().getCommentArray()) { - commentRefs.put(new CellAddress(comment.getRef()), comment); - } - } - } - - /** - * Create a new comment located at cell address - * - * @param ref the location to add the comment - * @return a new CTComment located at ref with default author - * @deprecated 2015-11-23 (circa POI 3.14beta1). Use {@link #newComment(CellAddress)} instead - */ - @Internal - public CTComment newComment(String ref) { - return newComment(new CellAddress(ref)); - } - - /** - * Create a new comment located` at cell address - * - * @param ref the location to add the comment - * @return a new CTComment located at ref with default author - */ - @Internal - public CTComment newComment(CellAddress ref) { - CTComment ct = comments.getCommentList().addNewComment(); - ct.setRef(ref.formatAsString()); - ct.setAuthorId(DEFAULT_AUTHOR_ID); - - if(commentRefs != null) { - commentRefs.put(ref, ct); - } - return ct; - } - - /** - * Remove the comment at cellRef location, if one exists - * - * @param cellRef the location of the comment to remove - * @return returns true if a comment was removed - * @deprecated 2015-11-23 (circa POI 3.14beta1). Use {@link #removeComment(CellAddress)} instead - */ - public boolean removeComment(String cellRef) { - return removeComment(new CellAddress(cellRef)); - } - - /** - * Remove the comment at cellRef location, if one exists - * - * @param cellRef the location of the comment to remove - * @return returns true if a comment was removed - */ - public boolean removeComment(CellAddress cellRef) { - final String stringRef = cellRef.formatAsString(); - CTCommentList lst = comments.getCommentList(); - if(lst != null) { - CTComment[] commentArray = lst.getCommentArray(); - for (int i = 0; i < commentArray.length; i++) { - CTComment comment = commentArray[i]; - if (stringRef.equals(comment.getRef())) { - lst.removeComment(i); - - if(commentRefs != null) { - commentRefs.remove(cellRef); - } - return true; - } - } - } - return false; - } - - /** - * Add a new author to the CommentsTable. - * This does not check if the author already exists. - * - * @param author the name of the comment author - * @return the index of the new author - */ - private int addNewAuthor(String author) { - int index = comments.getAuthors().sizeOfAuthorArray(); - comments.getAuthors().insertAuthor(index, author); - return index; - } - - /** - * Returns the underlying CTComments list xmlbean - * - * @return underlying comments list xmlbean - */ - @Internal - public CTComments getCTComments(){ - return comments; - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/model/ExternalLinksTable.java b/src/ooxml/java/org/apache/poi/xssf/model/ExternalLinksTable.java deleted file mode 100644 index 8a796924d..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/model/ExternalLinksTable.java +++ /dev/null @@ -1,203 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.model; - -import static org.apache.poi.POIXMLTypeLoader.DEFAULT_XML_OPTIONS; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.opc.PackageRelationship; -import org.apache.poi.openxml4j.opc.PackageRelationshipTypes; -import org.apache.poi.openxml4j.opc.TargetMode; -import org.apache.poi.ss.usermodel.Name; -import org.apache.xmlbeans.XmlException; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTExternalDefinedName; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTExternalLink; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTExternalSheetName; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.ExternalLinkDocument; - -/** - * Holds details of links to parts of other workbooks (eg named ranges), - * along with the most recently seen values for what they point to. - */ -public class ExternalLinksTable extends POIXMLDocumentPart { - private CTExternalLink link; - - public ExternalLinksTable() { - super(); - link = CTExternalLink.Factory.newInstance(); - link.addNewExternalBook(); - } - - /** - * @since POI 3.14-Beta1 - */ - public ExternalLinksTable(PackagePart part) throws IOException { - super(part); - readFrom(part.getInputStream()); - } - - public void readFrom(InputStream is) throws IOException { - try { - ExternalLinkDocument doc = ExternalLinkDocument.Factory.parse(is, DEFAULT_XML_OPTIONS); - link = doc.getExternalLink(); - } catch (XmlException e) { - throw new IOException(e.getLocalizedMessage()); - } - } - public void writeTo(OutputStream out) throws IOException { - ExternalLinkDocument doc = ExternalLinkDocument.Factory.newInstance(); - doc.setExternalLink(link); - doc.save(out, DEFAULT_XML_OPTIONS); - } - - @Override - protected void commit() throws IOException { - PackagePart part = getPackagePart(); - OutputStream out = part.getOutputStream(); - writeTo(out); - out.close(); - } - - /** - * Returns the underlying xmlbeans object for the external - * link table - */ - public CTExternalLink getCTExternalLink(){ - return link; - } - - /** - * Returns the last recorded name of the file that this - * is linked to - */ - public String getLinkedFileName() { - String rId = link.getExternalBook().getId(); - PackageRelationship rel = getPackagePart().getRelationship(rId); - if (rel != null && rel.getTargetMode() == TargetMode.EXTERNAL) { - return rel.getTargetURI().toString(); - } else { - return null; - } - } - /** - * Updates the last recorded name for the file that this links to - */ - public void setLinkedFileName(String target) { - String rId = link.getExternalBook().getId(); - - if (rId == null || rId.isEmpty()) { - // We're a new External Link Table, so nothing to remove - } else { - // Relationships can't be changed, so remove the old one - getPackagePart().removeRelationship(rId); - } - - // Have a new one added - PackageRelationship newRel = getPackagePart().addExternalRelationship( - target, PackageRelationshipTypes.EXTERNAL_LINK_PATH); - link.getExternalBook().setId(newRel.getId()); - } - - public List getSheetNames() { - CTExternalSheetName[] sheetNames = - link.getExternalBook().getSheetNames().getSheetNameArray(); - List names = new ArrayList(sheetNames.length); - for (CTExternalSheetName name : sheetNames) { - names.add(name.getVal()); - } - return names; - } - - public List getDefinedNames() { - CTExternalDefinedName[] extNames = - link.getExternalBook().getDefinedNames().getDefinedNameArray(); - List names = new ArrayList(extNames.length); - for (CTExternalDefinedName extName : extNames) { - names.add(new ExternalName(extName)); - } - return names; - } - - - // TODO Last seen data - - - protected class ExternalName implements Name { - private CTExternalDefinedName name; - protected ExternalName(CTExternalDefinedName name) { - this.name = name; - } - - public String getNameName() { - return name.getName(); - } - public void setNameName(String name) { - this.name.setName(name); - } - - public String getSheetName() { - int sheetId = getSheetIndex(); - if (sheetId >= 0) { - return getSheetNames().get(sheetId); - } else { - return null; - } - } - public int getSheetIndex() { - if (name.isSetSheetId()) { - return (int)name.getSheetId(); - } - return -1; - } - public void setSheetIndex(int sheetId) { - name.setSheetId(sheetId); - } - - public String getRefersToFormula() { - // Return, without the leading = - return name.getRefersTo().substring(1); - } - public void setRefersToFormula(String formulaText) { - // Save with leading = - name.setRefersTo('=' + formulaText); - } - - public boolean isFunctionName() { - return false; - } - public boolean isDeleted() { - return false; - } - - public String getComment() { - return null; - } - public void setComment(String comment) { - throw new IllegalStateException("Not Supported"); - } - public void setFunction(boolean value) { - throw new IllegalStateException("Not Supported"); - } - } -} \ No newline at end of file diff --git a/src/ooxml/java/org/apache/poi/xssf/model/MapInfo.java b/src/ooxml/java/org/apache/poi/xssf/model/MapInfo.java deleted file mode 100644 index ab4522134..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/model/MapInfo.java +++ /dev/null @@ -1,161 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.model; - -import static org.apache.poi.POIXMLTypeLoader.DEFAULT_XML_OPTIONS; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.xssf.usermodel.XSSFMap; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.apache.xmlbeans.XmlException; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTMap; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTMapInfo; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTSchema; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.MapInfoDocument; - -/** - * - * This class implements the Custom XML Mapping Part (Open Office XML Part 1: - * chapter 12.3.6) - * - * An instance of this part type contains a schema for an XML file, and - * information on the behavior that is used when allowing this custom XML schema - * to be mapped into the spreadsheet. - * - * @author Roberto Manicardi - */ - -public class MapInfo extends POIXMLDocumentPart { - - private CTMapInfo mapInfo; - - private Map maps ; - - public MapInfo() { - super(); - mapInfo = CTMapInfo.Factory.newInstance(); - - } - - /** - * @since POI 3.14-Beta1 - */ - public MapInfo(PackagePart part) throws IOException { - super(part); - readFrom(part.getInputStream()); - } - - public void readFrom(InputStream is) throws IOException { - try { - MapInfoDocument doc = MapInfoDocument.Factory.parse(is, DEFAULT_XML_OPTIONS); - mapInfo = doc.getMapInfo(); - - maps= new HashMap(); - for(CTMap map :mapInfo.getMapArray()){ - maps.put((int)map.getID(), new XSSFMap(map,this)); - } - - } catch (XmlException e) { - throw new IOException(e.getLocalizedMessage()); - } - } - - /** - * Returns the parent XSSFWorkbook - * - * @return the parent XSSFWorkbook - */ - public XSSFWorkbook getWorkbook() { - return (XSSFWorkbook)getParent(); - } - - /** - * - * @return the internal data object - */ - public CTMapInfo getCTMapInfo(){ - return mapInfo; - - } - - /** - * Gets the - * @param schemaId the schema ID - * @return CTSchema by it's ID - */ - public CTSchema getCTSchemaById(String schemaId){ - CTSchema xmlSchema = null; - - for(CTSchema schema: mapInfo.getSchemaArray()){ - if(schema.getID().equals(schemaId)){ - xmlSchema = schema; - break; - } - } - return xmlSchema; - } - - - public XSSFMap getXSSFMapById(int id){ - return maps.get(id); - } - - public XSSFMap getXSSFMapByName(String name){ - - XSSFMap matchedMap = null; - - for(XSSFMap map :maps.values()){ - if(map.getCtMap().getName()!=null && map.getCtMap().getName().equals(name)){ - matchedMap = map; - } - } - - return matchedMap; - } - - /** - * - * @return all the mappings configured in this document - */ - public Collection getAllXSSFMaps(){ - return maps.values(); - } - - protected void writeTo(OutputStream out) throws IOException { - MapInfoDocument doc = MapInfoDocument.Factory.newInstance(); - doc.setMapInfo(mapInfo); - doc.save(out, DEFAULT_XML_OPTIONS); - } - - @Override - protected void commit() throws IOException { - PackagePart part = getPackagePart(); - OutputStream out = part.getOutputStream(); - writeTo(out); - out.close(); - } - -} diff --git a/src/ooxml/java/org/apache/poi/xssf/model/ParagraphPropertyFetcher.java b/src/ooxml/java/org/apache/poi/xssf/model/ParagraphPropertyFetcher.java deleted file mode 100644 index 00f40f790..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/model/ParagraphPropertyFetcher.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xssf.model; - -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextParagraphProperties; -import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTShape; -import org.apache.xmlbeans.XmlObject; -import org.apache.poi.util.Internal; - -/** - * Used internally to navigate the paragraph text style hierarchy within a shape and fetch properties -*/ -@Internal -public abstract class ParagraphPropertyFetcher { - - private T _value; - private int _level; - - public T getValue(){ - return _value; - } - - public void setValue(T val){ - _value = val; - } - - public ParagraphPropertyFetcher(int level) { - _level = level; - } - - /** - * - * @param shape the shape being examined - * @return true if the desired property was fetched - */ - public boolean fetch(CTShape shape) { - - XmlObject[] o = shape.selectPath( - "declare namespace xdr='http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing' " + - "declare namespace a='http://schemas.openxmlformats.org/drawingml/2006/main' " + - ".//xdr:txBody/a:lstStyle/a:lvl" + (_level + 1) + "pPr" - ); - if (o.length == 1) { - CTTextParagraphProperties props = (CTTextParagraphProperties) o[0]; - return fetch(props); - } - return false; - } - - public abstract boolean fetch(CTTextParagraphProperties props); -} \ No newline at end of file diff --git a/src/ooxml/java/org/apache/poi/xssf/model/SharedStringsTable.java b/src/ooxml/java/org/apache/poi/xssf/model/SharedStringsTable.java deleted file mode 100644 index 59526d33e..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/model/SharedStringsTable.java +++ /dev/null @@ -1,232 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.model; - -import static org.apache.poi.POIXMLTypeLoader.DEFAULT_XML_OPTIONS; -import static org.apache.poi.xssf.usermodel.XSSFRelation.NS_SPREADSHEETML; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlOptions; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRst; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTSst; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.SstDocument; - -/** - * Table of strings shared across all sheets in a workbook. - *

    - * A workbook may contain thousands of cells containing string (non-numeric) data. Furthermore this data is very - * likely to be repeated across many rows or columns. The goal of implementing a single string table that is shared - * across the workbook is to improve performance in opening and saving the file by only reading and writing the - * repetitive information once. - *

    - *

    - * Consider for example a workbook summarizing information for cities within various countries. There may be a - * column for the name of the country, a column for the name of each city in that country, and a column - * containing the data for each city. In this case the country name is repetitive, being duplicated in many cells. - * In many cases the repetition is extensive, and a tremendous savings is realized by making use of a shared string - * table when saving the workbook. When displaying text in the spreadsheet, the cell table will just contain an - * index into the string table as the value of a cell, instead of the full string. - *

    - *

    - * The shared string table contains all the necessary information for displaying the string: the text, formatting - * properties, and phonetic properties (for East Asian languages). - *

    - */ -public class SharedStringsTable extends POIXMLDocumentPart { - - /** - * Array of individual string items in the Shared String table. - */ - private final List strings = new ArrayList(); - - /** - * Maps strings and their indexes in the strings arrays - */ - private final Map stmap = new HashMap(); - - /** - * An integer representing the total count of strings in the workbook. This count does not - * include any numbers, it counts only the total of text strings in the workbook. - */ - private int count; - - /** - * An integer representing the total count of unique strings in the Shared String Table. - * A string is unique even if it is a copy of another string, but has different formatting applied - * at the character level. - */ - private int uniqueCount; - - private SstDocument _sstDoc; - - private static final XmlOptions options = new XmlOptions(); - static { - options.put( XmlOptions.SAVE_INNER ); - options.put( XmlOptions.SAVE_AGGRESSIVE_NAMESPACES ); - options.put( XmlOptions.SAVE_USE_DEFAULT_NAMESPACE ); - options.setSaveImplicitNamespaces(Collections.singletonMap("", NS_SPREADSHEETML)); - } - - public SharedStringsTable() { - super(); - _sstDoc = SstDocument.Factory.newInstance(); - _sstDoc.addNewSst(); - } - - /** - * @since POI 3.14-Beta1 - */ - public SharedStringsTable(PackagePart part) throws IOException { - super(part); - readFrom(part.getInputStream()); - } - - /** - * Read this shared strings table from an XML file. - * - * @param is The input stream containing the XML document. - * @throws IOException if an error occurs while reading. - */ - public void readFrom(InputStream is) throws IOException { - try { - int cnt = 0; - _sstDoc = SstDocument.Factory.parse(is, DEFAULT_XML_OPTIONS); - CTSst sst = _sstDoc.getSst(); - count = (int)sst.getCount(); - uniqueCount = (int)sst.getUniqueCount(); - for (CTRst st : sst.getSiArray()) { - stmap.put(getKey(st), cnt); - strings.add(st); - cnt++; - } - } catch (XmlException e) { - throw new IOException("unable to parse shared strings table", e); - } - } - - private String getKey(CTRst st) { - return st.xmlText(options); - } - - /** - * Return a string item by index - * - * @param idx index of item to return. - * @return the item at the specified position in this Shared String table. - */ - public CTRst getEntryAt(int idx) { - return strings.get(idx); - } - - /** - * Return an integer representing the total count of strings in the workbook. This count does not - * include any numbers, it counts only the total of text strings in the workbook. - * - * @return the total count of strings in the workbook - */ - public int getCount(){ - return count; - } - - /** - * Returns an integer representing the total count of unique strings in the Shared String Table. - * A string is unique even if it is a copy of another string, but has different formatting applied - * at the character level. - * - * @return the total count of unique strings in the workbook - */ - public int getUniqueCount(){ - return uniqueCount; - } - - /** - * Add an entry to this Shared String table (a new value is appened to the end). - * - *

    - * If the Shared String table already contains this CTRst bean, its index is returned. - * Otherwise a new entry is aded. - *

    - * - * @param st the entry to add - * @return index the index of added entry - */ - public int addEntry(CTRst st) { - String s = getKey(st); - count++; - if (stmap.containsKey(s)) { - return stmap.get(s); - } - - uniqueCount++; - //create a CTRst bean attached to this SstDocument and copy the argument CTRst into it - CTRst newSt = _sstDoc.getSst().addNewSi(); - newSt.set(st); - int idx = strings.size(); - stmap.put(s, idx); - strings.add(newSt); - return idx; - } - /** - * Provide low-level access to the underlying array of CTRst beans - * - * @return array of CTRst beans - */ - public List getItems() { - return Collections.unmodifiableList(strings); - } - - /** - * Write this table out as XML. - * - * @param out The stream to write to. - * @throws IOException if an error occurs while writing. - */ - public void writeTo(OutputStream out) throws IOException { - XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS); - // the following two lines turn off writing CDATA - // see Bugzilla 48936 - xmlOptions.setSaveCDataLengthThreshold(1000000); - xmlOptions.setSaveCDataEntityCountThreshold(-1); - - //re-create the sst table every time saving a workbook - CTSst sst = _sstDoc.getSst(); - sst.setCount(count); - sst.setUniqueCount(uniqueCount); - - _sstDoc.save(out, xmlOptions); - } - - @Override - protected void commit() throws IOException { - PackagePart part = getPackagePart(); - OutputStream out = part.getOutputStream(); - writeTo(out); - out.close(); - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/model/SingleXmlCells.java b/src/ooxml/java/org/apache/poi/xssf/model/SingleXmlCells.java deleted file mode 100644 index fb1c80bb3..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/model/SingleXmlCells.java +++ /dev/null @@ -1,108 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.model; - -import static org.apache.poi.POIXMLTypeLoader.DEFAULT_XML_OPTIONS; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.List; -import java.util.Vector; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.helpers.XSSFSingleXmlCell; -import org.apache.xmlbeans.XmlException; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTSingleXmlCell; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTSingleXmlCells; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.SingleXmlCellsDocument; - - -/** - * - * This class implements the Single Cell Tables Part (Open Office XML Part 4: - * chapter 3.5.2) - * - * - * @author Roberto Manicardi - */ -public class SingleXmlCells extends POIXMLDocumentPart { - - - private CTSingleXmlCells singleXMLCells; - - public SingleXmlCells() { - super(); - singleXMLCells = CTSingleXmlCells.Factory.newInstance(); - - } - - /** - * @since POI 3.14-Beta1 - */ - public SingleXmlCells(PackagePart part) throws IOException { - super(part); - readFrom(part.getInputStream()); - } - - public void readFrom(InputStream is) throws IOException { - try { - SingleXmlCellsDocument doc = SingleXmlCellsDocument.Factory.parse(is, DEFAULT_XML_OPTIONS); - singleXMLCells = doc.getSingleXmlCells(); - } catch (XmlException e) { - throw new IOException(e.getLocalizedMessage()); - } - } - - public XSSFSheet getXSSFSheet(){ - return (XSSFSheet) getParent(); - } - - protected void writeTo(OutputStream out) throws IOException { - SingleXmlCellsDocument doc = SingleXmlCellsDocument.Factory.newInstance(); - doc.setSingleXmlCells(singleXMLCells); - doc.save(out, DEFAULT_XML_OPTIONS); - } - - @Override - protected void commit() throws IOException { - PackagePart part = getPackagePart(); - OutputStream out = part.getOutputStream(); - writeTo(out); - out.close(); - } - - public CTSingleXmlCells getCTSingleXMLCells(){ - return singleXMLCells; - } - - /** - * - * @return all the SimpleXmlCell contained in this SingleXmlCells element - */ - public List getAllSimpleXmlCell(){ - List list = new Vector(); - - for(CTSingleXmlCell singleXmlCell: singleXMLCells.getSingleXmlCellArray()){ - list.add(new XSSFSingleXmlCell(singleXmlCell,this)); - } - return list; - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/model/StylesTable.java b/src/ooxml/java/org/apache/poi/xssf/model/StylesTable.java deleted file mode 100644 index c192aed3d..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/model/StylesTable.java +++ /dev/null @@ -1,833 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.model; - -import static org.apache.poi.POIXMLTypeLoader.DEFAULT_XML_OPTIONS; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.SortedMap; -import java.util.TreeMap; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.ss.usermodel.BuiltinFormats; -import org.apache.poi.ss.usermodel.FontFamily; -import org.apache.poi.ss.usermodel.FontScheme; -import org.apache.poi.util.Internal; -import org.apache.poi.xssf.usermodel.XSSFCellStyle; -import org.apache.poi.xssf.usermodel.XSSFFactory; -import org.apache.poi.xssf.usermodel.XSSFFont; -import org.apache.poi.xssf.usermodel.XSSFRelation; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.apache.poi.xssf.usermodel.extensions.XSSFCellBorder; -import org.apache.poi.xssf.usermodel.extensions.XSSFCellFill; -import org.apache.xmlbeans.XmlException; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTBorder; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTBorders; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCellStyleXfs; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCellXfs; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTDxf; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTDxfs; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTFill; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTFills; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTFont; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTFonts; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTNumFmt; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTNumFmts; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTStylesheet; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTXf; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STPatternType; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.StyleSheetDocument; - -/** - * Table of styles shared across all sheets in a workbook. - */ -public class StylesTable extends POIXMLDocumentPart { - private final SortedMap numberFormats = new TreeMap(); - private final List fonts = new ArrayList(); - private final List fills = new ArrayList(); - private final List borders = new ArrayList(); - private final List styleXfs = new ArrayList(); - private final List xfs = new ArrayList(); - - private final List dxfs = new ArrayList(); - - /** - * The first style id available for use as a custom style - */ - public static final int FIRST_CUSTOM_STYLE_ID = BuiltinFormats.FIRST_USER_DEFINED_FORMAT_INDEX + 1; - // Is this right? Number formats (XSSFDataFormat) and cell styles (XSSFCellStyle) are different. What's up with the plus 1? - private static final int MAXIMUM_STYLE_ID = SpreadsheetVersion.EXCEL2007.getMaxCellStyles(); - - private static final short FIRST_USER_DEFINED_NUMBER_FORMAT_ID = BuiltinFormats.FIRST_USER_DEFINED_FORMAT_INDEX; - /** - * Depending on the version of Excel, the maximum number of number formats in a workbook is between 200 and 250 - * See https://support.office.com/en-us/article/excel-specifications-and-limits-1672b34d-7043-467e-8e27-269d656771c3 - * POI defaults this limit to 250, but can be increased or decreased on a per-StylesTable basis with - * {@link #setMaxNumberOfDataFormats(int)} if needed. - */ - private int MAXIMUM_NUMBER_OF_DATA_FORMATS = 250; - - /** - * Changes the maximum number of data formats that may be in a style table - * - * @param num the upper limit on number of data formats in the styles table when adding new data formats - * @throws IllegalArgumentException if num < 0 - * @throws IllegalStateException if num < current number of data formats in the style table. - * Data formats must be explicitly removed before the limit can be decreased. - */ - public void setMaxNumberOfDataFormats(int num) { - if (num < getNumDataFormats()) { - if (num < 0) { - throw new IllegalArgumentException("Maximum Number of Data Formats must be greater than or equal to 0"); - } else { - throw new IllegalStateException("Cannot set the maximum number of data formats less than the current quantity." + - "Data formats must be explicitly removed (via StylesTable.removeNumberFormat) before the limit can be decreased."); - } - } - MAXIMUM_NUMBER_OF_DATA_FORMATS = num; - } - - /** - * Get the upper limit on the number of data formats that has been set for the style table. - * To get the current number of data formats in use, use {@link #getNumDataFormats()}. - * - * @return the maximum number of data formats allowed in the workbook - */ - public int getMaxNumberOfDataFormats() { - return MAXIMUM_NUMBER_OF_DATA_FORMATS; - } - - private StyleSheetDocument doc; - private XSSFWorkbook workbook; - private ThemesTable theme; - - /** - * Create a new, empty StylesTable - */ - public StylesTable() { - super(); - doc = StyleSheetDocument.Factory.newInstance(); - doc.addNewStyleSheet(); - // Initialization required in order to make the document readable by MSExcel - initialize(); - } - - /** - * @since POI 3.14-Beta1 - */ - public StylesTable(PackagePart part) throws IOException { - super(part); - readFrom(part.getInputStream()); - } - - public void setWorkbook(XSSFWorkbook wb) { - this.workbook = wb; - } - - /** - * Get the current Workbook's theme table, or null if the - * Workbook lacks any themes. - *

    Use {@link #ensureThemesTable()} to have a themes table - * created if needed - */ - public ThemesTable getTheme() { - return theme; - } - - public void setTheme(ThemesTable theme) { - this.theme = theme; - - // Pass the themes table along to things which need to - // know about it, but have already been created by now - for(XSSFFont font : fonts) { - font.setThemesTable(theme); - } - for(XSSFCellBorder border : borders) { - border.setThemesTable(theme); - } - } - - /** - * If there isn't currently a {@link ThemesTable} for the - * current Workbook, then creates one and sets it up. - * After this, calls to {@link #getTheme()} won't give null - */ - public void ensureThemesTable() { - if (theme != null) return; - - theme = (ThemesTable)workbook.createRelationship(XSSFRelation.THEME, XSSFFactory.getInstance()); - } - - /** - * Read this shared styles table from an XML file. - * - * @param is The input stream containing the XML document. - * @throws IOException if an error occurs while reading. - */ - protected void readFrom(InputStream is) throws IOException { - try { - doc = StyleSheetDocument.Factory.parse(is, DEFAULT_XML_OPTIONS); - - CTStylesheet styleSheet = doc.getStyleSheet(); - - // Grab all the different bits we care about - CTNumFmts ctfmts = styleSheet.getNumFmts(); - if( ctfmts != null){ - for (CTNumFmt nfmt : ctfmts.getNumFmtArray()) { - short formatId = (short)nfmt.getNumFmtId(); - numberFormats.put(formatId, nfmt.getFormatCode()); - } - } - - CTFonts ctfonts = styleSheet.getFonts(); - if(ctfonts != null){ - int idx = 0; - for (CTFont font : ctfonts.getFontArray()) { - // Create the font and save it. Themes Table supplied later - XSSFFont f = new XSSFFont(font, idx); - fonts.add(f); - idx++; - } - } - CTFills ctfills = styleSheet.getFills(); - if(ctfills != null){ - for (CTFill fill : ctfills.getFillArray()) { - fills.add(new XSSFCellFill(fill)); - } - } - - CTBorders ctborders = styleSheet.getBorders(); - if(ctborders != null) { - for (CTBorder border : ctborders.getBorderArray()) { - borders.add(new XSSFCellBorder(border)); - } - } - - CTCellXfs cellXfs = styleSheet.getCellXfs(); - if(cellXfs != null) xfs.addAll(Arrays.asList(cellXfs.getXfArray())); - - CTCellStyleXfs cellStyleXfs = styleSheet.getCellStyleXfs(); - if(cellStyleXfs != null) styleXfs.addAll(Arrays.asList(cellStyleXfs.getXfArray())); - - CTDxfs styleDxfs = styleSheet.getDxfs(); - if(styleDxfs != null) dxfs.addAll(Arrays.asList(styleDxfs.getDxfArray())); - - } catch (XmlException e) { - throw new IOException(e.getLocalizedMessage()); - } - } - - // =========================================================== - // Start of style related getters and setters - // =========================================================== - - /** - * Get number format string given its id - * - * @param fmtId number format id - * @return number format code - */ - public String getNumberFormatAt(short fmtId) { - return numberFormats.get(fmtId); - } - - private short getNumberFormatId(String fmt) { - // Find the key, and return that - for (Entry numFmt : numberFormats.entrySet()) { - if(numFmt.getValue().equals(fmt)) { - return numFmt.getKey(); - } - } - throw new IllegalStateException("Number format not in style table: " + fmt); - } - - /** - * Puts fmt in the numberFormats map if the format is not - * already in the the number format style table. - * Does nothing if fmt is already in number format style table. - * - * @param fmt the number format to add to number format style table - * @return the index of fmt in the number format style table - * @throws IllegalStateException if adding the number format to the styles table - * would exceed the {@link #MAXIMUM_NUMBER_OF_DATA_FORMATS} allowed. - */ - public int putNumberFormat(String fmt) { - // Check if number format already exists - if (numberFormats.containsValue(fmt)) { - try { - return getNumberFormatId(fmt); - } catch (final IllegalStateException e) { - throw new IllegalStateException("Found the format, but couldn't figure out where - should never happen!"); - } - } - - - if (numberFormats.size() >= MAXIMUM_NUMBER_OF_DATA_FORMATS) { - throw new IllegalStateException("The maximum number of Data Formats was exceeded. " + - "You can define up to " + MAXIMUM_NUMBER_OF_DATA_FORMATS + " formats in a .xlsx Workbook."); - } - - // Find a spare key, and add that - final short formatIndex; - if (numberFormats.isEmpty()) { - formatIndex = FIRST_USER_DEFINED_NUMBER_FORMAT_ID; - } - else { - // get next-available numberFormat index. - // Assumption: gaps in number format ids are acceptable - // to catch arithmetic overflow, nextKey's data type - // must match numberFormat's key data type - short nextKey = (short) (numberFormats.lastKey() + 1); - if (nextKey < 0) { - throw new IllegalStateException( - "Cowardly avoiding creating a number format with a negative id." + - "This is probably due to arithmetic overflow."); - } - formatIndex = (short) Math.max(nextKey, FIRST_USER_DEFINED_NUMBER_FORMAT_ID); - } - - numberFormats.put(formatIndex, fmt); - return formatIndex; - } - - - /** - * Add a number format with a specific ID into the numberFormats map. - * If a format with the same ID already exists, overwrite the format code - * with fmt - * This may be used to override built-in number formats. - * - * @param index the number format ID - * @param fmt the number format code - */ - public void putNumberFormat(short index, String fmt) { - numberFormats.put(index, fmt); - } - - /** - * Remove a number format from the style table if it exists. - * All cell styles with this number format will be modified to use the default number format. - * - * @param index the number format id to remove - * @return true if the number format was removed - */ - public boolean removeNumberFormat(short index) { - String fmt = numberFormats.remove(index); - boolean removed = (fmt != null); - if (removed) { - for (final CTXf style : xfs) { - if (style.isSetNumFmtId() && style.getNumFmtId() == index) { - style.unsetApplyNumberFormat(); - style.unsetNumFmtId(); - } - } - } - return removed; - } - - /** - * Remove a number format from the style table if it exists - * All cell styles with this number format will be modified to use the default number format - * - * @param fmt the number format to remove - * @return true if the number format was removed - */ - public boolean removeNumberFormat(String fmt) { - short id = getNumberFormatId(fmt); - return removeNumberFormat(id); - } - - public XSSFFont getFontAt(int idx) { - return fonts.get(idx); - } - - /** - * Records the given font in the font table. - * Will re-use an existing font index if this - * font matches another, EXCEPT if forced - * registration is requested. - * This allows people to create several fonts - * then customise them later. - * Note - End Users probably want to call - * {@link XSSFFont#registerTo(StylesTable)} - */ - public int putFont(XSSFFont font, boolean forceRegistration) { - int idx = -1; - if(!forceRegistration) { - idx = fonts.indexOf(font); - } - - if (idx != -1) { - return idx; - } - - idx = fonts.size(); - fonts.add(font); - return idx; - } - public int putFont(XSSFFont font) { - return putFont(font, false); - } - - /** - * - * @param idx style index - * @return XSSFCellStyle or null if idx is out of bounds for xfs array - */ - public XSSFCellStyle getStyleAt(int idx) { - int styleXfId = 0; - - if (idx < 0 || idx >= xfs.size()) { - //BUG-60343 - return null; - } - // 0 is the empty default - if(xfs.get(idx).getXfId() > 0) { - styleXfId = (int) xfs.get(idx).getXfId(); - } - - return new XSSFCellStyle(idx, styleXfId, this, theme); - } - public int putStyle(XSSFCellStyle style) { - CTXf mainXF = style.getCoreXf(); - - if(! xfs.contains(mainXF)) { - xfs.add(mainXF); - } - return xfs.indexOf(mainXF); - } - - public XSSFCellBorder getBorderAt(int idx) { - return borders.get(idx); - } - - /** - * Adds a border to the border style table if it isn't already in the style table - * Does nothing if border is already in borders style table - * - * @param border border to add - * @return the index of the added border - */ - public int putBorder(XSSFCellBorder border) { - int idx = borders.indexOf(border); - if (idx != -1) { - return idx; - } - borders.add(border); - border.setThemesTable(theme); - return borders.size() - 1; - } - - public XSSFCellFill getFillAt(int idx) { - return fills.get(idx); - } - - public List getBorders(){ - return Collections.unmodifiableList(borders); - } - - public List getFills(){ - return Collections.unmodifiableList(fills); - } - - public List getFonts(){ - return Collections.unmodifiableList(fonts); - } - - public Map getNumberFormats(){ - return Collections.unmodifiableMap(numberFormats); - } - - /** - * Adds a fill to the fill style table if it isn't already in the style table - * Does nothing if fill is already in fill style table - * - * @param fill fill to add - * @return the index of the added fill - */ - public int putFill(XSSFCellFill fill) { - int idx = fills.indexOf(fill); - if (idx != -1) { - return idx; - } - fills.add(fill); - return fills.size() - 1; - } - - @Internal - public CTXf getCellXfAt(int idx) { - return xfs.get(idx); - } - - /** - * Adds a cell to the styles table. - * Does not check for duplicates. - * - * @param cellXf the cell to add to the styles table - * @return the added cell ID in the style table - */ - @Internal - public int putCellXf(CTXf cellXf) { - xfs.add(cellXf); - return xfs.size(); - } - - @Internal - public void replaceCellXfAt(int idx, CTXf cellXf) { - xfs.set(idx, cellXf); - } - - @Internal - public CTXf getCellStyleXfAt(int idx) { - try { - return styleXfs.get(idx); - } - catch (final IndexOutOfBoundsException e) { - return null; - } - } - - /** - * Adds a cell style to the styles table. - * Does not check for duplicates. - * - * @param cellStyleXf the cell style to add to the styles table - * @return the cell style ID in the style table - */ - @Internal - public int putCellStyleXf(CTXf cellStyleXf) { - styleXfs.add(cellStyleXf); - // TODO: check for duplicate - return styleXfs.size(); - } - - @Internal - protected void replaceCellStyleXfAt(int idx, CTXf cellStyleXf) { - styleXfs.set(idx, cellStyleXf); - } - - /** - * get the size of cell styles - */ - public int getNumCellStyles(){ - // Each cell style has a unique xfs entry - // Several might share the same styleXfs entry - return xfs.size(); - } - - /** - * @return number of data formats in the styles table - */ - public int getNumDataFormats() { - return numberFormats.size(); - } - - /** - * For unit testing only - * @deprecated POI 3.14 beta 2. Use {@link #getNumDataFormats()} instead. - */ - @Internal - public int _getNumberFormatSize() { - return getNumDataFormats(); - } - - /** - * For unit testing only - */ - @Internal - /*package*/ int _getXfsSize() { - return xfs.size(); - } - /** - * For unit testing only - */ - @Internal - public int _getStyleXfsSize() { - return styleXfs.size(); - } - - /** - * For unit testing only! - */ - @Internal - public CTStylesheet getCTStylesheet() { - return doc.getStyleSheet(); - } - - @Internal - public int _getDXfsSize() { - return dxfs.size(); - } - - - /** - * Write this table out as XML. - * - * @param out The stream to write to. - * @throws IOException if an error occurs while writing. - */ - public void writeTo(OutputStream out) throws IOException { - // Work on the current one - // Need to do this, as we don't handle - // all the possible entries yet - CTStylesheet styleSheet = doc.getStyleSheet(); - - // Formats - CTNumFmts formats = CTNumFmts.Factory.newInstance(); - formats.setCount(numberFormats.size()); - for (final Entry entry : numberFormats.entrySet()) { - CTNumFmt ctFmt = formats.addNewNumFmt(); - ctFmt.setNumFmtId(entry.getKey()); - ctFmt.setFormatCode(entry.getValue()); - } - styleSheet.setNumFmts(formats); - - int idx; - // Fonts - CTFonts ctFonts = styleSheet.getFonts(); - if (ctFonts == null) { - ctFonts = CTFonts.Factory.newInstance(); - } - ctFonts.setCount(fonts.size()); - CTFont[] ctfnt = new CTFont[fonts.size()]; - idx = 0; - for(XSSFFont f : fonts) ctfnt[idx++] = f.getCTFont(); - ctFonts.setFontArray(ctfnt); - styleSheet.setFonts(ctFonts); - - // Fills - CTFills ctFills = styleSheet.getFills(); - if (ctFills == null) { - ctFills = CTFills.Factory.newInstance(); - } - ctFills.setCount(fills.size()); - CTFill[] ctf = new CTFill[fills.size()]; - idx = 0; - for(XSSFCellFill f : fills) ctf[idx++] = f.getCTFill(); - ctFills.setFillArray(ctf); - styleSheet.setFills(ctFills); - - // Borders - CTBorders ctBorders = styleSheet.getBorders(); - if (ctBorders == null) { - ctBorders = CTBorders.Factory.newInstance(); - } - ctBorders.setCount(borders.size()); - CTBorder[] ctb = new CTBorder[borders.size()]; - idx = 0; - for(XSSFCellBorder b : borders) ctb[idx++] = b.getCTBorder(); - ctBorders.setBorderArray(ctb); - styleSheet.setBorders(ctBorders); - - // Xfs - if(xfs.size() > 0) { - CTCellXfs ctXfs = styleSheet.getCellXfs(); - if (ctXfs == null) { - ctXfs = CTCellXfs.Factory.newInstance(); - } - ctXfs.setCount(xfs.size()); - ctXfs.setXfArray( - xfs.toArray(new CTXf[xfs.size()]) - ); - styleSheet.setCellXfs(ctXfs); - } - - // Style xfs - if(styleXfs.size() > 0) { - CTCellStyleXfs ctSXfs = styleSheet.getCellStyleXfs(); - if (ctSXfs == null) { - ctSXfs = CTCellStyleXfs.Factory.newInstance(); - } - ctSXfs.setCount(styleXfs.size()); - ctSXfs.setXfArray( - styleXfs.toArray(new CTXf[styleXfs.size()]) - ); - styleSheet.setCellStyleXfs(ctSXfs); - } - - // Style dxfs - if(dxfs.size() > 0) { - CTDxfs ctDxfs = styleSheet.getDxfs(); - if (ctDxfs == null) { - ctDxfs = CTDxfs.Factory.newInstance(); - } - ctDxfs.setCount(dxfs.size()); - ctDxfs.setDxfArray(dxfs.toArray(new CTDxf[dxfs.size()])); - styleSheet.setDxfs(ctDxfs); - } - - // Save - doc.save(out, DEFAULT_XML_OPTIONS); - } - - @Override - protected void commit() throws IOException { - PackagePart part = getPackagePart(); - OutputStream out = part.getOutputStream(); - writeTo(out); - out.close(); - } - - private void initialize() { - //CTFont ctFont = createDefaultFont(); - XSSFFont xssfFont = createDefaultFont(); - fonts.add(xssfFont); - - CTFill[] ctFill = createDefaultFills(); - fills.add(new XSSFCellFill(ctFill[0])); - fills.add(new XSSFCellFill(ctFill[1])); - - CTBorder ctBorder = createDefaultBorder(); - borders.add(new XSSFCellBorder(ctBorder)); - - CTXf styleXf = createDefaultXf(); - styleXfs.add(styleXf); - CTXf xf = createDefaultXf(); - xf.setXfId(0); - xfs.add(xf); - } - - private static CTXf createDefaultXf() { - CTXf ctXf = CTXf.Factory.newInstance(); - ctXf.setNumFmtId(0); - ctXf.setFontId(0); - ctXf.setFillId(0); - ctXf.setBorderId(0); - return ctXf; - } - private static CTBorder createDefaultBorder() { - CTBorder ctBorder = CTBorder.Factory.newInstance(); - ctBorder.addNewBottom(); - ctBorder.addNewTop(); - ctBorder.addNewLeft(); - ctBorder.addNewRight(); - ctBorder.addNewDiagonal(); - return ctBorder; - } - - - private static CTFill[] createDefaultFills() { - CTFill[] ctFill = new CTFill[]{CTFill.Factory.newInstance(),CTFill.Factory.newInstance()}; - ctFill[0].addNewPatternFill().setPatternType(STPatternType.NONE); - ctFill[1].addNewPatternFill().setPatternType(STPatternType.DARK_GRAY); - return ctFill; - } - - private static XSSFFont createDefaultFont() { - CTFont ctFont = CTFont.Factory.newInstance(); - XSSFFont xssfFont=new XSSFFont(ctFont, 0); - xssfFont.setFontHeightInPoints(XSSFFont.DEFAULT_FONT_SIZE); - xssfFont.setColor(XSSFFont.DEFAULT_FONT_COLOR);//setTheme - xssfFont.setFontName(XSSFFont.DEFAULT_FONT_NAME); - xssfFont.setFamily(FontFamily.SWISS); - xssfFont.setScheme(FontScheme.MINOR); - return xssfFont; - } - - @Internal - public CTDxf getDxfAt(int idx) { - return dxfs.get(idx); - } - - /** - * Adds a Dxf to the style table - * Does not check for duplicates. - * - * @param dxf the Dxf to add - * @return added dxf ID in the style table - */ - @Internal - public int putDxf(CTDxf dxf) { - this.dxfs.add(dxf); - return this.dxfs.size(); - } - - /** - * Create a cell style in this style table. - * Note - End users probably want to call {@link XSSFWorkbook#createCellStyle()} - * rather than working with the styles table directly. - * @throws IllegalStateException if the maximum number of cell styles has been reached. - */ - public XSSFCellStyle createCellStyle() { - if (getNumCellStyles() > MAXIMUM_STYLE_ID) { - throw new IllegalStateException("The maximum number of Cell Styles was exceeded. " + - "You can define up to " + MAXIMUM_STYLE_ID + " style in a .xlsx Workbook"); - } - - int xfSize = styleXfs.size(); - CTXf xf = CTXf.Factory.newInstance(); - xf.setNumFmtId(0); - xf.setFontId(0); - xf.setFillId(0); - xf.setBorderId(0); - xf.setXfId(0); - int indexXf = putCellXf(xf); - return new XSSFCellStyle(indexXf - 1, xfSize - 1, this, theme); - } - - /** - * Finds a font that matches the one with the supplied attributes - * @deprecated POI 3.15 beta 2. Use {@link #findFont(boolean, short, short, String, boolean, boolean, short, byte)} instead. - */ - public XSSFFont findFont(short boldWeight, short color, short fontHeight, String name, boolean italic, boolean strikeout, short typeOffset, byte underline) { - for (XSSFFont font : fonts) { - if ( (font.getBoldweight() == boldWeight) - && font.getColor() == color - && font.getFontHeight() == fontHeight - && font.getFontName().equals(name) - && font.getItalic() == italic - && font.getStrikeout() == strikeout - && font.getTypeOffset() == typeOffset - && font.getUnderline() == underline) - { - return font; - } - } - return null; - } - - /** - * Finds a font that matches the one with the supplied attributes - */ - public XSSFFont findFont(boolean bold, short color, short fontHeight, String name, boolean italic, boolean strikeout, short typeOffset, byte underline) { - for (XSSFFont font : fonts) { - if ( (font.getBold() == bold) - && font.getColor() == color - && font.getFontHeight() == fontHeight - && font.getFontName().equals(name) - && font.getItalic() == italic - && font.getStrikeout() == strikeout - && font.getTypeOffset() == typeOffset - && font.getUnderline() == underline) - { - return font; - } - } - return null; - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/model/ThemesTable.java b/src/ooxml/java/org/apache/poi/xssf/model/ThemesTable.java deleted file mode 100644 index 9c3b1de40..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/model/ThemesTable.java +++ /dev/null @@ -1,179 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.model; - -import static org.apache.poi.POIXMLTypeLoader.DEFAULT_XML_OPTIONS; - -import java.io.IOException; -import java.io.OutputStream; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.xssf.usermodel.XSSFColor; -import org.apache.xmlbeans.XmlException; -import org.openxmlformats.schemas.drawingml.x2006.main.CTColor; -import org.openxmlformats.schemas.drawingml.x2006.main.CTColorScheme; -import org.openxmlformats.schemas.drawingml.x2006.main.ThemeDocument; - -/** - * Class that represents theme of XLSX document. The theme includes specific - * colors and fonts. - */ -public class ThemesTable extends POIXMLDocumentPart { - public enum ThemeElement { - LT1(0, "Lt1"), - DK1(1,"Dk1"), - LT2(2,"Lt2"), - DK2(3,"Dk2"), - ACCENT1(4,"Accent1"), - ACCENT2(5,"Accent2"), - ACCENT3(6,"Accent3"), - ACCENT4(7,"Accent4"), - ACCENT5(8,"Accent5"), - ACCENT6(9,"Accent6"), - HLINK(10,"Hlink"), - FOLHLINK(11,"FolHlink"), - UNKNOWN(-1,null); - - public static ThemeElement byId(int idx) { - if (idx >= values().length || idx < 0) return UNKNOWN; - return values()[idx]; - } - private ThemeElement(int idx, String name) { - this.idx = idx; this.name = name; - } - public final int idx; - public final String name; - } - - private ThemeDocument theme; - - /** - * Create a new, empty ThemesTable - */ - public ThemesTable() { - super(); - theme = ThemeDocument.Factory.newInstance(); - theme.addNewTheme().addNewThemeElements(); - } - - /** - * Construct a ThemesTable. - * @param part A PackagePart. - * - * @since POI 3.14-Beta1 - */ - public ThemesTable(PackagePart part) throws IOException { - super(part); - - try { - theme = ThemeDocument.Factory.parse(part.getInputStream(), DEFAULT_XML_OPTIONS); - } catch(XmlException e) { - throw new IOException(e.getLocalizedMessage(), e); - } - } - - /** - * Construct a ThemesTable from an existing ThemeDocument. - * @param theme A ThemeDocument. - */ - public ThemesTable(ThemeDocument theme) { - this.theme = theme; - } - - /** - * Convert a theme "index" (as used by fonts etc) into a color. - * @param idx A theme "index" - * @return The mapped XSSFColor, or null if not mapped. - */ - public XSSFColor getThemeColor(int idx) { - // Theme color references are NOT positional indices into the color scheme, - // i.e. these keys are NOT the same as the order in which theme colors appear - // in theme1.xml. They are keys to a mapped color. - CTColorScheme colorScheme = theme.getTheme().getThemeElements().getClrScheme(); - CTColor ctColor; - switch (ThemeElement.byId(idx)) { - case LT1: ctColor = colorScheme.getLt1(); break; - case DK1: ctColor = colorScheme.getDk1(); break; - case LT2: ctColor = colorScheme.getLt2(); break; - case DK2: ctColor = colorScheme.getDk2(); break; - case ACCENT1: ctColor = colorScheme.getAccent1(); break; - case ACCENT2: ctColor = colorScheme.getAccent2(); break; - case ACCENT3: ctColor = colorScheme.getAccent3(); break; - case ACCENT4: ctColor = colorScheme.getAccent4(); break; - case ACCENT5: ctColor = colorScheme.getAccent5(); break; - case ACCENT6: ctColor = colorScheme.getAccent6(); break; - case HLINK: ctColor = colorScheme.getHlink(); break; - case FOLHLINK:ctColor = colorScheme.getFolHlink();break; - default: return null; - } - - byte[] rgb = null; - if (ctColor.isSetSrgbClr()) { - // Color is a regular one - rgb = ctColor.getSrgbClr().getVal(); - } else if (ctColor.isSetSysClr()) { - // Color is a tint of white or black - rgb = ctColor.getSysClr().getLastClr(); - } else { - return null; - } - return new XSSFColor(rgb); - } - - /** - * If the colour is based on a theme, then inherit - * information (currently just colours) from it as - * required. - */ - public void inheritFromThemeAsRequired(XSSFColor color) { - if(color == null) { - // Nothing for us to do - return; - } - if(! color.getCTColor().isSetTheme()) { - // No theme set, nothing to do - return; - } - - // Get the theme colour - XSSFColor themeColor = getThemeColor(color.getTheme()); - // Set the raw colour, not the adjusted one - // Do a raw set, no adjusting at the XSSFColor layer either - color.getCTColor().setRgb(themeColor.getCTColor().getRgb()); - - // All done - } - - /** - * Write this table out as XML. - * - * @param out The stream to write to. - * @throws IOException if an error occurs while writing. - */ - public void writeTo(OutputStream out) throws IOException { - theme.save(out, DEFAULT_XML_OPTIONS); - } - - @Override - protected void commit() throws IOException { - PackagePart part = getPackagePart(); - OutputStream out = part.getOutputStream(); - writeTo(out); - out.close(); - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/streaming/AutoSizeColumnTracker.java b/src/ooxml/java/org/apache/poi/xssf/streaming/AutoSizeColumnTracker.java deleted file mode 100644 index 03a29a367..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/streaming/AutoSizeColumnTracker.java +++ /dev/null @@ -1,371 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.streaming; - -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.SortedSet; -import java.util.TreeSet; - -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.DataFormatter; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.util.SheetUtil; -import org.apache.poi.util.Internal; - -/** - * Tracks best fit column width for rows of an {@link SXSSFSheet}, - * to be able to correctly calculate auto-sized column widths even - * if some rows are already flushed to disk. - * This is an auxiliary data structure that uses a TreeMap containing - * one entry per tracked column, where the key is the column index and - * the value is a pair of doubles. This data structure's memory footprint - * is linear with the number of *tracked* columns and invariant with - * the number of rows or columns in the sheet. - * @since 3.14beta1 -*/ -@Internal -/*package*/ class AutoSizeColumnTracker { - private final int defaultCharWidth; - private final DataFormatter dataFormatter = new DataFormatter(); - - // map of tracked columns, with values containing the best-fit width for the column - // Using a HashMap instead of a TreeMap because insertion (trackColumn), removal (untrackColumn), and membership (everything) - // will be called more frequently than getTrackedColumns(). The O(1) cost of insertion, removal, and membership operations - // outweigh the infrequent O(n*log n) cost of sorting getTrackedColumns(). - // Memory consumption for a HashMap and TreeMap is about the same - private final Map maxColumnWidths = new HashMap(); - // untrackedColumns stores columns have been explicitly untracked so they aren't implicitly re-tracked by trackAllColumns - // Using a HashSet instead of a TreeSet because we don't care about order. - private final Set untrackedColumns = new HashSet(); - private boolean trackAllColumns = false; - - /** - * Tuple to store the column widths considering and not considering merged cells - * If more permutations are needed, it may be prudent to require the user to specify - * how they intend to auto-size a column when they track the column, so calculations - * are limited to the desired intentions. Unless this proves to be a performance problem, - * it's probably better to let the user defer how they want to auto-size to SXSSFSheet.autoSizeColumn, - * rather than twice (via SXSSFSheet.trackColumn(int column, boolean useMergedCells) and again at - * SXSFSheet.autoSizeColumn(int column, boolean useMergedCells)) - * @since 3.14beta1 - */ - private static class ColumnWidthPair { - private double withSkipMergedCells; - private double withUseMergedCells; - - public ColumnWidthPair() { - this(-1.0, -1.0); - } - - public ColumnWidthPair(final double columnWidthSkipMergedCells, final double columnWidthUseMergedCells) { - withSkipMergedCells = columnWidthSkipMergedCells; - withUseMergedCells = columnWidthUseMergedCells; - } - - /** - * Gets the current best-fit column width for the provided settings - * - * @param useMergedCells true if merged cells are considered into the best-fit column width calculation - * @return best fit column width, measured in default character widths. - */ - public double getMaxColumnWidth(final boolean useMergedCells) { - return useMergedCells ? withUseMergedCells : withSkipMergedCells; - } - - /** - * Sets the best-fit column width to the maximum of the current width and the provided width - * - * @param unmergedWidth the best-fit column width calculated with useMergedCells=False - * @param mergedWidth the best-fit column width calculated with useMergedCells=True - */ - public void setMaxColumnWidths(double unmergedWidth, double mergedWidth) { - withUseMergedCells = Math.max(withUseMergedCells, mergedWidth); - withSkipMergedCells = Math.max(withUseMergedCells, unmergedWidth); - } - } - - /** - * AutoSizeColumnTracker constructor. Holds no reference to sheet - * - * @param sheet the sheet associated with this auto-size column tracker - * @since 3.14beta1 - */ - public AutoSizeColumnTracker(final Sheet sheet) { - // If sheet needs to be saved, use a java.lang.ref.WeakReference to avoid garbage collector gridlock. - defaultCharWidth = SheetUtil.getDefaultCharWidth(sheet.getWorkbook()); - } - - /** - * Get the currently tracked columns, naturally ordered. - * Note if all columns are tracked, this will only return the columns that have been explicitly or implicitly tracked, - * which is probably only columns containing 1 or more non-blank values - * - * @return a set of the indices of all tracked columns - * @since 3.14beta1 - */ - public SortedSet getTrackedColumns() { - SortedSet sorted = new TreeSet(maxColumnWidths.keySet()); - return Collections.unmodifiableSortedSet(sorted); - } - - /** - * Returns true if column is currently tracked for auto-sizing. - * - * @param column the index of the column to check - * @return true if column is tracked - * @since 3.14beta1 - */ - public boolean isColumnTracked(int column) { - return trackAllColumns || maxColumnWidths.containsKey(column); - } - - /** - * Returns true if all columns are implicitly tracked. - * - * @return true if all columns are implicitly tracked - * @since 3.14beta1 - */ - public boolean isAllColumnsTracked() { - return trackAllColumns; - } - - /** - * Tracks all non-blank columns - * Allows columns that have been explicitly untracked to be tracked - * @since 3.14beta1 - */ - public void trackAllColumns() { - trackAllColumns = true; - untrackedColumns.clear(); - } - - /** - * Untrack all columns that were previously tracked for auto-sizing. - * All best-fit column widths are forgotten. - * @since 3.14beta1 - */ - public void untrackAllColumns() { - trackAllColumns = false; - maxColumnWidths.clear(); - untrackedColumns.clear(); - } - - /** - * Marks multiple columns for inclusion in auto-size column tracking. - * Note this has undefined behavior if columns are tracked after one or more rows are written to the sheet. - * Any column in columns that are already tracked are ignored by this call. - * - * @param columns the indices of the columns to track - * @since 3.14beta1 - */ - public void trackColumns(Collection columns) - { - for (final int column : columns) { - trackColumn(column); - } - } - - /** - * Marks a column for inclusion in auto-size column tracking. - * Note this has undefined behavior if a column is tracked after one or more rows are written to the sheet. - * If column is already tracked, this call does nothing. - * - * @param column the index of the column to track for auto-sizing - * @return if column is already tracked, the call does nothing and returns false - * @since 3.14beta1 - */ - public boolean trackColumn(int column) { - untrackedColumns.remove(column); - if (!maxColumnWidths.containsKey(column)) { - maxColumnWidths.put(column, new ColumnWidthPair()); - return true; - } - return false; - } - - /** - * Implicitly track a column if it has not been explicitly untracked - * If it has been explicitly untracked, this call does nothing and returns false. - * Otherwise return true - * - * @param column the column to implicitly track - * @return false if column has been explicitly untracked, otherwise return true - */ - private boolean implicitlyTrackColumn(int column) { - if (!untrackedColumns.contains(column)) { - trackColumn(column); - return true; - } - return false; - } - - /** - * Removes columns that were previously marked for inclusion in auto-size column tracking. - * When a column is untracked, the best-fit width is forgotten. - * Any column in columns that is not tracked will be ignored by this call. - * - * @param columns the indices of the columns to track for auto-sizing - * @return true if one or more columns were untracked as a result of this call - * @since 3.14beta1 - */ - public boolean untrackColumns(Collection columns) - { - untrackedColumns.addAll(columns); - return maxColumnWidths.keySet().removeAll(columns); - } - - /** - * Removes a column that was previously marked for inclusion in auto-size column tracking. - * When a column is untracked, the best-fit width is forgotten. - * If column is not tracked, it will be ignored by this call. - * - * @param column the index of the column to track for auto-sizing - * @return true if column was tracked prior this call, false if no action was taken - * @since 3.14beta1 - */ - public boolean untrackColumn(int column) { - untrackedColumns.add(column); - return maxColumnWidths.keySet().remove(column); - } - - /** - * Get the best-fit width of a tracked column - * - * @param column the index of the column to get the current best-fit width of - * @param useMergedCells true if merged cells should be considered when computing the best-fit width - * @return best-fit column width, measured in number of characters - * @throws IllegalStateException if column is not tracked and trackAllColumns is false - * @since 3.14beta1 - */ - public int getBestFitColumnWidth(int column, boolean useMergedCells) { - if (!maxColumnWidths.containsKey(column)) { - // if column is not tracked, implicitly track the column if trackAllColumns is True and column has not been explicitly untracked - if (trackAllColumns) { - if (!implicitlyTrackColumn(column)) { - final Throwable reason = new IllegalStateException( - "Column was explicitly untracked after trackAllColumns() was called."); - throw new IllegalStateException( - "Cannot get best fit column width on explicitly untracked column " + column + ". " + - "Either explicitly track the column or track all columns.", reason); - } - } - else { - final Throwable reason = new IllegalStateException( - "Column was never explicitly tracked and isAllColumnsTracked() is false " + - "(trackAllColumns() was never called or untrackAllColumns() was called after trackAllColumns() was called)."); - throw new IllegalStateException( - "Cannot get best fit column width on untracked column " + column + ". " + - "Either explicitly track the column or track all columns.", reason); - } - } - final double width = maxColumnWidths.get(column).getMaxColumnWidth(useMergedCells); - return (int) (256*width); - } - - - - /** - * Calculate the best fit width for each tracked column in row - * - * @param row the row to get the cells - * @since 3.14beta1 - */ - public void updateColumnWidths(Row row) { - // track new columns - implicitlyTrackColumnsInRow(row); - - // update the widths - // for-loop over the shorter of the number of cells in the row and the number of tracked columns - // these two for-loops should do the same thing - if (maxColumnWidths.size() < row.getPhysicalNumberOfCells()) { - // loop over the tracked columns, because there are fewer tracked columns than cells in this row - for (final Entry e : maxColumnWidths.entrySet()) { - final int column = e.getKey(); - final Cell cell = row.getCell(column); //is MissingCellPolicy=Row.RETURN_NULL_AND_BLANK needed? - - // FIXME: if cell belongs to a merged region, some of the merged region may have fallen outside of the random access window - // In this case, getting the column width may result in an error. Need to gracefully handle this. - - // FIXME: Most cells are not merged, so calling getCellWidth twice re-computes the same value twice. - // Need to rewrite this to avoid unnecessary computation if this proves to be a performance bottleneck. - - if (cell != null) { - final ColumnWidthPair pair = e.getValue(); - updateColumnWidth(cell, pair); - } - } - } - else { - // loop over the cells in this row, because there are fewer cells in this row than tracked columns - for (final Cell cell : row) { - final int column = cell.getColumnIndex(); - - // FIXME: if cell belongs to a merged region, some of the merged region may have fallen outside of the random access window - // In this case, getting the column width may result in an error. Need to gracefully handle this. - - // FIXME: Most cells are not merged, so calling getCellWidth twice re-computes the same value twice. - // Need to rewrite this to avoid unnecessary computation if this proves to be a performance bottleneck. - - if (maxColumnWidths.containsKey(column)) { - final ColumnWidthPair pair = maxColumnWidths.get(column); - updateColumnWidth(cell, pair); - } - } - } - } - - /** - * Helper for {@link #updateColumnWidths(Row)}. - * Implicitly track the columns corresponding to the cells in row. - * If all columns in the row are already tracked, this call does nothing. - * Explicitly untracked columns will not be tracked. - * - * @param row the row containing cells to implicitly track the columns - * @since 3.14beta1 - */ - private void implicitlyTrackColumnsInRow(Row row) { - // track new columns - if (trackAllColumns) { - // if column is not tracked, implicitly track the column if trackAllColumns is True and column has not been explicitly untracked - for (final Cell cell : row) { - final int column = cell.getColumnIndex(); - implicitlyTrackColumn(column); - } - } - } - - /** - * Helper for {@link #updateColumnWidths(Row)}. - * - * @param cell the cell to compute the best fit width on - * @param pair the column width pair to update - * @since 3.14beta1 - */ - private void updateColumnWidth(final Cell cell, final ColumnWidthPair pair) { - final double unmergedWidth = SheetUtil.getCellWidth(cell, defaultCharWidth, dataFormatter, false); - final double mergedWidth = SheetUtil.getCellWidth(cell, defaultCharWidth, dataFormatter, true); - pair.setMaxColumnWidths(unmergedWidth, mergedWidth); - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/streaming/GZIPSheetDataWriter.java b/src/ooxml/java/org/apache/poi/xssf/streaming/GZIPSheetDataWriter.java deleted file mode 100644 index ce2da084e..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/streaming/GZIPSheetDataWriter.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xssf.streaming; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.zip.GZIPInputStream; -import java.util.zip.GZIPOutputStream; - -import org.apache.poi.util.TempFile; -import org.apache.poi.xssf.model.SharedStringsTable; - -/** - * Sheet writer that supports gzip compression of the temp files. - */ -public class GZIPSheetDataWriter extends SheetDataWriter { - - public GZIPSheetDataWriter() throws IOException { - super(); - } - - /** - * @param sharedStringsTable the shared strings table, or null if inline text is used - */ - public GZIPSheetDataWriter(SharedStringsTable sharedStringsTable) throws IOException { - super(sharedStringsTable); - } - - /** - * @return temp file to write sheet data - */ - @Override - public File createTempFile() throws IOException { - return TempFile.createTempFile("poi-sxssf-sheet-xml", ".gz"); - } - - @Override - protected InputStream decorateInputStream(FileInputStream fis) throws IOException { - return new GZIPInputStream(fis); - } - - @Override - protected OutputStream decorateOutputStream(FileOutputStream fos) throws IOException { - return new GZIPOutputStream(fos); - } - -} diff --git a/src/ooxml/java/org/apache/poi/xssf/streaming/SXSSFCell.java b/src/ooxml/java/org/apache/poi/xssf/streaming/SXSSFCell.java deleted file mode 100644 index d0615b30c..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/streaming/SXSSFCell.java +++ /dev/null @@ -1,1306 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.streaming; - -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.Date; -import java.util.Map; - -import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.ss.formula.FormulaParseException; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.Comment; -import org.apache.poi.ss.usermodel.DateUtil; -import org.apache.poi.ss.usermodel.FormulaError; -import org.apache.poi.ss.usermodel.Hyperlink; -import org.apache.poi.ss.usermodel.RichTextString; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.util.CellAddress; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.util.Internal; -import org.apache.poi.util.LocaleUtil; -import org.apache.poi.util.NotImplemented; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.util.Removal; -import org.apache.poi.xssf.usermodel.XSSFHyperlink; -import org.apache.poi.xssf.usermodel.XSSFRichTextString; - -/** - * Streaming version of XSSFRow implementing the "BigGridDemo" strategy. -*/ -public class SXSSFCell implements Cell { - private static final POILogger logger = POILogFactory.getLogger(SXSSFCell.class); - - private final SXSSFRow _row; - private Value _value; - private CellStyle _style; - private Property _firstProperty; - - /** - * @deprecated POI 3.15 beta 3. - * Will be deleted when we make the CellType enum transition. See bug 59791. - */ - @Removal(version="3.17") - @Deprecated - public SXSSFCell(SXSSFRow row, int cellType) - { - this(row, CellType.forInt((cellType))); - } - - public SXSSFCell(SXSSFRow row,CellType cellType) - { - _row=row; - setType(cellType); - } - -//start of interface implementation - - /** - * Returns column index of this cell - * - * @return zero-based column index of a column in a sheet. - */ - @Override - public int getColumnIndex() - { - return _row.getCellIndex(this); - } - - /** - * Returns row index of a row in the sheet that contains this cell - * - * @return zero-based row index of a row in the sheet that contains this cell - */ - @Override - public int getRowIndex() - { - return _row.getRowNum(); - } - - /** - * {@inheritDoc} - */ - @Override - public CellAddress getAddress() { - return new CellAddress(this); - } - - /** - * Returns the sheet this cell belongs to - * - * @return the sheet this cell belongs to - */ - @Override - public SXSSFSheet getSheet() - { - return _row.getSheet(); - } - - /** - * Returns the Row this cell belongs to - * - * @return the Row that owns this cell - */ - @Override - public Row getRow() - { - return _row; - } - - /** - * Set the cells type (numeric, formula or string) - * - * @throws IllegalArgumentException if the specified cell type is invalid - * @see CellType#NUMERIC - * @see CellType#STRING - * @see CellType#FORMULA - * @see CellType#BLANK - * @see CellType#BOOLEAN - * @see CellType#ERROR - * @deprecated POI 3.15 beta 3. Use {@link #setCellType(CellType)} instead. - * Will be deleted when we make the CellType enum transition. See bug 59791. - */ - @Override - public void setCellType(int cellType) - { - ensureType(CellType.forInt(cellType)); - } - /** - * Set the cells type (numeric, formula or string) - * - * @throws IllegalArgumentException if the specified cell type is invalid - */ - @Override - public void setCellType(CellType cellType) - { - ensureType(cellType); - } - - /** - * Return the cell type. - * - * @return the cell type - * @deprecated 3.15. Will return a {@link CellType} enum in the future. - */ - @Override - public int getCellType() - { - return getCellTypeEnum().getCode(); - } - - /** - * Return the cell type. - * - * @return the cell type - * @since POI 3.15 beta 3 - * Will be deleted when we make the CellType enum transition. See bug 59791. - */ - @Override - public CellType getCellTypeEnum() - { - return _value.getType(); - } - - /** - * Only valid for formula cells - * @return one of ({@link CellType#NUMERIC}, {@link CellType#STRING}, - * {@link CellType#BOOLEAN}, {@link CellType#ERROR}) depending - * on the cached value of the formula - * @deprecated 3.15. Will return a {@link CellType} enum in the future. - */ - @Override - public int getCachedFormulaResultType() - { - return getCachedFormulaResultTypeEnum().getCode(); - } - - /** - * Only valid for formula cells - * @return one of ({@link CellType#NUMERIC}, {@link CellType#STRING}, - * {@link CellType#BOOLEAN}, {@link CellType#ERROR}) depending - * on the cached value of the formula - * @since POI 3.15 beta 3 - * Will be deleted when we make the CellType enum transition. See bug 59791. - */ - @Override - public CellType getCachedFormulaResultTypeEnum() - { - if (_value.getType() != CellType.FORMULA) { - throw new IllegalStateException("Only formula cells have cached results"); - } - - return ((FormulaValue)_value).getFormulaType(); - } - - /** - * Set a numeric value for the cell - * - * @param value the numeric value to set this cell to. For formulas we'll set the - * precalculated value, for numerics we'll set its value. For other types we - * will change the cell to a numeric cell and set its value. - */ - @Override - public void setCellValue(double value) - { - if(Double.isInfinite(value)) { - // Excel does not support positive/negative infinities, - // rather, it gives a #DIV/0! error in these cases. - setCellErrorValue(FormulaError.DIV0.getCode()); - } else if (Double.isNaN(value)){ - setCellErrorValue(FormulaError.NUM.getCode()); - } else { - ensureTypeOrFormulaType(CellType.NUMERIC); - if(_value.getType()==CellType.FORMULA) - ((NumericFormulaValue)_value).setPreEvaluatedValue(value); - else - ((NumericValue)_value).setValue(value); - } - } - - /** - * Converts the supplied date to its equivalent Excel numeric value and sets - * that into the cell. - *

    - * Note - There is actually no 'DATE' cell type in Excel. In many - * cases (when entering date values), Excel automatically adjusts the - * cell style to some date format, creating the illusion that the cell - * data type is now something besides {@link CellType#NUMERIC}. POI - * does not attempt to replicate this behaviour. To make a numeric cell - * display as a date, use {@link #setCellStyle(CellStyle)} etc. - * - * @param value the numeric value to set this cell to. For formulas we'll set the - * precalculated value, for numerics we'll set its value. For other types we - * will change the cell to a numerics cell and set its value. - */ - @Override - public void setCellValue(Date value) { - if(value == null) { - setCellType(CellType.BLANK); - return; - } - - boolean date1904 = getSheet().getWorkbook().isDate1904(); - setCellValue(DateUtil.getExcelDate(value, date1904)); - } - - /** - * Set a date value for the cell. Excel treats dates as numeric so you will need to format the cell as - * a date. - *

    - * This will set the cell value based on the Calendar's timezone. As Excel - * does not support timezones this means that both 20:00+03:00 and - * 20:00-03:00 will be reported as the same value (20:00) even that there - * are 6 hours difference between the two times. This difference can be - * preserved by using setCellValue(value.getTime()) which will - * automatically shift the times to the default timezone. - *

    - * - * @param value the date value to set this cell to. For formulas we'll set the - * precalculated value, for numerics we'll set its value. For othertypes we - * will change the cell to a numeric cell and set its value. - */ - @Override - public void setCellValue(Calendar value) { - if(value == null) { - setCellType(CellType.BLANK); - return; - } - - boolean date1904 = getSheet().getWorkbook().isDate1904(); - setCellValue( DateUtil.getExcelDate(value, date1904 )); - } - - /** - * Set a rich string value for the cell. - * - * @param value value to set the cell to. For formulas we'll set the formula - * string, for String cells we'll set its value. For other types we will - * change the cell to a string cell and set its value. - * If value is null then we will change the cell to a Blank cell. - */ - @Override - public void setCellValue(RichTextString value) - { - XSSFRichTextString xvalue = (XSSFRichTextString)value; - - if (xvalue != null && xvalue.getString() != null) { - ensureRichTextStringType(); - - if (xvalue.length() > SpreadsheetVersion.EXCEL2007.getMaxTextLength()) { - throw new IllegalArgumentException("The maximum length of cell contents (text) is 32,767 characters"); - } - if (xvalue.hasFormatting()) - logger.log(POILogger.WARN, "SXSSF doesn't support Shared Strings, rich text formatting information has be lost"); - - ((RichTextValue)_value).setValue(xvalue); - } else { - setCellType(CellType.BLANK); - } - } - - /** - * Set a string value for the cell. - * - * @param value value to set the cell to. For formulas we'll set the formula - * string, for String cells we'll set its value. For other types we will - * change the cell to a string cell and set its value. - * If value is null then we will change the cell to a Blank cell. - */ - @Override - public void setCellValue(String value) - { - if (value != null) { - ensureTypeOrFormulaType(CellType.STRING); - - if (value.length() > SpreadsheetVersion.EXCEL2007.getMaxTextLength()) { - throw new IllegalArgumentException("The maximum length of cell contents (text) is 32,767 characters"); - } - - if(_value.getType()==CellType.FORMULA) - if(_value instanceof NumericFormulaValue) { - ((NumericFormulaValue) _value).setPreEvaluatedValue(Double.parseDouble(value)); - } else { - ((StringFormulaValue) _value).setPreEvaluatedValue(value); - } - else - ((PlainStringValue)_value).setValue(value); - } else { - setCellType(CellType.BLANK); - } - } - - /** - * Sets formula for this cell. - *

    - * Note, this method only sets the formula string and does not calculate the formula value. - * To set the precalculated value use {@link #setCellValue(double)} or {@link #setCellValue(String)} - *

    - * - * @param formula the formula to set, e.g. "SUM(C4:E4)". - * If the argument is null then the current formula is removed. - * @throws FormulaParseException if the formula has incorrect syntax or is otherwise invalid - */ - @Override - public void setCellFormula(String formula) throws FormulaParseException - { - if(formula == null) { - setType(CellType.BLANK); - return; - } - - ensureFormulaType(computeTypeFromFormula(formula)); - ((FormulaValue)_value).setValue(formula); - } - /** - * Return a formula for the cell, for example, SUM(C4:E4) - * - * @return a formula for the cell - * @throws IllegalStateException if the cell type returned by {@link #getCellTypeEnum()} is not CellType.FORMULA - */ - @Override - public String getCellFormula() - { - if(_value.getType()!=CellType.FORMULA) - throw typeMismatch(CellType.FORMULA,_value.getType(),false); - return ((FormulaValue)_value).getValue(); - } - - /** - * Get the value of the cell as a number. - *

    - * For strings we throw an exception. For blank cells we return a 0. - * For formulas or error cells we return the precalculated value; - *

    - * @return the value of the cell as a number - * @throws IllegalStateException if the cell type returned by {@link #getCellTypeEnum()} is CellType.STRING - * @exception NumberFormatException if the cell value isn't a parsable double. - * @see org.apache.poi.ss.usermodel.DataFormatter for turning this number into a string similar to that which Excel would render this number as. - */ - @Override - public double getNumericCellValue() - { - CellType cellType = getCellTypeEnum(); - switch(cellType) - { - case BLANK: - return 0.0; - case FORMULA: - { - FormulaValue fv=(FormulaValue)_value; - if(fv.getFormulaType()!=CellType.NUMERIC) - throw typeMismatch(CellType.NUMERIC, CellType.FORMULA, false); - return ((NumericFormulaValue)_value).getPreEvaluatedValue(); - } - case NUMERIC: - return ((NumericValue)_value).getValue(); - default: - throw typeMismatch(CellType.NUMERIC, cellType, false); - } - } - - /** - * Get the value of the cell as a date. - *

    - * For strings we throw an exception. For blank cells we return a null. - *

    - * @return the value of the cell as a date - * @throws IllegalStateException if the cell type returned by {@link #getCellTypeEnum()} is CellType.STRING - * @exception NumberFormatException if the cell value isn't a parsable double. - * @see org.apache.poi.ss.usermodel.DataFormatter for formatting this date into a string similar to how excel does. - */ - @Override - public Date getDateCellValue() - { - CellType cellType = getCellTypeEnum(); - if (cellType == CellType.BLANK) - { - return null; - } - - double value = getNumericCellValue(); - boolean date1904 = getSheet().getWorkbook().isDate1904(); - return DateUtil.getJavaDate(value, date1904); - } - - /** - * Get the value of the cell as a XSSFRichTextString - *

    - * For numeric cells we throw an exception. For blank cells we return an empty string. - * For formula cells we return the pre-calculated value if a string, otherwise an exception. - *

    - * @return the value of the cell as a XSSFRichTextString - */ - @Override - public RichTextString getRichStringCellValue() - { - CellType cellType = getCellTypeEnum(); - if(getCellTypeEnum() != CellType.STRING) - throw typeMismatch(CellType.STRING, cellType, false); - - StringValue sval = (StringValue)_value; - if(sval.isRichText()) - return ((RichTextValue)_value).getValue(); - else { - String plainText = getStringCellValue(); - return getSheet().getWorkbook().getCreationHelper().createRichTextString(plainText); - } - } - - - /** - * Get the value of the cell as a string - *

    - * For numeric cells we throw an exception. For blank cells we return an empty string. - * For formulaCells that are not string Formulas, we throw an exception. - *

    - * @return the value of the cell as a string - */ - @Override - public String getStringCellValue() - { - CellType cellType = getCellTypeEnum(); - switch(cellType) - { - case BLANK: - return ""; - case FORMULA: - { - FormulaValue fv=(FormulaValue)_value; - if(fv.getFormulaType()!=CellType.STRING) - throw typeMismatch(CellType.STRING, CellType.FORMULA, false); - return ((StringFormulaValue)_value).getPreEvaluatedValue(); - } - case STRING: - { - if(((StringValue)_value).isRichText()) - return ((RichTextValue)_value).getValue().getString(); - else - return ((PlainStringValue)_value).getValue(); - } - default: - throw typeMismatch(CellType.STRING, cellType, false); - } - } - - /** - * Set a boolean value for the cell - * - * @param value the boolean value to set this cell to. For formulas we'll set the - * precalculated value, for booleans we'll set its value. For other types we - * will change the cell to a boolean cell and set its value. - */ - @Override - public void setCellValue(boolean value) - { - ensureTypeOrFormulaType(CellType.BOOLEAN); - if(_value.getType()==CellType.FORMULA) - ((BooleanFormulaValue)_value).setPreEvaluatedValue(value); - else - ((BooleanValue)_value).setValue(value); - } - - /** - * Set a error value for the cell - * - * @param value the error value to set this cell to. For formulas we'll set the - * precalculated value , for errors we'll set - * its value. For other types we will change the cell to an error - * cell and set its value. - * @see org.apache.poi.ss.usermodel.FormulaError - */ - @Override - public void setCellErrorValue(byte value) - { - ensureType(CellType.ERROR); - if(_value.getType()==CellType.FORMULA) - ((ErrorFormulaValue)_value).setPreEvaluatedValue(value); - else - ((ErrorValue)_value).setValue(value); - } - - /** - * Get the value of the cell as a boolean. - *

    - * For strings, numbers, and errors, we throw an exception. For blank cells we return a false. - *

    - * @return the value of the cell as a boolean - * @throws IllegalStateException if the cell type returned by {@link #getCellTypeEnum()} - * is not CellType.BOOLEAN, CellType.BLANK or CellType.FORMULA - */ - @Override - public boolean getBooleanCellValue() - { - CellType cellType = getCellTypeEnum(); - switch(cellType) - { - case BLANK: - return false; - case FORMULA: - { - FormulaValue fv=(FormulaValue)_value; - if(fv.getFormulaType()!=CellType.BOOLEAN) - throw typeMismatch(CellType.BOOLEAN, CellType.FORMULA, false); - return ((BooleanFormulaValue)_value).getPreEvaluatedValue(); - } - case BOOLEAN: - { - return ((BooleanValue)_value).getValue(); - } - default: - throw typeMismatch(CellType.BOOLEAN, cellType, false); - } - } - - /** - * Get the value of the cell as an error code. - *

    - * For strings, numbers, and booleans, we throw an exception. - * For blank cells we return a 0. - *

    - * - * @return the value of the cell as an error code - * @throws IllegalStateException if the cell type returned by {@link #getCellTypeEnum()} isn't CellType.ERROR - * @see org.apache.poi.ss.usermodel.FormulaError for error codes - */ - @Override - public byte getErrorCellValue() - { - CellType cellType = getCellTypeEnum(); - switch(cellType) - { - case BLANK: - return 0; - case FORMULA: - { - FormulaValue fv=(FormulaValue)_value; - if(fv.getFormulaType()!=CellType.ERROR) - throw typeMismatch(CellType.ERROR, CellType.FORMULA, false); - return ((ErrorFormulaValue)_value).getPreEvaluatedValue(); - } - case ERROR: - { - return ((ErrorValue)_value).getValue(); - } - default: - throw typeMismatch(CellType.ERROR, cellType, false); - } - } - - /** - *

    Set the style for the cell. The style should be an CellStyle created/retreived from - * the Workbook.

    - * - *

    To change the style of a cell without affecting other cells that use the same style, - * use {@link org.apache.poi.ss.util.CellUtil#setCellStyleProperties(Cell, Map)}

    - * - * @param style reference contained in the workbook. - * If the value is null then the style information is removed causing the cell to used the default workbook style. - * @see org.apache.poi.ss.usermodel.Workbook#createCellStyle - */ - @Override - public void setCellStyle(CellStyle style) - { - _style=style; - } - - /** - * Return the cell's style. - * - * @return the cell's style. Always not-null. Default cell style has zero index and can be obtained as - * workbook.getCellStyleAt(0) - * @see org.apache.poi.ss.usermodel.Workbook#getCellStyleAt(int) - */ - @Override - public CellStyle getCellStyle() - { - if(_style == null){ - SXSSFWorkbook wb = (SXSSFWorkbook)getRow().getSheet().getWorkbook(); - return wb.getCellStyleAt((short)0); - } else { - return _style; - } - } - - /** - * {@inheritDoc} - */ - @Override - public void setAsActiveCell() - { - getSheet().setActiveCell(getAddress()); - } - - /** - * Assign a comment to this cell - * - * @param comment comment associated with this cell - */ - @Override - public void setCellComment(Comment comment) - { - setProperty(Property.COMMENT,comment); - } - - /** - * Returns comment associated with this cell - * - * @return comment associated with this cell or null if not found - */ - @Override - public Comment getCellComment() - { - return (Comment)getPropertyValue(Property.COMMENT); - } - - /** - * Removes the comment for this cell, if there is one. - */ - @Override - public void removeCellComment() - { - removeProperty(Property.COMMENT); - } - - /** - * @return hyperlink associated with this cell or null if not found - */ - @Override - public Hyperlink getHyperlink() - { - return (Hyperlink)getPropertyValue(Property.HYPERLINK); - } - - /** - * Assign a hyperlink to this cell. If the supplied hyperlink is null, the - * hyperlink for this cell will be removed. - * - * @param link hyperlink associated with this cell - */ - @Override - public void setHyperlink(Hyperlink link) - { - if (link == null) { - removeHyperlink(); - return; - } - - setProperty(Property.HYPERLINK,link); - - XSSFHyperlink xssfobj = (XSSFHyperlink)link; - // Assign to us - CellReference ref = new CellReference(getRowIndex(), getColumnIndex()); - xssfobj.setCellReference( ref ); - - // Add to the lists - getSheet()._sh.addHyperlink(xssfobj); - } - - /** - * Removes the hyperlink for this cell, if there is one. - */ - @Override - public void removeHyperlink() - { - removeProperty(Property.HYPERLINK); - - getSheet()._sh.removeHyperlink(getRowIndex(), getColumnIndex()); - } - - /** - * Only valid for array formula cells - * - * @return range of the array formula group that the cell belongs to. - */ -// TODO: What is this? - @NotImplemented - public CellRangeAddress getArrayFormulaRange() - { - return null; - } - - /** - * @return true if this cell is part of group of cells having a common array formula. - */ -//TODO: What is this? - @NotImplemented - public boolean isPartOfArrayFormulaGroup() - { - return false; - } -//end of interface implementation - - /** - * Returns a string representation of the cell - *

    - * Formula cells return the formula string, rather than the formula result. - * Dates are displayed in dd-MMM-yyyy format - * Errors are displayed as #ERR<errIdx> - *

    - */ - @Override - public String toString() { - switch (getCellTypeEnum()) { - case BLANK: - return ""; - case BOOLEAN: - return getBooleanCellValue() ? "TRUE" : "FALSE"; - case ERROR: - return ErrorEval.getText(getErrorCellValue()); - case FORMULA: - return getCellFormula(); - case NUMERIC: - if (DateUtil.isCellDateFormatted(this)) { - DateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy", LocaleUtil.getUserLocale()); - sdf.setTimeZone(LocaleUtil.getUserTimeZone()); - return sdf.format(getDateCellValue()); - } - return getNumericCellValue() + ""; - case STRING: - return getRichStringCellValue().toString(); - default: - return "Unknown Cell Type: " + getCellTypeEnum(); - } - } - - /*package*/ void removeProperty(int type) - { - Property current=_firstProperty; - Property previous=null; - while(current!=null&¤t.getType()!=type) - { - previous=current; - current=current._next; - } - if(current!=null) - { - if(previous!=null) - { - previous._next=current._next; - } - else - { - _firstProperty=current._next; - } - } - } - /*package*/ void setProperty(int type,Object value) - { - Property current=_firstProperty; - Property previous=null; - while(current!=null&¤t.getType()!=type) - { - previous=current; - current=current._next; - } - if(current!=null) - { - current.setValue(value); - } - else - { - switch(type) - { - case Property.COMMENT: - { - current=new CommentProperty(value); - break; - } - case Property.HYPERLINK: - { - current=new HyperlinkProperty(value); - break; - } - default: - { - throw new IllegalArgumentException("Invalid type: " + type); - } - } - if(previous!=null) - { - previous._next=current; - } - else - { - _firstProperty=current; - } - } - } - /*package*/ Object getPropertyValue(int type) - { - return getPropertyValue(type,null); - } - /*package*/ Object getPropertyValue(int type,String defaultValue) - { - Property current=_firstProperty; - while(current!=null&¤t.getType()!=type) current=current._next; - return current==null?defaultValue:current.getValue(); - } - /*package*/ void ensurePlainStringType() - { - if(_value.getType()!=CellType.STRING - ||((StringValue)_value).isRichText()) - _value=new PlainStringValue(); - } - /*package*/ void ensureRichTextStringType() - { - if(_value.getType()!=CellType.STRING - ||!((StringValue)_value).isRichText()) - _value=new RichTextValue(); - } - /*package*/ void ensureType(CellType type) - { - if(_value.getType()!=type) - setType(type); - } - /*package*/ void ensureFormulaType(CellType type) - { - if(_value.getType()!=CellType.FORMULA - ||((FormulaValue)_value).getFormulaType()!=type) - setFormulaType(type); - } - /* - * Sets the cell type to type if it is different - */ - /*package*/ void ensureTypeOrFormulaType(CellType type) - { - if(_value.getType()==type) - { - if(type==CellType.STRING&&((StringValue)_value).isRichText()) - setType(CellType.STRING); - return; - } - if(_value.getType()==CellType.FORMULA) - { - if(((FormulaValue)_value).getFormulaType()==type) - return; - setFormulaType(type); // once a formula, always a formula - return; - } - setType(type); - } - /** - * changes the cell type to the specified type, and resets the value to the default value for that type - * If cell type is the same as specified type, this will reset the value to the default value for that type - * - * @param type the cell type to set - * @throws IllegalArgumentException if type is not a recognized type - */ - /*package*/ void setType(CellType type) - { - switch(type) - { - case NUMERIC: - { - _value=new NumericValue(); - break; - } - case STRING: - { - PlainStringValue sval = new PlainStringValue(); - if(_value != null){ - // if a cell is not blank then convert the old value to string - String str = convertCellValueToString(); - sval.setValue(str); - } - _value = sval; - break; - } - case FORMULA: - { - _value=new NumericFormulaValue(); - break; - } - case BLANK: - { - _value=new BlankValue(); - break; - } - case BOOLEAN: - { - BooleanValue bval = new BooleanValue(); - if(_value != null){ - // if a cell is not blank then convert the old value to string - boolean val = convertCellValueToBoolean(); - bval.setValue(val); - } - _value = bval; - break; - } - case ERROR: - { - _value=new ErrorValue(); - break; - } - default: - { - throw new IllegalArgumentException("Illegal type " + type); - } - } - } - /*package*/ void setFormulaType(CellType type) - { - Value prevValue = _value; - switch(type) - { - case NUMERIC: - { - _value=new NumericFormulaValue(); - break; - } - case STRING: - { - _value=new StringFormulaValue(); - break; - } - case BOOLEAN: - { - _value=new BooleanFormulaValue(); - break; - } - case ERROR: - { - _value=new ErrorFormulaValue(); - break; - } - default: - { - throw new IllegalArgumentException("Illegal type " + type); - } - } - - // if we had a Formula before, we should copy over the _value of the formula - if(prevValue instanceof FormulaValue) { - ((FormulaValue)_value)._value = ((FormulaValue)prevValue)._value; - } - } - -//TODO: implement this correctly - @NotImplemented - /*package*/ CellType computeTypeFromFormula(String formula) - { - return CellType.NUMERIC; - } -//COPIED FROM https://svn.apache.org/repos/asf/poi/trunk/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFCell.java since the functions are declared private there - /** - * Used to help format error messages - */ - private static RuntimeException typeMismatch(CellType expectedTypeCode, CellType actualTypeCode, boolean isFormulaCell) { - String msg = "Cannot get a " + expectedTypeCode + " value from a " + actualTypeCode - + " " + (isFormulaCell ? "formula " : "") + "cell"; - return new IllegalStateException(msg); - } - - private boolean convertCellValueToBoolean() { - CellType cellType = getCellTypeEnum(); - - if (cellType == CellType.FORMULA) { - cellType = getCachedFormulaResultTypeEnum(); - } - - switch (cellType) { - case BOOLEAN: - return getBooleanCellValue(); - case STRING: - - String text = getStringCellValue(); - return Boolean.parseBoolean(text); - case NUMERIC: - return getNumericCellValue() != 0; - case ERROR: - case BLANK: - return false; - default: throw new RuntimeException("Unexpected cell type (" + cellType + ")"); - } - - } - private String convertCellValueToString() { - CellType cellType = getCellTypeEnum(); - return convertCellValueToString(cellType); - } - private String convertCellValueToString(CellType cellType) { - switch (cellType) { - case BLANK: - return ""; - case BOOLEAN: - return getBooleanCellValue() ? "TRUE" : "FALSE"; - case STRING: - return getStringCellValue(); - case NUMERIC: - return Double.toString( getNumericCellValue() ); - case ERROR: - byte errVal = getErrorCellValue(); - return FormulaError.forInt(errVal).getString(); - case FORMULA: - if (_value != null) { - FormulaValue fv = (FormulaValue)_value; - if (fv.getFormulaType() != CellType.FORMULA) { - return convertCellValueToString(fv.getFormulaType()); - } - } - return ""; - default: - throw new IllegalStateException("Unexpected cell type (" + cellType + ")"); - } - } - -//END OF COPIED CODE - - static abstract class Property - { - static final int COMMENT=1; - static final int HYPERLINK=2; - Object _value; - Property _next; - public Property(Object value) - { - _value=value; - } - abstract int getType(); - void setValue(Object value) - { - _value=value; - } - Object getValue() - { - return _value; - } - } - static class CommentProperty extends Property - { - public CommentProperty(Object value) - { - super(value); - } - @Override - public int getType() - { - return COMMENT; - } - } - static class HyperlinkProperty extends Property - { - public HyperlinkProperty(Object value) - { - super(value); - } - @Override - public int getType() - { - return HYPERLINK; - } - } - interface Value - { - CellType getType(); - } - static class NumericValue implements Value - { - double _value; - public CellType getType() - { - return CellType.NUMERIC; - } - void setValue(double value) - { - _value=value; - } - double getValue() - { - return _value; - } - } - static abstract class StringValue implements Value - { - public CellType getType() - { - return CellType.STRING; - } -//We cannot introduce a new type CellType.RICH_TEXT because the types are public so we have to make rich text as a type of string - abstract boolean isRichText(); // using the POI style which seems to avoid "instanceof". - } - static class PlainStringValue extends StringValue - { - String _value; - void setValue(String value) - { - _value=value; - } - String getValue() - { - return _value; - } - @Override - boolean isRichText() - { - return false; - } - } - static class RichTextValue extends StringValue - { - RichTextString _value; - @Override - public CellType getType() - { - return CellType.STRING; - } - void setValue(RichTextString value) - { - _value=value; - } - RichTextString getValue() - { - return _value; - } - @Override - boolean isRichText() - { - return true; - } - } - static abstract class FormulaValue implements Value - { - String _value; - public CellType getType() - { - return CellType.FORMULA; - } - void setValue(String value) - { - _value=value; - } - String getValue() - { - return _value; - } - abstract CellType getFormulaType(); - } - static class NumericFormulaValue extends FormulaValue - { - double _preEvaluatedValue; - @Override - CellType getFormulaType() - { - return CellType.NUMERIC; - } - void setPreEvaluatedValue(double value) - { - _preEvaluatedValue=value; - } - double getPreEvaluatedValue() - { - return _preEvaluatedValue; - } - } - static class StringFormulaValue extends FormulaValue - { - String _preEvaluatedValue; - @Override - CellType getFormulaType() - { - return CellType.STRING; - } - void setPreEvaluatedValue(String value) - { - _preEvaluatedValue=value; - } - String getPreEvaluatedValue() - { - return _preEvaluatedValue; - } - } - static class BooleanFormulaValue extends FormulaValue - { - boolean _preEvaluatedValue; - @Override - CellType getFormulaType() - { - return CellType.BOOLEAN; - } - void setPreEvaluatedValue(boolean value) - { - _preEvaluatedValue=value; - } - boolean getPreEvaluatedValue() - { - return _preEvaluatedValue; - } - } - static class ErrorFormulaValue extends FormulaValue - { - byte _preEvaluatedValue; - @Override - CellType getFormulaType() - { - return CellType.ERROR; - } - void setPreEvaluatedValue(byte value) - { - _preEvaluatedValue=value; - } - byte getPreEvaluatedValue() - { - return _preEvaluatedValue; - } - } - static class BlankValue implements Value - { - public CellType getType() - { - return CellType.BLANK; - } - } - static class BooleanValue implements Value - { - boolean _value; - public CellType getType() - { - return CellType.BOOLEAN; - } - void setValue(boolean value) - { - _value=value; - } - boolean getValue() - { - return _value; - } - } - static class ErrorValue implements Value - { - byte _value; - public CellType getType() - { - return CellType.ERROR; - } - void setValue(byte value) - { - _value=value; - } - byte getValue() - { - return _value; - } - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/streaming/SXSSFCreationHelper.java b/src/ooxml/java/org/apache/poi/xssf/streaming/SXSSFCreationHelper.java deleted file mode 100644 index f2687ff1d..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/streaming/SXSSFCreationHelper.java +++ /dev/null @@ -1,93 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.streaming; - -import org.apache.poi.common.usermodel.HyperlinkType; -import org.apache.poi.ss.usermodel.ClientAnchor; -import org.apache.poi.ss.usermodel.CreationHelper; -import org.apache.poi.ss.usermodel.DataFormat; -import org.apache.poi.ss.usermodel.ExtendedColor; -import org.apache.poi.ss.usermodel.Hyperlink; -import org.apache.poi.util.Internal; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.util.Removal; -import org.apache.poi.xssf.usermodel.XSSFCreationHelper; -import org.apache.poi.xssf.usermodel.XSSFRichTextString; - -/** - * Streaming Creation Helper, which performs some actions - * based on the Streaming Workbook, and some on the related - * regular XSSF Workbook - */ -public class SXSSFCreationHelper implements CreationHelper { - private static final POILogger logger = POILogFactory.getLogger(SXSSFCreationHelper.class); - - private final SXSSFWorkbook wb; - private final XSSFCreationHelper helper; - - /** - * Should only be called by {@link SXSSFWorkbook#getCreationHelper()} - * - * @param workbook the workbook to create objects for - */ - @Internal - public SXSSFCreationHelper(SXSSFWorkbook workbook) { - this.helper = new XSSFCreationHelper(workbook.getXSSFWorkbook()); - this.wb = workbook; - } - - @Override - public XSSFRichTextString createRichTextString(String text) { - logger.log(POILogger.INFO, "SXSSF doesn't support Rich Text Strings, any formatting information will be lost"); - return new XSSFRichTextString(text); - } - - @Override - public SXSSFFormulaEvaluator createFormulaEvaluator() { - return new SXSSFFormulaEvaluator(wb); - } - - // Pass-through methods - @Override - public DataFormat createDataFormat() { - return helper.createDataFormat(); - } - /** - * {@inheritDoc} - * @deprecated POI 3.15 beta 3. Use {@link #createHyperlink(HyperlinkType)} instead. - */ - @Deprecated - @Removal(version="3.17") - @Override - public Hyperlink createHyperlink(int type) { - return helper.createHyperlink(type); - } - @Override - public Hyperlink createHyperlink(HyperlinkType type) { - return helper.createHyperlink(type); - } - @Override - public ExtendedColor createExtendedColor() { - return helper.createExtendedColor(); - } - @Override - public ClientAnchor createClientAnchor() { - return helper.createClientAnchor(); - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/streaming/SXSSFDrawing.java b/src/ooxml/java/org/apache/poi/xssf/streaming/SXSSFDrawing.java deleted file mode 100644 index 3a645f767..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/streaming/SXSSFDrawing.java +++ /dev/null @@ -1,77 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.streaming; - -import java.util.Iterator; - -import org.apache.poi.ss.usermodel.Chart; -import org.apache.poi.ss.usermodel.ClientAnchor; -import org.apache.poi.ss.usermodel.Comment; -import org.apache.poi.ss.usermodel.Drawing; -import org.apache.poi.ss.usermodel.ObjectData; -import org.apache.poi.xssf.usermodel.XSSFDrawing; -import org.apache.poi.xssf.usermodel.XSSFPicture; -import org.apache.poi.xssf.usermodel.XSSFShape; - -/** - * Streaming version of Drawing. - * Delegates most tasks to the non-streaming XSSF code. - * TODO: Potentially, Comment and Chart need a similar streaming wrapper like Picture. - */ -public class SXSSFDrawing implements Drawing { - private final SXSSFWorkbook _wb; - private final XSSFDrawing _drawing; - - public SXSSFDrawing(SXSSFWorkbook workbook, XSSFDrawing drawing) { - this._wb = workbook; - this._drawing = drawing; - } - - @Override - public SXSSFPicture createPicture(ClientAnchor anchor, int pictureIndex) { - XSSFPicture pict = _drawing.createPicture(anchor, pictureIndex); - return new SXSSFPicture(_wb, pict); - } - - @Override - public Comment createCellComment(ClientAnchor anchor) { - return _drawing.createCellComment(anchor); - } - - @Override - public Chart createChart(ClientAnchor anchor) { - return _drawing.createChart(anchor); - } - - @Override - public ClientAnchor createAnchor(int dx1, int dy1, int dx2, int dy2, int col1, int row1, int col2, int row2) { - return _drawing.createAnchor(dx1, dy1, dx2, dy2, col1, row1, col2, row2); - } - - @Override - public ObjectData createObjectData(ClientAnchor anchor, int storageId, int pictureIndex) { - return _drawing.createObjectData(anchor, storageId, pictureIndex); - } - - @Override - public Iterator iterator() { - return _drawing.getShapes().iterator(); - } - -} - diff --git a/src/ooxml/java/org/apache/poi/xssf/streaming/SXSSFEvaluationCell.java b/src/ooxml/java/org/apache/poi/xssf/streaming/SXSSFEvaluationCell.java deleted file mode 100644 index 8c11e8b8b..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/streaming/SXSSFEvaluationCell.java +++ /dev/null @@ -1,119 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.streaming; - -import org.apache.poi.ss.formula.EvaluationCell; -import org.apache.poi.ss.formula.EvaluationSheet; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.util.Internal; - -/** - * SXSSF wrapper for a cell under evaluation - */ -final class SXSSFEvaluationCell implements EvaluationCell { - private final EvaluationSheet _evalSheet; - private final SXSSFCell _cell; - - public SXSSFEvaluationCell(SXSSFCell cell, SXSSFEvaluationSheet evaluationSheet) { - _cell = cell; - _evalSheet = evaluationSheet; - } - - public SXSSFEvaluationCell(SXSSFCell cell) { - this(cell, new SXSSFEvaluationSheet(cell.getSheet())); - } - - @Override - public Object getIdentityKey() { - // save memory by just using the cell itself as the identity key - // Note - this assumes SXSSFCell has not overridden hashCode and equals - return _cell; - } - - public SXSSFCell getSXSSFCell() { - return _cell; - } - @Override - public boolean getBooleanCellValue() { - return _cell.getBooleanCellValue(); - } - /** - * Will return {@link CellType} in a future version of POI. - * For forwards compatibility, do not hard-code cell type literals in your code. - * - * @return cell type - */ - @Override - public int getCellType() { - return _cell.getCellType(); - } - /** - * @since POI 3.15 beta 3 - * @deprecated POI 3.15 beta 3. - * Will be deleted when we make the CellType enum transition. See bug 59791. - */ - @Internal(since="POI 3.15 beta 3") - @Override - public CellType getCellTypeEnum() { - return _cell.getCellTypeEnum(); - } - @Override - public int getColumnIndex() { - return _cell.getColumnIndex(); - } - @Override - public int getErrorCellValue() { - return _cell.getErrorCellValue(); - } - @Override - public double getNumericCellValue() { - return _cell.getNumericCellValue(); - } - @Override - public int getRowIndex() { - return _cell.getRowIndex(); - } - @Override - public EvaluationSheet getSheet() { - return _evalSheet; - } - @Override - public String getStringCellValue() { - return _cell.getRichStringCellValue().getString(); - } - /** - * Will return {@link CellType} in a future version of POI. - * For forwards compatibility, do not hard-code cell type literals in your code. - * - * @return cell type of cached formula result - */ - @Override - public int getCachedFormulaResultType() { - return _cell.getCachedFormulaResultType(); - } - /** - * @since POI 3.15 beta 3 - * @deprecated POI 3.15 beta 3. - * Will be deleted when we make the CellType enum transition. See bug 59791. - */ - @Internal(since="POI 3.15 beta 3") - @Override - public CellType getCachedFormulaResultTypeEnum() { - return _cell.getCachedFormulaResultTypeEnum(); - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/streaming/SXSSFEvaluationSheet.java b/src/ooxml/java/org/apache/poi/xssf/streaming/SXSSFEvaluationSheet.java deleted file mode 100644 index 57d7cc57b..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/streaming/SXSSFEvaluationSheet.java +++ /dev/null @@ -1,61 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.streaming; - -import org.apache.poi.ss.formula.EvaluationCell; -import org.apache.poi.ss.formula.EvaluationSheet; -import org.apache.poi.util.Internal; - -/** - * SXSSF wrapper for a sheet under evaluation - */ -@Internal -final class SXSSFEvaluationSheet implements EvaluationSheet { - private final SXSSFSheet _xs; - - public SXSSFEvaluationSheet(SXSSFSheet sheet) { - _xs = sheet; - } - - public SXSSFSheet getSXSSFSheet() { - return _xs; - } - @Override - public EvaluationCell getCell(int rowIndex, int columnIndex) { - SXSSFRow row = _xs.getRow(rowIndex); - if (row == null) { - if (rowIndex <= _xs.getLastFlushedRowNum()) { - throw new SXSSFFormulaEvaluator.RowFlushedException(rowIndex); - } - return null; - } - SXSSFCell cell = row.getCell(columnIndex); - if (cell == null) { - return null; - } - return new SXSSFEvaluationCell(cell, this); - } - - /* (non-JavaDoc), inherit JavaDoc from EvaluationSheet - * @since POI 3.15 beta 3 - */ - @Override - public void clearAllCachedResultValues() { - // nothing to do - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/streaming/SXSSFEvaluationWorkbook.java b/src/ooxml/java/org/apache/poi/xssf/streaming/SXSSFEvaluationWorkbook.java deleted file mode 100644 index e9040c912..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/streaming/SXSSFEvaluationWorkbook.java +++ /dev/null @@ -1,63 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.streaming; - -import org.apache.poi.ss.formula.EvaluationCell; -import org.apache.poi.ss.formula.EvaluationSheet; -import org.apache.poi.ss.formula.FormulaParser; -import org.apache.poi.ss.formula.FormulaType; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.apache.poi.xssf.usermodel.BaseXSSFEvaluationWorkbook; -import org.apache.poi.util.Internal; - -/** - * SXSSF wrapper around the SXSSF and XSSF workbooks - */ -@Internal -public final class SXSSFEvaluationWorkbook extends BaseXSSFEvaluationWorkbook { - private final SXSSFWorkbook _uBook; - - public static SXSSFEvaluationWorkbook create(SXSSFWorkbook book) { - if (book == null) { - return null; - } - return new SXSSFEvaluationWorkbook(book); - } - - private SXSSFEvaluationWorkbook(SXSSFWorkbook book) { - super(book.getXSSFWorkbook()); - _uBook = book; - } - - @Override - public int getSheetIndex(EvaluationSheet evalSheet) { - SXSSFSheet sheet = ((SXSSFEvaluationSheet)evalSheet).getSXSSFSheet(); - return _uBook.getSheetIndex(sheet); - } - - @Override - public EvaluationSheet getSheet(int sheetIndex) { - return new SXSSFEvaluationSheet(_uBook.getSheetAt(sheetIndex)); - } - - @Override - public Ptg[] getFormulaTokens(EvaluationCell evalCell) { - SXSSFCell cell = ((SXSSFEvaluationCell)evalCell).getSXSSFCell(); - return FormulaParser.parse(cell.getCellFormula(), this, FormulaType.CELL, _uBook.getSheetIndex(cell.getSheet())); - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/streaming/SXSSFFormulaEvaluator.java b/src/ooxml/java/org/apache/poi/xssf/streaming/SXSSFFormulaEvaluator.java deleted file mode 100644 index a995a08b5..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/streaming/SXSSFFormulaEvaluator.java +++ /dev/null @@ -1,139 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.streaming; - -import org.apache.poi.ss.formula.EvaluationCell; -import org.apache.poi.ss.formula.IStabilityClassifier; -import org.apache.poi.ss.formula.WorkbookEvaluator; -import org.apache.poi.ss.formula.udf.UDFFinder; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.xssf.usermodel.BaseXSSFFormulaEvaluator; - -/** - * Streaming-specific Formula Evaluator, which is able to - * lookup cells within the current Window. - */ -public final class SXSSFFormulaEvaluator extends BaseXSSFFormulaEvaluator { - private static final POILogger logger = POILogFactory.getLogger(SXSSFFormulaEvaluator.class); - - private SXSSFWorkbook wb; - - public SXSSFFormulaEvaluator(SXSSFWorkbook workbook) { - this(workbook, null, null); - } - private SXSSFFormulaEvaluator(SXSSFWorkbook workbook, IStabilityClassifier stabilityClassifier, UDFFinder udfFinder) { - this(workbook, new WorkbookEvaluator(SXSSFEvaluationWorkbook.create(workbook), stabilityClassifier, udfFinder)); - } - private SXSSFFormulaEvaluator(SXSSFWorkbook workbook, WorkbookEvaluator bookEvaluator) { - super(bookEvaluator); - this.wb = workbook; - } - - /** - * @param stabilityClassifier used to optimise caching performance. Pass null - * for the (conservative) assumption that any cell may have its definition changed after - * evaluation begins. - * @param udfFinder pass null for default (AnalysisToolPak only) - */ - public static SXSSFFormulaEvaluator create(SXSSFWorkbook workbook, IStabilityClassifier stabilityClassifier, UDFFinder udfFinder) { - return new SXSSFFormulaEvaluator(workbook, stabilityClassifier, udfFinder); - } - - /** - * Turns a SXSSFCell into a SXSSFEvaluationCell - */ - @Override - protected EvaluationCell toEvaluationCell(Cell cell) { - if (!(cell instanceof SXSSFCell)){ - throw new IllegalArgumentException("Unexpected type of cell: " + cell.getClass() + "." + - " Only SXSSFCells can be evaluated."); - } - - return new SXSSFEvaluationCell((SXSSFCell)cell); - } - - @Override - public SXSSFCell evaluateInCell(Cell cell) { - return (SXSSFCell) super.evaluateInCell(cell); - } - - /** - * For active worksheets only, will loop over rows and - * cells, evaluating formula cells there. - * If formula cells are outside the window for that sheet, - * it can either skip them silently, or give an exception - */ - public static void evaluateAllFormulaCells(SXSSFWorkbook wb, boolean skipOutOfWindow) { - SXSSFFormulaEvaluator eval = new SXSSFFormulaEvaluator(wb); - - // Check they're all available - for (Sheet sheet : wb) { - if (((SXSSFSheet)sheet).areAllRowsFlushed()) { - throw new SheetsFlushedException(); - } - } - - // Process the sheets as best we can - for (Sheet sheet : wb) { - - // Check if any rows have already been flushed out - int lastFlushedRowNum = ((SXSSFSheet) sheet).getLastFlushedRowNum(); - if (lastFlushedRowNum > -1) { - if (! skipOutOfWindow) throw new RowFlushedException(0); - logger.log(POILogger.INFO, "Rows up to " + lastFlushedRowNum + " have already been flushed, skipping"); - } - - // Evaluate what we have - for (Row r : sheet) { - for (Cell c : r) { - if (c.getCellTypeEnum() == CellType.FORMULA) { - eval.evaluateFormulaCellEnum(c); - } - } - } - } - } - - /** - * Loops over rows and cells, evaluating formula cells there. - * If any sheets are inactive, or any cells outside of the window, - * will give an Exception. - * For SXSSF, you generally don't want to use this method, instead - * evaluate your formulas as you go before they leave the window. - */ - public void evaluateAll() { - // Have the evaluation done, with exceptions - evaluateAllFormulaCells(wb, false); - } - - public static class SheetsFlushedException extends IllegalStateException { - protected SheetsFlushedException() { - super("One or more sheets have been flushed, cannot evaluate all cells"); - } - } - public static class RowFlushedException extends IllegalStateException { - protected RowFlushedException(int rowNum) { - super("Row " + rowNum + " has been flushed, cannot evaluate all cells"); - } - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/streaming/SXSSFPicture.java b/src/ooxml/java/org/apache/poi/xssf/streaming/SXSSFPicture.java deleted file mode 100644 index 963588297..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/streaming/SXSSFPicture.java +++ /dev/null @@ -1,300 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.streaming; - -import java.awt.Dimension; -import java.io.IOException; - -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.ss.usermodel.Picture; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Shape; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.ImageUtils; -import org.apache.poi.util.Internal; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.xssf.usermodel.XSSFAnchor; -import org.apache.poi.xssf.usermodel.XSSFClientAnchor; -import org.apache.poi.xssf.usermodel.XSSFDrawing; -import org.apache.poi.xssf.usermodel.XSSFPicture; -import org.apache.poi.xssf.usermodel.XSSFPictureData; -import org.apache.poi.xssf.usermodel.XSSFShape; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D; -import org.openxmlformats.schemas.drawingml.x2006.main.CTShapeProperties; -import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTPicture; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCol; - -/** - * Streaming version of Picture. - * Most of the code is a copy of the non-streaming XSSFPicture code. - * This is necessary as a private method getRowHeightInPixels of that class needs to be changed, which is called by a method call chain nested several levels. - * - * The main change is to access the rows in the SXSSF sheet, not the always empty rows in the XSSF sheet when checking the row heights. - */ -public final class SXSSFPicture implements Picture { - private static final POILogger logger = POILogFactory.getLogger(SXSSFPicture.class); - /** - * Column width measured as the number of characters of the maximum digit width of the - * numbers 0, 1, 2, ..., 9 as rendered in the normal style's font. There are 4 pixels of margin - * padding (two on each side), plus 1 pixel padding for the gridlines. - * - * This value is the same for default font in Office 2007 (Calibry) and Office 2003 and earlier (Arial) - */ - private static float DEFAULT_COLUMN_WIDTH = 9.140625f; - - private final SXSSFWorkbook _wb; - private final XSSFPicture _picture; - - SXSSFPicture(SXSSFWorkbook _wb, XSSFPicture _picture) { - this._wb = _wb; - this._picture = _picture; - } - - /** - * Return the underlying CTPicture bean that holds all properties for this picture - * - * @return the underlying CTPicture bean - */ - @Internal - public CTPicture getCTPicture(){ - return _picture.getCTPicture(); - } - - /** - * Reset the image to the original size. - * - *

    - * Please note, that this method works correctly only for workbooks - * with the default font size (Calibri 11pt for .xlsx). - * If the default font is changed the resized image can be streched vertically or horizontally. - *

    - */ - @Override - public void resize(){ - resize(1.0); - } - - /** - * Reset the image to the original size. - *

    - * Please note, that this method works correctly only for workbooks - * with the default font size (Calibri 11pt for .xlsx). - * If the default font is changed the resized image can be streched vertically or horizontally. - *

    - * - * @param scale the amount by which image dimensions are multiplied relative to the original size. - * resize(1.0) sets the original size, resize(0.5) resize to 50% of the original, - * resize(2.0) resizes to 200% of the original. - */ - @Override - public void resize(double scale){ - XSSFClientAnchor anchor = getClientAnchor(); - - XSSFClientAnchor pref = getPreferredSize(scale); - - int row2 = anchor.getRow1() + (pref.getRow2() - pref.getRow1()); - int col2 = anchor.getCol1() + (pref.getCol2() - pref.getCol1()); - - anchor.setCol2(col2); - anchor.setDx1(0); - anchor.setDx2(pref.getDx2()); - - anchor.setRow2(row2); - anchor.setDy1(0); - anchor.setDy2(pref.getDy2()); - } - - /** - * Calculate the preferred size for this picture. - * - * @return XSSFClientAnchor with the preferred size for this image - */ - @Override - public XSSFClientAnchor getPreferredSize(){ - return getPreferredSize(1.0); - } - - /** - * Calculate the preferred size for this picture. - * - * @param scale the amount by which image dimensions are multiplied relative to the original size. - * @return XSSFClientAnchor with the preferred size for this image - */ - public XSSFClientAnchor getPreferredSize(double scale){ - XSSFClientAnchor anchor = getClientAnchor(); - - XSSFPictureData data = getPictureData(); - Dimension size = getImageDimension(data.getPackagePart(), data.getPictureType()); - double scaledWidth = size.getWidth() * scale; - double scaledHeight = size.getHeight() * scale; - - float w = 0; - int col2 = anchor.getCol1()-1; - - while (w <= scaledWidth) { - w += getColumnWidthInPixels(++col2); - } - - assert (w > scaledWidth); - double cw = getColumnWidthInPixels(col2); - double deltaW = w - scaledWidth; - int dx2 = (int)(XSSFShape.EMU_PER_PIXEL * (cw - deltaW)); - - anchor.setCol2(col2); - anchor.setDx2(dx2); - - double h = 0; - int row2 = anchor.getRow1()-1; - - while (h <= scaledHeight) { - h += getRowHeightInPixels(++row2); - } - - assert (h > scaledHeight); - double ch = getRowHeightInPixels(row2); - double deltaH = h - scaledHeight; - int dy2 = (int)(XSSFShape.EMU_PER_PIXEL * (ch - deltaH)); - anchor.setRow2(row2); - anchor.setDy2(dy2); - - CTPositiveSize2D size2d = getCTPicture().getSpPr().getXfrm().getExt(); - size2d.setCx((long)(scaledWidth * XSSFShape.EMU_PER_PIXEL)); - size2d.setCy((long)(scaledHeight * XSSFShape.EMU_PER_PIXEL)); - - return anchor; - } - - private float getColumnWidthInPixels(int columnIndex){ - XSSFSheet sheet = getSheet(); - - CTCol col = sheet.getColumnHelper().getColumn(columnIndex, false); - double numChars = col == null || !col.isSetWidth() ? DEFAULT_COLUMN_WIDTH : col.getWidth(); - - return (float)numChars*XSSFWorkbook.DEFAULT_CHARACTER_WIDTH; - } - - private float getRowHeightInPixels(int rowIndex) { - // THE FOLLOWING THREE LINES ARE THE MAIN CHANGE compared to the non-streaming version: use the SXSSF sheet, - // not the XSSF sheet (which never contais rows when using SXSSF) - XSSFSheet xssfSheet = getSheet(); - SXSSFSheet sheet = _wb.getSXSSFSheet(xssfSheet); - Row row = sheet.getRow(rowIndex); - float height = row != null ? row.getHeightInPoints() : sheet.getDefaultRowHeightInPoints(); - return height * XSSFShape.PIXEL_DPI / XSSFShape.POINT_DPI; - } - /** - * Return the dimension of this image - * - * @param part the package part holding raw picture data - * @param type type of the picture: {@link Workbook#PICTURE_TYPE_JPEG}, - * {@link Workbook#PICTURE_TYPE_PNG} or {@link Workbook#PICTURE_TYPE_DIB} - * - * @return image dimension in pixels - */ - protected static Dimension getImageDimension(PackagePart part, int type){ - try { - return ImageUtils.getImageDimension(part.getInputStream(), type); - } catch (IOException e){ - //return a "singulariry" if ImageIO failed to read the image - logger.log(POILogger.WARN, e); - return new Dimension(); - } - } - - /** - * Return picture data for this shape - * - * @return picture data for this shape - */ - @Override - public XSSFPictureData getPictureData() { - return _picture.getPictureData(); - } - - protected CTShapeProperties getShapeProperties(){ - return getCTPicture().getSpPr(); - } - - @Override - public XSSFAnchor getAnchor() { - return _picture.getAnchor(); - } - - @Override - public void resize(double scaleX, double scaleY) { - _picture.resize(scaleX, scaleY); - } - - @Override - public XSSFClientAnchor getPreferredSize(double scaleX, double scaleY) { - return _picture.getPreferredSize(scaleX, scaleY); - } - - @Override - public Dimension getImageDimension() { - return _picture.getImageDimension(); - } - - @Override - public XSSFClientAnchor getClientAnchor() { - XSSFAnchor a = getAnchor(); - return (a instanceof XSSFClientAnchor) ? (XSSFClientAnchor)a : null; - } - - public XSSFDrawing getDrawing() { - return _picture.getDrawing(); - } - - @Override - public XSSFSheet getSheet() { - return _picture.getSheet(); - } - - @Override - public String getShapeName() { - return _picture.getShapeName(); - } - - @Override - public Shape getParent() { - return _picture.getParent(); - } - - @Override - public boolean isNoFill() { - return _picture.isNoFill(); - } - - @Override - public void setNoFill(boolean noFill) { - _picture.setNoFill(noFill); - } - - @Override - public void setFillColor(int red, int green, int blue) { - _picture.setFillColor(red, green, blue); - } - - @Override - public void setLineStyleColor( int red, int green, int blue ) { - _picture.setLineStyleColor(red, green, blue); - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/streaming/SXSSFRow.java b/src/ooxml/java/org/apache/poi/xssf/streaming/SXSSFRow.java deleted file mode 100644 index 7aaacdd9b..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/streaming/SXSSFRow.java +++ /dev/null @@ -1,579 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.streaming; - -import java.util.Iterator; -import java.util.Map.Entry; -import java.util.NoSuchElementException; -import java.util.SortedMap; -import java.util.TreeMap; - -import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.util.Internal; - -/** - * Streaming version of XSSFRow implementing the "BigGridDemo" strategy. - */ -public class SXSSFRow implements Row, Comparable -{ - private static final Boolean UNDEFINED = null; - - private final SXSSFSheet _sheet; // parent sheet - private final SortedMap _cells = new TreeMap(); - private short _style = -1; // index of cell style in style table - private short _height = -1; // row height in twips (1/20 point) - private boolean _zHeight = false; // row zero-height (this is somehow different than being hidden) - private int _outlineLevel = 0; // Outlining level of the row, when outlining is on - // use Boolean to have a tri-state for on/off/undefined - private Boolean _hidden = UNDEFINED; - private Boolean _collapsed = UNDEFINED; - - /** - * - * @param sheet the parent sheet the row belongs to - * @param initialSize - no longer needed - * @deprecated 2015-11-30 (circa POI 3.14beta1). Use {@link #SXSSFRow(SXSSFSheet)} instead. - */ - @Deprecated - public SXSSFRow(SXSSFSheet sheet, @SuppressWarnings("UnusedParameters") int initialSize) - { - this(sheet); - } - - public SXSSFRow(SXSSFSheet sheet) - { - _sheet=sheet; - } - - public Iterator allCellsIterator() - { - return new CellIterator(); - } - public boolean hasCustomHeight() - { - return _height!=-1; - } - - @Override - public int getOutlineLevel(){ - return _outlineLevel; - } - void setOutlineLevel(int level){ - _outlineLevel = level; - } - - /** - * get row hidden state: Hidden (true), Unhidden (false), Undefined (null) - * - * @return row hidden state - */ - public Boolean getHidden() { - return _hidden; - } - - /** - * set row hidden state: Hidden (true), Unhidden (false), Undefined (null) - * - * @param hidden row hidden state - */ - public void setHidden(Boolean hidden) { - this._hidden = hidden; - } - - public Boolean getCollapsed() { - return _collapsed; - } - - public void setCollapsed(Boolean collapsed) { - this._collapsed = collapsed; - } -//begin of interface implementation - /** - * {@inheritDoc} - */ - @Override - public Iterator iterator() - { - return new FilledCellIterator(); - } - - /** - * Use this to create new cells within the row and return it. - *

    - * The cell that is returned is a {@link CellType#BLANK}. The type can be changed - * either through calling setCellValue or setCellType. - * - * @param column - the column number this cell represents - * @return Cell a high level representation of the created cell. - * @throws IllegalArgumentException if columnIndex < 0 or greater than the maximum number of supported columns - * (255 for *.xls, 1048576 for *.xlsx) - */ - @Override - public SXSSFCell createCell(int column) - { - return createCell(column, CellType.BLANK); - } - - /** - * Use this to create new cells within the row and return it. - *

    - * The cell that is returned is a {@link CellType#BLANK}. The type can be changed - * either through calling setCellValue or setCellType. - * - * @param column - the column number this cell represents - * @return Cell a high level representation of the created cell. - * @throws IllegalArgumentException if columnIndex < 0 or greate than a maximum number of supported columns - * (255 for *.xls, 1048576 for *.xlsx) - * @deprecated POI 3.15 beta 3. Use {@link #createCell(int, CellType)} instead. - */ - @Override - public SXSSFCell createCell(int column, int type) - { - return createCell(column, CellType.forInt(type)); - } - /** - * Use this to create new cells within the row and return it. - *

    - * The cell that is returned is a {@link CellType#BLANK}. The type can be changed - * either through calling setCellValue or setCellType. - * - * @param column - the column number this cell represents - * @return Cell a high level representation of the created cell. - * @throws IllegalArgumentException if columnIndex < 0 or greate than a maximum number of supported columns - * (255 for *.xls, 1048576 for *.xlsx) - */ - @Override - public SXSSFCell createCell(int column, CellType type) - { - checkBounds(column); - SXSSFCell cell = new SXSSFCell(this, type); - _cells.put(column, cell); - return cell; - } - - /** - * @throws RuntimeException if the bounds are exceeded. - */ - private static void checkBounds(int cellIndex) { - SpreadsheetVersion v = SpreadsheetVersion.EXCEL2007; - int maxcol = SpreadsheetVersion.EXCEL2007.getLastColumnIndex(); - if (cellIndex < 0 || cellIndex > maxcol) { - throw new IllegalArgumentException("Invalid column index (" + cellIndex - + "). Allowable column range for " + v.name() + " is (0.." - + maxcol + ") or ('A'..'" + v.getLastColumnName() + "')"); - } - } - - /** - * Remove the Cell from this row. - * - * @param cell the cell to remove - */ - @Override - public void removeCell(Cell cell) - { - int index = getCellIndex((SXSSFCell) cell); - _cells.remove(index); - } - - /** - * Return the column number of a cell if it is in this row - * Otherwise return -1 - * - * @param cell the cell to get the index of - * @return cell column index if it is in this row, -1 otherwise - */ - /*package*/ int getCellIndex(SXSSFCell cell) - { - for (Entry entry : _cells.entrySet()) { - if (entry.getValue()==cell) { - return entry.getKey(); - } - } - return -1; - } - - /** - * Set the row number of this row. - * - * @param rowNum the row number (0-based) - * @throws IllegalArgumentException if rowNum < 0 - */ - @Override - public void setRowNum(int rowNum) - { - _sheet.changeRowNum(this,rowNum); - } - - /** - * Get row number this row represents - * - * @return the row number (0 based) - */ - @Override - public int getRowNum() - { - return _sheet.getRowNum(this); - } - - /** - * Get the cell representing a given column (logical cell) 0-based. - * If cell is missing or blank, uses the workbook's MissingCellPolicy - * to determine the return value. - * - * @param cellnum 0 based column number - * @return Cell representing that column or null if undefined. - * @see #getCell(int, org.apache.poi.ss.usermodel.Row.MissingCellPolicy) - * @throws RuntimeException if cellnum is out of bounds - */ - @Override - public SXSSFCell getCell(int cellnum) { - MissingCellPolicy policy = _sheet.getWorkbook().getMissingCellPolicy(); - return getCell(cellnum, policy); - } - - /** - * Returns the cell at the given (0 based) index, with the specified {@link org.apache.poi.ss.usermodel.Row.MissingCellPolicy} - * - * @return the cell at the given (0 based) index - * @throws IllegalArgumentException if cellnum < 0 or the specified MissingCellPolicy is invalid - */ - @Override - public SXSSFCell getCell(int cellnum, MissingCellPolicy policy) - { - checkBounds(cellnum); - - final SXSSFCell cell = _cells.get(cellnum); - switch (policy) { - case RETURN_NULL_AND_BLANK: - return cell; - case RETURN_BLANK_AS_NULL: - boolean isBlank = (cell != null && cell.getCellTypeEnum() == CellType.BLANK); - return (isBlank) ? null : cell; - case CREATE_NULL_AS_BLANK: - return (cell == null) ? createCell(cellnum, CellType.BLANK) : cell; - default: - throw new IllegalArgumentException("Illegal policy " + policy + " (" + policy.id + ")"); - } - } - - /** - * Get the number of the first cell contained in this row. - * - * @return short representing the first logical cell in the row, - * or -1 if the row does not contain any cells. - */ - @Override - public short getFirstCellNum() - { - try { - return _cells.firstKey().shortValue(); - } catch (final NoSuchElementException e) { - return -1; - } - } - - /** - * Gets the index of the last cell contained in this row PLUS ONE. The result also - * happens to be the 1-based column number of the last cell. This value can be used as a - * standard upper bound when iterating over cells: - *

    -     * short minColIx = row.getFirstCellNum();
    -     * short maxColIx = row.getLastCellNum();
    -     * for(short colIx=minColIx; colIx<maxColIx; colIx++) {
    -     *   Cell cell = row.getCell(colIx);
    -     *   if(cell == null) {
    -     *     continue;
    -     *   }
    -     *   //... do something with cell
    -     * }
    -     * 
    - * - * @return short representing the last logical cell in the row PLUS ONE, - * or -1 if the row does not contain any cells. - */ - @Override - public short getLastCellNum() - { - return _cells.isEmpty() ? -1 : (short)(_cells.lastKey() + 1); - } - - /** - * Gets the number of defined cells (NOT number of cells in the actual row!). - * That is to say if only columns 0,4,5 have values then there would be 3. - * - * @return int representing the number of defined cells in the row. - */ - @Override - public int getPhysicalNumberOfCells() - { - return _cells.size(); - } - - /** - * Set the row's height or set to ff (-1) for undefined/default-height. Set the height in "twips" or - * 1/20th of a point. - * - * @param height rowheight or 0xff for undefined (use sheet default) - */ - @Override - public void setHeight(short height) - { - _height=height; - } - - /** - * Set whether or not to display this row with 0 height - * - * @param zHeight height is zero or not. - */ - @Override - public void setZeroHeight(boolean zHeight) - { - _zHeight=zHeight; - } - - /** - * Get whether or not to display this row with 0 height - * - * @return - zHeight height is zero or not. - */ - @Override - public boolean getZeroHeight() - { - return _zHeight; - } - - /** - * Set the row's height in points. - * - * @param height the height in points. -1 resets to the default height - */ - @Override - public void setHeightInPoints(float height) - { - if(height==-1) - _height=-1; - else - _height=(short)(height*20); - } - - /** - * Get the row's height measured in twips (1/20th of a point). If the height is not set, the default worksheet value is returned, - * See {@link Sheet#getDefaultRowHeightInPoints()} - * - * @return row height measured in twips (1/20th of a point) - */ - @Override - public short getHeight() - { - return (short)(_height==-1?getSheet().getDefaultRowHeightInPoints()*20:_height); - } - - /** - * Returns row height measured in point size. If the height is not set, the default worksheet value is returned, - * See {@link Sheet#getDefaultRowHeightInPoints()} - * - * @return row height measured in point size - * @see Sheet#getDefaultRowHeightInPoints() - */ - @Override - public float getHeightInPoints() - { - return (float)(_height==-1?getSheet().getDefaultRowHeightInPoints():_height/20.0); - } - - /** - * Is this row formatted? Most aren't, but some rows - * do have whole-row styles. For those that do, you - * can get the formatting from {@link #getRowStyle()} - */ - @Override - public boolean isFormatted() { - return _style > -1; - } - /** - * Returns the whole-row cell style. Most rows won't - * have one of these, so will return null. Call - * {@link #isFormatted()} to check first. - */ - @Override - public CellStyle getRowStyle() { - if(!isFormatted()) return null; - - return getSheet().getWorkbook().getCellStyleAt(_style); - } - - @Internal - /*package*/ int getRowStyleIndex() { - return _style; - } - - /** - * Applies a whole-row cell styling to the row. - * The row style can be cleared by passing in null. - */ - @Override - public void setRowStyle(CellStyle style) { - if(style == null) { - _style = -1; - } else { - _style = style.getIndex(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public Iterator cellIterator() - { - return iterator(); - } - - /** - * Returns the Sheet this row belongs to - * - * @return the Sheet that owns this row - */ - @Override - public SXSSFSheet getSheet() - { - return _sheet; - } -//end of interface implementation - - - /** - * Create an iterator over the cells from [0, getLastCellNum()). - * Includes blank cells, excludes empty cells - * - * Returns an iterator over all filled cells (created via Row.createCell()) - * Throws ConcurrentModificationException if cells are added, moved, or - * removed after the iterator is created. - */ - public class FilledCellIterator implements Iterator - { - private final Iterator iter = _cells.values().iterator(); - - @Override - public boolean hasNext() - { - return iter.hasNext(); - } - @Override - public Cell next() throws NoSuchElementException - { - return iter.next(); - } - @Override - public void remove() - { - throw new UnsupportedOperationException(); - } - } - /** - * returns all cells including empty cells (null values are returned - * for empty cells). - * This method is not synchronized. This iterator should not be used after - * cells are added, moved, or removed, though a ConcurrentModificationException - * is NOT thrown. - */ - public class CellIterator implements Iterator - { - final int maxColumn = getLastCellNum(); //last column PLUS ONE - int pos = 0; - - @Override - public boolean hasNext() - { - return pos < maxColumn; - } - @Override - public Cell next() throws NoSuchElementException - { - if (hasNext()) - return _cells.get(pos++); - else - throw new NoSuchElementException(); - } - @Override - public void remove() - { - throw new UnsupportedOperationException(); - } - } - - /** - * Compares two SXSSFRow objects. Two rows are equal if they belong to the same worksheet and - * their row indexes are equal. - * - * @param other the SXSSFRow to be compared. - * @return
      - *
    • - * the value 0 if the row number of this SXSSFRow is - * equal to the row number of the argument SXSSFRow - *
    • - *
    • - * a value less than 0 if the row number of this this SXSSFRow is - * numerically less than the row number of the argument SXSSFRow - *
    • - *
    • - * a value greater than 0 if the row number of this this SXSSFRow is - * numerically greater than the row number of the argument SXSSFRow - *
    • - *
    - * @throws IllegalArgumentException if the argument row belongs to a different worksheet - */ - @Override - public int compareTo(SXSSFRow other) { - if (this.getSheet() != other.getSheet()) { - throw new IllegalArgumentException("The compared rows must belong to the same sheet"); - } - - Integer thisRow = this.getRowNum(); - Integer otherRow = other.getRowNum(); - return thisRow.compareTo(otherRow); - } - - @Override - public boolean equals(Object obj) - { - if (!(obj instanceof SXSSFRow)) - { - return false; - } - SXSSFRow other = (SXSSFRow) obj; - - return (this.getRowNum() == other.getRowNum()) && - (this.getSheet() == other.getSheet()); - } - - @Override - public int hashCode() { - return _cells.hashCode(); - } - - -} - diff --git a/src/ooxml/java/org/apache/poi/xssf/streaming/SXSSFSheet.java b/src/ooxml/java/org/apache/poi/xssf/streaming/SXSSFSheet.java deleted file mode 100644 index 6f85aad49..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/streaming/SXSSFSheet.java +++ /dev/null @@ -1,1969 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.streaming; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; - -import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.ss.usermodel.AutoFilter; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellRange; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.DataValidation; -import org.apache.poi.ss.usermodel.DataValidationHelper; -import org.apache.poi.ss.usermodel.Footer; -import org.apache.poi.ss.usermodel.Header; -import org.apache.poi.ss.usermodel.PrintSetup; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.SheetConditionalFormatting; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.CellAddress; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.PaneInformation; -import org.apache.poi.ss.util.SheetUtil; -import org.apache.poi.util.Internal; -import org.apache.poi.util.NotImplemented; -import org.apache.poi.util.Removal; -import org.apache.poi.xssf.usermodel.XSSFColor; -import org.apache.poi.xssf.usermodel.XSSFComment; -import org.apache.poi.xssf.usermodel.XSSFDataValidation; -import org.apache.poi.xssf.usermodel.XSSFDrawing; -import org.apache.poi.xssf.usermodel.XSSFHyperlink; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTSheetFormatPr; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet; - -/** - * Streaming version of XSSFSheet implementing the "BigGridDemo" strategy. -*/ -public class SXSSFSheet implements Sheet -{ - /*package*/ final XSSFSheet _sh; - private final SXSSFWorkbook _workbook; - private final TreeMap _rows=new TreeMap(); - private final SheetDataWriter _writer; - private int _randomAccessWindowSize = SXSSFWorkbook.DEFAULT_WINDOW_SIZE; - private final AutoSizeColumnTracker _autoSizeColumnTracker; - private int outlineLevelRow = 0; - private int lastFlushedRowNumber = -1; - private boolean allFlushed = false; - - public SXSSFSheet(SXSSFWorkbook workbook, XSSFSheet xSheet) throws IOException { - _workbook = workbook; - _sh = xSheet; - _writer = workbook.createSheetDataWriter(); - setRandomAccessWindowSize(_workbook.getRandomAccessWindowSize()); - _autoSizeColumnTracker = new AutoSizeColumnTracker(this); - } - - /** - * for testing purposes only - */ - @Internal - SheetDataWriter getSheetDataWriter(){ - return _writer; - } - -/* Gets "" document fragment*/ - public InputStream getWorksheetXMLInputStream() throws IOException - { - // flush all remaining data and close the temp file writer - flushRows(0); - _writer.close(); - return _writer.getWorksheetXMLInputStream(); - } - -//start of interface implementation - @Override - public Iterator iterator() - { - return rowIterator(); - } - - /** - * Create a new row within the sheet and return the high level representation - * - * @param rownum row number - * @return high level Row object representing a row in the sheet - * @throws IllegalArgumentException If the max. number of rows is exceeded or - * a rownum is provided where the row is already flushed to disk. - * @see #removeRow(Row) - */ - @Override - public SXSSFRow createRow(int rownum) - { - int maxrow = SpreadsheetVersion.EXCEL2007.getLastRowIndex(); - if (rownum < 0 || rownum > maxrow) { - throw new IllegalArgumentException("Invalid row number (" + rownum - + ") outside allowable range (0.." + maxrow + ")"); - } - - // attempt to overwrite a row that is already flushed to disk - if(rownum <= _writer.getLastFlushedRow() ) { - throw new IllegalArgumentException( - "Attempting to write a row["+rownum+"] " + - "in the range [0," + _writer.getLastFlushedRow() + "] that is already written to disk."); - } - - // attempt to overwrite a existing row in the input template - if(_sh.getPhysicalNumberOfRows() > 0 && rownum <= _sh.getLastRowNum() ) { - throw new IllegalArgumentException( - "Attempting to write a row["+rownum+"] " + - "in the range [0," + _sh.getLastRowNum() + "] that is already written to disk."); - } - - SXSSFRow newRow=new SXSSFRow(this); - _rows.put(rownum,newRow); - allFlushed = false; - if(_randomAccessWindowSize>=0&&_rows.size()>_randomAccessWindowSize) - { - try - { - flushRows(_randomAccessWindowSize); - } - catch (IOException ioe) - { - throw new RuntimeException(ioe); - } - } - return newRow; - } - - /** - * Remove a row from this sheet. All cells contained in the row are removed as well - * - * @param row representing a row to remove. - */ - @Override - public void removeRow(Row row) - { - if (row.getSheet() != this) { - throw new IllegalArgumentException("Specified row does not belong to this sheet"); - } - - for(Iterator> iter=_rows.entrySet().iterator();iter.hasNext();) - { - Map.Entry entry=iter.next(); - if(entry.getValue()==row) - { - iter.remove(); - return; - } - } - } - - /** - * Returns the logical row (not physical) 0-based. If you ask for a row that is not - * defined you get a null. This is to say row 4 represents the fifth row on a sheet. - * - * @param rownum row to get (0-based) - * @return Row representing the rownumber or null if its not defined on the sheet - */ - @Override - public SXSSFRow getRow(int rownum) - { - return _rows.get(rownum); - } - - /** - * Returns the number of physically defined rows (NOT the number of rows in the sheet) - * - * @return the number of physically defined rows in this sheet - */ - @Override - public int getPhysicalNumberOfRows() - { - return _rows.size()+_writer.getNumberOfFlushedRows(); - } - - /** - * Gets the first row on the sheet - * - * @return the number of the first logical row on the sheet (0-based) - */ - @Override - public int getFirstRowNum() - { - if(_writer.getNumberOfFlushedRows() > 0) { - return _writer.getLowestIndexOfFlushedRows(); - } - return _rows.size() == 0 ? 0 : _rows.firstKey(); - } - - /** - * Gets the last row on the sheet - * - * @return last row contained n this sheet (0-based) - */ - @Override - public int getLastRowNum() - { - return _rows.size() == 0 ? 0 : _rows.lastKey(); - } - - /** - * Get the visibility state for a given column - * - * @param columnIndex - the column to get (0-based) - * @param hidden - the visiblity state of the column - */ - @Override - public void setColumnHidden(int columnIndex, boolean hidden) - { - _sh.setColumnHidden(columnIndex,hidden); - } - - /** - * Get the hidden state for a given column - * - * @param columnIndex - the column to set (0-based) - * @return hidden - false if the column is visible - */ - @Override - public boolean isColumnHidden(int columnIndex) - { - return _sh.isColumnHidden(columnIndex); - } - - /** - * Set the width (in units of 1/256th of a character width) - *

    - * The maximum column width for an individual cell is 255 characters. - * This value represents the number of characters that can be displayed - * in a cell that is formatted with the standard font. - *

    - * - * @param columnIndex - the column to set (0-based) - * @param width - the width in units of 1/256th of a character width - */ - @Override - public void setColumnWidth(int columnIndex, int width) - { - _sh.setColumnWidth(columnIndex,width); - } - - /** - * get the width (in units of 1/256th of a character width ) - * @param columnIndex - the column to set (0-based) - * @return width - the width in units of 1/256th of a character width - */ - @Override - public int getColumnWidth(int columnIndex) - { - return _sh.getColumnWidth(columnIndex); - } - - /** - * Get the actual column width in pixels - * - *

    - * Please note, that this method works correctly only for workbooks - * with the default font size (Calibri 11pt for .xlsx). - *

    - */ - @Override - public float getColumnWidthInPixels(int columnIndex) { - return _sh.getColumnWidthInPixels(columnIndex); - } - - /** - * Set the default column width for the sheet (if the columns do not define their own width) - * in characters - * - * @param width default column width measured in characters - */ - @Override - public void setDefaultColumnWidth(int width) - { - _sh.setDefaultColumnWidth(width); - } - - /** - * Get the default column width for the sheet (if the columns do not define their own width) - * in characters - * - * @return default column width measured in characters - */ - @Override - public int getDefaultColumnWidth() - { - return _sh.getDefaultColumnWidth(); - } - - - /** - * Get the default row height for the sheet (if the rows do not define their own height) in - * twips (1/20 of a point) - * - * @return default row height measured in twips (1/20 of a point) - */ - @Override - public short getDefaultRowHeight() - { - return _sh.getDefaultRowHeight(); - } - - /** - * Get the default row height for the sheet (if the rows do not define their own height) in - * points. - * - * @return default row height in points - */ - @Override - public float getDefaultRowHeightInPoints() - { - return _sh.getDefaultRowHeightInPoints(); - } - - /** - * Set the default row height for the sheet (if the rows do not define their own height) in - * twips (1/20 of a point) - * - * @param height default row height measured in twips (1/20 of a point) - */ - @Override - public void setDefaultRowHeight(short height) - { - _sh.setDefaultRowHeight(height); - } - - /** - * Set the default row height for the sheet (if the rows do not define their own height) in - * points - * @param height default row height - */ - @Override - public void setDefaultRowHeightInPoints(float height) - { - _sh.setDefaultRowHeightInPoints(height); - } - - - /** - * Returns the CellStyle that applies to the given - * (0 based) column, or null if no style has been - * set for that column - */ - @Override - public CellStyle getColumnStyle(int column) - { - return _sh.getColumnStyle(column); - } - - /** - * Sets the CellStyle that applies to the given - * (0 based) column. - */ -// public CellStyle setColumnStyle(int column, CellStyle style); - - /** - * Adds a merged region of cells (hence those cells form one) - * - * @param region (rowfrom/colfrom-rowto/colto) to merge - * @return index of this region - */ - @Override - public int addMergedRegion(CellRangeAddress region) - { - return _sh.addMergedRegion(region); - } - - /** - * Adds a merged region of cells (hence those cells form one) - * - * @param region (rowfrom/colfrom-rowto/colto) to merge - * @return index of this region - */ - @Override - public int addMergedRegionUnsafe(CellRangeAddress region) - { - return _sh.addMergedRegionUnsafe(region); - } - - /** - * Verify that merged regions do not intersect multi-cell array formulas and - * no merged regions intersect another merged region in this sheet. - * - * @throws IllegalStateException if region intersects with a multi-cell array formula - * @throws IllegalStateException if at least one region intersects with another merged region in this sheet - */ - @Override - public void validateMergedRegions() { - _sh.validateMergedRegions(); - } - - /** - * Determines whether the output is vertically centered on the page. - * - * @param value true to vertically center, false otherwise. - */ - @Override - public void setVerticallyCenter(boolean value) - { - _sh.setVerticallyCenter(value); - } - - /** - * Determines whether the output is horizontally centered on the page. - * - * @param value true to horizontally center, false otherwise. - */ - @Override - public void setHorizontallyCenter(boolean value) - { - _sh.setHorizontallyCenter(value); - } - - /** - * Determine whether printed output for this sheet will be horizontally centered. - */ - @Override - public boolean getHorizontallyCenter() - { - return _sh.getHorizontallyCenter(); - } - - /** - * Determine whether printed output for this sheet will be vertically centered. - */ - @Override - public boolean getVerticallyCenter() - { - return _sh.getVerticallyCenter(); - } - - /** - * Removes a merged region of cells (hence letting them free) - * - * @param index of the region to unmerge - */ - @Override - public void removeMergedRegion(int index) - { - _sh.removeMergedRegion(index); - } - - /** - * Removes a merged region of cells (hence letting them free) - * - * @param indices of the regions to unmerge - */ - @Override - public void removeMergedRegions(Collection indices) - { - _sh.removeMergedRegions(indices); - } - - /** - * Returns the number of merged regions - * - * @return number of merged regions - */ - @Override - public int getNumMergedRegions() - { - return _sh.getNumMergedRegions(); - } - - /** - * Returns the merged region at the specified index. If you want multiple - * regions, it is faster to call {@link #getMergedRegions()} than to call - * this each time. - * - * @return the merged region at the specified index - */ - @Override - public CellRangeAddress getMergedRegion(int index) - { - return _sh.getMergedRegion(index); - } - - /** - * Returns the list of merged regions. If you want multiple regions, this is - * faster than calling {@link #getMergedRegion(int)} each time. - * - * @return the list of merged regions - */ - @Override - public List getMergedRegions() { - return _sh.getMergedRegions(); - } - - /** - * Returns an iterator of the physical rows - * - * @return an iterator of the PHYSICAL rows. Meaning the 3rd element may not - * be the third row if say for instance the second row is undefined. - */ - @Override - public Iterator rowIterator() - { - @SuppressWarnings("unchecked") - Iterator result = (Iterator)(Iterator)_rows.values().iterator(); - return result; - } - - /** - * Flag indicating whether the sheet displays Automatic Page Breaks. - * - * @param value true if the sheet displays Automatic Page Breaks. - */ - @Override - public void setAutobreaks(boolean value) - { - _sh.setAutobreaks(value); - } - - /** - * Set whether to display the guts or not - * - * @param value - guts or no guts - */ - @Override - public void setDisplayGuts(boolean value) - { - _sh.setDisplayGuts(value); - } - - /** - * Set whether the window should show 0 (zero) in cells containing zero value. - * When false, cells with zero value appear blank instead of showing the number zero. - * - * @param value whether to display or hide all zero values on the worksheet - */ - @Override - public void setDisplayZeros(boolean value) - { - _sh.setDisplayZeros(value); - } - - - /** - * Gets the flag indicating whether the window should show 0 (zero) in cells containing zero value. - * When false, cells with zero value appear blank instead of showing the number zero. - * - * @return whether all zero values on the worksheet are displayed - */ - @Override - public boolean isDisplayZeros() - { - return _sh.isDisplayZeros(); - } - - /** - * Sets whether the worksheet is displayed from right to left instead of from left to right. - * - * @param value true for right to left, false otherwise. - */ - @Override - public void setRightToLeft(boolean value) - { - _sh.setRightToLeft(value); - } - - /** - * Whether the text is displayed in right-to-left mode in the window - * - * @return whether the text is displayed in right-to-left mode in the window - */ - @Override - public boolean isRightToLeft() - { - return _sh.isRightToLeft(); - } - - /** - * Flag indicating whether the Fit to Page print option is enabled. - * - * @param value true if the Fit to Page print option is enabled. - */ - @Override - public void setFitToPage(boolean value) - { - _sh.setFitToPage(value); - } - - /** - * Flag indicating whether summary rows appear below detail in an outline, when applying an outline. - * - *

    - * When true a summary row is inserted below the detailed data being summarized and a - * new outline level is established on that row. - *

    - *

    - * When false a summary row is inserted above the detailed data being summarized and a new outline level - * is established on that row. - *

    - * @param value true if row summaries appear below detail in the outline - */ - @Override - public void setRowSumsBelow(boolean value) - { - _sh.setRowSumsBelow(value); - } - - /** - * Flag indicating whether summary columns appear to the right of detail in an outline, when applying an outline. - * - *

    - * When true a summary column is inserted to the right of the detailed data being summarized - * and a new outline level is established on that column. - *

    - *

    - * When false a summary column is inserted to the left of the detailed data being - * summarized and a new outline level is established on that column. - *

    - * @param value true if col summaries appear right of the detail in the outline - */ - @Override - public void setRowSumsRight(boolean value) - { - _sh.setRowSumsRight(value); - } - - /** - * Flag indicating whether the sheet displays Automatic Page Breaks. - * - * @return true if the sheet displays Automatic Page Breaks. - */ - @Override - public boolean getAutobreaks() - { - return _sh.getAutobreaks(); - } - - /** - * Get whether to display the guts or not, - * default value is true - * - * @return boolean - guts or no guts - */ - @Override - public boolean getDisplayGuts() - { - return _sh.getDisplayGuts(); - } - - /** - * Flag indicating whether the Fit to Page print option is enabled. - * - * @return true if the Fit to Page print option is enabled. - */ - @Override - public boolean getFitToPage() - { - return _sh.getFitToPage(); - } - - /** - * Flag indicating whether summary rows appear below detail in an outline, when applying an outline. - * - *

    - * When true a summary row is inserted below the detailed data being summarized and a - * new outline level is established on that row. - *

    - *

    - * When false a summary row is inserted above the detailed data being summarized and a new outline level - * is established on that row. - *

    - * @return true if row summaries appear below detail in the outline - */ - @Override - public boolean getRowSumsBelow() - { - return _sh.getRowSumsBelow(); - } - - /** - * Flag indicating whether summary columns appear to the right of detail in an outline, when applying an outline. - * - *

    - * When true a summary column is inserted to the right of the detailed data being summarized - * and a new outline level is established on that column. - *

    - *

    - * When false a summary column is inserted to the left of the detailed data being - * summarized and a new outline level is established on that column. - *

    - * @return true if col summaries appear right of the detail in the outline - */ - @Override - public boolean getRowSumsRight() - { - return _sh.getRowSumsRight(); - } - - /** - * Returns whether gridlines are printed. - * - * @return whether gridlines are printed - */ - @Override - public boolean isPrintGridlines() - { - return _sh.isPrintGridlines(); - } - - /** - * Turns on or off the printing of gridlines. - * - * @param show boolean to turn on or off the printing of gridlines - */ - @Override - public void setPrintGridlines(boolean show) - { - _sh.setPrintGridlines(show); - } - - /** - * Returns whether row and column headings are printed. - * - * @return whether row and column headings are printed - */ - @Override - public boolean isPrintRowAndColumnHeadings() - { - return _sh.isPrintRowAndColumnHeadings(); - } - - /** - * Turns on or off the printing of row and column headings. - * - * @param show boolean to turn on or off the printing of row and column headings - */ - @Override - public void setPrintRowAndColumnHeadings(boolean show) - { - _sh.setPrintRowAndColumnHeadings(show); - } - - /** - * Gets the print setup object. - * - * @return The user model for the print setup object. - */ - @Override - public PrintSetup getPrintSetup() - { - return _sh.getPrintSetup(); - } - - /** - * Gets the user model for the default document header. - *

    - * Note that XSSF offers more kinds of document headers than HSSF does - *

    - * @return the document header. Never null - */ - @Override - public Header getHeader() - { - return _sh.getHeader(); - } - - /** - * Gets the user model for the default document footer. - *

    - * Note that XSSF offers more kinds of document footers than HSSF does. - *

    - * @return the document footer. Never null - */ - @Override - public Footer getFooter() - { - return _sh.getFooter(); - } - - /** - * Sets a flag indicating whether this sheet is selected. - *

    - * Note: multiple sheets can be selected, but only one sheet can be active at one time. - *

    - * @param value true if this sheet is selected - * @see Workbook#setActiveSheet(int) - */ - @Override - public void setSelected(boolean value) - { - _sh.setSelected(value); - } - - /** - * Gets the size of the margin in inches. - * - * @param margin which margin to get - * @return the size of the margin - */ - @Override - public double getMargin(short margin) - { - return _sh.getMargin(margin); - } - - /** - * Sets the size of the margin in inches. - * - * @param margin which margin to get - * @param size the size of the margin - */ - @Override - public void setMargin(short margin, double size) - { - _sh.setMargin(margin,size); - } - - /** - * Answer whether protection is enabled or disabled - * - * @return true means protection enabled; false means protection disabled - */ - @Override - public boolean getProtect() - { - return _sh.getProtect(); - } - - /** - * Sets the protection enabled as well as the password - * @param password to set for protection. Pass null to remove protection - */ - @Override - public void protectSheet(String password) - { - _sh.protectSheet(password); - } - - /** - * Answer whether scenario protection is enabled or disabled - * - * @return true means protection enabled; false means protection disabled - */ - @Override - public boolean getScenarioProtect() - { - return _sh.getScenarioProtect(); - } - - /** - * Sets the zoom magnification for the sheet. The zoom is expressed as a - * fraction. For example to express a zoom of 75% use 3 for the numerator - * and 4 for the denominator. - * - * @param numerator The numerator for the zoom magnification. - * @param denominator The denominator for the zoom magnification. - * @deprecated 2015-11-23 (circa POI 3.14beta1). Use {@link #setZoom(int)} instead. - */ - @Deprecated - @Removal(version="3.16") - @Override - public void setZoom(int numerator, int denominator) - { - _sh.setZoom(numerator,denominator); - } - - /** - * Window zoom magnification for current view representing percent values. - * Valid values range from 10 to 400. Horizontal and Vertical scale together. - * - * For example: - *
    -     * 10 - 10%
    -     * 20 - 20%
    -     * ...
    -     * 100 - 100%
    -     * ...
    -     * 400 - 400%
    -     * 
    - * - * Current view can be Normal, Page Layout, or Page Break Preview. - * - * @param scale window zoom magnification - * @throws IllegalArgumentException if scale is invalid - */ - @Override - public void setZoom(int scale) { - _sh.setZoom(scale); - } - - /** - * The top row in the visible view when the sheet is - * first viewed after opening it in a viewer - * - * @return short indicating the rownum (0 based) of the top row - */ - @Override - public short getTopRow() - { - return _sh.getTopRow(); - } - - /** - * The left col in the visible view when the sheet is - * first viewed after opening it in a viewer - * - * @return short indicating the rownum (0 based) of the top row - */ - @Override - public short getLeftCol() - { - return _sh.getLeftCol(); - } - - /** - * Sets desktop window pane display area, when the - * file is first opened in a viewer. - * - * @param toprow the top row to show in desktop window pane - * @param leftcol the left column to show in desktop window pane - */ - @Override - public void showInPane(int toprow, int leftcol) - { - _sh.showInPane(toprow, leftcol); - } - - /** - * Control if Excel should be asked to recalculate all formulas when the - * workbook is opened, via the "sheetCalcPr fullCalcOnLoad" option. - * Calculating the formula values with {@link org.apache.poi.ss.usermodel.FormulaEvaluator} is the - * recommended solution, but this may be used for certain cases where - * evaluation in POI is not possible. - */ - @Override - public void setForceFormulaRecalculation(boolean value) { - _sh.setForceFormulaRecalculation(value); - } - - /** - * Whether Excel will be asked to recalculate all formulas when the - * workbook is opened. - */ - @Override - public boolean getForceFormulaRecalculation() { - return _sh.getForceFormulaRecalculation(); - } - - /** - * Not implemented for SXSSFSheets - * - * Shifts rows between startRow and endRow n number of rows. - * If you use a negative number, it will shift rows up. - * Code ensures that rows don't wrap around. - * - * Calls shiftRows(startRow, endRow, n, false, false); - * - *

    - * Additionally shifts merged regions that are completely defined in these - * rows (ie. merged 2 cells on a row to be shifted). - * @param startRow the row to start shifting - * @param endRow the row to end shifting - * @param n the number of rows to shift - */ - @NotImplemented - @Override - public void shiftRows(int startRow, int endRow, int n) - { - throw new RuntimeException("NotImplemented"); - } - - /** - * Not implemented for SXSSFSheets - * - * Shifts rows between startRow and endRow n number of rows. - * If you use a negative number, it will shift rows up. - * Code ensures that rows don't wrap around - * - *

    - * Additionally shifts merged regions that are completely defined in these - * rows (ie. merged 2 cells on a row to be shifted). All merged regions that are - * completely overlaid by shifting will be deleted. - *

    - * @param startRow the row to start shifting - * @param endRow the row to end shifting - * @param n the number of rows to shift - * @param copyRowHeight whether to copy the row height during the shift - * @param resetOriginalRowHeight whether to set the original row's height to the default - */ - @NotImplemented - @Override - public void shiftRows(int startRow, int endRow, int n, boolean copyRowHeight, boolean resetOriginalRowHeight) - { - throw new RuntimeException("NotImplemented"); - } - - /** - * Creates a split (freezepane). Any existing freezepane or split pane is overwritten. - * @param colSplit Horizonatal position of split. - * @param rowSplit Vertical position of split. - * @param leftmostColumn Left column visible in right pane. - * @param topRow Top row visible in bottom pane - */ - @Override - public void createFreezePane(int colSplit, int rowSplit, int leftmostColumn, int topRow) - { - _sh.createFreezePane(colSplit, rowSplit, leftmostColumn, topRow); - } - - /** - * Creates a split (freezepane). Any existing freezepane or split pane is overwritten. - * @param colSplit Horizonatal position of split. - * @param rowSplit Vertical position of split. - */ - @Override - public void createFreezePane(int colSplit, int rowSplit) - { - _sh.createFreezePane(colSplit,rowSplit); - } - - /** - * Creates a split pane. Any existing freezepane or split pane is overwritten. - * @param xSplitPos Horizonatal position of split (in 1/20th of a point). - * @param ySplitPos Vertical position of split (in 1/20th of a point). - * @param topRow Top row visible in bottom pane - * @param leftmostColumn Left column visible in right pane. - * @param activePane Active pane. One of: PANE_LOWER_RIGHT, - * PANE_UPPER_RIGHT, PANE_LOWER_LEFT, PANE_UPPER_LEFT - * @see #PANE_LOWER_LEFT - * @see #PANE_LOWER_RIGHT - * @see #PANE_UPPER_LEFT - * @see #PANE_UPPER_RIGHT - */ - @Override - public void createSplitPane(int xSplitPos, int ySplitPos, int leftmostColumn, int topRow, int activePane) - { - _sh.createSplitPane(xSplitPos, ySplitPos, leftmostColumn, topRow, activePane); - } - - /** - * Returns the information regarding the currently configured pane (split or freeze) - * - * @return null if no pane configured, or the pane information. - */ - @Override - public PaneInformation getPaneInformation() - { - return _sh.getPaneInformation(); - } - - /** - * Sets whether the gridlines are shown in a viewer - * - * @param show whether to show gridlines or not - */ - @Override - public void setDisplayGridlines(boolean show) - { - _sh.setDisplayGridlines(show); - } - - /** - * Returns if gridlines are displayed - * - * @return whether gridlines are displayed - */ - @Override - public boolean isDisplayGridlines() - { - return _sh.isDisplayGridlines(); - } - - /** - * Sets whether the formulas are shown in a viewer - * - * @param show whether to show formulas or not - */ - @Override - public void setDisplayFormulas(boolean show) - { - _sh.setDisplayFormulas(show); - } - - /** - * Returns if formulas are displayed - * - * @return whether formulas are displayed - */ - @Override - public boolean isDisplayFormulas() - { - return _sh.isDisplayFormulas(); - } - - /** - * Sets whether the RowColHeadings are shown in a viewer - * - * @param show whether to show RowColHeadings or not - */ - @Override - public void setDisplayRowColHeadings(boolean show) - { - _sh.setDisplayRowColHeadings(show); - } - - /** - * Returns if RowColHeadings are displayed. - * @return whether RowColHeadings are displayed - */ - @Override - public boolean isDisplayRowColHeadings() - { - return _sh.isDisplayRowColHeadings(); - } - - /** - * Sets a page break at the indicated row - * @param row FIXME: Document this! - */ - @Override - public void setRowBreak(int row) - { - _sh.setRowBreak(row); - } - - /** - * Determines if there is a page break at the indicated row - * @param row FIXME: Document this! - * @return FIXME: Document this! - */ - @Override - public boolean isRowBroken(int row) - { - return _sh.isRowBroken(row); - } - - /** - * Removes the page break at the indicated row - * @param row - */ - @Override - public void removeRowBreak(int row) - { - _sh.removeRowBreak(row); - } - - /** - * Retrieves all the horizontal page breaks - * @return all the horizontal page breaks, or null if there are no row page breaks - */ - @Override - public int[] getRowBreaks() - { - return _sh.getRowBreaks(); - } - - /** - * Retrieves all the vertical page breaks - * @return all the vertical page breaks, or null if there are no column page breaks - */ - @Override - public int[] getColumnBreaks() - { - return _sh.getColumnBreaks(); - } - - /** - * Sets a page break at the indicated column - * @param column - */ - @Override - public void setColumnBreak(int column) - { - _sh.setColumnBreak(column); - } - - /** - * Determines if there is a page break at the indicated column - * @param column FIXME: Document this! - * @return FIXME: Document this! - */ - @Override - public boolean isColumnBroken(int column) - { - return _sh.isColumnBroken(column); - } - - /** - * Removes a page break at the indicated column - * @param column - */ - @Override - public void removeColumnBreak(int column) - { - _sh.removeColumnBreak(column); - } - - /** - * Expands or collapses a column group. - * - * @param columnNumber One of the columns in the group. - * @param collapsed true = collapse group, false = expand group. - */ - @Override - public void setColumnGroupCollapsed(int columnNumber, boolean collapsed) - { - _sh.setColumnGroupCollapsed(columnNumber, collapsed); - } - - /** - * Create an outline for the provided column range. - * - * @param fromColumn beginning of the column range. - * @param toColumn end of the column range. - */ - @Override - public void groupColumn(int fromColumn, int toColumn) - { - _sh.groupColumn(fromColumn,toColumn); - } - - /** - * Ungroup a range of columns that were previously groupped - * - * @param fromColumn start column (0-based) - * @param toColumn end column (0-based) - */ - @Override - public void ungroupColumn(int fromColumn, int toColumn) - { - _sh.ungroupColumn(fromColumn, toColumn); - } - - /** - * Tie a range of rows together so that they can be collapsed or expanded - * - *

    - * Please note the rows being grouped must be in the current window, - * if the rows are already flushed then groupRow has no effect. - *

    - * - * Correct code: - *
    
    -     *       Workbook wb = new SXSSFWorkbook(100);  // keep 100 rows in memory
    -     *       Sheet sh = wb.createSheet();
    -     *       for (int rownum = 0; rownum < 1000; rownum++) {
    -     *           Row row = sh.createRow(rownum);
    -     *           if(rownum == 200)  {
    -     *               sh.groupRow(100, 200);
    -     *           }
    -     *       }
    -     *
    -     *      
    - * - * - * Incorrect code: - *
    
    -     *       Workbook wb = new SXSSFWorkbook(100);  // keep 100 rows in memory
    -     *       Sheet sh = wb.createSheet();
    -     *       for (int rownum = 0; rownum < 1000; rownum++) {
    -     *           Row row = sh.createRow(rownum);
    -     *       }
    -     *       sh.groupRow(100, 200); // the rows in the range [100, 200] are already flushed and groupRows has no effect
    -     *
    -     *      
    - * - * - * @param fromRow start row (0-based) - * @param toRow end row (0-based) - */ - @Override - public void groupRow(int fromRow, int toRow) - { - for(SXSSFRow row : _rows.subMap(fromRow, toRow + 1).values()){ - int level = row.getOutlineLevel() + 1; - row.setOutlineLevel(level); - - if(level > outlineLevelRow) { - outlineLevelRow = level; - } - } - - setWorksheetOutlineLevelRow(); - } - - /** - * Set row groupings (like groupRow) in a stream-friendly manner - * - *

    - * groupRows requires all rows in the group to be in the current window. - * This is not always practical. Instead use setRowOutlineLevel to - * explicitly set the group level. Level 1 is the top level group, - * followed by 2, etc. It is up to the user to ensure that level 2 - * groups are correctly nested under level 1, etc. - *

    - * - * @param rownum index of row to update (0-based) - * @param level outline level (greater than 0) - */ - public void setRowOutlineLevel(int rownum, int level) - { - SXSSFRow row = _rows.get(rownum); - row.setOutlineLevel(level); - if(level > 0 && level > outlineLevelRow) { - outlineLevelRow = level; - setWorksheetOutlineLevelRow(); - } - } - - private void setWorksheetOutlineLevelRow() { - CTWorksheet ct = _sh.getCTWorksheet(); - CTSheetFormatPr pr = ct.isSetSheetFormatPr() ? - ct.getSheetFormatPr() : - ct.addNewSheetFormatPr(); - if(outlineLevelRow > 0) { - pr.setOutlineLevelRow((short)outlineLevelRow); - } - } - - /** - * Ungroup a range of rows that were previously groupped - * - * @param fromRow start row (0-based) - * @param toRow end row (0-based) - */ - @Override - public void ungroupRow(int fromRow, int toRow) - { - _sh.ungroupRow(fromRow, toRow); - } - - /** - * Set view state of a grouped range of rows. - * - * Not implemented for expanding (i.e. collapse == false) - * - * @param row start row of a groupped range of rows (0-based) - * @param collapse whether to expand/collapse the detail rows - * @throws RuntimeException if collapse is false as this is not implemented for SXSSF. - */ - @Override - public void setRowGroupCollapsed(int row, boolean collapse) - { - if (collapse) { - collapseRow(row); - } else { - //expandRow(rowIndex); - throw new RuntimeException("Unable to expand row: Not Implemented"); - } - } - - /** - * @param rowIndex the zero based row index to collapse - */ - private void collapseRow(int rowIndex) { - SXSSFRow row = getRow(rowIndex); - if(row == null) { - throw new IllegalArgumentException("Invalid row number("+ rowIndex + "). Row does not exist."); - } else { - int startRow = findStartOfRowOutlineGroup(rowIndex); - - // Hide all the columns until the end of the group - int lastRow = writeHidden(row, startRow, true); - SXSSFRow lastRowObj = getRow(lastRow); - if (lastRowObj != null) { - lastRowObj.setCollapsed(true); - } else { - SXSSFRow newRow = createRow(lastRow); - newRow.setCollapsed(true); - } - } - } - - /** - * @param rowIndex the zero based row index to find from - */ - private int findStartOfRowOutlineGroup(int rowIndex) { - // Find the start of the group. - Row row = getRow(rowIndex); - int level = ((SXSSFRow) row).getOutlineLevel(); - if(level == 0) { - throw new IllegalArgumentException("Outline level is zero for the row (" + rowIndex + ")."); - } - int currentRow = rowIndex; - while (getRow(currentRow) != null) { - if (getRow(currentRow).getOutlineLevel() < level) { - return currentRow + 1; - } - currentRow--; - } - return currentRow + 1; - } - - private int writeHidden(SXSSFRow xRow, int rowIndex, boolean hidden) { - int level = xRow.getOutlineLevel(); - SXSSFRow currRow = getRow(rowIndex); - - while (currRow != null && currRow.getOutlineLevel() >= level) { - currRow.setHidden(hidden); - rowIndex++; - currRow = getRow(rowIndex); - } - return rowIndex; - } - - /** - * Sets the default column style for a given column. POI will only apply this style to new cells added to the sheet. - * - * @param column the column index - * @param style the style to set - */ - @Override - public void setDefaultColumnStyle(int column, CellStyle style) - { - _sh.setDefaultColumnStyle(column, style); - } - - - /** - * Track a column in the sheet for auto-sizing. - * Note this has undefined behavior if a column is tracked after one or more rows are written to the sheet. - * If column is already tracked, this call does nothing. - * - * @param column the column to track for auto-sizing - * @since 3.14beta1 - * @see #trackColumnsForAutoSizing(Collection) - * @see #trackAllColumnsForAutoSizing() - */ - public void trackColumnForAutoSizing(int column) - { - _autoSizeColumnTracker.trackColumn(column); - } - - /** - * Track several columns in the sheet for auto-sizing. - * Note this has undefined behavior if columns are tracked after one or more rows are written to the sheet. - * Any column in columns that are already tracked are ignored by this call. - * - * @param columns the columns to track for auto-sizing - * @since 3.14beta1 - */ - public void trackColumnsForAutoSizing(Collection columns) - { - _autoSizeColumnTracker.trackColumns(columns); - } - - /** - * Tracks all columns in the sheet for auto-sizing. If this is called, individual columns do not need to be tracked. - * Because determining the best-fit width for a cell is expensive, this may affect the performance. - * @since 3.14beta1 - */ - public void trackAllColumnsForAutoSizing() - { - _autoSizeColumnTracker.trackAllColumns(); - } - - /** - * Removes a column that was previously marked for inclusion in auto-size column tracking. - * When a column is untracked, the best-fit width is forgotten. - * If column is not tracked, it will be ignored by this call. - * - * @param column the index of the column to track for auto-sizing - * @return true if column was tracked prior to this call, false if no action was taken - * @since 3.14beta1 - * @see #untrackColumnsForAutoSizing(Collection) - * @see #untrackAllColumnsForAutoSizing() - */ - public boolean untrackColumnForAutoSizing(int column) - { - return _autoSizeColumnTracker.untrackColumn(column); - } - - /** - * Untracks several columns in the sheet for auto-sizing. - * When a column is untracked, the best-fit width is forgotten. - * Any column in columns that is not tracked will be ignored by this call. - * - * @param columns the indices of the columns to track for auto-sizing - * @return true if one or more columns were untracked as a result of this call - * @since 3.14beta1 - */ - public boolean untrackColumnsForAutoSizing(Collection columns) - { - return _autoSizeColumnTracker.untrackColumns(columns); - } - - /** - * Untracks all columns in the sheet for auto-sizing. Best-fit column widths are forgotten. - * If this is called, individual columns do not need to be untracked. - * @since 3.14beta1 - */ - public void untrackAllColumnsForAutoSizing() - { - _autoSizeColumnTracker.untrackAllColumns(); - } - - /** - * Returns true if column is currently tracked for auto-sizing. - * - * @param column the index of the column to check - * @return true if column is tracked - * @since 3.14beta1 - */ - public boolean isColumnTrackedForAutoSizing(int column) - { - return _autoSizeColumnTracker.isColumnTracked(column); - } - - /** - * Get the currently tracked columns for auto-sizing. - * Note if all columns are tracked, this will only return the columns that have been explicitly or implicitly tracked, - * which is probably only columns containing 1 or more non-blank values - * - * @return a set of the indices of all tracked columns - * @since 3.14beta1 - */ - public Set getTrackedColumnsForAutoSizing() - { - return _autoSizeColumnTracker.getTrackedColumns(); - } - - /** - * Adjusts the column width to fit the contents. - * - *

    - * This process can be relatively slow on large sheets, so this should - * normally only be called once per column, at the end of your - * processing. - *

    - * You can specify whether the content of merged cells should be considered or ignored. - * Default is to ignore merged cells. - * - *

    - * Special note about SXSSF implementation: You must register the columns you wish to track with - * the SXSSFSheet using {@link #trackColumnForAutoSizing(int)} or {@link #trackAllColumnsForAutoSizing()}. - * This is needed because the rows needed to compute the column width may have fallen outside the - * random access window and been flushed to disk. - * Tracking columns is required even if all rows are in the random access window. - *

    - *

    New in POI 3.14 beta 1: auto-sizes columns using cells from current and flushed rows.

    - * - * @param column the column index to auto-size - */ - @Override - public void autoSizeColumn(int column) - { - autoSizeColumn(column, false); - } - - /** - * Adjusts the column width to fit the contents. - *

    - * This process can be relatively slow on large sheets, so this should - * normally only be called once per column, at the end of your - * processing. - *

    - * You can specify whether the content of merged cells should be considered or ignored. - * Default is to ignore merged cells. - * - *

    - * Special note about SXSSF implementation: You must register the columns you wish to track with - * the SXSSFSheet using {@link #trackColumnForAutoSizing(int)} or {@link #trackAllColumnsForAutoSizing()}. - * This is needed because the rows needed to compute the column width may have fallen outside the - * random access window and been flushed to disk. - * Tracking columns is required even if all rows are in the random access window. - *

    - *

    New in POI 3.14 beta 1: auto-sizes columns using cells from current and flushed rows.

    - * - * @param column the column index to auto-size - * @param useMergedCells whether to use the contents of merged cells when calculating the width of the column - */ - @Override - public void autoSizeColumn(int column, boolean useMergedCells) - { - // Multiple calls to autoSizeColumn need to look up the best-fit width - // of rows already flushed to disk plus re-calculate the best-fit width - // of rows in the current window. It isn't safe to update the column - // widths before flushing to disk because columns in the random access - // window rows may change in best-fit width. The best-fit width of a cell - // is only fixed when it becomes inaccessible for modification. - // Changes to the shared strings table, styles table, or formulas might - // be able to invalidate the auto-size width without the opportunity - // to recalculate the best-fit width for the flushed rows. This is an - // inherent limitation of SXSSF. If having correct auto-sizing is - // critical, the flushed rows would need to be re-read by the read-only - // XSSF eventmodel (SAX) or the memory-heavy XSSF usermodel (DOM). - final int flushedWidth; - try { - // get the best fit width of rows already flushed to disk - flushedWidth = _autoSizeColumnTracker.getBestFitColumnWidth(column, useMergedCells); - } - catch (final IllegalStateException e) { - throw new IllegalStateException("Could not auto-size column. Make sure the column was tracked prior to auto-sizing the column.", e); - } - - // get the best-fit width of rows currently in the random access window - final int activeWidth = (int) (256 * SheetUtil.getColumnWidth(this, column, useMergedCells)); - - // the best-fit width for both flushed rows and random access window rows - // flushedWidth or activeWidth may be negative if column contains only blank cells - final int bestFitWidth = Math.max(flushedWidth, activeWidth); - - if (bestFitWidth > 0) { - final int maxColumnWidth = 255*256; // The maximum column width for an individual cell is 255 characters - final int width = Math.min(bestFitWidth, maxColumnWidth); - setColumnWidth(column, width); - } - } - - /** - * Returns cell comment for the specified row and column - * - * @return cell comment or null if not found - * @deprecated as of 2015-11-23 (circa POI 3.14beta1). Use {@link #getCellComment(CellAddress)} instead. - */ - @Deprecated - @Removal(version="3.16") - @Override - public XSSFComment getCellComment(int row, int column) - { - return getCellComment(new CellAddress(row, column)); - } - - /** - * Returns cell comment for the specified row and column - * - * @return cell comment or null if not found - */ - @Override - public XSSFComment getCellComment(CellAddress ref) - { - return _sh.getCellComment(ref); - } - - /** - * Returns all cell comments on this sheet. - * @return A map of each Comment in the sheet, keyed on the cell address where - * the comment is located. - */ - @Override - public Map getCellComments() { - return _sh.getCellComments(); - } - - /** - * Get a Hyperlink in this sheet anchored at row, column - * - * @param row - * @param column - * @return hyperlink if there is a hyperlink anchored at row, column; otherwise returns null - */ - @Override - public XSSFHyperlink getHyperlink(int row, int column) { - return _sh.getHyperlink(row, column); - } - - /** - * Get a Hyperlink in this sheet located in a cell specified by {code addr} - * - * @param addr The address of the cell containing the hyperlink - * @return hyperlink if there is a hyperlink anchored at {@code addr}; otherwise returns {@code null} - * @since POI 3.15 beta 3 - */ - @Override - public XSSFHyperlink getHyperlink(CellAddress addr) { - return _sh.getHyperlink(addr); - } - - /** - * Get a list of Hyperlinks in this sheet - * - * @return Hyperlinks for the sheet - */ - @Override - public List getHyperlinkList() { - return _sh.getHyperlinkList(); - } - - /** - * {@inheritDoc} - */ - @Override - public XSSFDrawing getDrawingPatriarch() - { - return _sh.getDrawingPatriarch(); - } - - /** - * Creates the top-level drawing patriarch. - * - * @return The new drawing patriarch. - */ - @Override - public SXSSFDrawing createDrawingPatriarch() - { - return new SXSSFDrawing(getWorkbook(), _sh.createDrawingPatriarch()); - } - - - /** - * Return the parent workbook - * - * @return the parent workbook - */ - @Override - public SXSSFWorkbook getWorkbook() - { - return _workbook; - } - - /** - * Returns the name of this sheet - * - * @return the name of this sheet - */ - @Override - public String getSheetName() - { - return _sh.getSheetName(); - } - - /** - * Note - this is not the same as whether the sheet is focused (isActive) - * @return true if this sheet is currently selected - */ - @Override - public boolean isSelected() - { - return _sh.isSelected(); - } - - - /** - * Sets array formula to specified region for result. - * - * @param formula text representation of the formula - * @param range Region of array formula for result. - * @return the {@link CellRange} of cells affected by this change - */ - @Override - public CellRange setArrayFormula(String formula, CellRangeAddress range) - { - return _sh.setArrayFormula(formula, range); - } - - /** - * Remove a Array Formula from this sheet. All cells contained in the Array Formula range are removed as well - * - * @param cell any cell within Array Formula range - * @return the {@link CellRange} of cells affected by this change - */ - @Override - public CellRange removeArrayFormula(Cell cell) - { - return _sh.removeArrayFormula(cell); - } - - @Override - public DataValidationHelper getDataValidationHelper() - { - return _sh.getDataValidationHelper(); - } - - @Override - public List getDataValidations() - { - return _sh.getDataValidations(); - } - - /** - * Creates a data validation object - * @param dataValidation The Data validation object settings - */ - @Override - public void addValidationData(DataValidation dataValidation) - { - _sh.addValidationData(dataValidation); - } - - /** - * Enable filtering for a range of cells - * - * @param range the range of cells to filter - */ - @Override - public AutoFilter setAutoFilter(CellRangeAddress range) - { - return _sh.setAutoFilter(range); - } - - @Override - public SheetConditionalFormatting getSheetConditionalFormatting(){ - return _sh.getSheetConditionalFormatting(); - } - - - @Override - public CellRangeAddress getRepeatingRows() { - return _sh.getRepeatingRows(); - } - - @Override - public CellRangeAddress getRepeatingColumns() { - return _sh.getRepeatingColumns(); - } - - @Override - public void setRepeatingRows(CellRangeAddress rowRangeRef) { - _sh.setRepeatingRows(rowRangeRef); - } - - @Override - public void setRepeatingColumns(CellRangeAddress columnRangeRef) { - _sh.setRepeatingColumns(columnRangeRef); - } - - - -//end of interface implementation - /** - * Specifies how many rows can be accessed at most via getRow(). - * When a new node is created via createRow() and the total number - * of unflushed records would exeed the specified value, then the - * row with the lowest index value is flushed and cannot be accessed - * via getRow() anymore. - * A value of -1 indicates unlimited access. In this case all - * records that have not been flushed by a call to flush() are available - * for random access. - * A value of 0 is not allowed because it would flush any newly created row - * without having a chance to specify any cells. - */ - public void setRandomAccessWindowSize(int value) - { - if(value == 0 || value < -1) { - throw new IllegalArgumentException("RandomAccessWindowSize must be either -1 or a positive integer"); - } - _randomAccessWindowSize=value; - } - - /** - * Are all rows flushed to disk? - */ - public boolean areAllRowsFlushed() { - return allFlushed; - } - /** - * @return Last row number to be flushed to disk, or -1 if none flushed yet - */ - public int getLastFlushedRowNum() { - return lastFlushedRowNumber; - } - - /** - * Specifies how many rows can be accessed at most via getRow(). - * The exeeding rows (if any) are flushed to the disk while rows - * with lower index values are flushed first. - */ - public void flushRows(int remaining) throws IOException - { - while(_rows.size() > remaining) { - flushOneRow(); - } - if (remaining == 0) { - allFlushed = true; - } - } - - /** - * Flush all rows to disk. After this call no rows can be accessed via getRow() - * - * @throws IOException - */ - public void flushRows() throws IOException - { - this.flushRows(0); - } - - private void flushOneRow() throws IOException - { - Integer firstRowNum = _rows.firstKey(); - if (firstRowNum!=null) { - int rowIndex = firstRowNum.intValue(); - SXSSFRow row = _rows.get(firstRowNum); - // Update the best fit column widths for auto-sizing just before the rows are flushed - _autoSizeColumnTracker.updateColumnWidths(row); - _writer.writeRow(rowIndex, row); - _rows.remove(firstRowNum); - lastFlushedRowNumber = rowIndex; - } - } - public void changeRowNum(SXSSFRow row, int newRowNum) - { - - removeRow(row); - _rows.put(newRowNum,row); - } - - public int getRowNum(SXSSFRow row) - { - for(Iterator> iter=_rows.entrySet().iterator();iter.hasNext();) - { - Map.Entry entry=iter.next(); - if(entry.getValue()==row) { - return entry.getKey().intValue(); - } - } - return -1; - } - - /** - * Deletes the temporary file that backed this sheet on disk. - * @return true if the file was deleted, false if it wasn't. - */ - boolean dispose() throws IOException { - if (!allFlushed) { - flushRows(); - } - return _writer.dispose(); - } - - @Override - public int getColumnOutlineLevel(int columnIndex) { - return _sh.getColumnOutlineLevel(columnIndex); - } - - /** - * {@inheritDoc} - */ - @Override - public CellAddress getActiveCell() { - return _sh.getActiveCell(); - } - - /** - * {@inheritDoc} - */ - @Override - public void setActiveCell(CellAddress address) { - _sh.setActiveCell(address); - } - - public XSSFColor getTabColor() { - return _sh.getTabColor(); - } - - public void setTabColor(XSSFColor color) { - _sh.setTabColor(color); - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/streaming/SXSSFWorkbook.java b/src/ooxml/java/org/apache/poi/xssf/streaming/SXSSFWorkbook.java deleted file mode 100644 index a5935e60f..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/streaming/SXSSFWorkbook.java +++ /dev/null @@ -1,1389 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.streaming; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; -import java.util.zip.ZipOutputStream; - -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.util.ZipEntrySource; -import org.apache.poi.openxml4j.util.ZipFileZipEntrySource; -import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.ss.formula.udf.UDFFinder; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.CreationHelper; -import org.apache.poi.ss.usermodel.DataFormat; -import org.apache.poi.ss.usermodel.Font; -import org.apache.poi.ss.usermodel.Name; -import org.apache.poi.ss.usermodel.PictureData; -import org.apache.poi.ss.usermodel.Row.MissingCellPolicy; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.SheetVisibility; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.Internal; -import org.apache.poi.util.NotImplemented; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.util.Removal; -import org.apache.poi.util.TempFile; -import org.apache.poi.xssf.model.SharedStringsTable; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -/** - * Streaming version of XSSFWorkbook implementing the "BigGridDemo" strategy. - * - * This allows to write very large files without running out of memory as only - * a configurable portion of the rows are kept in memory at any one time. - * - * You can provide a template workbook which is used as basis for the written - * data. - * - * See https://poi.apache.org/spreadsheet/how-to.html#sxssf for details. - * - * Please note that there are still things that still may consume a large - * amount of memory based on which features you are using, e.g. merged regions, - * comments, ... are still only stored in memory and thus may require a lot of - * memory if used extensively. - * - * SXSSFWorkbook defaults to using inline strings instead of a shared strings - * table. This is very efficient, since no document content needs to be kept in - * memory, but is also known to produce documents that are incompatible with - * some clients. With shared strings enabled all unique strings in the document - * has to be kept in memory. Depending on your document content this could use - * a lot more resources than with shared strings disabled. - * - * Carefully review your memory budget and compatibility needs before deciding - * whether to enable shared strings or not. - */ -public class SXSSFWorkbook implements Workbook { - /** - * Specifies how many rows can be accessed at most via {@link SXSSFSheet#getRow}. - * When a new node is created via {@link SXSSFSheet#createRow} and the total number - * of unflushed records would exceed the specified value, then the - * row with the lowest index value is flushed and cannot be accessed - * via {@link SXSSFSheet#getRow} anymore. - */ - public static final int DEFAULT_WINDOW_SIZE = 100; - private static final POILogger logger = POILogFactory.getLogger(SXSSFWorkbook.class); - - private final XSSFWorkbook _wb; - - private final Map _sxFromXHash = new HashMap(); - private final Map _xFromSxHash = new HashMap(); - - private int _randomAccessWindowSize = DEFAULT_WINDOW_SIZE; - - /** - * whether temp files should be compressed. - */ - private boolean _compressTmpFiles; - - /** - * shared string table - a cache of strings in this workbook - */ - private final SharedStringsTable _sharedStringSource; - - /** - * Construct a new workbook with default row window size - */ - public SXSSFWorkbook(){ - this(null /*workbook*/); - } - - /** - *

    Construct a workbook from a template.

    - * - * There are three use-cases to use SXSSFWorkbook(XSSFWorkbook) : - *
      - *
    1. - * Append new sheets to existing workbooks. You can open existing - * workbook from a file or create on the fly with XSSF. - *
    2. - *
    3. - * Append rows to existing sheets. The row number MUST be greater - * than {@code max(rownum)} in the template sheet. - *
    4. - *
    5. - * Use existing workbook as a template and re-use global objects such - * as cell styles, formats, images, etc. - *
    6. - *
    - * All three use cases can work in a combination. - * - * What is not supported: - *
      - *
    • - * Access initial cells and rows in the template. After constructing - * {@link #SXSSFWorkbook(XSSFWorkbook)} all internal windows are empty and - * {@link SXSSFSheet#getRow} and {@link SXSSFRow#getCell} return null. - *
    • - *
    • - * Override existing cells and rows. The API silently allows that but - * the output file is invalid and Excel cannot read it. - *
    • - *
    - * - * @param workbook the template workbook - */ - public SXSSFWorkbook(XSSFWorkbook workbook){ - this(workbook, DEFAULT_WINDOW_SIZE); - } - - - /** - * Constructs an workbook from an existing workbook. - *

    - * When a new node is created via {@link SXSSFSheet#createRow} and the total number - * of unflushed records would exceed the specified value, then the - * row with the lowest index value is flushed and cannot be accessed - * via {@link SXSSFSheet#getRow} anymore. - *

    - *

    - * A value of -1 indicates unlimited access. In this case all - * records that have not been flushed by a call to flush() are available - * for random access. - *

    - *

    - * A value of 0 is not allowed because it would flush any newly created row - * without having a chance to specify any cells. - *

    - * - * @param rowAccessWindowSize the number of rows that are kept in memory until flushed out, see above. - */ - public SXSSFWorkbook(XSSFWorkbook workbook, int rowAccessWindowSize){ - this(workbook,rowAccessWindowSize, false); - } - - /** - * Constructs an workbook from an existing workbook. - *

    - * When a new node is created via {@link SXSSFSheet#createRow} and the total number - * of unflushed records would exceed the specified value, then the - * row with the lowest index value is flushed and cannot be accessed - * via {@link SXSSFSheet#getRow} anymore. - *

    - *

    - * A value of -1 indicates unlimited access. In this case all - * records that have not been flushed by a call to flush() are available - * for random access. - *

    - *

    - * A value of 0 is not allowed because it would flush any newly created row - * without having a chance to specify any cells. - *

    - * - * @param rowAccessWindowSize the number of rows that are kept in memory until flushed out, see above. - * @param compressTmpFiles whether to use gzip compression for temporary files - */ - public SXSSFWorkbook(XSSFWorkbook workbook, int rowAccessWindowSize, boolean compressTmpFiles){ - this(workbook,rowAccessWindowSize, compressTmpFiles, false); - } - - /** - * Constructs an workbook from an existing workbook. - *

    - * When a new node is created via {@link SXSSFSheet#createRow} and the total number - * of unflushed records would exceed the specified value, then the - * row with the lowest index value is flushed and cannot be accessed - * via {@link SXSSFSheet#getRow} anymore. - *

    - *

    - * A value of -1 indicates unlimited access. In this case all - * records that have not been flushed by a call to flush() are available - * for random access. - *

    - *

    - * A value of 0 is not allowed because it would flush any newly created row - * without having a chance to specify any cells. - *

    - * - * @param workbook the template workbook - * @param rowAccessWindowSize the number of rows that are kept in memory until flushed out, see above. - * @param compressTmpFiles whether to use gzip compression for temporary files - * @param useSharedStringsTable whether to use a shared strings table - */ - public SXSSFWorkbook(XSSFWorkbook workbook, int rowAccessWindowSize, boolean compressTmpFiles, boolean useSharedStringsTable){ - setRandomAccessWindowSize(rowAccessWindowSize); - setCompressTempFiles(compressTmpFiles); - if (workbook == null) { - _wb=new XSSFWorkbook(); - _sharedStringSource = useSharedStringsTable ? _wb.getSharedStringSource() : null; - } else { - _wb=workbook; - _sharedStringSource = useSharedStringsTable ? _wb.getSharedStringSource() : null; - for ( Sheet sheet : _wb ) { - createAndRegisterSXSSFSheet( (XSSFSheet)sheet ); - } - } - } - /** - * Construct an empty workbook and specify the window for row access. - *

    - * When a new node is created via {@link SXSSFSheet#createRow} and the total number - * of unflushed records would exceed the specified value, then the - * row with the lowest index value is flushed and cannot be accessed - * via {@link SXSSFSheet#getRow} anymore. - *

    - *

    - * A value of -1 indicates unlimited access. In this case all - * records that have not been flushed by a call to flush() are available - * for random access. - *

    - *

    - * A value of 0 is not allowed because it would flush any newly created row - * without having a chance to specify any cells. - *

    - * - * @param rowAccessWindowSize the number of rows that are kept in memory until flushed out, see above. - */ - public SXSSFWorkbook(int rowAccessWindowSize){ - this(null /*workbook*/, rowAccessWindowSize); - } - - /** - * See the constructors for a more detailed description of the sliding window of rows. - * - * @return The number of rows that are kept in memory at once before flushing them out. - */ - public int getRandomAccessWindowSize() { - return _randomAccessWindowSize; - } - - private void setRandomAccessWindowSize(int rowAccessWindowSize) { - if(rowAccessWindowSize == 0 || rowAccessWindowSize < -1) { - throw new IllegalArgumentException("rowAccessWindowSize must be greater than 0 or -1"); - } - _randomAccessWindowSize = rowAccessWindowSize; - } - - /** - * Get whether temp files should be compressed. - * - * @return whether to compress temp files - */ - public boolean isCompressTempFiles() { - return _compressTmpFiles; - } - /** - * Set whether temp files should be compressed. - *

    - * SXSSF writes sheet data in temporary files (a temp file per-sheet) - * and the size of these temp files can grow to to a very large size, - * e.g. for a 20 MB csv data the size of the temp xml file become few GB large. - * If the "compress" flag is set to true then the temporary XML is gzipped. - *

    - *

    - * Please note the the "compress" option may cause performance penalty. - *

    - * @param compress whether to compress temp files - */ - public void setCompressTempFiles(boolean compress) { - _compressTmpFiles = compress; - } - - @Internal - protected SharedStringsTable getSharedStringSource() { - return _sharedStringSource; - } - - protected SheetDataWriter createSheetDataWriter() throws IOException { - if(_compressTmpFiles) { - return new GZIPSheetDataWriter(_sharedStringSource); - } - - return new SheetDataWriter(_sharedStringSource); - } - - XSSFSheet getXSSFSheet(SXSSFSheet sheet) - { - return _sxFromXHash.get(sheet); - } - - SXSSFSheet getSXSSFSheet(XSSFSheet sheet) - { - return _xFromSxHash.get(sheet); - } - - void registerSheetMapping(SXSSFSheet sxSheet,XSSFSheet xSheet) - { - _sxFromXHash.put(sxSheet,xSheet); - _xFromSxHash.put(xSheet,sxSheet); - } - - void deregisterSheetMapping(XSSFSheet xSheet) - { - SXSSFSheet sxSheet=getSXSSFSheet(xSheet); - - // ensure that the writer is closed in all cases to not have lingering writers - try { - sxSheet.getSheetDataWriter().close(); - } catch (IOException e) { - // ignore exception here - } - - _sxFromXHash.remove(sxSheet); - - _xFromSxHash.remove(xSheet); - } - - private XSSFSheet getSheetFromZipEntryName(String sheetRef) - { - for(XSSFSheet sheet : _sxFromXHash.values()) - { - if(sheetRef.equals(sheet.getPackagePart().getPartName().getName().substring(1))) { - return sheet; - } - } - return null; - } - - protected void injectData(ZipEntrySource zipEntrySource, OutputStream out) throws IOException { - try { - ZipOutputStream zos = new ZipOutputStream(out); - try { - Enumeration en = zipEntrySource.getEntries(); - while (en.hasMoreElements()) { - ZipEntry ze = en.nextElement(); - zos.putNextEntry(new ZipEntry(ze.getName())); - InputStream is = zipEntrySource.getInputStream(ze); - XSSFSheet xSheet=getSheetFromZipEntryName(ze.getName()); - if(xSheet!=null) { - SXSSFSheet sxSheet=getSXSSFSheet(xSheet); - InputStream xis = sxSheet.getWorksheetXMLInputStream(); - try { - copyStreamAndInjectWorksheet(is,zos,xis); - } finally { - xis.close(); - } - } else { - IOUtils.copy(is, zos); - } - is.close(); - } - } finally { - zos.close(); - } - } finally { - zipEntrySource.close(); - } - } - - private static void copyStreamAndInjectWorksheet(InputStream in, OutputStream out, InputStream worksheetData) throws IOException { - InputStreamReader inReader=new InputStreamReader(in,"UTF-8"); //TODO: Is it always UTF-8 or do we need to read the xml encoding declaration in the file? If not, we should perhaps use a SAX reader instead. - OutputStreamWriter outWriter=new OutputStreamWriter(out,"UTF-8"); - boolean needsStartTag = true; - int c; - int pos=0; - String s="" or "
    " (excluding). - while(((c=inReader.read())!=-1)) - { - if(c==s.charAt(pos)) - { - pos++; - if(pos==n) - { - if ("') - { - // Found - outWriter.write(s); - outWriter.write(c); - s = ""; - n = s.length(); - pos = 0; - needsStartTag = false; - continue; - } - if (c == '/') - { - // Found ') - { - // Found - break; - } - - outWriter.write(s); - outWriter.write('/'); - outWriter.write(c); - pos = 0; - continue; - } - - outWriter.write(s); - outWriter.write('/'); - outWriter.write(c); - pos = 0; - continue; - } - else - { - // Found - break; - } - } - } - else - { - if(pos>0) { - outWriter.write(s,0,pos); - } - if(c==s.charAt(0)) - { - pos=1; - } - else - { - outWriter.write(c); - pos=0; - } - } - } - outWriter.flush(); - if (needsStartTag) - { - outWriter.write("\n"); - outWriter.flush(); - } - //Copy the worksheet data to "out". - IOUtils.copy(worksheetData,out); - outWriter.write(""); - outWriter.flush(); - //Copy the rest of "in" to "out". - while(((c=inReader.read())!=-1)) { - outWriter.write(c); - } - outWriter.flush(); - } - - public XSSFWorkbook getXSSFWorkbook() - { - return _wb; - } - -//start of interface implementation - - /** - * Convenience method to get the active sheet. The active sheet is is the sheet - * which is currently displayed when the workbook is viewed in Excel. - * 'Selected' sheet(s) is a distinct concept. - * - * @return the index of the active sheet (0-based) - */ - @Override - public int getActiveSheetIndex() - { - return _wb.getActiveSheetIndex(); - } - - /** - * Convenience method to set the active sheet. The active sheet is is the sheet - * which is currently displayed when the workbook is viewed in Excel. - * 'Selected' sheet(s) is a distinct concept. - * - * @param sheetIndex index of the active sheet (0-based) - */ - @Override - public void setActiveSheet(int sheetIndex) - { - _wb.setActiveSheet(sheetIndex); - } - - /** - * Gets the first tab that is displayed in the list of tabs in excel. - * - * @return the first tab that to display in the list of tabs (0-based). - */ - @Override - public int getFirstVisibleTab() - { - return _wb.getFirstVisibleTab(); - } - - /** - * Sets the first tab that is displayed in the list of tabs in excel. - * - * @param sheetIndex the first tab that to display in the list of tabs (0-based) - */ - @Override - public void setFirstVisibleTab(int sheetIndex) - { - _wb.setFirstVisibleTab(sheetIndex); - } - - /** - * Sets the order of appearance for a given sheet. - * - * @param sheetname the name of the sheet to reorder - * @param pos the position that we want to insert the sheet into (0 based) - */ - @Override - public void setSheetOrder(String sheetname, int pos) - { - _wb.setSheetOrder(sheetname,pos); - } - - /** - * Sets the tab whose data is actually seen when the sheet is opened. - * This may be different from the "selected sheet" since excel seems to - * allow you to show the data of one sheet when another is seen "selected" - * in the tabs (at the bottom). - * - * @see Sheet#setSelected(boolean) - * @param index the index of the sheet to select (0 based) - */ - @Override - public void setSelectedTab(int index) - { - _wb.setSelectedTab(index); - } - - /** - * Set the sheet name. - * - * @param sheet number (0 based) - * @throws IllegalArgumentException if the name is greater than 31 chars or contains /\?*[] - */ - @Override - public void setSheetName(int sheet, String name) - { - _wb.setSheetName(sheet,name); - } - - /** - * Set the sheet name - * - * @param sheet sheet number (0 based) - * @return Sheet name - */ - @Override - public String getSheetName(int sheet) - { - return _wb.getSheetName(sheet); - } - - /** - * Returns the index of the sheet by his name - * - * @param name the sheet name - * @return index of the sheet (0 based) - */ - @Override - public int getSheetIndex(String name) - { - return _wb.getSheetIndex(name); - } - - /** - * Returns the index of the given sheet - * - * @param sheet the sheet to look up - * @return index of the sheet (0 based) - */ - @Override - public int getSheetIndex(Sheet sheet) - { - return _wb.getSheetIndex(getXSSFSheet((SXSSFSheet)sheet)); - } - - /** - * Sreate an Sheet for this Workbook, adds it to the sheets and returns - * the high level representation. Use this to create new sheets. - * - * @return Sheet representing the new sheet. - */ - @Override - public SXSSFSheet createSheet() - { - return createAndRegisterSXSSFSheet(_wb.createSheet()); - } - - SXSSFSheet createAndRegisterSXSSFSheet(XSSFSheet xSheet) - { - final SXSSFSheet sxSheet; - try - { - sxSheet=new SXSSFSheet(this,xSheet); - } - catch (IOException ioe) - { - throw new RuntimeException(ioe); - } - registerSheetMapping(sxSheet,xSheet); - return sxSheet; - } - - /** - * Create an Sheet for this Workbook, adds it to the sheets and returns - * the high level representation. Use this to create new sheets. - * - * @param sheetname sheetname to set for the sheet. - * @return Sheet representing the new sheet. - * @throws IllegalArgumentException if the name is greater than 31 chars or contains /\?*[] - */ - @Override - public SXSSFSheet createSheet(String sheetname) - { - return createAndRegisterSXSSFSheet(_wb.createSheet(sheetname)); - } - - /** - * Not implemented for SXSSFWorkbook - * - * Create an Sheet from an existing sheet in the Workbook. - * - * @return Sheet representing the cloned sheet. - */ - @Override - @NotImplemented - public Sheet cloneSheet(int sheetNum) - { - throw new RuntimeException("NotImplemented"); - } - - - /** - * Get the number of spreadsheets in the workbook - * - * @return the number of sheets - */ - @Override - public int getNumberOfSheets() - { - return _wb.getNumberOfSheets(); - } - - /** - * Returns an iterator of the sheets in the workbook - * in sheet order. Includes hidden and very hidden sheets. - * - * @return an iterator of the sheets. - */ - @Override - public Iterator sheetIterator() { - return new SheetIterator(); - } - - private final class SheetIterator implements Iterator { - final private Iterator it; - @SuppressWarnings("unchecked") - public SheetIterator() { - it = (Iterator)(Iterator) _wb.iterator(); - } - @Override - public boolean hasNext() { - return it.hasNext(); - } - @Override - @SuppressWarnings("unchecked") - public T next() throws NoSuchElementException { - final XSSFSheet xssfSheet = it.next(); - return (T) getSXSSFSheet(xssfSheet); - } - /** - * Unexpected behavior may occur if sheets are reordered after iterator - * has been created. Support for the remove method may be added in the future - * if someone can figure out a reliable implementation. - */ - @Override - public void remove() throws IllegalStateException { - throw new UnsupportedOperationException("remove method not supported on XSSFWorkbook.iterator(). "+ - "Use Sheet.removeSheetAt(int) instead."); - } - } - - /** - * Alias for {@link #sheetIterator()} to allow - * foreach loops - */ - @Override - public Iterator iterator() { - return sheetIterator(); - } - - /** - * Get the Sheet object at the given index. - * - * @param index of the sheet number (0-based physical and logical) - * @return Sheet at the provided index - */ - @Override - public SXSSFSheet getSheetAt(int index) - { - return getSXSSFSheet(_wb.getSheetAt(index)); - } - - /** - * Get sheet with the given name - * - * @param name of the sheet - * @return Sheet with the name provided or null if it does not exist - */ - @Override - public SXSSFSheet getSheet(String name) - { - return getSXSSFSheet(_wb.getSheet(name)); - } - - /** - * Removes sheet at the given index - * - * @param index of the sheet to remove (0-based) - */ - @Override - public void removeSheetAt(int index) - { - // Get the sheet to be removed - XSSFSheet xSheet = _wb.getSheetAt(index); - SXSSFSheet sxSheet = getSXSSFSheet(xSheet); - - // De-register it - _wb.removeSheetAt(index); - deregisterSheetMapping(xSheet); - - // Clean up temporary resources - try { - sxSheet.dispose(); - } catch (IOException e) { - logger.log(POILogger.WARN, e); - } - } - - /** - * Create a new Font and add it to the workbook's font table - * - * @return new font object - */ - @Override - public Font createFont() - { - return _wb.createFont(); - } - - /** - * Finds a font that matches the one with the supplied attributes - * - * @return the font with the matched attributes or null - * @deprecated POI 3.15 beta 2. Use {@link #findFont(boolean, short, short, String, boolean, boolean, short, byte)} instead. - */ - @Deprecated - @Override - @Removal(version="3.17") - public Font findFont(short boldWeight, short color, short fontHeight, String name, boolean italic, boolean strikeout, short typeOffset, byte underline) - { - //noinspection deprecation - return _wb.findFont(boldWeight, color, fontHeight, name, italic, strikeout, typeOffset, underline); - } - - /** - * Finds a font that matches the one with the supplied attributes - * - * @return the font with the matched attributes or null - */ - @Override - public Font findFont(boolean bold, short color, short fontHeight, String name, boolean italic, boolean strikeout, short typeOffset, byte underline) - { - return _wb.findFont(bold, color, fontHeight, name, italic, strikeout, typeOffset, underline); - } - - - /** - * Get the number of fonts in the font table - * - * @return number of fonts - */ - @Override - public short getNumberOfFonts() - { - return _wb.getNumberOfFonts(); - } - - /** - * Get the font at the given index number - * - * @param idx index number (0-based) - * @return font at the index - */ - @Override - public Font getFontAt(short idx) - { - return _wb.getFontAt(idx); - } - - /** - * Create a new Cell style and add it to the workbook's style table - * - * @return the new Cell Style object - */ - @Override - public CellStyle createCellStyle() - { - return _wb.createCellStyle(); - } - - /** - * Get the number of styles the workbook contains - * - * @return count of cell styles - */ - @Override - public int getNumCellStyles() - { - return _wb.getNumCellStyles(); - } - - /** - * Get the cell style object at the given index - * - * @param idx index within the set of styles (0-based) - * @return CellStyle object at the index - */ - @Override - public CellStyle getCellStyleAt(int idx) - { - return _wb.getCellStyleAt(idx); - } - - /** - * Closes the underlying {@link XSSFWorkbook} and {@link OPCPackage} - * on which this Workbook is based, if any. - * - *

    Once this has been called, no further - * operations, updates or reads should be performed on the - * Workbook. - */ - @Override - public void close() throws IOException { - // ensure that any lingering writer is closed - for (SXSSFSheet sheet : _xFromSxHash.values()) - { - try { - sheet.getSheetDataWriter().close(); - } catch (IOException e) { - logger.log(POILogger.WARN, - "An exception occurred while closing sheet data writer for sheet " - + sheet.getSheetName() + ".", e); - } - } - - - // Tell the base workbook to close, does nothing if - // it's a newly created one - _wb.close(); - } - - /** - * Write out this workbook to an OutputStream. - * - * @param stream - the java OutputStream you wish to write to - * @exception IOException if anything can't be written. - */ - @Override - public void write(OutputStream stream) throws IOException - { - flushSheets(); - - //Save the template - File tmplFile = TempFile.createTempFile("poi-sxssf-template", ".xlsx"); - boolean deleted; - try { - FileOutputStream os = new FileOutputStream(tmplFile); - try { - _wb.write(os); - } finally { - os.close(); - } - - //Substitute the template entries with the generated sheet data files - final ZipEntrySource source = new ZipFileZipEntrySource(new ZipFile(tmplFile)); - injectData(source, stream); - } finally { - deleted = tmplFile.delete(); - } - if(!deleted) { - throw new IOException("Could not delete temporary file after processing: " + tmplFile); - } - } - - protected void flushSheets() throws IOException { - for (SXSSFSheet sheet : _xFromSxHash.values()) - { - sheet.flushRows(); - } - } - - /** - * Dispose of temporary files backing this workbook on disk. - * Calling this method will render the workbook unusable. - * @return true if all temporary files were deleted successfully. - */ - public boolean dispose() - { - boolean success = true; - for (SXSSFSheet sheet : _sxFromXHash.keySet()) - { - try { - success = sheet.dispose() && success; - } catch (IOException e) { - logger.log(POILogger.WARN, e); - success = false; - } - } - return success; - } - - /** - * @return the total number of defined names in this workbook - */ - @Override - public int getNumberOfNames() - { - return _wb.getNumberOfNames(); - } - - /** - * @param name the name of the defined name - * @return the defined name with the specified name. null if not found. - */ - @Override - public Name getName(String name) - { - return _wb.getName(name); - } - - /** - * Returns all defined names with the given name. - * - * @param name the name of the defined name - * @return a list of the defined names with the specified name. An empty list is returned if none is found. - */ - @Override - public List getNames(String name) { - return _wb.getNames(name); - } - - /** - * Returns all defined names - * - * @return all defined names - */ - @Override - public List getAllNames() - { - return _wb.getAllNames(); - } - - /** - * @param nameIndex position of the named range (0-based) - * @return the defined name at the specified index - * @throws IllegalArgumentException if the supplied index is invalid - * @deprecated 3.16. New projects should avoid accessing named ranges by index. - */ - @Override - @Deprecated - @Removal(version="3.18") - public Name getNameAt(int nameIndex) { - //noinspection deprecation - return _wb.getNameAt(nameIndex); - } - - /** - * Creates a new (uninitialised) defined name in this workbook - * - * @return new defined name object - */ - @Override - public Name createName() - { - return _wb.createName(); - } - - /** - * Gets the defined name index by name - * - * Note: Excel defined names are case-insensitive and - * this method performs a case-insensitive search. - * - * @param name the name of the defined name - * @return zero based index of the defined name. -1 if not found. - * - * @deprecated 3.16. New projects should avoid accessing named ranges by index. - * Use {@link #getName(String)} instead. - */ - @Override - @Deprecated - @Removal(version="3.18") - public int getNameIndex(String name) { - //noinspection deprecation - return _wb.getNameIndex(name); - } - - /** - * Remove the defined name at the specified index - * - * @param index named range index (0 based) - * - * @deprecated 3.16. New projects should use {@link #removeName(Name)}. - */ - @Override - @Deprecated - @Removal(version="3.18") - public void removeName(int index) { - //noinspection deprecation - _wb.removeName(index); - } - - /** - * Remove a defined name by name - * - * @param name the name of the defined name - * - * @deprecated 3.16. New projects should use {@link #removeName(Name)}. - */ - @Override - @Deprecated - @Removal(version="3.18") - public void removeName(String name) { - //noinspection deprecation - _wb.removeName(name); - } - - /** - * Remove the given defined name - * - * @param name the name to remove - */ - @Override - public void removeName(Name name) - { - _wb.removeName(name); - } - - /** - * Sets the printarea for the sheet provided - *

    - * i.e. Reference = $A$1:$B$2 - * @param sheetIndex Zero-based sheet index (0 Represents the first sheet to keep consistent with java) - * @param reference Valid name Reference for the Print Area - */ - @Override - public void setPrintArea(int sheetIndex, String reference) - { - _wb.setPrintArea(sheetIndex,reference); - } - - /** - * For the Convenience of Java Programmers maintaining pointers. - * @see #setPrintArea(int, String) - * @param sheetIndex Zero-based sheet index (0 = First Sheet) - * @param startColumn Column to begin printarea - * @param endColumn Column to end the printarea - * @param startRow Row to begin the printarea - * @param endRow Row to end the printarea - */ - @Override - public void setPrintArea(int sheetIndex, int startColumn, int endColumn, int startRow, int endRow) - { - _wb.setPrintArea(sheetIndex, startColumn, endColumn, startRow, endRow); - } - - /** - * Retrieves the reference for the printarea of the specified sheet, - * the sheet name is appended to the reference even if it was not specified. - * - * @param sheetIndex Zero-based sheet index (0 Represents the first sheet to keep consistent with java) - * @return String Null if no print area has been defined - */ - @Override - public String getPrintArea(int sheetIndex) - { - return _wb.getPrintArea(sheetIndex); - } - - /** - * Delete the printarea for the sheet specified - * - * @param sheetIndex Zero-based sheet index (0 = First Sheet) - */ - @Override - public void removePrintArea(int sheetIndex) - { - _wb.removePrintArea(sheetIndex); - } - - /** - * Retrieves the current policy on what to do when - * getting missing or blank cells from a row. - *

    - * The default is to return blank and null cells. - * {@link MissingCellPolicy} - *

    - */ - @Override - public MissingCellPolicy getMissingCellPolicy() - { - return _wb.getMissingCellPolicy(); - } - - /** - * Sets the policy on what to do when - * getting missing or blank cells from a row. - * - * This will then apply to all calls to - * {@link org.apache.poi.ss.usermodel.Row#getCell(int)}. See - * {@link MissingCellPolicy} - */ - @Override - public void setMissingCellPolicy(MissingCellPolicy missingCellPolicy) - { - _wb.setMissingCellPolicy(missingCellPolicy); - } - - /** - * Returns the instance of DataFormat for this workbook. - * - * @return the DataFormat object - */ - @Override - public DataFormat createDataFormat() - { - return _wb.createDataFormat(); - } - - /** - * Adds a picture to the workbook. - * - * @param pictureData The bytes of the picture - * @param format The format of the picture. - * - * @return the index to this picture (1 based). - * @see #PICTURE_TYPE_EMF - * @see #PICTURE_TYPE_WMF - * @see #PICTURE_TYPE_PICT - * @see #PICTURE_TYPE_JPEG - * @see #PICTURE_TYPE_PNG - * @see #PICTURE_TYPE_DIB - */ - @Override - public int addPicture(byte[] pictureData, int format) - { - return _wb.addPicture(pictureData,format); - } - - /** - * Gets all pictures from the Workbook. - * - * @return the list of pictures (a list of {@link PictureData} objects.) - */ - @Override - public List getAllPictures() - { - return _wb.getAllPictures(); - } - - /** - * Returns an object that handles instantiating concrete - * classes of the various instances one needs for HSSF, XSSF - * and SXSSF. - */ - @Override - public CreationHelper getCreationHelper() { - return new SXSSFCreationHelper(this); - } - - protected boolean isDate1904() { - return _wb.isDate1904(); - } - - @Override - @NotImplemented("XSSFWorkbook#isHidden is not implemented") - public boolean isHidden() - { - return _wb.isHidden(); - } - - @Override - @NotImplemented("XSSFWorkbook#setHidden is not implemented") - public void setHidden(boolean hiddenFlag) - { - _wb.setHidden(hiddenFlag); - } - - @Override - public boolean isSheetHidden(int sheetIx) - { - return _wb.isSheetHidden(sheetIx); - } - - @Override - public boolean isSheetVeryHidden(int sheetIx) - { - return _wb.isSheetVeryHidden(sheetIx); - } - - @Override - public SheetVisibility getSheetVisibility(int sheetIx) { - return _wb.getSheetVisibility(sheetIx); - } - - @Override - public void setSheetHidden(int sheetIx, boolean hidden) - { - _wb.setSheetHidden(sheetIx,hidden); - } - - @Removal(version="3.18") - @Deprecated - @Override - public void setSheetHidden(int sheetIx, int hidden) - { - _wb.setSheetHidden(sheetIx,hidden); - } - - @Override - public void setSheetVisibility(int sheetIx, SheetVisibility visibility) { - _wb.setSheetVisibility(sheetIx, visibility); - } - - /** - * Not implemented for SXSSFWorkbook - * - * Adds the LinkTable records required to allow formulas referencing - * the specified external workbook to be added to this one. Allows - * formulas such as "[MyOtherWorkbook]Sheet3!$A$5" to be added to the - * file, for workbooks not already referenced. - * - * Note: this is not implemented and thus currently throws an Exception stating this. - * - * @param name The name the workbook will be referenced as in formulas - * @param workbook The open workbook to fetch the link required information from - * - * @throws RuntimeException stating that this method is not implemented yet. - */ - @Override - @NotImplemented - public int linkExternalWorkbook(String name, Workbook workbook) { - throw new RuntimeException("NotImplemented"); - } - - /** - * Register a new toolpack in this workbook. - * - * @param toopack the toolpack to register - */ - @Override - public void addToolPack(UDFFinder toopack) - { - _wb.addToolPack(toopack); - } - - /** - * Whether the application shall perform a full recalculation when the workbook is opened. - *

    - * Typically you want to force formula recalculation when you modify cell formulas or values - * of a workbook previously created by Excel. When set to 0, this flag will tell Excel - * that it needs to recalculate all formulas in the workbook the next time the file is opened. - *

    - * - * @param value true if the application will perform a full recalculation of - * workbook values when the workbook is opened - * @since 3.8 - */ - @Override - public void setForceFormulaRecalculation(boolean value){ - _wb.setForceFormulaRecalculation(value); - } - - /** - * Whether Excel will be asked to recalculate all formulas when the workbook is opened. - */ - @Override - public boolean getForceFormulaRecalculation(){ - return _wb.getForceFormulaRecalculation(); - } - - /** - * Returns the spreadsheet version (EXCLE2007) of this workbook - * - * @return EXCEL2007 SpreadsheetVersion enum - * @since 3.14 beta 2 - */ - @Override - public SpreadsheetVersion getSpreadsheetVersion() { - return SpreadsheetVersion.EXCEL2007; - } - - @Override - public int addOlePackage(byte[] oleData, String label, String fileName, String command) throws IOException { - return _wb.addOlePackage(oleData, label, fileName, command); - } - - /** - * Whether a call to {@link SXSSFCell#setCellFormula(String)} will validate the formula or not. - * - * @param value true if the application will validate the formula is correct - * @since 3.17 - */ - @Override - public void setCellFormulaValidation(final boolean value) { - // currently {@link SXSSFCell#setCellFormula(String)} does no validation anyway, ignore - } - - /** - * Whether a call to {@link SXSSFCell#setCellFormula(String)} will validate the formula or not. - * - * @since 3.17 - */ - @Override - public boolean getCellFormulaValidation() { - return false; - } - -//end of interface implementation -} diff --git a/src/ooxml/java/org/apache/poi/xssf/streaming/SheetDataWriter.java b/src/ooxml/java/org/apache/poi/xssf/streaming/SheetDataWriter.java deleted file mode 100644 index 3e734d481..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/streaming/SheetDataWriter.java +++ /dev/null @@ -1,437 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xssf.streaming; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.Writer; -import java.util.Iterator; - -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.FormulaError; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.util.TempFile; -import org.apache.poi.xssf.model.SharedStringsTable; -import org.apache.poi.xssf.usermodel.XSSFRichTextString; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STCellType; - -/** - * Initially copied from BigGridDemo "SpreadsheetWriter". - * Unlike the original code which wrote the entire document, - * this class only writes the "sheetData" document fragment - * so that it was renamed to "SheetDataWriter" - */ -public class SheetDataWriter { - private static final POILogger logger = POILogFactory.getLogger(SheetDataWriter.class); - - private final File _fd; - private final Writer _out; - private int _rownum; - private int _numberOfFlushedRows; - private int _lowestIndexOfFlushedRows; // meaningful only of _numberOfFlushedRows>0 - private int _numberOfCellsOfLastFlushedRow; // meaningful only of _numberOfFlushedRows>0 - private int _numberLastFlushedRow = -1; // meaningful only of _numberOfFlushedRows>0 - - /** - * Table of strings shared across this workbook. - * If two cells contain the same string, then the cell value is the same index into SharedStringsTable - */ - private SharedStringsTable _sharedStringSource; - - public SheetDataWriter() throws IOException { - _fd = createTempFile(); - _out = createWriter(_fd); - } - - public SheetDataWriter(SharedStringsTable sharedStringsTable) throws IOException { - this(); - this._sharedStringSource = sharedStringsTable; - } - /** - * Create a temp file to write sheet data. - * By default, temp files are created in the default temporary-file directory - * with a prefix "poi-sxssf-sheet" and suffix ".xml". Subclasses can override - * it and specify a different temp directory or filename or suffix, e.g. .gz - * - * @return temp file to write sheet data - */ - public File createTempFile() throws IOException { - return TempFile.createTempFile("poi-sxssf-sheet", ".xml"); - } - - /** - * Create a writer for the sheet data. - * - * @param fd the file to write to - */ - public Writer createWriter(File fd) throws IOException { - FileOutputStream fos = new FileOutputStream(fd); - OutputStream decorated; - try { - decorated = decorateOutputStream(fos); - } catch (final IOException e) { - fos.close(); - throw e; - } - return new BufferedWriter( - new OutputStreamWriter(decorated, "UTF-8")); - } - - /** - * Override this to translate (such as encrypt or compress) the file output stream - * as it is being written to disk. - * The default behavior is to to pass the stream through unmodified. - * - * @param fos the stream to decorate - * @return a decorated stream - * @throws IOException - * @see #decorateInputStream(FileInputStream) - */ - protected OutputStream decorateOutputStream(FileOutputStream fos) throws IOException { - return fos; - } - - /** - * flush and close the temp data writer. - * This method must be invoked before calling {@link #getWorksheetXMLInputStream()} - */ - public void close() throws IOException{ - _out.flush(); - _out.close(); - } - - protected File getTempFile(){ - return _fd; - } - - /** - * @return a stream to read temp file with the sheet data - */ - public InputStream getWorksheetXMLInputStream() throws IOException { - File fd = getTempFile(); - FileInputStream fis = new FileInputStream(fd); - try { - return decorateInputStream(fis); - } catch (IOException e) { - fis.close(); - throw e; - } - } - - /** - * Override this to translate (such as decrypt or expand) the file input stream - * as it is being read from disk. - * The default behavior is to to pass the stream through unmodified. - * - * @param fis the stream to decorate - * @return a decorated stream - * @throws IOException - * @see #decorateOutputStream(FileOutputStream) - */ - protected InputStream decorateInputStream(FileInputStream fis) throws IOException { - return fis; - } - - public int getNumberOfFlushedRows() { - return _numberOfFlushedRows; - } - - public int getNumberOfCellsOfLastFlushedRow() { - return _numberOfCellsOfLastFlushedRow; - } - - public int getLowestIndexOfFlushedRows() { - return _lowestIndexOfFlushedRows; - } - - public int getLastFlushedRow() { - return _numberLastFlushedRow; - } - - @Override - protected void finalize() throws Throwable { - if (!_fd.delete()) { - logger.log(POILogger.ERROR, "Can't delete temporary encryption file: "+_fd); - } - - super.finalize(); - } - - /** - * Write a row to the file - * - * @param rownum 0-based row number - * @param row a row - */ - public void writeRow(int rownum, SXSSFRow row) throws IOException { - if (_numberOfFlushedRows == 0) - _lowestIndexOfFlushedRows = rownum; - _numberLastFlushedRow = Math.max(rownum, _numberLastFlushedRow); - _numberOfCellsOfLastFlushedRow = row.getLastCellNum(); - _numberOfFlushedRows++; - beginRow(rownum, row); - Iterator cells = row.allCellsIterator(); - int columnIndex = 0; - while (cells.hasNext()) { - writeCell(columnIndex++, cells.next()); - } - endRow(); - } - - void beginRow(int rownum, SXSSFRow row) throws IOException { - _out.write("\n"); - } - - public void writeCell(int columnIndex, Cell cell) throws IOException { - if (cell == null) { - return; - } - String ref = new CellReference(_rownum, columnIndex).formatAsString(); - _out.write(""); - break; - } - case FORMULA: { - _out.write(">"); - _out.write(""); - outputQuotedString(cell.getCellFormula()); - _out.write(""); - switch (cell.getCachedFormulaResultTypeEnum()) { - case NUMERIC: - double nval = cell.getNumericCellValue(); - if (!Double.isNaN(nval)) { - _out.write("" + nval + ""); - } - break; - default: - break; - } - break; - } - case STRING: { - if (_sharedStringSource != null) { - XSSFRichTextString rt = new XSSFRichTextString(cell.getStringCellValue()); - int sRef = _sharedStringSource.addEntry(rt.getCTRst()); - - _out.write(" t=\"" + STCellType.S.toString() + "\">"); - _out.write(""); - _out.write(String.valueOf(sRef)); - _out.write(""); - } else { - _out.write(" t=\"inlineStr\">"); - _out.write(""); - outputQuotedString(cell.getStringCellValue()); - _out.write("
    "); - } - break; - } - case NUMERIC: { - _out.write(" t=\"n\">"); - _out.write("" + cell.getNumericCellValue() + ""); - break; - } - case BOOLEAN: { - _out.write(" t=\"b\">"); - _out.write("" + (cell.getBooleanCellValue() ? "1" : "0") + ""); - break; - } - case ERROR: { - FormulaError error = FormulaError.forInt(cell.getErrorCellValue()); - - _out.write(" t=\"e\">"); - _out.write("" + error.getString() + ""); - break; - } - default: { - throw new IllegalStateException("Invalid cell type: " + cellType); - } - } - _out.write(""); - } - - - /** - * @return whether the string has leading / trailing spaces that - * need to be preserved with the xml:space=\"preserve\" attribute - */ - boolean hasLeadingTrailingSpaces(String str) { - if (str != null && str.length() > 0) { - char firstChar = str.charAt(0); - char lastChar = str.charAt(str.length() - 1); - return Character.isWhitespace(firstChar) || Character.isWhitespace(lastChar) ; - } - return false; - } - - //Taken from jdk1.3/src/javax/swing/text/html/HTMLWriter.java - protected void outputQuotedString(String s) throws IOException { - if (s == null || s.length() == 0) { - return; - } - - char[] chars = s.toCharArray(); - int last = 0; - int length = s.length(); - for (int counter = 0; counter < length; counter++) { - char c = chars[counter]; - switch (c) { - case '<': - if (counter > last) { - _out.write(chars, last, counter - last); - } - last = counter + 1; - _out.write("<"); - break; - case '>': - if (counter > last) { - _out.write(chars, last, counter - last); - } - last = counter + 1; - _out.write(">"); - break; - case '&': - if (counter > last) { - _out.write(chars, last, counter - last); - } - last = counter + 1; - _out.write("&"); - break; - case '"': - if (counter > last) { - _out.write(chars, last, counter - last); - } - last = counter + 1; - _out.write("""); - break; - // Special characters - case '\n': - case '\r': - if (counter > last) { - _out.write(chars, last, counter - last); - } - _out.write(" "); - last = counter + 1; - break; - case '\t': - if (counter > last) { - _out.write(chars, last, counter - last); - } - _out.write(" "); - last = counter + 1; - break; - case 0xa0: - if (counter > last) { - _out.write(chars, last, counter - last); - } - _out.write(" "); - last = counter + 1; - break; - default: - // YK: XmlBeans silently replaces all ISO control characters ( < 32) with question marks. - // the same rule applies to unicode surrogates and "not a character" symbols. - if( c < ' ' || Character.isLowSurrogate(c) || Character.isHighSurrogate(c) || - ('\uFFFE' <= c && c <= '\uFFFF')) { - if (counter > last) { - _out.write(chars, last, counter - last); - } - _out.write('?'); - last = counter + 1; - } - else if (c > 127) { - if (counter > last) { - _out.write(chars, last, counter - last); - } - last = counter + 1; - // If the character is outside of ascii, write the - // numeric value. - _out.write("&#"); - _out.write(String.valueOf((int) c)); - _out.write(";"); - } - break; - } - } - if (last < length) { - _out.write(chars, last, length - last); - } - } - - /** - * Deletes the temporary file that backed this sheet on disk. - * @return true if the file was deleted, false if it wasn't. - */ - boolean dispose() throws IOException { - final boolean ret; - try { - _out.close(); - } finally { - ret = _fd.delete(); - } - return ret; - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/BaseXSSFEvaluationWorkbook.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/BaseXSSFEvaluationWorkbook.java deleted file mode 100644 index 9c5e6ffb1..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/BaseXSSFEvaluationWorkbook.java +++ /dev/null @@ -1,449 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.ss.formula.EvaluationName; -import org.apache.poi.ss.formula.EvaluationWorkbook; -import org.apache.poi.ss.formula.FormulaParser; -import org.apache.poi.ss.formula.FormulaParsingWorkbook; -import org.apache.poi.ss.formula.FormulaRenderingWorkbook; -import org.apache.poi.ss.formula.FormulaType; -import org.apache.poi.ss.formula.SheetIdentifier; -import org.apache.poi.ss.formula.functions.FreeRefFunction; -import org.apache.poi.ss.formula.ptg.Area3DPxg; -import org.apache.poi.ss.formula.ptg.NamePtg; -import org.apache.poi.ss.formula.ptg.NameXPtg; -import org.apache.poi.ss.formula.ptg.NameXPxg; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.apache.poi.ss.formula.ptg.Ref3DPxg; -import org.apache.poi.ss.formula.udf.IndexedUDFFinder; -import org.apache.poi.ss.formula.udf.UDFFinder; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.util.AreaReference; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.util.NotImplemented; -import org.apache.poi.util.Internal; -import org.apache.poi.xssf.model.ExternalLinksTable; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTDefinedName; - -/** - * Internal POI use only - parent of XSSF and SXSSF evaluation workbooks - */ -@Internal -public abstract class BaseXSSFEvaluationWorkbook implements FormulaRenderingWorkbook, EvaluationWorkbook, FormulaParsingWorkbook { - protected final XSSFWorkbook _uBook; - - // lazily populated. This should only be accessed through getTableCache - // keys are lower-case to make this a quasi-case-insensitive map - private Map _tableCache = null; - - - protected BaseXSSFEvaluationWorkbook(XSSFWorkbook book) { - _uBook = book; - } - - /* (non-JavaDoc), inherit JavaDoc from EvaluationWorkbook - * @since POI 3.15 beta 3 - */ - @Override - public void clearAllCachedResultValues() { - _tableCache = null; - } - - private int convertFromExternalSheetIndex(int externSheetIndex) { - return externSheetIndex; - } - /** - * XSSF doesn't use external sheet indexes, so when asked treat - * it just as a local index - */ - @Override - public int convertFromExternSheetIndex(int externSheetIndex) { - return externSheetIndex; - } - /** - * @return the external sheet index of the sheet with the given internal - * index. Used by some of the more obscure formula and named range things. - * Fairly easy on XSSF (we think...) since the internal and external - * indices are the same - */ - private int convertToExternalSheetIndex(int sheetIndex) { - return sheetIndex; - } - - @Override - public int getExternalSheetIndex(String sheetName) { - int sheetIndex = _uBook.getSheetIndex(sheetName); - return convertToExternalSheetIndex(sheetIndex); - } - - private int resolveBookIndex(String bookName) { - // Strip the [] wrapper, if still present - if (bookName.startsWith("[") && bookName.endsWith("]")) { - bookName = bookName.substring(1, bookName.length()-2); - } - - // Is it already in numeric form? - try { - return Integer.parseInt(bookName); - } catch (NumberFormatException e) {} - - // Look up an External Link Table for this name - List tables = _uBook.getExternalLinksTable(); - int index = findExternalLinkIndex(bookName, tables); - if (index != -1) return index; - - // Is it an absolute file reference? - if (bookName.startsWith("'file:///") && bookName.endsWith("'")) { - String relBookName = bookName.substring(bookName.lastIndexOf('/')+1); - relBookName = relBookName.substring(0, relBookName.length()-1); // Trailing ' - - // Try with this name - index = findExternalLinkIndex(relBookName, tables); - if (index != -1) return index; - - // If we get here, it's got no associated proper links yet - // So, add the missing reference and return - // Note - this is really rather nasty... - ExternalLinksTable fakeLinkTable = new FakeExternalLinksTable(relBookName); - tables.add(fakeLinkTable); - return tables.size(); // 1 based results, 0 = current workbook - } - - // Not properly referenced - throw new RuntimeException("Book not linked for filename " + bookName); - } - /* This is case-sensitive. Is that correct? */ - private int findExternalLinkIndex(String bookName, List tables) { - int i = 0; - for (ExternalLinksTable table : tables) { - if (table.getLinkedFileName().equals(bookName)) { - return i+1; // 1 based results, 0 = current workbook - } - i++; - } - return -1; - } - private static class FakeExternalLinksTable extends ExternalLinksTable { - private final String fileName; - private FakeExternalLinksTable(String fileName) { - this.fileName = fileName; - } - @Override - public String getLinkedFileName() { - return fileName; - } - } - - /** - * Return EvaluationName wrapper around the matching XSSFName (named range) - * @param name case-aware but case-insensitive named range in workbook - * @param sheetIndex index of sheet if named range scope is limited to one sheet - * if named range scope is global to the workbook, sheetIndex is -1. - * @return If name is a named range in the workbook, returns - * EvaluationName corresponding to that named range - * Returns null if there is no named range with the same name and scope in the workbook - */ - @Override - public EvaluationName getName(String name, int sheetIndex) { - for (int i = 0; i < _uBook.getNumberOfNames(); i++) { - XSSFName nm = _uBook.getNameAt(i); - String nameText = nm.getNameName(); - int nameSheetindex = nm.getSheetIndex(); - if (name.equalsIgnoreCase(nameText) && - (nameSheetindex == -1 || nameSheetindex == sheetIndex)) { - return new Name(nm, i, this); - } - } - return sheetIndex == -1 ? null : getName(name, -1); - } - - @Override - public String getSheetName(int sheetIndex) { - return _uBook.getSheetName(sheetIndex); - } - - @Override - public ExternalName getExternalName(int externSheetIndex, int externNameIndex) { - throw new IllegalStateException("HSSF-style external references are not supported for XSSF"); - } - - @Override - public ExternalName getExternalName(String nameName, String sheetName, int externalWorkbookNumber) { - if (externalWorkbookNumber > 0) { - // External reference - reference is 1 based, link table is 0 based - int linkNumber = externalWorkbookNumber - 1; - ExternalLinksTable linkTable = _uBook.getExternalLinksTable().get(linkNumber); - - for (org.apache.poi.ss.usermodel.Name name : linkTable.getDefinedNames()) { - if (name.getNameName().equals(nameName)) { - // HSSF returns one sheet higher than normal, and various bits - // of the code assume that. So, make us match that behaviour! - int nameSheetIndex = name.getSheetIndex() + 1; - - // TODO Return a more specialised form of this, see bug #56752 - // Should include the cached values, for in case that book isn't available - // Should support XSSF stuff lookups - return new ExternalName(nameName, -1, nameSheetIndex); - } - } - throw new IllegalArgumentException("Name '"+nameName+"' not found in " + - "reference to " + linkTable.getLinkedFileName()); - } else { - // Internal reference - int nameIdx = _uBook.getNameIndex(nameName); - return new ExternalName(nameName, nameIdx, 0); // TODO Is this right? - } - - } - - /** - * Return an external name (named range, function, user-defined function) Pxg - */ - @Override - public NameXPxg getNameXPtg(String name, SheetIdentifier sheet) { - // First, try to find it as a User Defined Function - IndexedUDFFinder udfFinder = (IndexedUDFFinder)getUDFFinder(); - FreeRefFunction func = udfFinder.findFunction(name); - if (func != null) { - return new NameXPxg(null, name); - } - - // Otherwise, try it as a named range - if (sheet == null) { - if (!_uBook.getNames(name).isEmpty()) { - return new NameXPxg(null, name); - } - return null; - } - if (sheet._sheetIdentifier == null) { - // Workbook + Named Range only - int bookIndex = resolveBookIndex(sheet._bookName); - return new NameXPxg(bookIndex, null, name); - } - - // Use the sheetname and process - String sheetName = sheet._sheetIdentifier.getName(); - - if (sheet._bookName != null) { - int bookIndex = resolveBookIndex(sheet._bookName); - return new NameXPxg(bookIndex, sheetName, name); - } else { - return new NameXPxg(sheetName, name); - } - } - @Override - public Ptg get3DReferencePtg(CellReference cell, SheetIdentifier sheet) { - if (sheet._bookName != null) { - int bookIndex = resolveBookIndex(sheet._bookName); - return new Ref3DPxg(bookIndex, sheet, cell); - } else { - return new Ref3DPxg(sheet, cell); - } - } - @Override - public Ptg get3DReferencePtg(AreaReference area, SheetIdentifier sheet) { - if (sheet._bookName != null) { - int bookIndex = resolveBookIndex(sheet._bookName); - return new Area3DPxg(bookIndex, sheet, area); - } else { - return new Area3DPxg(sheet, area); - } - } - - @Override - public String resolveNameXText(NameXPtg n) { - int idx = n.getNameIndex(); - String name = null; - - // First, try to find it as a User Defined Function - IndexedUDFFinder udfFinder = (IndexedUDFFinder)getUDFFinder(); - name = udfFinder.getFunctionName(idx); - if (name != null) return name; - - // Otherwise, try it as a named range - XSSFName xname = _uBook.getNameAt(idx); - if (xname != null) { - name = xname.getNameName(); - } - - return name; - } - - @Override - public ExternalSheet getExternalSheet(int externSheetIndex) { - throw new IllegalStateException("HSSF-style external references are not supported for XSSF"); - } - @Override - public ExternalSheet getExternalSheet(String firstSheetName, String lastSheetName, int externalWorkbookNumber) { - String workbookName; - if (externalWorkbookNumber > 0) { - // External reference - reference is 1 based, link table is 0 based - int linkNumber = externalWorkbookNumber - 1; - ExternalLinksTable linkTable = _uBook.getExternalLinksTable().get(linkNumber); - workbookName = linkTable.getLinkedFileName(); - } else { - // Internal reference - workbookName = null; - } - - if (lastSheetName == null || firstSheetName.equals(lastSheetName)) { - return new ExternalSheet(workbookName, firstSheetName); - } else { - return new ExternalSheetRange(workbookName, firstSheetName, lastSheetName); - } - } - - @NotImplemented - public int getExternalSheetIndex(String workbookName, String sheetName) { - throw new RuntimeException("not implemented yet"); - } - @Override - public int getSheetIndex(String sheetName) { - return _uBook.getSheetIndex(sheetName); - } - - @Override - public String getSheetFirstNameByExternSheet(int externSheetIndex) { - int sheetIndex = convertFromExternalSheetIndex(externSheetIndex); - return _uBook.getSheetName(sheetIndex); - } - @Override - public String getSheetLastNameByExternSheet(int externSheetIndex) { - // XSSF does multi-sheet references differently, so this is the same as the first - return getSheetFirstNameByExternSheet(externSheetIndex); - } - - @Override - public String getNameText(NamePtg namePtg) { - return _uBook.getNameAt(namePtg.getIndex()).getNameName(); - } - @Override - public EvaluationName getName(NamePtg namePtg) { - int ix = namePtg.getIndex(); - return new Name(_uBook.getNameAt(ix), ix, this); - } - @Override - public XSSFName createName() { - return _uBook.createName(); - } - - private static String caseInsensitive(String s) { - return s.toUpperCase(Locale.ROOT); - } - - /* - * TODO: data tables are stored at the workbook level in XSSF, but are bound to a single sheet. - * The current code structure has them hanging off XSSFSheet, but formulas reference them - * only by name (names are global, and case insensitive). - * This map stores names as lower case for case-insensitive lookups. - * - * FIXME: Caching tables by name here for fast formula lookup means the map is out of date if - * a table is renamed or added/removed to a sheet after the map is created. - * - * Perhaps tables can be managed similar to PivotTable references above? - */ - private Map getTableCache() { - if ( _tableCache != null ) { - return _tableCache; - } - // FIXME: use org.apache.commons.collections.map.CaseInsensitiveMap - _tableCache = new HashMap(); - - for (Sheet sheet : _uBook) { - for (XSSFTable tbl : ((XSSFSheet)sheet).getTables()) { - String lname = caseInsensitive(tbl.getName()); - _tableCache.put(lname, tbl); - } - } - return _tableCache; - } - - /** - * Returns the data table with the given name (case insensitive). - * Tables are cached for performance (formula evaluation looks them up by name repeatedly). - * After the first table lookup, adding or removing a table from the document structure will cause trouble. - * This is meant to be used on documents whose structure is essentially static at the point formulas are evaluated. - * - * @param name the data table name (case-insensitive) - * @return The Data table in the workbook named name, or null if no table is named name. - * @since 3.15 beta 2 - */ - @Override - public XSSFTable getTable(String name) { - if (name == null) return null; - String lname = caseInsensitive(name); - return getTableCache().get(lname); - } - - @Override - public UDFFinder getUDFFinder(){ - return _uBook.getUDFFinder(); - } - - @Override - public SpreadsheetVersion getSpreadsheetVersion(){ - return SpreadsheetVersion.EXCEL2007; - } - - private static final class Name implements EvaluationName { - - private final XSSFName _nameRecord; - private final int _index; - private final FormulaParsingWorkbook _fpBook; - - public Name(XSSFName name, int index, FormulaParsingWorkbook fpBook) { - _nameRecord = name; - _index = index; - _fpBook = fpBook; - } - - public Ptg[] getNameDefinition() { - - return FormulaParser.parse(_nameRecord.getRefersToFormula(), _fpBook, FormulaType.NAMEDRANGE, _nameRecord.getSheetIndex()); - } - - public String getNameText() { - return _nameRecord.getNameName(); - } - - public boolean hasFormula() { - // TODO - no idea if this is right - CTDefinedName ctn = _nameRecord.getCTName(); - String strVal = ctn.getStringValue(); - return !ctn.getFunction() && strVal != null && strVal.length() > 0; - } - - public boolean isFunctionName() { - return _nameRecord.isFunctionName(); - } - - public boolean isRange() { - return hasFormula(); // TODO - is this right? - } - public NamePtg createPtg() { - return new NamePtg(_index); - } - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/BaseXSSFFormulaEvaluator.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/BaseXSSFFormulaEvaluator.java deleted file mode 100644 index 780126c3d..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/BaseXSSFFormulaEvaluator.java +++ /dev/null @@ -1,83 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import org.apache.poi.ss.formula.BaseFormulaEvaluator; -import org.apache.poi.ss.formula.EvaluationCell; -import org.apache.poi.ss.formula.WorkbookEvaluator; -import org.apache.poi.ss.formula.eval.BoolEval; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; -import org.apache.poi.ss.usermodel.RichTextString; - -/** - * Internal POI use only - parent of XSSF and SXSSF formula evaluators - */ -public abstract class BaseXSSFFormulaEvaluator extends BaseFormulaEvaluator { - protected BaseXSSFFormulaEvaluator(WorkbookEvaluator bookEvaluator) { - super(bookEvaluator); - } - @Override - protected RichTextString createRichTextString(String str) { - return new XSSFRichTextString(str); - } - - public void notifySetFormula(Cell cell) { - _bookEvaluator.notifyUpdateCell(new XSSFEvaluationCell((XSSFCell)cell)); - } - public void notifyDeleteCell(Cell cell) { - _bookEvaluator.notifyDeleteCell(new XSSFEvaluationCell((XSSFCell)cell)); - } - public void notifyUpdateCell(Cell cell) { - _bookEvaluator.notifyUpdateCell(new XSSFEvaluationCell((XSSFCell)cell)); - } - - /** - * Turns a XSSFCell / SXSSFCell into a XSSFEvaluationCell - */ - protected abstract EvaluationCell toEvaluationCell(Cell cell); - - /** - * Returns a CellValue wrapper around the supplied ValueEval instance. - */ - protected CellValue evaluateFormulaCellValue(Cell cell) { - EvaluationCell evalCell = toEvaluationCell(cell); - ValueEval eval = _bookEvaluator.evaluate(evalCell); - if (eval instanceof NumberEval) { - NumberEval ne = (NumberEval) eval; - return new CellValue(ne.getNumberValue()); - } - if (eval instanceof BoolEval) { - BoolEval be = (BoolEval) eval; - return CellValue.valueOf(be.getBooleanValue()); - } - if (eval instanceof StringEval) { - StringEval ne = (StringEval) eval; - return new CellValue(ne.getStringValue()); - } - if (eval instanceof ErrorEval) { - return CellValue.getError(((ErrorEval)eval).getErrorCode()); - } - throw new RuntimeException("Unexpected eval class (" + eval.getClass().getName() + ")"); - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/ListAutoNumber.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/ListAutoNumber.java deleted file mode 100644 index 5108813b2..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/ListAutoNumber.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -package org.apache.poi.xssf.usermodel; - -/** - * Specifies type of automatic numbered bullet points that should be applied to a paragraph. - */ -public enum ListAutoNumber { - /** - * (a), (b), (c), ... - */ - ALPHA_LC_PARENT_BOTH, - /** - * (A), (B), (C), ... - */ - ALPHA_UC_PARENT_BOTH, - /** - * a), b), c), ... - */ - ALPHA_LC_PARENT_R, - /** - * A), B), C), ... - */ - ALPHA_UC_PARENT_R, - /** - * a., b., c., ... - */ - ALPHA_LC_PERIOD, - /** - * A., B., C., ... - */ - ALPHA_UC_PERIOD, - /** - * (1), (2), (3), ... - */ - ARABIC_PARENT_BOTH, - /** - * 1), 2), 3), ... - */ - ARABIC_PARENT_R, - - /** - * 1., 2., 3., ... - */ - ARABIC_PERIOD, - /** - * 1, 2, 3, ... - */ - ARABIC_PLAIN, - - /** - * (i), (ii), (iii), ... - */ - ROMAN_LC_PARENT_BOTH, - /** - * (I), (II), (III), ... - */ - ROMAN_UC_PARENT_BOTH, - /** - * i), ii), iii), ... - */ - ROMAN_LC_PARENT_R, - /** - * I), II), III), ... - */ - ROMAN_UC_PARENT_R, - /** - * i., ii., iii., ... - */ - ROMAN_LC_PERIOD , - /** - * I., II., III., ... - */ - ROMAN_UC_PERIOD, - /** - * Dbl-byte circle numbers - */ - CIRCLE_NUM_DB_PLAIN, - /** - * Wingdings black circle numbers - */ - CIRCLE_NUM_WD_BLACK_PLAIN, - /** - * Wingdings white circle numbers - */ - CIRCLE_NUM_WD_WHITE_PLAIN -} \ No newline at end of file diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/TextAlign.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/TextAlign.java deleted file mode 100644 index b93a885c2..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/TextAlign.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -package org.apache.poi.xssf.usermodel; - -/** - * Specified a list of text alignment types - */ -public enum TextAlign { - /** - * Align text to the left margin. - */ - LEFT, - /** - * Align text in the center. - */ - CENTER, - - /** - * Align text to the right margin. - */ - RIGHT, - - /** - * Align text so that it is justified across the whole line. It - * is smart in the sense that it will not justify sentences - * which are short - */ - JUSTIFY, - JUSTIFY_LOW, - DIST, - THAI_DIST -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/TextAutofit.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/TextAutofit.java deleted file mode 100644 index 6e01b134f..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/TextAutofit.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -package org.apache.poi.xssf.usermodel; - -/** - * Specifies a list of auto-fit types. - *

    - * Autofit specifies that a shape should be auto-fit to fully contain the text described within it. - * Auto-fitting is when text within a shape is scaled in order to contain all the text inside - *

    - */ -public enum TextAutofit { - /** - * Specifies that text within the text body should not be auto-fit to the bounding box. - * Auto-fitting is when text within a text box is scaled in order to remain inside - * the text box. - */ - NONE, - /** - * Specifies that text within the text body should be normally auto-fit to the bounding box. - * Autofitting is when text within a text box is scaled in order to remain inside the text box. - * - *

    - * Example: Consider the situation where a user is building a diagram and needs - * to have the text for each shape that they are using stay within the bounds of the shape. - * An easy way this might be done is by using NORMAL autofit - *

    - */ - NORMAL, - /** - * Specifies that a shape should be auto-fit to fully contain the text described within it. - * Auto-fitting is when text within a shape is scaled in order to contain all the text inside. - * - *

    - * Example: Consider the situation where a user is building a diagram and needs to have - * the text for each shape that they are using stay within the bounds of the shape. - * An easy way this might be done is by using SHAPE autofit - *

    - */ - SHAPE -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/TextCap.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/TextCap.java deleted file mode 100644 index 9202e92b4..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/TextCap.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xssf.usermodel; - -/** - * Text Capitalization that is to be applied to the text run. This is a render-only - * modification and does not affect the actual characters stored in the text run. - */ -public enum TextCap { - NONE, - SMALL, - ALL -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/TextDirection.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/TextDirection.java deleted file mode 100644 index f91fcca7a..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/TextDirection.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -package org.apache.poi.xssf.usermodel; - -/** - * Vertical Text Types - */ -public enum TextDirection { - /** - * Horizontal text. This should be default. - */ - HORIZONTAL, - /** - * Vertical orientation. - * (each line is 90 degrees rotated clockwise, so it goes - * from top to bottom; each next line is to the left from - * the previous one). - */ - VERTICAL, - /** - * Vertical orientation. - * (each line is 270 degrees rotated clockwise, so it goes - * from bottom to top; each next line is to the right from - * the previous one). - */ - VERTICAL_270, - /** - * Determines if all of the text is vertical - * ("one letter on top of another"). - */ - STACKED -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/TextFontAlign.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/TextFontAlign.java deleted file mode 100644 index 96417980c..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/TextFontAlign.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -package org.apache.poi.xssf.usermodel; - -/** - * Specified a list of text font alignment types - */ -public enum TextFontAlign { - /** - * Automatic alignment - */ - AUTO, - /** - * Align text to the top. - */ - TOP, - /** - * Align text in the center. - */ - CENTER, - - /** - * Align text to the baseline. - */ - BASELINE, - - /** - * Align text to the bottom. - */ - BOTTOM -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/TextHorizontalOverflow.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/TextHorizontalOverflow.java deleted file mode 100644 index b1fe0c18d..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/TextHorizontalOverflow.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -package org.apache.poi.xssf.usermodel; - -/** - * Text Horizontal Overflow - */ -public enum TextHorizontalOverflow { - /** - * When a big character does not fit into a line, allow a - * horizontal overflow. - */ - OVERFLOW, - - /** - * When a big character does not fit into a line, clip it at - * the proper horizontal overflow. - */ - CLIP -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/TextVerticalOverflow.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/TextVerticalOverflow.java deleted file mode 100644 index 87d3e4018..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/TextVerticalOverflow.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -package org.apache.poi.xssf.usermodel; - -/** - * Text Vertical Overflow - */ -public enum TextVerticalOverflow { - /** - * Overflow the text and pay no attention to top and bottom barriers. - */ - OVERFLOW, - - /** - * Pay attention to top and bottom barriers. Use an - * ellipsis to denote that there is text which is not visible. - */ - ELLIPSIS, - - /** - * Pay attention to top and bottom barriers. Provide no - * indication that there is text which is not visible. - */ - CLIP -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFAnchor.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFAnchor.java deleted file mode 100644 index de855787b..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFAnchor.java +++ /dev/null @@ -1,27 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import org.apache.poi.ss.usermodel.ChildAnchor; - -/** - * An anchor is what specifics the position of a shape within a client object - * or within another containing shape. - */ -public abstract class XSSFAnchor implements ChildAnchor { -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFAutoFilter.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFAutoFilter.java deleted file mode 100644 index d363ab31a..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFAutoFilter.java +++ /dev/null @@ -1,33 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; -import org.apache.poi.ss.usermodel.AutoFilter; - -/** - * Represents autofiltering for the specified worksheet. - * - * @author Yegor Kozlov - */ -public final class XSSFAutoFilter implements AutoFilter { - private XSSFSheet _sheet; - - XSSFAutoFilter(XSSFSheet sheet){ - _sheet = sheet; - } - -} \ No newline at end of file diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFBorderFormatting.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFBorderFormatting.java deleted file mode 100644 index f700aecf6..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFBorderFormatting.java +++ /dev/null @@ -1,367 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel; - -import org.apache.poi.ss.usermodel.BorderFormatting; -import org.apache.poi.ss.usermodel.BorderStyle; -import org.apache.poi.ss.usermodel.Color; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTBorder; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STBorderStyle; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTBorderPr; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTColor; - -/** - * XSSF high level representation for Border Formatting component - * of Conditional Formatting settings - */ -public class XSSFBorderFormatting implements BorderFormatting { - CTBorder _border; - - /*package*/ XSSFBorderFormatting(CTBorder border) { - _border = border; - } - - /** - * @deprecated POI 3.15. Use {@link #getBorderBottomEnum()}. - * This method will return an BorderStyle enum in the future. - */ - @Override - public short getBorderBottom() { - return getBorderBottomEnum().getCode(); - } - /** - * @since POI 3.15 - */ - @Override - public BorderStyle getBorderBottomEnum() { - STBorderStyle.Enum ptrn = _border.isSetBottom() ? _border.getBottom().getStyle() : null; - return ptrn == null ? BorderStyle.NONE : BorderStyle.valueOf((short)(ptrn.intValue() - 1)); - } - - /** - * @deprecated POI 3.15. Use {@link #getBorderDiagonalEnum()}. - * This method will return an BorderStyle enum in the future. - */ - @Override - public short getBorderDiagonal() { - return getBorderDiagonalEnum().getCode(); - } - /** - * @since POI 3.15 - */ - @Override - public BorderStyle getBorderDiagonalEnum() { - STBorderStyle.Enum ptrn = _border.isSetDiagonal() ? _border.getDiagonal().getStyle() : null; - return ptrn == null ? BorderStyle.NONE : BorderStyle.valueOf((short)(ptrn.intValue() - 1)); - } - - /** - * @deprecated POI 3.15. Use {@link #getBorderLeftEnum()}. - * This method will return an BorderStyle enum in the future. - */ - @Override - public short getBorderLeft() { - return getBorderLeftEnum().getCode(); - } - /** - * @since POI 3.15 - */ - @Override - public BorderStyle getBorderLeftEnum() { - STBorderStyle.Enum ptrn = _border.isSetLeft() ? _border.getLeft().getStyle() : null; - return ptrn == null ? BorderStyle.NONE : BorderStyle.valueOf((short)(ptrn.intValue() - 1)); - } - - /** - * @deprecated POI 3.15. Use {@link #getBorderRightEnum()}. - * This method will return an BorderStyle enum in the future. - */ - @Override - public short getBorderRight() { - return getBorderRightEnum().getCode(); - } - /** - * @since POI 3.15 - */ - @Override - public BorderStyle getBorderRightEnum() { - STBorderStyle.Enum ptrn = _border.isSetRight() ? _border.getRight().getStyle() : null; - return ptrn == null ? BorderStyle.NONE : BorderStyle.valueOf((short)(ptrn.intValue() - 1)); - } - - /** - * @deprecated POI 3.15. Use {@link #getBorderTopEnum()}. - * This method will return an BorderStyle enum in the future. - */ - @Override - public short getBorderTop() { - return getBorderTopEnum().getCode(); - } - /** - * @since POI 3.15 - */ - @Override - public BorderStyle getBorderTopEnum() { - STBorderStyle.Enum ptrn = _border.isSetTop() ? _border.getTop().getStyle() : null; - return ptrn == null ? BorderStyle.NONE : BorderStyle.valueOf((short)(ptrn.intValue() - 1)); - } - - @Override - public XSSFColor getBottomBorderColorColor() { - if(!_border.isSetBottom()) return null; - - CTBorderPr pr = _border.getBottom(); - return new XSSFColor(pr.getColor()); - } - @Override - public short getBottomBorderColor() { - XSSFColor color = getBottomBorderColorColor(); - if (color == null) return 0; - return color.getIndexed(); - } - - @Override - public XSSFColor getDiagonalBorderColorColor() { - if(!_border.isSetDiagonal()) return null; - - CTBorderPr pr = _border.getDiagonal(); - return new XSSFColor(pr.getColor()); - } - @Override - public short getDiagonalBorderColor() { - XSSFColor color = getDiagonalBorderColorColor(); - if (color == null) return 0; - return color.getIndexed(); - } - - @Override - public XSSFColor getLeftBorderColorColor() { - if(!_border.isSetLeft()) return null; - - CTBorderPr pr = _border.getLeft(); - return new XSSFColor(pr.getColor()); - } - @Override - public short getLeftBorderColor() { - XSSFColor color = getLeftBorderColorColor(); - if (color == null) return 0; - return color.getIndexed(); - } - - @Override - public XSSFColor getRightBorderColorColor() { - if(!_border.isSetRight()) return null; - - CTBorderPr pr = _border.getRight(); - return new XSSFColor(pr.getColor()); - } - @Override - public short getRightBorderColor() { - XSSFColor color = getRightBorderColorColor(); - if (color == null) return 0; - return color.getIndexed(); - } - - @Override - public XSSFColor getTopBorderColorColor() { - if(!_border.isSetTop()) return null; - - CTBorderPr pr = _border.getTop(); - return new XSSFColor(pr.getColor()); - } - @Override - public short getTopBorderColor() { - XSSFColor color = getRightBorderColorColor(); - if (color == null) return 0; - return color.getIndexed(); - } - - /** - * @deprecated 3.15 beta 2. Use {@link #setBorderBottom(BorderStyle)} - */ - @Override - public void setBorderBottom(short border) { - setBorderBottom(BorderStyle.valueOf(border)); - } - @Override - public void setBorderBottom(BorderStyle border) { - CTBorderPr pr = _border.isSetBottom() ? _border.getBottom() : _border.addNewBottom(); - if(border == BorderStyle.NONE) _border.unsetBottom(); - else pr.setStyle(STBorderStyle.Enum.forInt(border.getCode() + 1)); - } - - /** - * @deprecated 3.15 beta 2. Use {@link #setBorderDiagonal(BorderStyle)} - */ - @Override - public void setBorderDiagonal(short border) { - setBorderDiagonal(BorderStyle.valueOf(border)); - } - @Override - public void setBorderDiagonal(BorderStyle border) { - CTBorderPr pr = _border.isSetDiagonal() ? _border.getDiagonal() : _border.addNewDiagonal(); - if(border == BorderStyle.NONE) _border.unsetDiagonal(); - else pr.setStyle(STBorderStyle.Enum.forInt(border.getCode() + 1)); - } - - /** - * @deprecated 3.15 beta 2. Use {@link #setBorderLeft(BorderStyle)} - */ - @Override - public void setBorderLeft(short border) { - setBorderLeft(BorderStyle.valueOf(border)); - } - @Override - public void setBorderLeft(BorderStyle border) { - CTBorderPr pr = _border.isSetLeft() ? _border.getLeft() : _border.addNewLeft(); - if(border == BorderStyle.NONE) _border.unsetLeft(); - else pr.setStyle(STBorderStyle.Enum.forInt(border.getCode() + 1)); - } - - /** - * @deprecated 3.15 beta 2. Use {@link #setBorderRight(BorderStyle)} - */ - @Override - public void setBorderRight(short border) { - setBorderRight(BorderStyle.valueOf(border)); - } - @Override - public void setBorderRight(BorderStyle border) { - CTBorderPr pr = _border.isSetRight() ? _border.getRight() : _border.addNewRight(); - if(border == BorderStyle.NONE) _border.unsetRight(); - else pr.setStyle(STBorderStyle.Enum.forInt(border.getCode() + 1)); - } - - /** - * @deprecated 3.15 beta 2. Use {@link #setBorderTop(BorderStyle)} - */ - @Override - public void setBorderTop(short border) { - setBorderTop(BorderStyle.valueOf(border)); - } - @Override - public void setBorderTop(BorderStyle border) { - CTBorderPr pr = _border.isSetTop() ? _border.getTop() : _border.addNewTop(); - if(border == BorderStyle.NONE) _border.unsetTop(); - else pr.setStyle(STBorderStyle.Enum.forInt(border.getCode() + 1)); - } - - @Override - public void setBottomBorderColor(Color color) { - XSSFColor xcolor = XSSFColor.toXSSFColor(color); - if (xcolor == null) setBottomBorderColor((CTColor)null); - else setBottomBorderColor(xcolor.getCTColor()); - } - @Override - public void setBottomBorderColor(short color) { - CTColor ctColor = CTColor.Factory.newInstance(); - ctColor.setIndexed(color); - setBottomBorderColor(ctColor); - } - public void setBottomBorderColor(CTColor color) { - CTBorderPr pr = _border.isSetBottom() ? _border.getBottom() : _border.addNewBottom(); - if (color == null) { - pr.unsetColor(); - } else { - pr.setColor(color); - } - } - - @Override - public void setDiagonalBorderColor(Color color) { - XSSFColor xcolor = XSSFColor.toXSSFColor(color); - if (xcolor == null) setDiagonalBorderColor((CTColor)null); - else setDiagonalBorderColor(xcolor.getCTColor()); - } - @Override - public void setDiagonalBorderColor(short color) { - CTColor ctColor = CTColor.Factory.newInstance(); - ctColor.setIndexed(color); - setDiagonalBorderColor(ctColor); - } - public void setDiagonalBorderColor(CTColor color) { - CTBorderPr pr = _border.isSetDiagonal() ? _border.getDiagonal() : _border.addNewDiagonal(); - if (color == null) { - pr.unsetColor(); - } else { - pr.setColor(color); - } - } - - @Override - public void setLeftBorderColor(Color color) { - XSSFColor xcolor = XSSFColor.toXSSFColor(color); - if (xcolor == null) setLeftBorderColor((CTColor)null); - else setLeftBorderColor(xcolor.getCTColor()); - } - @Override - public void setLeftBorderColor(short color) { - CTColor ctColor = CTColor.Factory.newInstance(); - ctColor.setIndexed(color); - setLeftBorderColor(ctColor); - } - public void setLeftBorderColor(CTColor color) { - CTBorderPr pr = _border.isSetLeft() ? _border.getLeft() : _border.addNewLeft(); - if (color == null) { - pr.unsetColor(); - } else { - pr.setColor(color); - } - } - - @Override - public void setRightBorderColor(Color color) { - XSSFColor xcolor = XSSFColor.toXSSFColor(color); - if (xcolor == null) setRightBorderColor((CTColor)null); - else setRightBorderColor(xcolor.getCTColor()); - } - @Override - public void setRightBorderColor(short color) { - CTColor ctColor = CTColor.Factory.newInstance(); - ctColor.setIndexed(color); - setRightBorderColor(ctColor); - } - public void setRightBorderColor(CTColor color) { - CTBorderPr pr = _border.isSetRight() ? _border.getRight() : _border.addNewRight(); - if (color == null) { - pr.unsetColor(); - } else { - pr.setColor(color); - } - } - - @Override - public void setTopBorderColor(Color color) { - XSSFColor xcolor = XSSFColor.toXSSFColor(color); - if (xcolor == null) setTopBorderColor((CTColor)null); - else setTopBorderColor(xcolor.getCTColor()); - } - @Override - public void setTopBorderColor(short color) { - CTColor ctColor = CTColor.Factory.newInstance(); - ctColor.setIndexed(color); - setTopBorderColor(ctColor); - } - public void setTopBorderColor(CTColor color) { - CTBorderPr pr = _border.isSetTop() ? _border.getTop() : _border.addNewTop(); - if (color == null) { - pr.unsetColor(); - } else { - pr.setColor(color); - } - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFCell.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFCell.java deleted file mode 100644 index e6d423e53..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFCell.java +++ /dev/null @@ -1,1317 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.Date; - -import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.ss.formula.FormulaParser; -import org.apache.poi.ss.formula.FormulaRenderer; -import org.apache.poi.ss.formula.FormulaType; -import org.apache.poi.ss.formula.SharedFormula; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellCopyPolicy; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.Comment; -import org.apache.poi.ss.usermodel.DataFormatter; -import org.apache.poi.ss.usermodel.DateUtil; -import org.apache.poi.ss.usermodel.FormulaError; -import org.apache.poi.ss.usermodel.Hyperlink; -import org.apache.poi.ss.usermodel.RichTextString; -import org.apache.poi.ss.usermodel.Row.MissingCellPolicy; -import org.apache.poi.ss.util.CellAddress; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.util.Beta; -import org.apache.poi.util.Internal; -import org.apache.poi.util.LocaleUtil; -import org.apache.poi.util.Removal; -import org.apache.poi.xssf.model.SharedStringsTable; -import org.apache.poi.xssf.model.StylesTable; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCell; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCellFormula; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STCellFormulaType; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STCellType; - -/** - * High level representation of a cell in a row of a spreadsheet. - *

    - * Cells can be numeric, formula-based or string-based (text). The cell type - * specifies this. String cells cannot contain numbers and numeric cells cannot - * contain strings (at least according to our model). Client apps should do the - * conversions themselves. Formula cells have the formula string, as well as - * the formula result, which can be numeric or string. - *

    - *

    - * Cells should have their number (0 based) before being added to a row. Only - * cells that have values should be added. - *

    - */ -public final class XSSFCell implements Cell { - - private static final String FALSE_AS_STRING = "0"; - private static final String TRUE_AS_STRING = "1"; - private static final String FALSE = "FALSE"; - private static final String TRUE = "TRUE"; - - /** - * the xml bean containing information about the cell's location, value, - * data type, formatting, and formula - */ - private CTCell _cell; - - /** - * the XSSFRow this cell belongs to - */ - private final XSSFRow _row; - - /** - * 0-based column index - */ - private int _cellNum; - - /** - * Table of strings shared across this workbook. - * If two cells contain the same string, then the cell value is the same index into SharedStringsTable - */ - private SharedStringsTable _sharedStringSource; - - /** - * Table of cell styles shared across all cells in a workbook. - */ - private StylesTable _stylesSource; - - /** - * Construct a XSSFCell. - * - * @param row the parent row. - * @param cell the xml bean containing information about the cell. - */ - protected XSSFCell(XSSFRow row, CTCell cell) { - _cell = cell; - _row = row; - if (cell.getR() != null) { - _cellNum = new CellReference(cell.getR()).getCol(); - } else { - int prevNum = row.getLastCellNum(); - if(prevNum != -1){ - _cellNum = row.getCell(prevNum-1, MissingCellPolicy.RETURN_NULL_AND_BLANK).getColumnIndex() + 1; - } - } - _sharedStringSource = row.getSheet().getWorkbook().getSharedStringSource(); - _stylesSource = row.getSheet().getWorkbook().getStylesSource(); - } - - /** - * Copy cell value, formula and style, from srcCell per cell copy policy - * If srcCell is null, clears the cell value and cell style per cell copy policy - * - * This does not shift references in formulas. Use {@link org.apache.poi.xssf.usermodel.helpers.XSSFRowShifter} to shift references in formulas. - * - * @param srcCell The cell to take value, formula and style from - * @param policy The policy for copying the information, see {@link CellCopyPolicy} - * @throws IllegalArgumentException if copy cell style and srcCell is from a different workbook - */ - @Beta - @Internal - public void copyCellFrom(Cell srcCell, CellCopyPolicy policy) { - // Copy cell value (cell type is updated implicitly) - if (policy.isCopyCellValue()) { - if (srcCell != null) { - CellType copyCellType = srcCell.getCellTypeEnum(); - if (copyCellType == CellType.FORMULA && !policy.isCopyCellFormula()) { - // Copy formula result as value - // FIXME: Cached value may be stale - copyCellType = srcCell.getCachedFormulaResultTypeEnum(); - } - switch (copyCellType) { - case NUMERIC: - // DataFormat is not copied unless policy.isCopyCellStyle is true - if (DateUtil.isCellDateFormatted(srcCell)) { - setCellValue(srcCell.getDateCellValue()); - } - else { - setCellValue(srcCell.getNumericCellValue()); - } - break; - case STRING: - setCellValue(srcCell.getStringCellValue()); - break; - case FORMULA: - setCellFormula(srcCell.getCellFormula()); - break; - case BLANK: - setBlank(); - break; - case BOOLEAN: - setCellValue(srcCell.getBooleanCellValue()); - break; - case ERROR: - setCellErrorValue(srcCell.getErrorCellValue()); - break; - - default: - throw new IllegalArgumentException("Invalid cell type " + srcCell.getCellTypeEnum()); - } - } else { //srcCell is null - setBlank(); - } - } - - // Copy CellStyle - if (policy.isCopyCellStyle()) { - setCellStyle(srcCell == null ? null : srcCell.getCellStyle()); - } - - final Hyperlink srcHyperlink = (srcCell == null) ? null : srcCell.getHyperlink(); - - if (policy.isMergeHyperlink()) { - // if srcCell doesn't have a hyperlink and destCell has a hyperlink, don't clear destCell's hyperlink - if (srcHyperlink != null) { - setHyperlink(new XSSFHyperlink(srcHyperlink)); - } - } else if (policy.isCopyHyperlink()) { - // overwrite the hyperlink at dest cell with srcCell's hyperlink - // if srcCell doesn't have a hyperlink, clear the hyperlink (if one exists) at destCell - setHyperlink(srcHyperlink == null ? null : new XSSFHyperlink(srcHyperlink)); - } - } - - /** - * @return table of strings shared across this workbook - */ - protected SharedStringsTable getSharedStringSource() { - return _sharedStringSource; - } - - /** - * @return table of cell styles shared across this workbook - */ - protected StylesTable getStylesSource() { - return _stylesSource; - } - - /** - * Returns the sheet this cell belongs to - * - * @return the sheet this cell belongs to - */ - @Override - public XSSFSheet getSheet() { - return getRow().getSheet(); - } - - /** - * Returns the row this cell belongs to - * - * @return the row this cell belongs to - */ - @Override - public XSSFRow getRow() { - return _row; - } - - /** - * Get the value of the cell as a boolean. - *

    - * For strings, numbers, and errors, we throw an exception. For blank cells we return a false. - *

    - * @return the value of the cell as a boolean - * @throws IllegalStateException if the cell type returned by {@link #getCellTypeEnum()} - * is not {@link CellType#BOOLEAN}, {@link CellType#BLANK} or {@link CellType#FORMULA} - */ - @Override - public boolean getBooleanCellValue() { - CellType cellType = getCellTypeEnum(); - switch(cellType) { - case BLANK: - return false; - case BOOLEAN: - return _cell.isSetV() && TRUE_AS_STRING.equals(_cell.getV()); - case FORMULA: - //YK: should throw an exception if requesting boolean value from a non-boolean formula - return _cell.isSetV() && TRUE_AS_STRING.equals(_cell.getV()); - default: - throw typeMismatch(CellType.BOOLEAN, cellType, false); - } - } - - /** - * Set a boolean value for the cell - * - * @param value the boolean value to set this cell to. For formulas we'll set the - * precalculated value, for booleans we'll set its value. For other types we - * will change the cell to a boolean cell and set its value. - */ - @Override - public void setCellValue(boolean value) { - _cell.setT(STCellType.B); - _cell.setV(value ? TRUE_AS_STRING : FALSE_AS_STRING); - } - - /** - * Get the value of the cell as a number. - *

    - * For strings we throw an exception. For blank cells we return a 0. - * For formulas or error cells we return the precalculated value; - *

    - * @return the value of the cell as a number - * @throws IllegalStateException if the cell type returned by {@link #getCellTypeEnum()} is {@link CellType#STRING} - * @exception NumberFormatException if the cell value isn't a parsable double. - * @see DataFormatter for turning this number into a string similar to that which Excel would render this number as. - */ - @Override - public double getNumericCellValue() { - CellType cellType = getCellTypeEnum(); - switch(cellType) { - case BLANK: - return 0.0; - case FORMULA: - // fall-through - case NUMERIC: - if(_cell.isSetV()) { - String v = _cell.getV(); - if (v.isEmpty()) { - return 0.0; - } - try { - return Double.parseDouble(v); - } catch(NumberFormatException e) { - throw typeMismatch(CellType.NUMERIC, CellType.STRING, false); - } - } else { - return 0.0; - } - default: - throw typeMismatch(CellType.NUMERIC, cellType, false); - } - } - - - /** - * Set a numeric value for the cell - * - * @param value the numeric value to set this cell to. For formulas we'll set the - * precalculated value, for numerics we'll set its value. For other types we - * will change the cell to a numeric cell and set its value. - */ - @Override - public void setCellValue(double value) { - if(Double.isInfinite(value)) { - // Excel does not support positive/negative infinities, - // rather, it gives a #DIV/0! error in these cases. - _cell.setT(STCellType.E); - _cell.setV(FormulaError.DIV0.getString()); - } else if (Double.isNaN(value)){ - // Excel does not support Not-a-Number (NaN), - // instead it immediately generates an #NUM! error. - _cell.setT(STCellType.E); - _cell.setV(FormulaError.NUM.getString()); - } else { - _cell.setT(STCellType.N); - _cell.setV(String.valueOf(value)); - } - } - - /** - * Get the value of the cell as a string - *

    - * For numeric cells we throw an exception. For blank cells we return an empty string. - * For formulaCells that are not string Formulas, we throw an exception - *

    - * @return the value of the cell as a string - */ - @Override - public String getStringCellValue() { - return getRichStringCellValue().getString(); - } - - /** - * Get the value of the cell as a XSSFRichTextString - *

    - * For numeric cells we throw an exception. For blank cells we return an empty string. - * For formula cells we return the pre-calculated value if a string, otherwise an exception - *

    - * @return the value of the cell as a XSSFRichTextString - */ - @Override - public XSSFRichTextString getRichStringCellValue() { - CellType cellType = getCellTypeEnum(); - XSSFRichTextString rt; - switch (cellType) { - case BLANK: - rt = new XSSFRichTextString(""); - break; - case STRING: - if (_cell.getT() == STCellType.INLINE_STR) { - if(_cell.isSetIs()) { - //string is expressed directly in the cell definition instead of implementing the shared string table. - rt = new XSSFRichTextString(_cell.getIs()); - } else if (_cell.isSetV()) { - //cached result of a formula - rt = new XSSFRichTextString(_cell.getV()); - } else { - rt = new XSSFRichTextString(""); - } - } else if (_cell.getT() == STCellType.STR) { - //cached formula value - rt = new XSSFRichTextString(_cell.isSetV() ? _cell.getV() : ""); - } else { - if (_cell.isSetV()) { - int idx = Integer.parseInt(_cell.getV()); - rt = new XSSFRichTextString(_sharedStringSource.getEntryAt(idx)); - } - else { - rt = new XSSFRichTextString(""); - } - } - break; - case FORMULA: - checkFormulaCachedValueType(CellType.STRING, getBaseCellType(false)); - rt = new XSSFRichTextString(_cell.isSetV() ? _cell.getV() : ""); - break; - default: - throw typeMismatch(CellType.STRING, cellType, false); - } - rt.setStylesTableReference(_stylesSource); - return rt; - } - - private static void checkFormulaCachedValueType(CellType expectedTypeCode, CellType cachedValueType) { - if (cachedValueType != expectedTypeCode) { - throw typeMismatch(expectedTypeCode, cachedValueType, true); - } - } - - /** - * Set a string value for the cell. - * - * @param str value to set the cell to. For formulas we'll set the formula - * cached string result, for String cells we'll set its value. For other types we will - * change the cell to a string cell and set its value. - * If value is null then we will change the cell to a Blank cell. - */ - @Override - public void setCellValue(String str) { - setCellValue(str == null ? null : new XSSFRichTextString(str)); - } - - /** - * Set a string value for the cell. - * - * @param str value to set the cell to. For formulas we'll set the 'pre-evaluated result string, - * for String cells we'll set its value. For other types we will - * change the cell to a string cell and set its value. - * If value is null then we will change the cell to a Blank cell. - */ - @Override - public void setCellValue(RichTextString str) { - if(str == null || str.getString() == null){ - setCellType(CellType.BLANK); - return; - } - - if(str.length() > SpreadsheetVersion.EXCEL2007.getMaxTextLength()){ - throw new IllegalArgumentException("The maximum length of cell contents (text) is 32,767 characters"); - } - - CellType cellType = getCellTypeEnum(); - switch (cellType){ - case FORMULA: - _cell.setV(str.getString()); - _cell.setT(STCellType.STR); - break; - default: - if(_cell.getT() == STCellType.INLINE_STR) { - //set the 'pre-evaluated result - _cell.setV(str.getString()); - } else { - _cell.setT(STCellType.S); - XSSFRichTextString rt = (XSSFRichTextString)str; - rt.setStylesTableReference(_stylesSource); - int sRef = _sharedStringSource.addEntry(rt.getCTRst()); - _cell.setV(Integer.toString(sRef)); - } - break; - } - } - - /** - * Return a formula for the cell, for example, SUM(C4:E4) - * - * @return a formula for the cell - * @throws IllegalStateException if the cell type returned by {@link #getCellTypeEnum()} is not {@link CellType#FORMULA} - */ - @Override - public String getCellFormula() { - // existing behavior - create a new XSSFEvaluationWorkbook for every call - return getCellFormula(null); - } - - /** - * package/hierarchy use only - reuse an existing evaluation workbook if available for caching - * - * @param fpb evaluation workbook for reuse, if available, or null to create a new one as needed - * @return a formula for the cell - * @throws IllegalStateException if the cell type returned by {@link #getCellTypeEnum()} is not {@link CellType#FORMULA} - */ - protected String getCellFormula(XSSFEvaluationWorkbook fpb) { - CellType cellType = getCellTypeEnum(); - if(cellType != CellType.FORMULA) { - throw typeMismatch(CellType.FORMULA, cellType, false); - } - - CTCellFormula f = _cell.getF(); - if (isPartOfArrayFormulaGroup() && f == null) { - XSSFCell cell = getSheet().getFirstCellInArrayFormula(this); - return cell.getCellFormula(fpb); - } - if (f.getT() == STCellFormulaType.SHARED) { - return convertSharedFormula((int)f.getSi(), fpb == null ? XSSFEvaluationWorkbook.create(getSheet().getWorkbook()) : fpb); - } - return f.getStringValue(); - } - - /** - * Creates a non shared formula from the shared formula counterpart - * - * @param si Shared Group Index - * @return non shared formula created for the given shared formula and this cell - */ - private String convertSharedFormula(int si, XSSFEvaluationWorkbook fpb){ - XSSFSheet sheet = getSheet(); - - CTCellFormula f = sheet.getSharedFormula(si); - if(f == null) { - throw new IllegalStateException( - "Master cell of a shared formula with sid="+si+" was not found"); - } - - String sharedFormula = f.getStringValue(); - //Range of cells which the shared formula applies to - String sharedFormulaRange = f.getRef(); - - CellRangeAddress ref = CellRangeAddress.valueOf(sharedFormulaRange); - - int sheetIndex = sheet.getWorkbook().getSheetIndex(sheet); - SharedFormula sf = new SharedFormula(SpreadsheetVersion.EXCEL2007); - - Ptg[] ptgs = FormulaParser.parse(sharedFormula, fpb, FormulaType.CELL, sheetIndex, getRowIndex()); - Ptg[] fmla = sf.convertSharedFormulas(ptgs, - getRowIndex() - ref.getFirstRow(), getColumnIndex() - ref.getFirstColumn()); - return FormulaRenderer.toFormulaString(fpb, fmla); - } - - /** - * Sets formula for this cell. - *

    - * Note, this method only sets the formula string and does not calculate the formula value. - * To set the precalculated value use {@link #setCellValue(double)} or {@link #setCellValue(String)} - *

    - * - * @param formula the formula to set, e.g. "SUM(C4:E4)". - * If the argument is null then the current formula is removed. - * @throws org.apache.poi.ss.formula.FormulaParseException if the formula has incorrect syntax or is otherwise invalid - * @throws IllegalStateException if the operation is not allowed, for example, - * when the cell is a part of a multi-cell array formula - */ - @Override - public void setCellFormula(String formula) { - if(isPartOfArrayFormulaGroup()){ - notifyArrayFormulaChanging(); - } - setFormula(formula, FormulaType.CELL); - } - - /* package */ void setCellArrayFormula(String formula, CellRangeAddress range) { - setFormula(formula, FormulaType.ARRAY); - CTCellFormula cellFormula = _cell.getF(); - cellFormula.setT(STCellFormulaType.ARRAY); - cellFormula.setRef(range.formatAsString()); - } - - private void setFormula(String formula, FormulaType formulaType) { - XSSFWorkbook wb = _row.getSheet().getWorkbook(); - if (formula == null) { - wb.onDeleteFormula(this); - if(_cell.isSetF()) { - _cell.unsetF(); - } - return; - } - - if(wb.getCellFormulaValidation()) { - XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(wb); - //validate through the FormulaParser - FormulaParser.parse(formula, fpb, formulaType, wb.getSheetIndex(getSheet()), getRowIndex()); - } - - CTCellFormula f = CTCellFormula.Factory.newInstance(); - f.setStringValue(formula); - _cell.setF(f); - if(_cell.isSetV()) { - _cell.unsetV(); - } - } - - /** - * Returns column index of this cell - * - * @return zero-based column index of a column in a sheet. - */ - @Override - public int getColumnIndex() { - return this._cellNum; - } - - /** - * Returns row index of a row in the sheet that contains this cell - * - * @return zero-based row index of a row in the sheet that contains this cell - */ - @Override - public int getRowIndex() { - return _row.getRowNum(); - } - - /** - * Returns an A1 style reference to the location of this cell - * - * @return A1 style reference to the location of this cell - */ - public String getReference() { - String ref = _cell.getR(); - if(ref == null) { - return getAddress().formatAsString(); - } - return ref; - } - - /** - * {@inheritDoc} - */ - @Override - public CellAddress getAddress() { - return new CellAddress(this); - } - - /** - * Return the cell's style. - * - * @return the cell's style. - */ - @Override - public XSSFCellStyle getCellStyle() { - XSSFCellStyle style = null; - if(_stylesSource.getNumCellStyles() > 0){ - long idx = _cell.isSetS() ? _cell.getS() : 0; - style = _stylesSource.getStyleAt((int)idx); - } - return style; - } - - /** - *

    Set the style for the cell. The style should be an XSSFCellStyle created/retreived from - * the XSSFWorkbook.

    - * - *

    To change the style of a cell without affecting other cells that use the same style, - * use {@link org.apache.poi.ss.util.CellUtil#setCellStyleProperties(Cell, java.util.Map)}

    - * - * @param style reference contained in the workbook. - * If the value is null then the style information is removed causing the cell to used the default workbook style. - * @throws IllegalArgumentException if style belongs to a different styles source (most likely because style is from a different Workbook) - */ - @Override - public void setCellStyle(CellStyle style) { - if(style == null) { - if(_cell.isSetS()) { - _cell.unsetS(); - } - } else { - XSSFCellStyle xStyle = (XSSFCellStyle)style; - xStyle.verifyBelongsToStylesSource(_stylesSource); - - long idx = _stylesSource.putStyle(xStyle); - _cell.setS(idx); - } - } - - private boolean isFormulaCell() { - if (_cell.getF() != null || getSheet().isCellInArrayFormulaContext(this)) { - return true; - } - return false; - } - - /** - * Return the cell type. - * - * Will return {@link CellType} in a future version of POI. - * For forwards compatibility, do not hard-code cell type literals in your code. - * - * @return the cell type - * @deprecated 3.15. Will return a {@link CellType} enum in the future. - */ - @Deprecated - @Override - @Removal(version="3.17") - public int getCellType() { - return getCellTypeEnum().getCode(); - } - - /** - * Return the cell type. - * - * @return the cell type - * @since POI 3.15 beta 3 - * Will be deleted when we make the CellType enum transition. See bug 59791. - */ - @Override - public CellType getCellTypeEnum() { - if (isFormulaCell()) { - return CellType.FORMULA; - } - - return getBaseCellType(true); - } - - /** - * Only valid for formula cells - * - * Will return {@link CellType} in a future version of POI. - * For forwards compatibility, do not hard-code cell type literals in your code. - * - * @return one of ({@link CellType#NUMERIC}, {@link CellType#STRING}, - * {@link CellType#BOOLEAN}, {@link CellType#ERROR}) depending - * on the cached value of the formula - * @deprecated 3.15. Will return a {@link CellType} enum in the future. - */ - @Deprecated - @Override - @Removal(version="3.17") - public int getCachedFormulaResultType() { - return getCachedFormulaResultTypeEnum().getCode(); - } - - /** - * Only valid for formula cells - * @return one of ({@link CellType#NUMERIC}, {@link CellType#STRING}, - * {@link CellType#BOOLEAN}, {@link CellType#ERROR}) depending - * on the cached value of the formula - * @since POI 3.15 beta 3 - * Will be deleted when we make the CellType enum transition. See bug 59791. - */ - @Override - public CellType getCachedFormulaResultTypeEnum() { - if (! isFormulaCell()) { - throw new IllegalStateException("Only formula cells have cached results"); - } - - return getBaseCellType(false); - } - - /** - * Detect cell type based on the "t" attribute of the CTCell bean - */ - private CellType getBaseCellType(boolean blankCells) { - switch (_cell.getT().intValue()) { - case STCellType.INT_B: - return CellType.BOOLEAN; - case STCellType.INT_N: - if (!_cell.isSetV() && blankCells) { - // ooxml does have a separate cell type of 'blank'. A blank cell gets encoded as - // (either not present or) a numeric cell with no value set. - // The formula evaluator (and perhaps other clients of this interface) needs to - // distinguish blank values which sometimes get translated into zero and sometimes - // empty string, depending on context - return CellType.BLANK; - } - return CellType.NUMERIC; - case STCellType.INT_E: - return CellType.ERROR; - case STCellType.INT_S: // String is in shared strings - case STCellType.INT_INLINE_STR: // String is inline in cell - case STCellType.INT_STR: - return CellType.STRING; - default: - throw new IllegalStateException("Illegal cell type: " + this._cell.getT()); - } - } - - /** - * Get the value of the cell as a date. - *

    - * For strings we throw an exception. For blank cells we return a null. - *

    - * @return the value of the cell as a date - * @throws IllegalStateException if the cell type returned by {@link #getCellTypeEnum()} is {@link CellType#STRING} - * @exception NumberFormatException if the cell value isn't a parsable double. - * @see DataFormatter for formatting this date into a string similar to how excel does. - */ - @Override - public Date getDateCellValue() { - if (getCellTypeEnum() == CellType.BLANK) { - return null; - } - - double value = getNumericCellValue(); - boolean date1904 = getSheet().getWorkbook().isDate1904(); - return DateUtil.getJavaDate(value, date1904); - } - - /** - * Set a date value for the cell. Excel treats dates as numeric so you will need to format the cell as - * a date. - * - * @param value the date value to set this cell to. For formulas we'll set the - * precalculated value, for numerics we'll set its value. For other types we - * will change the cell to a numeric cell and set its value. - */ - @Override - public void setCellValue(Date value) { - if(value == null) { - setCellType(CellType.BLANK); - return; - } - - boolean date1904 = getSheet().getWorkbook().isDate1904(); - setCellValue(DateUtil.getExcelDate(value, date1904)); - } - - /** - * Set a date value for the cell. Excel treats dates as numeric so you will need to format the cell as - * a date. - *

    - * This will set the cell value based on the Calendar's timezone. As Excel - * does not support timezones this means that both 20:00+03:00 and - * 20:00-03:00 will be reported as the same value (20:00) even that there - * are 6 hours difference between the two times. This difference can be - * preserved by using setCellValue(value.getTime()) which will - * automatically shift the times to the default timezone. - *

    - * - * @param value the date value to set this cell to. For formulas we'll set the - * precalculated value, for numerics we'll set its value. For othertypes we - * will change the cell to a numeric cell and set its value. - */ - @Override - public void setCellValue(Calendar value) { - if(value == null) { - setCellType(CellType.BLANK); - return; - } - - boolean date1904 = getSheet().getWorkbook().isDate1904(); - setCellValue( DateUtil.getExcelDate(value, date1904 )); - } - - /** - * Returns the error message, such as #VALUE! - * - * @return the error message such as #VALUE! - * @throws IllegalStateException if the cell type returned by {@link #getCellTypeEnum()} isn't {@link CellType#ERROR} - * @see FormulaError - */ - public String getErrorCellString() throws IllegalStateException { - CellType cellType = getBaseCellType(true); - if(cellType != CellType.ERROR) { - throw typeMismatch(CellType.ERROR, cellType, false); - } - - return _cell.getV(); - } - /** - * Get the value of the cell as an error code. - *

    - * For strings, numbers, and booleans, we throw an exception. - * For blank cells we return a 0. - *

    - * - * @return the value of the cell as an error code - * @throws IllegalStateException if the cell type returned by {@link #getCellTypeEnum()} isn't {@link CellType #ERROR} - * @see FormulaError - */ - @Override - public byte getErrorCellValue() throws IllegalStateException { - String code = getErrorCellString(); - if (code == null) { - return 0; - } - try { - return FormulaError.forString(code).getCode(); - } catch (final IllegalArgumentException e) { - throw new IllegalStateException("Unexpected error code", e); - } - } - - /** - * Set a error value for the cell - * - * @param errorCode the error value to set this cell to. For formulas we'll set the - * precalculated value , for errors we'll set - * its value. For other types we will change the cell to an error - * cell and set its value. - * @see FormulaError - */ - @Override - public void setCellErrorValue(byte errorCode) { - FormulaError error = FormulaError.forInt(errorCode); - setCellErrorValue(error); - } - - /** - * Set a error value for the cell - * - * @param error the error value to set this cell to. For formulas we'll set the - * precalculated value , for errors we'll set - * its value. For other types we will change the cell to an error - * cell and set its value. - */ - public void setCellErrorValue(FormulaError error) { - _cell.setT(STCellType.E); - _cell.setV(error.getString()); - } - - /** - * {@inheritDoc} - */ - @Override - public void setAsActiveCell() { - getSheet().setActiveCell(getAddress()); - } - - /** - * Blanks this cell. Blank cells have no formula or value but may have styling. - * This method erases all the data previously associated with this cell. - */ - private void setBlank(){ - CTCell blank = CTCell.Factory.newInstance(); - blank.setR(_cell.getR()); - if(_cell.isSetS()) { - blank.setS(_cell.getS()); - } - _cell.set(blank); - } - - /** - * Sets column index of this cell - * - * @param num column index of this cell - */ - protected void setCellNum(int num) { - checkBounds(num); - _cellNum = num; - String ref = new CellReference(getRowIndex(), getColumnIndex()).formatAsString(); - _cell.setR(ref); - } - - /** - * Set the cells type (numeric, formula or string) - * - * @throws IllegalArgumentException if the specified cell type is invalid - * @see CellType#NUMERIC - * @see CellType#STRING - * @see CellType#FORMULA - * @see CellType#BLANK - * @see CellType#BOOLEAN - * @see CellType#ERROR - * @deprecated POI 3.15 beta 3. Use {@link #setCellType(CellType)} instead. - */ - @Deprecated - @Override - @Removal(version="3.17") - public void setCellType(int cellType) { - setCellType(CellType.forInt(cellType)); - } - /** - * Set the cells type (numeric, formula or string) - * - * @throws IllegalArgumentException if the specified cell type is invalid - */ - @Override - public void setCellType(CellType cellType) { - CellType prevType = getCellTypeEnum(); - - if(isPartOfArrayFormulaGroup()){ - notifyArrayFormulaChanging(); - } - if(prevType == CellType.FORMULA && cellType != CellType.FORMULA) { - getSheet().getWorkbook().onDeleteFormula(this); - } - - switch (cellType) { - case NUMERIC: - _cell.setT(STCellType.N); - break; - case STRING: - if(prevType != CellType.STRING){ - String str = convertCellValueToString(); - XSSFRichTextString rt = new XSSFRichTextString(str); - rt.setStylesTableReference(_stylesSource); - int sRef = _sharedStringSource.addEntry(rt.getCTRst()); - _cell.setV(Integer.toString(sRef)); - } - _cell.setT(STCellType.S); - break; - case FORMULA: - if(!_cell.isSetF()){ - CTCellFormula f = CTCellFormula.Factory.newInstance(); - f.setStringValue("0"); - _cell.setF(f); - if(_cell.isSetT()) { - _cell.unsetT(); - } - } - break; - case BLANK: - setBlank(); - break; - case BOOLEAN: - String newVal = convertCellValueToBoolean() ? TRUE_AS_STRING : FALSE_AS_STRING; - _cell.setT(STCellType.B); - _cell.setV(newVal); - break; - - case ERROR: - _cell.setT(STCellType.E); - break; - - - default: - throw new IllegalArgumentException("Illegal cell type: " + cellType); - } - if (cellType != CellType.FORMULA && _cell.isSetF()) { - _cell.unsetF(); - } - } - - /** - * Returns a string representation of the cell - *

    - * Formula cells return the formula string, rather than the formula result. - * Dates are displayed in dd-MMM-yyyy format - * Errors are displayed as #ERR<errIdx> - *

    - */ - @Override - public String toString() { - switch (getCellTypeEnum()) { - case NUMERIC: - if (DateUtil.isCellDateFormatted(this)) { - DateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy", LocaleUtil.getUserLocale()); - sdf.setTimeZone(LocaleUtil.getUserTimeZone()); - return sdf.format(getDateCellValue()); - } - return Double.toString(getNumericCellValue()); - case STRING: - return getRichStringCellValue().toString(); - case FORMULA: - return getCellFormula(); - case BLANK: - return ""; - case BOOLEAN: - return getBooleanCellValue() ? TRUE : FALSE; - case ERROR: - return ErrorEval.getText(getErrorCellValue()); - default: - return "Unknown Cell Type: " + getCellTypeEnum(); - } - } - - /** - * Returns the raw, underlying ooxml value for the cell - *

    - * If the cell contains a string, then this value is an index into - * the shared string table, pointing to the actual string value. Otherwise, - * the value of the cell is expressed directly in this element. Cells containing formulas express - * the last calculated result of the formula in this element. - *

    - * - * @return the raw cell value as contained in the underlying CTCell bean, - * null for blank cells. - */ - public String getRawValue() { - return _cell.getV(); - } - - - /** - * Used to help format error messages - */ - private static RuntimeException typeMismatch(CellType expectedType, CellType actualType, boolean isFormulaCell) { - String msg = "Cannot get a " + expectedType + " value from a " + actualType+ " " + (isFormulaCell ? "formula " : "") + "cell"; - return new IllegalStateException(msg); - } - - /** - * @throws RuntimeException if the bounds are exceeded. - */ - private static void checkBounds(int cellIndex) { - SpreadsheetVersion v = SpreadsheetVersion.EXCEL2007; - int maxcol = SpreadsheetVersion.EXCEL2007.getLastColumnIndex(); - if (cellIndex < 0 || cellIndex > maxcol) { - throw new IllegalArgumentException("Invalid column index (" + cellIndex - + "). Allowable column range for " + v.name() + " is (0.." - + maxcol + ") or ('A'..'" + v.getLastColumnName() + "')"); - } - } - - /** - * Returns cell comment associated with this cell - * - * @return the cell comment associated with this cell or null - */ - @Override - public XSSFComment getCellComment() { - return getSheet().getCellComment(new CellAddress(this)); - } - - /** - * Assign a comment to this cell. If the supplied comment is null, - * the comment for this cell will be removed. - * - * @param comment the XSSFComment associated with this cell - */ - @Override - public void setCellComment(Comment comment) { - if(comment == null) { - removeCellComment(); - return; - } - - comment.setAddress(getRowIndex(), getColumnIndex()); - } - - /** - * Removes the comment for this cell, if there is one. - */ - @Override - public void removeCellComment() { - XSSFComment comment = getCellComment(); - if(comment != null){ - CellAddress ref = new CellAddress(getReference()); - XSSFSheet sh = getSheet(); - sh.getCommentsTable(false).removeComment(ref); - sh.getVMLDrawing(false).removeCommentShape(getRowIndex(), getColumnIndex()); - } - } - - /** - * Returns hyperlink associated with this cell - * - * @return hyperlink associated with this cell or null if not found - */ - @Override - public XSSFHyperlink getHyperlink() { - return getSheet().getHyperlink(_row.getRowNum(), _cellNum); - } - - /** - * Assign a hyperlink to this cell. If the supplied hyperlink is null, the - * hyperlink for this cell will be removed. - * - * @param hyperlink the hyperlink to associate with this cell - */ - @Override - public void setHyperlink(Hyperlink hyperlink) { - if (hyperlink == null) { - removeHyperlink(); - return; - } - - XSSFHyperlink link = (XSSFHyperlink)hyperlink; - - // Assign to us - link.setCellReference( new CellReference(_row.getRowNum(), _cellNum).formatAsString() ); - - // Add to the lists - getSheet().addHyperlink(link); - } - - /** - * Removes the hyperlink for this cell, if there is one. - */ - @Override - public void removeHyperlink() { - getSheet().removeHyperlink(_row.getRowNum(), _cellNum); - } - - /** - * Returns the xml bean containing information about the cell's location (reference), value, - * data type, formatting, and formula - * - * @return the xml bean containing information about this cell - */ - @Internal - public CTCell getCTCell(){ - return _cell; - } - - /** - * Set a new internal xml bean. This is only for internal use, do not call this from outside! - * - * This is necessary in some rare cases to work around XMLBeans specialties. - */ - @Internal - public void setCTCell(CTCell cell) { - _cell = cell; - } - - /** - * Chooses a new boolean value for the cell when its type is changing.

    - * - * Usually the caller is calling setCellType() with the intention of calling - * setCellValue(boolean) straight afterwards. This method only exists to give - * the cell a somewhat reasonable value until the setCellValue() call (if at all). - * TODO - perhaps a method like setCellTypeAndValue(int, Object) should be introduced to avoid this - */ - private boolean convertCellValueToBoolean() { - CellType cellType = getCellTypeEnum(); - - if (cellType == CellType.FORMULA) { - cellType = getBaseCellType(false); - } - - switch (cellType) { - case BOOLEAN: - return TRUE_AS_STRING.equals(_cell.getV()); - case STRING: - int sstIndex = Integer.parseInt(_cell.getV()); - XSSFRichTextString rt = new XSSFRichTextString(_sharedStringSource.getEntryAt(sstIndex)); - String text = rt.getString(); - return Boolean.parseBoolean(text); - case NUMERIC: - return Double.parseDouble(_cell.getV()) != 0; - - case ERROR: - // fall-through - case BLANK: - return false; - - default: - throw new RuntimeException("Unexpected cell type (" + cellType + ")"); - } - } - - private String convertCellValueToString() { - CellType cellType = getCellTypeEnum(); - - switch (cellType) { - case BLANK: - return ""; - case BOOLEAN: - return TRUE_AS_STRING.equals(_cell.getV()) ? TRUE : FALSE; - case STRING: - int sstIndex = Integer.parseInt(_cell.getV()); - XSSFRichTextString rt = new XSSFRichTextString(_sharedStringSource.getEntryAt(sstIndex)); - return rt.getString(); - case NUMERIC: - case ERROR: - return _cell.getV(); - case FORMULA: - // should really evaluate, but HSSFCell can't call HSSFFormulaEvaluator - // just use cached formula result instead - break; - default: - throw new IllegalStateException("Unexpected cell type (" + cellType + ")"); - } - cellType = getBaseCellType(false); - String textValue = _cell.getV(); - switch (cellType) { - case BOOLEAN: - if (TRUE_AS_STRING.equals(textValue)) { - return TRUE; - } - if (FALSE_AS_STRING.equals(textValue)) { - return FALSE; - } - throw new IllegalStateException("Unexpected boolean cached formula value '" - + textValue + "'."); - - case STRING: - // fall-through - case NUMERIC: - // fall-through - case ERROR: - return textValue; - - default: - throw new IllegalStateException("Unexpected formula result type (" + cellType + ")"); - } - - } - - @Override - public CellRangeAddress getArrayFormulaRange() { - XSSFCell cell = getSheet().getFirstCellInArrayFormula(this); - if (cell == null) { - throw new IllegalStateException("Cell " + getReference() - + " is not part of an array formula."); - } - String formulaRef = cell._cell.getF().getRef(); - return CellRangeAddress.valueOf(formulaRef); - } - - @Override - public boolean isPartOfArrayFormulaGroup() { - return getSheet().isCellInArrayFormulaContext(this); - } - - /** - * The purpose of this method is to validate the cell state prior to modification - * - * @see #notifyArrayFormulaChanging() - */ - void notifyArrayFormulaChanging(String msg){ - if(isPartOfArrayFormulaGroup()){ - CellRangeAddress cra = getArrayFormulaRange(); - if(cra.getNumberOfCells() > 1) { - throw new IllegalStateException(msg); - } - //un-register the single-cell array formula from the parent XSSFSheet - getRow().getSheet().removeArrayFormula(this); - } - } - - /** - * Called when this cell is modified. - *

    - * The purpose of this method is to validate the cell state prior to modification. - *

    - * - * @see #setCellType(int) - * @see #setCellFormula(String) - * @see XSSFRow#removeCell(org.apache.poi.ss.usermodel.Cell) - * @see org.apache.poi.xssf.usermodel.XSSFSheet#removeRow(org.apache.poi.ss.usermodel.Row) - * @see org.apache.poi.xssf.usermodel.XSSFSheet#shiftRows(int, int, int) - * @see org.apache.poi.xssf.usermodel.XSSFSheet#addMergedRegion(org.apache.poi.ss.util.CellRangeAddress) - * @throws IllegalStateException if modification is not allowed - */ - void notifyArrayFormulaChanging(){ - CellReference ref = new CellReference(this); - String msg = "Cell "+ref.formatAsString()+" is part of a multi-cell array formula. " + - "You cannot change part of an array."; - notifyArrayFormulaChanging(msg); - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFCellStyle.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFCellStyle.java deleted file mode 100644 index 6e66f9926..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFCellStyle.java +++ /dev/null @@ -1,1522 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import static org.apache.poi.POIXMLTypeLoader.DEFAULT_XML_OPTIONS; - -import org.apache.poi.POIXMLException; -import org.apache.poi.ss.usermodel.BorderStyle; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.FillPatternType; -import org.apache.poi.ss.usermodel.Font; -import org.apache.poi.ss.usermodel.HorizontalAlignment; -import org.apache.poi.ss.usermodel.IndexedColors; -import org.apache.poi.ss.usermodel.VerticalAlignment; -import org.apache.poi.util.Internal; -import org.apache.poi.util.Removal; -import org.apache.poi.xssf.model.StylesTable; -import org.apache.poi.xssf.model.ThemesTable; -import org.apache.poi.xssf.usermodel.extensions.XSSFCellAlignment; -import org.apache.poi.xssf.usermodel.extensions.XSSFCellBorder; -import org.apache.poi.xssf.usermodel.extensions.XSSFCellBorder.BorderSide; -import org.apache.poi.xssf.usermodel.extensions.XSSFCellFill; -import org.apache.xmlbeans.XmlException; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTBorder; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTBorderPr; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCellAlignment; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTFill; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTFont; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPatternFill; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTXf; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STBorderStyle; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STPatternType; - -/** - * - * High level representation of the the possible formatting information for the contents of the cells on a sheet in a - * SpreadsheetML document. - * - * @see org.apache.poi.xssf.usermodel.XSSFWorkbook#createCellStyle() - * @see org.apache.poi.xssf.usermodel.XSSFWorkbook#getCellStyleAt(int) - * @see org.apache.poi.xssf.usermodel.XSSFCell#setCellStyle(org.apache.poi.ss.usermodel.CellStyle) - */ -public class XSSFCellStyle implements CellStyle { - - private int _cellXfId; - private final StylesTable _stylesSource; - private CTXf _cellXf; - private final CTXf _cellStyleXf; - private XSSFFont _font; - private XSSFCellAlignment _cellAlignment; - private ThemesTable _theme; - - /** - * Creates a Cell Style from the supplied parts - * @param cellXfId The main XF for the cell. Must be a valid 0-based index into the XF table - * @param cellStyleXfId Optional, style xf. A value of -1 means no xf. - * @param stylesSource Styles Source to work off - */ - public XSSFCellStyle(int cellXfId, int cellStyleXfId, StylesTable stylesSource, ThemesTable theme) { - _cellXfId = cellXfId; - _stylesSource = stylesSource; - _cellXf = stylesSource.getCellXfAt(this._cellXfId); - _cellStyleXf = cellStyleXfId == -1 ? null : stylesSource.getCellStyleXfAt(cellStyleXfId); - _theme = theme; - } - - /** - * Used so that StylesSource can figure out our location - */ - @Internal - public CTXf getCoreXf() { - return _cellXf; - } - - /** - * Used so that StylesSource can figure out our location - */ - @Internal - public CTXf getStyleXf() { - return _cellStyleXf; - } - - /** - * Creates an empty Cell Style - */ - public XSSFCellStyle(StylesTable stylesSource) { - _stylesSource = stylesSource; - // We need a new CTXf for the main styles - // TODO decide on a style ctxf - _cellXf = CTXf.Factory.newInstance(); - _cellStyleXf = null; - } - - /** - * Verifies that this style belongs to the supplied Workbook - * Styles Source. - * Will throw an exception if it belongs to a different one. - * This is normally called when trying to assign a style to a - * cell, to ensure the cell and the style are from the same - * workbook (if they're not, it won't work) - * @throws IllegalArgumentException if there's a workbook mis-match - */ - public void verifyBelongsToStylesSource(StylesTable src) { - if(this._stylesSource != src) { - throw new IllegalArgumentException("This Style does not belong to the supplied Workbook Stlyes Source. Are you trying to assign a style from one workbook to the cell of a differnt workbook?"); - } - } - - /** - * Clones all the style information from another - * XSSFCellStyle, onto this one. This - * XSSFCellStyle will then have all the same - * properties as the source, but the two may - * be edited independently. - * Any stylings on this XSSFCellStyle will be lost! - * - * The source XSSFCellStyle could be from another - * XSSFWorkbook if you like. This allows you to - * copy styles from one XSSFWorkbook to another. - */ - @Override - public void cloneStyleFrom(CellStyle source) { - if(source instanceof XSSFCellStyle) { - XSSFCellStyle src = (XSSFCellStyle)source; - - // Is it on our Workbook? - if(src._stylesSource == _stylesSource) { - // Nice and easy - _cellXf.set(src.getCoreXf()); - _cellStyleXf.set(src.getStyleXf()); - } else { - // Copy the style - try { - // Remove any children off the current style, to - // avoid orphaned nodes - if(_cellXf.isSetAlignment()) - _cellXf.unsetAlignment(); - if(_cellXf.isSetExtLst()) - _cellXf.unsetExtLst(); - - // Create a new Xf with the same contents - _cellXf = CTXf.Factory.parse( - src.getCoreXf().toString(), DEFAULT_XML_OPTIONS - ); - - // bug 56295: ensure that the fills is available and set correctly - CTFill fill = CTFill.Factory.parse( - src.getCTFill().toString(), DEFAULT_XML_OPTIONS - ); - addFill(fill); - - // bug 58084: set borders correctly - CTBorder border = CTBorder.Factory.parse( - src.getCTBorder().toString(), DEFAULT_XML_OPTIONS - ); - addBorder(border); - - // Swap it over - _stylesSource.replaceCellXfAt(_cellXfId, _cellXf); - } catch(XmlException e) { - throw new POIXMLException(e); - } - - // Copy the format - String fmt = src.getDataFormatString(); - setDataFormat( - (new XSSFDataFormat(_stylesSource)).getFormat(fmt) - ); - - // Copy the font - try { - CTFont ctFont = CTFont.Factory.parse( - src.getFont().getCTFont().toString(), DEFAULT_XML_OPTIONS - ); - XSSFFont font = new XSSFFont(ctFont); - font.registerTo(_stylesSource); - setFont(font); - } catch(XmlException e) { - throw new POIXMLException(e); - } - } - - // Clear out cached details - _font = null; - _cellAlignment = null; - } else { - throw new IllegalArgumentException("Can only clone from one XSSFCellStyle to another, not between HSSFCellStyle and XSSFCellStyle"); - } - } - - private void addFill(CTFill fill) { - int idx = _stylesSource.putFill(new XSSFCellFill(fill)); - - _cellXf.setFillId(idx); - _cellXf.setApplyFill(true); - } - - private void addBorder(CTBorder border) { - int idx = _stylesSource.putBorder(new XSSFCellBorder(border, _theme)); - - _cellXf.setBorderId(idx); - _cellXf.setApplyBorder(true); - } - - /** - * Get the type of horizontal alignment for the cell - * - * @return short - the type of alignment - * @see org.apache.poi.ss.usermodel.CellStyle#ALIGN_GENERAL - * @see org.apache.poi.ss.usermodel.CellStyle#ALIGN_LEFT - * @see org.apache.poi.ss.usermodel.CellStyle#ALIGN_CENTER - * @see org.apache.poi.ss.usermodel.CellStyle#ALIGN_RIGHT - * @see org.apache.poi.ss.usermodel.CellStyle#ALIGN_FILL - * @see org.apache.poi.ss.usermodel.CellStyle#ALIGN_JUSTIFY - * @see org.apache.poi.ss.usermodel.CellStyle#ALIGN_CENTER_SELECTION - * @deprecated POI 3.15 beta 3. Use {@link #getAlignmentEnum()} instead. - */ - @Override - public short getAlignment() { - return getAlignmentEnum().getCode(); - } - - /** - * Get the type of horizontal alignment for the cell - * - * @return HorizontalAlignment - the type of alignment - */ - @Override - public HorizontalAlignment getAlignmentEnum() { - CTCellAlignment align = _cellXf.getAlignment(); - if(align != null && align.isSetHorizontal()) { - return HorizontalAlignment.forInt(align.getHorizontal().intValue()-1); - } - return HorizontalAlignment.GENERAL; - } - - /** - * Get the type of border to use for the bottom border of the cell - * Will be removed when {@link #getBorderBottom()} returns a BorderStyle enum - * - * @return border type, default value is {@link org.apache.poi.ss.usermodel.BorderStyle#NONE} - * @since POI 3.15 - */ - @Override - public BorderStyle getBorderBottomEnum() { - if(!_cellXf.getApplyBorder()) return BorderStyle.NONE; - - int idx = (int)_cellXf.getBorderId(); - CTBorder ct = _stylesSource.getBorderAt(idx).getCTBorder(); - STBorderStyle.Enum ptrn = ct.isSetBottom() ? ct.getBottom().getStyle() : null; - if (ptrn == null) { - return BorderStyle.NONE; - } - return BorderStyle.valueOf((short)(ptrn.intValue() - 1)); - } - /** - * Get the type of border to use for the bottom border of the cell - * This will return a BorderStyle enum in the future. - * - * @return border type code - * @deprecated 3.15 beta 2. Use {@link #getBorderBottomEnum()} - */ - public short getBorderBottom() { - return getBorderBottomEnum().getCode(); - } - - /** - * Get the type of border to use for the left border of the cell - * Will be removed when {@link #getBorderLeft()} returns a BorderStyle enum - * - * @return border type, default value is {@link org.apache.poi.ss.usermodel.BorderStyle#NONE} - * @since POI 3.15 - */ - @Override - public BorderStyle getBorderLeftEnum() { - if(!_cellXf.getApplyBorder()) return BorderStyle.NONE; - - int idx = (int)_cellXf.getBorderId(); - CTBorder ct = _stylesSource.getBorderAt(idx).getCTBorder(); - STBorderStyle.Enum ptrn = ct.isSetLeft() ? ct.getLeft().getStyle() : null; - if (ptrn == null) { - return BorderStyle.NONE; - } - return BorderStyle.valueOf((short)(ptrn.intValue() - 1)); - } - - /** - * Get the type of border to use for the left border of the cell - * This will return a BorderStyle enum in the future. - * - * @return border type code - * @deprecated 3.15 beta 2. Use {@link #getBorderLeftEnum()} - */ - public short getBorderLeft() { - return getBorderLeftEnum().getCode(); - } - - /** - * Get the type of border to use for the right border of the cell - * Will be removed when {@link #getBorderRight()} returns a BorderStyle enum - * - * @return border type, default value is {@link org.apache.poi.ss.usermodel.BorderStyle#NONE} - * @since POI 3.15 - */ - @Override - public BorderStyle getBorderRightEnum() { - if(!_cellXf.getApplyBorder()) return BorderStyle.NONE; - - int idx = (int)_cellXf.getBorderId(); - CTBorder ct = _stylesSource.getBorderAt(idx).getCTBorder(); - STBorderStyle.Enum ptrn = ct.isSetRight() ? ct.getRight().getStyle() : null; - if (ptrn == null) { - return BorderStyle.NONE; - } - return BorderStyle.valueOf((short)(ptrn.intValue() - 1)); - } - /** - * Get the type of border to use for the right border of the cell - * This will return a BorderStyle enum in the future. - * - * @return border type, default value is {@link org.apache.poi.ss.usermodel.BorderStyle#NONE} - * @deprecated 3.15 beta 2. Use {@link #getBorderRightEnum()} instead - */ - public short getBorderRight() { - return getBorderRightEnum().getCode(); - } - - /** - * Get the type of border to use for the top border of the cell - * Will be removed when {@link #getBorderTop()} returns a BorderStyle enum - * - * @return border type, default value is {@link org.apache.poi.ss.usermodel.BorderStyle#NONE} - * @since POI 3.15 - */ - @Override - public BorderStyle getBorderTopEnum() { - if(!_cellXf.getApplyBorder()) return BorderStyle.NONE; - - int idx = (int)_cellXf.getBorderId(); - CTBorder ct = _stylesSource.getBorderAt(idx).getCTBorder(); - STBorderStyle.Enum ptrn = ct.isSetTop() ? ct.getTop().getStyle() : null; - if (ptrn == null) { - return BorderStyle.NONE; - } - return BorderStyle.valueOf((short) (ptrn.intValue() - 1)); - } - /** - * Get the type of border to use for the top border of the cell - * This will return a BorderStyle enum in the future. - * - * @return border type, default value is {@link org.apache.poi.ss.usermodel.BorderStyle#NONE} - * @deprecated 3.15 beta 2. Use {@link #getBorderTopEnum()} instead. - */ - public short getBorderTop() { - return getBorderTopEnum().getCode(); - } - - /** - * Get the color to use for the bottom border - *
    - * Color is optional. When missing, IndexedColors.AUTOMATIC is implied. - * @return the index of the color definition, default value is {@link org.apache.poi.ss.usermodel.IndexedColors#AUTOMATIC} - * @see org.apache.poi.ss.usermodel.IndexedColors - */ - @Override - public short getBottomBorderColor() { - XSSFColor clr = getBottomBorderXSSFColor(); - return clr == null ? IndexedColors.BLACK.getIndex() : clr.getIndexed(); - } - - /** - * Get the color to use for the bottom border as a {@link XSSFColor} - * - * @return the used color or null if not set - */ - public XSSFColor getBottomBorderXSSFColor() { - if(!_cellXf.getApplyBorder()) return null; - - int idx = (int)_cellXf.getBorderId(); - XSSFCellBorder border = _stylesSource.getBorderAt(idx); - - return border.getBorderColor(BorderSide.BOTTOM); - } - - /** - * Get the index of the number format (numFmt) record used by this cell format. - * - * @return the index of the number format - */ - @Override - public short getDataFormat() { - return (short)_cellXf.getNumFmtId(); - } - - /** - * Get the contents of the format string, by looking up - * the StylesSource - * - * @return the number format string - */ - @Override - public String getDataFormatString() { - int idx = getDataFormat(); - return new XSSFDataFormat(_stylesSource).getFormat((short)idx); - } - - /** - * Get the background fill color. - *

    - * Note - many cells are actually filled with a foreground - * fill, not a background fill - see {@link #getFillForegroundColor()} - *

    - * @return fill color, default value is {@link org.apache.poi.ss.usermodel.IndexedColors#AUTOMATIC} - * @see org.apache.poi.ss.usermodel.IndexedColors - */ - @Override - public short getFillBackgroundColor() { - XSSFColor clr = getFillBackgroundXSSFColor(); - return clr == null ? IndexedColors.AUTOMATIC.getIndex() : clr.getIndexed(); - } - - @Override - public XSSFColor getFillBackgroundColorColor() { - return getFillBackgroundXSSFColor(); - } - - /** - * Get the background fill color. - *

    - * Note - many cells are actually filled with a foreground - * fill, not a background fill - see {@link #getFillForegroundColor()} - *

    - * @see org.apache.poi.xssf.usermodel.XSSFColor#getRGB() - * @return XSSFColor - fill color or null if not set - */ - public XSSFColor getFillBackgroundXSSFColor() { - // bug 56295: handle missing applyFill attribute as "true" because Excel does as well - if(_cellXf.isSetApplyFill() && !_cellXf.getApplyFill()) return null; - - int fillIndex = (int)_cellXf.getFillId(); - XSSFCellFill fg = _stylesSource.getFillAt(fillIndex); - - XSSFColor fillBackgroundColor = fg.getFillBackgroundColor(); - if (fillBackgroundColor != null && _theme != null) { - _theme.inheritFromThemeAsRequired(fillBackgroundColor); - } - return fillBackgroundColor; - } - - /** - * Get the foreground fill color. - *

    - * Many cells are filled with this, instead of a - * background color ({@link #getFillBackgroundColor()}) - *

    - * @see IndexedColors - * @return fill color, default value is {@link org.apache.poi.ss.usermodel.IndexedColors#AUTOMATIC} - */ - @Override - public short getFillForegroundColor() { - XSSFColor clr = getFillForegroundXSSFColor(); - return clr == null ? IndexedColors.AUTOMATIC.getIndex() : clr.getIndexed(); - } - - @Override - public XSSFColor getFillForegroundColorColor() { - return getFillForegroundXSSFColor(); - } - - /** - * Get the foreground fill color. - * - * @return XSSFColor - fill color or null if not set - */ - public XSSFColor getFillForegroundXSSFColor() { - // bug 56295: handle missing applyFill attribute as "true" because Excel does as well - if(_cellXf.isSetApplyFill() && !_cellXf.getApplyFill()) return null; - - int fillIndex = (int)_cellXf.getFillId(); - XSSFCellFill fg = _stylesSource.getFillAt(fillIndex); - - XSSFColor fillForegroundColor = fg.getFillForegroundColor(); - if (fillForegroundColor != null && _theme != null) { - _theme.inheritFromThemeAsRequired(fillForegroundColor); - } - return fillForegroundColor; - } - - /** - * Get the fill pattern - * @return fill pattern, default value is {@link org.apache.poi.ss.usermodel.CellStyle#NO_FILL} - * - * @see org.apache.poi.ss.usermodel.CellStyle#NO_FILL - * @see org.apache.poi.ss.usermodel.CellStyle#SOLID_FOREGROUND - * @see org.apache.poi.ss.usermodel.CellStyle#FINE_DOTS - * @see org.apache.poi.ss.usermodel.CellStyle#ALT_BARS - * @see org.apache.poi.ss.usermodel.CellStyle#SPARSE_DOTS - * @see org.apache.poi.ss.usermodel.CellStyle#THICK_HORZ_BANDS - * @see org.apache.poi.ss.usermodel.CellStyle#THICK_VERT_BANDS - * @see org.apache.poi.ss.usermodel.CellStyle#THICK_BACKWARD_DIAG - * @see org.apache.poi.ss.usermodel.CellStyle#THICK_FORWARD_DIAG - * @see org.apache.poi.ss.usermodel.CellStyle#BIG_SPOTS - * @see org.apache.poi.ss.usermodel.CellStyle#BRICKS - * @see org.apache.poi.ss.usermodel.CellStyle#THIN_HORZ_BANDS - * @see org.apache.poi.ss.usermodel.CellStyle#THIN_VERT_BANDS - * @see org.apache.poi.ss.usermodel.CellStyle#THIN_BACKWARD_DIAG - * @see org.apache.poi.ss.usermodel.CellStyle#THIN_FORWARD_DIAG - * @see org.apache.poi.ss.usermodel.CellStyle#SQUARES - * @see org.apache.poi.ss.usermodel.CellStyle#DIAMONDS - * @deprecated POI 3.15 beta 3. This method will return {@link FillPatternType} in the future. Use {@link #setFillPattern(FillPatternType)} instead. - */ - @Override - public short getFillPattern() { - return getFillPatternEnum().getCode(); - } - - /** - * Get the fill pattern - * - * @return the fill pattern, default value is {@link FillPatternType#NO_FILL} - */ - @Override - public FillPatternType getFillPatternEnum() { - // bug 56295: handle missing applyFill attribute as "true" because Excel does as well - if(_cellXf.isSetApplyFill() && !_cellXf.getApplyFill()) return FillPatternType.NO_FILL; - - int fillIndex = (int)_cellXf.getFillId(); - XSSFCellFill fill = _stylesSource.getFillAt(fillIndex); - - STPatternType.Enum ptrn = fill.getPatternType(); - if(ptrn == null) return FillPatternType.NO_FILL; - return FillPatternType.forInt(ptrn.intValue() - 1); - } - - /** - * Gets the font for this style - * @return Font - font - */ - public XSSFFont getFont() { - if (_font == null) { - _font = _stylesSource.getFontAt(getFontId()); - } - return _font; - } - - /** - * Gets the index of the font for this style - * - * @return short - font index - * @see org.apache.poi.xssf.usermodel.XSSFWorkbook#getFontAt(short) - */ - @Override - public short getFontIndex() { - return (short) getFontId(); - } - - /** - * Get whether the cell's using this style are to be hidden - * - * @return boolean - whether the cell using this style is hidden - */ - @Override - public boolean getHidden() { - if (!_cellXf.isSetProtection() || !_cellXf.getProtection().isSetHidden()) { - return false; - } - return _cellXf.getProtection().getHidden(); - } - - /** - * Get the number of spaces to indent the text in the cell - * - * @return indent - number of spaces - */ - @Override - public short getIndention() { - CTCellAlignment align = _cellXf.getAlignment(); - return (short)(align == null ? 0 : align.getIndent()); - } - - /** - * Get the index within the StylesTable (sequence within the collection of CTXf elements) - * - * @return unique index number of the underlying record this style represents, as a short (may wrap) - */ - @Override - public short getIndex() { - return (short)this._cellXfId; - } - - /** - * Workaround for places where we need to support more than 32767 cell styles, ideally - * the main getIndex() and others would return int, not short, but that would affect some - * public APIs - * - * @return unique index number of the underlying record this style represents, as an int (always positive) - */ - protected int getUIndex() { - return this._cellXfId; - } - - /** - * Get the color to use for the left border - * - * @return the index of the color definition, default value is {@link org.apache.poi.ss.usermodel.IndexedColors#BLACK} - * @see org.apache.poi.ss.usermodel.IndexedColors - */ - @Override - public short getLeftBorderColor() { - XSSFColor clr = getLeftBorderXSSFColor(); - return clr == null ? IndexedColors.BLACK.getIndex() : clr.getIndexed(); - } - - /** - * Get the color to use for the left border - * - * @return the index of the color definition or null if not set - * @see org.apache.poi.ss.usermodel.IndexedColors - */ - public XSSFColor getLeftBorderXSSFColor() { - if(!_cellXf.getApplyBorder()) return null; - - int idx = (int)_cellXf.getBorderId(); - XSSFCellBorder border = _stylesSource.getBorderAt(idx); - - return border.getBorderColor(BorderSide.LEFT); - } - - /** - * Get whether the cell's using this style are locked - * - * @return whether the cell using this style are locked - */ - @Override - public boolean getLocked() { - if (!_cellXf.isSetProtection() || !_cellXf.getProtection().isSetLocked()) { - return true; - } - return _cellXf.getProtection().getLocked(); - } - - /** - * Is "Quote Prefix" or "123 Prefix" enabled for the cell? - */ - @Override - public boolean getQuotePrefixed() { - return _cellXf.getQuotePrefix(); - } - - /** - * Get the color to use for the right border - * - * @return the index of the color definition, default value is {@link org.apache.poi.ss.usermodel.IndexedColors#BLACK} - * @see org.apache.poi.ss.usermodel.IndexedColors - */ - @Override - public short getRightBorderColor() { - XSSFColor clr = getRightBorderXSSFColor(); - return clr == null ? IndexedColors.BLACK.getIndex() : clr.getIndexed(); - } - /** - * Get the color to use for the right border - * - * @return the used color or null if not set - */ - public XSSFColor getRightBorderXSSFColor() { - if(!_cellXf.getApplyBorder()) return null; - - int idx = (int)_cellXf.getBorderId(); - XSSFCellBorder border = _stylesSource.getBorderAt(idx); - - return border.getBorderColor(BorderSide.RIGHT); - } - - /** - * Get the degree of rotation for the text in the cell - *

    - * Expressed in degrees. Values range from 0 to 180. The first letter of - * the text is considered the center-point of the arc. - *
    - * For 0 - 90, the value represents degrees above horizon. For 91-180 the degrees below the - * horizon is calculated as: - *
    - * [degrees below horizon] = 90 - textRotation. - *

    - * - * @return rotation degrees (between 0 and 180 degrees) - */ - @Override - public short getRotation() { - CTCellAlignment align = _cellXf.getAlignment(); - return (short)(align == null ? 0 : align.getTextRotation()); - } - - @Override - public boolean getShrinkToFit() { - CTCellAlignment align = _cellXf.getAlignment(); - return align != null && align.getShrinkToFit(); - } - - /** - * Get the color to use for the top border - * - * @return the index of the color definition, default value is {@link org.apache.poi.ss.usermodel.IndexedColors#BLACK} - * @see org.apache.poi.ss.usermodel.IndexedColors - */ - @Override - public short getTopBorderColor() { - XSSFColor clr = getTopBorderXSSFColor(); - return clr == null ? IndexedColors.BLACK.getIndex() : clr.getIndexed(); - } - - /** - * Get the color to use for the top border - * - * @return the used color or null if not set - */ - public XSSFColor getTopBorderXSSFColor() { - if(!_cellXf.getApplyBorder()) return null; - - int idx = (int)_cellXf.getBorderId(); - XSSFCellBorder border = _stylesSource.getBorderAt(idx); - - return border.getBorderColor(BorderSide.TOP); - } - - /** - * Get the type of vertical alignment for the cell - * - * @return align the type of alignment, default value is {@link org.apache.poi.ss.usermodel.CellStyle#VERTICAL_BOTTOM} - * @see org.apache.poi.ss.usermodel.CellStyle#VERTICAL_TOP - * @see org.apache.poi.ss.usermodel.CellStyle#VERTICAL_CENTER - * @see org.apache.poi.ss.usermodel.CellStyle#VERTICAL_BOTTOM - * @see org.apache.poi.ss.usermodel.CellStyle#VERTICAL_JUSTIFY - * @deprecated POI 3.15 beta 3. Use {@link #getVerticalAlignmentEnum()} instead. - */ - @Override - public short getVerticalAlignment() { - return getVerticalAlignmentEnum().getCode(); - } - - /** - * Get the type of vertical alignment for the cell - * - * @return the type of alignment, default value is {@link VerticalAlignment#BOTTOM} - */ - @Override - public VerticalAlignment getVerticalAlignmentEnum() { - CTCellAlignment align = _cellXf.getAlignment(); - if(align != null && align.isSetVertical()) { - return VerticalAlignment.forInt(align.getVertical().intValue()-1); - } - return VerticalAlignment.BOTTOM; - } - - /** - * Whether the text should be wrapped - * - * @return a boolean value indicating if the text in a cell should be line-wrapped within the cell. - */ - @Override - public boolean getWrapText() { - CTCellAlignment align = _cellXf.getAlignment(); - return align != null && align.getWrapText(); - } - - /** - * Set the type of horizontal alignment for the cell - * - * @param align - the type of alignment - * @see org.apache.poi.ss.usermodel.CellStyle#ALIGN_GENERAL - * @see org.apache.poi.ss.usermodel.CellStyle#ALIGN_LEFT - * @see org.apache.poi.ss.usermodel.CellStyle#ALIGN_CENTER - * @see org.apache.poi.ss.usermodel.CellStyle#ALIGN_RIGHT - * @see org.apache.poi.ss.usermodel.CellStyle#ALIGN_FILL - * @see org.apache.poi.ss.usermodel.CellStyle#ALIGN_JUSTIFY - * @see org.apache.poi.ss.usermodel.CellStyle#ALIGN_CENTER_SELECTION - * @deprecated POI 3.15 beta 3. Use {@link #setAlignment(HorizontalAlignment)} instead. - */ - @Removal(version="3.17") - @Override - public void setAlignment(short align) { - setAlignment(HorizontalAlignment.forInt(align)); - } - - /** - * Set the type of horizontal alignment for the cell - * - * @param align - the type of alignment - */ - @Override - public void setAlignment(HorizontalAlignment align) { - getCellAlignment().setHorizontal(align); - } - - /** - * Set the type of border to use for the bottom border of the cell - * - * @param border the type of border to use - * @deprecated 3.15 beta 2. Use {@link #setBorderBottom(BorderStyle)} - */ - @Removal(version="3.17") - @Override - public void setBorderBottom(short border) { - setBorderBottom(BorderStyle.valueOf(border)); - } - - /** - * Set the type of border to use for the bottom border of the cell - * - * @param border - type of border to use - * @see org.apache.poi.ss.usermodel.BorderStyle - * @since POI 3.15 - */ - @Override - public void setBorderBottom(BorderStyle border) { - CTBorder ct = getCTBorder(); - CTBorderPr pr = ct.isSetBottom() ? ct.getBottom() : ct.addNewBottom(); - if(border == BorderStyle.NONE) ct.unsetBottom(); - else pr.setStyle(STBorderStyle.Enum.forInt(border.getCode() + 1)); - - int idx = _stylesSource.putBorder(new XSSFCellBorder(ct, _theme)); - - _cellXf.setBorderId(idx); - _cellXf.setApplyBorder(true); - } - - /** - * Set the type of border to use for the left border of the cell - * @param border the type of border to use - * @deprecated 3.15 beta 2. Use {@link #setBorderLeft(BorderStyle)} - */ - @Removal(version="3.17") - @Override - public void setBorderLeft(short border) { - setBorderLeft(BorderStyle.valueOf(border)); - } - - /** - * Set the type of border to use for the left border of the cell - * - * @param border the type of border to use - * @since POI 3.15 - */ - @Override - public void setBorderLeft(BorderStyle border) { - CTBorder ct = getCTBorder(); - CTBorderPr pr = ct.isSetLeft() ? ct.getLeft() : ct.addNewLeft(); - if(border == BorderStyle.NONE) ct.unsetLeft(); - else pr.setStyle(STBorderStyle.Enum.forInt(border.getCode() + 1)); - - int idx = _stylesSource.putBorder(new XSSFCellBorder(ct, _theme)); - - _cellXf.setBorderId(idx); - _cellXf.setApplyBorder(true); - } - - /** - * Set the type of border to use for the right border of the cell - * - * @param border the type of border to use - * @deprecated 3.15 beta 2. Use {@link #setBorderRight(BorderStyle)} - */ - @Removal(version="3.17") - @Override - public void setBorderRight(short border) { - setBorderRight(BorderStyle.valueOf(border)); - } - - /** - * Set the type of border to use for the right border of the cell - * - * @param border the type of border to use - * @since POI 3.15 - */ - @Override - public void setBorderRight(BorderStyle border) { - CTBorder ct = getCTBorder(); - CTBorderPr pr = ct.isSetRight() ? ct.getRight() : ct.addNewRight(); - if(border == BorderStyle.NONE) ct.unsetRight(); - else pr.setStyle(STBorderStyle.Enum.forInt(border.getCode() + 1)); - - int idx = _stylesSource.putBorder(new XSSFCellBorder(ct, _theme)); - - _cellXf.setBorderId(idx); - _cellXf.setApplyBorder(true); - } - - /** - * Set the type of border to use for the top border of the cell - * - * @param border the type of border to use - * @deprecated 3.15 beta 2. Use {@link #setBorderTop(BorderStyle)} - */ - @Removal(version="3.17") - @Override - public void setBorderTop(short border) { - setBorderTop(BorderStyle.valueOf(border)); - } - - /** - * Set the type of border to use for the top border of the cell - * - * @param border the type of border to use - * @since POI 3.15 - */ - @Override - public void setBorderTop(BorderStyle border) { - CTBorder ct = getCTBorder(); - CTBorderPr pr = ct.isSetTop() ? ct.getTop() : ct.addNewTop(); - if(border == BorderStyle.NONE) ct.unsetTop(); - else pr.setStyle(STBorderStyle.Enum.forInt(border.getCode() + 1)); - - int idx = _stylesSource.putBorder(new XSSFCellBorder(ct, _theme)); - - _cellXf.setBorderId(idx); - _cellXf.setApplyBorder(true); - } - - /** - * Set the color to use for the bottom border - * @param color the index of the color definition - * @see org.apache.poi.ss.usermodel.IndexedColors - */ - @Override - public void setBottomBorderColor(short color) { - XSSFColor clr = new XSSFColor(); - clr.setIndexed(color); - setBottomBorderColor(clr); - } - - /** - * Set the color to use for the bottom border - * - * @param color the color to use, null means no color - */ - public void setBottomBorderColor(XSSFColor color) { - CTBorder ct = getCTBorder(); - if(color == null && !ct.isSetBottom()) return; - - CTBorderPr pr = ct.isSetBottom() ? ct.getBottom() : ct.addNewBottom(); - if(color != null) pr.setColor(color.getCTColor()); - else pr.unsetColor(); - - int idx = _stylesSource.putBorder(new XSSFCellBorder(ct, _theme)); - - _cellXf.setBorderId(idx); - _cellXf.setApplyBorder(true); - } - - /** - * Set the index of a data format - * - * @param fmt the index of a data format - */ - @Override - public void setDataFormat(short fmt) { - // XSSF supports >32,767 formats - setDataFormat(fmt&0xffff); - } - /** - * Set the index of a data format - * - * @param fmt the index of a data format - */ - public void setDataFormat(int fmt) { - _cellXf.setApplyNumberFormat(true); - _cellXf.setNumFmtId(fmt); - } - - /** - * Set the background fill color represented as a {@link XSSFColor} value. - *

    - * For example: - *

    -     * cs.setFillPattern(XSSFCellStyle.FINE_DOTS );
    -     * cs.setFillBackgroundXSSFColor(new XSSFColor(java.awt.Color.RED));
    -     * 
    - * optionally a Foreground and background fill can be applied: - * Note: Ensure Foreground color is set prior to background - *
    -     * cs.setFillPattern(XSSFCellStyle.FINE_DOTS );
    -     * cs.setFillForegroundColor(new XSSFColor(java.awt.Color.BLUE));
    -     * cs.setFillBackgroundColor(new XSSFColor(java.awt.Color.GREEN));
    -     * 
    - * or, for the special case of SOLID_FILL: - *
    -     * cs.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND );
    -     * cs.setFillForegroundColor(new XSSFColor(java.awt.Color.GREEN));
    -     * 
    - * It is necessary to set the fill style in order - * for the color to be shown in the cell. - * - * @param color - the color to use - */ - public void setFillBackgroundColor(XSSFColor color) { - CTFill ct = getCTFill(); - CTPatternFill ptrn = ct.getPatternFill(); - if(color == null) { - if(ptrn != null && ptrn.isSetBgColor()) ptrn.unsetBgColor(); - } else { - if(ptrn == null) ptrn = ct.addNewPatternFill(); - ptrn.setBgColor(color.getCTColor()); - } - - addFill(ct); - } - - /** - * Set the background fill color represented as a indexed color value. - *

    - * For example: - *

    -     * cs.setFillPattern(XSSFCellStyle.FINE_DOTS );
    -     * cs.setFillBackgroundXSSFColor(IndexedColors.RED.getIndex());
    -     * 
    - * optionally a Foreground and background fill can be applied: - * Note: Ensure Foreground color is set prior to background - *
    -     * cs.setFillPattern(XSSFCellStyle.FINE_DOTS );
    -     * cs.setFillForegroundColor(IndexedColors.BLUE.getIndex());
    -     * cs.setFillBackgroundColor(IndexedColors.RED.getIndex());
    -     * 
    - * or, for the special case of SOLID_FILL: - *
    -     * cs.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND );
    -     * cs.setFillForegroundColor(IndexedColors.RED.getIndex());
    -     * 
    - * It is necessary to set the fill style in order - * for the color to be shown in the cell. - * - * @param bg - the color to use - * @see org.apache.poi.ss.usermodel.IndexedColors - */ - @Override - public void setFillBackgroundColor(short bg) { - XSSFColor clr = new XSSFColor(); - clr.setIndexed(bg); - setFillBackgroundColor(clr); - } - - /** - * Set the foreground fill color represented as a {@link XSSFColor} value. - *
    - * Note: Ensure Foreground color is set prior to background color. - * @param color the color to use - * @see #setFillBackgroundColor(org.apache.poi.xssf.usermodel.XSSFColor) ) - */ - public void setFillForegroundColor(XSSFColor color) { - CTFill ct = getCTFill(); - - CTPatternFill ptrn = ct.getPatternFill(); - if(color == null) { - if(ptrn != null && ptrn.isSetFgColor()) ptrn.unsetFgColor(); - } else { - if(ptrn == null) ptrn = ct.addNewPatternFill(); - ptrn.setFgColor(color.getCTColor()); - } - - addFill(ct); - } - - /** - * Set the foreground fill color as a indexed color value - *
    - * Note: Ensure Foreground color is set prior to background color. - * @param fg the color to use - * @see org.apache.poi.ss.usermodel.IndexedColors - */ - @Override - public void setFillForegroundColor(short fg) { - XSSFColor clr = new XSSFColor(); - clr.setIndexed(fg); - setFillForegroundColor(clr); - } - - /** - * Get a copy of the currently used CTFill, if none is used, return a new instance. - */ - private CTFill getCTFill(){ - CTFill ct; - // bug 56295: handle missing applyFill attribute as "true" because Excel does as well - if(!_cellXf.isSetApplyFill() || _cellXf.getApplyFill()) { - int fillIndex = (int)_cellXf.getFillId(); - XSSFCellFill cf = _stylesSource.getFillAt(fillIndex); - - ct = (CTFill)cf.getCTFill().copy(); - } else { - ct = CTFill.Factory.newInstance(); - } - return ct; - } - - /** - * Get a copy of the currently used CTBorder, if none is used, return a new instance. - */ - private CTBorder getCTBorder(){ - CTBorder ct; - if(_cellXf.getApplyBorder()) { - int idx = (int)_cellXf.getBorderId(); - XSSFCellBorder cf = _stylesSource.getBorderAt(idx); - - ct = (CTBorder)cf.getCTBorder().copy(); - } else { - ct = CTBorder.Factory.newInstance(); - } - return ct; - } - - /** - * This element is used to specify cell fill information for pattern and solid color cell fills. - * For solid cell fills (no pattern), foreground color is used. - * For cell fills with patterns specified, then the cell fill color is specified by the background color. - * - * @see org.apache.poi.ss.usermodel.CellStyle#NO_FILL - * @see org.apache.poi.ss.usermodel.CellStyle#SOLID_FOREGROUND - * @see org.apache.poi.ss.usermodel.CellStyle#FINE_DOTS - * @see org.apache.poi.ss.usermodel.CellStyle#ALT_BARS - * @see org.apache.poi.ss.usermodel.CellStyle#SPARSE_DOTS - * @see org.apache.poi.ss.usermodel.CellStyle#THICK_HORZ_BANDS - * @see org.apache.poi.ss.usermodel.CellStyle#THICK_VERT_BANDS - * @see org.apache.poi.ss.usermodel.CellStyle#THICK_BACKWARD_DIAG - * @see org.apache.poi.ss.usermodel.CellStyle#THICK_FORWARD_DIAG - * @see org.apache.poi.ss.usermodel.CellStyle#BIG_SPOTS - * @see org.apache.poi.ss.usermodel.CellStyle#BRICKS - * @see org.apache.poi.ss.usermodel.CellStyle#THIN_HORZ_BANDS - * @see org.apache.poi.ss.usermodel.CellStyle#THIN_VERT_BANDS - * @see org.apache.poi.ss.usermodel.CellStyle#THIN_BACKWARD_DIAG - * @see org.apache.poi.ss.usermodel.CellStyle#THIN_FORWARD_DIAG - * @see org.apache.poi.ss.usermodel.CellStyle#SQUARES - * @see org.apache.poi.ss.usermodel.CellStyle#DIAMONDS - * @see #setFillBackgroundColor(short) - * @see #setFillForegroundColor(short) - * @param fp fill pattern (set to {@link org.apache.poi.ss.usermodel.CellStyle#SOLID_FOREGROUND} to fill w/foreground color) - * @deprecated POI 3.15. Use {@link #setFillPattern(FillPatternType)} instead. - */ - @Removal(version="3.17") - @Override - public void setFillPattern(short fp) { - setFillPattern(FillPatternType.forInt(fp)); - } - - /** - * This element is used to specify cell fill information for pattern and solid color cell fills. For solid cell fills (no pattern), - * foreground color is used is used. For cell fills with patterns specified, then the cell fill color is specified by the background color element. - * - * @param pattern the fill pattern to use - * @see #setFillBackgroundColor(XSSFColor) - * @see #setFillForegroundColor(XSSFColor) - * @see org.apache.poi.ss.usermodel.FillPatternType - */ - @Override - public void setFillPattern(FillPatternType pattern) { - CTFill ct = getCTFill(); - CTPatternFill ctptrn = ct.isSetPatternFill() ? ct.getPatternFill() : ct.addNewPatternFill(); - if (pattern == FillPatternType.NO_FILL && ctptrn.isSetPatternType()) { - ctptrn.unsetPatternType(); - } else { - ctptrn.setPatternType(STPatternType.Enum.forInt(pattern.getCode() + 1)); - } - - addFill(ct); - } - - /** - * Set the font for this style - * - * @param font a font object created or retrieved from the XSSFWorkbook object - * @see org.apache.poi.xssf.usermodel.XSSFWorkbook#createFont() - * @see org.apache.poi.xssf.usermodel.XSSFWorkbook#getFontAt(short) - */ - @Override - public void setFont(Font font) { - if(font != null){ - long index = font.getIndex(); - this._cellXf.setFontId(index); - this._cellXf.setApplyFont(true); - } else { - this._cellXf.setApplyFont(false); - } - } - - /** - * Set the cell's using this style to be hidden - * - * @param hidden - whether the cell using this style should be hidden - */ - @Override - public void setHidden(boolean hidden) { - if (!_cellXf.isSetProtection()) { - _cellXf.addNewProtection(); - } - _cellXf.getProtection().setHidden(hidden); - } - - /** - * Set the number of spaces to indent the text in the cell - * - * @param indent - number of spaces - */ - @Override - public void setIndention(short indent) { - getCellAlignment().setIndent(indent); - } - - /** - * Set the color to use for the left border as a indexed color value - * - * @param color the index of the color definition - * @see org.apache.poi.ss.usermodel.IndexedColors - */ - @Override - public void setLeftBorderColor(short color) { - XSSFColor clr = new XSSFColor(); - clr.setIndexed(color); - setLeftBorderColor(clr); - } - - /** - * Set the color to use for the left border as a {@link XSSFColor} value - * - * @param color the color to use - */ - public void setLeftBorderColor(XSSFColor color) { - CTBorder ct = getCTBorder(); - if(color == null && !ct.isSetLeft()) return; - - CTBorderPr pr = ct.isSetLeft() ? ct.getLeft() : ct.addNewLeft(); - if(color != null) pr.setColor(color.getCTColor()); - else pr.unsetColor(); - - int idx = _stylesSource.putBorder(new XSSFCellBorder(ct, _theme)); - - _cellXf.setBorderId(idx); - _cellXf.setApplyBorder(true); - } - - /** - * Set the cell's using this style to be locked - * - * @param locked - whether the cell using this style should be locked - */ - @Override - public void setLocked(boolean locked) { - if (!_cellXf.isSetProtection()) { - _cellXf.addNewProtection(); - } - _cellXf.getProtection().setLocked(locked); - } - - /** - * Turn on or off "Quote Prefix" or "123 Prefix" for the style, - * which is used to tell Excel that the thing which looks like - * a number or a formula shouldn't be treated as on. - */ - @Override - public void setQuotePrefixed(boolean quotePrefix) { - _cellXf.setQuotePrefix(quotePrefix); - } - - /** - * Set the color to use for the right border - * - * @param color the index of the color definition - * @see org.apache.poi.ss.usermodel.IndexedColors - */ - @Override - public void setRightBorderColor(short color) { - XSSFColor clr = new XSSFColor(); - clr.setIndexed(color); - setRightBorderColor(clr); - } - - /** - * Set the color to use for the right border as a {@link XSSFColor} value - * - * @param color the color to use - */ - public void setRightBorderColor(XSSFColor color) { - CTBorder ct = getCTBorder(); - if(color == null && !ct.isSetRight()) return; - - CTBorderPr pr = ct.isSetRight() ? ct.getRight() : ct.addNewRight(); - if(color != null) pr.setColor(color.getCTColor()); - else pr.unsetColor(); - - int idx = _stylesSource.putBorder(new XSSFCellBorder(ct, _theme)); - - _cellXf.setBorderId(idx); - _cellXf.setApplyBorder(true); - } - - /** - * Set the degree of rotation for the text in the cell - *

    - * Expressed in degrees. Values range from 0 to 180. The first letter of - * the text is considered the center-point of the arc. - *
    - * For 0 - 90, the value represents degrees above horizon. For 91-180 the degrees below the - * horizon is calculated as: - *
    - * [degrees below horizon] = 90 - textRotation. - *

    - * - * Note: HSSF uses values from -90 to 90 degrees, whereas XSSF - * uses values from 0 to 180 degrees. The implementations of this method will map between these two value-ranges - * accordingly, however the corresponding getter is returning values in the range mandated by the current type - * of Excel file-format that this CellStyle is applied to. - * - * @param rotation - the rotation degrees (between 0 and 180 degrees) - */ - @Override - public void setRotation(short rotation) { - getCellAlignment().setTextRotation(rotation); - } - - - /** - * Set the color to use for the top border - * - * @param color the index of the color definition - * @see org.apache.poi.ss.usermodel.IndexedColors - */ - @Override - public void setTopBorderColor(short color) { - XSSFColor clr = new XSSFColor(); - clr.setIndexed(color); - setTopBorderColor(clr); - } - - /** - * Set the color to use for the top border as a {@link XSSFColor} value - * - * @param color the color to use - */ - public void setTopBorderColor(XSSFColor color) { - CTBorder ct = getCTBorder(); - if(color == null && !ct.isSetTop()) return; - - CTBorderPr pr = ct.isSetTop() ? ct.getTop() : ct.addNewTop(); - if(color != null) pr.setColor(color.getCTColor()); - else pr.unsetColor(); - - int idx = _stylesSource.putBorder(new XSSFCellBorder(ct, _theme)); - - _cellXf.setBorderId(idx); - _cellXf.setApplyBorder(true); - } - - /** - * Set the type of vertical alignment for the cell - * - * @param align - align the type of alignment - * @see org.apache.poi.ss.usermodel.CellStyle#VERTICAL_TOP - * @see org.apache.poi.ss.usermodel.CellStyle#VERTICAL_CENTER - * @see org.apache.poi.ss.usermodel.CellStyle#VERTICAL_BOTTOM - * @see org.apache.poi.ss.usermodel.CellStyle#VERTICAL_JUSTIFY - * @see org.apache.poi.ss.usermodel.VerticalAlignment - * @deprecated POI 3.15 beta 3. Use {@link #setVerticalAlignment(VerticalAlignment)} instead. - */ - @Removal(version="3.17") - @Override - public void setVerticalAlignment(short align) { - setVerticalAlignment(VerticalAlignment.forInt(align)); - } - - /** - * Set the type of vertical alignment for the cell - * - * @param align - the type of alignment - */ - public void setVerticalAlignment(VerticalAlignment align) { - getCellAlignment().setVertical(align); - } - - /** - * Set whether the text should be wrapped. - *

    - * Setting this flag to true make all content visible - * whithin a cell by displaying it on multiple lines - *

    - * - * @param wrapped a boolean value indicating if the text in a cell should be line-wrapped within the cell. - */ - @Override - public void setWrapText(boolean wrapped) { - getCellAlignment().setWrapText(wrapped); - } - - /** - * Gets border color - * - * @param side the border side - * @return the used color - */ - public XSSFColor getBorderColor(BorderSide side) { - switch(side){ - case BOTTOM: - return getBottomBorderXSSFColor(); - case RIGHT: - return getRightBorderXSSFColor(); - case TOP: - return getTopBorderXSSFColor(); - case LEFT: - return getLeftBorderXSSFColor(); - default: - throw new IllegalArgumentException("Unknown border: " + side); - } - } - - /** - * Set the color to use for the selected border - * - * @param side - where to apply the color definition - * @param color - the color to use - */ - public void setBorderColor(BorderSide side, XSSFColor color) { - switch(side){ - case BOTTOM: - setBottomBorderColor(color); - break; - case RIGHT: - setRightBorderColor(color); - break; - case TOP: - setTopBorderColor(color); - break; - case LEFT: - setLeftBorderColor(color); - break; - } - } - - @Override - public void setShrinkToFit(boolean shrinkToFit) { - getCellAlignment().setShrinkToFit(shrinkToFit); - } - - private int getFontId() { - if (_cellXf.isSetFontId()) { - return (int) _cellXf.getFontId(); - } - return (int) _cellStyleXf.getFontId(); - } - - /** - * get the cellAlignment object to use for manage alignment - * @return XSSFCellAlignment - cell alignment - */ - protected XSSFCellAlignment getCellAlignment() { - if (this._cellAlignment == null) { - this._cellAlignment = new XSSFCellAlignment(getCTCellAlignment()); - } - return this._cellAlignment; - } - - /** - * Return the CTCellAlignment instance for alignment - * - * @return CTCellAlignment - */ - private CTCellAlignment getCTCellAlignment() { - if (_cellXf.getAlignment() == null) { - _cellXf.setAlignment(CTCellAlignment.Factory.newInstance()); - } - return _cellXf.getAlignment(); - } - - /** - * Returns a hash code value for the object. The hash is derived from the underlying CTXf bean. - * - * @return the hash code value for this style - */ - @Override - public int hashCode(){ - return _cellXf.toString().hashCode(); - } - - /** - * Checks is the supplied style is equal to this style - * - * @param o the style to check - * @return true if the supplied style is equal to this style - */ - @Override - public boolean equals(Object o){ - if(o == null || !(o instanceof XSSFCellStyle)) return false; - - XSSFCellStyle cf = (XSSFCellStyle)o; - return _cellXf.toString().equals(cf.getCoreXf().toString()); - } - - /** - * Make a copy of this style. The underlying CTXf bean is cloned, - * the references to fills and borders remain. - * - * @return a copy of this style - */ - @Override - public Object clone(){ - CTXf xf = (CTXf)_cellXf.copy(); - - int xfSize = _stylesSource._getStyleXfsSize(); - int indexXf = _stylesSource.putCellXf(xf); - return new XSSFCellStyle(indexXf-1, xfSize-1, _stylesSource, _theme); - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFChart.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFChart.java deleted file mode 100644 index 43e865989..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFChart.java +++ /dev/null @@ -1,456 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import static org.apache.poi.POIXMLTypeLoader.DEFAULT_XML_OPTIONS; - -import java.io.IOException; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.List; - -import javax.xml.namespace.QName; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.ss.usermodel.Chart; -import org.apache.poi.ss.usermodel.charts.AxisPosition; -import org.apache.poi.ss.usermodel.charts.ChartAxis; -import org.apache.poi.ss.usermodel.charts.ChartAxisFactory; -import org.apache.poi.ss.usermodel.charts.ChartData; -import org.apache.poi.util.Internal; -import org.apache.poi.util.Removal; -import org.apache.poi.xssf.usermodel.charts.XSSFCategoryAxis; -import org.apache.poi.xssf.usermodel.charts.XSSFChartAxis; -import org.apache.poi.xssf.usermodel.charts.XSSFChartDataFactory; -import org.apache.poi.xssf.usermodel.charts.XSSFChartLegend; -import org.apache.poi.xssf.usermodel.charts.XSSFManualLayout; -import org.apache.poi.xssf.usermodel.charts.XSSFValueAxis; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlOptions; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTCatAx; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTChart; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTChartSpace; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTPageMargins; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTPlotArea; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTPrintSettings; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTStrRef; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTTitle; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTTx; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTValAx; -import org.openxmlformats.schemas.drawingml.x2006.chart.ChartSpaceDocument; -import org.openxmlformats.schemas.drawingml.x2006.main.CTRegularTextRun; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextBody; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextField; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextParagraph; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.w3c.dom.Text; - -/** - * Represents a SpreadsheetML Chart - */ -public final class XSSFChart extends POIXMLDocumentPart implements Chart, ChartAxisFactory { - - /** - * Parent graphic frame. - */ - private XSSFGraphicFrame frame; - - /** - * Root element of the SpreadsheetML Chart part - */ - private CTChartSpace chartSpace; - /** - * The Chart within that - */ - private CTChart chart; - - List axis = new ArrayList(); - - /** - * Create a new SpreadsheetML chart - */ - protected XSSFChart() { - super(); - createChart(); - } - - /** - * Construct a SpreadsheetML chart from a package part. - * - * @param part the package part holding the chart data, - * the content type must be application/vnd.openxmlformats-officedocument.drawingml.chart+xml - * - * @since POI 3.14-Beta1 - */ - protected XSSFChart(PackagePart part) throws IOException, XmlException { - super(part); - - chartSpace = ChartSpaceDocument.Factory.parse(part.getInputStream(), DEFAULT_XML_OPTIONS).getChartSpace(); - chart = chartSpace.getChart(); - } - - /** - * Construct a new CTChartSpace bean. - * By default, it's just an empty placeholder for chart objects. - * - * @return a new CTChartSpace bean - */ - private void createChart() { - chartSpace = CTChartSpace.Factory.newInstance(); - chart = chartSpace.addNewChart(); - CTPlotArea plotArea = chart.addNewPlotArea(); - - plotArea.addNewLayout(); - chart.addNewPlotVisOnly().setVal(true); - - CTPrintSettings printSettings = chartSpace.addNewPrintSettings(); - printSettings.addNewHeaderFooter(); - - CTPageMargins pageMargins = printSettings.addNewPageMargins(); - pageMargins.setB(0.75); - pageMargins.setL(0.70); - pageMargins.setR(0.70); - pageMargins.setT(0.75); - pageMargins.setHeader(0.30); - pageMargins.setFooter(0.30); - printSettings.addNewPageSetup(); - } - - /** - * Return the underlying CTChartSpace bean, the root element of the SpreadsheetML Chart part. - * - * @return the underlying CTChartSpace bean - */ - @Internal - public CTChartSpace getCTChartSpace(){ - return chartSpace; - } - - /** - * Return the underlying CTChart bean, within the Chart Space - * - * @return the underlying CTChart bean - */ - @Internal - public CTChart getCTChart(){ - return chart; - } - - @Override - protected void commit() throws IOException { - XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS); - - /* - Saved chart space must have the following namespaces set: - - */ - xmlOptions.setSaveSyntheticDocumentElement(new QName(CTChartSpace.type.getName().getNamespaceURI(), "chartSpace", "c")); - - PackagePart part = getPackagePart(); - OutputStream out = part.getOutputStream(); - chartSpace.save(out, xmlOptions); - out.close(); - } - - /** - * Returns the parent graphic frame. - * @return the graphic frame this chart belongs to - */ - public XSSFGraphicFrame getGraphicFrame() { - return frame; - } - - /** - * Sets the parent graphic frame. - */ - protected void setGraphicFrame(XSSFGraphicFrame frame) { - this.frame = frame; - } - - public XSSFChartDataFactory getChartDataFactory() { - return XSSFChartDataFactory.getInstance(); - } - - public XSSFChart getChartAxisFactory() { - return this; - } - - public void plot(ChartData data, ChartAxis... chartAxis) { - data.fillChart(this, chartAxis); - } - - public XSSFValueAxis createValueAxis(AxisPosition pos) { - long id = axis.size() + 1; - XSSFValueAxis valueAxis = new XSSFValueAxis(this, id, pos); - if (axis.size() == 1) { - ChartAxis ax = axis.get(0); - ax.crossAxis(valueAxis); - valueAxis.crossAxis(ax); - } - axis.add(valueAxis); - return valueAxis; - } - - public XSSFCategoryAxis createCategoryAxis(AxisPosition pos) { - long id = axis.size() + 1; - XSSFCategoryAxis categoryAxis = new XSSFCategoryAxis(this, id, pos); - if (axis.size() == 1) { - ChartAxis ax = axis.get(0); - ax.crossAxis(categoryAxis); - categoryAxis.crossAxis(ax); - } - axis.add(categoryAxis); - return categoryAxis; - } - - public List getAxis() { - if (axis.isEmpty() && hasAxis()) { - parseAxis(); - } - return axis; - } - - public XSSFManualLayout getManualLayout() { - return new XSSFManualLayout(this); - } - - /** - * @return true if only visible cells will be present on the chart, - * false otherwise - */ - public boolean isPlotOnlyVisibleCells() { - return chart.getPlotVisOnly().getVal(); - } - - /** - * @param plotVisOnly a flag specifying if only visible cells should be - * present on the chart - */ - public void setPlotOnlyVisibleCells(boolean plotVisOnly) { - chart.getPlotVisOnly().setVal(plotVisOnly); - } - - /** - * Returns the title static text, or null if none is set. - * Note that a title formula may be set instead. - * @return static title text, if set - * @deprecated POI 3.16, use {@link #getTitleText()} instead. - */ - @Deprecated - @Removal(version="4.0") - public XSSFRichTextString getTitle() { - return getTitleText(); - } - - /** - * Returns the title static text, or null if none is set. - * Note that a title formula may be set instead. - * Empty text result is for backward compatibility, and could mean the title text is empty or there is a formula instead. - * Check for a formula first, falling back on text for cleaner logic. - * @return static title text if set, - * null if there is no title, - * empty string if the title text is empty or the title uses a formula instead - */ - public XSSFRichTextString getTitleText() { - if(! chart.isSetTitle()) { - return null; - } - - // TODO Do properly - CTTitle title = chart.getTitle(); - - StringBuffer text = new StringBuffer(); - XmlObject[] t = title - .selectPath("declare namespace a='"+XSSFDrawing.NAMESPACE_A+"' .//a:t"); - for (int m = 0; m < t.length; m++) { - NodeList kids = t[m].getDomNode().getChildNodes(); - final int count = kids.getLength(); - for (int n = 0; n < count; n++) { - Node kid = kids.item(n); - if (kid instanceof Text) { - text.append(kid.getNodeValue()); - } - } - } - - return new XSSFRichTextString(text.toString()); - } - - /** - * Sets the title text as a static string. - * @param newTitle to use - * @deprecated POI 3.16, use {@link #setTitleText(String)} instead. - */ - @Deprecated - @Removal(version="4.0") - public void setTitle(String newTitle) { - - } - - /** - * Sets the title text as a static string. - * @param newTitle to use - */ - public void setTitleText(String newTitle) { - CTTitle ctTitle; - if (chart.isSetTitle()) { - ctTitle = chart.getTitle(); - } else { - ctTitle = chart.addNewTitle(); - } - - CTTx tx; - if (ctTitle.isSetTx()) { - tx = ctTitle.getTx(); - } else { - tx = ctTitle.addNewTx(); - } - - if (tx.isSetStrRef()) { - tx.unsetStrRef(); - } - - CTTextBody rich; - if (tx.isSetRich()) { - rich = tx.getRich(); - } else { - rich = tx.addNewRich(); - rich.addNewBodyPr(); // body properties must exist (but can be empty) - } - - CTTextParagraph para; - if (rich.sizeOfPArray() > 0) { - para = rich.getPArray(0); - } else { - para = rich.addNewP(); - } - - if (para.sizeOfRArray() > 0) { - CTRegularTextRun run = para.getRArray(0); - run.setT(newTitle); - } else if (para.sizeOfFldArray() > 0) { - CTTextField fld = para.getFldArray(0); - fld.setT(newTitle); - } else { - CTRegularTextRun run = para.addNewR(); - run.setT(newTitle); - } - } - - /** - * Get the chart title formula expression if there is one - * @return formula expression or null - */ - public String getTitleFormula() { - if(! chart.isSetTitle()) { - return null; - } - - CTTitle title = chart.getTitle(); - - if (! title.isSetTx()) { - return null; - } - - CTTx tx = title.getTx(); - - if (! tx.isSetStrRef()) { - return null; - } - - return tx.getStrRef().getF(); - } - - /** - * Set the formula expression to use for the chart title - * @param formula - */ - public void setTitleFormula(String formula) { - CTTitle ctTitle; - if (chart.isSetTitle()) { - ctTitle = chart.getTitle(); - } else { - ctTitle = chart.addNewTitle(); - } - - CTTx tx; - if (ctTitle.isSetTx()) { - tx = ctTitle.getTx(); - } else { - tx = ctTitle.addNewTx(); - } - - if (tx.isSetRich()) { - tx.unsetRich(); - } - - CTStrRef strRef; - if (tx.isSetStrRef()) { - strRef = tx.getStrRef(); - } else { - strRef = tx.addNewStrRef(); - } - - strRef.setF(formula); - } - - public XSSFChartLegend getOrCreateLegend() { - return new XSSFChartLegend(this); - } - - public void deleteLegend() { - if (chart.isSetLegend()) { - chart.unsetLegend(); - } - } - - private boolean hasAxis() { - CTPlotArea ctPlotArea = chart.getPlotArea(); - int totalAxisCount = - ctPlotArea.sizeOfValAxArray() + - ctPlotArea.sizeOfCatAxArray() + - ctPlotArea.sizeOfDateAxArray() + - ctPlotArea.sizeOfSerAxArray(); - return totalAxisCount > 0; - } - - private void parseAxis() { - // TODO: add other axis types - parseCategoryAxis(); - parseValueAxis(); - } - - private void parseCategoryAxis() { - for (CTCatAx catAx : chart.getPlotArea().getCatAxArray()) { - axis.add(new XSSFCategoryAxis(this, catAx)); - } - } - - private void parseValueAxis() { - for (CTValAx valAx : chart.getPlotArea().getValAxArray()) { - axis.add(new XSSFValueAxis(this, valAx)); - } - } - -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFChartSheet.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFChartSheet.java deleted file mode 100644 index 589cc19aa..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFChartSheet.java +++ /dev/null @@ -1,108 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import static org.apache.poi.POIXMLTypeLoader.DEFAULT_XML_OPTIONS; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import javax.xml.namespace.QName; - -import org.apache.poi.POIXMLException; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlOptions; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTChartsheet; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTDrawing; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTLegacyDrawing; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.ChartsheetDocument; - -/** - * High level representation of Sheet Parts that are of type 'chartsheet'. - *

    - * Chart sheet is a special kind of Sheet that contains only chart and no data. - *

    - * - * @author Yegor Kozlov - */ -public class XSSFChartSheet extends XSSFSheet { - - private static final byte[] BLANK_WORKSHEET = blankWorksheet(); - - protected CTChartsheet chartsheet; - - /** - * @since POI 3.14-Beta1 - */ - protected XSSFChartSheet(PackagePart part) { - super(part); - } - - protected void read(InputStream is) throws IOException { - //initialize the supeclass with a blank worksheet - super.read(new ByteArrayInputStream(BLANK_WORKSHEET)); - - try { - chartsheet = ChartsheetDocument.Factory.parse(is, DEFAULT_XML_OPTIONS).getChartsheet(); - } catch (XmlException e){ - throw new POIXMLException(e); - } - } - - /** - * Provide access to the CTChartsheet bean holding this sheet's data - * - * @return the CTChartsheet bean holding this sheet's data - */ - public CTChartsheet getCTChartsheet() { - return chartsheet; - } - - @Override - protected CTDrawing getCTDrawing() { - return chartsheet.getDrawing(); - } - - @Override - protected CTLegacyDrawing getCTLegacyDrawing() { - return chartsheet.getLegacyDrawing(); - } - - @Override - protected void write(OutputStream out) throws IOException { - XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS); - xmlOptions.setSaveSyntheticDocumentElement( - new QName(CTChartsheet.type.getName().getNamespaceURI(), "chartsheet")); - chartsheet.save(out, xmlOptions); - - } - - private static byte[] blankWorksheet(){ - ByteArrayOutputStream out = new ByteArrayOutputStream(); - try { - new XSSFSheet().write(out); - } catch (IOException e){ - throw new RuntimeException(e); - } - return out.toByteArray(); - } -} \ No newline at end of file diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFChildAnchor.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFChildAnchor.java deleted file mode 100644 index 4dc3db8c4..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFChildAnchor.java +++ /dev/null @@ -1,84 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import org.openxmlformats.schemas.drawingml.x2006.main.CTPoint2D; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTransform2D; -import org.apache.poi.util.Internal; - -/** - * @author Yegor Kozlov - */ -public final class XSSFChildAnchor extends XSSFAnchor { - private CTTransform2D t2d; - - public XSSFChildAnchor(int x, int y, int cx, int cy) { - t2d = CTTransform2D.Factory.newInstance(); - CTPoint2D off = t2d.addNewOff(); - CTPositiveSize2D ext = t2d.addNewExt(); - - off.setX(x); - off.setY(y); - ext.setCx(Math.abs(cx - x)); - ext.setCy(Math.abs(cy - y)); - if(x > cx) t2d.setFlipH(true); - if(y > cy) t2d.setFlipV(true); - } - - public XSSFChildAnchor(CTTransform2D t2d) { - this.t2d = t2d; - } - - @Internal - public CTTransform2D getCTTransform2D() { - return t2d; - } - - public int getDx1() { - return (int)t2d.getOff().getX(); - } - - public void setDx1(int dx1) { - t2d.getOff().setX(dx1); - } - - public int getDy1() { - return (int)t2d.getOff().getY(); - } - - public void setDy1(int dy1) { - t2d.getOff().setY(dy1); - } - - public int getDy2() { - return (int)(getDy1() + t2d.getExt().getCy()); - } - - public void setDy2(int dy2) { - t2d.getExt().setCy(dy2 - getDy1()); - } - - public int getDx2() { - return (int)(getDx1() + t2d.getExt().getCx()); - } - - public void setDx2(int dx2) { - t2d.getExt().setCx(dx2 - getDx1()); - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFClientAnchor.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFClientAnchor.java deleted file mode 100644 index df47fc227..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFClientAnchor.java +++ /dev/null @@ -1,256 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import org.apache.poi.ss.usermodel.ClientAnchor; -import org.apache.poi.util.Internal; -import org.apache.poi.util.Removal; -import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTMarker; - -/** - * A client anchor is attached to an excel worksheet. It anchors against - * top-left and bottom-right cells. - * - * @author Yegor Kozlov - */ -public final class XSSFClientAnchor extends XSSFAnchor implements ClientAnchor { - private AnchorType DEFAULT_ANCHOR_TYPE = AnchorType.MOVE_AND_RESIZE; - private AnchorType anchorType; - - /** - * Starting anchor point - */ - private CTMarker cell1; - - /** - * Ending anchor point - */ - private CTMarker cell2; - - /** - * Creates a new client anchor and defaults all the anchor positions to 0. - */ - public XSSFClientAnchor() { - anchorType = DEFAULT_ANCHOR_TYPE; - cell1 = CTMarker.Factory.newInstance(); - cell1.setCol(0); - cell1.setColOff(0); - cell1.setRow(0); - cell1.setRowOff(0); - cell2 = CTMarker.Factory.newInstance(); - cell2.setCol(0); - cell2.setColOff(0); - cell2.setRow(0); - cell2.setRowOff(0); - } - - /** - * Creates a new client anchor and sets the top-left and bottom-right - * coordinates of the anchor. - * - * @param dx1 the x coordinate within the first cell. - * @param dy1 the y coordinate within the first cell. - * @param dx2 the x coordinate within the second cell. - * @param dy2 the y coordinate within the second cell. - * @param col1 the column (0 based) of the first cell. - * @param row1 the row (0 based) of the first cell. - * @param col2 the column (0 based) of the second cell. - * @param row2 the row (0 based) of the second cell. - */ - public XSSFClientAnchor(int dx1, int dy1, int dx2, int dy2, int col1, int row1, int col2, int row2) { - this(); - cell1.setCol(col1); - cell1.setColOff(dx1); - cell1.setRow(row1); - cell1.setRowOff(dy1); - cell2.setCol(col2); - cell2.setColOff(dx2); - cell2.setRow(row2); - cell2.setRowOff(dy2); - } - - /** - * Create XSSFClientAnchor from existing xml beans - * - * @param cell1 starting anchor point - * @param cell2 ending anchor point - */ - protected XSSFClientAnchor(CTMarker cell1, CTMarker cell2) { - anchorType = DEFAULT_ANCHOR_TYPE; - this.cell1 = cell1; - this.cell2 = cell2; - } - - public short getCol1() { - return (short)cell1.getCol(); - } - - public void setCol1(int col1) { - cell1.setCol(col1); - } - - public short getCol2() { - return (short)cell2.getCol(); - } - - public void setCol2(int col2) { - cell2.setCol(col2); - } - - public int getRow1() { - return cell1.getRow(); - } - - public void setRow1(int row1) { - cell1.setRow(row1); - } - - public int getRow2() { - return cell2.getRow(); - } - - public void setRow2(int row2) { - cell2.setRow(row2); - } - - public int getDx1() { - return (int)cell1.getColOff(); - } - - public void setDx1(int dx1) { - cell1.setColOff(dx1); - } - - public int getDy1() { - return (int)cell1.getRowOff(); - } - - public void setDy1(int dy1) { - cell1.setRowOff(dy1); - } - - public int getDy2() { - return (int)cell2.getRowOff(); - } - - public void setDy2(int dy2) { - cell2.setRowOff(dy2); - } - - public int getDx2() { - return (int)cell2.getColOff(); - } - - public void setDx2(int dx2) { - cell2.setColOff(dx2); - } - - @Override - public boolean equals(Object o) { - if (o == null || !(o instanceof XSSFClientAnchor)) return false; - - XSSFClientAnchor anchor = (XSSFClientAnchor) o; - return getDx1() == anchor.getDx1() && - getDx2() == anchor.getDx2() && - getDy1() == anchor.getDy1() && - getDy2() == anchor.getDy2() && - getCol1() == anchor.getCol1() && - getCol2() == anchor.getCol2() && - getRow1() == anchor.getRow1() && - getRow2() == anchor.getRow2() ; - - } - - @Override - public int hashCode() { - assert false : "hashCode not designed"; - return 42; // any arbitrary constant will do - } - - @Override - public String toString(){ - return "from : " + cell1.toString() + "; to: " + cell2.toString(); - } - - /** - * Return starting anchor point - * - * @return starting anchor point - */ - @Internal - public CTMarker getFrom(){ - return cell1; - } - - protected void setFrom(CTMarker from){ - cell1 = from; - } - - /** - * Return ending anchor point - * - * @return ending anchor point - */ - @Internal - public CTMarker getTo(){ - return cell2; - } - - protected void setTo(CTMarker to){ - cell2 = to; - } - - - /** - * Sets the anchor type - * @param anchorType the anchor type to set - * @since POI 3.14 - */ - @Override - public void setAnchorType( AnchorType anchorType ) - { - this.anchorType = anchorType; - } - /** - * Sets the anchor type - * @param anchorType the anchor type to set - * @deprecated POI 3.15. Use {@link #setAnchorType(AnchorType)} instead - */ - @Removal(version="3.17") - @Override - public void setAnchorType( int anchorType ) - { - this.anchorType = AnchorType.byId(anchorType); - } - - /** - * Gets the anchor type - * Changed from returning an int to an enum in POI 3.14 beta 1. - * @return the anchor type - */ - @Override - public AnchorType getAnchorType() - { - return anchorType; - } - - public boolean isSet(){ - return !(cell1.getCol() == 0 && cell2.getCol() == 0 && - cell1.getRow() == 0 && cell2.getRow() == 0); - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFColor.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFColor.java deleted file mode 100644 index 441f42fdb..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFColor.java +++ /dev/null @@ -1,395 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel; - -import java.util.Arrays; - -import org.apache.poi.ss.usermodel.Color; -import org.apache.poi.ss.usermodel.ExtendedColor; -import org.apache.poi.ss.usermodel.IndexedColors; -import org.apache.poi.util.Internal; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTColor; - -/** - * Represents a color in SpreadsheetML - */ -public class XSSFColor extends ExtendedColor { - private final CTColor ctColor; - - /** - * Create an instance of XSSFColor from the supplied XML bean - */ - public XSSFColor(CTColor color) { - this.ctColor = color; - } - - /** - * Create an new instance of XSSFColor - */ - public XSSFColor() { - this.ctColor = CTColor.Factory.newInstance(); - } - - public XSSFColor(java.awt.Color clr) { - this(); - setColor(clr); - } - - public XSSFColor(byte[] rgb) { - this(); - ctColor.setRgb(rgb); - } - - public XSSFColor(IndexedColors indexedColor) { - this(); - ctColor.setIndexed(indexedColor.index); - } - - /** - * A boolean value indicating the ctColor is automatic and system ctColor dependent. - */ - @Override - public boolean isAuto() { - return ctColor.getAuto(); - } - /** - * A boolean value indicating the ctColor is automatic and system ctColor dependent. - */ - public void setAuto(boolean auto) { - ctColor.setAuto(auto); - } - - /** - * A boolean value indicating the ctColor is Indexed - */ - @Override - public boolean isIndexed() { - return ctColor.isSetIndexed(); - } - - /** - * A boolean value indicating the ctColor is RGB or ARGB based - */ - @Override - public boolean isRGB() { - return ctColor.isSetRgb(); - } - - /** - * A boolean value indicating the ctColor is Theme based - */ - @Override - public boolean isThemed() { - return ctColor.isSetTheme(); - } - - /** - * A boolean value indicating if the ctColor has a alpha or not - */ - public boolean hasAlpha() { - if (! ctColor.isSetRgb()) { - return false; - } - return ctColor.getRgb().length == 4; - } - - /** - * A boolean value indicating if the ctColor has a tint or not - */ - public boolean hasTint() { - if (!ctColor.isSetTint()) { - return false; - } - return ctColor.getTint() != 0; - } - - /** - * Indexed ctColor value. Only used for backwards compatibility. References a ctColor in indexedColors. - */ - @Override - public short getIndex() { - return (short)ctColor.getIndexed(); - } - /** - * Indexed ctColor value. Only used for backwards compatibility. References a ctColor in indexedColors. - */ - public short getIndexed() { - return getIndex(); - } - - /** - * Indexed ctColor value. Only used for backwards compatibility. References a ctColor in indexedColors. - */ - public void setIndexed(int indexed) { - ctColor.setIndexed(indexed); - } - - /** - * Standard Red Green Blue ctColor value (RGB). - * If there was an A (Alpha) value, it will be stripped. - */ - @Override - public byte[] getRGB() { - byte[] rgb = getRGBOrARGB(); - if(rgb == null) { - return null; - } - - if(rgb.length == 4) { - // Need to trim off the alpha - byte[] tmp = new byte[3]; - System.arraycopy(rgb, 1, tmp, 0, 3); - return tmp; - } else { - return rgb; - } - } - - /** - * Standard Alpha Red Green Blue ctColor value (ARGB). - */ - @Override - public byte[] getARGB() { - byte[] rgb = getRGBOrARGB(); - if(rgb == null) { - return null; - } - - if(rgb.length == 3) { - // Pad with the default Alpha - byte[] tmp = new byte[4]; - tmp[0] = -1; - System.arraycopy(rgb, 0, tmp, 1, 3); - return tmp; - } else { - return rgb; - } - } - - @Override - protected byte[] getStoredRBG() { - return ctColor.getRgb(); - } - - /** - * Standard Alpha Red Green Blue ctColor value (ARGB). - */ - @Override - public void setRGB(byte[] rgb) { - ctColor.setRgb(rgb); - } - - /** - * Index into the collection, referencing a particular or - * value expressed in the Theme part. - */ - @Override - public int getTheme() { - return (int)ctColor.getTheme(); - } - - /** - * Index into the collection, referencing a particular or - * value expressed in the Theme part. - */ - public void setTheme(int theme) { - ctColor.setTheme(theme); - } - - /** - * Specifies the tint value applied to the ctColor. - * - *

    - * If tint is supplied, then it is applied to the RGB value of the ctColor to determine the final - * ctColor applied. - *

    - *

    - * The tint value is stored as a double from -1.0 .. 1.0, where -1.0 means 100% darken and - * 1.0 means 100% lighten. Also, 0.0 means no change. - *

    - *

    - * In loading the RGB value, it is converted to HLS where HLS values are (0..HLSMAX), where - * HLSMAX is currently 255. - *

    - * Here are some examples of how to apply tint to ctColor: - *
    - *
    -     * If (tint < 0)
    -     * Lum' = Lum * (1.0 + tint)
    -     *
    -     * For example: Lum = 200; tint = -0.5; Darken 50%
    -     * Lum' = 200 * (0.5) => 100
    -     * For example: Lum = 200; tint = -1.0; Darken 100% (make black)
    -     * Lum' = 200 * (1.0-1.0) => 0
    -     * If (tint > 0)
    -     * Lum' = Lum * (1.0-tint) + (HLSMAX - HLSMAX * (1.0-tint))
    -     * For example: Lum = 100; tint = 0.75; Lighten 75%
    -     *
    -     * Lum' = 100 * (1-.75) + (HLSMAX - HLSMAX*(1-.75))
    -     * = 100 * .25 + (255 - 255 * .25)
    -     * = 25 + (255 - 63) = 25 + 192 = 217
    -     * For example: Lum = 100; tint = 1.0; Lighten 100% (make white)
    -     * Lum' = 100 * (1-1) + (HLSMAX - HLSMAX*(1-1))
    -     * = 100 * 0 + (255 - 255 * 0)
    -     * = 0 + (255 - 0) = 255
    -     * 
    - *
    - * - * @return the tint value - */ - @Override - public double getTint() { - return ctColor.getTint(); - } - - /** - * Specifies the tint value applied to the ctColor. - * - *

    - * If tint is supplied, then it is applied to the RGB value of the ctColor to determine the final - * ctColor applied. - *

    - *

    - * The tint value is stored as a double from -1.0 .. 1.0, where -1.0 means 100% darken and - * 1.0 means 100% lighten. Also, 0.0 means no change. - *

    - *

    - * In loading the RGB value, it is converted to HLS where HLS values are (0..HLSMAX), where - * HLSMAX is currently 255. - *

    - * Here are some examples of how to apply tint to ctColor: - *
    - *
    -     * If (tint < 0)
    -     * Lum' = Lum * (1.0 + tint)
    -     *
    -     * For example: Lum = 200; tint = -0.5; Darken 50%
    -     * Lum' = 200 * (0.5) => 100
    -     * For example: Lum = 200; tint = -1.0; Darken 100% (make black)
    -     * Lum' = 200 * (1.0-1.0) => 0
    -     * If (tint > 0)
    -     * Lum' = Lum * (1.0-tint) + (HLSMAX - HLSMAX * (1.0-tint))
    -     * For example: Lum = 100; tint = 0.75; Lighten 75%
    -     *
    -     * Lum' = 100 * (1-.75) + (HLSMAX - HLSMAX*(1-.75))
    -     * = 100 * .25 + (255 - 255 * .25)
    -     * = 25 + (255 - 63) = 25 + 192 = 217
    -     * For example: Lum = 100; tint = 1.0; Lighten 100% (make white)
    -     * Lum' = 100 * (1-1) + (HLSMAX - HLSMAX*(1-1))
    -     * = 100 * 0 + (255 - 255 * 0)
    -     * = 0 + (255 - 0) = 255
    -     * 
    - *
    - * - * @param tint the tint value - */ - @Override - public void setTint(double tint) { - ctColor.setTint(tint); - } - - /** - * Returns the underlying XML bean - * - * @return the underlying XML bean - */ - @Internal - public CTColor getCTColor(){ - return ctColor; - } - - /** - * Checked type cast color to an XSSFColor. - * - * @param color the color to type cast - * @return the type casted color - * @throws IllegalArgumentException if color is null or is not an instance of XSSFColor - */ - public static XSSFColor toXSSFColor(Color color) { - // FIXME: this method would be more useful if it could convert any Color to an XSSFColor - // Currently the only benefit of this method is to throw an IllegalArgumentException - // instead of a ClassCastException. - if (color != null && !(color instanceof XSSFColor)) { - throw new IllegalArgumentException("Only XSSFColor objects are supported"); - } - return (XSSFColor)color; - } - - @Override - public int hashCode(){ - return ctColor.toString().hashCode(); - } - - // Helper methods for {@link #equals(Object)} - private boolean sameIndexed(XSSFColor other) { - if (isIndexed() == other.isIndexed()) { - if (isIndexed()) { - return getIndexed() == other.getIndexed(); - } - return true; - } - return false; - } - private boolean sameARGB(XSSFColor other) { - if (isRGB() == other.isRGB()) { - if (isRGB()) { - return Arrays.equals(getARGB(), other.getARGB()); - } - return true; - } - return false; - } - private boolean sameTheme(XSSFColor other) { - if (isThemed() == other.isThemed()) { - if (isThemed()) { - return getTheme() == other.getTheme(); - } - return true; - } - return false; - } - private boolean sameTint(XSSFColor other) { - if (hasTint() == other.hasTint()) { - if (hasTint()) { - return getTint() == other.getTint(); - } - return true; - } - return false; - } - private boolean sameAuto(XSSFColor other) { - return isAuto() == other.isAuto(); - } - - @Override - public boolean equals(Object o){ - if(!(o instanceof XSSFColor)) { - return false; - } - - XSSFColor other = (XSSFColor)o; - - // Compare each field in ctColor. - // Cannot compare ctColor's XML string representation because equivalent - // colors may have different relation namespace URI's - return sameARGB(other) - && sameTheme(other) - && sameIndexed(other) - && sameTint(other) - && sameAuto(other); - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFColorScaleFormatting.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFColorScaleFormatting.java deleted file mode 100644 index 910e8b297..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFColorScaleFormatting.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -package org.apache.poi.xssf.usermodel; - -import org.apache.poi.ss.usermodel.Color; -import org.apache.poi.ss.usermodel.ColorScaleFormatting; -import org.apache.poi.ss.usermodel.ConditionalFormattingThreshold; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCfvo; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTColor; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTColorScale; - -/** - * High level representation for Color Scale / Color Gradient Formatting - * component of Conditional Formatting settings - */ -public class XSSFColorScaleFormatting implements ColorScaleFormatting { - CTColorScale _scale; - - /*package*/ XSSFColorScaleFormatting(CTColorScale scale){ - _scale = scale; - } - - public int getNumControlPoints() { - return _scale.sizeOfCfvoArray(); - } - public void setNumControlPoints(int num) { - while (num < _scale.sizeOfCfvoArray()) { - _scale.removeCfvo(_scale.sizeOfCfvoArray()-1); - _scale.removeColor(_scale.sizeOfColorArray()-1); - } - while (num > _scale.sizeOfCfvoArray()) { - _scale.addNewCfvo(); - _scale.addNewColor(); - } - } - - public XSSFColor[] getColors() { - CTColor[] ctcols = _scale.getColorArray(); - XSSFColor[] c = new XSSFColor[ctcols.length]; - for (int i=0; i 0) { - CellReference ref = new CellReference(comment.getRef()); - CTClientData clientData = vmlShape.getClientDataArray(0); - clientData.setRowArray(0, new BigInteger(String.valueOf(ref.getRow()))); - clientData.setColumnArray(0, new BigInteger(String.valueOf(ref.getCol()))); - - avoidXmlbeansCorruptPointer(vmlShape); - } - } - - /** - * - * @return Name of the original comment author. Default value is blank. - */ - @Override - public String getAuthor() { - return _comments.getAuthor((int) _comment.getAuthorId()); - } - - /** - * Name of the original comment author. Default value is blank. - * - * @param author the name of the original author of the comment - */ - @Override - public void setAuthor(String author) { - _comment.setAuthorId( - _comments.findAuthor(author) - ); - } - - /** - * @return the 0-based column of the cell that the comment is associated with. - */ - @Override - public int getColumn() { - return getAddress().getColumn(); - } - - /** - * @return the 0-based row index of the cell that the comment is associated with. - */ - @Override - public int getRow() { - return getAddress().getRow(); - } - - /** - * Returns whether this comment is visible. - * - * @return true if the comment is visible, false otherwise - */ - @Override - public boolean isVisible() { - boolean visible = false; - if(_vmlShape != null){ - String style = _vmlShape.getStyle(); - visible = style != null && style.indexOf("visibility:visible") != -1; - } - return visible; - } - - /** - * Sets whether this comment is visible. - * - * @param visible true if the comment is visible, false otherwise - */ - @Override - public void setVisible(boolean visible) { - if(_vmlShape != null){ - String style; - if(visible) style = "position:absolute;visibility:visible"; - else style = "position:absolute;visibility:hidden"; - _vmlShape.setStyle(style); - } - } - - @Override - public CellAddress getAddress() { - return new CellAddress(_comment.getRef()); - } - - @Override - public void setAddress(int row, int col) { - setAddress(new CellAddress(row, col)); - } - - @Override - public void setAddress(CellAddress address) { - CellAddress oldRef = new CellAddress(_comment.getRef()); - if (address.equals(oldRef)) { - // nothing to do - return; - } - - _comment.setRef(address.formatAsString()); - _comments.referenceUpdated(oldRef, _comment); - - if (_vmlShape != null) { - CTClientData clientData = _vmlShape.getClientDataArray(0); - clientData.setRowArray(0, new BigInteger(String.valueOf(address.getRow()))); - clientData.setColumnArray(0, new BigInteger(String.valueOf(address.getColumn()))); - - avoidXmlbeansCorruptPointer(_vmlShape); - } - } - - /** - * Set the column of the cell that contains the comment - * - * If changing both row and column, use {@link #setAddress}. - * - * @param col the 0-based column of the cell that contains the comment - */ - @Override - public void setColumn(int col) { - setAddress(getRow(), col); - } - - /** - * Set the row of the cell that contains the comment - * - * If changing both row and column, use {@link #setAddress}. - * - * @param row the 0-based row of the cell that contains the comment - */ - @Override - public void setRow(int row) { - setAddress(row, getColumn()); - } - - /** - * @return the rich text string of the comment - */ - @Override - public XSSFRichTextString getString() { - if(_str == null) { - CTRst rst = _comment.getText(); - if(rst != null) _str = new XSSFRichTextString(_comment.getText()); - } - return _str; - } - - /** - * Sets the rich text string used by this comment. - * - * @param string the XSSFRichTextString used by this object. - */ - @Override - public void setString(RichTextString string) { - if(!(string instanceof XSSFRichTextString)){ - throw new IllegalArgumentException("Only XSSFRichTextString argument is supported"); - } - _str = (XSSFRichTextString)string; - _comment.setText(_str.getCTRst()); - } - - public void setString(String string) { - setString(new XSSFRichTextString(string)); - } - - @Override - public ClientAnchor getClientAnchor() { - String position = _vmlShape.getClientDataArray(0).getAnchorArray(0); - int[] pos = new int[8]; - int i = 0; - for (String s : position.split(",")) { - pos[i++] = Integer.parseInt(s.trim()); - } - XSSFClientAnchor ca = new XSSFClientAnchor(pos[1]*EMU_PER_PIXEL, pos[3]*EMU_PER_PIXEL, pos[5]*EMU_PER_PIXEL, pos[7]*EMU_PER_PIXEL, pos[0], pos[2], pos[4], pos[6]); - return ca; - } - - /** - * @return the xml bean holding this comment's properties - */ - protected CTComment getCTComment(){ - return _comment; - } - - protected CTShape getCTShape(){ - return _vmlShape; - } - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof XSSFComment)) { - return false; - } - XSSFComment other = (XSSFComment) obj; - return ((getCTComment() == other.getCTComment()) && - (getCTShape() == other.getCTShape())); - } - - @Override - public int hashCode() { - return ((getRow()*17) + getColumn())*31; - } - - private static void avoidXmlbeansCorruptPointer(CTShape vmlShape) { - // There is a very odd xmlbeans bug when changing the row - // arrays which can lead to corrupt pointer - // This call seems to fix them again... See bug #50795 - vmlShape.getClientDataList().toString(); - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFConditionFilterData.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFConditionFilterData.java deleted file mode 100644 index 59bfb9406..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFConditionFilterData.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xssf.usermodel; - -import org.apache.poi.ss.usermodel.ConditionFilterData; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCfRule; - -public class XSSFConditionFilterData implements ConditionFilterData { - - private final CTCfRule _cfRule; - - /*package*/ XSSFConditionFilterData(CTCfRule cfRule) { - _cfRule = cfRule; - } - - public boolean getAboveAverage() { - return _cfRule.getAboveAverage(); - } - - public boolean getBottom() { - return _cfRule.getBottom(); - } - - public boolean getEqualAverage() { - return _cfRule.getEqualAverage(); - } - - public boolean getPercent() { - return _cfRule.getPercent(); - } - - public long getRank() { - return _cfRule.getRank(); - } - - public int getStdDev() { - return _cfRule.getStdDev(); - } - -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFConditionalFormatting.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFConditionalFormatting.java deleted file mode 100644 index 821fd4164..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFConditionalFormatting.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xssf.usermodel; - -import org.apache.poi.ss.usermodel.ConditionalFormatting; -import org.apache.poi.ss.usermodel.ConditionalFormattingRule; -import org.apache.poi.ss.util.CellRangeAddress; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTConditionalFormatting; - -import java.util.ArrayList; -import java.util.Collections; - -/** - * @author Yegor Kozlov - */ -public class XSSFConditionalFormatting implements ConditionalFormatting { - private final CTConditionalFormatting _cf; - private final XSSFSheet _sh; - - /*package*/ XSSFConditionalFormatting(XSSFSheet sh) { - _cf = CTConditionalFormatting.Factory.newInstance(); - _sh = sh; - } - - /*package*/ XSSFConditionalFormatting( - XSSFSheet sh, CTConditionalFormatting cf) { - _cf = cf; - _sh = sh; - } - - /*package*/ CTConditionalFormatting getCTConditionalFormatting() { - return _cf; - } - - /** - * @return array of CellRangeAddresss. Never null - */ - @Override - public CellRangeAddress[] getFormattingRanges() { - ArrayList lst = new ArrayList(); - for (Object stRef : _cf.getSqref()) { - String[] regions = stRef.toString().split(" "); - for (final String region : regions) { - lst.add(CellRangeAddress.valueOf(region)); - } - } - return lst.toArray(new CellRangeAddress[lst.size()]); - } - - @Override - public void setFormattingRanges(CellRangeAddress[] ranges) { - if (ranges == null) { - throw new IllegalArgumentException("cellRanges must not be null"); - } - final StringBuilder sb = new StringBuilder(); - boolean first = true; - for (CellRangeAddress range : ranges) { - if (!first) { - sb.append(" "); - } else { - first = false; - } - sb.append(range.formatAsString()); - } - _cf.setSqref(Collections.singletonList(sb.toString())); - } - - /** - * Replaces an existing Conditional Formatting rule at position idx. - * Excel allows to create up to 3 Conditional Formatting rules. - * This method can be useful to modify existing Conditional Formatting rules. - * - * @param idx position of the rule. Should be between 0 and 2. - * @param cfRule - Conditional Formatting rule - */ - @Override - public void setRule(int idx, ConditionalFormattingRule cfRule) { - XSSFConditionalFormattingRule xRule = (XSSFConditionalFormattingRule) cfRule; - _cf.getCfRuleArray(idx).set(xRule.getCTCfRule()); - } - - /** - * Add a Conditional Formatting rule. - * Excel allows to create up to 3 Conditional Formatting rules. - * - * @param cfRule - Conditional Formatting rule - */ - @Override - public void addRule(ConditionalFormattingRule cfRule) { - XSSFConditionalFormattingRule xRule = (XSSFConditionalFormattingRule) cfRule; - _cf.addNewCfRule().set(xRule.getCTCfRule()); - } - - /** - * @return the Conditional Formatting rule at position idx. - */ - @Override - public XSSFConditionalFormattingRule getRule(int idx) { - return new XSSFConditionalFormattingRule(_sh, _cf.getCfRuleArray(idx)); - } - - /** - * @return number of Conditional Formatting rules. - */ - @Override - public int getNumberOfRules() { - return _cf.sizeOfCfRuleArray(); - } - - @Override - public String toString() { - return _cf.toString(); - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFConditionalFormattingRule.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFConditionalFormattingRule.java deleted file mode 100644 index 69816b7fa..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFConditionalFormattingRule.java +++ /dev/null @@ -1,403 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xssf.usermodel; - -import java.util.HashMap; -import java.util.Map; - -import org.apache.poi.ss.usermodel.*; -import org.apache.poi.ss.usermodel.ConditionalFormattingThreshold.RangeType; -import org.apache.poi.ss.usermodel.IconMultiStateFormatting.IconSet; -import org.apache.poi.xssf.usermodel.XSSFFontFormatting; -import org.apache.poi.xssf.model.StylesTable; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.*; - -/** - * XSSF support for Conditional Formatting rules - */ -public class XSSFConditionalFormattingRule implements ConditionalFormattingRule { - private final CTCfRule _cfRule; - private XSSFSheet _sh; - - private static Map typeLookup = new HashMap(); - private static Map filterTypeLookup = new HashMap(); - static { - typeLookup.put(STCfType.CELL_IS, ConditionType.CELL_VALUE_IS); - typeLookup.put(STCfType.EXPRESSION, ConditionType.FORMULA); - typeLookup.put(STCfType.COLOR_SCALE, ConditionType.COLOR_SCALE); - typeLookup.put(STCfType.DATA_BAR, ConditionType.DATA_BAR); - typeLookup.put(STCfType.ICON_SET, ConditionType.ICON_SET); - - // These are all subtypes of Filter, we think... - typeLookup.put(STCfType.TOP_10, ConditionType.FILTER); - typeLookup.put(STCfType.UNIQUE_VALUES, ConditionType.FILTER); - typeLookup.put(STCfType.DUPLICATE_VALUES, ConditionType.FILTER); - typeLookup.put(STCfType.CONTAINS_TEXT, ConditionType.FILTER); - typeLookup.put(STCfType.NOT_CONTAINS_TEXT, ConditionType.FILTER); - typeLookup.put(STCfType.BEGINS_WITH, ConditionType.FILTER); - typeLookup.put(STCfType.ENDS_WITH, ConditionType.FILTER); - typeLookup.put(STCfType.CONTAINS_BLANKS, ConditionType.FILTER); - typeLookup.put(STCfType.NOT_CONTAINS_BLANKS, ConditionType.FILTER); - typeLookup.put(STCfType.CONTAINS_ERRORS, ConditionType.FILTER); - typeLookup.put(STCfType.NOT_CONTAINS_ERRORS, ConditionType.FILTER); - typeLookup.put(STCfType.TIME_PERIOD, ConditionType.FILTER); - typeLookup.put(STCfType.ABOVE_AVERAGE, ConditionType.FILTER); - - filterTypeLookup.put(STCfType.TOP_10, ConditionFilterType.TOP_10); - filterTypeLookup.put(STCfType.UNIQUE_VALUES, ConditionFilterType.UNIQUE_VALUES); - filterTypeLookup.put(STCfType.DUPLICATE_VALUES, ConditionFilterType.DUPLICATE_VALUES); - filterTypeLookup.put(STCfType.CONTAINS_TEXT, ConditionFilterType.CONTAINS_TEXT); - filterTypeLookup.put(STCfType.NOT_CONTAINS_TEXT, ConditionFilterType.NOT_CONTAINS_TEXT); - filterTypeLookup.put(STCfType.BEGINS_WITH, ConditionFilterType.BEGINS_WITH); - filterTypeLookup.put(STCfType.ENDS_WITH, ConditionFilterType.ENDS_WITH); - filterTypeLookup.put(STCfType.CONTAINS_BLANKS, ConditionFilterType.CONTAINS_BLANKS); - filterTypeLookup.put(STCfType.NOT_CONTAINS_BLANKS, ConditionFilterType.NOT_CONTAINS_BLANKS); - filterTypeLookup.put(STCfType.CONTAINS_ERRORS, ConditionFilterType.CONTAINS_ERRORS); - filterTypeLookup.put(STCfType.NOT_CONTAINS_ERRORS, ConditionFilterType.NOT_CONTAINS_ERRORS); - filterTypeLookup.put(STCfType.TIME_PERIOD, ConditionFilterType.TIME_PERIOD); - filterTypeLookup.put(STCfType.ABOVE_AVERAGE, ConditionFilterType.ABOVE_AVERAGE); - - } - - /** - * NOTE: does not set priority, so this assumes the rule will not be added to the sheet yet - * @param sh - */ - /*package*/ XSSFConditionalFormattingRule(XSSFSheet sh){ - _cfRule = CTCfRule.Factory.newInstance(); - _sh = sh; - } - - /*package*/ XSSFConditionalFormattingRule(XSSFSheet sh, CTCfRule cfRule){ - _cfRule = cfRule; - _sh = sh; - } - - /*package*/ CTCfRule getCTCfRule(){ - return _cfRule; - } - - /*package*/ CTDxf getDxf(boolean create){ - StylesTable styles = _sh.getWorkbook().getStylesSource(); - CTDxf dxf = null; - if(styles._getDXfsSize() > 0 && _cfRule.isSetDxfId()){ - int dxfId = (int)_cfRule.getDxfId(); - dxf = styles.getDxfAt(dxfId); - } - if(create && dxf == null) { - dxf = CTDxf.Factory.newInstance(); - int dxfId = styles.putDxf(dxf); - _cfRule.setDxfId(dxfId - 1); - } - return dxf; - } - - public int getPriority() { - final int priority = _cfRule.getPriority(); - // priorities start at 1, if it is less, it is undefined, use definition order in caller - return priority >=1 ? priority : 0; - } - - public boolean getStopIfTrue() { - return _cfRule.getStopIfTrue(); - } - - /** - * Create a new border formatting structure if it does not exist, - * otherwise just return existing object. - * - * @return - border formatting object, never returns null. - */ - public XSSFBorderFormatting createBorderFormatting(){ - CTDxf dxf = getDxf(true); - CTBorder border; - if(!dxf.isSetBorder()) { - border = dxf.addNewBorder(); - } else { - border = dxf.getBorder(); - } - - return new XSSFBorderFormatting(border); - } - - /** - * @return - border formatting object if defined, null otherwise - */ - public XSSFBorderFormatting getBorderFormatting(){ - CTDxf dxf = getDxf(false); - if(dxf == null || !dxf.isSetBorder()) return null; - - return new XSSFBorderFormatting(dxf.getBorder()); - } - - /** - * Create a new font formatting structure if it does not exist, - * otherwise just return existing object. - * - * @return - font formatting object, never returns null. - */ - public XSSFFontFormatting createFontFormatting(){ - CTDxf dxf = getDxf(true); - CTFont font; - if(!dxf.isSetFont()) { - font = dxf.addNewFont(); - } else { - font = dxf.getFont(); - } - - return new XSSFFontFormatting(font); - } - - /** - * @return - font formatting object if defined, null otherwise - */ - public XSSFFontFormatting getFontFormatting(){ - CTDxf dxf = getDxf(false); - if(dxf == null || !dxf.isSetFont()) return null; - - return new XSSFFontFormatting(dxf.getFont()); - } - - /** - * Create a new pattern formatting structure if it does not exist, - * otherwise just return existing object. - * - * @return - pattern formatting object, never returns null. - */ - public XSSFPatternFormatting createPatternFormatting(){ - CTDxf dxf = getDxf(true); - CTFill fill; - if(!dxf.isSetFill()) { - fill = dxf.addNewFill(); - } else { - fill = dxf.getFill(); - } - - return new XSSFPatternFormatting(fill); - } - - /** - * @return - pattern formatting object if defined, null otherwise - */ - public XSSFPatternFormatting getPatternFormatting(){ - CTDxf dxf = getDxf(false); - if(dxf == null || !dxf.isSetFill()) return null; - - return new XSSFPatternFormatting(dxf.getFill()); - } - - public XSSFDataBarFormatting createDataBarFormatting(XSSFColor color) { - // Is it already there? - if (_cfRule.isSetDataBar() && _cfRule.getType() == STCfType.DATA_BAR) - return getDataBarFormatting(); - - // Mark it as being a Data Bar - _cfRule.setType(STCfType.DATA_BAR); - - // Ensure the right element - CTDataBar bar = null; - if (_cfRule.isSetDataBar()) { - bar = _cfRule.getDataBar(); - } else { - bar = _cfRule.addNewDataBar(); - } - // Set the color - bar.setColor(color.getCTColor()); - - // Add the default thresholds - CTCfvo min = bar.addNewCfvo(); - min.setType(STCfvoType.Enum.forString(RangeType.MIN.name)); - CTCfvo max = bar.addNewCfvo(); - max.setType(STCfvoType.Enum.forString(RangeType.MAX.name)); - - // Wrap and return - return new XSSFDataBarFormatting(bar); - } - public XSSFDataBarFormatting getDataBarFormatting() { - if (_cfRule.isSetDataBar()) { - CTDataBar bar = _cfRule.getDataBar(); - return new XSSFDataBarFormatting(bar); - } else { - return null; - } - } - - public XSSFIconMultiStateFormatting createMultiStateFormatting(IconSet iconSet) { - // Is it already there? - if (_cfRule.isSetIconSet() && _cfRule.getType() == STCfType.ICON_SET) - return getMultiStateFormatting(); - - // Mark it as being an Icon Set - _cfRule.setType(STCfType.ICON_SET); - - // Ensure the right element - CTIconSet icons = null; - if (_cfRule.isSetIconSet()) { - icons = _cfRule.getIconSet(); - } else { - icons = _cfRule.addNewIconSet(); - } - // Set the type of the icon set - if (iconSet.name != null) { - STIconSetType.Enum xIconSet = STIconSetType.Enum.forString(iconSet.name); - icons.setIconSet(xIconSet); - } - - // Add a default set of thresholds - int jump = 100 / iconSet.num; - STCfvoType.Enum type = STCfvoType.Enum.forString(RangeType.PERCENT.name); - for (int i=0; i - * MUST be a constant from {@link org.apache.poi.ss.usermodel.ComparisonOperator} - *

    - * - * @return the conditional format operator - */ - @Override - public byte getComparisonOperation(){ - STConditionalFormattingOperator.Enum op = _cfRule.getOperator(); - if(op == null) return ComparisonOperator.NO_COMPARISON; - - switch(op.intValue()){ - case STConditionalFormattingOperator.INT_LESS_THAN: return ComparisonOperator.LT; - case STConditionalFormattingOperator.INT_LESS_THAN_OR_EQUAL: return ComparisonOperator.LE; - case STConditionalFormattingOperator.INT_GREATER_THAN: return ComparisonOperator.GT; - case STConditionalFormattingOperator.INT_GREATER_THAN_OR_EQUAL: return ComparisonOperator.GE; - case STConditionalFormattingOperator.INT_EQUAL: return ComparisonOperator.EQUAL; - case STConditionalFormattingOperator.INT_NOT_EQUAL: return ComparisonOperator.NOT_EQUAL; - case STConditionalFormattingOperator.INT_BETWEEN: return ComparisonOperator.BETWEEN; - case STConditionalFormattingOperator.INT_NOT_BETWEEN: return ComparisonOperator.NOT_BETWEEN; - } - return ComparisonOperator.NO_COMPARISON; - } - - /** - * The formula used to evaluate the first operand for the conditional formatting rule. - *

    - * If the condition type is {@link ConditionType#CELL_VALUE_IS}, - * this field is the first operand of the comparison. - * If type is {@link ConditionType#FORMULA}, this formula is used - * to determine if the conditional formatting is applied. - *

    - *

    - * If comparison type is {@link ConditionType#FORMULA} the formula MUST be a Boolean function - *

    - * - * @return the first formula - */ - public String getFormula1(){ - return _cfRule.sizeOfFormulaArray() > 0 ? _cfRule.getFormulaArray(0) : null; - } - - /** - * The formula used to evaluate the second operand of the comparison when - * comparison type is {@link ConditionType#CELL_VALUE_IS} and operator - * is either {@link org.apache.poi.ss.usermodel.ComparisonOperator#BETWEEN} or {@link org.apache.poi.ss.usermodel.ComparisonOperator#NOT_BETWEEN} - * - * @return the second formula - */ - public String getFormula2(){ - return _cfRule.sizeOfFormulaArray() == 2 ? _cfRule.getFormulaArray(1) : null; - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFConditionalFormattingThreshold.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFConditionalFormattingThreshold.java deleted file mode 100644 index f868f14a2..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFConditionalFormattingThreshold.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xssf.usermodel; - -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCfvo; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STCfvoType; - -/** - * High level representation for Icon / Multi-State / Databar / - * Colour Scale change thresholds - */ -public class XSSFConditionalFormattingThreshold implements org.apache.poi.ss.usermodel.ConditionalFormattingThreshold { - private CTCfvo cfvo; - - protected XSSFConditionalFormattingThreshold(CTCfvo cfvo) { - this.cfvo = cfvo; - } - - protected CTCfvo getCTCfvo() { - return cfvo; - } - - public RangeType getRangeType() { - return RangeType.byName(cfvo.getType().toString()); - } - public void setRangeType(RangeType type) { - STCfvoType.Enum xtype = STCfvoType.Enum.forString(type.name); - cfvo.setType(xtype); - } - - public String getFormula() { - if (cfvo.getType() == STCfvoType.FORMULA) { - return cfvo.getVal(); - } - return null; - } - public void setFormula(String formula) { - cfvo.setVal(formula); - } - - public Double getValue() { - if (cfvo.getType() == STCfvoType.FORMULA || - cfvo.getType() == STCfvoType.MIN || - cfvo.getType() == STCfvoType.MAX) { - return null; - } - if (cfvo.isSetVal()) { - return Double.parseDouble(cfvo.getVal()); - } else { - return null; - } - } - public void setValue(Double value) { - if (value == null) { - cfvo.unsetVal(); - } else { - cfvo.setVal(value.toString()); - } - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFConnector.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFConnector.java deleted file mode 100644 index f0d9d12af..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFConnector.java +++ /dev/null @@ -1,141 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import org.openxmlformats.schemas.drawingml.x2006.main.CTFontReference; -import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPoint2D; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPresetGeometry2D; -import org.openxmlformats.schemas.drawingml.x2006.main.CTSchemeColor; -import org.openxmlformats.schemas.drawingml.x2006.main.CTShapeProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTShapeStyle; -import org.openxmlformats.schemas.drawingml.x2006.main.CTStyleMatrixReference; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTransform2D; -import org.openxmlformats.schemas.drawingml.x2006.main.STFontCollectionIndex; -import org.openxmlformats.schemas.drawingml.x2006.main.STSchemeColorVal; -import org.openxmlformats.schemas.drawingml.x2006.main.STShapeType; -import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTConnector; -import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTConnectorNonVisual; -import org.apache.poi.util.Internal; - -/** - * A connection shape drawing element. A connection shape is a line, etc. - * that connects two other shapes in this drawing. - * - * @author Yegor Kozlov - */ -public final class XSSFConnector extends XSSFShape { - - private static CTConnector prototype = null; - - private CTConnector ctShape; - - /** - * Construct a new XSSFConnector object. - * - * @param drawing the XSSFDrawing that owns this shape - * @param ctShape the shape bean that holds all the shape properties - */ - protected XSSFConnector(XSSFDrawing drawing, CTConnector ctShape) { - this.drawing = drawing; - this.ctShape = ctShape; - } - - /** - * Initialize default structure of a new auto-shape - * - */ - protected static CTConnector prototype() { - if(prototype == null) { - CTConnector shape = CTConnector.Factory.newInstance(); - CTConnectorNonVisual nv = shape.addNewNvCxnSpPr(); - CTNonVisualDrawingProps nvp = nv.addNewCNvPr(); - nvp.setId(1); - nvp.setName("Shape 1"); - nv.addNewCNvCxnSpPr(); - - CTShapeProperties sp = shape.addNewSpPr(); - CTTransform2D t2d = sp.addNewXfrm(); - CTPositiveSize2D p1 = t2d.addNewExt(); - p1.setCx(0); - p1.setCy(0); - CTPoint2D p2 = t2d.addNewOff(); - p2.setX(0); - p2.setY(0); - - CTPresetGeometry2D geom = sp.addNewPrstGeom(); - geom.setPrst(STShapeType.LINE); - geom.addNewAvLst(); - - CTShapeStyle style = shape.addNewStyle(); - CTSchemeColor scheme = style.addNewLnRef().addNewSchemeClr(); - scheme.setVal(STSchemeColorVal.ACCENT_1); - style.getLnRef().setIdx(1); - - CTStyleMatrixReference fillref = style.addNewFillRef(); - fillref.setIdx(0); - fillref.addNewSchemeClr().setVal(STSchemeColorVal.ACCENT_1); - - CTStyleMatrixReference effectRef = style.addNewEffectRef(); - effectRef.setIdx(0); - effectRef.addNewSchemeClr().setVal(STSchemeColorVal.ACCENT_1); - - CTFontReference fontRef = style.addNewFontRef(); - fontRef.setIdx(STFontCollectionIndex.MINOR); - fontRef.addNewSchemeClr().setVal(STSchemeColorVal.TX_1); - - prototype = shape; - } - return prototype; - } - - @Internal - public CTConnector getCTConnector(){ - return ctShape; - } - - /** - * Gets the shape type, one of the constants defined in {@link org.apache.poi.ss.usermodel.ShapeTypes}. - * - * @return the shape type - * @see org.apache.poi.ss.usermodel.ShapeTypes - */ - public int getShapeType() { - return ctShape.getSpPr().getPrstGeom().getPrst().intValue(); - } - - /** - * Sets the shape types. - * - * @param type the shape type, one of the constants defined in {@link org.apache.poi.ss.usermodel.ShapeTypes}. - * @see org.apache.poi.ss.usermodel.ShapeTypes - */ - public void setShapeType(int type) { - ctShape.getSpPr().getPrstGeom().setPrst(STShapeType.Enum.forInt(type)); - } - - protected CTShapeProperties getShapeProperties(){ - return ctShape.getSpPr(); - } - - @Override - public String getShapeName() { - return ctShape.getNvCxnSpPr().getCNvPr().getName(); - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFCreationHelper.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFCreationHelper.java deleted file mode 100644 index cb11a73b2..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFCreationHelper.java +++ /dev/null @@ -1,102 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel; - -import org.apache.poi.common.usermodel.HyperlinkType; -import org.apache.poi.ss.usermodel.CreationHelper; -import org.apache.poi.ss.usermodel.Hyperlink; -import org.apache.poi.util.Internal; -import org.apache.poi.util.Removal; - -public class XSSFCreationHelper implements CreationHelper { - private final XSSFWorkbook workbook; - - /** - * Should only be called by {@link XSSFWorkbook#getCreationHelper()} - * - * @param wb the workbook to create objects for - */ - @Internal - public XSSFCreationHelper(XSSFWorkbook wb) { - workbook = wb; - } - - /** - * Creates a new XSSFRichTextString for you. - */ - @Override - public XSSFRichTextString createRichTextString(String text) { - XSSFRichTextString rt = new XSSFRichTextString(text); - rt.setStylesTableReference(workbook.getStylesSource()); - return rt; - } - - @Override - public XSSFDataFormat createDataFormat() { - return workbook.createDataFormat(); - } - - @Override - public XSSFColor createExtendedColor() { - return new XSSFColor(); - } - - /** - * Create a new XSSFHyperlink. - * - * @param type - the type of hyperlink to create, see {@link HyperlinkType} - * @deprecated POI 3.15 beta 3. Use {@link #createHyperlink(HyperlinkType)} instead. - */ - @Deprecated - @Removal(version="3.17") - @Override - public XSSFHyperlink createHyperlink(int type) { - return new XSSFHyperlink(type); - } - - /** - * Create a new XSSFHyperlink. - * - * @param type - the type of hyperlink to create, see {@link Hyperlink} - */ - @Override - public XSSFHyperlink createHyperlink(HyperlinkType type) { - return new XSSFHyperlink(type); - } - - /** - * Creates a XSSFFormulaEvaluator, the object that evaluates formula cells. - * - * @return a XSSFFormulaEvaluator instance - */ - @Override - public XSSFFormulaEvaluator createFormulaEvaluator() { - return new XSSFFormulaEvaluator(workbook); - } - - /** - * Creates a XSSFClientAnchor. Use this object to position drawing object in - * a sheet - * - * @return a XSSFClientAnchor instance - * @see org.apache.poi.ss.usermodel.Drawing - */ - @Override - public XSSFClientAnchor createClientAnchor() { - return new XSSFClientAnchor(); - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFDataBarFormatting.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFDataBarFormatting.java deleted file mode 100644 index 552d5e32f..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFDataBarFormatting.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -package org.apache.poi.xssf.usermodel; - -import org.apache.poi.ss.usermodel.Color; -import org.apache.poi.ss.usermodel.DataBarFormatting; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTDataBar; - -/** - * High level representation for DataBar / Data Bar Formatting - * component of Conditional Formatting settings - */ -public class XSSFDataBarFormatting implements DataBarFormatting { - CTDataBar _databar; - - /*package*/ XSSFDataBarFormatting(CTDataBar databar){ - _databar = databar; - } - - public boolean isIconOnly() { - if (_databar.isSetShowValue()) - return !_databar.getShowValue(); - return false; - } - public void setIconOnly(boolean only) { - _databar.setShowValue(!only); - } - - public boolean isLeftToRight() { - return true; - } - public void setLeftToRight(boolean ltr) { - // TODO How does XSSF encode this? - } - - public int getWidthMin() { - return 0; - } - public void setWidthMin(int width) { - // TODO How does XSSF encode this? - } - - public int getWidthMax() { - return 100; - } - public void setWidthMax(int width) { - // TODO How does XSSF encode this? - } - - public XSSFColor getColor() { - return new XSSFColor(_databar.getColor()); - } - public void setColor(Color color) { - _databar.setColor( ((XSSFColor)color).getCTColor() ); - } - - public XSSFConditionalFormattingThreshold getMinThreshold() { - return new XSSFConditionalFormattingThreshold(_databar.getCfvoArray(0)); - } - public XSSFConditionalFormattingThreshold getMaxThreshold() { - return new XSSFConditionalFormattingThreshold(_databar.getCfvoArray(1)); - } - - public XSSFConditionalFormattingThreshold createThreshold() { - return new XSSFConditionalFormattingThreshold(_databar.addNewCfvo()); - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFDataFormat.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFDataFormat.java deleted file mode 100644 index d82524515..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFDataFormat.java +++ /dev/null @@ -1,98 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel; - -import org.apache.poi.ss.usermodel.BuiltinFormats; -import org.apache.poi.ss.usermodel.DataFormat; -import org.apache.poi.util.Removal; -import org.apache.poi.xssf.model.StylesTable; - -/** - * Handles data formats for XSSF. - * - * Per Microsoft Excel 2007+ format limitations: - * Workbooks support between 200 and 250 "number formats" - * (POI calls them "data formats") So short or even byte - * would be acceptable data types to use for referring to - * data format indices. - * https://support.office.com/en-us/article/excel-specifications-and-limits-1672b34d-7043-467e-8e27-269d656771c3 - * - */ -public class XSSFDataFormat implements DataFormat { - private final StylesTable stylesSource; - - protected XSSFDataFormat(StylesTable stylesSource) { - this.stylesSource = stylesSource; - } - - /** - * Get the format index that matches the given format - * string, creating a new format entry if required. - * Aliases text to the proper format as required. - * - * @param format string matching a built-in format - * @return index of format. - */ - @Override - public short getFormat(String format) { - int idx = BuiltinFormats.getBuiltinFormat(format); - if(idx == -1) idx = stylesSource.putNumberFormat(format); - return (short)idx; - } - - /** - * get the format string that matches the given format index - * @param index of a format - * @return string represented at index of format or null if there is not a format at that index - */ - @Override - public String getFormat(short index) { - // Indices used for built-in formats may be overridden with - // custom formats, such as locale-specific currency. - // See org.apache.poi.xssf.usermodel.TestXSSFDataFormat#test49928() - // or bug 49928 for an example. - // This is why we need to check stylesSource first and only fall back to - // BuiltinFormats if the format hasn't been overridden. - String fmt = stylesSource.getNumberFormatAt(index); - if(fmt == null) fmt = BuiltinFormats.getBuiltinFormat(index); - return fmt; - } - /** - * get the format string that matches the given format index - * @param index of a format - * @return string represented at index of format or null if there is not a format at that index - * - * @deprecated POI 3.16 beta 1 - use {@link #getFormat(short)} instead - */ - @Removal(version="3.18") - public String getFormat(int index) { - return getFormat((short)index); - } - - /** - * Add a number format with a specific ID into the number format style table. - * If a format with the same ID already exists, overwrite the format code - * with fmt - * This may be used to override built-in number formats. - * - * @param index the number format ID - * @param format the number format code - */ - public void putFormat(short index, String format) { - stylesSource.putNumberFormat(index, format); - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFDataValidation.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFDataValidation.java deleted file mode 100644 index 9f945ddbe..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFDataValidation.java +++ /dev/null @@ -1,290 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel; - -import java.util.HashMap; -import java.util.Map; - -import org.apache.poi.ss.usermodel.DataValidation; -import org.apache.poi.ss.usermodel.DataValidationConstraint; -import org.apache.poi.ss.usermodel.DataValidationConstraint.ValidationType; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.CellRangeAddressList; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTDataValidation; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STDataValidationErrorStyle; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STDataValidationOperator; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STDataValidationType; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STDataValidationOperator.Enum; - -/** - * @author Radhakrishnan J - * - */ -public class XSSFDataValidation implements DataValidation { - private static final int MAX_TEXT_LENGTH = 255; - - private CTDataValidation ctDdataValidation; - private XSSFDataValidationConstraint validationConstraint; - private CellRangeAddressList regions; - - static Map operatorTypeMappings = new HashMap(); - static Map operatorTypeReverseMappings = new HashMap(); - static Map validationTypeMappings = new HashMap(); - static Map validationTypeReverseMappings = new HashMap(); - static Map errorStyleMappings = new HashMap(); - - static { - errorStyleMappings.put(DataValidation.ErrorStyle.INFO, STDataValidationErrorStyle.INFORMATION); - errorStyleMappings.put(DataValidation.ErrorStyle.STOP, STDataValidationErrorStyle.STOP); - errorStyleMappings.put(DataValidation.ErrorStyle.WARNING, STDataValidationErrorStyle.WARNING); - - operatorTypeMappings.put(DataValidationConstraint.OperatorType.BETWEEN,STDataValidationOperator.BETWEEN); - operatorTypeMappings.put(DataValidationConstraint.OperatorType.NOT_BETWEEN,STDataValidationOperator.NOT_BETWEEN); - operatorTypeMappings.put(DataValidationConstraint.OperatorType.EQUAL,STDataValidationOperator.EQUAL); - operatorTypeMappings.put(DataValidationConstraint.OperatorType.NOT_EQUAL,STDataValidationOperator.NOT_EQUAL); - operatorTypeMappings.put(DataValidationConstraint.OperatorType.GREATER_THAN,STDataValidationOperator.GREATER_THAN); - operatorTypeMappings.put(DataValidationConstraint.OperatorType.GREATER_OR_EQUAL,STDataValidationOperator.GREATER_THAN_OR_EQUAL); - operatorTypeMappings.put(DataValidationConstraint.OperatorType.LESS_THAN,STDataValidationOperator.LESS_THAN); - operatorTypeMappings.put(DataValidationConstraint.OperatorType.LESS_OR_EQUAL,STDataValidationOperator.LESS_THAN_OR_EQUAL); - - for( Map.Entry entry : operatorTypeMappings.entrySet() ) { - operatorTypeReverseMappings.put(entry.getValue(),entry.getKey()); - } - - validationTypeMappings.put(DataValidationConstraint.ValidationType.FORMULA,STDataValidationType.CUSTOM); - validationTypeMappings.put(DataValidationConstraint.ValidationType.DATE,STDataValidationType.DATE); - validationTypeMappings.put(DataValidationConstraint.ValidationType.DECIMAL,STDataValidationType.DECIMAL); - validationTypeMappings.put(DataValidationConstraint.ValidationType.LIST,STDataValidationType.LIST); - validationTypeMappings.put(DataValidationConstraint.ValidationType.ANY,STDataValidationType.NONE); - validationTypeMappings.put(DataValidationConstraint.ValidationType.TEXT_LENGTH,STDataValidationType.TEXT_LENGTH); - validationTypeMappings.put(DataValidationConstraint.ValidationType.TIME,STDataValidationType.TIME); - validationTypeMappings.put(DataValidationConstraint.ValidationType.INTEGER,STDataValidationType.WHOLE); - - for( Map.Entry entry : validationTypeMappings.entrySet() ) { - validationTypeReverseMappings.put(entry.getValue(),entry.getKey()); - } - } - - XSSFDataValidation(CellRangeAddressList regions,CTDataValidation ctDataValidation) { - this(getConstraint(ctDataValidation), regions, ctDataValidation); - } - - public XSSFDataValidation(XSSFDataValidationConstraint constraint,CellRangeAddressList regions,CTDataValidation ctDataValidation) { - super(); - this.validationConstraint = constraint; - this.ctDdataValidation = ctDataValidation; - this.regions = regions; - } - - CTDataValidation getCtDdataValidation() { - return ctDdataValidation; - } - - - - /* (non-Javadoc) - * @see org.apache.poi.ss.usermodel.DataValidation#createErrorBox(java.lang.String, java.lang.String) - */ - public void createErrorBox(String title, String text) { - // the spec does not specify a length-limit, however Excel reports files as "corrupt" if they exceed 255 bytes for these texts... - if(title != null && title.length() > MAX_TEXT_LENGTH) { - throw new IllegalStateException("Error-title cannot be longer than 32 characters, but had: " + title); - } - if(text != null && text.length() > MAX_TEXT_LENGTH) { - throw new IllegalStateException("Error-text cannot be longer than 255 characters, but had: " + text); - } - ctDdataValidation.setErrorTitle(encodeUtf(title)); - ctDdataValidation.setError(encodeUtf(text)); - } - - /* (non-Javadoc) - * @see org.apache.poi.ss.usermodel.DataValidation#createPromptBox(java.lang.String, java.lang.String) - */ - public void createPromptBox(String title, String text) { - // the spec does not specify a length-limit, however Excel reports files as "corrupt" if they exceed 255 bytes for these texts... - if(title != null && title.length() > MAX_TEXT_LENGTH) { - throw new IllegalStateException("Error-title cannot be longer than 32 characters, but had: " + title); - } - if(text != null && text.length() > MAX_TEXT_LENGTH) { - throw new IllegalStateException("Error-text cannot be longer than 255 characters, but had: " + text); - } - ctDdataValidation.setPromptTitle(encodeUtf(title)); - ctDdataValidation.setPrompt(encodeUtf(text)); - } - - /** - * For all characters which cannot be represented in XML as defined by the XML 1.0 specification, - * the characters are escaped using the Unicode numerical character representation escape character - * format _xHHHH_, where H represents a hexadecimal character in the character's value. - *

    - * Example: The Unicode character 0D is invalid in an XML 1.0 document, - * so it shall be escaped as _x000D_. - *

    - * See section 3.18.9 in the OOXML spec. - * - * @param text the string to encode - * @return the encoded string - */ - private String encodeUtf(String text) { - if(text == null) { - return null; - } - - StringBuilder builder = new StringBuilder(); - for(char c : text.toCharArray()) { - // for now only encode characters below 32, we can add more here if needed - if(c < 32) { - builder.append("_x").append(c < 16 ? "000" : "00").append(Integer.toHexString(c)).append("_"); - } else { - builder.append(c); - } - } - - return builder.toString(); - } - - /* (non-Javadoc) - * @see org.apache.poi.ss.usermodel.DataValidation#getEmptyCellAllowed() - */ - public boolean getEmptyCellAllowed() { - return ctDdataValidation.getAllowBlank(); - } - - /* (non-Javadoc) - * @see org.apache.poi.ss.usermodel.DataValidation#getErrorBoxText() - */ - public String getErrorBoxText() { - return ctDdataValidation.getError(); - } - - /* (non-Javadoc) - * @see org.apache.poi.ss.usermodel.DataValidation#getErrorBoxTitle() - */ - public String getErrorBoxTitle() { - return ctDdataValidation.getErrorTitle(); - } - - /* (non-Javadoc) - * @see org.apache.poi.ss.usermodel.DataValidation#getErrorStyle() - */ - public int getErrorStyle() { - return ctDdataValidation.getErrorStyle().intValue(); - } - - /* (non-Javadoc) - * @see org.apache.poi.ss.usermodel.DataValidation#getPromptBoxText() - */ - public String getPromptBoxText() { - return ctDdataValidation.getPrompt(); - } - - /* (non-Javadoc) - * @see org.apache.poi.ss.usermodel.DataValidation#getPromptBoxTitle() - */ - public String getPromptBoxTitle() { - return ctDdataValidation.getPromptTitle(); - } - - /* (non-Javadoc) - * @see org.apache.poi.ss.usermodel.DataValidation#getShowErrorBox() - */ - public boolean getShowErrorBox() { - return ctDdataValidation.getShowErrorMessage(); - } - - /* (non-Javadoc) - * @see org.apache.poi.ss.usermodel.DataValidation#getShowPromptBox() - */ - public boolean getShowPromptBox() { - return ctDdataValidation.getShowInputMessage(); - } - - /* (non-Javadoc) - * @see org.apache.poi.ss.usermodel.DataValidation#getSuppressDropDownArrow() - */ - public boolean getSuppressDropDownArrow() { - return !ctDdataValidation.getShowDropDown(); - } - - /* (non-Javadoc) - * @see org.apache.poi.ss.usermodel.DataValidation#getValidationConstraint() - */ - public DataValidationConstraint getValidationConstraint() { - return validationConstraint; - } - - /* (non-Javadoc) - * @see org.apache.poi.ss.usermodel.DataValidation#setEmptyCellAllowed(boolean) - */ - public void setEmptyCellAllowed(boolean allowed) { - ctDdataValidation.setAllowBlank(allowed); - } - - /* (non-Javadoc) - * @see org.apache.poi.ss.usermodel.DataValidation#setErrorStyle(int) - */ - public void setErrorStyle(int errorStyle) { - ctDdataValidation.setErrorStyle(errorStyleMappings.get(errorStyle)); - } - - /* (non-Javadoc) - * @see org.apache.poi.ss.usermodel.DataValidation#setShowErrorBox(boolean) - */ - public void setShowErrorBox(boolean show) { - ctDdataValidation.setShowErrorMessage(show); - } - - /* (non-Javadoc) - * @see org.apache.poi.ss.usermodel.DataValidation#setShowPromptBox(boolean) - */ - public void setShowPromptBox(boolean show) { - ctDdataValidation.setShowInputMessage(show); - } - - /* (non-Javadoc) - * @see org.apache.poi.ss.usermodel.DataValidation#setSuppressDropDownArrow(boolean) - */ - public void setSuppressDropDownArrow(boolean suppress) { - if (validationConstraint.getValidationType()==ValidationType.LIST) { - ctDdataValidation.setShowDropDown(!suppress); - } - } - - public CellRangeAddressList getRegions() { - return regions; - } - - public String prettyPrint() { - StringBuilder builder = new StringBuilder(); - for(CellRangeAddress address : regions.getCellRangeAddresses()) { - builder.append(address.formatAsString()); - } - builder.append(" => "); - builder.append(this.validationConstraint.prettyPrint()); - return builder.toString(); - } - - private static XSSFDataValidationConstraint getConstraint(CTDataValidation ctDataValidation) { - String formula1 = ctDataValidation.getFormula1(); - String formula2 = ctDataValidation.getFormula2(); - Enum operator = ctDataValidation.getOperator(); - org.openxmlformats.schemas.spreadsheetml.x2006.main.STDataValidationType.Enum type = ctDataValidation.getType(); - Integer validationType = XSSFDataValidation.validationTypeReverseMappings.get(type); - Integer operatorType = XSSFDataValidation.operatorTypeReverseMappings.get(operator); - return new XSSFDataValidationConstraint(validationType,operatorType, formula1,formula2); - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFDataValidationConstraint.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFDataValidationConstraint.java deleted file mode 100644 index d42641eb8..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFDataValidationConstraint.java +++ /dev/null @@ -1,246 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel; - -import java.util.Arrays; -import java.util.regex.Pattern; - -import org.apache.poi.ss.usermodel.DataValidationConstraint; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STDataValidationType; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STDataValidationOperator.Enum; - -/** - * @author Radhakrishnan J - * - */ -public class XSSFDataValidationConstraint implements DataValidationConstraint { - /** - * Excel validation constraints with static lists are delimited with optional whitespace and the Windows List Separator, - * which is typically comma, but can be changed by users. POI will just assume comma. - */ - private static final String LIST_SEPARATOR = ","; - private static final Pattern LIST_SPLIT_REGEX = Pattern.compile("\\s*" + LIST_SEPARATOR + "\\s*"); - private static final String QUOTE = "\""; - - private String formula1; - private String formula2; - private int validationType = -1; - private int operator = -1; - private String[] explicitListOfValues; - - /** - * list literal constructor - */ - public XSSFDataValidationConstraint(String[] explicitListOfValues) { - if( explicitListOfValues==null || explicitListOfValues.length==0) { - throw new IllegalArgumentException("List validation with explicit values must specify at least one value"); - } - this.validationType = ValidationType.LIST; - setExplicitListValues(explicitListOfValues); - - validate(); - } - - public XSSFDataValidationConstraint(int validationType, String formula1) { - super(); - setFormula1(formula1); - this.validationType = validationType; - validate(); - } - - - - public XSSFDataValidationConstraint(int validationType, int operator, String formula1) { - super(); - setFormula1(formula1); - this.validationType = validationType; - this.operator = operator; - validate(); - } - - /** - * This is the constructor called using the OOXML raw data. Excel overloads formula1 to also encode explicit value lists, - * so this constructor has to check for and parse that syntax. - * @param validationType - * @param operator - * @param formula1 Overloaded: formula1 or list of explicit values - * @param formula2 (formula1 is a list of explicit values, this is ignored: use null) - */ - public XSSFDataValidationConstraint(int validationType, int operator, String formula1, String formula2) { - super(); - //removes leading equals sign if present - setFormula1(formula1); - setFormula2(formula2); - this.validationType = validationType; - this.operator = operator; - - validate(); - - //FIXME: Need to confirm if this is not a formula. - // empirical testing shows Excel saves explicit lists surrounded by double quotes, - // range formula expressions can't start with quotes (I think - anyone have a creative counter example?) - if ( ValidationType.LIST == validationType - && this.formula1 != null - && isQuoted(this.formula1) ) { - explicitListOfValues = LIST_SPLIT_REGEX.split(unquote(this.formula1)); - } - } - - /* (non-Javadoc) - * @see org.apache.poi.ss.usermodel.DataValidationConstraint#getExplicitListValues() - */ - public String[] getExplicitListValues() { - return explicitListOfValues; - } - - /* (non-Javadoc) - * @see org.apache.poi.ss.usermodel.DataValidationConstraint#getFormula1() - */ - public String getFormula1() { - return formula1; - } - - /* (non-Javadoc) - * @see org.apache.poi.ss.usermodel.DataValidationConstraint#getFormula2() - */ - public String getFormula2() { - return formula2; - } - - /* (non-Javadoc) - * @see org.apache.poi.ss.usermodel.DataValidationConstraint#getOperator() - */ - public int getOperator() { - return operator; - } - - /* (non-Javadoc) - * @see org.apache.poi.ss.usermodel.DataValidationConstraint#getValidationType() - */ - public int getValidationType() { - return validationType; - } - - /* (non-Javadoc) - * @see org.apache.poi.ss.usermodel.DataValidationConstraint#setExplicitListValues(java.lang.String[]) - */ - public void setExplicitListValues(String[] explicitListValues) { - this.explicitListOfValues = explicitListValues; - - // for OOXML we need to set formula1 to the quoted csv list of values (doesn't appear documented, but that's where Excel puts its lists) - // further, Excel has no escaping for commas in explicit lists, so we don't need to worry about that. - if ( explicitListOfValues!=null && explicitListOfValues.length > 0 ) { - StringBuilder builder = new StringBuilder(QUOTE); - for (int i = 0; i < explicitListValues.length; i++) { - String string = explicitListValues[i]; - if (builder.length() > 1) { - builder.append(LIST_SEPARATOR); - } - builder.append(string); - } - builder.append(QUOTE); - setFormula1(builder.toString()); - } - } - - /* (non-Javadoc) - * @see org.apache.poi.ss.usermodel.DataValidationConstraint#setFormula1(java.lang.String) - */ - public void setFormula1(String formula1) { - this.formula1 = removeLeadingEquals(formula1); - } - - protected static String removeLeadingEquals(String formula1) { - return isFormulaEmpty(formula1) ? formula1 : formula1.charAt(0)=='=' ? formula1.substring(1) : formula1; - } - private static boolean isQuoted(String s) { - return s.startsWith(QUOTE) && s.endsWith(QUOTE); - } - private static String unquote(String s) { - // removes leading and trailing quotes from a quoted string - if (isQuoted(s)) { - return s.substring(1, s.length()-1); - } - return s; - } - protected static boolean isFormulaEmpty(String formula1) { - return formula1 == null || formula1.trim().length()==0; - } - - /* (non-Javadoc) - * @see org.apache.poi.ss.usermodel.DataValidationConstraint#setFormula2(java.lang.String) - */ - public void setFormula2(String formula2) { - this.formula2 = removeLeadingEquals(formula2); - } - - /* (non-Javadoc) - * @see org.apache.poi.ss.usermodel.DataValidationConstraint#setOperator(int) - */ - public void setOperator(int operator) { - this.operator = operator; - } - - public void validate() { - if (validationType==ValidationType.ANY) { - return; - } - - if (validationType==ValidationType.LIST ) { - if (isFormulaEmpty(formula1)) { - throw new IllegalArgumentException("A valid formula or a list of values must be specified for list validation."); - } - } else { - if( isFormulaEmpty(formula1) ) { - throw new IllegalArgumentException("Formula is not specified. Formula is required for all validation types except explicit list validation."); - } - - if( validationType!= ValidationType.FORMULA ) { - if (operator==-1) { - throw new IllegalArgumentException("This validation type requires an operator to be specified."); - } else if (( operator==OperatorType.BETWEEN || operator==OperatorType.NOT_BETWEEN) && isFormulaEmpty(formula2)) { - throw new IllegalArgumentException("Between and not between comparisons require two formulae to be specified."); - } - } - } - } - - - public String prettyPrint() { - StringBuilder builder = new StringBuilder(); - STDataValidationType.Enum vt = XSSFDataValidation.validationTypeMappings.get(validationType); - Enum ot = XSSFDataValidation.operatorTypeMappings.get(operator); - builder.append(vt); - builder.append(' '); - if (validationType!=ValidationType.ANY) { - if (validationType != ValidationType.LIST - && validationType != ValidationType.FORMULA) { - builder.append(LIST_SEPARATOR).append(ot).append(", "); - } - final String NOQUOTE = ""; - if (validationType == ValidationType.LIST && explicitListOfValues != null) { - builder.append(NOQUOTE).append(Arrays.asList(explicitListOfValues)).append(NOQUOTE).append(' '); - } else { - builder.append(NOQUOTE).append(formula1).append(NOQUOTE).append(' '); - } - if (formula2 != null) { - builder.append(NOQUOTE).append(formula2).append(NOQUOTE).append(' '); - } - } - return builder.toString(); - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFDataValidationHelper.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFDataValidationHelper.java deleted file mode 100644 index 8f7908dbd..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFDataValidationHelper.java +++ /dev/null @@ -1,177 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.ss.usermodel.DataValidation; -import org.apache.poi.ss.usermodel.DataValidationConstraint; -import org.apache.poi.ss.usermodel.DataValidationHelper; -import org.apache.poi.ss.usermodel.DataValidationConstraint.ValidationType; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.CellRangeAddressList; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTDataValidation; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STDataValidationErrorStyle; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STDataValidationOperator; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STDataValidationType; - -/** - * @author Radhakrishnan J - * - */ -public class XSSFDataValidationHelper implements DataValidationHelper { - // Findbugs: URF_UNREAD_FIELD. Do not delete without understanding how this class works. - //private XSSFSheet xssfSheet; - - - public XSSFDataValidationHelper(XSSFSheet xssfSheet) { - super(); - // Findbugs: URF_UNREAD_FIELD. Do not delete without understanding how this class works. - //this.xssfSheet = xssfSheet; - } - - /* (non-Javadoc) - * @see org.apache.poi.ss.usermodel.DataValidationHelper#createDateConstraint(int, java.lang.String, java.lang.String, java.lang.String) - */ - public DataValidationConstraint createDateConstraint(int operatorType, String formula1, String formula2, String dateFormat) { - return new XSSFDataValidationConstraint(ValidationType.DATE, operatorType,formula1, formula2); - } - - /* (non-Javadoc) - * @see org.apache.poi.ss.usermodel.DataValidationHelper#createDecimalConstraint(int, java.lang.String, java.lang.String) - */ - public DataValidationConstraint createDecimalConstraint(int operatorType, String formula1, String formula2) { - return new XSSFDataValidationConstraint(ValidationType.DECIMAL, operatorType,formula1, formula2); - } - - /* (non-Javadoc) - * @see org.apache.poi.ss.usermodel.DataValidationHelper#createExplicitListConstraint(java.lang.String[]) - */ - public DataValidationConstraint createExplicitListConstraint(String[] listOfValues) { - return new XSSFDataValidationConstraint(listOfValues); - } - - /* (non-Javadoc) - * @see org.apache.poi.ss.usermodel.DataValidationHelper#createFormulaListConstraint(java.lang.String) - */ - public DataValidationConstraint createFormulaListConstraint(String listFormula) { - return new XSSFDataValidationConstraint(ValidationType.LIST, listFormula); - } - - - - public DataValidationConstraint createNumericConstraint(int validationType, int operatorType, String formula1, String formula2) { - if( validationType==ValidationType.INTEGER) { - return createIntegerConstraint(operatorType, formula1, formula2); - } else if ( validationType==ValidationType.DECIMAL) { - return createDecimalConstraint(operatorType, formula1, formula2); - } else if ( validationType==ValidationType.TEXT_LENGTH) { - return createTextLengthConstraint(operatorType, formula1, formula2); - } - return null; - } - - /* (non-Javadoc) - * @see org.apache.poi.ss.usermodel.DataValidationHelper#createIntegerConstraint(int, java.lang.String, java.lang.String) - */ - public DataValidationConstraint createIntegerConstraint(int operatorType, String formula1, String formula2) { - return new XSSFDataValidationConstraint(ValidationType.INTEGER, operatorType,formula1,formula2); - } - - /* (non-Javadoc) - * @see org.apache.poi.ss.usermodel.DataValidationHelper#createTextLengthConstraint(int, java.lang.String, java.lang.String) - */ - public DataValidationConstraint createTextLengthConstraint(int operatorType, String formula1, String formula2) { - return new XSSFDataValidationConstraint(ValidationType.TEXT_LENGTH, operatorType,formula1,formula2); - } - - /* (non-Javadoc) - * @see org.apache.poi.ss.usermodel.DataValidationHelper#createTimeConstraint(int, java.lang.String, java.lang.String, java.lang.String) - */ - public DataValidationConstraint createTimeConstraint(int operatorType, String formula1, String formula2) { - return new XSSFDataValidationConstraint(ValidationType.TIME, operatorType,formula1,formula2); - } - - public DataValidationConstraint createCustomConstraint(String formula) { - return new XSSFDataValidationConstraint(ValidationType.FORMULA, formula); - } - - /* (non-Javadoc) - * @see org.apache.poi.ss.usermodel.DataValidationHelper#createValidation(org.apache.poi.ss.usermodel.DataValidationConstraint, org.apache.poi.ss.util.CellRangeAddressList) - */ - public DataValidation createValidation(DataValidationConstraint constraint, CellRangeAddressList cellRangeAddressList) { - XSSFDataValidationConstraint dataValidationConstraint = (XSSFDataValidationConstraint)constraint; - CTDataValidation newDataValidation = CTDataValidation.Factory.newInstance(); - - int validationType = constraint.getValidationType(); - switch(validationType) { - case DataValidationConstraint.ValidationType.LIST: - newDataValidation.setType(STDataValidationType.LIST); - newDataValidation.setFormula1(constraint.getFormula1()); - break; - case DataValidationConstraint.ValidationType.ANY: - newDataValidation.setType(STDataValidationType.NONE); - break; - case DataValidationConstraint.ValidationType.TEXT_LENGTH: - newDataValidation.setType(STDataValidationType.TEXT_LENGTH); - break; - case DataValidationConstraint.ValidationType.DATE: - newDataValidation.setType(STDataValidationType.DATE); - break; - case DataValidationConstraint.ValidationType.INTEGER: - newDataValidation.setType(STDataValidationType.WHOLE); - break; - case DataValidationConstraint.ValidationType.DECIMAL: - newDataValidation.setType(STDataValidationType.DECIMAL); - break; - case DataValidationConstraint.ValidationType.TIME: - newDataValidation.setType(STDataValidationType.TIME); - break; - case DataValidationConstraint.ValidationType.FORMULA: - newDataValidation.setType(STDataValidationType.CUSTOM); - break; - default: - newDataValidation.setType(STDataValidationType.NONE); - } - - if (validationType!=ValidationType.ANY && validationType!=ValidationType.LIST) { - STDataValidationOperator.Enum op = XSSFDataValidation.operatorTypeMappings.get(constraint.getOperator()); - if(op != null) { - newDataValidation.setOperator(op); - } - if (constraint.getFormula1() != null) { - newDataValidation.setFormula1(constraint.getFormula1()); - } - if (constraint.getFormula2() != null) { - newDataValidation.setFormula2(constraint.getFormula2()); - } - } - - CellRangeAddress[] cellRangeAddresses = cellRangeAddressList.getCellRangeAddresses(); - List sqref = new ArrayList(); - for (int i = 0; i < cellRangeAddresses.length; i++) { - CellRangeAddress cellRangeAddress = cellRangeAddresses[i]; - sqref.add(cellRangeAddress.formatAsString()); - } - newDataValidation.setSqref(sqref); - newDataValidation.setAllowBlank(true); - newDataValidation.setErrorStyle(STDataValidationErrorStyle.STOP); - - return new XSSFDataValidation(dataValidationConstraint,cellRangeAddressList,newDataValidation); - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFDialogsheet.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFDialogsheet.java deleted file mode 100644 index 46b6cd362..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFDialogsheet.java +++ /dev/null @@ -1,107 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import org.apache.poi.ss.usermodel.Sheet; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTDialogsheet; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTHeaderFooter; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPageBreak; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPageMargins; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPrintOptions; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTSheetFormatPr; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTSheetPr; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTSheetProtection; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTSheetViews; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet; - -//YK: TODO: this is only a prototype -public class XSSFDialogsheet extends XSSFSheet implements Sheet{ - protected CTDialogsheet dialogsheet; - - protected XSSFDialogsheet(XSSFSheet sheet) { - super(sheet.getPackagePart()); - this.dialogsheet = CTDialogsheet.Factory.newInstance(); - this.worksheet = CTWorksheet.Factory.newInstance(); - } - - public XSSFRow createRow(int rowNum) { - return null; - } - - protected CTHeaderFooter getSheetTypeHeaderFooter() { - if (dialogsheet.getHeaderFooter() == null) { - dialogsheet.setHeaderFooter(CTHeaderFooter.Factory.newInstance()); - } - return dialogsheet.getHeaderFooter(); - } - - protected CTSheetPr getSheetTypeSheetPr() { - if (dialogsheet.getSheetPr() == null) { - dialogsheet.setSheetPr(CTSheetPr.Factory.newInstance()); - } - return dialogsheet.getSheetPr(); - } - - protected CTPageBreak getSheetTypeColumnBreaks() { - return null; - } - - protected CTSheetFormatPr getSheetTypeSheetFormatPr() { - if (dialogsheet.getSheetFormatPr() == null) { - dialogsheet.setSheetFormatPr(CTSheetFormatPr.Factory.newInstance()); - } - return dialogsheet.getSheetFormatPr(); - } - - protected CTPageMargins getSheetTypePageMargins() { - if (dialogsheet.getPageMargins() == null) { - dialogsheet.setPageMargins(CTPageMargins.Factory.newInstance()); - } - return dialogsheet.getPageMargins(); - } - - protected CTPageBreak getSheetTypeRowBreaks() { - return null; - } - - protected CTSheetViews getSheetTypeSheetViews() { - if (dialogsheet.getSheetViews() == null) { - dialogsheet.setSheetViews(CTSheetViews.Factory.newInstance()); - dialogsheet.getSheetViews().addNewSheetView(); - } - return dialogsheet.getSheetViews(); - } - - protected CTPrintOptions getSheetTypePrintOptions() { - if (dialogsheet.getPrintOptions() == null) { - dialogsheet.setPrintOptions(CTPrintOptions.Factory.newInstance()); - } - return dialogsheet.getPrintOptions(); - } - - protected CTSheetProtection getSheetTypeProtection() { - if (dialogsheet.getSheetProtection() == null) { - dialogsheet.setSheetProtection(CTSheetProtection.Factory.newInstance()); - } - return dialogsheet.getSheetProtection(); - } - - public boolean getDialog(){ - return true; - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFDrawing.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFDrawing.java deleted file mode 100644 index 35f71381c..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFDrawing.java +++ /dev/null @@ -1,676 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import static org.apache.poi.POIXMLTypeLoader.DEFAULT_XML_OPTIONS; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import javax.xml.namespace.QName; - -import org.apache.poi.POIXMLDocument; -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.POIXMLException; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.opc.PackagePartName; -import org.apache.poi.openxml4j.opc.PackageRelationship; -import org.apache.poi.openxml4j.opc.PackageRelationshipTypes; -import org.apache.poi.openxml4j.opc.PackagingURIHelper; -import org.apache.poi.openxml4j.opc.TargetMode; -import org.apache.poi.ss.usermodel.ClientAnchor; -import org.apache.poi.ss.usermodel.Drawing; -import org.apache.poi.ss.util.CellAddress; -import org.apache.poi.ss.util.ImageUtils; -import org.apache.poi.util.Internal; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.util.Units; -import org.apache.poi.xssf.model.CommentsTable; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlOptions; -import org.apache.xmlbeans.impl.values.XmlAnyTypeImpl; -import org.openxmlformats.schemas.drawingml.x2006.main.CTBlipFillProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTGroupTransform2D; -import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPoint2D; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTransform2D; -import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTConnector; -import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTDrawing; -import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTGraphicalObjectFrame; -import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTGroupShape; -import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTMarker; -import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTOneCellAnchor; -import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTPicture; -import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTShape; -import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTTwoCellAnchor; -import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.STEditAs; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTOleObject; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTOleObjects; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet; - -/** - * Represents a SpreadsheetML drawing - */ -public final class XSSFDrawing extends POIXMLDocumentPart implements Drawing { - private static final POILogger LOG = POILogFactory.getLogger(XSSFDrawing.class); - - /** - * Root element of the SpreadsheetML Drawing part - */ - private CTDrawing drawing; - private long numOfGraphicFrames = 0L; - - protected static final String NAMESPACE_A = XSSFRelation.NS_DRAWINGML; - protected static final String NAMESPACE_C = XSSFRelation.NS_CHART; - - /** - * Create a new SpreadsheetML drawing - * - * @see org.apache.poi.xssf.usermodel.XSSFSheet#createDrawingPatriarch() - */ - protected XSSFDrawing() { - super(); - drawing = newDrawing(); - } - - /** - * Construct a SpreadsheetML drawing from a package part - * - * @param part the package part holding the drawing data, - * the content type must be application/vnd.openxmlformats-officedocument.drawing+xml - * - * @since POI 3.14-Beta1 - */ - public XSSFDrawing(PackagePart part) throws IOException, XmlException { - super(part); - XmlOptions options = new XmlOptions(DEFAULT_XML_OPTIONS); - //Removing root element - options.setLoadReplaceDocumentElement(null); - InputStream is = part.getInputStream(); - try { - drawing = CTDrawing.Factory.parse(is,options); - } finally { - is.close(); - } - } - - /** - * Construct a new CTDrawing bean. By default, it's just an empty placeholder for drawing objects - * - * @return a new CTDrawing bean - */ - private static CTDrawing newDrawing(){ - return CTDrawing.Factory.newInstance(); - } - - /** - * Return the underlying CTDrawing bean, the root element of the SpreadsheetML Drawing part. - * - * @return the underlying CTDrawing bean - */ - @Internal - public CTDrawing getCTDrawing(){ - return drawing; - } - - @Override - protected void commit() throws IOException { - XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS); - - /* - Saved drawings must have the following namespaces set: - - */ - xmlOptions.setSaveSyntheticDocumentElement( - new QName(CTDrawing.type.getName().getNamespaceURI(), "wsDr", "xdr") - ); - - PackagePart part = getPackagePart(); - OutputStream out = part.getOutputStream(); - drawing.save(out, xmlOptions); - out.close(); - } - - @Override - public XSSFClientAnchor createAnchor(int dx1, int dy1, int dx2, int dy2, - int col1, int row1, int col2, int row2) { - return new XSSFClientAnchor(dx1, dy1, dx2, dy2, col1, row1, col2, row2); - } - - /** - * Constructs a textbox under the drawing. - * - * @param anchor the client anchor describes how this group is attached - * to the sheet. - * @return the newly created textbox. - */ - public XSSFTextBox createTextbox(XSSFClientAnchor anchor){ - long shapeId = newShapeId(); - CTTwoCellAnchor ctAnchor = createTwoCellAnchor(anchor); - CTShape ctShape = ctAnchor.addNewSp(); - ctShape.set(XSSFSimpleShape.prototype()); - ctShape.getNvSpPr().getCNvPr().setId(shapeId); - XSSFTextBox shape = new XSSFTextBox(this, ctShape); - shape.anchor = anchor; - return shape; - - } - - /** - * Creates a picture. - * - * @param anchor the client anchor describes how this picture is attached to the sheet. - * @param pictureIndex the index of the picture in the workbook collection of pictures, - * {@link org.apache.poi.xssf.usermodel.XSSFWorkbook#getAllPictures()} . - * - * @return the newly created picture shape. - */ - public XSSFPicture createPicture(XSSFClientAnchor anchor, int pictureIndex) - { - PackageRelationship rel = addPictureReference(pictureIndex); - - long shapeId = newShapeId(); - CTTwoCellAnchor ctAnchor = createTwoCellAnchor(anchor); - CTPicture ctShape = ctAnchor.addNewPic(); - ctShape.set(XSSFPicture.prototype()); - - ctShape.getNvPicPr().getCNvPr().setId(shapeId); - - XSSFPicture shape = new XSSFPicture(this, ctShape); - shape.anchor = anchor; - shape.setPictureReference(rel); - ctShape.getSpPr().setXfrm(createXfrm(anchor)); - - return shape; - } - - @Override - public XSSFPicture createPicture(ClientAnchor anchor, int pictureIndex){ - return createPicture((XSSFClientAnchor)anchor, pictureIndex); - } - - /** - * Creates a chart. - * @param anchor the client anchor describes how this chart is attached to - * the sheet. - * @return the newly created chart - * @see org.apache.poi.xssf.usermodel.XSSFDrawing#createChart(ClientAnchor) - */ - public XSSFChart createChart(XSSFClientAnchor anchor) { - int chartNumber = getPackagePart().getPackage(). - getPartsByContentType(XSSFRelation.CHART.getContentType()).size() + 1; - - RelationPart rp = createRelationship( - XSSFRelation.CHART, XSSFFactory.getInstance(), chartNumber, false); - XSSFChart chart = rp.getDocumentPart(); - String chartRelId = rp.getRelationship().getId(); - - XSSFGraphicFrame frame = createGraphicFrame(anchor); - frame.setChart(chart, chartRelId); - frame.getCTGraphicalObjectFrame().setXfrm(createXfrm(anchor)); - - return chart; - } - - @Override - public XSSFChart createChart(ClientAnchor anchor) { - return createChart((XSSFClientAnchor)anchor); - } - - /** - * Add the indexed picture to this drawing relations - * - * @param pictureIndex the index of the picture in the workbook collection of pictures, - * {@link org.apache.poi.xssf.usermodel.XSSFWorkbook#getAllPictures()} . - */ - @SuppressWarnings("resource") - protected PackageRelationship addPictureReference(int pictureIndex){ - XSSFWorkbook wb = (XSSFWorkbook)getParent().getParent(); - XSSFPictureData data = wb.getAllPictures().get(pictureIndex); - XSSFPictureData pic = new XSSFPictureData(data.getPackagePart()); - RelationPart rp = addRelation(null, XSSFRelation.IMAGES, pic); - return rp.getRelationship(); - } - - /** - * Creates a simple shape. This includes such shapes as lines, rectangles, - * and ovals. - * - * @param anchor the client anchor describes how this group is attached - * to the sheet. - * @return the newly created shape. - */ - public XSSFSimpleShape createSimpleShape(XSSFClientAnchor anchor) - { - long shapeId = newShapeId(); - CTTwoCellAnchor ctAnchor = createTwoCellAnchor(anchor); - CTShape ctShape = ctAnchor.addNewSp(); - ctShape.set(XSSFSimpleShape.prototype()); - ctShape.getNvSpPr().getCNvPr().setId(shapeId); - ctShape.getSpPr().setXfrm(createXfrm(anchor)); - XSSFSimpleShape shape = new XSSFSimpleShape(this, ctShape); - shape.anchor = anchor; - return shape; - } - - /** - * Creates a simple shape. This includes such shapes as lines, rectangles, - * and ovals. - * - * @param anchor the client anchor describes how this group is attached - * to the sheet. - * @return the newly created shape. - */ - public XSSFConnector createConnector(XSSFClientAnchor anchor) - { - CTTwoCellAnchor ctAnchor = createTwoCellAnchor(anchor); - CTConnector ctShape = ctAnchor.addNewCxnSp(); - ctShape.set(XSSFConnector.prototype()); - - XSSFConnector shape = new XSSFConnector(this, ctShape); - shape.anchor = anchor; - return shape; - } - - /** - * Creates a simple shape. This includes such shapes as lines, rectangles, - * and ovals. - * - * @param anchor the client anchor describes how this group is attached - * to the sheet. - * @return the newly created shape. - */ - public XSSFShapeGroup createGroup(XSSFClientAnchor anchor) - { - CTTwoCellAnchor ctAnchor = createTwoCellAnchor(anchor); - CTGroupShape ctGroup = ctAnchor.addNewGrpSp(); - ctGroup.set(XSSFShapeGroup.prototype()); - CTTransform2D xfrm = createXfrm(anchor); - CTGroupTransform2D grpXfrm =ctGroup.getGrpSpPr().getXfrm(); - grpXfrm.setOff(xfrm.getOff()); - grpXfrm.setExt(xfrm.getExt()); - grpXfrm.setChExt(xfrm.getExt()); - - XSSFShapeGroup shape = new XSSFShapeGroup(this, ctGroup); - shape.anchor = anchor; - return shape; - } - - /** - * Creates a comment. - * @param anchor the client anchor describes how this comment is attached - * to the sheet. - * @return the newly created comment. - */ - @Override - public XSSFComment createCellComment(ClientAnchor anchor) { - XSSFClientAnchor ca = (XSSFClientAnchor)anchor; - XSSFSheet sheet = getSheet(); - - //create comments and vmlDrawing parts if they don't exist - CommentsTable comments = sheet.getCommentsTable(true); - XSSFVMLDrawing vml = sheet.getVMLDrawing(true); - com.microsoft.schemas.vml.CTShape vmlShape = vml.newCommentShape(); - if(ca.isSet()){ - // convert offsets from emus to pixels since we get a DrawingML-anchor - // but create a VML Drawing - int dx1Pixels = ca.getDx1()/Units.EMU_PER_PIXEL; - int dy1Pixels = ca.getDy1()/Units.EMU_PER_PIXEL; - int dx2Pixels = ca.getDx2()/Units.EMU_PER_PIXEL; - int dy2Pixels = ca.getDy2()/Units.EMU_PER_PIXEL; - String position = - ca.getCol1() + ", " + dx1Pixels + ", " + - ca.getRow1() + ", " + dy1Pixels + ", " + - ca.getCol2() + ", " + dx2Pixels + ", " + - ca.getRow2() + ", " + dy2Pixels; - vmlShape.getClientDataArray(0).setAnchorArray(0, position); - } - CellAddress ref = new CellAddress(ca.getRow1(), ca.getCol1()); - - if(comments.findCellComment(ref) != null) { - throw new IllegalArgumentException("Multiple cell comments in one cell are not allowed, cell: " + ref); - } - - return new XSSFComment(comments, comments.newComment(ref), vmlShape); - } - - /** - * Creates a new graphic frame. - * - * @param anchor the client anchor describes how this frame is attached - * to the sheet - * @return the newly created graphic frame - */ - private XSSFGraphicFrame createGraphicFrame(XSSFClientAnchor anchor) { - CTTwoCellAnchor ctAnchor = createTwoCellAnchor(anchor); - CTGraphicalObjectFrame ctGraphicFrame = ctAnchor.addNewGraphicFrame(); - ctGraphicFrame.set(XSSFGraphicFrame.prototype()); - ctGraphicFrame.setXfrm(createXfrm(anchor)); - - long frameId = numOfGraphicFrames++; - XSSFGraphicFrame graphicFrame = new XSSFGraphicFrame(this, ctGraphicFrame); - graphicFrame.setAnchor(anchor); - graphicFrame.setId(frameId); - graphicFrame.setName("Diagramm" + frameId); - return graphicFrame; - } - - @Override - public XSSFObjectData createObjectData(ClientAnchor anchor, int storageId, int pictureIndex) { - XSSFSheet sh = getSheet(); - PackagePart sheetPart = sh.getPackagePart(); - long shapeId = newShapeId(); - - // add reference to OLE part - PackagePartName olePN; - try { - olePN = PackagingURIHelper.createPartName( "/xl/embeddings/oleObject"+storageId+".bin" ); - } catch (InvalidFormatException e) { - throw new POIXMLException(e); - } - PackageRelationship olePR = sheetPart.addRelationship( olePN, TargetMode.INTERNAL, POIXMLDocument.OLE_OBJECT_REL_TYPE ); - - // add reference to image part - XSSFPictureData imgPD = sh.getWorkbook().getAllPictures().get(pictureIndex); - PackagePartName imgPN = imgPD.getPackagePart().getPartName(); - PackageRelationship imgSheetPR = sheetPart.addRelationship( imgPN, TargetMode.INTERNAL, PackageRelationshipTypes.IMAGE_PART ); - PackageRelationship imgDrawPR = getPackagePart().addRelationship( imgPN, TargetMode.INTERNAL, PackageRelationshipTypes.IMAGE_PART ); - - - // add OLE part metadata to sheet - CTWorksheet cwb = sh.getCTWorksheet(); - CTOleObjects oo = cwb.isSetOleObjects() ? cwb.getOleObjects() : cwb.addNewOleObjects(); - - CTOleObject ole1 = oo.addNewOleObject(); - ole1.setProgId("Package"); - ole1.setShapeId(shapeId); - ole1.setId(olePR.getId()); - - XmlCursor cur1 = ole1.newCursor(); - cur1.toEndToken(); - cur1.beginElement("objectPr", XSSFRelation.NS_SPREADSHEETML); - cur1.insertAttributeWithValue("id", PackageRelationshipTypes.CORE_PROPERTIES_ECMA376_NS, imgSheetPR.getId()); - cur1.insertAttributeWithValue("defaultSize", "0"); - cur1.beginElement("anchor", XSSFRelation.NS_SPREADSHEETML); - cur1.insertAttributeWithValue("moveWithCells", "1"); - - CTTwoCellAnchor ctAnchor = createTwoCellAnchor((XSSFClientAnchor)anchor); - - XmlCursor cur2 = ctAnchor.newCursor(); - cur2.copyXmlContents(cur1); - cur2.dispose(); - - cur1.toParent(); - cur1.toFirstChild(); - cur1.setName(new QName(XSSFRelation.NS_SPREADSHEETML, "from")); - cur1.toNextSibling(); - cur1.setName(new QName(XSSFRelation.NS_SPREADSHEETML, "to")); - - cur1.dispose(); - - // add a new shape and link OLE & image part - CTShape ctShape = ctAnchor.addNewSp(); - ctShape.set(XSSFObjectData.prototype()); - ctShape.getSpPr().setXfrm(createXfrm((XSSFClientAnchor)anchor)); - - // workaround for not having the vmlDrawing filled - CTBlipFillProperties blipFill = ctShape.getSpPr().addNewBlipFill(); - blipFill.addNewBlip().setEmbed(imgDrawPR.getId()); - blipFill.addNewStretch().addNewFillRect(); - - CTNonVisualDrawingProps cNvPr = ctShape.getNvSpPr().getCNvPr(); - cNvPr.setId(shapeId); - - XmlCursor extCur = cNvPr.getExtLst().getExtArray(0).newCursor(); - extCur.toFirstChild(); - extCur.setAttributeText(new QName("spid"), "_x0000_s"+shapeId); - extCur.dispose(); - - XSSFObjectData shape = new XSSFObjectData(this, ctShape); - shape.anchor = (XSSFClientAnchor)anchor; - - return shape; - } - - - /** - * Returns all charts in this drawing. - */ - public List getCharts() { - List charts = new ArrayList(); - for(POIXMLDocumentPart part : getRelations()) { - if(part instanceof XSSFChart) { - charts.add((XSSFChart)part); - } - } - return charts; - } - - /** - * Create and initialize a CTTwoCellAnchor that anchors a shape against top-left and bottom-right cells. - * - * @return a new CTTwoCellAnchor - */ - private CTTwoCellAnchor createTwoCellAnchor(XSSFClientAnchor anchor) { - CTTwoCellAnchor ctAnchor = drawing.addNewTwoCellAnchor(); - ctAnchor.setFrom(anchor.getFrom()); - ctAnchor.setTo(anchor.getTo()); - ctAnchor.addNewClientData(); - anchor.setTo(ctAnchor.getTo()); - anchor.setFrom(ctAnchor.getFrom()); - STEditAs.Enum aditAs; - switch(anchor.getAnchorType()) { - case DONT_MOVE_AND_RESIZE: aditAs = STEditAs.ABSOLUTE; break; - case MOVE_AND_RESIZE: aditAs = STEditAs.TWO_CELL; break; - case MOVE_DONT_RESIZE: aditAs = STEditAs.ONE_CELL; break; - default: aditAs = STEditAs.ONE_CELL; - } - ctAnchor.setEditAs(aditAs); - return ctAnchor; - } - - private CTTransform2D createXfrm(XSSFClientAnchor anchor) { - CTTransform2D xfrm = CTTransform2D.Factory.newInstance(); - CTPoint2D off = xfrm.addNewOff(); - off.setX(anchor.getDx1()); - off.setY(anchor.getDy1()); - XSSFSheet sheet = getSheet(); - double widthPx = 0; - for (int col=anchor.getCol1(); col getShapes(){ - List lst = new ArrayList(); - XmlCursor cur = drawing.newCursor(); - try { - if (cur.toFirstChild()) { - addShapes(cur, lst); - } - } finally { - cur.dispose(); - } - return lst; - } - - /** - * @return list of shapes in this shape group - */ - public List getShapes(XSSFShapeGroup groupshape){ - List lst = new ArrayList(); - XmlCursor cur = groupshape.getCTGroupShape().newCursor(); - try { - addShapes(cur, lst); - } finally { - cur.dispose(); - } - return lst; - } - - private void addShapes(XmlCursor cur, List lst) { - try { - do { - cur.push(); - if (cur.toFirstChild()) { - do { - XmlObject obj = cur.getObject(); - - XSSFShape shape; - if (obj instanceof CTMarker) { - // ignore anchor elements - continue; - } else if (obj instanceof CTPicture) { - shape = new XSSFPicture(this, (CTPicture)obj) ; - } else if(obj instanceof CTConnector) { - shape = new XSSFConnector(this, (CTConnector)obj) ; - } else if(obj instanceof CTShape) { - shape = hasOleLink(obj) - ? new XSSFObjectData(this, (CTShape)obj) - : new XSSFSimpleShape(this, (CTShape)obj) ; - } else if(obj instanceof CTGraphicalObjectFrame) { - shape = new XSSFGraphicFrame(this, (CTGraphicalObjectFrame)obj) ; - } else if(obj instanceof CTGroupShape) { - shape = new XSSFShapeGroup(this, (CTGroupShape)obj) ; - } else if(obj instanceof XmlAnyTypeImpl) { - LOG.log(POILogger.WARN, "trying to parse AlternateContent, " - + "this unlinks the returned Shapes from the underlying xml content, " - + "so those shapes can't be used to modify the drawing, " - + "i.e. modifications will be ignored!"); - - // XmlAnyTypeImpl is returned for AlternateContent parts, which might contain a CTDrawing - cur.push(); - cur.toFirstChild(); - XmlCursor cur2 = null; - try { - // need to parse AlternateContent again, otherwise the child elements aren't typed, - // but also XmlAnyTypes - CTDrawing alterWS = CTDrawing.Factory.parse(cur.newXMLStreamReader()); - cur2 = alterWS.newCursor(); - if (cur2.toFirstChild()) { - addShapes(cur2, lst); - } - } catch (XmlException e) { - LOG.log(POILogger.WARN, "unable to parse CTDrawing in alternate content.", e); - } finally { - if (cur2 != null) { - cur2.dispose(); - } - cur.pop(); - } - continue; - } else { - // ignore anything else - continue; - } - - assert(shape != null); - shape.anchor = getAnchorFromParent(obj); - lst.add(shape); - - } while (cur.toNextSibling()); - } - cur.pop(); - } while (cur.toNextSibling()); - } finally { - cur.dispose(); - } - } - - private boolean hasOleLink(XmlObject shape) { - QName uriName = new QName(null, "uri"); - String xquery = "declare namespace a='"+XSSFRelation.NS_DRAWINGML+"' .//a:extLst/a:ext"; - XmlCursor cur = shape.newCursor(); - cur.selectPath(xquery); - try { - while (cur.toNextSelection()) { - String uri = cur.getAttributeText(uriName); - if ("{63B3BB69-23CF-44E3-9099-C40C66FF867C}".equals(uri)) { - return true; - } - } - } finally { - cur.dispose(); - } - return false; - } - - private XSSFAnchor getAnchorFromParent(XmlObject obj){ - XSSFAnchor anchor = null; - - XmlObject parentXbean = null; - XmlCursor cursor = obj.newCursor(); - if(cursor.toParent()) { - parentXbean = cursor.getObject(); - } - cursor.dispose(); - if(parentXbean != null){ - if (parentXbean instanceof CTTwoCellAnchor) { - CTTwoCellAnchor ct = (CTTwoCellAnchor)parentXbean; - anchor = new XSSFClientAnchor(ct.getFrom(), ct.getTo()); - } else if (parentXbean instanceof CTOneCellAnchor) { - CTOneCellAnchor ct = (CTOneCellAnchor)parentXbean; - anchor = new XSSFClientAnchor(ct.getFrom(), CTMarker.Factory.newInstance()); - } - } - return anchor; - } - - @Override - public Iterator iterator() { - return getShapes().iterator(); - } - - /** - * @return the sheet associated with the drawing - */ - public XSSFSheet getSheet() { - return (XSSFSheet)getParent(); - } - -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFEvaluationCell.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFEvaluationCell.java deleted file mode 100644 index 129052e79..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFEvaluationCell.java +++ /dev/null @@ -1,120 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import org.apache.poi.ss.formula.EvaluationCell; -import org.apache.poi.ss.formula.EvaluationSheet; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.util.Internal; - -/** - * XSSF wrapper for a cell under evaluation - */ -final class XSSFEvaluationCell implements EvaluationCell { - - private final EvaluationSheet _evalSheet; - private final XSSFCell _cell; - - public XSSFEvaluationCell(XSSFCell cell, XSSFEvaluationSheet evaluationSheet) { - _cell = cell; - _evalSheet = evaluationSheet; - } - - public XSSFEvaluationCell(XSSFCell cell) { - this(cell, new XSSFEvaluationSheet(cell.getSheet())); - } - - @Override - public Object getIdentityKey() { - // save memory by just using the cell itself as the identity key - // Note - this assumes XSSFCell has not overridden hashCode and equals - return _cell; - } - - public XSSFCell getXSSFCell() { - return _cell; - } - @Override - public boolean getBooleanCellValue() { - return _cell.getBooleanCellValue(); - } -/** - * Will return {@link CellType} in a future version of POI. - * For forwards compatibility, do not hard-code cell type literals in your code. - * - * @return cell type - * @deprecated 3.15. Will return a {@link CellType} enum in the future. - */ - @Override - public int getCellType() { - return _cell.getCellType(); - } - /** - * @since POI 3.15 beta 3 - * @deprecated POI 3.15 beta 3. - * Will be deleted when we make the CellType enum transition. See bug 59791. - */ - @Override - public CellType getCellTypeEnum() { - return _cell.getCellTypeEnum(); - } - @Override - public int getColumnIndex() { - return _cell.getColumnIndex(); - } - @Override - public int getErrorCellValue() { - return _cell.getErrorCellValue(); - } - @Override - public double getNumericCellValue() { - return _cell.getNumericCellValue(); - } - @Override - public int getRowIndex() { - return _cell.getRowIndex(); - } - @Override - public EvaluationSheet getSheet() { - return _evalSheet; - } - @Override - public String getStringCellValue() { - return _cell.getRichStringCellValue().getString(); - } - /** - * Will return {@link CellType} in a future version of POI. - * For forwards compatibility, do not hard-code cell type literals in your code. - * - * @return cell type of cached formula result - */ - @Override - public int getCachedFormulaResultType() { - return _cell.getCachedFormulaResultType(); - } - /** - * @since POI 3.15 beta 3 - * @deprecated POI 3.15 beta 3. - * Will be deleted when we make the CellType enum transition. See bug 59791. - */ - @Internal(since="POI 3.15 beta 3") - @Override - public CellType getCachedFormulaResultTypeEnum() { - return _cell.getCachedFormulaResultTypeEnum(); - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFEvaluationSheet.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFEvaluationSheet.java deleted file mode 100644 index fb042afaf..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFEvaluationSheet.java +++ /dev/null @@ -1,122 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import java.util.HashMap; -import java.util.Map; - -import org.apache.poi.ss.formula.EvaluationCell; -import org.apache.poi.ss.formula.EvaluationSheet; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.util.Internal; - -/** - * XSSF wrapper for a sheet under evaluation - */ -@Internal -final class XSSFEvaluationSheet implements EvaluationSheet { - - private final XSSFSheet _xs; - private Map _cellCache; - - public XSSFEvaluationSheet(XSSFSheet sheet) { - _xs = sheet; - } - - public XSSFSheet getXSSFSheet() { - return _xs; - } - - /* (non-JavaDoc), inherit JavaDoc from EvaluationWorkbook - * @since POI 3.15 beta 3 - */ - @Override - public void clearAllCachedResultValues() { - _cellCache = null; - } - - @Override - public EvaluationCell getCell(int rowIndex, int columnIndex) { - // cache for performance: ~30% speedup due to caching - if (_cellCache == null) { - _cellCache = new HashMap(_xs.getLastRowNum()*3); - for (final Row row : _xs) { - final int rowNum = row.getRowNum(); - for (final Cell cell : row) { - // cast is safe, the iterator is just defined using the interface - final CellKey key = new CellKey(rowNum, cell.getColumnIndex()); - final EvaluationCell evalcell = new XSSFEvaluationCell((XSSFCell) cell, this); - _cellCache.put(key, evalcell); - } - } - } - - final CellKey key = new CellKey(rowIndex, columnIndex); - EvaluationCell evalcell = _cellCache.get(key); - - // If cache is stale, update cache with this one cell - // This is a compromise between rebuilding the entire cache - // (which would quickly defeat the benefit of the cache) - // and not caching at all. - // See bug 59958: Add cells on the fly to the evaluation sheet cache on cache miss - if (evalcell == null) { - XSSFRow row = _xs.getRow(rowIndex); - if (row == null) { - return null; - } - XSSFCell cell = row.getCell(columnIndex); - if (cell == null) { - return null; - } - evalcell = new XSSFEvaluationCell(cell, this); - _cellCache.put(key, evalcell); - } - - return evalcell; - } - - private static class CellKey { - private final int _row; - private final int _col; - private int _hash = -1; //lazily computed - - protected CellKey(int row, int col) { - _row = row; - _col = col; - } - - @Override - public int hashCode() { - if ( _hash == -1 ) { - _hash = (17 * 37 + _row) * 37 + _col; - } - return _hash; - } - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof CellKey)) { - return false; - } - // assumes other object is one of us, otherwise ClassCastException is thrown - final CellKey oKey = (CellKey) obj; - return _row == oKey._row && _col == oKey._col; - } - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFEvaluationWorkbook.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFEvaluationWorkbook.java deleted file mode 100644 index 2c13f8266..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFEvaluationWorkbook.java +++ /dev/null @@ -1,87 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import org.apache.poi.ss.formula.EvaluationCell; -import org.apache.poi.ss.formula.EvaluationSheet; -import org.apache.poi.ss.formula.FormulaParser; -import org.apache.poi.ss.formula.FormulaType; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.apache.poi.util.Internal; - -/** - * Internal POI use only - */ -@Internal -public final class XSSFEvaluationWorkbook extends BaseXSSFEvaluationWorkbook { - private XSSFEvaluationSheet[] _sheetCache; - - public static XSSFEvaluationWorkbook create(XSSFWorkbook book) { - if (book == null) { - return null; - } - return new XSSFEvaluationWorkbook(book); - } - - private XSSFEvaluationWorkbook(XSSFWorkbook book) { - super(book); - } - - /* (non-JavaDoc), inherit JavaDoc from EvaluationSheet - * @since POI 3.15 beta 3 - */ - @Override - public void clearAllCachedResultValues() { - super.clearAllCachedResultValues(); - _sheetCache = null; - } - - @Override - public int getSheetIndex(EvaluationSheet evalSheet) { - XSSFSheet sheet = ((XSSFEvaluationSheet)evalSheet).getXSSFSheet(); - return _uBook.getSheetIndex(sheet); - } - - @Override - public EvaluationSheet getSheet(int sheetIndex) { - // Performance optimization: build sheet cache the first time this is called - // to avoid re-creating the XSSFEvaluationSheet each time a new cell is evaluated - // EvaluationWorkbooks make not guarantee to synchronize changes made to - // the underlying workbook after the EvaluationWorkbook is created. - if (_sheetCache == null) { - final int numberOfSheets = _uBook.getNumberOfSheets(); - _sheetCache = new XSSFEvaluationSheet[numberOfSheets]; - for (int i=0; i < numberOfSheets; i++) { - _sheetCache[i] = new XSSFEvaluationSheet(_uBook.getSheetAt(i)); - } - } - if (sheetIndex < 0 || sheetIndex >= _sheetCache.length) { - // do this to reuse the out-of-bounds logic and message from XSSFWorkbook - _uBook.getSheetAt(sheetIndex); - } - return _sheetCache[sheetIndex]; - } - - @Override - public Ptg[] getFormulaTokens(EvaluationCell evalCell) { - final XSSFCell cell = ((XSSFEvaluationCell)evalCell).getXSSFCell(); - final int sheetIndex = _uBook.getSheetIndex(cell.getSheet()); - final int rowIndex = cell.getRowIndex(); - return FormulaParser.parse(cell.getCellFormula(this), this, FormulaType.CELL, sheetIndex, rowIndex); - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFEvenFooter.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFEvenFooter.java deleted file mode 100644 index 9dd28daf2..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFEvenFooter.java +++ /dev/null @@ -1,65 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import org.apache.poi.ss.usermodel.Footer; -import org.apache.poi.xssf.usermodel.extensions.XSSFHeaderFooter; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTHeaderFooter; - -/** - * - * Even page footer value. Corresponds to even printed pages. - * Even page(s) in the sheet may not be printed, for example, if the print area is specified to be - * a range such that it falls outside an even page's scope. - * If no even footer is specified, then the odd footer's value is assumed for even page footers. - * - */ -public class XSSFEvenFooter extends XSSFHeaderFooter implements Footer{ - - /** - * Create an instance of XSSFEvenFooter from the supplied XML bean - * @see XSSFSheet#getEvenFooter() - * @param headerFooter - */ - public XSSFEvenFooter(CTHeaderFooter headerFooter) { - super(headerFooter); - headerFooter.setDifferentOddEven(true); - } - - /** - * Get the content text representing the footer - * @return text - */ - public String getText() { - return getHeaderFooter().getEvenFooter(); - } - - /** - * Set a text for the footer. If null unset the value. - * @see XSSFHeaderFooter to see how to create a string with Header/Footer Formatting Syntax - * @param text - a string representing the footer. - */ - public void setText(String text) { - if(text == null) { - getHeaderFooter().unsetEvenFooter(); - } else { - getHeaderFooter().setEvenFooter(text); - } - } - -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFEvenHeader.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFEvenHeader.java deleted file mode 100644 index 1bf9555fc..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFEvenHeader.java +++ /dev/null @@ -1,67 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import org.apache.poi.ss.usermodel.Header; -import org.apache.poi.xssf.usermodel.extensions.XSSFHeaderFooter; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTHeaderFooter; - -/** - *

    - * Even page header value. Corresponds to even printed pages. - * Even page(s) in the sheet may not be printed, for example, if the print area is specified to be - * a range such that it falls outside an even page's scope. - * If no even header is specified, then odd header value is assumed for even page headers. - *

    - * - */ -public class XSSFEvenHeader extends XSSFHeaderFooter implements Header{ - - /** - * Create an instance of XSSFEvenHeader from the supplied XML bean - * @see XSSFSheet#getEvenHeader() - * @param headerFooter - */ - public XSSFEvenHeader(CTHeaderFooter headerFooter) { - super(headerFooter); - headerFooter.setDifferentOddEven(true); - } - - /** - * Get the content text representing this header - * @return text - */ - public String getText() { - return getHeaderFooter().getEvenHeader(); - } - - /** - * Set a text for the header. If null unset the value - * @see XSSFHeaderFooter to see how to create a string with Header/Footer Formatting Syntax - * @param text - a string representing the header. - */ - public void setText(String text) { - if(text == null) { - getHeaderFooter().unsetEvenHeader(); - } else { - getHeaderFooter().setEvenHeader(text); - } - } - - -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFFactory.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFFactory.java deleted file mode 100644 index 763b094f9..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFFactory.java +++ /dev/null @@ -1,58 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.POIXMLFactory; -import org.apache.poi.POIXMLRelation; - -/** - * Instantiates sub-classes of POIXMLDocumentPart depending on their relationship type - */ -public final class XSSFFactory extends POIXMLFactory { - private XSSFFactory() { - } - - private static final XSSFFactory inst = new XSSFFactory(); - - public static XSSFFactory getInstance(){ - return inst; - } - - /** - * @since POI 3.14-Beta1 - */ - @Override - protected POIXMLRelation getDescriptor(String relationshipType) { - return XSSFRelation.getInstance(relationshipType); - } - - /** - * @since POI 3.14-Beta1 - */ - @Override - protected POIXMLDocumentPart createDocumentPart - (Class cls, Class[] classes, Object[] values) - throws SecurityException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { - Constructor constructor = cls.getDeclaredConstructor(classes); - return constructor.newInstance(values); - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFFirstFooter.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFFirstFooter.java deleted file mode 100644 index b0f2cb517..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFFirstFooter.java +++ /dev/null @@ -1,63 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import org.apache.poi.ss.usermodel.Footer; -import org.apache.poi.xssf.usermodel.extensions.XSSFHeaderFooter; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTHeaderFooter; - -/** - * - * First page footer content. Corresponds to first printed page. - * The first logical page in the sheet may not be printed, for example, if the print area is specified to - * be a range such that it falls outside the first page's scope. - * - */ -public class XSSFFirstFooter extends XSSFHeaderFooter implements Footer{ - - /** - * Create an instance of XSSFFirstFooter from the supplied XML bean - * @see XSSFSheet#getFirstFooter() - * @param headerFooter - */ - protected XSSFFirstFooter(CTHeaderFooter headerFooter) { - super(headerFooter); - headerFooter.setDifferentFirst(true); - } - - /** - * Get the content text representing the footer - * @return text - */ - public String getText() { - return getHeaderFooter().getFirstFooter(); - } - - /** - * Set a text for the footer. If null unset the value. - * @see XSSFHeaderFooter to see how to create a string with Header/Footer Formatting Syntax - * @param text - a string representing the footer. - */ - public void setText(String text) { - if(text == null) { - getHeaderFooter().unsetFirstFooter(); - } else { - getHeaderFooter().setFirstFooter(text); - } - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFFirstHeader.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFFirstHeader.java deleted file mode 100644 index 9ffd45781..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFFirstHeader.java +++ /dev/null @@ -1,64 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import org.apache.poi.ss.usermodel.Header; -import org.apache.poi.xssf.usermodel.extensions.XSSFHeaderFooter; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTHeaderFooter; - -/** - * - * First page header content. Corresponds to first printed page. - * The first logical page in the sheet may not be printed, for example, if the print area is specified to - * be a range such that it falls outside the first page's scope. - * - */ -public class XSSFFirstHeader extends XSSFHeaderFooter implements Header{ - - /** - * Create an instance of XSSFFirstHeader from the supplied XML bean - * @see XSSFSheet#getFirstHeader() - * @param headerFooter - */ - protected XSSFFirstHeader(CTHeaderFooter headerFooter) { - super(headerFooter); - headerFooter.setDifferentFirst(true); - } - - /** - * Get the content text representing this header - * @return text - */ - public String getText() { - return getHeaderFooter().getFirstHeader(); - } - - /** - * Set a text for the header. If null unset the value - * @see XSSFHeaderFooter to see how to create a string with Header/Footer Formatting Syntax - * @param text - a string representing the header. - */ - public void setText(String text) { - if(text == null) { - getHeaderFooter().unsetFirstHeader(); - } else { - getHeaderFooter().setFirstHeader(text); - } - } - -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFFont.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFFont.java deleted file mode 100644 index bdbbf7478..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFFont.java +++ /dev/null @@ -1,650 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel; - -import org.apache.poi.POIXMLException; -import org.apache.poi.util.Internal; -import org.apache.poi.ss.usermodel.Font; -import org.apache.poi.ss.usermodel.FontCharset; -import org.apache.poi.ss.usermodel.FontFamily; -import org.apache.poi.ss.usermodel.FontScheme; -import org.apache.poi.ss.usermodel.FontUnderline; -import org.apache.poi.ss.usermodel.IndexedColors; -import org.apache.poi.xssf.model.StylesTable; -import org.apache.poi.xssf.model.ThemesTable; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTBooleanProperty; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTColor; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTFont; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTFontName; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTFontScheme; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTFontSize; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTIntProperty; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTUnderlineProperty; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTVerticalAlignFontProperty; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STFontScheme; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STUnderlineValues; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STVerticalAlignRun; - -/** - * Represents a font used in a workbook. - * - * @author Gisella Bronzetti - */ -public class XSSFFont implements Font { - - /** - * By default, Microsoft Office Excel 2007 uses the Calibry font in font size 11 - */ - public static final String DEFAULT_FONT_NAME = "Calibri"; - /** - * By default, Microsoft Office Excel 2007 uses the Calibry font in font size 11 - */ - public static final short DEFAULT_FONT_SIZE = 11; - /** - * Default font color is black - * @see org.apache.poi.ss.usermodel.IndexedColors#BLACK - */ - public static final short DEFAULT_FONT_COLOR = IndexedColors.BLACK.getIndex(); - - private ThemesTable _themes; - private CTFont _ctFont; - private short _index; - - /** - * Create a new XSSFFont - * - * @param font the underlying CTFont bean - */ - public XSSFFont(CTFont font) { - _ctFont = font; - _index = 0; - } - - public XSSFFont(CTFont font, int index) { - _ctFont = font; - _index = (short)index; - } - - /** - * Create a new XSSFont. This method is protected to be used only by XSSFWorkbook - */ - protected XSSFFont() { - this._ctFont = CTFont.Factory.newInstance(); - setFontName(DEFAULT_FONT_NAME); - setFontHeight((double)DEFAULT_FONT_SIZE); - } - - /** - * get the underlying CTFont font - */ - @Internal - public CTFont getCTFont() { - return _ctFont; - } - - /** - * get a boolean value for the boldness to use. - * - * @return boolean - bold - */ - public boolean getBold() { - CTBooleanProperty bold = _ctFont.sizeOfBArray() == 0 ? null : _ctFont.getBArray(0); - return (bold != null && bold.getVal()); - } - - /** - * get character-set to use. - * - * @return int - character-set (0-255) - * @see org.apache.poi.ss.usermodel.FontCharset - */ - public int getCharSet() { - CTIntProperty charset = _ctFont.sizeOfCharsetArray() == 0 ? null : _ctFont.getCharsetArray(0); - int val = charset == null ? FontCharset.ANSI.getValue() : FontCharset.valueOf(charset.getVal()).getValue(); - return val; - } - - - /** - * get the indexed color value for the font - * References a color defined in IndexedColors. - * - * @return short - indexed color to use - * @see IndexedColors - */ - public short getColor() { - CTColor color = _ctFont.sizeOfColorArray() == 0 ? null : _ctFont.getColorArray(0); - if (color == null) return IndexedColors.BLACK.getIndex(); - - long index = color.getIndexed(); - if (index == XSSFFont.DEFAULT_FONT_COLOR) { - return IndexedColors.BLACK.getIndex(); - } else if (index == IndexedColors.RED.getIndex()) { - return IndexedColors.RED.getIndex(); - } else { - return (short)index; - } - } - - - /** - * get the color value for the font - * References a color defined as Standard Alpha Red Green Blue color value (ARGB). - * - * @return XSSFColor - rgb color to use - */ - public XSSFColor getXSSFColor() { - CTColor ctColor = _ctFont.sizeOfColorArray() == 0 ? null : _ctFont.getColorArray(0); - if(ctColor != null) { - XSSFColor color = new XSSFColor(ctColor); - if(_themes != null) { - _themes.inheritFromThemeAsRequired(color); - } - return color; - } else { - return null; - } - } - - - /** - * get the color value for the font - * References a color defined in theme. - * - * @return short - theme defined to use - */ - public short getThemeColor() { - CTColor color = _ctFont.sizeOfColorArray() == 0 ? null : _ctFont.getColorArray(0); - long index = color == null ? 0 : color.getTheme(); - return (short) index; - } - - /** - * Get the font height in unit's of 1/20th of a point. - *

    - * For many users, the related {@link #getFontHeightInPoints()} - * will be more helpful, as that returns font heights in the - * more familiar points units, eg 10, 12, 14. - - * @return short - height in 1/20ths of a point - * @see #getFontHeightInPoints() - */ - public short getFontHeight() { - return (short)(getFontHeightRaw()*20); - } - - /** - * Get the font height in points. - *

    - * This will return the same font height that is shown in Excel, - * such as 10 or 14 or 28. - * @return short - height in the familiar unit of measure - points - * @see #getFontHeight() - */ - public short getFontHeightInPoints() { - return (short)getFontHeightRaw(); - } - - /** - * Return the raw font height, in points, but also - * including fractions. - */ - private double getFontHeightRaw() { - CTFontSize size = _ctFont.sizeOfSzArray() == 0 ? null : _ctFont.getSzArray(0); - if (size != null) { - double fontHeight = size.getVal(); - return fontHeight; - } - return DEFAULT_FONT_SIZE; - } - - /** - * get the name of the font (i.e. Arial) - * - * @return String - a string representing the name of the font to use - */ - public String getFontName() { - CTFontName name = _ctFont.sizeOfNameArray() == 0 ? null : _ctFont.getNameArray(0); - return name == null ? DEFAULT_FONT_NAME : name.getVal(); - } - - /** - * get a boolean value that specify whether to use italics or not - * - * @return boolean - value for italic - */ - public boolean getItalic() { - CTBooleanProperty italic = _ctFont.sizeOfIArray() == 0 ? null : _ctFont.getIArray(0); - return italic != null && italic.getVal(); - } - - /** - * get a boolean value that specify whether to use a strikeout horizontal line through the text or not - * - * @return boolean - value for strikeout - */ - public boolean getStrikeout() { - CTBooleanProperty strike = _ctFont.sizeOfStrikeArray() == 0 ? null : _ctFont.getStrikeArray(0); - return strike != null && strike.getVal(); - } - - /** - * get normal,super or subscript. - * - * @return short - offset type to use (none,super,sub) - * @see Font#SS_NONE - * @see Font#SS_SUPER - * @see Font#SS_SUB - */ - public short getTypeOffset() { - CTVerticalAlignFontProperty vAlign = _ctFont.sizeOfVertAlignArray() == 0 ? null : _ctFont.getVertAlignArray(0); - if (vAlign == null) { - return Font.SS_NONE; - } - int val = vAlign.getVal().intValue(); - switch (val) { - case STVerticalAlignRun.INT_BASELINE: - return Font.SS_NONE; - case STVerticalAlignRun.INT_SUBSCRIPT: - return Font.SS_SUB; - case STVerticalAlignRun.INT_SUPERSCRIPT: - return Font.SS_SUPER; - default: - throw new POIXMLException("Wrong offset value " + val); - } - } - - /** - * get type of text underlining to use - * - * @return byte - underlining type - * @see org.apache.poi.ss.usermodel.FontUnderline - */ - public byte getUnderline() { - CTUnderlineProperty underline = _ctFont.sizeOfUArray() == 0 ? null : _ctFont.getUArray(0); - if (underline != null) { - FontUnderline val = FontUnderline.valueOf(underline.getVal().intValue()); - return val.getByteValue(); - } - return Font.U_NONE; - } - - /** - * set a boolean value for the boldness to use. If omitted, the default value is true. - * - * @param bold - boldness to use - */ - public void setBold(boolean bold) { - if(bold){ - CTBooleanProperty ctBold = _ctFont.sizeOfBArray() == 0 ? _ctFont.addNewB() : _ctFont.getBArray(0); - ctBold.setVal(bold); - } else { - _ctFont.setBArray(null); - } - } - - /** - * @deprecated 3.15 beta 2. Scheduled for removal in 3.17. Use {@link #setBold(boolean)} instead. - */ - public void setBoldweight(short boldweight) - { - setBold(boldweight == BOLDWEIGHT_BOLD); - } - - /** - * get the boldness to use - * @return boldweight - * @see #BOLDWEIGHT_NORMAL - * @see #BOLDWEIGHT_BOLD - * @deprecated 3.15 beta 2. Scheduled for removal in 3.17. Use {@link #getBold} instead. - */ - public short getBoldweight() - { - return getBold() ? BOLDWEIGHT_BOLD : BOLDWEIGHT_NORMAL; - } - - /** - * set character-set to use. - * - * @param charset - charset - * @see FontCharset - */ - public void setCharSet(byte charset) { - int cs = charset & 0xff; - setCharSet(cs); - } - /** - * set character-set to use. - * - * @param charset - charset - * @see FontCharset - */ - public void setCharSet(int charset) { - FontCharset fontCharset = FontCharset.valueOf(charset); - if(fontCharset != null) { - setCharSet(fontCharset); - } else { - throw new POIXMLException("Attention: an attempt to set a type of unknow charset and charset"); - } - } - - /** - * set character-set to use. - * - * @param charSet - */ - public void setCharSet(FontCharset charSet) { - CTIntProperty charsetProperty; - if(_ctFont.sizeOfCharsetArray() == 0) { - charsetProperty = _ctFont.addNewCharset(); - } else { - charsetProperty = _ctFont.getCharsetArray(0); - } - // We know that FontCharset only has valid entries in it, - // so we can just set the int value from it - charsetProperty.setVal( charSet.getValue() ); - } - - /** - * set the indexed color for the font - * - * @param color - color to use - * @see #DEFAULT_FONT_COLOR - Note: default font color - * @see IndexedColors - */ - public void setColor(short color) { - CTColor ctColor = _ctFont.sizeOfColorArray() == 0 ? _ctFont.addNewColor() : _ctFont.getColorArray(0); - switch (color) { - case Font.COLOR_NORMAL: { - ctColor.setIndexed(XSSFFont.DEFAULT_FONT_COLOR); - break; - } - case Font.COLOR_RED: { - ctColor.setIndexed(IndexedColors.RED.getIndex()); - break; - } - default: - ctColor.setIndexed(color); - } - } - - /** - * set the color for the font in Standard Alpha Red Green Blue color value - * - * @param color - color to use - */ - public void setColor(XSSFColor color) { - if(color == null) _ctFont.setColorArray(null); - else { - CTColor ctColor = _ctFont.sizeOfColorArray() == 0 ? _ctFont.addNewColor() : _ctFont.getColorArray(0); - if (ctColor.isSetIndexed()) { - ctColor.unsetIndexed(); - } - ctColor.setRgb(color.getRGB()); - } - } - - /** - * set the font height in points. - * - * @param height - height in points - */ - public void setFontHeight(short height) { - setFontHeight((double) height/20); - } - - /** - * set the font height in points. - * - * @param height - height in points - */ - public void setFontHeight(double height) { - CTFontSize fontSize = _ctFont.sizeOfSzArray() == 0 ? _ctFont.addNewSz() : _ctFont.getSzArray(0); - fontSize.setVal(height); - } - - /** - * set the font height in points. - * - * @link #setFontHeight - */ - public void setFontHeightInPoints(short height) { - setFontHeight((double)height); - } - - /** - * set the theme color for the font to use - * - * @param theme - theme color to use - */ - public void setThemeColor(short theme) { - CTColor ctColor = _ctFont.sizeOfColorArray() == 0 ? _ctFont.addNewColor() : _ctFont.getColorArray(0); - ctColor.setTheme(theme); - } - - /** - * set the name for the font (i.e. Arial). - * If the font doesn't exist (because it isn't installed on the system), - * or the charset is invalid for that font, then another font should - * be substituted. - * The string length for this attribute shall be 0 to 31 characters. - * Default font name is Calibri. - * - * @param name - value representing the name of the font to use - * @see #DEFAULT_FONT_NAME - */ - public void setFontName(String name) { - CTFontName fontName = _ctFont.sizeOfNameArray() == 0 ? _ctFont.addNewName() : _ctFont.getNameArray(0); - fontName.setVal(name == null ? DEFAULT_FONT_NAME : name); - } - - - /** - * set a boolean value for the property specifying whether to use italics or not - * If omitted, the default value is true. - * - * @param italic - value for italics or not - */ - public void setItalic(boolean italic) { - if(italic){ - CTBooleanProperty bool = _ctFont.sizeOfIArray() == 0 ? _ctFont.addNewI() : _ctFont.getIArray(0); - bool.setVal(italic); - } else { - _ctFont.setIArray(null); - } - } - - - /** - * set a boolean value for the property specifying whether to use a strikeout horizontal line through the text or not - * If omitted, the default value is true. - * - * @param strikeout - value for strikeout or not - */ - public void setStrikeout(boolean strikeout) { - if(!strikeout) _ctFont.setStrikeArray(null); - else { - CTBooleanProperty strike = _ctFont.sizeOfStrikeArray() == 0 ? _ctFont.addNewStrike() : _ctFont.getStrikeArray(0); - strike.setVal(strikeout); - } - } - - /** - * set normal,super or subscript, that representing the vertical-alignment setting. - * Setting this to either subscript or superscript shall make the font size smaller if a - * smaller font size is available. - * - * @param offset - offset type to use (none,super,sub) - * @see #SS_NONE - * @see #SS_SUPER - * @see #SS_SUB - */ - public void setTypeOffset(short offset) { - if(offset == Font.SS_NONE){ - _ctFont.setVertAlignArray(null); - } else { - CTVerticalAlignFontProperty offsetProperty = _ctFont.sizeOfVertAlignArray() == 0 ? _ctFont.addNewVertAlign() : _ctFont.getVertAlignArray(0); - switch (offset) { - case Font.SS_NONE: - offsetProperty.setVal(STVerticalAlignRun.BASELINE); - break; - case Font.SS_SUB: - offsetProperty.setVal(STVerticalAlignRun.SUBSCRIPT); - break; - case Font.SS_SUPER: - offsetProperty.setVal(STVerticalAlignRun.SUPERSCRIPT); - break; - default: - throw new IllegalStateException("Invalid type offset: " + offset); - } - } - } - - /** - * set the style of underlining that is used. - * The none style is equivalent to not using underlining at all. - * - * @param underline - underline type to use - * @see FontUnderline - */ - public void setUnderline(byte underline) { - setUnderline(FontUnderline.valueOf(underline)); - } - - /** - * set an enumeration representing the style of underlining that is used. - * The none style is equivalent to not using underlining at all. - * The possible values for this attribute are defined by the FontUnderline - * - * @param underline - FontUnderline enum value - */ - public void setUnderline(FontUnderline underline) { - if(underline == FontUnderline.NONE && _ctFont.sizeOfUArray() > 0){ - _ctFont.setUArray(null); - } else { - CTUnderlineProperty ctUnderline = _ctFont.sizeOfUArray() == 0 ? _ctFont.addNewU() : _ctFont.getUArray(0); - STUnderlineValues.Enum val = STUnderlineValues.Enum.forInt(underline.getValue()); - ctUnderline.setVal(val); - } - } - - - public String toString() { - return _ctFont.toString(); - } - - - /** - * Perform a registration of ourselves - * to the style table - */ - public long registerTo(StylesTable styles) { - this._themes = styles.getTheme(); - short idx = (short)styles.putFont(this, true); - this._index = idx; - return idx; - } - /** - * Records the Themes Table that is associated with - * the current font, used when looking up theme - * based colours and properties. - */ - public void setThemesTable(ThemesTable themes) { - this._themes = themes; - } - - /** - * get the font scheme property. - * is used only in StylesTable to create the default instance of font - * - * @return FontScheme - * @see org.apache.poi.xssf.model.StylesTable#createDefaultFont() - */ - public FontScheme getScheme() { - CTFontScheme scheme = _ctFont.sizeOfSchemeArray() == 0 ? null : _ctFont.getSchemeArray(0); - return scheme == null ? FontScheme.NONE : FontScheme.valueOf(scheme.getVal().intValue()); - } - - /** - * set font scheme property - * - * @param scheme - FontScheme enum value - * @see FontScheme - */ - public void setScheme(FontScheme scheme) { - CTFontScheme ctFontScheme = _ctFont.sizeOfSchemeArray() == 0 ? _ctFont.addNewScheme() : _ctFont.getSchemeArray(0); - STFontScheme.Enum val = STFontScheme.Enum.forInt(scheme.getValue()); - ctFontScheme.setVal(val); - } - - /** - * get the font family to use. - * - * @return the font family to use - * @see org.apache.poi.ss.usermodel.FontFamily - */ - public int getFamily() { - CTIntProperty family = _ctFont.sizeOfFamilyArray() == 0 ? _ctFont.addNewFamily() : _ctFont.getFamilyArray(0); - return family == null ? FontFamily.NOT_APPLICABLE.getValue() : FontFamily.valueOf(family.getVal()).getValue(); - } - - /** - * Set the font family this font belongs to. - * A font family is a set of fonts having common stroke width and serif characteristics. - * The font name overrides when there are conflicting values. - * - * @param value - font family - * @see FontFamily - */ - public void setFamily(int value) { - CTIntProperty family = _ctFont.sizeOfFamilyArray() == 0 ? _ctFont.addNewFamily() : _ctFont.getFamilyArray(0); - family.setVal(value); - } - - /** - * set an enumeration representing the font family this font belongs to. - * A font family is a set of fonts having common stroke width and serif characteristics. - * - * @param family font family - * @link #setFamily(int value) - */ - public void setFamily(FontFamily family) { - setFamily(family.getValue()); - } - - /** - * get the index within the XSSFWorkbook (sequence within the collection of Font objects) - * @return unique index number of the underlying record this Font represents (probably you don't care - * unless you're comparing which one is which) - */ - public short getIndex() - { - return _index; - } - - public int hashCode(){ - return _ctFont.toString().hashCode(); - } - - public boolean equals(Object o){ - if(!(o instanceof XSSFFont)) return false; - - XSSFFont cf = (XSSFFont)o; - return _ctFont.toString().equals(cf.getCTFont().toString()); - } - -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFFontFormatting.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFFontFormatting.java deleted file mode 100644 index 8b3570ac9..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFFontFormatting.java +++ /dev/null @@ -1,237 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -package org.apache.poi.xssf.usermodel; - -import org.apache.poi.ss.usermodel.*; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTFont; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTUnderlineProperty; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STUnderlineValues; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTBooleanProperty; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTColor; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTFontSize; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTVerticalAlignFontProperty; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STVerticalAlignRun; - - -/** - * @author Yegor Kozlov - */ -public class XSSFFontFormatting implements FontFormatting { - CTFont _font; - - /*package*/ XSSFFontFormatting(CTFont font){ - _font = font; - } - - /** - * get the type of super or subscript for the font - * - * @return super or subscript option - * @see #SS_NONE - * @see #SS_SUPER - * @see #SS_SUB - */ - @Override - public short getEscapementType(){ - if(_font.sizeOfVertAlignArray() == 0) return SS_NONE; - - CTVerticalAlignFontProperty prop = _font.getVertAlignArray(0); - return (short)(prop.getVal().intValue() - 1); - } - - /** - * set the escapement type for the font - * - * @param escapementType super or subscript option - * @see #SS_NONE - * @see #SS_SUPER - * @see #SS_SUB - */ - @Override - public void setEscapementType(short escapementType){ - _font.setVertAlignArray(null); - if(escapementType != SS_NONE){ - _font.addNewVertAlign().setVal(STVerticalAlignRun.Enum.forInt(escapementType + 1)); - } - } - - /** - * XMLBeans and the XSD make this look like it can have multiple values, but it is maxOccurrs=1. - * Use get*Array(), it is much faster than get*List(). - * - * @see org.apache.poi.ss.usermodel.FontFormatting#isStruckout() - */ - @Override - public boolean isStruckout() { - for (CTBooleanProperty bProp : _font.getStrikeArray()) return bProp.getVal(); - return false; - } - - /** - * @return font color index - */ - @Override - public short getFontColorIndex(){ - if(_font.sizeOfColorArray() == 0) return -1; - - int idx = 0; - CTColor color = _font.getColorArray(0); - if(color.isSetIndexed()) idx = (int)color.getIndexed(); - return (short)idx; - } - - /** - * @param color font color index - */ - @Override - public void setFontColorIndex(short color){ - _font.setColorArray(null); - if(color != -1){ - _font.addNewColor().setIndexed(color); - } - } - - @Override - public XSSFColor getFontColor() { - if(_font.sizeOfColorArray() == 0) return null; - - return new XSSFColor(_font.getColorArray(0)); - } - - @Override - public void setFontColor(Color color) { - XSSFColor xcolor = XSSFColor.toXSSFColor(color); - if (xcolor == null) { - _font.getColorList().clear(); - } else { - _font.setColorArray(0, xcolor.getCTColor()); - } - } - - /** - * gets the height of the font in 1/20th point units - * - * @return fontheight (in points/20); or -1 if not modified - */ - @Override - public int getFontHeight(){ - if(_font.sizeOfSzArray() == 0) return -1; - - CTFontSize sz = _font.getSzArray(0); - return (short)(20*sz.getVal()); - } - - /** - * Sets the height of the font in 1/20th point units - * - * @param height the height in twips (in points/20) - */ - @Override - public void setFontHeight(int height){ - _font.setSzArray(null); - if(height != -1){ - _font.addNewSz().setVal((double)height / 20); - } - } - - /** - * get the type of underlining for the font - * - * @return font underlining type - * - * @see #U_NONE - * @see #U_SINGLE - * @see #U_DOUBLE - * @see #U_SINGLE_ACCOUNTING - * @see #U_DOUBLE_ACCOUNTING - */ - @Override - public short getUnderlineType(){ - if(_font.sizeOfUArray() == 0) return U_NONE; - CTUnderlineProperty u = _font.getUArray(0); - switch(u.getVal().intValue()){ - case STUnderlineValues.INT_SINGLE: return U_SINGLE; - case STUnderlineValues.INT_DOUBLE: return U_DOUBLE; - case STUnderlineValues.INT_SINGLE_ACCOUNTING: return U_SINGLE_ACCOUNTING; - case STUnderlineValues.INT_DOUBLE_ACCOUNTING: return U_DOUBLE_ACCOUNTING; - default: return U_NONE; - } - } - - /** - * set the type of underlining type for the font - * - * @param underlineType super or subscript option - * - * @see #U_NONE - * @see #U_SINGLE - * @see #U_DOUBLE - * @see #U_SINGLE_ACCOUNTING - * @see #U_DOUBLE_ACCOUNTING - */ - @Override - public void setUnderlineType(short underlineType){ - _font.setUArray(null); - if(underlineType != U_NONE){ - FontUnderline fenum = FontUnderline.valueOf(underlineType); - STUnderlineValues.Enum val = STUnderlineValues.Enum.forInt(fenum.getValue()); - _font.addNewU().setVal(val); - } - } - - /** - * get whether the font weight is set to bold or not - * - * @return bold - whether the font is bold or not - */ - @Override - public boolean isBold(){ - return _font.sizeOfBArray() == 1 && _font.getBArray(0).getVal(); - } - - /** - * @return true if font style was set to italic - */ - @Override - public boolean isItalic(){ - return _font.sizeOfIArray() == 1 && _font.getIArray(0).getVal(); - } - - /** - * set font style options. - * - * @param italic - if true, set posture style to italic, otherwise to normal - * @param bold if true, set font weight to bold, otherwise to normal - */ - @Override - public void setFontStyle(boolean italic, boolean bold){ - _font.setIArray(null); - _font.setBArray(null); - if(italic) _font.addNewI().setVal(true); - if(bold) _font.addNewB().setVal(true); - } - - /** - * set font style options to default values (non-italic, non-bold) - */ - @Override - public void resetFontStyle(){ - _font.set(CTFont.Factory.newInstance()); - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFFormulaEvaluator.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFFormulaEvaluator.java deleted file mode 100644 index e63f47b46..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFFormulaEvaluator.java +++ /dev/null @@ -1,106 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import org.apache.poi.ss.formula.BaseFormulaEvaluator; -import org.apache.poi.ss.formula.EvaluationCell; -import org.apache.poi.ss.formula.IStabilityClassifier; -import org.apache.poi.ss.formula.WorkbookEvaluator; -import org.apache.poi.ss.formula.udf.UDFFinder; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; - -/** - * Evaluates formula cells.

    - * - * For performance reasons, this class keeps a cache of all previously calculated intermediate - * cell values. Be sure to call {@link #clearAllCachedResultValues()} if any workbook cells are changed between - * calls to evaluate~ methods on this class. - */ -public final class XSSFFormulaEvaluator extends BaseXSSFFormulaEvaluator { - private XSSFWorkbook _book; - - public XSSFFormulaEvaluator(XSSFWorkbook workbook) { - this(workbook, null, null); - } - private XSSFFormulaEvaluator(XSSFWorkbook workbook, IStabilityClassifier stabilityClassifier, UDFFinder udfFinder) { - this(workbook, new WorkbookEvaluator(XSSFEvaluationWorkbook.create(workbook), stabilityClassifier, udfFinder)); - } - protected XSSFFormulaEvaluator(XSSFWorkbook workbook, WorkbookEvaluator bookEvaluator) { - super(bookEvaluator); - _book = workbook; - } - - /** - * @param stabilityClassifier used to optimise caching performance. Pass null - * for the (conservative) assumption that any cell may have its definition changed after - * evaluation begins. - * @param udfFinder pass null for default (AnalysisToolPak only) - */ - public static XSSFFormulaEvaluator create(XSSFWorkbook workbook, IStabilityClassifier stabilityClassifier, UDFFinder udfFinder) { - return new XSSFFormulaEvaluator(workbook, stabilityClassifier, udfFinder); - } - - /** - * Loops over all cells in all sheets of the supplied - * workbook. - * For cells that contain formulas, their formulas are - * evaluated, and the results are saved. These cells - * remain as formula cells. - * For cells that do not contain formulas, no changes - * are made. - * This is a helpful wrapper around looping over all - * cells, and calling evaluateFormulaCell on each one. - */ - public static void evaluateAllFormulaCells(XSSFWorkbook wb) { - BaseFormulaEvaluator.evaluateAllFormulaCells(wb); - } - - @Override - public XSSFCell evaluateInCell(Cell cell) { - return (XSSFCell) super.evaluateInCell(cell); - } - - /** - * Loops over all cells in all sheets of the supplied - * workbook. - * For cells that contain formulas, their formulas are - * evaluated, and the results are saved. These cells - * remain as formula cells. - * For cells that do not contain formulas, no changes - * are made. - * This is a helpful wrapper around looping over all - * cells, and calling evaluateFormulaCell on each one. - */ - public void evaluateAll() { - evaluateAllFormulaCells(_book, this); - } - - /** - * Turns a XSSFCell into a XSSFEvaluationCell - */ - protected EvaluationCell toEvaluationCell(Cell cell) { - if (!(cell instanceof XSSFCell)){ - throw new IllegalArgumentException("Unexpected type of cell: " + cell.getClass() + "." + - " Only XSSFCells can be evaluated."); - } - - return new XSSFEvaluationCell((XSSFCell)cell); - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFGraphicFrame.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFGraphicFrame.java deleted file mode 100644 index 4cee01628..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFGraphicFrame.java +++ /dev/null @@ -1,195 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xssf.usermodel; - -import javax.xml.namespace.QName; - -import org.apache.poi.util.Internal; -import org.apache.xmlbeans.XmlCursor; -import org.openxmlformats.schemas.drawingml.x2006.main.CTGraphicalObjectData; -import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPoint2D; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D; -import org.openxmlformats.schemas.drawingml.x2006.main.CTShapeProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTransform2D; -import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTGraphicalObjectFrame; -import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTGraphicalObjectFrameNonVisual; -import org.openxmlformats.schemas.officeDocument.x2006.relationships.STRelationshipId; - -/** - * Represents DrawingML GraphicalObjectFrame. - * - * @author Roman Kashitsyn - */ -public final class XSSFGraphicFrame extends XSSFShape { - - private static CTGraphicalObjectFrame prototype = null; - - private CTGraphicalObjectFrame graphicFrame; - private XSSFClientAnchor anchor; - - /** - * Construct a new XSSFGraphicFrame object. - * - * @param drawing the XSSFDrawing that owns this frame - * @param ctGraphicFrame the XML bean that stores this frame content - */ - protected XSSFGraphicFrame(XSSFDrawing drawing, CTGraphicalObjectFrame ctGraphicFrame) { - this.drawing = drawing; // protected field on XSSFShape - this.graphicFrame = ctGraphicFrame; - } - - @Internal - public CTGraphicalObjectFrame getCTGraphicalObjectFrame() { - return graphicFrame; - } - - /** - * Initialize default structure of a new graphic frame - */ - protected static CTGraphicalObjectFrame prototype() { - if (prototype == null) { - CTGraphicalObjectFrame graphicFrame = CTGraphicalObjectFrame.Factory.newInstance(); - - CTGraphicalObjectFrameNonVisual nvGraphic = graphicFrame.addNewNvGraphicFramePr(); - CTNonVisualDrawingProps props = nvGraphic.addNewCNvPr(); - props.setId(0); - props.setName("Diagramm 1"); - nvGraphic.addNewCNvGraphicFramePr(); - - CTTransform2D transform = graphicFrame.addNewXfrm(); - CTPositiveSize2D extPoint = transform.addNewExt(); - CTPoint2D offPoint = transform.addNewOff(); - - extPoint.setCx(0); - extPoint.setCy(0); - offPoint.setX(0); - offPoint.setY(0); - - /* CTGraphicalObject graphic = */ graphicFrame.addNewGraphic(); - - prototype = graphicFrame; - } - return prototype; - } - - /** - * Sets the frame macro. - */ - public void setMacro(String macro) { - graphicFrame.setMacro(macro); - } - - /** - * Sets the frame name. - */ - public void setName(String name) { - getNonVisualProperties().setName(name); - } - - /** - * Returns the frame name. - * @return name of the frame - */ - public String getName() { - return getNonVisualProperties().getName(); - } - - private CTNonVisualDrawingProps getNonVisualProperties() { - CTGraphicalObjectFrameNonVisual nvGraphic = graphicFrame.getNvGraphicFramePr(); - return nvGraphic.getCNvPr(); - } - - /** - * Attaches frame to an anchor. - */ - protected void setAnchor(XSSFClientAnchor anchor) { - this.anchor = anchor; - } - - /** - * Returns the frame anchor. - * @return the anchor this frame is attached to - */ - public XSSFClientAnchor getAnchor() { - return anchor; - } - - /** - * Assign a DrawingML chart to the graphic frame. - */ - protected void setChart(XSSFChart chart, String relId) { - CTGraphicalObjectData data = graphicFrame.getGraphic().addNewGraphicData(); - appendChartElement(data, relId); - chart.setGraphicFrame(this); - return; - } - - /** - * Gets the frame id. - */ - public long getId() { - return graphicFrame.getNvGraphicFramePr().getCNvPr().getId(); - } - - /** - * Sets the frame id. - */ - protected void setId(long id) { - graphicFrame.getNvGraphicFramePr().getCNvPr().setId(id); - } - - /** - * The low level code to insert {@code } tag into - * {@code}. - * - * Here is the schema (ECMA-376): - *

    -	 * {@code
    -	 * 
    -	 *   
    -	 *     
    -	 *   
    -	 *   
    -	 * 
    -	 * }
    -	 * 
    - */ - private void appendChartElement(CTGraphicalObjectData data, String id) { - String r_namespaceUri = STRelationshipId.type.getName().getNamespaceURI(); - String c_namespaceUri = XSSFDrawing.NAMESPACE_C; - XmlCursor cursor = data.newCursor(); - cursor.toNextToken(); - cursor.beginElement(new QName(c_namespaceUri, "chart", "c")); - cursor.insertAttributeWithValue(new QName(r_namespaceUri, "id", "r"), id); - cursor.dispose(); - data.setUri(c_namespaceUri); - } - - @Override - protected CTShapeProperties getShapeProperties(){ - return null; - } - - @Override - public String getShapeName() { - return graphicFrame.getNvGraphicFramePr().getCNvPr().getName(); - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFHyperlink.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFHyperlink.java deleted file mode 100644 index 401f33cc7..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFHyperlink.java +++ /dev/null @@ -1,403 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel; - -import java.net.URI; -import java.net.URISyntaxException; - -import org.apache.poi.common.usermodel.HyperlinkType; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.opc.PackageRelationship; -import org.apache.poi.ss.usermodel.Hyperlink; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.util.Internal; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTHyperlink; - -/** - * XSSF Implementation of a Hyperlink. - * Note - unlike with HSSF, many kinds of hyperlink - * are largely stored as relations of the sheet - */ -public class XSSFHyperlink implements Hyperlink { - final private HyperlinkType _type; - final private PackageRelationship _externalRel; - final private CTHyperlink _ctHyperlink; //contains a reference to the cell where the hyperlink is anchored, getRef() - private String _location; //what the hyperlink refers to - - /** - * Create a new XSSFHyperlink. This method is protected to be used only by - * {@link XSSFCreationHelper#createHyperlink(int)}. - * - * @param type - the type of hyperlink to create, see {@link Hyperlink} - * @deprecated POI 3.15 beta 3. Use {@link #XSSFHyperlink(HyperlinkType)} instead. - */ - protected XSSFHyperlink(int type) { - this(HyperlinkType.forInt(type)); - } - - /** - * Create a new XSSFHyperlink. This method is protected to be used only by - * {@link XSSFCreationHelper#createHyperlink(HyperlinkType)}. - * - * @param type - the type of hyperlink to create - */ - protected XSSFHyperlink(HyperlinkType type) { - _type = type; - _ctHyperlink = CTHyperlink.Factory.newInstance(); - _externalRel = null; - } - - /** - * Create a XSSFHyperlink and initialize it from the supplied CTHyperlink bean and package relationship - * - * @param ctHyperlink the xml bean containing xml properties - * @param hyperlinkRel the relationship in the underlying OPC package which stores the actual link's address - */ - protected XSSFHyperlink(CTHyperlink ctHyperlink, PackageRelationship hyperlinkRel) { - _ctHyperlink = ctHyperlink; - _externalRel = hyperlinkRel; - - // Figure out the Hyperlink type and destination - - if (_externalRel == null) { - // If it has a location, it's internal - if (ctHyperlink.getLocation() != null) { - _type = HyperlinkType.DOCUMENT; - _location = ctHyperlink.getLocation(); - } else if (ctHyperlink.getId() != null) { - throw new IllegalStateException("The hyperlink for cell " - + ctHyperlink.getRef() + " references relation " - + ctHyperlink.getId() + ", but that didn't exist!"); - } else { - // hyperlink is internal and is not related to other parts - _type = HyperlinkType.DOCUMENT; - } - } else { - URI target = _externalRel.getTargetURI(); - _location = target.toString(); - if (ctHyperlink.getLocation() != null) { - // URI fragment - _location += "#" + ctHyperlink.getLocation(); - } - - // Try to figure out the type - if (_location.startsWith("http://") || _location.startsWith("https://") - || _location.startsWith("ftp://")) { - _type = HyperlinkType.URL; - } else if (_location.startsWith("mailto:")) { - _type = HyperlinkType.EMAIL; - } else { - _type = HyperlinkType.FILE; - } - } - - } - - /** - * Create a new XSSFHyperlink. This method is for Internal use only. - * XSSFHyperlinks can be created by {@link XSSFCreationHelper}. - * See the spreadsheet quick-guide - * for an example. - * - * @param other the hyperlink to copy - */ - @Internal //FIXME: change to protected if/when SXSSFHyperlink class is created - public XSSFHyperlink(Hyperlink other) { - if (other instanceof XSSFHyperlink) { - XSSFHyperlink xlink = (XSSFHyperlink) other; - _type = xlink.getTypeEnum(); - _location = xlink._location; - _externalRel = xlink._externalRel; - _ctHyperlink = (CTHyperlink) xlink._ctHyperlink.copy(); - } - else { - _type = other.getTypeEnum(); - _location = other.getAddress(); - _externalRel = null; - _ctHyperlink = CTHyperlink.Factory.newInstance(); - setCellReference(new CellReference(other.getFirstRow(), other.getFirstColumn())); - } - } - /** - * @return the underlying CTHyperlink object - */ - @Internal - public CTHyperlink getCTHyperlink() { - return _ctHyperlink; - } - - /** - * Do we need to a relation too, to represent - * this hyperlink? - */ - public boolean needsRelationToo() { - return (_type != HyperlinkType.DOCUMENT); - } - - /** - * Generates the relation if required - */ - protected void generateRelationIfNeeded(PackagePart sheetPart) { - if (_externalRel == null && needsRelationToo()) { - // Generate the relation - PackageRelationship rel = - sheetPart.addExternalRelationship(_location, XSSFRelation.SHEET_HYPERLINKS.getRelation()); - - // Update the r:id - _ctHyperlink.setId(rel.getId()); - } - } - - /** - * Return the type of this hyperlink - * - * @return the type of this hyperlink - * @see HyperlinkType#forInt - * @deprecated POI 3.15 beta 3. Use {@link #getTypeEnum()} instead. - * getType will return a HyperlinkType enum in the future. - */ - @Override - public int getType() { - return _type.getCode(); - } - - /** - * Return the type of this hyperlink - * - * @return the type of this hyperlink - */ - @Override - public HyperlinkType getTypeEnum() { - return _type; - } - - /** - * Get the reference of the cell this applies to, - * es A55 - */ - public String getCellRef() { - return _ctHyperlink.getRef(); - } - - /** - * Hyperlink address. Depending on the hyperlink type it can be URL, e-mail, path to a file. - * The is the hyperlink target. - * - * @return the address of this hyperlink - */ - @Override - public String getAddress() { - return _location; - } - - /** - * Return text label for this hyperlink - * - * @return text to display - */ - @Override - public String getLabel() { - return _ctHyperlink.getDisplay(); - } - - /** - * Location within target. If target is a workbook (or this workbook) this shall refer to a - * sheet and cell or a defined name. Can also be an HTML anchor if target is HTML file. - * - * @return location - */ - public String getLocation() { - return _ctHyperlink.getLocation(); - } - - /** - * Sets text label for this hyperlink - * - * @param label text label for this hyperlink - */ - @Override - public void setLabel(String label) { - _ctHyperlink.setDisplay(label); - } - - /** - * Location within target. If target is a workbook (or this workbook) this shall refer to a - * sheet and cell or a defined name. Can also be an HTML anchor if target is HTML file. - * - * @param location - string representing a location of this hyperlink - */ - public void setLocation(String location) { - _ctHyperlink.setLocation(location); - } - - /** - * Hyperlink address. Depending on the hyperlink type it can be URL, e-mail, path to a file - * This is the hyperlink target. - * - * @param address - the address of this hyperlink - */ - @Override - public void setAddress(String address) { - validate(address); - - _location = address; - //we must set location for internal hyperlinks - if (_type == HyperlinkType.DOCUMENT) { - setLocation(address); - } - } - - @SuppressWarnings("fall-through") - private void validate(String address) { - switch (_type) { - // email, path to file and url must be valid URIs - case EMAIL: - case FILE: - case URL: - try { - new URI(address); - } catch (URISyntaxException e) { - throw new IllegalArgumentException("Address of hyperlink must be a valid URI", e); - } - break; - case DOCUMENT: - // currently not evaluating anything. - break; - default: - throw new IllegalStateException("Invalid Hyperlink type: " + _type); - } - } - - /** - * Assigns this hyperlink to the given cell reference - */ - @Internal - public void setCellReference(String ref) { - _ctHyperlink.setRef(ref); - } - @Internal - public void setCellReference(CellReference ref) { - setCellReference(ref.formatAsString()); - } - - private CellReference buildCellReference() { - String ref = _ctHyperlink.getRef(); - if (ref == null) { - ref = "A1"; - } - return new CellReference(ref); - } - - - /** - * Return the column of the first cell that contains the hyperlink - * - * @return the 0-based column of the first cell that contains the hyperlink - */ - @Override - public int getFirstColumn() { - return buildCellReference().getCol(); - } - - - /** - * Return the column of the last cell that contains the hyperlink - * - * @return the 0-based column of the last cell that contains the hyperlink - */ - @Override - public int getLastColumn() { - return buildCellReference().getCol(); - } - - /** - * Return the row of the first cell that contains the hyperlink - * - * @return the 0-based row of the cell that contains the hyperlink - */ - @Override - public int getFirstRow() { - return buildCellReference().getRow(); - } - - - /** - * Return the row of the last cell that contains the hyperlink - * - * @return the 0-based row of the last cell that contains the hyperlink - */ - @Override - public int getLastRow() { - return buildCellReference().getRow(); - } - - /** - * Set the column of the first cell that contains the hyperlink - * - * @param col the 0-based column of the first cell that contains the hyperlink - */ - @Override - public void setFirstColumn(int col) { - setCellReference(new CellReference( getFirstRow(), col )); - } - - /** - * Set the column of the last cell that contains the hyperlink. - * For XSSF, a Hyperlink may only reference one cell - * - * @param col the 0-based column of the last cell that contains the hyperlink - */ - @Override - public void setLastColumn(int col) { - setFirstColumn(col); - } - - /** - * Set the row of the first cell that contains the hyperlink - * - * @param row the 0-based row of the first cell that contains the hyperlink - */ - @Override - public void setFirstRow(int row) { - setCellReference(new CellReference( row, getFirstColumn() )); - } - - /** - * Set the row of the last cell that contains the hyperlink. - * For XSSF, a Hyperlink may only reference one cell - * - * @param row the 0-based row of the last cell that contains the hyperlink - */ - @Override - public void setLastRow(int row) { - setFirstRow(row); - } - - /** - * @return additional text to help the user understand more about the hyperlink - */ - public String getTooltip() { - return _ctHyperlink.getTooltip(); - } - - /** - * @param text additional text to help the user understand more about the hyperlink - */ - public void setTooltip(String text) { - _ctHyperlink.setTooltip(text); - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFIconMultiStateFormatting.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFIconMultiStateFormatting.java deleted file mode 100644 index 29062ee06..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFIconMultiStateFormatting.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -package org.apache.poi.xssf.usermodel; - -import org.apache.poi.ss.usermodel.ConditionalFormattingThreshold; -import org.apache.poi.ss.usermodel.IconMultiStateFormatting; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCfvo; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTIconSet; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STIconSetType; - -/** - * High level representation for Icon / Multi-State Formatting - * component of Conditional Formatting settings - */ -public class XSSFIconMultiStateFormatting implements IconMultiStateFormatting { - CTIconSet _iconset; - - /*package*/ XSSFIconMultiStateFormatting(CTIconSet iconset){ - _iconset = iconset; - } - - public IconSet getIconSet() { - String set = _iconset.getIconSet().toString(); - return IconSet.byName(set); - } - public void setIconSet(IconSet set) { - STIconSetType.Enum xIconSet = STIconSetType.Enum.forString(set.name); - _iconset.setIconSet(xIconSet); - } - - public boolean isIconOnly() { - if (_iconset.isSetShowValue()) - return !_iconset.getShowValue(); - return false; - } - public void setIconOnly(boolean only) { - _iconset.setShowValue(!only); - } - - public boolean isReversed() { - if (_iconset.isSetReverse()) - return _iconset.getReverse(); - return false; - } - public void setReversed(boolean reversed) { - _iconset.setReverse(reversed); - } - - public XSSFConditionalFormattingThreshold[] getThresholds() { - CTCfvo[] cfvos = _iconset.getCfvoArray(); - XSSFConditionalFormattingThreshold[] t = - new XSSFConditionalFormattingThreshold[cfvos.length]; - for (int i=0; i - * This element contains all of the properties related to the XML map, - * and the behaviors expected during data refresh operations. - * - * @author Roberto Manicardi - */ - - -public class XSSFMap { - private CTMap ctMap; - private MapInfo mapInfo; - - public XSSFMap(CTMap ctMap, MapInfo mapInfo) { - this.ctMap = ctMap; - this.mapInfo = mapInfo; - } - - - @Internal - public CTMap getCtMap() { - return ctMap; - } - - @Internal - public CTSchema getCTSchema() { - String schemaId = ctMap.getSchemaID(); - return mapInfo.getCTSchemaById(schemaId); - } - - public Node getSchema() { - Node xmlSchema = null; - - CTSchema schema = getCTSchema(); - xmlSchema = schema.getDomNode().getFirstChild(); - - return xmlSchema; - } - - /** - * @return the list of Single Xml Cells that provide a map rule to this mapping. - */ - public List getRelatedSingleXMLCell() { - List relatedSimpleXmlCells = new ArrayList(); - - int sheetNumber = mapInfo.getWorkbook().getNumberOfSheets(); - for (int i = 0; i < sheetNumber; i++) { - XSSFSheet sheet = mapInfo.getWorkbook().getSheetAt(i); - for (POIXMLDocumentPart p : sheet.getRelations()) { - if (p instanceof SingleXmlCells) { - SingleXmlCells singleXMLCells = (SingleXmlCells) p; - for (XSSFSingleXmlCell cell : singleXMLCells.getAllSimpleXmlCell()) { - if (cell.getMapId() == ctMap.getID()) { - relatedSimpleXmlCells.add(cell); - } - } - } - } - } - return relatedSimpleXmlCells; - } - - /** - * @return the list of all Tables that provide a map rule to this mapping - */ - public List getRelatedTables() { - List tables = new ArrayList(); - for (Sheet sheet : mapInfo.getWorkbook()) { - for (RelationPart rp : ((XSSFSheet)sheet).getRelationParts()) { - if (rp.getRelationship().getRelationshipType().equals(XSSFRelation.TABLE.getRelation())) { - XSSFTable table = rp.getDocumentPart(); - if (table.mapsTo(ctMap.getID())) { - tables.add(table); - } - } - } - } - - return tables; - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFName.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFName.java deleted file mode 100644 index d60ed5f89..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFName.java +++ /dev/null @@ -1,415 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel; - -import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.ss.formula.ptg.Ptg; - -import org.apache.poi.ss.formula.FormulaParser; -import org.apache.poi.ss.formula.FormulaType; -import org.apache.poi.ss.usermodel.Name; -import org.apache.poi.ss.util.AreaReference; -import org.apache.poi.ss.util.CellReference; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTDefinedName; - -/** - * Represents a defined named range in a SpreadsheetML workbook. - *

    - * Defined names are descriptive text that is used to represents a cell, range of cells, formula, or constant value. - * Use easy-to-understand names, such as Products, to refer to hard to understand ranges, such as Sales!C20:C30. - *

    - * Example: - *
    - * XSSFWorkbook wb = new XSSFWorkbook(); - * XSSFSheet sh = wb.createSheet("Sheet1"); - * - * //applies to the entire workbook - * XSSFName name1 = wb.createName(); - * name1.setNameName("FMLA"); - * name1.setRefersToFormula("Sheet1!$B$3"); - * - * //applies to Sheet1 - * XSSFName name2 = wb.createName(); - * name2.setNameName("SheetLevelName"); - * name2.setComment("This name is scoped to Sheet1"); - * name2.setLocalSheetId(0); - * name2.setRefersToFormula("Sheet1!$B$3"); - * - *
    - * - * @author Nick Burch - * @author Yegor Kozlov - */ -public final class XSSFName implements Name { - - /** - * A built-in defined name that specifies the workbook's print area - */ - public static final String BUILTIN_PRINT_AREA = "_xlnm.Print_Area"; - - /** - * A built-in defined name that specifies the row(s) or column(s) to repeat - * at the top of each printed page. - */ - public static final String BUILTIN_PRINT_TITLE = "_xlnm.Print_Titles"; - - /** - * A built-in defined name that refers to a range containing the criteria values - * to be used in applying an advanced filter to a range of data - */ - public static final String BUILTIN_CRITERIA = "_xlnm.Criteria:"; - - - /** - * this defined name refers to the range containing the filtered - * output values resulting from applying an advanced filter criteria to a source - * range - */ - public static final String BUILTIN_EXTRACT = "_xlnm.Extract:"; - - /** - * ?an be one of the following - *
  • this defined name refers to a range to which an advanced filter has been - * applied. This represents the source data range, unfiltered. - *
  • This defined name refers to a range to which an AutoFilter has been - * applied - */ - public static final String BUILTIN_FILTER_DB = "_xlnm._FilterDatabase"; - - /** - * A built-in defined name that refers to a consolidation area - */ - public static final String BUILTIN_CONSOLIDATE_AREA = "_xlnm.Consolidate_Area"; - - /** - * A built-in defined name that specified that the range specified is from a database data source - */ - public static final String BUILTIN_DATABASE = "_xlnm.Database"; - - /** - * A built-in defined name that refers to a sheet title. - */ - public static final String BUILTIN_SHEET_TITLE = "_xlnm.Sheet_Title"; - - private XSSFWorkbook _workbook; - private CTDefinedName _ctName; - - /** - * Creates an XSSFName object - called internally by XSSFWorkbook. - * - * @param name - the xml bean that holds data represenring this defined name. - * @param workbook - the workbook object associated with the name - * @see org.apache.poi.xssf.usermodel.XSSFWorkbook#createName() - */ - protected XSSFName(CTDefinedName name, XSSFWorkbook workbook) { - _workbook = workbook; - _ctName = name; - } - - /** - * Returns the underlying named range object - */ - protected CTDefinedName getCTName() { - return _ctName; - } - - /** - * Returns the name that will appear in the user interface for the defined name. - * - * @return text name of this defined name - */ - public String getNameName() { - return _ctName.getName(); - } - - /** - * Sets the name that will appear in the user interface for the defined name. - * Names must begin with a letter or underscore, not contain spaces and be unique across the workbook. - * - *

    - * A name must always be unique within its scope. POI prevents you from defining a name that is not unique - * within its scope. However you can use the same name in different scopes. Example: - *

    - * //by default names are workbook-global - * XSSFName name; - * name = workbook.createName(); - * name.setNameName("sales_08"); - * - * name = workbook.createName(); - * name.setNameName("sales_08"); //will throw an exception: "The workbook already contains this name (case-insensitive)" - * - * //create sheet-level name - * name = workbook.createName(); - * name.setSheetIndex(0); //the scope of the name is the first sheet - * name.setNameName("sales_08"); //ok - * - * name = workbook.createName(); - * name.setSheetIndex(0); - * name.setNameName("sales_08"); //will throw an exception: "The sheet already contains this name (case-insensitive)" - * - *
    - *

    - * @param name name of this defined name - * @throws IllegalArgumentException if the name is invalid or the workbook already contains this name (case-insensitive) - */ - public void setNameName(String name) { - validateName(name); - - String oldName = getNameName(); - int sheetIndex = getSheetIndex(); - //Check to ensure no other names have the same case-insensitive name at the same scope - for (XSSFName foundName : _workbook.getNames(name)) { - if (foundName.getSheetIndex() == sheetIndex && foundName != this) { - String msg = "The "+(sheetIndex == -1 ? "workbook" : "sheet")+" already contains this name: " + name; - throw new IllegalArgumentException(msg); - } - } - _ctName.setName(name); - //Need to update the name -> named ranges map - _workbook.updateName(this, oldName); - } - - public String getRefersToFormula() { - String result = _ctName.getStringValue(); - if (result == null || result.length() < 1) { - return null; - } - return result; - } - - public void setRefersToFormula(String formulaText) { - XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(_workbook); - //validate through the FormulaParser - FormulaParser.parse(formulaText, fpb, FormulaType.NAMEDRANGE, getSheetIndex(), -1); - - _ctName.setStringValue(formulaText); - } - - public boolean isDeleted(){ - String formulaText = getRefersToFormula(); - if (formulaText == null) { - return false; - } - XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(_workbook); - Ptg[] ptgs = FormulaParser.parse(formulaText, fpb, FormulaType.NAMEDRANGE, getSheetIndex(), -1); - return Ptg.doesFormulaReferToDeletedCell(ptgs); - } - - /** - * Tell Excel that this name applies to the worksheet with the specified index instead of the entire workbook. - * - * @param index the sheet index this name applies to, -1 unsets this property making the name workbook-global - */ - public void setSheetIndex(int index) { - int lastSheetIx = _workbook.getNumberOfSheets() - 1; - if (index < -1 || index > lastSheetIx) { - throw new IllegalArgumentException("Sheet index (" + index +") is out of range" + - (lastSheetIx == -1 ? "" : (" (0.." + lastSheetIx + ")"))); - } - - if(index == -1) { - if(_ctName.isSetLocalSheetId()) _ctName.unsetLocalSheetId(); - } else { - _ctName.setLocalSheetId(index); - } - } - - /** - * Returns the sheet index this name applies to. - * - * @return the sheet index this name applies to, -1 if this name applies to the entire workbook - */ - public int getSheetIndex() { - return _ctName.isSetLocalSheetId() ? (int) _ctName.getLocalSheetId() : -1; - } - - /** - * Indicates that the defined name refers to a user-defined function. - * This attribute is used when there is an add-in or other code project associated with the file. - * - * @param value true indicates the name refers to a function. - */ - public void setFunction(boolean value) { - _ctName.setFunction(value); - } - - /** - * Indicates that the defined name refers to a user-defined function. - * This attribute is used when there is an add-in or other code project associated with the file. - * - * @return true indicates the name refers to a function. - */ - public boolean getFunction() { - return _ctName.getFunction(); - } - - /** - * Specifies the function group index if the defined name refers to a function. The function - * group defines the general category for the function. This attribute is used when there is - * an add-in or other code project associated with the file. - * - * @param functionGroupId the function group index that defines the general category for the function - */ - public void setFunctionGroupId(int functionGroupId) { - _ctName.setFunctionGroupId(functionGroupId); - } - - /** - * Returns the function group index if the defined name refers to a function. The function - * group defines the general category for the function. This attribute is used when there is - * an add-in or other code project associated with the file. - * - * @return the function group index that defines the general category for the function - */ - public int getFunctionGroupId() { - return (int) _ctName.getFunctionGroupId(); - } - - /** - * Get the sheets name which this named range is referenced to - * - * @return sheet name, which this named range referred to. - * Empty string if the referenced sheet name weas not found. - */ - public String getSheetName() { - if (_ctName.isSetLocalSheetId()) { - // Given as explicit sheet id - int sheetId = (int)_ctName.getLocalSheetId(); - return _workbook.getSheetName(sheetId); - } - String ref = getRefersToFormula(); - AreaReference areaRef = new AreaReference(ref); - return areaRef.getFirstCell().getSheetName(); - } - - /** - * Is the name refers to a user-defined function ? - * - * @return true if this name refers to a user-defined function - */ - public boolean isFunctionName() { - return getFunction(); - } - - /** - * Returns the comment the user provided when the name was created. - * - * @return the user comment for this named range - */ - public String getComment() { - return _ctName.getComment(); - } - - /** - * Specifies the comment the user provided when the name was created. - * - * @param comment the user comment for this named range - */ - public void setComment(String comment) { - _ctName.setComment(comment); - } - - @Override - public int hashCode() { - return _ctName.toString().hashCode(); - } - - /** - * Compares this name to the specified object. - * The result is true if the argument is XSSFName and the - * underlying CTDefinedName bean equals to the CTDefinedName representing this name - * - * @param o the object to compare this XSSFName against. - * @return true if the XSSFName are equal; - * false otherwise. - */ - @Override - public boolean equals(Object o) { - if(o == this) return true; - - if (!(o instanceof XSSFName)) return false; - - XSSFName cf = (XSSFName) o; - return _ctName.toString().equals(cf.getCTName().toString()); - } - - /** - * https://support.office.com/en-us/article/Define-and-use-names-in-formulas-4D0F13AC-53B7-422E-AFD2-ABD7FF379C64#bmsyntax_rules_for_names - * - * Valid characters: - * First character: { letter | underscore | backslash } - * Remaining characters: { letter | number | period | underscore } - * - * Cell shorthand: cannot be { "C" | "c" | "R" | "r" } - * - * Cell references disallowed: cannot be a cell reference $A$1 or R1C1 - * - * Spaces are not valid (follows from valid characters above) - * - * Name length: (XSSF-specific?) 255 characters maximum - * - * Case sensitivity: all names are case-insensitive - * - * Uniqueness: must be unique (for names with the same scope) - * - * @param name - */ - private static void validateName(String name) { - - if (name.length() == 0) { - throw new IllegalArgumentException("Name cannot be blank"); - } - if (name.length() > 255) { - throw new IllegalArgumentException("Invalid name: '"+name+"': cannot exceed 255 characters in length"); - } - if (name.equalsIgnoreCase("R") || name.equalsIgnoreCase("C")) { - throw new IllegalArgumentException("Invalid name: '"+name+"': cannot be special shorthand R or C"); - } - - // is first character valid? - char c = name.charAt(0); - String allowedSymbols = "_\\"; - boolean characterIsValid = (Character.isLetter(c) || allowedSymbols.indexOf(c) != -1); - if (!characterIsValid) { - throw new IllegalArgumentException("Invalid name: '"+name+"': first character must be underscore or a letter"); - } - - // are all other characters valid? - allowedSymbols = "_.\\"; //backslashes needed for unicode escape - for (final char ch : name.toCharArray()) { - characterIsValid = (Character.isLetterOrDigit(ch) || allowedSymbols.indexOf(ch) != -1); - if (!characterIsValid) { - throw new IllegalArgumentException("Invalid name: '"+name+"': name must be letter, digit, period, or underscore"); - } - } - - // Is the name a valid $A$1 cell reference - // Because $, :, and ! are disallowed characters, A1-style references become just a letter-number combination - if (name.matches("[A-Za-z]+\\d+")) { - String col = name.replaceAll("\\d", ""); - String row = name.replaceAll("[A-Za-z]", ""); - if (CellReference.cellReferenceIsWithinRange(col, row, SpreadsheetVersion.EXCEL97)) { // todo: is EXCEL97 correct? sounds wrong... - throw new IllegalArgumentException("Invalid name: '"+name+"': cannot be $A$1-style cell reference"); - } - } - - // Is the name a valid R1C1 cell reference? - if (name.matches("[Rr]\\d+[Cc]\\d+")) { - throw new IllegalArgumentException("Invalid name: '"+name+"': cannot be R1C1-style cell reference"); - } - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFObjectData.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFObjectData.java deleted file mode 100644 index 222197941..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFObjectData.java +++ /dev/null @@ -1,220 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.PushbackInputStream; - -import javax.xml.namespace.QName; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.POIXMLException; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.opc.PackageRelationshipTypes; -import org.apache.poi.poifs.filesystem.DirectoryEntry; -import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.ss.usermodel.ObjectData; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.xmlbeans.XmlCursor; -import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps; -import org.openxmlformats.schemas.drawingml.x2006.main.CTOfficeArtExtension; -import org.openxmlformats.schemas.drawingml.x2006.main.CTOfficeArtExtensionList; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPoint2D; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPresetGeometry2D; -import org.openxmlformats.schemas.drawingml.x2006.main.CTShapeProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTransform2D; -import org.openxmlformats.schemas.drawingml.x2006.main.STShapeType; -import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTShape; -import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTShapeNonVisual; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTOleObject; - -/** - * Represents binary object (i.e. OLE) data stored in the file. Eg. A GIF, JPEG etc... - */ -public class XSSFObjectData extends XSSFSimpleShape implements ObjectData { - private static final POILogger LOG = POILogFactory.getLogger(XSSFObjectData.class); - - /** - * A default instance of CTShape used for creating new shapes. - */ - private static CTShape prototype = null; - - private CTOleObject oleObject; - - protected XSSFObjectData(XSSFDrawing drawing, CTShape ctShape) { - super(drawing, ctShape); - } - - /** - * Prototype with the default structure of a new auto-shape. - */ - /** - * Prototype with the default structure of a new auto-shape. - */ - protected static CTShape prototype() { - final String drawNS = "http://schemas.microsoft.com/office/drawing/2010/main"; - - if(prototype == null) { - CTShape shape = CTShape.Factory.newInstance(); - - CTShapeNonVisual nv = shape.addNewNvSpPr(); - CTNonVisualDrawingProps nvp = nv.addNewCNvPr(); - nvp.setId(1); - nvp.setName("Shape 1"); -// nvp.setHidden(true); - CTOfficeArtExtensionList extLst = nvp.addNewExtLst(); - // https://msdn.microsoft.com/en-us/library/dd911027(v=office.12).aspx - CTOfficeArtExtension ext = extLst.addNewExt(); - ext.setUri("{63B3BB69-23CF-44E3-9099-C40C66FF867C}"); - XmlCursor cur = ext.newCursor(); - cur.toEndToken(); - cur.beginElement(new QName(drawNS, "compatExt", "a14")); - cur.insertNamespace("a14", drawNS); - cur.insertAttributeWithValue("spid", "_x0000_s1"); - cur.dispose(); - - nv.addNewCNvSpPr(); - - CTShapeProperties sp = shape.addNewSpPr(); - CTTransform2D t2d = sp.addNewXfrm(); - CTPositiveSize2D p1 = t2d.addNewExt(); - p1.setCx(0); - p1.setCy(0); - CTPoint2D p2 = t2d.addNewOff(); - p2.setX(0); - p2.setY(0); - - CTPresetGeometry2D geom = sp.addNewPrstGeom(); - geom.setPrst(STShapeType.RECT); - geom.addNewAvLst(); - - prototype = shape; - } - return prototype; - } - - - - - @Override - public String getOLE2ClassName() { - return getOleObject().getProgId(); - } - - /** - * @return the CTOleObject associated with the shape - */ - public CTOleObject getOleObject() { - if (oleObject == null) { - long shapeId = getCTShape().getNvSpPr().getCNvPr().getId(); - oleObject = getSheet().readOleObject(shapeId); - if (oleObject == null) { - throw new POIXMLException("Ole object not found in sheet container - it's probably a control element"); - } - } - return oleObject; - } - - @Override - public byte[] getObjectData() throws IOException { - InputStream is = getObjectPart().getInputStream(); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - IOUtils.copy(is, bos); - is.close(); - return bos.toByteArray(); - } - - /** - * @return the package part of the object data - */ - public PackagePart getObjectPart() { - if (!getOleObject().isSetId()) { - throw new POIXMLException("Invalid ole object found in sheet container"); - } - POIXMLDocumentPart pdp = getSheet().getRelationById(getOleObject().getId()); - return (pdp == null) ? null : pdp.getPackagePart(); - } - - @Override - public boolean hasDirectoryEntry() { - InputStream is = null; - try { - is = getObjectPart().getInputStream(); - - // If clearly doesn't do mark/reset, wrap up - if (! is.markSupported()) { - is = new PushbackInputStream(is, 8); - } - - // Ensure that there is at least some data there - byte[] header8 = IOUtils.peekFirst8Bytes(is); - - // Try to create - return NPOIFSFileSystem.hasPOIFSHeader(header8); - } catch (IOException e) { - LOG.log(POILogger.WARN, "can't determine if directory entry exists", e); - return false; - } finally { - IOUtils.closeQuietly(is); - } - } - - @Override - @SuppressWarnings("resource") - public DirectoryEntry getDirectory() throws IOException { - InputStream is = null; - try { - is = getObjectPart().getInputStream(); - return new POIFSFileSystem(is).getRoot(); - } finally { - IOUtils.closeQuietly(is); - } - } - - /** - * The filename of the embedded image - */ - @Override - public String getFileName() { - return getObjectPart().getPartName().getName(); - } - - protected XSSFSheet getSheet() { - return (XSSFSheet)getDrawing().getParent(); - } - - @Override - public XSSFPictureData getPictureData() { - XmlCursor cur = getOleObject().newCursor(); - try { - if (cur.toChild(XSSFRelation.NS_SPREADSHEETML, "objectPr")) { - String blipId = cur.getAttributeText(new QName(PackageRelationshipTypes.CORE_PROPERTIES_ECMA376_NS, "id")); - return (XSSFPictureData)getDrawing().getRelationById(blipId); - } - return null; - } finally { - cur.dispose(); - } - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFOddFooter.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFOddFooter.java deleted file mode 100644 index ca3950f81..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFOddFooter.java +++ /dev/null @@ -1,61 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import org.apache.poi.ss.usermodel.Footer; -import org.apache.poi.xssf.usermodel.extensions.XSSFHeaderFooter; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTHeaderFooter; - -/** - * Odd page footer value. Corresponds to odd printed pages. - * Odd page(s) in the sheet may not be printed, for example, if the print area is specified to be - * a range such that it falls outside an odd page's scope. - * - */ -public class XSSFOddFooter extends XSSFHeaderFooter implements Footer{ - - /** - * Create an instance of XSSFOddFooter from the supplied XML bean - * @see XSSFSheet#getOddFooter() - * @param headerFooter - */ - public XSSFOddFooter(CTHeaderFooter headerFooter) { - super(headerFooter); - } - - /** - * Get the content text representing the footer - * @return text - */ - public String getText() { - return getHeaderFooter().getOddFooter(); - } - - /** - * Set a text for the footer. If null unset the value. - * @see XSSFHeaderFooter to see how to create a string with Header/Footer Formatting Syntax - * @param text - a string representing the footer. - */ - public void setText(String text) { - if(text == null) { - getHeaderFooter().unsetOddFooter(); - } else { - getHeaderFooter().setOddFooter(text); - } - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFOddHeader.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFOddHeader.java deleted file mode 100644 index ba5c1a06f..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFOddHeader.java +++ /dev/null @@ -1,61 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import org.apache.poi.ss.usermodel.Header; -import org.apache.poi.xssf.usermodel.extensions.XSSFHeaderFooter; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTHeaderFooter; - -/** - * Odd page header value. Corresponds to odd printed pages. - * Odd page(s) in the sheet may not be printed, for example, if the print area is specified to be - * a range such that it falls outside an odd page's scope. - * - */ -public class XSSFOddHeader extends XSSFHeaderFooter implements Header{ - - /** - * Create an instance of XSSFOddHeader from the supplied XML bean - * @see XSSFSheet#getOddHeader() - * @param headerFooter - */ - protected XSSFOddHeader(CTHeaderFooter headerFooter) { - super(headerFooter); - } - - /** - * Get the content text representing this header - * @return text - */ - public String getText() { - return getHeaderFooter().getOddHeader(); - } - - /** - * Set a text for the header. If null unset the value - * @see XSSFHeaderFooter to see how to create a string with Header/Footer Formatting Syntax - * @param text - a string representing the header. - */ - public void setText(String text) { - if(text == null) { - getHeaderFooter().unsetOddHeader(); - } else { - getHeaderFooter().setOddHeader(text); - } - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFPatternFormatting.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFPatternFormatting.java deleted file mode 100644 index e23d61ae1..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFPatternFormatting.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -package org.apache.poi.xssf.usermodel; - -import org.apache.poi.ss.usermodel.Color; -import org.apache.poi.ss.usermodel.PatternFormatting; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTFill; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPatternFill; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTColor; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STPatternType; - -/** - * @author Yegor Kozlov - */ -public class XSSFPatternFormatting implements PatternFormatting { - CTFill _fill; - - XSSFPatternFormatting(CTFill fill){ - _fill = fill; - } - - public XSSFColor getFillBackgroundColorColor() { - if(!_fill.isSetPatternFill()) return null; - return new XSSFColor(_fill.getPatternFill().getBgColor()); - } - public XSSFColor getFillForegroundColorColor() { - if(!_fill.isSetPatternFill() || ! _fill.getPatternFill().isSetFgColor()) - return null; - return new XSSFColor(_fill.getPatternFill().getFgColor()); - } - - public short getFillPattern() { - if(!_fill.isSetPatternFill() || !_fill.getPatternFill().isSetPatternType()) return NO_FILL; - - return (short)(_fill.getPatternFill().getPatternType().intValue() - 1); - } - - public short getFillBackgroundColor() { - XSSFColor color = getFillBackgroundColorColor(); - if (color == null) return 0; - return color.getIndexed(); - } - public short getFillForegroundColor() { - XSSFColor color = getFillForegroundColorColor(); - if (color == null) return 0; - return color.getIndexed(); - } - - public void setFillBackgroundColor(Color bg) { - XSSFColor xcolor = XSSFColor.toXSSFColor(bg); - if (xcolor == null) setFillBackgroundColor((CTColor)null); - else setFillBackgroundColor(xcolor.getCTColor()); - } - public void setFillBackgroundColor(short bg) { - CTColor bgColor = CTColor.Factory.newInstance(); - bgColor.setIndexed(bg); - setFillBackgroundColor(bgColor); - } - private void setFillBackgroundColor(CTColor color) { - CTPatternFill ptrn = _fill.isSetPatternFill() ? _fill.getPatternFill() : _fill.addNewPatternFill(); - if (color == null) { - ptrn.unsetBgColor(); - } else { - ptrn.setBgColor(color); - } - } - - public void setFillForegroundColor(Color fg) { - XSSFColor xcolor = XSSFColor.toXSSFColor(fg); - if (xcolor == null) setFillForegroundColor((CTColor)null); - else setFillForegroundColor(xcolor.getCTColor()); - } - public void setFillForegroundColor(short fg) { - CTColor fgColor = CTColor.Factory.newInstance(); - fgColor.setIndexed(fg); - setFillForegroundColor(fgColor); - } - private void setFillForegroundColor(CTColor color) { - CTPatternFill ptrn = _fill.isSetPatternFill() ? _fill.getPatternFill() : _fill.addNewPatternFill(); - if (color == null) { - ptrn.unsetFgColor(); - } else { - ptrn.setFgColor(color); - } - } - - public void setFillPattern(short fp){ - CTPatternFill ptrn = _fill.isSetPatternFill() ? _fill.getPatternFill() : _fill.addNewPatternFill(); - if(fp == NO_FILL) ptrn.unsetPatternType(); - else ptrn.setPatternType(STPatternType.Enum.forInt(fp + 1)); - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFPicture.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFPicture.java deleted file mode 100644 index e4055b3e5..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFPicture.java +++ /dev/null @@ -1,292 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import java.awt.Dimension; -import java.io.IOException; - -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.opc.PackageRelationship; -import org.apache.poi.ss.usermodel.Picture; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.ImageUtils; -import org.apache.poi.util.Internal; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.openxmlformats.schemas.drawingml.x2006.main.CTBlipFillProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps; -import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualPictureProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPoint2D; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPresetGeometry2D; -import org.openxmlformats.schemas.drawingml.x2006.main.CTShapeProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTransform2D; -import org.openxmlformats.schemas.drawingml.x2006.main.STShapeType; -import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTPicture; -import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTPictureNonVisual; - -/** - * Represents a picture shape in a SpreadsheetML drawing. - * - * @author Yegor Kozlov - */ -public final class XSSFPicture extends XSSFShape implements Picture { - private static final POILogger logger = POILogFactory.getLogger(XSSFPicture.class); - - /** - * Column width measured as the number of characters of the maximum digit width of the - * numbers 0, 1, 2, ..., 9 as rendered in the normal style's font. There are 4 pixels of margin - * padding (two on each side), plus 1 pixel padding for the gridlines. - * - * This value is the same for default font in Office 2007 (Calibry) and Office 2003 and earlier (Arial) - */ - // private static float DEFAULT_COLUMN_WIDTH = 9.140625f; - - /** - * A default instance of CTShape used for creating new shapes. - */ - private static CTPicture prototype = null; - - /** - * This object specifies a picture object and all its properties - */ - private CTPicture ctPicture; - - /** - * Construct a new XSSFPicture object. This constructor is called from - * {@link XSSFDrawing#createPicture(XSSFClientAnchor, int)} - * - * @param drawing the XSSFDrawing that owns this picture - */ - protected XSSFPicture(XSSFDrawing drawing, CTPicture ctPicture){ - this.drawing = drawing; - this.ctPicture = ctPicture; - } - - /** - * Returns a prototype that is used to construct new shapes - * - * @return a prototype that is used to construct new shapes - */ - protected static CTPicture prototype(){ - if(prototype == null) { - CTPicture pic = CTPicture.Factory.newInstance(); - CTPictureNonVisual nvpr = pic.addNewNvPicPr(); - CTNonVisualDrawingProps nvProps = nvpr.addNewCNvPr(); - nvProps.setId(1); - nvProps.setName("Picture 1"); - nvProps.setDescr("Picture"); - CTNonVisualPictureProperties nvPicProps = nvpr.addNewCNvPicPr(); - nvPicProps.addNewPicLocks().setNoChangeAspect(true); - - CTBlipFillProperties blip = pic.addNewBlipFill(); - blip.addNewBlip().setEmbed(""); - blip.addNewStretch().addNewFillRect(); - - CTShapeProperties sppr = pic.addNewSpPr(); - CTTransform2D t2d = sppr.addNewXfrm(); - CTPositiveSize2D ext = t2d.addNewExt(); - //should be original picture width and height expressed in EMUs - ext.setCx(0); - ext.setCy(0); - - CTPoint2D off = t2d.addNewOff(); - off.setX(0); - off.setY(0); - - CTPresetGeometry2D prstGeom = sppr.addNewPrstGeom(); - prstGeom.setPrst(STShapeType.RECT); - prstGeom.addNewAvLst(); - - prototype = pic; - } - return prototype; - } - - /** - * Link this shape with the picture data - * - * @param rel relationship referring the picture data - */ - protected void setPictureReference(PackageRelationship rel){ - ctPicture.getBlipFill().getBlip().setEmbed(rel.getId()); - } - - /** - * Return the underlying CTPicture bean that holds all properties for this picture - * - * @return the underlying CTPicture bean - */ - @Internal - public CTPicture getCTPicture(){ - return ctPicture; - } - - /** - * Reset the image to the dimension of the embedded image - * - * @see #resize(double, double) - */ - public void resize(){ - resize(Double.MAX_VALUE); - } - - /** - * Resize the image proportionally. - * - * @see #resize(double, double) - */ - public void resize(double scale) { - resize(scale, scale); - } - - /** - * Resize the image relatively to its current size. - *

    - * Please note, that this method works correctly only for workbooks - * with the default font size (Calibri 11pt for .xlsx). - * If the default font is changed the resized image can be streched vertically or horizontally. - *

    - *

    - * resize(1.0,1.0) keeps the original size,
    - * resize(0.5,0.5) resize to 50% of the original,
    - * resize(2.0,2.0) resizes to 200% of the original.
    - * resize({@link Double#MAX_VALUE},{@link Double#MAX_VALUE}) resizes to the dimension of the embedded image. - *

    - * - * @param scaleX the amount by which the image width is multiplied relative to the original width, - * when set to {@link java.lang.Double#MAX_VALUE} the width of the embedded image is used - * @param scaleY the amount by which the image height is multiplied relative to the original height, - * when set to {@link java.lang.Double#MAX_VALUE} the height of the embedded image is used - */ - public void resize(double scaleX, double scaleY){ - XSSFClientAnchor anchor = getClientAnchor(); - - XSSFClientAnchor pref = getPreferredSize(scaleX,scaleY); - - int row2 = anchor.getRow1() + (pref.getRow2() - pref.getRow1()); - int col2 = anchor.getCol1() + (pref.getCol2() - pref.getCol1()); - - anchor.setCol2(col2); - // anchor.setDx1(0); - anchor.setDx2(pref.getDx2()); - - anchor.setRow2(row2); - // anchor.setDy1(0); - anchor.setDy2(pref.getDy2()); - } - - /** - * Calculate the preferred size for this picture. - * - * @return XSSFClientAnchor with the preferred size for this image - */ - public XSSFClientAnchor getPreferredSize(){ - return getPreferredSize(1); - } - - /** - * Calculate the preferred size for this picture. - * - * @param scale the amount by which image dimensions are multiplied relative to the original size. - * @return XSSFClientAnchor with the preferred size for this image - */ - public XSSFClientAnchor getPreferredSize(double scale){ - return getPreferredSize(scale, scale); - } - - /** - * Calculate the preferred size for this picture. - * - * @param scaleX the amount by which image width is multiplied relative to the original width. - * @param scaleY the amount by which image height is multiplied relative to the original height. - * @return XSSFClientAnchor with the preferred size for this image - */ - public XSSFClientAnchor getPreferredSize(double scaleX, double scaleY){ - Dimension dim = ImageUtils.setPreferredSize(this, scaleX, scaleY); - CTPositiveSize2D size2d = ctPicture.getSpPr().getXfrm().getExt(); - size2d.setCx((int)dim.getWidth()); - size2d.setCy((int)dim.getHeight()); - return getClientAnchor(); - } - - /** - * Return the dimension of this image - * - * @param part the package part holding raw picture data - * @param type type of the picture: {@link Workbook#PICTURE_TYPE_JPEG}, - * {@link Workbook#PICTURE_TYPE_PNG} or {@link Workbook#PICTURE_TYPE_DIB} - * - * @return image dimension in pixels - */ - protected static Dimension getImageDimension(PackagePart part, int type){ - try { - return ImageUtils.getImageDimension(part.getInputStream(), type); - } catch (IOException e){ - //return a "singulariry" if ImageIO failed to read the image - logger.log(POILogger.WARN, e); - return new Dimension(); - } - } - - /** - * Return the dimension of the embedded image in pixel - * - * @return image dimension in pixels - */ - public Dimension getImageDimension() { - XSSFPictureData picData = getPictureData(); - return getImageDimension(picData.getPackagePart(), picData.getPictureType()); - } - - /** - * Return picture data for this shape - * - * @return picture data for this shape - */ - public XSSFPictureData getPictureData() { - String blipId = ctPicture.getBlipFill().getBlip().getEmbed(); - return (XSSFPictureData)getDrawing().getRelationById(blipId); - } - - protected CTShapeProperties getShapeProperties(){ - return ctPicture.getSpPr(); - } - - /** - * @return the anchor that is used by this shape. - */ - @Override - public XSSFClientAnchor getClientAnchor() { - XSSFAnchor a = getAnchor(); - return (a instanceof XSSFClientAnchor) ? (XSSFClientAnchor)a : null; - } - - /** - * @return the sheet which contains the picture shape - */ - @Override - public XSSFSheet getSheet() { - return (XSSFSheet)getDrawing().getParent(); - } - - @Override - public String getShapeName() { - return ctPicture.getNvPicPr().getCNvPr().getName(); - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFPictureData.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFPictureData.java deleted file mode 100644 index 4a47bd7af..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFPictureData.java +++ /dev/null @@ -1,140 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import java.io.IOException; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.POIXMLException; -import org.apache.poi.POIXMLRelation; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.ss.usermodel.PictureData; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.util.IOUtils; - -/** - * Raw picture data, normally attached to a SpreadsheetML Drawing. - * As a rule, pictures are stored in the /xl/media/ part of a SpreadsheetML package. - */ -public class XSSFPictureData extends POIXMLDocumentPart implements PictureData { - - /** - * Relationships for each known picture type - */ - protected static final POIXMLRelation[] RELATIONS; - static { - RELATIONS = new POIXMLRelation[13]; - RELATIONS[Workbook.PICTURE_TYPE_EMF] = XSSFRelation.IMAGE_EMF; - RELATIONS[Workbook.PICTURE_TYPE_WMF] = XSSFRelation.IMAGE_WMF; - RELATIONS[Workbook.PICTURE_TYPE_PICT] = XSSFRelation.IMAGE_PICT; - RELATIONS[Workbook.PICTURE_TYPE_JPEG] = XSSFRelation.IMAGE_JPEG; - RELATIONS[Workbook.PICTURE_TYPE_PNG] = XSSFRelation.IMAGE_PNG; - RELATIONS[Workbook.PICTURE_TYPE_DIB] = XSSFRelation.IMAGE_DIB; - RELATIONS[XSSFWorkbook.PICTURE_TYPE_GIF] = XSSFRelation.IMAGE_GIF; - RELATIONS[XSSFWorkbook.PICTURE_TYPE_TIFF] = XSSFRelation.IMAGE_TIFF; - RELATIONS[XSSFWorkbook.PICTURE_TYPE_EPS] = XSSFRelation.IMAGE_EPS; - RELATIONS[XSSFWorkbook.PICTURE_TYPE_BMP] = XSSFRelation.IMAGE_BMP; - RELATIONS[XSSFWorkbook.PICTURE_TYPE_WPG] = XSSFRelation.IMAGE_WPG; - } - - /** - * Create a new XSSFPictureData node - * - * @see org.apache.poi.xssf.usermodel.XSSFWorkbook#addPicture(byte[], int) - */ - protected XSSFPictureData() { - super(); - } - - /** - * Construct XSSFPictureData from a package part - * - * @param part the package part holding the drawing data, - * - * @since POI 3.14-Beta1 - */ - protected XSSFPictureData(PackagePart part) { - super(part); - } - - /** - * Gets the picture data as a byte array. - *

    - * Note, that this call might be expensive since all the picture data is copied into a temporary byte array. - * You can grab the picture data directly from the underlying package part as follows: - *
    - * - * InputStream is = getPackagePart().getInputStream(); - * - *

    - * - * @return the picture data. - */ - public byte[] getData() { - try { - return IOUtils.toByteArray(getPackagePart().getInputStream()); - } catch(IOException e) { - throw new POIXMLException(e); - } - } - - /** - * Suggests a file extension for this image. - * - * @return the file extension. - */ - public String suggestFileExtension() { - return getPackagePart().getPartName().getExtension(); - } - - /** - * Return an integer constant that specifies type of this picture - * - * @return an integer constant that specifies type of this picture - * @see org.apache.poi.ss.usermodel.Workbook#PICTURE_TYPE_EMF - * @see org.apache.poi.ss.usermodel.Workbook#PICTURE_TYPE_WMF - * @see org.apache.poi.ss.usermodel.Workbook#PICTURE_TYPE_PICT - * @see org.apache.poi.ss.usermodel.Workbook#PICTURE_TYPE_JPEG - * @see org.apache.poi.ss.usermodel.Workbook#PICTURE_TYPE_PNG - * @see org.apache.poi.ss.usermodel.Workbook#PICTURE_TYPE_DIB - */ - public int getPictureType(){ - String contentType = getPackagePart().getContentType(); - for (int i = 0; i < RELATIONS.length; i++) { - if(RELATIONS[i] == null) continue; - - if(RELATIONS[i].getContentType().equals(contentType)){ - return i; - } - } - return 0; - } - - public String getMimeType() { - return getPackagePart().getContentType(); - } - - /** - * *PictureData objects store the actual content in the part directly without keeping a - * copy like all others therefore we need to handle them differently. - */ - @Override - protected void prepareForCommit() { - // do not clear the part here - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFPivotCache.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFPivotCache.java deleted file mode 100644 index 74c5861c2..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFPivotCache.java +++ /dev/null @@ -1,77 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel; - -import static org.apache.poi.POIXMLTypeLoader.DEFAULT_XML_OPTIONS; - -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.util.Beta; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlOptions; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPivotCache; - -public class XSSFPivotCache extends POIXMLDocumentPart { - - private CTPivotCache ctPivotCache; - - @Beta - public XSSFPivotCache(){ - super(); - ctPivotCache = CTPivotCache.Factory.newInstance(); - } - - @Beta - public XSSFPivotCache(CTPivotCache ctPivotCache) { - super(); - this.ctPivotCache = ctPivotCache; - } - - /** - * Creates n XSSFPivotCache representing the given package part and relationship. - * Should only be called when reading in an existing file. - * - * @param part - The package part that holds xml data representing this pivot cache definition. - * - * @since POI 3.14-Beta1 - */ - @Beta - protected XSSFPivotCache(PackagePart part) throws IOException { - super(part); - readFrom(part.getInputStream()); - } - - @Beta - protected void readFrom(InputStream is) throws IOException { - try { - XmlOptions options = new XmlOptions(DEFAULT_XML_OPTIONS); - //Removing root element - options.setLoadReplaceDocumentElement(null); - ctPivotCache = CTPivotCache.Factory.parse(is, options); - } catch (XmlException e) { - throw new IOException(e.getLocalizedMessage()); - } - } - - @Beta - public CTPivotCache getCTPivotCache() { - return ctPivotCache; - } -} \ No newline at end of file diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFPivotCacheDefinition.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFPivotCacheDefinition.java deleted file mode 100644 index 5066ff7d0..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFPivotCacheDefinition.java +++ /dev/null @@ -1,189 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel; - -import static org.apache.poi.POIXMLTypeLoader.DEFAULT_XML_OPTIONS; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.Date; - -import javax.xml.namespace.QName; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.Name; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.AreaReference; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.util.Beta; -import org.apache.poi.util.Internal; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlOptions; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCacheField; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCacheFields; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPivotCacheDefinition; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheetSource; - -public class XSSFPivotCacheDefinition extends POIXMLDocumentPart{ - - private CTPivotCacheDefinition ctPivotCacheDefinition; - - @Beta - public XSSFPivotCacheDefinition(){ - super(); - ctPivotCacheDefinition = CTPivotCacheDefinition.Factory.newInstance(); - createDefaultValues(); - } - - /** - * Creates an XSSFPivotCacheDefintion representing the given package part and relationship. - * Should only be called when reading in an existing file. - * - * @param part - The package part that holds xml data representing this pivot cache definition. - * - * @since POI 3.14-Beta1 - */ - @Beta - protected XSSFPivotCacheDefinition(PackagePart part) throws IOException { - super(part); - readFrom(part.getInputStream()); - } - - @Beta - public void readFrom(InputStream is) throws IOException { - try { - XmlOptions options = new XmlOptions(DEFAULT_XML_OPTIONS); - //Removing root element - options.setLoadReplaceDocumentElement(null); - ctPivotCacheDefinition = CTPivotCacheDefinition.Factory.parse(is, options); - } catch (XmlException e) { - throw new IOException(e.getLocalizedMessage(), e); - } - } - - @Beta - @Internal - public CTPivotCacheDefinition getCTPivotCacheDefinition() { - return ctPivotCacheDefinition; - } - - @Beta - private void createDefaultValues() { - ctPivotCacheDefinition.setCreatedVersion(XSSFPivotTable.CREATED_VERSION); - ctPivotCacheDefinition.setMinRefreshableVersion(XSSFPivotTable.MIN_REFRESHABLE_VERSION); - ctPivotCacheDefinition.setRefreshedVersion(XSSFPivotTable.UPDATED_VERSION); - ctPivotCacheDefinition.setRefreshedBy("Apache POI"); - ctPivotCacheDefinition.setRefreshedDate(new Date().getTime()); - ctPivotCacheDefinition.setRefreshOnLoad(true); - } - - @Beta - @Override - protected void commit() throws IOException { - PackagePart part = getPackagePart(); - OutputStream out = part.getOutputStream(); - XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS); - //Sets the pivotCacheDefinition tag - xmlOptions.setSaveSyntheticDocumentElement(new QName(CTPivotCacheDefinition.type.getName(). - getNamespaceURI(), "pivotCacheDefinition")); - ctPivotCacheDefinition.save(out, xmlOptions); - out.close(); - } - - /** - * Find the 2D base data area for the pivot table, either from its direct reference or named table/range. - * @return AreaReference representing the current area defined by the pivot table - * @throws IllegalArgumentException if the ref attribute is not contiguous or the name attribute is not found. - */ - @Beta - public AreaReference getPivotArea(Workbook wb) throws IllegalArgumentException { - final CTWorksheetSource wsSource = ctPivotCacheDefinition.getCacheSource().getWorksheetSource(); - - final String ref = wsSource.getRef(); - final String name = wsSource.getName(); - - if (ref == null && name == null) { - throw new IllegalArgumentException("Pivot cache must reference an area, named range, or table."); - } - - // this is the XML format, so tell the reference that. - if (ref != null) { - return new AreaReference(ref, SpreadsheetVersion.EXCEL2007); - } - - assert (name != null); - - // named range or table? - final Name range = wb.getName(name); - if (range != null) { - return new AreaReference(range.getRefersToFormula(), SpreadsheetVersion.EXCEL2007); - } - - // not a named range, check for a table. - // do this second, as tables are sheet-specific, but named ranges are not, and may not have a sheet name given. - final XSSFSheet sheet = (XSSFSheet) wb.getSheet(wsSource.getSheet()); - for (XSSFTable table : sheet.getTables()) { - // TODO: case-sensitive? - if (name.equals(table.getName())) { - return new AreaReference(table.getStartCellReference(), table.getEndCellReference()); - } - } - - throw new IllegalArgumentException("Name '" + name + "' was not found."); - } - - /** - * Generates a cache field for each column in the reference area for the pivot table. - * @param sheet The sheet where the data i collected from - */ - @Beta - protected void createCacheFields(Sheet sheet) { - //Get values for start row, start and end column - AreaReference ar = getPivotArea(sheet.getWorkbook()); - CellReference firstCell = ar.getFirstCell(); - CellReference lastCell = ar.getLastCell(); - int columnStart = firstCell.getCol(); - int columnEnd = lastCell.getCol(); - Row row = sheet.getRow(firstCell.getRow()); - CTCacheFields cFields; - if(ctPivotCacheDefinition.getCacheFields() != null) { - cFields = ctPivotCacheDefinition.getCacheFields(); - } else { - cFields = ctPivotCacheDefinition.addNewCacheFields(); - } - //For each column, create a cache field and give it en empty sharedItems - for(int i=columnStart; i<=columnEnd; i++) { - CTCacheField cf = cFields.addNewCacheField(); - if(i==columnEnd){ - cFields.setCount(cFields.sizeOfCacheFieldArray()); - } - //General number format - cf.setNumFmtId(0); - Cell cell = row.getCell(i); - cell.setCellType(CellType.STRING); - cf.setName(row.getCell(i).getStringCellValue()); - cf.addNewSharedItems(); - } - } -} \ No newline at end of file diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFPivotCacheRecords.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFPivotCacheRecords.java deleted file mode 100644 index e084106c8..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFPivotCacheRecords.java +++ /dev/null @@ -1,88 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel; - -import static org.apache.poi.POIXMLTypeLoader.DEFAULT_XML_OPTIONS; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import javax.xml.namespace.QName; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.util.Beta; -import org.apache.poi.util.Internal; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlOptions; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPivotCacheRecords; - -public class XSSFPivotCacheRecords extends POIXMLDocumentPart { - private CTPivotCacheRecords ctPivotCacheRecords; - - @Beta - public XSSFPivotCacheRecords() { - super(); - ctPivotCacheRecords = CTPivotCacheRecords.Factory.newInstance(); - } - - /** - * Creates an XSSFPivotCacheRecords representing the given package part and relationship. - * Should only be called when reading in an existing file. - * - * @param part - The package part that holds xml data representing this pivot cache records. - * - * @since POI 3.14-Beta1 - */ - @Beta - protected XSSFPivotCacheRecords(PackagePart part) throws IOException { - super(part); - readFrom(part.getInputStream()); - } - - @Beta - protected void readFrom(InputStream is) throws IOException { - try { - XmlOptions options = new XmlOptions(DEFAULT_XML_OPTIONS); - //Removing root element - options.setLoadReplaceDocumentElement(null); - ctPivotCacheRecords = CTPivotCacheRecords.Factory.parse(is, options); - } catch (XmlException e) { - throw new IOException(e.getLocalizedMessage()); - } - } - - @Beta - @Internal - public CTPivotCacheRecords getCtPivotCacheRecords() { - return ctPivotCacheRecords; - } - - @Beta - @Override - protected void commit() throws IOException { - PackagePart part = getPackagePart(); - OutputStream out = part.getOutputStream(); - XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS); - //Sets the pivotCacheDefinition tag - xmlOptions.setSaveSyntheticDocumentElement(new QName(CTPivotCacheRecords.type.getName(). - getNamespaceURI(), "pivotCacheRecords")); - ctPivotCacheRecords.save(out, xmlOptions); - out.close(); - } -} \ No newline at end of file diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFPivotTable.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFPivotTable.java deleted file mode 100644 index 6f9009de2..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFPivotTable.java +++ /dev/null @@ -1,488 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel; - -import static org.apache.poi.POIXMLTypeLoader.DEFAULT_XML_OPTIONS; - -import javax.xml.namespace.QName; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.DataConsolidateFunction; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.AreaReference; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.util.Beta; -import org.apache.poi.util.Internal; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlOptions; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCacheSource; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTColFields; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTDataField; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTDataFields; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTField; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTItems; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTLocation; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPageField; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPageFields; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPivotCacheDefinition; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPivotField; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPivotFields; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPivotTableDefinition; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPivotTableStyle; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRowFields; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheetSource; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STAxis; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STDataConsolidateFunction; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STItemType; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STSourceType; - -public class XSSFPivotTable extends POIXMLDocumentPart { - - protected static final short CREATED_VERSION = 3; - protected static final short MIN_REFRESHABLE_VERSION = 3; - protected static final short UPDATED_VERSION = 3; - - private CTPivotTableDefinition pivotTableDefinition; - private XSSFPivotCacheDefinition pivotCacheDefinition; - private XSSFPivotCache pivotCache; - private XSSFPivotCacheRecords pivotCacheRecords; - private Sheet parentSheet; - private Sheet dataSheet; - - @Beta - protected XSSFPivotTable() { - super(); - pivotTableDefinition = CTPivotTableDefinition.Factory.newInstance(); - pivotCache = new XSSFPivotCache(); - pivotCacheDefinition = new XSSFPivotCacheDefinition(); - pivotCacheRecords = new XSSFPivotCacheRecords(); - } - - /** - * Creates an XSSFPivotTable representing the given package part and relationship. - * Should only be called when reading in an existing file. - * - * @param part - The package part that holds xml data representing this pivot table. - * - * @since POI 3.14-Beta1 - */ - @Beta - protected XSSFPivotTable(PackagePart part) throws IOException { - super(part); - readFrom(part.getInputStream()); - } - - @Beta - public void readFrom(InputStream is) throws IOException { - try { - XmlOptions options = new XmlOptions(DEFAULT_XML_OPTIONS); - //Removing root element - options.setLoadReplaceDocumentElement(null); - pivotTableDefinition = CTPivotTableDefinition.Factory.parse(is, options); - } catch (XmlException e) { - throw new IOException(e.getLocalizedMessage()); - } - } - - @Beta - public void setPivotCache(XSSFPivotCache pivotCache) { - this.pivotCache = pivotCache; - } - - @Beta - public XSSFPivotCache getPivotCache() { - return pivotCache; - } - - @Beta - public Sheet getParentSheet() { - return parentSheet; - } - - @Beta - public void setParentSheet(XSSFSheet parentSheet) { - this.parentSheet = parentSheet; - } - - @Beta - @Internal - public CTPivotTableDefinition getCTPivotTableDefinition() { - return pivotTableDefinition; - } - - @Beta - @Internal - public void setCTPivotTableDefinition(CTPivotTableDefinition pivotTableDefinition) { - this.pivotTableDefinition = pivotTableDefinition; - } - - @Beta - public XSSFPivotCacheDefinition getPivotCacheDefinition() { - return pivotCacheDefinition; - } - - @Beta - public void setPivotCacheDefinition(XSSFPivotCacheDefinition pivotCacheDefinition) { - this.pivotCacheDefinition = pivotCacheDefinition; - } - - @Beta - public XSSFPivotCacheRecords getPivotCacheRecords() { - return pivotCacheRecords; - } - - @Beta - public void setPivotCacheRecords(XSSFPivotCacheRecords pivotCacheRecords) { - this.pivotCacheRecords = pivotCacheRecords; - } - - @Beta - public Sheet getDataSheet() { - return dataSheet; - } - - @Beta - private void setDataSheet(Sheet dataSheet) { - this.dataSheet = dataSheet; - } - - @Beta - @Override - protected void commit() throws IOException { - XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS); - //Sets the pivotTableDefinition tag - xmlOptions.setSaveSyntheticDocumentElement(new QName(CTPivotTableDefinition.type.getName(). - getNamespaceURI(), "pivotTableDefinition")); - PackagePart part = getPackagePart(); - OutputStream out = part.getOutputStream(); - pivotTableDefinition.save(out, xmlOptions); - out.close(); - } - - /** - * Set default values for the table definition. - */ - @Beta - protected void setDefaultPivotTableDefinition() { - //Not more than one until more created - pivotTableDefinition.setMultipleFieldFilters(false); - //Indentation increment for compact rows - pivotTableDefinition.setIndent(0); - //The pivot version which created the pivot cache set to default value - pivotTableDefinition.setCreatedVersion(CREATED_VERSION); - //Minimun version required to update the pivot cache - pivotTableDefinition.setMinRefreshableVersion(MIN_REFRESHABLE_VERSION); - //Version of the application which "updated the spreadsheet last" - pivotTableDefinition.setUpdatedVersion(UPDATED_VERSION); - //Titles shown at the top of each page when printed - pivotTableDefinition.setItemPrintTitles(true); - //Set autoformat properties - pivotTableDefinition.setUseAutoFormatting(true); - pivotTableDefinition.setApplyNumberFormats(false); - pivotTableDefinition.setApplyWidthHeightFormats(true); - pivotTableDefinition.setApplyAlignmentFormats(false); - pivotTableDefinition.setApplyPatternFormats(false); - pivotTableDefinition.setApplyFontFormats(false); - pivotTableDefinition.setApplyBorderFormats(false); - pivotTableDefinition.setCacheId(pivotCache.getCTPivotCache().getCacheId()); - pivotTableDefinition.setName("PivotTable"+pivotTableDefinition.getCacheId()); - pivotTableDefinition.setDataCaption("Values"); - - //Set the default style for the pivot table - CTPivotTableStyle style = pivotTableDefinition.addNewPivotTableStyleInfo(); - style.setName("PivotStyleLight16"); - style.setShowLastColumn(true); - style.setShowColStripes(false); - style.setShowRowStripes(false); - style.setShowColHeaders(true); - style.setShowRowHeaders(true); - } - - protected AreaReference getPivotArea() { - final Workbook wb = getDataSheet().getWorkbook(); - AreaReference pivotArea = getPivotCacheDefinition().getPivotArea(wb); - return pivotArea; - } - - /** - * Verify column index (relative to first column in pivot area) is within the - * pivot area - * - * @param columnIndex - * @throws IndexOutOfBoundsException - */ - private void checkColumnIndex(int columnIndex) throws IndexOutOfBoundsException { - AreaReference pivotArea = getPivotArea(); - int size = pivotArea.getLastCell().getCol() - pivotArea.getFirstCell().getCol() + 1; - - if (columnIndex < 0 || columnIndex >= size) { - throw new IndexOutOfBoundsException("Column Index: " + columnIndex + ", Size: " + size); - } - } - - /** - * Add a row label using data from the given column. - * @param columnIndex the index of the source column to be used as row label. - * {@code columnIndex} is 0-based indexed and relative to the first column in the source. - */ - @Beta - public void addRowLabel(int columnIndex) { - checkColumnIndex(columnIndex); - - AreaReference pivotArea = getPivotArea(); - final int lastRowIndex = pivotArea.getLastCell().getRow() - pivotArea.getFirstCell().getRow(); - CTPivotFields pivotFields = pivotTableDefinition.getPivotFields(); - - CTPivotField pivotField = CTPivotField.Factory.newInstance(); - CTItems items = pivotField.addNewItems(); - - pivotField.setAxis(STAxis.AXIS_ROW); - pivotField.setShowAll(false); - for (int i = 0; i <= lastRowIndex; i++) { - items.addNewItem().setT(STItemType.DEFAULT); - } - items.setCount(items.sizeOfItemArray()); - pivotFields.setPivotFieldArray(columnIndex, pivotField); - - CTRowFields rowFields; - if(pivotTableDefinition.getRowFields() != null) { - rowFields = pivotTableDefinition.getRowFields(); - } else { - rowFields = pivotTableDefinition.addNewRowFields(); - } - - rowFields.addNewField().setX(columnIndex); - rowFields.setCount(rowFields.sizeOfFieldArray()); - } - - @Beta - public List getRowLabelColumns() { - if (pivotTableDefinition.getRowFields() != null) { - List columnIndexes = new ArrayList(); - for (CTField f : pivotTableDefinition.getRowFields().getFieldArray()) { - columnIndexes.add(f.getX()); - } - return columnIndexes; - } else { - return Collections.emptyList(); - } - } - - /** - * Add a column label using data from the given column and specified function - * @param columnIndex the index of the source column to be used as column label. - * {@code columnIndex} is 0-based indexed and relative to the first column in the source. - * @param function the function to be used on the data - * The following functions exists: - * Sum, Count, Average, Max, Min, Product, Count numbers, StdDev, StdDevp, Var, Varp - * @param valueFieldName the name of pivot table value field - */ - @Beta - public void addColumnLabel(DataConsolidateFunction function, int columnIndex, String valueFieldName) { - checkColumnIndex(columnIndex); - - addDataColumn(columnIndex, true); - addDataField(function, columnIndex, valueFieldName); - - // colfield should be added for the second one. - if (pivotTableDefinition.getDataFields().getCount() == 2) { - CTColFields colFields; - if(pivotTableDefinition.getColFields() != null) { - colFields = pivotTableDefinition.getColFields(); - } else { - colFields = pivotTableDefinition.addNewColFields(); - } - colFields.addNewField().setX(-2); - colFields.setCount(colFields.sizeOfFieldArray()); - } - } - - /** - * Add a column label using data from the given column and specified function - * @param columnIndex the index of the source column to be used as column label - * {@code columnIndex} is 0-based indexed and relative to the first column in the source.. - * @param function the function to be used on the data - * The following functions exists: - * Sum, Count, Average, Max, Min, Product, Count numbers, StdDev, StdDevp, Var, Varp - */ - @Beta - public void addColumnLabel(DataConsolidateFunction function, int columnIndex) { - addColumnLabel(function, columnIndex, function.getName()); - } - - /** - * Add data field with data from the given column and specified function. - * @param function the function to be used on the data - * The following functions exists: - * Sum, Count, Average, Max, Min, Product, Count numbers, StdDev, StdDevp, Var, Varp - * @param columnIndex the index of the column to be used as column label. - * @param valueFieldName the name of pivot table value field - */ - @Beta - private void addDataField(DataConsolidateFunction function, int columnIndex, String valueFieldName) { - checkColumnIndex(columnIndex); - - AreaReference pivotArea = getPivotArea(); - - CTDataFields dataFields; - if(pivotTableDefinition.getDataFields() != null) { - dataFields = pivotTableDefinition.getDataFields(); - } else { - dataFields = pivotTableDefinition.addNewDataFields(); - } - CTDataField dataField = dataFields.addNewDataField(); - dataField.setSubtotal(STDataConsolidateFunction.Enum.forInt(function.getValue())); - Cell cell = getDataSheet().getRow(pivotArea.getFirstCell().getRow()) - .getCell(pivotArea.getFirstCell().getCol() + columnIndex); - cell.setCellType(CellType.STRING); - dataField.setName(valueFieldName); - dataField.setFld(columnIndex); - dataFields.setCount(dataFields.sizeOfDataFieldArray()); - } - - /** - * Add column containing data from the referenced area. - * @param columnIndex the index of the column containing the data - * @param isDataField true if the data should be displayed in the pivot table. - */ - @Beta - public void addDataColumn(int columnIndex, boolean isDataField) { - checkColumnIndex(columnIndex); - - CTPivotFields pivotFields = pivotTableDefinition.getPivotFields(); - CTPivotField pivotField = CTPivotField.Factory.newInstance(); - - pivotField.setDataField(isDataField); - pivotField.setShowAll(false); - pivotFields.setPivotFieldArray(columnIndex, pivotField); - } - - /** - * Add filter for the column with the corresponding index and cell value - * @param columnIndex index of column to filter on - */ - @Beta - public void addReportFilter(int columnIndex) { - checkColumnIndex(columnIndex); - - AreaReference pivotArea = getPivotArea(); - int lastRowIndex = pivotArea.getLastCell().getRow() - pivotArea.getFirstCell().getRow(); - - CTPivotFields pivotFields = pivotTableDefinition.getPivotFields(); - - CTPivotField pivotField = CTPivotField.Factory.newInstance(); - CTItems items = pivotField.addNewItems(); - - pivotField.setAxis(STAxis.AXIS_PAGE); - pivotField.setShowAll(false); - for(int i = 0; i <= lastRowIndex; i++) { - items.addNewItem().setT(STItemType.DEFAULT); - } - items.setCount(items.sizeOfItemArray()); - pivotFields.setPivotFieldArray(columnIndex, pivotField); - - CTPageFields pageFields; - if (pivotTableDefinition.getPageFields()!= null) { - pageFields = pivotTableDefinition.getPageFields(); - //Another filter has already been created - pivotTableDefinition.setMultipleFieldFilters(true); - } else { - pageFields = pivotTableDefinition.addNewPageFields(); - } - CTPageField pageField = pageFields.addNewPageField(); - pageField.setHier(-1); - pageField.setFld(columnIndex); - - pageFields.setCount(pageFields.sizeOfPageFieldArray()); - pivotTableDefinition.getLocation().setColPageCount(pageFields.getCount()); - } - - /** - * Creates cacheSource and workSheetSource for pivot table and sets the source reference as well assets the location of the pivot table - * @param position Position for pivot table in sheet - * @param sourceSheet Sheet where the source will be collected from - * @param refConfig an configurator that knows how to configure pivot table references - */ - @Beta - protected void createSourceReferences(CellReference position, Sheet sourceSheet, PivotTableReferenceConfigurator refConfig){ - - //Get cell one to the right and one down from position, add both to AreaReference and set pivot table location. - AreaReference destination = new AreaReference(position, new CellReference(position.getRow()+1, position.getCol()+1)); - - CTLocation location; - if(pivotTableDefinition.getLocation() == null) { - location = pivotTableDefinition.addNewLocation(); - location.setFirstDataCol(1); - location.setFirstDataRow(1); - location.setFirstHeaderRow(1); - } else { - location = pivotTableDefinition.getLocation(); - } - location.setRef(destination.formatAsString()); - pivotTableDefinition.setLocation(location); - - //Set source for the pivot table - CTPivotCacheDefinition cacheDef = getPivotCacheDefinition().getCTPivotCacheDefinition(); - CTCacheSource cacheSource = cacheDef.addNewCacheSource(); - cacheSource.setType(STSourceType.WORKSHEET); - CTWorksheetSource worksheetSource = cacheSource.addNewWorksheetSource(); - worksheetSource.setSheet(sourceSheet.getSheetName()); - setDataSheet(sourceSheet); - - refConfig.configureReference(worksheetSource); - if (worksheetSource.getName() == null && worksheetSource.getRef() == null) throw new IllegalArgumentException("Pivot table source area reference or name must be specified."); - } - - @Beta - protected void createDefaultDataColumns() { - CTPivotFields pivotFields; - if (pivotTableDefinition.getPivotFields() != null) { - pivotFields = pivotTableDefinition.getPivotFields(); - } else { - pivotFields = pivotTableDefinition.addNewPivotFields(); - } - AreaReference sourceArea = getPivotArea(); - int firstColumn = sourceArea.getFirstCell().getCol(); - int lastColumn = sourceArea.getLastCell().getCol(); - CTPivotField pivotField; - for(int i = firstColumn; i<=lastColumn; i++) { - pivotField = pivotFields.addNewPivotField(); - pivotField.setDataField(false); - pivotField.setShowAll(false); - } - pivotFields.setCount(pivotFields.sizeOfPivotFieldArray()); - } - - protected static interface PivotTableReferenceConfigurator { - - /** - * Configure the name or area reference for the pivot table - * @param wsSource CTWorksheetSource that needs the pivot source reference assignment - */ - public void configureReference(CTWorksheetSource wsSource); - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFPrintSetup.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFPrintSetup.java deleted file mode 100644 index 43b8c5a21..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFPrintSetup.java +++ /dev/null @@ -1,468 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import org.apache.poi.POIXMLException; -import org.apache.poi.ss.usermodel.PageOrder; -import org.apache.poi.ss.usermodel.PaperSize; -import org.apache.poi.ss.usermodel.PrintCellComments; -import org.apache.poi.ss.usermodel.PrintOrientation; -import org.apache.poi.ss.usermodel.PrintSetup; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPageMargins; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPageSetup; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STCellComments; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STOrientation; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STPageOrder; - - -/** - * Page setup and page margins settings for the worksheet. - */ -public class XSSFPrintSetup implements PrintSetup { - private CTWorksheet ctWorksheet; - private CTPageSetup pageSetup; - private CTPageMargins pageMargins; - - protected XSSFPrintSetup(CTWorksheet worksheet) { - this.ctWorksheet = worksheet; - - if(ctWorksheet.isSetPageSetup()) { - this.pageSetup = ctWorksheet.getPageSetup(); - } else { - this.pageSetup = ctWorksheet.addNewPageSetup(); - } - if(ctWorksheet.isSetPageMargins()) { - this.pageMargins = ctWorksheet.getPageMargins(); - } else { - this.pageMargins = ctWorksheet.addNewPageMargins(); - } - } - - /** - * Set the paper size. - * - * @param size the paper size. - */ - public void setPaperSize(short size) { - pageSetup.setPaperSize(size); - } - - /** - * Set the paper size as enum value. - * - * @param size value for the paper size. - */ - public void setPaperSize(PaperSize size) { - setPaperSize((short) (size.ordinal() + 1)); - } - - /** - * Set the scale. - * Valid values range from 10 to 400. - * This setting is overridden when fitToWidth and/or fitToHeight are in use - * - * @param scale the scale to use - */ - public void setScale(short scale) { - if (scale < 10 || scale > 400) throw new POIXMLException("Scale value not accepted: you must choose a value between 10 and 400."); - pageSetup.setScale(scale); - } - - /** - * Set the page numbering start. - * Page number for first printed page. If no value is specified, then 'automatic' is assumed. - * - * @param start the page numbering start - */ - public void setPageStart(short start) { - pageSetup.setFirstPageNumber(start); - } - - /** - * Set the number of pages wide to fit the sheet in - * - * @param width the number of pages - */ - public void setFitWidth(short width) { - pageSetup.setFitToWidth(width); - } - - /** - * Set the number of pages high to fit the sheet in - * - * @param height the number of pages - */ - public void setFitHeight(short height) { - pageSetup.setFitToHeight(height); - } - - /** - * Set whether to go left to right or top down in ordering - * - * @param ltor left to right - */ - public void setLeftToRight(boolean ltor) { - if (ltor) - setPageOrder(PageOrder.OVER_THEN_DOWN); - else - setPageOrder(PageOrder.DOWN_THEN_OVER); - } - - /** - * Set whether to print in landscape - * - * @param ls landscape - */ - public void setLandscape(boolean ls) { - if (ls) - setOrientation(PrintOrientation.LANDSCAPE); - else - setOrientation(PrintOrientation.PORTRAIT); - } - - /** - * Use the printer's defaults settings for page setup values and don't use the default values - * specified in the schema. For example, if dpi is not present or specified in the XML, the - * a plication shall not assume 600dpi as specified in the schema as a default and instead - * shall let the printer specify the default dpi. - * - * @param valid Valid - */ - public void setValidSettings(boolean valid) { - pageSetup.setUsePrinterDefaults(valid); - } - - /** - * Set whether it is black and white - * - * @param mono Black and white - */ - public void setNoColor(boolean mono) { - pageSetup.setBlackAndWhite(mono); - } - - /** - * Set whether it is in draft mode - * - * @param d draft - */ - public void setDraft(boolean d) { - pageSetup.setDraft(d); - } - - /** - * Print the include notes - * - * @param printnotes print the notes - */ - public void setNotes(boolean printnotes) { - if (printnotes){ - pageSetup.setCellComments(STCellComments.AS_DISPLAYED); - } - } - - /** - * Set no orientation. - * - * @param orientation Orientation. - */ - public void setNoOrientation(boolean orientation) { - if (orientation) { - setOrientation(PrintOrientation.DEFAULT); - } - } - - /** - * Set whether to use page start - * - * @param page Use page start - */ - public void setUsePage(boolean page) { - pageSetup.setUseFirstPageNumber(page); - } - - /** - * Sets the horizontal resolution. - * - * @param resolution horizontal resolution - */ - public void setHResolution(short resolution) { - pageSetup.setHorizontalDpi(resolution); - } - - /** - * Sets the vertical resolution. - * - * @param resolution vertical resolution - */ - public void setVResolution(short resolution) { - pageSetup.setVerticalDpi(resolution); - } - - /** - * Sets the header margin. - * - * @param headermargin header margin - */ - public void setHeaderMargin(double headermargin) { - pageMargins.setHeader(headermargin); - } - - /** - * Sets the footer margin. - * - * @param footermargin footer margin - */ - public void setFooterMargin(double footermargin) { - pageMargins.setFooter(footermargin); - } - - /** - * Sets the number of copies. - * - * @param copies number of copies - */ - public void setCopies(short copies) { - pageSetup.setCopies(copies); - } - - /** - * Orientation of the page: landscape - portrait. - * - * @param orientation - Orientation of the page - * @see PrintOrientation - */ - public void setOrientation(PrintOrientation orientation) { - STOrientation.Enum v = STOrientation.Enum.forInt(orientation.getValue()); - pageSetup.setOrientation(v); - } - - /** - * Orientation of the page: landscape - portrait. - * - * @return Orientation of the page - * @see PrintOrientation - */ - public PrintOrientation getOrientation() { - STOrientation.Enum val = pageSetup.getOrientation(); - return val == null ? PrintOrientation.DEFAULT : PrintOrientation.valueOf(val.intValue()); - } - - - public PrintCellComments getCellComment() { - STCellComments.Enum val = pageSetup.getCellComments(); - return val == null ? PrintCellComments.NONE : PrintCellComments.valueOf(val.intValue()); - } - - /** - * Set print page order. - * - * @param pageOrder - */ - public void setPageOrder(PageOrder pageOrder) { - STPageOrder.Enum v = STPageOrder.Enum.forInt(pageOrder.getValue()); - pageSetup.setPageOrder(v); - } - - /** - * get print page order. - * - * @return PageOrder - */ - public PageOrder getPageOrder() { - return (pageSetup.getPageOrder() == null) ? null : PageOrder.valueOf(pageSetup.getPageOrder().intValue()); - } - - /** - * Returns the paper size. - * - * @return short - paper size - */ - public short getPaperSize() { - return (short) pageSetup.getPaperSize(); - } - - /** - * Returns the paper size as enum. - * - * @return PaperSize paper size - * @see PaperSize - */ - public PaperSize getPaperSizeEnum() { - return PaperSize.values()[getPaperSize() - 1]; - } - - /** - * Returns the scale. - * - * @return short - scale - */ - public short getScale() { - return (short) pageSetup.getScale(); - } - - /** - * Set the page numbering start. - * Page number for first printed page. If no value is specified, then 'automatic' is assumed. - * - * @return page number for first printed page - */ - public short getPageStart() { - return (short) pageSetup.getFirstPageNumber(); - } - - /** - * Returns the number of pages wide to fit sheet in. - * - * @return number of pages wide to fit sheet in - */ - public short getFitWidth() { - return (short) pageSetup.getFitToWidth(); - } - - /** - * Returns the number of pages high to fit the sheet in. - * - * @return number of pages high to fit the sheet in - */ - public short getFitHeight() { - return (short) pageSetup.getFitToHeight(); - } - - /** - * Returns the left to right print order. - * - * @return left to right print order - */ - public boolean getLeftToRight() { - return getPageOrder() == PageOrder.OVER_THEN_DOWN; - } - - /** - * Returns the landscape mode. - * - * @return landscape mode - */ - public boolean getLandscape() { - return getOrientation() == PrintOrientation.LANDSCAPE; - } - - /** - * Use the printer's defaults settings for page setup values and don't use the default values - * specified in the schema. For example, if dpi is not present or specified in the XML, the - * application shall not assume 600dpi as specified in the schema as a default and instead - * shall let the printer specify the default dpi. - * - * @return valid settings - */ - public boolean getValidSettings() { - return pageSetup.getUsePrinterDefaults(); - } - - /** - * Returns the black and white setting. - * - * @return black and white setting - */ - public boolean getNoColor() { - return pageSetup.getBlackAndWhite(); - } - - /** - * Returns the draft mode. - * - * @return draft mode - */ - public boolean getDraft() { - return pageSetup.getDraft(); - } - - /** - * Returns the print notes. - * - * @return print notes - */ - public boolean getNotes() { - return getCellComment() == PrintCellComments.AS_DISPLAYED; - } - - /** - * Returns the no orientation. - * - * @return no orientation - */ - public boolean getNoOrientation() { - return getOrientation() == PrintOrientation.DEFAULT; - } - - /** - * Returns the use page numbers. - * - * @return use page numbers - */ - public boolean getUsePage() { - return pageSetup.getUseFirstPageNumber(); - } - - /** - * Returns the horizontal resolution. - * - * @return horizontal resolution - */ - public short getHResolution() { - return (short) pageSetup.getHorizontalDpi(); - } - - /** - * Returns the vertical resolution. - * - * @return vertical resolution - */ - public short getVResolution() { - return (short) pageSetup.getVerticalDpi(); - } - - /** - * Returns the header margin. - * - * @return header margin - */ - public double getHeaderMargin() { - return pageMargins.getHeader(); - } - - /** - * Returns the footer margin. - * - * @return footer margin - */ - public double getFooterMargin() { - return pageMargins.getFooter(); - } - - /** - * Returns the number of copies. - * - * @return number of copies - */ - public short getCopies() { - return (short) pageSetup.getCopies(); - } - -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFRelation.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFRelation.java deleted file mode 100644 index 019d552a2..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFRelation.java +++ /dev/null @@ -1,368 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel; - -import java.util.HashMap; -import java.util.Map; - -import org.apache.poi.POIXMLDocument; -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.POIXMLRelation; -import org.apache.poi.openxml4j.opc.PackageRelationshipTypes; -import org.apache.poi.xssf.model.CalculationChain; -import org.apache.poi.xssf.model.CommentsTable; -import org.apache.poi.xssf.model.ExternalLinksTable; -import org.apache.poi.xssf.model.MapInfo; -import org.apache.poi.xssf.model.SharedStringsTable; -import org.apache.poi.xssf.model.SingleXmlCells; -import org.apache.poi.xssf.model.StylesTable; -import org.apache.poi.xssf.model.ThemesTable; - -/** - * Defines namespaces, content types and normal file names / naming - * patterns, for the well-known XSSF format parts. - */ -public final class XSSFRelation extends POIXMLRelation { - - /** - * A map to lookup POIXMLRelation by its relation type - */ - private static final Map _table = new HashMap(); - - - public static final XSSFRelation WORKBOOK = new XSSFRelation( - "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/workbook", - "/xl/workbook.xml", - null - ); - public static final XSSFRelation MACROS_WORKBOOK = new XSSFRelation( - "application/vnd.ms-excel.sheet.macroEnabled.main+xml", - PackageRelationshipTypes.CORE_DOCUMENT, - "/xl/workbook.xml", - null - ); - public static final XSSFRelation TEMPLATE_WORKBOOK = new XSSFRelation( - "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml", - PackageRelationshipTypes.CORE_DOCUMENT, - "/xl/workbook.xml", - null - ); - - public static final XSSFRelation MACRO_TEMPLATE_WORKBOOK = new XSSFRelation( - "application/vnd.ms-excel.template.macroEnabled.main+xml", - PackageRelationshipTypes.CORE_DOCUMENT, - "/xl/workbook.xml", - null - ); - public static final XSSFRelation MACRO_ADDIN_WORKBOOK = new XSSFRelation( - "application/vnd.ms-excel.addin.macroEnabled.main+xml", - PackageRelationshipTypes.CORE_DOCUMENT, - "/xl/workbook.xml", - null - ); - - public static final XSSFRelation XLSB_BINARY_WORKBOOK = new XSSFRelation( - "application/vnd.ms-excel.sheet.binary.macroEnabled.main", - PackageRelationshipTypes.CORE_DOCUMENT, - "/xl/workbook.bin", - null - ); - - public static final XSSFRelation WORKSHEET = new XSSFRelation( - "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet", - "/xl/worksheets/sheet#.xml", - XSSFSheet.class - ); - - public static final XSSFRelation CHARTSHEET = new XSSFRelation( - "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/chartsheet", - "/xl/chartsheets/sheet#.xml", - XSSFChartSheet.class - ); - - public static final XSSFRelation SHARED_STRINGS = new XSSFRelation( - "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings", - "/xl/sharedStrings.xml", - SharedStringsTable.class - ); - - public static final XSSFRelation STYLES = new XSSFRelation( - "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml", - PackageRelationshipTypes.STYLE_PART, - "/xl/styles.xml", - StylesTable.class - ); - - public static final XSSFRelation DRAWINGS = new XSSFRelation( - "application/vnd.openxmlformats-officedocument.drawing+xml", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing", - "/xl/drawings/drawing#.xml", - XSSFDrawing.class - ); - - public static final XSSFRelation VML_DRAWINGS = new XSSFRelation( - "application/vnd.openxmlformats-officedocument.vmlDrawing", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing", - "/xl/drawings/vmlDrawing#.vml", - XSSFVMLDrawing.class - ); - - public static final XSSFRelation CHART = new XSSFRelation( - "application/vnd.openxmlformats-officedocument.drawingml.chart+xml", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart", - "/xl/charts/chart#.xml", - XSSFChart.class - ); - - public static final XSSFRelation CUSTOM_XML_MAPPINGS = new XSSFRelation( - "application/xml", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/xmlMaps", - "/xl/xmlMaps.xml", - MapInfo.class - ); - - public static final XSSFRelation SINGLE_XML_CELLS = new XSSFRelation( - "application/vnd.openxmlformats-officedocument.spreadsheetml.tableSingleCells+xml", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/tableSingleCells", - "/xl/tables/tableSingleCells#.xml", - SingleXmlCells.class - ); - - public static final XSSFRelation TABLE = new XSSFRelation( - "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/table", - "/xl/tables/table#.xml", - XSSFTable.class - ); - - public static final XSSFRelation IMAGES = new XSSFRelation( - null, - PackageRelationshipTypes.IMAGE_PART, - null, - XSSFPictureData.class - ); - - public static final XSSFRelation IMAGE_EMF = new XSSFRelation( - "image/x-emf", - PackageRelationshipTypes.IMAGE_PART, - "/xl/media/image#.emf", - XSSFPictureData.class - ); - - public static final XSSFRelation IMAGE_WMF = new XSSFRelation( - "image/x-wmf", - PackageRelationshipTypes.IMAGE_PART, - "/xl/media/image#.wmf", - XSSFPictureData.class - ); - - public static final XSSFRelation IMAGE_PICT = new XSSFRelation( - "image/pict", - PackageRelationshipTypes.IMAGE_PART, - "/xl/media/image#.pict", - XSSFPictureData.class - ); - - public static final XSSFRelation IMAGE_JPEG = new XSSFRelation( - "image/jpeg", - PackageRelationshipTypes.IMAGE_PART, - "/xl/media/image#.jpeg", - XSSFPictureData.class - ); - - public static final XSSFRelation IMAGE_PNG = new XSSFRelation( - "image/png", - PackageRelationshipTypes.IMAGE_PART, - "/xl/media/image#.png", - XSSFPictureData.class - ); - - public static final XSSFRelation IMAGE_DIB = new XSSFRelation( - "image/dib", - PackageRelationshipTypes.IMAGE_PART, - "/xl/media/image#.dib", - XSSFPictureData.class - ); - - public static final XSSFRelation IMAGE_GIF = new XSSFRelation( - "image/gif", - PackageRelationshipTypes.IMAGE_PART, - "/xl/media/image#.gif", - XSSFPictureData.class - ); - - public static final XSSFRelation IMAGE_TIFF = new XSSFRelation( - "image/tiff", - PackageRelationshipTypes.IMAGE_PART, - "/xl/media/image#.tiff", - XSSFPictureData.class - ); - - public static final XSSFRelation IMAGE_EPS = new XSSFRelation( - "image/x-eps", - PackageRelationshipTypes.IMAGE_PART, - "/xl/media/image#.eps", - XSSFPictureData.class - ); - - public static final XSSFRelation IMAGE_BMP = new XSSFRelation( - "image/x-ms-bmp", - PackageRelationshipTypes.IMAGE_PART, - "/xl/media/image#.bmp", - XSSFPictureData.class - ); - - public static final XSSFRelation IMAGE_WPG = new XSSFRelation( - "image/x-wpg", - PackageRelationshipTypes.IMAGE_PART, - "/xl/media/image#.wpg", - XSSFPictureData.class - ); - - public static final XSSFRelation SHEET_COMMENTS = new XSSFRelation( - "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments", - "/xl/comments#.xml", - CommentsTable.class - ); - - public static final XSSFRelation SHEET_HYPERLINKS = new XSSFRelation( - null, - PackageRelationshipTypes.HYPERLINK_PART, - null, - null - ); - - public static final XSSFRelation OLEEMBEDDINGS = new XSSFRelation( - null, - POIXMLDocument.OLE_OBJECT_REL_TYPE, - null, - null - ); - - public static final XSSFRelation PACKEMBEDDINGS = new XSSFRelation( - null, - POIXMLDocument.PACK_OBJECT_REL_TYPE, - null, - null - ); - - public static final XSSFRelation VBA_MACROS = new XSSFRelation( - "application/vnd.ms-office.vbaProject", - "http://schemas.microsoft.com/office/2006/relationships/vbaProject", - "/xl/vbaProject.bin", - XSSFVBAPart.class - ); - - public static final XSSFRelation ACTIVEX_CONTROLS = new XSSFRelation( - "application/vnd.ms-office.activeX+xml", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/control", - "/xl/activeX/activeX#.xml", - null - ); - - public static final XSSFRelation ACTIVEX_BINS = new XSSFRelation( - "application/vnd.ms-office.activeX", - "http://schemas.microsoft.com/office/2006/relationships/activeXControlBinary", - "/xl/activeX/activeX#.bin", - null - ); - - public static final XSSFRelation THEME = new XSSFRelation( - "application/vnd.openxmlformats-officedocument.theme+xml", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme", - "/xl/theme/theme#.xml", - ThemesTable.class - ); - - public static final XSSFRelation CALC_CHAIN = new XSSFRelation( - "application/vnd.openxmlformats-officedocument.spreadsheetml.calcChain+xml", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/calcChain", - "/xl/calcChain.xml", - CalculationChain.class - ); - - public static final XSSFRelation EXTERNAL_LINKS = new XSSFRelation( - "application/vnd.openxmlformats-officedocument.spreadsheetml.externalLink+xml", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/externalLink", - "/xl/externalLinks/externalLink#.xmll", - ExternalLinksTable.class - ); - - public static final XSSFRelation PRINTER_SETTINGS = new XSSFRelation( - "application/vnd.openxmlformats-officedocument.spreadsheetml.printerSettings", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/printerSettings", - "/xl/printerSettings/printerSettings#.bin", - null - ); - public static final XSSFRelation PIVOT_TABLE = new XSSFRelation( - "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotTable+xml", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/pivotTable", - "/xl/pivotTables/pivotTable#.xml", - XSSFPivotTable.class - ); - public static final XSSFRelation PIVOT_CACHE_DEFINITION = new XSSFRelation( - "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheDefinition+xml", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/pivotCacheDefinition", - "/xl/pivotCache/pivotCacheDefinition#.xml", - XSSFPivotCacheDefinition.class - ); - public static final XSSFRelation PIVOT_CACHE_RECORDS = new XSSFRelation( - "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheRecords+xml", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/pivotCacheRecords", - "/xl/pivotCache/pivotCacheRecords#.xml", - XSSFPivotCacheRecords.class - ); - - public static final XSSFRelation CTRL_PROP_RECORDS = new XSSFRelation( - null, - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/ctrlProp", - "/xl/ctrlProps/ctrlProp#.xml", - null - ); - - public static final XSSFRelation CUSTOM_PROPERTIES = new XSSFRelation( - "application/vnd.openxmlformats-officedocument.spreadsheetml.customProperty", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/customProperty", - "/xl/customProperty#.bin", - null - ); - - public static final String NS_SPREADSHEETML = "http://schemas.openxmlformats.org/spreadsheetml/2006/main"; - public static final String NS_DRAWINGML = "http://schemas.openxmlformats.org/drawingml/2006/main"; - public static final String NS_CHART = "http://schemas.openxmlformats.org/drawingml/2006/chart"; - - private XSSFRelation(String type, String rel, String defaultName, Class cls) { - super(type, rel, defaultName, cls); - _table.put(rel, this); - } - - /** - * Get POIXMLRelation by relation type - * - * @param rel relation type, for example, - * http://schemas.openxmlformats.org/officeDocument/2006/relationships/image - * @return registered POIXMLRelation or null if not found - */ - public static XSSFRelation getInstance(String rel) { - return _table.get(rel); - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFRichTextString.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFRichTextString.java deleted file mode 100644 index e93f0fa4a..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFRichTextString.java +++ /dev/null @@ -1,601 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import java.util.*; -import java.util.regex.Pattern; -import java.util.regex.Matcher; - -import javax.xml.namespace.QName; - -import org.apache.poi.ss.usermodel.Font; -import org.apache.poi.ss.usermodel.RichTextString; -import org.apache.poi.xssf.model.StylesTable; -import org.apache.poi.xssf.model.ThemesTable; -import org.apache.poi.util.Internal; -import org.apache.xmlbeans.XmlCursor; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTColor; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTFont; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRElt; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRPrElt; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRst; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STXstring; - - -/** - * Rich text unicode string. These strings can have fonts applied to arbitary parts of the string. - * - *

    - * Most strings in a workbook have formatting applied at the cell level, that is, the entire string in the cell has the - * same formatting applied. In these cases, the formatting for the cell is stored in the styles part, - * and the string for the cell can be shared across the workbook. The following code illustrates the example. - *

    - * - *
    - *
    - *     cell1.setCellValue(new XSSFRichTextString("Apache POI"));
    - *     cell2.setCellValue(new XSSFRichTextString("Apache POI"));
    - *     cell3.setCellValue(new XSSFRichTextString("Apache POI"));
    - * 
    - *
    - * In the above example all three cells will use the same string cached on workbook level. - * - *

    - * Some strings in the workbook may have formatting applied at a level that is more granular than the cell level. - * For instance, specific characters within the string may be bolded, have coloring, italicizing, etc. - * In these cases, the formatting is stored along with the text in the string table, and is treated as - * a unique entry in the workbook. The following xml and code snippet illustrate this. - *

    - * - *
    - *
    - *     XSSFRichTextString s1 = new XSSFRichTextString("Apache POI");
    - *     s1.applyFont(boldArial);
    - *     cell1.setCellValue(s1);
    - *
    - *     XSSFRichTextString s2 = new XSSFRichTextString("Apache POI");
    - *     s2.applyFont(italicCourier);
    - *     cell2.setCellValue(s2);
    - * 
    - *
    - */ -public class XSSFRichTextString implements RichTextString { - private static final Pattern utfPtrn = Pattern.compile("_x([0-9A-Fa-f]{4})_"); - - private CTRst st; - private StylesTable styles; - - /** - * Create a rich text string - */ - public XSSFRichTextString(String str) { - st = CTRst.Factory.newInstance(); - st.setT(str); - preserveSpaces(st.xgetT()); - } - - /** - * Create empty rich text string and initialize it with empty string - */ - public XSSFRichTextString() { - st = CTRst.Factory.newInstance(); - } - - /** - * Create a rich text string from the supplied XML bean - */ - public XSSFRichTextString(CTRst st) { - this.st = st; - } - - /** - * Applies a font to the specified characters of a string. - * - * @param startIndex The start index to apply the font to (inclusive) - * @param endIndex The end index to apply the font to (exclusive) - * @param fontIndex The font to use. - */ - public void applyFont(int startIndex, int endIndex, short fontIndex) { - XSSFFont font; - if(styles == null) { - //style table is not set, remember fontIndex and set the run properties later, - //when setStylesTableReference is called - font = new XSSFFont(); - font.setFontName("#" + fontIndex); - } else { - font = styles.getFontAt(fontIndex); - } - applyFont(startIndex, endIndex, font); - } - - /** - * Applies a font to the specified characters of a string. - * - * @param startIndex The start index to apply the font to (inclusive) - * @param endIndex The end index to apply to font to (exclusive) - * @param font The index of the font to use. - */ - public void applyFont(int startIndex, int endIndex, Font font) { - if (startIndex > endIndex) - throw new IllegalArgumentException("Start index must be less than end index, but had " + startIndex + " and " + endIndex); - if (startIndex < 0 || endIndex > length()) - throw new IllegalArgumentException("Start and end index not in range, but had " + startIndex + " and " + endIndex); - - if (startIndex == endIndex) - return; - - if(st.sizeOfRArray() == 0 && st.isSetT()) { - //convert string into a text run: string - st.addNewR().setT(st.getT()); - st.unsetT(); - } - - String text = getString(); - XSSFFont xssfFont = (XSSFFont)font; - - TreeMap formats = getFormatMap(st); - CTRPrElt fmt = CTRPrElt.Factory.newInstance(); - setRunAttributes(xssfFont.getCTFont(), fmt); - applyFont(formats, startIndex, endIndex, fmt); - - CTRst newSt = buildCTRst(text, formats); - st.set(newSt); - } - - /** - * Sets the font of the entire string. - * @param font The font to use. - */ - public void applyFont(Font font) { - String text = getString(); - applyFont(0, text.length(), font); - } - - /** - * Applies the specified font to the entire string. - * - * @param fontIndex the font to apply. - */ - public void applyFont(short fontIndex) { - XSSFFont font; - if(styles == null) { - font = new XSSFFont(); - font.setFontName("#" + fontIndex); - } else { - font = styles.getFontAt(fontIndex); - } - String text = getString(); - applyFont(0, text.length(), font); - } - - /** - * Append new text to this text run and apply the specify font to it - * - * @param text the text to append - * @param font the font to apply to the appended text or null if no formatting is required - */ - public void append(String text, XSSFFont font){ - if(st.sizeOfRArray() == 0 && st.isSetT()) { - //convert string into a text run: string - CTRElt lt = st.addNewR(); - lt.setT(st.getT()); - preserveSpaces(lt.xgetT()); - st.unsetT(); - } - CTRElt lt = st.addNewR(); - lt.setT(text); - preserveSpaces(lt.xgetT()); - - if (font != null) { - CTRPrElt pr = lt.addNewRPr(); - setRunAttributes(font.getCTFont(), pr); - } - } - - /** - * Append new text to this text run - * - * @param text the text to append - */ - public void append(String text){ - append(text, null); - } - - /** - * Copy font attributes from CTFont bean into CTRPrElt bean - */ - private void setRunAttributes(CTFont ctFont, CTRPrElt pr){ - if(ctFont.sizeOfBArray() > 0) pr.addNewB().setVal(ctFont.getBArray(0).getVal()); - if(ctFont.sizeOfUArray() > 0) pr.addNewU().setVal(ctFont.getUArray(0).getVal()); - if(ctFont.sizeOfIArray() > 0) pr.addNewI().setVal(ctFont.getIArray(0).getVal()); - if(ctFont.sizeOfColorArray() > 0) { - CTColor c1 = ctFont.getColorArray(0); - CTColor c2 = pr.addNewColor(); - if(c1.isSetAuto()) c2.setAuto(c1.getAuto()); - if(c1.isSetIndexed()) c2.setIndexed(c1.getIndexed()); - if(c1.isSetRgb()) c2.setRgb(c1.getRgb()); - if(c1.isSetTheme()) c2.setTheme(c1.getTheme()); - if(c1.isSetTint()) c2.setTint(c1.getTint()); - } - if(ctFont.sizeOfSzArray() > 0) pr.addNewSz().setVal(ctFont.getSzArray(0).getVal()); - if(ctFont.sizeOfNameArray() > 0) pr.addNewRFont().setVal(ctFont.getNameArray(0).getVal()); - if(ctFont.sizeOfFamilyArray() > 0) pr.addNewFamily().setVal(ctFont.getFamilyArray(0).getVal()); - if(ctFont.sizeOfSchemeArray() > 0) pr.addNewScheme().setVal(ctFont.getSchemeArray(0).getVal()); - if(ctFont.sizeOfCharsetArray() > 0) pr.addNewCharset().setVal(ctFont.getCharsetArray(0).getVal()); - if(ctFont.sizeOfCondenseArray() > 0) pr.addNewCondense().setVal(ctFont.getCondenseArray(0).getVal()); - if(ctFont.sizeOfExtendArray() > 0) pr.addNewExtend().setVal(ctFont.getExtendArray(0).getVal()); - if(ctFont.sizeOfVertAlignArray() > 0) pr.addNewVertAlign().setVal(ctFont.getVertAlignArray(0).getVal()); - if(ctFont.sizeOfOutlineArray() > 0) pr.addNewOutline().setVal(ctFont.getOutlineArray(0).getVal()); - if(ctFont.sizeOfShadowArray() > 0) pr.addNewShadow().setVal(ctFont.getShadowArray(0).getVal()); - if(ctFont.sizeOfStrikeArray() > 0) pr.addNewStrike().setVal(ctFont.getStrikeArray(0).getVal()); - } - - /** - * Does this string have any explicit formatting applied, or is - * it just text in the default style? - */ - public boolean hasFormatting() { - //noinspection deprecation - for performance reasons! - CTRElt[] rs = st.getRArray(); - if (rs == null || rs.length == 0) { - return false; - } - for (CTRElt r : rs) { - if (r.isSetRPr()) return true; - } - return false; - } - - /** - * Removes any formatting that may have been applied to the string. - */ - public void clearFormatting() { - String text = getString(); - st.setRArray(null); - st.setT(text); - } - - /** - * The index within the string to which the specified formatting run applies. - * - * @param index the index of the formatting run - * @return the index within the string. - */ - public int getIndexOfFormattingRun(int index) { - if(st.sizeOfRArray() == 0) return 0; - - int pos = 0; - for(int i = 0; i < st.sizeOfRArray(); i++){ - CTRElt r = st.getRArray(i); - if(i == index) return pos; - - pos += r.getT().length(); - } - return -1; - } - - /** - * Returns the number of characters this format run covers. - * - * @param index the index of the formatting run - * @return the number of characters this format run covers - */ - public int getLengthOfFormattingRun(int index) { - if(st.sizeOfRArray() == 0 || index >= st.sizeOfRArray()) { - return -1; - } - - CTRElt r = st.getRArray(index); - return r.getT().length(); - } - - /** - * Returns the plain string representation. - */ - public String getString() { - if(st.sizeOfRArray() == 0) { - return utfDecode(st.getT()); - } - StringBuilder buf = new StringBuilder(); - //noinspection deprecation - for performance reasons! - for(CTRElt r : st.getRArray()){ - buf.append(r.getT()); - } - return utfDecode(buf.toString()); - } - - /** - * Removes any formatting and sets new string value - * - * @param s new string value - */ - public void setString(String s){ - clearFormatting(); - st.setT(s); - preserveSpaces(st.xgetT()); - } - - /** - * Returns the plain string representation. - */ - public String toString() { - return getString(); - } - - /** - * Returns the number of characters in this string. - */ - public int length() { - return getString().length(); - } - - /** - * @return The number of formatting runs used. - */ - public int numFormattingRuns() { - return st.sizeOfRArray(); - } - - /** - * Gets a copy of the font used in a particular formatting run. - * - * @param index the index of the formatting run - * @return A copy of the font used or null if no formatting is applied to the specified text run. - */ - public XSSFFont getFontOfFormattingRun(int index) { - if(st.sizeOfRArray() == 0 || index >= st.sizeOfRArray()) { - return null; - } - - CTRElt r = st.getRArray(index); - if(r.getRPr() != null) { - XSSFFont fnt = new XSSFFont(toCTFont(r.getRPr())); - fnt.setThemesTable(getThemesTable()); - return fnt; - } - - return null; - } - - /** - * Return a copy of the font in use at a particular index. - * - * @param index The index. - * @return A copy of the font that's currently being applied at that - * index or null if no font is being applied or the - * index is out of range. - */ - public XSSFFont getFontAtIndex( int index ) { - final ThemesTable themes = getThemesTable(); - int pos = 0; - //noinspection deprecation - for performance reasons! - for(CTRElt r : st.getRArray()){ - final int length = r.getT().length(); - if(index >= pos && index < pos + length) { - XSSFFont fnt = new XSSFFont(toCTFont(r.getRPr())); - fnt.setThemesTable(themes); - return fnt; - } - - pos += length; - } - return null; - - } - - /** - * Return the underlying xml bean - */ - @Internal - public CTRst getCTRst() { - return st; - } - - protected void setStylesTableReference(StylesTable tbl){ - styles = tbl; - if(st.sizeOfRArray() > 0) { - //noinspection deprecation - for performance reasons! - for (CTRElt r : st.getRArray()) { - CTRPrElt pr = r.getRPr(); - if(pr != null && pr.sizeOfRFontArray() > 0){ - String fontName = pr.getRFontArray(0).getVal(); - if(fontName.startsWith("#")){ - int idx = Integer.parseInt(fontName.substring(1)); - XSSFFont font = styles.getFontAt(idx); - pr.removeRFont(0); - setRunAttributes(font.getCTFont(), pr); - } - } - } - } - } - - /** - * - * CTRPrElt --> CTFont adapter - */ - protected static CTFont toCTFont(CTRPrElt pr){ - CTFont ctFont = CTFont.Factory.newInstance(); - - // Bug 58315: there are files where there is no pr-entry for a RichTextString - if(pr == null) { - return ctFont; - } - - if(pr.sizeOfBArray() > 0) ctFont.addNewB().setVal(pr.getBArray(0).getVal()); - if(pr.sizeOfUArray() > 0) ctFont.addNewU().setVal(pr.getUArray(0).getVal()); - if(pr.sizeOfIArray() > 0) ctFont.addNewI().setVal(pr.getIArray(0).getVal()); - if(pr.sizeOfColorArray() > 0) { - CTColor c1 = pr.getColorArray(0); - CTColor c2 = ctFont.addNewColor(); - if(c1.isSetAuto()) c2.setAuto(c1.getAuto()); - if(c1.isSetIndexed()) c2.setIndexed(c1.getIndexed()); - if(c1.isSetRgb()) c2.setRgb(c1.getRgb()); - if(c1.isSetTheme()) c2.setTheme(c1.getTheme()); - if(c1.isSetTint()) c2.setTint(c1.getTint()); - } - if(pr.sizeOfSzArray() > 0) ctFont.addNewSz().setVal(pr.getSzArray(0).getVal()); - if(pr.sizeOfRFontArray() > 0) ctFont.addNewName().setVal(pr.getRFontArray(0).getVal()); - if(pr.sizeOfFamilyArray() > 0) ctFont.addNewFamily().setVal(pr.getFamilyArray(0).getVal()); - if(pr.sizeOfSchemeArray() > 0) ctFont.addNewScheme().setVal(pr.getSchemeArray(0).getVal()); - if(pr.sizeOfCharsetArray() > 0) ctFont.addNewCharset().setVal(pr.getCharsetArray(0).getVal()); - if(pr.sizeOfCondenseArray() > 0) ctFont.addNewCondense().setVal(pr.getCondenseArray(0).getVal()); - if(pr.sizeOfExtendArray() > 0) ctFont.addNewExtend().setVal(pr.getExtendArray(0).getVal()); - if(pr.sizeOfVertAlignArray() > 0) ctFont.addNewVertAlign().setVal(pr.getVertAlignArray(0).getVal()); - if(pr.sizeOfOutlineArray() > 0) ctFont.addNewOutline().setVal(pr.getOutlineArray(0).getVal()); - if(pr.sizeOfShadowArray() > 0) ctFont.addNewShadow().setVal(pr.getShadowArray(0).getVal()); - if(pr.sizeOfStrikeArray() > 0) ctFont.addNewStrike().setVal(pr.getStrikeArray(0).getVal()); - - return ctFont; - } - - /** - * Add the xml:spaces="preserve" attribute if the string has leading or trailing spaces - * - * @param xs the string to check - */ - protected static void preserveSpaces(STXstring xs) { - String text = xs.getStringValue(); - if (text != null && text.length() > 0) { - char firstChar = text.charAt(0); - char lastChar = text.charAt(text.length() - 1); - if(Character.isWhitespace(firstChar) || Character.isWhitespace(lastChar)) { - XmlCursor c = xs.newCursor(); - c.toNextToken(); - c.insertAttributeWithValue(new QName("http://www.w3.org/XML/1998/namespace", "space"), "preserve"); - c.dispose(); - } - } - } - - /** - * For all characters which cannot be represented in XML as defined by the XML 1.0 specification, - * the characters are escaped using the Unicode numerical character representation escape character - * format _xHHHH_, where H represents a hexadecimal character in the character's value. - *

    - * Example: The Unicode character 0D is invalid in an XML 1.0 document, - * so it shall be escaped as _x000D_. - *

    - * See section 3.18.9 in the OOXML spec. - * - * @param value the string to decode - * @return the decoded string - */ - static String utfDecode(String value){ - if(value == null || !value.contains("_x")) { - return value; - } - - StringBuilder buf = new StringBuilder(); - Matcher m = utfPtrn.matcher(value); - int idx = 0; - while(m.find()) { - int pos = m.start(); - if( pos > idx) { - buf.append(value.substring(idx, pos)); - } - - String code = m.group(1); - int icode = Integer.decode("0x" + code); - buf.append((char)icode); - - idx = m.end(); - } - - // small optimization: don't go via StringBuilder if not necessary, - // the encodings are very rare, so we should almost always go via this shortcut. - if(idx == 0) { - return value; - } - - buf.append(value.substring(idx)); - return buf.toString(); - } - - void applyFont(TreeMap formats, int startIndex, int endIndex, CTRPrElt fmt) { - // delete format runs that fit between startIndex and endIndex - // runs intersecting startIndex and endIndex remain - int runStartIdx = 0; - for (Iterator it = formats.keySet().iterator(); it.hasNext();) { - int runEndIdx = it.next(); - if (runStartIdx >= startIndex && runEndIdx < endIndex) { - it.remove(); - } - runStartIdx = runEndIdx; - } - - if(startIndex > 0 && !formats.containsKey(startIndex)) { - // If there's a format that starts later in the string, make it start now - for(Map.Entry entry : formats.entrySet()) { - if(entry.getKey() > startIndex) { - formats.put(startIndex, entry.getValue()); - break; - } - } - } - formats.put(endIndex, fmt); - - // assure that the range [startIndex, endIndex] consists if a single run - // there can be two or three runs depending whether startIndex or endIndex - // intersected existing format runs - SortedMap sub = formats.subMap(startIndex, endIndex); - while(sub.size() > 1) sub.remove(sub.lastKey()); - } - - TreeMap getFormatMap(CTRst entry){ - int length = 0; - TreeMap formats = new TreeMap(); - //noinspection deprecation - for performance reasons! - for (CTRElt r : entry.getRArray()) { - String txt = r.getT(); - CTRPrElt fmt = r.getRPr(); - - length += txt.length(); - formats.put(length, fmt); - } - return formats; - } - - CTRst buildCTRst(String text, TreeMap formats){ - if(text.length() != formats.lastKey()) { - throw new IllegalArgumentException("Text length was " + text.length() + - " but the last format index was " + formats.lastKey()); - } - CTRst stf = CTRst.Factory.newInstance(); - int runStartIdx = 0; - for (Map.Entry me : formats.entrySet()) { - int runEndIdx = me.getKey(); - CTRElt run = stf.addNewR(); - String fragment = text.substring(runStartIdx, runEndIdx); - run.setT(fragment); - preserveSpaces(run.xgetT()); - - CTRPrElt fmt = me.getValue(); - if (fmt != null) { - run.setRPr(fmt); - } - runStartIdx = runEndIdx; - } - return stf; - } - - private ThemesTable getThemesTable() { - if(styles == null) return null; - return styles.getTheme(); - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFRow.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFRow.java deleted file mode 100644 index e936ed554..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFRow.java +++ /dev/null @@ -1,675 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; -import java.util.TreeMap; - -import org.apache.poi.ss.formula.FormulaShifter; -import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellCopyPolicy; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.util.Beta; -import org.apache.poi.util.Internal; -import org.apache.poi.xssf.model.CalculationChain; -import org.apache.poi.xssf.model.StylesTable; -import org.apache.poi.xssf.usermodel.helpers.XSSFRowShifter; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCell; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRow; - -/** - * High level representation of a row of a spreadsheet. - */ -public class XSSFRow implements Row, Comparable { - //private static final POILogger _logger = POILogFactory.getLogger(XSSFRow.class); - - /** - * the xml bean containing all cell definitions for this row - */ - private final CTRow _row; - - /** - * Cells of this row keyed by their column indexes. - * The TreeMap ensures that the cells are ordered by columnIndex in the ascending order. - */ - private final TreeMap _cells; - - /** - * the parent sheet - */ - private final XSSFSheet _sheet; - - /** - * Construct a XSSFRow. - * - * @param row the xml bean containing all cell definitions for this row. - * @param sheet the parent sheet. - */ - protected XSSFRow(CTRow row, XSSFSheet sheet) { - _row = row; - _sheet = sheet; - _cells = new TreeMap(); - for (CTCell c : row.getCArray()) { - XSSFCell cell = new XSSFCell(this, c); - // Performance optimization for bug 57840: explicit boxing is slightly faster than auto-unboxing, though may use more memory - final Integer colI = new Integer(cell.getColumnIndex()); // NOSONAR - _cells.put(colI, cell); - sheet.onReadCell(cell); - } - - if (! row.isSetR()) { - // Certain file format writers skip the row number - // Assume no gaps, and give this the next row number - int nextRowNum = sheet.getLastRowNum()+2; - if (nextRowNum == 2 && sheet.getPhysicalNumberOfRows() == 0) { - nextRowNum = 1; - } - row.setR(nextRowNum); - } - } - - /** - * Returns the XSSFSheet this row belongs to - * - * @return the XSSFSheet that owns this row - */ - @Override - public XSSFSheet getSheet() { - return this._sheet; - } - - /** - * Cell iterator over the physically defined cells: - *
    -     * for (Iterator it = row.cellIterator(); it.hasNext(); ) {
    -     *     Cell cell = it.next();
    -     *     ...
    -     * }
    -     * 
    - * - * @return an iterator over cells in this row. - */ - @Override - @SuppressWarnings("unchecked") - public Iterator cellIterator() { - return (Iterator)(Iterator)_cells.values().iterator(); - } - - /** - * Alias for {@link #cellIterator()} to allow foreach loops: - *
    -     * for(Cell cell : row){
    -     *     ...
    -     * }
    -     * 
    - * - * @return an iterator over cells in this row. - */ - @Override - public Iterator iterator() { - return cellIterator(); - } - - /** - * Compares two XSSFRow objects. Two rows are equal if they belong to the same worksheet and - * their row indexes are equal. - * - * @param other the XSSFRow to be compared. - * @return
      - *
    • - * the value 0 if the row number of this XSSFRow is - * equal to the row number of the argument XSSFRow - *
    • - *
    • - * a value less than 0 if the row number of this this XSSFRow is - * numerically less than the row number of the argument XSSFRow - *
    • - *
    • - * a value greater than 0 if the row number of this this XSSFRow is - * numerically greater than the row number of the argument XSSFRow - *
    • - *
    - * @throws IllegalArgumentException if the argument row belongs to a different worksheet - */ - @Override - public int compareTo(XSSFRow other) { - if (this.getSheet() != other.getSheet()) { - throw new IllegalArgumentException("The compared rows must belong to the same sheet"); - } - - Integer thisRow = this.getRowNum(); - Integer otherRow = other.getRowNum(); - return thisRow.compareTo(otherRow); - } - - @Override - public boolean equals(Object obj) - { - if (!(obj instanceof XSSFRow)) - { - return false; - } - XSSFRow other = (XSSFRow) obj; - - return (this.getRowNum() == other.getRowNum()) && - (this.getSheet() == other.getSheet()); - } - - @Override - public int hashCode() { - return _row.hashCode(); - } - - /** - * Use this to create new cells within the row and return it. - *

    - * The cell that is returned is a {@link CellType#BLANK}. The type can be changed - * either through calling setCellValue or setCellType. - *

    - * @param columnIndex - the column number this cell represents - * @return Cell a high level representation of the created cell. - * @throws IllegalArgumentException if columnIndex < 0 or greater than 16384, - * the maximum number of columns supported by the SpreadsheetML format (.xlsx) - */ - @Override - public XSSFCell createCell(int columnIndex) { - return createCell(columnIndex, CellType.BLANK); - } - - /** - * Use this to create new cells within the row and return it. - * - * @param columnIndex - the column number this cell represents - * @param type - the cell's data type - * @return XSSFCell a high level representation of the created cell. - * @throws IllegalArgumentException if the specified cell type is invalid, columnIndex < 0 - * or greater than 16384, the maximum number of columns supported by the SpreadsheetML format (.xlsx) - * @see CellType#BLANK - * @see CellType#BOOLEAN - * @see CellType#ERROR - * @see CellType#FORMULA - * @see CellType#NUMERIC - * @see CellType#STRING - * @deprecated POI 3.15 beta 3. Use {@link #createCell(int, CellType)} instead. - */ - @Override - public XSSFCell createCell(int columnIndex, int type) { - return createCell(columnIndex, CellType.forInt(type)); - } - /** - * Use this to create new cells within the row and return it. - * - * @param columnIndex - the column number this cell represents - * @param type - the cell's data type - * @return XSSFCell a high level representation of the created cell. - * @throws IllegalArgumentException if the specified cell type is invalid, columnIndex < 0 - * or greater than 16384, the maximum number of columns supported by the SpreadsheetML format (.xlsx) - */ - @Override - public XSSFCell createCell(int columnIndex, CellType type) { - // Performance optimization for bug 57840: explicit boxing is slightly faster than auto-unboxing, though may use more memory - final Integer colI = new Integer(columnIndex); // NOSONAR - CTCell ctCell; - XSSFCell prev = _cells.get(colI); - if(prev != null){ - ctCell = prev.getCTCell(); - ctCell.set(CTCell.Factory.newInstance()); - } else { - ctCell = _row.addNewC(); - } - XSSFCell xcell = new XSSFCell(this, ctCell); - xcell.setCellNum(columnIndex); - if (type != CellType.BLANK) { - xcell.setCellType(type); - } - _cells.put(colI, xcell); - return xcell; - } - - /** - * Returns the cell at the given (0 based) index, - * with the {@link org.apache.poi.ss.usermodel.Row.MissingCellPolicy} from the parent Workbook. - * - * @return the cell at the given (0 based) index - */ - @Override - public XSSFCell getCell(int cellnum) { - return getCell(cellnum, _sheet.getWorkbook().getMissingCellPolicy()); - } - - /** - * Returns the cell at the given (0 based) index, with the specified {@link org.apache.poi.ss.usermodel.Row.MissingCellPolicy} - * - * @return the cell at the given (0 based) index - * @throws IllegalArgumentException if cellnum < 0 or the specified MissingCellPolicy is invalid - */ - @Override - public XSSFCell getCell(int cellnum, MissingCellPolicy policy) { - if(cellnum < 0) throw new IllegalArgumentException("Cell index must be >= 0"); - - // Performance optimization for bug 57840: explicit boxing is slightly faster than auto-unboxing, though may use more memory - final Integer colI = new Integer(cellnum); // NOSONAR - XSSFCell cell = _cells.get(colI); - switch (policy) { - case RETURN_NULL_AND_BLANK: - return cell; - case RETURN_BLANK_AS_NULL: - boolean isBlank = (cell != null && cell.getCellTypeEnum() == CellType.BLANK); - return (isBlank) ? null : cell; - case CREATE_NULL_AS_BLANK: - return (cell == null) ? createCell(cellnum, CellType.BLANK) : cell; - default: - throw new IllegalArgumentException("Illegal policy " + policy + " (" + policy.id + ")"); - } - } - - /** - * Get the number of the first cell contained in this row. - * - * @return short representing the first logical cell in the row, - * or -1 if the row does not contain any cells. - */ - @Override - public short getFirstCellNum() { - return (short)(_cells.size() == 0 ? -1 : _cells.firstKey()); - } - - /** - * Gets the index of the last cell contained in this row PLUS ONE. The result also - * happens to be the 1-based column number of the last cell. This value can be used as a - * standard upper bound when iterating over cells: - *
    -     * short minColIx = row.getFirstCellNum();
    -     * short maxColIx = row.getLastCellNum();
    -     * for(short colIx=minColIx; colIx<maxColIx; colIx++) {
    -     *   XSSFCell cell = row.getCell(colIx);
    -     *   if(cell == null) {
    -     *     continue;
    -     *   }
    -     *   //... do something with cell
    -     * }
    -     * 
    - * - * @return short representing the last logical cell in the row PLUS ONE, - * or -1 if the row does not contain any cells. - */ - @Override - public short getLastCellNum() { - return (short)(_cells.size() == 0 ? -1 : (_cells.lastKey() + 1)); - } - - /** - * Get the row's height measured in twips (1/20th of a point). If the height is not set, the default worksheet value is returned, - * See {@link org.apache.poi.xssf.usermodel.XSSFSheet#getDefaultRowHeightInPoints()} - * - * @return row height measured in twips (1/20th of a point) - */ - @Override - public short getHeight() { - return (short)(getHeightInPoints()*20); - } - - /** - * Returns row height measured in point size. If the height is not set, the default worksheet value is returned, - * See {@link org.apache.poi.xssf.usermodel.XSSFSheet#getDefaultRowHeightInPoints()} - * - * @return row height measured in point size - * @see org.apache.poi.xssf.usermodel.XSSFSheet#getDefaultRowHeightInPoints() - */ - @Override - public float getHeightInPoints() { - if (this._row.isSetHt()) { - return (float) this._row.getHt(); - } - return _sheet.getDefaultRowHeightInPoints(); - } - - /** - * Set the height in "twips" or 1/20th of a point. - * - * @param height the height in "twips" or 1/20th of a point. -1 resets to the default height - */ - @Override - public void setHeight(short height) { - if (height == -1) { - if (_row.isSetHt()) _row.unsetHt(); - if (_row.isSetCustomHeight()) _row.unsetCustomHeight(); - } else { - _row.setHt((double) height / 20); - _row.setCustomHeight(true); - - } - } - - /** - * Set the row's height in points. - * - * @param height the height in points. -1 resets to the default height - */ - @Override - public void setHeightInPoints(float height) { - setHeight((short)(height == -1 ? -1 : (height*20))); - } - - /** - * Gets the number of defined cells (NOT number of cells in the actual row!). - * That is to say if only columns 0,4,5 have values then there would be 3. - * - * @return int representing the number of defined cells in the row. - */ - @Override - public int getPhysicalNumberOfCells() { - return _cells.size(); - } - - /** - * Get row number this row represents - * - * @return the row number (0 based) - */ - @Override - public int getRowNum() { - return (int) (_row.getR() - 1); - } - - /** - * Set the row number of this row. - * - * @param rowIndex the row number (0-based) - * @throws IllegalArgumentException if rowNum < 0 or greater than 1048575 - */ - @Override - public void setRowNum(int rowIndex) { - int maxrow = SpreadsheetVersion.EXCEL2007.getLastRowIndex(); - if (rowIndex < 0 || rowIndex > maxrow) { - throw new IllegalArgumentException("Invalid row number (" + rowIndex - + ") outside allowable range (0.." + maxrow + ")"); - } - _row.setR(rowIndex + 1); - } - - /** - * Get whether or not to display this row with 0 height - * - * @return - height is zero or not. - */ - @Override - public boolean getZeroHeight() { - return this._row.getHidden(); - } - - /** - * Set whether or not to display this row with 0 height - * - * @param height height is zero or not. - */ - @Override - public void setZeroHeight(boolean height) { - this._row.setHidden(height); - - } - - /** - * Is this row formatted? Most aren't, but some rows - * do have whole-row styles. For those that do, you - * can get the formatting from {@link #getRowStyle()} - */ - @Override - public boolean isFormatted() { - return _row.isSetS(); - } - /** - * Returns the whole-row cell style. Most rows won't - * have one of these, so will return null. Call - * {@link #isFormatted()} to check first. - */ - @Override - public XSSFCellStyle getRowStyle() { - if(!isFormatted()) return null; - - StylesTable stylesSource = getSheet().getWorkbook().getStylesSource(); - if(stylesSource.getNumCellStyles() > 0) { - return stylesSource.getStyleAt((int)_row.getS()); - } else { - return null; - } - } - - /** - * Applies a whole-row cell styling to the row. - * If the value is null then the style information is removed, - * causing the cell to used the default workbook style. - */ - @Override - public void setRowStyle(CellStyle style) { - if(style == null) { - if(_row.isSetS()) { - _row.unsetS(); - _row.unsetCustomFormat(); - } - } else { - StylesTable styleSource = getSheet().getWorkbook().getStylesSource(); - - XSSFCellStyle xStyle = (XSSFCellStyle)style; - xStyle.verifyBelongsToStylesSource(styleSource); - - long idx = styleSource.putStyle(xStyle); - _row.setS(idx); - _row.setCustomFormat(true); - } - } - - /** - * Remove the Cell from this row. - * - * @param cell the cell to remove - */ - @Override - public void removeCell(Cell cell) { - if (cell.getRow() != this) { - throw new IllegalArgumentException("Specified cell does not belong to this row"); - } - - XSSFCell xcell = (XSSFCell)cell; - if(xcell.isPartOfArrayFormulaGroup()) { - xcell.notifyArrayFormulaChanging(); - } - if(cell.getCellTypeEnum() == CellType.FORMULA) { - _sheet.getWorkbook().onDeleteFormula(xcell); - } - // Performance optimization for bug 57840: explicit boxing is slightly faster than auto-unboxing, though may use more memory - final Integer colI = new Integer(cell.getColumnIndex()); // NOSONAR - _cells.remove(colI); - } - - /** - * Returns the underlying CTRow xml bean containing all cell definitions in this row - * - * @return the underlying CTRow xml bean - */ - @Internal - public CTRow getCTRow(){ - return _row; - } - - /** - * Fired when the document is written to an output stream. - * - * @see org.apache.poi.xssf.usermodel.XSSFSheet#write(java.io.OutputStream) () - */ - protected void onDocumentWrite(){ - // check if cells in the CTRow are ordered - boolean isOrdered = true; - CTCell[] cArray = _row.getCArray(); - if (cArray.length != _cells.size()) { - isOrdered = false; - } else { - int i = 0; - for (XSSFCell cell : _cells.values()) { - CTCell c1 = cell.getCTCell(); - CTCell c2 = cArray[i++]; - - String r1 = c1.getR(); - String r2 = c2.getR(); - if (!(r1==null ? r2==null : r1.equals(r2))){ - isOrdered = false; - break; - } - } - } - - if(!isOrdered){ - cArray = new CTCell[_cells.size()]; - int i = 0; - for (XSSFCell xssfCell : _cells.values()) { - cArray[i] = (CTCell) xssfCell.getCTCell().copy(); - - // we have to copy and re-create the XSSFCell here because the - // elements as otherwise setCArray below invalidates all the columns! - // see Bug 56170, XMLBeans seems to always release previous objects - // in the CArray, so we need to provide completely new ones here! - //_cells.put(entry.getKey(), new XSSFCell(this, cArray[i])); - xssfCell.setCTCell(cArray[i]); - i++; - } - - _row.setCArray(cArray); - } - } - - /** - * @return formatted xml representation of this row - */ - @Override - public String toString(){ - return _row.toString(); - } - - /** - * update cell references when shifting rows - * - * @param n the number of rows to move - */ - protected void shift(int n) { - int rownum = getRowNum() + n; - CalculationChain calcChain = _sheet.getWorkbook().getCalculationChain(); - int sheetId = (int)_sheet.sheet.getSheetId(); - String msg = "Row[rownum="+getRowNum()+"] contains cell(s) included in a multi-cell array formula. " + - "You cannot change part of an array."; - for(Cell c : this){ - XSSFCell cell = (XSSFCell)c; - if(cell.isPartOfArrayFormulaGroup()){ - cell.notifyArrayFormulaChanging(msg); - } - - //remove the reference in the calculation chain - if(calcChain != null) calcChain.removeItem(sheetId, cell.getReference()); - - CTCell ctCell = cell.getCTCell(); - String r = new CellReference(rownum, cell.getColumnIndex()).formatAsString(); - ctCell.setR(r); - } - setRowNum(rownum); - } - - /** - * Copy the cells from srcRow to this row - * If this row is not a blank row, this will merge the two rows, overwriting - * the cells in this row with the cells in srcRow - * If srcRow is null, overwrite cells in destination row with blank values, styles, etc per cell copy policy - * srcRow may be from a different sheet in the same workbook - * @param srcRow the rows to copy from - * @param policy the policy to determine what gets copied - */ - @Beta - public void copyRowFrom(Row srcRow, CellCopyPolicy policy) { - if (srcRow == null) { - // srcRow is blank. Overwrite cells with blank values, blank styles, etc per cell copy policy - for (Cell destCell : this) { - final XSSFCell srcCell = null; - // FIXME: remove type casting when copyCellFrom(Cell, CellCopyPolicy) is added to Cell interface - ((XSSFCell)destCell).copyCellFrom(srcCell, policy); - } - - if (policy.isCopyMergedRegions()) { - // Remove MergedRegions in dest row - final int destRowNum = getRowNum(); - int index = 0; - final Set indices = new HashSet(); - for (CellRangeAddress destRegion : getSheet().getMergedRegions()) { - if (destRowNum == destRegion.getFirstRow() && destRowNum == destRegion.getLastRow()) { - indices.add(index); - } - index++; - } - getSheet().removeMergedRegions(indices); - } - - if (policy.isCopyRowHeight()) { - // clear row height - setHeight((short)-1); - } - - } - else { - for (final Cell c : srcRow){ - final XSSFCell srcCell = (XSSFCell)c; - final XSSFCell destCell = createCell(srcCell.getColumnIndex(), srcCell.getCellTypeEnum()); - destCell.copyCellFrom(srcCell, policy); - } - - final XSSFRowShifter rowShifter = new XSSFRowShifter(_sheet); - final int sheetIndex = _sheet.getWorkbook().getSheetIndex(_sheet); - final String sheetName = _sheet.getWorkbook().getSheetName(sheetIndex); - final int srcRowNum = srcRow.getRowNum(); - final int destRowNum = getRowNum(); - final int rowDifference = destRowNum - srcRowNum; - final FormulaShifter shifter = FormulaShifter.createForRowCopy(sheetIndex, sheetName, srcRowNum, srcRowNum, rowDifference, SpreadsheetVersion.EXCEL2007); - rowShifter.updateRowFormulas(this, shifter); - - // Copy merged regions that are fully contained on the row - // FIXME: is this something that rowShifter could be doing? - if (policy.isCopyMergedRegions()) { - for (CellRangeAddress srcRegion : srcRow.getSheet().getMergedRegions()) { - if (srcRowNum == srcRegion.getFirstRow() && srcRowNum == srcRegion.getLastRow()) { - CellRangeAddress destRegion = srcRegion.copy(); - destRegion.setFirstRow(destRowNum); - destRegion.setLastRow(destRowNum); - getSheet().addMergedRegion(destRegion); - } - } - } - - if (policy.isCopyRowHeight()) { - setHeight(srcRow.getHeight()); - } - } - } - - @Override - public int getOutlineLevel() { - return _row.getOutlineLevel(); - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFShape.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFShape.java deleted file mode 100644 index 886d2a923..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFShape.java +++ /dev/null @@ -1,143 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import org.apache.poi.ss.usermodel.Shape; -import org.openxmlformats.schemas.drawingml.x2006.main.CTLineProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTNoFillProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPresetLineDashProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTSRgbColor; -import org.openxmlformats.schemas.drawingml.x2006.main.CTShapeProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTSolidColorFillProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.STPresetLineDashVal; - -/** - * Represents a shape in a SpreadsheetML drawing. - */ -public abstract class XSSFShape implements Shape { - public static final int EMU_PER_PIXEL = 9525; - public static final int EMU_PER_POINT = 12700; - - public static final int POINT_DPI = 72; - public static final int PIXEL_DPI = 96; - - /** - * Parent drawing - */ - protected XSSFDrawing drawing; - - /** - * The parent shape, always not-null for shapes in groups - */ - protected XSSFShapeGroup parent; - - /** - * anchor that is used by this shape - */ - protected XSSFAnchor anchor; - - /** - * Return the drawing that owns this shape - * - * @return the parent drawing that owns this shape - */ - public XSSFDrawing getDrawing(){ - return drawing; - } - - @Override - public XSSFShapeGroup getParent() - { - return parent; - } - - /** - * @return the anchor that is used by this shape. - */ - @Override - public XSSFAnchor getAnchor() - { - return anchor; - } - - /** - * Returns xml bean with shape properties. - * - * @return xml bean with shape properties. - */ - protected abstract CTShapeProperties getShapeProperties(); - - @Override - public boolean isNoFill() { - return getShapeProperties().isSetNoFill(); - } - - @Override - public void setNoFill(boolean noFill) { - CTShapeProperties props = getShapeProperties(); - //unset solid and pattern fills if they are set - if (props.isSetPattFill()) props.unsetPattFill(); - if (props.isSetSolidFill()) props.unsetSolidFill(); - - props.setNoFill(CTNoFillProperties.Factory.newInstance()); - } - - @Override - public void setFillColor(int red, int green, int blue) { - CTShapeProperties props = getShapeProperties(); - CTSolidColorFillProperties fill = props.isSetSolidFill() ? props.getSolidFill() : props.addNewSolidFill(); - CTSRgbColor rgb = CTSRgbColor.Factory.newInstance(); - rgb.setVal(new byte[]{(byte)red, (byte)green, (byte)blue}); - fill.setSrgbClr(rgb); - } - - @Override - public void setLineStyleColor( int red, int green, int blue ) { - CTShapeProperties props = getShapeProperties(); - CTLineProperties ln = props.isSetLn() ? props.getLn() : props.addNewLn(); - CTSolidColorFillProperties fill = ln.isSetSolidFill() ? ln.getSolidFill() : ln.addNewSolidFill(); - CTSRgbColor rgb = CTSRgbColor.Factory.newInstance(); - rgb.setVal(new byte[]{(byte)red, (byte)green, (byte)blue}); - fill.setSrgbClr(rgb); - } - - /** - * Specifies the width to be used for the underline stroke. - * - * @param lineWidth width in points - */ - public void setLineWidth( double lineWidth ) { - CTShapeProperties props = getShapeProperties(); - CTLineProperties ln = props.isSetLn() ? props.getLn() : props.addNewLn(); - ln.setW((int)(lineWidth*EMU_PER_POINT)); - } - - /** - * Sets the line style. - * - * @param lineStyle - */ - public void setLineStyle( int lineStyle ) { - CTShapeProperties props = getShapeProperties(); - CTLineProperties ln = props.isSetLn() ? props.getLn() : props.addNewLn(); - CTPresetLineDashProperties dashStyle = CTPresetLineDashProperties.Factory.newInstance(); - dashStyle.setVal(STPresetLineDashVal.Enum.forInt(lineStyle+1)); - ln.setPrstDash(dashStyle); - } - -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFShapeGroup.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFShapeGroup.java deleted file mode 100644 index 60e090456..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFShapeGroup.java +++ /dev/null @@ -1,236 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import java.util.Iterator; - -import org.apache.poi.openxml4j.opc.PackageRelationship; -import org.apache.poi.ss.usermodel.ShapeContainer; -import org.apache.poi.util.Internal; -import org.openxmlformats.schemas.drawingml.x2006.main.CTGroupShapeProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTGroupTransform2D; -import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPoint2D; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D; -import org.openxmlformats.schemas.drawingml.x2006.main.CTShapeProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTransform2D; -import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTConnector; -import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTGroupShape; -import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTGroupShapeNonVisual; -import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTPicture; -import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTShape; - -/** - * This object specifies a group shape that represents many shapes grouped together. This shape is to be treated - * just as if it were a regular shape but instead of being described by a single geometry it is made up of all the - * shape geometries encompassed within it. Within a group shape each of the shapes that make up the group are - * specified just as they normally would. - */ -public final class XSSFShapeGroup extends XSSFShape implements ShapeContainer { - private static CTGroupShape prototype = null; - - private CTGroupShape ctGroup; - - /** - * Construct a new XSSFSimpleShape object. - * - * @param drawing the XSSFDrawing that owns this shape - * @param ctGroup the XML bean that stores this group content - */ - protected XSSFShapeGroup(XSSFDrawing drawing, CTGroupShape ctGroup) { - this.drawing = drawing; - this.ctGroup = ctGroup; - } - - /** - * Initialize default structure of a new shape group - */ - protected static CTGroupShape prototype() { - if (prototype == null) { - CTGroupShape shape = CTGroupShape.Factory.newInstance(); - - CTGroupShapeNonVisual nv = shape.addNewNvGrpSpPr(); - CTNonVisualDrawingProps nvpr = nv.addNewCNvPr(); - nvpr.setId(0); - nvpr.setName("Group 0"); - nv.addNewCNvGrpSpPr(); - CTGroupShapeProperties sp = shape.addNewGrpSpPr(); - CTGroupTransform2D t2d = sp.addNewXfrm(); - CTPositiveSize2D p1 = t2d.addNewExt(); - p1.setCx(0); - p1.setCy(0); - CTPoint2D p2 = t2d.addNewOff(); - p2.setX(0); - p2.setY(0); - CTPositiveSize2D p3 = t2d.addNewChExt(); - p3.setCx(0); - p3.setCy(0); - CTPoint2D p4 = t2d.addNewChOff(); - p4.setX(0); - p4.setY(0); - - prototype = shape; - } - return prototype; - } - - /** - * Constructs a textbox. - * - * @param anchor the child anchor describes how this shape is attached - * to the group. - * @return the newly created textbox. - */ - public XSSFTextBox createTextbox(XSSFChildAnchor anchor){ - CTShape ctShape = ctGroup.addNewSp(); - ctShape.set(XSSFSimpleShape.prototype()); - - XSSFTextBox shape = new XSSFTextBox(getDrawing(), ctShape); - shape.parent = this; - shape.anchor = anchor; - shape.getCTShape().getSpPr().setXfrm(anchor.getCTTransform2D()); - return shape; - - } - /** - * Creates a simple shape. This includes such shapes as lines, rectangles, - * and ovals. - * - * @param anchor the child anchor describes how this shape is attached - * to the group. - * @return the newly created shape. - */ - public XSSFSimpleShape createSimpleShape(XSSFChildAnchor anchor) { - CTShape ctShape = ctGroup.addNewSp(); - ctShape.set(XSSFSimpleShape.prototype()); - - XSSFSimpleShape shape = new XSSFSimpleShape(getDrawing(), ctShape); - shape.parent = this; - shape.anchor = anchor; - shape.getCTShape().getSpPr().setXfrm(anchor.getCTTransform2D()); - return shape; - } - - /** - * Creates a simple shape. This includes such shapes as lines, rectangles, - * and ovals. - * - * @param anchor the child anchor describes how this shape is attached - * to the group. - * @return the newly created shape. - */ - public XSSFConnector createConnector(XSSFChildAnchor anchor) { - CTConnector ctShape = ctGroup.addNewCxnSp(); - ctShape.set(XSSFConnector.prototype()); - - XSSFConnector shape = new XSSFConnector(getDrawing(), ctShape); - shape.parent = this; - shape.anchor = anchor; - shape.getCTConnector().getSpPr().setXfrm(anchor.getCTTransform2D()); - return shape; - } - - /** - * Creates a picture. - * - * @param anchor the client anchor describes how this picture is attached to the sheet. - * @param pictureIndex the index of the picture in the workbook collection of pictures, - * {@link XSSFWorkbook#getAllPictures()} . - * @return the newly created picture shape. - */ - public XSSFPicture createPicture(XSSFClientAnchor anchor, int pictureIndex) { - PackageRelationship rel = getDrawing().addPictureReference(pictureIndex); - - CTPicture ctShape = ctGroup.addNewPic(); - ctShape.set(XSSFPicture.prototype()); - - XSSFPicture shape = new XSSFPicture(getDrawing(), ctShape); - shape.parent = this; - shape.anchor = anchor; - shape.setPictureReference(rel); - return shape; - } - - /** - * Creates a group shape. - * - * @param anchor the client anchor describes how this group is attached to the group. - * @return the newly created group shape. - */ - public XSSFShapeGroup createGroup(XSSFChildAnchor anchor) { - CTGroupShape ctShape = ctGroup.addNewGrpSp(); - ctShape.set(prototype()); - - XSSFShapeGroup shape = new XSSFShapeGroup(getDrawing(), ctShape); - shape.parent = this; - shape.anchor = anchor; - - // TODO: calculate bounding rectangle on anchor and set off/ext correctly - - CTGroupTransform2D xfrm = shape.getCTGroupShape().getGrpSpPr().getXfrm(); - CTTransform2D t2 = anchor.getCTTransform2D(); - xfrm.setOff(t2.getOff()); - xfrm.setExt(t2.getExt()); - // child offset is left to 0,0 - xfrm.setChExt(t2.getExt()); - xfrm.setFlipH(t2.getFlipH()); - xfrm.setFlipV(t2.getFlipV()); - - return shape; - } - - @Internal - public CTGroupShape getCTGroupShape() { - return ctGroup; - } - - /** - * Sets the coordinate space of this group. All children are constrained - * to these coordinates. - */ - public void setCoordinates(int x1, int y1, int x2, int y2) { - CTGroupTransform2D t2d = ctGroup.getGrpSpPr().getXfrm(); - CTPoint2D off = t2d.getOff(); - off.setX(x1); - off.setY(y1); - CTPositiveSize2D ext = t2d.getExt(); - ext.setCx(x2); - ext.setCy(y2); - - CTPoint2D chOff = t2d.getChOff(); - chOff.setX(x1); - chOff.setY(y1); - CTPositiveSize2D chExt = t2d.getChExt(); - chExt.setCx(x2); - chExt.setCy(y2); - } - - protected CTShapeProperties getShapeProperties() { - throw new IllegalStateException("Not supported for shape group"); - } - - @Override - public Iterator iterator() { - return getDrawing().getShapes(this).iterator(); - } - - @Override - public String getShapeName() { - return ctGroup.getNvGrpSpPr().getCNvPr().getName(); - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFSheet.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFSheet.java deleted file mode 100644 index ddf8458d0..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFSheet.java +++ /dev/null @@ -1,4504 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import static org.apache.poi.POIXMLTypeLoader.DEFAULT_XML_OPTIONS; -import static org.apache.poi.xssf.usermodel.helpers.XSSFPasswordHelper.setPassword; -import static org.apache.poi.xssf.usermodel.helpers.XSSFPasswordHelper.validatePassword; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.SortedMap; -import java.util.TreeMap; - -import javax.xml.namespace.QName; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamReader; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.POIXMLException; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.exceptions.PartAlreadyExistsException; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.opc.PackageRelationship; -import org.apache.poi.openxml4j.opc.PackageRelationshipCollection; -import org.apache.poi.openxml4j.opc.TargetMode; -import org.apache.poi.poifs.crypt.HashAlgorithm; -import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.ss.formula.FormulaShifter; -import org.apache.poi.ss.formula.SheetNameFormatter; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellCopyPolicy; -import org.apache.poi.ss.usermodel.CellRange; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.DataValidation; -import org.apache.poi.ss.usermodel.DataValidationHelper; -import org.apache.poi.ss.usermodel.Footer; -import org.apache.poi.ss.usermodel.Header; -import org.apache.poi.ss.usermodel.IgnoredErrorType; -import org.apache.poi.ss.usermodel.IndexedColors; -import org.apache.poi.ss.usermodel.Name; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Table; -import org.apache.poi.ss.util.AreaReference; -import org.apache.poi.ss.util.CellAddress; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.CellRangeAddressList; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.ss.util.PaneInformation; -import org.apache.poi.ss.util.SSCellRange; -import org.apache.poi.ss.util.SheetUtil; -import org.apache.poi.util.Beta; -import org.apache.poi.util.Internal; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.util.Removal; -import org.apache.poi.xssf.model.CommentsTable; -import org.apache.poi.xssf.usermodel.XSSFPivotTable.PivotTableReferenceConfigurator; -import org.apache.poi.xssf.usermodel.helpers.ColumnHelper; -import org.apache.poi.xssf.usermodel.helpers.XSSFIgnoredErrorHelper; -import org.apache.poi.xssf.usermodel.helpers.XSSFRowShifter; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlOptions; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.*; - -/** - * High level representation of a SpreadsheetML worksheet. - * - *

    - * Sheets are the central structures within a workbook, and are where a user does most of his spreadsheet work. - * The most common type of sheet is the worksheet, which is represented as a grid of cells. Worksheet cells can - * contain text, numbers, dates, and formulas. Cells can also be formatted. - *

    - */ -public class XSSFSheet extends POIXMLDocumentPart implements Sheet { - private static final POILogger logger = POILogFactory.getLogger(XSSFSheet.class); - - private static final double DEFAULT_ROW_HEIGHT = 15.0; - private static final double DEFAULT_MARGIN_HEADER = 0.3; - private static final double DEFAULT_MARGIN_FOOTER = 0.3; - private static final double DEFAULT_MARGIN_TOP = 0.75; - private static final double DEFAULT_MARGIN_BOTTOM = 0.75; - private static final double DEFAULT_MARGIN_LEFT = 0.7; - private static final double DEFAULT_MARGIN_RIGHT = 0.7; - public static final int TWIPS_PER_POINT = 20; - - //TODO make the two variable below private! - protected CTSheet sheet; - protected CTWorksheet worksheet; - - private final SortedMap _rows = new TreeMap(); - private List hyperlinks; - private ColumnHelper columnHelper; - private CommentsTable sheetComments; - /** - * cache of master shared formulas in this sheet. - * Master shared formula is the first formula in a group of shared formulas is saved in the f element. - */ - private Map sharedFormulas; - private SortedMap tables; - private List arrayFormulas; - private XSSFDataValidationHelper dataValidationHelper; - - /** - * Creates new XSSFSheet - called by XSSFWorkbook to create a sheet from scratch. - * - * @see org.apache.poi.xssf.usermodel.XSSFWorkbook#createSheet() - */ - protected XSSFSheet() { - super(); - dataValidationHelper = new XSSFDataValidationHelper(this); - onDocumentCreate(); - } - - /** - * Creates an XSSFSheet representing the given package part and relationship. - * Should only be called by XSSFWorkbook when reading in an existing file. - * - * @param part - The package part that holds xml data representing this sheet. - * - * @since POI 3.14-Beta1 - */ - protected XSSFSheet(PackagePart part) { - super(part); - dataValidationHelper = new XSSFDataValidationHelper(this); - } - - /** - * Returns the parent XSSFWorkbook - * - * @return the parent XSSFWorkbook - */ - @Override - public XSSFWorkbook getWorkbook() { - return (XSSFWorkbook)getParent(); - } - - /** - * Initialize worksheet data when reading in an exisiting file. - */ - @Override - protected void onDocumentRead() { - try { - read(getPackagePart().getInputStream()); - } catch (IOException e){ - throw new POIXMLException(e); - } - } - - protected void read(InputStream is) throws IOException { - try { - worksheet = WorksheetDocument.Factory.parse(is, DEFAULT_XML_OPTIONS).getWorksheet(); - } catch (XmlException e){ - throw new POIXMLException(e); - } - - initRows(worksheet); - columnHelper = new ColumnHelper(worksheet); - // Look for bits we're interested in - for(RelationPart rp : getRelationParts()){ - POIXMLDocumentPart p = rp.getDocumentPart(); - if(p instanceof CommentsTable) { - sheetComments = (CommentsTable)p; - } - if(p instanceof XSSFTable) { - tables.put( rp.getRelationship().getId(), (XSSFTable)p ); - } - if(p instanceof XSSFPivotTable) { - getWorkbook().getPivotTables().add((XSSFPivotTable) p); - } - } - - // Process external hyperlinks for the sheet, if there are any - initHyperlinks(); - } - - /** - * Initialize worksheet data when creating a new sheet. - */ - @Override - protected void onDocumentCreate(){ - worksheet = newSheet(); - initRows(worksheet); - columnHelper = new ColumnHelper(worksheet); - hyperlinks = new ArrayList(); - } - - private void initRows(CTWorksheet worksheetParam) { - _rows.clear(); - tables = new TreeMap(); - sharedFormulas = new HashMap(); - arrayFormulas = new ArrayList(); - for (CTRow row : worksheetParam.getSheetData().getRowArray()) { - XSSFRow r = new XSSFRow(row, this); - // Performance optimization: explicit boxing is slightly faster than auto-unboxing, though may use more memory - final Integer rownumI = new Integer(r.getRowNum()); // NOSONAR - _rows.put(rownumI, r); - } - } - - /** - * Read hyperlink relations, link them with CTHyperlink beans in this worksheet - * and initialize the internal array of XSSFHyperlink objects - */ - private void initHyperlinks() { - hyperlinks = new ArrayList(); - - if(!worksheet.isSetHyperlinks()) { - return; - } - - try { - PackageRelationshipCollection hyperRels = - getPackagePart().getRelationshipsByType(XSSFRelation.SHEET_HYPERLINKS.getRelation()); - - // Turn each one into a XSSFHyperlink - for(CTHyperlink hyperlink : worksheet.getHyperlinks().getHyperlinkArray()) { - PackageRelationship hyperRel = null; - if(hyperlink.getId() != null) { - hyperRel = hyperRels.getRelationshipByID(hyperlink.getId()); - } - - hyperlinks.add( new XSSFHyperlink(hyperlink, hyperRel) ); - } - } catch (InvalidFormatException e){ - throw new POIXMLException(e); - } - } - - /** - * Create a new CTWorksheet instance with all values set to defaults - * - * @return a new instance - */ - private static CTWorksheet newSheet(){ - CTWorksheet worksheet = CTWorksheet.Factory.newInstance(); - CTSheetFormatPr ctFormat = worksheet.addNewSheetFormatPr(); - ctFormat.setDefaultRowHeight(DEFAULT_ROW_HEIGHT); - - CTSheetView ctView = worksheet.addNewSheetViews().addNewSheetView(); - ctView.setWorkbookViewId(0); - - worksheet.addNewDimension().setRef("A1"); - - worksheet.addNewSheetData(); - - CTPageMargins ctMargins = worksheet.addNewPageMargins(); - ctMargins.setBottom(DEFAULT_MARGIN_BOTTOM); - ctMargins.setFooter(DEFAULT_MARGIN_FOOTER); - ctMargins.setHeader(DEFAULT_MARGIN_HEADER); - ctMargins.setLeft(DEFAULT_MARGIN_LEFT); - ctMargins.setRight(DEFAULT_MARGIN_RIGHT); - ctMargins.setTop(DEFAULT_MARGIN_TOP); - - return worksheet; - } - - /** - * Provide access to the CTWorksheet bean holding this sheet's data - * - * @return the CTWorksheet bean holding this sheet's data - */ - @Internal - public CTWorksheet getCTWorksheet() { - return this.worksheet; - } - - public ColumnHelper getColumnHelper() { - return columnHelper; - } - - /** - * Returns the name of this sheet - * - * @return the name of this sheet - */ - @Override - public String getSheetName() { - return sheet.getName(); - } - - /** - * Adds a merged region of cells on a sheet. - * - * @param region to merge - * @return index of this region - * @throws IllegalArgumentException if region contains fewer than 2 cells - * @throws IllegalStateException if region intersects with a multi-cell array formula - * @throws IllegalStateException if region intersects with an existing region on this sheet - */ - @Override - public int addMergedRegion(CellRangeAddress region) { - return addMergedRegion(region, true); - } - - /** - * Adds a merged region of cells (hence those cells form one). - * Skips validation. It is possible to create overlapping merged regions - * or create a merged region that intersects a multi-cell array formula - * with this formula, which may result in a corrupt workbook. - * - * To check for merged regions overlapping array formulas or other merged regions - * after addMergedRegionUnsafe has been called, call {@link #validateMergedRegions()}, which runs in O(n^2) time. - * - * @param region to merge - * @return index of this region - * @throws IllegalArgumentException if region contains fewer than 2 cells - */ - @Override - public int addMergedRegionUnsafe(CellRangeAddress region) { - return addMergedRegion(region, false); - } - - /** - * Adds a merged region of cells (hence those cells form one). - * If validate is true, check to make sure adding the merged region to the sheet doesn't create a corrupt workbook - * If validate is false, skips the expensive merged region checks, but may produce a corrupt workbook. - * - * @param region to merge - * @param validate whether to validate merged region - * @return index of this region - * @throws IllegalArgumentException if region contains fewer than 2 cells (this check is inexpensive and is performed regardless of validate) - * @throws IllegalStateException if region intersects with a multi-cell array formula - * @throws IllegalStateException if region intersects with an existing region on this sheet - */ - private int addMergedRegion(CellRangeAddress region, boolean validate) { - if (region.getNumberOfCells() < 2) { - throw new IllegalArgumentException("Merged region " + region.formatAsString() + " must contain 2 or more cells"); - } - region.validate(SpreadsheetVersion.EXCEL2007); - - if (validate) { - // throw IllegalStateException if the argument CellRangeAddress intersects with - // a multi-cell array formula defined in this sheet - validateArrayFormulas(region); - - // Throw IllegalStateException if the argument CellRangeAddress intersects with - // a merged region already in this sheet - validateMergedRegions(region); - } - - CTMergeCells ctMergeCells = worksheet.isSetMergeCells() ? worksheet.getMergeCells() : worksheet.addNewMergeCells(); - CTMergeCell ctMergeCell = ctMergeCells.addNewMergeCell(); - ctMergeCell.setRef(region.formatAsString()); - return ctMergeCells.sizeOfMergeCellArray(); - } - - /** - * Verify that the candidate region does not intersect with an existing multi-cell array formula in this sheet - * - * @param region a region that is validated. - * @throws IllegalStateException if candidate region intersects an existing array formula in this sheet - */ - private void validateArrayFormulas(CellRangeAddress region) { - // FIXME: this may be faster if it looped over array formulas directly rather than looping over each cell in - // the region and searching if that cell belongs to an array formula - int firstRow = region.getFirstRow(); - int firstColumn = region.getFirstColumn(); - int lastRow = region.getLastRow(); - int lastColumn = region.getLastColumn(); - // for each cell in sheet, if cell belongs to an array formula, check if merged region intersects array formula cells - for (int rowIn = firstRow; rowIn <= lastRow; rowIn++) { - XSSFRow row = getRow(rowIn); - if (row == null) { - continue; - } - - for (int colIn = firstColumn; colIn <= lastColumn; colIn++) { - XSSFCell cell = row.getCell(colIn); - if (cell == null) { - continue; - } - - if (cell.isPartOfArrayFormulaGroup()) { - CellRangeAddress arrayRange = cell.getArrayFormulaRange(); - if (arrayRange.getNumberOfCells() > 1 && region.intersects(arrayRange)) { - String msg = "The range " + region.formatAsString() + " intersects with a multi-cell array formula. " + - "You cannot merge cells of an array."; - throw new IllegalStateException(msg); - } - } - } - } - } - - /** - * Verify that none of the merged regions intersect a multi-cell array formula in this sheet - * - * @throws IllegalStateException if candidate region intersects an existing array formula in this sheet - */ - private void checkForMergedRegionsIntersectingArrayFormulas() { - for (CellRangeAddress region : getMergedRegions()) { - validateArrayFormulas(region); - } - } - - /** - * Verify that candidate region does not intersect with an existing merged region in this sheet - * - * @param candidateRegion - * @throws IllegalStateException if candidate region intersects an existing merged region in this sheet (or candidateRegion is already merged in this sheet) - */ - private void validateMergedRegions(CellRangeAddress candidateRegion) { - for (final CellRangeAddress existingRegion : getMergedRegions()) { - if (existingRegion.intersects(candidateRegion)) { - throw new IllegalStateException("Cannot add merged region " + candidateRegion.formatAsString() + - " to sheet because it overlaps with an existing merged region (" + existingRegion.formatAsString() + ")."); - } - } - } - - /** - * Verify that no merged regions intersect another merged region in this sheet. - * - * @throws IllegalStateException if at least one region intersects with another merged region in this sheet - */ - private void checkForIntersectingMergedRegions() { - final List regions = getMergedRegions(); - final int size = regions.size(); - for (int i=0; i < size; i++) { - final CellRangeAddress region = regions.get(i); - for (final CellRangeAddress other : regions.subList(i+1, regions.size())) { - if (region.intersects(other)) { - String msg = "The range " + region.formatAsString() + - " intersects with another merged region " + - other.formatAsString() + " in this sheet"; - throw new IllegalStateException(msg); - } - } - } - } - - /** - * Verify that merged regions do not intersect multi-cell array formulas and - * no merged regions intersect another merged region in this sheet. - * - * @throws IllegalStateException if region intersects with a multi-cell array formula - * @throws IllegalStateException if at least one region intersects with another merged region in this sheet - */ - @Override - public void validateMergedRegions() { - checkForMergedRegionsIntersectingArrayFormulas(); - checkForIntersectingMergedRegions(); - } - - /** - * Adjusts the column width to fit the contents. - * - * This process can be relatively slow on large sheets, so this should - * normally only be called once per column, at the end of your - * processing. - * - * @param column the column index - */ - @Override - public void autoSizeColumn(int column) { - autoSizeColumn(column, false); - } - - /** - * Adjusts the column width to fit the contents. - *

    - * This process can be relatively slow on large sheets, so this should - * normally only be called once per column, at the end of your - * processing. - *

    - * You can specify whether the content of merged cells should be considered or ignored. - * Default is to ignore merged cells. - * - * @param column the column index - * @param useMergedCells whether to use the contents of merged cells when calculating the width of the column - */ - @Override - public void autoSizeColumn(int column, boolean useMergedCells) { - double width = SheetUtil.getColumnWidth(this, column, useMergedCells); - - if (width != -1) { - width *= 256; - int maxColumnWidth = 255*256; // The maximum column width for an individual cell is 255 characters - if (width > maxColumnWidth) { - width = maxColumnWidth; - } - setColumnWidth(column, (int)(width)); - columnHelper.setColBestFit(column, true); - } - } - - /** - * Return the sheet's existing drawing, or null if there isn't yet one. - * - * Use {@link #createDrawingPatriarch()} to get or create - * - * @return a SpreadsheetML drawing - */ - @Override - public XSSFDrawing getDrawingPatriarch() { - CTDrawing ctDrawing = getCTDrawing(); - if (ctDrawing != null) { - // Search the referenced drawing in the list of the sheet's relations - for (RelationPart rp : getRelationParts()){ - POIXMLDocumentPart p = rp.getDocumentPart(); - if (p instanceof XSSFDrawing) { - XSSFDrawing dr = (XSSFDrawing)p; - String drId = rp.getRelationship().getId(); - if (drId.equals(ctDrawing.getId())){ - return dr; - } - break; - } - } - logger.log(POILogger.ERROR, "Can't find drawing with id=" + ctDrawing.getId() + " in the list of the sheet's relationships"); - } - return null; - } - - /** - * Create a new SpreadsheetML drawing. If this sheet already contains a drawing - return that. - * - * @return a SpreadsheetML drawing - */ - @Override - public XSSFDrawing createDrawingPatriarch() { - CTDrawing ctDrawing = getCTDrawing(); - if (ctDrawing != null) { - return getDrawingPatriarch(); - } - - // Default drawingNumber = #drawings.size() + 1 - int drawingNumber = getPackagePart().getPackage().getPartsByContentType(XSSFRelation.DRAWINGS.getContentType()).size() + 1; - drawingNumber = getNextPartNumber(XSSFRelation.DRAWINGS, drawingNumber); - RelationPart rp = createRelationship(XSSFRelation.DRAWINGS, XSSFFactory.getInstance(), drawingNumber, false); - XSSFDrawing drawing = rp.getDocumentPart(); - String relId = rp.getRelationship().getId(); - - //add CT_Drawing element which indicates that this sheet contains drawing components built on the drawingML platform. - //The relationship Id references the part containing the drawingML definitions. - ctDrawing = worksheet.addNewDrawing(); - ctDrawing.setId(relId); - - // Return the newly created drawing - return drawing; - } - - /** - * Get VML drawing for this sheet (aka 'legacy' drawig) - * - * @param autoCreate if true, then a new VML drawing part is created - * - * @return the VML drawing of null if the drawing was not found and autoCreate=false - */ - protected XSSFVMLDrawing getVMLDrawing(boolean autoCreate) { - XSSFVMLDrawing drawing = null; - CTLegacyDrawing ctDrawing = getCTLegacyDrawing(); - if(ctDrawing == null) { - if(autoCreate) { - //drawingNumber = #drawings.size() + 1 - int drawingNumber = getPackagePart().getPackage().getPartsByContentType(XSSFRelation.VML_DRAWINGS.getContentType()).size() + 1; - RelationPart rp = createRelationship(XSSFRelation.VML_DRAWINGS, XSSFFactory.getInstance(), drawingNumber, false); - drawing = rp.getDocumentPart(); - String relId = rp.getRelationship().getId(); - - //add CTLegacyDrawing element which indicates that this sheet contains drawing components built on the drawingML platform. - //The relationship Id references the part containing the drawing definitions. - ctDrawing = worksheet.addNewLegacyDrawing(); - ctDrawing.setId(relId); - } - } else { - //search the referenced drawing in the list of the sheet's relations - final String id = ctDrawing.getId(); - for (RelationPart rp : getRelationParts()){ - POIXMLDocumentPart p = rp.getDocumentPart(); - if(p instanceof XSSFVMLDrawing) { - XSSFVMLDrawing dr = (XSSFVMLDrawing)p; - String drId = rp.getRelationship().getId(); - if (drId.equals(id)) { - drawing = dr; - break; - } - // do not break here since drawing has not been found yet (see bug 52425) - } - } - if(drawing == null){ - logger.log(POILogger.ERROR, "Can't find VML drawing with id=" + id + " in the list of the sheet's relationships"); - } - } - return drawing; - } - - protected CTDrawing getCTDrawing() { - return worksheet.getDrawing(); - } - protected CTLegacyDrawing getCTLegacyDrawing() { - return worksheet.getLegacyDrawing(); - } - - /** - * Creates a split (freezepane). Any existing freezepane or split pane is overwritten. - * @param colSplit Horizontal position of split. - * @param rowSplit Vertical position of split. - */ - @Override - public void createFreezePane(int colSplit, int rowSplit) { - createFreezePane( colSplit, rowSplit, colSplit, rowSplit ); - } - - /** - * Creates a split (freezepane). Any existing freezepane or split pane is overwritten. - * - *

    - * If both colSplit and rowSplit are zero then the existing freeze pane is removed - *

    - * - * @param colSplit Horizontal position of split. - * @param rowSplit Vertical position of split. - * @param leftmostColumn Left column visible in right pane. - * @param topRow Top row visible in bottom pane - */ - @Override - public void createFreezePane(int colSplit, int rowSplit, int leftmostColumn, int topRow) { - CTSheetView ctView = getDefaultSheetView(); - - // If both colSplit and rowSplit are zero then the existing freeze pane is removed - if(colSplit == 0 && rowSplit == 0){ - if(ctView.isSetPane()) { - ctView.unsetPane(); - } - ctView.setSelectionArray(null); - return; - } - - if (!ctView.isSetPane()) { - ctView.addNewPane(); - } - CTPane pane = ctView.getPane(); - - if (colSplit > 0) { - pane.setXSplit(colSplit); - } else { - if(pane.isSetXSplit()) { - pane.unsetXSplit(); - } - } - if (rowSplit > 0) { - pane.setYSplit(rowSplit); - } else { - if(pane.isSetYSplit()) { - pane.unsetYSplit(); - } - } - - pane.setState(STPaneState.FROZEN); - if (rowSplit == 0) { - pane.setTopLeftCell(new CellReference(0, leftmostColumn).formatAsString()); - pane.setActivePane(STPane.TOP_RIGHT); - } else if (colSplit == 0) { - pane.setTopLeftCell(new CellReference(topRow, 0).formatAsString()); - pane.setActivePane(STPane.BOTTOM_LEFT); - } else { - pane.setTopLeftCell(new CellReference(topRow, leftmostColumn).formatAsString()); - pane.setActivePane(STPane.BOTTOM_RIGHT); - } - - ctView.setSelectionArray(null); - CTSelection sel = ctView.addNewSelection(); - sel.setPane(pane.getActivePane()); - } - - /** - * Create a new row within the sheet and return the high level representation - * - * Note: If a row already exists at this position, it is removed/overwritten and - * any existing cell is removed! - * - * @param rownum row number - * @return High level {@link XSSFRow} object representing a row in the sheet - * @see #removeRow(org.apache.poi.ss.usermodel.Row) - */ - @Override - public XSSFRow createRow(int rownum) { - // Performance optimization: explicit boxing is slightly faster than auto-unboxing, though may use more memory - final Integer rownumI = new Integer(rownum); // NOSONAR - CTRow ctRow; - XSSFRow prev = _rows.get(rownumI); - if(prev != null){ - // the Cells in an existing row are invalidated on-purpose, in order to clean up correctly, we - // need to call the remove, so things like ArrayFormulas and CalculationChain updates are done - // correctly. - // We remove the cell this way as the internal cell-list is changed by the remove call and - // thus would cause ConcurrentModificationException otherwise - while(prev.getFirstCellNum() != -1) { - prev.removeCell(prev.getCell(prev.getFirstCellNum())); - } - - ctRow = prev.getCTRow(); - ctRow.set(CTRow.Factory.newInstance()); - } else { - if(_rows.isEmpty() || rownum > _rows.lastKey()) { - // we can append the new row at the end - ctRow = worksheet.getSheetData().addNewRow(); - } else { - // get number of rows where row index < rownum - // --> this tells us where our row should go - int idx = _rows.headMap(rownumI).size(); - ctRow = worksheet.getSheetData().insertNewRow(idx); - } - } - XSSFRow r = new XSSFRow(ctRow, this); - r.setRowNum(rownum); - _rows.put(rownumI, r); - return r; - } - - /** - * Creates a split pane. Any existing freezepane or split pane is overwritten. - * @param xSplitPos Horizontal position of split (in 1/20th of a point). - * @param ySplitPos Vertical position of split (in 1/20th of a point). - * @param topRow Top row visible in bottom pane - * @param leftmostColumn Left column visible in right pane. - * @param activePane Active pane. One of: PANE_LOWER_RIGHT, - * PANE_UPPER_RIGHT, PANE_LOWER_LEFT, PANE_UPPER_LEFT - * @see org.apache.poi.ss.usermodel.Sheet#PANE_LOWER_LEFT - * @see org.apache.poi.ss.usermodel.Sheet#PANE_LOWER_RIGHT - * @see org.apache.poi.ss.usermodel.Sheet#PANE_UPPER_LEFT - * @see org.apache.poi.ss.usermodel.Sheet#PANE_UPPER_RIGHT - */ - @Override - public void createSplitPane(int xSplitPos, int ySplitPos, int leftmostColumn, int topRow, int activePane) { - createFreezePane(xSplitPos, ySplitPos, leftmostColumn, topRow); - getPane().setState(STPaneState.SPLIT); - getPane().setActivePane(STPane.Enum.forInt(activePane)); - } - - /** - * Return cell comment at row, column, if one exists. Otherwise returns null. - * @param row the row where the comment is located - * @param column the column where the comment is located - * @return the cell comment, if one exists. Otherwise return null. - * @deprecated as of 2015-11-23 (circa POI 3.14beta1). Use {@link #getCellComment(CellAddress)} instead. - */ - @Deprecated - @Override - @Removal(version="3.16") - public XSSFComment getCellComment(int row, int column) { - return getCellComment(new CellAddress(row, column)); - } - - /** - * Return cell comment at row, column, if one exists. Otherwise returns null. - * - * @param address the location of the cell comment - * @return the cell comment, if one exists. Otherwise return null. - */ - @Override - public XSSFComment getCellComment(CellAddress address) { - if (sheetComments == null) { - return null; - } - - final int row = address.getRow(); - final int column = address.getColumn(); - - CellAddress ref = new CellAddress(row, column); - CTComment ctComment = sheetComments.getCTComment(ref); - if(ctComment == null) { - return null; - } - - XSSFVMLDrawing vml = getVMLDrawing(false); - return new XSSFComment(sheetComments, ctComment, - vml == null ? null : vml.findCommentShape(row, column)); - } - - /** - * Returns all cell comments on this sheet. - * @return A map of each Comment in the sheet, keyed on the cell address where - * the comment is located. - */ - @Override - public Map getCellComments() { - if (sheetComments == null) { - return Collections.emptyMap(); - } - return sheetComments.getCellComments(); - } - - /** - * Get a Hyperlink in this sheet anchored at row, column - * - * @param row - * @param column - * @return hyperlink if there is a hyperlink anchored at row, column; otherwise returns null - */ - @Override - public XSSFHyperlink getHyperlink(int row, int column) { - return getHyperlink(new CellAddress(row, column)); - } - - /** - * Get a Hyperlink in this sheet located in a cell specified by {code addr} - * - * @param addr The address of the cell containing the hyperlink - * @return hyperlink if there is a hyperlink anchored at {@code addr}; otherwise returns {@code null} - * @since POI 3.15 beta 3 - */ - @Override - public XSSFHyperlink getHyperlink(CellAddress addr) { - String ref = addr.formatAsString(); - for(XSSFHyperlink hyperlink : hyperlinks) { - if(hyperlink.getCellRef().equals(ref)) { - return hyperlink; - } - } - return null; - } - - /** - * Get a list of Hyperlinks in this sheet - * - * @return Hyperlinks for the sheet - */ - @Override - public List getHyperlinkList() { - return Collections.unmodifiableList(hyperlinks); - } - - private int[] getBreaks(CTPageBreak ctPageBreak) { - CTBreak[] brkArray = ctPageBreak.getBrkArray(); - int[] breaks = new int[brkArray.length]; - for (int i = 0 ; i < brkArray.length ; i++) { - breaks[i] = (int) brkArray[i].getId() - 1; - } - return breaks; - } - - private void removeBreak(int index, CTPageBreak ctPageBreak) { - int index1 = index + 1; - CTBreak[] brkArray = ctPageBreak.getBrkArray(); - for (int i = 0 ; i < brkArray.length ; i++) { - if (brkArray[i].getId() == index1) { - ctPageBreak.removeBrk(i); - // TODO: check if we can break here, i.e. if a page can have more than 1 break on the same id - } - } - } - - /** - * Vertical page break information used for print layout view, page layout view, drawing print breaks - * in normal view, and for printing the worksheet. - * - * @return column indexes of all the vertical page breaks, never null - */ - @Override - public int[] getColumnBreaks() { - return worksheet.isSetColBreaks() ? getBreaks(worksheet.getColBreaks()) : new int[0]; - } - - /** - * Get the actual column width (in units of 1/256th of a character width ) - * - *

    - * Note, the returned value is always gerater that {@link #getDefaultColumnWidth()} because the latter does not include margins. - * Actual column width measured as the number of characters of the maximum digit width of the - * numbers 0, 1, 2, ..., 9 as rendered in the normal style's font. There are 4 pixels of margin - * padding (two on each side), plus 1 pixel padding for the gridlines. - *

    - * - * @param columnIndex - the column to set (0-based) - * @return width - the width in units of 1/256th of a character width - */ - @Override - public int getColumnWidth(int columnIndex) { - CTCol col = columnHelper.getColumn(columnIndex, false); - double width = col == null || !col.isSetWidth() ? getDefaultColumnWidth() : col.getWidth(); - return (int)(width*256); - } - - /** - * Get the actual column width in pixels - * - *

    - * Please note, that this method works correctly only for workbooks - * with the default font size (Calibri 11pt for .xlsx). - *

    - */ - @Override - public float getColumnWidthInPixels(int columnIndex) { - float widthIn256 = getColumnWidth(columnIndex); - return (float)(widthIn256/256.0*XSSFWorkbook.DEFAULT_CHARACTER_WIDTH); - } - - /** - * Get the default column width for the sheet (if the columns do not define their own width) in - * characters. - *

    - * Note, this value is different from {@link #getColumnWidth(int)}. The latter is always greater and includes - * 4 pixels of margin padding (two on each side), plus 1 pixel padding for the gridlines. - *

    - * @return column width, default value is 8 - */ - @Override - public int getDefaultColumnWidth() { - CTSheetFormatPr pr = worksheet.getSheetFormatPr(); - return pr == null ? 8 : (int)pr.getBaseColWidth(); - } - - /** - * Get the default row height for the sheet (if the rows do not define their own height) in - * twips (1/20 of a point) - * - * @return default row height - */ - @Override - public short getDefaultRowHeight() { - return (short)(getDefaultRowHeightInPoints() * TWIPS_PER_POINT); - } - - - /** - * Get the default row height for the sheet measued in point size (if the rows do not define their own height). - * - * @return default row height in points - */ - @Override - public float getDefaultRowHeightInPoints() { - CTSheetFormatPr pr = worksheet.getSheetFormatPr(); - return (float)(pr == null ? 0 : pr.getDefaultRowHeight()); - } - - private CTSheetFormatPr getSheetTypeSheetFormatPr() { - return worksheet.isSetSheetFormatPr() ? - worksheet.getSheetFormatPr() : - worksheet.addNewSheetFormatPr(); - } - - /** - * Returns the CellStyle that applies to the given - * (0 based) column, or null if no style has been - * set for that column - */ - @Override - public CellStyle getColumnStyle(int column) { - int idx = columnHelper.getColDefaultStyle(column); - return getWorkbook().getCellStyleAt((short)(idx == -1 ? 0 : idx)); - } - - /** - * Sets whether the worksheet is displayed from right to left instead of from left to right. - * - * @param value true for right to left, false otherwise. - */ - @Override - public void setRightToLeft(boolean value) { - CTSheetView view = getDefaultSheetView(); - view.setRightToLeft(value); - } - - /** - * Whether the text is displayed in right-to-left mode in the window - * - * @return whether the text is displayed in right-to-left mode in the window - */ - @Override - public boolean isRightToLeft() { - CTSheetView view = getDefaultSheetView(); - return view != null && view.getRightToLeft(); - } - - /** - * Get whether to display the guts or not, - * default value is true - * - * @return boolean - guts or no guts - */ - @Override - public boolean getDisplayGuts() { - CTSheetPr sheetPr = getSheetTypeSheetPr(); - CTOutlinePr outlinePr = sheetPr.getOutlinePr() == null ? CTOutlinePr.Factory.newInstance() : sheetPr.getOutlinePr(); - return outlinePr.getShowOutlineSymbols(); - } - - /** - * Set whether to display the guts or not - * - * @param value - guts or no guts - */ - @Override - public void setDisplayGuts(boolean value) { - CTSheetPr sheetPr = getSheetTypeSheetPr(); - CTOutlinePr outlinePr = sheetPr.getOutlinePr() == null ? sheetPr.addNewOutlinePr() : sheetPr.getOutlinePr(); - outlinePr.setShowOutlineSymbols(value); - } - - /** - * Gets the flag indicating whether the window should show 0 (zero) in cells containing zero value. - * When false, cells with zero value appear blank instead of showing the number zero. - * - * @return whether all zero values on the worksheet are displayed - */ - @Override - public boolean isDisplayZeros(){ - CTSheetView view = getDefaultSheetView(); - return view == null || view.getShowZeros(); - } - - /** - * Set whether the window should show 0 (zero) in cells containing zero value. - * When false, cells with zero value appear blank instead of showing the number zero. - * - * @param value whether to display or hide all zero values on the worksheet - */ - @Override - public void setDisplayZeros(boolean value){ - CTSheetView view = getSheetTypeSheetView(); - view.setShowZeros(value); - } - - /** - * Gets the first row on the sheet - * - * @return the number of the first logical row on the sheet, zero based - */ - @Override - public int getFirstRowNum() { - return _rows.isEmpty() ? 0 : _rows.firstKey(); - } - - /** - * Flag indicating whether the Fit to Page print option is enabled. - * - * @return true - */ - @Override - public boolean getFitToPage() { - CTSheetPr sheetPr = getSheetTypeSheetPr(); - CTPageSetUpPr psSetup = (sheetPr == null || !sheetPr.isSetPageSetUpPr()) ? - CTPageSetUpPr.Factory.newInstance() : sheetPr.getPageSetUpPr(); - return psSetup.getFitToPage(); - } - - private CTSheetPr getSheetTypeSheetPr() { - if (worksheet.getSheetPr() == null) { - worksheet.setSheetPr(CTSheetPr.Factory.newInstance()); - } - return worksheet.getSheetPr(); - } - - private CTHeaderFooter getSheetTypeHeaderFooter() { - if (worksheet.getHeaderFooter() == null) { - worksheet.setHeaderFooter(CTHeaderFooter.Factory.newInstance()); - } - return worksheet.getHeaderFooter(); - } - - - - /** - * Returns the default footer for the sheet, - * creating one as needed. - * You may also want to look at - * {@link #getFirstFooter()}, - * {@link #getOddFooter()} and - * {@link #getEvenFooter()} - */ - @Override - public Footer getFooter() { - // The default footer is an odd footer - return getOddFooter(); - } - - /** - * Returns the default header for the sheet, - * creating one as needed. - * You may also want to look at - * {@link #getFirstHeader()}, - * {@link #getOddHeader()} and - * {@link #getEvenHeader()} - */ - @Override - public Header getHeader() { - // The default header is an odd header - return getOddHeader(); - } - - /** - * Returns the odd footer. Used on all pages unless - * other footers also present, when used on only - * odd pages. - */ - public Footer getOddFooter() { - return new XSSFOddFooter(getSheetTypeHeaderFooter()); - } - /** - * Returns the even footer. Not there by default, but - * when set, used on even pages. - */ - public Footer getEvenFooter() { - return new XSSFEvenFooter(getSheetTypeHeaderFooter()); - } - /** - * Returns the first page footer. Not there by - * default, but when set, used on the first page. - */ - public Footer getFirstFooter() { - return new XSSFFirstFooter(getSheetTypeHeaderFooter()); - } - - /** - * Returns the odd header. Used on all pages unless - * other headers also present, when used on only - * odd pages. - */ - public Header getOddHeader() { - return new XSSFOddHeader(getSheetTypeHeaderFooter()); - } - /** - * Returns the even header. Not there by default, but - * when set, used on even pages. - */ - public Header getEvenHeader() { - return new XSSFEvenHeader(getSheetTypeHeaderFooter()); - } - /** - * Returns the first page header. Not there by - * default, but when set, used on the first page. - */ - public Header getFirstHeader() { - return new XSSFFirstHeader(getSheetTypeHeaderFooter()); - } - - - /** - * Determine whether printed output for this sheet will be horizontally centered. - */ - @Override - public boolean getHorizontallyCenter() { - CTPrintOptions opts = worksheet.getPrintOptions(); - return opts != null && opts.getHorizontalCentered(); - } - - @Override - public int getLastRowNum() { - return _rows.isEmpty() ? 0 : _rows.lastKey(); - } - - @Override - public short getLeftCol() { - String cellRef = worksheet.getSheetViews().getSheetViewArray(0).getTopLeftCell(); - if(cellRef == null) { - return 0; - } - CellReference cellReference = new CellReference(cellRef); - return cellReference.getCol(); - } - - /** - * Gets the size of the margin in inches. - * - * @param margin which margin to get - * @return the size of the margin - * @see Sheet#LeftMargin - * @see Sheet#RightMargin - * @see Sheet#TopMargin - * @see Sheet#BottomMargin - * @see Sheet#HeaderMargin - * @see Sheet#FooterMargin - */ - @Override - public double getMargin(short margin) { - if (!worksheet.isSetPageMargins()) { - return 0; - } - - CTPageMargins pageMargins = worksheet.getPageMargins(); - switch (margin) { - case LeftMargin: - return pageMargins.getLeft(); - case RightMargin: - return pageMargins.getRight(); - case TopMargin: - return pageMargins.getTop(); - case BottomMargin: - return pageMargins.getBottom(); - case HeaderMargin: - return pageMargins.getHeader(); - case FooterMargin: - return pageMargins.getFooter(); - default : - throw new IllegalArgumentException("Unknown margin constant: " + margin); - } - } - - /** - * Sets the size of the margin in inches. - * - * @param margin which margin to get - * @param size the size of the margin - * @see Sheet#LeftMargin - * @see Sheet#RightMargin - * @see Sheet#TopMargin - * @see Sheet#BottomMargin - * @see Sheet#HeaderMargin - * @see Sheet#FooterMargin - */ - @Override - public void setMargin(short margin, double size) { - CTPageMargins pageMargins = worksheet.isSetPageMargins() ? - worksheet.getPageMargins() : worksheet.addNewPageMargins(); - switch (margin) { - case LeftMargin: - pageMargins.setLeft(size); - break; - case RightMargin: - pageMargins.setRight(size); - break; - case TopMargin: - pageMargins.setTop(size); - break; - case BottomMargin: - pageMargins.setBottom(size); - break; - case HeaderMargin: - pageMargins.setHeader(size); - break; - case FooterMargin: - pageMargins.setFooter(size); - break; - default : - throw new IllegalArgumentException( "Unknown margin constant: " + margin ); - } - } - - /** - * Returns the merged region at the specified index. If you want multiple - * regions, it is faster to call {@link #getMergedRegions()} than to call - * this each time. - * - * @return the merged region at the specified index - */ - @Override - public CellRangeAddress getMergedRegion(int index) { - CTMergeCells ctMergeCells = worksheet.getMergeCells(); - if(ctMergeCells == null) { - throw new IllegalStateException("This worksheet does not contain merged regions"); - } - - CTMergeCell ctMergeCell = ctMergeCells.getMergeCellArray(index); - String ref = ctMergeCell.getRef(); - return CellRangeAddress.valueOf(ref); - } - - /** - * Returns the list of merged regions. If you want multiple regions, this is - * faster than calling {@link #getMergedRegion(int)} each time. - * - * @return the list of merged regions - */ - @Override - public List getMergedRegions() { - List addresses = new ArrayList(); - CTMergeCells ctMergeCells = worksheet.getMergeCells(); - if(ctMergeCells == null) { - return addresses; - } - - for(CTMergeCell ctMergeCell : ctMergeCells.getMergeCellArray()) { - String ref = ctMergeCell.getRef(); - addresses.add(CellRangeAddress.valueOf(ref)); - } - return addresses; - } - - /** - * Returns the number of merged regions defined in this worksheet - * - * @return number of merged regions in this worksheet - */ - @Override - public int getNumMergedRegions() { - CTMergeCells ctMergeCells = worksheet.getMergeCells(); - return ctMergeCells == null ? 0 : ctMergeCells.sizeOfMergeCellArray(); - } - - public int getNumHyperlinks() { - return hyperlinks.size(); - } - - /** - * Returns the information regarding the currently configured pane (split or freeze). - * - * @return null if no pane configured, or the pane information. - */ - @Override - public PaneInformation getPaneInformation() { - CTPane pane = getDefaultSheetView().getPane(); - // no pane configured - if(pane == null) { - return null; - } - - CellReference cellRef = pane.isSetTopLeftCell() ? new CellReference(pane.getTopLeftCell()) : null; - return new PaneInformation((short)pane.getXSplit(), (short)pane.getYSplit(), - (short)(cellRef == null ? 0 : cellRef.getRow()),(cellRef == null ? 0 : cellRef.getCol()), - (byte)(pane.getActivePane().intValue() - 1), pane.getState() == STPaneState.FROZEN); - } - - /** - * Returns the number of physically defined rows (NOT the number of rows in the sheet) - * - * @return the number of physically defined rows - */ - @Override - public int getPhysicalNumberOfRows() { - return _rows.size(); - } - - /** - * Gets the print setup object. - * - * @return The user model for the print setup object. - */ - @Override - public XSSFPrintSetup getPrintSetup() { - return new XSSFPrintSetup(worksheet); - } - - /** - * Answer whether protection is enabled or disabled - * - * @return true => protection enabled; false => protection disabled - */ - @Override - public boolean getProtect() { - return isSheetLocked(); - } - - /** - * Enables sheet protection and sets the password for the sheet. - * Also sets some attributes on the {@link CTSheetProtection} that correspond to - * the default values used by Excel - * - * @param password to set for protection. Pass null to remove protection - */ - @Override - public void protectSheet(String password) { - if (password != null) { - CTSheetProtection sheetProtection = safeGetProtectionField(); - setSheetPassword(password, null); // defaults to xor password - sheetProtection.setSheet(true); - sheetProtection.setScenarios(true); - sheetProtection.setObjects(true); - } else { - worksheet.unsetSheetProtection(); - } - } - - /** - * Sets the sheet password. - * - * @param password if null, the password will be removed - * @param hashAlgo if null, the password will be set as XOR password (Excel 2010 and earlier) - * otherwise the given algorithm is used for calculating the hash password (Excel 2013) - */ - public void setSheetPassword(String password, HashAlgorithm hashAlgo) { - if (password == null && !isSheetProtectionEnabled()) { - return; - } - setPassword(safeGetProtectionField(), password, hashAlgo, null); - } - - /** - * Validate the password against the stored hash, the hashing method will be determined - * by the existing password attributes - * @return true, if the hashes match (... though original password may differ ...) - */ - public boolean validateSheetPassword(String password) { - if (!isSheetProtectionEnabled()) { - return (password == null); - } - return validatePassword(safeGetProtectionField(), password, null); - } - - /** - * Returns the logical row ( 0-based). If you ask for a row that is not - * defined you get a null. This is to say row 4 represents the fifth row on a sheet. - * - * @param rownum row to get - * @return XSSFRow representing the rownumber or null if its not defined on the sheet - */ - @Override - public XSSFRow getRow(int rownum) { - // Performance optimization: explicit boxing is slightly faster than auto-unboxing, though may use more memory - final Integer rownumI = new Integer(rownum); // NOSONAR - return _rows.get(rownumI); - } - - /** - * returns all rows between startRow and endRow, inclusive. - * Rows between startRow and endRow that haven't been created are not included - * in result unless createRowIfMissing is true - * - * @param startRowNum the first row number in this sheet to return - * @param endRowNum the last row number in this sheet to return - * @param createRowIfMissing - * @return All rows between startRow and endRow, inclusive - * @throws IllegalArgumentException if startRowNum and endRowNum are not in ascending order - */ - private List getRows(int startRowNum, int endRowNum, boolean createRowIfMissing) { - if (startRowNum > endRowNum) { - throw new IllegalArgumentException("getRows: startRowNum must be less than or equal to endRowNum"); - } - final List rows = new ArrayList(); - if (createRowIfMissing) { - for (int i = startRowNum; i <= endRowNum; i++) { - XSSFRow row = getRow(i); - if (row == null) { - row = createRow(i); - } - rows.add(row); - } - } - else { - // Performance optimization: explicit boxing is slightly faster than auto-unboxing, though may use more memory - final Integer startI = new Integer(startRowNum); // NOSONAR - final Integer endI = new Integer(endRowNum+1); // NOSONAR - final Collection inclusive = _rows.subMap(startI, endI).values(); - rows.addAll(inclusive); - } - return rows; - } - - /** - * Horizontal page break information used for print layout view, page layout view, drawing print breaks in normal - * view, and for printing the worksheet. - * - * @return row indexes of all the horizontal page breaks, never null - */ - @Override - public int[] getRowBreaks() { - return worksheet.isSetRowBreaks() ? getBreaks(worksheet.getRowBreaks()) : new int[0]; - - } - - /** - * Flag indicating whether summary rows appear below detail in an outline, when applying an outline. - * - *

    - * When true a summary row is inserted below the detailed data being summarized and a - * new outline level is established on that row. - *

    - *

    - * When false a summary row is inserted above the detailed data being summarized and a new outline level - * is established on that row. - *

    - * @return true if row summaries appear below detail in the outline - */ - @Override - public boolean getRowSumsBelow() { - CTSheetPr sheetPr = worksheet.getSheetPr(); - CTOutlinePr outlinePr = (sheetPr != null && sheetPr.isSetOutlinePr()) - ? sheetPr.getOutlinePr() : null; - return outlinePr == null || outlinePr.getSummaryBelow(); - } - - /** - * Flag indicating whether summary rows appear below detail in an outline, when applying an outline. - * - *

    - * When true a summary row is inserted below the detailed data being summarized and a - * new outline level is established on that row. - *

    - *

    - * When false a summary row is inserted above the detailed data being summarized and a new outline level - * is established on that row. - *

    - * @param value true if row summaries appear below detail in the outline - */ - @Override - public void setRowSumsBelow(boolean value) { - ensureOutlinePr().setSummaryBelow(value); - } - - /** - * Flag indicating whether summary columns appear to the right of detail in an outline, when applying an outline. - * - *

    - * When true a summary column is inserted to the right of the detailed data being summarized - * and a new outline level is established on that column. - *

    - *

    - * When false a summary column is inserted to the left of the detailed data being - * summarized and a new outline level is established on that column. - *

    - * @return true if col summaries appear right of the detail in the outline - */ - @Override - public boolean getRowSumsRight() { - CTSheetPr sheetPr = worksheet.getSheetPr(); - CTOutlinePr outlinePr = (sheetPr != null && sheetPr.isSetOutlinePr()) - ? sheetPr.getOutlinePr() : CTOutlinePr.Factory.newInstance(); - return outlinePr.getSummaryRight(); - } - - /** - * Flag indicating whether summary columns appear to the right of detail in an outline, when applying an outline. - * - *

    - * When true a summary column is inserted to the right of the detailed data being summarized - * and a new outline level is established on that column. - *

    - *

    - * When false a summary column is inserted to the left of the detailed data being - * summarized and a new outline level is established on that column. - *

    - * @param value true if col summaries appear right of the detail in the outline - */ - @Override - public void setRowSumsRight(boolean value) { - ensureOutlinePr().setSummaryRight(value); - } - - - /** - * Ensure CTWorksheet.CTSheetPr.CTOutlinePr - */ - private CTOutlinePr ensureOutlinePr(){ - CTSheetPr sheetPr = worksheet.isSetSheetPr() ? worksheet.getSheetPr() : worksheet.addNewSheetPr(); - return sheetPr.isSetOutlinePr() ? sheetPr.getOutlinePr() : sheetPr.addNewOutlinePr(); - } - - /** - * A flag indicating whether scenarios are locked when the sheet is protected. - * - * @return true => protection enabled; false => protection disabled - */ - @Override - public boolean getScenarioProtect() { - return worksheet.isSetSheetProtection() && worksheet.getSheetProtection().getScenarios(); - } - - /** - * The top row in the visible view when the sheet is - * first viewed after opening it in a viewer - * - * @return integer indicating the rownum (0 based) of the top row - */ - @Override - public short getTopRow() { - String cellRef = getSheetTypeSheetView().getTopLeftCell(); - if(cellRef == null) { - return 0; - } - CellReference cellReference = new CellReference(cellRef); - return (short) cellReference.getRow(); - } - - /** - * Determine whether printed output for this sheet will be vertically centered. - * - * @return whether printed output for this sheet will be vertically centered. - */ - @Override - public boolean getVerticallyCenter() { - CTPrintOptions opts = worksheet.getPrintOptions(); - return opts != null && opts.getVerticalCentered(); - } - - /** - * Group between (0 based) columns - */ - @Override - public void groupColumn(int fromColumn, int toColumn) { - groupColumn1Based(fromColumn+1, toColumn+1); - } - private void groupColumn1Based(int fromColumn, int toColumn) { - CTCols ctCols=worksheet.getColsArray(0); - CTCol ctCol=CTCol.Factory.newInstance(); - - // copy attributes, as they might be removed by merging with the new column - // TODO: check if this fix is really necessary or if the sweeping algorithm - // in addCleanColIntoCols needs to be adapted ... - CTCol fixCol_before = this.columnHelper.getColumn1Based(toColumn, false); - if (fixCol_before != null) { - fixCol_before = (CTCol)fixCol_before.copy(); - } - - ctCol.setMin(fromColumn); - ctCol.setMax(toColumn); - this.columnHelper.addCleanColIntoCols(ctCols, ctCol); - - CTCol fixCol_after = this.columnHelper.getColumn1Based(toColumn, false); - if (fixCol_before != null && fixCol_after != null) { - this.columnHelper.setColumnAttributes(fixCol_before, fixCol_after); - } - - for(int index=fromColumn;index<=toColumn;index++){ - CTCol col=columnHelper.getColumn1Based(index, false); - //col must exist - short outlineLevel=col.getOutlineLevel(); - col.setOutlineLevel((short)(outlineLevel+1)); - index=(int)col.getMax(); - } - worksheet.setColsArray(0,ctCols); - setSheetFormatPrOutlineLevelCol(); - } - - /** - * Do not leave the width attribute undefined (see #52186). - */ - private void setColWidthAttribute(CTCols ctCols) { - for (CTCol col : ctCols.getColArray()) { - if (!col.isSetWidth()) { - col.setWidth(getDefaultColumnWidth()); - col.setCustomWidth(false); - } - } - } - - /** - * Tie a range of cell together so that they can be collapsed or expanded - * - * @param fromRow start row (0-based) - * @param toRow end row (0-based) - */ - @Override - public void groupRow(int fromRow, int toRow) { - for (int i = fromRow; i <= toRow; i++) { - XSSFRow xrow = getRow(i); - if (xrow == null) { - xrow = createRow(i); - } - CTRow ctrow = xrow.getCTRow(); - short outlineLevel = ctrow.getOutlineLevel(); - ctrow.setOutlineLevel((short) (outlineLevel + 1)); - } - setSheetFormatPrOutlineLevelRow(); - } - - private short getMaxOutlineLevelRows(){ - int outlineLevel = 0; - for (XSSFRow xrow : _rows.values()) { - outlineLevel = Math.max(outlineLevel, xrow.getCTRow().getOutlineLevel()); - } - return (short) outlineLevel; - } - - private short getMaxOutlineLevelCols() { - CTCols ctCols = worksheet.getColsArray(0); - int outlineLevel = 0; - for (CTCol col : ctCols.getColArray()) { - outlineLevel = Math.max(outlineLevel, col.getOutlineLevel()); - } - return (short) outlineLevel; - } - - /** - * Determines if there is a page break at the indicated column - */ - @Override - public boolean isColumnBroken(int column) { - for (int colBreak : getColumnBreaks()) { - if (colBreak == column) { - return true; - } - } - return false; - } - - /** - * Get the hidden state for a given column. - * - * @param columnIndex - the column to set (0-based) - * @return hidden - false if the column is visible - */ - @Override - public boolean isColumnHidden(int columnIndex) { - CTCol col = columnHelper.getColumn(columnIndex, false); - return col != null && col.getHidden(); - } - - /** - * Gets the flag indicating whether this sheet should display formulas. - * - * @return true if this sheet should display formulas. - */ - @Override - public boolean isDisplayFormulas() { - return getSheetTypeSheetView().getShowFormulas(); - } - - /** - * Gets the flag indicating whether this sheet displays the lines - * between rows and columns to make editing and reading easier. - * - * @return true if this sheet displays gridlines. - * @see #isPrintGridlines() to check if printing of gridlines is turned on or off - */ - @Override - public boolean isDisplayGridlines() { - return getSheetTypeSheetView().getShowGridLines(); - } - - /** - * Sets the flag indicating whether this sheet should display the lines - * between rows and columns to make editing and reading easier. - * To turn printing of gridlines use {@link #setPrintGridlines(boolean)} - * - * - * @param show true if this sheet should display gridlines. - * @see #setPrintGridlines(boolean) - */ - @Override - public void setDisplayGridlines(boolean show) { - getSheetTypeSheetView().setShowGridLines(show); - } - - /** - * Gets the flag indicating whether this sheet should display row and column headings. - *

    - * Row heading are the row numbers to the side of the sheet - *

    - *

    - * Column heading are the letters or numbers that appear above the columns of the sheet - *

    - * - * @return true if this sheet should display row and column headings. - */ - @Override - public boolean isDisplayRowColHeadings() { - return getSheetTypeSheetView().getShowRowColHeaders(); - } - - /** - * Sets the flag indicating whether this sheet should display row and column headings. - *

    - * Row heading are the row numbers to the side of the sheet - *

    - *

    - * Column heading are the letters or numbers that appear above the columns of the sheet - *

    - * - * @param show true if this sheet should display row and column headings. - */ - @Override - public void setDisplayRowColHeadings(boolean show) { - getSheetTypeSheetView().setShowRowColHeaders(show); - } - - /** - * Returns whether gridlines are printed. - * - * @return whether gridlines are printed - */ - @Override - public boolean isPrintGridlines() { - CTPrintOptions opts = worksheet.getPrintOptions(); - return opts != null && opts.getGridLines(); - } - - /** - * Turns on or off the printing of gridlines. - * - * @param value boolean to turn on or off the printing of gridlines - */ - @Override - public void setPrintGridlines(boolean value) { - CTPrintOptions opts = worksheet.isSetPrintOptions() ? - worksheet.getPrintOptions() : worksheet.addNewPrintOptions(); - opts.setGridLines(value); - } - - /** - * Returns whether row and column headings are printed. - * - * @return whether row and column headings are printed - */ - @Override - public boolean isPrintRowAndColumnHeadings() { - CTPrintOptions opts = worksheet.getPrintOptions(); - return opts != null && opts.getHeadings(); - } - - /** - * Turns on or off the printing of row and column headings. - * - * @param value boolean to turn on or off the printing of row and column headings - */ - @Override - public void setPrintRowAndColumnHeadings(boolean value) { - CTPrintOptions opts = worksheet.isSetPrintOptions() ? - worksheet.getPrintOptions() : worksheet.addNewPrintOptions(); - opts.setHeadings(value); - } - - /** - * Tests if there is a page break at the indicated row - * - * @param row index of the row to test - * @return true if there is a page break at the indicated row - */ - @Override - public boolean isRowBroken(int row) { - for (int rowBreak : getRowBreaks()) { - if (rowBreak == row) { - return true; - } - } - return false; - } - - private void setBreak(int id, CTPageBreak ctPgBreak, int lastIndex) { - CTBreak brk = ctPgBreak.addNewBrk(); - brk.setId(id + 1); // this is id of the element which is 1-based: - brk.setMan(true); - brk.setMax(lastIndex); //end column of the break - - int nPageBreaks = ctPgBreak.sizeOfBrkArray(); - ctPgBreak.setCount(nPageBreaks); - ctPgBreak.setManualBreakCount(nPageBreaks); - } - - /** - * Sets a page break at the indicated row - * Breaks occur above the specified row and left of the specified column inclusive. - * - * For example, sheet.setColumnBreak(2); breaks the sheet into two parts - * with columns A,B,C in the first and D,E,... in the second. Simuilar, sheet.setRowBreak(2); - * breaks the sheet into two parts with first three rows (rownum=1...3) in the first part - * and rows starting with rownum=4 in the second. - * - * @param row the row to break, inclusive - */ - @Override - public void setRowBreak(int row) { - if (!isRowBroken(row)) { - CTPageBreak pgBreak = worksheet.isSetRowBreaks() ? worksheet.getRowBreaks() : worksheet.addNewRowBreaks(); - setBreak(row, pgBreak, SpreadsheetVersion.EXCEL2007.getLastColumnIndex()); - } - } - - /** - * Removes a page break at the indicated column - */ - @Override - public void removeColumnBreak(int column) { - if (worksheet.isSetColBreaks()) { - removeBreak(column, worksheet.getColBreaks()); - } // else no breaks - } - - /** - * Removes a merged region of cells (hence letting them free) - * - * @param index of the region to unmerge - */ - @Override - public void removeMergedRegion(int index) { - if (!worksheet.isSetMergeCells()) { - return; - } - - CTMergeCells ctMergeCells = worksheet.getMergeCells(); - int size = ctMergeCells.sizeOfMergeCellArray(); - assert(0 <= index && index < size); - if (size > 1) { - ctMergeCells.removeMergeCell(index); - } else { - worksheet.unsetMergeCells(); - } - } - - /** - * Removes a number of merged regions of cells (hence letting them free) - * - * This method can be used to bulk-remove merged regions in a way - * much faster than calling removeMergedRegion() for every single - * merged region. - * - * @param indices A set of the regions to unmerge - */ - @Override - public void removeMergedRegions(Collection indices) { - if (!worksheet.isSetMergeCells()) { - return; - } - - CTMergeCells ctMergeCells = worksheet.getMergeCells(); - List newMergeCells = new ArrayList(ctMergeCells.sizeOfMergeCellArray()); - - int idx = 0; - for (CTMergeCell mc : ctMergeCells.getMergeCellArray()) { - if (!indices.contains(idx++)) { - newMergeCells.add(mc); - } - } - - if (newMergeCells.isEmpty()) { - worksheet.unsetMergeCells(); - } else { - CTMergeCell[] newMergeCellsArray = new CTMergeCell[newMergeCells.size()]; - ctMergeCells.setMergeCellArray(newMergeCells.toArray(newMergeCellsArray)); - } - } - - /** - * Remove a row from this sheet. All cells contained in the row are removed as well - * - * @param row the row to remove. - */ - @Override - public void removeRow(Row row) { - if (row.getSheet() != this) { - throw new IllegalArgumentException("Specified row does not belong to this sheet"); - } - // collect cells into a temporary array to avoid ConcurrentModificationException - ArrayList cellsToDelete = new ArrayList(); - for (Cell cell : row) { - cellsToDelete.add((XSSFCell)cell); - } - - for (XSSFCell cell : cellsToDelete) { - row.removeCell(cell); - } - - // Performance optimization: explicit boxing is slightly faster than auto-unboxing, though may use more memory - final int rowNum = row.getRowNum(); - final Integer rowNumI = new Integer(rowNum); // NOSONAR - // this is not the physical row number! - final int idx = _rows.headMap(rowNumI).size(); - _rows.remove(rowNumI); - worksheet.getSheetData().removeRow(idx); - - // also remove any comment located in that row - if(sheetComments != null) { - for (CellAddress ref : getCellComments().keySet()) { - if (ref.getRow() == rowNum) { - sheetComments.removeComment(ref); - } - } - } - } - - /** - * Removes the page break at the indicated row - */ - @Override - public void removeRowBreak(int row) { - if (worksheet.isSetRowBreaks()) { - removeBreak(row, worksheet.getRowBreaks()); - } // else no breaks - } - - /** - * Control if Excel should be asked to recalculate all formulas on this sheet - * when the workbook is opened. - * - *

    - * Calculating the formula values with {@link org.apache.poi.ss.usermodel.FormulaEvaluator} is the - * recommended solution, but this may be used for certain cases where - * evaluation in POI is not possible. - *

    - * - *

    - * It is recommended to force recalcuation of formulas on workbook level using - * {@link org.apache.poi.ss.usermodel.Workbook#setForceFormulaRecalculation(boolean)} - * to ensure that all cross-worksheet formuals and external dependencies are updated. - *

    - * @param value true if the application will perform a full recalculation of - * this worksheet values when the workbook is opened - * - * @see org.apache.poi.ss.usermodel.Workbook#setForceFormulaRecalculation(boolean) - */ - @Override - public void setForceFormulaRecalculation(boolean value) { - CTCalcPr calcPr = getWorkbook().getCTWorkbook().getCalcPr(); - - if(worksheet.isSetSheetCalcPr()) { - // Change the current setting - CTSheetCalcPr calc = worksheet.getSheetCalcPr(); - calc.setFullCalcOnLoad(value); - } - else if(value) { - // Add the Calc block and set it - CTSheetCalcPr calc = worksheet.addNewSheetCalcPr(); - calc.setFullCalcOnLoad(value); - } - if(value && calcPr != null && calcPr.getCalcMode() == STCalcMode.MANUAL) { - calcPr.setCalcMode(STCalcMode.AUTO); - } - - } - - /** - * Whether Excel will be asked to recalculate all formulas when the - * workbook is opened. - */ - @Override - public boolean getForceFormulaRecalculation() { - if(worksheet.isSetSheetCalcPr()) { - CTSheetCalcPr calc = worksheet.getSheetCalcPr(); - return calc.getFullCalcOnLoad(); - } - return false; - } - - /** - * @return an iterator of the PHYSICAL rows. Meaning the 3rd element may not - * be the third row if say for instance the second row is undefined. - * Call getRowNum() on each row if you care which one it is. - */ - @Override - @SuppressWarnings("unchecked") - public Iterator rowIterator() { - return (Iterator)(Iterator) _rows.values().iterator(); - } - - /** - * Alias for {@link #rowIterator()} to - * allow foreach loops - */ - @Override - public Iterator iterator() { - return rowIterator(); - } - - /** - * Flag indicating whether the sheet displays Automatic Page Breaks. - * - * @return true if the sheet displays Automatic Page Breaks. - */ - @Override - public boolean getAutobreaks() { - CTSheetPr sheetPr = getSheetTypeSheetPr(); - CTPageSetUpPr psSetup = (sheetPr == null || !sheetPr.isSetPageSetUpPr()) ? - CTPageSetUpPr.Factory.newInstance() : sheetPr.getPageSetUpPr(); - return psSetup.getAutoPageBreaks(); - } - - /** - * Flag indicating whether the sheet displays Automatic Page Breaks. - * - * @param value true if the sheet displays Automatic Page Breaks. - */ - @Override - public void setAutobreaks(boolean value) { - CTSheetPr sheetPr = getSheetTypeSheetPr(); - CTPageSetUpPr psSetup = sheetPr.isSetPageSetUpPr() ? sheetPr.getPageSetUpPr() : sheetPr.addNewPageSetUpPr(); - psSetup.setAutoPageBreaks(value); - } - - /** - * Sets a page break at the indicated column. - * Breaks occur above the specified row and left of the specified column inclusive. - * - * For example, sheet.setColumnBreak(2); breaks the sheet into two parts - * with columns A,B,C in the first and D,E,... in the second. Simuilar, sheet.setRowBreak(2); - * breaks the sheet into two parts with first three rows (rownum=1...3) in the first part - * and rows starting with rownum=4 in the second. - * - * @param column the column to break, inclusive - */ - @Override - public void setColumnBreak(int column) { - if (!isColumnBroken(column)) { - CTPageBreak pgBreak = worksheet.isSetColBreaks() ? worksheet.getColBreaks() : worksheet.addNewColBreaks(); - setBreak(column, pgBreak, SpreadsheetVersion.EXCEL2007.getLastRowIndex()); - } - } - - @Override - public void setColumnGroupCollapsed(int columnNumber, boolean collapsed) { - if (collapsed) { - collapseColumn(columnNumber); - } else { - expandColumn(columnNumber); - } - } - - private void collapseColumn(int columnNumber) { - CTCols cols = worksheet.getColsArray(0); - CTCol col = columnHelper.getColumn(columnNumber, false); - int colInfoIx = columnHelper.getIndexOfColumn(cols, col); - if (colInfoIx == -1) { - return; - } - // Find the start of the group. - int groupStartColInfoIx = findStartOfColumnOutlineGroup(colInfoIx); - - CTCol columnInfo = cols.getColArray(groupStartColInfoIx); - - // Hide all the columns until the end of the group - int lastColMax = setGroupHidden(groupStartColInfoIx, columnInfo - .getOutlineLevel(), true); - - // write collapse field - setColumn(lastColMax + 1, 0, null, null, Boolean.TRUE); - - } - - private void setColumn(int targetColumnIx, Integer style, - Integer level, Boolean hidden, Boolean collapsed) { - CTCols cols = worksheet.getColsArray(0); - CTCol ci = null; - for (CTCol tci : cols.getColArray()) { - long tciMin = tci.getMin(); - long tciMax = tci.getMax(); - if (tciMin >= targetColumnIx && tciMax <= targetColumnIx) { - ci = tci; - break; - } - if (tciMin > targetColumnIx) { - // call column infos after k are for later columns - break; // exit now so k will be the correct insert pos - } - } - - if (ci == null) { - // okay so there ISN'T a column info record that covers this column - // so lets create one! - CTCol nci = CTCol.Factory.newInstance(); - nci.setMin(targetColumnIx); - nci.setMax(targetColumnIx); - unsetCollapsed(collapsed, nci); - this.columnHelper.addCleanColIntoCols(cols, nci); - return; - } - - boolean styleChanged = style != null && ci.getStyle() != style; - boolean levelChanged = level != null && ci.getOutlineLevel() != level; - boolean hiddenChanged = hidden != null && ci.getHidden() != hidden; - boolean collapsedChanged = collapsed != null && ci.getCollapsed() != collapsed; - boolean columnChanged = levelChanged || hiddenChanged || collapsedChanged || styleChanged; - if (!columnChanged) { - // do nothing...nothing changed. - return; - } - - long ciMin = ci.getMin(); - long ciMax = ci.getMax(); - if (ciMin == targetColumnIx && ciMax == targetColumnIx) { - // ColumnInfo ci for a single column, the target column - unsetCollapsed(collapsed, ci); - return; - } - - if (ciMin == targetColumnIx || ciMax == targetColumnIx) { - // The target column is at either end of the multi-column ColumnInfo - // ci - // we'll just divide the info and create a new one - if (ciMin == targetColumnIx) { - ci.setMin(targetColumnIx + 1); - } else { - ci.setMax(targetColumnIx - 1); - } - CTCol nci = columnHelper.cloneCol(cols, ci); - nci.setMin(targetColumnIx); - unsetCollapsed(collapsed, nci); - this.columnHelper.addCleanColIntoCols(cols, nci); - - } else { - // split to 3 records - CTCol ciMid = columnHelper.cloneCol(cols, ci); - CTCol ciEnd = columnHelper.cloneCol(cols, ci); - int lastcolumn = (int) ciMax; - - ci.setMax(targetColumnIx - 1); - - ciMid.setMin(targetColumnIx); - ciMid.setMax(targetColumnIx); - unsetCollapsed(collapsed, ciMid); - this.columnHelper.addCleanColIntoCols(cols, ciMid); - - ciEnd.setMin(targetColumnIx + 1); - ciEnd.setMax(lastcolumn); - this.columnHelper.addCleanColIntoCols(cols, ciEnd); - } - } - - private void unsetCollapsed(boolean collapsed, CTCol ci) { - if (collapsed) { - ci.setCollapsed(collapsed); - } else { - ci.unsetCollapsed(); - } - } - - /** - * Sets all adjacent columns of the same outline level to the specified - * hidden status. - * - * @param pIdx - * the col info index of the start of the outline group - * @return the column index of the last column in the outline group - */ - private int setGroupHidden(int pIdx, int level, boolean hidden) { - CTCols cols = worksheet.getColsArray(0); - int idx = pIdx; - CTCol[] colArray = cols.getColArray(); - CTCol columnInfo = colArray[idx]; - while (idx < colArray.length) { - columnInfo.setHidden(hidden); - if (idx + 1 < colArray.length) { - CTCol nextColumnInfo = colArray[idx + 1]; - - if (!isAdjacentBefore(columnInfo, nextColumnInfo)) { - break; - } - - if (nextColumnInfo.getOutlineLevel() < level) { - break; - } - columnInfo = nextColumnInfo; - } - idx++; - } - return (int) columnInfo.getMax(); - } - - private boolean isAdjacentBefore(CTCol col, CTCol otherCol) { - return col.getMax() == otherCol.getMin() - 1; - } - - private int findStartOfColumnOutlineGroup(int pIdx) { - // Find the start of the group. - CTCols cols = worksheet.getColsArray(0); - CTCol[] colArray = cols.getColArray(); - CTCol columnInfo = colArray[pIdx]; - int level = columnInfo.getOutlineLevel(); - int idx = pIdx; - while (idx != 0) { - CTCol prevColumnInfo = colArray[idx - 1]; - if (!isAdjacentBefore(prevColumnInfo, columnInfo)) { - break; - } - if (prevColumnInfo.getOutlineLevel() < level) { - break; - } - idx--; - columnInfo = prevColumnInfo; - } - return idx; - } - - private int findEndOfColumnOutlineGroup(int colInfoIndex) { - CTCols cols = worksheet.getColsArray(0); - // Find the end of the group. - CTCol[] colArray = cols.getColArray(); - CTCol columnInfo = colArray[colInfoIndex]; - int level = columnInfo.getOutlineLevel(); - int idx = colInfoIndex; - int lastIdx = colArray.length - 1; - while (idx < lastIdx) { - CTCol nextColumnInfo = colArray[idx + 1]; - if (!isAdjacentBefore(columnInfo, nextColumnInfo)) { - break; - } - if (nextColumnInfo.getOutlineLevel() < level) { - break; - } - idx++; - columnInfo = nextColumnInfo; - } - return idx; - } - - private void expandColumn(int columnIndex) { - CTCols cols = worksheet.getColsArray(0); - CTCol col = columnHelper.getColumn(columnIndex, false); - int colInfoIx = columnHelper.getIndexOfColumn(cols, col); - - int idx = findColInfoIdx((int) col.getMax(), colInfoIx); - if (idx == -1) { - return; - } - - // If it is already expanded do nothing. - if (!isColumnGroupCollapsed(idx)) { - return; - } - - // Find the start/end of the group. - int startIdx = findStartOfColumnOutlineGroup(idx); - int endIdx = findEndOfColumnOutlineGroup(idx); - - // expand: - // colapsed bit must be unset - // hidden bit gets unset _if_ surrounding groups are expanded you can - // determine - // this by looking at the hidden bit of the enclosing group. You will - // have - // to look at the start and the end of the current group to determine - // which - // is the enclosing group - // hidden bit only is altered for this outline level. ie. don't - // uncollapse contained groups - CTCol[] colArray = cols.getColArray(); - CTCol columnInfo = colArray[endIdx]; - if (!isColumnGroupHiddenByParent(idx)) { - short outlineLevel = columnInfo.getOutlineLevel(); - boolean nestedGroup = false; - for (int i = startIdx; i <= endIdx; i++) { - CTCol ci = colArray[i]; - if (outlineLevel == ci.getOutlineLevel()) { - ci.unsetHidden(); - if (nestedGroup) { - nestedGroup = false; - ci.setCollapsed(true); - } - } else { - nestedGroup = true; - } - } - } - // Write collapse flag (stored in a single col info record after this - // outline group) - setColumn((int) columnInfo.getMax() + 1, null, null, - Boolean.FALSE, Boolean.FALSE); - } - - private boolean isColumnGroupHiddenByParent(int idx) { - CTCols cols = worksheet.getColsArray(0); - // Look out outline details of end - int endLevel = 0; - boolean endHidden = false; - int endOfOutlineGroupIdx = findEndOfColumnOutlineGroup(idx); - CTCol[] colArray = cols.getColArray(); - if (endOfOutlineGroupIdx < colArray.length) { - CTCol nextInfo = colArray[endOfOutlineGroupIdx + 1]; - if (isAdjacentBefore(colArray[endOfOutlineGroupIdx], nextInfo)) { - endLevel = nextInfo.getOutlineLevel(); - endHidden = nextInfo.getHidden(); - } - } - // Look out outline details of start - int startLevel = 0; - boolean startHidden = false; - int startOfOutlineGroupIdx = findStartOfColumnOutlineGroup(idx); - if (startOfOutlineGroupIdx > 0) { - CTCol prevInfo = colArray[startOfOutlineGroupIdx - 1]; - - if (isAdjacentBefore(prevInfo, colArray[startOfOutlineGroupIdx])) { - startLevel = prevInfo.getOutlineLevel(); - startHidden = prevInfo.getHidden(); - } - - } - if (endLevel > startLevel) { - return endHidden; - } - return startHidden; - } - - private int findColInfoIdx(int columnValue, int fromColInfoIdx) { - CTCols cols = worksheet.getColsArray(0); - - if (columnValue < 0) { - throw new IllegalArgumentException( - "column parameter out of range: " + columnValue); - } - if (fromColInfoIdx < 0) { - throw new IllegalArgumentException( - "fromIdx parameter out of range: " + fromColInfoIdx); - } - - CTCol[] colArray = cols.getColArray(); - for (int k = fromColInfoIdx; k < colArray.length; k++) { - CTCol ci = colArray[k]; - - if (containsColumn(ci, columnValue)) { - return k; - } - - if (ci.getMin() > fromColInfoIdx) { - break; - } - - } - return -1; - } - - private boolean containsColumn(CTCol col, int columnIndex) { - return col.getMin() <= columnIndex && columnIndex <= col.getMax(); - } - - /** - * 'Collapsed' state is stored in a single column col info record - * immediately after the outline group - * - * @param idx - * @return a boolean represented if the column is collapsed - */ - private boolean isColumnGroupCollapsed(int idx) { - CTCols cols = worksheet.getColsArray(0); - CTCol[] colArray = cols.getColArray(); - int endOfOutlineGroupIdx = findEndOfColumnOutlineGroup(idx); - int nextColInfoIx = endOfOutlineGroupIdx + 1; - if (nextColInfoIx >= colArray.length) { - return false; - } - CTCol nextColInfo = colArray[nextColInfoIx]; - - CTCol col = colArray[endOfOutlineGroupIdx]; - if (!isAdjacentBefore(col, nextColInfo)) { - return false; - } - - return nextColInfo.getCollapsed(); - } - - /** - * Get the visibility state for a given column. - * - * @param columnIndex - the column to get (0-based) - * @param hidden - the visiblity state of the column - */ - @Override - public void setColumnHidden(int columnIndex, boolean hidden) { - columnHelper.setColHidden(columnIndex, hidden); - } - - /** - * Set the width (in units of 1/256th of a character width) - * - *

    - * The maximum column width for an individual cell is 255 characters. - * This value represents the number of characters that can be displayed - * in a cell that is formatted with the standard font (first font in the workbook). - *

    - * - *

    - * Character width is defined as the maximum digit width - * of the numbers 0, 1, 2, ... 9 as rendered - * using the default font (first font in the workbook). - *
    - * Unless you are using a very special font, the default character is '0' (zero), - * this is true for Arial (default font font in HSSF) and Calibri (default font in XSSF) - *

    - * - *

    - * Please note, that the width set by this method includes 4 pixels of margin padding (two on each side), - * plus 1 pixel padding for the gridlines (Section 3.3.1.12 of the OOXML spec). - * This results is a slightly less value of visible characters than passed to this method (approx. 1/2 of a character). - *

    - *

    - * To compute the actual number of visible characters, - * Excel uses the following formula (Section 3.3.1.12 of the OOXML spec): - *

    - * - * width = Truncate([{Number of Visible Characters} * - * {Maximum Digit Width} + {5 pixel padding}]/{Maximum Digit Width}*256)/256 - * - *

    Using the Calibri font as an example, the maximum digit width of 11 point font size is 7 pixels (at 96 dpi). - * If you set a column width to be eight characters wide, e.g. setColumnWidth(columnIndex, 8*256), - * then the actual value of visible characters (the value shown in Excel) is derived from the following equation: - * - Truncate([numChars*7+5]/7*256)/256 = 8; - * - * - * which gives 7.29. - * - * @param columnIndex - the column to set (0-based) - * @param width - the width in units of 1/256th of a character width - * @throws IllegalArgumentException if width > 255*256 (the maximum column width in Excel is 255 characters) - */ - @Override - public void setColumnWidth(int columnIndex, int width) { - if(width > 255*256) { - throw new IllegalArgumentException("The maximum column width for an individual cell is 255 characters."); - } - - columnHelper.setColWidth(columnIndex, (double)width/256); - columnHelper.setCustomWidth(columnIndex, true); - } - - @Override - public void setDefaultColumnStyle(int column, CellStyle style) { - columnHelper.setColDefaultStyle(column, style); - } - - /** - * Specifies the number of characters of the maximum digit width of the normal style's font. - * This value does not include margin padding or extra padding for gridlines. It is only the - * number of characters. - * - * @param width the number of characters. Default value is 8. - */ - @Override - public void setDefaultColumnWidth(int width) { - getSheetTypeSheetFormatPr().setBaseColWidth(width); - } - - /** - * Set the default row height for the sheet (if the rows do not define their own height) in - * twips (1/20 of a point) - * - * @param height default row height in twips (1/20 of a point) - */ - @Override - public void setDefaultRowHeight(short height) { - setDefaultRowHeightInPoints((float)height / TWIPS_PER_POINT); - } - - /** - * Sets default row height measured in point size. - * - * @param height default row height measured in point size. - */ - @Override - public void setDefaultRowHeightInPoints(float height) { - CTSheetFormatPr pr = getSheetTypeSheetFormatPr(); - pr.setDefaultRowHeight(height); - pr.setCustomHeight(true); - } - - /** - * Sets the flag indicating whether this sheet should display formulas. - * - * @param show true if this sheet should display formulas. - */ - @Override - public void setDisplayFormulas(boolean show) { - getSheetTypeSheetView().setShowFormulas(show); - } - - private CTSheetView getSheetTypeSheetView() { - if (getDefaultSheetView() == null) { - getSheetTypeSheetViews().setSheetViewArray(0, CTSheetView.Factory.newInstance()); - } - return getDefaultSheetView(); - } - - /** - * Flag indicating whether the Fit to Page print option is enabled. - * - * @param b true if the Fit to Page print option is enabled. - */ - @Override - public void setFitToPage(boolean b) { - getSheetTypePageSetUpPr().setFitToPage(b); - } - - /** - * Center on page horizontally when printing. - * - * @param value whether to center on page horizontally when printing. - */ - @Override - public void setHorizontallyCenter(boolean value) { - CTPrintOptions opts = worksheet.isSetPrintOptions() ? - worksheet.getPrintOptions() : worksheet.addNewPrintOptions(); - opts.setHorizontalCentered(value); - } - - /** - * Whether the output is vertically centered on the page. - * - * @param value true to vertically center, false otherwise. - */ - @Override - public void setVerticallyCenter(boolean value) { - CTPrintOptions opts = worksheet.isSetPrintOptions() ? - worksheet.getPrintOptions() : worksheet.addNewPrintOptions(); - opts.setVerticalCentered(value); - } - - /** - * group the row It is possible for collapsed to be false and yet still have - * the rows in question hidden. This can be achieved by having a lower - * outline level collapsed, thus hiding all the child rows. Note that in - * this case, if the lowest level were expanded, the middle level would - * remain collapsed. - * - * @param rowIndex - - * the row involved, 0 based - * @param collapse - - * boolean value for collapse - */ - @Override - public void setRowGroupCollapsed(int rowIndex, boolean collapse) { - if (collapse) { - collapseRow(rowIndex); - } else { - expandRow(rowIndex); - } - } - - /** - * @param rowIndex the zero based row index to collapse - */ - private void collapseRow(int rowIndex) { - XSSFRow row = getRow(rowIndex); - if (row != null) { - int startRow = findStartOfRowOutlineGroup(rowIndex); - - // Hide all the columns until the end of the group - int lastRow = writeHidden(row, startRow, true); - if (getRow(lastRow) != null) { - getRow(lastRow).getCTRow().setCollapsed(true); - } else { - XSSFRow newRow = createRow(lastRow); - newRow.getCTRow().setCollapsed(true); - } - } - } - - /** - * @param rowIndex the zero based row index to find from - */ - private int findStartOfRowOutlineGroup(int rowIndex) { - // Find the start of the group. - short level = getRow(rowIndex).getCTRow().getOutlineLevel(); - int currentRow = rowIndex; - while (getRow(currentRow) != null) { - if (getRow(currentRow).getCTRow().getOutlineLevel() < level) { - return currentRow + 1; - } - currentRow--; - } - return currentRow; - } - - private int writeHidden(XSSFRow xRow, int rowIndex, boolean hidden) { - short level = xRow.getCTRow().getOutlineLevel(); - for (Iterator it = rowIterator(); it.hasNext();) { - xRow = (XSSFRow) it.next(); - - // skip rows before the start of this group - if(xRow.getRowNum() < rowIndex) { - continue; - } - - if (xRow.getCTRow().getOutlineLevel() >= level) { - xRow.getCTRow().setHidden(hidden); - rowIndex++; - } - - } - return rowIndex; - } - - /** - * @param rowNumber the zero based row index to expand - */ - private void expandRow(int rowNumber) { - if (rowNumber == -1) { - return; - } - XSSFRow row = getRow(rowNumber); - // If it is already expanded do nothing. - if (!row.getCTRow().isSetHidden()) { - return; - } - - // Find the start of the group. - int startIdx = findStartOfRowOutlineGroup(rowNumber); - - // Find the end of the group. - int endIdx = findEndOfRowOutlineGroup(rowNumber); - - // expand: - // collapsed must be unset - // hidden bit gets unset _if_ surrounding groups are expanded you can - // determine - // this by looking at the hidden bit of the enclosing group. You will - // have - // to look at the start and the end of the current group to determine - // which - // is the enclosing group - // hidden bit only is altered for this outline level. ie. don't - // un-collapse contained groups - short level = row.getCTRow().getOutlineLevel(); - if (!isRowGroupHiddenByParent(rowNumber)) { - for (int i = startIdx; i < endIdx; i++) { - if (level == getRow(i).getCTRow().getOutlineLevel()) { - getRow(i).getCTRow().unsetHidden(); - } else if (!isRowGroupCollapsed(i)) { - getRow(i).getCTRow().unsetHidden(); - } - } - } - // Write collapse field - CTRow ctRow = getRow(endIdx).getCTRow(); - // This avoids an IndexOutOfBounds if multiple nested groups are collapsed/expanded - if(ctRow.getCollapsed()) { - ctRow.unsetCollapsed(); - } - } - - /** - * @param row the zero based row index to find from - */ - public int findEndOfRowOutlineGroup(int row) { - short level = getRow(row).getCTRow().getOutlineLevel(); - int currentRow; - final int lastRowNum = getLastRowNum(); - for (currentRow = row; currentRow < lastRowNum; currentRow++) { - if (getRow(currentRow) == null - || getRow(currentRow).getCTRow().getOutlineLevel() < level) { - break; - } - } - return currentRow; - } - - /** - * @param row the zero based row index to find from - */ - private boolean isRowGroupHiddenByParent(int row) { - // Look out outline details of end - int endLevel; - boolean endHidden; - int endOfOutlineGroupIdx = findEndOfRowOutlineGroup(row); - if (getRow(endOfOutlineGroupIdx) == null) { - endLevel = 0; - endHidden = false; - } else { - endLevel = getRow(endOfOutlineGroupIdx).getCTRow().getOutlineLevel(); - endHidden = getRow(endOfOutlineGroupIdx).getCTRow().getHidden(); - } - - // Look out outline details of start - int startLevel; - boolean startHidden; - int startOfOutlineGroupIdx = findStartOfRowOutlineGroup(row); - if (startOfOutlineGroupIdx < 0 - || getRow(startOfOutlineGroupIdx) == null) { - startLevel = 0; - startHidden = false; - } else { - startLevel = getRow(startOfOutlineGroupIdx).getCTRow() - .getOutlineLevel(); - startHidden = getRow(startOfOutlineGroupIdx).getCTRow() - .getHidden(); - } - if (endLevel > startLevel) { - return endHidden; - } - return startHidden; - } - - /** - * @param row the zero based row index to find from - */ - private boolean isRowGroupCollapsed(int row) { - int collapseRow = findEndOfRowOutlineGroup(row) + 1; - if (getRow(collapseRow) == null) { - return false; - } - return getRow(collapseRow).getCTRow().getCollapsed(); - } - - /** - * Sets the zoom magnification for the sheet. The zoom is expressed as a - * fraction. For example to express a zoom of 75% use 3 for the numerator - * and 4 for the denominator. - * - * @param numerator The numerator for the zoom magnification. - * @param denominator The denominator for the zoom magnification. - * @deprecated 2015-11-23 (circa POI 3.14beta1). Use {@link #setZoom(int)} instead. - */ - @Deprecated - @Removal(version="3.16") - @Override - public void setZoom(int numerator, int denominator) { - int zoom = 100*numerator/denominator; - setZoom(zoom); - } - - /** - * Window zoom magnification for current view representing percent values. - * Valid values range from 10 to 400. Horizontal & Vertical scale together. - * - * For example: - *

    -     * 10 - 10%
    -     * 20 - 20%
    -     * ...
    -     * 100 - 100%
    -     * ...
    -     * 400 - 400%
    -     * 
    - * - * Current view can be Normal, Page Layout, or Page Break Preview. - * - * @param scale window zoom magnification - * @throws IllegalArgumentException if scale is invalid - */ - @Override - public void setZoom(int scale) { - if (scale < 10 || scale > 400) { - throw new IllegalArgumentException("Valid scale values range from 10 to 400"); - } - getSheetTypeSheetView().setZoomScale(scale); - } - - - /** - * copyRows rows from srcRows to this sheet starting at destStartRow - * - * Additionally copies merged regions that are completely defined in these - * rows (ie. merged 2 cells on a row to be shifted). - * @param srcRows the rows to copy. Formulas will be offset by the difference - * in the row number of the first row in srcRows and destStartRow (even if srcRows - * are from a different sheet). - * @param destStartRow the row in this sheet to paste the first row of srcRows - * the remainder of srcRows will be pasted below destStartRow per the cell copy policy - * @param policy is the cell copy policy, which can be used to merge the source and destination - * when the source is blank, copy styles only, paste as value, etc - */ - @Beta - public void copyRows(List srcRows, int destStartRow, CellCopyPolicy policy) { - if (srcRows == null || srcRows.size() == 0) { - throw new IllegalArgumentException("No rows to copy"); - } - final Row srcStartRow = srcRows.get(0); - final Row srcEndRow = srcRows.get(srcRows.size() - 1); - - if (srcStartRow == null) { - throw new IllegalArgumentException("copyRows: First row cannot be null"); - } - - final int srcStartRowNum = srcStartRow.getRowNum(); - final int srcEndRowNum = srcEndRow.getRowNum(); - - // check row numbers to make sure they are continuous and increasing (monotonic) - // and srcRows does not contain null rows - final int size = srcRows.size(); - for (int index=1; index < size; index++) { - final Row curRow = srcRows.get(index); - if (curRow == null) { - throw new IllegalArgumentException("srcRows may not contain null rows. Found null row at index " + index + "."); - //} else if (curRow.getRowNum() != prevRow.getRowNum() + 1) { - // throw new IllegalArgumentException("srcRows must contain continuously increasing row numbers. " + - // "Got srcRows[" + (index-1) + "]=Row " + prevRow.getRowNum() + ", srcRows[" + index + "]=Row " + curRow.getRowNum() + "."); - // FIXME: assumes row objects belong to non-null sheets and sheets belong to non-null workbooks. - } else if (srcStartRow.getSheet().getWorkbook() != curRow.getSheet().getWorkbook()) { - throw new IllegalArgumentException("All rows in srcRows must belong to the same sheet in the same workbook." + - "Expected all rows from same workbook (" + srcStartRow.getSheet().getWorkbook() + "). " + - "Got srcRows[" + index + "] from different workbook (" + curRow.getSheet().getWorkbook() + ")."); - } else if (srcStartRow.getSheet() != curRow.getSheet()) { - throw new IllegalArgumentException("All rows in srcRows must belong to the same sheet. " + - "Expected all rows from " + srcStartRow.getSheet().getSheetName() + ". " + - "Got srcRows[" + index + "] from " + curRow.getSheet().getSheetName()); - } - } - - // FIXME: is special behavior needed if srcRows and destRows belong to the same sheets and the regions overlap? - - final CellCopyPolicy options = new CellCopyPolicy(policy); - // avoid O(N^2) performance scanning through all regions for each row - // merged regions will be copied after all the rows have been copied - options.setCopyMergedRegions(false); - - // FIXME: if srcRows contains gaps or null values, clear out those rows that will be overwritten - // how will this work with merging (copy just values, leave cell styles in place?) - - int r = destStartRow; - for (Row srcRow : srcRows) { - int destRowNum; - if (policy.isCondenseRows()) { - destRowNum = r++; - } else { - final int shift = (srcRow.getRowNum() - srcStartRowNum); - destRowNum = destStartRow + shift; - } - //removeRow(destRowNum); //this probably clears all external formula references to destRow, causing unwanted #REF! errors - final XSSFRow destRow = createRow(destRowNum); - destRow.copyRowFrom(srcRow, options); - } - - // ====================== - // Only do additional copy operations here that cannot be done with Row.copyFromRow(Row, options) - // reasons: operation needs to interact with multiple rows or sheets - - // Copy merged regions that are contained within the copy region - if (policy.isCopyMergedRegions()) { - // FIXME: is this something that rowShifter could be doing? - final int shift = destStartRow - srcStartRowNum; - for (CellRangeAddress srcRegion : srcStartRow.getSheet().getMergedRegions()) { - if (srcStartRowNum <= srcRegion.getFirstRow() && srcRegion.getLastRow() <= srcEndRowNum) { - // srcRegion is fully inside the copied rows - final CellRangeAddress destRegion = srcRegion.copy(); - destRegion.setFirstRow(destRegion.getFirstRow() + shift); - destRegion.setLastRow(destRegion.getLastRow() + shift); - addMergedRegion(destRegion); - } - } - } - } - - /** - * Copies rows between srcStartRow and srcEndRow to the same sheet, starting at destStartRow - * Convenience function for {@link #copyRows(List, int, CellCopyPolicy)} - * - * Equivalent to copyRows(getRows(srcStartRow, srcEndRow, false), destStartRow, cellCopyPolicy) - * - * @param srcStartRow the index of the first row to copy the cells from in this sheet - * @param srcEndRow the index of the last row to copy the cells from in this sheet - * @param destStartRow the index of the first row to copy the cells to in this sheet - * @param cellCopyPolicy the policy to use to determine how cells are copied - */ - @Beta - public void copyRows(int srcStartRow, int srcEndRow, int destStartRow, CellCopyPolicy cellCopyPolicy) { - final List srcRows = getRows(srcStartRow, srcEndRow, false); //FIXME: should be false, no need to create rows where src is only to copy them to dest - copyRows(srcRows, destStartRow, cellCopyPolicy); - } - - /** - * Shifts rows between startRow and endRow n number of rows. - * If you use a negative number, it will shift rows up. - * Code ensures that rows don't wrap around. - * - * Calls shiftRows(startRow, endRow, n, false, false); - * - *

    - * Additionally shifts merged regions that are completely defined in these - * rows (ie. merged 2 cells on a row to be shifted). - * @param startRow the row to start shifting - * @param endRow the row to end shifting - * @param n the number of rows to shift - */ - @Override - public void shiftRows(int startRow, int endRow, int n) { - shiftRows(startRow, endRow, n, false, false); - } - - /** - * Shifts rows between startRow and endRow n number of rows. - * If you use a negative number, it will shift rows up. - * Code ensures that rows don't wrap around - * - *

    - * Additionally shifts merged regions that are completely defined in these - * rows (ie. merged 2 cells on a row to be shifted). All merged regions that are - * completely overlaid by shifting will be deleted. - *

    - * @param startRow the row to start shifting - * @param endRow the row to end shifting - * @param n the number of rows to shift - * @param copyRowHeight whether to copy the row height during the shift - * @param resetOriginalRowHeight whether to set the original row's height to the default - */ - @Override - public void shiftRows(int startRow, int endRow, final int n, boolean copyRowHeight, boolean resetOriginalRowHeight) { - XSSFVMLDrawing vml = getVMLDrawing(false); - - // first remove all rows which will be overwritten - for (Iterator it = rowIterator() ; it.hasNext() ; ) { - XSSFRow row = (XSSFRow)it.next(); - int rownum = row.getRowNum(); - - // check if we should remove this row as it will be overwritten by the data later - if (shouldRemoveRow(startRow, endRow, n, rownum)) { - // remove row from worksheet.getSheetData row array - // Performance optimization: explicit boxing is slightly faster than auto-unboxing, though may use more memory - final Integer rownumI = new Integer(row.getRowNum()); // NOSONAR - int idx = _rows.headMap(rownumI).size(); - worksheet.getSheetData().removeRow(idx); - - // remove row from _rows - it.remove(); - - // FIXME: (performance optimization) this should be moved outside the for-loop so that comments only needs to be iterated over once. - // also remove any comments associated with this row - if(sheetComments != null){ - CTCommentList lst = sheetComments.getCTComments().getCommentList(); - for (CTComment comment : lst.getCommentArray()) { - String strRef = comment.getRef(); - CellAddress ref = new CellAddress(strRef); - - // is this comment part of the current row? - if(ref.getRow() == rownum) { - sheetComments.removeComment(ref); - vml.removeCommentShape(ref.getRow(), ref.getColumn()); - } - } - } - // FIXME: (performance optimization) this should be moved outside the for-loop so that hyperlinks only needs to be iterated over once. - // also remove any hyperlinks associated with this row - if (hyperlinks != null) { - for (XSSFHyperlink link : new ArrayList(hyperlinks)) { - CellReference ref = new CellReference(link.getCellRef()); - if (ref.getRow() == rownum) { - hyperlinks.remove(link); - } - } - } - } - } - - // then do the actual moving and also adjust comments/rowHeight - // we need to sort it in a way so the shifting does not mess up the structures, - // i.e. when shifting down, start from down and go up, when shifting up, vice-versa - SortedMap commentsToShift = new TreeMap(new Comparator() { - @Override - public int compare(XSSFComment o1, XSSFComment o2) { - int row1 = o1.getRow(); - int row2 = o2.getRow(); - - if(row1 == row2) { - // ordering is not important when row is equal, but don't return zero to still - // get multiple comments per row into the map - return o1.hashCode() - o2.hashCode(); - } - - // when shifting down, sort higher row-values first - if(n > 0) { - return row1 < row2 ? 1 : -1; - } else { - // sort lower-row values first when shifting up - return row1 > row2 ? 1 : -1; - } - } - }); - - - for (Iterator it = rowIterator() ; it.hasNext() ; ) { - XSSFRow row = (XSSFRow)it.next(); - int rownum = row.getRowNum(); - - if(sheetComments != null){ - // calculate the new rownum - int newrownum = shiftedRowNum(startRow, endRow, n, rownum); - - // is there a change necessary for the current row? - if(newrownum != rownum) { - CTCommentList lst = sheetComments.getCTComments().getCommentList(); - for (CTComment comment : lst.getCommentArray()) { - String oldRef = comment.getRef(); - CellReference ref = new CellReference(oldRef); - - // is this comment part of the current row? - if(ref.getRow() == rownum) { - XSSFComment xssfComment = new XSSFComment(sheetComments, comment, - vml == null ? null : vml.findCommentShape(rownum, ref.getCol())); - - // we should not perform the shifting right here as we would then find - // already shifted comments and would shift them again... - commentsToShift.put(xssfComment, newrownum); - } - } - } - } - - if(rownum < startRow || rownum > endRow) { - continue; - } - - if (!copyRowHeight) { - row.setHeight((short)-1); - } - - row.shift(n); - } - - // adjust all the affected comment-structures now - // the Map is sorted and thus provides them in the order that we need here, - // i.e. from down to up if shifting down, vice-versa otherwise - for(Map.Entry entry : commentsToShift.entrySet()) { - entry.getKey().setRow(entry.getValue()); - } - - XSSFRowShifter rowShifter = new XSSFRowShifter(this); - - int sheetIndex = getWorkbook().getSheetIndex(this); - String sheetName = getWorkbook().getSheetName(sheetIndex); - FormulaShifter shifter = FormulaShifter.createForRowShift( - sheetIndex, sheetName, startRow, endRow, n, SpreadsheetVersion.EXCEL2007); - - rowShifter.updateNamedRanges(shifter); - rowShifter.updateFormulas(shifter); - rowShifter.shiftMergedRegions(startRow, endRow, n); - rowShifter.updateConditionalFormatting(shifter); - rowShifter.updateHyperlinks(shifter); - - //rebuild the _rows map - Map map = new HashMap(); - for(XSSFRow r : _rows.values()) { - // Performance optimization: explicit boxing is slightly faster than auto-unboxing, though may use more memory - final Integer rownumI = new Integer(r.getRowNum()); // NOSONAR - map.put(rownumI, r); - } - _rows.clear(); - _rows.putAll(map); - } - - private int shiftedRowNum(int startRow, int endRow, int n, int rownum) { - // no change if before any affected row - if(rownum < startRow && (n > 0 || (startRow - rownum) > n)) { - return rownum; - } - - // no change if after any affected row - if(rownum > endRow && (n < 0 || (rownum - endRow) > n)) { - return rownum; - } - - // row before and things are moved up - if(rownum < startRow) { - // row is moved down by the shifting - return rownum + (endRow - startRow); - } - - // row is after and things are moved down - if(rownum > endRow) { - // row is moved up by the shifting - return rownum - (endRow - startRow); - } - - // row is part of the shifted block - return rownum + n; - } - - /** - * Location of the top left visible cell Location of the top left visible cell in the bottom right - * pane (when in Left-to-Right mode). - * - * @param toprow the top row to show in desktop window pane - * @param leftcol the left column to show in desktop window pane - */ - @Override - public void showInPane(int toprow, int leftcol) { - CellReference cellReference = new CellReference(toprow, leftcol); - String cellRef = cellReference.formatAsString(); - getPane().setTopLeftCell(cellRef); - } - - @Override - public void ungroupColumn(int fromColumn, int toColumn) { - CTCols cols = worksheet.getColsArray(0); - for (int index = fromColumn; index <= toColumn; index++) { - CTCol col = columnHelper.getColumn(index, false); - if (col != null) { - short outlineLevel = col.getOutlineLevel(); - col.setOutlineLevel((short) (outlineLevel - 1)); - index = (int) col.getMax(); - - if (col.getOutlineLevel() <= 0) { - int colIndex = columnHelper.getIndexOfColumn(cols, col); - worksheet.getColsArray(0).removeCol(colIndex); - } - } - } - worksheet.setColsArray(0, cols); - setSheetFormatPrOutlineLevelCol(); - } - - /** - * Ungroup a range of rows that were previously groupped - * - * @param fromRow start row (0-based) - * @param toRow end row (0-based) - */ - @Override - public void ungroupRow(int fromRow, int toRow) { - for (int i = fromRow; i <= toRow; i++) { - XSSFRow xrow = getRow(i); - if (xrow != null) { - CTRow ctRow = xrow.getCTRow(); - int outlineLevel = ctRow.getOutlineLevel(); - ctRow.setOutlineLevel((short) (outlineLevel - 1)); - //remove a row only if the row has no cell and if the outline level is 0 - if (outlineLevel == 1 && xrow.getFirstCellNum() == -1) { - removeRow(xrow); - } - } - } - setSheetFormatPrOutlineLevelRow(); - } - - private void setSheetFormatPrOutlineLevelRow(){ - short maxLevelRow=getMaxOutlineLevelRows(); - getSheetTypeSheetFormatPr().setOutlineLevelRow(maxLevelRow); - } - - private void setSheetFormatPrOutlineLevelCol(){ - short maxLevelCol=getMaxOutlineLevelCols(); - getSheetTypeSheetFormatPr().setOutlineLevelCol(maxLevelCol); - } - - private CTSheetViews getSheetTypeSheetViews() { - if (worksheet.getSheetViews() == null) { - worksheet.setSheetViews(CTSheetViews.Factory.newInstance()); - worksheet.getSheetViews().addNewSheetView(); - } - return worksheet.getSheetViews(); - } - - /** - * Returns a flag indicating whether this sheet is selected. - *

    - * When only 1 sheet is selected and active, this value should be in synch with the activeTab value. - * In case of a conflict, the Start Part setting wins and sets the active sheet tab. - *

    - * Note: multiple sheets can be selected, but only one sheet can be active at one time. - * - * @return true if this sheet is selected - */ - @Override - public boolean isSelected() { - CTSheetView view = getDefaultSheetView(); - return view != null && view.getTabSelected(); - } - - /** - * Sets a flag indicating whether this sheet is selected. - * - *

    - * When only 1 sheet is selected and active, this value should be in synch with the activeTab value. - * In case of a conflict, the Start Part setting wins and sets the active sheet tab. - *

    - * Note: multiple sheets can be selected, but only one sheet can be active at one time. - * - * @param value true if this sheet is selected - */ - @Override - public void setSelected(boolean value) { - CTSheetViews views = getSheetTypeSheetViews(); - for (CTSheetView view : views.getSheetViewArray()) { - view.setTabSelected(value); - } - } - - /** - * Register a hyperlink in the collection of hyperlinks on this sheet - * - * @param hyperlink the link to add - */ - @Internal - public void addHyperlink(XSSFHyperlink hyperlink) { - hyperlinks.add(hyperlink); - } - - /** - * Removes a hyperlink in the collection of hyperlinks on this sheet - * - * @param row row index - * @param column column index - */ - @Internal - public void removeHyperlink(int row, int column) { - // CTHyperlinks is regenerated from scratch when writing out the spreadsheet - // so don't worry about maintaining hyperlinks and CTHyperlinks in parallel. - // only maintain hyperlinks - String ref = new CellReference(row, column).formatAsString(); - for (Iterator it = hyperlinks.iterator(); it.hasNext();) { - XSSFHyperlink hyperlink = it.next(); - if (hyperlink.getCellRef().equals(ref)) { - it.remove(); - return; - } - } - } - - /** - * Return location of the active cell, e.g. A1. - * - * @return the location of the active cell. - */ - @Override - public CellAddress getActiveCell() { - String address = getSheetTypeSelection().getActiveCell(); - if (address == null) { - return null; - } - return new CellAddress(address); - } - - /** - * Sets location of the active cell - * - * @param cellRef the location of the active cell, e.g. A1.. - * @deprecated 3.14beta2 (circa 2015-12-05). Use {@link #setActiveCell(CellAddress)} instead. - */ - @Deprecated - @Removal(version="3.16") - public void setActiveCell(String cellRef) { - CTSelection ctsel = getSheetTypeSelection(); - ctsel.setActiveCell(cellRef); - ctsel.setSqref(Arrays.asList(cellRef)); - } - - /** - * {@inheritDoc} - */ - @Override - public void setActiveCell(CellAddress address) { - String ref = address.formatAsString(); - CTSelection ctsel = getSheetTypeSelection(); - ctsel.setActiveCell(ref); - ctsel.setSqref(Arrays.asList(ref)); - } - - /** - * Does this sheet have any comments on it? We need to know, - * so we can decide about writing it to disk or not - */ - public boolean hasComments() { - return sheetComments != null && sheetComments.getNumberOfComments() > 0; - } - - protected int getNumberOfComments() { - return sheetComments == null ? 0 : sheetComments.getNumberOfComments(); - } - - private CTSelection getSheetTypeSelection() { - if (getSheetTypeSheetView().sizeOfSelectionArray() == 0) { - getSheetTypeSheetView().insertNewSelection(0); - } - return getSheetTypeSheetView().getSelectionArray(0); - } - - /** - * Return the default sheet view. This is the last one if the sheet's views, according to sec. 3.3.1.83 - * of the OOXML spec: "A single sheet view definition. When more than 1 sheet view is defined in the file, - * it means that when opening the workbook, each sheet view corresponds to a separate window within the - * spreadsheet application, where each window is showing the particular sheet. containing the same - * workbookViewId value, the last sheetView definition is loaded, and the others are discarded. - * When multiple windows are viewing the same sheet, multiple sheetView elements (with corresponding - * workbookView entries) are saved." - */ - private CTSheetView getDefaultSheetView() { - CTSheetViews views = getSheetTypeSheetViews(); - if (views == null) { - return null; - } - int sz = views.sizeOfSheetViewArray(); - return (sz == 0) ? null : views.getSheetViewArray(sz - 1); - } - - /** - * Returns the sheet's comments object if there is one, - * or null if not - * - * @param create create a new comments table if it does not exist - */ - protected CommentsTable getCommentsTable(boolean create) { - if(sheetComments == null && create){ - // Try to create a comments table with the same number as - // the sheet has (i.e. sheet 1 -> comments 1) - try { - sheetComments = (CommentsTable)createRelationship( - XSSFRelation.SHEET_COMMENTS, XSSFFactory.getInstance(), (int)sheet.getSheetId()); - } catch(PartAlreadyExistsException e) { - // Technically a sheet doesn't need the same number as - // it's comments, and clearly someone has already pinched - // our number! Go for the next available one instead - sheetComments = (CommentsTable)createRelationship( - XSSFRelation.SHEET_COMMENTS, XSSFFactory.getInstance(), -1); - } - } - return sheetComments; - } - - private CTPageSetUpPr getSheetTypePageSetUpPr() { - CTSheetPr sheetPr = getSheetTypeSheetPr(); - return sheetPr.isSetPageSetUpPr() ? sheetPr.getPageSetUpPr() : sheetPr.addNewPageSetUpPr(); - } - - private static boolean shouldRemoveRow(int startRow, int endRow, int n, int rownum) { - // is this row in the target-window where the moved rows will land? - if (rownum >= (startRow + n) && rownum <= (endRow + n)) { - // only remove it if the current row is not part of the data that is copied - if (n > 0 && rownum > endRow) { - return true; - } - else if (n < 0 && rownum < startRow) { - return true; - } - } - return false; - } - - private CTPane getPane() { - if (getDefaultSheetView().getPane() == null) { - getDefaultSheetView().addNewPane(); - } - return getDefaultSheetView().getPane(); - } - - /** - * Return a master shared formula by index - * - * @param sid shared group index - * @return a CTCellFormula bean holding shared formula or null if not found - */ - @Internal - public CTCellFormula getSharedFormula(int sid){ - return sharedFormulas.get(sid); - } - - void onReadCell(XSSFCell cell){ - //collect cells holding shared formulas - CTCell ct = cell.getCTCell(); - CTCellFormula f = ct.getF(); - if (f != null && f.getT() == STCellFormulaType.SHARED && f.isSetRef() && f.getStringValue() != null) { - // save a detached copy to avoid XmlValueDisconnectedException, - // this may happen when the master cell of a shared formula is changed - CTCellFormula sf = (CTCellFormula)f.copy(); - CellRangeAddress sfRef = CellRangeAddress.valueOf(sf.getRef()); - CellReference cellRef = new CellReference(cell); - // If the shared formula range precedes the master cell then the preceding part is discarded, e.g. - // if the cell is E60 and the shared formula range is C60:M85 then the effective range is E60:M85 - // see more details in https://issues.apache.org/bugzilla/show_bug.cgi?id=51710 - if(cellRef.getCol() > sfRef.getFirstColumn() || cellRef.getRow() > sfRef.getFirstRow()){ - String effectiveRef = new CellRangeAddress( - Math.max(cellRef.getRow(), sfRef.getFirstRow()), sfRef.getLastRow(), - Math.max(cellRef.getCol(), sfRef.getFirstColumn()), sfRef.getLastColumn()).formatAsString(); - sf.setRef(effectiveRef); - } - - sharedFormulas.put((int)f.getSi(), sf); - } - if (f != null && f.getT() == STCellFormulaType.ARRAY && f.getRef() != null) { - arrayFormulas.add(CellRangeAddress.valueOf(f.getRef())); - } - } - - @Override - protected void commit() throws IOException { - PackagePart part = getPackagePart(); - OutputStream out = part.getOutputStream(); - write(out); - out.close(); - } - - protected void write(OutputStream out) throws IOException { - boolean setToNull = false; - if(worksheet.sizeOfColsArray() == 1) { - CTCols col = worksheet.getColsArray(0); - if(col.sizeOfColArray() == 0) { - setToNull = true; - // this is necessary so that we do not write an empty item into the sheet-xml in the xlsx-file - // Excel complains about a corrupted file if this shows up there! - worksheet.setColsArray(null); - } else { - setColWidthAttribute(col); - } - } - - // Now re-generate our CTHyperlinks, if needed - if(hyperlinks.size() > 0) { - if(worksheet.getHyperlinks() == null) { - worksheet.addNewHyperlinks(); - } - CTHyperlink[] ctHls = new CTHyperlink[hyperlinks.size()]; - for(int i=0; i=0; i--) { - worksheet.getHyperlinks().removeHyperlink(i); - } - // For some reason, we have to remove the hyperlinks one by one from the CTHyperlinks array - // before unsetting the hyperlink array. - // Resetting the hyperlink array seems to break some XML nodes. - //worksheet.getHyperlinks().setHyperlinkArray(new CTHyperlink[0]); - worksheet.unsetHyperlinks(); - } else { - // nothing to do - } - } - - int minCell=Integer.MAX_VALUE, maxCell=Integer.MIN_VALUE; - for(XSSFRow row : _rows.values()){ - // first perform the normal write actions for the row - row.onDocumentWrite(); - - // then calculate min/max cell-numbers for the worksheet-dimension - if(row.getFirstCellNum() != -1) { - minCell = Math.min(minCell, row.getFirstCellNum()); - } - if(row.getLastCellNum() != -1) { - maxCell = Math.max(maxCell, row.getLastCellNum()); - } - } - - // finally, if we had at least one cell we can populate the optional dimension-field - if(minCell != Integer.MAX_VALUE) { - String ref = new CellRangeAddress(getFirstRowNum(), getLastRowNum(), minCell, maxCell).formatAsString(); - if(worksheet.isSetDimension()) { - worksheet.getDimension().setRef(ref); - } else { - worksheet.addNewDimension().setRef(ref); - } - } - - XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS); - xmlOptions.setSaveSyntheticDocumentElement(new QName(CTWorksheet.type.getName().getNamespaceURI(), "worksheet")); - - worksheet.save(out, xmlOptions); - - // Bug 52233: Ensure that we have a col-array even if write() removed it - if(setToNull) { - worksheet.addNewCols(); - } - } - - /** - * @return true when Autofilters are locked and the sheet is protected. - */ - public boolean isAutoFilterLocked() { - return isSheetLocked() && safeGetProtectionField().getAutoFilter(); - } - - /** - * @return true when Deleting columns is locked and the sheet is protected. - */ - public boolean isDeleteColumnsLocked() { - return isSheetLocked() && safeGetProtectionField().getDeleteColumns(); - } - - /** - * @return true when Deleting rows is locked and the sheet is protected. - */ - public boolean isDeleteRowsLocked() { - return isSheetLocked() && safeGetProtectionField().getDeleteRows(); - } - - /** - * @return true when Formatting cells is locked and the sheet is protected. - */ - public boolean isFormatCellsLocked() { - return isSheetLocked() && safeGetProtectionField().getFormatCells(); - } - - /** - * @return true when Formatting columns is locked and the sheet is protected. - */ - public boolean isFormatColumnsLocked() { - return isSheetLocked() && safeGetProtectionField().getFormatColumns(); - } - - /** - * @return true when Formatting rows is locked and the sheet is protected. - */ - public boolean isFormatRowsLocked() { - return isSheetLocked() && safeGetProtectionField().getFormatRows(); - } - - /** - * @return true when Inserting columns is locked and the sheet is protected. - */ - public boolean isInsertColumnsLocked() { - return isSheetLocked() && safeGetProtectionField().getInsertColumns(); - } - - /** - * @return true when Inserting hyperlinks is locked and the sheet is protected. - */ - public boolean isInsertHyperlinksLocked() { - return isSheetLocked() && safeGetProtectionField().getInsertHyperlinks(); - } - - /** - * @return true when Inserting rows is locked and the sheet is protected. - */ - public boolean isInsertRowsLocked() { - return isSheetLocked() && safeGetProtectionField().getInsertRows(); - } - - /** - * @return true when Pivot tables are locked and the sheet is protected. - */ - public boolean isPivotTablesLocked() { - return isSheetLocked() && safeGetProtectionField().getPivotTables(); - } - - /** - * @return true when Sorting is locked and the sheet is protected. - */ - public boolean isSortLocked() { - return isSheetLocked() && safeGetProtectionField().getSort(); - } - - /** - * @return true when Objects are locked and the sheet is protected. - */ - public boolean isObjectsLocked() { - return isSheetLocked() && safeGetProtectionField().getObjects(); - } - - /** - * @return true when Scenarios are locked and the sheet is protected. - */ - public boolean isScenariosLocked() { - return isSheetLocked() && safeGetProtectionField().getScenarios(); - } - - /** - * @return true when Selection of locked cells is locked and the sheet is protected. - */ - public boolean isSelectLockedCellsLocked() { - return isSheetLocked() && safeGetProtectionField().getSelectLockedCells(); - } - - /** - * @return true when Selection of unlocked cells is locked and the sheet is protected. - */ - public boolean isSelectUnlockedCellsLocked() { - return isSheetLocked() && safeGetProtectionField().getSelectUnlockedCells(); - } - - /** - * @return true when Sheet is Protected. - */ - public boolean isSheetLocked() { - return worksheet.isSetSheetProtection() && safeGetProtectionField().getSheet(); - } - - /** - * Enable sheet protection - */ - public void enableLocking() { - safeGetProtectionField().setSheet(true); - } - - /** - * Disable sheet protection - */ - public void disableLocking() { - safeGetProtectionField().setSheet(false); - } - - /** - * Enable or disable Autofilters locking. - * This does not modify sheet protection status. - * To enforce this un-/locking, call {@link #disableLocking()} or {@link #enableLocking()} - */ - public void lockAutoFilter(boolean enabled) { - safeGetProtectionField().setAutoFilter(enabled); - } - - /** - * Enable or disable Deleting columns locking. - * This does not modify sheet protection status. - * To enforce this un-/locking, call {@link #disableLocking()} or {@link #enableLocking()} - */ - public void lockDeleteColumns(boolean enabled) { - safeGetProtectionField().setDeleteColumns(enabled); - } - - /** - * Enable or disable Deleting rows locking. - * This does not modify sheet protection status. - * To enforce this un-/locking, call {@link #disableLocking()} or {@link #enableLocking()} - */ - public void lockDeleteRows(boolean enabled) { - safeGetProtectionField().setDeleteRows(enabled); - } - - /** - * Enable or disable Formatting cells locking. - * This does not modify sheet protection status. - * To enforce this un-/locking, call {@link #disableLocking()} or {@link #enableLocking()} - */ - public void lockFormatCells(boolean enabled) { - safeGetProtectionField().setFormatCells(enabled); - } - - /** - * Enable or disable Formatting columns locking. - * This does not modify sheet protection status. - * To enforce this un-/locking, call {@link #disableLocking()} or {@link #enableLocking()} - */ - public void lockFormatColumns(boolean enabled) { - safeGetProtectionField().setFormatColumns(enabled); - } - - /** - * Enable or disable Formatting rows locking. - * This does not modify sheet protection status. - * To enforce this un-/locking, call {@link #disableLocking()} or {@link #enableLocking()} - */ - public void lockFormatRows(boolean enabled) { - safeGetProtectionField().setFormatRows(enabled); - } - - /** - * Enable or disable Inserting columns locking. - * This does not modify sheet protection status. - * To enforce this un-/locking, call {@link #disableLocking()} or {@link #enableLocking()} - */ - public void lockInsertColumns(boolean enabled) { - safeGetProtectionField().setInsertColumns(enabled); - } - - /** - * Enable or disable Inserting hyperlinks locking. - * This does not modify sheet protection status. - * To enforce this un-/locking, call {@link #disableLocking()} or {@link #enableLocking()} - */ - public void lockInsertHyperlinks(boolean enabled) { - safeGetProtectionField().setInsertHyperlinks(enabled); - } - - /** - * Enable or disable Inserting rows locking. - * This does not modify sheet protection status. - * To enforce this un-/locking, call {@link #disableLocking()} or {@link #enableLocking()} - */ - public void lockInsertRows(boolean enabled) { - safeGetProtectionField().setInsertRows(enabled); - } - - /** - * Enable or disable Pivot Tables locking. - * This does not modify sheet protection status. - * To enforce this un-/locking, call {@link #disableLocking()} or {@link #enableLocking()} - */ - public void lockPivotTables(boolean enabled) { - safeGetProtectionField().setPivotTables(enabled); - } - - /** - * Enable or disable Sort locking. - * This does not modify sheet protection status. - * To enforce this un-/locking, call {@link #disableLocking()} or {@link #enableLocking()} - */ - public void lockSort(boolean enabled) { - safeGetProtectionField().setSort(enabled); - } - - /** - * Enable or disable Objects locking. - * This does not modify sheet protection status. - * To enforce this un-/locking, call {@link #disableLocking()} or {@link #enableLocking()} - */ - public void lockObjects(boolean enabled) { - safeGetProtectionField().setObjects(enabled); - } - - /** - * Enable or disable Scenarios locking. - * This does not modify sheet protection status. - * To enforce this un-/locking, call {@link #disableLocking()} or {@link #enableLocking()} - */ - public void lockScenarios(boolean enabled) { - safeGetProtectionField().setScenarios(enabled); - } - - /** - * Enable or disable Selection of locked cells locking. - * This does not modify sheet protection status. - * To enforce this un-/locking, call {@link #disableLocking()} or {@link #enableLocking()} - */ - public void lockSelectLockedCells(boolean enabled) { - safeGetProtectionField().setSelectLockedCells(enabled); - } - - /** - * Enable or disable Selection of unlocked cells locking. - * This does not modify sheet protection status. - * To enforce this un-/locking, call {@link #disableLocking()} or {@link #enableLocking()} - */ - public void lockSelectUnlockedCells(boolean enabled) { - safeGetProtectionField().setSelectUnlockedCells(enabled); - } - - private CTSheetProtection safeGetProtectionField() { - if (!isSheetProtectionEnabled()) { - return worksheet.addNewSheetProtection(); - } - return worksheet.getSheetProtection(); - } - - /* package */ boolean isSheetProtectionEnabled() { - return (worksheet.isSetSheetProtection()); - } - - /* package */ boolean isCellInArrayFormulaContext(XSSFCell cell) { - for (CellRangeAddress range : arrayFormulas) { - if (range.isInRange(cell.getRowIndex(), cell.getColumnIndex())) { - return true; - } - } - return false; - } - - /* package */ XSSFCell getFirstCellInArrayFormula(XSSFCell cell) { - for (CellRangeAddress range : arrayFormulas) { - if (range.isInRange(cell.getRowIndex(), cell.getColumnIndex())) { - return getRow(range.getFirstRow()).getCell(range.getFirstColumn()); - } - } - return null; - } - - /** - * Also creates cells if they don't exist - */ - private CellRange getCellRange(CellRangeAddress range) { - int firstRow = range.getFirstRow(); - int firstColumn = range.getFirstColumn(); - int lastRow = range.getLastRow(); - int lastColumn = range.getLastColumn(); - int height = lastRow - firstRow + 1; - int width = lastColumn - firstColumn + 1; - List temp = new ArrayList(height*width); - for (int rowIn = firstRow; rowIn <= lastRow; rowIn++) { - for (int colIn = firstColumn; colIn <= lastColumn; colIn++) { - XSSFRow row = getRow(rowIn); - if (row == null) { - row = createRow(rowIn); - } - XSSFCell cell = row.getCell(colIn); - if (cell == null) { - cell = row.createCell(colIn); - } - temp.add(cell); - } - } - return SSCellRange.create(firstRow, firstColumn, height, width, temp, XSSFCell.class); - } - - @Override - public CellRange setArrayFormula(String formula, CellRangeAddress range) { - - CellRange cr = getCellRange(range); - - XSSFCell mainArrayFormulaCell = cr.getTopLeftCell(); - mainArrayFormulaCell.setCellArrayFormula(formula, range); - arrayFormulas.add(range); - return cr; - } - - @Override - public CellRange removeArrayFormula(Cell cell) { - if (cell.getSheet() != this) { - throw new IllegalArgumentException("Specified cell does not belong to this sheet."); - } - for (CellRangeAddress range : arrayFormulas) { - if (range.isInRange(cell)) { - arrayFormulas.remove(range); - CellRange cr = getCellRange(range); - for (XSSFCell c : cr) { - c.setCellType(CellType.BLANK); - } - return cr; - } - } - String ref = ((XSSFCell)cell).getCTCell().getR(); - throw new IllegalArgumentException("Cell " + ref + " is not part of an array formula."); - } - - - @Override - public DataValidationHelper getDataValidationHelper() { - return dataValidationHelper; - } - - @Override - public List getDataValidations() { - List xssfValidations = new ArrayList(); - CTDataValidations dataValidations = this.worksheet.getDataValidations(); - if( dataValidations!=null && dataValidations.getCount() > 0 ) { - for (CTDataValidation ctDataValidation : dataValidations.getDataValidationArray()) { - CellRangeAddressList addressList = new CellRangeAddressList(); - - @SuppressWarnings("unchecked") - List sqref = ctDataValidation.getSqref(); - for (String stRef : sqref) { - String[] regions = stRef.split(" "); - for (String region : regions) { - String[] parts = region.split(":"); - CellReference begin = new CellReference(parts[0]); - CellReference end = parts.length > 1 ? new CellReference(parts[1]) : begin; - CellRangeAddress cellRangeAddress = new CellRangeAddress(begin.getRow(), end.getRow(), begin.getCol(), end.getCol()); - addressList.addCellRangeAddress(cellRangeAddress); - } - } - XSSFDataValidation xssfDataValidation = new XSSFDataValidation(addressList, ctDataValidation); - xssfValidations.add(xssfDataValidation); - } - } - return xssfValidations; - } - - @Override - public void addValidationData(DataValidation dataValidation) { - XSSFDataValidation xssfDataValidation = (XSSFDataValidation)dataValidation; - CTDataValidations dataValidations = worksheet.getDataValidations(); - if( dataValidations==null ) { - dataValidations = worksheet.addNewDataValidations(); - } - int currentCount = dataValidations.sizeOfDataValidationArray(); - CTDataValidation newval = dataValidations.addNewDataValidation(); - newval.set(xssfDataValidation.getCtDdataValidation()); - dataValidations.setCount(currentCount + 1); - - } - - @SuppressWarnings("resource") - @Override - public XSSFAutoFilter setAutoFilter(CellRangeAddress range) { - CTAutoFilter af = worksheet.getAutoFilter(); - if(af == null) { - af = worksheet.addNewAutoFilter(); - } - - CellRangeAddress norm = new CellRangeAddress(range.getFirstRow(), range.getLastRow(), - range.getFirstColumn(), range.getLastColumn()); - String ref = norm.formatAsString(); - af.setRef(ref); - - XSSFWorkbook wb = getWorkbook(); - int sheetIndex = getWorkbook().getSheetIndex(this); - XSSFName name = wb.getBuiltInName(XSSFName.BUILTIN_FILTER_DB, sheetIndex); - if (name == null) { - name = wb.createBuiltInName(XSSFName.BUILTIN_FILTER_DB, sheetIndex); - } - - name.getCTName().setHidden(true); - CellReference r1 = new CellReference(getSheetName(), range.getFirstRow(), range.getFirstColumn(), true, true); - CellReference r2 = new CellReference(null, range.getLastRow(), range.getLastColumn(), true, true); - String fmla = r1.formatAsString() + ":" + r2.formatAsString(); - name.setRefersToFormula(fmla); - - return new XSSFAutoFilter(this); - } - - /** - * Creates a new Table, and associates it with this Sheet - */ - public XSSFTable createTable() { - if(! worksheet.isSetTableParts()) { - worksheet.addNewTableParts(); - } - - CTTableParts tblParts = worksheet.getTableParts(); - CTTablePart tbl = tblParts.addNewTablePart(); - - // Table numbers need to be unique in the file, not just - // unique within the sheet. Find the next one - int tableNumber = getPackagePart().getPackage().getPartsByContentType(XSSFRelation.TABLE.getContentType()).size() + 1; - RelationPart rp = createRelationship(XSSFRelation.TABLE, XSSFFactory.getInstance(), tableNumber, false); - XSSFTable table = rp.getDocumentPart(); - tbl.setId(rp.getRelationship().getId()); - - tables.put(tbl.getId(), table); - - return table; - } - - /** - * Returns any tables associated with this Sheet - */ - public List getTables() { - return new ArrayList(tables.values()); - } - - @Override - public XSSFSheetConditionalFormatting getSheetConditionalFormatting(){ - return new XSSFSheetConditionalFormatting(this); - } - - /** - * Get background color of the sheet tab. - * Returns null if no sheet tab color is set. - * - * @return the background color of the sheet tab - */ - public XSSFColor getTabColor() { - CTSheetPr pr = worksheet.getSheetPr(); - if(pr == null) { - pr = worksheet.addNewSheetPr(); - } - if (!pr.isSetTabColor()) { - return null; - } - return new XSSFColor(pr.getTabColor()); - } - - /** - * Set background color of the sheet tab - * - * @param colorIndex the indexed color to set, must be a constant from {@link org.apache.poi.ss.usermodel.IndexedColors} - * @deprecated 3.15-beta2. Removed in 3.17. Use {@link #setTabColor(XSSFColor)}. - */ - @Deprecated - @Removal(version="3.17") - public void setTabColor(int colorIndex) { - IndexedColors indexedColor = IndexedColors.fromInt(colorIndex); - XSSFColor color = new XSSFColor(indexedColor); - setTabColor(color); - } - - /** - * Set background color of the sheet tab - * - * @param color the color to set - */ - public void setTabColor(XSSFColor color) { - CTSheetPr pr = worksheet.getSheetPr(); - if(pr == null) { - pr = worksheet.addNewSheetPr(); - } - pr.setTabColor(color.getCTColor()); - } - - @Override - public CellRangeAddress getRepeatingRows() { - return getRepeatingRowsOrColums(true); - } - - - @Override - public CellRangeAddress getRepeatingColumns() { - return getRepeatingRowsOrColums(false); - } - - @Override - public void setRepeatingRows(CellRangeAddress rowRangeRef) { - CellRangeAddress columnRangeRef = getRepeatingColumns(); - setRepeatingRowsAndColumns(rowRangeRef, columnRangeRef); - } - - - @Override - public void setRepeatingColumns(CellRangeAddress columnRangeRef) { - CellRangeAddress rowRangeRef = getRepeatingRows(); - setRepeatingRowsAndColumns(rowRangeRef, columnRangeRef); - } - - - private void setRepeatingRowsAndColumns( - CellRangeAddress rowDef, CellRangeAddress colDef) { - int col1 = -1; - int col2 = -1; - int row1 = -1; - int row2 = -1; - - if (rowDef != null) { - row1 = rowDef.getFirstRow(); - row2 = rowDef.getLastRow(); - if ((row1 == -1 && row2 != -1) - || row1 < -1 || row2 < -1 || row1 > row2) { - throw new IllegalArgumentException("Invalid row range specification"); - } - } - if (colDef != null) { - col1 = colDef.getFirstColumn(); - col2 = colDef.getLastColumn(); - if ((col1 == -1 && col2 != -1) - || col1 < -1 || col2 < -1 || col1 > col2) { - throw new IllegalArgumentException( - "Invalid column range specification"); - } - } - - int sheetIndex = getWorkbook().getSheetIndex(this); - - boolean removeAll = rowDef == null && colDef == null; - - XSSFName name = getWorkbook().getBuiltInName( - XSSFName.BUILTIN_PRINT_TITLE, sheetIndex); - if (removeAll) { - if (name != null) { - getWorkbook().removeName(name); - } - return; - } - if (name == null) { - name = getWorkbook().createBuiltInName( - XSSFName.BUILTIN_PRINT_TITLE, sheetIndex); - } - - String reference = getReferenceBuiltInRecord( - name.getSheetName(), col1, col2, row1, row2); - name.setRefersToFormula(reference); - - // If the print setup isn't currently defined, then add it - // in but without printer defaults - // If it's already there, leave it as-is! - if (worksheet.isSetPageSetup() && worksheet.isSetPageMargins()) { - // Everything we need is already there - } else { - // Have initial ones put in place - getPrintSetup().setValidSettings(false); - } - } - - private static String getReferenceBuiltInRecord( - String sheetName, int startC, int endC, int startR, int endR) { - // Excel example for built-in title: - // 'second sheet'!$E:$F,'second sheet'!$2:$3 - - CellReference colRef = - new CellReference(sheetName, 0, startC, true, true); - CellReference colRef2 = - new CellReference(sheetName, 0, endC, true, true); - CellReference rowRef = - new CellReference(sheetName, startR, 0, true, true); - CellReference rowRef2 = - new CellReference(sheetName, endR, 0, true, true); - - String escapedName = SheetNameFormatter.format(sheetName); - - String c = ""; - String r = ""; - - if (startC != -1 || endC != -1) { - String col1 = colRef.getCellRefParts()[2]; - String col2 = colRef2.getCellRefParts()[2]; - c = escapedName + "!$" + col1 + ":$" + col2; - } - - if (startR != -1 || endR != -1) { - String row1 = rowRef.getCellRefParts()[1]; - String row2 = rowRef2.getCellRefParts()[1]; - if (!row1.equals("0") && !row2.equals("0")) { - r = escapedName + "!$" + row1 + ":$" + row2; - } - } - - StringBuilder rng = new StringBuilder(); - rng.append(c); - if(rng.length() > 0 && r.length() > 0) { - rng.append(','); - } - rng.append(r); - return rng.toString(); - } - - - private CellRangeAddress getRepeatingRowsOrColums(boolean rows) { - int sheetIndex = getWorkbook().getSheetIndex(this); - XSSFName name = getWorkbook().getBuiltInName( - XSSFName.BUILTIN_PRINT_TITLE, sheetIndex); - if (name == null ) { - return null; - } - String refStr = name.getRefersToFormula(); - if (refStr == null) { - return null; - } - String[] parts = refStr.split(","); - int maxRowIndex = SpreadsheetVersion.EXCEL2007.getLastRowIndex(); - int maxColIndex = SpreadsheetVersion.EXCEL2007.getLastColumnIndex(); - for (String part : parts) { - CellRangeAddress range = CellRangeAddress.valueOf(part); - if ((range.getFirstColumn() == 0 - && range.getLastColumn() == maxColIndex) - || (range.getFirstColumn() == -1 - && range.getLastColumn() == -1)) { - if (rows) { - return range; - } - } else if (range.getFirstRow() == 0 - && range.getLastRow() == maxRowIndex - || (range.getFirstRow() == -1 - && range.getLastRow() == -1)) { - if (!rows) { - return range; - } - } - } - return null; - } - - /** - * Creates an empty XSSFPivotTable and sets up all its relationships - * including: pivotCacheDefinition, pivotCacheRecords - * @return returns a pivotTable - */ - @SuppressWarnings("resource") - @Beta - private XSSFPivotTable createPivotTable() { - XSSFWorkbook wb = getWorkbook(); - List pivotTables = wb.getPivotTables(); - int tableId = getWorkbook().getPivotTables().size()+1; - //Create relationship between pivotTable and the worksheet - XSSFPivotTable pivotTable = (XSSFPivotTable) createRelationship(XSSFRelation.PIVOT_TABLE, - XSSFFactory.getInstance(), tableId); - pivotTable.setParentSheet(this); - pivotTables.add(pivotTable); - XSSFWorkbook workbook = getWorkbook(); - - //Create relationship between the pivot cache defintion and the workbook - XSSFPivotCacheDefinition pivotCacheDefinition = (XSSFPivotCacheDefinition) workbook. - createRelationship(XSSFRelation.PIVOT_CACHE_DEFINITION, XSSFFactory.getInstance(), tableId); - String rId = workbook.getRelationId(pivotCacheDefinition); - //Create relationship between pivotTable and pivotCacheDefinition without creating a new instance - PackagePart pivotPackagePart = pivotTable.getPackagePart(); - pivotPackagePart.addRelationship(pivotCacheDefinition.getPackagePart().getPartName(), - TargetMode.INTERNAL, XSSFRelation.PIVOT_CACHE_DEFINITION.getRelation()); - - pivotTable.setPivotCacheDefinition(pivotCacheDefinition); - - //Create pivotCache and sets up it's relationship with the workbook - pivotTable.setPivotCache(new XSSFPivotCache(workbook.addPivotCache(rId))); - - //Create relationship between pivotcacherecord and pivotcachedefinition - XSSFPivotCacheRecords pivotCacheRecords = (XSSFPivotCacheRecords) pivotCacheDefinition. - createRelationship(XSSFRelation.PIVOT_CACHE_RECORDS, XSSFFactory.getInstance(), tableId); - - //Set relationships id for pivotCacheDefinition to pivotCacheRecords - pivotTable.getPivotCacheDefinition().getCTPivotCacheDefinition().setId(pivotCacheDefinition.getRelationId(pivotCacheRecords)); - - wb.setPivotTables(pivotTables); - - return pivotTable; - } - - /** - * Create a pivot table using the AreaReference range on sourceSheet, at the given position. - * If the source reference contains a sheet name, it must match the sourceSheet - * @param source location of pivot data - * @param position A reference to the top left cell where the pivot table will start - * @param sourceSheet The sheet containing the source data, if the source reference doesn't contain a sheet name - * @throws IllegalArgumentException if source references a sheet different than sourceSheet - * @return The pivot table - */ - @Beta - public XSSFPivotTable createPivotTable(final AreaReference source, CellReference position, Sheet sourceSheet) { - final String sourceSheetName = source.getFirstCell().getSheetName(); - if(sourceSheetName != null && !sourceSheetName.equalsIgnoreCase(sourceSheet.getSheetName())) { - throw new IllegalArgumentException("The area is referenced in another sheet than the " - + "defined source sheet " + sourceSheet.getSheetName() + "."); - } - - return createPivotTable(position, sourceSheet, new PivotTableReferenceConfigurator() { - @Override - public void configureReference(CTWorksheetSource wsSource) { - final String[] firstCell = source.getFirstCell().getCellRefParts(); - final String firstRow = firstCell[1]; - final String firstCol = firstCell[2]; - final String[] lastCell = source.getLastCell().getCellRefParts(); - final String lastRow = lastCell[1]; - final String lastCol = lastCell[2]; - final String ref = firstCol+firstRow+':'+lastCol+lastRow; //or just source.formatAsString() - wsSource.setRef(ref); - } - }); - } - - /** - * Create a pivot table using the AreaReference or named/table range on sourceSheet, at the given position. - * If the source reference contains a sheet name, it must match the sourceSheet. - * @param position A reference to the top left cell where the pivot table will start - * @param sourceSheet The sheet containing the source data, if the source reference doesn't contain a sheet name - * @param refConfig A reference to the pivot table configurator - * @throws IllegalArgumentException if source references a sheet different than sourceSheet - * @return The pivot table - */ - private XSSFPivotTable createPivotTable(CellReference position, Sheet sourceSheet, PivotTableReferenceConfigurator refConfig) { - - XSSFPivotTable pivotTable = createPivotTable(); - //Creates default settings for the pivot table - pivotTable.setDefaultPivotTableDefinition(); - - //Set sources and references - pivotTable.createSourceReferences(position, sourceSheet, refConfig); - - //Create cachefield/s and empty SharedItems - must be after creating references - pivotTable.getPivotCacheDefinition().createCacheFields(sourceSheet); - pivotTable.createDefaultDataColumns(); - - return pivotTable; - } - - /** - * Create a pivot table using the AreaReference range, at the given position. - * If the source reference contains a sheet name, that sheet is used, otherwise this sheet is assumed as the source sheet. - * @param source location of pivot data - * @param position A reference to the top left cell where the pivot table will start - * @return The pivot table - */ - @Beta - public XSSFPivotTable createPivotTable(AreaReference source, CellReference position){ - final String sourceSheetName = source.getFirstCell().getSheetName(); - if(sourceSheetName != null && !sourceSheetName.equalsIgnoreCase(this.getSheetName())) { - final XSSFSheet sourceSheet = getWorkbook().getSheet(sourceSheetName); - return createPivotTable(source, position, sourceSheet); - } - return createPivotTable(source, position, this); - } - - /** - * Create a pivot table using the Name range reference on sourceSheet, at the given position. - * If the source reference contains a sheet name, it must match the sourceSheet - * @param source location of pivot data - * @param position A reference to the top left cell where the pivot table will start - * @param sourceSheet The sheet containing the source data, if the source reference doesn't contain a sheet name - * @throws IllegalArgumentException if source references a sheet different than sourceSheet - * @return The pivot table - */ - @Beta - public XSSFPivotTable createPivotTable(final Name source, CellReference position, Sheet sourceSheet) { - if(source.getSheetName() != null && !source.getSheetName().equals(sourceSheet.getSheetName())) { - throw new IllegalArgumentException("The named range references another sheet than the " - + "defined source sheet " + sourceSheet.getSheetName() + "."); - } - - return createPivotTable(position, sourceSheet, new PivotTableReferenceConfigurator() { - @Override - public void configureReference(CTWorksheetSource wsSource) { - wsSource.setName(source.getNameName()); - } - }); - } - - /** - * Create a pivot table using the Name range, at the given position. - * If the source reference contains a sheet name, that sheet is used, otherwise this sheet is assumed as the source sheet. - * @param source location of pivot data - * @param position A reference to the top left cell where the pivot table will start - * @return The pivot table - */ - @Beta - public XSSFPivotTable createPivotTable(Name source, CellReference position) { - return createPivotTable(source, position, getWorkbook().getSheet(source.getSheetName())); - } - - /** - * Create a pivot table using the Table, at the given position. - * Tables are required to have a sheet reference, so no additional logic around reference sheet is needed. - * @param source location of pivot data - * @param position A reference to the top left cell where the pivot table will start - * @return The pivot table - */ - @Beta - public XSSFPivotTable createPivotTable(final Table source, CellReference position) { - return createPivotTable(position, getWorkbook().getSheet(source.getSheetName()), new PivotTableReferenceConfigurator() { - @Override - public void configureReference(CTWorksheetSource wsSource) { - wsSource.setName(source.getName()); - } - }); - } - - /** - * Returns all the pivot tables for this Sheet - */ - @Beta - public List getPivotTables() { - List tables = new ArrayList(); - for (XSSFPivotTable table : getWorkbook().getPivotTables()) { - if (table.getParent() == this) { - tables.add(table); - } - } - return tables; - } - - @Override - public int getColumnOutlineLevel(int columnIndex) { - CTCol col = columnHelper.getColumn(columnIndex, false); - if (col == null) { - return 0; - } - return col.getOutlineLevel(); - } - - /** - * Add ignored errors (usually to suppress them in the UI of a consuming - * application). - * - * @param cell Cell. - * @param ignoredErrorTypes Types of error to ignore there. - */ - public void addIgnoredErrors(CellReference cell, IgnoredErrorType... ignoredErrorTypes) { - addIgnoredErrors(cell.formatAsString(), ignoredErrorTypes); - } - - /** - * Ignore errors across a range of cells. - * - * @param region Range of cells. - * @param ignoredErrorTypes Types of error to ignore there. - */ - public void addIgnoredErrors(CellRangeAddress region, IgnoredErrorType... ignoredErrorTypes) { - region.validate(SpreadsheetVersion.EXCEL2007); - addIgnoredErrors(region.formatAsString(), ignoredErrorTypes); - } - - /** - * Returns the errors currently being ignored and the ranges - * where they are ignored. - * - * @return Map of error type to the range(s) where they are ignored. - */ - public Map> getIgnoredErrors() { - Map> result = new LinkedHashMap>(); - if (worksheet.isSetIgnoredErrors()) { - for (CTIgnoredError err : worksheet.getIgnoredErrors().getIgnoredErrorList()) { - for (IgnoredErrorType errType : XSSFIgnoredErrorHelper.getErrorTypes(err)) { - if (!result.containsKey(errType)) { - result.put(errType, new LinkedHashSet()); - } - for (Object ref : err.getSqref()) { - result.get(errType).add(CellRangeAddress.valueOf(ref.toString())); - } - } - } - } - return result; - } - - private void addIgnoredErrors(String ref, IgnoredErrorType... ignoredErrorTypes) { - CTIgnoredErrors ctIgnoredErrors = worksheet.isSetIgnoredErrors() ? worksheet.getIgnoredErrors() : worksheet.addNewIgnoredErrors(); - CTIgnoredError ctIgnoredError = ctIgnoredErrors.addNewIgnoredError(); - XSSFIgnoredErrorHelper.addIgnoredErrors(ctIgnoredError, ref, ignoredErrorTypes); - } - - /** - * Determine the OleObject which links shapes with embedded resources - * - * @param shapeId the shape id - * @return the CTOleObject of the shape - */ - protected CTOleObject readOleObject(long shapeId) { - if (!getCTWorksheet().isSetOleObjects()) { - return null; - } - - // we use a XmlCursor here to handle oleObject with-/out AlternateContent wrappers - String xquery = "declare namespace p='"+XSSFRelation.NS_SPREADSHEETML+"' .//p:oleObject"; - XmlCursor cur = getCTWorksheet().getOleObjects().newCursor(); - try { - cur.selectPath(xquery); - CTOleObject coo = null; - while (cur.toNextSelection()) { - String sId = cur.getAttributeText(new QName(null, "shapeId")); - if (sId == null || Long.parseLong(sId) != shapeId) { - continue; - } - - XmlObject xObj = cur.getObject(); - if (xObj instanceof CTOleObject) { - // the unusual case ... - coo = (CTOleObject)xObj; - } else { - XMLStreamReader reader = cur.newXMLStreamReader(); - try { - CTOleObjects coos = CTOleObjects.Factory.parse(reader); - if (coos.sizeOfOleObjectArray() == 0) { - continue; - } - coo = coos.getOleObjectArray(0); - } catch (XmlException e) { - logger.log(POILogger.INFO, "can't parse CTOleObjects", e); - } finally { - try { - reader.close(); - } catch (XMLStreamException e) { - logger.log(POILogger.INFO, "can't close reader", e); - } - } - } - - // there are choice and fallback OleObject ... we prefer the one having the objectPr element, - // which is in the choice element - if (cur.toChild(XSSFRelation.NS_SPREADSHEETML, "objectPr")) { - break; - } - } - return (coo == null) ? null : coo; - } finally { - cur.dispose(); - } - } - - -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFSheetConditionalFormatting.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFSheetConditionalFormatting.java deleted file mode 100644 index 8c973e1c3..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFSheetConditionalFormatting.java +++ /dev/null @@ -1,295 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xssf.usermodel; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.ss.usermodel.ComparisonOperator; -import org.apache.poi.ss.usermodel.ConditionalFormatting; -import org.apache.poi.ss.usermodel.ConditionalFormattingRule; -import org.apache.poi.ss.usermodel.ExtendedColor; -import org.apache.poi.ss.usermodel.IconMultiStateFormatting.IconSet; -import org.apache.poi.ss.usermodel.SheetConditionalFormatting; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.CellRangeUtil; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCfRule; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTConditionalFormatting; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STCfType; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STConditionalFormattingOperator; - -/** - * XSSF Conditional Formattings - */ -public class XSSFSheetConditionalFormatting implements SheetConditionalFormatting { - /** Office 2010 Conditional Formatting extensions namespace */ - protected static final String CF_EXT_2009_NS_X14 = "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main"; - - private final XSSFSheet _sheet; - - /* package */ XSSFSheetConditionalFormatting(XSSFSheet sheet) { - _sheet = sheet; - } - - /** - * A factory method allowing to create a conditional formatting rule - * with a cell comparison operator

    - * TODO - formulas containing cell references are currently not parsed properly - * - * @param comparisonOperation - a constant value from - * {@link org.apache.poi.hssf.record.CFRuleBase.ComparisonOperator}:

    - *

      - *
    • BETWEEN
    • - *
    • NOT_BETWEEN
    • - *
    • EQUAL
    • - *
    • NOT_EQUAL
    • - *
    • GT
    • - *
    • LT
    • - *
    • GE
    • - *
    • LE
    • - *
    - *

    - * @param formula1 - formula for the valued, compared with the cell - * @param formula2 - second formula (only used with - * {@link org.apache.poi.ss.usermodel.ComparisonOperator#BETWEEN}) and - * {@link org.apache.poi.ss.usermodel.ComparisonOperator#NOT_BETWEEN} operations) - */ - public XSSFConditionalFormattingRule createConditionalFormattingRule( - byte comparisonOperation, - String formula1, - String formula2) { - - XSSFConditionalFormattingRule rule = new XSSFConditionalFormattingRule(_sheet); - CTCfRule cfRule = rule.getCTCfRule(); - cfRule.addFormula(formula1); - if(formula2 != null) cfRule.addFormula(formula2); - cfRule.setType(STCfType.CELL_IS); - STConditionalFormattingOperator.Enum operator; - switch (comparisonOperation){ - case ComparisonOperator.BETWEEN: operator = STConditionalFormattingOperator.BETWEEN; break; - case ComparisonOperator.NOT_BETWEEN: operator = STConditionalFormattingOperator.NOT_BETWEEN; break; - case ComparisonOperator.LT: operator = STConditionalFormattingOperator.LESS_THAN; break; - case ComparisonOperator.LE: operator = STConditionalFormattingOperator.LESS_THAN_OR_EQUAL; break; - case ComparisonOperator.GT: operator = STConditionalFormattingOperator.GREATER_THAN; break; - case ComparisonOperator.GE: operator = STConditionalFormattingOperator.GREATER_THAN_OR_EQUAL; break; - case ComparisonOperator.EQUAL: operator = STConditionalFormattingOperator.EQUAL; break; - case ComparisonOperator.NOT_EQUAL: operator = STConditionalFormattingOperator.NOT_EQUAL; break; - default: throw new IllegalArgumentException("Unknown comparison operator: " + comparisonOperation); - } - cfRule.setOperator(operator); - - return rule; - } - - public XSSFConditionalFormattingRule createConditionalFormattingRule( - byte comparisonOperation, - String formula) { - - return createConditionalFormattingRule(comparisonOperation, formula, null); - } - - /** - * A factory method allowing to create a conditional formatting rule with a formula.
    - * - * @param formula - formula for the valued, compared with the cell - */ - public XSSFConditionalFormattingRule createConditionalFormattingRule(String formula) { - XSSFConditionalFormattingRule rule = new XSSFConditionalFormattingRule(_sheet); - CTCfRule cfRule = rule.getCTCfRule(); - cfRule.addFormula(formula); - cfRule.setType(STCfType.EXPRESSION); - return rule; - } - - /** - * Create a Databar conditional formatting rule. - *

    The thresholds and colour for it will be created, but will be - * empty and require configuring with - * {@link XSSFConditionalFormattingRule#getDataBarFormatting()} - * then - * {@link XSSFDataBarFormatting#getMinThreshold()} - * and - * {@link XSSFDataBarFormatting#getMaxThreshold()} - */ - public XSSFConditionalFormattingRule createConditionalFormattingRule(XSSFColor color) { - XSSFConditionalFormattingRule rule = new XSSFConditionalFormattingRule(_sheet); - - // Have it setup, with suitable defaults - rule.createDataBarFormatting(color); - - // All done! - return rule; - } - public XSSFConditionalFormattingRule createConditionalFormattingRule(ExtendedColor color) { - return createConditionalFormattingRule((XSSFColor)color); - } - - /** - * A factory method allowing the creation of conditional formatting - * rules using an Icon Set / Multi-State formatting. - * The thresholds for it will be created, but will be empty - * and require configuring with - * {@link XSSFConditionalFormattingRule#getMultiStateFormatting()} - * then - * {@link XSSFIconMultiStateFormatting#getThresholds()} - */ - public XSSFConditionalFormattingRule createConditionalFormattingRule(IconSet iconSet) { - XSSFConditionalFormattingRule rule = new XSSFConditionalFormattingRule(_sheet); - - // Have it setup, with suitable defaults - rule.createMultiStateFormatting(iconSet); - - // All done! - return rule; - } - - /** - * Create a Color Scale / Color Gradient conditional formatting rule. - *

    The thresholds and colours for it will be created, but will be - * empty and require configuring with - * {@link XSSFConditionalFormattingRule#getColorScaleFormatting()} - * then - * {@link XSSFColorScaleFormatting#getThresholds()} - * and - * {@link XSSFColorScaleFormatting#getColors()} - */ - public XSSFConditionalFormattingRule createConditionalFormattingColorScaleRule() { - XSSFConditionalFormattingRule rule = new XSSFConditionalFormattingRule(_sheet); - - // Have it setup, with suitable defaults - rule.createColorScaleFormatting(); - - // All done! - return rule; - } - - public int addConditionalFormatting(CellRangeAddress[] regions, ConditionalFormattingRule[] cfRules) { - if (regions == null) { - throw new IllegalArgumentException("regions must not be null"); - } - for(CellRangeAddress range : regions) range.validate(SpreadsheetVersion.EXCEL2007); - - if (cfRules == null) { - throw new IllegalArgumentException("cfRules must not be null"); - } - if (cfRules.length == 0) { - throw new IllegalArgumentException("cfRules must not be empty"); - } - if (cfRules.length > 3) { - throw new IllegalArgumentException("Number of rules must not exceed 3"); - } - - CellRangeAddress[] mergeCellRanges = CellRangeUtil.mergeCellRanges(regions); - CTConditionalFormatting cf = _sheet.getCTWorksheet().addNewConditionalFormatting(); - List refs = new ArrayList(); - for(CellRangeAddress a : mergeCellRanges) refs.add(a.formatAsString()); - cf.setSqref(refs); - - int priority = 1; - for(CTConditionalFormatting c : _sheet.getCTWorksheet().getConditionalFormattingArray()){ - priority += c.sizeOfCfRuleArray(); - } - - for(ConditionalFormattingRule rule : cfRules){ - XSSFConditionalFormattingRule xRule = (XSSFConditionalFormattingRule)rule; - xRule.getCTCfRule().setPriority(priority++); - cf.addNewCfRule().set(xRule.getCTCfRule()); - } - return _sheet.getCTWorksheet().sizeOfConditionalFormattingArray() - 1; - } - - public int addConditionalFormatting(CellRangeAddress[] regions, - ConditionalFormattingRule rule1) - { - return addConditionalFormatting(regions, - rule1 == null ? null : new XSSFConditionalFormattingRule[] { - (XSSFConditionalFormattingRule)rule1 - }); - } - - public int addConditionalFormatting(CellRangeAddress[] regions, - ConditionalFormattingRule rule1, ConditionalFormattingRule rule2) - { - return addConditionalFormatting(regions, - rule1 == null ? null : new XSSFConditionalFormattingRule[] { - (XSSFConditionalFormattingRule)rule1, - (XSSFConditionalFormattingRule)rule2 - }); - } - - /** - * Adds a copy of HSSFConditionalFormatting object to the sheet - *

    This method could be used to copy HSSFConditionalFormatting object - * from one sheet to another. For example: - *

    -     * HSSFConditionalFormatting cf = sheet.getConditionalFormattingAt(index);
    -     * newSheet.addConditionalFormatting(cf);
    -     * 
    - * - * @param cf HSSFConditionalFormatting object - * @return index of the new Conditional Formatting object - */ - public int addConditionalFormatting( ConditionalFormatting cf ) { - XSSFConditionalFormatting xcf = (XSSFConditionalFormatting)cf; - CTWorksheet sh = _sheet.getCTWorksheet(); - sh.addNewConditionalFormatting().set(xcf.getCTConditionalFormatting().copy()); - return sh.sizeOfConditionalFormattingArray() - 1; - } - - /** - * gets Conditional Formatting object at a particular index - * - * @param index - * of the Conditional Formatting object to fetch - * @return Conditional Formatting object - */ - public XSSFConditionalFormatting getConditionalFormattingAt(int index) { - checkIndex(index); - CTConditionalFormatting cf = _sheet.getCTWorksheet().getConditionalFormattingArray(index); - return new XSSFConditionalFormatting(_sheet, cf); - } - - /** - * @return number of Conditional Formatting objects of the sheet - */ - public int getNumConditionalFormattings() { - return _sheet.getCTWorksheet().sizeOfConditionalFormattingArray(); - } - - /** - * removes a Conditional Formatting object by index - * @param index of a Conditional Formatting object to remove - */ - public void removeConditionalFormatting(int index) { - checkIndex(index); - _sheet.getCTWorksheet().removeConditionalFormatting(index); - } - - private void checkIndex(int index) { - int cnt = getNumConditionalFormattings(); - if (index < 0 || index >= cnt) { - throw new IllegalArgumentException("Specified CF index " + index - + " is outside the allowable range (0.." + (cnt - 1) + ")"); - } - } - -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFSimpleShape.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFSimpleShape.java deleted file mode 100644 index 1f8216765..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFSimpleShape.java +++ /dev/null @@ -1,872 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; - -import org.apache.poi.hssf.util.HSSFColor; -import org.apache.poi.ss.usermodel.SimpleShape; -import org.apache.poi.ss.usermodel.VerticalAlignment; -import org.apache.poi.util.Internal; -import org.apache.poi.util.Units; -import org.openxmlformats.schemas.drawingml.x2006.main.*; -import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTShape; -import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTShapeNonVisual; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRElt; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRPrElt; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STUnderlineValues; - -/** - * Represents a shape with a predefined geometry in a SpreadsheetML drawing. - * Possible shape types are defined in {@link org.apache.poi.ss.usermodel.ShapeTypes} - */ -public class XSSFSimpleShape extends XSSFShape implements Iterable, SimpleShape { - /** - * List of the paragraphs that make up the text in this shape - */ - private final List _paragraphs; - /** - * A default instance of CTShape used for creating new shapes. - */ - private static CTShape prototype = null; - - /** - * Xml bean that stores properties of this shape - */ - private CTShape ctShape; - - protected XSSFSimpleShape(XSSFDrawing drawing, CTShape ctShape) { - this.drawing = drawing; - this.ctShape = ctShape; - - _paragraphs = new ArrayList(); - - // initialize any existing paragraphs - this will be the default body paragraph in a new shape, - // or existing paragraphs that have been loaded from the file - CTTextBody body = ctShape.getTxBody(); - if(body != null) { - for(int i = 0; i < body.sizeOfPArray(); i++) { - _paragraphs.add(new XSSFTextParagraph(body.getPArray(i), ctShape)); - } - } - } - - /** - * Prototype with the default structure of a new auto-shape. - */ - protected static CTShape prototype() { - if(prototype == null) { - CTShape shape = CTShape.Factory.newInstance(); - - CTShapeNonVisual nv = shape.addNewNvSpPr(); - CTNonVisualDrawingProps nvp = nv.addNewCNvPr(); - nvp.setId(1); - nvp.setName("Shape 1"); - nv.addNewCNvSpPr(); - - CTShapeProperties sp = shape.addNewSpPr(); - CTTransform2D t2d = sp.addNewXfrm(); - CTPositiveSize2D p1 = t2d.addNewExt(); - p1.setCx(0); - p1.setCy(0); - CTPoint2D p2 = t2d.addNewOff(); - p2.setX(0); - p2.setY(0); - - CTPresetGeometry2D geom = sp.addNewPrstGeom(); - geom.setPrst(STShapeType.RECT); - geom.addNewAvLst(); - - CTTextBody body = shape.addNewTxBody(); - CTTextBodyProperties bodypr = body.addNewBodyPr(); - bodypr.setAnchor(STTextAnchoringType.T); - bodypr.setRtlCol(false); - CTTextParagraph p = body.addNewP(); - p.addNewPPr().setAlgn(STTextAlignType.L); - CTTextCharacterProperties endPr = p.addNewEndParaRPr(); - endPr.setLang("en-US"); - endPr.setSz(1100); - CTSolidColorFillProperties scfpr = endPr.addNewSolidFill(); - scfpr.addNewSrgbClr().setVal(new byte[] { 0, 0, 0 }); - - body.addNewLstStyle(); - - prototype = shape; - } - return prototype; - } - - @Internal - public CTShape getCTShape(){ - return ctShape; - } - - - public Iterator iterator(){ - return _paragraphs.iterator(); - } - - /** - * Returns the text from all paragraphs in the shape. Paragraphs are separated by new lines. - * - * @return text contained within this shape or empty string - */ - public String getText() { - final int MAX_LEVELS = 9; - StringBuilder out = new StringBuilder(); - List levelCount = new ArrayList(MAX_LEVELS); // maximum 9 levels - XSSFTextParagraph p = null; - - // initialise the levelCount array - this maintains a record of the numbering to be used at each level - for (int k = 0; k < MAX_LEVELS; k++){ - levelCount.add(0); - } - - for(int i = 0; i < _paragraphs.size(); i++) { - if (out.length() > 0) out.append('\n'); - p = _paragraphs.get(i); - - if(p.isBullet() && p.getText().length() > 0){ - - int level = Math.min(p.getLevel(), MAX_LEVELS - 1); - - if(p.isBulletAutoNumber()){ - i = processAutoNumGroup(i, level, levelCount, out); - } else { - // indent appropriately for the level - for(int j = 0; j < level; j++){ - out.append('\t'); - } - String character = p.getBulletCharacter(); - out.append(character.length() > 0 ? character + " " : "- "); - out.append(p.getText()); - } - } else { - out.append(p.getText()); - - // this paragraph is not a bullet, so reset the count array - for (int k = 0; k < MAX_LEVELS; k++){ - levelCount.set(k, 0); - } - } - } - - return out.toString(); - } - - /** - * - */ - private int processAutoNumGroup(int index, int level, List levelCount, StringBuilder out){ - XSSFTextParagraph p = null; - XSSFTextParagraph nextp = null; - ListAutoNumber scheme, nextScheme; - int startAt, nextStartAt; - - p = _paragraphs.get(index); - - // The rules for generating the auto numbers are as follows. If the following paragraph is also - // an auto-number, has the same type/scheme (and startAt if defined on this paragraph) then they are - // considered part of the same group. An empty bullet paragraph is counted as part of the same - // group but does not increment the count for the group. A change of type, startAt or the paragraph - // not being a bullet resets the count for that level to 1. - - // first auto-number paragraph so initialise to 1 or the bullets startAt if present - startAt = p.getBulletAutoNumberStart(); - scheme = p.getBulletAutoNumberScheme(); - if(levelCount.get(level) == 0) { - levelCount.set(level, startAt == 0 ? 1 : startAt); - } - // indent appropriately for the level - for(int j = 0; j < level; j++){ - out.append('\t'); - } - if (p.getText().length() > 0){ - out.append(getBulletPrefix(scheme, levelCount.get(level))); - out.append(p.getText()); - } - while(true) { - nextp = (index + 1) == _paragraphs.size() ? null : _paragraphs.get(index + 1); - if(nextp == null) break; // out of paragraphs - if(!(nextp.isBullet() && p.isBulletAutoNumber())) break; // not an auto-number bullet - if(nextp.getLevel() > level) { - // recurse into the new level group - if (out.length() > 0) out.append('\n'); - index = processAutoNumGroup(index + 1, nextp.getLevel(), levelCount, out); - continue; // restart the loop given the new index - } else if(nextp.getLevel() < level) { - break; // changed level - } - nextScheme = nextp.getBulletAutoNumberScheme(); - nextStartAt = nextp.getBulletAutoNumberStart(); - - if(nextScheme == scheme && nextStartAt == startAt) { - // bullet is valid, so increment i - ++index; - if (out.length() > 0) out.append('\n'); - // indent for the level - for(int j = 0; j < level; j++){ - out.append('\t'); - } - // check for empty text - only output a bullet if there is text, but it is still part of the group - if(nextp.getText().length() > 0) { - // increment the count for this level - levelCount.set(level, levelCount.get(level) + 1); - out.append(getBulletPrefix(nextScheme, levelCount.get(level))); - out.append(nextp.getText()); - } - } else { - // something doesn't match so stop - break; - } - } - // end of the group so reset the count for this level - levelCount.set(level, 0); - - return index; - } - /** - * Returns a string containing an appropriate prefix for an auto-numbering bullet - * @param scheme the auto-numbering scheme used by the bullet - * @param value the value of the bullet - * @return appropriate prefix for an auto-numbering bullet - */ - private String getBulletPrefix(ListAutoNumber scheme, int value){ - StringBuilder out = new StringBuilder(); - - switch(scheme) { - case ALPHA_LC_PARENT_BOTH: - case ALPHA_LC_PARENT_R: - if(scheme == ListAutoNumber.ALPHA_LC_PARENT_BOTH) out.append('('); - out.append(valueToAlpha(value).toLowerCase(Locale.ROOT)); - out.append(')'); - break; - case ALPHA_UC_PARENT_BOTH: - case ALPHA_UC_PARENT_R: - if(scheme == ListAutoNumber.ALPHA_UC_PARENT_BOTH) out.append('('); - out.append(valueToAlpha(value)); - out.append(')'); - break; - case ALPHA_LC_PERIOD: - out.append(valueToAlpha(value).toLowerCase(Locale.ROOT)); - out.append('.'); - break; - case ALPHA_UC_PERIOD: - out.append(valueToAlpha(value)); - out.append('.'); - break; - case ARABIC_PARENT_BOTH: - case ARABIC_PARENT_R: - if(scheme == ListAutoNumber.ARABIC_PARENT_BOTH) out.append('('); - out.append(value); - out.append(')'); - break; - case ARABIC_PERIOD: - out.append(value); - out.append('.'); - break; - case ARABIC_PLAIN: - out.append(value); - break; - case ROMAN_LC_PARENT_BOTH: - case ROMAN_LC_PARENT_R: - if(scheme == ListAutoNumber.ROMAN_LC_PARENT_BOTH) out.append('('); - out.append(valueToRoman(value).toLowerCase(Locale.ROOT)); - out.append(')'); - break; - case ROMAN_UC_PARENT_BOTH: - case ROMAN_UC_PARENT_R: - if(scheme == ListAutoNumber.ROMAN_UC_PARENT_BOTH) out.append('('); - out.append(valueToRoman(value)); - out.append(')'); - break; - case ROMAN_LC_PERIOD: - out.append(valueToRoman(value).toLowerCase(Locale.ROOT)); - out.append('.'); - break; - case ROMAN_UC_PERIOD: - out.append(valueToRoman(value)); - out.append('.'); - break; - default: - out.append('\u2022'); // can't set the font to wingdings so use the default bullet character - break; - } - out.append(" "); - return out.toString(); - } - - /** - * Convert an integer to its alpha equivalent e.g. 1 = A, 2 = B, 27 = AA etc - */ - private String valueToAlpha(int value) { - String alpha = ""; - int modulo; - while (value > 0) { - modulo = (value - 1) % 26; - alpha = (char)(65 + modulo) + alpha; - value = (value - modulo) / 26; - } - return alpha; - } - - private static String[] _romanChars = new String[] { "M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I" }; - private static int[] _romanAlphaValues = new int[] { 1000,900,500,400,100,90,50,40,10,9,5,4,1 }; - - /** - * Convert an integer to its roman equivalent e.g. 1 = I, 9 = IX etc - */ - private String valueToRoman(int value) { - StringBuilder out = new StringBuilder(); - for(int i = 0; value > 0 && i < _romanChars.length; i++) { - while(_romanAlphaValues[i] <= value) { - out.append(_romanChars[i]); - value -= _romanAlphaValues[i]; - } - } - return out.toString(); - } - - /** - * Clear all text from this shape - */ - public void clearText(){ - _paragraphs.clear(); - CTTextBody txBody = ctShape.getTxBody(); - txBody.setPArray(null); // remove any existing paragraphs - } - - /** - * Set a single paragraph of text on the shape. Note this will replace all existing paragraphs created on the shape. - * @param text string representing the paragraph text - */ - public void setText(String text){ - clearText(); - - addNewTextParagraph().addNewTextRun().setText(text); - } - - /** - * Set a single paragraph of text on the shape. Note this will replace all existing paragraphs created on the shape. - * @param str rich text string representing the paragraph text - */ - public void setText(XSSFRichTextString str){ - - XSSFWorkbook wb = (XSSFWorkbook)getDrawing().getParent().getParent(); - str.setStylesTableReference(wb.getStylesSource()); - - CTTextParagraph p = CTTextParagraph.Factory.newInstance(); - if(str.numFormattingRuns() == 0){ - CTRegularTextRun r = p.addNewR(); - CTTextCharacterProperties rPr = r.addNewRPr(); - rPr.setLang("en-US"); - rPr.setSz(1100); - r.setT(str.getString()); - - } else { - for (int i = 0; i < str.getCTRst().sizeOfRArray(); i++) { - CTRElt lt = str.getCTRst().getRArray(i); - CTRPrElt ltPr = lt.getRPr(); - if(ltPr == null) ltPr = lt.addNewRPr(); - - CTRegularTextRun r = p.addNewR(); - CTTextCharacterProperties rPr = r.addNewRPr(); - rPr.setLang("en-US"); - - applyAttributes(ltPr, rPr); - - r.setT(lt.getT()); - } - } - - clearText(); - ctShape.getTxBody().setPArray(new CTTextParagraph[]{p}); - _paragraphs.add(new XSSFTextParagraph(ctShape.getTxBody().getPArray(0), ctShape)); - } - - /** - * Returns a collection of the XSSFTextParagraphs that are attached to this shape - * - * @return text paragraphs in this shape - */ - public List getTextParagraphs() { - return _paragraphs; - } - - /** - * Add a new paragraph run to this shape - * - * @return created paragraph run - */ - public XSSFTextParagraph addNewTextParagraph() { - CTTextBody txBody = ctShape.getTxBody(); - CTTextParagraph p = txBody.addNewP(); - XSSFTextParagraph paragraph = new XSSFTextParagraph(p, ctShape); - _paragraphs.add(paragraph); - return paragraph; - } - - /** - * Add a new paragraph run to this shape, set to the provided string - * - * @return created paragraph run - */ - public XSSFTextParagraph addNewTextParagraph(String text) { - XSSFTextParagraph paragraph = addNewTextParagraph(); - paragraph.addNewTextRun().setText(text); - return paragraph; - } - - /** - * Add a new paragraph run to this shape, set to the provided rich text string - * - * @return created paragraph run - */ - public XSSFTextParagraph addNewTextParagraph(XSSFRichTextString str) { - CTTextBody txBody = ctShape.getTxBody(); - CTTextParagraph p = txBody.addNewP(); - - if(str.numFormattingRuns() == 0){ - CTRegularTextRun r = p.addNewR(); - CTTextCharacterProperties rPr = r.addNewRPr(); - rPr.setLang("en-US"); - rPr.setSz(1100); - r.setT(str.getString()); - - } else { - for (int i = 0; i < str.getCTRst().sizeOfRArray(); i++) { - CTRElt lt = str.getCTRst().getRArray(i); - CTRPrElt ltPr = lt.getRPr(); - if(ltPr == null) ltPr = lt.addNewRPr(); - - CTRegularTextRun r = p.addNewR(); - CTTextCharacterProperties rPr = r.addNewRPr(); - rPr.setLang("en-US"); - - applyAttributes(ltPr, rPr); - - r.setT(lt.getT()); - } - } - - // Note: the XSSFTextParagraph constructor will create its required XSSFTextRuns from the provided CTTextParagraph - XSSFTextParagraph paragraph = new XSSFTextParagraph(p, ctShape); - _paragraphs.add(paragraph); - - return paragraph; - } - - /** - * Sets the type of horizontal overflow for the text. - * - * @param overflow - the type of horizontal overflow. - * A null values unsets this property. - */ - public void setTextHorizontalOverflow(TextHorizontalOverflow overflow){ - CTTextBodyProperties bodyPr = ctShape.getTxBody().getBodyPr(); - if (bodyPr != null) { - if(overflow == null) { - if(bodyPr.isSetHorzOverflow()) bodyPr.unsetHorzOverflow(); - } else { - bodyPr.setHorzOverflow(STTextHorzOverflowType.Enum.forInt(overflow.ordinal() + 1)); - } - } - } - - /** - * Returns the type of horizontal overflow for the text. - * - * @return the type of horizontal overflow - */ - public TextHorizontalOverflow getTextHorizontalOverflow(){ - CTTextBodyProperties bodyPr = ctShape.getTxBody().getBodyPr(); - if(bodyPr != null) { - if(bodyPr.isSetHorzOverflow()){ - return TextHorizontalOverflow.values()[bodyPr.getHorzOverflow().intValue() - 1]; - } - } - return TextHorizontalOverflow.OVERFLOW; - } - - /** - * Sets the type of vertical overflow for the text. - * - * @param overflow - the type of vertical overflow. - * A null values unsets this property. - */ - public void setTextVerticalOverflow(TextVerticalOverflow overflow){ - CTTextBodyProperties bodyPr = ctShape.getTxBody().getBodyPr(); - if (bodyPr != null) { - if(overflow == null) { - if(bodyPr.isSetVertOverflow()) bodyPr.unsetVertOverflow(); - } else { - bodyPr.setVertOverflow(STTextVertOverflowType.Enum.forInt(overflow.ordinal() + 1)); - } - } - } - - /** - * Returns the type of vertical overflow for the text. - * - * @return the type of vertical overflow - */ - public TextVerticalOverflow getTextVerticalOverflow(){ - CTTextBodyProperties bodyPr = ctShape.getTxBody().getBodyPr(); - if(bodyPr != null) { - if(bodyPr.isSetVertOverflow()){ - return TextVerticalOverflow.values()[bodyPr.getVertOverflow().intValue() - 1]; - } - } - return TextVerticalOverflow.OVERFLOW; - } - - /** - * Sets the type of vertical alignment for the text within the shape. - * - * @param anchor - the type of alignment. - * A null values unsets this property. - */ - public void setVerticalAlignment(VerticalAlignment anchor){ - CTTextBodyProperties bodyPr = ctShape.getTxBody().getBodyPr(); - if (bodyPr != null) { - if(anchor == null) { - if(bodyPr.isSetAnchor()) bodyPr.unsetAnchor(); - } else { - bodyPr.setAnchor(STTextAnchoringType.Enum.forInt(anchor.ordinal() + 1)); - } - } - } - - /** - * Returns the type of vertical alignment for the text within the shape. - * - * @return the type of vertical alignment - */ - public VerticalAlignment getVerticalAlignment(){ - CTTextBodyProperties bodyPr = ctShape.getTxBody().getBodyPr(); - if(bodyPr != null) { - if(bodyPr.isSetAnchor()){ - return VerticalAlignment.values()[bodyPr.getAnchor().intValue() - 1]; - } - } - return VerticalAlignment.TOP; - } - - /** - * Sets the vertical orientation of the text - * - * @param orientation vertical orientation of the text - * A null values unsets this property. - */ - public void setTextDirection(TextDirection orientation){ - CTTextBodyProperties bodyPr = ctShape.getTxBody().getBodyPr(); - if (bodyPr != null) { - if(orientation == null) { - if(bodyPr.isSetVert()) bodyPr.unsetVert(); - } else { - bodyPr.setVert(STTextVerticalType.Enum.forInt(orientation.ordinal() + 1)); - } - } - } - - /** - * Gets the vertical orientation of the text - * - * @return vertical orientation of the text - */ - public TextDirection getTextDirection(){ - CTTextBodyProperties bodyPr = ctShape.getTxBody().getBodyPr(); - if (bodyPr != null) { - STTextVerticalType.Enum val = bodyPr.getVert(); - if(val != null){ - return TextDirection.values()[val.intValue() - 1]; - } - } - return TextDirection.HORIZONTAL; - } - - - /** - * Returns the distance (in points) between the bottom of the text frame - * and the bottom of the inscribed rectangle of the shape that contains the text. - * - * @return the bottom inset in points - */ - public double getBottomInset(){ - CTTextBodyProperties bodyPr = ctShape.getTxBody().getBodyPr(); - if (bodyPr != null) { - if(bodyPr.isSetBIns()){ - return Units.toPoints(bodyPr.getBIns()); - } - } - // If this attribute is omitted, then a value of 0.05 inches is implied - return 3.6; - } - - /** - * Returns the distance (in points) between the left edge of the text frame - * and the left edge of the inscribed rectangle of the shape that contains - * the text. - * - * @return the left inset in points - */ - public double getLeftInset(){ - CTTextBodyProperties bodyPr = ctShape.getTxBody().getBodyPr(); - if (bodyPr != null) { - if(bodyPr.isSetLIns()){ - return Units.toPoints(bodyPr.getLIns()); - } - } - // If this attribute is omitted, then a value of 0.05 inches is implied - return 3.6; - } - - /** - * Returns the distance (in points) between the right edge of the - * text frame and the right edge of the inscribed rectangle of the shape - * that contains the text. - * - * @return the right inset in points - */ - public double getRightInset(){ - CTTextBodyProperties bodyPr = ctShape.getTxBody().getBodyPr(); - if (bodyPr != null) { - if(bodyPr.isSetRIns()){ - return Units.toPoints(bodyPr.getRIns()); - } - } - // If this attribute is omitted, then a value of 0.05 inches is implied - return 3.6; - } - - /** - * Returns the distance (in points) between the top of the text frame - * and the top of the inscribed rectangle of the shape that contains the text. - * - * @return the top inset in points - */ - public double getTopInset(){ - CTTextBodyProperties bodyPr = ctShape.getTxBody().getBodyPr(); - if (bodyPr != null) { - if(bodyPr.isSetTIns()){ - return Units.toPoints(bodyPr.getTIns()); - } - } - // If this attribute is omitted, then a value of 0.05 inches is implied - return 3.6; - } - - /** - * Sets the bottom inset. - * @see #getBottomInset() - * - * @param margin the bottom margin - */ - public void setBottomInset(double margin){ - CTTextBodyProperties bodyPr = ctShape.getTxBody().getBodyPr(); - if (bodyPr != null) { - if(margin == -1) { - if(bodyPr.isSetBIns()) bodyPr.unsetBIns(); - } else bodyPr.setBIns(Units.toEMU(margin)); - } - } - - /** - * Sets the left inset. - * @see #getLeftInset() - * - * @param margin the left margin - */ - public void setLeftInset(double margin){ - CTTextBodyProperties bodyPr = ctShape.getTxBody().getBodyPr(); - if (bodyPr != null) { - if(margin == -1) { - if(bodyPr.isSetLIns()) bodyPr.unsetLIns(); - } else bodyPr.setLIns(Units.toEMU(margin)); - } - } - - /** - * Sets the right inset. - * @see #getRightInset() - * - * @param margin the right margin - */ - public void setRightInset(double margin){ - CTTextBodyProperties bodyPr = ctShape.getTxBody().getBodyPr(); - if (bodyPr != null) { - if(margin == -1) { - if(bodyPr.isSetRIns()) bodyPr.unsetRIns(); - } else bodyPr.setRIns(Units.toEMU(margin)); - } - } - - /** - * Sets the top inset. - * @see #getTopInset() - * - * @param margin the top margin - */ - public void setTopInset(double margin){ - CTTextBodyProperties bodyPr = ctShape.getTxBody().getBodyPr(); - if (bodyPr != null) { - if(margin == -1) { - if(bodyPr.isSetTIns()) bodyPr.unsetTIns(); - } else bodyPr.setTIns(Units.toEMU(margin)); - } - } - - - /** - * @return whether to wrap words within the bounding rectangle - */ - public boolean getWordWrap(){ - CTTextBodyProperties bodyPr = ctShape.getTxBody().getBodyPr(); - if (bodyPr != null) { - if(bodyPr.isSetWrap()){ - return bodyPr.getWrap() == STTextWrappingType.SQUARE; - } - } - return true; - } - - /** - * - * @param wrap whether to wrap words within the bounding rectangle - */ - public void setWordWrap(boolean wrap){ - CTTextBodyProperties bodyPr = ctShape.getTxBody().getBodyPr(); - if (bodyPr != null) { - bodyPr.setWrap(wrap ? STTextWrappingType.SQUARE : STTextWrappingType.NONE); - } - } - - /** - * - * Specifies that a shape should be auto-fit to fully contain the text described within it. - * Auto-fitting is when text within a shape is scaled in order to contain all the text inside - * - * @param value type of autofit - */ - public void setTextAutofit(TextAutofit value){ - CTTextBodyProperties bodyPr = ctShape.getTxBody().getBodyPr(); - if (bodyPr != null) { - if(bodyPr.isSetSpAutoFit()) bodyPr.unsetSpAutoFit(); - if(bodyPr.isSetNoAutofit()) bodyPr.unsetNoAutofit(); - if(bodyPr.isSetNormAutofit()) bodyPr.unsetNormAutofit(); - - switch(value){ - case NONE: bodyPr.addNewNoAutofit(); break; - case NORMAL: bodyPr.addNewNormAutofit(); break; - case SHAPE: bodyPr.addNewSpAutoFit(); break; - } - } - } - - /** - * - * @return type of autofit - */ - public TextAutofit getTextAutofit(){ - CTTextBodyProperties bodyPr = ctShape.getTxBody().getBodyPr(); - if (bodyPr != null) { - if(bodyPr.isSetNoAutofit()) return TextAutofit.NONE; - else if (bodyPr.isSetNormAutofit()) return TextAutofit.NORMAL; - else if (bodyPr.isSetSpAutoFit()) return TextAutofit.SHAPE; - } - return TextAutofit.NORMAL; - } - - /** - * Gets the shape type, one of the constants defined in {@link org.apache.poi.ss.usermodel.ShapeTypes}. - * - * @return the shape type - * @see org.apache.poi.ss.usermodel.ShapeTypes - */ - public int getShapeType() { - return ctShape.getSpPr().getPrstGeom().getPrst().intValue(); - } - - /** - * Sets the shape types. - * - * @param type the shape type, one of the constants defined in {@link org.apache.poi.ss.usermodel.ShapeTypes}. - * @see org.apache.poi.ss.usermodel.ShapeTypes - */ - public void setShapeType(int type) { - ctShape.getSpPr().getPrstGeom().setPrst(STShapeType.Enum.forInt(type)); - } - - protected CTShapeProperties getShapeProperties(){ - return ctShape.getSpPr(); - } - - /** - * org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRPrElt to - * org.openxmlformats.schemas.drawingml.x2006.main.CTFont adapter - */ - private static void applyAttributes(CTRPrElt pr, CTTextCharacterProperties rPr){ - - if(pr.sizeOfBArray() > 0) rPr.setB(pr.getBArray(0).getVal()); - if(pr.sizeOfUArray() > 0) { - STUnderlineValues.Enum u1 = pr.getUArray(0).getVal(); - if(u1 == STUnderlineValues.SINGLE) rPr.setU(STTextUnderlineType.SNG); - else if(u1 == STUnderlineValues.DOUBLE) rPr.setU(STTextUnderlineType.DBL); - else if(u1 == STUnderlineValues.NONE) rPr.setU(STTextUnderlineType.NONE); - } - if(pr.sizeOfIArray() > 0) rPr.setI(pr.getIArray(0).getVal()); - - if(pr.sizeOfRFontArray() > 0) { - CTTextFont rFont = rPr.isSetLatin() ? rPr.getLatin() : rPr.addNewLatin(); - rFont.setTypeface(pr.getRFontArray(0).getVal()); - } - - if(pr.sizeOfSzArray() > 0) { - int sz = (int)(pr.getSzArray(0).getVal()*100); - rPr.setSz(sz); - } - - if(pr.sizeOfColorArray() > 0) { - CTSolidColorFillProperties fill = rPr.isSetSolidFill() ? rPr.getSolidFill() : rPr.addNewSolidFill(); - org.openxmlformats.schemas.spreadsheetml.x2006.main.CTColor xlsColor = pr.getColorArray(0); - if(xlsColor.isSetRgb()) { - CTSRgbColor clr = fill.isSetSrgbClr() ? fill.getSrgbClr() : fill.addNewSrgbClr(); - clr.setVal(xlsColor.getRgb()); - } - else if(xlsColor.isSetIndexed()) { - HSSFColor indexed = HSSFColor.getIndexHash().get((int) xlsColor.getIndexed()); - if (indexed != null) { - byte[] rgb = new byte[3]; - rgb[0] = (byte) indexed.getTriplet()[0]; - rgb[1] = (byte) indexed.getTriplet()[1]; - rgb[2] = (byte) indexed.getTriplet()[2]; - CTSRgbColor clr = fill.isSetSrgbClr() ? fill.getSrgbClr() : fill.addNewSrgbClr(); - clr.setVal(rgb); - } - } - } - } - - @Override - public String getShapeName() { - return ctShape.getNvSpPr().getCNvPr().getName(); - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFTable.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFTable.java deleted file mode 100644 index 5bdd950de..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFTable.java +++ /dev/null @@ -1,447 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import static org.apache.poi.POIXMLTypeLoader.DEFAULT_XML_OPTIONS; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.ss.usermodel.Table; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.util.Internal; -import org.apache.poi.util.StringUtil; -import org.apache.poi.xssf.usermodel.helpers.XSSFXmlColumnPr; -import org.apache.xmlbeans.XmlException; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTable; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTableColumn; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.TableDocument; - -/** - * - * This class implements the Table Part (Open Office XML Part 4: - * chapter 3.5.1) - * - * This implementation works under the assumption that a table contains mappings to a subtree of an XML. - * The root element of this subtree an occur multiple times (one for each row of the table). The child nodes - * of the root element can be only attributes or element with maxOccurs=1 property set - * - * - * @author Roberto Manicardi - */ -public class XSSFTable extends POIXMLDocumentPart implements Table { - - private CTTable ctTable; - private transient List xmlColumnPr; - private transient CTTableColumn[] ctColumns; - private transient HashMap columnMap; - private transient CellReference startCellReference; - private transient CellReference endCellReference; - private transient String commonXPath; - - - public XSSFTable() { - super(); - ctTable = CTTable.Factory.newInstance(); - } - - /** - * @since POI 3.14-Beta1 - */ - public XSSFTable(PackagePart part) throws IOException { - super(part); - readFrom(part.getInputStream()); - } - - public void readFrom(InputStream is) throws IOException { - try { - TableDocument doc = TableDocument.Factory.parse(is, DEFAULT_XML_OPTIONS); - ctTable = doc.getTable(); - } catch (XmlException e) { - throw new IOException(e.getLocalizedMessage()); - } - } - - public XSSFSheet getXSSFSheet(){ - return (XSSFSheet) getParent(); - } - - public void writeTo(OutputStream out) throws IOException { - updateHeaders(); - - TableDocument doc = TableDocument.Factory.newInstance(); - doc.setTable(ctTable); - doc.save(out, DEFAULT_XML_OPTIONS); - } - - @Override - protected void commit() throws IOException { - PackagePart part = getPackagePart(); - OutputStream out = part.getOutputStream(); - writeTo(out); - out.close(); - } - - /** - * get the underlying CTTable XML bean - */ - @Internal(since="POI 3.15 beta 3") - public CTTable getCTTable() { - return ctTable; - } - - /** - * Checks if this Table element contains even a single mapping to the map identified by id - * @param id the XSSFMap ID - * @return true if the Table element contain mappings - */ - public boolean mapsTo(long id){ - List pointers = getXmlColumnPrs(); - - for (XSSFXmlColumnPr pointer: pointers) { - if (pointer.getMapId()==id) { - return true; - } - } - - return false; - } - - /** - * caches table columns for performance. - * Updated via updateHeaders - * @since 3.15 beta 2 - */ - private CTTableColumn[] getTableColumns() { - if (ctColumns == null) { - ctColumns = ctTable.getTableColumns().getTableColumnArray(); - } - return ctColumns; - } - - /** - * - * Calculates the xpath of the root element for the table. This will be the common part - * of all the mapping's xpaths - * Note: this function caches the result for performance. To flush the cache {@link #updateHeaders()} must be called. - * - * @return the xpath of the table's root element - */ - public String getCommonXpath() { - if (commonXPath == null) { - String[] commonTokens = {}; - for (CTTableColumn column : getTableColumns()) { - if (column.getXmlColumnPr()!=null) { - String xpath = column.getXmlColumnPr().getXpath(); - String[] tokens = xpath.split("/"); - if (commonTokens.length==0) { - commonTokens = tokens; - - } else { - final int maxLength = Math.min(commonTokens.length, tokens.length); - - for (int i =0; i subCommonTokens = Arrays.asList(commonTokens).subList(0, i); - - String[] container = {}; - - commonTokens = subCommonTokens.toArray(container); - break; - } - } - } - } - } - - commonTokens[0] = ""; - commonXPath = StringUtil.join(commonTokens, "/"); - } - - return commonXPath; - } - - - /** - * Note this list is static - once read, it does not notice later changes to the underlying column structures - * To clear the cache, call {@link #updateHeaders} - * @return List of XSSFXmlColumnPr - */ - public List getXmlColumnPrs() { - - if (xmlColumnPr==null) { - xmlColumnPr = new ArrayList(); - for (CTTableColumn column: getTableColumns()) { - if (column.getXmlColumnPr()!=null) { - XSSFXmlColumnPr columnPr = new XSSFXmlColumnPr(this,column,column.getXmlColumnPr()); - xmlColumnPr.add(columnPr); - } - } - } - return xmlColumnPr; - } - - /** - * @return the name of the Table, if set - */ - public String getName() { - return ctTable.getName(); - } - - /** - * Changes the name of the Table - */ - public void setName(String name) { - if (name == null) { - ctTable.unsetName(); - return; - } - ctTable.setName(name); - } - - /** - * @return the display name of the Table, if set - */ - public String getDisplayName() { - return ctTable.getDisplayName(); - } - - /** - * Changes the display name of the Table - */ - public void setDisplayName(String name) { - ctTable.setDisplayName(name); - } - - /** - * @return the number of mapped table columns (see Open Office XML Part 4: chapter 3.5.1.4) - */ - public long getNumberOfMappedColumns() { - return ctTable.getTableColumns().getCount(); - } - - /** - * @return the number of mapped table columns (see Open Office XML Part 4: chapter 3.5.1.4) - * @deprecated 3.15 beta 2. Use {@link #getNumberOfMappedColumns}. - */ - public long getNumerOfMappedColumns() { - return getNumberOfMappedColumns(); - } - - - - /** - * @return The reference for the cell in the top-left part of the table - * (see Open Office XML Part 4: chapter 3.5.1.2, attribute ref) - * - * Does not track updates to underlying changes to CTTable - * To synchronize with changes to the underlying CTTable, - * call {@link #updateReferences()}. - */ - public CellReference getStartCellReference() { - if (startCellReference==null) { - setCellReferences(); - } - return startCellReference; - } - - /** - * @return The reference for the cell in the bottom-right part of the table - * (see Open Office XML Part 4: chapter 3.5.1.2, attribute ref) - * - * Does not track updates to underlying changes to CTTable - * To synchronize with changes to the underlying CTTable, - * call {@link #updateReferences()}. - */ - public CellReference getEndCellReference() { - if (endCellReference==null) { - setCellReferences(); - } - return endCellReference; - } - - /** - * @since POI 3.15 beta 3 - */ - private void setCellReferences() { - String ref = ctTable.getRef(); - if (ref != null) { - String[] boundaries = ref.split(":", 2); - String from = boundaries[0]; - String to = boundaries[1]; - startCellReference = new CellReference(from); - endCellReference = new CellReference(to); - } - } - - - /** - * Clears the cached values set by {@link #getStartCellReference()} - * and {@link #getEndCellReference()}. - * The next call to {@link #getStartCellReference()} and - * {@link #getEndCellReference()} will synchronize the - * cell references with the underlying CTTable. - * Thus, {@link #updateReferences()} is inexpensive. - * - * @since POI 3.15 beta 3 - */ - public void updateReferences() { - startCellReference = null; - endCellReference = null; - } - - - /** - * @return the total number of rows in the selection. (Note: in this version autofiltering is ignored) - * Returns 0 if the start or end cell references are not set. - * - * Does not track updates to underlying changes to CTTable - * To synchronize with changes to the underlying CTTable, - * call {@link #updateReferences()}. - */ - public int getRowCount() { - CellReference from = getStartCellReference(); - CellReference to = getEndCellReference(); - - int rowCount = 0; - if (from!=null && to!=null) { - rowCount = to.getRow() - from.getRow() + 1; - } - return rowCount; - } - - /** - * Synchronize table headers with cell values in the parent sheet. - * Headers must be in sync, otherwise Excel will display a - * "Found unreadable content" message on startup. - * - * If calling both {@link #updateReferences()} and - * {@link #updateHeaders()}, {@link #updateReferences()} - * should be called first. - */ - public void updateHeaders() { - XSSFSheet sheet = (XSSFSheet)getParent(); - CellReference ref = getStartCellReference(); - if(ref == null) return; - - int headerRow = ref.getRow(); - int firstHeaderColumn = ref.getCol(); - XSSFRow row = sheet.getRow(headerRow); - - if (row != null && row.getCTRow().validate()) { - int cellnum = firstHeaderColumn; - for (CTTableColumn col : getCTTable().getTableColumns().getTableColumnArray()) { - XSSFCell cell = row.getCell(cellnum); - if (cell != null) { - col.setName(cell.getStringCellValue()); - } - cellnum++; - } - ctColumns = null; - columnMap = null; - xmlColumnPr = null; - commonXPath = null; - } - } - - private static String caseInsensitive(String s) { - return s.toUpperCase(Locale.ROOT); - } - - /** - * Gets the relative column index of a column in this table having the header name column. - * The column index is relative to the left-most column in the table, 0-indexed. - * Returns -1 if column is not a header name in table. - * - * Column Header names are case-insensitive - * - * Note: this function caches column names for performance. To flush the cache (because columns - * have been moved or column headers have been changed), {@link #updateHeaders()} must be called. - * - * @since 3.15 beta 2 - */ - public int findColumnIndex(String columnHeader) { - if (columnHeader == null) return -1; - if (columnMap == null) { - // FIXME: replace with org.apache.commons.collections.map.CaseInsensitiveMap - final int count = getTableColumns().length; - columnMap = new HashMap(count * 3 / 2); - - int i = 0; - for (CTTableColumn column : getTableColumns()) { - String columnName = column.getName(); - columnMap.put(caseInsensitive(columnName), i); - i++; - } - } - // Table column names with special characters need a single quote escape - // but the escape is not present in the column definition - Integer idx = columnMap.get(caseInsensitive(columnHeader.replace("'", ""))); - return idx == null ? -1 : idx.intValue(); - } - - /** - * @since 3.15 beta 2 - */ - public String getSheetName() { - return getXSSFSheet().getSheetName(); - } - - /** - * @since 3.15 beta 2 - */ - public boolean isHasTotalsRow() { - return ctTable.getTotalsRowShown(); - } - - /** - * @since 3.15 beta 2 - */ - public int getStartColIndex() { - return getStartCellReference().getCol(); - } - - /** - * @since 3.15 beta 2 - */ - public int getStartRowIndex() { - return getStartCellReference().getRow(); - } - - /** - * @since 3.15 beta 2 - */ - public int getEndColIndex() { - return getEndCellReference().getCol(); - } - - /** - * @since 3.15 beta 2 - */ - public int getEndRowIndex() { - return getEndCellReference().getRow(); - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFTextBox.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFTextBox.java deleted file mode 100644 index 74c26b930..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFTextBox.java +++ /dev/null @@ -1,32 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTShape; - -/** - * Represents a text box in a SpreadsheetML drawing. - * - * @author Yegor Kozlov - */ -public final class XSSFTextBox extends XSSFSimpleShape { - - protected XSSFTextBox(XSSFDrawing drawing, CTShape ctShape) { - super(drawing, ctShape); - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFTextParagraph.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFTextParagraph.java deleted file mode 100644 index 6500c1603..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFTextParagraph.java +++ /dev/null @@ -1,871 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel; - - -import org.apache.poi.util.Internal; -import org.apache.poi.util.Units; -import org.apache.poi.xssf.usermodel.TextAlign; -import org.apache.poi.xssf.model.ParagraphPropertyFetcher; -import org.apache.xmlbeans.XmlObject; -import org.openxmlformats.schemas.drawingml.x2006.main.*; -import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTShape; - -import java.awt.Color; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -/** - * Represents a paragraph of text within the containing text body. - * The paragraph is the highest level text separation mechanism. - */ -public class XSSFTextParagraph implements Iterable{ - private final CTTextParagraph _p; - private final CTShape _shape; - private final List _runs; - - XSSFTextParagraph(CTTextParagraph p, CTShape ctShape){ - _p = p; - _shape = ctShape; - _runs = new ArrayList(); - - for(XmlObject ch : _p.selectPath("*")){ - if(ch instanceof CTRegularTextRun){ - CTRegularTextRun r = (CTRegularTextRun)ch; - _runs.add(new XSSFTextRun(r, this)); - } else if (ch instanceof CTTextLineBreak){ - CTTextLineBreak br = (CTTextLineBreak)ch; - CTRegularTextRun r = CTRegularTextRun.Factory.newInstance(); - r.setRPr(br.getRPr()); - r.setT("\n"); - _runs.add(new XSSFTextRun(r, this)); - } else if (ch instanceof CTTextField){ - CTTextField f = (CTTextField)ch; - CTRegularTextRun r = CTRegularTextRun.Factory.newInstance(); - r.setRPr(f.getRPr()); - r.setT(f.getT()); - _runs.add(new XSSFTextRun(r, this)); - } - } - } - - public String getText(){ - StringBuilder out = new StringBuilder(); - for (XSSFTextRun r : _runs) { - out.append(r.getText()); - } - return out.toString(); - } - - @Internal - public CTTextParagraph getXmlObject(){ - return _p; - } - - @Internal - public CTShape getParentShape(){ - return _shape; - } - - public List getTextRuns(){ - return _runs; - } - - public Iterator iterator(){ - return _runs.iterator(); - } - - /** - * Add a new run of text - * - * @return a new run of text - */ - public XSSFTextRun addNewTextRun(){ - CTRegularTextRun r = _p.addNewR(); - CTTextCharacterProperties rPr = r.addNewRPr(); - rPr.setLang("en-US"); - XSSFTextRun run = new XSSFTextRun(r, this); - _runs.add(run); - return run; - } - - /** - * Insert a line break - * - * @return text run representing this line break ('\n') - */ - public XSSFTextRun addLineBreak(){ - CTTextLineBreak br = _p.addNewBr(); - CTTextCharacterProperties brProps = br.addNewRPr(); - if(_runs.size() > 0){ - // by default line break has the font size of the last text run - CTTextCharacterProperties prevRun = _runs.get(_runs.size() - 1).getRPr(); - brProps.set(prevRun); - } - CTRegularTextRun r = CTRegularTextRun.Factory.newInstance(); - r.setRPr(brProps); - r.setT("\n"); - XSSFTextRun run = new XSSFLineBreak(r, this, brProps); - _runs.add(run); - return run; - } - - /** - * Returns the alignment that is applied to the paragraph. - * - * If this attribute is omitted, then a value of left is implied. - * @return alignment that is applied to the paragraph - */ - public TextAlign getTextAlign(){ - ParagraphPropertyFetcher fetcher = new ParagraphPropertyFetcher(getLevel()){ - public boolean fetch(CTTextParagraphProperties props){ - if(props.isSetAlgn()){ - TextAlign val = TextAlign.values()[props.getAlgn().intValue() - 1]; - setValue(val); - return true; - } - return false; - } - }; - fetchParagraphProperty(fetcher); - return fetcher.getValue() == null ? TextAlign.LEFT : fetcher.getValue(); - } - - /** - * Specifies the alignment that is to be applied to the paragraph. - * Possible values for this include left, right, centered, justified and distributed, - * see {@link org.apache.poi.xssf.usermodel.TextAlign}. - * - * @param align text align - */ - public void setTextAlign(TextAlign align){ - CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr(); - if(align == null) { - if(pr.isSetAlgn()) pr.unsetAlgn(); - } else { - pr.setAlgn(STTextAlignType.Enum.forInt(align.ordinal() + 1)); - } - } - - /** - * Returns where vertically on a line of text the actual words are positioned. This deals - * with vertical placement of the characters with respect to the baselines. - * - * If this attribute is omitted, then a value of baseline is implied. - * @return alignment that is applied to the paragraph - */ - public TextFontAlign getTextFontAlign(){ - ParagraphPropertyFetcher fetcher = new ParagraphPropertyFetcher(getLevel()){ - public boolean fetch(CTTextParagraphProperties props){ - if(props.isSetFontAlgn()){ - TextFontAlign val = TextFontAlign.values()[props.getFontAlgn().intValue() - 1]; - setValue(val); - return true; - } - return false; - } - }; - fetchParagraphProperty(fetcher); - return fetcher.getValue() == null ? TextFontAlign.BASELINE : fetcher.getValue(); - } - - /** - * Determines where vertically on a line of text the actual words are positioned. This deals - * with vertical placement of the characters with respect to the baselines. For instance - * having text anchored to the top baseline, anchored to the bottom baseline, centered in - * between, etc. - * - * @param align text font align - */ - public void setTextFontAlign(TextFontAlign align){ - CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr(); - if(align == null) { - if(pr.isSetFontAlgn()) pr.unsetFontAlgn(); - } else { - pr.setFontAlgn(STTextFontAlignType.Enum.forInt(align.ordinal() + 1)); - } - } - - /** - * @return the font to be used on bullet characters within a given paragraph - */ - public String getBulletFont(){ - ParagraphPropertyFetcher fetcher = new ParagraphPropertyFetcher(getLevel()){ - public boolean fetch(CTTextParagraphProperties props){ - if(props.isSetBuFont()){ - setValue(props.getBuFont().getTypeface()); - return true; - } - return false; - } - }; - fetchParagraphProperty(fetcher); - return fetcher.getValue(); - } - - public void setBulletFont(String typeface){ - CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr(); - CTTextFont font = pr.isSetBuFont() ? pr.getBuFont() : pr.addNewBuFont(); - font.setTypeface(typeface); - } - - /** - * @return the character to be used in place of the standard bullet point - */ - public String getBulletCharacter(){ - ParagraphPropertyFetcher fetcher = new ParagraphPropertyFetcher(getLevel()){ - public boolean fetch(CTTextParagraphProperties props){ - if(props.isSetBuChar()){ - setValue(props.getBuChar().getChar()); - return true; - } - return false; - } - }; - fetchParagraphProperty(fetcher); - return fetcher.getValue(); - } - - public void setBulletCharacter(String str){ - CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr(); - CTTextCharBullet c = pr.isSetBuChar() ? pr.getBuChar() : pr.addNewBuChar(); - c.setChar(str); - } - - /** - * - * @return the color of bullet characters within a given paragraph. - * A null value means to use the text font color. - */ - public Color getBulletFontColor(){ - ParagraphPropertyFetcher fetcher = new ParagraphPropertyFetcher(getLevel()){ - public boolean fetch(CTTextParagraphProperties props){ - if(props.isSetBuClr()){ - if(props.getBuClr().isSetSrgbClr()){ - CTSRgbColor clr = props.getBuClr().getSrgbClr(); - byte[] rgb = clr.getVal(); - setValue(new Color(0xFF & rgb[0], 0xFF & rgb[1], 0xFF & rgb[2])); - return true; - } - } - return false; - } - }; - fetchParagraphProperty(fetcher); - return fetcher.getValue(); - } - - /** - * Set the color to be used on bullet characters within a given paragraph. - * - * @param color the bullet color - */ - public void setBulletFontColor(Color color){ - CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr(); - CTColor c = pr.isSetBuClr() ? pr.getBuClr() : pr.addNewBuClr(); - CTSRgbColor clr = c.isSetSrgbClr() ? c.getSrgbClr() : c.addNewSrgbClr(); - clr.setVal(new byte[]{(byte) color.getRed(), (byte) color.getGreen(), (byte) color.getBlue()}); - } - - /** - * Returns the bullet size that is to be used within a paragraph. - * This may be specified in two different ways, percentage spacing and font point spacing: - *

    - * If bulletSize >= 0, then bulletSize is a percentage of the font size. - * If bulletSize < 0, then it specifies the size in points - *

    - * - * @return the bullet size - */ - public double getBulletFontSize(){ - ParagraphPropertyFetcher fetcher = new ParagraphPropertyFetcher(getLevel()){ - public boolean fetch(CTTextParagraphProperties props){ - if(props.isSetBuSzPct()){ - setValue(props.getBuSzPct().getVal() * 0.001); - return true; - } - if(props.isSetBuSzPts()){ - setValue( - props.getBuSzPts().getVal() * 0.01); - return true; - } - return false; - } - }; - fetchParagraphProperty(fetcher); - return fetcher.getValue() == null ? 100 : fetcher.getValue(); - } - - /** - * Sets the bullet size that is to be used within a paragraph. - * This may be specified in two different ways, percentage spacing and font point spacing: - *

    - * If bulletSize >= 0, then bulletSize is a percentage of the font size. - * If bulletSize < 0, then it specifies the size in points - *

    - */ - public void setBulletFontSize(double bulletSize){ - CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr(); - - if(bulletSize >= 0) { - // percentage - CTTextBulletSizePercent pt = pr.isSetBuSzPct() ? pr.getBuSzPct() : pr.addNewBuSzPct(); - pt.setVal((int)(bulletSize*1000)); - // unset points if percentage is now set - if(pr.isSetBuSzPts()) pr.unsetBuSzPts(); - } else { - // points - CTTextBulletSizePoint pt = pr.isSetBuSzPts() ? pr.getBuSzPts() : pr.addNewBuSzPts(); - pt.setVal((int)(-bulletSize*100)); - // unset percentage if points is now set - if(pr.isSetBuSzPct()) pr.unsetBuSzPct(); - } - } - - /** - * Specifies the indent size that will be applied to the first line of text in the paragraph. - * - * @param value the indent in points, -1 to unset indent and use the default of 0. - */ - public void setIndent(double value){ - CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr(); - if(value == -1) { - if(pr.isSetIndent()) pr.unsetIndent(); - } else { - pr.setIndent(Units.toEMU(value)); - } - } - - /** - * - * @return the indent applied to the first line of text in the paragraph. - */ - public double getIndent(){ - ParagraphPropertyFetcher fetcher = new ParagraphPropertyFetcher(getLevel()){ - public boolean fetch(CTTextParagraphProperties props){ - if(props.isSetIndent()){ - setValue(Units.toPoints(props.getIndent())); - return true; - } - return false; - } - }; - fetchParagraphProperty(fetcher); - - return fetcher.getValue() == null ? 0 : fetcher.getValue(); - } - - - - /** - * Specifies the left margin of the paragraph. This is specified in addition to the text body - * inset and applies only to this text paragraph. That is the text body inset and the LeftMargin - * attributes are additive with respect to the text position. - * - * @param value the left margin of the paragraph, -1 to clear the margin and use the default of 0. - */ - public void setLeftMargin(double value){ - CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr(); - if(value == -1) { - if(pr.isSetMarL()) pr.unsetMarL(); - } else { - pr.setMarL(Units.toEMU(value)); - } - - } - - /** - * - * @return the left margin of the paragraph - */ - public double getLeftMargin(){ - ParagraphPropertyFetcher fetcher = new ParagraphPropertyFetcher(getLevel()){ - public boolean fetch(CTTextParagraphProperties props){ - if(props.isSetMarL()){ - double val = Units.toPoints(props.getMarL()); - setValue(val); - return true; - } - return false; - } - }; - fetchParagraphProperty(fetcher); - // if the marL attribute is omitted, then a value of 347663 is implied - return fetcher.getValue() == null ? 0 : fetcher.getValue(); - } - - /** - * Specifies the right margin of the paragraph. This is specified in addition to the text body - * inset and applies only to this text paragraph. That is the text body inset and the marR - * attributes are additive with respect to the text position. - * - * @param value the right margin of the paragraph, -1 to clear the margin and use the default of 0. - */ - public void setRightMargin(double value){ - CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr(); - if(value == -1) { - if(pr.isSetMarR()) pr.unsetMarR(); - } else { - pr.setMarR(Units.toEMU(value)); - } - - } - - /** - * - * @return the right margin of the paragraph - */ - public double getRightMargin(){ - ParagraphPropertyFetcher fetcher = new ParagraphPropertyFetcher(getLevel()){ - public boolean fetch(CTTextParagraphProperties props){ - if(props.isSetMarR()){ - double val = Units.toPoints(props.getMarR()); - setValue(val); - return true; - } - return false; - } - }; - fetchParagraphProperty(fetcher); - // if the marL attribute is omitted, then a value of 347663 is implied - return fetcher.getValue() == null ? 0 : fetcher.getValue(); - } - - /** - * - * @return the default size for a tab character within this paragraph in points - */ - public double getDefaultTabSize(){ - ParagraphPropertyFetcher fetcher = new ParagraphPropertyFetcher(getLevel()){ - public boolean fetch(CTTextParagraphProperties props){ - if(props.isSetDefTabSz()){ - double val = Units.toPoints(props.getDefTabSz()); - setValue(val); - return true; - } - return false; - } - }; - fetchParagraphProperty(fetcher); - return fetcher.getValue() == null ? 0 : fetcher.getValue(); - } - - public double getTabStop(final int idx){ - ParagraphPropertyFetcher fetcher = new ParagraphPropertyFetcher(getLevel()){ - public boolean fetch(CTTextParagraphProperties props){ - if(props.isSetTabLst()){ - CTTextTabStopList tabStops = props.getTabLst(); - if(idx < tabStops.sizeOfTabArray() ) { - CTTextTabStop ts = tabStops.getTabArray(idx); - double val = Units.toPoints(ts.getPos()); - setValue(val); - return true; - } - } - return false; - } - }; - fetchParagraphProperty(fetcher); - return fetcher.getValue() == null ? 0. : fetcher.getValue(); - } - /** - * Add a single tab stop to be used on a line of text when there are one or more tab characters - * present within the text. - * - * @param value the position of the tab stop relative to the left margin - */ - public void addTabStop(double value){ - CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr(); - CTTextTabStopList tabStops = pr.isSetTabLst() ? pr.getTabLst() : pr.addNewTabLst(); - tabStops.addNewTab().setPos(Units.toEMU(value)); - } - - /** - * This element specifies the vertical line spacing that is to be used within a paragraph. - * This may be specified in two different ways, percentage spacing and font point spacing: - *

    - * If linespacing >= 0, then linespacing is a percentage of normal line height - * If linespacing < 0, the absolute value of linespacing is the spacing in points - *

    - * Examples: - *
    
    -     *      // spacing will be 120% of the size of the largest text on each line
    -     *      paragraph.setLineSpacing(120);
    -     *
    -     *      // spacing will be 200% of the size of the largest text on each line
    -     *      paragraph.setLineSpacing(200);
    -     *
    -     *      // spacing will be 48 points
    -     *      paragraph.setLineSpacing(-48.0);
    -     * 
    - * - * @param linespacing the vertical line spacing - */ - public void setLineSpacing(double linespacing){ - CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr(); - CTTextSpacing spc = CTTextSpacing.Factory.newInstance(); - if(linespacing >= 0) spc.addNewSpcPct().setVal((int)(linespacing*1000)); - else spc.addNewSpcPts().setVal((int)(-linespacing*100)); - pr.setLnSpc(spc); - } - - /** - * Returns the vertical line spacing that is to be used within a paragraph. - * This may be specified in two different ways, percentage spacing and font point spacing: - *

    - * If linespacing >= 0, then linespacing is a percentage of normal line height. - * If linespacing < 0, the absolute value of linespacing is the spacing in points - *

    - * - * @return the vertical line spacing. - */ - public double getLineSpacing(){ - ParagraphPropertyFetcher fetcher = new ParagraphPropertyFetcher(getLevel()){ - public boolean fetch(CTTextParagraphProperties props){ - if(props.isSetLnSpc()){ - CTTextSpacing spc = props.getLnSpc(); - - if(spc.isSetSpcPct()) setValue( spc.getSpcPct().getVal()*0.001 ); - else if (spc.isSetSpcPts()) setValue( -spc.getSpcPts().getVal()*0.01 ); - return true; - } - return false; - } - }; - fetchParagraphProperty(fetcher); - - double lnSpc = fetcher.getValue() == null ? 100 : fetcher.getValue(); - if(lnSpc > 0) { - // check if the percentage value is scaled - CTTextNormalAutofit normAutofit = _shape.getTxBody().getBodyPr().getNormAutofit(); - if(normAutofit != null) { - double scale = 1 - (double)normAutofit.getLnSpcReduction() / 100000; - lnSpc *= scale; - } - } - - return lnSpc; - } - - /** - * Set the amount of vertical white space that will be present before the paragraph. - * This space is specified in either percentage or points: - *

    - * If spaceBefore >= 0, then space is a percentage of normal line height. - * If spaceBefore < 0, the absolute value of linespacing is the spacing in points - *

    - * Examples: - *
    
    -     *      // The paragraph will be formatted to have a spacing before the paragraph text.
    -     *      // The spacing will be 200% of the size of the largest text on each line
    -     *      paragraph.setSpaceBefore(200);
    -     *
    -     *      // The spacing will be a size of 48 points
    -     *      paragraph.setSpaceBefore(-48.0);
    -     * 
    - * - * @param spaceBefore the vertical white space before the paragraph. - */ - public void setSpaceBefore(double spaceBefore){ - CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr(); - CTTextSpacing spc = CTTextSpacing.Factory.newInstance(); - if(spaceBefore >= 0) spc.addNewSpcPct().setVal((int)(spaceBefore*1000)); - else spc.addNewSpcPts().setVal((int)(-spaceBefore*100)); - pr.setSpcBef(spc); - } - - /** - * The amount of vertical white space before the paragraph - * This may be specified in two different ways, percentage spacing and font point spacing: - *

    - * If spaceBefore >= 0, then space is a percentage of normal line height. - * If spaceBefore < 0, the absolute value of linespacing is the spacing in points - *

    - * - * @return the vertical white space before the paragraph - */ - public double getSpaceBefore(){ - ParagraphPropertyFetcher fetcher = new ParagraphPropertyFetcher(getLevel()){ - public boolean fetch(CTTextParagraphProperties props){ - if(props.isSetSpcBef()){ - CTTextSpacing spc = props.getSpcBef(); - - if(spc.isSetSpcPct()) setValue( spc.getSpcPct().getVal()*0.001 ); - else if (spc.isSetSpcPts()) setValue( -spc.getSpcPts().getVal()*0.01 ); - return true; - } - return false; - } - }; - fetchParagraphProperty(fetcher); - - double spcBef = fetcher.getValue() == null ? 0 : fetcher.getValue(); - return spcBef; - } - - /** - * Set the amount of vertical white space that will be present after the paragraph. - * This space is specified in either percentage or points: - *

    - * If spaceAfter >= 0, then space is a percentage of normal line height. - * If spaceAfter < 0, the absolute value of linespacing is the spacing in points - *

    - * Examples: - *
    
    -     *      // The paragraph will be formatted to have a spacing after the paragraph text.
    -     *      // The spacing will be 200% of the size of the largest text on each line
    -     *      paragraph.setSpaceAfter(200);
    -     *
    -     *      // The spacing will be a size of 48 points
    -     *      paragraph.setSpaceAfter(-48.0);
    -     * 
    - * - * @param spaceAfter the vertical white space after the paragraph. - */ - public void setSpaceAfter(double spaceAfter){ - CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr(); - CTTextSpacing spc = CTTextSpacing.Factory.newInstance(); - if(spaceAfter >= 0) spc.addNewSpcPct().setVal((int)(spaceAfter*1000)); - else spc.addNewSpcPts().setVal((int)(-spaceAfter*100)); - pr.setSpcAft(spc); - } - - /** - * The amount of vertical white space after the paragraph - * This may be specified in two different ways, percentage spacing and font point spacing: - *

    - * If spaceBefore >= 0, then space is a percentage of normal line height. - * If spaceBefore < 0, the absolute value of linespacing is the spacing in points - *

    - * - * @return the vertical white space after the paragraph - */ - public double getSpaceAfter(){ - ParagraphPropertyFetcher fetcher = new ParagraphPropertyFetcher(getLevel()){ - public boolean fetch(CTTextParagraphProperties props){ - if(props.isSetSpcAft()){ - CTTextSpacing spc = props.getSpcAft(); - - if(spc.isSetSpcPct()) setValue( spc.getSpcPct().getVal()*0.001 ); - else if (spc.isSetSpcPts()) setValue( -spc.getSpcPts().getVal()*0.01 ); - return true; - } - return false; - } - }; - fetchParagraphProperty(fetcher); - return fetcher.getValue() == null ? 0 : fetcher.getValue(); - } - - /** - * Specifies the particular level text properties that this paragraph will follow. - * The value for this attribute formats the text according to the corresponding level - * paragraph properties defined in the list of styles associated with the body of text - * that this paragraph belongs to (therefore in the parent shape). - *

    - * Note that the closest properties object to the text is used, therefore if there is - * a conflict between the text paragraph properties and the list style properties for - * this level then the text paragraph properties will take precedence. - *

    - * - * @param level the level (0 ... 4) - */ - public void setLevel(int level){ - CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr(); - - pr.setLvl(level); - } - - /** - * Returns the level of text properties that this paragraph will follow. - * - * @return the text level of this paragraph (0-based). Default is 0. - */ - public int getLevel(){ - CTTextParagraphProperties pr = _p.getPPr(); - if(pr == null) return 0; - - return pr.getLvl(); - } - - - /** - * Returns whether this paragraph has bullets - */ - public boolean isBullet() { - ParagraphPropertyFetcher fetcher = new ParagraphPropertyFetcher(getLevel()){ - public boolean fetch(CTTextParagraphProperties props){ - if (props.isSetBuNone()) { - setValue(false); - return true; - } - if (props.isSetBuFont()) { - if (props.isSetBuChar() || props.isSetBuAutoNum()) { - setValue(true); - return true; - } else { - // Excel treats text with buFont but no char/autonum - // as not bulleted - // Possibly the font is just used if bullets turned on again? - } - } - return false; - } - }; - fetchParagraphProperty(fetcher); - return fetcher.getValue() == null ? false : fetcher.getValue(); - } - - /** - * Set or unset this paragraph as a bullet point - * - * @param flag whether text in this paragraph has bullets - */ - public void setBullet(boolean flag) { - if(isBullet() == flag) return; - - CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr(); - if(!flag) { - pr.addNewBuNone(); - - if(pr.isSetBuAutoNum()) pr.unsetBuAutoNum(); - if(pr.isSetBuBlip()) pr.unsetBuBlip(); - if(pr.isSetBuChar()) pr.unsetBuChar(); - if(pr.isSetBuClr()) pr.unsetBuClr(); - if(pr.isSetBuClrTx()) pr.unsetBuClrTx(); - if(pr.isSetBuFont()) pr.unsetBuFont(); - if(pr.isSetBuFontTx()) pr.unsetBuFontTx(); - if(pr.isSetBuSzPct()) pr.unsetBuSzPct(); - if(pr.isSetBuSzPts()) pr.unsetBuSzPts(); - if(pr.isSetBuSzTx()) pr.unsetBuSzTx(); - } else { - if(pr.isSetBuNone()) pr.unsetBuNone(); - if(!pr.isSetBuFont()) pr.addNewBuFont().setTypeface("Arial"); - if(!pr.isSetBuAutoNum()) pr.addNewBuChar().setChar("\u2022"); - } - } - - /** - * Set this paragraph as an automatic numbered bullet point - * - * @param scheme type of auto-numbering - * @param startAt the number that will start number for a given sequence of automatically - * numbered bullets (1-based). - */ - public void setBullet(ListAutoNumber scheme, int startAt) { - if(startAt < 1) throw new IllegalArgumentException("Start Number must be greater or equal that 1") ; - CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr(); - CTTextAutonumberBullet lst = pr.isSetBuAutoNum() ? pr.getBuAutoNum() : pr.addNewBuAutoNum(); - lst.setType(STTextAutonumberScheme.Enum.forInt(scheme.ordinal() + 1)); - lst.setStartAt(startAt); - - if(!pr.isSetBuFont()) pr.addNewBuFont().setTypeface("Arial"); - if(pr.isSetBuNone()) pr.unsetBuNone(); - // remove these elements if present as it results in invalid content when opening in Excel. - if(pr.isSetBuBlip()) pr.unsetBuBlip(); - if(pr.isSetBuChar()) pr.unsetBuChar(); - } - - /** - * Set this paragraph as an automatic numbered bullet point - * - * @param scheme type of auto-numbering - */ - public void setBullet(ListAutoNumber scheme) { - CTTextParagraphProperties pr = _p.isSetPPr() ? _p.getPPr() : _p.addNewPPr(); - CTTextAutonumberBullet lst = pr.isSetBuAutoNum() ? pr.getBuAutoNum() : pr.addNewBuAutoNum(); - lst.setType(STTextAutonumberScheme.Enum.forInt(scheme.ordinal() + 1)); - - if(!pr.isSetBuFont()) pr.addNewBuFont().setTypeface("Arial"); - if(pr.isSetBuNone()) pr.unsetBuNone(); - // remove these elements if present as it results in invalid content when opening in Excel. - if(pr.isSetBuBlip()) pr.unsetBuBlip(); - if(pr.isSetBuChar()) pr.unsetBuChar(); - } - - /** - * Returns whether this paragraph has automatic numbered bullets - */ - public boolean isBulletAutoNumber() { - ParagraphPropertyFetcher fetcher = new ParagraphPropertyFetcher(getLevel()){ - public boolean fetch(CTTextParagraphProperties props){ - if(props.isSetBuAutoNum()) { - setValue(true); - return true; - } - return false; - } - }; - fetchParagraphProperty(fetcher); - return fetcher.getValue() == null ? false : fetcher.getValue(); - } - - /** - * Returns the starting number if this paragraph has automatic numbered bullets, otherwise returns 0 - */ - public int getBulletAutoNumberStart() { - ParagraphPropertyFetcher fetcher = new ParagraphPropertyFetcher(getLevel()){ - public boolean fetch(CTTextParagraphProperties props){ - if(props.isSetBuAutoNum() && props.getBuAutoNum().isSetStartAt()) { - setValue(props.getBuAutoNum().getStartAt()); - return true; - } - return false; - } - }; - fetchParagraphProperty(fetcher); - return fetcher.getValue() == null ? 0 : fetcher.getValue(); - } - - /** - * Returns the auto number scheme if this paragraph has automatic numbered bullets, otherwise returns ListAutoNumber.ARABIC_PLAIN - */ - public ListAutoNumber getBulletAutoNumberScheme() { - ParagraphPropertyFetcher fetcher = new ParagraphPropertyFetcher(getLevel()){ - public boolean fetch(CTTextParagraphProperties props){ - if(props.isSetBuAutoNum()) { - setValue(ListAutoNumber.values()[props.getBuAutoNum().getType().intValue() - 1]); - return true; - } - return false; - } - }; - fetchParagraphProperty(fetcher); - - // Note: documentation does not define a default, return ListAutoNumber.ARABIC_PLAIN (1,2,3...) - return fetcher.getValue() == null ? ListAutoNumber.ARABIC_PLAIN : fetcher.getValue(); - } - - - @SuppressWarnings("rawtypes") - private boolean fetchParagraphProperty(ParagraphPropertyFetcher visitor){ - boolean ok = false; - - if(_p.isSetPPr()) ok = visitor.fetch(_p.getPPr()); - - if(!ok) { - ok = visitor.fetch(_shape); - } - - return ok; - } - - @Override - public String toString(){ - return "[" + getClass() + "]" + getText(); - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFTextRun.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFTextRun.java deleted file mode 100644 index 5b63e94f1..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFTextRun.java +++ /dev/null @@ -1,356 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel; - -import org.openxmlformats.schemas.drawingml.x2006.main.CTRegularTextRun; -import org.openxmlformats.schemas.drawingml.x2006.main.CTSRgbColor; -import org.openxmlformats.schemas.drawingml.x2006.main.CTSolidColorFillProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextCharacterProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextFont; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextNormalAutofit; -import org.openxmlformats.schemas.drawingml.x2006.main.STTextStrikeType; -import org.openxmlformats.schemas.drawingml.x2006.main.STTextUnderlineType; - -import java.awt.Color; - -/** - * Represents a run of text within the containing text body. The run element is the - * lowest level text separation mechanism within a text body. - */ -public class XSSFTextRun { - private final CTRegularTextRun _r; - private final XSSFTextParagraph _p; - - XSSFTextRun(CTRegularTextRun r, XSSFTextParagraph p){ - _r = r; - _p = p; - } - - XSSFTextParagraph getParentParagraph(){ - return _p; - } - - public String getText(){ - return _r.getT(); - } - - public void setText(String text){ - _r.setT(text); - } - - public CTRegularTextRun getXmlObject(){ - return _r; - } - - public void setFontColor(Color color){ - CTTextCharacterProperties rPr = getRPr(); - CTSolidColorFillProperties fill = rPr.isSetSolidFill() ? rPr.getSolidFill() : rPr.addNewSolidFill(); - CTSRgbColor clr = fill.isSetSrgbClr() ? fill.getSrgbClr() : fill.addNewSrgbClr(); - clr.setVal(new byte[]{(byte)color.getRed(), (byte)color.getGreen(), (byte)color.getBlue()}); - - if(fill.isSetHslClr()) fill.unsetHslClr(); - if(fill.isSetPrstClr()) fill.unsetPrstClr(); - if(fill.isSetSchemeClr()) fill.unsetSchemeClr(); - if(fill.isSetScrgbClr()) fill.unsetScrgbClr(); - if(fill.isSetSysClr()) fill.unsetSysClr(); - - } - - public Color getFontColor(){ - - CTTextCharacterProperties rPr = getRPr(); - if(rPr.isSetSolidFill()){ - CTSolidColorFillProperties fill = rPr.getSolidFill(); - - if(fill.isSetSrgbClr()){ - CTSRgbColor clr = fill.getSrgbClr(); - byte[] rgb = clr.getVal(); - return new Color(0xFF & rgb[0], 0xFF & rgb[1], 0xFF & rgb[2]); - } - } - - return new Color(0, 0, 0); - } - - /** - * - * @param fontSize font size in points. - * The value of -1 unsets the Sz attribute from the underlying xml bean - */ - public void setFontSize(double fontSize){ - CTTextCharacterProperties rPr = getRPr(); - if(fontSize == -1.0) { - if(rPr.isSetSz()) rPr.unsetSz(); - } else { - if(fontSize < 1.0) { - throw new IllegalArgumentException("Minimum font size is 1pt but was " + fontSize); - } - - rPr.setSz((int)(100*fontSize)); - } - } - - /** - * @return font size in points or -1 if font size is not set. - */ - public double getFontSize(){ - double scale = 1; - double size = XSSFFont.DEFAULT_FONT_SIZE; // default font size - CTTextNormalAutofit afit = getParentParagraph().getParentShape().getTxBody().getBodyPr().getNormAutofit(); - if(afit != null) scale = (double)afit.getFontScale() / 100000; - - CTTextCharacterProperties rPr = getRPr(); - if(rPr.isSetSz()){ - size = rPr.getSz()*0.01; - } - - return size * scale; - } - - /** - * - * @return the spacing between characters within a text run, - * If this attribute is omitted then a value of 0 or no adjustment is assumed. - */ - public double getCharacterSpacing(){ - CTTextCharacterProperties rPr = getRPr(); - if(rPr.isSetSpc()){ - return rPr.getSpc()*0.01; - } - return 0; - } - - /** - * Set the spacing between characters within a text run. - *

    - * The spacing is specified in points. Positive values will cause the text to expand, - * negative values to condense. - *

    - * - * @param spc character spacing in points. - */ - public void setCharacterSpacing(double spc){ - CTTextCharacterProperties rPr = getRPr(); - if(spc == 0.0) { - if(rPr.isSetSpc()) rPr.unsetSpc(); - } else { - rPr.setSpc((int)(100*spc)); - } - } - - /** - * Specifies the typeface, or name of the font that is to be used for this text run. - * - * @param typeface the font to apply to this text run. - * The value of null unsets the Typeface attribute from the underlying xml. - */ - public void setFont(String typeface){ - setFontFamily(typeface, (byte)-1, (byte)-1, false); - } - - public void setFontFamily(String typeface, byte charset, byte pictAndFamily, boolean isSymbol){ - CTTextCharacterProperties rPr = getRPr(); - - if(typeface == null){ - if(rPr.isSetLatin()) rPr.unsetLatin(); - if(rPr.isSetCs()) rPr.unsetCs(); - if(rPr.isSetSym()) rPr.unsetSym(); - } else { - if(isSymbol){ - CTTextFont font = rPr.isSetSym() ? rPr.getSym() : rPr.addNewSym(); - font.setTypeface(typeface); - } else { - CTTextFont latin = rPr.isSetLatin() ? rPr.getLatin() : rPr.addNewLatin(); - latin.setTypeface(typeface); - if(charset != -1) latin.setCharset(charset); - if(pictAndFamily != -1) latin.setPitchFamily(pictAndFamily); - } - } - } - - /** - * @return font family or null if not set - */ - public String getFontFamily(){ - CTTextCharacterProperties rPr = getRPr(); - CTTextFont font = rPr.getLatin(); - if(font != null){ - return font.getTypeface(); - } - return XSSFFont.DEFAULT_FONT_NAME; - } - - public byte getPitchAndFamily(){ - CTTextCharacterProperties rPr = getRPr(); - CTTextFont font = rPr.getLatin(); - if(font != null){ - return font.getPitchFamily(); - } - return 0; - } - - /** - * Specifies whether a run of text will be formatted as strikethrough text. - * - * @param strike whether a run of text will be formatted as strikethrough text. - */ - public void setStrikethrough(boolean strike) { - getRPr().setStrike(strike ? STTextStrikeType.SNG_STRIKE : STTextStrikeType.NO_STRIKE); - } - - /** - * @return whether a run of text will be formatted as strikethrough text. Default is false. - */ - public boolean isStrikethrough() { - CTTextCharacterProperties rPr = getRPr(); - if(rPr.isSetStrike()){ - return rPr.getStrike() != STTextStrikeType.NO_STRIKE; - } - return false; - } - - /** - * @return whether a run of text will be formatted as a superscript text. Default is false. - */ - public boolean isSuperscript() { - CTTextCharacterProperties rPr = getRPr(); - if(rPr.isSetBaseline()){ - return rPr.getBaseline() > 0; - } - return false; - } - - /** - * Set the baseline for both the superscript and subscript fonts. - *

    - * The size is specified using a percentage. - * Positive values indicate superscript, negative values indicate subscript. - *

    - * - * @param baselineOffset - */ - public void setBaselineOffset(double baselineOffset){ - getRPr().setBaseline((int) baselineOffset * 1000); - } - - /** - * Set whether the text in this run is formatted as superscript. - * Default base line offset is 30% - * - * @see #setBaselineOffset(double) - */ - public void setSuperscript(boolean flag){ - setBaselineOffset(flag ? 30. : 0.); - } - - /** - * Set whether the text in this run is formatted as subscript. - * Default base line offset is -25%. - * - * @see #setBaselineOffset(double) - */ - public void setSubscript(boolean flag){ - setBaselineOffset(flag ? -25.0 : 0.); - } - - /** - * @return whether a run of text will be formatted as a superscript text. Default is false. - */ - public boolean isSubscript() { - CTTextCharacterProperties rPr = getRPr(); - if(rPr.isSetBaseline()){ - return rPr.getBaseline() < 0; - } - return false; - } - - /** - * @return whether a run of text will be formatted as a superscript text. Default is false. - */ - public TextCap getTextCap() { - CTTextCharacterProperties rPr = getRPr(); - if(rPr.isSetCap()){ - return TextCap.values()[rPr.getCap().intValue() - 1]; - } - return TextCap.NONE; - } - - /** - * Specifies whether this run of text will be formatted as bold text - * - * @param bold whether this run of text will be formatted as bold text - */ - public void setBold(boolean bold){ - getRPr().setB(bold); - } - - /** - * @return whether this run of text is formatted as bold text - */ - public boolean isBold(){ - CTTextCharacterProperties rPr = getRPr(); - if(rPr.isSetB()){ - return rPr.getB(); - } - return false; - } - - /** - * @param italic whether this run of text is formatted as italic text - */ - public void setItalic(boolean italic){ - getRPr().setI(italic); - } - - /** - * @return whether this run of text is formatted as italic text - */ - public boolean isItalic(){ - CTTextCharacterProperties rPr = getRPr(); - if(rPr.isSetI()){ - return rPr.getI(); - } - return false; - } - - /** - * @param underline whether this run of text is formatted as underlined text - */ - public void setUnderline(boolean underline) { - getRPr().setU(underline ? STTextUnderlineType.SNG : STTextUnderlineType.NONE); - } - - /** - * @return whether this run of text is formatted as underlined text - */ - public boolean isUnderline(){ - CTTextCharacterProperties rPr = getRPr(); - if(rPr.isSetU()){ - return rPr.getU() != STTextUnderlineType.NONE; - } - return false; - } - - protected CTTextCharacterProperties getRPr(){ - return _r.isSetRPr() ? _r.getRPr() : _r.addNewRPr(); - } - - @Override - public String toString(){ - return "[" + getClass() + "]" + getText(); - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFVBAPart.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFVBAPart.java deleted file mode 100644 index a58146b24..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFVBAPart.java +++ /dev/null @@ -1,52 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.openxml4j.opc.PackagePart; - -public class XSSFVBAPart extends POIXMLDocumentPart { - - /** - * Create a new XSSFVBAPart node - */ - protected XSSFVBAPart() { - super(); - } - - /** - * Construct XSSFVBAPart from a package part - * - * @param part the package part holding the VBA data, - * - * @since POI 3.14-Beta1 - */ - protected XSSFVBAPart(PackagePart part) { - super(part); - } - - /** - * Like *PictureData, VBA objects store the actual content in the part - * directly without keeping a copy like all others therefore we need to - * handle them differently. - */ - protected void prepareForCommit() { - // do not clear the part here - } - -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFVMLDrawing.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFVMLDrawing.java deleted file mode 100644 index 7a7f02f6c..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFVMLDrawing.java +++ /dev/null @@ -1,291 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import static org.apache.poi.POIXMLTypeLoader.DEFAULT_XML_OPTIONS; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.StringReader; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.xml.namespace.QName; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.util.DocumentHelper; -import org.apache.poi.util.ReplacingInputStream; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlObject; -import org.w3c.dom.Document; -import org.w3c.dom.Node; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; - -import com.microsoft.schemas.office.excel.CTClientData; -import com.microsoft.schemas.office.excel.STObjectType; -import com.microsoft.schemas.office.office.CTIdMap; -import com.microsoft.schemas.office.office.CTShapeLayout; -import com.microsoft.schemas.office.office.STConnectType; -import com.microsoft.schemas.office.office.STInsetMode; -import com.microsoft.schemas.vml.CTPath; -import com.microsoft.schemas.vml.CTShadow; -import com.microsoft.schemas.vml.CTShape; -import com.microsoft.schemas.vml.CTShapetype; -import com.microsoft.schemas.vml.STExt; -import com.microsoft.schemas.vml.STStrokeJoinStyle; -import com.microsoft.schemas.vml.STTrueFalse; - -/** - * Represents a SpreadsheetML VML drawing. - * - *

    - * In Excel 2007 VML drawings are used to describe properties of cell comments, - * although the spec says that VML is deprecated: - *

    - *

    - * The VML format is a legacy format originally introduced with Office 2000 and is included and fully defined - * in this Standard for backwards compatibility reasons. The DrawingML format is a newer and richer format - * created with the goal of eventually replacing any uses of VML in the Office Open XML formats. VML should be - * considered a deprecated format included in Office Open XML for legacy reasons only and new applications that - * need a file format for drawings are strongly encouraged to use preferentially DrawingML - *

    - * - *

    - * Warning - Excel is known to put invalid XML into these files! - * For example, >br< without being closed or escaped crops up. - *

    - * - * See 6.4 VML - SpreadsheetML Drawing in Office Open XML Part 4 - Markup Language Reference.pdf - * - * @author Yegor Kozlov - */ -public final class XSSFVMLDrawing extends POIXMLDocumentPart { - private static final QName QNAME_SHAPE_LAYOUT = new QName("urn:schemas-microsoft-com:office:office", "shapelayout"); - private static final QName QNAME_SHAPE_TYPE = new QName("urn:schemas-microsoft-com:vml", "shapetype"); - private static final QName QNAME_SHAPE = new QName("urn:schemas-microsoft-com:vml", "shape"); - private static final String COMMENT_SHAPE_TYPE_ID = "_x0000_t202"; // this ID value seems to have significance to Excel >= 2010; see https://issues.apache.org/bugzilla/show_bug.cgi?id=55409 - - /** - * regexp to parse shape ids, in VML they have weird form of id="_x0000_s1026" - */ - private static final Pattern ptrn_shapeId = Pattern.compile("_x0000_s(\\d+)"); - - private List _qnames = new ArrayList(); - private List _items = new ArrayList(); - private String _shapeTypeId; - private int _shapeId = 1024; - - /** - * Create a new SpreadsheetML drawing - * - * @see XSSFSheet#createDrawingPatriarch() - */ - protected XSSFVMLDrawing() { - super(); - newDrawing(); - } - - /** - * Construct a SpreadsheetML drawing from a package part - * - * @param part the package part holding the drawing data, - * the content type must be application/vnd.openxmlformats-officedocument.drawing+xml - * - * @since POI 3.14-Beta1 - */ - protected XSSFVMLDrawing(PackagePart part) throws IOException, XmlException { - super(part); - read(getPackagePart().getInputStream()); - } - - @SuppressWarnings("resource") - protected void read(InputStream is) throws IOException, XmlException { - Document doc; - try { - /* - * This is a seriously sick fix for the fact that some .xlsx files contain raw bits - * of HTML, without being escaped or properly turned into XML. - * The result is that they contain things like >br<, which breaks the XML parsing. - * This very sick InputStream wrapper attempts to spot these go past, and fix them. - */ - doc = DocumentHelper.readDocument(new ReplacingInputStream(is, "
    ", "
    ")); - } catch (SAXException e) { - throw new XmlException(e.getMessage(), e); - } - XmlObject root = XmlObject.Factory.parse(doc, DEFAULT_XML_OPTIONS); - - _qnames = new ArrayList(); - _items = new ArrayList(); - for(XmlObject obj : root.selectPath("$this/xml/*")) { - Node nd = obj.getDomNode(); - QName qname = new QName(nd.getNamespaceURI(), nd.getLocalName()); - if (qname.equals(QNAME_SHAPE_LAYOUT)) { - _items.add(CTShapeLayout.Factory.parse(obj.xmlText(), DEFAULT_XML_OPTIONS)); - } else if (qname.equals(QNAME_SHAPE_TYPE)) { - CTShapetype st = CTShapetype.Factory.parse(obj.xmlText(), DEFAULT_XML_OPTIONS); - _items.add(st); - _shapeTypeId = st.getId(); - } else if (qname.equals(QNAME_SHAPE)) { - CTShape shape = CTShape.Factory.parse(obj.xmlText(), DEFAULT_XML_OPTIONS); - String id = shape.getId(); - if(id != null) { - Matcher m = ptrn_shapeId.matcher(id); - if(m.find()) { - _shapeId = Math.max(_shapeId, Integer.parseInt(m.group(1))); - } - } - _items.add(shape); - } else { - Document doc2; - try { - InputSource is2 = new InputSource(new StringReader(obj.xmlText())); - doc2 = DocumentHelper.readDocument(is2); - } catch (SAXException e) { - throw new XmlException(e.getMessage(), e); - } - - _items.add(XmlObject.Factory.parse(doc2, DEFAULT_XML_OPTIONS)); - } - _qnames.add(qname); - } - } - - protected List getItems(){ - return _items; - } - - protected void write(OutputStream out) throws IOException { - XmlObject rootObject = XmlObject.Factory.newInstance(); - XmlCursor rootCursor = rootObject.newCursor(); - rootCursor.toNextToken(); - rootCursor.beginElement("xml"); - - for(int i=0; i < _items.size(); i++){ - XmlCursor xc = _items.get(i).newCursor(); - rootCursor.beginElement(_qnames.get(i)); - while(xc.toNextToken() == XmlCursor.TokenType.ATTR) { - Node anode = xc.getDomNode(); - rootCursor.insertAttributeWithValue(anode.getLocalName(), anode.getNamespaceURI(), anode.getNodeValue()); - } - xc.toStartDoc(); - xc.copyXmlContents(rootCursor); - rootCursor.toNextToken(); - xc.dispose(); - } - rootCursor.dispose(); - - rootObject.save(out, DEFAULT_XML_OPTIONS); - } - - @Override - protected void commit() throws IOException { - PackagePart part = getPackagePart(); - OutputStream out = part.getOutputStream(); - write(out); - out.close(); - } - - /** - * Initialize a new Speadsheet VML drawing - */ - private void newDrawing(){ - CTShapeLayout layout = CTShapeLayout.Factory.newInstance(); - layout.setExt(STExt.EDIT); - CTIdMap idmap = layout.addNewIdmap(); - idmap.setExt(STExt.EDIT); - idmap.setData("1"); - _items.add(layout); - _qnames.add(QNAME_SHAPE_LAYOUT); - - CTShapetype shapetype = CTShapetype.Factory.newInstance(); - _shapeTypeId = COMMENT_SHAPE_TYPE_ID; - shapetype.setId(_shapeTypeId); - shapetype.setCoordsize("21600,21600"); - shapetype.setSpt(202); - shapetype.setPath2("m,l,21600r21600,l21600,xe"); - shapetype.addNewStroke().setJoinstyle(STStrokeJoinStyle.MITER); - CTPath path = shapetype.addNewPath(); - path.setGradientshapeok(STTrueFalse.T); - path.setConnecttype(STConnectType.RECT); - _items.add(shapetype); - _qnames.add(QNAME_SHAPE_TYPE); - } - - protected CTShape newCommentShape(){ - CTShape shape = CTShape.Factory.newInstance(); - shape.setId("_x0000_s" + (++_shapeId)); - shape.setType("#" + _shapeTypeId); - shape.setStyle("position:absolute; visibility:hidden"); - shape.setFillcolor("#ffffe1"); - shape.setInsetmode(STInsetMode.AUTO); - shape.addNewFill().setColor("#ffffe1"); - CTShadow shadow = shape.addNewShadow(); - shadow.setOn(STTrueFalse.T); - shadow.setColor("black"); - shadow.setObscured(STTrueFalse.T); - shape.addNewPath().setConnecttype(STConnectType.NONE); - shape.addNewTextbox().setStyle("mso-direction-alt:auto"); - CTClientData cldata = shape.addNewClientData(); - cldata.setObjectType(STObjectType.NOTE); - cldata.addNewMoveWithCells(); - cldata.addNewSizeWithCells(); - cldata.addNewAnchor().setStringValue("1, 15, 0, 2, 3, 15, 3, 16"); - cldata.addNewAutoFill().setStringValue("False"); - cldata.addNewRow().setBigIntegerValue(new BigInteger("0")); - cldata.addNewColumn().setBigIntegerValue(new BigInteger("0")); - _items.add(shape); - _qnames.add(QNAME_SHAPE); - return shape; - } - - /** - * Find a shape with ClientData of type "NOTE" and the specified row and column - * - * @return the comment shape or null - */ - protected CTShape findCommentShape(int row, int col){ - for(XmlObject itm : _items){ - if(itm instanceof CTShape){ - CTShape sh = (CTShape)itm; - if(sh.sizeOfClientDataArray() > 0){ - CTClientData cldata = sh.getClientDataArray(0); - if(cldata.getObjectType() == STObjectType.NOTE){ - int crow = cldata.getRowArray(0).intValue(); - int ccol = cldata.getColumnArray(0).intValue(); - if(crow == row && ccol == col) { - return sh; - } - } - } - } - } - return null; - } - - protected boolean removeCommentShape(int row, int col){ - CTShape shape = findCommentShape(row, col); - return shape != null && _items.remove(shape); - } -} \ No newline at end of file diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFWorkbook.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFWorkbook.java deleted file mode 100644 index 4ed9811d0..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFWorkbook.java +++ /dev/null @@ -1,2499 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import static org.apache.poi.POIXMLTypeLoader.DEFAULT_XML_OPTIONS; -import static org.apache.poi.xssf.usermodel.helpers.XSSFPasswordHelper.setPassword; -import static org.apache.poi.xssf.usermodel.helpers.XSSFPasswordHelper.validatePassword; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.regex.Pattern; - -import javax.xml.namespace.QName; - -import org.apache.commons.collections4.ListValuedMap; -import org.apache.commons.collections4.multimap.ArrayListValuedHashMap; -import org.apache.poi.POIXMLDocument; -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.POIXMLException; -import org.apache.poi.POIXMLProperties; -import org.apache.poi.hpsf.ClassID; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.exceptions.OpenXML4JException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackageAccess; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.opc.PackagePartName; -import org.apache.poi.openxml4j.opc.PackageRelationship; -import org.apache.poi.openxml4j.opc.PackageRelationshipTypes; -import org.apache.poi.openxml4j.opc.PackagingURIHelper; -import org.apache.poi.openxml4j.opc.TargetMode; -import org.apache.poi.poifs.crypt.HashAlgorithm; -import org.apache.poi.poifs.filesystem.DirectoryNode; -import org.apache.poi.poifs.filesystem.Ole10Native; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.ss.formula.SheetNameFormatter; -import org.apache.poi.ss.formula.udf.AggregatingUDFFinder; -import org.apache.poi.ss.formula.udf.IndexedUDFFinder; -import org.apache.poi.ss.formula.udf.UDFFinder; -import org.apache.poi.ss.usermodel.Name; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Row.MissingCellPolicy; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.SheetVisibility; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.ss.util.WorkbookUtil; -import org.apache.poi.util.Beta; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.Internal; -import org.apache.poi.util.NotImplemented; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.util.PackageHelper; -import org.apache.poi.util.Removal; -import org.apache.poi.xssf.XLSBUnsupportedException; -import org.apache.poi.xssf.model.CalculationChain; -import org.apache.poi.xssf.model.ExternalLinksTable; -import org.apache.poi.xssf.model.MapInfo; -import org.apache.poi.xssf.model.SharedStringsTable; -import org.apache.poi.xssf.model.StylesTable; -import org.apache.poi.xssf.model.ThemesTable; -import org.apache.poi.xssf.usermodel.helpers.XSSFFormulaUtils; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlOptions; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTBookView; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTBookViews; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCalcPr; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTDefinedName; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTDefinedNames; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTDialogsheet; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTExternalReference; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPivotCache; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPivotCaches; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTSheet; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTSheets; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorkbook; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorkbookPr; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorkbookProtection; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STCalcMode; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STSheetState; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.WorkbookDocument; - -/** - * High level representation of a SpreadsheetML workbook. This is the first object most users - * will construct whether they are reading or writing a workbook. It is also the - * top level object for creating new sheets/etc. - */ -public class XSSFWorkbook extends POIXMLDocument implements Workbook { - private static final Pattern COMMA_PATTERN = Pattern.compile(","); - - /** - * Width of one character of the default font in pixels. Same for Calibry and Arial. - */ - public static final float DEFAULT_CHARACTER_WIDTH = 7.0017f; - - /** - * Excel silently truncates long sheet names to 31 chars. - * This constant is used to ensure uniqueness in the first 31 chars - */ - private static final int MAX_SENSITIVE_SHEET_NAME_LEN = 31; - - /** - * Images formats supported by XSSF but not by HSSF - */ - public static final int PICTURE_TYPE_GIF = 8; - public static final int PICTURE_TYPE_TIFF = 9; - public static final int PICTURE_TYPE_EPS = 10; - public static final int PICTURE_TYPE_BMP = 11; - public static final int PICTURE_TYPE_WPG = 12; - - /** - * The underlying XML bean - */ - private CTWorkbook workbook; - - /** - * this holds the XSSFSheet objects attached to this workbook - */ - private List sheets; - - /** - * this holds the XSSFName objects attached to this workbook, keyed by lower-case name - */ - private ListValuedMap namedRangesByName; - - /** - * this holds the XSSFName objects attached to this workbook - */ - private List namedRanges; - - /** - * shared string table - a cache of strings in this workbook - */ - private SharedStringsTable sharedStringSource; - - /** - * A collection of shared objects used for styling content, - * e.g. fonts, cell styles, colors, etc. - */ - private StylesTable stylesSource; - - /** - * The locator of user-defined functions. - * By default includes functions from the Excel Analysis Toolpack - */ - private IndexedUDFFinder _udfFinder = new IndexedUDFFinder(AggregatingUDFFinder.DEFAULT); - - /** - * TODO - */ - private CalculationChain calcChain; - - /** - * External Links, for referencing names or cells in other workbooks. - */ - private List externalLinks; - - /** - * A collection of custom XML mappings - */ - private MapInfo mapInfo; - - /** - * Used to keep track of the data formatter so that all - * createDataFormatter calls return the same one for a given - * book. This ensures that updates from one places is visible - * someplace else. - */ - private XSSFDataFormat formatter; - - /** - * The policy to apply in the event of missing or - * blank cells when fetching from a row. - * See {@link org.apache.poi.ss.usermodel.Row.MissingCellPolicy} - */ - private MissingCellPolicy _missingCellPolicy = MissingCellPolicy.RETURN_NULL_AND_BLANK; - - /** - * Whether a call to {@link XSSFCell#setCellFormula(String)} will validate the formula or not. - */ - private boolean cellFormulaValidation = true; - - /** - * array of pictures for this workbook - */ - private List pictures; - - private static POILogger logger = POILogFactory.getLogger(XSSFWorkbook.class); - - /** - * cached instance of XSSFCreationHelper for this workbook - * @see {@link #getCreationHelper()} - */ - private XSSFCreationHelper _creationHelper; - - /** - * List of all pivot tables in workbook - */ - private List pivotTables; - private List pivotCaches; - - - /** - * Create a new SpreadsheetML workbook. - */ - public XSSFWorkbook() { - this(XSSFWorkbookType.XLSX); - } - - /** - * Create a new SpreadsheetML workbook. - * @param workbookType The type of workbook to make (.xlsx or .xlsm). - */ - public XSSFWorkbook(XSSFWorkbookType workbookType) { - super(newPackage(workbookType)); - onWorkbookCreate(); - } - - /** - * Constructs a XSSFWorkbook object given a OpenXML4J Package object, - * see http://poi.apache.org/oxml4j/. - * - *

    Once you have finished working with the Workbook, you should close the package - * by calling either {@link #close()} or {@link OPCPackage#close()}, to avoid - * leaving file handles open. - * - *

    Creating a XSSFWorkbook from a file-backed OPC Package has a lower memory - * footprint than an InputStream backed one. - * - * @param pkg the OpenXML4J OPC Package object. - */ - public XSSFWorkbook(OPCPackage pkg) throws IOException { - super(pkg); - - beforeDocumentRead(); - - // Build a tree of POIXMLDocumentParts, this workbook being the root - load(XSSFFactory.getInstance()); - - // some broken Workbooks miss this... - if(!workbook.isSetBookViews()) { - CTBookViews bvs = workbook.addNewBookViews(); - CTBookView bv = bvs.addNewWorkbookView(); - bv.setActiveTab(0); - } - } - - /** - * Constructs a XSSFWorkbook object, by buffering the whole stream into memory - * and then opening an {@link OPCPackage} object for it. - * - *

    Using an {@link InputStream} requires more memory than using a File, so - * if a {@link File} is available then you should instead do something like - *

    
    -     *       OPCPackage pkg = OPCPackage.open(path);
    -     *       XSSFWorkbook wb = new XSSFWorkbook(pkg);
    -     *       // work with the wb object
    -     *       ......
    -     *       pkg.close(); // gracefully closes the underlying zip file
    -     *   
    - */ - public XSSFWorkbook(InputStream is) throws IOException { - super(PackageHelper.open(is)); - - beforeDocumentRead(); - - // Build a tree of POIXMLDocumentParts, this workbook being the root - load(XSSFFactory.getInstance()); - - // some broken Workbooks miss this... - if(!workbook.isSetBookViews()) { - CTBookViews bvs = workbook.addNewBookViews(); - CTBookView bv = bvs.addNewWorkbookView(); - bv.setActiveTab(0); - } - } - - /** - * Constructs a XSSFWorkbook object from a given file. - * - *

    Once you have finished working with the Workbook, you should close - * the package by calling {@link #close()}, to avoid leaving file - * handles open. - * - *

    Opening a XSSFWorkbook from a file has a lower memory footprint - * than opening from an InputStream - * - * @param file the file to open - */ - public XSSFWorkbook(File file) throws IOException, InvalidFormatException { - this(OPCPackage.open(file)); - } - - /** - * Constructs a XSSFWorkbook object given a file name. - * - * - *

    Once you have finished working with the Workbook, you should close - * the package by calling {@link #close()}, to avoid leaving file - * handles open. - * - *

    Opening a XSSFWorkbook from a file has a lower memory footprint - * than opening from an InputStream - * - * @param path the file name. - */ - public XSSFWorkbook(String path) throws IOException { - this(openPackage(path)); - } - - protected void beforeDocumentRead() { - // Ensure it isn't a XLSB file, which we don't support - if (getCorePart().getContentType().equals(XSSFRelation.XLSB_BINARY_WORKBOOK.getContentType())) { - throw new XLSBUnsupportedException(); - } - - // Create arrays for parts attached to the workbook itself - pivotTables = new ArrayList(); - pivotCaches = new ArrayList(); - } - - @Override - protected void onDocumentRead() throws IOException { - try { - WorkbookDocument doc = WorkbookDocument.Factory.parse(getPackagePart().getInputStream(), DEFAULT_XML_OPTIONS); - this.workbook = doc.getWorkbook(); - - ThemesTable theme = null; - Map shIdMap = new HashMap(); - Map elIdMap = new HashMap(); - for(RelationPart rp : getRelationParts()){ - POIXMLDocumentPart p = rp.getDocumentPart(); - if(p instanceof SharedStringsTable) { - sharedStringSource = (SharedStringsTable)p; - } else if(p instanceof StylesTable) { - stylesSource = (StylesTable)p; - } else if(p instanceof ThemesTable) { - theme = (ThemesTable)p; - } else if(p instanceof CalculationChain) { - calcChain = (CalculationChain)p; - } else if(p instanceof MapInfo) { - mapInfo = (MapInfo)p; - } else if (p instanceof XSSFSheet) { - shIdMap.put(rp.getRelationship().getId(), (XSSFSheet)p); - } else if (p instanceof ExternalLinksTable) { - elIdMap.put(rp.getRelationship().getId(), (ExternalLinksTable)p); - } - } - boolean packageReadOnly = (getPackage().getPackageAccess() == PackageAccess.READ); - - if (stylesSource == null) { - // Create Styles if it is missing - if (packageReadOnly) { - stylesSource = new StylesTable(); - } else { - stylesSource = (StylesTable)createRelationship(XSSFRelation.STYLES, XSSFFactory.getInstance()); - } - } - stylesSource.setWorkbook(this); - stylesSource.setTheme(theme); - - if (sharedStringSource == null) { - // Create SST if it is missing - if (packageReadOnly) { - sharedStringSource = new SharedStringsTable(); - } else { - sharedStringSource = (SharedStringsTable)createRelationship(XSSFRelation.SHARED_STRINGS, XSSFFactory.getInstance()); - } - } - - // Load individual sheets. The order of sheets is defined by the order - // of CTSheet elements in the workbook - sheets = new ArrayList(shIdMap.size()); - for (CTSheet ctSheet : this.workbook.getSheets().getSheetArray()) { - parseSheet(shIdMap, ctSheet); - } - - // Load the external links tables. Their order is defined by the order - // of CTExternalReference elements in the workbook - externalLinks = new ArrayList(elIdMap.size()); - if (this.workbook.isSetExternalReferences()) { - for (CTExternalReference er : this.workbook.getExternalReferences().getExternalReferenceArray()) { - ExternalLinksTable el = elIdMap.get(er.getId()); - if(el == null) { - logger.log(POILogger.WARN, "ExternalLinksTable with r:id " + er.getId()+ " was defined, but didn't exist in package, skipping"); - continue; - } - externalLinks.add(el); - } - } - - // Process the named ranges - reprocessNamedRanges(); - } catch (XmlException e) { - throw new POIXMLException(e); - } - } - - /** - * Not normally to be called externally, but possibly to be overridden to avoid - * the DOM based parse of large sheets (see examples). - */ - public void parseSheet(Map shIdMap, CTSheet ctSheet) { - XSSFSheet sh = shIdMap.get(ctSheet.getId()); - if(sh == null) { - logger.log(POILogger.WARN, "Sheet with name " + ctSheet.getName() + " and r:id " + ctSheet.getId()+ " was defined, but didn't exist in package, skipping"); - return; - } - sh.sheet = ctSheet; - sh.onDocumentRead(); - sheets.add(sh); - } - - /** - * Create a new CTWorkbook with all values set to default - */ - private void onWorkbookCreate() { - workbook = CTWorkbook.Factory.newInstance(); - - // don't EVER use the 1904 date system - CTWorkbookPr workbookPr = workbook.addNewWorkbookPr(); - workbookPr.setDate1904(false); - - CTBookViews bvs = workbook.addNewBookViews(); - CTBookView bv = bvs.addNewWorkbookView(); - bv.setActiveTab(0); - workbook.addNewSheets(); - - POIXMLProperties.ExtendedProperties expProps = getProperties().getExtendedProperties(); - expProps.getUnderlyingProperties().setApplication(DOCUMENT_CREATOR); - - sharedStringSource = (SharedStringsTable)createRelationship(XSSFRelation.SHARED_STRINGS, XSSFFactory.getInstance()); - stylesSource = (StylesTable)createRelationship(XSSFRelation.STYLES, XSSFFactory.getInstance()); - stylesSource.setWorkbook(this); - - namedRanges = new ArrayList(); - namedRangesByName = new ArrayListValuedHashMap(); - sheets = new ArrayList(); - pivotTables = new ArrayList(); - } - - /** - * Create a new SpreadsheetML package and setup the default minimal content - */ - protected static OPCPackage newPackage(XSSFWorkbookType workbookType) { - try { - OPCPackage pkg = OPCPackage.create(new ByteArrayOutputStream()); - // Main part - PackagePartName corePartName = PackagingURIHelper.createPartName(XSSFRelation.WORKBOOK.getDefaultFileName()); - // Create main part relationship - pkg.addRelationship(corePartName, TargetMode.INTERNAL, PackageRelationshipTypes.CORE_DOCUMENT); - // Create main document part - pkg.createPart(corePartName, workbookType.getContentType()); - - pkg.getPackageProperties().setCreatorProperty(DOCUMENT_CREATOR); - - return pkg; - } catch (Exception e){ - throw new POIXMLException(e); - } - } - - /** - * Return the underlying XML bean - * - * @return the underlying CTWorkbook bean - */ - @Internal - public CTWorkbook getCTWorkbook() { - return this.workbook; - } - - /** - * Adds a picture to the workbook. - * - * @param pictureData The bytes of the picture - * @param format The format of the picture. - * - * @return the index to this picture (0 based), the added picture can be obtained from {@link #getAllPictures()} . - * @see Workbook#PICTURE_TYPE_EMF - * @see Workbook#PICTURE_TYPE_WMF - * @see Workbook#PICTURE_TYPE_PICT - * @see Workbook#PICTURE_TYPE_JPEG - * @see Workbook#PICTURE_TYPE_PNG - * @see Workbook#PICTURE_TYPE_DIB - * @see #getAllPictures() - */ - @Override - public int addPicture(byte[] pictureData, int format) { - int imageNumber = getAllPictures().size() + 1; - XSSFPictureData img = (XSSFPictureData)createRelationship(XSSFPictureData.RELATIONS[format], XSSFFactory.getInstance(), imageNumber, true).getDocumentPart(); - try { - OutputStream out = img.getPackagePart().getOutputStream(); - out.write(pictureData); - out.close(); - } catch (IOException e){ - throw new POIXMLException(e); - } - pictures.add(img); - return imageNumber - 1; - } - - /** - * Adds a picture to the workbook. - * - * @param is The sream to read image from - * @param format The format of the picture. - * - * @return the index to this picture (0 based), the added picture can be obtained from {@link #getAllPictures()} . - * @see Workbook#PICTURE_TYPE_EMF - * @see Workbook#PICTURE_TYPE_WMF - * @see Workbook#PICTURE_TYPE_PICT - * @see Workbook#PICTURE_TYPE_JPEG - * @see Workbook#PICTURE_TYPE_PNG - * @see Workbook#PICTURE_TYPE_DIB - * @see #getAllPictures() - */ - public int addPicture(InputStream is, int format) throws IOException { - int imageNumber = getAllPictures().size() + 1; - XSSFPictureData img = createRelationship(XSSFPictureData.RELATIONS[format], XSSFFactory.getInstance(), imageNumber, true).getDocumentPart(); - OutputStream out = img.getPackagePart().getOutputStream(); - IOUtils.copy(is, out); - out.close(); - pictures.add(img); - return imageNumber - 1; - } - - /** - * Create an XSSFSheet from an existing sheet in the XSSFWorkbook. - * The cloned sheet is a deep copy of the original. - * - * @param sheetNum The index of the sheet to clone - * @return XSSFSheet representing the cloned sheet. - * @throws IllegalArgumentException if the sheet index in invalid - * @throws POIXMLException if there were errors when cloning - */ - @Override - public XSSFSheet cloneSheet(int sheetNum) { - return cloneSheet(sheetNum, null); - } - - /** - * Create an XSSFSheet from an existing sheet in the XSSFWorkbook. - * The cloned sheet is a deep copy of the original but with a new given - * name. - * - * @param sheetNum The index of the sheet to clone - * @param newName The name to set for the newly created sheet - * @return XSSFSheet representing the cloned sheet. - * @throws IllegalArgumentException if the sheet index or the sheet - * name is invalid - * @throws POIXMLException if there were errors when cloning - */ - public XSSFSheet cloneSheet(int sheetNum, String newName) { - validateSheetIndex(sheetNum); - XSSFSheet srcSheet = sheets.get(sheetNum); - - if (newName == null) { - String srcName = srcSheet.getSheetName(); - newName = getUniqueSheetName(srcName); - } else { - validateSheetName(newName); - } - - XSSFSheet clonedSheet = createSheet(newName); - - // copy sheet's relations - List rels = srcSheet.getRelationParts(); - // if the sheet being cloned has a drawing then rememebr it and re-create it too - XSSFDrawing dg = null; - for(RelationPart rp : rels) { - POIXMLDocumentPart r = rp.getDocumentPart(); - // do not copy the drawing relationship, it will be re-created - if(r instanceof XSSFDrawing) { - dg = (XSSFDrawing)r; - continue; - } - - addRelation(rp, clonedSheet); - } - - try { - for(PackageRelationship pr : srcSheet.getPackagePart().getRelationships()) { - if (pr.getTargetMode() == TargetMode.EXTERNAL) { - clonedSheet.getPackagePart().addExternalRelationship - (pr.getTargetURI().toASCIIString(), pr.getRelationshipType(), pr.getId()); - } - } - } catch (InvalidFormatException e) { - throw new POIXMLException("Failed to clone sheet", e); - } - - - try { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - srcSheet.write(out); - clonedSheet.read(new ByteArrayInputStream(out.toByteArray())); - } catch (IOException e){ - throw new POIXMLException("Failed to clone sheet", e); - } - CTWorksheet ct = clonedSheet.getCTWorksheet(); - if(ct.isSetLegacyDrawing()) { - logger.log(POILogger.WARN, "Cloning sheets with comments is not yet supported."); - ct.unsetLegacyDrawing(); - } - if (ct.isSetPageSetup()) { - logger.log(POILogger.WARN, "Cloning sheets with page setup is not yet supported."); - ct.unsetPageSetup(); - } - - clonedSheet.setSelected(false); - - // clone the sheet drawing alongs with its relationships - if (dg != null) { - if(ct.isSetDrawing()) { - // unset the existing reference to the drawing, - // so that subsequent call of clonedSheet.createDrawingPatriarch() will create a new one - ct.unsetDrawing(); - } - XSSFDrawing clonedDg = clonedSheet.createDrawingPatriarch(); - // copy drawing contents - clonedDg.getCTDrawing().set(dg.getCTDrawing()); - - clonedDg = clonedSheet.createDrawingPatriarch(); - - // Clone drawing relations - List srcRels = srcSheet.createDrawingPatriarch().getRelationParts(); - for (RelationPart rp : srcRels) { - addRelation(rp, clonedDg); - } - } - return clonedSheet; - } - - /** - * @since 3.14-Beta1 - */ - private static void addRelation(RelationPart rp, POIXMLDocumentPart target) { - PackageRelationship rel = rp.getRelationship(); - if (rel.getTargetMode() == TargetMode.EXTERNAL) { - target.getPackagePart().addRelationship( - rel.getTargetURI(), rel.getTargetMode(), rel.getRelationshipType(), rel.getId()); - } else { - XSSFRelation xssfRel = XSSFRelation.getInstance(rel.getRelationshipType()); - if (xssfRel == null) { - // Don't copy all relations blindly, but only the ones we know about - throw new POIXMLException("Can't clone sheet - unknown relation type found: "+rel.getRelationshipType()); - } - target.addRelation(rel.getId(), xssfRel, rp.getDocumentPart()); - } - } - - /** - * Generate a valid sheet name based on the existing one. Used when cloning sheets. - * - * @param srcName the original sheet name to - * @return clone sheet name - */ - private String getUniqueSheetName(String srcName) { - int uniqueIndex = 2; - String baseName = srcName; - int bracketPos = srcName.lastIndexOf('('); - if (bracketPos > 0 && srcName.endsWith(")")) { - String suffix = srcName.substring(bracketPos + 1, srcName.length() - ")".length()); - try { - uniqueIndex = Integer.parseInt(suffix.trim()); - uniqueIndex++; - baseName = srcName.substring(0, bracketPos).trim(); - } catch (NumberFormatException e) { - // contents of brackets not numeric - } - } - while (true) { - // Try and find the next sheet name that is unique - String index = Integer.toString(uniqueIndex++); - String name; - if (baseName.length() + index.length() + 2 < 31) { - name = baseName + " (" + index + ")"; - } else { - name = baseName.substring(0, 31 - index.length() - 2) + "(" + index + ")"; - } - - //If the sheet name is unique, then set it otherwise move on to the next number. - if (getSheetIndex(name) == -1) { - return name; - } - } - } - - /** - * Create a new XSSFCellStyle and add it to the workbook's style table - * - * @return the new XSSFCellStyle object - */ - @Override - public XSSFCellStyle createCellStyle() { - return stylesSource.createCellStyle(); - } - - /** - * Returns the workbook's data format table (a factory for creating data format strings). - * - * @return the XSSFDataFormat object - * @see org.apache.poi.ss.usermodel.DataFormat - */ - @Override - public XSSFDataFormat createDataFormat() { - if (formatter == null) { - formatter = new XSSFDataFormat(stylesSource); - } - return formatter; - } - - /** - * Create a new Font and add it to the workbook's font table - * - * @return new font object - */ - @Override - public XSSFFont createFont() { - XSSFFont font = new XSSFFont(); - font.registerTo(stylesSource); - return font; - } - - @Override - public XSSFName createName() { - CTDefinedName ctName = CTDefinedName.Factory.newInstance(); - ctName.setName(""); - return createAndStoreName(ctName); - } - - private XSSFName createAndStoreName(CTDefinedName ctName) { - XSSFName name = new XSSFName(ctName, this); - namedRanges.add(name); - namedRangesByName.put(ctName.getName().toLowerCase(Locale.ENGLISH), name); - return name; - } - - /** - * Create an XSSFSheet for this workbook, adds it to the sheets and returns - * the high level representation. Use this to create new sheets. - * - * @return XSSFSheet representing the new sheet. - */ - @Override - public XSSFSheet createSheet() { - String sheetname = "Sheet" + (sheets.size()); - int idx = 0; - while(getSheet(sheetname) != null) { - sheetname = "Sheet" + idx; - idx++; - } - return createSheet(sheetname); - } - - /** - * Create a new sheet for this Workbook and return the high level representation. - * Use this to create new sheets. - * - *

    - * Note that Excel allows sheet names up to 31 chars in length but other applications - * (such as OpenOffice) allow more. Some versions of Excel crash with names longer than 31 chars, - * others - truncate such names to 31 character. - *

    - *

    - * POI's SpreadsheetAPI silently truncates the input argument to 31 characters. - * Example: - * - *

    
    -     *     Sheet sheet = workbook.createSheet("My very long sheet name which is longer than 31 chars"); // will be truncated
    -     *     assert 31 == sheet.getSheetName().length();
    -     *     assert "My very long sheet name which i" == sheet.getSheetName();
    -     *     
    - *

    - * - * Except the 31-character constraint, Excel applies some other rules: - *

    - * Sheet name MUST be unique in the workbook and MUST NOT contain the any of the following characters: - *

      - *
    • 0x0000
    • - *
    • 0x0003
    • - *
    • colon (:)
    • - *
    • backslash (\)
    • - *
    • asterisk (*)
    • - *
    • question mark (?)
    • - *
    • forward slash (/)
    • - *
    • opening square bracket ([)
    • - *
    • closing square bracket (])
    • - *
    - * The string MUST NOT begin or end with the single quote (') character. - *

    - * - *

    - * See {@link org.apache.poi.ss.util.WorkbookUtil#createSafeSheetName(String nameProposal)} - * for a safe way to create valid names - *

    - * @param sheetname sheetname to set for the sheet. - * @return Sheet representing the new sheet. - * @throws IllegalArgumentException if the name is null or invalid - * or workbook already contains a sheet with this name - * @see org.apache.poi.ss.util.WorkbookUtil#createSafeSheetName(String nameProposal) - */ - @Override - public XSSFSheet createSheet(String sheetname) { - if (sheetname == null) { - throw new IllegalArgumentException("sheetName must not be null"); - } - - validateSheetName(sheetname); - - // YK: Mimic Excel and silently truncate sheet names longer than 31 characters - if(sheetname.length() > 31) { - sheetname = sheetname.substring(0, 31); - } - WorkbookUtil.validateSheetName(sheetname); - - CTSheet sheet = addSheet(sheetname); - - int sheetNumber = 1; - outerloop: - while(true) { - for(XSSFSheet sh : sheets) { - sheetNumber = (int)Math.max(sh.sheet.getSheetId() + 1, sheetNumber); - } - - // Bug 57165: We also need to check that the resulting file name is not already taken - // this can happen when moving/cloning sheets - String sheetName = XSSFRelation.WORKSHEET.getFileName(sheetNumber); - for(POIXMLDocumentPart relation : getRelations()) { - if(relation.getPackagePart() != null && - sheetName.equals(relation.getPackagePart().getPartName().getName())) { - // name is taken => try next one - sheetNumber++; - continue outerloop; - } - } - - // no duplicate found => use this one - break; - } - - RelationPart rp = createRelationship(XSSFRelation.WORKSHEET, XSSFFactory.getInstance(), sheetNumber, false); - XSSFSheet wrapper = rp.getDocumentPart(); - wrapper.sheet = sheet; - sheet.setId(rp.getRelationship().getId()); - sheet.setSheetId(sheetNumber); - if (sheets.isEmpty()) { - wrapper.setSelected(true); - } - sheets.add(wrapper); - return wrapper; - } - - private void validateSheetName(final String sheetName) throws IllegalArgumentException { - if (containsSheet( sheetName, sheets.size() )) { - throw new IllegalArgumentException("The workbook already contains a sheet named '" + sheetName + "'"); - } - } - - protected XSSFDialogsheet createDialogsheet(String sheetname, CTDialogsheet dialogsheet) { - XSSFSheet sheet = createSheet(sheetname); - return new XSSFDialogsheet(sheet); - } - - private CTSheet addSheet(String sheetname) { - CTSheet sheet = workbook.getSheets().addNewSheet(); - sheet.setName(sheetname); - return sheet; - } - - /** - * Finds a font that matches the one with the supplied attributes - * @deprecated POI 3.15. Use {@link #findFont(boolean, short, short, String, boolean, boolean, short, byte)} instead. - */ - @Deprecated - @Override - public XSSFFont findFont(short boldWeight, short color, short fontHeight, String name, boolean italic, boolean strikeout, short typeOffset, byte underline) { - return stylesSource.findFont(boldWeight, color, fontHeight, name, italic, strikeout, typeOffset, underline); - } - - /** - * Finds a font that matches the one with the supplied attributes - */ - @Override - public XSSFFont findFont(boolean bold, short color, short fontHeight, String name, boolean italic, boolean strikeout, short typeOffset, byte underline) { - return stylesSource.findFont(bold, color, fontHeight, name, italic, strikeout, typeOffset, underline); - } - - /** - * Convenience method to get the active sheet. The active sheet is is the sheet - * which is currently displayed when the workbook is viewed in Excel. - * 'Selected' sheet(s) is a distinct concept. - */ - @Override - public int getActiveSheetIndex() { - //activeTab (Active Sheet Index) Specifies an unsignedInt - //that contains the index to the active sheet in this book view. - return (int)workbook.getBookViews().getWorkbookViewArray(0).getActiveTab(); - } - - /** - * Gets all pictures from the Workbook. - * - * @return the list of pictures (a list of {@link XSSFPictureData} objects.) - * @see #addPicture(byte[], int) - */ - @Override - public List getAllPictures() { - if(pictures == null){ - List mediaParts = getPackage().getPartsByName(Pattern.compile("/xl/media/.*?")); - pictures = new ArrayList(mediaParts.size()); - for(PackagePart part : mediaParts){ - pictures.add(new XSSFPictureData(part)); - } - } - return pictures; //YK: should return Collections.unmodifiableList(pictures); - } - - /** - * Get the cell style object at the given index - * - * @param idx index within the set of styles - * @return XSSFCellStyle object at the index - */ - @Override - public XSSFCellStyle getCellStyleAt(int idx) { - return stylesSource.getStyleAt(idx); - } - - /** - * Get the font at the given index number - * - * @param idx index number - * @return XSSFFont at the index - */ - @Override - public XSSFFont getFontAt(short idx) { - return stylesSource.getFontAt(idx); - } - - /** - * Get the first named range with the given name. - * - * Note: names of named ranges are not unique as they are scoped by sheet. - * {@link #getNames(String name)} returns all named ranges with the given name. - * - * @param name named range name - * @return XSSFName with the given name. null is returned no named range could be found. - */ - @Override - public XSSFName getName(String name) { - Collection list = getNames(name); - if (list.isEmpty()) { - return null; - } - return list.iterator().next(); - } - - /** - * Get the named ranges with the given name. - * Note:Excel named ranges are case-insensitive and - * this method performs a case-insensitive search. - * - * @param name named range name - * @return list of XSSFNames with the given name. An empty list if no named ranges could be found - */ - @Override - public List getNames(String name) { - return Collections.unmodifiableList(namedRangesByName.get(name.toLowerCase(Locale.ENGLISH))); - } - - /** - * Get the named range at the given index. - * - * @param nameIndex the index of the named range - * @return the XSSFName at the given index - * - * @deprecated 3.16. New projects should avoid accessing named ranges by index. - */ - @Override - @Deprecated - public XSSFName getNameAt(int nameIndex) { - int nNames = namedRanges.size(); - if (nNames < 1) { - throw new IllegalStateException("There are no defined names in this workbook"); - } - if (nameIndex < 0 || nameIndex > nNames) { - throw new IllegalArgumentException("Specified name index " + nameIndex - + " is outside the allowable range (0.." + (nNames-1) + ")."); - } - return namedRanges.get(nameIndex); - } - - /** - * Get a list of all the named ranges in the workbook. - * - * @return list of XSSFNames in the workbook - */ - @Override - public List getAllNames() { - return Collections.unmodifiableList(namedRanges); - } - - /** - * Gets the named range index by name. - * - * @param name named range name - * @return named range index. -1 is returned if no named ranges could be found. - * - * @deprecated 3.16. New projects should avoid accessing named ranges by index. - * Use {@link #getName(String)} instead. - */ - @Override - @Deprecated - public int getNameIndex(String name) { - XSSFName nm = getName(name); - if (nm != null) { - return namedRanges.indexOf(nm); - } - return -1; - } - - /** - * Get the number of styles the workbook contains - * - * @return count of cell styles - */ - @Override - public int getNumCellStyles() { - return stylesSource.getNumCellStyles(); - } - - /** - * Get the number of fonts in the this workbook - * - * @return number of fonts - */ - @Override - public short getNumberOfFonts() { - return (short)stylesSource.getFonts().size(); - } - - /** - * Get the number of named ranges in the this workbook - * - * @return number of named ranges - */ - @Override - public int getNumberOfNames() { - return namedRanges.size(); - } - - /** - * Get the number of worksheets in the this workbook - * - * @return number of worksheets - */ - @Override - public int getNumberOfSheets() { - return sheets.size(); - } - - /** - * Retrieves the reference for the printarea of the specified sheet, the sheet name is appended to the reference even if it was not specified. - * @param sheetIndex Zero-based sheet index (0 Represents the first sheet to keep consistent with java) - * @return String Null if no print area has been defined - */ - @Override - public String getPrintArea(int sheetIndex) { - XSSFName name = getBuiltInName(XSSFName.BUILTIN_PRINT_AREA, sheetIndex); - if (name == null) { - return null; - } - //adding one here because 0 indicates a global named region; doesnt make sense for print areas - return name.getRefersToFormula(); - - } - - /** - * Get sheet with the given name (case insensitive match) - * - * @param name of the sheet - * @return XSSFSheet with the name provided or null if it does not exist - */ - @Override - public XSSFSheet getSheet(String name) { - for (XSSFSheet sheet : sheets) { - if (name.equalsIgnoreCase(sheet.getSheetName())) { - return sheet; - } - } - return null; - } - - /** - * Get the XSSFSheet object at the given index. - * - * @param index of the sheet number (0-based physical & logical) - * @return XSSFSheet at the provided index - * @throws IllegalArgumentException if the index is out of range (index - * < 0 || index >= getNumberOfSheets()). - */ - @Override - public XSSFSheet getSheetAt(int index) { - validateSheetIndex(index); - return sheets.get(index); - } - - /** - * Returns the index of the sheet by his name (case insensitive match) - * - * @param name the sheet name - * @return index of the sheet (0 based) or -1-1 if not found - */ - @Override - public int getSheetIndex(Sheet sheet) { - int idx = 0; - for(XSSFSheet sh : sheets){ - if(sh == sheet) { - return idx; - } - idx++; - } - return -1; - } - - /** - * Get the sheet name - * - * @param sheetIx Number - * @return Sheet name - */ - @Override - public String getSheetName(int sheetIx) { - validateSheetIndex(sheetIx); - return sheets.get(sheetIx).getSheetName(); - } - - /** - * Returns an iterator of the sheets in the workbook - * in sheet order. Includes hidden and very hidden sheets. - * - * Note: remove() is not supported on this iterator. - * Use {@link #removeSheetAt(int)} to remove sheets instead. - * - * @return an iterator of the sheets. - */ - @Override - public Iterator sheetIterator() { - return new SheetIterator(); - } - - /** - * Alias for {@link #sheetIterator()} to allow - * foreach loops - * - * Iterator iterator() was replaced with Iterator iterator() - * to make iterating over a container (Workbook, Sheet, Row) consistent across POI spreadsheets. - * This breaks backwards compatibility and may affect your code. - * See {@link XSSFWorkbook#xssfSheetIterator} for how to upgrade your code to be compatible - * with the new interface. - * - * Note: remove() is not supported on this iterator. - * Use {@link #removeSheetAt(int)} to remove sheets instead. - * - * @return an iterator of the sheets. - */ - @Override - public Iterator iterator() { - return sheetIterator(); - } - - private final class SheetIterator implements Iterator { - final private Iterator it; - @SuppressWarnings("unchecked") - public SheetIterator() { - it = (Iterator) sheets.iterator(); - } - @Override - public boolean hasNext() { - return it.hasNext(); - } - @Override - public T next() throws NoSuchElementException { - return it.next(); - } - /** - * Unexpected behavior may occur if sheets are reordered after iterator - * has been created. Support for the remove method may be added in the future - * if someone can figure out a reliable implementation. - */ - @Override - public void remove() throws IllegalStateException { - throw new UnsupportedOperationException("remove method not supported on XSSFWorkbook.iterator(). "+ - "Use Sheet.removeSheetAt(int) instead."); - } - } - - /** - * xssfSheetIterator was added to make transitioning to the new Iterator iterator() - * interface less painful for projects currently using POI. - * - * If your code was written using a for-each loop: - *
    
    -     *  for (XSSFSheet sh : wb) {
    -     *      sh.createRow(0);
    -     *  }
    -     *  
    - * - * There are two ways to upgrade your code: - * // Option A: - *
    
    -     *  for (XSSFSheet sh : (Iterable) (Iterable) wb) {
    -     *      sh.createRow(0);
    -     *  }
    -     *  
    - * - * // Option B (preferred for new code): - *
    
    -     *  for (Sheet sh : wb) {
    -     *      sh.createRow(0);
    -     *  }
    -     *  
    - * - * - * - * If your code was written using an iterator variable: - *
    
    -     *  Iterator it = wb.iterator();
    -     *  XSSFSheet sh = it.next();
    -     *  sh.createRow(0);
    -     *  
    - * - * There are three ways to upgrade your code: - * // Option A: - *
    
    -     *  Iterator it = (Iterator) (Iterator) wb.iterator();
    -     *  XSSFSheet sh = it.next();
    -     *  sh.createRow(0);
    -     *  
    - * - * // Option B: - *
    
    -     *  @SuppressWarnings("deprecation")
    -     *  Iterator it = wb.xssfSheetIterator();
    -     *  XSSFSheet sh = it.next();
    -     *  sh.createRow(0);
    -     *  
    - * - * // Option C (preferred for new code): - *
    
    -     *  Iterator it = wb.iterator();
    -     *  Sheet sh = it.next();
    -     *  sh.createRow(0);
    -     *  
    - * - * @deprecated 3.13. New projects should use the preferred options. Note: XSSFWorkbook.xssfSheetIterator - * is deprecated and will be removed in 3.15. - * - * @return an iterator of the sheets. - */ - @Deprecated - public Iterator xssfSheetIterator() { - return new SheetIterator(); - } - - /** - * Are we a normal workbook (.xlsx), or a - * macro enabled workbook (.xlsm)? - */ - public boolean isMacroEnabled() { - return getPackagePart().getContentType().equals(XSSFRelation.MACROS_WORKBOOK.getContentType()); - } - - /** - * Remove the named range at the given index. - * - * @param nameIndex the index of the named range name to remove - * - * @deprecated 3.16. New projects should use {@link #removeName(Name)}. - */ - @Override - @Deprecated - public void removeName(int nameIndex) { - removeName(getNameAt(nameIndex)); - } - - /** - * Remove the first named range found with the given name. - * - * Note: names of named ranges are not unique (name + sheet - * index is unique), so {@link #removeName(Name)} should - * be used if possible. - * - * @param name the named range name to remove - * - * @throws IllegalArgumentException if no named range could be found - * - * @deprecated 3.16. New projects should use {@link #removeName(Name)}. - */ - @Override - @Deprecated - public void removeName(String name) { - List names = namedRangesByName.get(name.toLowerCase(Locale.ENGLISH)); - if (names.isEmpty()) { - throw new IllegalArgumentException("Named range was not found: " + name); - } - removeName(names.get(0)); - } - - - /** - * As {@link #removeName(String)} is not necessarily unique - * (name + sheet index is unique), this method is more accurate. - * - * @param name the name to remove. - * - * @throws IllegalArgumentException if the named range is not a part of this XSSFWorkbook - */ - @Override - public void removeName(Name name) { - if (!namedRangesByName.removeMapping(name.getNameName().toLowerCase(Locale.ENGLISH), name) - || !namedRanges.remove(name)) { - throw new IllegalArgumentException("Name was not found: " + name); - } - } - - void updateName(XSSFName name, String oldName) { - if (!namedRangesByName.removeMapping(oldName.toLowerCase(Locale.ENGLISH), name)) { - throw new IllegalArgumentException("Name was not found: " + name); - } - namedRangesByName.put(name.getNameName().toLowerCase(Locale.ENGLISH), name); - } - - - /** - * Delete the printarea for the sheet specified - * - * @param sheetIndex 0-based sheet index (0 = First Sheet) - */ - @Override - public void removePrintArea(int sheetIndex) { - XSSFName name = getBuiltInName(XSSFName.BUILTIN_PRINT_AREA, sheetIndex); - if (name != null) { - removeName(name); - } - } - - /** - * Removes sheet at the given index.

    - * - * Care must be taken if the removed sheet is the currently active or only selected sheet in - * the workbook. There are a few situations when Excel must have a selection and/or active - * sheet. (For example when printing - see Bug 40414).
    - * - * This method makes sure that if the removed sheet was active, another sheet will become - * active in its place. Furthermore, if the removed sheet was the only selected sheet, another - * sheet will become selected. The newly active/selected sheet will have the same index, or - * one less if the removed sheet was the last in the workbook. - * - * @param index of the sheet (0-based) - */ - @Override - public void removeSheetAt(int index) { - validateSheetIndex(index); - - onSheetDelete(index); - - XSSFSheet sheet = getSheetAt(index); - removeRelation(sheet); - sheets.remove(index); - - // only set new sheet if there are still some left - if(sheets.size() == 0) { - return; - } - - // the index of the closest remaining sheet to the one just deleted - int newSheetIndex = index; - if (newSheetIndex >= sheets.size()) { - newSheetIndex = sheets.size()-1; - } - - // adjust active sheet - int active = getActiveSheetIndex(); - if(active == index) { - // removed sheet was the active one, reset active sheet if there is still one left now - setActiveSheet(newSheetIndex); - } else if (active > index) { - // removed sheet was below the active one => active is one less now - setActiveSheet(active-1); - } - } - - /** - * Gracefully remove references to the sheet being deleted - * - * @param index the 0-based index of the sheet to delete - */ - private void onSheetDelete(int index) { - //delete the CTSheet reference from workbook.xml - workbook.getSheets().removeSheet(index); - - //calculation chain is auxiliary, remove it as it may contain orphan references to deleted cells - if(calcChain != null) { - removeRelation(calcChain); - calcChain = null; - } - - //adjust indices of names ranges - List toRemove = new ArrayList(); - for (XSSFName nm : namedRanges) { - CTDefinedName ct = nm.getCTName(); - if(!ct.isSetLocalSheetId()) { - continue; - } - if (ct.getLocalSheetId() == index) { - toRemove.add(nm); - } else if (ct.getLocalSheetId() > index){ - // Bump down by one, so still points at the same sheet - ct.setLocalSheetId(ct.getLocalSheetId()-1); - } - } - for (XSSFName nm : toRemove) { - removeName(nm); - } - } - - /** - * Retrieves the current policy on what to do when - * getting missing or blank cells from a row. - * The default is to return blank and null cells. - * {@link MissingCellPolicy} - */ - @Override - public MissingCellPolicy getMissingCellPolicy() { - return _missingCellPolicy; - } - /** - * Sets the policy on what to do when - * getting missing or blank cells from a row. - * This will then apply to all calls to - * {@link Row#getCell(int)}}. See - * {@link MissingCellPolicy} - */ - @Override - public void setMissingCellPolicy(MissingCellPolicy missingCellPolicy) { - _missingCellPolicy = missingCellPolicy; - } - - /** - * Convenience method to set the active sheet. The active sheet is is the sheet - * which is currently displayed when the workbook is viewed in Excel. - * 'Selected' sheet(s) is a distinct concept. - */ - @Override - public void setActiveSheet(int index) { - - validateSheetIndex(index); - - for (CTBookView arrayBook : workbook.getBookViews().getWorkbookViewArray()) { - arrayBook.setActiveTab(index); - } - } - - /** - * Validate sheet index - * - * @param index the index to validate - * @throws IllegalArgumentException if the index is out of range (index - * < 0 || index >= getNumberOfSheets()). - */ - private void validateSheetIndex(int index) { - int lastSheetIx = sheets.size() - 1; - if (index < 0 || index > lastSheetIx) { - String range = "(0.." + lastSheetIx + ")"; - if (lastSheetIx == -1) { - range = "(no sheets)"; - } - throw new IllegalArgumentException("Sheet index (" - + index +") is out of range " + range); - } - } - - /** - * Gets the first tab that is displayed in the list of tabs in excel. - * - * @return integer that contains the index to the active sheet in this book view. - */ - @Override - public int getFirstVisibleTab() { - CTBookViews bookViews = workbook.getBookViews(); - CTBookView bookView = bookViews.getWorkbookViewArray(0); - return (short) bookView.getFirstSheet(); - } - - /** - * Sets the first tab that is displayed in the list of tabs in excel. - * - * @param index integer that contains the index to the active sheet in this book view. - */ - @Override - public void setFirstVisibleTab(int index) { - CTBookViews bookViews = workbook.getBookViews(); - CTBookView bookView= bookViews.getWorkbookViewArray(0); - bookView.setFirstSheet(index); - } - - /** - * Sets the printarea for the sheet provided - *

    - * i.e. Reference = $A$1:$B$2 - * @param sheetIndex Zero-based sheet index (0 Represents the first sheet to keep consistent with java) - * @param reference Valid name Reference for the Print Area - */ - @Override - public void setPrintArea(int sheetIndex, String reference) { - XSSFName name = getBuiltInName(XSSFName.BUILTIN_PRINT_AREA, sheetIndex); - if (name == null) { - name = createBuiltInName(XSSFName.BUILTIN_PRINT_AREA, sheetIndex); - } - //short externSheetIndex = getWorkbook().checkExternSheet(sheetIndex); - //name.setExternSheetNumber(externSheetIndex); - String[] parts = COMMA_PATTERN.split(reference); - StringBuffer sb = new StringBuffer(32); - for (int i = 0; i < parts.length; i++) { - if(i>0) { - sb.append(","); - } - SheetNameFormatter.appendFormat(sb, getSheetName(sheetIndex)); - sb.append("!"); - sb.append(parts[i]); - } - name.setRefersToFormula(sb.toString()); - } - - /** - * For the Convenience of Java Programmers maintaining pointers. - * @see #setPrintArea(int, String) - * @param sheetIndex Zero-based sheet index (0 = First Sheet) - * @param startColumn Column to begin printarea - * @param endColumn Column to end the printarea - * @param startRow Row to begin the printarea - * @param endRow Row to end the printarea - */ - @Override - public void setPrintArea(int sheetIndex, int startColumn, int endColumn, int startRow, int endRow) { - String reference=getReferencePrintArea(getSheetName(sheetIndex), startColumn, endColumn, startRow, endRow); - setPrintArea(sheetIndex, reference); - } - - private static String getReferencePrintArea(String sheetName, int startC, int endC, int startR, int endR) { - //windows excel example: Sheet1!$C$3:$E$4 - CellReference colRef = new CellReference(sheetName, startR, startC, true, true); - CellReference colRef2 = new CellReference(sheetName, endR, endC, true, true); - - return "$" + colRef.getCellRefParts()[2] + "$" + colRef.getCellRefParts()[1] + ":$" + colRef2.getCellRefParts()[2] + "$" + colRef2.getCellRefParts()[1]; - } - - XSSFName getBuiltInName(String builtInCode, int sheetNumber) { - for (XSSFName name : namedRangesByName.get(builtInCode.toLowerCase(Locale.ENGLISH))) { - if (name.getSheetIndex() == sheetNumber) { - return name; - } - } - return null; - } - - /** - * Generates a NameRecord to represent a built-in region - * - * @return a new NameRecord - * @throws IllegalArgumentException if sheetNumber is invalid - * @throws POIXMLException if such a name already exists in the workbook - */ - XSSFName createBuiltInName(String builtInName, int sheetNumber) { - validateSheetIndex(sheetNumber); - - CTDefinedNames names = workbook.getDefinedNames() == null ? workbook.addNewDefinedNames() : workbook.getDefinedNames(); - CTDefinedName nameRecord = names.addNewDefinedName(); - nameRecord.setName(builtInName); - nameRecord.setLocalSheetId(sheetNumber); - - if (getBuiltInName(builtInName, sheetNumber) != null) { - throw new POIXMLException("Builtin (" + builtInName - + ") already exists for sheet (" + sheetNumber + ")"); - } - - return createAndStoreName(nameRecord); - } - - /** - * We only set one sheet as selected for compatibility with HSSF. - */ - @Override - public void setSelectedTab(int index) { - int idx = 0; - for (XSSFSheet sh : sheets) { - sh.setSelected(idx == index); - idx++; - } - } - - /** - * Set the sheet name. - * - * @param sheetIndex sheet number (0 based) - * @param sheetname the new sheet name - * @throws IllegalArgumentException if the name is null or invalid - * or workbook already contains a sheet with this name - * @see #createSheet(String) - * @see org.apache.poi.ss.util.WorkbookUtil#createSafeSheetName(String nameProposal) - */ - @Override - public void setSheetName(int sheetIndex, String sheetname) { - if (sheetname == null) { - throw new IllegalArgumentException( "sheetName must not be null" ); - } - - validateSheetIndex(sheetIndex); - String oldSheetName = getSheetName(sheetIndex); - - // YK: Mimic Excel and silently truncate sheet names longer than 31 characters - if(sheetname.length() > 31) { - sheetname = sheetname.substring(0, 31); - } - WorkbookUtil.validateSheetName(sheetname); - - // Do nothing if no change - if (sheetname.equals(oldSheetName)) { - return; - } - - // Check it isn't already taken - if (containsSheet(sheetname, sheetIndex )) { - throw new IllegalArgumentException( "The workbook already contains a sheet of this name" ); - } - - // Update references to the name - XSSFFormulaUtils utils = new XSSFFormulaUtils(this); - utils.updateSheetName(sheetIndex, oldSheetName, sheetname); - - workbook.getSheets().getSheetArray(sheetIndex).setName(sheetname); - } - - /** - * sets the order of appearance for a given sheet. - * - * @param sheetname the name of the sheet to reorder - * @param pos the position that we want to insert the sheet into (0 based) - */ - @Override - public void setSheetOrder(String sheetname, int pos) { - int idx = getSheetIndex(sheetname); - sheets.add(pos, sheets.remove(idx)); - - // Reorder CTSheets - CTSheets ct = workbook.getSheets(); - XmlObject cts = ct.getSheetArray(idx).copy(); - workbook.getSheets().removeSheet(idx); - CTSheet newcts = ct.insertNewSheet(pos); - newcts.set(cts); - - //notify sheets - CTSheet[] sheetArray = ct.getSheetArray(); - for(int i=0; i < sheetArray.length; i++) { - sheets.get(i).sheet = sheetArray[i]; - } - - updateNamedRangesAfterSheetReorder(idx, pos); - updateActiveSheetAfterSheetReorder(idx, pos); - } - - /** - * update sheet-scoped named ranges in this workbook after changing the sheet order - * of a sheet at oldIndex to newIndex. - * Sheets between these indices will move left or right by 1. - * - * @param oldIndex the original index of the re-ordered sheet - * @param newIndex the new index of the re-ordered sheet - */ - private void updateNamedRangesAfterSheetReorder(int oldIndex, int newIndex) { - // update sheet index of sheet-scoped named ranges - for (final XSSFName name : namedRanges) { - final int i = name.getSheetIndex(); - // name has sheet-level scope - if (i != -1) { - // name refers to this sheet - if (i == oldIndex) { - name.setSheetIndex(newIndex); - } - // if oldIndex > newIndex then this sheet moved left and sheets between newIndex and oldIndex moved right - else if (newIndex <= i && i < oldIndex) { - name.setSheetIndex(i+1); - } - // if oldIndex < newIndex then this sheet moved right and sheets between oldIndex and newIndex moved left - else if (oldIndex < i && i <= newIndex) { - name.setSheetIndex(i-1); - } - } - } - } - - private void updateActiveSheetAfterSheetReorder(int oldIndex, int newIndex) { - // adjust active sheet if necessary - int active = getActiveSheetIndex(); - if(active == oldIndex) { - // moved sheet was the active one - setActiveSheet(newIndex); - } else if ((active < oldIndex && active < newIndex) || - (active > oldIndex && active > newIndex)) { - // not affected - } else if (newIndex > oldIndex) { - // moved sheet was below before and is above now => active is one less - setActiveSheet(active-1); - } else { - // remaining case: moved sheet was higher than active before and is lower now => active is one more - setActiveSheet(active+1); - } - } - - /** - * marshal named ranges from the {@link #namedRanges} collection to the underlying CTWorkbook bean - */ - private void saveNamedRanges(){ - // Named ranges - if(namedRanges.size() > 0) { - CTDefinedNames names = CTDefinedNames.Factory.newInstance(); - CTDefinedName[] nr = new CTDefinedName[namedRanges.size()]; - int i = 0; - for(XSSFName name : namedRanges) { - nr[i] = name.getCTName(); - i++; - } - names.setDefinedNameArray(nr); - if(workbook.isSetDefinedNames()) { - workbook.unsetDefinedNames(); - } - workbook.setDefinedNames(names); - - // Re-process the named ranges - reprocessNamedRanges(); - } else { - if(workbook.isSetDefinedNames()) { - workbook.unsetDefinedNames(); - } - } - } - - private void reprocessNamedRanges() { - namedRangesByName = new ArrayListValuedHashMap(); - namedRanges = new ArrayList(); - if(workbook.isSetDefinedNames()) { - for(CTDefinedName ctName : workbook.getDefinedNames().getDefinedNameArray()) { - createAndStoreName(ctName); - } - } - } - - private void saveCalculationChain(){ - if(calcChain != null){ - int count = calcChain.getCTCalcChain().sizeOfCArray(); - if(count == 0){ - removeRelation(calcChain); - calcChain = null; - } - } - } - - @Override - protected void commit() throws IOException { - saveNamedRanges(); - saveCalculationChain(); - - XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS); - xmlOptions.setSaveSyntheticDocumentElement(new QName(CTWorkbook.type.getName().getNamespaceURI(), "workbook")); - - PackagePart part = getPackagePart(); - OutputStream out = part.getOutputStream(); - workbook.save(out, xmlOptions); - out.close(); - } - - /** - * Returns SharedStringsTable - tha cache of string for this workbook - * - * @return the shared string table - */ - @Internal - public SharedStringsTable getSharedStringSource() { - return this.sharedStringSource; - } - - /** - * Return a object representing a collection of shared objects used for styling content, - * e.g. fonts, cell styles, colors, etc. - */ - public StylesTable getStylesSource() { - return this.stylesSource; - } - - /** - * Returns the Theme of current workbook. - */ - public ThemesTable getTheme() { - if (stylesSource == null) { - return null; - } - return stylesSource.getTheme(); - } - - /** - * Returns an object that handles instantiating concrete - * classes of the various instances for XSSF. - */ - @Override - public XSSFCreationHelper getCreationHelper() { - if(_creationHelper == null) { - _creationHelper = new XSSFCreationHelper(this); - } - return _creationHelper; - } - - /** - * Determines whether a workbook contains the provided sheet name. - * For the purpose of comparison, long names are truncated to 31 chars. - * - * @param name the name to test (case insensitive match) - * @param excludeSheetIdx the sheet to exclude from the check or -1 to include all sheets in the check. - * @return true if the sheet contains the name, false otherwise. - */ - private boolean containsSheet(String name, int excludeSheetIdx) { - CTSheet[] ctSheetArray = workbook.getSheets().getSheetArray(); - - if (name.length() > MAX_SENSITIVE_SHEET_NAME_LEN) { - name = name.substring(0, MAX_SENSITIVE_SHEET_NAME_LEN); - } - - for (int i = 0; i < ctSheetArray.length; i++) { - String ctName = ctSheetArray[i].getName(); - if (ctName.length() > MAX_SENSITIVE_SHEET_NAME_LEN) { - ctName = ctName.substring(0, MAX_SENSITIVE_SHEET_NAME_LEN); - } - - if (excludeSheetIdx != i && name.equalsIgnoreCase(ctName)) { - return true; - } - } - return false; - } - - /** - * Gets a boolean value that indicates whether the date systems used in the workbook starts in 1904. - *

    - * The default value is false, meaning that the workbook uses the 1900 date system, - * where 1/1/1900 is the first day in the system.. - *

    - * @return true if the date systems used in the workbook starts in 1904 - */ - @Internal - public boolean isDate1904(){ - CTWorkbookPr workbookPr = workbook.getWorkbookPr(); - return workbookPr != null && workbookPr.getDate1904(); - } - - /** - * Get the document's embedded files. - */ - @Override - public List getAllEmbedds() throws OpenXML4JException { - List embedds = new LinkedList(); - - for(XSSFSheet sheet : sheets){ - // Get the embeddings for the workbook - for(PackageRelationship rel : sheet.getPackagePart().getRelationshipsByType(XSSFRelation.OLEEMBEDDINGS.getRelation())) { - embedds.add( sheet.getPackagePart().getRelatedPart(rel) ); - } - - for(PackageRelationship rel : sheet.getPackagePart().getRelationshipsByType(XSSFRelation.PACKEMBEDDINGS.getRelation())) { - embedds.add( sheet.getPackagePart().getRelatedPart(rel) ); - } - } - return embedds; - } - - @Override - @NotImplemented - public boolean isHidden() { - throw new RuntimeException("Not implemented yet"); - } - - @Override - @NotImplemented - public void setHidden(boolean hiddenFlag) { - throw new RuntimeException("Not implemented yet"); - } - - @Override - public boolean isSheetHidden(int sheetIx) { - validateSheetIndex(sheetIx); - CTSheet ctSheet = sheets.get(sheetIx).sheet; - return ctSheet.getState() == STSheetState.HIDDEN; - } - - @Override - public boolean isSheetVeryHidden(int sheetIx) { - validateSheetIndex(sheetIx); - CTSheet ctSheet = sheets.get(sheetIx).sheet; - return ctSheet.getState() == STSheetState.VERY_HIDDEN; - } - - @Override - public SheetVisibility getSheetVisibility(int sheetIx) { - validateSheetIndex(sheetIx); - final CTSheet ctSheet = sheets.get(sheetIx).sheet; - final STSheetState.Enum state = ctSheet.getState(); - if (state == STSheetState.VISIBLE) { - return SheetVisibility.VISIBLE; - } - if (state == STSheetState.HIDDEN) { - return SheetVisibility.HIDDEN; - } - if (state == STSheetState.VERY_HIDDEN) { - return SheetVisibility.VERY_HIDDEN; - } - throw new IllegalArgumentException("This should never happen"); - } - - @Override - public void setSheetHidden(int sheetIx, boolean hidden) { - setSheetVisibility(sheetIx, hidden ? SheetVisibility.HIDDEN : SheetVisibility.VISIBLE); - } - - @Deprecated - @Removal(version="3.18") - @Override - public void setSheetHidden(int sheetIx, int state) { - WorkbookUtil.validateSheetState(state); - setSheetVisibility(sheetIx, SheetVisibility.values()[state]); - } - - @Override - public void setSheetVisibility(int sheetIx, SheetVisibility visibility) { - validateSheetIndex(sheetIx); - - final CTSheet ctSheet = sheets.get(sheetIx).sheet; - switch (visibility) { - case VISIBLE: - ctSheet.setState(STSheetState.VISIBLE); - break; - case HIDDEN: - ctSheet.setState(STSheetState.HIDDEN); - break; - case VERY_HIDDEN: - ctSheet.setState(STSheetState.VERY_HIDDEN); - break; - default: - throw new IllegalArgumentException("This should never happen"); - } - } - - - - - /** - * Fired when a formula is deleted from this workbook, - * for example when calling cell.setCellFormula(null) - * - * @see XSSFCell#setCellFormula(String) - */ - protected void onDeleteFormula(XSSFCell cell){ - if(calcChain != null) { - int sheetId = (int)cell.getSheet().sheet.getSheetId(); - calcChain.removeItem(sheetId, cell.getReference()); - } - } - - /** - * Return the {@link CalculationChain} object for this workbook - *

    - * The calculation chain object specifies the order in which the cells in a workbook were last calculated - *

    - * - * @return the CalculationChain object or null if not defined - */ - @Internal - public CalculationChain getCalculationChain() { - return calcChain; - } - - /** - * Returns the list of {@link ExternalLinksTable} object for this workbook - * - *

    The external links table specifies details of named ranges etc - * that are referenced from other workbooks, along with the last seen - * values of what they point to.

    - * - *

    Note that Excel uses index 0 for the current workbook, so the first - * External Links in a formula would be '[1]Foo' which corresponds to - * entry 0 in this list.

    - - * @return the ExternalLinksTable list, which may be empty - */ - @Internal - public List getExternalLinksTable() { - return externalLinks; - } - - /** - * - * @return a collection of custom XML mappings defined in this workbook - */ - public Collection getCustomXMLMappings(){ - return mapInfo == null ? new ArrayList() : mapInfo.getAllXSSFMaps(); - } - - /** - * - * @return the helper class used to query the custom XML mapping defined in this workbook - */ - @Internal - public MapInfo getMapInfo(){ - return mapInfo; - } - - /** - * Adds the External Link Table part and relations required to allow formulas - * referencing the specified external workbook to be added to this one. Allows - * formulas such as "[MyOtherWorkbook.xlsx]Sheet3!$A$5" to be added to the - * file, for workbooks not already linked / referenced. - * - * Note: this is not implemented and thus currently throws an Exception stating this. - * - * @param name The name the workbook will be referenced as in formulas - * @param workbook The open workbook to fetch the link required information from - * - * @throws RuntimeException stating that this method is not implemented yet. - */ - @Override - @NotImplemented - public int linkExternalWorkbook(String name, Workbook workbook) { - throw new RuntimeException("Not Implemented - see bug #57184"); - } - - /** - * Specifies a boolean value that indicates whether structure of workbook is locked.
    - * A value true indicates the structure of the workbook is locked. Worksheets in the workbook can't be moved, - * deleted, hidden, unhidden, or renamed, and new worksheets can't be inserted.
    - * A value of false indicates the structure of the workbook is not locked.
    - * - * @return true if structure of workbook is locked - */ - public boolean isStructureLocked() { - return workbookProtectionPresent() && workbook.getWorkbookProtection().getLockStructure(); - } - - /** - * Specifies a boolean value that indicates whether the windows that comprise the workbook are locked.
    - * A value of true indicates the workbook windows are locked. Windows are the same size and position each time the - * workbook is opened.
    - * A value of false indicates the workbook windows are not locked. - * - * @return true if windows that comprise the workbook are locked - */ - public boolean isWindowsLocked() { - return workbookProtectionPresent() && workbook.getWorkbookProtection().getLockWindows(); - } - - /** - * Specifies a boolean value that indicates whether the workbook is locked for revisions. - * - * @return true if the workbook is locked for revisions. - */ - public boolean isRevisionLocked() { - return workbookProtectionPresent() && workbook.getWorkbookProtection().getLockRevision(); - } - - /** - * Locks the structure of workbook. - */ - public void lockStructure() { - safeGetWorkbookProtection().setLockStructure(true); - } - - /** - * Unlocks the structure of workbook. - */ - public void unLockStructure() { - safeGetWorkbookProtection().setLockStructure(false); - } - - /** - * Locks the windows that comprise the workbook. - */ - public void lockWindows() { - safeGetWorkbookProtection().setLockWindows(true); - } - - /** - * Unlocks the windows that comprise the workbook. - */ - public void unLockWindows() { - safeGetWorkbookProtection().setLockWindows(false); - } - - /** - * Locks the workbook for revisions. - */ - public void lockRevision() { - safeGetWorkbookProtection().setLockRevision(true); - } - - /** - * Unlocks the workbook for revisions. - */ - public void unLockRevision() { - safeGetWorkbookProtection().setLockRevision(false); - } - - /** - * Sets the workbook password. - * - * @param password if null, the password will be removed - * @param hashAlgo if null, the password will be set as XOR password (Excel 2010 and earlier) - * otherwise the given algorithm is used for calculating the hash password (Excel 2013) - */ - public void setWorkbookPassword(String password, HashAlgorithm hashAlgo) { - if (password == null && !workbookProtectionPresent()) { - return; - } - setPassword(safeGetWorkbookProtection(), password, hashAlgo, "workbook"); - } - - /** - * Validate the password against the stored hash, the hashing method will be determined - * by the existing password attributes - * @return true, if the hashes match (... though original password may differ ...) - */ - public boolean validateWorkbookPassword(String password) { - if (!workbookProtectionPresent()) { - return (password == null); - } - return validatePassword(safeGetWorkbookProtection(), password, "workbook"); - } - - /** - * Sets the revisions password. - * - * @param password if null, the password will be removed - * @param hashAlgo if null, the password will be set as XOR password (Excel 2010 and earlier) - * otherwise the given algorithm is used for calculating the hash password (Excel 2013) - */ - public void setRevisionsPassword(String password, HashAlgorithm hashAlgo) { - if (password == null && !workbookProtectionPresent()) { - return; - } - setPassword(safeGetWorkbookProtection(), password, hashAlgo, "revisions"); - } - - /** - * Validate the password against the stored hash, the hashing method will be determined - * by the existing password attributes - * @return true if the hashes match (... though original password may differ ...) - */ - public boolean validateRevisionsPassword(String password) { - if (!workbookProtectionPresent()) { - return (password == null); - } - return validatePassword(safeGetWorkbookProtection(), password, "revisions"); - } - - /** - * Removes the workbook protection settings - */ - public void unLock() { - if (workbookProtectionPresent()) { - workbook.unsetWorkbookProtection(); - } - } - - private boolean workbookProtectionPresent() { - return workbook.isSetWorkbookProtection(); - } - - private CTWorkbookProtection safeGetWorkbookProtection() { - if (!workbookProtectionPresent()){ - return workbook.addNewWorkbookProtection(); - } - return workbook.getWorkbookProtection(); - } - - /** - * - * Returns the locator of user-defined functions. - *

    - * The default instance extends the built-in functions with the Excel Analysis Tool Pack. - * To set / evaluate custom functions you need to register them as follows: - * - * - * - *

    - * @return wrapped instance of UDFFinder that allows seeking functions both by index and name - */ - /*package*/ UDFFinder getUDFFinder() { - return _udfFinder; - } - - /** - * Register a new toolpack in this workbook. - * - * @param toopack the toolpack to register - */ - @Override - public void addToolPack(UDFFinder toopack){ - _udfFinder.add(toopack); - } - - /** - * Whether the application shall perform a full recalculation when the workbook is opened. - *

    - * Typically you want to force formula recalculation when you modify cell formulas or values - * of a workbook previously created by Excel. When set to true, this flag will tell Excel - * that it needs to recalculate all formulas in the workbook the next time the file is opened. - *

    - *

    - * Note, that recalculation updates cached formula results and, thus, modifies the workbook. - * Depending on the version, Excel may prompt you with "Do you want to save the changes in filename?" - * on close. - *

    - * - * @param value true if the application will perform a full recalculation of - * workbook values when the workbook is opened - * @since 3.8 - */ - @Override - public void setForceFormulaRecalculation(boolean value){ - CTWorkbook ctWorkbook = getCTWorkbook(); - CTCalcPr calcPr = ctWorkbook.isSetCalcPr() ? ctWorkbook.getCalcPr() : ctWorkbook.addNewCalcPr(); - // when set to 0, will tell Excel that it needs to recalculate all formulas - // in the workbook the next time the file is opened. - calcPr.setCalcId(0); - - if(value && calcPr.getCalcMode() == STCalcMode.MANUAL) { - calcPr.setCalcMode(STCalcMode.AUTO); - } - } - - /** - * Whether Excel will be asked to recalculate all formulas when the workbook is opened. - * - * @since 3.8 - */ - @Override - public boolean getForceFormulaRecalculation(){ - CTWorkbook ctWorkbook = getCTWorkbook(); - CTCalcPr calcPr = ctWorkbook.getCalcPr(); - return calcPr != null && calcPr.getCalcId() != 0; - } - - - - /** - * Add pivotCache to the workbook - */ - @Beta - protected CTPivotCache addPivotCache(String rId) { - CTWorkbook ctWorkbook = getCTWorkbook(); - CTPivotCaches caches; - if (ctWorkbook.isSetPivotCaches()) { - caches = ctWorkbook.getPivotCaches(); - } else { - caches = ctWorkbook.addNewPivotCaches(); - } - CTPivotCache cache = caches.addNewPivotCache(); - - int tableId = getPivotTables().size()+1; - cache.setCacheId(tableId); - cache.setId(rId); - if(pivotCaches == null) { - pivotCaches = new ArrayList(); - } - pivotCaches.add(cache); - return cache; - } - - @Beta - public List getPivotTables() { - return pivotTables; - } - - @Beta - protected void setPivotTables(List pivotTables) { - this.pivotTables = pivotTables; - } - - public XSSFWorkbookType getWorkbookType() { - return isMacroEnabled() ? XSSFWorkbookType.XLSM : XSSFWorkbookType.XLSX; - } - - /** - * Sets whether the workbook will be an .xlsx or .xlsm (macro-enabled) file. - */ - public void setWorkbookType(XSSFWorkbookType type) { - try { - getPackagePart().setContentType(type.getContentType()); - } catch (InvalidFormatException e) { - throw new POIXMLException(e); - } - } - - /** - * Adds a vbaProject.bin file to the workbook. This will change the workbook - * type if necessary. - * - * @throws IOException - */ - public void setVBAProject(InputStream vbaProjectStream) throws IOException { - if (!isMacroEnabled()) { - setWorkbookType(XSSFWorkbookType.XLSM); - } - - PackagePartName ppName; - try { - ppName = PackagingURIHelper.createPartName(XSSFRelation.VBA_MACROS.getDefaultFileName()); - } catch (InvalidFormatException e) { - throw new POIXMLException(e); - } - OPCPackage opc = getPackage(); - OutputStream outputStream; - if (!opc.containPart(ppName)) { - POIXMLDocumentPart relationship = createRelationship(XSSFRelation.VBA_MACROS, XSSFFactory.getInstance()); - outputStream = relationship.getPackagePart().getOutputStream(); - } else { - PackagePart part = opc.getPart(ppName); - outputStream = part.getOutputStream(); - } - try { - IOUtils.copy(vbaProjectStream, outputStream); - } finally { - IOUtils.closeQuietly(outputStream); - } - } - - /** - * Adds a vbaProject.bin file taken from another, given workbook to this one. - * @throws IOException - * @throws InvalidFormatException - */ - public void setVBAProject(XSSFWorkbook macroWorkbook) throws IOException, InvalidFormatException { - if (!macroWorkbook.isMacroEnabled()) { - return; - } - InputStream vbaProjectStream = XSSFRelation.VBA_MACROS.getContents(macroWorkbook.getCorePart()); - if (vbaProjectStream != null) { - setVBAProject(vbaProjectStream); - } - } - - /** - * Returns the spreadsheet version (EXCLE2007) of this workbook - * - * @return EXCEL2007 SpreadsheetVersion enum - * @since 3.14 beta 2 - */ - @Override - public SpreadsheetVersion getSpreadsheetVersion() { - return SpreadsheetVersion.EXCEL2007; - } - - /** - * Returns the data table with the given name (case insensitive). - * - * @param name the data table name (case-insensitive) - * @return The Data table in the workbook named name, or null if no table is named name. - * @since 3.15 beta 2 - */ - public XSSFTable getTable(String name) { - if (name != null && sheets != null) { - for (XSSFSheet sheet : sheets) { - for (XSSFTable tbl : sheet.getTables()) { - if (name.equalsIgnoreCase(tbl.getName())) { - return tbl; - } - } - } - } - return null; - } - - @Override - public int addOlePackage(byte[] oleData, String label, String fileName, String command) - throws IOException { - // find an unused part name - OPCPackage opc = getPackage(); - PackagePartName pnOLE; - int oleId=0; - do { - try { - pnOLE = PackagingURIHelper.createPartName( "/xl/embeddings/oleObject"+(++oleId)+".bin" ); - } catch (InvalidFormatException e) { - throw new IOException("ole object name not recognized", e); - } - } while (opc.containPart(pnOLE)); - - PackagePart pp = opc.createPart( pnOLE, "application/vnd.openxmlformats-officedocument.oleObject" ); - - Ole10Native ole10 = new Ole10Native(label, fileName, command, oleData); - - ByteArrayOutputStream bos = new ByteArrayOutputStream(oleData.length+500); - ole10.writeOut(bos); - - POIFSFileSystem poifs = new POIFSFileSystem(); - DirectoryNode root = poifs.getRoot(); - root.createDocument(Ole10Native.OLE10_NATIVE, new ByteArrayInputStream(bos.toByteArray())); - root.setStorageClsid(ClassID.OLE10_PACKAGE); - - // TODO: generate CombObj stream - - OutputStream os = pp.getOutputStream(); - poifs.writeFilesystem(os); - os.close(); - poifs.close(); - - return oleId; - } - - /** - * Whether a call to {@link XSSFCell#setCellFormula(String)} will validate the formula or not. - * - * @param value true if the application will validate the formula is correct - * @since 3.17 - */ - @Override - public void setCellFormulaValidation(final boolean value) { - this.cellFormulaValidation = value; - } - - /** - * Whether a call to {@link XSSFCell#setCellFormula(String)} will validate the formula or not. - * - * @since 3.17 - */ - @Override - public boolean getCellFormulaValidation() { - return this.cellFormulaValidation; - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFWorkbookType.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFWorkbookType.java deleted file mode 100644 index 917d3d6da..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFWorkbookType.java +++ /dev/null @@ -1,45 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - - -/** - * Represents the two different kinds of XML-based OOXML document. - */ -public enum XSSFWorkbookType { - - XLSX(XSSFRelation.WORKBOOK.getContentType(), "xlsx"), - XLSM(XSSFRelation.MACROS_WORKBOOK.getContentType(), "xlsm"); - - private final String _contentType; - private final String _extension; - - private XSSFWorkbookType(String contentType, String extension) { - _contentType = contentType; - _extension = extension; - } - - public String getContentType() { - return _contentType; - } - - public String getExtension() { - return _extension; - } - -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/charts/AbstractXSSFChartSeries.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/charts/AbstractXSSFChartSeries.java deleted file mode 100644 index 65bcfd774..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/charts/AbstractXSSFChartSeries.java +++ /dev/null @@ -1,79 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.charts; - -import org.apache.poi.ss.usermodel.charts.ChartSeries; -import org.apache.poi.ss.usermodel.charts.TitleType; -import org.apache.poi.ss.util.CellReference; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTSerTx; - -/** - * Base of all XSSF Chart Series - */ -public abstract class AbstractXSSFChartSeries implements ChartSeries { - - private String titleValue; - private CellReference titleRef; - private TitleType titleType; - - public void setTitle(CellReference titleReference) { - titleType = TitleType.CELL_REFERENCE; - titleRef = titleReference; - } - - public void setTitle(String title) { - titleType = TitleType.STRING; - titleValue = title; - } - - public CellReference getTitleCellReference() { - if (TitleType.CELL_REFERENCE.equals(titleType)) { - return titleRef; - } - throw new IllegalStateException("Title type is not CellReference."); - } - - public String getTitleString() { - if (TitleType.STRING.equals(titleType)) { - return titleValue; - } - throw new IllegalStateException("Title type is not String."); - } - - public TitleType getTitleType() { - return titleType; - } - - protected boolean isTitleSet() { - return titleType != null; - } - - protected CTSerTx getCTSerTx() { - CTSerTx tx = CTSerTx.Factory.newInstance(); - switch (titleType) { - case CELL_REFERENCE: - tx.addNewStrRef().setF(titleRef.formatAsString()); - return tx; - case STRING: - tx.setV(titleValue); - return tx; - default: - throw new IllegalStateException("Unkown title type: " + titleType); - } - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/charts/XSSFCategoryAxis.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/charts/XSSFCategoryAxis.java deleted file mode 100644 index 43ac8f6c4..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/charts/XSSFCategoryAxis.java +++ /dev/null @@ -1,106 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.charts; - -import org.apache.poi.ss.usermodel.charts.*; -import org.apache.poi.util.Beta; -import org.apache.poi.xssf.usermodel.XSSFChart; -import org.openxmlformats.schemas.drawingml.x2006.chart.*; - -/** - * Category axis type. - * - * @author Martin Andersson - */ -@Beta -public class XSSFCategoryAxis extends XSSFChartAxis { - - private CTCatAx ctCatAx; - - public XSSFCategoryAxis(XSSFChart chart, long id, AxisPosition pos) { - super(chart); - createAxis(id, pos); - } - - public XSSFCategoryAxis(XSSFChart chart, CTCatAx ctCatAx) { - super(chart); - this.ctCatAx = ctCatAx; - } - - public long getId() { - return ctCatAx.getAxId().getVal(); - } - - protected CTAxPos getCTAxPos() { - return ctCatAx.getAxPos(); - } - - protected CTNumFmt getCTNumFmt() { - if (ctCatAx.isSetNumFmt()) { - return ctCatAx.getNumFmt(); - } - return ctCatAx.addNewNumFmt(); - } - - protected CTScaling getCTScaling() { - return ctCatAx.getScaling(); - } - - protected CTCrosses getCTCrosses() { - return ctCatAx.getCrosses(); - } - - @Override - protected CTBoolean getDelete() { - return ctCatAx.getDelete(); - } - - @Override - protected CTTickMark getMajorCTTickMark() { - return ctCatAx.getMajorTickMark(); - } - - @Override - protected CTTickMark getMinorCTTickMark() { - return ctCatAx.getMinorTickMark(); - } - - public void crossAxis(ChartAxis axis) { - ctCatAx.getCrossAx().setVal(axis.getId()); - } - - private void createAxis(long id, AxisPosition pos) { - ctCatAx = chart.getCTChart().getPlotArea().addNewCatAx(); - ctCatAx.addNewAxId().setVal(id); - ctCatAx.addNewAxPos(); - ctCatAx.addNewScaling(); - ctCatAx.addNewCrosses(); - ctCatAx.addNewCrossAx(); - ctCatAx.addNewTickLblPos().setVal(STTickLblPos.NEXT_TO); - ctCatAx.addNewDelete(); - ctCatAx.addNewMajorTickMark(); - ctCatAx.addNewMinorTickMark(); - - setPosition(pos); - setOrientation(AxisOrientation.MIN_MAX); - setCrosses(AxisCrosses.AUTO_ZERO); - setVisible(true); - setMajorTickMark(AxisTickMark.CROSS); - setMinorTickMark(AxisTickMark.NONE); - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/charts/XSSFChartAxis.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/charts/XSSFChartAxis.java deleted file mode 100644 index 2e89755fc..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/charts/XSSFChartAxis.java +++ /dev/null @@ -1,276 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.charts; - -import org.apache.poi.ss.usermodel.charts.ChartAxis; -import org.apache.poi.ss.usermodel.charts.AxisPosition; -import org.apache.poi.ss.usermodel.charts.AxisOrientation; -import org.apache.poi.ss.usermodel.charts.AxisCrosses; -import org.apache.poi.ss.usermodel.charts.AxisTickMark; -import org.apache.poi.util.Beta; -import org.apache.poi.xssf.usermodel.XSSFChart; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTAxPos; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTBoolean; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTNumFmt; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTCrosses; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTOrientation; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTLogBase; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTScaling; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTTickMark; -import org.openxmlformats.schemas.drawingml.x2006.chart.STOrientation; -import org.openxmlformats.schemas.drawingml.x2006.chart.STAxPos; -import org.openxmlformats.schemas.drawingml.x2006.chart.STCrosses; -import org.openxmlformats.schemas.drawingml.x2006.chart.STTickMark; - -/** - * Base class for all axis types. - * - * @author Roman Kashitsyn - */ -@Beta -public abstract class XSSFChartAxis implements ChartAxis { - - protected XSSFChart chart; - - private static final double MIN_LOG_BASE = 2.0; - private static final double MAX_LOG_BASE = 1000.0; - - protected XSSFChartAxis(XSSFChart chart) { - this.chart = chart; - } - - public AxisPosition getPosition() { - return toAxisPosition(getCTAxPos()); - } - - public void setPosition(AxisPosition position) { - getCTAxPos().setVal(fromAxisPosition(position)); - } - - public void setNumberFormat(String format) { - getCTNumFmt().setFormatCode(format); - getCTNumFmt().setSourceLinked(true); - } - - public String getNumberFormat() { - return getCTNumFmt().getFormatCode(); - } - - public boolean isSetLogBase() { - return getCTScaling().isSetLogBase(); - } - - public void setLogBase(double logBase) { - if (logBase < MIN_LOG_BASE || - MAX_LOG_BASE < logBase) { - throw new IllegalArgumentException("Axis log base must be between 2 and 1000 (inclusive), got: " + logBase); - } - CTScaling scaling = getCTScaling(); - if (scaling.isSetLogBase()) { - scaling.getLogBase().setVal(logBase); - } else { - scaling.addNewLogBase().setVal(logBase); - } - } - - public double getLogBase() { - CTLogBase logBase = getCTScaling().getLogBase(); - if (logBase != null) { - return logBase.getVal(); - } - return 0.0; - } - - public boolean isSetMinimum() { - return getCTScaling().isSetMin(); - } - - public void setMinimum(double min) { - CTScaling scaling = getCTScaling(); - if (scaling.isSetMin()) { - scaling.getMin().setVal(min); - } else { - scaling.addNewMin().setVal(min); - } - } - - public double getMinimum() { - CTScaling scaling = getCTScaling(); - if (scaling.isSetMin()) { - return scaling.getMin().getVal(); - } else { - return 0.0; - } - } - - public boolean isSetMaximum() { - return getCTScaling().isSetMax(); - } - - public void setMaximum(double max) { - CTScaling scaling = getCTScaling(); - if (scaling.isSetMax()) { - scaling.getMax().setVal(max); - } else { - scaling.addNewMax().setVal(max); - } - } - - public double getMaximum() { - CTScaling scaling = getCTScaling(); - if (scaling.isSetMax()) { - return scaling.getMax().getVal(); - } else { - return 0.0; - } - } - - public AxisOrientation getOrientation() { - return toAxisOrientation(getCTScaling().getOrientation()); - } - - public void setOrientation(AxisOrientation orientation) { - CTScaling scaling = getCTScaling(); - STOrientation.Enum stOrientation = fromAxisOrientation(orientation); - if (scaling.isSetOrientation()) { - scaling.getOrientation().setVal(stOrientation); - } else { - getCTScaling().addNewOrientation().setVal(stOrientation); - } - } - - public AxisCrosses getCrosses() { - return toAxisCrosses(getCTCrosses()); - } - - public void setCrosses(AxisCrosses crosses) { - getCTCrosses().setVal(fromAxisCrosses(crosses)); - } - - public boolean isVisible() { - return !getDelete().getVal(); - } - - public void setVisible(boolean value) { - getDelete().setVal(!value); - } - - public AxisTickMark getMajorTickMark() { - return toAxisTickMark(getMajorCTTickMark()); - } - - public void setMajorTickMark(AxisTickMark tickMark) { - getMajorCTTickMark().setVal(fromAxisTickMark(tickMark)); - } - - public AxisTickMark getMinorTickMark() { - return toAxisTickMark(getMinorCTTickMark()); - } - - public void setMinorTickMark(AxisTickMark tickMark) { - getMinorCTTickMark().setVal(fromAxisTickMark(tickMark)); - } - - protected abstract CTAxPos getCTAxPos(); - protected abstract CTNumFmt getCTNumFmt(); - protected abstract CTScaling getCTScaling(); - protected abstract CTCrosses getCTCrosses(); - protected abstract CTBoolean getDelete(); - protected abstract CTTickMark getMajorCTTickMark(); - protected abstract CTTickMark getMinorCTTickMark(); - - private static STOrientation.Enum fromAxisOrientation(AxisOrientation orientation) { - switch (orientation) { - case MIN_MAX: return STOrientation.MIN_MAX; - case MAX_MIN: return STOrientation.MAX_MIN; - default: - throw new IllegalArgumentException(); - } - } - - private static AxisOrientation toAxisOrientation(CTOrientation ctOrientation) { - switch (ctOrientation.getVal().intValue()) { - case STOrientation.INT_MIN_MAX: return AxisOrientation.MIN_MAX; - case STOrientation.INT_MAX_MIN: return AxisOrientation.MAX_MIN; - default: - throw new IllegalArgumentException(); - } - } - - private static STCrosses.Enum fromAxisCrosses(AxisCrosses crosses) { - switch (crosses) { - case AUTO_ZERO: return STCrosses.AUTO_ZERO; - case MIN: return STCrosses.MIN; - case MAX: return STCrosses.MAX; - default: - throw new IllegalArgumentException(); - } - } - - private static AxisCrosses toAxisCrosses(CTCrosses ctCrosses) { - switch (ctCrosses.getVal().intValue()) { - case STCrosses.INT_AUTO_ZERO: return AxisCrosses.AUTO_ZERO; - case STCrosses.INT_MAX: return AxisCrosses.MAX; - case STCrosses.INT_MIN: return AxisCrosses.MIN; - default: - throw new IllegalArgumentException(); - } - } - - private static STAxPos.Enum fromAxisPosition(AxisPosition position) { - switch (position) { - case BOTTOM: return STAxPos.B; - case LEFT: return STAxPos.L; - case RIGHT: return STAxPos.R; - case TOP: return STAxPos.T; - default: - throw new IllegalArgumentException(); - } - } - - private static AxisPosition toAxisPosition(CTAxPos ctAxPos) { - switch (ctAxPos.getVal().intValue()) { - case STAxPos.INT_B: return AxisPosition.BOTTOM; - case STAxPos.INT_L: return AxisPosition.LEFT; - case STAxPos.INT_R: return AxisPosition.RIGHT; - case STAxPos.INT_T: return AxisPosition.TOP; - default: return AxisPosition.BOTTOM; - } - } - - private static STTickMark.Enum fromAxisTickMark(AxisTickMark tickMark) { - switch (tickMark) { - case NONE: return STTickMark.NONE; - case IN: return STTickMark.IN; - case OUT: return STTickMark.OUT; - case CROSS: return STTickMark.CROSS; - default: - throw new IllegalArgumentException("Unknown AxisTickMark: " + tickMark); - } - } - - private static AxisTickMark toAxisTickMark(CTTickMark ctTickMark) { - switch (ctTickMark.getVal().intValue()) { - case STTickMark.INT_NONE: return AxisTickMark.NONE; - case STTickMark.INT_IN: return AxisTickMark.IN; - case STTickMark.INT_OUT: return AxisTickMark.OUT; - case STTickMark.INT_CROSS: return AxisTickMark.CROSS; - default: return AxisTickMark.CROSS; - } - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/charts/XSSFChartDataFactory.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/charts/XSSFChartDataFactory.java deleted file mode 100644 index 8bde83a25..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/charts/XSSFChartDataFactory.java +++ /dev/null @@ -1,59 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.charts; - -import org.apache.poi.ss.usermodel.charts.*; -import org.apache.poi.util.Beta; - -/** - * @author Roman Kashitsyn - */ -@Beta -public class XSSFChartDataFactory implements ChartDataFactory { - - private static XSSFChartDataFactory instance; - - private XSSFChartDataFactory() { - super(); - } - - /** - * @return new scatter charts data instance - */ - public XSSFScatterChartData createScatterChartData() { - return new XSSFScatterChartData(); - } - - /** - * @return new line charts data instance - */ - public XSSFLineChartData createLineChartData() { - return new XSSFLineChartData(); - } - - /** - * @return factory instance - */ - public static XSSFChartDataFactory getInstance() { - if (instance == null) { - instance = new XSSFChartDataFactory(); - } - return instance; - } - -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/charts/XSSFChartLegend.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/charts/XSSFChartLegend.java deleted file mode 100644 index 6d82881a1..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/charts/XSSFChartLegend.java +++ /dev/null @@ -1,131 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.charts; - -import org.apache.poi.util.Beta; -import org.apache.poi.util.Internal; -import org.apache.poi.ss.usermodel.charts.ChartLegend; -import org.apache.poi.ss.usermodel.charts.LegendPosition; -import org.apache.poi.xssf.usermodel.XSSFChart; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTChart; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTLegend; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTLegendPos; -import org.openxmlformats.schemas.drawingml.x2006.chart.STLegendPos; - -/** - * Represents a SpreadsheetML chart legend - * @author Roman Kashitsyn - * @author Martin Andersson - */ -@Beta -public final class XSSFChartLegend implements ChartLegend { - - /** - * Underlaying CTLagend bean - */ - private CTLegend legend; - - /** - * Create a new SpreadsheetML chart legend - */ - public XSSFChartLegend(XSSFChart chart) { - CTChart ctChart = chart.getCTChart(); - this.legend = (ctChart.isSetLegend()) ? - ctChart.getLegend() : - ctChart.addNewLegend(); - - setDefaults(); - } - - /** - * Set sensible default styling. - */ - private void setDefaults() { - if (!legend.isSetOverlay()) { - legend.addNewOverlay(); - } - legend.getOverlay().setVal(false); - } - - /** - * Return the underlying CTLegend bean. - * - * @return the underlying CTLegend bean - */ - @Internal - public CTLegend getCTLegend(){ - return legend; - } - - public void setPosition(LegendPosition position) { - if (!legend.isSetLegendPos()) { - legend.addNewLegendPos(); - } - legend.getLegendPos().setVal(fromLegendPosition(position)); - } - - /* - * According to ECMA-376 default position is RIGHT. - */ - public LegendPosition getPosition() { - if (legend.isSetLegendPos()) { - return toLegendPosition(legend.getLegendPos()); - } else { - return LegendPosition.RIGHT; - } - } - - public XSSFManualLayout getManualLayout() { - if (!legend.isSetLayout()) { - legend.addNewLayout(); - } - return new XSSFManualLayout(legend.getLayout()); - } - - public boolean isOverlay() { - return legend.getOverlay().getVal(); - } - - public void setOverlay(boolean value) { - legend.getOverlay().setVal(value); - } - - private STLegendPos.Enum fromLegendPosition(LegendPosition position) { - switch (position) { - case BOTTOM: return STLegendPos.B; - case LEFT: return STLegendPos.L; - case RIGHT: return STLegendPos.R; - case TOP: return STLegendPos.T; - case TOP_RIGHT: return STLegendPos.TR; - default: - throw new IllegalArgumentException(); - } - } - - private LegendPosition toLegendPosition(CTLegendPos ctLegendPos) { - switch (ctLegendPos.getVal().intValue()) { - case STLegendPos.INT_B: return LegendPosition.BOTTOM; - case STLegendPos.INT_L: return LegendPosition.LEFT; - case STLegendPos.INT_R: return LegendPosition.RIGHT; - case STLegendPos.INT_T: return LegendPosition.TOP; - case STLegendPos.INT_TR: return LegendPosition.TOP_RIGHT; - default: - throw new IllegalArgumentException(); - } - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/charts/XSSFChartUtil.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/charts/XSSFChartUtil.java deleted file mode 100644 index d0a13b41c..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/charts/XSSFChartUtil.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xssf.usermodel.charts; - -import org.apache.poi.ss.usermodel.charts.ChartDataSource; -import org.openxmlformats.schemas.drawingml.x2006.chart.*; - -/** - * Package private class with utility methods. - * - * @author Roman Kashitsyn - */ -class XSSFChartUtil { - - private XSSFChartUtil() {} - - /** - * Builds CTAxDataSource object content from POI ChartDataSource. - * @param ctAxDataSource OOXML data source to build - * @param dataSource POI data source to use - */ - public static void buildAxDataSource(CTAxDataSource ctAxDataSource, ChartDataSource dataSource) { - if (dataSource.isNumeric()) { - if (dataSource.isReference()) { - buildNumRef(ctAxDataSource.addNewNumRef(), dataSource); - } else { - buildNumLit(ctAxDataSource.addNewNumLit(), dataSource); - } - } else { - if (dataSource.isReference()) { - buildStrRef(ctAxDataSource.addNewStrRef(), dataSource); - } else { - buildStrLit(ctAxDataSource.addNewStrLit(), dataSource); - } - } - } - - /** - * Builds CTNumDataSource object content from POI ChartDataSource - * @param ctNumDataSource OOXML data source to build - * @param dataSource POI data source to use - */ - public static void buildNumDataSource(CTNumDataSource ctNumDataSource, - ChartDataSource dataSource) { - if (dataSource.isReference()) { - buildNumRef(ctNumDataSource.addNewNumRef(), dataSource); - } else { - buildNumLit(ctNumDataSource.addNewNumLit(), dataSource); - } - } - - private static void buildNumRef(CTNumRef ctNumRef, ChartDataSource dataSource) { - ctNumRef.setF(dataSource.getFormulaString()); - CTNumData cache = ctNumRef.addNewNumCache(); - fillNumCache(cache, dataSource); - } - - private static void buildNumLit(CTNumData ctNumData, ChartDataSource dataSource) { - fillNumCache(ctNumData, dataSource); - } - - private static void buildStrRef(CTStrRef ctStrRef, ChartDataSource dataSource) { - ctStrRef.setF(dataSource.getFormulaString()); - CTStrData cache = ctStrRef.addNewStrCache(); - fillStringCache(cache, dataSource); - } - - private static void buildStrLit(CTStrData ctStrData, ChartDataSource dataSource) { - fillStringCache(ctStrData, dataSource); - } - - private static void fillStringCache(CTStrData cache, ChartDataSource dataSource) { - int numOfPoints = dataSource.getPointCount(); - cache.addNewPtCount().setVal(numOfPoints); - for (int i = 0; i < numOfPoints; ++i) { - Object value = dataSource.getPointAt(i); - if (value != null) { - CTStrVal ctStrVal = cache.addNewPt(); - ctStrVal.setIdx(i); - ctStrVal.setV(value.toString()); - } - } - - } - - private static void fillNumCache(CTNumData cache, ChartDataSource dataSource) { - int numOfPoints = dataSource.getPointCount(); - cache.addNewPtCount().setVal(numOfPoints); - for (int i = 0; i < numOfPoints; ++i) { - Number value = (Number) dataSource.getPointAt(i); - if (value != null) { - CTNumVal ctNumVal = cache.addNewPt(); - ctNumVal.setIdx(i); - ctNumVal.setV(value.toString()); - } - } - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/charts/XSSFLineChartData.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/charts/XSSFLineChartData.java deleted file mode 100644 index 64c72c250..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/charts/XSSFLineChartData.java +++ /dev/null @@ -1,126 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - ==================================================================== */ - -package org.apache.poi.xssf.usermodel.charts; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.ss.usermodel.Chart; -import org.apache.poi.ss.usermodel.charts.ChartAxis; -import org.apache.poi.ss.usermodel.charts.ChartDataSource; -import org.apache.poi.ss.usermodel.charts.LineChartData; -import org.apache.poi.ss.usermodel.charts.LineChartSeries; -import org.apache.poi.util.Beta; -import org.apache.poi.xssf.usermodel.XSSFChart; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTAxDataSource; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTLineChart; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTLineSer; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTNumDataSource; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTPlotArea; -import org.openxmlformats.schemas.drawingml.x2006.chart.STMarkerStyle; - -/** - * Holds data for a XSSF Line Chart - */ -@Beta -public class XSSFLineChartData implements LineChartData { - - /** - * List of all data series. - */ - private List series; - - public XSSFLineChartData() { - series = new ArrayList(); - } - - static class Series extends AbstractXSSFChartSeries implements LineChartSeries { - private int id; - private int order; - private ChartDataSource categories; - private ChartDataSource values; - - protected Series(int id, int order, - ChartDataSource categories, - ChartDataSource values) { - this.id = id; - this.order = order; - this.categories = categories; - this.values = values; - } - - public ChartDataSource getCategoryAxisData() { - return categories; - } - - public ChartDataSource getValues() { - return values; - } - - protected void addToChart(CTLineChart ctLineChart) { - CTLineSer ctLineSer = ctLineChart.addNewSer(); - ctLineSer.addNewIdx().setVal(id); - ctLineSer.addNewOrder().setVal(order); - - // No marker symbol on the chart line. - ctLineSer.addNewMarker().addNewSymbol().setVal(STMarkerStyle.NONE); - - CTAxDataSource catDS = ctLineSer.addNewCat(); - XSSFChartUtil.buildAxDataSource(catDS, categories); - CTNumDataSource valueDS = ctLineSer.addNewVal(); - XSSFChartUtil.buildNumDataSource(valueDS, values); - - if (isTitleSet()) { - ctLineSer.setTx(getCTSerTx()); - } - } - } - - public LineChartSeries addSeries(ChartDataSource categoryAxisData, ChartDataSource values) { - if (!values.isNumeric()) { - throw new IllegalArgumentException("Value data source must be numeric."); - } - int numOfSeries = series.size(); - Series newSeries = new Series(numOfSeries, numOfSeries, categoryAxisData, values); - series.add(newSeries); - return newSeries; - } - - public List getSeries() { - return series; - } - - public void fillChart(Chart chart, ChartAxis... axis) { - if (!(chart instanceof XSSFChart)) { - throw new IllegalArgumentException("Chart must be instance of XSSFChart"); - } - - XSSFChart xssfChart = (XSSFChart) chart; - CTPlotArea plotArea = xssfChart.getCTChart().getPlotArea(); - CTLineChart lineChart = plotArea.addNewLineChart(); - lineChart.addNewVaryColors().setVal(false); - - for (Series s : series) { - s.addToChart(lineChart); - } - - for (ChartAxis ax : axis) { - lineChart.addNewAxId().setVal(ax.getId()); - } - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/charts/XSSFManualLayout.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/charts/XSSFManualLayout.java deleted file mode 100644 index 76eaa45f9..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/charts/XSSFManualLayout.java +++ /dev/null @@ -1,247 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - ==================================================================== */ - -package org.apache.poi.xssf.usermodel.charts; - -import org.apache.poi.util.Beta; -import org.apache.poi.util.Internal; -import org.apache.poi.ss.usermodel.charts.ManualLayout; -import org.apache.poi.ss.usermodel.charts.LayoutMode; -import org.apache.poi.ss.usermodel.charts.LayoutTarget; -import org.apache.poi.xssf.usermodel.XSSFChart; -import org.openxmlformats.schemas.drawingml.x2006.chart.STLayoutTarget; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTLayout; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTManualLayout; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTPlotArea; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTLayoutMode; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTLayoutTarget; -import org.openxmlformats.schemas.drawingml.x2006.chart.STLayoutMode; - -/** - * Represents a SpreadsheetML manual layout. - * @author Roman Kashitsyn - */ -@Beta -public final class XSSFManualLayout implements ManualLayout { - - /** - * Underlaying CTManualLayout bean. - */ - private CTManualLayout layout; - - private static final LayoutMode defaultLayoutMode = LayoutMode.EDGE; - private static final LayoutTarget defaultLayoutTarget = LayoutTarget.INNER; - - /** - * Create a new SpreadsheetML manual layout. - * @param ctLayout a Spreadsheet ML layout that should be used as base. - */ - public XSSFManualLayout(CTLayout ctLayout) { - initLayout(ctLayout); - } - - /** - * Create a new SpreadsheetML manual layout for chart. - * @param chart a chart to create layout for. - */ - public XSSFManualLayout(XSSFChart chart) { - CTPlotArea ctPlotArea = chart.getCTChart().getPlotArea(); - CTLayout ctLayout = ctPlotArea.isSetLayout() ? - ctPlotArea.getLayout() : ctPlotArea.addNewLayout(); - - initLayout(ctLayout); - } - - /** - * Return the underlying CTManualLayout bean. - * - * @return the underlying CTManualLayout bean. - */ - @Internal public CTManualLayout getCTManualLayout(){ - return layout; - } - - public void setWidthRatio(double ratio) { - if (!layout.isSetW()) { - layout.addNewW(); - } - layout.getW().setVal(ratio); - } - - public double getWidthRatio() { - if (!layout.isSetW()) { - return 0.0; - } - return layout.getW().getVal(); - } - - public void setHeightRatio(double ratio) { - if (!layout.isSetH()) { - layout.addNewH(); - } - layout.getH().setVal(ratio); - } - - public double getHeightRatio() { - if (!layout.isSetH()) { - return 0.0; - } - return layout.getH().getVal(); - } - - public LayoutTarget getTarget() { - if (!layout.isSetLayoutTarget()) { - return defaultLayoutTarget; - } - return toLayoutTarget(layout.getLayoutTarget()); - } - - public void setTarget(LayoutTarget target) { - if (!layout.isSetLayoutTarget()) { - layout.addNewLayoutTarget(); - } - layout.getLayoutTarget().setVal(fromLayoutTarget(target)); - } - - public LayoutMode getXMode() { - if (!layout.isSetXMode()) { - return defaultLayoutMode; - } - return toLayoutMode(layout.getXMode()); - } - - public void setXMode(LayoutMode mode) { - if (!layout.isSetXMode()) { - layout.addNewXMode(); - } - layout.getXMode().setVal(fromLayoutMode(mode)); - } - - public LayoutMode getYMode() { - if (!layout.isSetYMode()) { - return defaultLayoutMode; - } - return toLayoutMode(layout.getYMode()); - } - - public void setYMode(LayoutMode mode) { - if (!layout.isSetYMode()) { - layout.addNewYMode(); - } - layout.getYMode().setVal(fromLayoutMode(mode)); - } - - public double getX() { - if (!layout.isSetX()) { - return 0.0; - } - return layout.getX().getVal(); - } - - public void setX(double x) { - if (!layout.isSetX()) { - layout.addNewX(); - } - layout.getX().setVal(x); - } - - public double getY() { - if (!layout.isSetY()) { - return 0.0; - } - return layout.getY().getVal(); - } - - public void setY(double y) { - if (!layout.isSetY()) { - layout.addNewY(); - } - layout.getY().setVal(y); - } - - public LayoutMode getWidthMode() { - if (!layout.isSetWMode()) { - return defaultLayoutMode; - } - return toLayoutMode(layout.getWMode()); - } - - public void setWidthMode(LayoutMode mode) { - if (!layout.isSetWMode()) { - layout.addNewWMode(); - } - layout.getWMode().setVal(fromLayoutMode(mode)); - } - - public LayoutMode getHeightMode() { - if (!layout.isSetHMode()) { - return defaultLayoutMode; - } - return toLayoutMode(layout.getHMode()); - } - - public void setHeightMode(LayoutMode mode) { - if (!layout.isSetHMode()) { - layout.addNewHMode(); - } - layout.getHMode().setVal(fromLayoutMode(mode)); - } - - private void initLayout(CTLayout ctLayout) { - if (ctLayout.isSetManualLayout()) { - this.layout = ctLayout.getManualLayout(); - } else { - this.layout = ctLayout.addNewManualLayout(); - } - } - - private STLayoutMode.Enum fromLayoutMode(LayoutMode mode) { - switch (mode) { - case EDGE: return STLayoutMode.EDGE; - case FACTOR: return STLayoutMode.FACTOR; - default: - throw new IllegalArgumentException(); - } - } - - private LayoutMode toLayoutMode(CTLayoutMode ctLayoutMode) { - switch (ctLayoutMode.getVal().intValue()) { - case STLayoutMode.INT_EDGE: return LayoutMode.EDGE; - case STLayoutMode.INT_FACTOR: return LayoutMode.FACTOR; - default: - throw new IllegalArgumentException(); - } - } - - private STLayoutTarget.Enum fromLayoutTarget(LayoutTarget target) { - switch (target) { - case INNER: return STLayoutTarget.INNER; - case OUTER: return STLayoutTarget.OUTER; - default: - throw new IllegalArgumentException(); - } - } - - private LayoutTarget toLayoutTarget(CTLayoutTarget ctLayoutTarget) { - switch (ctLayoutTarget.getVal().intValue()) { - case STLayoutTarget.INT_INNER: return LayoutTarget.INNER; - case STLayoutTarget.INT_OUTER: return LayoutTarget.OUTER; - default: - throw new IllegalArgumentException(); - } - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/charts/XSSFScatterChartData.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/charts/XSSFScatterChartData.java deleted file mode 100644 index f31b35503..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/charts/XSSFScatterChartData.java +++ /dev/null @@ -1,144 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - ==================================================================== */ - -package org.apache.poi.xssf.usermodel.charts; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.ss.usermodel.Chart; -import org.apache.poi.ss.usermodel.charts.ChartAxis; -import org.apache.poi.ss.usermodel.charts.ChartDataSource; -import org.apache.poi.ss.usermodel.charts.ScatterChartData; -import org.apache.poi.ss.usermodel.charts.ScatterChartSeries; -import org.apache.poi.util.Beta; -import org.apache.poi.xssf.usermodel.XSSFChart; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTAxDataSource; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTNumDataSource; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTPlotArea; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTScatterChart; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTScatterSer; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTScatterStyle; -import org.openxmlformats.schemas.drawingml.x2006.chart.STScatterStyle; - - -/** - * Represents DrawingML scatter charts. - */ -@Beta -public class XSSFScatterChartData implements ScatterChartData { - - /** - * List of all data series. - */ - private List series; - - public XSSFScatterChartData() { - series = new ArrayList(); - } - - /** - * Package private ScatterChartSerie implementation. - */ - static class Series extends AbstractXSSFChartSeries implements ScatterChartSeries { - private int id; - private int order; - private ChartDataSource xs; - private ChartDataSource ys; - - protected Series(int id, int order, - ChartDataSource xs, - ChartDataSource ys) { - super(); - this.id = id; - this.order = order; - this.xs = xs; - this.ys = ys; - } - - /** - * Returns data source used for X axis values. - * @return data source used for X axis values - */ - public ChartDataSource getXValues() { - return xs; - } - - /** - * Returns data source used for Y axis values. - * @return data source used for Y axis values - */ - public ChartDataSource getYValues() { - return ys; - } - - protected void addToChart(CTScatterChart ctScatterChart) { - CTScatterSer scatterSer = ctScatterChart.addNewSer(); - scatterSer.addNewIdx().setVal(this.id); - scatterSer.addNewOrder().setVal(this.order); - - CTAxDataSource xVal = scatterSer.addNewXVal(); - XSSFChartUtil.buildAxDataSource(xVal, xs); - - CTNumDataSource yVal = scatterSer.addNewYVal(); - XSSFChartUtil.buildNumDataSource(yVal, ys); - - if (isTitleSet()) { - scatterSer.setTx(getCTSerTx()); - } - } - } - - public ScatterChartSeries addSerie(ChartDataSource xs, - ChartDataSource ys) { - if (!ys.isNumeric()) { - throw new IllegalArgumentException("Y axis data source must be numeric."); - } - int numOfSeries = series.size(); - Series newSerie = new Series(numOfSeries, numOfSeries, xs, ys); - series.add(newSerie); - return newSerie; - } - - public void fillChart(Chart chart, ChartAxis... axis) { - if (!(chart instanceof XSSFChart)) { - throw new IllegalArgumentException("Chart must be instance of XSSFChart"); - } - - XSSFChart xssfChart = (XSSFChart) chart; - CTPlotArea plotArea = xssfChart.getCTChart().getPlotArea(); - CTScatterChart scatterChart = plotArea.addNewScatterChart(); - addStyle(scatterChart); - - for (Series s : series) { - s.addToChart(scatterChart); - } - - for (ChartAxis ax : axis) { - scatterChart.addNewAxId().setVal(ax.getId()); - } - } - - public List getSeries() { - return series; - } - - private void addStyle(CTScatterChart ctScatterChart) { - CTScatterStyle scatterStyle = ctScatterChart.addNewScatterStyle(); - scatterStyle.setVal(STScatterStyle.LINE_MARKER); - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/charts/XSSFValueAxis.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/charts/XSSFValueAxis.java deleted file mode 100644 index 7fc0718a9..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/charts/XSSFValueAxis.java +++ /dev/null @@ -1,153 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.charts; - -import org.apache.poi.ss.usermodel.charts.ChartAxis; -import org.apache.poi.ss.usermodel.charts.ValueAxis; -import org.apache.poi.ss.usermodel.charts.AxisPosition; -import org.apache.poi.ss.usermodel.charts.AxisOrientation; -import org.apache.poi.ss.usermodel.charts.AxisCrossBetween; -import org.apache.poi.ss.usermodel.charts.AxisCrosses; -import org.apache.poi.ss.usermodel.charts.AxisTickMark; - -import org.apache.poi.util.Beta; -import org.apache.poi.xssf.usermodel.XSSFChart; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTValAx; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTAxPos; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTBoolean; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTNumFmt; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTCrosses; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTScaling; -import org.openxmlformats.schemas.drawingml.x2006.chart.CTTickMark; -import org.openxmlformats.schemas.drawingml.x2006.chart.STCrossBetween; -import org.openxmlformats.schemas.drawingml.x2006.chart.STTickLblPos; - -/** - * Value axis type. - * - * @author Roman Kashitsyn - */ -@Beta -public class XSSFValueAxis extends XSSFChartAxis implements ValueAxis { - - private CTValAx ctValAx; - - public XSSFValueAxis(XSSFChart chart, long id, AxisPosition pos) { - super(chart); - createAxis(id, pos); - } - - public XSSFValueAxis(XSSFChart chart, CTValAx ctValAx) { - super(chart); - this.ctValAx = ctValAx; - } - - public long getId() { - return ctValAx.getAxId().getVal(); - } - - public void setCrossBetween(AxisCrossBetween crossBetween) { - ctValAx.getCrossBetween().setVal(fromCrossBetween(crossBetween)); - } - - public AxisCrossBetween getCrossBetween() { - return toCrossBetween(ctValAx.getCrossBetween().getVal()); - } - - @Override - protected CTAxPos getCTAxPos() { - return ctValAx.getAxPos(); - } - - @Override - protected CTNumFmt getCTNumFmt() { - if (ctValAx.isSetNumFmt()) { - return ctValAx.getNumFmt(); - } - return ctValAx.addNewNumFmt(); - } - - @Override - protected CTScaling getCTScaling() { - return ctValAx.getScaling(); - } - - @Override - protected CTCrosses getCTCrosses() { - return ctValAx.getCrosses(); - } - - @Override - protected CTBoolean getDelete() { - return ctValAx.getDelete(); - } - - @Override - protected CTTickMark getMajorCTTickMark() { - return ctValAx.getMajorTickMark(); - } - - @Override - protected CTTickMark getMinorCTTickMark() { - return ctValAx.getMinorTickMark(); - } - - public void crossAxis(ChartAxis axis) { - ctValAx.getCrossAx().setVal(axis.getId()); - } - - private void createAxis(long id, AxisPosition pos) { - ctValAx = chart.getCTChart().getPlotArea().addNewValAx(); - ctValAx.addNewAxId().setVal(id); - ctValAx.addNewAxPos(); - ctValAx.addNewScaling(); - ctValAx.addNewCrossBetween(); - ctValAx.addNewCrosses(); - ctValAx.addNewCrossAx(); - ctValAx.addNewTickLblPos().setVal(STTickLblPos.NEXT_TO); - ctValAx.addNewDelete(); - ctValAx.addNewMajorTickMark(); - ctValAx.addNewMinorTickMark(); - - setPosition(pos); - setOrientation(AxisOrientation.MIN_MAX); - setCrossBetween(AxisCrossBetween.MIDPOINT_CATEGORY); - setCrosses(AxisCrosses.AUTO_ZERO); - setVisible(true); - setMajorTickMark(AxisTickMark.CROSS); - setMinorTickMark(AxisTickMark.NONE); - } - - private static STCrossBetween.Enum fromCrossBetween(AxisCrossBetween crossBetween) { - switch (crossBetween) { - case BETWEEN: return STCrossBetween.BETWEEN; - case MIDPOINT_CATEGORY: return STCrossBetween.MID_CAT; - default: - throw new IllegalArgumentException(); - } - } - - private static AxisCrossBetween toCrossBetween(STCrossBetween.Enum ctCrossBetween) { - switch (ctCrossBetween.intValue()) { - case STCrossBetween.INT_BETWEEN: return AxisCrossBetween.BETWEEN; - case STCrossBetween.INT_MID_CAT: return AxisCrossBetween.MIDPOINT_CATEGORY; - default: - throw new IllegalArgumentException(); - } - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/extensions/XSSFCellAlignment.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/extensions/XSSFCellAlignment.java deleted file mode 100644 index 06e5d0bf6..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/extensions/XSSFCellAlignment.java +++ /dev/null @@ -1,183 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel.extensions; - -import org.apache.poi.ss.usermodel.HorizontalAlignment; -import org.apache.poi.ss.usermodel.VerticalAlignment; -import org.apache.poi.util.Internal; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCellAlignment; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STHorizontalAlignment; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STVerticalAlignment; - - -/** - * Cell settings available in the Format/Alignment tab - */ -public class XSSFCellAlignment { - private CTCellAlignment cellAlignement; - - /** - * Creates a Cell Alignment from the supplied XML definition - * - * @param cellAlignment - */ - public XSSFCellAlignment(CTCellAlignment cellAlignment) { - this.cellAlignement = cellAlignment; - } - - /** - * Get the type of vertical alignment for the cell - * - * @return the type of aligment - * @see VerticalAlignment - */ - public VerticalAlignment getVertical() { - STVerticalAlignment.Enum align = cellAlignement.getVertical(); - if (align == null) align = STVerticalAlignment.BOTTOM; - - return VerticalAlignment.values()[align.intValue() - 1]; - } - - /** - * Set the type of vertical alignment for the cell - * - * @param align - the type of alignment - * @see VerticalAlignment - */ - public void setVertical(VerticalAlignment align) { - cellAlignement.setVertical(STVerticalAlignment.Enum.forInt(align.ordinal() + 1)); - } - - /** - * Get the type of horizontal alignment for the cell - * - * @return the type of aligment - * @see HorizontalAlignment - */ - public HorizontalAlignment getHorizontal() { - STHorizontalAlignment.Enum align = cellAlignement.getHorizontal(); - if (align == null) align = STHorizontalAlignment.GENERAL; - - return HorizontalAlignment.values()[align.intValue() - 1]; - } - - /** - * Set the type of horizontal alignment for the cell - * - * @param align - the type of alignment - * @see HorizontalAlignment - */ - public void setHorizontal(HorizontalAlignment align) { - cellAlignement.setHorizontal(STHorizontalAlignment.Enum.forInt(align.ordinal() + 1)); - } - - /** - * Get the number of spaces to indent the text in the cell - * - * @return indent - number of spaces - */ - public long getIndent() { - return cellAlignement.getIndent(); - } - - /** - * Set the number of spaces to indent the text in the cell - * - * @param indent - number of spaces - */ - public void setIndent(long indent) { - cellAlignement.setIndent(indent); - } - - /** - * Get the degree of rotation for the text in the cell - *

    - * Expressed in degrees. Values range from 0 to 180. The first letter of - * the text is considered the center-point of the arc. - *
    - * For 0 - 90, the value represents degrees above horizon. For 91-180 the degrees below the - * horizon is calculated as: - *
    - * [degrees below horizon] = 90 - textRotation. - *

    - * - * @return rotation degrees (between 0 and 180 degrees) - */ - public long getTextRotation() { - return cellAlignement.getTextRotation(); - } - - /** - * Set the degree of rotation for the text in the cell - *

    - * Expressed in degrees. Values range from 0 to 180. The first letter of - * the text is considered the center-point of the arc. - *
    - * For 0 - 90, the value represents degrees above horizon. For 91-180 the degrees below the - * horizon is calculated as: - *
    - * [degrees below horizon] = 90 - textRotation. - *

    - * - * Note: HSSF uses values from -90 to 90 degrees, whereas XSSF - * uses values from 0 to 180 degrees. The implementations of this method will map between these two value-ranges - * accordingly, however the corresponding getter is returning values in the range mandated by the current type - * of Excel file-format that this CellStyle is applied to. - * - * @param rotation - the rotation degrees (between 0 and 180 degrees) - */ - public void setTextRotation(long rotation) { - if(rotation < 0 && rotation >= -90) { - rotation = 90 + ((-1)*rotation); - } - cellAlignement.setTextRotation(rotation); - } - - /** - * Whether the text should be wrapped - * - * @return a boolean value indicating if the text in a cell should be line-wrapped within the cell. - */ - public boolean getWrapText() { - return cellAlignement.getWrapText(); - } - - /** - * Set whether the text should be wrapped - * - * @param wrapped a boolean value indicating if the text in a cell should be line-wrapped within the cell. - */ - public void setWrapText(boolean wrapped) { - cellAlignement.setWrapText(wrapped); - } - - public boolean getShrinkToFit() { - return cellAlignement.getShrinkToFit(); - } - - public void setShrinkToFit(boolean shrink) { - cellAlignement.setShrinkToFit(shrink); - } - - /** - * Access to low-level data - */ - @Internal - public CTCellAlignment getCTCellAlignment() { - return cellAlignement; - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/extensions/XSSFCellBorder.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/extensions/XSSFCellBorder.java deleted file mode 100644 index b100bc210..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/extensions/XSSFCellBorder.java +++ /dev/null @@ -1,185 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel.extensions; - - -import org.apache.poi.ss.usermodel.BorderStyle; -import org.apache.poi.xssf.model.ThemesTable; -import org.apache.poi.xssf.usermodel.XSSFColor; -import org.apache.poi.util.Internal; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTBorder; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTBorderPr; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STBorderStyle; - -/** - * This element contains border formatting information, specifying border definition formats (left, right, top, bottom, diagonal) - * for cells in the workbook. - * Color is optional. - */ -public class XSSFCellBorder { - private ThemesTable _theme; - private CTBorder border; - - /** - * Creates a Cell Border from the supplied XML definition - */ - public XSSFCellBorder(CTBorder border, ThemesTable theme) { - this(border); - this._theme = theme; - } - - /** - * Creates a Cell Border from the supplied XML definition - */ - public XSSFCellBorder(CTBorder border) { - this.border = border; - } - - /** - * Creates a new, empty Cell Border. - * You need to attach this to the Styles Table - */ - public XSSFCellBorder() { - border = CTBorder.Factory.newInstance(); - } - - /** - * Records the Themes Table that is associated with - * the current font, used when looking up theme - * based colours and properties. - */ - public void setThemesTable(ThemesTable themes) { - this._theme = themes; - } - - /** - * The enumeration value indicating the side being used for a cell border. - */ - public static enum BorderSide { - TOP, RIGHT, BOTTOM, LEFT - } - - /** - * Returns the underlying XML bean. - * - * @return CTBorder - */ - @Internal - public CTBorder getCTBorder() { - return border; - } - - /** - * Get the type of border to use for the selected border - * - * @param side - - where to apply the color definition - * @return borderstyle - the type of border to use. default value is NONE if border style is not set. - * @see BorderStyle - */ - public BorderStyle getBorderStyle(BorderSide side) { - CTBorderPr ctBorder = getBorder(side); - STBorderStyle.Enum border = ctBorder == null ? STBorderStyle.NONE : ctBorder.getStyle(); - return BorderStyle.values()[border.intValue() - 1]; - } - - /** - * Set the type of border to use for the selected border - * - * @param side - - where to apply the color definition - * @param style - border style - * @see BorderStyle - */ - public void setBorderStyle(BorderSide side, BorderStyle style) { - getBorder(side, true).setStyle(STBorderStyle.Enum.forInt(style.ordinal() + 1)); - } - - /** - * Get the color to use for the selected border - * - * @param side - where to apply the color definition - * @return color - color to use as XSSFColor. null if color is not set - */ - public XSSFColor getBorderColor(BorderSide side) { - CTBorderPr borderPr = getBorder(side); - - if(borderPr != null && borderPr.isSetColor()) { - XSSFColor clr = new XSSFColor(borderPr.getColor()); - if(_theme != null) { - _theme.inheritFromThemeAsRequired(clr); - } - return clr; - } else { - // No border set - return null; - } - } - - /** - * Set the color to use for the selected border - * - * @param side - where to apply the color definition - * @param color - the color to use - */ - public void setBorderColor(BorderSide side, XSSFColor color) { - CTBorderPr borderPr = getBorder(side, true); - if (color == null) borderPr.unsetColor(); - else - borderPr.setColor(color.getCTColor()); - } - - private CTBorderPr getBorder(BorderSide side) { - return getBorder(side, false); - } - - - private CTBorderPr getBorder(BorderSide side, boolean ensure) { - CTBorderPr borderPr; - switch (side) { - case TOP: - borderPr = border.getTop(); - if (ensure && borderPr == null) borderPr = border.addNewTop(); - break; - case RIGHT: - borderPr = border.getRight(); - if (ensure && borderPr == null) borderPr = border.addNewRight(); - break; - case BOTTOM: - borderPr = border.getBottom(); - if (ensure && borderPr == null) borderPr = border.addNewBottom(); - break; - case LEFT: - borderPr = border.getLeft(); - if (ensure && borderPr == null) borderPr = border.addNewLeft(); - break; - default: - throw new IllegalArgumentException("No suitable side specified for the border"); - } - return borderPr; - } - - - public int hashCode() { - return border.toString().hashCode(); - } - - public boolean equals(Object o) { - if (!(o instanceof XSSFCellBorder)) return false; - - XSSFCellBorder cf = (XSSFCellBorder) o; - return border.toString().equals(cf.getCTBorder().toString()); - } -} \ No newline at end of file diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/extensions/XSSFCellFill.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/extensions/XSSFCellFill.java deleted file mode 100644 index fd6a70ef4..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/extensions/XSSFCellFill.java +++ /dev/null @@ -1,167 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel.extensions; - -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTColor; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTFill; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPatternFill; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STPatternType; -import org.apache.poi.xssf.usermodel.XSSFColor; -import org.apache.poi.util.Internal; - -/** - * This element specifies fill formatting. - * A cell fill consists of a background color, foreground color, and pattern to be applied across the cell. - */ -public final class XSSFCellFill { - - private CTFill _fill; - - /** - * Creates a CellFill from the supplied parts - * - * @param fill - fill - */ - public XSSFCellFill(CTFill fill) { - _fill = fill; - } - - /** - * Creates an empty CellFill - */ - public XSSFCellFill() { - _fill = CTFill.Factory.newInstance(); - } - - /** - * Get the background fill color. - * - * @return fill color, null if color is not set - */ - public XSSFColor getFillBackgroundColor() { - CTPatternFill ptrn = _fill.getPatternFill(); - if (ptrn == null) return null; - - CTColor ctColor = ptrn.getBgColor(); - return ctColor == null ? null : new XSSFColor(ctColor); - } - - /** - * Set the background fill color represented as a indexed color value. - * - * @param index - */ - public void setFillBackgroundColor(int index) { - CTPatternFill ptrn = ensureCTPatternFill(); - CTColor ctColor = ptrn.isSetBgColor() ? ptrn.getBgColor() : ptrn.addNewBgColor(); - ctColor.setIndexed(index); - } - - /** - * Set the background fill color represented as a {@link XSSFColor} value. - * - * @param color - */ - public void setFillBackgroundColor(XSSFColor color) { - CTPatternFill ptrn = ensureCTPatternFill(); - ptrn.setBgColor(color.getCTColor()); - } - - /** - * Get the foreground fill color. - * - * @return XSSFColor - foreground color. null if color is not set - */ - public XSSFColor getFillForegroundColor() { - CTPatternFill ptrn = _fill.getPatternFill(); - if (ptrn == null) return null; - - CTColor ctColor = ptrn.getFgColor(); - return ctColor == null ? null : new XSSFColor(ctColor); - } - - /** - * Set the foreground fill color as a indexed color value - * - * @param index - the color to use - */ - public void setFillForegroundColor(int index) { - CTPatternFill ptrn = ensureCTPatternFill(); - CTColor ctColor = ptrn.isSetFgColor() ? ptrn.getFgColor() : ptrn.addNewFgColor(); - ctColor.setIndexed(index); - } - - /** - * Set the foreground fill color represented as a {@link XSSFColor} value. - * - * @param color - the color to use - */ - public void setFillForegroundColor(XSSFColor color) { - CTPatternFill ptrn = ensureCTPatternFill(); - ptrn.setFgColor(color.getCTColor()); - } - - /** - * get the fill pattern - * - * @return fill pattern type. null if fill pattern is not set - */ - public STPatternType.Enum getPatternType() { - CTPatternFill ptrn = _fill.getPatternFill(); - return ptrn == null ? null : ptrn.getPatternType(); - } - - /** - * set the fill pattern - * - * @param patternType fill pattern to use - */ - public void setPatternType(STPatternType.Enum patternType) { - CTPatternFill ptrn = ensureCTPatternFill(); - ptrn.setPatternType(patternType); - } - - private CTPatternFill ensureCTPatternFill() { - CTPatternFill patternFill = _fill.getPatternFill(); - if (patternFill == null) { - patternFill = _fill.addNewPatternFill(); - } - return patternFill; - } - - /** - * Returns the underlying XML bean. - * - * @return CTFill - */ - @Internal - public CTFill getCTFill() { - return _fill; - } - - - public int hashCode() { - return _fill.toString().hashCode(); - } - - public boolean equals(Object o) { - if (!(o instanceof XSSFCellFill)) return false; - - XSSFCellFill cf = (XSSFCellFill) o; - return _fill.toString().equals(cf.getCTFill().toString()); - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/extensions/XSSFHeaderFooter.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/extensions/XSSFHeaderFooter.java deleted file mode 100644 index 62267f2c7..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/extensions/XSSFHeaderFooter.java +++ /dev/null @@ -1,237 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.extensions; - -import org.apache.poi.ss.usermodel.HeaderFooter; -import org.apache.poi.xssf.usermodel.helpers.HeaderFooterHelper; -import org.apache.poi.util.Internal; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTHeaderFooter; - -/** - * Parent class of all XSSF headers and footers. - * - * For a list of all the different fields that can be placed into a header or - * footer, such as page number, bold, underline etc, see the follow formatting - * syntax - * - * Header/Footer Formatting Syntax - *

    - * There are a number of formatting codes that can be written inline with the - * actual header / footer text, which affect the formatting in the header or - * footer. - *

    - * - * This example shows the text "Center Bold Header" on the first line (center - * section), and the date on the second line (center section). &CCenter - * &"-,Bold"Bold &"-,Regular"Header_x000A_&D - * - * General Rules: There is no required order in which these codes must - * appear. The first occurrence of the following codes turns the formatting ON, - * the second occurrence turns it OFF again: - * - *
    - *
    &L
    - *
    code for "left section" (there are three header / footer locations, - * "left", "center", and "right"). When two or more occurrences of this section - * marker exist, the contents from all markers are concatenated, in the order of - * appearance, and placed into the left section.
    - *
    &P
    - *
    code for "current page #"
    - *
    &N
    - *
    code for "total pages"
    - *
    &font size
    - *
    code for "text font size", where font size is a font size in points.
    - *
    &K
    - *
    code for "text font color" RGB Color is specified as RRGGBB Theme Color - * is specifed as TTSNN where TT is the theme color Id, S is either "+" or "-" - * of the tint/shade value, NN is the tint/shade value.
    - *
    &S
    - *
    code for "text strikethrough" on / off
    - *
    &X
    - *
    code for "text super script" on / off
    - *
    &Y
    - *
    code for "text subscript" on / off
    - *
    &C
    - *
    code for "center section". When two or more occurrences of this section - * marker exist, the contents from all markers are concatenated, in the order of - * appearance, and placed into the center section. SpreadsheetML Reference - * Material - Worksheets 1966
    - *
    &D
    - *
    code for "date"
    - *
    &T
    - *
    code for "time"
    - *
    &G
    - *
    code for "picture as background"
    - *
    &U
    - *
    code for "text single underline"
    - *
    &E
    - *
    code for "double underline"
    - *
    &R
    - *
    code for "right section". When two or more occurrences of this section - * marker exist, the contents from all markers are concatenated, in the order of - * appearance, and placed into the right section.
    - *
    &Z
    - *
    code for "this workbook's file path"
    - *
    &F
    - *
    code for "this workbook's file name"
    - *
    &A
    - *
    code for "sheet tab name"
    - *
    &+
    - *
    code for add to page #.
    - *
    &-
    - *
    code for subtract from page #.
    - *
    &"font name,font type" - code for "text font name" and "text font type", - * where font name and font type are strings specifying the name and type of the - * font, separated by a comma. When a hyphen appears in font name, it means - * "none specified". Both of font name and font type can be localized - * values. - *
    &"-,Bold"
    - *
    code for "bold font style"
    - *
    &B
    - *
    also means "bold font style"
    - *
    &"-,Regular"
    - *
    code for "regular font style"
    - *
    &"-,Italic"
    - *
    code for "italic font style"
    - *
    &I
    - *
    also means "italic font style"
    - *
    &"-,Bold Italic"
    - *
    code for "bold italic font style"
    - *
    &O
    - *
    code for "outline style"
    - *
    &H
    - *
    code for "shadow style"
    - *
    - * - * - */ -public abstract class XSSFHeaderFooter implements HeaderFooter { - private HeaderFooterHelper helper; - private CTHeaderFooter headerFooter; - - private boolean stripFields = false; - - /** - * Create an instance of XSSFHeaderFooter from the supplied XML bean - * - * @param headerFooter - */ - public XSSFHeaderFooter(CTHeaderFooter headerFooter) { - this.headerFooter = headerFooter; - this.helper = new HeaderFooterHelper(); - } - - /** - * Returns the underlying CTHeaderFooter xml bean - * - * @return the underlying CTHeaderFooter xml bean - */ - @Internal - public CTHeaderFooter getHeaderFooter() { - return this.headerFooter; - } - - public String getValue() { - String value = getText(); - if (value == null) - return ""; - return value; - } - - /** - * Are fields currently being stripped from the text that this - * {@link XSSFHeaderFooter} returns? Default is false, but can be changed - */ - public boolean areFieldsStripped() { - return stripFields; - } - - /** - * Should fields (eg macros) be stripped from the text that this class - * returns? Default is not to strip. - * - * @param stripFields - */ - public void setAreFieldsStripped(boolean stripFields) { - this.stripFields = stripFields; - } - - /** - * Removes any fields (eg macros, page markers etc) from the string. - * Normally used to make some text suitable for showing to humans, and the - * resultant text should not normally be saved back into the document! - */ - public static String stripFields(String text) { - return org.apache.poi.hssf.usermodel.HeaderFooter.stripFields(text); - } - - public abstract String getText(); - - protected abstract void setText(String text); - - /** - * get the text representing the center part of this element - */ - public String getCenter() { - String text = helper.getCenterSection(getText()); - if (stripFields) - return stripFields(text); - return text; - } - - /** - * get the text representing the left part of this element - */ - public String getLeft() { - String text = helper.getLeftSection(getText()); - if (stripFields) - return stripFields(text); - return text; - } - - /** - * get the text representing the right part of this element - */ - public String getRight() { - String text = helper.getRightSection(getText()); - if (stripFields) - return stripFields(text); - return text; - } - - /** - * set a centered string value for this element - */ - public void setCenter(String newCenter) { - setText(helper.setCenterSection(getText(), newCenter)); - } - - /** - * set a left string value for this element - */ - public void setLeft(String newLeft) { - setText(helper.setLeftSection(getText(), newLeft)); - } - - /** - * set a right string value for this element - */ - public void setRight(String newRight) { - setText(helper.setRightSection(getText(), newRight)); - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/helpers/ColumnHelper.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/helpers/ColumnHelper.java deleted file mode 100644 index b27100656..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/helpers/ColumnHelper.java +++ /dev/null @@ -1,332 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.helpers; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.NavigableSet; -import java.util.TreeSet; - -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.xssf.util.CTColComparator; -import org.apache.poi.xssf.util.NumericRanges; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCol; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCols; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet; - -/** - * Helper class for dealing with the Column settings on - * a CTWorksheet (the data part of a sheet). - * Note - within POI, we use 0 based column indexes, but - * the column definitions in the XML are 1 based! - */ -public class ColumnHelper { - - private CTWorksheet worksheet; - - public ColumnHelper(CTWorksheet worksheet) { - super(); - this.worksheet = worksheet; - cleanColumns(); - } - - public void cleanColumns() { - TreeSet trackedCols = new TreeSet(CTColComparator.BY_MIN_MAX); - CTCols newCols = CTCols.Factory.newInstance(); - CTCols[] colsArray = worksheet.getColsArray(); - int i = 0; - for (i = 0; i < colsArray.length; i++) { - CTCols cols = colsArray[i]; - CTCol[] colArray = cols.getColArray(); - for (CTCol col : colArray) { - addCleanColIntoCols(newCols, col, trackedCols); - } - } - for (int y = i - 1; y >= 0; y--) { - worksheet.removeCols(y); - } - - newCols.setColArray(trackedCols.toArray(new CTCol[trackedCols.size()])); - worksheet.addNewCols(); - worksheet.setColsArray(0, newCols); - } - - public CTCols addCleanColIntoCols(CTCols cols, CTCol newCol) { - // Performance issue. If we encapsulated management of min/max in this - // class then we could keep trackedCols as state, - // making this log(N) rather than Nlog(N). We do this for the initial - // read above. - TreeSet trackedCols = new TreeSet( - CTColComparator.BY_MIN_MAX); - trackedCols.addAll(cols.getColList()); - addCleanColIntoCols(cols, newCol, trackedCols); - cols.setColArray(trackedCols.toArray(new CTCol[0])); - return cols; - } - - private void addCleanColIntoCols(final CTCols cols, final CTCol newCol, final TreeSet trackedCols) { - List overlapping = getOverlappingCols(newCol, trackedCols); - if (overlapping.isEmpty()) { - trackedCols.add(cloneCol(cols, newCol)); - return; - } - - trackedCols.removeAll(overlapping); - for (CTCol existing : overlapping) { - // We add up to three columns for each existing one: non-overlap - // before, overlap, non-overlap after. - long[] overlap = getOverlap(newCol, existing); - - CTCol overlapCol = cloneCol(cols, existing, overlap); - setColumnAttributes(newCol, overlapCol); - trackedCols.add(overlapCol); - - CTCol beforeCol = existing.getMin() < newCol.getMin() ? existing - : newCol; - long[] before = new long[] { - Math.min(existing.getMin(), newCol.getMin()), - overlap[0] - 1 }; - if (before[0] <= before[1]) { - trackedCols.add(cloneCol(cols, beforeCol, before)); - } - - CTCol afterCol = existing.getMax() > newCol.getMax() ? existing - : newCol; - long[] after = new long[] { overlap[1] + 1, - Math.max(existing.getMax(), newCol.getMax()) }; - if (after[0] <= after[1]) { - trackedCols.add(cloneCol(cols, afterCol, after)); - } - } - } - - private CTCol cloneCol(final CTCols cols, final CTCol col, final long[] newRange) { - CTCol cloneCol = cloneCol(cols, col); - cloneCol.setMin(newRange[0]); - cloneCol.setMax(newRange[1]); - return cloneCol; - } - - private long[] getOverlap(final CTCol col1, final CTCol col2) { - return getOverlappingRange(col1, col2); - } - - private List getOverlappingCols(final CTCol newCol, final TreeSet trackedCols) { - CTCol lower = trackedCols.lower(newCol); - NavigableSet potentiallyOverlapping = lower == null ? trackedCols : trackedCols.tailSet(lower, overlaps(lower, newCol)); - List overlapping = new ArrayList(); - for (CTCol existing : potentiallyOverlapping) { - if (overlaps(newCol, existing)) { - overlapping.add(existing); - } else { - break; - } - } - return overlapping; - } - - private boolean overlaps(final CTCol col1, final CTCol col2) { - return NumericRanges.getOverlappingType(toRange(col1), toRange(col2)) != NumericRanges.NO_OVERLAPS; - } - - private long[] getOverlappingRange(final CTCol col1, final CTCol col2) { - return NumericRanges.getOverlappingRange(toRange(col1), toRange(col2)); - } - - private long[] toRange(final CTCol col) { - return new long[] { col.getMin(), col.getMax() }; - } - - public static void sortColumns(CTCols newCols) { - CTCol[] colArray = newCols.getColArray(); - Arrays.sort(colArray, CTColComparator.BY_MIN_MAX); - newCols.setColArray(colArray); - } - - public CTCol cloneCol(CTCols cols, CTCol col) { - CTCol newCol = cols.addNewCol(); - newCol.setMin(col.getMin()); - newCol.setMax(col.getMax()); - setColumnAttributes(col, newCol); - return newCol; - } - - /** - * Returns the Column at the given 0 based index - */ - public CTCol getColumn(long index, boolean splitColumns) { - return getColumn1Based(index+1, splitColumns); - } - - /** - * Returns the Column at the given 1 based index. - * POI default is 0 based, but the file stores - * as 1 based. - */ - public CTCol getColumn1Based(long index1, boolean splitColumns) { - CTCols cols = worksheet.getColsArray(0); - - // Fetching the array is quicker than working on the new style - // list, assuming we need to read many of them (which we often do), - // and assuming we're not making many changes (which we're not) - CTCol[] colArray = cols.getColArray(); - - for (CTCol col : colArray) { - long colMin = col.getMin(); - long colMax = col.getMax(); - if (colMin <= index1 && colMax >= index1) { - if (splitColumns) { - if (colMin < index1) { - insertCol(cols, colMin, (index1 - 1), new CTCol[]{col}); - } - if (colMax > index1) { - insertCol(cols, (index1 + 1), colMax, new CTCol[]{col}); - } - col.setMin(index1); - col.setMax(index1); - } - return col; - } - } - return null; - } - - /* - * Insert a new CTCol at position 0 into cols, setting min=min, max=max and - * copying all the colsWithAttributes array cols attributes into newCol - */ - private CTCol insertCol(CTCols cols, long min, long max, CTCol[] colsWithAttributes) { - return insertCol(cols, min, max, colsWithAttributes, false, null); - } - - private CTCol insertCol(CTCols cols, long min, long max, - CTCol[] colsWithAttributes, boolean ignoreExistsCheck, CTCol overrideColumn) { - if(ignoreExistsCheck || !columnExists(cols,min,max)){ - CTCol newCol = cols.insertNewCol(0); - newCol.setMin(min); - newCol.setMax(max); - for (CTCol col : colsWithAttributes) { - setColumnAttributes(col, newCol); - } - if (overrideColumn != null) setColumnAttributes(overrideColumn, newCol); - return newCol; - } - return null; - } - - /** - * Does the column at the given 0 based index exist - * in the supplied list of column definitions? - */ - public boolean columnExists(CTCols cols, long index) { - return columnExists1Based(cols, index+1); - } - - private boolean columnExists1Based(CTCols cols, long index1) { - for (CTCol col : cols.getColArray()) { - if (col.getMin() == index1) { - return true; - } - } - return false; - } - - public void setColumnAttributes(CTCol fromCol, CTCol toCol) { - if(fromCol.isSetBestFit()) toCol.setBestFit(fromCol.getBestFit()); - if(fromCol.isSetCustomWidth()) toCol.setCustomWidth(fromCol.getCustomWidth()); - if(fromCol.isSetHidden()) toCol.setHidden(fromCol.getHidden()); - if(fromCol.isSetStyle()) toCol.setStyle(fromCol.getStyle()); - if(fromCol.isSetWidth()) toCol.setWidth(fromCol.getWidth()); - if(fromCol.isSetCollapsed()) toCol.setCollapsed(fromCol.getCollapsed()); - if(fromCol.isSetPhonetic()) toCol.setPhonetic(fromCol.getPhonetic()); - if(fromCol.isSetOutlineLevel()) toCol.setOutlineLevel(fromCol.getOutlineLevel()); - toCol.setCollapsed(fromCol.isSetCollapsed()); - } - - public void setColBestFit(long index, boolean bestFit) { - CTCol col = getOrCreateColumn1Based(index+1, false); - col.setBestFit(bestFit); - } - public void setCustomWidth(long index, boolean bestFit) { - CTCol col = getOrCreateColumn1Based(index+1, true); - col.setCustomWidth(bestFit); - } - - public void setColWidth(long index, double width) { - CTCol col = getOrCreateColumn1Based(index+1, true); - col.setWidth(width); - } - - public void setColHidden(long index, boolean hidden) { - CTCol col = getOrCreateColumn1Based(index+1, true); - col.setHidden(hidden); - } - - /** - * Return the CTCol at the given (0 based) column index, - * creating it if required. - */ - protected CTCol getOrCreateColumn1Based(long index1, boolean splitColumns) { - CTCol col = getColumn1Based(index1, splitColumns); - if (col == null) { - col = worksheet.getColsArray(0).addNewCol(); - col.setMin(index1); - col.setMax(index1); - } - return col; - } - - public void setColDefaultStyle(long index, CellStyle style) { - setColDefaultStyle(index, style.getIndex()); - } - - public void setColDefaultStyle(long index, int styleId) { - CTCol col = getOrCreateColumn1Based(index+1, true); - col.setStyle(styleId); - } - - // Returns -1 if no column is found for the given index - public int getColDefaultStyle(long index) { - if (getColumn(index, false) != null) { - return (int) getColumn(index, false).getStyle(); - } - return -1; - } - - private boolean columnExists(CTCols cols, long min, long max) { - for (CTCol col : cols.getColArray()) { - if (col.getMin() == min && col.getMax() == max) { - return true; - } - } - return false; - } - - public int getIndexOfColumn(CTCols cols, CTCol searchCol) { - if (cols == null || searchCol == null) return -1; - int i = 0; - for (CTCol col : cols.getColArray()) { - if (col.getMin() == searchCol.getMin() && col.getMax() == searchCol.getMax()) { - return i; - } - i++; - } - return -1; - } -} \ No newline at end of file diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/helpers/HeaderFooterHelper.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/helpers/HeaderFooterHelper.java deleted file mode 100644 index 41e3ea462..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/helpers/HeaderFooterHelper.java +++ /dev/null @@ -1,119 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.helpers; - - -public class HeaderFooterHelper { - // Note - XmlBeans handles entity encoding for us, - // so these should be & forms, not the & ones! - private static final String HeaderFooterEntity_L = "&L"; - private static final String HeaderFooterEntity_C = "&C"; - private static final String HeaderFooterEntity_R = "&R"; - - // These are other entities that may be used in the - // left, center or right. Not exhaustive - public static final String HeaderFooterEntity_File = "&F"; - public static final String HeaderFooterEntity_Date = "&D"; - public static final String HeaderFooterEntity_Time = "&T"; - - public String getLeftSection(String string) { - return getParts(string)[0]; - } - public String getCenterSection(String string) { - return getParts(string)[1]; - } - public String getRightSection(String string) { - return getParts(string)[2]; - } - - public String setLeftSection(String string, String newLeft) { - String[] parts = getParts(string); - parts[0] = newLeft; - return joinParts(parts); - } - public String setCenterSection(String string, String newCenter) { - String[] parts = getParts(string); - parts[1] = newCenter; - return joinParts(parts); - } - public String setRightSection(String string, String newRight) { - String[] parts = getParts(string); - parts[2] = newRight; - return joinParts(parts); - } - - /** - * Split into left, center, right - */ - private String[] getParts(String string) { - String[] parts = new String[] { "", "", "" }; - if(string == null) - return parts; - - // They can come in any order, which is just nasty - // Work backwards from the end, picking the last - // on off each time as we go - int lAt = 0; - int cAt = 0; - int rAt = 0; - - while( - // Ensure all indicies get updated, then -1 tested - (lAt = string.indexOf(HeaderFooterEntity_L)) > -2 && - (cAt = string.indexOf(HeaderFooterEntity_C)) > -2 && - (rAt = string.indexOf(HeaderFooterEntity_R)) > -2 && - (lAt > -1 || cAt > -1 || rAt > -1) - ) { - // Pick off the last one - if(rAt > cAt && rAt > lAt) { - parts[2] = string.substring(rAt + HeaderFooterEntity_R.length()); - string = string.substring(0, rAt); - } else if(cAt > rAt && cAt > lAt) { - parts[1] = string.substring(cAt + HeaderFooterEntity_C.length()); - string = string.substring(0, cAt); - } else { - parts[0] = string.substring(lAt + HeaderFooterEntity_L.length()); - string = string.substring(0, lAt); - } - } - - return parts; - } - private String joinParts(String[] parts) { - return joinParts(parts[0], parts[1], parts[2]); - } - private String joinParts(String l, String c, String r) { - StringBuffer ret = new StringBuffer(); - - // Join as c, l, r - if(c.length() > 0) { - ret.append(HeaderFooterEntity_C); - ret.append(c); - } - if(l.length() > 0) { - ret.append(HeaderFooterEntity_L); - ret.append(l); - } - if(r.length() > 0) { - ret.append(HeaderFooterEntity_R); - ret.append(r); - } - - return ret.toString(); - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/helpers/XSSFFormulaUtils.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/helpers/XSSFFormulaUtils.java deleted file mode 100644 index ef0c5ea63..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/helpers/XSSFFormulaUtils.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xssf.usermodel.helpers; - -import org.apache.poi.ss.formula.FormulaParser; -import org.apache.poi.ss.formula.FormulaRenderer; -import org.apache.poi.ss.formula.FormulaType; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.apache.poi.ss.formula.ptg.Pxg; -import org.apache.poi.ss.formula.ptg.Pxg3D; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.xssf.usermodel.XSSFCell; -import org.apache.poi.xssf.usermodel.XSSFEvaluationWorkbook; -import org.apache.poi.xssf.usermodel.XSSFName; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCellFormula; - -/** - * Utility to update formulas and named ranges when a sheet name was changed - * - * @author Yegor Kozlov - */ -public final class XSSFFormulaUtils { - private final XSSFWorkbook _wb; - private final XSSFEvaluationWorkbook _fpwb; - - public XSSFFormulaUtils(XSSFWorkbook wb) { - _wb = wb; - _fpwb = XSSFEvaluationWorkbook.create(_wb); - } - - /** - * Update sheet name in all formulas and named ranges. - * Called from {@link XSSFWorkbook#setSheetName(int, String)} - *

    - *

    - * The idea is to parse every formula and render it back to string - * with the updated sheet name. This is done by parsing into Ptgs, - * looking for ones with sheet references in them, and changing those - *

    - * - * @param sheetIndex the 0-based index of the sheet being changed - * @param oldName the old sheet name - * @param newName the new sheet name - */ - public void updateSheetName(final int sheetIndex, final String oldName, final String newName) { - // update named ranges - for (XSSFName nm : _wb.getAllNames()) { - if (nm.getSheetIndex() == -1 || nm.getSheetIndex() == sheetIndex) { - updateName(nm, oldName, newName); - } - } - - // update formulas - for (Sheet sh : _wb) { - for (Row row : sh) { - for (Cell cell : row) { - if (cell.getCellTypeEnum() == CellType.FORMULA) { - updateFormula((XSSFCell) cell, oldName, newName); - } - } - } - } - } - - /** - * Parse cell formula and re-assemble it back using the new sheet name - * - * @param cell the cell to update - */ - private void updateFormula(XSSFCell cell, String oldName, String newName) { - CTCellFormula f = cell.getCTCell().getF(); - if (f != null) { - String formula = f.getStringValue(); - if (formula != null && formula.length() > 0) { - int sheetIndex = _wb.getSheetIndex(cell.getSheet()); - Ptg[] ptgs = FormulaParser.parse(formula, _fpwb, FormulaType.CELL, sheetIndex, cell.getRowIndex()); - for (Ptg ptg : ptgs) { - updatePtg(ptg, oldName, newName); - } - String updatedFormula = FormulaRenderer.toFormulaString(_fpwb, ptgs); - if (!formula.equals(updatedFormula)) f.setStringValue(updatedFormula); - } - } - } - - /** - * Parse formula in the named range and re-assemble it back using the new sheet name. - * - * @param name the name to update - */ - private void updateName(XSSFName name, String oldName, String newName) { - String formula = name.getRefersToFormula(); - if (formula != null) { - int sheetIndex = name.getSheetIndex(); - int rowIndex = -1; //don't care - Ptg[] ptgs = FormulaParser.parse(formula, _fpwb, FormulaType.NAMEDRANGE, sheetIndex, rowIndex); - for (Ptg ptg : ptgs) { - updatePtg(ptg, oldName, newName); - } - String updatedFormula = FormulaRenderer.toFormulaString(_fpwb, ptgs); - if (!formula.equals(updatedFormula)) name.setRefersToFormula(updatedFormula); - } - } - - private void updatePtg(Ptg ptg, String oldName, String newName) { - if (ptg instanceof Pxg) { - Pxg pxg = (Pxg)ptg; - if (pxg.getExternalWorkbookNumber() < 1) { - if (pxg.getSheetName() != null && - pxg.getSheetName().equals(oldName)) { - pxg.setSheetName(newName); - } - if (pxg instanceof Pxg3D) { - Pxg3D pxg3D = (Pxg3D)pxg; - if (pxg3D.getLastSheetName() != null && - pxg3D.getLastSheetName().equals(oldName)) { - pxg3D.setLastSheetName(newName); - } - } - } - } - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/helpers/XSSFIgnoredErrorHelper.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/helpers/XSSFIgnoredErrorHelper.java deleted file mode 100644 index d0dc0b760..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/helpers/XSSFIgnoredErrorHelper.java +++ /dev/null @@ -1,106 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.helpers; - -import java.util.Arrays; -import java.util.LinkedHashSet; -import java.util.Set; - -import org.apache.poi.ss.usermodel.IgnoredErrorType; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTIgnoredError; - -/** - * XSSF-specific code for working with ignored errors - */ -public class XSSFIgnoredErrorHelper { - public static boolean isSet(IgnoredErrorType errorType, CTIgnoredError error) { - switch(errorType) { - case CALCULATED_COLUMN: - return error.isSetCalculatedColumn(); - case EMPTY_CELL_REFERENCE: - return error.isSetEmptyCellReference(); - case EVALUATION_ERROR: - return error.isSetEvalError(); - case FORMULA: - return error.isSetFormula(); - case FORMULA_RANGE: - return error.isSetFormulaRange(); - case LIST_DATA_VALIDATION: - return error.isSetListDataValidation(); - case NUMBER_STORED_AS_TEXT: - return error.isSetNumberStoredAsText(); - case TWO_DIGIT_TEXT_YEAR: - return error.isSetTwoDigitTextYear(); - case UNLOCKED_FORMULA: - return error.isSetUnlockedFormula(); - default: - throw new IllegalStateException(); - } - } - - public static void set(IgnoredErrorType errorType, CTIgnoredError error) { - switch(errorType) { - case CALCULATED_COLUMN: - error.setCalculatedColumn(true); - break; - case EMPTY_CELL_REFERENCE: - error.setEmptyCellReference(true); - break; - case EVALUATION_ERROR: - error.setEvalError(true); - break; - case FORMULA: - error.setFormula(true); - break; - case FORMULA_RANGE: - error.setFormulaRange(true); - break; - case LIST_DATA_VALIDATION: - error.setListDataValidation(true); - break; - case NUMBER_STORED_AS_TEXT: - error.setNumberStoredAsText(true); - break; - case TWO_DIGIT_TEXT_YEAR: - error.setTwoDigitTextYear(true); - break; - case UNLOCKED_FORMULA: - error.setUnlockedFormula(true); - break; - default: - throw new IllegalStateException(); - } - } - - public static void addIgnoredErrors(CTIgnoredError err, String ref, IgnoredErrorType... ignoredErrorTypes) { - err.setSqref(Arrays.asList(ref)); - for (IgnoredErrorType errType : ignoredErrorTypes) { - XSSFIgnoredErrorHelper.set(errType, err); - } - } - - public static Set getErrorTypes(CTIgnoredError err) { - Set result = new LinkedHashSet(); - for (IgnoredErrorType errType : IgnoredErrorType.values()) { - if (XSSFIgnoredErrorHelper.isSet(errType, err)) { - result.add(errType); - } - } - return result; - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/helpers/XSSFPasswordHelper.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/helpers/XSSFPasswordHelper.java deleted file mode 100644 index 46e47f688..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/helpers/XSSFPasswordHelper.java +++ /dev/null @@ -1,136 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xssf.usermodel.helpers; - -import java.security.SecureRandom; -import java.util.Arrays; -import java.util.Locale; - -import javax.xml.bind.DatatypeConverter; -import javax.xml.namespace.QName; - -import org.apache.poi.poifs.crypt.CryptoFunctions; -import org.apache.poi.poifs.crypt.HashAlgorithm; -import org.apache.poi.util.Internal; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlObject; - -@Internal(since="3.15 beta 3") -public final class XSSFPasswordHelper { - private XSSFPasswordHelper() { - // no instances of this static class - } - - /** - * Sets the XORed or hashed password - * - * @param xobj the xmlbeans object which contains the password attributes - * @param password the password, if null, the password attributes will be removed - * @param hashAlgo the hash algorithm, if null the password will be XORed - * @param prefix the prefix of the password attributes, may be null - */ - public static void setPassword(XmlObject xobj, String password, HashAlgorithm hashAlgo, String prefix) { - XmlCursor cur = xobj.newCursor(); - - if (password == null) { - cur.removeAttribute(getAttrName(prefix, "password")); - cur.removeAttribute(getAttrName(prefix, "algorithmName")); - cur.removeAttribute(getAttrName(prefix, "hashValue")); - cur.removeAttribute(getAttrName(prefix, "saltValue")); - cur.removeAttribute(getAttrName(prefix, "spinCount")); - return; - } - - cur.toFirstContentToken(); - if (hashAlgo == null) { - int hash = CryptoFunctions.createXorVerifier1(password); - cur.insertAttributeWithValue(getAttrName(prefix, "password"), - String.format(Locale.ROOT, "%04X", hash).toUpperCase(Locale.ROOT)); - } else { - SecureRandom random = new SecureRandom(); - byte salt[] = random.generateSeed(16); - - // Iterations specifies the number of times the hashing function shall be iteratively run (using each - // iteration's result as the input for the next iteration). - int spinCount = 100000; - - // Implementation Notes List: - // --> In this third stage, the reversed byte order legacy hash from the second stage shall - // be converted to Unicode hex string representation - byte hash[] = CryptoFunctions.hashPassword(password, hashAlgo, salt, spinCount, false); - - cur.insertAttributeWithValue(getAttrName(prefix, "algorithmName"), hashAlgo.jceId); - cur.insertAttributeWithValue(getAttrName(prefix, "hashValue"), DatatypeConverter.printBase64Binary(hash)); - cur.insertAttributeWithValue(getAttrName(prefix, "saltValue"), DatatypeConverter.printBase64Binary(salt)); - cur.insertAttributeWithValue(getAttrName(prefix, "spinCount"), ""+spinCount); - } - cur.dispose(); - } - - /** - * Validates the password, i.e. - * calculates the hash of the given password and compares it against the stored hash - * - * @param xobj the xmlbeans object which contains the password attributes - * @param password the password, if null the method will always return false, - * even if there's no password set - * @param prefix the prefix of the password attributes, may be null - * - * @return true, if the hashes match - */ - public static boolean validatePassword(XmlObject xobj, String password, String prefix) { - // TODO: is "velvetSweatshop" the default password? - if (password == null) return false; - - XmlCursor cur = xobj.newCursor(); - String xorHashVal = cur.getAttributeText(getAttrName(prefix, "password")); - String algoName = cur.getAttributeText(getAttrName(prefix, "algorithmName")); - String hashVal = cur.getAttributeText(getAttrName(prefix, "hashValue")); - String saltVal = cur.getAttributeText(getAttrName(prefix, "saltValue")); - String spinCount = cur.getAttributeText(getAttrName(prefix, "spinCount")); - cur.dispose(); - - if (xorHashVal != null) { - int hash1 = Integer.parseInt(xorHashVal, 16); - int hash2 = CryptoFunctions.createXorVerifier1(password); - return hash1 == hash2; - } else { - if (hashVal == null || algoName == null || saltVal == null || spinCount == null) { - return false; - } - - byte hash1[] = DatatypeConverter.parseBase64Binary(hashVal); - HashAlgorithm hashAlgo = HashAlgorithm.fromString(algoName); - byte salt[] = DatatypeConverter.parseBase64Binary(saltVal); - int spinCnt = Integer.parseInt(spinCount); - byte hash2[] = CryptoFunctions.hashPassword(password, hashAlgo, salt, spinCnt, false); - return Arrays.equals(hash1, hash2); - } - } - - - private static QName getAttrName(String prefix, String name) { - if (prefix == null || "".equals(prefix)) { - return new QName(name); - } else { - return new QName(prefix+Character.toUpperCase(name.charAt(0))+name.substring(1)); - } - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/helpers/XSSFPaswordHelper.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/helpers/XSSFPaswordHelper.java deleted file mode 100644 index 4e3c90819..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/helpers/XSSFPaswordHelper.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xssf.usermodel.helpers; - -import org.apache.poi.poifs.crypt.HashAlgorithm; -import org.apache.poi.util.Internal; -import org.apache.poi.util.Removal; -import org.apache.xmlbeans.XmlObject; - -/** - * @deprecated POI 3.15 beta 3. Use {@link XSSFPasswordHelper} instead. - */ -@Internal(since="3.15 beta 3") -@Deprecated -@Removal(version="3.17") -public class XSSFPaswordHelper { - /** - * Sets the XORed or hashed password - * - * @param xobj the xmlbeans object which contains the password attributes - * @param password the password, if null, the password attributes will be removed - * @param hashAlgo the hash algorithm, if null the password will be XORed - * @param prefix the prefix of the password attributes, may be null - */ - public static void setPassword(XmlObject xobj, String password, HashAlgorithm hashAlgo, String prefix) { - XSSFPasswordHelper.setPassword(xobj, password, hashAlgo, prefix); - } - - /** - * Validates the password, i.e. - * calculates the hash of the given password and compares it against the stored hash - * - * @param xobj the xmlbeans object which contains the password attributes - * @param password the password, if null the method will always return false, - * even if there's no password set - * @param prefix the prefix of the password attributes, may be null - * - * @return true, if the hashes match - */ - public static boolean validatePassword(XmlObject xobj, String password, String prefix) { - return XSSFPasswordHelper.validatePassword(xobj, password, prefix); - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/helpers/XSSFRowShifter.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/helpers/XSSFRowShifter.java deleted file mode 100644 index 46f0b892c..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/helpers/XSSFRowShifter.java +++ /dev/null @@ -1,300 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.helpers; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.ss.formula.FormulaParseException; -import org.apache.poi.ss.formula.FormulaParser; -import org.apache.poi.ss.formula.FormulaRenderer; -import org.apache.poi.ss.formula.FormulaShifter; -import org.apache.poi.ss.formula.FormulaType; -import org.apache.poi.ss.formula.ptg.AreaErrPtg; -import org.apache.poi.ss.formula.ptg.AreaPtg; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Hyperlink; -import org.apache.poi.ss.usermodel.Name; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.usermodel.helpers.RowShifter; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.util.Internal; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.xssf.usermodel.XSSFCell; -import org.apache.poi.xssf.usermodel.XSSFEvaluationWorkbook; -import org.apache.poi.xssf.usermodel.XSSFHyperlink; -import org.apache.poi.xssf.usermodel.XSSFRow; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCell; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCellFormula; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCfRule; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTConditionalFormatting; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STCellFormulaType; - -/** - * Helper for shifting rows up or down - * - * When possible, code should be implemented in the RowShifter abstract class to avoid duplication with {@link org.apache.poi.hssf.usermodel.helpers.HSSFRowShifter} - */ -public final class XSSFRowShifter extends RowShifter { - private static final POILogger logger = POILogFactory.getLogger(XSSFRowShifter.class); - - public XSSFRowShifter(XSSFSheet sh) { - super(sh); - } - - /** - * Shift merged regions - * - * @param startRow the row to start shifting - * @param endRow the row to end shifting - * @param n the number of rows to shift - * @return an array of merged cell regions - * @deprecated POI 3.15 beta 2. Use {@link #shiftMergedRegions(int, int, int)} instead. - */ - public List shiftMerged(int startRow, int endRow, int n) { - return shiftMergedRegions(startRow, endRow, n); - } - - /** - * Updated named ranges - */ - public void updateNamedRanges(FormulaShifter shifter) { - Workbook wb = sheet.getWorkbook(); - XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create((XSSFWorkbook) wb); - for (Name name : wb.getAllNames()) { - String formula = name.getRefersToFormula(); - int sheetIndex = name.getSheetIndex(); - final int rowIndex = -1; //don't care, named ranges are not allowed to include structured references - - Ptg[] ptgs = FormulaParser.parse(formula, fpb, FormulaType.NAMEDRANGE, sheetIndex, rowIndex); - if (shifter.adjustFormula(ptgs, sheetIndex)) { - String shiftedFmla = FormulaRenderer.toFormulaString(fpb, ptgs); - name.setRefersToFormula(shiftedFmla); - } - } - } - - /** - * Update formulas. - */ - public void updateFormulas(FormulaShifter shifter) { - //update formulas on the parent sheet - updateSheetFormulas(sheet, shifter); - - //update formulas on other sheets - Workbook wb = sheet.getWorkbook(); - for (Sheet sh : wb) { - if (sheet == sh) continue; - updateSheetFormulas(sh, shifter); - } - } - - private void updateSheetFormulas(Sheet sh, FormulaShifter shifter) { - for (Row r : sh) { - XSSFRow row = (XSSFRow) r; - updateRowFormulas(row, shifter); - } - } - - /** - * Update the formulas in specified row using the formula shifting policy specified by shifter - * - * @param row the row to update the formulas on - * @param shifter the formula shifting policy - */ - @Internal - public void updateRowFormulas(Row row, FormulaShifter shifter) { - XSSFSheet sheet = (XSSFSheet) row.getSheet(); - for (Cell c : row) { - XSSFCell cell = (XSSFCell) c; - - CTCell ctCell = cell.getCTCell(); - if (ctCell.isSetF()) { - CTCellFormula f = ctCell.getF(); - String formula = f.getStringValue(); - if (formula.length() > 0) { - String shiftedFormula = shiftFormula(row, formula, shifter); - if (shiftedFormula != null) { - f.setStringValue(shiftedFormula); - if(f.getT() == STCellFormulaType.SHARED){ - int si = (int)f.getSi(); - CTCellFormula sf = sheet.getSharedFormula(si); - sf.setStringValue(shiftedFormula); - updateRefInCTCellFormula(row, shifter, sf); - } - } - - } - - //Range of cells which the formula applies to. - updateRefInCTCellFormula(row, shifter, f); - } - - } - } - - private void updateRefInCTCellFormula(Row row, FormulaShifter shifter, CTCellFormula f) { - if (f.isSetRef()) { //Range of cells which the formula applies to. - String ref = f.getRef(); - String shiftedRef = shiftFormula(row, ref, shifter); - if (shiftedRef != null) f.setRef(shiftedRef); - } - } - - /** - * Shift a formula using the supplied FormulaShifter - * - * @param row the row of the cell this formula belongs to. Used to get a reference to the parent workbook. - * @param formula the formula to shift - * @param shifter the FormulaShifter object that operates on the parsed formula tokens - * @return the shifted formula if the formula was changed, - * null if the formula wasn't modified - */ - private static String shiftFormula(Row row, String formula, FormulaShifter shifter) { - Sheet sheet = row.getSheet(); - Workbook wb = sheet.getWorkbook(); - int sheetIndex = wb.getSheetIndex(sheet); - final int rowIndex = row.getRowNum(); - XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create((XSSFWorkbook) wb); - - try { - Ptg[] ptgs = FormulaParser.parse(formula, fpb, FormulaType.CELL, sheetIndex, rowIndex); - String shiftedFmla = null; - if (shifter.adjustFormula(ptgs, sheetIndex)) { - shiftedFmla = FormulaRenderer.toFormulaString(fpb, ptgs); - } - return shiftedFmla; - } catch (FormulaParseException fpe) { - // Log, but don't change, rather than breaking - logger.log(POILogger.WARN, "Error shifting formula on row ", row.getRowNum(), fpe); - return formula; - } - } - - public void updateConditionalFormatting(FormulaShifter shifter) { - XSSFSheet xsheet = (XSSFSheet) sheet; - XSSFWorkbook wb = xsheet.getWorkbook(); - int sheetIndex = wb.getSheetIndex(sheet); - final int rowIndex = -1; //don't care, structured references not allowed in conditional formatting - - XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(wb); - CTWorksheet ctWorksheet = xsheet.getCTWorksheet(); - CTConditionalFormatting[] conditionalFormattingArray = ctWorksheet.getConditionalFormattingArray(); - // iterate backwards due to possible calls to ctWorksheet.removeConditionalFormatting(j) - for (int j = conditionalFormattingArray.length - 1; j >= 0; j--) { - CTConditionalFormatting cf = conditionalFormattingArray[j]; - - ArrayList cellRanges = new ArrayList(); - for (Object stRef : cf.getSqref()) { - String[] regions = stRef.toString().split(" "); - for (String region : regions) { - cellRanges.add(CellRangeAddress.valueOf(region)); - } - } - - boolean changed = false; - List temp = new ArrayList(); - for (CellRangeAddress craOld : cellRanges) { - CellRangeAddress craNew = shiftRange(shifter, craOld, sheetIndex); - if (craNew == null) { - changed = true; - continue; - } - temp.add(craNew); - if (craNew != craOld) { - changed = true; - } - } - - if (changed) { - int nRanges = temp.size(); - if (nRanges == 0) { - ctWorksheet.removeConditionalFormatting(j); - continue; - } - List refs = new ArrayList(); - for(CellRangeAddress a : temp) refs.add(a.formatAsString()); - cf.setSqref(refs); - } - - for(CTCfRule cfRule : cf.getCfRuleArray()){ - String[] formulaArray = cfRule.getFormulaArray(); - for (int i = 0; i < formulaArray.length; i++) { - String formula = formulaArray[i]; - Ptg[] ptgs = FormulaParser.parse(formula, fpb, FormulaType.CELL, sheetIndex, rowIndex); - if (shifter.adjustFormula(ptgs, sheetIndex)) { - String shiftedFmla = FormulaRenderer.toFormulaString(fpb, ptgs); - cfRule.setFormulaArray(i, shiftedFmla); - } - } - } - } - } - - /** - * Shift the Hyperlink anchors (not the hyperlink text, even if the hyperlink - * is of type LINK_DOCUMENT and refers to a cell that was shifted). Hyperlinks - * do not track the content they point to. - * - * @param shifter - */ - public void updateHyperlinks(FormulaShifter shifter) { - int sheetIndex = sheet.getWorkbook().getSheetIndex(sheet); - List hyperlinkList = sheet.getHyperlinkList(); - - for (Hyperlink hyperlink : hyperlinkList) { - XSSFHyperlink xhyperlink = (XSSFHyperlink) hyperlink; - String cellRef = xhyperlink.getCellRef(); - CellRangeAddress cra = CellRangeAddress.valueOf(cellRef); - CellRangeAddress shiftedRange = shiftRange(shifter, cra, sheetIndex); - if (shiftedRange != null && shiftedRange != cra) { - // shiftedRange should not be null. If shiftedRange is null, that means - // that a hyperlink wasn't deleted at the beginning of shiftRows when - // identifying rows that should be removed because they will be overwritten - xhyperlink.setCellReference(shiftedRange.formatAsString()); - } - } - } - - private static CellRangeAddress shiftRange(FormulaShifter shifter, CellRangeAddress cra, int currentExternSheetIx) { - // FormulaShifter works well in terms of Ptgs - so convert CellRangeAddress to AreaPtg (and back) here - AreaPtg aptg = new AreaPtg(cra.getFirstRow(), cra.getLastRow(), cra.getFirstColumn(), cra.getLastColumn(), false, false, false, false); - Ptg[] ptgs = { aptg, }; - - if (!shifter.adjustFormula(ptgs, currentExternSheetIx)) { - return cra; - } - Ptg ptg0 = ptgs[0]; - if (ptg0 instanceof AreaPtg) { - AreaPtg bptg = (AreaPtg) ptg0; - return new CellRangeAddress(bptg.getFirstRow(), bptg.getLastRow(), bptg.getFirstColumn(), bptg.getLastColumn()); - } - if (ptg0 instanceof AreaErrPtg) { - return null; - } - throw new IllegalStateException("Unexpected shifted ptg class (" + ptg0.getClass().getName() + ")"); - } - -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/helpers/XSSFSingleXmlCell.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/helpers/XSSFSingleXmlCell.java deleted file mode 100644 index b91b20b34..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/helpers/XSSFSingleXmlCell.java +++ /dev/null @@ -1,91 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.helpers; - -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.xssf.model.SingleXmlCells; -import org.apache.poi.xssf.usermodel.XSSFCell; -import org.apache.poi.xssf.usermodel.XSSFRow; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTSingleXmlCell; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTXmlCellPr; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTXmlPr; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STXmlDataType.Enum; - -/** - * - * This class is a wrapper around the CTSingleXmlCell (Open Office XML Part 4: - * chapter 3.5.2.1) - * - - * - * @author Roberto Manicardi - * - */ -public class XSSFSingleXmlCell { - - private CTSingleXmlCell singleXmlCell; - private SingleXmlCells parent; - - - public XSSFSingleXmlCell(CTSingleXmlCell singleXmlCell, SingleXmlCells parent){ - this.singleXmlCell = singleXmlCell; - this.parent = parent; - } - - /** - * Gets the XSSFCell referenced by the R attribute or creates a new one if cell doesn't exists - * @return the referenced XSSFCell, null if the cell reference is invalid - */ - public XSSFCell getReferencedCell(){ - XSSFCell cell = null; - - - CellReference cellReference = new CellReference(singleXmlCell.getR()); - - XSSFRow row = parent.getXSSFSheet().getRow(cellReference.getRow()); - if(row==null){ - row = parent.getXSSFSheet().createRow(cellReference.getRow()); - } - - cell = row.getCell(cellReference.getCol()); - if(cell==null){ - cell = row.createCell(cellReference.getCol()); - } - - - return cell; - } - - public String getXpath(){ - CTXmlCellPr xmlCellPr = singleXmlCell.getXmlCellPr(); - CTXmlPr xmlPr = xmlCellPr.getXmlPr(); - String xpath = xmlPr.getXpath(); - return xpath; - } - - public long getMapId(){ - return singleXmlCell.getXmlCellPr().getXmlPr().getMapId(); - } - - public Enum getXmlDataType() { - CTXmlCellPr xmlCellPr = singleXmlCell.getXmlCellPr(); - CTXmlPr xmlPr = xmlCellPr.getXmlPr(); - return xmlPr.getXmlDataType(); - } - -} diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/helpers/XSSFXmlColumnPr.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/helpers/XSSFXmlColumnPr.java deleted file mode 100644 index 574d64013..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/usermodel/helpers/XSSFXmlColumnPr.java +++ /dev/null @@ -1,87 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.helpers; - -import org.apache.poi.xssf.usermodel.XSSFTable; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTableColumn; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTXmlColumnPr; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STXmlDataType.Enum; - - -/** - * - * This class is a wrapper around the CTXmlColumnPr (Open Office XML Part 4: - * chapter 3.5.1.7) - * - * - * @author Roberto Manicardi - */ -public class XSSFXmlColumnPr { - - private XSSFTable table; - private CTTableColumn ctTableColumn; - private CTXmlColumnPr ctXmlColumnPr; - - public XSSFXmlColumnPr(XSSFTable table ,CTTableColumn ctTableColum,CTXmlColumnPr ctXmlColumnPr){ - this.table = table; - this.ctTableColumn = ctTableColum; - this.ctXmlColumnPr = ctXmlColumnPr; - } - - public long getMapId(){ - return ctXmlColumnPr.getMapId(); - } - - public String getXPath(){ - return ctXmlColumnPr.getXpath(); - } - /** - * (see Open Office XML Part 4: chapter 3.5.1.3) - * @return An integer representing the unique identifier of this column. - */ - public long getId(){ - return ctTableColumn.getId(); - } - - - /** - * If the XPath is, for example, /Node1/Node2/Node3 and /Node1/Node2 is the common XPath for the table, the local XPath is /Node3 - * - * @return the local XPath - */ - public String getLocalXPath(){ - StringBuilder localXPath = new StringBuilder(); - int numberOfCommonXPathAxis = table.getCommonXpath().split("/").length-1; - - String[] xPathTokens = ctXmlColumnPr.getXpath().split("/"); - for(int i=numberOfCommonXPathAxis; i BY_MAX = new Comparator() { - @Override - public int compare(CTCol col1, CTCol col2) { - long col1max = col1.getMax(); - long col2max = col2.getMax(); - return col1max < col2max ? -1 : col1max > col2max ? 1 : 0; - } - }; - - public static final Comparator BY_MIN_MAX = new Comparator() { - @Override - public int compare(CTCol col1, CTCol col2) { - long col11min = col1.getMin(); - long col2min = col2.getMin(); - return col11min < col2min ? -1 : col11min > col2min ? 1 : BY_MAX.compare(col1, col2); - } - }; - -} diff --git a/src/ooxml/java/org/apache/poi/xssf/util/EvilUnclosedBRFixingInputStream.java b/src/ooxml/java/org/apache/poi/xssf/util/EvilUnclosedBRFixingInputStream.java deleted file mode 100644 index 0ef1aeeb5..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/util/EvilUnclosedBRFixingInputStream.java +++ /dev/null @@ -1,46 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.util; - -import java.io.InputStream; - -import org.apache.poi.util.Internal; -import org.apache.poi.util.Removal; -import org.apache.poi.util.ReplacingInputStream; - -/** - * This is a seriously sick fix for the fact that some .xlsx - * files contain raw bits of HTML, without being escaped - * or properly turned into XML. - * The result is that they contain things like >br<, - * which breaks the XML parsing. - * This very sick InputStream wrapper attempts to spot - * these go past, and fix them. - * Only works for UTF-8 and US-ASCII based streams! - * It should only be used where experience shows the problem - * can occur... - * - * @deprecated 3.16-beta2 - use ReplacingInputStream(source, ">br<", ">br/<") - */ -@Deprecated -@Removal(version="3.18") -@Internal -public class EvilUnclosedBRFixingInputStream extends ReplacingInputStream { - public EvilUnclosedBRFixingInputStream(InputStream source) { - super(source, "
    ", "
    "); - } -} diff --git a/src/ooxml/java/org/apache/poi/xssf/util/NumericRanges.java b/src/ooxml/java/org/apache/poi/xssf/util/NumericRanges.java deleted file mode 100644 index 0a853cc7c..000000000 --- a/src/ooxml/java/org/apache/poi/xssf/util/NumericRanges.java +++ /dev/null @@ -1,66 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.util; - -public class NumericRanges { - - public static final int NO_OVERLAPS = -1; - public static final int OVERLAPS_1_MINOR = 0; - public static final int OVERLAPS_2_MINOR = 1; - public static final int OVERLAPS_1_WRAPS = 2; - public static final int OVERLAPS_2_WRAPS = 3; - - public static long[] getOverlappingRange(long[] range1, long[] range2) { - switch(getOverlappingType(range1, range2)) { - case OVERLAPS_1_MINOR: - return new long[]{range2[0], range1[1]}; - case OVERLAPS_2_MINOR: - return new long[]{range1[0], range2[1]}; - case OVERLAPS_2_WRAPS: - return range1; - case OVERLAPS_1_WRAPS: - return range2; - default: - case NO_OVERLAPS: - return new long[]{-1, -1}; - } - } - - public static int getOverlappingType(long[] range1, long[] range2) { - long min1 = range1[0]; - long max1 = range1[1]; - long min2 = range2[0]; - long max2 = range2[1]; - if (min1 >= min2) { - if (max1 <= max2) { - return OVERLAPS_2_WRAPS; - } else if (min1 <= max2) { - return OVERLAPS_2_MINOR; - } - } else { - if (max1 >= max2) { - return OVERLAPS_1_WRAPS; - } else if (max1 >= min2) { - return OVERLAPS_1_MINOR; - } - } - return NO_OVERLAPS; - - } - -} diff --git a/src/ooxml/java/org/apache/poi/xwpf/extractor/XWPFWordExtractor.java b/src/ooxml/java/org/apache/poi/xwpf/extractor/XWPFWordExtractor.java deleted file mode 100644 index 712e04b73..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/extractor/XWPFWordExtractor.java +++ /dev/null @@ -1,205 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.extractor; - -import java.io.IOException; -import java.util.List; - -import org.apache.poi.POIXMLDocument; -import org.apache.poi.POIXMLTextExtractor; -import org.apache.poi.openxml4j.exceptions.OpenXML4JException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.xwpf.model.XWPFCommentsDecorator; -import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy; -import org.apache.poi.xwpf.usermodel.IBodyElement; -import org.apache.poi.xwpf.usermodel.ICell; -import org.apache.poi.xwpf.usermodel.IRunElement; -import org.apache.poi.xwpf.usermodel.XWPFDocument; -import org.apache.poi.xwpf.usermodel.XWPFHyperlink; -import org.apache.poi.xwpf.usermodel.XWPFHyperlinkRun; -import org.apache.poi.xwpf.usermodel.XWPFParagraph; -import org.apache.poi.xwpf.usermodel.XWPFRelation; -import org.apache.poi.xwpf.usermodel.XWPFSDT; -import org.apache.poi.xwpf.usermodel.XWPFSDTCell; -import org.apache.poi.xwpf.usermodel.XWPFTable; -import org.apache.poi.xwpf.usermodel.XWPFTableCell; -import org.apache.poi.xwpf.usermodel.XWPFTableRow; -import org.apache.xmlbeans.XmlException; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSectPr; - -/** - * Helper class to extract text from an OOXML Word file - */ -public class XWPFWordExtractor extends POIXMLTextExtractor { - public static final XWPFRelation[] SUPPORTED_TYPES = { - XWPFRelation.DOCUMENT, XWPFRelation.TEMPLATE, - XWPFRelation.MACRO_DOCUMENT, - XWPFRelation.MACRO_TEMPLATE_DOCUMENT - }; - - private XWPFDocument document; - private boolean fetchHyperlinks = false; - - public XWPFWordExtractor(OPCPackage container) throws XmlException, OpenXML4JException, IOException { - this(new XWPFDocument(container)); - } - - public XWPFWordExtractor(XWPFDocument document) { - super(document); - this.document = document; - } - - public static void main(String[] args) throws Exception { - if (args.length < 1) { - System.err.println("Use:"); - System.err.println(" XWPFWordExtractor "); - System.exit(1); - } - POIXMLTextExtractor extractor = - new XWPFWordExtractor(POIXMLDocument.openPackage( - args[0] - )); - System.out.println(extractor.getText()); - extractor.close(); - } - - /** - * Should we also fetch the hyperlinks, when fetching - * the text content? Default is to only output the - * hyperlink label, and not the contents - */ - public void setFetchHyperlinks(boolean fetch) { - fetchHyperlinks = fetch; - } - - public String getText() { - StringBuffer text = new StringBuffer(); - XWPFHeaderFooterPolicy hfPolicy = document.getHeaderFooterPolicy(); - - // Start out with all headers - extractHeaders(text, hfPolicy); - - // Process all body elements - for (IBodyElement e : document.getBodyElements()) { - appendBodyElementText(text, e); - text.append('\n'); - } - - // Finish up with all the footers - extractFooters(text, hfPolicy); - - return text.toString(); - } - - public void appendBodyElementText(StringBuffer text, IBodyElement e) { - if (e instanceof XWPFParagraph) { - appendParagraphText(text, (XWPFParagraph) e); - } else if (e instanceof XWPFTable) { - appendTableText(text, (XWPFTable) e); - } else if (e instanceof XWPFSDT) { - text.append(((XWPFSDT) e).getContent().getText()); - } - } - - public void appendParagraphText(StringBuffer text, XWPFParagraph paragraph) { - CTSectPr ctSectPr = null; - if (paragraph.getCTP().getPPr() != null) { - ctSectPr = paragraph.getCTP().getPPr().getSectPr(); - } - - XWPFHeaderFooterPolicy headerFooterPolicy = null; - - if (ctSectPr != null) { - headerFooterPolicy = new XWPFHeaderFooterPolicy(document, ctSectPr); - extractHeaders(text, headerFooterPolicy); - } - - - for (IRunElement run : paragraph.getRuns()) { - text.append(run.toString()); - if (run instanceof XWPFHyperlinkRun && fetchHyperlinks) { - XWPFHyperlink link = ((XWPFHyperlinkRun) run).getHyperlink(document); - if (link != null) - text.append(" <").append(link.getURL()).append(">"); - } - } - - // Add comments - XWPFCommentsDecorator decorator = new XWPFCommentsDecorator(paragraph, null); - String commentText = decorator.getCommentText(); - if (commentText.length() > 0) { - text.append(commentText).append('\n'); - } - - // Do endnotes and footnotes - String footnameText = paragraph.getFootnoteText(); - if (footnameText != null && footnameText.length() > 0) { - text.append(footnameText).append('\n'); - } - - if (ctSectPr != null) { - extractFooters(text, headerFooterPolicy); - } - } - - private void appendTableText(StringBuffer text, XWPFTable table) { - //this works recursively to pull embedded tables from tables - for (XWPFTableRow row : table.getRows()) { - List cells = row.getTableICells(); - for (int i = 0; i < cells.size(); i++) { - ICell cell = cells.get(i); - if (cell instanceof XWPFTableCell) { - text.append(((XWPFTableCell) cell).getTextRecursively()); - } else if (cell instanceof XWPFSDTCell) { - text.append(((XWPFSDTCell) cell).getContent().getText()); - } - if (i < cells.size() - 1) { - text.append("\t"); - } - } - text.append('\n'); - } - } - - private void extractFooters(StringBuffer text, XWPFHeaderFooterPolicy hfPolicy) { - if (hfPolicy == null) return; - - if (hfPolicy.getFirstPageFooter() != null) { - text.append(hfPolicy.getFirstPageFooter().getText()); - } - if (hfPolicy.getEvenPageFooter() != null) { - text.append(hfPolicy.getEvenPageFooter().getText()); - } - if (hfPolicy.getDefaultFooter() != null) { - text.append(hfPolicy.getDefaultFooter().getText()); - } - } - - private void extractHeaders(StringBuffer text, XWPFHeaderFooterPolicy hfPolicy) { - if (hfPolicy == null) return; - - if (hfPolicy.getFirstPageHeader() != null) { - text.append(hfPolicy.getFirstPageHeader().getText()); - } - if (hfPolicy.getEvenPageHeader() != null) { - text.append(hfPolicy.getEvenPageHeader().getText()); - } - if (hfPolicy.getDefaultHeader() != null) { - text.append(hfPolicy.getDefaultHeader().getText()); - } - } -} diff --git a/src/ooxml/java/org/apache/poi/xwpf/model/WMLHelper.java b/src/ooxml/java/org/apache/poi/xwpf/model/WMLHelper.java deleted file mode 100644 index 0761aebeb..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/model/WMLHelper.java +++ /dev/null @@ -1,33 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.model; - -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STOnOff; - -public final class WMLHelper { - - public static boolean convertSTOnOffToBoolean (STOnOff.Enum value) { - if (value == STOnOff.TRUE || value == STOnOff.ON || value == STOnOff.X_1) { - return true; - } - return false; - } - - public static STOnOff.Enum convertBooleanToSTOnOff (boolean value) { - return (value ? STOnOff.TRUE : STOnOff.FALSE); - } -} diff --git a/src/ooxml/java/org/apache/poi/xwpf/model/XMLParagraph.java b/src/ooxml/java/org/apache/poi/xwpf/model/XMLParagraph.java deleted file mode 100644 index 497b9fe5a..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/model/XMLParagraph.java +++ /dev/null @@ -1,39 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.model; - -import org.apache.poi.util.Removal; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP; - -/** - * Base class for XWPF paragraphs - * - * @deprecated 3.16 beta1. This class isn't used ... - */ -@Deprecated -@Removal(version="3.18") -public class XMLParagraph { - protected CTP paragraph; - - public XMLParagraph(CTP paragraph) { - this.paragraph = paragraph; - } - - public CTP getCTP() { - return paragraph; - } -} \ No newline at end of file diff --git a/src/ooxml/java/org/apache/poi/xwpf/model/XWPFCommentsDecorator.java b/src/ooxml/java/org/apache/poi/xwpf/model/XWPFCommentsDecorator.java deleted file mode 100644 index 7b8356050..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/model/XWPFCommentsDecorator.java +++ /dev/null @@ -1,55 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.model; - -import org.apache.poi.xwpf.usermodel.XWPFComment; -import org.apache.poi.xwpf.usermodel.XWPFParagraph; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTMarkupRange; - -/** - * Decorator class for XWPFParagraph allowing to add comments - * found in paragraph to its text - * - * @author Yury Batrakov (batrakov at gmail.com) - */ -public class XWPFCommentsDecorator extends XWPFParagraphDecorator { - private StringBuffer commentText; - - public XWPFCommentsDecorator(XWPFParagraphDecorator nextDecorator) { - this(nextDecorator.paragraph, nextDecorator); - } - - public XWPFCommentsDecorator(XWPFParagraph paragraph, XWPFParagraphDecorator nextDecorator) { - super(paragraph, nextDecorator); - - XWPFComment comment; - commentText = new StringBuffer(); - - for (CTMarkupRange anchor : paragraph.getCTP().getCommentRangeStartArray()) { - if ((comment = paragraph.getDocument().getCommentByID(anchor.getId().toString())) != null) - commentText.append("\tComment by " + comment.getAuthor() + ": " + comment.getText()); - } - } - - public String getCommentText() { - return commentText.toString(); - } - - public String getText() { - return super.getText() + commentText; - } -} diff --git a/src/ooxml/java/org/apache/poi/xwpf/model/XWPFHeaderFooterPolicy.java b/src/ooxml/java/org/apache/poi/xwpf/model/XWPFHeaderFooterPolicy.java deleted file mode 100644 index 68799fdca..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/model/XWPFHeaderFooterPolicy.java +++ /dev/null @@ -1,494 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.model; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.POIXMLDocumentPart.RelationPart; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.xwpf.usermodel.XWPFDocument; -import org.apache.poi.xwpf.usermodel.XWPFFactory; -import org.apache.poi.xwpf.usermodel.XWPFFooter; -import org.apache.poi.xwpf.usermodel.XWPFHeader; -import org.apache.poi.xwpf.usermodel.XWPFHeaderFooter; -import org.apache.poi.xwpf.usermodel.XWPFParagraph; -import org.apache.poi.xwpf.usermodel.XWPFRelation; -import org.apache.xmlbeans.impl.values.XmlValueOutOfRangeException; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBody; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTHdrFtr; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTHdrFtrRef; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPPr; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPicture; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPr; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSectPr; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.FtrDocument; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.HdrDocument; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STHdrFtr; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STHdrFtr.Enum; - -import com.microsoft.schemas.office.office.CTLock; -import com.microsoft.schemas.office.office.STConnectType; -import com.microsoft.schemas.vml.CTFormulas; -import com.microsoft.schemas.vml.CTGroup; -import com.microsoft.schemas.vml.CTH; -import com.microsoft.schemas.vml.CTHandles; -import com.microsoft.schemas.vml.CTPath; -import com.microsoft.schemas.vml.CTShape; -import com.microsoft.schemas.vml.CTShapetype; -import com.microsoft.schemas.vml.CTTextPath; -import com.microsoft.schemas.vml.STExt; -import com.microsoft.schemas.vml.STTrueFalse; - -/** - * A .docx file can have no headers/footers, the same header/footer - * on each page, odd/even page footers, and optionally also - * a different header/footer on the first page. - * This class handles sorting out what there is, and giving you - * the right headers and footers for the document. - */ -public class XWPFHeaderFooterPolicy { - public static final Enum DEFAULT = STHdrFtr.DEFAULT; - public static final Enum EVEN = STHdrFtr.EVEN; - public static final Enum FIRST = STHdrFtr.FIRST; - - private XWPFDocument doc; - - private XWPFHeader firstPageHeader; - private XWPFFooter firstPageFooter; - - private XWPFHeader evenPageHeader; - private XWPFFooter evenPageFooter; - - private XWPFHeader defaultHeader; - private XWPFFooter defaultFooter; - - /** - * Figures out the policy for the given document, - * and creates any header and footer objects - * as required. - */ - public XWPFHeaderFooterPolicy(XWPFDocument doc) { - this(doc, null); - } - - /** - * Figures out the policy for the given document, - * and creates any header and footer objects - * as required. - */ - public XWPFHeaderFooterPolicy(XWPFDocument doc, CTSectPr sectPr) { - // Grab what headers and footers have been defined - // For now, we don't care about different ranges, as it - // doesn't seem that .docx properly supports that - // feature of the file format yet - if (sectPr == null) { - CTBody ctBody = doc.getDocument().getBody(); - sectPr = ctBody.isSetSectPr() - ? ctBody.getSectPr() - : ctBody.addNewSectPr(); - } - this.doc = doc; - for (int i = 0; i < sectPr.sizeOfHeaderReferenceArray(); i++) { - // Get the header - CTHdrFtrRef ref = sectPr.getHeaderReferenceArray(i); - POIXMLDocumentPart relatedPart = doc.getRelationById(ref.getId()); - XWPFHeader hdr = null; - if (relatedPart != null && relatedPart instanceof XWPFHeader) { - hdr = (XWPFHeader) relatedPart; - } - // Assign it; treat invalid options as "default" POI-60293 - Enum type; - try { - type = ref.getType(); - } catch (XmlValueOutOfRangeException e) { - type = STHdrFtr.DEFAULT; - } - - assignHeader(hdr, type); - } - for (int i = 0; i < sectPr.sizeOfFooterReferenceArray(); i++) { - // Get the footer - CTHdrFtrRef ref = sectPr.getFooterReferenceArray(i); - POIXMLDocumentPart relatedPart = doc.getRelationById(ref.getId()); - XWPFFooter ftr = null; - if (relatedPart != null && relatedPart instanceof XWPFFooter) { - ftr = (XWPFFooter) relatedPart; - } - // Assign it; treat invalid options as "default" POI-60293 - Enum type; - try { - type = ref.getType(); - } catch (XmlValueOutOfRangeException e) { - type = STHdrFtr.DEFAULT; - } - assignFooter(ftr, type); - } - } - - private void assignFooter(XWPFFooter ftr, Enum type) { - if (type == STHdrFtr.FIRST) { - firstPageFooter = ftr; - } else if (type == STHdrFtr.EVEN) { - evenPageFooter = ftr; - } else { - defaultFooter = ftr; - } - } - - private void assignHeader(XWPFHeader hdr, Enum type) { - if (type == STHdrFtr.FIRST) { - firstPageHeader = hdr; - } else if (type == STHdrFtr.EVEN) { - evenPageHeader = hdr; - } else { - defaultHeader = hdr; - } - } - - /** - * Creates an empty header of the specified type, containing a single - * empty paragraph, to which you can then set text, add more paragraphs etc. - */ - public XWPFHeader createHeader(Enum type) { - return createHeader(type, null); - } - - /** - * Creates a new header of the specified type, to which the - * supplied (and previously unattached!) paragraphs are - * added to. - */ - public XWPFHeader createHeader(Enum type, XWPFParagraph[] pars) { - XWPFHeader header = getHeader(type); - - if (header == null) { - HdrDocument hdrDoc = HdrDocument.Factory.newInstance(); - - XWPFRelation relation = XWPFRelation.HEADER; - int i = getRelationIndex(relation); - - XWPFHeader wrapper = (XWPFHeader) doc.createRelationship(relation, - XWPFFactory.getInstance(), i); - wrapper.setXWPFDocument(doc); - - String pStyle = "Header"; - CTHdrFtr hdr = buildHdr(type, pStyle, wrapper, pars); - wrapper.setHeaderFooter(hdr); - hdrDoc.setHdr(hdr); - assignHeader(wrapper, type); - header = wrapper; - } - - return header; - } - - /** - * Creates an empty footer of the specified type, containing a single - * empty paragraph, to which you can then set text, add more paragraphs etc. - */ - public XWPFFooter createFooter(Enum type) { - return createFooter(type, null); - } - - /** - * Creates a new footer of the specified type, to which the - * supplied (and previously unattached!) paragraphs are - * added to. - */ - public XWPFFooter createFooter(Enum type, XWPFParagraph[] pars) { - XWPFFooter footer = getFooter(type); - - if (footer == null) { - FtrDocument ftrDoc = FtrDocument.Factory.newInstance(); - - XWPFRelation relation = XWPFRelation.FOOTER; - int i = getRelationIndex(relation); - - XWPFFooter wrapper = (XWPFFooter) doc.createRelationship(relation, - XWPFFactory.getInstance(), i); - wrapper.setXWPFDocument(doc); - - String pStyle = "Footer"; - CTHdrFtr ftr = buildFtr(type, pStyle, wrapper, pars); - wrapper.setHeaderFooter(ftr); - ftrDoc.setFtr(ftr); - assignFooter(wrapper, type); - footer = wrapper; - } - - return footer; - } - - private int getRelationIndex(XWPFRelation relation) { - int i = 1; - for (RelationPart rp : doc.getRelationParts()) { - if (rp.getRelationship().getRelationshipType().equals(relation.getRelation())) { - i++; - } - } - return i; - } - - private CTHdrFtr buildFtr(Enum type, String pStyle, XWPFHeaderFooter wrapper, XWPFParagraph[] pars) { - //CTHdrFtr ftr = buildHdrFtr(pStyle, pars); // MB 24 May 2010 - CTHdrFtr ftr = buildHdrFtr(pStyle, pars, wrapper); // MB 24 May 2010 - setFooterReference(type, wrapper); - return ftr; - } - - private CTHdrFtr buildHdr(Enum type, String pStyle, XWPFHeaderFooter wrapper, XWPFParagraph[] pars) { - //CTHdrFtr hdr = buildHdrFtr(pStyle, pars); // MB 24 May 2010 - CTHdrFtr hdr = buildHdrFtr(pStyle, pars, wrapper); // MB 24 May 2010 - setHeaderReference(type, wrapper); - return hdr; - } - - /** - * MB 24 May 2010. Created this overloaded buildHdrFtr() method because testing demonstrated - * that the XWPFFooter or XWPFHeader object returned by calls to the createHeader(int, XWPFParagraph[]) - * and createFooter(int, XWPFParagraph[]) methods or the getXXXXXHeader/Footer methods where - * headers or footers had been added to a document since it had been created/opened, returned - * an object that contained no XWPFParagraph objects even if the header/footer itself did contain - * text. The reason was that this line of code; CTHdrFtr ftr = CTHdrFtr.Factory.newInstance(); - * created a brand new instance of the CTHDRFtr class which was then populated with data when - * it should have recovered the CTHdrFtr object encapsulated within the XWPFHeaderFooter object - * that had previoulsy been instantiated in the createHeader(int, XWPFParagraph[]) or - * createFooter(int, XWPFParagraph[]) methods. - */ - private CTHdrFtr buildHdrFtr(String pStyle, XWPFParagraph[] paragraphs, XWPFHeaderFooter wrapper) { - CTHdrFtr ftr = wrapper._getHdrFtr(); - if (paragraphs != null) { - for (int i = 0; i < paragraphs.length; i++) { - CTP p = ftr.addNewP(); - ftr.setPArray(i, paragraphs[i].getCTP()); - } -// } else { -// CTP p = ftr.addNewP(); -// CTBody body = doc.getDocument().getBody(); -// if (body.sizeOfPArray() > 0) { -// CTP p0 = body.getPArray(0); -// if (p0.isSetRsidR()) { -// byte[] rsidr = p0.getRsidR(); -// byte[] rsidrdefault = p0.getRsidRDefault(); -// p.setRsidP(rsidr); -// p.setRsidRDefault(rsidrdefault); -// } -// } -// CTPPr pPr = p.addNewPPr(); -// pPr.addNewPStyle().setVal(pStyle); - } - return ftr; - } - - - private void setFooterReference(Enum type, XWPFHeaderFooter wrapper) { - CTHdrFtrRef ref = doc.getDocument().getBody().getSectPr().addNewFooterReference(); - ref.setType(type); - ref.setId(doc.getRelationId(wrapper)); - } - - - private void setHeaderReference(Enum type, XWPFHeaderFooter wrapper) { - CTHdrFtrRef ref = doc.getDocument().getBody().getSectPr().addNewHeaderReference(); - ref.setType(type); - ref.setId(doc.getRelationId(wrapper)); - } - - public XWPFHeader getFirstPageHeader() { - return firstPageHeader; - } - - public XWPFFooter getFirstPageFooter() { - return firstPageFooter; - } - - /** - * Returns the odd page header. This is - * also the same as the default one... - */ - public XWPFHeader getOddPageHeader() { - return defaultHeader; - } - - /** - * Returns the odd page footer. This is - * also the same as the default one... - */ - public XWPFFooter getOddPageFooter() { - return defaultFooter; - } - - public XWPFHeader getEvenPageHeader() { - return evenPageHeader; - } - - public XWPFFooter getEvenPageFooter() { - return evenPageFooter; - } - - public XWPFHeader getDefaultHeader() { - return defaultHeader; - } - - public XWPFFooter getDefaultFooter() { - return defaultFooter; - } - - /** - * Get the header that applies to the given - * (1 based) page. - * - * @param pageNumber The one based page number - */ - public XWPFHeader getHeader(int pageNumber) { - if (pageNumber == 1 && firstPageHeader != null) { - return firstPageHeader; - } - if (pageNumber % 2 == 0 && evenPageHeader != null) { - return evenPageHeader; - } - return defaultHeader; - } - - /** - * Get this section header for the given type - * - * @param type of header to return - * @return {@link XWPFHeader} object - */ - public XWPFHeader getHeader(Enum type) { - if (type == STHdrFtr.EVEN) { - return evenPageHeader; - } else if (type == STHdrFtr.FIRST) { - return firstPageHeader; - } - return defaultHeader; - } - - /** - * Get the footer that applies to the given - * (1 based) page. - * - * @param pageNumber The one based page number - */ - public XWPFFooter getFooter(int pageNumber) { - if (pageNumber == 1 && firstPageFooter != null) { - return firstPageFooter; - } - if (pageNumber % 2 == 0 && evenPageFooter != null) { - return evenPageFooter; - } - return defaultFooter; - } - - /** - * Get this section footer for the given type - * - * @param type of footer to return - * @return {@link XWPFFooter} object - */ - public XWPFFooter getFooter(Enum type) { - if (type == STHdrFtr.EVEN) { - return evenPageFooter; - } else if (type == STHdrFtr.FIRST) { - return firstPageFooter; - } - return defaultFooter; - } - - - public void createWatermark(String text) { - XWPFParagraph[] pars = new XWPFParagraph[1]; - pars[0] = getWatermarkParagraph(text, 1); - createHeader(DEFAULT, pars); - pars[0] = getWatermarkParagraph(text, 2); - createHeader(FIRST, pars); - pars[0] = getWatermarkParagraph(text, 3); - createHeader(EVEN, pars); - } - - /* - * This is the default Watermark paragraph; the only variable is the text message - * TODO: manage all the other variables - */ - private XWPFParagraph getWatermarkParagraph(String text, int idx) { - CTP p = CTP.Factory.newInstance(); - byte[] rsidr = doc.getDocument().getBody().getPArray(0).getRsidR(); - byte[] rsidrdefault = doc.getDocument().getBody().getPArray(0).getRsidRDefault(); - p.setRsidP(rsidr); - p.setRsidRDefault(rsidrdefault); - CTPPr pPr = p.addNewPPr(); - pPr.addNewPStyle().setVal("Header"); - // start watermark paragraph - CTR r = p.addNewR(); - CTRPr rPr = r.addNewRPr(); - rPr.addNewNoProof(); - CTPicture pict = r.addNewPict(); - CTGroup group = CTGroup.Factory.newInstance(); - CTShapetype shapetype = group.addNewShapetype(); - shapetype.setId("_x0000_t136"); - shapetype.setCoordsize("1600,21600"); - shapetype.setSpt(136); - shapetype.setAdj("10800"); - shapetype.setPath2("m@7,0l@8,0m@5,21600l@6,21600e"); - CTFormulas formulas = shapetype.addNewFormulas(); - formulas.addNewF().setEqn("sum #0 0 10800"); - formulas.addNewF().setEqn("prod #0 2 1"); - formulas.addNewF().setEqn("sum 21600 0 @1"); - formulas.addNewF().setEqn("sum 0 0 @2"); - formulas.addNewF().setEqn("sum 21600 0 @3"); - formulas.addNewF().setEqn("if @0 @3 0"); - formulas.addNewF().setEqn("if @0 21600 @1"); - formulas.addNewF().setEqn("if @0 0 @2"); - formulas.addNewF().setEqn("if @0 @4 21600"); - formulas.addNewF().setEqn("mid @5 @6"); - formulas.addNewF().setEqn("mid @8 @5"); - formulas.addNewF().setEqn("mid @7 @8"); - formulas.addNewF().setEqn("mid @6 @7"); - formulas.addNewF().setEqn("sum @6 0 @5"); - CTPath path = shapetype.addNewPath(); - path.setTextpathok(STTrueFalse.T); - path.setConnecttype(STConnectType.CUSTOM); - path.setConnectlocs("@9,0;@10,10800;@11,21600;@12,10800"); - path.setConnectangles("270,180,90,0"); - CTTextPath shapeTypeTextPath = shapetype.addNewTextpath(); - shapeTypeTextPath.setOn(STTrueFalse.T); - shapeTypeTextPath.setFitshape(STTrueFalse.T); - CTHandles handles = shapetype.addNewHandles(); - CTH h = handles.addNewH(); - h.setPosition("#0,bottomRight"); - h.setXrange("6629,14971"); - CTLock lock = shapetype.addNewLock(); - lock.setExt(STExt.EDIT); - CTShape shape = group.addNewShape(); - shape.setId("PowerPlusWaterMarkObject" + idx); - shape.setSpid("_x0000_s102" + (4 + idx)); - shape.setType("#_x0000_t136"); - shape.setStyle("position:absolute;margin-left:0;margin-top:0;width:415pt;height:207.5pt;z-index:-251654144;mso-wrap-edited:f;mso-position-horizontal:center;mso-position-horizontal-relative:margin;mso-position-vertical:center;mso-position-vertical-relative:margin"); - shape.setWrapcoords("616 5068 390 16297 39 16921 -39 17155 7265 17545 7186 17467 -39 17467 18904 17467 10507 17467 8710 17545 18904 17077 18787 16843 18358 16297 18279 12554 19178 12476 20701 11774 20779 11228 21131 10059 21248 8811 21248 7563 20975 6316 20935 5380 19490 5146 14022 5068 2616 5068"); - shape.setFillcolor("black"); - shape.setStroked(STTrueFalse.FALSE); - CTTextPath shapeTextPath = shape.addNewTextpath(); - shapeTextPath.setStyle("font-family:"Cambria";font-size:1pt"); - shapeTextPath.setString(text); - pict.set(group); - // end watermark paragraph - return new XWPFParagraph(p, doc); - } -} diff --git a/src/ooxml/java/org/apache/poi/xwpf/model/XWPFParagraphDecorator.java b/src/ooxml/java/org/apache/poi/xwpf/model/XWPFParagraphDecorator.java deleted file mode 100644 index 46636c3ef..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/model/XWPFParagraphDecorator.java +++ /dev/null @@ -1,43 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.model; - -import org.apache.poi.xwpf.usermodel.XWPFParagraph; - -/** - * Base decorator class for XWPFParagraph - */ -public abstract class XWPFParagraphDecorator { - protected XWPFParagraph paragraph; - protected XWPFParagraphDecorator nextDecorator; - - public XWPFParagraphDecorator(XWPFParagraph paragraph) { - this(paragraph, null); - } - - public XWPFParagraphDecorator(XWPFParagraph paragraph, XWPFParagraphDecorator nextDecorator) { - this.paragraph = paragraph; - this.nextDecorator = nextDecorator; - } - - public String getText() { - if (nextDecorator != null) { - return nextDecorator.getText(); - } - return paragraph.getText(); - } -} diff --git a/src/ooxml/java/org/apache/poi/xwpf/package.html b/src/ooxml/java/org/apache/poi/xwpf/package.html deleted file mode 100644 index 0a5955646..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/package.html +++ /dev/null @@ -1,27 +0,0 @@ - - - - -

    This package contains classes for handling Microsoft .docx - Word Processing files, known in POI as XWPF (XML Word Processing - Format). -

    - - diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/AbstractXWPFSDT.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/AbstractXWPFSDT.java deleted file mode 100644 index cb9bc35dd..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/AbstractXWPFSDT.java +++ /dev/null @@ -1,107 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -import org.apache.poi.POIXMLDocumentPart; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtPr; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTString; - -/** - * Experimental abstract class that is a base for XWPFSDT and XWPFSDTCell - *

    - * WARNING - APIs expected to change rapidly. - *

    - * These classes have so far been built only for read-only processing. - */ -public abstract class AbstractXWPFSDT implements ISDTContents { - private final String title; - private final String tag; - private final IBody part; - - public AbstractXWPFSDT(CTSdtPr pr, IBody part) { - if (pr == null) { - title = ""; - tag = ""; - } else { - CTString[] aliases = pr.getAliasArray(); - if (aliases != null && aliases.length > 0) { - title = aliases[0].getVal(); - } else { - title = ""; - } - CTString[] tags = pr.getTagArray(); - if (tags != null && tags.length > 0) { - tag = tags[0].getVal(); - } else { - tag = ""; - } - } - this.part = part; - - } - - /** - * @return first SDT Title - */ - public String getTitle() { - return title; - } - - /** - * @return first SDT Tag - */ - public String getTag() { - return tag; - } - - /** - * @return the content object - */ - public abstract ISDTContent getContent(); - - /** - * @return null - */ - public IBody getBody() { - return null; - } - - /** - * @return document part - */ - public POIXMLDocumentPart getPart() { - return part.getPart(); - } - - /** - * @return partType - */ - public BodyType getPartType() { - return BodyType.CONTENTCONTROL; - } - - /** - * @return element type - */ - public BodyElementType getElementType() { - return BodyElementType.CONTENTCONTROL; - } - - public XWPFDocument getDocument() { - return part.getXWPFDocument(); - } -} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/BodyElementType.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/BodyElementType.java deleted file mode 100644 index d93ba9d0b..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/BodyElementType.java +++ /dev/null @@ -1,34 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xwpf.usermodel; - -/** - *

    - * 9 Jan 2010 - *

    - *

    - * // TODO insert Javadoc here! - *

    - * - * @author epp - */ -public enum BodyElementType { - CONTENTCONTROL, - PARAGRAPH, - TABLE, -} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/BodyType.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/BodyType.java deleted file mode 100644 index 39e4758b6..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/BodyType.java +++ /dev/null @@ -1,30 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xwpf.usermodel; - -/** - * The different kinds of {@link IBody} that exist - */ -public enum BodyType { - CONTENTCONTROL, - DOCUMENT, - HEADER, - FOOTER, - FOOTNOTE, - TABLECELL -} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/Borders.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/Borders.java deleted file mode 100644 index 69e039120..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/Borders.java +++ /dev/null @@ -1,628 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xwpf.usermodel; - -import java.util.HashMap; -import java.util.Map; - -/** - * Specifies all types of borders which can be specified for WordprocessingML - * objects which have a border. Borders can be separated into two types: - *
      - *
    • Line borders: which specify a pattern to be used when drawing a line around the - * specified object. - *
    • - *
    • Art borders: which specify a repeated image to be used - * when drawing a border around the specified object. Line borders may be - * specified on any object which allows a border, however, art borders may only - * be used as a border at the page level - the borders under the pgBorders - * element - *
    • - *
    - * - * @author Gisella Bronzetti - */ -public enum Borders { - - NIL(1), - - NONE(2), - - /** - * Specifies a line border consisting of a single line around the parent - * object. - */ - SINGLE(3), - - THICK(4), - - DOUBLE(5), - - DOTTED(6), - - DASHED(7), - - DOT_DASH(8), - - DOT_DOT_DASH(9), - - TRIPLE(10), - - THIN_THICK_SMALL_GAP(11), - - THICK_THIN_SMALL_GAP(12), - - THIN_THICK_THIN_SMALL_GAP(13), - - THIN_THICK_MEDIUM_GAP(14), - - THICK_THIN_MEDIUM_GAP(15), - - THIN_THICK_THIN_MEDIUM_GAP(16), - - THIN_THICK_LARGE_GAP(17), - - THICK_THIN_LARGE_GAP(18), - - THIN_THICK_THIN_LARGE_GAP(19), - - WAVE(20), - - DOUBLE_WAVE(21), - - DASH_SMALL_GAP(22), - - DASH_DOT_STROKED(23), - - THREE_D_EMBOSS(24), - - THREE_D_ENGRAVE(25), - - OUTSET(26), - - INSET(27), - - /** - * Specifies an art border consisting of a repeated image of an apple - */ - APPLES(28), - - /** - * Specifies an art border consisting of a repeated image of a shell pattern - */ - ARCHED_SCALLOPS(29), - - /** - * Specifies an art border consisting of a repeated image of a baby pacifier - */ - BABY_PACIFIER(30), - - /** - * Specifies an art border consisting of a repeated image of a baby rattle - */ - BABY_RATTLE(31), - - /** - * Specifies an art border consisting of a repeated image of a set of - * balloons - */ - BALLOONS_3_COLORS(32), - - /** - * Specifies an art border consisting of a repeated image of a hot air - * balloon - */ - BALLOONS_HOT_AIR(33), - - /** - * Specifies an art border consisting of a repeating image of a black and - * white background. - */ - BASIC_BLACK_DASHES(34), - - /** - * Specifies an art border consisting of a repeating image of a black dot on - * a white background. - */ - BASIC_BLACK_DOTS(35), - - /** - * Specifies an art border consisting of a repeating image of a black and - * white background - */ - BASIC_BLACK_SQUARES(36), - - /** - * Specifies an art border consisting of a repeating image of a black and - * white background. - */ - BASIC_THIN_LINES(37), - - /** - * Specifies an art border consisting of a repeating image of a black and - * white background. - */ - BASIC_WHITE_DASHES(38), - - /** - * Specifies an art border consisting of a repeating image of a white dot on - * a black background. - */ - BASIC_WHITE_DOTS(39), - - /** - * Specifies an art border consisting of a repeating image of a black and - * white background. - */ - BASIC_WHITE_SQUARES(40), - - /** - * Specifies an art border consisting of a repeating image of a black and - * white background. - */ - BASIC_WIDE_INLINE(41), - - /** - * Specifies an art border consisting of a repeating image of a black and - * white background - */ - BASIC_WIDE_MIDLINE(42), - - /** - * Specifies an art border consisting of a repeating image of a black and - * white background - */ - BASIC_WIDE_OUTLINE(43), - - /** - * Specifies an art border consisting of a repeated image of bats - */ - BATS(44), - - /** - * Specifies an art border consisting of repeating images of birds - */ - BIRDS(45), - - /** - * Specifies an art border consisting of a repeated image of birds flying - */ - BIRDS_FLIGHT(46), - - /** - * Specifies an art border consisting of a repeated image of a cabin - */ - CABINS(47), - - /** - * Specifies an art border consisting of a repeated image of a piece of cake - */ - CAKE_SLICE(48), - - /** - * Specifies an art border consisting of a repeated image of candy corn - */ - CANDY_CORN(49), - - /** - * Specifies an art border consisting of a repeated image of a knot work - * pattern - */ - CELTIC_KNOTWORK(50), - - /** - * Specifies an art border consisting of a banner. - *

    - * If the border is on the left or right, no border is displayed. - *

    - */ - CERTIFICATE_BANNER(51), - - /** - * Specifies an art border consisting of a repeating image of a chain link - * pattern. - */ - CHAIN_LINK(52), - - /** - * Specifies an art border consisting of a repeated image of a champagne - * bottle - */ - CHAMPAGNE_BOTTLE(53), - - /** - * Specifies an art border consisting of repeating images of a compass - */ - CHECKED_BAR_BLACK(54), - - /** - * Specifies an art border consisting of a repeating image of a colored - * pattern. - */ - CHECKED_BAR_COLOR(55), - - /** - * Specifies an art border consisting of a repeated image of a checkerboard - */ - CHECKERED(56), - - /** - * Specifies an art border consisting of a repeated image of a Christmas - * tree - */ - CHRISTMAS_TREE(57), - - /** - * Specifies an art border consisting of repeating images of lines and - * circles - */ - CIRCLES_LINES(58), - - /** - * Specifies an art border consisting of a repeated image of a rectangular - * pattern - */ - CIRCLES_RECTANGLES(59), - - /** - * Specifies an art border consisting of a repeated image of a wave - */ - CLASSICAL_WAVE(60), - - /** - * Specifies an art border consisting of a repeated image of a clock - */ - CLOCKS(61), - - /** - * Specifies an art border consisting of repeating images of a compass - */ - COMPASS(62), - - /** - * Specifies an art border consisting of a repeated image of confetti - */ - CONFETTI(63), - - /** - * Specifies an art border consisting of a repeated image of confetti - */ - CONFETTI_GRAYS(64), - - /** - * Specifies an art border consisting of a repeated image of confetti - */ - CONFETTI_OUTLINE(65), - - /** - * Specifies an art border consisting of a repeated image of confetti - * streamers - */ - CONFETTI_STREAMERS(66), - - /** - * Specifies an art border consisting of a repeated image of confetti - */ - CONFETTI_WHITE(67), - - /** - * Specifies an art border consisting of a repeated image - */ - CORNER_TRIANGLES(68), - - /** - * Specifies an art border consisting of a dashed line - */ - COUPON_CUTOUT_DASHES(69), - - /** - * Specifies an art border consisting of a dotted line - */ - COUPON_CUTOUT_DOTS(70), - - /** - * Specifies an art border consisting of a repeated image of a maze-like - * pattern - */ - CRAZY_MAZE(71), - - /** - * Specifies an art border consisting of a repeated image of a butterfly - */ - CREATURES_BUTTERFLY(72), - - /** - * Specifies an art border consisting of a repeated image of a fish - */ - CREATURES_FISH(73), - - /** - * Specifies an art border consisting of repeating images of insects. - */ - CREATURES_INSECTS(74), - - /** - * Specifies an art border consisting of a repeated image of a ladybug - */ - CREATURES_LADY_BUG(75), - - /** - * Specifies an art border consisting of repeating images of a cross-stitch - * pattern - */ - CROSS_STITCH(76), - - /** - * Specifies an art border consisting of a repeated image of Cupid - */ - CUP(77), - - DECO_ARCH(78), - - DECO_ARCH_COLOR(79), - - DECO_BLOCKS(80), - - DIAMONDS_GRAY(81), - - DOUBLE_D(82), - - DOUBLE_DIAMONDS(83), - - EARTH_1(84), - - EARTH_2(85), - - ECLIPSING_SQUARES_1(86), - - ECLIPSING_SQUARES_2(87), - - EGGS_BLACK(88), - - FANS(89), - - FILM(90), - - FIRECRACKERS(91), - - FLOWERS_BLOCK_PRINT(92), - - FLOWERS_DAISIES(93), - - FLOWERS_MODERN_1(94), - - FLOWERS_MODERN_2(95), - - FLOWERS_PANSY(96), - - FLOWERS_RED_ROSE(97), - - FLOWERS_ROSES(98), - - FLOWERS_TEACUP(99), - - FLOWERS_TINY(100), - - GEMS(101), - - GINGERBREAD_MAN(102), - - GRADIENT(103), - - HANDMADE_1(104), - - HANDMADE_2(105), - - HEART_BALLOON(106), - - HEART_GRAY(107), - - HEARTS(108), - - HEEBIE_JEEBIES(109), - - HOLLY(110), - - HOUSE_FUNKY(111), - - HYPNOTIC(112), - - ICE_CREAM_CONES(113), - - LIGHT_BULB(114), - - LIGHTNING_1(115), - - LIGHTNING_2(116), - - MAP_PINS(117), - - MAPLE_LEAF(118), - - MAPLE_MUFFINS(119), - - MARQUEE(120), - - MARQUEE_TOOTHED(121), - - MOONS(122), - - MOSAIC(123), - - MUSIC_NOTES(124), - - NORTHWEST(125), - - OVALS(126), - - PACKAGES(127), - - PALMS_BLACK(128), - - PALMS_COLOR(129), - - PAPER_CLIPS(130), - - PAPYRUS(131), - - PARTY_FAVOR(132), - - PARTY_GLASS(133), - - PENCILS(134), - - PEOPLE(135), - - PEOPLE_WAVING(136), - - PEOPLE_HATS(137), - - POINSETTIAS(138), - - POSTAGE_STAMP(139), - - PUMPKIN_1(140), - - PUSH_PIN_NOTE_2(141), - - PUSH_PIN_NOTE_1(142), - - PYRAMIDS(143), - - PYRAMIDS_ABOVE(144), - - QUADRANTS(145), - - RINGS(146), - - SAFARI(147), - - SAWTOOTH(148), - - SAWTOOTH_GRAY(149), - - SCARED_CAT(150), - - SEATTLE(151), - - SHADOWED_SQUARES(152), - - SHARKS_TEETH(153), - - SHOREBIRD_TRACKS(154), - - SKYROCKET(155), - - SNOWFLAKE_FANCY(156), - - SNOWFLAKES(157), - - SOMBRERO(158), - - SOUTHWEST(159), - - STARS(160), - - STARS_TOP(161), - - STARS_3_D(162), - - STARS_BLACK(163), - - STARS_SHADOWED(164), - - SUN(165), - - SWIRLIGIG(166), - - TORN_PAPER(167), - - TORN_PAPER_BLACK(168), - - TREES(169), - - TRIANGLE_PARTY(170), - - TRIANGLES(171), - - TRIBAL_1(172), - - TRIBAL_2(173), - - TRIBAL_3(174), - - TRIBAL_4(175), - - TRIBAL_5(176), - - TRIBAL_6(177), - - TWISTED_LINES_1(178), - - TWISTED_LINES_2(179), - - VINE(180), - - WAVELINE(181), - - WEAVING_ANGLES(182), - - WEAVING_BRAID(183), - - WEAVING_RIBBON(184), - - WEAVING_STRIPS(185), - - WHITE_FLOWERS(186), - - WOODWORK(187), - - X_ILLUSIONS(188), - - ZANY_TRIANGLES(189), - - ZIG_ZAG(190), - - ZIG_ZAG_STITCH(191); - - private static Map imap = new HashMap(); - - static { - for (Borders p : values()) { - imap.put(Integer.valueOf(p.getValue()), p); - } - } - - private final int value; - - private Borders(int val) { - value = val; - } - - public static Borders valueOf(int type) { - Borders pBorder = imap.get(Integer.valueOf(type)); - if (pBorder == null) { - throw new IllegalArgumentException("Unknown paragraph border: " + type); - } - return pBorder; - } - - public int getValue() { - return value; - } -} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/BreakClear.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/BreakClear.java deleted file mode 100644 index 0f44f21f7..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/BreakClear.java +++ /dev/null @@ -1,111 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -import java.util.HashMap; -import java.util.Map; - -/** - * Specifies the set of possible restart locations which may be used as to - * determine the next available line when a break's type attribute has a value - * of textWrapping. - * - * @author Gisella Bronzetti - */ -public enum BreakClear { - - /** - * Specifies that the text wrapping break shall advance the text to the next - * line in the WordprocessingML document, regardless of its position left to - * right or the presence of any floating objects which intersect with the - * line, - *

    - * This is the setting for a typical line break in a document. - */ - - NONE(1), - - /** - * Specifies that the text wrapping break shall behave as follows: - *

      - *
    • If this line is broken into multiple regions (a floating object in - * the center of the page has text wrapping on both sides: - *
        - *
      • If this is the leftmost region of text flow on this line, advance - * the text to the next position on the line
      • - *
      • Otherwise, treat this as a text wrapping break of type all.
      • - *
      - *
    • - *
    • If this line is not broken into multiple regions, then treat this - * break as a text wrapping break of type none.
    • - *
    - *
  • If the parent paragraph is right to left, then these behaviors are - * also reversed.
  • - */ - LEFT(2), - - /** - * Specifies that the text wrapping break shall behave as follows: - *
      - *
    • If this line is broken into multiple regions (a floating object in - * the center of the page has text wrapping on both sides: - *
        - *
      • If this is the rightmost region of text flow on this line, advance - * the text to the next position on the next line
      • - *
      • Otherwise, treat this as a text wrapping break of type all.
      • - *
      - *
    • If this line is not broken into multiple regions, then treat this - * break as a text wrapping break of type none.
    • - *
    • If the parent paragraph is right to left, then these beha viors are - * also reversed.
    • - *
    - */ - RIGHT(3), - - /** - * Specifies that the text wrapping break shall advance the text to the next - * line in the WordprocessingML document which spans the full width of the - * line. - */ - ALL(4); - - private static Map imap = new HashMap(); - - static { - for (BreakClear p : values()) { - imap.put(p.getValue(), p); - } - } - - private final int value; - - private BreakClear(int val) { - value = val; - } - - public static BreakClear valueOf(int type) { - BreakClear bType = imap.get(type); - if (bType == null) - throw new IllegalArgumentException("Unknown break clear type: " - + type); - return bType; - } - - public int getValue() { - return value; - } -} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/BreakType.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/BreakType.java deleted file mode 100644 index 3a6054b01..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/BreakType.java +++ /dev/null @@ -1,84 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -import java.util.HashMap; -import java.util.Map; - -/** - * Specifies the possible types of break characters in a WordprocessingML - * document. - * The break type determines the next location where text shall be - * placed after this manual break is applied to the text contents - * - * @author Gisella Bronzetti - */ -public enum BreakType { - - - /** - * Specifies that the current break shall restart itself on the next page of - * the document when the document is displayed in page view. - */ - PAGE(1), - - /** - * Specifies that the current break shall restart itself on the next column - * available on the current page when the document is displayed in page - * view. - *

    - * If the current section is not divided into columns, or the column break - * occurs in the last column on the current page when displayed, then the - * restart location for text shall be the next page in the document. - *

    - */ - COLUMN(2), - - /** - * Specifies that the current break shall restart itself on the next line in - * the document when the document is displayed in page view. - * The determine of the next line shall be done subject to the value of the clear - * attribute on the specified break character. - */ - TEXT_WRAPPING(3); - - private static Map imap = new HashMap(); - - static { - for (BreakType p : values()) { - imap.put(p.getValue(), p); - } - } - - private final int value; - - private BreakType(int val) { - value = val; - } - - public static BreakType valueOf(int type) { - BreakType bType = imap.get(type); - if (bType == null) - throw new IllegalArgumentException("Unknown break type: " - + type); - return bType; - } - - public int getValue() { - return value; - } -} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/Document.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/Document.java deleted file mode 100644 index 0bd4175f9..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/Document.java +++ /dev/null @@ -1,75 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -public interface Document { - /** - * Extended windows meta file - */ - public static final int PICTURE_TYPE_EMF = 2; - - /** - * Windows Meta File - */ - public static final int PICTURE_TYPE_WMF = 3; - - /** - * Mac PICT format - */ - public static final int PICTURE_TYPE_PICT = 4; - - /** - * JPEG format - */ - public static final int PICTURE_TYPE_JPEG = 5; - - /** - * PNG format - */ - public static final int PICTURE_TYPE_PNG = 6; - - /** - * Device independent bitmap - */ - public static final int PICTURE_TYPE_DIB = 7; - - /** - * GIF image format - */ - public static final int PICTURE_TYPE_GIF = 8; - - /** - * Tag Image File (.tiff) - */ - public static final int PICTURE_TYPE_TIFF = 9; - - /** - * Encapsulated Postscript (.eps) - */ - public static final int PICTURE_TYPE_EPS = 10; - - - /** - * Windows Bitmap (.bmp) - */ - public static final int PICTURE_TYPE_BMP = 11; - - /** - * WordPerfect graphics (.wpg) - */ - public static final int PICTURE_TYPE_WPG = 12; -} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/IBody.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/IBody.java deleted file mode 100644 index e7196d9a8..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/IBody.java +++ /dev/null @@ -1,136 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xwpf.usermodel; - -import java.util.List; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.xmlbeans.XmlCursor; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTc; - -/** - *

    An IBody represents the different parts of the document which - * can contain collections of Paragraphs and Tables. It provides a - * common way to work with these and their contents.

    - *

    Typically, this is something like a XWPFDocument, or one of - * the parts in it like XWPFHeader, XWPFFooter, XWPFTableCell - *

    - */ -public interface IBody { - /** - * returns the Part, to which the body belongs, which you need for adding relationship to other parts - * Actually it is needed of the class XWPFTableCell. Because you have to know to which part the tableCell - * belongs. - * - * @return the Part, to which the body belongs - */ - public POIXMLDocumentPart getPart(); - - /** - * get the PartType of the body, for example - * DOCUMENT, HEADER, FOOTER, FOOTNOTE, - * - * @return the PartType of the body - */ - public BodyType getPartType(); - - /** - * Returns an Iterator with paragraphs and tables, - * in the order that they occur in the text. - */ - public List getBodyElements(); - - /** - * Returns the paragraph(s) that holds - * the text of the header or footer. - */ - public List getParagraphs(); - - /** - * Return the table(s) that holds the text - * of the IBodyPart, for complex cases - * where a paragraph isn't used. - */ - public List getTables(); - - /** - * if there is a corresponding {@link XWPFParagraph} of the parameter ctTable in the paragraphList of this header or footer - * the method will return this paragraph - * if there is no corresponding {@link XWPFParagraph} the method will return null - * - * @param p is instance of CTP and is searching for an XWPFParagraph - * @return null if there is no XWPFParagraph with an corresponding CTPparagraph in the paragraphList of this header or footer - * XWPFParagraph with the correspondig CTP p - */ - public XWPFParagraph getParagraph(CTP p); - - /** - * if there is a corresponding {@link XWPFTable} of the parameter ctTable in the tableList of this header - * the method will return this table - * if there is no corresponding {@link XWPFTable} the method will return null - * - * @param ctTable - */ - public XWPFTable getTable(CTTbl ctTable); - - /** - * Returns the paragraph that of position pos - */ - public XWPFParagraph getParagraphArray(int pos); - - /** - * Returns the table at position pos - */ - public XWPFTable getTableArray(int pos); - - /** - * inserts a new paragraph at position of the cursor - * - * @param cursor - */ - public XWPFParagraph insertNewParagraph(XmlCursor cursor); - - /** - * inserts a new Table at the cursor position. - * - * @param cursor - */ - public XWPFTable insertNewTbl(XmlCursor cursor); - - /** - * inserts a new Table at position pos - * - * @param pos - * @param table - */ - void insertTable(int pos, XWPFTable table); - - /** - * returns the TableCell to which the Table belongs - * - * @param cell - */ - public XWPFTableCell getTableCell(CTTc cell); - - /** - * Return XWPFDocument - */ - public XWPFDocument getXWPFDocument(); -} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/IBodyElement.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/IBodyElement.java deleted file mode 100644 index 11020f444..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/IBodyElement.java +++ /dev/null @@ -1,35 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xwpf.usermodel; - -import org.apache.poi.POIXMLDocumentPart; - -/** - * 9 Jan 2010 - * - * @author Philipp Epp - */ -public interface IBodyElement { - IBody getBody(); - - POIXMLDocumentPart getPart(); - - BodyType getPartType(); - - BodyElementType getElementType(); -} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/ICell.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/ICell.java deleted file mode 100644 index d5a76429d..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/ICell.java +++ /dev/null @@ -1,27 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -/** - * Interface for anything that can be at a table cell level: - * {@link XWPFTableCell}, {@link XWPFSDTCell} - *

    - * Schematically something like this: - * <tr><tc/><tc/><sdt><tc/></sdt></tr> - */ -public interface ICell { -} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/IRunBody.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/IRunBody.java deleted file mode 100644 index fea7856d1..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/IRunBody.java +++ /dev/null @@ -1,32 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.wp.usermodel.Paragraph; - -/** - * Simple interface describing both {@link XWPFParagraph} - * and {@link XWPFSDT} - *

    - * TODO Should this be based on / extend {@link Paragraph}? - */ -public interface IRunBody { - public XWPFDocument getDocument(); - - public POIXMLDocumentPart getPart(); -} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/IRunElement.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/IRunElement.java deleted file mode 100644 index e8d1b83e7..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/IRunElement.java +++ /dev/null @@ -1,29 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -import org.apache.poi.wp.usermodel.CharacterRun; - -/** - * Common interface for things that can occur - * where a run (text with common stylings) can, - * eg {@link XWPFRun} or {@link XWPFSDT}. - * TODO More methods to follow shortly! - *

    - * TODO Make this based on {@link CharacterRun} - */ -public interface IRunElement {} \ No newline at end of file diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/ISDTContent.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/ISDTContent.java deleted file mode 100644 index dad119e00..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/ISDTContent.java +++ /dev/null @@ -1,34 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - - -/** - * Experimental interface to offer rudimentary read-only processing of - * of the contentblock of an SDT/ContentControl. - *

    - *

    - *

    - * WARNING - APIs expected to change rapidly - */ -public interface ISDTContent { - - public String getText(); - - public String toString(); - -} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/ISDTContents.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/ISDTContents.java deleted file mode 100644 index 66922b837..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/ISDTContents.java +++ /dev/null @@ -1,25 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -/** - * Interface for anything that can be within an SDT: - * {@link XWPFRun}, {@link XWPFTable}, {@link XWPFParagraph}, - * {@link XWPFSDT} etc - */ -public interface ISDTContents { -} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/LineSpacingRule.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/LineSpacingRule.java deleted file mode 100644 index 10a34418f..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/LineSpacingRule.java +++ /dev/null @@ -1,76 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -import java.util.HashMap; -import java.util.Map; - -/** - * Specifies the logic which shall be used to calculate the line spacing of the - * parent object when it is displayed in the document. - * - * @author Gisella Bronzetti - */ -public enum LineSpacingRule { - - /** - * Specifies that the line spacing of the parent object shall be - * automatically determined by the size of its contents, with no - * predetermined minimum or maximum size. - */ - - AUTO(1), - - /** - * Specifies that the height of the line shall be exactly the value - * specified, regardless of the size of the contents If the contents are too - * large for the specified height, then they shall be clipped as necessary. - */ - EXACT(2), - - /** - * Specifies that the height of the line shall be at least the value - * specified, but may be expanded to fit its content as needed. - */ - AT_LEAST(3); - - - private static Map imap = new HashMap(); - - static { - for (LineSpacingRule p : values()) { - imap.put(p.getValue(), p); - } - } - - private final int value; - - private LineSpacingRule(int val) { - value = val; - } - - public static LineSpacingRule valueOf(int type) { - LineSpacingRule lineType = imap.get(type); - if (lineType == null) - throw new IllegalArgumentException("Unknown line type: " + type); - return lineType; - } - - public int getValue() { - return value; - } -} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/ParagraphAlignment.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/ParagraphAlignment.java deleted file mode 100644 index f39d53350..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/ParagraphAlignment.java +++ /dev/null @@ -1,67 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xwpf.usermodel; - -import java.util.HashMap; -import java.util.Map; - -/** - * Specifies all types of alignment which are available to be applied to objects in a - * WordprocessingML document - * - * @author Yegor Kozlov - */ -public enum ParagraphAlignment { - //YK: TODO document each alignment option - - LEFT(1), - CENTER(2), - RIGHT(3), - BOTH(4), - MEDIUM_KASHIDA(5), - DISTRIBUTE(6), - NUM_TAB(7), - HIGH_KASHIDA(8), - LOW_KASHIDA(9), - THAI_DISTRIBUTE(10); - - private static Map imap = new HashMap(); - - static { - for (ParagraphAlignment p : values()) { - imap.put(p.getValue(), p); - } - } - - private final int value; - - private ParagraphAlignment(int val) { - value = val; - } - - public static ParagraphAlignment valueOf(int type) { - ParagraphAlignment err = imap.get(type); - if (err == null) throw new IllegalArgumentException("Unknown paragraph alignment: " + type); - return err; - } - - public int getValue() { - return value; - } - -} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/PositionInParagraph.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/PositionInParagraph.java deleted file mode 100644 index f0f2d316a..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/PositionInParagraph.java +++ /dev/null @@ -1,63 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xwpf.usermodel; - - -/** - * postion of a character in a paragrapho - * 1st RunPositon - * 2nd TextPosition - * 3rd CharacterPosition - */ -public class PositionInParagraph { - private int posRun = 0, posText = 0, posChar = 0; - - public PositionInParagraph() { - } - - public PositionInParagraph(int posRun, int posText, int posChar) { - this.posRun = posRun; - this.posChar = posChar; - this.posText = posText; - } - - public int getRun() { - return posRun; - } - - public void setRun(int beginRun) { - this.posRun = beginRun; - } - - public int getText() { - return posText; - } - - public void setText(int beginText) { - this.posText = beginText; - } - - public int getChar() { - return posChar; - } - - public void setChar(int beginChar) { - this.posChar = beginChar; - } - -} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/TOC.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/TOC.java deleted file mode 100644 index e7e9b8e98..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/TOC.java +++ /dev/null @@ -1,123 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -import java.math.BigInteger; - -import org.apache.poi.util.Internal; -import org.apache.poi.util.LocaleUtil; -import org.apache.xmlbeans.impl.xb.xmlschema.SpaceAttribute.Space; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDecimalNumber; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFonts; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPPr; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPr; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtBlock; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtContentBlock; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtEndPr; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtPr; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTabStop; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTabs; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTText; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STFldCharType; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STOnOff; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTabJc; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTabTlc; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTheme; - -public class TOC { - - CTSdtBlock block; - - public TOC() { - this(CTSdtBlock.Factory.newInstance()); - } - - public TOC(CTSdtBlock block) { - this.block = block; - CTSdtPr sdtPr = block.addNewSdtPr(); - CTDecimalNumber id = sdtPr.addNewId(); - id.setVal(new BigInteger("4844945")); - sdtPr.addNewDocPartObj().addNewDocPartGallery().setVal("Table of contents"); - CTSdtEndPr sdtEndPr = block.addNewSdtEndPr(); - CTRPr rPr = sdtEndPr.addNewRPr(); - CTFonts fonts = rPr.addNewRFonts(); - fonts.setAsciiTheme(STTheme.MINOR_H_ANSI); - fonts.setEastAsiaTheme(STTheme.MINOR_H_ANSI); - fonts.setHAnsiTheme(STTheme.MINOR_H_ANSI); - fonts.setCstheme(STTheme.MINOR_BIDI); - rPr.addNewB().setVal(STOnOff.OFF); - rPr.addNewBCs().setVal(STOnOff.OFF); - rPr.addNewColor().setVal("auto"); - rPr.addNewSz().setVal(new BigInteger("24")); - rPr.addNewSzCs().setVal(new BigInteger("24")); - CTSdtContentBlock content = block.addNewSdtContent(); - CTP p = content.addNewP(); - p.setRsidR("00EF7E24".getBytes(LocaleUtil.CHARSET_1252)); - p.setRsidRDefault("00EF7E24".getBytes(LocaleUtil.CHARSET_1252)); - p.addNewPPr().addNewPStyle().setVal("TOCHeading"); - p.addNewR().addNewT().setStringValue("Table of Contents"); - } - - @Internal - public CTSdtBlock getBlock() { - return this.block; - } - - public void addRow(int level, String title, int page, String bookmarkRef) { - CTSdtContentBlock contentBlock = this.block.getSdtContent(); - CTP p = contentBlock.addNewP(); - p.setRsidR("00EF7E24".getBytes(LocaleUtil.CHARSET_1252)); - p.setRsidRDefault("00EF7E24".getBytes(LocaleUtil.CHARSET_1252)); - CTPPr pPr = p.addNewPPr(); - pPr.addNewPStyle().setVal("TOC" + level); - CTTabs tabs = pPr.addNewTabs(); - CTTabStop tab = tabs.addNewTab(); - tab.setVal(STTabJc.RIGHT); - tab.setLeader(STTabTlc.DOT); - tab.setPos(new BigInteger("8290")); - pPr.addNewRPr().addNewNoProof(); - CTR run = p.addNewR(); - run.addNewRPr().addNewNoProof(); - run.addNewT().setStringValue(title); - run = p.addNewR(); - run.addNewRPr().addNewNoProof(); - run.addNewTab(); - run = p.addNewR(); - run.addNewRPr().addNewNoProof(); - run.addNewFldChar().setFldCharType(STFldCharType.BEGIN); - // pageref run - run = p.addNewR(); - run.addNewRPr().addNewNoProof(); - CTText text = run.addNewInstrText(); - text.setSpace(Space.PRESERVE); - // bookmark reference - text.setStringValue(" PAGEREF _Toc" + bookmarkRef + " \\h "); - p.addNewR().addNewRPr().addNewNoProof(); - run = p.addNewR(); - run.addNewRPr().addNewNoProof(); - run.addNewFldChar().setFldCharType(STFldCharType.SEPARATE); - // page number run - run = p.addNewR(); - run.addNewRPr().addNewNoProof(); - run.addNewT().setStringValue(Integer.toString(page)); - run = p.addNewR(); - run.addNewRPr().addNewNoProof(); - run.addNewFldChar().setFldCharType(STFldCharType.END); - } -} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/TextAlignment.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/TextAlignment.java deleted file mode 100644 index b8511a3bb..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/TextAlignment.java +++ /dev/null @@ -1,78 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -import java.util.HashMap; -import java.util.Map; - -/** - * Specifies all types of vertical alignment which are available to be applied to of all text - * on each line displayed within a paragraph. - * - * @author Gisella Bronzetti - */ -public enum TextAlignment { - /** - * Specifies that all text in the parent object shall be - * aligned to the top of each character when displayed - */ - TOP(1), - /** - * Specifies that all text in the parent object shall be - * aligned to the center of each character when displayed. - */ - CENTER(2), - /** - * Specifies that all text in the parent object shall be - * aligned to the baseline of each character when displayed. - */ - BASELINE(3), - /** - * Specifies that all text in the parent object shall be - * aligned to the bottom of each character when displayed. - */ - BOTTOM(4), - /** - * Specifies that all text in the parent object shall be - * aligned automatically when displayed. - */ - AUTO(5); - - private static Map imap = new HashMap(); - - static { - for (TextAlignment p : values()) { - imap.put(p.getValue(), p); - } - } - - private final int value; - - private TextAlignment(int val) { - value = val; - } - - public static TextAlignment valueOf(int type) { - TextAlignment align = imap.get(type); - if (align == null) throw new IllegalArgumentException("Unknown text alignment: " + type); - return align; - } - - public int getValue() { - return value; - } -} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/TextSegement.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/TextSegement.java deleted file mode 100644 index 46b272703..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/TextSegement.java +++ /dev/null @@ -1,99 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - - -/** - * saves the begin and end position of a text in a Paragraph - */ -public class TextSegement { - private PositionInParagraph beginPos; - private PositionInParagraph endPos; - - public TextSegement() { - this.beginPos = new PositionInParagraph(); - this.endPos = new PositionInParagraph(); - } - - public TextSegement(int beginRun, int endRun, int beginText, int endText, int beginChar, int endChar) { - PositionInParagraph beginPos = new PositionInParagraph(beginRun, beginText, beginChar); - PositionInParagraph endPos = new PositionInParagraph(endRun, endText, endChar); - this.beginPos = beginPos; - this.endPos = endPos; - } - - public TextSegement(PositionInParagraph beginPos, PositionInParagraph endPos) { - this.beginPos = beginPos; - this.endPos = endPos; - } - - public PositionInParagraph getBeginPos() { - return beginPos; - } - - public PositionInParagraph getEndPos() { - return endPos; - } - - public int getBeginRun() { - return beginPos.getRun(); - } - - public void setBeginRun(int beginRun) { - beginPos.setRun(beginRun); - } - - public int getBeginText() { - return beginPos.getText(); - } - - public void setBeginText(int beginText) { - beginPos.setText(beginText); - } - - public int getBeginChar() { - return beginPos.getChar(); - } - - public void setBeginChar(int beginChar) { - beginPos.setChar(beginChar); - } - - public int getEndRun() { - return endPos.getRun(); - } - - public void setEndRun(int endRun) { - endPos.setRun(endRun); - } - - public int getEndText() { - return endPos.getText(); - } - - public void setEndText(int endText) { - endPos.setText(endText); - } - - public int getEndChar() { - return endPos.getChar(); - } - - public void setEndChar(int endChar) { - endPos.setChar(endChar); - } -} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/UnderlinePatterns.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/UnderlinePatterns.java deleted file mode 100644 index 132444796..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/UnderlinePatterns.java +++ /dev/null @@ -1,163 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -import java.util.HashMap; -import java.util.Map; - -/** - * Specifies the types of patterns which may be used to create the underline - * applied beneath the text in a run. - * - * @author Gisella Bronzetti - */ -public enum UnderlinePatterns { - - /** - * Specifies an underline consisting of a single line beneath all characters - * in this run. - */ - SINGLE(1), - - /** - * Specifies an underline consisting of a single line beneath all non-space - * characters in the run. There shall be no underline beneath any space - * character (breaking or non-breaking). - */ - WORDS(2), - - /** - * Specifies an underline consisting of two lines beneath all characters in - * this run - */ - DOUBLE(3), - - /** - * Specifies an underline consisting of a single thick line beneath all - * characters in this run. - */ - THICK(4), - - /** - * Specifies an underline consisting of a series of dot characters beneath - * all characters in this run. - */ - DOTTED(5), - - /** - * Specifies an underline consisting of a series of thick dot characters - * beneath all characters in this run. - */ - DOTTED_HEAVY(6), - - /** - * Specifies an underline consisting of a dashed line beneath all characters - * in this run. - */ - DASH(7), - - /** - * Specifies an underline consisting of a series of thick dashes beneath all - * characters in this run. - */ - DASHED_HEAVY(8), - - /** - * Specifies an underline consisting of long dashed characters beneath all - * characters in this run. - */ - DASH_LONG(9), - - /** - * Specifies an underline consisting of thick long dashed characters beneath - * all characters in this run. - */ - DASH_LONG_HEAVY(10), - - /** - * Specifies an underline consisting of a series of dash, dot characters - * beneath all characters in this run. - */ - DOT_DASH(11), - - /** - * Specifies an underline consisting of a series of thick dash, dot - * characters beneath all characters in this run. - */ - DASH_DOT_HEAVY(12), - - /** - * Specifies an underline consisting of a series of dash, dot, dot - * characters beneath all characters in this run. - */ - DOT_DOT_DASH(13), - - /** - * Specifies an underline consisting of a series of thick dash, dot, dot - * characters beneath all characters in this run. - */ - DASH_DOT_DOT_HEAVY(14), - - /** - * Specifies an underline consisting of a single wavy line beneath all - * characters in this run. - */ - WAVE(15), - - /** - * Specifies an underline consisting of a single thick wavy line beneath all - * characters in this run. - */ - WAVY_HEAVY(16), - - /** - * Specifies an underline consisting of a pair of wavy lines beneath all - * characters in this run. - */ - WAVY_DOUBLE(17), - - /** - * Specifies no underline beneath this run. - */ - NONE(18); - - private static Map imap = new HashMap(); - - static { - for (UnderlinePatterns p : values()) { - imap.put(p.getValue(), p); - } - } - - private final int value; - - private UnderlinePatterns(int val) { - value = val; - } - - public static UnderlinePatterns valueOf(int type) { - UnderlinePatterns align = imap.get(type); - if (align == null) - throw new IllegalArgumentException("Unknown underline pattern: " - + type); - return align; - } - - public int getValue() { - return value; - } -} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/VerticalAlign.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/VerticalAlign.java deleted file mode 100644 index 57b279716..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/VerticalAlign.java +++ /dev/null @@ -1,75 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -import java.util.HashMap; -import java.util.Map; - -/** - * Specifies possible values for the alignment of the contents of this run in - * relation to the default appearance of the run's text. This allows the text to - * be repositioned as subscript or superscript without altering the font size of - * the run properties. - * - * @author Gisella Bronzetti - */ -public enum VerticalAlign { - - /** - * Specifies that the text in the parent run shall be located at the - * baseline and presented in the same size as surrounding text. - */ - BASELINE(1), - /** - * Specifies that this text should be subscript. This setting shall lower - * the text in this run below the baseline and change it to a smaller size, - * if a smaller size is available. - */ - SUPERSCRIPT(2), - /** - * Specifies that this text should be superscript. This setting shall raise - * the text in this run above the baseline and change it to a smaller size, - * if a smaller size is available. - */ - SUBSCRIPT(3); - - private static Map imap = new HashMap(); - - static { - for (VerticalAlign p : values()) { - imap.put(p.getValue(), p); - } - } - - private final int value; - - private VerticalAlign(int val) { - value = val; - } - - public static VerticalAlign valueOf(int type) { - VerticalAlign align = imap.get(type); - if (align == null) - throw new IllegalArgumentException("Unknown vertical alignment: " - + type); - return align; - } - - public int getValue() { - return value; - } -} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFAbstractNum.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFAbstractNum.java deleted file mode 100644 index c8c3caf00..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFAbstractNum.java +++ /dev/null @@ -1,60 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xwpf.usermodel; - -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTAbstractNum; - -/** - * @author Philipp Epp - */ -public class XWPFAbstractNum { - protected XWPFNumbering numbering; - private CTAbstractNum ctAbstractNum; - - protected XWPFAbstractNum() { - this.ctAbstractNum = null; - this.numbering = null; - - } - - public XWPFAbstractNum(CTAbstractNum abstractNum) { - this.ctAbstractNum = abstractNum; - } - - public XWPFAbstractNum(CTAbstractNum ctAbstractNum, XWPFNumbering numbering) { - this.ctAbstractNum = ctAbstractNum; - this.numbering = numbering; - } - - public CTAbstractNum getAbstractNum() { - return ctAbstractNum; - } - - public XWPFNumbering getNumbering() { - return numbering; - } - - public void setNumbering(XWPFNumbering numbering) { - this.numbering = numbering; - } - - public CTAbstractNum getCTAbstractNum() { - return ctAbstractNum; - } - -} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFComment.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFComment.java deleted file mode 100644 index 5f7fa5d8d..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFComment.java +++ /dev/null @@ -1,54 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTComment; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP; - -/** - * Sketch of XWPF comment class - * - * @author Yury Batrakov (batrakov at gmail.com) - */ -public class XWPFComment { - protected String id; - protected String author; - protected StringBuffer text; - - public XWPFComment(CTComment comment, XWPFDocument document) { - text = new StringBuffer(); - id = comment.getId().toString(); - author = comment.getAuthor(); - - for (CTP ctp : comment.getPArray()) { - XWPFParagraph p = new XWPFParagraph(ctp, document); - text.append(p.getText()); - } - } - - public String getId() { - return id; - } - - public String getAuthor() { - return author; - } - - public String getText() { - return text.toString(); - } -} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFDefaultParagraphStyle.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFDefaultParagraphStyle.java deleted file mode 100644 index 9a1a973e8..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFDefaultParagraphStyle.java +++ /dev/null @@ -1,42 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xwpf.usermodel; - -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPPr; - -/** - * Default Paragraph style, from which other styles will override - * TODO Share logic with {@link XWPFParagraph} which also uses CTPPr - */ -public class XWPFDefaultParagraphStyle { - private CTPPr ppr; - - public XWPFDefaultParagraphStyle(CTPPr ppr) { - this.ppr = ppr; - } - - protected CTPPr getPPr() { - return ppr; - } - - public int getSpacingAfter() { - if (ppr.isSetSpacing()) - return ppr.getSpacing().getAfter().intValue(); - return -1; - } -} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFDefaultRunStyle.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFDefaultRunStyle.java deleted file mode 100644 index 60c2f272d..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFDefaultRunStyle.java +++ /dev/null @@ -1,42 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xwpf.usermodel; - -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPr; - -/** - * Default Character Run style, from which other styles will override - * TODO Share logic with {@link XWPFRun} which also uses CTRPr - */ -public class XWPFDefaultRunStyle { - private CTRPr rpr; - - public XWPFDefaultRunStyle(CTRPr rpr) { - this.rpr = rpr; - } - - protected CTRPr getRPr() { - return rpr; - } - - public int getFontSize() { - if (rpr.isSetSz()) - return rpr.getSz().getVal().intValue() / 2; - return -1; - } -} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFDocument.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFDocument.java deleted file mode 100644 index 9afde2caf..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFDocument.java +++ /dev/null @@ -1,1564 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xwpf.usermodel; - -import static org.apache.poi.POIXMLTypeLoader.DEFAULT_XML_OPTIONS; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -import javax.xml.namespace.QName; - -import org.apache.poi.POIXMLDocument; -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.POIXMLException; -import org.apache.poi.POIXMLProperties; -import org.apache.poi.POIXMLRelation; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.exceptions.OpenXML4JException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.opc.PackagePartName; -import org.apache.poi.openxml4j.opc.PackageRelationship; -import org.apache.poi.openxml4j.opc.PackageRelationshipTypes; -import org.apache.poi.openxml4j.opc.PackagingURIHelper; -import org.apache.poi.openxml4j.opc.TargetMode; -import org.apache.poi.poifs.crypt.HashAlgorithm; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.IdentifierManager; -import org.apache.poi.util.Internal; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.util.PackageHelper; -import org.apache.poi.wp.usermodel.HeaderFooterType; -import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlOptions; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.*; - -/** - *

    High(ish) level class for working with .docx files.

    - *

    - *

    This class tries to hide some of the complexity - * of the underlying file format, but as it's not a - * mature and stable API yet, certain parts of the - * XML structure come through. You'll therefore almost - * certainly need to refer to the OOXML specifications - * from - * http://www.ecma-international.org/publications/standards/Ecma-376.htm - * at some point in your use.

    - */ -public class XWPFDocument extends POIXMLDocument implements Document, IBody { - private static final POILogger LOG = POILogFactory.getLogger(XWPFDocument.class); - - protected List footers = new ArrayList(); - protected List headers = new ArrayList(); - protected List comments = new ArrayList(); - protected List hyperlinks = new ArrayList(); - protected List paragraphs = new ArrayList(); - protected List tables = new ArrayList(); - protected List contentControls = new ArrayList(); - protected List bodyElements = new ArrayList(); - protected List pictures = new ArrayList(); - protected Map> packagePictures = new HashMap>(); - protected Map endnotes = new HashMap(); - protected XWPFNumbering numbering; - protected XWPFStyles styles; - protected XWPFFootnotes footnotes; - private CTDocument1 ctDocument; - private XWPFSettings settings; - /** - * Keeps track on all id-values used in this document and included parts, like headers, footers, etc. - */ - private IdentifierManager drawingIdManager = new IdentifierManager(0L, 4294967295L); - /** - * Handles the joy of different headers/footers for different pages - */ - private XWPFHeaderFooterPolicy headerFooterPolicy; - - public XWPFDocument(OPCPackage pkg) throws IOException { - super(pkg); - - //build a tree of POIXMLDocumentParts, this document being the root - load(XWPFFactory.getInstance()); - } - - public XWPFDocument(InputStream is) throws IOException { - super(PackageHelper.open(is)); - - //build a tree of POIXMLDocumentParts, this workbook being the root - load(XWPFFactory.getInstance()); - } - - public XWPFDocument() { - super(newPackage()); - onDocumentCreate(); - } - - /** - * Create a new WordProcessingML package and setup the default minimal content - */ - protected static OPCPackage newPackage() { - try { - OPCPackage pkg = OPCPackage.create(new ByteArrayOutputStream()); - // Main part - PackagePartName corePartName = PackagingURIHelper.createPartName(XWPFRelation.DOCUMENT.getDefaultFileName()); - // Create main part relationship - pkg.addRelationship(corePartName, TargetMode.INTERNAL, PackageRelationshipTypes.CORE_DOCUMENT); - // Create main document part - pkg.createPart(corePartName, XWPFRelation.DOCUMENT.getContentType()); - - pkg.getPackageProperties().setCreatorProperty(DOCUMENT_CREATOR); - - return pkg; - } catch (Exception e) { - throw new POIXMLException(e); - } - } - - @SuppressWarnings("deprecation") - @Override - protected void onDocumentRead() throws IOException { - try { - DocumentDocument doc = DocumentDocument.Factory.parse(getPackagePart().getInputStream(), DEFAULT_XML_OPTIONS); - ctDocument = doc.getDocument(); - - initFootnotes(); - - // parse the document with cursor and add - // the XmlObject to its lists - XmlCursor cursor = ctDocument.getBody().newCursor(); - cursor.selectPath("./*"); - while (cursor.toNextSelection()) { - XmlObject o = cursor.getObject(); - if (o instanceof CTP) { - XWPFParagraph p = new XWPFParagraph((CTP) o, this); - bodyElements.add(p); - paragraphs.add(p); - } else if (o instanceof CTTbl) { - XWPFTable t = new XWPFTable((CTTbl) o, this); - bodyElements.add(t); - tables.add(t); - } else if (o instanceof CTSdtBlock) { - XWPFSDT c = new XWPFSDT((CTSdtBlock) o, this); - bodyElements.add(c); - contentControls.add(c); - } - } - cursor.dispose(); - - // Sort out headers and footers - if (doc.getDocument().getBody().getSectPr() != null) - headerFooterPolicy = new XWPFHeaderFooterPolicy(this); - - // Create for each XML-part in the Package a PartClass - for (RelationPart rp : getRelationParts()) { - POIXMLDocumentPart p = rp.getDocumentPart(); - String relation = rp.getRelationship().getRelationshipType(); - if (relation.equals(XWPFRelation.STYLES.getRelation())) { - this.styles = (XWPFStyles) p; - this.styles.onDocumentRead(); - } else if (relation.equals(XWPFRelation.NUMBERING.getRelation())) { - this.numbering = (XWPFNumbering) p; - this.numbering.onDocumentRead(); - } else if (relation.equals(XWPFRelation.FOOTER.getRelation())) { - XWPFFooter footer = (XWPFFooter) p; - footers.add(footer); - footer.onDocumentRead(); - } else if (relation.equals(XWPFRelation.HEADER.getRelation())) { - XWPFHeader header = (XWPFHeader) p; - headers.add(header); - header.onDocumentRead(); - } else if (relation.equals(XWPFRelation.COMMENT.getRelation())) { - // TODO Create according XWPFComment class, extending POIXMLDocumentPart - CommentsDocument cmntdoc = CommentsDocument.Factory.parse(p.getPackagePart().getInputStream(), DEFAULT_XML_OPTIONS); - for (CTComment ctcomment : cmntdoc.getComments().getCommentArray()) { - comments.add(new XWPFComment(ctcomment, this)); - } - } else if (relation.equals(XWPFRelation.SETTINGS.getRelation())) { - settings = (XWPFSettings) p; - settings.onDocumentRead(); - } else if (relation.equals(XWPFRelation.IMAGES.getRelation())) { - XWPFPictureData picData = (XWPFPictureData) p; - picData.onDocumentRead(); - registerPackagePictureData(picData); - pictures.add(picData); - } else if (relation.equals(XWPFRelation.GLOSSARY_DOCUMENT.getRelation())) { - // We don't currently process the glossary itself - // Until we do, we do need to load the glossary child parts of it - for (POIXMLDocumentPart gp : p.getRelations()) { - // Trigger the onDocumentRead for all the child parts - // Otherwise we'll hit issues on Styles, Settings etc on save - // TODO: Refactor this to not need to access protected method - // from other package! Remove the static helper method once fixed!!! - POIXMLDocumentPart._invokeOnDocumentRead(gp); - } - } - } - initHyperlinks(); - } catch (XmlException e) { - throw new POIXMLException(e); - } - } - - private void initHyperlinks() { - // Get the hyperlinks - // TODO: make me optional/separated in private function - try { - Iterator relIter = - getPackagePart().getRelationshipsByType(XWPFRelation.HYPERLINK.getRelation()).iterator(); - while (relIter.hasNext()) { - PackageRelationship rel = relIter.next(); - hyperlinks.add(new XWPFHyperlink(rel.getId(), rel.getTargetURI().toString())); - } - } catch (InvalidFormatException e) { - throw new POIXMLException(e); - } - } - - private void initFootnotes() throws XmlException, IOException { - for (RelationPart rp : getRelationParts()) { - POIXMLDocumentPart p = rp.getDocumentPart(); - String relation = rp.getRelationship().getRelationshipType(); - if (relation.equals(XWPFRelation.FOOTNOTE.getRelation())) { - this.footnotes = (XWPFFootnotes) p; - this.footnotes.onDocumentRead(); - } else if (relation.equals(XWPFRelation.ENDNOTE.getRelation())) { - EndnotesDocument endnotesDocument = EndnotesDocument.Factory.parse(p.getPackagePart().getInputStream(), DEFAULT_XML_OPTIONS); - - for (CTFtnEdn ctFtnEdn : endnotesDocument.getEndnotes().getEndnoteArray()) { - endnotes.put(ctFtnEdn.getId().intValue(), new XWPFFootnote(this, ctFtnEdn)); - } - } - } - } - - /** - * Create a new CTWorkbook with all values set to default - */ - @Override - protected void onDocumentCreate() { - ctDocument = CTDocument1.Factory.newInstance(); - ctDocument.addNewBody(); - - settings = (XWPFSettings) createRelationship(XWPFRelation.SETTINGS, XWPFFactory.getInstance()); - - POIXMLProperties.ExtendedProperties expProps = getProperties().getExtendedProperties(); - expProps.getUnderlyingProperties().setApplication(DOCUMENT_CREATOR); - } - - /** - * Returns the low level document base object - */ - @Internal - public CTDocument1 getDocument() { - return ctDocument; - } - - IdentifierManager getDrawingIdManager() { - return drawingIdManager; - } - - /** - * returns an Iterator with paragraphs and tables - * - * @see org.apache.poi.xwpf.usermodel.IBody#getBodyElements() - */ - @Override - public List getBodyElements() { - return Collections.unmodifiableList(bodyElements); - } - - public Iterator getBodyElementsIterator() { - return bodyElements.iterator(); - } - - /** - * @see org.apache.poi.xwpf.usermodel.IBody#getParagraphs() - */ - @Override - public List getParagraphs() { - return Collections.unmodifiableList(paragraphs); - } - - /** - * @see org.apache.poi.xwpf.usermodel.IBody#getTables() - */ - @Override - public List getTables() { - return Collections.unmodifiableList(tables); - } - - /** - * @see org.apache.poi.xwpf.usermodel.IBody#getTableArray(int) - */ - @Override - public XWPFTable getTableArray(int pos) { - if (pos >= 0 && pos < tables.size()) { - return tables.get(pos); - } - return null; - } - - /** - * @return the list of footers - */ - public List getFooterList() { - return Collections.unmodifiableList(footers); - } - - public XWPFFooter getFooterArray(int pos) { - if(pos >=0 && pos < footers.size()) { - return footers.get(pos); - } - return null; - } - - /** - * @return the list of headers - */ - public List getHeaderList() { - return Collections.unmodifiableList(headers); - } - - public XWPFHeader getHeaderArray(int pos) { - if(pos >=0 && pos < headers.size()) { - return headers.get(pos); - } - return null; - } - - public String getTblStyle(XWPFTable table) { - return table.getStyleID(); - } - - public XWPFHyperlink getHyperlinkByID(String id) { - for (XWPFHyperlink link : hyperlinks) { - if (link.getId().equals(id)) - return link; - } - - return null; - } - - public XWPFFootnote getFootnoteByID(int id) { - if (footnotes == null) return null; - return footnotes.getFootnoteById(id); - } - - public XWPFFootnote getEndnoteByID(int id) { - if (endnotes == null) return null; - return endnotes.get(id); - } - - public List getFootnotes() { - if (footnotes == null) { - return Collections.emptyList(); - } - return footnotes.getFootnotesList(); - } - - public XWPFHyperlink[] getHyperlinks() { - return hyperlinks.toArray(new XWPFHyperlink[hyperlinks.size()]); - } - - public XWPFComment getCommentByID(String id) { - for (XWPFComment comment : comments) { - if (comment.getId().equals(id)) - return comment; - } - - return null; - } - - public XWPFComment[] getComments() { - return comments.toArray(new XWPFComment[comments.size()]); - } - - /** - * Get the document part that's defined as the - * given relationship of the core document. - */ - public PackagePart getPartById(String id) { - try { - PackagePart corePart = getCorePart(); - return corePart.getRelatedPart(corePart.getRelationship(id)); - } catch (InvalidFormatException e) { - throw new IllegalArgumentException(e); - } - } - - /** - * Returns the policy on headers and footers, which - * also provides a way to get at them. - */ - public XWPFHeaderFooterPolicy getHeaderFooterPolicy() { - return headerFooterPolicy; - } - public XWPFHeaderFooterPolicy createHeaderFooterPolicy() { - if (headerFooterPolicy == null) { -// if (! ctDocument.getBody().isSetSectPr()) { -// ctDocument.getBody().addNewSectPr(); -// } - headerFooterPolicy = new XWPFHeaderFooterPolicy(this); - } - return headerFooterPolicy; - } - - /** - * Create a header of the given type - * - * @param type {@link HeaderFooterType} enum - * @return object of type {@link XWPFHeader} - */ - public XWPFHeader createHeader(HeaderFooterType type) { - XWPFHeaderFooterPolicy hfPolicy = createHeaderFooterPolicy(); - // TODO this needs to be migrated out into section code - if (type == HeaderFooterType.FIRST) { - CTSectPr ctSectPr = getSection(); - if (ctSectPr.isSetTitlePg() == false) { - CTOnOff titlePg = ctSectPr.addNewTitlePg(); - titlePg.setVal(STOnOff.ON); - } - // } else if (type == HeaderFooterType.EVEN) { - // TODO Add support for Even/Odd headings and footers - } - return hfPolicy.createHeader(STHdrFtr.Enum.forInt(type.toInt())); - } - - - /** - * Create a footer of the given type - * - * @param type {@link HeaderFooterType} enum - * @return object of type {@link XWPFFooter} - */ - public XWPFFooter createFooter(HeaderFooterType type) { - XWPFHeaderFooterPolicy hfPolicy = createHeaderFooterPolicy(); - // TODO this needs to be migrated out into section code - if (type == HeaderFooterType.FIRST) { - CTSectPr ctSectPr = getSection(); - if (ctSectPr.isSetTitlePg() == false) { - CTOnOff titlePg = ctSectPr.addNewTitlePg(); - titlePg.setVal(STOnOff.ON); - } - // } else if (type == HeaderFooterType.EVEN) { - // TODO Add support for Even/Odd headings and footers - } - return hfPolicy.createFooter(STHdrFtr.Enum.forInt(type.toInt())); - } - - /** - * Return the {@link CTSectPr} object that corresponds with the - * last section in this document. - * - * @return {@link CTSectPr} object - */ - private CTSectPr getSection() { - CTBody ctBody = getDocument().getBody(); - return (ctBody.isSetSectPr() ? - ctBody.getSectPr() : - ctBody.addNewSectPr()); - } - - /** - * Returns the styles object used - */ - @Internal - public CTStyles getStyle() throws XmlException, IOException { - PackagePart[] parts; - try { - parts = getRelatedByType(XWPFRelation.STYLES.getRelation()); - } catch (InvalidFormatException e) { - throw new IllegalStateException(e); - } - if (parts.length != 1) { - throw new IllegalStateException("Expecting one Styles document part, but found " + parts.length); - } - - StylesDocument sd = StylesDocument.Factory.parse(parts[0].getInputStream(), DEFAULT_XML_OPTIONS); - return sd.getStyles(); - } - - /** - * Get the document's embedded files. - */ - @Override - public List getAllEmbedds() throws OpenXML4JException { - List embedds = new LinkedList(); - - // Get the embeddings for the workbook - PackagePart part = getPackagePart(); - for (PackageRelationship rel : getPackagePart().getRelationshipsByType(OLE_OBJECT_REL_TYPE)) { - embedds.add(part.getRelatedPart(rel)); - } - - for (PackageRelationship rel : getPackagePart().getRelationshipsByType(PACK_OBJECT_REL_TYPE)) { - embedds.add(part.getRelatedPart(rel)); - } - - return embedds; - } - - /** - * Finds that for example the 2nd entry in the body list is the 1st paragraph - */ - private int getBodyElementSpecificPos(int pos, List list) { - // If there's nothing to find, skip it - if (list.size() == 0) { - return -1; - } - - if (pos >= 0 && pos < bodyElements.size()) { - // Ensure the type is correct - IBodyElement needle = bodyElements.get(pos); - if (needle.getElementType() != list.get(0).getElementType()) { - // Wrong type - return -1; - } - - // Work back until we find it - int startPos = Math.min(pos, list.size() - 1); - for (int i = startPos; i >= 0; i--) { - if (list.get(i) == needle) { - return i; - } - } - } - - // Couldn't be found - return -1; - } - - /** - * Look up the paragraph at the specified position in the body elements list - * and return this paragraphs position in the paragraphs list - * - * @param pos The position of the relevant paragraph in the body elements - * list - * @return the position of the paragraph in the paragraphs list, if there is - * a paragraph at the position in the bodyelements list. Else it - * will return -1 - */ - public int getParagraphPos(int pos) { - return getBodyElementSpecificPos(pos, paragraphs); - } - - /** - * get with the position of a table in the bodyelement array list - * the position of this table in the table array list - * - * @param pos position of the table in the bodyelement array list - * @return if there is a table at the position in the bodyelement array list, - * else it will return null. - */ - public int getTablePos(int pos) { - return getBodyElementSpecificPos(pos, tables); - } - - /** - * Add a new paragraph at position of the cursor. The cursor must be on the - * {@link org.apache.xmlbeans.XmlCursor.TokenType#START} tag of an subelement - * of the documents body. When this method is done, the cursor passed as - * parameter points to the {@link org.apache.xmlbeans.XmlCursor.TokenType#END} - * of the newly inserted paragraph. - * - * @param cursor - * @return the {@link XWPFParagraph} object representing the newly inserted - * CTP object - */ - @Override - public XWPFParagraph insertNewParagraph(XmlCursor cursor) { - if (isCursorInBody(cursor)) { - String uri = CTP.type.getName().getNamespaceURI(); - /* - * TODO DO not use a coded constant, find the constant in the OOXML - * classes instead, as the child of type CT_Paragraph is defined in the - * OOXML schema as 'p' - */ - String localPart = "p"; - // creates a new Paragraph, cursor is positioned inside the new - // element - cursor.beginElement(localPart, uri); - // move the cursor to the START token to the paragraph just created - cursor.toParent(); - CTP p = (CTP) cursor.getObject(); - XWPFParagraph newP = new XWPFParagraph(p, this); - XmlObject o = null; - /* - * move the cursor to the previous element until a) the next - * paragraph is found or b) all elements have been passed - */ - while (!(o instanceof CTP) && (cursor.toPrevSibling())) { - o = cursor.getObject(); - } - /* - * if the object that has been found is a) not a paragraph or b) is - * the paragraph that has just been inserted, as the cursor in the - * while loop above was not moved as there were no other siblings, - * then the paragraph that was just inserted is the first paragraph - * in the body. Otherwise, take the previous paragraph and calculate - * the new index for the new paragraph. - */ - if ((!(o instanceof CTP)) || (CTP) o == p) { - paragraphs.add(0, newP); - } else { - int pos = paragraphs.indexOf(getParagraph((CTP) o)) + 1; - paragraphs.add(pos, newP); - } - - /* - * create a new cursor, that points to the START token of the just - * inserted paragraph - */ - XmlCursor newParaPos = p.newCursor(); - try { - /* - * Calculate the paragraphs index in the list of all body - * elements - */ - int i = 0; - cursor.toCursor(newParaPos); - while (cursor.toPrevSibling()) { - o = cursor.getObject(); - if (o instanceof CTP || o instanceof CTTbl) - i++; - } - bodyElements.add(i, newP); - cursor.toCursor(newParaPos); - cursor.toEndToken(); - return newP; - } finally { - newParaPos.dispose(); - } - } - return null; - } - - @Override - public XWPFTable insertNewTbl(XmlCursor cursor) { - if (isCursorInBody(cursor)) { - String uri = CTTbl.type.getName().getNamespaceURI(); - String localPart = "tbl"; - cursor.beginElement(localPart, uri); - cursor.toParent(); - CTTbl t = (CTTbl) cursor.getObject(); - XWPFTable newT = new XWPFTable(t, this); - XmlObject o = null; - while (!(o instanceof CTTbl) && (cursor.toPrevSibling())) { - o = cursor.getObject(); - } - if (!(o instanceof CTTbl)) { - tables.add(0, newT); - } else { - int pos = tables.indexOf(getTable((CTTbl) o)) + 1; - tables.add(pos, newT); - } - int i = 0; - XmlCursor tableCursor = t.newCursor(); - try { - cursor.toCursor(tableCursor); - while (cursor.toPrevSibling()) { - o = cursor.getObject(); - if (o instanceof CTP || o instanceof CTTbl) - i++; - } - bodyElements.add(i, newT); - cursor.toCursor(tableCursor); - cursor.toEndToken(); - return newT; - } finally { - tableCursor.dispose(); - } - } - return null; - } - - /** - * verifies that cursor is on the right position - * - * @param cursor - */ - private boolean isCursorInBody(XmlCursor cursor) { - XmlCursor verify = cursor.newCursor(); - verify.toParent(); - boolean result = (verify.getObject() == this.ctDocument.getBody()); - verify.dispose(); - return result; - } - - private int getPosOfBodyElement(IBodyElement needle) { - BodyElementType type = needle.getElementType(); - IBodyElement current; - for (int i = 0; i < bodyElements.size(); i++) { - current = bodyElements.get(i); - if (current.getElementType() == type) { - if (current.equals(needle)) { - return i; - } - } - } - return -1; - } - - /** - * Get the position of the paragraph, within the list - * of all the body elements. - * - * @param p The paragraph to find - * @return The location, or -1 if the paragraph couldn't be found - */ - public int getPosOfParagraph(XWPFParagraph p) { - return getPosOfBodyElement(p); - } - - /** - * Get the position of the table, within the list of - * all the body elements. - * - * @param t The table to find - * @return The location, or -1 if the table couldn't be found - */ - public int getPosOfTable(XWPFTable t) { - return getPosOfBodyElement(t); - } - - /** - * commit and saves the document - */ - @Override - protected void commit() throws IOException { - XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS); - xmlOptions.setSaveSyntheticDocumentElement(new QName(CTDocument1.type.getName().getNamespaceURI(), "document")); - - PackagePart part = getPackagePart(); - OutputStream out = part.getOutputStream(); - ctDocument.save(out, xmlOptions); - out.close(); - } - - /** - * Gets the index of the relation we're trying to create - * - * @param relation - * @return i - */ - private int getRelationIndex(XWPFRelation relation) { - int i = 1; - for (RelationPart rp : getRelationParts()) { - if (rp.getRelationship().getRelationshipType().equals(relation.getRelation())) { - i++; - } - } - return i; - } - - /** - * Appends a new paragraph to this document - * - * @return a new paragraph - */ - public XWPFParagraph createParagraph() { - XWPFParagraph p = new XWPFParagraph(ctDocument.getBody().addNewP(), this); - bodyElements.add(p); - paragraphs.add(p); - return p; - } - - /** - * Creates an empty numbering if one does not already exist and sets the numbering member - * - * @return numbering - */ - public XWPFNumbering createNumbering() { - if (numbering == null) { - NumberingDocument numberingDoc = NumberingDocument.Factory.newInstance(); - - XWPFRelation relation = XWPFRelation.NUMBERING; - int i = getRelationIndex(relation); - - XWPFNumbering wrapper = (XWPFNumbering) createRelationship(relation, XWPFFactory.getInstance(), i); - wrapper.setNumbering(numberingDoc.addNewNumbering()); - numbering = wrapper; - } - - return numbering; - } - - /** - * Creates an empty styles for the document if one does not already exist - * - * @return styles - */ - public XWPFStyles createStyles() { - if (styles == null) { - StylesDocument stylesDoc = StylesDocument.Factory.newInstance(); - - XWPFRelation relation = XWPFRelation.STYLES; - int i = getRelationIndex(relation); - - XWPFStyles wrapper = (XWPFStyles) createRelationship(relation, XWPFFactory.getInstance(), i); - wrapper.setStyles(stylesDoc.addNewStyles()); - styles = wrapper; - } - - return styles; - } - - /** - * Creates an empty footnotes element for the document if one does not already exist - * - * @return footnotes - */ - public XWPFFootnotes createFootnotes() { - if (footnotes == null) { - FootnotesDocument footnotesDoc = FootnotesDocument.Factory.newInstance(); - - XWPFRelation relation = XWPFRelation.FOOTNOTE; - int i = getRelationIndex(relation); - - XWPFFootnotes wrapper = (XWPFFootnotes) createRelationship(relation, XWPFFactory.getInstance(), i); - wrapper.setFootnotes(footnotesDoc.addNewFootnotes()); - footnotes = wrapper; - } - - return footnotes; - } - - public XWPFFootnote addFootnote(CTFtnEdn note) { - return footnotes.addFootnote(note); - } - - public XWPFFootnote addEndnote(CTFtnEdn note) { - XWPFFootnote endnote = new XWPFFootnote(this, note); - endnotes.put(note.getId().intValue(), endnote); - return endnote; - } - - /** - * remove a BodyElement from bodyElements array list - * - * @param pos - * @return true if removing was successfully, else return false - */ - public boolean removeBodyElement(int pos) { - if (pos >= 0 && pos < bodyElements.size()) { - BodyElementType type = bodyElements.get(pos).getElementType(); - if (type == BodyElementType.TABLE) { - int tablePos = getTablePos(pos); - tables.remove(tablePos); - ctDocument.getBody().removeTbl(tablePos); - } - if (type == BodyElementType.PARAGRAPH) { - int paraPos = getParagraphPos(pos); - paragraphs.remove(paraPos); - ctDocument.getBody().removeP(paraPos); - } - bodyElements.remove(pos); - return true; - } - return false; - } - - /** - * copies content of a paragraph to a existing paragraph in the list paragraphs at position pos - * - * @param paragraph - * @param pos - */ - public void setParagraph(XWPFParagraph paragraph, int pos) { - paragraphs.set(pos, paragraph); - ctDocument.getBody().setPArray(pos, paragraph.getCTP()); - /* TODO update body element, update xwpf element, verify that - * incoming paragraph belongs to this document or if not, XML was - * copied properly (namespace-abbreviations, etc.) - */ - } - - /** - * @return the LastParagraph of the document - */ - public XWPFParagraph getLastParagraph() { - int lastPos = paragraphs.toArray().length - 1; - return paragraphs.get(lastPos); - } - - /** - * Create an empty table with one row and one column as default. - * - * @return a new table - */ - public XWPFTable createTable() { - XWPFTable table = new XWPFTable(ctDocument.getBody().addNewTbl(), this); - bodyElements.add(table); - tables.add(table); - return table; - } - - /** - * Create an empty table with a number of rows and cols specified - * - * @param rows - * @param cols - * @return table - */ - public XWPFTable createTable(int rows, int cols) { - XWPFTable table = new XWPFTable(ctDocument.getBody().addNewTbl(), this, rows, cols); - bodyElements.add(table); - tables.add(table); - return table; - } - - /** - * - */ - public void createTOC() { - CTSdtBlock block = this.getDocument().getBody().addNewSdt(); - TOC toc = new TOC(block); - for (XWPFParagraph par : paragraphs) { - String parStyle = par.getStyle(); - if (parStyle != null && parStyle.startsWith("Heading")) { - try { - int level = Integer.parseInt(parStyle.substring("Heading".length())); - toc.addRow(level, par.getText(), 1, "112723803"); - } catch (NumberFormatException e) { - LOG.log(POILogger.ERROR, "can't format number in TOC heading", e); - } - } - } - } - - /** - * Replace content of table in array tables at position pos with a - * - * @param pos - * @param table - */ - public void setTable(int pos, XWPFTable table) { - tables.set(pos, table); - ctDocument.getBody().setTblArray(pos, table.getCTTbl()); - } - - /** - * Verifies that the documentProtection tag in settings.xml file
    - * specifies that the protection is enforced (w:enforcement="1")
    - *
    - * sample snippet from settings.xml - *
    -     *     <w:settings  ... >
    -     *         <w:documentProtection w:edit="readOnly" w:enforcement="1"/>
    -     * 
    - * - * @return true if documentProtection is enforced with option any - */ - public boolean isEnforcedProtection() { - return settings.isEnforcedWith(); - } - - /** - * Verifies that the documentProtection tag in settings.xml file
    - * specifies that the protection is enforced (w:enforcement="1")
    - * and that the kind of protection is readOnly (w:edit="readOnly")
    - *
    - * sample snippet from settings.xml - *
    -     *     <w:settings  ... >
    -     *         <w:documentProtection w:edit="readOnly" w:enforcement="1"/>
    -     * 
    - * - * @return true if documentProtection is enforced with option readOnly - */ - public boolean isEnforcedReadonlyProtection() { - return settings.isEnforcedWith(STDocProtect.READ_ONLY); - } - - /** - * Verifies that the documentProtection tag in settings.xml file
    - * specifies that the protection is enforced (w:enforcement="1")
    - * and that the kind of protection is forms (w:edit="forms")
    - *
    - * sample snippet from settings.xml - *
    -     *     <w:settings  ... >
    -     *         <w:documentProtection w:edit="forms" w:enforcement="1"/>
    -     * 
    - * - * @return true if documentProtection is enforced with option forms - */ - public boolean isEnforcedFillingFormsProtection() { - return settings.isEnforcedWith(STDocProtect.FORMS); - } - - /** - * Verifies that the documentProtection tag in settings.xml file
    - * specifies that the protection is enforced (w:enforcement="1")
    - * and that the kind of protection is comments (w:edit="comments")
    - *
    - * sample snippet from settings.xml - *
    -     *     <w:settings  ... >
    -     *         <w:documentProtection w:edit="comments" w:enforcement="1"/>
    -     * 
    - * - * @return true if documentProtection is enforced with option comments - */ - public boolean isEnforcedCommentsProtection() { - return settings.isEnforcedWith(STDocProtect.COMMENTS); - } - - /** - * Verifies that the documentProtection tag in settings.xml file
    - * specifies that the protection is enforced (w:enforcement="1")
    - * and that the kind of protection is trackedChanges (w:edit="trackedChanges")
    - *
    - * sample snippet from settings.xml - *
    -     *     <w:settings  ... >
    -     *         <w:documentProtection w:edit="trackedChanges" w:enforcement="1"/>
    -     * 
    - * - * @return true if documentProtection is enforced with option trackedChanges - */ - public boolean isEnforcedTrackedChangesProtection() { - return settings.isEnforcedWith(STDocProtect.TRACKED_CHANGES); - } - - public boolean isEnforcedUpdateFields() { - return settings.isUpdateFields(); - } - - /** - * Enforces the readOnly protection.
    - * In the documentProtection tag inside settings.xml file,
    - * it sets the value of enforcement to "1" (w:enforcement="1")
    - * and the value of edit to readOnly (w:edit="readOnly")
    - *
    - * sample snippet from settings.xml - *
    -     *     <w:settings  ... >
    -     *         <w:documentProtection w:edit="readOnly" w:enforcement="1"/>
    -     * 
    - */ - public void enforceReadonlyProtection() { - settings.setEnforcementEditValue(STDocProtect.READ_ONLY); - } - - /** - * Enforces the readOnly protection with a password.
    - *
    - * sample snippet from settings.xml - *
    -     *   <w:documentProtection w:edit="readOnly" w:enforcement="1"
    -     *       w:cryptProviderType="rsaAES" w:cryptAlgorithmClass="hash"
    -     *       w:cryptAlgorithmType="typeAny" w:cryptAlgorithmSid="14"
    -     *       w:cryptSpinCount="100000" w:hash="..." w:salt="...."
    -     *   />
    -     * 
    - * - * @param password the plaintext password, if null no password will be applied - * @param hashAlgo the hash algorithm - only md2, m5, sha1, sha256, sha384 and sha512 are supported. - * if null, it will default default to sha1 - */ - public void enforceReadonlyProtection(String password, HashAlgorithm hashAlgo) { - settings.setEnforcementEditValue(STDocProtect.READ_ONLY, password, hashAlgo); - } - - /** - * Enforce the Filling Forms protection.
    - * In the documentProtection tag inside settings.xml file,
    - * it sets the value of enforcement to "1" (w:enforcement="1")
    - * and the value of edit to forms (w:edit="forms")
    - *
    - * sample snippet from settings.xml - *
    -     *     <w:settings  ... >
    -     *         <w:documentProtection w:edit="forms" w:enforcement="1"/>
    -     * 
    - */ - public void enforceFillingFormsProtection() { - settings.setEnforcementEditValue(STDocProtect.FORMS); - } - - /** - * Enforce the Filling Forms protection.
    - *
    - * sample snippet from settings.xml - *
    -     *   <w:documentProtection w:edit="forms" w:enforcement="1"
    -     *       w:cryptProviderType="rsaAES" w:cryptAlgorithmClass="hash"
    -     *       w:cryptAlgorithmType="typeAny" w:cryptAlgorithmSid="14"
    -     *       w:cryptSpinCount="100000" w:hash="..." w:salt="...."
    -     *   />
    -     * 
    - * - * @param password the plaintext password, if null no password will be applied - * @param hashAlgo the hash algorithm - only md2, m5, sha1, sha256, sha384 and sha512 are supported. - * if null, it will default default to sha1 - */ - public void enforceFillingFormsProtection(String password, HashAlgorithm hashAlgo) { - settings.setEnforcementEditValue(STDocProtect.FORMS, password, hashAlgo); - } - - /** - * Enforce the Comments protection.
    - * In the documentProtection tag inside settings.xml file,
    - * it sets the value of enforcement to "1" (w:enforcement="1")
    - * and the value of edit to comments (w:edit="comments")
    - *
    - * sample snippet from settings.xml - *
    -     *     <w:settings  ... >
    -     *         <w:documentProtection w:edit="comments" w:enforcement="1"/>
    -     * 
    - */ - public void enforceCommentsProtection() { - settings.setEnforcementEditValue(STDocProtect.COMMENTS); - } - - /** - * Enforce the Comments protection.
    - *
    - * sample snippet from settings.xml - *
    -     *   <w:documentProtection w:edit="comments" w:enforcement="1"
    -     *       w:cryptProviderType="rsaAES" w:cryptAlgorithmClass="hash"
    -     *       w:cryptAlgorithmType="typeAny" w:cryptAlgorithmSid="14"
    -     *       w:cryptSpinCount="100000" w:hash="..." w:salt="...."
    -     *   />
    -     * 
    - * - * @param password the plaintext password, if null no password will be applied - * @param hashAlgo the hash algorithm - only md2, m5, sha1, sha256, sha384 and sha512 are supported. - * if null, it will default default to sha1 - */ - public void enforceCommentsProtection(String password, HashAlgorithm hashAlgo) { - settings.setEnforcementEditValue(STDocProtect.COMMENTS, password, hashAlgo); - } - - /** - * Enforce the Tracked Changes protection.
    - * In the documentProtection tag inside settings.xml file,
    - * it sets the value of enforcement to "1" (w:enforcement="1")
    - * and the value of edit to trackedChanges (w:edit="trackedChanges")
    - *
    - * sample snippet from settings.xml - *
    -     *     <w:settings  ... >
    -     *         <w:documentProtection w:edit="trackedChanges" w:enforcement="1"/>
    -     * 
    - */ - public void enforceTrackedChangesProtection() { - settings.setEnforcementEditValue(STDocProtect.TRACKED_CHANGES); - } - - /** - * Enforce the Tracked Changes protection.
    - *
    - * sample snippet from settings.xml - *
    -     *   <w:documentProtection w:edit="trackedChanges" w:enforcement="1"
    -     *       w:cryptProviderType="rsaAES" w:cryptAlgorithmClass="hash"
    -     *       w:cryptAlgorithmType="typeAny" w:cryptAlgorithmSid="14"
    -     *       w:cryptSpinCount="100000" w:hash="..." w:salt="...."
    -     *   />
    -     * 
    - * - * @param password the plaintext password, if null no password will be applied - * @param hashAlgo the hash algorithm - only md2, m5, sha1, sha256, sha384 and sha512 are supported. - * if null, it will default default to sha1 - */ - public void enforceTrackedChangesProtection(String password, HashAlgorithm hashAlgo) { - settings.setEnforcementEditValue(STDocProtect.TRACKED_CHANGES, password, hashAlgo); - } - - /** - * Validates the existing password - * - * @param password - * @return true, only if password was set and equals, false otherwise - */ - public boolean validateProtectionPassword(String password) { - return settings.validateProtectionPassword(password); - } - - /** - * Remove protection enforcement.
    - * In the documentProtection tag inside settings.xml file
    - * it sets the value of enforcement to "0" (w:enforcement="0")
    - */ - public void removeProtectionEnforcement() { - settings.removeEnforcement(); - } - - /** - * Enforces fields update on document open (in Word). - * In the settings.xml file
    - * sets the updateSettings value to true (w:updateSettings w:val="true") - *

    - * NOTICES: - *

      - *
    • Causing Word to ask on open: "This document contains fields that may refer to other files. Do you want to update the fields in this document?" - * (if "Update automatic links at open" is enabled)
    • - *
    • Flag is removed after saving with changes in Word
    • - *
    - */ - public void enforceUpdateFields() { - settings.setUpdateFields(); - } - - /** - * Check if revision tracking is turned on. - * - * @return true if revision tracking is turned on - */ - public boolean isTrackRevisions() { - return settings.isTrackRevisions(); - } - - /** - * Enable or disable revision tracking. - * - * @param enable true to turn on revision tracking, false to turn off revision tracking - */ - public void setTrackRevisions(boolean enable) { - settings.setTrackRevisions(enable); - } - - - /** - * Returns the current zoom factor in percent values, i.e. 100 is normal zoom. - * - * @return A percent value denoting the current zoom setting of this document. - */ - public long getZoomPercent() { - return settings.getZoomPercent(); - } - - /** - * Set the zoom setting as percent value, i.e. 100 is normal zoom. - * - * @param zoomPercent A percent value denoting the zoom setting for this document. - */ - public void setZoomPercent(long zoomPercent) { - settings.setZoomPercent(zoomPercent); - } - - /** - * inserts an existing XWPFTable to the arrays bodyElements and tables - * - * @param pos - * @param table - */ - @Override - public void insertTable(int pos, XWPFTable table) { - bodyElements.add(pos, table); - int i = 0; - for (CTTbl tbl : ctDocument.getBody().getTblArray()) { - if (tbl == table.getCTTbl()) { - break; - } - i++; - } - tables.add(i, table); - } - - /** - * Returns all Pictures, which are referenced from the document itself. - * - * @return a {@link List} of {@link XWPFPictureData}. The returned {@link List} is unmodifiable. Use #a - */ - public List getAllPictures() { - return Collections.unmodifiableList(pictures); - } - - /** - * @return all Pictures in this package - */ - public List getAllPackagePictures() { - List result = new ArrayList(); - Collection> values = packagePictures.values(); - for (List list : values) { - result.addAll(list); - } - return Collections.unmodifiableList(result); - } - - void registerPackagePictureData(XWPFPictureData picData) { - List list = packagePictures.get(picData.getChecksum()); - if (list == null) { - list = new ArrayList(1); - packagePictures.put(picData.getChecksum(), list); - } - if (!list.contains(picData)) { - list.add(picData); - } - } - - XWPFPictureData findPackagePictureData(byte[] pictureData, int format) { - long checksum = IOUtils.calculateChecksum(pictureData); - XWPFPictureData xwpfPicData = null; - /* - * Try to find PictureData with this checksum. Create new, if none - * exists. - */ - List xwpfPicDataList = packagePictures.get(checksum); - if (xwpfPicDataList != null) { - Iterator iter = xwpfPicDataList.iterator(); - while (iter.hasNext() && xwpfPicData == null) { - XWPFPictureData curElem = iter.next(); - if (Arrays.equals(pictureData, curElem.getData())) { - xwpfPicData = curElem; - } - } - } - return xwpfPicData; - } - - public String addPictureData(byte[] pictureData, int format) throws InvalidFormatException { - XWPFPictureData xwpfPicData = findPackagePictureData(pictureData, format); - POIXMLRelation relDesc = XWPFPictureData.RELATIONS[format]; - - if (xwpfPicData == null) { - /* Part doesn't exist, create a new one */ - int idx = getNextPicNameNumber(format); - xwpfPicData = (XWPFPictureData) createRelationship(relDesc, XWPFFactory.getInstance(), idx); - /* write bytes to new part */ - PackagePart picDataPart = xwpfPicData.getPackagePart(); - OutputStream out = null; - try { - out = picDataPart.getOutputStream(); - out.write(pictureData); - } catch (IOException e) { - throw new POIXMLException(e); - } finally { - try { - if (out != null) out.close(); - } catch (IOException e) { - // ignore - } - } - - registerPackagePictureData(xwpfPicData); - pictures.add(xwpfPicData); - - return getRelationId(xwpfPicData); - } else if (!getRelations().contains(xwpfPicData)) { - /* - * Part already existed, but was not related so far. Create - * relationship to the already existing part and update - * POIXMLDocumentPart data. - */ - // TODO add support for TargetMode.EXTERNAL relations. - RelationPart rp = addRelation(null, XWPFRelation.IMAGES, xwpfPicData); - return rp.getRelationship().getId(); - } else { - /* Part already existed, get relation id and return it */ - return getRelationId(xwpfPicData); - } - } - - public String addPictureData(InputStream is, int format) throws InvalidFormatException { - try { - byte[] data = IOUtils.toByteArray(is); - return addPictureData(data, format); - } catch (IOException e) { - throw new POIXMLException(e); - } - } - - /** - * get the next free ImageNumber - * - * @param format - * @return the next free ImageNumber - * @throws InvalidFormatException - */ - public int getNextPicNameNumber(int format) throws InvalidFormatException { - int img = getAllPackagePictures().size() + 1; - String proposal = XWPFPictureData.RELATIONS[format].getFileName(img); - PackagePartName createPartName = PackagingURIHelper.createPartName(proposal); - while (this.getPackage().getPart(createPartName) != null) { - img++; - proposal = XWPFPictureData.RELATIONS[format].getFileName(img); - createPartName = PackagingURIHelper.createPartName(proposal); - } - return img; - } - - /** - * returns the PictureData by blipID - * - * @param blipID - * @return XWPFPictureData of a specificID - */ - public XWPFPictureData getPictureDataByID(String blipID) { - POIXMLDocumentPart relatedPart = getRelationById(blipID); - if (relatedPart instanceof XWPFPictureData) { - XWPFPictureData xwpfPicData = (XWPFPictureData) relatedPart; - return xwpfPicData; - } - return null; - } - - /** - * getNumbering - * - * @return numbering - */ - public XWPFNumbering getNumbering() { - return numbering; - } - - /** - * get Styles - * - * @return styles for this document - */ - public XWPFStyles getStyles() { - return styles; - } - - /** - * get the paragraph with the CTP class p - * - * @param p - * @return the paragraph with the CTP class p - */ - @Override - public XWPFParagraph getParagraph(CTP p) { - for (int i = 0; i < getParagraphs().size(); i++) { - if (getParagraphs().get(i).getCTP() == p) { - return getParagraphs().get(i); - } - } - return null; - } - - /** - * get a table by its CTTbl-Object - * - * @param ctTbl - * @return a table by its CTTbl-Object or null - * @see org.apache.poi.xwpf.usermodel.IBody#getTable(org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl) - */ - @Override - public XWPFTable getTable(CTTbl ctTbl) { - for (int i = 0; i < tables.size(); i++) { - if (getTables().get(i).getCTTbl() == ctTbl) { - return getTables().get(i); - } - } - return null; - } - - public Iterator getTablesIterator() { - return tables.iterator(); - } - - public Iterator getParagraphsIterator() { - return paragraphs.iterator(); - } - - /** - * Returns the paragraph that of position pos - * - * @see org.apache.poi.xwpf.usermodel.IBody#getParagraphArray(int) - */ - @Override - public XWPFParagraph getParagraphArray(int pos) { - if (pos >= 0 && pos < paragraphs.size()) { - return paragraphs.get(pos); - } - return null; - } - - /** - * returns the Part, to which the body belongs, which you need for adding relationship to other parts - * Actually it is needed of the class XWPFTableCell. Because you have to know to which part the tableCell - * belongs. - * - * @see org.apache.poi.xwpf.usermodel.IBody#getPart() - */ - @Override - public POIXMLDocumentPart getPart() { - return this; - } - - - /** - * get the PartType of the body, for example - * DOCUMENT, HEADER, FOOTER, FOOTNOTE, - * - * @see org.apache.poi.xwpf.usermodel.IBody#getPartType() - */ - @Override - public BodyType getPartType() { - return BodyType.DOCUMENT; - } - - /** - * get the TableCell which belongs to the TableCell - * - * @param cell - */ - @Override - public XWPFTableCell getTableCell(CTTc cell) { - XmlCursor cursor = cell.newCursor(); - cursor.toParent(); - XmlObject o = cursor.getObject(); - if (!(o instanceof CTRow)) { - return null; - } - CTRow row = (CTRow) o; - cursor.toParent(); - o = cursor.getObject(); - cursor.dispose(); - if (!(o instanceof CTTbl)) { - return null; - } - CTTbl tbl = (CTTbl) o; - XWPFTable table = getTable(tbl); - if (table == null) { - return null; - } - XWPFTableRow tableRow = table.getRow(row); - if (tableRow == null) { - return null; - } - return tableRow.getTableCell(cell); - } - - @Override - public XWPFDocument getXWPFDocument() { - return this; - } -} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFFactory.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFFactory.java deleted file mode 100644 index bc5bbe4c0..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFFactory.java +++ /dev/null @@ -1,59 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xwpf.usermodel; - -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.POIXMLFactory; -import org.apache.poi.POIXMLRelation; - -/** - * Instantiates sub-classes of POIXMLDocumentPart depending on their relationship type - */ -public final class XWPFFactory extends POIXMLFactory { - private XWPFFactory() { - - } - - private static final XWPFFactory inst = new XWPFFactory(); - - public static XWPFFactory getInstance() { - return inst; - } - - /** - * @since POI 3.14-Beta1 - */ - @Override - protected POIXMLRelation getDescriptor(String relationshipType) { - return XWPFRelation.getInstance(relationshipType); - } - - /** - * @since POI 3.14-Beta1 - */ - @Override - protected POIXMLDocumentPart createDocumentPart - (Class cls, Class[] classes, Object[] values) - throws SecurityException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { - Constructor constructor = cls.getDeclaredConstructor(classes); - return constructor.newInstance(values); - } -} \ No newline at end of file diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFFieldRun.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFFieldRun.java deleted file mode 100644 index 1f1559b3a..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFFieldRun.java +++ /dev/null @@ -1,48 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -import org.apache.poi.util.Internal; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSimpleField; - -/** - * A run of text which is part of a field, such as Title - * of Page number or Author. - * Any given Field may be made up of multiple of these. - */ -public class XWPFFieldRun extends XWPFRun { - private CTSimpleField field; - - public XWPFFieldRun(CTSimpleField field, CTR run, IRunBody p) { - super(run, p); - this.field = field; - } - - @Internal - public CTSimpleField getCTField() { - return field; - } - - public String getFieldInstruction() { - return field.getInstr(); - } - - public void setFieldInstruction(String instruction) { - field.setInstr(instruction); - } -} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFFooter.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFFooter.java deleted file mode 100644 index 471b28bed..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFFooter.java +++ /dev/null @@ -1,137 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -import static org.apache.poi.POIXMLTypeLoader.DEFAULT_XML_OPTIONS; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import javax.xml.namespace.QName; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.POIXMLException; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlOptions; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTHdrFtr; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTNumbering; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtBlock; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.FtrDocument; - -/** - * Sketch of XWPF footer class - */ -public class XWPFFooter extends XWPFHeaderFooter { - public XWPFFooter() { - super(); - } - - public XWPFFooter(XWPFDocument doc, CTHdrFtr hdrFtr) throws IOException { - super(doc, hdrFtr); - XmlCursor cursor = headerFooter.newCursor(); - cursor.selectPath("./*"); - while (cursor.toNextSelection()) { - XmlObject o = cursor.getObject(); - if (o instanceof CTP) { - XWPFParagraph p = new XWPFParagraph((CTP) o, this); - paragraphs.add(p); - bodyElements.add(p); - } - if (o instanceof CTTbl) { - XWPFTable t = new XWPFTable((CTTbl) o, this); - tables.add(t); - bodyElements.add(t); - } - - } - cursor.dispose(); - } - - /** - * @since POI 3.14-Beta1 - */ - public XWPFFooter(POIXMLDocumentPart parent, PackagePart part) throws IOException { - super(parent, part); - } - - /** - * save and commit footer - */ - @Override - protected void commit() throws IOException { - XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS); - xmlOptions.setSaveSyntheticDocumentElement(new QName(CTNumbering.type.getName().getNamespaceURI(), "ftr")); - PackagePart part = getPackagePart(); - OutputStream out = part.getOutputStream(); - super._getHdrFtr().save(out, xmlOptions); - out.close(); - } - - @Override - protected void onDocumentRead() throws IOException { - super.onDocumentRead(); - FtrDocument ftrDocument = null; - InputStream is = null; - try { - is = getPackagePart().getInputStream(); - ftrDocument = FtrDocument.Factory.parse(is, DEFAULT_XML_OPTIONS); - headerFooter = ftrDocument.getFtr(); - // parse the document with cursor and add - // the XmlObject to its lists - XmlCursor cursor = headerFooter.newCursor(); - cursor.selectPath("./*"); - while (cursor.toNextSelection()) { - XmlObject o = cursor.getObject(); - if (o instanceof CTP) { - XWPFParagraph p = new XWPFParagraph((CTP) o, this); - paragraphs.add(p); - bodyElements.add(p); - } - if (o instanceof CTTbl) { - XWPFTable t = new XWPFTable((CTTbl) o, this); - tables.add(t); - bodyElements.add(t); - } - if (o instanceof CTSdtBlock) { - XWPFSDT c = new XWPFSDT((CTSdtBlock) o, this); - bodyElements.add(c); - } - } - cursor.dispose(); - } catch (Exception e) { - throw new POIXMLException(e); - } finally { - if (is != null) { - is.close(); - } - } - } - - /** - * get the PartType of the body - * - * @see org.apache.poi.xwpf.usermodel.IBody#getPartType() - */ - public BodyType getPartType() { - return BodyType.FOOTER; - } -} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFFootnote.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFFootnote.java deleted file mode 100644 index 8c89bf747..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFFootnote.java +++ /dev/null @@ -1,377 +0,0 @@ -/* ==================================================================== -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlObject; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFtnEdn; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRow; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtBlock; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTc; - -public class XWPFFootnote implements Iterable, IBody { - private List paragraphs = new ArrayList(); - private List tables = new ArrayList(); - private List pictures = new ArrayList(); - private List bodyElements = new ArrayList(); - - private CTFtnEdn ctFtnEdn; - private XWPFFootnotes footnotes; - private XWPFDocument document; - - public XWPFFootnote(CTFtnEdn note, XWPFFootnotes xFootnotes) { - footnotes = xFootnotes; - ctFtnEdn = note; - document = xFootnotes.getXWPFDocument(); - init(); - } - - public XWPFFootnote(XWPFDocument document, CTFtnEdn body) { - ctFtnEdn = body; - this.document = document; - init(); - } - - private void init() { - XmlCursor cursor = ctFtnEdn.newCursor(); - //copied from XWPFDocument...should centralize this code - //to avoid duplication - cursor.selectPath("./*"); - while (cursor.toNextSelection()) { - XmlObject o = cursor.getObject(); - if (o instanceof CTP) { - XWPFParagraph p = new XWPFParagraph((CTP) o, this); - bodyElements.add(p); - paragraphs.add(p); - } else if (o instanceof CTTbl) { - XWPFTable t = new XWPFTable((CTTbl) o, this); - bodyElements.add(t); - tables.add(t); - } else if (o instanceof CTSdtBlock) { - XWPFSDT c = new XWPFSDT((CTSdtBlock) o, this); - bodyElements.add(c); - } - - } - cursor.dispose(); - } - - public List getParagraphs() { - return paragraphs; - } - - public Iterator iterator() { - return paragraphs.iterator(); - } - - public List getTables() { - return tables; - } - - public List getPictures() { - return pictures; - } - - public List getBodyElements() { - return bodyElements; - } - - public CTFtnEdn getCTFtnEdn() { - return ctFtnEdn; - } - - public void setCTFtnEdn(CTFtnEdn footnote) { - ctFtnEdn = footnote; - } - - /** - * @param pos in table array - * @return The table at position pos - * @see org.apache.poi.xwpf.usermodel.IBody#getTableArray(int) - */ - public XWPFTable getTableArray(int pos) { - if (pos >= 0 && pos < tables.size()) { - return tables.get(pos); - } - return null; - } - - /** - * inserts an existing XWPFTable to the arrays bodyElements and tables - * - * @param pos - * @param table - * @see org.apache.poi.xwpf.usermodel.IBody#insertTable(int pos, XWPFTable table) - */ - public void insertTable(int pos, XWPFTable table) { - bodyElements.add(pos, table); - int i = 0; - for (CTTbl tbl : ctFtnEdn.getTblArray()) { - if (tbl == table.getCTTbl()) { - break; - } - i++; - } - tables.add(i, table); - - } - - /** - * if there is a corresponding {@link XWPFTable} of the parameter ctTable in the tableList of this header - * the method will return this table - * if there is no corresponding {@link XWPFTable} the method will return null - * - * @param ctTable - * @see org.apache.poi.xwpf.usermodel.IBody#getTable(CTTbl ctTable) - */ - public XWPFTable getTable(CTTbl ctTable) { - for (XWPFTable table : tables) { - if (table == null) - return null; - if (table.getCTTbl().equals(ctTable)) - return table; - } - return null; - } - - /** - * if there is a corresponding {@link XWPFParagraph} of the parameter ctTable in the paragraphList of this header or footer - * the method will return this paragraph - * if there is no corresponding {@link XWPFParagraph} the method will return null - * - * @param p is instance of CTP and is searching for an XWPFParagraph - * @return null if there is no XWPFParagraph with an corresponding CTPparagraph in the paragraphList of this header or footer - * XWPFParagraph with the correspondig CTP p - * @see org.apache.poi.xwpf.usermodel.IBody#getParagraph(CTP p) - */ - public XWPFParagraph getParagraph(CTP p) { - for (XWPFParagraph paragraph : paragraphs) { - if (paragraph.getCTP().equals(p)) - return paragraph; - } - return null; - } - - /** - * Returns the paragraph that holds - * the text of the header or footer. - * - * @see org.apache.poi.xwpf.usermodel.IBody#getParagraphArray(int pos) - */ - public XWPFParagraph getParagraphArray(int pos) { - if(pos >=0 && pos < paragraphs.size()) { - return paragraphs.get(pos); - } - return null; - } - - /** - * get the TableCell which belongs to the TableCell - * - * @param cell - * @see org.apache.poi.xwpf.usermodel.IBody#getTableCell(CTTc cell) - */ - public XWPFTableCell getTableCell(CTTc cell) { - XmlCursor cursor = cell.newCursor(); - cursor.toParent(); - XmlObject o = cursor.getObject(); - if (!(o instanceof CTRow)) { - return null; - } - CTRow row = (CTRow) o; - cursor.toParent(); - o = cursor.getObject(); - cursor.dispose(); - if (!(o instanceof CTTbl)) { - return null; - } - CTTbl tbl = (CTTbl) o; - XWPFTable table = getTable(tbl); - if (table == null) { - return null; - } - XWPFTableRow tableRow = table.getRow(row); - if(tableRow == null){ - return null; - } - return tableRow.getTableCell(cell); - } - - /** - * verifies that cursor is on the right position - * - * @param cursor - */ - private boolean isCursorInFtn(XmlCursor cursor) { - XmlCursor verify = cursor.newCursor(); - verify.toParent(); - if (verify.getObject() == this.ctFtnEdn) { - return true; - } - return false; - } - - public POIXMLDocumentPart getOwner() { - return footnotes; - } - - /** - * @param cursor - * @return the inserted table - * @see org.apache.poi.xwpf.usermodel.IBody#insertNewTbl(XmlCursor cursor) - */ - public XWPFTable insertNewTbl(XmlCursor cursor) { - if (isCursorInFtn(cursor)) { - String uri = CTTbl.type.getName().getNamespaceURI(); - String localPart = "tbl"; - cursor.beginElement(localPart, uri); - cursor.toParent(); - CTTbl t = (CTTbl) cursor.getObject(); - XWPFTable newT = new XWPFTable(t, this); - cursor.removeXmlContents(); - XmlObject o = null; - while (!(o instanceof CTTbl) && (cursor.toPrevSibling())) { - o = cursor.getObject(); - } - if (!(o instanceof CTTbl)) { - tables.add(0, newT); - } else { - int pos = tables.indexOf(getTable((CTTbl) o)) + 1; - tables.add(pos, newT); - } - int i = 0; - cursor = t.newCursor(); - while (cursor.toPrevSibling()) { - o = cursor.getObject(); - if (o instanceof CTP || o instanceof CTTbl) - i++; - } - bodyElements.add(i, newT); - XmlCursor c2 = t.newCursor(); - cursor.toCursor(c2); - cursor.toEndToken(); - c2.dispose(); - return newT; - } - return null; - } - - /** - * add a new paragraph at position of the cursor - * - * @param cursor - * @return the inserted paragraph - * @see org.apache.poi.xwpf.usermodel.IBody#insertNewParagraph(XmlCursor cursor) - */ - public XWPFParagraph insertNewParagraph(final XmlCursor cursor) { - if (isCursorInFtn(cursor)) { - String uri = CTP.type.getName().getNamespaceURI(); - String localPart = "p"; - cursor.beginElement(localPart, uri); - cursor.toParent(); - CTP p = (CTP) cursor.getObject(); - XWPFParagraph newP = new XWPFParagraph(p, this); - XmlObject o = null; - while (!(o instanceof CTP) && (cursor.toPrevSibling())) { - o = cursor.getObject(); - } - if ((!(o instanceof CTP)) || (CTP) o == p) { - paragraphs.add(0, newP); - } else { - int pos = paragraphs.indexOf(getParagraph((CTP) o)) + 1; - paragraphs.add(pos, newP); - } - int i = 0; - XmlCursor p2 = p.newCursor(); - cursor.toCursor(p2); - p2.dispose(); - while (cursor.toPrevSibling()) { - o = cursor.getObject(); - if (o instanceof CTP || o instanceof CTTbl) - i++; - } - bodyElements.add(i, newP); - p2 = p.newCursor(); - cursor.toCursor(p2); - cursor.toEndToken(); - p2.dispose(); - return newP; - } - return null; - } - - /** - * add a new table to the end of the footnote - * - * @param table - * @return the added XWPFTable - */ - public XWPFTable addNewTbl(CTTbl table) { - CTTbl newTable = ctFtnEdn.addNewTbl(); - newTable.set(table); - XWPFTable xTable = new XWPFTable(newTable, this); - tables.add(xTable); - return xTable; - } - - /** - * add a new paragraph to the end of the footnote - * - * @param paragraph - * @return the added XWPFParagraph - */ - public XWPFParagraph addNewParagraph(CTP paragraph) { - CTP newPara = ctFtnEdn.addNewP(); - newPara.set(paragraph); - XWPFParagraph xPara = new XWPFParagraph(newPara, this); - paragraphs.add(xPara); - return xPara; - } - - /** - * @see org.apache.poi.xwpf.usermodel.IBody#getXWPFDocument() - */ - public XWPFDocument getXWPFDocument() { - return document; - } - - /** - * returns the Part, to which the body belongs, which you need for adding relationship to other parts - * - * @see org.apache.poi.xwpf.usermodel.IBody#getPart() - */ - public POIXMLDocumentPart getPart() { - return footnotes; - } - - /** - * get the PartType of the body - * - * @see org.apache.poi.xwpf.usermodel.IBody#getPartType() - */ - public BodyType getPartType() { - return BodyType.FOOTNOTE; - } -} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFFootnotes.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFFootnotes.java deleted file mode 100644 index c037bd7d4..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFFootnotes.java +++ /dev/null @@ -1,160 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xwpf.usermodel; - -import static org.apache.poi.POIXMLTypeLoader.DEFAULT_XML_OPTIONS; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.List; - -import javax.xml.namespace.QName; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.POIXMLException; -import org.apache.poi.openxml4j.exceptions.OpenXML4JException; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlOptions; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFootnotes; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFtnEdn; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.FootnotesDocument; - -/** - * Looks after the collection of Footnotes for a document - */ -public class XWPFFootnotes extends POIXMLDocumentPart { - protected XWPFDocument document; - private List listFootnote = new ArrayList(); - private CTFootnotes ctFootnotes; - - /** - * Construct XWPFFootnotes from a package part - * - * @param part the package part holding the data of the footnotes, - * - * @since POI 3.14-Beta1 - */ - public XWPFFootnotes(PackagePart part) throws IOException, OpenXML4JException { - super(part); - } - - /** - * Construct XWPFFootnotes from scratch for a new document. - */ - public XWPFFootnotes() { - } - - /** - * Read document - */ - @Override - protected void onDocumentRead() throws IOException { - FootnotesDocument notesDoc; - InputStream is = null; - try { - is = getPackagePart().getInputStream(); - notesDoc = FootnotesDocument.Factory.parse(is, DEFAULT_XML_OPTIONS); - ctFootnotes = notesDoc.getFootnotes(); - } catch (XmlException e) { - throw new POIXMLException(); - } finally { - if (is != null) { - is.close(); - } - } - - // Find our footnotes - for (CTFtnEdn note : ctFootnotes.getFootnoteArray()) { - listFootnote.add(new XWPFFootnote(note, this)); - } - } - - @Override - protected void commit() throws IOException { - XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS); - xmlOptions.setSaveSyntheticDocumentElement(new QName(CTFootnotes.type.getName().getNamespaceURI(), "footnotes")); - PackagePart part = getPackagePart(); - OutputStream out = part.getOutputStream(); - ctFootnotes.save(out, xmlOptions); - out.close(); - } - - public List getFootnotesList() { - return listFootnote; - } - - public XWPFFootnote getFootnoteById(int id) { - for (XWPFFootnote note : listFootnote) { - if (note.getCTFtnEdn().getId().intValue() == id) - return note; - } - return null; - } - - /** - * Sets the ctFootnotes - * - * @param footnotes - */ - public void setFootnotes(CTFootnotes footnotes) { - ctFootnotes = footnotes; - } - - /** - * add an XWPFFootnote to the document - * - * @param footnote - * @throws IOException - */ - public void addFootnote(XWPFFootnote footnote) { - listFootnote.add(footnote); - ctFootnotes.addNewFootnote().set(footnote.getCTFtnEdn()); - } - - /** - * add a footnote to the document - * - * @param note - * @throws IOException - */ - public XWPFFootnote addFootnote(CTFtnEdn note) { - CTFtnEdn newNote = ctFootnotes.addNewFootnote(); - newNote.set(note); - XWPFFootnote xNote = new XWPFFootnote(newNote, this); - listFootnote.add(xNote); - return xNote; - } - - /** - * @see org.apache.poi.xwpf.usermodel.IBody#getPart() - */ - public XWPFDocument getXWPFDocument() { - if (document != null) { - return document; - } else { - return (XWPFDocument) getParent(); - } - } - - public void setXWPFDocument(XWPFDocument doc) { - document = doc; - } -} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFHeader.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFHeader.java deleted file mode 100644 index 3789b521e..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFHeader.java +++ /dev/null @@ -1,140 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -import static org.apache.poi.POIXMLTypeLoader.DEFAULT_XML_OPTIONS; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import javax.xml.namespace.QName; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.POIXMLException; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlOptions; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTHdrFtr; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTNumbering; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtBlock; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.HdrDocument; - -/** - * Sketch of XWPF header class - */ -public class XWPFHeader extends XWPFHeaderFooter { - public XWPFHeader() { - super(); - } - - /** - * @since POI 3.14-Beta1 - */ - public XWPFHeader(POIXMLDocumentPart parent, PackagePart part) throws IOException { - super(parent, part); - } - - public XWPFHeader(XWPFDocument doc, CTHdrFtr hdrFtr) { - super(doc, hdrFtr); - XmlCursor cursor = headerFooter.newCursor(); - cursor.selectPath("./*"); - while (cursor.toNextSelection()) { - XmlObject o = cursor.getObject(); - if (o instanceof CTP) { - XWPFParagraph p = new XWPFParagraph((CTP) o, this); - paragraphs.add(p); - } - if (o instanceof CTTbl) { - XWPFTable t = new XWPFTable((CTTbl) o, this); - tables.add(t); - } - } - cursor.dispose(); - } - - /** - * save and commit footer - */ - @Override - protected void commit() throws IOException { - XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS); - xmlOptions.setSaveSyntheticDocumentElement(new QName(CTNumbering.type.getName().getNamespaceURI(), "hdr")); - PackagePart part = getPackagePart(); - OutputStream out = part.getOutputStream(); - super._getHdrFtr().save(out, xmlOptions); - out.close(); - } - - /** - * reads the document - * - * @throws IOException - */ - @Override - protected void onDocumentRead() throws IOException { - super.onDocumentRead(); - HdrDocument hdrDocument = null; - InputStream is = null; - try { - is = getPackagePart().getInputStream(); - hdrDocument = HdrDocument.Factory.parse(is, DEFAULT_XML_OPTIONS); - headerFooter = hdrDocument.getHdr(); - // parse the document with cursor and add - // the XmlObject to its lists - XmlCursor cursor = headerFooter.newCursor(); - cursor.selectPath("./*"); - while (cursor.toNextSelection()) { - XmlObject o = cursor.getObject(); - if (o instanceof CTP) { - XWPFParagraph p = new XWPFParagraph((CTP) o, this); - paragraphs.add(p); - bodyElements.add(p); - } - if (o instanceof CTTbl) { - XWPFTable t = new XWPFTable((CTTbl) o, this); - tables.add(t); - bodyElements.add(t); - } - if (o instanceof CTSdtBlock) { - XWPFSDT c = new XWPFSDT((CTSdtBlock) o, this); - bodyElements.add(c); - } - } - cursor.dispose(); - } catch (XmlException e) { - throw new POIXMLException(e); - } finally { - if (is != null) { - is.close(); - } - } - } - - /** - * get the PartType of the body - * - * @see org.apache.poi.xwpf.usermodel.IBody#getPartType() - */ - public BodyType getPartType() { - return BodyType.HEADER; - } -}//end class diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFHeaderFooter.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFHeaderFooter.java deleted file mode 100644 index c5a936506..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFHeaderFooter.java +++ /dev/null @@ -1,614 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.POIXMLException; -import org.apache.poi.POIXMLRelation; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.Internal; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlObject; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTHdrFtr; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRow; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTc; - -/** - * Parent of XWPF headers and footers - */ -public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBody { - List paragraphs = new ArrayList(); - List tables = new ArrayList(); - List pictures = new ArrayList(); - List bodyElements = new ArrayList(); - - CTHdrFtr headerFooter; - XWPFDocument document; - - XWPFHeaderFooter(XWPFDocument doc, CTHdrFtr hdrFtr) { - if (doc == null) { - throw new NullPointerException(); - } - - document = doc; - headerFooter = hdrFtr; - readHdrFtr(); - } - - protected XWPFHeaderFooter() { - headerFooter = CTHdrFtr.Factory.newInstance(); - readHdrFtr(); - } - - /** - * @since by POI 3.14-Beta1 - */ - public XWPFHeaderFooter(POIXMLDocumentPart parent, PackagePart part) throws IOException { - super(parent, part); - this.document = (XWPFDocument) getParent(); - - if (this.document == null) { - throw new NullPointerException(); - } - } - - @Override - protected void onDocumentRead() throws IOException { - for (POIXMLDocumentPart poixmlDocumentPart : getRelations()) { - if (poixmlDocumentPart instanceof XWPFPictureData) { - XWPFPictureData xwpfPicData = (XWPFPictureData) poixmlDocumentPart; - pictures.add(xwpfPicData); - document.registerPackagePictureData(xwpfPicData); - } - } - } - - @Internal - public CTHdrFtr _getHdrFtr() { - return headerFooter; - } - - public List getBodyElements() { - return Collections.unmodifiableList(bodyElements); - } - - /** - * Returns the paragraph(s) that holds - * the text of the header or footer. - * Normally there is only the one paragraph, but - * there could be more in certain cases, or - * a table. - */ - public List getParagraphs() { - return Collections.unmodifiableList(paragraphs); - } - - - /** - * Return the table(s) that holds the text - * of the header or footer, for complex cases - * where a paragraph isn't used. - * Normally there's just one paragraph, but some - * complex headers/footers have a table or two - * in addition. - */ - public List getTables() throws ArrayIndexOutOfBoundsException { - return Collections.unmodifiableList(tables); - } - - - /** - * Returns the textual content of the header/footer, - * by flattening out the text of its paragraph(s) - */ - public String getText() { - StringBuffer t = new StringBuffer(); - //TODO: simplify this to get ibody elements in order - for (int i = 0; i < paragraphs.size(); i++) { - if (!paragraphs.get(i).isEmpty()) { - String text = paragraphs.get(i).getText(); - if (text != null && text.length() > 0) { - t.append(text); - t.append('\n'); - } - } - } - - for (int i = 0; i < tables.size(); i++) { - String text = tables.get(i).getText(); - if (text != null && text.length() > 0) { - t.append(text); - t.append('\n'); - } - } - - for (IBodyElement bodyElement : getBodyElements()) { - if (bodyElement instanceof XWPFSDT) { - t.append(((XWPFSDT) bodyElement).getContent().getText() + '\n'); - } - } - return t.toString(); - } - - /** - * set a new headerFooter - */ - public void setHeaderFooter(CTHdrFtr headerFooter) { - this.headerFooter = headerFooter; - readHdrFtr(); - } - - /** - * if there is a corresponding {@link XWPFTable} of the parameter ctTable in the tableList of this header - * the method will return this table - * if there is no corresponding {@link XWPFTable} the method will return null - * - * @param ctTable - */ - public XWPFTable getTable(CTTbl ctTable) { - for (XWPFTable table : tables) { - if (table == null) - return null; - if (table.getCTTbl().equals(ctTable)) - return table; - } - return null; - } - - /** - * if there is a corresponding {@link XWPFParagraph} of the parameter ctTable in the paragraphList of this header or footer - * the method will return this paragraph - * if there is no corresponding {@link XWPFParagraph} the method will return null - * - * @param p is instance of CTP and is searching for an XWPFParagraph - * @return null if there is no XWPFParagraph with an corresponding CTPparagraph in the paragraphList of this header or footer - * XWPFParagraph with the correspondig CTP p - */ - public XWPFParagraph getParagraph(CTP p) { - for (XWPFParagraph paragraph : paragraphs) { - if (paragraph.getCTP().equals(p)) - return paragraph; - } - return null; - - } - - /** - * Returns the paragraph that holds - * the text of the header or footer. - */ - public XWPFParagraph getParagraphArray(int pos) { - if(pos >= 0 && pos getListParagraph() { - return paragraphs; - } - - public List getAllPictures() { - return Collections.unmodifiableList(pictures); - } - - /** - * get all Pictures in this package - * - * @return all Pictures in this package - */ - public List getAllPackagePictures() { - return document.getAllPackagePictures(); - - } - - /** - * Adds a picture to the document. - * - * @param pictureData The picture data - * @param format The format of the picture. - * @return the index to this picture (0 based), the added picture can be obtained from {@link #getAllPictures()} . - * @throws InvalidFormatException - */ - public String addPictureData(byte[] pictureData, int format) throws InvalidFormatException { - XWPFPictureData xwpfPicData = document.findPackagePictureData(pictureData, format); - POIXMLRelation relDesc = XWPFPictureData.RELATIONS[format]; - - if (xwpfPicData == null) { - /* Part doesn't exist, create a new one */ - int idx = document.getNextPicNameNumber(format); - xwpfPicData = (XWPFPictureData) createRelationship(relDesc, XWPFFactory.getInstance(), idx); - /* write bytes to new part */ - PackagePart picDataPart = xwpfPicData.getPackagePart(); - OutputStream out = null; - try { - out = picDataPart.getOutputStream(); - out.write(pictureData); - } catch (IOException e) { - throw new POIXMLException(e); - } finally { - try { - if (out != null) out.close(); - } catch (IOException e) { - // ignore - } - } - - document.registerPackagePictureData(xwpfPicData); - pictures.add(xwpfPicData); - return getRelationId(xwpfPicData); - } else if (!getRelations().contains(xwpfPicData)) { - /* - * Part already existed, but was not related so far. Create - * relationship to the already existing part and update - * POIXMLDocumentPart data. - */ - // TODO add support for TargetMode.EXTERNAL relations. - RelationPart rp = addRelation(null, XWPFRelation.IMAGES, xwpfPicData); - pictures.add(xwpfPicData); - return rp.getRelationship().getId(); - } else { - /* Part already existed, get relation id and return it */ - return getRelationId(xwpfPicData); - } - } - - /** - * Adds a picture to the document. - * - * @param is The stream to read image from - * @param format The format of the picture. - * @return the index to this picture (0 based), the added picture can be obtained from {@link #getAllPictures()} . - * @throws InvalidFormatException - * @throws IOException - */ - public String addPictureData(InputStream is, int format) throws InvalidFormatException, IOException { - byte[] data = IOUtils.toByteArray(is); - return addPictureData(data, format); - } - - /** - * returns the PictureData by blipID - * - * @param blipID - * @return XWPFPictureData of a specificID - * @throws Exception - */ - public XWPFPictureData getPictureDataByID(String blipID) { - POIXMLDocumentPart relatedPart = getRelationById(blipID); - if (relatedPart != null && relatedPart instanceof XWPFPictureData) { - return (XWPFPictureData) relatedPart; - } - return null; - } - - /** - * Adds a new paragraph at the end of the header or footer - * - * @return new {@link XWPFParagraph} object - */ - public XWPFParagraph createParagraph() { - XWPFParagraph paragraph = new XWPFParagraph(headerFooter.addNewP(), this); - paragraphs.add(paragraph); - bodyElements.add(paragraph); - return paragraph; - } - - /** - * Adds a new table at the end of the header or footer - * - * @param rows - number of rows in the table - * @param cols - number of columns in the table - * @return new {@link XWPFTable} object - */ - public XWPFTable createTable(int rows, int cols) { - XWPFTable table = new XWPFTable(headerFooter.addNewTbl(), this, rows, cols); - tables.add(table); - bodyElements.add(table); - return table; - } - - /** - * Removes a specific paragraph from this header / footer - * - * @param paragraph - {@link XWPFParagraph} object to remove - */ - public void removeParagraph(XWPFParagraph paragraph) { - if (paragraphs.contains(paragraph)) { - CTP ctP = paragraph.getCTP(); - XmlCursor c = ctP.newCursor(); - c.removeXml(); - c.dispose(); - paragraphs.remove(paragraph); - bodyElements.remove(paragraph); - } - } - - /** - * Removes a specific table from this header / footer - * - * @param table - {@link XWPFTable} object to remove - */ - public void removeTable(XWPFTable table) { - if (tables.contains(table)) { - CTTbl ctTbl = table.getCTTbl(); - XmlCursor c = ctTbl.newCursor(); - c.removeXml(); - c.dispose(); - tables.remove(table); - bodyElements.remove(table); - } - } - - /** - * Clears all paragraphs and tables from this header / footer - */ - public void clearHeaderFooter() { - XmlCursor c = headerFooter.newCursor(); - c.removeXmlContents(); - c.dispose(); - paragraphs.clear(); - tables.clear(); - bodyElements.clear(); - } - - /** - * add a new paragraph at position of the cursor - * - * @param cursor - * @return the inserted paragraph - */ - public XWPFParagraph insertNewParagraph(XmlCursor cursor) { - if (isCursorInHdrF(cursor)) { - String uri = CTP.type.getName().getNamespaceURI(); - String localPart = "p"; - cursor.beginElement(localPart, uri); - cursor.toParent(); - CTP p = (CTP) cursor.getObject(); - XWPFParagraph newP = new XWPFParagraph(p, this); - XmlObject o = null; - while (!(o instanceof CTP) && (cursor.toPrevSibling())) { - o = cursor.getObject(); - } - if ((!(o instanceof CTP)) || (CTP) o == p) { - paragraphs.add(0, newP); - } else { - int pos = paragraphs.indexOf(getParagraph((CTP) o)) + 1; - paragraphs.add(pos, newP); - } - int i = 0; - XmlCursor p2 = p.newCursor(); - cursor.toCursor(p2); - p2.dispose(); - while (cursor.toPrevSibling()) { - o = cursor.getObject(); - if (o instanceof CTP || o instanceof CTTbl) - i++; - } - bodyElements.add(i, newP); - p2 = p.newCursor(); - cursor.toCursor(p2); - cursor.toEndToken(); - p2.dispose(); - return newP; - } - return null; - } - - - /** - * @param cursor - * @return the inserted table - */ - public XWPFTable insertNewTbl(final XmlCursor cursor) { - if (isCursorInHdrF(cursor)) { - String uri = CTTbl.type.getName().getNamespaceURI(); - String localPart = "tbl"; - cursor.beginElement(localPart, uri); - cursor.toParent(); - CTTbl t = (CTTbl) cursor.getObject(); - XWPFTable newT = new XWPFTable(t, this); - cursor.removeXmlContents(); - XmlObject o = null; - while (!(o instanceof CTTbl) && (cursor.toPrevSibling())) { - o = cursor.getObject(); - } - if (!(o instanceof CTTbl)) { - tables.add(0, newT); - } else { - int pos = tables.indexOf(getTable((CTTbl) o)) + 1; - tables.add(pos, newT); - } - int i = 0; - XmlCursor cursor2 = t.newCursor(); - while (cursor2.toPrevSibling()) { - o = cursor2.getObject(); - if (o instanceof CTP || o instanceof CTTbl) { - i++; - } - } - cursor2.dispose(); - bodyElements.add(i, newT); - cursor2 = t.newCursor(); - cursor.toCursor(cursor2); - cursor.toEndToken(); - cursor2.dispose(); - return newT; - } - return null; - } - - /** - * verifies that cursor is on the right position - * - * @param cursor - */ - private boolean isCursorInHdrF(XmlCursor cursor) { - XmlCursor verify = cursor.newCursor(); - verify.toParent(); - boolean result = (verify.getObject() == this.headerFooter); - verify.dispose(); - return result; - } - - - public POIXMLDocumentPart getOwner() { - return this; - } - - /** - * Returns the table at position pos - * - * @see org.apache.poi.xwpf.usermodel.IBody#getTableArray(int) - */ - public XWPFTable getTableArray(int pos) { - if (pos >= 0 && pos < tables.size()) { - return tables.get(pos); - } - return null; - } - - /** - * inserts an existing XWPFTable to the arrays bodyElements and tables - * - * @param pos - * @param table - */ - public void insertTable(int pos, XWPFTable table) { - bodyElements.add(pos, table); - int i = 0; - for (CTTbl tbl : headerFooter.getTblArray()) { - if (tbl == table.getCTTbl()) { - break; - } - i++; - } - tables.add(i, table); - - } - - public void readHdrFtr() { - bodyElements = new ArrayList(); - paragraphs = new ArrayList(); - tables = new ArrayList(); - // parse the document with cursor and add - // the XmlObject to its lists - XmlCursor cursor = headerFooter.newCursor(); - cursor.selectPath("./*"); - while (cursor.toNextSelection()) { - XmlObject o = cursor.getObject(); - if (o instanceof CTP) { - XWPFParagraph p = new XWPFParagraph((CTP) o, this); - paragraphs.add(p); - bodyElements.add(p); - } - if (o instanceof CTTbl) { - XWPFTable t = new XWPFTable((CTTbl) o, this); - tables.add(t); - bodyElements.add(t); - } - } - cursor.dispose(); - } - - /** - * get the TableCell which belongs to the TableCell - * - * @param cell - */ - public XWPFTableCell getTableCell(CTTc cell) { - XmlCursor cursor = cell.newCursor(); - cursor.toParent(); - XmlObject o = cursor.getObject(); - if (!(o instanceof CTRow)) { - cursor.dispose(); - return null; - } - CTRow row = (CTRow) o; - cursor.toParent(); - o = cursor.getObject(); - cursor.dispose(); - if (!(o instanceof CTTbl)) { - return null; - } - CTTbl tbl = (CTTbl) o; - XWPFTable table = getTable(tbl); - if (table == null) { - return null; - } - XWPFTableRow tableRow = table.getRow(row); - return tableRow.getTableCell(cell); - } - - public XWPFDocument getXWPFDocument() { - if (document != null) { - return document; - } else { - return (XWPFDocument) getParent(); - } - } - - public void setXWPFDocument(XWPFDocument doc) { - document = doc; - } - - /** - * returns the Part, to which the body belongs, which you need for adding relationship to other parts - * - * @see org.apache.poi.xwpf.usermodel.IBody#getPart() - */ - public POIXMLDocumentPart getPart() { - return this; - } - - @Override - protected void prepareForCommit() { - // must contain at least an empty paragraph - if (bodyElements.size() == 0) { - createParagraph(); - } - - // Cells must contain at least an empty paragraph - for (XWPFTable tbl : tables) { - for (XWPFTableRow row : tbl.tableRows) { - for (XWPFTableCell cell : row.getTableCells()) { - if (cell.getBodyElements().size() == 0) { - cell.addParagraph(); - } - } - } - } - super.prepareForCommit(); - - } -} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFHyperlink.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFHyperlink.java deleted file mode 100644 index c00f75a89..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFHyperlink.java +++ /dev/null @@ -1,39 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -/** - * Sketch of XWPF hyperlink class - * - * @author Yury Batrakov (batrakov at gmail.com) - */ -public class XWPFHyperlink { - String id, url; - - public XWPFHyperlink(String id, String url) { - this.id = id; - this.url = url; - } - - public String getId() { - return id; - } - - public String getURL() { - return url; - } -} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFHyperlinkRun.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFHyperlinkRun.java deleted file mode 100644 index 7a5ad06b8..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFHyperlinkRun.java +++ /dev/null @@ -1,66 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -import org.apache.poi.util.Internal; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTHyperlink; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR; - -/** - * A run of text with a Hyperlink applied to it. - * Any given Hyperlink may be made up of multiple of these. - */ -public class XWPFHyperlinkRun extends XWPFRun { - private CTHyperlink hyperlink; - - public XWPFHyperlinkRun(CTHyperlink hyperlink, CTR run, IRunBody p) { - super(run, p); - this.hyperlink = hyperlink; - } - - @Internal - public CTHyperlink getCTHyperlink() { - return hyperlink; - } - - public String getAnchor() { - return hyperlink.getAnchor(); - } - - /** - * Returns the ID of the hyperlink, if one is set. - */ - public String getHyperlinkId() { - return hyperlink.getId(); - } - - public void setHyperlinkId(String id) { - hyperlink.setId(id); - } - - /** - * If this Hyperlink is an external reference hyperlink, - * return the object for it. - */ - public XWPFHyperlink getHyperlink(XWPFDocument document) { - String id = getHyperlinkId(); - if (id == null) - return null; - - return document.getHyperlinkByID(id); - } -} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFLatentStyles.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFLatentStyles.java deleted file mode 100644 index 465428d2f..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFLatentStyles.java +++ /dev/null @@ -1,54 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTLatentStyles; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTLsdException; - -public class XWPFLatentStyles { - // As of 2016-06-10, POI does not contain a LatentStyle class, nor was one included in the patch for bug 48574. - protected XWPFStyles styles; //LatentStyle shall know styles - private CTLatentStyles latentStyles; - - protected XWPFLatentStyles() { - } - - protected XWPFLatentStyles(CTLatentStyles latentStyles) { - this(latentStyles, null); - } - - protected XWPFLatentStyles(CTLatentStyles latentStyles, XWPFStyles styles) { - this.latentStyles = latentStyles; - this.styles = styles; - } - - public int getNumberOfStyles() { - return latentStyles.sizeOfLsdExceptionArray(); - } - - /** - * checks whether specific LatentStyleID is a latentStyle - */ - protected boolean isLatentStyle(String latentStyleID) { - for (CTLsdException lsd : latentStyles.getLsdExceptionArray()) { - if (lsd.getName().equals(latentStyleID)) { - return true; - } - } - return false; - } -} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFNum.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFNum.java deleted file mode 100644 index 9fa8ab38d..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFNum.java +++ /dev/null @@ -1,64 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - - -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTNum; - -/** - * TODO Bring more of the logic over from XWPFParagraph - */ -public class XWPFNum { - protected XWPFNumbering numbering; - private CTNum ctNum; - - public XWPFNum() { - this.ctNum = null; - this.numbering = null; - } - - public XWPFNum(CTNum ctNum) { - this.ctNum = ctNum; - this.numbering = null; - } - - public XWPFNum(XWPFNumbering numbering) { - this.ctNum = null; - this.numbering = numbering; - } - - public XWPFNum(CTNum ctNum, XWPFNumbering numbering) { - this.ctNum = ctNum; - this.numbering = numbering; - } - - public XWPFNumbering getNumbering() { - return numbering; - } - - public void setNumbering(XWPFNumbering numbering) { - this.numbering = numbering; - } - - public CTNum getCTNum() { - return ctNum; - } - - public void setCTNum(CTNum ctNum) { - this.ctNum = ctNum; - } -} \ No newline at end of file diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFNumbering.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFNumbering.java deleted file mode 100644 index 1b7162e00..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFNumbering.java +++ /dev/null @@ -1,284 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -import static org.apache.poi.POIXMLTypeLoader.DEFAULT_XML_OPTIONS; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.List; - -import javax.xml.namespace.QName; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.POIXMLException; -import org.apache.poi.openxml4j.exceptions.OpenXML4JException; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlOptions; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTAbstractNum; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTNum; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTNumbering; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.NumberingDocument; - -/** - * @author Philipp Epp - */ -public class XWPFNumbering extends POIXMLDocumentPart { - protected List abstractNums = new ArrayList(); - protected List nums = new ArrayList(); - boolean isNew; - private CTNumbering ctNumbering; - - /** - * create a new styles object with an existing document - * - * @since POI 3.14-Beta1 - */ - public XWPFNumbering(PackagePart part) throws IOException, OpenXML4JException { - super(part); - isNew = true; - } - - /** - * create a new XWPFNumbering object for use in a new document - */ - public XWPFNumbering() { - abstractNums = new ArrayList(); - nums = new ArrayList(); - isNew = true; - } - - /** - * read numbering form an existing package - */ - @Override - protected void onDocumentRead() throws IOException { - NumberingDocument numberingDoc = null; - InputStream is; - is = getPackagePart().getInputStream(); - try { - numberingDoc = NumberingDocument.Factory.parse(is, DEFAULT_XML_OPTIONS); - ctNumbering = numberingDoc.getNumbering(); - //get any Nums - for (CTNum ctNum : ctNumbering.getNumArray()) { - nums.add(new XWPFNum(ctNum, this)); - } - for (CTAbstractNum ctAbstractNum : ctNumbering.getAbstractNumArray()) { - abstractNums.add(new XWPFAbstractNum(ctAbstractNum, this)); - } - isNew = false; - } catch (XmlException e) { - throw new POIXMLException(); - } finally { - is.close(); - } - } - - /** - * save and commit numbering - */ - @Override - protected void commit() throws IOException { - XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS); - xmlOptions.setSaveSyntheticDocumentElement(new QName(CTNumbering.type.getName().getNamespaceURI(), "numbering")); - PackagePart part = getPackagePart(); - OutputStream out = part.getOutputStream(); - ctNumbering.save(out, xmlOptions); - out.close(); - } - - - /** - * Sets the ctNumbering - * - * @param numbering - */ - public void setNumbering(CTNumbering numbering) { - ctNumbering = numbering; - } - - - /** - * Checks whether number with numID exists - * - * @param numID - * @return boolean true if num exist, false if num not exist - */ - public boolean numExist(BigInteger numID) { - for (XWPFNum num : nums) { - if (num.getCTNum().getNumId().equals(numID)) - return true; - } - return false; - } - - /** - * add a new number to the numbering document - * - * @param num - */ - public BigInteger addNum(XWPFNum num) { - ctNumbering.addNewNum(); - int pos = ctNumbering.sizeOfNumArray() - 1; - ctNumbering.setNumArray(pos, num.getCTNum()); - nums.add(num); - return num.getCTNum().getNumId(); - } - - /** - * Add a new num with an abstractNumID - * - * @return return NumId of the added num - */ - public BigInteger addNum(BigInteger abstractNumID) { - CTNum ctNum = this.ctNumbering.addNewNum(); - ctNum.addNewAbstractNumId(); - ctNum.getAbstractNumId().setVal(abstractNumID); - ctNum.setNumId(BigInteger.valueOf(nums.size() + 1)); - XWPFNum num = new XWPFNum(ctNum, this); - nums.add(num); - return ctNum.getNumId(); - } - - /** - * Add a new num with an abstractNumID and a numID - * - * @param abstractNumID - * @param numID - */ - public void addNum(BigInteger abstractNumID, BigInteger numID) { - CTNum ctNum = this.ctNumbering.addNewNum(); - ctNum.addNewAbstractNumId(); - ctNum.getAbstractNumId().setVal(abstractNumID); - ctNum.setNumId(numID); - XWPFNum num = new XWPFNum(ctNum, this); - nums.add(num); - } - - /** - * get Num by NumID - * - * @param numID - * @return abstractNum with NumId if no Num exists with that NumID - * null will be returned - */ - public XWPFNum getNum(BigInteger numID) { - for (XWPFNum num : nums) { - if (num.getCTNum().getNumId().equals(numID)) - return num; - } - return null; - } - - /** - * get AbstractNum by abstractNumID - * - * @param abstractNumID - * @return abstractNum with abstractNumId if no abstractNum exists with that abstractNumID - * null will be returned - */ - public XWPFAbstractNum getAbstractNum(BigInteger abstractNumID) { - for (XWPFAbstractNum abstractNum : abstractNums) { - if (abstractNum.getAbstractNum().getAbstractNumId().equals(abstractNumID)) { - return abstractNum; - } - } - return null; - } - - /** - * Compare AbstractNum with abstractNums of this numbering document. - * If the content of abstractNum equals with an abstractNum of the List in numbering - * the BigInteger Value of it will be returned. - * If no equal abstractNum is existing null will be returned - * - * @param abstractNum - * @return BigInteger - */ - public BigInteger getIdOfAbstractNum(XWPFAbstractNum abstractNum) { - CTAbstractNum copy = (CTAbstractNum) abstractNum.getCTAbstractNum().copy(); - XWPFAbstractNum newAbstractNum = new XWPFAbstractNum(copy, this); - int i; - for (i = 0; i < abstractNums.size(); i++) { - newAbstractNum.getCTAbstractNum().setAbstractNumId(BigInteger.valueOf(i)); - newAbstractNum.setNumbering(this); - if (newAbstractNum.getCTAbstractNum().valueEquals(abstractNums.get(i).getCTAbstractNum())) { - return newAbstractNum.getCTAbstractNum().getAbstractNumId(); - } - } - return null; - } - - - /** - * add a new AbstractNum and return its AbstractNumID - * - * @param abstractNum - */ - public BigInteger addAbstractNum(XWPFAbstractNum abstractNum) { - int pos = abstractNums.size(); - if (abstractNum.getAbstractNum() != null) { // Use the current CTAbstractNum if it exists - ctNumbering.addNewAbstractNum().set(abstractNum.getAbstractNum()); - } else { - ctNumbering.addNewAbstractNum(); - abstractNum.getAbstractNum().setAbstractNumId(BigInteger.valueOf(pos)); - ctNumbering.setAbstractNumArray(pos, abstractNum.getAbstractNum()); - } - abstractNums.add(abstractNum); - return abstractNum.getCTAbstractNum().getAbstractNumId(); - } - - /** - * remove an existing abstractNum - * - * @param abstractNumID - * @return true if abstractNum with abstractNumID exists in NumberingArray, - * false if abstractNum with abstractNumID not exists - */ - public boolean removeAbstractNum(BigInteger abstractNumID) { - if (abstractNumID.byteValue() < abstractNums.size()) { - ctNumbering.removeAbstractNum(abstractNumID.byteValue()); - abstractNums.remove(abstractNumID.byteValue()); - return true; - } - return false; - } - - /** - * return the abstractNumID - * If the AbstractNumID not exists - * return null - * - * @param numID - * @return abstractNumID - */ - public BigInteger getAbstractNumID(BigInteger numID) { - XWPFNum num = getNum(numID); - if (num == null) - return null; - if (num.getCTNum() == null) - return null; - if (num.getCTNum().getAbstractNumId() == null) - return null; - return num.getCTNum().getAbstractNumId().getVal(); - } -} - diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFParagraph.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFParagraph.java deleted file mode 100644 index 0fbc65ec0..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFParagraph.java +++ /dev/null @@ -1,1649 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.util.Internal; -import org.apache.poi.wp.usermodel.Paragraph; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlObject; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.*; - -/** - *

    A Paragraph within a Document, Table, Header etc.

    - *

    - *

    A paragraph has a lot of styling information, but the - * actual text (possibly along with more styling) is held on - * the child {@link XWPFRun}s.

    - */ -public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Paragraph { - private final CTP paragraph; - protected IBody part; - /** - * For access to the document's hyperlink, comments, tables etc - */ - protected XWPFDocument document; - protected List runs; - protected List iruns; - - private StringBuffer footnoteText = new StringBuffer(); - - public XWPFParagraph(CTP prgrph, IBody part) { - this.paragraph = prgrph; - this.part = part; - - this.document = part.getXWPFDocument(); - - if (document == null) { - throw new NullPointerException(); - } - - // Build up the character runs - runs = new ArrayList(); - iruns = new ArrayList(); - buildRunsInOrderFromXml(paragraph); - - // Look for bits associated with the runs - for (XWPFRun run : runs) { - CTR r = run.getCTR(); - - // Check for bits that only apply when attached to a core document - // TODO Make this nicer by tracking the XWPFFootnotes directly - XmlCursor c = r.newCursor(); - c.selectPath("child::*"); - while (c.toNextSelection()) { - XmlObject o = c.getObject(); - if (o instanceof CTFtnEdnRef) { - CTFtnEdnRef ftn = (CTFtnEdnRef) o; - footnoteText.append(" [").append(ftn.getId()).append(": "); - XWPFFootnote footnote = - ftn.getDomNode().getLocalName().equals("footnoteReference") ? - document.getFootnoteByID(ftn.getId().intValue()) : - document.getEndnoteByID(ftn.getId().intValue()); - - boolean first = true; - for (XWPFParagraph p : footnote.getParagraphs()) { - if (!first) { - footnoteText.append("\n"); - } - first = false; - footnoteText.append(p.getText()); - } - - footnoteText.append("] "); - } - } - c.dispose(); - } - } - - /** - * Identifies (in order) the parts of the paragraph / - * sub-paragraph that correspond to character text - * runs, and builds the appropriate runs for these. - */ - @SuppressWarnings("deprecation") - private void buildRunsInOrderFromXml(XmlObject object) { - XmlCursor c = object.newCursor(); - c.selectPath("child::*"); - while (c.toNextSelection()) { - XmlObject o = c.getObject(); - if (o instanceof CTR) { - XWPFRun r = new XWPFRun((CTR) o, this); - runs.add(r); - iruns.add(r); - } - if (o instanceof CTHyperlink) { - CTHyperlink link = (CTHyperlink)o; - for (CTR r : link.getRArray()) { - XWPFHyperlinkRun hr = new XWPFHyperlinkRun(link, r, this); - runs.add(hr); - iruns.add(hr); - } - } - if (o instanceof CTSimpleField) { - CTSimpleField field = (CTSimpleField)o; - for (CTR r : field.getRArray()) { - XWPFFieldRun fr = new XWPFFieldRun(field, r, this); - runs.add(fr); - iruns.add(fr); - } - } - if (o instanceof CTSdtBlock) { - XWPFSDT cc = new XWPFSDT((CTSdtBlock) o, part); - iruns.add(cc); - } - if (o instanceof CTSdtRun) { - XWPFSDT cc = new XWPFSDT((CTSdtRun) o, part); - iruns.add(cc); - } - if (o instanceof CTRunTrackChange) { - for (CTR r : ((CTRunTrackChange) o).getRArray()) { - XWPFRun cr = new XWPFRun(r, this); - runs.add(cr); - iruns.add(cr); - } - } - if (o instanceof CTSmartTagRun) { - // Smart Tags can be nested many times. - // This implementation does not preserve the tagging information - buildRunsInOrderFromXml(o); - } - } - c.dispose(); - } - - @Internal - public CTP getCTP() { - return paragraph; - } - - public List getRuns() { - return Collections.unmodifiableList(runs); - } - - /** - * Return literal runs and sdt/content control objects. - * - * @return List - */ - public List getIRuns() { - return Collections.unmodifiableList(iruns); - } - - public boolean isEmpty() { - return !paragraph.getDomNode().hasChildNodes(); - } - - @Override - public XWPFDocument getDocument() { - return document; - } - - /** - * Return the textual content of the paragraph, including text from pictures - * and sdt elements in it. - */ - public String getText() { - StringBuffer out = new StringBuffer(); - for (IRunElement run : iruns) { - if (run instanceof XWPFRun) { - XWPFRun xRun = (XWPFRun) run; - // don't include the text if reviewing is enabled and this is a deleted run - if (!xRun.getCTR().isSetRsidDel()) { - out.append(xRun.toString()); - } - } else if (run instanceof XWPFSDT) { - out.append(((XWPFSDT) run).getContent().getText()); - } else { - out.append(run.toString()); - } - } - out.append(footnoteText); - return out.toString(); - } - - /** - * Return styleID of the paragraph if style exist for this paragraph - * if not, null will be returned - * - * @return styleID as String - */ - public String getStyleID() { - if (paragraph.getPPr() != null) { - if (paragraph.getPPr().getPStyle() != null) { - if (paragraph.getPPr().getPStyle().getVal() != null) { - return paragraph.getPPr().getPStyle().getVal(); - } - } - } - return null; - } - - /** - * If style exist for this paragraph - * NumId of the paragraph will be returned. - * If style not exist null will be returned - * - * @return NumID as BigInteger - */ - public BigInteger getNumID() { - if (paragraph.getPPr() != null) { - if (paragraph.getPPr().getNumPr() != null) { - if (paragraph.getPPr().getNumPr().getNumId() != null) { - return paragraph.getPPr().getNumPr().getNumId().getVal(); - } - } - } - return null; - } - - /** - * setNumID of Paragraph - * - * @param numPos - */ - public void setNumID(BigInteger numPos) { - if (paragraph.getPPr() == null) { - paragraph.addNewPPr(); - } - if (paragraph.getPPr().getNumPr() == null) { - paragraph.getPPr().addNewNumPr(); - } - if (paragraph.getPPr().getNumPr().getNumId() == null) { - paragraph.getPPr().getNumPr().addNewNumId(); - } - paragraph.getPPr().getNumPr().getNumId().setVal(numPos); - } - - /** - * Returns Ilvl of the numeric style for this paragraph. - * Returns null if this paragraph does not have numeric style. - * - * @return Ilvl as BigInteger - */ - public BigInteger getNumIlvl() { - if (paragraph.getPPr() != null) { - if (paragraph.getPPr().getNumPr() != null) { - if (paragraph.getPPr().getNumPr().getIlvl() != null) { - return paragraph.getPPr().getNumPr().getIlvl().getVal(); - } - } - } - return null; - } - - /** - * Returns numbering format for this paragraph, eg bullet or - * lowerLetter. - * Returns null if this paragraph does not have numeric style. - */ - public String getNumFmt() { - BigInteger numID = getNumID(); - XWPFNumbering numbering = document.getNumbering(); - if (numID != null && numbering != null) { - XWPFNum num = numbering.getNum(numID); - if (num != null) { - BigInteger ilvl = getNumIlvl(); - BigInteger abstractNumId = num.getCTNum().getAbstractNumId().getVal(); - CTAbstractNum anum = numbering.getAbstractNum(abstractNumId).getAbstractNum(); - CTLvl level = null; - for (int i = 0; i < anum.sizeOfLvlArray(); i++) { - CTLvl lvl = anum.getLvlArray(i); - if (lvl.getIlvl().equals(ilvl)) { - level = lvl; - break; - } - } - if (level != null && level.getNumFmt() != null - && level.getNumFmt().getVal() != null) { - return level.getNumFmt().getVal().toString(); - } - } - } - return null; - } - - /** - * Returns the text that should be used around the paragraph level numbers. - * - * @return a string (e.g. "%1.") or null if the value is not found. - */ - public String getNumLevelText() { - BigInteger numID = getNumID(); - XWPFNumbering numbering = document.getNumbering(); - if (numID != null && numbering != null) { - XWPFNum num = numbering.getNum(numID); - if (num != null) { - BigInteger ilvl = getNumIlvl(); - CTNum ctNum = num.getCTNum(); - if (ctNum == null) { - return null; - } - - CTDecimalNumber ctDecimalNumber = ctNum.getAbstractNumId(); - if (ctDecimalNumber == null) { - return null; - } - - BigInteger abstractNumId = ctDecimalNumber.getVal(); - if (abstractNumId == null) { - return null; - } - - XWPFAbstractNum xwpfAbstractNum = numbering.getAbstractNum(abstractNumId); - - if (xwpfAbstractNum == null) { - return null; - } - - CTAbstractNum anum = xwpfAbstractNum.getCTAbstractNum(); - - if (anum == null) { - return null; - } - - CTLvl level = null; - for (int i = 0; i < anum.sizeOfLvlArray(); i++) { - CTLvl lvl = anum.getLvlArray(i); - if (lvl != null && lvl.getIlvl() != null && lvl.getIlvl().equals(ilvl)) { - level = lvl; - break; - } - } - if (level != null && level.getLvlText() != null - && level.getLvlText().getVal() != null) { - return level.getLvlText().getVal().toString(); - } - } - } - return null; - } - - /** - * Gets the numstartOverride for the paragraph numbering for this paragraph. - * - * @return returns the overridden start number or null if there is no override for this paragraph. - */ - public BigInteger getNumStartOverride() { - BigInteger numID = getNumID(); - XWPFNumbering numbering = document.getNumbering(); - if (numID != null && numbering != null) { - XWPFNum num = numbering.getNum(numID); - - if (num != null) { - CTNum ctNum = num.getCTNum(); - if (ctNum == null) { - return null; - } - BigInteger ilvl = getNumIlvl(); - CTNumLvl level = null; - for (int i = 0; i < ctNum.sizeOfLvlOverrideArray(); i++) { - CTNumLvl ctNumLvl = ctNum.getLvlOverrideArray(i); - if (ctNumLvl != null && ctNumLvl.getIlvl() != null && - ctNumLvl.getIlvl().equals(ilvl)) { - level = ctNumLvl; - break; - } - } - if (level != null && level.getStartOverride() != null) { - return level.getStartOverride().getVal(); - } - } - } - return null; - } - - /** - * Returns the text of the paragraph, but not of any objects in the - * paragraph - */ - public String getParagraphText() { - StringBuffer out = new StringBuffer(); - for (XWPFRun run : runs) { - out.append(run.toString()); - } - return out.toString(); - } - - /** - * Returns any text from any suitable pictures in the paragraph - */ - public String getPictureText() { - StringBuffer out = new StringBuffer(); - for (XWPFRun run : runs) { - out.append(run.getPictureText()); - } - return out.toString(); - } - - /** - * Returns the footnote text of the paragraph - * - * @return the footnote text or empty string if the paragraph does not have footnotes - */ - public String getFootnoteText() { - return footnoteText.toString(); - } - - /** - * Returns the paragraph alignment which shall be applied to text in this - * paragraph. - *

    - *

    - * If this element is not set on a given paragraph, its value is determined - * by the setting previously set at any level of the style hierarchy (i.e. - * that previous setting remains unchanged). If this setting is never - * specified in the style hierarchy, then no alignment is applied to the - * paragraph. - *

    - * - * @return the paragraph alignment of this paragraph. - */ - public ParagraphAlignment getAlignment() { - CTPPr pr = getCTPPr(); - return pr == null || !pr.isSetJc() ? ParagraphAlignment.LEFT - : ParagraphAlignment.valueOf(pr.getJc().getVal().intValue()); - } - - /** - * Specifies the paragraph alignment which shall be applied to text in this - * paragraph. - *

    - *

    - * If this element is not set on a given paragraph, its value is determined - * by the setting previously set at any level of the style hierarchy (i.e. - * that previous setting remains unchanged). If this setting is never - * specified in the style hierarchy, then no alignment is applied to the - * paragraph. - *

    - * - * @param align the paragraph alignment to apply to this paragraph. - */ - public void setAlignment(ParagraphAlignment align) { - CTPPr pr = getCTPPr(); - CTJc jc = pr.isSetJc() ? pr.getJc() : pr.addNewJc(); - STJc.Enum en = STJc.Enum.forInt(align.getValue()); - jc.setVal(en); - } - - /** - * @return The raw alignment value, {@link #getAlignment()} is suggested - */ - @Override - public int getFontAlignment() { - return getAlignment().getValue(); - } - - @Override - public void setFontAlignment(int align) { - ParagraphAlignment pAlign = ParagraphAlignment.valueOf(align); - setAlignment(pAlign); - } - - /** - * Returns the text vertical alignment which shall be applied to text in - * this paragraph. - *

    - * If the line height (before any added spacing) is larger than one or more - * characters on the line, all characters will be aligned to each other as - * specified by this element. - *

    - *

    - * If this element is omitted on a given paragraph, its value is determined - * by the setting previously set at any level of the style hierarchy (i.e. - * that previous setting remains unchanged). If this setting is never - * specified in the style hierarchy, then the vertical alignment of all - * characters on the line shall be automatically determined by the consumer. - *

    - * - * @return the vertical alignment of this paragraph. - */ - public TextAlignment getVerticalAlignment() { - CTPPr pr = getCTPPr(); - return (pr == null || !pr.isSetTextAlignment()) ? TextAlignment.AUTO - : TextAlignment.valueOf(pr.getTextAlignment().getVal() - .intValue()); - } - - /** - * Specifies the text vertical alignment which shall be applied to text in - * this paragraph. - *

    - * If the line height (before any added spacing) is larger than one or more - * characters on the line, all characters will be aligned to each other as - * specified by this element. - *

    - *

    - * If this element is omitted on a given paragraph, its value is determined - * by the setting previously set at any level of the style hierarchy (i.e. - * that previous setting remains unchanged). If this setting is never - * specified in the style hierarchy, then the vertical alignment of all - * characters on the line shall be automatically determined by the consumer. - *

    - * - * @param valign the paragraph vertical alignment to apply to this - * paragraph. - */ - public void setVerticalAlignment(TextAlignment valign) { - CTPPr pr = getCTPPr(); - CTTextAlignment textAlignment = pr.isSetTextAlignment() ? pr - .getTextAlignment() : pr.addNewTextAlignment(); - STTextAlignment.Enum en = STTextAlignment.Enum - .forInt(valign.getValue()); - textAlignment.setVal(en); - } - - /** - * Specifies the border which shall be displayed above a set of paragraphs - * which have the same set of paragraph border settings. - * - * @return paragraphBorder - the top border for the paragraph - * @see #setBorderTop(Borders) - * @see Borders a list of all types of borders - */ - public Borders getBorderTop() { - CTPBdr border = getCTPBrd(false); - CTBorder ct = null; - if (border != null) { - ct = border.getTop(); - } - STBorder.Enum ptrn = (ct != null) ? ct.getVal() : STBorder.NONE; - return Borders.valueOf(ptrn.intValue()); - } - - /** - * Specifies the border which shall be displayed above a set of paragraphs - * which have the same set of paragraph border settings. - *

    - *

    - * To determine if any two adjoining paragraphs shall have an individual top - * and bottom border or a between border, the set of borders on the two - * adjoining paragraphs are compared. If the border information on those two - * paragraphs is identical for all possible paragraphs borders, then the - * between border is displayed. Otherwise, the final paragraph shall use its - * bottom border and the following paragraph shall use its top border, - * respectively. If this border specifies a space attribute, that value - * determines the space above the text (ignoring any spacing above) which - * should be left before this border is drawn, specified in points. - *

    - *

    - * If this element is omitted on a given paragraph, its value is determined - * by the setting previously set at any level of the style hierarchy (i.e. - * that previous setting remains unchanged). If this setting is never - * specified in the style hierarchy, then no between border shall be applied - * above identical paragraphs. - *

    - * This border can only be a line border. - * - * @param border - * @see Borders for a list of all types of borders - */ - public void setBorderTop(Borders border) { - CTPBdr ct = getCTPBrd(true); - if (ct == null) { - throw new RuntimeException("invalid paragraph state"); - } - - CTBorder pr = (ct.isSetTop()) ? ct.getTop() : ct.addNewTop(); - if (border.getValue() == Borders.NONE.getValue()) { - ct.unsetTop(); - } else { - pr.setVal(STBorder.Enum.forInt(border.getValue())); - } - } - - /** - * Specifies the border which shall be displayed below a set of - * paragraphs which have the same set of paragraph border settings. - * - * @return paragraphBorder - the bottom border for the paragraph - * @see #setBorderBottom(Borders) - * @see Borders a list of all types of borders - */ - public Borders getBorderBottom() { - CTPBdr border = getCTPBrd(false); - CTBorder ct = null; - if (border != null) { - ct = border.getBottom(); - } - STBorder.Enum ptrn = ct != null ? ct.getVal() : STBorder.NONE; - return Borders.valueOf(ptrn.intValue()); - } - - /** - * Specifies the border which shall be displayed below a set of paragraphs - * which have the same set of paragraph border settings. - *

    - * To determine if any two adjoining paragraphs shall have an individual top - * and bottom border or a between border, the set of borders on the two - * adjoining paragraphs are compared. If the border information on those two - * paragraphs is identical for all possible paragraphs borders, then the - * between border is displayed. Otherwise, the final paragraph shall use its - * bottom border and the following paragraph shall use its top border, - * respectively. If this border specifies a space attribute, that value - * determines the space after the bottom of the text (ignoring any space - * below) which should be left before this border is drawn, specified in - * points. - *

    - *

    - * If this element is omitted on a given paragraph, its value is determined - * by the setting previously set at any level of the style hierarchy (i.e. - * that previous setting remains unchanged). If this setting is never - * specified in the style hierarchy, then no between border shall be applied - * below identical paragraphs. - *

    - * This border can only be a line border. - * - * @param border - * @see Borders a list of all types of borders - */ - public void setBorderBottom(Borders border) { - CTPBdr ct = getCTPBrd(true); - CTBorder pr = ct.isSetBottom() ? ct.getBottom() : ct.addNewBottom(); - if (border.getValue() == Borders.NONE.getValue()) { - ct.unsetBottom(); - } else { - pr.setVal(STBorder.Enum.forInt(border.getValue())); - } - } - - /** - * Specifies the border which shall be displayed on the left side of the - * page around the specified paragraph. - * - * @return ParagraphBorder - the left border for the paragraph - * @see #setBorderLeft(Borders) - * @see Borders for a list of all possible borders - */ - public Borders getBorderLeft() { - CTPBdr border = getCTPBrd(false); - CTBorder ct = null; - if (border != null) { - ct = border.getLeft(); - } - STBorder.Enum ptrn = ct != null ? ct.getVal() : STBorder.NONE; - return Borders.valueOf(ptrn.intValue()); - } - - /** - * Specifies the border which shall be displayed on the left side of the - * page around the specified paragraph. - *

    - * To determine if any two adjoining paragraphs should have a left border - * which spans the full line height or not, the left border shall be drawn - * between the top border or between border at the top (whichever would be - * rendered for the current paragraph), and the bottom border or between - * border at the bottom (whichever would be rendered for the current - * paragraph). - *

    - *

    - * If this element is omitted on a given paragraph, its value is determined - * by the setting previously set at any level of the style hierarchy (i.e. - * that previous setting remains unchanged). If this setting is never - * specified in the style hierarchy, then no left border shall be applied. - *

    - * This border can only be a line border. - * - * @param border - * @see Borders for a list of all possible borders - */ - public void setBorderLeft(Borders border) { - CTPBdr ct = getCTPBrd(true); - CTBorder pr = ct.isSetLeft() ? ct.getLeft() : ct.addNewLeft(); - if (border.getValue() == Borders.NONE.getValue()) { - ct.unsetLeft(); - } else { - pr.setVal(STBorder.Enum.forInt(border.getValue())); - } - } - - /** - * Specifies the border which shall be displayed on the right side of the - * page around the specified paragraph. - * - * @return ParagraphBorder - the right border for the paragraph - * @see #setBorderRight(Borders) - * @see Borders for a list of all possible borders - */ - public Borders getBorderRight() { - CTPBdr border = getCTPBrd(false); - CTBorder ct = null; - if (border != null) { - ct = border.getRight(); - } - STBorder.Enum ptrn = ct != null ? ct.getVal() : STBorder.NONE; - return Borders.valueOf(ptrn.intValue()); - } - - /** - * Specifies the border which shall be displayed on the right side of the - * page around the specified paragraph. - *

    - * To determine if any two adjoining paragraphs should have a right border - * which spans the full line height or not, the right border shall be drawn - * between the top border or between border at the top (whichever would be - * rendered for the current paragraph), and the bottom border or between - * border at the bottom (whichever would be rendered for the current - * paragraph). - *

    - *

    - * If this element is omitted on a given paragraph, its value is determined - * by the setting previously set at any level of the style hierarchy (i.e. - * that previous setting remains unchanged). If this setting is never - * specified in the style hierarchy, then no right border shall be applied. - *

    - * This border can only be a line border. - * - * @param border - * @see Borders for a list of all possible borders - */ - public void setBorderRight(Borders border) { - CTPBdr ct = getCTPBrd(true); - CTBorder pr = ct.isSetRight() ? ct.getRight() : ct.addNewRight(); - if (border.getValue() == Borders.NONE.getValue()) { - ct.unsetRight(); - } else { - pr.setVal(STBorder.Enum.forInt(border.getValue())); - } - } - - /** - * Specifies the border which shall be displayed between each paragraph in a - * set of paragraphs which have the same set of paragraph border settings. - * - * @return ParagraphBorder - the between border for the paragraph - * @see #setBorderBetween(Borders) - * @see Borders for a list of all possible borders - */ - public Borders getBorderBetween() { - CTPBdr border = getCTPBrd(false); - CTBorder ct = null; - if (border != null) { - ct = border.getBetween(); - } - STBorder.Enum ptrn = ct != null ? ct.getVal() : STBorder.NONE; - return Borders.valueOf(ptrn.intValue()); - } - - /** - * Specifies the border which shall be displayed between each paragraph in a - * set of paragraphs which have the same set of paragraph border settings. - *

    - * To determine if any two adjoining paragraphs should have a between border - * or an individual top and bottom border, the set of borders on the two - * adjoining paragraphs are compared. If the border information on those two - * paragraphs is identical for all possible paragraphs borders, then the - * between border is displayed. Otherwise, each paragraph shall use its - * bottom and top border, respectively. If this border specifies a space - * attribute, that value is ignored - this border is always located at the - * bottom of each paragraph with an identical following paragraph, taking - * into account any space after the line pitch. - *

    - *

    - * If this element is omitted on a given paragraph, its value is determined - * by the setting previously set at any level of the style hierarchy (i.e. - * that previous setting remains unchanged). If this setting is never - * specified in the style hierarchy, then no between border shall be applied - * between identical paragraphs. - *

    - * This border can only be a line border. - * - * @param border - * @see Borders for a list of all possible borders - */ - public void setBorderBetween(Borders border) { - CTPBdr ct = getCTPBrd(true); - CTBorder pr = ct.isSetBetween() ? ct.getBetween() : ct.addNewBetween(); - if (border.getValue() == Borders.NONE.getValue()) { - ct.unsetBetween(); - } else { - pr.setVal(STBorder.Enum.forInt(border.getValue())); - } - } - - /** - * Specifies that when rendering this document in a paginated - * view, the contents of this paragraph are rendered on the start of a new - * page in the document. - *

    - * If this element is omitted on a given paragraph, - * its value is determined by the setting previously set at any level of the - * style hierarchy (i.e. that previous setting remains unchanged). If this - * setting is never specified in the style hierarchy, then this property - * shall not be applied. Since the paragraph is specified to start on a new - * page, it begins page two even though it could have fit on page one. - *

    - * - * @return boolean - if page break is set - */ - public boolean isPageBreak() { - CTPPr ppr = getCTPPr(); - CTOnOff ctPageBreak = ppr.isSetPageBreakBefore() ? ppr - .getPageBreakBefore() : null; - if (ctPageBreak != null - && ctPageBreak.getVal().intValue() == STOnOff.INT_TRUE) { - return true; - } - return false; - } - - /** - * Specifies that when rendering this document in a paginated - * view, the contents of this paragraph are rendered on the start of a new - * page in the document. - *

    - * If this element is omitted on a given paragraph, - * its value is determined by the setting previously set at any level of the - * style hierarchy (i.e. that previous setting remains unchanged). If this - * setting is never specified in the style hierarchy, then this property - * shall not be applied. Since the paragraph is specified to start on a new - * page, it begins page two even though it could have fit on page one. - *

    - * - * @param pageBreak - - * boolean value - */ - public void setPageBreak(boolean pageBreak) { - CTPPr ppr = getCTPPr(); - CTOnOff ctPageBreak = ppr.isSetPageBreakBefore() ? ppr - .getPageBreakBefore() : ppr.addNewPageBreakBefore(); - if (pageBreak) { - ctPageBreak.setVal(STOnOff.TRUE); - } else { - ctPageBreak.setVal(STOnOff.FALSE); - } - } - - /** - * Specifies the spacing that should be added after the last line in this - * paragraph in the document in absolute units. - * - * @return int - value representing the spacing after the paragraph - */ - public int getSpacingAfter() { - CTSpacing spacing = getCTSpacing(false); - return (spacing != null && spacing.isSetAfter()) ? spacing.getAfter().intValue() : -1; - } - - /** - * Specifies the spacing that should be added after the last line in this - * paragraph in the document in absolute units. - *

    - * If the afterLines attribute or the afterAutoSpacing attribute is also - * specified, then this attribute value is ignored. - *

    - * - * @param spaces - - * a positive whole number, whose contents consist of a - * measurement in twentieths of a point. - */ - public void setSpacingAfter(int spaces) { - CTSpacing spacing = getCTSpacing(true); - if (spacing != null) { - BigInteger bi = new BigInteger("" + spaces); - spacing.setAfter(bi); - } - - } - - /** - * Specifies the spacing that should be added after the last line in this - * paragraph in the document in absolute units. - * - * @return int - value representing the spacing after the paragraph - * @see #setSpacingAfterLines(int) - */ - public int getSpacingAfterLines() { - CTSpacing spacing = getCTSpacing(false); - return (spacing != null && spacing.isSetAfterLines()) ? spacing.getAfterLines().intValue() : -1; - } - - /** - * Specifies the spacing that should be added after the last line in this - * paragraph in the document in line units. - * The value of this attribute is - * specified in one hundredths of a line. - * - *

    - * If the afterAutoSpacing attribute - * is also specified, then this attribute value is ignored. If this setting - * is never specified in the style hierarchy, then its value shall be zero - * (if needed) - *

    - * - * @param spaces - - * a positive whole number, whose contents consist of a - * measurement in hundredths of a line - */ - public void setSpacingAfterLines(int spaces) { - CTSpacing spacing = getCTSpacing(true); - BigInteger bi = new BigInteger("" + spaces); - spacing.setAfterLines(bi); - } - - /** - * Specifies the spacing that should be added above the first line in this - * paragraph in the document in absolute units. - * - * @return the spacing that should be added above the first line - * @see #setSpacingBefore(int) - */ - public int getSpacingBefore() { - CTSpacing spacing = getCTSpacing(false); - return (spacing != null && spacing.isSetBefore()) ? spacing.getBefore().intValue() : -1; - } - - /** - * Specifies the spacing that should be added above the first line in this - * paragraph in the document in absolute units. - *

    - * If the beforeLines attribute or the beforeAutoSpacing attribute is also - * specified, then this attribute value is ignored. - *

    - * - * @param spaces - */ - public void setSpacingBefore(int spaces) { - CTSpacing spacing = getCTSpacing(true); - BigInteger bi = new BigInteger("" + spaces); - spacing.setBefore(bi); - } - - /** - * Specifies the spacing that should be added before the first line in this paragraph in the - * document in line units. - * The value of this attribute is specified in one hundredths of a line. - * - * @return the spacing that should be added before the first line in this paragraph - * @see #setSpacingBeforeLines(int) - */ - public int getSpacingBeforeLines() { - CTSpacing spacing = getCTSpacing(false); - return (spacing != null && spacing.isSetBeforeLines()) ? spacing.getBeforeLines().intValue() : -1; - } - - /** - * Specifies the spacing that should be added before the first line in this - * paragraph in the document in line units. The value of this attribute - * is specified in one hundredths of a line. - *

    - * If the beforeAutoSpacing attribute is also specified, then this attribute - * value is ignored. If this setting is never specified in the style - * hierarchy, then its value shall be zero. - *

    - * - * @param spaces - */ - public void setSpacingBeforeLines(int spaces) { - CTSpacing spacing = getCTSpacing(true); - BigInteger bi = new BigInteger("" + spaces); - spacing.setBeforeLines(bi); - } - - /** - * Specifies how the spacing between lines is calculated as stored in the - * line attribute. If this attribute is omitted, then it shall be assumed to - * be of a value auto if a line attribute value is present. - * - * @return rule - * @see LineSpacingRule - * @see #setSpacingLineRule(LineSpacingRule) - */ - public LineSpacingRule getSpacingLineRule() { - CTSpacing spacing = getCTSpacing(false); - return (spacing != null && spacing.isSetLineRule()) ? LineSpacingRule.valueOf(spacing - .getLineRule().intValue()) : LineSpacingRule.AUTO; - } - - /** - * Specifies how the spacing between lines is calculated as stored in the - * line attribute. If this attribute is omitted, then it shall be assumed to - * be of a value auto if a line attribute value is present. - * - * @param rule - * @see LineSpacingRule - */ - // TODO Fix this to convert line to equivalent value, or deprecate this in - // favor of setSpacingLine(double, LineSpacingRule) - public void setSpacingLineRule(LineSpacingRule rule) { - CTSpacing spacing = getCTSpacing(true); - spacing.setLineRule(STLineSpacingRule.Enum.forInt(rule.getValue())); - } - - /** - * Return the spacing between lines of a paragraph. The units of the return value depends on the - * {@link LineSpacingRule}. If AUTO, the return value is in lines, otherwise the return - * value is in points - * - * @return a double specifying points or lines. - */ - public double getSpacingBetween() { - CTSpacing spacing = getCTSpacing(false); - if (spacing == null || !spacing.isSetLine()) { - return -1; - } else if (spacing.getLineRule() == null || spacing.getLineRule() == STLineSpacingRule.AUTO) { - BigInteger[] val = spacing.getLine().divideAndRemainder(BigInteger.valueOf(240L)); - return val[0].doubleValue() + (val[1].doubleValue() / 240L); - } - BigInteger[] val = spacing.getLine().divideAndRemainder(BigInteger.valueOf(20L)); - return val[0].doubleValue() + (val[1].doubleValue() / 20L); - } - - /** - * Sets the spacing between lines in a paragraph - * - * @param spacing - A double specifying spacing in inches or lines. If rule is - * AUTO, then spacing is in lines. Otherwise spacing is in points. - * @param rule - {@link LineSpacingRule} indicating how spacing is interpreted. If - * AUTO, then spacing value is in lines, and the height depends on the - * font size. If AT_LEAST, then spacing value is in inches, and is the - * minimum size of the line. If the line height is taller, then the - * line expands to match. If EXACT, then spacing is the exact line - * height. If the text is taller than the line height, then it is - * clipped at the top. - */ - public void setSpacingBetween(double spacing, LineSpacingRule rule) { - CTSpacing ctSp = getCTSpacing(true); - switch (rule) { - case AUTO: - ctSp.setLine(new BigInteger(String.valueOf(Math.round(spacing * 240.0)))); - break; - default: - ctSp.setLine(new BigInteger(String.valueOf(Math.round(spacing * 20.0)))); - } - ctSp.setLineRule(STLineSpacingRule.Enum.forInt(rule.getValue())); - } - - /** - * Sets the spacing between lines in a paragraph - * - * @param spacing - A double specifying spacing in lines. - */ - public void setSpacingBetween(double spacing) { - setSpacingBetween(spacing, LineSpacingRule.AUTO); - } - - /** - * Specifies the indentation which shall be placed between the left text - * margin for this paragraph and the left edge of that paragraph's content - * in a left to right paragraph, and the right text margin and the right - * edge of that paragraph's text in a right to left paragraph - *

    - * If this attribute is omitted, its value shall be assumed to be zero. - * Negative values are defined such that the text is moved past the text margin, - * positive values move the text inside the text margin. - *

    - * - * @return indentation or null if indentation is not set - */ - public int getIndentationLeft() { - CTInd indentation = getCTInd(false); - return (indentation != null && indentation.isSetLeft()) ? indentation.getLeft().intValue() - : -1; - } - - /** - * Specifies the indentation which shall be placed between the left text - * margin for this paragraph and the left edge of that paragraph's content - * in a left to right paragraph, and the right text margin and the right - * edge of that paragraph's text in a right to left paragraph - *

    - * If this attribute is omitted, its value shall be assumed to be zero. - * Negative values are defined such that the text is moved past the text margin, - * positive values move the text inside the text margin. - *

    - * - * @param indentation - */ - public void setIndentationLeft(int indentation) { - CTInd indent = getCTInd(true); - BigInteger bi = new BigInteger("" + indentation); - indent.setLeft(bi); - } - - /** - * Specifies the indentation which shall be placed between the right text - * margin for this paragraph and the right edge of that paragraph's content - * in a left to right paragraph, and the right text margin and the right - * edge of that paragraph's text in a right to left paragraph - *

    - * If this attribute is omitted, its value shall be assumed to be zero. - * Negative values are defined such that the text is moved past the text margin, - * positive values move the text inside the text margin. - *

    - * - * @return indentation or null if indentation is not set - */ - - public int getIndentationRight() { - CTInd indentation = getCTInd(false); - return (indentation != null && indentation.isSetRight()) ? indentation.getRight().intValue() - : -1; - } - - /** - * Specifies the indentation which shall be placed between the right text - * margin for this paragraph and the right edge of that paragraph's content - * in a left to right paragraph, and the right text margin and the right - * edge of that paragraph's text in a right to left paragraph - *

    - * If this attribute is omitted, its value shall be assumed to be zero. - * Negative values are defined such that the text is moved past the text margin, - * positive values move the text inside the text margin. - *

    - * - * @param indentation - */ - public void setIndentationRight(int indentation) { - CTInd indent = getCTInd(true); - BigInteger bi = new BigInteger("" + indentation); - indent.setRight(bi); - } - - /** - * Specifies the indentation which shall be removed from the first line of - * the parent paragraph, by moving the indentation on the first line back - * towards the beginning of the direction of text flow. - * This indentation is - * specified relative to the paragraph indentation which is specified for - * all other lines in the parent paragraph. - * The firstLine and hanging - * attributes are mutually exclusive, if both are specified, then the - * firstLine value is ignored. - * - * @return indentation or null if indentation is not set - */ - public int getIndentationHanging() { - CTInd indentation = getCTInd(false); - return (indentation != null && indentation.isSetHanging()) ? indentation.getHanging().intValue() : -1; - } - - /** - * Specifies the indentation which shall be removed from the first line of - * the parent paragraph, by moving the indentation on the first line back - * towards the beginning of the direction of text flow. - * This indentation is specified relative to the paragraph indentation which is specified for - * all other lines in the parent paragraph. - *

    - * The firstLine and hanging attributes are mutually exclusive, if both are specified, then the - * firstLine value is ignored. - *

    - * - * @param indentation - */ - - public void setIndentationHanging(int indentation) { - CTInd indent = getCTInd(true); - BigInteger bi = new BigInteger("" + indentation); - indent.setHanging(bi); - } - - /** - * Specifies the additional indentation which shall be applied to the first - * line of the parent paragraph. This additional indentation is specified - * relative to the paragraph indentation which is specified for all other - * lines in the parent paragraph. - * The firstLine and hanging attributes are - * mutually exclusive, if both are specified, then the firstLine value is - * ignored. - * If the firstLineChars attribute is also specified, then this - * value is ignored. - * If this attribute is omitted, then its value shall be - * assumed to be zero (if needed). - * - * @return indentation or null if indentation is not set - */ - public int getIndentationFirstLine() { - CTInd indentation = getCTInd(false); - return (indentation != null && indentation.isSetFirstLine()) ? indentation.getFirstLine().intValue() - : -1; - } - - /** - * Specifies the additional indentation which shall be applied to the first - * line of the parent paragraph. This additional indentation is specified - * relative to the paragraph indentation which is specified for all other - * lines in the parent paragraph. - * The firstLine and hanging attributes are - * mutually exclusive, if both are specified, then the firstLine value is - * ignored. - * If the firstLineChars attribute is also specified, then this - * value is ignored. If this attribute is omitted, then its value shall be - * assumed to be zero (if needed). - * - * @param indentation - */ - public void setIndentationFirstLine(int indentation) { - CTInd indent = getCTInd(true); - BigInteger bi = new BigInteger("" + indentation); - indent.setFirstLine(bi); - } - - @Override - public int getIndentFromLeft() { - return getIndentationLeft(); - } - - @Override - public void setIndentFromLeft(int dxaLeft) { - setIndentationLeft(dxaLeft); - } - - @Override - public int getIndentFromRight() { - return getIndentationRight(); - } - - @Override - public void setIndentFromRight(int dxaRight) { - setIndentationRight(dxaRight); - } - - @Override - public int getFirstLineIndent() { - return getIndentationFirstLine(); - } - - @Override - public void setFirstLineIndent(int first) { - setIndentationFirstLine(first); - } - - /** - * This element specifies whether a consumer shall break Latin text which - * exceeds the text extents of a line by breaking the word across two lines - * (breaking on the character level) or by moving the word to the following - * line (breaking on the word level). - * - * @return boolean - */ - @Override - public boolean isWordWrapped() { - CTOnOff wordWrap = getCTPPr().isSetWordWrap() ? getCTPPr() - .getWordWrap() : null; - if (wordWrap != null) { - return (wordWrap.getVal() == STOnOff.ON - || wordWrap.getVal() == STOnOff.TRUE || wordWrap.getVal() == STOnOff.X_1) ? true - : false; - } - return false; - } - - /** - * This element specifies whether a consumer shall break Latin text which - * exceeds the text extents of a line by breaking the word across two lines - * (breaking on the character level) or by moving the word to the following - * line (breaking on the word level). - * - * @param wrap - boolean - */ - @Override - public void setWordWrapped(boolean wrap) { - CTOnOff wordWrap = getCTPPr().isSetWordWrap() ? getCTPPr() - .getWordWrap() : getCTPPr().addNewWordWrap(); - if (wrap) { - wordWrap.setVal(STOnOff.TRUE); - } else { - wordWrap.unsetVal(); - } - } - - public boolean isWordWrap() { - return isWordWrapped(); - } - - @Deprecated - public void setWordWrap(boolean wrap) { - setWordWrapped(wrap); - } - - /** - * @return the style of the paragraph - */ - public String getStyle() { - CTPPr pr = getCTPPr(); - CTString style = pr.isSetPStyle() ? pr.getPStyle() : null; - return style != null ? style.getVal() : null; - } - - /** - * This method provides a style to the paragraph - * This is useful when, e.g. an Heading style has to be assigned - * - * @param newStyle - */ - public void setStyle(String newStyle) { - CTPPr pr = getCTPPr(); - CTString style = pr.getPStyle() != null ? pr.getPStyle() : pr.addNewPStyle(); - style.setVal(newStyle); - } - - /** - * Get a copy of the currently used CTPBrd, if none is used, return - * a new instance. - */ - private CTPBdr getCTPBrd(boolean create) { - CTPPr pr = getCTPPr(); - CTPBdr ct = pr.isSetPBdr() ? pr.getPBdr() : null; - if (create && ct == null) { - ct = pr.addNewPBdr(); - } - return ct; - } - - /** - * Get a copy of the currently used CTSpacing, if none is used, - * return a new instance. - */ - private CTSpacing getCTSpacing(boolean create) { - CTPPr pr = getCTPPr(); - CTSpacing ct = pr.getSpacing() == null ? null : pr.getSpacing(); - if (create && ct == null) { - ct = pr.addNewSpacing(); - } - return ct; - } - - /** - * Get a copy of the currently used CTPInd, if none is used, return - * a new instance. - */ - private CTInd getCTInd(boolean create) { - CTPPr pr = getCTPPr(); - CTInd ct = pr.getInd() == null ? null : pr.getInd(); - if (create && ct == null) { - ct = pr.addNewInd(); - } - return ct; - } - - /** - * Get a copy of the currently used CTPPr, if none is used, return - * a new instance. - */ - private CTPPr getCTPPr() { - CTPPr pr = paragraph.getPPr() == null ? paragraph.addNewPPr() - : paragraph.getPPr(); - return pr; - } - - - /** - * add a new run at the end of the position of - * the content of parameter run - * - * @param run - */ - protected void addRun(CTR run) { - int pos; - pos = paragraph.sizeOfRArray(); - paragraph.addNewR(); - paragraph.setRArray(pos, run); - } - - /** - * Appends a new run to this paragraph - * - * @return a new text run - */ - public XWPFRun createRun() { - XWPFRun xwpfRun = new XWPFRun(paragraph.addNewR(), (IRunBody)this); - runs.add(xwpfRun); - iruns.add(xwpfRun); - return xwpfRun; - } - - /** - * insert a new Run in RunArray - * - * @param pos The position at which the new run should be added. - * - * @return the inserted run or null if the given pos is out of bounds. - */ - public XWPFRun insertNewRun(int pos) { - if (pos >= 0 && pos <= runs.size()) { - // calculate the correct pos as our run/irun list contains - // hyperlinks - // and fields so it is different to the paragraph R array. - int rPos = 0; - for (int i = 0; i < pos; i++) { - XWPFRun currRun = runs.get(i); - if (!(currRun instanceof XWPFHyperlinkRun - || currRun instanceof XWPFFieldRun)) { - rPos++; - } - } - - CTR ctRun = paragraph.insertNewR(rPos); - XWPFRun newRun = new XWPFRun(ctRun, (IRunBody) this); - - // To update the iruns, find where we're going - // in the normal runs, and go in there - int iPos = iruns.size(); - if (pos < runs.size()) { - XWPFRun oldAtPos = runs.get(pos); - int oldAt = iruns.indexOf(oldAtPos); - if (oldAt != -1) { - iPos = oldAt; - } - } - iruns.add(iPos, newRun); - - // Runs itself is easy to update - runs.add(pos, newRun); - - return newRun; - } - - return null; - } - // TODO Add methods to allow adding a HyperlinkRun or a FieldRun - - /** - * this methods parse the paragraph and search for the string searched. - * If it finds the string, it will return true and the position of the String - * will be saved in the parameter startPos. - * - * @param searched - * @param startPos - */ - public TextSegement searchText(String searched, PositionInParagraph startPos) { - int startRun = startPos.getRun(), - startText = startPos.getText(), - startChar = startPos.getChar(); - int beginRunPos = 0, candCharPos = 0; - boolean newList = false; - - CTR[] rArray = paragraph.getRArray(); - for (int runPos = startRun; runPos < rArray.length; runPos++) { - int beginTextPos = 0, beginCharPos = 0, textPos = 0, charPos = 0; - CTR ctRun = rArray[runPos]; - XmlCursor c = ctRun.newCursor(); - c.selectPath("./*"); - try { - while (c.toNextSelection()) { - XmlObject o = c.getObject(); - if (o instanceof CTText) { - if (textPos >= startText) { - String candidate = ((CTText) o).getStringValue(); - if (runPos == startRun) { - charPos = startChar; - } else { - charPos = 0; - } - - for (; charPos < candidate.length(); charPos++) { - if ((candidate.charAt(charPos) == searched.charAt(0)) && (candCharPos == 0)) { - beginTextPos = textPos; - beginCharPos = charPos; - beginRunPos = runPos; - newList = true; - } - if (candidate.charAt(charPos) == searched.charAt(candCharPos)) { - if (candCharPos + 1 < searched.length()) { - candCharPos++; - } else if (newList) { - TextSegement segement = new TextSegement(); - segement.setBeginRun(beginRunPos); - segement.setBeginText(beginTextPos); - segement.setBeginChar(beginCharPos); - segement.setEndRun(runPos); - segement.setEndText(textPos); - segement.setEndChar(charPos); - return segement; - } - } else { - candCharPos = 0; - } - } - } - textPos++; - } else if (o instanceof CTProofErr) { - c.removeXml(); - } else if (o instanceof CTRPr) { - //do nothing - } else { - candCharPos = 0; - } - } - } finally { - c.dispose(); - } - } - return null; - } - - /** - * get a Text - * - * @param segment - */ - public String getText(TextSegement segment) { - int runBegin = segment.getBeginRun(); - int textBegin = segment.getBeginText(); - int charBegin = segment.getBeginChar(); - int runEnd = segment.getEndRun(); - int textEnd = segment.getEndText(); - int charEnd = segment.getEndChar(); - StringBuilder out = new StringBuilder(); - CTR[] rArray = paragraph.getRArray(); - for (int i = runBegin; i <= runEnd; i++) { - CTText[] tArray = rArray[i].getTArray(); - int startText = 0, endText = tArray.length - 1; - if (i == runBegin) { - startText = textBegin; - } - if (i == runEnd) { - endText = textEnd; - } - for (int j = startText; j <= endText; j++) { - String tmpText = tArray[j].getStringValue(); - int startChar = 0, endChar = tmpText.length() - 1; - if ((j == textBegin) && (i == runBegin)) { - startChar = charBegin; - } - if ((j == textEnd) && (i == runEnd)) { - endChar = charEnd; - } - out.append(tmpText.substring(startChar, endChar + 1)); - } - } - return out.toString(); - } - - /** - * removes a Run at the position pos in the paragraph - * - * @param pos - * @return true if the run was removed - */ - public boolean removeRun(int pos) { - if (pos >= 0 && pos < runs.size()) { - // Remove the run from our high level lists - XWPFRun run = runs.get(pos); - if (run instanceof XWPFHyperlinkRun || - run instanceof XWPFFieldRun) { - // TODO Add support for removing these kinds of nested runs, - // which aren't on the CTP -> R array, but CTP -> XXX -> R array - throw new IllegalArgumentException("Removing Field or Hyperlink runs not yet supported"); - } - runs.remove(pos); - iruns.remove(run); - // Remove the run from the low-level XML - //calculate the correct pos as our run/irun list contains hyperlinks and fields so is different to the paragraph R array. - int rPos = 0; - for(int i=0;i - * Note, that this call might be expensive since all the picture data is copied into a temporary byte array. - * You can grab the picture data directly from the underlying package part as follows: - *
    - * - * InputStream is = getPackagePart().getInputStream(); - * - *

    - * - * @return the Picture data. - */ - public byte[] getData() { - try { - return IOUtils.toByteArray(getPackagePart().getInputStream()); - } catch (IOException e) { - throw new POIXMLException(e); - } - } - - /** - * Returns the file name of the image, eg image7.jpg . The original filename - * isn't always available, but if it can be found it's likely to be in the - * CTDrawing - */ - public String getFileName() { - String name = getPackagePart().getPartName().getName(); - return name.substring(name.lastIndexOf('/') + 1); - } - - /** - * Suggests a file extension for this image. - * - * @return the file extension. - */ - public String suggestFileExtension() { - return getPackagePart().getPartName().getExtension(); - } - - /** - * Return an integer constant that specifies type of this picture - * - * @return an integer constant that specifies type of this picture - * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_EMF - * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_WMF - * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_PICT - * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_JPEG - * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_PNG - * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_DIB - */ - public int getPictureType() { - String contentType = getPackagePart().getContentType(); - for (int i = 0; i < RELATIONS.length; i++) { - if (RELATIONS[i] == null) { - continue; - } - - if (RELATIONS[i].getContentType().equals(contentType)) { - return i; - } - } - return 0; - } - - public Long getChecksum() { - if (this.checksum == null) { - InputStream is = null; - byte[] data; - try { - is = getPackagePart().getInputStream(); - data = IOUtils.toByteArray(is); - } catch (IOException e) { - throw new POIXMLException(e); - } finally { - IOUtils.closeQuietly(is); - } - this.checksum = IOUtils.calculateChecksum(data); - } - return this.checksum; - } - - @Override - public boolean equals(Object obj) { - /* - * In case two objects ARE equal, but its not the same instance, this - * implementation will always run through the whole - * byte-array-comparison before returning true. If this will turn into a - * performance issue, two possible approaches are available:
    - * a) Use the checksum only and take the risk that two images might have - * the same CRC32 sum, although they are not the same.
    - * b) Use a second (or third) checksum algorithm to minimise the chance - * that two images have the same checksums but are not equal (e.g. - * CRC32, MD5 and SHA-1 checksums, additionally compare the - * data-byte-array lengths). - */ - if (obj == this) { - return true; - } - - if (obj == null) { - return false; - } - - if (!(obj instanceof XWPFPictureData)) { - return false; - } - - XWPFPictureData picData = (XWPFPictureData) obj; - PackagePart foreignPackagePart = picData.getPackagePart(); - PackagePart ownPackagePart = this.getPackagePart(); - - if ((foreignPackagePart != null && ownPackagePart == null) - || (foreignPackagePart == null && ownPackagePart != null)) { - return false; - } - - if (ownPackagePart != null) { - OPCPackage foreignPackage = foreignPackagePart.getPackage(); - OPCPackage ownPackage = ownPackagePart.getPackage(); - - if ((foreignPackage != null && ownPackage == null) - || (foreignPackage == null && ownPackage != null)) { - return false; - } - if (ownPackage != null) { - - if (!ownPackage.equals(foreignPackage)) { - return false; - } - } - } - - Long foreignChecksum = picData.getChecksum(); - Long localChecksum = getChecksum(); - - if (!(localChecksum.equals(foreignChecksum))) { - return false; - } - return Arrays.equals(this.getData(), picData.getData()); - } - - @Override - public int hashCode() { - return getChecksum().hashCode(); - } - - /** - * *PictureData objects store the actual content in the part directly without keeping a - * copy like all others therefore we need to handle them differently. - */ - @Override - protected void prepareForCommit() { - // do not clear the part here - } -} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFRelation.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFRelation.java deleted file mode 100644 index 0afaedc71..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFRelation.java +++ /dev/null @@ -1,230 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xwpf.usermodel; - -import java.util.HashMap; -import java.util.Map; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.POIXMLRelation; - -/** - * @author Yegor Kozlov - */ -public final class XWPFRelation extends POIXMLRelation { - - /** - * A map to lookup POIXMLRelation by its relation type - */ - private static final Map _table = new HashMap(); - - public static final XWPFRelation DOCUMENT = new XWPFRelation( - "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument", - "/word/document.xml", - null - ); - public static final XWPFRelation TEMPLATE = new XWPFRelation( - "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument", - "/word/document.xml", - null - ); - public static final XWPFRelation MACRO_DOCUMENT = new XWPFRelation( - "application/vnd.ms-word.document.macroEnabled.main+xml", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument", - "/word/document.xml", - null - ); - public static final XWPFRelation MACRO_TEMPLATE_DOCUMENT = new XWPFRelation( - "application/vnd.ms-word.template.macroEnabledTemplate.main+xml", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument", - "/word/document.xml", - null - ); - public static final XWPFRelation GLOSSARY_DOCUMENT = new XWPFRelation( - "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/glossaryDocument", - "/word/glossary/document.xml", - null - ); - public static final XWPFRelation NUMBERING = new XWPFRelation( - "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering", - "/word/numbering.xml", - XWPFNumbering.class - ); - public static final XWPFRelation FONT_TABLE = new XWPFRelation( - "application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/fontTable", - "/word/fontTable.xml", - null - ); - public static final XWPFRelation SETTINGS = new XWPFRelation( - "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings", - "/word/settings.xml", - XWPFSettings.class - ); - public static final XWPFRelation STYLES = new XWPFRelation( - "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles", - "/word/styles.xml", - XWPFStyles.class - ); - public static final XWPFRelation WEB_SETTINGS = new XWPFRelation( - "application/vnd.openxmlformats-officedocument.wordprocessingml.webSettings+xml", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/webSettings", - "/word/webSettings.xml", - null - ); - public static final XWPFRelation HEADER = new XWPFRelation( - "application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/header", - "/word/header#.xml", - XWPFHeader.class - ); - public static final XWPFRelation FOOTER = new XWPFRelation( - "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer", - "/word/footer#.xml", - XWPFFooter.class - ); - public static final XWPFRelation THEME = new XWPFRelation( - "application/vnd.openxmlformats-officedocument.theme+xml", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme", - "/word/theme/theme#.xml", - null - ); - public static final XWPFRelation HYPERLINK = new XWPFRelation( - null, - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink", - null, - null - ); - public static final XWPFRelation COMMENT = new XWPFRelation( - null, - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments", - null, - null - ); - public static final XWPFRelation FOOTNOTE = new XWPFRelation( - "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes", - "/word/footnotes.xml", - XWPFFootnotes.class - ); - public static final XWPFRelation ENDNOTE = new XWPFRelation( - null, - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/endnotes", - null, - null - ); - /** - * Supported image formats - */ - public static final XWPFRelation IMAGE_EMF = new XWPFRelation( - "image/x-emf", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", - "/word/media/image#.emf", - XWPFPictureData.class - ); - public static final XWPFRelation IMAGE_WMF = new XWPFRelation( - "image/x-wmf", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", - "/word/media/image#.wmf", - XWPFPictureData.class - ); - public static final XWPFRelation IMAGE_PICT = new XWPFRelation( - "image/pict", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", - "/word/media/image#.pict", - XWPFPictureData.class - ); - public static final XWPFRelation IMAGE_JPEG = new XWPFRelation( - "image/jpeg", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", - "/word/media/image#.jpeg", - XWPFPictureData.class - ); - public static final XWPFRelation IMAGE_PNG = new XWPFRelation( - "image/png", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", - "/word/media/image#.png", - XWPFPictureData.class - ); - public static final XWPFRelation IMAGE_DIB = new XWPFRelation( - "image/dib", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", - "/word/media/image#.dib", - XWPFPictureData.class - ); - public static final XWPFRelation IMAGE_GIF = new XWPFRelation( - "image/gif", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", - "/word/media/image#.gif", - XWPFPictureData.class - ); - public static final XWPFRelation IMAGE_TIFF = new XWPFRelation( - "image/tiff", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", - "/word/media/image#.tiff", - XWPFPictureData.class - ); - public static final XWPFRelation IMAGE_EPS = new XWPFRelation( - "image/x-eps", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", - "/word/media/image#.eps", - XWPFPictureData.class - ); - public static final XWPFRelation IMAGE_BMP = new XWPFRelation( - "image/x-ms-bmp", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", - "/word/media/image#.bmp", - XWPFPictureData.class - ); - public static final XWPFRelation IMAGE_WPG = new XWPFRelation( - "image/x-wpg", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", - "/word/media/image#.wpg", - XWPFPictureData.class - ); - public static final XWPFRelation IMAGES = new XWPFRelation( - null, - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", - null, - XWPFPictureData.class - ); - - private XWPFRelation(String type, String rel, String defaultName, Class cls) { - super(type, rel, defaultName, cls); - _table.put(rel, this); - } - - /** - * Get POIXMLRelation by relation type - * - * @param rel relation type, for example, - * http://schemas.openxmlformats.org/officeDocument/2006/relationships/image - * @return registered POIXMLRelation or null if not found - */ - public static XWPFRelation getInstance(String rel) { - return _table.get(rel); - } - -} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFRun.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFRun.java deleted file mode 100644 index 88a6104cf..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFRun.java +++ /dev/null @@ -1,1140 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -import static org.apache.poi.POIXMLTypeLoader.DEFAULT_XML_OPTIONS; - -import java.io.IOException; -import java.io.InputStream; -import java.io.StringReader; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import javax.xml.namespace.QName; - -import org.apache.poi.POIXMLException; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.util.DocumentHelper; -import org.apache.poi.util.Internal; -import org.apache.poi.wp.usermodel.CharacterRun; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlObject; -import org.apache.xmlbeans.XmlString; -import org.apache.xmlbeans.XmlToken; -import org.apache.xmlbeans.impl.values.XmlAnyTypeImpl; -import org.openxmlformats.schemas.drawingml.x2006.main.CTBlip; -import org.openxmlformats.schemas.drawingml.x2006.main.CTBlipFillProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTGraphicalObject; -import org.openxmlformats.schemas.drawingml.x2006.main.CTGraphicalObjectData; -import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps; -import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualPictureProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPoint2D; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPresetGeometry2D; -import org.openxmlformats.schemas.drawingml.x2006.main.CTShapeProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTransform2D; -import org.openxmlformats.schemas.drawingml.x2006.main.STShapeType; -import org.openxmlformats.schemas.drawingml.x2006.picture.CTPicture; -import org.openxmlformats.schemas.drawingml.x2006.picture.CTPictureNonVisual; -import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTAnchor; -import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBr; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTColor; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDrawing; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTEmpty; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFFCheckBox; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFldChar; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFonts; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFtnEdnRef; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTHpsMeasure; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTOnOff; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPTab; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPr; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSignedHpsMeasure; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSignedTwipsMeasure; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTText; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTUnderline; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTVerticalAlignRun; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STBrClear; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STBrType; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STFldCharType; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STHighlightColor; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STOnOff; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STUnderline; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STVerticalAlignRun; -import org.w3c.dom.NodeList; -import org.w3c.dom.Text; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; - -/** - * XWPFRun object defines a region of text with a common set of properties - */ -public class XWPFRun implements ISDTContents, IRunElement, CharacterRun { - private CTR run; - private String pictureText; - private IRunBody parent; - private List pictures; - - /** - * @param r the CTR bean which holds the run attributes - * @param p the parent paragraph - */ - public XWPFRun(CTR r, IRunBody p) { - this.run = r; - this.parent = p; - - /** - * reserve already occupied drawing ids, so reserving new ids later will - * not corrupt the document - */ - for (CTDrawing ctDrawing : r.getDrawingArray()) { - for (CTAnchor anchor : ctDrawing.getAnchorArray()) { - if (anchor.getDocPr() != null) { - getDocument().getDrawingIdManager().reserve(anchor.getDocPr().getId()); - } - } - for (CTInline inline : ctDrawing.getInlineArray()) { - if (inline.getDocPr() != null) { - getDocument().getDrawingIdManager().reserve(inline.getDocPr().getId()); - } - } - } - - // Look for any text in any of our pictures or drawings - StringBuilder text = new StringBuilder(); - List pictTextObjs = new ArrayList(); - pictTextObjs.addAll(Arrays.asList(r.getPictArray())); - pictTextObjs.addAll(Arrays.asList(r.getDrawingArray())); - for (XmlObject o : pictTextObjs) { - XmlObject[] ts = o.selectPath("declare namespace w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' .//w:t"); - for (XmlObject t : ts) { - NodeList kids = t.getDomNode().getChildNodes(); - for (int n = 0; n < kids.getLength(); n++) { - if (kids.item(n) instanceof Text) { - if (text.length() > 0) - text.append("\n"); - text.append(kids.item(n).getNodeValue()); - } - } - } - } - pictureText = text.toString(); - - // Do we have any embedded pictures? - // (They're a different CTPicture, under the drawingml namespace) - pictures = new ArrayList(); - for (XmlObject o : pictTextObjs) { - for (CTPicture pict : getCTPictures(o)) { - XWPFPicture picture = new XWPFPicture(pict, this); - pictures.add(picture); - } - } - } - - /** - * @deprecated Use {@link XWPFRun#XWPFRun(CTR, IRunBody)} - */ - public XWPFRun(CTR r, XWPFParagraph p) { - this(r, (IRunBody) p); - } - - /** - * Add the xml:spaces="preserve" attribute if the string has leading or trailing white spaces - * - * @param xs the string to check - */ - static void preserveSpaces(XmlString xs) { - String text = xs.getStringValue(); - if (text != null && (text.startsWith(" ") || text.endsWith(" "))) { - XmlCursor c = xs.newCursor(); - c.toNextToken(); - c.insertAttributeWithValue(new QName("http://www.w3.org/XML/1998/namespace", "space"), "preserve"); - c.dispose(); - } - } - - private List getCTPictures(XmlObject o) { - List pics = new ArrayList(); - XmlObject[] picts = o.selectPath("declare namespace pic='" + CTPicture.type.getName().getNamespaceURI() + "' .//pic:pic"); - for (XmlObject pict : picts) { - if (pict instanceof XmlAnyTypeImpl) { - // Pesky XmlBeans bug - see Bugzilla #49934 - try { - pict = CTPicture.Factory.parse(pict.toString(), DEFAULT_XML_OPTIONS); - } catch (XmlException e) { - throw new POIXMLException(e); - } - } - if (pict instanceof CTPicture) { - pics.add((CTPicture) pict); - } - } - return pics; - } - - /** - * Get the currently used CTR object - * - * @return ctr object - */ - @Internal - public CTR getCTR() { - return run; - } - - /** - * Get the currently referenced paragraph/SDT object - * - * @return current parent - */ - public IRunBody getParent() { - return parent; - } - - /** - * Get the currently referenced paragraph, or null if a SDT object - * - * @deprecated use {@link XWPFRun#getParent()} instead - */ - public XWPFParagraph getParagraph() { - if (parent instanceof XWPFParagraph) - return (XWPFParagraph) parent; - return null; - } - - /** - * @return The {@link XWPFDocument} instance, this run belongs to, or - * null if parent structure (paragraph > document) is not properly set. - */ - public XWPFDocument getDocument() { - if (parent != null) { - return parent.getDocument(); - } - return null; - } - - /** - * For isBold, isItalic etc - */ - private static boolean isCTOnOff(CTOnOff onoff) { - if (!onoff.isSetVal()) - return true; - final STOnOff.Enum val = onoff.getVal(); - return ( - (STOnOff.TRUE == val) || - (STOnOff.X_1 == val) || - (STOnOff.ON == val) - ); - } - - /** - * Whether the bold property shall be applied to all non-complex script - * characters in the contents of this run when displayed in a document - * - * @return true if the bold property is applied - */ - public boolean isBold() { - CTRPr pr = run.getRPr(); - if (pr == null || !pr.isSetB()) { - return false; - } - return isCTOnOff(pr.getB()); - } - - /** - * Whether the bold property shall be applied to all non-complex script - * characters in the contents of this run when displayed in a document. - *

    - * This formatting property is a toggle property, which specifies that its - * behavior differs between its use within a style definition and its use as - * direct formatting. When used as part of a style definition, setting this - * property shall toggle the current state of that property as specified up - * to this point in the hierarchy (i.e. applied to not applied, and vice - * versa). Setting it to false (or an equivalent) shall - * result in the current setting remaining unchanged. However, when used as - * direct formatting, setting this property to true or false shall set the - * absolute state of the resulting property. - *

    - *

    - * If this element is not present, the default value is to leave the - * formatting applied at previous level in the style hierarchy. If this - * element is never applied in the style hierarchy, then bold shall not be - * applied to non-complex script characters. - *

    - * - * @param value true if the bold property is applied to - * this run - */ - public void setBold(boolean value) { - CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr(); - CTOnOff bold = pr.isSetB() ? pr.getB() : pr.addNewB(); - bold.setVal(value ? STOnOff.TRUE : STOnOff.FALSE); - } - - /** - * Get text color. The returned value is a string in the hex form "RRGGBB". - */ - public String getColor() { - String color = null; - if (run.isSetRPr()) { - CTRPr pr = run.getRPr(); - if (pr.isSetColor()) { - CTColor clr = pr.getColor(); - color = clr.xgetVal().getStringValue(); - } - } - return color; - } - - /** - * Set text color. - * - * @param rgbStr - the desired color, in the hex form "RRGGBB". - */ - public void setColor(String rgbStr) { - CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr(); - CTColor color = pr.isSetColor() ? pr.getColor() : pr.addNewColor(); - color.setVal(rgbStr); - } - - /** - * Return the string content of this text run - * - * @return the text of this text run or null if not set - */ - public String getText(int pos) { - return run.sizeOfTArray() == 0 ? null : run.getTArray(pos) - .getStringValue(); - } - - /** - * Returns text embedded in pictures - */ - public String getPictureText() { - return pictureText; - } - - /** - * Sets the text of this text run - * - * @param value the literal text which shall be displayed in the document - */ - public void setText(String value) { - setText(value, run.sizeOfTArray()); - } - - /** - * Sets the text of this text run in the - * - * @param value the literal text which shall be displayed in the document - * @param pos - position in the text array (NB: 0 based) - */ - public void setText(String value, int pos) { - if (pos > run.sizeOfTArray()) - throw new ArrayIndexOutOfBoundsException("Value too large for the parameter position in XWPFRun.setText(String value,int pos)"); - CTText t = (pos < run.sizeOfTArray() && pos >= 0) ? run.getTArray(pos) : run.addNewT(); - t.setStringValue(value); - preserveSpaces(t); - } - - /** - * Whether the italic property should be applied to all non-complex script - * characters in the contents of this run when displayed in a document. - * - * @return true if the italic property is applied - */ - public boolean isItalic() { - CTRPr pr = run.getRPr(); - if (pr == null || !pr.isSetI()) - return false; - return isCTOnOff(pr.getI()); - } - - /** - * Whether the bold property shall be applied to all non-complex script - * characters in the contents of this run when displayed in a document - *

    - *

    - * This formatting property is a toggle property, which specifies that its - * behavior differs between its use within a style definition and its use as - * direct formatting. When used as part of a style definition, setting this - * property shall toggle the current state of that property as specified up - * to this point in the hierarchy (i.e. applied to not applied, and vice - * versa). Setting it to false (or an equivalent) shall - * result in the current setting remaining unchanged. However, when used as - * direct formatting, setting this property to true or false shall set the - * absolute state of the resulting property. - *

    - *

    - * If this element is not present, the default value is to leave the - * formatting applied at previous level in the style hierarchy. If this - * element is never applied in the style hierarchy, then bold shall not be - * applied to non-complex script characters. - *

    - * - * @param value true if the italic property is applied to - * this run - */ - public void setItalic(boolean value) { - CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr(); - CTOnOff italic = pr.isSetI() ? pr.getI() : pr.addNewI(); - italic.setVal(value ? STOnOff.TRUE : STOnOff.FALSE); - } - - /** - * Specifies that the contents of this run should be displayed along with an - * underline appearing directly below the character heigh - * - * @return the Underline pattern applyed to this run - * @see UnderlinePatterns - */ - public UnderlinePatterns getUnderline() { - CTRPr pr = run.getRPr(); - return (pr != null && pr.isSetU() && pr.getU().getVal() != null) - ? UnderlinePatterns.valueOf(pr.getU().getVal().intValue()) - : UnderlinePatterns.NONE; - } - - /** - * Specifies that the contents of this run should be displayed along with an - * underline appearing directly below the character heigh - *

    - *

    - * If this element is not present, the default value is to leave the - * formatting applied at previous level in the style hierarchy. If this - * element is never applied in the style hierarchy, then an underline shall - * not be applied to the contents of this run. - *

    - * - * @param value - - * underline type - * @see UnderlinePatterns : all possible patterns that could be applied - */ - public void setUnderline(UnderlinePatterns value) { - CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr(); - CTUnderline underline = (pr.getU() == null) ? pr.addNewU() : pr.getU(); - underline.setVal(STUnderline.Enum.forInt(value.getValue())); - } - - /** - * Specifies that the contents of this run shall be displayed with a single - * horizontal line through the center of the line. - * - * @return true if the strike property is applied - */ - public boolean isStrikeThrough() { - CTRPr pr = run.getRPr(); - if (pr == null || !pr.isSetStrike()) - return false; - return isCTOnOff(pr.getStrike()); - } - - /** - * Specifies that the contents of this run shall be displayed with a single - * horizontal line through the center of the line. - *

    - * This formatting property is a toggle property, which specifies that its - * behaviour differs between its use within a style definition and its use as - * direct formatting. When used as part of a style definition, setting this - * property shall toggle the current state of that property as specified up - * to this point in the hierarchy (i.e. applied to not applied, and vice - * versa). Setting it to false (or an equivalent) shall result in the - * current setting remaining unchanged. However, when used as direct - * formatting, setting this property to true or false shall set the absolute - * state of the resulting property. - *

    - *

    - * If this element is not present, the default value is to leave the - * formatting applied at previous level in the style hierarchy. If this - * element is never applied in the style hierarchy, then strikethrough shall - * not be applied to the contents of this run. - *

    - * - * @param value true if the strike property is applied to - * this run - */ - public void setStrikeThrough(boolean value) { - CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr(); - CTOnOff strike = pr.isSetStrike() ? pr.getStrike() : pr.addNewStrike(); - strike.setVal(value ? STOnOff.TRUE : STOnOff.FALSE); - } - - @Deprecated - public boolean isStrike() { - return isStrikeThrough(); - } - - @Deprecated - public void setStrike(boolean value) { - setStrikeThrough(value); - } - - /** - * Specifies that the contents of this run shall be displayed with a double - * horizontal line through the center of the line. - * - * @return true if the double strike property is applied - */ - public boolean isDoubleStrikeThrough() { - CTRPr pr = run.getRPr(); - if (pr == null || !pr.isSetDstrike()) - return false; - return isCTOnOff(pr.getDstrike()); - } - - /** - * Specifies that the contents of this run shall be displayed with a - * double horizontal line through the center of the line. - * - * @see #setStrikeThrough(boolean) for the rules about this - */ - public void setDoubleStrikethrough(boolean value) { - CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr(); - CTOnOff dstrike = pr.isSetDstrike() ? pr.getDstrike() : pr.addNewDstrike(); - dstrike.setVal(value ? STOnOff.TRUE : STOnOff.FALSE); - } - - public boolean isSmallCaps() { - CTRPr pr = run.getRPr(); - if (pr == null || !pr.isSetSmallCaps()) - return false; - return isCTOnOff(pr.getSmallCaps()); - } - - public void setSmallCaps(boolean value) { - CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr(); - CTOnOff caps = pr.isSetSmallCaps() ? pr.getSmallCaps() : pr.addNewSmallCaps(); - caps.setVal(value ? STOnOff.TRUE : STOnOff.FALSE); - } - - public boolean isCapitalized() { - CTRPr pr = run.getRPr(); - if (pr == null || !pr.isSetCaps()) - return false; - return isCTOnOff(pr.getCaps()); - } - - public void setCapitalized(boolean value) { - CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr(); - CTOnOff caps = pr.isSetCaps() ? pr.getCaps() : pr.addNewCaps(); - caps.setVal(value ? STOnOff.TRUE : STOnOff.FALSE); - } - - public boolean isShadowed() { - CTRPr pr = run.getRPr(); - if (pr == null || !pr.isSetShadow()) - return false; - return isCTOnOff(pr.getShadow()); - } - - public void setShadow(boolean value) { - CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr(); - CTOnOff shadow = pr.isSetShadow() ? pr.getShadow() : pr.addNewShadow(); - shadow.setVal(value ? STOnOff.TRUE : STOnOff.FALSE); - } - - public boolean isImprinted() { - CTRPr pr = run.getRPr(); - if (pr == null || !pr.isSetImprint()) - return false; - return isCTOnOff(pr.getImprint()); - } - - public void setImprinted(boolean value) { - CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr(); - CTOnOff imprinted = pr.isSetImprint() ? pr.getImprint() : pr.addNewImprint(); - imprinted.setVal(value ? STOnOff.TRUE : STOnOff.FALSE); - } - - public boolean isEmbossed() { - CTRPr pr = run.getRPr(); - if (pr == null || !pr.isSetEmboss()) - return false; - return isCTOnOff(pr.getEmboss()); - } - - public void setEmbossed(boolean value) { - CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr(); - CTOnOff emboss = pr.isSetEmboss() ? pr.getEmboss() : pr.addNewEmboss(); - emboss.setVal(value ? STOnOff.TRUE : STOnOff.FALSE); - } - - /** - * Specifies the alignment which shall be applied to the contents of this - * run in relation to the default appearance of the run's text. - * This allows the text to be repositioned as subscript or superscript without - * altering the font size of the run properties. - * - * @return VerticalAlign - * @see VerticalAlign all possible value that could be applyed to this run - */ - public VerticalAlign getSubscript() { - CTRPr pr = run.getRPr(); - return (pr != null && pr.isSetVertAlign()) ? VerticalAlign.valueOf(pr.getVertAlign().getVal().intValue()) : VerticalAlign.BASELINE; - } - - /** - * Specifies the alignment which shall be applied to the contents of this - * run in relation to the default appearance of the run's text. This allows - * the text to be repositioned as subscript or superscript without altering - * the font size of the run properties. - *

    - * If this element is not present, the default value is to leave the - * formatting applied at previous level in the style hierarchy. If this - * element is never applied in the style hierarchy, then the text shall not - * be subscript or superscript relative to the default baseline location for - * the contents of this run. - *

    - * - * @param valign - * @see VerticalAlign - */ - public void setSubscript(VerticalAlign valign) { - CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr(); - CTVerticalAlignRun ctValign = pr.isSetVertAlign() ? pr.getVertAlign() : pr.addNewVertAlign(); - ctValign.setVal(STVerticalAlignRun.Enum.forInt(valign.getValue())); - } - - public int getKerning() { - CTRPr pr = run.getRPr(); - if (pr == null || !pr.isSetKern()) - return 0; - return pr.getKern().getVal().intValue(); - } - - public void setKerning(int kern) { - CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr(); - CTHpsMeasure kernmes = pr.isSetKern() ? pr.getKern() : pr.addNewKern(); - kernmes.setVal(BigInteger.valueOf(kern)); - } - - public boolean isHighlighted() { - CTRPr pr = run.getRPr(); - if (pr == null || !pr.isSetHighlight()) - return false; - if (pr.getHighlight().getVal() == STHighlightColor.NONE) - return false; - return true; - } - // TODO Provide a wrapper round STHighlightColor, then expose getter/setter - // for the highlight colour. Ideally also then add to CharacterRun interface - - public int getCharacterSpacing() { - CTRPr pr = run.getRPr(); - if (pr == null || !pr.isSetSpacing()) - return 0; - return pr.getSpacing().getVal().intValue(); - } - - public void setCharacterSpacing(int twips) { - CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr(); - CTSignedTwipsMeasure spc = pr.isSetSpacing() ? pr.getSpacing() : pr.addNewSpacing(); - spc.setVal(BigInteger.valueOf(twips)); - } - - /** - * Gets the fonts which shall be used to display the text contents of - * this run. Specifies a font which shall be used to format all characters - * in the ASCII range (0 - 127) within the parent run - * - * @return a string representing the font family - */ - public String getFontFamily() { - return getFontFamily(null); - } - - /** - * Specifies the fonts which shall be used to display the text contents of - * this run. Specifies a font which shall be used to format all characters - * in the ASCII range (0 - 127) within the parent run. - *

    - * Also sets the other font ranges, if they haven't been set before - * - * @param fontFamily - * @see FontCharRange - */ - public void setFontFamily(String fontFamily) { - setFontFamily(fontFamily, null); - } - - /** - * Alias for {@link #getFontFamily()} - */ - public String getFontName() { - return getFontFamily(); - } - - /** - * Gets the font family for the specified font char range. - * If fcr is null, the font char range "ascii" is used - * - * @param fcr the font char range, defaults to "ansi" - * @return a string representing the font famil - */ - public String getFontFamily(FontCharRange fcr) { - CTRPr pr = run.getRPr(); - if (pr == null || !pr.isSetRFonts()) return null; - - CTFonts fonts = pr.getRFonts(); - switch (fcr == null ? FontCharRange.ascii : fcr) { - default: - case ascii: - return fonts.getAscii(); - case cs: - return fonts.getCs(); - case eastAsia: - return fonts.getEastAsia(); - case hAnsi: - return fonts.getHAnsi(); - } - } - - /** - * Specifies the fonts which shall be used to display the text contents of - * this run. The default handling for fcr == null is to overwrite the - * ascii font char range with the given font family and also set all not - * specified font ranges - * - * @param fontFamily - * @param fcr FontCharRange or null for default handling - */ - public void setFontFamily(String fontFamily, FontCharRange fcr) { - CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr(); - CTFonts fonts = pr.isSetRFonts() ? pr.getRFonts() : pr.addNewRFonts(); - - if (fcr == null) { - fonts.setAscii(fontFamily); - if (!fonts.isSetHAnsi()) { - fonts.setHAnsi(fontFamily); - } - if (!fonts.isSetCs()) { - fonts.setCs(fontFamily); - } - if (!fonts.isSetEastAsia()) { - fonts.setEastAsia(fontFamily); - } - } else { - switch (fcr) { - case ascii: - fonts.setAscii(fontFamily); - break; - case cs: - fonts.setCs(fontFamily); - break; - case eastAsia: - fonts.setEastAsia(fontFamily); - break; - case hAnsi: - fonts.setHAnsi(fontFamily); - break; - } - } - } - - /** - * Specifies the font size which shall be applied to all non complex script - * characters in the contents of this run when displayed. - * - * @return value representing the font size - */ - public int getFontSize() { - CTRPr pr = run.getRPr(); - return (pr != null && pr.isSetSz()) ? pr.getSz().getVal().divide(new BigInteger("2")).intValue() : -1; - } - - /** - * Specifies the font size which shall be applied to all non complex script - * characters in the contents of this run when displayed. - *

    - * If this element is not present, the default value is to leave the value - * applied at previous level in the style hierarchy. If this element is - * never applied in the style hierarchy, then any appropriate font size may - * be used for non complex script characters. - *

    - * - * @param size - */ - public void setFontSize(int size) { - BigInteger bint = new BigInteger("" + size); - CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr(); - CTHpsMeasure ctSize = pr.isSetSz() ? pr.getSz() : pr.addNewSz(); - ctSize.setVal(bint.multiply(new BigInteger("2"))); - } - - /** - * This element specifies the amount by which text shall be raised or - * lowered for this run in relation to the default baseline of the - * surrounding non-positioned text. This allows the text to be repositioned - * without altering the font size of the contents. - * - * @return a big integer representing the amount of text shall be "moved" - */ - public int getTextPosition() { - CTRPr pr = run.getRPr(); - return (pr != null && pr.isSetPosition()) ? pr.getPosition().getVal().intValue() - : -1; - } - - /** - * This element specifies the amount by which text shall be raised or - * lowered for this run in relation to the default baseline of the - * surrounding non-positioned text. This allows the text to be repositioned - * without altering the font size of the contents. - *

    - * If the val attribute is positive, then the parent run shall be raised - * above the baseline of the surrounding text by the specified number of - * half-points. If the val attribute is negative, then the parent run shall - * be lowered below the baseline of the surrounding text by the specified - * number of half-points. - *

    - *

    - * If this element is not present, the default value is to leave the - * formatting applied at previous level in the style hierarchy. If this - * element is never applied in the style hierarchy, then the text shall not - * be raised or lowered relative to the default baseline location for the - * contents of this run. - *

    - * - * @param val - */ - public void setTextPosition(int val) { - BigInteger bint = new BigInteger("" + val); - CTRPr pr = run.isSetRPr() ? run.getRPr() : run.addNewRPr(); - CTSignedHpsMeasure position = pr.isSetPosition() ? pr.getPosition() : pr.addNewPosition(); - position.setVal(bint); - } - - /** - * - */ - public void removeBreak() { - // TODO - } - - /** - * Specifies that a break shall be placed at the current location in the run - * content. - * A break is a special character which is used to override the - * normal line breaking that would be performed based on the normal layout - * of the document's contents. - * - * @see #addCarriageReturn() - */ - public void addBreak() { - run.addNewBr(); - } - - /** - * Specifies that a break shall be placed at the current location in the run - * content. - * A break is a special character which is used to override the - * normal line breaking that would be performed based on the normal layout - * of the document's contents. - *

    - * The behavior of this break character (the - * location where text shall be restarted after this break) shall be - * determined by its type values. - *

    - * - * @see BreakType - */ - public void addBreak(BreakType type) { - CTBr br = run.addNewBr(); - br.setType(STBrType.Enum.forInt(type.getValue())); - } - - /** - * Specifies that a break shall be placed at the current location in the run - * content. A break is a special character which is used to override the - * normal line breaking that would be performed based on the normal layout - * of the document's contents. - *

    - * The behavior of this break character (the - * location where text shall be restarted after this break) shall be - * determined by its type (in this case is BreakType.TEXT_WRAPPING as default) and clear attribute values. - *

    - * - * @see BreakClear - */ - public void addBreak(BreakClear clear) { - CTBr br = run.addNewBr(); - br.setType(STBrType.Enum.forInt(BreakType.TEXT_WRAPPING.getValue())); - br.setClear(STBrClear.Enum.forInt(clear.getValue())); - } - - /** - * Specifies that a tab shall be placed at the current location in - * the run content. - */ - public void addTab() { - run.addNewTab(); - } - - public void removeTab() { - //TODO - } - - /** - * Specifies that a carriage return shall be placed at the - * current location in the run content. - * A carriage return is used to end the current line of text in - * Wordprocess. - * The behavior of a carriage return in run content shall be - * identical to a break character with null type and clear attributes, which - * shall end the current line and find the next available line on which to - * continue. - * The carriage return character forced the following text to be - * restarted on the next available line in the document. - */ - public void addCarriageReturn() { - run.addNewCr(); - } - - public void removeCarriageReturn() { - //TODO - } - - /** - * Adds a picture to the run. This method handles - * attaching the picture data to the overall file. - * - * @param pictureData The raw picture data - * @param pictureType The type of the picture, eg {@link Document#PICTURE_TYPE_JPEG} - * @param width width in EMUs. To convert to / from points use {@link org.apache.poi.util.Units} - * @param height height in EMUs. To convert to / from points use {@link org.apache.poi.util.Units} - * @throws org.apache.poi.openxml4j.exceptions.InvalidFormatException - * @throws IOException - * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_EMF - * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_WMF - * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_PICT - * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_JPEG - * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_PNG - * @see org.apache.poi.xwpf.usermodel.Document#PICTURE_TYPE_DIB - */ - public XWPFPicture addPicture(InputStream pictureData, int pictureType, String filename, int width, int height) - throws InvalidFormatException, IOException { - String relationId; - XWPFPictureData picData; - - // Work out what to add the picture to, then add both the - // picture and the relationship for it - // TODO Should we have an interface for this sort of thing? - if (parent.getPart() instanceof XWPFHeaderFooter) { - XWPFHeaderFooter headerFooter = (XWPFHeaderFooter)parent.getPart(); - relationId = headerFooter.addPictureData(pictureData, pictureType); - picData = (XWPFPictureData) headerFooter.getRelationById(relationId); - } else { - @SuppressWarnings("resource") - XWPFDocument doc = parent.getDocument(); - relationId = doc.addPictureData(pictureData, pictureType); - picData = (XWPFPictureData) doc.getRelationById(relationId); - } - - // Create the drawing entry for it - try { - CTDrawing drawing = run.addNewDrawing(); - CTInline inline = drawing.addNewInline(); - - // Do the fiddly namespace bits on the inline - // (We need full control of what goes where and as what) - String xml = - "" + - "" + - "" + - "" + - ""; - InputSource is = new InputSource(new StringReader(xml)); - org.w3c.dom.Document doc = DocumentHelper.readDocument(is); - inline.set(XmlToken.Factory.parse(doc.getDocumentElement(), DEFAULT_XML_OPTIONS)); - - // Setup the inline - inline.setDistT(0); - inline.setDistR(0); - inline.setDistB(0); - inline.setDistL(0); - - CTNonVisualDrawingProps docPr = inline.addNewDocPr(); - long id = getParent().getDocument().getDrawingIdManager().reserveNew(); - docPr.setId(id); - /* This name is not visible in Word 2010 anywhere. */ - docPr.setName("Drawing " + id); - docPr.setDescr(filename); - - CTPositiveSize2D extent = inline.addNewExtent(); - extent.setCx(width); - extent.setCy(height); - - // Grab the picture object - CTGraphicalObject graphic = inline.getGraphic(); - CTGraphicalObjectData graphicData = graphic.getGraphicData(); - CTPicture pic = getCTPictures(graphicData).get(0); - - // Set it up - CTPictureNonVisual nvPicPr = pic.addNewNvPicPr(); - - CTNonVisualDrawingProps cNvPr = nvPicPr.addNewCNvPr(); - /* use "0" for the id. See ECM-576, 20.2.2.3 */ - cNvPr.setId(0L); - /* This name is not visible in Word 2010 anywhere */ - cNvPr.setName("Picture " + id); - cNvPr.setDescr(filename); - - CTNonVisualPictureProperties cNvPicPr = nvPicPr.addNewCNvPicPr(); - cNvPicPr.addNewPicLocks().setNoChangeAspect(true); - - CTBlipFillProperties blipFill = pic.addNewBlipFill(); - CTBlip blip = blipFill.addNewBlip(); - blip.setEmbed(parent.getPart().getRelationId(picData)); - blipFill.addNewStretch().addNewFillRect(); - - CTShapeProperties spPr = pic.addNewSpPr(); - CTTransform2D xfrm = spPr.addNewXfrm(); - - CTPoint2D off = xfrm.addNewOff(); - off.setX(0); - off.setY(0); - - CTPositiveSize2D ext = xfrm.addNewExt(); - ext.setCx(width); - ext.setCy(height); - - CTPresetGeometry2D prstGeom = spPr.addNewPrstGeom(); - prstGeom.setPrst(STShapeType.RECT); - prstGeom.addNewAvLst(); - - // Finish up - XWPFPicture xwpfPicture = new XWPFPicture(pic, this); - pictures.add(xwpfPicture); - return xwpfPicture; - } catch (XmlException e) { - throw new IllegalStateException(e); - } catch (SAXException e) { - throw new IllegalStateException(e); - } - } - - /** - * Returns the embedded pictures of the run. These - * are pictures which reference an external, - * embedded picture image such as a .png or .jpg - */ - public List getEmbeddedPictures() { - return pictures; - } - - /** - * Returns the string version of the text - */ - public String toString() { - return text(); - } - - /** - * Returns the string version of the text, with tabs and - * carriage returns in place of their xml equivalents. - */ - public String text() { - StringBuffer text = new StringBuffer(); - - // Grab the text and tabs of the text run - // Do so in a way that preserves the ordering - XmlCursor c = run.newCursor(); - c.selectPath("./*"); - while (c.toNextSelection()) { - XmlObject o = c.getObject(); - if (o instanceof CTText) { - String tagName = o.getDomNode().getNodeName(); - // Field Codes (w:instrText, defined in spec sec. 17.16.23) - // come up as instances of CTText, but we don't want them - // in the normal text output - if (!"w:instrText".equals(tagName)) { - text.append(((CTText) o).getStringValue()); - } - } - - // Complex type evaluation (currently only for extraction of check boxes) - if (o instanceof CTFldChar) { - CTFldChar ctfldChar = ((CTFldChar) o); - if (ctfldChar.getFldCharType() == STFldCharType.BEGIN) { - if (ctfldChar.getFfData() != null) { - for (CTFFCheckBox checkBox : ctfldChar.getFfData().getCheckBoxList()) { - if (checkBox.getDefault() != null && checkBox.getDefault().getVal() == STOnOff.X_1) { - text.append("|X|"); - } else { - text.append("|_|"); - } - } - } - } - } - - if (o instanceof CTPTab) { - text.append("\t"); - } - if (o instanceof CTBr) { - text.append("\n"); - } - if (o instanceof CTEmpty) { - // Some inline text elements get returned not as - // themselves, but as CTEmpty, owing to some odd - // definitions around line 5642 of the XSDs - // This bit works around it, and replicates the above - // rules for that case - String tagName = o.getDomNode().getNodeName(); - if ("w:tab".equals(tagName) || "tab".equals(tagName)) { - text.append("\t"); - } - if ("w:br".equals(tagName) || "br".equals(tagName)) { - text.append("\n"); - } - if ("w:cr".equals(tagName) || "cr".equals(tagName)) { - text.append("\n"); - } - } - if (o instanceof CTFtnEdnRef) { - CTFtnEdnRef ftn = (CTFtnEdnRef) o; - String footnoteRef = ftn.getDomNode().getLocalName().equals("footnoteReference") ? - "[footnoteRef:" + ftn.getId().intValue() + "]" : "[endnoteRef:" + ftn.getId().intValue() + "]"; - text.append(footnoteRef); - } - } - - c.dispose(); - - // Any picture text? - if (pictureText != null && pictureText.length() > 0) { - text.append("\n").append(pictureText); - } - - return text.toString(); - } - - /** - * @see [MS-OI29500] Run Fonts - */ - public static enum FontCharRange { - ascii /* char 0-127 */, - cs /* complex symbol */, - eastAsia /* east asia */, - hAnsi /* high ansi */ - } -} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFSDT.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFSDT.java deleted file mode 100644 index 355527019..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFSDT.java +++ /dev/null @@ -1,46 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtBlock; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtRun; - -/** - * Experimental class to offer rudimentary read-only processing of - * of StructuredDocumentTags/ContentControl - *

    - * WARNING - APIs expected to change rapidly - */ -public class XWPFSDT extends AbstractXWPFSDT - implements IBodyElement, IRunBody, ISDTContents, IRunElement { - private final ISDTContent content; - - public XWPFSDT(CTSdtRun sdtRun, IBody part) { - super(sdtRun.getSdtPr(), part); - this.content = new XWPFSDTContent(sdtRun.getSdtContent(), part, this); - } - - public XWPFSDT(CTSdtBlock block, IBody part) { - super(block.getSdtPr(), part); - this.content = new XWPFSDTContent(block.getSdtContent(), part, this); - } - - public ISDTContent getContent() { - return content; - } - -} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFSDTCell.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFSDTCell.java deleted file mode 100644 index 83548f7f2..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFSDTCell.java +++ /dev/null @@ -1,43 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtCell; - -/** - * Experimental class to offer rudimentary read-only processing of - * of StructuredDocumentTags/ContentControl that can appear - * in a table row as if a table cell. - *

    - * These can contain one or more cells or other SDTs within them. - *

    - * WARNING - APIs expected to change rapidly - */ -public class XWPFSDTCell extends AbstractXWPFSDT implements ICell { - private final XWPFSDTContentCell cellContent; - - public XWPFSDTCell(CTSdtCell sdtCell, XWPFTableRow xwpfTableRow, IBody part) { - super(sdtCell.getSdtPr(), part); - cellContent = new XWPFSDTContentCell(sdtCell.getSdtContent(), xwpfTableRow, part); - } - - @Override - public ISDTContent getContent() { - return cellContent; - } - -} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFSDTContent.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFSDTContent.java deleted file mode 100644 index 545ef434f..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFSDTContent.java +++ /dev/null @@ -1,136 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlObject; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtBlock; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtContentBlock; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtContentRun; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl; - -/** - * Experimental class to offer rudimentary read-only processing of - * of the contentblock of an SDT/ContentControl. - *

    - *

    - *

    - * WARNING - APIs expected to change rapidly - */ -public class XWPFSDTContent implements ISDTContent { - - // private final IBody part; - // private final XWPFDocument document; - private List paragraphs = new ArrayList(); - private List tables = new ArrayList(); - private List runs = new ArrayList(); - private List contentControls = new ArrayList(); - private List bodyElements = new ArrayList(); - - public XWPFSDTContent(CTSdtContentRun sdtRun, IBody part, IRunBody parent) { - for (CTR ctr : sdtRun.getRArray()) { - XWPFRun run = new XWPFRun(ctr, parent); - runs.add(run); - bodyElements.add(run); - } - } - - public XWPFSDTContent(CTSdtContentBlock block, IBody part, IRunBody parent) { - XmlCursor cursor = block.newCursor(); - cursor.selectPath("./*"); - while (cursor.toNextSelection()) { - XmlObject o = cursor.getObject(); - if (o instanceof CTP) { - XWPFParagraph p = new XWPFParagraph((CTP) o, part); - bodyElements.add(p); - paragraphs.add(p); - } else if (o instanceof CTTbl) { - XWPFTable t = new XWPFTable((CTTbl) o, part); - bodyElements.add(t); - tables.add(t); - } else if (o instanceof CTSdtBlock) { - XWPFSDT c = new XWPFSDT(((CTSdtBlock) o), part); - bodyElements.add(c); - contentControls.add(c); - } else if (o instanceof CTR) { - XWPFRun run = new XWPFRun((CTR) o, parent); - runs.add(run); - bodyElements.add(run); - } - } - cursor.dispose(); - } - - public String getText() { - StringBuilder text = new StringBuilder(); - boolean addNewLine = false; - for (int i = 0; i < bodyElements.size(); i++) { - Object o = bodyElements.get(i); - if (o instanceof XWPFParagraph) { - appendParagraph((XWPFParagraph) o, text); - addNewLine = true; - } else if (o instanceof XWPFTable) { - appendTable((XWPFTable) o, text); - addNewLine = true; - } else if (o instanceof XWPFSDT) { - text.append(((XWPFSDT) o).getContent().getText()); - addNewLine = true; - } else if (o instanceof XWPFRun) { - text.append(((XWPFRun) o).toString()); - addNewLine = false; - } - if (addNewLine == true && i < bodyElements.size() - 1) { - text.append("\n"); - } - } - return text.toString(); - } - - private void appendTable(XWPFTable table, StringBuilder text) { - //this works recursively to pull embedded tables from within cells - for (XWPFTableRow row : table.getRows()) { - List cells = row.getTableICells(); - for (int i = 0; i < cells.size(); i++) { - ICell cell = cells.get(i); - if (cell instanceof XWPFTableCell) { - text.append(((XWPFTableCell) cell).getTextRecursively()); - } else if (cell instanceof XWPFSDTCell) { - text.append(((XWPFSDTCell) cell).getContent().getText()); - } - if (i < cells.size() - 1) { - text.append("\t"); - } - } - text.append('\n'); - } - } - - private void appendParagraph(XWPFParagraph paragraph, StringBuilder text) { - for (IRunElement run : paragraph.getRuns()) { - text.append(run.toString()); - } - } - - public String toString() { - return getText(); - } -} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFSDTContentCell.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFSDTContentCell.java deleted file mode 100644 index 74645dc67..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFSDTContentCell.java +++ /dev/null @@ -1,116 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - - -import javax.xml.namespace.QName; - -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlCursor.TokenType; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtContentCell; - - -/** - * Experimental class to offer rudimentary read-only processing of - * of the XWPFSDTCellContent. - *

    - * WARNING - APIs expected to change rapidly - */ -public class XWPFSDTContentCell implements ISDTContent { - - //A full implementation would grab the icells - //that a content cell can contain. This would require - //significant changes, including changing the notion that the - //parent of a cell can be not just a row, but an sdt. - //For now we are just grabbing the text out of the text tokentypes. - - //private List cells = new ArrayList(). - - private String text = ""; - - public XWPFSDTContentCell(CTSdtContentCell sdtContentCell, - XWPFTableRow xwpfTableRow, IBody part) { - super(); - //sdtContentCell is allowed to be null: minOccurs="0" maxOccurs="1" - if (sdtContentCell == null) { - return; - } - StringBuilder sb = new StringBuilder(); - XmlCursor cursor = sdtContentCell.newCursor(); - - //keep track of the following, - //and add "\n" only before the start of a body - //element if it is not the first body element. - - //index of cell in row - int tcCnt = 0; - //count of body objects - int iBodyCnt = 0; - int depth = 1; - - while (cursor.hasNextToken() && depth > 0) { - TokenType t = cursor.toNextToken(); - if (t.isText()) { - sb.append(cursor.getTextValue()); - } else if (isStartToken(cursor, "tr")) { - tcCnt = 0; - iBodyCnt = 0; - } else if (isStartToken(cursor, "tc")) { - if (tcCnt++ > 0) { - sb.append("\t"); - } - iBodyCnt = 0; - } else if (isStartToken(cursor, "p") || - isStartToken(cursor, "tbl") || - isStartToken(cursor, "sdt")) { - if (iBodyCnt > 0) { - sb.append("\n"); - } - iBodyCnt++; - } - if (cursor.isStart()) { - depth++; - } else if (cursor.isEnd()) { - depth--; - } - } - text = sb.toString(); - cursor.dispose(); - } - - - private boolean isStartToken(XmlCursor cursor, String string) { - if (!cursor.isStart()) { - return false; - } - QName qName = cursor.getName(); - if (qName != null && qName.getLocalPart() != null && - qName.getLocalPart().equals(string)) { - return true; - } - return false; - } - - - public String getText() { - return text; - } - - public String toString() { - return getText(); - } -} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFSettings.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFSettings.java deleted file mode 100644 index 559c73f0c..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFSettings.java +++ /dev/null @@ -1,433 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -import static org.apache.poi.POIXMLTypeLoader.DEFAULT_XML_OPTIONS; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.math.BigInteger; -import java.security.SecureRandom; -import java.util.Arrays; - -import javax.xml.namespace.QName; - -import org.apache.poi.EncryptedDocumentException; -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.poifs.crypt.CryptoFunctions; -import org.apache.poi.poifs.crypt.HashAlgorithm; -import org.apache.xmlbeans.XmlOptions; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDocProtect; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTOnOff; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSettings; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTZoom; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STAlgClass; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STAlgType; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STCryptProv; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STDocProtect; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STOnOff; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.SettingsDocument; - -public class XWPFSettings extends POIXMLDocumentPart { - - private CTSettings ctSettings; - - /** - * @since POI 3.14-Beta1 - */ - public XWPFSettings(PackagePart part) throws IOException { - super(part); - } - - public XWPFSettings() { - super(); - ctSettings = CTSettings.Factory.newInstance(); - } - - @Override - protected void onDocumentRead() throws IOException { - super.onDocumentRead(); - readFrom(getPackagePart().getInputStream()); - } - - /** - * Set zoom.
    - * In the zoom tag inside settings.xml file
    - * it sets the value of zoom - *
    - * sample snippet from settings.xml - *

    -     *    <w:zoom w:percent="50" />
    -     * 
    -     *
    -     * @return percentage as an integer of zoom level
    -     */
    -    public long getZoomPercent() {
    -        CTZoom zoom;
    -        if (!ctSettings.isSetZoom()) {
    -            zoom = ctSettings.addNewZoom();
    -        } else {
    -            zoom = ctSettings.getZoom();
    -        }
    -
    -        
    -        BigInteger percent = zoom.getPercent();
    -        if(percent == null) {
    -            return 100;
    -        }
    -        return percent.longValue();
    -    }
    -
    -    /**
    -     * Set zoom.
    - * In the zoom tag inside settings.xml file
    - * it sets the value of zoom - *
    - * sample snippet from settings.xml - *
    -     *    <w:zoom w:percent="50" />
    -     * 
    -     */
    -    public void setZoomPercent(long zoomPercent) {
    -        if (!ctSettings.isSetZoom()) {
    -            ctSettings.addNewZoom();
    -        }
    -        CTZoom zoom = ctSettings.getZoom();
    -        zoom.setPercent(BigInteger.valueOf(zoomPercent));
    -    }
    -	
    -	/**
    -     * Verifies the documentProtection tag inside settings.xml file 
    - * if the protection is enforced (w:enforcement="1")
    - *

    - *
    - * sample snippet from settings.xml - *

    -     *     <w:settings  ... >
    -     *         <w:documentProtection w:edit="readOnly" w:enforcement="1"/>
    -     * 
    - * - * @return true if documentProtection is enforced with option any - */ - public boolean isEnforcedWith() { - CTDocProtect ctDocProtect = ctSettings.getDocumentProtection(); - - if (ctDocProtect == null) { - return false; - } - - return ctDocProtect.getEnforcement().equals(STOnOff.X_1); - } - - /** - * Verifies the documentProtection tag inside settings.xml file
    - * if the protection is enforced (w:enforcement="1")
    - * and if the kind of protection equals to passed (STDocProtect.Enum editValue)
    - *

    - *
    - * sample snippet from settings.xml - *

    -     *     <w:settings  ... >
    -     *         <w:documentProtection w:edit="readOnly" w:enforcement="1"/>
    -     * 
    - * - * @return true if documentProtection is enforced with option readOnly - */ - public boolean isEnforcedWith(STDocProtect.Enum editValue) { - CTDocProtect ctDocProtect = ctSettings.getDocumentProtection(); - - if (ctDocProtect == null) { - return false; - } - - return ctDocProtect.getEnforcement().equals(STOnOff.X_1) && ctDocProtect.getEdit().equals(editValue); - } - - /** - * Enforces the protection with the option specified by passed editValue.
    - *
    - * In the documentProtection tag inside settings.xml file
    - * it sets the value of enforcement to "1" (w:enforcement="1")
    - * and the value of edit to the passed editValue (w:edit="[passed editValue]")
    - *
    - * sample snippet from settings.xml - *
    -     *     <w:settings  ... >
    -     *         <w:documentProtection w:edit="[passed editValue]" w:enforcement="1"/>
    -     * 
    - */ - public void setEnforcementEditValue(org.openxmlformats.schemas.wordprocessingml.x2006.main.STDocProtect.Enum editValue) { - safeGetDocumentProtection().setEnforcement(STOnOff.X_1); - safeGetDocumentProtection().setEdit(editValue); - } - - /** - * Enforces the protection with the option specified by passed editValue and password.
    - *
    - * sample snippet from settings.xml - *
    -     *   <w:documentProtection w:edit="[passed editValue]" w:enforcement="1"
    -     *       w:cryptProviderType="rsaAES" w:cryptAlgorithmClass="hash"
    -     *       w:cryptAlgorithmType="typeAny" w:cryptAlgorithmSid="14"
    -     *       w:cryptSpinCount="100000" w:hash="..." w:salt="...."
    -     *   />
    -     * 
    - * - * @param editValue the protection type - * @param password the plaintext password, if null no password will be applied - * @param hashAlgo the hash algorithm - only md2, m5, sha1, sha256, sha384 and sha512 are supported. - * if null, it will default default to sha1 - */ - public void setEnforcementEditValue(org.openxmlformats.schemas.wordprocessingml.x2006.main.STDocProtect.Enum editValue, - String password, HashAlgorithm hashAlgo) { - safeGetDocumentProtection().setEnforcement(STOnOff.X_1); - safeGetDocumentProtection().setEdit(editValue); - - if (password == null) { - if (safeGetDocumentProtection().isSetCryptProviderType()) { - safeGetDocumentProtection().unsetCryptProviderType(); - } - - if (safeGetDocumentProtection().isSetCryptAlgorithmClass()) { - safeGetDocumentProtection().unsetCryptAlgorithmClass(); - } - - if (safeGetDocumentProtection().isSetCryptAlgorithmType()) { - safeGetDocumentProtection().unsetCryptAlgorithmType(); - } - - if (safeGetDocumentProtection().isSetCryptAlgorithmSid()) { - safeGetDocumentProtection().unsetCryptAlgorithmSid(); - } - - if (safeGetDocumentProtection().isSetSalt()) { - safeGetDocumentProtection().unsetSalt(); - } - - if (safeGetDocumentProtection().isSetCryptSpinCount()) { - safeGetDocumentProtection().unsetCryptSpinCount(); - } - - if (safeGetDocumentProtection().isSetHash()) { - safeGetDocumentProtection().unsetHash(); - } - } else { - final STCryptProv.Enum providerType; - final int sid; - if (hashAlgo == null) { - hashAlgo = HashAlgorithm.sha1; - } - - switch (hashAlgo) { - case md2: - providerType = STCryptProv.RSA_FULL; - sid = 1; - break; - case md4: - providerType = STCryptProv.RSA_FULL; - sid = 2; - break; - case md5: - providerType = STCryptProv.RSA_FULL; - sid = 3; - break; - case sha1: - providerType = STCryptProv.RSA_FULL; - sid = 4; - break; - case sha256: - providerType = STCryptProv.RSA_AES; - sid = 12; - break; - case sha384: - providerType = STCryptProv.RSA_AES; - sid = 13; - break; - case sha512: - providerType = STCryptProv.RSA_AES; - sid = 14; - break; - default: - throw new EncryptedDocumentException - ("Hash algorithm '" + hashAlgo + "' is not supported for document write protection."); - } - - - SecureRandom random = new SecureRandom(); - byte salt[] = random.generateSeed(16); - - // Iterations specifies the number of times the hashing function shall be iteratively run (using each - // iteration's result as the input for the next iteration). - int spinCount = 100000; - - String legacyHash = CryptoFunctions.xorHashPasswordReversed(password); - // Implementation Notes List: - // --> In this third stage, the reversed byte order legacy hash from the second stage shall - // be converted to Unicode hex string representation - byte hash[] = CryptoFunctions.hashPassword(legacyHash, hashAlgo, salt, spinCount, false); - - safeGetDocumentProtection().setSalt(salt); - safeGetDocumentProtection().setHash(hash); - safeGetDocumentProtection().setCryptSpinCount(BigInteger.valueOf(spinCount)); - safeGetDocumentProtection().setCryptAlgorithmType(STAlgType.TYPE_ANY); - safeGetDocumentProtection().setCryptAlgorithmClass(STAlgClass.HASH); - safeGetDocumentProtection().setCryptProviderType(providerType); - safeGetDocumentProtection().setCryptAlgorithmSid(BigInteger.valueOf(sid)); - } - } - - /** - * Validates the existing password - * - * @param password - * @return true, only if password was set and equals, false otherwise - */ - public boolean validateProtectionPassword(String password) { - BigInteger sid = safeGetDocumentProtection().getCryptAlgorithmSid(); - byte hash[] = safeGetDocumentProtection().getHash(); - byte salt[] = safeGetDocumentProtection().getSalt(); - BigInteger spinCount = safeGetDocumentProtection().getCryptSpinCount(); - - if (sid == null || hash == null || salt == null || spinCount == null) return false; - - HashAlgorithm hashAlgo; - switch (sid.intValue()) { - case 1: - hashAlgo = HashAlgorithm.md2; - break; - case 2: - hashAlgo = HashAlgorithm.md4; - break; - case 3: - hashAlgo = HashAlgorithm.md5; - break; - case 4: - hashAlgo = HashAlgorithm.sha1; - break; - case 12: - hashAlgo = HashAlgorithm.sha256; - break; - case 13: - hashAlgo = HashAlgorithm.sha384; - break; - case 14: - hashAlgo = HashAlgorithm.sha512; - break; - default: - return false; - } - - String legacyHash = CryptoFunctions.xorHashPasswordReversed(password); - // Implementation Notes List: - // --> In this third stage, the reversed byte order legacy hash from the second stage shall - // be converted to Unicode hex string representation - byte hash2[] = CryptoFunctions.hashPassword(legacyHash, hashAlgo, salt, spinCount.intValue(), false); - - return Arrays.equals(hash, hash2); - } - - /** - * Removes protection enforcement.
    - * In the documentProtection tag inside settings.xml file
    - * it sets the value of enforcement to "0" (w:enforcement="0")
    - */ - public void removeEnforcement() { - safeGetDocumentProtection().setEnforcement(STOnOff.X_0); - } - - /** - * Enforces fields update on document open (in Word). - * In the settings.xml file
    - * sets the updateSettings value to true (w:updateSettings w:val="true") - *

    - * NOTICES: - *

      - *
    • Causing Word to ask on open: "This document contains fields that may refer to other files. Do you want to update the fields in this document?" - * (if "Update automatic links at open" is enabled)
    • - *
    • Flag is removed after saving with changes in Word
    • - *
    - */ - public void setUpdateFields() { - CTOnOff onOff = CTOnOff.Factory.newInstance(); - onOff.setVal(STOnOff.TRUE); - ctSettings.setUpdateFields(onOff); - } - - boolean isUpdateFields() { - return ctSettings.isSetUpdateFields() && ctSettings.getUpdateFields().getVal() == STOnOff.TRUE; - } - - /** - * Check if revision tracking is turned on. - * - * @return true if revision tracking is turned on - */ - public boolean isTrackRevisions() { - return ctSettings.isSetTrackRevisions(); - } - - /** - * Enable or disable revision tracking. - * - * @param enable true to turn on revision tracking, false to turn off revision tracking - */ - public void setTrackRevisions(boolean enable) { - if (enable) { - if (!ctSettings.isSetTrackRevisions()) { - ctSettings.addNewTrackRevisions(); - } - } else { - if (ctSettings.isSetTrackRevisions()) { - ctSettings.unsetTrackRevisions(); - } - } - } - - @Override - protected void commit() throws IOException { - if (ctSettings == null) { - throw new IllegalStateException("Unable to write out settings that were never read in!"); - } - - XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS); - xmlOptions.setSaveSyntheticDocumentElement(new QName(CTSettings.type.getName().getNamespaceURI(), "settings")); - - PackagePart part = getPackagePart(); - OutputStream out = part.getOutputStream(); - ctSettings.save(out, xmlOptions); - out.close(); - } - - private CTDocProtect safeGetDocumentProtection() { - CTDocProtect documentProtection = ctSettings.getDocumentProtection(); - if (documentProtection == null) { - documentProtection = CTDocProtect.Factory.newInstance(); - ctSettings.setDocumentProtection(documentProtection); - } - return ctSettings.getDocumentProtection(); - } - - private void readFrom(InputStream inputStream) { - try { - ctSettings = SettingsDocument.Factory.parse(inputStream, DEFAULT_XML_OPTIONS).getSettings(); - } catch (Exception e) { - throw new RuntimeException(e); - } - } -} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFStyle.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFStyle.java deleted file mode 100644 index 05f59189a..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFStyle.java +++ /dev/null @@ -1,159 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xwpf.usermodel; - -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTStyle; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STStyleType; - -/** - * @author Philipp Epp - */ -public class XWPFStyle { - - protected XWPFStyles styles; - private CTStyle ctStyle; - - /** - * constructor - * - * @param style - */ - public XWPFStyle(CTStyle style) { - this(style, null); - } - - /** - * constructor - * - * @param style - * @param styles - */ - public XWPFStyle(CTStyle style, XWPFStyles styles) { - this.ctStyle = style; - this.styles = styles; - } - - /** - * get StyleID of the style - * - * @return styleID StyleID of the style - */ - public String getStyleId() { - return ctStyle.getStyleId(); - } - - /** - * set styleID - * - * @param styleId - */ - public void setStyleId(String styleId) { - ctStyle.setStyleId(styleId); - } - - /** - * get Type of the Style - * - * @return ctType - */ - public STStyleType.Enum getType() { - return ctStyle.getType(); - } - - /** - * set styleType - * - * @param type - */ - public void setType(STStyleType.Enum type) { - ctStyle.setType(type); - } - - /** - * set style - * - * @param style - */ - public void setStyle(CTStyle style) { - this.ctStyle = style; - } - - /** - * get ctStyle - * - * @return ctStyle - */ - public CTStyle getCTStyle() { - return this.ctStyle; - } - - /** - * get styles - * - * @return styles the styles to which this style belongs - */ - public XWPFStyles getStyles() { - return styles; - } - - public String getBasisStyleID() { - if (ctStyle.getBasedOn() != null) - return ctStyle.getBasedOn().getVal(); - else - return null; - } - - - /** - * get StyleID of the linked Style - */ - public String getLinkStyleID() { - if (ctStyle.getLink() != null) - return ctStyle.getLink().getVal(); - else - return null; - } - - /** - * get StyleID of the next style - */ - public String getNextStyleID() { - if (ctStyle.getNext() != null) - return ctStyle.getNext().getVal(); - else - return null; - } - - public String getName() { - if (ctStyle.isSetName()) - return ctStyle.getName().getVal(); - return null; - } - - /** - * compares the names of the Styles - * - * @param compStyle - */ - public boolean hasSameName(XWPFStyle compStyle) { - CTStyle ctCompStyle = compStyle.getCTStyle(); - String name = ctCompStyle.getName().getVal(); - return name.equals(ctStyle.getName().getVal()); - } - -}//end class diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFStyles.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFStyles.java deleted file mode 100644 index 511c85a6b..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFStyles.java +++ /dev/null @@ -1,326 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xwpf.usermodel; - -import static org.apache.poi.POIXMLTypeLoader.DEFAULT_XML_OPTIONS; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.List; - -import javax.xml.namespace.QName; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.POIXMLException; -import org.apache.poi.openxml4j.exceptions.OpenXML4JException; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlOptions; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDocDefaults; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFonts; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTLanguage; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPPrDefault; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPr; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPrDefault; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTStyle; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTStyles; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.StylesDocument; - -/** - * Holds details of built-in, default and user styles, which - * apply to tables / paragraphs / lists etc. - * Text within one of those with custom stylings has the style - * information stored in the {@link XWPFRun} - */ -public class XWPFStyles extends POIXMLDocumentPart { - private CTStyles ctStyles; - private List listStyle = new ArrayList(); - - private XWPFLatentStyles latentStyles; - private XWPFDefaultRunStyle defaultRunStyle; - private XWPFDefaultParagraphStyle defaultParaStyle; - - /** - * Construct XWPFStyles from a package part - * - * @param part the package part holding the data of the styles, - * - * @since POI 3.14-Beta1 - */ - public XWPFStyles(PackagePart part) throws IOException, OpenXML4JException { - super(part); - } - - /** - * Construct XWPFStyles from scratch for a new document. - */ - public XWPFStyles() { - } - - /** - * Read document - */ - @Override - protected void onDocumentRead() throws IOException { - StylesDocument stylesDoc; - InputStream is = getPackagePart().getInputStream(); - try { - stylesDoc = StylesDocument.Factory.parse(is, DEFAULT_XML_OPTIONS); - setStyles(stylesDoc.getStyles()); - latentStyles = new XWPFLatentStyles(ctStyles.getLatentStyles(), this); - } catch (XmlException e) { - throw new POIXMLException("Unable to read styles", e); - } finally { - is.close(); - } - } - - @Override - protected void commit() throws IOException { - if (ctStyles == null) { - throw new IllegalStateException("Unable to write out styles that were never read in!"); - } - - XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS); - xmlOptions.setSaveSyntheticDocumentElement(new QName(CTStyles.type.getName().getNamespaceURI(), "styles")); - PackagePart part = getPackagePart(); - OutputStream out = part.getOutputStream(); - ctStyles.save(out, xmlOptions); - out.close(); - } - - protected void ensureDocDefaults() { - if (!ctStyles.isSetDocDefaults()) { - ctStyles.addNewDocDefaults(); - } - - CTDocDefaults docDefaults = ctStyles.getDocDefaults(); - if (!docDefaults.isSetPPrDefault()) - docDefaults.addNewPPrDefault(); - if (!docDefaults.isSetRPrDefault()) - docDefaults.addNewRPrDefault(); - - CTPPrDefault pprd = docDefaults.getPPrDefault(); - CTRPrDefault rprd = docDefaults.getRPrDefault(); - if (!pprd.isSetPPr()) pprd.addNewPPr(); - if (!rprd.isSetRPr()) rprd.addNewRPr(); - - defaultRunStyle = new XWPFDefaultRunStyle(rprd.getRPr()); - defaultParaStyle = new XWPFDefaultParagraphStyle(pprd.getPPr()); - } - - /** - * Sets the ctStyles - * - * @param styles - */ - public void setStyles(CTStyles styles) { - ctStyles = styles; - - // Build up all the style objects - for (CTStyle style : ctStyles.getStyleArray()) { - listStyle.add(new XWPFStyle(style, this)); - } - if (ctStyles.isSetDocDefaults()) { - CTDocDefaults docDefaults = ctStyles.getDocDefaults(); - if (docDefaults.isSetRPrDefault() && docDefaults.getRPrDefault().isSetRPr()) { - defaultRunStyle = new XWPFDefaultRunStyle( - docDefaults.getRPrDefault().getRPr()); - } - if (docDefaults.isSetPPrDefault() && docDefaults.getPPrDefault().isSetPPr()) { - defaultParaStyle = new XWPFDefaultParagraphStyle( - docDefaults.getPPrDefault().getPPr()); - } - } - } - - /** - * checks whether style with styleID exist - * - * @param styleID styleID of the Style in the style-Document - * @return true if style exist, false if style not exist - */ - public boolean styleExist(String styleID) { - for (XWPFStyle style : listStyle) { - if (style.getStyleId().equals(styleID)) - return true; - } - return false; - } - - /** - * add a style to the document - * - * @param style - * @throws IOException - */ - public void addStyle(XWPFStyle style) { - listStyle.add(style); - ctStyles.addNewStyle(); - int pos = ctStyles.sizeOfStyleArray() - 1; - ctStyles.setStyleArray(pos, style.getCTStyle()); - } - - /** - * Get style by a styleID - * - * @param styleID styleID of the searched style - * @return style - */ - public XWPFStyle getStyle(String styleID) { - for (XWPFStyle style : listStyle) { - try { - if (style.getStyleId().equals(styleID)) - return style; - } catch (NullPointerException e) { - // Ignore NPE - } - } - return null; - } - - public int getNumberOfStyles() { - return listStyle.size(); - } - - /** - * get the styles which are related to the parameter style and their relatives - * this method can be used to copy all styles from one document to another document - * - * @param style - * @return a list of all styles which were used by this method - */ - public List getUsedStyleList(XWPFStyle style) { - List usedStyleList = new ArrayList(); - usedStyleList.add(style); - return getUsedStyleList(style, usedStyleList); - } - - /** - * get the styles which are related to parameter style - * - * @param style - * @return all Styles of the parameterList - */ - private List getUsedStyleList(XWPFStyle style, List usedStyleList) { - String basisStyleID = style.getBasisStyleID(); - XWPFStyle basisStyle = getStyle(basisStyleID); - if ((basisStyle != null) && (!usedStyleList.contains(basisStyle))) { - usedStyleList.add(basisStyle); - getUsedStyleList(basisStyle, usedStyleList); - } - String linkStyleID = style.getLinkStyleID(); - XWPFStyle linkStyle = getStyle(linkStyleID); - if ((linkStyle != null) && (!usedStyleList.contains(linkStyle))) { - usedStyleList.add(linkStyle); - getUsedStyleList(linkStyle, usedStyleList); - } - - String nextStyleID = style.getNextStyleID(); - XWPFStyle nextStyle = getStyle(nextStyleID); - if ((nextStyle != null) && (!usedStyleList.contains(nextStyle))) { - usedStyleList.add(linkStyle); - getUsedStyleList(linkStyle, usedStyleList); - } - return usedStyleList; - } - - protected CTLanguage getCTLanguage() { - ensureDocDefaults(); - - CTLanguage lang = null; - if (defaultRunStyle.getRPr().isSetLang()) { - lang = defaultRunStyle.getRPr().getLang(); - } else { - lang = defaultRunStyle.getRPr().addNewLang(); - } - - return lang; - } - - /** - * Sets the default spelling language on ctStyles DocDefaults parameter - * - * @param strSpellingLanguage - */ - public void setSpellingLanguage(String strSpellingLanguage) { - CTLanguage lang = getCTLanguage(); - lang.setVal(strSpellingLanguage); - lang.setBidi(strSpellingLanguage); - } - - /** - * Sets the default East Asia spelling language on ctStyles DocDefaults parameter - * - * @param strEastAsia - */ - public void setEastAsia(String strEastAsia) { - CTLanguage lang = getCTLanguage(); - lang.setEastAsia(strEastAsia); - } - - /** - * Sets the default font on ctStyles DocDefaults parameter - * TODO Replace this with specific setters for each type, possibly - * on XWPFDefaultRunStyle - */ - public void setDefaultFonts(CTFonts fonts) { - ensureDocDefaults(); - - CTRPr runProps = defaultRunStyle.getRPr(); - runProps.setRFonts(fonts); - } - - /** - * get the style with the same name - * if this style is not existing, return null - */ - public XWPFStyle getStyleWithSameName(XWPFStyle style) { - for (XWPFStyle ownStyle : listStyle) { - if (ownStyle.hasSameName(style)) { - return ownStyle; - } - } - return null; - } - - /** - * Get the default style which applies text runs in the document - */ - public XWPFDefaultRunStyle getDefaultRunStyle() { - ensureDocDefaults(); - return defaultRunStyle; - } - - /** - * Get the default paragraph style which applies to the document - */ - public XWPFDefaultParagraphStyle getDefaultParagraphStyle() { - ensureDocDefaults(); - return defaultParaStyle; - } - - /** - * Get the definition of all the Latent Styles - */ - public XWPFLatentStyles getLatentStyles() { - return latentStyles; - } -} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFTable.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFTable.java deleted file mode 100644 index 2e4bb5c80..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFTable.java +++ /dev/null @@ -1,635 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.List; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.util.Internal; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBorder; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDecimalNumber; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRow; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTString; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblBorders; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblCellMar; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblPr; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblWidth; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTc; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STBorder; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTblWidth; - -/** - *

    Sketch of XWPFTable class. Only table's text is being hold.

    - *

    Specifies the contents of a table present in the document. A table is a set - * of paragraphs (and other block-level content) arranged in rows and columns.

    - */ -public class XWPFTable implements IBodyElement, ISDTContents { - private static EnumMap xwpfBorderTypeMap; - // Create a map from the STBorder.Enum values to the XWPF-level enums - private static HashMap stBorderTypeMap; - - static { - // populate enum maps - xwpfBorderTypeMap = new EnumMap(XWPFBorderType.class); - xwpfBorderTypeMap.put(XWPFBorderType.NIL, STBorder.Enum.forInt(STBorder.INT_NIL)); - xwpfBorderTypeMap.put(XWPFBorderType.NONE, STBorder.Enum.forInt(STBorder.INT_NONE)); - xwpfBorderTypeMap.put(XWPFBorderType.SINGLE, STBorder.Enum.forInt(STBorder.INT_SINGLE)); - xwpfBorderTypeMap.put(XWPFBorderType.THICK, STBorder.Enum.forInt(STBorder.INT_THICK)); - xwpfBorderTypeMap.put(XWPFBorderType.DOUBLE, STBorder.Enum.forInt(STBorder.INT_DOUBLE)); - xwpfBorderTypeMap.put(XWPFBorderType.DOTTED, STBorder.Enum.forInt(STBorder.INT_DOTTED)); - xwpfBorderTypeMap.put(XWPFBorderType.DASHED, STBorder.Enum.forInt(STBorder.INT_DASHED)); - xwpfBorderTypeMap.put(XWPFBorderType.DOT_DASH, STBorder.Enum.forInt(STBorder.INT_DOT_DASH)); - - stBorderTypeMap = new HashMap(); - stBorderTypeMap.put(STBorder.INT_NIL, XWPFBorderType.NIL); - stBorderTypeMap.put(STBorder.INT_NONE, XWPFBorderType.NONE); - stBorderTypeMap.put(STBorder.INT_SINGLE, XWPFBorderType.SINGLE); - stBorderTypeMap.put(STBorder.INT_THICK, XWPFBorderType.THICK); - stBorderTypeMap.put(STBorder.INT_DOUBLE, XWPFBorderType.DOUBLE); - stBorderTypeMap.put(STBorder.INT_DOTTED, XWPFBorderType.DOTTED); - stBorderTypeMap.put(STBorder.INT_DASHED, XWPFBorderType.DASHED); - stBorderTypeMap.put(STBorder.INT_DOT_DASH, XWPFBorderType.DOT_DASH); - } - - protected StringBuffer text = new StringBuffer(); - protected List tableRows; - - // Unused: UUF_UNUSED_PUBLIC_OR_PROTECTED_FIELD - //protected List styleIDs; - protected IBody part; - private CTTbl ctTbl; - - public XWPFTable(CTTbl table, IBody part, int row, int col) { - this(table, part); - - for (int i = 0; i < row; i++) { - XWPFTableRow tabRow = (getRow(i) == null) ? createRow() : getRow(i); - for (int k = 0; k < col; k++) { - if (tabRow.getCell(k) == null) { - tabRow.createCell(); - } - } - } - } - - public XWPFTable(CTTbl table, IBody part) { - this.part = part; - this.ctTbl = table; - - tableRows = new ArrayList(); - - // is an empty table: I add one row and one column as default - if (table.sizeOfTrArray() == 0) - createEmptyTable(table); - - for (CTRow row : table.getTrArray()) { - StringBuilder rowText = new StringBuilder(); - XWPFTableRow tabRow = new XWPFTableRow(row, this); - tableRows.add(tabRow); - for (CTTc cell : row.getTcArray()) { - for (CTP ctp : cell.getPArray()) { - XWPFParagraph p = new XWPFParagraph(ctp, part); - if (rowText.length() > 0) { - rowText.append('\t'); - } - rowText.append(p.getText()); - } - } - if (rowText.length() > 0) { - this.text.append(rowText); - this.text.append('\n'); - } - } - } - - private void createEmptyTable(CTTbl table) { - // MINIMUM ELEMENTS FOR A TABLE - table.addNewTr().addNewTc().addNewP(); - - CTTblPr tblpro = table.addNewTblPr(); - tblpro.addNewTblW().setW(new BigInteger("0")); - tblpro.getTblW().setType(STTblWidth.AUTO); - - // layout - // tblpro.addNewTblLayout().setType(STTblLayoutType.AUTOFIT); - - // borders - CTTblBorders borders = tblpro.addNewTblBorders(); - borders.addNewBottom().setVal(STBorder.SINGLE); - borders.addNewInsideH().setVal(STBorder.SINGLE); - borders.addNewInsideV().setVal(STBorder.SINGLE); - borders.addNewLeft().setVal(STBorder.SINGLE); - borders.addNewRight().setVal(STBorder.SINGLE); - borders.addNewTop().setVal(STBorder.SINGLE); - - /* - * CTTblGrid tblgrid=table.addNewTblGrid(); - * tblgrid.addNewGridCol().setW(new BigInteger("2000")); - */ - getRows(); - } - - /** - * @return ctTbl object - */ - @Internal - public CTTbl getCTTbl() { - return ctTbl; - } - - /** - * Convenience method to extract text in cells. This - * does not extract text recursively in cells, and it does not - * currently include text in SDT (form) components. - *

    - * To get all text within a table, see XWPFWordExtractor's appendTableText - * as an example. - * - * @return text - */ - public String getText() { - return text.toString(); - } - - public void addNewRowBetween(int start, int end) { - // TODO - } - - /** - * add a new column for each row in this table - */ - public void addNewCol() { - if (ctTbl.sizeOfTrArray() == 0) { - createRow(); - } - for (int i = 0; i < ctTbl.sizeOfTrArray(); i++) { - XWPFTableRow tabRow = new XWPFTableRow(ctTbl.getTrArray(i), this); - tabRow.createCell(); - } - } - - /** - * create a new XWPFTableRow object with as many cells as the number of columns defined in that moment - * - * @return tableRow - */ - public XWPFTableRow createRow() { - int sizeCol = ctTbl.sizeOfTrArray() > 0 ? ctTbl.getTrArray(0) - .sizeOfTcArray() : 0; - XWPFTableRow tabRow = new XWPFTableRow(ctTbl.addNewTr(), this); - addColumn(tabRow, sizeCol); - tableRows.add(tabRow); - return tabRow; - } - - /** - * @param pos - index of the row - * @return the row at the position specified or null if no rows is defined or if the position is greather than the max size of rows array - */ - public XWPFTableRow getRow(int pos) { - if (pos >= 0 && pos < ctTbl.sizeOfTrArray()) { - //return new XWPFTableRow(ctTbl.getTrArray(pos)); - return getRows().get(pos); - } - return null; - } - - /** - * @return width value - */ - public int getWidth() { - CTTblPr tblPr = getTrPr(); - return tblPr.isSetTblW() ? tblPr.getTblW().getW().intValue() : -1; - } - - /** - * @param width - */ - public void setWidth(int width) { - CTTblPr tblPr = getTrPr(); - CTTblWidth tblWidth = tblPr.isSetTblW() ? tblPr.getTblW() : tblPr.addNewTblW(); - tblWidth.setW(new BigInteger("" + width)); - } - - /** - * @return number of rows in table - */ - public int getNumberOfRows() { - return ctTbl.sizeOfTrArray(); - } - - private CTTblPr getTrPr() { - return (ctTbl.getTblPr() != null) ? ctTbl.getTblPr() : ctTbl - .addNewTblPr(); - } - - private void addColumn(XWPFTableRow tabRow, int sizeCol) { - if (sizeCol > 0) { - for (int i = 0; i < sizeCol; i++) { - tabRow.createCell(); - } - } - } - - /** - * get the StyleID of the table - * - * @return style-ID of the table - */ - public String getStyleID() { - String styleId = null; - CTTblPr tblPr = ctTbl.getTblPr(); - if (tblPr != null) { - CTString styleStr = tblPr.getTblStyle(); - if (styleStr != null) { - styleId = styleStr.getVal(); - } - } - return styleId; - } - - /** - * Set the table style. If the style is not defined in the document, MS Word - * will set the table style to "Normal". - * - * @param styleName - the style name to apply to this table - */ - public void setStyleID(String styleName) { - CTTblPr tblPr = getTrPr(); - CTString styleStr = tblPr.getTblStyle(); - if (styleStr == null) { - styleStr = tblPr.addNewTblStyle(); - } - styleStr.setVal(styleName); - } - - public XWPFBorderType getInsideHBorderType() { - XWPFBorderType bt = null; - - CTTblPr tblPr = getTrPr(); - if (tblPr.isSetTblBorders()) { - CTTblBorders ctb = tblPr.getTblBorders(); - if (ctb.isSetInsideH()) { - CTBorder border = ctb.getInsideH(); - bt = stBorderTypeMap.get(border.getVal().intValue()); - } - } - return bt; - } - - public int getInsideHBorderSize() { - int size = -1; - - CTTblPr tblPr = getTrPr(); - if (tblPr.isSetTblBorders()) { - CTTblBorders ctb = tblPr.getTblBorders(); - if (ctb.isSetInsideH()) { - CTBorder border = ctb.getInsideH(); - size = border.getSz().intValue(); - } - } - return size; - } - - public int getInsideHBorderSpace() { - int space = -1; - - CTTblPr tblPr = getTrPr(); - if (tblPr.isSetTblBorders()) { - CTTblBorders ctb = tblPr.getTblBorders(); - if (ctb.isSetInsideH()) { - CTBorder border = ctb.getInsideH(); - space = border.getSpace().intValue(); - } - } - return space; - } - - public String getInsideHBorderColor() { - String color = null; - - CTTblPr tblPr = getTrPr(); - if (tblPr.isSetTblBorders()) { - CTTblBorders ctb = tblPr.getTblBorders(); - if (ctb.isSetInsideH()) { - CTBorder border = ctb.getInsideH(); - color = border.xgetColor().getStringValue(); - } - } - return color; - } - - public XWPFBorderType getInsideVBorderType() { - XWPFBorderType bt = null; - - CTTblPr tblPr = getTrPr(); - if (tblPr.isSetTblBorders()) { - CTTblBorders ctb = tblPr.getTblBorders(); - if (ctb.isSetInsideV()) { - CTBorder border = ctb.getInsideV(); - bt = stBorderTypeMap.get(border.getVal().intValue()); - } - } - return bt; - } - - public int getInsideVBorderSize() { - int size = -1; - - CTTblPr tblPr = getTrPr(); - if (tblPr.isSetTblBorders()) { - CTTblBorders ctb = tblPr.getTblBorders(); - if (ctb.isSetInsideV()) { - CTBorder border = ctb.getInsideV(); - size = border.getSz().intValue(); - } - } - return size; - } - - public int getInsideVBorderSpace() { - int space = -1; - - CTTblPr tblPr = getTrPr(); - if (tblPr.isSetTblBorders()) { - CTTblBorders ctb = tblPr.getTblBorders(); - if (ctb.isSetInsideV()) { - CTBorder border = ctb.getInsideV(); - space = border.getSpace().intValue(); - } - } - return space; - } - - public String getInsideVBorderColor() { - String color = null; - - CTTblPr tblPr = getTrPr(); - if (tblPr.isSetTblBorders()) { - CTTblBorders ctb = tblPr.getTblBorders(); - if (ctb.isSetInsideV()) { - CTBorder border = ctb.getInsideV(); - color = border.xgetColor().getStringValue(); - } - } - return color; - } - - public int getRowBandSize() { - int size = 0; - CTTblPr tblPr = getTrPr(); - if (tblPr.isSetTblStyleRowBandSize()) { - CTDecimalNumber rowSize = tblPr.getTblStyleRowBandSize(); - size = rowSize.getVal().intValue(); - } - return size; - } - - public void setRowBandSize(int size) { - CTTblPr tblPr = getTrPr(); - CTDecimalNumber rowSize = tblPr.isSetTblStyleRowBandSize() ? tblPr.getTblStyleRowBandSize() : tblPr.addNewTblStyleRowBandSize(); - rowSize.setVal(BigInteger.valueOf(size)); - } - - public int getColBandSize() { - int size = 0; - CTTblPr tblPr = getTrPr(); - if (tblPr.isSetTblStyleColBandSize()) { - CTDecimalNumber colSize = tblPr.getTblStyleColBandSize(); - size = colSize.getVal().intValue(); - } - return size; - } - - public void setColBandSize(int size) { - CTTblPr tblPr = getTrPr(); - CTDecimalNumber colSize = tblPr.isSetTblStyleColBandSize() ? tblPr.getTblStyleColBandSize() : tblPr.addNewTblStyleColBandSize(); - colSize.setVal(BigInteger.valueOf(size)); - } - - public void setInsideHBorder(XWPFBorderType type, int size, int space, String rgbColor) { - CTTblPr tblPr = getTrPr(); - CTTblBorders ctb = tblPr.isSetTblBorders() ? tblPr.getTblBorders() : tblPr.addNewTblBorders(); - CTBorder b = ctb.isSetInsideH() ? ctb.getInsideH() : ctb.addNewInsideH(); - b.setVal(xwpfBorderTypeMap.get(type)); - b.setSz(BigInteger.valueOf(size)); - b.setSpace(BigInteger.valueOf(space)); - b.setColor(rgbColor); - } - - public void setInsideVBorder(XWPFBorderType type, int size, int space, String rgbColor) { - CTTblPr tblPr = getTrPr(); - CTTblBorders ctb = tblPr.isSetTblBorders() ? tblPr.getTblBorders() : tblPr.addNewTblBorders(); - CTBorder b = ctb.isSetInsideV() ? ctb.getInsideV() : ctb.addNewInsideV(); - b.setVal(xwpfBorderTypeMap.get(type)); - b.setSz(BigInteger.valueOf(size)); - b.setSpace(BigInteger.valueOf(space)); - b.setColor(rgbColor); - } - - public int getCellMarginTop() { - int margin = 0; - CTTblPr tblPr = getTrPr(); - CTTblCellMar tcm = tblPr.getTblCellMar(); - if (tcm != null) { - CTTblWidth tw = tcm.getTop(); - if (tw != null) { - margin = tw.getW().intValue(); - } - } - return margin; - } - - public int getCellMarginLeft() { - int margin = 0; - CTTblPr tblPr = getTrPr(); - CTTblCellMar tcm = tblPr.getTblCellMar(); - if (tcm != null) { - CTTblWidth tw = tcm.getLeft(); - if (tw != null) { - margin = tw.getW().intValue(); - } - } - return margin; - } - - public int getCellMarginBottom() { - int margin = 0; - CTTblPr tblPr = getTrPr(); - CTTblCellMar tcm = tblPr.getTblCellMar(); - if (tcm != null) { - CTTblWidth tw = tcm.getBottom(); - if (tw != null) { - margin = tw.getW().intValue(); - } - } - return margin; - } - - public int getCellMarginRight() { - int margin = 0; - CTTblPr tblPr = getTrPr(); - CTTblCellMar tcm = tblPr.getTblCellMar(); - if (tcm != null) { - CTTblWidth tw = tcm.getRight(); - if (tw != null) { - margin = tw.getW().intValue(); - } - } - return margin; - } - - public void setCellMargins(int top, int left, int bottom, int right) { - CTTblPr tblPr = getTrPr(); - CTTblCellMar tcm = tblPr.isSetTblCellMar() ? tblPr.getTblCellMar() : tblPr.addNewTblCellMar(); - - CTTblWidth tw = tcm.isSetLeft() ? tcm.getLeft() : tcm.addNewLeft(); - tw.setType(STTblWidth.DXA); - tw.setW(BigInteger.valueOf(left)); - - tw = tcm.isSetTop() ? tcm.getTop() : tcm.addNewTop(); - tw.setType(STTblWidth.DXA); - tw.setW(BigInteger.valueOf(top)); - - tw = tcm.isSetBottom() ? tcm.getBottom() : tcm.addNewBottom(); - tw.setType(STTblWidth.DXA); - tw.setW(BigInteger.valueOf(bottom)); - - tw = tcm.isSetRight() ? tcm.getRight() : tcm.addNewRight(); - tw.setType(STTblWidth.DXA); - tw.setW(BigInteger.valueOf(right)); - } - - /** - * add a new Row to the table - * - * @param row the row which should be added - */ - public void addRow(XWPFTableRow row) { - ctTbl.addNewTr(); - ctTbl.setTrArray(getNumberOfRows() - 1, row.getCtRow()); - tableRows.add(row); - } - - /** - * add a new Row to the table - * at position pos - * - * @param row the row which should be added - */ - public boolean addRow(XWPFTableRow row, int pos) { - if (pos >= 0 && pos <= tableRows.size()) { - ctTbl.insertNewTr(pos); - ctTbl.setTrArray(pos, row.getCtRow()); - tableRows.add(pos, row); - return true; - } - return false; - } - - /** - * inserts a new tablerow - * - * @param pos - * @return the inserted row - */ - public XWPFTableRow insertNewTableRow(int pos) { - if (pos >= 0 && pos <= tableRows.size()) { - CTRow row = ctTbl.insertNewTr(pos); - XWPFTableRow tableRow = new XWPFTableRow(row, this); - tableRows.add(pos, tableRow); - return tableRow; - } - return null; - } - - /** - * Remove a row at position pos from the table - * - * @param pos position the Row in the Table - */ - public boolean removeRow(int pos) throws IndexOutOfBoundsException { - if (pos >= 0 && pos < tableRows.size()) { - if (ctTbl.sizeOfTrArray() > 0) { - ctTbl.removeTr(pos); - } - tableRows.remove(pos); - return true; - } - return false; - } - - public List getRows() { - return tableRows; - } - - /** - * returns the type of the BodyElement Table - * - * @see org.apache.poi.xwpf.usermodel.IBodyElement#getElementType() - */ - public BodyElementType getElementType() { - return BodyElementType.TABLE; - } - - public IBody getBody() { - return part; - } - - /** - * returns the part of the bodyElement - * - * @see org.apache.poi.xwpf.usermodel.IBody#getPart() - */ - public POIXMLDocumentPart getPart() { - if (part != null) { - return part.getPart(); - } - return null; - } - - /** - * returns the partType of the bodyPart which owns the bodyElement - * - * @see org.apache.poi.xwpf.usermodel.IBody#getPartType() - */ - public BodyType getPartType() { - return part.getPartType(); - } - - /** - * returns the XWPFRow which belongs to the CTRow row - * if this row is not existing in the table null will be returned - */ - public XWPFTableRow getRow(CTRow row) { - for (int i = 0; i < getRows().size(); i++) { - if (getRows().get(i).getCtRow() == row) return getRow(i); - } - return null; - } - - // Create a map from this XWPF-level enum to the STBorder.Enum values - public static enum XWPFBorderType { - NIL, NONE, SINGLE, THICK, DOUBLE, DOTTED, DASHED, DOT_DASH - } -} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFTableCell.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFTableCell.java deleted file mode 100644 index 27f2c43ad..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFTableCell.java +++ /dev/null @@ -1,513 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.List; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.util.Internal; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlObject; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRow; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtBlock; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtRun; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTShd; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTc; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTcPr; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTVerticalJc; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STShd; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STVerticalJc; - -/** - * Represents a Cell within a {@link XWPFTable}. The - * Cell is the thing that holds the actual content (paragraphs etc) - */ -public class XWPFTableCell implements IBody, ICell { - private static EnumMap alignMap; - // Create a map from the STVerticalJc.Enum values to the XWPF-level enums - private static HashMap stVertAlignTypeMap; - - static { - // populate enum maps - alignMap = new EnumMap(XWPFVertAlign.class); - alignMap.put(XWPFVertAlign.TOP, STVerticalJc.Enum.forInt(STVerticalJc.INT_TOP)); - alignMap.put(XWPFVertAlign.CENTER, STVerticalJc.Enum.forInt(STVerticalJc.INT_CENTER)); - alignMap.put(XWPFVertAlign.BOTH, STVerticalJc.Enum.forInt(STVerticalJc.INT_BOTH)); - alignMap.put(XWPFVertAlign.BOTTOM, STVerticalJc.Enum.forInt(STVerticalJc.INT_BOTTOM)); - - stVertAlignTypeMap = new HashMap(); - stVertAlignTypeMap.put(STVerticalJc.INT_TOP, XWPFVertAlign.TOP); - stVertAlignTypeMap.put(STVerticalJc.INT_CENTER, XWPFVertAlign.CENTER); - stVertAlignTypeMap.put(STVerticalJc.INT_BOTH, XWPFVertAlign.BOTH); - stVertAlignTypeMap.put(STVerticalJc.INT_BOTTOM, XWPFVertAlign.BOTTOM); - - } - - private final CTTc ctTc; - protected List paragraphs = null; - protected List tables = null; - protected List bodyElements = null; - - protected IBody part; - private XWPFTableRow tableRow = null; - - /** - * If a table cell does not include at least one block-level element, then this document shall be considered corrupt - */ - public XWPFTableCell(CTTc cell, XWPFTableRow tableRow, IBody part) { - this.ctTc = cell; - this.part = part; - this.tableRow = tableRow; - // NB: If a table cell does not include at least one block-level element, then this document shall be considered corrupt. - if (cell.sizeOfPArray() < 1) - cell.addNewP(); - bodyElements = new ArrayList(); - paragraphs = new ArrayList(); - tables = new ArrayList(); - - XmlCursor cursor = ctTc.newCursor(); - cursor.selectPath("./*"); - while (cursor.toNextSelection()) { - XmlObject o = cursor.getObject(); - if (o instanceof CTP) { - XWPFParagraph p = new XWPFParagraph((CTP) o, this); - paragraphs.add(p); - bodyElements.add(p); - } - if (o instanceof CTTbl) { - XWPFTable t = new XWPFTable((CTTbl) o, this); - tables.add(t); - bodyElements.add(t); - } - if (o instanceof CTSdtBlock) { - XWPFSDT c = new XWPFSDT((CTSdtBlock) o, this); - bodyElements.add(c); - } - if (o instanceof CTSdtRun) { - XWPFSDT c = new XWPFSDT((CTSdtRun) o, this); - System.out.println(c.getContent().getText()); - bodyElements.add(c); - } - } - cursor.dispose(); - } - - @Internal - public CTTc getCTTc() { - return ctTc; - } - - /** - * returns an Iterator with paragraphs and tables - * - * @see org.apache.poi.xwpf.usermodel.IBody#getBodyElements() - */ - public List getBodyElements() { - return Collections.unmodifiableList(bodyElements); - } - - public void setParagraph(XWPFParagraph p) { - if (ctTc.sizeOfPArray() == 0) { - ctTc.addNewP(); - } - ctTc.setPArray(0, p.getCTP()); - } - - /** - * returns a list of paragraphs - */ - public List getParagraphs() { - return paragraphs; - } - - /** - * Add a Paragraph to this Table Cell - * - * @return The paragraph which was added - */ - public XWPFParagraph addParagraph() { - XWPFParagraph p = new XWPFParagraph(ctTc.addNewP(), this); - addParagraph(p); - return p; - } - - /** - * add a Paragraph to this TableCell - * - * @param p the paragaph which has to be added - */ - public void addParagraph(XWPFParagraph p) { - paragraphs.add(p); - } - - /** - * removes a paragraph of this tablecell - * - * @param pos The position in the list of paragraphs, 0-based - */ - public void removeParagraph(int pos) { - paragraphs.remove(pos); - ctTc.removeP(pos); - } - - /** - * if there is a corresponding {@link XWPFParagraph} of the parameter ctTable in the paragraphList of this table - * the method will return this paragraph - * if there is no corresponding {@link XWPFParagraph} the method will return null - * - * @param p is instance of CTP and is searching for an XWPFParagraph - * @return null if there is no XWPFParagraph with an corresponding CTPparagraph in the paragraphList of this table - * XWPFParagraph with the correspondig CTP p - */ - public XWPFParagraph getParagraph(CTP p) { - for (XWPFParagraph paragraph : paragraphs) { - if (p.equals(paragraph.getCTP())) { - return paragraph; - } - } - return null; - } - - public XWPFTableRow getTableRow() { - return tableRow; - } - - /** - * Get cell color. Note that this method only returns the "fill" value. - * - * @return RGB string of cell color - */ - public String getColor() { - String color = null; - CTTcPr tcpr = ctTc.getTcPr(); - if (tcpr != null) { - CTShd ctshd = tcpr.getShd(); - if (ctshd != null) { - color = ctshd.xgetFill().getStringValue(); - } - } - return color; - } - - /** - * Set cell color. This sets some associated values; for finer control - * you may want to access these elements individually. - * - * @param rgbStr - the desired cell color, in the hex form "RRGGBB". - */ - public void setColor(String rgbStr) { - CTTcPr tcpr = ctTc.isSetTcPr() ? ctTc.getTcPr() : ctTc.addNewTcPr(); - CTShd ctshd = tcpr.isSetShd() ? tcpr.getShd() : tcpr.addNewShd(); - ctshd.setColor("auto"); - ctshd.setVal(STShd.CLEAR); - ctshd.setFill(rgbStr); - } - - /** - * Get the vertical alignment of the cell. - * - * @return the cell alignment enum value or null - * if no vertical alignment is set. - */ - public XWPFVertAlign getVerticalAlignment() { - XWPFVertAlign vAlign = null; - CTTcPr tcpr = ctTc.getTcPr(); - if (tcpr != null) { - CTVerticalJc va = tcpr.getVAlign(); - if(va != null) { - vAlign = stVertAlignTypeMap.get(va.getVal().intValue()); - } - } - return vAlign; - } - - /** - * Set the vertical alignment of the cell. - * - * @param vAlign - the desired alignment enum value - */ - public void setVerticalAlignment(XWPFVertAlign vAlign) { - CTTcPr tcpr = ctTc.isSetTcPr() ? ctTc.getTcPr() : ctTc.addNewTcPr(); - CTVerticalJc va = tcpr.addNewVAlign(); - va.setVal(alignMap.get(vAlign)); - } - - /** - * add a new paragraph at position of the cursor - * - * @param cursor The XmlCursor structure created with XmlBeans - * @return the inserted paragraph - */ - public XWPFParagraph insertNewParagraph(final XmlCursor cursor) { - if (!isCursorInTableCell(cursor)) { - return null; - } - - String uri = CTP.type.getName().getNamespaceURI(); - String localPart = "p"; - cursor.beginElement(localPart, uri); - cursor.toParent(); - CTP p = (CTP) cursor.getObject(); - XWPFParagraph newP = new XWPFParagraph(p, this); - XmlObject o = null; - while (!(o instanceof CTP) && (cursor.toPrevSibling())) { - o = cursor.getObject(); - } - if ((!(o instanceof CTP)) || (CTP) o == p) { - paragraphs.add(0, newP); - } else { - int pos = paragraphs.indexOf(getParagraph((CTP) o)) + 1; - paragraphs.add(pos, newP); - } - int i = 0; - XmlCursor p2 = p.newCursor(); - cursor.toCursor(p2); - p2.dispose(); - while (cursor.toPrevSibling()) { - o = cursor.getObject(); - if (o instanceof CTP || o instanceof CTTbl) - i++; - } - bodyElements.add(i, newP); - p2 = p.newCursor(); - cursor.toCursor(p2); - p2.dispose(); - cursor.toEndToken(); - return newP; - } - - public XWPFTable insertNewTbl(final XmlCursor cursor) { - if (isCursorInTableCell(cursor)) { - String uri = CTTbl.type.getName().getNamespaceURI(); - String localPart = "tbl"; - cursor.beginElement(localPart, uri); - cursor.toParent(); - CTTbl t = (CTTbl) cursor.getObject(); - XWPFTable newT = new XWPFTable(t, this); - cursor.removeXmlContents(); - XmlObject o = null; - while (!(o instanceof CTTbl) && (cursor.toPrevSibling())) { - o = cursor.getObject(); - } - if (!(o instanceof CTTbl)) { - tables.add(0, newT); - } else { - int pos = tables.indexOf(getTable((CTTbl) o)) + 1; - tables.add(pos, newT); - } - int i = 0; - XmlCursor cursor2 = t.newCursor(); - while (cursor2.toPrevSibling()) { - o = cursor2.getObject(); - if (o instanceof CTP || o instanceof CTTbl) - i++; - } - cursor2.dispose(); - bodyElements.add(i, newT); - cursor2 = t.newCursor(); - cursor.toCursor(cursor2); - cursor.toEndToken(); - cursor2.dispose(); - return newT; - } - return null; - } - - /** - * verifies that cursor is on the right position - */ - private boolean isCursorInTableCell(XmlCursor cursor) { - XmlCursor verify = cursor.newCursor(); - verify.toParent(); - boolean result = (verify.getObject() == this.ctTc); - verify.dispose(); - return result; - } - - /** - * @see org.apache.poi.xwpf.usermodel.IBody#getParagraphArray(int) - */ - public XWPFParagraph getParagraphArray(int pos) { - if (pos >= 0 && pos < paragraphs.size()) { - return paragraphs.get(pos); - } - return null; - } - - /** - * get the to which the TableCell belongs - * - * @see org.apache.poi.xwpf.usermodel.IBody#getPart() - */ - public POIXMLDocumentPart getPart() { - return tableRow.getTable().getPart(); - } - - /** - * @see org.apache.poi.xwpf.usermodel.IBody#getPartType() - */ - public BodyType getPartType() { - return BodyType.TABLECELL; - } - - /** - * get a table by its CTTbl-Object - * - * @see org.apache.poi.xwpf.usermodel.IBody#getTable(org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl) - */ - public XWPFTable getTable(CTTbl ctTable) { - for (int i = 0; i < tables.size(); i++) { - if (getTables().get(i).getCTTbl() == ctTable) return getTables().get(i); - } - return null; - } - - /** - * @see org.apache.poi.xwpf.usermodel.IBody#getTableArray(int) - */ - public XWPFTable getTableArray(int pos) { - if(pos >= 0 && pos < tables.size()) { - return tables.get(pos); - } - return null; - } - - /** - * @see org.apache.poi.xwpf.usermodel.IBody#getTables() - */ - public List getTables() { - return Collections.unmodifiableList(tables); - } - - /** - * inserts an existing XWPFTable to the arrays bodyElements and tables - * - * @see org.apache.poi.xwpf.usermodel.IBody#insertTable(int, org.apache.poi.xwpf.usermodel.XWPFTable) - */ - public void insertTable(int pos, XWPFTable table) { - bodyElements.add(pos, table); - int i = 0; - for (CTTbl tbl : ctTc.getTblArray()) { - if (tbl == table.getCTTbl()) { - break; - } - i++; - } - tables.add(i, table); - } - - public String getText() { - StringBuilder text = new StringBuilder(); - for (XWPFParagraph p : paragraphs) { - text.append(p.getText()); - } - return text.toString(); - } - - public void setText(String text) { - CTP ctP = (ctTc.sizeOfPArray() == 0) ? ctTc.addNewP() : ctTc.getPArray(0); - XWPFParagraph par = new XWPFParagraph(ctP, this); - par.createRun().setText(text); - } - - /** - * extracts all text recursively through embedded tables and embedded SDTs - */ - public String getTextRecursively() { - - StringBuffer text = new StringBuffer(); - for (int i = 0; i < bodyElements.size(); i++) { - boolean isLast = (i == bodyElements.size() - 1); - appendBodyElementText(text, bodyElements.get(i), isLast); - } - - return text.toString(); - } - - private void appendBodyElementText(StringBuffer text, IBodyElement e, boolean isLast) { - if (e instanceof XWPFParagraph) { - text.append(((XWPFParagraph) e).getText()); - if (!isLast) { - text.append('\t'); - } - } else if (e instanceof XWPFTable) { - XWPFTable eTable = (XWPFTable) e; - for (XWPFTableRow row : eTable.getRows()) { - for (XWPFTableCell cell : row.getTableCells()) { - List localBodyElements = cell.getBodyElements(); - for (int i = 0; i < localBodyElements.size(); i++) { - boolean localIsLast = (i == localBodyElements.size() - 1); - appendBodyElementText(text, localBodyElements.get(i), localIsLast); - } - } - } - - if (!isLast) { - text.append('\n'); - } - } else if (e instanceof XWPFSDT) { - text.append(((XWPFSDT) e).getContent().getText()); - if (!isLast) { - text.append('\t'); - } - } - } - - /** - * get the TableCell which belongs to the TableCell - */ - public XWPFTableCell getTableCell(CTTc cell) { - XmlCursor cursor = cell.newCursor(); - cursor.toParent(); - XmlObject o = cursor.getObject(); - if (!(o instanceof CTRow)) { - return null; - } - CTRow row = (CTRow) o; - cursor.toParent(); - o = cursor.getObject(); - cursor.dispose(); - if (!(o instanceof CTTbl)) { - return null; - } - CTTbl tbl = (CTTbl) o; - XWPFTable table = getTable(tbl); - if (table == null) { - return null; - } - XWPFTableRow tr = table.getRow(row); - if (tr == null) { - return null; - } - return tr.getTableCell(cell); - } - - public XWPFDocument getXWPFDocument() { - return part.getXWPFDocument(); - } - - // Create a map from this XWPF-level enum to the STVerticalJc.Enum values - public enum XWPFVertAlign { - TOP, CENTER, BOTH, BOTTOM - } -} diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFTableRow.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFTableRow.java deleted file mode 100644 index 4755a8209..000000000 --- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFTableRow.java +++ /dev/null @@ -1,265 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.util.Internal; -import org.apache.poi.xwpf.model.WMLHelper; -import org.apache.xmlbeans.XmlCursor; -import org.apache.xmlbeans.XmlObject; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTHeight; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTOnOff; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRow; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtCell; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTc; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTrPr; - - -/** - * A row within an {@link XWPFTable}. Rows mostly just have - * sizings and stylings, the interesting content lives inside - * the child {@link XWPFTableCell}s - */ -public class XWPFTableRow { - private CTRow ctRow; - private XWPFTable table; - private List tableCells; - - public XWPFTableRow(CTRow row, XWPFTable table) { - this.table = table; - this.ctRow = row; - getTableCells(); - } - - @Internal - public CTRow getCtRow() { - return ctRow; - } - - /** - * create a new XWPFTableCell and add it to the tableCell-list of this tableRow - * - * @return the newly created XWPFTableCell - */ - public XWPFTableCell createCell() { - XWPFTableCell tableCell = new XWPFTableCell(ctRow.addNewTc(), this, table.getBody()); - tableCells.add(tableCell); - return tableCell; - } - - public XWPFTableCell getCell(int pos) { - if (pos >= 0 && pos < ctRow.sizeOfTcArray()) { - return getTableCells().get(pos); - } - return null; - } - - public void removeCell(int pos) { - if (pos >= 0 && pos < ctRow.sizeOfTcArray()) { - tableCells.remove(pos); - } - } - - /** - * adds a new TableCell at the end of this tableRow - */ - public XWPFTableCell addNewTableCell() { - CTTc cell = ctRow.addNewTc(); - XWPFTableCell tableCell = new XWPFTableCell(cell, this, table.getBody()); - tableCells.add(tableCell); - return tableCell; - } - - /** - * This element specifies the height of the current table row within the - * current table. This height shall be used to determine the resulting - * height of the table row, which may be absolute or relative (depending on - * its attribute values). If omitted, then the table row shall automatically - * resize its height to the height required by its contents (the equivalent - * of an hRule value of auto). - * - * @return height - */ - public int getHeight() { - CTTrPr properties = getTrPr(); - return properties.sizeOfTrHeightArray() == 0 ? 0 : properties.getTrHeightArray(0).getVal().intValue(); - } - - /** - * This element specifies the height of the current table row within the - * current table. This height shall be used to determine the resulting - * height of the table row, which may be absolute or relative (depending on - * its attribute values). If omitted, then the table row shall automatically - * resize its height to the height required by its contents (the equivalent - * of an hRule value of auto). - * - * @param height - */ - public void setHeight(int height) { - CTTrPr properties = getTrPr(); - CTHeight h = properties.sizeOfTrHeightArray() == 0 ? properties.addNewTrHeight() : properties.getTrHeightArray(0); - h.setVal(new BigInteger("" + height)); - } - - private CTTrPr getTrPr() { - return (ctRow.isSetTrPr()) ? ctRow.getTrPr() : ctRow.addNewTrPr(); - } - - public XWPFTable getTable() { - return table; - } - - /** - * create and return a list of all XWPFTableCell - * who belongs to this row - * - * @return a list of {@link XWPFTableCell} - */ - public List getTableICells() { - - List cells = new ArrayList(); - //Can't use ctRow.getTcList because that only gets table cells - //Can't use ctRow.getSdtList because that only gets sdts that are at cell level - XmlCursor cursor = ctRow.newCursor(); - cursor.selectPath("./*"); - while (cursor.toNextSelection()) { - XmlObject o = cursor.getObject(); - if (o instanceof CTTc) { - cells.add(new XWPFTableCell((CTTc) o, this, table.getBody())); - } else if (o instanceof CTSdtCell) { - cells.add(new XWPFSDTCell((CTSdtCell) o, this, table.getBody())); - } - } - cursor.dispose(); - return cells; - } - - /** - * create and return a list of all XWPFTableCell - * who belongs to this row - * - * @return a list of {@link XWPFTableCell} - */ - public List getTableCells() { - if (tableCells == null) { - List cells = new ArrayList(); - for (CTTc tableCell : ctRow.getTcArray()) { - cells.add(new XWPFTableCell(tableCell, this, table.getBody())); - } - //TODO: it is possible to have an SDT that contains a cell in within a row - //need to modify this code so that it pulls out SDT wrappers around cells, too. - - this.tableCells = cells; - } - return tableCells; - } - - /** - * returns the XWPFTableCell which belongs to the CTTC cell - * if there is no XWPFTableCell which belongs to the parameter CTTc cell null will be returned - */ - public XWPFTableCell getTableCell(CTTc cell) { - for (int i = 0; i < tableCells.size(); i++) { - if (tableCells.get(i).getCTTc() == cell) - return tableCells.get(i); - } - return null; - } - - /** - * Return true if the "can't split row" value is true. The logic for this - * attribute is a little unusual: a TRUE value means DON'T allow rows to - * split, FALSE means allow rows to split. - * - * @return true if rows can't be split, false otherwise. - */ - public boolean isCantSplitRow() { - boolean isCant = false; - if (ctRow.isSetTrPr()) { - CTTrPr trpr = getTrPr(); - if (trpr.sizeOfCantSplitArray() > 0) { - CTOnOff onoff = trpr.getCantSplitArray(0); - isCant = (onoff.isSetVal() ? WMLHelper.convertSTOnOffToBoolean(onoff.getVal()) : true); - } - } - return isCant; - } - - /** - * Controls whether to allow this table row to split across pages. - * The logic for this attribute is a little unusual: a true value means - * DON'T allow rows to split, false means allow rows to split. - * - * @param split - if true, don't allow row to be split. If false, allow - * row to be split. - */ - public void setCantSplitRow(boolean split) { - CTTrPr trpr = getTrPr(); - CTOnOff onoff = (trpr.sizeOfCantSplitArray() > 0 ? trpr.getCantSplitArray(0) : trpr.addNewCantSplit()); - onoff.setVal(WMLHelper.convertBooleanToSTOnOff(split)); - } - - /** - * Return true if a table's header row should be repeated at the top of a - * table split across pages. NOTE - Word will not repeat a table row unless - * all preceding rows of the table are also repeated. This function returns - * false if the row will not be repeated even if the repeat tag is present - * for this row. - * - * @return true if table's header row should be repeated at the top of each - * page of table, false otherwise. - */ - public boolean isRepeatHeader() { - boolean repeat = false; - for (XWPFTableRow row : table.getRows()) { - repeat = row.getRepeat(); - if (row == this || !repeat) { - break; - } - } - return repeat; - } - - private boolean getRepeat() { - boolean repeat = false; - if (ctRow.isSetTrPr()) { - CTTrPr trpr = getTrPr(); - if (trpr.sizeOfTblHeaderArray() > 0) { - CTOnOff rpt = trpr.getTblHeaderArray(0); - repeat = (rpt.isSetVal() ? WMLHelper.convertSTOnOffToBoolean(rpt.getVal()) : true); - } - } - return repeat; - } - - /** - * This attribute controls whether to repeat a table's header row at the top - * of a table split across pages. NOTE - for a row to be repeated, all preceding - * rows in the table must also be repeated. - * - * @param repeat - if TRUE, repeat header row at the top of each page of table; - * if FALSE, don't repeat header row. - */ - public void setRepeatHeader(boolean repeat) { - CTTrPr trpr = getTrPr(); - CTOnOff onoff = (trpr.sizeOfTblHeaderArray() > 0 ? trpr.getTblHeaderArray(0) : trpr.addNewTblHeader()); - onoff.setVal(WMLHelper.convertBooleanToSTOnOff(repeat)); - } -} diff --git a/src/ooxml/resources/org/apache/poi/poifs/crypt/encryptionCertificate.xsd b/src/ooxml/resources/org/apache/poi/poifs/crypt/encryptionCertificate.xsd deleted file mode 100644 index 7423c85de..000000000 --- a/src/ooxml/resources/org/apache/poi/poifs/crypt/encryptionCertificate.xsd +++ /dev/null @@ -1,39 +0,0 @@ - - - - - - - - - - - - A base64-encoded value that specifies the encrypted form of the intermediate key, which is encrypted with the public key contained within the X509Certificate attribute. - - - A base64-encoded value that specifies a DER-encoded X.509 certificate (1) used to encrypt the intermediate key. The certificate (1) MUST contain only the public portion of the public-private key pair. - - - A base64-encoded value that specifies the HMAC of the binary data obtained by base64-decoding the X509Certificate attribute. The hashing algorithm used to derive the HMAC MUST be the hashing algorithm specified for the Encryption.keyData element. The secret key used to derive the HMAC MUST be the intermediate key. If the intermediate key is reset, any CertificateKeyEncryptor elements are also reset to contain the new intermediate key, except that the certVerifier attribute MUST match the value calculated using the current intermediate key, to verify that the CertificateKeyEncryptor element actually encrypted the current intermediate key. If a CertificateKeyEncryptor element does not have a correct certVerifier attribute, it MUST be discarded. - - - - diff --git a/src/ooxml/resources/org/apache/poi/poifs/crypt/encryptionCertificate.xsdconfig b/src/ooxml/resources/org/apache/poi/poifs/crypt/encryptionCertificate.xsdconfig deleted file mode 100644 index 73a27fa50..000000000 --- a/src/ooxml/resources/org/apache/poi/poifs/crypt/encryptionCertificate.xsdconfig +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/src/ooxml/resources/org/apache/poi/poifs/crypt/encryptionInfo.xsd b/src/ooxml/resources/org/apache/poi/poifs/crypt/encryptionInfo.xsd deleted file mode 100644 index 5b08560c3..000000000 --- a/src/ooxml/resources/org/apache/poi/poifs/crypt/encryptionInfo.xsd +++ /dev/null @@ -1,259 +0,0 @@ - - - - - - - - An unsigned integer that specifies the number of bytes used by a salt. It MUST be at least 1 and no greater than 65,536. - - - - - - - - - An unsigned integer that specifies the number of bytes used to encrypt one block of data. It MUST be at least 2, no greater than 4096, and a multiple of 2. - - - - - - - - - An unsigned integer that specifies the number of bits used by an encryption algorithm. It MUST be at least 8 and a multiple of 8. - - - - - - - - An unsigned integer that specifies the number of bytes used by a hash value. It MUST be at least 1, no greater than 65,536, and the same number of bytes as the hash algorithm emits. - - - - - - - - - An unsigned integer that specifies the number of times to iterate on a hash of a password. It MUST NOT be greater than 10,000,000. - - - - - - - - - modified for poi - list is restricted to given list in [ms-offcrypto] - A string that specifies the cipher algorithm. Values that are not defined MAY be used, and a compliant implementation is not required to support all defined values. Any algorithm that can be resolved by name by the underlying operating system can be used for hashing or encryption. Only block algorithms are supported for encryption. AES-128 is the default encryption algorithm, and SHA-1 is the default hashing algorithm if no other algorithms have been configured. - - - - - MUST conform to the AES algorithm. - - - - - MUST conform to the algorithm as specified in [RFC2268] (http://tools.ietf.org/html/rfc2268). The use of RC2 is not recommended. If RC2 is used with a key length of less than 128 bits, documents could interoperate incorrectly across different versions of Windows. - - - - - MUST NOT be used. - - - - - MUST conform to the DES algorithm. The use of DES is not recommended. If DES is used, the key length specified in the KeyBits element is required to be set to 64 for 56-bit encryption, and the key decrypted from encryptedKeyValue of KeyEncryptor is required to include the DES parity bits. - - - - - MUST conform to the algorithm as specified in [DRAFT-DESX] (http://tools.ietf.org/html/draft-ietf-ipsec-ciph-desx-00). The use of DESX is not recommended. If DESX is used, documents could interoperate incorrectly across different versions of Windows. - - - - - MUST conform to the algorithm as specified in [RFC1851] (http://tools.ietf.org/html/rfc1851). If 3DES or 3DES_112 is used, the key length specified in the KeyBits element is required to be set to 192 for 168-bit encryption and 128 for 112-bit encryption, and the key decrypted from encryptedKeyValue of KeyEncryptor is required to include the DES parity bits. - - - - - see 3DES - - - - - - - A string that specifies the chaining mode used by CipherAlgorithm. For more details about chaining modes, see [BCMO800-38A] (http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf). - - - - - block chaining (CBC) - - - - - Cipher feedback chaining (CFB), with an 8-bit window - - - - - - - modified for poi - list is restricted to given list in [ms-offcrypto] - A string specifying a hashing algorithm. Values that are not defined MAY be used, and a compliant implementation is not required to support all defined values. - - - - - MUST conform to the algorithm as specified in [RFC4634] (http://tools.ietf.org/html/rfc4634). - - - - - see SHA1 - - - - - see SHA1 - - - - - see SHA1 - - - - - MUST conform to MD5. - - - - - MUST conform to the algorithm as specified in [RFC1320] (http://tools.ietf.org/html/rfc1320). - - - - - MUST conform to the algorithm as specified in [RFC1319] (http://tools.ietf.org/html/rfc1319). - - - - - MUST conform to the hash functions specified in [ISO/IEC 10118]. (https://en.wikipedia.org/wiki/RIPEMD) - - - - - see RIPEMD-128 (https://en.wikipedia.org/wiki/RIPEMD) - - - - - see RIPEMD-128 (https://en.wikipedia.org/wiki/ISO/IEC_10118-3) - - - - - - - A complex type that specifies the encryption used within this element. The saltValue attribute is a base64-encoded binary value that is randomly generated. The number of bytes required to decode the saltValue attribute MUST be equal to the value of the saltSize attribute. - - - - - - - - - - - - - A complex type that specifies data used to verify whether the encrypted data passes an integrity check. It MUST be generated using the method specified in section 2.3.4.14 (http://msdn.microsoft.com/en-us/library/dd924068(v=office.12).aspx). - - - - A base64-encoded value that specifies an encrypted key used in calculating the encryptedHmacValue. - - - - - A base64-encoded value that specifies an HMAC derived from encryptedHmacKey and the encrypted data. - - - - - - modified for POI - A complex type that specifies the parameters used to encrypt an intermediate key, which is used to perform the final encryption of the document. To ensure extensibility, arbitrary elements can be defined to encrypt the intermediate key. The intermediate key MUST be the same for all KeyEncryptor elements. - - - - - - - - modified for POI - - - - - - - - - - - - A sequence of KeyEncryptor elements. Exactly one KeyEncryptors element MUST be present, and the KeyEncryptors element MUST contain at least one KeyEncryptor. - - - - - - - - - - - modified for POI - All ECMA-376 documents [ECMA-376] encrypted by Microsoft Office using agile encryption will have a DataIntegrity element present. The schema allows for a DataIntegrity element to not be present because the encryption schema can be used by applications that do not create ECMA-376 documents [ECMA-376]. - - - - - The KeyEncryptor element, which MUST be used when encrypting password-protected agile encryption documents, is either a PasswordKeyEncryptor or a CertificateKeyEncryptor. Exactly one PasswordKeyEncryptor MUST be present. Zero or more CertificateKeyEncryptor elements are contained within the KeyEncryptors element. - - - - - - diff --git a/src/ooxml/resources/org/apache/poi/poifs/crypt/encryptionInfo.xsdconfig b/src/ooxml/resources/org/apache/poi/poifs/crypt/encryptionInfo.xsdconfig deleted file mode 100644 index c9474a0f3..000000000 --- a/src/ooxml/resources/org/apache/poi/poifs/crypt/encryptionInfo.xsdconfig +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/src/ooxml/resources/org/apache/poi/poifs/crypt/encryptionPassword.xsd b/src/ooxml/resources/org/apache/poi/poifs/crypt/encryptionPassword.xsd deleted file mode 100644 index 79ae888a0..000000000 --- a/src/ooxml/resources/org/apache/poi/poifs/crypt/encryptionPassword.xsd +++ /dev/null @@ -1,66 +0,0 @@ - - - - - - - - - - - - A SaltSize that specifies the size of the salt for a PasswordKeyEncryptor. - - - A BlockSize that specifies the block size for a PasswordKeyEncryptor. - - - A KeyBits that specifies the number of bits for a PasswordKeyEncryptor. - - - A HashSize that specifies the size of the binary form of the hash for a PasswordKeyEncryptor. - - - A CipherAlgorithm that specifies the cipher algorithm for a PasswordKeyEncryptor. The cipher algorithm specified MUST be the same as the cipher algorithm specified for the Encryption.keyData element. - - - A CipherChaining that specifies the cipher chaining mode for a PasswordKeyEncryptor. - - - A HashAlgorithm that specifies the hashing algorithm for a PasswordKeyEncryptor. The hashing algorithm specified MUST be the same as the hashing algorithm specified for the Encryption.keyData element. - - - A base64-encoded binary byte array that specifies the salt value for a PasswordKeyEncryptor. The number of bytes required by the decoded form of this element MUST be saltSize. - - - A SpinCount that specifies the spin count for a PasswordKeyEncryptor. - - - A base64-encoded value that specifies the encrypted verifier hash input for a PasswordKeyEncryptor used in password verification. - - - A base64-encoded value that specifies the encrypted verifier hash value for a PasswordKeyEncryptor used in password verification. - - - A base64-encoded value that specifies the encrypted form of the intermediate key. - - - - diff --git a/src/ooxml/resources/org/apache/poi/poifs/crypt/encryptionPassword.xsdconfig b/src/ooxml/resources/org/apache/poi/poifs/crypt/encryptionPassword.xsdconfig deleted file mode 100644 index 3a2bb2c8e..000000000 --- a/src/ooxml/resources/org/apache/poi/poifs/crypt/encryptionPassword.xsdconfig +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/src/ooxml/resources/org/apache/poi/poifs/crypt/signatureInfo.xsd b/src/ooxml/resources/org/apache/poi/poifs/crypt/signatureInfo.xsd deleted file mode 100644 index f7019f13f..000000000 --- a/src/ooxml/resources/org/apache/poi/poifs/crypt/signatureInfo.xsd +++ /dev/null @@ -1,103 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/ooxml/resources/org/apache/poi/schemas/ooxmlSchemas.xsdconfig b/src/ooxml/resources/org/apache/poi/schemas/ooxmlSchemas.xsdconfig deleted file mode 100644 index 3121e451d..000000000 --- a/src/ooxml/resources/org/apache/poi/schemas/ooxmlSchemas.xsdconfig +++ /dev/null @@ -1,42 +0,0 @@ - - - - - - com.microsoft.schemas.office.office - - - - com.microsoft.schemas.office.excel - - - - com.microsoft.schemas.office.word - - - - com.microsoft.schemas.office.powerpoint - - - - com.microsoft.schemas.vml - - - \ No newline at end of file diff --git a/src/ooxml/resources/org/apache/poi/xdgf/visio.xsd b/src/ooxml/resources/org/apache/poi/xdgf/visio.xsd deleted file mode 100644 index eec0b68c0..000000000 --- a/src/ooxml/resources/org/apache/poi/xdgf/visio.xsd +++ /dev/null @@ -1,829 +0,0 @@ - - - - - - - - Permission to copy, display and distribute the contents of this document (the - "Specification"), in any medium for any purpose without fee or royalty is - hereby granted, provided that you include the following notice on ALL copies of - the Specification, or portions thereof, that you make: - Copyright (c) Microsoft Corporation. All rights reserved. Permission to copy, - display and distribute this document is available at: - http://msdn.microsoft.com/library/en-us/odcXMLRef/html/odcXMLRefLegalNotice.asp?frame=true. - No right to create modifications or derivatives of this Specification is - granted herein. There is a separate patent license available to parties - interested in implementing software programs that can read and write files that - conform to the Specification. This patent license is available at this - location: http://www.microsoft.com/mscorp/ip/format/xmlpatentlicense.asp. - THE SPECIFICATION IS PROVIDED "AS IS" AND MICROSOFT MAKES NO REPRESENTATIONS OR - WARRANTIES, EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, OR TITLE; - THAT THE CONTENTS OF THE SPECIFICATION ARE SUITABLE FOR ANY PURPOSE; NOR THAT - THE IMPLEMENTATION OF SUCH CONTENTS WILL NOT INFRINGE ANY THIRD PARTY PATENTS, - COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. MICROSOFT WILL NOT BE LIABLE FOR ANY - DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF - OR RELATING TO ANY USE OR DISTRIBUTION OF THE SPECIFICATION. - The name and trademarks of Microsoft may NOT be used in any manner, including - advertising or publicity pertaining to the Specification or its contents - without specific, written prior permission. Title to copyright in the - Specification will at all times remain with Microsoft. No other rights are - granted by implication, estoppel or otherwise. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/TestDetectAsOOXML.java b/src/ooxml/testcases/org/apache/poi/TestDetectAsOOXML.java deleted file mode 100644 index 137f631b5..000000000 --- a/src/ooxml/testcases/org/apache/poi/TestDetectAsOOXML.java +++ /dev/null @@ -1,87 +0,0 @@ - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - - -package org.apache.poi; - -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.io.PushbackInputStream; -import java.util.Arrays; - -import junit.framework.TestCase; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.poifs.filesystem.DocumentFactoryHelper; - -/** - * Class to test that HXF correctly detects OOXML - * documents - */ -public class TestDetectAsOOXML extends TestCase -{ - public void testOpensProperly() throws Exception - { - OPCPackage.open(HSSFTestDataSamples.openSampleFileStream("sample.xlsx")); - } - - public void testDetectAsPOIFS() throws Exception { - InputStream in; - - // ooxml file is - in = new PushbackInputStream( - HSSFTestDataSamples.openSampleFileStream("SampleSS.xlsx"), 10 - ); - assertTrue(DocumentFactoryHelper.hasOOXMLHeader(in)); - in.close(); - - // xls file isn't - in = new PushbackInputStream( - HSSFTestDataSamples.openSampleFileStream("SampleSS.xls"), 10 - ); - assertFalse(DocumentFactoryHelper.hasOOXMLHeader(in)); - in.close(); - - // text file isn't - in = new PushbackInputStream( - HSSFTestDataSamples.openSampleFileStream("SampleSS.txt"), 10 - ); - assertFalse(DocumentFactoryHelper.hasOOXMLHeader(in)); - in.close(); - } - - public void testFileCorruption() throws Exception { - - // create test InputStream - byte[] testData = { (byte)1, (byte)2, (byte)3 }; - ByteArrayInputStream testInput = new ByteArrayInputStream(testData); - - // detect header - InputStream in = new PushbackInputStream(testInput, 10); - assertFalse(DocumentFactoryHelper.hasOOXMLHeader(in)); - //noinspection deprecation - assertFalse(POIXMLDocument.hasOOXMLHeader(in)); - - // check if InputStream is still intact - byte[] test = new byte[3]; - assertEquals(3, in.read(test)); - assertTrue(Arrays.equals(testData, test)); - assertEquals(-1, in.read()); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/TestEmbeded.java b/src/ooxml/testcases/org/apache/poi/TestEmbeded.java deleted file mode 100644 index fb16b8a0e..000000000 --- a/src/ooxml/testcases/org/apache/poi/TestEmbeded.java +++ /dev/null @@ -1,70 +0,0 @@ - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - - -package org.apache.poi; - -import org.apache.poi.util.IOUtils; -import org.apache.poi.xslf.usermodel.XSLFSlideShow; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.apache.poi.xwpf.usermodel.XWPFDocument; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackagePart; - -import junit.framework.TestCase; - -/** - * Class to test that we handle embeded bits in - * OOXML files properly - */ -public class TestEmbeded extends TestCase -{ - public void testExcel() throws Exception { - POIXMLDocument doc = new XSSFWorkbook( - POIDataSamples.getSpreadSheetInstance().openResourceAsStream("ExcelWithAttachments.xlsm") - ); - test(doc, 4); - } - - public void testWord() throws Exception { - POIXMLDocument doc = new XWPFDocument( - POIDataSamples.getDocumentInstance().openResourceAsStream("WordWithAttachments.docx") - ); - test(doc, 5); - } - - public void testPowerPoint() throws Exception { - POIXMLDocument doc = new XSLFSlideShow(OPCPackage.open( - POIDataSamples.getSlideShowInstance().openResourceAsStream("PPTWithAttachments.pptm")) - ); - test(doc, 4); - } - - private void test(POIXMLDocument doc, int expectedCount) throws Exception { - assertNotNull(doc.getAllEmbedds()); - assertEquals(expectedCount, doc.getAllEmbedds().size()); - - for(int i=0; i 0); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/TestPOIXMLDocument.java b/src/ooxml/testcases/org/apache/poi/TestPOIXMLDocument.java deleted file mode 100644 index 432e9f093..000000000 --- a/src/ooxml/testcases/org/apache/poi/TestPOIXMLDocument.java +++ /dev/null @@ -1,359 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.fail; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.InvocationTargetException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; - -import org.apache.poi.POIXMLDocumentPart.RelationPart; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.exceptions.OpenXML4JRuntimeException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.opc.PackageRelationshipTypes; -import org.apache.poi.util.NullOutputStream; -import org.apache.poi.util.PackageHelper; -import org.apache.poi.util.TempFile; -import org.apache.poi.xslf.usermodel.XMLSlideShow; -import org.apache.poi.xssf.usermodel.XSSFRelation; -import org.apache.poi.xwpf.usermodel.XWPFRelation; -import org.junit.Test; - -/** - * Test recursive read and write of OPC packages - */ -public final class TestPOIXMLDocument { - - private static class OPCParser extends POIXMLDocument { - - public OPCParser(OPCPackage pkg) { - super(pkg); - } - - public OPCParser(OPCPackage pkg, String coreDocumentRel) { - super(pkg, coreDocumentRel); - } - - @Override - public List getAllEmbedds() { - throw new RuntimeException("not supported"); - } - - public void parse(POIXMLFactory factory) throws IOException{ - load(factory); - } - } - - private static final class TestFactory extends POIXMLFactory { - - public TestFactory() { - // - } - - @Override - protected POIXMLRelation getDescriptor(String relationshipType) { - return null; - } - - /** - * @since POI 3.14-Beta1 - */ - @Override - protected POIXMLDocumentPart createDocumentPart - (Class cls, Class[] classes, Object[] values) - throws SecurityException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { - return null; - } - } - - private static void traverse(POIXMLDocument doc) throws IOException{ - HashMap context = new HashMap(); - for (RelationPart p : doc.getRelationParts()){ - traverse(p, context); - } - } - - /** - * Recursively traverse a OOXML document and assert that same logical parts have the same physical instances - */ - private static void traverse(RelationPart rp, HashMap context) throws IOException{ - POIXMLDocumentPart dp = rp.getDocumentPart(); - assertEquals(rp.getRelationship().getTargetURI().toString(), dp.getPackagePart().getPartName().getName()); - - context.put(dp.getPackagePart().getPartName().getName(), dp); - for(RelationPart p : dp.getRelationParts()){ - assertNotNull(p.getRelationship().toString()); - - String uri = p.getDocumentPart().getPackagePart().getPartName().getURI().toString(); - assertEquals(uri, p.getRelationship().getTargetURI().toString()); - if (!context.containsKey(uri)) { - traverse(p, context); - } else { - POIXMLDocumentPart prev = context.get(uri); - assertSame("Duplicate POIXMLDocumentPart instance for targetURI=" + uri, prev, p.getDocumentPart()); - } - } - } - - public void assertReadWrite(OPCPackage pkg1) throws Exception { - - OPCParser doc = new OPCParser(pkg1); - doc.parse(new TestFactory()); - - traverse(doc); - - File tmp = TempFile.createTempFile("poi-ooxml", ".tmp"); - FileOutputStream out = new FileOutputStream(tmp); - doc.write(out); - out.close(); - - // Should not be able to write to an output stream that has been closed - try { - doc.write(out); - fail("Should not be able to write to an output stream that has been closed."); - } catch (final OpenXML4JRuntimeException e) { - // FIXME: A better exception class (IOException?) and message should be raised - // indicating that the document could not be written because the output stream is closed. - // see {@link org.apache.poi.openxml4j.opc.ZipPackage#saveImpl(java.io.OutputStream)} - if (e.getMessage().matches("Fail to save: an error occurs while saving the package : The part .+ failed to be saved in the stream with marshaller .+")) { - // expected - } else { - throw e; - } - } - - // Should not be able to write a document that has been closed - doc.close(); - try { - doc.write(new NullOutputStream()); - fail("Should not be able to write a document that has been closed."); - } catch (final IOException e) { - if (e.getMessage().equals("Cannot write data, document seems to have been closed already")) { - // expected - } else { - throw e; - } - } - - // Should be able to close a document multiple times, though subsequent closes will have no effect. - doc.close(); - - - @SuppressWarnings("resource") - OPCPackage pkg2 = OPCPackage.open(tmp.getAbsolutePath()); - doc = new OPCParser(pkg1); - try { - doc.parse(new TestFactory()); - traverse(doc); - - assertEquals(pkg1.getRelationships().size(), pkg2.getRelationships().size()); - - ArrayList l1 = pkg1.getParts(); - ArrayList l2 = pkg2.getParts(); - - assertEquals(l1.size(), l2.size()); - for (int i=0; i < l1.size(); i++){ - PackagePart p1 = l1.get(i); - PackagePart p2 = l2.get(i); - - assertEquals(p1.getContentType(), p2.getContentType()); - assertEquals(p1.hasRelationships(), p2.hasRelationships()); - if(p1.hasRelationships()){ - assertEquals(p1.getRelationships().size(), p2.getRelationships().size()); - } - assertEquals(p1.getPartName(), p2.getPartName()); - } - } finally { - doc.close(); - pkg1.close(); - pkg2.close(); - } - } - - @Test - public void testPPTX() throws Exception { - POIDataSamples pds = POIDataSamples.getSlideShowInstance(); - assertReadWrite(PackageHelper.open(pds.openResourceAsStream("PPTWithAttachments.pptm"))); - } - - @Test - public void testXLSX() throws Exception { - POIDataSamples pds = POIDataSamples.getSpreadSheetInstance(); - assertReadWrite(PackageHelper.open(pds.openResourceAsStream("ExcelWithAttachments.xlsm"))); - } - - @Test - public void testDOCX() throws Exception { - POIDataSamples pds = POIDataSamples.getDocumentInstance(); - assertReadWrite(PackageHelper.open(pds.openResourceAsStream("WordWithAttachments.docx"))); - } - - @Test - public void testRelationOrder() throws Exception { - POIDataSamples pds = POIDataSamples.getDocumentInstance(); - @SuppressWarnings("resource") - OPCPackage pkg = PackageHelper.open(pds.openResourceAsStream("WordWithAttachments.docx")); - OPCParser doc = new OPCParser(pkg); - try { - doc.parse(new TestFactory()); - - for(POIXMLDocumentPart rel : doc.getRelations()){ - //TODO finish me - assertNotNull(rel); - } - } finally { - doc.close(); - } - } - - @Test - public void testGetNextPartNumber() throws Exception { - POIDataSamples pds = POIDataSamples.getDocumentInstance(); - @SuppressWarnings("resource") - OPCPackage pkg = PackageHelper.open(pds.openResourceAsStream("WordWithAttachments.docx")); - OPCParser doc = new OPCParser(pkg); - try { - doc.parse(new TestFactory()); - - // Non-indexed parts: Word is taken, Excel is not - assertEquals(-1, doc.getNextPartNumber(XWPFRelation.DOCUMENT, 0)); - assertEquals(-1, doc.getNextPartNumber(XWPFRelation.DOCUMENT, -1)); - assertEquals(-1, doc.getNextPartNumber(XWPFRelation.DOCUMENT, 99)); - assertEquals(0, doc.getNextPartNumber(XSSFRelation.WORKBOOK, 0)); - assertEquals(0, doc.getNextPartNumber(XSSFRelation.WORKBOOK, -1)); - assertEquals(0, doc.getNextPartNumber(XSSFRelation.WORKBOOK, 99)); - - // Indexed parts: - // Has 2 headers - assertEquals(0, doc.getNextPartNumber(XWPFRelation.HEADER, 0)); - assertEquals(3, doc.getNextPartNumber(XWPFRelation.HEADER, -1)); - assertEquals(3, doc.getNextPartNumber(XWPFRelation.HEADER, 1)); - assertEquals(8, doc.getNextPartNumber(XWPFRelation.HEADER, 8)); - - // Has no Excel Sheets - assertEquals(0, doc.getNextPartNumber(XSSFRelation.WORKSHEET, 0)); - assertEquals(1, doc.getNextPartNumber(XSSFRelation.WORKSHEET, -1)); - assertEquals(1, doc.getNextPartNumber(XSSFRelation.WORKSHEET, 1)); - } finally { - doc.close(); - } - } - - @Test - public void testCommitNullPart() throws IOException, InvalidFormatException { - POIXMLDocumentPart part = new POIXMLDocumentPart(); - part.prepareForCommit(); - part.commit(); - part.onSave(new HashSet()); - - assertNull(part.getRelationById(null)); - assertNull(part.getRelationId(null)); - assertFalse(part.removeRelation(null, true)); - part.removeRelation(null); - assertEquals("",part.toString()); - part.onDocumentCreate(); - //part.getTargetPart(null); - } - - @Test - public void testVSDX() throws Exception { - POIDataSamples pds = POIDataSamples.getDiagramInstance(); - @SuppressWarnings("resource") - OPCPackage open = PackageHelper.open(pds.openResourceAsStream("test.vsdx")); - POIXMLDocument part = new OPCParser(open, PackageRelationshipTypes.VISIO_CORE_DOCUMENT); - - assertNotNull(part); - assertEquals(0, part.getRelationCounter()); - part.close(); - } - - @Test - public void testVSDXPart() throws IOException { - POIDataSamples pds = POIDataSamples.getDiagramInstance(); - OPCPackage open = PackageHelper.open(pds.openResourceAsStream("test.vsdx")); - - POIXMLDocumentPart part = new POIXMLDocumentPart(open, PackageRelationshipTypes.VISIO_CORE_DOCUMENT); - - assertNotNull(part); - assertEquals(0, part.getRelationCounter()); - - open.close(); - } - - @Test(expected=POIXMLException.class) - public void testInvalidCoreRel() throws IOException { - POIDataSamples pds = POIDataSamples.getDiagramInstance(); - OPCPackage open = PackageHelper.open(pds.openResourceAsStream("test.vsdx")); - - try { - new POIXMLDocumentPart(open, "somethingillegal"); - } finally { - open.close(); - } - } - - @Test(expected=IllegalStateException.class) - public void testOSGIClassLoadingAsIs() throws IOException { - Thread thread = Thread.currentThread(); - ClassLoader cl = thread.getContextClassLoader(); - InputStream is = POIDataSamples.getSlideShowInstance().openResourceAsStream("table_test.pptx"); - try { - thread.setContextClassLoader(cl.getParent()); - XMLSlideShow ppt = new XMLSlideShow(is); - ppt.getSlides().get(0).getShapes(); - ppt.close(); - } finally { - thread.setContextClassLoader(cl); - is.close(); - } - } - - - @Test - public void testOSGIClassLoadingFixed() throws IOException { - Thread thread = Thread.currentThread(); - ClassLoader cl = thread.getContextClassLoader(); - InputStream is = POIDataSamples.getSlideShowInstance().openResourceAsStream("table_test.pptx"); - try { - thread.setContextClassLoader(cl.getParent()); - POIXMLTypeLoader.setClassLoader(cl); - XMLSlideShow ppt = new XMLSlideShow(is); - ppt.getSlides().get(0).getShapes(); - ppt.close(); - } finally { - thread.setContextClassLoader(cl); - POIXMLTypeLoader.setClassLoader(null); - is.close(); - } - } - -} diff --git a/src/ooxml/testcases/org/apache/poi/TestPOIXMLProperties.java b/src/ooxml/testcases/org/apache/poi/TestPOIXMLProperties.java deleted file mode 100644 index 86732836a..000000000 --- a/src/ooxml/testcases/org/apache/poi/TestPOIXMLProperties.java +++ /dev/null @@ -1,268 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.util.Calendar; -import java.util.Date; - -import org.apache.poi.POIXMLProperties.CoreProperties; -import org.apache.poi.openxml4j.util.Nullable; -import org.apache.poi.util.LocaleUtil; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.apache.poi.xwpf.usermodel.XWPFDocument; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -/** - * Test setting extended and custom OOXML properties - */ -public final class TestPOIXMLProperties { - private XWPFDocument sampleDoc; - private XWPFDocument sampleNoThumb; - private POIXMLProperties _props; - private CoreProperties _coreProperties; - - @Before - public void setUp() throws IOException { - sampleDoc = XWPFTestDataSamples.openSampleDocument("documentProperties.docx"); - sampleNoThumb = XWPFTestDataSamples.openSampleDocument("SampleDoc.docx"); - assertNotNull(sampleDoc); - assertNotNull(sampleNoThumb); - _props = sampleDoc.getProperties(); - _coreProperties = _props.getCoreProperties(); - assertNotNull(_props); - } - - @After - public void closeResources() throws Exception { - sampleDoc.close(); - sampleNoThumb.close(); - } - - @Test - public void testWorkbookExtendedProperties() throws Exception { - XSSFWorkbook workbook = new XSSFWorkbook(); - POIXMLProperties props = workbook.getProperties(); - assertNotNull(props); - - org.apache.poi.POIXMLProperties.ExtendedProperties properties = - props.getExtendedProperties(); - - org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.CTProperties - ctProps = properties.getUnderlyingProperties(); - - - String appVersion = "3.5 beta"; - String application = "POI"; - - ctProps.setApplication(application); - ctProps.setAppVersion(appVersion); - - XSSFWorkbook newWorkbook = - XSSFTestDataSamples.writeOutAndReadBack(workbook); - workbook.close(); - assertTrue(workbook != newWorkbook); - - - POIXMLProperties newProps = newWorkbook.getProperties(); - assertNotNull(newProps); - org.apache.poi.POIXMLProperties.ExtendedProperties newProperties = - newProps.getExtendedProperties(); - - assertEquals(application, newProperties.getApplication()); - assertEquals(appVersion, newProperties.getAppVersion()); - - org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.CTProperties - newCtProps = newProperties.getUnderlyingProperties(); - - assertEquals(application, newCtProps.getApplication()); - assertEquals(appVersion, newCtProps.getAppVersion()); - - newWorkbook.close(); - } - - - /** - * Test usermodel API for setting custom properties - */ - @Test - public void testCustomProperties() throws Exception { - POIXMLDocument wb1 = new XSSFWorkbook(); - - POIXMLProperties.CustomProperties customProps = wb1.getProperties().getCustomProperties(); - customProps.addProperty("test-1", "string val"); - customProps.addProperty("test-2", 1974); - customProps.addProperty("test-3", 36.6); - //adding a duplicate - try { - customProps.addProperty("test-3", 36.6); - fail("expected exception"); - } catch(IllegalArgumentException e){ - assertEquals("A property with this name already exists in the custom properties", e.getMessage()); - } - customProps.addProperty("test-4", true); - - POIXMLDocument wb2 = XSSFTestDataSamples.writeOutAndReadBack((XSSFWorkbook)wb1); - wb1.close(); - org.openxmlformats.schemas.officeDocument.x2006.customProperties.CTProperties ctProps = - wb2.getProperties().getCustomProperties().getUnderlyingProperties(); - assertEquals(4, ctProps.sizeOfPropertyArray()); - org.openxmlformats.schemas.officeDocument.x2006.customProperties.CTProperty p; - - p = ctProps.getPropertyArray(0); - assertEquals("{D5CDD505-2E9C-101B-9397-08002B2CF9AE}", p.getFmtid()); - assertEquals("test-1", p.getName()); - assertEquals("string val", p.getLpwstr()); - assertEquals(2, p.getPid()); - - p = ctProps.getPropertyArray(1); - assertEquals("{D5CDD505-2E9C-101B-9397-08002B2CF9AE}", p.getFmtid()); - assertEquals("test-2", p.getName()); - assertEquals(1974, p.getI4()); - assertEquals(3, p.getPid()); - - p = ctProps.getPropertyArray(2); - assertEquals("{D5CDD505-2E9C-101B-9397-08002B2CF9AE}", p.getFmtid()); - assertEquals("test-3", p.getName()); - assertEquals(36.6, p.getR8(), 0); - assertEquals(4, p.getPid()); - - p = ctProps.getPropertyArray(3); - assertEquals("{D5CDD505-2E9C-101B-9397-08002B2CF9AE}", p.getFmtid()); - assertEquals("test-4", p.getName()); - assertEquals(true, p.getBool()); - assertEquals(5, p.getPid()); - - wb2.close(); - } - - @Test - public void testDocumentProperties() { - String category = _coreProperties.getCategory(); - assertEquals("test", category); - String contentStatus = "Draft"; - _coreProperties.setContentStatus(contentStatus); - assertEquals("Draft", contentStatus); - Date created = _coreProperties.getCreated(); - // the original file contains a following value: 2009-07-20T13:12:00Z - assertTrue(dateTimeEqualToUTCString(created, "2009-07-20T13:12:00Z")); - String creator = _coreProperties.getCreator(); - assertEquals("Paolo Mottadelli", creator); - String subject = _coreProperties.getSubject(); - assertEquals("Greetings", subject); - String title = _coreProperties.getTitle(); - assertEquals("Hello World", title); - } - - @Test - public void testTransitiveSetters() throws IOException { - XWPFDocument doc = new XWPFDocument(); - CoreProperties cp = doc.getProperties().getCoreProperties(); - - - Date dateCreated = LocaleUtil.getLocaleCalendar(2010, 6, 15, 10, 0, 0).getTime(); - cp.setCreated(new Nullable(dateCreated)); - assertEquals(dateCreated, cp.getCreated()); - - XWPFDocument doc2 = XWPFTestDataSamples.writeOutAndReadBack(doc); - doc.close(); - cp = doc2.getProperties().getCoreProperties(); - Date dt3 = cp.getCreated(); - assertEquals(dateCreated, dt3); - doc2.close(); - } - - @Test - public void testGetSetRevision() { - String revision = _coreProperties.getRevision(); - assertTrue("Revision number is 1", Integer.parseInt(revision) > 1); - _coreProperties.setRevision("20"); - assertEquals("20", _coreProperties.getRevision()); - _coreProperties.setRevision("20xx"); - assertEquals("20", _coreProperties.getRevision()); - } - - @Test - public void testLastModifiedByUserProperty() { - String lastModifiedByUser = _coreProperties.getLastModifiedByUser(); - assertEquals("Paolo Mottadelli", lastModifiedByUser); - _coreProperties.setLastModifiedByUser("Test User"); - assertEquals("Test User", _coreProperties.getLastModifiedByUser()); - } - - public static boolean dateTimeEqualToUTCString(Date dateTime, String utcString) { - Calendar utcCalendar = LocaleUtil.getLocaleCalendar(LocaleUtil.TIMEZONE_UTC); - utcCalendar.setTimeInMillis(dateTime.getTime()); - String dateTimeUtcString = utcCalendar.get(Calendar.YEAR) + "-" + - zeroPad((utcCalendar.get(Calendar.MONTH)+1)) + "-" + - zeroPad(utcCalendar.get(Calendar.DAY_OF_MONTH)) + "T" + - zeroPad(utcCalendar.get(Calendar.HOUR_OF_DAY)) + ":" + - zeroPad(utcCalendar.get(Calendar.MINUTE)) + ":" + - zeroPad(utcCalendar.get(Calendar.SECOND)) + "Z"; - - return utcString.equals(dateTimeUtcString); - } - - public void testThumbnails() throws Exception { - POIXMLProperties noThumbProps = sampleNoThumb.getProperties(); - - assertNotNull(_props.getThumbnailPart()); - assertNull(noThumbProps.getThumbnailPart()); - - assertNotNull(_props.getThumbnailFilename()); - assertNull(noThumbProps.getThumbnailFilename()); - - assertNotNull(_props.getThumbnailImage()); - assertNull(noThumbProps.getThumbnailImage()); - - assertEquals("thumbnail.jpeg", _props.getThumbnailFilename()); - - - // Adding / changing - noThumbProps.setThumbnail("Testing.png", new ByteArrayInputStream(new byte[1])); - assertNotNull(noThumbProps.getThumbnailPart()); - assertEquals("Testing.png", noThumbProps.getThumbnailFilename()); - assertNotNull(noThumbProps.getThumbnailImage()); - assertEquals(1, noThumbProps.getThumbnailImage().available()); - - noThumbProps.setThumbnail("Testing2.png", new ByteArrayInputStream(new byte[2])); - assertNotNull(noThumbProps.getThumbnailPart()); - assertEquals("Testing.png", noThumbProps.getThumbnailFilename()); - assertNotNull(noThumbProps.getThumbnailImage()); - assertEquals(2, noThumbProps.getThumbnailImage().available()); - } - - private static String zeroPad(long i) { - if (i >= 0 && i <=9) { - return "0" + i; - } else { - return String.valueOf(i); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/TestXMLPropertiesTextExtractor.java b/src/ooxml/testcases/org/apache/poi/TestXMLPropertiesTextExtractor.java deleted file mode 100644 index 9ba1333c3..000000000 --- a/src/ooxml/testcases/org/apache/poi/TestXMLPropertiesTextExtractor.java +++ /dev/null @@ -1,133 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi; - -import junit.framework.TestCase; - -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.util.PackageHelper; -import org.apache.poi.xslf.usermodel.XSLFSlideShow; -import org.apache.poi.xssf.extractor.XSSFExcelExtractor; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -public final class TestXMLPropertiesTextExtractor extends TestCase { - private static final POIDataSamples _ssSamples = POIDataSamples.getSpreadSheetInstance(); - private static final POIDataSamples _slSamples = POIDataSamples.getSlideShowInstance(); - - public void testGetFromMainExtractor() throws Exception { - OPCPackage pkg = PackageHelper.open(_ssSamples.openResourceAsStream("ExcelWithAttachments.xlsm")); - - XSSFWorkbook wb = new XSSFWorkbook(pkg); - - XSSFExcelExtractor ext = new XSSFExcelExtractor(wb); - POIXMLPropertiesTextExtractor textExt = ext.getMetadataTextExtractor(); - - // Check basics - assertNotNull(textExt); - assertTrue(textExt.getText().length() > 0); - - // Check some of the content - String text = textExt.getText(); - String cText = textExt.getCorePropertiesText(); - - assertTrue(text.contains("LastModifiedBy = Yury Batrakov")); - assertTrue(cText.contains("LastModifiedBy = Yury Batrakov")); - - textExt.close(); - ext.close(); - } - - public void testCore() throws Exception { - OPCPackage pkg = PackageHelper.open( - _ssSamples.openResourceAsStream("ExcelWithAttachments.xlsm") - ); - XSSFWorkbook wb = new XSSFWorkbook(pkg); - - POIXMLPropertiesTextExtractor ext = new POIXMLPropertiesTextExtractor(wb); - ext.getText(); - - // Now check - String text = ext.getText(); - String cText = ext.getCorePropertiesText(); - - assertTrue(text.contains("LastModifiedBy = Yury Batrakov")); - assertTrue(cText.contains("LastModifiedBy = Yury Batrakov")); - - ext.close(); - } - - public void testExtended() throws Exception { - OPCPackage pkg = OPCPackage.open( - _ssSamples.openResourceAsStream("ExcelWithAttachments.xlsm") - ); - XSSFWorkbook wb = new XSSFWorkbook(pkg); - - POIXMLPropertiesTextExtractor ext = new POIXMLPropertiesTextExtractor(wb); - ext.getText(); - - // Now check - String text = ext.getText(); - String eText = ext.getExtendedPropertiesText(); - - assertTrue(text.contains("Application = Microsoft Excel")); - assertTrue(text.contains("Company = Mera")); - assertTrue(eText.contains("Application = Microsoft Excel")); - assertTrue(eText.contains("Company = Mera")); - - ext.close(); - } - - public void testCustom() throws Exception { - OPCPackage pkg = OPCPackage.open( - _ssSamples.openResourceAsStream("ExcelWithAttachments.xlsm") - ); - XSSFWorkbook wb = new XSSFWorkbook(pkg); - - POIXMLPropertiesTextExtractor ext = new POIXMLPropertiesTextExtractor(wb); - ext.getText(); - - // Now check - String text = ext.getText(); - String cText = ext.getCustomPropertiesText(); - - assertTrue(text.contains("description = another value")); - assertTrue(cText.contains("description = another value")); - - ext.close(); - } - - /** - * Bug #49386 - some properties, especially - * dates can be null - */ - public void testWithSomeNulls() throws Exception { - OPCPackage pkg = OPCPackage.open( - _slSamples.openResourceAsStream("49386-null_dates.pptx") - ); - XSLFSlideShow sl = new XSLFSlideShow(pkg); - - POIXMLPropertiesTextExtractor ext = new POIXMLPropertiesTextExtractor(sl); - ext.getText(); - - String text = ext.getText(); - assertFalse(text.contains("Created =")); // With date is null - assertTrue(text.contains("CreatedString = ")); // Via string is blank - assertTrue(text.contains("LastModifiedBy = IT Client Services")); - - ext.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/dev/TestOOXMLLister.java b/src/ooxml/testcases/org/apache/poi/dev/TestOOXMLLister.java deleted file mode 100644 index cb883c876..000000000 --- a/src/ooxml/testcases/org/apache/poi/dev/TestOOXMLLister.java +++ /dev/null @@ -1,53 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - - 2012 - Alfresco Software, Ltd. - Alfresco Software has modified source of this file - The details of changes as svn diff can be found in svn at location root/projects/3rd-party/src -==================================================================== */ -package org.apache.poi.dev; - -import java.io.File; -import java.io.IOException; -import java.io.PrintStream; - -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackageAccess; -import org.apache.poi.util.NullOutputStream; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.Test; - -public class TestOOXMLLister { - @Test - public void testMain() throws IOException, InvalidFormatException { - File file = XSSFTestDataSamples.getSampleFile("Formatting.xlsx"); - OOXMLLister.main(new String[] {file.getAbsolutePath()}); - } - - @Test - public void testWithPrintStream() throws IOException, InvalidFormatException { - File file = XSSFTestDataSamples.getSampleFile("Formatting.xlsx"); - PrintStream nullStream = new PrintStream(new NullOutputStream(), true, "UTF-8"); - OPCPackage opc = OPCPackage.open(file.getAbsolutePath(), PackageAccess.READ); - OOXMLLister lister = new OOXMLLister(opc, nullStream); - lister.displayParts(); - lister.displayRelations(); - lister.close(); - opc.close(); - nullStream.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/dev/TestOOXMLPrettyPrint.java b/src/ooxml/testcases/org/apache/poi/dev/TestOOXMLPrettyPrint.java deleted file mode 100644 index edc0bdd7d..000000000 --- a/src/ooxml/testcases/org/apache/poi/dev/TestOOXMLPrettyPrint.java +++ /dev/null @@ -1,48 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - - 2012 - Alfresco Software, Ltd. - Alfresco Software has modified source of this file - The details of changes as svn diff can be found in svn at location root/projects/3rd-party/src -==================================================================== */ -package org.apache.poi.dev; - -import org.apache.poi.util.TempFile; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.Test; - -import java.io.File; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -public class TestOOXMLPrettyPrint { - @Test - public void testMain() throws Exception { - File file = XSSFTestDataSamples.getSampleFile("Formatting.xlsx"); - File outFile = TempFile.createTempFile("Formatting", "-pretty.xlsx"); - - assertTrue(outFile.delete()); - assertFalse(outFile.exists()); - - OOXMLPrettyPrint.main(new String[] { - file.getAbsolutePath(), outFile.getAbsolutePath() - }); - - assertTrue(outFile.exists()); - assertTrue(outFile.delete()); - } -} \ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/dev/TestRecordGenerator.java b/src/ooxml/testcases/org/apache/poi/dev/TestRecordGenerator.java deleted file mode 100644 index 84de1f844..000000000 --- a/src/ooxml/testcases/org/apache/poi/dev/TestRecordGenerator.java +++ /dev/null @@ -1,61 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - - 2012 - Alfresco Software, Ltd. - Alfresco Software has modified source of this file - The details of changes as svn diff can be found in svn at location root/projects/3rd-party/src -==================================================================== */ -package org.apache.poi.dev; - -import org.apache.poi.util.TempFile; -import org.junit.Ignore; -import org.junit.Test; - -import java.io.File; - -public class TestRecordGenerator { - @Ignore("Could not get this to run, probably the dev-application does not work any more at all") - @Test - public void testNotEnoughArgs() throws Exception { - RecordGenerator.main(new String[] {}); - } - - @Ignore("Could not get this to run, probably the dev-application does not work any more at all") - @Test - public void testMainRecords() throws Exception { - File dir = TempFile.createTempDirectory("TestRecordGenerator"); - - RecordGenerator.main(new String[] { - "src/records/definitions/", - "src/records/styles/", - dir.getAbsolutePath(), - dir.getAbsolutePath(), - }); - } - - @Ignore("Could not get this to run, probably the dev-application does not work any more at all") - @Test - public void testMainTypes() throws Exception { - File dir = TempFile.createTempDirectory("TestRecordGenerator"); - - RecordGenerator.main(new String[] { - "src/types/definitions/", - "src/types/styles/", - dir.getAbsolutePath(), - dir.getAbsolutePath(), - }); - } -} \ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/extractor/TestExtractorFactory.java b/src/ooxml/testcases/org/apache/poi/extractor/TestExtractorFactory.java deleted file mode 100644 index ec0b14b1e..000000000 --- a/src/ooxml/testcases/org/apache/poi/extractor/TestExtractorFactory.java +++ /dev/null @@ -1,1043 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.extractor; - -import static org.apache.poi.POITestCase.assertContains; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.POIOLE2TextExtractor; -import org.apache.poi.POITextExtractor; -import org.apache.poi.POIXMLException; -import org.apache.poi.POIXMLTextExtractor; -import org.apache.poi.UnsupportedFileFormatException; -import org.apache.poi.hdgf.extractor.VisioTextExtractor; -import org.apache.poi.hpbf.extractor.PublisherTextExtractor; -import org.apache.poi.hslf.extractor.PowerPointExtractor; -import org.apache.poi.hsmf.extractor.OutlookTextExtactor; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.OldExcelFormatException; -import org.apache.poi.hssf.extractor.EventBasedExcelExtractor; -import org.apache.poi.hssf.extractor.ExcelExtractor; -import org.apache.poi.hwpf.extractor.Word6Extractor; -import org.apache.poi.hwpf.extractor.WordExtractor; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackageAccess; -import org.apache.poi.poifs.filesystem.OPOIFSFileSystem; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.util.IOUtils; -import org.apache.poi.xdgf.extractor.XDGFVisioExtractor; -import org.apache.poi.xslf.extractor.XSLFPowerPointExtractor; -import org.apache.poi.xssf.extractor.XSSFEventBasedExcelExtractor; -import org.apache.poi.xssf.extractor.XSSFExcelExtractor; -import org.apache.poi.xwpf.extractor.XWPFWordExtractor; -import org.junit.BeforeClass; -import org.junit.Test; - -/** - * Test that the extractor factory plays nicely - */ -public class TestExtractorFactory { - private static File txt; - - private static File xls; - private static File xlsx; - private static File xlsxStrict; - private static File xltx; - private static File xlsEmb; - private static File xlsb; - - private static File doc; - private static File doc6; - private static File doc95; - private static File docx; - private static File dotx; - private static File docEmb; - private static File docEmbOOXML; - - private static File ppt; - private static File pptx; - - private static File msg; - private static File msgEmb; - private static File msgEmbMsg; - - private static File vsd; - private static File vsdx; - - private static File pub; - - private static File getFileAndCheck(POIDataSamples samples, String name) { - File file = samples.getFile(name); - - assertNotNull("Did not get a file for " + name, file); - assertTrue("Did not get a type file for " + name, file.isFile()); - assertTrue("File did not exist: " + name, file.exists()); - - return file; - } - - @BeforeClass - public static void setUp() throws Exception { - - POIDataSamples ssTests = POIDataSamples.getSpreadSheetInstance(); - xls = getFileAndCheck(ssTests, "SampleSS.xls"); - xlsx = getFileAndCheck(ssTests, "SampleSS.xlsx"); - xlsxStrict = getFileAndCheck(ssTests, "SampleSS.strict.xlsx"); - xltx = getFileAndCheck(ssTests, "test.xltx"); - xlsEmb = getFileAndCheck(ssTests, "excel_with_embeded.xls"); - xlsb = getFileAndCheck(ssTests, "testVarious.xlsb"); - - POIDataSamples wpTests = POIDataSamples.getDocumentInstance(); - doc = getFileAndCheck(wpTests, "SampleDoc.doc"); - doc6 = getFileAndCheck(wpTests, "Word6.doc"); - doc95 = getFileAndCheck(wpTests, "Word95.doc"); - docx = getFileAndCheck(wpTests, "SampleDoc.docx"); - dotx = getFileAndCheck(wpTests, "test.dotx"); - docEmb = getFileAndCheck(wpTests, "word_with_embeded.doc"); - docEmbOOXML = getFileAndCheck(wpTests, "word_with_embeded_ooxml.doc"); - - POIDataSamples slTests = POIDataSamples.getSlideShowInstance(); - ppt = getFileAndCheck(slTests, "SampleShow.ppt"); - pptx = getFileAndCheck(slTests, "SampleShow.pptx"); - txt = getFileAndCheck(slTests, "SampleShow.txt"); - - POIDataSamples dgTests = POIDataSamples.getDiagramInstance(); - vsd = getFileAndCheck(dgTests, "Test_Visio-Some_Random_Text.vsd"); - vsdx = getFileAndCheck(dgTests, "test.vsdx"); - - POIDataSamples pubTests = POIDataSamples.getPublisherInstance(); - pub = getFileAndCheck(pubTests, "Simple.pub"); - - POIDataSamples olTests = POIDataSamples.getHSMFInstance(); - msg = getFileAndCheck(olTests, "quick.msg"); - msgEmb = getFileAndCheck(olTests, "attachment_test_msg.msg"); - msgEmbMsg = getFileAndCheck(olTests, "attachment_msg_pdf.msg"); - } - - @Test - public void testFile() throws Exception { - // Excel - POITextExtractor xlsExtractor = ExtractorFactory.createExtractor(xls); - assertNotNull("Had empty extractor for " + xls, xlsExtractor); - assertTrue("Expected instanceof ExcelExtractor, but had: " + xlsExtractor.getClass(), - xlsExtractor - instanceof ExcelExtractor - ); - assertTrue( - xlsExtractor.getText().length() > 200 - ); - xlsExtractor.close(); - - POITextExtractor extractor = ExtractorFactory.createExtractor(xlsx); - assertTrue( - extractor.getClass().getName(), - extractor - instanceof XSSFExcelExtractor - ); - extractor.close(); - - extractor = ExtractorFactory.createExtractor(xlsx); - assertTrue( - extractor.getText().length() > 200 - ); - extractor.close(); - - extractor = ExtractorFactory.createExtractor(xltx); - assertTrue( - extractor.getClass().getName(), - extractor - instanceof XSSFExcelExtractor - ); - extractor.close(); - - extractor = ExtractorFactory.createExtractor(xlsb); - assertContains(extractor.getText(), "test"); - extractor.close(); - - - extractor = ExtractorFactory.createExtractor(xltx); - assertContains(extractor.getText(), "test"); - extractor.close(); - - // TODO Support OOXML-Strict, see bug #57699 - try { - /*extractor =*/ ExtractorFactory.createExtractor(xlsxStrict); - fail("OOXML-Strict isn't yet supported"); - } catch (POIXMLException e) { - // Expected, for now - } -// extractor = ExtractorFactory.createExtractor(xlsxStrict); -// assertTrue( -// extractor -// instanceof XSSFExcelExtractor -// ); -// extractor.close(); -// -// extractor = ExtractorFactory.createExtractor(xlsxStrict); -// assertTrue( -// extractor.getText().contains("test") -// ); -// extractor.close(); - - - // Word - extractor = ExtractorFactory.createExtractor(doc); - assertTrue( - extractor - instanceof WordExtractor - ); - assertTrue( - extractor.getText().length() > 120 - ); - extractor.close(); - - extractor = ExtractorFactory.createExtractor(doc6); - assertTrue( - extractor - instanceof Word6Extractor - ); - assertTrue( - extractor.getText().length() > 20 - ); - extractor.close(); - - extractor = ExtractorFactory.createExtractor(doc95); - assertTrue( - extractor - instanceof Word6Extractor - ); - assertTrue( - extractor.getText().length() > 120 - ); - extractor.close(); - - extractor = ExtractorFactory.createExtractor(docx); - assertTrue( - extractor instanceof XWPFWordExtractor - ); - extractor.close(); - - extractor = ExtractorFactory.createExtractor(docx); - assertTrue( - extractor.getText().length() > 120 - ); - extractor.close(); - - extractor = ExtractorFactory.createExtractor(dotx); - assertTrue( - extractor instanceof XWPFWordExtractor - ); - extractor.close(); - - extractor = ExtractorFactory.createExtractor(dotx); - assertContains(extractor.getText(), "Test"); - extractor.close(); - - // PowerPoint (PPT) - extractor = ExtractorFactory.createExtractor(ppt); - assertTrue( - extractor - instanceof PowerPointExtractor - ); - assertTrue( - extractor.getText().length() > 120 - ); - extractor.close(); - - // PowerPoint (PPTX) - extractor = ExtractorFactory.createExtractor(pptx); - assertTrue( - extractor - instanceof XSLFPowerPointExtractor - ); - assertTrue( - extractor.getText().length() > 120 - ); - extractor.close(); - - // Visio - binary - extractor = ExtractorFactory.createExtractor(vsd); - assertTrue( - extractor - instanceof VisioTextExtractor - ); - assertTrue( - extractor.getText().length() > 50 - ); - extractor.close(); - - // Visio - vsdx - extractor = ExtractorFactory.createExtractor(vsdx); - assertTrue( - extractor - instanceof XDGFVisioExtractor - ); - assertTrue( - extractor.getText().length() > 20 - ); - extractor.close(); - - // Publisher - extractor = ExtractorFactory.createExtractor(pub); - assertTrue( - extractor - instanceof PublisherTextExtractor - ); - assertTrue( - extractor.getText().length() > 50 - ); - extractor.close(); - - // Outlook msg - extractor = ExtractorFactory.createExtractor(msg); - assertTrue( - extractor - instanceof OutlookTextExtactor - ); - assertTrue( - extractor.getText().length() > 50 - ); - extractor.close(); - - // Text - try { - ExtractorFactory.createExtractor(txt); - fail(); - } catch(IllegalArgumentException e) { - // Good - } - } - - @Test - public void testInputStream() throws Exception { - // Excel - POITextExtractor extractor = ExtractorFactory.createExtractor(new FileInputStream(xls)); - assertTrue( - extractor - instanceof ExcelExtractor - ); - assertTrue( - extractor.getText().length() > 200 - ); - extractor.close(); - - extractor = ExtractorFactory.createExtractor(new FileInputStream(xlsx)); - assertTrue( - extractor.getClass().getName(), - extractor - instanceof XSSFExcelExtractor - ); - assertTrue( - extractor.getText().length() > 200 - ); - // TODO Support OOXML-Strict, see bug #57699 -// assertTrue( -// ExtractorFactory.createExtractor(new FileInputStream(xlsxStrict)) -// instanceof XSSFExcelExtractor -// ); -// assertTrue( -// ExtractorFactory.createExtractor(new FileInputStream(xlsxStrict)).getText().length() > 200 -// ); - extractor.close(); - - // Word - extractor = ExtractorFactory.createExtractor(new FileInputStream(doc)); - assertTrue( - extractor.getClass().getName(), - extractor - instanceof WordExtractor - ); - assertTrue( - extractor.getText().length() > 120 - ); - extractor.close(); - - extractor = ExtractorFactory.createExtractor(new FileInputStream(doc6)); - assertTrue( - extractor.getClass().getName(), - extractor - instanceof Word6Extractor - ); - assertTrue( - extractor.getText().length() > 20 - ); - extractor.close(); - - extractor = ExtractorFactory.createExtractor(new FileInputStream(doc95)); - assertTrue( - extractor.getClass().getName(), - extractor - instanceof Word6Extractor - ); - assertTrue( - extractor.getText().length() > 120 - ); - extractor.close(); - - extractor = ExtractorFactory.createExtractor(new FileInputStream(docx)); - assertTrue( - extractor - instanceof XWPFWordExtractor - ); - assertTrue( - extractor.getText().length() > 120 - ); - extractor.close(); - - // PowerPoint - extractor = ExtractorFactory.createExtractor(new FileInputStream(ppt)); - assertTrue( - extractor - instanceof PowerPointExtractor - ); - assertTrue( - extractor.getText().length() > 120 - ); - extractor.close(); - - extractor = ExtractorFactory.createExtractor(new FileInputStream(pptx)); - assertTrue( - extractor - instanceof XSLFPowerPointExtractor - ); - assertTrue( - extractor.getText().length() > 120 - ); - extractor.close(); - - // Visio - extractor = ExtractorFactory.createExtractor(new FileInputStream(vsd)); - assertTrue( - extractor - instanceof VisioTextExtractor - ); - assertTrue( - extractor.getText().length() > 50 - ); - extractor.close(); - - // Visio - vsdx - extractor = ExtractorFactory.createExtractor(new FileInputStream(vsdx)); - assertTrue( - extractor - instanceof XDGFVisioExtractor - ); - assertTrue( - extractor.getText().length() > 20 - ); - extractor.close(); - - // Publisher - extractor = ExtractorFactory.createExtractor(new FileInputStream(pub)); - assertTrue( - extractor - instanceof PublisherTextExtractor - ); - assertTrue( - extractor.getText().length() > 50 - ); - extractor.close(); - - // Outlook msg - extractor = ExtractorFactory.createExtractor(new FileInputStream(msg)); - assertTrue( - extractor - instanceof OutlookTextExtactor - ); - assertTrue( - extractor.getText().length() > 50 - ); - extractor.close(); - - // Text - try { - FileInputStream stream = new FileInputStream(txt); - try { - ExtractorFactory.createExtractor(stream); - fail(); - } finally { - IOUtils.closeQuietly(stream); - } - } catch(IllegalArgumentException e) { - // Good - } - } - - @Test - public void testPOIFS() throws Exception { - // Excel - assertTrue( - ExtractorFactory.createExtractor(new POIFSFileSystem(new FileInputStream(xls))) - instanceof ExcelExtractor - ); - assertTrue( - ExtractorFactory.createExtractor(new POIFSFileSystem(new FileInputStream(xls))).getText().length() > 200 - ); - - // Word - assertTrue( - ExtractorFactory.createExtractor(new POIFSFileSystem(new FileInputStream(doc))) - instanceof WordExtractor - ); - assertTrue( - ExtractorFactory.createExtractor(new POIFSFileSystem(new FileInputStream(doc))).getText().length() > 120 - ); - - assertTrue( - ExtractorFactory.createExtractor(new POIFSFileSystem(new FileInputStream(doc6))) - instanceof Word6Extractor - ); - assertTrue( - ExtractorFactory.createExtractor(new POIFSFileSystem(new FileInputStream(doc6))).getText().length() > 20 - ); - - assertTrue( - ExtractorFactory.createExtractor(new POIFSFileSystem(new FileInputStream(doc95))) - instanceof Word6Extractor - ); - assertTrue( - ExtractorFactory.createExtractor(new POIFSFileSystem(new FileInputStream(doc95))).getText().length() > 120 - ); - - // PowerPoint - assertTrue( - ExtractorFactory.createExtractor(new POIFSFileSystem(new FileInputStream(ppt))) - instanceof PowerPointExtractor - ); - assertTrue( - ExtractorFactory.createExtractor(new POIFSFileSystem(new FileInputStream(ppt))).getText().length() > 120 - ); - - // Visio - assertTrue( - ExtractorFactory.createExtractor(new POIFSFileSystem(new FileInputStream(vsd))) - instanceof VisioTextExtractor - ); - assertTrue( - ExtractorFactory.createExtractor(new POIFSFileSystem(new FileInputStream(vsd))).getText().length() > 50 - ); - - // Publisher - assertTrue( - ExtractorFactory.createExtractor(new POIFSFileSystem(new FileInputStream(pub))) - instanceof PublisherTextExtractor - ); - assertTrue( - ExtractorFactory.createExtractor(new POIFSFileSystem(new FileInputStream(pub))).getText().length() > 50 - ); - - // Outlook msg - assertTrue( - ExtractorFactory.createExtractor(new POIFSFileSystem(new FileInputStream(msg))) - instanceof OutlookTextExtactor - ); - assertTrue( - ExtractorFactory.createExtractor(new POIFSFileSystem(new FileInputStream(msg))).getText().length() > 50 - ); - - // Text - try { - ExtractorFactory.createExtractor(new POIFSFileSystem(new FileInputStream(txt))); - fail(); - } catch(IOException e) { - // Good - } - } - - - @Test - public void testOPOIFS() throws Exception { - // Excel - assertTrue( - ExtractorFactory.createExtractor(new OPOIFSFileSystem(new FileInputStream(xls))) - instanceof ExcelExtractor - ); - assertTrue( - ExtractorFactory.createExtractor(new OPOIFSFileSystem(new FileInputStream(xls))).getText().length() > 200 - ); - - // Word - assertTrue( - ExtractorFactory.createExtractor(new OPOIFSFileSystem(new FileInputStream(doc))) - instanceof WordExtractor - ); - assertTrue( - ExtractorFactory.createExtractor(new OPOIFSFileSystem(new FileInputStream(doc))).getText().length() > 120 - ); - - assertTrue( - ExtractorFactory.createExtractor(new OPOIFSFileSystem(new FileInputStream(doc6))) - instanceof Word6Extractor - ); - assertTrue( - ExtractorFactory.createExtractor(new OPOIFSFileSystem(new FileInputStream(doc6))).getText().length() > 20 - ); - - assertTrue( - ExtractorFactory.createExtractor(new OPOIFSFileSystem(new FileInputStream(doc95))) - instanceof Word6Extractor - ); - assertTrue( - ExtractorFactory.createExtractor(new OPOIFSFileSystem(new FileInputStream(doc95))).getText().length() > 120 - ); - - // PowerPoint - assertTrue( - ExtractorFactory.createExtractor(new OPOIFSFileSystem(new FileInputStream(ppt))) - instanceof PowerPointExtractor - ); - assertTrue( - ExtractorFactory.createExtractor(new OPOIFSFileSystem(new FileInputStream(ppt))).getText().length() > 120 - ); - - // Visio - assertTrue( - ExtractorFactory.createExtractor(new OPOIFSFileSystem(new FileInputStream(vsd))) - instanceof VisioTextExtractor - ); - assertTrue( - ExtractorFactory.createExtractor(new OPOIFSFileSystem(new FileInputStream(vsd))).getText().length() > 50 - ); - - // Publisher - assertTrue( - ExtractorFactory.createExtractor(new OPOIFSFileSystem(new FileInputStream(pub))) - instanceof PublisherTextExtractor - ); - assertTrue( - ExtractorFactory.createExtractor(new OPOIFSFileSystem(new FileInputStream(pub))).getText().length() > 50 - ); - - // Outlook msg - assertTrue( - ExtractorFactory.createExtractor(new OPOIFSFileSystem(new FileInputStream(msg))) - instanceof OutlookTextExtactor - ); - assertTrue( - ExtractorFactory.createExtractor(new OPOIFSFileSystem(new FileInputStream(msg))).getText().length() > 50 - ); - - // Text - try { - ExtractorFactory.createExtractor(new OPOIFSFileSystem(new FileInputStream(txt))); - fail(); - } catch(IOException e) { - // Good - } - } - - @Test - public void testPackage() throws Exception { - // Excel - POIXMLTextExtractor extractor = ExtractorFactory.createExtractor(OPCPackage.open(xlsx.toString(), PackageAccess.READ)); - assertTrue(extractor instanceof XSSFExcelExtractor); - extractor.close(); - extractor = ExtractorFactory.createExtractor(OPCPackage.open(xlsx.toString())); - assertTrue(extractor.getText().length() > 200); - extractor.close(); - - // Word - extractor = ExtractorFactory.createExtractor(OPCPackage.open(docx.toString())); - assertTrue(extractor instanceof XWPFWordExtractor); - extractor.close(); - - extractor = ExtractorFactory.createExtractor(OPCPackage.open(docx.toString())); - assertTrue(extractor.getText().length() > 120); - extractor.close(); - - // PowerPoint - extractor = ExtractorFactory.createExtractor(OPCPackage.open(pptx.toString())); - assertTrue(extractor instanceof XSLFPowerPointExtractor); - extractor.close(); - - extractor = ExtractorFactory.createExtractor(OPCPackage.open(pptx.toString())); - assertTrue(extractor.getText().length() > 120); - extractor.close(); - - // Visio - extractor = ExtractorFactory.createExtractor(OPCPackage.open(vsdx.toString())); - assertTrue(extractor instanceof XDGFVisioExtractor); - assertTrue(extractor.getText().length() > 20); - extractor.close(); - - // Text - try { - ExtractorFactory.createExtractor(OPCPackage.open(txt.toString())); - fail("TestExtractorFactory.testPackage() failed on " + txt); - } catch(UnsupportedFileFormatException e) { - // Good - } catch (Exception e) { - System.out.println("TestExtractorFactory.testPackage() failed on " + txt); - throw e; - } - } - - @Test - public void testPreferEventBased() throws Exception { - assertFalse(ExtractorFactory.getPreferEventExtractor()); - assertFalse(ExtractorFactory.getThreadPrefersEventExtractors()); - assertNull(ExtractorFactory.getAllThreadsPreferEventExtractors()); - - ExtractorFactory.setThreadPrefersEventExtractors(true); - - assertTrue(ExtractorFactory.getPreferEventExtractor()); - assertTrue(ExtractorFactory.getThreadPrefersEventExtractors()); - assertNull(ExtractorFactory.getAllThreadsPreferEventExtractors()); - - ExtractorFactory.setAllThreadsPreferEventExtractors(false); - - assertFalse(ExtractorFactory.getPreferEventExtractor()); - assertTrue(ExtractorFactory.getThreadPrefersEventExtractors()); - assertEquals(Boolean.FALSE, ExtractorFactory.getAllThreadsPreferEventExtractors()); - - ExtractorFactory.setAllThreadsPreferEventExtractors(null); - - assertTrue(ExtractorFactory.getPreferEventExtractor()); - assertTrue(ExtractorFactory.getThreadPrefersEventExtractors()); - assertNull(ExtractorFactory.getAllThreadsPreferEventExtractors()); - - - // Check we get the right extractors now - POITextExtractor extractor = ExtractorFactory.createExtractor(new POIFSFileSystem(new FileInputStream(xls))); - assertTrue( - extractor - instanceof EventBasedExcelExtractor - ); - extractor.close(); - extractor = ExtractorFactory.createExtractor(new POIFSFileSystem(new FileInputStream(xls))); - assertTrue( - extractor.getText().length() > 200 - ); - extractor.close(); - - extractor = ExtractorFactory.createExtractor(OPCPackage.open(xlsx.toString(), PackageAccess.READ)); - assertTrue(extractor instanceof XSSFEventBasedExcelExtractor); - extractor.close(); - - extractor = ExtractorFactory.createExtractor(OPCPackage.open(xlsx.toString(), PackageAccess.READ)); - assertTrue( - extractor.getText().length() > 200 - ); - extractor.close(); - - - // Put back to normal - ExtractorFactory.setThreadPrefersEventExtractors(false); - assertFalse(ExtractorFactory.getPreferEventExtractor()); - assertFalse(ExtractorFactory.getThreadPrefersEventExtractors()); - assertNull(ExtractorFactory.getAllThreadsPreferEventExtractors()); - - // And back - extractor = ExtractorFactory.createExtractor(new POIFSFileSystem(new FileInputStream(xls))); - assertTrue( - extractor - instanceof ExcelExtractor - ); - extractor.close(); - extractor = ExtractorFactory.createExtractor(new POIFSFileSystem(new FileInputStream(xls))); - assertTrue( - extractor.getText().length() > 200 - ); - extractor.close(); - - extractor = ExtractorFactory.createExtractor(OPCPackage.open(xlsx.toString(), PackageAccess.READ)); - assertTrue( - extractor - instanceof XSSFExcelExtractor - ); - extractor.close(); - extractor = ExtractorFactory.createExtractor(OPCPackage.open(xlsx.toString())); - assertTrue( - extractor.getText().length() > 200 - ); - extractor.close(); - } - - /** - * Test embeded docs text extraction. For now, only - * does poifs embeded, but will do ooxml ones - * at some point. - */ - @Test - public void testEmbeded() throws Exception { - POIOLE2TextExtractor ext; - POITextExtractor[] embeds; - - // No embedings - ext = (POIOLE2TextExtractor) - ExtractorFactory.createExtractor(xls); - embeds = ExtractorFactory.getEmbededDocsTextExtractors(ext); - assertEquals(0, embeds.length); - ext.close(); - - // Excel - ext = (POIOLE2TextExtractor) - ExtractorFactory.createExtractor(xlsEmb); - embeds = ExtractorFactory.getEmbededDocsTextExtractors(ext); - - assertEquals(6, embeds.length); - int numWord = 0, numXls = 0, numPpt = 0, numMsg = 0, numWordX; - for (POITextExtractor embed : embeds) { - assertTrue(embed.getText().length() > 20); - - if (embed instanceof PowerPointExtractor) numPpt++; - else if (embed instanceof ExcelExtractor) numXls++; - else if (embed instanceof WordExtractor) numWord++; - else if (embed instanceof OutlookTextExtactor) numMsg++; - } - assertEquals(2, numPpt); - assertEquals(2, numXls); - assertEquals(2, numWord); - assertEquals(0, numMsg); - ext.close(); - - // Word - ext = (POIOLE2TextExtractor) - ExtractorFactory.createExtractor(docEmb); - embeds = ExtractorFactory.getEmbededDocsTextExtractors(ext); - - numWord = 0; numXls = 0; numPpt = 0; numMsg = 0; - assertEquals(4, embeds.length); - for (POITextExtractor embed : embeds) { - assertTrue(embed.getText().length() > 20); - if (embed instanceof PowerPointExtractor) numPpt++; - else if (embed instanceof ExcelExtractor) numXls++; - else if (embed instanceof WordExtractor) numWord++; - else if (embed instanceof OutlookTextExtactor) numMsg++; - } - assertEquals(1, numPpt); - assertEquals(2, numXls); - assertEquals(1, numWord); - assertEquals(0, numMsg); - ext.close(); - - // Word which contains an OOXML file - ext = (POIOLE2TextExtractor) - ExtractorFactory.createExtractor(docEmbOOXML); - embeds = ExtractorFactory.getEmbededDocsTextExtractors(ext); - - numWord = 0; numXls = 0; numPpt = 0; numMsg = 0; numWordX = 0; - assertEquals(3, embeds.length); - for (POITextExtractor embed : embeds) { - assertTrue(embed.getText().length() > 20); - if (embed instanceof PowerPointExtractor) numPpt++; - else if (embed instanceof ExcelExtractor) numXls++; - else if (embed instanceof WordExtractor) numWord++; - else if (embed instanceof OutlookTextExtactor) numMsg++; - else if (embed instanceof XWPFWordExtractor) numWordX++; - } - assertEquals(1, numPpt); - assertEquals(1, numXls); - assertEquals(0, numWord); - assertEquals(1, numWordX); - assertEquals(0, numMsg); - ext.close(); - - // Outlook - ext = (OutlookTextExtactor) - ExtractorFactory.createExtractor(msgEmb); - embeds = ExtractorFactory.getEmbededDocsTextExtractors(ext); - - numWord = 0; numXls = 0; numPpt = 0; numMsg = 0; - assertEquals(1, embeds.length); - for (POITextExtractor embed : embeds) { - assertTrue(embed.getText().length() > 20); - if (embed instanceof PowerPointExtractor) numPpt++; - else if (embed instanceof ExcelExtractor) numXls++; - else if (embed instanceof WordExtractor) numWord++; - else if (embed instanceof OutlookTextExtactor) numMsg++; - } - assertEquals(0, numPpt); - assertEquals(0, numXls); - assertEquals(1, numWord); - assertEquals(0, numMsg); - ext.close(); - - // Outlook with another outlook file in it - ext = (OutlookTextExtactor) - ExtractorFactory.createExtractor(msgEmbMsg); - embeds = ExtractorFactory.getEmbededDocsTextExtractors(ext); - - numWord = 0; numXls = 0; numPpt = 0; numMsg = 0; - assertEquals(1, embeds.length); - for (POITextExtractor embed : embeds) { - assertTrue(embed.getText().length() > 20); - if (embed instanceof PowerPointExtractor) numPpt++; - else if (embed instanceof ExcelExtractor) numXls++; - else if (embed instanceof WordExtractor) numWord++; - else if (embed instanceof OutlookTextExtactor) numMsg++; - } - assertEquals(0, numPpt); - assertEquals(0, numXls); - assertEquals(0, numWord); - assertEquals(1, numMsg); - ext.close(); - - // TODO - PowerPoint - // TODO - Publisher - // TODO - Visio - } - - private static final String[] EXPECTED_FAILURES = new String[] { - // password protected files - "spreadsheet/password.xls", - "spreadsheet/protected_passtika.xlsx", - "spreadsheet/51832.xls", - "document/PasswordProtected.doc", - "slideshow/Password_Protected-hello.ppt", - "slideshow/Password_Protected-56-hello.ppt", - "slideshow/Password_Protected-np-hello.ppt", - "slideshow/cryptoapi-proc2356.ppt", - //"document/bug53475-password-is-pass.docx", - //"document/bug53475-password-is-solrcell.docx", - "spreadsheet/xor-encryption-abc.xls", - "spreadsheet/35897-type4.xls", - //"poifs/protect.xlsx", - //"poifs/protected_sha512.xlsx", - //"poifs/extenxls_pwd123.xlsx", - //"poifs/protected_agile.docx", - "spreadsheet/58616.xlsx", - - // TODO: fails XMLExportTest, is this ok? - "spreadsheet/CustomXMLMapping-singleattributenamespace.xlsx", - "spreadsheet/55864.xlsx", - "spreadsheet/57890.xlsx", - - // TODO: these fail now with some NPE/file read error because we now try to compute every value via Cell.toString()! - "spreadsheet/44958.xls", - "spreadsheet/44958_1.xls", - "spreadsheet/testArraysAndTables.xls", - - // TODO: good to ignore? - "spreadsheet/sample-beta.xlsx", - - // This is actually a spreadsheet! - "hpsf/TestRobert_Flaherty.doc", - - // some files that are broken, eg Word 95, ... - "spreadsheet/43493.xls", - "spreadsheet/46904.xls", - "document/Bug50955.doc", - "slideshow/PPT95.ppt", - "openxml4j/OPCCompliance_CoreProperties_DCTermsNamespaceLimitedUseFAIL.docx", - "openxml4j/OPCCompliance_CoreProperties_DoNotUseCompatibilityMarkupFAIL.docx", - "openxml4j/OPCCompliance_CoreProperties_LimitedXSITypeAttribute_NotPresentFAIL.docx", - "openxml4j/OPCCompliance_CoreProperties_LimitedXSITypeAttribute_PresentWithUnauthorizedValueFAIL.docx", - "openxml4j/OPCCompliance_CoreProperties_OnlyOneCorePropertiesPartFAIL.docx", - "openxml4j/OPCCompliance_CoreProperties_UnauthorizedXMLLangAttributeFAIL.docx", - "openxml4j/OPCCompliance_DerivedPartNameFAIL.docx", - "openxml4j/invalid.xlsx", - "spreadsheet/54764-2.xlsx", // see TestXSSFBugs.bug54764() - "spreadsheet/54764.xlsx", // see TestXSSFBugs.bug54764() - "spreadsheet/Simple.xlsb", - "poifs/unknown_properties.msg", // POIFS properties corrupted - "poifs/only-zero-byte-streams.ole2", // No actual contents - "spreadsheet/poc-xmlbomb.xlsx", // contains xml-entity-expansion - "spreadsheet/poc-xmlbomb-empty.xlsx", // contains xml-entity-expansion - "spreadsheet/poc-shared-strings.xlsx", // contains shared-string-entity-expansion - - // old Excel files, which we only support simple text extraction of - "spreadsheet/testEXCEL_2.xls", - "spreadsheet/testEXCEL_3.xls", - "spreadsheet/testEXCEL_4.xls", - "spreadsheet/testEXCEL_5.xls", - "spreadsheet/testEXCEL_95.xls", - - // OOXML Strict is not yet supported, see bug #57699 - "spreadsheet/SampleSS.strict.xlsx", - "spreadsheet/SimpleStrict.xlsx", - "spreadsheet/sample.strict.xlsx", - - // non-TNEF files - "ddf/Container.dat", - "ddf/47143.dat", - - // sheet cloning errors - "spreadsheet/47813.xlsx", - "spreadsheet/56450.xls", - "spreadsheet/57231_MixedGasReport.xls", - "spreadsheet/OddStyleRecord.xls", - "spreadsheet/WithChartSheet.xlsx", - "spreadsheet/chart_sheet.xlsx", - }; - - @Test - public void testFileLeak() throws Exception { - // run a number of files that might fail in order to catch - // leaked file resources when using file-leak-detector while - // running the test - - for(String file : EXPECTED_FAILURES) { - try { - ExtractorFactory.createExtractor(POIDataSamples.getSpreadSheetInstance().getFile(file)); - } catch (Exception e) { - // catch all exceptions here as we are only interested in file-handle leaks - } - } - } - - /** - * #59074 - Excel 95 files should give a helpful message, not just - * "No supported documents found in the OLE2 stream" - */ - @Test - public void bug59074() throws Exception { - try { - ExtractorFactory.createExtractor( - POIDataSamples.getSpreadSheetInstance().getFile("59074.xls")); - fail("Old excel formats not supported via ExtractorFactory"); - } catch (OldExcelFormatException e) { - // expected here - } - } - - @Test - public void testGetEmbeddedFromXMLExtractor() { - try { - // currently not implemented - ExtractorFactory.getEmbededDocsTextExtractors((POIXMLTextExtractor)null); - fail("Unsupported currently"); - } catch (IllegalStateException e) { - // expected here - } - } - - // This bug is currently open. This test will fail with "expected error not thrown" when the bug has been fixed. - // When this happens, change this from @Test(expected=...) to @Test - // bug 45565: text within TextBoxes is extracted by ExcelExtractor and WordExtractor - @Test(expected=AssertionError.class) - public void test45565() throws Exception { - POITextExtractor extractor = ExtractorFactory.createExtractor(HSSFTestDataSamples.getSampleFile("45565.xls")); - try { - String text = extractor.getText(); - assertContains(text, "testdoc"); - assertContains(text, "test phrase"); - } finally { - extractor.close(); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/OpenXML4JTestDataSamples.java b/src/ooxml/testcases/org/apache/poi/openxml4j/OpenXML4JTestDataSamples.java deleted file mode 100644 index 1c6b942a5..000000000 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/OpenXML4JTestDataSamples.java +++ /dev/null @@ -1,58 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.util.TempFile; - -import java.io.File; -import java.io.InputStream; -import java.io.IOException; - -/** - * Centralises logic for finding/opening sample files for ooxml4j unit tests - */ -public final class OpenXML4JTestDataSamples { - private static final POIDataSamples _samples = POIDataSamples.getOpenXML4JInstance(); - - private OpenXML4JTestDataSamples() { - // no instances of this class - } - - public static InputStream openSampleStream(String sampleFileName) { - return _samples.openResourceAsStream(sampleFileName); - } - public static String getSampleFileName(String sampleFileName) { - return getSampleFile(sampleFileName).getAbsolutePath(); - } - - public static File getSampleFile(String sampleFileName) { - return _samples.getFile(sampleFileName); - } - - public static File getOutputFile(String outputFileName) throws IOException { - String suffix = outputFileName.substring(outputFileName.lastIndexOf('.')); - return TempFile.createTempFile(outputFileName, suffix); - } - - - public static InputStream openComplianceSampleStream(String sampleFileName) { - return _samples.openResourceAsStream(sampleFileName); - } - -} diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/AllOpenXML4JTests.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/AllOpenXML4JTests.java deleted file mode 100644 index 7b98afd97..000000000 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/AllOpenXML4JTests.java +++ /dev/null @@ -1,36 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestContentType.class - , TestFileHelper.class - , TestListParts.class - , TestPackage.class - , TestPackageCoreProperties.class - , TestPackagePartName.class - , TestPackageThumbnail.class - , TestPackagingURIHelper.class - , TestRelationships.class -}) -public final class AllOpenXML4JTests { -} diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestContentType.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestContentType.java deleted file mode 100644 index 91187ceb9..000000000 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestContentType.java +++ /dev/null @@ -1,242 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc; - -import java.io.InputStream; - -import junit.framework.TestCase; - -import org.apache.poi.openxml4j.OpenXML4JTestDataSamples; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.internal.ContentType; -import org.apache.poi.xwpf.usermodel.XWPFRelation; - -/** - * Tests for content type (ContentType class). - * - * @author Julien Chable - */ -public final class TestContentType extends TestCase { - - /** - * Check rule M1.13: Package implementers shall only create and only - * recognize parts with a content type; format designers shall specify a - * content type for each part included in the format. Content types for - * package parts shall fit the definition and syntax for media types as - * specified in RFC 2616, \u00A73.7. - */ - public void testContentTypeValidation() throws InvalidFormatException { - String[] contentTypesToTest = new String[] { "text/xml", - "application/pgp-key", "application/vnd.hp-PCLXL", - "application/vnd.lotus-1-2-3" }; - for (String contentType : contentTypesToTest) { - new ContentType(contentType); - } - } - - /** - * Check rule M1.13 : Package implementers shall only create and only - * recognize parts with a content type; format designers shall specify a - * content type for each part included in the format. Content types for - * package parts shall fit the definition and syntax for media types as - * specified in RFC 2616, \u00A3.7. - * - * Check rule M1.14: Content types shall not use linear white space either - * between the type and subtype or between an attribute and its value. - * Content types also shall not have leading or trailing white spaces. - * Package implementers shall create only such content types and shall - * require such content types when retrieving a part from a package; format - * designers shall specify only such content types for inclusion in the - * format. - */ - public void testContentTypeValidationFailure() { - String[] contentTypesToTest = new String[] { "text/xml/app", "", - "test", "text(xml/xml", "text)xml/xml", "text/xml", "text@/xml", "text,/xml", "text;/xml", - "text:/xml", "text\\/xml", "t/ext/xml", "t\"ext/xml", - "text[/xml", "text]/xml", "text?/xml", "tex=t/xml", - "te{xt/xml", "tex}t/xml", "te xt/xml", - "text" + (char) 9 + "/xml", "text xml", " text/xml " }; - for (String contentType : contentTypesToTest) { - try { - new ContentType(contentType); - } catch (InvalidFormatException e) { - continue; - } - fail("Must have fail for content type: '" + contentType + "' !"); - } - } - - /** - * Parameters are allowed, provides that they meet the - * criteria of rule [01.2] - * Invalid parameters are verified as incorrect in - * {@link #testContentTypeParameterFailure()} - */ - public void testContentTypeParam() throws InvalidFormatException { - String[] contentTypesToTest = new String[] { "mail/toto;titi=tata", - "text/xml;a=b;c=d", "text/xml;key1=param1;key2=param2", - "application/pgp-key;version=\"2\"", - "application/x-resqml+xml;version=2.0;type=obj_global2dCrs" - }; - for (String contentType : contentTypesToTest) { - new ContentType(contentType); - } - } - - /** - * Check rule [O1.2]: Format designers might restrict the usage of - * parameters for content types. - */ - public void testContentTypeParameterFailure() { - String[] contentTypesToTest = new String[] { - "mail/toto;\"titi=tata\"", // quotes not allowed like that - "mail/toto;titi = tata", // spaces not allowed - "text/\u0080" // characters above ASCII are not allowed - }; - for (String contentType : contentTypesToTest) { - try { - new ContentType(contentType); - } catch (InvalidFormatException e) { - continue; - } - fail("Must have fail for content type: '" + contentType + "' !"); - } - } - - /** - * Check rule M1.15: The package implementer shall require a content type - * that does not include comments and the format designer shall specify such - * a content type. - */ - public void testContentTypeCommentFailure() { - String[] contentTypesToTest = new String[] { "text/xml(comment)" }; - for (String contentType : contentTypesToTest) { - try { - new ContentType(contentType); - } catch (InvalidFormatException e) { - continue; - } - fail("Must have fail for content type: '" + contentType + "' !"); - } - } - - /** - * OOXML content types don't need entities, but we shouldn't - * barf if we get one from a third party system that added them - */ - public void testFileWithContentTypeEntities() throws Exception { - InputStream is = OpenXML4JTestDataSamples.openSampleStream("ContentTypeHasEntities.ooxml"); - OPCPackage p = OPCPackage.open(is); - - // Check we found the contents of it - boolean foundCoreProps = false, foundDocument = false, foundTheme1 = false; - for (PackagePart part : p.getParts()) { - if (part.getPartName().toString().equals("/docProps/core.xml")) { - assertEquals(ContentTypes.CORE_PROPERTIES_PART, part.getContentType()); - foundCoreProps = true; - } - if (part.getPartName().toString().equals("/word/document.xml")) { - assertEquals(XWPFRelation.DOCUMENT.getContentType(), part.getContentType()); - foundDocument = true; - } - if (part.getPartName().toString().equals("/word/theme/theme1.xml")) { - assertEquals(XWPFRelation.THEME.getContentType(), part.getContentType()); - foundTheme1 = true; - } - } - assertTrue("Core not found in " + p.getParts(), foundCoreProps); - assertTrue("Document not found in " + p.getParts(), foundDocument); - assertTrue("Theme1 not found in " + p.getParts(), foundTheme1); - } - - /** - * Check that we can open a file where there are valid - * parameters on a content type - */ - public void testFileWithContentTypeParams() throws Exception { - InputStream is = OpenXML4JTestDataSamples.openSampleStream("ContentTypeHasParameters.ooxml"); - - OPCPackage p = OPCPackage.open(is); - - final String typeResqml = "application/x-resqml+xml"; - - // Check the types on everything - for (PackagePart part : p.getParts()) { - final String contentType = part.getContentType(); - final ContentType details = part.getContentTypeDetails(); - final int length = details.getParameterKeys().length; - final boolean hasParameters = details.hasParameters(); - - // _rels type doesn't have any params - if (part.isRelationshipPart()) { - assertEquals(ContentTypes.RELATIONSHIPS_PART, contentType); - assertEquals(ContentTypes.RELATIONSHIPS_PART, details.toString()); - assertEquals(false, hasParameters); - assertEquals(0, length); - } - // Core type doesn't have any params - else if (part.getPartName().toString().equals("/docProps/core.xml")) { - assertEquals(ContentTypes.CORE_PROPERTIES_PART, contentType); - assertEquals(ContentTypes.CORE_PROPERTIES_PART, details.toString()); - assertEquals(false, hasParameters); - assertEquals(0, length); - } - // Global Crs types do have params - else if (part.getPartName().toString().equals("/global1dCrs.xml")) { - assertTrue(part.getContentType().startsWith(typeResqml)); - assertEquals(typeResqml, details.toString(false)); - assertEquals(true, hasParameters); - assertContains("version=2.0", details.toString()); - assertContains("type=obj_global1dCrs", details.toString()); - assertEquals(2, length); - assertEquals("2.0", details.getParameter("version")); - assertEquals("obj_global1dCrs", details.getParameter("type")); - } - else if (part.getPartName().toString().equals("/global2dCrs.xml")) { - assertTrue(part.getContentType().startsWith(typeResqml)); - assertEquals(typeResqml, details.toString(false)); - assertEquals(true, hasParameters); - assertContains("version=2.0", details.toString()); - assertContains("type=obj_global2dCrs", details.toString()); - assertEquals(2, length); - assertEquals("2.0", details.getParameter("version")); - assertEquals("obj_global2dCrs", details.getParameter("type")); - } - // Other thingy - else if (part.getPartName().toString().equals("/myTestingGuid.xml")) { - assertTrue(part.getContentType().startsWith(typeResqml)); - assertEquals(typeResqml, details.toString(false)); - assertEquals(true, hasParameters); - assertContains("version=2.0", details.toString()); - assertContains("type=obj_tectonicBoundaryFeature", details.toString()); - assertEquals(2, length); - assertEquals("2.0", details.getParameter("version")); - assertEquals("obj_tectonicBoundaryFeature", details.getParameter("type")); - } - // That should be it! - else { - fail("Unexpected part " + part); - } - } - } - - private static void assertContains(String needle, String haystack) { - assertTrue(haystack.contains(needle)); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestFileHelper.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestFileHelper.java deleted file mode 100644 index 72dc40cee..000000000 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestFileHelper.java +++ /dev/null @@ -1,58 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc; - -import static org.junit.Assert.assertTrue; - -import java.io.File; -import java.util.TreeMap; - -import org.apache.poi.openxml4j.opc.internal.FileHelper; -import org.junit.Test; - -/** - * Test TestFileHelper class. - * - * @author Julien Chable - */ -public final class TestFileHelper { - - /** - * TODO - use simple JDK methods on {@link File} instead:
    - * {@link File#getParentFile()} instead of {@link FileHelper#getDirectory(File) - * {@link File#getName()} instead of {@link FileHelper#getFilename(File) - */ - @Test - public void testGetDirectory() { - TreeMap expectedValue = new TreeMap(); - expectedValue.put("/dir1/test.doc", "/dir1"); - expectedValue.put("/dir1/dir2/test.doc.xml", "/dir1/dir2"); - - for (String filename : expectedValue.keySet()) { - File f1 = new File(expectedValue.get(filename)); - File f2 = FileHelper.getDirectory(new File(filename)); - -// if (false) { -// // YK: The original version asserted expected values against File#getAbsolutePath(): -// assertTrue(expectedValue.get(filename).equalsIgnoreCase(f2.getAbsolutePath())); -// // This comparison is platform dependent. A better approach is below -// } - assertTrue(f1.equals(f2)); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestListParts.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestListParts.java deleted file mode 100644 index 78294e353..000000000 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestListParts.java +++ /dev/null @@ -1,104 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc; - -import java.io.IOException; -import java.io.InputStream; -import java.util.TreeMap; - -import junit.framework.TestCase; - -import org.apache.poi.openxml4j.OpenXML4JTestDataSamples; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.util.POILogger; -import org.apache.poi.util.POILogFactory; - -public final class TestListParts extends TestCase { - private static final POILogger logger = POILogFactory.getLogger(TestListParts.class); - - private TreeMap expectedValues; - - private TreeMap values; - - @Override - protected void setUp() throws Exception { - values = new TreeMap(); - - // Expected values - expectedValues = new TreeMap(); - expectedValues.put(PackagingURIHelper.createPartName("/_rels/.rels"), - "application/vnd.openxmlformats-package.relationships+xml"); - - expectedValues - .put(PackagingURIHelper.createPartName("/docProps/app.xml"), - "application/vnd.openxmlformats-officedocument.extended-properties+xml"); - expectedValues.put(PackagingURIHelper - .createPartName("/docProps/core.xml"), - "application/vnd.openxmlformats-package.core-properties+xml"); - expectedValues.put(PackagingURIHelper - .createPartName("/word/_rels/document.xml.rels"), - "application/vnd.openxmlformats-package.relationships+xml"); - expectedValues - .put( - PackagingURIHelper.createPartName("/word/document.xml"), - "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"); - expectedValues - .put(PackagingURIHelper.createPartName("/word/fontTable.xml"), - "application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml"); - expectedValues.put(PackagingURIHelper - .createPartName("/word/media/image1.gif"), "image/gif"); - expectedValues - .put(PackagingURIHelper.createPartName("/word/settings.xml"), - "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml"); - expectedValues - .put(PackagingURIHelper.createPartName("/word/styles.xml"), - "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"); - expectedValues.put(PackagingURIHelper - .createPartName("/word/theme/theme1.xml"), - "application/vnd.openxmlformats-officedocument.theme+xml"); - expectedValues - .put( - PackagingURIHelper - .createPartName("/word/webSettings.xml"), - "application/vnd.openxmlformats-officedocument.wordprocessingml.webSettings+xml"); - } - - /** - * List all parts of a package. - */ - public void testListParts() throws InvalidFormatException { - InputStream is = OpenXML4JTestDataSamples.openSampleStream("sample.docx"); - - OPCPackage p; - try { - p = OPCPackage.open(is); - } catch (IOException e) { - throw new RuntimeException(e); - } - for (PackagePart part : p.getParts()) { - values.put(part.getPartName(), part.getContentType()); - logger.log(POILogger.DEBUG, part.getPartName()); - } - - // Compare expected values with values return by the package - for (PackagePartName partName : expectedValues.keySet()) { - assertNotNull(values.get(partName)); - assertEquals(expectedValues.get(partName), values.get(partName)); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackage.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackage.java deleted file mode 100644 index 4362f62d1..000000000 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackage.java +++ /dev/null @@ -1,966 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc; - -import org.apache.poi.*; -import org.apache.poi.extractor.ExtractorFactory; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.openxml4j.OpenXML4JTestDataSamples; -import org.apache.poi.openxml4j.exceptions.*; -import org.apache.poi.openxml4j.opc.internal.ContentTypeManager; -import org.apache.poi.openxml4j.opc.internal.FileHelper; -import org.apache.poi.openxml4j.opc.internal.PackagePropertiesPart; -import org.apache.poi.openxml4j.opc.internal.ZipHelper; -import org.apache.poi.openxml4j.util.ZipSecureFile; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.usermodel.WorkbookFactory; -import org.apache.poi.util.*; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.xmlbeans.XmlException; -import org.junit.Ignore; -import org.junit.Test; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.NodeList; -import org.xml.sax.SAXException; - -import java.io.*; -import java.lang.reflect.InvocationTargetException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.List; -import java.util.TreeMap; -import java.util.regex.Pattern; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; -import java.util.zip.ZipOutputStream; - -import static org.junit.Assert.*; - -public final class TestPackage { - private static final POILogger logger = POILogFactory.getLogger(TestPackage.class); - - /** - * Test that just opening and closing the file doesn't alter the document. - */ - @Test - public void openSave() throws IOException, InvalidFormatException { - String originalFile = OpenXML4JTestDataSamples.getSampleFileName("TestPackageCommon.docx"); - File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageOpenSaveTMP.docx"); - - @SuppressWarnings("resource") - OPCPackage p = OPCPackage.open(originalFile, PackageAccess.READ_WRITE); - try { - p.save(targetFile.getAbsoluteFile()); - - // Compare the original and newly saved document - assertTrue(targetFile.exists()); - ZipFileAssert.assertEquals(new File(originalFile), targetFile); - assertTrue(targetFile.delete()); - } finally { - // use revert to not re-write the input file - p.revert(); - } - } - - /** - * Test that when we create a new Package, we give it - * the correct default content types - */ - @Test - public void createGetsContentTypes() - throws IOException, InvalidFormatException, SecurityException, IllegalArgumentException, NoSuchFieldException, IllegalAccessException { - File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestCreatePackageTMP.docx"); - - // Zap the target file, in case of an earlier run - if(targetFile.exists()) { - assertTrue(targetFile.delete()); - } - - @SuppressWarnings("resource") - OPCPackage pkg = OPCPackage.create(targetFile); - - // Check it has content types for rels and xml - ContentTypeManager ctm = getContentTypeManager(pkg); - assertEquals( - "application/xml", - ctm.getContentType( - PackagingURIHelper.createPartName("/foo.xml") - ) - ); - assertEquals( - ContentTypes.RELATIONSHIPS_PART, - ctm.getContentType( - PackagingURIHelper.createPartName("/foo.rels") - ) - ); - assertNull( - ctm.getContentType( - PackagingURIHelper.createPartName("/foo.txt") - ) - ); - - pkg.revert(); - } - - /** - * Test package creation. - */ - @Test - public void createPackageAddPart() throws IOException, InvalidFormatException { - File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestCreatePackageTMP.docx"); - - File expectedFile = OpenXML4JTestDataSamples.getSampleFile("TestCreatePackageOUTPUT.docx"); - - // Zap the target file, in case of an earlier run - if(targetFile.exists()) { - assertTrue(targetFile.delete()); - } - - // Create a package - OPCPackage pkg = OPCPackage.create(targetFile); - PackagePartName corePartName = PackagingURIHelper - .createPartName("/word/document.xml"); - - pkg.addRelationship(corePartName, TargetMode.INTERNAL, - PackageRelationshipTypes.CORE_DOCUMENT, "rId1"); - - PackagePart corePart = pkg - .createPart( - corePartName, - "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"); - - Document doc = DocumentHelper.createDocument(); - Element elDocument = doc.createElementNS("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w:document"); - doc.appendChild(elDocument); - Element elBody = doc.createElementNS("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w:body"); - elDocument.appendChild(elBody); - Element elParagraph = doc.createElementNS("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w:p"); - elBody.appendChild(elParagraph); - Element elRun = doc.createElementNS("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w:r"); - elParagraph.appendChild(elRun); - Element elText = doc.createElementNS("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w:t"); - elRun.appendChild(elText); - elText.setTextContent("Hello Open XML !"); - - StreamHelper.saveXmlInStream(doc, corePart.getOutputStream()); - pkg.close(); - - ZipFileAssert.assertEquals(expectedFile, targetFile); - assertTrue(targetFile.delete()); - } - - /** - * Tests that we can create a new package, add a core - * document and another part, save and re-load and - * have everything setup as expected - */ - @Test - public void createPackageWithCoreDocument() throws IOException, InvalidFormatException, URISyntaxException, SAXException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - OPCPackage pkg = OPCPackage.create(baos); - - // Add a core document - PackagePartName corePartName = PackagingURIHelper.createPartName("/xl/workbook.xml"); - // Create main part relationship - pkg.addRelationship(corePartName, TargetMode.INTERNAL, PackageRelationshipTypes.CORE_DOCUMENT, "rId1"); - // Create main document part - PackagePart corePart = pkg.createPart(corePartName, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"); - // Put in some dummy content - OutputStream coreOut = corePart.getOutputStream(); - coreOut.write("".getBytes("UTF-8")); - coreOut.close(); - - // And another bit - PackagePartName sheetPartName = PackagingURIHelper.createPartName("/xl/worksheets/sheet1.xml"); - PackageRelationship rel = - corePart.addRelationship(sheetPartName, TargetMode.INTERNAL, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet", "rSheet1"); - assertNotNull(rel); - - PackagePart part = pkg.createPart(sheetPartName, "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"); - assertNotNull(part); - - // Dummy content again - coreOut = corePart.getOutputStream(); - coreOut.write("".getBytes("UTF-8")); - coreOut.close(); - - //add a relationship with internal target: "#Sheet1!A1" - corePart.addRelationship(new URI("#Sheet1!A1"), TargetMode.INTERNAL, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink", "rId2"); - - // Check things are as expected - PackageRelationshipCollection coreRels = - pkg.getRelationshipsByType(PackageRelationshipTypes.CORE_DOCUMENT); - assertEquals(1, coreRels.size()); - PackageRelationship coreRel = coreRels.getRelationship(0); - assertNotNull(coreRel); - assertEquals("/", coreRel.getSourceURI().toString()); - assertEquals("/xl/workbook.xml", coreRel.getTargetURI().toString()); - assertNotNull(pkg.getPart(coreRel)); - - - // Save and re-load - pkg.close(); - File tmp = TempFile.createTempFile("testCreatePackageWithCoreDocument", ".zip"); - OutputStream fout = new FileOutputStream(tmp); - try { - fout.write(baos.toByteArray()); - } finally { - fout.close(); - } - pkg = OPCPackage.open(tmp.getPath()); - //tmp.delete(); - - try { - // Check still right - coreRels = pkg.getRelationshipsByType(PackageRelationshipTypes.CORE_DOCUMENT); - assertEquals(1, coreRels.size()); - coreRel = coreRels.getRelationship(0); - - assertNotNull(coreRel); - assertEquals("/", coreRel.getSourceURI().toString()); - assertEquals("/xl/workbook.xml", coreRel.getTargetURI().toString()); - corePart = pkg.getPart(coreRel); - assertNotNull(corePart); - - PackageRelationshipCollection rels = corePart.getRelationshipsByType("http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink"); - assertEquals(1, rels.size()); - rel = rels.getRelationship(0); - assertNotNull(rel); - assertEquals("Sheet1!A1", rel.getTargetURI().getRawFragment()); - - assertMSCompatibility(pkg); - } finally { - pkg.close(); - } - } - - private void assertMSCompatibility(OPCPackage pkg) throws IOException, InvalidFormatException, SAXException { - PackagePartName relName = PackagingURIHelper.createPartName(PackageRelationship.getContainerPartRelationship()); - PackagePart relPart = pkg.getPart(relName); - - Document xmlRelationshipsDoc = DocumentHelper.readDocument(relPart.getInputStream()); - - Element root = xmlRelationshipsDoc.getDocumentElement(); - NodeList nodeList = root.getElementsByTagName(PackageRelationship.RELATIONSHIP_TAG_NAME); - int nodeCount = nodeList.getLength(); - for (int i = 0; i < nodeCount; i++) { - Element element = (Element) nodeList.item(i); - String value = element.getAttribute(PackageRelationship.TARGET_ATTRIBUTE_NAME); - assertTrue("Root target must not start with a leading slash ('/'): " + value, value.charAt(0) != '/'); - } - - } - - /** - * Test package opening. - */ - @Test - public void openPackage() throws IOException, InvalidFormatException { - File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestOpenPackageTMP.docx"); - - File inputFile = OpenXML4JTestDataSamples.getSampleFile("TestOpenPackageINPUT.docx"); - - File expectedFile = OpenXML4JTestDataSamples.getSampleFile("TestOpenPackageOUTPUT.docx"); - - // Copy the input file in the output directory - FileHelper.copyFile(inputFile, targetFile); - - // Create a package - OPCPackage pkg = OPCPackage.open(targetFile.getAbsolutePath()); - - // Modify core part - PackagePartName corePartName = PackagingURIHelper - .createPartName("/word/document.xml"); - - PackagePart corePart = pkg.getPart(corePartName); - - // Delete some part to have a valid document - for (PackageRelationship rel : corePart.getRelationships()) { - corePart.removeRelationship(rel.getId()); - pkg.removePart(PackagingURIHelper.createPartName(PackagingURIHelper - .resolvePartUri(corePart.getPartName().getURI(), rel - .getTargetURI()))); - } - - // Create a content - Document doc = DocumentHelper.createDocument(); - Element elDocument = doc.createElementNS("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w:document"); - doc.appendChild(elDocument); - Element elBody = doc.createElementNS("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w:body"); - elDocument.appendChild(elBody); - Element elParagraph = doc.createElementNS("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w:p"); - elBody.appendChild(elParagraph); - Element elRun = doc.createElementNS("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w:r"); - elParagraph.appendChild(elRun); - Element elText = doc.createElementNS("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w:t"); - elRun.appendChild(elText); - elText.setTextContent("Hello Open XML !"); - - StreamHelper.saveXmlInStream(doc, corePart.getOutputStream()); - - // Save and close - try { - pkg.close(); - } catch (IOException e) { - fail(); - } - - ZipFileAssert.assertEquals(expectedFile, targetFile); - assertTrue(targetFile.delete()); - } - - /** - * Checks that we can write a package to a simple - * OutputStream, in addition to the normal writing - * to a file - */ - @Test - public void saveToOutputStream() throws IOException, InvalidFormatException { - String originalFile = OpenXML4JTestDataSamples.getSampleFileName("TestPackageCommon.docx"); - File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageOpenSaveTMP.docx"); - - @SuppressWarnings("resource") - OPCPackage p = OPCPackage.open(originalFile, PackageAccess.READ_WRITE); - try { - FileOutputStream fout = new FileOutputStream(targetFile); - try { - p.save(fout); - } finally { - fout.close(); - } - - // Compare the original and newly saved document - assertTrue(targetFile.exists()); - ZipFileAssert.assertEquals(new File(originalFile), targetFile); - assertTrue(targetFile.delete()); - } finally { - // use revert to not re-write the input file - p.revert(); - } - } - - /** - * Checks that we can open+read a package from a - * simple InputStream, in addition to the normal - * reading from a file - */ - @Test - public void openFromInputStream() throws IOException, InvalidFormatException { - String originalFile = OpenXML4JTestDataSamples.getSampleFileName("TestPackageCommon.docx"); - - FileInputStream finp = new FileInputStream(originalFile); - - @SuppressWarnings("resource") - OPCPackage p = OPCPackage.open(finp); - - assertNotNull(p); - assertNotNull(p.getRelationships()); - assertEquals(12, p.getParts().size()); - - // Check it has the usual bits - assertTrue(p.hasRelationships()); - assertTrue(p.containPart(PackagingURIHelper.createPartName("/_rels/.rels"))); - - p.revert(); - finp.close(); - } - - /** - * TODO: fix and enable - */ - @Test - @Ignore - public void removePartRecursive() throws IOException, InvalidFormatException, URISyntaxException { - String originalFile = OpenXML4JTestDataSamples.getSampleFileName("TestPackageCommon.docx"); - File targetFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageRemovePartRecursiveOUTPUT.docx"); - File tempFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageRemovePartRecursiveTMP.docx"); - - @SuppressWarnings("resource") - OPCPackage p = OPCPackage.open(originalFile, PackageAccess.READ_WRITE); - p.removePartRecursive(PackagingURIHelper.createPartName(new URI( - "/word/document.xml"))); - p.save(tempFile.getAbsoluteFile()); - - // Compare the original and newly saved document - assertTrue(targetFile.exists()); - ZipFileAssert.assertEquals(targetFile, tempFile); - assertTrue(targetFile.delete()); - - p.revert(); - } - - @Test - public void deletePart() throws InvalidFormatException { - TreeMap expectedValues; - TreeMap values; - - values = new TreeMap(); - - // Expected values - expectedValues = new TreeMap(); - expectedValues.put(PackagingURIHelper.createPartName("/_rels/.rels"), - "application/vnd.openxmlformats-package.relationships+xml"); - - expectedValues - .put(PackagingURIHelper.createPartName("/docProps/app.xml"), - "application/vnd.openxmlformats-officedocument.extended-properties+xml"); - expectedValues.put(PackagingURIHelper - .createPartName("/docProps/core.xml"), - "application/vnd.openxmlformats-package.core-properties+xml"); - expectedValues - .put(PackagingURIHelper.createPartName("/word/fontTable.xml"), - "application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml"); - expectedValues.put(PackagingURIHelper - .createPartName("/word/media/image1.gif"), "image/gif"); - expectedValues - .put(PackagingURIHelper.createPartName("/word/settings.xml"), - "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml"); - expectedValues - .put(PackagingURIHelper.createPartName("/word/styles.xml"), - "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"); - expectedValues.put(PackagingURIHelper - .createPartName("/word/theme/theme1.xml"), - "application/vnd.openxmlformats-officedocument.theme+xml"); - expectedValues - .put( - PackagingURIHelper - .createPartName("/word/webSettings.xml"), - "application/vnd.openxmlformats-officedocument.wordprocessingml.webSettings+xml"); - - String filepath = OpenXML4JTestDataSamples.getSampleFileName("sample.docx"); - - @SuppressWarnings("resource") - OPCPackage p = OPCPackage.open(filepath, PackageAccess.READ_WRITE); - // Remove the core part - p.deletePart(PackagingURIHelper.createPartName("/word/document.xml")); - - for (PackagePart part : p.getParts()) { - values.put(part.getPartName(), part.getContentType()); - logger.log(POILogger.DEBUG, part.getPartName()); - } - - // Compare expected values with values return by the package - for (PackagePartName partName : expectedValues.keySet()) { - assertNotNull(values.get(partName)); - assertEquals(expectedValues.get(partName), values.get(partName)); - } - // Don't save modifications - p.revert(); - } - - @Test - public void deletePartRecursive() throws InvalidFormatException { - TreeMap expectedValues; - TreeMap values; - - values = new TreeMap(); - - // Expected values - expectedValues = new TreeMap(); - expectedValues.put(PackagingURIHelper.createPartName("/_rels/.rels"), - "application/vnd.openxmlformats-package.relationships+xml"); - - expectedValues - .put(PackagingURIHelper.createPartName("/docProps/app.xml"), - "application/vnd.openxmlformats-officedocument.extended-properties+xml"); - expectedValues.put(PackagingURIHelper - .createPartName("/docProps/core.xml"), - "application/vnd.openxmlformats-package.core-properties+xml"); - - String filepath = OpenXML4JTestDataSamples.getSampleFileName("sample.docx"); - - @SuppressWarnings("resource") - OPCPackage p = OPCPackage.open(filepath, PackageAccess.READ_WRITE); - // Remove the core part - p.deletePartRecursive(PackagingURIHelper.createPartName("/word/document.xml")); - - for (PackagePart part : p.getParts()) { - values.put(part.getPartName(), part.getContentType()); - logger.log(POILogger.DEBUG, part.getPartName()); - } - - // Compare expected values with values return by the package - for (PackagePartName partName : expectedValues.keySet()) { - assertNotNull(values.get(partName)); - assertEquals(expectedValues.get(partName), values.get(partName)); - } - // Don't save modifications - p.revert(); - } - - /** - * Test that we can open a file by path, and then - * write changes to it. - */ - @Test - public void openFileThenOverwrite() throws IOException, InvalidFormatException { - File tempFile = TempFile.createTempFile("poiTesting","tmp"); - File origFile = OpenXML4JTestDataSamples.getSampleFile("TestPackageCommon.docx"); - FileHelper.copyFile(origFile, tempFile); - - // Open the temp file - OPCPackage p = OPCPackage.open(tempFile.toString(), PackageAccess.READ_WRITE); - // Close it - p.close(); - // Delete it - assertTrue(tempFile.delete()); - - // Reset - FileHelper.copyFile(origFile, tempFile); - p = OPCPackage.open(tempFile.toString(), PackageAccess.READ_WRITE); - - // Save it to the same file - not allowed - try { - p.save(tempFile); - fail("You shouldn't be able to call save(File) to overwrite the current file"); - } catch(InvalidOperationException e) { - // expected here - } - - p.close(); - // Delete it - assertTrue(tempFile.delete()); - - - // Open it read only, then close and delete - allowed - FileHelper.copyFile(origFile, tempFile); - p = OPCPackage.open(tempFile.toString(), PackageAccess.READ); - p.close(); - assertTrue(tempFile.delete()); - } - /** - * Test that we can open a file by path, save it - * to another file, then delete both - */ - @Test - public void openFileThenSaveDelete() throws IOException, InvalidFormatException { - File tempFile = TempFile.createTempFile("poiTesting","tmp"); - File tempFile2 = TempFile.createTempFile("poiTesting","tmp"); - File origFile = OpenXML4JTestDataSamples.getSampleFile("TestPackageCommon.docx"); - FileHelper.copyFile(origFile, tempFile); - - // Open the temp file - OPCPackage p = OPCPackage.open(tempFile.toString(), PackageAccess.READ_WRITE); - - // Save it to a different file - p.save(tempFile2); - p.close(); - - // Delete both the files - assertTrue(tempFile.delete()); - assertTrue(tempFile2.delete()); - } - - private static ContentTypeManager getContentTypeManager(OPCPackage pkg) { - return POITestCase.getFieldValue(OPCPackage.class, pkg, ContentTypeManager.class, "contentTypeManager"); - } - - @Test - public void getPartsByName() throws IOException, InvalidFormatException { - String filepath = OpenXML4JTestDataSamples.getSampleFileName("sample.docx"); - - @SuppressWarnings("resource") - OPCPackage pkg = OPCPackage.open(filepath, PackageAccess.READ_WRITE); - try { - List rs = pkg.getPartsByName(Pattern.compile("/word/.*?\\.xml")); - HashMap selected = new HashMap(); - - for(PackagePart p : rs) - selected.put(p.getPartName().getName(), p); - - assertEquals(6, selected.size()); - assertTrue(selected.containsKey("/word/document.xml")); - assertTrue(selected.containsKey("/word/fontTable.xml")); - assertTrue(selected.containsKey("/word/settings.xml")); - assertTrue(selected.containsKey("/word/styles.xml")); - assertTrue(selected.containsKey("/word/theme/theme1.xml")); - assertTrue(selected.containsKey("/word/webSettings.xml")); - } finally { - // use revert to not re-write the input file - pkg.revert(); - } - } - - @Test - public void getPartSize() throws IOException, InvalidFormatException { - String filepath = OpenXML4JTestDataSamples.getSampleFileName("sample.docx"); - OPCPackage pkg = OPCPackage.open(filepath, PackageAccess.READ); - try { - int checked = 0; - for (PackagePart part : pkg.getParts()) { - // Can get the size of zip parts - if (part.getPartName().getName().equals("/word/document.xml")) { - checked++; - assertEquals(ZipPackagePart.class, part.getClass()); - assertEquals(6031L, part.getSize()); - } - if (part.getPartName().getName().equals("/word/fontTable.xml")) { - checked++; - assertEquals(ZipPackagePart.class, part.getClass()); - assertEquals(1312L, part.getSize()); - } - - // But not from the others - if (part.getPartName().getName().equals("/docProps/core.xml")) { - checked++; - assertEquals(PackagePropertiesPart.class, part.getClass()); - assertEquals(-1, part.getSize()); - } - } - // Ensure we actually found the parts we want to check - assertEquals(3, checked); - } finally { - pkg.close(); - } - } - - @Test - public void replaceContentType() - throws IOException, InvalidFormatException, SecurityException, IllegalArgumentException, NoSuchFieldException, IllegalAccessException { - InputStream is = OpenXML4JTestDataSamples.openSampleStream("sample.xlsx"); - @SuppressWarnings("resource") - OPCPackage p = OPCPackage.open(is); - - ContentTypeManager mgr = getContentTypeManager(p); - - assertTrue(mgr.isContentTypeRegister("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml")); - assertFalse(mgr.isContentTypeRegister("application/vnd.ms-excel.sheet.macroEnabled.main+xml")); - - assertTrue( - p.replaceContentType( - "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml", - "application/vnd.ms-excel.sheet.macroEnabled.main+xml") - ); - - assertFalse(mgr.isContentTypeRegister("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml")); - assertTrue(mgr.isContentTypeRegister("application/vnd.ms-excel.sheet.macroEnabled.main+xml")); - p.revert(); - is.close(); - } - - /** - * Verify we give helpful exceptions (or as best we can) when - * supplied with non-OOXML file types (eg OLE2, ODF) - */ - @Test - public void NonOOXMLFileTypes() throws Exception { - // Spreadsheet has a good mix of alternate file types - POIDataSamples files = POIDataSamples.getSpreadSheetInstance(); - - // OLE2 - Stream - try { - InputStream stream = files.openResourceAsStream("SampleSS.xls"); - try { - OPCPackage.open(stream); - } finally { - stream.close(); - } - fail("Shouldn't be able to open OLE2"); - } catch (OLE2NotOfficeXmlFileException e) { - assertTrue(e.getMessage().contains("The supplied data appears to be in the OLE2 Format")); - assertTrue(e.getMessage().contains("You are calling the part of POI that deals with OOXML")); - } - // OLE2 - File - try { - OPCPackage.open(files.getFile("SampleSS.xls")); - fail("Shouldn't be able to open OLE2"); - } catch (OLE2NotOfficeXmlFileException e) { - assertTrue(e.getMessage().contains("The supplied data appears to be in the OLE2 Format")); - assertTrue(e.getMessage().contains("You are calling the part of POI that deals with OOXML")); - } - - // Raw XML - Stream - try { - InputStream stream = files.openResourceAsStream("SampleSS.xml"); - try { - OPCPackage.open(stream); - } finally { - stream.close(); - } - fail("Shouldn't be able to open XML"); - } catch (NotOfficeXmlFileException e) { - assertTrue(e.getMessage().contains("The supplied data appears to be a raw XML file")); - assertTrue(e.getMessage().contains("Formats such as Office 2003 XML")); - } - // Raw XML - File - try { - OPCPackage.open(files.getFile("SampleSS.xml")); - fail("Shouldn't be able to open XML"); - } catch (NotOfficeXmlFileException e) { - assertTrue(e.getMessage().contains("The supplied data appears to be a raw XML file")); - assertTrue(e.getMessage().contains("Formats such as Office 2003 XML")); - } - - // ODF / ODS - Stream - try { - InputStream stream = files.openResourceAsStream("SampleSS.ods"); - try { - OPCPackage.open(stream); - } finally { - stream.close(); - } - fail("Shouldn't be able to open ODS"); - } catch (ODFNotOfficeXmlFileException e) { - assertTrue(e.toString().contains("The supplied data appears to be in ODF")); - assertTrue(e.toString().contains("Formats like these (eg ODS")); - } - // ODF / ODS - File - try { - OPCPackage.open(files.getFile("SampleSS.ods")); - fail("Shouldn't be able to open ODS"); - } catch (ODFNotOfficeXmlFileException e) { - assertTrue(e.toString().contains("The supplied data appears to be in ODF")); - assertTrue(e.toString().contains("Formats like these (eg ODS")); - } - - // Plain Text - Stream - try { - InputStream stream = files.openResourceAsStream("SampleSS.txt"); - try { - OPCPackage.open(stream); - } finally { - stream.close(); - } - fail("Shouldn't be able to open Plain Text"); - } catch (NotOfficeXmlFileException e) { - assertTrue(e.getMessage().contains("No valid entries or contents found")); - assertTrue(e.getMessage().contains("not a valid OOXML")); - } - // Plain Text - File - try { - OPCPackage.open(files.getFile("SampleSS.txt")); - fail("Shouldn't be able to open Plain Text"); - } catch (UnsupportedFileFormatException e) { - // Unhelpful low-level error, sorry - } - } - - @Test(expected=IOException.class) - public void zipBombCreateAndHandle() - throws IOException, EncryptedDocumentException, InvalidFormatException { - // #50090 / #56865 - ZipFile zipFile = ZipHelper.openZipFile(OpenXML4JTestDataSamples.getSampleFile("sample.xlsx")); - assertNotNull(zipFile); - - ByteArrayOutputStream bos = new ByteArrayOutputStream(2500000); - ZipOutputStream append = new ZipOutputStream(bos); - // first, copy contents from existing war - Enumeration entries = zipFile.entries(); - while (entries.hasMoreElements()) { - ZipEntry e2 = entries.nextElement(); - ZipEntry e = new ZipEntry(e2.getName()); - e.setTime(e2.getTime()); - e.setComment(e2.getComment()); - e.setSize(e2.getSize()); - - append.putNextEntry(e); - if (!e.isDirectory()) { - InputStream is = zipFile.getInputStream(e); - if (e.getName().equals("[Content_Types].xml")) { - ByteArrayOutputStream bos2 = new ByteArrayOutputStream(); - IOUtils.copy(is, bos2); - long size = bos2.size()-"".length(); - append.write(bos2.toByteArray(), 0, (int)size); - byte spam[] = new byte[0x7FFF]; - for (int i=0; i".getBytes("UTF-8")); - size += 8; - e.setSize(size); - } else { - IOUtils.copy(is, append); - } - is.close(); - } - append.closeEntry(); - } - - append.close(); - zipFile.close(); - - byte buf[] = bos.toByteArray(); - //noinspection UnusedAssignment - bos = null; - - Workbook wb = WorkbookFactory.create(new ByteArrayInputStream(buf)); - wb.getSheetAt(0); - wb.close(); - zipFile.close(); - } - - @Test - public void zipBombSampleFiles() throws IOException, OpenXML4JException, XmlException { - openZipBombFile("poc-shared-strings.xlsx"); - openZipBombFile("poc-xmlbomb.xlsx"); - openZipBombFile("poc-xmlbomb-empty.xlsx"); - } - - private void openZipBombFile(String file) throws IOException, OpenXML4JException, XmlException { - try { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook(file); - wb.close(); - - POITextExtractor extractor = ExtractorFactory.createExtractor(HSSFTestDataSamples.getSampleFile("poc-shared-strings.xlsx")); - try { - assertNotNull(extractor); - extractor.getText(); - } finally { - extractor.close(); - } - - fail("Should catch an exception because of a ZipBomb"); - } catch (IllegalStateException e) { - if(!e.getMessage().contains("The text would exceed the max allowed overall size of extracted text.")) { - throw e; - } - } catch (POIXMLException e) { - checkForZipBombException(e); - } - } - - @Test - public void zipBombCheckSizes() throws IOException, EncryptedDocumentException, InvalidFormatException { - File file = OpenXML4JTestDataSamples.getSampleFile("sample.xlsx"); - - try { - double min_ratio = Double.MAX_VALUE; - long max_size = 0; - ZipFile zf = ZipHelper.openZipFile(file); - assertNotNull(zf); - Enumeration entries = zf.entries(); - while (entries.hasMoreElements()) { - ZipEntry ze = entries.nextElement(); - double ratio = (double)ze.getCompressedSize() / (double)ze.getSize(); - min_ratio = Math.min(min_ratio, ratio); - max_size = Math.max(max_size, ze.getSize()); - } - zf.close(); - - // use values close to, but within the limits - ZipSecureFile.setMinInflateRatio(min_ratio-0.002); - assertEquals(min_ratio-0.002, ZipSecureFile.getMinInflateRatio(), 0.00001); - ZipSecureFile.setMaxEntrySize(max_size+1); - assertEquals(max_size+1, ZipSecureFile.getMaxEntrySize()); - - WorkbookFactory.create(file, null, true).close(); - - // check ratio out of bounds - ZipSecureFile.setMinInflateRatio(min_ratio+0.002); - try { - WorkbookFactory.create(file, null, true).close(); - // this is a bit strange, as there will be different exceptions thrown - // depending if this executed via "ant test" or within eclipse - // maybe a difference in JDK ... - } catch (InvalidFormatException e) { - checkForZipBombException(e); - } catch (POIXMLException e) { - checkForZipBombException(e); - } - - // check max entry size ouf of bounds - ZipSecureFile.setMinInflateRatio(min_ratio-0.002); - ZipSecureFile.setMaxEntrySize(max_size-1); - try { - WorkbookFactory.create(file, null, true).close(); - } catch (InvalidFormatException e) { - checkForZipBombException(e); - } catch (POIXMLException e) { - checkForZipBombException(e); - } - } finally { - // reset otherwise a lot of ooxml tests will fail - ZipSecureFile.setMinInflateRatio(0.01d); - ZipSecureFile.setMaxEntrySize(0xFFFFFFFFL); - } - } - - private void checkForZipBombException(Throwable e) { - // unwrap InvocationTargetException as they usually contain the nested exception in the "target" member - if(e instanceof InvocationTargetException) { - e = ((InvocationTargetException)e).getTargetException(); - } - - String msg = e.getMessage(); - if(msg != null && (msg.startsWith("Zip bomb detected!") || - msg.contains("The parser has encountered more than \"4,096\" entity expansions in this document;") || - msg.contains("The parser has encountered more than \"4096\" entity expansions in this document;"))) { - return; - } - - // recursively check the causes for the message as it can be nested further down in the exception-tree - if(e.getCause() != null && e.getCause() != e) { - checkForZipBombException(e.getCause()); - return; - } - - throw new IllegalStateException("Expected to catch an Exception because of a detected Zip Bomb, but did not find the related error message in the exception", e); - } - - @Test - public void testConstructors() throws IOException { - // verify the various ways to construct a ZipSecureFile - File file = OpenXML4JTestDataSamples.getSampleFile("sample.xlsx"); - ZipSecureFile zipFile = new ZipSecureFile(file); - assertNotNull(zipFile.getName()); - zipFile.close(); - - zipFile = new ZipSecureFile(file, ZipFile.OPEN_READ); - assertNotNull(zipFile.getName()); - zipFile.close(); - - zipFile = new ZipSecureFile(file.getAbsolutePath()); - assertNotNull(zipFile.getName()); - zipFile.close(); - } - - @Test - public void testMaxTextSize() { - long before = ZipSecureFile.getMaxTextSize(); - try { - ZipSecureFile.setMaxTextSize(12345); - assertEquals(12345, ZipSecureFile.getMaxTextSize()); - } finally { - ZipSecureFile.setMaxTextSize(before); - } - } - - // bug 60128 - @Test - public void testCorruptFile() throws IOException { - OPCPackage pkg = null; - File file = OpenXML4JTestDataSamples.getSampleFile("invalid.xlsx"); - try { - pkg = OPCPackage.open(file, PackageAccess.READ); - } catch (Exception e) { - System.out.println(e.getClass().getName()); - System.out.println(e.getMessage()); - e.printStackTrace(); - } finally { - if (pkg != null) { - pkg.close(); - } - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackageCoreProperties.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackageCoreProperties.java deleted file mode 100644 index b29d21fc0..000000000 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackageCoreProperties.java +++ /dev/null @@ -1,327 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.InputStream; -import java.text.ParsePosition; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Locale; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.openxml4j.OpenXML4JTestDataSamples; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.internal.PackagePropertiesPart; -import org.apache.poi.openxml4j.util.Nullable; -import org.apache.poi.util.LocaleUtil; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Test; -import org.openxmlformats.schemas.officeDocument.x2006.customProperties.CTProperty; - -public final class TestPackageCoreProperties { - /** - * Test package core properties getters. - */ - @Test - public void testGetProperties() throws Exception { - // Open the package - @SuppressWarnings("resource") - OPCPackage p = OPCPackage.open(OpenXML4JTestDataSamples.openSampleStream("TestPackageCoreProperiesGetters.docx")); - compareProperties(p); - p.revert(); - } - - /** - * Test package core properties setters. - */ - @Test - public void testSetProperties() throws Exception { - String inputPath = OpenXML4JTestDataSamples.getSampleFileName("TestPackageCoreProperiesSetters.docx"); - - File outputFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageCoreProperiesSettersOUTPUT.docx"); - - // Open package - @SuppressWarnings("resource") - OPCPackage p = OPCPackage.open(inputPath, PackageAccess.READ_WRITE); - SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ROOT); - df.setTimeZone(LocaleUtil.TIMEZONE_UTC); - Date dateToInsert = df.parse("2007-05-12T08:00:00Z", new ParsePosition(0)); - - SimpleDateFormat msdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ROOT); - msdf.setTimeZone(LocaleUtil.TIMEZONE_UTC); - - PackageProperties props = p.getPackageProperties(); - - //test various date formats - props.setCreatedProperty("2007-05-12T08:00:00Z"); - assertEquals(dateToInsert, props.getCreatedProperty().getValue()); - - props.setCreatedProperty("2007-05-12T08:00:00"); //no Z, assume Z - assertEquals(dateToInsert, props.getCreatedProperty().getValue()); - - props.setCreatedProperty("2007-05-12T08:00:00.123Z");//millis - assertEquals(msdf.parse("2007-05-12T08:00:00.123Z"), props.getCreatedProperty().getValue()); - - props.setCreatedProperty("2007-05-12T10:00:00+0200"); - assertEquals(dateToInsert, props.getCreatedProperty().getValue()); - - props.setCreatedProperty("2007-05-12T10:00:00+02:00");//colon in tz - assertEquals(dateToInsert, props.getCreatedProperty().getValue()); - - props.setCreatedProperty("2007-05-12T06:00:00-0200"); - assertEquals(dateToInsert, props.getCreatedProperty().getValue()); - - props.setCreatedProperty("2015-07-27"); - assertEquals(msdf.parse("2015-07-27T00:00:00.000Z"), props.getCreatedProperty().getValue()); - - props.setCreatedProperty("2007-05-12T10:00:00.123+0200"); - assertEquals(msdf.parse("2007-05-12T08:00:00.123Z"), props.getCreatedProperty().getValue()); - - props.setCategoryProperty("MyCategory"); - props.setContentStatusProperty("MyContentStatus"); - props.setContentTypeProperty("MyContentType"); - props.setCreatorProperty("MyCreator"); - props.setDescriptionProperty("MyDescription"); - props.setIdentifierProperty("MyIdentifier"); - props.setKeywordsProperty("MyKeywords"); - props.setLanguageProperty("MyLanguage"); - props.setLastModifiedByProperty("Julien Chable"); - props.setLastPrintedProperty(new Nullable(dateToInsert)); - props.setModifiedProperty(new Nullable(dateToInsert)); - props.setRevisionProperty("2"); - props.setTitleProperty("MyTitle"); - props.setSubjectProperty("MySubject"); - props.setVersionProperty("2"); - // Save the package in the output directory - p.save(outputFile); - p.revert(); - - // Open the newly created file to check core properties saved values. - @SuppressWarnings("resource") - OPCPackage p2 = OPCPackage.open(outputFile.getAbsolutePath(), PackageAccess.READ); - compareProperties(p2); - p2.revert(); - outputFile.delete(); - } - - private void compareProperties(OPCPackage p) throws InvalidFormatException { - SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ROOT); - df.setTimeZone(LocaleUtil.TIMEZONE_UTC); - Date expectedDate = df.parse("2007-05-12T08:00:00Z", new ParsePosition(0)); - - // Gets the core properties - PackageProperties props = p.getPackageProperties(); - assertEquals("MyCategory", props.getCategoryProperty().getValue()); - assertEquals("MyContentStatus", props.getContentStatusProperty().getValue()); - assertEquals("MyContentType", props.getContentTypeProperty().getValue()); - assertEquals(expectedDate, props.getCreatedProperty().getValue()); - assertEquals("MyCreator", props.getCreatorProperty().getValue()); - assertEquals("MyDescription", props.getDescriptionProperty().getValue()); - assertEquals("MyIdentifier", props.getIdentifierProperty().getValue()); - assertEquals("MyKeywords", props.getKeywordsProperty().getValue()); - assertEquals("MyLanguage", props.getLanguageProperty().getValue()); - assertEquals("Julien Chable", props.getLastModifiedByProperty().getValue()); - assertEquals(expectedDate, props.getLastPrintedProperty().getValue()); - assertEquals(expectedDate, props.getModifiedProperty().getValue()); - assertEquals("2", props.getRevisionProperty().getValue()); - assertEquals("MySubject", props.getSubjectProperty().getValue()); - assertEquals("MyTitle", props.getTitleProperty().getValue()); - assertEquals("2", props.getVersionProperty().getValue()); - } - - @Test - public void testCoreProperties_bug51374() throws Exception { - SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ROOT); - df.setTimeZone(LocaleUtil.TIMEZONE_UTC); - String strDate = "2007-05-12T08:00:00Z"; - Date date = df.parse(strDate); - - OPCPackage pkg = new ZipPackage(); - PackagePropertiesPart props = (PackagePropertiesPart)pkg.getPackageProperties(); - - // created - assertEquals("", props.getCreatedPropertyString()); - assertNull(props.getCreatedProperty().getValue()); - props.setCreatedProperty((String)null); - assertEquals("", props.getCreatedPropertyString()); - assertNull(props.getCreatedProperty().getValue()); - props.setCreatedProperty(new Nullable()); - assertEquals("", props.getCreatedPropertyString()); - assertNull(props.getCreatedProperty().getValue()); - props.setCreatedProperty(new Nullable(date)); - assertEquals(strDate, props.getCreatedPropertyString()); - assertEquals(date, props.getCreatedProperty().getValue()); - props.setCreatedProperty(strDate); - assertEquals(strDate, props.getCreatedPropertyString()); - assertEquals(date, props.getCreatedProperty().getValue()); - - // lastPrinted - assertEquals("", props.getLastPrintedPropertyString()); - assertNull(props.getLastPrintedProperty().getValue()); - props.setLastPrintedProperty((String)null); - assertEquals("", props.getLastPrintedPropertyString()); - assertNull(props.getLastPrintedProperty().getValue()); - props.setLastPrintedProperty(new Nullable()); - assertEquals("", props.getLastPrintedPropertyString()); - assertNull(props.getLastPrintedProperty().getValue()); - props.setLastPrintedProperty(new Nullable(date)); - assertEquals(strDate, props.getLastPrintedPropertyString()); - assertEquals(date, props.getLastPrintedProperty().getValue()); - props.setLastPrintedProperty(strDate); - assertEquals(strDate, props.getLastPrintedPropertyString()); - assertEquals(date, props.getLastPrintedProperty().getValue()); - - // modified - assertNull(props.getModifiedProperty().getValue()); - props.setModifiedProperty((String)null); - assertNull(props.getModifiedProperty().getValue()); - props.setModifiedProperty(new Nullable()); - assertNull(props.getModifiedProperty().getValue()); - props.setModifiedProperty(new Nullable(date)); - assertEquals(strDate, props.getModifiedPropertyString()); - assertEquals(date, props.getModifiedProperty().getValue()); - props.setModifiedProperty(strDate); - assertEquals(strDate, props.getModifiedPropertyString()); - assertEquals(date, props.getModifiedProperty().getValue()); - - // Tidy - pkg.close(); - } - - @Test - public void testGetPropertiesLO() throws Exception { - // Open the package - OPCPackage pkg1 = OPCPackage.open(OpenXML4JTestDataSamples.openSampleStream("51444.xlsx")); - PackageProperties props1 = pkg1.getPackageProperties(); - assertEquals(null, props1.getTitleProperty().getValue()); - props1.setTitleProperty("Bug 51444 fixed"); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - pkg1.save(out); - out.close(); - pkg1.close(); - - OPCPackage pkg2 = OPCPackage.open(new ByteArrayInputStream(out.toByteArray())); - PackageProperties props2 = pkg2.getPackageProperties(); - props2.setTitleProperty("Bug 51444 fixed"); - pkg2.close(); - } - - @Test - public void testEntitiesInCoreProps_56164() throws Exception { - InputStream is = OpenXML4JTestDataSamples.openSampleStream("CorePropertiesHasEntities.ooxml"); - OPCPackage p = OPCPackage.open(is); - is.close(); - - // Should have 3 root relationships - boolean foundDocRel = false, foundCorePropRel = false, foundExtPropRel = false; - for (PackageRelationship pr : p.getRelationships()) { - if (pr.getRelationshipType().equals(PackageRelationshipTypes.CORE_DOCUMENT)) - foundDocRel = true; - if (pr.getRelationshipType().equals(PackageRelationshipTypes.CORE_PROPERTIES)) - foundCorePropRel = true; - if (pr.getRelationshipType().equals(PackageRelationshipTypes.EXTENDED_PROPERTIES)) - foundExtPropRel = true; - } - assertTrue("Core/Doc Relationship not found in " + p.getRelationships(), foundDocRel); - assertTrue("Core Props Relationship not found in " + p.getRelationships(), foundCorePropRel); - assertTrue("Ext Props Relationship not found in " + p.getRelationships(), foundExtPropRel); - - // Get the Core Properties - PackagePropertiesPart props = (PackagePropertiesPart)p.getPackageProperties(); - - // Check - assertEquals("Stefan Kopf", props.getCreatorProperty().getValue()); - - p.close(); - } - - @Test - public void testListOfCustomProperties() throws Exception { - File inp = POIDataSamples.getSpreadSheetInstance().getFile("ExcelWithAttachments.xlsm"); - OPCPackage pkg = OPCPackage.open(inp, PackageAccess.READ); - XSSFWorkbook wb = new XSSFWorkbook(pkg); - - assertNotNull(wb.getProperties()); - assertNotNull(wb.getProperties().getCustomProperties()); - - for (CTProperty prop : wb.getProperties().getCustomProperties().getUnderlyingProperties().getPropertyList()) { - assertNotNull(prop); - } - - wb.close(); - pkg.close(); - } - - @Test - public void testAlternateCorePropertyTimezones() throws Exception { - InputStream is = OpenXML4JTestDataSamples.openSampleStream("OPCCompliance_CoreProperties_AlternateTimezones.docx"); - OPCPackage pkg = OPCPackage.open(is); - PackagePropertiesPart props = (PackagePropertiesPart)pkg.getPackageProperties(); - is.close(); - - // We need predictable dates for testing! - SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ROOT); - df.setTimeZone(LocaleUtil.TIMEZONE_UTC); - - // Check text properties first - assertEquals("Lorem Ipsum", props.getTitleProperty().getValue()); - assertEquals("Apache POI", props.getCreatorProperty().getValue()); - - // Created at has a +3 timezone and milliseconds - // 2006-10-13T18:06:00.123+03:00 - // = 2006-10-13T15:06:00.123+00:00 - assertEquals("2006-10-13T15:06:00Z", props.getCreatedPropertyString()); - assertEquals("2006-10-13T15:06:00.123Z", df.format(props.getCreatedProperty().getValue())); - - // Modified at has a -13 timezone but no milliseconds - // 2007-06-20T07:59:00-13:00 - // = 2007-06-20T20:59:00-13:00 - assertEquals("2007-06-20T20:59:00Z", props.getModifiedPropertyString()); - assertEquals("2007-06-20T20:59:00.000Z", df.format(props.getModifiedProperty().getValue())); - - - // Ensure we can change them with other timezones and still read back OK - props.setCreatedProperty("2007-06-20T20:57:00+13:00"); - props.setModifiedProperty("2007-06-20T20:59:00.123-13:00"); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - pkg.save(baos); - pkg = OPCPackage.open(new ByteArrayInputStream(baos.toByteArray())); - - // Check text properties first - should be unchanged - assertEquals("Lorem Ipsum", props.getTitleProperty().getValue()); - assertEquals("Apache POI", props.getCreatorProperty().getValue()); - - // Check the updated times - // 2007-06-20T20:57:00+13:00 - // = 2007-06-20T07:57:00Z - assertEquals("2007-06-20T07:57:00.000Z", df.format(props.getCreatedProperty().getValue())); - - // 2007-06-20T20:59:00.123-13:00 - // = 2007-06-21T09:59:00.123Z - assertEquals("2007-06-21T09:59:00.123Z", df.format(props.getModifiedProperty().getValue())); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackagePartName.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackagePartName.java deleted file mode 100644 index ed9b90093..000000000 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackagePartName.java +++ /dev/null @@ -1,36 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc; - -import org.apache.poi.openxml4j.opc.PackagePartName; -import org.apache.poi.openxml4j.opc.PackagingURIHelper; - -import junit.framework.TestCase; - -public final class TestPackagePartName extends TestCase { - - /** - * Test method getExtension(). - */ - public void testGetExtension() throws Exception{ - PackagePartName name1 = PackagingURIHelper.createPartName("/doc/props/document.xml"); - PackagePartName name2 = PackagingURIHelper.createPartName("/root/document"); - assertEquals("xml", name1.getExtension()); - assertEquals("", name2.getExtension()); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackageThumbnail.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackageThumbnail.java deleted file mode 100644 index 432bd896c..000000000 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackageThumbnail.java +++ /dev/null @@ -1,65 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc; - -import java.io.File; - -import junit.framework.TestCase; - -import org.apache.poi.openxml4j.OpenXML4JTestDataSamples; - -/** - * Test the addition of thumbnail in a package. - * - * @author Julien Chable - */ -public final class TestPackageThumbnail extends TestCase { - - /** - * Test package addThumbnail() method. - */ - public void testSetProperties() throws Exception { - String inputPath = OpenXML4JTestDataSamples.getSampleFileName("TestPackageThumbnail.docx"); - - String imagePath = OpenXML4JTestDataSamples.getSampleFileName("thumbnail.jpg"); - - File outputFile = OpenXML4JTestDataSamples.getOutputFile("TestPackageThumbnailOUTPUT.docx"); - - // Open package - OPCPackage p = OPCPackage.open(inputPath, PackageAccess.READ_WRITE); - try { - p.addThumbnail(imagePath); - // Save the package in the output directory - p.save(outputFile); - - // Open the newly created file to check core properties saved values. - OPCPackage p2 = OPCPackage.open(outputFile.getAbsolutePath(), PackageAccess.READ); - try { - if (p2.getRelationshipsByType(PackageRelationshipTypes.THUMBNAIL) - .size() == 0) - fail("Thumbnail not added to the package !"); - } finally { - p2.revert(); - p2.close(); - } - } finally { - p.revert(); - outputFile.delete(); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackagingURIHelper.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackagingURIHelper.java deleted file mode 100644 index 39ab5ed4d..000000000 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackagingURIHelper.java +++ /dev/null @@ -1,145 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.openxml4j.opc; - -import java.net.URI; -import java.net.URISyntaxException; - -import junit.framework.TestCase; - -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.ContentTypes; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.opc.PackagePartName; -import org.apache.poi.openxml4j.opc.PackagingURIHelper; - -public class TestPackagingURIHelper extends TestCase { - - /** - * Test relativizePartName() method. - */ - public void testRelativizeURI() throws Exception { - URI uri1 = new URI("/word/document.xml"); - URI uri2 = new URI("/word/media/image1.gif"); - URI uri3 = new URI("/word/media/image1.gif#Sheet1!A1"); - URI uri4 = new URI("#'My%20Sheet1'!A1"); - - // Document to image is down a directory - URI retURI1to2 = PackagingURIHelper.relativizeURI(uri1, uri2); - assertEquals("media/image1.gif", retURI1to2.getPath()); - // Image to document is up a directory - URI retURI2to1 = PackagingURIHelper.relativizeURI(uri2, uri1); - assertEquals("../document.xml", retURI2to1.getPath()); - - // Document and CustomXML parts totally different [Julien C.] - URI uriCustomXml = new URI("/customXml/item1.xml"); - URI uriRes = PackagingURIHelper.relativizeURI(uri1, uriCustomXml); - assertEquals("../customXml/item1.xml", uriRes.toString()); - - // Document to itself is the same place (empty URI) - URI retURI2 = PackagingURIHelper.relativizeURI(uri1, uri1); - // YK: the line below used to assert empty string which is wrong - // if source and target are the same they should be relaitivized as the last segment, - // see Bugzilla 51187 - assertEquals("document.xml", retURI2.getPath()); - - // relativization against root - URI root = new URI("/"); - uriRes = PackagingURIHelper.relativizeURI(root, uri1); - assertEquals("/word/document.xml", uriRes.toString()); - - //URI compatible with MS Office and OpenOffice: leading slash is removed - uriRes = PackagingURIHelper.relativizeURI(root, uri1, true); - assertEquals("word/document.xml", uriRes.toString()); - - //preserve URI fragments - uriRes = PackagingURIHelper.relativizeURI(uri1, uri3, true); - assertEquals("media/image1.gif#Sheet1!A1", uriRes.toString()); - uriRes = PackagingURIHelper.relativizeURI(root, uri4, true); - assertEquals("#'My%20Sheet1'!A1", uriRes.toString()); - } - - /** - * Test createPartName(String, y) - */ - public void testCreatePartNameRelativeString() - throws InvalidFormatException { - PackagePartName partNameToValid = PackagingURIHelper - .createPartName("/word/media/image1.gif"); - - OPCPackage pkg = OPCPackage.create("DELETEIFEXISTS.docx"); - // Base part - PackagePartName nameBase = PackagingURIHelper - .createPartName("/word/document.xml"); - PackagePart partBase = pkg.createPart(nameBase, ContentTypes.XML); - // Relative part name - PackagePartName relativeName = PackagingURIHelper.createPartName( - "media/image1.gif", partBase); - assertTrue("The part name must be equal to " - + partNameToValid.getName(), partNameToValid - .equals(relativeName)); - pkg.revert(); - } - - /** - * Test createPartName(URI, y) - */ - public void testCreatePartNameRelativeURI() throws Exception { - PackagePartName partNameToValid = PackagingURIHelper - .createPartName("/word/media/image1.gif"); - - OPCPackage pkg = OPCPackage.create("DELETEIFEXISTS.docx"); - // Base part - PackagePartName nameBase = PackagingURIHelper - .createPartName("/word/document.xml"); - PackagePart partBase = pkg.createPart(nameBase, ContentTypes.XML); - // Relative part name - PackagePartName relativeName = PackagingURIHelper.createPartName( - new URI("media/image1.gif"), partBase); - assertTrue("The part name must be equal to " - + partNameToValid.getName(), partNameToValid - .equals(relativeName)); - pkg.revert(); - } - - public void testCreateURIFromString() throws Exception { - String[] href = { - "..\\\\\\cygwin\\home\\yegor\\.vim\\filetype.vim", - "..\\Program%20Files\\AGEIA%20Technologies\\v2.3.3\\NxCooking.dll", - "file:///D:\\seva\\1981\\r810102ns.mp3", - "..\\cygwin\\home\\yegor\\dinom\\%5baccess%5d.2010-10-26.log", - "#'Instructions (Text)'!B21", - "javascript://" - }; - for(String s : href){ - try { - URI uri = PackagingURIHelper.toURI(s); - } catch (URISyntaxException e){ - fail("Failed to create URI from " + s); - } - } - } - - public void test53734() throws Exception { - URI uri = PackagingURIHelper.toURI("javascript://"); - // POI appends a trailing slash tpo avoid "Expected authority at index 13: javascript://" - // https://issues.apache.org/bugzilla/show_bug.cgi?id=53734 - assertEquals("javascript:///", uri.toASCIIString()); - } - -} diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestRelationships.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestRelationships.java deleted file mode 100644 index cf485ed1f..000000000 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestRelationships.java +++ /dev/null @@ -1,445 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.InputStream; -import java.net.URI; -import java.util.regex.Pattern; - -import junit.framework.TestCase; - -import org.apache.poi.openxml4j.OpenXML4JTestDataSamples; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.xwpf.usermodel.XWPFRelation; - - -public class TestRelationships extends TestCase { - private static final String HYPERLINK_REL_TYPE = - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink"; - private static final String COMMENTS_REL_TYPE = - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments"; - private static final String SHEET_WITH_COMMENTS = - "/xl/worksheets/sheet1.xml"; - - private static final POILogger logger = POILogFactory.getLogger(TestPackageCoreProperties.class); - - /** - * Test relationships are correctly loaded. This at the moment fails (as of r499) - * whenever a document is loaded before its correspondig .rels file has been found. - * The code in this case assumes there are no relationships defined, but it should - * really look also for not yet loaded parts. - */ - public void testLoadRelationships() throws Exception { - InputStream is = OpenXML4JTestDataSamples.openSampleStream("sample.xlsx"); - OPCPackage pkg = OPCPackage.open(is); - logger.log(POILogger.DEBUG, "1: " + pkg); - PackageRelationshipCollection rels = pkg.getRelationshipsByType(PackageRelationshipTypes.CORE_DOCUMENT); - PackageRelationship coreDocRelationship = rels.getRelationship(0); - PackagePart corePart = pkg.getPart(coreDocRelationship); - String relIds[] = { "rId1", "rId2", "rId3" }; - for (String relId : relIds) { - PackageRelationship rel = corePart.getRelationship(relId); - assertNotNull(rel); - PackagePartName relName = PackagingURIHelper.createPartName(rel.getTargetURI()); - PackagePart sheetPart = pkg.getPart(relName); - assertEquals("Number of relationships1 for " + sheetPart.getPartName(), 1, sheetPart.getRelationships().size()); - } - } - - /** - * Checks that we can fetch a collection of relations by - * type, then grab from within there by id - */ - public void testFetchFromCollection() throws Exception { - InputStream is = OpenXML4JTestDataSamples.openSampleStream("ExcelWithHyperlinks.xlsx"); - OPCPackage pkg = OPCPackage.open(is); - PackagePart sheet = pkg.getPart( - PackagingURIHelper.createPartName(SHEET_WITH_COMMENTS)); - assertNotNull(sheet); - - assertTrue(sheet.hasRelationships()); - assertEquals(6, sheet.getRelationships().size()); - - // Should have three hyperlinks, and one comment - PackageRelationshipCollection hyperlinks = - sheet.getRelationshipsByType(HYPERLINK_REL_TYPE); - PackageRelationshipCollection comments = - sheet.getRelationshipsByType(COMMENTS_REL_TYPE); - assertEquals(3, hyperlinks.size()); - assertEquals(1, comments.size()); - - // Check we can get bits out by id - // Hyperlinks are rId1, rId2 and rId3 - // Comment is rId6 - assertNotNull(hyperlinks.getRelationshipByID("rId1")); - assertNotNull(hyperlinks.getRelationshipByID("rId2")); - assertNotNull(hyperlinks.getRelationshipByID("rId3")); - assertNull(hyperlinks.getRelationshipByID("rId6")); - - assertNull(comments.getRelationshipByID("rId1")); - assertNull(comments.getRelationshipByID("rId2")); - assertNull(comments.getRelationshipByID("rId3")); - assertNotNull(comments.getRelationshipByID("rId6")); - - assertNotNull(sheet.getRelationship("rId1")); - assertNotNull(sheet.getRelationship("rId2")); - assertNotNull(sheet.getRelationship("rId3")); - assertNotNull(sheet.getRelationship("rId6")); - } - - /** - * Excel uses relations on sheets to store the details of - * external hyperlinks. Check we can load these ok. - */ - public void testLoadExcelHyperlinkRelations() throws Exception { - InputStream is = OpenXML4JTestDataSamples.openSampleStream("ExcelWithHyperlinks.xlsx"); - OPCPackage pkg = OPCPackage.open(is); - PackagePart sheet = pkg.getPart( - PackagingURIHelper.createPartName(SHEET_WITH_COMMENTS)); - assertNotNull(sheet); - - // rId1 is url - PackageRelationship url = sheet.getRelationship("rId1"); - assertNotNull(url); - assertEquals("rId1", url.getId()); - assertEquals("/xl/worksheets/sheet1.xml", url.getSourceURI().toString()); - assertEquals("http://poi.apache.org/", url.getTargetURI().toString()); - - // rId2 is file - PackageRelationship file = sheet.getRelationship("rId2"); - assertNotNull(file); - assertEquals("rId2", file.getId()); - assertEquals("/xl/worksheets/sheet1.xml", file.getSourceURI().toString()); - assertEquals("WithVariousData.xlsx", file.getTargetURI().toString()); - - // rId3 is mailto - PackageRelationship mailto = sheet.getRelationship("rId3"); - assertNotNull(mailto); - assertEquals("rId3", mailto.getId()); - assertEquals("/xl/worksheets/sheet1.xml", mailto.getSourceURI().toString()); - assertEquals("mailto:dev@poi.apache.org?subject=XSSF%20Hyperlinks", mailto.getTargetURI().toString()); - } - - /* - * Excel uses relations on sheets to store the details of - * external hyperlinks. Check we can create these OK, - * then still read them later - */ - public void testCreateExcelHyperlinkRelations() throws Exception { - String filepath = OpenXML4JTestDataSamples.getSampleFileName("ExcelWithHyperlinks.xlsx"); - OPCPackage pkg = OPCPackage.open(filepath, PackageAccess.READ_WRITE); - PackagePart sheet = pkg.getPart( - PackagingURIHelper.createPartName(SHEET_WITH_COMMENTS)); - assertNotNull(sheet); - - assertEquals(3, sheet.getRelationshipsByType(HYPERLINK_REL_TYPE).size()); - - // Add three new ones - PackageRelationship openxml4j = - sheet.addExternalRelationship("http://www.openxml4j.org/", HYPERLINK_REL_TYPE); - PackageRelationship sf = - sheet.addExternalRelationship("http://openxml4j.sf.net/", HYPERLINK_REL_TYPE); - PackageRelationship file = - sheet.addExternalRelationship("MyDocument.docx", HYPERLINK_REL_TYPE); - - // Check they were added properly - assertNotNull(openxml4j); - assertNotNull(sf); - assertNotNull(file); - - assertEquals(6, sheet.getRelationshipsByType(HYPERLINK_REL_TYPE).size()); - - assertEquals("http://www.openxml4j.org/", openxml4j.getTargetURI().toString()); - assertEquals("/xl/worksheets/sheet1.xml", openxml4j.getSourceURI().toString()); - assertEquals(HYPERLINK_REL_TYPE, openxml4j.getRelationshipType()); - - assertEquals("http://openxml4j.sf.net/", sf.getTargetURI().toString()); - assertEquals("/xl/worksheets/sheet1.xml", sf.getSourceURI().toString()); - assertEquals(HYPERLINK_REL_TYPE, sf.getRelationshipType()); - - assertEquals("MyDocument.docx", file.getTargetURI().toString()); - assertEquals("/xl/worksheets/sheet1.xml", file.getSourceURI().toString()); - assertEquals(HYPERLINK_REL_TYPE, file.getRelationshipType()); - - // Will get ids 7, 8 and 9, as we already have 1-6 - assertEquals("rId7", openxml4j.getId()); - assertEquals("rId8", sf.getId()); - assertEquals("rId9", file.getId()); - - - // Write out and re-load - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - pkg.save(baos); - - // use revert to not re-write the input file - pkg.revert(); - - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - pkg = OPCPackage.open(bais); - - // Check again - sheet = pkg.getPart( - PackagingURIHelper.createPartName(SHEET_WITH_COMMENTS)); - - assertEquals(6, sheet.getRelationshipsByType(HYPERLINK_REL_TYPE).size()); - - assertEquals("http://poi.apache.org/", - sheet.getRelationship("rId1").getTargetURI().toString()); - assertEquals("mailto:dev@poi.apache.org?subject=XSSF%20Hyperlinks", - sheet.getRelationship("rId3").getTargetURI().toString()); - - assertEquals("http://www.openxml4j.org/", - sheet.getRelationship("rId7").getTargetURI().toString()); - assertEquals("http://openxml4j.sf.net/", - sheet.getRelationship("rId8").getTargetURI().toString()); - assertEquals("MyDocument.docx", - sheet.getRelationship("rId9").getTargetURI().toString()); - } - - public void testCreateRelationsFromScratch() throws Exception { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - OPCPackage pkg = OPCPackage.create(baos); - - PackagePart partA = - pkg.createPart(PackagingURIHelper.createPartName("/partA"), "text/plain"); - PackagePart partB = - pkg.createPart(PackagingURIHelper.createPartName("/partB"), "image/png"); - assertNotNull(partA); - assertNotNull(partB); - - // Internal - partA.addRelationship(partB.getPartName(), TargetMode.INTERNAL, "http://example/Rel"); - - // External - partA.addExternalRelationship("http://poi.apache.org/", "http://example/poi"); - partB.addExternalRelationship("http://poi.apache.org/ss/", "http://example/poi/ss"); - - // Check as expected currently - assertEquals("/partB", partA.getRelationship("rId1").getTargetURI().toString()); - assertEquals("http://poi.apache.org/", - partA.getRelationship("rId2").getTargetURI().toString()); - assertEquals("http://poi.apache.org/ss/", - partB.getRelationship("rId1").getTargetURI().toString()); - - - // Save, and re-load - pkg.close(); - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - pkg = OPCPackage.open(bais); - - partA = pkg.getPart(PackagingURIHelper.createPartName("/partA")); - partB = pkg.getPart(PackagingURIHelper.createPartName("/partB")); - - - // Check the relations - assertEquals(2, partA.getRelationships().size()); - assertEquals(1, partB.getRelationships().size()); - - assertEquals("/partB", partA.getRelationship("rId1").getTargetURI().toString()); - assertEquals("http://poi.apache.org/", - partA.getRelationship("rId2").getTargetURI().toString()); - assertEquals("http://poi.apache.org/ss/", - partB.getRelationship("rId1").getTargetURI().toString()); - // Check core too - assertEquals("/docProps/core.xml", - pkg.getRelationshipsByType("http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties").getRelationship(0).getTargetURI().toString()); - - - // Add some more - partB.addExternalRelationship("http://poi.apache.org/new", "http://example/poi/new"); - partB.addExternalRelationship("http://poi.apache.org/alt", "http://example/poi/alt"); - - // Check the relations - assertEquals(2, partA.getRelationships().size()); - assertEquals(3, partB.getRelationships().size()); - - assertEquals("/partB", partA.getRelationship("rId1").getTargetURI().toString()); - assertEquals("http://poi.apache.org/", - partA.getRelationship("rId2").getTargetURI().toString()); - assertEquals("http://poi.apache.org/ss/", - partB.getRelationship("rId1").getTargetURI().toString()); - assertEquals("http://poi.apache.org/new", - partB.getRelationship("rId2").getTargetURI().toString()); - assertEquals("http://poi.apache.org/alt", - partB.getRelationship("rId3").getTargetURI().toString()); - } - - - public void testTargetWithSpecialChars() throws Exception{ - OPCPackage pkg; - - String filepath = OpenXML4JTestDataSamples.getSampleFileName("50154.xlsx"); - pkg = OPCPackage.open(filepath); - assert_50154(pkg); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - pkg.save(baos); - - // use revert to not re-write the input file - pkg.revert(); - - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - pkg = OPCPackage.open(bais); - - assert_50154(pkg); - } - - public void assert_50154(OPCPackage pkg) throws Exception { - URI drawingURI = new URI("/xl/drawings/drawing1.xml"); - PackagePart drawingPart = pkg.getPart(PackagingURIHelper.createPartName(drawingURI)); - PackageRelationshipCollection drawingRels = drawingPart.getRelationships(); - - assertEquals(6, drawingRels.size()); - - // expected one image - assertEquals(1, drawingPart.getRelationshipsByType("http://schemas.openxmlformats.org/officeDocument/2006/relationships/image").size()); - // and three hyperlinks - assertEquals(5, drawingPart.getRelationshipsByType("http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink").size()); - - PackageRelationship rId1 = drawingPart.getRelationship("rId1"); - URI parent = drawingPart.getPartName().getURI(); - URI rel1 = parent.relativize(rId1.getTargetURI()); - URI rel11 = PackagingURIHelper.relativizeURI(drawingPart.getPartName().getURI(), rId1.getTargetURI()); - assertEquals("'Another Sheet'!A1", rel1.getFragment()); - assertEquals("'Another Sheet'!A1", rel11.getFragment()); - - PackageRelationship rId2 = drawingPart.getRelationship("rId2"); - URI rel2 = PackagingURIHelper.relativizeURI(drawingPart.getPartName().getURI(), rId2.getTargetURI()); - assertEquals("../media/image1.png", rel2.getPath()); - - PackageRelationship rId3 = drawingPart.getRelationship("rId3"); - URI rel3 = parent.relativize(rId3.getTargetURI()); - assertEquals("ThirdSheet!A1", rel3.getFragment()); - - PackageRelationship rId4 = drawingPart.getRelationship("rId4"); - URI rel4 = parent.relativize(rId4.getTargetURI()); - assertEquals("'\u0410\u043F\u0430\u0447\u0435 \u041F\u041E\u0418'!A1", rel4.getFragment()); - - PackageRelationship rId5 = drawingPart.getRelationship("rId5"); - URI rel5 = parent.relativize(rId5.getTargetURI()); - // back slashed have been replaced with forward - assertEquals("file:///D:/chan-chan.mp3", rel5.toString()); - - PackageRelationship rId6 = drawingPart.getRelationship("rId6"); - URI rel6 = parent.relativize(rId6.getTargetURI()); - assertEquals("../../../../../../../cygwin/home/yegor/dinom/&&&[access].2010-10-26.log", rel6.getPath()); - assertEquals("'\u0410\u043F\u0430\u0447\u0435 \u041F\u041E\u0418'!A5", rel6.getFragment()); - } - - public void testSelfRelations_bug51187() throws Exception { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - OPCPackage pkg = OPCPackage.create(baos); - - PackagePart partA = - pkg.createPart(PackagingURIHelper.createPartName("/partA"), "text/plain"); - assertNotNull(partA); - - // reference itself - PackageRelationship rel1 = partA.addRelationship(partA.getPartName(), TargetMode.INTERNAL, "partA"); - - - // Save, and re-load - pkg.close(); - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - pkg = OPCPackage.open(bais); - - partA = pkg.getPart(PackagingURIHelper.createPartName("/partA")); - - - // Check the relations - assertEquals(1, partA.getRelationships().size()); - - PackageRelationship rel2 = partA.getRelationships().getRelationship(0); - - assertEquals(rel1.getRelationshipType(), rel2.getRelationshipType()); - assertEquals(rel1.getId(), rel2.getId()); - assertEquals(rel1.getSourceURI(), rel2.getSourceURI()); - assertEquals(rel1.getTargetURI(), rel2.getTargetURI()); - assertEquals(rel1.getTargetMode(), rel2.getTargetMode()); - } - - public void testTrailingSpacesInURI_53282() throws Exception { - InputStream is = OpenXML4JTestDataSamples.openSampleStream("53282.xlsx"); - OPCPackage pkg = OPCPackage.open(is); - is.close(); - - PackageRelationshipCollection sheetRels = pkg.getPartsByName(Pattern.compile("/xl/worksheets/sheet1.xml")).get(0).getRelationships(); - assertEquals(3, sheetRels.size()); - PackageRelationship rId1 = sheetRels.getRelationshipByID("rId1"); - assertEquals(TargetMode.EXTERNAL, rId1.getTargetMode()); - URI targetUri = rId1.getTargetURI(); - assertEquals("mailto:nobody@nowhere.uk%C2%A0", targetUri.toASCIIString()); - assertEquals("nobody@nowhere.uk\u00A0", targetUri.getSchemeSpecificPart()); - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - pkg.save(out); - out.close(); - - pkg = OPCPackage.open(new ByteArrayInputStream(out.toByteArray())); - sheetRels = pkg.getPartsByName(Pattern.compile("/xl/worksheets/sheet1.xml")).get(0).getRelationships(); - assertEquals(3, sheetRels.size()); - rId1 = sheetRels.getRelationshipByID("rId1"); - assertEquals(TargetMode.EXTERNAL, rId1.getTargetMode()); - targetUri = rId1.getTargetURI(); - assertEquals("mailto:nobody@nowhere.uk%C2%A0", targetUri.toASCIIString()); - assertEquals("nobody@nowhere.uk\u00A0", targetUri.getSchemeSpecificPart()); - } - - public void testEntitiesInRels_56164() throws Exception { - InputStream is = OpenXML4JTestDataSamples.openSampleStream("PackageRelsHasEntities.ooxml"); - OPCPackage p = OPCPackage.open(is); - is.close(); - - // Should have 3 root relationships - boolean foundDocRel = false, foundCorePropRel = false, foundExtPropRel = false; - for (PackageRelationship pr : p.getRelationships()) { - if (pr.getRelationshipType().equals(PackageRelationshipTypes.CORE_DOCUMENT)) - foundDocRel = true; - if (pr.getRelationshipType().equals(PackageRelationshipTypes.CORE_PROPERTIES)) - foundCorePropRel = true; - if (pr.getRelationshipType().equals(PackageRelationshipTypes.EXTENDED_PROPERTIES)) - foundExtPropRel = true; - } - assertTrue("Core/Doc Relationship not found in " + p.getRelationships(), foundDocRel); - assertTrue("Core Props Relationship not found in " + p.getRelationships(), foundCorePropRel); - assertTrue("Ext Props Relationship not found in " + p.getRelationships(), foundExtPropRel); - - // Should have normal work parts - boolean foundCoreProps = false, foundDocument = false, foundTheme1 = false; - for (PackagePart part : p.getParts()) { - if (part.getPartName().toString().equals("/docProps/core.xml")) { - assertEquals(ContentTypes.CORE_PROPERTIES_PART, part.getContentType()); - foundCoreProps = true; - } - if (part.getPartName().toString().equals("/word/document.xml")) { - assertEquals(XWPFRelation.DOCUMENT.getContentType(), part.getContentType()); - foundDocument = true; - } - if (part.getPartName().toString().equals("/word/theme/theme1.xml")) { - assertEquals(XWPFRelation.THEME.getContentType(), part.getContentType()); - foundTheme1 = true; - } - } - assertTrue("Core not found in " + p.getParts(), foundCoreProps); - assertTrue("Document not found in " + p.getParts(), foundDocument); - assertTrue("Theme1 not found in " + p.getParts(), foundTheme1); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestZipPackage.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestZipPackage.java deleted file mode 100644 index 91a3db04a..000000000 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestZipPackage.java +++ /dev/null @@ -1,257 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.io.UnsupportedEncodingException; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.POITextExtractor; -import org.apache.poi.POIXMLException; -import org.apache.poi.extractor.ExtractorFactory; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.openxml4j.OpenXML4JTestDataSamples; -import org.apache.poi.openxml4j.exceptions.NotOfficeXmlFileException; -import org.apache.poi.openxml4j.exceptions.ODFNotOfficeXmlFileException; -import org.apache.poi.sl.usermodel.SlideShow; -import org.apache.poi.sl.usermodel.SlideShowFactory; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.usermodel.WorkbookFactory; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xwpf.usermodel.XWPFRelation; -import org.apache.xmlbeans.XmlException; -import org.junit.Test; - -public class TestZipPackage { - @Test - public void testBug56479() throws Exception { - InputStream is = OpenXML4JTestDataSamples.openSampleStream("dcterms_bug_56479.zip"); - OPCPackage p = OPCPackage.open(is); - - // Check we found the contents of it - boolean foundCoreProps = false, foundDocument = false, foundTheme1 = false; - for (final PackagePart part : p.getParts()) { - final String partName = part.getPartName().toString(); - final String contentType = part.getContentType(); - if ("/docProps/core.xml".equals(partName)) { - assertEquals(ContentTypes.CORE_PROPERTIES_PART, contentType); - foundCoreProps = true; - } - if ("/word/document.xml".equals(partName)) { - assertEquals(XWPFRelation.DOCUMENT.getContentType(), contentType); - foundDocument = true; - } - if ("/word/theme/theme1.xml".equals(partName)) { - assertEquals(XWPFRelation.THEME.getContentType(), contentType); - foundTheme1 = true; - } - } - assertTrue("Core not found in " + p.getParts(), foundCoreProps); - assertFalse("Document should not be found in " + p.getParts(), foundDocument); - assertFalse("Theme1 should not found in " + p.getParts(), foundTheme1); - p.close(); - is.close(); - } - - @Test - public void testZipEntityExpansionTerminates() throws IOException { - try { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("poc-xmlbomb.xlsx"); - wb.close(); - fail("Should catch exception due to entity expansion limitations"); - } catch (POIXMLException e) { - assertEntityLimitReached(e); - } - } - - private void assertEntityLimitReached(Exception e) throws UnsupportedEncodingException { - ByteArrayOutputStream str = new ByteArrayOutputStream(); - PrintWriter writer = new PrintWriter(new OutputStreamWriter(str, "UTF-8")); - try { - e.printStackTrace(writer); - } finally { - writer.close(); - } - String string = new String(str.toByteArray(), "UTF-8"); - assertTrue("Had: " + string, string.contains("The parser has encountered more than")); - } - - @Test - public void testZipEntityExpansionExceedsMemory() throws Exception { - try { - Workbook wb = WorkbookFactory.create(XSSFTestDataSamples.openSamplePackage("poc-xmlbomb.xlsx")); - wb.close(); - fail("Should catch exception due to entity expansion limitations"); - } catch (POIXMLException e) { - assertEntityLimitReached(e); - } - - try { - POITextExtractor extractor = ExtractorFactory.createExtractor(HSSFTestDataSamples.getSampleFile("poc-xmlbomb.xlsx")); - try { - assertNotNull(extractor); - - try { - extractor.getText(); - } catch (IllegalStateException e) { - // expected due to shared strings expansion - } - } finally { - extractor.close(); - } - } catch (POIXMLException e) { - assertEntityLimitReached(e); - } - } - - @Test - public void testZipEntityExpansionSharedStringTable() throws Exception { - Workbook wb = WorkbookFactory.create(XSSFTestDataSamples.openSamplePackage("poc-shared-strings.xlsx")); - wb.close(); - - POITextExtractor extractor = ExtractorFactory.createExtractor(HSSFTestDataSamples.getSampleFile("poc-shared-strings.xlsx")); - try { - assertNotNull(extractor); - - try { - extractor.getText(); - } catch (IllegalStateException e) { - // expected due to shared strings expansion - } - } finally { - extractor.close(); - } - } - - @Test - public void testZipEntityExpansionSharedStringTableEvents() throws Exception { - boolean before = ExtractorFactory.getThreadPrefersEventExtractors(); - ExtractorFactory.setThreadPrefersEventExtractors(true); - try { - POITextExtractor extractor = ExtractorFactory.createExtractor(HSSFTestDataSamples.getSampleFile("poc-shared-strings.xlsx")); - try { - assertNotNull(extractor); - - try { - extractor.getText(); - } catch (IllegalStateException e) { - // expected due to shared strings expansion - } - } finally { - extractor.close(); - } - } catch (XmlException e) { - assertEntityLimitReached(e); - } finally { - ExtractorFactory.setThreadPrefersEventExtractors(before); - } - } - - @Test - public void unparseableCentralDirectory() throws IOException { - File f = OpenXML4JTestDataSamples.getSampleFile("at.pzp.www_uploads_media_PP_Scheinecker-jdk6error.pptx"); - SlideShow ppt = SlideShowFactory.create(f, null, true); - ppt.close(); - } - - @Test - public void testClosingStreamOnException() throws IOException { - InputStream is = OpenXML4JTestDataSamples.openSampleStream("dcterms_bug_56479.zip"); - File tmp = File.createTempFile("poi-test-truncated-zip", ""); - // create a corrupted zip file by truncating a valid zip file to the first 100 bytes - OutputStream os = new FileOutputStream(tmp); - for (int i = 0; i < 100; i++) { - os.write(is.read()); - } - os.flush(); - os.close(); - is.close(); - - // feed the corrupted zip file to OPCPackage - try { - OPCPackage.open(tmp, PackageAccess.READ); - } catch (Exception e) { - // expected: the zip file is invalid - // this test does not care if open() throws an exception or not. - } - // If the stream is not closed on exception, it will keep a file descriptor to tmp, - // and requests to the OS to delete the file will fail. - assertTrue("Can't delete tmp file", tmp.delete()); - } - - /** - * If ZipPackage is passed an invalid file, a call to close - * (eg from the OPCPackage open method) should tidy up the - * stream / file the broken file is being read from. - * See bug #60128 for more - */ - @Test - public void testTidyStreamOnInvalidFile() throws Exception { - // Spreadsheet has a good mix of alternate file types - POIDataSamples files = POIDataSamples.getSpreadSheetInstance(); - - File[] notValidF = new File[] { - files.getFile("SampleSS.ods"), files.getFile("SampleSS.txt") - }; - InputStream[] notValidS = new InputStream[] { - files.openResourceAsStream("SampleSS.ods"), files.openResourceAsStream("SampleSS.txt") - }; - - for (File notValid : notValidF) { - ZipPackage pkg = new ZipPackage(notValid, PackageAccess.READ); - assertNotNull(pkg.getZipArchive()); - assertFalse(pkg.getZipArchive().isClosed()); - try { - pkg.getParts(); - fail("Shouldn't work"); - } catch (ODFNotOfficeXmlFileException e) { - } catch (NotOfficeXmlFileException ne) {} - pkg.close(); - - assertNotNull(pkg.getZipArchive()); - assertTrue(pkg.getZipArchive().isClosed()); - } - for (InputStream notValid : notValidS) { - ZipPackage pkg = new ZipPackage(notValid, PackageAccess.READ); - assertNotNull(pkg.getZipArchive()); - assertFalse(pkg.getZipArchive().isClosed()); - try { - pkg.getParts(); - fail("Shouldn't work"); - } catch (ODFNotOfficeXmlFileException e) { - } catch (NotOfficeXmlFileException ne) {} - pkg.close(); - - assertNotNull(pkg.getZipArchive()); - assertTrue(pkg.getZipArchive().isClosed()); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/ZipFileAssert.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/ZipFileAssert.java deleted file mode 100644 index a19e52b97..000000000 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/ZipFileAssert.java +++ /dev/null @@ -1,139 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.BufferedInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.util.Set; -import java.util.TreeMap; -import java.util.zip.ZipEntry; -import java.util.zip.ZipInputStream; - -import org.junit.Assert; - -import junit.framework.AssertionFailedError; - -/** - * Compare the contents of 2 zip files. - */ -public class ZipFileAssert { - private ZipFileAssert() { - } - - static final int BUFFER_SIZE = 2048; - - protected static void equals( - TreeMap file1, - TreeMap file2) { - Set listFile1 = file1.keySet(); - Assert.assertEquals("not the same number of files in zip:", listFile1.size(), file2.keySet().size()); - - for (String fileName : listFile1) { - // extract the contents for both - ByteArrayOutputStream contain2 = file2.get(fileName); - ByteArrayOutputStream contain1 = file1.get(fileName); - - assertNotNull(fileName + " not found in 2nd zip", contain2); - // no need to check for contain1. The key come from it - - if ((fileName.endsWith(".xml")) || fileName.endsWith(".rels")) { - // we have a xml file - // TODO - // YK: the original OpenXML4J version attempted to compare xml using xmlunit (http://xmlunit.sourceforge.net), - // but POI does not depend on this library - } else { - // not xml, may be an image or other binary format - Assert.assertEquals(fileName + " does not have the same size in both zip:", contain2.size(), contain1.size()); - assertArrayEquals("contents differ", contain1.toByteArray(), contain2.toByteArray()); - } - } - } - - protected static TreeMap decompress( - File filename) throws IOException { - // store the zip content in memory - // let s assume it is not Go ;-) - TreeMap zipContent = new TreeMap(); - - byte data[] = new byte[BUFFER_SIZE]; - /* Open file to decompress */ - FileInputStream file_decompress = new FileInputStream(filename); - - /* Create a buffer for the decompressed files */ - BufferedInputStream buffi = new BufferedInputStream(file_decompress); - - /* Open the file with the buffer */ - ZipInputStream zis = new ZipInputStream(buffi); - - /* Processing entries of the zip file */ - ZipEntry entree; - int count; - while ((entree = zis.getNextEntry()) != null) { - - /* Create a array for the current entry */ - ByteArrayOutputStream byteArray = new ByteArrayOutputStream(); - zipContent.put(entree.getName(), byteArray); - - /* copy in memory */ - while ((count = zis.read(data, 0, BUFFER_SIZE)) != -1) { - byteArray.write(data, 0, count); - } - /* Flush the buffer */ - byteArray.flush(); - byteArray.close(); - } - - zis.close(); - - return zipContent; - } - - /** - * Asserts that two files are equal. Throws an AssertionFailedError - * if they are not. - *

    - * - */ - public static void assertEquals(File expected, File actual) { - assertNotNull(expected); - assertNotNull(actual); - - assertTrue("File does not exist [" + expected.getAbsolutePath() - + "]", expected.exists()); - assertTrue("File does not exist [" + actual.getAbsolutePath() - + "]", actual.exists()); - - assertTrue("Expected file not readable", expected.canRead()); - assertTrue("Actual file not readable", actual.canRead()); - - try { - TreeMap file1 = decompress(expected); - TreeMap file2 = decompress(actual); - equals(file1, file2); - } catch (IOException e) { - throw new AssertionFailedError(e.toString()); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCComplianceCoreProperties.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCComplianceCoreProperties.java deleted file mode 100644 index 311db55c2..000000000 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCComplianceCoreProperties.java +++ /dev/null @@ -1,335 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc.compliance; - -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.URI; -import java.net.URISyntaxException; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.openxml4j.OpenXML4JTestDataSamples; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.exceptions.InvalidOperationException; -import org.apache.poi.openxml4j.opc.ContentTypes; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackageRelationshipTypes; -import org.apache.poi.openxml4j.opc.PackagingURIHelper; -import org.apache.poi.openxml4j.opc.TargetMode; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.TempFile; -import org.junit.Test; - -import junit.framework.AssertionFailedError; - -/** - * Test core properties Open Packaging Convention compliance. - * - * M4.1: The format designer shall specify and the format producer shall create - * at most one core properties relationship for a package. A format consumer - * shall consider more than one core properties relationship for a package to be - * an error. If present, the relationship shall target the Core Properties part. - * (POI relaxes this on reading, as Office sometimes breaks this) - * - * M4.2: The format designer shall not specify and the format producer shall not - * create Core Properties that use the Markup Compatibility namespace as defined - * in Annex F, "Standard Namespaces and Content Types". A format consumer shall - * consider the use of the Markup Compatibility namespace to be an error. - * - * M4.3: Producers shall not create a document element that contains refinements - * to the Dublin Core elements, except for the two specified in the schema: - * and Consumers shall consider a document - * element that violates this constraint to be an error. - * - * M4.4: Producers shall not create a document element that contains the - * xml:lang attribute. Consumers shall consider a document element that violates - * this constraint to be an error. - * - * M4.5: Producers shall not create a document element that contains the - * xsi:type attribute, except for a or - * element where the xsi:type attribute shall be present and shall hold the - * value dcterms:W3CDTF, where dcterms is the namespace prefix of the Dublin - * Core namespace. Consumers shall consider a document element that violates - * this constraint to be an error. - * - * @author Julien Chable - */ -public final class TestOPCComplianceCoreProperties { - - @Test - public void testCorePropertiesPart() { - OPCPackage pkg; - try { - InputStream is = OpenXML4JTestDataSamples.openComplianceSampleStream("OPCCompliance_CoreProperties_OnlyOneCorePropertiesPart.docx"); - pkg = OPCPackage.open(is); - } catch (InvalidFormatException e) { - throw new RuntimeException(e); - } catch (IOException e) { - throw new RuntimeException(e); - } - pkg.revert(); - } - - private static String extractInvalidFormatMessage(String sampleNameSuffix) { - InputStream is = OpenXML4JTestDataSamples.openComplianceSampleStream("OPCCompliance_CoreProperties_" + sampleNameSuffix); - OPCPackage pkg; - try { - pkg = OPCPackage.open(is); - } catch (InvalidFormatException e) { - // no longer required for successful test - return e.getMessage(); - } catch (IOException e) { - throw new RuntimeException(e); - } - pkg.revert(); - throw new AssertionFailedError("expected OPC compliance exception was not thrown"); - } - - /** - * Test M4.1 rule. - */ - @Test - public void testOnlyOneCorePropertiesPart() throws Exception { - // We have relaxed this check, so we can read the file anyway - try { - extractInvalidFormatMessage("OnlyOneCorePropertiesPartFAIL.docx"); - fail("M4.1 should be being relaxed"); - } catch (AssertionFailedError e) { - // expected here - } - - // We will use the first core properties, and ignore the others - InputStream is = OpenXML4JTestDataSamples.openSampleStream("MultipleCoreProperties.docx"); - OPCPackage pkg = OPCPackage.open(is); - - // We can see 2 by type - assertEquals(2, pkg.getPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).size()); - // But only the first one by relationship - assertEquals(1, pkg.getPartsByRelationshipType(PackageRelationshipTypes.CORE_PROPERTIES).size()); - // It should be core.xml not the older core1.xml - assertEquals( - "/docProps/core.xml", - pkg.getPartsByRelationshipType(PackageRelationshipTypes.CORE_PROPERTIES).get(0).getPartName().toString() - ); - } - - private static URI createURI(String text) { - try { - return new URI(text); - } catch (URISyntaxException e) { - throw new RuntimeException(e); - } - } - - /** - * Test M4.1 rule. - */ - @Test - public void testOnlyOneCorePropertiesPart_AddRelationship() { - InputStream is = OpenXML4JTestDataSamples.openComplianceSampleStream("OPCCompliance_CoreProperties_OnlyOneCorePropertiesPart.docx"); - OPCPackage pkg; - try { - pkg = OPCPackage.open(is); - } catch (InvalidFormatException e) { - throw new RuntimeException(e); - } catch (IOException e) { - throw new RuntimeException(e); - } - URI partUri = createURI("/docProps/core2.xml"); - try { - pkg.addRelationship(PackagingURIHelper.createPartName(partUri), TargetMode.INTERNAL, - PackageRelationshipTypes.CORE_PROPERTIES); - // no longer fail on compliance error - //fail("expected OPC compliance exception was not thrown"); - } catch (InvalidFormatException e) { - throw new RuntimeException(e); - } catch (InvalidOperationException e) { - // expected during successful test - assertEquals("OPC Compliance error [M4.1]: can't add another core properties part ! Use the built-in package method instead.", e.getMessage()); - } - pkg.revert(); - } - - /** - * Test M4.1 rule. - */ - @Test - public void testOnlyOneCorePropertiesPart_AddPart() throws InvalidFormatException { - String sampleFileName = "OPCCompliance_CoreProperties_OnlyOneCorePropertiesPart.docx"; - OPCPackage pkg = OPCPackage.open(POIDataSamples.getOpenXML4JInstance().getFile(sampleFileName).getPath()); - - URI partUri = createURI("/docProps/core2.xml"); - try { - pkg.createPart(PackagingURIHelper.createPartName(partUri), - ContentTypes.CORE_PROPERTIES_PART); - // no longer fail on compliance error - //fail("expected OPC compliance exception was not thrown"); - } catch (InvalidOperationException e) { - // expected during successful test - assertEquals("OPC Compliance error [M4.1]: you try to add more than one core properties relationship in the package !", e.getMessage()); - } - pkg.revert(); - } - - /** - * Test M4.2 rule. - */ - @Test - public void testDoNotUseCompatibilityMarkup() { - String msg = extractInvalidFormatMessage("DoNotUseCompatibilityMarkupFAIL.docx"); - assertEquals("OPC Compliance error [M4.2]: A format consumer shall consider the use of the Markup Compatibility namespace to be an error.", msg); - } - - /** - * Test M4.3 rule. - */ - @Test - public void testDCTermsNamespaceLimitedUse() { - String msg = extractInvalidFormatMessage("DCTermsNamespaceLimitedUseFAIL.docx"); - assertEquals("OPC Compliance error [M4.3]: Producers shall not create a document element that contains refinements to the Dublin Core elements, except for the two specified in the schema: and Consumers shall consider a document element that violates this constraint to be an error.", msg); - } - - /** - * Test M4.4 rule. - */ - @Test - public void testUnauthorizedXMLLangAttribute() { - String msg = extractInvalidFormatMessage("UnauthorizedXMLLangAttributeFAIL.docx"); - assertEquals("OPC Compliance error [M4.4]: Producers shall not create a document element that contains the xml:lang attribute. Consumers shall consider a document element that violates this constraint to be an error.", msg); - } - - /** - * Test M4.5 rule. - */ - @Test - public void testLimitedXSITypeAttribute_NotPresent() { - String msg = extractInvalidFormatMessage("LimitedXSITypeAttribute_NotPresentFAIL.docx"); - assertEquals("The element 'created' must have the 'xsi:type' attribute present !", msg); - } - - /** - * Test M4.5 rule. - */ - @Test - public void testLimitedXSITypeAttribute_PresentWithUnauthorizedValue() { - String msg = extractInvalidFormatMessage("LimitedXSITypeAttribute_PresentWithUnauthorizedValueFAIL.docx"); - assertEquals("The element 'modified' must have the 'xsi:type' attribute with the value 'dcterms:W3CDTF', but had 'W3CDTF' !", msg); - } - - /** - * Document with no core properties - testing at the OPC level, - * saving into a new stream - */ - @Test - public void testNoCoreProperties_saveNew() throws Exception { - String sampleFileName = "OPCCompliance_NoCoreProperties.xlsx"; - OPCPackage pkg = OPCPackage.open(POIDataSamples.getOpenXML4JInstance().getFile(sampleFileName).getPath()); - - // Verify it has empty properties - assertEquals(0, pkg.getPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).size()); - assertNotNull(pkg.getPackageProperties()); - assertNotNull(pkg.getPackageProperties().getLanguageProperty()); - assertNull(pkg.getPackageProperties().getLanguageProperty().getValue()); - - // Save and re-load - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - pkg.save(baos); - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - pkg.revert(); - - pkg = OPCPackage.open(bais); - - // An Empty Properties part has been added in the save/load - assertEquals(1, pkg.getPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).size()); - assertNotNull(pkg.getPackageProperties()); - assertNotNull(pkg.getPackageProperties().getLanguageProperty()); - assertNull(pkg.getPackageProperties().getLanguageProperty().getValue()); - pkg.close(); - - // Open a new copy of it - pkg = OPCPackage.open(POIDataSamples.getOpenXML4JInstance().getFile(sampleFileName).getPath()); - - // Save and re-load, without having touched the properties yet - baos = new ByteArrayOutputStream(); - pkg.save(baos); - pkg.revert(); - - bais = new ByteArrayInputStream(baos.toByteArray()); - pkg = OPCPackage.open(bais); - - // Check that this too added empty properties without error - assertEquals(1, pkg.getPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).size()); - assertNotNull(pkg.getPackageProperties()); - assertNotNull(pkg.getPackageProperties().getLanguageProperty()); - assertNull(pkg.getPackageProperties().getLanguageProperty().getValue()); - } - - /** - * Document with no core properties - testing at the OPC level, - * from a temp-file, saving in-place - */ - @Test - public void testNoCoreProperties_saveInPlace() throws Exception { - String sampleFileName = "OPCCompliance_NoCoreProperties.xlsx"; - - // Copy this into a temp file, so we can play with it - File tmp = TempFile.createTempFile("poi-test", ".opc"); - FileOutputStream out = new FileOutputStream(tmp); - InputStream in = POIDataSamples.getOpenXML4JInstance().openResourceAsStream(sampleFileName); - IOUtils.copy( - in, - out); - out.close(); - in.close(); - - // Open it from that temp file - OPCPackage pkg = OPCPackage.open(tmp); - - // Empty properties - assertEquals(0, pkg.getPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).size()); - assertNotNull(pkg.getPackageProperties()); - assertNotNull(pkg.getPackageProperties().getLanguageProperty()); - assertNull(pkg.getPackageProperties().getLanguageProperty().getValue()); - - // Save and close - pkg.close(); - - // Re-open and check - pkg = OPCPackage.open(tmp); - - // An Empty Properties part has been added in the save/load - assertEquals(1, pkg.getPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).size()); - assertNotNull(pkg.getPackageProperties()); - assertNotNull(pkg.getPackageProperties().getLanguageProperty()); - assertNull(pkg.getPackageProperties().getLanguageProperty().getValue()); - - // Finish and tidy - pkg.revert(); - assertTrue(tmp.delete()); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCCompliancePackageModel.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCCompliancePackageModel.java deleted file mode 100644 index 7cf9e4b95..000000000 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCCompliancePackageModel.java +++ /dev/null @@ -1,165 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc.compliance; - -import static org.junit.Assert.fail; - -import java.io.IOException; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.exceptions.InvalidOperationException; -import org.apache.poi.openxml4j.exceptions.PartAlreadyExistsException; -import org.apache.poi.openxml4j.opc.ContentTypes; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackagePartName; -import org.apache.poi.openxml4j.opc.PackageRelationshipTypes; -import org.apache.poi.openxml4j.opc.PackagingURIHelper; -import org.apache.poi.openxml4j.opc.TargetMode; -import org.junit.Test; - -/** - * Test Open Packaging Convention package model compliance. - * - * M1.11 : A package implementer shall neither create nor recognize a part with - * a part name derived from another part name by appending segments to it. - * - * @author Julien Chable - */ -public class TestOPCCompliancePackageModel { - - /** - * A package implementer shall neither create nor recognize a part with a - * part name derived from another part name by appending segments to it. - * [M1.11] - */ - @Test - public void testPartNameDerivationAdditionFailure() { - OPCPackage pkg = OPCPackage.create("TODELETEIFEXIST.docx"); - try { - PackagePartName name = PackagingURIHelper - .createPartName("/word/document.xml"); - PackagePartName nameDerived = PackagingURIHelper - .createPartName("/word/document.xml/image1.gif"); - pkg.createPart(name, ContentTypes.XML); - pkg.createPart(nameDerived, ContentTypes.EXTENSION_GIF); - } catch (InvalidOperationException e) { - pkg.revert(); - return; - } catch (InvalidFormatException e) { - fail(e.getMessage()); - } - fail("A package implementer shall neither create nor recognize a part with a" - + " part name derived from another part name by appending segments to it." - + " [M1.11]"); - } - - /** - * A package implementer shall neither create nor recognize a part with a - * part name derived from another part name by appending segments to it. - * [M1.11] - */ - @Test - public void testPartNameDerivationReadingFailure() throws IOException { - String filename = "OPCCompliance_DerivedPartNameFAIL.docx"; - try { - OPCPackage.open(POIDataSamples.getOpenXML4JInstance().openResourceAsStream(filename)); - } catch (InvalidFormatException e) { - return; - } - fail("A package implementer shall neither create nor recognize a part with a" - + " part name derived from another part name by appending segments to it." - + " [M1.11]"); - } - - /** - * Rule M1.12 : Packages shall not contain equivalent part names and package - * implementers shall neither create nor recognize packages with equivalent - * part names. - */ - @Test - public void testAddPackageAlreadyAddFailure() throws Exception { - OPCPackage pkg = OPCPackage.create("DELETEIFEXISTS.docx"); - PackagePartName name1 = null; - PackagePartName name2 = null; - try { - name1 = PackagingURIHelper.createPartName("/word/document.xml"); - name2 = PackagingURIHelper.createPartName("/word/document.xml"); - } catch (InvalidFormatException e) { - throw new Exception(e.getMessage()); - } - pkg.createPart(name1, ContentTypes.XML); - try { - pkg.createPart(name2, ContentTypes.XML); - } catch (PartAlreadyExistsException e) { - return; - } - fail("Packages shall not contain equivalent part names and package implementers shall neither create nor recognize packages with equivalent part names. [M1.12]"); - } - - /** - * Rule M1.12 : Packages shall not contain equivalent part names and package - * implementers shall neither create nor recognize packages with equivalent - * part names. - */ - @Test - public void testAddPackageAlreadyAddFailure2() throws Exception { - OPCPackage pkg = OPCPackage.create("DELETEIFEXISTS.docx"); - PackagePartName partName = null; - try { - partName = PackagingURIHelper.createPartName("/word/document.xml"); - } catch (InvalidFormatException e) { - throw new Exception(e.getMessage()); - } - pkg.createPart(partName, ContentTypes.XML); - try { - pkg.createPart(partName, ContentTypes.XML); - } catch (InvalidOperationException e) { - return; - } - fail("Packages shall not contain equivalent part names and package implementers shall neither create nor recognize packages with equivalent part names. [M1.12]"); - } - - /** - * Try to add a relationship to a relationship part. - * - * Check rule M1.25: The Relationships part shall not have relationships to - * any other part. Package implementers shall enforce this requirement upon - * the attempt to create such a relationship and shall treat any such - * relationship as invalid. - */ - @Test - public void testAddRelationshipRelationshipsPartFailure() { - OPCPackage pkg = OPCPackage.create("DELETEIFEXISTS.docx"); - PackagePartName name1 = null; - try { - name1 = PackagingURIHelper - .createPartName("/test/_rels/document.xml.rels"); - } catch (InvalidFormatException e) { - fail("This exception should never happen !"); - } - - try { - pkg.addRelationship(name1, TargetMode.INTERNAL, - PackageRelationshipTypes.CORE_DOCUMENT); - } catch (InvalidOperationException e) { - return; - } - fail("Fail test -> M1.25: The Relationships part shall not have relationships to any other part"); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCCompliancePartName.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCCompliancePartName.java deleted file mode 100644 index e7754ed57..000000000 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/compliance/TestOPCCompliancePartName.java +++ /dev/null @@ -1,252 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc.compliance; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.net.URI; -import java.net.URISyntaxException; - -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.PackagePartName; -import org.apache.poi.openxml4j.opc.PackagingURIHelper; -import org.junit.Test; - -/** - * Test part name Open Packaging Convention compliance. - * - * (Open Packaging Convention 8.1.1 Part names) : - * - * The part name grammar is defined as follows: - * - * part_name = 1*( "/" segment ) - * - * segment = 1*( pchar ) - * - * pchar is defined in RFC 3986. - * - * The part name grammar implies the following constraints. The package - * implementer shall neither create any part that violates these constraints nor - * retrieve any data from a package as a part if the purported part name - * violates these constraints. - * - * A part name shall not be empty. [M1.1] - * - * A part name shall not have empty segments. [M1.3] - * - * A part name shall start with a forward slash ("/") character. [M1.4] - * - * A part name shall not have a forward slash as the last character. [M1.5] - * - * A segment shall not hold any characters other than pchar characters. [M1.6] - * - * Part segments have the following additional constraints. The package - * implementer shall neither create any part with a part name comprised of a - * segment that violates these constraints nor retrieve any data from a package - * as a part if the purported part name contains a segment that violates these - * constraints. - * - * A segment shall not contain percent-encoded forward slash ("/"), or backward - * slash ("\") characters. [M1.7] - * - * A segment shall not contain percent-encoded unreserved characters. [M1.8] - * - * A segment shall not end with a dot (".") character. [M1.9] - * - * A segment shall include at least one non-dot character. [M1.10] - * - * A package implementer shall neither create nor recognize a part with a part - * name derived from another part name by appending segments to it. [M1.11] - * - * Part name equivalence is determined by comparing part names as - * case-insensitive ASCII strings. [M1.12] - * - * @author Julien Chable - */ -public final class TestOPCCompliancePartName { - - /** - * Test some common invalid names. - * - * A segment shall not contain percent-encoded unreserved characters. [M1.8] - */ - @Test - public void testInvalidPartNames() { - String[] invalidNames = { "/", "/xml./doc.xml", "[Content_Types].xml", "//xml/." }; - for (String s : invalidNames) { - URI uri = null; - try { - uri = new URI(s); - } catch (URISyntaxException e) { - assertTrue(s.equals("[Content_Types].xml")); - continue; - } - assertFalse("This part name SHOULD NOT be valid: " + s, - PackagingURIHelper.isValidPartName(uri)); - } - } - - /** - * Test some common valid names. - */ - @Test - public void testValidPartNames() throws URISyntaxException { - String[] validNames = { "/xml/item1.xml", "/document.xml", - "/a/%D1%86.xml" }; - for (String s : validNames) - assertTrue("This part name SHOULD be valid: " + s, - PackagingURIHelper.isValidPartName(new URI(s))); - } - - /** - * A part name shall not be empty. [M1.1] - */ - @Test - public void testEmptyPartNameFailure() throws URISyntaxException { - try { - PackagingURIHelper.createPartName(new URI("")); - fail("A part name shall not be empty. [M1.1]"); - } catch (InvalidFormatException e) { - // Normal behaviour - } - } - - /** - * A part name shall not have empty segments. [M1.3] - * - * A segment shall not end with a dot ('.') character. [M1.9] - * - * A segment shall include at least one non-dot character. [M1.10] - */ - @Test - public void testPartNameWithInvalidSegmentsFailure() { - String[] invalidNames = { "//document.xml", "//word/document.xml", - "/word//document.rels", "/word//rels//document.rels", - "/xml./doc.xml", "/document.", "/./document.xml", - "/word/./doc.rels", "/%2F/document.xml" }; - try { - for (String s : invalidNames) - assertFalse( - "A part name shall not have empty segments. [M1.3]", - PackagingURIHelper.isValidPartName(new URI(s))); - } catch (URISyntaxException e) { - fail(); - } - } - - /** - * A segment shall not hold any characters other than ipchar (RFC 3987) characters. - * [M1.6]. - */ - @Test - public void testPartNameWithNonPCharCharacters() { - String[] validNames = { "/doc&.xml" }; - try { - for (String s : validNames) - assertTrue( - "A segment shall not contain non pchar characters [M1.6] : " - + s, PackagingURIHelper - .isValidPartName(new URI(s))); - } catch (URISyntaxException e) { - fail(); - } - } - - /** - * A segment shall not contain percent-encoded unreserved characters [M1.8]. - */ - @Test - public void testPartNameWithUnreservedEncodedCharactersFailure() { - String[] invalidNames = { "/a/docum%65nt.xml" }; - try { - for (String s : invalidNames) - assertFalse( - "A segment shall not contain percent-encoded unreserved characters [M1.8] : " - + s, PackagingURIHelper - .isValidPartName(new URI(s))); - } catch (URISyntaxException e) { - fail(); - } - } - - /** - * A part name shall start with a forward slash ('/') character. [M1.4] - */ - @Test - public void testPartNameStartsWithAForwardSlashFailure() - throws URISyntaxException { - try { - PackagingURIHelper.createPartName(new URI("document.xml")); - fail("A part name shall start with a forward slash ('/') character. [M1.4]"); - } catch (InvalidFormatException e) { - // Normal behaviour - } - } - - /** - * A part name shall not have a forward slash as the last character. [M1.5] - */ - @Test - public void testPartNameEndsWithAForwardSlashFailure() - throws URISyntaxException { - try { - PackagingURIHelper.createPartName(new URI("/document.xml/")); - fail("A part name shall not have a forward slash as the last character. [M1.5]"); - } catch (InvalidFormatException e) { - // Normal behaviour - } - } - - /** - * Part name equivalence is determined by comparing part names as - * case-insensitive ASCII strings. [M1.12] - */ - @Test - public void testPartNameComparaison() throws Exception { - String[] partName1 = { "/word/document.xml", "/docProps/core.xml", "/rels/.rels" }; - String[] partName2 = { "/WORD/DocUment.XML", "/docProps/core.xml", "/rels/.rels" }; - for (int i = 0; i < partName1.length || i < partName2.length; ++i) { - PackagePartName p1 = PackagingURIHelper.createPartName(partName1[i]); - PackagePartName p2 = PackagingURIHelper.createPartName(partName2[i]); - assertTrue(p1.equals(p2)); - assertTrue(p1.compareTo(p2) == 0); - assertTrue(p1.hashCode() == p2.hashCode()); - } - } - - /** - * Part name equivalence is determined by comparing part names as - * case-insensitive ASCII strings. [M1.12]. - * - * All the comparisons MUST FAIL ! - */ - @Test - public void testPartNameComparaisonFailure() throws Exception { - String[] partName1 = { "/word/document.xml", "/docProps/core.xml", "/rels/.rels" }; - String[] partName2 = { "/WORD/DocUment.XML2", "/docProp/core.xml", "/rels/rels" }; - for (int i = 0; i < partName1.length || i < partName2.length; ++i) { - PackagePartName p1 = PackagingURIHelper.createPartName(partName1[i]); - PackagePartName p2 = PackagingURIHelper.createPartName(partName2[i]); - assertFalse(p1.equals(p2)); - assertFalse(p1.compareTo(p2) == 0); - assertFalse(p1.hashCode() == p2.hashCode()); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/internal/TestContentTypeManager.java b/src/ooxml/testcases/org/apache/poi/openxml4j/opc/internal/TestContentTypeManager.java deleted file mode 100644 index 936d0f9e8..000000000 --- a/src/ooxml/testcases/org/apache/poi/openxml4j/opc/internal/TestContentTypeManager.java +++ /dev/null @@ -1,127 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.openxml4j.opc.internal; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; -import static org.junit.Assume.assumeTrue; - -import org.apache.poi.openxml4j.OpenXML4JTestDataSamples; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackageAccess; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.opc.PackagePartName; -import org.apache.poi.openxml4j.opc.PackageRelationship; -import org.apache.poi.openxml4j.opc.PackageRelationshipCollection; -import org.apache.poi.openxml4j.opc.PackageRelationshipTypes; -import org.apache.poi.openxml4j.opc.PackagingURIHelper; -import org.junit.Ignore; -import org.junit.Test; - -public final class TestContentTypeManager { - - /** - * Test the properties part content parsing. - */ - @Test - public void testContentType() throws Exception { - String filepath = OpenXML4JTestDataSamples.getSampleFileName("sample.docx"); - - // Retrieves core properties part - OPCPackage p = OPCPackage.open(filepath, PackageAccess.READ); - try { - PackageRelationshipCollection rels = p.getRelationshipsByType(PackageRelationshipTypes.CORE_PROPERTIES); - PackageRelationship corePropertiesRelationship = rels.getRelationship(0); - PackagePart coreDocument = p.getPart(corePropertiesRelationship); - - assertEquals("application/vnd.openxmlformats-package.core-properties+xml", coreDocument.getContentType()); - - // TODO - finish writing this test - assumeTrue("finish writing this test", false); - - ContentTypeManager ctm = new ZipContentTypeManager(coreDocument.getInputStream(), p); - assertNotNull(ctm); - } finally { - p.close(); - } - } - - /** - * Test the addition of several default and override content types. - */ - @Test - public void testContentTypeAddition() throws Exception { - ContentTypeManager ctm = new ZipContentTypeManager(null, null); - - PackagePartName name1 = PackagingURIHelper.createPartName("/foo/foo.XML"); - PackagePartName name2 = PackagingURIHelper.createPartName("/foo/foo2.xml"); - PackagePartName name3 = PackagingURIHelper.createPartName("/foo/doc.rels"); - PackagePartName name4 = PackagingURIHelper.createPartName("/foo/doc.RELS"); - - // Add content types - ctm.addContentType(name1, "foo-type1"); - ctm.addContentType(name2, "foo-type2"); - ctm.addContentType(name3, "text/xml+rel"); - ctm.addContentType(name4, "text/xml+rel"); - - assertEquals(ctm.getContentType(name1), "foo-type1"); - assertEquals(ctm.getContentType(name2), "foo-type2"); - assertEquals(ctm.getContentType(name3), "text/xml+rel"); - assertEquals(ctm.getContentType(name3), "text/xml+rel"); - } - - /** - * Test the addition then removal of content types. - */ - @Test - public void testContentTypeRemoval() throws Exception { - ContentTypeManager ctm = new ZipContentTypeManager(null, null); - - PackagePartName name1 = PackagingURIHelper.createPartName("/foo/foo.xml"); - PackagePartName name2 = PackagingURIHelper.createPartName("/foo/foo2.xml"); - PackagePartName name3 = PackagingURIHelper.createPartName("/foo/doc.rels"); - PackagePartName name4 = PackagingURIHelper.createPartName("/foo/doc.RELS"); - - // Add content types - ctm.addContentType(name1, "foo-type1"); - ctm.addContentType(name2, "foo-type2"); - ctm.addContentType(name3, "text/xml+rel"); - ctm.addContentType(name4, "text/xml+rel"); - ctm.removeContentType(name2); - ctm.removeContentType(name3); - - assertEquals(ctm.getContentType(name1), "foo-type1"); - assertEquals(ctm.getContentType(name2), "foo-type1"); - assertEquals(ctm.getContentType(name3), null); - - ctm.removeContentType(name1); - assertEquals(ctm.getContentType(name1), null); - assertEquals(ctm.getContentType(name2), null); - } - - /** - * Test the addition then removal of content types in a package. - */ - @Ignore - @Test - public void testContentTypeRemovalPackage() { - // TODO - fail("test not written"); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/poifs/crypt/AllPOIFSCryptoTests.java b/src/ooxml/testcases/org/apache/poi/poifs/crypt/AllPOIFSCryptoTests.java deleted file mode 100644 index 90bc4ceb3..000000000 --- a/src/ooxml/testcases/org/apache/poi/poifs/crypt/AllPOIFSCryptoTests.java +++ /dev/null @@ -1,36 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.crypt; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - - -/** - * Tests for org.apache.poi.poifs.crypt - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestEncryptionInfo.class - , TestDecryptor.class - , TestEncryptor.class - , TestAgileEncryptionParameters.class - , TestCertificateEncryption.class -}) -public final class AllPOIFSCryptoTests { -} \ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/poifs/crypt/PkiTestUtils.java b/src/ooxml/testcases/org/apache/poi/poifs/crypt/PkiTestUtils.java deleted file mode 100644 index 2b6ab9838..000000000 --- a/src/ooxml/testcases/org/apache/poi/poifs/crypt/PkiTestUtils.java +++ /dev/null @@ -1,317 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.poifs.crypt; - -import java.io.IOException; -import java.io.InputStream; -import java.io.StringWriter; -import java.math.BigInteger; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.SecureRandom; -import java.security.cert.CRLException; -import java.security.cert.CertificateEncodingException; -import java.security.cert.CertificateException; -import java.security.cert.X509CRL; -import java.security.cert.X509Certificate; -import java.security.interfaces.RSAPublicKey; -import java.security.spec.RSAKeyGenParameterSpec; -import java.util.Date; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Result; -import javax.xml.transform.Source; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; - -import org.bouncycastle.asn1.DERIA5String; -import org.bouncycastle.asn1.DEROctetString; -import org.bouncycastle.asn1.DERSequence; -import org.bouncycastle.asn1.ocsp.OCSPObjectIdentifiers; -import org.bouncycastle.asn1.x500.X500Name; -import org.bouncycastle.asn1.x509.AuthorityInformationAccess; -import org.bouncycastle.asn1.x509.AuthorityKeyIdentifier; -import org.bouncycastle.asn1.x509.BasicConstraints; -import org.bouncycastle.asn1.x509.CRLNumber; -import org.bouncycastle.asn1.x509.CRLReason; -import org.bouncycastle.asn1.x509.DistributionPoint; -import org.bouncycastle.asn1.x509.DistributionPointName; -import org.bouncycastle.asn1.x509.Extension; -import org.bouncycastle.asn1.x509.Extensions; -import org.bouncycastle.asn1.x509.GeneralName; -import org.bouncycastle.asn1.x509.GeneralNames; -import org.bouncycastle.asn1.x509.KeyUsage; -import org.bouncycastle.asn1.x509.SubjectKeyIdentifier; -import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; -import org.bouncycastle.asn1.x509.X509ObjectIdentifiers; -import org.bouncycastle.cert.X509CRLHolder; -import org.bouncycastle.cert.X509CertificateHolder; -import org.bouncycastle.cert.X509ExtensionUtils; -import org.bouncycastle.cert.X509v2CRLBuilder; -import org.bouncycastle.cert.X509v3CertificateBuilder; -import org.bouncycastle.cert.jcajce.JcaX509CRLConverter; -import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; -import org.bouncycastle.cert.ocsp.BasicOCSPResp; -import org.bouncycastle.cert.ocsp.BasicOCSPRespBuilder; -import org.bouncycastle.cert.ocsp.CertificateID; -import org.bouncycastle.cert.ocsp.CertificateStatus; -import org.bouncycastle.cert.ocsp.OCSPReq; -import org.bouncycastle.cert.ocsp.OCSPReqBuilder; -import org.bouncycastle.cert.ocsp.OCSPResp; -import org.bouncycastle.cert.ocsp.OCSPRespBuilder; -import org.bouncycastle.cert.ocsp.Req; -import org.bouncycastle.cert.ocsp.RevokedStatus; -import org.bouncycastle.crypto.params.RSAKeyParameters; -import org.bouncycastle.crypto.util.SubjectPublicKeyInfoFactory; -import org.bouncycastle.operator.ContentSigner; -import org.bouncycastle.operator.DigestCalculator; -import org.bouncycastle.operator.OperatorCreationException; -import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; -import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder; -import org.w3c.dom.Document; -import org.w3c.dom.Node; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; - -public class PkiTestUtils { - - private PkiTestUtils() { - super(); - } - - static KeyPair generateKeyPair() throws Exception { - KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); - SecureRandom random = new SecureRandom(); - keyPairGenerator.initialize(new RSAKeyGenParameterSpec(1024, - RSAKeyGenParameterSpec.F4), random); - KeyPair keyPair = keyPairGenerator.generateKeyPair(); - return keyPair; - } - - static X509Certificate generateCertificate(PublicKey subjectPublicKey, - String subjectDn, Date notBefore, Date notAfter, - X509Certificate issuerCertificate, PrivateKey issuerPrivateKey, - boolean caFlag, int pathLength, String crlUri, String ocspUri, - KeyUsage keyUsage) - throws IOException, OperatorCreationException, CertificateException - { - String signatureAlgorithm = "SHA1withRSA"; - X500Name issuerName; - if (issuerCertificate != null) { - issuerName = new X509CertificateHolder(issuerCertificate.getEncoded()).getIssuer(); - } else { - issuerName = new X500Name(subjectDn); - } - - RSAPublicKey rsaPubKey = (RSAPublicKey)subjectPublicKey; - RSAKeyParameters rsaSpec = new RSAKeyParameters(false, rsaPubKey.getModulus(), rsaPubKey.getPublicExponent()); - - SubjectPublicKeyInfo subjectPublicKeyInfo = - SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(rsaSpec); - - DigestCalculator digestCalc = new JcaDigestCalculatorProviderBuilder() - .setProvider("BC").build().get(CertificateID.HASH_SHA1); - - X509v3CertificateBuilder certificateGenerator = new X509v3CertificateBuilder( - issuerName - , new BigInteger(128, new SecureRandom()) - , notBefore - , notAfter - , new X500Name(subjectDn) - , subjectPublicKeyInfo - ); - - X509ExtensionUtils exUtils = new X509ExtensionUtils(digestCalc); - SubjectKeyIdentifier subKeyId = exUtils.createSubjectKeyIdentifier(subjectPublicKeyInfo); - AuthorityKeyIdentifier autKeyId = (issuerCertificate != null) - ? exUtils.createAuthorityKeyIdentifier(new X509CertificateHolder(issuerCertificate.getEncoded())) - : exUtils.createAuthorityKeyIdentifier(subjectPublicKeyInfo); - - certificateGenerator.addExtension(Extension.subjectKeyIdentifier, false, subKeyId); - certificateGenerator.addExtension(Extension.authorityKeyIdentifier, false, autKeyId); - - if (caFlag) { - BasicConstraints bc; - - if (-1 == pathLength) { - bc = new BasicConstraints(true); - } else { - bc = new BasicConstraints(pathLength); - } - certificateGenerator.addExtension(Extension.basicConstraints, false, bc); - } - - if (null != crlUri) { - int uri = GeneralName.uniformResourceIdentifier; - DERIA5String crlUriDer = new DERIA5String(crlUri); - GeneralName gn = new GeneralName(uri, crlUriDer); - - DERSequence gnDer = new DERSequence(gn); - GeneralNames gns = GeneralNames.getInstance(gnDer); - - DistributionPointName dpn = new DistributionPointName(0, gns); - DistributionPoint distp = new DistributionPoint(dpn, null, null); - DERSequence distpDer = new DERSequence(distp); - certificateGenerator.addExtension(Extension.cRLDistributionPoints, false, distpDer); - } - - if (null != ocspUri) { - int uri = GeneralName.uniformResourceIdentifier; - GeneralName ocspName = new GeneralName(uri, ocspUri); - - AuthorityInformationAccess authorityInformationAccess = - new AuthorityInformationAccess(X509ObjectIdentifiers.ocspAccessMethod, ocspName); - - certificateGenerator.addExtension(Extension.authorityInfoAccess, false, authorityInformationAccess); - } - - if (null != keyUsage) { - certificateGenerator.addExtension(Extension.keyUsage, true, keyUsage); - } - - JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder(signatureAlgorithm); - signerBuilder.setProvider("BC"); - - X509CertificateHolder certHolder = - certificateGenerator.build(signerBuilder.build(issuerPrivateKey)); - - /* - * Next certificate factory trick is needed to make sure that the - * certificate delivered to the caller is provided by the default - * security provider instead of BouncyCastle. If we don't do this trick - * we might run into trouble when trying to use the CertPath validator. - */ -// CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); -// certificate = (X509Certificate) certificateFactory -// .generateCertificate(new ByteArrayInputStream(certificate -// .getEncoded())); - return new JcaX509CertificateConverter().getCertificate(certHolder); - } - - static Document loadDocument(InputStream documentInputStream) - throws ParserConfigurationException, SAXException, IOException { - InputSource inputSource = new InputSource(documentInputStream); - DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory - .newInstance(); - documentBuilderFactory.setNamespaceAware(true); - DocumentBuilder documentBuilder = documentBuilderFactory - .newDocumentBuilder(); - Document document = documentBuilder.parse(inputSource); - return document; - } - - static String toString(Node dom) throws TransformerException { - Source source = new DOMSource(dom); - StringWriter stringWriter = new StringWriter(); - Result result = new StreamResult(stringWriter); - TransformerFactory transformerFactory = TransformerFactory - .newInstance(); - Transformer transformer = transformerFactory.newTransformer(); - /* - * We have to omit the ?xml declaration if we want to embed the - * document. - */ - transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); - transformer.transform(source, result); - return stringWriter.getBuffer().toString(); - } - - public static X509CRL generateCrl(X509Certificate issuer, PrivateKey issuerPrivateKey) - throws CertificateEncodingException, IOException, CRLException, OperatorCreationException { - - X509CertificateHolder holder = new X509CertificateHolder(issuer.getEncoded()); - X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(holder.getIssuer(), new Date()); - crlBuilder.setNextUpdate(new Date(new Date().getTime() + 100000)); - JcaContentSignerBuilder contentBuilder = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC"); - - CRLNumber crlNumber = new CRLNumber(new BigInteger("1234")); - - crlBuilder.addExtension(Extension.cRLNumber, false, crlNumber); - X509CRLHolder x509Crl = crlBuilder.build(contentBuilder.build(issuerPrivateKey)); - return new JcaX509CRLConverter().setProvider("BC").getCRL(x509Crl); - } - - public static OCSPResp createOcspResp(X509Certificate certificate, - boolean revoked, X509Certificate issuerCertificate, - X509Certificate ocspResponderCertificate, - PrivateKey ocspResponderPrivateKey, String signatureAlgorithm, - long nonceTimeinMillis) - throws Exception { - DigestCalculator digestCalc = new JcaDigestCalculatorProviderBuilder() - .setProvider("BC").build().get(CertificateID.HASH_SHA1); - X509CertificateHolder issuerHolder = new X509CertificateHolder(issuerCertificate.getEncoded()); - CertificateID certId = new CertificateID(digestCalc, issuerHolder, certificate.getSerialNumber()); - - // request - //create a nonce to avoid replay attack - BigInteger nonce = BigInteger.valueOf(nonceTimeinMillis); - DEROctetString nonceDer = new DEROctetString(nonce.toByteArray()); - Extension ext = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, true, nonceDer); - Extensions exts = new Extensions(ext); - - OCSPReqBuilder ocspReqBuilder = new OCSPReqBuilder(); - ocspReqBuilder.addRequest(certId); - ocspReqBuilder.setRequestExtensions(exts); - OCSPReq ocspReq = ocspReqBuilder.build(); - - - SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo - (CertificateID.HASH_SHA1, ocspResponderCertificate.getPublicKey().getEncoded()); - - BasicOCSPRespBuilder basicOCSPRespBuilder = new BasicOCSPRespBuilder(keyInfo, digestCalc); - basicOCSPRespBuilder.setResponseExtensions(exts); - - // request processing - Req[] requestList = ocspReq.getRequestList(); - for (Req ocspRequest : requestList) { - CertificateID certificateID = ocspRequest.getCertID(); - CertificateStatus certificateStatus = CertificateStatus.GOOD; - if (revoked) { - certificateStatus = new RevokedStatus(new Date(), CRLReason.privilegeWithdrawn); - } - basicOCSPRespBuilder.addResponse(certificateID, certificateStatus); - } - - // basic response generation - X509CertificateHolder[] chain = null; - if (!ocspResponderCertificate.equals(issuerCertificate)) { - // TODO: HorribleProxy can't convert array input params yet - chain = new X509CertificateHolder[] { - new X509CertificateHolder(ocspResponderCertificate.getEncoded()), - issuerHolder - }; - } - - ContentSigner contentSigner = new JcaContentSignerBuilder("SHA1withRSA") - .setProvider("BC").build(ocspResponderPrivateKey); - BasicOCSPResp basicOCSPResp = basicOCSPRespBuilder.build(contentSigner, chain, new Date(nonceTimeinMillis)); - - - OCSPRespBuilder ocspRespBuilder = new OCSPRespBuilder(); - OCSPResp ocspResp = ocspRespBuilder.build(OCSPRespBuilder.SUCCESSFUL, basicOCSPResp); - - return ocspResp; - } -} diff --git a/src/ooxml/testcases/org/apache/poi/poifs/crypt/TestAgileEncryptionParameters.java b/src/ooxml/testcases/org/apache/poi/poifs/crypt/TestAgileEncryptionParameters.java deleted file mode 100644 index 0786ed51d..000000000 --- a/src/ooxml/testcases/org/apache/poi/poifs/crypt/TestAgileEncryptionParameters.java +++ /dev/null @@ -1,109 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.poifs.crypt; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import javax.crypto.Cipher; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.util.IOUtils; -import org.junit.Assume; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; - -@RunWith(Parameterized.class) -public class TestAgileEncryptionParameters { - - static byte testData[]; - - @Parameter(value = 0) - public CipherAlgorithm ca; - @Parameter(value = 1) - public HashAlgorithm ha; - @Parameter(value = 2) - public ChainingMode cm; - - @Parameters(name="{0} {1} {2}") - public static Collection data() { - CipherAlgorithm caList[] = { CipherAlgorithm.aes128, CipherAlgorithm.aes192, CipherAlgorithm.aes256, CipherAlgorithm.rc2, CipherAlgorithm.des, CipherAlgorithm.des3 }; - HashAlgorithm haList[] = { HashAlgorithm.sha1, HashAlgorithm.sha256, HashAlgorithm.sha384, HashAlgorithm.sha512, HashAlgorithm.md5 }; - ChainingMode cmList[] = { ChainingMode.cbc, ChainingMode.cfb }; - - List data = new ArrayList(); - for (CipherAlgorithm ca : caList) { - for (HashAlgorithm ha : haList) { - for (ChainingMode cm : cmList) { - data.add(new Object[]{ca,ha,cm}); - } - } - } - - return data; - } - - @BeforeClass - public static void initTestData() throws Exception { - InputStream testFile = POIDataSamples.getDocumentInstance().openResourceAsStream("SampleDoc.docx"); - testData = IOUtils.toByteArray(testFile); - testFile.close(); - } - - @Test - public void testAgileEncryptionModes() throws Exception { - int maxKeyLen = Cipher.getMaxAllowedKeyLength(ca.jceId); - Assume.assumeTrue("Please install JCE Unlimited Strength Jurisdiction Policy files", maxKeyLen >= ca.defaultKeySize); - - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - - POIFSFileSystem fsEnc = new POIFSFileSystem(); - EncryptionInfo infoEnc = new EncryptionInfo(EncryptionMode.agile, ca, ha, -1, -1, cm); - Encryptor enc = infoEnc.getEncryptor(); - enc.confirmPassword("foobaa"); - OutputStream os = enc.getDataStream(fsEnc); - os.write(testData); - os.close(); - bos.reset(); - fsEnc.writeFilesystem(bos); - fsEnc.close(); - - POIFSFileSystem fsDec = new POIFSFileSystem(new ByteArrayInputStream(bos.toByteArray())); - EncryptionInfo infoDec = new EncryptionInfo(fsDec); - Decryptor dec = infoDec.getDecryptor(); - boolean passed = dec.verifyPassword("foobaa"); - assertTrue(passed); - InputStream is = dec.getDataStream(fsDec); - byte actualData[] = IOUtils.toByteArray(is); - is.close(); - fsDec.close(); - assertArrayEquals("Failed roundtrip - "+ca+"-"+ha+"-"+cm, testData, actualData); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/poifs/crypt/TestCertificateEncryption.java b/src/ooxml/testcases/org/apache/poi/poifs/crypt/TestCertificateEncryption.java deleted file mode 100644 index 5495d7a80..000000000 --- a/src/ooxml/testcases/org/apache/poi/poifs/crypt/TestCertificateEncryption.java +++ /dev/null @@ -1,197 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.poifs.crypt; - -import static org.hamcrest.core.IsEqual.equalTo; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.security.GeneralSecurityException; -import java.security.KeyPair; -import java.security.KeyStore; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.cert.X509Certificate; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.poifs.crypt.agile.AgileDecryptor; -import org.apache.poi.poifs.crypt.agile.AgileEncryptionVerifier; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.util.IOUtils; -import org.junit.Test; - -/* -import org.junit.BeforeClass; -import java.util.Date; -import java.math.BigInteger; -import java.security.KeyPairGenerator; -import java.security.SecureRandom; -import java.security.cert.Certificate; -import sun.security.x509.AlgorithmId; -import sun.security.x509.CertificateAlgorithmId; -import sun.security.x509.CertificateIssuerName; -import sun.security.x509.CertificateSerialNumber; -import sun.security.x509.CertificateSubjectName; -import sun.security.x509.CertificateValidity; -import sun.security.x509.CertificateVersion; -import sun.security.x509.CertificateX509Key; -import sun.security.x509.X500Name; -import sun.security.x509.X509CertImpl; -import sun.security.x509.X509CertInfo; -*/ - -/** - * @see creating a self-signed certificate - */ -public class TestCertificateEncryption { - /** - * how many days from now the Certificate is valid for - */ - static final int days = 1000; - /** - * the signing algorithm, eg "SHA1withRSA" - */ - static final String algorithm = "SHA1withRSA"; - static final String password = "foobaa"; - static final String certAlias = "poitest"; - /** - * the X.509 Distinguished Name, eg "CN=Test, L=London, C=GB" - */ - static final String certDN = "CN=poitest"; - // static final File pfxFile = TempFile.createTempFile("poitest", ".pfx"); - static byte pfxFileBytes[]; - - static class CertData { - KeyPair keypair; - X509Certificate x509; - } - - /** - * Create a self-signed X.509 Certificate - * - * The keystore generation / loading is split, because normally the keystore would - * already exist. - */ - /* @BeforeClass - public static void initKeystore() throws GeneralSecurityException, IOException { - CertData certData = new CertData(); - - KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); - keyGen.initialize(1024); - certData.keypair = keyGen.generateKeyPair(); - PrivateKey privkey = certData.keypair.getPrivate(); - PublicKey publkey = certData.keypair.getPublic(); - - X509CertInfo info = new X509CertInfo(); - Date from = new Date(); - Date to = new Date(from.getTime() + days * 86400000l); - CertificateValidity interval = new CertificateValidity(from, to); - BigInteger sn = new BigInteger(64, new SecureRandom()); - X500Name owner = new X500Name(certDN); - - info.set(X509CertInfo.VALIDITY, interval); - info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(sn)); - info.set(X509CertInfo.SUBJECT, new CertificateSubjectName(owner)); - info.set(X509CertInfo.ISSUER, new CertificateIssuerName(owner)); - info.set(X509CertInfo.KEY, new CertificateX509Key(publkey)); - info.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3)); - AlgorithmId algo = new AlgorithmId(AlgorithmId.md5WithRSAEncryption_oid); - info.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(algo)); - - // Sign the cert to identify the algorithm that's used. - X509CertImpl cert = new X509CertImpl(info); - cert.sign(privkey, algorithm); - - // Update the algorith, and resign. - algo = (AlgorithmId)cert.get(X509CertImpl.SIG_ALG); - info.set(CertificateAlgorithmId.NAME + "." + CertificateAlgorithmId.ALGORITHM, algo); - cert = new X509CertImpl(info); - cert.sign(privkey, algorithm); - certData.x509 = cert; - - KeyStore keystore = KeyStore.getInstance("PKCS12"); - keystore.load(null, password.toCharArray()); - keystore.setKeyEntry(certAlias, certData.keypair.getPrivate(), password.toCharArray(), new Certificate[]{certData.x509}); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - keystore.store(bos, password.toCharArray()); - pfxFileBytes = bos.toByteArray(); - } */ - - public CertData loadKeystore() - throws GeneralSecurityException, IOException { - KeyStore keystore = KeyStore.getInstance("PKCS12"); - - // InputStream fis = new ByteArrayInputStream(pfxFileBytes); - InputStream fis = POIDataSamples.getPOIFSInstance().openResourceAsStream("poitest.pfx"); - keystore.load(fis, password.toCharArray()); - fis.close(); - - X509Certificate x509 = (X509Certificate)keystore.getCertificate(certAlias); - PrivateKey privateKey = (PrivateKey)keystore.getKey(certAlias, password.toCharArray()); - PublicKey publicKey = x509.getPublicKey(); - - CertData certData = new CertData(); - certData.keypair = new KeyPair(publicKey, privateKey); - certData.x509 = x509; - - return certData; - } - - @Test - public void testCertificateEncryption() throws Exception { - POIFSFileSystem fs = new POIFSFileSystem(); - EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile, CipherAlgorithm.aes128, HashAlgorithm.sha1, -1, -1, ChainingMode.cbc); - AgileEncryptionVerifier aev = (AgileEncryptionVerifier)info.getVerifier(); - CertData certData = loadKeystore(); - aev.addCertificate(certData.x509); - - Encryptor enc = info.getEncryptor(); - enc.confirmPassword("foobaa"); - - File file = POIDataSamples.getDocumentInstance().getFile("VariousPictures.docx"); - InputStream fis = new FileInputStream(file); - byte byteExpected[] = IOUtils.toByteArray(fis); - fis.close(); - - OutputStream os = enc.getDataStream(fs); - IOUtils.copy(new ByteArrayInputStream(byteExpected), os); - os.close(); - - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - fs.writeFilesystem(bos); - bos.close(); - - fs = new POIFSFileSystem(new ByteArrayInputStream(bos.toByteArray())); - info = new EncryptionInfo(fs); - AgileDecryptor agDec = (AgileDecryptor)info.getDecryptor(); - boolean passed = agDec.verifyPassword(certData.keypair, certData.x509); - assertTrue("certificate verification failed", passed); - - fis = agDec.getDataStream(fs); - byte byteActual[] = IOUtils.toByteArray(fis); - fis.close(); - - assertThat(byteExpected, equalTo(byteActual)); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/poifs/crypt/TestDecryptor.java b/src/ooxml/testcases/org/apache/poi/poifs/crypt/TestDecryptor.java deleted file mode 100644 index c6c8f959e..000000000 --- a/src/ooxml/testcases/org/apache/poi/poifs/crypt/TestDecryptor.java +++ /dev/null @@ -1,198 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.poifs.crypt; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.security.GeneralSecurityException; -import java.util.zip.ZipEntry; -import java.util.zip.ZipInputStream; - -import javax.crypto.Cipher; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.poifs.filesystem.DirectoryNode; -import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.util.IOUtils; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.Assume; -import org.junit.Test; - -public class TestDecryptor { - @Test - public void passwordVerification() throws IOException, GeneralSecurityException { - POIFSFileSystem fs = new POIFSFileSystem(POIDataSamples.getPOIFSInstance().openResourceAsStream("protect.xlsx")); - - EncryptionInfo info = new EncryptionInfo(fs); - - Decryptor d = Decryptor.getInstance(info); - - assertTrue(d.verifyPassword(Decryptor.DEFAULT_PASSWORD)); - - fs.close(); - } - - @Test - public void decrypt() throws IOException, GeneralSecurityException { - POIFSFileSystem fs = new POIFSFileSystem(POIDataSamples.getPOIFSInstance().openResourceAsStream("protect.xlsx")); - - EncryptionInfo info = new EncryptionInfo(fs); - - Decryptor d = Decryptor.getInstance(info); - - d.verifyPassword(Decryptor.DEFAULT_PASSWORD); - - zipOk(fs.getRoot(), d); - - fs.close(); - } - - @Test - public void agile() throws IOException, GeneralSecurityException { - POIFSFileSystem fs = new POIFSFileSystem(POIDataSamples.getPOIFSInstance().openResourceAsStream("protected_agile.docx")); - - EncryptionInfo info = new EncryptionInfo(fs); - - assertTrue(info.getVersionMajor() == 4 && info.getVersionMinor() == 4); - - Decryptor d = Decryptor.getInstance(info); - - assertTrue(d.verifyPassword(Decryptor.DEFAULT_PASSWORD)); - - zipOk(fs.getRoot(), d); - - fs.close(); - } - - private void zipOk(DirectoryNode root, Decryptor d) throws IOException, GeneralSecurityException { - ZipInputStream zin = new ZipInputStream(d.getDataStream(root)); - - while (true) { - ZipEntry entry = zin.getNextEntry(); - if (entry==null) { - break; - } - // crc32 is checked within zip-stream - if (entry.isDirectory()) { - continue; - } - zin.skip(entry.getSize()); - byte buf[] = new byte[10]; - int readBytes = zin.read(buf); - // zin.available() doesn't work for entries - assertEquals("size failed for "+entry.getName(), -1, readBytes); - } - - zin.close(); - } - - @Test - public void dataLength() throws Exception { - POIFSFileSystem fs = new POIFSFileSystem(POIDataSamples.getPOIFSInstance().openResourceAsStream("protected_agile.docx")); - - EncryptionInfo info = new EncryptionInfo(fs); - - Decryptor d = Decryptor.getInstance(info); - - d.verifyPassword(Decryptor.DEFAULT_PASSWORD); - - InputStream is = d.getDataStream(fs); - - long len = d.getLength(); - assertEquals(12810, len); - - byte[] buf = new byte[(int)len]; - - is.read(buf); - - ZipInputStream zin = new ZipInputStream(new ByteArrayInputStream(buf)); - - while (true) { - ZipEntry entry = zin.getNextEntry(); - if (entry==null) { - break; - } - - while (zin.available()>0) { - zin.skip(zin.available()); - } - } - } - - @Test - public void bug57080() throws Exception { - // the test file contains a wrong ole entry size, produced by extenxls - // the fix limits the available size and tries to read all entries - File f = POIDataSamples.getPOIFSInstance().getFile("extenxls_pwd123.xlsx"); - NPOIFSFileSystem fs = new NPOIFSFileSystem(f, true); - EncryptionInfo info = new EncryptionInfo(fs); - Decryptor d = Decryptor.getInstance(info); - d.verifyPassword("pwd123"); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - ZipInputStream zis = new ZipInputStream(d.getDataStream(fs)); - ZipEntry ze; - while ((ze = zis.getNextEntry()) != null) { - bos.reset(); - IOUtils.copy(zis, bos); - assertEquals(ze.getSize(), bos.size()); - } - - zis.close(); - fs.close(); - } - - @Test - public void test58616() throws IOException, GeneralSecurityException { - FileInputStream fis = new FileInputStream(XSSFTestDataSamples.getSampleFile("58616.xlsx")); - POIFSFileSystem pfs = new POIFSFileSystem(fis); - EncryptionInfo info = new EncryptionInfo(pfs); - Decryptor dec = Decryptor.getInstance(info); - //dec.verifyPassword(null); - dec.getDataStream(pfs); - pfs.close(); - fis.close(); - } - - @Test - public void bug60320() throws IOException, GeneralSecurityException { - int maxKeyLen = Cipher.getMaxAllowedKeyLength("AES"); - Assume.assumeTrue("Please install JCE Unlimited Strength Jurisdiction Policy files for AES 256", maxKeyLen == 2147483647); - - InputStream is = POIDataSamples.getPOIFSInstance().openResourceAsStream("60320-protected.xlsx"); - POIFSFileSystem fs = new POIFSFileSystem(is); - is.close(); - - EncryptionInfo info = new EncryptionInfo(fs); - - Decryptor d = Decryptor.getInstance(info); - - boolean b = d.verifyPassword("Test001!!"); - assertTrue(b); - - zipOk(fs.getRoot(), d); - - fs.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/poifs/crypt/TestEncryptionInfo.java b/src/ooxml/testcases/org/apache/poi/poifs/crypt/TestEncryptionInfo.java deleted file mode 100644 index 0b4e3d270..000000000 --- a/src/ooxml/testcases/org/apache/poi/poifs/crypt/TestEncryptionInfo.java +++ /dev/null @@ -1,65 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.poifs.crypt; - -import static org.junit.Assert.assertEquals; - -import java.io.IOException; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.junit.Test; - -public class TestEncryptionInfo { - @Test - public void testEncryptionInfo() throws IOException { - POIFSFileSystem fs = new POIFSFileSystem(POIDataSamples.getPOIFSInstance().openResourceAsStream("protect.xlsx")); - - EncryptionInfo info = new EncryptionInfo(fs); - - assertEquals(3, info.getVersionMajor()); - assertEquals(2, info.getVersionMinor()); - - assertEquals(CipherAlgorithm.aes128, info.getHeader().getCipherAlgorithm()); - assertEquals(HashAlgorithm.sha1, info.getHeader().getHashAlgorithm()); - assertEquals(128, info.getHeader().getKeySize()); - assertEquals(32, info.getVerifier().getEncryptedVerifierHash().length); - assertEquals(CipherProvider.aes, info.getHeader().getCipherProvider()); - assertEquals("Microsoft Enhanced RSA and AES Cryptographic Provider", info.getHeader().getCspName()); - - fs.close(); - } - - @Test - public void testEncryptionInfoSHA512() throws Exception { - POIFSFileSystem fs = new POIFSFileSystem(POIDataSamples.getPOIFSInstance().openResourceAsStream("protected_sha512.xlsx")); - - EncryptionInfo info = new EncryptionInfo(fs); - - assertEquals(4, info.getVersionMajor()); - assertEquals(4, info.getVersionMinor()); - - assertEquals(CipherAlgorithm.aes256, info.getHeader().getCipherAlgorithm()); - assertEquals(HashAlgorithm.sha512, info.getHeader().getHashAlgorithm()); - assertEquals(256, info.getHeader().getKeySize()); - assertEquals(64, info.getVerifier().getEncryptedVerifierHash().length); - assertEquals(CipherProvider.aes, info.getHeader().getCipherProvider()); -// assertEquals("Microsoft Enhanced RSA and AES Cryptographic Provider", info.getHeader().getCspName()); - - fs.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/poifs/crypt/TestEncryptor.java b/src/ooxml/testcases/org/apache/poi/poifs/crypt/TestEncryptor.java deleted file mode 100644 index 2e95fa59d..000000000 --- a/src/ooxml/testcases/org/apache/poi/poifs/crypt/TestEncryptor.java +++ /dev/null @@ -1,535 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.poifs.crypt; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.Iterator; - -import javax.crypto.Cipher; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.openxml4j.opc.ContentTypes; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.poifs.crypt.agile.AgileDecryptor; -import org.apache.poi.poifs.crypt.agile.AgileEncryptionHeader; -import org.apache.poi.poifs.crypt.agile.AgileEncryptionVerifier; -import org.apache.poi.poifs.filesystem.DirectoryNode; -import org.apache.poi.poifs.filesystem.DocumentNode; -import org.apache.poi.poifs.filesystem.Entry; -import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.util.BoundedInputStream; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.TempFile; -import org.apache.poi.xwpf.usermodel.XWPFDocument; -import org.junit.Assume; -import org.junit.Ignore; -import org.junit.Test; - -public class TestEncryptor { - @Test - public void binaryRC4Encryption() throws Exception { - // please contribute a real sample file, which is binary rc4 encrypted - // ... at least the output can be opened in Excel Viewer - String password = "pass"; - - InputStream is = POIDataSamples.getSpreadSheetInstance().openResourceAsStream("SimpleMultiCell.xlsx"); - ByteArrayOutputStream payloadExpected = new ByteArrayOutputStream(); - IOUtils.copy(is, payloadExpected); - is.close(); - - POIFSFileSystem fs = new POIFSFileSystem(); - EncryptionInfo ei = new EncryptionInfo(EncryptionMode.binaryRC4); - Encryptor enc = ei.getEncryptor(); - enc.confirmPassword(password); - - OutputStream os = enc.getDataStream(fs.getRoot()); - payloadExpected.writeTo(os); - os.close(); - - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - fs.writeFilesystem(bos); - - fs = new POIFSFileSystem(new ByteArrayInputStream(bos.toByteArray())); - ei = new EncryptionInfo(fs); - Decryptor dec = ei.getDecryptor(); - boolean b = dec.verifyPassword(password); - assertTrue(b); - - ByteArrayOutputStream payloadActual = new ByteArrayOutputStream(); - is = dec.getDataStream(fs.getRoot()); - IOUtils.copy(is,payloadActual); - is.close(); - - assertArrayEquals(payloadExpected.toByteArray(), payloadActual.toByteArray()); - } - - @Test - public void agileEncryption() throws Exception { - int maxKeyLen = Cipher.getMaxAllowedKeyLength("AES"); - Assume.assumeTrue("Please install JCE Unlimited Strength Jurisdiction Policy files for AES 256", maxKeyLen == 2147483647); - - File file = POIDataSamples.getDocumentInstance().getFile("bug53475-password-is-pass.docx"); - String pass = "pass"; - NPOIFSFileSystem nfs = new NPOIFSFileSystem(file); - - // Check the encryption details - EncryptionInfo infoExpected = new EncryptionInfo(nfs); - Decryptor decExpected = Decryptor.getInstance(infoExpected); - boolean passed = decExpected.verifyPassword(pass); - assertTrue("Unable to process: document is encrypted", passed); - - // extract the payload - InputStream is = decExpected.getDataStream(nfs); - byte payloadExpected[] = IOUtils.toByteArray(is); - is.close(); - - long decPackLenExpected = decExpected.getLength(); - assertEquals(decPackLenExpected, payloadExpected.length); - - is = nfs.getRoot().createDocumentInputStream(Decryptor.DEFAULT_POIFS_ENTRY); - is = new BoundedInputStream(is, is.available()-16); // ignore padding block - byte encPackExpected[] = IOUtils.toByteArray(is); - is.close(); - - // listDir(nfs.getRoot(), "orig", ""); - - nfs.close(); - - // check that same verifier/salt lead to same hashes - byte verifierSaltExpected[] = infoExpected.getVerifier().getSalt(); - byte verifierExpected[] = decExpected.getVerifier(); - byte keySalt[] = infoExpected.getHeader().getKeySalt(); - byte keySpec[] = decExpected.getSecretKey().getEncoded(); - byte integritySalt[] = decExpected.getIntegrityHmacKey(); - // the hmacs of the file always differ, as we use PKCS5-padding to pad the bytes - // whereas office just uses random bytes - // byte integrityHash[] = d.getIntegrityHmacValue(); - - POIFSFileSystem fs = new POIFSFileSystem(); - EncryptionInfo infoActual = new EncryptionInfo( - EncryptionMode.agile - , infoExpected.getVerifier().getCipherAlgorithm() - , infoExpected.getVerifier().getHashAlgorithm() - , infoExpected.getHeader().getKeySize() - , infoExpected.getHeader().getBlockSize() - , infoExpected.getVerifier().getChainingMode() - ); - - Encryptor e = Encryptor.getInstance(infoActual); - e.confirmPassword(pass, keySpec, keySalt, verifierExpected, verifierSaltExpected, integritySalt); - - OutputStream os = e.getDataStream(fs); - IOUtils.copy(new ByteArrayInputStream(payloadExpected), os); - os.close(); - - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - fs.writeFilesystem(bos); - fs.close(); - - nfs = new NPOIFSFileSystem(new ByteArrayInputStream(bos.toByteArray())); - infoActual = new EncryptionInfo(nfs.getRoot()); - Decryptor decActual = Decryptor.getInstance(infoActual); - passed = decActual.verifyPassword(pass); - assertTrue("Unable to process: document is encrypted", passed); - - // extract the payload - is = decActual.getDataStream(nfs); - byte payloadActual[] = IOUtils.toByteArray(is); - is.close(); - - long decPackLenActual = decActual.getLength(); - - is = nfs.getRoot().createDocumentInputStream(Decryptor.DEFAULT_POIFS_ENTRY); - is = new BoundedInputStream(is, is.available()-16); // ignore padding block - byte encPackActual[] = IOUtils.toByteArray(is); - is.close(); - - // listDir(nfs.getRoot(), "copy", ""); - - nfs.close(); - - AgileEncryptionHeader aehExpected = (AgileEncryptionHeader)infoExpected.getHeader(); - AgileEncryptionHeader aehActual = (AgileEncryptionHeader)infoActual.getHeader(); - assertArrayEquals(aehExpected.getEncryptedHmacKey(), aehActual.getEncryptedHmacKey()); - assertEquals(decPackLenExpected, decPackLenActual); - assertArrayEquals(payloadExpected, payloadActual); - assertArrayEquals(encPackExpected, encPackActual); - } - - @Test - public void standardEncryption() throws Exception { - File file = POIDataSamples.getDocumentInstance().getFile("bug53475-password-is-solrcell.docx"); - String pass = "solrcell"; - - NPOIFSFileSystem nfs = new NPOIFSFileSystem(file); - - // Check the encryption details - EncryptionInfo infoExpected = new EncryptionInfo(nfs); - Decryptor d = Decryptor.getInstance(infoExpected); - boolean passed = d.verifyPassword(pass); - assertTrue("Unable to process: document is encrypted", passed); - - // extract the payload - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - InputStream is = d.getDataStream(nfs); - IOUtils.copy(is, bos); - is.close(); - nfs.close(); - byte payloadExpected[] = bos.toByteArray(); - - // check that same verifier/salt lead to same hashes - byte verifierSaltExpected[] = infoExpected.getVerifier().getSalt(); - byte verifierExpected[] = d.getVerifier(); - byte keySpec[] = d.getSecretKey().getEncoded(); - byte keySalt[] = infoExpected.getHeader().getKeySalt(); - - - EncryptionInfo infoActual = new EncryptionInfo( - EncryptionMode.standard - , infoExpected.getVerifier().getCipherAlgorithm() - , infoExpected.getVerifier().getHashAlgorithm() - , infoExpected.getHeader().getKeySize() - , infoExpected.getHeader().getBlockSize() - , infoExpected.getVerifier().getChainingMode() - ); - - Encryptor e = Encryptor.getInstance(infoActual); - e.confirmPassword(pass, keySpec, keySalt, verifierExpected, verifierSaltExpected, null); - - assertArrayEquals(infoExpected.getVerifier().getEncryptedVerifier(), infoActual.getVerifier().getEncryptedVerifier()); - assertArrayEquals(infoExpected.getVerifier().getEncryptedVerifierHash(), infoActual.getVerifier().getEncryptedVerifierHash()); - - // now we use a newly generated salt/verifier and check - // if the file content is still the same - - infoActual = new EncryptionInfo( - EncryptionMode.standard - , infoExpected.getVerifier().getCipherAlgorithm() - , infoExpected.getVerifier().getHashAlgorithm() - , infoExpected.getHeader().getKeySize() - , infoExpected.getHeader().getBlockSize() - , infoExpected.getVerifier().getChainingMode() - ); - - e = Encryptor.getInstance(infoActual); - e.confirmPassword(pass); - - POIFSFileSystem fs = new POIFSFileSystem(); - OutputStream os = e.getDataStream(fs); - IOUtils.copy(new ByteArrayInputStream(payloadExpected), os); - os.close(); - - bos.reset(); - fs.writeFilesystem(bos); - - ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); - - // FileOutputStream fos = new FileOutputStream("encrypted.docx"); - // IOUtils.copy(bis, fos); - // fos.close(); - // bis.reset(); - - nfs = new NPOIFSFileSystem(bis); - infoExpected = new EncryptionInfo(nfs); - d = Decryptor.getInstance(infoExpected); - passed = d.verifyPassword(pass); - assertTrue("Unable to process: document is encrypted", passed); - - bos.reset(); - is = d.getDataStream(nfs); - IOUtils.copy(is, bos); - is.close(); - nfs.close(); - byte payloadActual[] = bos.toByteArray(); - - assertArrayEquals(payloadExpected, payloadActual); - } - - /** - * Ensure we can encrypt a package that is missing the Core - * Properties, eg one from dodgy versions of Jasper Reports - * See https://github.com/nestoru/xlsxenc/ and - * http://stackoverflow.com/questions/28593223 - */ - @Test - public void encryptPackageWithoutCoreProperties() throws Exception { - // Open our file without core properties - File inp = POIDataSamples.getOpenXML4JInstance().getFile("OPCCompliance_NoCoreProperties.xlsx"); - OPCPackage pkg = OPCPackage.open(inp.getPath()); - - // It doesn't have any core properties yet - assertEquals(0, pkg.getPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).size()); - assertNotNull(pkg.getPackageProperties()); - assertNotNull(pkg.getPackageProperties().getLanguageProperty()); - assertNull(pkg.getPackageProperties().getLanguageProperty().getValue()); - - // Encrypt it - EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile); - NPOIFSFileSystem fs = new NPOIFSFileSystem(); - - Encryptor enc = info.getEncryptor(); - enc.confirmPassword("password"); - OutputStream os = enc.getDataStream(fs); - pkg.save(os); - os.close(); - pkg.revert(); - - // Save the resulting OLE2 document, and re-open it - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - fs.writeFilesystem(baos); - fs.close(); - - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - NPOIFSFileSystem inpFS = new NPOIFSFileSystem(bais); - - // Check we can decrypt it - info = new EncryptionInfo(inpFS); - Decryptor d = Decryptor.getInstance(info); - assertEquals(true, d.verifyPassword("password")); - - OPCPackage inpPkg = OPCPackage.open(d.getDataStream(inpFS)); - - // Check it now has empty core properties - assertEquals(1, inpPkg.getPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).size()); - assertNotNull(inpPkg.getPackageProperties()); - assertNotNull(inpPkg.getPackageProperties().getLanguageProperty()); - assertNull(inpPkg.getPackageProperties().getLanguageProperty().getValue()); - - inpPkg.close(); - inpFS.close(); - } - - @Test - @Ignore - public void inPlaceRewrite() throws Exception { - File f = TempFile.createTempFile("protected_agile", ".docx"); - // File f = new File("protected_agile.docx"); - FileOutputStream fos = new FileOutputStream(f); - InputStream fis = POIDataSamples.getPOIFSInstance().openResourceAsStream("protected_agile.docx"); - IOUtils.copy(fis, fos); - fis.close(); - fos.close(); - - NPOIFSFileSystem fs = new NPOIFSFileSystem(f, false); - - // decrypt the protected file - in this case it was encrypted with the default password - EncryptionInfo encInfo = new EncryptionInfo(fs); - Decryptor d = encInfo.getDecryptor(); - boolean b = d.verifyPassword(Decryptor.DEFAULT_PASSWORD); - assertTrue(b); - - // do some strange things with it ;) - InputStream docIS = d.getDataStream(fs); - XWPFDocument docx = new XWPFDocument(docIS); - docx.getParagraphArray(0).insertNewRun(0).setText("POI was here! All your base are belong to us!"); - docx.getParagraphArray(0).insertNewRun(1).addBreak(); - - // and encrypt it again - Encryptor e = encInfo.getEncryptor(); - e.confirmPassword("AYBABTU"); - docx.write(e.getDataStream(fs)); - docx.close(); - docIS.close(); - - docx.close(); - fs.close(); - } - - - private void listEntry(DocumentNode de, String ext, String path) throws IOException { - path += "\\" + de.getName().replaceAll("[\\p{Cntrl}]", "_"); - System.out.println(ext+": "+path+" ("+de.getSize()+" bytes)"); - - String name = de.getName().replaceAll("[\\p{Cntrl}]", "_"); - - InputStream is = ((DirectoryNode)de.getParent()).createDocumentInputStream(de); - FileOutputStream fos = new FileOutputStream("solr."+name+"."+ext); - IOUtils.copy(is, fos); - fos.close(); - is.close(); - } - - @SuppressWarnings("unused") - private void listDir(DirectoryNode dn, String ext, String path) throws IOException { - path += "\\" + dn.getName().replace('\u0006', '_'); - System.out.println(ext+": "+path+" ("+dn.getStorageClsid()+")"); - - Iterator iter = dn.getEntries(); - while (iter.hasNext()) { - Entry ent = iter.next(); - if (ent instanceof DirectoryNode) { - listDir((DirectoryNode)ent, ext, path); - } else { - listEntry((DocumentNode)ent, ext, path); - } - } - } - - /* - * this test simulates the generation of bugs 60320 sample file - * as the padding bytes of the EncryptedPackage stream are random or in POIs case PKCS5-padded - * one would need to mock those bytes to get the same hmacValues - see diff below - * - * this use-case is experimental - for the time being the setters of the encryption classes - * are spreaded between two packages and are protected - so you would need to violate - * the packages rules and provide a helper class in the *poifs.crypt package-namespace. - * the default way of defining the encryption settings is via the EncryptionInfo class - */ - @Test - public void bug60320CustomEncrypt() throws Exception { - int maxKeyLen = Cipher.getMaxAllowedKeyLength("AES"); - Assume.assumeTrue("Please install JCE Unlimited Strength Jurisdiction Policy files for AES 256", maxKeyLen == 2147483647); - - // --- src/java/org/apache/poi/poifs/crypt/ChunkedCipherOutputStream.java (revision 1766745) - // +++ src/java/org/apache/poi/poifs/crypt/ChunkedCipherOutputStream.java (working copy) - // @@ -208,6 +208,13 @@ - // protected int invokeCipher(int posInChunk, boolean doFinal) throws GeneralSecurityException { - // byte plain[] = (_plainByteFlags.isEmpty()) ? null : _chunk.clone(); - // - // + if (posInChunk < 4096) { - // + _cipher.update(_chunk, 0, posInChunk, _chunk); - // + byte bla[] = { (byte)0x7A,(byte)0x0F,(byte)0x27,(byte)0xF0,(byte)0x17,(byte)0x6E,(byte)0x77,(byte)0x05,(byte)0xB9,(byte)0xDA,(byte)0x49,(byte)0xF9,(byte)0xD7,(byte)0x8E,(byte)0x03,(byte)0x1D }; - // + System.arraycopy(bla, 0, _chunk, posInChunk-2, bla.length); - // + return posInChunk-2+bla.length; - // + } - // + - // int ciLen = (doFinal) - // ? _cipher.doFinal(_chunk, 0, posInChunk, _chunk) - // : _cipher.update(_chunk, 0, posInChunk, _chunk); - // - // --- src/ooxml/java/org/apache/poi/poifs/crypt/agile/AgileDecryptor.java (revision 1766745) - // +++ src/ooxml/java/org/apache/poi/poifs/crypt/agile/AgileDecryptor.java (working copy) - // - // @@ -300,7 +297,7 @@ - // protected static Cipher initCipherForBlock(Cipher existing, int block, boolean lastChunk, EncryptionInfo encryptionInfo, SecretKey skey, int encryptionMode) - // throws GeneralSecurityException { - // EncryptionHeader header = encryptionInfo.getHeader(); - // - String padding = (lastChunk ? "PKCS5Padding" : "NoPadding"); - // + String padding = "NoPadding"; // (lastChunk ? "PKCS5Padding" : "NoPadding"); - // if (existing == null || !existing.getAlgorithm().endsWith(padding)) { - // existing = getCipher(skey, header.getCipherAlgorithm(), header.getChainingMode(), header.getKeySalt(), encryptionMode, padding); - // } - - InputStream is = POIDataSamples.getPOIFSInstance().openResourceAsStream("60320-protected.xlsx"); - POIFSFileSystem fsOrig = new POIFSFileSystem(is); - is.close(); - EncryptionInfo infoOrig = new EncryptionInfo(fsOrig); - Decryptor decOrig = infoOrig.getDecryptor(); - boolean b = decOrig.verifyPassword("Test001!!"); - assertTrue(b); - InputStream decIn = decOrig.getDataStream(fsOrig); - byte[] zipInput = IOUtils.toByteArray(decIn); - decIn.close(); - - InputStream epOrig = fsOrig.getRoot().createDocumentInputStream("EncryptedPackage"); - // ignore the 16 padding bytes - byte[] epOrigBytes = IOUtils.toByteArray(epOrig, 9400); - epOrig.close(); - - EncryptionInfo eiNew = new EncryptionInfo(EncryptionMode.agile); - AgileEncryptionHeader aehHeader = (AgileEncryptionHeader)eiNew.getHeader(); - aehHeader.setCipherAlgorithm(CipherAlgorithm.aes128); - aehHeader.setHashAlgorithm(HashAlgorithm.sha1); - AgileEncryptionVerifier aehVerifier = (AgileEncryptionVerifier)eiNew.getVerifier(); - - // this cast might look strange - if the setters would be public, it will become obsolete - // see http://stackoverflow.com/questions/5637650/overriding-protected-methods-in-java - ((EncryptionVerifier)aehVerifier).setCipherAlgorithm(CipherAlgorithm.aes256); - aehVerifier.setHashAlgorithm(HashAlgorithm.sha512); - - Encryptor enc = eiNew.getEncryptor(); - enc.confirmPassword("Test001!!", - infoOrig.getDecryptor().getSecretKey().getEncoded(), - infoOrig.getHeader().getKeySalt(), - infoOrig.getDecryptor().getVerifier(), - infoOrig.getVerifier().getSalt(), - infoOrig.getDecryptor().getIntegrityHmacKey() - ); - NPOIFSFileSystem fsNew = new NPOIFSFileSystem(); - OutputStream os = enc.getDataStream(fsNew); - os.write(zipInput); - os.close(); - - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - fsNew.writeFilesystem(bos); - fsNew.close(); - - NPOIFSFileSystem fsReload = new NPOIFSFileSystem(new ByteArrayInputStream(bos.toByteArray())); - InputStream epReload = fsReload.getRoot().createDocumentInputStream("EncryptedPackage"); - byte[] epNewBytes = IOUtils.toByteArray(epReload, 9400); - epReload.close(); - - assertArrayEquals(epOrigBytes, epNewBytes); - - EncryptionInfo infoReload = new EncryptionInfo(fsOrig); - Decryptor decReload = infoReload.getDecryptor(); - b = decReload.verifyPassword("Test001!!"); - assertTrue(b); - - AgileEncryptionHeader aehOrig = (AgileEncryptionHeader)infoOrig.getHeader(); - AgileEncryptionHeader aehReload = (AgileEncryptionHeader)infoReload.getHeader(); - assertEquals(aehOrig.getBlockSize(), aehReload.getBlockSize()); - assertEquals(aehOrig.getChainingMode(), aehReload.getChainingMode()); - assertEquals(aehOrig.getCipherAlgorithm(), aehReload.getCipherAlgorithm()); - assertEquals(aehOrig.getCipherProvider(), aehReload.getCipherProvider()); - assertEquals(aehOrig.getCspName(), aehReload.getCspName()); - assertArrayEquals(aehOrig.getEncryptedHmacKey(), aehReload.getEncryptedHmacKey()); - // this only works, when the paddings are mocked to be the same ... - // assertArrayEquals(aehOrig.getEncryptedHmacValue(), aehReload.getEncryptedHmacValue()); - assertEquals(aehOrig.getFlags(), aehReload.getFlags()); - assertEquals(aehOrig.getHashAlgorithm(), aehReload.getHashAlgorithm()); - assertArrayEquals(aehOrig.getKeySalt(), aehReload.getKeySalt()); - assertEquals(aehOrig.getKeySize(), aehReload.getKeySize()); - - AgileEncryptionVerifier aevOrig = (AgileEncryptionVerifier)infoOrig.getVerifier(); - AgileEncryptionVerifier aevReload = (AgileEncryptionVerifier)infoReload.getVerifier(); - assertEquals(aevOrig.getBlockSize(), aevReload.getBlockSize()); - assertEquals(aevOrig.getChainingMode(), aevReload.getChainingMode()); - assertEquals(aevOrig.getCipherAlgorithm(), aevReload.getCipherAlgorithm()); - assertArrayEquals(aevOrig.getEncryptedKey(), aevReload.getEncryptedKey()); - assertArrayEquals(aevOrig.getEncryptedVerifier(), aevReload.getEncryptedVerifier()); - assertArrayEquals(aevOrig.getEncryptedVerifierHash(), aevReload.getEncryptedVerifierHash()); - assertEquals(aevOrig.getHashAlgorithm(), aevReload.getHashAlgorithm()); - assertEquals(aevOrig.getKeySize(), aevReload.getKeySize()); - assertArrayEquals(aevOrig.getSalt(), aevReload.getSalt()); - assertEquals(aevOrig.getSpinCount(), aevReload.getSpinCount()); - - AgileDecryptor adOrig = (AgileDecryptor)infoOrig.getDecryptor(); - AgileDecryptor adReload = (AgileDecryptor)infoReload.getDecryptor(); - - assertArrayEquals(adOrig.getIntegrityHmacKey(), adReload.getIntegrityHmacKey()); - // doesn't work without mocking ... see above - // assertArrayEquals(adOrig.getIntegrityHmacValue(), adReload.getIntegrityHmacValue()); - assertArrayEquals(adOrig.getSecretKey().getEncoded(), adReload.getSecretKey().getEncoded()); - assertArrayEquals(adOrig.getVerifier(), adReload.getVerifier()); - - fsReload.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/poifs/crypt/TestSecureTempZip.java b/src/ooxml/testcases/org/apache/poi/poifs/crypt/TestSecureTempZip.java deleted file mode 100644 index 6244cec2f..000000000 --- a/src/ooxml/testcases/org/apache/poi/poifs/crypt/TestSecureTempZip.java +++ /dev/null @@ -1,127 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.crypt; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import javax.crypto.Cipher; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.security.GeneralSecurityException; - -import org.apache.poi.openxml4j.exceptions.OpenXML4JException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.util.ZipEntrySource; -import org.apache.poi.poifs.crypt.temp.AesZipFileZipEntrySource; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.extractor.XSSFBEventBasedExcelExtractor; -import org.apache.poi.xssf.extractor.XSSFEventBasedExcelExtractor; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.apache.xmlbeans.XmlException; -import org.junit.Assume; -import org.junit.Test; - -public class TestSecureTempZip { - - /** - * Test case for #59841 - this is an example on how to use encrypted temp files, - * which are streamed into POI opposed to having everything in memory - */ - @Test - public void protectedTempZip() throws IOException, GeneralSecurityException, XmlException, OpenXML4JException { - File tikaProt = XSSFTestDataSamples.getSampleFile("protected_passtika.xlsx"); - FileInputStream fis = new FileInputStream(tikaProt); - POIFSFileSystem poifs = new POIFSFileSystem(fis); - EncryptionInfo ei = new EncryptionInfo(poifs); - Decryptor dec = ei.getDecryptor(); - boolean passOk = dec.verifyPassword("tika"); - assertTrue(passOk); - - // extract encrypted ooxml file and write to custom encrypted zip file - InputStream is = dec.getDataStream(poifs); - - // provide ZipEntrySource to poi which decrypts on the fly - ZipEntrySource source = AesZipFileZipEntrySource.createZipEntrySource(is); - - // test the source - OPCPackage opc = OPCPackage.open(source); - String expected = "This is an Encrypted Excel spreadsheet."; - - XSSFEventBasedExcelExtractor extractor = new XSSFEventBasedExcelExtractor(opc); - extractor.setIncludeSheetNames(false); - String txt = extractor.getText(); - assertEquals(expected, txt.trim()); - - XSSFWorkbook wb = new XSSFWorkbook(opc); - txt = wb.getSheetAt(0).getRow(0).getCell(0).getStringCellValue(); - assertEquals(expected, txt); - - extractor.close(); - - wb.close(); - opc.close(); - source.close(); - poifs.close(); - fis.close(); - } - - /** - * Now try with xlsb. - */ - @Test - public void protectedXLSBZip() throws IOException, GeneralSecurityException, XmlException, OpenXML4JException { - //The test file requires that JCE unlimited be installed. - //If it isn't installed, skip this test. - int maxKeyLen = Cipher.getMaxAllowedKeyLength("AES"); - Assume.assumeTrue("Please install JCE Unlimited Strength Jurisdiction Policy files for AES 256", - maxKeyLen == 2147483647); - - File tikaProt = XSSFTestDataSamples.getSampleFile("protected_passtika.xlsb"); - FileInputStream fis = new FileInputStream(tikaProt); - POIFSFileSystem poifs = new POIFSFileSystem(fis); - EncryptionInfo ei = new EncryptionInfo(poifs); - Decryptor dec = ei.getDecryptor(); - boolean passOk = dec.verifyPassword("tika"); - assertTrue(passOk); - - // extract encrypted ooxml file and write to custom encrypted zip file - InputStream is = dec.getDataStream(poifs); - - // provide ZipEntrySource to poi which decrypts on the fly - ZipEntrySource source = AesZipFileZipEntrySource.createZipEntrySource(is); - - // test the source - OPCPackage opc = OPCPackage.open(source); - String expected = "You can't see me"; - - XSSFBEventBasedExcelExtractor extractor = new XSSFBEventBasedExcelExtractor(opc); - extractor.setIncludeSheetNames(false); - String txt = extractor.getText(); - assertEquals(expected, txt.trim()); - - extractor.close(); - opc.close(); - poifs.close(); - fis.close(); - } - -} diff --git a/src/ooxml/testcases/org/apache/poi/poifs/crypt/TestSignatureInfo.java b/src/ooxml/testcases/org/apache/poi/poifs/crypt/TestSignatureInfo.java deleted file mode 100644 index 3c172f385..000000000 --- a/src/ooxml/testcases/org/apache/poi/poifs/crypt/TestSignatureInfo.java +++ /dev/null @@ -1,724 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -/* ==================================================================== - This product contains an ASLv2 licensed version of the OOXML signer - package from the eID Applet project - http://code.google.com/p/eid-applet/source/browse/trunk/README.txt - Copyright (C) 2008-2014 FedICT. - ================================================================= */ -package org.apache.poi.poifs.crypt; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.ConnectException; -import java.net.HttpURLConnection; -import java.net.MalformedURLException; -import java.net.SocketTimeoutException; -import java.net.URL; -import java.security.Key; -import java.security.KeyPair; -import java.security.KeyStore; -import java.security.PrivateKey; -import java.security.cert.Certificate; -import java.security.cert.X509CRL; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Collections; -import java.util.Date; -import java.util.Iterator; -import java.util.List; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.POITestCase; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackageAccess; -import org.apache.poi.openxml4j.opc.PackageRelationshipTypes; -import org.apache.poi.poifs.crypt.dsig.DigestInfo; -import org.apache.poi.poifs.crypt.dsig.SignatureConfig; -import org.apache.poi.poifs.crypt.dsig.SignatureInfo; -import org.apache.poi.poifs.crypt.dsig.SignatureInfo.SignaturePart; -import org.apache.poi.poifs.crypt.dsig.facets.EnvelopedSignatureFacet; -import org.apache.poi.poifs.crypt.dsig.facets.KeyInfoSignatureFacet; -import org.apache.poi.poifs.crypt.dsig.facets.XAdESSignatureFacet; -import org.apache.poi.poifs.crypt.dsig.facets.XAdESXLSignatureFacet; -import org.apache.poi.poifs.crypt.dsig.services.RevocationData; -import org.apache.poi.poifs.crypt.dsig.services.RevocationDataService; -import org.apache.poi.poifs.crypt.dsig.services.TimeStampService; -import org.apache.poi.poifs.crypt.dsig.services.TimeStampServiceValidator; -import org.apache.poi.ss.usermodel.WorkbookFactory; -import org.apache.poi.util.DocumentHelper; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.LocaleUtil; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.xssf.streaming.SXSSFWorkbook; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.apache.xmlbeans.XmlObject; -import org.bouncycastle.asn1.x509.KeyUsage; -import org.bouncycastle.cert.ocsp.OCSPResp; -import org.etsi.uri.x01903.v13.DigestAlgAndValueType; -import org.etsi.uri.x01903.v13.QualifyingPropertiesType; -import org.junit.Assume; -import org.junit.BeforeClass; -import org.junit.Test; -import org.w3.x2000.x09.xmldsig.ReferenceType; -import org.w3.x2000.x09.xmldsig.SignatureDocument; -import org.w3c.dom.Document; - -public class TestSignatureInfo { - private static final POILogger LOG = POILogFactory.getLogger(TestSignatureInfo.class); - private static final POIDataSamples testdata = POIDataSamples.getXmlDSignInstance(); - - private static Calendar cal; - private KeyPair keyPair = null; - private X509Certificate x509 = null; - - @BeforeClass - public static void initBouncy() throws IOException { - CryptoFunctions.registerBouncyCastle(); - - // Set cal to now ... only set to fixed date for debugging ... - cal = LocaleUtil.getLocaleCalendar(LocaleUtil.TIMEZONE_UTC); - assertNotNull(cal); -// cal.set(2014, 7, 6, 21, 42, 12); -// cal.clear(Calendar.MILLISECOND); - - // don't run this test when we are using older Xerces as it triggers an XML Parser backwards compatibility issue - // in the xmlsec jar file - String additionalJar = System.getProperty("additionaljar"); - //System.out.println("Having: " + additionalJar); - Assume.assumeTrue("Not running TestSignatureInfo because we are testing with additionaljar set to " + additionalJar, - additionalJar == null || additionalJar.trim().length() == 0); - } - - @Test - public void office2007prettyPrintedRels() throws Exception { - OPCPackage pkg = OPCPackage.open(testdata.getFile("office2007prettyPrintedRels.docx"), PackageAccess.READ); - try { - SignatureConfig sic = new SignatureConfig(); - sic.setOpcPackage(pkg); - SignatureInfo si = new SignatureInfo(); - si.setSignatureConfig(sic); - boolean isValid = si.verifySignature(); - assertTrue(isValid); - } finally { - pkg.close(); - } - } - - @Test - public void getSignerUnsigned() throws Exception { - String testFiles[] = { - "hello-world-unsigned.docx", - "hello-world-unsigned.pptx", - "hello-world-unsigned.xlsx", - "hello-world-office-2010-technical-preview-unsigned.docx" - }; - - for (String testFile : testFiles) { - OPCPackage pkg = OPCPackage.open(testdata.getFile(testFile), PackageAccess.READ); - SignatureConfig sic = new SignatureConfig(); - sic.setOpcPackage(pkg); - SignatureInfo si = new SignatureInfo(); - si.setSignatureConfig(sic); - List result = new ArrayList(); - for (SignaturePart sp : si.getSignatureParts()) { - if (sp.validate()) { - result.add(sp.getSigner()); - } - } - pkg.revert(); - pkg.close(); - assertNotNull(result); - assertTrue(result.isEmpty()); - } - } - - @Test - public void getSigner() throws Exception { - String testFiles[] = { - "hyperlink-example-signed.docx", - "hello-world-signed.docx", - "hello-world-signed.pptx", - "hello-world-signed.xlsx", - "hello-world-office-2010-technical-preview.docx", - "ms-office-2010-signed.docx", - "ms-office-2010-signed.pptx", - "ms-office-2010-signed.xlsx", - "Office2010-SP1-XAdES-X-L.docx", - "signed.docx", - }; - - for (String testFile : testFiles) { - OPCPackage pkg = OPCPackage.open(testdata.getFile(testFile), PackageAccess.READ); - try { - SignatureConfig sic = new SignatureConfig(); - sic.setOpcPackage(pkg); - SignatureInfo si = new SignatureInfo(); - si.setSignatureConfig(sic); - List result = new ArrayList(); - for (SignaturePart sp : si.getSignatureParts()) { - if (sp.validate()) { - result.add(sp.getSigner()); - } - } - - assertNotNull(result); - assertEquals("test-file: "+testFile, 1, result.size()); - X509Certificate signer = result.get(0); - LOG.log(POILogger.DEBUG, "signer: " + signer.getSubjectX500Principal()); - - boolean b = si.verifySignature(); - assertTrue("test-file: "+testFile, b); - pkg.revert(); - } finally { - pkg.close(); - } - } - } - - @Test - public void getMultiSigners() throws Exception { - String testFile = "hello-world-signed-twice.docx"; - OPCPackage pkg = OPCPackage.open(testdata.getFile(testFile), PackageAccess.READ); - try { - SignatureConfig sic = new SignatureConfig(); - sic.setOpcPackage(pkg); - SignatureInfo si = new SignatureInfo(); - si.setSignatureConfig(sic); - List result = new ArrayList(); - for (SignaturePart sp : si.getSignatureParts()) { - if (sp.validate()) { - result.add(sp.getSigner()); - } - } - - assertNotNull(result); - assertEquals("test-file: "+testFile, 2, result.size()); - X509Certificate signer1 = result.get(0); - X509Certificate signer2 = result.get(1); - LOG.log(POILogger.DEBUG, "signer 1: " + signer1.getSubjectX500Principal()); - LOG.log(POILogger.DEBUG, "signer 2: " + signer2.getSubjectX500Principal()); - - boolean b = si.verifySignature(); - assertTrue("test-file: "+testFile, b); - pkg.revert(); - } finally { - pkg.close(); - } - } - - @Test - public void testSignSpreadsheet() throws Exception { - String testFile = "hello-world-unsigned.xlsx"; - OPCPackage pkg = OPCPackage.open(copy(testdata.getFile(testFile)), PackageAccess.READ_WRITE); - sign(pkg, "Test", "CN=Test", 1); - pkg.close(); - } - - @Test - public void testManipulation() throws Exception { - // sign & validate - String testFile = "hello-world-unsigned.xlsx"; - @SuppressWarnings("resource") - OPCPackage pkg = OPCPackage.open(copy(testdata.getFile(testFile)), PackageAccess.READ_WRITE); - sign(pkg, "Test", "CN=Test", 1); - - // manipulate - XSSFWorkbook wb = new XSSFWorkbook(pkg); - wb.setSheetName(0, "manipulated"); - // ... I don't know, why commit is protected ... - POITestCase.callMethod(XSSFWorkbook.class, wb, Void.class, "commit", new Class[0], new Object[0]); - - // todo: test a manipulation on a package part, which is not signed - // ... maybe in combination with #56164 - - // validate - SignatureConfig sic = new SignatureConfig(); - sic.setOpcPackage(pkg); - SignatureInfo si = new SignatureInfo(); - si.setSignatureConfig(sic); - boolean b = si.verifySignature(); - assertFalse("signature should be broken", b); - - wb.close(); - } - - @Test - public void testSignSpreadsheetWithSignatureInfo() throws Exception { - initKeyPair("Test", "CN=Test"); - String testFile = "hello-world-unsigned.xlsx"; - OPCPackage pkg = OPCPackage.open(copy(testdata.getFile(testFile)), PackageAccess.READ_WRITE); - SignatureConfig sic = new SignatureConfig(); - sic.setOpcPackage(pkg); - sic.setKey(keyPair.getPrivate()); - sic.setSigningCertificateChain(Collections.singletonList(x509)); - SignatureInfo si = new SignatureInfo(); - si.setSignatureConfig(sic); - // hash > sha1 doesn't work in excel viewer ... - si.confirmSignature(); - List result = new ArrayList(); - for (SignaturePart sp : si.getSignatureParts()) { - if (sp.validate()) { - result.add(sp.getSigner()); - } - } - assertEquals(1, result.size()); - pkg.close(); - } - - @Test - public void testSignEnvelopingDocument() throws Exception { - String testFile = "hello-world-unsigned.xlsx"; - OPCPackage pkg = OPCPackage.open(copy(testdata.getFile(testFile)), PackageAccess.READ_WRITE); - - initKeyPair("Test", "CN=Test"); - final X509CRL crl = PkiTestUtils.generateCrl(x509, keyPair.getPrivate()); - - // setup - SignatureConfig signatureConfig = new SignatureConfig(); - signatureConfig.setOpcPackage(pkg); - signatureConfig.setKey(keyPair.getPrivate()); - - /* - * We need at least 2 certificates for the XAdES-C complete certificate - * refs construction. - */ - List certificateChain = new ArrayList(); - certificateChain.add(x509); - certificateChain.add(x509); - signatureConfig.setSigningCertificateChain(certificateChain); - - signatureConfig.addSignatureFacet(new EnvelopedSignatureFacet()); - signatureConfig.addSignatureFacet(new KeyInfoSignatureFacet()); - signatureConfig.addSignatureFacet(new XAdESSignatureFacet()); - signatureConfig.addSignatureFacet(new XAdESXLSignatureFacet()); - - // check for internet, no error means it works - boolean mockTsp = (getAccessError("http://timestamp.comodoca.com/rfc3161", true, 10000) != null); - - // http://timestamping.edelweb.fr/service/tsp - // http://tsa.belgium.be/connect - // http://timestamp.comodoca.com/authenticode - // http://timestamp.comodoca.com/rfc3161 - // http://services.globaltrustfinder.com/adss/tsa - signatureConfig.setTspUrl("http://timestamp.comodoca.com/rfc3161"); - signatureConfig.setTspRequestPolicy(null); // comodoca request fails, if default policy is set ... - signatureConfig.setTspOldProtocol(false); - - //set proxy info if any - String proxy = System.getProperty("http_proxy"); - if (proxy != null && proxy.trim().length() > 0) { - signatureConfig.setProxyUrl(proxy); - } - - if (mockTsp) { - TimeStampService tspService = new TimeStampService(){ - @Override - public byte[] timeStamp(byte[] data, RevocationData revocationData) throws Exception { - revocationData.addCRL(crl); - return "time-stamp-token".getBytes(LocaleUtil.CHARSET_1252); - } - @Override - public void setSignatureConfig(SignatureConfig config) { - // empty on purpose - } - }; - signatureConfig.setTspService(tspService); - } else { - TimeStampServiceValidator tspValidator = new TimeStampServiceValidator() { - @Override - public void validate(List validateChain, - RevocationData revocationData) throws Exception { - for (X509Certificate certificate : validateChain) { - LOG.log(POILogger.DEBUG, "certificate: " + certificate.getSubjectX500Principal()); - LOG.log(POILogger.DEBUG, "validity: " + certificate.getNotBefore() + " - " + certificate.getNotAfter()); - } - } - }; - signatureConfig.setTspValidator(tspValidator); - signatureConfig.setTspOldProtocol(signatureConfig.getTspUrl().contains("edelweb")); - } - - final RevocationData revocationData = new RevocationData(); - revocationData.addCRL(crl); - OCSPResp ocspResp = PkiTestUtils.createOcspResp(x509, false, - x509, x509, keyPair.getPrivate(), "SHA1withRSA", cal.getTimeInMillis()); - revocationData.addOCSP(ocspResp.getEncoded()); - - RevocationDataService revocationDataService = new RevocationDataService(){ - @Override - public RevocationData getRevocationData(List revocationChain) { - return revocationData; - } - }; - signatureConfig.setRevocationDataService(revocationDataService); - - // operate - SignatureInfo si = new SignatureInfo(); - si.setSignatureConfig(signatureConfig); - try { - si.confirmSignature(); - } catch (RuntimeException e) { - pkg.close(); - // only allow a ConnectException because of timeout, we see this in Jenkins from time to time... - if(e.getCause() == null) { - throw e; - } - if((e.getCause() instanceof ConnectException) || (e.getCause() instanceof SocketTimeoutException)) { - Assume.assumeFalse("Only allowing ConnectException with 'timed out' as message here, but had: " + e, - e.getCause().getMessage().contains("timed out")); - } else if (e.getCause() instanceof IOException) { - Assume.assumeFalse("Only allowing IOException with 'Error contacting TSP server' as message here, but had: " + e, - e.getCause().getMessage().contains("Error contacting TSP server")); - } else if (e.getCause() instanceof RuntimeException) { - Assume.assumeFalse("Only allowing RuntimeException with 'This site is cur' as message here, but had: " + e, - e.getCause().getMessage().contains("This site is cur")); - } - throw e; - } - - // verify - Iterator spIter = si.getSignatureParts().iterator(); - assertTrue("Had: " + si.getSignatureConfig().getOpcPackage(). - getRelationshipsByType(PackageRelationshipTypes.DIGITAL_SIGNATURE_ORIGIN), - spIter.hasNext()); - SignaturePart sp = spIter.next(); - boolean valid = sp.validate(); - assertTrue(valid); - - SignatureDocument sigDoc = sp.getSignatureDocument(); - String declareNS = - "declare namespace xades='http://uri.etsi.org/01903/v1.3.2#'; " - + "declare namespace ds='http://www.w3.org/2000/09/xmldsig#'; "; - - String digestValXQuery = declareNS + - "$this/ds:Signature/ds:SignedInfo/ds:Reference"; - for (ReferenceType rt : (ReferenceType[])sigDoc.selectPath(digestValXQuery)) { - assertNotNull(rt.getDigestValue()); - assertEquals(signatureConfig.getDigestMethodUri(), rt.getDigestMethod().getAlgorithm()); - } - - String certDigestXQuery = declareNS + - "$this//xades:SigningCertificate/xades:Cert/xades:CertDigest"; - XmlObject xoList[] = sigDoc.selectPath(certDigestXQuery); - assertEquals(xoList.length, 1); - DigestAlgAndValueType certDigest = (DigestAlgAndValueType)xoList[0]; - assertNotNull(certDigest.getDigestValue()); - - String qualPropXQuery = declareNS + - "$this/ds:Signature/ds:Object/xades:QualifyingProperties"; - xoList = sigDoc.selectPath(qualPropXQuery); - assertEquals(xoList.length, 1); - QualifyingPropertiesType qualProp = (QualifyingPropertiesType)xoList[0]; - boolean qualPropXsdOk = qualProp.validate(); - assertTrue(qualPropXsdOk); - - pkg.close(); - } - - public static String getAccessError(String destinationUrl, boolean fireRequest, int timeout) { - URL url; - try { - url = new URL(destinationUrl); - } catch (MalformedURLException e) { - throw new IllegalArgumentException("Invalid destination URL", e); - } - - HttpURLConnection conn = null; - try { - conn = (HttpURLConnection) url.openConnection(); - - // set specified timeout if non-zero - if(timeout != 0) { - conn.setConnectTimeout(timeout); - conn.setReadTimeout(timeout); - } - - conn.setDoOutput(false); - conn.setDoInput(true); - - /* if connecting is not possible this will throw a connection refused exception */ - conn.connect(); - - if (fireRequest) { - InputStream is = null; - try { - is = conn.getInputStream(); - } finally { - IOUtils.closeQuietly(is); - } - - } - /* if connecting is possible we return true here */ - return null; - - } catch (IOException e) { - /* exception is thrown -> server not available */ - return e.getClass().getName() + ": " + e.getMessage(); - } finally { - if (conn != null) { - conn.disconnect(); - } - } - } - - @Test - public void testCertChain() throws Exception { - KeyStore keystore = KeyStore.getInstance("PKCS12"); - String password = "test"; - InputStream is = testdata.openResourceAsStream("chaintest.pfx"); - keystore.load(is, password.toCharArray()); - is.close(); - - Key key = keystore.getKey("poitest", password.toCharArray()); - Certificate chainList[] = keystore.getCertificateChain("poitest"); - List certChain = new ArrayList(); - for (Certificate c : chainList) { - certChain.add((X509Certificate)c); - } - x509 = certChain.get(0); - keyPair = new KeyPair(x509.getPublicKey(), (PrivateKey)key); - - String testFile = "hello-world-unsigned.xlsx"; - OPCPackage pkg = OPCPackage.open(copy(testdata.getFile(testFile)), PackageAccess.READ_WRITE); - - SignatureConfig signatureConfig = new SignatureConfig(); - signatureConfig.setKey(keyPair.getPrivate()); - signatureConfig.setSigningCertificateChain(certChain); - Calendar oldCal = LocaleUtil.getLocaleCalendar(2007, 7, 1); - signatureConfig.setExecutionTime(oldCal.getTime()); - signatureConfig.setDigestAlgo(HashAlgorithm.sha1); - signatureConfig.setOpcPackage(pkg); - - SignatureInfo si = new SignatureInfo(); - si.setSignatureConfig(signatureConfig); - - si.confirmSignature(); - - for (SignaturePart sp : si.getSignatureParts()){ - assertTrue("Could not validate", sp.validate()); - X509Certificate signer = sp.getSigner(); - assertNotNull("signer undefined?!", signer); - List certChainRes = sp.getCertChain(); - assertEquals(3, certChainRes.size()); - } - - pkg.close(); - } - - @Test - public void testNonSha1() throws Exception { - String testFile = "hello-world-unsigned.xlsx"; - initKeyPair("Test", "CN=Test"); - - SignatureConfig signatureConfig = new SignatureConfig(); - signatureConfig.setKey(keyPair.getPrivate()); - signatureConfig.setSigningCertificateChain(Collections.singletonList(x509)); - - HashAlgorithm testAlgo[] = { HashAlgorithm.sha224, HashAlgorithm.sha256 - , HashAlgorithm.sha384, HashAlgorithm.sha512, HashAlgorithm.ripemd160 }; - - for (HashAlgorithm ha : testAlgo) { - OPCPackage pkg = null; - try { - signatureConfig.setDigestAlgo(ha); - pkg = OPCPackage.open(copy(testdata.getFile(testFile)), PackageAccess.READ_WRITE); - signatureConfig.setOpcPackage(pkg); - - SignatureInfo si = new SignatureInfo(); - si.setSignatureConfig(signatureConfig); - - si.confirmSignature(); - boolean b = si.verifySignature(); - assertTrue("Signature not correctly calculated for " + ha, b); - } finally { - if (pkg != null) { - pkg.close(); - } - } - } - } - - @Test - public void bug58630() throws Exception { - // test deletion of sheet 0 and signing - File tpl = copy(testdata.getFile("bug58630.xlsx")); - SXSSFWorkbook wb1 = new SXSSFWorkbook((XSSFWorkbook)WorkbookFactory.create(tpl), 10); - wb1.setCompressTempFiles(true); - wb1.removeSheetAt(0); - ByteArrayOutputStream os = new ByteArrayOutputStream(); - wb1.write(os); - wb1.close(); - OPCPackage pkg = OPCPackage.open(new ByteArrayInputStream(os.toByteArray())); - - initKeyPair("Test", "CN=Test"); - SignatureConfig signatureConfig = new SignatureConfig(); - signatureConfig.setKey(keyPair.getPrivate()); - signatureConfig.setSigningCertificateChain(Collections.singletonList(x509)); - signatureConfig.setOpcPackage(pkg); - - SignatureInfo si = new SignatureInfo(); - si.setSignatureConfig(signatureConfig); - si.confirmSignature(); - assertTrue("invalid signature", si.verifySignature()); - - pkg.close(); - } - - @Test - public void testMultiSign() throws Exception { - initKeyPair("KeyA", "CN=KeyA"); - //KeyPair keyPairA = keyPair; - //X509Certificate x509A = x509; - initKeyPair("KeyB", "CN=KeyB"); - //KeyPair keyPairB = keyPair; - //X509Certificate x509B = x509; - - File tpl = copy(testdata.getFile("bug58630.xlsx")); - OPCPackage pkg = OPCPackage.open(tpl); - try { - //SignatureConfig signatureConfig = new SignatureConfig(); - assertNotNull(pkg); - } finally { - pkg.close(); - } - } - - private void sign(OPCPackage pkgCopy, String alias, String signerDn, int signerCount) throws Exception { - initKeyPair(alias, signerDn); - - SignatureConfig signatureConfig = new SignatureConfig(); - signatureConfig.setKey(keyPair.getPrivate()); - signatureConfig.setSigningCertificateChain(Collections.singletonList(x509)); - signatureConfig.setExecutionTime(cal.getTime()); - signatureConfig.setDigestAlgo(HashAlgorithm.sha1); - signatureConfig.setOpcPackage(pkgCopy); - - SignatureInfo si = new SignatureInfo(); - si.setSignatureConfig(signatureConfig); - - Document document = DocumentHelper.createDocument(); - - // operate - DigestInfo digestInfo = si.preSign(document, null); - - // verify - assertNotNull(digestInfo); - LOG.log(POILogger.DEBUG, "digest algo: " + digestInfo.hashAlgo); - LOG.log(POILogger.DEBUG, "digest description: " + digestInfo.description); - assertEquals("Office OpenXML Document", digestInfo.description); - assertNotNull(digestInfo.hashAlgo); - assertNotNull(digestInfo.digestValue); - - // setup: key material, signature value - byte[] signatureValue = si.signDigest(digestInfo.digestValue); - - // operate: postSign - si.postSign(document, signatureValue); - - // verify: signature - si.getSignatureConfig().setOpcPackage(pkgCopy); - List result = new ArrayList(); - for (SignaturePart sp : si.getSignatureParts()) { - if (sp.validate()) { - result.add(sp.getSigner()); - } - } - assertEquals(signerCount, result.size()); - } - - private void initKeyPair(String alias, String subjectDN) throws Exception { - final char password[] = "test".toCharArray(); - File file = new File("build/test.pfx"); - - KeyStore keystore = KeyStore.getInstance("PKCS12"); - - if (file.exists()) { - FileInputStream fis = new FileInputStream(file); - keystore.load(fis, password); - fis.close(); - } else { - keystore.load(null, password); - } - - if (keystore.isKeyEntry(alias)) { - Key key = keystore.getKey(alias, password); - x509 = (X509Certificate)keystore.getCertificate(alias); - keyPair = new KeyPair(x509.getPublicKey(), (PrivateKey)key); - } else { - keyPair = PkiTestUtils.generateKeyPair(); - Date notBefore = cal.getTime(); - Calendar cal2 = (Calendar)cal.clone(); - cal2.add(Calendar.YEAR, 1); - Date notAfter = cal2.getTime(); - KeyUsage keyUsage = new KeyUsage(KeyUsage.digitalSignature); - - x509 = PkiTestUtils.generateCertificate(keyPair.getPublic(), subjectDN - , notBefore, notAfter, null, keyPair.getPrivate(), true, 0, null, null, keyUsage); - - keystore.setKeyEntry(alias, keyPair.getPrivate(), password, new Certificate[]{x509}); - FileOutputStream fos = new FileOutputStream(file); - keystore.store(fos, password); - fos.close(); - } - } - - private static File copy(File input) throws IOException { - String extension = input.getName().replaceAll(".*?(\\.[^.]+)?$", "$1"); - if (extension == null || "".equals(extension)) { - extension = ".zip"; - } - - // ensure that we create the "build" directory as it might not be existing - // in the Sonar Maven runs where we are at a different source directory - File buildDir = new File("build"); - if(!buildDir.exists()) { - assertTrue("Failed to create " + buildDir.getAbsolutePath(), - buildDir.mkdirs()); - } - File tmpFile = new File(buildDir, "sigtest"+extension); - - OutputStream fos = new FileOutputStream(tmpFile); - try { - InputStream fis = new FileInputStream(input); - try { - IOUtils.copy(fis, fos); - } finally { - fis.close(); - } - } finally { - fos.close(); - } - - return tmpFile; - } - -} diff --git a/src/ooxml/testcases/org/apache/poi/sl/TestHeadersFooters.java b/src/ooxml/testcases/org/apache/poi/sl/TestHeadersFooters.java deleted file mode 100644 index c51652ff5..000000000 --- a/src/ooxml/testcases/org/apache/poi/sl/TestHeadersFooters.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.sl; - -import static org.apache.poi.sl.TestTable.openSampleSlideshow; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assume.assumeFalse; - -import java.io.IOException; -import java.util.List; - -import org.apache.poi.hslf.model.HeadersFooters; -import org.apache.poi.hslf.usermodel.HSLFSlide; -import org.apache.poi.hslf.usermodel.HSLFTextParagraph; -import org.apache.poi.sl.usermodel.Shape; -import org.apache.poi.sl.usermodel.Slide; -import org.apache.poi.sl.usermodel.SlideShow; -import org.apache.poi.sl.usermodel.TextParagraph; -import org.apache.poi.sl.usermodel.TextShape; -import org.junit.BeforeClass; -import org.junit.Test; - -public class TestHeadersFooters { - private static boolean xslfOnly = false; - - @BeforeClass - public static void checkHslf() { - try { - Class.forName("org.apache.poi.hslf.usermodel.HSLFSlideShow"); - } catch (Exception e) { - xslfOnly = true; - } - } - - - @Test - public void bug58144a() throws IOException { - assumeFalse(xslfOnly); - SlideShow ppt = openSampleSlideshow("bug58144-headers-footers-2003.ppt"); - HSLFSlide sl = (HSLFSlide)ppt.getSlides().get(0); - HeadersFooters hfs = sl.getHeadersFooters(); - assertNull(hfs.getHeaderText()); - assertEquals("Confidential", hfs.getFooterText()); - List> llp = sl.getTextParagraphs(); - assertEquals("Test", HSLFTextParagraph.getText(llp.get(0))); - assertFalse(llp.get(0).get(0).isHeaderOrFooter()); - ppt.close(); - } - - @Test - public void bug58144b() throws IOException { - assumeFalse(xslfOnly); - SlideShow ppt = openSampleSlideshow("bug58144-headers-footers-2007.ppt"); - Slide sl = ppt.getSlides().get(0); - HeadersFooters hfs2 = ((HSLFSlide)sl).getHeadersFooters(); - assertNull(hfs2.getHeaderText()); - assertEquals("Slide footer", hfs2.getFooterText()); - - testSlideShow(ppt); - ppt.close(); - } - - @Test - public void bug58144c() throws IOException { - SlideShow ppt = openSampleSlideshow("bug58144-headers-footers-2007.pptx"); - testSlideShow(ppt); - ppt.close(); - } - - private void testSlideShow(SlideShow ppt) { - Slide sl = ppt.getSlides().get(0); - - List> shapes = sl.getShapes(); - TextShape ts0 = (TextShape)shapes.get(0); - assertEquals("Test file", ts0.getText()); - TextShape ts1 = (TextShape)shapes.get(1); - assertEquals("Has some text in the headers and footers", ts1.getText()); - TextShape ts2 = (TextShape)shapes.get(2); - assertEquals("Slide footer", ts2.getText()); - List> ltp = ts2.getTextParagraphs(); - assertTrue(ltp.get(0).isHeaderOrFooter()); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/sl/TestTable.java b/src/ooxml/testcases/org/apache/poi/sl/TestTable.java deleted file mode 100644 index 0b02b7478..000000000 --- a/src/ooxml/testcases/org/apache/poi/sl/TestTable.java +++ /dev/null @@ -1,163 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.sl; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assume.assumeFalse; - -import java.awt.geom.Rectangle2D; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hslf.usermodel.HSLFSlideShow; -import org.apache.poi.sl.usermodel.SlideShow; -import org.apache.poi.sl.usermodel.SlideShowFactory; -import org.apache.poi.sl.usermodel.TableCell; -import org.apache.poi.sl.usermodel.TableShape; -import org.apache.poi.sl.usermodel.TextShape.TextDirection; -import org.apache.poi.xslf.usermodel.XMLSlideShow; -import org.junit.BeforeClass; -import org.junit.Test; - -public class TestTable { - private static POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); - private static boolean xslfOnly = false; - - @BeforeClass - public static void checkHslf() { - try { - Class.forName("org.apache.poi.hslf.usermodel.HSLFSlideShow"); - } catch (Exception e) { - xslfOnly = true; - } - } - - - /** a generic way to open a sample slideshow document **/ - public static SlideShow openSampleSlideshow(String sampleName) throws IOException { - InputStream is = _slTests.openResourceAsStream(sampleName); - try { - return SlideShowFactory.create(is); - } catch (Exception e) { - throw new RuntimeException(e); - } finally { - is.close(); - } - } - - @Test - public void testColWidthRowHeight() throws IOException { - assumeFalse(xslfOnly); - - // Test of table dimensions of same slideshow saved as ppt/x - // to check if both return similar (points) value - SlideShow ppt = openSampleSlideshow("table_test.ppt"); - TableShape ts = (TableShape)ppt.getSlides().get(0).getShapes().get(0); - - SlideShow pptx = openSampleSlideshow("table_test.pptx"); - TableShape tsx = (TableShape)pptx.getSlides().get(0).getShapes().get(0); - - // assume table shape should be equal to itself - confirmTableShapeEqual(ts, ts); - confirmTableShapeEqual(tsx, tsx); - - // assert ppt and pptx versions of the same table have the same shape - confirmTableShapeEqual(ts, tsx); - - pptx.close(); - ppt.close(); - } - - private void confirmTableShapeEqual(TableShape tableA, TableShape tableB) { - int cols = tableA.getNumberOfColumns(); - int rows = tableA.getNumberOfRows(); - - int colsx = tableB.getNumberOfColumns(); - int rowsx = tableB.getNumberOfRows(); - - assertEquals("tables should have same number of columns", cols, colsx); - assertEquals("tables should have same number of rows", rows, rowsx); - - for (int i=0; i ppt1 = new HSLFSlideShow(); - testTextDirection(ppt1); - ppt1.close(); - } - - @Test - public void testTextDirectionXSLF() throws IOException { - SlideShow ppt1 = new XMLSlideShow(); - testTextDirection(ppt1); - ppt1.close(); - } - - private void testTextDirection(SlideShow ppt1) throws IOException { - - TextDirection tds[] = { - TextDirection.HORIZONTAL, - TextDirection.VERTICAL, - TextDirection.VERTICAL_270, - // TextDirection.STACKED is not supported on HSLF - }; - - TableShape tbl1 = ppt1.createSlide().createTable(1, 3); - tbl1.setAnchor(new Rectangle2D.Double(50, 50, 200, 200)); - - int col = 0; - for (TextDirection td : tds) { - TableCell c = tbl1.getCell(0, col++); - if (c != null) { - c.setTextDirection(td); - c.setText("bla"); - } - } - - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - ppt1.write(bos); - ppt1.close(); - - InputStream is = new ByteArrayInputStream(bos.toByteArray()); - SlideShow ppt2 = SlideShowFactory.create(is); - TableShape tbl2 = (TableShape)ppt2.getSlides().get(0).getShapes().get(0); - - col = 0; - for (TextDirection td : tds) { - TableCell c = tbl2.getCell(0, col++); - assertEquals(td, c.getTextDirection()); - } - ppt2.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/sl/draw/TestDrawPictureShape.java b/src/ooxml/testcases/org/apache/poi/sl/draw/TestDrawPictureShape.java deleted file mode 100644 index 809a307d5..000000000 --- a/src/ooxml/testcases/org/apache/poi/sl/draw/TestDrawPictureShape.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -package org.apache.poi.sl.draw; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assume.assumeFalse; - -import java.awt.Dimension; -import java.awt.geom.Rectangle2D; -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.sl.usermodel.PictureData; -import org.apache.poi.sl.usermodel.PictureShape; -import org.apache.poi.sl.usermodel.RectAlign; -import org.apache.poi.sl.usermodel.Shape; -import org.apache.poi.sl.usermodel.Slide; -import org.apache.poi.sl.usermodel.SlideShow; -import org.apache.poi.sl.usermodel.SlideShowFactory; -import org.apache.poi.util.Units; -import org.junit.BeforeClass; -import org.junit.Test; - -public class TestDrawPictureShape { - final static POIDataSamples ssSamples = POIDataSamples.getSlideShowInstance(); - - private static boolean xslfOnly = false; - - @BeforeClass - public static void checkHslf() { - try { - Class.forName("org.apache.poi.hslf.usermodel.HSLFSlideShow"); - } catch (Exception e) { - xslfOnly = true; - } - } - - /** a generic way to open a sample slideshow document **/ - public static SlideShow openSampleDocument(String sampleName) throws IOException { - InputStream is = ssSamples.openResourceAsStream(sampleName); - try { - return SlideShowFactory.create(is); - } catch (Exception e) { - throw new RuntimeException(e); - } finally { - is.close(); - } - } - - @Test - public void testResizeHSLF() throws IOException { - assumeFalse(xslfOnly); - testResize("pictures.ppt"); - } - - @Test - public void testResizeXSLF() throws IOException { - testResize("shapes.pptx"); - } - - - public void testResize(String file) throws IOException { - SlideShow ss = openSampleDocument(file); - - Slide slide = ss.getSlides().get(0); - PictureShape picShape = null; - for (Shape shape : slide.getShapes()) { - if (shape instanceof PictureShape) { - picShape = (PictureShape)shape; - break; - } - } - assertNotNull(picShape); - PictureData pd = picShape.getPictureData(); - Dimension dimPd = pd.getImageDimension(); - new DrawPictureShape(picShape).resize(); - Dimension dimShape = new Dimension( - (int)picShape.getAnchor().getWidth(), - (int)picShape.getAnchor().getHeight() - ); - assertEquals(dimPd, dimShape); - - double newWidth = (dimPd.getWidth()*(100d/dimPd.getHeight())); - // ... -1 is a rounding error - Rectangle2D expRect = new Rectangle2D.Double(rbf(50+300-newWidth, picShape), 50, rbf(newWidth, picShape), 100); - Rectangle2D target = new Rectangle2D.Double(50,50,300,100); - new DrawPictureShape(picShape).resize(target, RectAlign.BOTTOM_RIGHT); - Rectangle2D actRect = picShape.getAnchor(); - assertEquals(expRect.getX(), actRect.getX(), .0001); - assertEquals(expRect.getY(), actRect.getY(), .0001); - assertEquals(expRect.getWidth(), actRect.getWidth(), .0001); - assertEquals(expRect.getHeight(), actRect.getHeight(), .0001); - ss.close(); - } - - // round back and forth - points -> master -> points - static double rbf(double val, PictureShape picShape) { - if (picShape.getClass().getName().contains("HSLF")) { - return Units.masterToPoints(Units.pointsToMaster(val)); - } else { - return val; - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/ss/TestWorkbookFactory.java b/src/ooxml/testcases/org/apache/poi/ss/TestWorkbookFactory.java deleted file mode 100644 index 4b77e96be..000000000 --- a/src/ooxml/testcases/org/apache/poi/ss/TestWorkbookFactory.java +++ /dev/null @@ -1,385 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss; - -import static org.junit.Assert.*; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.FileNotFoundException; - -import org.apache.poi.EmptyFileException; -import org.apache.poi.EncryptedDocumentException; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.usermodel.WorkbookFactory; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.util.TempFile; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackageAccess; -import org.junit.Test; - -public final class TestWorkbookFactory { - private static final String xls = "SampleSS.xls"; - private static final String xlsx = "SampleSS.xlsx"; - private static final String[] xls_prot = new String[] {"password.xls", "password"}; - private static final String[] xlsx_prot = new String[]{"protected_passtika.xlsx", "tika"}; - private static final String txt = "SampleSS.txt"; - - private static final POILogger LOGGER = POILogFactory.getLogger(TestWorkbookFactory.class); - - /** - * Closes the sample workbook read in from filename. - * Throws an exception if closing the workbook results in the file on disk getting modified. - * - * @param filename the sample workbook to read in - * @param wb the workbook to close - * @throws IOException - */ - private static void assertCloseDoesNotModifyFile(String filename, Workbook wb) throws IOException { - final byte[] before = HSSFTestDataSamples.getTestDataFileContent(filename); - // FIXME: replace with wb.close() when bug 58779 is resolved - closeOrRevert(wb); - final byte[] after = HSSFTestDataSamples.getTestDataFileContent(filename); - assertArrayEquals(filename + " sample file was modified as a result of closing the workbook", - before, after); - } - - /** - * bug 58779: Closing an XSSFWorkbook that was created with WorkbookFactory modifies the file - * FIXME: replace this method with wb.close() when bug 58779 is resolved. - * - * @param wb the workbook to close or revert - */ - private static void closeOrRevert(Workbook wb) throws IOException { - if (wb instanceof HSSFWorkbook) { - wb.close(); - } - else if (wb instanceof XSSFWorkbook) { - final XSSFWorkbook xwb = (XSSFWorkbook) wb; - if (PackageAccess.READ == xwb.getPackage().getPackageAccess()) { - xwb.close(); - } - else { - // TODO: close() re-writes the sample-file?! Resort to revert() for now to close file handle... - LOGGER.log(POILogger.WARN, - "reverting XSSFWorkbook rather than closing it to avoid close() modifying the file on disk. " + - "Refer to bug 58779."); - xwb.getPackage().revert(); - } - } else { - throw new RuntimeException("Unsupported workbook type"); - } - } - - @Test - public void testCreateNative() throws Exception { - Workbook wb; - - // POIFS -> hssf - wb = WorkbookFactory.create( - new POIFSFileSystem(HSSFTestDataSamples.openSampleFileStream(xls)) - ); - assertNotNull(wb); - assertTrue(wb instanceof HSSFWorkbook); - assertCloseDoesNotModifyFile(xls, wb); - - // Package -> xssf - wb = WorkbookFactory.create( - OPCPackage.open( - HSSFTestDataSamples.openSampleFileStream(xlsx)) - ); - assertNotNull(wb); - assertTrue(wb instanceof XSSFWorkbook); - assertCloseDoesNotModifyFile(xlsx, wb); - } - - @Test - public void testCreateReadOnly() throws Exception { - Workbook wb; - - // POIFS -> hssf - wb = WorkbookFactory.create(HSSFTestDataSamples.getSampleFile(xls), null, true); - assertNotNull(wb); - assertTrue(wb instanceof HSSFWorkbook); - assertCloseDoesNotModifyFile(xls, wb); - - // Package -> xssf - wb = WorkbookFactory.create(HSSFTestDataSamples.getSampleFile(xlsx), null, true); - assertNotNull(wb); - assertTrue(wb instanceof XSSFWorkbook); - assertCloseDoesNotModifyFile(xlsx, wb); - } - - /** - * Creates the appropriate kind of Workbook, but - * checking the mime magic at the start of the - * InputStream, then creating what's required. - */ - @Test - public void testCreateGeneric() throws Exception { - Workbook wb; - - // InputStream -> either - wb = WorkbookFactory.create( - HSSFTestDataSamples.openSampleFileStream(xls) - ); - assertNotNull(wb); - assertTrue(wb instanceof HSSFWorkbook); - assertCloseDoesNotModifyFile(xls, wb); - - wb = WorkbookFactory.create( - HSSFTestDataSamples.openSampleFileStream(xlsx) - ); - assertNotNull(wb); - assertTrue(wb instanceof XSSFWorkbook); - assertCloseDoesNotModifyFile(xlsx, wb); - - // File -> either - wb = WorkbookFactory.create( - HSSFTestDataSamples.getSampleFile(xls) - ); - assertNotNull(wb); - assertTrue(wb instanceof HSSFWorkbook); - assertCloseDoesNotModifyFile(xls, wb); - - wb = WorkbookFactory.create( - HSSFTestDataSamples.getSampleFile(xlsx) - ); - assertNotNull(wb); - assertTrue(wb instanceof XSSFWorkbook); - assertCloseDoesNotModifyFile(xlsx, wb); - - // Invalid type -> exception - final byte[] before = HSSFTestDataSamples.getTestDataFileContent(txt); - try { - InputStream stream = HSSFTestDataSamples.openSampleFileStream(txt); - try { - wb = WorkbookFactory.create(stream); - } finally { - stream.close(); - } - fail(); - } catch(InvalidFormatException e) { - // Good - } - final byte[] after = HSSFTestDataSamples.getTestDataFileContent(txt); - assertArrayEquals("Invalid type file was modified after trying to open the file as a spreadsheet", - before, after); - } - - /** - * Check that the overloaded stream methods which take passwords work properly - */ - @Test - public void testCreateWithPasswordFromStream() throws Exception { - Workbook wb; - - - // Unprotected, no password given, opens normally - wb = WorkbookFactory.create( - HSSFTestDataSamples.openSampleFileStream(xls), null - ); - assertNotNull(wb); - assertTrue(wb instanceof HSSFWorkbook); - assertCloseDoesNotModifyFile(xls, wb); - - wb = WorkbookFactory.create( - HSSFTestDataSamples.openSampleFileStream(xlsx), null - ); - assertNotNull(wb); - assertTrue(wb instanceof XSSFWorkbook); - assertCloseDoesNotModifyFile(xlsx, wb); - - - // Unprotected, wrong password, opens normally - wb = WorkbookFactory.create( - HSSFTestDataSamples.openSampleFileStream(xls), "wrong" - ); - assertNotNull(wb); - assertTrue(wb instanceof HSSFWorkbook); - assertCloseDoesNotModifyFile(xls, wb); - - wb = WorkbookFactory.create( - HSSFTestDataSamples.openSampleFileStream(xlsx), "wrong" - ); - assertNotNull(wb); - assertTrue(wb instanceof XSSFWorkbook); - assertCloseDoesNotModifyFile(xlsx, wb); - - - // Protected, correct password, opens fine - wb = WorkbookFactory.create( - HSSFTestDataSamples.openSampleFileStream(xls_prot[0]), xls_prot[1] - ); - assertNotNull(wb); - assertTrue(wb instanceof HSSFWorkbook); - assertCloseDoesNotModifyFile(xls_prot[0], wb); - - wb = WorkbookFactory.create( - HSSFTestDataSamples.openSampleFileStream(xlsx_prot[0]), xlsx_prot[1] - ); - assertNotNull(wb); - assertTrue(wb instanceof XSSFWorkbook); - assertCloseDoesNotModifyFile(xlsx_prot[0], wb); - - - // Protected, wrong password, throws Exception - try { - wb = WorkbookFactory.create( - HSSFTestDataSamples.openSampleFileStream(xls_prot[0]), "wrong" - ); - assertCloseDoesNotModifyFile(xls_prot[0], wb); - fail("Shouldn't be able to open with the wrong password"); - } catch (EncryptedDocumentException e) {} - - try { - wb = WorkbookFactory.create( - HSSFTestDataSamples.openSampleFileStream(xlsx_prot[0]), "wrong" - ); - assertCloseDoesNotModifyFile(xlsx_prot[0], wb); - fail("Shouldn't be able to open with the wrong password"); - } catch (EncryptedDocumentException e) {} - } - - /** - * Check that the overloaded file methods which take passwords work properly - */ - @Test - public void testCreateWithPasswordFromFile() throws Exception { - Workbook wb; - - // Unprotected, no password given, opens normally - wb = WorkbookFactory.create( - HSSFTestDataSamples.getSampleFile(xls), null - ); - assertNotNull(wb); - assertTrue(wb instanceof HSSFWorkbook); - assertCloseDoesNotModifyFile(xls, wb); - - wb = WorkbookFactory.create( - HSSFTestDataSamples.getSampleFile(xlsx), null - ); - assertNotNull(wb); - assertTrue(wb instanceof XSSFWorkbook); - assertCloseDoesNotModifyFile(xlsx, wb); - - // Unprotected, wrong password, opens normally - wb = WorkbookFactory.create( - HSSFTestDataSamples.getSampleFile(xls), "wrong" - ); - assertNotNull(wb); - assertTrue(wb instanceof HSSFWorkbook); - assertCloseDoesNotModifyFile(xls, wb); - - wb = WorkbookFactory.create( - HSSFTestDataSamples.getSampleFile(xlsx), "wrong" - ); - assertNotNull(wb); - assertTrue(wb instanceof XSSFWorkbook); - assertCloseDoesNotModifyFile(xlsx, wb); - - // Protected, correct password, opens fine - wb = WorkbookFactory.create( - HSSFTestDataSamples.getSampleFile(xls_prot[0]), xls_prot[1] - ); - assertNotNull(wb); - assertTrue(wb instanceof HSSFWorkbook); - assertCloseDoesNotModifyFile(xls_prot[0], wb); - - wb = WorkbookFactory.create( - HSSFTestDataSamples.getSampleFile(xlsx_prot[0]), xlsx_prot[1] - ); - assertNotNull(wb); - assertTrue(wb instanceof XSSFWorkbook); - assertTrue(wb.getNumberOfSheets() > 0); - assertNotNull(wb.getSheetAt(0)); - assertNotNull(wb.getSheetAt(0).getRow(0)); - assertCloseDoesNotModifyFile(xlsx_prot[0], wb); - - // Protected, wrong password, throws Exception - try { - wb = WorkbookFactory.create( - HSSFTestDataSamples.getSampleFile(xls_prot[0]), "wrong" - ); - assertCloseDoesNotModifyFile(xls_prot[0], wb); - fail("Shouldn't be able to open with the wrong password"); - } catch (EncryptedDocumentException e) { - // expected here - } - - try { - wb = WorkbookFactory.create( - HSSFTestDataSamples.getSampleFile(xlsx_prot[0]), "wrong" - ); - assertCloseDoesNotModifyFile(xlsx_prot[0], wb); - fail("Shouldn't be able to open with the wrong password"); - } catch (EncryptedDocumentException e) { - // expected here - } - } - - /** - * Check that a helpful exception is given on an empty input stream - */ - @Test - public void testEmptyInputStream() throws Exception { - InputStream emptyStream = new ByteArrayInputStream(new byte[0]); - try { - WorkbookFactory.create(emptyStream); - fail("Shouldn't be able to create for an empty stream"); - } catch (final EmptyFileException expected) {} - } - - /** - * Check that a helpful exception is given on an empty file - */ - @Test - public void testEmptyFile() throws Exception { - File emptyFile = TempFile.createTempFile("empty", ".poi"); - try { - WorkbookFactory.create(emptyFile); - fail("Shouldn't be able to create for an empty file"); - } catch (final EmptyFileException expected) {} - emptyFile.delete(); - } - - /** - * Check that a helpful exception is raised on a non-existing file - */ - @Test - public void testNonExistantFile() throws Exception { - File nonExistantFile = new File("notExistantFile"); - assertFalse(nonExistantFile.exists()); - - try { - WorkbookFactory.create(nonExistantFile, "password", true); - fail("Should not be able to create for a non-existant file"); - } catch (final FileNotFoundException e) { - // expected - } - } - -} diff --git a/src/ooxml/testcases/org/apache/poi/ss/extractor/TestEmbeddedExtractor.java b/src/ooxml/testcases/org/apache/poi/ss/extractor/TestEmbeddedExtractor.java deleted file mode 100644 index 669fd3381..000000000 --- a/src/ooxml/testcases/org/apache/poi/ss/extractor/TestEmbeddedExtractor.java +++ /dev/null @@ -1,134 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.extractor; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import java.io.IOException; -import java.io.InputStream; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.ArrayList; -import java.util.List; - -import javax.xml.bind.DatatypeConverter; - -import org.apache.poi.EncryptedDocumentException; -import org.apache.poi.POIDataSamples; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.usermodel.WorkbookFactory; -import org.junit.Test; - -public class TestEmbeddedExtractor { - private static final POIDataSamples samples = POIDataSamples.getSpreadSheetInstance(); - - @Test - public void extractPDFfromEMF() throws Exception { - InputStream fis = samples.openResourceAsStream("Basic_Expense_Template_2011.xls"); - Workbook wb = WorkbookFactory.create(fis); - fis.close(); - - EmbeddedExtractor ee = new EmbeddedExtractor(); - List edList = new ArrayList(); - for (Sheet s : wb) { - edList.addAll(ee.extractAll(s)); - } - wb.close(); - - assertEquals(2, edList.size()); - - String filename1 = "Sample.pdf"; - EmbeddedData ed0 = edList.get(0); - assertEquals(filename1, ed0.getFilename()); - assertEquals(filename1, ed0.getShape().getShapeName().trim()); - assertEquals("uNplB1QpYug+LWappiTh0w==", md5hash(ed0.getEmbeddedData())); - - String filename2 = "kalastuslupa_jiyjhnj_yuiyuiyuio_uyte_sldfsdfsdf_sfsdfsdf_sfsssfsf_sdfsdfsdfsdf_sdfsdfsdf.pdf"; - EmbeddedData ed1 = edList.get(1); - assertEquals(filename2, ed1.getFilename()); - assertEquals(filename2, ed1.getShape().getShapeName().trim()); - assertEquals("QjLuAZ+cd7KbhVz4sj+QdA==", md5hash(ed1.getEmbeddedData())); - } - - @Test - public void extractFromXSSF() throws IOException, EncryptedDocumentException, InvalidFormatException { - InputStream fis = samples.openResourceAsStream("58325_db.xlsx"); - Workbook wb = WorkbookFactory.create(fis); - fis.close(); - - EmbeddedExtractor ee = new EmbeddedExtractor(); - List edList = new ArrayList(); - for (Sheet s : wb) { - edList.addAll(ee.extractAll(s)); - } - wb.close(); - - assertEquals(4, edList.size()); - EmbeddedData ed0 = edList.get(0); - assertEquals("Object 1.pdf", ed0.getFilename()); - assertEquals("Object 1", ed0.getShape().getShapeName().trim()); - assertEquals("Oyys6UtQU1gbHYBYqA4NFA==", md5hash(ed0.getEmbeddedData())); - - EmbeddedData ed1 = edList.get(1); - assertEquals("Object 2.pdf", ed1.getFilename()); - assertEquals("Object 2", ed1.getShape().getShapeName().trim()); - assertEquals("xLScPUS0XH+5CTZ2A3neNw==", md5hash(ed1.getEmbeddedData())); - - EmbeddedData ed2 = edList.get(2); - assertEquals("Object 3.pdf", ed2.getFilename()); - assertEquals("Object 3", ed2.getShape().getShapeName().trim()); - assertEquals("rX4klZqJAeM5npb54Gi2+Q==", md5hash(ed2.getEmbeddedData())); - - EmbeddedData ed3 = edList.get(3); - assertEquals("Microsoft_Excel_Worksheet1.xlsx", ed3.getFilename()); - assertEquals("Object 1", ed3.getShape().getShapeName().trim()); - assertEquals("4m4N8ji2tjpEGPQuw2YwGA==", md5hash(ed3.getEmbeddedData())); - } - - public static String md5hash(byte[] input) { - try { - MessageDigest md = MessageDigest.getInstance("MD5"); - byte hash[] = md.digest(input); - return DatatypeConverter.printBase64Binary(hash); - } catch (NoSuchAlgorithmException e) { - // doesn't happen - throw new RuntimeException(e); - } - } - - - @Test - public void testNPE() throws IOException { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("angelo.edu_content_files_19555-nsse-2011-multiyear-benchmark.xls"); - EmbeddedExtractor ee = new EmbeddedExtractor(); - - for (Sheet s : wb) { - for (EmbeddedData ed : ee.extractAll(s)) { - assertNotNull(ed.getFilename()); - assertNotNull(ed.getEmbeddedData()); - assertNotNull(ed.getShape()); - } - } - - } -} diff --git a/src/ooxml/testcases/org/apache/poi/ss/format/TestCellFormatPart.java b/src/ooxml/testcases/org/apache/poi/ss/format/TestCellFormatPart.java deleted file mode 100644 index ea5192638..000000000 --- a/src/ooxml/testcases/org/apache/poi/ss/format/TestCellFormatPart.java +++ /dev/null @@ -1,170 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.format; - -import static org.junit.Assert.assertEquals; - -import java.util.Locale; -import java.util.TimeZone; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.util.LocaleUtil; -import org.apache.poi.xssf.XSSFITestDataProvider; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; - -/** Test the individual CellFormatPart types. */ -public class TestCellFormatPart extends CellFormatTestBase { - - private static Locale userLocale; - - @BeforeClass - public static void setLocale() { - userLocale = LocaleUtil.getUserLocale(); - LocaleUtil.setUserLocale(Locale.ROOT); - } - - @AfterClass - public static void unsetLocale() { - LocaleUtil.setUserLocale(userLocale); - } - - private static final Pattern NUMBER_EXTRACT_FMT = Pattern.compile( - "([-+]?[0-9]+)(\\.[0-9]+)?.*(?:(e).*?([+-]?[0-9]+))", - Pattern.CASE_INSENSITIVE); - - public TestCellFormatPart() { - super(XSSFITestDataProvider.instance); - } - - @Test - public void testGeneralFormat() throws Exception { - runFormatTests("GeneralFormatTests.xlsx", new CellValue() { - @Override - public Object getValue(Cell cell) { - switch (CellFormat.ultimateTypeEnum(cell)) { - case BOOLEAN: - return cell.getBooleanCellValue(); - case NUMERIC: - return cell.getNumericCellValue(); - default: - return cell.getStringCellValue(); - } - } - }); - } - - public void testNumberFormat() throws Exception { - runFormatTests("NumberFormatTests.xlsx", new CellValue() { - @Override - public Object getValue(Cell cell) { - return cell.getNumericCellValue(); - } - }); - } - - @Test - public void testNumberApproxFormat() throws Exception { - runFormatTests("NumberFormatApproxTests.xlsx", new CellValue() { - @Override - public Object getValue(Cell cell) { - return cell.getNumericCellValue(); - } - - @Override - void equivalent(String expected, String actual, - CellFormatPart format) { - double expectedVal = extractNumber(expected); - double actualVal = extractNumber(actual); - // equal within 1% - double delta = expectedVal / 100; - assertEquals("format \"" + format + "\"," + expected + " ~= " + - actual, expectedVal, actualVal, delta); - } - }); - } - - @Test - public void testDateFormat() throws Exception { - TimeZone tz = LocaleUtil.getUserTimeZone(); - LocaleUtil.setUserTimeZone(TimeZone.getTimeZone("CET")); - try { - runFormatTests("DateFormatTests.xlsx", new CellValue() { - @Override - public Object getValue(Cell cell) { - return cell.getDateCellValue(); - } - }); - } finally { - LocaleUtil.setUserTimeZone(tz); - } - } - - @Test - public void testElapsedFormat() throws Exception { - runFormatTests("ElapsedFormatTests.xlsx", new CellValue() { - @Override - public Object getValue(Cell cell) { - return cell.getNumericCellValue(); - } - }); - } - - @Test - public void testTextFormat() throws Exception { - runFormatTests("TextFormatTests.xlsx", new CellValue() { - @Override - public Object getValue(Cell cell) { - switch(CellFormat.ultimateTypeEnum(cell)) { - case BOOLEAN: - return cell.getBooleanCellValue(); - default: - return cell.getStringCellValue(); - } - } - }); - } - - @Test - public void testConditions() throws Exception { - runFormatTests("FormatConditionTests.xlsx", new CellValue() { - @Override - Object getValue(Cell cell) { - return cell.getNumericCellValue(); - } - }); - } - - private double extractNumber(String str) { - Matcher m = NUMBER_EXTRACT_FMT.matcher(str); - if (!m.find()) - throw new IllegalArgumentException( - "Cannot find numer in \"" + str + "\""); - - StringBuffer sb = new StringBuffer(); - // The groups in the pattern are the parts of the number - for (int i = 1; i <= m.groupCount(); i++) { - String part = m.group(i); - if (part != null) - sb.append(part); - } - return Double.valueOf(sb.toString()); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/ss/formula/TestFormulaParser.java b/src/ooxml/testcases/org/apache/poi/ss/formula/TestFormulaParser.java deleted file mode 100644 index a9d739796..000000000 --- a/src/ooxml/testcases/org/apache/poi/ss/formula/TestFormulaParser.java +++ /dev/null @@ -1,230 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -package org.apache.poi.ss.formula; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFEvaluationWorkbook; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.ptg.AbstractFunctionPtg; -import org.apache.poi.ss.formula.ptg.NameXPxg; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.apache.poi.ss.formula.ptg.Ref3DPxg; -import org.apache.poi.ss.formula.ptg.StringPtg; -import org.apache.poi.util.IOUtils; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.usermodel.XSSFEvaluationWorkbook; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Test; - -/** - * Test {@link FormulaParser}'s handling of row numbers at the edge of the - * HSSF/XSSF ranges. - * - * @author David North - */ -public class TestFormulaParser { - - @Test - public void testHSSFFailsForOver65536() { - FormulaParsingWorkbook workbook = HSSFEvaluationWorkbook.create(new HSSFWorkbook()); - try { - FormulaParser.parse("Sheet1!1:65537", workbook, FormulaType.CELL, 0); - fail("Expected exception"); - } - catch (FormulaParseException expected) { - // expected here - } - } - - private static void checkHSSFFormula(String formula) { - HSSFWorkbook wb = new HSSFWorkbook(); - FormulaParsingWorkbook workbook = HSSFEvaluationWorkbook.create(wb); - FormulaParser.parse(formula, workbook, FormulaType.CELL, 0); - IOUtils.closeQuietly(wb); - } - private static void checkXSSFFormula(String formula) { - XSSFWorkbook wb = new XSSFWorkbook(); - FormulaParsingWorkbook workbook = XSSFEvaluationWorkbook.create(wb); - FormulaParser.parse(formula, workbook, FormulaType.CELL, 0); - IOUtils.closeQuietly(wb); - } - private static void checkFormula(String formula) { - checkHSSFFormula(formula); - checkXSSFFormula(formula); - } - - @Test - public void testHSSFPassCase() { - checkHSSFFormula("Sheet1!1:65536"); - } - - @Test - public void testXSSFWorksForOver65536() { - checkXSSFFormula("Sheet1!1:65537"); - } - - @Test - public void testXSSFFailCase() { - FormulaParsingWorkbook workbook = XSSFEvaluationWorkbook.create(new XSSFWorkbook()); - try { - FormulaParser.parse("Sheet1!1:1048577", workbook, FormulaType.CELL, 0); // one more than max rows. - fail("Expected exception"); - } - catch (FormulaParseException expected) { - // expected here - } - } - - // copied from org.apache.poi.hssf.model.TestFormulaParser - @Test - public void testMacroFunction() throws Exception { - // testNames.xlsm contains a VB function called 'myFunc' - final String testFile = "testNames.xlsm"; - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook(testFile); - try { - XSSFEvaluationWorkbook workbook = XSSFEvaluationWorkbook.create(wb); - - //Expected ptg stack: [NamePtg(myFunc), StringPtg(arg), (additional operands would go here...), FunctionPtg(myFunc)] - Ptg[] ptg = FormulaParser.parse("myFunc(\"arg\")", workbook, FormulaType.CELL, -1); - assertEquals(3, ptg.length); - - // the name gets encoded as the first operand on the stack - NameXPxg tname = (NameXPxg) ptg[0]; - assertEquals("myFunc", tname.toFormulaString()); - - // the function's arguments are pushed onto the stack from left-to-right as OperandPtgs - StringPtg arg = (StringPtg) ptg[1]; - assertEquals("arg", arg.getValue()); - - // The external FunctionPtg is the last Ptg added to the stack - // During formula evaluation, this Ptg pops off the the appropriate number of - // arguments (getNumberOfOperands()) and pushes the result on the stack - AbstractFunctionPtg tfunc = (AbstractFunctionPtg) ptg[2]; - assertTrue(tfunc.isExternalFunction()); - - // confirm formula parsing is case-insensitive - FormulaParser.parse("mYfUnC(\"arg\")", workbook, FormulaType.CELL, -1); - - // confirm formula parsing doesn't care about argument count or type - // this should only throw an error when evaluating the formula. - FormulaParser.parse("myFunc()", workbook, FormulaType.CELL, -1); - FormulaParser.parse("myFunc(\"arg\", 0, TRUE)", workbook, FormulaType.CELL, -1); - - // A completely unknown formula name (not saved in workbook) should still be parseable and renderable - // but will throw an NotImplementedFunctionException or return a #NAME? error value if evaluated. - FormulaParser.parse("yourFunc(\"arg\")", workbook, FormulaType.CELL, -1); - - // Make sure workbook can be written and read - XSSFTestDataSamples.writeOutAndReadBack(wb).close(); - - // Manually check to make sure file isn't corrupted - // TODO: develop a process for occasionally manually reviewing workbooks - // to verify workbooks are not corrupted - /* - final File fileIn = XSSFTestDataSamples.getSampleFile(testFile); - final File reSavedFile = new File(fileIn.getParentFile(), fileIn.getName().replace(".xlsm", "-saved.xlsm")); - final FileOutputStream fos = new FileOutputStream(reSavedFile); - wb.write(fos); - fos.close(); - */ - } finally { - wb.close(); - } - } - - @Test - public void testParserErrors() throws Exception { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("testNames.xlsm"); - try { - XSSFEvaluationWorkbook workbook = XSSFEvaluationWorkbook.create(wb); - - parseExpectedException("("); - parseExpectedException(")"); - parseExpectedException("+"); - parseExpectedException("42+"); - parseExpectedException("IF()"); - parseExpectedException("IF("); //no closing paren - parseExpectedException("myFunc(", workbook); //no closing paren - } finally { - wb.close(); - } - } - - private static void parseExpectedException(String formula) { - parseExpectedException(formula, null); - } - - /** confirm formula has invalid syntax and parsing the formula results in FormulaParseException - */ - private static void parseExpectedException(String formula, FormulaParsingWorkbook wb) { - try { - FormulaParser.parse(formula, wb, FormulaType.CELL, -1); - fail("Expected FormulaParseException: " + formula); - } catch (final FormulaParseException e) { - // expected during successful test - assertNotNull(e.getMessage()); - } - } - - // trivial case for bug 60219: FormulaParser can't parse external references when sheet name is quoted - @Test - public void testParseExternalReferencesWithUnquotedSheetName() throws Exception { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFEvaluationWorkbook fpwb = XSSFEvaluationWorkbook.create(wb); - Ptg[] ptgs = FormulaParser.parse("[1]Sheet1!A1", fpwb, FormulaType.CELL, -1); - // org.apache.poi.ss.formula.ptg.Ref3DPxg [ [workbook=1] sheet=Sheet 1 ! A1] - assertEquals("Ptgs length", 1, ptgs.length); - assertTrue("Ptg class", ptgs[0] instanceof Ref3DPxg); - Ref3DPxg pxg = (Ref3DPxg) ptgs[0]; - assertEquals("External workbook number", 1, pxg.getExternalWorkbookNumber()); - assertEquals("Sheet name", "Sheet1", pxg.getSheetName()); - assertEquals("Row", 0, pxg.getRow()); - assertEquals("Column", 0, pxg.getColumn()); - wb.close(); - } - - // bug 60219: FormulaParser can't parse external references when sheet name is quoted - @Test - public void testParseExternalReferencesWithQuotedSheetName() throws Exception { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFEvaluationWorkbook fpwb = XSSFEvaluationWorkbook.create(wb); - Ptg[] ptgs = FormulaParser.parse("'[1]Sheet 1'!A1", fpwb, FormulaType.CELL, -1); - // org.apache.poi.ss.formula.ptg.Ref3DPxg [ [workbook=1] sheet=Sheet 1 ! A1] - assertEquals("Ptgs length", 1, ptgs.length); - assertTrue("Ptg class", ptgs[0] instanceof Ref3DPxg); - Ref3DPxg pxg = (Ref3DPxg) ptgs[0]; - assertEquals("External workbook number", 1, pxg.getExternalWorkbookNumber()); - assertEquals("Sheet name", "Sheet 1", pxg.getSheetName()); - assertEquals("Row", 0, pxg.getRow()); - assertEquals("Column", 0, pxg.getColumn()); - wb.close(); - } - - // bug 60260 - @Test - public void testUnicodeSheetName() { - checkFormula("'Sheet\u30FB1'!A1:A6"); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/ss/formula/TestStructuredReferences.java b/src/ooxml/testcases/org/apache/poi/ss/formula/TestStructuredReferences.java deleted file mode 100644 index b60664ad0..000000000 --- a/src/ooxml/testcases/org/apache/poi/ss/formula/TestStructuredReferences.java +++ /dev/null @@ -1,127 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Table; -import org.apache.poi.ss.util.AreaReference; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFTable; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Test; - -/** - * Tests Excel Table expressions (structured references) - * @see - * Excel Structured Reference Syntax - * - */ -public class TestStructuredReferences { - - /** - * Test the regular expression used in INDIRECT() evaluation to recognize structured references - */ - @Test - public void testTableExpressionSyntax() { - assertTrue("Valid structured reference syntax didn't match expression", Table.isStructuredReference.matcher("abc[col1]").matches()); - assertTrue("Valid structured reference syntax didn't match expression", Table.isStructuredReference.matcher("_abc[col1]").matches()); - assertTrue("Valid structured reference syntax didn't match expression", Table.isStructuredReference.matcher("_[col1]").matches()); - assertTrue("Valid structured reference syntax didn't match expression", Table.isStructuredReference.matcher("\\[col1]").matches()); - assertTrue("Valid structured reference syntax didn't match expression", Table.isStructuredReference.matcher("\\[col1]").matches()); - assertTrue("Valid structured reference syntax didn't match expression", Table.isStructuredReference.matcher("\\[#This Row]").matches()); - assertTrue("Valid structured reference syntax didn't match expression", Table.isStructuredReference.matcher("\\[ [col1], [col2] ]").matches()); - - // can't have a space between the table name and open bracket - assertFalse("Invalid structured reference syntax didn't fail expression", Table.isStructuredReference.matcher("\\abc [ [col1], [col2] ]").matches()); - } - - @Test - public void testTableFormulas() throws Exception { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("StructuredReferences.xlsx"); - try { - - final FormulaEvaluator eval = new XSSFFormulaEvaluator(wb); - final XSSFSheet tableSheet = wb.getSheet("Table"); - final XSSFSheet formulaSheet = wb.getSheet("Formulas"); - - confirm(eval, tableSheet.getRow(5).getCell(0), 49); - confirm(eval, formulaSheet.getRow(0).getCell(0), 209); - confirm(eval, formulaSheet.getRow(1).getCell(0), "one"); - - // test changing a table value, to see if the caches are properly cleared - // Issue 59814 - - // this test passes before the fix for 59814 - tableSheet.getRow(1).getCell(1).setCellValue("ONEA"); - confirm(eval, formulaSheet.getRow(1).getCell(0), "ONEA"); - - // test adding a row to a table, issue 59814 - Row newRow = tableSheet.getRow(7); - if (newRow == null) newRow = tableSheet.createRow(7); - newRow.createCell(0, CellType.FORMULA).setCellFormula("\\_Prime.1[[#This Row],[@Number]]*\\_Prime.1[[#This Row],[@Number]]"); - newRow.createCell(1, CellType.STRING).setCellValue("thirteen"); - newRow.createCell(2, CellType.NUMERIC).setCellValue(13); - - // update Table - final XSSFTable table = wb.getTable("\\_Prime.1"); - final AreaReference newArea = new AreaReference(table.getStartCellReference(), new CellReference(table.getEndRowIndex() + 1, table.getEndColIndex())); - String newAreaStr = newArea.formatAsString(); - table.getCTTable().setRef(newAreaStr); - table.getCTTable().getAutoFilter().setRef(newAreaStr); - table.updateHeaders(); - table.updateReferences(); - - // these fail before the fix for 59814 - confirm(eval, tableSheet.getRow(7).getCell(0), 13*13); - confirm(eval, formulaSheet.getRow(0).getCell(0), 209 + 13*13); - - } finally { - wb.close(); - } - } - - private static void confirm(FormulaEvaluator fe, Cell cell, double expectedResult) { - fe.clearAllCachedResultValues(); - CellValue cv = fe.evaluate(cell); - if (cv.getCellTypeEnum() != CellType.NUMERIC) { - fail("expected numeric cell type but got " + cv.formatAsString()); - } - assertEquals(expectedResult, cv.getNumberValue(), 0.0); - } - - private static void confirm(FormulaEvaluator fe, Cell cell, String expectedResult) { - fe.clearAllCachedResultValues(); - CellValue cv = fe.evaluate(cell); - if (cv.getCellTypeEnum() != CellType.STRING) { - fail("expected String cell type but got " + cv.formatAsString()); - } - assertEquals(expectedResult, cv.getStringValue()); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/ss/formula/eval/TestXSSFCircularReferences.java b/src/ooxml/testcases/org/apache/poi/ss/formula/eval/TestXSSFCircularReferences.java deleted file mode 100644 index 0b8c9fcb1..000000000 --- a/src/ooxml/testcases/org/apache/poi/ss/formula/eval/TestXSSFCircularReferences.java +++ /dev/null @@ -1,31 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.eval; - -import org.apache.poi.xssf.XSSFITestDataProvider; - -/** - * Tests XSSFFormulaEvaluator for its handling of cell formula circular references. - * - * @author Josh Micich - */ -public final class TestXSSFCircularReferences extends BaseTestCircularReferences { - public TestXSSFCircularReferences() { - super(XSSFITestDataProvider.instance); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/ss/formula/functions/CountifsTests.java b/src/ooxml/testcases/org/apache/poi/ss/formula/functions/CountifsTests.java deleted file mode 100644 index 3b3d71465..000000000 --- a/src/ooxml/testcases/org/apache/poi/ss/formula/functions/CountifsTests.java +++ /dev/null @@ -1,122 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - - -package org.apache.poi.ss.formula.functions; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.SheetUtil; -import org.apache.poi.util.IOUtils; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -/** - * Test the COUNTIFS() function - */ -public class CountifsTests { - - private Workbook workbook; - - /** - * initialize a workbook - */ - @Before - public void before() { - // not sure why we allow this, COUNTIFS() is only available - // in OOXML, it was introduced with Office 2007 - workbook = new HSSFWorkbook(); - } - - /** - * Close the workbook if needed - */ - @After - public void after() { - IOUtils.closeQuietly(workbook); - } - - /** - * Basic call - */ - @Test - public void testCallFunction() { - Sheet sheet = workbook.createSheet("test"); - Row row1 = sheet.createRow(0); - Cell cellA1 = row1.createCell(0, CellType.FORMULA); - Cell cellB1 = row1.createCell(1, CellType.NUMERIC); - Cell cellC1 = row1.createCell(2, CellType.NUMERIC); - Cell cellD1 = row1.createCell(3, CellType.NUMERIC); - Cell cellE1 = row1.createCell(4, CellType.NUMERIC); - cellB1.setCellValue(1); - cellC1.setCellValue(1); - cellD1.setCellValue(2); - cellE1.setCellValue(4); - - cellA1.setCellFormula("COUNTIFS(B1:C1,1, D1:E1,2)"); - FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator(); - CellValue evaluate = evaluator.evaluate(cellA1); - assertEquals(1.0d, evaluate.getNumberValue(), 0.000000000000001); - } - - /** - * Test argument count check - */ - @Test - public void testCallFunction_invalidArgs() { - Sheet sheet = workbook.createSheet("test"); - Row row1 = sheet.createRow(0); - Cell cellA1 = row1.createCell(0, CellType.FORMULA); - cellA1.setCellFormula("COUNTIFS()"); - FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator(); - CellValue evaluate = evaluator.evaluate(cellA1); - assertEquals(15, evaluate.getErrorValue()); - cellA1.setCellFormula("COUNTIFS(A1:C1)"); - evaluator = workbook.getCreationHelper().createFormulaEvaluator(); - evaluate = evaluator.evaluate(cellA1); - assertEquals(15, evaluate.getErrorValue()); - cellA1.setCellFormula("COUNTIFS(A1:C1,2,2)"); - evaluator = workbook.getCreationHelper().createFormulaEvaluator(); - evaluate = evaluator.evaluate(cellA1); - assertEquals(15, evaluate.getErrorValue()); - } - - /** - * the bug returned the wrong count, this verifies the fix - * @throws Exception if the file can't be read - */ - @Test - public void testBug56822() throws Exception { - workbook = XSSFTestDataSamples.openSampleWorkbook("56822-Countifs.xlsx"); - FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator(); - Cell cell = SheetUtil.getCell(workbook.getSheetAt(0), 0, 3); - assertNotNull("Test workbook missing cell D1", cell); - CellValue evaluate = evaluator.evaluate(cell); - assertEquals(2.0d, evaluate.getNumberValue(), 0.00000000000001); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/ss/formula/functions/TestProper.java b/src/ooxml/testcases/org/apache/poi/ss/formula/functions/TestProper.java deleted file mode 100644 index 921dc445e..000000000 --- a/src/ooxml/testcases/org/apache/poi/ss/formula/functions/TestProper.java +++ /dev/null @@ -1,141 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -import junit.framework.AssertionFailedError; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -public final class TestProper { - private Cell cell11; - private FormulaEvaluator evaluator; - - @Test - public void testValidHSSF() { - HSSFWorkbook wb = new HSSFWorkbook(); - evaluator = new HSSFFormulaEvaluator(wb); - - confirm(wb); - } - - @Test - public void testValidXSSF() { - XSSFWorkbook wb = new XSSFWorkbook(); - evaluator = new XSSFFormulaEvaluator(wb); - - confirm(wb); - } - - private void confirm(Workbook wb) { - Sheet sheet = wb.createSheet("new sheet"); - cell11 = sheet.createRow(0).createCell(0); - cell11.setCellType(CellType.FORMULA); - - confirm("PROPER(\"hi there\")", "Hi There"); //simple case - confirm("PROPER(\"what's up\")", "What'S Up"); //apostrophes are treated as word breaks - confirm("PROPER(\"I DON'T TH!NK SO!\")", "I Don'T Th!Nk So!"); //capitalization is ignored, special punctuation is treated as a word break - confirm("PROPER(\"dr\u00dcb\u00f6'\u00e4 \u00e9lo\u015f|\u00eb\u00e8 \")", "Dr\u00fcb\u00f6'\u00c4 \u00c9lo\u015f|\u00cb\u00e8 "); - confirm("PROPER(\"hi123 the123re\")", "Hi123 The123Re"); //numbers are treated as word breaks - confirm("PROPER(\"-\")", "-"); //nothing happens with ascii punctuation that is not upper or lower case - confirm("PROPER(\"!\u00a7$\")", "!\u00a7$"); //nothing happens with unicode punctuation (section sign) that is not upper or lower case - confirm("PROPER(\"/&%\")", "/&%"); //nothing happens with ascii punctuation that is not upper or lower case - confirm("PROPER(\"Apache POI\")", "Apache Poi"); //acronyms are not special - confirm("PROPER(\" hello world\")", " Hello World"); //leading whitespace is ignored - - final String scharfes = "\u00df"; //German lowercase eszett, scharfes s, sharp s - confirm("PROPER(\"stra"+scharfes+"e\")", "Stra"+scharfes+"e"); - assertTrue(Character.isLetter(scharfes.charAt(0))); - - // CURRENTLY FAILS: result: "SSUnd"+scharfes - // LibreOffice 5.0.3.2 behavior: "Sund"+scharfes - // Excel 2013 behavior: ??? - confirm("PROPER(\""+scharfes+"und"+scharfes+"\")", "SSund"+scharfes); - - // also test longer string - StringBuilder builder = new StringBuilder("A"); - StringBuilder expected = new StringBuilder("A"); - for(int i = 1;i < 254;i++) { - builder.append((char)(65 + (i % 26))); - expected.append((char)(97 + (i % 26))); - } - confirm("PROPER(\"" + builder.toString() + "\")", expected.toString()); - } - - private void confirm(String formulaText, String expectedResult) { - cell11.setCellFormula(formulaText); - evaluator.clearAllCachedResultValues(); - CellValue cv = evaluator.evaluate(cell11); - if (cv.getCellTypeEnum() != CellType.STRING) { - throw new AssertionFailedError("Wrong result type: " + cv.formatAsString()); - } - String actualValue = cv.getStringValue(); - assertEquals(expectedResult, actualValue); - } - - @Test - public void test() { - checkProper("", ""); - checkProper("a", "A"); - checkProper("abc", "Abc"); - checkProper("abc abc", "Abc Abc"); - checkProper("abc/abc", "Abc/Abc"); - checkProper("ABC/ABC", "Abc/Abc"); - checkProper("aBc/ABC", "Abc/Abc"); - checkProper("aBc@#$%^&*()_+=-ABC", "Abc@#$%^&*()_+=-Abc"); - checkProper("aBc25aerg/ABC", "Abc25Aerg/Abc"); - checkProper("aBc/\u00C4\u00F6\u00DF\u00FC/ABC", "Abc/\u00C4\u00F6\u00DF\u00FC/Abc"); // Some German umlauts with uppercase first letter is not changed - checkProper("\u00FC", "\u00DC"); - checkProper("\u00DC", "\u00DC"); - checkProper("\u00DF", "SS"); // German "scharfes s" is uppercased to "SS" - checkProper("\u00DFomesing", "SSomesing"); // German "scharfes s" is uppercased to "SS" - checkProper("aBc/\u00FC\u00C4\u00F6\u00DF\u00FC/ABC", "Abc/\u00DC\u00E4\u00F6\u00DF\u00FC/Abc"); // Some German umlauts with lowercase first letter is changed to uppercase - } - - @Test - public void testMicroBenchmark() { - ValueEval strArg = new StringEval("some longer text that needs a number of replacements to check for runtime of different implementations"); - long start = System.currentTimeMillis(); - for(int i = 0;i < 300000;i++) { - final ValueEval ret = TextFunction.PROPER.evaluate(new ValueEval[]{strArg}, 0, 0); - assertEquals("Some Longer Text That Needs A Number Of Replacements To Check For Runtime Of Different Implementations", ((StringEval)ret).getStringValue()); - } - // Took aprox. 600ms on a decent Laptop in July 2016 - System.out.println("Took: " + (System.currentTimeMillis() - start) + "ms"); - } - - private void checkProper(String input, String expected) { - ValueEval strArg = new StringEval(input); - final ValueEval ret = TextFunction.PROPER.evaluate(new ValueEval[]{strArg}, 0, 0); - assertEquals(expected, ((StringEval)ret).getStringValue()); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/ss/formula/functions/TestSumifsXSSF.java b/src/ooxml/testcases/org/apache/poi/ss/formula/functions/TestSumifsXSSF.java deleted file mode 100644 index c00ca5e56..000000000 --- a/src/ooxml/testcases/org/apache/poi/ss/formula/functions/TestSumifsXSSF.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.Assert.assertEquals; - -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.Test; - -/** - * - */ -public class TestSumifsXSSF { - - /** - * handle null cell predicate - */ - @Test - public void testBug60858() { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("bug60858.xlsx"); - FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); - - Sheet sheet = wb.getSheetAt(0); - Cell cell = sheet.getRow(1).getCell(5); - fe.evaluate(cell); - assertEquals(0.0, cell.getNumericCellValue(), 0.0000000000000001); - } - -} diff --git a/src/ooxml/testcases/org/apache/poi/ss/usermodel/BaseTestXCell.java b/src/ooxml/testcases/org/apache/poi/ss/usermodel/BaseTestXCell.java deleted file mode 100644 index 0a471419c..000000000 --- a/src/ooxml/testcases/org/apache/poi/ss/usermodel/BaseTestXCell.java +++ /dev/null @@ -1,74 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import static org.junit.Assert.assertEquals; - -import java.io.IOException; -import java.util.Calendar; -import java.util.Date; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.xssf.streaming.SXSSFCell; -import org.apache.poi.xssf.usermodel.XSSFCell; -import org.junit.Test; - -/** - * Class for combined testing of XML-specific functionality of - * {@link XSSFCell} and {@link SXSSFCell}. - * - * Any test that is applicable for {@link HSSFCell} as well should go into - * the common base class {@link BaseTestCell}. - */ -public abstract class BaseTestXCell extends BaseTestCell { - protected BaseTestXCell(ITestDataProvider testDataProvider) { - super(testDataProvider); - } - - @Test - public void testXmlEncoding() throws IOException { - Workbook wb1 = _testDataProvider.createWorkbook(); - Sheet sh = wb1.createSheet(); - Row row = sh.createRow(0); - Cell cell = row.createCell(0); - String sval = "\u0000\u0002\u0012<>\t\n\u00a0 &\"POI\'\u2122"; - cell.setCellValue(sval); - - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - wb1.close(); - - // invalid characters are replaced with question marks - assertEquals("???<>\t\n\u00a0 &\"POI\'\u2122", wb2.getSheetAt(0).getRow(0).getCell(0).getStringCellValue()); - wb2.close(); - } - - @Test - public void testSetNullValues() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Cell cell = wb.createSheet("test").createRow(0).createCell(0); - - cell.setCellValue((Calendar)null); - cell.setCellValue((Date)null); - cell.setCellValue((String)null); - cell.setCellValue((RichTextString) null); - cell.setCellValue((String)null); - - wb.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/ss/usermodel/BaseTestXRow.java b/src/ooxml/testcases/org/apache/poi/ss/usermodel/BaseTestXRow.java deleted file mode 100644 index a4b21001e..000000000 --- a/src/ooxml/testcases/org/apache/poi/ss/usermodel/BaseTestXRow.java +++ /dev/null @@ -1,48 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import java.io.IOException; - -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.xssf.streaming.SXSSFRow; -import org.apache.poi.xssf.usermodel.XSSFRow; -import org.junit.Test; - -/** - * Class for combined testing of XML-specific functionality of - * {@link XSSFRow} and {@link SXSSFRow}. - * - * Any test that is applicable for {@link org.apache.poi.hssf.usermodel.HSSFRow} as well should go into - * the common base class {@link BaseTestRow}. - */ -public abstract class BaseTestXRow extends BaseTestRow { - protected BaseTestXRow(ITestDataProvider testDataProvider) { - super(testDataProvider); - } - - @Test - public void testRowBounds() throws IOException { - baseTestRowBounds(_testDataProvider.getSpreadsheetVersion().getLastRowIndex()); - } - - @Test - public void testCellBounds() throws IOException { - baseTestCellBounds(_testDataProvider.getSpreadsheetVersion().getLastColumnIndex()); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/ss/usermodel/BaseTestXSheet.java b/src/ooxml/testcases/org/apache/poi/ss/usermodel/BaseTestXSheet.java deleted file mode 100644 index f6e1bffde..000000000 --- a/src/ooxml/testcases/org/apache/poi/ss/usermodel/BaseTestXSheet.java +++ /dev/null @@ -1,35 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.xssf.streaming.SXSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFSheet; - -/** - * Class for combined testing of XML-specific functionality of - * {@link XSSFSheet} and {@link SXSSFSheet}. - * - * Any test that is applicable for {@link org.apache.poi.hssf.usermodel.HSSFSheet} as well should go into - * the common base class {@link BaseTestSheet}. - */ -public abstract class BaseTestXSheet extends BaseTestSheet { - protected BaseTestXSheet(ITestDataProvider testDataProvider) { - super(testDataProvider); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/ss/usermodel/BaseTestXWorkbook.java b/src/ooxml/testcases/org/apache/poi/ss/usermodel/BaseTestXWorkbook.java deleted file mode 100644 index 9c7fe3a09..000000000 --- a/src/ooxml/testcases/org/apache/poi/ss/usermodel/BaseTestXWorkbook.java +++ /dev/null @@ -1,35 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.xssf.streaming.SXSSFWorkbook; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -/** - * Class for combined testing of XML-specific functionality of - * {@link XSSFWorkbook} and {@link SXSSFWorkbook}. - * - * Any test that is applicable for {@link org.apache.poi.hssf.usermodel.HSSFWorkbook} as well should go into - * the common base class {@link BaseTestWorkbook}. - */ -public abstract class BaseTestXWorkbook extends BaseTestWorkbook { - protected BaseTestXWorkbook(ITestDataProvider testDataProvider) { - super(testDataProvider); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/ss/usermodel/ConditionalFormattingEvalTest.java b/src/ooxml/testcases/org/apache/poi/ss/usermodel/ConditionalFormattingEvalTest.java deleted file mode 100644 index 45be388bf..000000000 --- a/src/ooxml/testcases/org/apache/poi/ss/usermodel/ConditionalFormattingEvalTest.java +++ /dev/null @@ -1,135 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - - -import java.io.IOException; -import java.util.List; - -import org.apache.poi.ss.formula.ConditionalFormattingEvaluator; -import org.apache.poi.ss.formula.EvaluationConditionalFormatRule; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.usermodel.XSSFColor; -import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.*; - -public class ConditionalFormattingEvalTest { - - private XSSFWorkbook wb; - private Sheet sheet; - private XSSFFormulaEvaluator formulaEval; - private ConditionalFormattingEvaluator cfe; - private CellReference ref; - private List rules; - - @Before - public void openWB() { - wb = XSSFTestDataSamples.openSampleWorkbook("ConditionalFormattingSamples.xlsx"); - formulaEval = new XSSFFormulaEvaluator(wb); - cfe = new ConditionalFormattingEvaluator(wb, formulaEval); - } - - @After - public void closeWB() { - formulaEval = null; - cfe = null; - ref = null; - rules = null; - try { - if (wb != null) wb.close(); - } catch (IOException e) { - // keep going, this shouldn't cancel things - e.printStackTrace(); - } - } - - @Test - public void testFormattingEvaluation() { - sheet = wb.getSheet("Products1"); - - getRulesFor(12, 1); - assertEquals("wrong # of rules for " + ref, 1, rules.size()); - assertEquals("wrong bg color for " + ref, "FFFFEB9C", getColor(rules.get(0).getRule().getPatternFormatting().getFillBackgroundColorColor())); - assertFalse("should not be italic " + ref, rules.get(0).getRule().getFontFormatting().isItalic()); - - getRulesFor(16, 3); - assertEquals("wrong # of rules for " + ref, 1, rules.size()); - assertEquals("wrong bg color for " + ref, 0.7999816888943144d, getTint(rules.get(0).getRule().getPatternFormatting().getFillBackgroundColorColor()), 0.000000000000001); - - getRulesFor(12, 3); - assertEquals("wrong # of rules for " + ref, 0, rules.size()); - - sheet = wb.getSheet("Products2"); - - getRulesFor(15,1); - assertEquals("wrong # of rules for " + ref, 1, rules.size()); - assertEquals("wrong bg color for " + ref, "FFFFEB9C", getColor(rules.get(0).getRule().getPatternFormatting().getFillBackgroundColorColor())); - - getRulesFor(20,3); - assertEquals("wrong # of rules for " + ref, 0, rules.size()); - - // now change a cell value that's an input for the rules - Cell cell = sheet.getRow(1).getCell(6); - cell.setCellValue("Dairy"); - formulaEval.notifyUpdateCell(cell); - cell = sheet.getRow(4).getCell(6); - cell.setCellValue(500); - formulaEval.notifyUpdateCell(cell); - // need to throw away all evaluations, since we don't know how value changes may have affected format formulas - cfe.clearAllCachedValues(); - - // test that the conditional validation evaluations changed - getRulesFor(15,1); - assertEquals("wrong # of rules for " + ref, 0, rules.size()); - - getRulesFor(20,3); - assertEquals("wrong # of rules for " + ref, 1, rules.size()); - assertEquals("wrong bg color for " + ref, 0.7999816888943144d, getTint(rules.get(0).getRule().getPatternFormatting().getFillBackgroundColorColor()), 0.000000000000001); - - getRulesFor(20,1); - assertEquals("wrong # of rules for " + ref, 1, rules.size()); - assertEquals("wrong bg color for " + ref, "FFFFEB9C", getColor(rules.get(0).getRule().getPatternFormatting().getFillBackgroundColorColor())); - - sheet = wb.getSheet("Book tour"); - - getRulesFor(8,2); - assertEquals("wrong # of rules for " + ref, 1, rules.size()); - - } - - private List getRulesFor(int row, int col) { - ref = new CellReference(sheet.getSheetName(), row, col, false, false); - return rules = cfe.getConditionalFormattingForCell(ref); - } - - private String getColor(Color color) { - final XSSFColor c = XSSFColor.toXSSFColor(color); - return c.getARGBHex(); - } - - private double getTint(Color color) { - final XSSFColor c = XSSFColor.toXSSFColor(color); - return c.getTint(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/ss/usermodel/TestEmbedOLEPackage.java b/src/ooxml/testcases/org/apache/poi/ss/usermodel/TestEmbedOLEPackage.java deleted file mode 100644 index b17d5d32d..000000000 --- a/src/ooxml/testcases/org/apache/poi/ss/usermodel/TestEmbedOLEPackage.java +++ /dev/null @@ -1,117 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assume.assumeTrue; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.sl.usermodel.AutoShape; -import org.apache.poi.sl.usermodel.ShapeType; -import org.apache.poi.sl.usermodel.Slide; -import org.apache.poi.sl.usermodel.SlideShow; -import org.apache.poi.ss.extractor.EmbeddedData; -import org.apache.poi.ss.extractor.EmbeddedExtractor; -import org.apache.poi.xslf.usermodel.XMLSlideShow; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Test; - -public class TestEmbedOLEPackage { - @Test - public void embedXSSF() throws IOException { - Workbook wb1 = new XSSFWorkbook(); - Sheet sh = wb1.createSheet(); - int picIdx = wb1.addPicture(getSamplePng(), Workbook.PICTURE_TYPE_PNG); - byte samplePPTX[] = getSamplePPT(true); - int oleIdx = wb1.addOlePackage(samplePPTX, "dummy.pptx", "dummy.pptx", "dummy.pptx"); - - Drawing pat = sh.createDrawingPatriarch(); - ClientAnchor anchor = pat.createAnchor(0, 0, 0, 0, 1, 1, 3, 6); - pat.createObjectData(anchor, oleIdx, picIdx); - - Workbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - - pat = wb2.getSheetAt(0).getDrawingPatriarch(); - assertTrue(pat.iterator().next() instanceof ObjectData); - - EmbeddedExtractor ee = new EmbeddedExtractor(); - EmbeddedData ed = ee.extractAll(wb2.getSheetAt(0)).get(0); - assertArrayEquals(samplePPTX, ed.getEmbeddedData()); - - wb2.close(); - wb1.close(); - } - - @Test - public void embedHSSF() throws IOException { - try { - Class.forName("org.apache.poi.hslf.usermodel.HSLFSlideShow"); - } catch (Exception e) { - assumeTrue(false); - } - - Workbook wb1 = new HSSFWorkbook(); - Sheet sh = wb1.createSheet(); - int picIdx = wb1.addPicture(getSamplePng(), Workbook.PICTURE_TYPE_PNG); - byte samplePPT[] = getSamplePPT(false); - int oleIdx = wb1.addOlePackage(samplePPT, "dummy.ppt", "dummy.ppt", "dummy.ppt"); - - Drawing pat = sh.createDrawingPatriarch(); - ClientAnchor anchor = pat.createAnchor(0, 0, 0, 0, 1, 1, 3, 6); - pat.createObjectData(anchor, oleIdx, picIdx); - - Workbook wb2 = HSSFTestDataSamples.writeOutAndReadBack((HSSFWorkbook)wb1); - - pat = wb2.getSheetAt(0).getDrawingPatriarch(); - assertTrue(pat.iterator().next() instanceof ObjectData); - - EmbeddedExtractor ee = new EmbeddedExtractor(); - EmbeddedData ed = ee.extractAll(wb2.getSheetAt(0)).get(0); - assertArrayEquals(samplePPT, ed.getEmbeddedData()); - - wb2.close(); - wb1.close(); - } - - static byte[] getSamplePng() { - return POIDataSamples.getSpreadSheetInstance().readFile("logoKarmokar4.png"); - } - - static byte[] getSamplePPT(boolean ooxml) throws IOException { - SlideShow ppt = (ooxml) ? new XMLSlideShow() : new org.apache.poi.hslf.usermodel.HSLFSlideShow(); - Slide slide = ppt.createSlide(); - - AutoShape sh1 = slide.createAutoShape(); - sh1.setShapeType(ShapeType.STAR_32); - sh1.setAnchor(new java.awt.Rectangle(50, 50, 100, 200)); - sh1.setFillColor(java.awt.Color.red); - - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - ppt.write(bos); - ppt.close(); - - return bos.toByteArray(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/ss/usermodel/TestXSSFBorderStyle.java b/src/ooxml/testcases/org/apache/poi/ss/usermodel/TestXSSFBorderStyle.java deleted file mode 100644 index 2e9334b1a..000000000 --- a/src/ooxml/testcases/org/apache/poi/ss/usermodel/TestXSSFBorderStyle.java +++ /dev/null @@ -1,30 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import org.apache.poi.xssf.XSSFITestDataProvider; - -/** - * @author Yegor Kozlov - */ -public final class TestXSSFBorderStyle extends BaseTestBorderStyle { - - public TestXSSFBorderStyle() { - super(XSSFITestDataProvider.instance); - } -} \ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/ss/util/TestSXSSFCellUtil.java b/src/ooxml/testcases/org/apache/poi/ss/util/TestSXSSFCellUtil.java deleted file mode 100644 index 70c5fae44..000000000 --- a/src/ooxml/testcases/org/apache/poi/ss/util/TestSXSSFCellUtil.java +++ /dev/null @@ -1,26 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - ==================================================================== */ - -package org.apache.poi.ss.util; - -import org.apache.poi.xssf.SXSSFITestDataProvider; - -public class TestSXSSFCellUtil extends BaseTestCellUtil { - public TestSXSSFCellUtil() { - super(SXSSFITestDataProvider.instance); - } -} \ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/ss/util/TestXSSFCellUtil.java b/src/ooxml/testcases/org/apache/poi/ss/util/TestXSSFCellUtil.java deleted file mode 100644 index c58ebe90d..000000000 --- a/src/ooxml/testcases/org/apache/poi/ss/util/TestXSSFCellUtil.java +++ /dev/null @@ -1,26 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - ==================================================================== */ - -package org.apache.poi.ss.util; - -import org.apache.poi.xssf.XSSFITestDataProvider; - -public class TestXSSFCellUtil extends BaseTestCellUtil { - public TestXSSFCellUtil() { - super(XSSFITestDataProvider.instance); - } -} \ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/ss/util/TestXSSFPropertyTemplate.java b/src/ooxml/testcases/org/apache/poi/ss/util/TestXSSFPropertyTemplate.java deleted file mode 100644 index 1c4b7adc3..000000000 --- a/src/ooxml/testcases/org/apache/poi/ss/util/TestXSSFPropertyTemplate.java +++ /dev/null @@ -1,136 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.util; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotSame; - -import java.io.IOException; - -import org.apache.poi.ss.usermodel.BorderExtent; -import org.apache.poi.ss.usermodel.BorderStyle; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.IndexedColors; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Test; - -public class TestXSSFPropertyTemplate { - - @Test - public void applyBorders() throws IOException { - CellRangeAddress a1c3 = new CellRangeAddress(0, 2, 0, 2); - CellRangeAddress b2 = new CellRangeAddress(1, 1, 1, 1); - PropertyTemplate pt = new PropertyTemplate(); - Workbook wb = new XSSFWorkbook(); - Sheet sheet = wb.createSheet(); - - pt.drawBorders(a1c3, BorderStyle.THIN, IndexedColors.RED.getIndex(), BorderExtent.ALL); - pt.applyBorders(sheet); - - for (Row row: sheet) { - for (Cell cell: row) { - CellStyle cs = cell.getCellStyle(); - assertEquals(BorderStyle.THIN, cs.getBorderTopEnum()); - assertEquals(IndexedColors.RED.getIndex(), cs.getTopBorderColor()); - assertEquals(BorderStyle.THIN, cs.getBorderBottomEnum()); - assertEquals(IndexedColors.RED.getIndex(), cs.getBottomBorderColor()); - assertEquals(BorderStyle.THIN, cs.getBorderLeftEnum()); - assertEquals(IndexedColors.RED.getIndex(), cs.getLeftBorderColor()); - assertEquals(BorderStyle.THIN, cs.getBorderRightEnum()); - assertEquals(IndexedColors.RED.getIndex(), cs.getRightBorderColor()); - } - } - - pt.drawBorders(b2, BorderStyle.NONE, BorderExtent.ALL); - pt.applyBorders(sheet); - - for (Row row: sheet) { - for (Cell cell: row) { - CellStyle cs = cell.getCellStyle(); - if (cell.getColumnIndex() != 1 || row.getRowNum() == 0) { - assertEquals(BorderStyle.THIN, cs.getBorderTopEnum()); - assertEquals(IndexedColors.RED.getIndex(), cs.getTopBorderColor()); - } else { - assertEquals(BorderStyle.NONE, cs.getBorderTopEnum()); - } - if (cell.getColumnIndex() != 1 || row.getRowNum() == 2) { - assertEquals(BorderStyle.THIN, cs.getBorderBottomEnum()); - assertEquals(IndexedColors.RED.getIndex(), cs.getBottomBorderColor()); - } else { - assertEquals(BorderStyle.NONE, cs.getBorderBottomEnum()); - } - if (cell.getColumnIndex() == 0 || row.getRowNum() != 1) { - assertEquals(BorderStyle.THIN, cs.getBorderLeftEnum()); - assertEquals(IndexedColors.RED.getIndex(), cs.getLeftBorderColor()); - } else { - assertEquals(BorderStyle.NONE, cs.getBorderLeftEnum()); - } - if (cell.getColumnIndex() == 2 || row.getRowNum() != 1) { - assertEquals(BorderStyle.THIN, cs.getBorderRightEnum()); - assertEquals(IndexedColors.RED.getIndex(), cs.getRightBorderColor()); - } else { - assertEquals(BorderStyle.NONE, cs.getBorderRightEnum()); - } - } - } - - wb.close(); - } - - @Test - public void clonePropertyTemplate() throws IOException { - CellRangeAddress a1c3 = new CellRangeAddress(0, 2, 0, 2); - PropertyTemplate pt = new PropertyTemplate(); - pt.drawBorders(a1c3, BorderStyle.MEDIUM, IndexedColors.RED.getIndex(), BorderExtent.ALL); - PropertyTemplate pt2 = new PropertyTemplate(pt); - assertNotSame(pt2, pt); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - assertEquals(4, pt2.getNumBorderColors(i, j)); - assertEquals(4, pt2.getNumBorderColors(i, j)); - } - } - - CellRangeAddress b2 = new CellRangeAddress(1,1,1,1); - pt2.drawBorders(b2, BorderStyle.THIN, BorderExtent.ALL); - - Workbook wb = new XSSFWorkbook(); - Sheet sheet = wb.createSheet(); - pt.applyBorders(sheet); - - for (Row row : sheet) { - for (Cell cell : row) { - CellStyle cs = cell.getCellStyle(); - assertEquals(BorderStyle.MEDIUM, cs.getBorderTopEnum()); - assertEquals(BorderStyle.MEDIUM, cs.getBorderBottomEnum()); - assertEquals(BorderStyle.MEDIUM, cs.getBorderLeftEnum()); - assertEquals(BorderStyle.MEDIUM, cs.getBorderRightEnum()); - assertEquals(IndexedColors.RED.getIndex(), cs.getTopBorderColor()); - assertEquals(IndexedColors.RED.getIndex(), cs.getBottomBorderColor()); - assertEquals(IndexedColors.RED.getIndex(), cs.getLeftBorderColor()); - assertEquals(IndexedColors.RED.getIndex(), cs.getRightBorderColor()); - } - } - - wb.close(); - } -} \ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/util/TestIdentifierManager.java b/src/ooxml/testcases/org/apache/poi/util/TestIdentifierManager.java deleted file mode 100644 index 383545176..000000000 --- a/src/ooxml/testcases/org/apache/poi/util/TestIdentifierManager.java +++ /dev/null @@ -1,129 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.util; - -import junit.framework.TestCase; - -public class TestIdentifierManager extends TestCase -{ - public void testBasic() - { - IdentifierManager manager = new IdentifierManager(0L,100L); - assertEquals(101L,manager.getRemainingIdentifiers()); - assertEquals(0L,manager.reserveNew()); - assertEquals(100L,manager.getRemainingIdentifiers()); - assertEquals(1L,manager.reserve(0L)); - assertEquals(99L,manager.getRemainingIdentifiers()); - } - - public void testLongLimits() - { - long min = IdentifierManager.MIN_ID; - long max = IdentifierManager.MAX_ID; - IdentifierManager manager = new IdentifierManager(min,max); - assertTrue("Limits lead to a long variable overflow", max - min + 1 > 0); - assertTrue("Limits lead to a long variable overflow", manager.getRemainingIdentifiers() > 0); - assertEquals(min,manager.reserveNew()); - assertEquals(max,manager.reserve(max)); - assertEquals(max - min -1, manager.getRemainingIdentifiers()); - manager.release(max); - manager.release(min); - } - - public void testReserve() - { - IdentifierManager manager = new IdentifierManager(10L,30L); - assertEquals(12L,manager.reserve(12L)); - long reserve = manager.reserve(12L); - assertFalse("Same id must be reserved twice!",reserve == 12L); - assertTrue(manager.release(12L)); - assertTrue(manager.release(reserve)); - assertFalse(manager.release(12L)); - assertFalse(manager.release(reserve)); - - manager = new IdentifierManager(0L,2L); - assertEquals(0L,manager.reserve(0L)); - assertEquals(1L,manager.reserve(1L)); - assertEquals(2L,manager.reserve(2L)); - try - { - manager.reserve(0L); - fail("Exception expected"); - } - catch(IllegalStateException e) - { - // expected - } - try - { - manager.reserve(1L); - fail("Exception expected"); - } - catch(IllegalStateException e) - { - // expected - } - try - { - manager.reserve(2L); - fail("Exception expected"); - } - catch(IllegalStateException e) - { - // expected - } - } - - public void testReserveNew() - { - IdentifierManager manager = new IdentifierManager(10L,12L); - assertSame(10L,manager.reserveNew()); - assertSame(11L,manager.reserveNew()); - assertSame(12L,manager.reserveNew()); - try { - manager.reserveNew(); - fail("IllegalStateException expected"); - } - catch (IllegalStateException e) - { - // expected - } - } - - public void testRelease() { - IdentifierManager manager = new IdentifierManager(10L,20L); - assertEquals(10L,manager.reserve(10L)); - assertEquals(11L,manager.reserve(11L)); - assertEquals(12L,manager.reserve(12L)); - assertEquals(13L,manager.reserve(13L)); - assertEquals(14L,manager.reserve(14L)); - - assertTrue(manager.release(10L)); - assertEquals(10L,manager.reserve(10L)); - assertTrue(manager.release(10L)); - - assertTrue(manager.release(11L)); - assertEquals(11L,manager.reserve(11L)); - assertTrue(manager.release(11L)); - assertFalse(manager.release(11L)); - assertFalse(manager.release(10L)); - - assertEquals(10L,manager.reserve(10L)); - assertEquals(11L,manager.reserve(11L)); - assertTrue(manager.release(12L)); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/util/TestSAXHelper.java b/src/ooxml/testcases/org/apache/poi/util/TestSAXHelper.java deleted file mode 100644 index 6d3c038b4..000000000 --- a/src/ooxml/testcases/org/apache/poi/util/TestSAXHelper.java +++ /dev/null @@ -1,40 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.util; - -import javax.xml.XMLConstants; - -import org.junit.Test; -import org.xml.sax.InputSource; -import org.xml.sax.XMLReader; - -import java.io.ByteArrayInputStream; - -import static org.junit.Assert.*; - -public class TestSAXHelper { - @Test - public void testXMLReader() throws Exception { - XMLReader reader = SAXHelper.newXMLReader(); - assertNotSame(reader, SAXHelper.newXMLReader()); - assertTrue(reader.getFeature(XMLConstants.FEATURE_SECURE_PROCESSING)); - assertEquals(SAXHelper.IGNORING_ENTITY_RESOLVER, reader.getEntityResolver()); - assertNotNull(reader.getProperty("http://apache.org/xml/properties/security-manager")); - - reader.parse(new InputSource(new ByteArrayInputStream("".getBytes("UTF-8")))); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xdgf/extractor/TestXDGFVisioExtractor.java b/src/ooxml/testcases/org/apache/poi/xdgf/extractor/TestXDGFVisioExtractor.java deleted file mode 100644 index 0be1814b2..000000000 --- a/src/ooxml/testcases/org/apache/poi/xdgf/extractor/TestXDGFVisioExtractor.java +++ /dev/null @@ -1,78 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xdgf.extractor; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.xdgf.usermodel.XmlVisioDocument; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class TestXDGFVisioExtractor { - - private static final POIDataSamples SAMPLES = POIDataSamples.getDiagramInstance(); - private OPCPackage pkg; - private XmlVisioDocument xml; - - @Before - public void setUp() throws Exception { - pkg = OPCPackage.open(SAMPLES.openResourceAsStream("test_text_extraction.vsdx")); - xml = new XmlVisioDocument(pkg); - } - - @After - public void closeResoures() throws IOException { - xml.close(); - pkg.close(); - } - - @Test - public void testGetSimpleText() throws IOException { - new XDGFVisioExtractor(xml).close(); - new XDGFVisioExtractor(pkg).close(); - - XDGFVisioExtractor extractor = new XDGFVisioExtractor(xml); - extractor.getText(); - - String text = extractor.getText(); - String expected = "Text here\nText there\nText, text, everywhere!\nRouter here\n"; - assertEquals(expected, text); - - extractor.close(); - } - - - //the point of this is to trigger the addition of - //some common visio classes -- ConnectsType - @Test - public void testVisioConnects() throws IOException { - InputStream is = SAMPLES.openResourceAsStream("60489.vsdx"); - XmlVisioDocument document = new XmlVisioDocument(is); - is.close(); - XDGFVisioExtractor extractor = new XDGFVisioExtractor(document); - String text = extractor.getText(); - assertTrue(text.indexOf("Arrears") > -1); - extractor.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xdgf/usermodel/section/CombinedIteratorTest.java b/src/ooxml/testcases/org/apache/poi/xdgf/usermodel/section/CombinedIteratorTest.java deleted file mode 100644 index 447684ca9..000000000 --- a/src/ooxml/testcases/org/apache/poi/xdgf/usermodel/section/CombinedIteratorTest.java +++ /dev/null @@ -1,157 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xdgf.usermodel.section; - -import java.util.Iterator; -import java.util.SortedMap; -import java.util.TreeMap; - -import org.junit.Assert; -import org.junit.Test; - -public class CombinedIteratorTest { - - void testIteration(CombinedIterable iterable, String... expected) { - - Iterator iter = iterable.iterator(); - - for (String element : expected) { - Assert.assertEquals(true, iter.hasNext()); - Assert.assertEquals(element, iter.next()); - } - - Assert.assertEquals(false, iter.hasNext()); - } - - @Test - public void testNullMaster() { - - SortedMap base = new TreeMap(); - base.put(1L, "B1"); - base.put(2L, "B2"); - base.put(3L, "B3"); - - testIteration(new CombinedIterable(base, null), "B1", "B2", - "B3"); - } - - @Test - public void testNoMatchesBaseFirst() { - - SortedMap base = new TreeMap(); - base.put(1L, "B1"); - base.put(2L, "B2"); - base.put(3L, "B3"); - - SortedMap master = new TreeMap(); - master.put(4L, "M4"); - master.put(5L, "M5"); - master.put(6L, "M6"); - - testIteration(new CombinedIterable(base, master), "B1", "B2", - "B3", "M4", "M5", "M6"); - } - - @Test - public void testNoMatchesMasterFirst() { - - SortedMap base = new TreeMap(); - base.put(4L, "B4"); - base.put(5L, "B5"); - base.put(6L, "B6"); - - SortedMap master = new TreeMap(); - master.put(1L, "M1"); - master.put(2L, "M2"); - master.put(3L, "M3"); - - testIteration(new CombinedIterable(base, master), "M1", "M2", - "M3", "B4", "B5", "B6"); - } - - @Test - public void testInterleaved1() { - - SortedMap base = new TreeMap(); - base.put(1L, "B1"); - base.put(3L, "B3"); - base.put(5L, "B5"); - - SortedMap master = new TreeMap(); - master.put(2L, "M2"); - master.put(4L, "M4"); - master.put(6L, "M6"); - - testIteration(new CombinedIterable(base, master), "B1", "M2", - "B3", "M4", "B5", "M6"); - } - - @Test - public void testInterleaved2() { - - SortedMap base = new TreeMap(); - base.put(1L, "B1"); - base.put(2L, "B2"); - base.put(5L, "B5"); - base.put(6L, "B6"); - - SortedMap master = new TreeMap(); - master.put(3L, "M3"); - master.put(4L, "M4"); - master.put(7L, "M7"); - master.put(8L, "M8"); - - testIteration(new CombinedIterable(base, master), "B1", "B2", - "M3", "M4", "B5", "B6", "M7", "M8"); - } - - @Test - public void testAllMatching() { - - SortedMap base = new TreeMap(); - base.put(1L, "B1"); - base.put(2L, "B2"); - base.put(3L, "B3"); - - SortedMap master = new TreeMap(); - master.put(1L, "M1"); - master.put(2L, "M2"); - master.put(3L, "M3"); - - testIteration(new CombinedIterable(base, master), "B1", "B2", - "B3"); - } - - @Test - public void testAllMatching2() { - - SortedMap base = new TreeMap(); - base.put(1L, "B1"); - base.put(2L, "B2"); - base.put(3L, "B3"); - - SortedMap master = new TreeMap(); - master.put(1L, "M1"); - master.put(2L, "M2"); - master.put(3L, "M3"); - master.put(4L, "M4"); - - testIteration(new CombinedIterable(base, master), "B1", "B2", - "B3", "M4"); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xslf/TestXSLFBugs.java b/src/ooxml/testcases/org/apache/poi/xslf/TestXSLFBugs.java deleted file mode 100644 index 65939eec4..000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/TestXSLFBugs.java +++ /dev/null @@ -1,634 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.POIXMLDocumentPart.RelationPart; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.sl.draw.DrawPaint; -import org.apache.poi.sl.usermodel.PaintStyle; -import org.apache.poi.sl.usermodel.PaintStyle.SolidPaint; -import org.apache.poi.sl.usermodel.PaintStyle.TexturePaint; -import org.apache.poi.sl.usermodel.PictureData; -import org.apache.poi.sl.usermodel.PictureData.PictureType; -import org.apache.poi.sl.usermodel.ShapeType; -import org.apache.poi.sl.usermodel.VerticalAlignment; -import org.apache.poi.xslf.extractor.XSLFPowerPointExtractor; -import org.apache.poi.xslf.usermodel.*; -import org.junit.Ignore; -import org.junit.Test; -import org.openxmlformats.schemas.drawingml.x2006.main.CTOuterShadowEffect; -import org.openxmlformats.schemas.presentationml.x2006.main.CTShape; - -import javax.imageio.ImageIO; -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Graphics2D; -import java.awt.RenderingHints; -import java.awt.geom.AffineTransform; -import java.awt.geom.Rectangle2D; -import java.awt.image.BufferedImage; -import java.io.File; -import java.io.IOException; -import java.net.URI; -import java.util.Collection; - -import static org.apache.poi.POITestCase.assertContains; -import static org.junit.Assert.*; - - -public class TestXSLFBugs { - private static final POIDataSamples slTests = POIDataSamples.getSlideShowInstance(); - - @Test - public void bug51187() throws Exception { - XMLSlideShow ss1 = XSLFTestDataSamples.openSampleDocument("51187.pptx"); - - assertEquals(1, ss1.getSlides().size()); - - // Check the relations on it - // Note - rId3 is a self reference - XSLFSlide slide0 = ss1.getSlides().get(0); - - assertRelation(slide0, "/ppt/slides/slide1.xml", null); - assertRelation(slide0, "/ppt/slideLayouts/slideLayout12.xml", "rId1"); - assertRelation(slide0, "/ppt/notesSlides/notesSlide1.xml", "rId2"); - assertRelation(slide0, "/ppt/slides/slide1.xml", "rId3"); - assertRelation(slide0, "/ppt/media/image1.png", "rId4"); - - // Save and re-load - XMLSlideShow ss2 = XSLFTestDataSamples.writeOutAndReadBack(ss1); - ss1.close(); - assertEquals(1, ss2.getSlides().size()); - - slide0 = ss2.getSlides().get(0); - assertRelation(slide0, "/ppt/slides/slide1.xml", null); - assertRelation(slide0, "/ppt/slideLayouts/slideLayout12.xml", "rId1"); - assertRelation(slide0, "/ppt/notesSlides/notesSlide1.xml", "rId2"); - // TODO Fix this - assertRelation(slide0, "/ppt/slides/slide1.xml", "rId3"); - assertRelation(slide0, "/ppt/media/image1.png", "rId4"); - - ss2.close(); - } - - private static void assertRelation(XSLFSlide slide, String exp, String rId) { - POIXMLDocumentPart pd = (rId != null) ? slide.getRelationById(rId) : slide; - assertNotNull(pd); - assertEquals(exp, pd.getPackagePart().getPartName().getName()); - } - - /** - * Slide relations with anchors in them - */ - @Test - public void tika705() throws Exception { - XMLSlideShow ss = XSLFTestDataSamples.openSampleDocument("with_japanese.pptx"); - - // Should have one slide - assertEquals(1, ss.getSlides().size()); - XSLFSlide slide = ss.getSlides().get(0); - - // Check the relations from this - Collection rels = slide.getRelationParts(); - - // Should have 6 relations: - // 1 external hyperlink (skipped from list) - // 4 internal hyperlinks - // 1 slide layout - assertEquals(5, rels.size()); - int layouts = 0; - int hyperlinks = 0; - for(RelationPart p : rels) { - if(p.getRelationship().getRelationshipType().equals(XSLFRelation.HYPERLINK.getRelation())) { - hyperlinks++; - } else if(p.getDocumentPart() instanceof XSLFSlideLayout) { - layouts++; - } - } - assertEquals(1, layouts); - assertEquals(4, hyperlinks); - - // Hyperlinks should all be to #_ftn1 or #ftnref1 - for(RelationPart p : rels) { - if(p.getRelationship().getRelationshipType().equals(XSLFRelation.HYPERLINK.getRelation())) { - URI target = p.getRelationship().getTargetURI(); - - //noinspection StatementWithEmptyBody - if(target.getFragment().equals("_ftn1") || - target.getFragment().equals("_ftnref1")) { - // Good - } else { - fail("Invalid target " + target.getFragment() + " on " + target); - } - } - } - ss.close(); - } - - /** - * A slideshow can have more than one rID pointing to a given - * slide, eg presentation.xml rID1 -> slide1.xml, but slide1.xml - * rID2 -> slide3.xml - */ - @Test - public void bug54916() throws Exception { - XMLSlideShow ss = XSLFTestDataSamples.openSampleDocument("OverlappingRelations.pptx"); - XSLFSlide slide; - - // Should find 4 slides - assertEquals(4, ss.getSlides().size()); - - // Check the text, to see we got them in order - slide = ss.getSlides().get(0); - assertContains(getSlideText(slide), "POI cannot read this"); - - slide = ss.getSlides().get(1); - assertContains(getSlideText(slide), "POI can read this"); - assertContains(getSlideText(slide), "Has a relationship to another slide"); - - slide = ss.getSlides().get(2); - assertContains(getSlideText(slide), "POI can read this"); - - slide = ss.getSlides().get(3); - assertContains(getSlideText(slide), "POI can read this"); - - ss.close(); - } - - /** - * When the picture is not embedded but inserted only as a "link to file", - * there is no data available and XSLFPictureShape.getPictureData() - * gives a NPE, see bug #56812 - */ - @Test - public void bug56812() throws Exception { - XMLSlideShow ppt = XSLFTestDataSamples.openSampleDocument("56812.pptx"); - - int internalPictures = 0; - int externalPictures = 0; - for (XSLFSlide slide : ppt.getSlides()){ - for (XSLFShape shape : slide.getShapes()){ - assertNotNull(shape); - - if (shape instanceof XSLFPictureShape) { - XSLFPictureShape picture = (XSLFPictureShape)shape; - if (picture.isExternalLinkedPicture()) { - externalPictures++; - - assertNotNull(picture.getPictureLink()); - } else { - internalPictures++; - - XSLFPictureData data = picture.getPictureData(); - assertNotNull(data); - assertNotNull(data.getFileName()); - } - } - } - } - - assertEquals(2, internalPictures); - assertEquals(1, externalPictures); - ppt.close(); - } - - @Test - @Ignore("Similar to TestFontRendering it doesn't make sense to compare images because of tiny rendering differences in windows/unix") - public void bug54542() throws Exception { - XMLSlideShow ss = XSLFTestDataSamples.openSampleDocument("54542_cropped_bitmap.pptx"); - - Dimension pgsize = ss.getPageSize(); - - XSLFSlide slide = ss.getSlides().get(0); - - // render it - double zoom = 1; - AffineTransform at = new AffineTransform(); - at.setToScale(zoom, zoom); - - BufferedImage imgActual = new BufferedImage((int)Math.ceil(pgsize.width*zoom), (int)Math.ceil(pgsize.height*zoom), BufferedImage.TYPE_3BYTE_BGR); - Graphics2D graphics = imgActual.createGraphics(); - graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); - graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); - graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); - graphics.setTransform(at); - graphics.setPaint(Color.white); - graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height)); - slide.draw(graphics); - - ImageIO.write(imgActual, "PNG", new File("bug54542.png")); - ss.close(); - } - - protected String getSlideText(XSLFSlide slide) { - return XSLFPowerPointExtractor.getText(slide, true, false, false); - } - - @Test - public void bug57250() throws Exception { - XMLSlideShow ss = new XMLSlideShow(); - for (String s : new String[]{"Slide1","Slide2"}) { - ss.createSlide().createTextBox().setText(s); - } - validateSlides(ss, false, "Slide1","Slide2"); - - XSLFSlide slide = ss.createSlide(); - slide.createTextBox().setText("New slide"); - validateSlides(ss, true, "Slide1","Slide2","New slide"); - - // Move backward - ss.setSlideOrder(slide, 0); - validateSlides(ss, true, "New slide","Slide1","Slide2"); - - // Move forward - ss.setSlideOrder(slide, 1); - validateSlides(ss, true, "Slide1","New slide","Slide2"); - - // Move to end - ss.setSlideOrder(slide, 0); - ss.setSlideOrder(slide, 2); - validateSlides(ss, true, "Slide1","Slide2","New slide"); - ss.close(); - } - - /** - * When working with >9 images, make sure the sorting ensures - * that image10.foo isn't between image1.foo and image2.foo - */ - @Test - public void test57552() throws Exception { - XMLSlideShow ss = new XMLSlideShow(); - for (String s : new String[]{"Slide1","Slide2"}) { - ss.createSlide().createTextBox().setText(s); - } - - // Slide starts with just layout relation - XSLFSlide slide = ss.getSlides().get(0); - assertEquals(0, ss.getPictureData().size()); - assertEquals(1, slide.getShapes().size()); - - assertEquals(1, slide.getRelations().size()); - assertRelationEquals(XSLFRelation.SLIDE_LAYOUT, slide.getRelations().get(0)); - - // Some dummy pictures - byte[][] pics = new byte[15][3]; - for (int i=0; i 1); - ppt.removeSlide(1); - assertNotNull(ppt.createSlide()); - } - - @Test - public void blibFillAlternateContent() throws IOException { - XMLSlideShow ppt = XSLFTestDataSamples.openSampleDocument("2411-Performance_Up.pptx"); - XSLFPictureShape ps = (XSLFPictureShape)ppt.getSlides().get(4).getShapes().get(0); - assertNotNull(ps.getPictureData()); - ppt.close(); - } - - @Test - public void bug59434() throws IOException { - String url1 = "http://poi.apache.org/changes.html"; - String url2 = "http://poi.apache.org/faq.html"; - XMLSlideShow ppt1 = new XMLSlideShow(); - PictureData pd1 = ppt1.addPicture(slTests.readFile("tomcat.png"), PictureType.PNG); - PictureData pd2 = ppt1.addPicture(slTests.readFile("santa.wmf"), PictureType.WMF); - XSLFSlide slide = ppt1.createSlide(); - XSLFPictureShape ps1 = slide.createPicture(pd1); - ps1.setAnchor(new Rectangle2D.Double(20, 20, 100, 100)); - XSLFHyperlink hl1 = ps1.createHyperlink(); - hl1.linkToUrl(url1); - XSLFPictureShape ps2 = slide.createPicture(pd2); - ps2.setAnchor(new Rectangle2D.Double(120, 120, 100, 100)); - XSLFHyperlink hl2 = ps2.createHyperlink(); - hl2.linkToUrl(url2); - XMLSlideShow ppt2 = XSLFTestDataSamples.writeOutAndReadBack(ppt1); - ppt1.close(); - slide = ppt2.getSlides().get(0); - ps1 = (XSLFPictureShape)slide.getShapes().get(0); - ps2 = (XSLFPictureShape)slide.getShapes().get(1); - assertEquals(url1, ps1.getHyperlink().getAddress()); - assertEquals(url2, ps2.getHyperlink().getAddress()); - - ppt2.close(); - } - - @Test - public void bug58217() throws IOException { - Color fillColor = new Color(1f,1f,0f,0.1f); - Color lineColor = new Color(25.3f/255f,1f,0f,0.4f); - Color textColor = new Color(1f,1f,0f,0.6f); - - XMLSlideShow ppt1 = new XMLSlideShow(); - XSLFSlide sl = ppt1.createSlide(); - XSLFAutoShape as = sl.createAutoShape(); - as.setShapeType(ShapeType.STAR_10); - as.setAnchor(new Rectangle2D.Double(100,100,300,300)); - as.setFillColor(fillColor); - as.setLineColor(lineColor); - as.setText("Alpha"); - as.setVerticalAlignment(VerticalAlignment.MIDDLE); - as.setHorizontalCentered(true); - XSLFTextRun tr = as.getTextParagraphs().get(0).getTextRuns().get(0); - tr.setFontSize(32d); - tr.setFontColor(textColor); - XMLSlideShow ppt2 = XSLFTestDataSamples.writeOutAndReadBack(ppt1); - ppt1.close(); - sl = ppt2.getSlides().get(0); - as = (XSLFAutoShape)sl.getShapes().get(0); - checkColor(fillColor, as.getFillStyle().getPaint()); - checkColor(lineColor, as.getStrokeStyle().getPaint()); - checkColor(textColor, as.getTextParagraphs().get(0).getTextRuns().get(0).getFontColor()); - ppt2.close(); - } - - private static void checkColor(Color expected, PaintStyle actualStyle) { - assertTrue(actualStyle instanceof SolidPaint); - SolidPaint ps = (SolidPaint)actualStyle; - Color actual = DrawPaint.applyColorTransform(ps.getSolidColor()); - float expRGB[] = expected.getRGBComponents(null); - float actRGB[] = actual.getRGBComponents(null); - assertArrayEquals(expRGB, actRGB, 0.0001f); - } - - @Test - public void bug55714() throws IOException { - XMLSlideShow srcPptx = XSLFTestDataSamples.openSampleDocument("pptx2svg.pptx"); - XMLSlideShow newPptx = new XMLSlideShow(); - XSLFSlide srcSlide = srcPptx.getSlides().get(0); - XSLFSlide newSlide = newPptx.createSlide(); - - XSLFSlideLayout srcSlideLayout = srcSlide.getSlideLayout(); - XSLFSlideLayout newSlideLayout = newSlide.getSlideLayout(); - newSlideLayout.importContent(srcSlideLayout); - - XSLFSlideMaster srcSlideMaster = srcSlide.getSlideMaster(); - XSLFSlideMaster newSlideMaster = newSlide.getSlideMaster(); - newSlideMaster.importContent(srcSlideMaster); - - newSlide.importContent(srcSlide); - XMLSlideShow rwPptx = XSLFTestDataSamples.writeOutAndReadBack(newPptx); - - PaintStyle ps = rwPptx.getSlides().get(0).getBackground().getFillStyle().getPaint(); - assertTrue(ps instanceof TexturePaint); - - rwPptx.close(); - newPptx.close(); - srcPptx.close(); - } - - @Test - public void bug59273() throws IOException { - XMLSlideShow ppt = XSLFTestDataSamples.openSampleDocument("bug59273.potx"); - ppt.getPackage().replaceContentType( - XSLFRelation.PRESENTATIONML_TEMPLATE.getContentType(), - XSLFRelation.MAIN.getContentType() - ); - - XMLSlideShow rwPptx = XSLFTestDataSamples.writeOutAndReadBack(ppt); - OPCPackage pkg = rwPptx.getPackage(); - int size = pkg.getPartsByContentType(XSLFRelation.MAIN.getContentType()).size(); - assertEquals(1, size); - size = pkg.getPartsByContentType(XSLFRelation.PRESENTATIONML_TEMPLATE.getContentType()).size(); - assertEquals(0, size); - - rwPptx.close(); - ppt.close(); - } - - - @Test - public void bug60373() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - XSLFSlide sl = ppt.createSlide(); - XSLFTable t = sl.createTable(); - XSLFTableRow r = t.addRow(); - bug60373_addCell(r); - bug60373_addCell(r); - r = t.addRow(); - XSLFTableCell c = bug60373_addCell(r); - // call getTextHeight, when table is not fully populated - double th = c.getTextHeight(); - assertTrue(th > 10); - ppt.close(); - } - - private static XSLFTableCell bug60373_addCell(XSLFTableRow r) { - XSLFTableCell cell = r.addCell(); - XSLFTextParagraph p = cell.addNewTextParagraph(); - XSLFTextRun tr = p.addNewTextRun(); - tr.setText("t"); - return cell; - } - - @Test - public void bug60715() throws IOException { - XMLSlideShow ppt = XSLFTestDataSamples.openSampleDocument("bug60715.pptx"); - ppt.createSlide(); - ppt.close(); - } - - @Test - public void bug60662() throws IOException { - XMLSlideShow src = new XMLSlideShow(); - XSLFSlide sl = src.createSlide(); - XSLFGroupShape gs = sl.createGroup(); - gs.setAnchor(new Rectangle2D.Double(100,100,100,100)); - gs.setInteriorAnchor(new Rectangle2D.Double(0,0,100,100)); - XSLFAutoShape as = gs.createAutoShape(); - as.setAnchor(new Rectangle2D.Double(0,0,100,100)); - as.setShapeType(ShapeType.STAR_24); - as.setFillColor(Color.YELLOW); - CTShape csh = (CTShape)as.getXmlObject(); - CTOuterShadowEffect shadow = csh.getSpPr().addNewEffectLst().addNewOuterShdw(); - shadow.setDir(270000); - shadow.setDist(100000); - shadow.addNewSrgbClr().setVal(new byte[] {0x00, (byte)0xFF, 0x00}); - - XMLSlideShow dst = new XMLSlideShow(); - XSLFSlide sl2 = dst.createSlide(); - sl2.importContent(sl); - XSLFGroupShape gs2 = (XSLFGroupShape)sl2.getShapes().get(0); - XSLFAutoShape as2 = (XSLFAutoShape)gs2.getShapes().get(0); - CTShape csh2 = (CTShape)as2.getXmlObject(); - assertTrue(csh2.getSpPr().isSetEffectLst()); - - dst.close(); - src.close(); - } - - @Test - public void test60810() throws IOException { - XMLSlideShow ppt = XSLFTestDataSamples.openSampleDocument("60810.pptx"); - for(XSLFSlide slide : ppt.getSlides()) { - XSLFNotes notesSlide = ppt.getNotesSlide(slide); - assertNotNull(notesSlide); - } - - /*OutputStream stream = new FileOutputStream("/tmp/test.pptx"); - try { - ppt.write(stream); - } finally { - stream.close(); - }*/ - - ppt.close(); - } - - @Test - public void test60042() { - XMLSlideShow ppt = XSLFTestDataSamples.openSampleDocument("60042.pptx"); - ppt.removeSlide(0); - ppt.createSlide(); - } -} \ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xslf/TestXSLFSlideShow.java b/src/ooxml/testcases/org/apache/poi/xslf/TestXSLFSlideShow.java deleted file mode 100644 index 31b116f94..000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/TestXSLFSlideShow.java +++ /dev/null @@ -1,157 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.awt.Color; -import java.awt.geom.Rectangle2D; -import java.io.IOException; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.POIXMLProperties.CoreProperties; -import org.apache.poi.openxml4j.exceptions.OpenXML4JException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.sl.usermodel.ShapeType; -import org.apache.poi.xslf.usermodel.XMLSlideShow; -import org.apache.poi.xslf.usermodel.XSLFAutoShape; -import org.apache.poi.xslf.usermodel.XSLFBackground; -import org.apache.poi.xslf.usermodel.XSLFRelation; -import org.apache.poi.xslf.usermodel.XSLFSlide; -import org.apache.poi.xslf.usermodel.XSLFSlideShow; -import org.apache.xmlbeans.XmlException; -import org.junit.Before; -import org.junit.Test; -import org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.CTProperties; -import org.openxmlformats.schemas.presentationml.x2006.main.CTSlideIdListEntry; -import org.openxmlformats.schemas.presentationml.x2006.main.CTSlideMasterIdListEntry; - -public class TestXSLFSlideShow { - private static final POIDataSamples slTests = POIDataSamples.getSlideShowInstance(); - private OPCPackage pack; - - @Before - public void setUp() throws Exception { - pack = OPCPackage.open(slTests.openResourceAsStream("sample.pptx")); - } - - @Test - public void testContainsMainContentType() throws Exception { - boolean found = false; - for(PackagePart part : pack.getParts()) { - if(part.getContentType().equals(XSLFRelation.MAIN.getContentType())) { - found = true; - } - } - assertTrue(found); - } - - @Test - public void testOpen() throws IOException, OpenXML4JException, XmlException { - // With the finalized uri, should be fine - XSLFSlideShow xml = new XSLFSlideShow(pack); - // Check the core - assertNotNull(xml.getPresentation()); - - // Check it has some slides - assertNotEquals(0, xml.getSlideReferences().sizeOfSldIdArray()); - assertNotEquals(0, xml.getSlideMasterReferences().sizeOfSldMasterIdArray()); - - xml.close(); - } - - @Test - public void testSlideBasics() throws IOException, OpenXML4JException, XmlException { - XSLFSlideShow xml = new XSLFSlideShow(pack); - - // Should have 1 master - assertEquals(1, xml.getSlideMasterReferences().sizeOfSldMasterIdArray()); - - // Should have three sheets - assertEquals(2, xml.getSlideReferences().sizeOfSldIdArray()); - - // Check they're as expected - CTSlideIdListEntry[] slides = xml.getSlideReferences().getSldIdArray(); - - assertEquals(256, slides[0].getId()); - assertEquals(257, slides[1].getId()); - assertEquals("rId2", slides[0].getId2()); - assertEquals("rId3", slides[1].getId2()); - - // Now get those objects - assertNotNull(xml.getSlide(slides[0])); - assertNotNull(xml.getSlide(slides[1])); - - // And check they have notes as expected - assertNotNull(xml.getNotes(slides[0])); - assertNotNull(xml.getNotes(slides[1])); - - // And again for the master - CTSlideMasterIdListEntry[] masters = xml.getSlideMasterReferences().getSldMasterIdArray(); - - // see SlideAtom.USES_MASTER_SLIDE_ID - assertEquals(0x80000000L, masters[0].getId()); - assertEquals("rId1", masters[0].getId2()); - assertNotNull(xml.getSlideMaster(masters[0])); - - xml.close(); - } - - @Test - public void testMetadataBasics() throws IOException, OpenXML4JException, XmlException { - XSLFSlideShow xml = new XSLFSlideShow(pack); - - assertNotNull(xml.getProperties().getCoreProperties()); - assertNotNull(xml.getProperties().getExtendedProperties()); - - CTProperties props = xml.getProperties().getExtendedProperties().getUnderlyingProperties(); - assertEquals("Microsoft Office PowerPoint", props.getApplication()); - assertEquals(0, props.getCharacters()); - assertEquals(0, props.getLines()); - - CoreProperties cprops = xml.getProperties().getCoreProperties(); - assertNull(cprops.getTitle()); - assertNull(cprops.getUnderlyingProperties().getSubjectProperty().getValue()); - - xml.close(); - } - - @Test - public void testMasterBackground() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - XSLFBackground b = ppt.getSlideMasters().get(0).getBackground(); - b.setFillColor(Color.RED); - - XSLFSlide sl = ppt.createSlide(); - XSLFAutoShape as = sl.createAutoShape(); - as.setAnchor(new Rectangle2D.Double(100,100,100,100)); - as.setShapeType(ShapeType.CLOUD); - - XMLSlideShow ppt2 = XSLFTestDataSamples.writeOutAndReadBack(ppt); - ppt.close(); - - XSLFBackground b2 = ppt2.getSlideMasters().get(0).getBackground(); - assertEquals(Color.RED, b2.getFillColor()); - - ppt2.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xslf/XSLFTestDataSamples.java b/src/ooxml/testcases/org/apache/poi/xslf/XSLFTestDataSamples.java deleted file mode 100644 index 72ed16f94..000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/XSLFTestDataSamples.java +++ /dev/null @@ -1,72 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.xslf.usermodel.XMLSlideShow; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; - -/** - * @author Yegor Kozlov - */ -public class XSLFTestDataSamples { - - public static XMLSlideShow openSampleDocument(String sampleName) { - InputStream is = POIDataSamples.getSlideShowInstance().openResourceAsStream(sampleName); - try { - return new XMLSlideShow(OPCPackage.open(is)); - } catch (Exception e) { - throw new RuntimeException(e); - } finally { - try { - is.close(); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - } - - public static XMLSlideShow writeOutAndReadBack(XMLSlideShow doc) throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(4096); - try { - doc.write(baos); - } catch (IOException e) { - throw new RuntimeException(e); - } - - InputStream bais; - bais = new ByteArrayInputStream(baos.toByteArray()); - try { - return new XMLSlideShow(OPCPackage.open(bais)); - } catch (Exception e) { - throw new RuntimeException(e); - } finally { - try { - baos.close(); - bais.close(); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xslf/extractor/TestXSLFPowerPointExtractor.java b/src/ooxml/testcases/org/apache/poi/xslf/extractor/TestXSLFPowerPointExtractor.java deleted file mode 100644 index f76e084f9..000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/extractor/TestXSLFPowerPointExtractor.java +++ /dev/null @@ -1,328 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.extractor; - -import static org.apache.poi.POITestCase.assertContains; -import static org.apache.poi.POITestCase.assertNotContained; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.POITextExtractor; -import org.apache.poi.extractor.ExtractorFactory; -import org.apache.poi.openxml4j.exceptions.OpenXML4JException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.xslf.usermodel.XMLSlideShow; -import org.apache.xmlbeans.XmlException; -import org.junit.Test; - -/** - * Tests for XSLFPowerPointExtractor - */ -public class TestXSLFPowerPointExtractor { - private static POIDataSamples slTests = POIDataSamples.getSlideShowInstance(); - - /** - * Get text out of the simple file - * @throws XmlException - * @throws OpenXML4JException - */ - @Test - public void testGetSimpleText() - throws IOException, XmlException, OpenXML4JException { - XMLSlideShow xmlA = openPPTX("sample.pptx"); - @SuppressWarnings("resource") - OPCPackage pkg = xmlA.getPackage(); - - new XSLFPowerPointExtractor(xmlA).close(); - new XSLFPowerPointExtractor(pkg).close(); - - XSLFPowerPointExtractor extractor = - new XSLFPowerPointExtractor(xmlA); - extractor.getText(); - - String text = extractor.getText(); - assertTrue(text.length() > 0); - - // Check Basics - assertTrue(text.startsWith("Lorem ipsum dolor sit amet\n")); - assertContains(text, "amet\n\n"); - - // Our placeholder master text - // This shouldn't show up in the output - // String masterText = - // "Click to edit Master title style\n" + - // "Click to edit Master subtitle style\n" + - // "\n\n\n\n\n\n" + - // "Click to edit Master title style\n" + - // "Click to edit Master text styles\n" + - // "Second level\n" + - // "Third level\n" + - // "Fourth level\n" + - // "Fifth level\n"; - - // Just slides, no notes - text = extractor.getText(true, false, false); - String slideText = - "Lorem ipsum dolor sit amet\n" + - "Nunc at risus vel erat tempus posuere. Aenean non ante.\n" + - "\n" + - "Lorem ipsum dolor sit amet\n" + - "Lorem\n" + - "ipsum\n" + - "dolor\n" + - "sit\n" + - "amet\n" + - "\n"; - assertEquals(slideText, text); - - // Just notes, no slides - text = extractor.getText(false, true); - assertEquals("\n\n1\n\n\n2\n", text); - - // Both - text = extractor.getText(true, true, false); - String bothText = - "Lorem ipsum dolor sit amet\n" + - "Nunc at risus vel erat tempus posuere. Aenean non ante.\n" + - "\n\n\n1\n" + - "Lorem ipsum dolor sit amet\n" + - "Lorem\n" + - "ipsum\n" + - "dolor\n" + - "sit\n" + - "amet\n" + - "\n\n\n2\n"; - assertEquals(bothText, text); - - // With Slides and Master Text - text = extractor.getText(true, false, true); - String smText = - "Lorem ipsum dolor sit amet\n" + - "Nunc at risus vel erat tempus posuere. Aenean non ante.\n" + - "\n" + - "Lorem ipsum dolor sit amet\n" + - "Lorem\n" + - "ipsum\n" + - "dolor\n" + - "sit\n" + - "amet\n" + - "\n"; - assertEquals(smText, text); - - // With Slides, Notes and Master Text - text = extractor.getText(true, true, true); - String snmText = - "Lorem ipsum dolor sit amet\n" + - "Nunc at risus vel erat tempus posuere. Aenean non ante.\n" + - "\n\n\n1\n" + - "Lorem ipsum dolor sit amet\n" + - "Lorem\n" + - "ipsum\n" + - "dolor\n" + - "sit\n" + - "amet\n" + - "\n\n\n2\n"; - assertEquals(snmText, text); - - // Via set defaults - extractor.setSlidesByDefault(false); - extractor.setNotesByDefault(true); - text = extractor.getText(); - assertEquals("\n\n1\n\n\n2\n", text); - - extractor.close(); - xmlA.close(); - } - - public void testGetComments() throws IOException { - XMLSlideShow xml = openPPTX("45545_Comment.pptx"); - XSLFPowerPointExtractor extractor = new XSLFPowerPointExtractor(xml); - - String text = extractor.getText(); - assertTrue(text.length() > 0); - - // Check comments are there - assertContains(text, "testdoc"); - assertContains(text, "test phrase"); - - // Check the authors came through too - assertContains(text, "XPVMWARE01"); - - extractor.close(); - xml.close(); - } - - public void testGetMasterText() throws Exception { - XMLSlideShow xml = openPPTX("WithMaster.pptx"); - XSLFPowerPointExtractor extractor = new XSLFPowerPointExtractor(xml); - extractor.setSlidesByDefault(true); - extractor.setNotesByDefault(false); - extractor.setMasterByDefault(true); - - String text = extractor.getText(); - assertTrue(text.length() > 0); - - // Check master text is there - assertContains(text, "Footer from the master slide"); - - // Theme text shouldn't show up - // String themeText = - // "Theme Master Title\n" + - // "Theme Master first level\n" + - // "And the 2nd level\n" + - // "Our 3rd level goes here\n" + - // "And onto the 4th, such fun....\n" + - // "Finally is the Fifth level\n"; - - // Check the whole text - String wholeText = - "First page title\n" + - "First page subtitle\n" + - "This is the Master Title\n" + - "This text comes from the Master Slide\n" + - "\n" + - // TODO Detect we didn't have a title, and include the master one - "2nd page subtitle\n" + - "Footer from the master slide\n" + - "This is the Master Title\n" + - "This text comes from the Master Slide\n"; - assertEquals(wholeText, text); - - extractor.close(); - xml.close(); - } - - @Test - public void testTable() throws Exception { - XMLSlideShow xml = openPPTX("present1.pptx"); - XSLFPowerPointExtractor extractor = new XSLFPowerPointExtractor(xml); - - String text = extractor.getText(); - assertTrue(text.length() > 0); - - // Check comments are there - assertTrue("Unable to find expected word in text\n" + text, text.contains("TEST")); - - extractor.close(); - xml.close(); - } - - /** - * Test that we can get the text from macro enabled, - * template, theme, slide enabled etc formats, as - * well as from the normal file - */ - @Test - public void testDifferentSubformats() throws Exception { - String[] extensions = new String[] { - "pptx", "pptm", "ppsm", "ppsx", "thmx", - // "xps" - Doesn't have a core document - }; - for(String extension : extensions) { - String filename = "testPPT." + extension; - XMLSlideShow xml = openPPTX(filename); - XSLFPowerPointExtractor extractor = new XSLFPowerPointExtractor(xml); - - String text = extractor.getText(); - if (extension.equals("thmx")) { - // Theme file doesn't have any textual content - assertEquals(0, text.length()); - continue; - } - - assertTrue(text.length() > 0); - assertTrue( - "Text missing for " + filename + "\n" + text, - text.contains("Attachment Test") - ); - assertTrue( - "Text missing for " + filename + "\n" + text, - text.contains("This is a test file data with the same content") - ); - assertTrue( - "Text missing for " + filename + "\n" + text, - text.contains("content parsing") - ); - assertTrue( - "Text missing for " + filename + "\n" + text, - text.contains("Different words to test against") - ); - assertTrue( - "Text missing for " + filename + "\n" + text, - text.contains("Mystery") - ); - - extractor.close(); - xml.close(); - } - } - - @Test - public void test45541() throws Exception { - // extract text from a powerpoint that has a header in the notes-element - POITextExtractor extr = ExtractorFactory.createExtractor( - slTests.getFile("45541_Header.pptx")); - String text = extr.getText(); - assertNotNull(text); - assertFalse("Had: " + text, text.contains("testdoc")); - - text = ((XSLFPowerPointExtractor)extr).getText(false, true); - assertContains(text, "testdoc"); - extr.close(); - assertNotNull(text); - - // extract text from a powerpoint that has a footer in the master-slide - extr = ExtractorFactory.createExtractor( - slTests.getFile("45541_Footer.pptx")); - text = extr.getText(); - assertNotContained(text, "testdoc"); - - text = ((XSLFPowerPointExtractor)extr).getText(false, true); - assertNotContained(text, "testdoc"); - - text = ((XSLFPowerPointExtractor)extr).getText(false, false, true); - assertNotContained(text, "testdoc"); - - extr.close(); - } - - - @Test - public void bug54570() throws IOException { - XMLSlideShow xml = openPPTX("bug54570.pptx"); - XSLFPowerPointExtractor extractor = new XSLFPowerPointExtractor(xml); - String text = extractor.getText(); - assertNotNull(text); - extractor.close(); - xml.close(); - } - - private XMLSlideShow openPPTX(String file) throws IOException { - InputStream is = slTests.openResourceAsStream(file); - try { - return new XMLSlideShow(is); - } finally { - is.close(); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xslf/geom/TestFormulaParser.java b/src/ooxml/testcases/org/apache/poi/xslf/geom/TestFormulaParser.java deleted file mode 100644 index 36d42471c..000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/geom/TestFormulaParser.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -package org.apache.poi.xslf.geom; - -import static org.junit.Assert.assertEquals; - -import org.apache.poi.sl.draw.binding.CTCustomGeometry2D; -import org.apache.poi.sl.draw.geom.*; -import org.junit.Test; - -/** - * Date: 10/24/11 - * - * @author Yegor Kozlov - */ -public class TestFormulaParser { - @Test - public void testParse(){ - - Formula[] ops = { - new Guide("adj1", "val 100"), - new Guide("adj2", "val 200"), - new Guide("adj3", "val -1"), - new Guide("a1", "*/ adj1 2 adj2"), // a1 = 100*2 / 200 - new Guide("a2", "+- adj2 a1 adj1"), // a2 = 200 + a1 - 100 - new Guide("a3", "+/ adj1 adj2 adj2"), // a3 = (100 + 200) / 200 - new Guide("a4", "?: adj3 adj1 adj2"), // a4 = adj3 > 0 ? adj1 : adj2 - new Guide("a5", "abs -2"), - }; - - CustomGeometry geom = new CustomGeometry(new CTCustomGeometry2D()); - Context ctx = new Context(geom, null, null); - for(Formula fmla : ops) { - ctx.evaluate(fmla); - } - - assertEquals(100.0, ctx.getValue("adj1"), 0.0); - assertEquals(200.0, ctx.getValue("adj2"), 0.0); - assertEquals(1.0, ctx.getValue("a1"), 0.0); - assertEquals(101.0, ctx.getValue("a2"), 0.0); - assertEquals(1.5, ctx.getValue("a3"), 0.0); - assertEquals(200.0, ctx.getValue("a4"), 0.0); - assertEquals(2.0, ctx.getValue("a5"), 0.0); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestPPTX2PNG.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestPPTX2PNG.java deleted file mode 100644 index 50ad6347a..000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestPPTX2PNG.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xslf.usermodel; - -import static org.junit.Assume.assumeFalse; - -import java.io.File; -import java.io.FileFilter; -import java.util.Collection; -import java.util.Locale; -import java.util.Set; -import java.util.TreeSet; -import java.util.regex.Pattern; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.xslf.util.PPTX2PNG; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; - -/** - * Test class for testing PPTX2PNG utility which renderes .ppt and .pptx slideshows - */ -@RunWith(Parameterized.class) -public class TestPPTX2PNG { - private static boolean xslfOnly = false; - private static final POIDataSamples samples = POIDataSamples.getSlideShowInstance(); - private static final File basedir = null; - private static final String files = - "53446.ppt, alterman_security.ppt, alterman_security.pptx, KEY02.pptx, themes.pptx, backgrounds.pptx, layouts.pptx, sample.pptx, shapes.pptx, 54880_chinese.ppt"; - - - - @BeforeClass - public static void checkHslf() { - try { - Class.forName("org.apache.poi.hslf.usermodel.HSLFSlideShow"); - } catch (Exception e) { - xslfOnly = true; - } - } - - // use filename instead of File object to omit full pathname in test name - @Parameter(value = 0) - public String pptFile; - - @Parameters(name="{0}") - public static Collection data() { - final Set data = new TreeSet(); - for (String f : files.split(", ?")) { - if (basedir == null) { - data.add(f); - } else { - final Pattern p = Pattern.compile(f); - basedir.listFiles(new FileFilter(){ - public boolean accept(File pathname) { - String name = pathname.getName(); - if (p.matcher(name).matches()) { - data.add(name); - } - return false; - } - }); - } - } - - return data; - } - - @Test - public void render() throws Exception { - assumeFalse("ignore HSLF / .ppt files in no-scratchpad run", xslfOnly && pptFile.toLowerCase(Locale.ROOT).endsWith("ppt")); - - String[] args = { - "-format", "null", // png,gif,jpg or null for test - "-slide", "-1", // -1 for all - "-outdir", new File("build/tmp/").getCanonicalPath(), - "-quiet", - (basedir == null ? samples.getFile(pptFile) : new File(basedir, pptFile)).getAbsolutePath() - }; - PPTX2PNG.main(args); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXMLSlideShow.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXMLSlideShow.java deleted file mode 100644 index 3ef1988b2..000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXMLSlideShow.java +++ /dev/null @@ -1,182 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; - -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.sl.usermodel.BaseTestSlideShow; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.openxmlformats.schemas.presentationml.x2006.main.CTNotesMasterIdListEntry; -import org.openxmlformats.schemas.presentationml.x2006.main.CTSlideIdListEntry; -import org.openxmlformats.schemas.presentationml.x2006.main.CTSlideMasterIdListEntry; - -public class TestXMLSlideShow extends BaseTestSlideShow { - private OPCPackage pack; - - @Override - public XMLSlideShow createSlideShow() { - return new XMLSlideShow(); - } - - @Before - public void setUp() throws Exception { - pack = OPCPackage.open(slTests.openResourceAsStream("sample.pptx")); - } - - @After - public void tearDown() throws IOException { - pack.revert(); - } - - @Test - public void testContainsMainContentType() throws Exception { - boolean found = false; - for(PackagePart part : pack.getParts()) { - if(part.getContentType().equals(XSLFRelation.MAIN.getContentType())) { - found = true; - } - } - assertTrue(found); - } - - @Test - public void testOpen() throws Exception { - // With the finalised uri, should be fine - XMLSlideShow xml = new XMLSlideShow(pack); - // Check the core - assertNotNull(xml.getCTPresentation()); - - // Check it has some slides - assertFalse(xml.getSlides().isEmpty()); - assertFalse(xml.getSlideMasters().isEmpty()); - - xml.close(); - } - - @Test - public void testSlideBasics() throws IOException { - XMLSlideShow xml = new XMLSlideShow(pack); - - // Should have 1 master - assertEquals(1, xml.getSlideMasters().size()); - - // Should have two sheets - assertEquals(2, xml.getSlides().size()); - - // Check they're as expected - CTSlideIdListEntry[] slides = xml.getCTPresentation().getSldIdLst().getSldIdArray(); - - assertEquals(256, slides[0].getId()); - assertEquals(257, slides[1].getId()); - assertEquals("rId2", slides[0].getId2()); - assertEquals("rId3", slides[1].getId2()); - - // Now get those objects - assertNotNull(xml.getSlides().get(0)); - assertNotNull(xml.getSlides().get(1)); - - // And check they have notes as expected - assertNotNull(xml.getSlides().get(0).getNotes()); - assertNotNull(xml.getSlides().get(1).getNotes()); - - // Next up look for the slide master - CTSlideMasterIdListEntry[] masters = xml.getCTPresentation().getSldMasterIdLst().getSldMasterIdArray(); - - // see SlideAtom.USES_MASTER_SLIDE_ID - assertEquals(0x80000000L, masters[0].getId()); - assertEquals("rId1", masters[0].getId2()); - assertNotNull(xml.getSlideMasters().get(0)); - - // Finally look for the notes master - CTNotesMasterIdListEntry notesMaster = - xml.getCTPresentation().getNotesMasterIdLst().getNotesMasterId(); - assertNotNull(notesMaster); - - assertNotNull(xml.getNotesMaster()); - - xml.close(); - } - - @Test - public void testMetadataBasics() throws IOException { - XMLSlideShow xml = new XMLSlideShow(pack); - - assertNotNull(xml.getProperties().getCoreProperties()); - assertNotNull(xml.getProperties().getExtendedProperties()); - - assertEquals("Microsoft Office PowerPoint", xml.getProperties().getExtendedProperties().getUnderlyingProperties().getApplication()); - assertEquals(0, xml.getProperties().getExtendedProperties().getUnderlyingProperties().getCharacters()); - assertEquals(0, xml.getProperties().getExtendedProperties().getUnderlyingProperties().getLines()); - - assertEquals(null, xml.getProperties().getCoreProperties().getTitle()); - assertEquals(null, xml.getProperties().getCoreProperties().getUnderlyingProperties().getSubjectProperty().getValue()); - - xml.close(); - } - - @Test - public void testComments() throws Exception { - // Default sample file has none - XMLSlideShow xml = new XMLSlideShow(pack); - - assertEquals(null, xml.getCommentAuthors()); - - for (XSLFSlide slide : xml.getSlides()) { - assertEquals(null, slide.getComments()); - } - - // Try another with comments - XMLSlideShow xmlComments = new XMLSlideShow(slTests.openResourceAsStream("45545_Comment.pptx")); - - // Has one author - assertNotNull(xmlComments.getCommentAuthors()); - assertEquals(1, xmlComments.getCommentAuthors().getCTCommentAuthorsList().sizeOfCmAuthorArray()); - assertEquals("XPVMWARE01", xmlComments.getCommentAuthors().getAuthorById(0).getName()); - - // First two slides have comments - int i = -1; - for (XSLFSlide slide : xmlComments.getSlides()) { - i++; - - if(i == 0) { - assertNotNull(slide.getComments()); - assertEquals(1, slide.getComments().getNumberOfComments()); - assertEquals("testdoc", slide.getComments().getCommentAt(0).getText()); - assertEquals(0, slide.getComments().getCommentAt(0).getAuthorId()); - } else if (i == 1) { - assertNotNull(slide.getComments()); - assertEquals(1, slide.getComments().getNumberOfComments()); - assertEquals("test phrase", slide.getComments().getCommentAt(0).getText()); - assertEquals(0, slide.getComments().getCommentAt(0).getAuthorId()); - } else { - assertEquals(null, slide.getComments()); - } - } - - xmlComments.close(); - xml.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFAutoShape.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFAutoShape.java deleted file mode 100644 index d7869d722..000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFAutoShape.java +++ /dev/null @@ -1,311 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; - -import org.apache.poi.sl.usermodel.ShapeType; -import org.apache.poi.sl.usermodel.TextParagraph.TextAlign; -import org.apache.poi.sl.usermodel.TextShape.TextAutofit; -import org.apache.poi.sl.usermodel.TextShape.TextDirection; -import org.apache.poi.sl.usermodel.VerticalAlignment; -import org.apache.poi.util.Units; -import org.junit.Test; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextCharacterProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.STTextStrikeType; -import org.openxmlformats.schemas.drawingml.x2006.main.STTextUnderlineType; - -public class TestXSLFAutoShape { - @Test - public void testTextBodyProperies() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - XSLFSlide slide = ppt.createSlide(); - - XSLFAutoShape shape = slide.createAutoShape(); - shape.addNewTextParagraph().addNewTextRun().setText("POI"); - - // default margins from slide master - assertEquals(3.6, shape.getBottomInset(), 0); - assertEquals(3.6, shape.getTopInset(), 0); - assertEquals(7.2, shape.getLeftInset(), 0); - assertEquals(7.2, shape.getRightInset(), 0); - - shape.setBottomInset(1.0); - assertEquals(1.0, shape.getBottomInset(), 0); - shape.setTopInset(2.0); - assertEquals(2.0, shape.getTopInset(), 0); - shape.setLeftInset(3.0); - assertEquals(3.0, shape.getLeftInset(), 0); - shape.setRightInset(4.0); - assertEquals(4.0, shape.getRightInset(), 0); - - shape.setBottomInset(0.0); - assertEquals(0.0, shape.getBottomInset(), 0); - shape.setTopInset(0.0); - assertEquals(0.0, shape.getTopInset(), 0); - shape.setLeftInset(0.0); - assertEquals(0.0, shape.getLeftInset(), 0); - shape.setRightInset(0.0); - assertEquals(0.0, shape.getRightInset(), 0); - - // unset to defauls - shape.setBottomInset(-1); - assertEquals(3.6, shape.getBottomInset(), 0); - shape.setTopInset(-1); - assertEquals(3.6, shape.getTopInset(), 0); - shape.setLeftInset(-1); - assertEquals(7.2, shape.getLeftInset(), 0); - shape.setRightInset(-1); - assertEquals(7.2, shape.getRightInset(), 0); - - // shape - assertTrue(shape.getWordWrap()); - shape.setWordWrap(false); - assertFalse(shape.getWordWrap()); - shape.setWordWrap(true); - assertTrue(shape.getWordWrap()); - - // shape - assertEquals(TextAutofit.NORMAL, shape.getTextAutofit()); - shape.setTextAutofit(TextAutofit.NONE); - assertEquals(TextAutofit.NONE, shape.getTextAutofit()); - shape.setTextAutofit(TextAutofit.SHAPE); - assertEquals(TextAutofit.SHAPE, shape.getTextAutofit()); - shape.setTextAutofit(TextAutofit.NORMAL); - assertEquals(TextAutofit.NORMAL, shape.getTextAutofit()); - - assertEquals(VerticalAlignment.TOP, shape.getVerticalAlignment()); - shape.setVerticalAlignment(VerticalAlignment.BOTTOM); - assertEquals(VerticalAlignment.BOTTOM, shape.getVerticalAlignment()); - shape.setVerticalAlignment(VerticalAlignment.MIDDLE); - assertEquals(VerticalAlignment.MIDDLE, shape.getVerticalAlignment()); - shape.setVerticalAlignment(null); - assertEquals(VerticalAlignment.TOP, shape.getVerticalAlignment()); - - assertEquals(TextDirection.HORIZONTAL, shape.getTextDirection()); - shape.setTextDirection(TextDirection.VERTICAL); - assertEquals(TextDirection.VERTICAL, shape.getTextDirection()); - shape.setTextDirection(null); - assertEquals(TextDirection.HORIZONTAL, shape.getTextDirection()); - - ppt.close(); - } - - @Test - public void testTextParagraph() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - XSLFSlide slide = ppt.createSlide(); - assertTrue(slide.getShapes().isEmpty()); - - XSLFAutoShape shape = slide.createAutoShape(); - assertEquals(0, shape.getTextParagraphs().size()); - XSLFTextParagraph p = shape.addNewTextParagraph(); - assertEquals(1, shape.getTextParagraphs().size()); - - assertNull(p.getIndent()); - assertEquals(0, p.getLeftMargin(), 0); - assertNull(p.getLineSpacing()); - assertNull(p.getSpaceAfter()); - assertNull(p.getSpaceBefore()); - assertEquals(0, p.getIndentLevel()); - - p.setIndent(2.0); - assertEquals(2.0, p.getIndent(), 0); - assertTrue(p.getXmlObject().getPPr().isSetIndent()); - p.setIndent(null); - assertNull(p.getIndent()); - assertFalse(p.getXmlObject().getPPr().isSetIndent()); - p.setIndent(10.0); - assertEquals(10., p.getIndent(), 0); - assertTrue(p.getXmlObject().getPPr().isSetIndent()); - - - assertFalse(p.getXmlObject().getPPr().isSetLvl()); - p.setIndentLevel(1); - assertEquals(1, p.getIndentLevel()); - assertTrue(p.getXmlObject().getPPr().isSetLvl()); - p.setIndentLevel(2); - assertEquals(2, p.getIndentLevel()); - - p.setLeftMargin(2.0); - assertEquals(2.0, p.getLeftMargin(), 0); - assertTrue(p.getXmlObject().getPPr().isSetMarL()); - p.setLeftMargin(10.0); - assertEquals(10., p.getLeftMargin(), 0); - assertEquals(Units.toEMU(10), p.getXmlObject().getPPr().getMarL()); - - - assertFalse(p.getXmlObject().getPPr().isSetSpcAft()); - p.setSpaceAfter(200d); - assertEquals(200000, p.getXmlObject().getPPr().getSpcAft().getSpcPct().getVal()); - assertFalse(p.getXmlObject().getPPr().getSpcAft().isSetSpcPts()); - p.setSpaceAfter(100d); - assertEquals(100000, p.getXmlObject().getPPr().getSpcAft().getSpcPct().getVal()); - assertFalse(p.getXmlObject().getPPr().getSpcAft().isSetSpcPts()); - p.setSpaceAfter(-20d); - assertEquals(2000, p.getXmlObject().getPPr().getSpcAft().getSpcPts().getVal()); - assertFalse(p.getXmlObject().getPPr().getSpcAft().isSetSpcPct()); - p.setSpaceAfter(-10d); - assertEquals(1000, p.getXmlObject().getPPr().getSpcAft().getSpcPts().getVal()); - assertFalse(p.getXmlObject().getPPr().getSpcAft().isSetSpcPct()); - - assertFalse(p.getXmlObject().getPPr().isSetSpcBef()); - p.setSpaceBefore(200d); - assertEquals(200000, p.getXmlObject().getPPr().getSpcBef().getSpcPct().getVal()); - assertFalse(p.getXmlObject().getPPr().getSpcBef().isSetSpcPts()); - p.setSpaceBefore(100d); - assertEquals(100000, p.getXmlObject().getPPr().getSpcBef().getSpcPct().getVal()); - assertFalse(p.getXmlObject().getPPr().getSpcBef().isSetSpcPts()); - p.setSpaceBefore(-20d); - assertEquals(2000, p.getXmlObject().getPPr().getSpcBef().getSpcPts().getVal()); - assertFalse(p.getXmlObject().getPPr().getSpcBef().isSetSpcPct()); - p.setSpaceBefore(-10d); - assertEquals(1000, p.getXmlObject().getPPr().getSpcBef().getSpcPts().getVal()); - assertFalse(p.getXmlObject().getPPr().getSpcBef().isSetSpcPct()); - - assertFalse(p.getXmlObject().getPPr().isSetLnSpc()); - p.setLineSpacing(200d); - assertEquals(200000, p.getXmlObject().getPPr().getLnSpc().getSpcPct().getVal()); - assertFalse(p.getXmlObject().getPPr().getLnSpc().isSetSpcPts()); - p.setLineSpacing(100d); - assertEquals(100000, p.getXmlObject().getPPr().getLnSpc().getSpcPct().getVal()); - assertFalse(p.getXmlObject().getPPr().getLnSpc().isSetSpcPts()); - p.setLineSpacing(-20d); - assertEquals(2000, p.getXmlObject().getPPr().getLnSpc().getSpcPts().getVal()); - assertFalse(p.getXmlObject().getPPr().getLnSpc().isSetSpcPct()); - p.setLineSpacing(-10d); - assertEquals(1000, p.getXmlObject().getPPr().getLnSpc().getSpcPts().getVal()); - assertFalse(p.getXmlObject().getPPr().getLnSpc().isSetSpcPct()); - - // align is set in autoshape prototype - assertTrue(p.getXmlObject().getPPr().isSetAlgn()); - assertEquals(TextAlign.LEFT, p.getTextAlign()); - p.setTextAlign(TextAlign.LEFT); - assertTrue(p.getXmlObject().getPPr().isSetAlgn()); - assertEquals(TextAlign.LEFT, p.getTextAlign()); - p.setTextAlign(TextAlign.RIGHT); - assertEquals(TextAlign.RIGHT, p.getTextAlign()); - p.setTextAlign(TextAlign.JUSTIFY); - assertEquals(TextAlign.JUSTIFY, p.getTextAlign()); - p.setTextAlign(null); - assertEquals(TextAlign.LEFT, p.getTextAlign()); - assertFalse(p.getXmlObject().getPPr().isSetAlgn()); - - ppt.close(); - } - - @Test - public void testTextRun() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - XSLFSlide slide = ppt.createSlide(); - - XSLFAutoShape shape = slide.createAutoShape(); - assertEquals(0, shape.getTextParagraphs().size()); - XSLFTextParagraph p = shape.addNewTextParagraph(); - assertEquals(1, shape.getTextParagraphs().size()); - assertEquals(0, p.getTextRuns().size()); - XSLFTextRun r = p.addNewTextRun(); - CTTextCharacterProperties rPr = r.getRPr(false); - assertNotNull(rPr); - assertEquals(1, p.getTextRuns().size()); - assertSame(r, p.getTextRuns().get(0)); - - - assertEquals(18.0, r.getFontSize(), 0); // default font size for text boxes - assertFalse(rPr.isSetSz()); - r.setFontSize(10.0); - assertEquals(1000, rPr.getSz()); - r.setFontSize(12.5); - assertEquals(1250, rPr.getSz()); - r.setFontSize(null); - assertFalse(rPr.isSetSz()); - - assertFalse(rPr.isSetLatin()); - assertEquals("Calibri", r.getFontFamily()); // comes from the slide master - r.setFontFamily(null); - assertEquals("Calibri", r.getFontFamily()); // comes from the slide master - r.setFontFamily("Arial"); - assertEquals("Arial", r.getFontFamily()); - assertEquals("Arial", rPr.getLatin().getTypeface()); - r.setFontFamily("Symbol"); - assertEquals("Symbol", r.getFontFamily()); - assertEquals("Symbol", rPr.getLatin().getTypeface()); - r.setFontFamily(null); - assertEquals("Calibri", r.getFontFamily()); // comes from the slide master - assertFalse(rPr.isSetLatin()); - - assertFalse(r.isStrikethrough()); - assertFalse(rPr.isSetStrike()); - r.setStrikethrough(true); - assertTrue(r.isStrikethrough()); - assertEquals(STTextStrikeType.SNG_STRIKE, rPr.getStrike()); - - assertFalse(r.isBold()); - assertFalse(rPr.isSetB()); - r.setBold(true); - assertTrue(r.isBold()); - assertEquals(true, rPr.getB()); - - assertFalse(r.isItalic()); - assertFalse(rPr.isSetI()); - r.setItalic(true); - assertTrue(r.isItalic()); - assertEquals(true, rPr.getI()); - - assertFalse(r.isUnderlined()); - assertFalse(rPr.isSetU()); - r.setUnderlined(true); - assertTrue(r.isUnderlined()); - assertEquals(STTextUnderlineType.SNG, rPr.getU()); - - r.setText("Apache"); - assertEquals("Apache", r.getRawText()); - r.setText("POI"); - assertEquals("POI", r.getRawText()); - r.setText(null); - assertNull(r.getRawText()); - - ppt.close(); - } - - @Test - public void testShapeType() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - XSLFSlide slide = ppt.createSlide(); - - XSLFAutoShape shape = slide.createAutoShape(); - assertEquals(ShapeType.RECT, shape.getShapeType()); - - shape.setShapeType(ShapeType.TRIANGLE); - assertEquals(ShapeType.TRIANGLE, shape.getShapeType()); - - for(ShapeType tp : ShapeType.values()) { - if (tp.ooxmlId == -1 || tp == ShapeType.SEAL) continue; - shape.setShapeType(tp); - assertEquals(tp, shape.getShapeType()); - } - - ppt.close(); - } -} \ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFChart.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFChart.java deleted file mode 100644 index c6d1efca9..000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFChart.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -package org.apache.poi.xslf.usermodel; - -import java.io.OutputStream; -import java.util.LinkedHashMap; -import java.util.Map; - -import junit.framework.TestCase; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.xslf.XSLFTestDataSamples; -import org.apache.poi.xssf.usermodel.XSSFRow; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.openxmlformats.schemas.drawingml.x2006.chart.*; - -/** - * @author Yegor Kozlov - */ -public class TestXSLFChart extends TestCase { - - /** - * a modified version from POI-examples - */ - public void testFillChartTemplate() throws Exception { - - String chartTitle = "Apache POI"; // first line is chart title - - XMLSlideShow pptx = XSLFTestDataSamples.openSampleDocument("pie-chart.pptx"); - XSLFSlide slide = pptx.getSlides().get(0); - - // find chart in the slide - XSLFChart chart = null; - for(POIXMLDocumentPart part : slide.getRelations()){ - if(part instanceof XSLFChart){ - chart = (XSLFChart) part; - break; - } - } - - if(chart == null) throw new IllegalStateException("chart not found in the template"); - - // embedded Excel workbook that holds the chart data - POIXMLDocumentPart xlsPart = chart.getRelations().get(0); - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet(); - - CTChart ctChart = chart.getCTChart(); - CTPlotArea plotArea = ctChart.getPlotArea(); - - CTPieChart pieChart = plotArea.getPieChartArray(0); - //Pie Chart Series - CTPieSer ser = pieChart.getSerArray(0); - - // Series Text - CTSerTx tx = ser.getTx(); - tx.getStrRef().getStrCache().getPtArray(0).setV(chartTitle); - sheet.createRow(0).createCell(1).setCellValue(chartTitle); - String titleRef = new CellReference(sheet.getSheetName(), 0, 1, true, true).formatAsString(); - tx.getStrRef().setF(titleRef); - - - // Category Axis Data - CTAxDataSource cat = ser.getCat(); - CTStrData strData = cat.getStrRef().getStrCache(); - - // Values - CTNumDataSource valSrc = ser.getVal(); - CTNumData numData = valSrc.getNumRef().getNumCache(); - - strData.setPtArray(null); // unset old axis text - numData.setPtArray(null); // unset old values - - Map pieModel = new LinkedHashMap(); - pieModel.put("First", 1.0); - pieModel.put("Second", 3.0); - pieModel.put("Third", 4.0); - - // set model - int idx = 0; - int rownum = 1; - for(String key : pieModel.keySet()){ - double val = pieModel.get(key); - - CTNumVal numVal = numData.addNewPt(); - numVal.setIdx(idx); - numVal.setV("" + val); - - CTStrVal sVal = strData.addNewPt(); - sVal.setIdx(idx); - sVal.setV(key); - - idx++; - XSSFRow row = sheet.createRow(rownum++); - row.createCell(0).setCellValue(key); - row.createCell(1).setCellValue(val); - } - numData.getPtCount().setVal(idx); - strData.getPtCount().setVal(idx); - - String numDataRange = new CellRangeAddress(1, rownum-1, 1, 1).formatAsString(sheet.getSheetName(), true); - valSrc.getNumRef().setF(numDataRange); - String axisDataRange = new CellRangeAddress(1, rownum-1, 0, 0).formatAsString(sheet.getSheetName(), true); - cat.getStrRef().setF(axisDataRange); - - // updated the embedded workbook with the data - OutputStream xlsOut = xlsPart.getPackagePart().getOutputStream(); - wb.write(xlsOut); - xlsOut.close(); - - } - -} \ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFColor.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFColor.java deleted file mode 100644 index a862c16b4..000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFColor.java +++ /dev/null @@ -1,184 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.awt.Color; -import java.io.IOException; - -import org.apache.poi.sl.usermodel.PresetColor; -import org.junit.Test; -import org.openxmlformats.schemas.drawingml.x2006.main.CTColor; -import org.openxmlformats.schemas.drawingml.x2006.main.CTHslColor; -import org.openxmlformats.schemas.drawingml.x2006.main.CTSRgbColor; -import org.openxmlformats.schemas.drawingml.x2006.main.CTSystemColor; -import org.openxmlformats.schemas.drawingml.x2006.main.STPresetColorVal; -import org.openxmlformats.schemas.drawingml.x2006.main.STSchemeColorVal; -import org.openxmlformats.schemas.drawingml.x2006.main.STSystemColorVal; - -public class TestXSLFColor { - - @Test - public void testGetters() { - CTColor xml = CTColor.Factory.newInstance(); - CTSRgbColor c = xml.addNewSrgbClr(); - c.setVal(new byte[]{(byte)0xFF, 0, 0}); - - XSLFColor color = new XSLFColor(xml, null, null); - - assertEquals(-1, color.getAlpha()); - c.addNewAlpha().setVal(50000); - assertEquals(50, color.getAlpha()); - - assertEquals(-1, color.getAlphaMod()); - c.addNewAlphaMod().setVal(50000); - assertEquals(50, color.getAlphaMod()); - - assertEquals(-1, color.getAlphaOff()); - c.addNewAlphaOff().setVal(50000); - assertEquals(50, color.getAlphaOff()); - - assertEquals(-1, color.getLumMod()); - c.addNewLumMod().setVal(50000); - assertEquals(50, color.getLumMod()); - - assertEquals(-1, color.getLumOff()); - c.addNewLumOff().setVal(50000); - assertEquals(50, color.getLumOff()); - - assertEquals(-1, color.getSat()); - c.addNewSat().setVal(50000); - assertEquals(50, color.getSat()); - - assertEquals(-1, color.getSatMod()); - c.addNewSatMod().setVal(50000); - assertEquals(50, color.getSatMod()); - - assertEquals(-1, color.getSatOff()); - c.addNewSatOff().setVal(50000); - assertEquals(50, color.getSatOff()); - - assertEquals(-1, color.getRed()); - c.addNewRed().setVal(50000); - assertEquals(50, color.getRed()); - - assertEquals(-1, color.getGreen()); - c.addNewGreen().setVal(50000); - assertEquals(50, color.getGreen()); - - assertEquals(-1, color.getBlue()); - c.addNewBlue().setVal(50000); - assertEquals(50, color.getRed()); - - assertEquals(-1, color.getShade()); - c.addNewShade().setVal(50000); - assertEquals(50, color.getShade()); - - assertEquals(-1, color.getTint()); - c.addNewTint().setVal(50000); - assertEquals(50, color.getTint()); - } - - @Test - public void testHSL() { - CTColor xml = CTColor.Factory.newInstance(); - CTHslColor c = xml.addNewHslClr(); - c.setHue2(14400000); - c.setSat2(100000); - c.setLum2(50000); - - XSLFColor color = new XSLFColor(xml, null, null); - assertEquals(Color.BLUE, color.getColor()); - } - - @Test - public void testSRgb() { - CTColor xml = CTColor.Factory.newInstance(); - xml.addNewSrgbClr().setVal(new byte[]{ (byte)0xFF, (byte)0xFF, 0}); - - XSLFColor color = new XSLFColor(xml, null, null); - assertEquals(new Color(0xFF, 0xFF, 0), color.getColor()); - } - - @Test - public void testSchemeColor() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - XSLFTheme theme = ppt.createSlide().getTheme(); - - CTColor xml = CTColor.Factory.newInstance(); - xml.addNewSchemeClr().setVal(STSchemeColorVal.ACCENT_2); - - XSLFColor color = new XSLFColor(xml, theme, null); - // accent2 is theme1.xml is - assertEquals(Color.decode("0xC0504D"), color.getColor()); - - xml = CTColor.Factory.newInstance(); - xml.addNewSchemeClr().setVal(STSchemeColorVal.LT_1); - color = new XSLFColor(xml, theme, null); - // - assertEquals(Color.decode("0xFFFFFF"), color.getColor()); - - xml = CTColor.Factory.newInstance(); - xml.addNewSchemeClr().setVal(STSchemeColorVal.DK_1); - color = new XSLFColor(xml, theme, null); - // - assertEquals(Color.decode("0x000000"), color.getColor()); - - ppt.close(); - } - - @Test - public void testPresetColor() { - CTColor xml = CTColor.Factory.newInstance(); - xml.addNewPrstClr().setVal(STPresetColorVal.AQUAMARINE); - XSLFColor color = new XSLFColor(xml, null, null); - assertEquals(new Color(127, 255, 212), color.getColor()); - - - for(PresetColor pc : PresetColor.values()) { - if (pc.ooxmlId == null) continue; - xml = CTColor.Factory.newInstance(); - STPresetColorVal.Enum preVal = STPresetColorVal.Enum.forString(pc.ooxmlId); - STSystemColorVal.Enum sysVal = STSystemColorVal.Enum.forString(pc.ooxmlId); - assertTrue(pc.ooxmlId, preVal != null || sysVal != null); - if (preVal != null) { - xml.addNewPrstClr().setVal(preVal); - } else { - xml.addNewSysClr().setVal(sysVal); - } - color = new XSLFColor(xml, null, null); - assertEquals(pc.color, color.getColor()); - } - } - - @Test - public void testSys() { - CTColor xml = CTColor.Factory.newInstance(); - CTSystemColor sys = xml.addNewSysClr(); - sys.setVal(STSystemColorVal.CAPTION_TEXT); - XSLFColor color = new XSLFColor(xml, null, null); - assertEquals(Color.black, color.getColor()); - - xml = CTColor.Factory.newInstance(); - sys = xml.addNewSysClr(); - sys.setLastClr(new byte[]{(byte)0xFF, 0, 0}); - color = new XSLFColor(xml, null, null); - assertEquals(Color.red, color.getColor()); - } -} \ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFConnectorShape.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFConnectorShape.java deleted file mode 100644 index 03f29859a..000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFConnectorShape.java +++ /dev/null @@ -1,159 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.apache.poi.xslf.usermodel.TestXSLFSimpleShape.getSpPr; - -import java.awt.Color; -import java.awt.geom.Rectangle2D; -import java.io.IOException; - -import org.apache.poi.sl.usermodel.LineDecoration.DecorationShape; -import org.apache.poi.sl.usermodel.LineDecoration.DecorationSize; -import org.apache.poi.sl.usermodel.ShapeType; -import org.junit.Test; -import org.openxmlformats.schemas.drawingml.x2006.main.CTConnection; -import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualConnectorProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.STLineEndLength; -import org.openxmlformats.schemas.drawingml.x2006.main.STLineEndType; -import org.openxmlformats.schemas.drawingml.x2006.main.STLineEndWidth; -import org.openxmlformats.schemas.drawingml.x2006.main.STShapeType; -import org.openxmlformats.schemas.presentationml.x2006.main.CTConnector; - -public class TestXSLFConnectorShape { - - @Test - public void testLineDecorations() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - XSLFSlide slide = ppt.createSlide(); - - XSLFConnectorShape shape = slide.createConnector(); - assertEquals(1, slide.getShapes().size()); - - assertFalse(getSpPr(shape).getLn().isSetHeadEnd()); - assertFalse(getSpPr(shape).getLn().isSetTailEnd()); - - // line decorations - assertEquals(DecorationShape.NONE, shape.getLineHeadDecoration()); - assertEquals(DecorationShape.NONE, shape.getLineTailDecoration()); - shape.setLineHeadDecoration(null); - shape.setLineTailDecoration(null); - assertEquals(DecorationShape.NONE, shape.getLineHeadDecoration()); - assertEquals(DecorationShape.NONE, shape.getLineTailDecoration()); - assertFalse(getSpPr(shape).getLn().getHeadEnd().isSetType()); - assertFalse(getSpPr(shape).getLn().getTailEnd().isSetType()); - - shape.setLineHeadDecoration(DecorationShape.ARROW); - shape.setLineTailDecoration(DecorationShape.DIAMOND); - assertEquals(DecorationShape.ARROW, shape.getLineHeadDecoration()); - assertEquals(DecorationShape.DIAMOND, shape.getLineTailDecoration()); - assertEquals(STLineEndType.ARROW, getSpPr(shape).getLn().getHeadEnd().getType()); - assertEquals(STLineEndType.DIAMOND, getSpPr(shape).getLn().getTailEnd().getType()); - - shape.setLineHeadDecoration(DecorationShape.DIAMOND); - shape.setLineTailDecoration(DecorationShape.ARROW); - assertEquals(DecorationShape.DIAMOND, shape.getLineHeadDecoration()); - assertEquals(DecorationShape.ARROW, shape.getLineTailDecoration()); - assertEquals(STLineEndType.DIAMOND, getSpPr(shape).getLn().getHeadEnd().getType()); - assertEquals(STLineEndType.ARROW, getSpPr(shape).getLn().getTailEnd().getType()); - - // line end width - assertEquals(DecorationSize.MEDIUM, shape.getLineHeadWidth()); - assertEquals(DecorationSize.MEDIUM, shape.getLineTailWidth()); - shape.setLineHeadWidth(null); - shape.setLineHeadWidth(null); - assertEquals(DecorationSize.MEDIUM, shape.getLineHeadWidth()); - assertEquals(DecorationSize.MEDIUM, shape.getLineTailWidth()); - assertFalse(getSpPr(shape).getLn().getHeadEnd().isSetW()); - assertFalse(getSpPr(shape).getLn().getTailEnd().isSetW()); - shape.setLineHeadWidth(DecorationSize.LARGE); - shape.setLineTailWidth(DecorationSize.MEDIUM); - assertEquals(DecorationSize.LARGE, shape.getLineHeadWidth()); - assertEquals(DecorationSize.MEDIUM, shape.getLineTailWidth()); - assertEquals(STLineEndWidth.LG, getSpPr(shape).getLn().getHeadEnd().getW()); - assertEquals(STLineEndWidth.MED, getSpPr(shape).getLn().getTailEnd().getW()); - shape.setLineHeadWidth(DecorationSize.MEDIUM); - shape.setLineTailWidth(DecorationSize.LARGE); - assertEquals(DecorationSize.MEDIUM, shape.getLineHeadWidth()); - assertEquals(DecorationSize.LARGE, shape.getLineTailWidth()); - assertEquals(STLineEndWidth.MED, getSpPr(shape).getLn().getHeadEnd().getW()); - assertEquals(STLineEndWidth.LG, getSpPr(shape).getLn().getTailEnd().getW()); - - // line end length - assertEquals(DecorationSize.MEDIUM, shape.getLineHeadLength()); - assertEquals(DecorationSize.MEDIUM, shape.getLineTailLength()); - shape.setLineHeadLength(null); - shape.setLineTailLength(null); - assertEquals(DecorationSize.MEDIUM, shape.getLineHeadLength()); - assertEquals(DecorationSize.MEDIUM, shape.getLineTailLength()); - assertFalse(getSpPr(shape).getLn().getHeadEnd().isSetLen()); - assertFalse(getSpPr(shape).getLn().getTailEnd().isSetLen()); - shape.setLineHeadLength(DecorationSize.LARGE); - shape.setLineTailLength(DecorationSize.MEDIUM); - assertEquals(DecorationSize.LARGE, shape.getLineHeadLength()); - assertEquals(DecorationSize.MEDIUM, shape.getLineTailLength()); - assertEquals(STLineEndLength.LG, getSpPr(shape).getLn().getHeadEnd().getLen()); - assertEquals(STLineEndLength.MED, getSpPr(shape).getLn().getTailEnd().getLen()); - shape.setLineHeadLength(DecorationSize.MEDIUM); - shape.setLineTailLength(DecorationSize.LARGE); - assertEquals(DecorationSize.MEDIUM, shape.getLineHeadLength()); - assertEquals(DecorationSize.LARGE, shape.getLineTailLength()); - assertEquals(STLineEndLength.MED, getSpPr(shape).getLn().getHeadEnd().getLen()); - assertEquals(STLineEndLength.LG, getSpPr(shape).getLn().getTailEnd().getLen()); - - ppt.close(); - } - - @Test - public void testAddConnector() throws IOException { - XMLSlideShow pptx = new XMLSlideShow(); - XSLFSlide slide = pptx.createSlide(); - - XSLFAutoShape rect1 = slide.createAutoShape(); - rect1.setShapeType(ShapeType.RECT); - rect1.setAnchor(new Rectangle2D.Double(100, 100, 100, 100)); - rect1.setFillColor(Color.blue); - - XSLFAutoShape rect2 = slide.createAutoShape(); - rect2.setShapeType(ShapeType.RECT); - rect2.setAnchor(new Rectangle2D.Double(300, 300, 100, 100)); - rect2.setFillColor(Color.red); - - - XSLFConnectorShape connector1 = slide.createConnector(); - connector1.setAnchor(new Rectangle2D.Double(200, 150, 100, 200)); - - CTConnector ctConnector = (CTConnector)connector1.getXmlObject(); - ctConnector.getSpPr().getPrstGeom().setPrst(STShapeType.BENT_CONNECTOR_3); - CTNonVisualConnectorProperties cx = ctConnector.getNvCxnSpPr().getCNvCxnSpPr(); - // connection start - CTConnection stCxn = cx.addNewStCxn(); - stCxn.setId(rect1.getShapeId()); - // side of the rectangle to attach the connector: left=1, bottom=2,right=3, top=4 - stCxn.setIdx(2); - - CTConnection end = cx.addNewEndCxn(); - end.setId(rect2.getShapeId()); - // side of the rectangle to attach the connector: left=1, bottom=2,right=3, top=4 - end.setIdx(3); - - pptx.close(); - } - -} \ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFFreeformShape.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFFreeformShape.java deleted file mode 100644 index c45244ee5..000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFFreeformShape.java +++ /dev/null @@ -1,55 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.usermodel; - - -import static org.junit.Assert.assertEquals; -import static org.apache.poi.xslf.usermodel.TestXSLFSimpleShape.getSpPr; - -import java.awt.geom.Ellipse2D; -import java.awt.geom.Path2D; -import java.awt.geom.Rectangle2D; -import java.io.IOException; - -import org.junit.Test; - -public class TestXSLFFreeformShape { - - @Test - public void testSetPath() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - XSLFSlide slide = ppt.createSlide(); - XSLFFreeformShape shape1 = slide.createFreeform(); - // comples path consisting of a rectangle and an ellipse inside it - Path2D.Double path1 = new Path2D.Double(new Rectangle2D.Double(150, 150, 300, 300)); - path1.append(new Ellipse2D.Double(200, 200, 100, 50), false); - shape1.setPath(path1); - - Path2D.Double path2 = shape1.getPath(); - - // YK: how to compare the original path1 and the value returned by XSLFFreeformShape.getPath() ? - // one way is to create another XSLFFreeformShape from path2 and compare the resulting xml - assertEquals(path1.getBounds2D(), path2.getBounds2D()); - - XSLFFreeformShape shape2 = slide.createFreeform(); - shape2.setPath(path2); - - assertEquals(getSpPr(shape1).getCustGeom().toString(), getSpPr(shape2).getCustGeom().toString()); - - ppt.close(); - } -} \ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFGroupShape.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFGroupShape.java deleted file mode 100644 index 636317721..000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFGroupShape.java +++ /dev/null @@ -1,108 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; - -import java.awt.Dimension; -import java.awt.geom.Rectangle2D; - -import org.junit.Test; - -/** - * @author Yegor Kozlov - */ -public class TestXSLFGroupShape { - - @Test - public void testCreateShapes() throws Exception { - XMLSlideShow ppt = new XMLSlideShow(); - XSLFSlide slide = ppt.createSlide(); - - ppt.setPageSize(new Dimension(792, 612)); - - XSLFGroupShape group = slide.createGroup(); - assertEquals(1, slide.getShapes().size()); - - Rectangle2D interior = new Rectangle2D.Double(-10, -10, 20, 20); - group.setInteriorAnchor(interior); - assertEquals(interior, group.getInteriorAnchor()); - - Rectangle2D anchor = new Rectangle2D.Double(0, 0, 792, 612); - group.setAnchor(anchor); - assertEquals(anchor, group.getAnchor()); - - assertTrue(group.getShapes().isEmpty()); - - XSLFTextBox shape1 = group.createTextBox(); - assertEquals(1, group.getShapes().size()); - assertSame(shape1, group.getShapes().get(0)); - assertEquals(3, shape1.getShapeId()); - - XSLFAutoShape shape2 = group.createAutoShape(); - assertEquals(2, group.getShapes().size()); - assertSame(shape1, group.getShapes().get(0)); - assertSame(shape2, group.getShapes().get(1)); - assertEquals(4, shape2.getShapeId()); - - XSLFConnectorShape shape3 = group.createConnector(); - assertEquals(3, group.getShapes().size()); - assertSame(shape3, group.getShapes().get(2)); - assertEquals(5, shape3.getShapeId()); - - XSLFGroupShape shape4 = group.createGroup(); - assertEquals(4, group.getShapes().size()); - assertSame(shape4, group.getShapes().get(3)); - assertEquals(6, shape4.getShapeId()); - - group.removeShape(shape2); - assertEquals(3, group.getShapes().size()); - assertSame(shape1, group.getShapes().get(0)); - assertSame(shape3, group.getShapes().get(1)); - assertSame(shape4, group.getShapes().get(2)); - - group.removeShape(shape3); - assertEquals(2, group.getShapes().size()); - assertSame(shape1, group.getShapes().get(0)); - assertSame(shape4, group.getShapes().get(1)); - - group.removeShape(shape1); - group.removeShape(shape4); - assertTrue(group.getShapes().isEmpty()); - - ppt.close(); - } - - @Test - public void testRemoveShapes() throws Exception { - XMLSlideShow ppt = new XMLSlideShow(); - XSLFSlide slide = ppt.createSlide(); - - XSLFGroupShape group1 = slide.createGroup(); - group1.createTextBox(); - XSLFGroupShape group2 = slide.createGroup(); - group2.createTextBox(); - XSLFGroupShape group3 = slide.createGroup(); - slide.removeShape(group1); - slide.removeShape(group2); - slide.removeShape(group3); - - ppt.close(); - } -} \ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFHyperlink.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFHyperlink.java deleted file mode 100644 index 746c1bb12..000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFHyperlink.java +++ /dev/null @@ -1,180 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import java.awt.geom.Rectangle2D; -import java.io.IOException; -import java.util.List; - -import org.apache.poi.common.usermodel.HyperlinkType; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.PackageRelationship; -import org.apache.poi.openxml4j.opc.TargetMode; -import org.apache.poi.xslf.XSLFTestDataSamples; -import org.junit.Test; - -public class TestXSLFHyperlink { - - @Test - public void testRead() throws IOException{ - XMLSlideShow ppt = XSLFTestDataSamples.openSampleDocument("shapes.pptx"); - - XSLFSlide slide = ppt.getSlides().get(4); - List shapes = slide.getShapes(); - XSLFTable tbl = (XSLFTable)shapes.get(0); - XSLFTableCell cell1 = tbl.getRows().get(1).getCells().get(0); - assertEquals("Web Page", cell1.getText()); - XSLFHyperlink link1 = cell1.getTextParagraphs().get(0).getTextRuns().get(0).getHyperlink(); - assertNotNull(link1); - assertEquals("http://poi.apache.org/", link1.getAddress()); - - XSLFTableCell cell2 = tbl.getRows().get(2).getCells().get(0); - assertEquals("Place in this document", cell2.getText()); - XSLFHyperlink link2 = cell2.getTextParagraphs().get(0).getTextRuns().get(0).getHyperlink(); - assertNotNull(link2); - assertEquals("/ppt/slides/slide2.xml", link2.getAddress()); - - XSLFTableCell cell3 = tbl.getRows().get(3).getCells().get(0); - assertEquals("Email", cell3.getText()); - XSLFHyperlink link3 = cell3.getTextParagraphs().get(0).getTextRuns().get(0).getHyperlink(); - assertNotNull(link3); - assertEquals("mailto:dev@poi.apache.org?subject=Hi%20There", link3.getAddress()); - - ppt.close(); - } - - @Test - public void testCreate() throws IOException, InvalidFormatException { - XMLSlideShow ppt = new XMLSlideShow(); - XSLFSlide slide1 = ppt.createSlide(); - XSLFSlide slide2 = ppt.createSlide(); - - int numRel = slide1.getPackagePart().getRelationships().size(); - assertEquals(1, numRel); - XSLFTextBox sh1 = slide1.createTextBox(); - XSLFTextRun r1 = sh1.addNewTextParagraph().addNewTextRun(); - r1.setText("Web Page"); - XSLFHyperlink link1 = r1.createHyperlink(); - link1.setAddress("http://poi.apache.org/"); - assertEquals("http://poi.apache.org/", link1.getAddress()); - assertEquals(numRel + 1, slide1.getPackagePart().getRelationships().size()); - - String id1 = link1.getXmlObject().getId(); - assertNotNull(id1); - PackageRelationship rel1 = slide1.getPackagePart().getRelationship(id1); - assertNotNull(rel1); - assertEquals(id1, rel1.getId()); - assertEquals(TargetMode.EXTERNAL, rel1.getTargetMode()); - assertEquals(XSLFRelation.HYPERLINK.getRelation(), rel1.getRelationshipType()); - - XSLFTextBox sh2 = slide1.createTextBox(); - XSLFTextRun r2 = sh2.addNewTextParagraph().addNewTextRun(); - r2.setText("Place in this document"); - XSLFHyperlink link2 = r2.createHyperlink(); - link2.linkToSlide(slide2); - assertEquals("/ppt/slides/slide2.xml", link2.getAddress()); - assertEquals(numRel + 2, slide1.getPackagePart().getRelationships().size()); - - String id2 = link2.getXmlObject().getId(); - assertNotNull(id2); - PackageRelationship rel2 = slide1.getPackagePart().getRelationship(id2); - assertNotNull(rel2); - assertEquals(id2, rel2.getId()); - assertEquals(TargetMode.INTERNAL, rel2.getTargetMode()); - assertEquals(XSLFRelation.SLIDE.getRelation(), rel2.getRelationshipType()); - - ppt.close(); - } - - - @Test - public void bug47291() throws IOException { - Rectangle2D anchor = new Rectangle2D.Double(100,100,100,100); - XMLSlideShow ppt1 = new XMLSlideShow(); - XSLFSlide slide1 = ppt1.createSlide(); - XSLFTextBox tb1 = slide1.createTextBox(); - tb1.setAnchor(anchor); - XSLFTextRun r1 = tb1.setText("page1"); - XSLFHyperlink hl1 = r1.createHyperlink(); - hl1.linkToEmail("dev@poi.apache.org"); - XSLFTextBox tb2 = ppt1.createSlide().createTextBox(); - tb2.setAnchor(anchor); - XSLFTextRun r2 = tb2.setText("page2"); - XSLFHyperlink hl2 = r2.createHyperlink(); - hl2.linkToLastSlide(); - XSLFSlide sl3 = ppt1.createSlide(); - XSLFTextBox tb3 = sl3.createTextBox(); - tb3.setAnchor(anchor); - tb3.setText("text1 "); - tb3.appendText("lin\u000bk", false); - tb3.appendText(" text2", false); - List tb3runs = tb3.getTextParagraphs().get(0).getTextRuns(); - tb3runs.get(1).createHyperlink().linkToSlide(slide1); // "lin" - tb3runs.get(3).createHyperlink().linkToSlide(slide1); // "k" - XSLFTextBox tb4 = ppt1.createSlide().createTextBox(); - tb4.setAnchor(anchor); - XSLFTextRun r4 = tb4.setText("page4"); - XSLFHyperlink hl4 = r4.createHyperlink(); - hl4.linkToUrl("http://poi.apache.org"); - XSLFTextBox tb5 = ppt1.createSlide().createTextBox(); - tb5.setAnchor(anchor); - tb5.setText("page5"); - XSLFHyperlink hl5 = tb5.createHyperlink(); - hl5.linkToFirstSlide(); - - XMLSlideShow ppt2 = XSLFTestDataSamples.writeOutAndReadBack(ppt1); - ppt1.close(); - - List slides = ppt2.getSlides(); - tb1 = (XSLFTextBox)slides.get(0).getShapes().get(0); - hl1 = tb1.getTextParagraphs().get(0).getTextRuns().get(0).getHyperlink(); - assertNotNull(hl1); - assertEquals("dev@poi.apache.org", hl1.getLabel()); - assertEquals(HyperlinkType.EMAIL, hl1.getTypeEnum()); - - tb2 = (XSLFTextBox)slides.get(1).getShapes().get(0); - hl2 = tb2.getTextParagraphs().get(0).getTextRuns().get(0).getHyperlink(); - assertNotNull(hl2); - assertEquals("lastslide", hl2.getXmlObject().getAction().split("=")[1]); - assertEquals(HyperlinkType.DOCUMENT, hl2.getTypeEnum()); - - tb3 = (XSLFTextBox)slides.get(2).getShapes().get(0); - XSLFHyperlink hl3 = tb3.getTextParagraphs().get(0).getTextRuns().get(1).getHyperlink(); - assertNotNull(hl3); - hl3 = tb3.getTextParagraphs().get(0).getTextRuns().get(3).getHyperlink(); - assertNotNull(hl3); - assertEquals("/ppt/slides/slide1.xml", hl3.getAddress()); - assertEquals(HyperlinkType.DOCUMENT, hl3.getTypeEnum()); - - tb4 = (XSLFTextBox)slides.get(3).getShapes().get(0); - hl4 = tb4.getTextParagraphs().get(0).getTextRuns().get(0).getHyperlink(); - assertNotNull(hl4); - assertEquals("http://poi.apache.org", hl4.getLabel()); - assertEquals(HyperlinkType.URL, hl4.getTypeEnum()); - - tb5 = (XSLFTextBox)slides.get(4).getShapes().get(0); - hl5 = tb5.getHyperlink(); - assertNotNull(hl5); - assertEquals("firstslide", hl5.getXmlObject().getAction().split("=")[1]); - assertEquals(HyperlinkType.DOCUMENT, hl5.getTypeEnum()); - - ppt2.close(); - } -} \ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFNotes.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFNotes.java deleted file mode 100644 index 6ce747be7..000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFNotes.java +++ /dev/null @@ -1,106 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - -import java.io.IOException; - -import org.apache.poi.sl.usermodel.Placeholder; -import org.apache.poi.xslf.XSLFTestDataSamples; -import org.junit.Test; - -public class TestXSLFNotes { - - @Test - public void createNewNote() throws IOException { - - XMLSlideShow ppt = new XMLSlideShow(); - XSLFSlide slide1 = ppt.createSlide(); - - assertNull(ppt.getNotesMaster()); - assertNull(slide1.getNotes()); - - XSLFNotes notesSlide = ppt.getNotesSlide(slide1); - assertNotNull(ppt.getNotesMaster()); - assertNotNull(notesSlide); - - String note = null; - for (XSLFTextShape shape : notesSlide.getPlaceholders()) { - if (shape.getTextType() == Placeholder.BODY) { - shape.setText("New Note"); - note = shape.getText(); - break; - } - } - assertNotNull(note); - assertEquals("New Note", note); - - ppt.close(); - } - - @Test - public void addNote() throws IOException { - - XMLSlideShow ppt = XSLFTestDataSamples.openSampleDocument("sample.pptx"); - - XSLFSlide slide = ppt.createSlide(); - XSLFNotes notesSlide = ppt.getNotesSlide(slide); - assertNotNull(notesSlide); - - String note = null; - for (XSLFTextShape shape : notesSlide.getPlaceholders()) { - if (shape.getTextType() == Placeholder.BODY) { - shape.setText("New Note"); - note = shape.getText(); - break; - } - } - assertNotNull(note); - assertEquals("New Note", note); - - ppt.close(); - } - - @Test - public void replaceNotes() throws IOException { - - XMLSlideShow ppt = XSLFTestDataSamples.openSampleDocument("sample.pptx"); - - for (XSLFSlide slide : ppt.getSlides()) { - assertNotNull(slide.getNotes()); - - XSLFNotes notesSlide = ppt.getNotesSlide(slide); - assertNotNull(notesSlide); - - String note = null; - for (XSLFTextShape shape : notesSlide.getPlaceholders()) { - if (shape.getTextType() == Placeholder.BODY) { - shape.setText("New Note"); - note = shape.getText(); - break; - } - } - assertNotNull(note); - assertEquals("New Note", note); - } - - ppt.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFPictureShape.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFPictureShape.java deleted file mode 100644 index 3ca01733e..000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFPictureShape.java +++ /dev/null @@ -1,211 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.usermodel; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.sl.usermodel.PictureData.PictureType; -import org.apache.poi.util.IOUtils; -import org.apache.poi.xslf.XSLFTestDataSamples; -import org.junit.Test; -import org.openxmlformats.schemas.presentationml.x2006.main.CTPicture; - -public class TestXSLFPictureShape { - private static POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); - - @Test - public void testCreate() throws Exception { - XMLSlideShow ppt1 = new XMLSlideShow(); - assertEquals(0, ppt1.getPictureData().size()); - byte[] data1 = new byte[100]; - for(int i = 0;i < 100;i++) { data1[i] = (byte)i; } - XSLFPictureData pdata1 = ppt1.addPicture(data1, PictureType.JPEG); - assertEquals(0, pdata1.getIndex()); - assertEquals(1, ppt1.getPictureData().size()); - - XSLFSlide slide = ppt1.createSlide(); - XSLFPictureShape shape1 = slide.createPicture(pdata1); - assertNotNull(shape1.getPictureData()); - assertArrayEquals(data1, shape1.getPictureData().getData()); - - byte[] data2 = new byte[200]; - for(int i = 0;i < 200;i++) { data2[i] = (byte)i; } - XSLFPictureData pdata2 = ppt1.addPicture(data2, PictureType.PNG); - XSLFPictureShape shape2 = slide.createPicture(pdata2); - assertNotNull(shape2.getPictureData()); - assertEquals(1, pdata2.getIndex()); - assertEquals(2, ppt1.getPictureData().size()); - assertArrayEquals(data2, shape2.getPictureData().getData()); - - XMLSlideShow ppt2 = XSLFTestDataSamples.writeOutAndReadBack(ppt1); - ppt1.close(); - List pics = ppt2.getPictureData(); - assertEquals(2, pics.size()); - assertArrayEquals(data1, pics.get(0).getData()); - assertArrayEquals(data2, pics.get(1).getData()); - - List shapes = ppt2.getSlides().get(0).getShapes(); - assertArrayEquals(data1, ((XSLFPictureShape) shapes.get(0)).getPictureData().getData()); - assertArrayEquals(data2, ((XSLFPictureShape) shapes.get(1)).getPictureData().getData()); - ppt2.close(); - } - - @Test - public void testCreateMultiplePictures() throws Exception { - XMLSlideShow ppt1 = new XMLSlideShow(); - XSLFSlide slide1 = ppt1.createSlide(); - XSLFGroupShape group1 = slide1.createGroup(); - - - int pictureIndex = 0; - // first add 20 images to the slide - for (int i = 0; i < 20; i++, pictureIndex++) { - byte[] data = new byte[]{(byte)pictureIndex}; - XSLFPictureData elementData = ppt1.addPicture(data, PictureType.PNG); - assertEquals(pictureIndex, elementData.getIndex()); // added images have indexes 0,1,2....19 - XSLFPictureShape picture = slide1.createPicture(elementData); - // POI saves images as image1.png, image2.png, etc. - String fileName = "image" + (elementData.getIndex()+1) + ".png"; - assertEquals(fileName, picture.getPictureData().getFileName()); - assertArrayEquals(data, picture.getPictureData().getData()); - } - - // and then add next 20 images to a group - for (int i = 0; i < 20; i++, pictureIndex++) { - byte[] data = new byte[]{(byte)pictureIndex}; - XSLFPictureData elementData = ppt1.addPicture(data, PictureType.PNG); - XSLFPictureShape picture = group1.createPicture(elementData); - // POI saves images as image1.png, image2.png, etc. - assertEquals(pictureIndex, elementData.getIndex()); // added images have indexes 0,1,2....19 - String fileName = "image" + (pictureIndex + 1) + ".png"; - assertEquals(fileName, picture.getPictureData().getFileName()); - assertArrayEquals(data, picture.getPictureData().getData()); - } - - // serialize, read back and check that all images are there - - XMLSlideShow ppt2 = XSLFTestDataSamples.writeOutAndReadBack(ppt1); - ppt1.close(); - // pictures keyed by file name - Map pics = new HashMap(); - for(XSLFPictureData p : ppt2.getPictureData()){ - pics.put(p.getFileName(), p); - } - assertEquals(40, pics.size()); - for (int i = 0; i < 40; i++) { - byte[] data1 = new byte[]{(byte)i}; - String fileName = "image" + (i + 1) + ".png"; - XSLFPictureData data = pics.get(fileName); - assertNotNull(data); - assertEquals(fileName, data.getFileName()); - assertArrayEquals(data1, data.getData()); - } - ppt2.close(); - } - - @Test - public void testImageCaching() throws Exception { - XMLSlideShow ppt = new XMLSlideShow(); - byte[] img1 = new byte[]{1,2,3}; - byte[] img2 = new byte[]{3,4,5}; - XSLFPictureData pdata1 = ppt.addPicture(img1, PictureType.PNG); - assertEquals(0, pdata1.getIndex()); - assertEquals(0, ppt.addPicture(img1, PictureType.PNG).getIndex()); - - XSLFPictureData idx2 = ppt.addPicture(img2, PictureType.PNG); - assertEquals(1, idx2.getIndex()); - assertEquals(1, ppt.addPicture(img2, PictureType.PNG).getIndex()); - - XSLFSlide slide1 = ppt.createSlide(); - assertNotNull(slide1); - XSLFSlide slide2 = ppt.createSlide(); - assertNotNull(slide2); - - ppt.close(); - } - - @Test - public void testMerge() throws Exception { - XMLSlideShow ppt1 = new XMLSlideShow(); - byte[] data1 = new byte[100]; - XSLFPictureData pdata1 = ppt1.addPicture(data1, PictureType.JPEG); - - XSLFSlide slide1 = ppt1.createSlide(); - XSLFPictureShape shape1 = slide1.createPicture(pdata1); - CTPicture ctPic1 = (CTPicture)shape1.getXmlObject(); - ctPic1.getNvPicPr().getNvPr().addNewCustDataLst().addNewTags().setId("rId99"); - - XMLSlideShow ppt2 = new XMLSlideShow(); - - XSLFSlide slide2 = ppt2.createSlide().importContent(slide1); - XSLFPictureShape shape2 = (XSLFPictureShape)slide2.getShapes().get(0); - - assertArrayEquals(data1, shape2.getPictureData().getData()); - - CTPicture ctPic2 = (CTPicture)shape2.getXmlObject(); - assertFalse(ctPic2.getNvPicPr().getNvPr().isSetCustDataLst()); - - ppt1.close(); - ppt2.close(); - } - - @Test - public void bug58663() throws IOException { - InputStream is = _slTests.openResourceAsStream("shapes.pptx"); - XMLSlideShow ppt = new XMLSlideShow(is); - is.close(); - - XSLFSlide slide = ppt.getSlides().get(0); - XSLFPictureShape ps = (XSLFPictureShape)slide.getShapes().get(3); - slide.removeShape(ps); - - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - ppt.write(bos); - ppt.close(); - - XMLSlideShow ppt2 = new XMLSlideShow(new ByteArrayInputStream(bos.toByteArray())); - assertTrue(ppt2.getPictureData().isEmpty()); - ppt2.close(); - } - - @Test - public void testTiffImageBug59742() throws Exception { - XMLSlideShow slideShow = new XMLSlideShow(); - final InputStream tiffStream = _slTests.openResourceAsStream("testtiff.tif"); - final byte[] pictureData = IOUtils.toByteArray(tiffStream); - IOUtils.closeQuietly(tiffStream); - - XSLFPictureData pic = slideShow.addPicture(pictureData, PictureType.TIFF); - assertEquals("image/tiff", pic.getContentType()); - assertEquals("image1.tiff", pic.getFileName()); - - slideShow.close(); - } -} \ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFShape.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFShape.java deleted file mode 100644 index 346e98922..000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFShape.java +++ /dev/null @@ -1,108 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.util.List; - -import org.apache.poi.xslf.XSLFTestDataSamples; -import org.junit.Test; -import org.openxmlformats.schemas.drawingml.x2006.main.STTextUnderlineType; - -public class TestXSLFShape { - - @Test - public void testReadTextShapes() throws IOException { - XMLSlideShow ppt = XSLFTestDataSamples.openSampleDocument("shapes.pptx"); - List slides = ppt.getSlides(); - - XSLFSlide slide1 = slides.get(0); - List shapes1 = slide1.getShapes(); - assertEquals(7, shapes1.size()); - assertEquals("TextBox 3", shapes1.get(0).getShapeName()); - XSLFAutoShape sh0 = (XSLFAutoShape) shapes1.get(0); - assertEquals("Learning PPTX", sh0.getText()); - List paragraphs0 = sh0.getTextParagraphs(); - assertEquals(1, paragraphs0.size()); - XSLFTextParagraph p0 = paragraphs0.get(0); - assertEquals("Learning PPTX", p0.getText()); - assertEquals(1, p0.getTextRuns().size()); - XSLFTextRun r0 = p0.getTextRuns().get(0); - assertEquals("Learning PPTX", r0.getRawText()); - - XSLFSlide slide2 = slides.get(1); - List shapes2 = slide2.getShapes(); - assertTrue(shapes2.get(0) instanceof XSLFAutoShape); - assertEquals("PPTX Title", ((XSLFAutoShape) shapes2.get(0)).getText()); - XSLFAutoShape sh1 = (XSLFAutoShape) shapes2.get(0); - List paragraphs1 = sh1.getTextParagraphs(); - assertEquals(1, paragraphs1.size()); - XSLFTextParagraph p1 = paragraphs1.get(0); - assertEquals("PPTX Title", p1.getText()); - List r2 = paragraphs1.get(0).getTextRuns(); - assertEquals(2, r2.size()); - assertEquals("PPTX ", r2.get(0).getRawText()); - assertEquals("Title", r2.get(1).getRawText()); - // Title is underlined - assertEquals(STTextUnderlineType.SNG, r2.get(1).getRPr(false).getU()); - - - assertTrue(shapes2.get(1) instanceof XSLFAutoShape); - assertEquals("Subtitle\nAnd second line", ((XSLFAutoShape) shapes2.get(1)).getText()); - XSLFAutoShape sh2 = (XSLFAutoShape) shapes2.get(1); - List paragraphs2 = sh2.getTextParagraphs(); - assertEquals(2, paragraphs2.size()); - assertEquals("Subtitle", paragraphs2.get(0).getText()); - assertEquals("And second line", paragraphs2.get(1).getText()); - - assertEquals(1, paragraphs2.get(0).getTextRuns().size()); - assertEquals(1, paragraphs2.get(1).getTextRuns().size()); - - assertEquals("Subtitle", paragraphs2.get(0).getTextRuns().get(0).getRawText()); - assertTrue(paragraphs2.get(0).getTextRuns().get(0).getRPr(false).getB()); - assertEquals("And second line", paragraphs2.get(1).getTextRuns().get(0).getRawText()); - - ppt.close(); - } - - @Test - public void testCreateShapes() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - XSLFSlide slide = ppt.createSlide(); - assertTrue(slide.getShapes().isEmpty()); - - XSLFTextBox textBox = slide.createTextBox(); - - assertEquals(1, slide.getShapes().size()); - assertSame(textBox, slide.getShapes().get(0)); - - assertEquals("", textBox.getText()); - // FIXME: is this correct? Should it be starting out with 0 or 1 text paragraphs? - assertEquals(1, textBox.getTextParagraphs().size()); - textBox.addNewTextParagraph().addNewTextRun().setText("Apache"); - textBox.addNewTextParagraph().addNewTextRun().setText("POI"); - assertEquals("Apache\nPOI", textBox.getText()); - assertEquals(3, textBox.getTextParagraphs().size()); - - ppt.close(); - } - -} \ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFShapeContainer.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFShapeContainer.java deleted file mode 100644 index 217976def..000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFShapeContainer.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -package org.apache.poi.xslf.usermodel; - -import static org.junit.Assert.*; - -import org.junit.Test; - -/** - * test common operations on containers of shapes (sheets and groups of shapes) - * - * @author Yegor Kozlov - */ -public class TestXSLFShapeContainer { - - @SuppressWarnings("unused") - public void verifyContainer(XSLFShapeContainer container) { - container.clear(); - assertEquals(0, container.getShapes().size()); - - XSLFGroupShape shape1 = container.createGroup(); - assertEquals(1, container.getShapes().size()); - - XSLFTextBox shape2 = container.createTextBox(); - assertEquals(2, container.getShapes().size()); - - XSLFAutoShape shape3 = container.createAutoShape(); - assertEquals(3, container.getShapes().size()); - - XSLFConnectorShape shape4 = container.createConnector(); - assertEquals(4, container.getShapes().size()); - - container.clear(); - assertEquals(0, container.getShapes().size()); - } - - @Test - public void testSheet() { - XMLSlideShow ppt = new XMLSlideShow(); - XSLFSheet sheet = ppt.createSlide(); - verifyContainer(sheet); - - - XSLFGroupShape group = sheet.createGroup(); - verifyContainer(group); - - } -} \ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFSheet.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFSheet.java deleted file mode 100644 index b68577aca..000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFSheet.java +++ /dev/null @@ -1,75 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.usermodel; - -import static org.junit.Assert.*; - -import java.io.IOException; -import java.util.List; - -import org.apache.poi.xslf.XSLFTestDataSamples; -import org.junit.Test; - -/** - * test common properties for sheets (slides, masters, layouts, etc.) - * - * @author Yegor Kozlov - */ -public class TestXSLFSheet { - - @Test - public void testCreateShapes() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - XSLFSlide slide = ppt.createSlide(); - assertTrue(slide.getShapes().isEmpty()); - - XSLFSimpleShape shape1 = slide.createAutoShape(); - assertEquals(1, slide.getShapes().size()); - assertSame(shape1, slide.getShapes().get(0)); - - XSLFTextBox shape2 = slide.createTextBox(); - assertEquals(2, slide.getShapes().size()); - assertSame(shape1, slide.getShapes().get(0)); - assertSame(shape2, slide.getShapes().get(1)); - - XSLFConnectorShape shape3 = slide.createConnector(); - assertEquals(3, slide.getShapes().size()); - assertSame(shape1, slide.getShapes().get(0)); - assertSame(shape2, slide.getShapes().get(1)); - assertSame(shape3, slide.getShapes().get(2)); - - XSLFGroupShape shape4 = slide.createGroup(); - assertEquals(4, slide.getShapes().size()); - assertSame(shape1, slide.getShapes().get(0)); - assertSame(shape2, slide.getShapes().get(1)); - assertSame(shape3, slide.getShapes().get(2)); - assertSame(shape4, slide.getShapes().get(3)); - - XMLSlideShow ppt2 = XSLFTestDataSamples.writeOutAndReadBack(ppt); - slide = ppt2.getSlides().get(0); - List shapes = slide.getShapes(); - assertEquals(4, shapes.size()); - - assertTrue(shapes.get(0) instanceof XSLFAutoShape); - assertTrue(shapes.get(1) instanceof XSLFTextBox); - assertTrue(shapes.get(2) instanceof XSLFConnectorShape); - assertTrue(shapes.get(3) instanceof XSLFGroupShape); - - ppt.close(); - ppt2.close(); - } -} \ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFSimpleShape.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFSimpleShape.java deleted file mode 100644 index 4531ddd85..000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFSimpleShape.java +++ /dev/null @@ -1,386 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Graphics2D; -import java.awt.RenderingHints; -import java.awt.image.BufferedImage; -import java.io.IOException; -import java.util.List; - -import org.apache.poi.sl.draw.DrawFactory; -import org.apache.poi.sl.draw.geom.TestPresetGeometries; -import org.apache.poi.sl.usermodel.Placeholder; -import org.apache.poi.sl.usermodel.Slide; -import org.apache.poi.sl.usermodel.StrokeStyle.LineCap; -import org.apache.poi.sl.usermodel.StrokeStyle.LineDash; -import org.apache.poi.util.Units; -import org.apache.poi.xslf.XSLFTestDataSamples; -import org.apache.xmlbeans.XmlObject; -import org.junit.Test; -import org.openxmlformats.schemas.drawingml.x2006.main.CTEffectStyleItem; -import org.openxmlformats.schemas.drawingml.x2006.main.CTEffectStyleList; -import org.openxmlformats.schemas.drawingml.x2006.main.CTOuterShadowEffect; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPresetGeometry2D; -import org.openxmlformats.schemas.drawingml.x2006.main.CTSchemeColor; -import org.openxmlformats.schemas.drawingml.x2006.main.CTShapeProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTStyleMatrix; -import org.openxmlformats.schemas.drawingml.x2006.main.STLineCap; -import org.openxmlformats.schemas.drawingml.x2006.main.STPresetLineDashVal; -import org.openxmlformats.schemas.drawingml.x2006.main.STShapeType; - -public class TestXSLFSimpleShape { - - @Test - public void testLineStyles() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - XSLFSlide slide = ppt.createSlide(); - - XSLFSimpleShape shape = slide.createAutoShape(); - assertEquals(1, slide.getShapes().size()); - // line properties are not set by default - assertFalse(getSpPr(shape).isSetLn()); - - assertEquals(0., shape.getLineWidth(), 0); - assertEquals(null, shape.getLineColor()); - assertEquals(null, shape.getLineDash()); - assertEquals(null, shape.getLineCap()); - - shape.setLineWidth(0); - shape.setLineColor(null); - shape.setLineDash(null); - shape.setLineCap(null); - - assertTrue(getSpPr(shape).isSetLn()); - assertTrue(getSpPr(shape).getLn().isSetNoFill()); - - // line width - shape.setLineWidth(1.0); - assertEquals(1.0, shape.getLineWidth(), 0); - assertEquals(Units.EMU_PER_POINT, getSpPr(shape).getLn().getW()); - shape.setLineWidth(5.5); - assertEquals(5.5, shape.getLineWidth(), 0); - assertEquals(Units.toEMU(5.5), getSpPr(shape).getLn().getW()); - shape.setLineWidth(0.0); - // setting line width to zero unsets the W attribute - assertFalse(getSpPr(shape).getLn().isSetW()); - - // line cap - shape.setLineCap(LineCap.FLAT); - assertEquals(LineCap.FLAT, shape.getLineCap()); - assertEquals(STLineCap.FLAT, getSpPr(shape).getLn().getCap()); - shape.setLineCap(LineCap.SQUARE); - assertEquals(LineCap.SQUARE, shape.getLineCap()); - assertEquals(STLineCap.SQ, getSpPr(shape).getLn().getCap()); - shape.setLineCap(LineCap.ROUND); - assertEquals(LineCap.ROUND, shape.getLineCap()); - assertEquals(STLineCap.RND, getSpPr(shape).getLn().getCap()); - shape.setLineCap(null); - // setting cap to null unsets the Cap attribute - assertFalse(getSpPr(shape).getLn().isSetCap()); - - // line dash - shape.setLineDash(LineDash.SOLID); - assertEquals(LineDash.SOLID, shape.getLineDash()); - assertEquals(STPresetLineDashVal.SOLID, getSpPr(shape).getLn().getPrstDash().getVal()); - shape.setLineDash(LineDash.DASH_DOT); - assertEquals(LineDash.DASH_DOT, shape.getLineDash()); - assertEquals(STPresetLineDashVal.DASH_DOT, getSpPr(shape).getLn().getPrstDash().getVal()); - shape.setLineDash(LineDash.LG_DASH_DOT); - assertEquals(LineDash.LG_DASH_DOT, shape.getLineDash()); - assertEquals(STPresetLineDashVal.LG_DASH_DOT, getSpPr(shape).getLn().getPrstDash().getVal()); - shape.setLineDash(null); - // setting dash width to null unsets the Dash element - assertFalse(getSpPr(shape).getLn().isSetPrstDash()); - - // line color - assertFalse(getSpPr(shape).getLn().isSetSolidFill()); - shape.setLineColor(Color.RED); - assertEquals(Color.RED, shape.getLineColor()); - assertTrue(getSpPr(shape).getLn().isSetSolidFill()); - shape.setLineColor(Color.BLUE); - assertEquals(Color.BLUE, shape.getLineColor()); - assertTrue(getSpPr(shape).getLn().isSetSolidFill()); - shape.setLineColor(null); - assertEquals(null, shape.getLineColor()); - // setting dash width to null unsets the SolidFill element - assertFalse(getSpPr(shape).getLn().isSetSolidFill()); - - XSLFSimpleShape ln2 = slide.createAutoShape(); - ln2.setLineDash(LineDash.DOT); - assertEquals(LineDash.DOT, ln2.getLineDash()); - ln2.setLineWidth(0.); - assertEquals(0., ln2.getLineWidth(), 0); - - XSLFSimpleShape ln3 = slide.createAutoShape(); - ln3.setLineWidth(1.); - assertEquals(1., ln3.getLineWidth(), 0); - ln3.setLineDash(null); - assertEquals(null, ln3.getLineDash()); - ln3.setLineCap(null); - assertEquals(null, ln3.getLineDash()); - - ppt.close(); - } - - @Test - public void testFill() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - XSLFSlide slide = ppt.createSlide(); - - XSLFAutoShape shape = slide.createAutoShape(); - // line properties are not set by default - assertFalse(getSpPr(shape).isSetSolidFill()); - - assertNull(shape.getFillColor()); - shape.setFillColor(null); - assertNull(shape.getFillColor()); - assertFalse(getSpPr(shape).isSetSolidFill()); - - shape.setFillColor(Color.RED); - assertEquals(Color.RED, shape.getFillColor()); - shape.setFillColor(Color.DARK_GRAY); - assertEquals(Color.DARK_GRAY, shape.getFillColor()); - assertTrue(getSpPr(shape).isSetSolidFill()); - - shape.setFillColor(null); - assertNull(shape.getFillColor()); - assertFalse(getSpPr(shape).isSetSolidFill()); - ppt.close(); - } - - @Test - public void testDefaultProperties() throws IOException { - XMLSlideShow ppt = XSLFTestDataSamples.openSampleDocument("shapes.pptx"); - - XSLFSlide slide6 = ppt.getSlides().get(5); - List shapes = slide6.getShapes(); - for(XSLFShape xs : shapes){ - XSLFSimpleShape s = (XSLFSimpleShape)xs; - // all shapes have a theme color="accent1" - assertEquals("accent1", s.getSpStyle().getFillRef().getSchemeClr().getVal().toString()); - assertEquals(2.0, s.getLineWidth(), 0); - assertEquals(LineCap.FLAT, s.getLineCap()); - assertEquals(new Color(79,129,189), s.getLineColor()); - } - - XSLFSimpleShape s0 = (XSLFSimpleShape) shapes.get(0); - // fill is not set - assertNull(getSpPr(s0).getSolidFill()); - //assertEquals(slide6.getTheme().getColor("accent1").getColor(), s0.getFillColor()); - assertEquals(new Color(79, 129, 189), s0.getFillColor()); - - // lighter 80% - XSLFSimpleShape s1 = (XSLFSimpleShape)shapes.get(1); - CTSchemeColor ref1 = getSpPr(s1).getSolidFill().getSchemeClr(); - assertEquals(1, ref1.sizeOfLumModArray()); - assertEquals(1, ref1.sizeOfLumOffArray()); - assertEquals(20000, ref1.getLumModArray(0).getVal()); - assertEquals(80000, ref1.getLumOffArray(0).getVal()); - assertEquals("accent1", ref1.getVal().toString()); - assertEquals(new Color(220, 230, 242), s1.getFillColor()); - - // lighter 60% - XSLFSimpleShape s2 = (XSLFSimpleShape)shapes.get(2); - CTSchemeColor ref2 = getSpPr(s2).getSolidFill().getSchemeClr(); - assertEquals(1, ref2.sizeOfLumModArray()); - assertEquals(1, ref2.sizeOfLumOffArray()); - assertEquals(40000, ref2.getLumModArray(0).getVal()); - assertEquals(60000, ref2.getLumOffArray(0).getVal()); - assertEquals("accent1", ref2.getVal().toString()); - assertEquals(new Color(185, 205, 229), s2.getFillColor()); - - // lighter 40% - XSLFSimpleShape s3 = (XSLFSimpleShape)shapes.get(3); - CTSchemeColor ref3 = getSpPr(s3).getSolidFill().getSchemeClr(); - assertEquals(1, ref3.sizeOfLumModArray()); - assertEquals(1, ref3.sizeOfLumOffArray()); - assertEquals(60000, ref3.getLumModArray(0).getVal()); - assertEquals(40000, ref3.getLumOffArray(0).getVal()); - assertEquals("accent1", ref3.getVal().toString()); - assertEquals(new Color(149, 179, 215), s3.getFillColor()); - - // darker 25% - XSLFSimpleShape s4 = (XSLFSimpleShape)shapes.get(4); - CTSchemeColor ref4 = getSpPr(s4).getSolidFill().getSchemeClr(); - assertEquals(1, ref4.sizeOfLumModArray()); - assertEquals(0, ref4.sizeOfLumOffArray()); - assertEquals(75000, ref4.getLumModArray(0).getVal()); - assertEquals("accent1", ref3.getVal().toString()); - assertEquals(new Color(55, 96, 146), s4.getFillColor()); - - XSLFSimpleShape s5 = (XSLFSimpleShape)shapes.get(5); - CTSchemeColor ref5 = getSpPr(s5).getSolidFill().getSchemeClr(); - assertEquals(1, ref5.sizeOfLumModArray()); - assertEquals(0, ref5.sizeOfLumOffArray()); - assertEquals(50000, ref5.getLumModArray(0).getVal()); - assertEquals("accent1", ref5.getVal().toString()); - assertEquals(new Color(37, 64, 97), s5.getFillColor()); - - ppt.close(); - } - - @Test - public void testAnchor() throws IOException { - XMLSlideShow ppt = XSLFTestDataSamples.openSampleDocument("shapes.pptx"); - List slide = ppt.getSlides(); - - XSLFSlide slide2 = slide.get(1); - XSLFSlideLayout layout2 = slide2.getSlideLayout(); - List shapes2 = slide2.getShapes(); - XSLFTextShape sh1 = (XSLFTextShape)shapes2.get(0); - assertEquals(Placeholder.CENTERED_TITLE, sh1.getTextType()); - assertEquals("PPTX Title", sh1.getText()); - assertFalse(getSpPr(sh1).isSetXfrm()); // xfrm is not set, the query is delegated to the slide layout - assertEquals(sh1.getAnchor(), layout2.getTextShapeByType(Placeholder.CENTERED_TITLE).getAnchor()); - - XSLFTextShape sh2 = (XSLFTextShape)shapes2.get(1); - assertEquals("Subtitle\nAnd second line", sh2.getText()); - assertEquals(Placeholder.SUBTITLE, sh2.getTextType()); - assertFalse(getSpPr(sh2).isSetXfrm()); // xfrm is not set, the query is delegated to the slide layout - assertEquals(sh2.getAnchor(), layout2.getTextShapeByType(Placeholder.SUBTITLE).getAnchor()); - - XSLFSlide slide5 = slide.get(4); - XSLFSlideLayout layout5 = slide5.getSlideLayout(); - XSLFTextShape shTitle = slide5.getTextShapeByType(Placeholder.TITLE); - assertEquals("Hyperlinks", shTitle.getText()); - // xfrm is not set, the query is delegated to the slide layout - assertFalse(getSpPr(shTitle).isSetXfrm()); - // xfrm is not set, the query is delegated to the slide master - assertFalse(getSpPr(layout5.getTextShapeByType(Placeholder.TITLE)).isSetXfrm()); - assertTrue(getSpPr(layout5.getSlideMaster().getTextShapeByType(Placeholder.TITLE)).isSetXfrm()); - assertEquals(shTitle.getAnchor(), layout5.getSlideMaster().getTextShapeByType(Placeholder.TITLE).getAnchor()); - - ppt.close(); - } - - @SuppressWarnings("unused") - @Test - public void testShadowEffects() throws IOException{ - XMLSlideShow ppt = new XMLSlideShow(); - XSLFSlide slide = ppt.createSlide(); - CTStyleMatrix styleMatrix = slide.getTheme().getXmlObject().getThemeElements().getFmtScheme(); - CTEffectStyleList lst = styleMatrix.getEffectStyleLst(); - assertNotNull(lst); - for(CTEffectStyleItem ef : lst.getEffectStyleArray()){ - CTOuterShadowEffect obj = ef.getEffectLst().getOuterShdw(); - } - ppt.close(); - } - - @Test - public void testValidGeometry() throws Exception { - XMLSlideShow ppt = new XMLSlideShow(); - XSLFSlide slide = ppt.createSlide(); - - XSLFSimpleShape shape = slide.createAutoShape(); - CTShapeProperties spPr = getSpPr(shape); - - CTPresetGeometry2D prstGeom = CTPresetGeometry2D.Factory.newInstance(); - prstGeom.setPrst(STShapeType.Enum.forInt(1)); - - assertNotNull(prstGeom.getPrst()); - assertNotNull(prstGeom.getPrst().toString()); - assertNotNull(spPr.getPrstGeom()); - spPr.setPrstGeom(prstGeom); - assertNotNull(spPr.getPrstGeom().getPrst()); - assertNotNull(spPr.getPrstGeom().getPrst().toString()); - - assertNotNull(shape.getGeometry()); - - ppt.close(); - } - - - @Test - public void testInvalidGeometry() throws Exception { - XMLSlideShow ppt = new XMLSlideShow(); - XSLFSlide slide = ppt.createSlide(); - - XSLFSimpleShape shape = slide.createAutoShape(); - CTShapeProperties spPr = getSpPr(shape); - - CTPresetGeometry2D prstGeom = CTPresetGeometry2D.Factory.newInstance(); - prstGeom.setPrst(STShapeType.Enum.forInt(1)); - - assertNotNull(prstGeom.getPrst()); - assertNotNull(prstGeom.getPrst().toString()); - assertNotNull(spPr.getPrstGeom()); - spPr.setPrstGeom(prstGeom); - assertNotNull(spPr.getPrstGeom().getPrst()); - assertNotNull(spPr.getPrstGeom().getPrst().toString()); - - try { - // cause the geometries to be not found - TestPresetGeometries.clearPreset(); - try { - shape.getGeometry(); - fail("Should fail without the geometry"); - } catch (IllegalStateException e) { - assertTrue(e.getMessage(), e.getMessage().contains("line")); - } - } finally { - // reset to not affect other tests - TestPresetGeometries.resetPreset(); - } - - ppt.close(); - } - - @SuppressWarnings("Duplicates") - @Test - public void testArrayStoreException() throws IOException { - XMLSlideShow ppt = XSLFTestDataSamples.openSampleDocument("aascu.org_workarea_downloadasset.aspx_id=5864.pptx"); - Dimension pgsize = ppt.getPageSize(); - - for (Slide s : ppt.getSlides()) { - //System.out.println("Slide: " + s); - - BufferedImage img = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_ARGB); - Graphics2D graphics = img.createGraphics(); - DrawFactory.getInstance(graphics).fixFonts(graphics); - - // default rendering options - graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); - graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); - graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); - - // draw stuff - s.draw(graphics); - - graphics.dispose(); - img.flush(); - } - ppt.close(); - } - - static CTShapeProperties getSpPr(XSLFShape shape) { - XmlObject xo = shape.getShapeProperties(); - assertTrue(xo instanceof CTShapeProperties); - return (CTShapeProperties)xo; - } -} \ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFSlide.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFSlide.java deleted file mode 100644 index fbf458976..000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFSlide.java +++ /dev/null @@ -1,197 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.usermodel; - -import static org.apache.poi.sl.TestCommonSL.sameColor; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.awt.Color; -import java.io.IOException; -import java.util.List; - -import org.apache.poi.xslf.XSLFTestDataSamples; -import org.junit.Test; - -/** - * @author Yegor Kozlov - */ -public class TestXSLFSlide { - - @Test - public void testReadShapes() throws IOException { - XMLSlideShow ppt = XSLFTestDataSamples.openSampleDocument("shapes.pptx"); - List slides = ppt.getSlides(); - - XSLFSlide slide1 = slides.get(0); - List shapes1 = slide1.getShapes(); - assertEquals(7, shapes1.size()); - assertEquals("TextBox 3", shapes1.get(0).getShapeName()); - assertTrue(shapes1.get(0) instanceof XSLFTextBox); - XSLFAutoShape sh0 = (XSLFAutoShape)shapes1.get(0); - assertEquals("Learning PPTX", sh0.getText()); - - - assertEquals("Straight Connector 5", shapes1.get(1).getShapeName()); - assertTrue(shapes1.get(1) instanceof XSLFConnectorShape); - - assertEquals("Freeform 6", shapes1.get(2).getShapeName()); - assertTrue(shapes1.get(2) instanceof XSLFFreeformShape); - XSLFAutoShape sh2 = (XSLFAutoShape)shapes1.get(2); - assertEquals("Cloud", sh2.getText()); - - assertEquals("Picture 1", shapes1.get(3).getShapeName()); - assertTrue(shapes1.get(3) instanceof XSLFPictureShape); - - assertEquals("Table 2", shapes1.get(4).getShapeName()); - assertTrue(shapes1.get(4) instanceof XSLFGraphicFrame); - - assertEquals("Straight Arrow Connector 7", shapes1.get(5).getShapeName()); - assertTrue(shapes1.get(5) instanceof XSLFConnectorShape); - - assertEquals("Elbow Connector 9", shapes1.get(6).getShapeName()); - assertTrue(shapes1.get(6) instanceof XSLFConnectorShape); - - // titles on slide2 - XSLFSlide slide2 = slides.get(1); - List shapes2 = slide2.getShapes(); - assertEquals(2, shapes2.size()); - assertTrue(shapes2.get(0) instanceof XSLFAutoShape); - assertEquals("PPTX Title", ((XSLFAutoShape)shapes2.get(0)).getText()); - assertTrue(shapes2.get(1) instanceof XSLFAutoShape); - assertEquals("Subtitle\nAnd second line", ((XSLFAutoShape)shapes2.get(1)).getText()); - - // group shape on slide3 - XSLFSlide slide3 = slides.get(2); - List shapes3 = slide3.getShapes(); - assertEquals(1, shapes3.size()); - assertTrue(shapes3.get(0) instanceof XSLFGroupShape); - List groupShapes = ((XSLFGroupShape)shapes3.get(0)).getShapes(); - assertEquals(3, groupShapes.size()); - assertTrue(groupShapes.get(0) instanceof XSLFAutoShape); - assertEquals("Rectangle 1", groupShapes.get(0).getShapeName()); - - assertTrue(groupShapes.get(1) instanceof XSLFAutoShape); - assertEquals("Oval 2", groupShapes.get(1).getShapeName()); - - assertTrue(groupShapes.get(2) instanceof XSLFAutoShape); - assertEquals("Right Arrow 3", groupShapes.get(2).getShapeName()); - - XSLFSlide slide4 = slides.get(3); - List shapes4 = slide4.getShapes(); - assertEquals(1, shapes4.size()); - assertTrue(shapes4.get(0) instanceof XSLFTable); - XSLFTable tbl = (XSLFTable)shapes4.get(0); - assertEquals(3, tbl.getNumberOfColumns()); - assertEquals(6, tbl.getNumberOfRows()); - - ppt.close(); - } - - @Test - public void testCreateSlide() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - assertEquals(0, ppt.getSlides().size()); - - XSLFSlide slide = ppt.createSlide(); - assertTrue(slide.getFollowMasterGraphics()); - slide.setFollowMasterGraphics(false); - assertFalse(slide.getFollowMasterGraphics()); - slide.setFollowMasterGraphics(true); - assertTrue(slide.getFollowMasterGraphics()); - - ppt.close(); - } - - @Test - public void testImportContent() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - - XMLSlideShow src = XSLFTestDataSamples.openSampleDocument("themes.pptx"); - - // create a blank slide and import content from the 4th slide of themes.pptx - XSLFSlide slide1 = ppt.createSlide().importContent(src.getSlides().get(3)); - List shapes1 = slide1.getShapes(); - assertEquals(2, shapes1.size()); - - XSLFTextShape sh1 = (XSLFTextShape)shapes1.get(0); - assertEquals("Austin Theme", sh1.getText()); - XSLFTextRun r1 = sh1.getTextParagraphs().get(0).getTextRuns().get(0); - assertEquals("Century Gothic", r1.getFontFamily()); - assertEquals(40.0, r1.getFontSize(), 0); - assertTrue(r1.isBold()); - assertTrue(r1.isItalic()); - assertTrue(sameColor(new Color(148, 198, 0), r1.getFontColor())); - assertNull(sh1.getFillColor()); - assertNull(sh1.getLineColor()); - - XSLFTextShape sh2 = (XSLFTextShape)shapes1.get(1); - assertEquals( - "Text in a autoshape is white\n" + - "Fill: RGB(148, 198,0)", sh2.getText()); - XSLFTextRun r2 = sh2.getTextParagraphs().get(0).getTextRuns().get(0); - assertEquals("Century Gothic", r2.getFontFamily()); - assertEquals(18.0, r2.getFontSize(), 0); - assertFalse(r2.isBold()); - assertFalse(r2.isItalic()); - assertTrue(sameColor(Color.white, r2.getFontColor())); - assertEquals(new Color(148, 198, 0), sh2.getFillColor()); - assertEquals(new Color(148, 198, 0), sh2.getLineColor()); // slightly different from PowerPoint! - - // the 5th slide has a picture and a texture fill - XSLFSlide slide2 = ppt.createSlide().importContent(src.getSlides().get(4)); - List shapes2 = slide2.getShapes(); - assertEquals(2, shapes2.size()); - - XSLFTextShape sh3 = (XSLFTextShape)shapes2.get(0); - assertEquals("This slide overrides master background with a texture fill", sh3.getText()); - XSLFTextRun r3 = sh3.getTextParagraphs().get(0).getTextRuns().get(0); - assertEquals("Century Gothic", r3.getFontFamily()); - //assertEquals(32.4.0, r3.getFontSize()); - assertTrue(r3.isBold()); - assertTrue(r3.isItalic()); - assertTrue(sameColor(new Color(148, 198, 0), r3.getFontColor())); - assertNull(sh3.getFillColor()); - assertNull(sh3.getLineColor()); - - XSLFPictureShape sh4 = (XSLFPictureShape)shapes2.get(1); - XSLFPictureShape srcPic = (XSLFPictureShape)src.getSlides().get(4).getShapes().get(1); - assertArrayEquals(sh4.getPictureData().getData(), srcPic.getPictureData().getData()); - - ppt.close(); - } - - @Test - public void testMergeSlides() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - String[] pptx = {"shapes.pptx", "themes.pptx", "layouts.pptx", "backgrounds.pptx"}; - - for(String arg : pptx){ - XMLSlideShow src = XSLFTestDataSamples.openSampleDocument(arg); - - for(XSLFSlide srcSlide : src.getSlides()){ - ppt.createSlide().importContent(srcSlide); - } - } - assertEquals(30, ppt.getSlides().size()); - - ppt.close(); - } -} \ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFSlideShow.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFSlideShow.java deleted file mode 100644 index 61e4438f2..000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFSlideShow.java +++ /dev/null @@ -1,149 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; - -import java.awt.Dimension; -import java.io.IOException; -import java.util.List; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.xslf.XSLFTestDataSamples; -import org.junit.Test; - -/** - * @author Yegor Kozlov - */ -public class TestXSLFSlideShow { - @Test - public void testCreateSlide() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - assertEquals(0, ppt.getSlides().size()); - - XSLFSlide slide1 = ppt.createSlide(); - assertEquals(1, ppt.getSlides().size()); - assertSame(slide1, ppt.getSlides().get(0)); - - List rels = slide1.getRelations(); - assertEquals(1, rels.size()); - assertEquals(slide1.getSlideMaster().getLayout(SlideLayout.BLANK), rels.get(0)); - - XSLFSlide slide2 = ppt.createSlide(); - assertEquals(2, ppt.getSlides().size()); - assertSame(slide2, ppt.getSlides().get(1)); - - ppt.setSlideOrder(slide2, 0); - assertSame(slide2, ppt.getSlides().get(0)); - assertSame(slide1, ppt.getSlides().get(1)); - - XMLSlideShow ppt2 = XSLFTestDataSamples.writeOutAndReadBack(ppt); - assertEquals(2, ppt2.getSlides().size()); - rels = ppt2.getSlides().get(0).getRelations(); - - ppt2.close(); - ppt.close(); - } - - @Test - public void testRemoveSlide() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - assertEquals(0, ppt.getSlides().size()); - - XSLFSlide slide1 = ppt.createSlide(); - XSLFSlide slide2 = ppt.createSlide(); - - assertEquals(2, ppt.getSlides().size()); - assertSame(slide1, ppt.getSlides().get(0)); - assertSame(slide2, ppt.getSlides().get(1)); - - XSLFSlide removedSlide = ppt.removeSlide(0); - assertSame(slide1, removedSlide); - - assertEquals(1, ppt.getSlides().size()); - assertSame(slide2, ppt.getSlides().get(0)); - - XMLSlideShow ppt2 = XSLFTestDataSamples.writeOutAndReadBack(ppt); - assertEquals(1, ppt2.getSlides().size()); - - ppt2.close(); - ppt.close(); - } - - @Test - public void testDimension() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - Dimension sz = ppt.getPageSize(); - assertEquals(720, sz.width); - assertEquals(540, sz.height); - ppt.setPageSize(new Dimension(792, 612)); - sz = ppt.getPageSize(); - assertEquals(792, sz.width); - assertEquals(612, sz.height); - ppt.close(); - } - - @Test - public void testSlideMasters() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - List masters = ppt.getSlideMasters(); - assertEquals(1, masters.size()); - - XSLFSlide slide = ppt.createSlide(); - assertSame(masters.get(0), slide.getSlideMaster()); - ppt.close(); - } - - @Test - public void testSlideLayout() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - List masters = ppt.getSlideMasters(); - assertEquals(1, masters.size()); - - XSLFSlide slide = ppt.createSlide(); - XSLFSlideLayout layout = slide.getSlideLayout(); - assertNotNull(layout); - - assertSame(masters.get(0), layout.getSlideMaster()); - ppt.close(); - } - - @Test - public void testSlideLayoutNames() throws IOException { - final String names[] = { - "Blank", "Title Only", "Section Header", "Picture with Caption", "Title and Content" - , "Title Slide", "Title and Vertical Text", "Vertical Title and Text", "Comparison" - , "Two Content", "Content with Caption" - }; - XMLSlideShow ppt = XSLFTestDataSamples.openSampleDocument("layouts.pptx"); - for (String name : names) { - assertNotNull(ppt.findLayout(name)); - } - final SlideLayout layTypes[] = { - SlideLayout.BLANK, SlideLayout.TITLE_ONLY, SlideLayout.SECTION_HEADER - , SlideLayout.PIC_TX, SlideLayout.TITLE_AND_CONTENT, SlideLayout.TITLE - , SlideLayout.VERT_TX, SlideLayout.VERT_TITLE_AND_TX, SlideLayout.TWO_TX_TWO_OBJ - , SlideLayout.TWO_OBJ, SlideLayout.OBJ_TX - }; - for (SlideLayout sl : layTypes){ - assertNotNull(ppt.getSlideMasters().get(0).getLayout(sl)); - } - ppt.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFSlideShowFactory.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFSlideShowFactory.java deleted file mode 100644 index 9bfc695a8..000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFSlideShowFactory.java +++ /dev/null @@ -1,119 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xslf.usermodel; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.security.GeneralSecurityException; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.poifs.crypt.EncryptionInfo; -import org.apache.poi.poifs.crypt.EncryptionMode; -import org.apache.poi.poifs.crypt.Encryptor; -import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; -import org.apache.poi.sl.usermodel.BaseTestSlideShowFactory; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.TempFile; -import org.junit.Test; -import org.junit.Rule; -import org.junit.rules.ExpectedException; - -public final class TestXSLFSlideShowFactory extends BaseTestSlideShowFactory { - private static POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); - private static final String filename = "SampleShow.pptx"; - private static final String password = "opensesame"; - private static final String removeExpectedExceptionMsg = - "This functionality this unit test is trying to test is now passing. " + - "The unit test needs to be updated by deleting the expected exception code. Status and close any related bugs."; - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - public void testFactoryFromFile() throws Exception { - // Remove thrown.* when bug 58779 is resolved - // In the mean time, this function will modify SampleShow.pptx on disk. - thrown.expect(AssertionError.class); - // thrown.expectCause(Matcher); - thrown.expectMessage("SampleShow.pptx sample file was modified as a result of closing the slideshow"); - thrown.reportMissingExceptionWithMessage("Bug 58779: " + removeExpectedExceptionMsg); - - testFactoryFromFile(filename); - } - - @Test - public void testFactoryFromStream() throws Exception { - testFactoryFromStream(filename); - } - - @Test - public void testFactoryFromNative() throws Exception { - // Remove thrown.* when unit test for XSLF SlideShowFactory.create(OPCPackage) is implemented - thrown.expect(UnsupportedOperationException.class); - thrown.expectMessage("Test not implemented"); - thrown.reportMissingExceptionWithMessage(removeExpectedExceptionMsg); - - testFactoryFromNative(filename); - } - - @Test - public void testFactoryFromProtectedFile() throws Exception { - File pFile = createProtected(); - testFactoryFromProtectedFile(pFile.getAbsolutePath(), password); - } - - @Test - public void testFactoryFromProtectedStream() throws Exception { - File pFile = createProtected(); - testFactoryFromProtectedStream(pFile.getAbsolutePath(), password); - } - - @Test - public void testFactoryFromProtectedNative() throws Exception { - File pFile = createProtected(); - testFactoryFromProtectedNative(pFile.getAbsolutePath(), password); - } - - private static File createProtected() throws IOException, GeneralSecurityException { - return createProtected(filename, password); - } - - private static File createProtected(String basefile, String password) - throws IOException, GeneralSecurityException { - NPOIFSFileSystem fs = new NPOIFSFileSystem(); - EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile); - Encryptor enc = info.getEncryptor(); - enc.confirmPassword(password); - InputStream fis = _slTests.openResourceAsStream(basefile); - OutputStream os = enc.getDataStream(fs); - IOUtils.copy(fis, os); - os.close(); - fis.close(); - - File tf = TempFile.createTempFile("test-xslf-slidefactory", ".pptx"); - FileOutputStream fos = new FileOutputStream(tf); - fs.writeFilesystem(fos); - fos.close(); - fs.close(); - - return tf; - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTable.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTable.java deleted file mode 100644 index 736d276d9..000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTable.java +++ /dev/null @@ -1,218 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Graphics2D; -import java.awt.RenderingHints; -import java.awt.geom.Rectangle2D; -import java.awt.image.BufferedImage; -import java.io.IOException; -import java.util.List; - -import org.apache.poi.sl.draw.DrawFactory; -import org.apache.poi.sl.usermodel.Slide; -import org.apache.poi.sl.usermodel.TableCell.BorderEdge; -import org.apache.poi.sl.usermodel.VerticalAlignment; -import org.apache.poi.xslf.XSLFTestDataSamples; -import org.junit.Test; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTableCell; -import org.openxmlformats.schemas.presentationml.x2006.main.CTGraphicalObjectFrame; - -public class TestXSLFTable { - @Test - public void testRead() throws IOException { - XMLSlideShow ppt = XSLFTestDataSamples.openSampleDocument("shapes.pptx"); - - XSLFSlide slide = ppt.getSlides().get(3); - List shapes = slide.getShapes(); - assertEquals(1, shapes.size()); - assertTrue(shapes.get(0) instanceof XSLFTable); - XSLFTable tbl = (XSLFTable)shapes.get(0); - assertEquals(3, tbl.getNumberOfColumns()); - assertEquals(6, tbl.getNumberOfRows()); - assertNotNull(tbl.getCTTable()); - - List rows = tbl.getRows(); - assertEquals(6, rows.size()); - - assertEquals(90.0, tbl.getColumnWidth(0), 0); - assertEquals(240.0, tbl.getColumnWidth(1), 0); - assertEquals(150.0, tbl.getColumnWidth(2), 0); - - for(XSLFTableRow row : tbl){ - // all rows have the same height - assertEquals(29.2, row.getHeight(), 0); - } - - XSLFTableRow row0 = rows.get(0); - List cells0 = row0.getCells(); - assertEquals(3, cells0.size()); - assertEquals("header1", cells0.get(0).getText()); - assertEquals("header2", cells0.get(1).getText()); - assertEquals("header3", cells0.get(2).getText()); - - XSLFTableRow row1 = rows.get(1); - List cells1 = row1.getCells(); - assertEquals(3, cells1.size()); - assertEquals("A1", cells1.get(0).getText()); - assertEquals("B1", cells1.get(1).getText()); - assertEquals("C1", cells1.get(2).getText()); - - ppt.close(); - } - - @Test - public void testCreate() throws IOException { - XMLSlideShow ppt1 = new XMLSlideShow(); - XSLFSlide slide = ppt1.createSlide(); - - XSLFTable tbl = slide.createTable(); - assertNotNull(tbl.getCTTable()); - assertNotNull(tbl.getCTTable().getTblGrid()); - assertNotNull(tbl.getCTTable().getTblPr()); - assertTrue(tbl.getXmlObject() instanceof CTGraphicalObjectFrame); - assertEquals("Table 1", tbl.getShapeName()); - assertEquals(2, tbl.getShapeId()); - assertEquals(0, tbl.getRows().size()); - assertEquals(0, tbl.getCTTable().sizeOfTrArray()); - assertEquals(0, tbl.getCTTable().getTblGrid().sizeOfGridColArray()); - - assertEquals(0, tbl.getNumberOfColumns()); - assertEquals(0, tbl.getNumberOfRows()); - - XSLFTableRow row0 = tbl.addRow(); - assertNotNull(row0.getXmlObject()); - assertEquals(1, tbl.getNumberOfRows()); - assertSame(row0, tbl.getRows().get(0)); - assertEquals(20.0, row0.getHeight(), 0); - row0.setHeight(30.0); - assertEquals(30.0, row0.getHeight(), 0); - - assertEquals(0, row0.getCells().size()); - XSLFTableCell cell0 = row0.addCell(); - assertNotNull(cell0.getXmlObject()); - // by default table cell has no borders - CTTableCell tc = (CTTableCell)cell0.getXmlObject(); - assertTrue(tc.getTcPr().getLnB().isSetNoFill()); - assertTrue(tc.getTcPr().getLnT().isSetNoFill()); - assertTrue(tc.getTcPr().getLnL().isSetNoFill()); - assertTrue(tc.getTcPr().getLnR().isSetNoFill()); - - assertSame(cell0, row0.getCells().get(0)); - assertEquals(1, tbl.getNumberOfColumns()); - assertEquals(100.0, tbl.getColumnWidth(0), 0); - cell0.addNewTextParagraph().addNewTextRun().setText("POI"); - assertEquals("POI", cell0.getText()); - - XSLFTableCell cell1 = row0.addCell(); - assertSame(cell1, row0.getCells().get(1)); - assertEquals(2, tbl.getNumberOfColumns()); - assertEquals(100.0, tbl.getColumnWidth(1), 0); - cell1.addNewTextParagraph().addNewTextRun().setText("Apache"); - assertEquals("Apache", cell1.getText()); - - for (BorderEdge edge : BorderEdge.values()) { - assertNull(cell1.getBorderWidth(edge)); - cell1.setBorderWidth(edge, 2.0); - assertEquals(2.0, cell1.getBorderWidth(edge), 0); - assertNull(cell1.getBorderColor(edge)); - cell1.setBorderColor(edge, Color.yellow); - assertEquals(Color.yellow, cell1.getBorderColor(edge)); - } - - assertEquals(VerticalAlignment.TOP, cell1.getVerticalAlignment()); - cell1.setVerticalAlignment(VerticalAlignment.MIDDLE); - assertEquals(VerticalAlignment.MIDDLE, cell1.getVerticalAlignment()); - cell1.setVerticalAlignment(null); - assertEquals(VerticalAlignment.TOP, cell1.getVerticalAlignment()); - - XMLSlideShow ppt2 = XSLFTestDataSamples.writeOutAndReadBack(ppt1); - ppt1.close(); - - slide = ppt2.getSlides().get(0); - tbl = (XSLFTable)slide.getShapes().get(0); - assertEquals(2, tbl.getNumberOfColumns()); - assertEquals(1, tbl.getNumberOfRows()); - assertEquals("POI", tbl.getCell(0, 0).getText()); - assertEquals("Apache", tbl.getCell(0, 1).getText()); - - ppt2.close(); - } - - @Test - public void removeTable() throws IOException { - XMLSlideShow ss = XSLFTestDataSamples.openSampleDocument("shapes.pptx"); - XSLFSlide sl = ss.getSlides().get(0); - XSLFTable tab = (XSLFTable)sl.getShapes().get(4); - sl.removeShape(tab); - - XMLSlideShow ss2 = XSLFTestDataSamples.writeOutAndReadBack(ss); - ss.close(); - - sl = ss2.getSlides().get(0); - for (XSLFShape s : sl.getShapes()) { - assertFalse(s instanceof XSLFTable); - } - - ss2.close(); - } - - @Test - public void checkTextHeight() throws IOException { - // from bug 59686 - XMLSlideShow ppt = new XMLSlideShow(); - XSLFSlide sl = ppt.createSlide(); - XSLFTable tab = sl.createTable(); - tab.setAnchor(new Rectangle2D.Double(50,50,300,50)); - XSLFTableRow tr = tab.addRow(); - XSLFTableCell tc0 = tr.addCell(); - tc0.setText("bla bla bla bla"); - tab.setColumnWidth(0, 50); - - // usually text height == 88, but font rendering is plattform dependent - // so we use something more reliable - assertTrue(tc0.getTextHeight() > 50); - assertEquals(0, tc0.getLineWidth(), 0); - - ppt.close(); - } - - @Test - public void checkNullPointerException() { - XMLSlideShow ss = XSLFTestDataSamples.openSampleDocument("au.asn.aes.www_conferences_2011_presentations_Fri_20Room4Level4_20930_20Maloney.pptx"); - Dimension pgsize = ss.getPageSize(); - for (Slide s : ss.getSlides()) { - BufferedImage img = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_ARGB); - Graphics2D graphics = img.createGraphics(); - - // draw stuff - s.draw(graphics); - - graphics.dispose(); - img.flush(); - } - } -} \ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTableRow.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTableRow.java deleted file mode 100644 index 8a0892819..000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTableRow.java +++ /dev/null @@ -1,131 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.IOException; -import java.util.List; - -import org.apache.poi.xslf.XSLFTestDataSamples; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTableCell; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTableRow; - -public class TestXSLFTableRow { - - private static XMLSlideShow ppt; - private static XSLFTable tbl; - private static XSLFTableRow row; - - /** Copied from {@link TestXSLFTable#testRead()} */ - @Before - public void setUp() throws IOException { - ppt = XSLFTestDataSamples.openSampleDocument("shapes.pptx"); - - XSLFSlide slide = ppt.getSlides().get(3); - List shapes = slide.getShapes(); - tbl = (XSLFTable)shapes.get(0); - List rows = tbl.getRows(); - row = rows.get(0); - } - - @After - public void tearDown() throws IOException { - ppt.getPackage().revert(); - ppt.close(); - } - - - @Test - public void constructor() { - XSLFTableRow row2 = new XSLFTableRow(row.getXmlObject(), tbl); - assertSame(row.getXmlObject(), row2.getXmlObject()); - assertEquals(row.getHeight(), row2.getHeight(), 1e-16); - } - - @Test - public void testHeight() { - final double h = 10.0; - row.setHeight(h); - assertEquals(h, row.getHeight(), 1e-16); - } - - /** copied from {@link TestXSLFTable#testCreate()} */ - @Test - public void getCells() { - List cells = row.getCells(); - assertNotNull(cells); - assertEquals(3, cells.size()); - } - - @Test - public void testIterator() { - int i = 0; - for (XSLFTableCell cell : row) { - i++; - assertEquals("header"+i, cell.getText()); - } - assertEquals(3, i); - } - - /** copied from {@link TestXSLFTable#testCreate()} */ - @Test - public void addCell() { - XSLFTableCell cell = row.addCell(); - assertNotNull(cell); - - assertNotNull(cell.getXmlObject()); - // by default table cell has no borders - CTTableCell tc = (CTTableCell)cell.getXmlObject(); - assertTrue(tc.getTcPr().getLnB().isSetNoFill()); - assertTrue(tc.getTcPr().getLnT().isSetNoFill()); - assertTrue(tc.getTcPr().getLnL().isSetNoFill()); - assertTrue(tc.getTcPr().getLnR().isSetNoFill()); - } - - @Test - public void mergeCells() { - try { - row.mergeCells(0, 0); - fail("expected IllegalArgumentException when merging fewer than 2 columns"); - } catch (final IllegalArgumentException e) { - // expected - } - - row.mergeCells(0, 1); - List cells = row.getCells(); - //the top-left cell of a merged region is not regarded as merged - assertFalse("top-left cell of merged region", cells.get(0).isMerged()); - assertTrue("inside merged region", cells.get(1).isMerged()); - assertFalse("outside merged region", cells.get(2).isMerged()); - } - - @Test - public void getXmlObject() { - CTTableRow ctrow = row.getXmlObject(); - assertNotNull(ctrow); - } - -} diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTableStyles.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTableStyles.java deleted file mode 100644 index 710363747..000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTableStyles.java +++ /dev/null @@ -1,38 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import java.io.IOException; - -import org.junit.Test; - -public class TestXSLFTableStyles { - - @Test - public void testRead() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - XSLFTableStyles tblStyles = ppt.getTableStyles(); - assertNotNull(tblStyles); - - assertEquals(0, tblStyles.getStyles().size()); - - ppt.close(); - } -} \ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTextBox.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTextBox.java deleted file mode 100644 index 6edc3bdf2..000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTextBox.java +++ /dev/null @@ -1,90 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -import java.io.IOException; - -import org.apache.poi.sl.usermodel.Placeholder; -import org.junit.Test; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextCharacterProperties; - -/** - * @author Yegor Kozlov - */ -public class TestXSLFTextBox { - - @Test - public void testPlaceholder() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - XSLFSlide slide = ppt.createSlide(); - - XSLFTextBox shape = slide.createTextBox(); - assertNull(shape.getTextType()); - shape.setPlaceholder(Placeholder.TITLE); - assertEquals(Placeholder.TITLE, shape.getTextType()); - shape.setPlaceholder(null); - assertNull(shape.getTextType()); - shape.setText("Apache POI"); - - ppt.close(); - } - - /** - * text box inherits default text proeprties from presentation.xml - */ - @Test - public void testDefaultTextStyle() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - XSLFSlide slide = ppt.createSlide(); - - // default character properties for paragraphs with level=1 - CTTextCharacterProperties pPr = ppt.getCTPresentation().getDefaultTextStyle().getLvl1PPr().getDefRPr(); - - XSLFTextBox shape = slide.createTextBox(); - shape.setText("Apache POI"); - assertEquals(1, shape.getTextParagraphs().size()); - assertEquals(1, shape.getTextParagraphs().get(0).getTextRuns().size()); - - XSLFTextRun r = shape.getTextParagraphs().get(0).getTextRuns().get(0); - - assertEquals(1800, pPr.getSz()); - assertEquals(18.0, r.getFontSize(), 0); - assertEquals("Calibri", r.getFontFamily()); - - pPr.setSz(900); - pPr.getLatin().setTypeface("Arial"); - assertEquals(9.0, r.getFontSize(), 0); - assertEquals("Arial", r.getFontFamily()); - - // unset font size in presentation.xml. The value should be taken from master slide - // from /p:sldMaster/p:txStyles/p:otherStyle/a:lvl1pPr/a:defRPr - ppt.getCTPresentation().getDefaultTextStyle().getLvl1PPr().getDefRPr().unsetSz(); - pPr = slide.getSlideMaster().getXmlObject().getTxStyles().getOtherStyle().getLvl1PPr().getDefRPr(); - assertEquals(1800, pPr.getSz()); - assertEquals(18.0, r.getFontSize(), 0); - pPr.setSz(2000); - assertEquals(20.0, r.getFontSize(), 0); - - pPr.unsetSz(); // Should never be - assertNull(r.getFontSize()); - - ppt.close(); - } -} \ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTextParagraph.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTextParagraph.java deleted file mode 100644 index 7d165387b..000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTextParagraph.java +++ /dev/null @@ -1,394 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.usermodel; - -import static org.apache.poi.sl.TestCommonSL.sameColor; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.geom.Rectangle2D; -import java.awt.image.BufferedImage; -import java.io.IOException; -import java.util.List; - -import org.apache.poi.sl.draw.DrawTextFragment; -import org.apache.poi.sl.draw.DrawTextParagraph; -import org.apache.poi.sl.usermodel.AutoNumberingScheme; -import org.apache.poi.sl.usermodel.TextParagraph.TextAlign; -import org.apache.poi.xslf.XSLFTestDataSamples; -import org.junit.Assume; -import org.junit.Test; - -/** - * @author Yegor Kozlov - */ -public class TestXSLFTextParagraph { - // private static POILogger _logger = POILogFactory.getLogger(XSLFTextParagraph.class); - - static class DrawTextParagraphProxy extends DrawTextParagraph { - DrawTextParagraphProxy(XSLFTextParagraph p) { - super(p); - } - - @Override - public void breakText(Graphics2D graphics) { - super.breakText(graphics); - } - - @Override - public double getWrappingWidth(boolean firstLine, Graphics2D graphics) { - return super.getWrappingWidth(firstLine, graphics); - } - - public List getLines() { - return lines; - } - } - - @Test - public void testWrappingWidth() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - XSLFSlide slide = ppt.createSlide(); - XSLFTextShape sh = slide.createAutoShape(); - sh.setLineColor(Color.black); - - XSLFTextParagraph p = sh.addNewTextParagraph(); - p.addNewTextRun().setText( - "Paragraph formatting allows for more granular control " + - "of text within a shape. Properties here apply to all text " + - "residing within the corresponding paragraph."); - - Rectangle2D anchor = new Rectangle2D.Double(50, 50, 300, 200); - sh.setAnchor(anchor); - - DrawTextParagraphProxy dtp = new DrawTextParagraphProxy(p); - - Double leftInset = sh.getLeftInset(); - Double rightInset = sh.getRightInset(); - assertEquals(7.2, leftInset, 0); - assertEquals(7.2, rightInset, 0); - - Double leftMargin = p.getLeftMargin(); - assertEquals(0.0, leftMargin, 0); - - Double indent = p.getIndent(); - assertNull(indent); // default - - double expectedWidth; - - // Case 1: bullet=false, leftMargin=0, indent=0. - expectedWidth = anchor.getWidth() - leftInset - rightInset - leftMargin; - assertEquals(285.6, expectedWidth, 0); // 300 - 7.2 - 7.2 - 0 - assertEquals(expectedWidth, dtp.getWrappingWidth(true, null), 0); - assertEquals(expectedWidth, dtp.getWrappingWidth(false, null), 0); - - p.setLeftMargin(36d); // 0.5" - leftMargin = p.getLeftMargin(); - assertEquals(36.0, leftMargin, 0); - expectedWidth = anchor.getWidth() - leftInset - rightInset - leftMargin; - assertEquals(249.6, expectedWidth, 1E-5); // 300 - 7.2 - 7.2 - 36 - assertEquals(expectedWidth, dtp.getWrappingWidth(true, null), 0); - assertEquals(expectedWidth, dtp.getWrappingWidth(false, null), 0); - - // increase insets, the wrapping width should get smaller - sh.setLeftInset(10); - sh.setRightInset(10); - leftInset = sh.getLeftInset(); - rightInset = sh.getRightInset(); - assertEquals(10.0, leftInset, 0); - assertEquals(10.0, rightInset, 0); - expectedWidth = anchor.getWidth() - leftInset - rightInset - leftMargin; - assertEquals(244.0, expectedWidth, 0); // 300 - 10 - 10 - 36 - assertEquals(expectedWidth, dtp.getWrappingWidth(true, null), 0); - assertEquals(expectedWidth, dtp.getWrappingWidth(false, null), 0); - - // set a positive indent of a 0.5 inch. This means "First Line" indentation: - // |<--- indent -->|Here goes first line of the text - // Here go other lines (second and subsequent) - - p.setIndent(36.0); // 0.5" - indent = p.getIndent(); - assertEquals(36.0, indent, 0); - expectedWidth = anchor.getWidth() - leftInset - rightInset - leftMargin - indent; - assertEquals(208.0, expectedWidth, 0); // 300 - 10 - 10 - 36 - 6.4 - assertEquals(expectedWidth, dtp.getWrappingWidth(true, null), 0); // first line is indented - // other lines are not indented - expectedWidth = anchor.getWidth() - leftInset - rightInset - leftMargin; - assertEquals(244.0, expectedWidth, 0); // 300 - 10 - 10 - 36 - assertEquals(expectedWidth, dtp.getWrappingWidth(false, null), 0); - - // set a negative indent of a 1 inch. This means "Hanging" indentation: - // Here goes first line of the text - // |<--- indent -->|Here go other lines (second and subsequent) - p.setIndent(-72.0); // 1" - indent = p.getIndent(); - assertEquals(-72.0, indent, 0); - expectedWidth = anchor.getWidth() - leftInset - rightInset; - assertEquals(280.0, expectedWidth, 0); // 300 - 10 - 10 - assertEquals(expectedWidth, dtp.getWrappingWidth(true, null), 0); // first line is NOT indented - // other lines are indented by leftMargin (the value of indent is not used) - expectedWidth = anchor.getWidth() - leftInset - rightInset - leftMargin; - assertEquals(244.0, expectedWidth, 0); // 300 - 10 - 10 - 36 - assertEquals(expectedWidth, dtp.getWrappingWidth(false, null), 0); - - ppt.close(); - } - - /** - * test breaking test into lines. - * This test requires that the Arial font is available and will run only on windows - */ - @Test - public void testBreakLines() throws IOException { - String os = System.getProperty("os.name"); - Assume.assumeTrue("Skipping testBreakLines(), it is executed only on Windows machines", (os != null && os.contains("Windows"))); - - XMLSlideShow ppt = new XMLSlideShow(); - XSLFSlide slide = ppt.createSlide(); - XSLFTextShape sh = slide.createAutoShape(); - - XSLFTextParagraph p = sh.addNewTextParagraph(); - XSLFTextRun r = p.addNewTextRun(); - r.setFontFamily("Arial"); // this should always be available - r.setFontSize(12d); - r.setText( - "Paragraph formatting allows for more granular control " + - "of text within a shape. Properties here apply to all text " + - "residing within the corresponding paragraph."); - - sh.setAnchor(new Rectangle2D.Double(50, 50, 300, 200)); - DrawTextParagraphProxy dtp = new DrawTextParagraphProxy(p); - - BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB); - Graphics2D graphics = img.createGraphics(); - - List lines; - dtp.breakText(graphics); - lines = dtp.getLines(); - assertEquals(4, lines.size()); - - // decrease the shape width from 300 pt to 100 pt - sh.setAnchor(new Rectangle2D.Double(50, 50, 100, 200)); - dtp.breakText(graphics); - lines = dtp.getLines(); - assertEquals(12, lines.size()); - - // decrease the shape width from 300 pt to 100 pt - sh.setAnchor(new Rectangle2D.Double(50, 50, 600, 200)); - dtp.breakText(graphics); - lines = dtp.getLines(); - assertEquals(2, lines.size()); - - // set left and right margins to 200pt. This leaves 200pt for wrapping text - sh.setLeftInset(200); - sh.setRightInset(200); - dtp.breakText(graphics); - lines = dtp.getLines(); - assertEquals(5, lines.size()); - - r.setText("Apache POI"); - dtp.breakText(graphics); - lines = dtp.getLines(); - assertEquals(1, lines.size()); - assertEquals("Apache POI", lines.get(0).getString()); - - r.setText("Apache\nPOI"); - dtp.breakText(graphics); - lines = dtp.getLines(); - assertEquals(2, lines.size()); - assertEquals("Apache", lines.get(0).getString()); - assertEquals("POI", lines.get(1).getString()); - - // trailing newlines are ignored - r.setText("Apache\nPOI\n"); - dtp.breakText(graphics); - lines = dtp.getLines(); - assertEquals(2, lines.size()); - assertEquals("Apache", lines.get(0).getString()); - assertEquals("POI", lines.get(1).getString()); - - XSLFAutoShape sh2 = slide.createAutoShape(); - sh2.setAnchor(new Rectangle2D.Double(50, 50, 300, 200)); - XSLFTextParagraph p2 = sh2.addNewTextParagraph(); - XSLFTextRun r2 = p2.addNewTextRun(); - r2.setFontFamily("serif"); // this should always be available - r2.setFontSize(30d); - r2.setText("Apache\n"); - XSLFTextRun r3 = p2.addNewTextRun(); - r3.setFontFamily("serif"); // this should always be available - r3.setFontSize(10d); - r3.setText("POI"); - dtp = new DrawTextParagraphProxy(p2); - dtp.breakText(graphics); - lines = dtp.getLines(); - assertEquals(2, lines.size()); - assertEquals("Apache", lines.get(0).getString()); - assertEquals("POI", lines.get(1).getString()); - // the first line is at least two times higher than the second - assertTrue(lines.get(0).getHeight() > lines.get(1).getHeight()*2); - - ppt.close(); - } - - @Test - public void testThemeInheritance() throws IOException { - XMLSlideShow ppt = XSLFTestDataSamples.openSampleDocument("prProps.pptx"); - List shapes = ppt.getSlides().get(0).getShapes(); - XSLFTextShape sh1 = (XSLFTextShape)shapes.get(0); - assertEquals("Apache", sh1.getText()); - assertEquals(TextAlign.CENTER, sh1.getTextParagraphs().get(0).getTextAlign()); - XSLFTextShape sh2 = (XSLFTextShape)shapes.get(1); - assertEquals("Software", sh2.getText()); - assertEquals(TextAlign.CENTER, sh2.getTextParagraphs().get(0).getTextAlign()); - XSLFTextShape sh3 = (XSLFTextShape)shapes.get(2); - assertEquals("Foundation", sh3.getText()); - assertEquals(TextAlign.CENTER, sh3.getTextParagraphs().get(0).getTextAlign()); - ppt.close(); - } - - @Test - public void testParagraphProperties() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - XSLFSlide slide = ppt.createSlide(); - XSLFTextShape sh = slide.createAutoShape(); - - XSLFTextParagraph p = sh.addNewTextParagraph(); - assertFalse(p.isBullet()); - p.setBullet(true); - assertTrue(p.isBullet()); - - assertEquals("\u2022", p.getBulletCharacter()); - p.setBulletCharacter("*"); - assertEquals("*", p.getBulletCharacter()); - - assertEquals("Arial", p.getBulletFont()); - p.setBulletFont("Calibri"); - assertEquals("Calibri", p.getBulletFont()); - - assertEquals(null, p.getBulletFontColor()); - p.setBulletFontColor(Color.red); - assertTrue(sameColor(Color.red, p.getBulletFontColor())); - - assertNull(p.getBulletFontSize()); - p.setBulletFontSize(200.); - assertEquals(200., p.getBulletFontSize(), 0); - p.setBulletFontSize(-20.); - assertEquals(-20.0, p.getBulletFontSize(), 0); - - assertEquals(72.0, p.getDefaultTabSize(), 0); - - assertNull(p.getIndent()); - p.setIndent(72.0); - assertEquals(72.0, p.getIndent(), 0); - p.setIndent(-1d); // the value of -1.0 resets to the defaults (not any more ...) - assertEquals(-1d, p.getIndent(), 0); - p.setIndent(null); - assertNull(p.getIndent()); - - assertEquals(0.0, p.getLeftMargin(), 0); - p.setLeftMargin(72.0); - assertEquals(72.0, p.getLeftMargin(), 0); - p.setLeftMargin(-1.0); // the value of -1.0 resets to the defaults - assertEquals(-1.0, p.getLeftMargin(), 0); - p.setLeftMargin(null); - assertEquals(0d, p.getLeftMargin(), 0); // default will be taken from master - - assertEquals(0, p.getIndentLevel()); - p.setIndentLevel(1); - assertEquals(1, p.getIndentLevel()); - p.setIndentLevel(2); - assertEquals(2, p.getIndentLevel()); - - assertNull(p.getLineSpacing()); - p.setLineSpacing(200.); - assertEquals(200.0, p.getLineSpacing(), 0); - p.setLineSpacing(-15.); - assertEquals(-15.0, p.getLineSpacing(), 0); - - assertNull(p.getSpaceAfter()); - p.setSpaceAfter(200.); - assertEquals(200.0, p.getSpaceAfter(), 0); - p.setSpaceAfter(-15.); - assertEquals(-15.0, p.getSpaceAfter(), 0); - p.setSpaceAfter(null); - assertNull(p.getSpaceAfter()); - p.setSpaceAfter(null); - assertNull(p.getSpaceAfter()); - - assertNull(p.getSpaceBefore()); - p.setSpaceBefore(200.); - assertEquals(200.0, p.getSpaceBefore(), 0); - p.setSpaceBefore(-15.); - assertEquals(-15.0, p.getSpaceBefore(), 0); - p.setSpaceBefore(null); - assertNull(p.getSpaceBefore()); - p.setSpaceBefore(null); - assertNull(p.getSpaceBefore()); - - assertEquals(TextAlign.LEFT, p.getTextAlign()); - p.setTextAlign(TextAlign.RIGHT); - assertEquals(TextAlign.RIGHT, p.getTextAlign()); - - p.setBullet(false); - assertFalse(p.isBullet()); - - p.setBulletAutoNumber(AutoNumberingScheme.alphaLcParenBoth, 1); - - double tabStop = p.getTabStop(0); - assertEquals(0.0, tabStop, 0); - - p.addTabStop(100.); - assertEquals(100., p.getTabStop(0), 0); - - assertEquals(72.0, p.getDefaultTabSize(), 0); - - ppt.close(); - } - - @Test(expected = IllegalStateException.class) - public void testLineBreak() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - try { - XSLFSlide slide = ppt.createSlide(); - XSLFTextShape sh = slide.createAutoShape(); - - XSLFTextParagraph p = sh.addNewTextParagraph(); - XSLFTextRun r1 = p.addNewTextRun(); - r1.setText("Hello,"); - XSLFTextRun r2 = p.addLineBreak(); - assertEquals("\n", r2.getRawText()); - r2.setFontSize(10.0); - assertEquals(10.0, r2.getFontSize(), 0); - XSLFTextRun r3 = p.addNewTextRun(); - r3.setText("World!"); - r3.setFontSize(20.0); - XSLFTextRun r4 = p.addLineBreak(); - assertEquals(20.0, r4.getFontSize(), 0); - - assertEquals("Hello,\nWorld!\n",sh.getText()); - - // "You cannot change text of a line break, it is always '\\n'" - r2.setText("aaa"); - } finally { - ppt.close(); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTextRun.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTextRun.java deleted file mode 100644 index de6085433..000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTextRun.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -package org.apache.poi.xslf.usermodel; - -import static org.apache.poi.sl.TestCommonSL.sameColor; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.awt.Color; -import java.io.IOException; - -import org.junit.Test; - -/** - * @author Yegor Kozlov - */ -public class TestXSLFTextRun { - - @Test - public void testRunProperties() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - XSLFSlide slide = ppt.createSlide(); - XSLFTextShape sh = slide.createAutoShape(); - - XSLFTextRun r = sh.addNewTextParagraph().addNewTextRun(); - assertEquals("en-US", r.getRPr(true).getLang()); - - assertEquals(0., r.getCharacterSpacing(), 0); - r.setCharacterSpacing(3); - assertEquals(3., r.getCharacterSpacing(), 0); - r.setCharacterSpacing(-3); - assertEquals(-3., r.getCharacterSpacing(), 0); - r.setCharacterSpacing(0); - assertEquals(0., r.getCharacterSpacing(), 0); - assertFalse(r.getRPr(true).isSetSpc()); - - assertTrue(sameColor(Color.black, r.getFontColor())); - r.setFontColor(Color.red); - assertTrue(sameColor(Color.red, r.getFontColor())); - - assertEquals("Calibri", r.getFontFamily()); - r.setFontFamily("Arial"); - assertEquals("Arial", r.getFontFamily()); - - assertEquals(18.0, r.getFontSize(), 0); - r.setFontSize(13.0); - assertEquals(13.0, r.getFontSize(), 0); - - assertEquals(false, r.isSuperscript()); - r.setSuperscript(true); - assertEquals(true, r.isSuperscript()); - r.setSuperscript(false); - assertEquals(false, r.isSuperscript()); - - assertEquals(false, r.isSubscript()); - r.setSubscript(true); - assertEquals(true, r.isSubscript()); - r.setSubscript(false); - assertEquals(false, r.isSubscript()); - - ppt.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTextShape.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTextShape.java deleted file mode 100644 index 9cf4adcd8..000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTextShape.java +++ /dev/null @@ -1,944 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.usermodel; - -import static org.apache.poi.sl.TestCommonSL.sameColor; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assume.assumeFalse; -import static org.apache.poi.xslf.usermodel.TestXSLFSimpleShape.getSpPr; - -import java.awt.Color; -import java.io.File; -import java.io.IOException; -import java.util.List; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hslf.usermodel.HSLFTextShape; -import org.apache.poi.sl.usermodel.Placeholder; -import org.apache.poi.sl.usermodel.SlideShow; -import org.apache.poi.sl.usermodel.SlideShowFactory; -import org.apache.poi.sl.usermodel.TextParagraph.TextAlign; -import org.apache.poi.sl.usermodel.VerticalAlignment; -import org.apache.poi.xslf.XSLFTestDataSamples; -import org.junit.BeforeClass; -import org.junit.Test; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextBodyProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextCharacterProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextParagraphProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.STTextAlignType; -import org.openxmlformats.schemas.presentationml.x2006.main.CTPlaceholder; -import org.openxmlformats.schemas.presentationml.x2006.main.STPlaceholderType; - -public class TestXSLFTextShape { - private static boolean xslfOnly = false; - - @BeforeClass - public static void checkHslf() { - try { - Class.forName("org.apache.poi.hslf.usermodel.HSLFSlideShow"); - } catch (Exception e) { - xslfOnly = true; - } - } - - @Test - public void testLayouts() throws IOException { - XMLSlideShow ppt = XSLFTestDataSamples.openSampleDocument("layouts.pptx"); - - List slide = ppt.getSlides(); - - verifySlide1(slide.get(0)); - verifySlide2(slide.get(1)); - verifySlide3(slide.get(2)); - verifySlide4(slide.get(3)); - verifySlide7(slide.get(6)); - verifySlide8(slide.get(7)); - verifySlide10(slide.get(9)); - - ppt.close(); - } - - void verifySlide1(XSLFSlide slide){ - XSLFSlideLayout layout = slide.getSlideLayout(); - List shapes = slide.getShapes(); - assertEquals("Title Slide",layout.getName()); - - XSLFTextShape shape1 = (XSLFTextShape)shapes.get(0); - CTPlaceholder ph1 = shape1.getCTPlaceholder(); - assertEquals(STPlaceholderType.CTR_TITLE, ph1.getType()); - // anchor is not defined in the shape - assertNull(getSpPr(shape1).getXfrm()); - - XSLFTextShape masterShape1 = (XSLFTextShape)layout.getPlaceholder(ph1); - assertNotNull(getSpPr(masterShape1).getXfrm()); - assertEquals(masterShape1.getAnchor(), shape1.getAnchor()); - - CTTextBodyProperties bodyPr1 = shape1.getTextBodyPr(); - // none of the following properties are set in the shapes and fetched from the master shape - assertTrue( - !bodyPr1.isSetLIns() && !bodyPr1.isSetRIns() && - !bodyPr1.isSetBIns() && !bodyPr1.isSetTIns() && - !bodyPr1.isSetAnchor() - ); - assertEquals(7.2, shape1.getLeftInset(), 0); // 0.1" - assertEquals(7.2, shape1.getRightInset(), 0); // 0.1" - assertEquals(3.6, shape1.getTopInset(), 0); // 0.05" - assertEquals(3.6, shape1.getBottomInset(), 0); // 0.05" - assertEquals(VerticalAlignment.MIDDLE, shape1.getVerticalAlignment()); - - // now check text properties - assertEquals("Centered Title", shape1.getText()); - XSLFTextRun r1 = shape1.getTextParagraphs().get(0).getTextRuns().get(0); - assertEquals("Calibri", r1.getFontFamily()); - assertEquals(44.0, r1.getFontSize(), 0); - assertTrue(sameColor(Color.black, r1.getFontColor())); - - XSLFTextShape shape2 = (XSLFTextShape)shapes.get(1); - CTPlaceholder ph2 = shape2.getCTPlaceholder(); - assertEquals(STPlaceholderType.SUB_TITLE, ph2.getType()); - // anchor is not defined in the shape - assertNull(getSpPr(shape2).getXfrm()); - - XSLFTextShape masterShape2 = (XSLFTextShape)layout.getPlaceholder(ph2); - assertNotNull(getSpPr(masterShape2).getXfrm()); - assertEquals(masterShape2.getAnchor(), shape2.getAnchor()); - - CTTextBodyProperties bodyPr2 = shape2.getTextBodyPr(); - // none of the following properties are set in the shapes and fetched from the master shape - assertTrue( - !bodyPr2.isSetLIns() && !bodyPr2.isSetRIns() && - !bodyPr2.isSetBIns() && !bodyPr2.isSetTIns() && - !bodyPr2.isSetAnchor() - ); - assertEquals(7.2, shape2.getLeftInset(), 0); // 0.1" - assertEquals(7.2, shape2.getRightInset(), 0); // 0.1" - assertEquals(3.6, shape2.getTopInset(), 0); // 0.05" - assertEquals(3.6, shape2.getBottomInset(), 0); // 0.05" - assertEquals(VerticalAlignment.TOP, shape2.getVerticalAlignment()); - - assertEquals("subtitle", shape2.getText()); - XSLFTextRun r2 = shape2.getTextParagraphs().get(0).getTextRuns().get(0); - assertEquals("Calibri", r2.getFontFamily()); - assertEquals(32.0, r2.getFontSize(), 0); - // TODO fix calculation of tint - //assertEquals(new Color(137, 137, 137), r2.getFontColor()); - } - - void verifySlide2(XSLFSlide slide){ - XSLFSlideLayout layout = slide.getSlideLayout(); - List shapes = slide.getShapes(); - assertEquals("Title and Content",layout.getName()); - - XSLFTextShape shape1 = (XSLFTextShape)shapes.get(0); - CTPlaceholder ph1 = shape1.getCTPlaceholder(); - assertEquals(STPlaceholderType.TITLE, ph1.getType()); - // anchor is not defined in the shape - assertNull(getSpPr(shape1).getXfrm()); - - XSLFTextShape masterShape1 = (XSLFTextShape)layout.getPlaceholder(ph1); - // layout does not have anchor info either, it is in the slide master - assertNull(getSpPr(masterShape1).getXfrm()); - masterShape1 = (XSLFTextShape)layout.getSlideMaster().getPlaceholder(ph1); - assertNotNull(getSpPr(masterShape1).getXfrm()); - assertEquals(masterShape1.getAnchor(), shape1.getAnchor()); - - CTTextBodyProperties bodyPr1 = shape1.getTextBodyPr(); - // none of the following properties are set in the shapes and fetched from the master shape - assertTrue( - !bodyPr1.isSetLIns() && !bodyPr1.isSetRIns() && - !bodyPr1.isSetBIns() && !bodyPr1.isSetTIns() && - !bodyPr1.isSetAnchor() - ); - assertEquals(7.2, shape1.getLeftInset(), 0); // 0.1" - assertEquals(7.2, shape1.getRightInset(), 0); // 0.1" - assertEquals(3.6, shape1.getTopInset(), 0); // 0.05" - assertEquals(3.6, shape1.getBottomInset(), 0); // 0.05" - assertEquals(VerticalAlignment.MIDDLE, shape1.getVerticalAlignment()); - - // now check text properties - assertEquals("Title", shape1.getText()); - XSLFTextRun r1 = shape1.getTextParagraphs().get(0).getTextRuns().get(0); - assertEquals("Calibri", r1.getFontFamily()); - assertEquals(44.0, r1.getFontSize(), 0); - assertTrue(sameColor(Color.black, r1.getFontColor())); - - XSLFTextShape shape2 = (XSLFTextShape)shapes.get(1); - CTPlaceholder ph2 = shape2.getCTPlaceholder(); - assertFalse(ph2.isSetType()); // - assertTrue(ph2.isSetIdx()); - assertEquals(1, ph2.getIdx()); - // anchor is not defined in the shape - assertNull(getSpPr(shape2).getXfrm()); - - XSLFTextShape masterShape2 = (XSLFTextShape)layout.getPlaceholder(ph2); - // anchor of the body text is missing in the slide layout, llokup in the slide master - assertNull(getSpPr(masterShape2).getXfrm()); - masterShape2 = (XSLFTextShape)layout.getSlideMaster().getPlaceholder(ph2); - assertNotNull(getSpPr(masterShape2).getXfrm()); - assertEquals(masterShape2.getAnchor(), shape2.getAnchor()); - - CTTextBodyProperties bodyPr2 = shape2.getTextBodyPr(); - // none of the following properties are set in the shapes and fetched from the master shape - assertTrue( - !bodyPr2.isSetLIns() && !bodyPr2.isSetRIns() && - !bodyPr2.isSetBIns() && !bodyPr2.isSetTIns() && - !bodyPr2.isSetAnchor() - ); - assertEquals(7.2, shape2.getLeftInset(), 0); // 0.1" - assertEquals(7.2, shape2.getRightInset(), 0); // 0.1" - assertEquals(3.6, shape2.getTopInset(), 0); // 0.05" - assertEquals(3.6, shape2.getBottomInset(), 0); // 0.05" - assertEquals(VerticalAlignment.TOP, shape2.getVerticalAlignment()); - - XSLFTextRun pr1 = shape2.getTextParagraphs().get(0).getTextRuns().get(0); - assertEquals(0, pr1.getParentParagraph().getIndentLevel()); - assertEquals("Content", pr1.getRawText()); - assertEquals("Calibri", pr1.getFontFamily()); - assertEquals(32.0, pr1.getFontSize(), 0); - assertEquals(27.0, pr1.getParentParagraph().getLeftMargin(), 0); - assertEquals("\u2022", pr1.getParentParagraph().getBulletCharacter()); - assertEquals("Arial", pr1.getParentParagraph().getBulletFont()); - - XSLFTextRun pr2 = shape2.getTextParagraphs().get(1).getTextRuns().get(0); - assertEquals(1, pr2.getParentParagraph().getIndentLevel()); - assertEquals("Level 2", pr2.getRawText()); - assertEquals("Calibri", pr2.getFontFamily()); - assertEquals(28.0, pr2.getFontSize(), 0); - assertEquals(58.5, pr2.getParentParagraph().getLeftMargin(), 0); - assertEquals("\u2013", pr2.getParentParagraph().getBulletCharacter()); - assertEquals("Arial", pr2.getParentParagraph().getBulletFont()); - - XSLFTextRun pr3 = shape2.getTextParagraphs().get(2).getTextRuns().get(0); - assertEquals(2, pr3.getParentParagraph().getIndentLevel()); - assertEquals("Level 3", pr3.getRawText()); - assertEquals("Calibri", pr3.getFontFamily()); - assertEquals(24.0, pr3.getFontSize(), 0); - assertEquals(90.0, pr3.getParentParagraph().getLeftMargin(), 0); - assertEquals("\u2022", pr3.getParentParagraph().getBulletCharacter()); - assertEquals("Arial", pr3.getParentParagraph().getBulletFont()); - - XSLFTextRun pr4 = shape2.getTextParagraphs().get(3).getTextRuns().get(0); - assertEquals(3, pr4.getParentParagraph().getIndentLevel()); - assertEquals("Level 4", pr4.getRawText()); - assertEquals("Calibri", pr4.getFontFamily()); - assertEquals(20.0, pr4.getFontSize(), 0); - assertEquals(126.0, pr4.getParentParagraph().getLeftMargin(), 0); - assertEquals("\u2013", pr4.getParentParagraph().getBulletCharacter()); - assertEquals("Arial", pr4.getParentParagraph().getBulletFont()); - - XSLFTextRun pr5 = shape2.getTextParagraphs().get(4).getTextRuns().get(0); - assertEquals(4, pr5.getParentParagraph().getIndentLevel()); - assertEquals("Level 5", pr5.getRawText()); - assertEquals("Calibri", pr5.getFontFamily()); - assertEquals(20.0, pr5.getFontSize(), 0); - assertEquals(162.0, pr5.getParentParagraph().getLeftMargin(), 0); - assertEquals("\u00bb", pr5.getParentParagraph().getBulletCharacter()); - assertEquals("Arial", pr5.getParentParagraph().getBulletFont()); - - } - - void verifySlide3(XSLFSlide slide){ - XSLFSlideLayout layout = slide.getSlideLayout(); - List shapes = slide.getShapes(); - assertEquals("Section Header",layout.getName()); - - XSLFTextShape shape1 = (XSLFTextShape)shapes.get(0); - CTPlaceholder ph1 = shape1.getCTPlaceholder(); - assertEquals(STPlaceholderType.TITLE, ph1.getType()); - // anchor is not defined in the shape - assertNull(getSpPr(shape1).getXfrm()); - - XSLFTextShape masterShape1 = (XSLFTextShape)layout.getPlaceholder(ph1); - assertNotNull(getSpPr(masterShape1).getXfrm()); - assertEquals(masterShape1.getAnchor(), shape1.getAnchor()); - - CTTextBodyProperties bodyPr1 = shape1.getTextBodyPr(); - // none of the following properties are set in the shapes and fetched from the master shape - assertTrue( - !bodyPr1.isSetLIns() && !bodyPr1.isSetRIns() && - !bodyPr1.isSetBIns() && !bodyPr1.isSetTIns() && - !bodyPr1.isSetAnchor() - ); - assertEquals(7.2, shape1.getLeftInset(), 0); // 0.1" - assertEquals(7.2, shape1.getRightInset(), 0); // 0.1" - assertEquals(3.6, shape1.getTopInset(), 0); // 0.05" - assertEquals(3.6, shape1.getBottomInset(), 0); // 0.05" - assertEquals(VerticalAlignment.TOP, shape1.getVerticalAlignment()); - - // now check text properties - assertEquals("Section Title", shape1.getText()); - XSLFTextRun r1 = shape1.getTextParagraphs().get(0).getTextRuns().get(0); - assertEquals(TextAlign.LEFT, r1.getParentParagraph().getTextAlign()); - assertEquals("Calibri", r1.getFontFamily()); - assertEquals(40.0, r1.getFontSize(), 0); - assertTrue(sameColor(Color.black, r1.getFontColor())); - assertTrue(r1.isBold()); - assertFalse(r1.isItalic()); - assertFalse(r1.isUnderlined()); - - XSLFTextShape shape2 = (XSLFTextShape)shapes.get(1); - CTPlaceholder ph2 = shape2.getCTPlaceholder(); - assertEquals(STPlaceholderType.BODY, ph2.getType()); - // anchor is not defined in the shape - assertNull(getSpPr(shape2).getXfrm()); - - XSLFTextShape masterShape2 = (XSLFTextShape)layout.getPlaceholder(ph2); - assertNotNull(getSpPr(masterShape2).getXfrm()); - assertEquals(masterShape2.getAnchor(), shape2.getAnchor()); - - CTTextBodyProperties bodyPr2 = shape2.getTextBodyPr(); - // none of the following properties are set in the shapes and fetched from the master shape - assertTrue( - !bodyPr2.isSetLIns() && !bodyPr2.isSetRIns() && - !bodyPr2.isSetBIns() && !bodyPr2.isSetTIns() && - !bodyPr2.isSetAnchor() - ); - assertEquals(7.2, shape2.getLeftInset(), 0); // 0.1" - assertEquals(7.2, shape2.getRightInset(), 0); // 0.1" - assertEquals(3.6, shape2.getTopInset(), 0); // 0.05" - assertEquals(3.6, shape2.getBottomInset(), 0); // 0.05" - assertEquals(VerticalAlignment.BOTTOM, shape2.getVerticalAlignment()); - - assertEquals("Section Header", shape2.getText()); - XSLFTextRun r2 = shape2.getTextParagraphs().get(0).getTextRuns().get(0); - assertEquals(TextAlign.LEFT, r2.getParentParagraph().getTextAlign()); - assertEquals("Calibri", r2.getFontFamily()); - assertEquals(20.0, r2.getFontSize(), 0); - // TODO fix calculation of tint - //assertEquals(new Color(137, 137, 137), r2.getFontColor()); - } - - void verifySlide4(XSLFSlide slide){ - XSLFSlideLayout layout = slide.getSlideLayout(); - List shapes = slide.getShapes(); - assertEquals("Two Content",layout.getName()); - - XSLFTextShape shape1 = (XSLFTextShape)shapes.get(0); - CTPlaceholder ph1 = shape1.getCTPlaceholder(); - assertEquals(STPlaceholderType.TITLE, ph1.getType()); - // anchor is not defined in the shape - assertNull(getSpPr(shape1).getXfrm()); - - XSLFTextShape masterShape1 = (XSLFTextShape)layout.getPlaceholder(ph1); - // layout does not have anchor info either, it is in the slide master - assertNull(getSpPr(masterShape1).getXfrm()); - masterShape1 = (XSLFTextShape)layout.getSlideMaster().getPlaceholder(ph1); - assertNotNull(getSpPr(masterShape1).getXfrm()); - assertEquals(masterShape1.getAnchor(), shape1.getAnchor()); - - CTTextBodyProperties bodyPr1 = shape1.getTextBodyPr(); - // none of the following properties are set in the shapes and fetched from the master shape - assertTrue( - !bodyPr1.isSetLIns() && !bodyPr1.isSetRIns() && - !bodyPr1.isSetBIns() && !bodyPr1.isSetTIns() && - !bodyPr1.isSetAnchor() - ); - assertEquals(7.2, shape1.getLeftInset(), 0); // 0.1" - assertEquals(7.2, shape1.getRightInset(), 0); // 0.1" - assertEquals(3.6, shape1.getTopInset(), 0); // 0.05" - assertEquals(3.6, shape1.getBottomInset(), 0); // 0.05" - assertEquals(VerticalAlignment.MIDDLE, shape1.getVerticalAlignment()); - - // now check text properties - assertEquals("Title", shape1.getText()); - XSLFTextRun r1 = shape1.getTextParagraphs().get(0).getTextRuns().get(0); - assertEquals(TextAlign.CENTER, r1.getParentParagraph().getTextAlign()); - assertEquals("Calibri", r1.getFontFamily()); - assertEquals(44.0, r1.getFontSize(), 0); - assertTrue(sameColor(Color.black, r1.getFontColor())); - - XSLFTextShape shape2 = (XSLFTextShape)shapes.get(1); - CTPlaceholder ph2 = shape2.getCTPlaceholder(); - assertFalse(ph2.isSetType()); - assertTrue(ph2.isSetIdx()); - assertEquals(1, ph2.getIdx()); // - // anchor is not defined in the shape - assertNull(getSpPr(shape2).getXfrm()); - - XSLFTextShape masterShape2 = (XSLFTextShape)layout.getPlaceholder(ph2); - assertNotNull(getSpPr(masterShape2).getXfrm()); - assertEquals(masterShape2.getAnchor(), shape2.getAnchor()); - - CTTextBodyProperties bodyPr2 = shape2.getTextBodyPr(); - // none of the following properties are set in the shapes and fetched from the master shape - assertTrue( - !bodyPr2.isSetLIns() && !bodyPr2.isSetRIns() && - !bodyPr2.isSetBIns() && !bodyPr2.isSetTIns() && - !bodyPr2.isSetAnchor() - ); - assertEquals(7.2, shape2.getLeftInset(), 0); // 0.1" - assertEquals(7.2, shape2.getRightInset(), 0); // 0.1" - assertEquals(3.6, shape2.getTopInset(), 0); // 0.05" - assertEquals(3.6, shape2.getBottomInset(), 0); // 0.05" - assertEquals(VerticalAlignment.TOP, shape2.getVerticalAlignment()); - - XSLFTextRun pr1 = shape2.getTextParagraphs().get(0).getTextRuns().get(0); - assertEquals(0, pr1.getParentParagraph().getIndentLevel()); - assertEquals("Left", pr1.getRawText()); - assertEquals("Calibri", pr1.getFontFamily()); - assertEquals(28.0, pr1.getFontSize(), 0); - assertEquals(27.0, pr1.getParentParagraph().getLeftMargin(), 0); - assertEquals("\u2022", pr1.getParentParagraph().getBulletCharacter()); - assertEquals("Arial", pr1.getParentParagraph().getBulletFont()); - - XSLFTextRun pr2 = shape2.getTextParagraphs().get(1).getTextRuns().get(0); - assertEquals(1, pr2.getParentParagraph().getIndentLevel()); - assertEquals("Level 2", pr2.getParentParagraph().getText()); - assertEquals("Calibri", pr2.getFontFamily()); - assertEquals(24.0, pr2.getFontSize(), 0); - assertEquals(58.5, pr2.getParentParagraph().getLeftMargin(), 0); - assertEquals("\u2013", pr2.getParentParagraph().getBulletCharacter()); - assertEquals("Arial", pr2.getParentParagraph().getBulletFont()); - - XSLFTextRun pr3 = shape2.getTextParagraphs().get(2).getTextRuns().get(0); - assertEquals(2, pr3.getParentParagraph().getIndentLevel()); - assertEquals("Level 3", pr3.getParentParagraph().getText()); - assertEquals("Calibri", pr3.getFontFamily()); - assertEquals(20.0, pr3.getFontSize(), 0); - assertEquals(90.0, pr3.getParentParagraph().getLeftMargin(), 0); - assertEquals("\u2022", pr3.getParentParagraph().getBulletCharacter()); - assertEquals("Arial", pr3.getParentParagraph().getBulletFont()); - - XSLFTextRun pr4 = shape2.getTextParagraphs().get(3).getTextRuns().get(0); - assertEquals(3, pr4.getParentParagraph().getIndentLevel()); - assertEquals("Level 4", pr4.getParentParagraph().getText()); - assertEquals("Calibri", pr4.getFontFamily()); - assertEquals(18.0, pr4.getFontSize(), 0); - assertEquals(126.0, pr4.getParentParagraph().getLeftMargin(), 0); - assertEquals("\u2013", pr4.getParentParagraph().getBulletCharacter()); - assertEquals("Arial", pr4.getParentParagraph().getBulletFont()); - - XSLFTextShape shape3 = (XSLFTextShape)shapes.get(2); - XSLFTextRun pr5 = shape3.getTextParagraphs().get(0).getTextRuns().get(0); - assertEquals(0, pr5.getParentParagraph().getIndentLevel()); - assertEquals("Right", pr5.getRawText()); - assertEquals("Calibri", pr5.getFontFamily()); - assertTrue(sameColor(Color.black, pr5.getFontColor())); - } - - @SuppressWarnings("unused") - void verifySlide5(XSLFSlide slide){ - XSLFSlideLayout layout = slide.getSlideLayout(); - List shapes = slide.getShapes(); - // TODO - } - - void verifySlide7(XSLFSlide slide){ - XSLFSlideLayout layout = slide.getSlideLayout(); - List shapes = slide.getShapes(); - assertEquals("Blank",layout.getName()); - - XSLFTextShape shape1 = (XSLFTextShape)shapes.get(0); - CTPlaceholder ph1 = shape1.getCTPlaceholder(); - assertEquals(STPlaceholderType.TITLE, ph1.getType()); - // anchor is not defined in the shape - assertNull(getSpPr(shape1).getXfrm()); - - CTTextBodyProperties bodyPr1 = shape1.getTextBodyPr(); - // none of the following properties are set in the shapes and fetched from the master shape - assertTrue( - !bodyPr1.isSetLIns() && !bodyPr1.isSetRIns() && - !bodyPr1.isSetBIns() && !bodyPr1.isSetTIns() && - !bodyPr1.isSetAnchor() - ); - assertEquals(7.2, shape1.getLeftInset(), 0); // 0.1" - assertEquals(7.2, shape1.getRightInset(), 0); // 0.1" - assertEquals(3.6, shape1.getTopInset(), 0); // 0.05" - assertEquals(3.6, shape1.getBottomInset(), 0); // 0.05" - assertEquals(VerticalAlignment.MIDDLE, shape1.getVerticalAlignment()); - - // now check text properties - assertEquals("Blank with Default Title", shape1.getText()); - XSLFTextRun r1 = shape1.getTextParagraphs().get(0).getTextRuns().get(0); - assertEquals(TextAlign.CENTER, r1.getParentParagraph().getTextAlign()); - assertEquals("Calibri", r1.getFontFamily()); - assertEquals(44.0, r1.getFontSize(), 0); - assertTrue(sameColor(Color.black, r1.getFontColor())); - assertFalse(r1.isBold()); - - XSLFTextShape shape2 = (XSLFTextShape)shapes.get(1); - - CTTextBodyProperties bodyPr2 = shape2.getTextBodyPr(); - // none of the following properties are set in the shapes and fetched from the master shape - assertTrue( - !bodyPr2.isSetLIns() && !bodyPr2.isSetRIns() && - !bodyPr2.isSetBIns() && !bodyPr2.isSetTIns() && - !bodyPr2.isSetAnchor() - ); - assertEquals(7.2, shape2.getLeftInset(), 0); // 0.1" - assertEquals(7.2, shape2.getRightInset(), 0); // 0.1" - assertEquals(3.6, shape2.getTopInset(), 0); // 0.05" - assertEquals(3.6, shape2.getBottomInset(), 0); // 0.05" - assertEquals(VerticalAlignment.TOP, shape2.getVerticalAlignment()); - - XSLFTextRun pr1 = shape2.getTextParagraphs().get(0).getTextRuns().get(0); - assertEquals(0, pr1.getParentParagraph().getIndentLevel()); - assertEquals("Default Text", pr1.getRawText()); - assertEquals("Calibri", pr1.getFontFamily()); - assertEquals(18.0, pr1.getFontSize(), 0); - - XSLFTextShape shape3 = (XSLFTextShape)shapes.get(2); - assertEquals("Default", shape3.getTextParagraphs().get(0).getText()); - assertEquals("Text with levels", shape3.getTextParagraphs().get(1).getText()); - assertEquals("Level 1", shape3.getTextParagraphs().get(2).getText()); - assertEquals("Level 2", shape3.getTextParagraphs().get(3).getText()); - assertEquals("Level 3", shape3.getTextParagraphs().get(4).getText()); - - for(int p = 0; p < 5; p++) { - XSLFTextParagraph pr = shape3.getTextParagraphs().get(p); - assertEquals("Calibri", pr.getTextRuns().get(0).getFontFamily()); - assertEquals(18.0, pr.getTextRuns().get(0).getFontSize(), 0); - } - } - - void verifySlide8(XSLFSlide slide){ - XSLFSlideLayout layout = slide.getSlideLayout(); - List shapes = slide.getShapes(); - assertEquals("Content with Caption",layout.getName()); - - XSLFTextShape shape1 = (XSLFTextShape)shapes.get(0); - CTPlaceholder ph1 = shape1.getCTPlaceholder(); - assertEquals(STPlaceholderType.TITLE, ph1.getType()); - // anchor is not defined in the shape - assertNull(getSpPr(shape1).getXfrm()); - - XSLFTextShape masterShape1 = (XSLFTextShape)layout.getPlaceholder(ph1); - // layout does not have anchor info either, it is in the slide master - assertNotNull(getSpPr(masterShape1).getXfrm()); - assertEquals(masterShape1.getAnchor(), shape1.getAnchor()); - - CTTextBodyProperties bodyPr1 = shape1.getTextBodyPr(); - // none of the following properties are set in the shapes and fetched from the master shape - assertTrue( - !bodyPr1.isSetLIns() && !bodyPr1.isSetRIns() && - !bodyPr1.isSetBIns() && !bodyPr1.isSetTIns() && - !bodyPr1.isSetAnchor() - ); - assertEquals(7.2, shape1.getLeftInset(), 0); // 0.1" - assertEquals(7.2, shape1.getRightInset(), 0); // 0.1" - assertEquals(3.6, shape1.getTopInset(), 0); // 0.05" - assertEquals(3.6, shape1.getBottomInset(), 0); // 0.05" - assertEquals(VerticalAlignment.BOTTOM, shape1.getVerticalAlignment()); - - // now check text properties - assertEquals("Caption", shape1.getText()); - XSLFTextRun r1 = shape1.getTextParagraphs().get(0).getTextRuns().get(0); - assertEquals(TextAlign.LEFT, r1.getParentParagraph().getTextAlign()); - assertEquals("Calibri", r1.getFontFamily()); - assertEquals(20.0, r1.getFontSize(), 0); - assertTrue(sameColor(Color.black, r1.getFontColor())); - assertTrue(r1.isBold()); - - XSLFTextShape shape2 = (XSLFTextShape)shapes.get(1); - CTPlaceholder ph2 = shape2.getCTPlaceholder(); - assertFalse(ph2.isSetType()); - assertTrue(ph2.isSetIdx()); - assertEquals(1, ph2.getIdx()); - // anchor is not defined in the shape - assertNull(getSpPr(shape2).getXfrm()); - - XSLFTextShape masterShape2 = (XSLFTextShape)layout.getPlaceholder(ph2); - assertNotNull(getSpPr(masterShape2).getXfrm()); - assertEquals(masterShape2.getAnchor(), shape2.getAnchor()); - - CTTextBodyProperties bodyPr2 = shape2.getTextBodyPr(); - // none of the following properties are set in the shapes and fetched from the master shape - assertTrue( - !bodyPr2.isSetLIns() && !bodyPr2.isSetRIns() && - !bodyPr2.isSetBIns() && !bodyPr2.isSetTIns() && - !bodyPr2.isSetAnchor() - ); - assertEquals(7.2, shape2.getLeftInset(), 0); // 0.1" - assertEquals(7.2, shape2.getRightInset(), 0); // 0.1" - assertEquals(3.6, shape2.getTopInset(), 0); // 0.05" - assertEquals(3.6, shape2.getBottomInset(), 0); // 0.05" - assertEquals(VerticalAlignment.TOP, shape2.getVerticalAlignment()); - - XSLFTextRun pr1 = shape2.getTextParagraphs().get(0).getTextRuns().get(0); - assertEquals(0, pr1.getParentParagraph().getIndentLevel()); - assertEquals("Level 1", pr1.getRawText()); - assertEquals("Calibri", pr1.getFontFamily()); - assertEquals(32.0, pr1.getFontSize(), 0); - assertEquals(27.0, pr1.getParentParagraph().getLeftMargin(), 0); - assertEquals("\u2022", pr1.getParentParagraph().getBulletCharacter()); - assertEquals("Arial", pr1.getParentParagraph().getBulletFont()); - - XSLFTextRun pr2 = shape2.getTextParagraphs().get(1).getTextRuns().get(0); - assertEquals(1, pr2.getParentParagraph().getIndentLevel()); - assertEquals("Level 2", pr2.getParentParagraph().getText()); - assertEquals("Calibri", pr2.getFontFamily()); - assertEquals(28.0, pr2.getFontSize(), 0); - assertEquals(58.5, pr2.getParentParagraph().getLeftMargin(), 0); - assertEquals("\u2013", pr2.getParentParagraph().getBulletCharacter()); - assertEquals("Arial", pr2.getParentParagraph().getBulletFont()); - - XSLFTextRun pr3 = shape2.getTextParagraphs().get(2).getTextRuns().get(0); - assertEquals(2, pr3.getParentParagraph().getIndentLevel()); - assertEquals("Level 3", pr3.getParentParagraph().getText()); - assertEquals("Calibri", pr3.getFontFamily()); - assertEquals(24.0, pr3.getFontSize(), 0); - assertEquals(90.0, pr3.getParentParagraph().getLeftMargin(), 0); - assertEquals("\u2022", pr3.getParentParagraph().getBulletCharacter()); - assertEquals("Arial", pr3.getParentParagraph().getBulletFont()); - - XSLFTextRun pr4 = shape2.getTextParagraphs().get(3).getTextRuns().get(0); - assertEquals(3, pr4.getParentParagraph().getIndentLevel()); - assertEquals("Level 4", pr4.getParentParagraph().getText()); - assertEquals("Calibri", pr4.getFontFamily()); - assertEquals(20.0, pr4.getFontSize(), 0); - assertEquals(126.0, pr4.getParentParagraph().getLeftMargin(), 0); - assertEquals("\u2013", pr4.getParentParagraph().getBulletCharacter()); - assertEquals("Arial", pr4.getParentParagraph().getBulletFont()); - - XSLFTextShape shape3 = (XSLFTextShape)shapes.get(2); - assertEquals(VerticalAlignment.TOP, shape3.getVerticalAlignment()); - assertEquals("Content with caption", shape3.getText()); - - pr1 = shape3.getTextParagraphs().get(0).getTextRuns().get(0); - assertEquals(0, pr1.getParentParagraph().getIndentLevel()); - assertEquals("Content with caption", pr1.getRawText()); - assertEquals("Calibri", pr1.getFontFamily()); - assertEquals(14.0, pr1.getFontSize(), 0); - - } - - void verifySlide10(XSLFSlide slide){ - XSLFTextShape footer = (XSLFTextShape)slide.getPlaceholderByType(STPlaceholderType.INT_FTR); - - // now check text properties - assertEquals("Apache Software Foundation", footer.getText()); - assertEquals(VerticalAlignment.MIDDLE, footer.getVerticalAlignment()); - - XSLFTextRun r1 = footer.getTextParagraphs().get(0).getTextRuns().get(0); - assertEquals(TextAlign.CENTER, r1.getParentParagraph().getTextAlign()); - assertEquals("Calibri", r1.getFontFamily()); - assertEquals(12.0, r1.getFontSize(), 0); - // TODO calculation of tint is incorrect - assertTrue(sameColor(new Color(64,64,64), r1.getFontColor())); - - XSLFTextShape dt = (XSLFTextShape)slide.getPlaceholderByType(STPlaceholderType.INT_DT); - assertEquals("Friday, October 21, 2011", dt.getText()); - - XSLFTextShape sldNum = (XSLFTextShape)slide.getPlaceholderByType(STPlaceholderType.INT_SLD_NUM); - assertEquals("10", sldNum.getText()); - } - - @Test - public void testTitleStyles() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - - XSLFSlideMaster master = ppt.getSlideMasters().get(0); - XSLFTheme theme = master.getTheme(); - XSLFSlideLayout layout = master.getLayout(SlideLayout.TITLE); - XSLFSlide slide = ppt.createSlide(layout) ; - assertSame(layout, slide.getSlideLayout()); - assertSame(master, slide.getSlideMaster()); - - XSLFTextShape titleShape = slide.getPlaceholder(0); - titleShape.setText("Apache POI"); - XSLFTextParagraph paragraph = titleShape.getTextParagraphs().get(0); - XSLFTextRun textRun = paragraph.getTextRuns().get(0); - - // level 1 : default title style on the master slide - // /p:sldMaster/p:txStyles/p:titleStyle/a:lvl1pPr - CTTextParagraphProperties lv1PPr = master.getXmlObject().getTxStyles().getTitleStyle().getLvl1PPr(); - CTTextCharacterProperties lv1CPr = lv1PPr.getDefRPr(); - assertEquals(4400, lv1CPr.getSz()); - assertEquals(44.0, textRun.getFontSize(), 0); - assertEquals("+mj-lt", lv1CPr.getLatin().getTypeface()); - assertEquals("Calibri", theme.getMajorFont()); - assertEquals("Calibri", textRun.getFontFamily()); - lv1CPr.setSz(3200); - assertEquals(32.0, textRun.getFontSize(), 0); - lv1CPr.getLatin().setTypeface("Arial"); - assertEquals("Arial", textRun.getFontFamily()); - assertEquals(STTextAlignType.CTR, lv1PPr.getAlgn()); - assertEquals(TextAlign.CENTER, paragraph.getTextAlign()); - lv1PPr.setAlgn(STTextAlignType.L); - assertEquals(TextAlign.LEFT, paragraph.getTextAlign()); - - // level 2: title placeholder on the master slide - // /p:sldMaster/p:cSld/p:spTree/p:sp/p:nvPr/p:ph[@type="title"] - XSLFTextShape tx2 = master.getPlaceholder(0); - CTTextParagraphProperties lv2PPr = tx2.getTextBody(true).getLstStyle().addNewLvl1PPr(); - CTTextCharacterProperties lv2CPr = lv2PPr.addNewDefRPr(); - lv2CPr.setSz(3300); - assertEquals(33.0, textRun.getFontSize(), 0); - lv2CPr.addNewLatin().setTypeface("Times"); - assertEquals("Times", textRun.getFontFamily()); - lv2PPr.setAlgn(STTextAlignType.R); - assertEquals(TextAlign.RIGHT, paragraph.getTextAlign()); - - - // level 3: title placeholder on the slide layout - // /p:sldLayout /p:cSld/p:spTree/p:sp/p:nvPr/p:ph[@type="ctrTitle"] - XSLFTextShape tx3 = layout.getPlaceholder(0); - CTTextParagraphProperties lv3PPr = tx3.getTextBody(true).getLstStyle().addNewLvl1PPr(); - CTTextCharacterProperties lv3CPr = lv3PPr.addNewDefRPr(); - lv3CPr.setSz(3400); - assertEquals(34.0, textRun.getFontSize(), 0); - lv3CPr.addNewLatin().setTypeface("Courier New"); - assertEquals("Courier New", textRun.getFontFamily()); - lv3PPr.setAlgn(STTextAlignType.CTR); - assertEquals(TextAlign.CENTER, paragraph.getTextAlign()); - - // level 4: default text properties in the shape itself - // ./p:sp/p:txBody/a:lstStyle/a:lvl1pPr - CTTextParagraphProperties lv4PPr = titleShape.getTextBody(true).getLstStyle().addNewLvl1PPr(); - CTTextCharacterProperties lv4CPr = lv4PPr.addNewDefRPr(); - lv4CPr.setSz(3500); - assertEquals(35.0, textRun.getFontSize(), 0); - lv4CPr.addNewLatin().setTypeface("Arial"); - assertEquals("Arial", textRun.getFontFamily()); - lv4PPr.setAlgn(STTextAlignType.L); - assertEquals(TextAlign.LEFT, paragraph.getTextAlign()); - - // level 5: text properties are defined in the text run - CTTextParagraphProperties lv5PPr = paragraph.getXmlObject().addNewPPr(); - CTTextCharacterProperties lv5CPr = textRun.getRPr(false); - lv5CPr.setSz(3600); - assertEquals(36.0, textRun.getFontSize(), 0); - lv5CPr.addNewLatin().setTypeface("Calibri"); - assertEquals("Calibri", textRun.getFontFamily()); - lv5PPr.setAlgn(STTextAlignType.CTR); - assertEquals(TextAlign.CENTER, paragraph.getTextAlign()); - - ppt.close(); - } - - @Test - public void testBodyStyles() throws IOException { - XMLSlideShow ppt = new XMLSlideShow(); - - XSLFSlideMaster master = ppt.getSlideMasters().get(0); - XSLFTheme theme = master.getTheme(); - XSLFSlideLayout layout = master.getLayout(SlideLayout.TITLE_AND_CONTENT); - XSLFSlide slide = ppt.createSlide(layout) ; - assertSame(layout, slide.getSlideLayout()); - assertSame(master, slide.getSlideMaster()); - - XSLFTextShape tx1 = slide.getPlaceholder(1); - tx1.clearText(); - - XSLFTextParagraph p1 = tx1.addNewTextParagraph(); - assertEquals(0, p1.getIndentLevel()); - XSLFTextRun r1 = p1.addNewTextRun(); - r1.setText("Apache POI"); - - XSLFTextParagraph p2 = tx1.addNewTextParagraph(); - p2.setIndentLevel(1); - assertEquals(1, p2.getIndentLevel()); - XSLFTextRun r2 = p2.addNewTextRun(); - r2.setText("HSLF"); - - XSLFTextParagraph p3 = tx1.addNewTextParagraph(); - p3.setIndentLevel(2); - assertEquals(2, p3.getIndentLevel()); - XSLFTextRun r3 = p3.addNewTextRun(); - r3.setText("XSLF"); - - // level 1 : default title style on the master slide - // /p:sldMaster/p:txStyles/p:bodyStyle/a:lvl1pPr - CTTextParagraphProperties lv1PPr = master.getXmlObject().getTxStyles().getBodyStyle().getLvl1PPr(); - CTTextCharacterProperties lv1CPr = lv1PPr.getDefRPr(); - CTTextParagraphProperties lv2PPr = master.getXmlObject().getTxStyles().getBodyStyle().getLvl2PPr(); - CTTextCharacterProperties lv2CPr = lv2PPr.getDefRPr(); - CTTextParagraphProperties lv3PPr = master.getXmlObject().getTxStyles().getBodyStyle().getLvl3PPr(); - CTTextCharacterProperties lv3CPr = lv3PPr.getDefRPr(); - // lv1 - assertEquals(3200, lv1CPr.getSz()); - assertEquals(32.0, r1.getFontSize(), 0); - assertEquals("+mn-lt", lv1CPr.getLatin().getTypeface()); - assertEquals("Calibri", theme.getMinorFont()); - assertEquals("Calibri", r1.getFontFamily()); - lv1CPr.setSz(3300); - assertEquals(33.0, r1.getFontSize(), 0); - lv1CPr.getLatin().setTypeface("Arial"); - assertEquals("Arial", r1.getFontFamily()); - assertEquals(STTextAlignType.L, lv1PPr.getAlgn()); - assertEquals(TextAlign.LEFT, p1.getTextAlign()); - lv1PPr.setAlgn(STTextAlignType.R); - assertEquals(TextAlign.RIGHT, p1.getTextAlign()); - //lv2 - assertEquals(2800, lv2CPr.getSz()); - assertEquals(28.0, r2.getFontSize(), 0); - lv2CPr.setSz(3300); - assertEquals(33.0, r2.getFontSize(), 0); - lv2CPr.getLatin().setTypeface("Times"); - assertEquals("Times", r2.getFontFamily()); - assertEquals(STTextAlignType.L, lv2PPr.getAlgn()); - assertEquals(TextAlign.LEFT, p2.getTextAlign()); - lv2PPr.setAlgn(STTextAlignType.R); - assertEquals(TextAlign.RIGHT, p2.getTextAlign()); - //lv3 - assertEquals(2400, lv3CPr.getSz()); - assertEquals(24.0, r3.getFontSize(), 0); - lv3CPr.setSz(2500); - assertEquals(25.0, r3.getFontSize(), 0); - lv3CPr.getLatin().setTypeface("Courier New"); - assertEquals("Courier New", r3.getFontFamily()); - assertEquals(STTextAlignType.L, lv3PPr.getAlgn()); - assertEquals(TextAlign.LEFT, p3.getTextAlign()); - lv3PPr.setAlgn(STTextAlignType.R); - assertEquals(TextAlign.RIGHT, p3.getTextAlign()); - - - // level 2: body placeholder on the master slide - // /p:sldMaster/p:cSld/p:spTree/p:sp/p:nvPr/p:ph[@type="body"] - XSLFTextShape tx2 = master.getPlaceholder(1); - assertEquals(Placeholder.BODY, tx2.getTextType()); - - lv1PPr = tx2.getTextBody(true).getLstStyle().addNewLvl1PPr(); - lv1CPr = lv1PPr.addNewDefRPr(); - lv2PPr = tx2.getTextBody(true).getLstStyle().addNewLvl2PPr(); - lv2CPr = lv2PPr.addNewDefRPr(); - lv3PPr = tx2.getTextBody(true).getLstStyle().addNewLvl3PPr(); - lv3CPr = lv3PPr.addNewDefRPr(); - - lv1CPr.setSz(3300); - assertEquals(33.0, r1.getFontSize(), 0); - lv1CPr.addNewLatin().setTypeface("Times"); - assertEquals("Times", r1.getFontFamily()); - lv1PPr.setAlgn(STTextAlignType.L); - assertEquals(TextAlign.LEFT, p1.getTextAlign()); - - lv2CPr.setSz(3300); - assertEquals(33.0, r2.getFontSize(), 0); - lv2CPr.addNewLatin().setTypeface("Times"); - assertEquals("Times", r2.getFontFamily()); - lv2PPr.setAlgn(STTextAlignType.L); - assertEquals(TextAlign.LEFT, p2.getTextAlign()); - - lv3CPr.setSz(3300); - assertEquals(33.0, r3.getFontSize(), 0); - lv3CPr.addNewLatin().setTypeface("Times"); - assertEquals("Times", r3.getFontFamily()); - lv3PPr.setAlgn(STTextAlignType.L); - assertEquals(TextAlign.LEFT, p3.getTextAlign()); - - // level 3: body placeholder on the slide layout - // /p:sldLayout /p:cSld/p:spTree/p:sp/p:nvPr/p:ph[@type="ctrTitle"] - XSLFTextShape tx3 = layout.getPlaceholder(1); - assertEquals(Placeholder.BODY, tx2.getTextType()); - lv1PPr = tx3.getTextBody(true).getLstStyle().addNewLvl1PPr(); - lv1CPr = lv1PPr.addNewDefRPr(); - lv2PPr = tx3.getTextBody(true).getLstStyle().addNewLvl2PPr(); - lv2CPr = lv2PPr.addNewDefRPr(); - lv3PPr = tx3.getTextBody(true).getLstStyle().addNewLvl3PPr(); - lv3CPr = lv3PPr.addNewDefRPr(); - - lv1CPr.setSz(3400); - assertEquals(34.0, r1.getFontSize(), 0); - lv1CPr.addNewLatin().setTypeface("Courier New"); - assertEquals("Courier New", r1.getFontFamily()); - lv1PPr.setAlgn(STTextAlignType.CTR); - assertEquals(TextAlign.CENTER, p1.getTextAlign()); - - lv2CPr.setSz(3400); - assertEquals(34.0, r2.getFontSize(), 0); - lv2CPr.addNewLatin().setTypeface("Courier New"); - assertEquals("Courier New", r2.getFontFamily()); - lv2PPr.setAlgn(STTextAlignType.CTR); - assertEquals(TextAlign.CENTER, p2.getTextAlign()); - - lv3CPr.setSz(3400); - assertEquals(34.0, r3.getFontSize(), 0); - lv3CPr.addNewLatin().setTypeface("Courier New"); - assertEquals("Courier New", r3.getFontFamily()); - lv3PPr.setAlgn(STTextAlignType.CTR); - assertEquals(TextAlign.CENTER, p3.getTextAlign()); - - // level 4: default text properties in the shape itself - // ./p:sp/p:txBody/a:lstStyle/a:lvl1pPr - lv1PPr = tx1.getTextBody(true).getLstStyle().addNewLvl1PPr(); - lv1CPr = lv1PPr.addNewDefRPr(); - lv2PPr = tx1.getTextBody(true).getLstStyle().addNewLvl2PPr(); - lv2CPr = lv2PPr.addNewDefRPr(); - lv3PPr = tx1.getTextBody(true).getLstStyle().addNewLvl3PPr(); - lv3CPr = lv3PPr.addNewDefRPr(); - - lv1CPr.setSz(3500); - assertEquals(35.0, r1.getFontSize(), 0); - lv1CPr.addNewLatin().setTypeface("Arial"); - assertEquals("Arial", r1.getFontFamily()); - lv1PPr.setAlgn(STTextAlignType.L); - assertEquals(TextAlign.LEFT, p1.getTextAlign()); - - lv2CPr.setSz(3500); - assertEquals(35.0, r2.getFontSize(), 0); - lv2CPr.addNewLatin().setTypeface("Arial"); - assertEquals("Arial", r2.getFontFamily()); - lv2PPr.setAlgn(STTextAlignType.L); - assertEquals(TextAlign.LEFT, p2.getTextAlign()); - - lv3CPr.setSz(3500); - assertEquals(35.0, r3.getFontSize(), 0); - lv3CPr.addNewLatin().setTypeface("Arial"); - assertEquals("Arial", r3.getFontFamily()); - lv3PPr.setAlgn(STTextAlignType.L); - assertEquals(TextAlign.LEFT, p3.getTextAlign()); - - // level 5: text properties are defined in the text run - lv1PPr = p1.getXmlObject().isSetPPr() ? p1.getXmlObject().getPPr() : p1.getXmlObject().addNewPPr(); - lv1CPr = r1.getRPr(false); - lv2PPr = p2.getXmlObject().isSetPPr() ? p2.getXmlObject().getPPr() : p2.getXmlObject().addNewPPr(); - lv2CPr = r2.getRPr(false); - lv3PPr = p3.getXmlObject().isSetPPr() ? p3.getXmlObject().getPPr() : p3.getXmlObject().addNewPPr(); - lv3CPr = r3.getRPr(false); - - lv1CPr.setSz(3600); - assertEquals(36.0, r1.getFontSize(), 0); - lv1CPr.addNewLatin().setTypeface("Calibri"); - assertEquals("Calibri", r1.getFontFamily()); - lv1PPr.setAlgn(STTextAlignType.CTR); - assertEquals(TextAlign.CENTER, p1.getTextAlign()); - - lv2CPr.setSz(3600); - assertEquals(36.0, r2.getFontSize(), 0); - lv2CPr.addNewLatin().setTypeface("Calibri"); - assertEquals("Calibri", r2.getFontFamily()); - lv2PPr.setAlgn(STTextAlignType.CTR); - assertEquals(TextAlign.CENTER, p2.getTextAlign()); - - lv3CPr.setSz(3600); - assertEquals(36.0, r3.getFontSize(), 0); - lv3CPr.addNewLatin().setTypeface("Calibri"); - assertEquals("Calibri", r3.getFontFamily()); - lv3PPr.setAlgn(STTextAlignType.CTR); - assertEquals(TextAlign.CENTER, p3.getTextAlign()); - - ppt.close(); - } - - @Test - public void metroBlob() throws IOException { - assumeFalse(xslfOnly); - File f = POIDataSamples.getSlideShowInstance().getFile("bug52297.ppt"); - SlideShow ppt = SlideShowFactory.create(f); - HSLFTextShape sh = (HSLFTextShape)ppt.getSlides().get(1).getShapes().get(3); - XSLFAutoShape xsh = (XSLFAutoShape)sh.getMetroShape(); - String textExp = " ___ ___ ___ ________ __ _______ ___ ___________ __________ __ _____ ___ ___ ___ _______ ____ ______ ___________ _____________ ___ _______ ______ ____ ______ __ ___________ __________ ___ _________ _____ ________ __________ ___ _______ __________ "; - String textAct = xsh.getText(); - ppt.close(); - assertEquals(textExp, textAct); - } -} \ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTheme.java b/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTheme.java deleted file mode 100644 index 1a504e795..000000000 --- a/src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFTheme.java +++ /dev/null @@ -1,171 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xslf.usermodel; - -import static org.apache.poi.sl.TestCommonSL.sameColor; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.awt.Color; -import java.util.List; - -import org.apache.poi.sl.usermodel.PaintStyle; -import org.apache.poi.sl.usermodel.PaintStyle.GradientPaint; -import org.apache.poi.sl.usermodel.PaintStyle.SolidPaint; -import org.apache.poi.sl.usermodel.PaintStyle.TexturePaint; -import org.apache.poi.xslf.XSLFTestDataSamples; -import org.junit.Test; - -/** - * test reading properties from a multi-theme and multi-master document - * - * @author Yegor Kozlov - */ -public class TestXSLFTheme { - @Test - public void testRead(){ - XMLSlideShow ppt = XSLFTestDataSamples.openSampleDocument("themes.pptx"); - List slides = ppt.getSlides(); - - slide1(slides.get(0)); - slide2(slides.get(1)); - slide3(slides.get(2)); - slide4(slides.get(3)); - slide5(slides.get(4)); - slide6(slides.get(5)); - slide7(slides.get(6)); - slide8(slides.get(7)); - slide9(slides.get(8)); - slide10(slides.get(9)); - } - - private XSLFShape getShape(XSLFSheet sheet, String name){ - for(XSLFShape sh : sheet.getShapes()){ - if(sh.getShapeName().equals(name)) { - return sh; - } - } - throw new IllegalArgumentException("Shape not found: " + name); - } - - void slide1(XSLFSlide slide){ - assertEquals(Color.WHITE, slide.getBackground().getFillColor()); - - XSLFTheme theme = slide.getTheme(); - assertEquals("Office Theme", theme.getName()); - - XSLFTextShape sh1 = (XSLFTextShape)getShape(slide, "Rectangle 3"); - XSLFTextRun run1 = sh1.getTextParagraphs().get(0).getTextRuns().get(0); - assertTrue(sameColor(Color.white, run1.getFontColor())); - assertEquals(new Color(79, 129, 189), sh1.getFillColor()); - assertTrue(sh1.getFillStyle().getPaint() instanceof SolidPaint) ; // solid fill - - } - - void slide2(XSLFSlide slide){ - // Background 2, darker 10% - // YK: PPT shows slightly different color: new Color(221, 217, 195) - assertEquals(new Color(221, 217, 195), slide.getBackground().getFillColor()); - } - - void slide3(XSLFSlide slide){ - PaintStyle fs = slide.getBackground().getFillStyle().getPaint(); - assertTrue(fs instanceof GradientPaint); - } - - void slide4(XSLFSlide slide){ - PaintStyle fs = slide.getBackground().getFillStyle().getPaint(); - assertTrue(fs instanceof GradientPaint); - - XSLFTextShape sh1 = (XSLFTextShape)getShape(slide, "Rectangle 4"); - XSLFTextRun run1 = sh1.getTextParagraphs().get(0).getTextRuns().get(0); - assertTrue(sameColor(Color.white, run1.getFontColor())); - assertEquals(new Color(148, 198, 0), sh1.getFillColor()); - assertTrue(sh1.getFillStyle().getPaint() instanceof SolidPaint) ; // solid fill - - XSLFTextShape sh2 = (XSLFTextShape)getShape(slide, "Title 3"); - XSLFTextRun run2 = sh2.getTextParagraphs().get(0).getTextRuns().get(0); - assertTrue(sameColor(new Color(148, 198, 0), run2.getFontColor())); - assertNull(sh2.getFillColor()); // no fill - - assertTrue(slide.getSlideLayout().getFollowMasterGraphics()); - } - - void slide5(XSLFSlide slide){ - PaintStyle fs = slide.getBackground().getFillStyle().getPaint(); - assertTrue(fs instanceof TexturePaint); - - XSLFTextShape sh2 = (XSLFTextShape)getShape(slide, "Title 1"); - XSLFTextRun run2 = sh2.getTextParagraphs().get(0).getTextRuns().get(0); - assertTrue(sameColor(new Color(148, 198, 0), run2.getFontColor())); - assertNull(sh2.getFillColor()); // no fill - // font size is 40pt and scale factor is 90% - assertEquals(36.0, run2.getFontSize(), 0); - - assertTrue(slide.getSlideLayout().getFollowMasterGraphics()); - } - - void slide6(XSLFSlide slide){ - - XSLFTextShape sh1 = (XSLFTextShape)getShape(slide, "Subtitle 3"); - XSLFTextRun run1 = sh1.getTextParagraphs().get(0).getTextRuns().get(0); - assertTrue(sameColor(new Color(66, 66, 66), run1.getFontColor())); - assertNull(sh1.getFillColor()); // no fill - - XSLFTextShape sh2 = (XSLFTextShape)getShape(slide, "Title 2"); - XSLFTextRun run2 = sh2.getTextParagraphs().get(0).getTextRuns().get(0); - assertTrue(sameColor(new Color(148, 198, 0), run2.getFontColor())); - assertNull(sh2.getFillColor()); // no fill - - assertFalse(slide.getSlideLayout().getFollowMasterGraphics()); - } - - void slide7(XSLFSlide slide){ - - //YK: PPT reports a slightly different color: r=189,g=239,b=87 - assertEquals(new Color(189, 239, 87), slide.getBackground().getFillColor()); - - assertFalse(slide.getFollowMasterGraphics()); - } - - void slide8(XSLFSlide slide){ - PaintStyle fs = slide.getBackground().getFillStyle().getPaint(); - assertTrue(fs instanceof TexturePaint); - } - - void slide9(XSLFSlide slide){ - PaintStyle fs = slide.getBackground().getFillStyle().getPaint(); - assertTrue(fs instanceof TexturePaint); - } - - void slide10(XSLFSlide slide){ - PaintStyle fs = slide.getBackground().getFillStyle().getPaint(); - assertTrue(fs instanceof GradientPaint); - - XSLFTextShape sh1 = (XSLFTextShape)getShape(slide, "Title 3"); - XSLFTextRun run1 = sh1.getTextParagraphs().get(0).getTextRuns().get(0); - assertTrue(sameColor(Color.white, run1.getFontColor())); - assertNull(sh1.getFillColor()); // no fill - - XSLFTextShape sh2 = (XSLFTextShape)getShape(slide, "Subtitle 4"); - XSLFTextRun run2 = sh2.getTextParagraphs().get(0).getTextRuns().get(0); - assertTrue(sameColor(Color.white, run2.getFontColor())); - assertNull(sh2.getFillColor()); // no fill - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/AllXSSFTests.java b/src/ooxml/testcases/org/apache/poi/xssf/AllXSSFTests.java deleted file mode 100644 index c6e2f7eca..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/AllXSSFTests.java +++ /dev/null @@ -1,52 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf; - -import org.apache.poi.ss.format.TestCellFormatPart; -import org.apache.poi.xssf.eventusermodel.TestXSSFReader; -import org.apache.poi.xssf.extractor.TestXSSFExcelExtractor; -import org.apache.poi.xssf.io.TestLoadSaveXSSF; -import org.apache.poi.xssf.model.TestCommentsTable; -import org.apache.poi.xssf.model.TestSharedStringsTable; -import org.apache.poi.xssf.usermodel.AllXSSFUsermodelTests; -import org.apache.poi.xssf.util.TestCTColComparator; -import org.apache.poi.xssf.util.TestNumericRanges; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - - -/** - * Collects all tests for org.apache.poi.xssf and sub-packages. - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - AllXSSFUsermodelTests.class, - TestXSSFReader.class, - TestXSSFExcelExtractor.class, - TestLoadSaveXSSF.class, - TestCommentsTable.class, - TestSharedStringsTable.class, - //TestStylesTable.class, //converted to junit4 - //TestCellReference.class, //converted to junit4 - TestCTColComparator.class, - TestNumericRanges.class, - TestCellFormatPart.class, - TestXSSFCloneSheet.class -}) -public final class AllXSSFTests { -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/SXSSFITestDataProvider.java b/src/ooxml/testcases/org/apache/poi/xssf/SXSSFITestDataProvider.java deleted file mode 100644 index ab84979d0..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/SXSSFITestDataProvider.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xssf; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Collection; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.xssf.streaming.SXSSFSheet; -import org.apache.poi.xssf.streaming.SXSSFWorkbook; -import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -/** - * @author Yegor Kozlov - */ -public final class SXSSFITestDataProvider implements ITestDataProvider { - public static final SXSSFITestDataProvider instance = new SXSSFITestDataProvider(); - - // an instance of all SXSSFWorkbooks opened by this TestDataProvider, - // so that the temporary files created can be disposed up by cleanup() - private final Collection instances = new ArrayList(); - - private SXSSFITestDataProvider() { - // enforce singleton - } - - @Override - public Workbook openSampleWorkbook(String sampleFileName) { - XSSFWorkbook xssfWorkbook = XSSFITestDataProvider.instance.openSampleWorkbook(sampleFileName); - SXSSFWorkbook swb = new SXSSFWorkbook(xssfWorkbook); - instances.add(swb); - return swb; - } - - /** - * Returns an XSSFWorkbook since SXSSFWorkbook is write-only - */ - @Override - public XSSFWorkbook writeOutAndReadBack(Workbook wb) { - // wb is usually an SXSSFWorkbook, but must also work on an XSSFWorkbook - // since workbooks must be able to be written out and read back - // several times in succession - if(!(wb instanceof SXSSFWorkbook || wb instanceof XSSFWorkbook)) { - throw new IllegalArgumentException("Expected an instance of SXSSFWorkbook"); - } - - XSSFWorkbook result; - try { - ByteArrayOutputStream baos = new ByteArrayOutputStream(8192); - wb.write(baos); - InputStream is = new ByteArrayInputStream(baos.toByteArray()); - result = new XSSFWorkbook(is); - } catch (IOException e) { - throw new RuntimeException(e); - } - return result; - } - - @Override - public SXSSFWorkbook createWorkbook() { - SXSSFWorkbook wb = new SXSSFWorkbook(); - instances.add(wb); - return wb; - } - - //************ SXSSF-specific methods ***************// - @Override - public SXSSFWorkbook createWorkbook(int rowAccessWindowSize) { - SXSSFWorkbook wb = new SXSSFWorkbook(rowAccessWindowSize); - instances.add(wb); - return wb; - } - - @Override - public void trackAllColumnsForAutosizing(Sheet sheet) { - ((SXSSFSheet)sheet).trackAllColumnsForAutoSizing(); - } - //************ End SXSSF-specific methods ***************// - - @Override - public FormulaEvaluator createFormulaEvaluator(Workbook wb) { - return new XSSFFormulaEvaluator(((SXSSFWorkbook) wb).getXSSFWorkbook()); - } - - @Override - public byte[] getTestDataFileContent(String fileName) { - return POIDataSamples.getSpreadSheetInstance().readFile(fileName); - } - - @Override - public SpreadsheetVersion getSpreadsheetVersion() { - return SpreadsheetVersion.EXCEL2007; - } - - @Override - public String getStandardFileNameExtension() { - return "xlsx"; - } - - public synchronized boolean cleanup() { - boolean ok = true; - for(final SXSSFWorkbook wb : instances) { - ok = ok && wb.dispose(); - } - instances.clear(); - return ok; - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/TestSheetProtection.java b/src/ooxml/testcases/org/apache/poi/xssf/TestSheetProtection.java deleted file mode 100644 index 9e126097c..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/TestSheetProtection.java +++ /dev/null @@ -1,260 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf; - -import junit.framework.TestCase; - -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -public class TestSheetProtection extends TestCase { - private XSSFSheet sheet; - - @Override - protected void setUp() throws Exception { - XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("sheetProtection_not_protected.xlsx"); - sheet = workbook.getSheetAt(0); - } - - public void testShouldReadWorkbookProtection() throws Exception { - assertFalse(sheet.isAutoFilterLocked()); - assertFalse(sheet.isDeleteColumnsLocked()); - assertFalse(sheet.isDeleteRowsLocked()); - assertFalse(sheet.isFormatCellsLocked()); - assertFalse(sheet.isFormatColumnsLocked()); - assertFalse(sheet.isFormatRowsLocked()); - assertFalse(sheet.isInsertColumnsLocked()); - assertFalse(sheet.isInsertHyperlinksLocked()); - assertFalse(sheet.isInsertRowsLocked()); - assertFalse(sheet.isPivotTablesLocked()); - assertFalse(sheet.isSortLocked()); - assertFalse(sheet.isObjectsLocked()); - assertFalse(sheet.isScenariosLocked()); - assertFalse(sheet.isSelectLockedCellsLocked()); - assertFalse(sheet.isSelectUnlockedCellsLocked()); - assertFalse(sheet.isSheetLocked()); - - sheet = XSSFTestDataSamples.openSampleWorkbook("sheetProtection_allLocked.xlsx").getSheetAt(0); - - assertTrue(sheet.isAutoFilterLocked()); - assertTrue(sheet.isDeleteColumnsLocked()); - assertTrue(sheet.isDeleteRowsLocked()); - assertTrue(sheet.isFormatCellsLocked()); - assertTrue(sheet.isFormatColumnsLocked()); - assertTrue(sheet.isFormatRowsLocked()); - assertTrue(sheet.isInsertColumnsLocked()); - assertTrue(sheet.isInsertHyperlinksLocked()); - assertTrue(sheet.isInsertRowsLocked()); - assertTrue(sheet.isPivotTablesLocked()); - assertTrue(sheet.isSortLocked()); - assertTrue(sheet.isObjectsLocked()); - assertTrue(sheet.isScenariosLocked()); - assertTrue(sheet.isSelectLockedCellsLocked()); - assertTrue(sheet.isSelectUnlockedCellsLocked()); - assertTrue(sheet.isSheetLocked()); - } - - public void testWriteAutoFilter() throws Exception { - assertFalse(sheet.isAutoFilterLocked()); - sheet.lockAutoFilter(true); - assertFalse(sheet.isAutoFilterLocked()); - sheet.enableLocking(); - assertTrue(sheet.isAutoFilterLocked()); - sheet.lockAutoFilter(false); - assertFalse(sheet.isAutoFilterLocked()); - } - - public void testWriteDeleteColumns() throws Exception { - assertFalse(sheet.isDeleteColumnsLocked()); - sheet.lockDeleteColumns(true); - assertFalse(sheet.isDeleteColumnsLocked()); - sheet.enableLocking(); - assertTrue(sheet.isDeleteColumnsLocked()); - sheet.lockDeleteColumns(false); - assertFalse(sheet.isDeleteColumnsLocked()); - } - - public void testWriteDeleteRows() throws Exception { - assertFalse(sheet.isDeleteRowsLocked()); - sheet.lockDeleteRows(true); - assertFalse(sheet.isDeleteRowsLocked()); - sheet.enableLocking(); - assertTrue(sheet.isDeleteRowsLocked()); - sheet.lockDeleteRows(false); - assertFalse(sheet.isDeleteRowsLocked()); - } - - public void testWriteFormatCells() throws Exception { - assertFalse(sheet.isFormatCellsLocked()); - sheet.lockFormatCells(true); - assertFalse(sheet.isFormatCellsLocked()); - sheet.enableLocking(); - assertTrue(sheet.isFormatCellsLocked()); - sheet.lockFormatCells(false); - assertFalse(sheet.isFormatCellsLocked()); - } - - public void testWriteFormatColumns() throws Exception { - assertFalse(sheet.isFormatColumnsLocked()); - sheet.lockFormatColumns(true); - assertFalse(sheet.isFormatColumnsLocked()); - sheet.enableLocking(); - assertTrue(sheet.isFormatColumnsLocked()); - sheet.lockFormatColumns(false); - assertFalse(sheet.isFormatColumnsLocked()); - } - - public void testWriteFormatRows() throws Exception { - assertFalse(sheet.isFormatRowsLocked()); - sheet.lockFormatRows(true); - assertFalse(sheet.isFormatRowsLocked()); - sheet.enableLocking(); - assertTrue(sheet.isFormatRowsLocked()); - sheet.lockFormatRows(false); - assertFalse(sheet.isFormatRowsLocked()); - } - - public void testWriteInsertColumns() throws Exception { - assertFalse(sheet.isInsertColumnsLocked()); - sheet.lockInsertColumns(true); - assertFalse(sheet.isInsertColumnsLocked()); - sheet.enableLocking(); - assertTrue(sheet.isInsertColumnsLocked()); - sheet.lockInsertColumns(false); - assertFalse(sheet.isInsertColumnsLocked()); - } - - public void testWriteInsertHyperlinks() throws Exception { - assertFalse(sheet.isInsertHyperlinksLocked()); - sheet.lockInsertHyperlinks(true); - assertFalse(sheet.isInsertHyperlinksLocked()); - sheet.enableLocking(); - assertTrue(sheet.isInsertHyperlinksLocked()); - sheet.lockInsertHyperlinks(false); - assertFalse(sheet.isInsertHyperlinksLocked()); - } - - public void testWriteInsertRows() throws Exception { - assertFalse(sheet.isInsertRowsLocked()); - sheet.lockInsertRows(true); - assertFalse(sheet.isInsertRowsLocked()); - sheet.enableLocking(); - assertTrue(sheet.isInsertRowsLocked()); - sheet.lockInsertRows(false); - assertFalse(sheet.isInsertRowsLocked()); - } - - public void testWritePivotTables() throws Exception { - assertFalse(sheet.isPivotTablesLocked()); - sheet.lockPivotTables(true); - assertFalse(sheet.isPivotTablesLocked()); - sheet.enableLocking(); - assertTrue(sheet.isPivotTablesLocked()); - sheet.lockPivotTables(false); - assertFalse(sheet.isPivotTablesLocked()); - } - - public void testWriteSort() throws Exception { - assertFalse(sheet.isSortLocked()); - sheet.lockSort(true); - assertFalse(sheet.isSortLocked()); - sheet.enableLocking(); - assertTrue(sheet.isSortLocked()); - sheet.lockSort(false); - assertFalse(sheet.isSortLocked()); - } - - public void testWriteObjects() throws Exception { - assertFalse(sheet.isObjectsLocked()); - sheet.lockObjects(true); - assertFalse(sheet.isObjectsLocked()); - sheet.enableLocking(); - assertTrue(sheet.isObjectsLocked()); - sheet.lockObjects(false); - assertFalse(sheet.isObjectsLocked()); - } - - public void testWriteScenarios() throws Exception { - assertFalse(sheet.isScenariosLocked()); - sheet.lockScenarios(true); - assertFalse(sheet.isScenariosLocked()); - sheet.enableLocking(); - assertTrue(sheet.isScenariosLocked()); - sheet.lockScenarios(false); - assertFalse(sheet.isScenariosLocked()); - } - - public void testWriteSelectLockedCells() throws Exception { - assertFalse(sheet.isSelectLockedCellsLocked()); - sheet.lockSelectLockedCells(true); - assertFalse(sheet.isSelectLockedCellsLocked()); - sheet.enableLocking(); - assertTrue(sheet.isSelectLockedCellsLocked()); - sheet.lockSelectLockedCells(false); - assertFalse(sheet.isSelectLockedCellsLocked()); - } - - public void testWriteSelectUnlockedCells() throws Exception { - assertFalse(sheet.isSelectUnlockedCellsLocked()); - sheet.lockSelectUnlockedCells(true); - assertFalse(sheet.isSelectUnlockedCellsLocked()); - sheet.enableLocking(); - assertTrue(sheet.isSelectUnlockedCellsLocked()); - sheet.lockSelectUnlockedCells(false); - assertFalse(sheet.isSelectUnlockedCellsLocked()); - } - - public void testWriteSelectEnableLocking() throws Exception { - sheet = XSSFTestDataSamples.openSampleWorkbook("sheetProtection_allLocked.xlsx").getSheetAt(0); - - assertTrue(sheet.isAutoFilterLocked()); - assertTrue(sheet.isDeleteColumnsLocked()); - assertTrue(sheet.isDeleteRowsLocked()); - assertTrue(sheet.isFormatCellsLocked()); - assertTrue(sheet.isFormatColumnsLocked()); - assertTrue(sheet.isFormatRowsLocked()); - assertTrue(sheet.isInsertColumnsLocked()); - assertTrue(sheet.isInsertHyperlinksLocked()); - assertTrue(sheet.isInsertRowsLocked()); - assertTrue(sheet.isPivotTablesLocked()); - assertTrue(sheet.isSortLocked()); - assertTrue(sheet.isObjectsLocked()); - assertTrue(sheet.isScenariosLocked()); - assertTrue(sheet.isSelectLockedCellsLocked()); - assertTrue(sheet.isSelectUnlockedCellsLocked()); - assertTrue(sheet.isSheetLocked()); - - sheet.disableLocking(); - - assertFalse(sheet.isAutoFilterLocked()); - assertFalse(sheet.isDeleteColumnsLocked()); - assertFalse(sheet.isDeleteRowsLocked()); - assertFalse(sheet.isFormatCellsLocked()); - assertFalse(sheet.isFormatColumnsLocked()); - assertFalse(sheet.isFormatRowsLocked()); - assertFalse(sheet.isInsertColumnsLocked()); - assertFalse(sheet.isInsertHyperlinksLocked()); - assertFalse(sheet.isInsertRowsLocked()); - assertFalse(sheet.isPivotTablesLocked()); - assertFalse(sheet.isSortLocked()); - assertFalse(sheet.isObjectsLocked()); - assertFalse(sheet.isScenariosLocked()); - assertFalse(sheet.isSelectLockedCellsLocked()); - assertFalse(sheet.isSelectUnlockedCellsLocked()); - assertFalse(sheet.isSheetLocked()); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/TestWorkbookProtection.java b/src/ooxml/testcases/org/apache/poi/xssf/TestWorkbookProtection.java deleted file mode 100644 index 9c7e9355d..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/TestWorkbookProtection.java +++ /dev/null @@ -1,236 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf; - -import static org.apache.poi.xssf.XSSFTestDataSamples.openSampleWorkbook; -import static org.apache.poi.xssf.XSSFTestDataSamples.writeOutAndReadBack; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.OutputStream; - -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.poifs.crypt.CryptoFunctions; -import org.apache.poi.poifs.crypt.Decryptor; -import org.apache.poi.poifs.crypt.EncryptionInfo; -import org.apache.poi.poifs.crypt.EncryptionMode; -import org.apache.poi.poifs.crypt.Encryptor; -import org.apache.poi.poifs.crypt.HashAlgorithm; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.TempFile; -import org.apache.poi.xssf.usermodel.XSSFCell; -import org.apache.poi.xssf.usermodel.XSSFRow; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Ignore; -import org.junit.Test; - -public class TestWorkbookProtection { - - @Test - public void workbookAndRevisionPassword() throws Exception { - XSSFWorkbook workbook; - String password = "test"; - - // validate password with an actual office file (Excel 2010) - workbook = openSampleWorkbook("workbookProtection-workbook_password_user_range-2010.xlsx"); - assertTrue(workbook.validateWorkbookPassword(password)); - - // validate with another office file (Excel 2013) - workbook = openSampleWorkbook("workbookProtection-workbook_password-2013.xlsx"); - assertTrue(workbook.validateWorkbookPassword(password)); - - - workbook = openSampleWorkbook("workbookProtection_not_protected.xlsx"); - - // setting a null password shouldn't introduce the protection element - workbook.setWorkbookPassword(null, null); - assertNull(workbook.getCTWorkbook().getWorkbookProtection()); - - // compare the hashes - workbook.setWorkbookPassword(password, null); - int hashVal = CryptoFunctions.createXorVerifier1(password); - int actualVal = Integer.parseInt(workbook.getCTWorkbook().getWorkbookProtection().xgetWorkbookPassword().getStringValue(),16); - assertEquals(hashVal, actualVal); - assertTrue(workbook.validateWorkbookPassword(password)); - - // removing the password again - workbook.setWorkbookPassword(null, null); - assertFalse(workbook.getCTWorkbook().getWorkbookProtection().isSetWorkbookPassword()); - - // removing the whole protection structure - workbook.unLock(); - assertNull(workbook.getCTWorkbook().getWorkbookProtection()); - - // setting a null password shouldn't introduce the protection element - workbook.setRevisionsPassword(null, null); - assertNull(workbook.getCTWorkbook().getWorkbookProtection()); - - // compare the hashes - password = "T\u0400ST\u0100passwordWhichIsLongerThan15Chars"; - workbook.setRevisionsPassword(password, null); - hashVal = CryptoFunctions.createXorVerifier1(password); - actualVal = Integer.parseInt(workbook.getCTWorkbook().getWorkbookProtection().xgetRevisionsPassword().getStringValue(),16); - assertEquals(hashVal, actualVal); - assertTrue(workbook.validateRevisionsPassword(password)); - } - - @Test - public void shouldReadWorkbookProtection() throws Exception { - XSSFWorkbook workbook = openSampleWorkbook("workbookProtection_not_protected.xlsx"); - assertFalse(workbook.isStructureLocked()); - assertFalse(workbook.isWindowsLocked()); - assertFalse(workbook.isRevisionLocked()); - - workbook = openSampleWorkbook("workbookProtection_workbook_structure_protected.xlsx"); - assertTrue(workbook.isStructureLocked()); - assertFalse(workbook.isWindowsLocked()); - assertFalse(workbook.isRevisionLocked()); - - workbook = openSampleWorkbook("workbookProtection_workbook_windows_protected.xlsx"); - assertTrue(workbook.isWindowsLocked()); - assertFalse(workbook.isStructureLocked()); - assertFalse(workbook.isRevisionLocked()); - - workbook = openSampleWorkbook("workbookProtection_workbook_revision_protected.xlsx"); - assertTrue(workbook.isRevisionLocked()); - assertFalse(workbook.isWindowsLocked()); - assertFalse(workbook.isStructureLocked()); - } - - @Test - public void shouldWriteStructureLock() throws Exception { - XSSFWorkbook workbook = openSampleWorkbook("workbookProtection_not_protected.xlsx"); - assertFalse(workbook.isStructureLocked()); - - workbook.lockStructure(); - - assertTrue(workbook.isStructureLocked()); - - workbook.unLockStructure(); - - assertFalse(workbook.isStructureLocked()); - } - - @Test - public void shouldWriteWindowsLock() throws Exception { - XSSFWorkbook workbook = openSampleWorkbook("workbookProtection_not_protected.xlsx"); - assertFalse(workbook.isWindowsLocked()); - - workbook.lockWindows(); - - assertTrue(workbook.isWindowsLocked()); - - workbook.unLockWindows(); - - assertFalse(workbook.isWindowsLocked()); - } - - @Test - public void shouldWriteRevisionLock() throws Exception { - XSSFWorkbook workbook = openSampleWorkbook("workbookProtection_not_protected.xlsx"); - assertFalse(workbook.isRevisionLocked()); - - workbook.lockRevision(); - - assertTrue(workbook.isRevisionLocked()); - - workbook.unLockRevision(); - - assertFalse(workbook.isRevisionLocked()); - } - - @SuppressWarnings("resource") - @Test - public void testHashPassword() throws Exception { - XSSFWorkbook wb = new XSSFWorkbook(); - wb.lockRevision(); - wb.setRevisionsPassword("test", HashAlgorithm.sha1); - - wb = writeOutAndReadBack(wb); - - assertTrue(wb.isRevisionLocked()); - assertTrue(wb.validateRevisionsPassword("test")); - } - - @SuppressWarnings("resource") - @Test - public void testIntegration() throws Exception { - XSSFWorkbook wb = new XSSFWorkbook(); - wb.createSheet("Testing purpose sheet"); - assertFalse(wb.isRevisionLocked()); - - wb.lockRevision(); - wb.setRevisionsPassword("test", null); - - wb = writeOutAndReadBack(wb); - - assertTrue(wb.isRevisionLocked()); - assertTrue(wb.validateRevisionsPassword("test")); - } - - @Test - public void testEncryptDecrypt() throws Exception { - final String password = "abc123"; - final String sheetName = "TestSheet1"; - final String cellValue = "customZipEntrySource"; - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFSheet sheet1 = workbook.createSheet(sheetName); - XSSFRow row1 = sheet1.createRow(1); - XSSFCell cell1 = row1.createCell(1); - cell1.setCellValue(cellValue); - File tf1 = TempFile.createTempFile("poitest", ".xlsx"); - FileOutputStream fos1 = new FileOutputStream(tf1); - workbook.write(fos1); - IOUtils.closeQuietly(fos1); - POIFSFileSystem poiFileSystem = new POIFSFileSystem(); - EncryptionInfo encryptionInfo = new EncryptionInfo(EncryptionMode.agile); - Encryptor enc = encryptionInfo.getEncryptor(); - enc.confirmPassword(password); - FileInputStream fis = new FileInputStream(tf1); - OPCPackage opc = OPCPackage.open(fis); - IOUtils.closeQuietly(fis); - try { - OutputStream os = enc.getDataStream(poiFileSystem); - opc.save(os); - IOUtils.closeQuietly(os); - } finally { - IOUtils.closeQuietly(opc); - } - tf1.delete(); - FileOutputStream fos2 = new FileOutputStream(tf1); - poiFileSystem.writeFilesystem(fos2); - IOUtils.closeQuietly(fos2); - workbook.close(); - fis = new FileInputStream(tf1); - POIFSFileSystem poiFileSystem2 = new POIFSFileSystem(fis); - IOUtils.closeQuietly(fis); - EncryptionInfo encryptionInfo2 = new EncryptionInfo(poiFileSystem2); - Decryptor decryptor = encryptionInfo2.getDecryptor(); - decryptor.verifyPassword(password); - XSSFWorkbook workbook2 = new XSSFWorkbook(decryptor.getDataStream(poiFileSystem2)); - workbook2.close(); - tf1.delete(); - } - -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/TestXSSFCloneSheet.java b/src/ooxml/testcases/org/apache/poi/xssf/TestXSSFCloneSheet.java deleted file mode 100644 index a1b5bd85d..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/TestXSSFCloneSheet.java +++ /dev/null @@ -1,88 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; - -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.ss.usermodel.BaseTestCloneSheet; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.util.TempFile; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Before; -import org.junit.Test; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; - -public class TestXSSFCloneSheet extends BaseTestCloneSheet { - public TestXSSFCloneSheet() { - super(HSSFITestDataProvider.instance); - } - - private static final String OTHER_SHEET_NAME = "Another"; - private static final String VALID_SHEET_NAME = "Sheet01"; - private XSSFWorkbook wb; - - @Before - public void setUp() { - wb = new XSSFWorkbook(); - wb.createSheet(VALID_SHEET_NAME); - } - - @Test - public void testCloneSheetIntStringValidName() { - XSSFSheet cloned = wb.cloneSheet(0, OTHER_SHEET_NAME); - assertEquals(OTHER_SHEET_NAME, cloned.getSheetName()); - assertEquals(2, wb.getNumberOfSheets()); - } - - @Test - public void testCloneSheetIntStringInvalidName() { - try { - wb.cloneSheet(0, VALID_SHEET_NAME); - fail("Should fail"); - } catch (IllegalArgumentException e) { - // expected here - } - assertEquals(1, wb.getNumberOfSheets()); - } - - @Test - public void test60512() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("60512.xlsm"); - - assertEquals(1, wb.getNumberOfSheets()); - Sheet sheet = wb.cloneSheet(0); - assertNotNull(sheet); - assertEquals(2, wb.getNumberOfSheets()); - - - Workbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb); - assertNotNull(wbBack); - wbBack.close(); - - wb.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/XSSFITestDataProvider.java b/src/ooxml/testcases/org/apache/poi/xssf/XSSFITestDataProvider.java deleted file mode 100644 index e0ba6617c..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/XSSFITestDataProvider.java +++ /dev/null @@ -1,86 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -/** - * @author Yegor Kozlov - */ -public final class XSSFITestDataProvider implements ITestDataProvider { - public static final XSSFITestDataProvider instance = new XSSFITestDataProvider(); - - private XSSFITestDataProvider() { - // enforce singleton - } - - @Override - public XSSFWorkbook openSampleWorkbook(String sampleFileName) { - return XSSFTestDataSamples.openSampleWorkbook(sampleFileName); - } - - @Override - public XSSFWorkbook writeOutAndReadBack(Workbook original) { - if(!(original instanceof XSSFWorkbook)) { - throw new IllegalArgumentException("Expected an instance of XSSFWorkbook, but had " + original.getClass()); - } - return XSSFTestDataSamples.writeOutAndReadBack((XSSFWorkbook)original); - } - - @Override - public XSSFWorkbook createWorkbook() { - return new XSSFWorkbook(); - } - - //************ SXSSF-specific methods ***************// - @Override - public XSSFWorkbook createWorkbook(int rowAccessWindowSize) { - return createWorkbook(); - } - - @Override - public void trackAllColumnsForAutosizing(Sheet sheet) {} - //************ End SXSSF-specific methods ***************// - - @Override - public FormulaEvaluator createFormulaEvaluator(Workbook wb) { - return new XSSFFormulaEvaluator((XSSFWorkbook) wb); - } - - @Override - public byte[] getTestDataFileContent(String fileName) { - return POIDataSamples.getSpreadSheetInstance().readFile(fileName); - } - - @Override - public SpreadsheetVersion getSpreadsheetVersion(){ - return SpreadsheetVersion.EXCEL2007; - } - - @Override - public String getStandardFileNameExtension() { - return "xlsx"; - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/XSSFTestDataSamples.java b/src/ooxml/testcases/org/apache/poi/xssf/XSSFTestDataSamples.java deleted file mode 100644 index 68188cb22..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/XSSFTestDataSamples.java +++ /dev/null @@ -1,289 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.util.TempFile; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -/** - * Centralises logic for finding/opening sample files in the test-data/spreadsheet folder. - * - * @author Josh Micich - */ -public class XSSFTestDataSamples { - /** - * Used by {@link writeOutAndReadBack(R wb, String testName)}. If a - * value is set for this in the System Properties, the xlsx file - * will be written out to that directory. - */ - public static final String TEST_OUTPUT_DIR = "poi.test.xssf.output.dir"; - - public static File getSampleFile(String sampleFileName) { - return HSSFTestDataSamples.getSampleFile(sampleFileName); - } - public static OPCPackage openSamplePackage(String sampleName) { - try { - return OPCPackage.open(HSSFTestDataSamples.openSampleFileStream(sampleName)); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - public static XSSFWorkbook openSampleWorkbook(String sampleName) { - InputStream is = HSSFTestDataSamples.openSampleFileStream(sampleName); - try { - return new XSSFWorkbook(is); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - /** - * Write out workbook wb to {@link #TEST_OUTPUT_DIR}/testName.xlsx - * (or create a temporary file if TEST_OUTPUT_DIR is not defined). - * - * @param wb the workbook to write - * @param testName a fragment of the filename - * @return the location where the workbook was saved - * @throws IOException - */ - public static File writeOut(R wb, String testName) throws IOException { - final String testOutputDir = System.getProperty(TEST_OUTPUT_DIR); - final File file; - if (testOutputDir != null) { - file = new File(testOutputDir, testName + ".xlsx"); - } - else { - file = TempFile.createTempFile(testName, ".xlsx"); - } - if (file.exists()) { - file.delete(); - } - final OutputStream out = new FileOutputStream(file); - try { - wb.write(out); - } finally { - out.close(); - } - return file; - } - - /** - * Write out workbook wb to a memory buffer - * - * @param wb the workbook to write - * @return the memory buffer - * @throws IOException - */ - public static ByteArrayOutputStream writeOut(R wb) throws IOException { - ByteArrayOutputStream out = new ByteArrayOutputStream(8192); - wb.write(out); - return out; - } - - /** - * Write out the workbook then closes the workbook. - * This should be used when there is insufficient memory to have - * both workbooks open. - * - * Make sure there are no references to any objects in the workbook - * so that garbage collection may free the workbook. - * - * After calling this method, null the reference to wb, - * then call {@link #readBack(File)} or {@link #readBackAndDelete(File)} to re-read the file. - * - * Alternatively, use {@link #writeOutAndClose(Workbook)} to use a ByteArrayOutputStream/ByteArrayInputStream - * to avoid creating a temporary file. However, this may complicate the calling - * code to avoid having the workbook, BAOS, and BAIS open at the same time. - * - * @param wb - * @param testName file name to be used to write to a file. This file will be cleaned up by a call to readBack(String) - * @return workbook location - * @throws RuntimeException if {@link #TEST_OUTPUT_DIR} System property is not set - */ - public static File writeOutAndClose(R wb, String testName) { - try { - File file = writeOut(wb, testName); - // Do not close the workbook if there was a problem writing the workbook - wb.close(); - return file; - } - catch (final IOException e) { - throw new RuntimeException(e); - } - } - - - /** - * Write out workbook wb to a memory buffer, - * then close the workbook - * - * @param wb the workbook to write - * @return the memory buffer - * @throws IOException - */ - public static ByteArrayOutputStream writeOutAndClose(R wb) { - try { - ByteArrayOutputStream out = writeOut(wb); - // Do not close the workbook if there was a problem writing the workbook - wb.close(); - return out; - } - catch (final IOException e) { - throw new RuntimeException(e); - } - } - - /** - * Read back a workbook that was written out to a file with - * {@link #writeOut(Workbook, String))} or {@link #writeOutAndClose(Workbook, String)}. - * Deletes the file after reading back the file. - * Does not delete the file if an exception is raised. - * - * @param file the workbook file to read and delete - * @return the read back workbook - * @throws IOException - */ - public static XSSFWorkbook readBackAndDelete(File file) throws IOException { - XSSFWorkbook wb = readBack(file); - // do not delete the file if there's an error--might be helpful for debugging - file.delete(); - return wb; - } - - /** - * Read back a workbook that was written out to a file with - * {@link #writeOut(Workbook, String)} or {@link #writeOutAndClose(Workbook, String)}. - * - * @param file the workbook file to read - * @return the read back workbook - * @throws IOException - */ - public static XSSFWorkbook readBack(File file) throws IOException { - InputStream in = new FileInputStream(file); - try { - return new XSSFWorkbook(in); - } - finally { - in.close(); - } - } - - /** - * Read back a workbook that was written out to a memory buffer with - * {@link #writeOut(Workbook)} or {@link #writeOutAndClose(Workbook)}. - * - * @param file the workbook file to read - * @return the read back workbook - * @throws IOException - */ - public static XSSFWorkbook readBack(ByteArrayOutputStream out) throws IOException { - InputStream is = new ByteArrayInputStream(out.toByteArray()); - out.close(); - try { - return new XSSFWorkbook(is); - } - finally { - is.close(); - } - } - - /** - * Write out and read back using a memory buffer to avoid disk I/O. - * If there is not enough memory to have two workbooks open at the same time, - * consider using: - * - * Workbook wb = new XSSFWorkbook(); - * String testName = "example"; - * - * - * File file = writeOutAndClose(wb, testName); - * // clear all references that would prevent the workbook from getting garbage collected - * wb = null; - * Workbook wbBack = readBackAndDelete(file); - * - * - * @param wb the workbook to write out - * @return the read back workbook - */ - public static R writeOutAndReadBack(R wb) { - Workbook result; - try { - result = readBack(writeOut(wb)); - } catch (IOException e) { - throw new RuntimeException(e); - } - @SuppressWarnings("unchecked") - R r = (R) result; - return r; - } - - /** - * Write out, close, and read back the workbook using a memory buffer to avoid disk I/O. - * - * @param wb the workbook to write out and close - * @return the read back workbook - */ - public static R writeOutCloseAndReadBack(R wb) { - Workbook result; - try { - result = readBack(writeOutAndClose(wb)); - } catch (IOException e) { - throw new RuntimeException(e); - } - @SuppressWarnings("unchecked") - R r = (R) result; - return r; - - } - - /** - * Writes the Workbook either into a file or into a byte array, depending on presence of - * the system property {@value #TEST_OUTPUT_DIR}, and reads it in a new instance of the Workbook back. - * If TEST_OUTPUT_DIR is set, the file will NOT be deleted at the end of this function. - * @param wb workbook to write - * @param testName file name to be used if writing into a file. The old file with the same name will be overridden. - * @return new instance read from the stream written by the wb parameter. - */ - - public static R writeOutAndReadBack(R wb, String testName) { - if (System.getProperty(TEST_OUTPUT_DIR) == null) { - return writeOutAndReadBack(wb); - } else { - try { - Workbook result = readBack(writeOut(wb, testName)); - @SuppressWarnings("unchecked") - R r = (R) result; - return r; - } catch (IOException e) { - throw new RuntimeException(e); - } - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/binary/TestXSSFBSharedStringsTable.java b/src/ooxml/testcases/org/apache/poi/xssf/binary/TestXSSFBSharedStringsTable.java deleted file mode 100644 index 7bf1cf391..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/binary/TestXSSFBSharedStringsTable.java +++ /dev/null @@ -1,56 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.binary; - -import static org.junit.Assert.assertEquals; - -import java.util.List; -import java.util.regex.Pattern; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.junit.Test; - -public class TestXSSFBSharedStringsTable { - - - private static POIDataSamples _ssTests = POIDataSamples.getSpreadSheetInstance(); - - @Test - public void testBasic() throws Exception { - - OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("51519.xlsb")); - List parts = pkg.getPartsByName(Pattern.compile("/xl/sharedStrings.bin")); - assertEquals(1, parts.size()); - - XSSFBSharedStringsTable rtbl = new XSSFBSharedStringsTable(parts.get(0)); - List strings = rtbl.getItems(); - assertEquals(49, strings.size()); - - assertEquals("\u30B3\u30E1\u30F3\u30C8", rtbl.getEntryAt(0)); - assertEquals("\u65E5\u672C\u30AA\u30E9\u30AF\u30EB", rtbl.getEntryAt(3)); - assertEquals(55, rtbl.getCount()); - assertEquals(49, rtbl.getUniqueCount()); - - //TODO: add in tests for phonetic runs - - } - - -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/binary/TestXSSFBSheetHyperlinkManager.java b/src/ooxml/testcases/org/apache/poi/xssf/binary/TestXSSFBSheetHyperlinkManager.java deleted file mode 100644 index 992517dfc..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/binary/TestXSSFBSheetHyperlinkManager.java +++ /dev/null @@ -1,54 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.binary; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import java.util.List; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.ss.util.CellAddress; -import org.apache.poi.xssf.eventusermodel.XSSFBReader; -import org.apache.poi.xssf.eventusermodel.XSSFReader; -import org.junit.Test; - -public class TestXSSFBSheetHyperlinkManager { - - private static POIDataSamples _ssTests = POIDataSamples.getSpreadSheetInstance(); - - @Test - public void testBasic() throws Exception { - - OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("hyperlink.xlsb")); - XSSFBReader reader = new XSSFBReader(pkg); - XSSFReader.SheetIterator it = (XSSFReader.SheetIterator) reader.getSheetsData(); - it.next(); - XSSFBHyperlinksTable manager = new XSSFBHyperlinksTable(it.getSheetPart()); - List records = manager.getHyperLinks().get(new CellAddress(0, 0)); - assertNotNull(records); - assertEquals(1, records.size()); - XSSFHyperlinkRecord record = records.get(0); - assertEquals("http://tika.apache.org/", record.getLocation()); - assertEquals("rId2", record.getRelId()); - - } - - -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/eventusermodel/TestReadOnlySharedStringsTable.java b/src/ooxml/testcases/org/apache/poi/xssf/eventusermodel/TestReadOnlySharedStringsTable.java deleted file mode 100644 index 4b5e62cc5..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/eventusermodel/TestReadOnlySharedStringsTable.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xssf.eventusermodel; - -import java.io.IOException; -import java.util.List; -import java.util.regex.Pattern; - -import junit.framework.TestCase; -import org.apache.poi.POIDataSamples; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.xssf.model.SharedStringsTable; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRst; -import org.xml.sax.SAXException; - -/** - * Tests for {@link org.apache.poi.xssf.eventusermodel.XSSFReader} - */ -public final class TestReadOnlySharedStringsTable extends TestCase { - private static POIDataSamples _ssTests = POIDataSamples.getSpreadSheetInstance(); - - public void testParse() throws Exception { - OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("SampleSS.xlsx")); - List parts = pkg.getPartsByName(Pattern.compile("/xl/sharedStrings.xml")); - assertEquals(1, parts.size()); - - SharedStringsTable stbl = new SharedStringsTable(parts.get(0)); - ReadOnlySharedStringsTable rtbl = new ReadOnlySharedStringsTable(parts.get(0)); - - assertEquals(stbl.getCount(), rtbl.getCount()); - assertEquals(stbl.getUniqueCount(), rtbl.getUniqueCount()); - - assertEquals(stbl.getItems().size(), stbl.getUniqueCount()); - assertEquals(rtbl.getItems().size(), rtbl.getUniqueCount()); - for(int i=0; i < stbl.getUniqueCount(); i++){ - CTRst i1 = stbl.getEntryAt(i); - String i2 = rtbl.getEntryAt(i); - assertEquals(i1.getT(), i2); - } - - } - - //51519 - public void testPhoneticRuns() throws Exception { - OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("51519.xlsx")); - List parts = pkg.getPartsByName(Pattern.compile("/xl/sharedStrings.xml")); - assertEquals(1, parts.size()); - - ReadOnlySharedStringsTable rtbl = new ReadOnlySharedStringsTable(parts.get(0), true); - List strings = rtbl.getItems(); - assertEquals(49, strings.size()); - - assertEquals("\u30B3\u30E1\u30F3\u30C8", rtbl.getEntryAt(0)); - assertEquals("\u65E5\u672C\u30AA\u30E9\u30AF\u30EB \u30CB\u30DB\u30F3", rtbl.getEntryAt(3)); - - //now do not include phonetic runs - rtbl = new ReadOnlySharedStringsTable(parts.get(0), false); - strings = rtbl.getItems(); - assertEquals(49, strings.size()); - - assertEquals("\u30B3\u30E1\u30F3\u30C8", rtbl.getEntryAt(0)); - assertEquals("\u65E5\u672C\u30AA\u30E9\u30AF\u30EB", rtbl.getEntryAt(3)); - - } - - public void testEmptySSTOnPackageObtainedViaWorkbook() throws Exception { - XSSFWorkbook wb = new XSSFWorkbook(_ssTests.openResourceAsStream("noSharedStringTable.xlsx")); - OPCPackage pkg = wb.getPackage(); - assertEmptySST(pkg); - wb.close(); - } - - public void testEmptySSTOnPackageDirect() throws Exception { - OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("noSharedStringTable.xlsx")); - assertEmptySST(pkg); - } - - private void assertEmptySST(OPCPackage pkg) throws IOException, SAXException { - ReadOnlySharedStringsTable sst = new ReadOnlySharedStringsTable(pkg); - assertEquals(0, sst.getCount()); - assertEquals(0, sst.getUniqueCount()); - assertNull(sst.getItems()); // same state it's left in if fed a package which has no SST part. - } - -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/eventusermodel/TestXSSFBReader.java b/src/ooxml/testcases/org/apache/poi/xssf/eventusermodel/TestXSSFBReader.java deleted file mode 100644 index 6ea533276..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/eventusermodel/TestXSSFBReader.java +++ /dev/null @@ -1,211 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.eventusermodel; - -import static org.apache.poi.POITestCase.assertContains; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.ss.usermodel.DataFormatter; -import org.apache.poi.xssf.binary.XSSFBSharedStringsTable; -import org.apache.poi.xssf.binary.XSSFBSheetHandler; -import org.apache.poi.xssf.binary.XSSFBStylesTable; -import org.apache.poi.xssf.usermodel.XSSFComment; -import org.junit.Test; - -public class TestXSSFBReader { - - private static POIDataSamples _ssTests = POIDataSamples.getSpreadSheetInstance(); - - @Test - public void testBasic() throws Exception { - List sheetTexts = getSheets("testVarious.xlsb"); - - assertEquals(1, sheetTexts.size()); - String xsxml = sheetTexts.get(0); - assertContains(xsxml, "This is a string"); - assertContains(xsxml, "13"); - assertContains(xsxml, "13.12112313"); - assertContains(xsxml, "$ 3.03"); - assertContains(xsxml, "20%"); - assertContains(xsxml, "13.12"); - assertContains(xsxml, "1.23457E+14"); - assertContains(xsxml, "1.23457E+15"); - - assertContains(xsxml, "46/1963");//custom format 1 - assertContains(xsxml, "3/128");//custom format 2 - - assertContains(xsxml, "\n" + - "\tlonger int\n" + - "\t1.23457E+15\n" + - "\tAllison, Timothy B.:\n" + - "test comment2\n" + - ""); - - assertContains(xsxml, "\n" + - "\tcomment6Allison, Timothy B.:\n" + - "comment6 actually in cell\n" + - ""); - - assertContains(xsxml, "\n" + - "\tAllison, Timothy B.:\n" + - "comment7 end of file\n" + - ""); - - assertContains(xsxml, "\n" + - "\tAllison, Timothy B.:\n" + - "comment8 end of file\n" + - ""); - - assertContains(xsxml, - "

    OddLeftHeader OddCenterHeader OddRightHeader
    "); - assertContains(xsxml, - "
    OddLeftFooter OddCenterFooter OddRightFooter
    "); - assertContains(xsxml, - "
    EvenLeftHeader EvenCenterHeader EvenRightHeader\n
    "); - assertContains(xsxml, - "
    EvenLeftFooter EvenCenterFooter EvenRightFooter
    "); - assertContains(xsxml, - "
    FirstPageLeftHeader FirstPageCenterHeader FirstPageRightHeader
    "); - assertContains(xsxml, - "
    FirstPageLeftFooter FirstPageCenterFooter FirstPageRightFooter
    "); - - } - - @Test - public void testComments() throws Exception { - List sheetTexts = getSheets("comments.xlsb"); - String xsxml = sheetTexts.get(0); - assertContains(xsxml, - "\n" + - "\tcomment top row1 (index0)\n" + - "\trow1\n" + - ""); - assertContains(xsxml, - "\n" + - "\tAllison, Timothy B.:\n" + - "comment row2 (index1)\n" + - ""); - assertContains(xsxml, "\n" + - "\trow3comment top row3 (index2)\n" + - "\trow3\n"); - - assertContains(xsxml, "\n" + - "\tcomment top row4 (index3)\n" + - "\trow4\n" + - ""); - - } - - private List getSheets(String testFileName) throws Exception { - OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream(testFileName)); - List sheetTexts = new ArrayList(); - XSSFBReader r = new XSSFBReader(pkg); - -// assertNotNull(r.getWorkbookData()); - // assertNotNull(r.getSharedStringsData()); - assertNotNull(r.getXSSFBStylesTable()); - XSSFBSharedStringsTable sst = new XSSFBSharedStringsTable(pkg); - XSSFBStylesTable xssfbStylesTable = r.getXSSFBStylesTable(); - XSSFBReader.SheetIterator it = (XSSFBReader.SheetIterator) r.getSheetsData(); - - while (it.hasNext()) { - InputStream is = it.next(); - String name = it.getSheetName(); - TestSheetHandler testSheetHandler = new TestSheetHandler(); - testSheetHandler.startSheet(name); - XSSFBSheetHandler sheetHandler = new XSSFBSheetHandler(is, - xssfbStylesTable, - it.getXSSFBSheetComments(), - sst, testSheetHandler, - new DataFormatter(), - false); - sheetHandler.parse(); - testSheetHandler.endSheet(); - sheetTexts.add(testSheetHandler.toString()); - } - return sheetTexts; - - } - - @Test - public void testDate() throws Exception { - List sheets = getSheets("date.xlsb"); - assertEquals(1, sheets.size()); - assertContains(sheets.get(0), "1/12/13"); - } - - - private class TestSheetHandler implements XSSFSheetXMLHandler.SheetContentsHandler { - private final StringBuilder sb = new StringBuilder(); - - public void startSheet(String sheetName) { - sb.append(""); - } - - public void endSheet() { - sb.append(""); - } - - @Override - public void startRow(int rowNum) { - sb.append("\n"); - } - - @Override - public void endRow(int rowNum) { - sb.append("\n"); - } - - @Override - public void cell(String cellReference, String formattedValue, XSSFComment comment) { - formattedValue = (formattedValue == null) ? "" : formattedValue; - if (comment == null) { - sb.append("\n\t").append(formattedValue).append(""); - } else { - sb.append("\n\t") - .append(formattedValue) - .append("") - .append(comment.getString().toString().trim()).append("") - .append(""); - } - } - - @Override - public void headerFooter(String text, boolean isHeader, String tagName) { - if (isHeader) { - sb.append("
    " + text + "
    "); - } else { - sb.append("
    " + text + "
    "); - - } - } - - @Override - public String toString() { - return sb.toString(); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/eventusermodel/TestXSSFReader.java b/src/ooxml/testcases/org/apache/poi/xssf/eventusermodel/TestXSSFReader.java deleted file mode 100644 index 49742dc9d..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/eventusermodel/TestXSSFReader.java +++ /dev/null @@ -1,268 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.eventusermodel; - -import java.io.InputStream; -import java.util.Iterator; -import java.util.List; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.POIXMLException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.util.IOUtils; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.model.CommentsTable; -import org.apache.poi.xssf.model.StylesTable; -import org.apache.poi.xssf.usermodel.XSSFRichTextString; -import org.apache.poi.xssf.usermodel.XSSFShape; -import org.apache.poi.xssf.usermodel.XSSFSimpleShape; - -import junit.framework.TestCase; - -/** - * Tests for {@link XSSFReader} - */ -public final class TestXSSFReader extends TestCase { - private static POIDataSamples _ssTests = POIDataSamples.getSpreadSheetInstance(); - - public void testGetBits() throws Exception { - OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("SampleSS.xlsx")); - - XSSFReader r = new XSSFReader(pkg); - - assertNotNull(r.getWorkbookData()); - assertNotNull(r.getSharedStringsData()); - assertNotNull(r.getStylesData()); - - assertNotNull(r.getSharedStringsTable()); - assertNotNull(r.getStylesTable()); - } - - public void testStyles() throws Exception { - OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("SampleSS.xlsx")); - - XSSFReader r = new XSSFReader(pkg); - - assertEquals(3, r.getStylesTable().getFonts().size()); - assertEquals(0, r.getStylesTable().getNumDataFormats()); - - // The Styles Table should have the themes associated with it too - assertNotNull(r.getStylesTable().getTheme()); - - // Check we get valid data for the two - assertNotNull(r.getStylesData()); - assertNotNull(r.getThemesData()); - } - - public void testStrings() throws Exception { - OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("SampleSS.xlsx")); - - XSSFReader r = new XSSFReader(pkg); - - assertEquals(11, r.getSharedStringsTable().getItems().size()); - assertEquals("Test spreadsheet", new XSSFRichTextString(r.getSharedStringsTable().getEntryAt(0)).toString()); - } - - public void testSheets() throws Exception { - OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("SampleSS.xlsx")); - - XSSFReader r = new XSSFReader(pkg); - byte[] data = new byte[4096]; - - // By r:id - assertNotNull(r.getSheet("rId2")); - int read = IOUtils.readFully(r.getSheet("rId2"), data); - assertEquals(974, read); - - // All - Iterator it = r.getSheetsData(); - - int count = 0; - while(it.hasNext()) { - count++; - InputStream inp = it.next(); - assertNotNull(inp); - read = IOUtils.readFully(inp, data); - inp.close(); - - assertTrue(read > 400); - assertTrue(read < 1500); - } - assertEquals(3, count); - } - - /** - * Check that the sheet iterator returns sheets in the logical order - * (as they are defined in the workbook.xml) - */ - public void testOrderOfSheets() throws Exception { - OPCPackage pkg = OPCPackage.open(_ssTests.openResourceAsStream("reordered_sheets.xlsx")); - - XSSFReader r = new XSSFReader(pkg); - - String[] sheetNames = {"Sheet4", "Sheet2", "Sheet3", "Sheet1"}; - XSSFReader.SheetIterator it = (XSSFReader.SheetIterator)r.getSheetsData(); - - int count = 0; - while(it.hasNext()) { - InputStream inp = it.next(); - assertNotNull(inp); - inp.close(); - - assertEquals(sheetNames[count], it.getSheetName()); - count++; - } - assertEquals(4, count); - } - - public void testComments() throws Exception { - OPCPackage pkg = XSSFTestDataSamples.openSamplePackage("comments.xlsx"); - XSSFReader r = new XSSFReader(pkg); - XSSFReader.SheetIterator it = (XSSFReader.SheetIterator)r.getSheetsData(); - - int count = 0; - while(it.hasNext()) { - count++; - InputStream inp = it.next(); - inp.close(); - - if(count == 1) { - assertNotNull(it.getSheetComments()); - CommentsTable ct = it.getSheetComments(); - assertEquals(1, ct.getNumberOfAuthors()); - assertEquals(3, ct.getNumberOfComments()); - } else { - assertNull(it.getSheetComments()); - } - } - assertEquals(3, count); - } - - /** - * Iterating over a workbook with chart sheets in it, using the - * XSSFReader method - * @throws Exception - */ - public void test50119() throws Exception { - OPCPackage pkg = XSSFTestDataSamples.openSamplePackage("WithChartSheet.xlsx"); - XSSFReader r = new XSSFReader(pkg); - XSSFReader.SheetIterator it = (XSSFReader.SheetIterator)r.getSheetsData(); - - while(it.hasNext()) - { - InputStream stream = it.next(); - stream.close(); - } - } - - /** - * Test text extraction from text box using getShapes() - * - * @throws Exception - */ - public void testShapes() throws Exception { - OPCPackage pkg = XSSFTestDataSamples.openSamplePackage("WithTextBox.xlsx"); - XSSFReader r = new XSSFReader(pkg); - XSSFReader.SheetIterator it = (XSSFReader.SheetIterator) r.getSheetsData(); - - String text = getShapesString(it); - assertTrue(text.contains("Line 1")); - assertTrue(text.contains("Line 2")); - assertTrue(text.contains("Line 3")); - } - - private String getShapesString(XSSFReader.SheetIterator it) { - StringBuilder sb = new StringBuilder(); - while (it.hasNext()) { - it.next(); - List shapes = it.getShapes(); - if (shapes != null) { - for (XSSFShape shape : shapes) { - if (shape instanceof XSSFSimpleShape) { - String t = ((XSSFSimpleShape) shape).getText(); - sb.append(t).append('\n'); - } - } - } - } - return sb.toString(); - } - - public void testBug57914() throws Exception { - OPCPackage pkg = XSSFTestDataSamples.openSamplePackage("57914.xlsx"); - final XSSFReader r; - - // for now expect this to fail, when we fix 57699, this one should fail so we know we should adjust - // this test as well - try { - r = new XSSFReader(pkg); - fail("This will fail until bug 57699 is fixed"); - } catch (POIXMLException e) { - assertTrue("Had " + e, e.getMessage().contains("57699")); - return; - } - - XSSFReader.SheetIterator it = (XSSFReader.SheetIterator) r.getSheetsData(); - - String text = getShapesString(it); - assertTrue(text.contains("Line 1")); - assertTrue(text.contains("Line 2")); - assertTrue(text.contains("Line 3")); - } - - /** - * NPE from XSSFReader$SheetIterator. on XLSX files generated by - * the openpyxl library - */ - public void test58747() throws Exception { - OPCPackage pkg = XSSFTestDataSamples.openSamplePackage("58747.xlsx"); - ReadOnlySharedStringsTable strings = new ReadOnlySharedStringsTable(pkg); - assertNotNull(strings); - XSSFReader reader = new XSSFReader(pkg); - StylesTable styles = reader.getStylesTable(); - assertNotNull(styles); - - XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) reader.getSheetsData(); - assertEquals(true, iter.hasNext()); - iter.next(); - - assertEquals(false, iter.hasNext()); - assertEquals("Orders", iter.getSheetName()); - - pkg.close(); - } - - /** - * NPE when sheet has no relationship id in the workbook - * 60825 - */ - public void testSheetWithNoRelationshipId() throws Exception { - OPCPackage pkg = XSSFTestDataSamples.openSamplePackage("60825.xlsx"); - ReadOnlySharedStringsTable strings = new ReadOnlySharedStringsTable(pkg); - assertNotNull(strings); - XSSFReader reader = new XSSFReader(pkg); - StylesTable styles = reader.getStylesTable(); - assertNotNull(styles); - - XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) reader.getSheetsData(); - assertNotNull(iter.next()); - assertFalse(iter.hasNext()); - - pkg.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFBEventBasedExcelExtractor.java b/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFBEventBasedExcelExtractor.java deleted file mode 100644 index 56d17ee27..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFBEventBasedExcelExtractor.java +++ /dev/null @@ -1,111 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.extractor; - -import static org.apache.poi.POITestCase.assertContains; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.Test; - -/** - * Tests for {@link XSSFBEventBasedExcelExtractor} - */ -public class TestXSSFBEventBasedExcelExtractor { - - - protected XSSFEventBasedExcelExtractor getExtractor(String sampleName) throws Exception { - return new XSSFBEventBasedExcelExtractor(XSSFTestDataSamples. - openSamplePackage(sampleName)); - } - - /** - * Get text out of the simple file - */ - @Test - public void testGetSimpleText() throws Exception { - // a very simple file - XSSFEventBasedExcelExtractor extractor = getExtractor("sample.xlsb"); - extractor.setIncludeCellComments(true); - extractor.getText(); - - String text = extractor.getText(); - assertTrue(text.length() > 0); - - // Check sheet names - assertTrue(text.startsWith("Sheet1")); - assertTrue(text.endsWith("Sheet3\n")); - - // Now without, will have text - extractor.setIncludeSheetNames(false); - text = extractor.getText(); - String CHUNK1 = - "Lorem\t111\n" + - "ipsum\t222\n" + - "dolor\t333\n" + - "sit\t444\n" + - "amet\t555\n" + - "consectetuer\t666\n" + - "adipiscing\t777\n" + - "elit\t888\n" + - "Nunc\t999\n"; - String CHUNK2 = - "The quick brown fox jumps over the lazy dog\n" + - "hello, xssf hello, xssf\n" + - "hello, xssf hello, xssf\n" + - "hello, xssf hello, xssf\n" + - "hello, xssf hello, xssf\n"; - assertEquals( - CHUNK1 + - "at\t4995\n" + - CHUNK2 - , text); - - } - - - /** - * Test text extraction from text box using getShapes() - * - * @throws Exception - */ - @Test - public void testShapes() throws Exception { - XSSFEventBasedExcelExtractor ooxmlExtractor = getExtractor("WithTextBox.xlsb"); - - try { - String text = ooxmlExtractor.getText(); - assertContains(text, "Line 1"); - assertContains(text, "Line 2"); - assertContains(text, "Line 3"); - } finally { - ooxmlExtractor.close(); - } - } - - @Test - public void testBeta() throws Exception { - XSSFEventBasedExcelExtractor extractor = getExtractor("Simple.xlsb"); - extractor.setIncludeCellComments(true); - String text = extractor.getText(); - assertContains(text, - "This is an example spreadsheet created with Microsoft Excel 2007 Beta 2."); - } - -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFEventBasedExcelExtractor.java b/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFEventBasedExcelExtractor.java deleted file mode 100644 index 55a170287..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFEventBasedExcelExtractor.java +++ /dev/null @@ -1,384 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.extractor; - -import static org.apache.poi.POITestCase.assertContains; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.poi.POITextExtractor; -import org.apache.poi.POIXMLTextExtractor; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.extractor.ExcelExtractor; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.Test; - -/** - * Tests for {@link XSSFEventBasedExcelExtractor} - */ -public class TestXSSFEventBasedExcelExtractor { - protected XSSFEventBasedExcelExtractor getExtractor(String sampleName) throws Exception { - return new XSSFEventBasedExcelExtractor(XSSFTestDataSamples. - openSamplePackage(sampleName)); - } - - /** - * Get text out of the simple file - */ - @Test - public void testGetSimpleText() throws Exception { - // a very simple file - XSSFEventBasedExcelExtractor extractor = getExtractor("sample.xlsx"); - extractor.getText(); - - String text = extractor.getText(); - assertTrue(text.length() > 0); - - // Check sheet names - assertTrue(text.startsWith("Sheet1")); - assertTrue(text.endsWith("Sheet3\n")); - - // Now without, will have text - extractor.setIncludeSheetNames(false); - text = extractor.getText(); - String CHUNK1 = - "Lorem\t111\n" + - "ipsum\t222\n" + - "dolor\t333\n" + - "sit\t444\n" + - "amet\t555\n" + - "consectetuer\t666\n" + - "adipiscing\t777\n" + - "elit\t888\n" + - "Nunc\t999\n"; - String CHUNK2 = - "The quick brown fox jumps over the lazy dog\n" + - "hello, xssf hello, xssf\n" + - "hello, xssf hello, xssf\n" + - "hello, xssf hello, xssf\n" + - "hello, xssf hello, xssf\n"; - assertEquals( - CHUNK1 + - "at\t4995\n" + - CHUNK2 - , text); - - // Now get formulas not their values - extractor.setFormulasNotResults(true); - text = extractor.getText(); - assertEquals( - CHUNK1 + - "at\tSUM(B1:B9)\n" + - CHUNK2, text); - - // With sheet names too - extractor.setIncludeSheetNames(true); - text = extractor.getText(); - assertEquals( - "Sheet1\n" + - CHUNK1 + - "at\tSUM(B1:B9)\n" + - "rich test\n" + - CHUNK2 + - "Sheet3\n" - , text); - - extractor.close(); - } - - @Test - public void testGetComplexText() throws Exception { - // A fairly complex file - XSSFEventBasedExcelExtractor extractor = getExtractor("AverageTaxRates.xlsx"); - extractor.getText(); - - String text = extractor.getText(); - assertTrue(text.length() > 0); - - // Might not have all formatting it should do! - assertTrue(text.startsWith( - "Avgtxfull\n" + - "(iii) AVERAGE TAX RATES ON ANNUAL" - )); - - extractor.close(); - } - - @Test - public void testInlineStrings() throws Exception { - XSSFEventBasedExcelExtractor extractor = getExtractor("InlineStrings.xlsx"); - extractor.setFormulasNotResults(true); - String text = extractor.getText(); - - // Numbers - assertContains(text, "43"); - assertContains(text, "22"); - - // Strings - assertContains(text, "ABCDE"); - assertContains(text, "Long Text"); - - // Inline Strings - assertContains(text, "1st Inline String"); - assertContains(text, "And More"); - - // Formulas - assertContains(text, "A2"); - assertContains(text, "A5-A$2"); - - extractor.close(); - } - - /** - * Test that we return pretty much the same as - * ExcelExtractor does, when we're both passed - * the same file, just saved as xls and xlsx - */ - @Test - public void testComparedToOLE2() throws Exception { - // A fairly simple file - ooxml - XSSFEventBasedExcelExtractor ooxmlExtractor = getExtractor("SampleSS.xlsx"); - - ExcelExtractor ole2Extractor = - new ExcelExtractor(HSSFTestDataSamples.openSampleWorkbook("SampleSS.xls")); - - POITextExtractor[] extractors = - new POITextExtractor[] { ooxmlExtractor, ole2Extractor }; - for (POITextExtractor extractor : extractors) { - String text = extractor.getText().replaceAll("[\r\t]", ""); - assertTrue(text.startsWith("First Sheet\nTest spreadsheet\n2nd row2nd row 2nd column\n")); - Pattern pattern = Pattern.compile(".*13(\\.0+)?\\s+Sheet3.*", Pattern.DOTALL); - Matcher m = pattern.matcher(text); - assertTrue(m.matches()); - } - - ole2Extractor.close(); - ooxmlExtractor.close(); - } - - /** - * Test text extraction from text box using getShapes() - * @throws Exception - */ - @Test - public void testShapes() throws Exception{ - XSSFEventBasedExcelExtractor ooxmlExtractor = getExtractor("WithTextBox.xlsx"); - - try { - String text = ooxmlExtractor.getText(); - assertContains(text, "Line 1"); - assertContains(text, "Line 2"); - assertContains(text, "Line 3"); - } finally { - ooxmlExtractor.close(); - } - } - - /** - * Test that we return the same output for unstyled numbers as the - * non-event-based XSSFExcelExtractor. - */ - @Test - public void testUnstyledNumbersComparedToNonEventBasedExtractor() - throws Exception { - - String expectedOutput = "Sheet1\n99.99\n"; - - XSSFExcelExtractor extractor = new XSSFExcelExtractor( - XSSFTestDataSamples.openSampleWorkbook("56011.xlsx")); - try { - assertEquals(expectedOutput, extractor.getText().replace(",", ".")); - } finally { - extractor.close(); - } - - XSSFEventBasedExcelExtractor fixture = - new XSSFEventBasedExcelExtractor( - XSSFTestDataSamples.openSamplePackage("56011.xlsx")); - try { - assertEquals(expectedOutput, fixture.getText().replace(",", ".")); - } finally { - fixture.close(); - } - } - - /** - * Test that we return the same output headers and footers as the - * non-event-based XSSFExcelExtractor. - */ - @Test - public void testHeadersAndFootersComparedToNonEventBasedExtractor() - throws Exception { - - String expectedOutputWithHeadersAndFooters = - "Sheet1\n" + - "&\"Calibri,Regular\"&K000000top left\t&\"Calibri,Regular\"&K000000top center\t&\"Calibri,Regular\"&K000000top right\n" + - "abc\t123\n" + - "&\"Calibri,Regular\"&K000000bottom left\t&\"Calibri,Regular\"&K000000bottom center\t&\"Calibri,Regular\"&K000000bottom right\n"; - - String expectedOutputWithoutHeadersAndFooters = - "Sheet1\n" + - "abc\t123\n"; - - XSSFExcelExtractor extractor = new XSSFExcelExtractor( - XSSFTestDataSamples.openSampleWorkbook("headerFooterTest.xlsx")); - try { - assertEquals(expectedOutputWithHeadersAndFooters, extractor.getText()); - extractor.setIncludeHeadersFooters(false); - assertEquals(expectedOutputWithoutHeadersAndFooters, extractor.getText()); - } finally { - extractor.close(); - } - - XSSFEventBasedExcelExtractor fixture = - new XSSFEventBasedExcelExtractor( - XSSFTestDataSamples.openSamplePackage("headerFooterTest.xlsx")); - try { - assertEquals(expectedOutputWithHeadersAndFooters, fixture.getText()); - fixture.setIncludeHeadersFooters(false); - assertEquals(expectedOutputWithoutHeadersAndFooters, fixture.getText()); - } finally { - fixture.close(); - } - } - - /** - * Test that XSSFEventBasedExcelExtractor outputs comments when specified. - * The output will contain two improvements over the output from - * XSSFExcelExtractor in that (1) comments from empty cells will be - * outputted, and (2) the author will not be outputted twice. - *

    - * This test will need to be modified if these improvements are ported to - * XSSFExcelExtractor. - */ - @Test - public void testCommentsComparedToNonEventBasedExtractor() - throws Exception { - - String expectedOutputWithoutComments = - "Sheet1\n" + - "\n" + - "abc\n" + - "\n" + - "123\n" + - "\n" + - "\n" + - "\n"; - - String nonEventBasedExtractorOutputWithComments = - "Sheet1\n" + - "\n" + - "abc Comment by Shaun Kalley: Shaun Kalley: Comment A2\n" + - "\n" + - "123 Comment by Shaun Kalley: Shaun Kalley: Comment B4\n" + - "\n" + - "\n" + - "\n"; - - String eventBasedExtractorOutputWithComments = - "Sheet1\n" + - "Comment by Shaun Kalley: Comment A1\tComment by Shaun Kalley: Comment B1\n" + - "abc Comment by Shaun Kalley: Comment A2\tComment by Shaun Kalley: Comment B2\n" + - "Comment by Shaun Kalley: Comment A3\tComment by Shaun Kalley: Comment B3\n" + - "Comment by Shaun Kalley: Comment A4\t123 Comment by Shaun Kalley: Comment B4\n" + - "Comment by Shaun Kalley: Comment A5\tComment by Shaun Kalley: Comment B5\n" + - "Comment by Shaun Kalley: Comment A7\tComment by Shaun Kalley: Comment B7\n" + - "Comment by Shaun Kalley: Comment A8\tComment by Shaun Kalley: Comment B8\n"; - - XSSFExcelExtractor extractor = new XSSFExcelExtractor( - XSSFTestDataSamples.openSampleWorkbook("commentTest.xlsx")); - try { - assertEquals(expectedOutputWithoutComments, extractor.getText()); - extractor.setIncludeCellComments(true); - assertEquals(nonEventBasedExtractorOutputWithComments, extractor.getText()); - } finally { - extractor.close(); - } - - XSSFEventBasedExcelExtractor fixture = - new XSSFEventBasedExcelExtractor( - XSSFTestDataSamples.openSamplePackage("commentTest.xlsx")); - try { - assertEquals(expectedOutputWithoutComments, fixture.getText()); - fixture.setIncludeCellComments(true); - assertEquals(eventBasedExtractorOutputWithComments, fixture.getText()); - } finally { - fixture.close(); - } - } - - @Test - public void testFile56278_normal() throws Exception { - // first with normal Text Extractor - POIXMLTextExtractor extractor = new XSSFExcelExtractor( - XSSFTestDataSamples.openSampleWorkbook("56278.xlsx")); - try { - assertNotNull(extractor.getText()); - } finally { - extractor.close(); - } - } - - @Test - public void testFile56278_event() throws Exception { - // then with event based one - POIXMLTextExtractor extractor = getExtractor("56278.xlsx"); - try { - assertNotNull(extractor.getText()); - } finally { - extractor.close(); - } - } - - @Test - public void test59021() throws Exception { - XSSFEventBasedExcelExtractor ex = - new XSSFEventBasedExcelExtractor( - XSSFTestDataSamples.openSamplePackage("59021.xlsx")); - String text = ex.getText(); - assertContains(text, "Abkhazia - Fixed"); - assertContains(text, "10/02/2016"); - ex.close(); - } - - @Test - public void test51519() throws Exception { - //default behavior: include phonetic runs - XSSFEventBasedExcelExtractor ex = - new XSSFEventBasedExcelExtractor( - XSSFTestDataSamples.openSamplePackage("51519.xlsx")); - String text = ex.getText(); - assertContains(text, "\u65E5\u672C\u30AA\u30E9\u30AF\u30EB \u30CB\u30DB\u30F3"); - ex.close(); - - //now try turning them off - ex = - new XSSFEventBasedExcelExtractor( - XSSFTestDataSamples.openSamplePackage("51519.xlsx")); - ex.setConcatenatePhoneticRuns(false); - text = ex.getText(); - assertFalse("should not be able to find appended phonetic run", text.contains("\u65E5\u672C\u30AA\u30E9\u30AF\u30EB \u30CB\u30DB\u30F3")); - ex.close(); - - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFEventBasedExcelExtractorUsingFactory.java b/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFEventBasedExcelExtractorUsingFactory.java deleted file mode 100644 index 09fca4d85..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFEventBasedExcelExtractorUsingFactory.java +++ /dev/null @@ -1,36 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.extractor; - -import org.apache.poi.extractor.ExtractorFactory; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.junit.After; - - -public class TestXSSFEventBasedExcelExtractorUsingFactory extends TestXSSFEventBasedExcelExtractor { - @Override - protected final XSSFEventBasedExcelExtractor getExtractor(String sampleName) throws Exception { - ExtractorFactory.setAllThreadsPreferEventExtractors(true); - return (XSSFEventBasedExcelExtractor) ExtractorFactory.createExtractor(HSSFTestDataSamples.openSampleFileStream(sampleName)); - } - - @After - public void tearDown() { - // reset setting to not affect other tests - ExtractorFactory.setAllThreadsPreferEventExtractors(null); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFExcelExtractor.java b/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFExcelExtractor.java deleted file mode 100644 index d82ac6205..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFExcelExtractor.java +++ /dev/null @@ -1,242 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.extractor; - -import java.io.IOException; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import junit.framework.TestCase; -import org.apache.poi.POITextExtractor; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.extractor.ExcelExtractor; -import org.apache.poi.xssf.XSSFTestDataSamples; - -/** - * Tests for {@link XSSFExcelExtractor} - */ -public class TestXSSFExcelExtractor extends TestCase { - protected XSSFExcelExtractor getExtractor(String sampleName) { - return new XSSFExcelExtractor(XSSFTestDataSamples.openSampleWorkbook(sampleName)); - } - - /** - * Get text out of the simple file - * @throws IOException - */ - public void testGetSimpleText() throws IOException { - // a very simple file - XSSFExcelExtractor extractor = getExtractor("sample.xlsx"); - extractor.getText(); - - String text = extractor.getText(); - assertTrue(text.length() > 0); - - // Check sheet names - assertTrue(text.startsWith("Sheet1")); - assertTrue(text.endsWith("Sheet3\n")); - - // Now without, will have text - extractor.setIncludeSheetNames(false); - text = extractor.getText(); - String CHUNK1 = - "Lorem\t111\n" + - "ipsum\t222\n" + - "dolor\t333\n" + - "sit\t444\n" + - "amet\t555\n" + - "consectetuer\t666\n" + - "adipiscing\t777\n" + - "elit\t888\n" + - "Nunc\t999\n"; - String CHUNK2 = - "The quick brown fox jumps over the lazy dog\n" + - "hello, xssf hello, xssf\n" + - "hello, xssf hello, xssf\n" + - "hello, xssf hello, xssf\n" + - "hello, xssf hello, xssf\n"; - assertEquals( - CHUNK1 + - "at\t4995\n" + - CHUNK2 - , text); - - // Now get formulas not their values - extractor.setFormulasNotResults(true); - text = extractor.getText(); - assertEquals( - CHUNK1 + - "at\tSUM(B1:B9)\n" + - CHUNK2, text); - - // With sheet names too - extractor.setIncludeSheetNames(true); - text = extractor.getText(); - assertEquals( - "Sheet1\n" + - CHUNK1 + - "at\tSUM(B1:B9)\n" + - "rich test\n" + - CHUNK2 + - "Sheet3\n" - , text); - - extractor.close(); - } - - public void testGetComplexText() throws IOException { - // A fairly complex file - XSSFExcelExtractor extractor = getExtractor("AverageTaxRates.xlsx"); - extractor.getText(); - - String text = extractor.getText(); - assertTrue(text.length() > 0); - - // Might not have all formatting it should do! - // TODO decide if we should really have the "null" in there - assertTrue(text.startsWith( - "Avgtxfull\n" + - "null\t(iii) AVERAGE TAX RATES ON ANNUAL" - )); - - extractor.close(); - } - - /** - * Test that we return pretty much the same as - * ExcelExtractor does, when we're both passed - * the same file, just saved as xls and xlsx - * @throws IOException - */ - public void testComparedToOLE2() throws IOException { - // A fairly simple file - ooxml - XSSFExcelExtractor ooxmlExtractor = getExtractor("SampleSS.xlsx"); - - ExcelExtractor ole2Extractor = - new ExcelExtractor(HSSFTestDataSamples.openSampleWorkbook("SampleSS.xls")); - - POITextExtractor[] extractors = - new POITextExtractor[] { ooxmlExtractor, ole2Extractor }; - - for (POITextExtractor extractor : extractors) { - String text = extractor.getText().replaceAll("[\r\t]", ""); - assertTrue(text.startsWith("First Sheet\nTest spreadsheet\n2nd row2nd row 2nd column\n")); - Pattern pattern = Pattern.compile(".*13(\\.0+)?\\s+Sheet3.*", Pattern.DOTALL); - Matcher m = pattern.matcher(text); - assertTrue(m.matches()); - } - - ole2Extractor.close(); - ooxmlExtractor.close(); - } - - /** - * From bug #45540 - * @throws IOException - */ - public void testHeaderFooter() throws IOException { - String[] files = new String[] { - "45540_classic_Header.xlsx", "45540_form_Header.xlsx", - "45540_classic_Footer.xlsx", "45540_form_Footer.xlsx", - }; - for(String sampleName : files) { - XSSFExcelExtractor extractor = getExtractor(sampleName); - String text = extractor.getText(); - - assertTrue("Unable to find expected word in text from " + sampleName + "\n" + text, text.contains("testdoc")); - assertTrue("Unable to find expected word in text\n" + text, text.contains("test phrase")); - - extractor.close(); - } - } - - /** - * From bug #45544 - * @throws IOException - */ - public void testComments() throws IOException { - XSSFExcelExtractor extractor = getExtractor("45544.xlsx"); - String text = extractor.getText(); - - // No comments there yet - assertFalse("Unable to find expected word in text\n" + text, text.contains("testdoc")); - assertFalse("Unable to find expected word in text\n" + text, text.contains("test phrase")); - - // Turn on comment extraction, will then be - extractor.setIncludeCellComments(true); - text = extractor.getText(); - assertTrue("Unable to find expected word in text\n" + text, text.contains("testdoc")); - assertTrue("Unable to find expected word in text\n" + text, text.contains("test phrase")); - - extractor.close(); - } - - public void testInlineStrings() throws IOException { - XSSFExcelExtractor extractor = getExtractor("InlineStrings.xlsx"); - extractor.setFormulasNotResults(true); - String text = extractor.getText(); - - // Numbers - assertTrue("Unable to find expected word in text\n" + text, text.contains("43")); - assertTrue("Unable to find expected word in text\n" + text, text.contains("22")); - - // Strings - assertTrue("Unable to find expected word in text\n" + text, text.contains("ABCDE")); - assertTrue("Unable to find expected word in text\n" + text, text.contains("Long Text")); - - // Inline Strings - assertTrue("Unable to find expected word in text\n" + text, text.contains("1st Inline String")); - assertTrue("Unable to find expected word in text\n" + text, text.contains("And More")); - - // Formulas - assertTrue("Unable to find expected word in text\n" + text, text.contains("A2")); - assertTrue("Unable to find expected word in text\n" + text, text.contains("A5-A$2")); - - extractor.close(); - } - /** - * Simple test for text box text - * @throws IOException - */ - public void testTextBoxes() throws IOException { - XSSFExcelExtractor extractor = getExtractor("WithTextBox.xlsx"); - try { - extractor.setFormulasNotResults(true); - String text = extractor.getText(); - assertTrue(text.indexOf("Line 1") > -1); - assertTrue(text.indexOf("Line 2") > -1); - assertTrue(text.indexOf("Line 3") > -1); - } finally { - extractor.close(); - } - } - - public void testPhoneticRuns() throws Exception { - XSSFExcelExtractor extractor = getExtractor("51519.xlsx"); - try { - String text = extractor.getText(); - assertTrue(text.contains("\u8C4A\u7530")); - //this shows up only as a phonetic run and should not appear - //in the extracted text - assertFalse(text.contains("\u30CB\u30DB\u30F3")); - } finally { - extractor.close(); - } - - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFExcelExtractorUsingFactory.java b/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFExcelExtractorUsingFactory.java deleted file mode 100644 index 57983be00..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFExcelExtractorUsingFactory.java +++ /dev/null @@ -1,43 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.extractor; - -import org.apache.poi.extractor.ExtractorFactory; -import org.apache.poi.hssf.HSSFTestDataSamples; - -/** - * Tests for {@link XSSFExcelExtractor} - */ -public final class TestXSSFExcelExtractorUsingFactory extends TestXSSFExcelExtractor { - @Override - protected final XSSFExcelExtractor getExtractor(String sampleName) { - ExtractorFactory.setAllThreadsPreferEventExtractors(false); - ExtractorFactory.setThreadPrefersEventExtractors(false); - try { - return (XSSFExcelExtractor) ExtractorFactory.createExtractor(HSSFTestDataSamples.openSampleFileStream(sampleName)); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - @Override - public void tearDown() { - // reset setting to not affect other tests - ExtractorFactory.setAllThreadsPreferEventExtractors(null); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFExportToXML.java b/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFExportToXML.java deleted file mode 100644 index 783b7a0b2..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFExportToXML.java +++ /dev/null @@ -1,637 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.extractor; - -import junit.framework.TestCase; -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.util.XMLHelper; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.model.MapInfo; -import org.apache.poi.xssf.usermodel.XSSFMap; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.xml.sax.EntityResolver; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.Collection; -import java.util.Date; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * @author Roberto Manicardi - */ -public final class TestXSSFExportToXML extends TestCase { - - public void testExportToXML() throws Exception { - - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("CustomXMLMappings.xlsx"); - - boolean found = false; - for (POIXMLDocumentPart p : wb.getRelations()) { - - if (!(p instanceof MapInfo)) { - continue; - } - MapInfo mapInfo = (MapInfo) p; - - XSSFMap map = mapInfo.getXSSFMapById(1); - XSSFExportToXml exporter = new XSSFExportToXml(map); - ByteArrayOutputStream os = new ByteArrayOutputStream(); - exporter.exportToXML(os, true); - String xml = os.toString("UTF-8"); - - assertNotNull(xml); - assertFalse(xml.equals("")); - - String docente = xml.split("")[1].split("")[0].trim(); - String nome = xml.split("")[1].split("")[0].trim(); - String tutor = xml.split("")[1].split("")[0].trim(); - String cdl = xml.split("")[1].split("")[0].trim(); - String durata = xml.split("")[1].split("")[0].trim(); - String argomento = xml.split("")[1].split("")[0].trim(); - String progetto = xml.split("")[1].split("")[0].trim(); - String crediti = xml.split("")[1].split("")[0].trim(); - - assertEquals("ro", docente); - assertEquals("ro", nome); - assertEquals("ds", tutor); - assertEquals("gs", cdl); - assertEquals("g", durata); - assertEquals("gvvv", argomento); - assertEquals("aaaa", progetto); - assertEquals("aa", crediti); - - parseXML(xml); - - found = true; - } - assertTrue(found); - } - - public void testExportToXMLInverseOrder() throws Exception { - - XSSFWorkbook wb = XSSFTestDataSamples - .openSampleWorkbook("CustomXmlMappings-inverse-order.xlsx"); - - boolean found = false; - for (POIXMLDocumentPart p : wb.getRelations()) { - - if (!(p instanceof MapInfo)) { - continue; - } - MapInfo mapInfo = (MapInfo) p; - - XSSFMap map = mapInfo.getXSSFMapById(1); - XSSFExportToXml exporter = new XSSFExportToXml(map); - ByteArrayOutputStream os = new ByteArrayOutputStream(); - exporter.exportToXML(os, true); - String xml = os.toString("UTF-8"); - - assertNotNull(xml); - assertFalse(xml.equals("")); - - String docente = xml.split("")[1].split("")[0].trim(); - String nome = xml.split("")[1].split("")[0].trim(); - String tutor = xml.split("")[1].split("")[0].trim(); - String cdl = xml.split("")[1].split("")[0].trim(); - String durata = xml.split("")[1].split("")[0].trim(); - String argomento = xml.split("")[1].split("")[0].trim(); - String progetto = xml.split("")[1].split("")[0].trim(); - String crediti = xml.split("")[1].split("")[0].trim(); - - assertEquals("aa", nome); - assertEquals("aaaa", docente); - assertEquals("gvvv", tutor); - assertEquals("g", cdl); - assertEquals("gs", durata); - assertEquals("ds", argomento); - assertEquals("ro", progetto); - assertEquals("ro", crediti); - - parseXML(xml); - - found = true; - } - assertTrue(found); - } - - public void testXPathOrdering() { - - XSSFWorkbook wb = XSSFTestDataSamples - .openSampleWorkbook("CustomXmlMappings-inverse-order.xlsx"); - - boolean found = false; - for (POIXMLDocumentPart p : wb.getRelations()) { - - if (p instanceof MapInfo) { - MapInfo mapInfo = (MapInfo) p; - - XSSFMap map = mapInfo.getXSSFMapById(1); - XSSFExportToXml exporter = new XSSFExportToXml(map); - - assertEquals(1, exporter.compare("/CORSO/DOCENTE", "/CORSO/NOME")); - assertEquals(-1, exporter.compare("/CORSO/NOME", "/CORSO/DOCENTE")); - } - - found = true; - } - assertTrue(found); - } - - public void testMultiTable() throws Exception { - - XSSFWorkbook wb = XSSFTestDataSamples - .openSampleWorkbook("CustomXMLMappings-complex-type.xlsx"); - - boolean found = false; - for (POIXMLDocumentPart p : wb.getRelations()) { - - if (p instanceof MapInfo) { - MapInfo mapInfo = (MapInfo) p; - - XSSFMap map = mapInfo.getXSSFMapById(2); - - assertNotNull(map); - - XSSFExportToXml exporter = new XSSFExportToXml(map); - ByteArrayOutputStream os = new ByteArrayOutputStream(); - exporter.exportToXML(os, true); - String xml = os.toString("UTF-8"); - - assertNotNull(xml); - - String[] regexConditions = { - "", - "", - "", - "DataBinding", - "Map Append=\"false\" AutoFit=\"false\" ID=\"1\"", - "Map Append=\"false\" AutoFit=\"false\" ID=\"5\"", - }; - - for (String condition : regexConditions) { - Pattern pattern = Pattern.compile(condition); - Matcher matcher = pattern.matcher(xml); - assertTrue(matcher.find()); - } - } - - found = true; - } - assertTrue(found); - } - - public void testExportToXMLSingleAttributeNamespace() throws Exception { - // TODO: Fails, but I don't know if it is ok or not... - -// XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("CustomXMLMapping-singleattributenamespace.xlsx"); -// -// for (XSSFMap map : wb.getCustomXMLMappings()) { -// XSSFExportToXml exporter = new XSSFExportToXml(map); -// -// ByteArrayOutputStream os = new ByteArrayOutputStream(); -// exporter.exportToXML(os, true); -// } - } - - public void test55850ComplexXmlExport() throws Exception { - - XSSFWorkbook wb = XSSFTestDataSamples - .openSampleWorkbook("55850.xlsx"); - - boolean found = false; - for (POIXMLDocumentPart p : wb.getRelations()) { - - if (!(p instanceof MapInfo)) { - continue; - } - MapInfo mapInfo = (MapInfo) p; - - XSSFMap map = mapInfo.getXSSFMapById(2); - - assertNotNull("XSSFMap is null", map); - - XSSFExportToXml exporter = new XSSFExportToXml(map); - ByteArrayOutputStream os = new ByteArrayOutputStream(); - exporter.exportToXML(os, true); - String xmlData = os.toString("UTF-8"); - - assertNotNull(xmlData); - assertFalse(xmlData.equals("")); - - String a = xmlData.split("")[1].split("")[0].trim(); - String b = a.split("")[1].split("")[0].trim(); - String c = b.split("")[1].split("")[0].trim(); - String d = c.split("")[1].split("")[0].trim(); - String e = d.split("")[1].split("")[0].trim(); - - String euro = e.split("")[1].split("")[0].trim(); - String chf = e.split("")[1].split("")[0].trim(); - - assertEquals("15", euro); - assertEquals("19", chf); - - parseXML(xmlData); - - found = true; - } - assertTrue(found); - } - - public void testFormulaCells_Bugzilla_55927() throws Exception { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("55927.xlsx"); - - boolean found = false; - for (POIXMLDocumentPart p : wb.getRelations()) { - - if (!(p instanceof MapInfo)) { - continue; - } - MapInfo mapInfo = (MapInfo) p; - - XSSFMap map = mapInfo.getXSSFMapById(1); - - assertNotNull("XSSFMap is null", map); - - XSSFExportToXml exporter = new XSSFExportToXml(map); - ByteArrayOutputStream os = new ByteArrayOutputStream(); - exporter.exportToXML(os, true); - String xmlData = os.toString("UTF-8"); - - assertNotNull(xmlData); - assertFalse(xmlData.equals("")); - - assertEquals("2012-01-13", xmlData.split("")[1].split("")[0].trim()); - assertEquals("2012-02-16", xmlData.split("")[1].split("")[0].trim()); - - parseXML(xmlData); - - found = true; - } - assertTrue(found); - } - - public void testFormulaCells_Bugzilla_55926() throws Exception { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("55926.xlsx"); - - boolean found = false; - for (POIXMLDocumentPart p : wb.getRelations()) { - - if (!(p instanceof MapInfo)) { - continue; - } - MapInfo mapInfo = (MapInfo) p; - - XSSFMap map = mapInfo.getXSSFMapById(1); - - assertNotNull("XSSFMap is null", map); - - XSSFExportToXml exporter = new XSSFExportToXml(map); - ByteArrayOutputStream os = new ByteArrayOutputStream(); - exporter.exportToXML(os, true); - String xmlData = os.toString("UTF-8"); - - assertNotNull(xmlData); - assertFalse(xmlData.equals("")); - - String a = xmlData.split("")[1].split("")[0].trim(); - String doubleValue = a.split("")[1].split("")[0].trim(); - String stringValue = a.split("")[1].split("")[0].trim(); - - assertEquals("Hello World", stringValue); - assertEquals("5.1", doubleValue); - - parseXML(xmlData); - - found = true; - } - assertTrue(found); - } - - public void testXmlExportIgnoresEmptyCells_Bugzilla_55924() throws Exception { - - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("55924.xlsx"); - - boolean found = false; - for (POIXMLDocumentPart p : wb.getRelations()) { - - if (!(p instanceof MapInfo)) { - continue; - } - MapInfo mapInfo = (MapInfo) p; - - XSSFMap map = mapInfo.getXSSFMapById(1); - - assertNotNull("XSSFMap is null", map); - - XSSFExportToXml exporter = new XSSFExportToXml(map); - ByteArrayOutputStream os = new ByteArrayOutputStream(); - exporter.exportToXML(os, true); - String xmlData = os.toString("UTF-8"); - - assertNotNull(xmlData); - assertFalse(xmlData.equals("")); - - String a = xmlData.split("")[1].split("")[0].trim(); - String euro = a.split("")[1].split("")[0].trim(); - assertEquals("1",euro); - - parseXML(xmlData); - - found = true; - } - assertTrue(found); - } - - public void testXmlExportSchemaWithXSAllTag_Bugzilla_56169() throws Exception { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56169.xlsx"); - - for (XSSFMap map : wb.getCustomXMLMappings()) { - XSSFExportToXml exporter = new XSSFExportToXml(map); - - ByteArrayOutputStream os = new ByteArrayOutputStream(); - exporter.exportToXML(os, true); - String xmlData = os.toString("UTF-8"); - - assertNotNull(xmlData); - assertTrue(!xmlData.equals("")); - - String a = xmlData.split("")[1].split("")[0].trim(); - String a_b = a.split("")[1].split("")[0].trim(); - String a_b_c = a_b.split("")[1].split("")[0].trim(); - String a_b_c_e = a_b_c.split("")[1].split("")[0].trim(); - String a_b_c_e_euro = a_b_c_e.split("")[1].split("")[0].trim(); - String a_b_c_e_chf = a_b_c_e.split("")[1].split("")[0].trim(); - - assertEquals("1", a_b_c_e_euro); - assertEquals("2", a_b_c_e_chf); - - String a_b_d = a_b.split("")[1].split("")[0].trim(); - String a_b_d_e = a_b_d.split("")[1].split("")[0].trim(); - - String a_b_d_e_euro = a_b_d_e.split("")[1].split("")[0].trim(); - String a_b_d_e_chf = a_b_d_e.split("")[1].split("")[0].trim(); - - assertEquals("3", a_b_d_e_euro); - assertEquals("4", a_b_d_e_chf); - } - } - - public void testXmlExportCompare_Bug_55923() throws Exception { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("55923.xlsx"); - - boolean found = false; - for (POIXMLDocumentPart p : wb.getRelations()) { - - if (!(p instanceof MapInfo)) { - continue; - } - MapInfo mapInfo = (MapInfo) p; - - XSSFMap map = mapInfo.getXSSFMapById(4); - - assertNotNull("XSSFMap is null", map); - - XSSFExportToXml exporter = new XSSFExportToXml(map); - assertEquals(0, exporter.compare("", "")); - assertEquals(0, exporter.compare("/", "/")); - assertEquals(0, exporter.compare("//", "//")); - assertEquals(0, exporter.compare("/a/", "/b/")); - - assertEquals(-1, exporter.compare("/ns1:Entry/ns1:A/ns1:B/ns1:C/ns1:E/ns1:EUR", - "/ns1:Entry/ns1:A/ns1:B/ns1:C/ns1:E/ns1:CHF")); - - found = true; - } - assertTrue(found); - } - - public void testXmlExportSchemaOrderingBug_Bugzilla_55923() throws Exception { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("55923.xlsx"); - - boolean found = false; - for (POIXMLDocumentPart p : wb.getRelations()) { - - if (!(p instanceof MapInfo)) { - continue; - } - MapInfo mapInfo = (MapInfo) p; - - XSSFMap map = mapInfo.getXSSFMapById(4); - - assertNotNull("XSSFMap is null", map); - - XSSFExportToXml exporter = new XSSFExportToXml(map); - ByteArrayOutputStream os = new ByteArrayOutputStream(); - exporter.exportToXML(os, true); - String xmlData = os.toString("UTF-8"); - - assertNotNull(xmlData); - assertFalse(xmlData.equals("")); - - String a = xmlData.split("")[1].split("")[0].trim(); - String a_b = a.split("")[1].split("")[0].trim(); - String a_b_c = a_b.split("")[1].split("")[0].trim(); - String a_b_c_e = a_b_c.split("")[1].split("")[0].trim(); - String a_b_c_e_euro = a_b_c_e.split("")[1].split("")[0].trim(); - String a_b_c_e_chf = a_b_c_e.split("")[1].split("")[0].trim(); - - assertEquals("1",a_b_c_e_euro); - assertEquals("2",a_b_c_e_chf); - - String a_b_d = a_b.split("")[1].split("")[0].trim(); - String a_b_d_e = a_b_d.split("")[1].split("")[0].trim(); - - String a_b_d_e_euro = a_b_d_e.split("")[1].split("")[0].trim(); - String a_b_d_e_chf = a_b_d_e.split("")[1].split("")[0].trim(); - - assertEquals("3",a_b_d_e_euro); - assertEquals("4",a_b_d_e_chf); - - found = true; - } - assertTrue(found); - } - - private void parseXML(String xmlData) throws IOException, SAXException, ParserConfigurationException { - DocumentBuilderFactory docBuilderFactory = XMLHelper.getDocumentBuilderFactory(); - docBuilderFactory.setNamespaceAware(true); - docBuilderFactory.setValidating(false); - DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); - docBuilder.setEntityResolver(new DummyEntityResolver()); - - docBuilder.parse(new ByteArrayInputStream(xmlData.getBytes("UTF-8"))); - } - - private static class DummyEntityResolver implements EntityResolver - { - @Override - public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException - { - return null; - } - } - - public void testExportDataTypes() throws Exception { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("55923.xlsx"); - - Sheet sheet = wb.getSheetAt(0); - Row row = sheet.getRow(0); - - Cell cString = row.createCell(0); - cString.setCellValue("somestring"); - cString.setCellType(CellType.STRING); - - Cell cBoolean = row.createCell(1); - cBoolean.setCellValue(true); - cBoolean.setCellType(CellType.BOOLEAN); - - Cell cError = row.createCell(2); - cError.setCellType(CellType.ERROR); - - Cell cFormulaString = row.createCell(3); - cFormulaString.setCellFormula("A1"); - cFormulaString.setCellType(CellType.FORMULA); - - Cell cFormulaNumeric = row.createCell(4); - cFormulaNumeric.setCellFormula("F1"); - cFormulaNumeric.setCellType(CellType.FORMULA); - - Cell cNumeric = row.createCell(5); - cNumeric.setCellValue(1.2); - cNumeric.setCellType(CellType.NUMERIC); - - Cell cDate = row.createCell(6); - cDate.setCellValue(new Date()); - cDate.setCellType(CellType.NUMERIC); - - boolean found = false; - for (POIXMLDocumentPart p : wb.getRelations()) { - - if (!(p instanceof MapInfo)) { - continue; - } - MapInfo mapInfo = (MapInfo) p; - - XSSFMap map = mapInfo.getXSSFMapById(4); - - assertNotNull("XSSFMap is null", map); - - XSSFExportToXml exporter = new XSSFExportToXml(map); - ByteArrayOutputStream os = new ByteArrayOutputStream(); - exporter.exportToXML(os, true); - String xmlData = os.toString("UTF-8"); - - assertNotNull(xmlData); - assertFalse(xmlData.equals("")); - - parseXML(xmlData); - - found = true; - } - assertTrue(found); - } - - public void testValidateFalse() throws Exception { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("55923.xlsx"); - - boolean found = false; - for (POIXMLDocumentPart p : wb.getRelations()) { - - if (!(p instanceof MapInfo)) { - continue; - } - MapInfo mapInfo = (MapInfo) p; - - XSSFMap map = mapInfo.getXSSFMapById(4); - - assertNotNull("XSSFMap is null", map); - - XSSFExportToXml exporter = new XSSFExportToXml(map); - ByteArrayOutputStream os = new ByteArrayOutputStream(); - exporter.exportToXML(os, false); - String xmlData = os.toString("UTF-8"); - - assertNotNull(xmlData); - assertFalse(xmlData.equals("")); - - parseXML(xmlData); - - found = true; - } - assertTrue(found); - } - - public void testRefElementsInXmlSchema_Bugzilla_56730() throws Exception { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56730.xlsx"); - - boolean found = false; - for (POIXMLDocumentPart p : wb.getRelations()) { - - if (!(p instanceof MapInfo)) { - continue; - } - MapInfo mapInfo = (MapInfo) p; - - XSSFMap map = mapInfo.getXSSFMapById(1); - - assertNotNull("XSSFMap is null", map); - - XSSFExportToXml exporter = new XSSFExportToXml(map); - ByteArrayOutputStream os = new ByteArrayOutputStream(); - exporter.exportToXML(os, true); - String xmlData = os.toString("UTF-8"); - - assertNotNull(xmlData); - assertFalse(xmlData.equals("")); - - assertEquals("2014-12-31", xmlData.split("")[1].split("")[0].trim()); - assertEquals("12.5", xmlData.split("")[1].split("")[0].trim()); - - parseXML(xmlData); - - found = true; - } - assertTrue(found); - } - - public void testBug59026() throws Exception { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("59026.xlsx"); - - Collection mappings = wb.getCustomXMLMappings(); - assertTrue(mappings.size() > 0); - for (XSSFMap map : mappings) { - XSSFExportToXml exporter = new XSSFExportToXml(map); - - ByteArrayOutputStream os = new ByteArrayOutputStream(); - exporter.exportToXML(os, false); - assertNotNull(os.toString("UTF-8")); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFImportFromXML.java b/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFImportFromXML.java deleted file mode 100644 index 8a849026c..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/extractor/TestXSSFImportFromXML.java +++ /dev/null @@ -1,250 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.extractor; - -import static org.apache.poi.xssf.usermodel.XSSFRelation.NS_SPREADSHEETML; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.text.DateFormatSymbols; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Locale; - -import javax.xml.xpath.XPathExpressionException; - -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.usermodel.XSSFMap; -import org.apache.poi.xssf.usermodel.XSSFRow; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Test; -import org.xml.sax.SAXException; - -public class TestXSSFImportFromXML { - - @Test - public void testImportFromXML() throws IOException, XPathExpressionException, SAXException{ - - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("CustomXMLMappings.xlsx"); - try { - String name = "name"; - String teacher = "teacher"; - String tutor = "tutor"; - String cdl = "cdl"; - String duration = "duration"; - String topic = "topic"; - String project = "project"; - String credits = "credits"; - - String testXML = ""+ - ""+name+""+ - ""+teacher+""+ - ""+tutor+""+ - ""+cdl+""+ - ""+duration+""+ - ""+topic+""+ - ""+project+""+ - ""+credits+""+ - "\u0000"; - - XSSFMap map = wb.getMapInfo().getXSSFMapByName("CORSO_mapping"); - assertNotNull(map); - XSSFImportFromXML importer = new XSSFImportFromXML(map); - - importer.importFromXML(testXML); - - XSSFSheet sheet=wb.getSheetAt(0); - - XSSFRow row = sheet.getRow(0); - assertTrue(row.getCell(0).getStringCellValue().equals(name)); - assertTrue(row.getCell(1).getStringCellValue().equals(teacher)); - assertTrue(row.getCell(2).getStringCellValue().equals(tutor)); - assertTrue(row.getCell(3).getStringCellValue().equals(cdl)); - assertTrue(row.getCell(4).getStringCellValue().equals(duration)); - assertTrue(row.getCell(5).getStringCellValue().equals(topic)); - assertTrue(row.getCell(6).getStringCellValue().equals(project)); - assertTrue(row.getCell(7).getStringCellValue().equals(credits)); - } finally { - wb.close(); - } - } - - @Test(timeout=60000) - public void testMultiTable() throws IOException, XPathExpressionException, SAXException{ - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("CustomXMLMappings-complex-type.xlsx"); - try { - String cellC6 = "c6"; - String cellC7 = "c7"; - String cellC8 = "c8"; - String cellC9 = "c9"; - - String testXML = "" + - ""+ - ""+ - ""+ - ""; - - for(int i = 10; i< 10010; i++){ - testXML += ""; - } - - testXML += ""+ - ""+ - ""+ - ""+ - ""+ - ""+ - ""+ - ""+ - ""+ - "\u0000"; - - XSSFMap map = wb.getMapInfo().getXSSFMapByName("MapInfo_mapping"); - assertNotNull(map); - XSSFImportFromXML importer = new XSSFImportFromXML(map); - - importer.importFromXML(testXML); - - //Check for Schema element - XSSFSheet sheet=wb.getSheetAt(1); - - assertEquals(cellC6,sheet.getRow(5).getCell(2).getStringCellValue()); - assertEquals(cellC7,sheet.getRow(6).getCell(2).getStringCellValue()); - assertEquals(cellC8,sheet.getRow(7).getCell(2).getStringCellValue()); - assertEquals(cellC9,sheet.getRow(8).getCell(2).getStringCellValue()); - assertEquals("c5001",sheet.getRow(5000).getCell(2).getStringCellValue()); - } finally { - wb.close(); - } - } - - - @Test - public void testSingleAttributeCellWithNamespace() throws IOException, XPathExpressionException, SAXException{ - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("CustomXMLMapping-singleattributenamespace.xlsx"); - try { - int id = 1; - String displayName = "dispName"; - String ref="19"; - int count = 21; - - String testXML = ""+ - ""+ - ""+ - "\u0000"; - XSSFMap map = wb.getMapInfo().getXSSFMapByName("table_mapping"); - assertNotNull(map); - XSSFImportFromXML importer = new XSSFImportFromXML(map); - importer.importFromXML(testXML); - - //Check for Schema element - XSSFSheet sheet=wb.getSheetAt(0); - - assertEquals(new Double(id), sheet.getRow(28).getCell(1).getNumericCellValue(), 0); - assertEquals(displayName, sheet.getRow(11).getCell(5).getStringCellValue()); - assertEquals(ref, sheet.getRow(14).getCell(7).getStringCellValue()); - assertEquals(new Double(count), sheet.getRow(18).getCell(3).getNumericCellValue(), 0); - } finally { - wb.close(); - } - } - - @Test - public void testOptionalFields_Bugzilla_55864() throws IOException, XPathExpressionException, SAXException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("55864.xlsx"); - try { - String testXML = "" + - "" + - "" + - "Albert" + - "Einstein" + - "1879-03-14" + - "" + - ""; - - XSSFMap map = wb.getMapInfo().getXSSFMapByName("PersonInfoRoot_Map"); - assertNotNull(map); - XSSFImportFromXML importer = new XSSFImportFromXML(map); - - importer.importFromXML(testXML); - - XSSFSheet sheet=wb.getSheetAt(0); - - XSSFRow rowHeadings = sheet.getRow(0); - XSSFRow rowData = sheet.getRow(1); - - assertEquals("FirstName", rowHeadings.getCell(0).getStringCellValue()); - assertEquals("Albert", rowData.getCell(0).getStringCellValue()); - - assertEquals("LastName", rowHeadings.getCell(1).getStringCellValue()); - assertEquals("Einstein", rowData.getCell(1).getStringCellValue()); - - assertEquals("BirthDate", rowHeadings.getCell(2).getStringCellValue()); - assertEquals("1879-03-14", rowData.getCell(2).getStringCellValue()); - - // Value for OptionalRating is declared optional (minOccurs=0) in 55864.xlsx - assertEquals("OptionalRating", rowHeadings.getCell(3).getStringCellValue()); - assertNull("", rowData.getCell(3)); - } finally { - wb.close(); - } - } - - @Test - public void testOptionalFields_Bugzilla_57890() throws IOException, ParseException, XPathExpressionException, SAXException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("57890.xlsx"); - - String testXML = "" + "" - + "" + "" + Integer.MIN_VALUE + "" + "12345" - + "1.0000123" + "1991-03-14" + "" + ""; - - XSSFMap map = wb.getMapInfo().getXSSFMapByName("TestInfoRoot_Map"); - assertNotNull(map); - XSSFImportFromXML importer = new XSSFImportFromXML(map); - - importer.importFromXML(testXML); - - XSSFSheet sheet = wb.getSheetAt(0); - - XSSFRow rowHeadings = sheet.getRow(0); - XSSFRow rowData = sheet.getRow(1); - - assertEquals("Date", rowHeadings.getCell(0).getStringCellValue()); - Date date = new SimpleDateFormat("yyyy-MM-dd", DateFormatSymbols.getInstance(Locale.ROOT)).parse("1991-3-14"); - assertEquals(date, rowData.getCell(0).getDateCellValue()); - - assertEquals("Amount Int", rowHeadings.getCell(1).getStringCellValue()); - assertEquals(new Double(Integer.MIN_VALUE), rowData.getCell(1).getNumericCellValue(), 0); - - assertEquals("Amount Double", rowHeadings.getCell(2).getStringCellValue()); - assertEquals(1.0000123, rowData.getCell(2).getNumericCellValue(), 0); - - assertEquals("Amount UnsignedInt", rowHeadings.getCell(3).getStringCellValue()); - assertEquals(new Double(12345), rowData.getCell(3).getNumericCellValue(), 0); - - wb.close(); - } - - - -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/io/TestLoadSaveXSSF.java b/src/ooxml/testcases/org/apache/poi/xssf/io/TestLoadSaveXSSF.java deleted file mode 100644 index 366d853f7..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/io/TestLoadSaveXSSF.java +++ /dev/null @@ -1,65 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.io; - -import java.util.List; - -import junit.framework.TestCase; - -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.apache.poi.xssf.usermodel.XSSFPictureData; -import org.apache.poi.POIDataSamples; - - -public class TestLoadSaveXSSF extends TestCase { - private static final POIDataSamples _ssSampels = POIDataSamples.getSpreadSheetInstance(); - - public void testLoadSample() throws Exception { - XSSFWorkbook workbook = new XSSFWorkbook(_ssSampels.openResourceAsStream("sample.xlsx")); - assertEquals(3, workbook.getNumberOfSheets()); - assertEquals("Sheet1", workbook.getSheetName(0)); - Sheet sheet = workbook.getSheetAt(0); - Row row = sheet.getRow(0); - Cell cell = row.getCell((short) 1); - assertNotNull(cell); - assertEquals(111.0, cell.getNumericCellValue(), 0.0); - cell = row.getCell((short) 0); - assertEquals("Lorem", cell.getRichStringCellValue().getString()); - } - - // TODO filename string hard coded in XSSFWorkbook constructor in order to make ant test-ooxml target be successful. - public void testLoadStyles() throws Exception { - XSSFWorkbook workbook = new XSSFWorkbook(_ssSampels.openResourceAsStream("styles.xlsx")); - Sheet sheet = workbook.getSheetAt(0); - Row row = sheet.getRow(0); - Cell cell = row.getCell((short) 0); - CellStyle style = cell.getCellStyle(); - // assertNotNull(style); - } - - // TODO filename string hard coded in XSSFWorkbook constructor in order to make ant test-ooxml target be successful. - public void testLoadPictures() throws Exception { - XSSFWorkbook workbook = new XSSFWorkbook(_ssSampels.openResourceAsStream("picture.xlsx")); - List pictures = workbook.getAllPictures(); - assertEquals(1, pictures.size()); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/model/TestCalculationChain.java b/src/ooxml/testcases/org/apache/poi/xssf/model/TestCalculationChain.java deleted file mode 100644 index d2fd60f3e..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/model/TestCalculationChain.java +++ /dev/null @@ -1,62 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.model; - -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.usermodel.XSSFCell; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCalcCell; - -import junit.framework.TestCase; - - -public final class TestCalculationChain extends TestCase { - - public void test46535() { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("46535.xlsx"); - - CalculationChain chain = wb.getCalculationChain(); - //the bean holding the reference to the formula to be deleted - CTCalcCell c = chain.getCTCalcChain().getCArray(0); - int cnt = chain.getCTCalcChain().sizeOfCArray(); - assertEquals(10, c.getI()); - assertEquals("E1", c.getR()); - - XSSFSheet sheet = wb.getSheet("Test"); - XSSFCell cell = sheet.getRow(0).getCell(4); - - assertEquals(CellType.FORMULA, cell.getCellTypeEnum()); - cell.setCellFormula(null); - - //the count of items is less by one - c = chain.getCTCalcChain().getCArray(0); - int cnt2 = chain.getCTCalcChain().sizeOfCArray(); - assertEquals(cnt - 1, cnt2); - //the first item in the calculation chain is the former second one - assertEquals(10, c.getI()); - assertEquals("C1", c.getR()); - - assertEquals(CellType.STRING, cell.getCellTypeEnum()); - cell.setCellValue("ABC"); - assertEquals(CellType.STRING, cell.getCellTypeEnum()); - } - - -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/model/TestCommentsTable.java b/src/ooxml/testcases/org/apache/poi/xssf/model/TestCommentsTable.java deleted file mode 100644 index 4ebd5387d..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/model/TestCommentsTable.java +++ /dev/null @@ -1,321 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.model; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; - -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.ClientAnchor; -import org.apache.poi.ss.usermodel.Comment; -import org.apache.poi.ss.usermodel.CreationHelper; -import org.apache.poi.ss.usermodel.Drawing; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.CellAddress; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.usermodel.XSSFClientAnchor; -import org.apache.poi.xssf.usermodel.XSSFRichTextString; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Test; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTComment; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCommentList; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTComments; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRst; - - -public class TestCommentsTable { - - private static final String TEST_A2_TEXT = "test A2 text"; - private static final String TEST_A1_TEXT = "test A1 text"; - private static final String TEST_AUTHOR = "test author"; - - @Test - public void findAuthor() throws Exception { - CommentsTable sheetComments = new CommentsTable(); - assertEquals(1, sheetComments.getNumberOfAuthors()); - assertEquals(0, sheetComments.findAuthor("")); - assertEquals("", sheetComments.getAuthor(0)); - - assertEquals(1, sheetComments.findAuthor(TEST_AUTHOR)); - assertEquals(2, sheetComments.findAuthor("another author")); - assertEquals(1, sheetComments.findAuthor(TEST_AUTHOR)); - assertEquals(3, sheetComments.findAuthor("YAA")); - assertEquals(2, sheetComments.findAuthor("another author")); - } - - @Test - public void getCellComment() throws Exception { - CommentsTable sheetComments = new CommentsTable(); - - CTComments comments = sheetComments.getCTComments(); - CTCommentList commentList = comments.getCommentList(); - - // Create 2 comments for A1 and A" cells - CTComment comment0 = commentList.insertNewComment(0); - comment0.setRef("A1"); - CTRst ctrst0 = CTRst.Factory.newInstance(); - ctrst0.setT(TEST_A1_TEXT); - comment0.setText(ctrst0); - CTComment comment1 = commentList.insertNewComment(0); - comment1.setRef("A2"); - CTRst ctrst1 = CTRst.Factory.newInstance(); - ctrst1.setT(TEST_A2_TEXT); - comment1.setText(ctrst1); - - // test finding the right comment for a cell - assertSame(comment0, sheetComments.getCTComment(new CellAddress("A1"))); - assertSame(comment1, sheetComments.getCTComment(new CellAddress("A2"))); - assertNull(sheetComments.getCTComment(new CellAddress("A3"))); - } - - - @Test - public void existing() { - Workbook workbook = XSSFTestDataSamples.openSampleWorkbook("WithVariousData.xlsx"); - Sheet sheet1 = workbook.getSheetAt(0); - Sheet sheet2 = workbook.getSheetAt(1); - - assertTrue( ((XSSFSheet)sheet1).hasComments() ); - assertFalse( ((XSSFSheet)sheet2).hasComments() ); - - // Comments should be in C5 and C7 - Row r5 = sheet1.getRow(4); - Row r7 = sheet1.getRow(6); - assertNotNull( r5.getCell(2).getCellComment() ); - assertNotNull( r7.getCell(2).getCellComment() ); - - // Check they have what we expect - // TODO: Rich text formatting - Comment cc5 = r5.getCell(2).getCellComment(); - Comment cc7 = r7.getCell(2).getCellComment(); - - assertEquals("Nick Burch", cc5.getAuthor()); - assertEquals("Nick Burch:\nThis is a comment", cc5.getString().getString()); - assertEquals(4, cc5.getRow()); - assertEquals(2, cc5.getColumn()); - - assertEquals("Nick Burch", cc7.getAuthor()); - assertEquals("Nick Burch:\nComment #1\n", cc7.getString().getString()); - assertEquals(6, cc7.getRow()); - assertEquals(2, cc7.getColumn()); - } - - @Test - public void writeRead() { - XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("WithVariousData.xlsx"); - XSSFSheet sheet1 = workbook.getSheetAt(0); - XSSFSheet sheet2 = workbook.getSheetAt(1); - - assertTrue( sheet1.hasComments() ); - assertFalse( sheet2.hasComments() ); - - // Change on comment on sheet 1, and add another into - // sheet 2 - Row r5 = sheet1.getRow(4); - Comment cc5 = r5.getCell(2).getCellComment(); - cc5.setAuthor("Apache POI"); - cc5.setString(new XSSFRichTextString("Hello!")); - - Row r2s2 = sheet2.createRow(2); - Cell c1r2s2 = r2s2.createCell(1); - assertNull(c1r2s2.getCellComment()); - - Drawing dg = sheet2.createDrawingPatriarch(); - Comment cc2 = dg.createCellComment(new XSSFClientAnchor()); - cc2.setAuthor("Also POI"); - cc2.setString(new XSSFRichTextString("A new comment")); - c1r2s2.setCellComment(cc2); - - - // Save, and re-load the file - workbook = XSSFTestDataSamples.writeOutAndReadBack(workbook); - - // Check we still have comments where we should do - sheet1 = workbook.getSheetAt(0); - sheet2 = workbook.getSheetAt(1); - assertNotNull(sheet1.getRow(4).getCell(2).getCellComment()); - assertNotNull(sheet1.getRow(6).getCell(2).getCellComment()); - assertNotNull(sheet2.getRow(2).getCell(1).getCellComment()); - - // And check they still have the contents they should do - assertEquals("Apache POI", - sheet1.getRow(4).getCell(2).getCellComment().getAuthor()); - assertEquals("Nick Burch", - sheet1.getRow(6).getCell(2).getCellComment().getAuthor()); - assertEquals("Also POI", - sheet2.getRow(2).getCell(1).getCellComment().getAuthor()); - - assertEquals("Hello!", - sheet1.getRow(4).getCell(2).getCellComment().getString().getString()); - } - - @Test - public void readWriteMultipleAuthors() { - XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("WithMoreVariousData.xlsx"); - XSSFSheet sheet1 = workbook.getSheetAt(0); - XSSFSheet sheet2 = workbook.getSheetAt(1); - - assertTrue( sheet1.hasComments() ); - assertFalse( sheet2.hasComments() ); - - assertEquals("Nick Burch", - sheet1.getRow(4).getCell(2).getCellComment().getAuthor()); - assertEquals("Nick Burch", - sheet1.getRow(6).getCell(2).getCellComment().getAuthor()); - assertEquals("Torchbox", - sheet1.getRow(12).getCell(2).getCellComment().getAuthor()); - - // Save, and re-load the file - workbook = XSSFTestDataSamples.writeOutAndReadBack(workbook); - - // Check we still have comments where we should do - sheet1 = workbook.getSheetAt(0); - assertNotNull(sheet1.getRow(4).getCell(2).getCellComment()); - assertNotNull(sheet1.getRow(6).getCell(2).getCellComment()); - assertNotNull(sheet1.getRow(12).getCell(2).getCellComment()); - - // And check they still have the contents they should do - assertEquals("Nick Burch", - sheet1.getRow(4).getCell(2).getCellComment().getAuthor()); - assertEquals("Nick Burch", - sheet1.getRow(6).getCell(2).getCellComment().getAuthor()); - assertEquals("Torchbox", - sheet1.getRow(12).getCell(2).getCellComment().getAuthor()); - - // Todo - check text too, once bug fixed - } - - @Test - public void removeComment() throws Exception { - final CellAddress addrA1 = new CellAddress("A1"); - final CellAddress addrA2 = new CellAddress("A2"); - final CellAddress addrA3 = new CellAddress("A3"); - - CommentsTable sheetComments = new CommentsTable(); - CTComment a1 = sheetComments.newComment(addrA1); - CTComment a2 = sheetComments.newComment(addrA2); - CTComment a3 = sheetComments.newComment(addrA3); - - assertSame(a1, sheetComments.getCTComment(addrA1)); - assertSame(a2, sheetComments.getCTComment(addrA2)); - assertSame(a3, sheetComments.getCTComment(addrA3)); - assertEquals(3, sheetComments.getNumberOfComments()); - - assertTrue(sheetComments.removeComment(addrA1)); - assertEquals(2, sheetComments.getNumberOfComments()); - assertNull(sheetComments.getCTComment(addrA1)); - assertSame(a2, sheetComments.getCTComment(addrA2)); - assertSame(a3, sheetComments.getCTComment(addrA3)); - - assertTrue(sheetComments.removeComment(addrA2)); - assertEquals(1, sheetComments.getNumberOfComments()); - assertNull(sheetComments.getCTComment(addrA1)); - assertNull(sheetComments.getCTComment(addrA2)); - assertSame(a3, sheetComments.getCTComment(addrA3)); - - assertTrue(sheetComments.removeComment(addrA3)); - assertEquals(0, sheetComments.getNumberOfComments()); - assertNull(sheetComments.getCTComment(addrA1)); - assertNull(sheetComments.getCTComment(addrA2)); - assertNull(sheetComments.getCTComment(addrA3)); - } - - @Test - public void bug54920() throws IOException { - final Workbook workbook = new XSSFWorkbook(); - final Sheet sheet = workbook.createSheet("sheet01"); - // create anchor - CreationHelper helper = sheet.getWorkbook().getCreationHelper(); - ClientAnchor anchor = helper.createClientAnchor(); - - // place comment in A1 - // NOTE - only occurs if a comment is placed in A1 first - Cell A1 = getCell(sheet, 0, 0); - //Cell A1 = getCell(sheet, 2, 2); - Drawing drawing = sheet.createDrawingPatriarch(); - setComment(sheet, A1, drawing, "for A1", helper, anchor); - - // find comment in A1 before we set the comment in B2 - Comment commentA1 = A1.getCellComment(); - assertNotNull("Should still find the previous comment in A1, but had null", commentA1); - assertEquals("should find correct comment in A1, but had null: " + commentA1, "for A1", commentA1.getString().getString()); - - // place comment in B2, according to Bug 54920 this removes the comment in A1! - Cell B2 = getCell(sheet, 1, 1); - setComment(sheet, B2, drawing, "for B2", helper, anchor); - - // find comment in A1 - Comment commentB2 = B2.getCellComment(); - assertEquals("should find correct comment in B2, but had null: " + commentB2, "for B2", commentB2.getString().getString()); - - // find comment in A1 - commentA1 = A1.getCellComment(); - assertNotNull("Should still find the previous comment in A1, but had null", commentA1); - assertEquals("should find correct comment in A1, but had null: " + commentA1, "for A1", commentA1.getString().getString()); - - workbook.close(); - } - - // Set the comment on a sheet - // - private static void setComment(Sheet sheet, Cell cell, Drawing drawing, String commentText, CreationHelper helper, ClientAnchor anchor) { - System.out.println("Setting col: " + cell.getColumnIndex() + " and row " + cell.getRowIndex()); - anchor.setCol1(cell.getColumnIndex()); - anchor.setCol2(cell.getColumnIndex()); - anchor.setRow1(cell.getRowIndex()); - anchor.setRow2(cell.getRowIndex()); - - // get comment, or create if it does not exist - // NOTE - only occurs if getCellComment is called first - Comment comment = cell.getCellComment(); - //Comment comment = null; - if (comment == null) { - comment = drawing.createCellComment(anchor); - } - comment.setAuthor("Test"); - - // attach the comment to the cell - comment.setString(helper.createRichTextString(commentText)); - cell.setCellComment(comment); - } - - // Get a cell, create as needed - // - private static Cell getCell(Sheet sheet, int rowIndex, int colIndex) { - Row row = sheet.getRow(rowIndex); - if (row == null) { - row = sheet.createRow(rowIndex); - } - - Cell cell = row.getCell(colIndex); - if (cell == null) { - cell = row.createCell(colIndex); - } - - return cell; - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/model/TestExternalLinksTable.java b/src/ooxml/testcases/org/apache/poi/xssf/model/TestExternalLinksTable.java deleted file mode 100644 index 1fbf86a33..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/model/TestExternalLinksTable.java +++ /dev/null @@ -1,144 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.model; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import org.apache.poi.ss.usermodel.Name; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Test; - -public final class TestExternalLinksTable { - @Test - public void none() { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("SampleSS.xlsx"); - assertNotNull(wb.getExternalLinksTable()); - assertEquals(0, wb.getExternalLinksTable().size()); - } - - @Test - public void basicRead() { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("ref-56737.xlsx"); - assertNotNull(wb.getExternalLinksTable()); - Name name = null; - - assertEquals(1, wb.getExternalLinksTable().size()); - - ExternalLinksTable links = wb.getExternalLinksTable().get(0); - assertEquals(3, links.getSheetNames().size()); - assertEquals(2, links.getDefinedNames().size()); - - assertEquals("Uses", links.getSheetNames().get(0)); - assertEquals("Defines", links.getSheetNames().get(1)); - assertEquals("56737", links.getSheetNames().get(2)); - - name = links.getDefinedNames().get(0); - assertEquals("NR_Global_B2", name.getNameName()); - assertEquals(-1, name.getSheetIndex()); - assertEquals(null, name.getSheetName()); - assertEquals("'Defines'!$B$2", name.getRefersToFormula()); - - name = links.getDefinedNames().get(1); - assertEquals("NR_To_A1", name.getNameName()); - assertEquals(1, name.getSheetIndex()); - assertEquals("Defines", name.getSheetName()); - assertEquals("'Defines'!$A$1", name.getRefersToFormula()); - - assertEquals("56737.xlsx", links.getLinkedFileName()); - } - - @Test - public void basicReadWriteRead() { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("ref-56737.xlsx"); - Name name = wb.getExternalLinksTable().get(0).getDefinedNames().get(1); - name.setNameName("Testing"); - name.setRefersToFormula("$A$1"); - - wb = XSSFTestDataSamples.writeOutAndReadBack(wb); - assertEquals(1, wb.getExternalLinksTable().size()); - ExternalLinksTable links = wb.getExternalLinksTable().get(0); - - name = links.getDefinedNames().get(0); - assertEquals("NR_Global_B2", name.getNameName()); - assertEquals(-1, name.getSheetIndex()); - assertEquals(null, name.getSheetName()); - assertEquals("'Defines'!$B$2", name.getRefersToFormula()); - - name = links.getDefinedNames().get(1); - assertEquals("Testing", name.getNameName()); - assertEquals(1, name.getSheetIndex()); - assertEquals("Defines", name.getSheetName()); - assertEquals("$A$1", name.getRefersToFormula()); - } - - @Test - public void readWithReferencesToTwoExternalBooks() { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("ref2-56737.xlsx"); - - assertNotNull(wb.getExternalLinksTable()); - Name name = null; - - assertEquals(2, wb.getExternalLinksTable().size()); - - // Check the first one, links to 56737.xlsx - ExternalLinksTable links = wb.getExternalLinksTable().get(0); - assertEquals("56737.xlsx", links.getLinkedFileName()); - assertEquals(3, links.getSheetNames().size()); - assertEquals(2, links.getDefinedNames().size()); - - assertEquals("Uses", links.getSheetNames().get(0)); - assertEquals("Defines", links.getSheetNames().get(1)); - assertEquals("56737", links.getSheetNames().get(2)); - - name = links.getDefinedNames().get(0); - assertEquals("NR_Global_B2", name.getNameName()); - assertEquals(-1, name.getSheetIndex()); - assertEquals(null, name.getSheetName()); - assertEquals("'Defines'!$B$2", name.getRefersToFormula()); - - name = links.getDefinedNames().get(1); - assertEquals("NR_To_A1", name.getNameName()); - assertEquals(1, name.getSheetIndex()); - assertEquals("Defines", name.getSheetName()); - assertEquals("'Defines'!$A$1", name.getRefersToFormula()); - - - // Check the second one, links to 56737.xls, slightly differently - links = wb.getExternalLinksTable().get(1); - assertEquals("56737.xls", links.getLinkedFileName()); - assertEquals(2, links.getSheetNames().size()); - assertEquals(2, links.getDefinedNames().size()); - - assertEquals("Uses", links.getSheetNames().get(0)); - assertEquals("Defines", links.getSheetNames().get(1)); - - name = links.getDefinedNames().get(0); - assertEquals("NR_Global_B2", name.getNameName()); - assertEquals(-1, name.getSheetIndex()); - assertEquals(null, name.getSheetName()); - assertEquals("'Defines'!$B$2", name.getRefersToFormula()); - - name = links.getDefinedNames().get(1); - assertEquals("NR_To_A1", name.getNameName()); - assertEquals(1, name.getSheetIndex()); - assertEquals("Defines", name.getSheetName()); - assertEquals("'Defines'!$A$1", name.getRefersToFormula()); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/model/TestMapInfo.java b/src/ooxml/testcases/org/apache/poi/xssf/model/TestMapInfo.java deleted file mode 100644 index 33e91e8d3..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/model/TestMapInfo.java +++ /dev/null @@ -1,74 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.model; - -import junit.framework.TestCase; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.usermodel.XSSFMap; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTMapInfo; -import org.w3c.dom.Node; - -/** - * @author Roberto Manicardi - */ -public final class TestMapInfo extends TestCase { - - - public void testMapInfoExists() { - - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("CustomXMLMappings.xlsx"); - - MapInfo mapInfo = null; - SingleXmlCells singleXMLCells = null; - - for (POIXMLDocumentPart p : wb.getRelations()) { - - - if (p instanceof MapInfo) { - mapInfo = (MapInfo) p; - - - CTMapInfo ctMapInfo = mapInfo.getCTMapInfo(); - - assertNotNull(ctMapInfo); - - assertEquals(1, ctMapInfo.sizeOfSchemaArray()); - - for (XSSFMap map : mapInfo.getAllXSSFMaps()) { - Node xmlSchema = map.getSchema(); - assertNotNull(xmlSchema); - } - } - } - - XSSFSheet sheet1 = wb.getSheetAt(0); - - for (POIXMLDocumentPart p : sheet1.getRelations()) { - - if (p instanceof SingleXmlCells) { - singleXMLCells = (SingleXmlCells) p; - } - - } - assertNotNull(mapInfo); - assertNotNull(singleXMLCells); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/model/TestSharedStringsTable.java b/src/ooxml/testcases/org/apache/poi/xssf/model/TestSharedStringsTable.java deleted file mode 100644 index ef87a9fd0..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/model/TestSharedStringsTable.java +++ /dev/null @@ -1,189 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.model; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.usermodel.XSSFRichTextString; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRElt; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRPrElt; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRst; - -import junit.framework.TestCase; - -/** - * Test {@link SharedStringsTable}, the cache of strings in a workbook - * - * @author Yegor Kozlov - */ -public final class TestSharedStringsTable extends TestCase { - - public void testCreateNew() { - SharedStringsTable sst = new SharedStringsTable(); - - CTRst st; - int idx; - - // Check defaults - assertNotNull(sst.getItems()); - assertEquals(0, sst.getItems().size()); - assertEquals(0, sst.getCount()); - assertEquals(0, sst.getUniqueCount()); - - st = CTRst.Factory.newInstance(); - st.setT("Hello, World!"); - - idx = sst.addEntry(st); - assertEquals(0, idx); - assertEquals(1, sst.getCount()); - assertEquals(1, sst.getUniqueCount()); - - //add the same entry again - idx = sst.addEntry(st); - assertEquals(0, idx); - assertEquals(2, sst.getCount()); - assertEquals(1, sst.getUniqueCount()); - - //and again - idx = sst.addEntry(st); - assertEquals(0, idx); - assertEquals(3, sst.getCount()); - assertEquals(1, sst.getUniqueCount()); - - st = CTRst.Factory.newInstance(); - st.setT("Second string"); - - idx = sst.addEntry(st); - assertEquals(1, idx); - assertEquals(4, sst.getCount()); - assertEquals(2, sst.getUniqueCount()); - - //add the same entry again - idx = sst.addEntry(st); - assertEquals(1, idx); - assertEquals(5, sst.getCount()); - assertEquals(2, sst.getUniqueCount()); - - st = CTRst.Factory.newInstance(); - CTRElt r = st.addNewR(); - CTRPrElt pr = r.addNewRPr(); - pr.addNewColor().setRgb(new byte[]{(byte)0xFF, 0, 0}); //red - pr.addNewI().setVal(true); //bold - pr.addNewB().setVal(true); //italic - r.setT("Second string"); - - idx = sst.addEntry(st); - assertEquals(2, idx); - assertEquals(6, sst.getCount()); - assertEquals(3, sst.getUniqueCount()); - - idx = sst.addEntry(st); - assertEquals(2, idx); - assertEquals(7, sst.getCount()); - assertEquals(3, sst.getUniqueCount()); - - //OK. the sst table is filled, check the contents - assertEquals(3, sst.getItems().size()); - assertEquals("Hello, World!", new XSSFRichTextString(sst.getEntryAt(0)).toString()); - assertEquals("Second string", new XSSFRichTextString(sst.getEntryAt(1)).toString()); - assertEquals("Second string", new XSSFRichTextString(sst.getEntryAt(2)).toString()); - } - - public void testReadWrite() throws IOException { - XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("sample.xlsx"); - SharedStringsTable sst1 = wb1.getSharedStringSource(); - - //serialize, read back and compare with the original - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - SharedStringsTable sst2 = wb2.getSharedStringSource(); - - assertEquals(sst1.getCount(), sst2.getCount()); - assertEquals(sst1.getUniqueCount(), sst2.getUniqueCount()); - - List items1 = sst1.getItems(); - List items2 = sst2.getItems(); - assertEquals(items1.size(), items2.size()); - for (int i = 0; i < items1.size(); i++) { - CTRst st1 = items1.get(i); - CTRst st2 = items2.get(i); - assertEquals(st1.toString(), st2.toString()); - } - - XSSFWorkbook wb3 = XSSFTestDataSamples.writeOutAndReadBack(wb2); - assertNotNull(wb3); - wb3.close(); - wb2.close(); - wb1.close(); - } - - /** - * Test for Bugzilla 48936 - * - * A specific sequence of strings can result in broken CDATA section in sharedStrings.xml file. - * - * @author Philippe Laflamme - */ - public void testBug48936() throws IOException { - Workbook w1 = new XSSFWorkbook(); - Sheet s = w1.createSheet(); - int i = 0; - List lst = readStrings("48936-strings.txt"); - for (String str : lst) { - s.createRow(i++).createCell(0).setCellValue(str); - } - - Workbook w2 = XSSFTestDataSamples.writeOutAndReadBack(w1); - w1.close(); - s = w2.getSheetAt(0); - i = 0; - for (String str : lst) { - String val = s.getRow(i++).getCell(0).getStringCellValue(); - assertEquals(str, val); - } - - Workbook w3 = XSSFTestDataSamples.writeOutAndReadBack(w2); - w2.close(); - assertNotNull(w3); - w3.close(); - } - - private List readStrings(String filename) throws IOException { - List strs = new ArrayList(); - POIDataSamples samples = POIDataSamples.getSpreadSheetInstance(); - BufferedReader br = new BufferedReader( - new InputStreamReader(samples.openResourceAsStream(filename), "UTF-8")); - String s; - while ((s = br.readLine()) != null) { - if (s.trim().length() > 0) { - strs.add(s.trim()); - } - } - br.close(); - return strs; - } - -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/model/TestStylesTable.java b/src/ooxml/testcases/org/apache/poi/xssf/model/TestStylesTable.java deleted file mode 100644 index 9d29fc453..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/model/TestStylesTable.java +++ /dev/null @@ -1,359 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.model; - -import org.junit.BeforeClass; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.IOException; -import java.util.Map; - -import org.apache.poi.ss.usermodel.BuiltinFormats; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.usermodel.XSSFCellStyle; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -public final class TestStylesTable { - private static final String testFile = "Formatting.xlsx"; - private static final String customDataFormat = "YYYY-mm-dd"; - - @BeforeClass - public static void assumeCustomDataFormatIsNotBuiltIn() { - assertEquals(-1, BuiltinFormats.getBuiltinFormat(customDataFormat)); - } - - @Test - public void testCreateNew() { - StylesTable st = new StylesTable(); - - // Check defaults - assertNotNull(st.getCTStylesheet()); - assertEquals(1, st._getXfsSize()); - assertEquals(1, st._getStyleXfsSize()); - assertEquals(0, st.getNumDataFormats()); - } - - @Test - public void testCreateSaveLoad() { - XSSFWorkbook wb = new XSSFWorkbook(); - StylesTable st = wb.getStylesSource(); - - assertNotNull(st.getCTStylesheet()); - assertEquals(1, st._getXfsSize()); - assertEquals(1, st._getStyleXfsSize()); - assertEquals(0, st.getNumDataFormats()); - - st = XSSFTestDataSamples.writeOutAndReadBack(wb).getStylesSource(); - - assertNotNull(st.getCTStylesheet()); - assertEquals(1, st._getXfsSize()); - assertEquals(1, st._getStyleXfsSize()); - assertEquals(0, st.getNumDataFormats()); - - assertNotNull(XSSFTestDataSamples.writeOutAndReadBack(wb)); - } - - @Test - public void testLoadExisting() { - XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook(testFile); - assertNotNull(workbook.getStylesSource()); - - StylesTable st = workbook.getStylesSource(); - - doTestExisting(st); - - assertNotNull(XSSFTestDataSamples.writeOutAndReadBack(workbook)); - } - - @Test - public void testLoadSaveLoad() { - XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook(testFile); - assertNotNull(workbook.getStylesSource()); - - StylesTable st = workbook.getStylesSource(); - doTestExisting(st); - - st = XSSFTestDataSamples.writeOutAndReadBack(workbook).getStylesSource(); - doTestExisting(st); - } - - public void doTestExisting(StylesTable st) { - // Check contents - assertNotNull(st.getCTStylesheet()); - assertEquals(11, st._getXfsSize()); - assertEquals(1, st._getStyleXfsSize()); - assertEquals(8, st.getNumDataFormats()); - - assertEquals(2, st.getFonts().size()); - assertEquals(2, st.getFills().size()); - assertEquals(1, st.getBorders().size()); - - assertEquals("yyyy/mm/dd", st.getNumberFormatAt((short)165)); - assertEquals("yy/mm/dd", st.getNumberFormatAt((short)167)); - - assertNotNull(st.getStyleAt(0)); - assertNotNull(st.getStyleAt(1)); - assertNotNull(st.getStyleAt(2)); - - assertEquals(0, st.getStyleAt(0).getDataFormat()); - assertEquals(14, st.getStyleAt(1).getDataFormat()); - assertEquals(0, st.getStyleAt(2).getDataFormat()); - assertEquals(165, st.getStyleAt(3).getDataFormat()); - - assertEquals("yyyy/mm/dd", st.getStyleAt(3).getDataFormatString()); - } - - @Test - public void populateNew() { - XSSFWorkbook wb = new XSSFWorkbook(); - StylesTable st = wb.getStylesSource(); - - assertNotNull(st.getCTStylesheet()); - assertEquals(1, st._getXfsSize()); - assertEquals(1, st._getStyleXfsSize()); - assertEquals(0, st.getNumDataFormats()); - - int nf1 = st.putNumberFormat("yyyy-mm-dd"); - int nf2 = st.putNumberFormat("yyyy-mm-DD"); - assertEquals(nf1, st.putNumberFormat("yyyy-mm-dd")); - - st.putStyle(new XSSFCellStyle(st)); - - // Save and re-load - st = XSSFTestDataSamples.writeOutAndReadBack(wb).getStylesSource(); - - assertNotNull(st.getCTStylesheet()); - assertEquals(2, st._getXfsSize()); - assertEquals(1, st._getStyleXfsSize()); - assertEquals(2, st.getNumDataFormats()); - - assertEquals("yyyy-mm-dd", st.getNumberFormatAt((short)nf1)); - assertEquals(nf1, st.putNumberFormat("yyyy-mm-dd")); - assertEquals(nf2, st.putNumberFormat("yyyy-mm-DD")); - - assertNotNull(XSSFTestDataSamples.writeOutAndReadBack(wb)); - } - - @Test - public void populateExisting() { - XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook(testFile); - assertNotNull(workbook.getStylesSource()); - - StylesTable st = workbook.getStylesSource(); - assertEquals(11, st._getXfsSize()); - assertEquals(1, st._getStyleXfsSize()); - assertEquals(8, st.getNumDataFormats()); - - int nf1 = st.putNumberFormat("YYYY-mm-dd"); - int nf2 = st.putNumberFormat("YYYY-mm-DD"); - assertEquals(nf1, st.putNumberFormat("YYYY-mm-dd")); - - st = XSSFTestDataSamples.writeOutAndReadBack(workbook).getStylesSource(); - - assertEquals(11, st._getXfsSize()); - assertEquals(1, st._getStyleXfsSize()); - assertEquals(10, st.getNumDataFormats()); - - assertEquals("YYYY-mm-dd", st.getNumberFormatAt((short)nf1)); - assertEquals(nf1, st.putNumberFormat("YYYY-mm-dd")); - assertEquals(nf2, st.putNumberFormat("YYYY-mm-DD")); - - assertNotNull(XSSFTestDataSamples.writeOutAndReadBack(workbook)); - } - - @Test - public void exceedNumberFormatLimit() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - try { - StylesTable styles = wb.getStylesSource(); - for (int i = 0; i < styles.getMaxNumberOfDataFormats(); i++) { - wb.getStylesSource().putNumberFormat("\"test" + i + " \"0"); - } - try { - wb.getStylesSource().putNumberFormat("\"anotherformat \"0"); - } catch (final IllegalStateException e) { - if (e.getMessage().startsWith("The maximum number of Data Formats was exceeded.")) { - //expected - } - else { - throw e; - } - } - } finally { - wb.close(); - } - } - - private static final void assertNotContainsKey(Map map, K key) { - assertFalse(map.containsKey(key)); - } - private static final void assertNotContainsValue(Map map, V value) { - assertFalse(map.containsValue(value)); - } - - @Test - public void removeNumberFormat() throws IOException { - XSSFWorkbook wb1 = new XSSFWorkbook(); - try { - final String fmt = customDataFormat; - final short fmtIdx = (short) wb1.getStylesSource().putNumberFormat(fmt); - - Cell cell = wb1.createSheet("test").createRow(0).createCell(0); - cell.setCellValue(5.25); - CellStyle style = wb1.createCellStyle(); - style.setDataFormat(fmtIdx); - cell.setCellStyle(style); - - assertEquals(fmt, cell.getCellStyle().getDataFormatString()); - assertEquals(fmt, wb1.getStylesSource().getNumberFormatAt(fmtIdx)); - - // remove the number format from the workbook - wb1.getStylesSource().removeNumberFormat(fmt); - - // number format in CellStyles should be restored to default number format - final short defaultFmtIdx = 0; - final String defaultFmt = BuiltinFormats.getBuiltinFormat(0); - assertEquals(defaultFmtIdx, style.getDataFormat()); - assertEquals(defaultFmt, style.getDataFormatString()); - - // The custom number format should be entirely removed from the workbook - Map numberFormats = wb1.getStylesSource().getNumberFormats(); - assertNotContainsKey(numberFormats, fmtIdx); - assertNotContainsValue(numberFormats, fmt); - - // The default style shouldn't be added back to the styles source because it's built-in - assertEquals(0, wb1.getStylesSource().getNumDataFormats()); - - cell = null; style = null; numberFormats = null; - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutCloseAndReadBack(wb1); - - cell = wb2.getSheet("test").getRow(0).getCell(0); - style = cell.getCellStyle(); - - // number format in CellStyles should be restored to default number format - assertEquals(defaultFmtIdx, style.getDataFormat()); - assertEquals(defaultFmt, style.getDataFormatString()); - - // The custom number format should be entirely removed from the workbook - numberFormats = wb2.getStylesSource().getNumberFormats(); - assertNotContainsKey(numberFormats, fmtIdx); - assertNotContainsValue(numberFormats, fmt); - - // The default style shouldn't be added back to the styles source because it's built-in - assertEquals(0, wb2.getStylesSource().getNumDataFormats()); - - wb2.close(); - - } finally { - wb1.close(); - } - } - - @Test - public void maxNumberOfDataFormats() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - - try { - StylesTable styles = wb.getStylesSource(); - - // Check default limit - int n = styles.getMaxNumberOfDataFormats(); - // https://support.office.com/en-us/article/excel-specifications-and-limits-1672b34d-7043-467e-8e27-269d656771c3 - assertTrue(200 <= n); - assertTrue(n <= 250); - - // Check upper limit - n = Integer.MAX_VALUE; - styles.setMaxNumberOfDataFormats(n); - assertEquals(n, styles.getMaxNumberOfDataFormats()); - - // Check negative (illegal) limits - try { - styles.setMaxNumberOfDataFormats(-1); - fail("Expected to get an IllegalArgumentException(\"Maximum Number of Data Formats must be greater than or equal to 0\")"); - } catch (final IllegalArgumentException e) { - if (e.getMessage().startsWith("Maximum Number of Data Formats must be greater than or equal to 0")) { - // expected - } else { - throw e; - } - } - } - finally { - wb.close(); - } - } - - @Test - public void addDataFormatsBeyondUpperLimit() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - - try { - StylesTable styles = wb.getStylesSource(); - styles.setMaxNumberOfDataFormats(0); - - // Try adding a format beyond the upper limit - try { - styles.putNumberFormat("\"test \"0"); - fail("Expected to raise IllegalStateException"); - } catch (final IllegalStateException e) { - if (e.getMessage().startsWith("The maximum number of Data Formats was exceeded.")) { - // expected - } else { - throw e; - } - } - } - finally { - wb.close(); - } - } - - @Test - public void decreaseUpperLimitBelowCurrentNumDataFormats() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - - try { - StylesTable styles = wb.getStylesSource(); - styles.putNumberFormat(customDataFormat); - - // Try decreasing the upper limit below the current number of formats - try { - styles.setMaxNumberOfDataFormats(0); - fail("Expected to raise IllegalStateException"); - } catch (final IllegalStateException e) { - if (e.getMessage().startsWith("Cannot set the maximum number of data formats less than the current quantity.")) { - // expected - } else { - throw e; - } - } - } - finally { - wb.close(); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/model/TestThemesTable.java b/src/ooxml/testcases/org/apache/poi/xssf/model/TestThemesTable.java deleted file mode 100644 index b91c88c2c..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/model/TestThemesTable.java +++ /dev/null @@ -1,263 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.model; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import java.io.FileOutputStream; -import java.util.LinkedHashMap; -import java.util.Locale; -import java.util.Map; - -import org.apache.commons.codec.binary.Hex; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.model.ThemesTable.ThemeElement; -import org.apache.poi.xssf.usermodel.XSSFCell; -import org.apache.poi.xssf.usermodel.XSSFCellStyle; -import org.apache.poi.xssf.usermodel.XSSFColor; -import org.apache.poi.xssf.usermodel.XSSFFont; -import org.apache.poi.xssf.usermodel.XSSFRow; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Test; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTColor; - -public class TestThemesTable { - private final String testFileSimple = "Themes.xlsx"; - private final String testFileComplex = "Themes2.xlsx"; - // TODO .xls version available too, add HSSF support then check - - // What colours they should show up as - private static String rgbExpected[] = { - "ffffff", // Lt1 - "000000", // Dk1 - "eeece1", // Lt2 - "1f497d", // DK2 - "4f81bd", // Accent1 - "c0504d", // Accent2 - "9bbb59", // Accent3 - "8064a2", // Accent4 - "4bacc6", // Accent5 - "f79646", // Accent6 - "0000ff", // Hlink - "800080" // FolHlink - }; - - @Test - public void testThemesTableColors() throws Exception { - // Load our two test workbooks - XSSFWorkbook simple = XSSFTestDataSamples.openSampleWorkbook(testFileSimple); - XSSFWorkbook complex = XSSFTestDataSamples.openSampleWorkbook(testFileComplex); - // Save and re-load them, to check for stability across that - XSSFWorkbook simpleRS = XSSFTestDataSamples.writeOutAndReadBack(simple); - XSSFWorkbook complexRS = XSSFTestDataSamples.writeOutAndReadBack(complex); - // Fetch fresh copies to test with - simple = XSSFTestDataSamples.openSampleWorkbook(testFileSimple); - complex = XSSFTestDataSamples.openSampleWorkbook(testFileComplex); - // Files and descriptions - Map workbooks = new LinkedHashMap(); - workbooks.put(testFileSimple, simple); - workbooks.put("Re-Saved_" + testFileSimple, simpleRS); - workbooks.put(testFileComplex, complex); - workbooks.put("Re-Saved_" + testFileComplex, complexRS); - - // Sanity check - assertEquals(rgbExpected.length, rgbExpected.length); - - // For offline testing - boolean createFiles = false; - - // Check each workbook in turn, and verify that the colours - // for the theme-applied cells in Column A are correct - for (String whatWorkbook : workbooks.keySet()) { - XSSFWorkbook workbook = workbooks.get(whatWorkbook); - XSSFSheet sheet = workbook.getSheetAt(0); - int startRN = 0; - if (whatWorkbook.endsWith(testFileComplex)) startRN++; - - for (int rn=startRN; rn tempFiles = new ArrayList(); - - List getTempFiles() { - return new ArrayList(tempFiles); - } - - @Override - protected SheetDataWriter createSheetDataWriter() throws IOException { - return new TempFileRecordingSheetDataWriterWithDecorator(); - } - - class TempFileRecordingSheetDataWriterWithDecorator extends SheetDataWriterWithDecorator { - - TempFileRecordingSheetDataWriterWithDecorator() throws IOException { - super(); - tempFiles.add(getTempFile()); - } - } -} \ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestAutoSizeColumnTracker.java b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestAutoSizeColumnTracker.java deleted file mode 100644 index a6a2dde5e..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestAutoSizeColumnTracker.java +++ /dev/null @@ -1,219 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.streaming; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.junit.Assume.assumeFalse; -import static org.junit.Assume.assumeTrue; - -import java.io.IOException; -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; -import java.util.SortedSet; -import java.util.TreeSet; - -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Font; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.SheetUtil; -import org.junit.After; -import org.junit.Assume; -import org.junit.Before; -import org.junit.Test; - - -/** - * Tests the auto-sizing behaviour of {@link SXSSFSheet} when not all - * rows fit into the memory window size etc. - * - * @see Bug #57450 which reported the original mis-behaviour - */ -public class TestAutoSizeColumnTracker { - - private SXSSFSheet sheet; - private SXSSFWorkbook workbook; - private AutoSizeColumnTracker tracker; - private static final SortedSet columns; - static { - SortedSet_columns = new TreeSet(); - _columns.add(0); - _columns.add(1); - _columns.add(3); - columns = Collections.unmodifiableSortedSet(_columns); - } - private final static String SHORT_MESSAGE = "short"; - private final static String LONG_MESSAGE = "This is a test of a long message! This is a test of a long message!"; - - @Before - public void setUpSheetAndWorkbook() { - workbook = new SXSSFWorkbook(); - sheet = workbook.createSheet(); - tracker = new AutoSizeColumnTracker(sheet); - } - - @After - public void tearDownSheetAndWorkbook() throws IOException { - if (sheet != null) { - sheet.dispose(); - } - if (workbook != null) { - workbook.close(); - } - } - - @Test - public void trackAndUntrackColumn() { - assumeTrue(tracker.getTrackedColumns().isEmpty()); - tracker.trackColumn(0); - Set expected = new HashSet(); - expected.add(0); - assertEquals(expected, tracker.getTrackedColumns()); - tracker.untrackColumn(0); - assertTrue(tracker.getTrackedColumns().isEmpty()); - } - - @Test - public void trackAndUntrackColumns() { - assumeTrue(tracker.getTrackedColumns().isEmpty()); - tracker.trackColumns(columns); - assertEquals(columns, tracker.getTrackedColumns()); - tracker.untrackColumn(3); - tracker.untrackColumn(0); - tracker.untrackColumn(1); - assertTrue(tracker.getTrackedColumns().isEmpty()); - tracker.trackColumn(0); - tracker.trackColumns(columns); - tracker.untrackColumn(4); - assertEquals(columns, tracker.getTrackedColumns()); - tracker.untrackColumns(columns); - assertTrue(tracker.getTrackedColumns().isEmpty()); - } - - @Test - public void trackAndUntrackAllColumns() { - assumeTrue(tracker.getTrackedColumns().isEmpty()); - tracker.trackAllColumns(); - assertTrue(tracker.getTrackedColumns().isEmpty()); - - Row row = sheet.createRow(0); - for (int column : columns) { - row.createCell(column); - } - // implicitly track the columns - tracker.updateColumnWidths(row); - assertEquals(columns, tracker.getTrackedColumns()); - - tracker.untrackAllColumns(); - assertTrue(tracker.getTrackedColumns().isEmpty()); - } - - @Test - public void isColumnTracked() { - assumeFalse(tracker.isColumnTracked(0)); - tracker.trackColumn(0); - assertTrue(tracker.isColumnTracked(0)); - tracker.untrackColumn(0); - assertFalse(tracker.isColumnTracked(0)); - } - - @Test - public void getTrackedColumns() { - assumeTrue(tracker.getTrackedColumns().isEmpty()); - - for (int column : columns) { - tracker.trackColumn(column); - } - - assertEquals(3, tracker.getTrackedColumns().size()); - assertEquals(columns, tracker.getTrackedColumns()); - } - - @Test - public void isAllColumnsTracked() { - assertFalse(tracker.isAllColumnsTracked()); - tracker.trackAllColumns(); - assertTrue(tracker.isAllColumnsTracked()); - tracker.untrackAllColumns(); - assertFalse(tracker.isAllColumnsTracked()); - } - - @Test - public void updateColumnWidths_and_getBestFitColumnWidth() { - tracker.trackAllColumns(); - Row row1 = sheet.createRow(0); - Row row2 = sheet.createRow(1); - // A1, B1, D1 - for (int column : columns) { - row1.createCell(column).setCellValue(LONG_MESSAGE); - row2.createCell(column+1).setCellValue(SHORT_MESSAGE); - } - tracker.updateColumnWidths(row1); - tracker.updateColumnWidths(row2); - sheet.addMergedRegion(CellRangeAddress.valueOf("D1:E1")); - - assumeRequiredFontsAreInstalled(workbook, row1.getCell(columns.iterator().next())); - - // Excel 2013 and LibreOffice 4.2.8.2 both treat columns with merged regions as blank - /** A B C D E - * 1 LONG LONG LONGMERGE - * 2 SHORT SHORT SHORT - */ - - // measured in Excel 2013. Sizes may vary. - final int longMsgWidth = (int) (57.43*256); - final int shortMsgWidth = (int) (4.86*256); - - checkColumnWidth(longMsgWidth, 0, true); - checkColumnWidth(longMsgWidth, 0, false); - checkColumnWidth(longMsgWidth, 1, true); - checkColumnWidth(longMsgWidth, 1, false); - checkColumnWidth(shortMsgWidth, 2, true); - checkColumnWidth(shortMsgWidth, 2, false); - checkColumnWidth(-1, 3, true); - checkColumnWidth(longMsgWidth, 3, false); - checkColumnWidth(shortMsgWidth, 4, true); //but is it really? shouldn't autosizing column E use "" from E1 and SHORT from E2? - checkColumnWidth(shortMsgWidth, 4, false); - } - - private void checkColumnWidth(int expectedWidth, int column, boolean useMergedCells) { - final int bestFitWidth = tracker.getBestFitColumnWidth(column, useMergedCells); - if (bestFitWidth < 0 && expectedWidth < 0) return; - final double abs_error = Math.abs(bestFitWidth-expectedWidth); - final double rel_error = abs_error / expectedWidth; - if (rel_error > 0.25) { - fail("check column width: " + - rel_error + ", " + abs_error + ", " + - expectedWidth + ", " + bestFitWidth); - } - - } - - private static void assumeRequiredFontsAreInstalled(final Workbook workbook, final Cell cell) { - // autoSize will fail if required fonts are not installed, skip this test then - Font font = workbook.getFontAt(cell.getCellStyle().getFontIndex()); - System.out.println(font.getFontHeightInPoints()); - System.out.println(font.getFontName()); - Assume.assumeTrue("Cannot verify autoSizeColumn() because the necessary Fonts are not installed on this machine: " + font, - SheetUtil.canComputeColumnWidth(font)); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestOutlining.java b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestOutlining.java deleted file mode 100644 index 7ce130d54..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestOutlining.java +++ /dev/null @@ -1,235 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xssf.streaming; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Test; - -public final class TestOutlining { - @Test - public void testSetRowGroupCollapsed() throws IOException { - SXSSFWorkbook wb2 = new SXSSFWorkbook(100); - wb2.setCompressTempFiles(true); - SXSSFSheet sheet2 = wb2.createSheet("new sheet"); - - int rowCount = 20; - for (int i = 0; i < rowCount; i++) { - sheet2.createRow(i); - } - - sheet2.groupRow(4, 9); - sheet2.groupRow(11, 19); - - sheet2.setRowGroupCollapsed(4, true); - - SXSSFRow r = sheet2.getRow(8); - assertTrue(r.getHidden()); - r = sheet2.getRow(10); - assertTrue(r.getCollapsed()); - r = sheet2.getRow(12); - assertNull(r.getHidden()); - wb2.dispose(); - - wb2.close(); - } - - @Test - public void testSetRowGroupCollapsedError() throws IOException { - SXSSFWorkbook wb2 = new SXSSFWorkbook(100); - wb2.setCompressTempFiles(true); - SXSSFSheet sheet2 = wb2.createSheet("new sheet"); - - int rowCount = 20; - for (int i = 0; i < rowCount; i++) { - sheet2.createRow(i); - } - - sheet2.groupRow(4, 9); - sheet2.groupRow(11, 19); - - try { - sheet2.setRowGroupCollapsed(3, true); - fail("Should fail with an exception"); - } catch (IllegalArgumentException e) { - assertTrue(e.getMessage().contains("row (3)")); - } - - try { - sheet2.setRowGroupCollapsed(10, true); - fail("Should fail with an exception"); - } catch (IllegalArgumentException e) { - assertTrue(e.getMessage().contains("row (10)")); - } - - try { - sheet2.setRowGroupCollapsed(0, true); - fail("Should fail with an exception"); - } catch (IllegalArgumentException e) { - assertTrue(e.getMessage().contains("row (0)")); - } - - try { - sheet2.setRowGroupCollapsed(20, true); - fail("Should fail with an exception"); - } catch (IllegalArgumentException e) { - assertTrue("Had: " + e.getMessage(), - e.getMessage().contains("Row does not exist")); - } - - SXSSFRow r = sheet2.getRow(8); - assertNotNull(r); - assertNull(r.getHidden()); - r = sheet2.getRow(10); - assertNull(r.getCollapsed()); - r = sheet2.getRow(12); - assertNull(r.getHidden()); - wb2.dispose(); - - wb2.close(); - } - - @Test - public void testOutlineGettersHSSF() throws IOException { - HSSFWorkbook hssfWorkbook = new HSSFWorkbook(); - HSSFSheet hssfSheet = hssfWorkbook.createSheet(); - hssfSheet.createRow(0); - hssfSheet.createRow(1); - hssfSheet.createRow(2); - hssfSheet.createRow(3); - hssfSheet.createRow(4); - hssfSheet.groupRow(1, 3); - hssfSheet.groupRow(2, 3); - - assertEquals(0, hssfSheet.getRow(0).getOutlineLevel()); - assertEquals(1, hssfSheet.getRow(1).getOutlineLevel()); - assertEquals(2, hssfSheet.getRow(2).getOutlineLevel()); - assertEquals(2, hssfSheet.getRow(3).getOutlineLevel()); - assertEquals(0, hssfSheet.getRow(4).getOutlineLevel()); - hssfWorkbook.close(); - } - - @Test - public void testOutlineGettersXSSF() throws IOException { - XSSFWorkbook xssfWorkbook = new XSSFWorkbook(); - XSSFSheet xssfSheet = xssfWorkbook.createSheet(); - xssfSheet.createRow(0); - xssfSheet.createRow(1); - xssfSheet.createRow(2); - xssfSheet.createRow(3); - xssfSheet.createRow(4); - xssfSheet.groupRow(1, 3); - xssfSheet.groupRow(2, 3); - - assertEquals(0, xssfSheet.getRow(0).getOutlineLevel()); - assertEquals(1, xssfSheet.getRow(1).getOutlineLevel()); - assertEquals(2, xssfSheet.getRow(2).getOutlineLevel()); - assertEquals(2, xssfSheet.getRow(3).getOutlineLevel()); - assertEquals(0, xssfSheet.getRow(4).getOutlineLevel()); - xssfWorkbook.close(); - } - - @Test - public void testOutlineGettersSXSSF() throws IOException { - SXSSFWorkbook sxssfWorkbook = new SXSSFWorkbook(); - Sheet sxssfSheet = sxssfWorkbook.createSheet(); - sxssfSheet.createRow(0); - sxssfSheet.createRow(1); - sxssfSheet.createRow(2); - sxssfSheet.createRow(3); - sxssfSheet.createRow(4); - sxssfSheet.createRow(5); - - // nothing happens with empty row-area - sxssfSheet.groupRow(1, 0); - assertEquals(0, sxssfSheet.getRow(0).getOutlineLevel()); - assertEquals(0, sxssfSheet.getRow(1).getOutlineLevel()); - assertEquals(0, sxssfSheet.getRow(2).getOutlineLevel()); - assertEquals(0, sxssfSheet.getRow(3).getOutlineLevel()); - assertEquals(0, sxssfSheet.getRow(4).getOutlineLevel()); - assertEquals(0, sxssfSheet.getRow(5).getOutlineLevel()); - - sxssfSheet.groupRow(1, 3); - sxssfSheet.groupRow(2, 3); - - assertEquals(0, sxssfSheet.getRow(0).getOutlineLevel()); - assertEquals(1, sxssfSheet.getRow(1).getOutlineLevel()); - assertEquals(2, sxssfSheet.getRow(2).getOutlineLevel()); - assertEquals(2, sxssfSheet.getRow(3).getOutlineLevel()); - assertEquals(0, sxssfSheet.getRow(4).getOutlineLevel()); - assertEquals(0, sxssfSheet.getRow(5).getOutlineLevel()); - - // add tests for direct setting - add row 4 to deepest group - ((SXSSFSheet)sxssfSheet).setRowOutlineLevel(4, 2); - assertEquals(0, sxssfSheet.getRow(0).getOutlineLevel()); - assertEquals(1, sxssfSheet.getRow(1).getOutlineLevel()); - assertEquals(2, sxssfSheet.getRow(2).getOutlineLevel()); - assertEquals(2, sxssfSheet.getRow(3).getOutlineLevel()); - assertEquals(2, sxssfSheet.getRow(4).getOutlineLevel()); - assertEquals(0, sxssfSheet.getRow(5).getOutlineLevel()); - - sxssfWorkbook.dispose(); - sxssfWorkbook.close(); - } - - @Test - public void testOutlineGettersSXSSFSetOutlineLevel() throws IOException { - SXSSFWorkbook sxssfWorkbook = new SXSSFWorkbook(); - Sheet sxssfSheet = sxssfWorkbook.createSheet(); - sxssfSheet.createRow(0); - sxssfSheet.createRow(1); - sxssfSheet.createRow(2); - sxssfSheet.createRow(3); - sxssfSheet.createRow(4); - sxssfSheet.createRow(5); - - // what happens with level below 1 - ((SXSSFSheet)sxssfSheet).setRowOutlineLevel(0, -2); - assertEquals(-2, sxssfSheet.getRow(0).getOutlineLevel()); - assertEquals(0, sxssfSheet.getRow(1).getOutlineLevel()); - assertEquals(0, sxssfSheet.getRow(2).getOutlineLevel()); - assertEquals(0, sxssfSheet.getRow(3).getOutlineLevel()); - assertEquals(0, sxssfSheet.getRow(4).getOutlineLevel()); - assertEquals(0, sxssfSheet.getRow(5).getOutlineLevel()); - - // add tests for direct setting - ((SXSSFSheet)sxssfSheet).setRowOutlineLevel(4, 2); - assertEquals(-2, sxssfSheet.getRow(0).getOutlineLevel()); - assertEquals(0, sxssfSheet.getRow(1).getOutlineLevel()); - assertEquals(0, sxssfSheet.getRow(2).getOutlineLevel()); - assertEquals(0, sxssfSheet.getRow(3).getOutlineLevel()); - assertEquals(2, sxssfSheet.getRow(4).getOutlineLevel()); - assertEquals(0, sxssfSheet.getRow(5).getOutlineLevel()); - - sxssfWorkbook.dispose(); - sxssfWorkbook.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFCell.java b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFCell.java deleted file mode 100644 index b84b06bb3..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFCell.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xssf.streaming; - -import static org.junit.Assert.assertEquals; - -import java.io.IOException; - -import javax.xml.namespace.QName; - -import org.apache.poi.ss.usermodel.BaseTestXCell; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.xssf.SXSSFITestDataProvider; -import org.apache.poi.xssf.usermodel.XSSFCell; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.apache.xmlbeans.XmlCursor; -import org.junit.AfterClass; -import org.junit.Test; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRst; - -/** - * Tests various functionality having to do with {@link SXSSFCell}. For instance support for - * particular datatypes, etc. - */ -public class TestSXSSFCell extends BaseTestXCell { - - public TestSXSSFCell() { - super(SXSSFITestDataProvider.instance); - } - - @AfterClass - public static void tearDownClass(){ - SXSSFITestDataProvider.instance.cleanup(); - } - - @Test - public void testPreserveSpaces() throws IOException { - String[] samplesWithSpaces = { - " POI", - "POI ", - " POI ", - "\nPOI", - "\n\nPOI \n", - }; - for(String str : samplesWithSpaces){ - Workbook swb = _testDataProvider.createWorkbook(); - Cell sCell = swb.createSheet().createRow(0).createCell(0); - sCell.setCellValue(str); - assertEquals(sCell.getStringCellValue(), str); - - // read back as XSSF and check that xml:spaces="preserve" is set - XSSFWorkbook xwb = (XSSFWorkbook)_testDataProvider.writeOutAndReadBack(swb); - XSSFCell xCell = xwb.getSheetAt(0).getRow(0).getCell(0); - - CTRst is = xCell.getCTCell().getIs(); - XmlCursor c = is.newCursor(); - c.toNextToken(); - String t = c.getAttributeText(new QName("http://www.w3.org/XML/1998/namespace", "space")); - c.dispose(); - assertEquals("expected xml:spaces=\"preserve\" \"" + str + "\"", "preserve", t); - xwb.close(); - swb.close(); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFDataValidation.java b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFDataValidation.java deleted file mode 100644 index c383c1c7b..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFDataValidation.java +++ /dev/null @@ -1,62 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.streaming; - -import static org.junit.Assert.assertEquals; - -import java.util.List; - -import org.apache.poi.ss.usermodel.BaseTestDataValidation; -import org.apache.poi.ss.usermodel.DataValidation; -import org.apache.poi.ss.usermodel.DataValidationConstraint; -import org.apache.poi.ss.usermodel.DataValidationHelper; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.util.CellRangeAddressList; -import org.apache.poi.xssf.SXSSFITestDataProvider; -import org.junit.Test; - -public class TestSXSSFDataValidation extends BaseTestDataValidation { - - public TestSXSSFDataValidation(){ - super(SXSSFITestDataProvider.instance); - } - - @Test - public void test53965() throws Exception { - SXSSFWorkbook wb = new SXSSFWorkbook(); - try { - Sheet sheet = wb.createSheet(); - List lst = sheet.getDataValidations(); //<-- works - assertEquals(0, lst.size()); - - //create the cell that will have the validation applied - sheet.createRow(0).createCell(0); - - DataValidationHelper dataValidationHelper = sheet.getDataValidationHelper(); - DataValidationConstraint constraint = dataValidationHelper.createCustomConstraint("SUM($A$1:$A$1) <= 3500"); - CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0); - DataValidation validation = dataValidationHelper.createValidation(constraint, addressList); - sheet.addValidationData(validation); - - // this line caused XmlValueOutOfRangeException , see Bugzilla 3965 - lst = sheet.getDataValidations(); - assertEquals(1, lst.size()); - } finally { - wb.close(); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFFormulaEvaluation.java b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFFormulaEvaluation.java deleted file mode 100644 index 0839fe801..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFFormulaEvaluation.java +++ /dev/null @@ -1,181 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xssf.streaming; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -import java.io.IOException; - -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.xssf.SXSSFITestDataProvider; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Test; - -/** - * Formula Evaluation with SXSSF. - * - * Note that SXSSF can only evaluate formulas where the - * cell is in the current window, and all references - * from the cell are in the current window - */ -public final class TestSXSSFFormulaEvaluation { - public static final SXSSFITestDataProvider _testDataProvider = SXSSFITestDataProvider.instance; - - /** - * EvaluateAll will normally fail, as any reference or - * formula outside of the window will fail, and any - * non-active sheets will fail - */ - @Test - public void testEvaluateAllFails() throws IOException { - SXSSFWorkbook wb = new SXSSFWorkbook(5); - SXSSFSheet s = wb.createSheet(); - - FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator(); - - s.createRow(0).createCell(0).setCellFormula("1+2"); - s.createRow(1).createCell(0).setCellFormula("A21"); - for (int i=2; i<19; i++) { s.createRow(i); } - - // Cells outside window will fail, whether referenced or not - s.createRow(19).createCell(0).setCellFormula("A1+A2"); - s.createRow(20).createCell(0).setCellFormula("A1+A11+100"); - try { - eval.evaluateAll(); - fail("Evaluate All shouldn't work, as some cells outside the window"); - } catch(SXSSFFormulaEvaluator.RowFlushedException e) { - // Expected - } - - - // Inactive sheets will fail - XSSFWorkbook xwb = new XSSFWorkbook(); - xwb.createSheet("Open"); - xwb.createSheet("Closed"); - - wb.close(); - wb = new SXSSFWorkbook(xwb, 5); - s = wb.getSheet("Closed"); - s.flushRows(); - s = wb.getSheet("Open"); - s.createRow(0).createCell(0).setCellFormula("1+2"); - - eval = wb.getCreationHelper().createFormulaEvaluator(); - try { - eval.evaluateAll(); - fail("Evaluate All shouldn't work, as sheets flushed"); - } catch (SXSSFFormulaEvaluator.SheetsFlushedException e) {} - - wb.close(); - } - - @Test - public void testEvaluateRefOutsideWindowFails() throws IOException { - SXSSFWorkbook wb = new SXSSFWorkbook(5); - SXSSFSheet s = wb.createSheet(); - - s.createRow(0).createCell(0).setCellFormula("1+2"); - assertEquals(false, s.areAllRowsFlushed()); - assertEquals(-1, s.getLastFlushedRowNum()); - - for (int i=1; i<=19; i++) { s.createRow(i); } - Cell c = s.createRow(20).createCell(0); - c.setCellFormula("A1+100"); - - assertEquals(false, s.areAllRowsFlushed()); - assertEquals(15, s.getLastFlushedRowNum()); - - FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator(); - try { - eval.evaluateFormulaCellEnum(c); - fail("Evaluate shouldn't work, as reference outside the window"); - } catch(SXSSFFormulaEvaluator.RowFlushedException e) { - // Expected - } - - wb.close(); - } - - /** - * If all formula cells + their references are inside the window, - * then evaluation works - * @throws IOException - */ - @Test - public void testEvaluateAllInWindow() throws IOException { - SXSSFWorkbook wb = new SXSSFWorkbook(5); - SXSSFSheet s = wb.createSheet(); - s.createRow(0).createCell(0).setCellFormula("1+2"); - s.createRow(1).createCell(1).setCellFormula("A1+10"); - s.createRow(2).createCell(2).setCellFormula("B2+100"); - - FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator(); - eval.evaluateAll(); - - assertEquals(3, (int)s.getRow(0).getCell(0).getNumericCellValue()); - assertEquals(13, (int)s.getRow(1).getCell(1).getNumericCellValue()); - assertEquals(113, (int)s.getRow(2).getCell(2).getNumericCellValue()); - - wb.close(); - } - - @Test - public void testEvaluateRefInsideWindow() throws IOException { - SXSSFWorkbook wb = new SXSSFWorkbook(5); - SXSSFSheet s = wb.createSheet(); - - FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator(); - - SXSSFCell c = s.createRow(0).createCell(0); - c.setCellValue(1.5); - - c = s.createRow(1).createCell(0); - c.setCellFormula("A1*2"); - - assertEquals(0, (int)c.getNumericCellValue()); - eval.evaluateFormulaCellEnum(c); - assertEquals(3, (int)c.getNumericCellValue()); - - wb.close(); - } - - @Test - public void testEvaluateSimple() throws IOException { - SXSSFWorkbook wb = new SXSSFWorkbook(5); - SXSSFSheet s = wb.createSheet(); - - FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator(); - - SXSSFCell c = s.createRow(0).createCell(0); - c.setCellFormula("1+2"); - assertEquals(0, (int)c.getNumericCellValue()); - eval.evaluateFormulaCellEnum(c); - assertEquals(3, (int)c.getNumericCellValue()); - - c = s.createRow(1).createCell(0); - c.setCellFormula("CONCATENATE(\"hello\",\" \",\"world\")"); - eval.evaluateFormulaCellEnum(c); - assertEquals("hello world", c.getStringCellValue()); - - wb.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFHyperlink.java b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFHyperlink.java deleted file mode 100644 index e1e237b68..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFHyperlink.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xssf.streaming; - -import org.junit.After; - -import org.apache.poi.ss.usermodel.BaseTestHyperlink; -import org.apache.poi.ss.usermodel.Hyperlink; -import org.apache.poi.xssf.SXSSFITestDataProvider; -import org.apache.poi.xssf.usermodel.XSSFHyperlink; - -/** - * Test setting hyperlinks in SXSSF - * - * @author Yegor Kozlov - */ -public class TestSXSSFHyperlink extends BaseTestHyperlink { - - public TestSXSSFHyperlink() { - super(SXSSFITestDataProvider.instance); - } - - - @After - public void tearDown(){ - SXSSFITestDataProvider.instance.cleanup(); - } - - @Override - public XSSFHyperlink copyHyperlink(Hyperlink link) { - // FIXME: replace with SXSSFHyperlink if it ever gets created - return new XSSFHyperlink(link); - } - -} \ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFRow.java b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFRow.java deleted file mode 100644 index 90a730d19..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFRow.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xssf.streaming; - -import org.apache.poi.ss.usermodel.BaseTestXRow; -import org.apache.poi.xssf.SXSSFITestDataProvider; -import org.junit.After; - -/** - * Tests for XSSFRow - */ -public final class TestSXSSFRow extends BaseTestXRow { - - public TestSXSSFRow() { - super(SXSSFITestDataProvider.instance); - } - - - @After - public void tearDown() { - ((SXSSFITestDataProvider) _testDataProvider).cleanup(); - } - -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFSheet.java b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFSheet.java deleted file mode 100644 index d5be11e2f..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFSheet.java +++ /dev/null @@ -1,175 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xssf.streaming; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -import java.io.IOException; - -import org.apache.poi.ss.usermodel.BaseTestXSheet; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.xssf.SXSSFITestDataProvider; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.After; -import org.junit.Test; - - -public final class TestSXSSFSheet extends BaseTestXSheet { - - public TestSXSSFSheet() { - super(SXSSFITestDataProvider.instance); - } - - - @After - public void tearDown(){ - SXSSFITestDataProvider.instance.cleanup(); - } - - @Override - protected void trackColumnsForAutoSizingIfSXSSF(Sheet sheet) { - SXSSFSheet sxSheet = (SXSSFSheet) sheet; - sxSheet.trackAllColumnsForAutoSizing(); - } - - - /** - * cloning of sheets is not supported in SXSSF - */ - @Override - @Test - public void cloneSheet() throws IOException { - thrown.expect(RuntimeException.class); - thrown.expectMessage("NotImplemented"); - super.cloneSheet(); - } - - @Override - @Test - public void cloneSheetMultipleTimes() throws IOException { - thrown.expect(RuntimeException.class); - thrown.expectMessage("NotImplemented"); - super.cloneSheetMultipleTimes(); - } - - /** - * shifting rows is not supported in SXSSF - */ - @Override - @Test - public void shiftMerged() throws IOException { - thrown.expect(RuntimeException.class); - thrown.expectMessage("NotImplemented"); - super.shiftMerged(); - } - - /** - * Bug 35084: cloning cells with formula - * - * The test is disabled because cloning of sheets is not supported in SXSSF - */ - @Override - @Test - public void bug35084() throws IOException { - thrown.expect(RuntimeException.class); - thrown.expectMessage("NotImplemented"); - super.bug35084(); - } - - @Override - @Test - public void getCellComment() throws IOException { - // TODO: reading cell comments via Sheet does not work currently as it tries - // to access the underlying sheet for this, but comments are stored as - // properties on Cells... - } - - @Override - @Test - public void defaultColumnStyle() { - //TODO column styles are not yet supported by XSSF - } - - @Test - public void overrideFlushedRows() throws IOException { - Workbook wb = new SXSSFWorkbook(3); - try { - Sheet sheet = wb.createSheet(); - - sheet.createRow(1); - sheet.createRow(2); - sheet.createRow(3); - sheet.createRow(4); - - thrown.expect(Throwable.class); - thrown.expectMessage("Attempting to write a row[1] in the range [0,1] that is already written to disk."); - sheet.createRow(1); - } finally { - wb.close(); - } - } - - @Test - public void overrideRowsInTemplate() throws IOException { - XSSFWorkbook template = new XSSFWorkbook(); - template.createSheet().createRow(1); - - Workbook wb = new SXSSFWorkbook(template); - try { - Sheet sheet = wb.getSheetAt(0); - - try { - sheet.createRow(1); - fail("expected exception"); - } catch (Throwable e){ - assertEquals("Attempting to write a row[1] in the range [0,1] that is already written to disk.", e.getMessage()); - } - try { - sheet.createRow(0); - fail("expected exception"); - } catch (Throwable e){ - assertEquals("Attempting to write a row[0] in the range [0,1] that is already written to disk.", e.getMessage()); - } - sheet.createRow(2); - } finally { - wb.close(); - template.close(); - } - } - - @Test - public void changeRowNum() throws IOException { - SXSSFWorkbook wb = new SXSSFWorkbook(3); - SXSSFSheet sheet = wb.createSheet(); - SXSSFRow row0 = sheet.createRow(0); - SXSSFRow row1 = sheet.createRow(1); - sheet.changeRowNum(row0, 2); - - assertEquals("Row 1 knows its row number", 1, row1.getRowNum()); - assertEquals("Row 2 knows its row number", 2, row0.getRowNum()); - assertEquals("Sheet knows Row 1's row number", 1, sheet.getRowNum(row1)); - assertEquals("Sheet knows Row 2's row number", 2, sheet.getRowNum(row0)); - assertEquals("Sheet row iteratation order should be ascending", row1, sheet.iterator().next()); - - wb.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFSheetAutoSizeColumn.java b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFSheetAutoSizeColumn.java deleted file mode 100644 index 15acbfca0..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFSheetAutoSizeColumn.java +++ /dev/null @@ -1,379 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.streaming; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.junit.Assume.assumeFalse; -import static org.junit.Assume.assumeTrue; - -import java.io.IOException; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.SortedSet; -import java.util.TreeSet; - -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Font; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.SheetUtil; -import org.junit.After; -import org.junit.Assume; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; - - -/** - * Tests the auto-sizing behaviour of {@link SXSSFSheet} when not all - * rows fit into the memory window size etc. - * - * @see Bug #57450 which reported the original mis-behaviour - */ -@RunWith(Parameterized.class) -public class TestSXSSFSheetAutoSizeColumn { - - private static final String SHORT_CELL_VALUE = "Ben"; - private static final String LONG_CELL_VALUE = "B Be Ben Beni Benif Benify Benif Beni Ben Be B"; - - // Approximative threshold to decide whether test is PASS or FAIL: - // shortCellValue ends up with approx column width 1_000 (on my machine), - // longCellValue ends up with approx. column width 10_000 (on my machine) - // so shortCellValue can be expected to be < 5000 for all fonts - // and longCellValue can be expected to be > 5000 for all fonts - private static final int COLUMN_WIDTH_THRESHOLD_BETWEEN_SHORT_AND_LONG = 4000; - private static final int MAX_COLUMN_WIDTH = 255*256; - - private static final SortedSet columns; - static { - SortedSet_columns = new TreeSet(); - _columns.add(0); - _columns.add(1); - _columns.add(3); - columns = Collections.unmodifiableSortedSet(_columns); - } - - - private SXSSFSheet sheet; - private SXSSFWorkbook workbook; - - @Parameter(0) - public boolean useMergedCells; - - @Parameters(name="{index}: useMergedCells={0}") - public static Collection data() { - return Arrays.asList(new Object[][] { - {false}, - {true}, - }); - } - - @After - public void tearDownSheetAndWorkbook() throws IOException { - if (sheet != null) { - sheet.dispose(); - } - if (workbook != null) { - workbook.close(); - } - } - - @Test - public void test_EmptySheet_NoException() { - workbook = new SXSSFWorkbook(); - sheet = workbook.createSheet(); - sheet.trackAllColumnsForAutoSizing(); - - for (int i = 0; i < 10; i++) { - sheet.autoSizeColumn(i, useMergedCells); - } - } - - @Test - public void test_WindowSizeDefault_AllRowsFitIntoWindowSize() { - workbook = new SXSSFWorkbook(); - sheet = workbook.createSheet(); - sheet.trackAllColumnsForAutoSizing(); - - final Cell cellRow0 = createRowWithCellValues(sheet, 0, LONG_CELL_VALUE); - - assumeRequiredFontsAreInstalled(workbook, cellRow0); - - createRowWithCellValues(sheet, 1, SHORT_CELL_VALUE); - - sheet.autoSizeColumn(0, useMergedCells); - - assertColumnWidthStrictlyWithinRange(sheet.getColumnWidth(0), COLUMN_WIDTH_THRESHOLD_BETWEEN_SHORT_AND_LONG, MAX_COLUMN_WIDTH); - } - - @Test - public void test_WindowSizeEqualsOne_ConsiderFlushedRows() { - workbook = new SXSSFWorkbook(null, 1); // Window size 1 so only last row will be in memory - sheet = workbook.createSheet(); - sheet.trackAllColumnsForAutoSizing(); - - final Cell cellRow0 = createRowWithCellValues(sheet, 0, LONG_CELL_VALUE); - - assumeRequiredFontsAreInstalled(workbook, cellRow0); - - createRowWithCellValues(sheet, 1, SHORT_CELL_VALUE); - - sheet.autoSizeColumn(0, useMergedCells); - - assertColumnWidthStrictlyWithinRange(sheet.getColumnWidth(0), COLUMN_WIDTH_THRESHOLD_BETWEEN_SHORT_AND_LONG, MAX_COLUMN_WIDTH); - } - - @Test - public void test_WindowSizeEqualsOne_lastRowIsNotWidest() { - workbook = new SXSSFWorkbook(null, 1); // Window size 1 so only last row will be in memory - sheet = workbook.createSheet(); - sheet.trackAllColumnsForAutoSizing(); - - final Cell cellRow0 = createRowWithCellValues(sheet, 0, LONG_CELL_VALUE); - - assumeRequiredFontsAreInstalled(workbook, cellRow0); - - createRowWithCellValues(sheet, 1, SHORT_CELL_VALUE); - - sheet.autoSizeColumn(0, useMergedCells); - - assertColumnWidthStrictlyWithinRange(sheet.getColumnWidth(0), COLUMN_WIDTH_THRESHOLD_BETWEEN_SHORT_AND_LONG, MAX_COLUMN_WIDTH); - } - - @Test - public void test_WindowSizeEqualsOne_lastRowIsWidest() { - workbook = new SXSSFWorkbook(null, 1); // Window size 1 so only last row will be in memory - sheet = workbook.createSheet(); - sheet.trackAllColumnsForAutoSizing(); - - final Cell cellRow0 = createRowWithCellValues(sheet, 0, SHORT_CELL_VALUE); - - assumeRequiredFontsAreInstalled(workbook, cellRow0); - - createRowWithCellValues(sheet, 1, LONG_CELL_VALUE); - - sheet.autoSizeColumn(0, useMergedCells); - - assertColumnWidthStrictlyWithinRange(sheet.getColumnWidth(0), COLUMN_WIDTH_THRESHOLD_BETWEEN_SHORT_AND_LONG, MAX_COLUMN_WIDTH); - } - - // fails only for useMergedCell=true - @Test - public void test_WindowSizeEqualsOne_flushedRowHasMergedCell() { - workbook = new SXSSFWorkbook(null, 1); // Window size 1 so only last row will be in memory - sheet = workbook.createSheet(); - sheet.trackAllColumnsForAutoSizing(); - - Cell a1 = createRowWithCellValues(sheet, 0, LONG_CELL_VALUE); - - assumeRequiredFontsAreInstalled(workbook, a1); - sheet.addMergedRegion(CellRangeAddress.valueOf("A1:B1")); - - createRowWithCellValues(sheet, 1, SHORT_CELL_VALUE, SHORT_CELL_VALUE); - - /** - * A B - * 1 LONGMERGED - * 2 SHORT SHORT - */ - - sheet.autoSizeColumn(0, useMergedCells); - sheet.autoSizeColumn(1, useMergedCells); - - if (useMergedCells) { - // Excel and LibreOffice behavior: ignore merged cells for auto-sizing. - // POI behavior: evenly distribute the column width among the merged columns. - // each column must be auto-sized in order for the column widths - // to add up to the best fit width. - final int colspan = 2; - final int expectedWidth = (10000 + 1000)/colspan; //average of 1_000 and 10_000 - final int minExpectedWidth = expectedWidth / 2; - final int maxExpectedWidth = expectedWidth * 3 / 2; - assertColumnWidthStrictlyWithinRange(sheet.getColumnWidth(0), minExpectedWidth, maxExpectedWidth); //short - } else { - assertColumnWidthStrictlyWithinRange(sheet.getColumnWidth(0), COLUMN_WIDTH_THRESHOLD_BETWEEN_SHORT_AND_LONG, MAX_COLUMN_WIDTH); //long - } - assertColumnWidthStrictlyWithinRange(sheet.getColumnWidth(1), 0, COLUMN_WIDTH_THRESHOLD_BETWEEN_SHORT_AND_LONG); //short - } - - @Test - public void autoSizeColumn_trackColumnForAutoSizing() { - workbook = new SXSSFWorkbook(); - sheet = workbook.createSheet(); - sheet.trackColumnForAutoSizing(0); - - SortedSet expected = new TreeSet(); - expected.add(0); - assertEquals(expected, sheet.getTrackedColumnsForAutoSizing()); - - sheet.autoSizeColumn(0, useMergedCells); - try { - sheet.autoSizeColumn(1, useMergedCells); - fail("Should not be able to auto-size an untracked column"); - } - catch (final IllegalStateException e) { - // expected - } - } - - @Test - public void autoSizeColumn_trackColumnsForAutoSizing() { - workbook = new SXSSFWorkbook(); - sheet = workbook.createSheet(); - - sheet.trackColumnsForAutoSizing(columns); - SortedSet sorted = new TreeSet(columns); - assertEquals(sorted, sheet.getTrackedColumnsForAutoSizing()); - - sheet.autoSizeColumn(sorted.first(), useMergedCells); - try { - assumeFalse(columns.contains(5)); - sheet.autoSizeColumn(5, useMergedCells); - fail("Should not be able to auto-size an untracked column"); - } - catch (final IllegalStateException e) { - // expected - } - } - - @Test - public void autoSizeColumn_untrackColumnForAutoSizing() { - workbook = new SXSSFWorkbook(); - sheet = workbook.createSheet(); - - sheet.trackColumnsForAutoSizing(columns); - sheet.untrackColumnForAutoSizing(columns.first()); - - assumeTrue(sheet.getTrackedColumnsForAutoSizing().contains(columns.last())); - sheet.autoSizeColumn(columns.last(), useMergedCells); - try { - assumeFalse(sheet.getTrackedColumnsForAutoSizing().contains(columns.first())); - sheet.autoSizeColumn(columns.first(), useMergedCells); - fail("Should not be able to auto-size an untracked column"); - } - catch (final IllegalStateException e) { - // expected - } - } - - @Test - public void autoSizeColumn_untrackColumnsForAutoSizing() { - workbook = new SXSSFWorkbook(); - sheet = workbook.createSheet(); - - sheet.trackColumnForAutoSizing(15); - sheet.trackColumnsForAutoSizing(columns); - sheet.untrackColumnsForAutoSizing(columns); - - assumeTrue(sheet.getTrackedColumnsForAutoSizing().contains(15)); - sheet.autoSizeColumn(15, useMergedCells); - try { - assumeFalse(sheet.getTrackedColumnsForAutoSizing().contains(columns.first())); - sheet.autoSizeColumn(columns.first(), useMergedCells); - fail("Should not be able to auto-size an untracked column"); - } - catch (final IllegalStateException e) { - // expected - } - } - - @Test - public void autoSizeColumn_isColumnTrackedForAutoSizing() { - workbook = new SXSSFWorkbook(); - sheet = workbook.createSheet(); - - sheet.trackColumnsForAutoSizing(columns); - for (int column : columns) { - assertTrue(sheet.isColumnTrackedForAutoSizing(column)); - - assumeFalse(columns.contains(column+10)); - assertFalse(sheet.isColumnTrackedForAutoSizing(column+10)); - } - } - - @Test - public void autoSizeColumn_trackAllColumns() { - workbook = new SXSSFWorkbook(); - sheet = workbook.createSheet(); - - sheet.trackAllColumnsForAutoSizing(); - sheet.autoSizeColumn(0, useMergedCells); - - sheet.untrackAllColumnsForAutoSizing(); - try { - sheet.autoSizeColumn(0, useMergedCells); - fail("Should not be able to auto-size an implicitly untracked column"); - } catch (final IllegalStateException e) { - // expected - } - } - - @Test - public void autoSizeColumn_trackAllColumns_explicitUntrackColumn() { - workbook = new SXSSFWorkbook(); - sheet = workbook.createSheet(); - - sheet.trackColumnsForAutoSizing(columns); - sheet.trackAllColumnsForAutoSizing(); - - sheet.untrackColumnForAutoSizing(0); - try { - sheet.autoSizeColumn(0, useMergedCells); - fail("Should not be able to auto-size an explicitly untracked column"); - } catch (final IllegalStateException e) { - // expected - } - } - - - private static void assumeRequiredFontsAreInstalled(final Workbook workbook, final Cell cell) { - // autoSize will fail if required fonts are not installed, skip this test then - Font font = workbook.getFontAt(cell.getCellStyle().getFontIndex()); - Assume.assumeTrue("Cannot verify autoSizeColumn() because the necessary Fonts are not installed on this machine: " + font, - SheetUtil.canComputeColumnWidth(font)); - } - - private static Cell createRowWithCellValues(final Sheet sheet, final int rowNumber, final String... cellValues) { - Row row = sheet.createRow(rowNumber); - int cellIndex = 0; - Cell firstCell = null; - for (final String cellValue : cellValues) { - Cell cell = row.createCell(cellIndex++); - if (firstCell == null) { - firstCell = cell; - } - cell.setCellValue(cellValue); - } - return firstCell; - } - - private static void assertColumnWidthStrictlyWithinRange(final int actualColumnWidth, final int lowerBoundExclusive, final int upperBoundExclusive) { - assertTrue("Expected a column width greater than " + lowerBoundExclusive + " but found " + actualColumnWidth, - actualColumnWidth > lowerBoundExclusive); - assertTrue("Expected column width less than " + upperBoundExclusive + " but found " + actualColumnWidth, actualColumnWidth < upperBoundExclusive); - - } - -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFWorkbook.java b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFWorkbook.java deleted file mode 100644 index 7b5a67de5..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFWorkbook.java +++ /dev/null @@ -1,578 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xssf.streaming; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Arrays; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.POITestCase; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackageAccess; -import org.apache.poi.ss.usermodel.BaseTestXWorkbook; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.usermodel.WorkbookFactory; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.util.NullOutputStream; -import org.apache.poi.xssf.SXSSFITestDataProvider; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.model.SharedStringsTable; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.After; -import org.junit.Assume; -import org.junit.Ignore; -import org.junit.Test; - -public final class TestSXSSFWorkbook extends BaseTestXWorkbook { - - public TestSXSSFWorkbook() { - super(SXSSFITestDataProvider.instance); - } - - @After - public void tearDown(){ - ((SXSSFITestDataProvider)_testDataProvider).cleanup(); - } - - /** - * cloning of sheets is not supported in SXSSF - */ - @Override - @Test - public void cloneSheet() throws IOException { - try { - super.cloneSheet(); - fail("expected exception"); - } catch (RuntimeException e){ - assertEquals("NotImplemented", e.getMessage()); - } - } - - /** - * cloning of sheets is not supported in SXSSF - */ - @Override - @Test - public void sheetClone() throws IOException { - try { - super.sheetClone(); - fail("expected exception"); - } catch (RuntimeException e){ - assertEquals("NotImplemented", e.getMessage()); - } - } - - /** - * Skip this test, as SXSSF doesn't update formulas on sheet name - * changes. - */ - @Override - @Test - public void setSheetName() { - Assume.assumeTrue("SXSSF doesn't update formulas on sheet name changes, as most cells probably aren't in memory at the time", false); - } - - @Test - public void existingWorkbook() throws IOException { - XSSFWorkbook xssfWb1 = new XSSFWorkbook(); - xssfWb1.createSheet("S1"); - SXSSFWorkbook wb1 = new SXSSFWorkbook(xssfWb1); - XSSFWorkbook xssfWb2 = SXSSFITestDataProvider.instance.writeOutAndReadBack(wb1); - assertTrue(wb1.dispose()); - - SXSSFWorkbook wb2 = new SXSSFWorkbook(xssfWb2); - assertEquals(1, wb2.getNumberOfSheets()); - Sheet sheet = wb2.getSheetAt(0); - assertNotNull(sheet); - assertEquals("S1", sheet.getSheetName()); - assertTrue(wb2.dispose()); - xssfWb2.close(); - xssfWb1.close(); - - wb2.close(); - wb1.close(); - } - - @Test - public void useSharedStringsTable() throws Exception { - SXSSFWorkbook wb = new SXSSFWorkbook(null, 10, false, true); - - SharedStringsTable sss = POITestCase.getFieldValue(SXSSFWorkbook.class, wb, SharedStringsTable.class, "_sharedStringSource"); - - assertNotNull(sss); - - Row row = wb.createSheet("S1").createRow(0); - - row.createCell(0).setCellValue("A"); - row.createCell(1).setCellValue("B"); - row.createCell(2).setCellValue("A"); - - XSSFWorkbook xssfWorkbook = SXSSFITestDataProvider.instance.writeOutAndReadBack(wb); - sss = POITestCase.getFieldValue(SXSSFWorkbook.class, wb, SharedStringsTable.class, "_sharedStringSource"); - assertEquals(2, sss.getUniqueCount()); - assertTrue(wb.dispose()); - - Sheet sheet1 = xssfWorkbook.getSheetAt(0); - assertEquals("S1", sheet1.getSheetName()); - assertEquals(1, sheet1.getPhysicalNumberOfRows()); - row = sheet1.getRow(0); - assertNotNull(row); - Cell cell = row.getCell(0); - assertNotNull(cell); - assertEquals("A", cell.getStringCellValue()); - cell = row.getCell(1); - assertNotNull(cell); - assertEquals("B", cell.getStringCellValue()); - cell = row.getCell(2); - assertNotNull(cell); - assertEquals("A", cell.getStringCellValue()); - - xssfWorkbook.close(); - wb.close(); - } - - @Test - public void addToExistingWorkbook() throws IOException { - XSSFWorkbook xssfWb1 = new XSSFWorkbook(); - xssfWb1.createSheet("S1"); - Sheet sheet = xssfWb1.createSheet("S2"); - Row row = sheet.createRow(1); - Cell cell = row.createCell(1); - cell.setCellValue("value 2_1_1"); - SXSSFWorkbook wb1 = new SXSSFWorkbook(xssfWb1); - XSSFWorkbook xssfWb2 = SXSSFITestDataProvider.instance.writeOutAndReadBack(wb1); - assertTrue(wb1.dispose()); - xssfWb1.close(); - - SXSSFWorkbook wb2 = new SXSSFWorkbook(xssfWb2); - // Add a row to the existing empty sheet - Sheet sheet1 = wb2.getSheetAt(0); - Row row1_1 = sheet1.createRow(1); - Cell cell1_1_1 = row1_1.createCell(1); - cell1_1_1.setCellValue("value 1_1_1"); - - // Add a row to the existing non-empty sheet - Sheet sheet2 = wb2.getSheetAt(1); - Row row2_2 = sheet2.createRow(2); - Cell cell2_2_1 = row2_2.createCell(1); - cell2_2_1.setCellValue("value 2_2_1"); - - // Add a sheet with one row - Sheet sheet3 = wb2.createSheet("S3"); - Row row3_1 = sheet3.createRow(1); - Cell cell3_1_1 = row3_1.createCell(1); - cell3_1_1.setCellValue("value 3_1_1"); - - XSSFWorkbook xssfWb3 = SXSSFITestDataProvider.instance.writeOutAndReadBack(wb2); - wb2.close(); - - assertEquals(3, xssfWb3.getNumberOfSheets()); - // Verify sheet 1 - sheet1 = xssfWb3.getSheetAt(0); - assertEquals("S1", sheet1.getSheetName()); - assertEquals(1, sheet1.getPhysicalNumberOfRows()); - row1_1 = sheet1.getRow(1); - assertNotNull(row1_1); - cell1_1_1 = row1_1.getCell(1); - assertNotNull(cell1_1_1); - assertEquals("value 1_1_1", cell1_1_1.getStringCellValue()); - // Verify sheet 2 - sheet2 = xssfWb3.getSheetAt(1); - assertEquals("S2", sheet2.getSheetName()); - assertEquals(2, sheet2.getPhysicalNumberOfRows()); - Row row2_1 = sheet2.getRow(1); - assertNotNull(row2_1); - Cell cell2_1_1 = row2_1.getCell(1); - assertNotNull(cell2_1_1); - assertEquals("value 2_1_1", cell2_1_1.getStringCellValue()); - row2_2 = sheet2.getRow(2); - assertNotNull(row2_2); - cell2_2_1 = row2_2.getCell(1); - assertNotNull(cell2_2_1); - assertEquals("value 2_2_1", cell2_2_1.getStringCellValue()); - // Verify sheet 3 - sheet3 = xssfWb3.getSheetAt(2); - assertEquals("S3", sheet3.getSheetName()); - assertEquals(1, sheet3.getPhysicalNumberOfRows()); - row3_1 = sheet3.getRow(1); - assertNotNull(row3_1); - cell3_1_1 = row3_1.getCell(1); - assertNotNull(cell3_1_1); - assertEquals("value 3_1_1", cell3_1_1.getStringCellValue()); - - xssfWb2.close(); - xssfWb3.close(); - wb1.close(); - } - - @Test - public void sheetdataWriter() throws IOException{ - SXSSFWorkbook wb = new SXSSFWorkbook(); - SXSSFSheet sh = wb.createSheet(); - SheetDataWriter wr = sh.getSheetDataWriter(); - assertTrue(wr.getClass() == SheetDataWriter.class); - File tmp = wr.getTempFile(); - assertTrue(tmp.getName().startsWith("poi-sxssf-sheet")); - assertTrue(tmp.getName().endsWith(".xml")); - assertTrue(wb.dispose()); - wb.close(); - - wb = new SXSSFWorkbook(); - wb.setCompressTempFiles(true); - sh = wb.createSheet(); - wr = sh.getSheetDataWriter(); - assertTrue(wr.getClass() == GZIPSheetDataWriter.class); - tmp = wr.getTempFile(); - assertTrue(tmp.getName().startsWith("poi-sxssf-sheet-xml")); - assertTrue(tmp.getName().endsWith(".gz")); - assertTrue(wb.dispose()); - wb.close(); - - //Test escaping of Unicode control characters - wb = new SXSSFWorkbook(); - wb.createSheet("S1").createRow(0).createCell(0).setCellValue("value\u0019"); - XSSFWorkbook xssfWorkbook = SXSSFITestDataProvider.instance.writeOutAndReadBack(wb); - Cell cell = xssfWorkbook.getSheet("S1").getRow(0).getCell(0); - assertEquals("value?", cell.getStringCellValue()); - - assertTrue(wb.dispose()); - wb.close(); - xssfWorkbook.close(); - } - - @Test - public void gzipSheetdataWriter() throws IOException { - SXSSFWorkbook wb = new SXSSFWorkbook(); - wb.setCompressTempFiles(true); - int rowNum = 1000; - int sheetNum = 5; - for(int i = 0; i < sheetNum; i++){ - Sheet sh = wb.createSheet("sheet" + i); - for(int j = 0; j < rowNum; j++){ - Row row = sh.createRow(j); - Cell cell1 = row.createCell(0); - cell1.setCellValue(new CellReference(cell1).formatAsString()); - - Cell cell2 = row.createCell(1); - cell2.setCellValue(i); - - Cell cell3 = row.createCell(2); - cell3.setCellValue(j); - } - } - - XSSFWorkbook xwb = SXSSFITestDataProvider.instance.writeOutAndReadBack(wb); - for(int i = 0; i < sheetNum; i++){ - Sheet sh = xwb.getSheetAt(i); - assertEquals("sheet" + i, sh.getSheetName()); - for(int j = 0; j < rowNum; j++){ - Row row = sh.getRow(j); - assertNotNull("row[" + j + "]", row); - Cell cell1 = row.getCell(0); - assertEquals(new CellReference(cell1).formatAsString(), cell1.getStringCellValue()); - - Cell cell2 = row.getCell(1); - assertEquals(i, (int)cell2.getNumericCellValue()); - - Cell cell3 = row.getCell(2); - assertEquals(j, (int)cell3.getNumericCellValue()); - } - } - - assertTrue(wb.dispose()); - xwb.close(); - wb.close(); - } - - protected static void assertWorkbookDispose(SXSSFWorkbook wb) - { - int rowNum = 1000; - int sheetNum = 5; - for(int i = 0; i < sheetNum; i++){ - Sheet sh = wb.createSheet("sheet" + i); - for(int j = 0; j < rowNum; j++){ - Row row = sh.createRow(j); - Cell cell1 = row.createCell(0); - cell1.setCellValue(new CellReference(cell1).formatAsString()); - - Cell cell2 = row.createCell(1); - cell2.setCellValue(i); - - Cell cell3 = row.createCell(2); - cell3.setCellValue(j); - } - } - - for (Sheet sheet : wb) { - SXSSFSheet sxSheet = (SXSSFSheet) sheet; - assertTrue(sxSheet.getSheetDataWriter().getTempFile().exists()); - } - - assertTrue(wb.dispose()); - - for (Sheet sheet : wb) { - SXSSFSheet sxSheet = (SXSSFSheet) sheet; - assertFalse(sxSheet.getSheetDataWriter().getTempFile().exists()); - } - } - - @Test - public void workbookDispose() throws IOException { - SXSSFWorkbook wb1 = new SXSSFWorkbook(); - // the underlying writer is SheetDataWriter - assertWorkbookDispose(wb1); - wb1.close(); - - SXSSFWorkbook wb2 = new SXSSFWorkbook(); - wb2.setCompressTempFiles(true); - // the underlying writer is GZIPSheetDataWriter - assertWorkbookDispose(wb2); - wb2.close(); - } - - @Ignore("currently writing the same sheet multiple times is not supported...") - @Test - public void bug53515() throws Exception { - Workbook wb1 = new SXSSFWorkbook(10); - populateWorkbook(wb1); - saveTwice(wb1); - Workbook wb2 = new XSSFWorkbook(); - populateWorkbook(wb2); - saveTwice(wb2); - wb2.close(); - wb1.close(); - } - - @Ignore("Crashes the JVM because of documented JVM behavior with concurrent writing/reading of zip-files, " - + "see http://www.oracle.com/technetwork/java/javase/documentation/overview-156328.html") - @Test - public void bug53515a() throws Exception { - File out = new File("Test.xlsx"); - out.delete(); - for (int i = 0; i < 2; i++) { - System.out.println("Iteration " + i); - final SXSSFWorkbook wb; - if (out.exists()) { - wb = new SXSSFWorkbook( - (XSSFWorkbook) WorkbookFactory.create(out)); - } else { - wb = new SXSSFWorkbook(10); - } - - try { - FileOutputStream outSteam = new FileOutputStream(out); - if (i == 0) { - populateWorkbook(wb); - } else { - System.gc(); - System.gc(); - System.gc(); - } - - wb.write(outSteam); - // assertTrue(wb.dispose()); - outSteam.close(); - } finally { - assertTrue(wb.dispose()); - } - wb.close(); - } - out.delete(); - } - - private static void populateWorkbook(Workbook wb) { - Sheet sh = wb.createSheet(); - for (int rownum = 0; rownum < 100; rownum++) { - Row row = sh.createRow(rownum); - for (int cellnum = 0; cellnum < 10; cellnum++) { - Cell cell = row.createCell(cellnum); - String address = new CellReference(cell).formatAsString(); - cell.setCellValue(address); - } - } - } - - private static void saveTwice(Workbook wb) throws Exception { - for (int i = 0; i < 2; i++) { - try { - NullOutputStream out = new NullOutputStream(); - wb.write(out); - out.close(); - } catch (Exception e) { - throw new Exception("ERROR: failed on " + (i + 1) - + "th time calling " + wb.getClass().getName() - + ".write() with exception " + e.getMessage(), e); - } - } - } - - @Ignore("Just a local test for http://stackoverflow.com/questions/33627329/apache-poi-streaming-api-using-xssf-template") - @Test - public void testTemplateFile() throws IOException { - XSSFWorkbook workBook = XSSFTestDataSamples.openSampleWorkbook("sample.xlsx"); - SXSSFWorkbook streamingWorkBook = new SXSSFWorkbook(workBook,10); - Sheet sheet = streamingWorkBook.getSheet("Sheet1"); - for(int rowNum = 10;rowNum < 1000000;rowNum++) { - Row row = sheet.createRow(rowNum); - for(int cellNum = 0;cellNum < 700;cellNum++) { - Cell cell = row.createCell(cellNum); - cell.setCellValue("somevalue"); - } - - if(rowNum % 100 == 0) { - System.out.print("."); - if(rowNum % 10000 == 0) { - System.out.println(rowNum); - } - } - } - - FileOutputStream fos = new FileOutputStream("C:\\temp\\streaming.xlsx"); - streamingWorkBook.write(fos); - fos.close(); - - streamingWorkBook.close(); - workBook.close(); - } - - - @Test - public void closeDoesNotModifyWorkbook() throws IOException, InvalidFormatException { - final String filename = "SampleSS.xlsx"; - final File file = POIDataSamples.getSpreadSheetInstance().getFile(filename); - SXSSFWorkbook wb = null; - XSSFWorkbook xwb = null; - - // Some tests commented out because close() modifies the file - // See bug 58779 - - // String - //wb = new SXSSFWorkbook(new XSSFWorkbook(file.getPath())); - //assertCloseDoesNotModifyFile(filename, wb); - - // File - //wb = new SXSSFWorkbook(new XSSFWorkbook(file)); - //assertCloseDoesNotModifyFile(filename, wb); - - // InputStream - FileInputStream fis = new FileInputStream(file); - try { - xwb = new XSSFWorkbook(fis); - wb = new SXSSFWorkbook(xwb); - assertCloseDoesNotModifyFile(filename, wb); - } finally { - if (xwb != null) { - xwb.close(); - } - if (wb != null) { - wb.close(); - } - fis.close(); - } - - // OPCPackage - //wb = new SXSSFWorkbook(new XSSFWorkbook(OPCPackage.open(file))); - //assertCloseDoesNotModifyFile(filename, wb); - } - - /** - * Bug #59743 - * - * this is only triggered on other files apart of sheet[1,2,...].xml - * as those are either copied uncompressed or with the use of GZIPInputStream - * so we use shared strings - */ - @Test - public void testZipBombNotTriggeredOnUselessContent() throws IOException { - SXSSFWorkbook swb = new SXSSFWorkbook(null, 1, true, true); - SXSSFSheet s = swb.createSheet(); - char useless[] = new char[32767]; - Arrays.fill(useless, ' '); - - for (int row=0; row<1; row++) { - Row r = s.createRow(row); - for (int col=0; col<10; col++) { - char prefix[] = Integer.toHexString(row*1000+col).toCharArray(); - Arrays.fill(useless, 0, 10, ' '); - System.arraycopy(prefix, 0, useless, 0, prefix.length); - String ul = new String(useless); - r.createCell(col, CellType.STRING).setCellValue(ul); - ul = null; - } - } - - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - swb.write(bos); - swb.dispose(); - swb.close(); - } - - /** - * To avoid accident changes to the template, you should be able - * to create a SXSSFWorkbook from a read-only XSSF one, then - * change + save that (only). See bug #60010 - * TODO Fix this to work! - */ - @Test - @Ignore - public void createFromReadOnlyWorkbook() throws Exception { - File input = XSSFTestDataSamples.getSampleFile("sample.xlsx"); - OPCPackage pkg = OPCPackage.open(input, PackageAccess.READ); - XSSFWorkbook xssf = new XSSFWorkbook(pkg); - SXSSFWorkbook wb = new SXSSFWorkbook(xssf, 2); - - String sheetName = "Test SXSSF"; - Sheet s = wb.createSheet(sheetName); - for (int i=0; i<10; i++) { - Row r = s.createRow(i); - r.createCell(0).setCellValue(true); - r.createCell(1).setCellValue(2.4); - r.createCell(2).setCellValue("Test Row " + i); - } - assertEquals(10, s.getLastRowNum()); - - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - wb.write(bos); - wb.dispose(); - wb.close(); - - xssf = new XSSFWorkbook(new ByteArrayInputStream(bos.toByteArray())); - s = xssf.getSheet(sheetName); - assertEquals(10, s.getLastRowNum()); - assertEquals(true, s.getRow(0).getCell(0).getBooleanCellValue()); - assertEquals("Test Row 9", s.getRow(9).getCell(2).getStringCellValue()); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFWorkbookWithCustomZipEntrySource.java b/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFWorkbookWithCustomZipEntrySource.java deleted file mode 100644 index b477c8b10..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFWorkbookWithCustomZipEntrySource.java +++ /dev/null @@ -1,136 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xssf.streaming; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.Charset; -import java.security.GeneralSecurityException; -import java.util.List; - -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.util.ZipEntrySource; -import org.apache.poi.poifs.crypt.temp.AesZipFileZipEntrySource; -import org.apache.poi.poifs.crypt.temp.EncryptedTempData; -import org.apache.poi.poifs.crypt.temp.SXSSFWorkbookWithCustomZipEntrySource; -import org.apache.poi.util.IOUtils; -import org.apache.poi.xssf.usermodel.XSSFCell; -import org.apache.poi.xssf.usermodel.XSSFRow; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Test; - -/** - * This class tests that an SXSSFWorkbook can be written and read where all temporary disk I/O - * is encrypted, but the final saved workbook is not encrypted - */ -public final class TestSXSSFWorkbookWithCustomZipEntrySource { - - final String sheetName = "TestSheet1"; - final String cellValue = "customZipEntrySource"; - - // write an unencrypted workbook to disk, but any temporary files are encrypted - @Test - public void customZipEntrySource() throws IOException { - SXSSFWorkbookWithCustomZipEntrySource workbook = new SXSSFWorkbookWithCustomZipEntrySource(); - SXSSFSheet sheet1 = workbook.createSheet(sheetName); - SXSSFRow row1 = sheet1.createRow(1); - SXSSFCell cell1 = row1.createCell(1); - cell1.setCellValue(cellValue); - ByteArrayOutputStream os = new ByteArrayOutputStream(8192); - workbook.write(os); - workbook.close(); - workbook.dispose(); - XSSFWorkbook xwb = new XSSFWorkbook(new ByteArrayInputStream(os.toByteArray())); - XSSFSheet xs1 = xwb.getSheetAt(0); - assertEquals(sheetName, xs1.getSheetName()); - XSSFRow xr1 = xs1.getRow(1); - XSSFCell xc1 = xr1.getCell(1); - assertEquals(cellValue, xc1.getStringCellValue()); - xwb.close(); - } - - // write an encrypted workbook to disk, and encrypt any temporary files as well - @Test - public void customZipEntrySourceForWriteAndRead() throws IOException, GeneralSecurityException, InvalidFormatException { - SXSSFWorkbookWithCustomZipEntrySource workbook = new SXSSFWorkbookWithCustomZipEntrySource(); - SXSSFSheet sheet1 = workbook.createSheet(sheetName); - SXSSFRow row1 = sheet1.createRow(1); - SXSSFCell cell1 = row1.createCell(1); - cell1.setCellValue(cellValue); - EncryptedTempData tempData = new EncryptedTempData(); - workbook.write(tempData.getOutputStream()); - workbook.close(); - workbook.dispose(); - ZipEntrySource zipEntrySource = AesZipFileZipEntrySource.createZipEntrySource(tempData.getInputStream()); - tempData.dispose(); - OPCPackage opc = OPCPackage.open(zipEntrySource); - XSSFWorkbook xwb = new XSSFWorkbook(opc); - zipEntrySource.close(); - XSSFSheet xs1 = xwb.getSheetAt(0); - assertEquals(sheetName, xs1.getSheetName()); - XSSFRow xr1 = xs1.getRow(1); - XSSFCell xc1 = xr1.getCell(1); - assertEquals(cellValue, xc1.getStringCellValue()); - xwb.close(); - opc.close(); - } - - // Java 7 and above: - // import static java.nio.charset.StandardCharsets.UTF_8; - // Java 6 and below: - private static final Charset UTF_8 = Charset.forName("UTF-8"); - - @Test - public void validateTempFilesAreEncrypted() throws IOException { - TempFileRecordingSXSSFWorkbookWithCustomZipEntrySource workbook = new TempFileRecordingSXSSFWorkbookWithCustomZipEntrySource(); - SXSSFSheet sheet1 = workbook.createSheet(sheetName); - SXSSFRow row1 = sheet1.createRow(1); - SXSSFCell cell1 = row1.createCell(1); - cell1.setCellValue(cellValue); - ByteArrayOutputStream os = new ByteArrayOutputStream(8192); - workbook.write(os); - workbook.close(); - List tempFiles = workbook.getTempFiles(); - assertEquals(1, tempFiles.size()); - File tempFile = tempFiles.get(0); - assertTrue("tempFile exists?", tempFile.exists()); - InputStream stream = new FileInputStream(tempFile); - try { - byte[] data = IOUtils.toByteArray(stream); - String text = new String(data, UTF_8); - assertFalse(text.contains(sheetName)); - assertFalse(text.contains(cellValue)); - } finally { - stream.close(); - } - workbook.dispose(); - assertFalse("tempFile deleted after dispose?", tempFile.exists()); - } -} \ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/AllXSSFUsermodelTests.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/AllXSSFUsermodelTests.java deleted file mode 100644 index 6ecad0a74..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/AllXSSFUsermodelTests.java +++ /dev/null @@ -1,66 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import org.apache.poi.ss.formula.eval.forked.TestForkedEvaluator; -import org.apache.poi.xssf.usermodel.extensions.TestXSSFBorder; -import org.apache.poi.xssf.usermodel.extensions.TestXSSFCellFill; -import org.apache.poi.xssf.usermodel.extensions.TestXSSFSheetComments; -import org.apache.poi.xssf.usermodel.helpers.TestColumnHelper; -import org.apache.poi.xssf.usermodel.helpers.TestHeaderFooterHelper; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -/** - * Collects all tests for org.apache.poi.xssf.usermodel and sub-packages. - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestFormulaEvaluatorOnXSSF.class, - TestMultiSheetFormulaEvaluatorOnXSSF.class, - TestSheetHiding.class, - TestXSSFBugs.class, - TestXSSFDataFormat.class, - TestXSSFCellStyle.class, - TestXSSFComment.class, - TestXSSFDialogSheet.class, - TestXSSFDrawing.class, - TestXSSFFont.class, - TestXSSFFormulaEvaluation.class, - TestXSSFHeaderFooter.class, - TestXSSFHyperlink.class, - TestXSSFName.class, - TestXSSFPicture.class, - TestXSSFPictureData.class, - TestXSSFPrintSetup.class, - TestXSSFRichTextString.class, - TestXSSFRow.class, - TestXSSFSheet.class, - TestXSSFSheetUpdateArrayFormulas.class, - TestXSSFTable.class, - TestXSSFWorkbook.class, - TestXSSFBorder.class, - TestXSSFCellFill.class, - TestXSSFSheetComments.class, - TestColumnHelper.class, - TestHeaderFooterHelper.class, - //TestXSSFPivotTable.class, //converted to junit4 - TestForkedEvaluator.class -}) -public final class AllXSSFUsermodelTests { -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/BaseTestXSSFPivotTable.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/BaseTestXSSFPivotTable.java deleted file mode 100644 index 445812566..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/BaseTestXSSFPivotTable.java +++ /dev/null @@ -1,299 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel; - -import static org.junit.Assert.*; - -import java.io.IOException; - -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.DataConsolidateFunction; -import org.apache.poi.ss.util.AreaReference; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.xssf.XSSFITestDataProvider; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPageField; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPageFields; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPivotFields; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPivotTableDefinition; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STDataConsolidateFunction; - -public abstract class BaseTestXSSFPivotTable { - private static final XSSFITestDataProvider _testDataProvider = XSSFITestDataProvider.instance; - protected XSSFWorkbook wb; - protected XSSFPivotTable pivotTable; - protected XSSFPivotTable offsetPivotTable; - protected Cell offsetOuterCell; - - /** - * required to set up the test pivot tables and cell reference, either by name or reference. - * @see junit.framework.TestCase#setUp() - */ - @Before - public abstract void setUp(); - - @After - public void tearDown() throws IOException { - if (wb != null) { - XSSFWorkbook wb2 = _testDataProvider.writeOutAndReadBack(wb); - wb.close(); - wb2.close(); - } - } - - /** - * Verify that when creating a row label it's created on the correct row - * and the count is increased by one. - */ - @Test - public void testAddRowLabelToPivotTable() { - int columnIndex = 0; - - assertEquals(0, pivotTable.getRowLabelColumns().size()); - - pivotTable.addRowLabel(columnIndex); - CTPivotTableDefinition defintion = pivotTable.getCTPivotTableDefinition(); - - assertEquals(defintion.getRowFields().getFieldArray(0).getX(), columnIndex); - assertEquals(defintion.getRowFields().getCount(), 1); - assertEquals(1, pivotTable.getRowLabelColumns().size()); - - columnIndex = 1; - pivotTable.addRowLabel(columnIndex); - assertEquals(2, pivotTable.getRowLabelColumns().size()); - - assertEquals(0, (int)pivotTable.getRowLabelColumns().get(0)); - assertEquals(1, (int)pivotTable.getRowLabelColumns().get(1)); - } - - /** - * Verify that it's not possible to create a row label outside of the referenced area. - */ - @Test - public void testAddRowLabelOutOfRangeThrowsException() { - int columnIndex = 5; - - try { - pivotTable.addRowLabel(columnIndex); - } catch(IndexOutOfBoundsException e) { - return; - } - fail(); - } - - /** - * Verify that when creating one column label, no col fields are being created. - */ - @Test - public void testAddOneColumnLabelToPivotTableDoesNotCreateColField() { - int columnIndex = 0; - - pivotTable.addColumnLabel(DataConsolidateFunction.SUM, columnIndex); - CTPivotTableDefinition defintion = pivotTable.getCTPivotTableDefinition(); - - assertEquals(defintion.getColFields(), null); - } - - /** - * Verify that it's possible to create three column labels with different DataConsolidateFunction - */ - @Test - public void testAddThreeDifferentColumnLabelsToPivotTable() { - int columnOne = 0; - int columnTwo = 1; - int columnThree = 2; - - pivotTable.addColumnLabel(DataConsolidateFunction.SUM, columnOne); - pivotTable.addColumnLabel(DataConsolidateFunction.MAX, columnTwo); - pivotTable.addColumnLabel(DataConsolidateFunction.MIN, columnThree); - CTPivotTableDefinition defintion = pivotTable.getCTPivotTableDefinition(); - - assertEquals(defintion.getDataFields().getDataFieldList().size(), 3); - } - - - /** - * Verify that it's possible to create three column labels with the same DataConsolidateFunction - */ - @Test - public void testAddThreeSametColumnLabelsToPivotTable() { - int columnOne = 0; - int columnTwo = 1; - int columnThree = 2; - - pivotTable.addColumnLabel(DataConsolidateFunction.SUM, columnOne); - pivotTable.addColumnLabel(DataConsolidateFunction.SUM, columnTwo); - pivotTable.addColumnLabel(DataConsolidateFunction.SUM, columnThree); - CTPivotTableDefinition defintion = pivotTable.getCTPivotTableDefinition(); - - assertEquals(defintion.getDataFields().getDataFieldList().size(), 3); - } - - /** - * Verify that when creating two column labels, a col field is being created and X is set to -2. - */ - @Test - public void testAddTwoColumnLabelsToPivotTable() { - int columnOne = 0; - int columnTwo = 1; - - pivotTable.addColumnLabel(DataConsolidateFunction.SUM, columnOne); - pivotTable.addColumnLabel(DataConsolidateFunction.SUM, columnTwo); - CTPivotTableDefinition defintion = pivotTable.getCTPivotTableDefinition(); - - assertEquals(defintion.getColFields().getFieldArray(0).getX(), -2); - } - - /** - * Verify that a data field is created when creating a data column - */ - @Test - public void testColumnLabelCreatesDataField() { - int columnIndex = 0; - - pivotTable.addColumnLabel(DataConsolidateFunction.SUM, columnIndex); - - CTPivotTableDefinition defintion = pivotTable.getCTPivotTableDefinition(); - - assertEquals(defintion.getDataFields().getDataFieldArray(0).getFld(), columnIndex); - assertEquals(defintion.getDataFields().getDataFieldArray(0).getSubtotal(), - STDataConsolidateFunction.Enum.forInt(DataConsolidateFunction.SUM.getValue())); - } - - /** - * Verify that it's possible to set a custom name when creating a data column - */ - @Test - public void testColumnLabelSetCustomName() { - int columnIndex = 0; - - String customName = "Custom Name"; - - pivotTable.addColumnLabel(DataConsolidateFunction.SUM, columnIndex, customName); - - CTPivotTableDefinition defintion = pivotTable.getCTPivotTableDefinition(); - - assertEquals(defintion.getDataFields().getDataFieldArray(0).getFld(), columnIndex); - assertEquals(defintion.getDataFields().getDataFieldArray(0).getName(), customName); - } - - /** - * Verify that it's not possible to create a column label outside of the referenced area. - */ - @Test - public void testAddColumnLabelOutOfRangeThrowsException() { - int columnIndex = 5; - - try { - pivotTable.addColumnLabel(DataConsolidateFunction.SUM, columnIndex); - } catch(IndexOutOfBoundsException e) { - return; - } - fail(); - } - - /** - * Verify when creating a data column set to a data field, the data field with the corresponding - * column index will be set to true. - */ - @Test - public void testAddDataColumn() { - int columnIndex = 0; - boolean isDataField = true; - - pivotTable.addDataColumn(columnIndex, isDataField); - CTPivotFields pivotFields = pivotTable.getCTPivotTableDefinition().getPivotFields(); - assertEquals(pivotFields.getPivotFieldArray(columnIndex).getDataField(), isDataField); - } - - /** - * Verify that it's not possible to create a data column outside of the referenced area. - */ - @Test - public void testAddDataColumnOutOfRangeThrowsException() { - int columnIndex = 5; - boolean isDataField = true; - - try { - pivotTable.addDataColumn(columnIndex, isDataField); - } catch(IndexOutOfBoundsException e) { - return; - } - fail(); - } - - /** - * Verify that it's possible to create a new filter - */ - @Test - public void testAddReportFilter() { - int columnIndex = 0; - - pivotTable.addReportFilter(columnIndex); - CTPageFields fields = pivotTable.getCTPivotTableDefinition().getPageFields(); - CTPageField field = fields.getPageFieldArray(0); - assertEquals(field.getFld(), columnIndex); - assertEquals(field.getHier(), -1); - assertEquals(fields.getCount(), 1); - } - - /** - * Verify that it's not possible to create a new filter outside of the referenced area. - */ - @Test - public void testAddReportFilterOutOfRangeThrowsException() { - int columnIndex = 5; - try { - pivotTable.addReportFilter(columnIndex); - } catch(IndexOutOfBoundsException e) { - return; - } - fail(); - } - - /** - * Verify that the Pivot Table operates only within the referenced area, even when the - * first column of the referenced area is not index 0. - */ - @Test - public void testAddDataColumnWithOffsetData() { - offsetPivotTable.addColumnLabel(DataConsolidateFunction.SUM, 1); - assertEquals(CellType.NUMERIC, offsetOuterCell.getCellTypeEnum()); - - offsetPivotTable.addColumnLabel(DataConsolidateFunction.SUM, 0); - } - - @Test - public void testPivotTableSheetNamesAreCaseInsensitive() { - wb.setSheetName(0, "original"); - wb.setSheetName(1, "offset"); - XSSFSheet original = wb.getSheet("OriginaL"); - XSSFSheet offset = wb.getSheet("OffseT"); - // assume sheets are accessible via case-insensitive name - assertNotNull(original); - assertNotNull(offset); - - AreaReference source = new AreaReference("ORIGinal!A1:C2", _testDataProvider.getSpreadsheetVersion()); - // create a pivot table on the same sheet, case insensitive - original.createPivotTable(source, new CellReference("W1")); - // create a pivot table on a different sheet, case insensitive - offset.createPivotTable(source, new CellReference("W1")); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestFormulaEvaluatorOnXSSF.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestFormulaEvaluatorOnXSSF.java deleted file mode 100644 index ad8b49028..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestFormulaEvaluatorOnXSSF.java +++ /dev/null @@ -1,277 +0,0 @@ -/* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -package org.apache.poi.xssf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; -import static org.junit.Assume.assumeFalse; -import static org.junit.Assume.assumeNotNull; -import static org.junit.Assume.assumeTrue; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Locale; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackageAccess; -import org.apache.poi.ss.formula.eval.TestFormulasFromSpreadsheet; -import org.apache.poi.ss.formula.functions.TestMathX; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.util.LocaleUtil; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.junit.AfterClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; - -/** - * Performs much the same role as {@link TestFormulasFromSpreadsheet}, - * except for a XSSF spreadsheet, not a HSSF one. - * This allows us to check that all our Formula Evaluation code - * is able to work for XSSF, as well as for HSSF. - * - * Periodically, you should open FormulaEvalTestData.xls in - * Excel 2007, and re-save it as FormulaEvalTestData_Copy.xlsx - * - */ -@RunWith(Parameterized.class) -public final class TestFormulaEvaluatorOnXSSF { - private static final POILogger logger = POILogFactory.getLogger(TestFormulaEvaluatorOnXSSF.class); - - private static XSSFWorkbook workbook; - private static Sheet sheet; - private static FormulaEvaluator evaluator; - private static Locale userLocale; - - /** - * This class defines constants for navigating around the test data spreadsheet used for these tests. - */ - private static interface SS { - - /** - * Name of the test spreadsheet (found in the standard test data folder) - */ - String FILENAME = "FormulaEvalTestData_Copy.xlsx"; - /** - * Row (zero-based) in the test spreadsheet where the operator examples start. - */ - int START_OPERATORS_ROW_INDEX = 22; // Row '23' - /** - * Row (zero-based) in the test spreadsheet where the function examples start. - */ - int START_FUNCTIONS_ROW_INDEX = 95; // Row '96' - /** - * Index of the column that contains the function names - */ - int COLUMN_INDEX_FUNCTION_NAME = 1; // Column 'B' - - /** - * Used to indicate when there are no more functions left - */ - String FUNCTION_NAMES_END_SENTINEL = ""; - - /** - * Index of the column where the test values start (for each function) - */ - short COLUMN_INDEX_FIRST_TEST_VALUE = 3; // Column 'D' - - /** - * Each function takes 4 rows in the test spreadsheet - */ - int NUMBER_OF_ROWS_PER_FUNCTION = 4; - } - - @Parameter(value = 0) - public String targetFunctionName; - @Parameter(value = 1) - public int formulasRowIdx; - @Parameter(value = 2) - public int expectedValuesRowIdx; - - @AfterClass - public static void closeResource() throws Exception { - LocaleUtil.setUserLocale(userLocale); - workbook.close(); - } - - @Parameters(name="{0}") - public static Collection data() throws Exception { - // Function "Text" uses custom-formats which are locale specific - // can't set the locale on a per-testrun execution, as some settings have been - // already set, when we would try to change the locale by then - userLocale = LocaleUtil.getUserLocale(); - LocaleUtil.setUserLocale(Locale.ROOT); - - workbook = new XSSFWorkbook( OPCPackage.open(HSSFTestDataSamples.getSampleFile(SS.FILENAME), PackageAccess.READ) ); - sheet = workbook.getSheetAt( 0 ); - evaluator = new XSSFFormulaEvaluator(workbook); - - List data = new ArrayList(); - - processFunctionGroup(data, SS.START_OPERATORS_ROW_INDEX, null); - processFunctionGroup(data, SS.START_FUNCTIONS_ROW_INDEX, null); - // example for debugging individual functions/operators: - // processFunctionGroup(data, SS.START_OPERATORS_ROW_INDEX, "ConcatEval"); - // processFunctionGroup(data, SS.START_FUNCTIONS_ROW_INDEX, "Text"); - - return data; - } - - /** - * @param startRowIndex row index in the spreadsheet where the first function/operator is found - * @param testFocusFunctionName name of a single function/operator to test alone. - * Typically pass null to test all functions - */ - private static void processFunctionGroup(List data, int startRowIndex, String testFocusFunctionName) { - for (int rowIndex = startRowIndex; true; rowIndex += SS.NUMBER_OF_ROWS_PER_FUNCTION) { - Row r = sheet.getRow(rowIndex); - - // only evaluate non empty row - if(r == null) continue; - - String targetFunctionName = getTargetFunctionName(r); - assertNotNull("Test spreadsheet cell empty on row (" - + (rowIndex+1) + "). Expected function name or '" - + SS.FUNCTION_NAMES_END_SENTINEL + "'", targetFunctionName); - - if(targetFunctionName.equals(SS.FUNCTION_NAMES_END_SENTINEL)) { - // found end of functions list - break; - } - if(testFocusFunctionName == null || targetFunctionName.equalsIgnoreCase(testFocusFunctionName)) { - - // expected results are on the row below - Row expectedValuesRow = sheet.getRow(rowIndex + 1); - // +1 for 1-based, +1 for next row - assertNotNull("Missing expected values row for function '" - + targetFunctionName + " (row " + rowIndex + 2 + ")" - , expectedValuesRow); - - data.add(new Object[]{targetFunctionName, rowIndex, rowIndex + 1}); - } - } - } - - - @Test - public void processFunctionRow() { - Row formulasRow = sheet.getRow(formulasRowIdx); - Row expectedValuesRow = sheet.getRow(expectedValuesRowIdx); - - short endcolnum = formulasRow.getLastCellNum(); - - // iterate across the row for all the evaluation cases - for (short colnum=SS.COLUMN_INDEX_FIRST_TEST_VALUE; colnum < endcolnum; colnum++) { - Cell c = formulasRow.getCell(colnum); - assumeNotNull(c); - assumeTrue(c.getCellTypeEnum() == CellType.FORMULA); - ignoredFormulaTestCase(c.getCellFormula()); - - CellValue actValue = evaluator.evaluate(c); - Cell expValue = (expectedValuesRow == null) ? null : expectedValuesRow.getCell(colnum); - - String msg = String.format(Locale.ROOT, "Function '%s': Formula: %s @ %d:%d" - , targetFunctionName, c.getCellFormula(), formulasRow.getRowNum(), colnum); - - assertNotNull(msg + " - Bad setup data expected value is null", expValue); - assertNotNull(msg + " - actual value was null", actValue); - - final CellType expectedCellType = expValue.getCellTypeEnum(); - switch (expectedCellType) { - case BLANK: - assertEquals(msg, CellType.BLANK, actValue.getCellTypeEnum()); - break; - case BOOLEAN: - assertEquals(msg, CellType.BOOLEAN, actValue.getCellTypeEnum()); - assertEquals(msg, expValue.getBooleanCellValue(), actValue.getBooleanValue()); - break; - case ERROR: - assertEquals(msg, CellType.ERROR, actValue.getCellTypeEnum()); -// if(false) { // TODO: fix ~45 functions which are currently returning incorrect error values -// assertEquals(msg, expValue.getErrorCellValue(), actValue.getErrorValue()); -// } - break; - case FORMULA: // will never be used, since we will call method after formula evaluation - fail("Cannot expect formula as result of formula evaluation: " + msg); - case NUMERIC: - assertEquals(msg, CellType.NUMERIC, actValue.getCellTypeEnum()); - TestMathX.assertEquals(msg, expValue.getNumericCellValue(), actValue.getNumberValue(), TestMathX.POS_ZERO, TestMathX.DIFF_TOLERANCE_FACTOR); -// double delta = Math.abs(expValue.getNumericCellValue()-actValue.getNumberValue()); -// double pctExpValue = Math.abs(0.00001*expValue.getNumericCellValue()); -// assertTrue(msg, delta <= pctExpValue); - break; - case STRING: - assertEquals(msg, CellType.STRING, actValue.getCellTypeEnum()); - assertEquals(msg, expValue.getRichStringCellValue().getString(), actValue.getStringValue()); - break; - default: - fail("Unexpected cell type: " + expectedCellType); - } - } - } - - /* - * TODO - these are all formulas which currently (Apr-2008) break on ooxml - */ - private static void ignoredFormulaTestCase(String cellFormula) { - // full row ranges are not parsed properly yet. - // These cases currently work in svn trunk because of another bug which causes the - // formula to get rendered as COLUMN($A$1:$IV$2) or ROW($A$2:$IV$3) - assumeFalse("COLUMN(1:2)".equals(cellFormula)); - assumeFalse("ROW(2:3)".equals(cellFormula)); - - // currently throws NPE because unknown function "currentcell" causes name lookup - // Name lookup requires some equivalent object of the Workbook within xSSFWorkbook. - assumeFalse("ISREF(currentcell())".equals(cellFormula)); - } - - /** - * @return null if cell is missing, empty or blank - */ - private static String getTargetFunctionName(Row r) { - if(r == null) { - logger.log(POILogger.WARN, "Warning - given null row, can't figure out function name"); - return null; - } - Cell cell = r.getCell(SS.COLUMN_INDEX_FUNCTION_NAME); - if(cell == null) { - logger.log(POILogger.WARN, "Warning - Row " + r.getRowNum() + " has no cell " + SS.COLUMN_INDEX_FUNCTION_NAME + ", can't figure out function name"); - return null; - } - if(cell.getCellTypeEnum() == CellType.BLANK) { - return null; - } - if(cell.getCellTypeEnum() == CellType.STRING) { - return cell.getRichStringCellValue().getString(); - } - - fail("Bad cell type for 'function name' column: ("+cell.getColumnIndex()+") row ("+(r.getRowNum()+1)+")"); - return null; - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestMissingWorkbookOnXSSF.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestMissingWorkbookOnXSSF.java deleted file mode 100644 index 2427dd1d8..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestMissingWorkbookOnXSSF.java +++ /dev/null @@ -1,40 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.ss.formula.TestMissingWorkbook; -import org.apache.poi.xssf.XSSFTestDataSamples; - -/** - * XSSF Specific version of the Missing Workbooks test - */ -public final class TestMissingWorkbookOnXSSF extends TestMissingWorkbook { - public TestMissingWorkbookOnXSSF() { - super("52575_main.xlsx", "source_dummy.xlsx", "52575_source.xls"); - } - - @Override - protected void setUp() throws Exception { - mainWorkbook = XSSFTestDataSamples.openSampleWorkbook(MAIN_WORKBOOK_FILENAME); - sourceWorkbook = HSSFTestDataSamples.openSampleWorkbook(SOURCE_WORKBOOK_FILENAME); - - assertNotNull(mainWorkbook); - assertNotNull(sourceWorkbook); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestMultiSheetFormulaEvaluatorOnXSSF.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestMultiSheetFormulaEvaluatorOnXSSF.java deleted file mode 100644 index b8926a3cf..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestMultiSheetFormulaEvaluatorOnXSSF.java +++ /dev/null @@ -1,270 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; -import static org.junit.Assume.assumeNotNull; -import static org.junit.Assume.assumeTrue; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Locale; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackageAccess; -import org.apache.poi.ss.formula.eval.TestFormulasFromSpreadsheet; -import org.apache.poi.ss.formula.functions.TestMathX; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.junit.AfterClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; - -/** - * Tests formulas for multi sheet reference (i.e. SUM(Sheet1:Sheet5!A1)) - */ -@RunWith(Parameterized.class) -public final class TestMultiSheetFormulaEvaluatorOnXSSF { - private static final POILogger logger = POILogFactory.getLogger(TestFormulasFromSpreadsheet.class); - - private static XSSFWorkbook workbook; - private static Sheet sheet; - private static FormulaEvaluator evaluator; - - /** - * This class defines constants for navigating around the test data spreadsheet used for these tests. - */ - interface SS { - - /** - * Name of the test spreadsheet (found in the standard test data folder) - */ - String FILENAME = "FormulaSheetRange.xlsx"; - /** - * Row (zero-based) in the test spreadsheet where the function examples start. - */ - int START_FUNCTIONS_ROW_INDEX = 10; // Row '11' - /** - * Index of the column that contains the function names - */ - int COLUMN_INDEX_FUNCTION_NAME = 0; // Column 'A' - /** - * Index of the column that contains the test names - */ - int COLUMN_INDEX_TEST_NAME = 1; // Column 'B' - /** - * Used to indicate when there are no more functions left - */ - String FUNCTION_NAMES_END_SENTINEL = ""; - - /** - * Index of the column where the test expected value is present - */ - short COLUMN_INDEX_EXPECTED_VALUE = 2; // Column 'C' - /** - * Index of the column where the test actual value is present - */ - short COLUMN_INDEX_ACTUAL_VALUE = 3; // Column 'D' - /** - * Test sheet name (sheet with all test formulae) - */ - String TEST_SHEET_NAME = "test"; - } - - @Parameter(value = 0) - public String targetTestName; - @Parameter(value = 1) - public String targetFunctionName; - @Parameter(value = 2) - public int formulasRowIdx; - - @AfterClass - public static void closeResource() throws Exception { - workbook.close(); - } - - @Parameters(name="{0}") - public static Collection data() throws Exception { - workbook = new XSSFWorkbook( OPCPackage.open(HSSFTestDataSamples.getSampleFile(SS.FILENAME), PackageAccess.READ) ); - sheet = workbook.getSheet( SS.TEST_SHEET_NAME ); - evaluator = new XSSFFormulaEvaluator(workbook); - - List data = new ArrayList(); - - processFunctionGroup(data, SS.START_FUNCTIONS_ROW_INDEX, null); - - return data; - } - - /** - * @param startRowIndex row index in the spreadsheet where the first function/operator is found - * @param testFocusFunctionName name of a single function/operator to test alone. - * Typically pass null to test all functions - */ - private static void processFunctionGroup(List data, int startRowIndex, String testFocusFunctionName) { - for (int rowIndex = startRowIndex; true; rowIndex++) { - Row r = sheet.getRow(rowIndex); - - // only evaluate non empty row - if(r == null) continue; - - String targetFunctionName = getTargetFunctionName(r); - assertNotNull("Test spreadsheet cell empty on row (" - + (rowIndex+1) + "). Expected function name or '" - + SS.FUNCTION_NAMES_END_SENTINEL + "'", targetFunctionName); - - if(targetFunctionName.equals(SS.FUNCTION_NAMES_END_SENTINEL)) { - // found end of functions list - break; - } - - String targetTestName = getTargetTestName(r); - if(testFocusFunctionName == null || targetFunctionName.equalsIgnoreCase(testFocusFunctionName)) { - - // expected results are on the row below - Cell expectedValueCell = r.getCell(SS.COLUMN_INDEX_EXPECTED_VALUE); - assertNotNull("Missing expected values cell for function '" - + targetFunctionName + ", test" + targetTestName + " (row " + - rowIndex + 1 + ")", expectedValueCell); - - data.add(new Object[]{targetTestName, targetFunctionName, rowIndex}); - } - } - } - - /** - * - * @return a constant from the local Result class denoting whether there were any evaluation - * cases, and whether they all succeeded. - */ - @Test - public void processFunctionRow() { - Row r = sheet.getRow(formulasRowIdx); - - Cell expValue = r.getCell(SS.COLUMN_INDEX_EXPECTED_VALUE); - assertNotNull("Missing expected values cell for function '" - + targetFunctionName + ", test" + targetTestName + " (row " + - formulasRowIdx + 1 + ")", expValue); - - Cell c = r.getCell(SS.COLUMN_INDEX_ACTUAL_VALUE); - assumeNotNull(c); - assumeTrue(c.getCellTypeEnum() == CellType.FORMULA); - - CellValue actValue = evaluator.evaluate(c); - - String msg = String.format(Locale.ROOT, "Function '%s': Test: '%s': Formula: %s @ %d:%d", - targetFunctionName, targetTestName, c.getCellFormula(), formulasRowIdx, SS.COLUMN_INDEX_ACTUAL_VALUE); - - assertNotNull(msg + " - actual value was null", actValue); - - final CellType expectedCellType = expValue.getCellTypeEnum(); - switch (expectedCellType) { - case BLANK: - assertEquals(msg, CellType.BLANK, actValue.getCellTypeEnum()); - break; - case BOOLEAN: - assertEquals(msg, CellType.BOOLEAN, actValue.getCellTypeEnum()); - assertEquals(msg, expValue.getBooleanCellValue(), actValue.getBooleanValue()); - break; - case ERROR: - assertEquals(msg, CellType.ERROR, actValue.getCellTypeEnum()); -// if(false) { // TODO: fix ~45 functions which are currently returning incorrect error values -// assertEquals(msg, expected.getErrorCellValue(), actual.getErrorValue()); -// } - break; - case FORMULA: // will never be used, since we will call method after formula evaluation - fail("Cannot expect formula as result of formula evaluation: " + msg); - case NUMERIC: - assertEquals(msg, CellType.NUMERIC, actValue.getCellTypeEnum()); - TestMathX.assertEquals(msg, expValue.getNumericCellValue(), actValue.getNumberValue(), TestMathX.POS_ZERO, TestMathX.DIFF_TOLERANCE_FACTOR); -// double delta = Math.abs(expected.getNumericCellValue()-actual.getNumberValue()); -// double pctExpected = Math.abs(0.00001*expected.getNumericCellValue()); -// assertTrue(msg, delta <= pctExpected); - break; - case STRING: - assertEquals(msg, CellType.STRING, actValue.getCellTypeEnum()); - assertEquals(msg, expValue.getRichStringCellValue().getString(), actValue.getStringValue()); - break; - default: - fail("Unexpected cell type: " + expectedCellType); - } - } - - /** - * @return null if cell is missing, empty or blank - */ - private static String getTargetFunctionName(Row r) { - if(r == null) { - logger.log(POILogger.WARN, "Warning - given null row, can't figure out function name"); - return null; - } - Cell cell = r.getCell(SS.COLUMN_INDEX_FUNCTION_NAME); - if(cell == null) { - logger.log(POILogger.WARN, "Warning - Row " + r.getRowNum() + " has no cell " + SS.COLUMN_INDEX_FUNCTION_NAME + ", can't figure out function name"); - return null; - } - if(cell.getCellTypeEnum() == CellType.BLANK) { - return null; - } - if(cell.getCellTypeEnum() == CellType.STRING) { - return cell.getRichStringCellValue().getString(); - } - - fail("Bad cell type for 'function name' column: (" - + cell.getCellTypeEnum() + ") row (" + (r.getRowNum() +1) + ")"); - return ""; - } - /** - * @return null if cell is missing, empty or blank - */ - private static String getTargetTestName(Row r) { - if(r == null) { - logger.log(POILogger.WARN, "Warning - given null row, can't figure out test name"); - return null; - } - Cell cell = r.getCell(SS.COLUMN_INDEX_TEST_NAME); - if(cell == null) { - logger.log(POILogger.WARN, "Warning - Row " + r.getRowNum() + " has no cell " + SS.COLUMN_INDEX_TEST_NAME + ", can't figure out test name"); - return null; - } - if(cell.getCellTypeEnum() == CellType.BLANK) { - return null; - } - if(cell.getCellTypeEnum() == CellType.STRING) { - return cell.getRichStringCellValue().getString(); - } - - fail("Bad cell type for 'test name' column: (" - + cell.getCellTypeEnum() + ") row (" + (r.getRowNum() +1) + ")"); - return ""; - } - -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestSXSSFBugs.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestSXSSFBugs.java deleted file mode 100644 index af58706a7..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestSXSSFBugs.java +++ /dev/null @@ -1,103 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import static org.junit.Assert.fail; -import static org.junit.Assert.assertEquals; - -import java.io.IOException; - -import org.apache.poi.ss.usermodel.BaseTestBugzillaIssues; -import org.apache.poi.ss.usermodel.PrintSetup; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.xssf.SXSSFITestDataProvider; -import org.apache.poi.xssf.streaming.SXSSFWorkbook; -import org.junit.Ignore; -import org.junit.Test; - -public final class TestSXSSFBugs extends BaseTestBugzillaIssues { - public TestSXSSFBugs() { - super(SXSSFITestDataProvider.instance); - } - - // override some tests which do not work for SXSSF - @Override @Ignore("cloneSheet() not implemented") @Test public void bug18800() { /* cloneSheet() not implemented */ } - @Override @Ignore("cloneSheet() not implemented") @Test public void bug22720() { /* cloneSheet() not implemented */ } - @Override @Ignore("Evaluation is not fully supported") @Test public void bug47815() { /* Evaluation is not supported */ } - @Override @Ignore("Evaluation is not fully supported") @Test public void test58113() { /* Evaluation is not supported */ } - @Override @Ignore("Evaluation is not fully supported") @Test public void bug46729_testMaxFunctionArguments() { /* Evaluation is not supported */ } - @Override @Ignore("Reading data is not supported") @Test public void bug57798() { /* Reading data is not supported */ } - - /** - * Setting repeating rows and columns shouldn't break - * any print settings that were there before - */ - @Test - public void bug49253() throws Exception { - Workbook wb1 = new SXSSFWorkbook(); - Workbook wb2 = new SXSSFWorkbook(); - CellRangeAddress cra = CellRangeAddress.valueOf("C2:D3"); - - // No print settings before repeating - Sheet s1 = wb1.createSheet(); - s1.setRepeatingColumns(cra); - s1.setRepeatingRows(cra); - - PrintSetup ps1 = s1.getPrintSetup(); - assertEquals(false, ps1.getValidSettings()); - assertEquals(false, ps1.getLandscape()); - - - // Had valid print settings before repeating - Sheet s2 = wb2.createSheet(); - PrintSetup ps2 = s2.getPrintSetup(); - - ps2.setLandscape(false); - assertEquals(true, ps2.getValidSettings()); - assertEquals(false, ps2.getLandscape()); - s2.setRepeatingColumns(cra); - s2.setRepeatingRows(cra); - - ps2 = s2.getPrintSetup(); - assertEquals(true, ps2.getValidSettings()); - assertEquals(false, ps2.getLandscape()); - - wb1.close(); - wb2.close(); - } - - // bug 60197: setSheetOrder should update sheet-scoped named ranges to maintain references to the sheets before the re-order - @Test - @Override - public void bug60197_NamedRangesReferToCorrectSheetWhenSheetOrderIsChanged() throws Exception { - try { - super.bug60197_NamedRangesReferToCorrectSheetWhenSheetOrderIsChanged(); - } catch (final RuntimeException e) { - final Throwable cause = e.getCause(); - if (cause instanceof IOException && cause.getMessage().equals("Stream closed")) { - // expected on the second time that _testDataProvider.writeOutAndReadBack(SXSSFWorkbook) is called - // if the test makes it this far, then we know that XSSFName sheet indices are updated when sheet - // order is changed, which is the purpose of this test. Therefore, consider this a passing test. - } else { - throw e; - } - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestSheetHiding.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestSheetHiding.java deleted file mode 100644 index f6b4e632b..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestSheetHiding.java +++ /dev/null @@ -1,28 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import org.apache.poi.xssf.XSSFITestDataProvider; -import org.apache.poi.ss.usermodel.BaseTestSheetHiding; - -public final class TestSheetHiding extends BaseTestSheetHiding { - public TestSheetHiding() { - super(XSSFITestDataProvider.instance, - "TwoSheetsOneHidden.xlsx", "TwoSheetsNoneHidden.xlsx"); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestUnfixedBugs.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestUnfixedBugs.java deleted file mode 100644 index 0892d1017..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestUnfixedBugs.java +++ /dev/null @@ -1,400 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.nio.charset.Charset; -import java.util.Calendar; -import java.util.Date; -import java.util.Iterator; -import java.util.List; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.DateUtil; -import org.apache.poi.ss.usermodel.RichTextString; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.CellUtil; -import org.apache.poi.ss.util.RegionUtil; -import org.apache.poi.util.LocaleUtil; -import org.apache.poi.xssf.SXSSFITestDataProvider; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.streaming.SXSSFWorkbook; -import org.junit.Test; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRow; - -/** - * @author centic - * - * This testcase contains tests for bugs that are yet to be fixed. Therefore, - * the standard ant test target does not run these tests. Run this testcase with - * the single-test target. The names of the tests usually correspond to the - * Bugzilla id's PLEASE MOVE tests from this class to TestBugs once the bugs are - * fixed, so that they are then run automatically. - */ -public final class TestUnfixedBugs { - @Test - public void testBug54084Unicode() throws IOException { - // sample XLSX with the same text-contents as the text-file above - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("54084 - Greek - beyond BMP.xlsx"); - - verifyBug54084Unicode(wb); - -// OutputStream baos = new FileOutputStream("/tmp/test.xlsx"); -// try { -// wb.write(baos); -// } finally { -// baos.close(); -// } - - // now write the file and read it back in - XSSFWorkbook wbWritten = XSSFTestDataSamples.writeOutAndReadBack(wb); - verifyBug54084Unicode(wbWritten); - - // finally also write it out via the streaming interface and verify that we still can read it back in - SXSSFWorkbook swb = new SXSSFWorkbook(wb); - Workbook wbStreamingWritten = SXSSFITestDataProvider.instance.writeOutAndReadBack(swb); - verifyBug54084Unicode(wbStreamingWritten); - - wbWritten.close(); - swb.close(); - wbStreamingWritten.close(); - wb.close(); - } - - private void verifyBug54084Unicode(Workbook wb) { - // expected data is stored in UTF-8 in a text-file - byte data[] = HSSFTestDataSamples.getTestDataFileContent("54084 - Greek - beyond BMP.txt"); - String testData = new String(data, Charset.forName("UTF-8")).trim(); - - Sheet sheet = wb.getSheetAt(0); - Row row = sheet.getRow(0); - Cell cell = row.getCell(0); - - String value = cell.getStringCellValue(); - //System.out.println(value); - - assertEquals("The data in the text-file should exactly match the data that we read from the workbook", testData, value); - } - - @Test - public void test54071() throws Exception { - Workbook workbook = XSSFTestDataSamples.openSampleWorkbook("54071.xlsx"); - Sheet sheet = workbook.getSheetAt(0); - int rows = sheet.getPhysicalNumberOfRows(); - System.out.println(">> file rows is:"+(rows-1)+" <<"); - Row title = sheet.getRow(0); - - Date prev = null; - for (int row = 1; row < rows; row++) { - Row rowObj = sheet.getRow(row); - for (int col = 0; col < 1; col++) { - String titleName = title.getCell(col).toString(); - Cell cell = rowObj.getCell(col); - if (titleName.startsWith("time")) { - // here the output will produce ...59 or ...58 for the rows, probably POI is - // doing some different rounding or some other small difference... - System.out.println("==Time:"+cell.getDateCellValue()); - if(prev != null) { - assertEquals(prev, cell.getDateCellValue()); - } - - prev = cell.getDateCellValue(); - } - } - } - - workbook.close(); - } - - @Test - public void test54071Simple() { - double value1 = 41224.999988425923; - double value2 = 41224.999988368058; - - int wholeDays1 = (int)Math.floor(value1); - int millisecondsInDay1 = (int)((value1 - wholeDays1) * DateUtil.DAY_MILLISECONDS + 0.5); - - int wholeDays2 = (int)Math.floor(value2); - int millisecondsInDay2 = (int)((value2 - wholeDays2) * DateUtil.DAY_MILLISECONDS + 0.5); - - assertEquals(wholeDays1, wholeDays2); - // here we see that the time-value is 5 milliseconds apart, one is 86399000 and the other is 86398995, - // thus one is one second higher than the other - assertEquals("The time-values are 5 milliseconds apart", - millisecondsInDay1, millisecondsInDay2); - - // when we do the calendar-stuff, there is a boolean which determines if - // the milliseconds are rounded or not, having this at "false" causes the - // second to be different here! - int startYear = 1900; - int dayAdjust = -1; // Excel thinks 2/29/1900 is a valid date, which it isn't - Calendar calendar1 = LocaleUtil.getLocaleCalendar(startYear,0, wholeDays1 + dayAdjust); - calendar1.set(Calendar.MILLISECOND, millisecondsInDay1); - // this is the rounding part: - calendar1.add(Calendar.MILLISECOND, 500); - calendar1.clear(Calendar.MILLISECOND); - - Calendar calendar2 = LocaleUtil.getLocaleCalendar(startYear,0, wholeDays2 + dayAdjust); - calendar2.set(Calendar.MILLISECOND, millisecondsInDay2); - // this is the rounding part: - calendar2.add(Calendar.MILLISECOND, 500); - calendar2.clear(Calendar.MILLISECOND); - - // now the calendars are equal - assertEquals(calendar1, calendar2); - - assertEquals(DateUtil.getJavaDate(value1, false), DateUtil.getJavaDate(value2, false)); - } - - // When this is fixed, the test case should go to BaseTestXCell with - // adjustments to use _testDataProvider to also verify this for XSSF - @Test - public void testBug57294() throws IOException { - Workbook wb = SXSSFITestDataProvider.instance.createWorkbook(); - - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - - RichTextString str = new XSSFRichTextString("Test rich text string"); - str.applyFont(2, 4, (short)0); - assertEquals(3, str.numFormattingRuns()); - cell.setCellValue(str); - - Workbook wbBack = SXSSFITestDataProvider.instance.writeOutAndReadBack(wb); - wb.close(); - - // re-read after serializing and reading back - Cell cellBack = wbBack.getSheetAt(0).getRow(0).getCell(0); - assertNotNull(cellBack); - RichTextString strBack = cellBack.getRichStringCellValue(); - assertNotNull(strBack); - assertEquals(3, strBack.numFormattingRuns()); - assertEquals(0, strBack.getIndexOfFormattingRun(0)); - assertEquals(2, strBack.getIndexOfFormattingRun(1)); - assertEquals(4, strBack.getIndexOfFormattingRun(2)); - - wbBack.close(); - } - - @Test - public void testBug55752() throws IOException { - Workbook wb = new XSSFWorkbook(); - try { - Sheet sheet = wb.createSheet("test"); - - for (int i = 0; i < 4; i++) { - Row row = sheet.createRow(i); - for (int j = 0; j < 2; j++) { - Cell cell = row.createCell(j); - cell.setCellStyle(wb.createCellStyle()); - } - } - - // set content - Row row1 = sheet.getRow(0); - row1.getCell(0).setCellValue("AAA"); - Row row2 = sheet.getRow(1); - row2.getCell(0).setCellValue("BBB"); - Row row3 = sheet.getRow(2); - row3.getCell(0).setCellValue("CCC"); - Row row4 = sheet.getRow(3); - row4.getCell(0).setCellValue("DDD"); - - // merge cells - CellRangeAddress range1 = new CellRangeAddress(0, 0, 0, 1); - sheet.addMergedRegion(range1); - CellRangeAddress range2 = new CellRangeAddress(1, 1, 0, 1); - sheet.addMergedRegion(range2); - CellRangeAddress range3 = new CellRangeAddress(2, 2, 0, 1); - sheet.addMergedRegion(range3); - assertEquals(0, range3.getFirstColumn()); - assertEquals(1, range3.getLastColumn()); - assertEquals(2, range3.getLastRow()); - CellRangeAddress range4 = new CellRangeAddress(3, 3, 0, 1); - sheet.addMergedRegion(range4); - - // set border - RegionUtil.setBorderBottom(CellStyle.BORDER_THIN, range1, sheet, wb); - - row2.getCell(0).getCellStyle().setBorderBottom(CellStyle.BORDER_THIN); - row2.getCell(1).getCellStyle().setBorderBottom(CellStyle.BORDER_THIN); - - Cell cell0 = CellUtil.getCell(row3, 0); - CellUtil.setCellStyleProperty(cell0, CellUtil.BORDER_BOTTOM, CellStyle.BORDER_THIN); - Cell cell1 = CellUtil.getCell(row3, 1); - CellUtil.setCellStyleProperty(cell1, CellUtil.BORDER_BOTTOM, CellStyle.BORDER_THIN); - - RegionUtil.setBorderBottom(CellStyle.BORDER_THIN, range4, sheet, wb); - - // write to file - OutputStream stream = new FileOutputStream(new File("C:/temp/55752.xlsx")); - try { - wb.write(stream); - } finally { - stream.close(); - } - } finally { - wb.close(); - } - } - - @Test - public void test57423() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57423.xlsx"); - - Sheet testSheet = wb.getSheetAt(0); - - // row shift (negative or positive) causes corrupted output xlsx file when the shift value is bigger - // than the number of rows being shifted - // Excel 2010 on opening the output file says: - // "Excel found unreadable content" and offers recovering the file by removing the unreadable content - // This can be observed in cases like the following: - // negative shift of 1 row by less than -1 - // negative shift of 2 rows by less than -2 - // positive shift of 1 row by 2 or more - // positive shift of 2 rows by 3 or more - - //testSheet.shiftRows(4, 5, -3); - testSheet.shiftRows(10, 10, 2); - - checkRows57423(testSheet); - - Workbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb); - - /*FileOutputStream stream = new FileOutputStream("C:\\temp\\57423.xlsx"); - try { - wb.write(stream); - } finally { - stream.close(); - }*/ - - wb.close(); - - checkRows57423(wbBack.getSheetAt(0)); - - wbBack.close(); - } - - private void checkRows57423(Sheet testSheet) throws IOException { - checkRow57423(testSheet, 0, "0"); - checkRow57423(testSheet, 1, "1"); - checkRow57423(testSheet, 2, "2"); - checkRow57423(testSheet, 3, "3"); - checkRow57423(testSheet, 4, "4"); - checkRow57423(testSheet, 5, "5"); - checkRow57423(testSheet, 6, "6"); - checkRow57423(testSheet, 7, "7"); - checkRow57423(testSheet, 8, "8"); - checkRow57423(testSheet, 9, "9"); - - assertNull("Row number 10 should be gone after the shift", - testSheet.getRow(10)); - - checkRow57423(testSheet, 11, "11"); - checkRow57423(testSheet, 12, "10"); - checkRow57423(testSheet, 13, "13"); - checkRow57423(testSheet, 14, "14"); - checkRow57423(testSheet, 15, "15"); - checkRow57423(testSheet, 16, "16"); - checkRow57423(testSheet, 17, "17"); - checkRow57423(testSheet, 18, "18"); - - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - try { - ((XSSFSheet)testSheet).write(stream); - } finally { - stream.close(); - } - - // verify that the resulting XML has the rows in correct order as required by Excel - String xml = new String(stream.toByteArray(), "UTF-8"); - int posR12 = xml.indexOf(" shapes = drawing.getShapes(); - str.append("drawing.getShapes().size() = " + shapes.size()); - Iterator it = shapes.iterator(); - while(it.hasNext()) { - XSSFShape shape = it.next(); - str.append(", " + shape.toString()); - str.append(", Col1:"+((XSSFClientAnchor)shape.getAnchor()).getCol1()); - str.append(", Col2:"+((XSSFClientAnchor)shape.getAnchor()).getCol2()); - str.append(", Row1:"+((XSSFClientAnchor)shape.getAnchor()).getRow1()); - str.append(", Row2:"+((XSSFClientAnchor)shape.getAnchor()).getRow2()); - } - - assertEquals("Having shapes: " + str, - expectedShapes, shapes.size()); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFBugs.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFBugs.java deleted file mode 100644 index decd3b6b3..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFBugs.java +++ /dev/null @@ -1,3197 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.Arrays; -import java.util.Calendar; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TimeZone; -import java.util.TreeMap; - -import org.apache.poi.EncryptedDocumentException; -import org.apache.poi.POIDataSamples; -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.POIXMLDocumentPart.RelationPart; -import org.apache.poi.POIXMLException; -import org.apache.poi.POIXMLProperties; -import org.apache.poi.common.usermodel.HyperlinkType; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.exceptions.InvalidOperationException; -import org.apache.poi.openxml4j.exceptions.OpenXML4JException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackageAccess; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.opc.PackageRelationship; -import org.apache.poi.openxml4j.opc.PackagingURIHelper; -import org.apache.poi.openxml4j.util.ZipSecureFile; -import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.ss.formula.WorkbookEvaluator; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.ss.formula.functions.Function; -import org.apache.poi.ss.usermodel.*; -import org.apache.poi.ss.util.AreaReference; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.ss.util.CellUtil; -import org.apache.poi.util.LocaleUtil; -import org.apache.poi.util.TempFile; -import org.apache.poi.xssf.XLSBUnsupportedException; -import org.apache.poi.xssf.XSSFITestDataProvider; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.model.CalculationChain; -import org.apache.poi.xssf.streaming.SXSSFWorkbook; -import org.apache.poi.xssf.usermodel.extensions.XSSFCellFill; -import org.apache.xmlbeans.XmlException; -import org.junit.Ignore; -import org.junit.Test; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCalcCell; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCols; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTDefinedName; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTDefinedNames; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.impl.CTFontImpl; - -@SuppressWarnings("deprecation") -public final class TestXSSFBugs extends BaseTestBugzillaIssues { - public TestXSSFBugs() { - super(XSSFITestDataProvider.instance); - } - - /** - * test writing a file with large number of unique strings, - * open resulting file in Excel to check results! - */ - @Test - public void bug15375_2() throws IOException { - bug15375(1000); - } - - /** - * Named ranges had the right reference, but - * the wrong sheet name - */ - @Test - public void bug45430() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("45430.xlsx"); - assertFalse(wb.isMacroEnabled()); - assertEquals(3, wb.getNumberOfNames()); - - assertEquals(0, wb.getName("SheetAA1").getCTName().getLocalSheetId()); - assertFalse(wb.getName("SheetAA1").getCTName().isSetLocalSheetId()); - assertEquals("SheetA!$A$1", wb.getName("SheetAA1").getRefersToFormula()); - assertEquals("SheetA", wb.getName("SheetAA1").getSheetName()); - - assertEquals(0, wb.getName("SheetBA1").getCTName().getLocalSheetId()); - assertFalse(wb.getName("SheetBA1").getCTName().isSetLocalSheetId()); - assertEquals("SheetB!$A$1", wb.getName("SheetBA1").getRefersToFormula()); - assertEquals("SheetB", wb.getName("SheetBA1").getSheetName()); - - assertEquals(0, wb.getName("SheetCA1").getCTName().getLocalSheetId()); - assertFalse(wb.getName("SheetCA1").getCTName().isSetLocalSheetId()); - assertEquals("SheetC!$A$1", wb.getName("SheetCA1").getRefersToFormula()); - assertEquals("SheetC", wb.getName("SheetCA1").getSheetName()); - - // Save and re-load, still there - XSSFWorkbook nwb = XSSFTestDataSamples.writeOutAndReadBack(wb); - assertEquals(3, nwb.getNumberOfNames()); - assertEquals("SheetA!$A$1", nwb.getName("SheetAA1").getRefersToFormula()); - - nwb.close(); - wb.close(); - } - - /** - * We should carry vba macros over after save - */ - @Test - public void bug45431() throws IOException, InvalidFormatException { - XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("45431.xlsm"); - OPCPackage pkg1 = wb1.getPackage(); - assertTrue(wb1.isMacroEnabled()); - - // Check the various macro related bits can be found - PackagePart vba = pkg1.getPart( - PackagingURIHelper.createPartName("/xl/vbaProject.bin") - ); - assertNotNull(vba); - // And the drawing bit - PackagePart drw = pkg1.getPart( - PackagingURIHelper.createPartName("/xl/drawings/vmlDrawing1.vml") - ); - assertNotNull(drw); - - - // Save and re-open, both still there - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - pkg1.close(); - wb1.close(); - - OPCPackage pkg2 = wb2.getPackage(); - assertTrue(wb2.isMacroEnabled()); - - vba = pkg2.getPart( - PackagingURIHelper.createPartName("/xl/vbaProject.bin") - ); - assertNotNull(vba); - drw = pkg2.getPart( - PackagingURIHelper.createPartName("/xl/drawings/vmlDrawing1.vml") - ); - assertNotNull(drw); - - // And again, just to be sure - XSSFWorkbook wb3 = XSSFTestDataSamples.writeOutAndReadBack(wb2); - pkg2.close(); - wb2.close(); - OPCPackage pkg3 = wb3.getPackage(); - assertTrue(wb3.isMacroEnabled()); - - vba = pkg3.getPart( - PackagingURIHelper.createPartName("/xl/vbaProject.bin") - ); - assertNotNull(vba); - drw = pkg3.getPart( - PackagingURIHelper.createPartName("/xl/drawings/vmlDrawing1.vml") - ); - assertNotNull(drw); - - pkg3.close(); - wb3.close(); - } - - @Test - public void bug47504() throws IOException { - XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("47504.xlsx"); - assertEquals(1, wb1.getNumberOfSheets()); - XSSFSheet sh = wb1.getSheetAt(0); - XSSFDrawing drawing = sh.createDrawingPatriarch(); - List rels = drawing.getRelationParts(); - assertEquals(1, rels.size()); - assertEquals("Sheet1!A1", rels.get(0).getRelationship().getTargetURI().getFragment()); - - // And again, just to be sure - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - assertEquals(1, wb2.getNumberOfSheets()); - sh = wb2.getSheetAt(0); - drawing = sh.createDrawingPatriarch(); - rels = drawing.getRelationParts(); - assertEquals(1, rels.size()); - assertEquals("Sheet1!A1", rels.get(0).getRelationship().getTargetURI().getFragment()); - wb2.close(); - } - - /** - * Excel will sometimes write a button with a textbox - * containing >br< (not closed!). - * Clearly Excel shouldn't do this, but test that we can - * read the file despite the naughtyness - */ - @Test - public void bug49020() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("BrNotClosed.xlsx"); - wb.close(); - } - - /** - * ensure that CTPhoneticPr is loaded by the ooxml test suite so that it is included in poi-ooxml-schemas - */ - @Test - public void bug49325() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("49325.xlsx"); - CTWorksheet sh = wb.getSheetAt(0).getCTWorksheet(); - assertNotNull(sh.getPhoneticPr()); - wb.close(); - } - - /** - * Names which are defined with a Sheet - * should return that sheet index properly - */ - @Test - public void bug48923() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48923.xlsx"); - assertEquals(4, wb.getNumberOfNames()); - - Name b1 = wb.getName("NameB1"); - Name b2 = wb.getName("NameB2"); - Name sheet2 = wb.getName("NameSheet2"); - Name test = wb.getName("Test"); - - assertNotNull(b1); - assertEquals("NameB1", b1.getNameName()); - assertEquals("Sheet1", b1.getSheetName()); - assertEquals(-1, b1.getSheetIndex()); - - assertNotNull(b2); - assertEquals("NameB2", b2.getNameName()); - assertEquals("Sheet1", b2.getSheetName()); - assertEquals(-1, b2.getSheetIndex()); - - assertNotNull(sheet2); - assertEquals("NameSheet2", sheet2.getNameName()); - assertEquals("Sheet2", sheet2.getSheetName()); - assertEquals(-1, sheet2.getSheetIndex()); - - assertNotNull(test); - assertEquals("Test", test.getNameName()); - assertEquals("Sheet1", test.getSheetName()); - assertEquals(-1, test.getSheetIndex()); - - wb.close(); - } - - /** - * Problem with evaluation formulas due to - * NameXPtgs. - * Blows up on: - * IF(B6= (ROUNDUP(B6,0) + ROUNDDOWN(B6,0))/2, MROUND(B6,2),ROUND(B6,0)) - * - * TODO: delete this test case when MROUND and VAR are implemented - */ - @Test - public void bug48539() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48539.xlsx"); - try { - assertEquals(3, wb.getNumberOfSheets()); - assertEquals(0, wb.getNumberOfNames()); - - // Try each cell individually - XSSFFormulaEvaluator eval = new XSSFFormulaEvaluator(wb); - for(int i=0; i rels0 = sh0.getRelationParts(); - List rels1 = sh1.getRelationParts(); - assertEquals(1, rels0.size()); - assertEquals(1, rels1.size()); - - PackageRelationship pr0 = rels0.get(0).getRelationship(); - PackageRelationship pr1 = rels1.get(0).getRelationship(); - - assertEquals(pr0.getTargetMode(), pr1.getTargetMode()); - assertEquals(pr0.getTargetURI(), pr1.getTargetURI()); - POIXMLDocumentPart doc0 = rels0.get(0).getDocumentPart(); - POIXMLDocumentPart doc1 = rels1.get(0).getDocumentPart(); - - assertEquals(doc0, doc1); - wb.close(); - } - - /** - * Add comments to Sheet 1, when Sheet 2 already has - * comments (so /xl/comments1.xml is taken) - */ - @Test - public void bug51850() throws IOException { - XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("51850.xlsx"); - XSSFSheet sh1 = wb1.getSheetAt(0); - XSSFSheet sh2 = wb1.getSheetAt(1); - - // Sheet 2 has comments - assertNotNull(sh2.getCommentsTable(false)); - assertEquals(1, sh2.getCommentsTable(false).getNumberOfComments()); - - // Sheet 1 doesn't (yet) - assertNull(sh1.getCommentsTable(false)); - - // Try to add comments to Sheet 1 - CreationHelper factory = wb1.getCreationHelper(); - Drawing drawing = sh1.createDrawingPatriarch(); - - ClientAnchor anchor = factory.createClientAnchor(); - anchor.setCol1(0); - anchor.setCol2(4); - anchor.setRow1(0); - anchor.setRow2(1); - - Comment comment1 = drawing.createCellComment(anchor); - comment1.setString( - factory.createRichTextString("I like this cell. It's my favourite.")); - comment1.setAuthor("Bob T. Fish"); - - anchor = factory.createClientAnchor(); - anchor.setCol1(0); - anchor.setCol2(4); - anchor.setRow1(1); - anchor.setRow2(1); - Comment comment2 = drawing.createCellComment(anchor); - comment2.setString( - factory.createRichTextString("This is much less fun...")); - comment2.setAuthor("Bob T. Fish"); - - Cell c1 = sh1.getRow(0).createCell(4); - c1.setCellValue(2.3); - c1.setCellComment(comment1); - - Cell c2 = sh1.getRow(0).createCell(5); - c2.setCellValue(2.1); - c2.setCellComment(comment2); - - - // Save and re-load - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sh1 = wb2.getSheetAt(0); - sh2 = wb2.getSheetAt(1); - - // Check the comments - assertNotNull(sh2.getCommentsTable(false)); - assertEquals(1, sh2.getCommentsTable(false).getNumberOfComments()); - - assertNotNull(sh1.getCommentsTable(false)); - assertEquals(2, sh1.getCommentsTable(false).getNumberOfComments()); - wb2.close(); - } - - /** - * Sheet names with a , in them - */ - @Test - public void bug51963() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("51963.xlsx"); - Sheet sheet = wb.getSheetAt(0); - assertEquals("Abc,1", sheet.getSheetName()); - - Name name = wb.getName("Intekon.ProdCodes"); - assertEquals("'Abc,1'!$A$1:$A$2", name.getRefersToFormula()); - - AreaReference ref = new AreaReference(name.getRefersToFormula(), SpreadsheetVersion.EXCEL2007); - assertEquals(0, ref.getFirstCell().getRow()); - assertEquals(0, ref.getFirstCell().getCol()); - assertEquals(1, ref.getLastCell().getRow()); - assertEquals(0, ref.getLastCell().getCol()); - wb.close(); - } - - /** - * Sum across multiple workbooks - * eg =SUM($Sheet1.C1:$Sheet4.C1) - */ - @Test - public void bug48703() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48703.xlsx"); - XSSFSheet sheet = wb.getSheetAt(0); - - // Contains two forms, one with a range and one a list - XSSFRow r1 = sheet.getRow(0); - XSSFRow r2 = sheet.getRow(1); - XSSFCell c1 = r1.getCell(1); - XSSFCell c2 = r2.getCell(1); - - assertEquals(20.0, c1.getNumericCellValue(), 0); - assertEquals("SUM(Sheet1!C1,Sheet2!C1,Sheet3!C1,Sheet4!C1)", c1.getCellFormula()); - - assertEquals(20.0, c2.getNumericCellValue(), 0); - assertEquals("SUM(Sheet1:Sheet4!C1)", c2.getCellFormula()); - - // Try evaluating both - XSSFFormulaEvaluator eval = new XSSFFormulaEvaluator(wb); - eval.evaluateFormulaCellEnum(c1); - eval.evaluateFormulaCellEnum(c2); - - assertEquals(20.0, c1.getNumericCellValue(), 0); - assertEquals(20.0, c2.getNumericCellValue(), 0); - wb.close(); - } - - /** - * Bugzilla 51710: problems reading shared formuals from .xlsx - */ - @Test - public void bug51710() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("51710.xlsx"); - - final String[] columns = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N"}; - final int rowMax = 500; // bug triggers on row index 59 - - Sheet sheet = wb.getSheetAt(0); - - - // go through all formula cells - for (int rInd = 2; rInd <= rowMax; rInd++) { - Row row = sheet.getRow(rInd); - - for (int cInd = 1; cInd <= 12; cInd++) { - Cell cell = row.getCell(cInd); - String formula = cell.getCellFormula(); - CellReference ref = new CellReference(cell); - - //simulate correct answer - String correct = "$A" + (rInd + 1) + "*" + columns[cInd] + "$2"; - - assertEquals("Incorrect formula in " + ref.formatAsString(), correct, formula); - } - - } - wb.close(); - } - - /** - * Bug 53101: - */ - @Test - public void bug5301() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("53101.xlsx"); - FormulaEvaluator evaluator = - wb.getCreationHelper().createFormulaEvaluator(); - // A1: SUM(B1: IZ1) - double a1Value = - evaluator.evaluate(wb.getSheetAt(0).getRow(0).getCell(0)).getNumberValue(); - - // Assert - assertEquals(259.0, a1Value, 0.0); - - // KY: SUM(B1: IZ1) - /*double ky1Value =*/ - evaluator.evaluate(wb.getSheetAt(0).getRow(0).getCell(310)).getNumberValue(); - - // Assert - assertEquals(259.0, a1Value, 0.0); - wb.close(); - } - - @Test - public void bug54436() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("54436.xlsx"); - if(!WorkbookEvaluator.getSupportedFunctionNames().contains("GETPIVOTDATA")){ - Function func = new Function() { - @Override - public ValueEval evaluate(ValueEval[] args, int srcRowIndex, int srcColumnIndex) { - return ErrorEval.NA; - } - }; - - WorkbookEvaluator.registerFunction("GETPIVOTDATA", func); - } - wb.getCreationHelper().createFormulaEvaluator().evaluateAll(); - wb.close(); - } - - /** - * Password Protected .xlsx files should give a helpful - * error message when called via WorkbookFactory with no password - */ - @Test(expected=EncryptedDocumentException.class) - public void bug55692_poifs() throws IOException { - // Via a POIFSFileSystem - POIFSFileSystem fsP = new POIFSFileSystem( - POIDataSamples.getPOIFSInstance().openResourceAsStream("protect.xlsx")); - try { - WorkbookFactory.create(fsP); - } finally { - fsP.close(); - } - } - - @Test - public void bug55692_stream() throws IOException, InvalidFormatException { - // Directly on a Stream, will go via NPOIFS and spot it's - // actually a .xlsx file encrypted with the default password, and open - Workbook wb = WorkbookFactory.create( - POIDataSamples.getPOIFSInstance().openResourceAsStream("protect.xlsx")); - assertNotNull(wb); - assertEquals(3, wb.getNumberOfSheets()); - wb.close(); - } - - @Test - public void bug55692_npoifs() throws IOException { - // Via a NPOIFSFileSystem, will spot it's actually a .xlsx file - // encrypted with the default password, and open - NPOIFSFileSystem fsNP = new NPOIFSFileSystem( - POIDataSamples.getPOIFSInstance().openResourceAsStream("protect.xlsx")); - Workbook wb = WorkbookFactory.create(fsNP); - assertNotNull(wb); - assertEquals(3, wb.getNumberOfSheets()); - wb.close(); - fsNP.close(); - } - - @Test - public void bug53282() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("53282b.xlsx"); - Cell c = wb.getSheetAt(0).getRow(1).getCell(0); - assertEquals("#@_#", c.getStringCellValue()); - assertEquals("http://invalid.uri", c.getHyperlink().getAddress()); - wb.close(); - } - - /** - * Was giving NullPointerException - * at org.apache.poi.xssf.usermodel.XSSFWorkbook.onDocumentRead - * due to a lack of Styles Table - */ - @Test - public void bug56278() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("56278.xlsx"); - assertEquals(0, wb.getSheetIndex("Market Rates")); - - // Save and re-check - Workbook nwb = XSSFTestDataSamples.writeOutAndReadBack(wb); - assertEquals(0, nwb.getSheetIndex("Market Rates")); - nwb.close(); - wb.close(); - } - - @Test - public void bug56315() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56315.xlsx"); - Cell c = wb.getSheetAt(0).getRow(1).getCell(0); - CellValue cv = wb.getCreationHelper().createFormulaEvaluator().evaluate(c); - double rounded = cv.getNumberValue(); - assertEquals(0.1, rounded, 0.0); - wb.close(); - } - - @Test - public void bug56468() throws IOException, InterruptedException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet(); - XSSFRow row = sheet.createRow(0); - XSSFCell cell = row.createCell(0); - cell.setCellValue("Hi"); - sheet.setRepeatingRows(new CellRangeAddress(0, 0, 0, 0)); - - // small hack to try to make this test stable, previously it failed whenever the two written ZIP files had different file-creation - // dates stored. - // We try to do a loop until the current second changes in order to avoid problems with some date information that is written to the ZIP and thus - // causes differences - long start = System.currentTimeMillis()/1000; - while(System.currentTimeMillis()/1000 == start) { - Thread.sleep(10); - } - - ByteArrayOutputStream bos = new ByteArrayOutputStream(8096); - wb.write(bos); - byte firstSave[] = bos.toByteArray(); - bos.reset(); - wb.write(bos); - byte secondSave[] = bos.toByteArray(); - - /*OutputStream stream = new FileOutputStream("C:\\temp\\poi.xlsx"); - try { - wb.write(stream); - } finally { - stream.close(); - }*/ - - assertArrayEquals("Had: \n" + Arrays.toString(firstSave) + " and \n" + Arrays.toString(secondSave), - firstSave, secondSave); - - wb.close(); - } - - /** - * ISO-8601 style cell formats with a T in them, eg - * cell format of "yyyy-MM-ddTHH:mm:ss" - */ - @Test - public void bug54034() throws IOException { - TimeZone tz = LocaleUtil.getUserTimeZone(); - LocaleUtil.setUserTimeZone(TimeZone.getTimeZone("CET")); - try { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("54034.xlsx"); - Sheet sheet = wb.getSheet("Sheet1"); - Row row = sheet.getRow(1); - Cell cell = row.getCell(2); - assertTrue(DateUtil.isCellDateFormatted(cell)); - - DataFormatter fmt = new DataFormatter(); - assertEquals("yyyy\\-mm\\-dd\\Thh:mm", cell.getCellStyle().getDataFormatString()); - assertEquals("2012-08-08T22:59", fmt.formatCellValue(cell)); - - wb.close(); - } finally { - LocaleUtil.setUserTimeZone(tz); - } - } - - - @Test - public void testBug53798XLSX() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("53798_shiftNegative_TMPL.xlsx"); - File xlsOutput = TempFile.createTempFile("testBug53798", ".xlsx"); - bug53798Work(wb, xlsOutput); - wb.close(); - } - - @Ignore("Shifting rows is not yet implemented in SXSSFSheet") - @Test - public void testBug53798XLSXStream() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("53798_shiftNegative_TMPL.xlsx"); - File xlsOutput = TempFile.createTempFile("testBug53798", ".xlsx"); - SXSSFWorkbook wb2 = new SXSSFWorkbook(wb); - bug53798Work(wb2, xlsOutput); - wb2.close(); - wb.close(); - } - - @Test - public void testBug53798XLS() throws IOException { - Workbook wb = HSSFTestDataSamples.openSampleWorkbook("53798_shiftNegative_TMPL.xls"); - File xlsOutput = TempFile.createTempFile("testBug53798", ".xls"); - bug53798Work(wb, xlsOutput); - wb.close(); - } - - /** - * SUMIF was throwing a NPE on some formulas - */ - @Test - public void testBug56420SumIfNPE() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56420.xlsx"); - - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - - Sheet sheet = wb.getSheetAt(0); - Row r = sheet.getRow(2); - Cell c = r.getCell(2); - assertEquals("SUMIF($A$1:$A$4,A3,$B$1:$B$4)", c.getCellFormula()); - Cell eval = evaluator.evaluateInCell(c); - assertEquals(0.0, eval.getNumericCellValue(), 0.0001); - wb.close(); - } - - private void bug53798Work(Workbook wb, File xlsOutput) throws IOException { - Sheet testSheet = wb.getSheetAt(0); - - testSheet.shiftRows(2, 2, 1); - - saveAndReloadReport(wb, xlsOutput); - - // 1) corrupted xlsx (unreadable data in the first row of a shifted group) already comes about - // when shifted by less than -1 negative amount (try -2) - testSheet.shiftRows(3, 3, -1); - - saveAndReloadReport(wb, xlsOutput); - - testSheet.shiftRows(2, 2, 1); - - saveAndReloadReport(wb, xlsOutput); - - // 2) attempt to create a new row IN PLACE of a removed row by a negative shift causes corrupted - // xlsx file with unreadable data in the negative shifted row. - // NOTE it's ok to create any other row. - Row newRow = testSheet.createRow(3); - - saveAndReloadReport(wb, xlsOutput); - - Cell newCell = newRow.createCell(0); - - saveAndReloadReport(wb, xlsOutput); - - newCell.setCellValue("new Cell in row "+newRow.getRowNum()); - - saveAndReloadReport(wb, xlsOutput); - - // 3) once a negative shift has been made any attempt to shift another group of rows - // (note: outside of previously negative shifted rows) by a POSITIVE amount causes POI exception: - // org.apache.xmlbeans.impl.values.XmlValueDisconnectedException. - // NOTE: another negative shift on another group of rows is successful, provided no new rows in - // place of previously shifted rows were attempted to be created as explained above. - testSheet.shiftRows(6, 7, 1); // -- CHANGE the shift to positive once the behaviour of - // the above has been tested - - saveAndReloadReport(wb, xlsOutput); - } - - /** - * XSSFCell.typeMismatch on certain blank cells when formatting - * with DataFormatter - */ - @Test - public void bug56702() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56702.xlsx"); - - Sheet sheet = wb.getSheetAt(0); - - // Get wrong cell by row 8 & column 7 - Cell cell = sheet.getRow(8).getCell(7); - assertEquals(CellType.NUMERIC, cell.getCellTypeEnum()); - - // Check the value - will be zero as it is - assertEquals(0.0, cell.getNumericCellValue(), 0.001); - - // Try to format - DataFormatter formatter = new DataFormatter(); - formatter.formatCellValue(cell); - - // Check the formatting - assertEquals("0", formatter.formatCellValue(cell)); - wb.close(); - } - - /** - * Formulas which reference named ranges, either in other - * sheets, or workbook scoped but in other workbooks. - * Used to fail with with errors like - * org.apache.poi.ss.formula.FormulaParseException: Cell reference expected after sheet name at index 9 - * org.apache.poi.ss.formula.FormulaParseException: Parse error near char 0 '[' in specified formula '[0]!NR_Global_B2'. Expected number, string, or defined name - */ - @Test - public void bug56737() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("56737.xlsx"); - - // Check the named range definitions - Name nSheetScope = wb.getName("NR_To_A1"); - Name nWBScope = wb.getName("NR_Global_B2"); - - assertNotNull(nSheetScope); - assertNotNull(nWBScope); - - assertEquals("Defines!$A$1", nSheetScope.getRefersToFormula()); - assertEquals("Defines!$B$2", nWBScope.getRefersToFormula()); - - // Check the different kinds of formulas - Sheet s = wb.getSheetAt(0); - Cell cRefSName = s.getRow(1).getCell(3); - Cell cRefWName = s.getRow(2).getCell(3); - - assertEquals("Defines!NR_To_A1", cRefSName.getCellFormula()); - // Note the formula, as stored in the file, has the external name index not filename - // TODO Provide a way to get the one with the filename - assertEquals("[0]!NR_Global_B2", cRefWName.getCellFormula()); - - // Try to evaluate them - FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator(); - assertEquals("Test A1", eval.evaluate(cRefSName).getStringValue()); - assertEquals(142, (int)eval.evaluate(cRefWName).getNumberValue()); - - // Try to evaluate everything - eval.evaluateAll(); - wb.close(); - } - - private void saveAndReloadReport(Workbook wb, File outFile) throws IOException { - // run some method on the font to verify if it is "disconnected" already - //for(short i = 0;i < 256;i++) - { - Font font = wb.getFontAt((short)0); - if(font instanceof XSSFFont) { - XSSFFont xfont = (XSSFFont) wb.getFontAt((short)0); - CTFontImpl ctFont = (CTFontImpl) xfont.getCTFont(); - assertEquals(0, ctFont.sizeOfBArray()); - } - } - - FileOutputStream fileOutStream = new FileOutputStream(outFile); - try { - wb.write(fileOutStream); - } finally { - fileOutStream.close(); - } - - FileInputStream is = new FileInputStream(outFile); - try { - Workbook newWB = null; - try { - if(wb instanceof XSSFWorkbook) { - newWB = new XSSFWorkbook(is); - } else if(wb instanceof HSSFWorkbook) { - newWB = new HSSFWorkbook(is); - } else if(wb instanceof SXSSFWorkbook) { - newWB = new SXSSFWorkbook(new XSSFWorkbook(is)); - } else { - throw new IllegalStateException("Unknown workbook: " + wb); - } - assertNotNull(newWB.getSheet("test")); - } finally { - if (newWB != null) { - newWB.close(); - } - } - } finally { - is.close(); - } - } - - @Test - public void testBug56688_1() throws IOException { - XSSFWorkbook excel = XSSFTestDataSamples.openSampleWorkbook("56688_1.xlsx"); - checkValue(excel, "-1.0"); /* Not 0.0 because POI sees date "0" minus one month as invalid date, which is -1! */ - excel.close(); - } - - @Test - public void testBug56688_2() throws IOException { - XSSFWorkbook excel = XSSFTestDataSamples.openSampleWorkbook("56688_2.xlsx"); - checkValue(excel, "#VALUE!"); - excel.close(); - } - - @Test - public void testBug56688_3() throws IOException { - XSSFWorkbook excel = XSSFTestDataSamples.openSampleWorkbook("56688_3.xlsx"); - checkValue(excel, "#VALUE!"); - excel.close(); - } - - @Test - public void testBug56688_4() throws IOException { - XSSFWorkbook excel = XSSFTestDataSamples.openSampleWorkbook("56688_4.xlsx"); - - Calendar calendar = LocaleUtil.getLocaleCalendar(); - calendar.add(Calendar.MONTH, 2); - double excelDate = DateUtil.getExcelDate(calendar.getTime()); - NumberEval eval = new NumberEval(Math.floor(excelDate)); - checkValue(excel, eval.getStringValue() + ".0"); - - excel.close(); - } - - /** - * New hyperlink with no initial cell reference, still need - * to be able to change it - */ - @Test - public void testBug56527() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet(); - XSSFCreationHelper creationHelper = wb.getCreationHelper(); - XSSFHyperlink hyperlink; - - // Try with a cell reference - hyperlink = creationHelper.createHyperlink(HyperlinkType.URL); - sheet.addHyperlink(hyperlink); - hyperlink.setAddress("http://myurl"); - hyperlink.setCellReference("B4"); - assertEquals(3, hyperlink.getFirstRow()); - assertEquals(1, hyperlink.getFirstColumn()); - assertEquals(3, hyperlink.getLastRow()); - assertEquals(1, hyperlink.getLastColumn()); - - // Try with explicit rows / columns - hyperlink = creationHelper.createHyperlink(HyperlinkType.URL); - sheet.addHyperlink(hyperlink); - hyperlink.setAddress("http://myurl"); - hyperlink.setFirstRow(5); - hyperlink.setFirstColumn(3); - - assertEquals(5, hyperlink.getFirstRow()); - assertEquals(3, hyperlink.getFirstColumn()); - assertEquals(5, hyperlink.getLastRow()); - assertEquals(3, hyperlink.getLastColumn()); - wb.close(); - } - - /** - * Shifting rows with a formula that references a - * function in another file - */ - @Test - public void bug56502() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("56502.xlsx"); - Sheet sheet = wb.getSheetAt(0); - - Cell cFunc = sheet.getRow(3).getCell(0); - assertEquals("[1]!LUCANET(\"Ist\")", cFunc.getCellFormula()); - Cell cRef = sheet.getRow(3).createCell(1); - cRef.setCellFormula("A3"); - - // Shift it down one row - sheet.shiftRows(1, sheet.getLastRowNum(), 1); - - // Check the new formulas: Function won't change, Reference will - cFunc = sheet.getRow(4).getCell(0); - assertEquals("[1]!LUCANET(\"Ist\")", cFunc.getCellFormula()); - cRef = sheet.getRow(4).getCell(1); - assertEquals("A4", cRef.getCellFormula()); - wb.close(); - } - - @Test - public void bug54764() throws IOException, OpenXML4JException, XmlException { - OPCPackage pkg = XSSFTestDataSamples.openSamplePackage("54764.xlsx"); - - // Check the core properties - will be found but empty, due - // to the expansion being too much to be considered valid - POIXMLProperties props = new POIXMLProperties(pkg); - assertEquals(null, props.getCoreProperties().getTitle()); - assertEquals(null, props.getCoreProperties().getSubject()); - assertEquals(null, props.getCoreProperties().getDescription()); - - // Now check the spreadsheet itself - try { - new XSSFWorkbook(pkg).close(); - fail("Should fail as too much expansion occurs"); - } catch(POIXMLException e) { - // Expected - } - pkg.close(); - - // Try with one with the entities in the Content Types - try { - XSSFTestDataSamples.openSamplePackage("54764-2.xlsx").close(); - fail("Should fail as too much expansion occurs"); - } catch(Exception e) { - // Expected - } - - // Check we can still parse valid files after all that - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("sample.xlsx"); - assertEquals(3, wb.getNumberOfSheets()); - wb.close(); - } - - /** - * CTDefinedNamesImpl should be included in the smaller - * poi-ooxml-schemas jar - */ - @Test - public void bug57176() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("57176.xlsx"); - CTDefinedNames definedNames = wb.getCTWorkbook().getDefinedNames(); - List definedNameList = definedNames.getDefinedNameList(); - for (CTDefinedName defName : definedNameList) { - assertNotNull(defName.getName()); - assertNotNull(defName.getStringValue()); - } - assertEquals("TestDefinedName", definedNameList.get(0).getName()); - wb.close(); - } - - /** - * .xlsb files are not supported, but we should generate a helpful - * error message if given one - */ - @Test - public void bug56800_xlsb() throws IOException, InvalidFormatException { - // Can be opened at the OPC level - OPCPackage pkg = XSSFTestDataSamples.openSamplePackage("Simple.xlsb"); - - // XSSF Workbook gives helpful error - try { - new XSSFWorkbook(pkg).close(); - fail(".xlsb files not supported"); - } catch (XLSBUnsupportedException e) { - // Good, detected and warned - } - - // Workbook Factory gives helpful error on package - try { - WorkbookFactory.create(pkg).close(); - fail(".xlsb files not supported"); - } catch (XLSBUnsupportedException e) { - // Good, detected and warned - } - - // Workbook Factory gives helpful error on file - File xlsbFile = HSSFTestDataSamples.getSampleFile("Simple.xlsb"); - try { - WorkbookFactory.create(xlsbFile).close(); - fail(".xlsb files not supported"); - } catch (XLSBUnsupportedException e) { - // Good, detected and warned - } - - pkg.close(); - } - - private void checkValue(XSSFWorkbook excel, String expect) { - XSSFFormulaEvaluator evaluator = new XSSFFormulaEvaluator(excel); - evaluator.evaluateAll(); - - XSSFCell cell = excel.getSheetAt(0).getRow(1).getCell(1); - CellValue value = evaluator.evaluate(cell); - - assertEquals(expect, value.formatAsString()); - } - - @Test - public void testBug57196() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57196.xlsx"); - Sheet sheet = wb.getSheet("Feuil1"); - Row mod=sheet.getRow(1); - mod.getCell(1).setCellValue(3); - HSSFFormulaEvaluator.evaluateAllFormulaCells(wb); -// FileOutputStream fileOutput = new FileOutputStream("/tmp/57196.xlsx"); -// wb.write(fileOutput); -// fileOutput.close(); - wb.close(); - } - - @Test - public void test57196_Detail() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet("Sheet1"); - XSSFRow row = sheet.createRow(0); - XSSFCell cell = row.createCell(0); - cell.setCellFormula("DEC2HEX(HEX2DEC(O8)-O2+D2)"); - XSSFFormulaEvaluator fe = new XSSFFormulaEvaluator(wb); - CellValue cv = fe.evaluate(cell); - - assertNotNull(cv); - wb.close(); - } - - @Test - public void test57196_Detail2() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet("Sheet1"); - XSSFRow row = sheet.createRow(0); - XSSFCell cell = row.createCell(0); - cell.setCellFormula("DEC2HEX(O2+D2)"); - XSSFFormulaEvaluator fe = new XSSFFormulaEvaluator(wb); - CellValue cv = fe.evaluate(cell); - - assertNotNull(cv); - wb.close(); - } - - @Test - public void test57196_WorkbookEvaluator() throws IOException { - String previousLogger = System.getProperty("org.apache.poi.util.POILogger"); - //System.setProperty("org.apache.poi.util.POILogger", "org.apache.poi.util.SystemOutLogger"); - //System.setProperty("poi.log.level", "3"); - try { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet("Sheet1"); - XSSFRow row = sheet.createRow(0); - XSSFCell cell = row.createCell(0); - cell.setCellValue("0"); - cell = row.createCell(1); - cell.setCellValue(0); - cell = row.createCell(2); - cell.setCellValue(0); - - // simple formula worked - cell.setCellFormula("DEC2HEX(O2+D2)"); - - WorkbookEvaluator workbookEvaluator = new WorkbookEvaluator(XSSFEvaluationWorkbook.create(wb), null, null); - workbookEvaluator.setDebugEvaluationOutputForNextEval(true); - workbookEvaluator.evaluate(new XSSFEvaluationCell(cell)); - - // this already failed! Hex2Dec did not correctly handle RefEval - cell.setCellFormula("HEX2DEC(O8)"); - workbookEvaluator.clearAllCachedResultValues(); - - workbookEvaluator = new WorkbookEvaluator(XSSFEvaluationWorkbook.create(wb), null, null); - workbookEvaluator.setDebugEvaluationOutputForNextEval(true); - workbookEvaluator.evaluate(new XSSFEvaluationCell(cell)); - - // slightly more complex one failed - cell.setCellFormula("HEX2DEC(O8)-O2+D2"); - workbookEvaluator.clearAllCachedResultValues(); - - workbookEvaluator = new WorkbookEvaluator(XSSFEvaluationWorkbook.create(wb), null, null); - workbookEvaluator.setDebugEvaluationOutputForNextEval(true); - workbookEvaluator.evaluate(new XSSFEvaluationCell(cell)); - - // more complicated failed - cell.setCellFormula("DEC2HEX(HEX2DEC(O8)-O2+D2)"); - workbookEvaluator.clearAllCachedResultValues(); - - workbookEvaluator.setDebugEvaluationOutputForNextEval(true); - workbookEvaluator.evaluate(new XSSFEvaluationCell(cell)); - - // what other similar functions - cell.setCellFormula("DEC2BIN(O8)-O2+D2"); - workbookEvaluator.clearAllCachedResultValues(); - - workbookEvaluator = new WorkbookEvaluator(XSSFEvaluationWorkbook.create(wb), null, null); - workbookEvaluator.setDebugEvaluationOutputForNextEval(true); - workbookEvaluator.evaluate(new XSSFEvaluationCell(cell)); - - // what other similar functions - cell.setCellFormula("DEC2BIN(A1)"); - workbookEvaluator.clearAllCachedResultValues(); - - workbookEvaluator = new WorkbookEvaluator(XSSFEvaluationWorkbook.create(wb), null, null); - workbookEvaluator.setDebugEvaluationOutputForNextEval(true); - workbookEvaluator.evaluate(new XSSFEvaluationCell(cell)); - - // what other similar functions - cell.setCellFormula("BIN2DEC(B1)"); - workbookEvaluator.clearAllCachedResultValues(); - - workbookEvaluator = new WorkbookEvaluator(XSSFEvaluationWorkbook.create(wb), null, null); - workbookEvaluator.setDebugEvaluationOutputForNextEval(true); - workbookEvaluator.evaluate(new XSSFEvaluationCell(cell)); - - wb.close(); - } finally { - if(previousLogger == null) { - System.clearProperty("org.apache.poi.util.POILogger"); - } else { - System.setProperty("org.apache.poi.util.POILogger", previousLogger); - } - System.clearProperty("poi.log.level"); - } - } - - /** - * A .xlsx file with no Shared Strings table should open fine - * in read-only mode - */ - @SuppressWarnings("resource") - @Test - public void bug57482() throws IOException, InvalidFormatException { - for (PackageAccess access : new PackageAccess[] { - PackageAccess.READ_WRITE, PackageAccess.READ - }) { - File file = HSSFTestDataSamples.getSampleFile("57482-OnlyNumeric.xlsx"); - OPCPackage pkg = OPCPackage.open(file, access); - try { - // Try to open it and read the contents - XSSFWorkbook wb1 = new XSSFWorkbook(pkg); - assertNotNull(wb1.getSharedStringSource()); - assertEquals(0, wb1.getSharedStringSource().getCount()); - - DataFormatter fmt = new DataFormatter(); - XSSFSheet s = wb1.getSheetAt(0); - assertEquals("1", fmt.formatCellValue(s.getRow(0).getCell(0))); - assertEquals("11", fmt.formatCellValue(s.getRow(0).getCell(1))); - assertEquals("5", fmt.formatCellValue(s.getRow(4).getCell(0))); - - // Add a text cell - s.getRow(0).createCell(3).setCellValue("Testing"); - assertEquals("Testing", fmt.formatCellValue(s.getRow(0).getCell(3))); - - // Try to write-out and read again, should only work - // in read-write mode, not read-only mode - XSSFWorkbook wb2 = null; - try { - wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - if (access == PackageAccess.READ) { - fail("Shouln't be able to write from read-only mode"); - } - - // Check again - s = wb2.getSheetAt(0); - assertEquals("1", fmt.formatCellValue(s.getRow(0).getCell(0))); - assertEquals("11", fmt.formatCellValue(s.getRow(0).getCell(1))); - assertEquals("5", fmt.formatCellValue(s.getRow(4).getCell(0))); - assertEquals("Testing", fmt.formatCellValue(s.getRow(0).getCell(3))); - - } catch (InvalidOperationException e) { - if (access == PackageAccess.READ_WRITE) { - // Shouldn't occur in write-mode - throw e; - } - } finally { - if (wb2 != null) { - wb2.getPackage().revert(); - } - } - - wb1.getPackage().revert(); - } finally { - pkg.revert(); - } - } - } - - /** - * "Unknown error type: -60" fetching formula error value - */ - @Test - public void bug57535() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57535.xlsx"); - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - evaluator.clearAllCachedResultValues(); - - Sheet sheet = wb.getSheet("Sheet1"); - Cell cell = sheet.getRow(5).getCell(4); - assertEquals(CellType.FORMULA, cell.getCellTypeEnum()); - assertEquals("E4+E5", cell.getCellFormula()); - - CellValue value = evaluator.evaluate(cell); - assertEquals(CellType.ERROR, value.getCellTypeEnum()); - assertEquals(-60, value.getErrorValue()); - assertEquals("~CIRCULAR~REF~", FormulaError.forInt(value.getErrorValue()).getString()); - assertEquals("CIRCULAR_REF", FormulaError.forInt(value.getErrorValue()).toString()); - - wb.close(); - } - - - @Test - public void test57165() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("57171_57163_57165.xlsx"); - try { - removeAllSheetsBut(3, wb); - wb.cloneSheet(0); // Throws exception here - wb.setSheetName(1, "New Sheet"); - //saveWorkbook(wb, fileName); - - XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb); - wbBack.close(); - } finally { - wb.close(); - } - } - - @Test - public void test57165_create() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("57171_57163_57165.xlsx"); - try { - removeAllSheetsBut(3, wb); - wb.createSheet("newsheet"); // Throws exception here - wb.setSheetName(1, "New Sheet"); - //saveWorkbook(wb, fileName); - - XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb); - wbBack.close(); - } finally { - wb.close(); - } - } - - private static void removeAllSheetsBut(int sheetIndex, Workbook wb) - { - int sheetNb = wb.getNumberOfSheets(); - // Move this sheet at the first position - wb.setSheetOrder(wb.getSheetName(sheetIndex), 0); - for (int sn = sheetNb - 1; sn > 0; sn--) - { - wb.removeSheetAt(sn); - } - } - - /** - * Sums 2 plus the cell at the left, indirectly to avoid reference - * problems when deleting columns, conditionally to stop recursion - */ - private static final String FORMULA1 = - "IF( INDIRECT( ADDRESS( ROW(), COLUMN()-1 ) ) = 0, 0," - + "INDIRECT( ADDRESS( ROW(), COLUMN()-1 ) ) ) + 2"; - - /** - * Sums 2 plus the upper cell, indirectly to avoid reference - * problems when deleting rows, conditionally to stop recursion - */ - private static final String FORMULA2 = - "IF( INDIRECT( ADDRESS( ROW()-1, COLUMN() ) ) = 0, 0," - + "INDIRECT( ADDRESS( ROW()-1, COLUMN() ) ) ) + 2"; - - /** - * Expected: - - * [ 0][ 2][ 4] - */ - @Test - public void testBug56820_Formula1() throws IOException { - Workbook wb = new XSSFWorkbook(); - try { - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - Sheet sh = wb.createSheet(); - - sh.createRow(0).createCell(0).setCellValue(0.0d); - Cell formulaCell1 = sh.getRow(0).createCell(1); - Cell formulaCell2 = sh.getRow(0).createCell(2); - formulaCell1.setCellFormula(FORMULA1); - formulaCell2.setCellFormula(FORMULA1); - - double A1 = evaluator.evaluate(formulaCell1).getNumberValue(); - double A2 = evaluator.evaluate(formulaCell2).getNumberValue(); - - assertEquals(2, A1, 0); - assertEquals(4, A2, 0); //<-- FAILS EXPECTATIONS - } finally { - wb.close(); - } - } - - /** - * Expected: - - * [ 0] <- number - * [ 2] <- formula - * [ 4] <- formula - */ - @Test - public void testBug56820_Formula2() throws IOException { - Workbook wb = new XSSFWorkbook(); - try { - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - Sheet sh = wb.createSheet(); - - sh.createRow(0).createCell(0).setCellValue(0.0d); - Cell formulaCell1 = sh.createRow(1).createCell(0); - Cell formulaCell2 = sh.createRow(2).createCell(0); - formulaCell1.setCellFormula(FORMULA2); - formulaCell2.setCellFormula(FORMULA2); - - double A1 = evaluator.evaluate(formulaCell1).getNumberValue(); - double A2 = evaluator.evaluate(formulaCell2).getNumberValue(); //<-- FAILS EVALUATION - - assertEquals(2, A1, 0); - assertEquals(4, A2, 0); - } finally { - wb.close(); - } - } - - @Test - public void test56467() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("picture.xlsx"); - try { - Sheet orig = wb.getSheetAt(0); - assertNotNull(orig); - - Sheet sheet = wb.cloneSheet(0); - Drawing drawing = sheet.createDrawingPatriarch(); - for (XSSFShape shape : ((XSSFDrawing) drawing).getShapes()) { - if (shape instanceof XSSFPicture) { - XSSFPictureData pictureData = ((XSSFPicture) shape).getPictureData(); - assertNotNull(pictureData); - } - } - - } finally { - wb.close(); - } - } - - /** - * OOXML-Strict files - * Not currently working - namespace mis-match from XMLBeans - */ - @Test - @Ignore("XMLBeans namespace mis-match on ooxml-strict files") - public void test57699() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("sample.strict.xlsx"); - assertEquals(3, wb.getNumberOfSheets()); - // TODO Check sheet contents - // TODO Check formula evaluation - - XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb); - assertEquals(3, wbBack.getNumberOfSheets()); - // TODO Re-check sheet contents - // TODO Re-check formula evaluation - - wb.close(); - wbBack.close(); - } - - @Test - public void testBug56295_MergeXlslsWithStyles() throws IOException { - XSSFWorkbook xlsToAppendWorkbook = XSSFTestDataSamples.openSampleWorkbook("56295.xlsx"); - XSSFSheet sheet = xlsToAppendWorkbook.getSheetAt(0); - XSSFRow srcRow = sheet.getRow(0); - XSSFCell oldCell = srcRow.getCell(0); - XSSFCellStyle cellStyle = oldCell.getCellStyle(); - - checkStyle(cellStyle); - -// StylesTable table = xlsToAppendWorkbook.getStylesSource(); -// List fills = table.getFills(); -// System.out.println("Having " + fills.size() + " fills"); -// for(XSSFCellFill fill : fills) { -// System.out.println("Fill: " + fill.getFillBackgroundColor() + "/" + fill.getFillForegroundColor()); -// } - xlsToAppendWorkbook.close(); - - XSSFWorkbook targetWorkbook = new XSSFWorkbook(); - XSSFSheet newSheet = targetWorkbook.createSheet(sheet.getSheetName()); - XSSFRow destRow = newSheet.createRow(0); - XSSFCell newCell = destRow.createCell(0); - - //newCell.getCellStyle().cloneStyleFrom(cellStyle); - CellStyle newCellStyle = targetWorkbook.createCellStyle(); - newCellStyle.cloneStyleFrom(cellStyle); - newCell.setCellStyle(newCellStyle); - checkStyle(newCell.getCellStyle()); - newCell.setCellValue(oldCell.getStringCellValue()); - -// OutputStream os = new FileOutputStream("output.xlsm"); -// try { -// targetWorkbook.write(os); -// } finally { -// os.close(); -// } - - XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(targetWorkbook); - XSSFCellStyle styleBack = wbBack.getSheetAt(0).getRow(0).getCell(0).getCellStyle(); - checkStyle(styleBack); - - targetWorkbook.close(); - wbBack.close(); - } - - /** - * Paragraph with property BuFont but none of the properties - * BuNone, BuChar, and BuAutoNum, used to trigger a NPE - * Excel treats this as not-bulleted, so now do we - */ - @Test - public void testBug57826() throws IOException { - XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("57826.xlsx"); - - assertTrue("no sheets in workbook", workbook.getNumberOfSheets() >= 1); - XSSFSheet sheet = workbook.getSheetAt(0); - - XSSFDrawing drawing = sheet.getDrawingPatriarch(); - assertNotNull(drawing); - - List shapes = drawing.getShapes(); - assertEquals(1, shapes.size()); - assertTrue(shapes.get(0) instanceof XSSFSimpleShape); - - XSSFSimpleShape shape = (XSSFSimpleShape)shapes.get(0); - - // Used to throw a NPE - String text = shape.getText(); - - // No bulleting info included - assertEquals("test ok", text); - - workbook.close(); - } - - private void checkStyle(XSSFCellStyle cellStyle) { - assertNotNull(cellStyle); - assertEquals(0, cellStyle.getFillForegroundColor()); - assertNotNull(cellStyle.getFillForegroundXSSFColor()); - XSSFColor fgColor = cellStyle.getFillForegroundColorColor(); - assertNotNull(fgColor); - assertEquals("FF00FFFF", fgColor.getARGBHex()); - - assertEquals(0, cellStyle.getFillBackgroundColor()); - assertNotNull(cellStyle.getFillBackgroundXSSFColor()); - XSSFColor bgColor = cellStyle.getFillBackgroundColorColor(); - assertNotNull(bgColor); - assertEquals("FF00FFFF", fgColor.getARGBHex()); - } - - @Test - public void bug57642() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet s = wb.createSheet("TestSheet"); - XSSFCell c = s.createRow(0).createCell(0); - c.setCellFormula("ISERROR(TestSheet!A1)"); - c = s.createRow(1).createCell(1); - c.setCellFormula("ISERROR(B2)"); - - wb.setSheetName(0, "CSN"); - c = s.getRow(0).getCell(0); - assertEquals("ISERROR(CSN!A1)", c.getCellFormula()); - c = s.getRow(1).getCell(1); - assertEquals("ISERROR(B2)", c.getCellFormula()); - - wb.close(); - } - - /** - * .xlsx supports 64000 cell styles, the style indexes after - * 32,767 must not be -32,768, then -32,767, -32,766 - */ - @SuppressWarnings("resource") - @Test - public void bug57880() throws IOException { - int numStyles = 33000; - XSSFWorkbook wb = new XSSFWorkbook(); - for (int i=1; i data; - data = new TreeMap(); - data.put("1", new Object[] {"ID", "NAME", "LASTNAME"}); - data.put("2", new Object[] {2, "Amit", "Shukla"}); - data.put("3", new Object[] {1, "Lokesh", "Gupta"}); - data.put("4", new Object[] {4, "John", "Adwards"}); - data.put("5", new Object[] {2, "Brian", "Schultz"}); - - int rownum = 1; - for (Map.Entry me : data.entrySet()) { - final Row row; - if(createRow) { - row = sheet.createRow(rownum++); - } else { - row = sheet.getRow(rownum++); - } - assertNotNull(row); - - int cellnum = 0; - for (Object obj : me.getValue()) { - Cell cell = row.getCell(cellnum); - if(cell == null){ - cell = row.createCell(cellnum); - } else { - if(cell.getCellTypeEnum() == CellType.FORMULA) { - cell.setCellFormula(null); - cell.getCellStyle().setDataFormat((short) 0); - } - } - if(obj instanceof String) { - cell.setCellValue((String)obj); - } else if(obj instanceof Integer) { - cell.setCellValue((Integer)obj); - } - cellnum++; - } - } - - XSSFFormulaEvaluator.evaluateAllFormulaCells((XSSFWorkbook) wb); - wb.getCreationHelper().createFormulaEvaluator().evaluateAll(); - - CalculationChain chain = ((XSSFWorkbook)wb).getCalculationChain(); - for(CTCalcCell calc : chain.getCTCalcChain().getCList()) { - // A2 to A6 should be gone - assertFalse(calc.getR().equals("A2")); - assertFalse(calc.getR().equals("A3")); - assertFalse(calc.getR().equals("A4")); - assertFalse(calc.getR().equals("A5")); - assertFalse(calc.getR().equals("A6")); - } - - Workbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb); - Sheet sheetBack = wbBack.getSheet("Func"); - assertNotNull(sheetBack); - - chain = ((XSSFWorkbook)wbBack).getCalculationChain(); - for(CTCalcCell calc : chain.getCTCalcChain().getCList()) { - // A2 to A6 should be gone - assertFalse(calc.getR().equals("A2")); - assertFalse(calc.getR().equals("A3")); - assertFalse(calc.getR().equals("A4")); - assertFalse(calc.getR().equals("A5")); - assertFalse(calc.getR().equals("A6")); - } - - wbBack.close(); - wb.close(); - } - - /** - * Excel 2007 generated Macro-Enabled .xlsm file - */ - @Test - public void bug57181() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("57181.xlsm"); - assertEquals(9, wb.getNumberOfSheets()); - wb.close(); - } - - @Test - public void bug52111() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("Intersection-52111-xssf.xlsx"); - Sheet s = wb.getSheetAt(0); - assertFormula(wb, s.getRow(2).getCell(0), "(C2:D3 D3:E4)", "4.0"); - assertFormula(wb, s.getRow(6).getCell(0), "Tabelle2!E:E Tabelle2!11:11", "5.0"); - assertFormula(wb, s.getRow(8).getCell(0), "Tabelle2!E:F Tabelle2!11:12", null); - wb.close(); - } - - private void assertFormula(Workbook wb, Cell intF, String expectedFormula, String expectedResultOrNull) { - assertEquals(CellType.FORMULA, intF.getCellTypeEnum()); - if (null == expectedResultOrNull) { - assertEquals(CellType.ERROR, intF.getCachedFormulaResultTypeEnum()); - expectedResultOrNull = "#VALUE!"; - } - else { - assertEquals(CellType.NUMERIC, intF.getCachedFormulaResultTypeEnum()); - } - - assertEquals(expectedFormula, intF.getCellFormula()); - - // Check we can evaluate it correctly - FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator(); - assertEquals(expectedResultOrNull, eval.evaluate(intF).formatAsString()); - } - - @Test - public void test48962() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("48962.xlsx"); - Sheet sh = wb.getSheetAt(0); - Row row = sh.getRow(1); - Cell cell = row.getCell(0); - - CellStyle style = cell.getCellStyle(); - assertNotNull(style); - - // color index - assertEquals(64, style.getFillBackgroundColor()); - XSSFColor color = ((XSSFCellStyle)style).getFillBackgroundXSSFColor(); - assertNotNull(color); - - // indexed color - assertEquals(64, color.getIndexed()); - assertEquals(64, color.getIndex()); - - // not an RGB color - assertFalse(color.isRGB()); - assertNull(color.getRGB()); - wb.close(); - } - - @Test - public void test50755_workday_formula_example() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("50755_workday_formula_example.xlsx"); - Sheet sheet = wb.getSheet("Sheet1"); - for(Row aRow : sheet) { - Cell cell = aRow.getCell(1); - if(cell.getCellTypeEnum() == CellType.FORMULA) { - String formula = cell.getCellFormula(); - //System.out.println("formula: " + formula); - assertNotNull(formula); - assertTrue(formula.contains("WORKDAY")); - } else { - assertNotNull(cell.toString()); - } - } - wb.close(); - } - - @Test - public void test51626() throws IOException, InvalidFormatException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("51626.xlsx"); - assertNotNull(wb); - wb.close(); - - InputStream stream = HSSFTestDataSamples.openSampleFileStream("51626.xlsx"); - wb = WorkbookFactory.create(stream); - stream.close(); - wb.close(); - - wb = XSSFTestDataSamples.openSampleWorkbook("51626_contact.xlsx"); - assertNotNull(wb); - wb.close(); - - stream = HSSFTestDataSamples.openSampleFileStream("51626_contact.xlsx"); - wb = WorkbookFactory.create(stream); - stream.close(); - wb.close(); - } - - @Test - public void test51451() throws IOException { - Workbook wb = new XSSFWorkbook(); - Sheet sh = wb.createSheet(); - - Row row = sh.createRow(0); - Cell cell = row.createCell(0); - cell.setCellValue(239827342); - - CellStyle style = wb.createCellStyle(); - //style.setHidden(false); - DataFormat excelFormat = wb.createDataFormat(); - style.setDataFormat(excelFormat.getFormat("#,##0")); - sh.setDefaultColumnStyle(0, style); - -// FileOutputStream out = new FileOutputStream("/tmp/51451.xlsx"); -// wb.write(out); -// out.close(); - - wb.close(); - } - - @Test - public void test53105() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("53105.xlsx"); - assertNotNull(wb); - - - // Act - // evaluate SUM('Skye Lookup Input'!A4:XFD4), cells in range each contain "1" - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - double numericValue = evaluator.evaluate(wb.getSheetAt(0).getRow(1).getCell(0)).getNumberValue(); - - // Assert - assertEquals(16384.0, numericValue, 0.0); - - wb.close(); - } - - - @Test - public void test58315() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("58315.xlsx"); - Cell cell = wb.getSheetAt(0).getRow(0).getCell(0); - assertNotNull(cell); - StringBuilder tmpCellContent = new StringBuilder(cell.getStringCellValue()); - XSSFRichTextString richText = (XSSFRichTextString) cell.getRichStringCellValue(); - - for (int i = richText.length() - 1; i >= 0; i--) { - Font f = richText.getFontAtIndex(i); - if (f != null && f.getStrikeout()) { - tmpCellContent.deleteCharAt(i); - } - } - String result = tmpCellContent.toString(); - assertEquals("320 350", result); - - wb.close(); - } - - @Test - public void test55406() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("55406_Conditional_formatting_sample.xlsx"); - Sheet sheet = wb.getSheetAt(0); - Cell cellA1 = sheet.getRow(0).getCell(0); - Cell cellA2 = sheet.getRow(1).getCell(0); - - assertEquals(0, cellA1.getCellStyle().getFillForegroundColor()); - assertEquals("FFFDFDFD", ((XSSFColor)cellA1.getCellStyle().getFillForegroundColorColor()).getARGBHex()); - assertEquals(0, cellA2.getCellStyle().getFillForegroundColor()); - assertEquals("FFFDFDFD", ((XSSFColor)cellA2.getCellStyle().getFillForegroundColorColor()).getARGBHex()); - - SheetConditionalFormatting cond = sheet.getSheetConditionalFormatting(); - assertEquals(2, cond.getNumConditionalFormattings()); - - assertEquals(1, cond.getConditionalFormattingAt(0).getNumberOfRules()); - assertEquals(64, cond.getConditionalFormattingAt(0).getRule(0).getPatternFormatting().getFillForegroundColor()); - assertEquals("ISEVEN(ROW())", cond.getConditionalFormattingAt(0).getRule(0).getFormula1()); - assertNull(((XSSFColor)cond.getConditionalFormattingAt(0).getRule(0).getPatternFormatting().getFillForegroundColorColor()).getARGBHex()); - - assertEquals(1, cond.getConditionalFormattingAt(1).getNumberOfRules()); - assertEquals(64, cond.getConditionalFormattingAt(1).getRule(0).getPatternFormatting().getFillForegroundColor()); - assertEquals("ISEVEN(ROW())", cond.getConditionalFormattingAt(1).getRule(0).getFormula1()); - assertNull(((XSSFColor)cond.getConditionalFormattingAt(1).getRule(0).getPatternFormatting().getFillForegroundColorColor()).getARGBHex()); - - wb.close(); - } - - @Test - public void test51998() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("51998.xlsx"); - - Set sheetNames = new HashSet(); - - for (int sheetNum = 0; sheetNum < wb.getNumberOfSheets(); sheetNum++) - { - sheetNames.add(wb.getSheetName(sheetNum)); - } - - for (String sheetName : sheetNames) - { - int sheetIndex = wb.getSheetIndex(sheetName); - - wb.removeSheetAt(sheetIndex); - - Sheet newSheet = wb.createSheet(); - //Sheet newSheet = wb.createSheet(sheetName); - int newSheetIndex = wb.getSheetIndex(newSheet); - //System.out.println(newSheetIndex); - wb.setSheetName(newSheetIndex, sheetName); - wb.setSheetOrder(sheetName, sheetIndex); - } - - Workbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb); - wb.close(); - - assertNotNull(wbBack); - wbBack.close(); - } - - @Test - public void test58731() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("58731.xlsx"); - Sheet sheet = wb.createSheet("Java Books"); - - Object[][] bookData = { - {"Head First Java", "Kathy Serria", 79}, - {"Effective Java", "Joshua Bloch", 36}, - {"Clean Code", "Robert martin", 42}, - {"Thinking in Java", "Bruce Eckel", 35}, - }; - - int rowCount = 0; - for (Object[] aBook : bookData) { - Row row = sheet.createRow(rowCount++); - - int columnCount = 0; - for (Object field : aBook) { - Cell cell = row.createCell(columnCount++); - if (field instanceof String) { - cell.setCellValue((String) field); - } else if (field instanceof Integer) { - cell.setCellValue((Integer) field); - } - } - } - - Workbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb); - sheet = wb2.getSheet("Java Books"); - assertNotNull(sheet.getRow(0)); - assertNotNull(sheet.getRow(0).getCell(0)); - assertEquals(bookData[0][0], sheet.getRow(0).getCell(0).getStringCellValue()); - - wb2.close(); - wb.close(); - } - - /** - * Regression between 3.10.1 and 3.13 - - * org.apache.poi.openxml4j.exceptions.InvalidFormatException: - * The part /xl/sharedStrings.xml does not have any content type - * ! Rule: Package require content types when retrieving a part from a package. [M.1.14] - */ - @Test - public void test58760() throws IOException { - Workbook wb1 = XSSFTestDataSamples.openSampleWorkbook("58760.xlsx"); - assertEquals(1, wb1.getNumberOfSheets()); - assertEquals("Sheet1", wb1.getSheetName(0)); - Workbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - assertEquals(1, wb2.getNumberOfSheets()); - assertEquals("Sheet1", wb2.getSheetName(0)); - wb2.close(); - wb1.close(); - } - - @Test - public void test57236() throws IOException { - // Having very small numbers leads to different formatting, Excel uses the scientific notation, but POI leads to "0" - - /* - DecimalFormat format = new DecimalFormat("#.##########", new DecimalFormatSymbols(Locale.getDefault())); - double d = 3.0E-104; - assertEquals("3.0E-104", format.format(d)); - */ - - DataFormatter formatter = new DataFormatter(true); - - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("57236.xlsx"); - for(int sheetNum = 0;sheetNum < wb.getNumberOfSheets();sheetNum++) { - Sheet sheet = wb.getSheetAt(sheetNum); - for(int rowNum = sheet.getFirstRowNum();rowNum < sheet.getLastRowNum();rowNum++) { - Row row = sheet.getRow(rowNum); - for(int cellNum = row.getFirstCellNum();cellNum < row.getLastCellNum();cellNum++) { - Cell cell = row.getCell(cellNum); - String fmtCellValue = formatter.formatCellValue(cell); - - System.out.println("Cell: " + fmtCellValue); - assertNotNull(fmtCellValue); - assertFalse(fmtCellValue.equals("0")); - } - } - } - - wb.close(); - } - - private void createXls() throws IOException - { - Workbook workbook = new HSSFWorkbook(); - FileOutputStream fileOut = new FileOutputStream("/tmp/rotated.xls"); - Sheet sheet1 = workbook.createSheet(); - Row row1 = sheet1.createRow((short) 0); - - Cell cell1 = row1.createCell(0); - - cell1.setCellValue("Successful rotated text."); - - CellStyle style = workbook.createCellStyle(); - style.setRotation((short) -90); - - cell1.setCellStyle(style); - - workbook.write(fileOut); - fileOut.close(); - workbook.close(); - } - - private void createXlsx() throws IOException { - Workbook workbook = new XSSFWorkbook(); - FileOutputStream fileOut = new FileOutputStream("/tmp/rotated.xlsx"); - Sheet sheet1 = workbook.createSheet(); - Row row1 = sheet1.createRow((short) 0); - - Cell cell1 = row1.createCell(0); - - cell1.setCellValue("Unsuccessful rotated text."); - - CellStyle style = workbook.createCellStyle(); - style.setRotation((short) -90); - - cell1.setCellStyle(style); - - workbook.write(fileOut); - fileOut.close(); - workbook.close(); - } - - @Ignore("Creates files for checking results manually, actual values are tested in Test*CellStyle") - @Test - public void test58043() throws IOException { - createXls(); - createXlsx(); - } - - @Test - public void test59132() throws IOException { - Workbook workbook = XSSFTestDataSamples.openSampleWorkbook("59132.xlsx"); - Sheet worksheet = workbook.getSheet("sheet1"); - - // B3 - Row row = worksheet.getRow(2); - Cell cell = row.getCell(1); - - cell.setCellValue((String)null); - - FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator(); - - // B3 - row = worksheet.getRow(2); - cell = row.getCell(1); - - assertEquals(CellType.BLANK, cell.getCellTypeEnum()); - assertEquals(CellType._NONE, evaluator.evaluateFormulaCellEnum(cell)); - - // A3 - row = worksheet.getRow(2); - cell = row.getCell(0); - - assertEquals(CellType.FORMULA, cell.getCellTypeEnum()); - assertEquals("IF(ISBLANK(B3),\"\",B3)", cell.getCellFormula()); - assertEquals(CellType.STRING, evaluator.evaluateFormulaCellEnum(cell)); - CellValue value = evaluator.evaluate(cell); - assertEquals("", value.getStringValue()); - - // A5 - row = worksheet.getRow(4); - cell = row.getCell(0); - - assertEquals(CellType.FORMULA, cell.getCellTypeEnum()); - assertEquals("COUNTBLANK(A1:A4)", cell.getCellFormula()); - assertEquals(CellType.NUMERIC, evaluator.evaluateFormulaCellEnum(cell)); - value = evaluator.evaluate(cell); - assertEquals(1.0, value.getNumberValue(), 0.1); - - /*FileOutputStream output = new FileOutputStream("C:\\temp\\59132.xlsx"); - try { - workbook.write(output); - } finally { - output.close(); - }*/ - - workbook.close(); - } - - @Ignore("bug 59442") - @Test - public void testSetRGBBackgroundColor() throws IOException { - - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFCell cell = workbook.createSheet().createRow(0).createCell(0); - - XSSFColor color = new XSSFColor(java.awt.Color.RED); - XSSFCellStyle style = workbook.createCellStyle(); - style.setFillForegroundColor(color); - style.setFillPattern(CellStyle.SOLID_FOREGROUND); - cell.setCellStyle(style); - - // Everything is fine at this point, cell is red - - Map properties = new HashMap(); - properties.put(CellUtil.BORDER_BOTTOM, CellStyle.BORDER_THIN); //or BorderStyle.THIN - CellUtil.setCellStyleProperties(cell, properties); - - // Now the cell is all black - XSSFColor actual = cell.getCellStyle().getFillBackgroundColorColor(); - assertNotNull(actual); - assertEquals(color.getARGBHex(), actual.getARGBHex()); - - XSSFWorkbook nwb = XSSFTestDataSamples.writeOutAndReadBack(workbook); - workbook.close(); - XSSFCell ncell = nwb.getSheetAt(0).getRow(0).getCell(0); - XSSFColor ncolor = new XSSFColor(java.awt.Color.RED); - - // Now the cell is all black - XSSFColor nactual = ncell.getCellStyle().getFillBackgroundColorColor(); - assertNotNull(nactual); - assertEquals(ncolor.getARGBHex(), nactual.getARGBHex()); - - nwb.close(); - } - - @Ignore("currently fails on POI 3.15 beta 2") - @Test - public void test55273() { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("ExcelTables.xlsx"); - Sheet sheet = wb.getSheet("ExcelTable"); - - Name name = wb.getName("TableAsRangeName"); - assertEquals("TableName[#All]", name.getRefersToFormula()); - // POI 3.15-beta 2 (2016-06-15): getSheetName throws IllegalArgumentException: Invalid CellReference: TableName[#All] - assertEquals("TableName", name.getSheetName()); - - XSSFSheet xsheet = (XSSFSheet) sheet; - List tables = xsheet.getTables(); - assertEquals(2, tables.size()); //FIXME: how many tables are there in this spreadsheet? - assertEquals("Table1", tables.get(0).getName()); //FIXME: what is the table name? - assertEquals("Table2", tables.get(1).getName()); //FIXME: what is the table name? - } - - @Test - public void test57523() { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57523.xlsx"); - Sheet sheet = wb.getSheet("Attribute Master"); - Row row = sheet.getRow(15); - - int N = CellReference.convertColStringToIndex("N"); - Cell N16 = row.getCell(N); - assertEquals(500.0, N16.getNumericCellValue(), 0.00001); - - int P = CellReference.convertColStringToIndex("P"); - Cell P16 = row.getCell(P); - assertEquals(10.0, P16.getNumericCellValue(), 0.00001); - } - - /** - * Files produced by some scientific equipment neglect - * to include the row number on the row tags - */ - @Test - public void noRowNumbers59746() { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("59746_NoRowNums.xlsx"); - Sheet sheet = wb.getSheetAt(0); - assertTrue("Last row num: "+sheet.getLastRowNum(), sheet.getLastRowNum()>20); - assertEquals("Checked", sheet.getRow(0).getCell(0).getStringCellValue()); - assertEquals("Checked", sheet.getRow(9).getCell(2).getStringCellValue()); - assertEquals(false, sheet.getRow(70).getCell(8).getBooleanCellValue()); - assertEquals(71, sheet.getPhysicalNumberOfRows()); - assertEquals(70, sheet.getLastRowNum()); - assertEquals(70, sheet.getRow(sheet.getLastRowNum()).getRowNum()); - } - - @Test - public void testWorkdayFunction() throws IOException { - XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("59106.xlsx"); - XSSFSheet sheet = workbook.getSheet("Test"); - Row row = sheet.getRow(1); - Cell cell = row.getCell(0); - DataFormatter form = new DataFormatter(); - FormulaEvaluator evaluator = cell.getSheet().getWorkbook().getCreationHelper().createFormulaEvaluator(); - String result = form.formatCellValue(cell, evaluator); - - assertEquals("09 Mar 2016", result); - } - - // This bug is currently open. When this bug is fixed, it should not throw an AssertionError - @Test(expected=AssertionError.class) - public void test55076_collapseColumnGroups() throws Exception { - Workbook wb = new XSSFWorkbook(); - Sheet sheet = wb.createSheet(); - - // this column collapsing bug only occurs when the grouped columns are different widths - sheet.setColumnWidth(1, 400); - sheet.setColumnWidth(2, 600); - sheet.setColumnWidth(3, 800); - - assertEquals(400, sheet.getColumnWidth(1)); - assertEquals(600, sheet.getColumnWidth(2)); - assertEquals(800, sheet.getColumnWidth(3)); - - sheet.groupColumn(1, 3); - sheet.setColumnGroupCollapsed(1, true); - - assertEquals(0, sheet.getColumnOutlineLevel(0)); - assertEquals(1, sheet.getColumnOutlineLevel(1)); - assertEquals(1, sheet.getColumnOutlineLevel(2)); - assertEquals(1, sheet.getColumnOutlineLevel(3)); - assertEquals(0, sheet.getColumnOutlineLevel(4)); - - // none of the columns should be hidden - // column group collapsing is a different concept - for (int c=0; c<5; c++) { - assertFalse("Column " + c, sheet.isColumnHidden(c)); - } - - assertEquals(400, sheet.getColumnWidth(1)); - assertEquals(600, sheet.getColumnWidth(2)); - assertEquals(800, sheet.getColumnWidth(3)); - - wb.close(); - } - - /** - * Other things, including charts, may end up taking drawing part - * numbers. (Uses a test file hand-crafted with an extra non-drawing - * part with a part number) - */ - @Test - public void drawingNumbersAlreadyTaken_60255() throws Exception { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("60255_extra_drawingparts.xlsx"); - assertEquals(4, wb.getNumberOfSheets()); - - // Sheet 3 starts with a drawing - Sheet sheet = wb.getSheetAt(0); - assertNull(sheet.getDrawingPatriarch()); - sheet = wb.getSheetAt(1); - assertNull(sheet.getDrawingPatriarch()); - sheet = wb.getSheetAt(2); - assertNotNull(sheet.getDrawingPatriarch()); - sheet = wb.getSheetAt(3); - assertNull(sheet.getDrawingPatriarch()); - - // Add another sheet, and give it a drawing - sheet = wb.createSheet(); - assertNull(sheet.getDrawingPatriarch()); - sheet.createDrawingPatriarch(); - assertNotNull(sheet.getDrawingPatriarch()); - - // Save and check - wb = XSSFTestDataSamples.writeOutAndReadBack(wb); - assertEquals(5, wb.getNumberOfSheets()); - - // Sheets 3 and 5 now - sheet = wb.getSheetAt(0); - assertNull(sheet.getDrawingPatriarch()); - sheet = wb.getSheetAt(1); - assertNull(sheet.getDrawingPatriarch()); - sheet = wb.getSheetAt(2); - assertNotNull(sheet.getDrawingPatriarch()); - sheet = wb.getSheetAt(3); - assertNull(sheet.getDrawingPatriarch()); - sheet = wb.getSheetAt(4); - assertNotNull(sheet.getDrawingPatriarch()); - } - - @Test - public void test53611() throws IOException { - Workbook wb = new XSSFWorkbook(); - Sheet sheet = wb.createSheet("test"); - Row row = sheet.createRow(1); - Cell cell = row.createCell(1); - cell.setCellValue("blabla"); - - row = sheet.createRow(4); - cell = row.createCell(7); - cell.setCellValue("blabla"); - - // we currently only populate the dimension during writing out - // to avoid having to iterate all rows/cells in each add/remove of a row or cell - //OutputStream str = new FileOutputStream("/tmp/53611.xlsx"); - OutputStream str = new ByteArrayOutputStream(); - try { - wb.write(str); - } finally { - str.close(); - } - - assertEquals("B2:I5", ((XSSFSheet)sheet).getCTWorksheet().getDimension().getRef()); - - wb.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFCell.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFCell.java deleted file mode 100644 index 76e477298..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFCell.java +++ /dev/null @@ -1,705 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.assertFalse; - -import java.io.IOException; -import java.util.List; - -import org.apache.poi.common.usermodel.HyperlinkType; -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.ss.formula.FormulaParseException; -import org.apache.poi.ss.usermodel.BaseTestXCell; -import org.apache.poi.ss.usermodel.BorderStyle; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellCopyPolicy; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CreationHelper; -import org.apache.poi.ss.usermodel.DataFormatter; -import org.apache.poi.ss.usermodel.Font; -import org.apache.poi.ss.usermodel.Hyperlink; -import org.apache.poi.ss.usermodel.IndexedColors; -import org.apache.poi.ss.usermodel.RichTextString; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Row.MissingCellPolicy; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.xssf.SXSSFITestDataProvider; -import org.apache.poi.xssf.XSSFITestDataProvider; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.model.SharedStringsTable; -import org.junit.Test; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCell; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STCellType; - -public final class TestXSSFCell extends BaseTestXCell { - - public TestXSSFCell() { - super(XSSFITestDataProvider.instance); - } - - /** - * Bug 47026: trouble changing cell type when workbook doesn't contain - * Shared String Table - */ - @Test - public void test47026_1() throws IOException { - Workbook wb = _testDataProvider.openSampleWorkbook("47026.xlsm"); - Sheet sheet = wb.getSheetAt(0); - Row row = sheet.getRow(0); - Cell cell = row.getCell(0); - cell.setCellType(CellType.STRING); - cell.setCellValue("456"); - wb.close(); - } - - @Test - public void test47026_2() throws IOException { - Workbook wb = _testDataProvider.openSampleWorkbook("47026.xlsm"); - Sheet sheet = wb.getSheetAt(0); - Row row = sheet.getRow(0); - Cell cell = row.getCell(0); - cell.setCellFormula(null); - cell.setCellValue("456"); - wb.close(); - } - - /** - * Test that we can read inline strings that are expressed directly in the cell definition - * instead of implementing the shared string table. - * - * Some programs, for example, Microsoft Excel Driver for .xlsx insert inline string - * instead of using the shared string table. See bug 47206 - */ - @Test - public void testInlineString() throws IOException { - XSSFWorkbook wb = (XSSFWorkbook)_testDataProvider.openSampleWorkbook("xlsx-jdbc.xlsx"); - XSSFSheet sheet = wb.getSheetAt(0); - XSSFRow row = sheet.getRow(1); - - XSSFCell cell_0 = row.getCell(0); - assertEquals(STCellType.INT_INLINE_STR, cell_0.getCTCell().getT().intValue()); - assertTrue(cell_0.getCTCell().isSetIs()); - assertEquals("A Very large string in column 1 AAAAAAAAAAAAAAAAAAAAA", cell_0.getStringCellValue()); - - XSSFCell cell_1 = row.getCell(1); - assertEquals(STCellType.INT_INLINE_STR, cell_1.getCTCell().getT().intValue()); - assertTrue(cell_1.getCTCell().isSetIs()); - assertEquals("foo", cell_1.getStringCellValue()); - - XSSFCell cell_2 = row.getCell(2); - assertEquals(STCellType.INT_INLINE_STR, cell_2.getCTCell().getT().intValue()); - assertTrue(cell_2.getCTCell().isSetIs()); - assertEquals("bar", row.getCell(2).getStringCellValue()); - wb.close(); - } - - /** - * Bug 47278 - xsi:nil attribute for tag caused Excel 2007 to fail to open workbook - */ - @Test - public void test47278() throws IOException { - XSSFWorkbook wb = (XSSFWorkbook)_testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - SharedStringsTable sst = wb.getSharedStringSource(); - assertEquals(0, sst.getCount()); - - //case 1. cell.setCellValue(new XSSFRichTextString((String)null)); - Cell cell_0 = row.createCell(0); - RichTextString str = new XSSFRichTextString((String)null); - assertNull(str.getString()); - cell_0.setCellValue(str); - assertEquals(0, sst.getCount()); - assertEquals(CellType.BLANK, cell_0.getCellTypeEnum()); - - //case 2. cell.setCellValue((String)null); - Cell cell_1 = row.createCell(1); - cell_1.setCellValue((String)null); - assertEquals(0, sst.getCount()); - assertEquals(CellType.BLANK, cell_1.getCellTypeEnum()); - wb.close(); - } - - @Test - public void testFormulaString() throws IOException { - XSSFWorkbook wb = (XSSFWorkbook)_testDataProvider.createWorkbook(); - try { - XSSFCell cell = wb.createSheet().createRow(0).createCell(0); - CTCell ctCell = cell.getCTCell(); //low-level bean holding cell's xml - - cell.setCellFormula("A2"); - assertEquals(CellType.FORMULA, cell.getCellTypeEnum()); - assertEquals("A2", cell.getCellFormula()); - //the value is not set and cell's type='N' which means blank - assertEquals(STCellType.N, ctCell.getT()); - - //set cached formula value - cell.setCellValue("t='str'"); - //we are still of 'formula' type - assertEquals(CellType.FORMULA, cell.getCellTypeEnum()); - assertEquals("A2", cell.getCellFormula()); - //cached formula value is set and cell's type='STR' - assertEquals(STCellType.STR, ctCell.getT()); - assertEquals("t='str'", cell.getStringCellValue()); - - //now remove the formula, the cached formula result remains - cell.setCellFormula(null); - assertEquals(CellType.STRING, cell.getCellTypeEnum()); - assertEquals(STCellType.STR, ctCell.getT()); - //the line below failed prior to fix of Bug #47889 - assertEquals("t='str'", cell.getStringCellValue()); - - //revert to a blank cell - cell.setCellValue((String)null); - assertEquals(CellType.BLANK, cell.getCellTypeEnum()); - assertEquals(STCellType.N, ctCell.getT()); - assertEquals("", cell.getStringCellValue()); - - // check behavior with setCellFormulaValidation - final String invalidFormula = "A", validFormula = "A2"; - FormulaParseException fpe = null; - // check that default is true - assertTrue(wb.getCellFormulaValidation()); - - // check that valid formula does not throw exception - try { - cell.setCellFormula(validFormula); - } catch(FormulaParseException e) { - fpe = e; - } - assertNull(fpe); - - // check that invalid formula does throw exception - try { - cell.setCellFormula(invalidFormula); - } catch(FormulaParseException e) { - fpe = e; - } - assertNotNull(fpe); - fpe = null; - - // set cell formula validation to false - wb.setCellFormulaValidation(false); - assertFalse(wb.getCellFormulaValidation()); - - // check that neither valid nor invalid formula throw an exception - try { - cell.setCellFormula(validFormula); - cell.setCellFormula(invalidFormula); - } catch(FormulaParseException e) { - fpe = e; - } - assertNull(fpe); - } finally { - wb.close(); - } - } - - /** - * Bug 47889: problems when calling XSSFCell.getStringCellValue() on a workbook created in Gnumeric - */ - @Test - public void test47889() throws IOException { - XSSFWorkbook wb = (XSSFWorkbook)_testDataProvider.openSampleWorkbook("47889.xlsx"); - XSSFSheet sh = wb.getSheetAt(0); - - XSSFCell cell; - - //try a string cell - cell = sh.getRow(0).getCell(0); - assertEquals(CellType.STRING, cell.getCellTypeEnum()); - assertEquals("a", cell.getStringCellValue()); - assertEquals("a", cell.toString()); - //Gnumeric produces spreadsheets without styles - //make sure we return null for that instead of throwing OutOfBounds - assertEquals(null, cell.getCellStyle()); - - //try a numeric cell - cell = sh.getRow(1).getCell(0); - assertEquals(CellType.NUMERIC, cell.getCellTypeEnum()); - assertEquals(1.0, cell.getNumericCellValue(), 0); - assertEquals("1.0", cell.toString()); - //Gnumeric produces spreadsheets without styles - //make sure we return null for that instead of throwing OutOfBounds - assertEquals(null, cell.getCellStyle()); - wb.close(); - } - - @Test - public void testMissingRAttribute() throws IOException { - XSSFWorkbook wb1 = new XSSFWorkbook(); - XSSFSheet sheet = wb1.createSheet(); - XSSFRow row = sheet.createRow(0); - XSSFCell a1 = row.createCell(0); - a1.setCellValue("A1"); - XSSFCell a2 = row.createCell(1); - a2.setCellValue("B1"); - XSSFCell a4 = row.createCell(4); - a4.setCellValue("E1"); - XSSFCell a6 = row.createCell(5); - a6.setCellValue("F1"); - - assertCellsWithMissingR(row); - - a2.getCTCell().unsetR(); - a6.getCTCell().unsetR(); - - assertCellsWithMissingR(row); - - XSSFWorkbook wb2 = (XSSFWorkbook)_testDataProvider.writeOutAndReadBack(wb1); - row = wb2.getSheetAt(0).getRow(0); - assertCellsWithMissingR(row); - - wb2.close(); - wb1.close(); - } - - private void assertCellsWithMissingR(XSSFRow row){ - XSSFCell a1 = row.getCell(0); - assertNotNull(a1); - XSSFCell a2 = row.getCell(1); - assertNotNull(a2); - XSSFCell a5 = row.getCell(4); - assertNotNull(a5); - XSSFCell a6 = row.getCell(5); - assertNotNull(a6); - - assertEquals(6, row.getLastCellNum()); - assertEquals(4, row.getPhysicalNumberOfCells()); - - assertEquals("A1", a1.getStringCellValue()); - assertEquals("B1", a2.getStringCellValue()); - assertEquals("E1", a5.getStringCellValue()); - assertEquals("F1", a6.getStringCellValue()); - - // even if R attribute is not set, - // POI is able to re-construct it from column and row indexes - assertEquals("A1", a1.getReference()); - assertEquals("B1", a2.getReference()); - assertEquals("E1", a5.getReference()); - assertEquals("F1", a6.getReference()); - } - - @Test - public void testMissingRAttributeBug54288() throws IOException { - // workbook with cells missing the R attribute - XSSFWorkbook wb = (XSSFWorkbook)_testDataProvider.openSampleWorkbook("54288.xlsx"); - // same workbook re-saved in Excel 2010, the R attribute is updated for every cell with the right value. - XSSFWorkbook wbRef = (XSSFWorkbook)_testDataProvider.openSampleWorkbook("54288-ref.xlsx"); - - XSSFSheet sheet = wb.getSheetAt(0); - XSSFSheet sheetRef = wbRef.getSheetAt(0); - assertEquals(sheetRef.getPhysicalNumberOfRows(), sheet.getPhysicalNumberOfRows()); - - // Test idea: iterate over cells in the reference worksheet, they all have the R attribute set. - // For each cell from the reference sheet find the corresponding cell in the problematic file (with missing R) - // and assert that POI reads them equally: - DataFormatter formater = new DataFormatter(); - for(Row r : sheetRef){ - XSSFRow rowRef = (XSSFRow)r; - XSSFRow row = sheet.getRow(rowRef.getRowNum()); - - assertEquals("number of cells in row["+row.getRowNum()+"]", - rowRef.getPhysicalNumberOfCells(), row.getPhysicalNumberOfCells()); - - for(Cell c : rowRef){ - XSSFCell cellRef = (XSSFCell)c; - XSSFCell cell = row.getCell(cellRef.getColumnIndex()); - - assertEquals(cellRef.getColumnIndex(), cell.getColumnIndex()); - assertEquals(cellRef.getReference(), cell.getReference()); - - if(!cell.getCTCell().isSetR()){ - assertTrue("R must e set in cellRef", cellRef.getCTCell().isSetR()); - - String valRef = formater.formatCellValue(cellRef); - String val = formater.formatCellValue(cell); - assertEquals(valRef, val); - } - - } - } - wbRef.close(); - wb.close(); - } - - @Test - public void test56170() throws IOException { - final Workbook wb1 = XSSFTestDataSamples.openSampleWorkbook("56170.xlsx"); - final XSSFSheet sheet = (XSSFSheet) wb1.getSheetAt(0); - - Workbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - Cell cell; - - // add some contents to table so that the table will need expansion - Row row = sheet.getRow(0); - Workbook wb3 = XSSFTestDataSamples.writeOutAndReadBack(wb2); - cell = row.createCell(0); - Workbook wb4 = XSSFTestDataSamples.writeOutAndReadBack(wb3); - cell.setCellValue("demo1"); - Workbook wb5 = XSSFTestDataSamples.writeOutAndReadBack(wb4); - cell = row.createCell(1); - Workbook wb6 = XSSFTestDataSamples.writeOutAndReadBack(wb5); - cell.setCellValue("demo2"); - Workbook wb7 = XSSFTestDataSamples.writeOutAndReadBack(wb6); - cell = row.createCell(2); - Workbook wb8 = XSSFTestDataSamples.writeOutAndReadBack(wb7); - cell.setCellValue("demo3"); - - Workbook wb9 = XSSFTestDataSamples.writeOutAndReadBack(wb8); - - row = sheet.getRow(1); - cell = row.createCell(0); - cell.setCellValue("demo1"); - cell = row.createCell(1); - cell.setCellValue("demo2"); - cell = row.createCell(2); - cell.setCellValue("demo3"); - - Workbook wb10 = XSSFTestDataSamples.writeOutAndReadBack(wb9); - - // expand table - XSSFTable table = sheet.getTables().get(0); - final CellReference startRef = table.getStartCellReference(); - final CellReference endRef = table.getEndCellReference(); - table.getCTTable().setRef(new CellRangeAddress(startRef.getRow(), 1, startRef.getCol(), endRef.getCol()).formatAsString()); - - Workbook wb11 = XSSFTestDataSamples.writeOutAndReadBack(wb10); - assertNotNull(wb11); - - wb11.close(); - wb10.close(); - wb9.close(); - wb8.close(); - wb7.close(); - wb6.close(); - wb5.close(); - wb4.close(); - wb3.close(); - wb2.close(); - wb1.close(); - } - - @Test - public void test56170Reproduce() throws IOException { - final Workbook wb = new XSSFWorkbook(); - try { - final Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - - // by creating Cells out of order we trigger the handling in onDocumentWrite() - Cell cell1 = row.createCell(1); - Cell cell2 = row.createCell(0); - - validateRow(row); - - validateRow(row); - - // once again with removing one cell - row.removeCell(cell1); - - validateRow(row); - - // once again with removing one cell - row.removeCell(cell1); - - // now check again - validateRow(row); - - // once again with removing one cell - row.removeCell(cell2); - - // now check again - validateRow(row); - } finally { - wb.close(); - } - } - - private void validateRow(Row row) { - // trigger bug with CArray handling - ((XSSFRow)row).onDocumentWrite(); - - for(Cell cell : row) { - assertNotNull(cell.toString()); - } - } - - @Test - public void testBug56644ReturnNull() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("56644.xlsx"); - try { - wb.setMissingCellPolicy(MissingCellPolicy.RETURN_BLANK_AS_NULL); - Sheet sheet = wb.getSheet("samplelist"); - Row row = sheet.getRow(20); - row.createCell(2); - } finally { - wb.close(); - } - } - - @Test - public void testBug56644ReturnBlank() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("56644.xlsx"); - try { - wb.setMissingCellPolicy(MissingCellPolicy.RETURN_NULL_AND_BLANK); - Sheet sheet = wb.getSheet("samplelist"); - Row row = sheet.getRow(20); - row.createCell(2); - } finally { - wb.close(); - } - } - - @Test - public void testBug56644CreateBlank() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("56644.xlsx"); - try { - wb.setMissingCellPolicy(MissingCellPolicy.CREATE_NULL_AS_BLANK); - Sheet sheet = wb.getSheet("samplelist"); - Row row = sheet.getRow(20); - row.createCell(2); - } finally { - wb.close(); - } - } - - @Test - public void testEncodingBelowAscii() throws IOException { - StringBuilder sb = new StringBuilder(); - // test all possible characters - for(int i = 0; i < Character.MAX_VALUE; i++) { - sb.append((char)i); - } - - String strAll = sb.toString(); - - // process in chunks as we have a limit on size of column now - int pos = 0; - while(pos < strAll.length()) { - String str = strAll.substring(pos, Math.min(strAll.length(), pos+SpreadsheetVersion.EXCEL2007.getMaxTextLength())); - - Workbook wb = HSSFITestDataProvider.instance.createWorkbook(); - Cell cell = wb.createSheet().createRow(0).createCell(0); - - Workbook xwb = XSSFITestDataProvider.instance.createWorkbook(); - Cell xCell = xwb.createSheet().createRow(0).createCell(0); - - Workbook swb = SXSSFITestDataProvider.instance.createWorkbook(); - Cell sCell = swb.createSheet().createRow(0).createCell(0); - - cell.setCellValue(str); - assertEquals(str, cell.getStringCellValue()); - xCell.setCellValue(str); - assertEquals(str, xCell.getStringCellValue()); - sCell.setCellValue(str); - assertEquals(str, sCell.getStringCellValue()); - - Workbook wbBack = HSSFITestDataProvider.instance.writeOutAndReadBack(wb); - Workbook xwbBack = XSSFITestDataProvider.instance.writeOutAndReadBack(xwb); - Workbook swbBack = SXSSFITestDataProvider.instance.writeOutAndReadBack(swb); - cell = wbBack.getSheetAt(0).createRow(0).createCell(0); - xCell = xwbBack.getSheetAt(0).createRow(0).createCell(0); - sCell = swbBack.getSheetAt(0).createRow(0).createCell(0); - - assertEquals(cell.getStringCellValue(), xCell.getStringCellValue()); - assertEquals(cell.getStringCellValue(), sCell.getStringCellValue()); - - pos += SpreadsheetVersion.EXCEL97.getMaxTextLength(); - - swbBack.close(); - xwbBack.close(); - wbBack.close(); - swb.close(); - xwb.close(); - wb.close(); - } - } - - private XSSFCell srcCell, destCell; //used for testCopyCellFrom_CellCopyPolicy - - @Test - public final void testCopyCellFrom_CellCopyPolicy_default() { - setUp_testCopyCellFrom_CellCopyPolicy(); - - // default copy policy - final CellCopyPolicy policy = new CellCopyPolicy(); - destCell.copyCellFrom(srcCell, policy); - - assertEquals(CellType.FORMULA, destCell.getCellTypeEnum()); - assertEquals("2+3", destCell.getCellFormula()); - assertEquals(srcCell.getCellStyle(), destCell.getCellStyle()); - } - - @Test - public final void testCopyCellFrom_CellCopyPolicy_value() { - setUp_testCopyCellFrom_CellCopyPolicy(); - - // Paste values only - final CellCopyPolicy policy = new CellCopyPolicy.Builder().cellFormula(false).build(); - destCell.copyCellFrom(srcCell, policy); - assertEquals(CellType.NUMERIC, destCell.getCellTypeEnum()); - } - - @Test - public final void testCopyCellFrom_CellCopyPolicy_formulaWithUnregisteredUDF() { - setUp_testCopyCellFrom_CellCopyPolicy(); - - srcCell.setCellFormula("MYFUNC2(123, $A5, Sheet1!$B7)"); - - // Copy formula verbatim (no shifting). This is okay because copyCellFrom is Internal. - // Users should use higher-level copying functions to row- or column-shift formulas. - final CellCopyPolicy policy = new CellCopyPolicy.Builder().cellFormula(true).build(); - destCell.copyCellFrom(srcCell, policy); - assertEquals("MYFUNC2(123, $A5, Sheet1!$B7)", destCell.getCellFormula()); - } - - @Test - public final void testCopyCellFrom_CellCopyPolicy_style() { - setUp_testCopyCellFrom_CellCopyPolicy(); - srcCell.setCellValue((String) null); - - // Paste styles only - final CellCopyPolicy policy = new CellCopyPolicy.Builder().cellValue(false).build(); - destCell.copyCellFrom(srcCell, policy); - assertEquals(srcCell.getCellStyle(), destCell.getCellStyle()); - - // Old cell value should not have been overwritten - assertNotEquals(CellType.BLANK, destCell.getCellTypeEnum()); - assertEquals(CellType.BOOLEAN, destCell.getCellTypeEnum()); - assertEquals(true, destCell.getBooleanCellValue()); - } - - @Test - public final void testCopyCellFrom_CellCopyPolicy_copyHyperlink() throws IOException { - setUp_testCopyCellFrom_CellCopyPolicy(); - final Workbook wb = srcCell.getSheet().getWorkbook(); - final CreationHelper createHelper = wb.getCreationHelper(); - - srcCell.setCellValue("URL LINK"); - Hyperlink link = createHelper.createHyperlink(HyperlinkType.URL); - link.setAddress("http://poi.apache.org/"); - srcCell.setHyperlink(link); - - // Set link cell style (optional) - CellStyle hlinkStyle = wb.createCellStyle(); - Font hlinkFont = wb.createFont(); - hlinkFont.setUnderline(Font.U_SINGLE); - hlinkFont.setColor(IndexedColors.BLUE.getIndex()); - hlinkStyle.setFont(hlinkFont); - srcCell.setCellStyle(hlinkStyle); - - // Copy hyperlink - final CellCopyPolicy policy = new CellCopyPolicy.Builder().copyHyperlink(true).mergeHyperlink(false).build(); - destCell.copyCellFrom(srcCell, policy); - assertNotNull(destCell.getHyperlink()); - - assertSame("unit test assumes srcCell and destCell are on the same sheet", - srcCell.getSheet(), destCell.getSheet()); - - final List links = srcCell.getSheet().getHyperlinkList(); - assertEquals("number of hyperlinks on sheet", 2, links.size()); - assertEquals("source hyperlink", - new CellReference(srcCell).formatAsString(), links.get(0).getCellRef()); - assertEquals("destination hyperlink", - new CellReference(destCell).formatAsString(), links.get(1).getCellRef()); - - wb.close(); - } - - @Test - public final void testCopyCellFrom_CellCopyPolicy_mergeHyperlink() throws IOException { - setUp_testCopyCellFrom_CellCopyPolicy(); - final Workbook wb = srcCell.getSheet().getWorkbook(); - final CreationHelper createHelper = wb.getCreationHelper(); - - srcCell.setCellValue("URL LINK"); - Hyperlink link = createHelper.createHyperlink(HyperlinkType.URL); - link.setAddress("http://poi.apache.org/"); - destCell.setHyperlink(link); - - // Set link cell style (optional) - CellStyle hlinkStyle = wb.createCellStyle(); - Font hlinkFont = wb.createFont(); - hlinkFont.setUnderline(Font.U_SINGLE); - hlinkFont.setColor(IndexedColors.BLUE.getIndex()); - hlinkStyle.setFont(hlinkFont); - destCell.setCellStyle(hlinkStyle); - - // Pre-condition assumptions. This test is broken if either of these fail. - assertSame("unit test assumes srcCell and destCell are on the same sheet", - srcCell.getSheet(), destCell.getSheet()); - assertNull(srcCell.getHyperlink()); - - // Merge hyperlink - since srcCell doesn't have a hyperlink, destCell's hyperlink is not overwritten (cleared). - final CellCopyPolicy policy = new CellCopyPolicy.Builder().mergeHyperlink(true).copyHyperlink(false).build(); - destCell.copyCellFrom(srcCell, policy); - assertNull(srcCell.getHyperlink()); - assertNotNull(destCell.getHyperlink()); - assertSame(link, destCell.getHyperlink()); - - List links; - links = srcCell.getSheet().getHyperlinkList(); - assertEquals("number of hyperlinks on sheet", 1, links.size()); - assertEquals("source hyperlink", - new CellReference(destCell).formatAsString(), links.get(0).getCellRef()); - - // Merge destCell's hyperlink to srcCell. Since destCell does have a hyperlink, this should copy destCell's hyperlink to srcCell. - srcCell.copyCellFrom(destCell, policy); - assertNotNull(srcCell.getHyperlink()); - assertNotNull(destCell.getHyperlink()); - - links = srcCell.getSheet().getHyperlinkList(); - assertEquals("number of hyperlinks on sheet", 2, links.size()); - assertEquals("dest hyperlink", - new CellReference(destCell).formatAsString(), links.get(0).getCellRef()); - assertEquals("source hyperlink", - new CellReference(srcCell).formatAsString(), links.get(1).getCellRef()); - - wb.close(); - } - - private void setUp_testCopyCellFrom_CellCopyPolicy() { - @SuppressWarnings("resource") - final XSSFWorkbook wb = new XSSFWorkbook(); - final XSSFRow row = wb.createSheet("Sheet1").createRow(0); - srcCell = row.createCell(0); - destCell = row.createCell(1); - - srcCell.setCellFormula("2+3"); - - final CellStyle style = wb.createCellStyle(); - style.setBorderTop(BorderStyle.THICK); - style.setFillBackgroundColor((short) 5); - srcCell.setCellStyle(style); - - destCell.setCellValue(true); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFCellStyle.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFCellStyle.java deleted file mode 100644 index c907d40db..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFCellStyle.java +++ /dev/null @@ -1,1065 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFCellStyle; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.*; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.model.StylesTable; -import org.apache.poi.xssf.usermodel.extensions.XSSFCellBorder; -import org.apache.poi.xssf.usermodel.extensions.XSSFCellFill; -import org.junit.Before; -import org.junit.Test; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTBorder; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCellXfs; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTFill; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTFont; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTStylesheet; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTXf; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STBorderStyle; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STHorizontalAlignment; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STPatternType; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STVerticalAlignment; - -public class TestXSSFCellStyle { - private StylesTable stylesTable; - private CTBorder ctBorderA; - private CTFill ctFill; - private CTFont ctFont; - private CTXf cellStyleXf; - private CTXf cellXf; - private CTCellXfs cellXfs; - private XSSFCellStyle cellStyle; - private CTStylesheet ctStylesheet; - - @Before - public void setUp() { - stylesTable = new StylesTable(); - - ctStylesheet = stylesTable.getCTStylesheet(); - - ctBorderA = CTBorder.Factory.newInstance(); - XSSFCellBorder borderA = new XSSFCellBorder(ctBorderA); - long borderId = stylesTable.putBorder(borderA); - assertEquals(1, borderId); - - XSSFCellBorder borderB = new XSSFCellBorder(); - assertEquals(1, stylesTable.putBorder(borderB)); - - ctFill = CTFill.Factory.newInstance(); - XSSFCellFill fill = new XSSFCellFill(ctFill); - long fillId = stylesTable.putFill(fill); - assertEquals(2, fillId); - - ctFont = CTFont.Factory.newInstance(); - XSSFFont font = new XSSFFont(ctFont); - long fontId = stylesTable.putFont(font); - assertEquals(1, fontId); - - cellStyleXf = ctStylesheet.addNewCellStyleXfs().addNewXf(); - cellStyleXf.setBorderId(1); - cellStyleXf.setFillId(1); - cellStyleXf.setFontId(1); - - cellXfs = ctStylesheet.addNewCellXfs(); - cellXf = cellXfs.addNewXf(); - cellXf.setXfId(1); - cellXf.setBorderId(1); - cellXf.setFillId(1); - cellXf.setFontId(1); - stylesTable.putCellStyleXf(cellStyleXf); - stylesTable.putCellXf(cellXf); - cellStyle = new XSSFCellStyle(1, 1, stylesTable, null); - - assertNotNull(stylesTable.getFillAt(1).getCTFill().getPatternFill()); - assertEquals(STPatternType.INT_DARK_GRAY, stylesTable.getFillAt(1).getCTFill().getPatternFill().getPatternType().intValue()); - } - - @Test - public void testGetSetBorderBottom() { - //default values - assertEquals(BorderStyle.NONE, cellStyle.getBorderBottomEnum()); - - int num = stylesTable.getBorders().size(); - cellStyle.setBorderBottom(BorderStyle.MEDIUM); - assertEquals(BorderStyle.MEDIUM, cellStyle.getBorderBottomEnum()); - //a new border has been added - assertEquals(num + 1, stylesTable.getBorders().size()); - //id of the created border - int borderId = (int)cellStyle.getCoreXf().getBorderId(); - assertTrue(borderId > 0); - //check changes in the underlying xml bean - CTBorder ctBorder = stylesTable.getBorderAt(borderId).getCTBorder(); - assertEquals(STBorderStyle.MEDIUM, ctBorder.getBottom().getStyle()); - - num = stylesTable.getBorders().size(); - //setting the same border multiple times should not change borderId - for (int i = 0; i < 3; i++) { - cellStyle.setBorderBottom(BorderStyle.MEDIUM); - assertEquals(BorderStyle.MEDIUM, cellStyle.getBorderBottomEnum()); - } - assertEquals(borderId, cellStyle.getCoreXf().getBorderId()); - assertEquals(num, stylesTable.getBorders().size()); - assertSame(ctBorder, stylesTable.getBorderAt(borderId).getCTBorder()); - - //setting border to none removes the element - cellStyle.setBorderBottom(BorderStyle.NONE); - assertEquals(num, stylesTable.getBorders().size()); - borderId = (int)cellStyle.getCoreXf().getBorderId(); - ctBorder = stylesTable.getBorderAt(borderId).getCTBorder(); - assertFalse(ctBorder.isSetBottom()); - } - - @Test - public void testGetSetBorderRight() { - //default values - assertEquals(BorderStyle.NONE, cellStyle.getBorderRightEnum()); - - int num = stylesTable.getBorders().size(); - cellStyle.setBorderRight(BorderStyle.MEDIUM); - assertEquals(BorderStyle.MEDIUM, cellStyle.getBorderRightEnum()); - //a new border has been added - assertEquals(num + 1, stylesTable.getBorders().size()); - //id of the created border - int borderId = (int)cellStyle.getCoreXf().getBorderId(); - assertTrue(borderId > 0); - //check changes in the underlying xml bean - CTBorder ctBorder = stylesTable.getBorderAt(borderId).getCTBorder(); - assertEquals(STBorderStyle.MEDIUM, ctBorder.getRight().getStyle()); - - num = stylesTable.getBorders().size(); - //setting the same border multiple times should not change borderId - for (int i = 0; i < 3; i++) { - cellStyle.setBorderRight(BorderStyle.MEDIUM); - assertEquals(BorderStyle.MEDIUM, cellStyle.getBorderRightEnum()); - } - assertEquals(borderId, cellStyle.getCoreXf().getBorderId()); - assertEquals(num, stylesTable.getBorders().size()); - assertSame(ctBorder, stylesTable.getBorderAt(borderId).getCTBorder()); - - //setting border to none removes the element - cellStyle.setBorderRight(BorderStyle.NONE); - assertEquals(num, stylesTable.getBorders().size()); - borderId = (int)cellStyle.getCoreXf().getBorderId(); - ctBorder = stylesTable.getBorderAt(borderId).getCTBorder(); - assertFalse(ctBorder.isSetRight()); - } - - @Test - public void testGetSetBorderLeft() { - //default values - assertEquals(BorderStyle.NONE, cellStyle.getBorderLeftEnum()); - - int num = stylesTable.getBorders().size(); - cellStyle.setBorderLeft(BorderStyle.MEDIUM); - assertEquals(BorderStyle.MEDIUM, cellStyle.getBorderLeftEnum()); - //a new border has been added - assertEquals(num + 1, stylesTable.getBorders().size()); - //id of the created border - int borderId = (int)cellStyle.getCoreXf().getBorderId(); - assertTrue(borderId > 0); - //check changes in the underlying xml bean - CTBorder ctBorder = stylesTable.getBorderAt(borderId).getCTBorder(); - assertEquals(STBorderStyle.MEDIUM, ctBorder.getLeft().getStyle()); - - num = stylesTable.getBorders().size(); - //setting the same border multiple times should not change borderId - for (int i = 0; i < 3; i++) { - cellStyle.setBorderLeft(BorderStyle.MEDIUM); - assertEquals(BorderStyle.MEDIUM, cellStyle.getBorderLeftEnum()); - } - assertEquals(borderId, cellStyle.getCoreXf().getBorderId()); - assertEquals(num, stylesTable.getBorders().size()); - assertSame(ctBorder, stylesTable.getBorderAt(borderId).getCTBorder()); - - //setting border to none removes the element - cellStyle.setBorderLeft(BorderStyle.NONE); - assertEquals(num, stylesTable.getBorders().size()); - borderId = (int)cellStyle.getCoreXf().getBorderId(); - ctBorder = stylesTable.getBorderAt(borderId).getCTBorder(); - assertFalse(ctBorder.isSetLeft()); - } - - @Test - public void testGetSetBorderTop() { - //default values - assertEquals(BorderStyle.NONE, cellStyle.getBorderTopEnum()); - - int num = stylesTable.getBorders().size(); - cellStyle.setBorderTop(BorderStyle.MEDIUM); - assertEquals(BorderStyle.MEDIUM, cellStyle.getBorderTopEnum()); - //a new border has been added - assertEquals(num + 1, stylesTable.getBorders().size()); - //id of the created border - int borderId = (int)cellStyle.getCoreXf().getBorderId(); - assertTrue(borderId > 0); - //check changes in the underlying xml bean - CTBorder ctBorder = stylesTable.getBorderAt(borderId).getCTBorder(); - assertEquals(STBorderStyle.MEDIUM, ctBorder.getTop().getStyle()); - - num = stylesTable.getBorders().size(); - //setting the same border multiple times should not change borderId - for (int i = 0; i < 3; i++) { - cellStyle.setBorderTop(BorderStyle.MEDIUM); - assertEquals(BorderStyle.MEDIUM, cellStyle.getBorderTopEnum()); - } - assertEquals(borderId, cellStyle.getCoreXf().getBorderId()); - assertEquals(num, stylesTable.getBorders().size()); - assertSame(ctBorder, stylesTable.getBorderAt(borderId).getCTBorder()); - - //setting border to none removes the element - cellStyle.setBorderTop(BorderStyle.NONE); - assertEquals(num, stylesTable.getBorders().size()); - borderId = (int)cellStyle.getCoreXf().getBorderId(); - ctBorder = stylesTable.getBorderAt(borderId).getCTBorder(); - assertFalse(ctBorder.isSetTop()); - } - - private void testGetSetBorderXMLBean(BorderStyle border, STBorderStyle.Enum expected) { - cellStyle.setBorderTop(border); - assertEquals(border, cellStyle.getBorderTopEnum()); - int borderId = (int)cellStyle.getCoreXf().getBorderId(); - assertTrue(borderId > 0); - //check changes in the underlying xml bean - CTBorder ctBorder = stylesTable.getBorderAt(borderId).getCTBorder(); - assertEquals(expected, ctBorder.getTop().getStyle()); - } - - - // Border Styles, in BorderStyle/STBorderStyle enum order - @Test - public void testGetSetBorderNone() { - cellStyle.setBorderTop(BorderStyle.NONE); - assertEquals(BorderStyle.NONE, cellStyle.getBorderTopEnum()); - int borderId = (int)cellStyle.getCoreXf().getBorderId(); - assertTrue(borderId > 0); - //check changes in the underlying xml bean - CTBorder ctBorder = stylesTable.getBorderAt(borderId).getCTBorder(); - assertNull(ctBorder.getTop()); - // no border style and STBorderStyle.NONE are equivalent - // POI prefers to unset the border style than explicitly set it STBorderStyle.NONE - } - - @Test - public void testGetSetBorderThin() { - testGetSetBorderXMLBean(BorderStyle.THIN, STBorderStyle.THIN); - } - - @Test - public void testGetSetBorderMedium() { - testGetSetBorderXMLBean(BorderStyle.MEDIUM, STBorderStyle.MEDIUM); - } - - @Test - public void testGetSetBorderDashed() { - testGetSetBorderXMLBean(BorderStyle.DASHED, STBorderStyle.DASHED); - } - - @Test - public void testGetSetBorderDotted() { - testGetSetBorderXMLBean(BorderStyle.DOTTED, STBorderStyle.DOTTED); - } - - @Test - public void testGetSetBorderThick() { - testGetSetBorderXMLBean(BorderStyle.THICK, STBorderStyle.THICK); - } - - @Test - public void testGetSetBorderDouble() { - testGetSetBorderXMLBean(BorderStyle.DOUBLE, STBorderStyle.DOUBLE); - } - - @Test - public void testGetSetBorderHair() { - testGetSetBorderXMLBean(BorderStyle.HAIR, STBorderStyle.HAIR); - } - - @Test - public void testGetSetBorderMediumDashed() { - testGetSetBorderXMLBean(BorderStyle.MEDIUM_DASHED, STBorderStyle.MEDIUM_DASHED); - } - - @Test - public void testGetSetBorderDashDot() { - testGetSetBorderXMLBean(BorderStyle.DASH_DOT, STBorderStyle.DASH_DOT); - } - - @Test - public void testGetSetBorderMediumDashDot() { - testGetSetBorderXMLBean(BorderStyle.MEDIUM_DASH_DOT, STBorderStyle.MEDIUM_DASH_DOT); - } - - @Test - public void testGetSetBorderDashDotDot() { - testGetSetBorderXMLBean(BorderStyle.DASH_DOT_DOT, STBorderStyle.DASH_DOT_DOT); - } - - @Test - public void testGetSetBorderMediumDashDotDot() { - testGetSetBorderXMLBean(BorderStyle.MEDIUM_DASH_DOT_DOT, STBorderStyle.MEDIUM_DASH_DOT_DOT); - } - - @Test - public void testGetSetBorderSlantDashDot() { - testGetSetBorderXMLBean(BorderStyle.SLANTED_DASH_DOT, STBorderStyle.SLANT_DASH_DOT); - } - - @Test - public void testGetSetBottomBorderColor() { - //defaults - assertEquals(IndexedColors.BLACK.getIndex(), cellStyle.getBottomBorderColor()); - assertNull(cellStyle.getBottomBorderXSSFColor()); - - int num = stylesTable.getBorders().size(); - - XSSFColor clr; - - //setting indexed color - cellStyle.setBottomBorderColor(IndexedColors.BLUE_GREY.getIndex()); - assertEquals(IndexedColors.BLUE_GREY.getIndex(), cellStyle.getBottomBorderColor()); - clr = cellStyle.getBottomBorderXSSFColor(); - assertTrue(clr.getCTColor().isSetIndexed()); - assertEquals(IndexedColors.BLUE_GREY.getIndex(), clr.getIndexed()); - //a new border was added to the styles table - assertEquals(num + 1, stylesTable.getBorders().size()); - - //id of the created border - int borderId = (int)cellStyle.getCoreXf().getBorderId(); - assertTrue(borderId > 0); - //check changes in the underlying xml bean - CTBorder ctBorder = stylesTable.getBorderAt(borderId).getCTBorder(); - assertEquals(IndexedColors.BLUE_GREY.getIndex(), ctBorder.getBottom().getColor().getIndexed()); - - //setting XSSFColor - num = stylesTable.getBorders().size(); - clr = new XSSFColor(java.awt.Color.CYAN); - cellStyle.setBottomBorderColor(clr); - assertEquals(clr.getCTColor().toString(), cellStyle.getBottomBorderXSSFColor().getCTColor().toString()); - byte[] rgb = cellStyle.getBottomBorderXSSFColor().getRGB(); - assertEquals(java.awt.Color.CYAN, new java.awt.Color(rgb[0] & 0xFF, rgb[1] & 0xFF, rgb[2] & 0xFF)); - //another border was added to the styles table - assertEquals(num + 1, stylesTable.getBorders().size()); - - //passing null unsets the color - cellStyle.setBottomBorderColor(null); - assertNull(cellStyle.getBottomBorderXSSFColor()); - } - - @Test - public void testGetSetTopBorderColor() { - //defaults - assertEquals(IndexedColors.BLACK.getIndex(), cellStyle.getTopBorderColor()); - assertNull(cellStyle.getTopBorderXSSFColor()); - - int num = stylesTable.getBorders().size(); - - XSSFColor clr; - - //setting indexed color - cellStyle.setTopBorderColor(IndexedColors.BLUE_GREY.getIndex()); - assertEquals(IndexedColors.BLUE_GREY.getIndex(), cellStyle.getTopBorderColor()); - clr = cellStyle.getTopBorderXSSFColor(); - assertTrue(clr.getCTColor().isSetIndexed()); - assertEquals(IndexedColors.BLUE_GREY.getIndex(), clr.getIndexed()); - //a new border was added to the styles table - assertEquals(num + 1, stylesTable.getBorders().size()); - - //id of the created border - int borderId = (int)cellStyle.getCoreXf().getBorderId(); - assertTrue(borderId > 0); - //check changes in the underlying xml bean - CTBorder ctBorder = stylesTable.getBorderAt(borderId).getCTBorder(); - assertEquals(IndexedColors.BLUE_GREY.getIndex(), ctBorder.getTop().getColor().getIndexed()); - - //setting XSSFColor - num = stylesTable.getBorders().size(); - clr = new XSSFColor(java.awt.Color.CYAN); - cellStyle.setTopBorderColor(clr); - assertEquals(clr.getCTColor().toString(), cellStyle.getTopBorderXSSFColor().getCTColor().toString()); - byte[] rgb = cellStyle.getTopBorderXSSFColor().getRGB(); - assertEquals(java.awt.Color.CYAN, new java.awt.Color(rgb[0] & 0xFF, rgb[1] & 0xFF, rgb[2] & 0xFF)); - //another border was added to the styles table - assertEquals(num + 1, stylesTable.getBorders().size()); - - //passing null unsets the color - cellStyle.setTopBorderColor(null); - assertNull(cellStyle.getTopBorderXSSFColor()); - } - - @Test - public void testGetSetLeftBorderColor() { - //defaults - assertEquals(IndexedColors.BLACK.getIndex(), cellStyle.getLeftBorderColor()); - assertNull(cellStyle.getLeftBorderXSSFColor()); - - int num = stylesTable.getBorders().size(); - - XSSFColor clr; - - //setting indexed color - cellStyle.setLeftBorderColor(IndexedColors.BLUE_GREY.getIndex()); - assertEquals(IndexedColors.BLUE_GREY.getIndex(), cellStyle.getLeftBorderColor()); - clr = cellStyle.getLeftBorderXSSFColor(); - assertTrue(clr.getCTColor().isSetIndexed()); - assertEquals(IndexedColors.BLUE_GREY.getIndex(), clr.getIndexed()); - //a new border was added to the styles table - assertEquals(num + 1, stylesTable.getBorders().size()); - - //id of the created border - int borderId = (int)cellStyle.getCoreXf().getBorderId(); - assertTrue(borderId > 0); - //check changes in the underlying xml bean - CTBorder ctBorder = stylesTable.getBorderAt(borderId).getCTBorder(); - assertEquals(IndexedColors.BLUE_GREY.getIndex(), ctBorder.getLeft().getColor().getIndexed()); - - //setting XSSFColor - num = stylesTable.getBorders().size(); - clr = new XSSFColor(java.awt.Color.CYAN); - cellStyle.setLeftBorderColor(clr); - assertEquals(clr.getCTColor().toString(), cellStyle.getLeftBorderXSSFColor().getCTColor().toString()); - byte[] rgb = cellStyle.getLeftBorderXSSFColor().getRGB(); - assertEquals(java.awt.Color.CYAN, new java.awt.Color(rgb[0] & 0xFF, rgb[1] & 0xFF, rgb[2] & 0xFF)); - //another border was added to the styles table - assertEquals(num + 1, stylesTable.getBorders().size()); - - //passing null unsets the color - cellStyle.setLeftBorderColor(null); - assertNull(cellStyle.getLeftBorderXSSFColor()); - } - - @Test - public void testGetSetRightBorderColor() { - //defaults - assertEquals(IndexedColors.BLACK.getIndex(), cellStyle.getRightBorderColor()); - assertNull(cellStyle.getRightBorderXSSFColor()); - - int num = stylesTable.getBorders().size(); - - XSSFColor clr; - - //setting indexed color - cellStyle.setRightBorderColor(IndexedColors.BLUE_GREY.getIndex()); - assertEquals(IndexedColors.BLUE_GREY.getIndex(), cellStyle.getRightBorderColor()); - clr = cellStyle.getRightBorderXSSFColor(); - assertTrue(clr.getCTColor().isSetIndexed()); - assertEquals(IndexedColors.BLUE_GREY.getIndex(), clr.getIndexed()); - //a new border was added to the styles table - assertEquals(num + 1, stylesTable.getBorders().size()); - - //id of the created border - int borderId = (int)cellStyle.getCoreXf().getBorderId(); - assertTrue(borderId > 0); - //check changes in the underlying xml bean - CTBorder ctBorder = stylesTable.getBorderAt(borderId).getCTBorder(); - assertEquals(IndexedColors.BLUE_GREY.getIndex(), ctBorder.getRight().getColor().getIndexed()); - - //setting XSSFColor - num = stylesTable.getBorders().size(); - clr = new XSSFColor(java.awt.Color.CYAN); - cellStyle.setRightBorderColor(clr); - assertEquals(clr.getCTColor().toString(), cellStyle.getRightBorderXSSFColor().getCTColor().toString()); - byte[] rgb = cellStyle.getRightBorderXSSFColor().getRGB(); - assertEquals(java.awt.Color.CYAN, new java.awt.Color(rgb[0] & 0xFF, rgb[1] & 0xFF, rgb[2] & 0xFF)); - //another border was added to the styles table - assertEquals(num + 1, stylesTable.getBorders().size()); - - //passing null unsets the color - cellStyle.setRightBorderColor(null); - assertNull(cellStyle.getRightBorderXSSFColor()); - } - - @Test - public void testGetSetFillBackgroundColor() { - - assertEquals(IndexedColors.AUTOMATIC.getIndex(), cellStyle.getFillBackgroundColor()); - assertNull(cellStyle.getFillBackgroundXSSFColor()); - - XSSFColor clr; - - int num = stylesTable.getFills().size(); - - //setting indexed color - cellStyle.setFillBackgroundColor(IndexedColors.RED.getIndex()); - assertEquals(IndexedColors.RED.getIndex(), cellStyle.getFillBackgroundColor()); - clr = cellStyle.getFillBackgroundXSSFColor(); - assertTrue(clr.getCTColor().isSetIndexed()); - assertEquals(IndexedColors.RED.getIndex(), clr.getIndexed()); - //a new fill was added to the styles table - assertEquals(num + 1, stylesTable.getFills().size()); - - //id of the created border - int fillId = (int)cellStyle.getCoreXf().getFillId(); - assertTrue(fillId > 0); - //check changes in the underlying xml bean - CTFill ctFill2 = stylesTable.getFillAt(fillId).getCTFill(); - assertEquals(IndexedColors.RED.getIndex(), ctFill2.getPatternFill().getBgColor().getIndexed()); - - //setting XSSFColor - num = stylesTable.getFills().size(); - clr = new XSSFColor(java.awt.Color.CYAN); - cellStyle.setFillBackgroundColor(clr); - assertEquals(clr.getCTColor().toString(), cellStyle.getFillBackgroundXSSFColor().getCTColor().toString()); - byte[] rgb = cellStyle.getFillBackgroundXSSFColor().getRGB(); - assertEquals(java.awt.Color.CYAN, new java.awt.Color(rgb[0] & 0xFF, rgb[1] & 0xFF, rgb[2] & 0xFF)); - //another border was added to the styles table - assertEquals(num + 1, stylesTable.getFills().size()); - - //passing null unsets the color - cellStyle.setFillBackgroundColor(null); - assertNull(cellStyle.getFillBackgroundXSSFColor()); - assertEquals(IndexedColors.AUTOMATIC.getIndex(), cellStyle.getFillBackgroundColor()); - } - - @Test - public void testDefaultStyles() throws IOException { - - XSSFWorkbook wb1 = new XSSFWorkbook(); - - XSSFCellStyle style1 = wb1.createCellStyle(); - assertEquals(IndexedColors.AUTOMATIC.getIndex(), style1.getFillBackgroundColor()); - assertNull(style1.getFillBackgroundXSSFColor()); - - assertNotNull(XSSFTestDataSamples.writeOutAndReadBack(wb1)); - wb1.close(); - - //compatibility with HSSF - HSSFWorkbook wb2 = new HSSFWorkbook(); - HSSFCellStyle style2 = wb2.createCellStyle(); - assertEquals(style2.getFillBackgroundColor(), style1.getFillBackgroundColor()); - assertEquals(style2.getFillForegroundColor(), style1.getFillForegroundColor()); - assertEquals(style2.getFillPatternEnum(), style1.getFillPatternEnum()); - assertEquals(style2.getFillPattern(), style1.getFillPattern()); - - assertEquals(style2.getLeftBorderColor(), style1.getLeftBorderColor()); - assertEquals(style2.getTopBorderColor(), style1.getTopBorderColor()); - assertEquals(style2.getRightBorderColor(), style1.getRightBorderColor()); - assertEquals(style2.getBottomBorderColor(), style1.getBottomBorderColor()); - - assertEquals(style2.getBorderBottomEnum(), style1.getBorderBottomEnum()); - assertEquals(style2.getBorderLeftEnum(), style1.getBorderLeftEnum()); - assertEquals(style2.getBorderRightEnum(), style1.getBorderRightEnum()); - assertEquals(style2.getBorderTopEnum(), style1.getBorderTopEnum()); - wb2.close(); - } - - @Test - public void testGetFillForegroundColor() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - StylesTable styles = wb.getStylesSource(); - assertEquals(1, wb.getNumCellStyles()); - assertEquals(2, styles.getFills().size()); - - XSSFCellStyle defaultStyle = wb.getCellStyleAt((short)0); - assertEquals(IndexedColors.AUTOMATIC.getIndex(), defaultStyle.getFillForegroundColor()); - assertEquals(null, defaultStyle.getFillForegroundXSSFColor()); - assertEquals(FillPatternType.NO_FILL, defaultStyle.getFillPatternEnum()); - assertEquals(CellStyle.NO_FILL, defaultStyle.getFillPattern()); - - XSSFCellStyle customStyle = wb.createCellStyle(); - - customStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); - assertEquals(FillPatternType.SOLID_FOREGROUND, customStyle.getFillPatternEnum()); - assertEquals(CellStyle.SOLID_FOREGROUND, customStyle.getFillPattern()); - assertEquals(3, styles.getFills().size()); - - customStyle.setFillForegroundColor(IndexedColors.BRIGHT_GREEN.getIndex()); - assertEquals(IndexedColors.BRIGHT_GREEN.getIndex(), customStyle.getFillForegroundColor()); - assertEquals(4, styles.getFills().size()); - - for (int i = 0; i < 3; i++) { - XSSFCellStyle style = wb.createCellStyle(); - - style.setFillPattern(FillPatternType.SOLID_FOREGROUND); - assertEquals(FillPatternType.SOLID_FOREGROUND, style.getFillPatternEnum()); - assertEquals(CellStyle.SOLID_FOREGROUND, style.getFillPattern()); - assertEquals(4, styles.getFills().size()); - - style.setFillForegroundColor(IndexedColors.BRIGHT_GREEN.getIndex()); - assertEquals(IndexedColors.BRIGHT_GREEN.getIndex(), style.getFillForegroundColor()); - assertEquals(4, styles.getFills().size()); - } - - assertNotNull(XSSFTestDataSamples.writeOutAndReadBack(wb)); - wb.close(); - } - - @Test - public void testGetFillPattern() { - - assertEquals(STPatternType.INT_DARK_GRAY-1, cellStyle.getFillPatternEnum().getCode()); - assertEquals(STPatternType.INT_DARK_GRAY-1, cellStyle.getFillPattern()); - - int num = stylesTable.getFills().size(); - cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); - assertEquals(FillPatternType.SOLID_FOREGROUND, cellStyle.getFillPatternEnum()); - assertEquals(CellStyle.SOLID_FOREGROUND, cellStyle.getFillPattern()); - assertEquals(num + 1, stylesTable.getFills().size()); - int fillId = (int)cellStyle.getCoreXf().getFillId(); - assertTrue(fillId > 0); - //check changes in the underlying xml bean - CTFill ctFill2 = stylesTable.getFillAt(fillId).getCTFill(); - assertEquals(STPatternType.SOLID, ctFill2.getPatternFill().getPatternType()); - - //setting the same fill multiple time does not update the styles table - for (int i = 0; i < 3; i++) { - cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); - } - assertEquals(num + 1, stylesTable.getFills().size()); - - cellStyle.setFillPattern(FillPatternType.NO_FILL); - assertEquals(FillPatternType.NO_FILL, cellStyle.getFillPatternEnum()); - assertEquals(CellStyle.NO_FILL, cellStyle.getFillPattern()); - fillId = (int)cellStyle.getCoreXf().getFillId(); - ctFill2 = stylesTable.getFillAt(fillId).getCTFill(); - assertFalse(ctFill2.getPatternFill().isSetPatternType()); - - } - - @Test - public void testGetFont() { - assertNotNull(cellStyle.getFont()); - } - - @Test - public void testGetSetHidden() { - assertFalse(cellStyle.getHidden()); - cellStyle.setHidden(true); - assertTrue(cellStyle.getHidden()); - cellStyle.setHidden(false); - assertFalse(cellStyle.getHidden()); - } - - @Test - public void testGetSetLocked() { - assertTrue(cellStyle.getLocked()); - cellStyle.setLocked(true); - assertTrue(cellStyle.getLocked()); - cellStyle.setLocked(false); - assertFalse(cellStyle.getLocked()); - } - - @Test - public void testGetSetIndent() { - assertEquals((short)0, cellStyle.getIndention()); - cellStyle.setIndention((short)3); - assertEquals((short)3, cellStyle.getIndention()); - cellStyle.setIndention((short) 13); - assertEquals((short)13, cellStyle.getIndention()); - } - - @Test - public void testGetSetAlignement() { - assertNull(cellStyle.getCellAlignment().getCTCellAlignment().getHorizontal()); - assertEquals(HorizontalAlignment.GENERAL, cellStyle.getAlignmentEnum()); - - cellStyle.setAlignment(XSSFCellStyle.ALIGN_LEFT); - assertEquals(XSSFCellStyle.ALIGN_LEFT, cellStyle.getAlignment()); - assertEquals(HorizontalAlignment.LEFT, cellStyle.getAlignmentEnum()); - assertEquals(STHorizontalAlignment.LEFT, cellStyle.getCellAlignment().getCTCellAlignment().getHorizontal()); - - cellStyle.setAlignment(HorizontalAlignment.JUSTIFY); - assertEquals(XSSFCellStyle.ALIGN_JUSTIFY, cellStyle.getAlignment()); - assertEquals(HorizontalAlignment.JUSTIFY, cellStyle.getAlignmentEnum()); - assertEquals(STHorizontalAlignment.JUSTIFY, cellStyle.getCellAlignment().getCTCellAlignment().getHorizontal()); - - cellStyle.setAlignment(HorizontalAlignment.CENTER); - assertEquals(XSSFCellStyle.ALIGN_CENTER, cellStyle.getAlignment()); - assertEquals(HorizontalAlignment.CENTER, cellStyle.getAlignmentEnum()); - assertEquals(STHorizontalAlignment.CENTER, cellStyle.getCellAlignment().getCTCellAlignment().getHorizontal()); - } - - @Test - public void testGetSetVerticalAlignment() { - assertEquals(VerticalAlignment.BOTTOM, cellStyle.getVerticalAlignmentEnum()); - assertEquals(XSSFCellStyle.VERTICAL_BOTTOM, cellStyle.getVerticalAlignment()); - assertNull(cellStyle.getCellAlignment().getCTCellAlignment().getVertical()); - - cellStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER); - assertEquals(XSSFCellStyle.VERTICAL_CENTER, cellStyle.getVerticalAlignment()); - assertEquals(VerticalAlignment.CENTER, cellStyle.getVerticalAlignmentEnum()); - assertEquals(STVerticalAlignment.CENTER, cellStyle.getCellAlignment().getCTCellAlignment().getVertical()); - - cellStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_JUSTIFY); - assertEquals(XSSFCellStyle.VERTICAL_JUSTIFY, cellStyle.getVerticalAlignment()); - assertEquals(VerticalAlignment.JUSTIFY, cellStyle.getVerticalAlignmentEnum()); - assertEquals(STVerticalAlignment.JUSTIFY, cellStyle.getCellAlignment().getCTCellAlignment().getVertical()); - } - - @Test - public void testGetSetWrapText() { - assertFalse(cellStyle.getWrapText()); - cellStyle.setWrapText(true); - assertTrue(cellStyle.getWrapText()); - cellStyle.setWrapText(false); - assertFalse(cellStyle.getWrapText()); - } - - /** - * Cloning one XSSFCellStyle onto Another, same XSSFWorkbook - */ - @Test - public void testCloneStyleSameWB() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - assertEquals(1, wb.getNumberOfFonts()); - - XSSFFont fnt = wb.createFont(); - fnt.setFontName("TestingFont"); - assertEquals(2, wb.getNumberOfFonts()); - - XSSFCellStyle orig = wb.createCellStyle(); - orig.setAlignment(CellStyle.ALIGN_RIGHT); - orig.setFont(fnt); - orig.setDataFormat((short)18); - - assertTrue(CellStyle.ALIGN_RIGHT == orig.getAlignment()); - assertTrue(fnt == orig.getFont()); - assertTrue(18 == orig.getDataFormat()); - - XSSFCellStyle clone = wb.createCellStyle(); - assertFalse(CellStyle.ALIGN_RIGHT == clone.getAlignment()); - assertFalse(fnt == clone.getFont()); - assertFalse(18 == clone.getDataFormat()); - - clone.cloneStyleFrom(orig); - assertTrue(CellStyle.ALIGN_RIGHT == clone.getAlignment()); - assertTrue(fnt == clone.getFont()); - assertTrue(18 == clone.getDataFormat()); - assertEquals(2, wb.getNumberOfFonts()); - - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb); - assertNotNull(wb2); - wb2.close(); - - wb.close(); - } - - /** - * Cloning one XSSFCellStyle onto Another, different XSSFWorkbooks - */ - @Test - public void testCloneStyleDiffWB() throws IOException { - XSSFWorkbook wbOrig = new XSSFWorkbook(); - assertEquals(1, wbOrig.getNumberOfFonts()); - assertEquals(0, wbOrig.getStylesSource().getNumberFormats().size()); - - XSSFFont fnt = wbOrig.createFont(); - fnt.setFontName("TestingFont"); - assertEquals(2, wbOrig.getNumberOfFonts()); - assertEquals(0, wbOrig.getStylesSource().getNumberFormats().size()); - - XSSFDataFormat fmt = wbOrig.createDataFormat(); - fmt.getFormat("MadeUpOne"); - fmt.getFormat("MadeUpTwo"); - - XSSFCellStyle orig = wbOrig.createCellStyle(); - orig.setAlignment(HSSFCellStyle.ALIGN_RIGHT); - orig.setFont(fnt); - orig.setDataFormat(fmt.getFormat("Test##")); - - assertTrue(XSSFCellStyle.ALIGN_RIGHT == orig.getAlignment()); - assertTrue(fnt == orig.getFont()); - assertTrue(fmt.getFormat("Test##") == orig.getDataFormat()); - - assertEquals(2, wbOrig.getNumberOfFonts()); - assertEquals(3, wbOrig.getStylesSource().getNumberFormats().size()); - - - // Now a style on another workbook - XSSFWorkbook wbClone = new XSSFWorkbook(); - assertEquals(1, wbClone.getNumberOfFonts()); - assertEquals(0, wbClone.getStylesSource().getNumberFormats().size()); - assertEquals(1, wbClone.getNumCellStyles()); - - XSSFDataFormat fmtClone = wbClone.createDataFormat(); - XSSFCellStyle clone = wbClone.createCellStyle(); - - assertEquals(1, wbClone.getNumberOfFonts()); - assertEquals(0, wbClone.getStylesSource().getNumberFormats().size()); - - assertFalse(HSSFCellStyle.ALIGN_RIGHT == clone.getAlignment()); - assertNotEquals("TestingFont", clone.getFont().getFontName()); - - clone.cloneStyleFrom(orig); - - assertEquals(2, wbClone.getNumberOfFonts()); - assertEquals(2, wbClone.getNumCellStyles()); - assertEquals(1, wbClone.getStylesSource().getNumberFormats().size()); - - assertEquals(HSSFCellStyle.ALIGN_RIGHT, clone.getAlignment()); - assertEquals("TestingFont", clone.getFont().getFontName()); - assertEquals(fmtClone.getFormat("Test##"), clone.getDataFormat()); - assertFalse(fmtClone.getFormat("Test##") == fmt.getFormat("Test##")); - - // Save it and re-check - XSSFWorkbook wbReload = XSSFTestDataSamples.writeOutAndReadBack(wbClone); - assertEquals(2, wbReload.getNumberOfFonts()); - assertEquals(2, wbReload.getNumCellStyles()); - assertEquals(1, wbReload.getStylesSource().getNumberFormats().size()); - - XSSFCellStyle reload = wbReload.getCellStyleAt((short)1); - assertEquals(HSSFCellStyle.ALIGN_RIGHT, reload.getAlignment()); - assertEquals("TestingFont", reload.getFont().getFontName()); - assertEquals(fmtClone.getFormat("Test##"), reload.getDataFormat()); - assertFalse(fmtClone.getFormat("Test##") == fmt.getFormat("Test##")); - - XSSFWorkbook wbOrig2 = XSSFTestDataSamples.writeOutAndReadBack(wbOrig); - assertNotNull(wbOrig2); - wbOrig2.close(); - - XSSFWorkbook wbClone2 = XSSFTestDataSamples.writeOutAndReadBack(wbClone); - assertNotNull(wbClone2); - wbClone2.close(); - - wbReload.close(); - wbClone.close(); - wbOrig.close(); - } - - /** - * Avoid ArrayIndexOutOfBoundsException when creating cell style - * in a workbook that has an empty xf table. - */ - @Test - public void testBug52348() throws IOException { - XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("52348.xlsx"); - StylesTable st = workbook.getStylesSource(); - assertEquals(0, st._getStyleXfsSize()); - - XSSFCellStyle style = workbook.createCellStyle(); // no exception at this point - assertNull(style.getStyleXf()); - - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(workbook); - assertNotNull(wb2); - wb2.close(); - workbook.close(); - } - - /** - * Avoid ArrayIndexOutOfBoundsException when getting cell style - * in a workbook that has an empty xf table. - */ - @Test - public void testBug55650() throws IOException { - XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("52348.xlsx"); - StylesTable st = workbook.getStylesSource(); - assertEquals(0, st._getStyleXfsSize()); - - // no exception at this point - XSSFCellStyle style = workbook.getSheetAt(0).getRow(0).getCell(0).getCellStyle(); - assertNull(style.getStyleXf()); - - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(workbook); - assertNotNull(wb2); - wb2.close(); - - workbook.close(); - } - - @Test - public void testShrinkToFit() throws IOException { - // Existing file - XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("ShrinkToFit.xlsx"); - Sheet s = wb1.getSheetAt(0); - Row r = s.getRow(0); - CellStyle cs = r.getCell(0).getCellStyle(); - - assertEquals(true, cs.getShrinkToFit()); - - // New file - XSSFWorkbook wb2 = new XSSFWorkbook(); - s = wb2.createSheet(); - r = s.createRow(0); - - cs = wb2.createCellStyle(); - cs.setShrinkToFit(false); - r.createCell(0).setCellStyle(cs); - - cs = wb2.createCellStyle(); - cs.setShrinkToFit(true); - r.createCell(1).setCellStyle(cs); - - // Write out, read, and check - XSSFWorkbook wb3 = XSSFTestDataSamples.writeOutAndReadBack(wb2); - s = wb3.getSheetAt(0); - r = s.getRow(0); - assertEquals(false, r.getCell(0).getCellStyle().getShrinkToFit()); - assertEquals(true, r.getCell(1).getCellStyle().getShrinkToFit()); - - XSSFWorkbook wb4 = XSSFTestDataSamples.writeOutAndReadBack(wb2); - assertNotNull(wb4); - wb4.close(); - - XSSFWorkbook wb5 = XSSFTestDataSamples.writeOutAndReadBack(wb3); - assertNotNull(wb5); - wb5.close(); - - wb3.close(); - wb2.close(); - wb1.close(); - - } - - @Test - public void testSetColor() throws IOException { - Workbook wb = new XSSFWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - - DataFormat format = wb.createDataFormat(); - Cell cell = row.createCell(1); - cell.setCellValue("somevalue"); - CellStyle cellStyle2 = wb.createCellStyle(); - - - cellStyle2.setDataFormat(format.getFormat("###0")); - - cellStyle2.setFillBackgroundColor(IndexedColors.DARK_BLUE.getIndex()); - cellStyle2.setFillForegroundColor(IndexedColors.DARK_BLUE.getIndex()); - cellStyle2.setFillPattern(FillPatternType.SOLID_FOREGROUND); - - cellStyle2.setAlignment(CellStyle.ALIGN_RIGHT); - cellStyle2.setVerticalAlignment(CellStyle.VERTICAL_TOP); - - cell.setCellStyle(cellStyle2); - - Workbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb); - Cell cellBack = wbBack.getSheetAt(0).getRow(0).getCell(1); - assertNotNull(cellBack); - CellStyle styleBack = cellBack.getCellStyle(); - assertEquals(IndexedColors.DARK_BLUE.getIndex(), styleBack.getFillBackgroundColor()); - assertEquals(IndexedColors.DARK_BLUE.getIndex(), styleBack.getFillForegroundColor()); - assertEquals(CellStyle.ALIGN_RIGHT, styleBack.getAlignment()); - assertEquals(CellStyle.VERTICAL_TOP, styleBack.getVerticalAlignment()); - assertEquals(FillPatternType.SOLID_FOREGROUND, styleBack.getFillPatternEnum()); - assertEquals(CellStyle.SOLID_FOREGROUND, styleBack.getFillPattern()); - - wbBack.close(); - - wb.close(); - } - - public static void copyStyles(Workbook reference, Workbook target) { - final int numberOfStyles = reference.getNumCellStyles(); - // don't copy default style (style index 0) - for (int i = 1; i < numberOfStyles; i++) { - final CellStyle referenceStyle = reference.getCellStyleAt(i); - final CellStyle targetStyle = target.createCellStyle(); - targetStyle.cloneStyleFrom(referenceStyle); - } - /*System.out.println("Reference : "+reference.getNumCellStyles()); - System.out.println("Target : "+target.getNumCellStyles());*/ - } - - @Test - public void test58084() throws IOException { - Workbook reference = XSSFTestDataSamples.openSampleWorkbook("template.xlsx"); - Workbook target = new XSSFWorkbook(); - copyStyles(reference, target); - - assertEquals(reference.getNumCellStyles(), target.getNumCellStyles()); - final Sheet sheet = target.createSheet(); - final Row row = sheet.createRow(0); - int col = 0; - for (short i = 1; i < target.getNumCellStyles(); i++) { - final Cell cell = row.createCell(col++); - cell.setCellValue("Coucou"+i); - cell.setCellStyle(target.getCellStyleAt(i)); - } - /*OutputStream out = new FileOutputStream("C:\\temp\\58084.xlsx"); - target.write(out); - out.close();*/ - - Workbook copy = XSSFTestDataSamples.writeOutAndReadBack(target); - - // previously this failed because the border-element was not copied over - copy.getCellStyleAt((short)1).getBorderBottomEnum(); - - copy.close(); - - target.close(); - reference.close(); - } - - @Test - public void test58043() { - assertEquals(0, cellStyle.getRotation()); - - cellStyle.setRotation((short)89); - assertEquals(89, cellStyle.getRotation()); - - cellStyle.setRotation((short)90); - assertEquals(90, cellStyle.getRotation()); - - cellStyle.setRotation((short)179); - assertEquals(179, cellStyle.getRotation()); - - cellStyle.setRotation((short)180); - assertEquals(180, cellStyle.getRotation()); - - // negative values are mapped to the correct values for compatibility between HSSF and XSSF - cellStyle.setRotation((short)-1); - assertEquals(91, cellStyle.getRotation()); - - cellStyle.setRotation((short)-89); - assertEquals(179, cellStyle.getRotation()); - - cellStyle.setRotation((short)-90); - assertEquals(180, cellStyle.getRotation()); - } - - @Test - public void bug58996_UsedToWorkIn3_11_ButNotIn3_13() throws IOException { - XSSFWorkbook workbook = new XSSFWorkbook(); - - XSSFCellStyle cellStyle = workbook.createCellStyle(); - cellStyle.setFillForegroundColor(null); - assertNull(cellStyle.getFillForegroundColorColor()); - - cellStyle.setFillBackgroundColor(null); - assertNull(cellStyle.getFillBackgroundColorColor()); - - cellStyle.setFillPattern(FillPatternType.NO_FILL); - assertEquals(FillPatternType.NO_FILL, cellStyle.getFillPatternEnum()); - - cellStyle.setBottomBorderColor(null); - assertNull(cellStyle.getBottomBorderXSSFColor()); - - cellStyle.setTopBorderColor(null); - assertNull(cellStyle.getTopBorderXSSFColor()); - - cellStyle.setLeftBorderColor(null); - assertNull(cellStyle.getLeftBorderXSSFColor()); - - cellStyle.setRightBorderColor(null); - assertNull(cellStyle.getRightBorderXSSFColor()); - - workbook.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFChart.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFChart.java deleted file mode 100644 index f033e8ed4..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFChart.java +++ /dev/null @@ -1,81 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import junit.framework.TestCase; - -import org.apache.poi.xssf.XSSFTestDataSamples; - -public final class TestXSSFChart extends TestCase { - - public void testGetAccessors() { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("WithThreeCharts.xlsx"); - XSSFSheet s1 = wb.getSheetAt(0); - XSSFSheet s2 = wb.getSheetAt(1); - XSSFSheet s3 = wb.getSheetAt(2); - - assertEquals(0, s1.getRelations().size()); - assertEquals(1, s2.getRelations().size()); - assertEquals(1, s3.getRelations().size()); - - assertNotNull(XSSFTestDataSamples.writeOutAndReadBack(wb)); - } - - public void testGetCharts() throws Exception { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("WithThreeCharts.xlsx"); - - XSSFSheet s1 = wb.getSheetAt(0); - XSSFSheet s2 = wb.getSheetAt(1); - XSSFSheet s3 = wb.getSheetAt(2); - - assertEquals(0, s1.createDrawingPatriarch().getCharts().size()); - assertEquals(2, s2.createDrawingPatriarch().getCharts().size()); - assertEquals(1, s3.createDrawingPatriarch().getCharts().size()); - - // Check the titles - XSSFChart chart = s2.createDrawingPatriarch().getCharts().get(0); - assertEquals(null, chart.getTitleText()); - - chart = s2.createDrawingPatriarch().getCharts().get(1); - assertEquals("Pie Chart Title Thingy", chart.getTitleText().getString()); - - chart = s3.createDrawingPatriarch().getCharts().get(0); - assertEquals("Sheet 3 Chart with Title", chart.getTitleText().getString()); - - assertNotNull(XSSFTestDataSamples.writeOutAndReadBack(wb)); - } - - public void testAddChartsToNewWorkbook() throws Exception { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet s1 = wb.createSheet(); - XSSFDrawing d1 = s1.createDrawingPatriarch(); - XSSFClientAnchor a1 = new XSSFClientAnchor(0, 0, 0, 0, 1, 1, 10, 30); - XSSFChart c1 = d1.createChart(a1); - - assertEquals(1, d1.getCharts().size()); - assertNotNull(c1.getGraphicFrame()); - assertNotNull(c1.getOrCreateLegend()); - - XSSFClientAnchor a2 = new XSSFClientAnchor(0, 0, 0, 0, 1, 11, 10, 60); - XSSFChart c2 = d1.createChart(a2); - assertNotNull(c2); - assertEquals(2, d1.getCharts().size()); - - assertNotNull(XSSFTestDataSamples.writeOutAndReadBack(wb)); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFChartSheet.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFChartSheet.java deleted file mode 100644 index 8cb76ac0f..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFChartSheet.java +++ /dev/null @@ -1,83 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import org.apache.poi.ss.util.CellAddress; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.Test; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTChartsheet; - -import static org.junit.Assert.*; - -public final class TestXSSFChartSheet { - - @Test - public void testXSSFFactory() { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("chart_sheet.xlsx"); - assertEquals(4, wb.getNumberOfSheets()); - - //the third sheet is of type 'chartsheet' - assertEquals("Chart1", wb.getSheetName(2)); - assertTrue(wb.getSheetAt(2) instanceof XSSFChartSheet); - assertEquals("Chart1", wb.getSheetAt(2).getSheetName()); - - final CTChartsheet ctChartsheet = ((XSSFChartSheet) wb.getSheetAt(2)).getCTChartsheet(); - assertNotNull(ctChartsheet); - } - - @Test - public void testGetAccessors() { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("chart_sheet.xlsx"); - XSSFChartSheet sheet = (XSSFChartSheet)wb.getSheetAt(2); - - assertFalse("Row iterator for charts sheets should return zero rows", - sheet.iterator().hasNext()); - - //access to a arbitrary row - assertNull(sheet.getRow(1)); - - //some basic get* accessors - assertEquals(0, sheet.getNumberOfComments()); - assertEquals(0, sheet.getNumHyperlinks()); - assertEquals(0, sheet.getNumMergedRegions()); - assertNull(sheet.getActiveCell()); - assertTrue(sheet.getAutobreaks()); - //noinspection deprecation - assertNull(sheet.getCellComment(0, 0)); - assertNull(sheet.getCellComment(new CellAddress(0, 0))); - assertEquals(0, sheet.getColumnBreaks().length); - assertTrue(sheet.getRowSumsBelow()); - assertNotNull(sheet.createDrawingPatriarch()); - assertNotNull(sheet.getDrawingPatriarch()); - assertNotNull(sheet.getCTChartsheet()); - } - - @Test - public void testGetCharts() throws Exception { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("chart_sheet.xlsx"); - - XSSFSheet ns = wb.getSheetAt(0); - XSSFChartSheet cs = (XSSFChartSheet)wb.getSheetAt(2); - - assertEquals(0, ns.createDrawingPatriarch().getCharts().size()); - assertEquals(1, cs.createDrawingPatriarch().getCharts().size()); - - XSSFChart chart = cs.createDrawingPatriarch().getCharts().get(0); - assertNull(chart.getTitleText()); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFColGrouping.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFColGrouping.java deleted file mode 100644 index 1d3f97ff8..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFColGrouping.java +++ /dev/null @@ -1,303 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; - -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.Test; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCol; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCols; - -/** - * Test asserts the POI produces <cols> element that could be read and properly interpreted by the MS Excel. - * For specification of the "cols" element see the chapter 3.3.1.16 of the "Office Open XML Part 4 - Markup Language Reference.pdf". - * The specification can be downloaded at http://www.ecma-international.org/publications/files/ECMA-ST/Office%20Open%20XML%201st%20edition%20Part%204%20(PDF).zip. - * - *

    - * The test saves xlsx file on a disk if the system property is set: - * -Dpoi.test.xssf.output.dir=${workspace_loc}/poi/build/xssf-output - * - * - */ -public class TestXSSFColGrouping { - - private static final POILogger logger = POILogFactory.getLogger(TestXSSFColGrouping.class); - - - /** - * Tests that POI doesn't produce "col" elements without "width" attribute. - * POI-52186 - */ - @Test - public void testNoColsWithoutWidthWhenGrouping() throws IOException { - XSSFWorkbook wb1 = new XSSFWorkbook(); - XSSFSheet sheet = wb1.createSheet("test"); - - sheet.setColumnWidth(4, 5000); - sheet.setColumnWidth(5, 5000); - - sheet.groupColumn((short) 4, (short) 7); - sheet.groupColumn((short) 9, (short) 12); - - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1, "testNoColsWithoutWidthWhenGrouping"); - sheet = wb2.getSheet("test"); - - CTCols cols = sheet.getCTWorksheet().getColsArray(0); - logger.log(POILogger.DEBUG, "test52186/cols:" + cols); - for (CTCol col : cols.getColArray()) { - assertTrue("Col width attribute is unset: " + col.toString(), col.isSetWidth()); - } - - wb2.close(); - wb1.close(); - } - - /** - * Tests that POI doesn't produce "col" elements without "width" attribute. - * POI-52186 - */ - @Test - public void testNoColsWithoutWidthWhenGroupingAndCollapsing() throws IOException { - XSSFWorkbook wb1 = new XSSFWorkbook(); - XSSFSheet sheet = wb1.createSheet("test"); - - sheet.setColumnWidth(4, 5000); - sheet.setColumnWidth(5, 5000); - - sheet.groupColumn((short) 4, (short) 5); - - sheet.setColumnGroupCollapsed(4, true); - - CTCols cols = sheet.getCTWorksheet().getColsArray(0); - logger.log(POILogger.DEBUG, "test52186_2/cols:" + cols); - - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1, "testNoColsWithoutWidthWhenGroupingAndCollapsing"); - sheet = wb2.getSheet("test"); - - for (int i = 4; i <= 5; i++) { - assertEquals("Unexpected width of column "+ i, 5000, sheet.getColumnWidth(i)); - } - cols = sheet.getCTWorksheet().getColsArray(0); - for (CTCol col : cols.getColArray()) { - assertTrue("Col width attribute is unset: " + col.toString(), col.isSetWidth()); - } - wb2.close(); - wb1.close(); - } - - /** - * Test the cols element is correct in case of NumericRanges.OVERLAPS_2_WRAPS - */ - @Test - public void testMergingOverlappingCols_OVERLAPS_2_WRAPS() throws IOException { - XSSFWorkbook wb1 = new XSSFWorkbook(); - XSSFSheet sheet = wb1.createSheet("test"); - - CTCols cols = sheet.getCTWorksheet().getColsArray(0); - CTCol col = cols.addNewCol(); - col.setMin(1 + 1); - col.setMax(4 + 1); - col.setWidth(20); - col.setCustomWidth(true); - - sheet.groupColumn((short) 2, (short) 3); - - sheet.getCTWorksheet().getColsArray(0); - logger.log(POILogger.DEBUG, "testMergingOverlappingCols_OVERLAPS_2_WRAPS/cols:" + cols); - - assertEquals(0, cols.getColArray(0).getOutlineLevel()); - assertEquals(2, cols.getColArray(0).getMin()); // 1 based - assertEquals(2, cols.getColArray(0).getMax()); // 1 based - assertEquals(true, cols.getColArray(0).getCustomWidth()); - - assertEquals(1, cols.getColArray(1).getOutlineLevel()); - assertEquals(3, cols.getColArray(1).getMin()); // 1 based - assertEquals(4, cols.getColArray(1).getMax()); // 1 based - assertEquals(true, cols.getColArray(1).getCustomWidth()); - - assertEquals(0, cols.getColArray(2).getOutlineLevel()); - assertEquals(5, cols.getColArray(2).getMin()); // 1 based - assertEquals(5, cols.getColArray(2).getMax()); // 1 based - assertEquals(true, cols.getColArray(2).getCustomWidth()); - - assertEquals(3, cols.sizeOfColArray()); - - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1, "testMergingOverlappingCols_OVERLAPS_2_WRAPS"); - sheet = wb2.getSheet("test"); - - for (int i = 1; i <= 4; i++) { - assertEquals("Unexpected width of column "+ i, 20 * 256, sheet.getColumnWidth(i)); - } - - wb2.close(); - wb1.close(); - } - - /** - * Test the cols element is correct in case of NumericRanges.OVERLAPS_1_WRAPS - */ - @Test - public void testMergingOverlappingCols_OVERLAPS_1_WRAPS() throws IOException { - XSSFWorkbook wb1 = new XSSFWorkbook(); - XSSFSheet sheet = wb1.createSheet("test"); - - CTCols cols = sheet.getCTWorksheet().getColsArray(0); - CTCol col = cols.addNewCol(); - col.setMin(2 + 1); - col.setMax(4 + 1); - col.setWidth(20); - col.setCustomWidth(true); - - sheet.groupColumn((short) 1, (short) 5); - - cols = sheet.getCTWorksheet().getColsArray(0); - logger.log(POILogger.DEBUG, "testMergingOverlappingCols_OVERLAPS_1_WRAPS/cols:" + cols); - - assertEquals(1, cols.getColArray(0).getOutlineLevel()); - assertEquals(2, cols.getColArray(0).getMin()); // 1 based - assertEquals(2, cols.getColArray(0).getMax()); // 1 based - assertEquals(false, cols.getColArray(0).getCustomWidth()); - - assertEquals(1, cols.getColArray(1).getOutlineLevel()); - assertEquals(3, cols.getColArray(1).getMin()); // 1 based - assertEquals(5, cols.getColArray(1).getMax()); // 1 based - assertEquals(true, cols.getColArray(1).getCustomWidth()); - - assertEquals(1, cols.getColArray(2).getOutlineLevel()); - assertEquals(6, cols.getColArray(2).getMin()); // 1 based - assertEquals(6, cols.getColArray(2).getMax()); // 1 based - assertEquals(false, cols.getColArray(2).getCustomWidth()); - - assertEquals(3, cols.sizeOfColArray()); - - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1, "testMergingOverlappingCols_OVERLAPS_1_WRAPS"); - sheet = wb2.getSheet("test"); - - for (int i = 2; i <= 4; i++) { - assertEquals("Unexpected width of column "+ i, 20 * 256, sheet.getColumnWidth(i)); - } - - wb2.close(); - wb1.close(); - } - - /** - * Test the cols element is correct in case of NumericRanges.OVERLAPS_1_MINOR - */ - @Test - public void testMergingOverlappingCols_OVERLAPS_1_MINOR() throws IOException { - XSSFWorkbook wb1 = new XSSFWorkbook(); - XSSFSheet sheet = wb1.createSheet("test"); - - CTCols cols = sheet.getCTWorksheet().getColsArray(0); - CTCol col = cols.addNewCol(); - col.setMin(2 + 1); - col.setMax(4 + 1); - col.setWidth(20); - col.setCustomWidth(true); - - sheet.groupColumn((short) 3, (short) 5); - - cols = sheet.getCTWorksheet().getColsArray(0); - logger.log(POILogger.DEBUG, "testMergingOverlappingCols_OVERLAPS_1_MINOR/cols:" + cols); - - assertEquals(0, cols.getColArray(0).getOutlineLevel()); - assertEquals(3, cols.getColArray(0).getMin()); // 1 based - assertEquals(3, cols.getColArray(0).getMax()); // 1 based - assertEquals(true, cols.getColArray(0).getCustomWidth()); - - assertEquals(1, cols.getColArray(1).getOutlineLevel()); - assertEquals(4, cols.getColArray(1).getMin()); // 1 based - assertEquals(5, cols.getColArray(1).getMax()); // 1 based - assertEquals(true, cols.getColArray(1).getCustomWidth()); - - assertEquals(1, cols.getColArray(2).getOutlineLevel()); - assertEquals(6, cols.getColArray(2).getMin()); // 1 based - assertEquals(6, cols.getColArray(2).getMax()); // 1 based - assertEquals(false, cols.getColArray(2).getCustomWidth()); - - assertEquals(3, cols.sizeOfColArray()); - - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1, "testMergingOverlappingCols_OVERLAPS_1_MINOR"); - sheet = wb2.getSheet("test"); - - for (int i = 2; i <= 4; i++) { - assertEquals("Unexpected width of column "+ i, 20 * 256, sheet.getColumnWidth(i)); - } - assertEquals("Unexpected width of column "+ 5, sheet.getDefaultColumnWidth() * 256, sheet.getColumnWidth(5)); - - wb2.close(); - wb1.close(); - } - - /** - * Test the cols element is correct in case of NumericRanges.OVERLAPS_2_MINOR - */ - @Test - public void testMergingOverlappingCols_OVERLAPS_2_MINOR() throws IOException { - XSSFWorkbook wb1 = new XSSFWorkbook(); - XSSFSheet sheet = wb1.createSheet("test"); - - CTCols cols = sheet.getCTWorksheet().getColsArray(0); - CTCol col = cols.addNewCol(); - col.setMin(2 + 1); - col.setMax(4 + 1); - col.setWidth(20); - col.setCustomWidth(true); - - sheet.groupColumn((short) 1, (short) 3); - - cols = sheet.getCTWorksheet().getColsArray(0); - logger.log(POILogger.DEBUG, "testMergingOverlappingCols_OVERLAPS_2_MINOR/cols:" + cols); - - assertEquals(1, cols.getColArray(0).getOutlineLevel()); - assertEquals(2, cols.getColArray(0).getMin()); // 1 based - assertEquals(2, cols.getColArray(0).getMax()); // 1 based - assertEquals(false, cols.getColArray(0).getCustomWidth()); - - assertEquals(1, cols.getColArray(1).getOutlineLevel()); - assertEquals(3, cols.getColArray(1).getMin()); // 1 based - assertEquals(4, cols.getColArray(1).getMax()); // 1 based - assertEquals(true, cols.getColArray(1).getCustomWidth()); - - assertEquals(0, cols.getColArray(2).getOutlineLevel()); - assertEquals(5, cols.getColArray(2).getMin()); // 1 based - assertEquals(5, cols.getColArray(2).getMax()); // 1 based - assertEquals(true, cols.getColArray(2).getCustomWidth()); - - assertEquals(3, cols.sizeOfColArray()); - - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1, "testMergingOverlappingCols_OVERLAPS_2_MINOR"); - sheet = wb2.getSheet("test"); - - for (int i = 2; i <= 4; i++) { - assertEquals("Unexpected width of column "+ i, 20 * 256, sheet.getColumnWidth(i)); - } - assertEquals("Unexpected width of column "+ 1, sheet.getDefaultColumnWidth() * 256, sheet.getColumnWidth(1)); - - wb2.close(); - wb1.close(); - } - -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFColor.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFColor.java deleted file mode 100644 index 38406c30a..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFColor.java +++ /dev/null @@ -1,183 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import static org.junit.Assert.*; - -import java.io.IOException; - -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.Test; - -public final class TestXSSFColor { - - @Test - public void testIndexedColour() throws Exception { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48779.xlsx"); - - // Check the CTColor is as expected - XSSFColor indexed = wb.getCellStyleAt((short)1).getFillBackgroundXSSFColor(); - assertEquals(true, indexed.getCTColor().isSetIndexed()); - assertEquals(64, indexed.getCTColor().getIndexed()); - assertEquals(false, indexed.getCTColor().isSetRgb()); - assertEquals(null, indexed.getCTColor().getRgb()); - - // Now check the XSSFColor - // Note - 64 is a special "auto" one with no rgb equiv - assertEquals(64, indexed.getIndexed()); - assertEquals(null, indexed.getRGB()); - assertEquals(null, indexed.getRGBWithTint()); - assertEquals(null, indexed.getARGBHex()); - assertFalse(indexed.hasAlpha()); - assertFalse(indexed.hasTint()); - - // Now move to one with indexed rgb values - indexed.setIndexed(59); - assertEquals(true, indexed.getCTColor().isSetIndexed()); - assertEquals(59, indexed.getCTColor().getIndexed()); - assertEquals(false, indexed.getCTColor().isSetRgb()); - assertEquals(null, indexed.getCTColor().getRgb()); - - assertEquals(59, indexed.getIndexed()); - assertEquals("FF333300", indexed.getARGBHex()); - - assertEquals(3, indexed.getRGB().length); - assertEquals(0x33, indexed.getRGB()[0]); - assertEquals(0x33, indexed.getRGB()[1]); - assertEquals(0x00, indexed.getRGB()[2]); - - assertEquals(4, indexed.getARGB().length); - assertEquals(-1, indexed.getARGB()[0]); - assertEquals(0x33, indexed.getARGB()[1]); - assertEquals(0x33, indexed.getARGB()[2]); - assertEquals(0x00, indexed.getARGB()[3]); - - // You don't get tinted indexed colours, sorry... - assertEquals(null, indexed.getRGBWithTint()); - - wb.close(); - } - - @Test - public void testRGBColour() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("50299.xlsx"); - - // Check the CTColor is as expected - XSSFColor rgb3 = wb.getCellStyleAt((short)25).getFillForegroundXSSFColor(); - assertEquals(false, rgb3.getCTColor().isSetIndexed()); - assertEquals(0, rgb3.getCTColor().getIndexed()); - assertEquals(true, rgb3.getCTColor().isSetTint()); - assertEquals(-0.34999, rgb3.getCTColor().getTint(), 0.00001); - assertEquals(true, rgb3.getCTColor().isSetRgb()); - assertEquals(3, rgb3.getCTColor().getRgb().length); - - // Now check the XSSFColor - assertEquals(0, rgb3.getIndexed()); - assertEquals(-0.34999, rgb3.getTint(), 0.00001); - assertFalse(rgb3.hasAlpha()); - assertTrue(rgb3.hasTint()); - - assertEquals("FFFFFFFF", rgb3.getARGBHex()); - assertEquals(3, rgb3.getRGB().length); - assertEquals(-1, rgb3.getRGB()[0]); - assertEquals(-1, rgb3.getRGB()[1]); - assertEquals(-1, rgb3.getRGB()[2]); - - assertEquals(4, rgb3.getARGB().length); - assertEquals(-1, rgb3.getARGB()[0]); - assertEquals(-1, rgb3.getARGB()[1]); - assertEquals(-1, rgb3.getARGB()[2]); - assertEquals(-1, rgb3.getARGB()[3]); - - // Tint doesn't have the alpha - // tint = -0.34999 - // 255 * (1 + tint) = 165 truncated - // or (byte) -91 (which is 165 - 256) - assertEquals(3, rgb3.getRGBWithTint().length); - assertEquals(-91, rgb3.getRGBWithTint()[0]); - assertEquals(-91, rgb3.getRGBWithTint()[1]); - assertEquals(-91, rgb3.getRGBWithTint()[2]); - - // Set the color to black (no theme). - rgb3.setRGB(new byte[] {0, 0, 0}); - assertEquals("FF000000", rgb3.getARGBHex()); - assertEquals(0, rgb3.getCTColor().getRgb()[0]); - assertEquals(0, rgb3.getCTColor().getRgb()[1]); - assertEquals(0, rgb3.getCTColor().getRgb()[2]); - - // Set another, is fine - rgb3.setRGB(new byte[] {16,17,18}); - assertFalse(rgb3.hasAlpha()); - assertEquals("FF101112", rgb3.getARGBHex()); - assertEquals(0x10, rgb3.getCTColor().getRgb()[0]); - assertEquals(0x11, rgb3.getCTColor().getRgb()[1]); - assertEquals(0x12, rgb3.getCTColor().getRgb()[2]); - - wb.close(); - } - - @Test - public void testARGBColour() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("48779.xlsx"); - - // Check the CTColor is as expected - XSSFColor rgb4 = wb.getCellStyleAt((short)1).getFillForegroundXSSFColor(); - assertEquals(false, rgb4.getCTColor().isSetIndexed()); - assertEquals(0, rgb4.getCTColor().getIndexed()); - assertEquals(true, rgb4.getCTColor().isSetRgb()); - assertEquals(4, rgb4.getCTColor().getRgb().length); - - // Now check the XSSFColor - assertEquals(0, rgb4.getIndexed()); - assertEquals(0.0, rgb4.getTint(), 0); - assertFalse(rgb4.hasTint()); - assertTrue(rgb4.hasAlpha()); - - assertEquals("FFFF0000", rgb4.getARGBHex()); - assertEquals(3, rgb4.getRGB().length); - assertEquals(-1, rgb4.getRGB()[0]); - assertEquals(0, rgb4.getRGB()[1]); - assertEquals(0, rgb4.getRGB()[2]); - - assertEquals(4, rgb4.getARGB().length); - assertEquals(-1, rgb4.getARGB()[0]); - assertEquals(-1, rgb4.getARGB()[1]); - assertEquals(0, rgb4.getARGB()[2]); - assertEquals(0, rgb4.getARGB()[3]); - - // Tint doesn't have the alpha - assertEquals(3, rgb4.getRGBWithTint().length); - assertEquals(-1, rgb4.getRGBWithTint()[0]); - assertEquals(0, rgb4.getRGBWithTint()[1]); - assertEquals(0, rgb4.getRGBWithTint()[2]); - - - // Turn on tinting, and check it behaves - // TODO These values are suspected to be wrong... - rgb4.setTint(0.4); - assertTrue(rgb4.hasTint()); - assertEquals(0.4, rgb4.getTint(), 0); - - assertEquals(3, rgb4.getRGBWithTint().length); - assertEquals(-1, rgb4.getRGBWithTint()[0]); - assertEquals(102, rgb4.getRGBWithTint()[1]); - assertEquals(102, rgb4.getRGBWithTint()[2]); - - wb.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFComment.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFComment.java deleted file mode 100644 index fd153a77a..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFComment.java +++ /dev/null @@ -1,339 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import static org.apache.poi.xssf.usermodel.XSSFRelation.NS_SPREADSHEETML; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.fail; - -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; - -import org.apache.poi.hssf.usermodel.HSSFRichTextString; -import org.apache.poi.ss.usermodel.BaseTestCellComment; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.ClientAnchor; -import org.apache.poi.ss.usermodel.Comment; -import org.apache.poi.ss.usermodel.CreationHelper; -import org.apache.poi.ss.usermodel.Drawing; -import org.apache.poi.ss.usermodel.IndexedColors; -import org.apache.poi.ss.usermodel.RichTextString; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.CellAddress; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.xssf.XSSFITestDataProvider; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.model.CommentsTable; -import org.apache.poi.xssf.streaming.SXSSFWorkbook; -import org.apache.xmlbeans.XmlObject; -import org.junit.Ignore; -import org.junit.Test; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTComment; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRPrElt; - -import com.microsoft.schemas.vml.CTShape; - -public final class TestXSSFComment extends BaseTestCellComment { - - private static final String TEST_RICHTEXTSTRING = "test richtextstring"; - - public TestXSSFComment() { - super(XSSFITestDataProvider.instance); - } - - /** - * test properties of a newly constructed comment - */ - @Test - public void constructor() { - CommentsTable sheetComments = new CommentsTable(); - assertNotNull(sheetComments.getCTComments().getCommentList()); - assertNotNull(sheetComments.getCTComments().getAuthors()); - assertEquals(1, sheetComments.getCTComments().getAuthors().sizeOfAuthorArray()); - assertEquals(1, sheetComments.getNumberOfAuthors()); - - CTComment ctComment = sheetComments.newComment(CellAddress.A1); - CTShape vmlShape = CTShape.Factory.newInstance(); - - XSSFComment comment = new XSSFComment(sheetComments, ctComment, vmlShape); - assertEquals(null, comment.getString()); - assertEquals(0, comment.getRow()); - assertEquals(0, comment.getColumn()); - assertEquals("", comment.getAuthor()); - assertEquals(false, comment.isVisible()); - } - - @Test - public void getSetCol() { - CommentsTable sheetComments = new CommentsTable(); - XSSFVMLDrawing vml = new XSSFVMLDrawing(); - CTComment ctComment = sheetComments.newComment(CellAddress.A1); - CTShape vmlShape = vml.newCommentShape(); - - XSSFComment comment = new XSSFComment(sheetComments, ctComment, vmlShape); - comment.setColumn(1); - assertEquals(1, comment.getColumn()); - assertEquals(1, new CellReference(ctComment.getRef()).getCol()); - assertEquals(1, vmlShape.getClientDataArray(0).getColumnArray(0).intValue()); - - comment.setColumn(5); - assertEquals(5, comment.getColumn()); - assertEquals(5, new CellReference(ctComment.getRef()).getCol()); - assertEquals(5, vmlShape.getClientDataArray(0).getColumnArray(0).intValue()); - } - - @Test - public void getSetRow() { - CommentsTable sheetComments = new CommentsTable(); - XSSFVMLDrawing vml = new XSSFVMLDrawing(); - CTComment ctComment = sheetComments.newComment(CellAddress.A1); - CTShape vmlShape = vml.newCommentShape(); - - XSSFComment comment = new XSSFComment(sheetComments, ctComment, vmlShape); - comment.setRow(1); - assertEquals(1, comment.getRow()); - assertEquals(1, new CellReference(ctComment.getRef()).getRow()); - assertEquals(1, vmlShape.getClientDataArray(0).getRowArray(0).intValue()); - - comment.setRow(5); - assertEquals(5, comment.getRow()); - assertEquals(5, new CellReference(ctComment.getRef()).getRow()); - assertEquals(5, vmlShape.getClientDataArray(0).getRowArray(0).intValue()); - } - - @Test - public void setString() { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sh = wb.createSheet(); - XSSFComment comment = sh.createDrawingPatriarch().createCellComment(new XSSFClientAnchor()); - - //passing HSSFRichTextString is incorrect - try { - comment.setString(new HSSFRichTextString(TEST_RICHTEXTSTRING)); - fail("expected exception"); - } catch (IllegalArgumentException e){ - assertEquals("Only XSSFRichTextString argument is supported", e.getMessage()); - } - - //simple string argument - comment.setString(TEST_RICHTEXTSTRING); - assertEquals(TEST_RICHTEXTSTRING, comment.getString().getString()); - - //if the text is already set, it should be overridden, not added twice! - comment.setString(TEST_RICHTEXTSTRING); - - CTComment ctComment = comment.getCTComment(); - XmlObject[] obj = ctComment.selectPath( - "declare namespace w='"+NS_SPREADSHEETML+"' .//w:text"); - assertEquals(1, obj.length); - assertEquals(TEST_RICHTEXTSTRING, comment.getString().getString()); - - //sequential call of comment.getString() should return the same XSSFRichTextString object - assertSame(comment.getString(), comment.getString()); - - XSSFRichTextString richText = new XSSFRichTextString(TEST_RICHTEXTSTRING); - XSSFFont font1 = wb.createFont(); - font1.setFontName("Tahoma"); - font1.setFontHeight(8.5); - font1.setItalic(true); - font1.setColor(IndexedColors.BLUE_GREY.getIndex()); - richText.applyFont(0, 5, font1); - - //check the low-level stuff - comment.setString(richText); - obj = ctComment.selectPath( - "declare namespace w='"+NS_SPREADSHEETML+"' .//w:text"); - assertEquals(1, obj.length); - assertSame(comment.getString(), richText); - //check that the rich text is set in the comment - CTRPrElt rPr = richText.getCTRst().getRArray(0).getRPr(); - assertEquals(true, rPr.getIArray(0).getVal()); - assertEquals(8.5, rPr.getSzArray(0).getVal(), 0); - assertEquals(IndexedColors.BLUE_GREY.getIndex(), rPr.getColorArray(0).getIndexed()); - assertEquals("Tahoma", rPr.getRFontArray(0).getVal()); - - assertNotNull(XSSFTestDataSamples.writeOutAndReadBack(wb)); - } - - @Test - public void author() { - CommentsTable sheetComments = new CommentsTable(); - CTComment ctComment = sheetComments.newComment(CellAddress.A1); - - assertEquals(1, sheetComments.getNumberOfAuthors()); - XSSFComment comment = new XSSFComment(sheetComments, ctComment, null); - assertEquals("", comment.getAuthor()); - comment.setAuthor("Apache POI"); - assertEquals("Apache POI", comment.getAuthor()); - assertEquals(2, sheetComments.getNumberOfAuthors()); - comment.setAuthor("Apache POI"); - assertEquals(2, sheetComments.getNumberOfAuthors()); - comment.setAuthor(""); - assertEquals("", comment.getAuthor()); - assertEquals(2, sheetComments.getNumberOfAuthors()); - } - - @Test - public void testBug58175() throws IOException { - Workbook wb = new SXSSFWorkbook(); - try { - Sheet sheet = wb.createSheet(); - - Row row = sheet.createRow(1); - Cell cell = row.createCell(3); - - cell.setCellValue("F4"); - - CreationHelper factory = wb.getCreationHelper(); - - // When the comment box is visible, have it show in a 1x3 space - ClientAnchor anchor = factory.createClientAnchor(); - anchor.setCol1(cell.getColumnIndex()); - anchor.setCol2(cell.getColumnIndex() + 1); - anchor.setRow1(row.getRowNum()); - anchor.setRow2(row.getRowNum() + 3); - - XSSFClientAnchor ca = (XSSFClientAnchor) anchor; - - // create comments and vmlDrawing parts if they don't exist - CommentsTable comments = ((SXSSFWorkbook) wb).getXSSFWorkbook() - .getSheetAt(0).getCommentsTable(true); - XSSFVMLDrawing vml = ((SXSSFWorkbook) wb).getXSSFWorkbook() - .getSheetAt(0).getVMLDrawing(true); - CTShape vmlShape1 = vml.newCommentShape(); - if (ca.isSet()) { - String position = ca.getCol1() + ", 0, " + ca.getRow1() - + ", 0, " + ca.getCol2() + ", 0, " + ca.getRow2() - + ", 0"; - vmlShape1.getClientDataArray(0).setAnchorArray(0, position); - } - - // create the comment in two different ways and verify that there is no difference - XSSFComment shape1 = new XSSFComment(comments, comments.newComment(CellAddress.A1), vmlShape1); - shape1.setColumn(ca.getCol1()); - shape1.setRow(ca.getRow1()); - - CTShape vmlShape2 = vml.newCommentShape(); - if (ca.isSet()) { - String position = ca.getCol1() + ", 0, " + ca.getRow1() - + ", 0, " + ca.getCol2() + ", 0, " + ca.getRow2() - + ", 0"; - vmlShape2.getClientDataArray(0).setAnchorArray(0, position); - } - - CellAddress ref = new CellAddress(ca.getRow1(), ca.getCol1()); - XSSFComment shape2 = new XSSFComment(comments, comments.newComment(ref), vmlShape2); - - assertEquals(shape1.getAuthor(), shape2.getAuthor()); - assertEquals(shape1.getClientAnchor(), shape2.getClientAnchor()); - assertEquals(shape1.getColumn(), shape2.getColumn()); - assertEquals(shape1.getRow(), shape2.getRow()); - assertEquals(shape1.getCTComment().toString(), shape2.getCTComment().toString()); - assertEquals(shape1.getCTComment().getRef(), shape2.getCTComment().getRef()); - - /*CommentsTable table1 = shape1.getCommentsTable(); - CommentsTable table2 = shape2.getCommentsTable(); - assertEquals(table1.getCTComments().toString(), table2.getCTComments().toString()); - assertEquals(table1.getNumberOfComments(), table2.getNumberOfComments()); - assertEquals(table1.getRelations(), table2.getRelations());*/ - - assertEquals("The vmlShapes should have equal content afterwards", - vmlShape1.toString().replaceAll("_x0000_s\\d+", "_x0000_s0000"), vmlShape2.toString().replaceAll("_x0000_s\\d+", "_x0000_s0000")); - } finally { - wb.close(); - } - } - - @Ignore("Used for manual testing with opening the resulting Workbook in Excel") - @Test - public void testBug58175a() throws IOException { - Workbook wb = new SXSSFWorkbook(); - try { - Sheet sheet = wb.createSheet(); - - Row row = sheet.createRow(1); - Cell cell = row.createCell(3); - - cell.setCellValue("F4"); - - Drawing drawing = sheet.createDrawingPatriarch(); - - CreationHelper factory = wb.getCreationHelper(); - - // When the comment box is visible, have it show in a 1x3 space - ClientAnchor anchor = factory.createClientAnchor(); - anchor.setCol1(cell.getColumnIndex()); - anchor.setCol2(cell.getColumnIndex() + 1); - anchor.setRow1(row.getRowNum()); - anchor.setRow2(row.getRowNum() + 3); - - // Create the comment and set the text+author - Comment comment = drawing.createCellComment(anchor); - RichTextString str = factory.createRichTextString("Hello, World!"); - comment.setString(str); - comment.setAuthor("Apache POI"); - - /* fixed the problem as well - * comment.setColumn(cell.getColumnIndex()); - * comment.setRow(cell.getRowIndex()); - */ - - // Assign the comment to the cell - cell.setCellComment(comment); - - OutputStream out = new FileOutputStream("C:\\temp\\58175.xlsx"); - try { - wb.write(out); - } finally { - out.close(); - } - } finally { - wb.close(); - } - } - - @Test - public void bug57838DeleteRowsWthCommentsBug() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57838.xlsx"); - Sheet sheet=wb.getSheetAt(0); - Comment comment1 = sheet.getCellComment(new CellAddress(2, 1)); - assertNotNull(comment1); - Comment comment2 = sheet.getCellComment(new CellAddress(2, 2)); - assertNotNull(comment2); - Row row=sheet.getRow(2); - assertNotNull(row); - - sheet.removeRow(row); // Remove row from index 2 - - row=sheet.getRow(2); - assertNull(row); // Row is null since we deleted it. - - comment1 = sheet.getCellComment(new CellAddress(2, 1)); - assertNull(comment1); // comment should be null but will fail due to bug - comment2 = sheet.getCellComment(new CellAddress(2, 2)); - assertNull(comment2); // comment should be null but will fail due to bug - - wb.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFConditionalFormatting.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFConditionalFormatting.java deleted file mode 100644 index 1aa8b3165..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFConditionalFormatting.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -package org.apache.poi.xssf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import java.io.IOException; - -import org.apache.poi.ss.usermodel.BaseTestConditionalFormatting; -import org.apache.poi.ss.usermodel.Color; -import org.apache.poi.xssf.XSSFITestDataProvider; -import org.junit.Test; - -/** - * XSSF-specific Conditional Formatting tests - */ -public class TestXSSFConditionalFormatting extends BaseTestConditionalFormatting { - public TestXSSFConditionalFormatting(){ - super(XSSFITestDataProvider.instance); - } - - @Override - protected void assertColour(String hexExpected, Color actual) { - assertNotNull("Colour must be given", actual); - XSSFColor colour = (XSSFColor)actual; - if (hexExpected.length() == 8) { - assertEquals(hexExpected, colour.getARGBHex()); - } else { - assertEquals(hexExpected, colour.getARGBHex().substring(2)); - } - } - - @Test - public void testRead() throws IOException { - testRead("WithConditionalFormatting.xlsx"); - } - - @Test - public void testReadOffice2007() throws IOException { - testReadOffice2007("NewStyleConditionalFormattings.xlsx"); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDataFormat.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDataFormat.java deleted file mode 100644 index c7179531d..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDataFormat.java +++ /dev/null @@ -1,111 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import static org.junit.Assert.*; - -import java.io.IOException; - -import org.apache.poi.ss.usermodel.BaseTestDataFormat; -import org.apache.poi.ss.usermodel.BuiltinFormats; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.DataFormat; -import org.apache.poi.xssf.XSSFITestDataProvider; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.Test; - -/** - * Tests for {@link XSSFDataFormat} - */ -public final class TestXSSFDataFormat extends BaseTestDataFormat { - - public TestXSSFDataFormat() { - super(XSSFITestDataProvider.instance); - } - - /** - * [Bug 49928] formatCellValue returns incorrect value for \u00a3 formatted cells - */ - @Override - @Test - public void test49928() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("49928.xlsx"); - doTest49928Core(wb); - - DataFormat dataFormat = wb.createDataFormat(); - - // As of 2015-12-27, there is no way to override a built-in number format with POI XSSFWorkbook - // 49928.xlsx has been saved with a poundFmt that overrides the default value (dollar) - short poundFmtIdx = wb.getSheetAt(0).getRow(0).getCell(0).getCellStyle().getDataFormat(); - assertEquals(poundFmtIdx, dataFormat.getFormat(poundFmt)); - - // now create a custom format with Pound (\u00a3) - - String customFmt = "\u00a3##.00[Yellow]"; - assertNotBuiltInFormat(customFmt); - short customFmtIdx = dataFormat.getFormat(customFmt); - assertTrue(customFmtIdx >= BuiltinFormats.FIRST_USER_DEFINED_FORMAT_INDEX); - assertEquals(customFmt, dataFormat.getFormat(customFmtIdx)); - - wb.close(); - } - - /** - * [Bug 58532] Handle formats that go numnum, numK, numM etc - */ - @Override - @Test - public void test58532() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("FormatKM.xlsx"); - doTest58532Core(wb); - wb.close(); - } - - /** - * [Bug 58778] Built-in number formats can be overridden with XSSFDataFormat.putFormat(int id, String fmt) - */ - @Test - public void test58778() throws IOException { - XSSFWorkbook wb1 = new XSSFWorkbook(); - Cell cell = wb1.createSheet("bug58778").createRow(0).createCell(0); - cell.setCellValue(5.25); - CellStyle style = wb1.createCellStyle(); - - XSSFDataFormat dataFormat = wb1.createDataFormat(); - - short poundFmtIdx = 6; - dataFormat.putFormat(poundFmtIdx, poundFmt); - style.setDataFormat(poundFmtIdx); - cell.setCellStyle(style); - // Cell should appear as "5" - - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutCloseAndReadBack(wb1); - cell = wb2.getSheet("bug58778").getRow(0).getCell(0); - assertEquals(5.25, cell.getNumericCellValue(), 0); - - style = cell.getCellStyle(); - assertEquals(poundFmt, style.getDataFormatString()); - assertEquals(poundFmtIdx, style.getDataFormat()); - - // manually check the file to make sure the cell is rendered as "5" - // Verified with LibreOffice 4.2.8.2 on 2015-12-28 - wb2.close(); - wb1.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDataValidation.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDataValidation.java deleted file mode 100644 index e0da16ba2..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDataValidation.java +++ /dev/null @@ -1,344 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel; - -import static org.junit.Assert.assertEquals; - -import java.io.IOException; -import java.math.BigDecimal; -import java.util.List; - -import org.apache.poi.ss.usermodel.BaseTestDataValidation; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.DataValidation; -import org.apache.poi.ss.usermodel.DataValidationConstraint; -import org.apache.poi.ss.usermodel.DataValidationConstraint.OperatorType; -import org.apache.poi.ss.usermodel.DataValidationConstraint.ValidationType; -import org.apache.poi.ss.usermodel.DataValidationHelper; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.CellRangeAddressList; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.xssf.XSSFITestDataProvider; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.Test; - -public class TestXSSFDataValidation extends BaseTestDataValidation { - - public TestXSSFDataValidation(){ - super(XSSFITestDataProvider.instance); - } - - @Test - public void testAddValidations() throws Exception { - XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("DataValidations-49244.xlsx"); - Sheet sheet = wb1.getSheetAt(0); - List dataValidations = ((XSSFSheet)sheet).getDataValidations(); - -/** - * For each validation type, there are two cells with the same validation. This tests - * application of a single validation definition to multiple cells. - * - * For list ( 3 validations for explicit and 3 for formula ) - * - one validation that allows blank. - * - one that does not allow blank. - * - one that does not show the drop down arrow. - * = 2 - * - * For number validations ( integer/decimal and text length ) with 8 different types of operators. - * = 50 - * - * = 52 ( Total ) - */ - assertEquals(52,dataValidations.size()); - - DataValidationHelper dataValidationHelper = sheet.getDataValidationHelper(); - int[] validationTypes = new int[]{ValidationType.INTEGER,ValidationType.DECIMAL,ValidationType.TEXT_LENGTH}; - - int[] singleOperandOperatorTypes = new int[]{ - OperatorType.LESS_THAN,OperatorType.LESS_OR_EQUAL, - OperatorType.GREATER_THAN,OperatorType.GREATER_OR_EQUAL, - OperatorType.EQUAL,OperatorType.NOT_EQUAL - } ; - int[] doubleOperandOperatorTypes = new int[]{ - OperatorType.BETWEEN,OperatorType.NOT_BETWEEN - }; - - BigDecimal value = new BigDecimal("10"),value2 = new BigDecimal("20"); - BigDecimal dvalue = new BigDecimal("10.001"),dvalue2 = new BigDecimal("19.999"); - final int lastRow = sheet.getLastRowNum(); - int offset = lastRow + 3; - - int lastKnownNumValidations = dataValidations.size(); - - Row row = sheet.createRow(offset++); - Cell cell = row.createCell(0); - DataValidationConstraint explicitListValidation = dataValidationHelper.createExplicitListConstraint(new String[]{"MA","MI","CA"}); - CellRangeAddressList cellRangeAddressList = new CellRangeAddressList(); - cellRangeAddressList.addCellRangeAddress(cell.getRowIndex(), cell.getColumnIndex(), cell.getRowIndex(), cell.getColumnIndex()); - DataValidation dataValidation = dataValidationHelper.createValidation(explicitListValidation, cellRangeAddressList); - setOtherValidationParameters(dataValidation); - sheet.addValidationData(dataValidation); - lastKnownNumValidations++; - - row = sheet.createRow(offset++); - cell = row.createCell(0); - - cellRangeAddressList = new CellRangeAddressList(); - cellRangeAddressList.addCellRangeAddress(cell.getRowIndex(), cell.getColumnIndex(), cell.getRowIndex(), cell.getColumnIndex()); - - Cell firstCell = row.createCell(1);firstCell.setCellValue("UT"); - Cell secondCell = row.createCell(2);secondCell.setCellValue("MN"); - Cell thirdCell = row.createCell(3);thirdCell.setCellValue("IL"); - - int rowNum = row.getRowNum() + 1; - String listFormula = new StringBuilder("$B$").append(rowNum).append(":").append("$D$").append(rowNum).toString(); - DataValidationConstraint formulaListValidation = dataValidationHelper.createFormulaListConstraint(listFormula); - - dataValidation = dataValidationHelper.createValidation(formulaListValidation, cellRangeAddressList); - setOtherValidationParameters(dataValidation); - sheet.addValidationData(dataValidation); - lastKnownNumValidations++; - - offset++; - offset++; - - for (int i = 0; i < validationTypes.length; i++) { - int validationType = validationTypes[i]; - offset = offset + 2; - final Row row0 = sheet.createRow(offset++); - Cell cell_10 = row0.createCell(0); - cell_10.setCellValue(validationType==ValidationType.DECIMAL ? "Decimal " : validationType==ValidationType.INTEGER ? "Integer" : "Text Length"); - offset++; - for (int j = 0; j < singleOperandOperatorTypes.length; j++) { - int operatorType = singleOperandOperatorTypes[j]; - final Row row1 = sheet.createRow(offset++); - - //For Integer (> and >=) we add 1 extra cell for validations whose formulae reference other cells. - final Row row2 = i==0 && j < 2 ? sheet.createRow(offset++) : null; - - cell_10 = row1.createCell(0); - cell_10.setCellValue(XSSFDataValidation.operatorTypeMappings.get(operatorType).toString()); - Cell cell_11 = row1.createCell(1); - Cell cell_21 = row1.createCell(2); - Cell cell_22 = i==0 && j < 2 ? row2.createCell(2) : null; - - Cell cell_13 = row1.createCell(3); - - - cell_13.setCellType(CellType.NUMERIC); - cell_13.setCellValue(validationType==ValidationType.DECIMAL ? dvalue.doubleValue() : value.intValue()); - - - //First create value based validation; - DataValidationConstraint constraint = dataValidationHelper.createNumericConstraint(validationType,operatorType, value.toString(), null); - cellRangeAddressList = new CellRangeAddressList(); - cellRangeAddressList.addCellRangeAddress(new CellRangeAddress(cell_11.getRowIndex(),cell_11.getRowIndex(),cell_11.getColumnIndex(),cell_11.getColumnIndex())); - DataValidation validation = dataValidationHelper.createValidation(constraint, cellRangeAddressList); - setOtherValidationParameters(validation); - sheet.addValidationData(validation); - assertEquals(++lastKnownNumValidations,((XSSFSheet)sheet).getDataValidations().size()); - - //Now create real formula based validation. - String formula1 = new CellReference(cell_13.getRowIndex(),cell_13.getColumnIndex()).formatAsString(); - constraint = dataValidationHelper.createNumericConstraint(validationType,operatorType, formula1, null); - if (i==0 && j==0) { - cellRangeAddressList = new CellRangeAddressList(); - cellRangeAddressList.addCellRangeAddress(new CellRangeAddress(cell_21.getRowIndex(), cell_21.getRowIndex(), cell_21.getColumnIndex(), cell_21.getColumnIndex())); - validation = dataValidationHelper.createValidation(constraint, cellRangeAddressList); - setOtherValidationParameters(validation); - sheet.addValidationData(validation); - assertEquals(++lastKnownNumValidations, ((XSSFSheet) sheet).getDataValidations().size()); - - cellRangeAddressList = new CellRangeAddressList(); - cellRangeAddressList.addCellRangeAddress(new CellRangeAddress(cell_22.getRowIndex(), cell_22.getRowIndex(), cell_22.getColumnIndex(), cell_22.getColumnIndex())); - validation = dataValidationHelper.createValidation(constraint, cellRangeAddressList); - setOtherValidationParameters( validation); - sheet.addValidationData(validation); - assertEquals(++lastKnownNumValidations, ((XSSFSheet) sheet).getDataValidations().size()); - } else if(i==0 && j==1 ){ - cellRangeAddressList = new CellRangeAddressList(); - cellRangeAddressList.addCellRangeAddress(new CellRangeAddress(cell_21.getRowIndex(), cell_21.getRowIndex(), cell_21.getColumnIndex(), cell_21.getColumnIndex())); - cellRangeAddressList.addCellRangeAddress(new CellRangeAddress(cell_22.getRowIndex(), cell_22.getRowIndex(), cell_22.getColumnIndex(), cell_22.getColumnIndex())); - validation = dataValidationHelper.createValidation(constraint, cellRangeAddressList); - setOtherValidationParameters( validation); - sheet.addValidationData(validation); - assertEquals(++lastKnownNumValidations, ((XSSFSheet) sheet).getDataValidations().size()); - } else { - cellRangeAddressList = new CellRangeAddressList(); - cellRangeAddressList.addCellRangeAddress(new CellRangeAddress(cell_21.getRowIndex(), cell_21.getRowIndex(), cell_21.getColumnIndex(), cell_21.getColumnIndex())); - validation = dataValidationHelper.createValidation(constraint, cellRangeAddressList); - setOtherValidationParameters(validation); - sheet.addValidationData(validation); - assertEquals(++lastKnownNumValidations, ((XSSFSheet) sheet).getDataValidations().size()); - } - } - - for (int operatorType : doubleOperandOperatorTypes) { - final Row row1 = sheet.createRow(offset++); - - cell_10 = row1.createCell(0); - cell_10.setCellValue(XSSFDataValidation.operatorTypeMappings.get(operatorType).toString()); - - Cell cell_11 = row1.createCell(1); - Cell cell_21 = row1.createCell(2); - - Cell cell_13 = row1.createCell(3); - Cell cell_14 = row1.createCell(4); - - - String value1String = validationType==ValidationType.DECIMAL ? dvalue.toString() : value.toString(); - cell_13.setCellType(CellType.NUMERIC); - cell_13.setCellValue(validationType==ValidationType.DECIMAL ? dvalue.doubleValue() : value.intValue()); - - String value2String = validationType==ValidationType.DECIMAL ? dvalue2.toString() : value2.toString(); - cell_14.setCellType(CellType.NUMERIC); - cell_14.setCellValue(validationType==ValidationType.DECIMAL ? dvalue2.doubleValue() : value2.intValue()); - - - //First create value based validation; - DataValidationConstraint constraint = dataValidationHelper.createNumericConstraint(validationType,operatorType, value1String, value2String); - cellRangeAddressList = new CellRangeAddressList(); - cellRangeAddressList.addCellRangeAddress(new CellRangeAddress(cell_11.getRowIndex(),cell_11.getRowIndex(),cell_11.getColumnIndex(),cell_11.getColumnIndex())); - DataValidation validation = dataValidationHelper.createValidation(constraint, cellRangeAddressList); - setOtherValidationParameters(validation); - sheet.addValidationData(validation); - assertEquals(++lastKnownNumValidations,((XSSFSheet)sheet).getDataValidations().size()); - - - //Now create real formula based validation. - String formula1 = new CellReference(cell_13.getRowIndex(),cell_13.getColumnIndex()).formatAsString(); - String formula2 = new CellReference(cell_14.getRowIndex(),cell_14.getColumnIndex()).formatAsString(); - constraint = dataValidationHelper.createNumericConstraint(validationType,operatorType, formula1, formula2); - cellRangeAddressList = new CellRangeAddressList(); - cellRangeAddressList.addCellRangeAddress(new CellRangeAddress(cell_21.getRowIndex(),cell_21.getRowIndex(),cell_21.getColumnIndex(),cell_21.getColumnIndex())); - validation = dataValidationHelper.createValidation(constraint, cellRangeAddressList); - - setOtherValidationParameters(validation); - sheet.addValidationData(validation); - assertEquals(++lastKnownNumValidations,((XSSFSheet)sheet).getDataValidations().size()); - } - } - - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - Sheet sheetAt = wb2.getSheetAt(0); - assertEquals(lastKnownNumValidations,((XSSFSheet)sheetAt).getDataValidations().size()); - wb2.close(); - } - - protected void setOtherValidationParameters(DataValidation validation) { - boolean yesNo = true; - validation.setEmptyCellAllowed(yesNo); - validation.setShowErrorBox(yesNo); - validation.setShowPromptBox(yesNo); - validation.createErrorBox("Error Message Title", "Error Message"); - validation.createPromptBox("Prompt", "Enter some value"); - validation.setSuppressDropDownArrow(yesNo); - } - - @Test - public void test53965() throws Exception { - XSSFWorkbook wb = new XSSFWorkbook(); - try { - XSSFSheet sheet = wb.createSheet(); - List lst = sheet.getDataValidations(); //<-- works - assertEquals(0, lst.size()); - - //create the cell that will have the validation applied - sheet.createRow(0).createCell(0); - - DataValidationHelper dataValidationHelper = sheet.getDataValidationHelper(); - DataValidationConstraint constraint = dataValidationHelper.createCustomConstraint("SUM($A$1:$A$1) <= 3500"); - CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0); - DataValidation validation = dataValidationHelper.createValidation(constraint, addressList); - sheet.addValidationData(validation); - - // this line caused XmlValueOutOfRangeException , see Bugzilla 3965 - lst = sheet.getDataValidations(); - assertEquals(1, lst.size()); - } finally { - wb.close(); - } - } - - @Test - public void testDefaultAllowBlank() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - try { - XSSFSheet sheet = wb.createSheet(); - - final XSSFDataValidation validation = createValidation(sheet); - sheet.addValidationData(validation); - - final List dataValidations = sheet.getDataValidations(); - assertEquals(true, dataValidations.get(0).getCtDdataValidation().getAllowBlank()); - } finally { - wb.close(); - } - } - - @Test - public void testSetAllowBlankToFalse() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - try { - XSSFSheet sheet = wb.createSheet(); - - final XSSFDataValidation validation = createValidation(sheet); - validation.getCtDdataValidation().setAllowBlank(false); - - sheet.addValidationData(validation); - - final List dataValidations = sheet.getDataValidations(); - assertEquals(false, dataValidations.get(0).getCtDdataValidation().getAllowBlank()); - } finally { - wb.close(); - } - } - - @Test - public void testSetAllowBlankToTrue() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - try { - XSSFSheet sheet = wb.createSheet(); - - final XSSFDataValidation validation = createValidation(sheet); - validation.getCtDdataValidation().setAllowBlank(true); - - sheet.addValidationData(validation); - - final List dataValidations = sheet.getDataValidations(); - assertEquals(true, dataValidations.get(0).getCtDdataValidation().getAllowBlank()); - } finally { - wb.close(); - } - } - - private XSSFDataValidation createValidation(XSSFSheet sheet) { - //create the cell that will have the validation applied - final Row row = sheet.createRow(0); - row.createCell(0); - - DataValidationHelper dataValidationHelper = sheet.getDataValidationHelper(); - - DataValidationConstraint constraint = dataValidationHelper.createCustomConstraint("true"); - final XSSFDataValidation validation = (XSSFDataValidation) dataValidationHelper.createValidation(constraint, new CellRangeAddressList(0, 0, 0, 0)); - return validation; - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDataValidationConstraint.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDataValidationConstraint.java deleted file mode 100644 index a3475f4a5..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDataValidationConstraint.java +++ /dev/null @@ -1,72 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel; - -import static org.junit.Assert.*; - -import org.apache.poi.ss.usermodel.DataValidationConstraint; -import org.apache.poi.ss.usermodel.DataValidationConstraint.ValidationType; -import org.apache.poi.ss.usermodel.DataValidationConstraint.OperatorType; -import org.junit.Test; - -public class TestXSSFDataValidationConstraint { - static final int listType = ValidationType.LIST; - static final int ignoredType = OperatorType.IGNORED; - - // See bug 59719 - @Test - public void listLiteralsQuotesAreStripped_formulaConstructor() { - // literal list, using formula constructor - String literal = "\"one, two, three\""; - String[] expected = new String[] { "one", "two", "three" }; - DataValidationConstraint constraint = new XSSFDataValidationConstraint(listType, ignoredType, literal, null); - assertArrayEquals(expected, constraint.getExplicitListValues()); - // Excel and DataValidationConstraint parser ignore (strip) whitespace; quotes should still be intact - // FIXME: whitespace wasn't stripped - assertEquals(literal, constraint.getFormula1()); - } - - @Test - public void listLiteralsQuotesAreStripped_arrayConstructor() { - // literal list, using array constructor - String literal = "\"one, two, three\""; - String[] expected = new String[] { "one", "two", "three" }; - DataValidationConstraint constraint = new XSSFDataValidationConstraint(expected); - assertArrayEquals(expected, constraint.getExplicitListValues()); - // Excel and DataValidationConstraint parser ignore (strip) whitespace; quotes should still be intact - assertEquals(literal.replace(" ", ""), constraint.getFormula1()); - } - - @Test - public void rangeReference() { - // (unnamed range) reference list - String reference = "A1:A5"; - DataValidationConstraint constraint = new XSSFDataValidationConstraint(listType, ignoredType, reference, null); - assertNull(constraint.getExplicitListValues()); - assertEquals("A1:A5", constraint.getFormula1()); - } - - @Test - public void namedRangeReference() { - // named range list - String namedRange = "MyNamedRange"; - DataValidationConstraint constraint = new XSSFDataValidationConstraint(listType, ignoredType, namedRange, null); - assertNull(constraint.getExplicitListValues()); - assertEquals("MyNamedRange", constraint.getFormula1()); - } - -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDialogSheet.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDialogSheet.java deleted file mode 100644 index 8a72b4105..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDialogSheet.java +++ /dev/null @@ -1,173 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import junit.framework.TestCase; - -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTDialogsheet; - - -public class TestXSSFDialogSheet extends TestCase { - - - public void testCreateDialogSheet() { - XSSFWorkbook workbook = new XSSFWorkbook(); - Sheet dialogsheet = workbook.createDialogsheet("Dialogsheet 1", CTDialogsheet.Factory.newInstance()); - assertNotNull(dialogsheet); - } - - public void testGetDialog() { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFDialogsheet dialogsheet = workbook.createDialogsheet("Dialogsheet 1", null); - assertTrue(dialogsheet.getDialog()); - - } - - public void testAddRow() { - XSSFWorkbook workbook = new XSSFWorkbook(); - Sheet dialogsheet = workbook.createDialogsheet("Dialogsheet 1", CTDialogsheet.Factory.newInstance()); - assertNotNull(dialogsheet); - Row row = dialogsheet.createRow(0); - assertNull(row); - } - - public void testGetSetAutoBreaks() { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFDialogsheet sheet = workbook.createDialogsheet("Dialogsheet 1", null); - assertTrue(sheet.getAutobreaks()); - sheet.setAutobreaks(false); - assertFalse(sheet.getAutobreaks()); - } - - public void testIsSetFitToPage() { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFDialogsheet sheet = workbook.createDialogsheet("Dialogsheet 1", null); - assertFalse(sheet.getFitToPage()); - sheet.setFitToPage(true); - assertTrue(sheet.getFitToPage()); - sheet.setFitToPage(false); - assertFalse(sheet.getFitToPage()); - } - - - public void testGetFooter() { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFDialogsheet sheet = workbook.createDialogsheet("Dialogsheet 1", null); - assertNotNull(sheet.getFooter()); - sheet.getFooter().setCenter("test center footer"); - assertEquals("test center footer", sheet.getFooter().getCenter()); - } - - public void testGetAllHeadersFooters() { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFDialogsheet sheet = workbook.createDialogsheet("Dialogsheet 1", null); - assertNotNull(sheet); - assertNotNull(sheet.getOddFooter()); - assertNotNull(sheet.getEvenFooter()); - assertNotNull(sheet.getFirstFooter()); - assertNotNull(sheet.getOddHeader()); - assertNotNull(sheet.getEvenHeader()); - assertNotNull(sheet.getFirstHeader()); - - assertEquals("", sheet.getOddFooter().getLeft()); - sheet.getOddFooter().setLeft("odd footer left"); - assertEquals("odd footer left", sheet.getOddFooter().getLeft()); - - assertEquals("", sheet.getEvenFooter().getLeft()); - sheet.getEvenFooter().setLeft("even footer left"); - assertEquals("even footer left", sheet.getEvenFooter().getLeft()); - - assertEquals("", sheet.getFirstFooter().getLeft()); - sheet.getFirstFooter().setLeft("first footer left"); - assertEquals("first footer left", sheet.getFirstFooter().getLeft()); - - assertEquals("", sheet.getOddHeader().getLeft()); - sheet.getOddHeader().setLeft("odd header left"); - assertEquals("odd header left", sheet.getOddHeader().getLeft()); - - assertEquals("", sheet.getOddHeader().getRight()); - sheet.getOddHeader().setRight("odd header right"); - assertEquals("odd header right", sheet.getOddHeader().getRight()); - - assertEquals("", sheet.getOddHeader().getCenter()); - sheet.getOddHeader().setCenter("odd header center"); - assertEquals("odd header center", sheet.getOddHeader().getCenter()); - - } - - public void testGetSetHorizontallyCentered() { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFDialogsheet sheet = workbook.createDialogsheet("Dialogsheet 1", null); - assertFalse(sheet.getHorizontallyCenter()); - sheet.setHorizontallyCenter(true); - assertTrue(sheet.getHorizontallyCenter()); - sheet.setHorizontallyCenter(false); - assertFalse(sheet.getHorizontallyCenter()); - } - - public void testGetSetVerticallyCentered() { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFDialogsheet sheet = workbook.createDialogsheet("Dialogsheet 1", null); - assertFalse(sheet.getVerticallyCenter()); - sheet.setVerticallyCenter(true); - assertTrue(sheet.getVerticallyCenter()); - sheet.setVerticallyCenter(false); - assertFalse(sheet.getVerticallyCenter()); - } - - public void testIsSetPrintGridlines() { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFDialogsheet sheet = workbook.createDialogsheet("Dialogsheet 1", null); - assertFalse(sheet.isPrintGridlines()); - sheet.setPrintGridlines(true); - assertTrue(sheet.isPrintGridlines()); - } - - public void testIsSetDisplayFormulas() { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFDialogsheet sheet = workbook.createDialogsheet("Dialogsheet 1", null); - assertFalse(sheet.isDisplayFormulas()); - sheet.setDisplayFormulas(true); - assertTrue(sheet.isDisplayFormulas()); - } - - public void testIsSetDisplayGridLines() { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFDialogsheet sheet = workbook.createDialogsheet("Dialogsheet 1", null); - assertTrue(sheet.isDisplayGridlines()); - sheet.setDisplayGridlines(false); - assertFalse(sheet.isDisplayGridlines()); - } - - public void testIsSetDisplayRowColHeadings() { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFDialogsheet sheet = workbook.createDialogsheet("Dialogsheet 1", null); - assertTrue(sheet.isDisplayRowColHeadings()); - sheet.setDisplayRowColHeadings(false); - assertFalse(sheet.isDisplayRowColHeadings()); - } - - public void testGetScenarioProtect() { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFDialogsheet sheet = workbook.createDialogsheet("Dialogsheet 1", null); - assertFalse(sheet.getScenarioProtect()); - } - -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDrawing.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDrawing.java deleted file mode 100644 index c5b5d6fa4..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFDrawing.java +++ /dev/null @@ -1,844 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel; - -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.POIXMLDocumentPart.RelationPart; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.ss.usermodel.ClientAnchor; -import org.apache.poi.ss.usermodel.FontUnderline; -import org.apache.poi.ss.usermodel.ShapeTypes; -import org.apache.poi.util.Units; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.Test; -import org.openxmlformats.schemas.drawingml.x2006.main.CTGroupTransform2D; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextCharacterProperties; -import org.openxmlformats.schemas.drawingml.x2006.main.CTTextParagraph; -import org.openxmlformats.schemas.drawingml.x2006.main.STTextUnderlineType; -import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTDrawing; - -import java.awt.Color; -import java.io.IOException; -import java.util.List; - -import static org.junit.Assert.*; - -public class TestXSSFDrawing { - @Test - public void testRead() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("WithDrawing.xlsx"); - XSSFSheet sheet = wb.getSheetAt(0); - //the sheet has one relationship and it is XSSFDrawing - List rels = sheet.getRelationParts(); - assertEquals(1, rels.size()); - RelationPart rp = rels.get(0); - assertTrue(rp.getDocumentPart() instanceof XSSFDrawing); - - XSSFDrawing drawing = (XSSFDrawing)rp.getDocumentPart(); - //sheet.createDrawingPatriarch() should return the same instance of XSSFDrawing - assertSame(drawing, sheet.createDrawingPatriarch()); - String drawingId = rp.getRelationship().getId(); - - //there should be a relation to this drawing in the worksheet - assertTrue(sheet.getCTWorksheet().isSetDrawing()); - assertEquals(drawingId, sheet.getCTWorksheet().getDrawing().getId()); - - List shapes = drawing.getShapes(); - assertEquals(6, shapes.size()); - - assertTrue(shapes.get(0) instanceof XSSFPicture); - assertTrue(shapes.get(1) instanceof XSSFPicture); - assertTrue(shapes.get(2) instanceof XSSFPicture); - assertTrue(shapes.get(3) instanceof XSSFPicture); - assertTrue(shapes.get(4) instanceof XSSFSimpleShape); - assertTrue(shapes.get(5) instanceof XSSFPicture); - - for(XSSFShape sh : shapes) assertNotNull(sh.getAnchor()); - - checkRewrite(wb); - wb.close(); - } - - @Test - public void testNew() throws IOException { - XSSFWorkbook wb1 = new XSSFWorkbook(); - XSSFSheet sheet = wb1.createSheet(); - //multiple calls of createDrawingPatriarch should return the same instance of XSSFDrawing - XSSFDrawing dr1 = sheet.createDrawingPatriarch(); - XSSFDrawing dr2 = sheet.createDrawingPatriarch(); - assertSame(dr1, dr2); - - List rels = sheet.getRelationParts(); - assertEquals(1, rels.size()); - RelationPart rp = rels.get(0); - assertTrue(rp.getDocumentPart() instanceof XSSFDrawing); - - XSSFDrawing drawing = rp.getDocumentPart(); - String drawingId = rp.getRelationship().getId(); - - //there should be a relation to this drawing in the worksheet - assertTrue(sheet.getCTWorksheet().isSetDrawing()); - assertEquals(drawingId, sheet.getCTWorksheet().getDrawing().getId()); - - XSSFConnector c1= drawing.createConnector(new XSSFClientAnchor(0,0,0,0,0,0,2,2)); - c1.setLineWidth(2.5); - c1.setLineStyle(1); - - XSSFShapeGroup c2 = drawing.createGroup(new XSSFClientAnchor(0,0,0,0,0,0,5,5)); - assertNotNull(c2); - - XSSFSimpleShape c3 = drawing.createSimpleShape(new XSSFClientAnchor(0,0,0,0,2,2,3,4)); - c3.setText(new XSSFRichTextString("Test String")); - c3.setFillColor(128, 128, 128); - - XSSFTextBox c4 = drawing.createTextbox(new XSSFClientAnchor(0,0,0,0,4,4,5,6)); - XSSFRichTextString rt = new XSSFRichTextString("Test String"); - rt.applyFont(0, 5, wb1.createFont()); - rt.applyFont(5, 6, wb1.createFont()); - c4.setText(rt); - - c4.setNoFill(true); - assertEquals(4, drawing.getCTDrawing().sizeOfTwoCellAnchorArray()); - - List shapes = drawing.getShapes(); - assertEquals(4, shapes.size()); - assertTrue(shapes.get(0) instanceof XSSFConnector); - assertTrue(shapes.get(1) instanceof XSSFShapeGroup); - assertTrue(shapes.get(2) instanceof XSSFSimpleShape); - assertTrue(shapes.get(3) instanceof XSSFSimpleShape); // - - // Save and re-load it - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sheet = wb2.getSheetAt(0); - - // Check - dr1 = sheet.createDrawingPatriarch(); - CTDrawing ctDrawing = dr1.getCTDrawing(); - - // Connector, shapes and text boxes are all two cell anchors - assertEquals(0, ctDrawing.sizeOfAbsoluteAnchorArray()); - assertEquals(0, ctDrawing.sizeOfOneCellAnchorArray()); - assertEquals(4, ctDrawing.sizeOfTwoCellAnchorArray()); - - shapes = dr1.getShapes(); - assertEquals(4, shapes.size()); - assertTrue(shapes.get(0) instanceof XSSFConnector); - assertTrue(shapes.get(1) instanceof XSSFShapeGroup); - assertTrue(shapes.get(2) instanceof XSSFSimpleShape); - assertTrue(shapes.get(3) instanceof XSSFSimpleShape); // - - // Ensure it got the right namespaces - String xml = ctDrawing.toString(); - assertTrue(xml.contains("xmlns:xdr=\"http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing\"")); - assertTrue(xml.contains("xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\"")); - - checkRewrite(wb2); - wb2.close(); - } - - @Test - public void testMultipleDrawings() throws IOException{ - XSSFWorkbook wb = new XSSFWorkbook(); - for (int i = 0; i < 3; i++) { - XSSFSheet sheet = wb.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - assertNotNull(drawing); - } - OPCPackage pkg = wb.getPackage(); - try { - assertEquals(3, pkg.getPartsByContentType(XSSFRelation.DRAWINGS.getContentType()).size()); - checkRewrite(wb); - } finally { - pkg.close(); - } - wb.close(); - } - - @Test - public void testClone() throws Exception{ - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("WithDrawing.xlsx"); - XSSFSheet sheet1 = wb.getSheetAt(0); - - XSSFSheet sheet2 = wb.cloneSheet(0); - - //the source sheet has one relationship and it is XSSFDrawing - List rels1 = sheet1.getRelations(); - assertEquals(1, rels1.size()); - assertTrue(rels1.get(0) instanceof XSSFDrawing); - - List rels2 = sheet2.getRelations(); - assertEquals(1, rels2.size()); - assertTrue(rels2.get(0) instanceof XSSFDrawing); - - XSSFDrawing drawing1 = (XSSFDrawing)rels1.get(0); - XSSFDrawing drawing2 = (XSSFDrawing)rels2.get(0); - assertNotSame(drawing1, drawing2); // drawing2 is a clone of drawing1 - - List shapes1 = drawing1.getShapes(); - List shapes2 = drawing2.getShapes(); - assertEquals(shapes1.size(), shapes2.size()); - - for(int i = 0; i < shapes1.size(); i++){ - XSSFShape sh1 = shapes1.get(i); - XSSFShape sh2 = shapes2.get(i); - - assertTrue(sh1.getClass() == sh2.getClass()); - assertEquals(sh1.getShapeProperties().toString(), sh2.getShapeProperties().toString()); - } - - checkRewrite(wb); - wb.close(); - } - - /** - * ensure that rich text attributes defined in a XSSFRichTextString - * are passed to XSSFSimpleShape. - * - * See Bugzilla 52219. - */ - @Test - public void testRichText() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - - XSSFTextBox shape = drawing.createTextbox(new XSSFClientAnchor(0, 0, 0, 0, 2, 2, 3, 4)); - XSSFRichTextString rt = new XSSFRichTextString("Test String"); - - XSSFFont font = wb.createFont(); - font.setColor(new XSSFColor(new Color(0, 128, 128))); - font.setItalic(true); - font.setBold(true); - font.setUnderline(FontUnderline.SINGLE); - rt.applyFont(font); - - shape.setText(rt); - - CTTextParagraph pr = shape.getCTShape().getTxBody().getPArray(0); - assertEquals(1, pr.sizeOfRArray()); - - CTTextCharacterProperties rPr = pr.getRArray(0).getRPr(); - assertEquals(true, rPr.getB()); - assertEquals(true, rPr.getI()); - assertEquals(STTextUnderlineType.SNG, rPr.getU()); - assertArrayEquals( - new byte[]{0, (byte)128, (byte)128} , - rPr.getSolidFill().getSrgbClr().getVal()); - - checkRewrite(wb); - wb.close(); - } - - /** - * test that anchor is not null when reading shapes from existing drawings - */ - @Test - public void testReadAnchors() throws IOException { - XSSFWorkbook wb1 = new XSSFWorkbook(); - XSSFSheet sheet = wb1.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - - XSSFClientAnchor anchor1 = new XSSFClientAnchor(0, 0, 0, 0, 2, 2, 3, 4); - XSSFShape shape1 = drawing.createTextbox(anchor1); - assertNotNull(shape1); - - XSSFClientAnchor anchor2 = new XSSFClientAnchor(0, 0, 0, 0, 2, 2, 3, 5); - XSSFShape shape2 = drawing.createTextbox(anchor2); - assertNotNull(shape2); - - int pictureIndex= wb1.addPicture(new byte[]{}, XSSFWorkbook.PICTURE_TYPE_PNG); - XSSFClientAnchor anchor3 = new XSSFClientAnchor(0, 0, 0, 0, 2, 2, 3, 6); - XSSFShape shape3 = drawing.createPicture(anchor3, pictureIndex); - assertNotNull(shape3); - - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sheet = wb2.getSheetAt(0); - drawing = sheet.createDrawingPatriarch(); - List shapes = drawing.getShapes(); - assertEquals(shapes.get(0).getAnchor(), anchor1); - assertEquals(shapes.get(1).getAnchor(), anchor2); - assertEquals(shapes.get(2).getAnchor(), anchor3); - - checkRewrite(wb2); - wb2.close(); - } - - /** - * ensure that font and color rich text attributes defined in a XSSFRichTextString - * are passed to XSSFSimpleShape. - * - * See Bugzilla 54969. - */ - @Test - public void testRichTextFontAndColor() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - - XSSFTextBox shape = drawing.createTextbox(new XSSFClientAnchor(0, 0, 0, 0, 2, 2, 3, 4)); - XSSFRichTextString rt = new XSSFRichTextString("Test String"); - - XSSFFont font = wb.createFont(); - font.setColor(new XSSFColor(new Color(0, 128, 128))); - font.setFontName("Arial"); - rt.applyFont(font); - - shape.setText(rt); - - CTTextParagraph pr = shape.getCTShape().getTxBody().getPArray(0); - assertEquals(1, pr.sizeOfRArray()); - - CTTextCharacterProperties rPr = pr.getRArray(0).getRPr(); - assertEquals("Arial", rPr.getLatin().getTypeface()); - assertArrayEquals( - new byte[]{0, (byte)128, (byte)128} , - rPr.getSolidFill().getSrgbClr().getVal()); - checkRewrite(wb); - wb.close(); - } - - /** - * Test setText single paragraph to ensure backwards compatibility - */ - @Test - public void testSetTextSingleParagraph() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - - XSSFTextBox shape = drawing.createTextbox(new XSSFClientAnchor(0, 0, 0, 0, 2, 2, 3, 4)); - XSSFRichTextString rt = new XSSFRichTextString("Test String"); - - XSSFFont font = wb.createFont(); - font.setColor(new XSSFColor(new Color(0, 255, 255))); - font.setFontName("Arial"); - rt.applyFont(font); - - shape.setText(rt); - - List paras = shape.getTextParagraphs(); - assertEquals(1, paras.size()); - assertEquals("Test String", paras.get(0).getText()); - - List runs = paras.get(0).getTextRuns(); - assertEquals(1, runs.size()); - assertEquals("Arial", runs.get(0).getFontFamily()); - - Color clr = runs.get(0).getFontColor(); - assertArrayEquals( - new int[] { 0, 255, 255 } , - new int[] { clr.getRed(), clr.getGreen(), clr.getBlue() }); - - checkRewrite(wb); - wb.close(); - } - - /** - * Test addNewTextParagraph - */ - @Test - public void testAddNewTextParagraph() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - - XSSFTextBox shape = drawing.createTextbox(new XSSFClientAnchor(0, 0, 0, 0, 2, 2, 3, 4)); - - XSSFTextParagraph para = shape.addNewTextParagraph(); - para.addNewTextRun().setText("Line 1"); - - List paras = shape.getTextParagraphs(); - assertEquals(2, paras.size()); // this should be 2 as XSSFSimpleShape creates a default paragraph (no text), and then we add a string to that. - - List runs = para.getTextRuns(); - assertEquals(1, runs.size()); - assertEquals("Line 1", runs.get(0).getText()); - - checkRewrite(wb); - wb.close(); - } - - /** - * Test addNewTextParagraph using RichTextString - */ - @Test - public void testAddNewTextParagraphWithRTS() throws IOException { - XSSFWorkbook wb1 = new XSSFWorkbook(); - XSSFSheet sheet = wb1.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - - XSSFTextBox shape = drawing.createTextbox(new XSSFClientAnchor(0, 0, 0, 0, 2, 2, 3, 4)); - XSSFRichTextString rt = new XSSFRichTextString("Test Rich Text String"); - - XSSFFont font = wb1.createFont(); - font.setColor(new XSSFColor(new Color(0, 255, 255))); - font.setFontName("Arial"); - rt.applyFont(font); - - XSSFFont midfont = wb1.createFont(); - midfont.setColor(new XSSFColor(new Color(0, 255, 0))); - rt.applyFont(5, 14, midfont); // set the text "Rich Text" to be green and the default font - - XSSFTextParagraph para = shape.addNewTextParagraph(rt); - - // Save and re-load it - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sheet = wb2.getSheetAt(0); - - // Check - drawing = sheet.createDrawingPatriarch(); - - List shapes = drawing.getShapes(); - assertEquals(1, shapes.size()); - assertTrue(shapes.get(0) instanceof XSSFSimpleShape); - - XSSFSimpleShape sshape = (XSSFSimpleShape) shapes.get(0); - - List paras = sshape.getTextParagraphs(); - assertEquals(2, paras.size()); // this should be 2 as XSSFSimpleShape creates a default paragraph (no text), and then we add a string to that. - - List runs = para.getTextRuns(); - assertEquals(3, runs.size()); - - // first run properties - assertEquals("Test ", runs.get(0).getText()); - assertEquals("Arial", runs.get(0).getFontFamily()); - - Color clr = runs.get(0).getFontColor(); - assertArrayEquals( - new int[] { 0, 255, 255 } , - new int[] { clr.getRed(), clr.getGreen(), clr.getBlue() }); - - // second run properties - assertEquals("Rich Text", runs.get(1).getText()); - assertEquals(XSSFFont.DEFAULT_FONT_NAME, runs.get(1).getFontFamily()); - - clr = runs.get(1).getFontColor(); - assertArrayEquals( - new int[] { 0, 255, 0 } , - new int[] { clr.getRed(), clr.getGreen(), clr.getBlue() }); - - // third run properties - assertEquals(" String", runs.get(2).getText()); - assertEquals("Arial", runs.get(2).getFontFamily()); - clr = runs.get(2).getFontColor(); - assertArrayEquals( - new int[] { 0, 255, 255 } , - new int[] { clr.getRed(), clr.getGreen(), clr.getBlue() }); - - checkRewrite(wb2); - wb2.close(); - } - - /** - * Test add multiple paragraphs and retrieve text - */ - @Test - public void testAddMultipleParagraphs() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - - XSSFTextBox shape = drawing.createTextbox(new XSSFClientAnchor(0, 0, 0, 0, 2, 2, 3, 4)); - - XSSFTextParagraph para = shape.addNewTextParagraph(); - para.addNewTextRun().setText("Line 1"); - - para = shape.addNewTextParagraph(); - para.addNewTextRun().setText("Line 2"); - - para = shape.addNewTextParagraph(); - para.addNewTextRun().setText("Line 3"); - - List paras = shape.getTextParagraphs(); - assertEquals(4, paras.size()); // this should be 4 as XSSFSimpleShape creates a default paragraph (no text), and then we added 3 paragraphs - assertEquals("Line 1\nLine 2\nLine 3", shape.getText()); - - checkRewrite(wb); - wb.close(); - } - - /** - * Test setting the text, then adding multiple paragraphs and retrieve text - */ - @Test - public void testSetAddMultipleParagraphs() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - - XSSFTextBox shape = drawing.createTextbox(new XSSFClientAnchor(0, 0, 0, 0, 2, 2, 3, 4)); - - shape.setText("Line 1"); - - XSSFTextParagraph para = shape.addNewTextParagraph(); - para.addNewTextRun().setText("Line 2"); - - para = shape.addNewTextParagraph(); - para.addNewTextRun().setText("Line 3"); - - List paras = shape.getTextParagraphs(); - assertEquals(3, paras.size()); // this should be 3 as we overwrote the default paragraph with setText, then added 2 new paragraphs - assertEquals("Line 1\nLine 2\nLine 3", shape.getText()); - - checkRewrite(wb); - wb.close(); - } - - /** - * Test reading text from a textbox in an existing file - */ - @Test - public void testReadTextBox() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("WithDrawing.xlsx"); - XSSFSheet sheet = wb.getSheetAt(0); - //the sheet has one relationship and it is XSSFDrawing - List rels = sheet.getRelationParts(); - assertEquals(1, rels.size()); - RelationPart rp = rels.get(0); - assertTrue(rp.getDocumentPart() instanceof XSSFDrawing); - - XSSFDrawing drawing = rp.getDocumentPart(); - //sheet.createDrawingPatriarch() should return the same instance of XSSFDrawing - assertSame(drawing, sheet.createDrawingPatriarch()); - String drawingId = rp.getRelationship().getId(); - - //there should be a relation to this drawing in the worksheet - assertTrue(sheet.getCTWorksheet().isSetDrawing()); - assertEquals(drawingId, sheet.getCTWorksheet().getDrawing().getId()); - - List shapes = drawing.getShapes(); - assertEquals(6, shapes.size()); - - assertTrue(shapes.get(4) instanceof XSSFSimpleShape); - - XSSFSimpleShape textbox = (XSSFSimpleShape) shapes.get(4); - assertEquals("Sheet with various pictures\n(jpeg, png, wmf, emf and pict)", textbox.getText()); - - checkRewrite(wb); - wb.close(); - } - - - /** - * Test reading multiple paragraphs from a textbox in an existing file - */ - @Test - public void testReadTextBoxParagraphs() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("WithTextBox.xlsx"); - XSSFSheet sheet = wb.getSheetAt(0); - //the sheet has one relationship and it is XSSFDrawing - List rels = sheet.getRelationParts(); - assertEquals(1, rels.size()); - RelationPart rp = rels.get(0); - - assertTrue(rp.getDocumentPart() instanceof XSSFDrawing); - - XSSFDrawing drawing = rp.getDocumentPart(); - - //sheet.createDrawingPatriarch() should return the same instance of XSSFDrawing - assertSame(drawing, sheet.createDrawingPatriarch()); - String drawingId = rp.getRelationship().getId(); - - //there should be a relation to this drawing in the worksheet - assertTrue(sheet.getCTWorksheet().isSetDrawing()); - assertEquals(drawingId, sheet.getCTWorksheet().getDrawing().getId()); - - List shapes = drawing.getShapes(); - assertEquals(1, shapes.size()); - - assertTrue(shapes.get(0) instanceof XSSFSimpleShape); - - XSSFSimpleShape textbox = (XSSFSimpleShape) shapes.get(0); - - List paras = textbox.getTextParagraphs(); - assertEquals(3, paras.size()); - - assertEquals("Line 2", paras.get(1).getText()); // check content of second paragraph - - assertEquals("Line 1\nLine 2\nLine 3", textbox.getText()); // check content of entire textbox - - // check attributes of paragraphs - assertEquals(TextAlign.LEFT, paras.get(0).getTextAlign()); - assertEquals(TextAlign.CENTER, paras.get(1).getTextAlign()); - assertEquals(TextAlign.RIGHT, paras.get(2).getTextAlign()); - - Color clr = paras.get(0).getTextRuns().get(0).getFontColor(); - assertArrayEquals( - new int[] { 255, 0, 0 } , - new int[] { clr.getRed(), clr.getGreen(), clr.getBlue() }); - - clr = paras.get(1).getTextRuns().get(0).getFontColor(); - assertArrayEquals( - new int[] { 0, 255, 0 } , - new int[] { clr.getRed(), clr.getGreen(), clr.getBlue() }); - - clr = paras.get(2).getTextRuns().get(0).getFontColor(); - assertArrayEquals( - new int[] { 0, 0, 255 } , - new int[] { clr.getRed(), clr.getGreen(), clr.getBlue() }); - - checkRewrite(wb); - wb.close(); - } - - /** - * Test adding and reading back paragraphs as bullet points - */ - @Test - public void testAddBulletParagraphs() throws IOException { - - XSSFWorkbook wb1 = new XSSFWorkbook(); - XSSFSheet sheet = wb1.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - - XSSFTextBox shape = drawing.createTextbox(new XSSFClientAnchor(0, 0, 0, 0, 2, 2, 10, 20)); - - String paraString1 = "A normal paragraph"; - String paraString2 = "First bullet"; - String paraString3 = "Second bullet (level 1)"; - String paraString4 = "Third bullet"; - String paraString5 = "Another normal paragraph"; - String paraString6 = "First numbered bullet"; - String paraString7 = "Second bullet (level 1)"; - String paraString8 = "Third bullet (level 1)"; - String paraString9 = "Fourth bullet (level 1)"; - String paraString10 = "Fifth Bullet"; - - XSSFTextParagraph para = shape.addNewTextParagraph(paraString1); - assertNotNull(para); - para = shape.addNewTextParagraph(paraString2); - para.setBullet(true); - - para = shape.addNewTextParagraph(paraString3); - para.setBullet(true); - para.setLevel(1); - - para = shape.addNewTextParagraph(paraString4); - para.setBullet(true); - - para = shape.addNewTextParagraph(paraString5); - assertNotNull(para); - para = shape.addNewTextParagraph(paraString6); - para.setBullet(ListAutoNumber.ARABIC_PERIOD); - - para = shape.addNewTextParagraph(paraString7); - para.setBullet(ListAutoNumber.ARABIC_PERIOD, 3); - para.setLevel(1); - - para = shape.addNewTextParagraph(paraString8); - para.setBullet(ListAutoNumber.ARABIC_PERIOD, 3); - para.setLevel(1); - - para = shape.addNewTextParagraph(""); - para.setBullet(ListAutoNumber.ARABIC_PERIOD, 3); - para.setLevel(1); - - para = shape.addNewTextParagraph(paraString9); - para.setBullet(ListAutoNumber.ARABIC_PERIOD, 3); - para.setLevel(1); - - para = shape.addNewTextParagraph(paraString10); - para.setBullet(ListAutoNumber.ARABIC_PERIOD); - - // Save and re-load it - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sheet = wb2.getSheetAt(0); - - // Check - drawing = sheet.createDrawingPatriarch(); - - List shapes = drawing.getShapes(); - assertEquals(1, shapes.size()); - assertTrue(shapes.get(0) instanceof XSSFSimpleShape); - - XSSFSimpleShape sshape = (XSSFSimpleShape) shapes.get(0); - - List paras = sshape.getTextParagraphs(); - assertEquals(12, paras.size()); // this should be 12 as XSSFSimpleShape creates a default paragraph (no text), and then we added to that - - String builder = - paraString1 + - "\n" + - "\u2022 " + - paraString2 + - "\n" + - "\t\u2022 " + - paraString3 + - "\n" + - "\u2022 " + - paraString4 + - "\n" + - paraString5 + - "\n" + - "1. " + - paraString6 + - "\n" + - "\t3. " + - paraString7 + - "\n" + - "\t4. " + - paraString8 + - "\n" + - "\t" + // should be empty - "\n" + - "\t5. " + - paraString9 + - "\n" + - "2. " + - paraString10; - - assertEquals(builder, sshape.getText()); - - checkRewrite(wb2); - wb2.close(); - } - - /** - * Test reading bullet numbering from a textbox in an existing file - */ - @Test - public void testReadTextBox2() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("WithTextBox2.xlsx"); - XSSFSheet sheet = wb.getSheetAt(0); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - List shapes = drawing.getShapes(); - XSSFSimpleShape textbox = (XSSFSimpleShape) shapes.get(0); - String extracted = textbox.getText(); - String sb = - "1. content1A\n" + - "\t1. content1B\n" + - "\t2. content2B\n" + - "\t3. content3B\n" + - "2. content2A\n" + - "\t3. content2BStartAt3\n" + - "\t\n\t\n\t" + - "4. content2BStartAt3Incremented\n" + - "\t\n\t\n\t\n\t"; - - assertEquals(sb, extracted); - checkRewrite(wb); - wb.close(); - } - - @Test - public void testXSSFSimpleShapeCausesNPE56514() throws IOException { - XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("56514.xlsx"); - XSSFSheet sheet = wb1.getSheetAt(0); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - List shapes = drawing.getShapes(); - assertEquals(4, shapes.size()); - - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sheet = wb2.getSheetAt(0); - drawing = sheet.createDrawingPatriarch(); - - shapes = drawing.getShapes(); - assertEquals(4, shapes.size()); - wb2.close(); - - } - - @Test(expected=IllegalArgumentException.class) - public void testBug56835CellComment() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - - // first comment works - ClientAnchor anchor = new XSSFClientAnchor(1, 1, 2, 2, 3, 3, 4, 4); - XSSFComment comment = drawing.createCellComment(anchor); - assertNotNull(comment); - - // Should fail if we try to add the same comment for the same cell - try { - drawing.createCellComment(anchor); - } finally { - wb.close(); - } - } - - @Test - public void testGroupShape() throws Exception { - XSSFWorkbook wb1 = new XSSFWorkbook(); - XSSFSheet sheet = wb1.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - - XSSFSimpleShape s0 = drawing.createSimpleShape(drawing.createAnchor(0, 0, Units.pixelToEMU(30), Units.pixelToEMU(30), 1, 1, 10, 10)); - s0.setShapeType(ShapeTypes.RECT); - s0.setLineStyleColor(100, 0, 0); - - XSSFShapeGroup g1 = drawing.createGroup(drawing.createAnchor(0, 0, 300, 300, 1, 1, 10, 10)); - CTGroupTransform2D xfrmG1 = g1.getCTGroupShape().getGrpSpPr().getXfrm(); - - XSSFSimpleShape s1 = g1.createSimpleShape(new XSSFChildAnchor( - (int)(xfrmG1.getChExt().getCx()*0.1), - (int)(xfrmG1.getChExt().getCy()*0.1), - (int)(xfrmG1.getChExt().getCx()*0.9), - (int)(xfrmG1.getChExt().getCy()*0.9) - )); - s1.setShapeType(ShapeTypes.RECT); - s1.setLineStyleColor(0, 100, 0); - - XSSFShapeGroup g2 = g1.createGroup(new XSSFChildAnchor( - (int)(xfrmG1.getChExt().getCx()*0.2), - (int)(xfrmG1.getChExt().getCy()*0.2), - (int)(xfrmG1.getChExt().getCx()*0.8), - (int)(xfrmG1.getChExt().getCy()*0.8) - )); - CTGroupTransform2D xfrmG2 = g2.getCTGroupShape().getGrpSpPr().getXfrm(); - - XSSFSimpleShape s2 = g2.createSimpleShape(new XSSFChildAnchor( - (int)(xfrmG2.getChExt().getCx()*0.1), - (int)(xfrmG2.getChExt().getCy()*0.1), - (int)(xfrmG2.getChExt().getCx()*0.9), - (int)(xfrmG2.getChExt().getCy()*0.9) - )); - s2.setShapeType(ShapeTypes.RECT); - s2.setLineStyleColor(0, 0, 100); - - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - - XSSFDrawing draw = wb2.getSheetAt(0).getDrawingPatriarch(); - List shapes = draw.getShapes(); - assertEquals(2, shapes.size()); - assertTrue(shapes.get(0) instanceof XSSFSimpleShape); - assertTrue(shapes.get(1) instanceof XSSFShapeGroup); - shapes = draw.getShapes((XSSFShapeGroup)shapes.get(1)); - assertEquals(2, shapes.size()); - assertTrue(shapes.get(0) instanceof XSSFSimpleShape); - assertTrue(shapes.get(1) instanceof XSSFShapeGroup); - shapes = draw.getShapes((XSSFShapeGroup)shapes.get(1)); - assertEquals(1, shapes.size()); - assertTrue(shapes.get(0) instanceof XSSFSimpleShape); - - wb2.close(); - } - - - private static void checkRewrite(XSSFWorkbook wb) throws IOException { - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb); - assertNotNull(wb2); - wb2.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFEvaluationSheet.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFEvaluationSheet.java deleted file mode 100644 index 1b1417fbb..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFEvaluationSheet.java +++ /dev/null @@ -1,55 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel; - -import org.junit.Test; - -import static org.junit.Assert.*; - -public class TestXSSFEvaluationSheet { - - @Test - public void test() throws Exception { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet("test"); - XSSFRow row = sheet.createRow(0); - row.createCell(0); - XSSFEvaluationSheet evalsheet = new XSSFEvaluationSheet(sheet); - - assertNotNull("Cell 0,0 is found", evalsheet.getCell(0, 0)); - assertNull("Cell 0,1 is not found", evalsheet.getCell(0, 1)); - assertNull("Cell 1,0 is not found", evalsheet.getCell(1, 0)); - - // now add Cell 0,1 - row.createCell(1); - - assertNotNull("Cell 0,0 is found", evalsheet.getCell(0, 0)); - assertNotNull("Cell 0,1 is now also found", evalsheet.getCell(0, 1)); - assertNull("Cell 1,0 is not found", evalsheet.getCell(1, 0)); - - // after clearing all values it also works - row.createCell(2); - evalsheet.clearAllCachedResultValues(); - - assertNotNull("Cell 0,0 is found", evalsheet.getCell(0, 0)); - assertNotNull("Cell 0,2 is now also found", evalsheet.getCell(0, 2)); - assertNull("Cell 1,0 is not found", evalsheet.getCell(1, 0)); - - // other things - assertEquals(sheet, evalsheet.getXSSFSheet()); - } -} \ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFExternalFunctions.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFExternalFunctions.java deleted file mode 100644 index 219b8423c..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFExternalFunctions.java +++ /dev/null @@ -1,30 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import org.apache.poi.ss.formula.BaseTestExternalFunctions; -import org.apache.poi.xssf.XSSFITestDataProvider; - -/** - * Tests setting and evaluating user-defined functions in HSSF - */ -public final class TestXSSFExternalFunctions extends BaseTestExternalFunctions { - public TestXSSFExternalFunctions() { - super(XSSFITestDataProvider.instance, "atp.xlsx"); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFont.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFont.java deleted file mode 100644 index 2eeb5e8bb..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFont.java +++ /dev/null @@ -1,340 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; - -import java.io.IOException; - -import org.apache.poi.POIXMLException; -import org.apache.poi.ss.usermodel.BaseTestFont; -import org.apache.poi.ss.usermodel.Font; -import org.apache.poi.ss.usermodel.FontCharset; -import org.apache.poi.ss.usermodel.FontFamily; -import org.apache.poi.ss.usermodel.FontScheme; -import org.apache.poi.ss.usermodel.FontUnderline; -import org.apache.poi.ss.usermodel.IndexedColors; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.SheetUtil; -import org.apache.poi.util.LocaleUtil; -import org.apache.poi.xssf.XSSFITestDataProvider; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.Test; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTBooleanProperty; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTColor; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTFont; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTFontName; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTFontScheme; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTFontSize; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTIntProperty; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTUnderlineProperty; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTVerticalAlignFontProperty; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STFontScheme; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STUnderlineValues; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STVerticalAlignRun; - -public final class TestXSSFFont extends BaseTestFont{ - - public TestXSSFFont() { - super(XSSFITestDataProvider.instance); - } - - @Test - public void testDefaultFont() throws IOException { - baseTestDefaultFont("Calibri", (short) 220, IndexedColors.BLACK.getIndex()); - } - - @Test - public void testConstructor() { - XSSFFont xssfFont=new XSSFFont(); - assertNotNull(xssfFont.getCTFont()); - } - - @Test - public void testBold() { - CTFont ctFont=CTFont.Factory.newInstance(); - CTBooleanProperty bool=ctFont.addNewB(); - bool.setVal(false); - ctFont.setBArray(0,bool); - XSSFFont xssfFont=new XSSFFont(ctFont); - assertEquals(false, xssfFont.getBold()); - - - xssfFont.setBold(true); - assertEquals(ctFont.sizeOfBArray(),1); - assertEquals(true, ctFont.getBArray(0).getVal()); - } - - @Test - public void testCharSet() throws IOException { - CTFont ctFont=CTFont.Factory.newInstance(); - CTIntProperty prop=ctFont.addNewCharset(); - prop.setVal(FontCharset.ANSI.getValue()); - - ctFont.setCharsetArray(0,prop); - XSSFFont xssfFont=new XSSFFont(ctFont); - assertEquals(Font.ANSI_CHARSET,xssfFont.getCharSet()); - - xssfFont.setCharSet(FontCharset.DEFAULT); - assertEquals(FontCharset.DEFAULT.getValue(),ctFont.getCharsetArray(0).getVal()); - - // Try with a few less usual ones: - // Set with the Charset itself - xssfFont.setCharSet(FontCharset.RUSSIAN); - assertEquals(FontCharset.RUSSIAN.getValue(), xssfFont.getCharSet()); - // And set with the Charset index - xssfFont.setCharSet(FontCharset.ARABIC.getValue()); - assertEquals(FontCharset.ARABIC.getValue(), xssfFont.getCharSet()); - xssfFont.setCharSet((byte)(FontCharset.ARABIC.getValue())); - assertEquals(FontCharset.ARABIC.getValue(), xssfFont.getCharSet()); - - // This one isn't allowed - assertEquals(null, FontCharset.valueOf(9999)); - try { - xssfFont.setCharSet(9999); - fail("Shouldn't be able to set an invalid charset"); - } catch(POIXMLException e) {} - - - // Now try with a few sample files - - // Normal charset - XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("Formatting.xlsx"); - assertEquals(0, - wb1.getSheetAt(0).getRow(0).getCell(0).getCellStyle().getFont().getCharSet() - ); - wb1.close(); - - // GB2312 charact set - XSSFWorkbook wb2 = XSSFTestDataSamples.openSampleWorkbook("49273.xlsx"); - assertEquals(134, - wb2.getSheetAt(0).getRow(0).getCell(0).getCellStyle().getFont().getCharSet() - ); - wb2.close(); - } - - @Test - public void testFontName() { - CTFont ctFont=CTFont.Factory.newInstance(); - CTFontName fname=ctFont.addNewName(); - fname.setVal("Arial"); - ctFont.setNameArray(0,fname); - - XSSFFont xssfFont=new XSSFFont(ctFont); - assertEquals("Arial", xssfFont.getFontName()); - - xssfFont.setFontName("Courier"); - assertEquals("Courier",ctFont.getNameArray(0).getVal()); - } - - @Test - public void testItalic() { - CTFont ctFont=CTFont.Factory.newInstance(); - CTBooleanProperty bool=ctFont.addNewI(); - bool.setVal(false); - ctFont.setIArray(0,bool); - - XSSFFont xssfFont=new XSSFFont(ctFont); - assertEquals(false, xssfFont.getItalic()); - - xssfFont.setItalic(true); - assertEquals(ctFont.sizeOfIArray(),1); - assertEquals(true, ctFont.getIArray(0).getVal()); - assertEquals(true,ctFont.getIArray(0).getVal()); - } - - @Test - public void testStrikeout() { - CTFont ctFont=CTFont.Factory.newInstance(); - CTBooleanProperty bool=ctFont.addNewStrike(); - bool.setVal(false); - ctFont.setStrikeArray(0,bool); - - XSSFFont xssfFont=new XSSFFont(ctFont); - assertEquals(false, xssfFont.getStrikeout()); - - xssfFont.setStrikeout(true); - assertEquals(ctFont.sizeOfStrikeArray(),1); - assertEquals(true, ctFont.getStrikeArray(0).getVal()); - assertEquals(true,ctFont.getStrikeArray(0).getVal()); - } - - @Test - public void testFontHeight() { - CTFont ctFont=CTFont.Factory.newInstance(); - CTFontSize size=ctFont.addNewSz(); - size.setVal(11); - ctFont.setSzArray(0,size); - - XSSFFont xssfFont=new XSSFFont(ctFont); - assertEquals(11,xssfFont.getFontHeightInPoints()); - - xssfFont.setFontHeight(20); - assertEquals(20.0, ctFont.getSzArray(0).getVal(), 0.0); - } - - @Test - public void testFontHeightInPoint() { - CTFont ctFont=CTFont.Factory.newInstance(); - CTFontSize size=ctFont.addNewSz(); - size.setVal(14); - ctFont.setSzArray(0,size); - - XSSFFont xssfFont=new XSSFFont(ctFont); - assertEquals(14,xssfFont.getFontHeightInPoints()); - - xssfFont.setFontHeightInPoints((short)20); - assertEquals(20.0, ctFont.getSzArray(0).getVal(), 0.0); - } - - @Test - public void testUnderline() { - CTFont ctFont=CTFont.Factory.newInstance(); - CTUnderlineProperty underlinePropr=ctFont.addNewU(); - underlinePropr.setVal(STUnderlineValues.SINGLE); - ctFont.setUArray(0,underlinePropr); - - XSSFFont xssfFont=new XSSFFont(ctFont); - assertEquals(Font.U_SINGLE, xssfFont.getUnderline()); - - xssfFont.setUnderline(Font.U_DOUBLE); - assertEquals(ctFont.sizeOfUArray(),1); - assertEquals(STUnderlineValues.DOUBLE,ctFont.getUArray(0).getVal()); - - xssfFont.setUnderline(FontUnderline.DOUBLE_ACCOUNTING); - assertEquals(ctFont.sizeOfUArray(),1); - assertEquals(STUnderlineValues.DOUBLE_ACCOUNTING,ctFont.getUArray(0).getVal()); - } - - @Test - public void testColor() { - CTFont ctFont=CTFont.Factory.newInstance(); - CTColor color=ctFont.addNewColor(); - color.setIndexed(XSSFFont.DEFAULT_FONT_COLOR); - ctFont.setColorArray(0,color); - - XSSFFont xssfFont=new XSSFFont(ctFont); - assertEquals(IndexedColors.BLACK.getIndex(),xssfFont.getColor()); - - xssfFont.setColor(IndexedColors.RED.getIndex()); - assertEquals(IndexedColors.RED.getIndex(), ctFont.getColorArray(0).getIndexed()); - } - - @Test - public void testRgbColor() { - CTFont ctFont=CTFont.Factory.newInstance(); - CTColor color=ctFont.addNewColor(); - - color.setRgb(Integer.toHexString(0xFFFFFF).getBytes(LocaleUtil.CHARSET_1252)); - ctFont.setColorArray(0,color); - - XSSFFont xssfFont=new XSSFFont(ctFont); - assertEquals(ctFont.getColorArray(0).getRgb()[0],xssfFont.getXSSFColor().getRGB()[0]); - assertEquals(ctFont.getColorArray(0).getRgb()[1],xssfFont.getXSSFColor().getRGB()[1]); - assertEquals(ctFont.getColorArray(0).getRgb()[2],xssfFont.getXSSFColor().getRGB()[2]); - assertEquals(ctFont.getColorArray(0).getRgb()[3],xssfFont.getXSSFColor().getRGB()[3]); - - xssfFont.setColor((short)23); - - byte[] bytes = Integer.toHexString(0xF1F1F1).getBytes(LocaleUtil.CHARSET_1252); - color.setRgb(bytes); - XSSFColor newColor=new XSSFColor(color); - xssfFont.setColor(newColor); - assertEquals(ctFont.getColorArray(0).getRgb()[2],newColor.getRGB()[2]); - - assertArrayEquals(bytes, xssfFont.getXSSFColor().getRGB()); - assertEquals(0, xssfFont.getColor()); - } - - @Test - public void testThemeColor() { - CTFont ctFont=CTFont.Factory.newInstance(); - CTColor color=ctFont.addNewColor(); - color.setTheme(1); - ctFont.setColorArray(0,color); - - XSSFFont xssfFont=new XSSFFont(ctFont); - assertEquals(ctFont.getColorArray(0).getTheme(),xssfFont.getThemeColor()); - - xssfFont.setThemeColor(IndexedColors.RED.getIndex()); - assertEquals(IndexedColors.RED.getIndex(),ctFont.getColorArray(0).getTheme()); - } - - @Test - public void testFamily() { - CTFont ctFont=CTFont.Factory.newInstance(); - CTIntProperty family=ctFont.addNewFamily(); - family.setVal(FontFamily.MODERN.getValue()); - ctFont.setFamilyArray(0,family); - - XSSFFont xssfFont=new XSSFFont(ctFont); - assertEquals(FontFamily.MODERN.getValue(),xssfFont.getFamily()); - } - - @Test - public void testScheme() { - CTFont ctFont=CTFont.Factory.newInstance(); - CTFontScheme scheme=ctFont.addNewScheme(); - scheme.setVal(STFontScheme.MAJOR); - ctFont.setSchemeArray(0,scheme); - - XSSFFont font=new XSSFFont(ctFont); - assertEquals(FontScheme.MAJOR,font.getScheme()); - - font.setScheme(FontScheme.NONE); - assertEquals(STFontScheme.NONE,ctFont.getSchemeArray(0).getVal()); - } - - @Test - public void testTypeOffset() { - CTFont ctFont=CTFont.Factory.newInstance(); - CTVerticalAlignFontProperty valign=ctFont.addNewVertAlign(); - valign.setVal(STVerticalAlignRun.BASELINE); - ctFont.setVertAlignArray(0,valign); - - XSSFFont font=new XSSFFont(ctFont); - assertEquals(Font.SS_NONE,font.getTypeOffset()); - - font.setTypeOffset(XSSFFont.SS_SUPER); - assertEquals(STVerticalAlignRun.SUPERSCRIPT,ctFont.getVertAlignArray(0).getVal()); - } - - // store test from TestSheetUtil here as it uses XSSF - @Test - public void testCanComputeWidthXSSF() throws IOException { - Workbook wb = new XSSFWorkbook(); - - // cannot check on result because on some machines we get back false here! - SheetUtil.canComputeColumnWidth(wb.getFontAt((short)0)); - - wb.close(); - } - - // store test from TestSheetUtil here as it uses XSSF - @Test - public void testCanComputeWidthInvalidFont() throws IOException { - Font font = new XSSFFont(CTFont.Factory.newInstance()); - font.setFontName("some non existing font name"); - - // Even with invalid fonts we still get back useful data most of the time... - SheetUtil.canComputeColumnWidth(font); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFForkedEvaluator.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFForkedEvaluator.java deleted file mode 100644 index 4da863faf..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFForkedEvaluator.java +++ /dev/null @@ -1,29 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import org.apache.poi.ss.formula.eval.forked.TestForkedEvaluator; -import org.apache.poi.ss.usermodel.Workbook; - -public class TestXSSFForkedEvaluator extends TestForkedEvaluator { - - @Override - protected Workbook newWorkbook() { - return new XSSFWorkbook(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFormulaEvaluation.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFormulaEvaluation.java deleted file mode 100644 index 84a4aa680..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFormulaEvaluation.java +++ /dev/null @@ -1,696 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import static org.junit.Assert.*; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.ss.usermodel.BaseTestFormulaEvaluator; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; -import org.apache.poi.ss.usermodel.FormulaError; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.xssf.XSSFITestDataProvider; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.Ignore; -import org.junit.Test; - -public final class TestXSSFFormulaEvaluation extends BaseTestFormulaEvaluator { - - public TestXSSFFormulaEvaluation() { - super(XSSFITestDataProvider.instance); - } - - @Test - public void testSharedFormulas() throws IOException { - baseTestSharedFormulas("shared_formulas.xlsx"); - } - - @Test - public void testSharedFormulas_evaluateInCell() throws IOException { - XSSFWorkbook wb = (XSSFWorkbook)_testDataProvider.openSampleWorkbook("49872.xlsx"); - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - XSSFSheet sheet = wb.getSheetAt(0); - - double result = 3.0; - - // B3 is a master shared formula, C3 and D3 don't have the formula written in their f element. - // Instead, the attribute si for a particular cell is used to figure what the formula expression - // should be based on the cell's relative location to the master formula, e.g. - // B3: B1+B2 - // C3 and D3: - - // get B3 and evaluate it in the cell - XSSFCell b3 = sheet.getRow(2).getCell(1); - assertEquals(result, evaluator.evaluateInCell(b3).getNumericCellValue(), 0); - - //at this point the master formula is gone, but we are still able to evaluate dependent cells - XSSFCell c3 = sheet.getRow(2).getCell(2); - assertEquals(result, evaluator.evaluateInCell(c3).getNumericCellValue(), 0); - - XSSFCell d3 = sheet.getRow(2).getCell(3); - assertEquals(result, evaluator.evaluateInCell(d3).getNumericCellValue(), 0); - - wb.close(); - } - - /** - * Evaluation of cell references with column indexes greater than 255. See bugzilla 50096 - */ - @Test - public void testEvaluateColumnGreaterThan255() throws IOException { - XSSFWorkbook wb = (XSSFWorkbook) _testDataProvider.openSampleWorkbook("50096.xlsx"); - XSSFFormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - - /** - * The first row simply contains the numbers 1 - 300. - * The second row simply refers to the cell value above in the first row by a simple formula. - */ - for (int i = 245; i < 265; i++) { - XSSFCell cell_noformula = wb.getSheetAt(0).getRow(0).getCell(i); - XSSFCell cell_formula = wb.getSheetAt(0).getRow(1).getCell(i); - - CellReference ref_noformula = new CellReference(cell_noformula.getRowIndex(), cell_noformula.getColumnIndex()); - CellReference ref_formula = new CellReference(cell_noformula.getRowIndex(), cell_noformula.getColumnIndex()); - String fmla = cell_formula.getCellFormula(); - // assure that the formula refers to the cell above. - // the check below is 'deep' and involves conversion of the shared formula: - // in the sample file a shared formula in GN1 is spanned in the range GN2:IY2, - assertEquals(ref_noformula.formatAsString(), fmla); - - CellValue cv_noformula = evaluator.evaluate(cell_noformula); - CellValue cv_formula = evaluator.evaluate(cell_formula); - assertEquals("Wrong evaluation result in " + ref_formula.formatAsString(), - cv_noformula.getNumberValue(), cv_formula.getNumberValue(), 0); - } - - wb.close(); - } - - /** - * Related to bugs #56737 and #56752 - XSSF workbooks which have - * formulas that refer to cells and named ranges in multiple other - * workbooks, both HSSF and XSSF ones - */ - @Test - public void testReferencesToOtherWorkbooks() throws Exception { - XSSFWorkbook wb = (XSSFWorkbook) _testDataProvider.openSampleWorkbook("ref2-56737.xlsx"); - XSSFFormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - XSSFSheet s = wb.getSheetAt(0); - - // References to a .xlsx file - Row rXSLX = s.getRow(2); - Cell cXSLX_cell = rXSLX.getCell(4); - Cell cXSLX_sNR = rXSLX.getCell(6); - Cell cXSLX_gNR = rXSLX.getCell(8); - assertEquals("[1]Uses!$A$1", cXSLX_cell.getCellFormula()); - assertEquals("[1]Defines!NR_To_A1", cXSLX_sNR.getCellFormula()); - assertEquals("[1]!NR_Global_B2", cXSLX_gNR.getCellFormula()); - - assertEquals("Hello!", cXSLX_cell.getStringCellValue()); - assertEquals("Test A1", cXSLX_sNR.getStringCellValue()); - assertEquals(142.0, cXSLX_gNR.getNumericCellValue(), 0); - - // References to a .xls file - Row rXSL = s.getRow(4); - Cell cXSL_cell = rXSL.getCell(4); - Cell cXSL_sNR = rXSL.getCell(6); - Cell cXSL_gNR = rXSL.getCell(8); - assertEquals("[2]Uses!$C$1", cXSL_cell.getCellFormula()); - assertEquals("[2]Defines!NR_To_A1", cXSL_sNR.getCellFormula()); - assertEquals("[2]!NR_Global_B2", cXSL_gNR.getCellFormula()); - - assertEquals("Hello!", cXSL_cell.getStringCellValue()); - assertEquals("Test A1", cXSL_sNR.getStringCellValue()); - assertEquals(142.0, cXSL_gNR.getNumericCellValue(), 0); - - // Try to evaluate without references, won't work - // (At least, not unit we fix bug #56752 that is) - try { - evaluator.evaluate(cXSL_cell); - fail("Without a fix for #56752, shouldn't be able to evaluate a " + - "reference to a non-provided linked workbook"); - } catch(Exception e) { - // expected here - } - - // Setup the environment - Map evaluators = new HashMap(); - evaluators.put("ref2-56737.xlsx", evaluator); - evaluators.put("56737.xlsx", - _testDataProvider.openSampleWorkbook("56737.xlsx").getCreationHelper().createFormulaEvaluator()); - evaluators.put("56737.xls", - HSSFTestDataSamples.openSampleWorkbook("56737.xls").getCreationHelper().createFormulaEvaluator()); - evaluator.setupReferencedWorkbooks(evaluators); - - // Try evaluating all of them, ensure we don't blow up - for(Row r : s) { - for (Cell c : r) { - evaluator.evaluate(c); - } - } - // And evaluate the other way too - evaluator.evaluateAll(); - - // Static evaluator won't work, as no references passed in - try { - XSSFFormulaEvaluator.evaluateAllFormulaCells(wb); - fail("Static method lacks references, shouldn't work"); - } catch(Exception e) { - // expected here - } - - - // Evaluate specific cells and check results - assertEquals("\"Hello!\"", evaluator.evaluate(cXSLX_cell).formatAsString()); - assertEquals("\"Test A1\"", evaluator.evaluate(cXSLX_sNR).formatAsString()); - assertEquals("142.0", evaluator.evaluate(cXSLX_gNR).formatAsString()); - - assertEquals("\"Hello!\"", evaluator.evaluate(cXSL_cell).formatAsString()); - assertEquals("\"Test A1\"", evaluator.evaluate(cXSL_sNR).formatAsString()); - assertEquals("142.0", evaluator.evaluate(cXSL_gNR).formatAsString()); - - - // Add another formula referencing these workbooks - Cell cXSL_cell2 = rXSL.createCell(40); - cXSL_cell2.setCellFormula("[56737.xls]Uses!$C$1"); - // TODO Shouldn't it become [2] like the others? - assertEquals("[56737.xls]Uses!$C$1", cXSL_cell2.getCellFormula()); - assertEquals("\"Hello!\"", evaluator.evaluate(cXSL_cell2).formatAsString()); - - - // Now add a formula that refers to yet another (different) workbook - // Won't work without the workbook being linked - Cell cXSLX_nw_cell = rXSLX.createCell(42); - try { - cXSLX_nw_cell.setCellFormula("[alt.xlsx]Sheet1!$A$1"); - fail("New workbook not linked, shouldn't be able to add"); - } catch (Exception e) { - // expected here - } - - // Link and re-try - Workbook alt = new XSSFWorkbook(); - try { - alt.createSheet().createRow(0).createCell(0).setCellValue("In another workbook"); - // TODO Implement the rest of this, see bug #57184 -/* - wb.linkExternalWorkbook("alt.xlsx", alt); - - cXSLX_nw_cell.setCellFormula("[alt.xlsx]Sheet1!$A$1"); - // Check it - TODO Is this correct? Or should it become [3]Sheet1!$A$1 ? - assertEquals("[alt.xlsx]Sheet1!$A$1", cXSLX_nw_cell.getCellFormula()); - - // Evaluate it, without a link to that workbook - try { - evaluator.evaluate(cXSLX_nw_cell); - fail("No cached value and no link to workbook, shouldn't evaluate"); - } catch(Exception e) {} - - // Add a link, check it does - evaluators.put("alt.xlsx", alt.getCreationHelper().createFormulaEvaluator()); - evaluator.setupReferencedWorkbooks(evaluators); - - evaluator.evaluate(cXSLX_nw_cell); - assertEquals("In another workbook", cXSLX_nw_cell.getStringCellValue()); -*/ - } finally { - alt.close(); - } - - wb.close(); - } - - /** - * If a formula references cells or named ranges in another workbook, - * but that isn't available at evaluation time, the cached values - * should be used instead - * TODO Add the support then add a unit test - * See bug #56752 - */ - @Test - @Ignore - public void testCachedReferencesToOtherWorkbooks() throws Exception { - // TODO - } - - /** - * A handful of functions (such as SUM, COUNTA, MIN) support - * multi-sheet references (eg Sheet1:Sheet3!A1 = Cell A1 from - * Sheets 1 through Sheet 3). - * This test, based on common test files for HSSF and XSSF, checks - * that we can correctly evaluate these - */ - @Test - public void testMultiSheetReferencesHSSFandXSSF() throws Exception { - Workbook wb1 = HSSFTestDataSamples.openSampleWorkbook("55906-MultiSheetRefs.xls"); - Workbook wb2 = XSSFTestDataSamples.openSampleWorkbook("55906-MultiSheetRefs.xlsx"); - - for (Workbook wb : new Workbook[] {wb1,wb2}) { - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - Sheet s1 = wb.getSheetAt(0); - - - // Simple SUM over numbers - Cell sumF = s1.getRow(2).getCell(0); - assertNotNull(sumF); - assertEquals("SUM(Sheet1:Sheet3!A1)", sumF.getCellFormula()); - assertEquals("Failed for " + wb.getClass(), "66.0", evaluator.evaluate(sumF).formatAsString()); - - - // Various Stats formulas on numbers - Cell avgF = s1.getRow(2).getCell(1); - assertNotNull(avgF); - assertEquals("AVERAGE(Sheet1:Sheet3!A1)", avgF.getCellFormula()); - assertEquals("22.0", evaluator.evaluate(avgF).formatAsString()); - - Cell minF = s1.getRow(3).getCell(1); - assertNotNull(minF); - assertEquals("MIN(Sheet1:Sheet3!A$1)", minF.getCellFormula()); - assertEquals("11.0", evaluator.evaluate(minF).formatAsString()); - - Cell maxF = s1.getRow(4).getCell(1); - assertNotNull(maxF); - assertEquals("MAX(Sheet1:Sheet3!A$1)", maxF.getCellFormula()); - assertEquals("33.0", evaluator.evaluate(maxF).formatAsString()); - - Cell countF = s1.getRow(5).getCell(1); - assertNotNull(countF); - assertEquals("COUNT(Sheet1:Sheet3!A$1)", countF.getCellFormula()); - assertEquals("3.0", evaluator.evaluate(countF).formatAsString()); - - - // Various CountAs on Strings - Cell countA_1F = s1.getRow(2).getCell(2); - assertNotNull(countA_1F); - assertEquals("COUNTA(Sheet1:Sheet3!C1)", countA_1F.getCellFormula()); - assertEquals("3.0", evaluator.evaluate(countA_1F).formatAsString()); - - Cell countA_2F = s1.getRow(2).getCell(3); - assertNotNull(countA_2F); - assertEquals("COUNTA(Sheet1:Sheet3!D1)", countA_2F.getCellFormula()); - assertEquals("0.0", evaluator.evaluate(countA_2F).formatAsString()); - - Cell countA_3F = s1.getRow(2).getCell(4); - assertNotNull(countA_3F); - assertEquals("COUNTA(Sheet1:Sheet3!E1)", countA_3F.getCellFormula()); - assertEquals("3.0", evaluator.evaluate(countA_3F).formatAsString()); - } - - wb2.close(); - wb1.close(); - } - - /** - * A handful of functions (such as SUM, COUNTA, MIN) support - * multi-sheet areas (eg Sheet1:Sheet3!A1:B2 = Cell A1 to Cell B2, - * from Sheets 1 through Sheet 3). - * This test, based on common test files for HSSF and XSSF, checks - * that we can correctly evaluate these - */ - @Test - public void testMultiSheetAreasHSSFandXSSF() throws IOException { - Workbook wb1 = HSSFTestDataSamples.openSampleWorkbook("55906-MultiSheetRefs.xls"); - Workbook wb2 = XSSFTestDataSamples.openSampleWorkbook("55906-MultiSheetRefs.xlsx"); - - for (Workbook wb : new Workbook[]{wb1,wb2}) { - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - Sheet s1 = wb.getSheetAt(0); - - - // SUM over a range - Cell sumFA = s1.getRow(2).getCell(7); - assertNotNull(sumFA); - assertEquals("SUM(Sheet1:Sheet3!A1:B2)", sumFA.getCellFormula()); - assertEquals("Failed for " + wb.getClass(), "110.0", evaluator.evaluate(sumFA).formatAsString()); - - - // Various Stats formulas on ranges of numbers - Cell avgFA = s1.getRow(2).getCell(8); - assertNotNull(avgFA); - assertEquals("AVERAGE(Sheet1:Sheet3!A1:B2)", avgFA.getCellFormula()); - assertEquals("27.5", evaluator.evaluate(avgFA).formatAsString()); - - Cell minFA = s1.getRow(3).getCell(8); - assertNotNull(minFA); - assertEquals("MIN(Sheet1:Sheet3!A$1:B$2)", minFA.getCellFormula()); - assertEquals("11.0", evaluator.evaluate(minFA).formatAsString()); - - Cell maxFA = s1.getRow(4).getCell(8); - assertNotNull(maxFA); - assertEquals("MAX(Sheet1:Sheet3!A$1:B$2)", maxFA.getCellFormula()); - assertEquals("44.0", evaluator.evaluate(maxFA).formatAsString()); - - Cell countFA = s1.getRow(5).getCell(8); - assertNotNull(countFA); - assertEquals("COUNT(Sheet1:Sheet3!$A$1:$B$2)", countFA.getCellFormula()); - assertEquals("4.0", evaluator.evaluate(countFA).formatAsString()); - } - - wb2.close(); - wb1.close(); - } - - @Test - public void testMultisheetFormulaEval() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - try { - XSSFSheet sheet1 = wb.createSheet("Sheet1"); - XSSFSheet sheet2 = wb.createSheet("Sheet2"); - XSSFSheet sheet3 = wb.createSheet("Sheet3"); - - // sheet1 A1 - XSSFCell cell = sheet1.createRow(0).createCell(0); - cell.setCellType(CellType.NUMERIC); - cell.setCellValue(1.0); - - // sheet2 A1 - cell = sheet2.createRow(0).createCell(0); - cell.setCellType(CellType.NUMERIC); - cell.setCellValue(1.0); - - // sheet2 B1 - cell = sheet2.getRow(0).createCell(1); - cell.setCellType(CellType.NUMERIC); - cell.setCellValue(1.0); - - // sheet3 A1 - cell = sheet3.createRow(0).createCell(0); - cell.setCellType(CellType.NUMERIC); - cell.setCellValue(1.0); - - // sheet1 A2 formulae - cell = sheet1.createRow(1).createCell(0); - cell.setCellType(CellType.FORMULA); - cell.setCellFormula("SUM(Sheet1:Sheet3!A1)"); - - // sheet1 A3 formulae - cell = sheet1.createRow(2).createCell(0); - cell.setCellType(CellType.FORMULA); - cell.setCellFormula("SUM(Sheet1:Sheet3!A1:B1)"); - - wb.getCreationHelper().createFormulaEvaluator().evaluateAll(); - - cell = sheet1.getRow(1).getCell(0); - assertEquals(3.0, cell.getNumericCellValue(), 0); - - cell = sheet1.getRow(2).getCell(0); - assertEquals(4.0, cell.getNumericCellValue(), 0); - } finally { - wb.close(); - } - } - - @Test - public void testBug55843() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - try { - XSSFSheet sheet = wb.createSheet("test"); - XSSFRow row = sheet.createRow(0); - XSSFRow row2 = sheet.createRow(1); - XSSFCell cellA2 = row2.createCell(0, CellType.FORMULA); - XSSFCell cellB1 = row.createCell(1, CellType.NUMERIC); - cellB1.setCellValue(10); - XSSFFormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator(); - cellA2.setCellFormula("IF(B1=0,\"\",((ROW()-ROW(A$1))*12))"); - CellValue evaluate = formulaEvaluator.evaluate(cellA2); - assertEquals("12.0", evaluate.formatAsString()); - - cellA2.setCellFormula("IF(NOT(B1=0),((ROW()-ROW(A$1))*12),\"\")"); - CellValue evaluateN = formulaEvaluator.evaluate(cellA2); - - assertEquals(evaluate.toString(), evaluateN.toString()); - assertEquals("12.0", evaluateN.formatAsString()); - } finally { - wb.close(); - } - } - - @Test - public void testBug55843a() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - try { - XSSFSheet sheet = wb.createSheet("test"); - XSSFRow row = sheet.createRow(0); - XSSFRow row2 = sheet.createRow(1); - XSSFCell cellA2 = row2.createCell(0, CellType.FORMULA); - XSSFCell cellB1 = row.createCell(1, CellType.NUMERIC); - cellB1.setCellValue(10); - XSSFFormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator(); - cellA2.setCellFormula("IF(B1=0,\"\",((ROW(A$1))))"); - CellValue evaluate = formulaEvaluator.evaluate(cellA2); - assertEquals("1.0", evaluate.formatAsString()); - - cellA2.setCellFormula("IF(NOT(B1=0),((ROW(A$1))),\"\")"); - CellValue evaluateN = formulaEvaluator.evaluate(cellA2); - - assertEquals(evaluate.toString(), evaluateN.toString()); - assertEquals("1.0", evaluateN.formatAsString()); - } finally { - wb.close(); - } - } - - @Test - public void testBug55843b() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - try { - XSSFSheet sheet = wb.createSheet("test"); - XSSFRow row = sheet.createRow(0); - XSSFRow row2 = sheet.createRow(1); - XSSFCell cellA2 = row2.createCell(0, CellType.FORMULA); - XSSFCell cellB1 = row.createCell(1, CellType.NUMERIC); - cellB1.setCellValue(10); - XSSFFormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator(); - - cellA2.setCellFormula("IF(B1=0,\"\",((ROW())))"); - CellValue evaluate = formulaEvaluator.evaluate(cellA2); - assertEquals("2.0", evaluate.formatAsString()); - - cellA2.setCellFormula("IF(NOT(B1=0),((ROW())),\"\")"); - CellValue evaluateN = formulaEvaluator.evaluate(cellA2); - - assertEquals(evaluate.toString(), evaluateN.toString()); - assertEquals("2.0", evaluateN.formatAsString()); - } finally { - wb.close(); - } - } - - @Test - public void testBug55843c() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - try { - XSSFSheet sheet = wb.createSheet("test"); - XSSFRow row = sheet.createRow(0); - XSSFRow row2 = sheet.createRow(1); - XSSFCell cellA2 = row2.createCell(0, CellType.FORMULA); - XSSFCell cellB1 = row.createCell(1, CellType.NUMERIC); - cellB1.setCellValue(10); - XSSFFormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator(); - - cellA2.setCellFormula("IF(NOT(B1=0),((ROW())))"); - CellValue evaluateN = formulaEvaluator.evaluate(cellA2); - assertEquals("2.0", evaluateN.formatAsString()); - } finally { - wb.close(); - } - } - - @Test - public void testBug55843d() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - try { - XSSFSheet sheet = wb.createSheet("test"); - XSSFRow row = sheet.createRow(0); - XSSFRow row2 = sheet.createRow(1); - XSSFCell cellA2 = row2.createCell(0, CellType.FORMULA); - XSSFCell cellB1 = row.createCell(1, CellType.NUMERIC); - cellB1.setCellValue(10); - XSSFFormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator(); - - cellA2.setCellFormula("IF(NOT(B1=0),((ROW())),\"\")"); - CellValue evaluateN = formulaEvaluator.evaluate(cellA2); - assertEquals("2.0", evaluateN.formatAsString()); - } finally { - wb.close(); - } - } - - @Test - public void testBug55843e() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - try { - XSSFSheet sheet = wb.createSheet("test"); - XSSFRow row = sheet.createRow(0); - XSSFRow row2 = sheet.createRow(1); - XSSFCell cellA2 = row2.createCell(0, CellType.FORMULA); - XSSFCell cellB1 = row.createCell(1, CellType.NUMERIC); - cellB1.setCellValue(10); - XSSFFormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator(); - - cellA2.setCellFormula("IF(B1=0,\"\",((ROW())))"); - CellValue evaluate = formulaEvaluator.evaluate(cellA2); - assertEquals("2.0", evaluate.formatAsString()); - } finally { - wb.close(); - } - } - - @Test - public void testBug55843f() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - try { - XSSFSheet sheet = wb.createSheet("test"); - XSSFRow row = sheet.createRow(0); - XSSFRow row2 = sheet.createRow(1); - XSSFCell cellA2 = row2.createCell(0, CellType.FORMULA); - XSSFCell cellB1 = row.createCell(1, CellType.NUMERIC); - cellB1.setCellValue(10); - XSSFFormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator(); - - cellA2.setCellFormula("IF(B1=0,\"\",IF(B1=10,3,4))"); - CellValue evaluate = formulaEvaluator.evaluate(cellA2); - assertEquals("3.0", evaluate.formatAsString()); - } finally { - wb.close(); - } - } - - @Test - public void testBug56655() throws IOException { - Workbook wb = new XSSFWorkbook(); - Sheet sheet = wb.createSheet(); - - setCellFormula(sheet, 0, 0, "#VALUE!"); - setCellFormula(sheet, 0, 1, "SUMIFS(A:A,A:A,#VALUE!)"); - - wb.getCreationHelper().createFormulaEvaluator().evaluateAll(); - - assertEquals(CellType.ERROR, getCell(sheet, 0,0).getCachedFormulaResultTypeEnum()); - assertEquals(FormulaError.VALUE.getCode(), getCell(sheet, 0,0).getErrorCellValue()); - assertEquals(CellType.ERROR, getCell(sheet, 0,1).getCachedFormulaResultTypeEnum()); - assertEquals(FormulaError.VALUE.getCode(), getCell(sheet, 0,1).getErrorCellValue()); - - wb.close(); - } - - @Test - public void testBug56655a() throws IOException { - Workbook wb = new XSSFWorkbook(); - Sheet sheet = wb.createSheet(); - - setCellFormula(sheet, 0, 0, "B1*C1"); - sheet.getRow(0).createCell(1).setCellValue("A"); - setCellFormula(sheet, 1, 0, "B1*C1"); - sheet.getRow(1).createCell(1).setCellValue("A"); - setCellFormula(sheet, 0, 3, "SUMIFS(A:A,A:A,A2)"); - - wb.getCreationHelper().createFormulaEvaluator().evaluateAll(); - - assertEquals(CellType.ERROR, getCell(sheet, 0, 0).getCachedFormulaResultTypeEnum()); - assertEquals(FormulaError.VALUE.getCode(), getCell(sheet, 0, 0).getErrorCellValue()); - assertEquals(CellType.ERROR, getCell(sheet, 1, 0).getCachedFormulaResultTypeEnum()); - assertEquals(FormulaError.VALUE.getCode(), getCell(sheet, 1, 0).getErrorCellValue()); - assertEquals(CellType.ERROR, getCell(sheet, 0, 3).getCachedFormulaResultTypeEnum()); - assertEquals(FormulaError.VALUE.getCode(), getCell(sheet, 0, 3).getErrorCellValue()); - - wb.close(); - } - - // bug 57721 - @Test - public void structuredReferences() throws IOException { - verifyAllFormulasInWorkbookCanBeEvaluated("evaluate_formula_with_structured_table_references.xlsx"); - } - - // bug 57840 - @Ignore("Takes over a minute to evaluate all formulas in this large workbook. Run this test when profiling for formula evaluation speed.") - @Test - public void testLotsOfFormulasWithStructuredReferencesToCalculatedTableColumns() throws IOException { - verifyAllFormulasInWorkbookCanBeEvaluated("StructuredRefs-lots-with-lookups.xlsx"); - } - - // FIXME: use junit4 parameterization - private static void verifyAllFormulasInWorkbookCanBeEvaluated(String sampleWorkbook) throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook(sampleWorkbook); - XSSFFormulaEvaluator.evaluateAllFormulaCells(wb); - wb.close(); - } - - /** - * @param row 0-based - * @param column 0-based - */ - private void setCellFormula(Sheet sheet, int row, int column, String formula) { - Row r = sheet.getRow(row); - if (r == null) { - r = sheet.createRow(row); - } - Cell cell = r.getCell(column); - if (cell == null) { - cell = r.createCell(column); - } - cell.setCellType(CellType.FORMULA); - cell.setCellFormula(formula); - } - - /** - * @param rowNo 0-based - * @param column 0-based - */ - private Cell getCell(Sheet sheet, int rowNo, int column) { - return sheet.getRow(rowNo).getCell(column); - } - - @Test - public void test59736() { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("59736.xlsx"); - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - Cell cell = wb.getSheetAt(0).getRow(0).getCell(0); - assertEquals(1, cell.getNumericCellValue(), 0.001); - - cell = wb.getSheetAt(0).getRow(1).getCell(0); - CellValue value = evaluator.evaluate(cell); - assertEquals(1, value.getNumberValue(), 0.001); - - cell = wb.getSheetAt(0).getRow(2).getCell(0); - value = evaluator.evaluate(cell); - assertEquals(1, value.getNumberValue(), 0.001); - } - - @Test - public void evaluateInCellReturnsSameDataType() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - wb.createSheet().createRow(0).createCell(0); - XSSFFormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - XSSFCell cell = wb.getSheetAt(0).getRow(0).getCell(0); - XSSFCell same = evaluator.evaluateInCell(cell); - assertSame(cell, same); - wb.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFormulaParser.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFormulaParser.java deleted file mode 100644 index 88677c347..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFFormulaParser.java +++ /dev/null @@ -1,746 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.IOException; -import java.util.Arrays; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.usermodel.HSSFEvaluationWorkbook; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.FormulaParseException; -import org.apache.poi.ss.formula.FormulaParser; -import org.apache.poi.ss.formula.FormulaParsingWorkbook; -import org.apache.poi.ss.formula.FormulaRenderingWorkbook; -import org.apache.poi.ss.formula.FormulaType; -import org.apache.poi.ss.formula.WorkbookDependentFormula; -import org.apache.poi.ss.formula.ptg.Area3DPtg; -import org.apache.poi.ss.formula.ptg.Area3DPxg; -import org.apache.poi.ss.formula.ptg.AreaPtg; -import org.apache.poi.ss.formula.ptg.AttrPtg; -import org.apache.poi.ss.formula.ptg.ErrPtg; -import org.apache.poi.ss.formula.ptg.FuncPtg; -import org.apache.poi.ss.formula.ptg.FuncVarPtg; -import org.apache.poi.ss.formula.ptg.IntPtg; -import org.apache.poi.ss.formula.ptg.IntersectionPtg; -import org.apache.poi.ss.formula.ptg.MemAreaPtg; -import org.apache.poi.ss.formula.ptg.MemFuncPtg; -import org.apache.poi.ss.formula.ptg.NamePtg; -import org.apache.poi.ss.formula.ptg.NameXPxg; -import org.apache.poi.ss.formula.ptg.ParenthesisPtg; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.apache.poi.ss.formula.ptg.Ref3DPtg; -import org.apache.poi.ss.formula.ptg.Ref3DPxg; -import org.apache.poi.ss.formula.ptg.RefPtg; -import org.apache.poi.ss.formula.ptg.StringPtg; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.Test; - -public final class TestXSSFFormulaParser { - private static Ptg[] parse(FormulaParsingWorkbook fpb, String fmla) { - return FormulaParser.parse(fmla, fpb, FormulaType.CELL, -1); - } - private static Ptg[] parse(FormulaParsingWorkbook fpb, String fmla, int rowIndex) { - return FormulaParser.parse(fmla, fpb, FormulaType.CELL, -1, rowIndex); - } - - @Test - public void basicParsing() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(wb); - Ptg[] ptgs; - - ptgs = parse(fpb, "ABC10"); - assertEquals(1, ptgs.length); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[0] instanceof RefPtg); - - ptgs = parse(fpb, "A500000"); - assertEquals(1, ptgs.length); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[0] instanceof RefPtg); - - ptgs = parse(fpb, "ABC500000"); - assertEquals(1, ptgs.length); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[0] instanceof RefPtg); - - //highest allowed rows and column (XFD and 0x100000) - ptgs = parse(fpb, "XFD1048576"); - assertEquals(1, ptgs.length); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[0] instanceof RefPtg); - - - //column greater than XFD - try { - /*ptgs =*/ parse(fpb, "XFE10"); - fail("expected exception"); - } catch (FormulaParseException e){ - assertEquals("Specified named range 'XFE10' does not exist in the current workbook.", e.getMessage()); - } - - //row greater than 0x100000 - try { - /*ptgs =*/ parse(fpb, "XFD1048577"); - fail("expected exception"); - } catch (FormulaParseException e){ - assertEquals("Specified named range 'XFD1048577' does not exist in the current workbook.", e.getMessage()); - } - - // Formula referencing one cell - ptgs = parse(fpb, "ISEVEN(A1)"); - assertEquals(3, ptgs.length); - assertEquals(NameXPxg.class, ptgs[0].getClass()); - assertEquals(RefPtg.class, ptgs[1].getClass()); - assertEquals(FuncVarPtg.class, ptgs[2].getClass()); - assertEquals("ISEVEN", ptgs[0].toFormulaString()); - assertEquals("A1", ptgs[1].toFormulaString()); - assertEquals("#external#", ptgs[2].toFormulaString()); - - // Formula referencing an area - ptgs = parse(fpb, "SUM(A1:B3)"); - assertEquals(2, ptgs.length); - assertEquals(AreaPtg.class, ptgs[0].getClass()); - assertEquals(AttrPtg.class, ptgs[1].getClass()); - assertEquals("A1:B3", ptgs[0].toFormulaString()); - assertEquals("SUM", ptgs[1].toFormulaString()); - - // Formula referencing one cell in a different sheet - ptgs = parse(fpb, "SUM(Sheet1!A1)"); - assertEquals(2, ptgs.length); - assertEquals(Ref3DPxg.class, ptgs[0].getClass()); - assertEquals(AttrPtg.class, ptgs[1].getClass()); - assertEquals("Sheet1!A1", ptgs[0].toFormulaString()); - assertEquals("SUM", ptgs[1].toFormulaString()); - - // Formula referencing an area in a different sheet - ptgs = parse(fpb, "SUM(Sheet1!A1:B3)"); - assertEquals(2, ptgs.length); - assertEquals(Area3DPxg.class,ptgs[0].getClass()); - assertEquals(AttrPtg.class, ptgs[1].getClass()); - assertEquals("Sheet1!A1:B3", ptgs[0].toFormulaString()); - assertEquals("SUM", ptgs[1].toFormulaString()); - - wb.close(); - } - - @Test - public void builtInFormulas() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(wb); - Ptg[] ptgs; - - ptgs = parse(fpb, "LOG10"); - assertEquals(1, ptgs.length); - assertTrue("",(ptgs[0] instanceof RefPtg)); - - ptgs = parse(fpb, "LOG10(100)"); - assertEquals(2, ptgs.length); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[0] instanceof IntPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[1] instanceof FuncPtg); - - wb.close(); - } - - @Test - public void formulaReferencesSameWorkbook() throws IOException { - // Use a test file with "other workbook" style references - // to itself - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56737.xlsx"); - XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(wb); - Ptg[] ptgs; - - // Reference to a named range in our own workbook, as if it - // were defined in a different workbook - ptgs = parse(fpb, "[0]!NR_Global_B2"); - assertEquals(1, ptgs.length); - assertEquals(NameXPxg.class, ptgs[0].getClass()); - assertEquals(0, ((NameXPxg)ptgs[0]).getExternalWorkbookNumber()); - assertEquals(null, ((NameXPxg)ptgs[0]).getSheetName()); - assertEquals("NR_Global_B2",((NameXPxg)ptgs[0]).getNameName()); - assertEquals("[0]!NR_Global_B2",((NameXPxg)ptgs[0]).toFormulaString()); - - wb.close(); - } - - @Test - public void formulaReferencesOtherSheets() throws IOException { - // Use a test file with the named ranges in place - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56737.xlsx"); - XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(wb); - Ptg[] ptgs; - - // Reference to a single cell in a different sheet - ptgs = parse(fpb, "Uses!A1"); - assertEquals(1, ptgs.length); - assertEquals(Ref3DPxg.class, ptgs[0].getClass()); - assertEquals(-1, ((Ref3DPxg)ptgs[0]).getExternalWorkbookNumber()); - assertEquals("A1", ((Ref3DPxg)ptgs[0]).format2DRefAsString()); - assertEquals("Uses!A1", ((Ref3DPxg)ptgs[0]).toFormulaString()); - - // Reference to a single cell in a different sheet, which needs quoting - ptgs = parse(fpb, "'Testing 47100'!A1"); - assertEquals(1, ptgs.length); - assertEquals(Ref3DPxg.class, ptgs[0].getClass()); - assertEquals(-1, ((Ref3DPxg)ptgs[0]).getExternalWorkbookNumber()); - assertEquals("Testing 47100", ((Ref3DPxg)ptgs[0]).getSheetName()); - assertEquals("A1", ((Ref3DPxg)ptgs[0]).format2DRefAsString()); - assertEquals("'Testing 47100'!A1", ((Ref3DPxg)ptgs[0]).toFormulaString()); - - // Reference to a sheet scoped named range from another sheet - ptgs = parse(fpb, "Defines!NR_To_A1"); - assertEquals(1, ptgs.length); - assertEquals(NameXPxg.class, ptgs[0].getClass()); - assertEquals(-1, ((NameXPxg)ptgs[0]).getExternalWorkbookNumber()); - assertEquals("Defines", ((NameXPxg)ptgs[0]).getSheetName()); - assertEquals("NR_To_A1",((NameXPxg)ptgs[0]).getNameName()); - assertEquals("Defines!NR_To_A1",((NameXPxg)ptgs[0]).toFormulaString()); - - // Reference to a workbook scoped named range - ptgs = parse(fpb, "NR_Global_B2"); - assertEquals(1, ptgs.length); - assertEquals(NamePtg.class, ptgs[0].getClass()); - assertEquals("NR_Global_B2",((NamePtg)ptgs[0]).toFormulaString(fpb)); - - wb.close(); - } - - @Test - public void formulaReferencesOtherWorkbook() throws IOException { - // Use a test file with the external linked table in place - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("ref-56737.xlsx"); - XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(wb); - Ptg[] ptgs; - - // Reference to a single cell in a different workbook - ptgs = parse(fpb, "[1]Uses!$A$1"); - assertEquals(1, ptgs.length); - assertEquals(Ref3DPxg.class, ptgs[0].getClass()); - assertEquals(1, ((Ref3DPxg)ptgs[0]).getExternalWorkbookNumber()); - assertEquals("Uses",((Ref3DPxg)ptgs[0]).getSheetName()); - assertEquals("$A$1",((Ref3DPxg)ptgs[0]).format2DRefAsString()); - assertEquals("[1]Uses!$A$1",((Ref3DPxg)ptgs[0]).toFormulaString()); - - // Reference to a sheet-scoped named range in a different workbook - ptgs = parse(fpb, "[1]Defines!NR_To_A1"); - assertEquals(1, ptgs.length); - assertEquals(NameXPxg.class, ptgs[0].getClass()); - assertEquals(1, ((NameXPxg)ptgs[0]).getExternalWorkbookNumber()); - assertEquals("Defines", ((NameXPxg)ptgs[0]).getSheetName()); - assertEquals("NR_To_A1",((NameXPxg)ptgs[0]).getNameName()); - assertEquals("[1]Defines!NR_To_A1",((NameXPxg)ptgs[0]).toFormulaString()); - - // Reference to a global named range in a different workbook - ptgs = parse(fpb, "[1]!NR_Global_B2"); - assertEquals(1, ptgs.length); - assertEquals(NameXPxg.class, ptgs[0].getClass()); - assertEquals(1, ((NameXPxg)ptgs[0]).getExternalWorkbookNumber()); - assertEquals(null, ((NameXPxg)ptgs[0]).getSheetName()); - assertEquals("NR_Global_B2",((NameXPxg)ptgs[0]).getNameName()); - assertEquals("[1]!NR_Global_B2",((NameXPxg)ptgs[0]).toFormulaString()); - - wb.close(); - } - - /** - * A handful of functions (such as SUM, COUNTA, MIN) support - * multi-sheet references (eg Sheet1:Sheet3!A1 = Cell A1 from - * Sheets 1 through Sheet 3) and multi-sheet area references - * (eg Sheet1:Sheet3!A1:B2 = Cells A1 through B2 from Sheets - * 1 through Sheet 3). - * This test, based on common test files for HSSF and XSSF, checks - * that we can read and parse these kinds of references - * (but not evaluate - that's elsewhere in the test suite) - */ - @Test - public void multiSheetReferencesHSSFandXSSF() throws IOException { - Workbook[] wbs = new Workbook[] { - HSSFTestDataSamples.openSampleWorkbook("55906-MultiSheetRefs.xls"), - XSSFTestDataSamples.openSampleWorkbook("55906-MultiSheetRefs.xlsx") - }; - for (Workbook wb : wbs) { - Sheet s1 = wb.getSheetAt(0); - Ptg[] ptgs; - - // Check the contents - Cell sumF = s1.getRow(2).getCell(0); - assertNotNull(sumF); - assertEquals("SUM(Sheet1:Sheet3!A1)", sumF.getCellFormula()); - - Cell avgF = s1.getRow(2).getCell(1); - assertNotNull(avgF); - assertEquals("AVERAGE(Sheet1:Sheet3!A1)", avgF.getCellFormula()); - - Cell countAF = s1.getRow(2).getCell(2); - assertNotNull(countAF); - assertEquals("COUNTA(Sheet1:Sheet3!C1)", countAF.getCellFormula()); - - Cell maxF = s1.getRow(4).getCell(1); - assertNotNull(maxF); - assertEquals("MAX(Sheet1:Sheet3!A$1)", maxF.getCellFormula()); - - - Cell sumFA = s1.getRow(2).getCell(7); - assertNotNull(sumFA); - assertEquals("SUM(Sheet1:Sheet3!A1:B2)", sumFA.getCellFormula()); - - Cell avgFA = s1.getRow(2).getCell(8); - assertNotNull(avgFA); - assertEquals("AVERAGE(Sheet1:Sheet3!A1:B2)", avgFA.getCellFormula()); - - Cell maxFA = s1.getRow(4).getCell(8); - assertNotNull(maxFA); - assertEquals("MAX(Sheet1:Sheet3!A$1:B$2)", maxFA.getCellFormula()); - - Cell countFA = s1.getRow(5).getCell(8); - assertNotNull(countFA); - assertEquals("COUNT(Sheet1:Sheet3!$A$1:$B$2)", countFA.getCellFormula()); - - - // Create a formula parser - final FormulaParsingWorkbook fpb; - if (wb instanceof HSSFWorkbook) - fpb = HSSFEvaluationWorkbook.create((HSSFWorkbook)wb); - else - fpb = XSSFEvaluationWorkbook.create((XSSFWorkbook)wb); - - // Check things parse as expected: - - // SUM to one cell over 3 workbooks, relative reference - ptgs = parse(fpb, "SUM(Sheet1:Sheet3!A1)"); - assertEquals(2, ptgs.length); - if (wb instanceof HSSFWorkbook) { - assertEquals(Ref3DPtg.class, ptgs[0].getClass()); - } else { - assertEquals(Ref3DPxg.class, ptgs[0].getClass()); - } - assertEquals("Sheet1:Sheet3!A1", toFormulaString(ptgs[0], fpb)); - assertEquals(AttrPtg.class, ptgs[1].getClass()); - assertEquals("SUM", toFormulaString(ptgs[1], fpb)); - - // MAX to one cell over 3 workbooks, absolute row reference - ptgs = parse(fpb, "MAX(Sheet1:Sheet3!A$1)"); - assertEquals(2, ptgs.length); - if (wb instanceof HSSFWorkbook) { - assertEquals(Ref3DPtg.class, ptgs[0].getClass()); - } else { - assertEquals(Ref3DPxg.class, ptgs[0].getClass()); - } - assertEquals("Sheet1:Sheet3!A$1", toFormulaString(ptgs[0], fpb)); - assertEquals(FuncVarPtg.class, ptgs[1].getClass()); - assertEquals("MAX", toFormulaString(ptgs[1], fpb)); - - // MIN to one cell over 3 workbooks, absolute reference - ptgs = parse(fpb, "MIN(Sheet1:Sheet3!$A$1)"); - assertEquals(2, ptgs.length); - if (wb instanceof HSSFWorkbook) { - assertEquals(Ref3DPtg.class, ptgs[0].getClass()); - } else { - assertEquals(Ref3DPxg.class, ptgs[0].getClass()); - } - assertEquals("Sheet1:Sheet3!$A$1", toFormulaString(ptgs[0], fpb)); - assertEquals(FuncVarPtg.class, ptgs[1].getClass()); - assertEquals("MIN", toFormulaString(ptgs[1], fpb)); - - // SUM to a range of cells over 3 workbooks - ptgs = parse(fpb, "SUM(Sheet1:Sheet3!A1:B2)"); - assertEquals(2, ptgs.length); - if (wb instanceof HSSFWorkbook) { - assertEquals(Area3DPtg.class, ptgs[0].getClass()); - } else { - assertEquals(Area3DPxg.class, ptgs[0].getClass()); - } - assertEquals("Sheet1:Sheet3!A1:B2", toFormulaString(ptgs[0], fpb)); - assertEquals(AttrPtg.class, ptgs[1].getClass()); - assertEquals("SUM", toFormulaString(ptgs[1], fpb)); - - // MIN to a range of cells over 3 workbooks, absolute reference - ptgs = parse(fpb, "MIN(Sheet1:Sheet3!$A$1:$B$2)"); - assertEquals(2, ptgs.length); - if (wb instanceof HSSFWorkbook) { - assertEquals(Area3DPtg.class, ptgs[0].getClass()); - } else { - assertEquals(Area3DPxg.class, ptgs[0].getClass()); - } - assertEquals("Sheet1:Sheet3!$A$1:$B$2", toFormulaString(ptgs[0], fpb)); - assertEquals(FuncVarPtg.class, ptgs[1].getClass()); - assertEquals("MIN", toFormulaString(ptgs[1], fpb)); - - // Check we can round-trip - try to set a new one to a new single cell - Cell newF = s1.getRow(0).createCell(10, CellType.FORMULA); - newF.setCellFormula("SUM(Sheet2:Sheet3!A1)"); - assertEquals("SUM(Sheet2:Sheet3!A1)", newF.getCellFormula()); - - // Check we can round-trip - try to set a new one to a cell range - newF = s1.getRow(0).createCell(11, CellType.FORMULA); - newF.setCellFormula("MIN(Sheet1:Sheet2!A1:B2)"); - assertEquals("MIN(Sheet1:Sheet2!A1:B2)", newF.getCellFormula()); - - wb.close(); - } - } - - private static String toFormulaString(Ptg ptg, FormulaParsingWorkbook wb) { - if (ptg instanceof WorkbookDependentFormula) { - return ((WorkbookDependentFormula)ptg).toFormulaString((FormulaRenderingWorkbook)wb); - } - return ptg.toFormulaString(); - } - - @Test - public void test58648Single() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(wb); - Ptg[] ptgs; - - ptgs = parse(fpb, "(ABC10 )"); - assertEquals("Had: " + Arrays.toString(ptgs), - 2, ptgs.length); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[0] instanceof RefPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[1] instanceof ParenthesisPtg); - - wb.close(); - } - - @Test - public void test58648Basic() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(wb); - Ptg[] ptgs; - - // verify whitespaces in different places - ptgs = parse(fpb, "(ABC10)"); - assertEquals("Had: " + Arrays.toString(ptgs), - 2, ptgs.length); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[0] instanceof RefPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[1] instanceof ParenthesisPtg); - - ptgs = parse(fpb, "( ABC10)"); - assertEquals("Had: " + Arrays.toString(ptgs), - 2, ptgs.length); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[0] instanceof RefPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[1] instanceof ParenthesisPtg); - - ptgs = parse(fpb, "(ABC10 )"); - assertEquals("Had: " + Arrays.toString(ptgs), - 2, ptgs.length); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[0] instanceof RefPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[1] instanceof ParenthesisPtg); - - ptgs = parse(fpb, "((ABC10))"); - assertEquals("Had: " + Arrays.toString(ptgs), - 3, ptgs.length); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[0] instanceof RefPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[1] instanceof ParenthesisPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[2] instanceof ParenthesisPtg); - - ptgs = parse(fpb, "((ABC10) )"); - assertEquals("Had: " + Arrays.toString(ptgs), - 3, ptgs.length); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[0] instanceof RefPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[1] instanceof ParenthesisPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[2] instanceof ParenthesisPtg); - - ptgs = parse(fpb, "( (ABC10))"); - assertEquals("Had: " + Arrays.toString(ptgs), - 3, ptgs.length); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[0] instanceof RefPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[1] instanceof ParenthesisPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[2] instanceof ParenthesisPtg); - - wb.close(); - } - - @Test - public void test58648FormulaParsing() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("58648.xlsx"); - - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - - for (int i = 0; i < wb.getNumberOfSheets(); i++) { - Sheet xsheet = wb.getSheetAt(i); - - for (Row row : xsheet) { - for (Cell cell : row) { - if (cell.getCellTypeEnum() == CellType.FORMULA) { - try { - evaluator.evaluateFormulaCellEnum(cell); - } catch (Exception e) { - CellReference cellRef = new CellReference(cell.getRowIndex(), cell.getColumnIndex()); - throw new RuntimeException("error at: " + cellRef.toString(), e); - } - } - } - } - } - - Sheet sheet = wb.getSheet("my-sheet"); - Cell cell = sheet.getRow(1).getCell(4); - - assertEquals(5d, cell.getNumericCellValue(), 0d); - - wb.close(); - } - - @Test - public void testWhitespaceInFormula() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(wb); - Ptg[] ptgs; - - // verify whitespaces in different places - ptgs = parse(fpb, "INTERCEPT(A2:A5, B2:B5)"); - assertEquals("Had: " + Arrays.toString(ptgs), - 3, ptgs.length); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[0] instanceof AreaPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[1] instanceof AreaPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[2] instanceof FuncPtg); - - ptgs = parse(fpb, " INTERCEPT ( \t \r A2 : \nA5 , B2 : B5 ) \t"); - assertEquals("Had: " + Arrays.toString(ptgs), - 3, ptgs.length); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[0] instanceof AreaPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[1] instanceof AreaPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[2] instanceof FuncPtg); - - ptgs = parse(fpb, "(VLOOKUP(\"item1\", A2:B3, 2, FALSE) - VLOOKUP(\"item2\", A2:B3, 2, FALSE) )"); - assertEquals("Had: " + Arrays.toString(ptgs), - 12, ptgs.length); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[0] instanceof StringPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[1] instanceof AreaPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[2] instanceof IntPtg); - - ptgs = parse(fpb, "A1:B1 B1:B2"); - assertEquals("Had: " + Arrays.toString(ptgs), - 4, ptgs.length); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[0] instanceof MemAreaPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[1] instanceof AreaPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[2] instanceof AreaPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[3] instanceof IntersectionPtg); - - ptgs = parse(fpb, "A1:B1 B1:B2"); - assertEquals("Had: " + Arrays.toString(ptgs), - 4, ptgs.length); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[0] instanceof MemAreaPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[1] instanceof AreaPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[2] instanceof AreaPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[3] instanceof IntersectionPtg); - - wb.close(); - } - - @Test - public void testWhitespaceInComplexFormula() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(wb); - Ptg[] ptgs; - - // verify whitespaces in different places - ptgs = parse(fpb, "SUM(A1:INDEX(1:1048576,MAX(IFERROR(MATCH(99^99,B:B,1),0),IFERROR(MATCH(\"zzzz\",B:B,1),0)),MAX(IFERROR(MATCH(99^99,1:1,1),0),IFERROR(MATCH(\"zzzz\",1:1,1),0))))"); - assertEquals("Had: " + Arrays.toString(ptgs), - 40, ptgs.length); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[0] instanceof MemFuncPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[1] instanceof RefPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[2] instanceof AreaPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[3] instanceof NameXPxg); - - ptgs = parse(fpb, "SUM ( A1 : INDEX( 1 : 1048576 , MAX( IFERROR ( MATCH ( 99 ^ 99 , B : B , 1 ) , 0 ) , IFERROR ( MATCH ( \"zzzz\" , B:B , 1 ) , 0 ) ) , MAX ( IFERROR ( MATCH ( 99 ^ 99 , 1 : 1 , 1 ) , 0 ) , IFERROR ( MATCH ( \"zzzz\" , 1 : 1 , 1 ) , 0 ) ) ) )"); - assertEquals("Had: " + Arrays.toString(ptgs), - 40, ptgs.length); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[0] instanceof MemFuncPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[1] instanceof RefPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[2] instanceof AreaPtg); - assertTrue("Had " + Arrays.toString(ptgs), ptgs[3] instanceof NameXPxg); - - wb.close(); - } - - @Test - public void parseStructuredReferences() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("StructuredReferences.xlsx"); - - XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.create(wb); - Ptg[] ptgs; - - /* - The following cases are tested (copied from FormulaParser.parseStructuredReference) - 1 Table1[col] - 2 Table1[[#Totals],[col]] - 3 Table1[#Totals] - 4 Table1[#All] - 5 Table1[#Data] - 6 Table1[#Headers] - 7 Table1[#Totals] - 8 Table1[#This Row] - 9 Table1[[#All],[col]] - 10 Table1[[#Headers],[col]] - 11 Table1[[#Totals],[col]] - 12 Table1[[#All],[col1]:[col2]] - 13 Table1[[#Data],[col1]:[col2]] - 14 Table1[[#Headers],[col1]:[col2]] - 15 Table1[[#Totals],[col1]:[col2]] - 16 Table1[[#Headers],[#Data],[col2]] - 17 Table1[[#This Row], [col1]] - 18 Table1[ [col1]:[col2] ] - */ - - final String tbl = "\\_Prime.1"; - final String noTotalsRowReason = ": Tables without a Totals row should return #REF! on [#Totals]"; - - ////// Case 1: Evaluate Table1[col] with apostrophe-escaped #-signs //////// - ptgs = parse(fpb, "SUM("+tbl+"[calc='#*'#])"); - assertEquals(2, ptgs.length); - - // Area3DPxg [sheet=Table ! A2:A7] - assertTrue(ptgs[0] instanceof Area3DPxg); - Area3DPxg ptg0 = (Area3DPxg) ptgs[0]; - assertEquals("Table", ptg0.getSheetName()); - assertEquals("A2:A7", ptg0.format2DRefAsString()); - // Note: structured references are evaluated and resolved to regular 3D area references. - assertEquals("Table!A2:A7", ptg0.toFormulaString()); - - // AttrPtg [sum ] - assertTrue(ptgs[1] instanceof AttrPtg); - AttrPtg ptg1 = (AttrPtg) ptgs[1]; - assertTrue(ptg1.isSum()); - - ////// Case 1: Evaluate "Table1[col]" //////// - ptgs = parse(fpb, tbl+"[Name]"); - assertEquals(1, ptgs.length); - assertEquals("Table1[col]", "Table!B2:B7", ptgs[0].toFormulaString()); - - ////// Case 2: Evaluate "Table1[[#Totals],[col]]" //////// - ptgs = parse(fpb, tbl+"[[#Totals],[col]]"); - assertEquals(1, ptgs.length); - assertEquals("Table1[[#Totals],[col]]" + noTotalsRowReason, ErrPtg.REF_INVALID, ptgs[0]); - - ////// Case 3: Evaluate "Table1[#Totals]" //////// - ptgs = parse(fpb, tbl+"[#Totals]"); - assertEquals(1, ptgs.length); - assertEquals("Table1[#Totals]" + noTotalsRowReason, ErrPtg.REF_INVALID, ptgs[0]); - - ////// Case 4: Evaluate "Table1[#All]" //////// - ptgs = parse(fpb, tbl+"[#All]"); - assertEquals(1, ptgs.length); - assertEquals("Table1[#All]", "Table!A1:C7", ptgs[0].toFormulaString()); - - ////// Case 5: Evaluate "Table1[#Data]" (excludes Header and Data rows) //////// - ptgs = parse(fpb, tbl+"[#Data]"); - assertEquals(1, ptgs.length); - assertEquals("Table1[#Data]", "Table!A2:C7", ptgs[0].toFormulaString()); - - ////// Case 6: Evaluate "Table1[#Headers]" //////// - ptgs = parse(fpb, tbl+"[#Headers]"); - assertEquals(1, ptgs.length); - assertEquals("Table1[#Headers]", "Table!A1:C1", ptgs[0].toFormulaString()); - - ////// Case 7: Evaluate "Table1[#Totals]" //////// - ptgs = parse(fpb, tbl+"[#Totals]"); - assertEquals(1, ptgs.length); - assertEquals("Table1[#Totals]" + noTotalsRowReason, ErrPtg.REF_INVALID, ptgs[0]); - - ////// Case 8: Evaluate "Table1[#This Row]" //////// - ptgs = parse(fpb, tbl+"[#This Row]", 2); - assertEquals(1, ptgs.length); - assertEquals("Table1[#This Row]", "Table!A3:C3", ptgs[0].toFormulaString()); - - ////// Evaluate "Table1[@]" (equivalent to "Table1[#This Row]") //////// - ptgs = parse(fpb, tbl+"[@]", 2); - assertEquals(1, ptgs.length); - assertEquals("Table!A3:C3", ptgs[0].toFormulaString()); - - ////// Evaluate "Table1[#This Row]" when rowIndex is outside Table //////// - ptgs = parse(fpb, tbl+"[#This Row]", 10); - assertEquals(1, ptgs.length); - assertEquals("Table1[#This Row]", ErrPtg.VALUE_INVALID, ptgs[0]); - - ////// Evaluate "Table1[@]" when rowIndex is outside Table //////// - ptgs = parse(fpb, tbl+"[@]", 10); - assertEquals(1, ptgs.length); - assertEquals("Table1[@]", ErrPtg.VALUE_INVALID, ptgs[0]); - - ////// Evaluate "Table1[[#Data],[col]]" //////// - ptgs = parse(fpb, tbl+"[[#Data], [Number]]"); - assertEquals(1, ptgs.length); - assertEquals("Table1[[#Data],[col]]", "Table!C2:C7", ptgs[0].toFormulaString()); - - - ////// Case 9: Evaluate "Table1[[#All],[col]]" //////// - ptgs = parse(fpb, tbl+"[[#All], [Number]]"); - assertEquals(1, ptgs.length); - assertEquals("Table1[[#All],[col]]", "Table!C1:C7", ptgs[0].toFormulaString()); - - ////// Case 10: Evaluate "Table1[[#Headers],[col]]" //////// - ptgs = parse(fpb, tbl+"[[#Headers], [Number]]"); - assertEquals(1, ptgs.length); - // also acceptable: Table1!B1 - assertEquals("Table1[[#Headers],[col]]", "Table!C1:C1", ptgs[0].toFormulaString()); - - ////// Case 11: Evaluate "Table1[[#Totals],[col]]" //////// - ptgs = parse(fpb, tbl+"[[#Totals],[Name]]"); - assertEquals(1, ptgs.length); - assertEquals("Table1[[#Totals],[col]]" + noTotalsRowReason, ErrPtg.REF_INVALID, ptgs[0]); - - ////// Case 12: Evaluate "Table1[[#All],[col1]:[col2]]" //////// - ptgs = parse(fpb, tbl+"[[#All], [Name]:[Number]]"); - assertEquals(1, ptgs.length); - assertEquals("Table1[[#All],[col1]:[col2]]", "Table!B1:C7", ptgs[0].toFormulaString()); - - ////// Case 13: Evaluate "Table1[[#Data],[col]:[col2]]" //////// - ptgs = parse(fpb, tbl+"[[#Data], [Name]:[Number]]"); - assertEquals(1, ptgs.length); - assertEquals("Table1[[#Data],[col]:[col2]]", "Table!B2:C7", ptgs[0].toFormulaString()); - - ////// Case 14: Evaluate "Table1[[#Headers],[col1]:[col2]]" //////// - ptgs = parse(fpb, tbl+"[[#Headers], [Name]:[Number]]"); - assertEquals(1, ptgs.length); - assertEquals("Table1[[#Headers],[col1]:[col2]]", "Table!B1:C1", ptgs[0].toFormulaString()); - - ////// Case 15: Evaluate "Table1[[#Totals],[col]:[col2]]" //////// - ptgs = parse(fpb, tbl+"[[#Totals], [Name]:[Number]]"); - assertEquals(1, ptgs.length); - assertEquals("Table1[[#Totals],[col]:[col2]]" + noTotalsRowReason, ErrPtg.REF_INVALID, ptgs[0]); - - ////// Case 16: Evaluate "Table1[[#Headers],[#Data],[col]]" //////// - ptgs = parse(fpb, tbl+"[[#Headers],[#Data],[Number]]"); - assertEquals(1, ptgs.length); - assertEquals("Table1[[#Headers],[#Data],[col]]", "Table!C1:C7", ptgs[0].toFormulaString()); - - ////// Case 17: Evaluate "Table1[[#This Row], [col1]]" //////// - ptgs = parse(fpb, tbl+"[[#This Row], [Number]]", 2); - assertEquals(1, ptgs.length); - // also acceptable: Table!C3 - assertEquals("Table1[[#This Row], [col1]]", "Table!C3:C3", ptgs[0].toFormulaString()); - - ////// Case 18: Evaluate "Table1[[col]:[col2]]" //////// - ptgs = parse(fpb, tbl+"[[Name]:[Number]]"); - assertEquals(1, ptgs.length); - assertEquals("Table1[[col]:[col2]]", "Table!B2:C7", ptgs[0].toFormulaString()); - - wb.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFHeaderFooter.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFHeaderFooter.java deleted file mode 100644 index 7c50d6aed..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFHeaderFooter.java +++ /dev/null @@ -1,90 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import org.apache.poi.xssf.usermodel.extensions.XSSFHeaderFooter; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTHeaderFooter; - -import junit.framework.TestCase; - -/** - * Tests for {@link XSSFHeaderFooter} - */ -public class TestXSSFHeaderFooter extends TestCase { - public void testStripFields() { - String simple = "I am a test header"; - String withPage = "I am a&P test header"; - String withLots = "I&A am&N a&P test&T header&U"; - String withFont = "I&22 am a&\"Arial,bold\" test header"; - String withOtherAnds = "I am a&P test header&&"; - String withOtherAnds2 = "I am a&P test header&a&b"; - - assertEquals(simple, XSSFOddHeader.stripFields(simple)); - assertEquals(simple, XSSFOddHeader.stripFields(withPage)); - assertEquals(simple, XSSFOddHeader.stripFields(withLots)); - assertEquals(simple, XSSFOddHeader.stripFields(withFont)); - assertEquals(simple + "&&", XSSFOddHeader.stripFields(withOtherAnds)); - assertEquals(simple + "&a&b", XSSFOddHeader.stripFields(withOtherAnds2)); - - // Now test the default strip flag - XSSFEvenHeader head = new XSSFEvenHeader(CTHeaderFooter.Factory.newInstance()); - head.setCenter("Center"); - head.setLeft("In the left"); - - assertEquals("In the left", head.getLeft()); - assertEquals("Center", head.getCenter()); - assertEquals("", head.getRight()); - - head.setLeft("Top &P&F&D Left"); - assertEquals("Top &P&F&D Left", head.getLeft()); - assertFalse(head.areFieldsStripped()); - - head.setAreFieldsStripped(true); - assertEquals("Top Left", head.getLeft()); - assertTrue(head.areFieldsStripped()); - - // Now even more complex - head.setCenter("HEADER TEXT &P&N&D&T&Z&F&F&A&V"); - assertEquals("HEADER TEXT &V", head.getCenter()); - } - - public void testGetSetCenterLeftRight() { - - XSSFOddFooter footer = new XSSFOddFooter(CTHeaderFooter.Factory.newInstance()); - assertEquals("", footer.getCenter()); - footer.setCenter("My first center section"); - assertEquals("My first center section", footer.getCenter()); - footer.setCenter("No, let's update the center section"); - assertEquals("No, let's update the center section", footer.getCenter()); - footer.setLeft("And add a left one"); - footer.setRight("Finally the right section is added"); - assertEquals("And add a left one", footer.getLeft()); - assertEquals("Finally the right section is added", footer.getRight()); - - // Test changing the three sections value - footer.setCenter("Second center version"); - footer.setLeft("Second left version"); - footer.setRight("Second right version"); - assertEquals("Second center version", footer.getCenter()); - assertEquals("Second left version", footer.getLeft()); - assertEquals("Second right version", footer.getRight()); - - } - - // TODO Rest of tests -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFHyperlink.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFHyperlink.java deleted file mode 100644 index e03edcdd6..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFHyperlink.java +++ /dev/null @@ -1,336 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; - -import java.io.IOException; - -import org.apache.poi.common.usermodel.HyperlinkType; -import org.apache.poi.hssf.usermodel.HSSFHyperlink; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.openxml4j.opc.PackageRelationship; -import org.apache.poi.openxml4j.opc.PackageRelationshipCollection; -import org.apache.poi.ss.usermodel.BaseTestHyperlink; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CreationHelper; -import org.apache.poi.ss.usermodel.Hyperlink; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.util.CellAddress; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.xssf.XSSFITestDataProvider; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.Test; - -public final class TestXSSFHyperlink extends BaseTestHyperlink { - public TestXSSFHyperlink() { - super(XSSFITestDataProvider.instance); - } - - @Test - public void testLoadExisting() { - XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("WithMoreVariousData.xlsx"); - assertEquals(3, workbook.getNumberOfSheets()); - - XSSFSheet sheet = workbook.getSheetAt(0); - - // Check the hyperlinks - assertEquals(4, sheet.getNumHyperlinks()); - doTestHyperlinkContents(sheet); - } - - @Test - public void testCreate() throws Exception { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFSheet sheet = workbook.createSheet(); - XSSFRow row = sheet.createRow(0); - XSSFCreationHelper createHelper = workbook.getCreationHelper(); - - String[] urls = { - "http://apache.org", - "www.apache.org", - "/temp", - "c:/temp", - "http://apache.org/default.php?s=isTramsformed&submit=Search&la=*&li=*"}; - for(int i = 0; i < urls.length; i++){ - String s = urls[i]; - XSSFHyperlink link = createHelper.createHyperlink(HyperlinkType.URL); - link.setAddress(s); - - XSSFCell cell = row.createCell(i); - cell.setHyperlink(link); - } - workbook = XSSFTestDataSamples.writeOutAndReadBack(workbook); - sheet = workbook.getSheetAt(0); - PackageRelationshipCollection rels = sheet.getPackagePart().getRelationships(); - assertEquals(urls.length, rels.size()); - for(int i = 0; i < rels.size(); i++){ - PackageRelationship rel = rels.getRelationship(i); - // there should be a relationship for each URL - assertEquals(urls[i], rel.getTargetURI().toString()); - } - - // Bugzilla 53041: Hyperlink relations are duplicated when saving XSSF file - workbook = XSSFTestDataSamples.writeOutAndReadBack(workbook); - sheet = workbook.getSheetAt(0); - rels = sheet.getPackagePart().getRelationships(); - assertEquals(urls.length, rels.size()); - for(int i = 0; i < rels.size(); i++){ - PackageRelationship rel = rels.getRelationship(i); - // there should be a relationship for each URL - assertEquals(urls[i], rel.getTargetURI().toString()); - } - } - - @Test - public void testInvalidURLs() throws IOException { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFCreationHelper createHelper = workbook.getCreationHelper(); - - String[] invalidURLs = { - "http:\\apache.org", - "www.apache .org", - "c:\\temp", - "\\poi"}; - for(String s : invalidURLs){ - try { - createHelper.createHyperlink(HyperlinkType.URL).setAddress(s); - fail("expected IllegalArgumentException: " + s); - } catch (IllegalArgumentException e){ - - } - } - workbook.close(); - } - - @Test - public void testLoadSave() { - XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("WithMoreVariousData.xlsx"); - CreationHelper createHelper = workbook.getCreationHelper(); - assertEquals(3, workbook.getNumberOfSheets()); - XSSFSheet sheet = workbook.getSheetAt(0); - - // Check hyperlinks - assertEquals(4, sheet.getNumHyperlinks()); - doTestHyperlinkContents(sheet); - - - // Write out, and check - - // Load up again, check all links still there - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(workbook); - assertEquals(3, wb2.getNumberOfSheets()); - assertNotNull(wb2.getSheetAt(0)); - assertNotNull(wb2.getSheetAt(1)); - assertNotNull(wb2.getSheetAt(2)); - - sheet = wb2.getSheetAt(0); - - - // Check hyperlinks again - assertEquals(4, sheet.getNumHyperlinks()); - doTestHyperlinkContents(sheet); - - - // Add one more, and re-check - Row r17 = sheet.createRow(17); - Cell r17c = r17.createCell(2); - - Hyperlink hyperlink = createHelper.createHyperlink(HyperlinkType.URL); - hyperlink.setAddress("http://poi.apache.org/spreadsheet/"); - hyperlink.setLabel("POI SS Link"); - r17c.setHyperlink(hyperlink); - - assertEquals(5, sheet.getNumHyperlinks()); - doTestHyperlinkContents(sheet); - - assertEquals(HyperlinkType.URL, - sheet.getRow(17).getCell(2).getHyperlink().getTypeEnum()); - assertEquals("POI SS Link", - sheet.getRow(17).getCell(2).getHyperlink().getLabel()); - assertEquals("http://poi.apache.org/spreadsheet/", - sheet.getRow(17).getCell(2).getHyperlink().getAddress()); - - - // Save and re-load once more - - XSSFWorkbook wb3 = XSSFTestDataSamples.writeOutAndReadBack(wb2); - assertEquals(3, wb3.getNumberOfSheets()); - assertNotNull(wb3.getSheetAt(0)); - assertNotNull(wb3.getSheetAt(1)); - assertNotNull(wb3.getSheetAt(2)); - - sheet = wb3.getSheetAt(0); - - assertEquals(5, sheet.getNumHyperlinks()); - doTestHyperlinkContents(sheet); - - assertEquals(HyperlinkType.URL, - sheet.getRow(17).getCell(2).getHyperlink().getTypeEnum()); - assertEquals("POI SS Link", - sheet.getRow(17).getCell(2).getHyperlink().getLabel()); - assertEquals("http://poi.apache.org/spreadsheet/", - sheet.getRow(17).getCell(2).getHyperlink().getAddress()); - } - - /** - * Only for WithMoreVariousData.xlsx ! - */ - private static void doTestHyperlinkContents(XSSFSheet sheet) { - assertNotNull(sheet.getRow(3).getCell(2).getHyperlink()); - assertNotNull(sheet.getRow(14).getCell(2).getHyperlink()); - assertNotNull(sheet.getRow(15).getCell(2).getHyperlink()); - assertNotNull(sheet.getRow(16).getCell(2).getHyperlink()); - - // First is a link to poi - assertEquals(HyperlinkType.URL, - sheet.getRow(3).getCell(2).getHyperlink().getTypeEnum()); - assertEquals(null, - sheet.getRow(3).getCell(2).getHyperlink().getLabel()); - assertEquals("http://poi.apache.org/", - sheet.getRow(3).getCell(2).getHyperlink().getAddress()); - - // Next is an internal doc link - assertEquals(HyperlinkType.DOCUMENT, - sheet.getRow(14).getCell(2).getHyperlink().getTypeEnum()); - assertEquals("Internal hyperlink to A2", - sheet.getRow(14).getCell(2).getHyperlink().getLabel()); - assertEquals("Sheet1!A2", - sheet.getRow(14).getCell(2).getHyperlink().getAddress()); - - // Next is a file - assertEquals(HyperlinkType.FILE, - sheet.getRow(15).getCell(2).getHyperlink().getTypeEnum()); - assertEquals(null, - sheet.getRow(15).getCell(2).getHyperlink().getLabel()); - assertEquals("WithVariousData.xlsx", - sheet.getRow(15).getCell(2).getHyperlink().getAddress()); - - // Last is a mailto - assertEquals(HyperlinkType.EMAIL, - sheet.getRow(16).getCell(2).getHyperlink().getTypeEnum()); - assertEquals(null, - sheet.getRow(16).getCell(2).getHyperlink().getLabel()); - assertEquals("mailto:dev@poi.apache.org?subject=XSSF%20Hyperlinks", - sheet.getRow(16).getCell(2).getHyperlink().getAddress()); - } - - @Test - public void test52716() { - XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("52716.xlsx"); - XSSFSheet sh1 = wb1.getSheetAt(0); - - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - XSSFSheet sh2 = wb2.getSheetAt(0); - - assertEquals(sh1.getNumberOfComments(), sh2.getNumberOfComments()); - XSSFHyperlink l1 = sh1.getHyperlink(0, 1); - assertEquals(HyperlinkType.DOCUMENT, l1.getTypeEnum()); - assertEquals("B1", l1.getCellRef()); - assertEquals("Sort on Titel", l1.getTooltip()); - - XSSFHyperlink l2 = sh2.getHyperlink(0, 1); - assertEquals(l1.getTooltip(), l2.getTooltip()); - assertEquals(HyperlinkType.DOCUMENT, l2.getTypeEnum()); - assertEquals("B1", l2.getCellRef()); - } - - @Test - public void test53734() { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("53734.xlsx"); - XSSFHyperlink link = wb.getSheetAt(0).getRow(0).getCell(0).getHyperlink(); - assertEquals("javascript:///", link.getAddress()); - - wb = XSSFTestDataSamples.writeOutAndReadBack(wb); - link = wb.getSheetAt(0).getRow(0).getCell(0).getHyperlink(); - assertEquals("javascript:///", link.getAddress()); - } - - @Test - public void test53282() { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("53282.xlsx"); - XSSFHyperlink link = wb.getSheetAt(0).getRow(0).getCell(14).getHyperlink(); - assertEquals("mailto:nobody@nowhere.uk%C2%A0", link.getAddress()); - - wb = XSSFTestDataSamples.writeOutAndReadBack(wb); - link = wb.getSheetAt(0).getRow(0).getCell(14).getHyperlink(); - assertEquals("mailto:nobody@nowhere.uk%C2%A0", link.getAddress()); - } - - @Override - public XSSFHyperlink copyHyperlink(Hyperlink link) { - return new XSSFHyperlink(link); - } - - @Test - public void testCopyHSSFHyperlink() throws IOException { - HSSFWorkbook hssfworkbook = new HSSFWorkbook(); - HSSFHyperlink hlink = hssfworkbook.getCreationHelper().createHyperlink(HyperlinkType.URL); - hlink.setAddress("http://poi.apache.org/"); - hlink.setFirstColumn(3); - hlink.setFirstRow(2); - hlink.setLastColumn(5); - hlink.setLastRow(6); - hlink.setLabel("label"); - XSSFHyperlink xlink = new XSSFHyperlink(hlink); - - assertEquals("http://poi.apache.org/", xlink.getAddress()); - assertEquals(new CellReference(2, 3), new CellReference(xlink.getCellRef())); - // Are HSSFHyperlink.label and XSSFHyperlink.tooltip the same? If so, perhaps one of these needs renamed for a consistent Hyperlink interface - // assertEquals("label", xlink.getTooltip()); - - hssfworkbook.close(); - } - - /* bug 59775: XSSFHyperlink has wrong type if it contains a location (CTHyperlink#getLocation) - * URLs with a hash mark (#) are still URL hyperlinks, not document links - */ - @Test - public void testURLsWithHashMark() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("59775.xlsx"); - XSSFSheet sh = wb.getSheetAt(0); - CellAddress A2 = new CellAddress("A2"); - CellAddress A3 = new CellAddress("A3"); - CellAddress A4 = new CellAddress("A4"); - CellAddress A7 = new CellAddress("A7"); - - XSSFHyperlink link = sh.getHyperlink(A2); - assertEquals("address", "A2", link.getCellRef()); - assertEquals("link type", HyperlinkType.URL, link.getTypeEnum()); - assertEquals("link target", "http://twitter.com/#!/apacheorg", link.getAddress()); - - link = sh.getHyperlink(A3); - assertEquals("address", "A3", link.getCellRef()); - assertEquals("link type", HyperlinkType.URL, link.getTypeEnum()); - assertEquals("link target", "http://www.bailii.org/databases.html#ie", link.getAddress()); - - link = sh.getHyperlink(A4); - assertEquals("address", "A4", link.getCellRef()); - assertEquals("link type", HyperlinkType.URL, link.getTypeEnum()); - assertEquals("link target", "https://en.wikipedia.org/wiki/Apache_POI#See_also", link.getAddress()); - - link = sh.getHyperlink(A7); - assertEquals("address", "A7", link.getCellRef()); - assertEquals("link type", HyperlinkType.DOCUMENT, link.getTypeEnum()); - assertEquals("link target", "Sheet1", link.getAddress()); - - wb.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFName.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFName.java deleted file mode 100644 index a188a11ed..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFName.java +++ /dev/null @@ -1,133 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.Test; -import org.apache.poi.xssf.XSSFITestDataProvider; - -import static org.junit.Assert.*; - -import org.apache.poi.ss.usermodel.BaseTestNamedRange; -import org.apache.poi.ss.util.CellRangeAddress; - -/** - * @author Yegor Kozlov - */ -public final class TestXSSFName extends BaseTestNamedRange { - - public TestXSSFName() { - super(XSSFITestDataProvider.instance); - } - - //TODO combine testRepeatingRowsAndColums() for HSSF and XSSF - @Test - public void testRepeatingRowsAndColums() throws Exception { - // First test that setting RR&C for same sheet more than once only creates a - // single Print_Titles built-in record - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet1 = wb.createSheet("First Sheet"); - - sheet1.setRepeatingRows(null); - sheet1.setRepeatingColumns(null); - - // set repeating rows and columns twice for the first sheet - for (int i = 0; i < 2; i++) { - sheet1.setRepeatingRows(CellRangeAddress.valueOf("1:4")); - sheet1.setRepeatingColumns(CellRangeAddress.valueOf("A:A")); - //sheet.createFreezePane(0, 3); - } - assertEquals(1, wb.getNumberOfNames()); - XSSFName nr1 = wb.getName(XSSFName.BUILTIN_PRINT_TITLE); - - assertEquals("'First Sheet'!$A:$A,'First Sheet'!$1:$4", nr1.getRefersToFormula()); - - //remove the columns part - sheet1.setRepeatingColumns(null); - assertEquals("'First Sheet'!$1:$4", nr1.getRefersToFormula()); - - //revert - sheet1.setRepeatingColumns(CellRangeAddress.valueOf("A:A")); - - //remove the rows part - sheet1.setRepeatingRows(null); - assertEquals("'First Sheet'!$A:$A", nr1.getRefersToFormula()); - - //revert - sheet1.setRepeatingRows(CellRangeAddress.valueOf("1:4")); - - // Save and re-open - XSSFWorkbook nwb = XSSFTestDataSamples.writeOutAndReadBack(wb); - wb.close(); - - assertEquals(1, nwb.getNumberOfNames()); - nr1 = nwb.getName(XSSFName.BUILTIN_PRINT_TITLE); - - assertEquals("'First Sheet'!$A:$A,'First Sheet'!$1:$4", nr1.getRefersToFormula()); - - // check that setting RR&C on a second sheet causes a new Print_Titles built-in - // name to be created - XSSFSheet sheet2 = nwb.createSheet("SecondSheet"); - sheet2.setRepeatingRows(CellRangeAddress.valueOf("1:1")); - sheet2.setRepeatingColumns(CellRangeAddress.valueOf("B:C")); - - assertEquals(2, nwb.getNumberOfNames()); - XSSFName nr2 = nwb.getNames(XSSFName.BUILTIN_PRINT_TITLE).get(1); - - assertEquals(XSSFName.BUILTIN_PRINT_TITLE, nr2.getNameName()); - assertEquals("SecondSheet!$B:$C,SecondSheet!$1:$1", nr2.getRefersToFormula()); - - sheet2.setRepeatingRows(null); - sheet2.setRepeatingColumns(null); - nwb.close(); - } - - @Test - public void testSetNameName() throws Exception { - // Test that renaming named ranges doesn't break our new named range map - XSSFWorkbook wb = new XSSFWorkbook(); - wb.createSheet("First Sheet"); - - // Two named ranges called "name1", one scoped to sheet1 and one globally - XSSFName nameSheet1 = wb.createName(); - nameSheet1.setNameName("name1"); - nameSheet1.setRefersToFormula("'First Sheet'!$A$1"); - nameSheet1.setSheetIndex(0); - - XSSFName nameGlobal = wb.createName(); - nameGlobal.setNameName("name1"); - nameGlobal.setRefersToFormula("'First Sheet'!$B$1"); - - // Rename sheet-scoped name to "name2", check everything is updated properly - // and that the other name is unaffected - nameSheet1.setNameName("name2"); - assertEquals(1, wb.getNames("name1").size()); - assertEquals(1, wb.getNames("name2").size()); - assertEquals(nameGlobal, wb.getName("name1")); - assertEquals(nameSheet1, wb.getName("name2")); - - // Rename the other name to "name" and check everything again - nameGlobal.setNameName("name2"); - assertEquals(0, wb.getNames("name1").size()); - assertEquals(2, wb.getNames("name2").size()); - assertTrue(wb.getNames("name2").contains(nameGlobal)); - assertTrue(wb.getNames("name2").contains(nameSheet1)); - - wb.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFPicture.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFPicture.java deleted file mode 100644 index edaa974a2..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFPicture.java +++ /dev/null @@ -1,163 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import static org.junit.Assert.*; - -import java.io.IOException; -import java.util.List; - -import org.apache.poi.ss.usermodel.BaseTestPicture; -import org.apache.poi.ss.usermodel.ClientAnchor.AnchorType; -import org.apache.poi.util.LocaleUtil; -import org.apache.poi.xssf.XSSFITestDataProvider; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.Test; -import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTTwoCellAnchor; -import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.STEditAs; - -/** - * @author Yegor Kozlov - */ -public final class TestXSSFPicture extends BaseTestPicture { - - public TestXSSFPicture() { - super(XSSFITestDataProvider.instance); - } - - @Test - public void resize() throws Exception { - XSSFWorkbook wb = XSSFITestDataProvider.instance.openSampleWorkbook("resize_compare.xlsx"); - XSSFDrawing dp = wb.getSheetAt(0).createDrawingPatriarch(); - List pics = dp.getShapes(); - XSSFPicture inpPic = (XSSFPicture)pics.get(0); - XSSFPicture cmpPic = (XSSFPicture)pics.get(0); - - baseTestResize(inpPic, cmpPic, 2.0, 2.0); - wb.close(); - } - - - @Test - public void create() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - - byte[] jpegData = "test jpeg data".getBytes(LocaleUtil.CHARSET_1252); - - List pictures = wb.getAllPictures(); - assertEquals(0, pictures.size()); - - int jpegIdx = wb.addPicture(jpegData, XSSFWorkbook.PICTURE_TYPE_JPEG); - assertEquals(1, pictures.size()); - assertEquals("jpeg", pictures.get(jpegIdx).suggestFileExtension()); - assertArrayEquals(jpegData, pictures.get(jpegIdx).getData()); - - XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, 1, 1, 10, 30); - assertEquals(AnchorType.MOVE_AND_RESIZE, anchor.getAnchorType()); - anchor.setAnchorType(AnchorType.DONT_MOVE_AND_RESIZE); - assertEquals(AnchorType.DONT_MOVE_AND_RESIZE, anchor.getAnchorType()); - - XSSFPicture shape = drawing.createPicture(anchor, jpegIdx); - assertTrue(anchor.equals(shape.getAnchor())); - assertNotNull(shape.getPictureData()); - assertArrayEquals(jpegData, shape.getPictureData().getData()); - - CTTwoCellAnchor ctShapeHolder = drawing.getCTDrawing().getTwoCellAnchorArray(0); - // STEditAs.ABSOLUTE corresponds to ClientAnchor.DONT_MOVE_AND_RESIZE - assertEquals(STEditAs.ABSOLUTE, ctShapeHolder.getEditAs()); - - wb.close(); - } - - /** - * test that ShapeId in CTNonVisualDrawingProps is incremented - * - * See Bugzilla 50458 - */ - @Test - public void incrementShapeId() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - - XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, 1, 1, 10, 30); - byte[] jpegData = "picture1".getBytes(LocaleUtil.CHARSET_1252); - int jpegIdx = wb.addPicture(jpegData, XSSFWorkbook.PICTURE_TYPE_JPEG); - - XSSFPicture shape1 = drawing.createPicture(anchor, jpegIdx); - assertEquals(1, shape1.getCTPicture().getNvPicPr().getCNvPr().getId()); - - jpegData = "picture2".getBytes(LocaleUtil.CHARSET_1252); - jpegIdx = wb.addPicture(jpegData, XSSFWorkbook.PICTURE_TYPE_JPEG); - XSSFPicture shape2 = drawing.createPicture(anchor, jpegIdx); - assertEquals(2, shape2.getCTPicture().getNvPicPr().getCNvPr().getId()); - wb.close(); - } - - /** - * same image refrerred by mulitple sheets - */ - @SuppressWarnings("resource") - @Test - public void multiRelationShips() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - - byte[] pic1Data = "test jpeg data".getBytes(LocaleUtil.CHARSET_1252); - byte[] pic2Data = "test png data".getBytes(LocaleUtil.CHARSET_1252); - - List pictures = wb.getAllPictures(); - assertEquals(0, pictures.size()); - - int pic1 = wb.addPicture(pic1Data, XSSFWorkbook.PICTURE_TYPE_JPEG); - int pic2 = wb.addPicture(pic2Data, XSSFWorkbook.PICTURE_TYPE_PNG); - - XSSFSheet sheet1 = wb.createSheet(); - XSSFDrawing drawing1 = sheet1.createDrawingPatriarch(); - XSSFPicture shape1 = drawing1.createPicture(new XSSFClientAnchor(), pic1); - XSSFPicture shape2 = drawing1.createPicture(new XSSFClientAnchor(), pic2); - - XSSFSheet sheet2 = wb.createSheet(); - XSSFDrawing drawing2 = sheet2.createDrawingPatriarch(); - XSSFPicture shape3 = drawing2.createPicture(new XSSFClientAnchor(), pic2); - XSSFPicture shape4 = drawing2.createPicture(new XSSFClientAnchor(), pic1); - - assertEquals(2, pictures.size()); - - wb = XSSFTestDataSamples.writeOutAndReadBack(wb); - pictures = wb.getAllPictures(); - assertEquals(2, pictures.size()); - - sheet1 = wb.getSheetAt(0); - drawing1 = sheet1.createDrawingPatriarch(); - XSSFPicture shape11 = (XSSFPicture)drawing1.getShapes().get(0); - assertArrayEquals(shape1.getPictureData().getData(), shape11.getPictureData().getData()); - XSSFPicture shape22 = (XSSFPicture)drawing1.getShapes().get(1); - assertArrayEquals(shape2.getPictureData().getData(), shape22.getPictureData().getData()); - - sheet2 = wb.getSheetAt(1); - drawing2 = sheet2.createDrawingPatriarch(); - XSSFPicture shape33 = (XSSFPicture)drawing2.getShapes().get(0); - assertArrayEquals(shape3.getPictureData().getData(), shape33.getPictureData().getData()); - XSSFPicture shape44 = (XSSFPicture)drawing2.getShapes().get(1); - assertArrayEquals(shape4.getPictureData().getData(), shape44.getPictureData().getData()); - - wb.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFPictureData.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFPictureData.java deleted file mode 100644 index db2801fc3..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFPictureData.java +++ /dev/null @@ -1,146 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; - -import java.io.IOException; -import java.util.List; - -import org.apache.poi.util.LocaleUtil; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.Test; - -/** - * @author Yegor Kozlov - */ -public final class TestXSSFPictureData { - @Test - public void testRead() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("WithDrawing.xlsx"); - List pictures = wb.getAllPictures(); - //wb.getAllPictures() should return the same instance across multiple calls - assertSame(pictures, wb.getAllPictures()); - - assertEquals(5, pictures.size()); - String[] ext = {"jpeg", "emf", "png", "emf", "wmf"}; - String[] mimetype = {"image/jpeg", "image/x-emf", "image/png", "image/x-emf", "image/x-wmf"}; - for (int i = 0; i < pictures.size(); i++) { - assertEquals(ext[i], pictures.get(i).suggestFileExtension()); - assertEquals(mimetype[i], pictures.get(i).getMimeType()); - } - - int num = pictures.size(); - - byte[] pictureData = {0xA, 0xB, 0XC, 0xD, 0xE, 0xF}; - - int idx = wb.addPicture(pictureData, XSSFWorkbook.PICTURE_TYPE_JPEG); - assertEquals(num + 1, pictures.size()); - //idx is 0-based index in the #pictures array - assertEquals(pictures.size() - 1, idx); - XSSFPictureData pict = pictures.get(idx); - assertEquals("jpeg", pict.suggestFileExtension()); - assertArrayEquals(pictureData, pict.getData()); - wb.close(); - } - - @Test - public void testNew() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - - byte[] jpegData = "test jpeg data".getBytes(LocaleUtil.CHARSET_1252); - byte[] wmfData = "test wmf data".getBytes(LocaleUtil.CHARSET_1252); - byte[] pngData = "test png data".getBytes(LocaleUtil.CHARSET_1252); - - List pictures = wb.getAllPictures(); - assertEquals(0, pictures.size()); - - int jpegIdx = wb.addPicture(jpegData, XSSFWorkbook.PICTURE_TYPE_JPEG); - assertEquals(1, pictures.size()); - assertEquals("jpeg", pictures.get(jpegIdx).suggestFileExtension()); - assertArrayEquals(jpegData, pictures.get(jpegIdx).getData()); - - int wmfIdx = wb.addPicture(wmfData, XSSFWorkbook.PICTURE_TYPE_WMF); - assertEquals(2, pictures.size()); - assertEquals("wmf", pictures.get(wmfIdx).suggestFileExtension()); - assertArrayEquals(wmfData, pictures.get(wmfIdx).getData()); - - int pngIdx = wb.addPicture(pngData, XSSFWorkbook.PICTURE_TYPE_PNG); - assertEquals(3, pictures.size()); - assertEquals("png", pictures.get(pngIdx).suggestFileExtension()); - assertArrayEquals(pngData, pictures.get(pngIdx).getData()); - - //TODO finish usermodel API for XSSFPicture - XSSFPicture p1 = drawing.createPicture(new XSSFClientAnchor(), jpegIdx); - assertNotNull(p1); - XSSFPicture p2 = drawing.createPicture(new XSSFClientAnchor(), wmfIdx); - assertNotNull(p2); - XSSFPicture p3 = drawing.createPicture(new XSSFClientAnchor(), pngIdx); - assertNotNull(p3); - - //check that the added pictures are accessible after write - XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb); - List pictures2 = wbBack.getAllPictures(); - assertEquals(3, pictures2.size()); - - assertEquals("jpeg", pictures2.get(jpegIdx).suggestFileExtension()); - assertArrayEquals(jpegData, pictures2.get(jpegIdx).getData()); - - assertEquals("wmf", pictures2.get(wmfIdx).suggestFileExtension()); - assertArrayEquals(wmfData, pictures2.get(wmfIdx).getData()); - - assertEquals("png", pictures2.get(pngIdx).suggestFileExtension()); - assertArrayEquals(pngData, pictures2.get(pngIdx).getData()); - wbBack.close(); - wb.close(); - } - - /** - * Bug 53568: XSSFPicture.getPictureData() can return null. - */ - @Test - public void test53568() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("53568.xlsx"); - List pictures = wb.getAllPictures(); - assertNotNull(pictures); - assertEquals(4, pictures.size()); - - XSSFSheet sheet1 = wb.getSheetAt(0); - List shapes1 = sheet1.createDrawingPatriarch().getShapes(); - assertNotNull(shapes1); - assertEquals(5, shapes1.size()); - - for(int i = 0; i < wb.getNumberOfSheets(); i++){ - XSSFSheet sheet = wb.getSheetAt(i); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - for(XSSFShape shape : drawing.getShapes()){ - if(shape instanceof XSSFPicture){ - XSSFPicture pic = (XSSFPicture)shape; - XSSFPictureData picData = pic.getPictureData(); - assertNotNull(picData); - } - } - } - wb.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFPivotTableName.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFPivotTableName.java deleted file mode 100644 index 8df2a663d..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFPivotTableName.java +++ /dev/null @@ -1,112 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.util.CellReference; -import org.junit.Before; - -/** - * Test pivot tables created by named range - */ -public class TestXSSFPivotTableName extends BaseTestXSSFPivotTable { - - @Override - @Before - public void setUp(){ - wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet(); - - Row row1 = sheet.createRow(0); - // Create a cell and put a value in it. - Cell cell = row1.createCell(0); - cell.setCellValue("Names"); - Cell cell2 = row1.createCell(1); - cell2.setCellValue("#"); - Cell cell7 = row1.createCell(2); - cell7.setCellValue("Data"); - Cell cell10 = row1.createCell(3); - cell10.setCellValue("Value"); - - Row row2 = sheet.createRow(1); - Cell cell3 = row2.createCell(0); - cell3.setCellValue("Jan"); - Cell cell4 = row2.createCell(1); - cell4.setCellValue(10); - Cell cell8 = row2.createCell(2); - cell8.setCellValue("Apa"); - Cell cell11 = row1.createCell(3); - cell11.setCellValue(11.11); - - Row row3 = sheet.createRow(2); - Cell cell5 = row3.createCell(0); - cell5.setCellValue("Ben"); - Cell cell6 = row3.createCell(1); - cell6.setCellValue(9); - Cell cell9 = row3.createCell(2); - cell9.setCellValue("Bepa"); - Cell cell12 = row1.createCell(3); - cell12.setCellValue(12.12); - - XSSFName namedRange = sheet.getWorkbook().createName(); - namedRange.setRefersToFormula(sheet.getSheetName() + "!" + "A1:C2"); - pivotTable = sheet.createPivotTable(namedRange, new CellReference("H5")); - - XSSFSheet offsetSheet = wb.createSheet(); - - Row tableRow_1 = offsetSheet.createRow(1); - offsetOuterCell = tableRow_1.createCell(1); - offsetOuterCell.setCellValue(-1); - Cell tableCell_1_1 = tableRow_1.createCell(2); - tableCell_1_1.setCellValue("Row #"); - Cell tableCell_1_2 = tableRow_1.createCell(3); - tableCell_1_2.setCellValue("Exponent"); - Cell tableCell_1_3 = tableRow_1.createCell(4); - tableCell_1_3.setCellValue("10^Exponent"); - - Row tableRow_2 = offsetSheet.createRow(2); - Cell tableCell_2_1 = tableRow_2.createCell(2); - tableCell_2_1.setCellValue(0); - Cell tableCell_2_2 = tableRow_2.createCell(3); - tableCell_2_2.setCellValue(0); - Cell tableCell_2_3 = tableRow_2.createCell(4); - tableCell_2_3.setCellValue(1); - - Row tableRow_3= offsetSheet.createRow(3); - Cell tableCell_3_1 = tableRow_3.createCell(2); - tableCell_3_1.setCellValue(1); - Cell tableCell_3_2 = tableRow_3.createCell(3); - tableCell_3_2.setCellValue(1); - Cell tableCell_3_3 = tableRow_3.createCell(4); - tableCell_3_3.setCellValue(10); - - Row tableRow_4 = offsetSheet.createRow(4); - Cell tableCell_4_1 = tableRow_4.createCell(2); - tableCell_4_1.setCellValue(2); - Cell tableCell_4_2 = tableRow_4.createCell(3); - tableCell_4_2.setCellValue(2); - Cell tableCell_4_3 = tableRow_4.createCell(4); - tableCell_4_3.setCellValue(100); - - namedRange = sheet.getWorkbook().createName(); - namedRange.setRefersToFormula("C2:E4"); - namedRange.setSheetIndex(sheet.getWorkbook().getSheetIndex(sheet)); - offsetPivotTable = offsetSheet.createPivotTable(namedRange, new CellReference("C6")); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFPivotTableRef.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFPivotTableRef.java deleted file mode 100644 index ec0c5c6c1..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFPivotTableRef.java +++ /dev/null @@ -1,111 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.util.AreaReference; -import org.apache.poi.ss.util.CellReference; -import org.junit.Before; - -/** - * Test pivot tables created by area reference - */ -public class TestXSSFPivotTableRef extends BaseTestXSSFPivotTable { - - @Override - @Before - public void setUp(){ - wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet(); - - Row row1 = sheet.createRow(0); - // Create a cell and put a value in it. - Cell cell = row1.createCell(0); - cell.setCellValue("Names"); - Cell cell2 = row1.createCell(1); - cell2.setCellValue("#"); - Cell cell7 = row1.createCell(2); - cell7.setCellValue("Data"); - Cell cell10 = row1.createCell(3); - cell10.setCellValue("Value"); - - Row row2 = sheet.createRow(1); - Cell cell3 = row2.createCell(0); - cell3.setCellValue("Jan"); - Cell cell4 = row2.createCell(1); - cell4.setCellValue(10); - Cell cell8 = row2.createCell(2); - cell8.setCellValue("Apa"); - Cell cell11 = row1.createCell(3); - cell11.setCellValue(11.11); - - Row row3 = sheet.createRow(2); - Cell cell5 = row3.createCell(0); - cell5.setCellValue("Ben"); - Cell cell6 = row3.createCell(1); - cell6.setCellValue(9); - Cell cell9 = row3.createCell(2); - cell9.setCellValue("Bepa"); - Cell cell12 = row1.createCell(3); - cell12.setCellValue(12.12); - - AreaReference source = new AreaReference("A1:C2", SpreadsheetVersion.EXCEL2007); - pivotTable = sheet.createPivotTable(source, new CellReference("H5")); - - XSSFSheet offsetSheet = wb.createSheet(); - - Row tableRow_1 = offsetSheet.createRow(1); - offsetOuterCell = tableRow_1.createCell(1); - offsetOuterCell.setCellValue(-1); - Cell tableCell_1_1 = tableRow_1.createCell(2); - tableCell_1_1.setCellValue("Row #"); - Cell tableCell_1_2 = tableRow_1.createCell(3); - tableCell_1_2.setCellValue("Exponent"); - Cell tableCell_1_3 = tableRow_1.createCell(4); - tableCell_1_3.setCellValue("10^Exponent"); - - Row tableRow_2 = offsetSheet.createRow(2); - Cell tableCell_2_1 = tableRow_2.createCell(2); - tableCell_2_1.setCellValue(0); - Cell tableCell_2_2 = tableRow_2.createCell(3); - tableCell_2_2.setCellValue(0); - Cell tableCell_2_3 = tableRow_2.createCell(4); - tableCell_2_3.setCellValue(1); - - Row tableRow_3= offsetSheet.createRow(3); - Cell tableCell_3_1 = tableRow_3.createCell(2); - tableCell_3_1.setCellValue(1); - Cell tableCell_3_2 = tableRow_3.createCell(3); - tableCell_3_2.setCellValue(1); - Cell tableCell_3_3 = tableRow_3.createCell(4); - tableCell_3_3.setCellValue(10); - - Row tableRow_4 = offsetSheet.createRow(4); - Cell tableCell_4_1 = tableRow_4.createCell(2); - tableCell_4_1.setCellValue(2); - Cell tableCell_4_2 = tableRow_4.createCell(3); - tableCell_4_2.setCellValue(2); - Cell tableCell_4_3 = tableRow_4.createCell(4); - tableCell_4_3.setCellValue(100); - - AreaReference offsetSource = new AreaReference(new CellReference("C2"), new CellReference("E4")); - offsetPivotTable = offsetSheet.createPivotTable(offsetSource, new CellReference("C6")); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFPrintSetup.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFPrintSetup.java deleted file mode 100644 index 6cda3aff2..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFPrintSetup.java +++ /dev/null @@ -1,285 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import junit.framework.TestCase; - -import org.apache.poi.ss.usermodel.PageOrder; -import org.apache.poi.ss.usermodel.PaperSize; -import org.apache.poi.ss.usermodel.PrintCellComments; -import org.apache.poi.ss.usermodel.PrintOrientation; -import org.apache.poi.xssf.XSSFITestDataProvider; -import org.junit.Test; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPageMargins; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPageSetup; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STCellComments; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STOrientation; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STPageOrder; - -/** - * Tests for {@link XSSFPrintSetup} - */ -public class TestXSSFPrintSetup extends TestCase { - public void testSetGetPaperSize() { - CTWorksheet worksheet = CTWorksheet.Factory.newInstance(); - CTPageSetup pSetup = worksheet.addNewPageSetup(); - pSetup.setPaperSize(9); - XSSFPrintSetup printSetup = new XSSFPrintSetup(worksheet); - assertEquals(PaperSize.A4_PAPER, printSetup.getPaperSizeEnum()); - assertEquals(9, printSetup.getPaperSize()); - - printSetup.setPaperSize(PaperSize.A3_PAPER); - assertEquals(8, pSetup.getPaperSize()); - } - - - public void testSetGetScale() { - CTWorksheet worksheet = CTWorksheet.Factory.newInstance(); - CTPageSetup pSetup = worksheet.addNewPageSetup(); - pSetup.setScale(9); - XSSFPrintSetup printSetup = new XSSFPrintSetup(worksheet); - assertEquals(9, printSetup.getScale()); - - printSetup.setScale((short) 100); - assertEquals(100, pSetup.getScale()); - } - - public void testSetGetPageStart() { - CTWorksheet worksheet = CTWorksheet.Factory.newInstance(); - CTPageSetup pSetup = worksheet.addNewPageSetup(); - pSetup.setFirstPageNumber(9); - XSSFPrintSetup printSetup = new XSSFPrintSetup(worksheet); - assertEquals(9, printSetup.getPageStart()); - - printSetup.setPageStart((short) 1); - assertEquals(1, pSetup.getFirstPageNumber()); - } - - - public void testSetGetFitWidthHeight() { - CTWorksheet worksheet = CTWorksheet.Factory.newInstance(); - CTPageSetup pSetup = worksheet.addNewPageSetup(); - pSetup.setFitToWidth(50); - pSetup.setFitToHeight(99); - XSSFPrintSetup printSetup = new XSSFPrintSetup(worksheet); - assertEquals(50, printSetup.getFitWidth()); - assertEquals(99, printSetup.getFitHeight()); - - printSetup.setFitWidth((short) 66); - printSetup.setFitHeight((short) 80); - assertEquals(66, pSetup.getFitToWidth()); - assertEquals(80, pSetup.getFitToHeight()); - - } - - public void testSetGetLeftToRight() { - CTWorksheet worksheet = CTWorksheet.Factory.newInstance(); - CTPageSetup pSetup = worksheet.addNewPageSetup(); - pSetup.setPageOrder(STPageOrder.DOWN_THEN_OVER); - XSSFPrintSetup printSetup = new XSSFPrintSetup(worksheet); - assertEquals(false, printSetup.getLeftToRight()); - - printSetup.setLeftToRight(true); - assertEquals(PageOrder.OVER_THEN_DOWN.getValue(), pSetup.getPageOrder().intValue()); - } - - public void testSetGetOrientation() { - CTWorksheet worksheet = CTWorksheet.Factory.newInstance(); - CTPageSetup pSetup = worksheet.addNewPageSetup(); - pSetup.setOrientation(STOrientation.PORTRAIT); - XSSFPrintSetup printSetup = new XSSFPrintSetup(worksheet); - assertEquals(PrintOrientation.PORTRAIT, printSetup.getOrientation()); - assertEquals(false, printSetup.getLandscape()); - assertEquals(false, printSetup.getNoOrientation()); - - printSetup.setOrientation(PrintOrientation.LANDSCAPE); - assertEquals(pSetup.getOrientation().intValue(), printSetup.getOrientation().getValue()); - assertEquals(true, printSetup.getLandscape()); - assertEquals(false, printSetup.getNoOrientation()); - } - - - public void testSetGetValidSettings() { - CTWorksheet worksheet = CTWorksheet.Factory.newInstance(); - CTPageSetup pSetup = worksheet.addNewPageSetup(); - pSetup.setUsePrinterDefaults(false); - XSSFPrintSetup printSetup = new XSSFPrintSetup(worksheet); - assertEquals(false, printSetup.getValidSettings()); - - printSetup.setValidSettings(true); - assertEquals(true, pSetup.getUsePrinterDefaults()); - } - - public void testSetGetNoColor() { - CTWorksheet worksheet = CTWorksheet.Factory.newInstance(); - CTPageSetup pSetup = worksheet.addNewPageSetup(); - pSetup.setBlackAndWhite(false); - XSSFPrintSetup printSetup = new XSSFPrintSetup(worksheet); - assertEquals(false, printSetup.getNoColor()); - - printSetup.setNoColor(true); - assertEquals(true, pSetup.getBlackAndWhite()); - } - - public void testSetGetDraft() { - CTWorksheet worksheet = CTWorksheet.Factory.newInstance(); - CTPageSetup pSetup = worksheet.addNewPageSetup(); - pSetup.setDraft(false); - XSSFPrintSetup printSetup = new XSSFPrintSetup(worksheet); - assertEquals(false, printSetup.getDraft()); - - printSetup.setDraft(true); - assertEquals(true, pSetup.getDraft()); - } - - public void testSetGetNotes() { - CTWorksheet worksheet = CTWorksheet.Factory.newInstance(); - CTPageSetup pSetup = worksheet.addNewPageSetup(); - pSetup.setCellComments(STCellComments.NONE); - XSSFPrintSetup printSetup = new XSSFPrintSetup(worksheet); - assertEquals(false, printSetup.getNotes()); - - printSetup.setNotes(true); - assertEquals(PrintCellComments.AS_DISPLAYED.getValue(), pSetup.getCellComments().intValue()); - } - - - public void testSetGetUsePage() { - CTWorksheet worksheet = CTWorksheet.Factory.newInstance(); - CTPageSetup pSetup = worksheet.addNewPageSetup(); - pSetup.setUseFirstPageNumber(false); - XSSFPrintSetup printSetup = new XSSFPrintSetup(worksheet); - assertEquals(false, printSetup.getUsePage()); - - printSetup.setUsePage(true); - assertEquals(true, pSetup.getUseFirstPageNumber()); - } - - public void testSetGetHVResolution() { - CTWorksheet worksheet = CTWorksheet.Factory.newInstance(); - CTPageSetup pSetup = worksheet.addNewPageSetup(); - pSetup.setHorizontalDpi(120); - pSetup.setVerticalDpi(100); - XSSFPrintSetup printSetup = new XSSFPrintSetup(worksheet); - assertEquals(120, printSetup.getHResolution()); - assertEquals(100, printSetup.getVResolution()); - - printSetup.setHResolution((short) 150); - printSetup.setVResolution((short) 130); - assertEquals(150, pSetup.getHorizontalDpi()); - assertEquals(130, pSetup.getVerticalDpi()); - } - - public void testSetGetHeaderFooterMargin() { - CTWorksheet worksheet = CTWorksheet.Factory.newInstance(); - CTPageMargins pMargins = worksheet.addNewPageMargins(); - pMargins.setHeader(1.5); - pMargins.setFooter(2); - XSSFPrintSetup printSetup = new XSSFPrintSetup(worksheet); - assertEquals(1.5, printSetup.getHeaderMargin(), 0.0); - assertEquals(2.0, printSetup.getFooterMargin(), 0.0); - - printSetup.setHeaderMargin(5); - printSetup.setFooterMargin(3.5); - assertEquals(5.0, pMargins.getHeader(), 0.0); - assertEquals(3.5, pMargins.getFooter(), 0.0); - } - - public void testSetGetCopies() { - CTWorksheet worksheet = CTWorksheet.Factory.newInstance(); - CTPageSetup pSetup = worksheet.addNewPageSetup(); - pSetup.setCopies(9); - XSSFPrintSetup printSetup = new XSSFPrintSetup(worksheet); - assertEquals(9, printSetup.getCopies()); - - printSetup.setCopies((short) 15); - assertEquals(15, pSetup.getCopies()); - } - - public void testSetSaveRead() throws Exception { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet s1 = wb.createSheet(); - assertEquals(false, s1.getCTWorksheet().isSetPageSetup()); - assertEquals(true, s1.getCTWorksheet().isSetPageMargins()); - - XSSFPrintSetup print = s1.getPrintSetup(); - assertEquals(true, s1.getCTWorksheet().isSetPageSetup()); - assertEquals(true, s1.getCTWorksheet().isSetPageMargins()); - - print.setCopies((short)3); - print.setLandscape(true); - assertEquals(3, print.getCopies()); - assertEquals(true, print.getLandscape()); - - XSSFSheet s2 = wb.createSheet(); - assertEquals(false, s2.getCTWorksheet().isSetPageSetup()); - assertEquals(true, s2.getCTWorksheet().isSetPageMargins()); - - // Round trip and check - XSSFWorkbook wbBack = XSSFITestDataProvider.instance.writeOutAndReadBack(wb); - - s1 = wbBack.getSheetAt(0); - s2 = wbBack.getSheetAt(1); - - assertEquals(true, s1.getCTWorksheet().isSetPageSetup()); - assertEquals(true, s1.getCTWorksheet().isSetPageMargins()); - assertEquals(false, s2.getCTWorksheet().isSetPageSetup()); - assertEquals(true, s2.getCTWorksheet().isSetPageMargins()); - - print = s1.getPrintSetup(); - assertEquals(3, print.getCopies()); - assertEquals(true, print.getLandscape()); - - wb.close(); - } - - /** - * Open a file with print settings, save and check. - * Then, change, save, read, check - */ - public void testRoundTrip() { - // TODO - } - - @Test - public void testSetLandscapeFalse() throws Exception { - XSSFPrintSetup ps = new XSSFPrintSetup(CTWorksheet.Factory.newInstance()); - - assertFalse(ps.getLandscape()); - - ps.setLandscape(true); - assertTrue(ps.getLandscape()); - - ps.setLandscape(false); - assertFalse(ps.getLandscape()); - } - - @Test - public void testSetLeftToRight() throws Exception { - XSSFPrintSetup ps = new XSSFPrintSetup(CTWorksheet.Factory.newInstance()); - - assertFalse(ps.getLeftToRight()); - - ps.setLeftToRight(true); - assertTrue(ps.getLeftToRight()); - - ps.setLeftToRight(false); - assertFalse(ps.getLeftToRight()); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFRichTextString.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFRichTextString.java deleted file mode 100644 index 9adc5312f..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFRichTextString.java +++ /dev/null @@ -1,542 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import junit.framework.TestCase; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.model.StylesTable; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTFont; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRPrElt; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRst; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STXstring; - -import java.io.IOException; -import java.util.TreeMap; - -/** - * Tests functionality of the XSSFRichTextRun object - * - * @author Yegor Kozlov - */ -public final class TestXSSFRichTextString extends TestCase { - - public void testCreate() { - XSSFRichTextString rt = new XSSFRichTextString("Apache POI"); - assertEquals("Apache POI", rt.getString()); - assertEquals(false, rt.hasFormatting()); - - CTRst st = rt.getCTRst(); - assertTrue(st.isSetT()); - assertEquals("Apache POI", st.getT()); - assertEquals(false, rt.hasFormatting()); - - rt.append(" is cool stuff"); - assertEquals(2, st.sizeOfRArray()); - assertFalse(st.isSetT()); - - assertEquals("Apache POI is cool stuff", rt.getString()); - assertEquals(false, rt.hasFormatting()); - } - - public void testEmpty() { - XSSFRichTextString rt = new XSSFRichTextString(); - assertEquals(0, rt.getIndexOfFormattingRun(9999)); - assertEquals(-1, rt.getLengthOfFormattingRun(9999)); - assertNull(rt.getFontAtIndex(9999)); - } - - public void testApplyFont() { - XSSFRichTextString rt = new XSSFRichTextString(); - rt.append("123"); - rt.append("4567"); - rt.append("89"); - - assertEquals("123456789", rt.getString()); - assertEquals(false, rt.hasFormatting()); - - XSSFFont font1 = new XSSFFont(); - font1.setBold(true); - - rt.applyFont(2, 5, font1); - assertEquals(true, rt.hasFormatting()); - - assertEquals(4, rt.numFormattingRuns()); - assertEquals(0, rt.getIndexOfFormattingRun(0)); - assertEquals("12", rt.getCTRst().getRArray(0).getT()); - - assertEquals(2, rt.getIndexOfFormattingRun(1)); - assertEquals("345", rt.getCTRst().getRArray(1).getT()); - - assertEquals(5, rt.getIndexOfFormattingRun(2)); - assertEquals(2, rt.getLengthOfFormattingRun(2)); - assertEquals("67", rt.getCTRst().getRArray(2).getT()); - - assertEquals(7, rt.getIndexOfFormattingRun(3)); - assertEquals(2, rt.getLengthOfFormattingRun(3)); - assertEquals("89", rt.getCTRst().getRArray(3).getT()); - - - assertEquals(-1, rt.getIndexOfFormattingRun(9999)); - assertEquals(-1, rt.getLengthOfFormattingRun(9999)); - assertNull(rt.getFontAtIndex(9999)); - } - - public void testApplyFontIndex() { - XSSFRichTextString rt = new XSSFRichTextString("Apache POI"); - rt.applyFont(0, 10, (short)1); - - rt.applyFont((short)1); - - assertNotNull(rt.getFontAtIndex(0)); - } - - public void testApplyFontWithStyles() { - XSSFRichTextString rt = new XSSFRichTextString("Apache POI"); - - StylesTable tbl = new StylesTable(); - rt.setStylesTableReference(tbl); - - try { - rt.applyFont(0, 10, (short)1); - fail("Fails without styles in the table"); - } catch (IndexOutOfBoundsException e) { - // expected - } - - tbl.putFont(new XSSFFont()); - rt.applyFont(0, 10, (short)1); - rt.applyFont((short)1); - } - - public void testApplyFontException() { - XSSFRichTextString rt = new XSSFRichTextString("Apache POI"); - - rt.applyFont(0, 0, (short)1); - - try { - rt.applyFont(11, 10, (short)1); - fail("Should catch Exception here"); - } catch (IllegalArgumentException e) { - assertTrue(e.getMessage().contains("11")); - } - - try { - rt.applyFont(-1, 10, (short)1); - fail("Should catch Exception here"); - } catch (IllegalArgumentException e) { - assertTrue(e.getMessage().contains("-1")); - } - - try { - rt.applyFont(0, 555, (short)1); - fail("Should catch Exception here"); - } catch (IllegalArgumentException e) { - assertTrue(e.getMessage().contains("555")); - } - } - - public void testClearFormatting() { - - XSSFRichTextString rt = new XSSFRichTextString("Apache POI"); - assertEquals("Apache POI", rt.getString()); - assertEquals(false, rt.hasFormatting()); - - rt.clearFormatting(); - - CTRst st = rt.getCTRst(); - assertTrue(st.isSetT()); - assertEquals("Apache POI", rt.getString()); - assertEquals(0, rt.numFormattingRuns()); - assertEquals(false, rt.hasFormatting()); - - XSSFFont font = new XSSFFont(); - font.setBold(true); - - rt.applyFont(7, 10, font); - assertEquals(2, rt.numFormattingRuns()); - assertEquals(true, rt.hasFormatting()); - - rt.clearFormatting(); - - assertEquals("Apache POI", rt.getString()); - assertEquals(0, rt.numFormattingRuns()); - assertEquals(false, rt.hasFormatting()); - } - - public void testGetFonts() { - - XSSFRichTextString rt = new XSSFRichTextString(); - - XSSFFont font1 = new XSSFFont(); - font1.setFontName("Arial"); - font1.setItalic(true); - rt.append("The quick", font1); - - XSSFFont font1$ = rt.getFontOfFormattingRun(0); - assertEquals(font1.getItalic(), font1$.getItalic()); - assertEquals(font1.getFontName(), font1$.getFontName()); - - XSSFFont font2 = new XSSFFont(); - font2.setFontName("Courier"); - font2.setBold(true); - rt.append(" brown fox", font2); - - XSSFFont font2$ = rt.getFontOfFormattingRun(1); - assertEquals(font2.getBold(), font2$.getBold()); - assertEquals(font2.getFontName(), font2$.getFontName()); - } - - /** - * make sure we insert xml:space="preserve" attribute - * if a string has leading or trailing white spaces - */ - public void testPreserveSpaces() { - XSSFRichTextString rt = new XSSFRichTextString("Apache"); - CTRst ct = rt.getCTRst(); - STXstring xs = ct.xgetT(); - assertEquals("Apache", xs.xmlText()); - rt.setString(" Apache"); - assertEquals(" Apache", xs.xmlText()); - - rt.append(" POI"); - rt.append(" "); - assertEquals(" Apache POI ", rt.getString()); - assertEquals(" Apache", rt.getCTRst().getRArray(0).xgetT().xmlText()); - assertEquals(" POI", rt.getCTRst().getRArray(1).xgetT().xmlText()); - assertEquals(" ", rt.getCTRst().getRArray(2).xgetT().xmlText()); - } - - /** - * test that unicode representation_ xHHHH_ is properly processed - */ - public void testUtfDecode() throws IOException { - CTRst st = CTRst.Factory.newInstance(); - st.setT("abc_x000D_2ef_x000D_"); - XSSFRichTextString rt = new XSSFRichTextString(st); - //_x000D_ is converted into carriage return - assertEquals("abc\r2ef\r", rt.getString()); - - // Test Lowercase case - CTRst st2 = CTRst.Factory.newInstance(); - st2.setT("abc_x000d_2ef_x000d_"); - XSSFRichTextString rt2 = new XSSFRichTextString(st2); - assertEquals("abc\r2ef\r", rt2.getString()); - } - - public void testApplyFont_lowlevel(){ - CTRst st = CTRst.Factory.newInstance(); - String text = "Apache Software Foundation"; - XSSFRichTextString str = new XSSFRichTextString(text); - assertEquals(26, text.length()); - - st.addNewR().setT(text); - - TreeMap formats = str.getFormatMap(st); - assertEquals(1, formats.size()); - assertEquals(26, (int)formats.firstKey()); - assertNull(formats.get( formats.firstKey() )); - - CTRPrElt fmt1 = CTRPrElt.Factory.newInstance(); - str.applyFont(formats, 0, 6, fmt1); - assertEquals(2, formats.size()); - assertEquals("[6, 26]", formats.keySet().toString()); - Object[] runs1 = formats.values().toArray(); - assertSame(fmt1, runs1[0]); - assertSame(null, runs1[1]); - - CTRPrElt fmt2 = CTRPrElt.Factory.newInstance(); - str.applyFont(formats, 7, 15, fmt2); - assertEquals(4, formats.size()); - assertEquals("[6, 7, 15, 26]", formats.keySet().toString()); - Object[] runs2 = formats.values().toArray(); - assertSame(fmt1, runs2[0]); - assertSame(null, runs2[1]); - assertSame(fmt2, runs2[2]); - assertSame(null, runs2[3]); - - CTRPrElt fmt3 = CTRPrElt.Factory.newInstance(); - str.applyFont(formats, 6, 7, fmt3); - assertEquals(4, formats.size()); - assertEquals("[6, 7, 15, 26]", formats.keySet().toString()); - Object[] runs3 = formats.values().toArray(); - assertSame(fmt1, runs3[0]); - assertSame(fmt3, runs3[1]); - assertSame(fmt2, runs3[2]); - assertSame(null, runs3[3]); - - CTRPrElt fmt4 = CTRPrElt.Factory.newInstance(); - str.applyFont(formats, 0, 7, fmt4); - assertEquals(3, formats.size()); - assertEquals("[7, 15, 26]", formats.keySet().toString()); - Object[] runs4 = formats.values().toArray(); - assertSame(fmt4, runs4[0]); - assertSame(fmt2, runs4[1]); - assertSame(null, runs4[2]); - - CTRPrElt fmt5 = CTRPrElt.Factory.newInstance(); - str.applyFont(formats, 0, 26, fmt5); - assertEquals(1, formats.size()); - assertEquals("[26]", formats.keySet().toString()); - Object[] runs5 = formats.values().toArray(); - assertSame(fmt5, runs5[0]); - - CTRPrElt fmt6 = CTRPrElt.Factory.newInstance(); - str.applyFont(formats, 15, 26, fmt6); - assertEquals(2, formats.size()); - assertEquals("[15, 26]", formats.keySet().toString()); - Object[] runs6 = formats.values().toArray(); - assertSame(fmt5, runs6[0]); - assertSame(fmt6, runs6[1]); - - str.applyFont(formats, 0, 26, null); - assertEquals(1, formats.size()); - assertEquals("[26]", formats.keySet().toString()); - Object[] runs7 = formats.values().toArray(); - assertSame(null, runs7[0]); - - str.applyFont(formats, 15, 26, fmt6); - assertEquals(2, formats.size()); - assertEquals("[15, 26]", formats.keySet().toString()); - Object[] runs8 = formats.values().toArray(); - assertSame(null, runs8[0]); - assertSame(fmt6, runs8[1]); - - str.applyFont(formats, 15, 26, fmt5); - assertEquals(2, formats.size()); - assertEquals("[15, 26]", formats.keySet().toString()); - Object[] runs9 = formats.values().toArray(); - assertSame(null, runs9[0]); - assertSame(fmt5, runs9[1]); - - str.applyFont(formats, 2, 20, fmt6); - assertEquals(3, formats.size()); - assertEquals("[2, 20, 26]", formats.keySet().toString()); - Object[] runs10 = formats.values().toArray(); - assertSame(null, runs10[0]); - assertSame(fmt6, runs10[1]); - assertSame(fmt5, runs10[2]); - - str.applyFont(formats, 22, 24, fmt4); - assertEquals(5, formats.size()); - assertEquals("[2, 20, 22, 24, 26]", formats.keySet().toString()); - Object[] runs11 = formats.values().toArray(); - assertSame(null, runs11[0]); - assertSame(fmt6, runs11[1]); - assertSame(fmt5, runs11[2]); - assertSame(fmt4, runs11[3]); - assertSame(fmt5, runs11[4]); - - str.applyFont(formats, 0, 10, fmt1); - assertEquals(5, formats.size()); - assertEquals("[10, 20, 22, 24, 26]", formats.keySet().toString()); - Object[] runs12 = formats.values().toArray(); - assertSame(fmt1, runs12[0]); - assertSame(fmt6, runs12[1]); - assertSame(fmt5, runs12[2]); - assertSame(fmt4, runs12[3]); - assertSame(fmt5, runs12[4]); - } - - public void testApplyFont_usermodel(){ - String text = "Apache Software Foundation"; - XSSFRichTextString str = new XSSFRichTextString(text); - XSSFFont font1 = new XSSFFont(); - XSSFFont font2 = new XSSFFont(); - XSSFFont font3 = new XSSFFont(); - str.applyFont(font1); - assertEquals(1, str.numFormattingRuns()); - - str.applyFont(0, 6, font1); - str.applyFont(6, text.length(), font2); - assertEquals(2, str.numFormattingRuns()); - assertEquals("Apache", str.getCTRst().getRArray(0).getT()); - assertEquals(" Software Foundation", str.getCTRst().getRArray(1).getT()); - - str.applyFont(15, 26, font3); - assertEquals(3, str.numFormattingRuns()); - assertEquals("Apache", str.getCTRst().getRArray(0).getT()); - assertEquals(" Software", str.getCTRst().getRArray(1).getT()); - assertEquals(" Foundation", str.getCTRst().getRArray(2).getT()); - - str.applyFont(6, text.length(), font2); - assertEquals(2, str.numFormattingRuns()); - assertEquals("Apache", str.getCTRst().getRArray(0).getT()); - assertEquals(" Software Foundation", str.getCTRst().getRArray(1).getT()); - } - - public void testLineBreaks_bug48877() throws IOException{ - - XSSFFont font = new XSSFFont(); - //noinspection deprecation - font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD); - font.setFontHeightInPoints((short) 14); - XSSFRichTextString str; - STXstring t1, t2, t3; - - str = new XSSFRichTextString("Incorrect\nLine-Breaking"); - str.applyFont(0, 8, font); - t1 = str.getCTRst().getRArray(0).xgetT(); - t2 = str.getCTRst().getRArray(1).xgetT(); - assertEquals("Incorrec", t1.xmlText()); - assertEquals("t\nLine-Breaking", t2.xmlText()); - - str = new XSSFRichTextString("Incorrect\nLine-Breaking"); - str.applyFont(0, 9, font); - t1 = str.getCTRst().getRArray(0).xgetT(); - t2 = str.getCTRst().getRArray(1).xgetT(); - assertEquals("Incorrect", t1.xmlText()); - assertEquals("\nLine-Breaking", t2.xmlText()); - - str = new XSSFRichTextString("Incorrect\n Line-Breaking"); - str.applyFont(0, 9, font); - t1 = str.getCTRst().getRArray(0).xgetT(); - t2 = str.getCTRst().getRArray(1).xgetT(); - assertEquals("Incorrect", t1.xmlText()); - assertEquals("\n Line-Breaking", t2.xmlText()); - - str = new XSSFRichTextString("Tab\tseparated\n"); - t1 = str.getCTRst().xgetT(); - // trailing \n causes must be preserved - assertEquals("Tab\tseparated\n", t1.xmlText()); - - str.applyFont(0, 3, font); - t1 = str.getCTRst().getRArray(0).xgetT(); - t2 = str.getCTRst().getRArray(1).xgetT(); - assertEquals("Tab", t1.xmlText()); - assertEquals("\tseparated\n", t2.xmlText()); - - str = new XSSFRichTextString("Tab\tseparated\n"); - str.applyFont(0, 4, font); - t1 = str.getCTRst().getRArray(0).xgetT(); - t2 = str.getCTRst().getRArray(1).xgetT(); - assertEquals("Tab\t", t1.xmlText()); - assertEquals("separated\n", t2.xmlText()); - - str = new XSSFRichTextString("\n\n\nNew Line\n\n"); - str.applyFont(0, 3, font); - str.applyFont(11, 13, font); - t1 = str.getCTRst().getRArray(0).xgetT(); - t2 = str.getCTRst().getRArray(1).xgetT(); - t3 = str.getCTRst().getRArray(2).xgetT(); - // YK: don't know why, but XmlBeans converts leading tab characters to spaces - assertEquals("\n\n\n", t1.xmlText()); - assertEquals("New Line", t2.xmlText()); - assertEquals("\n\n", t3.xmlText()); - } - - public void testBug56511() { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56511.xlsx"); - for (Sheet sheet : wb) { - int lastRow = sheet.getLastRowNum(); - for (int rowIdx = sheet.getFirstRowNum(); rowIdx <= lastRow; rowIdx++) { - Row row = sheet.getRow(rowIdx); - if(row != null) { - int lastCell = row.getLastCellNum(); - - for (int cellIdx = row.getFirstCellNum(); cellIdx <= lastCell; cellIdx++) { - - Cell cell = row.getCell(cellIdx); - if (cell != null) { - //System.out.println("row " + rowIdx + " column " + cellIdx + ": " + cell.getCellType() + ": " + cell.toString()); - - XSSFRichTextString richText = (XSSFRichTextString) cell.getRichStringCellValue(); - int anzFormattingRuns = richText.numFormattingRuns(); - for (int run = 0; run < anzFormattingRuns; run++) { - /*XSSFFont font =*/ richText.getFontOfFormattingRun(run); - //System.out.println(" run " + run - // + " font " + (font == null ? "" : font.getFontName())); - } - } - } - } - } - } - } - - public void testBug56511_values() { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("56511.xlsx"); - Sheet sheet = wb.getSheetAt(0); - Row row = sheet.getRow(0); - - // verify the values to ensure future changes keep the returned information equal - XSSFRichTextString rt = (XSSFRichTextString) row.getCell(0).getRichStringCellValue(); - assertEquals(0, rt.numFormattingRuns()); - assertNull(rt.getFontOfFormattingRun(0)); - assertEquals(-1, rt.getLengthOfFormattingRun(0)); - - rt = (XSSFRichTextString) row.getCell(1).getRichStringCellValue(); - assertEquals(0, row.getCell(1).getRichStringCellValue().numFormattingRuns()); - assertNull(rt.getFontOfFormattingRun(1)); - assertEquals(-1, rt.getLengthOfFormattingRun(1)); - - rt = (XSSFRichTextString) row.getCell(2).getRichStringCellValue(); - assertEquals(2, rt.numFormattingRuns()); - assertNotNull(rt.getFontOfFormattingRun(0)); - assertEquals(4, rt.getLengthOfFormattingRun(0)); - - assertNotNull(rt.getFontOfFormattingRun(1)); - assertEquals(9, rt.getLengthOfFormattingRun(1)); - - assertNull(rt.getFontOfFormattingRun(2)); - - rt = (XSSFRichTextString) row.getCell(3).getRichStringCellValue(); - assertEquals(3, rt.numFormattingRuns()); - assertNull(rt.getFontOfFormattingRun(0)); - assertEquals(1, rt.getLengthOfFormattingRun(0)); - - assertNotNull(rt.getFontOfFormattingRun(1)); - assertEquals(3, rt.getLengthOfFormattingRun(1)); - - assertNotNull(rt.getFontOfFormattingRun(2)); - assertEquals(9, rt.getLengthOfFormattingRun(2)); - } - - public void testToString() { - XSSFRichTextString rt = new XSSFRichTextString("Apache POI"); - assertNotNull(rt.toString()); - - // TODO: normally toString() should never return null, should we adjust this? - rt = new XSSFRichTextString(); - assertNull(rt.toString()); - } - - public void test59008Font() { - XSSFFont font = new XSSFFont(CTFont.Factory.newInstance()); - - XSSFRichTextString rts = new XSSFRichTextString(); - rts.append("This is correct "); - int s1 = rts.length(); - rts.append("This is Bold Red", font); - int s2 = rts.length(); - rts.append(" This uses the default font rather than the cell style font"); - int s3 = rts.length(); - - assertEquals("", rts.getFontAtIndex(s1-1).toString()); - assertEquals(font, rts.getFontAtIndex(s2-1)); - assertEquals("", rts.getFontAtIndex(s3-1).toString()); - } - - public void test60289UtfDecode() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("60289.xlsx"); - assertEquals("Rich Text\r\nTest", wb.getSheetAt(0).getRow(1).getCell(1).getRichStringCellValue().getString()); - wb.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFRow.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFRow.java deleted file mode 100644 index 6b49d81c9..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFRow.java +++ /dev/null @@ -1,196 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; - -import java.io.IOException; - -import org.apache.poi.ss.usermodel.BaseTestXRow; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellCopyPolicy; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.xssf.XSSFITestDataProvider; -import org.junit.Test; - -/** - * Tests for XSSFRow - */ -public final class TestXSSFRow extends BaseTestXRow { - - public TestXSSFRow() { - super(XSSFITestDataProvider.instance); - } - - @Test - public void testCopyRowFrom() throws IOException { - final XSSFWorkbook workbook = new XSSFWorkbook(); - final XSSFSheet sheet = workbook.createSheet("test"); - final XSSFRow srcRow = sheet.createRow(0); - srcRow.createCell(0).setCellValue("Hello"); - final XSSFRow destRow = sheet.createRow(1); - - destRow.copyRowFrom(srcRow, new CellCopyPolicy()); - assertNotNull(destRow.getCell(0)); - assertEquals("Hello", destRow.getCell(0).getStringCellValue()); - - workbook.close(); - } - - @Test - public void testCopyRowFromExternalSheet() throws IOException { - final XSSFWorkbook workbook = new XSSFWorkbook(); - final Sheet srcSheet = workbook.createSheet("src"); - final XSSFSheet destSheet = workbook.createSheet("dest"); - workbook.createSheet("other"); - - final Row srcRow = srcSheet.createRow(0); - int col = 0; - //Test 2D and 3D Ref Ptgs (Pxg for OOXML Workbooks) - srcRow.createCell(col++).setCellFormula("B5"); - srcRow.createCell(col++).setCellFormula("src!B5"); - srcRow.createCell(col++).setCellFormula("dest!B5"); - srcRow.createCell(col++).setCellFormula("other!B5"); - - //Test 2D and 3D Ref Ptgs with absolute row - srcRow.createCell(col++).setCellFormula("B$5"); - srcRow.createCell(col++).setCellFormula("src!B$5"); - srcRow.createCell(col++).setCellFormula("dest!B$5"); - srcRow.createCell(col++).setCellFormula("other!B$5"); - - //Test 2D and 3D Area Ptgs (Pxg for OOXML Workbooks) - srcRow.createCell(col++).setCellFormula("SUM(B5:D$5)"); - srcRow.createCell(col++).setCellFormula("SUM(src!B5:D$5)"); - srcRow.createCell(col++).setCellFormula("SUM(dest!B5:D$5)"); - srcRow.createCell(col++).setCellFormula("SUM(other!B5:D$5)"); - - ////////////////// - - final XSSFRow destRow = destSheet.createRow(1); - destRow.copyRowFrom(srcRow, new CellCopyPolicy()); - - ////////////////// - - //Test 2D and 3D Ref Ptgs (Pxg for OOXML Workbooks) - col = 0; - Cell cell = destRow.getCell(col++); - assertNotNull(cell); - assertEquals("RefPtg", "B6", cell.getCellFormula()); - - cell = destRow.getCell(col++); - assertNotNull(cell); - assertEquals("Ref3DPtg", "src!B6", cell.getCellFormula()); - - cell = destRow.getCell(col++); - assertNotNull(cell); - assertEquals("Ref3DPtg", "dest!B6", cell.getCellFormula()); - - cell = destRow.getCell(col++); - assertNotNull(cell); - assertEquals("Ref3DPtg", "other!B6", cell.getCellFormula()); - - ///////////////////////////////////////////// - - //Test 2D and 3D Ref Ptgs with absolute row (Ptg row number shouldn't change) - cell = destRow.getCell(col++); - assertNotNull(cell); - assertEquals("RefPtg", "B$5", cell.getCellFormula()); - - cell = destRow.getCell(col++); - assertNotNull(cell); - assertEquals("Ref3DPtg", "src!B$5", cell.getCellFormula()); - - cell = destRow.getCell(col++); - assertNotNull(cell); - assertEquals("Ref3DPtg", "dest!B$5", cell.getCellFormula()); - - cell = destRow.getCell(col++); - assertNotNull(cell); - assertEquals("Ref3DPtg", "other!B$5", cell.getCellFormula()); - - ////////////////////////////////////////// - - //Test 2D and 3D Area Ptgs (Pxg for OOXML Workbooks) - // Note: absolute row changes from last cell to first cell in order - // to maintain topLeft:bottomRight order - cell = destRow.getCell(col++); - assertNotNull(cell); - assertEquals("Area2DPtg", "SUM(B$5:D6)", cell.getCellFormula()); - - cell = destRow.getCell(col++); - assertNotNull(cell); - assertEquals("Area3DPtg", "SUM(src!B$5:D6)", cell.getCellFormula()); - - cell = destRow.getCell(col++); - assertNotNull(destRow.getCell(6)); - assertEquals("Area3DPtg", "SUM(dest!B$5:D6)", cell.getCellFormula()); - - cell = destRow.getCell(col++); - assertNotNull(destRow.getCell(7)); - assertEquals("Area3DPtg", "SUM(other!B$5:D6)", cell.getCellFormula()); - - workbook.close(); - } - - @Test - public void testCopyRowOverwritesExistingRow() throws IOException { - final XSSFWorkbook workbook = new XSSFWorkbook(); - final XSSFSheet sheet1 = workbook.createSheet("Sheet1"); - final Sheet sheet2 = workbook.createSheet("Sheet2"); - - final Row srcRow = sheet1.createRow(0); - final XSSFRow destRow = sheet1.createRow(1); - final Row observerRow = sheet1.createRow(2); - final Row externObserverRow = sheet2.createRow(0); - - srcRow.createCell(0).setCellValue("hello"); - srcRow.createCell(1).setCellValue("world"); - destRow.createCell(0).setCellValue(5.0); //A2 -> 5.0 - destRow.createCell(1).setCellFormula("A1"); // B2 -> A1 -> "hello" - observerRow.createCell(0).setCellFormula("A2"); // A3 -> A2 -> 5.0 - observerRow.createCell(1).setCellFormula("B2"); // B3 -> B2 -> A1 -> "hello" - externObserverRow.createCell(0).setCellFormula("Sheet1!A2"); //Sheet2!A1 -> Sheet1!A2 -> 5.0 - - // overwrite existing destRow with row-copy of srcRow - destRow.copyRowFrom(srcRow, new CellCopyPolicy()); - - // copyRowFrom should update existing destRow, rather than creating a new row and reassigning the destRow pointer - // to the new row (and allow the old row to be garbage collected) - // this is mostly so existing references to rows that are overwritten are updated - // rather than allowing users to continue updating rows that are no longer part of the sheet - assertSame("existing references to srcRow are still valid", srcRow, sheet1.getRow(0)); - assertSame("existing references to destRow are still valid", destRow, sheet1.getRow(1)); - assertSame("existing references to observerRow are still valid", observerRow, sheet1.getRow(2)); - assertSame("existing references to externObserverRow are still valid", externObserverRow, sheet2.getRow(0)); - - // Make sure copyRowFrom actually copied row (this is tested elsewhere) - assertEquals(CellType.STRING, destRow.getCell(0).getCellTypeEnum()); - assertEquals("hello", destRow.getCell(0).getStringCellValue()); - - // We don't want #REF! errors if we copy a row that contains cells that are referred to by other cells outside of copied region - assertEquals("references to overwritten cells are unmodified", "A2", observerRow.getCell(0).getCellFormula()); - assertEquals("references to overwritten cells are unmodified", "B2", observerRow.getCell(1).getCellFormula()); - assertEquals("references to overwritten cells are unmodified", "Sheet1!A2", externObserverRow.getCell(0).getCellFormula()); - - workbook.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheet.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheet.java deleted file mode 100644 index 27bfe5b2a..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheet.java +++ /dev/null @@ -1,2000 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import static org.apache.poi.xssf.XSSFTestDataSamples.openSampleWorkbook; -import static org.apache.poi.xssf.XSSFTestDataSamples.writeOutAndReadBack; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.util.Arrays; -import java.util.Calendar; -import java.util.Date; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.poi.POIXMLException; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.poifs.crypt.CryptoFunctions; -import org.apache.poi.poifs.crypt.HashAlgorithm; -import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.ss.usermodel.AutoFilter; -import org.apache.poi.ss.usermodel.BaseTestXSheet; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellCopyPolicy; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.ClientAnchor; -import org.apache.poi.ss.usermodel.Comment; -import org.apache.poi.ss.usermodel.CreationHelper; -import org.apache.poi.ss.usermodel.Drawing; -import org.apache.poi.ss.usermodel.FormulaError; -import org.apache.poi.ss.usermodel.IgnoredErrorType; -import org.apache.poi.ss.usermodel.IndexedColors; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.AreaReference; -import org.apache.poi.ss.util.CellAddress; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.ss.util.CellUtil; -import org.apache.poi.util.LocaleUtil; -import org.apache.poi.xssf.XSSFITestDataProvider; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.model.CalculationChain; -import org.apache.poi.xssf.model.CommentsTable; -import org.apache.poi.xssf.model.StylesTable; -import org.apache.poi.xssf.streaming.SXSSFWorkbook; -import org.apache.poi.xssf.usermodel.helpers.ColumnHelper; -import org.junit.Test; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCalcPr; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCell; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCol; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCols; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTComments; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTIgnoredError; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRow; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTSheetData; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTSheetProtection; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTXf; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STCalcMode; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STPane; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STUnsignedShortHex; - - -public final class TestXSSFSheet extends BaseTestXSheet { - - public TestXSSFSheet() { - super(XSSFITestDataProvider.instance); - } - - //TODO column styles are not yet supported by XSSF - @Override - @Test - public void defaultColumnStyle() { - //super.defaultColumnStyle(); - } - - @Test - public void getSetMargin() throws IOException { - baseTestGetSetMargin(new double[]{0.7, 0.7, 0.75, 0.75, 0.3, 0.3}); - } - - @Test - public void existingHeaderFooter() throws IOException { - XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("45540_classic_Header.xlsx"); - XSSFOddHeader hdr; - XSSFOddFooter ftr; - - // Sheet 1 has a header with center and right text - XSSFSheet s1 = wb1.getSheetAt(0); - assertNotNull(s1.getHeader()); - assertNotNull(s1.getFooter()); - hdr = (XSSFOddHeader) s1.getHeader(); - ftr = (XSSFOddFooter) s1.getFooter(); - - assertEquals("&Ctestdoc&Rtest phrase", hdr.getText()); - assertEquals(null, ftr.getText()); - - assertEquals("", hdr.getLeft()); - assertEquals("testdoc", hdr.getCenter()); - assertEquals("test phrase", hdr.getRight()); - - assertEquals("", ftr.getLeft()); - assertEquals("", ftr.getCenter()); - assertEquals("", ftr.getRight()); - - // Sheet 2 has a footer, but it's empty - XSSFSheet s2 = wb1.getSheetAt(1); - assertNotNull(s2.getHeader()); - assertNotNull(s2.getFooter()); - hdr = (XSSFOddHeader) s2.getHeader(); - ftr = (XSSFOddFooter) s2.getFooter(); - - assertEquals(null, hdr.getText()); - assertEquals("&L&F", ftr.getText()); - - assertEquals("", hdr.getLeft()); - assertEquals("", hdr.getCenter()); - assertEquals("", hdr.getRight()); - - assertEquals("&F", ftr.getLeft()); - assertEquals("", ftr.getCenter()); - assertEquals("", ftr.getRight()); - - // Save and reload - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - - hdr = (XSSFOddHeader) wb2.getSheetAt(0).getHeader(); - ftr = (XSSFOddFooter) wb2.getSheetAt(0).getFooter(); - - assertEquals("", hdr.getLeft()); - assertEquals("testdoc", hdr.getCenter()); - assertEquals("test phrase", hdr.getRight()); - - assertEquals("", ftr.getLeft()); - assertEquals("", ftr.getCenter()); - assertEquals("", ftr.getRight()); - - wb2.close(); - } - - @Test - public void getAllHeadersFooters() throws IOException { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFSheet sheet = workbook.createSheet("Sheet 1"); - assertNotNull(sheet.getOddFooter()); - assertNotNull(sheet.getEvenFooter()); - assertNotNull(sheet.getFirstFooter()); - assertNotNull(sheet.getOddHeader()); - assertNotNull(sheet.getEvenHeader()); - assertNotNull(sheet.getFirstHeader()); - - assertEquals("", sheet.getOddFooter().getLeft()); - sheet.getOddFooter().setLeft("odd footer left"); - assertEquals("odd footer left", sheet.getOddFooter().getLeft()); - - assertEquals("", sheet.getEvenFooter().getLeft()); - sheet.getEvenFooter().setLeft("even footer left"); - assertEquals("even footer left", sheet.getEvenFooter().getLeft()); - - assertEquals("", sheet.getFirstFooter().getLeft()); - sheet.getFirstFooter().setLeft("first footer left"); - assertEquals("first footer left", sheet.getFirstFooter().getLeft()); - - assertEquals("", sheet.getOddHeader().getLeft()); - sheet.getOddHeader().setLeft("odd header left"); - assertEquals("odd header left", sheet.getOddHeader().getLeft()); - - assertEquals("", sheet.getOddHeader().getRight()); - sheet.getOddHeader().setRight("odd header right"); - assertEquals("odd header right", sheet.getOddHeader().getRight()); - - assertEquals("", sheet.getOddHeader().getCenter()); - sheet.getOddHeader().setCenter("odd header center"); - assertEquals("odd header center", sheet.getOddHeader().getCenter()); - - // Defaults are odd - assertEquals("odd footer left", sheet.getFooter().getLeft()); - assertEquals("odd header center", sheet.getHeader().getCenter()); - - workbook.close(); - } - - @Test - public void autoSizeColumn() throws IOException { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFSheet sheet = workbook.createSheet("Sheet 1"); - sheet.createRow(0).createCell(13).setCellValue("test"); - - sheet.autoSizeColumn(13); - - ColumnHelper columnHelper = sheet.getColumnHelper(); - CTCol col = columnHelper.getColumn(13, false); - assertTrue(col.getBestFit()); - workbook.close(); - } - - - @Test - public void setCellComment() throws IOException { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFSheet sheet = workbook.createSheet(); - - XSSFDrawing dg = sheet.createDrawingPatriarch(); - XSSFComment comment = dg.createCellComment(new XSSFClientAnchor()); - - Cell cell = sheet.createRow(0).createCell(0); - CommentsTable comments = sheet.getCommentsTable(false); - CTComments ctComments = comments.getCTComments(); - - cell.setCellComment(comment); - assertEquals("A1", ctComments.getCommentList().getCommentArray(0).getRef()); - comment.setAuthor("test A1 author"); - assertEquals("test A1 author", comments.getAuthor((int) ctComments.getCommentList().getCommentArray(0).getAuthorId())); - workbook.close(); - } - - @Test - public void getActiveCell() throws IOException { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFSheet sheet = workbook.createSheet(); - CellAddress R5 = new CellAddress("R5"); - sheet.setActiveCell(R5); - - assertEquals(R5, sheet.getActiveCell()); - workbook.close(); - } - - @Test - public void createFreezePane_XSSF() throws IOException { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFSheet sheet = workbook.createSheet(); - CTWorksheet ctWorksheet = sheet.getCTWorksheet(); - - sheet.createFreezePane(2, 4); - assertEquals(2.0, ctWorksheet.getSheetViews().getSheetViewArray(0).getPane().getXSplit(), 0.0); - assertEquals(STPane.BOTTOM_RIGHT, ctWorksheet.getSheetViews().getSheetViewArray(0).getPane().getActivePane()); - sheet.createFreezePane(3, 6, 10, 10); - assertEquals(3.0, ctWorksheet.getSheetViews().getSheetViewArray(0).getPane().getXSplit(), 0.0); - // assertEquals(10, sheet.getTopRow()); - // assertEquals(10, sheet.getLeftCol()); - sheet.createSplitPane(4, 8, 12, 12, 1); - assertEquals(8.0, ctWorksheet.getSheetViews().getSheetViewArray(0).getPane().getYSplit(), 0.0); - assertEquals(STPane.BOTTOM_RIGHT, ctWorksheet.getSheetViews().getSheetViewArray(0).getPane().getActivePane()); - - workbook.close(); - } - - @Test - public void removeMergedRegion_lowlevel() throws IOException { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFSheet sheet = workbook.createSheet(); - CTWorksheet ctWorksheet = sheet.getCTWorksheet(); - CellRangeAddress region_1 = CellRangeAddress.valueOf("A1:B2"); - CellRangeAddress region_2 = CellRangeAddress.valueOf("C3:D4"); - CellRangeAddress region_3 = CellRangeAddress.valueOf("E5:F6"); - CellRangeAddress region_4 = CellRangeAddress.valueOf("G7:H8"); - sheet.addMergedRegion(region_1); - sheet.addMergedRegion(region_2); - sheet.addMergedRegion(region_3); - assertEquals("C3:D4", ctWorksheet.getMergeCells().getMergeCellArray(1).getRef()); - assertEquals(3, sheet.getNumMergedRegions()); - sheet.removeMergedRegion(1); - assertEquals("E5:F6", ctWorksheet.getMergeCells().getMergeCellArray(1).getRef()); - assertEquals(2, sheet.getNumMergedRegions()); - sheet.removeMergedRegion(1); - sheet.removeMergedRegion(0); - assertEquals(0, sheet.getNumMergedRegions()); - assertNull(" CTMergeCells should be deleted after removing the last merged " + - "region on the sheet.", sheet.getCTWorksheet().getMergeCells()); - sheet.addMergedRegion(region_1); - sheet.addMergedRegion(region_2); - sheet.addMergedRegion(region_3); - sheet.addMergedRegion(region_4); - // test invalid indexes OOBE - Set rmIdx = new HashSet(Arrays.asList(5,6)); - sheet.removeMergedRegions(rmIdx); - rmIdx = new HashSet(Arrays.asList(1,3)); - sheet.removeMergedRegions(rmIdx); - assertEquals("A1:B2", ctWorksheet.getMergeCells().getMergeCellArray(0).getRef()); - assertEquals("E5:F6", ctWorksheet.getMergeCells().getMergeCellArray(1).getRef()); - workbook.close(); - } - - @Test - public void setDefaultColumnStyle() throws IOException { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFSheet sheet = workbook.createSheet(); - CTWorksheet ctWorksheet = sheet.getCTWorksheet(); - StylesTable stylesTable = workbook.getStylesSource(); - XSSFFont font = new XSSFFont(); - font.setFontName("Cambria"); - stylesTable.putFont(font); - CTXf cellStyleXf = CTXf.Factory.newInstance(); - cellStyleXf.setFontId(1); - cellStyleXf.setFillId(0); - cellStyleXf.setBorderId(0); - cellStyleXf.setNumFmtId(0); - stylesTable.putCellStyleXf(cellStyleXf); - CTXf cellXf = CTXf.Factory.newInstance(); - cellXf.setXfId(1); - stylesTable.putCellXf(cellXf); - XSSFCellStyle cellStyle = new XSSFCellStyle(1, 1, stylesTable, null); - assertEquals(1, cellStyle.getFontIndex()); - - sheet.setDefaultColumnStyle(3, cellStyle); - assertEquals(1, ctWorksheet.getColsArray(0).getColArray(0).getStyle()); - workbook.close(); - } - - - @Test - public void groupUngroupColumn() throws IOException { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFSheet sheet = workbook.createSheet(); - - //one level - sheet.groupColumn(2, 7); - sheet.groupColumn(10, 11); - CTCols cols = sheet.getCTWorksheet().getColsArray(0); - assertEquals(2, cols.sizeOfColArray()); - CTCol[] colArray = cols.getColArray(); - assertNotNull(colArray); - assertEquals(2 + 1, colArray[0].getMin()); // 1 based - assertEquals(7 + 1, colArray[0].getMax()); // 1 based - assertEquals(1, colArray[0].getOutlineLevel()); - assertEquals(0, sheet.getColumnOutlineLevel(0)); - - //two level - sheet.groupColumn(1, 2); - cols = sheet.getCTWorksheet().getColsArray(0); - assertEquals(4, cols.sizeOfColArray()); - colArray = cols.getColArray(); - assertEquals(2, colArray[1].getOutlineLevel()); - - //three level - sheet.groupColumn(6, 8); - sheet.groupColumn(2, 3); - cols = sheet.getCTWorksheet().getColsArray(0); - assertEquals(7, cols.sizeOfColArray()); - colArray = cols.getColArray(); - assertEquals(3, colArray[1].getOutlineLevel()); - assertEquals(3, sheet.getCTWorksheet().getSheetFormatPr().getOutlineLevelCol()); - - sheet.ungroupColumn(8, 10); - colArray = cols.getColArray(); - //assertEquals(3, colArray[1].getOutlineLevel()); - - sheet.ungroupColumn(4, 6); - sheet.ungroupColumn(2, 2); - colArray = cols.getColArray(); - assertEquals(4, colArray.length); - assertEquals(2, sheet.getCTWorksheet().getSheetFormatPr().getOutlineLevelCol()); - - workbook.close(); - } - - @Test - public void groupUngroupRow() throws IOException { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFSheet sheet = workbook.createSheet(); - - //one level - sheet.groupRow(9, 10); - assertEquals(2, sheet.getPhysicalNumberOfRows()); - CTRow ctrow = sheet.getRow(9).getCTRow(); - - assertNotNull(ctrow); - assertEquals(10, ctrow.getR()); - assertEquals(1, ctrow.getOutlineLevel()); - assertEquals(1, sheet.getCTWorksheet().getSheetFormatPr().getOutlineLevelRow()); - - //two level - sheet.groupRow(10, 13); - assertEquals(5, sheet.getPhysicalNumberOfRows()); - ctrow = sheet.getRow(10).getCTRow(); - assertNotNull(ctrow); - assertEquals(11, ctrow.getR()); - assertEquals(2, ctrow.getOutlineLevel()); - assertEquals(2, sheet.getCTWorksheet().getSheetFormatPr().getOutlineLevelRow()); - - - sheet.ungroupRow(8, 10); - assertEquals(4, sheet.getPhysicalNumberOfRows()); - assertEquals(1, sheet.getCTWorksheet().getSheetFormatPr().getOutlineLevelRow()); - - sheet.ungroupRow(10, 10); - assertEquals(3, sheet.getPhysicalNumberOfRows()); - - assertEquals(1, sheet.getCTWorksheet().getSheetFormatPr().getOutlineLevelRow()); - - workbook.close(); - } - - @Test(expected=IllegalArgumentException.class) - public void setZoom() throws IOException { - XSSFWorkbook workBook = new XSSFWorkbook(); - XSSFSheet sheet1 = workBook.createSheet("new sheet"); - sheet1.setZoom(75); // 75 percent magnification - long zoom = sheet1.getCTWorksheet().getSheetViews().getSheetViewArray(0).getZoomScale(); - assertEquals(zoom, 75); - - sheet1.setZoom(200); - zoom = sheet1.getCTWorksheet().getSheetViews().getSheetViewArray(0).getZoomScale(); - assertEquals(zoom, 200); - - // Valid scale values range from 10 to 400 - try { - sheet1.setZoom(500); - } finally { - workBook.close(); - } - } - - /** - * TODO - while this is internally consistent, I'm not - * completely clear in all cases what it's supposed to - * be doing... Someone who understands the goals a little - * better should really review this! - */ - @Test - public void setColumnGroupCollapsed() throws IOException { - XSSFWorkbook wb1 = new XSSFWorkbook(); - XSSFSheet sheet1 = wb1.createSheet(); - - CTCols cols = sheet1.getCTWorksheet().getColsArray(0); - assertEquals(0, cols.sizeOfColArray()); - - sheet1.groupColumn( 4, 7 ); - - assertEquals(1, cols.sizeOfColArray()); - checkColumnGroup(cols.getColArray(0), 4, 7); // false, true - - sheet1.groupColumn( 9, 12 ); - - assertEquals(2, cols.sizeOfColArray()); - checkColumnGroup(cols.getColArray(0), 4, 7); // false, true - checkColumnGroup(cols.getColArray(1), 9, 12); // false, true - - sheet1.groupColumn( 10, 11 ); - - assertEquals(4, cols.sizeOfColArray()); - checkColumnGroup(cols.getColArray(0), 4, 7); // false, true - checkColumnGroup(cols.getColArray(1), 9, 9); // false, true - checkColumnGroup(cols.getColArray(2), 10, 11); // false, true - checkColumnGroup(cols.getColArray(3), 12, 12); // false, true - - // collapse columns - 1 - sheet1.setColumnGroupCollapsed( 5, true ); - - // FIXME: we grew a column? - assertEquals(5, cols.sizeOfColArray()); - checkColumnGroupIsCollapsed(cols.getColArray(0), 4, 7); // true, true - checkColumnGroup(cols.getColArray(1), 8, 8); // false, true - checkColumnGroup(cols.getColArray(2), 9, 9); // false, true - checkColumnGroup(cols.getColArray(3), 10, 11); // false, true - checkColumnGroup(cols.getColArray(4), 12, 12); // false, true - - - // expand columns - 1 - sheet1.setColumnGroupCollapsed( 5, false ); - assertEquals(5, cols.sizeOfColArray()); - - checkColumnGroupIsExpanded(cols.getColArray(0), 4, 7); // false, true - checkColumnGroup(cols.getColArray(1), 8, 8, false, false); - checkColumnGroup(cols.getColArray(2), 9, 9); // false, true - checkColumnGroup(cols.getColArray(3), 10, 11); // false, true - checkColumnGroup(cols.getColArray(4), 12, 12); // false, true - - - //collapse - 2 - sheet1.setColumnGroupCollapsed( 9, true ); - // it grew again? - assertEquals(6, cols.sizeOfColArray()); - checkColumnGroup(cols.getColArray(0), 4, 7); // false, true - checkColumnGroup(cols.getColArray(1), 8, 8, false, false); - checkColumnGroupIsCollapsed(cols.getColArray(2), 9, 9); // true, true - checkColumnGroupIsCollapsed(cols.getColArray(3), 10, 11); // true, true - checkColumnGroupIsCollapsed(cols.getColArray(4), 12, 12); // true, true - // why was this column group added? - checkColumnGroup(cols.getColArray(5), 13, 13); // false, true - - - //expand - 2 - sheet1.setColumnGroupCollapsed( 9, false ); - assertEquals(6, cols.sizeOfColArray()); - - //outline level 2: the line under ==> collapsed==True - assertEquals(2, cols.getColArray(3).getOutlineLevel()); - assertTrue(cols.getColArray(4).isSetCollapsed()); - - checkColumnGroup(cols.getColArray(0), 4, 7); - checkColumnGroup(cols.getColArray(1), 8, 8, false, false); - checkColumnGroup(cols.getColArray(2), 9, 9); // false, true - checkColumnGroupIsCollapsed(cols.getColArray(3), 10, 11); // true, true - checkColumnGroup(cols.getColArray(4), 12, 12); // false, true - checkColumnGroup(cols.getColArray(5), 13, 13, false, false); - - //DOCUMENTARE MEGLIO IL DISCORSO DEL LIVELLO - //collapse - 3 - sheet1.setColumnGroupCollapsed( 10, true ); - assertEquals(6, cols.sizeOfColArray()); - checkColumnGroup(cols.getColArray(0), 4, 7); - checkColumnGroup(cols.getColArray(1), 8, 8, false, false); - checkColumnGroup(cols.getColArray(2), 9, 9); // false, true - checkColumnGroupIsCollapsed(cols.getColArray(3), 10, 11); // true, true - checkColumnGroup(cols.getColArray(4), 12, 12); // false, true - checkColumnGroup(cols.getColArray(5), 13, 13, false, false); - - - //expand - 3 - sheet1.setColumnGroupCollapsed( 10, false ); - assertEquals(6, cols.sizeOfColArray()); - assertFalse(cols.getColArray(0).getHidden()); - assertFalse(cols.getColArray(5).getHidden()); - assertFalse(cols.getColArray(4).isSetCollapsed()); - -// write out and give back - // Save and re-load - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sheet1 = wb2.getSheetAt(0); - // FIXME: forgot to reassign! - //cols = sheet1.getCTWorksheet().getColsArray(0); - - assertEquals(6, cols.sizeOfColArray()); - checkColumnGroup(cols.getColArray(0), 4, 7); // false, true - checkColumnGroup(cols.getColArray(1), 8, 8, false, false); - checkColumnGroup(cols.getColArray(2), 9, 9); // false, true - checkColumnGroup(cols.getColArray(3), 10, 11); // false, true - checkColumnGroup(cols.getColArray(4), 12, 12, false, false); - checkColumnGroup(cols.getColArray(5), 13, 13, false, false); - - wb2.close(); - } - - /** - * Verify that column groups were created correctly after Sheet.groupColumn - * - * @param col the column group xml bean - * @param fromColumnIndex 0-indexed - * @param toColumnIndex 0-indexed - */ - private static void checkColumnGroup( - CTCol col, - int fromColumnIndex, int toColumnIndex, - boolean isSetHidden, boolean isSetCollapsed - ) { - assertEquals("from column index", fromColumnIndex, col.getMin() - 1); // 1 based - assertEquals("to column index", toColumnIndex, col.getMax() - 1); // 1 based - assertEquals("isSetHidden", isSetHidden, col.isSetHidden()); - assertEquals("isSetCollapsed", isSetCollapsed, col.isSetCollapsed()); //not necessarily set - } - - /** - * Verify that column groups were created correctly after Sheet.groupColumn - * - * @param col the column group xml bean - * @param fromColumnIndex 0-indexed - * @param toColumnIndex 0-indexed - */ - private static void checkColumnGroup( - CTCol col, - int fromColumnIndex, int toColumnIndex - ) { - assertEquals("from column index", fromColumnIndex, col.getMin() - 1); // 1 based - assertEquals("to column index", toColumnIndex, col.getMax() - 1); // 1 based - assertFalse("isSetHidden", col.isSetHidden()); - assertTrue("isSetCollapsed", col.isSetCollapsed()); //not necessarily set - } - /** - * Verify that column groups were created correctly after Sheet.groupColumn - * - * @param col the column group xml bean - * @param fromColumnIndex 0-indexed - * @param toColumnIndex 0-indexed - */ - private static void checkColumnGroupIsCollapsed( - CTCol col, - int fromColumnIndex, int toColumnIndex - ) { - assertEquals("from column index", fromColumnIndex, col.getMin() - 1); // 1 based - assertEquals("to column index", toColumnIndex, col.getMax() - 1); // 1 based - assertTrue("isSetHidden", col.isSetHidden()); - assertTrue("isSetCollapsed", col.isSetCollapsed()); - //assertTrue("getCollapsed", col.getCollapsed()); - } - /** - * Verify that column groups were created correctly after Sheet.groupColumn - * - * @param col the column group xml bean - * @param fromColumnIndex 0-indexed - * @param toColumnIndex 0-indexed - */ - private static void checkColumnGroupIsExpanded( - CTCol col, - int fromColumnIndex, int toColumnIndex - ) { - assertEquals("from column index", fromColumnIndex, col.getMin() - 1); // 1 based - assertEquals("to column index", toColumnIndex, col.getMax() - 1); // 1 based - assertFalse("isSetHidden", col.isSetHidden()); - assertTrue("isSetCollapsed", col.isSetCollapsed()); - //assertTrue("isSetCollapsed", !col.isSetCollapsed() || !col.getCollapsed()); - //assertFalse("getCollapsed", col.getCollapsed()); - } - - /** - * TODO - while this is internally consistent, I'm not - * completely clear in all cases what it's supposed to - * be doing... Someone who understands the goals a little - * better should really review this! - */ - @Test - public void setRowGroupCollapsed() throws IOException { - XSSFWorkbook wb1 = new XSSFWorkbook(); - XSSFSheet sheet1 = wb1.createSheet(); - - sheet1.groupRow( 5, 14 ); - sheet1.groupRow( 7, 14 ); - sheet1.groupRow( 16, 19 ); - - assertEquals(14,sheet1.getPhysicalNumberOfRows()); - assertFalse(sheet1.getRow(6).getCTRow().isSetCollapsed()); - assertFalse(sheet1.getRow(6).getCTRow().isSetHidden()); - assertFalse(sheet1.getRow(7).getCTRow().isSetCollapsed()); - assertFalse(sheet1.getRow(7).getCTRow().isSetHidden()); - assertFalse(sheet1.getRow(9).getCTRow().isSetCollapsed()); - assertFalse(sheet1.getRow(9).getCTRow().isSetHidden()); - assertFalse(sheet1.getRow(14).getCTRow().isSetCollapsed()); - assertFalse(sheet1.getRow(14).getCTRow().isSetHidden()); - assertFalse(sheet1.getRow(16).getCTRow().isSetCollapsed()); - assertFalse(sheet1.getRow(16).getCTRow().isSetHidden()); - assertFalse(sheet1.getRow(18).getCTRow().isSetCollapsed()); - assertFalse(sheet1.getRow(18).getCTRow().isSetHidden()); - - //collapsed - sheet1.setRowGroupCollapsed( 7, true ); - - assertFalse(sheet1.getRow(6).getCTRow().isSetCollapsed()); - assertFalse(sheet1.getRow(6).getCTRow().isSetHidden()); - assertFalse(sheet1.getRow(7).getCTRow().isSetCollapsed()); - assertTrue (sheet1.getRow(7).getCTRow().isSetHidden()); - assertFalse(sheet1.getRow(9).getCTRow().isSetCollapsed()); - assertTrue (sheet1.getRow(9).getCTRow().isSetHidden()); - assertFalse(sheet1.getRow(14).getCTRow().isSetCollapsed()); - assertTrue (sheet1.getRow(14).getCTRow().isSetHidden()); - assertFalse(sheet1.getRow(16).getCTRow().isSetCollapsed()); - assertFalse(sheet1.getRow(16).getCTRow().isSetHidden()); - assertFalse(sheet1.getRow(18).getCTRow().isSetCollapsed()); - assertFalse(sheet1.getRow(18).getCTRow().isSetHidden()); - - //expanded - sheet1.setRowGroupCollapsed( 7, false ); - - assertFalse(sheet1.getRow(6).getCTRow().isSetCollapsed()); - assertFalse(sheet1.getRow(6).getCTRow().isSetHidden()); - assertFalse(sheet1.getRow(7).getCTRow().isSetCollapsed()); - assertTrue (sheet1.getRow(7).getCTRow().isSetHidden()); - assertFalse(sheet1.getRow(9).getCTRow().isSetCollapsed()); - assertTrue (sheet1.getRow(9).getCTRow().isSetHidden()); - assertFalse(sheet1.getRow(14).getCTRow().isSetCollapsed()); - assertTrue (sheet1.getRow(14).getCTRow().isSetHidden()); - assertFalse(sheet1.getRow(16).getCTRow().isSetCollapsed()); - assertFalse(sheet1.getRow(16).getCTRow().isSetHidden()); - assertFalse(sheet1.getRow(18).getCTRow().isSetCollapsed()); - assertFalse(sheet1.getRow(18).getCTRow().isSetHidden()); - - - // Save and re-load - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sheet1 = wb2.getSheetAt(0); - - assertFalse(sheet1.getRow(6).getCTRow().isSetCollapsed()); - assertFalse(sheet1.getRow(6).getCTRow().isSetHidden()); - assertFalse(sheet1.getRow(7).getCTRow().isSetCollapsed()); - assertTrue (sheet1.getRow(7).getCTRow().isSetHidden()); - assertFalse(sheet1.getRow(9).getCTRow().isSetCollapsed()); - assertTrue (sheet1.getRow(9).getCTRow().isSetHidden()); - assertFalse(sheet1.getRow(14).getCTRow().isSetCollapsed()); - assertTrue (sheet1.getRow(14).getCTRow().isSetHidden()); - assertFalse(sheet1.getRow(16).getCTRow().isSetCollapsed()); - assertFalse(sheet1.getRow(16).getCTRow().isSetHidden()); - assertFalse(sheet1.getRow(18).getCTRow().isSetCollapsed()); - assertFalse(sheet1.getRow(18).getCTRow().isSetHidden()); - - wb2.close(); - } - - /** - * Get / Set column width and check the actual values of the underlying XML beans - */ - @Test - public void columnWidth_lowlevel() throws IOException { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFSheet sheet = workbook.createSheet("Sheet 1"); - sheet.setColumnWidth(1, 22 * 256); - assertEquals(22 * 256, sheet.getColumnWidth(1)); - - // Now check the low level stuff, and check that's all - // been set correctly - XSSFSheet xs = sheet; - CTWorksheet cts = xs.getCTWorksheet(); - - assertEquals(1, cts.sizeOfColsArray()); - CTCols cols = cts.getColsArray(0); - assertEquals(1, cols.sizeOfColArray()); - CTCol col = cols.getColArray(0); - - // XML is 1 based, POI is 0 based - assertEquals(2, col.getMin()); - assertEquals(2, col.getMax()); - assertEquals(22.0, col.getWidth(), 0.0); - assertTrue(col.getCustomWidth()); - - // Now set another - sheet.setColumnWidth(3, 33 * 256); - - assertEquals(1, cts.sizeOfColsArray()); - cols = cts.getColsArray(0); - assertEquals(2, cols.sizeOfColArray()); - - col = cols.getColArray(0); - assertEquals(2, col.getMin()); // POI 1 - assertEquals(2, col.getMax()); - assertEquals(22.0, col.getWidth(), 0.0); - assertTrue(col.getCustomWidth()); - - col = cols.getColArray(1); - assertEquals(4, col.getMin()); // POI 3 - assertEquals(4, col.getMax()); - assertEquals(33.0, col.getWidth(), 0.0); - assertTrue(col.getCustomWidth()); - - workbook.close(); - } - - /** - * Setting width of a column included in a column span - */ - @Test - public void bug47862() throws IOException { - XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("47862.xlsx"); - XSSFSheet sheet = wb1.getSheetAt(0); - CTCols cols = sheet.getCTWorksheet().getColsArray(0); - // - // - // - - //a span of columns [1,5] - assertEquals(1, cols.sizeOfColArray()); - CTCol col = cols.getColArray(0); - assertEquals(1, col.getMin()); - assertEquals(5, col.getMax()); - double swidth = 15.77734375; //width of columns in the span - assertEquals(swidth, col.getWidth(), 0.0); - - for (int i = 0; i < 5; i++) { - assertEquals((int)(swidth*256), sheet.getColumnWidth(i)); - } - - int[] cw = new int[]{10, 15, 20, 25, 30}; - for (int i = 0; i < 5; i++) { - sheet.setColumnWidth(i, cw[i]*256); - } - - //the check below failed prior to fix of Bug #47862 - ColumnHelper.sortColumns(cols); - // - // - // - // - // - // - // - - //now the span is splitted into 5 individual columns - assertEquals(5, cols.sizeOfColArray()); - for (int i = 0; i < 5; i++) { - assertEquals(cw[i]*256, sheet.getColumnWidth(i)); - assertEquals(cw[i], cols.getColArray(i).getWidth(), 0.0); - } - - //serialize and check again - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sheet = wb2.getSheetAt(0); - cols = sheet.getCTWorksheet().getColsArray(0); - assertEquals(5, cols.sizeOfColArray()); - for (int i = 0; i < 5; i++) { - assertEquals(cw[i]*256, sheet.getColumnWidth(i)); - assertEquals(cw[i], cols.getColArray(i).getWidth(), 0.0); - } - - wb2.close(); - } - - /** - * Hiding a column included in a column span - */ - @Test - public void bug47804() throws IOException { - XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("47804.xlsx"); - XSSFSheet sheet = wb1.getSheetAt(0); - CTCols cols = sheet.getCTWorksheet().getColsArray(0); - assertEquals(2, cols.sizeOfColArray()); - CTCol col; - // - // - // - // - - //a span of columns [2,4] - col = cols.getColArray(0); - assertEquals(2, col.getMin()); - assertEquals(4, col.getMax()); - //individual column - col = cols.getColArray(1); - assertEquals(7, col.getMin()); - assertEquals(7, col.getMax()); - - sheet.setColumnHidden(2, true); // Column C - sheet.setColumnHidden(6, true); // Column G - - assertTrue(sheet.isColumnHidden(2)); - assertTrue(sheet.isColumnHidden(6)); - - //other columns but C and G are not hidden - assertFalse(sheet.isColumnHidden(1)); - assertFalse(sheet.isColumnHidden(3)); - assertFalse(sheet.isColumnHidden(4)); - assertFalse(sheet.isColumnHidden(5)); - - //the check below failed prior to fix of Bug #47804 - ColumnHelper.sortColumns(cols); - //the span is now splitted into three parts - // - // - // - // - // - // - - assertEquals(4, cols.sizeOfColArray()); - col = cols.getColArray(0); - assertEquals(2, col.getMin()); - assertEquals(2, col.getMax()); - col = cols.getColArray(1); - assertEquals(3, col.getMin()); - assertEquals(3, col.getMax()); - col = cols.getColArray(2); - assertEquals(4, col.getMin()); - assertEquals(4, col.getMax()); - col = cols.getColArray(3); - assertEquals(7, col.getMin()); - assertEquals(7, col.getMax()); - - //serialize and check again - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sheet = wb2.getSheetAt(0); - assertTrue(sheet.isColumnHidden(2)); - assertTrue(sheet.isColumnHidden(6)); - assertFalse(sheet.isColumnHidden(1)); - assertFalse(sheet.isColumnHidden(3)); - assertFalse(sheet.isColumnHidden(4)); - assertFalse(sheet.isColumnHidden(5)); - - wb2.close(); - } - - @Test - public void commentsTable() throws IOException { - XSSFWorkbook wb1 = new XSSFWorkbook(); - XSSFSheet sheet1 = wb1.createSheet(); - CommentsTable comment1 = sheet1.getCommentsTable(false); - assertNull(comment1); - - comment1 = sheet1.getCommentsTable(true); - assertNotNull(comment1); - assertEquals("/xl/comments1.xml", comment1.getPackagePart().getPartName().getName()); - - assertSame(comment1, sheet1.getCommentsTable(true)); - - //second sheet - XSSFSheet sheet2 = wb1.createSheet(); - CommentsTable comment2 = sheet2.getCommentsTable(false); - assertNull(comment2); - - comment2 = sheet2.getCommentsTable(true); - assertNotNull(comment2); - - assertSame(comment2, sheet2.getCommentsTable(true)); - assertEquals("/xl/comments2.xml", comment2.getPackagePart().getPartName().getName()); - - //comment1 and comment2 are different objects - assertNotSame(comment1, comment2); - wb1.close(); - - //now test against a workbook containing cell comments - XSSFWorkbook wb2 = XSSFTestDataSamples.openSampleWorkbook("WithMoreVariousData.xlsx"); - sheet1 = wb2.getSheetAt(0); - comment1 = sheet1.getCommentsTable(true); - assertNotNull(comment1); - assertEquals("/xl/comments1.xml", comment1.getPackagePart().getPartName().getName()); - assertSame(comment1, sheet1.getCommentsTable(true)); - - wb2.close(); - } - - /** - * Rows and cells can be created in random order, - * but CTRows are kept in ascending order - */ - @Override - @Test - public void createRow() throws IOException { - XSSFWorkbook wb1 = new XSSFWorkbook(); - XSSFSheet sheet = wb1.createSheet(); - CTWorksheet wsh = sheet.getCTWorksheet(); - CTSheetData sheetData = wsh.getSheetData(); - assertEquals(0, sheetData.sizeOfRowArray()); - - XSSFRow row1 = sheet.createRow(2); - row1.createCell(2); - row1.createCell(1); - - XSSFRow row2 = sheet.createRow(1); - row2.createCell(2); - row2.createCell(1); - row2.createCell(0); - - XSSFRow row3 = sheet.createRow(0); - row3.createCell(3); - row3.createCell(0); - row3.createCell(2); - row3.createCell(5); - - - CTRow[] xrow = sheetData.getRowArray(); - assertEquals(3, xrow.length); - - //rows are sorted: {0, 1, 2} - assertEquals(4, xrow[0].sizeOfCArray()); - assertEquals(1, xrow[0].getR()); - assertTrue(xrow[0].equals(row3.getCTRow())); - - assertEquals(3, xrow[1].sizeOfCArray()); - assertEquals(2, xrow[1].getR()); - assertTrue(xrow[1].equals(row2.getCTRow())); - - assertEquals(2, xrow[2].sizeOfCArray()); - assertEquals(3, xrow[2].getR()); - assertTrue(xrow[2].equals(row1.getCTRow())); - - CTCell[] xcell = xrow[0].getCArray(); - assertEquals("D1", xcell[0].getR()); - assertEquals("A1", xcell[1].getR()); - assertEquals("C1", xcell[2].getR()); - assertEquals("F1", xcell[3].getR()); - - //re-creating a row does NOT add extra data to the parent - row2 = sheet.createRow(1); - assertEquals(3, sheetData.sizeOfRowArray()); - //existing cells are invalidated - assertEquals(0, sheetData.getRowArray(1).sizeOfCArray()); - assertEquals(0, row2.getPhysicalNumberOfCells()); - - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sheet = wb2.getSheetAt(0); - wsh = sheet.getCTWorksheet(); - xrow = sheetData.getRowArray(); - assertEquals(3, xrow.length); - - //rows are sorted: {0, 1, 2} - assertEquals(4, xrow[0].sizeOfCArray()); - assertEquals(1, xrow[0].getR()); - //cells are now sorted - xcell = xrow[0].getCArray(); - assertEquals("A1", xcell[0].getR()); - assertEquals("C1", xcell[1].getR()); - assertEquals("D1", xcell[2].getR()); - assertEquals("F1", xcell[3].getR()); - - - assertEquals(0, xrow[1].sizeOfCArray()); - assertEquals(2, xrow[1].getR()); - - assertEquals(2, xrow[2].sizeOfCArray()); - assertEquals(3, xrow[2].getR()); - - wb2.close(); - } - - @Test - public void setAutoFilter() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet("new sheet"); - sheet.setAutoFilter(CellRangeAddress.valueOf("A1:D100")); - - assertEquals("A1:D100", sheet.getCTWorksheet().getAutoFilter().getRef()); - - // auto-filter must be registered in workboook.xml, see Bugzilla 50315 - XSSFName nm = wb.getBuiltInName(XSSFName.BUILTIN_FILTER_DB, 0); - assertNotNull(nm); - - assertEquals(0, nm.getCTName().getLocalSheetId()); - assertTrue(nm.getCTName().getHidden()); - assertEquals("_xlnm._FilterDatabase", nm.getCTName().getName()); - assertEquals("'new sheet'!$A$1:$D$100", nm.getCTName().getStringValue()); - - wb.close(); - } - - @Test - public void protectSheet_lowlevel() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet(); - CTSheetProtection pr = sheet.getCTWorksheet().getSheetProtection(); - assertNull("CTSheetProtection should be null by default", pr); - String password = "Test"; - sheet.protectSheet(password); - pr = sheet.getCTWorksheet().getSheetProtection(); - assertNotNull("CTSheetProtection should be not null", pr); - assertTrue("sheet protection should be on", pr.isSetSheet()); - assertTrue("object protection should be on", pr.isSetObjects()); - assertTrue("scenario protection should be on", pr.isSetScenarios()); - int hashVal = CryptoFunctions.createXorVerifier1(password); - int actualVal = Integer.parseInt(pr.xgetPassword().getStringValue(),16); - assertEquals("well known value for top secret hash should match", hashVal, actualVal); - - sheet.protectSheet(null); - assertNull("protectSheet(null) should unset CTSheetProtection", sheet.getCTWorksheet().getSheetProtection()); - - wb.close(); - } - - @Test - public void protectSheet_emptyPassword() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet(); - CTSheetProtection pr = sheet.getCTWorksheet().getSheetProtection(); - assertNull("CTSheetProtection should be null by default", pr); - String password = ""; - sheet.protectSheet(password); - pr = sheet.getCTWorksheet().getSheetProtection(); - assertNotNull("CTSheetProtection should be not null", pr); - assertTrue("sheet protection should be on", pr.isSetSheet()); - assertTrue("object protection should be on", pr.isSetObjects()); - assertTrue("scenario protection should be on", pr.isSetScenarios()); - int hashVal = CryptoFunctions.createXorVerifier1(password); - STUnsignedShortHex xpassword = pr.xgetPassword(); - int actualVal = Integer.parseInt(xpassword.getStringValue(),16); - assertEquals("well known value for top secret hash should match", hashVal, actualVal); - - sheet.protectSheet(null); - assertNull("protectSheet(null) should unset CTSheetProtection", sheet.getCTWorksheet().getSheetProtection()); - - wb.close(); - } - - @Test - public void protectSheet_lowlevel_2013() throws IOException { - String password = "test"; - XSSFWorkbook wb1 = new XSSFWorkbook(); - XSSFSheet xs = wb1.createSheet(); - xs.setSheetPassword(password, HashAlgorithm.sha384); - XSSFWorkbook wb2 = writeOutAndReadBack(wb1); - wb1.close(); - assertTrue(wb2.getSheetAt(0).validateSheetPassword(password)); - wb2.close(); - - XSSFWorkbook wb3 = openSampleWorkbook("workbookProtection-sheet_password-2013.xlsx"); - assertTrue(wb3.getSheetAt(0).validateSheetPassword("pwd")); - wb3.close(); - } - - - @Test - public void bug49966() throws IOException { - XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("49966.xlsx"); - CalculationChain calcChain = wb1.getCalculationChain(); - assertNotNull(wb1.getCalculationChain()); - assertEquals(3, calcChain.getCTCalcChain().sizeOfCArray()); - - XSSFSheet sheet = wb1.getSheetAt(0); - XSSFRow row = sheet.getRow(0); - - sheet.removeRow(row); - assertEquals("XSSFSheet#removeRow did not clear calcChain entries", - 0, calcChain.getCTCalcChain().sizeOfCArray()); - - //calcChain should be gone - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - assertNull(wb2.getCalculationChain()); - wb2.close(); - } - - /** - * See bug #50829 test data tables - */ - @Test - public void tables() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("WithTable.xlsx"); - assertEquals(3, wb.getNumberOfSheets()); - - // Check the table sheet - XSSFSheet s1 = wb.getSheetAt(0); - assertEquals("a", s1.getRow(0).getCell(0).getRichStringCellValue().toString()); - assertEquals(1.0, s1.getRow(1).getCell(0).getNumericCellValue(), 0); - - List tables = s1.getTables(); - assertNotNull(tables); - assertEquals(1, tables.size()); - - XSSFTable table = tables.get(0); - assertEquals("Tabella1", table.getName()); - assertEquals("Tabella1", table.getDisplayName()); - - // And the others - XSSFSheet s2 = wb.getSheetAt(1); - assertEquals(0, s2.getTables().size()); - XSSFSheet s3 = wb.getSheetAt(2); - assertEquals(0, s3.getTables().size()); - wb.close(); - } - - /** - * Test to trigger OOXML-LITE generating to include org.openxmlformats.schemas.spreadsheetml.x2006.main.CTSheetCalcPr - */ - @Test - public void setForceFormulaRecalculation() throws IOException { - XSSFWorkbook wb1 = new XSSFWorkbook(); - XSSFSheet sheet = wb1.createSheet("Sheet 1"); - - assertFalse(sheet.getForceFormulaRecalculation()); - - // Set - sheet.setForceFormulaRecalculation(true); - assertTrue(sheet.getForceFormulaRecalculation()); - - // calcMode="manual" is unset when forceFormulaRecalculation=true - CTCalcPr calcPr = wb1.getCTWorkbook().addNewCalcPr(); - calcPr.setCalcMode(STCalcMode.MANUAL); - sheet.setForceFormulaRecalculation(true); - assertEquals(STCalcMode.AUTO, calcPr.getCalcMode()); - - // Check - sheet.setForceFormulaRecalculation(false); - assertFalse(sheet.getForceFormulaRecalculation()); - - - // Save, re-load, and re-check - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sheet = wb2.getSheet("Sheet 1"); - assertFalse(sheet.getForceFormulaRecalculation()); - wb2.close(); - } - - @Test - public void bug54607() throws IOException { - // run with the file provided in the Bug-Report - runGetTopRow("54607.xlsx", true, 1, 0, 0); - runGetLeftCol("54607.xlsx", true, 0, 0, 0); - - // run with some other flie to see - runGetTopRow("54436.xlsx", true, 0); - runGetLeftCol("54436.xlsx", true, 0); - runGetTopRow("TwoSheetsNoneHidden.xlsx", true, 0, 0); - runGetLeftCol("TwoSheetsNoneHidden.xlsx", true, 0, 0); - runGetTopRow("TwoSheetsNoneHidden.xls", false, 0, 0); - runGetLeftCol("TwoSheetsNoneHidden.xls", false, 0, 0); - } - - private void runGetTopRow(String file, boolean isXSSF, int... topRows) throws IOException { - final Workbook wb = (isXSSF) - ? XSSFTestDataSamples.openSampleWorkbook(file) - : HSSFTestDataSamples.openSampleWorkbook(file); - - for (int si = 0; si < wb.getNumberOfSheets(); si++) { - Sheet sh = wb.getSheetAt(si); - assertNotNull(sh.getSheetName()); - assertEquals("Did not match for sheet " + si, topRows[si], sh.getTopRow()); - } - - // for XSSF also test with SXSSF - if (isXSSF) { - Workbook swb = new SXSSFWorkbook((XSSFWorkbook) wb); - for (int si = 0; si < swb.getNumberOfSheets(); si++) { - Sheet sh = swb.getSheetAt(si); - assertNotNull(sh.getSheetName()); - assertEquals("Did not match for sheet " + si, topRows[si], sh.getTopRow()); - } - swb.close(); - } - - wb.close(); - } - - private void runGetLeftCol(String file, boolean isXSSF, int... topRows) throws IOException { - final Workbook wb = (isXSSF) - ? XSSFTestDataSamples.openSampleWorkbook(file) - : HSSFTestDataSamples.openSampleWorkbook(file); - - for (int si = 0; si < wb.getNumberOfSheets(); si++) { - Sheet sh = wb.getSheetAt(si); - assertNotNull(sh.getSheetName()); - assertEquals("Did not match for sheet " + si, topRows[si], sh.getLeftCol()); - } - - // for XSSF also test with SXSSF - if(isXSSF) { - Workbook swb = new SXSSFWorkbook((XSSFWorkbook) wb); - for (int si = 0; si < swb.getNumberOfSheets(); si++) { - Sheet sh = swb.getSheetAt(si); - assertNotNull(sh.getSheetName()); - assertEquals("Did not match for sheet " + si, topRows[si], sh.getLeftCol()); - } - swb.close(); - } - - wb.close(); - } - - @Test - public void bug55745() throws Exception { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("55745.xlsx"); - XSSFSheet sheet = wb.getSheetAt(0); - List tables = sheet.getTables(); - /*System.out.println(tables.size()); - - for(XSSFTable table : tables) { - System.out.println("XPath: " + table.getCommonXpath()); - System.out.println("Name: " + table.getName()); - System.out.println("Mapped Cols: " + table.getNumberOfMappedColumns()); - System.out.println("Rowcount: " + table.getRowCount()); - System.out.println("End Cell: " + table.getEndCellReference()); - System.out.println("Start Cell: " + table.getStartCellReference()); - }*/ - assertEquals("Sheet should contain 8 tables", 8, tables.size()); - assertNotNull("Sheet should contain a comments table", sheet.getCommentsTable(false)); - wb.close(); - } - - @Test - public void bug55723b() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - Sheet sheet = wb.createSheet(); - - // stored with a special name - assertNull(wb.getBuiltInName(XSSFName.BUILTIN_FILTER_DB, 0)); - - CellRangeAddress range = CellRangeAddress.valueOf("A:B"); - AutoFilter filter = sheet.setAutoFilter(range); - assertNotNull(filter); - - // stored with a special name - XSSFName name = wb.getBuiltInName(XSSFName.BUILTIN_FILTER_DB, 0); - assertNotNull(name); - assertEquals("Sheet0!$A:$B", name.getRefersToFormula()); - - range = CellRangeAddress.valueOf("B:C"); - filter = sheet.setAutoFilter(range); - assertNotNull(filter); - - // stored with a special name - name = wb.getBuiltInName(XSSFName.BUILTIN_FILTER_DB, 0); - assertNotNull(name); - assertEquals("Sheet0!$B:$C", name.getRefersToFormula()); - - wb.close(); - } - - @Test(timeout=180000) - public void bug51585() throws IOException { - XSSFTestDataSamples.openSampleWorkbook("51585.xlsx").close(); - } - - private XSSFWorkbook setupSheet(){ - //set up workbook - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet(); - - Row row1 = sheet.createRow(0); - Cell cell = row1.createCell(0); - cell.setCellValue("Names"); - Cell cell2 = row1.createCell(1); - cell2.setCellValue("#"); - - Row row2 = sheet.createRow(1); - Cell cell3 = row2.createCell(0); - cell3.setCellValue("Jane"); - Cell cell4 = row2.createCell(1); - cell4.setCellValue(3); - - Row row3 = sheet.createRow(2); - Cell cell5 = row3.createCell(0); - cell5.setCellValue("John"); - Cell cell6 = row3.createCell(1); - cell6.setCellValue(3); - - return wb; - } - - @Test - public void testCreateTwoPivotTablesInOneSheet() throws IOException { - XSSFWorkbook wb = setupSheet(); - XSSFSheet sheet = wb.getSheetAt(0); - - assertNotNull(wb); - assertNotNull(sheet); - XSSFPivotTable pivotTable = sheet.createPivotTable(new AreaReference("A1:B2", SpreadsheetVersion.EXCEL2007), new CellReference("H5")); - assertNotNull(pivotTable); - assertTrue(wb.getPivotTables().size() > 0); - XSSFPivotTable pivotTable2 = sheet.createPivotTable(new AreaReference("A1:B2", SpreadsheetVersion.EXCEL2007), new CellReference("L5"), sheet); - assertNotNull(pivotTable2); - assertTrue(wb.getPivotTables().size() > 1); - wb.close(); - } - - @Test - public void testCreateTwoPivotTablesInTwoSheets() throws IOException { - XSSFWorkbook wb = setupSheet(); - XSSFSheet sheet = wb.getSheetAt(0); - - assertNotNull(wb); - assertNotNull(sheet); - XSSFPivotTable pivotTable = sheet.createPivotTable(new AreaReference("A1:B2", SpreadsheetVersion.EXCEL2007), new CellReference("H5")); - assertNotNull(pivotTable); - assertTrue(wb.getPivotTables().size() > 0); - assertNotNull(wb); - XSSFSheet sheet2 = wb.createSheet(); - XSSFPivotTable pivotTable2 = sheet2.createPivotTable(new AreaReference("A1:B2", SpreadsheetVersion.EXCEL2007), new CellReference("H5"), sheet); - assertNotNull(pivotTable2); - assertTrue(wb.getPivotTables().size() > 1); - wb.close(); - } - - @Test - public void testCreatePivotTable() throws IOException { - XSSFWorkbook wb = setupSheet(); - XSSFSheet sheet = wb.getSheetAt(0); - - assertNotNull(wb); - assertNotNull(sheet); - XSSFPivotTable pivotTable = sheet.createPivotTable(new AreaReference("A1:B2", SpreadsheetVersion.EXCEL2007), new CellReference("H5")); - assertNotNull(pivotTable); - assertTrue(wb.getPivotTables().size() > 0); - wb.close(); - } - - @Test - public void testCreatePivotTableInOtherSheetThanDataSheet() throws IOException { - XSSFWorkbook wb = setupSheet(); - XSSFSheet sheet1 = wb.getSheetAt(0); - XSSFSheet sheet2 = wb.createSheet(); - - XSSFPivotTable pivotTable = sheet2.createPivotTable - (new AreaReference("A1:B2", SpreadsheetVersion.EXCEL2007), new CellReference("H5"), sheet1); - assertEquals(0, pivotTable.getRowLabelColumns().size()); - - assertEquals(1, wb.getPivotTables().size()); - assertEquals(0, sheet1.getPivotTables().size()); - assertEquals(1, sheet2.getPivotTables().size()); - wb.close(); - } - - @Test - public void testCreatePivotTableInOtherSheetThanDataSheetUsingAreaReference() throws IOException { - XSSFWorkbook wb = setupSheet(); - XSSFSheet sheet = wb.getSheetAt(0); - XSSFSheet sheet2 = wb.createSheet("TEST"); - - XSSFPivotTable pivotTable = sheet2.createPivotTable( - new AreaReference(sheet.getSheetName()+"!A$1:B$2", SpreadsheetVersion.EXCEL2007), - new CellReference("H5")); - assertEquals(0, pivotTable.getRowLabelColumns().size()); - wb.close(); - } - - @Test(expected=IllegalArgumentException.class) - public void testCreatePivotTableWithConflictingDataSheets() throws IOException { - XSSFWorkbook wb = setupSheet(); - XSSFSheet sheet = wb.getSheetAt(0); - XSSFSheet sheet2 = wb.createSheet("TEST"); - - sheet2.createPivotTable( - new AreaReference(sheet.getSheetName()+"!A$1:B$2", SpreadsheetVersion.EXCEL2007), - new CellReference("H5"), - sheet2); - wb.close(); - } - - @Test(expected=POIXMLException.class) - public void testReadFails() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet(); - - // Throws exception because we cannot read here - try { - sheet.onDocumentRead(); - } finally { - wb.close(); - } - } - - /** - * This would be better off as a testable example rather than a simple unit test - * since Sheet.createComment() was deprecated and removed. - * https://poi.apache.org/spreadsheet/quick-guide.html#CellComments - * Feel free to relocated or delete this unit test if it doesn't belong here. - */ - @Test - public void testCreateComment() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - ClientAnchor anchor = wb.getCreationHelper().createClientAnchor(); - XSSFSheet sheet = wb.createSheet(); - XSSFComment comment = sheet.createDrawingPatriarch().createCellComment(anchor); - assertNotNull(comment); - wb.close(); - } - - protected void testCopyOneRow(String copyRowsTestWorkbook) throws IOException { - final double FLOAT_PRECISION = 1e-9; - final XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook(copyRowsTestWorkbook); - final XSSFSheet sheet = wb.getSheetAt(0); - final CellCopyPolicy defaultCopyPolicy = new CellCopyPolicy(); - sheet.copyRows(1, 1, 6, defaultCopyPolicy); - - final Row srcRow = sheet.getRow(1); - final Row destRow = sheet.getRow(6); - int col = 0; - Cell cell; - - cell = CellUtil.getCell(destRow, col++); - assertEquals("Source row ->", cell.getStringCellValue()); - - // Style - cell = CellUtil.getCell(destRow, col++); - assertEquals("[Style] B7 cell value", "Red", cell.getStringCellValue()); - assertEquals("[Style] B7 cell style", CellUtil.getCell(srcRow, 1).getCellStyle(), cell.getCellStyle()); - - // Blank - cell = CellUtil.getCell(destRow, col++); - assertEquals("[Blank] C7 cell type", CellType.BLANK, cell.getCellTypeEnum()); - - // Error - cell = CellUtil.getCell(destRow, col++); - assertEquals("[Error] D7 cell type", CellType.ERROR, cell.getCellTypeEnum()); - final FormulaError error = FormulaError.forInt(cell.getErrorCellValue()); - assertEquals("[Error] D7 cell value", FormulaError.NA, error); //FIXME: XSSFCell and HSSFCell expose different interfaces. getErrorCellString would be helpful here - - // Date - cell = CellUtil.getCell(destRow, col++); - assertEquals("[Date] E7 cell type", CellType.NUMERIC, cell.getCellTypeEnum()); - final Date date = LocaleUtil.getLocaleCalendar(2000, Calendar.JANUARY, 1).getTime(); - assertEquals("[Date] E7 cell value", date, cell.getDateCellValue()); - - // Boolean - cell = CellUtil.getCell(destRow, col++); - assertEquals("[Boolean] F7 cell type", CellType.BOOLEAN, cell.getCellTypeEnum()); - assertEquals("[Boolean] F7 cell value", true, cell.getBooleanCellValue()); - - // String - cell = CellUtil.getCell(destRow, col++); - assertEquals("[String] G7 cell type", CellType.STRING, cell.getCellTypeEnum()); - assertEquals("[String] G7 cell value", "Hello", cell.getStringCellValue()); - - // Int - cell = CellUtil.getCell(destRow, col++); - assertEquals("[Int] H7 cell type", CellType.NUMERIC, cell.getCellTypeEnum()); - assertEquals("[Int] H7 cell value", 15, (int) cell.getNumericCellValue()); - - // Float - cell = CellUtil.getCell(destRow, col++); - assertEquals("[Float] I7 cell type", CellType.NUMERIC, cell.getCellTypeEnum()); - assertEquals("[Float] I7 cell value", 12.5, cell.getNumericCellValue(), FLOAT_PRECISION); - - // Cell Formula - cell = CellUtil.getCell(destRow, col++); - assertEquals("J7", new CellReference(cell).formatAsString()); - assertEquals("[Cell Formula] J7 cell type", CellType.FORMULA, cell.getCellTypeEnum()); - assertEquals("[Cell Formula] J7 cell formula", "5+2", cell.getCellFormula()); - System.out.println("Cell formula evaluation currently unsupported"); - - // Cell Formula with Reference - // Formula row references should be adjusted by destRowNum-srcRowNum - cell = CellUtil.getCell(destRow, col++); - assertEquals("K7", new CellReference(cell).formatAsString()); - assertEquals("[Cell Formula with Reference] K7 cell type", - CellType.FORMULA, cell.getCellTypeEnum()); - assertEquals("[Cell Formula with Reference] K7 cell formula", - "J7+H$2", cell.getCellFormula()); - - // Cell Formula with Reference spanning multiple rows - cell = CellUtil.getCell(destRow, col++); - assertEquals("[Cell Formula with Reference spanning multiple rows] L7 cell type", - CellType.FORMULA, cell.getCellTypeEnum()); - assertEquals("[Cell Formula with Reference spanning multiple rows] L7 cell formula", - "G7&\" \"&G8", cell.getCellFormula()); - - // Cell Formula with Reference spanning multiple rows - cell = CellUtil.getCell(destRow, col++); - assertEquals("[Cell Formula with Area Reference] M7 cell type", - CellType.FORMULA, cell.getCellTypeEnum()); - assertEquals("[Cell Formula with Area Reference] M7 cell formula", - "SUM(H7:I8)", cell.getCellFormula()); - - // Array Formula - cell = CellUtil.getCell(destRow, col++); - System.out.println("Array formulas currently unsupported"); - // FIXME: Array Formula set with Sheet.setArrayFormula() instead of cell.setFormula() - /* - assertEquals("[Array Formula] N7 cell type", CellType.FORMULA, cell.getCellTypeEnum()); - assertEquals("[Array Formula] N7 cell formula", "{SUM(H7:J7*{1,2,3})}", cell.getCellFormula()); - */ - - // Data Format - cell = CellUtil.getCell(destRow, col++); - assertEquals("[Data Format] O7 cell type;", CellType.NUMERIC, cell.getCellTypeEnum()); - assertEquals("[Data Format] O7 cell value", 100.20, cell.getNumericCellValue(), FLOAT_PRECISION); - //FIXME: currently fails - final String moneyFormat = "\"$\"#,##0.00_);[Red]\\(\"$\"#,##0.00\\)"; - assertEquals("[Data Format] O7 data format", moneyFormat, cell.getCellStyle().getDataFormatString()); - - // Merged - cell = CellUtil.getCell(destRow, col); - assertEquals("[Merged] P7:Q7 cell value", - "Merged cells", cell.getStringCellValue()); - assertTrue("[Merged] P7:Q7 merged region", - sheet.getMergedRegions().contains(CellRangeAddress.valueOf("P7:Q7"))); - - // Merged across multiple rows - // Microsoft Excel 2013 does not copy a merged region unless all rows of - // the source merged region are selected - // POI's behavior should match this behavior - col += 2; - cell = CellUtil.getCell(destRow, col); - // Note: this behavior deviates from Microsoft Excel, - // which will not overwrite a cell in destination row if merged region extends beyond the copied row. - // The Excel way would require: - //assertEquals("[Merged across multiple rows] R7:S8 merged region", "Should NOT be overwritten", cell.getStringCellValue()); - //assertFalse("[Merged across multiple rows] R7:S8 merged region", - // sheet.getMergedRegions().contains(CellRangeAddress.valueOf("R7:S8"))); - // As currently implemented, cell value is copied but merged region is not copied - assertEquals("[Merged across multiple rows] R7:S8 cell value", - "Merged cells across multiple rows", cell.getStringCellValue()); - assertFalse("[Merged across multiple rows] R7:S7 merged region (one row)", - sheet.getMergedRegions().contains(CellRangeAddress.valueOf("R7:S7"))); //shouldn't do 1-row merge - assertFalse("[Merged across multiple rows] R7:S8 merged region", - sheet.getMergedRegions().contains(CellRangeAddress.valueOf("R7:S8"))); //shouldn't do 2-row merge - - // Make sure other rows are blank (off-by-one errors) - assertNull(sheet.getRow(5)); - assertNull(sheet.getRow(7)); - - wb.close(); - } - - protected void testCopyMultipleRows(String copyRowsTestWorkbook) throws IOException { - final double FLOAT_PRECISION = 1e-9; - final XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook(copyRowsTestWorkbook); - final XSSFSheet sheet = wb.getSheetAt(0); - final CellCopyPolicy defaultCopyPolicy = new CellCopyPolicy(); - sheet.copyRows(0, 3, 8, defaultCopyPolicy); - - @SuppressWarnings("unused") - final Row srcHeaderRow = sheet.getRow(0); - final Row srcRow1 = sheet.getRow(1); - final Row srcRow2 = sheet.getRow(2); - final Row srcRow3 = sheet.getRow(3); - final Row destHeaderRow = sheet.getRow(8); - final Row destRow1 = sheet.getRow(9); - final Row destRow2 = sheet.getRow(10); - final Row destRow3 = sheet.getRow(11); - int col = 0; - Cell cell; - - // Header row should be copied - assertNotNull(destHeaderRow); - - // Data rows - cell = CellUtil.getCell(destRow1, col); - assertEquals("Source row ->", cell.getStringCellValue()); - - // Style - col++; - cell = CellUtil.getCell(destRow1, col); - assertEquals("[Style] B10 cell value", "Red", cell.getStringCellValue()); - assertEquals("[Style] B10 cell style", CellUtil.getCell(srcRow1, 1).getCellStyle(), cell.getCellStyle()); - - cell = CellUtil.getCell(destRow2, col); - assertEquals("[Style] B11 cell value", "Blue", cell.getStringCellValue()); - assertEquals("[Style] B11 cell style", CellUtil.getCell(srcRow2, 1).getCellStyle(), cell.getCellStyle()); - - // Blank - col++; - cell = CellUtil.getCell(destRow1, col); - assertEquals("[Blank] C10 cell type", CellType.BLANK, cell.getCellTypeEnum()); - - cell = CellUtil.getCell(destRow2, col); - assertEquals("[Blank] C11 cell type", CellType.BLANK, cell.getCellTypeEnum()); - - // Error - col++; - cell = CellUtil.getCell(destRow1, col); - assertEquals("[Error] D10 cell type", CellType.ERROR, cell.getCellTypeEnum()); - FormulaError error = FormulaError.forInt(cell.getErrorCellValue()); - assertEquals("[Error] D10 cell value", FormulaError.NA, error); //FIXME: XSSFCell and HSSFCell expose different interfaces. getErrorCellString would be helpful here - - cell = CellUtil.getCell(destRow2, col); - assertEquals("[Error] D11 cell type", CellType.ERROR, cell.getCellTypeEnum()); - error = FormulaError.forInt(cell.getErrorCellValue()); - assertEquals("[Error] D11 cell value", FormulaError.NAME, error); //FIXME: XSSFCell and HSSFCell expose different interfaces. getErrorCellString would be helpful here - - // Date - col++; - cell = CellUtil.getCell(destRow1, col); - assertEquals("[Date] E10 cell type", CellType.NUMERIC, cell.getCellTypeEnum()); - Date date = LocaleUtil.getLocaleCalendar(2000, Calendar.JANUARY, 1).getTime(); - assertEquals("[Date] E10 cell value", date, cell.getDateCellValue()); - - cell = CellUtil.getCell(destRow2, col); - assertEquals("[Date] E11 cell type", CellType.NUMERIC, cell.getCellTypeEnum()); - date = LocaleUtil.getLocaleCalendar(2000, Calendar.JANUARY, 2).getTime(); - assertEquals("[Date] E11 cell value", date, cell.getDateCellValue()); - - // Boolean - col++; - cell = CellUtil.getCell(destRow1, col); - assertEquals("[Boolean] F10 cell type", CellType.BOOLEAN, cell.getCellTypeEnum()); - assertEquals("[Boolean] F10 cell value", true, cell.getBooleanCellValue()); - - cell = CellUtil.getCell(destRow2, col); - assertEquals("[Boolean] F11 cell type", CellType.BOOLEAN, cell.getCellTypeEnum()); - assertEquals("[Boolean] F11 cell value", false, cell.getBooleanCellValue()); - - // String - col++; - cell = CellUtil.getCell(destRow1, col); - assertEquals("[String] G10 cell type", CellType.STRING, cell.getCellTypeEnum()); - assertEquals("[String] G10 cell value", "Hello", cell.getStringCellValue()); - - cell = CellUtil.getCell(destRow2, col); - assertEquals("[String] G11 cell type", CellType.STRING, cell.getCellTypeEnum()); - assertEquals("[String] G11 cell value", "World", cell.getStringCellValue()); - - // Int - col++; - cell = CellUtil.getCell(destRow1, col); - assertEquals("[Int] H10 cell type", CellType.NUMERIC, cell.getCellTypeEnum()); - assertEquals("[Int] H10 cell value", 15, (int) cell.getNumericCellValue()); - - cell = CellUtil.getCell(destRow2, col); - assertEquals("[Int] H11 cell type", CellType.NUMERIC, cell.getCellTypeEnum()); - assertEquals("[Int] H11 cell value", 42, (int) cell.getNumericCellValue()); - - // Float - col++; - cell = CellUtil.getCell(destRow1, col); - assertEquals("[Float] I10 cell type", CellType.NUMERIC, cell.getCellTypeEnum()); - assertEquals("[Float] I10 cell value", 12.5, cell.getNumericCellValue(), FLOAT_PRECISION); - - cell = CellUtil.getCell(destRow2, col); - assertEquals("[Float] I11 cell type", CellType.NUMERIC, cell.getCellTypeEnum()); - assertEquals("[Float] I11 cell value", 5.5, cell.getNumericCellValue(), FLOAT_PRECISION); - - // Cell Formula - col++; - cell = CellUtil.getCell(destRow1, col); - assertEquals("[Cell Formula] J10 cell type", CellType.FORMULA, cell.getCellTypeEnum()); - assertEquals("[Cell Formula] J10 cell formula", "5+2", cell.getCellFormula()); - - cell = CellUtil.getCell(destRow2, col); - assertEquals("[Cell Formula] J11 cell type", CellType.FORMULA, cell.getCellTypeEnum()); - assertEquals("[Cell Formula] J11 cell formula", "6+18", cell.getCellFormula()); - - // Cell Formula with Reference - col++; - // Formula row references should be adjusted by destRowNum-srcRowNum - cell = CellUtil.getCell(destRow1, col); - assertEquals("[Cell Formula with Reference] K10 cell type", - CellType.FORMULA, cell.getCellTypeEnum()); - assertEquals("[Cell Formula with Reference] K10 cell formula", - "J10+H$2", cell.getCellFormula()); - - cell = CellUtil.getCell(destRow2, col); - assertEquals("[Cell Formula with Reference] K11 cell type", CellType.FORMULA, cell.getCellTypeEnum()); - assertEquals("[Cell Formula with Reference] K11 cell formula", "J11+H$2", cell.getCellFormula()); - - // Cell Formula with Reference spanning multiple rows - col++; - cell = CellUtil.getCell(destRow1, col); - assertEquals("[Cell Formula with Reference spanning multiple rows] L10 cell type", - CellType.FORMULA, cell.getCellTypeEnum()); - assertEquals("[Cell Formula with Reference spanning multiple rows] L10 cell formula", - "G10&\" \"&G11", cell.getCellFormula()); - - cell = CellUtil.getCell(destRow2, col); - assertEquals("[Cell Formula with Reference spanning multiple rows] L11 cell type", - CellType.FORMULA, cell.getCellTypeEnum()); - assertEquals("[Cell Formula with Reference spanning multiple rows] L11 cell formula", - "G11&\" \"&G12", cell.getCellFormula()); - - // Cell Formula with Area Reference - col++; - cell = CellUtil.getCell(destRow1, col); - assertEquals("[Cell Formula with Area Reference] M10 cell type", - CellType.FORMULA, cell.getCellTypeEnum()); - assertEquals("[Cell Formula with Area Reference] M10 cell formula", - "SUM(H10:I11)", cell.getCellFormula()); - - cell = CellUtil.getCell(destRow2, col); - assertEquals("[Cell Formula with Area Reference] M11 cell type", - CellType.FORMULA, cell.getCellTypeEnum()); - assertEquals("[Cell Formula with Area Reference] M11 cell formula", - "SUM($H$3:I10)", cell.getCellFormula()); //Also acceptable: SUM($H10:I$3), but this AreaReference isn't in ascending order - - // Array Formula - col++; - cell = CellUtil.getCell(destRow1, col); - // System.out.println("Array formulas currently unsupported"); - /* - // FIXME: Array Formula set with Sheet.setArrayFormula() instead of cell.setFormula() - assertEquals("[Array Formula] N10 cell type", CellType.FORMULA, cell.getCellTypeEnum()); - assertEquals("[Array Formula] N10 cell formula", "{SUM(H10:J10*{1,2,3})}", cell.getCellFormula()); - - cell = CellUtil.getCell(destRow2, col); - // FIXME: Array Formula set with Sheet.setArrayFormula() instead of cell.setFormula() - assertEquals("[Array Formula] N11 cell type", CellType.FORMULA, cell.getCellTypeEnum()); - assertEquals("[Array Formula] N11 cell formula", "{SUM(H11:J11*{1,2,3})}", cell.getCellFormula()); - */ - - // Data Format - col++; - cell = CellUtil.getCell(destRow2, col); - assertEquals("[Data Format] O10 cell type", CellType.NUMERIC, cell.getCellTypeEnum()); - assertEquals("[Data Format] O10 cell value", 100.20, cell.getNumericCellValue(), FLOAT_PRECISION); - final String moneyFormat = "\"$\"#,##0.00_);[Red]\\(\"$\"#,##0.00\\)"; - assertEquals("[Data Format] O10 cell data format", moneyFormat, cell.getCellStyle().getDataFormatString()); - - // Merged - col++; - cell = CellUtil.getCell(destRow1, col); - assertEquals("[Merged] P10:Q10 cell value", - "Merged cells", cell.getStringCellValue()); - assertTrue("[Merged] P10:Q10 merged region", - sheet.getMergedRegions().contains(CellRangeAddress.valueOf("P10:Q10"))); - - cell = CellUtil.getCell(destRow2, col); - assertEquals("[Merged] P11:Q11 cell value", "Merged cells", cell.getStringCellValue()); - assertTrue("[Merged] P11:Q11 merged region", - sheet.getMergedRegions().contains(CellRangeAddress.valueOf("P11:Q11"))); - - // Should Q10/Q11 be checked? - - // Merged across multiple rows - // Microsoft Excel 2013 does not copy a merged region unless all rows of - // the source merged region are selected - // POI's behavior should match this behavior - col += 2; - cell = CellUtil.getCell(destRow1, col); - assertEquals("[Merged across multiple rows] R10:S11 cell value", - "Merged cells across multiple rows", cell.getStringCellValue()); - assertTrue("[Merged across multiple rows] R10:S11 merged region", - sheet.getMergedRegions().contains(CellRangeAddress.valueOf("R10:S11"))); - - // Row 3 (zero-based) was empty, so Row 11 (zero-based) should be empty too. - if (srcRow3 == null) { - assertNull("Row 3 was empty, so Row 11 should be empty", destRow3); - } - - // Make sure other rows are blank (off-by-one errors) - assertNull("Off-by-one lower edge case", sheet.getRow(7)); //one row above destHeaderRow - assertNull("Off-by-one upper edge case", sheet.getRow(12)); //one row below destRow3 - - wb.close(); - } - - @Test - public void testCopyOneRow() throws IOException { - testCopyOneRow("XSSFSheet.copyRows.xlsx"); - } - - @Test - public void testCopyMultipleRows() throws IOException { - testCopyMultipleRows("XSSFSheet.copyRows.xlsx"); - } - - @Test - public void testIgnoredErrors() throws IOException { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFSheet sheet = workbook.createSheet(); - CellRangeAddress region = CellRangeAddress.valueOf("B2:D4"); - sheet.addIgnoredErrors(region, IgnoredErrorType.NUMBER_STORED_AS_TEXT); - final CTIgnoredError ignoredError = sheet.getCTWorksheet().getIgnoredErrors().getIgnoredErrorArray(0); - assertEquals(1, ignoredError.getSqref().size()); - assertEquals("B2:D4", ignoredError.getSqref().get(0)); - assertTrue(ignoredError.getNumberStoredAsText()); - - Map> ignoredErrors = sheet.getIgnoredErrors(); - assertEquals(1, ignoredErrors.size()); - assertEquals(1, ignoredErrors.get(IgnoredErrorType.NUMBER_STORED_AS_TEXT).size()); - assertEquals("B2:D4", ignoredErrors.get(IgnoredErrorType.NUMBER_STORED_AS_TEXT).iterator().next().formatAsString()); - - workbook.close(); - } - - @Test - public void testIgnoredErrorsMultipleTypes() throws IOException { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFSheet sheet = workbook.createSheet(); - CellRangeAddress region = CellRangeAddress.valueOf("B2:D4"); - sheet.addIgnoredErrors(region, IgnoredErrorType.FORMULA, IgnoredErrorType.EVALUATION_ERROR); - final CTIgnoredError ignoredError = sheet.getCTWorksheet().getIgnoredErrors().getIgnoredErrorArray(0); - assertEquals(1, ignoredError.getSqref().size()); - assertEquals("B2:D4", ignoredError.getSqref().get(0)); - assertFalse(ignoredError.getNumberStoredAsText()); - assertTrue(ignoredError.getFormula()); - assertTrue(ignoredError.getEvalError()); - - Map> ignoredErrors = sheet.getIgnoredErrors(); - assertEquals(2, ignoredErrors.size()); - assertEquals(1, ignoredErrors.get(IgnoredErrorType.FORMULA).size()); - assertEquals("B2:D4", ignoredErrors.get(IgnoredErrorType.FORMULA).iterator().next().formatAsString()); - assertEquals(1, ignoredErrors.get(IgnoredErrorType.EVALUATION_ERROR).size()); - assertEquals("B2:D4", ignoredErrors.get(IgnoredErrorType.EVALUATION_ERROR).iterator().next().formatAsString()); - workbook.close(); - } - - @Test - public void testIgnoredErrorsMultipleCalls() throws IOException { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFSheet sheet = workbook.createSheet(); - CellRangeAddress region = CellRangeAddress.valueOf("B2:D4"); - // Two calls means two elements, no clever collapsing just yet. - sheet.addIgnoredErrors(region, IgnoredErrorType.EVALUATION_ERROR); - sheet.addIgnoredErrors(region, IgnoredErrorType.FORMULA); - - CTIgnoredError ignoredError = sheet.getCTWorksheet().getIgnoredErrors().getIgnoredErrorArray(0); - assertEquals(1, ignoredError.getSqref().size()); - assertEquals("B2:D4", ignoredError.getSqref().get(0)); - assertFalse(ignoredError.getFormula()); - assertTrue(ignoredError.getEvalError()); - - ignoredError = sheet.getCTWorksheet().getIgnoredErrors().getIgnoredErrorArray(1); - assertEquals(1, ignoredError.getSqref().size()); - assertEquals("B2:D4", ignoredError.getSqref().get(0)); - assertTrue(ignoredError.getFormula()); - assertFalse(ignoredError.getEvalError()); - - Map> ignoredErrors = sheet.getIgnoredErrors(); - assertEquals(2, ignoredErrors.size()); - assertEquals(1, ignoredErrors.get(IgnoredErrorType.FORMULA).size()); - assertEquals("B2:D4", ignoredErrors.get(IgnoredErrorType.FORMULA).iterator().next().formatAsString()); - assertEquals(1, ignoredErrors.get(IgnoredErrorType.EVALUATION_ERROR).size()); - assertEquals("B2:D4", ignoredErrors.get(IgnoredErrorType.EVALUATION_ERROR).iterator().next().formatAsString()); - workbook.close(); - } - - @Test - public void setTabColor() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - try { - XSSFSheet sh = wb.createSheet(); - assertTrue(sh.getCTWorksheet().getSheetPr() == null || !sh.getCTWorksheet().getSheetPr().isSetTabColor()); - sh.setTabColor(new XSSFColor(IndexedColors.RED)); - assertTrue(sh.getCTWorksheet().getSheetPr().isSetTabColor()); - assertEquals(IndexedColors.RED.index, - sh.getCTWorksheet().getSheetPr().getTabColor().getIndexed()); - } finally { - wb.close(); - } - } - - @Test - public void getTabColor() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - try { - XSSFSheet sh = wb.createSheet(); - assertTrue(sh.getCTWorksheet().getSheetPr() == null || !sh.getCTWorksheet().getSheetPr().isSetTabColor()); - assertNull(sh.getTabColor()); - sh.setTabColor(new XSSFColor(IndexedColors.RED)); - XSSFColor expected = new XSSFColor(IndexedColors.RED); - assertEquals(expected, sh.getTabColor()); - } finally { - wb.close(); - } - } - - // Test using an existing workbook saved by Excel - @Test - public void tabColor() throws IOException { - XSSFWorkbook wb = openSampleWorkbook("SheetTabColors.xlsx"); - try { - // non-colored sheets do not have a color - assertNull(wb.getSheet("default").getTabColor()); - - // test indexed-colored sheet - XSSFColor expected = new XSSFColor(IndexedColors.RED); - assertEquals(expected, wb.getSheet("indexedRed").getTabColor()); - - // test regular-colored (non-indexed, ARGB) sheet - expected = new XSSFColor(); - expected.setARGBHex("FF7F2700"); - assertEquals(expected, wb.getSheet("customOrange").getTabColor()); - } finally { - wb.close(); - } - } - - /** - * See bug #52425 - */ - @Test - public void testInsertCommentsToClonedSheet() { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("52425.xlsx"); - CreationHelper helper = wb.getCreationHelper(); - Sheet sheet2 = wb.createSheet("Sheet 2"); - Sheet sheet3 = wb.cloneSheet(0); - wb.setSheetName(2, "Sheet 3"); - - // Adding Comment to new created Sheet 2 - addComments(helper, sheet2); - // Adding Comment to cloned Sheet 3 - addComments(helper, sheet3); - } - - private void addComments(CreationHelper helper, Sheet sheet) { - Drawing drawing = sheet.createDrawingPatriarch(); - - for (int i = 0; i < 2; i++) { - ClientAnchor anchor = helper.createClientAnchor(); - anchor.setCol1(0); - anchor.setRow1(0 + i); - anchor.setCol2(2); - anchor.setRow2(3 + i); - - Comment comment = drawing.createCellComment(anchor); - comment.setString(helper.createRichTextString("BugTesting")); - - Row row = sheet.getRow(0 + i); - if (row == null) { - row = sheet.createRow(0 + i); - } - Cell cell = row.getCell(0); - if (cell == null) { - cell = row.createCell(0); - } - - cell.setCellComment(comment); - } - - } - - // bug 59687: XSSFSheet.RemoveRow doesn't handle row gaps properly when removing row comments - @Test - public void testRemoveRowWithCommentAndGapAbove() throws IOException { - final Workbook wb = _testDataProvider.openSampleWorkbook("59687.xlsx"); - final Sheet sheet = wb.getSheetAt(0); - - // comment exists - CellAddress commentCellAddress = new CellAddress("A4"); - assertNotNull(sheet.getCellComment(commentCellAddress)); - - assertEquals("Wrong starting # of comments", 1, sheet.getCellComments().size()); - - sheet.removeRow(sheet.getRow(commentCellAddress.getRow())); - - assertEquals("There should not be any comments left!", 0, sheet.getCellComments().size()); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetAutosizeColumn.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetAutosizeColumn.java deleted file mode 100644 index 031aadfc3..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetAutosizeColumn.java +++ /dev/null @@ -1,31 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import org.apache.poi.ss.usermodel.BaseTestSheetAutosizeColumn; -import org.apache.poi.xssf.XSSFITestDataProvider; - -/** - * @author Yegor Kozlov - */ -public final class TestXSSFSheetAutosizeColumn extends BaseTestSheetAutosizeColumn { - - public TestXSSFSheetAutosizeColumn(){ - super(XSSFITestDataProvider.instance); - } -} \ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetMergeRegions.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetMergeRegions.java deleted file mode 100644 index fb7a9c0b0..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetMergeRegions.java +++ /dev/null @@ -1,71 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel; - -import static org.junit.Assert.*; - -import java.io.IOException; -import java.util.List; - -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.junit.Test; - -public class TestXSSFSheetMergeRegions { - @Test - public void testMergeRegionsSpeed() throws IOException { - final XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("57893-many-merges.xlsx"); - try { - long millis = Long.MAX_VALUE; - - // in order to reduce the number of false positives we run it a few times before we fail, - // sometimes it fails on machines that are busy at the moment. - for(int i = 0;i < 5;i++) { - millis = runTest(wb); - if(millis < 2000) { - break; - } - System.out.println("Retry " + i + " because run-time is too high: " + millis); - } - - boolean inGump = false; - String version = System.getProperty("version.id"); - if(version != null && version.startsWith("gump-")) { - inGump = true; - } - - // This time is typically ~800ms, versus ~7800ms to iterate getMergedRegion(int). - // when running in Gump, the VM is very slow, so we should allow much more time - assertTrue("Should have taken <2000 ms to iterate 50k merged regions but took " + millis, - inGump ? millis < 8000 : millis < 2000); - } finally { - wb.close(); - } - } - - private long runTest(final XSSFWorkbook wb) { - final long start = System.currentTimeMillis(); - final XSSFSheet sheet = wb.getSheetAt(0); - final List mergedRegions = sheet.getMergedRegions(); - assertEquals(50000, mergedRegions.size()); - for (CellRangeAddress cellRangeAddress : mergedRegions) { - assertEquals(cellRangeAddress.getFirstRow(), cellRangeAddress.getLastRow()); - assertEquals(2, cellRangeAddress.getNumberOfCells()); - } - return System.currentTimeMillis() - start; - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetRowGrouping.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetRowGrouping.java deleted file mode 100644 index cb8fc60c0..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetRowGrouping.java +++ /dev/null @@ -1,441 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import java.io.IOException; - -import junit.framework.TestCase; - -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.xssf.XSSFTestDataSamples; - -public final class TestXSSFSheetRowGrouping extends TestCase { - - private static final int ROWS_NUMBER = 200; - private static final int GROUP_SIZE = 5; - - //private int o_groupsNumber = 0; - - public void test55640() throws IOException { - //long startTime = System.currentTimeMillis(); - Workbook wb = new XSSFWorkbook(); - fillData(wb); - writeToFile(wb); - - //System.out.println("Number of groups: " + o_groupsNumber); - //System.out.println("Execution time: " + (System.currentTimeMillis()-startTime) + " ms"); - } - - - private void fillData(Workbook p_wb) { - Sheet sheet = p_wb.createSheet("sheet123"); - sheet.setRowSumsBelow(false); - - for (int i = 0; i < ROWS_NUMBER; i++) { - Row row = sheet.createRow(i); - Cell cell = row.createCell(0); - cell.setCellValue(i+1); - } - - int i = 1; - while (i < ROWS_NUMBER) { - int end = i+(GROUP_SIZE-2); - int start = i; // natural order -// int start = end - 1; // reverse order - while (start < end) { // natural order -// while (start >= i) { // reverse order - sheet.groupRow(start, end); - //o_groupsNumber++; - boolean collapsed = isCollapsed(); - //System.out.println("Set group " + start + "->" + end + " to " + collapsed); - sheet.setRowGroupCollapsed(start, collapsed); - start++; // natural order -// start--; // reverse order - } - i += GROUP_SIZE; - } - } - - private boolean isCollapsed() { - return Math.random() > 0.5d; - } - - private void writeToFile(Workbook p_wb) throws IOException { -// FileOutputStream fileOut = new FileOutputStream("/tmp/55640.xlsx"); -// try { -// p_wb.write(fileOut); -// } finally { -// fileOut.close(); -// } - assertNotNull(XSSFTestDataSamples.writeOutAndReadBack(p_wb)); - } - - public void test55640reduce1() throws IOException { - Workbook wb = new XSSFWorkbook(); - Sheet sheet = wb.createSheet("sheet123"); - sheet.setRowSumsBelow(false); - - for (int i = 0; i < ROWS_NUMBER; i++) { - Row row = sheet.createRow(i); - Cell cell = row.createCell(0); - cell.setCellValue(i+1); - } - - int i = 1; - while (i < ROWS_NUMBER) { - int end = i+(GROUP_SIZE-2); - int start = i; // natural order - while (start < end) { // natural order - sheet.groupRow(start, end); - //o_groupsNumber++; - boolean collapsed = start % 2 == 0 ? false : true; - //System.out.println("Set group " + start + "->" + end + " to " + collapsed); - sheet.setRowGroupCollapsed(start, collapsed); - start++; // natural order - } - i += GROUP_SIZE; - } - writeToFile(wb); - } - - - public void test55640_VerifyCases() throws IOException { - // NOTE: This is currently based on current behavior of POI, somehow - // what POI returns in the calls to collapsed/hidden is not fully matching - // the examples in the spec or I did not fully understand how POI stores the data internally... - - // all expanded - verifyGroupCollapsed( - // level1, level2, level3 - false, false, false, - // collapsed: - new Boolean[] { false, false, false, false, false}, - // hidden: - new boolean[] { false, false, false, false, false}, - // outlineLevel - new int[] { 1, 2, 3, 3, 3 } - ); - - - // Level 1 collapsed, others expanded, should only have 4 rows, all hidden: - verifyGroupCollapsed( - // level1, level2, level3 - true, false, false, - // collapsed: - new Boolean[] { false, false, false, false, false}, - // hidden: - new boolean[] { true, true, true, true, true}, - // outlineLevel - new int[] { 1, 2, 3, 3, 3 } - ); - - // Level 1 and 2 collapsed, Level 3 expanded, - verifyGroupCollapsed( - // level1, level2, level3 - true, true, false, - // collapsed: - new Boolean[] { false, false, false, false, true, false}, - // hidden: - new boolean[] { true, true, true, true, true, false}, - // outlineLevel - new int[] { 1, 2, 3, 3, 3, 0 } - ); - - // Level 1 collapsed, Level 2 expanded, Level 3 collapsed - verifyGroupCollapsed( - // level1, level2, level3 - true, false, true, - // collapsed: - new Boolean[] { false, false, false, false, false, true}, - // hidden: - new boolean[] { true, true, true, true, true, false}, - // outlineLevel - new int[] { 1, 2, 3, 3, 3, 0 } - ); - - // Level 2 collapsed, others expanded: - verifyGroupCollapsed( - // level1, level2, level3 - false, true, false, - // collapsed: - new Boolean[] { false, false, false, false, false, false}, - // hidden: - new boolean[] { false, true, true, true, true, false}, - // outlineLevel - new int[] { 1, 2, 3, 3, 3, 0 } - ); - - // Level 3 collapsed, others expanded - verifyGroupCollapsed( - // level1, level2, level3 - false, false, true, - // collapsed: - new Boolean[] { false, false, false, false, false, true}, - // hidden: - new boolean[] { false, false, true, true, true, false}, - // outlineLevel - new int[] { 1, 2, 3, 3, 3, 0 } - ); - - // All collapsed - verifyGroupCollapsed( - // level1, level2, level3 - true, true, true, - // collapsed: - new Boolean[] { false, false, false, false, true, true}, - // hidden: - new boolean[] { true, true, true, true, true, false}, - // outlineLevel - new int[] { 1, 2, 3, 3, 3, 0 } - ); - } - - - private void verifyGroupCollapsed(boolean level1, boolean level2, boolean level3, - Boolean[] collapsed, boolean[] hidden, int[] outlineLevel) throws IOException { - Workbook wb = new XSSFWorkbook(); - Sheet sheet = wb.createSheet("sheet123"); - - for (int i = 0; i < 4; i++) { - sheet.createRow(i); - } - - sheet.groupRow(0, 4); - sheet.groupRow(1, 4); - sheet.groupRow(2, 4); - - sheet.setRowGroupCollapsed(0, level1); - sheet.setRowGroupCollapsed(1, level2); - sheet.setRowGroupCollapsed(2, level3); - - checkWorkbookGrouping(wb, collapsed, hidden, outlineLevel); - } - - public void test55640_VerifyCasesSpec() throws IOException { - // NOTE: This is currently based on current behavior of POI, somehow - // what POI returns in the calls to collapsed/hidden is not fully matching - // the examples in the spec or I did not fully understand how POI stores the data internally... - - // all expanded - verifyGroupCollapsedSpec( - // level3, level2, level1 - false, false, false, - // collapsed: - new Boolean[] { false, false, false, false}, - // hidden: - new boolean[] { false, false, false, false}, - // outlineLevel - new int[] { 3, 3, 2, 1 } - ); - - - verifyGroupCollapsedSpec( - // level3, level2, level1 - false, false, true, - // collapsed: - new Boolean[] { false, false, false, true}, - // hidden: - new boolean[] { true, true, true, false}, - // outlineLevel - new int[] { 3, 3, 2, 1 } - ); - - verifyGroupCollapsedSpec( - // level3, level2, level1 - false, true, false, - // collapsed: - new Boolean[] { false, false, true, false}, - // hidden: - new boolean[] { true, true, true, false}, - // outlineLevel - new int[] { 3, 3, 2, 1 } - ); - - verifyGroupCollapsedSpec( - // level3, level2, level1 - false, true, true, - // collapsed: - new Boolean[] { false, false, true, true}, - // hidden: - new boolean[] { true, true, true, false}, - // outlineLevel - new int[] { 3, 3, 2, 1 } - ); - } - - private void verifyGroupCollapsedSpec(boolean level1, boolean level2, boolean level3, - Boolean[] collapsed, boolean[] hidden, int[] outlineLevel) throws IOException { - Workbook wb = new XSSFWorkbook(); - Sheet sheet = wb.createSheet("sheet123"); - - for (int i = 5; i < 9; i++) { - sheet.createRow(i); - } - - sheet.groupRow(5, 6); - sheet.groupRow(5, 7); - sheet.groupRow(5, 8); - - sheet.setRowGroupCollapsed(6, level1); - sheet.setRowGroupCollapsed(7, level2); - sheet.setRowGroupCollapsed(8, level3); - - checkWorkbookGrouping(wb, collapsed, hidden, outlineLevel); - } - - private void checkWorkbookGrouping(Workbook wb, Boolean[] collapsed, boolean[] hidden, int[] outlineLevel) throws IOException { - printWorkbook(wb); - Sheet sheet = wb.getSheetAt(0); - - assertEquals(collapsed.length, hidden.length); - assertEquals(collapsed.length, outlineLevel.length); - assertEquals("Expected " + collapsed.length + " rows with collapsed state, but had " + (sheet.getLastRowNum()-sheet.getFirstRowNum()+1) + " rows (" - + sheet.getFirstRowNum() + "-" + sheet.getLastRowNum() + ")", - collapsed.length, sheet.getLastRowNum()-sheet.getFirstRowNum()+1); - for(int i = sheet.getFirstRowNum(); i < sheet.getLastRowNum();i++) { - if(collapsed[i-sheet.getFirstRowNum()] == null) { - continue; - } - XSSFRow row = (XSSFRow) sheet.getRow(i); - assertNotNull("Could not read row " + i, row); - assertNotNull("Could not read row " + i, row.getCTRow()); - assertEquals("Row: " + i + ": collapsed", collapsed[i-sheet.getFirstRowNum()].booleanValue(), row.getCTRow().getCollapsed()); - assertEquals("Row: " + i + ": hidden", hidden[i-sheet.getFirstRowNum()], row.getCTRow().getHidden()); - - assertEquals("Row: " + i + ": level", outlineLevel[i-sheet.getFirstRowNum()], row.getCTRow().getOutlineLevel()); - } - - writeToFile(wb); - } - - - public void test55640working() throws IOException { - Workbook wb = new XSSFWorkbook(); - Sheet sheet = wb.createSheet("sheet123"); - - sheet.groupRow(1, 4); - sheet.groupRow(2, 5); - sheet.groupRow(3, 6); - - sheet.setRowGroupCollapsed(1, true); - sheet.setRowGroupCollapsed(2, false); - sheet.setRowGroupCollapsed(3, false); - - writeToFile(wb); - } - - // just used for printing out contents of spreadsheets - public void notRuntest55640printSample() { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("55640.xlsx"); - printWorkbook(wb); - - wb = XSSFTestDataSamples.openSampleWorkbook("GroupTest.xlsx"); - printWorkbook(wb); - } - - private void printWorkbook(Workbook wb) { - // disable all output for now... -// Sheet sheet = wb.getSheetAt(0); -// -// for(Iterator it = sheet.rowIterator();it.hasNext();) { -// XSSFRow row = (XSSFRow) it.next(); -// boolean collapsed = row.getCTRow().getCollapsed(); -// boolean hidden = row.getCTRow().getHidden(); -// short level = row.getCTRow().getOutlineLevel(); -// -// System.out.println("Row: " + row.getRowNum() + ": Level: " + level + " Collapsed: " + collapsed + " Hidden: " + hidden); -// } - } - - public void testGroupingTest() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("GroupTest.xlsx"); - - assertEquals(31, wb.getSheetAt(0).getLastRowNum()); - - // NOTE: This is currently based on current behavior of POI, somehow - // what POI returns in the calls to collapsed/hidden is not fully matching - // the examples in the spec or I did not fully understand how POI stores the data internally... - checkWorkbookGrouping(wb, - new Boolean [] { - // 0-4 - false, false, false, false, false, null, null, - // 7-11 - false, false, true, true, true, null, null, - // 14-18 - false, false, true, false, false, null, - // 20-24 - false, false, true, true, false, null, null, - // 27-31 - false, false, false, true, false }, - new boolean[] { - // 0-4 - false, false, false, false, false, false, false, - // 7-11 - true, true, true, true, false, false, false, - // 14-18 - true, true, false, false, false, false, - // 20-24 - true, true, true, false, false, false, false, - // 27-31 - true, true, true, true, false }, - // outlineLevel - new int[] { - // 0-4 - 3, 3, 2, 1, 0, 0, 0, - // 7-11 - 3, 3, 2, 1, 0, 0, 0, - // 14-18 - 3, 3, 2, 1, 0, 0, - // 20-24 - 3, 3, 2, 1, 0, 0, 0, - // 27-31 - 3, 3, 2, 1, 0, - } - ); - /* -Row: 0: Level: 3 Collapsed: false Hidden: false -Row: 1: Level: 3 Collapsed: false Hidden: false -Row: 2: Level: 2 Collapsed: false Hidden: false -Row: 3: Level: 1 Collapsed: false Hidden: false -Row: 4: Level: 0 Collapsed: false Hidden: false -Row: 7: Level: 3 Collapsed: false Hidden: true -Row: 8: Level: 3 Collapsed: false Hidden: true -Row: 9: Level: 2 Collapsed: true Hidden: true -Row: 10: Level: 1 Collapsed: true Hidden: true -Row: 11: Level: 0 Collapsed: true Hidden: false -Row: 14: Level: 3 Collapsed: false Hidden: true -Row: 15: Level: 3 Collapsed: false Hidden: true -Row: 16: Level: 2 Collapsed: true Hidden: false -Row: 17: Level: 1 Collapsed: false Hidden: false -Row: 18: Level: 0 Collapsed: false Hidden: false -Row: 20: Level: 3 Collapsed: false Hidden: true -Row: 21: Level: 3 Collapsed: false Hidden: true -Row: 22: Level: 2 Collapsed: true Hidden: true -Row: 23: Level: 1 Collapsed: true Hidden: false -Row: 24: Level: 0 Collapsed: false Hidden: false -Row: 27: Level: 3 Collapsed: false Hidden: true -Row: 28: Level: 3 Collapsed: false Hidden: true -Row: 29: Level: 2 Collapsed: false Hidden: true -Row: 30: Level: 1 Collapsed: true Hidden: true -Row: 31: Level: 0 Collapsed: true Hidden: false - */ - } -} \ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetShiftRows.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetShiftRows.java deleted file mode 100644 index 78e9d1bb2..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetShiftRows.java +++ /dev/null @@ -1,489 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import static org.apache.poi.POITestCase.skipTest; -import static org.apache.poi.POITestCase.testPassesNow; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; - -import java.io.IOException; - -import org.apache.poi.ss.usermodel.BaseTestSheetShiftRows; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.Comment; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.CellAddress; -import org.apache.poi.ss.util.CellUtil; -import org.apache.poi.util.IOUtils; -import org.apache.poi.xssf.XSSFITestDataProvider; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.xmlbeans.impl.values.XmlValueDisconnectedException; -import org.junit.Test; - -public final class TestXSSFSheetShiftRows extends BaseTestSheetShiftRows { - - public TestXSSFSheetShiftRows(){ - super(XSSFITestDataProvider.instance); - } - - @Override - @Test - public void testShiftRowBreaks() { - // disabled test from superclass - // TODO - support shifting of page breaks - } - - /** Error occurred at FormulaShifter#rowMoveAreaPtg while shift rows upward. */ - @Test - public void testBug54524() throws IOException { - XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("54524.xlsx"); - XSSFSheet sheet = workbook.getSheetAt(0); - sheet.shiftRows(3, 5, -1); - - Cell cell = CellUtil.getCell(sheet.getRow(1), 0); - assertEquals(1.0, cell.getNumericCellValue(), 0); - cell = CellUtil.getCell(sheet.getRow(2), 0); - assertEquals("SUM(A2:A2)", cell.getCellFormula()); - cell = CellUtil.getCell(sheet.getRow(3), 0); - assertEquals("X", cell.getStringCellValue()); - workbook.close(); - } - - /** negative row shift causes corrupted data or throws exception */ - @Test - public void testBug53798() throws IOException { - // NOTE that for HSSF (.xls) negative shifts combined with positive ones do work as expected - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("53798.xlsx"); - - Sheet testSheet = wb.getSheetAt(0); - // 1) corrupted xlsx (unreadable data in the first row of a shifted group) already comes about - // when shifted by less than -1 negative amount (try -2) - testSheet.shiftRows(3, 3, -2); - - // 2) attempt to create a new row IN PLACE of a removed row by a negative shift causes corrupted - // xlsx file with unreadable data in the negative shifted row. - // NOTE it's ok to create any other row. - Row newRow = testSheet.createRow(3); - Cell newCell = newRow.createCell(0); - newCell.setCellValue("new Cell in row "+newRow.getRowNum()); - - // 3) once a negative shift has been made any attempt to shift another group of rows - // (note: outside of previously negative shifted rows) by a POSITIVE amount causes POI exception: - // org.apache.xmlbeans.impl.values.XmlValueDisconnectedException. - // NOTE: another negative shift on another group of rows is successful, provided no new rows in - // place of previously shifted rows were attempted to be created as explained above. - - // -- CHANGE the shift to positive once the behaviour of the above has been tested - testSheet.shiftRows(6, 7, 1); - - Workbook read = XSSFTestDataSamples.writeOutAndReadBack(wb); - wb.close(); - assertNotNull(read); - - Sheet readSheet = read.getSheetAt(0); - verifyCellContent(readSheet, 0, "0.0"); - verifyCellContent(readSheet, 1, "3.0"); - verifyCellContent(readSheet, 2, "2.0"); - verifyCellContent(readSheet, 3, "new Cell in row 3"); - verifyCellContent(readSheet, 4, "4.0"); - verifyCellContent(readSheet, 5, "5.0"); - verifyCellContent(readSheet, 6, null); - verifyCellContent(readSheet, 7, "6.0"); - verifyCellContent(readSheet, 8, "7.0"); - read.close(); - } - - private void verifyCellContent(Sheet readSheet, int row, String expect) { - Row readRow = readSheet.getRow(row); - if(expect == null) { - assertNull(readRow); - return; - } - Cell readCell = readRow.getCell(0); - //noinspection deprecation - if(readCell.getCellTypeEnum() == CellType.NUMERIC) { - assertEquals(expect, Double.toString(readCell.getNumericCellValue())); - } else { - assertEquals(expect, readCell.getStringCellValue()); - } - } - - /** negative row shift causes corrupted data or throws exception */ - @Test - public void testBug53798a() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("53798.xlsx"); - - Sheet testSheet = wb.getSheetAt(0); - testSheet.shiftRows(3, 3, -1); - for (Row r : testSheet) { - r.getRowNum(); - } - testSheet.shiftRows(6, 6, 1); - - Workbook read = XSSFTestDataSamples.writeOutAndReadBack(wb); - wb.close(); - assertNotNull(read); - - Sheet readSheet = read.getSheetAt(0); - verifyCellContent(readSheet, 0, "0.0"); - verifyCellContent(readSheet, 1, "1.0"); - verifyCellContent(readSheet, 2, "3.0"); - verifyCellContent(readSheet, 3, null); - verifyCellContent(readSheet, 4, "4.0"); - verifyCellContent(readSheet, 5, "5.0"); - verifyCellContent(readSheet, 6, null); - verifyCellContent(readSheet, 7, "6.0"); - verifyCellContent(readSheet, 8, "8.0"); - read.close(); - } - - /** Shifting rows with comment result - Unreadable content error and comment deletion */ - @Test - public void testBug56017() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("56017.xlsx"); - - Sheet sheet = wb.getSheetAt(0); - - Comment comment = sheet.getCellComment(new CellAddress(0, 0)); - assertNotNull(comment); - assertEquals("Amdocs", comment.getAuthor()); - assertEquals("Amdocs:\ntest\n", comment.getString().getString()); - - sheet.shiftRows(0, 1, 1); - - // comment in row 0 is gone - comment = sheet.getCellComment(new CellAddress(0, 0)); - assertNull(comment); - - // comment is now in row 1 - comment = sheet.getCellComment(new CellAddress(1, 0)); - assertNotNull(comment); - assertEquals("Amdocs", comment.getAuthor()); - assertEquals("Amdocs:\ntest\n", comment.getString().getString()); - - Workbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(wb); - wb.close(); - assertNotNull(wbBack); - - Sheet sheetBack = wbBack.getSheetAt(0); - - // comment in row 0 is gone - comment = sheetBack.getCellComment(new CellAddress(0, 0)); - assertNull(comment); - - // comment is now in row 1 - comment = sheetBack.getCellComment(new CellAddress(1, 0)); - assertNotNull(comment); - assertEquals("Amdocs", comment.getAuthor()); - assertEquals("Amdocs:\ntest\n", comment.getString().getString()); - wbBack.close(); - } - - /** Moving the active sheet and deleting the others results in a corrupted file */ - @Test - public void test57171() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57171_57163_57165.xlsx"); - assertEquals(5, wb.getActiveSheetIndex()); - removeAllSheetsBut(5, wb); // 5 is the active / selected sheet - assertEquals(0, wb.getActiveSheetIndex()); - - Workbook wbRead = XSSFTestDataSamples.writeOutAndReadBack(wb); - wb.close(); - assertEquals(0, wbRead.getActiveSheetIndex()); - - wbRead.removeSheetAt(0); - assertEquals(0, wbRead.getActiveSheetIndex()); - - wbRead.close(); - } - - /** Cannot delete an arbitrary sheet in an XLS workbook (only the last one) */ - @Test - public void test57163() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57171_57163_57165.xlsx"); - assertEquals(5, wb.getActiveSheetIndex()); - wb.removeSheetAt(0); - assertEquals(4, wb.getActiveSheetIndex()); - - wb.close(); - } - - @Test - public void testSetSheetOrderAndAdjustActiveSheet() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57171_57163_57165.xlsx"); - - assertEquals(5, wb.getActiveSheetIndex()); - - // move the sheets around in all possible combinations to check that the active sheet - // is set correctly in all cases - wb.setSheetOrder(wb.getSheetName(5), 4); - assertEquals(4, wb.getActiveSheetIndex()); - - wb.setSheetOrder(wb.getSheetName(5), 5); - assertEquals(4, wb.getActiveSheetIndex()); - - wb.setSheetOrder(wb.getSheetName(3), 5); - assertEquals(3, wb.getActiveSheetIndex()); - - wb.setSheetOrder(wb.getSheetName(4), 5); - assertEquals(3, wb.getActiveSheetIndex()); - - wb.setSheetOrder(wb.getSheetName(2), 2); - assertEquals(3, wb.getActiveSheetIndex()); - - wb.setSheetOrder(wb.getSheetName(2), 1); - assertEquals(3, wb.getActiveSheetIndex()); - - wb.setSheetOrder(wb.getSheetName(3), 5); - assertEquals(5, wb.getActiveSheetIndex()); - - wb.setSheetOrder(wb.getSheetName(0), 5); - assertEquals(4, wb.getActiveSheetIndex()); - - wb.setSheetOrder(wb.getSheetName(0), 5); - assertEquals(3, wb.getActiveSheetIndex()); - - wb.setSheetOrder(wb.getSheetName(0), 5); - assertEquals(2, wb.getActiveSheetIndex()); - - wb.setSheetOrder(wb.getSheetName(0), 5); - assertEquals(1, wb.getActiveSheetIndex()); - - wb.setSheetOrder(wb.getSheetName(0), 5); - assertEquals(0, wb.getActiveSheetIndex()); - - wb.setSheetOrder(wb.getSheetName(0), 5); - assertEquals(5, wb.getActiveSheetIndex()); - - wb.close(); - } - - @Test - public void testRemoveSheetAndAdjustActiveSheet() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57171_57163_57165.xlsx"); - - assertEquals(5, wb.getActiveSheetIndex()); - - wb.removeSheetAt(0); - assertEquals(4, wb.getActiveSheetIndex()); - - wb.setActiveSheet(3); - assertEquals(3, wb.getActiveSheetIndex()); - - wb.removeSheetAt(4); - assertEquals(3, wb.getActiveSheetIndex()); - - wb.removeSheetAt(3); - assertEquals(2, wb.getActiveSheetIndex()); - - wb.removeSheetAt(0); - assertEquals(1, wb.getActiveSheetIndex()); - - wb.removeSheetAt(1); - assertEquals(0, wb.getActiveSheetIndex()); - - wb.removeSheetAt(0); - assertEquals(0, wb.getActiveSheetIndex()); - - try { - wb.removeSheetAt(0); - fail("Should catch exception as no more sheets are there"); - } catch (IllegalArgumentException e) { - // expected - } - assertEquals(0, wb.getActiveSheetIndex()); - - wb.createSheet(); - assertEquals(0, wb.getActiveSheetIndex()); - - wb.removeSheetAt(0); - assertEquals(0, wb.getActiveSheetIndex()); - - wb.close(); - } - - /** Failed to clone a sheet from an Excel 2010 */ - @Test - public void test57165() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("57171_57163_57165.xlsx"); - assertEquals(5, wb.getActiveSheetIndex()); - removeAllSheetsBut(3, wb); - assertEquals(0, wb.getActiveSheetIndex()); - wb.createSheet("New Sheet1"); - assertEquals(0, wb.getActiveSheetIndex()); - wb.cloneSheet(0); // Throws exception here - wb.setSheetName(1, "New Sheet"); - assertEquals(0, wb.getActiveSheetIndex()); - - wb.close(); - } - - private static void removeAllSheetsBut(int sheetIndex, Workbook wb) { - int sheetNb = wb.getNumberOfSheets(); - // Move this sheet at the first position - wb.setSheetOrder(wb.getSheetName(sheetIndex), 0); - // Must make this sheet active (otherwise, for XLSX, Excel might protest that active sheet no longer exists) - // I think POI should automatically handle this case when deleting sheets... - // wb.setActiveSheet(0); - for (int sn = sheetNb - 1; sn > 0; sn--) { - wb.removeSheetAt(sn); - } - } - - /** Shifting rows with cell comments only shifts comments from first such cell. Other cell comments not shifted */ - @Test - public void testBug57828_OnlyOneCommentShiftedInRow() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("57828.xlsx"); - XSSFSheet sheet = wb.getSheetAt(0); - - Comment comment1 = sheet.getCellComment(new CellAddress(2, 1)); - assertNotNull(comment1); - - Comment comment2 = sheet.getCellComment(new CellAddress(2, 2)); - assertNotNull(comment2); - - Comment comment3 = sheet.getCellComment(new CellAddress(1, 1)); - assertNull("NO comment in (1,1) and it should be null", comment3); - - sheet.shiftRows(2, 2, -1); - - comment3 = sheet.getCellComment(new CellAddress(1, 1)); - assertNotNull("Comment in (2,1) moved to (1,1) so its not null now.", comment3); - - comment1 = sheet.getCellComment(new CellAddress(2, 1)); - assertNull("No comment currently in (2,1) and hence it is null", comment1); - - comment2 = sheet.getCellComment(new CellAddress(1, 2)); - assertNotNull("Comment in (2,2) should have moved as well because of shift rows. But its not", comment2); - - wb.close(); - } - - // This test is written as expected-to-fail and should be rewritten - // as expected-to-pass when the bug is fixed. - //@Ignore("Bug 59733 - shiftRows() causes org.apache.xmlbeans.impl.values.XmlValueDisconnectedException") - @Test - public void bug59733() throws IOException { - Workbook workbook = new XSSFWorkbook(); - Sheet sheet = workbook.createSheet(); - for (int r=0; r<4; r++) { - sheet.createRow(r); - } - - // Shift the 2nd row on top of the 0th row - sheet.shiftRows(2, 2, -2); - - /* - * The following error is thrown when shifting the 3rd row on top of the 0th row - * If the rows are not created, the error does not occur - - org.apache.xmlbeans.impl.values.XmlValueDisconnectedException - at org.apache.xmlbeans.impl.values.XmlObjectBase.check_orphaned(XmlObjectBase.java:1258) - at org.openxmlformats.schemas.spreadsheetml.x2006.main.impl.CTRowImpl.getR(Unknown Source) - at org.apache.poi.xssf.usermodel.XSSFRow.getRowNum(XSSFRow.java:363) - at org.apache.poi.xssf.usermodel.TestXSSFSheetShiftRows.bug59733(TestXSSFSheetShiftRows.java:393) - */ - // FIXME: remove try, catch, and testPassesNow, skipTest when test passes - try { - sheet.removeRow(sheet.getRow(0)); - assertEquals(1, sheet.getRow(1).getRowNum()); - testPassesNow(59733); - } catch (XmlValueDisconnectedException e) { - skipTest(e); - } - - - workbook.close(); - } - - private static String getCellFormula(Sheet sheet, String address) { - CellAddress cellAddress = new CellAddress(address); - Row row = sheet.getRow(cellAddress.getRow()); - assertNotNull(row); - Cell cell = row.getCell(cellAddress.getColumn()); - assertNotNull(cell); - assertEquals(CellType.FORMULA, cell.getCellTypeEnum()); - return cell.getCellFormula(); - } - - // bug 59983: Wrong update of shared formulas after shiftRow - @Test - public void testSharedFormulas() throws Exception { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("TestShiftRowSharedFormula.xlsx"); - XSSFSheet sheet = wb.getSheetAt(0); - assertEquals("SUM(C2:C4)", getCellFormula(sheet, "C5")); - assertEquals("SUM(D2:D4)", getCellFormula(sheet, "D5")); - assertEquals("SUM(E2:E4)", getCellFormula(sheet, "E5")); - - assertEquals("SUM(C3:C5)", getCellFormula(sheet, "C6")); - assertEquals("SUM(D3:D5)", getCellFormula(sheet, "D6")); - assertEquals("SUM(E3:E5)", getCellFormula(sheet, "E6")); - - sheet.shiftRows(3, sheet.getLastRowNum(), 1); - - assertEquals("SUM(C2:C5)", getCellFormula(sheet, "C6")); - assertEquals("SUM(D2:D5)", getCellFormula(sheet, "D6")); - assertEquals("SUM(E2:E5)", getCellFormula(sheet, "E6")); - - assertEquals("SUM(C3:C6)", getCellFormula(sheet, "C7")); - assertEquals("SUM(D3:D6)", getCellFormula(sheet, "D7")); - assertEquals("SUM(E3:E6)", getCellFormula(sheet, "E7")); - wb.close(); - } - - // bug 59983: Wrong update of shared formulas after shiftRow - @Test - public void testShiftSharedFormulas() throws Exception { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("TestShiftRowSharedFormula.xlsx"); - XSSFSheet sheet = wb.getSheetAt(0); - assertEquals("SUM(C2:C4)", getCellFormula(sheet, "C5")); - assertEquals("SUM(D2:D4)", getCellFormula(sheet, "D5")); - assertEquals("SUM(E2:E4)", getCellFormula(sheet, "E5")); - - assertEquals("SUM(C3:C5)", getCellFormula(sheet, "C6")); - assertEquals("SUM(D3:D5)", getCellFormula(sheet, "D6")); - assertEquals("SUM(E3:E5)", getCellFormula(sheet, "E6")); - - sheet.shiftRows(sheet.getFirstRowNum(), 4, -1); - - assertEquals("SUM(C1:C3)", getCellFormula(sheet, "C4")); - assertEquals("SUM(D1:D3)", getCellFormula(sheet, "D4")); - assertEquals("SUM(E1:E3)", getCellFormula(sheet, "E4")); - - assertEquals("SUM(C2:C4)", getCellFormula(sheet, "C6")); - assertEquals("SUM(D2:D4)", getCellFormula(sheet, "D6")); - assertEquals("SUM(E2:E4)", getCellFormula(sheet, "E6")); - wb.close(); - } - - // bug 60260: shift rows or rename a sheet containing a named range - // that refers to formula with a unicode (non-ASCII) sheet name formula - @Test - public void shiftRowsWithUnicodeNamedRange() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("unicodeSheetName.xlsx"); - XSSFSheet sheet = wb.getSheetAt(0); - sheet.shiftRows(1, 2, 3); - IOUtils.closeQuietly(wb); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetUpdateArrayFormulas.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetUpdateArrayFormulas.java deleted file mode 100644 index 85378ec2b..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSheetUpdateArrayFormulas.java +++ /dev/null @@ -1,122 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; - -import java.io.IOException; - -import org.apache.poi.ss.usermodel.BaseTestSheetUpdateArrayFormulas; -import org.apache.poi.ss.usermodel.CellRange; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.xssf.XSSFITestDataProvider; -import org.junit.Test; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCell; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCellFormula; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STCellFormulaType; - -import junit.framework.AssertionFailedError; -/** - * Test array formulas in XSSF - * - * @author Yegor Kozlov - * @author Josh Micich - */ -public final class TestXSSFSheetUpdateArrayFormulas extends BaseTestSheetUpdateArrayFormulas { - - public TestXSSFSheetUpdateArrayFormulas() { - super(XSSFITestDataProvider.instance); - } - - // Test methods common with HSSF are in superclass - // Local methods here test XSSF-specific details of updating array formulas - @Test - public void testXSSFSetArrayFormula_singleCell() throws IOException { - CellRange cells; - - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFSheet sheet = workbook.createSheet(); - - // 1. single-cell array formula - String formula1 = "123"; - CellRangeAddress range = CellRangeAddress.valueOf("C3:C3"); - cells = sheet.setArrayFormula(formula1, range); - assertEquals(1, cells.size()); - - // check getFirstCell... - XSSFCell firstCell = cells.getTopLeftCell(); - assertSame(firstCell, sheet.getFirstCellInArrayFormula(firstCell)); - //retrieve the range and check it is the same - assertEquals(range.formatAsString(), firstCell.getArrayFormulaRange().formatAsString()); - confirmArrayFormulaCell(firstCell, "C3", formula1, "C3"); - - workbook.close(); - } - - @Test - public void testXSSFSetArrayFormula_multiCell() throws IOException { - CellRange cells; - - String formula2 = "456"; - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFSheet sheet = workbook.createSheet(); - - CellRangeAddress range = CellRangeAddress.valueOf("C4:C6"); - cells = sheet.setArrayFormula(formula2, range); - assertEquals(3, cells.size()); - - // sheet.setArrayFormula creates rows and cells for the designated range - /* - * From the spec: - * For a multi-cell formula, the c elements for all cells except the top-left - * cell in that range shall not have an f element; - */ - // Check that each cell exists and that the formula text is set correctly on the first cell - XSSFCell firstCell = cells.getTopLeftCell(); - confirmArrayFormulaCell(firstCell, "C4", formula2, "C4:C6"); - confirmArrayFormulaCell(cells.getCell(1, 0), "C5"); - confirmArrayFormulaCell(cells.getCell(2, 0), "C6"); - - assertSame(firstCell, sheet.getFirstCellInArrayFormula(firstCell)); - workbook.close(); - } - - private static void confirmArrayFormulaCell(XSSFCell c, String cellRef) { - confirmArrayFormulaCell(c, cellRef, null, null); - } - private static void confirmArrayFormulaCell(XSSFCell c, String cellRef, String formulaText, String arrayRangeRef) { - if (c == null) { - throw new AssertionFailedError("Cell should not be null."); - } - CTCell ctCell = c.getCTCell(); - assertEquals(cellRef, ctCell.getR()); - if (formulaText == null) { - assertFalse(ctCell.isSetF()); - assertNull(ctCell.getF()); - } else { - CTCellFormula f = ctCell.getF(); - assertEquals(arrayRangeRef, f.getRef()); - assertEquals(formulaText, f.getStringValue()); - assertEquals(STCellFormulaType.ARRAY, f.getT()); - } - } - -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSimpleShape.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSimpleShape.java deleted file mode 100644 index e9eebe68e..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFSimpleShape.java +++ /dev/null @@ -1,172 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel; - -import static org.junit.Assert.*; - -import java.awt.Color; -import java.io.IOException; - -import org.apache.poi.ss.usermodel.VerticalAlignment; -import org.junit.Test; - -public class TestXSSFSimpleShape { - @Test - public void testXSSFTextParagraph() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - try { - XSSFSheet sheet = wb.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - - XSSFTextBox shape = drawing.createTextbox(new XSSFClientAnchor(0, 0, 0, 0, 2, 2, 3, 4)); - - XSSFRichTextString rt = new XSSFRichTextString("Test String"); - - XSSFFont font = wb.createFont(); - Color color = new Color(0, 255, 255); - font.setColor(new XSSFColor(color)); - font.setFontName("Arial"); - rt.applyFont(font); - - shape.setText(rt); - - assertNotNull(shape.getCTShape()); - assertNotNull(shape.iterator()); - assertNotNull(XSSFSimpleShape.prototype()); - - for(ListAutoNumber nr : ListAutoNumber.values()) { - shape.getTextParagraphs().get(0).setBullet(nr); - assertNotNull(shape.getText()); - } - - shape.getTextParagraphs().get(0).setBullet(false); - assertNotNull(shape.getText()); - - shape.setText("testtext"); - assertEquals("testtext", shape.getText()); - - shape.setText(new XSSFRichTextString()); - assertEquals("null", shape.getText()); - - shape.addNewTextParagraph(); - shape.addNewTextParagraph("test-other-text"); - shape.addNewTextParagraph(new XSSFRichTextString("rtstring")); - shape.addNewTextParagraph(new XSSFRichTextString()); - assertEquals("null\n\ntest-other-text\nrtstring\nnull", shape.getText()); - - assertEquals(TextHorizontalOverflow.OVERFLOW, shape.getTextHorizontalOverflow()); - shape.setTextHorizontalOverflow(TextHorizontalOverflow.CLIP); - assertEquals(TextHorizontalOverflow.CLIP, shape.getTextHorizontalOverflow()); - shape.setTextHorizontalOverflow(TextHorizontalOverflow.OVERFLOW); - assertEquals(TextHorizontalOverflow.OVERFLOW, shape.getTextHorizontalOverflow()); - shape.setTextHorizontalOverflow(null); - assertEquals(TextHorizontalOverflow.OVERFLOW, shape.getTextHorizontalOverflow()); - shape.setTextHorizontalOverflow(null); - assertEquals(TextHorizontalOverflow.OVERFLOW, shape.getTextHorizontalOverflow()); - - assertEquals(TextVerticalOverflow.OVERFLOW, shape.getTextVerticalOverflow()); - shape.setTextVerticalOverflow(TextVerticalOverflow.CLIP); - assertEquals(TextVerticalOverflow.CLIP, shape.getTextVerticalOverflow()); - shape.setTextVerticalOverflow(TextVerticalOverflow.OVERFLOW); - assertEquals(TextVerticalOverflow.OVERFLOW, shape.getTextVerticalOverflow()); - shape.setTextVerticalOverflow(null); - assertEquals(TextVerticalOverflow.OVERFLOW, shape.getTextVerticalOverflow()); - shape.setTextVerticalOverflow(null); - assertEquals(TextVerticalOverflow.OVERFLOW, shape.getTextVerticalOverflow()); - - assertEquals(VerticalAlignment.TOP, shape.getVerticalAlignment()); - shape.setVerticalAlignment(VerticalAlignment.BOTTOM); - assertEquals(VerticalAlignment.BOTTOM, shape.getVerticalAlignment()); - shape.setVerticalAlignment(VerticalAlignment.TOP); - assertEquals(VerticalAlignment.TOP, shape.getVerticalAlignment()); - shape.setVerticalAlignment(null); - assertEquals(VerticalAlignment.TOP, shape.getVerticalAlignment()); - shape.setVerticalAlignment(null); - assertEquals(VerticalAlignment.TOP, shape.getVerticalAlignment()); - - assertEquals(TextDirection.HORIZONTAL, shape.getTextDirection()); - shape.setTextDirection(TextDirection.STACKED); - assertEquals(TextDirection.STACKED, shape.getTextDirection()); - shape.setTextDirection(TextDirection.HORIZONTAL); - assertEquals(TextDirection.HORIZONTAL, shape.getTextDirection()); - shape.setTextDirection(null); - assertEquals(TextDirection.HORIZONTAL, shape.getTextDirection()); - shape.setTextDirection(null); - assertEquals(TextDirection.HORIZONTAL, shape.getTextDirection()); - - assertEquals(3.6, shape.getBottomInset(), 0.01); - shape.setBottomInset(12.32); - assertEquals(12.32, shape.getBottomInset(), 0.01); - shape.setBottomInset(-1); - assertEquals(3.6, shape.getBottomInset(), 0.01); - shape.setBottomInset(-1); - assertEquals(3.6, shape.getBottomInset(), 0.01); - - assertEquals(3.6, shape.getLeftInset(), 0.01); - shape.setLeftInset(12.31); - assertEquals(12.31, shape.getLeftInset(), 0.01); - shape.setLeftInset(-1); - assertEquals(3.6, shape.getLeftInset(), 0.01); - shape.setLeftInset(-1); - assertEquals(3.6, shape.getLeftInset(), 0.01); - - assertEquals(3.6, shape.getRightInset(), 0.01); - shape.setRightInset(13.31); - assertEquals(13.31, shape.getRightInset(), 0.01); - shape.setRightInset(-1); - assertEquals(3.6, shape.getRightInset(), 0.01); - shape.setRightInset(-1); - assertEquals(3.6, shape.getRightInset(), 0.01); - - assertEquals(3.6, shape.getTopInset(), 0.01); - shape.setTopInset(23.31); - assertEquals(23.31, shape.getTopInset(), 0.01); - shape.setTopInset(-1); - assertEquals(3.6, shape.getTopInset(), 0.01); - shape.setTopInset(-1); - assertEquals(3.6, shape.getTopInset(), 0.01); - - assertTrue(shape.getWordWrap()); - shape.setWordWrap(false); - assertFalse(shape.getWordWrap()); - shape.setWordWrap(true); - assertTrue(shape.getWordWrap()); - - assertEquals(TextAutofit.NORMAL, shape.getTextAutofit()); - shape.setTextAutofit(TextAutofit.NORMAL); - assertEquals(TextAutofit.NORMAL, shape.getTextAutofit()); - shape.setTextAutofit(TextAutofit.SHAPE); - assertEquals(TextAutofit.SHAPE, shape.getTextAutofit()); - shape.setTextAutofit(TextAutofit.NONE); - assertEquals(TextAutofit.NONE, shape.getTextAutofit()); - - assertEquals(5, shape.getShapeType()); - shape.setShapeType(23); - assertEquals(23, shape.getShapeType()); - - // TODO: should this be supported? -// shape.setShapeType(-1); -// assertEquals(-1, shape.getShapeType()); -// shape.setShapeType(-1); -// assertEquals(-1, shape.getShapeType()); - - assertNotNull(shape.getShapeProperties()); - } finally { - wb.close(); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFTable.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFTable.java deleted file mode 100644 index 69b412a51..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFTable.java +++ /dev/null @@ -1,290 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.util.TempFile; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.streaming.SXSSFWorkbook; -import org.junit.Test; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTable; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTableColumn; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTableStyleInfo; - -public final class TestXSSFTable { - - @Test - public void bug56274() throws IOException { - // read sample file - XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("56274.xlsx"); - - // read the original sheet header order - XSSFRow row = wb1.getSheetAt(0).getRow(0); - List headers = new ArrayList(); - for (Cell cell : row) { - headers.add(cell.getStringCellValue()); - } - - // save the worksheet as-is using SXSSF - File outputFile = TempFile.createTempFile("poi-56274", ".xlsx"); - SXSSFWorkbook outputWorkbook = new SXSSFWorkbook(wb1); - FileOutputStream fos = new FileOutputStream(outputFile); - outputWorkbook.write(fos); - fos.close(); - outputWorkbook.close(); - - // re-read the saved file and make sure headers in the xml are in the original order - FileInputStream fis = new FileInputStream(outputFile); - XSSFWorkbook wb2 = new XSSFWorkbook(fis); - fis.close(); - CTTable ctTable = wb2.getSheetAt(0).getTables().get(0).getCTTable(); - CTTableColumn[] ctTableColumnArray = ctTable.getTableColumns().getTableColumnArray(); - - assertEquals("number of headers in xml table should match number of header cells in worksheet", - headers.size(), ctTableColumnArray.length); - for (int i = 0; i < headers.size(); i++) { - assertEquals("header name in xml table should match number of header cells in worksheet", - headers.get(i), ctTableColumnArray[i].getName()); - } - assertTrue(outputFile.delete()); - wb2.close(); - wb1.close(); - } - - @Test - public void testCTTableStyleInfo() throws IOException { - XSSFWorkbook outputWorkbook = new XSSFWorkbook(); - XSSFSheet sheet = outputWorkbook.createSheet(); - - //Create - XSSFTable outputTable = sheet.createTable(); - outputTable.setDisplayName("Test"); - CTTable outputCTTable = outputTable.getCTTable(); - - //Style configurations - CTTableStyleInfo outputStyleInfo = outputCTTable.addNewTableStyleInfo(); - outputStyleInfo.setName("TableStyleLight1"); - outputStyleInfo.setShowColumnStripes(false); - outputStyleInfo.setShowRowStripes(true); - - XSSFWorkbook inputWorkbook = XSSFTestDataSamples.writeOutAndReadBack(outputWorkbook); - List tables = inputWorkbook.getSheetAt(0).getTables(); - assertEquals("Tables number", 1, tables.size()); - - XSSFTable inputTable = tables.get(0); - assertEquals("Table display name", outputTable.getDisplayName(), inputTable.getDisplayName()); - - CTTableStyleInfo inputStyleInfo = inputTable.getCTTable().getTableStyleInfo(); - assertEquals("Style name", outputStyleInfo.getName(), inputStyleInfo.getName()); - assertEquals("Show column stripes", - outputStyleInfo.getShowColumnStripes(), inputStyleInfo.getShowColumnStripes()); - assertEquals("Show row stripes", - outputStyleInfo.getShowRowStripes(), inputStyleInfo.getShowRowStripes()); - - inputWorkbook.close(); - outputWorkbook.close(); - } - - @Test - public void findColumnIndex() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("StructuredReferences.xlsx"); - - XSSFTable table = wb.getTable("\\_Prime.1"); - assertNotNull(table); - assertEquals("column header has special escaped characters", - 0, table.findColumnIndex("calc='#*'#")); - assertEquals(1, table.findColumnIndex("Name")); - assertEquals(2, table.findColumnIndex("Number")); - - assertEquals("case insensitive", 2, table.findColumnIndex("NuMbEr")); - - // findColumnIndex should return -1 if no column header name matches - assertEquals(-1, table.findColumnIndex(null)); - assertEquals(-1, table.findColumnIndex("")); - assertEquals(-1, table.findColumnIndex("one")); - - wb.close(); - } - - @Test - public void findColumnIndexIsRelativeToTableNotSheet() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("DataTableCities.xlsx"); - XSSFTable table = wb.getTable("SmallCity"); - - // Make sure that XSSFTable.findColumnIndex returns the column index relative to the first - // column in the table, not the column number in the sheet - assertEquals(0, table.findColumnIndex("City")); // column I in worksheet but 0th column in table - assertEquals(1, table.findColumnIndex("Latitude")); - assertEquals(2, table.findColumnIndex("Longitude")); - assertEquals(3, table.findColumnIndex("Population")); - - wb.close(); - } - - @Test - public void getSheetName() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("StructuredReferences.xlsx"); - XSSFTable table = wb.getTable("\\_Prime.1"); - assertEquals("Table", table.getSheetName()); - wb.close(); - } - - @Test - public void isHasTotalsRow() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("StructuredReferences.xlsx"); - XSSFTable table = wb.getTable("\\_Prime.1"); - assertFalse(table.isHasTotalsRow()); - wb.close(); - } - - @Test - public void getStartColIndex() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("StructuredReferences.xlsx"); - XSSFTable table = wb.getTable("\\_Prime.1"); - assertEquals(0, table.getStartColIndex()); - wb.close(); - } - - @Test - public void getEndColIndex() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("StructuredReferences.xlsx"); - XSSFTable table = wb.getTable("\\_Prime.1"); - assertEquals(2, table.getEndColIndex()); - wb.close(); - } - - @Test - public void getStartRowIndex() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("StructuredReferences.xlsx"); - XSSFTable table = wb.getTable("\\_Prime.1"); - assertEquals(0, table.getStartRowIndex()); - wb.close(); - } - - @Test - public void getEndRowIndex() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("StructuredReferences.xlsx"); - XSSFTable table = wb.getTable("\\_Prime.1"); - assertEquals(6, table.getEndRowIndex()); - wb.close(); - } - - @Test - public void getStartCellReference() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("StructuredReferences.xlsx"); - XSSFTable table = wb.getTable("\\_Prime.1"); - assertEquals(new CellReference("A1"), table.getStartCellReference()); - wb.close(); - } - - @Test - public void getEndCellReference() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("StructuredReferences.xlsx"); - XSSFTable table = wb.getTable("\\_Prime.1"); - assertEquals(new CellReference("C7"), table.getEndCellReference()); - wb.close(); - } - - @Test - public void getNumberOfMappedColumns() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("StructuredReferences.xlsx"); - XSSFTable table = wb.getTable("\\_Prime.1"); - assertEquals(3, table.getNumberOfMappedColumns()); - wb.close(); - } - - @Test - public void getAndSetDisplayName() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("StructuredReferences.xlsx"); - XSSFTable table = wb.getTable("\\_Prime.1"); - assertEquals("\\_Prime.1", table.getDisplayName()); - - table.setDisplayName(null); - assertNull(table.getDisplayName()); - assertEquals("\\_Prime.1", table.getName()); // name and display name are different - - table.setDisplayName("Display name"); - assertEquals("Display name", table.getDisplayName()); - assertEquals("\\_Prime.1", table.getName()); // name and display name are different - - wb.close(); - } - - @Test - public void getCellReferences() { - // make sure that cached start and end cell references - // can be synchronized with the underlying CTTable - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sh = wb.createSheet(); - XSSFTable table = sh.createTable(); - CTTable ctTable = table.getCTTable(); - ctTable.setRef("B2:E8"); - - assertEquals(new CellReference("B2"), table.getStartCellReference()); - assertEquals(new CellReference("E8"), table.getEndCellReference()); - - // At this point start and end cell reference are cached - // and may not follow changes to the underlying CTTable - ctTable.setRef("C1:M3"); - - assertEquals(new CellReference("B2"), table.getStartCellReference()); - assertEquals(new CellReference("E8"), table.getEndCellReference()); - - // Force a synchronization between CTTable and XSSFTable - // start and end cell references - table.updateReferences(); - - assertEquals(new CellReference("C1"), table.getStartCellReference()); - assertEquals(new CellReference("M3"), table.getEndCellReference()); - - } - - @Test - public void getRowCount() { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sh = wb.createSheet(); - XSSFTable table = sh.createTable(); - CTTable ctTable = table.getCTTable(); - - assertEquals(0, table.getRowCount()); - - ctTable.setRef("B2:B2"); - // update cell references to clear the cache - table.updateReferences(); - assertEquals(1, table.getRowCount()); - - ctTable.setRef("B2:B12"); - // update cell references to clear the cache - table.updateReferences(); - assertEquals(11, table.getRowCount()); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFTextParagraph.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFTextParagraph.java deleted file mode 100644 index 7952f1f01..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFTextParagraph.java +++ /dev/null @@ -1,198 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel; - -import static org.junit.Assert.*; - -import java.awt.Color; -import java.io.IOException; -import java.util.List; - -import org.junit.Test; - -public class TestXSSFTextParagraph { - @Test - public void testXSSFTextParagraph() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - try { - XSSFSheet sheet = wb.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - - XSSFTextBox shape = drawing.createTextbox(new XSSFClientAnchor(0, 0, 0, 0, 2, 2, 3, 4)); - XSSFRichTextString rt = new XSSFRichTextString("Test String"); - - XSSFFont font = wb.createFont(); - Color color = new Color(0, 255, 255); - font.setColor(new XSSFColor(color)); - font.setFontName("Arial"); - rt.applyFont(font); - - shape.setText(rt); - - List paras = shape.getTextParagraphs(); - assertEquals(1, paras.size()); - - XSSFTextParagraph text = paras.get(0); - assertEquals("Test String", text.getText()); - - assertFalse(text.isBullet()); - assertNotNull(text.getXmlObject()); - assertEquals(shape.getCTShape(), text.getParentShape()); - assertNotNull(text.iterator()); - assertNotNull(text.addLineBreak()); - - assertNotNull(text.getTextRuns()); - assertEquals(2, text.getTextRuns().size()); - text.addNewTextRun(); - assertEquals(3, text.getTextRuns().size()); - - assertEquals(TextAlign.LEFT, text.getTextAlign()); - text.setTextAlign(null); - assertEquals(TextAlign.LEFT, text.getTextAlign()); - text.setTextAlign(TextAlign.CENTER); - assertEquals(TextAlign.CENTER, text.getTextAlign()); - text.setTextAlign(TextAlign.RIGHT); - assertEquals(TextAlign.RIGHT, text.getTextAlign()); - text.setTextAlign(null); - assertEquals(TextAlign.LEFT, text.getTextAlign()); - - text.setTextFontAlign(TextFontAlign.BASELINE); - assertEquals(TextFontAlign.BASELINE, text.getTextFontAlign()); - text.setTextFontAlign(TextFontAlign.BOTTOM); - assertEquals(TextFontAlign.BOTTOM, text.getTextFontAlign()); - text.setTextFontAlign(null); - assertEquals(TextFontAlign.BASELINE, text.getTextFontAlign()); - text.setTextFontAlign(null); - assertEquals(TextFontAlign.BASELINE, text.getTextFontAlign()); - - assertNull(text.getBulletFont()); - text.setBulletFont("Arial"); - assertEquals("Arial", text.getBulletFont()); - - assertNull(text.getBulletCharacter()); - text.setBulletCharacter("."); - assertEquals(".", text.getBulletCharacter()); - - assertNull(text.getBulletFontColor()); - text.setBulletFontColor(color); - assertEquals(color, text.getBulletFontColor()); - - assertEquals(100.0, text.getBulletFontSize(), 0.01); - text.setBulletFontSize(1.0); - assertEquals(1.0, text.getBulletFontSize(), 0.01); - text.setBulletFontSize(1.0); - assertEquals(1.0, text.getBulletFontSize(), 0.01); - text.setBulletFontSize(-9.0); - assertEquals(-9.0, text.getBulletFontSize(), 0.01); - text.setBulletFontSize(-9.0); - assertEquals(-9.0, text.getBulletFontSize(), 0.01); - text.setBulletFontSize(1.0); - assertEquals(1.0, text.getBulletFontSize(), 0.01); - text.setBulletFontSize(-9.0); - assertEquals(-9.0, text.getBulletFontSize(), 0.01); - - assertEquals(0.0, text.getIndent(), 0.01); - text.setIndent(2.0); - assertEquals(2.0, text.getIndent(), 0.01); - text.setIndent(-1.0); - assertEquals(0.0, text.getIndent(), 0.01); - text.setIndent(-1.0); - assertEquals(0.0, text.getIndent(), 0.01); - - assertEquals(0.0, text.getLeftMargin(), 0.01); - text.setLeftMargin(3.0); - assertEquals(3.0, text.getLeftMargin(), 0.01); - text.setLeftMargin(-1.0); - assertEquals(0.0, text.getLeftMargin(), 0.01); - text.setLeftMargin(-1.0); - assertEquals(0.0, text.getLeftMargin(), 0.01); - - assertEquals(0.0, text.getRightMargin(), 0.01); - text.setRightMargin(4.5); - assertEquals(4.5, text.getRightMargin(), 0.01); - text.setRightMargin(-1.0); - assertEquals(0.0, text.getRightMargin(), 0.01); - text.setRightMargin(-1.0); - assertEquals(0.0, text.getRightMargin(), 0.01); - - assertEquals(0.0, text.getDefaultTabSize(), 0.01); - - assertEquals(0.0, text.getTabStop(0), 0.01); - text.addTabStop(3.14); - assertEquals(3.14, text.getTabStop(0), 0.01); - - assertEquals(100.0, text.getLineSpacing(), 0.01); - text.setLineSpacing(3.15); - assertEquals(3.15, text.getLineSpacing(), 0.01); - text.setLineSpacing(-2.13); - assertEquals(-2.13, text.getLineSpacing(), 0.01); - - assertEquals(0.0, text.getSpaceBefore(), 0.01); - text.setSpaceBefore(3.17); - assertEquals(3.17, text.getSpaceBefore(), 0.01); - text.setSpaceBefore(-4.7); - assertEquals(-4.7, text.getSpaceBefore(), 0.01); - - assertEquals(0.0, text.getSpaceAfter(), 0.01); - text.setSpaceAfter(6.17); - assertEquals(6.17, text.getSpaceAfter(), 0.01); - text.setSpaceAfter(-8.17); - assertEquals(-8.17, text.getSpaceAfter(), 0.01); - - assertEquals(0, text.getLevel()); - text.setLevel(1); - assertEquals(1, text.getLevel()); - text.setLevel(4); - assertEquals(4, text.getLevel()); - - assertTrue(text.isBullet()); - assertFalse(text.isBulletAutoNumber()); - text.setBullet(false); - text.setBullet(false); - assertFalse(text.isBullet()); - assertFalse(text.isBulletAutoNumber()); - text.setBullet(true); - assertTrue(text.isBullet()); - assertFalse(text.isBulletAutoNumber()); - assertEquals(0, text.getBulletAutoNumberStart()); - assertEquals(ListAutoNumber.ARABIC_PLAIN, text.getBulletAutoNumberScheme()); - - text.setBullet(false); - assertFalse(text.isBullet()); - text.setBullet(ListAutoNumber.CIRCLE_NUM_DB_PLAIN); - assertTrue(text.isBullet()); - assertTrue(text.isBulletAutoNumber()); - assertEquals(0, text.getBulletAutoNumberStart()); - assertEquals(ListAutoNumber.CIRCLE_NUM_DB_PLAIN, text.getBulletAutoNumberScheme()); - text.setBullet(false); - assertFalse(text.isBullet()); - assertFalse(text.isBulletAutoNumber()); - text.setBullet(ListAutoNumber.CIRCLE_NUM_WD_BLACK_PLAIN, 10); - assertTrue(text.isBullet()); - assertTrue(text.isBulletAutoNumber()); - assertEquals(10, text.getBulletAutoNumberStart()); - assertEquals(ListAutoNumber.CIRCLE_NUM_WD_BLACK_PLAIN, text.getBulletAutoNumberScheme()); - - - assertNotNull(text.toString()); - - new XSSFTextParagraph(text.getXmlObject(), shape.getCTShape()); - } finally { - wb.close(); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFTextRun.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFTextRun.java deleted file mode 100644 index e599e1761..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFTextRun.java +++ /dev/null @@ -1,142 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel; - -import static org.junit.Assert.*; - -import java.awt.Color; -import java.io.IOException; -import java.util.List; - -import org.junit.Test; - -public class TestXSSFTextRun { - @Test - public void testXSSFTextParagraph() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - try { - XSSFSheet sheet = wb.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - - XSSFTextBox shape = drawing.createTextbox(new XSSFClientAnchor(0, 0, 0, 0, 2, 2, 3, 4)); - - XSSFTextParagraph para = shape.addNewTextParagraph(); - para.addNewTextRun().setText("Line 1"); - - List runs = para.getTextRuns(); - assertEquals(1, runs.size()); - XSSFTextRun run = runs.get(0); - assertEquals("Line 1", run.getText()); - - assertNotNull(run.getParentParagraph()); - assertNotNull(run.getXmlObject()); - assertNotNull(run.getRPr()); - - assertEquals(new Color(0,0,0), run.getFontColor()); - - Color color = new Color(0, 255, 255); - run.setFontColor(color); - assertEquals(color, run.getFontColor()); - - assertEquals(11.0, run.getFontSize(), 0.01); - run.setFontSize(12.32); - assertEquals(12.32, run.getFontSize(), 0.01); - run.setFontSize(-1.0); - assertEquals(11.0, run.getFontSize(), 0.01); - run.setFontSize(-1.0); - assertEquals(11.0, run.getFontSize(), 0.01); - try { - run.setFontSize(0.9); - fail("Should fail"); - } catch (IllegalArgumentException e) { - assertTrue(e.getMessage().contains("0.9")); - } - assertEquals(11.0, run.getFontSize(), 0.01); - - assertEquals(0.0, run.getCharacterSpacing(), 0.01); - run.setCharacterSpacing(12.31); - assertEquals(12.31, run.getCharacterSpacing(), 0.01); - run.setCharacterSpacing(0.0); - assertEquals(0.0, run.getCharacterSpacing(), 0.01); - run.setCharacterSpacing(0.0); - assertEquals(0.0, run.getCharacterSpacing(), 0.01); - - assertEquals("Calibri", run.getFontFamily()); - run.setFontFamily("Arial", (byte)1, (byte)1, false); - assertEquals("Arial", run.getFontFamily()); - run.setFontFamily("Arial", (byte)-1, (byte)1, false); - assertEquals("Arial", run.getFontFamily()); - run.setFontFamily("Arial", (byte)1, (byte)-1, false); - assertEquals("Arial", run.getFontFamily()); - run.setFontFamily("Arial", (byte)1, (byte)1, true); - assertEquals("Arial", run.getFontFamily()); - run.setFontFamily(null, (byte)1, (byte)1, false); - assertEquals("Calibri", run.getFontFamily()); - run.setFontFamily(null, (byte)1, (byte)1, false); - assertEquals("Calibri", run.getFontFamily()); - - run.setFont("Arial"); - assertEquals("Arial", run.getFontFamily()); - - assertEquals((byte)0, run.getPitchAndFamily()); - run.setFont(null); - assertEquals((byte)0, run.getPitchAndFamily()); - - assertFalse(run.isStrikethrough()); - run.setStrikethrough(true); - assertTrue(run.isStrikethrough()); - run.setStrikethrough(false); - assertFalse(run.isStrikethrough()); - - assertFalse(run.isSuperscript()); - run.setSuperscript(true); - assertTrue(run.isSuperscript()); - run.setSuperscript(false); - assertFalse(run.isSuperscript()); - - assertFalse(run.isSubscript()); - run.setSubscript(true); - assertTrue(run.isSubscript()); - run.setSubscript(false); - assertFalse(run.isSubscript()); - - assertEquals(TextCap.NONE, run.getTextCap()); - - assertFalse(run.isBold()); - run.setBold(true); - assertTrue(run.isBold()); - run.setBold(false); - assertFalse(run.isBold()); - - assertFalse(run.isItalic()); - run.setItalic(true); - assertTrue(run.isItalic()); - run.setItalic(false); - assertFalse(run.isItalic()); - - assertFalse(run.isUnderline()); - run.setUnderline(true); - assertTrue(run.isUnderline()); - run.setUnderline(false); - assertFalse(run.isUnderline()); - - assertNotNull(run.toString()); - } finally { - wb.close(); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFVMLDrawing.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFVMLDrawing.java deleted file mode 100644 index b8dbd36a7..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFVMLDrawing.java +++ /dev/null @@ -1,185 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.math.BigInteger; -import java.util.List; -import java.util.regex.Pattern; - -import org.apache.poi.POIDataSamples; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlObject; -import org.junit.Test; - -import com.microsoft.schemas.office.excel.CTClientData; -import com.microsoft.schemas.office.excel.STObjectType; -import com.microsoft.schemas.office.excel.STTrueFalseBlank; -import com.microsoft.schemas.office.office.CTShapeLayout; -import com.microsoft.schemas.office.office.STConnectType; -import com.microsoft.schemas.office.office.STInsetMode; -import com.microsoft.schemas.vml.CTShadow; -import com.microsoft.schemas.vml.CTShape; -import com.microsoft.schemas.vml.CTShapetype; -import com.microsoft.schemas.vml.STExt; -import com.microsoft.schemas.vml.STTrueFalse; - -public class TestXSSFVMLDrawing { - - @Test - public void testNew() throws IOException, XmlException { - XSSFVMLDrawing vml = new XSSFVMLDrawing(); - List items = vml.getItems(); - assertEquals(2, items.size()); - assertTrue(items.get(0) instanceof CTShapeLayout); - CTShapeLayout layout = (CTShapeLayout)items.get(0); - assertEquals(STExt.EDIT, layout.getExt()); - assertEquals(STExt.EDIT, layout.getIdmap().getExt()); - assertEquals("1", layout.getIdmap().getData()); - - assertTrue(items.get(1) instanceof CTShapetype); - CTShapetype type = (CTShapetype)items.get(1); - assertEquals("21600,21600", type.getCoordsize()); - assertEquals(202.0f, type.getSpt(), 0); - assertEquals("m,l,21600r21600,l21600,xe", type.getPath2()); - assertEquals("_x0000_t202", type.getId()); - assertEquals(STTrueFalse.T, type.getPathArray(0).getGradientshapeok()); - assertEquals(STConnectType.RECT, type.getPathArray(0).getConnecttype()); - - CTShape shape = vml.newCommentShape(); - assertEquals(3, items.size()); - assertSame(items.get(2), shape); - assertEquals("#_x0000_t202", shape.getType()); - assertEquals("position:absolute; visibility:hidden", shape.getStyle()); - assertEquals("#ffffe1", shape.getFillcolor()); - assertEquals(STInsetMode.AUTO, shape.getInsetmode()); - assertEquals("#ffffe1", shape.getFillArray(0).getColor()); - CTShadow shadow = shape.getShadowArray(0); - assertEquals(STTrueFalse.T, shadow.getOn()); - assertEquals("black", shadow.getColor()); - assertEquals(STTrueFalse.T, shadow.getObscured()); - assertEquals(STConnectType.NONE, shape.getPathArray(0).getConnecttype()); - assertEquals("mso-direction-alt:auto", shape.getTextboxArray(0).getStyle()); - CTClientData cldata = shape.getClientDataArray(0); - assertEquals(STObjectType.NOTE, cldata.getObjectType()); - assertEquals(1, cldata.sizeOfMoveWithCellsArray()); - assertEquals(1, cldata.sizeOfSizeWithCellsArray()); - assertEquals("1, 15, 0, 2, 3, 15, 3, 16", cldata.getAnchorArray(0)); - assertEquals("False", cldata.getAutoFillArray(0).toString()); - assertEquals(0, cldata.getRowArray(0).intValue()); - assertEquals(0, cldata.getColumnArray(0).intValue()); - assertEquals("[]", cldata.getVisibleList().toString()); - cldata.setVisibleArray(new STTrueFalseBlank.Enum[] { STTrueFalseBlank.Enum.forString("True") }); - assertEquals("[True]", cldata.getVisibleList().toString()); - - //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - vml.write(out); - - XSSFVMLDrawing vml2 = new XSSFVMLDrawing(); - vml2.read(new ByteArrayInputStream(out.toByteArray())); - List items2 = vml2.getItems(); - assertEquals(3, items2.size()); - assertTrue(items2.get(0) instanceof CTShapeLayout); - assertTrue(items2.get(1) instanceof CTShapetype); - assertTrue(items2.get(2) instanceof CTShape); - } - - @Test - public void testFindCommentShape() throws IOException, XmlException { - - XSSFVMLDrawing vml = new XSSFVMLDrawing(); - InputStream stream = POIDataSamples.getSpreadSheetInstance().openResourceAsStream("vmlDrawing1.vml"); - try { - vml.read(stream); - } finally { - stream.close(); - } - - CTShape sh_a1 = vml.findCommentShape(0, 0); - assertNotNull(sh_a1); - assertEquals("_x0000_s1025", sh_a1.getId()); - - CTShape sh_b1 = vml.findCommentShape(0, 1); - assertNotNull(sh_b1); - assertEquals("_x0000_s1026", sh_b1.getId()); - - CTShape sh_c1 = vml.findCommentShape(0, 2); - assertNull(sh_c1); - - CTShape sh_d1 = vml.newCommentShape(); - assertEquals("_x0000_s1027", sh_d1.getId()); - sh_d1.getClientDataArray(0).setRowArray(0, new BigInteger("0")); - sh_d1.getClientDataArray(0).setColumnArray(0, new BigInteger("3")); - assertSame(sh_d1, vml.findCommentShape(0, 3)); - - //newly created drawing - XSSFVMLDrawing newVml = new XSSFVMLDrawing(); - assertNull(newVml.findCommentShape(0, 0)); - - sh_a1 = newVml.newCommentShape(); - assertEquals("_x0000_s1025", sh_a1.getId()); - sh_a1.getClientDataArray(0).setRowArray(0, new BigInteger("0")); - sh_a1.getClientDataArray(0).setColumnArray(0, new BigInteger("1")); - assertSame(sh_a1, newVml.findCommentShape(0, 1)); - } - - @Test - public void testRemoveCommentShape() throws IOException, XmlException { - XSSFVMLDrawing vml = new XSSFVMLDrawing(); - InputStream stream = POIDataSamples.getSpreadSheetInstance().openResourceAsStream("vmlDrawing1.vml"); - try { - vml.read(stream); - } finally { - stream.close(); - } - - CTShape sh_a1 = vml.findCommentShape(0, 0); - assertNotNull(sh_a1); - - assertTrue(vml.removeCommentShape(0, 0)); - assertNull(vml.findCommentShape(0, 0)); - - } - - @Test - public void testEvilUnclosedBRFixing() throws IOException, XmlException { - XSSFVMLDrawing vml = new XSSFVMLDrawing(); - InputStream stream = POIDataSamples.getOpenXML4JInstance().openResourceAsStream("bug-60626.vml"); - try { - vml.read(stream); - } finally { - stream.close(); - } - Pattern p = Pattern.compile("
    "); - int count = 0; - for (XmlObject xo : vml.getItems()) { - String split[] = p.split(xo.toString()); - count += split.length-1; - } - assertEquals(16, count); - } -} \ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFWorkbook.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFWorkbook.java deleted file mode 100644 index b6360a6bb..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/TestXSSFWorkbook.java +++ /dev/null @@ -1,1175 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.util.Date; -import java.util.Iterator; -import java.util.List; -import java.util.zip.CRC32; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.POIXMLProperties; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.ContentTypes; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackageAccess; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.opc.PackagePartName; -import org.apache.poi.openxml4j.opc.PackageRelationshipCollection; -import org.apache.poi.openxml4j.opc.PackagingURIHelper; -import org.apache.poi.openxml4j.opc.internal.FileHelper; -import org.apache.poi.openxml4j.opc.internal.MemoryPackagePart; -import org.apache.poi.openxml4j.opc.internal.PackagePropertiesPart; -import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.ss.usermodel.BaseTestXWorkbook; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.Font; -import org.apache.poi.ss.usermodel.RichTextString; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Row.MissingCellPolicy; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.usermodel.WorkbookFactory; -import org.apache.poi.ss.util.AreaReference; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.LocaleUtil; -import org.apache.poi.util.TempFile; -import org.apache.poi.xssf.XSSFITestDataProvider; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.model.StylesTable; -import org.junit.Test; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCalcPr; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPivotCache; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorkbook; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorkbookPr; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STCalcMode; - -public final class TestXSSFWorkbook extends BaseTestXWorkbook { - - public TestXSSFWorkbook() { - super(XSSFITestDataProvider.instance); - } - - /** - * Tests that we can save, and then re-load a new document - */ - @Test - public void saveLoadNew() throws IOException, InvalidFormatException { - XSSFWorkbook wb1 = new XSSFWorkbook(); - - //check that the default date system is set to 1900 - CTWorkbookPr pr = wb1.getCTWorkbook().getWorkbookPr(); - assertNotNull(pr); - assertTrue(pr.isSetDate1904()); - assertFalse("XSSF must use the 1900 date system", pr.getDate1904()); - - Sheet sheet1 = wb1.createSheet("sheet1"); - Sheet sheet2 = wb1.createSheet("sheet2"); - wb1.createSheet("sheet3"); - - RichTextString rts = wb1.getCreationHelper().createRichTextString("hello world"); - - sheet1.createRow(0).createCell((short)0).setCellValue(1.2); - sheet1.createRow(1).createCell((short)0).setCellValue(rts); - sheet2.createRow(0); - - assertEquals(0, wb1.getSheetAt(0).getFirstRowNum()); - assertEquals(1, wb1.getSheetAt(0).getLastRowNum()); - assertEquals(0, wb1.getSheetAt(1).getFirstRowNum()); - assertEquals(0, wb1.getSheetAt(1).getLastRowNum()); - assertEquals(0, wb1.getSheetAt(2).getFirstRowNum()); - assertEquals(0, wb1.getSheetAt(2).getLastRowNum()); - - File file = TempFile.createTempFile("poi-", ".xlsx"); - OutputStream out = new FileOutputStream(file); - wb1.write(out); - out.close(); - - // Check the package contains what we'd expect it to - OPCPackage pkg = OPCPackage.open(file.toString()); - PackagePart wbRelPart = - pkg.getPart(PackagingURIHelper.createPartName("/xl/_rels/workbook.xml.rels")); - assertNotNull(wbRelPart); - assertTrue(wbRelPart.isRelationshipPart()); - assertEquals(ContentTypes.RELATIONSHIPS_PART, wbRelPart.getContentType()); - - PackagePart wbPart = - pkg.getPart(PackagingURIHelper.createPartName("/xl/workbook.xml")); - // Links to the three sheets, shared strings and styles - assertTrue(wbPart.hasRelationships()); - assertEquals(5, wbPart.getRelationships().size()); - wb1.close(); - - // Load back the XSSFWorkbook - @SuppressWarnings("resource") - XSSFWorkbook wb2 = new XSSFWorkbook(pkg); - assertEquals(3, wb2.getNumberOfSheets()); - assertNotNull(wb2.getSheetAt(0)); - assertNotNull(wb2.getSheetAt(1)); - assertNotNull(wb2.getSheetAt(2)); - - assertNotNull(wb2.getSharedStringSource()); - assertNotNull(wb2.getStylesSource()); - - assertEquals(0, wb2.getSheetAt(0).getFirstRowNum()); - assertEquals(1, wb2.getSheetAt(0).getLastRowNum()); - assertEquals(0, wb2.getSheetAt(1).getFirstRowNum()); - assertEquals(0, wb2.getSheetAt(1).getLastRowNum()); - assertEquals(0, wb2.getSheetAt(2).getFirstRowNum()); - assertEquals(0, wb2.getSheetAt(2).getLastRowNum()); - - sheet1 = wb2.getSheetAt(0); - assertEquals(1.2, sheet1.getRow(0).getCell(0).getNumericCellValue(), 0.0001); - assertEquals("hello world", sheet1.getRow(1).getCell(0).getRichStringCellValue().getString()); - - pkg.close(); - } - - @Test - public void existing() throws Exception { - - XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("Formatting.xlsx"); - assertNotNull(workbook.getSharedStringSource()); - assertNotNull(workbook.getStylesSource()); - - // And check a few low level bits too - OPCPackage pkg = OPCPackage.open(HSSFTestDataSamples.openSampleFileStream("Formatting.xlsx")); - PackagePart wbPart = - pkg.getPart(PackagingURIHelper.createPartName("/xl/workbook.xml")); - - // Links to the three sheets, shared, styles and themes - assertTrue(wbPart.hasRelationships()); - assertEquals(6, wbPart.getRelationships().size()); - - pkg.close(); - workbook.close(); - } - - @Test - public void getCellStyleAt() throws IOException{ - XSSFWorkbook workbook = new XSSFWorkbook(); - try { - short i = 0; - //get default style - CellStyle cellStyleAt = workbook.getCellStyleAt(i); - assertNotNull(cellStyleAt); - - //get custom style - StylesTable styleSource = workbook.getStylesSource(); - XSSFCellStyle customStyle = new XSSFCellStyle(styleSource); - XSSFFont font = new XSSFFont(); - font.setFontName("Verdana"); - customStyle.setFont(font); - int x = styleSource.putStyle(customStyle); - cellStyleAt = workbook.getCellStyleAt((short)x); - assertNotNull(cellStyleAt); - } finally { - workbook.close(); - } - } - - @Test - public void getFontAt() throws IOException{ - XSSFWorkbook workbook = new XSSFWorkbook(); - try { - StylesTable styleSource = workbook.getStylesSource(); - short i = 0; - //get default font - Font fontAt = workbook.getFontAt(i); - assertNotNull(fontAt); - - //get customized font - XSSFFont customFont = new XSSFFont(); - customFont.setItalic(true); - int x = styleSource.putFont(customFont); - fontAt = workbook.getFontAt((short)x); - assertNotNull(fontAt); - } finally { - workbook.close(); - } - } - - @Test - public void getNumCellStyles() throws IOException{ - XSSFWorkbook workbook = new XSSFWorkbook(); - try { - //get default cellStyles - assertEquals(1, workbook.getNumCellStyles()); - } finally { - workbook.close(); - } - } - - @Test - public void loadSave() throws IOException { - XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("Formatting.xlsx"); - assertEquals(3, workbook.getNumberOfSheets()); - assertEquals("dd/mm/yyyy", workbook.getSheetAt(0).getRow(1).getCell(0).getRichStringCellValue().getString()); - assertNotNull(workbook.getSharedStringSource()); - assertNotNull(workbook.getStylesSource()); - - // Write out, and check - // Load up again, check all still there - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(workbook); - assertEquals(3, wb2.getNumberOfSheets()); - assertNotNull(wb2.getSheetAt(0)); - assertNotNull(wb2.getSheetAt(1)); - assertNotNull(wb2.getSheetAt(2)); - - assertEquals("dd/mm/yyyy", wb2.getSheetAt(0).getRow(1).getCell(0).getRichStringCellValue().getString()); - assertEquals("yyyy/mm/dd", wb2.getSheetAt(0).getRow(2).getCell(0).getRichStringCellValue().getString()); - assertEquals("yyyy-mm-dd", wb2.getSheetAt(0).getRow(3).getCell(0).getRichStringCellValue().getString()); - assertEquals("yy/mm/dd", wb2.getSheetAt(0).getRow(4).getCell(0).getRichStringCellValue().getString()); - assertNotNull(wb2.getSharedStringSource()); - assertNotNull(wb2.getStylesSource()); - - workbook.close(); - wb2.close(); - } - - @Test - public void styles() throws IOException { - XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("Formatting.xlsx"); - - StylesTable ss = wb1.getStylesSource(); - assertNotNull(ss); - StylesTable st = ss; - - // Has 8 number formats - assertEquals(8, st.getNumDataFormats()); - // Has 2 fonts - assertEquals(2, st.getFonts().size()); - // Has 2 fills - assertEquals(2, st.getFills().size()); - // Has 1 border - assertEquals(1, st.getBorders().size()); - - // Add two more styles - assertEquals(StylesTable.FIRST_CUSTOM_STYLE_ID + 8, - st.putNumberFormat("testFORMAT")); - assertEquals(StylesTable.FIRST_CUSTOM_STYLE_ID + 8, - st.putNumberFormat("testFORMAT")); - assertEquals(StylesTable.FIRST_CUSTOM_STYLE_ID + 9, - st.putNumberFormat("testFORMAT2")); - assertEquals(10, st.getNumDataFormats()); - - - // Save, load back in again, and check - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - - ss = wb2.getStylesSource(); - assertNotNull(ss); - - assertEquals(10, st.getNumDataFormats()); - assertEquals(2, st.getFonts().size()); - assertEquals(2, st.getFills().size()); - assertEquals(1, st.getBorders().size()); - wb2.close(); - } - - @Test - public void incrementSheetId() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - try { - int sheetId = (int)wb.createSheet().sheet.getSheetId(); - assertEquals(1, sheetId); - sheetId = (int)wb.createSheet().sheet.getSheetId(); - assertEquals(2, sheetId); - - //test file with gaps in the sheetId sequence - XSSFWorkbook wbBack = XSSFTestDataSamples.openSampleWorkbook("47089.xlsm"); - try { - int lastSheetId = (int)wbBack.getSheetAt(wbBack.getNumberOfSheets() - 1).sheet.getSheetId(); - sheetId = (int)wbBack.createSheet().sheet.getSheetId(); - assertEquals(lastSheetId+1, sheetId); - } finally { - wbBack.close(); - } - } finally { - wb.close(); - } - } - - /** - * Test setting of core properties such as Title and Author - * @throws IOException - */ - @Test - public void workbookProperties() throws IOException { - XSSFWorkbook workbook = new XSSFWorkbook(); - try { - POIXMLProperties props = workbook.getProperties(); - assertNotNull(props); - //the Application property must be set for new workbooks, see Bugzilla #47559 - assertEquals("Apache POI", props.getExtendedProperties().getUnderlyingProperties().getApplication()); - - PackagePropertiesPart opcProps = props.getCoreProperties().getUnderlyingProperties(); - assertNotNull(opcProps); - - opcProps.setTitleProperty("Testing Bugzilla #47460"); - assertEquals("Apache POI", opcProps.getCreatorProperty().getValue()); - opcProps.setCreatorProperty("poi-dev@poi.apache.org"); - - XSSFWorkbook wbBack = XSSFTestDataSamples.writeOutAndReadBack(workbook); - assertEquals("Apache POI", wbBack.getProperties().getExtendedProperties().getUnderlyingProperties().getApplication()); - opcProps = wbBack.getProperties().getCoreProperties().getUnderlyingProperties(); - assertEquals("Testing Bugzilla #47460", opcProps.getTitleProperty().getValue()); - assertEquals("poi-dev@poi.apache.org", opcProps.getCreatorProperty().getValue()); - wbBack.close(); - } finally { - workbook.close(); - } - } - - /** - * Verify that the attached test data was not modified. If this test method - * fails, the test data is not working properly. - */ - @Test - public void bug47668() throws Exception { - XSSFWorkbook workbook = XSSFTestDataSamples.openSampleWorkbook("47668.xlsx"); - List allPictures = workbook.getAllPictures(); - assertEquals(1, allPictures.size()); - - PackagePartName imagePartName = PackagingURIHelper - .createPartName("/xl/media/image1.jpeg"); - PackagePart imagePart = workbook.getPackage().getPart(imagePartName); - assertNotNull(imagePart); - - for (XSSFPictureData pictureData : allPictures) { - PackagePart picturePart = pictureData.getPackagePart(); - assertSame(imagePart, picturePart); - } - - XSSFSheet sheet0 = workbook.getSheetAt(0); - XSSFDrawing drawing0 = sheet0.createDrawingPatriarch(); - XSSFPictureData pictureData0 = (XSSFPictureData) drawing0.getRelations().get(0); - byte[] data0 = pictureData0.getData(); - CRC32 crc0 = new CRC32(); - crc0.update(data0); - - XSSFSheet sheet1 = workbook.getSheetAt(1); - XSSFDrawing drawing1 = sheet1.createDrawingPatriarch(); - XSSFPictureData pictureData1 = (XSSFPictureData) drawing1.getRelations().get(0); - byte[] data1 = pictureData1.getData(); - CRC32 crc1 = new CRC32(); - crc1.update(data1); - - assertEquals(crc0.getValue(), crc1.getValue()); - workbook.close(); - } - - /** - * When deleting a sheet make sure that we adjust sheet indices of named ranges - */ - @Test - public void bug47737() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("47737.xlsx"); - assertEquals(2, wb.getNumberOfNames()); - assertNotNull(wb.getCalculationChain()); - - XSSFName nm0 = wb.getNameAt(0); - assertTrue(nm0.getCTName().isSetLocalSheetId()); - assertEquals(0, nm0.getCTName().getLocalSheetId()); - - XSSFName nm1 = wb.getNameAt(1); - assertTrue(nm1.getCTName().isSetLocalSheetId()); - assertEquals(1, nm1.getCTName().getLocalSheetId()); - - wb.removeSheetAt(0); - assertEquals(1, wb.getNumberOfNames()); - XSSFName nm2 = wb.getNameAt(0); - assertTrue(nm2.getCTName().isSetLocalSheetId()); - assertEquals(0, nm2.getCTName().getLocalSheetId()); - //calculation chain is removed as well - assertNull(wb.getCalculationChain()); - wb.close(); - - } - - /** - * Problems with XSSFWorkbook.removeSheetAt when workbook contains charts - */ - @Test - public void bug47813() throws IOException { - XSSFWorkbook wb1 = XSSFTestDataSamples.openSampleWorkbook("47813.xlsx"); - assertEquals(3, wb1.getNumberOfSheets()); - assertNotNull(wb1.getCalculationChain()); - - assertEquals("Numbers", wb1.getSheetName(0)); - //the second sheet is of type 'chartsheet' - assertEquals("Chart", wb1.getSheetName(1)); - assertTrue(wb1.getSheetAt(1) instanceof XSSFChartSheet); - assertEquals("SomeJunk", wb1.getSheetName(2)); - - wb1.removeSheetAt(2); - assertEquals(2, wb1.getNumberOfSheets()); - assertNull(wb1.getCalculationChain()); - - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - assertEquals(2, wb2.getNumberOfSheets()); - assertNull(wb2.getCalculationChain()); - - assertEquals("Numbers", wb2.getSheetName(0)); - assertEquals("Chart", wb2.getSheetName(1)); - wb2.close(); - wb1.close(); - } - - /** - * Problems with the count of the number of styles - * coming out wrong - */ - @Test - public void bug49702() throws IOException { - // First try with a new file - XSSFWorkbook wb1 = new XSSFWorkbook(); - - // Should have one style - assertEquals(1, wb1.getNumCellStyles()); - wb1.getCellStyleAt((short)0); - assertNull("Shouldn't be able to get style at 0 that doesn't exist", - wb1.getCellStyleAt((short)1)); - - // Add another one - CellStyle cs = wb1.createCellStyle(); - cs.setDataFormat((short)11); - - // Re-check - assertEquals(2, wb1.getNumCellStyles()); - wb1.getCellStyleAt((short)0); - wb1.getCellStyleAt((short)1); - assertNull("Shouldn't be able to get style at 2 that doesn't exist", - wb1.getCellStyleAt((short)2)); - - // Save and reload - XSSFWorkbook nwb = XSSFTestDataSamples.writeOutAndReadBack(wb1); - assertEquals(2, nwb.getNumCellStyles()); - nwb.getCellStyleAt((short)0); - nwb.getCellStyleAt((short)1); - assertNull("Shouldn't be able to get style at 2 that doesn't exist", - nwb.getCellStyleAt((short)2)); - - // Now with an existing file - XSSFWorkbook wb2 = XSSFTestDataSamples.openSampleWorkbook("sample.xlsx"); - assertEquals(3, wb2.getNumCellStyles()); - wb2.getCellStyleAt((short)0); - wb2.getCellStyleAt((short)1); - wb2.getCellStyleAt((short)2); - assertNull("Shouldn't be able to get style at 3 that doesn't exist", - wb2.getCellStyleAt((short)3)); - - wb2.close(); - wb1.close(); - nwb.close(); - } - - @Test - public void recalcId() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - try { - assertFalse(wb.getForceFormulaRecalculation()); - CTWorkbook ctWorkbook = wb.getCTWorkbook(); - assertFalse(ctWorkbook.isSetCalcPr()); - - wb.setForceFormulaRecalculation(true); // resets the EngineId flag to zero - - CTCalcPr calcPr = ctWorkbook.getCalcPr(); - assertNotNull(calcPr); - assertEquals(0, (int) calcPr.getCalcId()); - - calcPr.setCalcId(100); - assertTrue(wb.getForceFormulaRecalculation()); - - wb.setForceFormulaRecalculation(true); // resets the EngineId flag to zero - assertEquals(0, (int) calcPr.getCalcId()); - assertFalse(wb.getForceFormulaRecalculation()); - - // calcMode="manual" is unset when forceFormulaRecalculation=true - calcPr.setCalcMode(STCalcMode.MANUAL); - wb.setForceFormulaRecalculation(true); - assertEquals(STCalcMode.AUTO, calcPr.getCalcMode()); - } finally { - wb.close(); - } - } - - @Test - public void changeSheetNameWithSharedFormulas() throws IOException { - changeSheetNameWithSharedFormulas("shared_formulas.xlsx"); - } - - @Test - public void columnWidthPOI52233() throws Exception { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFSheet sheet = workbook.createSheet(); - XSSFRow row = sheet.createRow(0); - XSSFCell cell = row.createCell(0); - cell.setCellValue("hello world"); - - sheet = workbook.createSheet(); - sheet.setColumnWidth(4, 5000); - sheet.setColumnWidth(5, 5000); - - sheet.groupColumn((short) 4, (short) 5); - - accessWorkbook(workbook); - - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - try { - workbook.write(stream); - } finally { - stream.close(); - } - - accessWorkbook(workbook); - workbook.close(); - } - - private void accessWorkbook(XSSFWorkbook workbook) { - workbook.getSheetAt(1).setColumnGroupCollapsed(4, true); - workbook.getSheetAt(1).setColumnGroupCollapsed(4, false); - - assertEquals("hello world", workbook.getSheetAt(0).getRow(0).getCell(0).getStringCellValue()); - assertEquals(2048, workbook.getSheetAt(0).getColumnWidth(0)); // <-works - } - - @Test - public void bug48495() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("48495.xlsx"); - - assertSheetOrder(wb, "Sheet1"); - - Sheet sheet = wb.getSheetAt(0); - sheet.shiftRows(2, sheet.getLastRowNum(), 1, true, false); - Row newRow = sheet.getRow(2); - if (newRow == null) newRow = sheet.createRow(2); - newRow.createCell(0).setCellValue(" Another Header"); - wb.cloneSheet(0); - - assertSheetOrder(wb, "Sheet1", "Sheet1 (2)"); - - // FileOutputStream fileOut = new FileOutputStream("/tmp/bug48495.xlsx"); -// try { -// wb.write(fileOut); -// } finally { -// fileOut.close(); -// } - - Workbook read = XSSFTestDataSamples.writeOutAndReadBack(wb); - assertNotNull(read); - assertSheetOrder(read, "Sheet1", "Sheet1 (2)"); - read.close(); - wb.close(); - } - - @Test - public void bug47090a() throws IOException { - Workbook workbook = XSSFTestDataSamples.openSampleWorkbook("47090.xlsx"); - assertSheetOrder(workbook, "Sheet1", "Sheet2"); - workbook.removeSheetAt(0); - assertSheetOrder(workbook, "Sheet2"); - workbook.createSheet(); - assertSheetOrder(workbook, "Sheet2", "Sheet1"); - Workbook read = XSSFTestDataSamples.writeOutAndReadBack(workbook); - assertSheetOrder(read, "Sheet2", "Sheet1"); - read.close(); - workbook.close(); - } - - @Test - public void bug47090b() throws IOException { - Workbook workbook = XSSFTestDataSamples.openSampleWorkbook("47090.xlsx"); - assertSheetOrder(workbook, "Sheet1", "Sheet2"); - workbook.removeSheetAt(1); - assertSheetOrder(workbook, "Sheet1"); - workbook.createSheet(); - assertSheetOrder(workbook, "Sheet1", "Sheet0"); // Sheet0 because it uses "Sheet" + sheets.size() as starting point! - Workbook read = XSSFTestDataSamples.writeOutAndReadBack(workbook); - assertSheetOrder(read, "Sheet1", "Sheet0"); - read.close(); - workbook.close(); - } - - @Test - public void bug47090c() throws IOException { - Workbook workbook = XSSFTestDataSamples.openSampleWorkbook("47090.xlsx"); - assertSheetOrder(workbook, "Sheet1", "Sheet2"); - workbook.removeSheetAt(0); - assertSheetOrder(workbook, "Sheet2"); - workbook.cloneSheet(0); - assertSheetOrder(workbook, "Sheet2", "Sheet2 (2)"); - Workbook read = XSSFTestDataSamples.writeOutAndReadBack(workbook); - assertSheetOrder(read, "Sheet2", "Sheet2 (2)"); - read.close(); - workbook.close(); - } - - @Test - public void bug47090d() throws IOException { - Workbook workbook = XSSFTestDataSamples.openSampleWorkbook("47090.xlsx"); - assertSheetOrder(workbook, "Sheet1", "Sheet2"); - workbook.createSheet(); - assertSheetOrder(workbook, "Sheet1", "Sheet2", "Sheet0"); - workbook.removeSheetAt(0); - assertSheetOrder(workbook, "Sheet2", "Sheet0"); - workbook.createSheet(); - assertSheetOrder(workbook, "Sheet2", "Sheet0", "Sheet1"); - Workbook read = XSSFTestDataSamples.writeOutAndReadBack(workbook); - assertSheetOrder(read, "Sheet2", "Sheet0", "Sheet1"); - read.close(); - workbook.close(); - } - - @Test - public void bug51158() throws IOException { - // create a workbook - final XSSFWorkbook wb1 = new XSSFWorkbook(); - XSSFSheet sheet = wb1.createSheet("Test Sheet"); - XSSFRow row = sheet.createRow(2); - XSSFCell cell = row.createCell(3); - cell.setCellValue("test1"); - - //XSSFCreationHelper helper = workbook.getCreationHelper(); - //cell.setHyperlink(helper.createHyperlink(0)); - - XSSFComment comment = sheet.createDrawingPatriarch().createCellComment(new XSSFClientAnchor()); - assertNotNull(comment); - comment.setString("some comment"); - -// CellStyle cs = workbook.createCellStyle(); -// cs.setShrinkToFit(false); -// row.createCell(0).setCellStyle(cs); - - // write the first excel file - XSSFWorkbook wb2 = XSSFTestDataSamples.writeOutAndReadBack(wb1); - assertNotNull(wb2); - sheet = wb2.getSheetAt(0); - row = sheet.getRow(2); - assertEquals("test1", row.getCell(3).getStringCellValue()); - assertNull(row.getCell(4)); - - // add a new cell to the sheet - cell = row.createCell(4); - cell.setCellValue("test2"); - - // write the second excel file - XSSFWorkbook wb3 = XSSFTestDataSamples.writeOutAndReadBack(wb2); - assertNotNull(wb3); - sheet = wb3.getSheetAt(0); - row = sheet.getRow(2); - - assertEquals("test1", row.getCell(3).getStringCellValue()); - assertEquals("test2", row.getCell(4).getStringCellValue()); - wb3.close(); - wb2.close(); - wb1.close(); - } - - @Test - public void bug51158a() throws IOException { - // create a workbook - final XSSFWorkbook workbook = new XSSFWorkbook(); - try { - workbook.createSheet("Test Sheet"); - - XSSFSheet sheetBack = workbook.getSheetAt(0); - - // committing twice did add the XML twice without clearing the part in between - sheetBack.commit(); - - // ensure that a memory based package part does not have lingering data from previous commit() calls - if(sheetBack.getPackagePart() instanceof MemoryPackagePart) { - ((MemoryPackagePart)sheetBack.getPackagePart()).clear(); - } - - sheetBack.commit(); - - String str = new String(IOUtils.toByteArray(sheetBack.getPackagePart().getInputStream()), "UTF-8"); - - assertEquals(1, countMatches(str, " XSSFWorkbook.iterator was committed in r700472 on 2008-09-30 - * and has been replaced with Iterator XSSFWorkbook.iterator - * - * In order to make code for looping over sheets in workbooks standard, regardless - * of the type of workbook (HSSFWorkbook, XSSFWorkbook, SXSSFWorkbook), the previously - * available Iterator iterator and Iterator sheetIterator - * have been replaced with Iterator {@link #iterator} and - * Iterator {@link #sheetIterator}. This makes iterating over sheets in a workbook - * similar to iterating over rows in a sheet and cells in a row. - * - * Note: this breaks backwards compatibility! Existing codebases will need to - * upgrade their code with either of the following options presented in this test case. - * - */ - @SuppressWarnings("unchecked") - @Test - public void bug58245_XSSFSheetIterator() throws IOException { - final XSSFWorkbook wb = new XSSFWorkbook(); - wb.createSheet(); - - // ===================================================================== - // Case 1: Existing code uses XSSFSheet for-each loop - // ===================================================================== - // Original code (no longer valid) - /* - for (XSSFSheet sh : wb) { - sh.createRow(0); - } - */ - - // Option A: - for (XSSFSheet sh : (Iterable) (Iterable) wb) { - sh.createRow(0); - } - - // Option B (preferred for new code): - for (Sheet sh : wb) { - sh.createRow(0); - } - - // ===================================================================== - // Case 2: Existing code creates an iterator variable - // ===================================================================== - // Original code (no longer valid) - /* - Iterator it = wb.iterator(); - XSSFSheet sh = it.next(); - sh.createRow(0); - */ - - // Option A: - { - Iterator it = (Iterator) (Iterator) wb.iterator(); - XSSFSheet sh = it.next(); - sh.createRow(0); - } - - // Option B: - { - @SuppressWarnings("deprecation") - Iterator it = wb.xssfSheetIterator(); - XSSFSheet sh = it.next(); - sh.createRow(0); - } - - // Option C (preferred for new code): - { - Iterator it = wb.iterator(); - Sheet sh = it.next(); - sh.createRow(0); - } - wb.close(); - } - - @Test - public void testBug56957CloseWorkbook() throws Exception { - File file = TempFile.createTempFile("TestBug56957_", ".xlsx"); - final Date dateExp = LocaleUtil.getLocaleCalendar(2014, 10, 9).getTime(); - - try { - // as the file is written to, we make a copy before actually working on it - FileHelper.copyFile(HSSFTestDataSamples.getSampleFile("56957.xlsx"), file); - - assertTrue(file.exists()); - - // read-only mode works! - Workbook workbook = WorkbookFactory.create(OPCPackage.open(file, PackageAccess.READ)); - Date dateAct = workbook.getSheetAt(0).getRow(0).getCell(0, MissingCellPolicy.CREATE_NULL_AS_BLANK).getDateCellValue(); - assertEquals(dateExp, dateAct); - workbook.close(); - workbook = null; - - workbook = WorkbookFactory.create(OPCPackage.open(file, PackageAccess.READ)); - dateAct = workbook.getSheetAt(0).getRow(0).getCell(0, MissingCellPolicy.CREATE_NULL_AS_BLANK).getDateCellValue(); - assertEquals(dateExp, dateAct); - workbook.close(); - workbook = null; - - // now check read/write mode - workbook = WorkbookFactory.create(OPCPackage.open(file, PackageAccess.READ_WRITE)); - dateAct = workbook.getSheetAt(0).getRow(0).getCell(0, MissingCellPolicy.CREATE_NULL_AS_BLANK).getDateCellValue(); - assertEquals(dateExp, dateAct); - workbook.close(); - workbook = null; - - workbook = WorkbookFactory.create(OPCPackage.open(file, PackageAccess.READ_WRITE)); - dateAct = workbook.getSheetAt(0).getRow(0).getCell(0, MissingCellPolicy.CREATE_NULL_AS_BLANK).getDateCellValue(); - assertEquals(dateExp, dateAct); - workbook.close(); - workbook = null; - } finally { - assertTrue(file.exists()); - assertTrue(file.delete()); - } - } - - @Test - public void closeDoesNotModifyWorkbook() throws IOException, InvalidFormatException { - final String filename = "SampleSS.xlsx"; - final File file = POIDataSamples.getSpreadSheetInstance().getFile(filename); - Workbook wb; - - // Some tests commented out because close() modifies the file - // See bug 58779 - - // String - //wb = new XSSFWorkbook(file.getPath()); - //assertCloseDoesNotModifyFile(filename, wb); - - // File - //wb = new XSSFWorkbook(file); - //assertCloseDoesNotModifyFile(filename, wb); - - // InputStream - wb = new XSSFWorkbook(new FileInputStream(file)); - assertCloseDoesNotModifyFile(filename, wb); - - // OPCPackage - //wb = new XSSFWorkbook(OPCPackage.open(file)); - //assertCloseDoesNotModifyFile(filename, wb); - } - - @Test - public void testCloseBeforeWrite() throws IOException { - Workbook wb = new XSSFWorkbook(); - wb.createSheet("somesheet"); - - // test what happens if we close the Workbook before we write it out - wb.close(); - - try { - XSSFTestDataSamples.writeOutAndReadBack(wb); - fail("Expecting IOException here"); - } catch (RuntimeException e) { - // expected here - assertTrue("Had: " + e.getCause(), e.getCause() instanceof IOException); - } - } - - /** - * See bug #57840 test data tables - */ - @Test - public void getTable() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("WithTable.xlsx"); - XSSFTable table1 = wb.getTable("Tabella1"); - assertNotNull("Tabella1 was not found in workbook", table1); - assertEquals("Table name", "Tabella1", table1.getName()); - assertEquals("Sheet name", "Foglio1", table1.getSheetName()); - - // Table lookup should be case-insensitive - assertSame("Case insensitive table name lookup", table1, wb.getTable("TABELLA1")); - - // If workbook does not contain any data tables matching the provided name, getTable should return null - assertNull("Null table name should not throw NPE", wb.getTable(null)); - assertNull("Should not be able to find non-existent table", wb.getTable("Foglio1")); - - // If a table is added after getTable is called it should still be reachable by XSSFWorkbook.getTable - // This test makes sure that if any caching is done that getTable never uses a stale cache - XSSFTable table2 = wb.getSheet("Foglio2").createTable(); - table2.setName("Table2"); - assertSame("Did not find Table2", table2, wb.getTable("Table2")); - - // If table name is modified after getTable is called, the table can only be found by its new name - // This test makes sure that if any caching is done that getTable never uses a stale cache - table1.setName("Table1"); - assertSame("Did not find Tabella1 renamed to Table1", table1, wb.getTable("TABLE1")); - - wb.close(); - } - - @Test - public void testRemoveSheet() throws IOException { - // Test removing a sheet maintains the named ranges correctly - XSSFWorkbook wb = new XSSFWorkbook(); - wb.createSheet("Sheet1"); - wb.createSheet("Sheet2"); - - XSSFName sheet1Name = wb.createName(); - sheet1Name.setNameName("name1"); - sheet1Name.setSheetIndex(0); - sheet1Name.setRefersToFormula("Sheet1!$A$1"); - - XSSFName sheet2Name = wb.createName(); - sheet2Name.setNameName("name1"); - sheet2Name.setSheetIndex(1); - sheet2Name.setRefersToFormula("Sheet2!$A$1"); - - assertTrue(wb.getAllNames().contains(sheet1Name)); - assertTrue(wb.getAllNames().contains(sheet2Name)); - - assertEquals(2, wb.getNames("name1").size()); - assertEquals(sheet1Name, wb.getNames("name1").get(0)); - assertEquals(sheet2Name, wb.getNames("name1").get(1)); - - // Remove sheet1, we should only have sheet2Name now - wb.removeSheetAt(0); - - assertFalse(wb.getAllNames().contains(sheet1Name)); - assertTrue(wb.getAllNames().contains(sheet2Name)); - assertEquals(1, wb.getNames("name1").size()); - assertEquals(sheet2Name, wb.getNames("name1").get(0)); - - // Check by index as well for sanity - assertEquals(1, wb.getNumberOfNames()); - assertEquals(0, wb.getNameIndex("name1")); - assertEquals(sheet2Name, wb.getNameAt(0)); - - wb.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFCategoryAxis.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFCategoryAxis.java deleted file mode 100644 index 64ce92b57..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFCategoryAxis.java +++ /dev/null @@ -1,40 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.charts; - -import junit.framework.TestCase; - -import org.apache.poi.ss.usermodel.charts.*; -import org.apache.poi.xssf.usermodel.*; - -public final class TestXSSFCategoryAxis extends TestCase { - - public void testAccessMethods() throws Exception { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 1, 10, 30); - XSSFChart chart = drawing.createChart(anchor); - XSSFCategoryAxis axis = chart.getChartAxisFactory().createCategoryAxis(AxisPosition.BOTTOM); - - axis.setCrosses(AxisCrosses.AUTO_ZERO); - assertEquals(axis.getCrosses(), AxisCrosses.AUTO_ZERO); - - assertEquals(chart.getAxis().size(), 1); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFChartAxis.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFChartAxis.java deleted file mode 100644 index 41e02b12f..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFChartAxis.java +++ /dev/null @@ -1,136 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.charts; - -import java.util.List; - -import junit.framework.TestCase; - -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.usermodel.charts.*; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.usermodel.*; - -public final class TestXSSFChartAxis extends TestCase { - - private static final double EPSILON = 1E-7; - private final XSSFChartAxis axis; - - public TestXSSFChartAxis() { - super(); - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 1, 10, 30); - XSSFChart chart = drawing.createChart(anchor); - axis = chart.getChartAxisFactory().createValueAxis(AxisPosition.BOTTOM); - } - - public void testLogBaseIllegalArgument() throws Exception { - IllegalArgumentException iae = null; - try { - axis.setLogBase(0.0); - } catch (IllegalArgumentException e) { - iae = e; - } - assertNotNull(iae); - - iae = null; - try { - axis.setLogBase(30000.0); - } catch (IllegalArgumentException e) { - iae = e; - } - assertNotNull(iae); - } - - public void testLogBaseLegalArgument() throws Exception { - axis.setLogBase(Math.E); - assertTrue(Math.abs(axis.getLogBase() - Math.E) < EPSILON); - } - - public void testNumberFormat() throws Exception { - final String numberFormat = "General"; - axis.setNumberFormat(numberFormat); - assertEquals(numberFormat, axis.getNumberFormat()); - } - - public void testMaxAndMinAccessMethods() { - final double newValue = 10.0; - - axis.setMinimum(newValue); - assertTrue(Math.abs(axis.getMinimum() - newValue) < EPSILON); - - axis.setMaximum(newValue); - assertTrue(Math.abs(axis.getMaximum() - newValue) < EPSILON); - } - - public void testVisibleAccessMethods() { - axis.setVisible(true); - assertTrue(axis.isVisible()); - - axis.setVisible(false); - assertFalse(axis.isVisible()); - } - - public void testMajorTickMarkAccessMethods() { - axis.setMajorTickMark(AxisTickMark.NONE); - assertEquals(AxisTickMark.NONE, axis.getMajorTickMark()); - - axis.setMajorTickMark(AxisTickMark.IN); - assertEquals(AxisTickMark.IN, axis.getMajorTickMark()); - - axis.setMajorTickMark(AxisTickMark.OUT); - assertEquals(AxisTickMark.OUT, axis.getMajorTickMark()); - - axis.setMajorTickMark(AxisTickMark.CROSS); - assertEquals(AxisTickMark.CROSS, axis.getMajorTickMark()); - } - - public void testMinorTickMarkAccessMethods() { - axis.setMinorTickMark(AxisTickMark.NONE); - assertEquals(AxisTickMark.NONE, axis.getMinorTickMark()); - - axis.setMinorTickMark(AxisTickMark.IN); - assertEquals(AxisTickMark.IN, axis.getMinorTickMark()); - - axis.setMinorTickMark(AxisTickMark.OUT); - assertEquals(AxisTickMark.OUT, axis.getMinorTickMark()); - - axis.setMinorTickMark(AxisTickMark.CROSS); - assertEquals(AxisTickMark.CROSS, axis.getMinorTickMark()); - } - - public void testGetChartAxisBug57362() { - //Load existing excel with some chart on it having primary and secondary axis. - final Workbook workbook = XSSFTestDataSamples.openSampleWorkbook("57362.xlsx"); - final Sheet sh = workbook.getSheetAt(0); - final XSSFSheet xsh = (XSSFSheet) sh; - final XSSFDrawing drawing = xsh.createDrawingPatriarch(); - final XSSFChart chart = drawing.getCharts().get(0); - - final List axisList = chart.getAxis(); - - assertEquals(4, axisList.size()); - assertNotNull(axisList.get(0)); - assertNotNull(axisList.get(1)); - assertNotNull(axisList.get(2)); - assertNotNull(axisList.get(3)); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFChartLegend.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFChartLegend.java deleted file mode 100644 index 524b421da..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFChartLegend.java +++ /dev/null @@ -1,91 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.charts; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; - -import org.apache.poi.ss.usermodel.Chart; -import org.apache.poi.ss.usermodel.ClientAnchor; -import org.apache.poi.ss.usermodel.Drawing; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.usermodel.charts.ChartLegend; -import org.apache.poi.ss.usermodel.charts.LegendPosition; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Test; - -/** - * Tests ChartLegend - */ -public final class TestXSSFChartLegend { - @Test - public void testLegendPositionAccessMethods() throws IOException { - Workbook wb = new XSSFWorkbook(); - Sheet sheet = wb.createSheet(); - Drawing drawing = sheet.createDrawingPatriarch(); - ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 1, 10, 30); - Chart chart = drawing.createChart(anchor); - ChartLegend legend = chart.getOrCreateLegend(); - - legend.setPosition(LegendPosition.TOP_RIGHT); - assertEquals(LegendPosition.TOP_RIGHT, legend.getPosition()); - - wb.close(); - } - - @Test - public void test_setOverlay_defaultChartLegend_expectOverlayInitialValueSetToFalse() throws IOException { - // Arrange - Workbook wb = new XSSFWorkbook(); - Sheet sheet = wb.createSheet(); - Drawing drawing = sheet.createDrawingPatriarch(); - ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 1, 10, 30); - Chart chart = drawing.createChart(anchor); - ChartLegend legend = chart.getOrCreateLegend(); - - // Act - - // Assert - assertFalse(legend.isOverlay()); - - wb.close(); - } - - @Test - public void test_setOverlay_chartLegendSetToTrue_expectOverlayInitialValueSetToTrue() throws IOException { - // Arrange - Workbook wb = new XSSFWorkbook(); - Sheet sheet = wb.createSheet(); - Drawing drawing = sheet.createDrawingPatriarch(); - ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 1, 10, 30); - Chart chart = drawing.createChart(anchor); - ChartLegend legend = chart.getOrCreateLegend(); - - // Act - legend.setOverlay(true); - - // Assert - assertTrue(legend.isOverlay()); - - wb.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFChartTitle.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFChartTitle.java deleted file mode 100644 index 7282aa0f4..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFChartTitle.java +++ /dev/null @@ -1,184 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.charts; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - -import java.io.IOException; -import java.util.List; - -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Chart; -import org.apache.poi.ss.usermodel.ClientAnchor; -import org.apache.poi.ss.usermodel.Drawing; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.usermodel.charts.AxisCrosses; -import org.apache.poi.ss.usermodel.charts.AxisPosition; -import org.apache.poi.ss.usermodel.charts.ChartAxis; -import org.apache.poi.ss.usermodel.charts.ChartDataSource; -import org.apache.poi.ss.usermodel.charts.ChartLegend; -import org.apache.poi.ss.usermodel.charts.DataSources; -import org.apache.poi.ss.usermodel.charts.LegendPosition; -import org.apache.poi.ss.usermodel.charts.LineChartData; -import org.apache.poi.ss.usermodel.charts.ValueAxis; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.usermodel.XSSFChart; -import org.apache.poi.xssf.usermodel.XSSFDrawing; -import org.apache.poi.xssf.usermodel.XSSFRichTextString; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Test; - -/** - * Test get/set chart title. - */ -public class TestXSSFChartTitle { - private Workbook createWorkbookWithChart() { - Workbook wb = new XSSFWorkbook(); - Sheet sheet = wb.createSheet("linechart"); - final int NUM_OF_ROWS = 3; - final int NUM_OF_COLUMNS = 10; - - // Create a row and put some cells in it. Rows are 0 based. - Row row; - Cell cell; - for (int rowIndex = 0; rowIndex < NUM_OF_ROWS; rowIndex++) { - row = sheet.createRow((short) rowIndex); - for (int colIndex = 0; colIndex < NUM_OF_COLUMNS; colIndex++) { - cell = row.createCell((short) colIndex); - cell.setCellValue(colIndex * (rowIndex + 1)); - } - } - - Drawing drawing = sheet.createDrawingPatriarch(); - ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 10, 15); - - Chart chart = drawing.createChart(anchor); - ChartLegend legend = chart.getOrCreateLegend(); - legend.setPosition(LegendPosition.TOP_RIGHT); - - LineChartData data = chart.getChartDataFactory().createLineChartData(); - - // Use a category axis for the bottom axis. - ChartAxis bottomAxis = chart.getChartAxisFactory().createCategoryAxis(AxisPosition.BOTTOM); - ValueAxis leftAxis = chart.getChartAxisFactory().createValueAxis(AxisPosition.LEFT); - leftAxis.setCrosses(AxisCrosses.AUTO_ZERO); - - ChartDataSource xs = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(0, 0, 0, NUM_OF_COLUMNS - 1)); - ChartDataSource ys1 = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(1, 1, 0, NUM_OF_COLUMNS - 1)); - ChartDataSource ys2 = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(2, 2, 0, NUM_OF_COLUMNS - 1)); - - data.addSeries(xs, ys1); - data.addSeries(xs, ys2); - - chart.plot(data, bottomAxis, leftAxis); - - return wb; - } - - /** - * Gets the first chart from the named sheet in the workbook. - */ - private XSSFChart getChartFromWorkbook(Workbook wb, String sheetName) { - Sheet sheet = wb.getSheet(sheetName); - if (sheet instanceof XSSFSheet) { - XSSFSheet xsheet = (XSSFSheet) sheet; - XSSFDrawing drawing = xsheet.getDrawingPatriarch(); - if (drawing != null) { - List charts = drawing.getCharts(); - if (charts != null && charts.size() > 0) { - return charts.get(0); - } - } - } - return null; - } - - @Test - public void testNewChart() throws IOException { - Workbook wb = createWorkbookWithChart(); - XSSFChart chart = getChartFromWorkbook(wb, "linechart"); - assertNotNull(chart); - assertNull(chart.getTitleText()); - final String myTitle = "My chart title"; - chart.setTitleText(myTitle); - XSSFRichTextString queryTitle = chart.getTitleText(); - assertNotNull(queryTitle); - assertEquals(myTitle, queryTitle.toString()); - - final String myTitleFormula = "1 & \" and \" & 2"; - chart.setTitleFormula(myTitleFormula); - // setting formula should unset text, but since there is a formula, returns an empty string - assertEquals("", chart.getTitleText().toString()); - String titleFormula = chart.getTitleFormula(); - assertNotNull(titleFormula); - assertEquals(myTitleFormula, titleFormula); - wb.close(); - } - - @Test - public void testExistingChartWithTitle() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("chartTitle_withTitle.xlsx"); - XSSFChart chart = getChartFromWorkbook(wb, "Sheet1"); - assertNotNull(chart); - XSSFRichTextString originalTitle = chart.getTitleText(); - assertNotNull(originalTitle); - final String myTitle = "My chart title"; - assertFalse(myTitle.equals(originalTitle.toString())); - chart.setTitleText(myTitle); - XSSFRichTextString queryTitle = chart.getTitleText(); - assertNotNull(queryTitle); - assertEquals(myTitle, queryTitle.toString()); - wb.close(); - } - - @Test - public void testExistingChartNoTitle() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("chartTitle_noTitle.xlsx"); - XSSFChart chart = getChartFromWorkbook(wb, "Sheet1"); - assertNotNull(chart); - assertNull(chart.getTitleText()); - final String myTitle = "My chart title"; - chart.setTitleText(myTitle); - XSSFRichTextString queryTitle = chart.getTitleText(); - assertNotNull(queryTitle); - assertEquals(myTitle, queryTitle.toString()); - wb.close(); - } - - @Test - public void testExistingChartWithFormulaTitle() throws IOException { - Workbook wb = XSSFTestDataSamples.openSampleWorkbook("chartTitle_withTitleFormula.xlsx"); - XSSFChart chart = getChartFromWorkbook(wb, "Sheet1"); - assertNotNull(chart); - XSSFRichTextString originalTitle = chart.getTitleText(); - assertNotNull(originalTitle); - assertEquals("", originalTitle.toString()); - String formula = chart.getTitleFormula(); - assertNotNull(formula); - assertEquals("Sheet1!$E$1", formula); - wb.close(); - } - -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFLineChartData.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFLineChartData.java deleted file mode 100644 index e5ee56b50..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFLineChartData.java +++ /dev/null @@ -1,76 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xssf.usermodel.charts; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; - -import org.apache.poi.ss.usermodel.Chart; -import org.apache.poi.ss.usermodel.ClientAnchor; -import org.apache.poi.ss.usermodel.Drawing; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.usermodel.charts.AxisPosition; -import org.apache.poi.ss.usermodel.charts.ChartAxis; -import org.apache.poi.ss.usermodel.charts.ChartDataSource; -import org.apache.poi.ss.usermodel.charts.DataSources; -import org.apache.poi.ss.usermodel.charts.LineChartData; -import org.apache.poi.ss.usermodel.charts.LineChartSeries; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.SheetBuilder; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Test; - -/** - * Tests for XSSF Line Charts - */ -public class TestXSSFLineChartData { - - private static final Object[][] plotData = { - {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J"}, - {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} - }; - - @Test - public void testOneSeriePlot() throws IOException { - Workbook wb = new XSSFWorkbook(); - Sheet sheet = new SheetBuilder(wb, plotData).build(); - Drawing drawing = sheet.createDrawingPatriarch(); - ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 1, 10, 30); - Chart chart = drawing.createChart(anchor); - - ChartAxis bottomAxis = chart.getChartAxisFactory().createCategoryAxis(AxisPosition.BOTTOM); - ChartAxis leftAxis = chart.getChartAxisFactory().createValueAxis(AxisPosition.LEFT); - - LineChartData lineChartData = - chart.getChartDataFactory().createLineChartData(); - - ChartDataSource xs = DataSources.fromStringCellRange(sheet, CellRangeAddress.valueOf("A1:J1")); - ChartDataSource ys = DataSources.fromNumericCellRange(sheet, CellRangeAddress.valueOf("A2:J2")); - LineChartSeries series = lineChartData.addSeries(xs, ys); - - assertNotNull(series); - assertEquals(1, lineChartData.getSeries().size()); - assertTrue(lineChartData.getSeries().contains(series)); - - chart.plot(lineChartData, bottomAxis, leftAxis); - wb.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFManualLayout.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFManualLayout.java deleted file mode 100644 index 73df55914..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFManualLayout.java +++ /dev/null @@ -1,120 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.charts; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; - -import org.apache.poi.ss.usermodel.Chart; -import org.apache.poi.ss.usermodel.ClientAnchor; -import org.apache.poi.ss.usermodel.Drawing; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.usermodel.charts.ChartLegend; -import org.apache.poi.ss.usermodel.charts.LayoutMode; -import org.apache.poi.ss.usermodel.charts.LayoutTarget; -import org.apache.poi.ss.usermodel.charts.ManualLayout; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public final class TestXSSFManualLayout { - - private Workbook wb; - private ManualLayout layout; - - @Before - public void createEmptyLayout() { - wb = new XSSFWorkbook(); - Sheet sheet = wb.createSheet(); - Drawing drawing = sheet.createDrawingPatriarch(); - ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 1, 10, 30); - Chart chart = drawing.createChart(anchor); - ChartLegend legend = chart.getOrCreateLegend(); - layout = legend.getManualLayout(); - } - - @After - public void closeWB() throws IOException { - wb.close(); - } - - /* - * Accessor methods are not trivial. They use lazy underlying bean - * initialization so there can be some errors (NPE, for example). - */ - @Test - public void testAccessorMethods() { - final double newRatio = 1.1; - final double newCoordinate = 0.3; - final LayoutMode nonDefaultMode = LayoutMode.FACTOR; - final LayoutTarget nonDefaultTarget = LayoutTarget.OUTER; - - layout.setWidthRatio(newRatio); - assertTrue(layout.getWidthRatio() == newRatio); - - layout.setHeightRatio(newRatio); - assertTrue(layout.getHeightRatio() == newRatio); - - layout.setX(newCoordinate); - assertTrue(layout.getX() == newCoordinate); - - layout.setY(newCoordinate); - assertTrue(layout.getY() == newCoordinate); - - layout.setXMode(nonDefaultMode); - assertTrue(layout.getXMode() == nonDefaultMode); - - layout.setYMode(nonDefaultMode); - assertTrue(layout.getYMode() == nonDefaultMode); - - layout.setWidthMode(nonDefaultMode); - assertTrue(layout.getWidthMode() == nonDefaultMode); - - layout.setHeightMode(nonDefaultMode); - assertTrue(layout.getHeightMode() == nonDefaultMode); - - layout.setTarget(nonDefaultTarget); - assertTrue(layout.getTarget() == nonDefaultTarget); - - } - - /* - * Layout must have reasonable default values and must not throw - * any exceptions. - */ - @Test - public void testDefaultValues() { - assertNotNull(layout.getTarget()); - assertNotNull(layout.getXMode()); - assertNotNull(layout.getYMode()); - assertNotNull(layout.getHeightMode()); - assertNotNull(layout.getWidthMode()); - /* - * According to interface, 0.0 should be returned for - * uninitialized double properties. - */ - assertTrue(layout.getX() == 0.0); - assertTrue(layout.getY() == 0.0); - assertTrue(layout.getWidthRatio() == 0.0); - assertTrue(layout.getHeightRatio() == 0.0); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFScatterChartData.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFScatterChartData.java deleted file mode 100644 index 79dc71c8d..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFScatterChartData.java +++ /dev/null @@ -1,77 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - ==================================================================== */ - -package org.apache.poi.xssf.usermodel.charts; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; - -import org.apache.poi.ss.usermodel.Chart; -import org.apache.poi.ss.usermodel.ClientAnchor; -import org.apache.poi.ss.usermodel.Drawing; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.usermodel.charts.AxisPosition; -import org.apache.poi.ss.usermodel.charts.ChartAxis; -import org.apache.poi.ss.usermodel.charts.ChartDataSource; -import org.apache.poi.ss.usermodel.charts.DataSources; -import org.apache.poi.ss.usermodel.charts.ScatterChartData; -import org.apache.poi.ss.usermodel.charts.ScatterChartSeries; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.SheetBuilder; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Test; - -/** - * Tests for XSSFScatterChartData. - */ -public final class TestXSSFScatterChartData { - - private static final Object[][] plotData = { - {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J"}, - { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10} - }; - - @Test - public void testOneSeriePlot() throws IOException { - Workbook wb = new XSSFWorkbook(); - Sheet sheet = new SheetBuilder(wb, plotData).build(); - Drawing drawing = sheet.createDrawingPatriarch(); - ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 1, 10, 30); - Chart chart = drawing.createChart(anchor); - - ChartAxis bottomAxis = chart.getChartAxisFactory().createValueAxis(AxisPosition.BOTTOM); - ChartAxis leftAxis = chart.getChartAxisFactory().createValueAxis(AxisPosition.LEFT); - - ScatterChartData scatterChartData = - chart.getChartDataFactory().createScatterChartData(); - - ChartDataSource xs = DataSources.fromStringCellRange(sheet, CellRangeAddress.valueOf("A1:J1")); - ChartDataSource ys = DataSources.fromNumericCellRange(sheet, CellRangeAddress.valueOf("A2:J2")); - ScatterChartSeries series = scatterChartData.addSerie(xs, ys); - - assertNotNull(series); - assertEquals(1, scatterChartData.getSeries().size()); - assertTrue(scatterChartData.getSeries().contains(series)); - - chart.plot(scatterChartData, bottomAxis, leftAxis); - wb.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFValueAxis.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFValueAxis.java deleted file mode 100644 index db8ded370..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/charts/TestXSSFValueAxis.java +++ /dev/null @@ -1,43 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.charts; - -import junit.framework.TestCase; - -import org.apache.poi.ss.usermodel.charts.*; -import org.apache.poi.xssf.usermodel.*; - -public final class TestXSSFValueAxis extends TestCase { - - public void testAccessMethods() throws Exception { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFSheet sheet = wb.createSheet(); - XSSFDrawing drawing = sheet.createDrawingPatriarch(); - XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 1, 1, 10, 30); - XSSFChart chart = drawing.createChart(anchor); - XSSFValueAxis axis = chart.getChartAxisFactory().createValueAxis(AxisPosition.BOTTOM); - - axis.setCrossBetween(AxisCrossBetween.MIDPOINT_CATEGORY); - assertEquals(axis.getCrossBetween(), AxisCrossBetween.MIDPOINT_CATEGORY); - - axis.setCrosses(AxisCrosses.AUTO_ZERO); - assertEquals(axis.getCrosses(), AxisCrosses.AUTO_ZERO); - - assertEquals(chart.getAxis().size(), 1); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/extensions/TestXSSFBorder.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/extensions/TestXSSFBorder.java deleted file mode 100644 index e7233c227..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/extensions/TestXSSFBorder.java +++ /dev/null @@ -1,54 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.extensions; - -import junit.framework.TestCase; - -import org.apache.poi.ss.usermodel.BorderStyle; -import org.apache.poi.xssf.usermodel.extensions.XSSFCellBorder.BorderSide; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTBorder; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTBorderPr; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTStylesheet; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STBorderStyle; - - -public class TestXSSFBorder extends TestCase { - - public void testGetBorderStyle() { - CTStylesheet stylesheet = CTStylesheet.Factory.newInstance(); - CTBorder border = stylesheet.addNewBorders().addNewBorder(); - CTBorderPr top = border.addNewTop(); - CTBorderPr right = border.addNewRight(); - CTBorderPr bottom = border.addNewBottom(); - - top.setStyle(STBorderStyle.DASH_DOT); - right.setStyle(STBorderStyle.NONE); - bottom.setStyle(STBorderStyle.THIN); - - XSSFCellBorder cellBorderStyle = new XSSFCellBorder(border); - assertEquals("DASH_DOT", cellBorderStyle.getBorderStyle(BorderSide.TOP).toString()); - - assertEquals("NONE", cellBorderStyle.getBorderStyle(BorderSide.RIGHT).toString()); - assertEquals(BorderStyle.NONE.ordinal(), cellBorderStyle.getBorderStyle(BorderSide.RIGHT).ordinal()); - - assertEquals("THIN", cellBorderStyle.getBorderStyle(BorderSide.BOTTOM).toString()); - - assertEquals(BorderStyle.THIN.ordinal(), cellBorderStyle.getBorderStyle(BorderSide.BOTTOM).ordinal()); - } - -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/extensions/TestXSSFCellFill.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/extensions/TestXSSFCellFill.java deleted file mode 100644 index 832d6bfb2..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/extensions/TestXSSFCellFill.java +++ /dev/null @@ -1,101 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.extensions; - - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import java.io.IOException; - -import org.apache.poi.ss.usermodel.FillPatternType; -import org.apache.poi.xssf.XSSFTestDataSamples; -import org.apache.poi.xssf.usermodel.XSSFCell; -import org.apache.poi.xssf.usermodel.XSSFColor; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.Test; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTColor; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTFill; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPatternFill; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.STPatternType; - - -public class TestXSSFCellFill { - - @Test - public void testGetFillBackgroundColor() { - CTFill ctFill = CTFill.Factory.newInstance(); - XSSFCellFill cellFill = new XSSFCellFill(ctFill); - CTPatternFill ctPatternFill = ctFill.addNewPatternFill(); - CTColor bgColor = ctPatternFill.addNewBgColor(); - assertNotNull(cellFill.getFillBackgroundColor()); - bgColor.setIndexed(2); - assertEquals(2, cellFill.getFillBackgroundColor().getIndexed()); - } - - @Test - public void testGetFillForegroundColor() { - CTFill ctFill = CTFill.Factory.newInstance(); - XSSFCellFill cellFill = new XSSFCellFill(ctFill); - CTPatternFill ctPatternFill = ctFill.addNewPatternFill(); - CTColor fgColor = ctPatternFill.addNewFgColor(); - assertNotNull(cellFill.getFillForegroundColor()); - fgColor.setIndexed(8); - assertEquals(8, cellFill.getFillForegroundColor().getIndexed()); - } - - @Test - public void testGetSetPatternType() { - CTFill ctFill = CTFill.Factory.newInstance(); - XSSFCellFill cellFill = new XSSFCellFill(ctFill); - CTPatternFill ctPatternFill = ctFill.addNewPatternFill(); - ctPatternFill.setPatternType(STPatternType.SOLID); - assertEquals(FillPatternType.SOLID_FOREGROUND.ordinal(), cellFill.getPatternType().intValue()-1); - } - - @Test - public void testGetNotModifies() { - CTFill ctFill = CTFill.Factory.newInstance(); - XSSFCellFill cellFill = new XSSFCellFill(ctFill); - CTPatternFill ctPatternFill = ctFill.addNewPatternFill(); - ctPatternFill.setPatternType(STPatternType.DARK_DOWN); - assertEquals(8, cellFill.getPatternType().intValue()); - } - - @Test - public void testColorFromTheme() throws IOException { - XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("styles.xlsx"); - XSSFCell cellWithThemeColor = wb.getSheetAt(0).getRow(10).getCell(0); - //color RGB will be extracted from theme - XSSFColor foregroundColor = cellWithThemeColor.getCellStyle().getFillForegroundXSSFColor(); - byte[] rgb = foregroundColor.getRGB(); - byte[] rgbWithTint = foregroundColor.getRGBWithTint(); - // Dk2 - assertEquals(rgb[0],31); - assertEquals(rgb[1],73); - assertEquals(rgb[2],125); - // Dk2, lighter 40% (tint is about 0.39998) - // 31 * (1.0 - 0.39998) + (255 - 255 * (1.0 - 0.39998)) = 120.59552 => 120 (byte) - // 73 * (1.0 - 0.39998) + (255 - 255 * (1.0 - 0.39998)) = 145.79636 => -111 (byte) - // 125 * (1.0 - 0.39998) + (255 - 255 * (1.0 - 0.39998)) = 176.99740 => -80 (byte) - assertEquals(rgbWithTint[0],120); - assertEquals(rgbWithTint[1],-111); - assertEquals(rgbWithTint[2],-80); - wb.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/extensions/TestXSSFSheetComments.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/extensions/TestXSSFSheetComments.java deleted file mode 100644 index b58078f06..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/extensions/TestXSSFSheetComments.java +++ /dev/null @@ -1,26 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.extensions; - -import junit.framework.TestCase; - -public class TestXSSFSheetComments extends TestCase { - // So eclipse doesn't moan - public void testTODO() { - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/helpers/TestColumnHelper.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/helpers/TestColumnHelper.java deleted file mode 100644 index 34876e8ad..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/helpers/TestColumnHelper.java +++ /dev/null @@ -1,400 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.helpers; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import org.junit.Test; - -import org.apache.poi.xssf.model.StylesTable; -import org.apache.poi.xssf.usermodel.XSSFCellStyle; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCol; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCols; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTXf; - -/** - * Tests for {@link ColumnHelper} - * - */ -public final class TestColumnHelper { - - @Test - public void testCleanColumns() { - CTWorksheet worksheet = CTWorksheet.Factory.newInstance(); - - CTCols cols1 = worksheet.addNewCols(); - CTCol col1 = cols1.addNewCol(); - col1.setMin(1); - col1.setMax(1); - col1.setWidth(88); - col1.setHidden(true); - CTCol col2 = cols1.addNewCol(); - col2.setMin(2); - col2.setMax(3); - CTCols cols2 = worksheet.addNewCols(); - CTCol col4 = cols2.addNewCol(); - col4.setMin(13); - col4.setMax(16384); - - // Test cleaning cols - assertEquals(2, worksheet.sizeOfColsArray()); - int count = countColumns(worksheet); - assertEquals(16375, count); - // Clean columns and test a clean worksheet - ColumnHelper helper = new ColumnHelper(worksheet); - assertEquals(1, worksheet.sizeOfColsArray()); - count = countColumns(worksheet); - assertEquals(16375, count); - // Remember - POI column 0 == OOXML column 1 - assertEquals(88.0, helper.getColumn(0, false).getWidth(), 0.0); - assertTrue(helper.getColumn(0, false).getHidden()); - assertEquals(0.0, helper.getColumn(1, false).getWidth(), 0.0); - assertFalse(helper.getColumn(1, false).getHidden()); - } - - @Test - public void testSortColumns() { - CTCols cols1 = CTCols.Factory.newInstance(); - CTCol col1 = cols1.addNewCol(); - col1.setMin(1); - col1.setMax(1); - col1.setWidth(88); - col1.setHidden(true); - CTCol col2 = cols1.addNewCol(); - col2.setMin(2); - col2.setMax(3); - CTCol col3 = cols1.addNewCol(); - col3.setMin(13); - col3.setMax(16750); - assertEquals(3, cols1.sizeOfColArray()); - CTCol col4 = cols1.addNewCol(); - col4.setMin(8); - col4.setMax(11); - assertEquals(4, cols1.sizeOfColArray()); - CTCol col5 = cols1.addNewCol(); - col5.setMin(4); - col5.setMax(5); - assertEquals(5, cols1.sizeOfColArray()); - CTCol col6 = cols1.addNewCol(); - col6.setMin(8); - col6.setMax(9); - col6.setHidden(true); - CTCol col7 = cols1.addNewCol(); - col7.setMin(6); - col7.setMax(8); - col7.setWidth(17.0); - CTCol col8 = cols1.addNewCol(); - col8.setMin(25); - col8.setMax(27); - CTCol col9 = cols1.addNewCol(); - col9.setMin(20); - col9.setMax(30); - assertEquals(9, cols1.sizeOfColArray()); - assertEquals(20, cols1.getColArray(8).getMin()); - assertEquals(30, cols1.getColArray(8).getMax()); - ColumnHelper.sortColumns(cols1); - assertEquals(9, cols1.sizeOfColArray()); - assertEquals(25, cols1.getColArray(8).getMin()); - assertEquals(27, cols1.getColArray(8).getMax()); - } - - @Test - public void testCloneCol() { - CTWorksheet worksheet = CTWorksheet.Factory.newInstance(); - ColumnHelper helper = new ColumnHelper(worksheet); - - CTCols cols = CTCols.Factory.newInstance(); - CTCol col = CTCol.Factory.newInstance(); - col.setMin(2); - col.setMax(8); - col.setHidden(true); - col.setWidth(13.4); - CTCol newCol = helper.cloneCol(cols, col); - assertEquals(2, newCol.getMin()); - assertEquals(8, newCol.getMax()); - assertTrue(newCol.getHidden()); - assertEquals(13.4, newCol.getWidth(), 0.0); - } - - @Test - public void testAddCleanColIntoCols() { - CTWorksheet worksheet = CTWorksheet.Factory.newInstance(); - ColumnHelper helper = new ColumnHelper(worksheet); - - CTCols cols1 = CTCols.Factory.newInstance(); - CTCol col1 = cols1.addNewCol(); - col1.setMin(1); - col1.setMax(1); - col1.setWidth(88); - col1.setHidden(true); - CTCol col2 = cols1.addNewCol(); - col2.setMin(2); - col2.setMax(3); - CTCol col3 = cols1.addNewCol(); - col3.setMin(13); - col3.setMax(16750); - assertEquals(3, cols1.sizeOfColArray()); - CTCol col4 = cols1.addNewCol(); - col4.setMin(8); - col4.setMax(9); - assertEquals(4, cols1.sizeOfColArray()); - - // No overlap - helper.addCleanColIntoCols(cols1, createCol(4, 5)); - assertEquals(5, cols1.sizeOfColArray()); - - // Overlaps with 8 - 9 (overlap and after replacements required) - CTCol col6 = createCol(8, 11); - col6.setHidden(true); - helper.addCleanColIntoCols(cols1, col6); - assertEquals(6, cols1.sizeOfColArray()); - - // Overlaps with 8 - 9 (before and overlap replacements required) - CTCol col7 = createCol(6, 8); - col7.setWidth(17.0); - helper.addCleanColIntoCols(cols1, col7); - assertEquals(8, cols1.sizeOfColArray()); - - // Overlaps with 13 - 16750 (before, overlap and after replacements required) - helper.addCleanColIntoCols(cols1, createCol(20, 30)); - assertEquals(10, cols1.sizeOfColArray()); - - // Overlaps with 20 - 30 (before, overlap and after replacements required) - helper.addCleanColIntoCols(cols1, createCol(25, 27)); - - // TODO - assert something interesting - assertEquals(12, cols1.sizeOfColArray()); - assertEquals(1, cols1.getColArray(0).getMin()); - assertEquals(16750, cols1.getColArray(11).getMax()); - } - - @Test - public void testAddCleanColIntoColsExactOverlap() throws Exception { - CTCols cols = createHiddenAndBestFitColsWithHelper(1, 1, 1, 1); - assertEquals(1, cols.sizeOfColArray()); - assertMinMaxHiddenBestFit(cols, 0, 1, 1, true, true); - } - - @Test - public void testAddCleanColIntoColsOverlapsOverhangingBothSides() throws Exception { - CTCols cols = createHiddenAndBestFitColsWithHelper(2, 2, 1, 3); - assertEquals(3, cols.sizeOfColArray()); - assertMinMaxHiddenBestFit(cols, 0, 1, 1, false, true); - assertMinMaxHiddenBestFit(cols, 1, 2, 2, true, true); - assertMinMaxHiddenBestFit(cols, 2, 3, 3, false, true); - } - - @Test - public void testAddCleanColIntoColsOverlapsCompletelyNested() throws Exception { - CTCols cols = createHiddenAndBestFitColsWithHelper(1, 3, 2, 2); - assertEquals(3, cols.sizeOfColArray()); - assertMinMaxHiddenBestFit(cols, 0, 1, 1, true, false); - assertMinMaxHiddenBestFit(cols, 1, 2, 2, true, true); - assertMinMaxHiddenBestFit(cols, 2, 3, 3, true, false); - } - - @Test - public void testAddCleanColIntoColsNewOverlapsOverhangingLeftNotRightExactRight() throws Exception { - CTCols cols = createHiddenAndBestFitColsWithHelper(2, 3, 1, 3); - assertEquals(2, cols.sizeOfColArray()); - assertMinMaxHiddenBestFit(cols, 0, 1, 1, false, true); - assertMinMaxHiddenBestFit(cols, 1, 2, 3, true, true); - } - - @Test - public void testAddCleanColIntoColsNewOverlapsOverhangingRightNotLeftExactLeft() throws Exception { - CTCols cols = createHiddenAndBestFitColsWithHelper(1, 2, 1, 3); - assertEquals(2, cols.sizeOfColArray()); - assertMinMaxHiddenBestFit(cols, 0, 1, 2, true, true); - assertMinMaxHiddenBestFit(cols, 1, 3, 3, false, true); - } - - @Test - public void testAddCleanColIntoColsNewOverlapsOverhangingLeftNotRight() throws Exception { - CTCols cols = createHiddenAndBestFitColsWithHelper(2, 3, 1, 2); - assertEquals(3, cols.sizeOfColArray()); - assertMinMaxHiddenBestFit(cols, 0, 1, 1, false, true); - assertMinMaxHiddenBestFit(cols, 1, 2, 2, true, true); - assertMinMaxHiddenBestFit(cols, 2, 3, 3, true, false); - } - - @Test - public void testAddCleanColIntoColsNewOverlapsOverhangingRightNotLeft() throws Exception { - CTCols cols = createHiddenAndBestFitColsWithHelper(1, 2, 2, 3); - assertEquals(3, cols.sizeOfColArray()); - assertMinMaxHiddenBestFit(cols, 0, 1, 1, true, false); - assertMinMaxHiddenBestFit(cols, 1, 2, 2, true, true); - assertMinMaxHiddenBestFit(cols, 2, 3, 3, false, true); - } - - /** - * Creates and adds a hidden column and then a best fit column with the given min/max pairs. - * Suitable for testing handling of overlap. - */ - private static CTCols createHiddenAndBestFitColsWithHelper(int hiddenMin, int hiddenMax, int bestFitMin, int bestFitMax) { - CTWorksheet worksheet = CTWorksheet.Factory.newInstance(); - ColumnHelper helper = new ColumnHelper(worksheet); - CTCols cols = worksheet.getColsArray(0); - - CTCol hidden = createCol(hiddenMin, hiddenMax); - hidden.setHidden(true); - helper.addCleanColIntoCols(cols, hidden); - - CTCol bestFit = createCol(bestFitMin, bestFitMax); - bestFit.setBestFit(true); - helper.addCleanColIntoCols(cols, bestFit); - return cols; - } - - private static void assertMinMaxHiddenBestFit(CTCols cols, int index, int min, int max, boolean hidden, boolean bestFit) { - CTCol col = cols.getColArray(index); - assertEquals(min, col.getMin()); - assertEquals(max, col.getMax()); - assertEquals(hidden, col.getHidden()); - assertEquals(bestFit, col.getBestFit()); - } - - private static CTCol createCol(int min, int max) { - CTCol col = CTCol.Factory.newInstance(); - col.setMin(min); - col.setMax(max); - return col; - } - - @Test - public void testGetColumn() { - CTWorksheet worksheet = CTWorksheet.Factory.newInstance(); - - CTCols cols1 = worksheet.addNewCols(); - CTCol col1 = cols1.addNewCol(); - col1.setMin(1); - col1.setMax(1); - col1.setWidth(88); - col1.setHidden(true); - CTCol col2 = cols1.addNewCol(); - col2.setMin(2); - col2.setMax(3); - CTCols cols2 = worksheet.addNewCols(); - CTCol col4 = cols2.addNewCol(); - col4.setMin(3); - col4.setMax(6); - - // Remember - POI column 0 == OOXML column 1 - ColumnHelper helper = new ColumnHelper(worksheet); - assertNotNull(helper.getColumn(0, false)); - assertNotNull(helper.getColumn(1, false)); - assertEquals(88.0, helper.getColumn(0, false).getWidth(), 0.0); - assertEquals(0.0, helper.getColumn(1, false).getWidth(), 0.0); - assertTrue(helper.getColumn(0, false).getHidden()); - assertFalse(helper.getColumn(1, false).getHidden()); - assertNull(helper.getColumn(99, false)); - assertNotNull(helper.getColumn(5, false)); - } - - @Test - public void testSetColumnAttributes() { - CTCol col = CTCol.Factory.newInstance(); - col.setWidth(12); - col.setHidden(true); - CTCol newCol = CTCol.Factory.newInstance(); - assertEquals(0.0, newCol.getWidth(), 0.0); - assertFalse(newCol.getHidden()); - ColumnHelper helper = new ColumnHelper(CTWorksheet.Factory - .newInstance()); - helper.setColumnAttributes(col, newCol); - assertEquals(12.0, newCol.getWidth(), 0.0); - assertTrue(newCol.getHidden()); - } - - @Test - public void testGetOrCreateColumn() { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFSheet sheet = workbook.createSheet("Sheet 1"); - ColumnHelper columnHelper = sheet.getColumnHelper(); - - // Check POI 0 based, OOXML 1 based - CTCol col = columnHelper.getOrCreateColumn1Based(3, false); - assertNotNull(col); - assertNull(columnHelper.getColumn(1, false)); - assertNotNull(columnHelper.getColumn(2, false)); - assertNotNull(columnHelper.getColumn1Based(3, false)); - assertNull(columnHelper.getColumn(3, false)); - - CTCol col2 = columnHelper.getOrCreateColumn1Based(30, false); - assertNotNull(col2); - assertNull(columnHelper.getColumn(28, false)); - assertNotNull(columnHelper.getColumn(29, false)); - assertNotNull(columnHelper.getColumn1Based(30, false)); - assertNull(columnHelper.getColumn(30, false)); - } - - @Test - public void testGetSetColDefaultStyle() { - XSSFWorkbook workbook = new XSSFWorkbook(); - XSSFSheet sheet = workbook.createSheet(); - CTWorksheet ctWorksheet = sheet.getCTWorksheet(); - ColumnHelper columnHelper = sheet.getColumnHelper(); - - // POI column 3, OOXML column 4 - CTCol col = columnHelper.getOrCreateColumn1Based(4, false); - - assertNotNull(col); - assertNotNull(columnHelper.getColumn(3, false)); - columnHelper.setColDefaultStyle(3, 2); - assertEquals(2, columnHelper.getColDefaultStyle(3)); - assertEquals(-1, columnHelper.getColDefaultStyle(4)); - StylesTable stylesTable = workbook.getStylesSource(); - CTXf cellXf = CTXf.Factory.newInstance(); - cellXf.setFontId(0); - cellXf.setFillId(0); - cellXf.setBorderId(0); - cellXf.setNumFmtId(0); - cellXf.setXfId(0); - stylesTable.putCellXf(cellXf); - CTCol col_2 = ctWorksheet.getColsArray(0).addNewCol(); - col_2.setMin(10); - col_2.setMax(12); - col_2.setStyle(1); - assertEquals(1, columnHelper.getColDefaultStyle(11)); - XSSFCellStyle cellStyle = new XSSFCellStyle(0, 0, stylesTable, null); - columnHelper.setColDefaultStyle(11, cellStyle); - assertEquals(0, col_2.getStyle()); - assertEquals(1, columnHelper.getColDefaultStyle(10)); - } - - private static int countColumns(CTWorksheet worksheet) { - int count; - count = 0; - for (int i = 0; i < worksheet.sizeOfColsArray(); i++) { - for (int y = 0; y < worksheet.getColsArray(i).sizeOfColArray(); y++) { - for (long k = worksheet.getColsArray(i).getColArray(y).getMin(); k <= worksheet - .getColsArray(i).getColArray(y).getMax(); k++) { - count++; - } - } - } - return count; - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/helpers/TestHeaderFooterHelper.java b/src/ooxml/testcases/org/apache/poi/xssf/usermodel/helpers/TestHeaderFooterHelper.java deleted file mode 100644 index 2d25e3e95..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/usermodel/helpers/TestHeaderFooterHelper.java +++ /dev/null @@ -1,64 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.usermodel.helpers; - -import junit.framework.TestCase; - -import org.apache.poi.xssf.usermodel.helpers.HeaderFooterHelper; - -/** - * Test the header and footer helper. - * As we go through XmlBeans, should always use &, - * and not & - */ -public class TestHeaderFooterHelper extends TestCase { - - public void testGetCenterLeftRightSection() { - HeaderFooterHelper helper = new HeaderFooterHelper(); - - String headerFooter = "&CTest the center section"; - assertEquals("Test the center section", helper.getCenterSection(headerFooter)); - - headerFooter = "&CTest the center section<he left one&RAnd the right one"; - assertEquals("Test the center section", helper.getCenterSection(headerFooter)); - assertEquals("The left one", helper.getLeftSection(headerFooter)); - assertEquals("And the right one", helper.getRightSection(headerFooter)); - } - - public void testSetCenterLeftRightSection() { - HeaderFooterHelper helper = new HeaderFooterHelper(); - String headerFooter = ""; - headerFooter = helper.setCenterSection(headerFooter, "First added center section"); - assertEquals("First added center section", helper.getCenterSection(headerFooter)); - headerFooter = helper.setLeftSection(headerFooter, "First left"); - assertEquals("First left", helper.getLeftSection(headerFooter)); - - headerFooter = helper.setRightSection(headerFooter, "First right"); - assertEquals("First right", helper.getRightSection(headerFooter)); - assertEquals("&CFirst added center section&LFirst left&RFirst right", headerFooter); - - headerFooter = helper.setRightSection(headerFooter, "First right&F"); - assertEquals("First right&F", helper.getRightSection(headerFooter)); - assertEquals("&CFirst added center section&LFirst left&RFirst right&F", headerFooter); - - headerFooter = helper.setRightSection(headerFooter, "First right&"); - assertEquals("First right&", helper.getRightSection(headerFooter)); - assertEquals("&CFirst added center section&LFirst left&RFirst right&", headerFooter); - } - -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/util/MemoryUsage.java b/src/ooxml/testcases/org/apache/poi/xssf/util/MemoryUsage.java deleted file mode 100644 index 812a92125..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/util/MemoryUsage.java +++ /dev/null @@ -1,217 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.util; - -import junit.framework.TestCase; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.util.CellReference; -import org.openxmlformats.schemas.spreadsheetml.x2006.main.*; - -import java.util.List; -import java.util.ArrayList; - -/** - * Mixed utilities for testing memory usage in XSSF - * - * @author Yegor Kozlov - */ -public class MemoryUsage extends TestCase { - private static final int NUM_COLUMNS = 255; - - private static void printMemoryUsage(String msg) { - System.out.println(" Memory (" + msg + "): " + Runtime.getRuntime().totalMemory()/(1024*1024) + "MB"); - } - - /** - * Generate a spreadsheet until OutOfMemoryError - *

    - * cells in even columns are numbers, cells in odd columns are strings - *

    - * - * @param wb the workbook to write to - * @param numCols the number of columns in a row - */ - public static void mixedSpreadsheet(Workbook wb, int numCols){ - - System.out.println("Testing " + wb.getClass().getName()); - printMemoryUsage("before"); - int i=0, cnt=0; - try { - Sheet sh = wb.createSheet(); - for(i=0; ; i++){ - Row row = sh.createRow(i); - for(int j=0; j < numCols; j++){ - Cell cell = row.createCell(j); - if(j % 2 == 0) cell.setCellValue(j); - else cell.setCellValue(new CellReference(j, i).formatAsString()); - cnt++; - } - } - } catch (OutOfMemoryError er){ - System.out.println("Failed at row=" + i + ", objects : " + cnt); - } catch (final Exception e) { - System.out.println("Unable to reach an OutOfMemoryError"); - System.out.println(e.getClass().getName() + ": " + e.getMessage()); - } - printMemoryUsage("after"); - } - - /** - * Generate a spreadsheet who's all cell values are numbers. - * The data is generated until OutOfMemoryError. - *

    - * as compared to {@link #mixedSpreadsheet(org.apache.poi.ss.usermodel.Workbook, int)}, - * this method does not set string values and, hence, does not involve the Shared Strings Table. - *

    - * - * @param wb the workbook to write to - * @param numCols the number of columns in a row - */ - public static void numberSpreadsheet(Workbook wb, int numCols){ - - System.out.println("Testing " + wb.getClass().getName()); - printMemoryUsage("before"); - int i=0, cnt=0; - try { - Sheet sh = wb.createSheet(); - for(i=0; ; i++){ - Row row = sh.createRow(i); - for(int j=0; j < numCols; j++){ - Cell cell = row.createCell(j); - cell.setCellValue(j); - cnt++; - } - } - } catch (OutOfMemoryError er){ - System.out.println("Failed at row=" + i + ", objects : " + cnt); - } catch (final Exception e) { - System.out.println("Unable to reach an OutOfMemoryError"); - System.out.println(e.getClass().getName() + ": " + e.getMessage()); - } - printMemoryUsage("after"); - } - - /** - * Generate a spreadsheet until OutOfMemoryError using low-level OOXML XmlBeans. - * Similar to {@link #numberSpreadsheet(org.apache.poi.ss.usermodel.Workbook, int)} - * - *

    - * - * @param numCols the number of columns in a row - */ - public static void xmlBeans(int numCols) { - int i = 0, cnt = 0; - printMemoryUsage("before"); - - CTWorksheet sh = CTWorksheet.Factory.newInstance(); - CTSheetData data = sh.addNewSheetData(); - try { - for (i = 0; ; i++) { - CTRow row = data.addNewRow(); - row.setR(i); - for (int j = 0; j < numCols; j++) { - CTCell cell = row.addNewC(); - cell.setT(STCellType.N); - cell.setV(String.valueOf(j)); - cnt++; - } - } - } catch (OutOfMemoryError er) { - System.out.println("Failed at row=" + i + ", objects: " + cnt); - } catch (final Exception e) { - System.out.println("Unable to reach an OutOfMemoryError"); - System.out.println(e.getClass().getName() + ": " + e.getMessage()); - } - printMemoryUsage("after"); - } - - /** - * Generate detached (parentless) Xml beans until OutOfMemoryError - * - * @see #testXmlAttached() - */ - public void testXmlDetached(){ - List rows = new ArrayList(); - int i = 0; - try { - for(;;){ - //create a standalone CTRow bean - CTRow r = CTRow.Factory.newInstance(); - r.setR(++i); - rows.add(r); - } - } catch (OutOfMemoryError er) { - System.out.println("Failed at row=" + i); - } catch (final Exception e) { - System.out.println("Unable to reach an OutOfMemoryError"); - System.out.println(e.getClass().getName() + ": " + e.getMessage()); - } - printMemoryUsage("after"); - } - - /** - * Generate attached (having a parent bean) Xml beans until OutOfMemoryError. - * This is MUCH more memory-efficient than {@link #testXmlDetached()} - * - * @see #testXmlAttached() - */ - public void testXmlAttached(){ - printMemoryUsage("before"); - List rows = new ArrayList(); - int i = 0; - //top-level element in sheet.xml - CTWorksheet sh = CTWorksheet.Factory.newInstance(); - CTSheetData data = sh.addNewSheetData(); - try { - for(;;){ - //create CTRow attached to the parent object - CTRow r = data.addNewRow(); - r.setR(++i); - rows.add(r); - } - } catch (OutOfMemoryError er) { - System.out.println("Failed at row=" + i); - } catch (final Exception e) { - System.out.println("Unable to reach an OutOfMemoryError"); - System.out.println(e.getClass().getName() + ": " + e.getMessage()); - } - printMemoryUsage("after"); - } - - public void testMixedHSSF(){ - numberSpreadsheet(new HSSFWorkbook(), NUM_COLUMNS); - } - - public void testMixedXSSF(){ - numberSpreadsheet(new XSSFWorkbook(), NUM_COLUMNS); - } - - public void testNumberHSSF(){ - numberSpreadsheet(new HSSFWorkbook(), NUM_COLUMNS); - } - - public void testNumberXSSF(){ - numberSpreadsheet(new XSSFWorkbook(), NUM_COLUMNS); - } - -} \ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xssf/util/TestCTColComparator.java b/src/ooxml/testcases/org/apache/poi/xssf/util/TestCTColComparator.java deleted file mode 100644 index 9fa8320bb..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/util/TestCTColComparator.java +++ /dev/null @@ -1,73 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.util; - -import java.util.Arrays; - -import junit.framework.TestCase; - -import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCol; - - -public final class TestCTColComparator extends TestCase { - - public void testCompare() { - CTCol o1 = CTCol.Factory.newInstance(); - o1.setMin(1); - o1.setMax(10); - CTCol o2 = CTCol.Factory.newInstance(); - o2.setMin(11); - o2.setMax(12); - assertEquals(-1, CTColComparator.BY_MIN_MAX.compare(o1, o2)); - CTCol o3 = CTCol.Factory.newInstance(); - o3.setMin(5); - o3.setMax(8); - CTCol o4 = CTCol.Factory.newInstance(); - o4.setMin(5); - o4.setMax(80); - assertEquals(-1, CTColComparator.BY_MIN_MAX.compare(o3, o4)); - } - - public void testArraysSort() { - CTCol o1 = CTCol.Factory.newInstance(); - o1.setMin(1); - o1.setMax(10); - CTCol o2 = CTCol.Factory.newInstance(); - o2.setMin(11); - o2.setMax(12); - assertEquals(-1, CTColComparator.BY_MIN_MAX.compare(o1, o2)); - CTCol o3 = CTCol.Factory.newInstance(); - o3.setMin(5); - o3.setMax(80); - CTCol o4 = CTCol.Factory.newInstance(); - o4.setMin(5); - o4.setMax(8); - assertEquals(1, CTColComparator.BY_MIN_MAX.compare(o3, o4)); - CTCol[] cols = new CTCol[4]; - cols[0] = o1; - cols[1] = o2; - cols[2] = o3; - cols[3] = o4; - assertEquals(80, cols[2].getMax()); - assertEquals(8, cols[3].getMax()); - Arrays.sort(cols, CTColComparator.BY_MIN_MAX); - assertEquals(12, cols[3].getMax()); - assertEquals(8, cols[1].getMax()); - assertEquals(80, cols[2].getMax()); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/util/TestEvilUnclosedBRFixingInputStream.java b/src/ooxml/testcases/org/apache/poi/xssf/util/TestEvilUnclosedBRFixingInputStream.java deleted file mode 100644 index d9010fbbc..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/util/TestEvilUnclosedBRFixingInputStream.java +++ /dev/null @@ -1,94 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.util; - -import static org.junit.Assert.assertArrayEquals; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.nio.charset.Charset; - -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.ReplacingInputStream; -import org.junit.Test; - -public final class TestEvilUnclosedBRFixingInputStream { - - static class EvilUnclosedBRFixingInputStream extends ReplacingInputStream { - public EvilUnclosedBRFixingInputStream(byte[] source) { - super(new ByteArrayInputStream(source), "
    ", "
    "); - } - } - - @Test - public void testOK() throws IOException { - byte[] ok = getBytes("

    Hello There!
    Tags!

    "); - - EvilUnclosedBRFixingInputStream inp = new EvilUnclosedBRFixingInputStream(ok); - - assertArrayEquals(ok, IOUtils.toByteArray(inp)); - inp.close(); - } - - @Test - public void testProblem() throws IOException { - byte[] orig = getBytes("

    Hello
    There!
    Tags!

    "); - byte[] fixed = getBytes("

    Hello
    There!
    Tags!

    "); - - EvilUnclosedBRFixingInputStream inp = new EvilUnclosedBRFixingInputStream(orig); - - assertArrayEquals(fixed, IOUtils.toByteArray(inp)); - inp.close(); - } - - /** - * Checks that we can copy with br tags around the buffer boundaries - */ - @Test - public void testBufferSize() throws IOException { - byte[] orig = getBytes("

    Hello

    There!
    Tags!

    "); - byte[] fixed = getBytes("

    Hello

    There!
    Tags!

    "); - - // Vary the buffer size, so that we can end up with the br in the - // overflow or only part in the buffer - for(int i=5; i 0) { - bout.write(b, 0, r); - } else { - going = false; - } - } - - byte[] result = bout.toByteArray(); - assertArrayEquals(fixed, result); - inp.close(); - } - } - - private static byte[] getBytes(String str) { - return str.getBytes(Charset.forName("UTF-8")); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xssf/util/TestNumericRanges.java b/src/ooxml/testcases/org/apache/poi/xssf/util/TestNumericRanges.java deleted file mode 100644 index 90ea9736a..000000000 --- a/src/ooxml/testcases/org/apache/poi/xssf/util/TestNumericRanges.java +++ /dev/null @@ -1,58 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xssf.util; - -import junit.framework.TestCase; - - -public class TestNumericRanges extends TestCase { - - public void testGetOverlappingType() { - long[] r1 = {3, 8}; - long[] r2 = {6, 11}; - long[] r3 = {1, 5}; - long[] r4 = {2, 20}; - long[] r5 = {5, 6}; - long[] r6 = {20, 23}; - assertEquals(NumericRanges.OVERLAPS_1_MINOR, NumericRanges.getOverlappingType(r1, r2)); - assertEquals(NumericRanges.OVERLAPS_2_MINOR, NumericRanges.getOverlappingType(r1, r3)); - assertEquals(NumericRanges.OVERLAPS_2_WRAPS, NumericRanges.getOverlappingType(r1, r4)); - assertEquals(NumericRanges.OVERLAPS_1_WRAPS, NumericRanges.getOverlappingType(r1, r5)); - assertEquals(NumericRanges.NO_OVERLAPS, NumericRanges.getOverlappingType(r1, r6)); - } - - public void testGetOverlappingRange() { - long[] r1 = {3, 8}; - long[] r2 = {6, 11}; - long[] r3 = {1, 5}; - long[] r4 = {2, 20}; - long[] r5 = {5, 6}; - long[] r6 = {20, 23}; - assertEquals(6, NumericRanges.getOverlappingRange(r1, r2)[0]); - assertEquals(8, NumericRanges.getOverlappingRange(r1, r2)[1]); - assertEquals(3, NumericRanges.getOverlappingRange(r1, r3)[0]); - assertEquals(5, NumericRanges.getOverlappingRange(r1, r3)[1]); - assertEquals(3, NumericRanges.getOverlappingRange(r1, r4)[0]); - assertEquals(8, NumericRanges.getOverlappingRange(r1, r4)[1]); - assertEquals(5, NumericRanges.getOverlappingRange(r1, r5)[0]); - assertEquals(6, NumericRanges.getOverlappingRange(r1, r5)[1]); - assertEquals(-1, NumericRanges.getOverlappingRange(r1, r6)[0]); - assertEquals(-1, NumericRanges.getOverlappingRange(r1, r6)[1]); - } - -} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/AllXWPFTests.java b/src/ooxml/testcases/org/apache/poi/xwpf/AllXWPFTests.java deleted file mode 100644 index e3311ff2f..000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/AllXWPFTests.java +++ /dev/null @@ -1,56 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xwpf; - -import org.apache.poi.xwpf.extractor.TestXWPFWordExtractor; -import org.apache.poi.xwpf.model.TestXWPFHeaderFooterPolicy; -import org.apache.poi.xwpf.usermodel.TestXWPFDocument; -import org.apache.poi.xwpf.usermodel.TestXWPFHeader; -import org.apache.poi.xwpf.usermodel.TestXWPFHeadings; -import org.apache.poi.xwpf.usermodel.TestXWPFNumbering; -import org.apache.poi.xwpf.usermodel.TestXWPFParagraph; -import org.apache.poi.xwpf.usermodel.TestXWPFPictureData; -import org.apache.poi.xwpf.usermodel.TestXWPFRun; -import org.apache.poi.xwpf.usermodel.TestXWPFStyles; -import org.apache.poi.xwpf.usermodel.TestXWPFTable; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -/** - * Collects all tests for org.apache.poi.xwpf and sub-packages. - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestXWPFBugs.class, - org.apache.poi.xwpf.usermodel.TestXWPFBugs.class, - TestXWPFDocument.class, - TestXWPFWordExtractor.class, - TestXWPFHeaderFooterPolicy.class, - TestXWPFHeader.class, - TestXWPFHeadings.class, - TestXWPFParagraph.class, - TestXWPFRun.class, - TestXWPFTable.class, - TestXWPFStyles.class, - TestXWPFPictureData.class, - TestXWPFNumbering.class, - TestAllExtendedProperties.class, - TestPackageCorePropertiesGetKeywords.class -}) -public final class AllXWPFTests { -} \ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/TestAllExtendedProperties.java b/src/ooxml/testcases/org/apache/poi/xwpf/TestAllExtendedProperties.java deleted file mode 100644 index 707e9b83d..000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/TestAllExtendedProperties.java +++ /dev/null @@ -1,105 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xwpf; - -import java.io.IOException; - -import junit.framework.TestCase; -import org.apache.poi.POIXMLProperties.CoreProperties; -import org.apache.poi.openxml4j.opc.PackageProperties; -import org.apache.poi.xwpf.usermodel.XWPFDocument; -import org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.CTDigSigBlob; -import org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.CTProperties; -import org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.CTVectorLpstr; -import org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.CTVectorVariant; - -/** - * Tests if the {@link CoreProperties#getKeywords()} method. This test has been - * submitted because even though the - * {@link PackageProperties#getKeywordsProperty()} had been present before, the - * {@link CoreProperties#getKeywords()} had been missing. - *

    - * The author of this has added {@link CoreProperties#getKeywords()} and - * {@link CoreProperties#setKeywords(String)} and this test is supposed to test - * them. - * - * @author Antoni Mylka - */ -public final class TestAllExtendedProperties extends TestCase { - public void testGetAllExtendedProperties() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestPoiXMLDocumentCorePropertiesGetKeywords.docx"); - CTProperties ctProps = doc.getProperties().getExtendedProperties().getUnderlyingProperties(); - assertEquals("Microsoft Office Word", ctProps.getApplication()); - assertEquals("14.0000", ctProps.getAppVersion()); - assertEquals(57, ctProps.getCharacters()); - assertEquals(66, ctProps.getCharactersWithSpaces()); - assertEquals("", ctProps.getCompany()); - assertNull(ctProps.getDigSig()); - assertEquals(0, ctProps.getDocSecurity()); - assertNotNull(ctProps.getDomNode()); - - CTVectorVariant vec = ctProps.getHeadingPairs(); - assertEquals(2, vec.getVector().sizeOfVariantArray()); - assertEquals("Title", vec.getVector().getVariantArray(0).getLpstr()); - assertEquals(1, vec.getVector().getVariantArray(1).getI4()); - - assertFalse(ctProps.isSetHiddenSlides()); - assertEquals(0, ctProps.getHiddenSlides()); - assertFalse(ctProps.isSetHLinks()); - assertNull(ctProps.getHLinks()); - assertNull(ctProps.getHyperlinkBase()); - assertTrue(ctProps.isSetHyperlinksChanged()); - assertFalse(ctProps.getHyperlinksChanged()); - assertEquals(1, ctProps.getLines()); - assertTrue(ctProps.isSetLinksUpToDate()); - assertFalse(ctProps.getLinksUpToDate()); - assertNull(ctProps.getManager()); - assertFalse(ctProps.isSetMMClips()); - assertEquals(0, ctProps.getMMClips()); - assertFalse(ctProps.isSetNotes()); - assertEquals(0, ctProps.getNotes()); - assertEquals(1, ctProps.getPages()); - assertEquals(1, ctProps.getParagraphs()); - assertNull(ctProps.getPresentationFormat()); - assertTrue(ctProps.isSetScaleCrop()); - assertFalse(ctProps.getScaleCrop()); - assertTrue(ctProps.isSetSharedDoc()); - assertFalse(ctProps.getSharedDoc()); - assertFalse(ctProps.isSetSlides()); - assertEquals(0, ctProps.getSlides()); - assertEquals("Normal.dotm", ctProps.getTemplate()); - - CTVectorLpstr vec2 = ctProps.getTitlesOfParts(); - assertEquals(1, vec2.getVector().sizeOfLpstrArray()); - assertEquals("Example Word 2010 Document", vec2.getVector().getLpstrArray(0)); - - assertEquals(3, ctProps.getTotalTime()); - assertEquals(10, ctProps.getWords()); - - // Check the digital signature part - // Won't be there in this file, but we - // need to do this check so that the - // appropriate parts end up in the - // smaller ooxml schemas file - CTDigSigBlob blob = ctProps.getDigSig(); - assertNull(blob); - - blob = CTDigSigBlob.Factory.newInstance(); - blob.setBlob(new byte[]{2, 6, 7, 2, 3, 4, 5, 1, 2, 3}); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/TestDocumentProtection.java b/src/ooxml/testcases/org/apache/poi/xwpf/TestDocumentProtection.java deleted file mode 100644 index 550a0c18c..000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/TestDocumentProtection.java +++ /dev/null @@ -1,199 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; - -import org.apache.poi.poifs.crypt.CryptoFunctions; -import org.apache.poi.poifs.crypt.HashAlgorithm; -import org.apache.poi.util.TempFile; -import org.apache.poi.xwpf.usermodel.XWPFDocument; -import org.apache.poi.xwpf.usermodel.XWPFParagraph; -import org.apache.poi.xwpf.usermodel.XWPFRun; -import org.junit.Test; - -public class TestDocumentProtection { - - @Test - public void testShouldReadEnforcementProperties() throws IOException { - - XWPFDocument documentWithoutDocumentProtectionTag = XWPFTestDataSamples.openSampleDocument("documentProtection_no_protection.docx"); - assertFalse(documentWithoutDocumentProtectionTag.isEnforcedReadonlyProtection()); - assertFalse(documentWithoutDocumentProtectionTag.isEnforcedFillingFormsProtection()); - assertFalse(documentWithoutDocumentProtectionTag.isEnforcedCommentsProtection()); - assertFalse(documentWithoutDocumentProtectionTag.isEnforcedTrackedChangesProtection()); - documentWithoutDocumentProtectionTag.close(); - - XWPFDocument documentWithoutEnforcement = XWPFTestDataSamples.openSampleDocument("documentProtection_no_protection_tag_existing.docx"); - assertFalse(documentWithoutEnforcement.isEnforcedReadonlyProtection()); - assertFalse(documentWithoutEnforcement.isEnforcedFillingFormsProtection()); - assertFalse(documentWithoutEnforcement.isEnforcedCommentsProtection()); - assertFalse(documentWithoutEnforcement.isEnforcedTrackedChangesProtection()); - documentWithoutEnforcement.close(); - - XWPFDocument documentWithReadonlyEnforcement = XWPFTestDataSamples.openSampleDocument("documentProtection_readonly_no_password.docx"); - assertTrue(documentWithReadonlyEnforcement.isEnforcedReadonlyProtection()); - assertFalse(documentWithReadonlyEnforcement.isEnforcedFillingFormsProtection()); - assertFalse(documentWithReadonlyEnforcement.isEnforcedCommentsProtection()); - assertFalse(documentWithReadonlyEnforcement.isEnforcedTrackedChangesProtection()); - documentWithReadonlyEnforcement.close(); - - XWPFDocument documentWithFillingFormsEnforcement = XWPFTestDataSamples.openSampleDocument("documentProtection_forms_no_password.docx"); - assertTrue(documentWithFillingFormsEnforcement.isEnforcedFillingFormsProtection()); - assertFalse(documentWithFillingFormsEnforcement.isEnforcedReadonlyProtection()); - assertFalse(documentWithFillingFormsEnforcement.isEnforcedCommentsProtection()); - assertFalse(documentWithFillingFormsEnforcement.isEnforcedTrackedChangesProtection()); - documentWithFillingFormsEnforcement.close(); - - XWPFDocument documentWithCommentsEnforcement = XWPFTestDataSamples.openSampleDocument("documentProtection_comments_no_password.docx"); - assertFalse(documentWithCommentsEnforcement.isEnforcedFillingFormsProtection()); - assertFalse(documentWithCommentsEnforcement.isEnforcedReadonlyProtection()); - assertTrue(documentWithCommentsEnforcement.isEnforcedCommentsProtection()); - assertFalse(documentWithCommentsEnforcement.isEnforcedTrackedChangesProtection()); - documentWithCommentsEnforcement.close(); - - XWPFDocument documentWithTrackedChangesEnforcement = XWPFTestDataSamples.openSampleDocument("documentProtection_trackedChanges_no_password.docx"); - assertFalse(documentWithTrackedChangesEnforcement.isEnforcedFillingFormsProtection()); - assertFalse(documentWithTrackedChangesEnforcement.isEnforcedReadonlyProtection()); - assertFalse(documentWithTrackedChangesEnforcement.isEnforcedCommentsProtection()); - assertTrue(documentWithTrackedChangesEnforcement.isEnforcedTrackedChangesProtection()); - documentWithTrackedChangesEnforcement.close(); - } - - @Test - public void testShouldEnforceForReadOnly() throws IOException { - // XWPFDocument document = createDocumentFromSampleFile("test-data/document/documentProtection_no_protection.docx"); - XWPFDocument document = XWPFTestDataSamples.openSampleDocument("documentProtection_no_protection.docx"); - assertFalse(document.isEnforcedReadonlyProtection()); - - document.enforceReadonlyProtection(); - - assertTrue(document.isEnforcedReadonlyProtection()); - document.close(); - } - - @Test - public void testShouldEnforceForFillingForms() throws IOException { - XWPFDocument document = XWPFTestDataSamples.openSampleDocument("documentProtection_no_protection.docx"); - assertFalse(document.isEnforcedFillingFormsProtection()); - - document.enforceFillingFormsProtection(); - - assertTrue(document.isEnforcedFillingFormsProtection()); - document.close(); - } - - @Test - public void testShouldEnforceForComments() throws IOException { - XWPFDocument document = XWPFTestDataSamples.openSampleDocument("documentProtection_no_protection.docx"); - assertFalse(document.isEnforcedCommentsProtection()); - - document.enforceCommentsProtection(); - - assertTrue(document.isEnforcedCommentsProtection()); - document.close(); - } - - @Test - public void testShouldEnforceForTrackedChanges() throws IOException { - XWPFDocument document = XWPFTestDataSamples.openSampleDocument("documentProtection_no_protection.docx"); - assertFalse(document.isEnforcedTrackedChangesProtection()); - - document.enforceTrackedChangesProtection(); - - assertTrue(document.isEnforcedTrackedChangesProtection()); - document.close(); - } - - @Test - public void testShouldUnsetEnforcement() throws IOException { - XWPFDocument document = XWPFTestDataSamples.openSampleDocument("documentProtection_readonly_no_password.docx"); - assertTrue(document.isEnforcedReadonlyProtection()); - - document.removeProtectionEnforcement(); - - assertFalse(document.isEnforcedReadonlyProtection()); - document.close(); - } - - @Test - public void testIntegration() throws IOException { - XWPFDocument doc1 = new XWPFDocument(); - - XWPFParagraph p1 = doc1.createParagraph(); - - XWPFRun r1 = p1.createRun(); - r1.setText("Lorem ipsum dolor sit amet."); - doc1.enforceCommentsProtection(); - - File tempFile = TempFile.createTempFile("documentProtectionFile", ".docx"); - FileOutputStream out = new FileOutputStream(tempFile); - - doc1.write(out); - out.close(); - - FileInputStream inputStream = new FileInputStream(tempFile); - XWPFDocument doc2 = new XWPFDocument(inputStream); - inputStream.close(); - - assertTrue(doc2.isEnforcedCommentsProtection()); - doc2.close(); - doc1.close(); - } - - @Test - public void testUpdateFields() throws IOException { - XWPFDocument doc = new XWPFDocument(); - assertFalse(doc.isEnforcedUpdateFields()); - doc.enforceUpdateFields(); - assertTrue(doc.isEnforcedUpdateFields()); - doc.close(); - } - - @Test - public void bug56076_read() throws IOException { - // test legacy xored-hashed password - assertEquals("64CEED7E", CryptoFunctions.xorHashPassword("Example")); - // check leading 0 - assertEquals("0005CB00", CryptoFunctions.xorHashPassword("34579")); - - // test document write protection with password - XWPFDocument document = XWPFTestDataSamples.openSampleDocument("bug56076.docx"); - boolean isValid = document.validateProtectionPassword("Example"); - assertTrue(isValid); - document.close(); - } - - @Test - public void bug56076_write() throws IOException { - // test document write protection with password - XWPFDocument doc1 = new XWPFDocument(); - doc1.enforceCommentsProtection("Example", HashAlgorithm.sha512); - XWPFDocument doc2 = XWPFTestDataSamples.writeOutAndReadBack(doc1); - doc1.close(); - boolean isValid = doc2.validateProtectionPassword("Example"); - assertTrue(isValid); - doc2.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/TestPackageCorePropertiesGetKeywords.java b/src/ooxml/testcases/org/apache/poi/xwpf/TestPackageCorePropertiesGetKeywords.java deleted file mode 100644 index d53c5c14d..000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/TestPackageCorePropertiesGetKeywords.java +++ /dev/null @@ -1,50 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xwpf; - -import java.io.IOException; - -import junit.framework.TestCase; -import org.apache.poi.POIXMLProperties.CoreProperties; -import org.apache.poi.openxml4j.opc.PackageProperties; -import org.apache.poi.xwpf.usermodel.XWPFDocument; - -/** - * Tests if the {@link CoreProperties#getKeywords()} method. This test has been - * submitted because even though the - * {@link PackageProperties#getKeywordsProperty()} had been present before, the - * {@link CoreProperties#getKeywords()} had been missing. - *

    - * The author of this has added {@link CoreProperties#getKeywords()} and - * {@link CoreProperties#setKeywords(String)} and this test is supposed to test - * them. - * - * @author Antoni Mylka - */ -public final class TestPackageCorePropertiesGetKeywords extends TestCase { - public void testGetSetKeywords() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestPoiXMLDocumentCorePropertiesGetKeywords.docx"); - String keywords = doc.getProperties().getCoreProperties().getKeywords(); - assertEquals("extractor, test, rdf", keywords); - - doc.getProperties().getCoreProperties().setKeywords("test, keywords"); - doc = XWPFTestDataSamples.writeOutAndReadBack(doc); - keywords = doc.getProperties().getCoreProperties().getKeywords(); - assertEquals("test, keywords", keywords); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/TestXWPFBugs.java b/src/ooxml/testcases/org/apache/poi/xwpf/TestXWPFBugs.java deleted file mode 100644 index 377d98b33..000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/TestXWPFBugs.java +++ /dev/null @@ -1,127 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; - -import javax.crypto.Cipher; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.poifs.crypt.CipherAlgorithm; -import org.apache.poi.poifs.crypt.Decryptor; -import org.apache.poi.poifs.crypt.EncryptionInfo; -import org.apache.poi.poifs.crypt.HashAlgorithm; -import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; -import org.apache.poi.xwpf.extractor.XWPFWordExtractor; -import org.apache.poi.xwpf.usermodel.XWPFDocument; -import org.apache.xmlbeans.XmlException; -import org.junit.Assume; -import org.junit.Test; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.DocumentDocument; - -public class TestXWPFBugs { - /** - * A word document that's encrypted with non-standard - * Encryption options, and no cspname section. See bug 53475 - */ - @Test - public void bug53475NoCSPName() throws Exception { - File file = POIDataSamples.getDocumentInstance().getFile("bug53475-password-is-solrcell.docx"); - NPOIFSFileSystem filesystem = new NPOIFSFileSystem(file, true); - - // Check the encryption details - EncryptionInfo info = new EncryptionInfo(filesystem); - assertEquals(128, info.getHeader().getKeySize()); - assertEquals(CipherAlgorithm.aes128, info.getHeader().getCipherAlgorithm()); - assertEquals(HashAlgorithm.sha1, info.getHeader().getHashAlgorithmEx()); - - // Check it can be decoded - Decryptor d = Decryptor.getInstance(info); - assertTrue("Unable to process: document is encrypted", d.verifyPassword("solrcell")); - - // Check we can read the word document in that - InputStream dataStream = d.getDataStream(filesystem); - OPCPackage opc = OPCPackage.open(dataStream); - XWPFDocument doc = new XWPFDocument(opc); - XWPFWordExtractor ex = new XWPFWordExtractor(doc); - String text = ex.getText(); - assertNotNull(text); - assertEquals("This is password protected Word document.", text.trim()); - ex.close(); - - filesystem.close(); - } - - /** - * A word document with aes-256, i.e. aes is always 128 bit (= 128 bit block size), - * but the key can be 128/192/256 bits - */ - @Test - public void bug53475_aes256() throws Exception { - int maxKeyLen = Cipher.getMaxAllowedKeyLength("AES"); - Assume.assumeTrue("Please install JCE Unlimited Strength Jurisdiction Policy files for AES 256", maxKeyLen == 2147483647); - - File file = POIDataSamples.getDocumentInstance().getFile("bug53475-password-is-pass.docx"); - NPOIFSFileSystem filesystem = new NPOIFSFileSystem(file, true); - - // Check the encryption details - EncryptionInfo info = new EncryptionInfo(filesystem); - assertEquals(16, info.getHeader().getBlockSize()); - assertEquals(256, info.getHeader().getKeySize()); - assertEquals(CipherAlgorithm.aes256, info.getHeader().getCipherAlgorithm()); - assertEquals(HashAlgorithm.sha1, info.getHeader().getHashAlgorithmEx()); - - // Check it can be decoded - Decryptor d = Decryptor.getInstance(info); - assertTrue("Unable to process: document is encrypted", d.verifyPassword("pass")); - - // Check we can read the word document in that - InputStream dataStream = d.getDataStream(filesystem); - OPCPackage opc = OPCPackage.open(dataStream); - XWPFDocument doc = new XWPFDocument(opc); - XWPFWordExtractor ex = new XWPFWordExtractor(doc); - String text = ex.getText(); - assertNotNull(text); - // I know ... a stupid typo, maybe next time ... - assertEquals("The is a password protected document.", text.trim()); - ex.close(); - - filesystem.close(); - } - - - @Test - public void bug59058() throws IOException, XmlException { - String files[] = { "bug57031.docx", "bug59058.docx" }; - for (String f : files) { - ZipFile zf = new ZipFile(POIDataSamples.getDocumentInstance().getFile(f)); - ZipEntry entry = zf.getEntry("word/document.xml"); - DocumentDocument document = DocumentDocument.Factory.parse(zf.getInputStream(entry)); - assertNotNull(document); - zf.close(); - } - } -} \ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/XWPFTestDataSamples.java b/src/ooxml/testcases/org/apache/poi/xwpf/XWPFTestDataSamples.java deleted file mode 100644 index 14cb582b3..000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/XWPFTestDataSamples.java +++ /dev/null @@ -1,53 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.util.IOUtils; -import org.apache.poi.xwpf.usermodel.XWPFDocument; - -/** - * @author Yegor Kozlov - */ -public class XWPFTestDataSamples { - - public static XWPFDocument openSampleDocument(String sampleName) throws IOException { - InputStream is = POIDataSamples.getDocumentInstance().openResourceAsStream(sampleName); - return new XWPFDocument(is); - } - - public static XWPFDocument writeOutAndReadBack(XWPFDocument doc) throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(4096); - doc.write(baos); - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - return new XWPFDocument(bais); - } - - public static byte[] getImage(String filename) throws IOException { - InputStream is = POIDataSamples.getDocumentInstance().openResourceAsStream(filename); - try { - return IOUtils.toByteArray(is); - } finally { - is.close(); - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/extractor/TestExternalEntities.java b/src/ooxml/testcases/org/apache/poi/xwpf/extractor/TestExternalEntities.java deleted file mode 100644 index 929d43041..000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/extractor/TestExternalEntities.java +++ /dev/null @@ -1,47 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xwpf.extractor; - -import java.io.IOException; - -import junit.framework.TestCase; -import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.apache.poi.xwpf.usermodel.XWPFDocument; - -public class TestExternalEntities extends TestCase { - - /** - * Get text out of the simple file - * - * @throws IOException - */ - public void testFile() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("ExternalEntityInText.docx"); - XWPFWordExtractor extractor = new XWPFWordExtractor(doc); - - String text = extractor.getText(); - - assertTrue(text.length() > 0); - - // Check contents, they should not contain the text from POI web site after colon! - assertEquals("Here should not be the POI web site: \"\"", text.trim()); - - extractor.close(); - } - -} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/extractor/TestXWPFWordExtractor.java b/src/ooxml/testcases/org/apache/poi/xwpf/extractor/TestXWPFWordExtractor.java deleted file mode 100644 index cf1ba0a6b..000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/extractor/TestXWPFWordExtractor.java +++ /dev/null @@ -1,411 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xwpf.extractor; - -import java.io.IOException; -import java.util.Locale; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import junit.framework.TestCase; - -import org.apache.poi.util.StringUtil; -import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.apache.poi.xwpf.usermodel.XWPFDocument; - -/** - * Tests for HXFWordExtractor - */ -public class TestXWPFWordExtractor extends TestCase { - - /** - * Get text out of the simple file - * - * @throws IOException - */ - public void testGetSimpleText() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx"); - XWPFWordExtractor extractor = new XWPFWordExtractor(doc); - - String text = extractor.getText(); - assertTrue(text.length() > 0); - - // Check contents - assertTrue(text.startsWith( - "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nunc at risus vel erat tempus posuere. Aenean non ante. Suspendisse vehicula dolor sit amet odio." - )); - assertTrue(text.endsWith( - "Phasellus ultricies mi nec leo. Sed tempus. In sit amet lorem at velit faucibus vestibulum.\n" - )); - - // Check number of paragraphs by counting number of newlines - int numberOfParagraphs = StringUtil.countMatches(text, '\n'); - assertEquals(3, numberOfParagraphs); - - extractor.close(); - } - - /** - * Tests getting the text out of a complex file - * - * @throws IOException - */ - public void testGetComplexText() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("IllustrativeCases.docx"); - XWPFWordExtractor extractor = new XWPFWordExtractor(doc); - - String text = extractor.getText(); - assertTrue(text.length() > 0); - - char euro = '\u20ac'; -// System.err.println("'"+text.substring(text.length() - 40) + "'"); - - // Check contents - assertTrue(text.startsWith( - " \n(V) ILLUSTRATIVE CASES\n\n" - )); - assertTrue(text.contains( - "As well as gaining " + euro + "90 from child benefit increases, he will also receive the early childhood supplement of " + euro + "250 per quarter for Vincent for the full four quarters of the year.\n\n\n\n"// \n\n\n" - )); - assertTrue(text.endsWith( - "11.4%\t\t90\t\t\t\t\t250\t\t1,310\t\n\n \n\n\n" - )); - - // Check number of paragraphs by counting number of newlines - int numberOfParagraphs = StringUtil.countMatches(text, '\n'); - assertEquals(134, numberOfParagraphs); - - extractor.close(); - } - - public void testGetWithHyperlinks() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestDocument.docx"); - XWPFWordExtractor extractor = new XWPFWordExtractor(doc); - - // Now check contents - extractor.setFetchHyperlinks(false); - assertEquals( - "This is a test document.\nThis bit is in bold and italic\n" + - "Back to normal\n" + - "This contains BOLD, ITALIC and BOTH, as well as RED and YELLOW text.\n" + - "We have a hyperlink here, and another.\n", - extractor.getText() - ); - - // One hyperlink is a real one, one is just to the top of page - extractor.setFetchHyperlinks(true); - assertEquals( - "This is a test document.\nThis bit is in bold and italic\n" + - "Back to normal\n" + - "This contains BOLD, ITALIC and BOTH, as well as RED and YELLOW text.\n" + - "We have a hyperlink here, and another.\n", - extractor.getText() - ); - - extractor.close(); - } - - public void testHeadersFooters() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("ThreeColHeadFoot.docx"); - XWPFWordExtractor extractor = new XWPFWordExtractor(doc); - - assertEquals( - "First header column!\tMid header\tRight header!\n" + - "This is a sample word document. It has two pages. It has a three column heading, and a three column footer\n" + - "\n" + - "HEADING TEXT\n" + - "\n" + - "More on page one\n" + - "\n\n" + - "End of page 1\n\n\n" + - "This is page two. It also has a three column heading, and a three column footer.\n" + - "Footer Left\tFooter Middle\tFooter Right\n", - extractor.getText() - ); - - // Now another file, expect multiple headers - // and multiple footers - doc = XWPFTestDataSamples.openSampleDocument("DiffFirstPageHeadFoot.docx"); - extractor.close(); - - extractor = new XWPFWordExtractor(doc); - extractor.close(); - - extractor = - new XWPFWordExtractor(doc); - extractor.getText(); - - assertEquals( - "I am the header on the first page, and I" + '\u2019' + "m nice and simple\n" + - "First header column!\tMid header\tRight header!\n" + - "This is a sample word document. It has two pages. It has a simple header and footer, which is different to all the other pages.\n" + - "\n" + - "HEADING TEXT\n" + - "\n" + - "More on page one\n" + - "\n\n" + - "End of page 1\n\n\n" + - "This is page two. It also has a three column heading, and a three column footer.\n" + - "The footer of the first page\n" + - "Footer Left\tFooter Middle\tFooter Right\n", - extractor.getText() - ); - - extractor.close(); - } - - public void testFootnotes() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("footnotes.docx"); - XWPFWordExtractor extractor = new XWPFWordExtractor(doc); - String text = extractor.getText(); - assertTrue(text.contains("snoska")); - assertTrue(text.contains("Eto ochen prostoy[footnoteRef:1] text so snoskoy")); - - extractor.close(); - } - - - public void testTableFootnotes() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("table_footnotes.docx"); - XWPFWordExtractor extractor = new XWPFWordExtractor(doc); - - assertTrue(extractor.getText().contains("snoska")); - - extractor.close(); - } - - public void testFormFootnotes() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("form_footnotes.docx"); - XWPFWordExtractor extractor = new XWPFWordExtractor(doc); - - String text = extractor.getText(); - assertTrue("Unable to find expected word in text\n" + text, text.contains("testdoc")); - assertTrue("Unable to find expected word in text\n" + text, text.contains("test phrase")); - - extractor.close(); - } - - public void testEndnotes() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("endnotes.docx"); - XWPFWordExtractor extractor = new XWPFWordExtractor(doc); - String text = extractor.getText(); - assertTrue(text.contains("XXX")); - assertTrue(text.contains("tilaka [endnoteRef:2]or 'tika'")); - - extractor.close(); - } - - public void testInsertedDeletedText() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("delins.docx"); - XWPFWordExtractor extractor = new XWPFWordExtractor(doc); - - assertTrue(extractor.getText().contains("pendant worn")); - assertTrue(extractor.getText().contains("extremely well")); - - extractor.close(); - } - - public void testParagraphHeader() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Headers.docx"); - XWPFWordExtractor extractor = new XWPFWordExtractor(doc); - - assertTrue(extractor.getText().contains("Section 1")); - assertTrue(extractor.getText().contains("Section 2")); - assertTrue(extractor.getText().contains("Section 3")); - - extractor.close(); - } - - /** - * Test that we can open and process .docm - * (macro enabled) docx files (bug #45690) - * - * @throws IOException - */ - public void testDOCMFiles() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("45690.docm"); - XWPFWordExtractor extractor = new XWPFWordExtractor(doc); - - assertTrue(extractor.getText().contains("2004")); - assertTrue(extractor.getText().contains("2008")); - assertTrue(extractor.getText().contains("(120 ")); - - extractor.close(); - } - - /** - * Test that we handle things like tabs and - * carriage returns properly in the text that - * we're extracting (bug #49189) - * - * @throws IOException - */ - public void testDocTabs() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("WithTabs.docx"); - XWPFWordExtractor extractor = new XWPFWordExtractor(doc); - - // Check bits - assertTrue(extractor.getText().contains("a")); - assertTrue(extractor.getText().contains("\t")); - assertTrue(extractor.getText().contains("b")); - - // Now check the first paragraph in total - assertTrue(extractor.getText().contains("a\tb\n")); - - extractor.close(); - } - - /** - * The output should not contain field codes, e.g. those specified in the - * w:instrText tag (spec sec. 17.16.23) - * - * @throws IOException - */ - public void testNoFieldCodes() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("FieldCodes.docx"); - XWPFWordExtractor extractor = new XWPFWordExtractor(doc); - String text = extractor.getText(); - assertTrue(text.length() > 0); - assertFalse(text.contains("AUTHOR")); - assertFalse(text.contains("CREATEDATE")); - - extractor.close(); - } - - /** - * The output should contain the values of simple fields, those specified - * with the fldSimple element (spec sec. 17.16.19) - * - * @throws IOException - */ - public void testFldSimpleContent() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("FldSimple.docx"); - XWPFWordExtractor extractor = new XWPFWordExtractor(doc); - String text = extractor.getText(); - assertTrue(text.length() > 0); - assertTrue(text.contains("FldSimple.docx")); - - extractor.close(); - } - - /** - * Test for parsing document with drawings to prevent - * NoClassDefFoundError for CTAnchor in XWPFRun - */ - public void testDrawings() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("drawing.docx"); - XWPFWordExtractor extractor = new XWPFWordExtractor(doc); - String text = extractor.getText(); - assertTrue(text.length() > 0); - - extractor.close(); - } - - /** - * Test for basic extraction of SDT content - * - * @throws IOException - */ - public void testSimpleControlContent() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Bug54849.docx"); - String[] targs = new String[]{ - "header_rich_text", - "rich_text", - "rich_text_pre_table\nrich_text_cell1\t\t\t\n\t\t\t\n\t\t\t\n\nrich_text_post_table", - "plain_text_no_newlines", - "plain_text_with_newlines1\nplain_text_with_newlines2\n", - "watermelon\n", - "dirt\n", - "4/16/2013\n", - "rich_text_in_cell", - "abc", - "rich_text_in_paragraph_in_cell", - "footer_rich_text", - "footnote_sdt", - "endnote_sdt" - }; - XWPFWordExtractor ex = new XWPFWordExtractor(doc); - String s = ex.getText().toLowerCase(Locale.ROOT); - int hits = 0; - - for (String targ : targs) { - boolean hit = false; - if (s.contains(targ)) { - hit = true; - hits++; - } - assertEquals("controlled content loading-" + targ, true, hit); - } - assertEquals("controlled content loading hit count", targs.length, hits); - ex.close(); - - - doc = XWPFTestDataSamples.openSampleDocument("Bug54771a.docx"); - targs = new String[]{ - "bb", - "test subtitle\n", - "test user\n", - }; - ex = new XWPFWordExtractor(doc); - s = ex.getText().toLowerCase(Locale.ROOT); - - //At one point in development there were three copies of the text. - //This ensures that there is only one copy. - for (String targ : targs) { - Matcher m = Pattern.compile(targ).matcher(s); - int hit = 0; - while (m.find()) { - hit++; - } - assertEquals("controlled content loading-" + targ, 1, hit); - } - //"test\n" appears twice: once as the "title" and once in the text. - //This also happens when you save this document as text from MSWord. - Matcher m = Pattern.compile("test\n").matcher(s); - int hit = 0; - while (m.find()) { - hit++; - } - assertEquals("test", 2, hit); - ex.close(); - } - - /** - * No Header or Footer in document - */ - public void testBug55733() throws Exception { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("55733.docx"); - XWPFWordExtractor extractor = new XWPFWordExtractor(doc); - - // Check it gives text without error - extractor.getText(); - extractor.close(); - } - - public void testCheckboxes() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("checkboxes.docx"); - XWPFWordExtractor extractor = new XWPFWordExtractor(doc); - - assertEquals("This is a small test for checkboxes \nunchecked: |_| \n" + - "Or checked: |X|\n\n\n\n\n" + - "Test a checkbox within a textbox: |_| -> |X|\n\n\n" + - "In Table:\n|_|\t|X|\n\n\n" + - "In Sequence:\n|X||_||X|\n", extractor.getText()); - extractor.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/model/TestXWPFDecorators.java b/src/ooxml/testcases/org/apache/poi/xwpf/model/TestXWPFDecorators.java deleted file mode 100644 index 1b81c2a9e..000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/model/TestXWPFDecorators.java +++ /dev/null @@ -1,80 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xwpf.model; - -import java.io.IOException; - -import junit.framework.TestCase; -import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.apache.poi.xwpf.usermodel.XWPFDocument; -import org.apache.poi.xwpf.usermodel.XWPFHyperlinkRun; -import org.apache.poi.xwpf.usermodel.XWPFParagraph; - -/** - * Tests for the various XWPF decorators - */ -public class TestXWPFDecorators extends TestCase { - private XWPFDocument simple; - private XWPFDocument hyperlink; - private XWPFDocument comments; - - @Override - protected void setUp() throws IOException { - simple = XWPFTestDataSamples.openSampleDocument("SampleDoc.docx"); - hyperlink = XWPFTestDataSamples.openSampleDocument("TestDocument.docx"); - comments = XWPFTestDataSamples.openSampleDocument("WordWithAttachments.docx"); - } - - public void testHyperlink() { - XWPFParagraph ps; - XWPFParagraph ph; - assertEquals(7, simple.getParagraphs().size()); - assertEquals(5, hyperlink.getParagraphs().size()); - - // Simple text - ps = simple.getParagraphs().get(0); - assertEquals("I am a test document", ps.getParagraphText()); - assertEquals(1, ps.getRuns().size()); - - ph = hyperlink.getParagraphs().get(4); - assertEquals("We have a hyperlink here, and another.", ph.getParagraphText()); - assertEquals(3, ph.getRuns().size()); - - - // The proper way to do hyperlinks(!) - assertFalse(ps.getRuns().get(0) instanceof XWPFHyperlinkRun); - assertFalse(ph.getRuns().get(0) instanceof XWPFHyperlinkRun); - assertTrue(ph.getRuns().get(1) instanceof XWPFHyperlinkRun); - assertFalse(ph.getRuns().get(2) instanceof XWPFHyperlinkRun); - - XWPFHyperlinkRun link = (XWPFHyperlinkRun) ph.getRuns().get(1); - assertEquals("http://poi.apache.org/", link.getHyperlink(hyperlink).getURL()); - } - - public void testComments() { - int numComments = 0; - for (XWPFParagraph p : comments.getParagraphs()) { - XWPFCommentsDecorator d = new XWPFCommentsDecorator(p, null); - if (d.getCommentText().length() > 0) { - numComments++; - assertEquals("\tComment by", d.getCommentText().substring(0, 11)); - } - } - assertEquals(3, numComments); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/model/TestXWPFHeaderFooterPolicy.java b/src/ooxml/testcases/org/apache/poi/xwpf/model/TestXWPFHeaderFooterPolicy.java deleted file mode 100644 index 0596a941f..000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/model/TestXWPFHeaderFooterPolicy.java +++ /dev/null @@ -1,188 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xwpf.model; - -import java.io.IOException; - -import junit.framework.TestCase; - -import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.apache.poi.xwpf.usermodel.XWPFDocument; -import org.apache.poi.xwpf.usermodel.XWPFFooter; -import org.apache.poi.xwpf.usermodel.XWPFHeader; - -/** - * Tests for XWPF Header Footer Stuff - */ -public class TestXWPFHeaderFooterPolicy extends TestCase { - private XWPFDocument noHeader; - private XWPFDocument header; - private XWPFDocument headerFooter; - private XWPFDocument footer; - private XWPFDocument oddEven; - private XWPFDocument diffFirst; - - @Override - protected void setUp() throws IOException { - noHeader = XWPFTestDataSamples.openSampleDocument("NoHeadFoot.docx"); - header = XWPFTestDataSamples.openSampleDocument("ThreeColHead.docx"); - headerFooter = XWPFTestDataSamples.openSampleDocument("SimpleHeadThreeColFoot.docx"); - footer = XWPFTestDataSamples.openSampleDocument("FancyFoot.docx"); - oddEven = XWPFTestDataSamples.openSampleDocument("PageSpecificHeadFoot.docx"); - diffFirst = XWPFTestDataSamples.openSampleDocument("DiffFirstPageHeadFoot.docx"); - } - - public void testPolicy() { - XWPFHeaderFooterPolicy policy; - - policy = noHeader.getHeaderFooterPolicy(); - assertNull(policy.getDefaultHeader()); - assertNull(policy.getDefaultFooter()); - - assertNull(policy.getHeader(1)); - assertNull(policy.getHeader(2)); - assertNull(policy.getHeader(3)); - assertNull(policy.getFooter(1)); - assertNull(policy.getFooter(2)); - assertNull(policy.getFooter(3)); - - - policy = header.getHeaderFooterPolicy(); - assertNotNull(policy.getDefaultHeader()); - assertNull(policy.getDefaultFooter()); - - assertEquals(policy.getDefaultHeader(), policy.getHeader(1)); - assertEquals(policy.getDefaultHeader(), policy.getHeader(2)); - assertEquals(policy.getDefaultHeader(), policy.getHeader(3)); - assertNull(policy.getFooter(1)); - assertNull(policy.getFooter(2)); - assertNull(policy.getFooter(3)); - - - policy = footer.getHeaderFooterPolicy(); - assertNull(policy.getDefaultHeader()); - assertNotNull(policy.getDefaultFooter()); - - assertNull(policy.getHeader(1)); - assertNull(policy.getHeader(2)); - assertNull(policy.getHeader(3)); - assertEquals(policy.getDefaultFooter(), policy.getFooter(1)); - assertEquals(policy.getDefaultFooter(), policy.getFooter(2)); - assertEquals(policy.getDefaultFooter(), policy.getFooter(3)); - - - policy = headerFooter.getHeaderFooterPolicy(); - assertNotNull(policy.getDefaultHeader()); - assertNotNull(policy.getDefaultFooter()); - - assertEquals(policy.getDefaultHeader(), policy.getHeader(1)); - assertEquals(policy.getDefaultHeader(), policy.getHeader(2)); - assertEquals(policy.getDefaultHeader(), policy.getHeader(3)); - assertEquals(policy.getDefaultFooter(), policy.getFooter(1)); - assertEquals(policy.getDefaultFooter(), policy.getFooter(2)); - assertEquals(policy.getDefaultFooter(), policy.getFooter(3)); - - - policy = oddEven.getHeaderFooterPolicy(); - assertNotNull(policy.getDefaultHeader()); - assertNotNull(policy.getDefaultFooter()); - assertNotNull(policy.getEvenPageHeader()); - assertNotNull(policy.getEvenPageFooter()); - - assertEquals(policy.getDefaultHeader(), policy.getHeader(1)); - assertEquals(policy.getEvenPageHeader(), policy.getHeader(2)); - assertEquals(policy.getDefaultHeader(), policy.getHeader(3)); - assertEquals(policy.getDefaultFooter(), policy.getFooter(1)); - assertEquals(policy.getEvenPageFooter(), policy.getFooter(2)); - assertEquals(policy.getDefaultFooter(), policy.getFooter(3)); - - - policy = diffFirst.getHeaderFooterPolicy(); - assertNotNull(policy.getDefaultHeader()); - assertNotNull(policy.getDefaultFooter()); - assertNotNull(policy.getFirstPageHeader()); - assertNotNull(policy.getFirstPageFooter()); - assertNull(policy.getEvenPageHeader()); - assertNull(policy.getEvenPageFooter()); - - assertEquals(policy.getFirstPageHeader(), policy.getHeader(1)); - assertEquals(policy.getDefaultHeader(), policy.getHeader(2)); - assertEquals(policy.getDefaultHeader(), policy.getHeader(3)); - assertEquals(policy.getFirstPageFooter(), policy.getFooter(1)); - assertEquals(policy.getDefaultFooter(), policy.getFooter(2)); - assertEquals(policy.getDefaultFooter(), policy.getFooter(3)); - } - - @SuppressWarnings("resource") - public void testCreate() throws Exception { - XWPFDocument doc = new XWPFDocument(); - assertEquals(null, doc.getHeaderFooterPolicy()); - assertEquals(0, doc.getHeaderList().size()); - assertEquals(0, doc.getFooterList().size()); - - XWPFHeaderFooterPolicy policy = doc.createHeaderFooterPolicy(); - assertNotNull(doc.getHeaderFooterPolicy()); - assertEquals(0, doc.getHeaderList().size()); - assertEquals(0, doc.getFooterList().size()); - - // Create a header and a footer - XWPFHeader header = policy.createHeader(XWPFHeaderFooterPolicy.DEFAULT); - XWPFFooter footer = policy.createFooter(XWPFHeaderFooterPolicy.DEFAULT); - header.createParagraph().createRun().setText("Header Hello"); - footer.createParagraph().createRun().setText("Footer Bye"); - - - // Save, re-load, and check - doc = XWPFTestDataSamples.writeOutAndReadBack(doc); - assertNotNull(doc.getHeaderFooterPolicy()); - assertEquals(1, doc.getHeaderList().size()); - assertEquals(1, doc.getFooterList().size()); - - assertEquals("Header Hello\n", doc.getHeaderList().get(0).getText()); - assertEquals("Footer Bye\n", doc.getFooterList().get(0).getText()); - } - - public void testContents() { - XWPFHeaderFooterPolicy policy; - - // Test a few simple bits off a simple header - policy = diffFirst.getHeaderFooterPolicy(); - - assertEquals( - "I am the header on the first page, and I" + '\u2019' + "m nice and simple\n", - policy.getFirstPageHeader().getText() - ); - assertEquals( - "First header column!\tMid header\tRight header!\n", - policy.getDefaultHeader().getText() - ); - - - // And a few bits off a more complex header - policy = oddEven.getHeaderFooterPolicy(); - - assertEquals( - "[ODD Page Header text]\n\n", - policy.getDefaultHeader().getText() - ); - assertEquals( - "[This is an Even Page, with a Header]\n\n", - policy.getEvenPageHeader().getText() - ); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestChangeTracking.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestChangeTracking.java deleted file mode 100644 index 47ec76524..000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestChangeTracking.java +++ /dev/null @@ -1,68 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; - -import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.junit.Test; - -public class TestChangeTracking { - @Test - public void detection() throws Exception { - XWPFDocument documentWithoutChangeTracking = XWPFTestDataSamples.openSampleDocument("bug56075-changeTracking_off.docx"); - assertFalse(documentWithoutChangeTracking.isTrackRevisions()); - - XWPFDocument documentWithChangeTracking = XWPFTestDataSamples.openSampleDocument("bug56075-changeTracking_on.docx"); - assertTrue(documentWithChangeTracking.isTrackRevisions()); - } - - @Test - public void activateChangeTracking() throws Exception { - XWPFDocument document = XWPFTestDataSamples.openSampleDocument("bug56075-changeTracking_off.docx"); - assertFalse(document.isTrackRevisions()); - - document.setTrackRevisions(true); - - assertTrue(document.isTrackRevisions()); - } - - @Test - @SuppressWarnings("resource") - public void integration() throws Exception { - XWPFDocument doc = new XWPFDocument(); - - XWPFParagraph p1 = doc.createParagraph(); - - XWPFRun r1 = p1.createRun(); - r1.setText("Lorem ipsum dolor sit amet."); - doc.setTrackRevisions(true); - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - doc.write(out); - - ByteArrayInputStream inputStream = new ByteArrayInputStream(out.toByteArray()); - XWPFDocument document = new XWPFDocument(inputStream); - inputStream.close(); - - assertTrue(document.isTrackRevisions()); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFBugs.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFBugs.java deleted file mode 100644 index 8d26db292..000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFBugs.java +++ /dev/null @@ -1,177 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -import org.apache.poi.util.Units; -import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.apache.poi.xwpf.usermodel.XWPFRun.FontCharRange; -import org.junit.Test; - -public class TestXWPFBugs { - @Test - public void bug55802() throws Exception { - String blabla = - "Bir, iki, \u00fc\u00e7, d\u00f6rt, be\u015f,\n" + - "\nalt\u0131, yedi, sekiz, dokuz, on.\n" + - "\nK\u0131rm\u0131z\u0131 don,\n" + - "\ngel bizim bah\u00e7eye kon,\n" + - "\nsar\u0131 limon"; - XWPFDocument doc = new XWPFDocument(); - XWPFRun run = doc.createParagraph().createRun(); - - for (String str : blabla.split("\n")) { - run.setText(str); - run.addBreak(); - } - - run.setFontFamily("Times New Roman"); - run.setFontSize(20); - assertEquals(run.getFontFamily(), "Times New Roman"); - assertEquals(run.getFontFamily(FontCharRange.cs), "Times New Roman"); - assertEquals(run.getFontFamily(FontCharRange.eastAsia), "Times New Roman"); - assertEquals(run.getFontFamily(FontCharRange.hAnsi), "Times New Roman"); - run.setFontFamily("Arial", FontCharRange.hAnsi); - assertEquals(run.getFontFamily(FontCharRange.hAnsi), "Arial"); - - doc.close(); - } - - @Test - public void bug57312_NullPointException() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("57312.docx"); - assertNotNull(doc); - - for (IBodyElement bodyElement : doc.getBodyElements()) { - BodyElementType elementType = bodyElement.getElementType(); - - if (elementType == BodyElementType.PARAGRAPH) { - XWPFParagraph paragraph = (XWPFParagraph) bodyElement; - - for (IRunElement iRunElem : paragraph.getIRuns()) { - - if (iRunElem instanceof XWPFRun) { - XWPFRun runElement = (XWPFRun) iRunElem; - - UnderlinePatterns underline = runElement.getUnderline(); - assertNotNull(underline); - - //System.out.println("Found: " + underline + ": " + runElement.getText(0)); - } - } - } - } - doc.close(); - } - - @Test - public void bug57495_getTableArrayInDoc() throws IOException { - XWPFDocument doc =new XWPFDocument(); - //let's create a few tables for the test - for(int i=0;i<3;i++) { - doc.createTable(2, 2); - } - XWPFTable table = doc.getTableArray(0); - assertNotNull(table); - //let's check also that returns the correct table - XWPFTable same = doc.getTables().get(0); - assertEquals(table, same); - doc.close(); - } - - @Test - public void bug57495_getParagraphArrayInTableCell() throws IOException { - XWPFDocument doc =new XWPFDocument(); - //let's create a table for the test - XWPFTable table = doc.createTable(2, 2); - assertNotNull(table); - XWPFParagraph p = table.getRow(0).getCell(0).getParagraphArray(0); - assertNotNull(p); - //let's check also that returns the correct paragraph - XWPFParagraph same = table.getRow(0).getCell(0).getParagraphs().get(0); - assertEquals(p, same); - doc.close(); - } - - @Test - public void bug57495_convertPixelsToEMUs() { - int pixels = 100; - int expectedEMU = 952500; - int result = Units.pixelToEMU(pixels); - assertEquals(expectedEMU, result); - } - - @Test - public void test56392() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("56392.docx"); - assertNotNull(doc); - doc.close(); - } - - /** - * Removing a run needs to remove it from both Runs and IRuns - */ - @Test - public void test57829() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx"); - assertNotNull(doc); - assertEquals(3, doc.getParagraphs().size()); - - for (XWPFParagraph paragraph : doc.getParagraphs()) { - paragraph.removeRun(0); - assertNotNull(paragraph.getText()); - } - doc.close(); - } - - /** - * Removing a run needs to take into account position of run if paragraph contains hyperlink runs - */ - @Test - public void test58618() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("58618.docx"); - XWPFParagraph para = (XWPFParagraph)doc.getBodyElements().get(0); - assertNotNull(para); - assertEquals("Some text some hyper links link link and some text.....", para.getText()); - XWPFRun run = para.insertNewRun(para.getRuns().size()); - run.setText("New Text"); - assertEquals("Some text some hyper links link link and some text.....New Text", para.getText()); - para.removeRun(para.getRuns().size() -2); - assertEquals("Some text some hyper links link linkNew Text", para.getText()); - doc.close(); - } - - @Test - public void test59378() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("59378.docx"); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - doc.write(out); - out.close(); - - XWPFDocument doc2 = new XWPFDocument(new ByteArrayInputStream(out.toByteArray())); - doc2.close(); - - XWPFDocument docBack = XWPFTestDataSamples.writeOutAndReadBack(doc); - docBack.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFDocument.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFDocument.java deleted file mode 100644 index 16959b4c9..000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFDocument.java +++ /dev/null @@ -1,451 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xwpf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.IOException; -import java.io.OutputStream; -import java.util.Arrays; -import java.util.List; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.POIXMLProperties; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackageAccess; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.opc.PackagePartName; -import org.apache.poi.openxml4j.opc.PackagingURIHelper; -import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.apache.poi.xwpf.extractor.XWPFWordExtractor; -import org.apache.xmlbeans.XmlCursor; -import org.junit.Ignore; -import org.junit.Test; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP; - -public final class TestXWPFDocument { - - @Test - public void testContainsMainContentType() throws Exception { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx"); - OPCPackage pack = doc.getPackage(); - - boolean found = false; - for (PackagePart part : pack.getParts()) { - if (part.getContentType().equals(XWPFRelation.DOCUMENT.getContentType())) { - found = true; - } -// if (false) { -// // successful tests should be silent -// System.out.println(part); -// } - } - assertTrue(found); - - pack.close(); - doc.close(); - } - - @Test - public void testOpen() throws Exception { - // Simple file - XWPFDocument xml1 = XWPFTestDataSamples.openSampleDocument("sample.docx"); - // Check it has key parts - assertNotNull(xml1.getDocument()); - assertNotNull(xml1.getDocument().getBody()); - assertNotNull(xml1.getStyle()); - xml1.close(); - - // Complex file - XWPFDocument xml2 = XWPFTestDataSamples.openSampleDocument("IllustrativeCases.docx"); - assertNotNull(xml2.getDocument()); - assertNotNull(xml2.getDocument().getBody()); - assertNotNull(xml2.getStyle()); - xml2.close(); - } - - @Test - public void testMetadataBasics() throws IOException { - XWPFDocument xml = XWPFTestDataSamples.openSampleDocument("sample.docx"); - assertNotNull(xml.getProperties().getCoreProperties()); - assertNotNull(xml.getProperties().getExtendedProperties()); - - assertEquals("Microsoft Office Word", xml.getProperties().getExtendedProperties().getUnderlyingProperties().getApplication()); - assertEquals(1315, xml.getProperties().getExtendedProperties().getUnderlyingProperties().getCharacters()); - assertEquals(10, xml.getProperties().getExtendedProperties().getUnderlyingProperties().getLines()); - - assertEquals(null, xml.getProperties().getCoreProperties().getTitle()); - assertEquals(null, xml.getProperties().getCoreProperties().getUnderlyingProperties().getSubjectProperty().getValue()); - xml.close(); - } - - @Test - public void testMetadataComplex() throws IOException { - XWPFDocument xml = XWPFTestDataSamples.openSampleDocument("IllustrativeCases.docx"); - assertNotNull(xml.getProperties().getCoreProperties()); - assertNotNull(xml.getProperties().getExtendedProperties()); - - assertEquals("Microsoft Office Outlook", xml.getProperties().getExtendedProperties().getUnderlyingProperties().getApplication()); - assertEquals(5184, xml.getProperties().getExtendedProperties().getUnderlyingProperties().getCharacters()); - assertEquals(0, xml.getProperties().getExtendedProperties().getUnderlyingProperties().getLines()); - - assertEquals(" ", xml.getProperties().getCoreProperties().getTitle()); - assertEquals(" ", xml.getProperties().getCoreProperties().getUnderlyingProperties().getSubjectProperty().getValue()); - xml.close(); - } - - @Test - public void testWorkbookProperties() throws Exception { - XWPFDocument doc = new XWPFDocument(); - POIXMLProperties props = doc.getProperties(); - assertNotNull(props); - assertEquals("Apache POI", props.getExtendedProperties().getUnderlyingProperties().getApplication()); - doc.close(); - } - - @Test - public void testAddParagraph() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx"); - assertEquals(3, doc.getParagraphs().size()); - - XWPFParagraph p = doc.createParagraph(); - assertEquals(p, doc.getParagraphs().get(3)); - assertEquals(4, doc.getParagraphs().size()); - - assertEquals(3, doc.getParagraphPos(3)); - assertEquals(3, doc.getPosOfParagraph(p)); - - CTP ctp = p.getCTP(); - XWPFParagraph newP = doc.getParagraph(ctp); - assertSame(p, newP); - XmlCursor cursor = doc.getDocument().getBody().getPArray(0).newCursor(); - XWPFParagraph cP = doc.insertNewParagraph(cursor); - assertSame(cP, doc.getParagraphs().get(0)); - assertEquals(5, doc.getParagraphs().size()); - doc.close(); - } - - @Test - public void testAddPicture() throws IOException, InvalidFormatException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx"); - byte[] jpeg = XWPFTestDataSamples.getImage("nature1.jpg"); - String relationId = doc.addPictureData(jpeg, Document.PICTURE_TYPE_JPEG); - - byte[] newJpeg = ((XWPFPictureData) doc.getRelationById(relationId)).getData(); - assertEquals(newJpeg.length, jpeg.length); - for (int i = 0; i < jpeg.length; i++) { - assertEquals(newJpeg[i], jpeg[i]); - } - doc.close(); - } - - @Test - public void testAllPictureFormats() throws IOException, InvalidFormatException { - XWPFDocument doc = new XWPFDocument(); - - doc.addPictureData(new byte[10], Document.PICTURE_TYPE_EMF); - doc.addPictureData(new byte[11], Document.PICTURE_TYPE_WMF); - doc.addPictureData(new byte[12], Document.PICTURE_TYPE_PICT); - doc.addPictureData(new byte[13], Document.PICTURE_TYPE_JPEG); - doc.addPictureData(new byte[14], Document.PICTURE_TYPE_PNG); - doc.addPictureData(new byte[15], Document.PICTURE_TYPE_DIB); - doc.addPictureData(new byte[16], Document.PICTURE_TYPE_GIF); - doc.addPictureData(new byte[17], Document.PICTURE_TYPE_TIFF); - doc.addPictureData(new byte[18], Document.PICTURE_TYPE_EPS); - doc.addPictureData(new byte[19], Document.PICTURE_TYPE_BMP); - doc.addPictureData(new byte[20], Document.PICTURE_TYPE_WPG); - - assertEquals(11, doc.getAllPictures().size()); - - XWPFDocument doc2 = XWPFTestDataSamples.writeOutAndReadBack(doc); - assertEquals(11, doc2.getAllPictures().size()); - doc2.close(); - doc.close(); - } - - @Test - public void testRemoveBodyElement() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx"); - assertEquals(3, doc.getParagraphs().size()); - assertEquals(3, doc.getBodyElements().size()); - - XWPFParagraph p1 = doc.getParagraphs().get(0); - XWPFParagraph p2 = doc.getParagraphs().get(1); - XWPFParagraph p3 = doc.getParagraphs().get(2); - - assertEquals(p1, doc.getBodyElements().get(0)); - assertEquals(p1, doc.getParagraphs().get(0)); - assertEquals(p2, doc.getBodyElements().get(1)); - assertEquals(p2, doc.getParagraphs().get(1)); - assertEquals(p3, doc.getBodyElements().get(2)); - assertEquals(p3, doc.getParagraphs().get(2)); - - // Add another - XWPFParagraph p4 = doc.createParagraph(); - - assertEquals(4, doc.getParagraphs().size()); - assertEquals(4, doc.getBodyElements().size()); - assertEquals(p1, doc.getBodyElements().get(0)); - assertEquals(p1, doc.getParagraphs().get(0)); - assertEquals(p2, doc.getBodyElements().get(1)); - assertEquals(p2, doc.getParagraphs().get(1)); - assertEquals(p3, doc.getBodyElements().get(2)); - assertEquals(p3, doc.getParagraphs().get(2)); - assertEquals(p4, doc.getBodyElements().get(3)); - assertEquals(p4, doc.getParagraphs().get(3)); - - // Remove the 2nd - assertEquals(true, doc.removeBodyElement(1)); - assertEquals(3, doc.getParagraphs().size()); - assertEquals(3, doc.getBodyElements().size()); - - assertEquals(p1, doc.getBodyElements().get(0)); - assertEquals(p1, doc.getParagraphs().get(0)); - assertEquals(p3, doc.getBodyElements().get(1)); - assertEquals(p3, doc.getParagraphs().get(1)); - assertEquals(p4, doc.getBodyElements().get(2)); - assertEquals(p4, doc.getParagraphs().get(2)); - - // Remove the 1st - assertEquals(true, doc.removeBodyElement(0)); - assertEquals(2, doc.getParagraphs().size()); - assertEquals(2, doc.getBodyElements().size()); - - assertEquals(p3, doc.getBodyElements().get(0)); - assertEquals(p3, doc.getParagraphs().get(0)); - assertEquals(p4, doc.getBodyElements().get(1)); - assertEquals(p4, doc.getParagraphs().get(1)); - - // Remove the last - assertEquals(true, doc.removeBodyElement(1)); - assertEquals(1, doc.getParagraphs().size()); - assertEquals(1, doc.getBodyElements().size()); - - assertEquals(p3, doc.getBodyElements().get(0)); - assertEquals(p3, doc.getParagraphs().get(0)); - doc.close(); - } - - @Test - public void testRegisterPackagePictureData() throws IOException, InvalidFormatException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("issue_51265_1.docx"); - - /* manually assemble a new image package part*/ - OPCPackage opcPckg = doc.getPackage(); - XWPFRelation jpgRelation = XWPFRelation.IMAGE_JPEG; - PackagePartName partName = PackagingURIHelper.createPartName(jpgRelation.getDefaultFileName().replace('#', '2')); - PackagePart newImagePart = opcPckg.createPart(partName, jpgRelation.getContentType()); - byte[] nature1 = XWPFTestDataSamples.getImage("abstract4.jpg"); - OutputStream os = newImagePart.getOutputStream(); - os.write(nature1); - os.close(); - XWPFHeader xwpfHeader = doc.getHeaderArray(0); - XWPFPictureData newPicData = new XWPFPictureData(newImagePart); - /* new part is now ready to rumble */ - - assertFalse(xwpfHeader.getAllPictures().contains(newPicData)); - assertFalse(doc.getAllPictures().contains(newPicData)); - assertFalse(doc.getAllPackagePictures().contains(newPicData)); - - doc.registerPackagePictureData(newPicData); - - assertFalse(xwpfHeader.getAllPictures().contains(newPicData)); - assertFalse(doc.getAllPictures().contains(newPicData)); - assertTrue(doc.getAllPackagePictures().contains(newPicData)); - - doc.getPackage().revert(); - opcPckg.close(); - doc.close(); - } - - @Test - public void testFindPackagePictureData() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("issue_51265_1.docx"); - byte[] nature1 = XWPFTestDataSamples.getImage("nature1.gif"); - XWPFPictureData part = doc.findPackagePictureData(nature1, Document.PICTURE_TYPE_GIF); - assertNotNull(part); - assertTrue(doc.getAllPictures().contains(part)); - assertTrue(doc.getAllPackagePictures().contains(part)); - doc.getPackage().revert(); - doc.close(); - } - - @Test - public void testGetAllPictures() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("issue_51265_3.docx"); - List allPictures = doc.getAllPictures(); - List allPackagePictures = doc.getAllPackagePictures(); - - assertNotNull(allPictures); - assertEquals(3, allPictures.size()); - for (XWPFPictureData xwpfPictureData : allPictures) { - assertTrue(allPackagePictures.contains(xwpfPictureData)); - } - - try { - allPictures.add(allPictures.get(0)); - fail("This list must be unmodifiable!"); - } catch (UnsupportedOperationException e) { - // all ok - } - - doc.getPackage().revert(); - doc.close(); - } - - @Test - public void testGetAllPackagePictures() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("issue_51265_3.docx"); - List allPackagePictures = doc.getAllPackagePictures(); - - assertNotNull(allPackagePictures); - assertEquals(5, allPackagePictures.size()); - - try { - allPackagePictures.add(allPackagePictures.get(0)); - fail("This list must be unmodifiable!"); - } catch (UnsupportedOperationException e) { - // all ok - } - - doc.getPackage().revert(); - doc.close(); - } - - @Test - public void testPictureHandlingSimpleFile() throws IOException, InvalidFormatException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("issue_51265_1.docx"); - assertEquals(1, doc.getAllPackagePictures().size()); - byte[] newPic = XWPFTestDataSamples.getImage("abstract4.jpg"); - String id1 = doc.addPictureData(newPic, Document.PICTURE_TYPE_JPEG); - assertEquals(2, doc.getAllPackagePictures().size()); - /* copy data, to avoid instance-equality */ - byte[] newPicCopy = Arrays.copyOf(newPic, newPic.length); - String id2 = doc.addPictureData(newPicCopy, Document.PICTURE_TYPE_JPEG); - assertEquals(id1, id2); - doc.getPackage().revert(); - doc.close(); - } - - @Test - public void testPictureHandlingHeaderDocumentImages() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("issue_51265_2.docx"); - assertEquals(1, doc.getAllPictures().size()); - assertEquals(1, doc.getAllPackagePictures().size()); - assertEquals(1, doc.getHeaderArray(0).getAllPictures().size()); - doc.getPackage().revert(); - doc.close(); - } - - @Test - public void testPictureHandlingComplex() throws IOException, InvalidFormatException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("issue_51265_3.docx"); - XWPFHeader xwpfHeader = doc.getHeaderArray(0); - - assertEquals(3, doc.getAllPictures().size()); - assertEquals(3, xwpfHeader.getAllPictures().size()); - assertEquals(5, doc.getAllPackagePictures().size()); - - byte[] nature1 = XWPFTestDataSamples.getImage("nature1.jpg"); - String id = doc.addPictureData(nature1, Document.PICTURE_TYPE_JPEG); - POIXMLDocumentPart part1 = xwpfHeader.getRelationById("rId1"); - XWPFPictureData part2 = (XWPFPictureData) doc.getRelationById(id); - assertSame(part1, part2); - - doc.getPackage().revert(); - doc.close(); - } - - @Test - public void testZeroLengthLibreOfficeDocumentWithWaterMarkHeader() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("zero-length.docx"); - POIXMLProperties properties = doc.getProperties(); - - assertNotNull(properties.getCoreProperties()); - - XWPFHeader headerArray = doc.getHeaderArray(0); - assertEquals(1, headerArray.getAllPictures().size()); - assertEquals("image1.png", headerArray.pictures.get(0).getFileName()); - assertEquals("", headerArray.getText()); - - POIXMLProperties.ExtendedProperties extendedProperties = properties.getExtendedProperties(); - assertNotNull(extendedProperties); - assertEquals(0, extendedProperties.getUnderlyingProperties().getCharacters()); - doc.close(); - } - - @Test - public void testSettings() throws IOException { - XWPFSettings settings = new XWPFSettings(); - assertEquals(100, settings.getZoomPercent()); - settings.setZoomPercent(50); - assertEquals(50, settings.getZoomPercent()); - - XWPFDocument doc = new XWPFDocument(); - assertEquals(100, doc.getZoomPercent()); - - doc.setZoomPercent(50); - assertEquals(50, doc.getZoomPercent()); - - doc.setZoomPercent(200); - assertEquals(200, doc.getZoomPercent()); - - XWPFDocument back = XWPFTestDataSamples.writeOutAndReadBack(doc); - assertEquals(200, back.getZoomPercent()); - back.close(); - -// OutputStream out = new FileOutputStream("/tmp/testZoom.docx"); -// doc.write(out); -// out.close(); - - doc.close(); - } - - @Test - public void testEnforcedWith() throws IOException { - XWPFDocument docx = XWPFTestDataSamples.openSampleDocument("EnforcedWith.docx"); - assertTrue(docx.isEnforcedProtection()); - docx.close(); - } - - @Test - @Ignore("XWPF should be able to write to a new Stream when opened Read-Only") - public void testWriteFromReadOnlyOPC() throws Exception { - OPCPackage opc = OPCPackage.open( - POIDataSamples.getDocumentInstance().getFile("SampleDoc.docx"), - PackageAccess.READ - ); - XWPFDocument doc = new XWPFDocument(opc); - XWPFWordExtractor ext = new XWPFWordExtractor(doc); - String origText = ext.getText(); - - doc = XWPFTestDataSamples.writeOutAndReadBack(doc); - ext.close(); - ext = new XWPFWordExtractor(doc); - - assertEquals(origText, ext.getText()); - ext.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFFootnotes.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFFootnotes.java deleted file mode 100644 index 7025a266c..000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFFootnotes.java +++ /dev/null @@ -1,68 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xwpf.usermodel; - -import java.io.IOException; -import java.math.BigInteger; -import java.util.List; - -import junit.framework.TestCase; -import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFtnEdn; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STFtnEdn; - -public class TestXWPFFootnotes extends TestCase { - - public void testAddFootnotesToDocument() throws IOException { - XWPFDocument docOut = new XWPFDocument(); - - BigInteger noteId = BigInteger.valueOf(1); - - XWPFFootnotes footnotes = docOut.createFootnotes(); - CTFtnEdn ctNote = CTFtnEdn.Factory.newInstance(); - ctNote.setId(noteId); - ctNote.setType(STFtnEdn.NORMAL); - footnotes.addFootnote(ctNote); - - XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(docOut); - - XWPFFootnote note = docIn.getFootnoteByID(noteId.intValue()); - assertEquals(note.getCTFtnEdn().getType(), STFtnEdn.NORMAL); - } - - /** - * Bug 55066 - avoid double loading the footnotes - */ - public void testLoadFootnotesOnce() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Bug54849.docx"); - List footnotes = doc.getFootnotes(); - int hits = 0; - for (XWPFFootnote fn : footnotes) { - for (IBodyElement e : fn.getBodyElements()) { - if (e instanceof XWPFParagraph) { - String txt = ((XWPFParagraph) e).getText(); - if (txt.indexOf("Footnote_sdt") > -1) { - hits++; - } - } - } - } - assertEquals("Load footnotes once", 1, hits); - } -} - diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFHeader.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFHeader.java deleted file mode 100644 index fbb24f506..000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFHeader.java +++ /dev/null @@ -1,230 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xwpf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - -import java.io.IOException; - -import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy; -import org.junit.Test; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTText; - -public final class TestXWPFHeader { - - @Test - public void testSimpleHeader() throws IOException { - XWPFDocument sampleDoc = XWPFTestDataSamples.openSampleDocument("headerFooter.docx"); - - XWPFHeaderFooterPolicy policy = sampleDoc.getHeaderFooterPolicy(); - - XWPFHeader header = policy.getDefaultHeader(); - XWPFFooter footer = policy.getDefaultFooter(); - assertNotNull(header); - assertNotNull(footer); - } - - @Test - public void testImageInHeader() throws IOException { - XWPFDocument sampleDoc = XWPFTestDataSamples.openSampleDocument("headerPic.docx"); - - XWPFHeaderFooterPolicy policy = sampleDoc.getHeaderFooterPolicy(); - - XWPFHeader header = policy.getDefaultHeader(); - - assertNotNull(header.getRelations()); - assertEquals(1, header.getRelations().size()); - } - - @Test - public void testSetHeader() throws IOException { - XWPFDocument sampleDoc = XWPFTestDataSamples.openSampleDocument("SampleDoc.docx"); - // no header is set (yet) - XWPFHeaderFooterPolicy policy = sampleDoc.getHeaderFooterPolicy(); - assertNull(policy.getDefaultHeader()); - assertNull(policy.getFirstPageHeader()); - assertNull(policy.getDefaultFooter()); - assertNull(policy.getFirstPageFooter()); - - CTP ctP1 = CTP.Factory.newInstance(); - CTR ctR1 = ctP1.addNewR(); - CTText t = ctR1.addNewT(); - String tText = "Paragraph in header"; - t.setStringValue(tText); - - // Commented MB 23 May 2010 - //CTP ctP2 = CTP.Factory.newInstance(); - //CTR ctR2 = ctP2.addNewR(); - //CTText t2 = ctR2.addNewT(); - //t2.setStringValue("Second paragraph.. for footer"); - - // Create two paragraphs for insertion into the footer. - // Previously only one was inserted MB 23 May 2010 - CTP ctP2 = CTP.Factory.newInstance(); - CTR ctR2 = ctP2.addNewR(); - CTText t2 = ctR2.addNewT(); - t2.setStringValue("First paragraph for the footer"); - - CTP ctP3 = CTP.Factory.newInstance(); - CTR ctR3 = ctP3.addNewR(); - CTText t3 = ctR3.addNewT(); - t3.setStringValue("Second paragraph for the footer"); - - XWPFParagraph p1 = new XWPFParagraph(ctP1, sampleDoc); - XWPFParagraph[] pars = new XWPFParagraph[1]; - pars[0] = p1; - - XWPFParagraph p2 = new XWPFParagraph(ctP2, sampleDoc); - XWPFParagraph p3 = new XWPFParagraph(ctP3, sampleDoc); - XWPFParagraph[] pars2 = new XWPFParagraph[2]; - pars2[0] = p2; - pars2[1] = p3; - - // Set headers - XWPFHeader headerD = policy.createHeader(XWPFHeaderFooterPolicy.DEFAULT, pars); - XWPFHeader headerF = policy.createHeader(XWPFHeaderFooterPolicy.FIRST); - // Set a default footer and capture the returned XWPFFooter object. - XWPFFooter footerD = policy.createFooter(XWPFHeaderFooterPolicy.DEFAULT, pars2); - XWPFFooter footerF = policy.createFooter(XWPFHeaderFooterPolicy.FIRST); - - // Ensure the headers and footer were set correctly.... - assertNotNull(policy.getDefaultHeader()); - assertNotNull(policy.getFirstPageHeader()); - assertNotNull(policy.getDefaultFooter()); - assertNotNull(policy.getFirstPageFooter()); - // ....and that the footer object captured above contains two - // paragraphs of text. - assertEquals(2, footerD.getParagraphs().size()); - assertEquals(0, footerF.getParagraphs().size()); - - // Check the header created with the paragraph got them, and the one - // created without got none - assertEquals(1, headerD.getParagraphs().size()); - assertEquals(tText, headerD.getParagraphs().get(0).getText()); - - assertEquals(0, headerF.getParagraphs().size()); - - // As an additional check, recover the defauls footer and - // make sure that it contains two paragraphs of text and that - // both do hold what is expected. - footerD = policy.getDefaultFooter(); - XWPFParagraph[] paras = footerD.getParagraphs().toArray(new XWPFParagraph[0]); - - assertEquals(2, paras.length); - assertEquals("First paragraph for the footer", paras[0].getText()); - assertEquals("Second paragraph for the footer", paras[1].getText()); - - - // Add some text to the empty header - String fText1 = "New Text!"; - String fText2 = "More Text!"; - headerF.createParagraph().insertNewRun(0).setText(fText1); - headerF.createParagraph().insertNewRun(0).setText(fText2); -// headerF.getParagraphs().get(0).insertNewRun(0).setText(fText1); - - // Check it - assertEquals(tText, headerD.getParagraphs().get(0).getText()); - assertEquals(fText1, headerF.getParagraphs().get(0).getText()); - assertEquals(fText2, headerF.getParagraphs().get(1).getText()); - - - // Save, re-open, ensure it's all still there - XWPFDocument reopened = XWPFTestDataSamples.writeOutAndReadBack(sampleDoc); - policy = reopened.getHeaderFooterPolicy(); - assertNotNull(policy.getDefaultHeader()); - assertNotNull(policy.getFirstPageHeader()); - assertNull(policy.getEvenPageHeader()); - assertNotNull(policy.getDefaultFooter()); - assertNotNull(policy.getFirstPageFooter()); - assertNull(policy.getEvenPageFooter()); - - // Check the new headers still have their text - headerD = policy.getDefaultHeader(); - headerF = policy.getFirstPageHeader(); - assertEquals(tText, headerD.getParagraphs().get(0).getText()); - assertEquals(fText1, headerF.getParagraphs().get(0).getText()); - assertEquals(fText2, headerF.getParagraphs().get(1).getText()); - - // Check the new footers have their new text too - footerD = policy.getDefaultFooter(); - paras = footerD.getParagraphs().toArray(new XWPFParagraph[0]); - footerF = policy.getFirstPageFooter(); - - assertEquals(2, paras.length); - assertEquals("First paragraph for the footer", paras[0].getText()); - assertEquals("Second paragraph for the footer", paras[1].getText()); - assertEquals(1, footerF.getParagraphs().size()); - } - - @Test - public void testSetWatermark() throws IOException { - XWPFDocument sampleDoc = XWPFTestDataSamples.openSampleDocument("SampleDoc.docx"); - - // No header is set (yet) - XWPFHeaderFooterPolicy policy = sampleDoc.getHeaderFooterPolicy(); - assertNull(policy.getDefaultHeader()); - assertNull(policy.getFirstPageHeader()); - assertNull(policy.getDefaultFooter()); - - policy.createWatermark("DRAFT"); - - assertNotNull(policy.getDefaultHeader()); - assertNotNull(policy.getFirstPageHeader()); - assertNotNull(policy.getEvenPageHeader()); - - // Re-open, and check - XWPFDocument reopened = XWPFTestDataSamples.writeOutAndReadBack(sampleDoc); - policy = reopened.getHeaderFooterPolicy(); - - assertNotNull(policy.getDefaultHeader()); - assertNotNull(policy.getFirstPageHeader()); - assertNotNull(policy.getEvenPageHeader()); - } - - @Test - public void testAddPictureData() { - // TODO - } - - @Test - public void testGetAllPictures() { - // TODO - } - - @Test - public void testGetAllPackagePictures() { - // TODO - } - - @Test - public void testGetPictureDataById() { - // TODO - } - - @Test - public void bug60293() throws Exception { - //test handling of non-standard header/footer options - XWPFDocument xwpf = XWPFTestDataSamples.openSampleDocument("60293.docx"); - assertEquals(3, xwpf.getHeaderList().size()); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFHeadings.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFHeadings.java deleted file mode 100644 index ef7620eee..000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFHeadings.java +++ /dev/null @@ -1,63 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -import java.io.IOException; - -import junit.framework.TestCase; -import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.apache.xmlbeans.XmlException; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtBlock; - -/** - * @author Paolo Mottadelli - */ -public final class TestXWPFHeadings extends TestCase { - private static final String HEADING1 = "Heading1"; - - public void testSetParagraphStyle() throws IOException, XmlException { - //new clean instance of paragraph - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("heading123.docx"); - XWPFParagraph p = doc.createParagraph(); - XWPFRun run = p.createRun(); - run.setText("Heading 1"); - - CTSdtBlock block = doc.getDocument().getBody().addNewSdt(); - - assertNull(p.getStyle()); - p.setStyle(HEADING1); - assertEquals(HEADING1, p.getCTP().getPPr().getPStyle().getVal()); - - doc.createTOC(); - /* - // TODO - finish this test - if (false) { - CTStyles styles = doc.getStyle(); - CTStyle style = styles.addNewStyle(); - style.setType(STStyleType.PARAGRAPH); - style.setStyleId("Heading1"); - } - - if (false) { - File file = TempFile.createTempFile("testHeaders", ".docx"); - OutputStream out = new FileOutputStream(file); - doc.write(out); - out.close(); - } - */ - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFNumbering.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFNumbering.java deleted file mode 100644 index 5a5ce78f5..000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFNumbering.java +++ /dev/null @@ -1,102 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xwpf.usermodel; - -import java.io.IOException; -import java.math.BigInteger; - -import junit.framework.TestCase; -import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTNum; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTNumLvl; - -public class TestXWPFNumbering extends TestCase { - - public void testCompareAbstractNum() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Numbering.docx"); - XWPFNumbering numbering = doc.getNumbering(); - BigInteger numId = BigInteger.valueOf(1); - assertTrue(numbering.numExist(numId)); - XWPFNum num = numbering.getNum(numId); - BigInteger abstrNumId = num.getCTNum().getAbstractNumId().getVal(); - XWPFAbstractNum abstractNum = numbering.getAbstractNum(abstrNumId); - BigInteger compareAbstractNum = numbering.getIdOfAbstractNum(abstractNum); - assertEquals(abstrNumId, compareAbstractNum); - } - - public void testAddNumberingToDoc() throws IOException { - BigInteger abstractNumId = BigInteger.valueOf(1); - BigInteger numId = BigInteger.valueOf(1); - - XWPFDocument docOut = new XWPFDocument(); - XWPFNumbering numbering = docOut.createNumbering(); - numId = numbering.addNum(abstractNumId); - - XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(docOut); - - numbering = docIn.getNumbering(); - assertTrue(numbering.numExist(numId)); - XWPFNum num = numbering.getNum(numId); - - BigInteger compareAbstractNum = num.getCTNum().getAbstractNumId().getVal(); - assertEquals(abstractNumId, compareAbstractNum); - } - - public void testGetNumIlvl() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Numbering.docx"); - BigInteger numIlvl = BigInteger.valueOf(0); - assertEquals(numIlvl, doc.getParagraphs().get(0).getNumIlvl()); - numIlvl = BigInteger.valueOf(1); - assertEquals(numIlvl, doc.getParagraphs().get(5).getNumIlvl()); - } - - public void testGetNumFmt() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Numbering.docx"); - assertEquals("bullet", doc.getParagraphs().get(0).getNumFmt()); - assertEquals("bullet", doc.getParagraphs().get(1).getNumFmt()); - assertEquals("bullet", doc.getParagraphs().get(2).getNumFmt()); - assertEquals("bullet", doc.getParagraphs().get(3).getNumFmt()); - assertEquals("decimal", doc.getParagraphs().get(4).getNumFmt()); - assertEquals("lowerLetter", doc.getParagraphs().get(5).getNumFmt()); - assertEquals("lowerRoman", doc.getParagraphs().get(6).getNumFmt()); - } - - public void testLvlText() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Numbering.docx"); - - assertEquals("%1.%2.%3.", doc.getParagraphs().get(12).getNumLevelText()); - - assertEquals("NEW-%1-FORMAT", doc.getParagraphs().get(14).getNumLevelText()); - - XWPFParagraph p = doc.getParagraphs().get(18); - assertEquals("%1.", p.getNumLevelText()); - //test that null doesn't throw NPE - assertNull(p.getNumFmt()); - } - - public void testOverrideList() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("NumberingWOverrides.docx"); - XWPFParagraph p = doc.getParagraphs().get(4); - XWPFNumbering numbering = doc.getNumbering(); - CTNum ctNum = numbering.getNum(p.getNumID()).getCTNum(); - assertEquals(9, ctNum.sizeOfLvlOverrideArray()); - CTNumLvl ctNumLvl = ctNum.getLvlOverrideArray(0); - assertEquals("upperLetter", ctNumLvl.getLvl().getNumFmt().getVal().toString()); - } - -} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFParagraph.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFParagraph.java deleted file mode 100644 index 718c73e70..000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFParagraph.java +++ /dev/null @@ -1,705 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xwpf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.math.BigInteger; -import java.util.List; - -import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.junit.Test; -import org.openxmlformats.schemas.drawingml.x2006.picture.CTPicture; -import org.openxmlformats.schemas.drawingml.x2006.picture.PicDocument; -import org.openxmlformats.schemas.drawingml.x2006.picture.impl.PicDocumentImpl; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBookmark; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBorder; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTInd; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTJc; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTOnOff; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPBdr; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPPr; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSpacing; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTextAlignment; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STBorder; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STJc; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STLineSpacingRule; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STOnOff; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTextAlignment; - -/** - * Tests for XWPF Paragraphs - */ -public final class TestXWPFParagraph { - - /** - * Check that we get the right paragraph from the header - * - * @throws IOException - */ - @Test - public void testHeaderParagraph() throws IOException { - XWPFDocument xml = XWPFTestDataSamples.openSampleDocument("ThreeColHead.docx"); - - XWPFHeader hdr = xml.getHeaderFooterPolicy().getDefaultHeader(); - assertNotNull(hdr); - - List ps = hdr.getParagraphs(); - assertEquals(1, ps.size()); - XWPFParagraph p = ps.get(0); - - assertEquals(5, p.getCTP().sizeOfRArray()); - assertEquals("First header column!\tMid header\tRight header!", p.getText()); - - xml.close(); - } - - /** - * Check that we get the right paragraphs from the document - * - * @throws IOException - */ - @Test - public void testDocumentParagraph() throws IOException { - XWPFDocument xml = XWPFTestDataSamples.openSampleDocument("ThreeColHead.docx"); - List ps = xml.getParagraphs(); - assertEquals(10, ps.size()); - - assertFalse(ps.get(0).isEmpty()); - assertEquals( - "This is a sample word document. It has two pages. It has a three column heading, but no footer.", - ps.get(0).getText()); - - assertTrue(ps.get(1).isEmpty()); - assertEquals("", ps.get(1).getText()); - - assertFalse(ps.get(2).isEmpty()); - assertEquals("HEADING TEXT", ps.get(2).getText()); - - assertTrue(ps.get(3).isEmpty()); - assertEquals("", ps.get(3).getText()); - - assertFalse(ps.get(4).isEmpty()); - assertEquals("More on page one", ps.get(4).getText()); - - xml.close(); - } - - @Test - public void testSetGetBorderTop() throws IOException { - //new clean instance of paragraph - XWPFDocument doc = new XWPFDocument(); - XWPFParagraph p = doc.createParagraph(); - - assertEquals(STBorder.NONE.intValue(), p.getBorderTop().getValue()); - - CTP ctp = p.getCTP(); - CTPPr ppr = ctp.getPPr() == null ? ctp.addNewPPr() : ctp.getPPr(); - - //bordi - CTPBdr bdr = ppr.addNewPBdr(); - CTBorder borderTop = bdr.addNewTop(); - borderTop.setVal(STBorder.DOUBLE); - bdr.setTop(borderTop); - - assertEquals(Borders.DOUBLE, p.getBorderTop()); - p.setBorderTop(Borders.SINGLE); - assertEquals(STBorder.SINGLE, borderTop.getVal()); - - doc.close(); - } - - @Test - public void testSetGetAlignment() throws IOException { - //new clean instance of paragraph - XWPFDocument doc = new XWPFDocument(); - XWPFParagraph p = doc.createParagraph(); - - assertEquals(STJc.LEFT.intValue(), p.getAlignment().getValue()); - - CTP ctp = p.getCTP(); - CTPPr ppr = ctp.getPPr() == null ? ctp.addNewPPr() : ctp.getPPr(); - - CTJc align = ppr.addNewJc(); - align.setVal(STJc.CENTER); - assertEquals(ParagraphAlignment.CENTER, p.getAlignment()); - - p.setAlignment(ParagraphAlignment.BOTH); - assertEquals(STJc.BOTH, ppr.getJc().getVal()); - - doc.close(); - } - - @Test - public void testSetGetSpacing() throws IOException { - XWPFDocument doc = new XWPFDocument(); - XWPFParagraph p = doc.createParagraph(); - - CTP ctp = p.getCTP(); - CTPPr ppr = ctp.getPPr() == null ? ctp.addNewPPr() : ctp.getPPr(); - - assertEquals(-1, p.getSpacingBefore()); - assertEquals(-1, p.getSpacingAfter()); - assertEquals(-1, p.getSpacingBetween(), 0.1); - assertEquals(LineSpacingRule.AUTO, p.getSpacingLineRule()); - - CTSpacing spacing = ppr.addNewSpacing(); - spacing.setAfter(new BigInteger("10")); - assertEquals(10, p.getSpacingAfter()); - spacing.setBefore(new BigInteger("10")); - assertEquals(10, p.getSpacingBefore()); - - p.setSpacingAfter(100); - assertEquals(100, spacing.getAfter().intValue()); - p.setSpacingBefore(100); - assertEquals(100, spacing.getBefore().intValue()); - - p.setSpacingBetween(.25, LineSpacingRule.EXACT); - assertEquals(.25, p.getSpacingBetween(), 0.01); - assertEquals(LineSpacingRule.EXACT, p.getSpacingLineRule()); - p.setSpacingBetween(1.25, LineSpacingRule.AUTO); - assertEquals(1.25, p.getSpacingBetween(), 0.01); - assertEquals(LineSpacingRule.AUTO, p.getSpacingLineRule()); - p.setSpacingBetween(.5, LineSpacingRule.AT_LEAST); - assertEquals(.5, p.getSpacingBetween(), 0.01); - assertEquals(LineSpacingRule.AT_LEAST, p.getSpacingLineRule()); - p.setSpacingBetween(1.15); - assertEquals(1.15, p.getSpacingBetween(), 0.01); - assertEquals(LineSpacingRule.AUTO, p.getSpacingLineRule()); - - doc.close(); - } - - @Test - public void testSetGetSpacingLineRule() throws IOException { - XWPFDocument doc = new XWPFDocument(); - XWPFParagraph p = doc.createParagraph(); - - CTP ctp = p.getCTP(); - CTPPr ppr = ctp.getPPr() == null ? ctp.addNewPPr() : ctp.getPPr(); - - assertEquals(STLineSpacingRule.INT_AUTO, p.getSpacingLineRule().getValue()); - - CTSpacing spacing = ppr.addNewSpacing(); - spacing.setLineRule(STLineSpacingRule.AT_LEAST); - assertEquals(LineSpacingRule.AT_LEAST, p.getSpacingLineRule()); - - p.setSpacingAfter(100); - assertEquals(100, spacing.getAfter().intValue()); - - doc.close(); - } - - @Test - public void testSetGetIndentation() throws IOException { - XWPFDocument doc = new XWPFDocument(); - XWPFParagraph p = doc.createParagraph(); - - assertEquals(-1, p.getIndentationLeft()); - - CTP ctp = p.getCTP(); - CTPPr ppr = ctp.getPPr() == null ? ctp.addNewPPr() : ctp.getPPr(); - - assertEquals(-1, p.getIndentationLeft()); - - CTInd ind = ppr.addNewInd(); - ind.setLeft(new BigInteger("10")); - assertEquals(10, p.getIndentationLeft()); - - p.setIndentationLeft(100); - assertEquals(100, ind.getLeft().intValue()); - - doc.close(); - } - - @Test - public void testSetGetVerticalAlignment() throws IOException { - //new clean instance of paragraph - XWPFDocument doc = new XWPFDocument(); - XWPFParagraph p = doc.createParagraph(); - - CTP ctp = p.getCTP(); - CTPPr ppr = ctp.getPPr() == null ? ctp.addNewPPr() : ctp.getPPr(); - - CTTextAlignment txtAlign = ppr.addNewTextAlignment(); - txtAlign.setVal(STTextAlignment.CENTER); - assertEquals(TextAlignment.CENTER, p.getVerticalAlignment()); - - p.setVerticalAlignment(TextAlignment.BOTTOM); - assertEquals(STTextAlignment.BOTTOM, ppr.getTextAlignment().getVal()); - - doc.close(); - } - - @Test - public void testSetGetWordWrap() throws IOException { - XWPFDocument doc = new XWPFDocument(); - XWPFParagraph p = doc.createParagraph(); - - CTP ctp = p.getCTP(); - CTPPr ppr = ctp.getPPr() == null ? ctp.addNewPPr() : ctp.getPPr(); - - CTOnOff wordWrap = ppr.addNewWordWrap(); - wordWrap.setVal(STOnOff.FALSE); - assertEquals(false, p.isWordWrap()); - - p.setWordWrapped(true); - assertEquals(STOnOff.TRUE, ppr.getWordWrap().getVal()); - - doc.close(); - } - - @Test - public void testSetGetPageBreak() throws IOException { - XWPFDocument doc = new XWPFDocument(); - XWPFParagraph p = doc.createParagraph(); - - CTP ctp = p.getCTP(); - CTPPr ppr = ctp.getPPr() == null ? ctp.addNewPPr() : ctp.getPPr(); - - CTOnOff pageBreak = ppr.addNewPageBreakBefore(); - pageBreak.setVal(STOnOff.FALSE); - assertEquals(false, p.isPageBreak()); - - p.setPageBreak(true); - assertEquals(STOnOff.TRUE, ppr.getPageBreakBefore().getVal()); - doc.close(); - } - - @Test - public void testBookmarks() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("bookmarks.docx"); - XWPFParagraph paragraph = doc.getParagraphs().get(0); - assertEquals("Sample Word Document", paragraph.getText()); - assertEquals(1, paragraph.getCTP().sizeOfBookmarkStartArray()); - assertEquals(0, paragraph.getCTP().sizeOfBookmarkEndArray()); - CTBookmark ctBookmark = paragraph.getCTP().getBookmarkStartArray(0); - assertEquals("poi", ctBookmark.getName()); - for (CTBookmark bookmark : paragraph.getCTP().getBookmarkStartList()) { - assertEquals("poi", bookmark.getName()); - } - doc.close(); - } - - @Test - public void testGetSetNumID() throws IOException { - XWPFDocument doc = new XWPFDocument(); - XWPFParagraph p = doc.createParagraph(); - - p.setNumID(new BigInteger("10")); - assertEquals("10", p.getNumID().toString()); - doc.close(); - } - - @Test - public void testAddingRuns() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx"); - - XWPFParagraph p = doc.getParagraphs().get(0); - assertEquals(2, p.getRuns().size()); - - XWPFRun r = p.createRun(); - assertEquals(3, p.getRuns().size()); - assertEquals(2, p.getRuns().indexOf(r)); - - XWPFRun r2 = p.insertNewRun(1); - assertEquals(4, p.getRuns().size()); - assertEquals(1, p.getRuns().indexOf(r2)); - assertEquals(3, p.getRuns().indexOf(r)); - - doc.close(); - } - - @Test - public void testPictures() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("VariousPictures.docx"); - assertEquals(7, doc.getParagraphs().size()); - - XWPFParagraph p; - XWPFRun r; - - // Text paragraphs - assertEquals("Sheet with various pictures", doc.getParagraphs().get(0).getText()); - assertEquals("(jpeg, png, wmf, emf and pict) ", doc.getParagraphs().get(1).getText()); - - // Spacer ones - assertEquals("", doc.getParagraphs().get(2).getText()); - assertEquals("", doc.getParagraphs().get(3).getText()); - assertEquals("", doc.getParagraphs().get(4).getText()); - - // Image one - p = doc.getParagraphs().get(5); - assertEquals(6, p.getRuns().size()); - - r = p.getRuns().get(0); - assertEquals("", r.toString()); - assertEquals(1, r.getEmbeddedPictures().size()); - assertNotNull(r.getEmbeddedPictures().get(0).getPictureData()); - assertEquals("image1.wmf", r.getEmbeddedPictures().get(0).getPictureData().getFileName()); - - r = p.getRuns().get(1); - assertEquals("", r.toString()); - assertEquals(1, r.getEmbeddedPictures().size()); - assertNotNull(r.getEmbeddedPictures().get(0).getPictureData()); - assertEquals("image2.png", r.getEmbeddedPictures().get(0).getPictureData().getFileName()); - - r = p.getRuns().get(2); - assertEquals("", r.toString()); - assertEquals(1, r.getEmbeddedPictures().size()); - assertNotNull(r.getEmbeddedPictures().get(0).getPictureData()); - assertEquals("image3.emf", r.getEmbeddedPictures().get(0).getPictureData().getFileName()); - - r = p.getRuns().get(3); - assertEquals("", r.toString()); - assertEquals(1, r.getEmbeddedPictures().size()); - assertNotNull(r.getEmbeddedPictures().get(0).getPictureData()); - assertEquals("image4.emf", r.getEmbeddedPictures().get(0).getPictureData().getFileName()); - - r = p.getRuns().get(4); - assertEquals("", r.toString()); - assertEquals(1, r.getEmbeddedPictures().size()); - assertNotNull(r.getEmbeddedPictures().get(0).getPictureData()); - assertEquals("image5.jpeg", r.getEmbeddedPictures().get(0).getPictureData().getFileName()); - - r = p.getRuns().get(5); - assertEquals(" ", r.toString()); - assertEquals(0, r.getEmbeddedPictures().size()); - - // Final spacer - assertEquals("", doc.getParagraphs().get(6).getText()); - - - // Look in detail at one - r = p.getRuns().get(4); - XWPFPicture pict = r.getEmbeddedPictures().get(0); - CTPicture picture = pict.getCTPicture(); - assertEquals("rId8", picture.getBlipFill().getBlip().getEmbed()); - - // Ensure that the ooxml compiler finds everything we need - r.getCTR().getDrawingArray(0); - r.getCTR().getDrawingArray(0).getInlineArray(0); - r.getCTR().getDrawingArray(0).getInlineArray(0).getGraphic(); - r.getCTR().getDrawingArray(0).getInlineArray(0).getGraphic().getGraphicData(); - PicDocument pd = new PicDocumentImpl(null); - assertTrue(pd.isNil()); - - doc.close(); - } - - @Test - public void testTika792() throws Exception { - //This test forces the loading of CTMoveBookmark and - //CTMoveBookmarkImpl into ooxml-lite. - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Tika-792.docx"); - XWPFParagraph paragraph = doc.getParagraphs().get(0); - assertEquals("s", paragraph.getText()); - doc.close(); - } - - @Test - public void testSettersGetters() throws IOException { - XWPFDocument doc = new XWPFDocument(); - XWPFParagraph p = doc.createParagraph(); - - assertTrue(p.isEmpty()); - assertFalse(p.removeRun(0)); - - p.setBorderTop(Borders.BABY_PACIFIER); - p.setBorderBetween(Borders.BABY_PACIFIER); - p.setBorderBottom(Borders.BABY_RATTLE); - - assertNotNull(p.getIRuns()); - assertEquals(0, p.getIRuns().size()); - assertFalse(p.isEmpty()); - assertNull(p.getStyleID()); - assertNull(p.getStyle()); - - assertNull(p.getNumID()); - p.setNumID(BigInteger.valueOf(12)); - assertEquals(BigInteger.valueOf(12), p.getNumID()); - p.setNumID(BigInteger.valueOf(13)); - assertEquals(BigInteger.valueOf(13), p.getNumID()); - - assertNull(p.getNumFmt()); - - assertNull(p.getNumIlvl()); - - assertEquals("", p.getParagraphText()); - assertEquals("", p.getPictureText()); - assertEquals("", p.getFootnoteText()); - - p.setBorderBetween(Borders.NONE); - assertEquals(Borders.NONE, p.getBorderBetween()); - p.setBorderBetween(Borders.BASIC_BLACK_DASHES); - assertEquals(Borders.BASIC_BLACK_DASHES, p.getBorderBetween()); - - p.setBorderBottom(Borders.NONE); - assertEquals(Borders.NONE, p.getBorderBottom()); - p.setBorderBottom(Borders.BABY_RATTLE); - assertEquals(Borders.BABY_RATTLE, p.getBorderBottom()); - - p.setBorderLeft(Borders.NONE); - assertEquals(Borders.NONE, p.getBorderLeft()); - p.setBorderLeft(Borders.BASIC_WHITE_SQUARES); - assertEquals(Borders.BASIC_WHITE_SQUARES, p.getBorderLeft()); - - p.setBorderRight(Borders.NONE); - assertEquals(Borders.NONE, p.getBorderRight()); - p.setBorderRight(Borders.BASIC_WHITE_DASHES); - assertEquals(Borders.BASIC_WHITE_DASHES, p.getBorderRight()); - - p.setBorderBottom(Borders.NONE); - assertEquals(Borders.NONE, p.getBorderBottom()); - p.setBorderBottom(Borders.BASIC_WHITE_DOTS); - assertEquals(Borders.BASIC_WHITE_DOTS, p.getBorderBottom()); - - assertFalse(p.isPageBreak()); - p.setPageBreak(true); - assertTrue(p.isPageBreak()); - p.setPageBreak(false); - assertFalse(p.isPageBreak()); - - assertEquals(-1, p.getSpacingAfter()); - p.setSpacingAfter(12); - assertEquals(12, p.getSpacingAfter()); - - assertEquals(-1, p.getSpacingAfterLines()); - p.setSpacingAfterLines(14); - assertEquals(14, p.getSpacingAfterLines()); - - assertEquals(-1, p.getSpacingBefore()); - p.setSpacingBefore(16); - assertEquals(16, p.getSpacingBefore()); - - assertEquals(-1, p.getSpacingBeforeLines()); - p.setSpacingBeforeLines(18); - assertEquals(18, p.getSpacingBeforeLines()); - - assertEquals(LineSpacingRule.AUTO, p.getSpacingLineRule()); - p.setSpacingLineRule(LineSpacingRule.EXACT); - assertEquals(LineSpacingRule.EXACT, p.getSpacingLineRule()); - - assertEquals(-1, p.getIndentationLeft()); - p.setIndentationLeft(21); - assertEquals(21, p.getIndentationLeft()); - - assertEquals(-1, p.getIndentationRight()); - p.setIndentationRight(25); - assertEquals(25, p.getIndentationRight()); - - assertEquals(-1, p.getIndentationHanging()); - p.setIndentationHanging(25); - assertEquals(25, p.getIndentationHanging()); - - assertEquals(-1, p.getIndentationFirstLine()); - p.setIndentationFirstLine(25); - assertEquals(25, p.getIndentationFirstLine()); - - assertFalse(p.isWordWrap()); - p.setWordWrapped(true); - assertTrue(p.isWordWrap()); - p.setWordWrapped(false); - assertFalse(p.isWordWrap()); - - assertNull(p.getStyle()); - p.setStyle("teststyle"); - assertEquals("teststyle", p.getStyle()); - - p.addRun(CTR.Factory.newInstance()); - - //assertTrue(p.removeRun(0)); - - assertNotNull(p.getBody()); - assertEquals(BodyElementType.PARAGRAPH, p.getElementType()); - assertEquals(BodyType.DOCUMENT, p.getPartType()); - - doc.close(); - } - - @Test - public void testSearchTextNotFound() throws IOException { - XWPFDocument doc = new XWPFDocument(); - XWPFParagraph p = doc.createParagraph(); - - assertNull(p.searchText("test", new PositionInParagraph())); - assertEquals("", p.getText()); - doc.close(); - } - - @Test - public void testSearchTextFound() throws IOException { - XWPFDocument xml = XWPFTestDataSamples.openSampleDocument("ThreeColHead.docx"); - - List ps = xml.getParagraphs(); - assertEquals(10, ps.size()); - - XWPFParagraph p = ps.get(0); - - TextSegement segment = p.searchText("sample word document", new PositionInParagraph()); - assertNotNull(segment); - - assertEquals("sample word document", p.getText(segment)); - - assertTrue(p.removeRun(0)); - xml.close(); - } - - @Test - public void testFieldRuns() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("FldSimple.docx"); - List ps = doc.getParagraphs(); - assertEquals(1, ps.size()); - - XWPFParagraph p = ps.get(0); - assertEquals(1, p.getRuns().size()); - assertEquals(1, p.getIRuns().size()); - - XWPFRun r = p.getRuns().get(0); - assertEquals(XWPFFieldRun.class, r.getClass()); - - XWPFFieldRun fr = (XWPFFieldRun)r; - assertEquals(" FILENAME \\* MERGEFORMAT ", fr.getFieldInstruction()); - assertEquals("FldSimple.docx", fr.text()); - assertEquals("FldSimple.docx", p.getText()); - doc.close(); - } - - @SuppressWarnings("deprecation") - @Test - public void testRuns() throws IOException { - XWPFDocument doc = new XWPFDocument(); - XWPFParagraph p = doc.createParagraph(); - - CTR run = CTR.Factory.newInstance(); - XWPFRun r = new XWPFRun(run, doc.createParagraph()); - p.addRun(r); - p.addRun(r); - - assertNotNull(p.getRun(run)); - assertNull(p.getRun(null)); - doc.close(); - } - - @Test - public void test58067() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("58067.docx"); - - StringBuilder str = new StringBuilder(); - for(XWPFParagraph par : doc.getParagraphs()) { - str.append(par.getText()).append("\n"); - } - assertEquals("This is a test.\n\n\n\n3\n4\n5\n\n\n\nThis is a whole paragraph where one word is deleted.\n", str.toString()); - } - - /** - * Tests for numbered lists - * - * See also https://github.com/jimklo/apache-poi-sample/blob/master/src/main/java/com/sri/jklo/StyledDocument.java - * for someone else trying a similar thing - */ - @Test - public void testNumberedLists() throws Exception { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("ComplexNumberedLists.docx"); - XWPFParagraph p; - - p = doc.getParagraphArray(0); - assertEquals("This is a document with numbered lists", p.getText()); - assertEquals(null, p.getNumID()); - assertEquals(null, p.getNumIlvl()); - assertEquals(null, p.getNumStartOverride()); - - p = doc.getParagraphArray(1); - assertEquals("Entry #1", p.getText()); - assertEquals(BigInteger.valueOf(1), p.getNumID()); - assertEquals(BigInteger.valueOf(0), p.getNumIlvl()); - assertEquals(null, p.getNumStartOverride()); - - p = doc.getParagraphArray(2); - assertEquals("Entry #2, with children", p.getText()); - assertEquals(BigInteger.valueOf(1), p.getNumID()); - assertEquals(BigInteger.valueOf(0), p.getNumIlvl()); - assertEquals(null, p.getNumStartOverride()); - - p = doc.getParagraphArray(3); - assertEquals("2-a", p.getText()); - assertEquals(BigInteger.valueOf(1), p.getNumID()); - assertEquals(BigInteger.valueOf(1), p.getNumIlvl()); - assertEquals(null, p.getNumStartOverride()); - - p = doc.getParagraphArray(4); - assertEquals("2-b", p.getText()); - assertEquals(BigInteger.valueOf(1), p.getNumID()); - assertEquals(BigInteger.valueOf(1), p.getNumIlvl()); - assertEquals(null, p.getNumStartOverride()); - - p = doc.getParagraphArray(5); - assertEquals("2-c", p.getText()); - assertEquals(BigInteger.valueOf(1), p.getNumID()); - assertEquals(BigInteger.valueOf(1), p.getNumIlvl()); - assertEquals(null, p.getNumStartOverride()); - - p = doc.getParagraphArray(6); - assertEquals("Entry #3", p.getText()); - assertEquals(BigInteger.valueOf(1), p.getNumID()); - assertEquals(BigInteger.valueOf(0), p.getNumIlvl()); - assertEquals(null, p.getNumStartOverride()); - - p = doc.getParagraphArray(7); - assertEquals("Entry #4", p.getText()); - assertEquals(BigInteger.valueOf(1), p.getNumID()); - assertEquals(BigInteger.valueOf(0), p.getNumIlvl()); - assertEquals(null, p.getNumStartOverride()); - - // New list - p = doc.getParagraphArray(8); - assertEquals("Restarted to 1 from 5", p.getText()); - assertEquals(BigInteger.valueOf(2), p.getNumID()); - assertEquals(BigInteger.valueOf(0), p.getNumIlvl()); - assertEquals(null, p.getNumStartOverride()); - - p = doc.getParagraphArray(9); - assertEquals("Restarted @ 2", p.getText()); - assertEquals(BigInteger.valueOf(2), p.getNumID()); - assertEquals(BigInteger.valueOf(0), p.getNumIlvl()); - assertEquals(null, p.getNumStartOverride()); - - p = doc.getParagraphArray(10); - assertEquals("Restarted @ 3", p.getText()); - assertEquals(BigInteger.valueOf(2), p.getNumID()); - assertEquals(BigInteger.valueOf(0), p.getNumIlvl()); - assertEquals(null, p.getNumStartOverride()); - - // New list starting at 10 - p = doc.getParagraphArray(11); - assertEquals("Jump to new list at 10", p.getText()); - assertEquals(BigInteger.valueOf(6), p.getNumID()); - assertEquals(BigInteger.valueOf(0), p.getNumIlvl()); - // TODO Why isn't this seen as 10? - assertEquals(null, p.getNumStartOverride()); - - // TODO Shouldn't we use XWPFNumbering or similar here? - // TODO Make it easier to change - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFPictureData.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFPictureData.java deleted file mode 100644 index f4c0a49c0..000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFPictureData.java +++ /dev/null @@ -1,179 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xwpf.usermodel; - -import static org.junit.Assert.assertArrayEquals; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.util.List; - -import junit.framework.TestCase; - -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.PackageRelationship; -import org.apache.poi.xssf.usermodel.XSSFRelation; -import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy; - -public class TestXWPFPictureData extends TestCase { - - public void testRead() throws InvalidFormatException, IOException { - XWPFDocument sampleDoc = XWPFTestDataSamples.openSampleDocument("VariousPictures.docx"); - List pictures = sampleDoc.getAllPictures(); - - assertEquals(5, pictures.size()); - String[] ext = {"wmf", "png", "emf", "emf", "jpeg"}; - for (int i = 0; i < pictures.size(); i++) { - assertEquals(ext[i], pictures.get(i).suggestFileExtension()); - } - - int num = pictures.size(); - - byte[] pictureData = XWPFTestDataSamples.getImage("nature1.jpg"); - - String relationId = sampleDoc.addPictureData(pictureData, XWPFDocument.PICTURE_TYPE_JPEG); - // picture list was updated - assertEquals(num + 1, pictures.size()); - XWPFPictureData pict = (XWPFPictureData) sampleDoc.getRelationById(relationId); - assertEquals("jpeg", pict.suggestFileExtension()); - assertArrayEquals(pictureData, pict.getData()); - } - - public void testPictureInHeader() throws IOException { - XWPFDocument sampleDoc = XWPFTestDataSamples.openSampleDocument("headerPic.docx"); - verifyOneHeaderPicture(sampleDoc); - - XWPFDocument readBack = XWPFTestDataSamples.writeOutAndReadBack(sampleDoc); - verifyOneHeaderPicture(readBack); - } - - public void testCreateHeaderPicture() throws Exception { - XWPFDocument doc = new XWPFDocument(); - - // Starts with no header - XWPFHeaderFooterPolicy policy = doc.getHeaderFooterPolicy(); - assertNull(policy); - - // Add a default header - policy = doc.createHeaderFooterPolicy(); - XWPFHeader header = policy.createHeader(XWPFHeaderFooterPolicy.DEFAULT); - header.createParagraph().createRun().setText("Hello, Header World!"); - header.createParagraph().createRun().setText("Paragraph 2"); - assertEquals(0, header.getAllPictures().size()); - assertEquals(2, header.getParagraphs().size()); - - // Add a picture to the first paragraph - header.getParagraphs().get(0).getRuns().get(0).addPicture( - new ByteArrayInputStream(new byte[] {1,2,3,4}), - Document.PICTURE_TYPE_JPEG, "test.jpg", 2, 2); - - // Check - verifyOneHeaderPicture(doc); - - // Save, re-load, re-check - XWPFDocument readBack = XWPFTestDataSamples.writeOutAndReadBack(doc); - verifyOneHeaderPicture(readBack); - } - - private void verifyOneHeaderPicture(XWPFDocument sampleDoc) { - XWPFHeaderFooterPolicy policy = sampleDoc.getHeaderFooterPolicy(); - - XWPFHeader header = policy.getDefaultHeader(); - - List pictures = header.getAllPictures(); - assertEquals(1, pictures.size()); - } - - public void testNew() throws InvalidFormatException, IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("EmptyDocumentWithHeaderFooter.docx"); - byte[] jpegData = XWPFTestDataSamples.getImage("nature1.jpg"); - assertNotNull(jpegData); - byte[] gifData = XWPFTestDataSamples.getImage("nature1.gif"); - assertNotNull(gifData); - byte[] pngData = XWPFTestDataSamples.getImage("nature1.png"); - assertNotNull(pngData); - - List pictures = doc.getAllPictures(); - assertEquals(0, pictures.size()); - - // Document shouldn't have any image relationships - assertEquals(13, doc.getPackagePart().getRelationships().size()); - for (PackageRelationship rel : doc.getPackagePart().getRelationships()) { - if (rel.getRelationshipType().equals(XSSFRelation.IMAGE_JPEG.getRelation())) { - fail("Shouldn't have JPEG yet"); - } - } - - // Add the image - String relationId = doc.addPictureData(jpegData, XWPFDocument.PICTURE_TYPE_JPEG); - assertEquals(1, pictures.size()); - XWPFPictureData jpgPicData = (XWPFPictureData) doc.getRelationById(relationId); - assertEquals("jpeg", jpgPicData.suggestFileExtension()); - assertArrayEquals(jpegData, jpgPicData.getData()); - - // Ensure it now has one - assertEquals(14, doc.getPackagePart().getRelationships().size()); - PackageRelationship jpegRel = null; - for (PackageRelationship rel : doc.getPackagePart().getRelationships()) { - if (rel.getRelationshipType().equals(XWPFRelation.IMAGE_JPEG.getRelation())) { - if (jpegRel != null) - fail("Found 2 jpegs!"); - jpegRel = rel; - } - } - assertNotNull("JPEG Relationship not found", jpegRel); - - // Check the details - assertNotNull(jpegRel); - assertEquals(XWPFRelation.IMAGE_JPEG.getRelation(), jpegRel.getRelationshipType()); - assertEquals("/word/document.xml", jpegRel.getSource().getPartName().toString()); - assertEquals("/word/media/image1.jpeg", jpegRel.getTargetURI().getPath()); - - XWPFPictureData pictureDataByID = doc.getPictureDataByID(jpegRel.getId()); - assertArrayEquals(jpegData, pictureDataByID.getData()); - - // Save an re-load, check it appears - doc = XWPFTestDataSamples.writeOutAndReadBack(doc); - assertEquals(1, doc.getAllPictures().size()); - assertEquals(1, doc.getAllPackagePictures().size()); - - // verify the picture that we read back in - pictureDataByID = doc.getPictureDataByID(jpegRel.getId()); - assertArrayEquals(jpegData, pictureDataByID.getData()); - - } - - public void testBug51770() throws InvalidFormatException, IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Bug51170.docx"); - XWPFHeaderFooterPolicy policy = doc.getHeaderFooterPolicy(); - XWPFHeader header = policy.getDefaultHeader(); - for (XWPFParagraph paragraph : header.getParagraphs()) { - for (XWPFRun run : paragraph.getRuns()) { - for (XWPFPicture picture : run.getEmbeddedPictures()) { - if (paragraph.getDocument() != null) { - //System.out.println(picture.getCTPicture()); - XWPFPictureData data = picture.getPictureData(); - if (data != null) System.out.println(data.getFileName()); - } - } - } - } - - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFRun.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFRun.java deleted file mode 100644 index a603ab276..000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFRun.java +++ /dev/null @@ -1,638 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.math.BigInteger; -import java.util.Iterator; -import java.util.List; - -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.util.Units; -import org.apache.poi.wp.usermodel.HeaderFooterType; -import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.openxmlformats.schemas.drawingml.x2006.main.CTBlip; -import org.openxmlformats.schemas.drawingml.x2006.main.CTBlipFillProperties; -import org.openxmlformats.schemas.drawingml.x2006.picture.CTPicture; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBr; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTOnOff; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPr; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STBrClear; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STHighlightColor; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STOnOff; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STUnderline; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STVerticalAlignRun; - -/** - * Tests for XWPF Run - */ -public class TestXWPFRun { - private CTR ctRun; - private XWPFParagraph p; - private IRunBody irb; - private XWPFDocument doc; - - @Before - public void setUp() { - doc = new XWPFDocument(); - p = doc.createParagraph(); - irb = p; - - this.ctRun = CTR.Factory.newInstance(); - } - - @After - public void tearDown() throws Exception { - doc.close(); - } - - @Test - public void testSetGetText() { - ctRun.addNewT().setStringValue("TEST STRING"); - ctRun.addNewT().setStringValue("TEST2 STRING"); - ctRun.addNewT().setStringValue("TEST3 STRING"); - - assertEquals(3, ctRun.sizeOfTArray()); - XWPFRun run = new XWPFRun(ctRun, irb); - - assertEquals("TEST2 STRING", run.getText(1)); - - run.setText("NEW STRING", 0); - assertEquals("NEW STRING", run.getText(0)); - - //run.setText("xxx",14); - //fail("Position wrong"); - } - - /* - * bug 59208 - * Purpose: test all valid boolean-like values - * exercise isCTOnOff(CTOnOff) through all valid permutations - */ - @Test - public void testCTOnOff() { - CTRPr rpr = ctRun.addNewRPr(); - CTOnOff bold = rpr.addNewB(); - XWPFRun run = new XWPFRun(ctRun, irb); - - // True values: "true", "1", "on" - bold.setVal(STOnOff.TRUE); - assertEquals(true, run.isBold()); - - bold.setVal(STOnOff.X_1); - assertEquals(true, run.isBold()); - - bold.setVal(STOnOff.ON); - assertEquals(true, run.isBold()); - - // False values: "false", "0", "off" - bold.setVal(STOnOff.FALSE); - assertEquals(false, run.isBold()); - - bold.setVal(STOnOff.X_0); - assertEquals(false, run.isBold()); - - bold.setVal(STOnOff.OFF); - assertEquals(false, run.isBold()); - } - - @Test - public void testSetGetBold() { - CTRPr rpr = ctRun.addNewRPr(); - rpr.addNewB().setVal(STOnOff.TRUE); - - XWPFRun run = new XWPFRun(ctRun, irb); - assertEquals(true, run.isBold()); - - run.setBold(false); - // Implementation detail: POI natively prefers , - // but should correctly read val="0" and val="off" - assertEquals(STOnOff.FALSE, rpr.getB().getVal()); - } - - @Test - public void testSetGetItalic() { - CTRPr rpr = ctRun.addNewRPr(); - rpr.addNewI().setVal(STOnOff.TRUE); - - XWPFRun run = new XWPFRun(ctRun, irb); - assertEquals(true, run.isItalic()); - - run.setItalic(false); - assertEquals(STOnOff.FALSE, rpr.getI().getVal()); - } - - @Test - public void testSetGetStrike() { - CTRPr rpr = ctRun.addNewRPr(); - rpr.addNewStrike().setVal(STOnOff.TRUE); - - XWPFRun run = new XWPFRun(ctRun, irb); - assertEquals(true, run.isStrikeThrough()); - - run.setStrikeThrough(false); - assertEquals(STOnOff.FALSE, rpr.getStrike().getVal()); - } - - @Test - public void testSetGetUnderline() { - CTRPr rpr = ctRun.addNewRPr(); - rpr.addNewU().setVal(STUnderline.DASH); - - XWPFRun run = new XWPFRun(ctRun, irb); - assertEquals(UnderlinePatterns.DASH.getValue(), run.getUnderline() - .getValue()); - - run.setUnderline(UnderlinePatterns.NONE); - assertEquals(STUnderline.NONE.intValue(), rpr.getU().getVal() - .intValue()); - } - - @Test - public void testSetGetVAlign() { - CTRPr rpr = ctRun.addNewRPr(); - rpr.addNewVertAlign().setVal(STVerticalAlignRun.SUBSCRIPT); - - XWPFRun run = new XWPFRun(ctRun, irb); - assertEquals(VerticalAlign.SUBSCRIPT, run.getSubscript()); - - run.setSubscript(VerticalAlign.BASELINE); - assertEquals(STVerticalAlignRun.BASELINE, rpr.getVertAlign().getVal()); - } - - @Test - public void testSetGetFontFamily() { - CTRPr rpr = ctRun.addNewRPr(); - rpr.addNewRFonts().setAscii("Times New Roman"); - - XWPFRun run = new XWPFRun(ctRun, irb); - assertEquals("Times New Roman", run.getFontFamily()); - - run.setFontFamily("Verdana"); - assertEquals("Verdana", rpr.getRFonts().getAscii()); - } - - @Test - public void testSetGetFontSize() { - CTRPr rpr = ctRun.addNewRPr(); - rpr.addNewSz().setVal(new BigInteger("14")); - - XWPFRun run = new XWPFRun(ctRun, irb); - assertEquals(7, run.getFontSize()); - - run.setFontSize(24); - assertEquals(48, rpr.getSz().getVal().longValue()); - } - - @Test - public void testSetGetTextForegroundBackground() { - CTRPr rpr = ctRun.addNewRPr(); - rpr.addNewPosition().setVal(new BigInteger("4000")); - - XWPFRun run = new XWPFRun(ctRun, irb); - assertEquals(4000, run.getTextPosition()); - - run.setTextPosition(2400); - assertEquals(2400, rpr.getPosition().getVal().longValue()); - } - - @Test - public void testSetGetColor() { - XWPFRun run = new XWPFRun(ctRun, irb); - run.setColor("0F0F0F"); - String clr = run.getColor(); - assertEquals("0F0F0F", clr); - } - - @Test - public void testAddCarriageReturn() { - ctRun.addNewT().setStringValue("TEST STRING"); - ctRun.addNewCr(); - ctRun.addNewT().setStringValue("TEST2 STRING"); - ctRun.addNewCr(); - ctRun.addNewT().setStringValue("TEST3 STRING"); - assertEquals(2, ctRun.sizeOfCrArray()); - - XWPFRun run = new XWPFRun(CTR.Factory.newInstance(), irb); - run.setText("T1"); - run.addCarriageReturn(); - run.addCarriageReturn(); - run.setText("T2"); - run.addCarriageReturn(); - assertEquals(3, run.getCTR().sizeOfCrArray()); - - assertEquals("T1\n\nT2\n", run.toString()); - } - - @Test - public void testAddTabsAndLineBreaks() { - ctRun.addNewT().setStringValue("TEST STRING"); - ctRun.addNewCr(); - ctRun.addNewT().setStringValue("TEST2 STRING"); - ctRun.addNewTab(); - ctRun.addNewT().setStringValue("TEST3 STRING"); - assertEquals(1, ctRun.sizeOfCrArray()); - assertEquals(1, ctRun.sizeOfTabArray()); - - XWPFRun run = new XWPFRun(CTR.Factory.newInstance(), irb); - run.setText("T1"); - run.addCarriageReturn(); - run.setText("T2"); - run.addTab(); - run.setText("T3"); - assertEquals(1, run.getCTR().sizeOfCrArray()); - assertEquals(1, run.getCTR().sizeOfTabArray()); - - assertEquals("T1\nT2\tT3", run.toString()); - } - - @Test - public void testAddPageBreak() { - ctRun.addNewT().setStringValue("TEST STRING"); - ctRun.addNewBr(); - ctRun.addNewT().setStringValue("TEST2 STRING"); - CTBr breac = ctRun.addNewBr(); - breac.setClear(STBrClear.LEFT); - ctRun.addNewT().setStringValue("TEST3 STRING"); - assertEquals(2, ctRun.sizeOfBrArray()); - - XWPFRun run = new XWPFRun(CTR.Factory.newInstance(), irb); - run.setText("TEXT1"); - run.addBreak(); - run.setText("TEXT2"); - run.addBreak(BreakType.TEXT_WRAPPING); - assertEquals(2, run.getCTR().sizeOfBrArray()); - } - - /** - * Test that on an existing document, we do the - * right thing with it - * - * @throws IOException - */ - @Test - public void testExisting() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestDocument.docx"); - XWPFParagraph p; - XWPFRun run; - - - // First paragraph is simple - p = doc.getParagraphArray(0); - assertEquals("This is a test document.", p.getText()); - assertEquals(2, p.getRuns().size()); - - run = p.getRuns().get(0); - assertEquals("This is a test document", run.toString()); - assertEquals(false, run.isBold()); - assertEquals(false, run.isItalic()); - assertEquals(false, run.isStrikeThrough()); - assertEquals(null, run.getCTR().getRPr()); - - run = p.getRuns().get(1); - assertEquals(".", run.toString()); - assertEquals(false, run.isBold()); - assertEquals(false, run.isItalic()); - assertEquals(false, run.isStrikeThrough()); - assertEquals(null, run.getCTR().getRPr()); - - - // Next paragraph is all in one style, but a different one - p = doc.getParagraphArray(1); - assertEquals("This bit is in bold and italic", p.getText()); - assertEquals(1, p.getRuns().size()); - - run = p.getRuns().get(0); - assertEquals("This bit is in bold and italic", run.toString()); - assertEquals(true, run.isBold()); - assertEquals(true, run.isItalic()); - assertEquals(false, run.isStrikeThrough()); - assertEquals(true, run.getCTR().getRPr().isSetB()); - assertEquals(false, run.getCTR().getRPr().getB().isSetVal()); - - - // Back to normal - p = doc.getParagraphArray(2); - assertEquals("Back to normal", p.getText()); - assertEquals(1, p.getRuns().size()); - - run = p.getRuns().get(0); - assertEquals("Back to normal", run.toString()); - assertEquals(false, run.isBold()); - assertEquals(false, run.isItalic()); - assertEquals(false, run.isStrikeThrough()); - assertEquals(null, run.getCTR().getRPr()); - - - // Different styles in one paragraph - p = doc.getParagraphArray(3); - assertEquals("This contains BOLD, ITALIC and BOTH, as well as RED and YELLOW text.", p.getText()); - assertEquals(11, p.getRuns().size()); - - run = p.getRuns().get(0); - assertEquals("This contains ", run.toString()); - assertEquals(false, run.isBold()); - assertEquals(false, run.isItalic()); - assertEquals(false, run.isStrikeThrough()); - assertEquals(null, run.getCTR().getRPr()); - - run = p.getRuns().get(1); - assertEquals("BOLD", run.toString()); - assertEquals(true, run.isBold()); - assertEquals(false, run.isItalic()); - assertEquals(false, run.isStrikeThrough()); - - run = p.getRuns().get(2); - assertEquals(", ", run.toString()); - assertEquals(false, run.isBold()); - assertEquals(false, run.isItalic()); - assertEquals(false, run.isStrikeThrough()); - assertEquals(null, run.getCTR().getRPr()); - - run = p.getRuns().get(3); - assertEquals("ITALIC", run.toString()); - assertEquals(false, run.isBold()); - assertEquals(true, run.isItalic()); - assertEquals(false, run.isStrikeThrough()); - - run = p.getRuns().get(4); - assertEquals(" and ", run.toString()); - assertEquals(false, run.isBold()); - assertEquals(false, run.isItalic()); - assertEquals(false, run.isStrikeThrough()); - assertEquals(null, run.getCTR().getRPr()); - - run = p.getRuns().get(5); - assertEquals("BOTH", run.toString()); - assertEquals(true, run.isBold()); - assertEquals(true, run.isItalic()); - assertEquals(false, run.isStrikeThrough()); - - run = p.getRuns().get(6); - assertEquals(", as well as ", run.toString()); - assertEquals(false, run.isBold()); - assertEquals(false, run.isItalic()); - assertEquals(false, run.isStrikeThrough()); - assertEquals(null, run.getCTR().getRPr()); - - run = p.getRuns().get(7); - assertEquals("RED", run.toString()); - assertEquals(false, run.isBold()); - assertEquals(false, run.isItalic()); - assertEquals(false, run.isStrikeThrough()); - - run = p.getRuns().get(8); - assertEquals(" and ", run.toString()); - assertEquals(false, run.isBold()); - assertEquals(false, run.isItalic()); - assertEquals(false, run.isStrikeThrough()); - assertEquals(null, run.getCTR().getRPr()); - - run = p.getRuns().get(9); - assertEquals("YELLOW", run.toString()); - assertEquals(false, run.isBold()); - assertEquals(false, run.isItalic()); - assertEquals(false, run.isStrikeThrough()); - - run = p.getRuns().get(10); - assertEquals(" text.", run.toString()); - assertEquals(false, run.isBold()); - assertEquals(false, run.isItalic()); - assertEquals(false, run.isStrikeThrough()); - assertEquals(null, run.getCTR().getRPr()); - - doc.close(); - } - - @Test - public void testPictureInHeader() throws IOException { - XWPFDocument sampleDoc = XWPFTestDataSamples.openSampleDocument("headerPic.docx"); - XWPFHeaderFooterPolicy policy = sampleDoc.getHeaderFooterPolicy(); - - XWPFHeader header = policy.getDefaultHeader(); - - int count = 0; - - for (XWPFParagraph p : header.getParagraphs()) { - for (XWPFRun r : p.getRuns()) { - List pictures = r.getEmbeddedPictures(); - - for (XWPFPicture pic : pictures) { - assertNotNull(pic.getPictureData()); - assertEquals("DOZOR", pic.getDescription()); - } - - count += pictures.size(); - } - } - - assertEquals(1, count); - sampleDoc.close(); - } - - @Test - public void testSetGetHighlight() throws IOException { - XWPFRun run = p.createRun(); - assertEquals(false, run.isHighlighted()); - - // TODO Do this using XWPFRun methods - run.getCTR().addNewRPr().addNewHighlight().setVal(STHighlightColor.NONE); - assertEquals(false, run.isHighlighted()); - run.getCTR().getRPr().getHighlight().setVal(STHighlightColor.CYAN); - assertEquals(true, run.isHighlighted()); - run.getCTR().getRPr().getHighlight().setVal(STHighlightColor.NONE); - assertEquals(false, run.isHighlighted()); - } - - @Test - public void testAddPicture() throws Exception { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestDocument.docx"); - XWPFParagraph p = doc.getParagraphArray(2); - XWPFRun r = p.getRuns().get(0); - - assertEquals(0, doc.getAllPictures().size()); - assertEquals(0, r.getEmbeddedPictures().size()); - - r.addPicture(new ByteArrayInputStream(new byte[0]), Document.PICTURE_TYPE_JPEG, "test.jpg", 21, 32); - - assertEquals(1, doc.getAllPictures().size()); - assertEquals(1, r.getEmbeddedPictures().size()); - - XWPFDocument docBack = XWPFTestDataSamples.writeOutAndReadBack(doc); - XWPFParagraph pBack = docBack.getParagraphArray(2); - XWPFRun rBack = pBack.getRuns().get(0); - - assertEquals(1, docBack.getAllPictures().size()); - assertEquals(1, rBack.getEmbeddedPictures().size()); - docBack.close(); - doc.close(); - } - - /** - * Bugzilla #58237 - Unable to add image to word document header - */ - @Test - public void testAddPictureInHeader() throws IOException, InvalidFormatException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("TestDocument.docx"); - XWPFHeader hdr = doc.createHeader(HeaderFooterType.DEFAULT); - XWPFParagraph p = hdr.createParagraph(); - XWPFRun r = p.createRun(); - - assertEquals(0, hdr.getAllPictures().size()); - assertEquals(0, r.getEmbeddedPictures().size()); - - r.addPicture(new ByteArrayInputStream(new byte[0]), Document.PICTURE_TYPE_JPEG, "test.jpg", 21, 32); - - assertEquals(1, hdr.getAllPictures().size()); - assertEquals(1, r.getEmbeddedPictures().size()); - - XWPFPicture pic = r.getEmbeddedPictures().get(0); - CTPicture ctPic = pic.getCTPicture(); - CTBlipFillProperties ctBlipFill = ctPic.getBlipFill(); - - assertNotNull(ctBlipFill); - - CTBlip ctBlip = ctBlipFill.getBlip(); - - assertNotNull(ctBlip); - assertEquals("rId1", ctBlip.getEmbed()); - - XWPFDocument docBack = XWPFTestDataSamples.writeOutAndReadBack(doc); - XWPFHeader hdrBack = docBack.getHeaderArray(0); - XWPFParagraph pBack = hdrBack.getParagraphArray(0); - XWPFRun rBack = pBack.getRuns().get(0); - - assertEquals(1, hdrBack.getAllPictures().size()); - assertEquals(1, rBack.getEmbeddedPictures().size()); - docBack.close(); - doc.close(); - } - - /** - * Bugzilla #52288 - setting the font family on the - * run mustn't NPE - */ - @Test - public void testSetFontFamily_52288() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("52288.docx"); - final Iterator paragraphs = doc.getParagraphsIterator(); - while (paragraphs.hasNext()) { - final XWPFParagraph paragraph = paragraphs.next(); - for (final XWPFRun run : paragraph.getRuns()) { - if (run != null) { - final String text = run.getText(0); - if (text != null) { - run.setFontFamily("Times New Roman"); - } - } - } - } - doc.close(); - } - - @Test - public void testBug55476() throws IOException, InvalidFormatException { - byte[] image = XWPFTestDataSamples.getImage("abstract1.jpg"); - XWPFDocument document = new XWPFDocument(); - - document.createParagraph().createRun().addPicture( - new ByteArrayInputStream(image), Document.PICTURE_TYPE_JPEG, "test.jpg", Units.toEMU(300), Units.toEMU(100)); - - XWPFDocument docBack = XWPFTestDataSamples.writeOutAndReadBack(document); - List pictures = docBack.getParagraphArray(0).getRuns().get(0).getEmbeddedPictures(); - assertEquals(1, pictures.size()); - docBack.close(); - - /*OutputStream stream = new FileOutputStream("c:\\temp\\55476.docx"); - try { - document.write(stream); - } finally { - stream.close(); - }*/ - - document.close(); - } - - @Test - public void testBug58922() throws IOException { - XWPFDocument document = new XWPFDocument(); - - final XWPFRun run = document.createParagraph().createRun(); - - - assertEquals(-1, run.getFontSize()); - - run.setFontSize(10); - assertEquals(10, run.getFontSize()); - - run.setFontSize(Short.MAX_VALUE-1); - assertEquals(Short.MAX_VALUE-1, run.getFontSize()); - - run.setFontSize(Short.MAX_VALUE); - assertEquals(Short.MAX_VALUE, run.getFontSize()); - - run.setFontSize(Short.MAX_VALUE+1); - assertEquals(Short.MAX_VALUE+1, run.getFontSize()); - - run.setFontSize(Integer.MAX_VALUE-1); - assertEquals(Integer.MAX_VALUE-1, run.getFontSize()); - - run.setFontSize(Integer.MAX_VALUE); - assertEquals(Integer.MAX_VALUE, run.getFontSize()); - - run.setFontSize(-1); - assertEquals(-1, run.getFontSize()); - - - assertEquals(-1, run.getTextPosition()); - - run.setTextPosition(10); - assertEquals(10, run.getTextPosition()); - - run.setTextPosition(Short.MAX_VALUE-1); - assertEquals(Short.MAX_VALUE-1, run.getTextPosition()); - - run.setTextPosition(Short.MAX_VALUE); - assertEquals(Short.MAX_VALUE, run.getTextPosition()); - - run.setTextPosition(Short.MAX_VALUE+1); - assertEquals(Short.MAX_VALUE+1, run.getTextPosition()); - - run.setTextPosition(Short.MAX_VALUE+1); - assertEquals(Short.MAX_VALUE+1, run.getTextPosition()); - - run.setTextPosition(Integer.MAX_VALUE-1); - assertEquals(Integer.MAX_VALUE-1, run.getTextPosition()); - - run.setTextPosition(Integer.MAX_VALUE); - assertEquals(Integer.MAX_VALUE, run.getTextPosition()); - - run.setTextPosition(-1); - assertEquals(-1, run.getTextPosition()); - - document.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFSDT.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFSDT.java deleted file mode 100644 index 9cba17e36..000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFSDT.java +++ /dev/null @@ -1,213 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xwpf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.junit.Ignore; -import org.junit.Test; - -public final class TestXWPFSDT { - - /** - * Test simple tag and title extraction from SDT - * - * @throws Exception - */ - @Test - public void testTagTitle() throws Exception { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Bug54849.docx"); - String tag = null; - String title = null; - List sdts = extractAllSDTs(doc); - for (AbstractXWPFSDT sdt : sdts) { - if (sdt.getContent().toString().equals("Rich_text")) { - tag = "MyTag"; - title = "MyTitle"; - break; - } - - } - assertEquals("controls size", 13, sdts.size()); - - assertEquals("tag", "MyTag", tag); - assertEquals("title", "MyTitle", title); - } - - @Test - public void testGetSDTs() throws Exception { - String[] contents = new String[]{ - "header_rich_text", - "Rich_text", - "Rich_text_pre_table\nRich_text_cell1\t\t\t\n\t\t\t\n\t\t\t\n\nRich_text_post_table", - "Plain_text_no_newlines", - "Plain_text_with_newlines1\nplain_text_with_newlines2", - "Watermelon", - "Dirt", - "4/16/2013", - "Rich_text_in_cell", - "rich_text_in_paragraph_in_cell", - "Footer_rich_text", - "Footnote_sdt", - "Endnote_sdt" - - }; - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Bug54849.docx"); - List sdts = extractAllSDTs(doc); - - assertEquals("number of sdts", contents.length, sdts.size()); - - for (int i = 0; i < contents.length; i++) { - AbstractXWPFSDT sdt = sdts.get(i); - assertEquals(i + ": " + contents[i], contents[i], sdt.getContent().toString()); - } - } - - /** - * POI-54771 and TIKA-1317 - */ - @Test - public void testSDTAsCell() throws Exception { - //Bug54771a.docx and Bug54771b.docx test slightly - //different recursion patterns. Keep both! - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Bug54771a.docx"); - List sdts = extractAllSDTs(doc); - String text = sdts.get(0).getContent().getText(); - assertEquals(2, sdts.size()); - assertTrue(text.indexOf("Test") > -1); - - text = sdts.get(1).getContent().getText(); - assertTrue(text.indexOf("Test Subtitle") > -1); - assertTrue(text.indexOf("Test User") > -1); - assertTrue(text.indexOf("Test") < text.indexOf("Test Subtitle")); - - doc = XWPFTestDataSamples.openSampleDocument("Bug54771b.docx"); - sdts = extractAllSDTs(doc); - assertEquals(3, sdts.size()); - assertTrue(sdts.get(0).getContent().getText().indexOf("Test") > -1); - - assertTrue(sdts.get(1).getContent().getText().indexOf("Test Subtitle") > -1); - assertTrue(sdts.get(2).getContent().getText().indexOf("Test User") > -1); - - } - - /** - * POI-55142 and Tika 1130 - */ - @Test - public void testNewLinesBetweenRuns() throws Exception { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Bug55142.docx"); - List sdts = extractAllSDTs(doc); - List targs = new ArrayList(); - //these test newlines and tabs in paragraphs/body elements - targs.add("Rich-text1 abcdefghi"); - targs.add("Rich-text2 abcd\t\tefgh"); - targs.add("Rich-text3 abcd\nefg"); - targs.add("Rich-text4 abcdefg"); - targs.add("Rich-text5 abcdefg\nhijk"); - targs.add("Plain-text1 abcdefg"); - targs.add("Plain-text2 abcdefg\nhijk\nlmnop"); - //this tests consecutive runs within a cell (not a paragraph) - //this test case was triggered by Tika-1130 - targs.add("sdt_incell2 abcdefg"); - - for (int i = 0; i < sdts.size(); i++) { - AbstractXWPFSDT sdt = sdts.get(i); - assertEquals(targs.get(i), targs.get(i), sdt.getContent().getText()); - } - } - - @Test - public void test60341() throws IOException { - //handle sdtbody without an sdtpr - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("Bug60341.docx"); - List sdts = extractAllSDTs(doc); - assertEquals(1, sdts.size()); - assertEquals("", sdts.get(0).getTag()); - assertEquals("", sdts.get(0).getTitle()); - } - - private List extractAllSDTs(XWPFDocument doc) { - - List sdts = new ArrayList(); - - List headers = doc.getHeaderList(); - for (XWPFHeader header : headers) { - sdts.addAll(extractSDTsFromBodyElements(header.getBodyElements())); - } - sdts.addAll(extractSDTsFromBodyElements(doc.getBodyElements())); - - List footers = doc.getFooterList(); - for (XWPFFooter footer : footers) { - sdts.addAll(extractSDTsFromBodyElements(footer.getBodyElements())); - } - - for (XWPFFootnote footnote : doc.getFootnotes()) { - sdts.addAll(extractSDTsFromBodyElements(footnote.getBodyElements())); - } - for (Map.Entry e : doc.endnotes.entrySet()) { - sdts.addAll(extractSDTsFromBodyElements(e.getValue().getBodyElements())); - } - return sdts; - } - - private List extractSDTsFromBodyElements(List elements) { - List sdts = new ArrayList(); - for (IBodyElement e : elements) { - if (e instanceof XWPFSDT) { - XWPFSDT sdt = (XWPFSDT) e; - sdts.add(sdt); - } else if (e instanceof XWPFParagraph) { - - XWPFParagraph p = (XWPFParagraph) e; - for (IRunElement e2 : p.getIRuns()) { - if (e2 instanceof XWPFSDT) { - XWPFSDT sdt = (XWPFSDT) e2; - sdts.add(sdt); - } - } - } else if (e instanceof XWPFTable) { - XWPFTable table = (XWPFTable) e; - sdts.addAll(extractSDTsFromTable(table)); - } - } - return sdts; - } - - private List extractSDTsFromTable(XWPFTable table) { - - List sdts = new ArrayList(); - for (XWPFTableRow r : table.getRows()) { - for (ICell c : r.getTableICells()) { - if (c instanceof XWPFSDTCell) { - sdts.add((XWPFSDTCell) c); - } else if (c instanceof XWPFTableCell) { - sdts.addAll(extractSDTsFromBodyElements(((XWPFTableCell) c).getBodyElements())); - } - } - } - return sdts; - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFSmartTag.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFSmartTag.java deleted file mode 100644 index 7adc0d0f3..000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFSmartTag.java +++ /dev/null @@ -1,38 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -import java.io.IOException; - -import junit.framework.TestCase; -import org.apache.poi.xwpf.XWPFTestDataSamples; - -/** - * Tests for reading SmartTags from Word docx. - * - * @author Fabian Lange - */ -public final class TestXWPFSmartTag extends TestCase { - - public void testSmartTags() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("smarttag-snippet.docx"); - XWPFParagraph p = doc.getParagraphArray(0); - assertTrue(p.getText().contains("Carnegie Mellon University School of Computer Science")); - p = doc.getParagraphArray(2); - assertTrue(p.getText().contains("Alice's Adventures")); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFStyles.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFStyles.java deleted file mode 100644 index 6210d1178..000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFStyles.java +++ /dev/null @@ -1,222 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xwpf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.junit.Test; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFonts; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTLatentStyles; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTLsdException; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTStyle; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTStyles; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STStyleType; - -public final class TestXWPFStyles { - @Test - public void testGetUsedStyles() throws IOException { - XWPFDocument sampleDoc = XWPFTestDataSamples.openSampleDocument("Styles.docx"); - List testUsedStyleList = new ArrayList(); - XWPFStyles styles = sampleDoc.getStyles(); - XWPFStyle style = styles.getStyle("berschrift1"); - testUsedStyleList.add(style); - testUsedStyleList.add(styles.getStyle("Standard")); - testUsedStyleList.add(styles.getStyle("berschrift1Zchn")); - testUsedStyleList.add(styles.getStyle("Absatz-Standardschriftart")); - style.hasSameName(style); - - List usedStyleList = styles.getUsedStyleList(style); - assertEquals(usedStyleList, testUsedStyleList); - } - - @Test - public void testAddStylesToDocument() throws IOException { - XWPFDocument docOut = new XWPFDocument(); - XWPFStyles styles = docOut.createStyles(); - - String strStyleId = "headline1"; - CTStyle ctStyle = CTStyle.Factory.newInstance(); - - ctStyle.setStyleId(strStyleId); - XWPFStyle s = new XWPFStyle(ctStyle); - styles.addStyle(s); - - assertTrue(styles.styleExist(strStyleId)); - - XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(docOut); - - styles = docIn.getStyles(); - assertTrue(styles.styleExist(strStyleId)); - } - - /** - * Bug #52449 - We should be able to write a file containing - * both regular and glossary styles without error - */ - @Test - public void test52449() throws Exception { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("52449.docx"); - XWPFStyles styles = doc.getStyles(); - assertNotNull(styles); - - XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(doc); - styles = docIn.getStyles(); - assertNotNull(styles); - } - - - /** - * YK: tests below don't make much sense, - * they exist only to copy xml beans to pi-ooxml-schemas.jar - */ - @SuppressWarnings("resource") - @Test - public void testLanguages() { - XWPFDocument docOut = new XWPFDocument(); - XWPFStyles styles = docOut.createStyles(); - styles.setEastAsia("Chinese"); - - styles.setSpellingLanguage("English"); - - CTFonts def = CTFonts.Factory.newInstance(); - styles.setDefaultFonts(def); - } - - @Test - public void testType() { - CTStyle ctStyle = CTStyle.Factory.newInstance(); - XWPFStyle style = new XWPFStyle(ctStyle); - - style.setType(STStyleType.PARAGRAPH); - assertEquals(STStyleType.PARAGRAPH, style.getType()); - } - - @Test - public void testLatentStyles() { - CTLatentStyles latentStyles = CTLatentStyles.Factory.newInstance(); - CTLsdException ex = latentStyles.addNewLsdException(); - ex.setName("ex1"); - XWPFLatentStyles ls = new XWPFLatentStyles(latentStyles); - assertEquals(true, ls.isLatentStyle("ex1")); - assertEquals(false, ls.isLatentStyle("notex1")); - } - - @Test - public void testSetStyles_Bug57254() throws IOException { - XWPFDocument docOut = new XWPFDocument(); - XWPFStyles styles = docOut.createStyles(); - - CTStyles ctStyles = CTStyles.Factory.newInstance(); - String strStyleId = "headline1"; - CTStyle ctStyle = ctStyles.addNewStyle(); - - ctStyle.setStyleId(strStyleId); - styles.setStyles(ctStyles); - - assertTrue(styles.styleExist(strStyleId)); - - XWPFDocument docIn = XWPFTestDataSamples.writeOutAndReadBack(docOut); - - styles = docIn.getStyles(); - assertTrue(styles.styleExist(strStyleId)); - } - - @Test - public void testEasyAccessToStyles() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("SampleDoc.docx"); - XWPFStyles styles = doc.getStyles(); - assertNotNull(styles); - - // Has 3 paragraphs on page one, a break, and 3 on page 2 - assertEquals(7, doc.getParagraphs().size()); - - // Check the first three have no run styles, just default paragraph style - for (int i = 0; i < 3; i++) { - XWPFParagraph p = doc.getParagraphs().get(i); - assertEquals(null, p.getStyle()); - assertEquals(null, p.getStyleID()); - assertEquals(1, p.getRuns().size()); - - XWPFRun r = p.getRuns().get(0); - assertEquals(null, r.getColor()); - assertEquals(null, r.getFontFamily()); - assertEquals(null, r.getFontName()); - assertEquals(-1, r.getFontSize()); - } - - // On page two, has explicit styles, but on runs not on - // the paragraph itself - for (int i = 4; i < 7; i++) { - XWPFParagraph p = doc.getParagraphs().get(i); - assertEquals(null, p.getStyle()); - assertEquals(null, p.getStyleID()); - assertEquals(1, p.getRuns().size()); - - XWPFRun r = p.getRuns().get(0); - assertEquals("Arial Black", r.getFontFamily()); - assertEquals("Arial Black", r.getFontName()); - assertEquals(16, r.getFontSize()); - assertEquals("548DD4", r.getColor()); - } - - // Check the document styles - // Should have a style defined for each type - assertEquals(4, styles.getNumberOfStyles()); - assertNotNull(styles.getStyle("Normal")); - assertNotNull(styles.getStyle("DefaultParagraphFont")); - assertNotNull(styles.getStyle("TableNormal")); - assertNotNull(styles.getStyle("NoList")); - - // We can't do much yet with latent styles - assertEquals(137, styles.getLatentStyles().getNumberOfStyles()); - - // Check the default styles - assertNotNull(styles.getDefaultRunStyle()); - assertNotNull(styles.getDefaultParagraphStyle()); - - assertEquals(11, styles.getDefaultRunStyle().getFontSize()); - assertEquals(200, styles.getDefaultParagraphStyle().getSpacingAfter()); - } - - // Bug 60329: style with missing StyleID throws NPE - @Test - public void testMissingStyleId() throws IOException { - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("60329.docx"); - XWPFStyles styles = doc.getStyles(); - // Styles exist in the test document in this order, EmptyCellLayoutStyle - // is missing a StyleId - try { - assertNotNull(styles.getStyle("NoList")); - assertNull(styles.getStyle("EmptyCellLayoutStyle")); - assertNotNull(styles.getStyle("BalloonText")); - } catch (NullPointerException e) { - fail(e.toString()); - } - - doc.close(); - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFTable.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFTable.java deleted file mode 100644 index 449f6b6b8..000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFTable.java +++ /dev/null @@ -1,258 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.xwpf.usermodel; - -import java.math.BigInteger; -import java.util.List; - -import junit.framework.TestCase; -import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.apache.poi.xwpf.usermodel.XWPFTable.XWPFBorderType; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRow; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblBorders; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblCellMar; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblGrid; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTc; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTText; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STBorder; - -/** - * Tests for XWPF Tables - */ -public class TestXWPFTable extends TestCase { - @Override - protected void setUp() { - /* - XWPFDocument doc = new XWPFDocument(); - p = doc.createParagraph(); - - this.ctRun = CTR.Factory.newInstance(); - */ - } - - public void testConstructor() { - XWPFDocument doc = new XWPFDocument(); - CTTbl ctTable = CTTbl.Factory.newInstance(); - XWPFTable xtab = new XWPFTable(ctTable, doc); - assertNotNull(xtab); - assertEquals(1, ctTable.sizeOfTrArray()); - assertEquals(1, ctTable.getTrArray(0).sizeOfTcArray()); - assertNotNull(ctTable.getTrArray(0).getTcArray(0).getPArray(0)); - - ctTable = CTTbl.Factory.newInstance(); - xtab = new XWPFTable(ctTable, doc, 3, 2); - assertNotNull(xtab); - assertEquals(3, ctTable.sizeOfTrArray()); - assertEquals(2, ctTable.getTrArray(0).sizeOfTcArray()); - assertNotNull(ctTable.getTrArray(0).getTcArray(0).getPArray(0)); - } - - public void testTblGrid() { - XWPFDocument doc = new XWPFDocument(); - CTTbl ctTable = CTTbl.Factory.newInstance(); - CTTblGrid cttblgrid = ctTable.addNewTblGrid(); - cttblgrid.addNewGridCol().setW(new BigInteger("123")); - cttblgrid.addNewGridCol().setW(new BigInteger("321")); - - XWPFTable xtab = new XWPFTable(ctTable, doc); - assertEquals(123, xtab.getCTTbl().getTblGrid().getGridColArray(0).getW().intValue()); - assertEquals(321, xtab.getCTTbl().getTblGrid().getGridColArray(1).getW().intValue()); - } - - public void testGetText() { - XWPFDocument doc = new XWPFDocument(); - CTTbl table = CTTbl.Factory.newInstance(); - CTRow row = table.addNewTr(); - CTTc cell = row.addNewTc(); - CTP paragraph = cell.addNewP(); - CTR run = paragraph.addNewR(); - CTText text = run.addNewT(); - text.setStringValue("finally I can write!"); - - XWPFTable xtab = new XWPFTable(table, doc); - assertEquals("finally I can write!\n", xtab.getText()); - } - - - public void testCreateRow() { - XWPFDocument doc = new XWPFDocument(); - - CTTbl table = CTTbl.Factory.newInstance(); - CTRow r1 = table.addNewTr(); - r1.addNewTc().addNewP(); - r1.addNewTc().addNewP(); - CTRow r2 = table.addNewTr(); - r2.addNewTc().addNewP(); - r2.addNewTc().addNewP(); - CTRow r3 = table.addNewTr(); - r3.addNewTc().addNewP(); - r3.addNewTc().addNewP(); - - XWPFTable xtab = new XWPFTable(table, doc); - assertEquals(3, xtab.getNumberOfRows()); - assertNotNull(xtab.getRow(2)); - - //add a new row - xtab.createRow(); - assertEquals(4, xtab.getNumberOfRows()); - - //check number of cols - assertEquals(2, table.getTrArray(0).sizeOfTcArray()); - - //check creation of first row - xtab = new XWPFTable(CTTbl.Factory.newInstance(), doc); - assertEquals(1, xtab.getCTTbl().getTrArray(0).sizeOfTcArray()); - } - - - public void testSetGetWidth() { - XWPFDocument doc = new XWPFDocument(); - - CTTbl table = CTTbl.Factory.newInstance(); - table.addNewTblPr().addNewTblW().setW(new BigInteger("1000")); - - XWPFTable xtab = new XWPFTable(table, doc); - - assertEquals(1000, xtab.getWidth()); - - xtab.setWidth(100); - assertEquals(100, table.getTblPr().getTblW().getW().intValue()); - } - - public void testSetGetHeight() { - XWPFDocument doc = new XWPFDocument(); - - CTTbl table = CTTbl.Factory.newInstance(); - - XWPFTable xtab = new XWPFTable(table, doc); - XWPFTableRow row = xtab.createRow(); - row.setHeight(20); - assertEquals(20, row.getHeight()); - } - - public void testSetGetMargins() { - // instantiate the following class so it'll get picked up by - // the XmlBean process and added to the jar file. it's required - // for the following XWPFTable methods. - CTTblCellMar ctm = CTTblCellMar.Factory.newInstance(); - assertNotNull(ctm); - // create a table - XWPFDocument doc = new XWPFDocument(); - CTTbl ctTable = CTTbl.Factory.newInstance(); - XWPFTable table = new XWPFTable(ctTable, doc); - // set margins - table.setCellMargins(50, 50, 250, 450); - // get margin components - int t = table.getCellMarginTop(); - assertEquals(50, t); - int l = table.getCellMarginLeft(); - assertEquals(50, l); - int b = table.getCellMarginBottom(); - assertEquals(250, b); - int r = table.getCellMarginRight(); - assertEquals(450, r); - } - - public void testSetGetHBorders() { - // instantiate the following classes so they'll get picked up by - // the XmlBean process and added to the jar file. they are required - // for the following XWPFTable methods. - CTTblBorders cttb = CTTblBorders.Factory.newInstance(); - assertNotNull(cttb); - STBorder stb = STBorder.Factory.newInstance(); - assertNotNull(stb); - // create a table - XWPFDocument doc = new XWPFDocument(); - CTTbl ctTable = CTTbl.Factory.newInstance(); - XWPFTable table = new XWPFTable(ctTable, doc); - // set inside horizontal border - table.setInsideHBorder(XWPFBorderType.SINGLE, 4, 0, "FF0000"); - // get inside horizontal border components - int s = table.getInsideHBorderSize(); - assertEquals(4, s); - int sp = table.getInsideHBorderSpace(); - assertEquals(0, sp); - String clr = table.getInsideHBorderColor(); - assertEquals("FF0000", clr); - XWPFBorderType bt = table.getInsideHBorderType(); - assertEquals(XWPFBorderType.SINGLE, bt); - } - - public void testSetGetVBorders() { - // create a table - XWPFDocument doc = new XWPFDocument(); - CTTbl ctTable = CTTbl.Factory.newInstance(); - XWPFTable table = new XWPFTable(ctTable, doc); - // set inside vertical border - table.setInsideVBorder(XWPFBorderType.DOUBLE, 4, 0, "00FF00"); - // get inside vertical border components - XWPFBorderType bt = table.getInsideVBorderType(); - assertEquals(XWPFBorderType.DOUBLE, bt); - int sz = table.getInsideVBorderSize(); - assertEquals(4, sz); - int sp = table.getInsideVBorderSpace(); - assertEquals(0, sp); - String clr = table.getInsideVBorderColor(); - assertEquals("00FF00", clr); - } - - public void testSetGetRowBandSize() { - XWPFDocument doc = new XWPFDocument(); - CTTbl ctTable = CTTbl.Factory.newInstance(); - XWPFTable table = new XWPFTable(ctTable, doc); - table.setRowBandSize(12); - int sz = table.getRowBandSize(); - assertEquals(12, sz); - } - - public void testSetGetColBandSize() { - XWPFDocument doc = new XWPFDocument(); - CTTbl ctTable = CTTbl.Factory.newInstance(); - XWPFTable table = new XWPFTable(ctTable, doc); - table.setColBandSize(16); - int sz = table.getColBandSize(); - assertEquals(16, sz); - } - - public void testCreateTable() throws Exception { - // open an empty document - XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("sample.docx"); - - // create a table with 5 rows and 7 columns - int noRows = 5; - int noCols = 7; - XWPFTable table = doc.createTable(noRows, noCols); - - // assert the table is empty - List rows = table.getRows(); - assertEquals("Table has less rows than requested.", noRows, rows.size()); - for (XWPFTableRow xwpfRow : rows) { - assertNotNull(xwpfRow); - for (int i = 0; i < 7; i++) { - XWPFTableCell xwpfCell = xwpfRow.getCell(i); - assertNotNull(xwpfCell); - assertEquals("Empty cells should not have one paragraph.", 1, xwpfCell.getParagraphs().size()); - xwpfCell = xwpfRow.getCell(i); - assertEquals("Calling 'getCell' must not modify cells content.", 1, xwpfCell.getParagraphs().size()); - } - } - doc.getPackage().revert(); - } -} \ No newline at end of file diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFTableCell.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFTableCell.java deleted file mode 100644 index d1cf5b2e9..000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFTableCell.java +++ /dev/null @@ -1,136 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.xwpf.usermodel; - -import static org.junit.Assert.*; - -import org.junit.Ignore; -import org.junit.Test; - -import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.apache.poi.xwpf.usermodel.XWPFTableCell.XWPFVertAlign; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.*; - -import java.util.List; - -public class TestXWPFTableCell { - - @Test - public void testSetGetVertAlignment() throws Exception { - // instantiate the following classes so they'll get picked up by - // the XmlBean process and added to the jar file. they are required - // for the following XWPFTableCell methods. - CTShd ctShd = CTShd.Factory.newInstance(); - assertNotNull(ctShd); - CTVerticalJc ctVjc = CTVerticalJc.Factory.newInstance(); - assertNotNull(ctVjc); - STShd stShd = STShd.Factory.newInstance(); - assertNotNull(stShd); - STVerticalJc stVjc = STVerticalJc.Factory.newInstance(); - assertNotNull(stVjc); - - // create a table - XWPFDocument doc = new XWPFDocument(); - CTTbl ctTable = CTTbl.Factory.newInstance(); - XWPFTable table = new XWPFTable(ctTable, doc); - // table has a single row by default; grab it - XWPFTableRow tr = table.getRow(0); - assertNotNull(tr); - // row has a single cell by default; grab it - XWPFTableCell cell = tr.getCell(0); - - cell.setVerticalAlignment(XWPFVertAlign.BOTH); - XWPFVertAlign al = cell.getVerticalAlignment(); - assertEquals(XWPFVertAlign.BOTH, al); - } - - @Test - public void testSetGetColor() throws Exception { - // create a table - XWPFDocument doc = new XWPFDocument(); - CTTbl ctTable = CTTbl.Factory.newInstance(); - XWPFTable table = new XWPFTable(ctTable, doc); - // table has a single row by default; grab it - XWPFTableRow tr = table.getRow(0); - assertNotNull(tr); - // row has a single cell by default; grab it - XWPFTableCell cell = tr.getCell(0); - - cell.setColor("F0000F"); - String clr = cell.getColor(); - assertEquals("F0000F", clr); - } - - /** - * ensure that CTHMerge and CTTcBorders go in poi-ooxml.jar - */ - @SuppressWarnings("unused") - @Test - public void test54099() { - XWPFDocument doc = new XWPFDocument(); - CTTbl ctTable = CTTbl.Factory.newInstance(); - XWPFTable table = new XWPFTable(ctTable, doc); - XWPFTableRow tr = table.getRow(0); - XWPFTableCell cell = tr.getCell(0); - - CTTc ctTc = cell.getCTTc(); - CTTcPr tcPr = ctTc.addNewTcPr(); - CTHMerge hMerge = tcPr.addNewHMerge(); - hMerge.setVal(STMerge.RESTART); - - CTTcBorders tblBorders = tcPr.addNewTcBorders(); - CTVMerge vMerge = tcPr.addNewVMerge(); - } - - @Test - public void testCellVerticalAlign() throws Exception{ - XWPFDocument docx = XWPFTestDataSamples.openSampleDocument("59030.docx"); - List tables = docx.getTables(); - assertEquals(1, tables.size()); - - XWPFTable table = tables.get(0); - - List tableRows = table.getRows(); - assertEquals(2, tableRows.size()); - - assertNull(tableRows.get(0).getCell(0).getVerticalAlignment()); - assertEquals(XWPFVertAlign.BOTTOM, tableRows.get(0).getCell(1).getVerticalAlignment()); - assertEquals(XWPFVertAlign.CENTER, tableRows.get(1).getCell(0).getVerticalAlignment()); - assertNull(tableRows.get(1).getCell(1).getVerticalAlignment()); // should return null since alignment isn't set - } - - // This is not a very useful test as written. It is not worth the execution time for a unit test - @Ignore - @Test - public void testCellVerticalAlignShouldNotThrowNPE() throws Exception { - XWPFDocument docx = XWPFTestDataSamples.openSampleDocument("TestTableCellAlign.docx"); - List tables = docx.getTables(); - for (XWPFTable table : tables) { - List tableRows = table.getRows(); - for (XWPFTableRow tableRow : tableRows) { - List tableCells = tableRow.getTableCells(); - for (XWPFTableCell tableCell : tableCells) { - // getVerticalAlignment should return either an XWPFVertAlign enum or null if not set - tableCell.getVerticalAlignment(); - } - } - } - } -} diff --git a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFTableRow.java b/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFTableRow.java deleted file mode 100644 index 57ed43532..000000000 --- a/src/ooxml/testcases/org/apache/poi/xwpf/usermodel/TestXWPFTableRow.java +++ /dev/null @@ -1,140 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.xwpf.usermodel; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; - -import org.apache.poi.xwpf.XWPFTestDataSamples; -import org.junit.Test; - -public class TestXWPFTableRow { - - @Test - public void testCreateRow() throws IOException { - XWPFDocument doc = new XWPFDocument(); - XWPFTable table = doc.createTable(1, 1); - XWPFTableRow tr = table.createRow(); - assertNotNull(tr); - doc.close(); - } - - @Test - public void testSetGetCantSplitRow() throws IOException { - // create a table - XWPFDocument doc = new XWPFDocument(); - XWPFTable table = doc.createTable(1, 1); - // table has a single row by default; grab it - XWPFTableRow tr = table.getRow(0); - assertNotNull(tr); - - // Assert the repeat header is false by default - boolean isCantSplit = tr.isCantSplitRow(); - assertFalse(isCantSplit); - - // Repeat the header - tr.setCantSplitRow(true); - isCantSplit = tr.isCantSplitRow(); - assertTrue(isCantSplit); - - // Make the header no longer repeating - tr.setCantSplitRow(false); - isCantSplit = tr.isCantSplitRow(); - assertFalse(isCantSplit); - - doc.close(); - } - - @Test - public void testSetGetRepeatHeader() throws IOException { - // create a table - XWPFDocument doc = new XWPFDocument(); - XWPFTable table = doc.createTable(3, 1); - // table has a single row by default; grab it - XWPFTableRow tr = table.getRow(0); - assertNotNull(tr); - - // Assert the repeat header is false by default - boolean isRpt = tr.isRepeatHeader(); - assertFalse(isRpt); - - // Repeat the header - tr.setRepeatHeader(true); - isRpt = tr.isRepeatHeader(); - assertTrue(isRpt); - - // Make the header no longer repeating - tr.setRepeatHeader(false); - isRpt = tr.isRepeatHeader(); - assertFalse(isRpt); - - // If the third row is set to repeat, but not the second, - // isRepeatHeader should report false because Word will - // ignore it. - tr = table.getRow(2); - tr.setRepeatHeader(true); - isRpt = tr.isRepeatHeader(); - assertFalse(isRpt); - - doc.close(); - } - - // Test that validates the table header value can be parsed from a document - // generated in Word - @Test - public void testIsRepeatHeader() throws Exception { - XWPFDocument doc = XWPFTestDataSamples - .openSampleDocument("Bug60337.docx"); - XWPFTable table = doc.getTables().get(0); - XWPFTableRow tr = table.getRow(0); - boolean isRpt = tr.isRepeatHeader(); - assertTrue(isRpt); - - tr = table.getRow(1); - isRpt = tr.isRepeatHeader(); - assertFalse(isRpt); - - tr = table.getRow(2); - isRpt = tr.isRepeatHeader(); - assertFalse(isRpt); - } - - - // Test that validates the table header value can be parsed from a document - // generated in Word - @Test - public void testIsCantSplit() throws Exception { - XWPFDocument doc = XWPFTestDataSamples - .openSampleDocument("Bug60337.docx"); - XWPFTable table = doc.getTables().get(0); - XWPFTableRow tr = table.getRow(0); - boolean isCantSplit = tr.isCantSplitRow(); - assertFalse(isCantSplit); - - tr = table.getRow(1); - isCantSplit = tr.isCantSplitRow(); - assertFalse(isCantSplit); - - tr = table.getRow(2); - isCantSplit = tr.isCantSplitRow(); - assertTrue(isCantSplit); - } -} diff --git a/src/records/definitions/area_format_record.xml b/src/records/definitions/area_format_record.xml deleted file mode 100644 index 3fc2a9c18..000000000 --- a/src/records/definitions/area_format_record.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - Record - Record - The area format record is used to define the colours and patterns for an area. - Glen Stampoultzis (glens at apache.org) - - - - - - - - - - - - diff --git a/src/records/definitions/area_record.xml b/src/records/definitions/area_record.xml deleted file mode 100644 index 16f04e15f..000000000 --- a/src/records/definitions/area_record.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - - Record - Record - The area record is used to define a area chart. - Glen Stampoultzis (glens at apache.org) - - - - - - - - diff --git a/src/records/definitions/attached_label_record.xml b/src/records/definitions/attached_label_record.xml deleted file mode 100644 index e2e59e8e8..000000000 --- a/src/records/definitions/attached_label_record.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - Record - Record - The series label record defines the type of label associated with the data format record. - Glen Stampoultzis (glens at apache.org) - - - - - - - - - - - diff --git a/src/records/definitions/axes_used_record.xml b/src/records/definitions/axes_used_record.xml deleted file mode 100644 index cd8cf1065..000000000 --- a/src/records/definitions/axes_used_record.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - Record - Record - The number of axes used on a chart. - Glen Stampoultzis (glens at apache.org) - - - - diff --git a/src/records/definitions/axis_line_format_record.xml b/src/records/definitions/axis_line_format_record.xml deleted file mode 100644 index ff0fc4d39..000000000 --- a/src/records/definitions/axis_line_format_record.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - - Record - Record - The axis line format record defines the axis type details. - Glen Stampoultzis (glens at apache.org) - - - - - - - - - diff --git a/src/records/definitions/axis_options_record.xml b/src/records/definitions/axis_options_record.xml deleted file mode 100644 index 0100f6e1a..000000000 --- a/src/records/definitions/axis_options_record.xml +++ /dev/null @@ -1,46 +0,0 @@ - - - - Record - Record - The axis options record provides unit information and other various tidbits about the axis. - Andrew C. Oliver(acoliver at apache.org) - - - - - - - - - - - - - - - - - - - - - diff --git a/src/records/definitions/axis_parent_record.xml b/src/records/definitions/axis_parent_record.xml deleted file mode 100644 index 22532a81c..000000000 --- a/src/records/definitions/axis_parent_record.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - Record - Record - The axis size and location - Glen Stampoultzis (glens at apache.org) - - - - - - - - - - - diff --git a/src/records/definitions/axis_record.xml b/src/records/definitions/axis_record.xml deleted file mode 100644 index b03c23f77..000000000 --- a/src/records/definitions/axis_record.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - Record - Record - The axis record defines the type of an axis. - Glen Stampoultzis (glens at apache.org) - - - - - - - - - - - - diff --git a/src/records/definitions/bar_record.xml b/src/records/definitions/bar_record.xml deleted file mode 100644 index 9fffd79fa..000000000 --- a/src/records/definitions/bar_record.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - Record - Record - The bar record is used to define a bar chart. - Glen Stampoultzis (glens at apache.org) - - - - - - - - - - - diff --git a/src/records/definitions/category_series_axis_record.xml b/src/records/definitions/category_series_axis_record.xml deleted file mode 100644 index 94088b5a7..000000000 --- a/src/records/definitions/category_series_axis_record.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - Record - Record - This record refers to a category or series axis and is used to specify label/tickmark frequency. - Glen Stampoultzis (glens at apache.org) - - - - - - - - - - - diff --git a/src/records/definitions/chart_record.xml b/src/records/definitions/chart_record.xml deleted file mode 100644 index f1bd8fc9d..000000000 --- a/src/records/definitions/chart_record.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - Record - Record - The chart record is used to define the location and size of a chart. - Glen Stampoultzis (glens at apache.org) - - - - - - - diff --git a/src/records/definitions/common_object_data_record.xml b/src/records/definitions/common_object_data_record.xml deleted file mode 100644 index ad7ebfd18..000000000 --- a/src/records/definitions/common_object_data_record.xml +++ /dev/null @@ -1,71 +0,0 @@ - - - - SubRecord - SubRecord - The common object data record is used to store all common preferences for an excel object. - Glen Stampoultzis (glens at apache.org) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/records/definitions/dat_record.xml b/src/records/definitions/dat_record.xml deleted file mode 100644 index bda909ea5..000000000 --- a/src/records/definitions/dat_record.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - - Record - Record - The dat record is used to store options for the chart. - Glen Stampoultzis (glens at apache.org) - - - - - - - - - diff --git a/src/records/definitions/dataformat_record.xml b/src/records/definitions/dataformat_record.xml deleted file mode 100644 index 3720e24ff..000000000 --- a/src/records/definitions/dataformat_record.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - - Record - Record - The data format record is used to index into a series. - Glen Stampoultzis (glens at apache.org) - - - - - - - - - diff --git a/src/records/definitions/default_data_label_text_properties_record.xml b/src/records/definitions/default_data_label_text_properties_record.xml deleted file mode 100644 index 9a0e755bd..000000000 --- a/src/records/definitions/default_data_label_text_properties_record.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - - Record - Record - The default data label text properties record identifies the text characteristics of the preceeding text record. - Glen Stampoultzis (glens at apache.org) - - - - - - - - diff --git a/src/records/definitions/font_basis_record.xml b/src/records/definitions/font_basis_record.xml deleted file mode 100644 index e16b292fe..000000000 --- a/src/records/definitions/font_basis_record.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - - Record - Record - The font basis record stores various font metrics. - Glen Stampoultzis (glens at apache.org) - - - - - - - - diff --git a/src/records/definitions/font_example.xml b/src/records/definitions/font_example.xml deleted file mode 100644 index 9bf54470a..000000000 --- a/src/records/definitions/font_example.xml +++ /dev/null @@ -1,53 +0,0 @@ - - - - Record - Record - Describes a font record. In Excel a font belongs in the font table. - Glen Stampoultzis (glens at apache.org) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/records/definitions/font_index_record.xml b/src/records/definitions/font_index_record.xml deleted file mode 100644 index bac26e2cb..000000000 --- a/src/records/definitions/font_index_record.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - Record - Record - The font index record indexes into the font table for the text record. - Glen Stampoultzis (glens at apache.org) - - - - diff --git a/src/records/definitions/frame_record.xml b/src/records/definitions/frame_record.xml deleted file mode 100644 index b3b033998..000000000 --- a/src/records/definitions/frame_record.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - Record - Record - The frame record indicates whether there is a border around the displayed text of a chart. - Glen Stampoultzis (glens at apache.org) - - - - - - - - - - - diff --git a/src/records/definitions/ftend_record.xml b/src/records/definitions/ftend_record.xml deleted file mode 100644 index 45f9d59bf..000000000 --- a/src/records/definitions/ftend_record.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - SubRecord - SubRecord - The end data record is used to denote the end of the subrecords. - Glen Stampoultzis (glens at apache.org) - - - diff --git a/src/records/definitions/legend_record.xml b/src/records/definitions/legend_record.xml deleted file mode 100644 index 577443e96..000000000 --- a/src/records/definitions/legend_record.xml +++ /dev/null @@ -1,81 +0,0 @@ - - - - Record - Record - Defines a legend for a chart. - Andrew C. Oliver (acoliver at apache.org) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 76 0E 00 00 86 07 00 00 19 01 00 00 8B 00 00 00 03 01 1F 00 - - 24 - diff --git a/src/records/definitions/line_format_record.xml b/src/records/definitions/line_format_record.xml deleted file mode 100644 index f55679fce..000000000 --- a/src/records/definitions/line_format_record.xml +++ /dev/null @@ -1,52 +0,0 @@ - - - - Record - Record - Describes a line format record. The line format record controls how a line on a chart appears. - Glen Stampoultzis (glens at apache.org) - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/records/definitions/linked_data_record.xml b/src/records/definitions/linked_data_record.xml deleted file mode 100644 index bd247bd63..000000000 --- a/src/records/definitions/linked_data_record.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - - Record - Record - Describes a linked data record. This record refers to the series data or text. - Glen Stampoultzis (glens at apache.org) - - - - - - - - - - - - - - - - - - - - diff --git a/src/records/definitions/number_format_index_record.xml b/src/records/definitions/number_format_index_record.xml deleted file mode 100644 index 08d5f5c7f..000000000 --- a/src/records/definitions/number_format_index_record.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - Record - Record - The number format index record indexes format table. This applies to an axis. - Glen Stampoultzis (glens at apache.org) - - - - diff --git a/src/records/definitions/object_link_record.xml b/src/records/definitions/object_link_record.xml deleted file mode 100644 index 03848bb8f..000000000 --- a/src/records/definitions/object_link_record.xml +++ /dev/null @@ -1,46 +0,0 @@ - - - - Record - Record - Links text to an object on the chart or identifies it as the title. - Andrew C. Oliver (acoliver at apache.org) - - - - - - - - - - - - - - - - - - 03 00 00 00 00 00 - - 10 - diff --git a/src/records/definitions/pane_record.xml b/src/records/definitions/pane_record.xml deleted file mode 100644 index 436443113..000000000 --- a/src/records/definitions/pane_record.xml +++ /dev/null @@ -1,37 +0,0 @@ - - - - Record - Record - Describes the frozen and unfozen panes. - Glen Stampoultzis (glens at apache.org) - - - - - - - - - - - - - diff --git a/src/records/definitions/plot_area_record.xml b/src/records/definitions/plot_area_record.xml deleted file mode 100644 index 300492a4c..000000000 --- a/src/records/definitions/plot_area_record.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - Record - Record - preceeds and identifies a frame as belonging to the plot area. - Andrew C. Oliver (acoliver at apache.org) - 4 - diff --git a/src/records/definitions/plotgrowth_record.xml b/src/records/definitions/plotgrowth_record.xml deleted file mode 100644 index 469b9816b..000000000 --- a/src/records/definitions/plotgrowth_record.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - Record - Record - The plot growth record specifies the scaling factors used when a font is scaled. - Glen Stampoultzis (glens at apache.org) - - - - - diff --git a/src/records/definitions/scl_record.xml b/src/records/definitions/scl_record.xml deleted file mode 100644 index abe21b15b..000000000 --- a/src/records/definitions/scl_record.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - Record - Record - Specifies the window's zoom magnification. If this record isn't present then the windows zoom is 100%. see p384 Excel Dev Kit - Andrew C. Oliver (acoliver at apache.org) - - - - - diff --git a/src/records/definitions/series_chart_group_record.xml b/src/records/definitions/series_chart_group_record.xml deleted file mode 100644 index 84338f144..000000000 --- a/src/records/definitions/series_chart_group_record.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - Record - Record - The series chart group index record stores the index to the CHARTFORMAT record (0 based). - Glen Stampoultzis (glens at apache.org) - - - - diff --git a/src/records/definitions/series_index_record.xml b/src/records/definitions/series_index_record.xml deleted file mode 100644 index a35e01925..000000000 --- a/src/records/definitions/series_index_record.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - - Record - Record - links a series to its position in the series list. - Andrew C. Oliver (acoliver at apache.org) - - - - - - - 03 00 - - 6 - diff --git a/src/records/definitions/series_list_record.xml b/src/records/definitions/series_list_record.xml deleted file mode 100644 index 88eeb6704..000000000 --- a/src/records/definitions/series_list_record.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - Record - Record - The series list record defines the series displayed as an overlay to the main chart record. - Glen Stampoultzis (glens at apache.org) - - - - diff --git a/src/records/definitions/series_record.xml b/src/records/definitions/series_record.xml deleted file mode 100644 index e6d516410..000000000 --- a/src/records/definitions/series_record.xml +++ /dev/null @@ -1,48 +0,0 @@ - - - - Record - Record - The series record describes the overall data for a series. - Glen Stampoultzis (glens at apache.org) - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/records/definitions/series_text_record.xml b/src/records/definitions/series_text_record.xml deleted file mode 100644 index f86aa2da8..000000000 --- a/src/records/definitions/series_text_record.xml +++ /dev/null @@ -1,42 +0,0 @@ - - - - Record - Record - Defines a series name - Andrew C. Oliver (acoliver at apache.org) - - - - - - - - - - - - - - - 00 00 0C 01 56 00 61 00 6C 00 75 00 65 00 20 00 4E 00 75 00 6D 00 62 00 65 00 72 00 - 32 - diff --git a/src/records/definitions/sertocrt_record.xml b/src/records/definitions/sertocrt_record.xml deleted file mode 100644 index a904e96c8..000000000 --- a/src/records/definitions/sertocrt_record.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - Record - Record - Indicates the chart-group index for a series. The order probably defines the mapping. So the 0th record probably means the 0th series. The only field in this of course defines which chart group the 0th series (for instance) would map to. Confusing? Well thats because it is. (p 522 BCG) - Andrew C. Oliver (acoliver at apache.org) - - - - diff --git a/src/records/definitions/sheet_properties_record.xml b/src/records/definitions/sheet_properties_record.xml deleted file mode 100644 index 97c5300e7..000000000 --- a/src/records/definitions/sheet_properties_record.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - - Record - Record - Describes a chart sheet properties record. - Glen Stampoultzis (glens at apache.org) - - - - - - - - - - - - - - - diff --git a/src/records/definitions/subrecord.xsl b/src/records/definitions/subrecord.xsl deleted file mode 100644 index 01016bc6b..000000000 --- a/src/records/definitions/subrecord.xsl +++ /dev/null @@ -1,292 +0,0 @@ - - - - - - - -package ; - - - -import org.apache.poi.util.*; - -/** - * - * NOTE: This source is automatically generated please do not modify this file. Either subclass or - * remove the record in src/records/definitions. - - */ -public class SubRecord - extends SubRecord -{ - public final static short sid = ; - private ; - - - - public SubRecord() - { - - - = ; - - } - - /** - * Constructs a record and sets its fields appropriately. - * - * @param id id must be or an exception - * will be throw upon validation - * @param size size the size of the data area of the record - * @param data data of the record (should not contain sid/len) - */ - - public SubRecord(short id, short size, byte [] data) - { - super(id, size, data); - - - - = - ; - - - - } - - /** - * Constructs a record and sets its fields appropriately. - * - * @param id id must be or an exception - * will be throw upon validation - * @param size size the size of the data area of the record - * @param data data of the record (should not contain sid/len) - * @param offset of the record's data - */ - - public SubRecord(short id, short size, byte [] data, int offset) - { - super(id, size, data, offset); - - - - = - ; - - - - } - - /** - * Checks the sid matches the expected side for this record - * - * @param id the expected sid. - */ - protected void validateSid(short id) - { - if (id != sid) - { - throw new RecordFormatException("Not a record"); - } - } - - protected void fillFields(byte [] data, short size, int offset) - { - - int pos = 0; - - - - - ; - - } - - public String toString() - { - StringBuffer buffer = new StringBuffer(); - - buffer.append("[]\n"); - - buffer.append("[/]\n"); - return buffer.toString(); - } - - public int serialize(int offset, byte[] data) - { - int pos = 0; - - LittleEndian.putShort(data, 0 + offset, sid); - LittleEndian.putShort(data, 2 + offset, (short)(getRecordSize() - 4)); - - - - - - return getRecordSize(); - } - - /** - * Size of record (exluding 4 byte header) - */ - public int getRecordSize() - { - - return 4 - - -; - } - - public short getSid() - { - return this.sid; - } - - public Object clone() { - SubRecord rec = new SubRecord(); - - - ; - - return rec; - } - - - - -} // END OF CLASS - - - - - - - - - /** - * Sets the field value. - * - */ - public void set(boolean value) - { - = .setBoolean(, value); - } - - /** - * - * @return the field value. - */ - public boolean is() - { - return .isSet(); - } - - - /** - * Sets the field value. - * - */ - public void set(short value) - { - = .setValue(, value); - } - - /** - * - * @return the field value. - */ - public short get() - { - return .getShortValue(); - } - - - - - private BitField = new BitField(); - private BitField = new BitField(); - - - public final static = ; - - - - - * - - - /** - * Get the field for the record. - * - * @return One of - */ - public get() - { - return ; - } - - /** - * Set the field for the record. - * - * @param - * One of - */ - public void set( ) - { - this. = ; - } - - - - - - buffer.append(System.getProperty("line.separator")); - - - - - - - buffer.append(" . - - = ").append(is - - ()).append('\n'); - - - buffer.append(" . - - = ").append(get - - ()).append('\n'); - - - - - * @author - - - diff --git a/src/records/definitions/subrecord_test.xsl b/src/records/definitions/subrecord_test.xsl deleted file mode 100644 index c729b4130..000000000 --- a/src/records/definitions/subrecord_test.xsl +++ /dev/null @@ -1,121 +0,0 @@ - - - - - - - -package ; - - -import junit.framework.TestCase; - -/** - * Tests the serialization and deserialization of the SubRecord - * class works correctly. Test data taken directly from a real - * Excel file. - * - - */ -public class TestSubRecord - extends TestCase -{ - byte[] data = new byte[] { - - }; - - public TestSubRecord(String name) - { - super(name); - } - - public void testLoad() - throws Exception - { - SubRecord record = new SubRecord((short), (short)data.length, data); - - - - assertEquals( "", record.get()); - - assertEquals( (byte), record.get()); - - assertEquals( (short), record.get()); - - assertEquals( (int), record.get()); - - assertEquals( (double), record.get()); - - - - - assertEquals( , record.getRecordSize() ); - - record.validateSid((short)); - } - - public void testStore() - { - SubRecord record = new SubRecord(); - - - - - record.set( "" ); - - record.set( (byte) ); - - record.set( (short) ); - - record.set( (int) ); - - record.set( (double) ); - - - - - - byte [] recordBytes = record.serialize(); - assertEquals(recordBytes.length - 4, data.length); - for (int i = 0; i < data.length; i++) - assertEquals("At offset " + i, data[i], recordBytes[i+4]); - } -} - - - - * @author - - - - assertEquals( , record.is() ); - - - - - record.set( ); - - - - diff --git a/src/records/definitions/text_record.xml b/src/records/definitions/text_record.xml deleted file mode 100644 index c486a7fd9..000000000 --- a/src/records/definitions/text_record.xml +++ /dev/null @@ -1,85 +0,0 @@ - - - - Record - Record - The text record is used to define text stored on a chart. - Glen Stampoultzis (glens at apache.org) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/records/definitions/textobject_record.xml b/src/records/definitions/textobject_record.xml deleted file mode 100644 index 8e7e6e83c..000000000 --- a/src/records/definitions/textobject_record.xml +++ /dev/null @@ -1,60 +0,0 @@ - - - - Record - Record - The TXO record is used to define the properties of a text box. It is followed - by two continue records unless there is no actual text. The first continue record contains - the text data and the next continue record contains the formatting runs. - Glen Stampoultzis (glens at apache.org) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/records/definitions/tick_record.xml b/src/records/definitions/tick_record.xml deleted file mode 100644 index d1f704a7c..000000000 --- a/src/records/definitions/tick_record.xml +++ /dev/null @@ -1,44 +0,0 @@ - - - - Record - Record - The Tick record defines how tick marks and label positioning/formatting - Andrew C. Oliver(acoliver at apache.org) - - - - - - - - - - - - - - - - - - - - diff --git a/src/records/definitions/units_record.xml b/src/records/definitions/units_record.xml deleted file mode 100644 index ff281265a..000000000 --- a/src/records/definitions/units_record.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - Record - Record - The units record describes units. - Glen Stampoultzis (glens at apache.org) - - - - diff --git a/src/records/definitions/value_range_record.xml b/src/records/definitions/value_range_record.xml deleted file mode 100644 index c5be1d819..000000000 --- a/src/records/definitions/value_range_record.xml +++ /dev/null @@ -1,44 +0,0 @@ - - - - Record - Record - The value range record defines the range of the value axis. - Glen Stampoultzis (glens at apache.org) - - - - - - - - - - - - - - - - - - - diff --git a/src/records/styles/record.xsl b/src/records/styles/record.xsl deleted file mode 100644 index dae346b5d..000000000 --- a/src/records/styles/record.xsl +++ /dev/null @@ -1,570 +0,0 @@ -<<<<<<< record.xsl - - - - - - - -package ; - - - -import org.apache.poi.util.*; - -/** - * - * NOTE: This source is automatically generated please do not modify this file. Either subclass or - * remove the record in src/records/definitions. - - */ -public class Record - extends Record -{ - public final static short sid = ; - private ; - - - - public Record() - { - - - = ; - - } - - /** - * Constructs a record and sets its fields appropriately. - * - * @param id id must be or an exception - * will be throw upon validation - * @param size size the size of the data area of the record - * @param data data of the record (should not contain sid/len) - */ - - public Record(RecordInputStream in) - { - super(in); - - - - = - ; - - - - } - - /** - * Checks the sid matches the expected side for this record - * - * @param id the expected sid. - */ - protected void validateSid(short id) - { - if (id != sid) - { - throw new RecordFormatException("Not a record"); - } - } - - protected void fillFields(RecordInputStream in) - { - - int pos = 0; - - - - - ; - - } - - public String toString() - { - StringBuffer buffer = new StringBuffer(); - - buffer.append("[]\n"); - - buffer.append("[/]\n"); - return buffer.toString(); - } - - public int serialize(int offset, byte[] data) - { - int pos = 0; - - LittleEndian.putShort(data, 0 + offset, sid); - LittleEndian.putShort(data, 2 + offset, (short)(getRecordSize() - 4)); - - - - - - return getRecordSize(); - } - - /** - * Size of record (exluding 4 byte header) - */ - public int getRecordSize() - { - - return 4 - - -; - } - - public short getSid() - { - return this.sid; - } - - public Object clone() { - Record rec = new Record(); - - - ; - - return rec; - } - - - - - - -} // END OF CLASS - - - - - - - - - - - /** - * Sets the field value. - * - */ - public void set(boolean value) - { - = .setBoolean(, value); - } - - /** - * - * @return the field value. - */ - public boolean is() - { - return .isSet(); - } - - - /** - * Sets the field value. - * - */ - public void set(short value) - { - = .setValue(, value); - } - - /** - * - * @return the field value. - */ - public short get() - { - return .getShortValue(); - } - - - - - private BitField = new BitField(); - private BitField = new BitField(); - - - public final static = ; - - - - - * - - - /** - * Get the field for the record. - * - * @return One of - */ - public get() - { - return ; - } - - /** - * Set the field for the record. - * - * @param - * One of - */ - public void set( ) - { - this. = ; - } - - - - - - buffer.append(System.getProperty("line.separator")); - - - - - - - buffer.append(" . - - = ").append(is - - ()).append('\n'); - - - buffer.append(" . - - = ").append(get - - ()).append('\n'); - - - - - * @author - - - -======= - - - - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - - -package ; - - - -import org.apache.poi.util.*; - -/** - * - * NOTE: This source is automatically generated please do not modify this file. Either subclass or - * remove the record in src/records/definitions. - - */ -public class Record - extends Record -{ - public final static short sid = ; - private ; - - - - public Record() - { - - - = ; - - } - - /** - * Constructs a record and sets its fields appropriately. - * - * @param id id must be or an exception - * will be throw upon validation - * @param size size the size of the data area of the record - * @param data data of the record (should not contain sid/len) - */ - - public Record(short id, short size, byte [] data) - { - super(id, size, data); - - - - = - ; - - - - } - - /** - * Constructs a record and sets its fields appropriately. - * - * @param id id must be or an exception - * will be throw upon validation - * @param size size the size of the data area of the record - * @param data data of the record (should not contain sid/len) - * @param offset of the record's data - */ - - public Record(short id, short size, byte [] data, int offset) - { - super(id, size, data, offset); - - - - = - ; - - - - } - - /** - * Checks the sid matches the expected side for this record - * - * @param id the expected sid. - */ - protected void validateSid(short id) - { - if (id != sid) - { - throw new RecordFormatException("Not a record"); - } - } - - protected void fillFields(byte [] data, short size, int offset) - { - - int pos = 0; - - - - - ; - - } - - public String toString() - { - StringBuffer buffer = new StringBuffer(); - - buffer.append("[]\n"); - - buffer.append("[/]\n"); - return buffer.toString(); - } - - public int serialize(int offset, byte[] data) - { - int pos = 0; - - LittleEndian.putShort(data, 0 + offset, sid); - LittleEndian.putShort(data, 2 + offset, (short)(getRecordSize() - 4)); - - - - - - return getRecordSize(); - } - - /** - * Size of record (exluding 4 byte header) - */ - public int getRecordSize() - { - - return 4 - - -; - } - - public short getSid() - { - return this.sid; - } - - public Object clone() { - Record rec = new Record(); - - - ; - - return rec; - } - - - - - - -} // END OF CLASS - - - - - - - - - - - /** - * Sets the field value. - * - */ - public void set(boolean value) - { - = .setBoolean(, value); - } - - /** - * - * @return the field value. - */ - public boolean is() - { - return .isSet(); - } - - - /** - * Sets the field value. - * - */ - public void set(short value) - { - = .setValue(, value); - } - - /** - * - * @return the field value. - */ - public short get() - { - return .getShortValue(); - } - - - - - private BitField = new BitField(); - private BitField = new BitField(); - - - public final static = ; - - - - - * - - - /** - * Get the field for the record. - * - * @return One of - */ - public get() - { - return ; - } - - /** - * Set the field for the record. - * - * @param - * One of - */ - public void set( ) - { - this. = ; - } - - - - - - buffer.append(System.getProperty("line.separator")); - - - - - - - buffer.append(" . - - = ").append(is - - ()).append('\n'); - - - buffer.append(" . - - = ").append(get - - ()).append('\n'); - - - - - * @author - - - ->>>>>>> 1.11 diff --git a/src/records/styles/record_document.xsl b/src/records/styles/record_document.xsl deleted file mode 100644 index 7895c661b..000000000 --- a/src/records/styles/record_document.xsl +++ /dev/null @@ -1,69 +0,0 @@ - - - - - - -

    - <xsl:value-of select="@name"/> Record Documentation -
    - - - -

    -

    -
    - - - - - - - - - - -
    NameSizeOffsetDescriptionDefault Value
    -
    - -
    - - Copyright (c) @year@ The Poi Project All rights reserved. - -
    - - - - - - - - - - - - - - - diff --git a/src/records/styles/record_test.xsl b/src/records/styles/record_test.xsl deleted file mode 100644 index a70a9491b..000000000 --- a/src/records/styles/record_test.xsl +++ /dev/null @@ -1,121 +0,0 @@ - - - - - - - -package ; - - -import junit.framework.TestCase; - -/** - * Tests the serialization and deserialization of the Record - * class works correctly. Test data taken directly from a real - * Excel file. - * - - */ -public class TestRecord - extends TestCase -{ - byte[] data = new byte[] { - - }; - - public TestRecord(String name) - { - super(name); - } - - public void testLoad() - throws Exception - { - Record record = new Record((short), (short)data.length, data); - - - - assertEquals( "", record.get()); - - assertEquals( (byte), record.get()); - - assertEquals( (short), record.get()); - - assertEquals( (int), record.get()); - - assertEquals( (double), record.get()); - - - - - assertEquals( , record.getRecordSize() ); - - record.validateSid((short)); - } - - public void testStore() - { - Record record = new Record(); - - - - - record.set( "" ); - - record.set( (byte) ); - - record.set( (short) ); - - record.set( (int) ); - - record.set( (double) ); - - - - - - byte [] recordBytes = record.serialize(); - assertEquals(recordBytes.length - 4, data.length); - for (int i = 0; i < data.length; i++) - assertEquals("At offset " + i, data[i], recordBytes[i+4]); - } -} - - - - * @author - - - - assertEquals( , record.is() ); - - - - - record.set( ); - - - - diff --git a/src/resources/devtools/complete-log4j.properties b/src/resources/devtools/complete-log4j.properties deleted file mode 100644 index 0959ec27d..000000000 --- a/src/resources/devtools/complete-log4j.properties +++ /dev/null @@ -1,46 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -#log4j.rootCategory=debug, globalLog -log4j.category.org.apache.poi.hssf=debug, hssfLog -log4j.category.org.apache.poi.hdf=debug, hdfLog -log4j.category.org.apache.poi.hpsf=debug, hpsfLog -log4j.category.org.apache.poi.poifs=debug, poifsLog -log4j.category.org.apache.poi.util=debug, utilLog - -log4j.appender.hssfLog=org.apache.log4j.FileAppender -log4j.appender.hssfLog.File=build/hssf.log -log4j.appender.hssfLog.layout=org.apache.log4j.PatternLayout -log4j.appender.hssfLog.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n - -log4j.appender.hdfLog=org.apache.log4j.FileAppender -log4j.appender.hdfLog.File=build/hdf.log -log4j.appender.hdfLog.layout=org.apache.log4j.PatternLayout -log4j.appender.hdfLog.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n - -log4j.appender.hpsfLog=org.apache.log4j.FileAppender -log4j.appender.hpsfLog.File=build/hpsf.log -log4j.appender.hpsfLog.layout=org.apache.log4j.PatternLayout -log4j.appender.hpsfLog.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n - -log4j.appender.poifsLog=org.apache.log4j.FileAppender -log4j.appender.poifsLog.File=build/poifs.log -log4j.appender.poifsLog.layout=org.apache.log4j.PatternLayout -log4j.appender.poifsLog.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n - -log4j.appender.utilLog=org.apache.log4j.FileAppender -log4j.appender.utilLog.File=build/util.log -log4j.appender.utilLog.layout=org.apache.log4j.PatternLayout -log4j.appender.utilLog.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n diff --git a/src/resources/devtools/fatal-only-log4j.properties b/src/resources/devtools/fatal-only-log4j.properties deleted file mode 100644 index c1e023ae6..000000000 --- a/src/resources/devtools/fatal-only-log4j.properties +++ /dev/null @@ -1,27 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Set root logger level to FATAL and its only appender to stdout -log4j.rootLogger=FATAL, stdout -log4j.category.org=FATAL, stdout - -# stdout is set to be a ConsoleAppender. -log4j.appender.stdout=org.apache.log4j.ConsoleAppender - -# stdout uses PatternLayout. -log4j.appender.stdout.layout=org.apache.log4j.PatternLayout -log4j.appender.stdout.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n - - diff --git a/src/resources/devtools/findbugs-filters.xml b/src/resources/devtools/findbugs-filters.xml deleted file mode 100644 index 0355a441a..000000000 --- a/src/resources/devtools/findbugs-filters.xml +++ /dev/null @@ -1,134 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/resources/devtools/forbidden-signatures-prod.txt b/src/resources/devtools/forbidden-signatures-prod.txt deleted file mode 100644 index 59dcf4789..000000000 --- a/src/resources/devtools/forbidden-signatures-prod.txt +++ /dev/null @@ -1,32 +0,0 @@ -# (C) Copyright Uwe Schindler (Generics Policeman) and others. -# Parts of this work are licensed to the Apache Software Foundation (ASF) -# under one or more contributor license agreements. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This file contains API signatures which are specific to POI. -# The goal is to minimize implicit defaults - -@defaultMessage POI forbidden APIs which are tolerated in non-production code, e.g. in tests and examples - -# We have applications which use this to return error codes on invalid commandline parameters... -#@defaultMessage Please do not terminate the application -#java.lang.System#exit(int) -#java.lang.Runtime#exit(int) -#java.lang.Runtime#halt(int) - - -java.lang.System#gc() @ Please do not try to stop the world -java.lang.Throwable#printStackTrace() @ Please use POILogger for exceptions -java.lang.Throwable#printStackTrace(java.io.PrintStream) @ Please use POILogger for exceptions -java.lang.Throwable#printStackTrace(java.io.PrintWriter) @ Please use POILogger for exceptions \ No newline at end of file diff --git a/src/resources/devtools/forbidden-signatures.txt b/src/resources/devtools/forbidden-signatures.txt deleted file mode 100644 index 54b285678..000000000 --- a/src/resources/devtools/forbidden-signatures.txt +++ /dev/null @@ -1,111 +0,0 @@ -# (C) Copyright Uwe Schindler (Generics Policeman) and others. -# Parts of this work are licensed to the Apache Software Foundation (ASF) -# under one or more contributor license agreements. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# This file contains API signatures which are specific to POI. -# The goal is to minimize implicit defaults - -@ignoreUnresolvable -@defaultMessage POI forbidden APIs - -# Locale related interfaces which we want to avoid to not have code which depends on the locale of the current machine -java.util.Locale#getDefault() @ Do not use methods that depend on the current Local, either use Locale.ROOT or let the user define the local, see class LocaleUtil for details -java.util.Locale#setDefault(java.util.Locale) @ Do not use methods that depend on the current Local, either use Locale.ROOT or let the user define the local, see class LocaleUtil for details -java.util.TimeZone#getDefault() @ Do not use methods that depend on the current Local, either use Locale.ROOT or let the user define the local, see class LocaleUtil for details -java.util.Date#toString() @ Do not use methods that depend on the current Local, either use Locale.ROOT or let the user define the local, see class LocaleUtil for details - -java.text.DecimalFormatSymbols#() @ use DecimalFormatSymbols.getInstance() -java.text.DecimalFormatSymbols#(java.util.Locale) @ use DecimalFormatSymbols.getInstance() - -# the following are taken from the Elasticsearch source at https://github.com/elastic/elasticsearch/tree/master/buildSrc/src/main/resources/forbidden - -@defaultMessage Convert to URI -java.net.URL#getPath() -java.net.URL#getFile() - -@defaultMessage Usage of getLocalHost is discouraged -java.net.InetAddress#getLocalHost() - -@defaultMessage Specify a location for the temp file/directory instead. -java.nio.file.Files#createTempDirectory(java.lang.String,java.nio.file.attribute.FileAttribute[]) -java.nio.file.Files#createTempFile(java.lang.String,java.lang.String,java.nio.file.attribute.FileAttribute[]) - -@defaultMessage Specify a location for the temp file/directory instead. -java.nio.file.Files#createTempDirectory(java.lang.String,java.nio.file.attribute.FileAttribute[]) -java.nio.file.Files#createTempFile(java.lang.String,java.lang.String,java.nio.file.attribute.FileAttribute[]) - -@defaultMessage Don't use java serialization - this can break BWC without noticing it -java.io.ObjectOutputStream -java.io.ObjectOutput -java.io.ObjectInputStream -java.io.ObjectInput - -@defaultMessage Resolve hosts explicitly to the address(es) you want with InetAddress. -java.net.InetSocketAddress#(java.lang.String,int) -java.net.Socket#(java.lang.String,int) -java.net.Socket#(java.lang.String,int,java.net.InetAddress,int) - -@defaultMessage Don't bind to wildcard addresses. Be specific. -java.net.DatagramSocket#() -java.net.DatagramSocket#(int) -java.net.InetSocketAddress#(int) -java.net.MulticastSocket#() -java.net.MulticastSocket#(int) -java.net.ServerSocket#(int) -java.net.ServerSocket#(int,int) - -@defaultMessage use NetworkAddress format/formatAddress to print IP or IP+ports -java.net.InetAddress#toString() -java.net.InetAddress#getHostAddress() -java.net.Inet4Address#getHostAddress() -java.net.Inet6Address#getHostAddress() -java.net.InetSocketAddress#toString() - -@defaultMessage avoid DNS lookups by accident: if you have a valid reason, then @SuppressWarnings with that reason so its completely clear -java.net.InetAddress#getHostName() -java.net.InetAddress#getCanonicalHostName() - -java.net.InetSocketAddress#getHostName() @ Use getHostString() instead, which avoids a DNS lookup - -@defaultMessage this method needs special permission -java.lang.Thread#getAllStackTraces() - -@defaultMessage Avoid unchecked warnings by using Collections#empty(List|Map|Set) methods -java.util.Collections#EMPTY_LIST -java.util.Collections#EMPTY_MAP -java.util.Collections#EMPTY_SET - - -@defaultMessage spawns threads with vague names; use a custom thread factory and name threads so that you can tell (by its name) which executor it is associated with -java.util.concurrent.Executors#newFixedThreadPool(int) -java.util.concurrent.Executors#newSingleThreadExecutor() -java.util.concurrent.Executors#newCachedThreadPool() -java.util.concurrent.Executors#newSingleThreadScheduledExecutor() -java.util.concurrent.Executors#newScheduledThreadPool(int) -java.util.concurrent.Executors#defaultThreadFactory() -java.util.concurrent.Executors#privilegedThreadFactory() - -java.lang.Character#codePointBefore(char[],int) @ Implicit start offset is error-prone when the char[] is a buffer and the first chars are random chars -java.lang.Character#codePointAt(char[],int) @ Implicit end offset is error-prone when the char[] is a buffer and the last chars are random chars - -@defaultMessage Only use wait / notify when really needed try to use concurrency primitives, latches or callbacks instead. -java.lang.Object#wait() -java.lang.Object#wait(long) -java.lang.Object#wait(long,int) -java.lang.Object#notify() -java.lang.Object#notifyAll() - -@defaultMessage Don't interrupt threads use FutureUtils#cancel(Future) instead -java.util.concurrent.Future#cancel(boolean) diff --git a/src/resources/devtools/poi.jin b/src/resources/devtools/poi.jin deleted file mode 100644 index c52acef80..000000000 --- a/src/resources/devtools/poi.jin +++ /dev/null @@ -1,284 +0,0 @@ -### -### Jindent 3.2x property file -- http://www.jindent.de -### -### this encapsulates my preferred style, plus project-specific style ... -### -### author: Marc Johnson -### - -### General -- Convention - -conventionName = "" -conventionString = "" -conventionNotePosition = "none" -blankLinesToSeparateConventionNote = 2 - -### General -- Jindent Note - -jindentNotePosition = "none" -blankLinesToSeparateJindentNote = 2 - -### Header/Footer -- Header Template - -headerSmartMode = infinite -headerIdentifyKey = "Copyright (c) 2002-2006 The Apache Software Foundation" -blankLinesBeforeHeader = 1 -header[00]="/* ===================================================================" -header[01]=" * Licensed to the Apache Software Foundation (ASF) under one" -header[02]=" * or more contributor license agreements. See the NOTICE file" -header[03]=" * distributed with this work for additional information" -header[04]=" * regarding copyright ownership. The ASF licenses this file" -header[05]=" * to you under the Apache License, Version 2.0 (the" -header[06]=" * \"License\"); you may not use this file except in compliance" -header[07]=" * with the License. You may obtain a copy of the License at" -header[08]=" * " -header[09]=" * http://www.apache.org/licenses/LICENSE-2.0" -header[10]=" * " -header[11]=" * Unless required by applicable law or agreed to in writing," -header[12]=" * software distributed under the License is distributed on an" -header[13]=" * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY" -header[14]=" * KIND, either express or implied. See the License for the" -header[15]=" * specific language governing permissions and limitations" -header[16]=" * under the License" -header[17]=" */" -blankLinesAfterHeader = 1 - -### Header/Footer -- Footer Template - -footerSmartMode = infinite -footerIdentifyKey = "" -blankLinesBeforeFooter = 0 -footer[00] = "" -blankLinesAfterFooter = 0 - -### Indentation -- Misc - -tabulatorSize = 8 -indentSize = 4 -firstLevelIndent = 0 -indentCaseFromSwitch = true -labelNewLine = true -indentLabels = true -minimumCommentIndent = 3 -indentLeadingsByTabs = false -indentCommentsByTabs = false -indentDeclarationsByTabs = false -indentAssignmentsByTabs = false - -### Indentation -- Alignment - -alignComments = true -alignDeclarations = true -alignAssignments = true -alignTernaryConditions = false -alignTernaryExpressions = true -alignTooLongComments = true - -### Braces -- Style - -leftBraceNewLineGeneral = true -rightBraceNewLineGeneral = true -indentLeftBraceGeneral = 0 -indentRightBraceGeneral = 0 -indentAfterRightBraceGeneral = 0 -cuddleEmptyBracesGeneral = false -indentCuddledBracesGeneral = 0 - -leftBraceNewLineClassInterface = true -rightBraceNewLineClassInterface = true -indentLeftBraceClassInterface = 0 -indentRightBraceClassInterface = 0 -indentAfterRightBraceClassInterface = 0 -cuddleEmptyBracesClassInterface = false -indentCuddledBracesClassInterface = 0 - -leftBraceNewLineMethod = true -rightBraceNewLineMethod = true -indentLeftBraceMethod = 0 -indentRightBraceMethod = 0 -indentAfterRightBraceMethod = 0 -cuddleEmptyBracesMethod = false -indentCuddledBracesMethod = 0 - -leftBraceNewLineTryCatch = true -rightBraceNewLineTryCatch = true -indentLeftBraceTryCatch = 0 -indentRightBraceTryCatch = 0 -indentAfterRightBraceTryCatch = 0 -cuddleEmptyBracesTryCatch = false -indentCuddledBracesTryCatch = 0 - -### Braces -- Insert At - -insertBracesAtIfElse = true -insertBracesAtFor = true -insertBracesAtWhile = true -insertBracesAtDoWhile = true -insertParenthesisAtConditions = true - -### Braces -- If-Else - -singleIfStatementInOneLine = false -singleElseStatementInOneLine = false -specialElseIfTreatment = true - -### JavaDoc -- Misc - -deleteJavaDocComments = false -formatJavaDocComments = true -insertMissingJavaDocTags = true -deleteObsoleteJavaDocTags = false -createPublicClassInterfaceJavaDocs = true -createFriendlyClassInterfaceJavaDocs = false -createPrivateClassInterfaceJavaDocs = false -createProtectedClassInterfaceJavaDocs = false -createPublicMethodJavaDocs = false -createFriendlyMethodJavaDocs = false -createPrivateMethodJavaDocs = false -createProtectedMethodJavaDocs = false -createPublicFieldJavaDocs = false -createFriendlyFieldJavaDocs = false -createPrivateFieldJavaDocs = false -createProtectedFieldJavaDocs = false - -### JavaDoc -- Templates - -sortExceptionsInTemplates = true -javaDocMethodTop[00] = "/**" -javaDocMethodTop[01] = " * Method $objectName$" -javaDocMethodTop[02] = " *" -javaDocMethodParamSeparator[00] = " *" -javaDocMethodParam[00] = " * @param $paramName$" -javaDocMethodReturn[00] = " *" -javaDocMethodReturn[01] = " * @return" -javaDocMethodExceptionSeparator[00] = " *" -javaDocMethodException[00] = " * @exception $exceptionName$" -javaDocMethodBottom[00] = " *" -javaDocMethodBottom[01] = " */" -javaDocConstructorTop[00] = "/**" -javaDocConstructorTop[01] = " * Constructor $objectName$" -javaDocConstructorTop[02] = " *" -javaDocConstructorParamSeparator[00] = " *" -javaDocConstructorParam[00] = " * @param $paramName$" -javaDocConstructorExceptionSeparator[00] = " *" -javaDocConstructorException[00] = " * @exception $exceptionName$" -javaDocConstructorBottom[00] = " *" -javaDocConstructorBottom[01] = " */" -javaDocClass[00] = "/**" -javaDocClass[01] = " * Class $objectName$" -javaDocClass[02] = " *" -javaDocClass[03] = " *" -javaDocClass[04] = " * @author" -javaDocClass[05] = " * @version %I%, %G%" -javaDocClass[06] = " */" -javaDocInterface[00] = "/**" -javaDocInterface[01] = " * Interface $objectName$" -javaDocInterface[02] = " *" -javaDocInterface[03] = " *" -javaDocInterface[04] = " * @author" -javaDocInterface[05] = " * @version %I%, %G%" -javaDocInterface[06] = " */" -javaDocField[00] = "/** Field $objectName$ */" - -### Comments -- Format/Delete - -deleteBlockComments = false -deleteSingleLineComments = false -deleteTrailingComments = false -deleteEndOfLineComments = false -formatBlockComments = true -formatSingleLineComments = true -formatTrailingComments = true -formatEndOfLineComments = true - -### Comments -- Exceptions - -neverIndentFirstColumnComments = true -neverFormatFirstColumnComments = true -neverFormatHeader = false -neverFormatFooter = false - -### Separation -- Misc - -keepBlankLines = 0 -minLinesToInsertBlankLineInClasses = infinite -minLinesToInsertBlankLineInMethods = infinite - -### Separation -- Separate - -separateChunksByComments = false -allowBreakSeparatedFromCaseBlock = false -blankLinesBetweenCaseBlocks = 1 -blankLinesBetweenChunks = 0 -comparableImportDepth = 2 -blankLinesToSeparateImports = 1 -blankLinesBetweenClassInterface = 2 - -### Separation -- Insert Blank Lines - -blankLinesAfterDeclarations = 1 -blankLinesAfterMethods = 1 -blankLinesAfterClasses = 1 -blankLinesAfterInterfaces = 1 -blankLinesBeforeJavaDocComments = 1 -blankLinesAfterJavaDocComments = 1 -blankLinesBeforeBlockComments = 1 -blankLinesAfterBlockComments = 0 -blankLinesBeforeSingleLineComments = 1 -blankLinesAfterSingleLineComments = 0 -blankLinesBeforeEndOfLineComments = 1 -blankLinesAfterEndOfLineComments = 0 -blankLinesAfterSwitch = 1 -blankLinesAfterPackage = 1 -blankLinesAfterLastImport = 1 - -### Whitespaces -- Padding - -separateAssignmentOperators = true -separateConditionalOperators = true -separateComparisonOperators = true -separateNumericalOperators = true -paddingCastParenthesis = true -paddingParenthesis = false -paddingBrackets = true -paddingBraces = true - -### Whitespaces -- Space Before - -spaceBeforeMethodDeclarationParenthesis = false -spaceBeforeMethodCallParenthesis = false -spaceBeforeBrackets = false -spaceBeforeBracketsInTypes = true -spaceBeforeStatementParenthesis = true -spaceBeforeConditionBang = true -spaceBeforeCaseColon = true - -### Whitespaces -- Space After - -spaceAfterComma = true -spaceAfterSemicolon = true -spaceAfterCasting = true - -### Whitespaces -- No Spaces - -noSpacesInEmptyForExpressions = true - -### Line Wrapping -- Misc - -maxFieldElementsPerLine = 0 -wrapLines = true -wrapBecauseOfComments = true -wrapLongMethodNames = true -maxLineLength = 78 -deepIndent = 45 -forceIndent = 8 -forceIndentTolerance = 4 -allowWrappingAfterAssignments = true -allowWrappingAfterParenthesis = true -preferWrappingAfterThrows = true -alwaysWrapThrows = true -alwaysWrapExtends = true -alwaysWrapImplements = true -indentWrappedThrows = 4 -indentWrappedExtends = 4 -indentWrappedImplements = 4 diff --git a/src/resources/devtools/unpack_ooxml.sh b/src/resources/devtools/unpack_ooxml.sh deleted file mode 100755 index a4b8703a8..000000000 --- a/src/resources/devtools/unpack_ooxml.sh +++ /dev/null @@ -1,45 +0,0 @@ -#!/bin/bash -e -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# basename it - -FILENAME="$1" -BASENAME="${FILENAME##*/}" -OUTDIR="${BASENAME%.*}" - -if [ ! -f "$FILENAME" ]; then - echo "File $FILENAME does not exist" - exit 1 -fi - -# if dir exists, fail -if [ -d "$OUTDIR" ]; then - echo "Directory '$OUTDIR' already exists!" - exit 1 -fi - -mkdir "$OUTDIR" -unzip -d "$OUTDIR" "$FILENAME" - -pushd "$OUTDIR" - -find . -type f \( -iname "*.xml" -or -iname "*.rels" \) -exec python -c "import os, sys, xml.dom.minidom -with open('{}', 'r') as fp: - s = fp.read() -with open('{}.bak', 'w') as fp: - fp.write(xml.dom.minidom.parseString(s).toprettyxml().encode('utf-8')) -os.rename('{}.bak', '{}')" \; diff --git a/src/resources/logos/logoKarmokar4.png b/src/resources/logos/logoKarmokar4.png deleted file mode 100644 index 90a915a3a..000000000 Binary files a/src/resources/logos/logoKarmokar4.png and /dev/null differ diff --git a/src/resources/logos/logoKarmokar4edited.png b/src/resources/logos/logoKarmokar4edited.png deleted file mode 100644 index 73c02a560..000000000 Binary files a/src/resources/logos/logoKarmokar4edited.png and /dev/null differ diff --git a/src/resources/logos/logoKarmokar4s.png b/src/resources/logos/logoKarmokar4s.png deleted file mode 100644 index 33391cd96..000000000 Binary files a/src/resources/logos/logoKarmokar4s.png and /dev/null differ diff --git a/src/resources/logos/logoKarmokar5.png b/src/resources/logos/logoKarmokar5.png deleted file mode 100644 index e2d1f3f85..000000000 Binary files a/src/resources/logos/logoKarmokar5.png and /dev/null differ diff --git a/src/resources/logos/project-alt-logo.jpg b/src/resources/logos/project-alt-logo.jpg deleted file mode 100644 index 073175151..000000000 Binary files a/src/resources/logos/project-alt-logo.jpg and /dev/null differ diff --git a/src/resources/logos/project-feather-logo.jpg b/src/resources/logos/project-feather-logo.jpg deleted file mode 100644 index 24c9e06dd..000000000 Binary files a/src/resources/logos/project-feather-logo.jpg and /dev/null differ diff --git a/src/resources/main/org/apache/poi/sl/draw/geom/presetShapeDefinitions.xml b/src/resources/main/org/apache/poi/sl/draw/geom/presetShapeDefinitions.xml deleted file mode 100644 index 4a3a0701d..000000000 --- a/src/resources/main/org/apache/poi/sl/draw/geom/presetShapeDefinitions.xml +++ /dev/null @@ -1,19906 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/resources/main/org/apache/poi/ss/formula/function/functionMetadata-asGenerated.txt b/src/resources/main/org/apache/poi/ss/formula/function/functionMetadata-asGenerated.txt deleted file mode 100644 index b56f65e23..000000000 --- a/src/resources/main/org/apache/poi/ss/formula/function/functionMetadata-asGenerated.txt +++ /dev/null @@ -1,285 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Created by (org.apache.poi.hssf.record.formula.function.ExcelFileFormatDocFunctionExtractor) -# from source file 'excelfileformat.odt' (size=356107, md5=0x8f789cb6e75594caf068f8e193004ef4) -# -#Columns: (index, name, minParams, maxParams, returnClass, paramClasses, isVolatile, hasFootnote ) - -# Built-In Sheet Functions in BIFF2 -0 COUNT 0 30 V R -1 IF 2 3 R V R R -2 ISNA 1 1 V V -3 ISERROR 1 1 V V -4 SUM 0 30 V R -5 AVERAGE 1 30 V R -6 MIN 1 30 V R -7 MAX 1 30 V R -8 ROW 0 1 V R -9 COLUMN 0 1 V R -10 NA 0 0 V - -11 NPV 2 30 V V R -12 STDEV 1 30 V R -13 DOLLAR 1 2 V V V -14 FIXED 2 2 V V V x -15 SIN 1 1 V V -16 COS 1 1 V V -17 TAN 1 1 V V -18 ATAN 1 1 V V -19 PI 0 0 V - -20 SQRT 1 1 V V -21 EXP 1 1 V V -22 LN 1 1 V V -23 LOG10 1 1 V V -24 ABS 1 1 V V -25 INT 1 1 V V -26 SIGN 1 1 V V -27 ROUND 2 2 V V V -28 LOOKUP 2 3 V V R R -29 INDEX 2 4 R R V V V -30 REPT 2 2 V V V -31 MID 3 3 V V V V -32 LEN 1 1 V V -33 VALUE 1 1 V V -34 TRUE 0 0 V - -35 FALSE 0 0 V - -36 AND 1 30 V R -37 OR 1 30 V R -38 NOT 1 1 V V -39 MOD 2 2 V V V -40 DCOUNT 3 3 V R R R -41 DSUM 3 3 V R R R -42 DAVERAGE 3 3 V R R R -43 DMIN 3 3 V R R R -44 DMAX 3 3 V R R R -45 DSTDEV 3 3 V R R R -46 VAR 1 30 V R -47 DVAR 3 3 V R R R -48 TEXT 2 2 V V V -49 LINEST 1 2 A R R x -50 TREND 1 3 A R R R x -51 LOGEST 1 2 A R R x -52 GROWTH 1 3 A R R R x -56 PV 3 5 V V V V V V -# Built-In Sheet Functions in BIFF2 -57 FV 3 5 V V V V V V -58 NPER 3 5 V V V V V V -59 PMT 3 5 V V V V V V -60 RATE 3 6 V V V V V V V -61 MIRR 3 3 V R V V -62 IRR 1 2 V R V -63 RAND 0 0 V - x -64 MATCH 2 3 V V R R -65 DATE 3 3 V V V V -66 TIME 3 3 V V V V -67 DAY 1 1 V V -68 MONTH 1 1 V V -69 YEAR 1 1 V V -70 WEEKDAY 1 1 V V x -71 HOUR 1 1 V V -72 MINUTE 1 1 V V -73 SECOND 1 1 V V -74 NOW 0 0 V - x -75 AREAS 1 1 V R -76 ROWS 1 1 V R -77 COLUMNS 1 1 V R -78 OFFSET 3 5 R R V V V V x -82 SEARCH 2 3 V V V V -83 TRANSPOSE 1 1 A A -86 TYPE 1 1 V V -97 ATAN2 2 2 V V V -98 ASIN 1 1 V V -99 ACOS 1 1 V V -100 CHOOSE 2 30 R V R -101 HLOOKUP 3 3 V V R R x -102 VLOOKUP 3 3 V V R R x -105 ISREF 1 1 V R -109 LOG 1 2 V V V -111 CHAR 1 1 V V -112 LOWER 1 1 V V -113 UPPER 1 1 V V -114 PROPER 1 1 V V -115 LEFT 1 2 V V V -116 RIGHT 1 2 V V V -117 EXACT 2 2 V V V -118 TRIM 1 1 V V -119 REPLACE 4 4 V V V V V -120 SUBSTITUTE 3 4 V V V V V -121 CODE 1 1 V V -124 FIND 2 3 V V V V -125 CELL 1 2 V V R x -126 ISERR 1 1 V V -127 ISTEXT 1 1 V V -128 ISNUMBER 1 1 V V -129 ISBLANK 1 1 V V -130 T 1 1 V R -131 N 1 1 V R -140 DATEVALUE 1 1 V V -141 TIMEVALUE 1 1 V V -142 SLN 3 3 V V V V -143 SYD 4 4 V V V V V -144 DDB 4 5 V V V V V V -148 INDIRECT 1 2 R V V x -162 CLEAN 1 1 V V -163 MDETERM 1 1 V A -164 MINVERSE 1 1 A A -165 MMULT 2 2 A A A -167 IPMT 4 6 V V V V V V V -168 PPMT 4 6 V V V V V V V -169 COUNTA 0 30 V R -183 PRODUCT 0 30 V R -184 FACT 1 1 V V -189 DPRODUCT 3 3 V R R R -190 ISNONTEXT 1 1 V V -193 STDEVP 1 30 V R -194 VARP 1 30 V R -195 DSTDEVP 3 3 V R R R -196 DVARP 3 3 V R R R -197 TRUNC 1 1 V V x -198 ISLOGICAL 1 1 V V -199 DCOUNTA 3 3 V R R R -# New Built-In Sheet Functions in BIFF3 -49 LINEST 1 4 A R R V V x -50 TREND 1 4 A R R R V x -51 LOGEST 1 4 A R R V V x -52 GROWTH 1 4 A R R R V x -197 TRUNC 1 2 V V V x -204 YEN 1 2 V V V x -205 FINDB 2 3 V V V V -206 SEARCHB 2 3 V V V V -207 REPLACEB 4 4 V V V V V -208 LEFTB 1 2 V V V -209 RIGHTB 1 2 V V V -210 MIDB 3 3 V V V V -211 LENB 1 1 V V -212 ROUNDUP 2 2 V V V -213 ROUNDDOWN 2 2 V V V -214 ASC 1 1 V V -215 JIS 1 1 V V x -219 ADDRESS 2 5 V V V V V V -220 DAYS360 2 2 V V V x -221 TODAY 0 0 V - x -222 VDB 5 7 V V V V V V V V -227 MEDIAN 1 30 V R ... -228 SUMPRODUCT 1 30 V A ... -229 SINH 1 1 V V -230 COSH 1 1 V V -231 TANH 1 1 V V -232 ASINH 1 1 V V -233 ACOSH 1 1 V V -234 ATANH 1 1 V V -235 DGET 3 3 V R R R -244 INFO 1 1 V V -# New Built-In Sheet Functions in BIFF4 -14 FIXED 2 3 V V V V x -204 USDOLLAR 1 2 V V V x -215 DBCS 1 1 V V x -216 RANK 2 3 V V R V -247 DB 4 5 V V V V V V -252 FREQUENCY 2 2 A R R -261 ERROR.TYPE 1 1 V V -269 AVEDEV 1 30 V R ... -270 BETADIST 3 5 V V V V V V -271 GAMMALN 1 1 V V -272 BETAINV 3 5 V V V V V V -273 BINOMDIST 4 4 V V V V V -274 CHIDIST 2 2 V V V -275 CHIINV 2 2 V V V -276 COMBIN 2 2 V V V -277 CONFIDENCE 3 3 V V V V -278 CRITBINOM 3 3 V V V V -279 EVEN 1 1 V V -280 EXPONDIST 3 3 V V V V -281 FDIST 3 3 V V V V -282 FINV 3 3 V V V V -283 FISHER 1 1 V V -284 FISHERINV 1 1 V V -285 FLOOR 2 2 V V V -286 GAMMADIST 4 4 V V V V V -287 GAMMAINV 3 3 V V V V -288 CEILING 2 2 V V V -289 HYPGEOMDIST 4 4 V V V V V -290 LOGNORMDIST 3 3 V V V V -291 LOGINV 3 3 V V V V -292 NEGBINOMDIST 3 3 V V V V -293 NORMDIST 4 4 V V V V V -294 NORMSDIST 1 1 V V -295 NORMINV 3 3 V V V V -296 NORMSINV 1 1 V V -297 STANDARDIZE 3 3 V V V V -298 ODD 1 1 V V -299 PERMUT 2 2 V V V -300 POISSON 3 3 V V V V -301 TDIST 3 3 V V V V -302 WEIBULL 4 4 V V V V V -303 SUMXMY2 2 2 V A A -304 SUMX2MY2 2 2 V A A -305 SUMX2PY2 2 2 V A A -306 CHITEST 2 2 V A A -307 CORREL 2 2 V A A -308 COVAR 2 2 V A A -309 FORECAST 3 3 V V A A -310 FTEST 2 2 V A A -311 INTERCEPT 2 2 V A A -312 PEARSON 2 2 V A A -313 RSQ 2 2 V A A -314 STEYX 2 2 V A A -315 SLOPE 2 2 V A A -316 TTEST 4 4 V A A V V -317 PROB 3 4 V A A V V -318 DEVSQ 1 30 V R ... -319 GEOMEAN 1 30 V R ... -320 HARMEAN 1 30 V R ... -321 SUMSQ 0 30 V R ... -322 KURT 1 30 V R ... -323 SKEW 1 30 V R ... -324 ZTEST 2 3 V R V V -325 LARGE 2 2 V R V -326 SMALL 2 2 V R V -327 QUARTILE 2 2 V R V -328 PERCENTILE 2 2 V R V -329 PERCENTRANK 2 3 V R V V -330 MODE 1 30 V A -331 TRIMMEAN 2 2 V R V -332 TINV 2 2 V V V -# New Built-In Sheet Functions in BIFF5 -70 WEEKDAY 1 2 V V V x -101 HLOOKUP 3 4 V V R R V x -102 VLOOKUP 3 4 V V R R V x -220 DAYS360 2 3 V V V V x -336 CONCATENATE 0 30 V V -337 POWER 2 2 V V V -342 RADIANS 1 1 V V -343 DEGREES 1 1 V V -344 SUBTOTAL 2 30 V V R -345 SUMIF 2 3 V R V R -346 COUNTIF 2 2 V R V -347 COUNTBLANK 1 1 V R -350 ISPMT 4 4 V V V V V -351 DATEDIF 3 3 V V V V -352 DATESTRING 1 1 V V -353 NUMBERSTRING 2 2 V V V -354 ROMAN 1 2 V V V -# New Built-In Sheet Functions in BIFF8 -358 GETPIVOTDATA 2 30 -359 HYPERLINK 1 2 V V V -360 PHONETIC 1 1 V R -361 AVERAGEA 1 30 V R ... -362 MAXA 1 30 V R ... -363 MINA 1 30 V R ... -364 STDEVPA 1 30 V R ... -365 VARPA 1 30 V R ... -366 STDEVA 1 30 V R ... -367 VARA 1 30 V R ... diff --git a/src/resources/ooxml/org/apache/poi/xslf/usermodel/empty.pptx b/src/resources/ooxml/org/apache/poi/xslf/usermodel/empty.pptx deleted file mode 100644 index ababa9379..000000000 Binary files a/src/resources/ooxml/org/apache/poi/xslf/usermodel/empty.pptx and /dev/null differ diff --git a/src/resources/ooxml/org/apache/poi/xslf/usermodel/notesMaster.xml b/src/resources/ooxml/org/apache/poi/xslf/usermodel/notesMaster.xml deleted file mode 100644 index 0a8db65bd..000000000 --- a/src/resources/ooxml/org/apache/poi/xslf/usermodel/notesMaster.xml +++ /dev/null @@ -1,2 +0,0 @@ - -1.7.2013Click to edit Master text stylesSecond levelThird levelFourth levelFifth level‹#› \ No newline at end of file diff --git a/src/resources/scratchpad/org/apache/poi/hdgf/chunks_parse_cmds.tbl b/src/resources/scratchpad/org/apache/poi/hdgf/chunks_parse_cmds.tbl deleted file mode 100644 index 7cb715abd..000000000 --- a/src/resources/scratchpad/org/apache/poi/hdgf/chunks_parse_cmds.tbl +++ /dev/null @@ -1,993 +0,0 @@ -# vsdump: test program to dump and parse content of vsd file -# -# Copyright (C) 2006-2007 Valek Filippov (frob@df.ru) -# -# This file is dual-licensed (GPLv3 and ASLv2). -# -# ======================================================================= -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ======================================================================= -# This program is free software; you can redistribute it and/or -# modify it under the terms of version 3 or later of the GNU General Public -# License as published by the Free Software Foundation. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 -# USA -# ======================================================================= -# -# version 0.0.45 -# -# Need to extend with 'format' field for conversion length (inch->mm), angles(rad->degree) and enums (e.g. -# for aligns -- left/right/justify etc. -# -# The Format description for .tbl file. -# Lines start with # are comments. -# Every list of commands starts with 'start ch_type' -# and ends with 'end'. -# In between start and end are space-separeted lines -# with 'type', 'offset', 'name' values. -# Atm I use 'atoi', so only decimal value is allowed for ch_type, type and offset. -# The possible values for 'type' are: -# 0..7 - flag at bit 0..7 at offset 'offset' -# 8 - 1 byte value -# 9 - 8 bytes IEEE-754 fraction -# 10(a) - name of chunk (we must start with a name atm, because with parse for printing) -# 11(b) - offset to start of blocks -# 12(c) - text block -# 13(d) - some "name" from the list -# 14(e) - one byte "function" from the list -# 15(f) - some "function" from the list -# 16 - string, next byte is length terminating '0' wasn't added to length -# 17 - 'ForeignData' -# 18 - Dump it to file as-is -# 25 - 2 bytes LE -# 26 - 4 bytes LE -# 27 - Tabs? [experimental] -# 21 - offset to start of blocks in version 11 -# 28 - extension for image files [experimental] -# 29 - num of parts and type for OLE [experimental] -# 30 - 3 bytes RGB-color -# 31 - 9 bytes -- 1st is 'Unit', + 8 bytes IEEE-754 fraction - -# Quick workaround for losing of 1st table -start 10 -end - -start 12 -17 0 ForeignData -end - -start 13 -10 0 OLE_Info -29 0 0 -18 0 0 -end - -start 14 -10 0 Text -12 8 0 -18 0 0 -end - -start 16 -10 0 Data1 -12 0 0 -end - -start 17 -10 0 Data2 -12 0 0 -end - -start 18 -10 0 Data3 -12 0 0 -end - -start 21 -10 0 Stream15 -9 53 Center X -9 61 Center Y -18 0 0 -end - -start 24 -10 0 Stream18 -18 0 0 -end - -start 25 -10 0 FaceName -16 24 0 -end - -start 26 -10 0 Stream1a -18 0 0 -end - -start 31 -17 0 OLEData -end - -start 40 -10 0 Unknown 0x28 -9 39 Unknown1 -9 47 Unknown2 -18 0 0 -end - -start 44 -10 0 Unknown 0x2c -18 0 0 -end - -#seems to be text string -start 45 -10 0 Unknown 0x2d -12 0 0 -end - -start 49 -10 0 Stream31 -18 0 0 -end - -start 66 -10 0 Unknown 0x42 -18 0 0 -end - -start 70 -10 0 PageSheet -18 0 0 -end - -start 71 -10 0 Shape ID Type="Group" -18 0 0 -end - -start 72 -10 0 Shape ID Type="Shape" -26 53 LineStyle -26 61 FillStyle -26 69 TextStyle -18 0 0 -end - -start 74 -10 0 StyleSheet -26 53 LineStyle -26 61 FillStyle -26 69 TextStyle -18 0 0 -end - -start 77 -10 0 Shape ID Type="Guide" -18 0 0 -end - - -start 78 -10 0 Shape ID Type="Foreign" -18 0 0 -end - -start 79 -10 0 DocumentSheet -26 53 LineStyle -26 61 FillStyle -26 69 TextStyle -18 0 0 -end - -start 100 -10 0 Unknown 0x64 -18 0 0 -end - -start 101 -10 0 ShapeList -18 0 0 -end - -start 102 -10 0 Unknown 0x66 -18 0 0 -end - -start 103 -10 0 Unknown 0x67 -18 0 0 -end - -start 104 -10 0 PropList -18 0 0 -end - -start 105 -10 0 CharList -18 0 0 -end - -start 106 -10 0 ParaList -18 0 0 -end - -start 107 -10 0 Unknown 0x6b -18 0 0 -end - -start 108 -10 0 GeomList -18 0 0 -end - -start 109 -10 0 Unknown 0x6d -18 0 0 -end - -start 110 -10 0 Unknown 0x6e -18 0 0 -end - -start 111 -10 0 Unknown 0x6f -18 0 0 -end - -start 112 -10 0 Unknown 0x70 -18 0 0 -end - -start 113 -10 0 ConnectionList -18 0 0 -end - -start 114 -10 0 Unknown 0x72 -18 0 0 -end - -start 115 -10 0 Unknown 0x73 -18 0 0 -end - -start 116 -10 0 Unknown 0x74 -18 0 0 -end - -start 117 -10 0 Unknown 0x75 -18 0 0 -end - -start 118 -10 0 Unknown 0x76 -18 0 0 -end - -start 130 -10 0 Unknown 0x82 -18 0 0 -end - -start 131 -10 0 ShapeID -18 0 0 -end - -start 132 -10 0 Event -8 20 TheText -11 36 BlockStarts -21 36 BlockStarts -18 0 0 -end - -start 133 -10 0 Line -31 19 LineWeight -8 28 LineColor -8 33 LinePattern -9 35 Rounding -8 43 EndArrowSize -8 44 BeginArrow -8 45 EndArrow -8 47 BeginArrowSize -1 50 Color -2 50 Pattern -3 50 RoundingCap -4 50 LineEndEnd -5 50 LineEndBegin -6 50 EndSize -7 50 SqueareCap -0 51 BeginSize -11 54 BlockStarts -21 54 BlockStarts -18 0 0 -end - -start 134 -10 0 Fill -8 19 FillForegnd -30 25 FillBkgnd -8 29 FillPattern -30 31 ShdwForegnd -8 35 ShdwBkgnd -8 40 ShdwPattern -31 42 ShapeShdwOffsetX -31 51 ShapeShdwOffsetY -9 69 ShapeShdwScaleFactor -11 44 BlockStarts -21 80 BlockStarts -18 0 0 -end - -start 135 -10 0 TextBlock -31 19 LeftMargin -31 28 RightMargin -31 37 TopMargin -31 46 BottomMargin -8 55 VerticalAlign -30 56 TextBkgnd -9 62 DefaultTabStop -8 82 TextDirection -11 90 BlockStarts -21 111 BlockStarts -18 0 0 -end - -start 136 -10 0 Tabs -11 26 BlocksStart -21 26 BlocksStart -18 0 0 -end - -start 137 -10 0 Geometry -0 19 NoFill -1 19 NoLine -2 19 NoShow -3 19 NoSnap -21 22 BlocksStart -18 0 0 -end - -start 138 -10 0 MoveTo -9 20 X -9 29 Y -11 39 BlocksStart -21 39 BlocksStart -end - -start 139 -10 0 LineTo -9 20 X -9 29 Y -11 39 BlocksStart -21 39 BlocksStart -end - -start 140 -10 0 ArcTo -9 20 X -9 29 Y -9 38 A -11 48 BlocksStart -18 0 0 -end - -start 141 -10 0 InfiniteLine -9 20 X -9 29 Y -9 37 A -9 45 B -11 57 BlocksStart -18 0 0 -end - -start 143 -10 0 Ellipse -9 20 X -9 29 Y -9 38 A -9 47 B -9 56 C -9 65 D -11 75 BlocksStart -18 0 0 -end - -start 144 -10 0 EllipticalArcTo -31 19 X -31 28 Y -31 37 A -31 46 B -31 55 C -31 64 D -11 75 BlocksStart -18 0 0 -end - -start 146 -10 0 PageProps -9 20 PageWidth -9 29 PageHeight -9 38 ShdwOffsetX -9 47 ShdwOffsetY -9 56 PageScale -9 65 DrawingScale -8 73 DrawingSizeType -8 74 DrawingScaleType -0 93 InhibitSnap -11 150 BlockStarts -18 0 0 -end - -start 147 -10 0 StyleProp -8 19 EnableLineProps -8 20 EnableFillProps -8 21 EnableTextProps -8 22 HideForApply -11 26 BlocksStart -21 26 BlocksStart -18 0 0 -end - -start 148 -10 0 Char -25 23 FontNum -30 26 Color -8 29 Transparency*255/100% -0 30 Bold -1 30 Italic -2 30 Underline -3 30 Smallcaps -0 31 AllCaps -1 31 InitCaps -0 32 Subscript -1 32 Superscipt -25 33 Scale*100 % -8 35 LangCode -31 36 Size -25 46 Spacing pt*200 -25 56 AsianFont -25 58 ComplexScriptFont -8 60 LocalizeFont -25 88 LangID -11 54 BlocksStart -21 107 BlocksStart -18 0 0 -end - -start 149 -10 0 Para -31 23 IndFirst -31 32 IndLeft -31 41 IndRight -31 50 SpLine -31 59 SpBefore -31 68 SpAfter -8 77 HorizAlign -8 78 Bullet -11 92 BlockStarts -21 142 BlockStarts -18 0 0 -end - -start 150 -10 0 Tabs -27 0 TabsID -11 48 BlockStarts -18 0 0 -end - -start 151 -10 0 Tabs -27 0 TabsID -11 139 BlockStarts -18 0 0 -end - -start 181 -10 0 Tabs -27 0 TabsID -11 708 BlockStarts -18 0 0 -end - -start 152 -10 0 Foreign -9 20 IndFirst -9 29 IndLeft -9 38 IndRight -9 47 SpLine -28 68 Ext -18 0 0 -end - -start 153 -10 0 Connection -31 19 Width -31 28 Height -31 37 DirX/A -31 46 DirY/B -8 55 Type/C -11 67 BlockStarts -21 67 BlockStarts -18 0 0 -end - -start 155 -10 0 XForm -9 20 PinX -9 29 PinY -9 38 Width -9 47 Height -9 56 LocPinX -9 65 LocPinY -9 74 Angle -8 82 FlipX -8 83 FlipY -8 84 ResizeMode -11 88 BlockStarts -21 88 BlockStarts -18 0 0 -end - -start 156 -10 0 TextXForm -9 20 TxtPinX -9 29 TxtPinY -31 37 TxtWidth -9 47 TxtHeight -9 56 TxtLocPinX -9 65 TxtLocPinY -9 74 TxtAngle -11 88 BlockStarts -21 88 BlockStarts -18 0 0 -end - -start 157 -10 0 XForm1D -9 20 BeginX -9 29 BeginY -9 38 EndX -9 47 EndY -11 57 BlockStarts -21 57 BlockStarts -end - -start 158 -10 0 Scratch -9 20 X -9 29 Y -9 38 A -9 47 B -9 56 C -9 65 D -11 75 BlockStarts -18 0 0 -end - -start 159 -10 0 Alignment -9 20 AlignLeft -9 29 AlignCenter -9 38 AlignRight -9 47 AlignTop -9 56 AlignMiddle -9 65 AlignBottom -11 75 BlockStarts -21 79 BlockStarts -18 0 0 -end - -start 160 -10 0 Protection -8 19 LockWidth -8 20 LockHeight -8 21 LockMoveX -8 22 LockMoveY -8 23 LockAspect -8 24 LockDelete -8 25 LockBegin -8 26 LockEnd -8 27 LockRotate -8 28 LockCrop -8 29 LockVtxEdit -8 30 LockTextEdit -8 31 LockFormat -8 32 LockGroup -8 33 LockCalcWH -8 34 LockSelect -8 35 LockCustProp -11 43 BlockStarts -21 43 BlockStarts -18 0 0 -end - -start 161 -10 0 TextFields -18 0 0 -end - -start 162 -10 0 Control -9 20 X -9 29 Y -9 38 XDyn -9 47 YDyn -8 55 XCon -8 56 YCon -0 57 CanGlue -11 60 BlockStarts -21 60 BlockStarts -18 0 0 -end - -start 163 -10 0 Help -11 49 BlockStarts -21 49 BlockStarts -18 0 0 -end - -start 164 -10 0 Misc -0 19 NoObjHandles -1 19 NonPrinting -2 19 NoCtlHandles -3 19 NoAlignBox -4 19 UpdateAlignBox -5 19 HideText -8 20 DynFeedback -8 21 GlueType -8 22 WalkPreference -25 25 ObjType -0 35 IsDropSource -1 35 NoLiveDynamics -25 37 LangID -11 42 BlockStarts -21 64 BlockStarts -18 0 0 -end - -start 165 -10 0 SplineStart -9 20 X -9 29 Y -9 37 A -9 45 B -9 53 C -8 61 D -11 65 BlockStarts -18 0 0 -end - -start 166 -10 0 SplineKnot -9 20 X -9 29 Y -9 37 A -11 47 BlockStarts -18 0 0 -end - -start 167 -10 0 LayerMem -11 25 BlockStarts -21 25 BlockStarts -18 0 0 -end - -# Transparency 255 - 100% -start 168 -10 0 Layer -30 27 Color -8 31 Transparency -8 33 Visible -8 34 Print -8 35 Active -8 36 Lock -8 37 Snap -8 38 Glue -11 52 BlockStarts -21 52 BlockStarts -18 0 0 -end - -start 169 -10 0 Act -8 40 Checked -8 41 Disabled -0 42 ReadOnly -1 42 Invisible -2 42 BeginGroup -11 47 BlockStarts -21 76 BlockStarts -18 0 0 -end - -start 170 -10 0 Control -9 20 X -9 29 Y -9 38 XDyn -9 47 YDyn -8 55 XBehavior -8 56 YBehavior -0 57 CanGlue -11 66 BlockStarts -21 66 BlockStarts -18 0 0 -end - -start 180 -10 0 User-defined Cells -9 20 Value -11 34 BlockStarts -21 34 BlockStarts -18 0 0 -end - -start 182 -10 0 CustomProps -9 20 Value -8 44 Type -0 46 Invisible -1 46 Ask -11 55 BlockStarts -18 0 0 -end - -start 183 -10 0 RulerGrid -8 19 XRulerDensity -8 20 XRulerDensity -31 21 Unknown1 -31 30 Unknown2 -31 39 XRulerOrigin -31 48 YRulerOrigin -8 57 XGridDensity -8 58 YGridDensity -31 59 XGridSpacing -31 68 YGridSpacing -31 77 XGridOrigin -31 86 YGridOrigin -11 98 BlockStarts -21 98 BlockStarts -18 0 0 -end - -start 185 -10 0 Connection -31 19 Width -31 28 Height -31 37 DirX/A -31 46 DirY/B -8 55 Type/C -11 67 BlockStarts -21 67 BlockStarts -18 0 0 -end - -start 186 -10 0 ConnectionPoints -9 20 Width -9 29 Height -11 79 BlockStarts -18 0 0 -end - -start 188 -10 0 DocProps -25 24 DocLangID -18 0 0 -end - -start 189 -10 0 Image -9 19 Gamma -25 27 Contrast*100 (%) -25 29 Brightness*100 (%) -25 31 Sharpen*100 (%) -25 33 Blur*100 (%) -25 35 Denoise*100 (%) -25 37 Transparency*100 (%) -11 64 BlockStarts -21 64 BlockStarts -18 0 0 -end - -start 190 -10 0 Group -8 19 SelectMode -8 20 DisplayMode -0 21 IsDropTarget -1 21 IsSnapTarget -2 21 IsTextEditTarget -3 21 DontMoveChildren -11 44 BlocksStart -21 44 BlocksStart -end - -start 191 -10 0 Layout -0 19 ShapePermeableX -1 19 ShapePermeableY -2 19 ShapePermeablePlace -8 20 ShapeFixedCode -8 21 ShapePlowCode -8 22 ShapeRouteStyle -8 24 ConFixedCode -8 25 ConLineJumpCode -8 26 ConLineJumpStyle -8 28 ConLineJumpDirX -8 29 ConLineJumpDirY -11 57 BlockStarts -21 57 BlockStarts -18 0 0 -end - -start 192 -10 0 PageLayout -0 19 ResizePage -1 19 EnableGrid -2 19 DynamicOff -3 19 CtrlAsInput -8 20 PlaceStyle -8 21 RouteStyle -8 22 PlaceDepth -8 23 PlowCode -8 24 LineJumpCode -8 25 LineJumpStyle -8 26 PageLineJumpDirX -8 27 PageLineJumpDirY -9 29 LineToNodeX -9 38 LineToNodeY -9 47 BlockSizeX -9 56 BlockSizeY -9 65 AvenueSizeX -9 74 AvenueSizeY -9 83 LineToLineX -9 92 LineToLineY -9 100 LineJumpFactorX -9 108 LineJumpFactorY -8 116 LineAdjustFrom -8 117 LineAdjustTo -11 163 Blocks start -21 163 Blocks start -end - -start 193 -10 0 PolylineTo -9 20 X -9 29 Y -18 0 0 -end - - -start 195 -10 0 NURBSTo -9 20 X -9 29 Y -9 37 A -9 45 B -9 53 C -9 61 D -11 80 BlocksStart -21 80 BlocksStart -18 0 0 -end - -start 196 -10 0 Hyperlink -0 39 NewWindow -2 39 Default -11 65 BlocksStart -18 0 0 -end - -start 197 -10 0 Reviewer -8 28 ColorRed -8 29 ColorGreen -8 30 ColorBlue -26 31 ReviewerID -26 35 CurrentIndex -11 57 BlocksStart -21 57 BlocksStart -18 0 0 -end - -start 198 -10 0 Annotation -18 0 0 -end - -start 199 -10 0 SmartTagDef -18 0 0 -end - -start 200 -10 0 PrintProps -31 19 PageLeftMargin -31 28 PageRightMargin -31 37 PageTopMargin -31 46 PageBottomMargin -9 55 ScaleX -9 63 ScaleY -25 71 PagesX -25 73 PagesY -8 76 PrintPageOrientation -25 77 PaperKind -25 79 PaperSource -11 91 BlocksStart -21 91 BlocksStart -18 0 0 -end - -start 201 -10 0 Unknown 0xc9 -18 0 0 -end - -start 209 -10 0 NURBSTo E-cell -9 35 1st fr of NURBSTo -9 43 3 bytes are here, need to map -9 51 2nd fr -9 59 3rd fr -9 67 4th byte -9 75 5th byte -9 83 4th fr -9 91 5th fr -9 99 6th byte -9 107 7th byte -9 115 6th fr -9 123 7th fr -9 131 8th byte -9 139 9th byte -18 0 0 -end diff --git a/src/resources/scratchpad/org/apache/poi/hslf/data/empty.ppt b/src/resources/scratchpad/org/apache/poi/hslf/data/empty.ppt deleted file mode 100644 index 20d2398e3..000000000 Binary files a/src/resources/scratchpad/org/apache/poi/hslf/data/empty.ppt and /dev/null differ diff --git a/src/resources/version/Version.java.template b/src/resources/version/Version.java.template deleted file mode 100644 index 716ec916b..000000000 --- a/src/resources/version/Version.java.template +++ /dev/null @@ -1,69 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi; - -/** - * Administrative class to keep track of the version number of the - * POI release. - * - * This class implements the upcoming standard of having - * org.apache.project-name.Version.getVersion() be a standard - * way to get version information. - */ -public class Version { - private static final String VERSION_STRING = "@VERSION@"; - private static final String RELEASE_DATE = "@DSTAMP@"; - - /** - * Return the basic version string, of the form - * nn.nn(.nn) - */ - public static String getVersion() { - return VERSION_STRING; - } - - /** - * Return the date of the release / build - */ - public static String getReleaseDate() { - return RELEASE_DATE; - } - - /** - * Name of product: POI - */ - public static String getProduct() { - return "POI"; - } - /** - * Implementation Language: Java - */ - public static String getImplementationLanguage() { - return "Java"; - } - - /** - * Prints the version to the command line - */ - public static void main(String[] args) { - System.out.println( - "Apache " + getProduct() + " " + - getVersion() + " (" + getReleaseDate() + ")" - ); - } -} diff --git a/src/scratchpad/models/poi-hdf.zargo b/src/scratchpad/models/poi-hdf.zargo deleted file mode 100644 index dde113285..000000000 Binary files a/src/scratchpad/models/poi-hdf.zargo and /dev/null differ diff --git a/src/scratchpad/src/org/apache/poi/POIReadOnlyDocument.java b/src/scratchpad/src/org/apache/poi/POIReadOnlyDocument.java deleted file mode 100644 index 3b3eca588..000000000 --- a/src/scratchpad/src/org/apache/poi/POIReadOnlyDocument.java +++ /dev/null @@ -1,75 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi; - -import java.io.File; -import java.io.OutputStream; - -import org.apache.poi.poifs.filesystem.DirectoryNode; -import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; -import org.apache.poi.poifs.filesystem.OPOIFSFileSystem; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; - - -/** - * This holds the common functionality for all read-only - * POI Document classes, i.e. ones which don't support writing. - * - * @since POI 3.15 beta 3 - */ -public abstract class POIReadOnlyDocument extends POIDocument { - public POIReadOnlyDocument(DirectoryNode dir) { - super(dir); - } - public POIReadOnlyDocument(NPOIFSFileSystem fs) { - super(fs); - } - public POIReadOnlyDocument(OPOIFSFileSystem fs) { - super(fs); - } - public POIReadOnlyDocument(POIFSFileSystem fs) { - super(fs); - } - - /** - * Note - writing is not yet supported for this file format, sorry. - * - * @throws IllegalStateException If you call the method, as writing is not supported - */ - @Override - public void write() { - throw new IllegalStateException("Writing is not yet implemented for this Document Format"); - } - /** - * Note - writing is not yet supported for this file format, sorry. - * - * @throws IllegalStateException If you call the method, as writing is not supported - */ - @Override - public void write(File file) { - throw new IllegalStateException("Writing is not yet implemented for this Document Format"); - } - /** - * Note - writing is not yet supported for this file format, sorry. - * - * @throws IllegalStateException If you call the method, as writing is not supported - */ - @Override - public void write(OutputStream out) { - throw new IllegalStateException("Writing is not yet implemented for this Document Format"); - } -} diff --git a/src/scratchpad/src/org/apache/poi/extractor/OLE2ScratchpadExtractorFactory.java b/src/scratchpad/src/org/apache/poi/extractor/OLE2ScratchpadExtractorFactory.java deleted file mode 100644 index 429e257ab..000000000 --- a/src/scratchpad/src/org/apache/poi/extractor/OLE2ScratchpadExtractorFactory.java +++ /dev/null @@ -1,145 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.extractor; - -import java.io.ByteArrayInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.util.Iterator; -import java.util.List; - -import org.apache.poi.POIOLE2TextExtractor; -import org.apache.poi.POITextExtractor; -import org.apache.poi.hdgf.extractor.VisioTextExtractor; -import org.apache.poi.hpbf.extractor.PublisherTextExtractor; -import org.apache.poi.hslf.extractor.PowerPointExtractor; -import org.apache.poi.hsmf.MAPIMessage; -import org.apache.poi.hsmf.datatypes.AttachmentChunks; -import org.apache.poi.hsmf.extractor.OutlookTextExtactor; -import org.apache.poi.hwpf.OldWordFileFormatException; -import org.apache.poi.hwpf.extractor.Word6Extractor; -import org.apache.poi.hwpf.extractor.WordExtractor; -import org.apache.poi.poifs.filesystem.DirectoryEntry; -import org.apache.poi.poifs.filesystem.DirectoryNode; -import org.apache.poi.poifs.filesystem.Entry; - -/** - * Scratchpad-specific logic for {@link OLE2ExtractorFactory} and - * {@link org.apache.poi.extractor.ExtractorFactory}, which permit the other two to run with - * no Scratchpad jar (though without functionality!) - *

    Note - should not be used standalone, always use via the other - * two classes

    - */ -@SuppressWarnings("WeakerAccess") -public class OLE2ScratchpadExtractorFactory { - /** - * Look for certain entries in the stream, to figure it - * out what format is desired - * Note - doesn't check for core-supported formats! - * Note - doesn't check for OOXML-supported formats - */ - public static POITextExtractor createExtractor(DirectoryNode poifsDir) throws IOException { - if (poifsDir.hasEntry("WordDocument")) { - // Old or new style word document? - try { - return new WordExtractor(poifsDir); - } catch (OldWordFileFormatException e) { - return new Word6Extractor(poifsDir); - } - } - - if (poifsDir.hasEntry("PowerPoint Document")) { - return new PowerPointExtractor(poifsDir); - } - - if (poifsDir.hasEntry("VisioDocument")) { - return new VisioTextExtractor(poifsDir); - } - - if (poifsDir.hasEntry("Quill")) { - return new PublisherTextExtractor(poifsDir); - } - - final String[] outlookEntryNames = new String[] { - // message bodies, saved as plain text (PtypString) - // The first short (0x1000, 0x0047, 0x0037) refer to the Property ID (see [MS-OXPROPS].pdf) - // the second short (0x001e, 0x001f, 0x0102) refer to the type of data stored in this entry - // https://msdn.microsoft.com/endatatypes.Ex-us/library/cc433490(v=exchg.80).aspx - // @see org.apache.poi.hsmf.Types.MAPIType - "__substg1.0_1000001E", //PidTagBody ASCII - "__substg1.0_1000001F", //PidTagBody Unicode - "__substg1.0_0047001E", //PidTagMessageSubmissionId ASCII - "__substg1.0_0047001F", //PidTagMessageSubmissionId Unicode - "__substg1.0_0037001E", //PidTagSubject ASCII - "__substg1.0_0037001F", //PidTagSubject Unicode - }; - for (String entryName : outlookEntryNames) { - if (poifsDir.hasEntry(entryName)) { - return new OutlookTextExtactor(poifsDir); - } - } - - throw new IllegalArgumentException("No supported documents found in the OLE2 stream"); - } - - /** - * Returns an array of text extractors, one for each of - * the embedded documents in the file (if there are any). - * If there are no embedded documents, you'll get back an - * empty array. Otherwise, you'll get one open - * {@link POITextExtractor} for each embedded file. - */ - public static void identifyEmbeddedResources(POIOLE2TextExtractor ext, List dirs, List nonPOIFS) throws IOException { - // Find all the embedded directories - DirectoryEntry root = ext.getRoot(); - if (root == null) { - throw new IllegalStateException("The extractor didn't know which POIFS it came from!"); - } - - if (ext instanceof WordExtractor) { - // These are in ObjectPool -> _... under the root - try { - DirectoryEntry op = (DirectoryEntry) - root.getEntry("ObjectPool"); - Iterator it = op.getEntries(); - while(it.hasNext()) { - Entry entry = it.next(); - if(entry.getName().startsWith("_")) { - dirs.add(entry); - } - } - } catch(FileNotFoundException e) { - // ignored here - } - //} else if(ext instanceof PowerPointExtractor) { - // Tricky, not stored directly in poifs - // TODO - } else if (ext instanceof OutlookTextExtactor) { - // Stored in the Attachment blocks - MAPIMessage msg = ((OutlookTextExtactor)ext).getMAPIMessage(); - for (AttachmentChunks attachment : msg.getAttachmentFiles()) { - if (attachment.getAttachData() != null) { - byte[] data = attachment.getAttachData().getValue(); - nonPOIFS.add( new ByteArrayInputStream(data) ); - } else if (attachment.getAttachmentDirectory() != null) { - dirs.add(attachment.getAttachmentDirectory().getDirectory()); - } - } - } - } -} diff --git a/src/scratchpad/src/org/apache/poi/hdgf/HDGFDiagram.java b/src/scratchpad/src/org/apache/poi/hdgf/HDGFDiagram.java deleted file mode 100644 index c85278882..000000000 --- a/src/scratchpad/src/org/apache/poi/hdgf/HDGFDiagram.java +++ /dev/null @@ -1,168 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hdgf; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.POIReadOnlyDocument; -import org.apache.poi.hdgf.chunks.ChunkFactory; -import org.apache.poi.hdgf.pointers.Pointer; -import org.apache.poi.hdgf.pointers.PointerFactory; -import org.apache.poi.hdgf.streams.PointerContainingStream; -import org.apache.poi.hdgf.streams.Stream; -import org.apache.poi.hdgf.streams.StringsStream; -import org.apache.poi.hdgf.streams.TrailerStream; -import org.apache.poi.poifs.filesystem.DirectoryNode; -import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.LocaleUtil; - -/** - * See - * http://www.redferni.uklinux.net/visio/ - * http://www.gnome.ru/projects/docs/vsdocs.html - * http://www.gnome.ru/projects/docs/slide1.png - * http://www.gnome.ru/projects/docs/slide2.png - */ -public final class HDGFDiagram extends POIReadOnlyDocument { - private static final String VISIO_HEADER = "Visio (TM) Drawing\r\n"; - - private byte[] _docstream; - - private short version; - private long docSize; - - private Pointer trailerPointer; - private TrailerStream trailer; - - private ChunkFactory chunkFactory; - private PointerFactory ptrFactory; - - public HDGFDiagram(POIFSFileSystem fs) throws IOException { - this(fs.getRoot()); - } - public HDGFDiagram(NPOIFSFileSystem fs) throws IOException { - this(fs.getRoot()); - } - public HDGFDiagram(DirectoryNode dir) throws IOException { - super(dir); - - // Grab the document stream - InputStream is = dir.createDocumentInputStream("VisioDocument"); - _docstream = IOUtils.toByteArray(is); - is.close(); - - // Check it's really visio - String typeString = new String(_docstream, 0, 20, LocaleUtil.CHARSET_1252 ); - if(! typeString.equals(VISIO_HEADER)) { - throw new IllegalArgumentException("Wasn't a valid visio document, started with " + typeString); - } - - // Grab the version number, 0x1a -> 0x1b - version = LittleEndian.getShort(_docstream, 0x1a); - // Grab the document size, 0x1c -> 0x1f - docSize = LittleEndian.getUInt(_docstream, 0x1c); - // ??? 0x20 -> 0x23 - - // Create the Chunk+Pointer Factories for the document version - ptrFactory = new PointerFactory(version); - chunkFactory = new ChunkFactory(version); - - // Grab the pointer to the trailer - trailerPointer = ptrFactory.createPointer(_docstream, 0x24); - - // Now grab the trailer - trailer = (TrailerStream) - Stream.createStream(trailerPointer, _docstream, chunkFactory, ptrFactory); - - // Finally, find all our streams - trailer.findChildren(_docstream); - } - - /** - * Returns the TrailerStream, which is at the root of the - * tree of Streams. - */ - public TrailerStream getTrailerStream() { return trailer; } - /** - * Returns all the top level streams, which are the streams - * pointed to by the TrailerStream. - */ - public Stream[] getTopLevelStreams() { return trailer.getPointedToStreams(); } - public long getDocumentSize() { return docSize; } - - /** - * Prints out some simple debug on the base contents of the file. - * @see org.apache.poi.hdgf.dev.VSDDumper - */ - public void debug() { - System.err.println("Trailer is at " + trailerPointer.getOffset()); - System.err.println("Trailer has type " + trailerPointer.getType()); - System.err.println("Trailer has length " + trailerPointer.getLength()); - System.err.println("Trailer has format " + trailerPointer.getFormat()); - - for(int i=0; i 0) { - System.err.println("\tContains " + pcs.getPointedToStreams().length + " other pointers/streams"); - for(int j=0; j 4078) { - pntr = pntr - 4078; - } else { - pntr = pntr + 18; - } - return pntr; - } - - /** - * We want an empty dictionary, so do nothing - */ - @Override - protected int populateDictionary(byte[] dict) { - return 0; - } - - /** - * Performs the Visio compatible streaming LZW compression. - */ - public void compress(InputStream src, OutputStream res) throws IOException { - HDGFLZWCompressor c = new HDGFLZWCompressor(); - c.compress(src, res); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hdgf/HDGFLZWCompressor.java b/src/scratchpad/src/org/apache/poi/hdgf/HDGFLZWCompressor.java deleted file mode 100644 index d79c43c87..000000000 --- a/src/scratchpad/src/org/apache/poi/hdgf/HDGFLZWCompressor.java +++ /dev/null @@ -1,258 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hdgf; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -/** - * Helper class to handle the Visio compatible - * streaming LZW compression. - * Need our own class to handle keeping track of the - * code buffer, pending bytes to write out etc. - * - * TODO Fix this, as it starts to go wrong on - * large streams - */ -/* package */ final class HDGFLZWCompressor { - // We use 12 bit codes: - // * 0-255 are real bytes - // * 256-4095 are the substring codes - // Java handily initialises our buffer / dictionary - // to all zeros - private byte[] dict = new byte[4096]; - - // The next block of data to be written out, minus - // its mask byte - private byte[] buffer = new byte[16]; - // And how long it is - // (Un-compressed codes are 1 byte each, compressed codes - // are two) - private int bufferLen = 0; - - // The raw length of a code is limited to 4 bits + 2 - private byte[] rawCode = new byte[18]; - // And how much we're using - private int rawCodeLen = 0; - - // How far through the input and output streams we are - private int posInp = 0; - private int posOut = 0; - - // What the next mask byte to output will be - private int nextMask = 0; - // And how many bits we've already set - private int maskBitsSet = 0; - - public HDGFLZWCompressor() {} - -/** - * Returns the last place that the bytes from rawCode are found - * at in the buffer, or -1 if they can't be found - */ -private int findRawCodeInBuffer() { - // Work our way through all the codes until we - // find the right one. Visio starts from the end - for(int i=4096-rawCodeLen; i>0; i--) { - boolean matches = true; - for(int j=0; matches && j> 4); - buffer[bufferLen] = HDGFLZW.fromInt(bp1); - bufferLen++; - buffer[bufferLen] = HDGFLZW.fromInt(bp2); - bufferLen++; - - // Copy the data to the dictionary in the new place - for(int i=0; i 0) { - outputCompressed(res); - if(maskBitsSet > 0) { - output8Codes(res); - } - } - break; - } - - // Try adding this new byte onto rawCode, and - // see if all of that is still found in the - // buffer dictionary or not - rawCode[rawCodeLen] = dataB; - rawCodeLen++; - int rawAt = findRawCodeInBuffer(); - - // If we found it and are now at 18 bytes, - // we need to output our pending code block - if(rawCodeLen == 18 && rawAt > -1) { - outputCompressed(res); - rawCodeLen = 0; - continue; - } - - // If we did find all of rawCode with our new - // byte added on, we can wait to see what happens - // with the next byte - if(rawAt > -1) { - continue; - } - - // If we get here, then the rawCode + this byte weren't - // found in the dictionary - - // If there was something in rawCode before, then that was - // found in the dictionary, so output that compressed - rawCodeLen--; - if(rawCodeLen > 0) { - // Output the old rawCode - outputCompressed(res); - - // Can this byte start a new rawCode, or does - // it need outputting itself? - rawCode[0] = dataB; - rawCodeLen = 1; - if(findRawCodeInBuffer() > -1) { - // Fits in, wait for next byte - continue; - } - // Doesn't fit, output - outputUncompressed(dataB,res); - rawCodeLen = 0; - } else { - // Nothing in rawCode before, so this byte - // isn't in the buffer dictionary - // Output it un-compressed - outputUncompressed(dataB,res); - } - } -} -} diff --git a/src/scratchpad/src/org/apache/poi/hdgf/chunks/Chunk.java b/src/scratchpad/src/org/apache/poi/hdgf/chunks/Chunk.java deleted file mode 100644 index ce92ac8dc..000000000 --- a/src/scratchpad/src/org/apache/poi/hdgf/chunks/Chunk.java +++ /dev/null @@ -1,290 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hdgf.chunks; - -import java.util.ArrayList; - -import org.apache.poi.hdgf.chunks.ChunkFactory.CommandDefinition; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; - -/** - * Base of all chunks, which hold data, flags etc - */ -public final class Chunk { - /** - * The contents of the chunk, excluding the header, - * trailer and separator - */ - private byte[] contents; - private ChunkHeader header; - /** May be null */ - private ChunkTrailer trailer; - /** May be null */ - private ChunkSeparator separator; - /** The possible different commands we can hold */ - protected CommandDefinition[] commandDefinitions; - /** The command+value pairs we hold */ - private Command[] commands; - /** The blocks (if any) we hold */ - //private Block[] blocks - /** The name of the chunk, as found from the commandDefinitions */ - private String name; - - /** For logging warnings about the structure of the file */ - private POILogger logger = POILogFactory.getLogger(Chunk.class); - - public Chunk(ChunkHeader header, ChunkTrailer trailer, ChunkSeparator separator, byte[] contents) { - this.header = header; - this.trailer = trailer; - this.separator = separator; - this.contents = contents.clone(); - } - - public byte[] _getContents() { - return contents; - } - public ChunkHeader getHeader() { - return header; - } - /** Gets the separator between this chunk and the next, if it exists */ - public ChunkSeparator getSeparator() { - return separator; - } - /** Gets the trailer for this chunk, if it exists */ - public ChunkTrailer getTrailer() { - return trailer; - } - /** - * Gets the command definitions, which define and describe much - * of the data held by the chunk. - */ - public CommandDefinition[] getCommandDefinitions() { - return commandDefinitions; - } - public Command[] getCommands() { - return commands; - } - /** - * Get the name of the chunk, as found from the CommandDefinitions - */ - public String getName() { - return name; - } - - /** - * Returns the size of the chunk, including any - * headers, trailers and separators. - */ - public int getOnDiskSize() { - int size = header.getSizeInBytes() + contents.length; - if(trailer != null) { - size += trailer.getTrailerData().length; - } - if(separator != null) { - size += separator.separatorData.length; - } - return size; - } - - /** - * Uses our CommandDefinitions to process the commands - * our chunk type has, and figure out the - * values for them. - */ - protected void processCommands() { - if(commandDefinitions == null) { - throw new IllegalStateException("You must supply the command definitions before calling processCommands!"); - } - - // Loop over the definitions, building the commands - // and getting their values - ArrayList commandList = new ArrayList(); - for(CommandDefinition cdef : commandDefinitions) { - int type = cdef.getType(); - int offset = cdef.getOffset(); - - // Handle virtual commands - if(type == 10) { - name = cdef.getName(); - continue; - } else if(type == 18) { - continue; - } - - - // Build the appropriate command for the type - Command command; - if(type == 11 || type == 21) { - command = new BlockOffsetCommand(cdef); - } else { - command = new Command(cdef); - } - - // Bizarely, many of the offsets are from the start of the - // header, not from the start of the chunk body - switch(type) { - case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: - case 11: case 21: - case 12: case 16: case 17: case 18: case 28: case 29: - // Offset is from start of chunk - break; - default: - // Offset is from start of header! - if(offset >= 19) { - offset -= 19; - } - } - - // Check we seem to have enough data - if(offset >= contents.length) { - logger.log(POILogger.WARN, - "Command offset " + offset + " past end of data at " + contents.length - ); - continue; - } - - try { - // Process - switch(type) { - // Types 0->7 = a flat at bit 0->7 - case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: - int val = contents[offset] & (1< 0); - break; - case 8: - command.value = Byte.valueOf(contents[offset]); - break; - case 9: - command.value = new Double( - LittleEndian.getDouble(contents, offset) - ); - break; - case 12: - // A Little Endian String - // Starts 8 bytes into the data segment - // Ends at end of data, or 00 00 - - // Ensure we have enough data - if(contents.length < 8) { - command.value = ""; - break; - } - - // Find the end point - int startsAt = 8; - int endsAt = startsAt; - for(int j=startsAt; j chunkCommandDefinitions = - new HashMap(); - /** - * What the name is of the chunk table definitions file? - * This file comes from the scratchpad resources directory. - */ - private static final String chunkTableName = - "/org/apache/poi/hdgf/chunks_parse_cmds.tbl"; - - /** For logging problems we spot with the file */ - private static final POILogger logger = POILogFactory.getLogger(ChunkFactory.class); - - public ChunkFactory(int version) throws IOException { - this.version = version; - - processChunkParseCommands(); - } - - /** - * Open chunks_parse_cmds.tbl and process it, to get the definitions - * of all the different possible chunk commands. - */ - private void processChunkParseCommands() throws IOException { - String line; - InputStream cpd = null; - BufferedReader inp = null; - try { - cpd = ChunkFactory.class.getResourceAsStream(chunkTableName); - if(cpd == null) { - throw new IllegalStateException("Unable to find HDGF chunk definition on the classpath - " + chunkTableName); - } - - inp = new BufferedReader(new InputStreamReader(cpd, LocaleUtil.CHARSET_1252)); - - while( (line = inp.readLine()) != null ) { - if (line.isEmpty() || "# \t".contains(line.substring(0,1))) { - continue; - } - - // Start xxx - if(!line.matches("^start [0-9]+$")) { - throw new IllegalStateException("Expecting start xxx, found " + line); - } - int chunkType = Integer.parseInt(line.substring(6)); - ArrayList defsL = new ArrayList(); - - // Data entries - while( (line = inp.readLine()) != null ) { - if (line.startsWith("end")) { - break; - } - StringTokenizer st = new StringTokenizer(line, " "); - int defType = Integer.parseInt(st.nextToken()); - int offset = Integer.parseInt(st.nextToken()); - String name = st.nextToken("\uffff").substring(1); - - CommandDefinition def = new CommandDefinition(defType,offset,name); - defsL.add(def); - } - - CommandDefinition[] defs = defsL.toArray(new CommandDefinition[defsL.size()]); - - // Add to the map - chunkCommandDefinitions.put(Integer.valueOf(chunkType), defs); - } - } finally { - if (inp != null) { - inp.close(); - } - if (cpd != null) { - cpd.close(); - } - } - } - - public int getVersion() { return version; } - - /** - * Creates the appropriate chunk at the given location. - * @param data - * @param offset - */ - public Chunk createChunk(byte[] data, int offset) { - // Create the header - ChunkHeader header = - ChunkHeader.createChunkHeader(version, data, offset); - // Sanity check - if(header.getLength() < 0) { - throw new IllegalArgumentException("Found a chunk with a negative length, which isn't allowed"); - } - - // How far up to look - int endOfDataPos = offset + header.getLength() + header.getSizeInBytes(); - - // Check we have enough data, and tweak the header size - // as required - if(endOfDataPos > data.length) { - logger.log(POILogger.WARN, - "Header called for " + header.getLength() +" bytes, but that would take us past the end of the data!"); - - endOfDataPos = data.length; - header.setLength(data.length - offset - header.getSizeInBytes()); - - if(header.hasTrailer()) { - header.setLength(header.getLength() - 8); - endOfDataPos -= 8; - } - if(header.hasSeparator()) { - header.setLength(header.getLength() - 4); - endOfDataPos -= 4; - } - } - - - // Create the trailer and separator, if required - ChunkTrailer trailer = null; - ChunkSeparator separator = null; - if(header.hasTrailer()) { - if(endOfDataPos <= data.length-8) { - trailer = new ChunkTrailer( - data, endOfDataPos); - endOfDataPos += 8; - } else { - logger.log(POILogger.ERROR, "Header claims a length to " + endOfDataPos + " there's then no space for the trailer in the data (" + data.length + ")"); - } - } - if(header.hasSeparator()) { - if(endOfDataPos <= data.length-4) { - separator = new ChunkSeparator( - data, endOfDataPos); - } else { - logger.log(POILogger.ERROR, "Header claims a length to " + endOfDataPos + " there's then no space for the separator in the data (" + data.length + ")"); - } - } - - // Now, create the chunk - byte[] contents = new byte[header.getLength()]; - System.arraycopy(data, offset+header.getSizeInBytes(), contents, 0, contents.length); - Chunk chunk = new Chunk(header, trailer, separator, contents); - - // Feed in the stuff from chunks_parse_cmds.tbl - CommandDefinition[] defs = chunkCommandDefinitions.get(Integer.valueOf(header.getType())); - if (defs == null) { - defs = new CommandDefinition[0]; - } - chunk.commandDefinitions = defs; - - // Now get the chunk to process its commands - chunk.processCommands(); - - // All done - return chunk; - } - - /** - * The definition of a Command, which a chunk may hold. - * The Command holds the value, this describes it. - */ - public static class CommandDefinition { - private int type; - private int offset; - private String name; - public CommandDefinition(int type, int offset, String name) { - this.type = type; - this.offset = offset; - this.name = name; - } - - public String getName() { - return name; - } - public int getOffset() { - return offset; - } - public int getType() { - return type; - } - } -} diff --git a/src/scratchpad/src/org/apache/poi/hdgf/chunks/ChunkHeader.java b/src/scratchpad/src/org/apache/poi/hdgf/chunks/ChunkHeader.java deleted file mode 100644 index df7c9940b..000000000 --- a/src/scratchpad/src/org/apache/poi/hdgf/chunks/ChunkHeader.java +++ /dev/null @@ -1,129 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hdgf.chunks; - -import org.apache.poi.util.LittleEndian; - -import java.nio.charset.Charset; - -/** - * A chunk header - */ -public abstract class ChunkHeader { - private int type; - private int id; - private int length; - private int unknown1; - - /** - * Creates the appropriate ChunkHeader for the Chunk Header at - * the given location, for the given document version. - */ - public static ChunkHeader createChunkHeader(int documentVersion, byte[] data, int offset) { - if(documentVersion >= 6) { - ChunkHeaderV6 ch; - if(documentVersion > 6) { - ch = new ChunkHeaderV11(); - } else { - ch = new ChunkHeaderV6(); - } - ch.setType((int)LittleEndian.getUInt(data, offset + 0)); - ch.setId((int)LittleEndian.getUInt(data, offset + 4)); - ch.setUnknown1((int)LittleEndian.getUInt(data, offset + 8)); - ch.setLength((int)LittleEndian.getUInt(data, offset + 12)); - ch.setUnknown2(LittleEndian.getShort(data, offset + 16)); - ch.setUnknown3(LittleEndian.getUByte(data, offset + 18)); - - return ch; - } else if(documentVersion == 5 || documentVersion == 4) { - ChunkHeaderV4V5 ch = new ChunkHeaderV4V5(); - - ch.setType(LittleEndian.getShort(data, offset + 0)); - ch.setId(LittleEndian.getShort(data, offset + 2)); - ch.setUnknown2(LittleEndian.getUByte(data, offset + 4)); - ch.setUnknown3(LittleEndian.getUByte(data, offset + 5)); - ch.setUnknown1(LittleEndian.getShort(data, offset + 6)); - ch.setLength((int)LittleEndian.getUInt(data, offset + 8)); - - return ch; - } else { - throw new IllegalArgumentException("Visio files with versions below 4 are not supported, yours was " + documentVersion); - } - } - - /** - * Returns the size of a chunk header for the given document version. - */ - public static int getHeaderSize(int documentVersion) { - if(documentVersion > 6) { - return ChunkHeaderV11.getHeaderSize(); - } else if(documentVersion == 6) { - return ChunkHeaderV6.getHeaderSize(); - } else { - return ChunkHeaderV4V5.getHeaderSize(); - } - } - - public abstract int getSizeInBytes(); - public abstract boolean hasTrailer(); - public abstract boolean hasSeparator(); - public abstract Charset getChunkCharset(); - - /** - * Returns the ID/IX of the chunk - */ - public int getId() { - return id; - } - - /** - * Returns the length of the trunk, excluding the length - * of the header, trailer or separator. - */ - public int getLength() { - return length; - } - - /** - * Returns the type of the chunk, which affects the - * mandatory information - */ - public int getType() { - return type; - } - - public int getUnknown1() { - return unknown1; - } - - void setType(int type) { - this.type = type; - } - - void setId(int id) { - this.id = id; - } - - void setLength(int length) { - this.length = length; - } - - void setUnknown1(int unknown1) { - this.unknown1 = unknown1; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hdgf/chunks/ChunkHeaderV11.java b/src/scratchpad/src/org/apache/poi/hdgf/chunks/ChunkHeaderV11.java deleted file mode 100644 index ca243c996..000000000 --- a/src/scratchpad/src/org/apache/poi/hdgf/chunks/ChunkHeaderV11.java +++ /dev/null @@ -1,67 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hdgf.chunks; - -import java.nio.charset.Charset; - -/** - * A chunk header from v11+ - */ -public final class ChunkHeaderV11 extends ChunkHeaderV6 { - /** - * Does the chunk have a separator? - */ - public boolean hasSeparator() { - short unknown2 = getUnknown2(); - short unknown3 = getUnknown3(); - - switch (getType()) { - case 0x1f: case 0xc9: - // For some reason, there are two types that don't have a - // separator despite the flags that indicate they do - return false; - - case 0x69: - return true; - - case 0xa9: case 0xaa: case 0xb4: case 0xb6: - if (unknown2 == 2 && unknown3 == 0x54) { - return true; - } - break; - - default: - break; - } - - if ( - (unknown2 == 2 && unknown3 == 0x55) || - (unknown2 == 3 && unknown3 != 0x50) - ) { - return true; - } - - // If there's a trailer, there's a separator - return hasTrailer(); - } - - @Override - public Charset getChunkCharset() { - return Charset.forName("UTF-16LE"); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hdgf/chunks/ChunkHeaderV4V5.java b/src/scratchpad/src/org/apache/poi/hdgf/chunks/ChunkHeaderV4V5.java deleted file mode 100644 index b4eb9d83d..000000000 --- a/src/scratchpad/src/org/apache/poi/hdgf/chunks/ChunkHeaderV4V5.java +++ /dev/null @@ -1,72 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hdgf.chunks; - -import java.nio.charset.Charset; - -/** - * A chunk header from v4 or v5 - */ -public final class ChunkHeaderV4V5 extends ChunkHeader { - private short unknown2; - private short unknown3; - - public short getUnknown2() { - return unknown2; - } - public short getUnknown3() { - return unknown3; - } - - protected static int getHeaderSize() { - return 12; - } - - public int getSizeInBytes() { - return getHeaderSize(); - } - - /** - * Does the chunk have a trailer? - */ - public boolean hasTrailer() { - // V4 and V5 never has trailers - return false; - } - - /** - * Does the chunk have a separator? - */ - public boolean hasSeparator() { - // V4 and V5 never has separators - return false; - } - - @Override - public Charset getChunkCharset() { - return Charset.forName("ASCII"); - } - - void setUnknown2(short unknown2) { - this.unknown2 = unknown2; - } - - void setUnknown3(short unknown3) { - this.unknown3 = unknown3; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hdgf/chunks/ChunkHeaderV6.java b/src/scratchpad/src/org/apache/poi/hdgf/chunks/ChunkHeaderV6.java deleted file mode 100644 index 2a221a702..000000000 --- a/src/scratchpad/src/org/apache/poi/hdgf/chunks/ChunkHeaderV6.java +++ /dev/null @@ -1,77 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hdgf.chunks; - -import java.nio.charset.Charset; - -/** - * A chunk header from v6 - */ -public class ChunkHeaderV6 extends ChunkHeader { - private short unknown2; - private short unknown3; - - public short getUnknown2() { - return unknown2; - } - public short getUnknown3() { - return unknown3; - } - - protected static int getHeaderSize() { - // Looks like it ought to be 19... - return 19; - } - public int getSizeInBytes() { - return getHeaderSize(); - } - - /** - * Does the chunk have a trailer? - */ - public boolean hasTrailer() { - switch (getType()) { - case 0x2c: case 0x65: case 0x66: case 0x69: - case 0x6a: case 0x6b: case 0x70: case 0x71: - return true; - default: - return (getUnknown1() != 0); - } - } - - /** - * Does the chunk have a separator? - */ - public boolean hasSeparator() { - // V6 never has separators - return false; - } - - @Override - public Charset getChunkCharset() { - return Charset.forName("ASCII"); - } - - void setUnknown2(short unknown2) { - this.unknown2 = unknown2; - } - - void setUnknown3(short unknown3) { - this.unknown3 = unknown3; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hdgf/chunks/ChunkSeparator.java b/src/scratchpad/src/org/apache/poi/hdgf/chunks/ChunkSeparator.java deleted file mode 100644 index bf49ceac4..000000000 --- a/src/scratchpad/src/org/apache/poi/hdgf/chunks/ChunkSeparator.java +++ /dev/null @@ -1,35 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hdgf.chunks; - -/** - * A separator between the trailer of one chunk, and the - * header of the next one - */ -public final class ChunkSeparator { - protected byte[] separatorData; - - public ChunkSeparator(byte[] data, int offset) { - separatorData = new byte[4]; - System.arraycopy(data, offset, separatorData, 0, 4); - } - - public String toString() { - return ""; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hdgf/chunks/ChunkTrailer.java b/src/scratchpad/src/org/apache/poi/hdgf/chunks/ChunkTrailer.java deleted file mode 100644 index a4c9e178c..000000000 --- a/src/scratchpad/src/org/apache/poi/hdgf/chunks/ChunkTrailer.java +++ /dev/null @@ -1,38 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hdgf.chunks; - -/** - * A trailer that follows a chunk - */ -public final class ChunkTrailer { - private byte[] trailerData; - - public ChunkTrailer(byte[] data, int offset) { - trailerData = new byte[8]; - System.arraycopy(data, offset, trailerData, 0, 8); - } - - public String toString() { - return ""; - } - - byte[] getTrailerData() { - return trailerData; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hdgf/dev/VSDDumper.java b/src/scratchpad/src/org/apache/poi/hdgf/dev/VSDDumper.java deleted file mode 100644 index 3301743d5..000000000 --- a/src/scratchpad/src/org/apache/poi/hdgf/dev/VSDDumper.java +++ /dev/null @@ -1,139 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hdgf.dev; - -import java.io.File; -import java.io.PrintStream; -import java.util.Arrays; - -import org.apache.poi.hdgf.HDGFDiagram; -import org.apache.poi.hdgf.chunks.Chunk; -import org.apache.poi.hdgf.chunks.Chunk.Command; -import org.apache.poi.hdgf.pointers.Pointer; -import org.apache.poi.hdgf.streams.ChunkStream; -import org.apache.poi.hdgf.streams.PointerContainingStream; -import org.apache.poi.hdgf.streams.Stream; -import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; - -/** - * Developer helper class to dump out the pointer+stream structure - * of a Visio file - */ -public final class VSDDumper { - final static String tabs = "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t"; - - private final PrintStream ps; - private final HDGFDiagram hdgf; - VSDDumper(PrintStream ps, HDGFDiagram hdgf) { - this.ps = ps; - this.hdgf = hdgf; - } - - public static void main(String[] args) throws Exception { - if(args.length == 0) { - System.err.println("Use:"); - System.err.println(" VSDDumper "); - System.exit(1); - } - - NPOIFSFileSystem poifs = new NPOIFSFileSystem(new File(args[0])); - try { - HDGFDiagram hdgf = new HDGFDiagram(poifs); - - PrintStream ps = System.out; - ps.println("Opened " + args[0]); - VSDDumper vd = new VSDDumper(ps, hdgf); - vd.dumpFile(); - } finally { - poifs.close(); - } - } - - public void dumpFile() { - dumpVal("Claimed document size", hdgf.getDocumentSize(), 0); - ps.println(); - dumpStream(hdgf.getTrailerStream(), 0); - } - - private void dumpStream(Stream stream, int indent) { - Pointer ptr = stream.getPointer(); - dumpVal("Stream at", ptr.getOffset(), indent); - dumpVal("Type is", ptr.getType(), indent+1); - dumpVal("Format is", ptr.getFormat(), indent+1); - dumpVal("Length is", ptr.getLength(), indent+1); - if(ptr.destinationCompressed()) { - dumpVal("DC.Length is", stream._getContentsLength(), indent+1); - } - dumpVal("Compressed is", ptr.destinationCompressed(), indent+1); - dumpVal("Stream is", stream.getClass().getName(), indent+1); - - byte[] db = stream._getStore()._getContents(); - String ds = (db.length >= 8) ? Arrays.toString(db) : "[]"; - dumpVal("First few bytes are", ds, indent+1); - - if (stream instanceof PointerContainingStream) { - Stream streams[] = ((PointerContainingStream)stream).getPointedToStreams(); - dumpVal("Nbr of children", streams.length, indent+1); - - for(Stream s : streams) { - dumpStream(s, indent+1); - } - } - if(stream instanceof ChunkStream) { - Chunk chunks[] = ((ChunkStream)stream).getChunks(); - dumpVal("Nbr of chunks", chunks.length, indent+1); - - for(Chunk chunk : chunks) { - dumpChunk(chunk, indent+1); - } - } - } - - private void dumpChunk(Chunk chunk, int indent) { - dumpVal(chunk.getName(), "", indent); - dumpVal("Length is", chunk._getContents().length, indent); - dumpVal("OD Size is", chunk.getOnDiskSize(), indent); - dumpVal("T / S is", chunk.getTrailer() + " / " + chunk.getSeparator(), indent); - Command commands[] = chunk.getCommands(); - dumpVal("Nbr of commands", commands.length, indent); - for(Command command : commands) { - dumpVal(command.getDefinition().getName(), ""+command.getValue(), indent+1); - } - } - - private void dumpVal(String label, long value, int indent) { - ps.print(tabs.substring(0,indent)); - ps.print(label); - ps.print('\t'); - ps.print(value); - ps.print(" (0x"); - ps.print(Long.toHexString(value)); - ps.println(")"); - } - - private void dumpVal(String label, boolean value, int indent) { - dumpVal(label, Boolean.toString(value), indent); - } - - private void dumpVal(String label, String value, int indent) { - ps.print(tabs.substring(0,indent)); - ps.print(label); - ps.print('\t'); - ps.println(value); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hdgf/exceptions/HDGFException.java b/src/scratchpad/src/org/apache/poi/hdgf/exceptions/HDGFException.java deleted file mode 100644 index c893bd2df..000000000 --- a/src/scratchpad/src/org/apache/poi/hdgf/exceptions/HDGFException.java +++ /dev/null @@ -1,43 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hdgf.exceptions; - -/** - * The superclass of all HDGF exceptions - * - * @author Yegor Kozlov - */ -public final class HDGFException extends RuntimeException { - - public HDGFException() { - super(); - } - - public HDGFException(String message) { - super(message); - } - - public HDGFException(String message, Throwable cause) { - super(message, cause); - } - - public HDGFException(Throwable cause) { - super(cause); - } - -} diff --git a/src/scratchpad/src/org/apache/poi/hdgf/extractor/VisioTextExtractor.java b/src/scratchpad/src/org/apache/poi/hdgf/extractor/VisioTextExtractor.java deleted file mode 100644 index fae6e3f5c..000000000 --- a/src/scratchpad/src/org/apache/poi/hdgf/extractor/VisioTextExtractor.java +++ /dev/null @@ -1,141 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hdgf.extractor; - -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; - -import org.apache.poi.POIOLE2TextExtractor; -import org.apache.poi.hdgf.HDGFDiagram; -import org.apache.poi.hdgf.chunks.Chunk; -import org.apache.poi.hdgf.chunks.Chunk.Command; -import org.apache.poi.hdgf.streams.ChunkStream; -import org.apache.poi.hdgf.streams.PointerContainingStream; -import org.apache.poi.hdgf.streams.Stream; -import org.apache.poi.poifs.filesystem.DirectoryNode; -import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; - -/** - * Class to find all the text in a Visio file, and return it. - * Can operate on the command line (outputs to stdout), or - * can return the text for you (example: for use with Lucene). - */ -public final class VisioTextExtractor extends POIOLE2TextExtractor { - private HDGFDiagram hdgf; - - public VisioTextExtractor(HDGFDiagram hdgf) { - super(hdgf); - this.hdgf = hdgf; - } - public VisioTextExtractor(POIFSFileSystem fs) throws IOException { - this(fs.getRoot()); - } - public VisioTextExtractor(NPOIFSFileSystem fs) throws IOException { - this(fs.getRoot()); - } - public VisioTextExtractor(DirectoryNode dir) throws IOException { - this(new HDGFDiagram(dir)); - } - public VisioTextExtractor(InputStream inp) throws IOException { - this(new NPOIFSFileSystem(inp)); - } - - /** - * Locates all the text entries in the file, and returns their - * contents. - * - * @return An array of each Text item in the document - */ - public String[] getAllText() { - ArrayList text = new ArrayList(); - for(Stream stream : hdgf.getTopLevelStreams()) { - findText(stream, text); - } - return text.toArray( new String[text.size()] ); - } - private void findText(Stream stream, ArrayList text) { - if(stream instanceof PointerContainingStream) { - PointerContainingStream ps = (PointerContainingStream)stream; - for(int i=0; i 0) { - - // First command - Command cmd = chunk.getCommands()[0]; - if(cmd != null && cmd.getValue() != null) { - // Capture the text, as long as it isn't - // simply an empty string - String str = cmd.getValue().toString(); - if(str.equals("") || str.equals("\n")) { - // Ignore empty strings - } else { - text.add( str ); - } - } - } - } - } - } - - /** - * Returns the textual contents of the file. - * Each textual object's text will be separated - * by a newline - * - * @return All text contained in this document, separated by \n - */ - @Override - public String getText() { - StringBuffer text = new StringBuffer(); - for(String t : getAllText()) { - text.append(t); - if(!t.endsWith("\r") && !t.endsWith("\n")) { - text.append('\n'); - } - } - return text.toString(); - } - - public static void main(String[] args) throws Exception { - if(args.length == 0) { - System.err.println("Use:"); - System.err.println(" VisioTextExtractor "); - System.exit(1); - } - - VisioTextExtractor extractor = - new VisioTextExtractor(new FileInputStream(args[0])); - - // Print not PrintLn as already has \n added to it - System.out.print(extractor.getText()); - - extractor.close(); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hdgf/pointers/Pointer.java b/src/scratchpad/src/org/apache/poi/hdgf/pointers/Pointer.java deleted file mode 100644 index 06db8781b..000000000 --- a/src/scratchpad/src/org/apache/poi/hdgf/pointers/Pointer.java +++ /dev/null @@ -1,77 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hdgf.pointers; - -/** - * Base class of pointers, which hold metadata and offsets about - * blocks elsewhere in the file - */ -public abstract class Pointer { - private int type; - private int address; - private int offset; - private int length; - private short format; - - public int getAddress() { - return address; - } - public short getFormat() { - return format; - } - public int getLength() { - return length; - } - public int getOffset() { - return offset; - } - public int getType() { - return type; - } - - public abstract int getSizeInBytes(); - public abstract int getNumPointersOffset(byte[] data); - public abstract int getNumPointers(int offset, byte[] data); - public abstract int getPostNumPointersSkip(); - - public abstract boolean destinationHasStrings(); - public abstract boolean destinationHasPointers(); - public abstract boolean destinationHasChunks(); - public abstract boolean destinationCompressed(); - - protected void setType(int type) { - this.type = type; - } - protected void setAddress(int address) { - this.address = address; - } - protected void setOffset(int offset) { - this.offset = offset; - } - protected void setLength(int length) { - this.length = length; - } - protected void setFormat(short format) { - this.format = format; - } - - protected boolean isFormatBetween(int min, int max) { - return (min <= format && format < max); - } - -} diff --git a/src/scratchpad/src/org/apache/poi/hdgf/pointers/PointerFactory.java b/src/scratchpad/src/org/apache/poi/hdgf/pointers/PointerFactory.java deleted file mode 100644 index bb1d06436..000000000 --- a/src/scratchpad/src/org/apache/poi/hdgf/pointers/PointerFactory.java +++ /dev/null @@ -1,84 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hdgf.pointers; - -import org.apache.poi.hdgf.streams.PointerContainingStream; -import org.apache.poi.util.LittleEndian; - -/** - * Factor class to create the appropriate pointers, based on the version - * of the file - */ -public final class PointerFactory { - private int version; - public PointerFactory(int version) { - this.version = version; - } - public int getVersion() { return version; } - - /** - * Creates a single Pointer from the data at the given offset - */ - public Pointer createPointer(byte[] data, int offset) { - Pointer p; - if(version >= 6) { - p = new PointerV6(); - p.setType(LittleEndian.getInt(data, offset+0)); - p.setAddress((int)LittleEndian.getUInt(data, offset+4)); - p.setOffset((int)LittleEndian.getUInt(data, offset+8)); - p.setLength((int)LittleEndian.getUInt(data, offset+12)); - p.setFormat(LittleEndian.getShort(data, offset+16)); - - return p; - } else if(version == 5) { - p = new PointerV5(); - p.setType(LittleEndian.getShort(data, offset+0)); - p.setFormat(LittleEndian.getShort(data, offset+2)); - p.setAddress((int)LittleEndian.getUInt(data, offset+4)); - p.setOffset((int)LittleEndian.getUInt(data, offset+8)); - p.setLength((int)LittleEndian.getUInt(data, offset+12)); - - return p; - } else { - throw new IllegalArgumentException("Visio files with versions below 5 are not supported, yours was " + version); - } - } - - /** - * Parsers the {@link PointerContainingStream} contents and - * creates all the child Pointers for it - */ - public Pointer[] createContainerPointers(Pointer parent, byte[] data) { - // Where in the stream does the "number of pointers" offset live? - int numPointersOffset = parent.getNumPointersOffset(data); - // How many do we have? - int numPointers = parent.getNumPointers(numPointersOffset, data); - // How much to skip for the num pointers + any extra data? - int skip = parent.getPostNumPointersSkip(); - - // Create - int pos = numPointersOffset + skip; - Pointer[] childPointers = new Pointer[numPointers]; - for(int i=0; i 0; - } - - /** - * With v6 pointers, the on-disk size is 16 bytes - */ - public int getSizeInBytes() { return 16; } - - /** - * Depends on the type only, not stored - */ - public int getNumPointersOffset(byte[] data) { - switch (getType()) { - case 0x1d: - case 0x4e: - return 30; - case 0x1e: - return 54; - case 0x14: - return 130; - } - return 10; - } - /** - * 16 bit int at the given offset - */ - public int getNumPointers(int offset, byte[] data) { - // V5 stores it as a 16 bit number at the offset - return LittleEndian.getShort(data, offset); - } - /** - * Just the 2 bytes of the number of pointers - */ - public int getPostNumPointersSkip() { - return 2; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hdgf/pointers/PointerV6.java b/src/scratchpad/src/org/apache/poi/hdgf/pointers/PointerV6.java deleted file mode 100644 index 9983c4ccd..000000000 --- a/src/scratchpad/src/org/apache/poi/hdgf/pointers/PointerV6.java +++ /dev/null @@ -1,76 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hdgf.pointers; - -import org.apache.poi.util.LittleEndian; - -/** - * A Pointer from v6+ - */ -public final class PointerV6 extends Pointer { - public boolean destinationHasStrings() { - return isFormatBetween(0x40, 0x50); - } - - public boolean destinationHasPointers() { - return (getType() == 20) || isFormatBetween(0x1d, 0x1f) || isFormatBetween(0x50, 0x60); - } - public boolean destinationHasChunks() { - return isFormatBetween(0xd0, 0xdf); - } - - public boolean destinationCompressed() { - // Apparently, it's the second least significant bit - return (getFormat() & 2) > 0; - } - - /** - * With v6 pointers, the on-disk size is 18 bytes - */ - public int getSizeInBytes() { return 18; } - - /** - * Stored within the data - */ - public int getNumPointersOffset(byte[] data) { - return getNumPointersOffsetV6(data); - } - public static int getNumPointersOffsetV6(byte[] data) { - // V6 stores it as the first value in the stream - return (int)LittleEndian.getUInt(data, 0); - } - /** - * 32 bit int at the given offset - */ - public int getNumPointers(int offset, byte[] data) { - return getNumPointersV6(offset, data); - } - public static int getNumPointersV6(int offset, byte[] data) { - // V6 stores it a 32 bit number at the offset - return (int)LittleEndian.getUInt(data, offset); - } - /** - * 4 bytes of the number, and 4 more unknown bytes - */ - public int getPostNumPointersSkip() { - return getPostNumPointersSkipV6(); - } - public static int getPostNumPointersSkipV6() { - return 8; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hdgf/streams/ChunkStream.java b/src/scratchpad/src/org/apache/poi/hdgf/streams/ChunkStream.java deleted file mode 100644 index f58a4c851..000000000 --- a/src/scratchpad/src/org/apache/poi/hdgf/streams/ChunkStream.java +++ /dev/null @@ -1,81 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hdgf.streams; - -import java.util.ArrayList; - -import org.apache.poi.hdgf.chunks.Chunk; -import org.apache.poi.hdgf.chunks.ChunkFactory; -import org.apache.poi.hdgf.chunks.ChunkHeader; -import org.apache.poi.hdgf.pointers.Pointer; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; - -public final class ChunkStream extends Stream { - private final static POILogger logger = POILogFactory.getLogger(ChunkStream.class); - - private ChunkFactory chunkFactory; - /** All the Chunks we contain */ - private Chunk[] chunks; - - protected ChunkStream(Pointer pointer, StreamStore store, ChunkFactory chunkFactory) { - super(pointer, store); - this.chunkFactory = chunkFactory; - - // For compressed stores, we require all of the data - store.copyBlockHeaderToContents(); - } - - public Chunk[] getChunks() { return chunks; } - - /** - * Process the contents of the stream out into chunks - */ - public void findChunks() { - ArrayList chunksA = new ArrayList(); - - if(getPointer().getOffset() == 0x64b3) { - int i = 0; - i++; - } - - int pos = 0; - byte[] contents = getStore().getContents(); - try { - while(pos < contents.length) { - // Ensure we have enough data to create a chunk from - int headerSize = ChunkHeader.getHeaderSize(chunkFactory.getVersion()); - if(pos+headerSize <= contents.length) { - Chunk chunk = chunkFactory.createChunk(contents, pos); - chunksA.add(chunk); - - pos += chunk.getOnDiskSize(); - } else { - logger.log(POILogger.WARN, "Needed " + headerSize + " bytes to create the next chunk header, but only found " + (contents.length-pos) + " bytes, ignoring rest of data"); - pos = contents.length; - } - } - } - catch (Exception e) - { - logger.log(POILogger.ERROR, "Failed to create chunk at " + pos + ", ignoring rest of data." + e); - } - - chunks = chunksA.toArray(new Chunk[chunksA.size()]); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hdgf/streams/CompressedStreamStore.java b/src/scratchpad/src/org/apache/poi/hdgf/streams/CompressedStreamStore.java deleted file mode 100644 index 2fae8888d..000000000 --- a/src/scratchpad/src/org/apache/poi/hdgf/streams/CompressedStreamStore.java +++ /dev/null @@ -1,94 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hdgf.streams; - -import java.io.ByteArrayInputStream; -import java.io.IOException; - -import org.apache.poi.hdgf.HDGFLZW; - -/** - * A StreamStore where the data on-disk is compressed, - * using the crazy Visio LZW - */ -public final class CompressedStreamStore extends StreamStore { - /** The raw, compressed contents */ - private byte[] compressedContents; - /** - * We're not sure what this is, but it comes before the - * real contents in the de-compressed data - */ - private byte[] blockHeader = new byte[4]; - private boolean blockHeaderInContents = false; - - protected byte[] _getCompressedContents() { return compressedContents; } - protected byte[] _getBlockHeader() { return blockHeader; } - - /** - * Creates a new compressed StreamStore, which will handle - * the decompression. - */ - protected CompressedStreamStore(byte[] data, int offset, int length) throws IOException { - this(decompress(data,offset,length)); - - compressedContents = new byte[length]; - System.arraycopy(data, offset, compressedContents, 0, length); - } - /** - * Handles passing the de-compressed data onto our superclass. - */ - private CompressedStreamStore(byte[][] decompressedData) { - super(decompressedData[1], 0, decompressedData[1].length); - blockHeader = decompressedData[0]; - } - - /** - * Some kinds of streams expect their 4 byte header to be - * on the front of the contents. - * They can call this to have it sorted. - */ - protected void copyBlockHeaderToContents() { - if(blockHeaderInContents) return; - - prependContentsWith(blockHeader); - blockHeaderInContents = true; - } - - - /** - * Decompresses the given data, returning it as header + contents - */ - public static byte[][] decompress(byte[] data, int offset, int length) throws IOException { - ByteArrayInputStream bais = new ByteArrayInputStream(data, offset, length); - - // Decompress - HDGFLZW lzw = new HDGFLZW(); - byte[] decompressed = lzw.decompress(bais); - - // Split into header and contents - byte[][] ret = new byte[2][]; - ret[0] = new byte[4]; - ret[1] = new byte[decompressed.length - 4]; - - System.arraycopy(decompressed, 0, ret[0], 0, 4); - System.arraycopy(decompressed, 4, ret[1], 0, ret[1].length); - - // All done - return ret; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hdgf/streams/PointerContainingStream.java b/src/scratchpad/src/org/apache/poi/hdgf/streams/PointerContainingStream.java deleted file mode 100644 index e7f3cf39d..000000000 --- a/src/scratchpad/src/org/apache/poi/hdgf/streams/PointerContainingStream.java +++ /dev/null @@ -1,81 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hdgf.streams; - -import org.apache.poi.hdgf.chunks.ChunkFactory; -import org.apache.poi.hdgf.pointers.Pointer; -import org.apache.poi.hdgf.pointers.PointerFactory; - -/** - * A stream that holds pointers, possibly in addition to some - * other data too. - */ -public class PointerContainingStream extends Stream { // TODO - instantiable superclass - private Pointer[] childPointers; - private Stream[] childStreams; - - private ChunkFactory chunkFactory; - private PointerFactory pointerFactory; - - protected PointerContainingStream(Pointer pointer, StreamStore store, ChunkFactory chunkFactory, PointerFactory pointerFactory) { - super(pointer, store); - this.chunkFactory = chunkFactory; - this.pointerFactory = pointerFactory; - - // Have the child pointers identified and created - childPointers = pointerFactory.createContainerPointers(pointer, store.getContents()); - } - - /** - * Returns all the pointers that we contain - */ - protected Pointer[] getChildPointers() { return childPointers; } - /** - * Returns all the "child" streams. - * These are all the streams pointed to by the pointers - * that we contain. - */ - public Stream[] getPointedToStreams() { return childStreams; } - - /** - * Performs a recursive search, identifying the pointers we contain, - * creating the Streams for where they point to, then searching - * those if appropriate. - */ - public void findChildren(byte[] documentData) { - // For each pointer, generate the Stream it points to - childStreams = new Stream[childPointers.length]; - for(int i=0; i { - - private HemfHeader header; - private final LittleEndianInputStream stream; - - public HemfExtractor(InputStream is) throws IOException { - stream = new LittleEndianInputStream(is); - header = new HemfHeader(); - long recordId = stream.readUInt(); - long recordSize = stream.readUInt(); - - header = new HemfHeader(); - header.init(stream, recordId, recordSize-8); - } - - @Override - public Iterator iterator() { - return new HemfRecordIterator(); - } - - public HemfHeader getHeader() { - return header; - } - - private class HemfRecordIterator implements Iterator { - - private HemfRecord currentRecord = null; - - HemfRecordIterator() { - //queue the first non-header record - currentRecord = _next(); - } - - @Override - public boolean hasNext() { - return currentRecord != null; - } - - @Override - public HemfRecord next() { - HemfRecord toReturn = currentRecord; - currentRecord = _next(); - return toReturn; - } - - private HemfRecord _next() { - if (currentRecord != null && currentRecord.getRecordType().equals(HemfRecordType.eof)) { - return null; - } - long recordId = stream.readUInt(); - long recordSize = stream.readUInt(); - - HemfRecord record = null; - HemfRecordType type = HemfRecordType.getById(recordId); - if (type == null) { - throw new RuntimeException("Undefined record of type:"+recordId); - } - try { - record = type.clazz.newInstance(); - } catch (InstantiationException e) { - throw new RuntimeException(e); - } catch (IllegalAccessException e) { - throw new RuntimeException(e); - } - try { - record.init(stream, recordId, recordSize-8); - } catch (IOException e) { - throw new RecordFormatException(e); - } - - return record; - } - - @Override - public void remove() { - throw new UnsupportedOperationException("Remove not supported"); - } - - } -} diff --git a/src/scratchpad/src/org/apache/poi/hemf/hemfplus/record/HemfPlusHeader.java b/src/scratchpad/src/org/apache/poi/hemf/hemfplus/record/HemfPlusHeader.java deleted file mode 100644 index 25947937b..000000000 --- a/src/scratchpad/src/org/apache/poi/hemf/hemfplus/record/HemfPlusHeader.java +++ /dev/null @@ -1,82 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hemf.hemfplus.record; - - -import java.io.IOException; - -import org.apache.poi.util.Internal; -import org.apache.poi.util.LittleEndian; - -@Internal -public class HemfPlusHeader implements HemfPlusRecord { - - private int flags; - private long version; //hack for now; replace with EmfPlusGraphicsVersion object - private long emfPlusFlags; - private long logicalDpiX; - private long logicalDpiY; - - @Override - public HemfPlusRecordType getRecordType() { - return HemfPlusRecordType.header; - } - - public int getFlags() { - return flags; - } - - @Override - public void init(byte[] dataBytes, int recordId, int flags) throws IOException { - //assert record id == header - this.flags = flags; - int offset = 0; - this.version = LittleEndian.getUInt(dataBytes, offset); offset += LittleEndian.INT_SIZE; - this.emfPlusFlags = LittleEndian.getUInt(dataBytes, offset); offset += LittleEndian.INT_SIZE; - this.logicalDpiX = LittleEndian.getUInt(dataBytes, offset); offset += LittleEndian.INT_SIZE; - this.logicalDpiY = LittleEndian.getUInt(dataBytes, offset); - - } - - public long getVersion() { - return version; - } - - public long getEmfPlusFlags() { - return emfPlusFlags; - } - - public long getLogicalDpiX() { - return logicalDpiX; - } - - public long getLogicalDpiY() { - return logicalDpiY; - } - - @Override - public String toString() { - return "HemfPlusHeader{" + - "flags=" + flags + - ", version=" + version + - ", emfPlusFlags=" + emfPlusFlags + - ", logicalDpiX=" + logicalDpiX + - ", logicalDpiY=" + logicalDpiY + - '}'; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hemf/hemfplus/record/HemfPlusRecord.java b/src/scratchpad/src/org/apache/poi/hemf/hemfplus/record/HemfPlusRecord.java deleted file mode 100644 index 09af3d5cf..000000000 --- a/src/scratchpad/src/org/apache/poi/hemf/hemfplus/record/HemfPlusRecord.java +++ /dev/null @@ -1,44 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hemf.hemfplus.record; - - -import java.io.IOException; - -import org.apache.poi.util.Internal; - -@Internal -public interface HemfPlusRecord { - - HemfPlusRecordType getRecordType(); - - int getFlags(); - - /** - * - * @param dataBytes these are the bytes that start after the id, flags, record size - * and go to the end of the record; they do not include any required padding - * at the end. - * @param recordId record type id - * @param flags flags - * @throws IOException, RecordFormatException - */ - void init(byte[] dataBytes, int recordId, int flags) throws IOException; - - -} diff --git a/src/scratchpad/src/org/apache/poi/hemf/hemfplus/record/HemfPlusRecordType.java b/src/scratchpad/src/org/apache/poi/hemf/hemfplus/record/HemfPlusRecordType.java deleted file mode 100644 index 70837628e..000000000 --- a/src/scratchpad/src/org/apache/poi/hemf/hemfplus/record/HemfPlusRecordType.java +++ /dev/null @@ -1,97 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hemf.hemfplus.record; - -import org.apache.poi.util.Internal; - -@Internal -public enum HemfPlusRecordType { - header(0x4001, HemfPlusHeader.class), - endOfFile(0x4002, UnimplementedHemfPlusRecord.class), - comment(0x4003, UnimplementedHemfPlusRecord.class), - getDC(0x4004, UnimplementedHemfPlusRecord.class), - multiFormatStart(0x4005, UnimplementedHemfPlusRecord.class), - multiFormatSection(0x4006, UnimplementedHemfPlusRecord.class), - multiFormatEnd(0x4007, UnimplementedHemfPlusRecord.class), - object(0x4008, UnimplementedHemfPlusRecord.class), - clear(0x4009, UnimplementedHemfPlusRecord.class), - fillRects(0x400A, UnimplementedHemfPlusRecord.class), - drawRects(0x400B, UnimplementedHemfPlusRecord.class), - fillPolygon(0x400C, UnimplementedHemfPlusRecord.class), - drawLines(0x400D, UnimplementedHemfPlusRecord.class), - fillEllipse(0x400E, UnimplementedHemfPlusRecord.class), - drawEllipse(0x400F, UnimplementedHemfPlusRecord.class), - fillPie(0x4010, UnimplementedHemfPlusRecord.class), - drawPie(0x4011, UnimplementedHemfPlusRecord.class), - drawArc(0x4012, UnimplementedHemfPlusRecord.class), - fillRegion(0x4013, UnimplementedHemfPlusRecord.class), - fillPath(0x4014, UnimplementedHemfPlusRecord.class), - drawPath(0x4015, UnimplementedHemfPlusRecord.class), - fillClosedCurve(0x4016, UnimplementedHemfPlusRecord.class), - drawClosedCurve(0x4017, UnimplementedHemfPlusRecord.class), - drawCurve(0x4018, UnimplementedHemfPlusRecord.class), - drawBeziers(0x4019, UnimplementedHemfPlusRecord.class), - drawImage(0x401A, UnimplementedHemfPlusRecord.class), - drawImagePoints(0x401B, UnimplementedHemfPlusRecord.class), - drawString(0x401C, UnimplementedHemfPlusRecord.class), - setRenderingOrigin(0x401D, UnimplementedHemfPlusRecord.class), - setAntiAliasMode(0x401E, UnimplementedHemfPlusRecord.class), - setTextRenderingHint(0x401F, UnimplementedHemfPlusRecord.class), - setTextContrast(0x4020, UnimplementedHemfPlusRecord.class), - setInterpolationMode(0x4021, UnimplementedHemfPlusRecord.class), - setPixelOffsetMode(0x4022, UnimplementedHemfPlusRecord.class), - setComositingMode(0x4023, UnimplementedHemfPlusRecord.class), - setCompositingQuality(0x4024, UnimplementedHemfPlusRecord.class), - save(0x4025, UnimplementedHemfPlusRecord.class), - restore(0x4026, UnimplementedHemfPlusRecord.class), - beginContainer(0x4027, UnimplementedHemfPlusRecord.class), - beginContainerNoParams(0x428, UnimplementedHemfPlusRecord.class), - endContainer(0x4029, UnimplementedHemfPlusRecord.class), - setWorldTransform(0x402A, UnimplementedHemfPlusRecord.class), - resetWorldTransform(0x402B, UnimplementedHemfPlusRecord.class), - multiplyWorldTransform(0x402C, UnimplementedHemfPlusRecord.class), - translateWorldTransform(0x402D, UnimplementedHemfPlusRecord.class), - scaleWorldTransform(0x402E, UnimplementedHemfPlusRecord.class), - rotateWorldTransform(0x402F, UnimplementedHemfPlusRecord.class), - setPageTransform(0x4030, UnimplementedHemfPlusRecord.class), - resetClip(0x4031, UnimplementedHemfPlusRecord.class), - setClipRect(0x4032, UnimplementedHemfPlusRecord.class), - setClipRegion(0x4033, UnimplementedHemfPlusRecord.class), - setClipPath(0x4034, UnimplementedHemfPlusRecord.class), - offsetClip(0x4035, UnimplementedHemfPlusRecord.class), - drawDriverstring(0x4036, UnimplementedHemfPlusRecord.class), - strokeFillPath(0x4037, UnimplementedHemfPlusRecord.class), - serializableObject(0x4038, UnimplementedHemfPlusRecord.class), - setTSGraphics(0x4039, UnimplementedHemfPlusRecord.class), - setTSClip(0x403A, UnimplementedHemfPlusRecord.class); - - public final long id; - public final Class clazz; - - HemfPlusRecordType(long id, Class clazz) { - this.id = id; - this.clazz = clazz; - } - - public static HemfPlusRecordType getById(long id) { - for (HemfPlusRecordType wrt : values()) { - if (wrt.id == id) return wrt; - } - return null; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hemf/hemfplus/record/UnimplementedHemfPlusRecord.java b/src/scratchpad/src/org/apache/poi/hemf/hemfplus/record/UnimplementedHemfPlusRecord.java deleted file mode 100644 index 7e3cbcff4..000000000 --- a/src/scratchpad/src/org/apache/poi/hemf/hemfplus/record/UnimplementedHemfPlusRecord.java +++ /dev/null @@ -1,53 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hemf.hemfplus.record; - - -import java.io.IOException; - -import org.apache.poi.util.Internal; - -@Internal -public class UnimplementedHemfPlusRecord implements HemfPlusRecord { - - private int recordId; - private int flags; - private byte[] recordBytes; - - @Override - public HemfPlusRecordType getRecordType() { - return HemfPlusRecordType.getById(recordId); - } - - @Override - public int getFlags() { - return flags; - } - - @Override - public void init(byte[] recordBytes, int recordId, int flags) throws IOException { - this.recordId = recordId; - this.flags = flags; - this.recordBytes = recordBytes; - } - - public byte[] getRecordBytes() { - //should probably defensively return a copy. - return recordBytes; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hemf/record/AbstractHemfComment.java b/src/scratchpad/src/org/apache/poi/hemf/record/AbstractHemfComment.java deleted file mode 100644 index 7ffff6b01..000000000 --- a/src/scratchpad/src/org/apache/poi/hemf/record/AbstractHemfComment.java +++ /dev/null @@ -1,39 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hemf.record; - -import org.apache.poi.util.Internal; - -/** - * Syntactic utility to allow for four different - * comment classes - */ -@Internal -public abstract class AbstractHemfComment { - - private final byte[] rawBytes; - - public AbstractHemfComment(byte[] rawBytes) { - this.rawBytes = rawBytes; - } - - public byte[] getRawBytes() { - return rawBytes; - } - -} diff --git a/src/scratchpad/src/org/apache/poi/hemf/record/HemfComment.java b/src/scratchpad/src/org/apache/poi/hemf/record/HemfComment.java deleted file mode 100644 index 5d45927bb..000000000 --- a/src/scratchpad/src/org/apache/poi/hemf/record/HemfComment.java +++ /dev/null @@ -1,31 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hemf.record; - -import org.apache.poi.util.Internal; - -/** - * Contains arbitrary data - */ -@Internal -public class HemfComment extends AbstractHemfComment { - - public HemfComment(byte[] rawBytes) { - super(rawBytes); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hemf/record/HemfCommentEMFPlus.java b/src/scratchpad/src/org/apache/poi/hemf/record/HemfCommentEMFPlus.java deleted file mode 100644 index b32bf5481..000000000 --- a/src/scratchpad/src/org/apache/poi/hemf/record/HemfCommentEMFPlus.java +++ /dev/null @@ -1,107 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hemf.record; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.hemf.hemfplus.record.HemfPlusRecord; -import org.apache.poi.hemf.hemfplus.record.HemfPlusRecordType; -import org.apache.poi.util.Internal; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.RecordFormatException; - -/** - * An HemfCommentEMFPlus may contain one or more EMFPlus records - */ -@Internal -public class HemfCommentEMFPlus extends AbstractHemfComment { - - long dataSize; - public HemfCommentEMFPlus(byte[] rawBytes) { - //these rawBytes contain only the EMFPlusRecord(s?) - //the EmfComment type, size, datasize and comment identifier have all been stripped. - //The EmfPlus type, flags, size, data size should start at rawBytes[0] - super(rawBytes); - - } - - public List getRecords() { - return HemfPlusParser.parse(getRawBytes()); - } - - private static class HemfPlusParser { - - public static List parse(byte[] bytes) { - List records = new ArrayList(); - int offset = 0; - while (offset < bytes.length) { - if (offset + 12 > bytes.length) { - //if header will go beyond bytes, stop now - //TODO: log or throw - break; - } - int type = LittleEndian.getUShort(bytes, offset); offset += LittleEndian.SHORT_SIZE; - int flags = LittleEndian.getUShort(bytes, offset); offset += LittleEndian.SHORT_SIZE; - long sizeLong = LittleEndian.getUInt(bytes, offset); offset += LittleEndian.INT_SIZE; - if (sizeLong >= Integer.MAX_VALUE) { - throw new RecordFormatException("size of emf record >= Integer.MAX_VALUE"); - } - int size = (int)sizeLong; - long dataSizeLong = LittleEndian.getUInt(bytes, offset); offset += LittleEndian.INT_SIZE; - if (dataSizeLong >= Integer.MAX_VALUE) { - throw new RuntimeException("data size of emfplus record cannot be >= Integer.MAX_VALUE"); - } - int dataSize = (int)dataSizeLong; - if (dataSize + offset > bytes.length) { - //TODO: log or throw? - break; - } - HemfPlusRecord record = buildRecord(type, flags, dataSize, offset, bytes); - records.add(record); - offset += dataSize; - } - return records; - } - - private static HemfPlusRecord buildRecord(int recordId, int flags, int size, int offset, byte[] bytes) { - HemfPlusRecord record = null; - HemfPlusRecordType type = HemfPlusRecordType.getById(recordId); - if (type == null) { - throw new RuntimeException("Undefined record of type:"+recordId); - } - try { - record = type.clazz.newInstance(); - } catch (InstantiationException e) { - throw new RuntimeException(e); - } catch (IllegalAccessException e) { - throw new RuntimeException(e); - } - byte[] dataBytes = new byte[size]; - System.arraycopy(bytes, offset, dataBytes, 0, size); - try { - record.init(dataBytes, recordId, flags); - } catch (IOException e) { - throw new RuntimeException(e); - } - return record; - - } - } -} diff --git a/src/scratchpad/src/org/apache/poi/hemf/record/HemfCommentEMFSpool.java b/src/scratchpad/src/org/apache/poi/hemf/record/HemfCommentEMFSpool.java deleted file mode 100644 index 009974d10..000000000 --- a/src/scratchpad/src/org/apache/poi/hemf/record/HemfCommentEMFSpool.java +++ /dev/null @@ -1,31 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hemf.record; - -import org.apache.poi.util.Internal; - -/** - * Not yet implemented - */ -@Internal -public class HemfCommentEMFSpool extends AbstractHemfComment { - - public HemfCommentEMFSpool(byte[] rawBytes) { - super(rawBytes); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hemf/record/HemfCommentPublic.java b/src/scratchpad/src/org/apache/poi/hemf/record/HemfCommentPublic.java deleted file mode 100644 index cb0447619..000000000 --- a/src/scratchpad/src/org/apache/poi/hemf/record/HemfCommentPublic.java +++ /dev/null @@ -1,176 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hemf.record; - - -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.util.Internal; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.RecordFormatException; - -/** - * Container class for four subtypes of HemfCommentPublic: BeginGroup, EndGroup, MultiFormats - * and Windows Metafile. - */ -@Internal -public class HemfCommentPublic { - - /** - * Stub, to be implemented - */ - public static class BeginGroup extends AbstractHemfComment { - - public BeginGroup(byte[] rawBytes) { - super(rawBytes); - } - - } - - /** - * Stub, to be implemented - */ - public static class EndGroup extends AbstractHemfComment { - - public EndGroup(byte[] rawBytes) { - super(rawBytes); - } - } - - public static class MultiFormats extends AbstractHemfComment { - - public MultiFormats(byte[] rawBytes) { - super(rawBytes); - } - - /** - * - * @return a list of HemfMultFormatsData - */ - public List getData() { - - byte[] rawBytes = getRawBytes(); - //note that raw bytes includes the public comment identifier - int currentOffset = 4 + 16;//4 public comment identifier, 16 for outputrect - long countFormats = LittleEndian.getUInt(rawBytes, currentOffset); - currentOffset += LittleEndian.INT_SIZE; - List emrFormatList = new ArrayList(); - for (long i = 0; i < countFormats; i++) { - emrFormatList.add(new EmrFormat(rawBytes, currentOffset)); - currentOffset += 4 * LittleEndian.INT_SIZE; - } - List list = new ArrayList(); - for (EmrFormat emrFormat : emrFormatList) { - byte[] data = new byte[emrFormat.size]; - System.arraycopy(rawBytes, emrFormat.offset-4, data, 0, emrFormat.size); - list.add(new HemfMultiFormatsData(emrFormat.signature, emrFormat.version, data)); - } - return list; - } - - private class EmrFormat { - long signature; - long version; - int size; - int offset; - - public EmrFormat(byte[] rawBytes, int currentOffset) { - signature = LittleEndian.getUInt(rawBytes, currentOffset); currentOffset += LittleEndian.INT_SIZE; - version = LittleEndian.getUInt(rawBytes, currentOffset); currentOffset += LittleEndian.INT_SIZE; - //spec says this must be a 32bit "aligned" typo for "signed"? - //realistically, this has to be an int... - size = LittleEndian.getInt(rawBytes, currentOffset); currentOffset += LittleEndian.INT_SIZE; - //y, can be long, but realistically? - offset = LittleEndian.getInt(rawBytes, currentOffset); currentOffset += LittleEndian.INT_SIZE; - if (size < 0) { - throw new RecordFormatException("size for emrformat must be > 0"); - } - if (offset < 0) { - throw new RecordFormatException("offset for emrformat must be > 0"); - } - } - } - } - - /** - * Stub, to be implemented - */ - public static class WindowsMetafile extends AbstractHemfComment { - - private final byte[] wmfBytes; - public WindowsMetafile(byte[] rawBytes) { - super(rawBytes); - int offset = LittleEndian.INT_SIZE;//public comment identifier - int version = LittleEndian.getUShort(rawBytes, offset); offset += LittleEndian.SHORT_SIZE; - int reserved = LittleEndian.getUShort(rawBytes, offset); offset += LittleEndian.SHORT_SIZE; - offset += LittleEndian.INT_SIZE; //checksum - offset += LittleEndian.INT_SIZE; //flags - long winMetafileSizeLong = LittleEndian.getUInt(rawBytes, offset); offset += LittleEndian.INT_SIZE; - if (winMetafileSizeLong == 0L) { - wmfBytes = new byte[0]; - return; - } - if (winMetafileSizeLong > Integer.MAX_VALUE) { - throw new RecordFormatException("Metafile record length can't be > Integer.MAX_VALUE"); - } - int winMetafileSize = (int)winMetafileSizeLong; - wmfBytes = new byte[winMetafileSize]; - System.arraycopy(rawBytes, offset, wmfBytes, 0, winMetafileSize); - } - - /** - * - * @return an InputStream for the embedded WMF file - */ - public InputStream getWmfInputStream() { - return new ByteArrayInputStream(wmfBytes); - } - } - - /** - * This encapulates a single record stored within - * a HemfCommentPublic.MultiFormats record. - */ - public static class HemfMultiFormatsData { - - long signature; - long version; - byte[] data; - - public HemfMultiFormatsData(long signature, long version, byte[] data) { - this.signature = signature; - this.version = version; - this.data = data; - } - - public long getSignature() { - return signature; - } - - public long getVersion() { - return version; - } - - public byte[] getData() { - return data; - } - } -} diff --git a/src/scratchpad/src/org/apache/poi/hemf/record/HemfCommentRecord.java b/src/scratchpad/src/org/apache/poi/hemf/record/HemfCommentRecord.java deleted file mode 100644 index 51efb2f2b..000000000 --- a/src/scratchpad/src/org/apache/poi/hemf/record/HemfCommentRecord.java +++ /dev/null @@ -1,139 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hemf.record; - - -import java.io.IOException; - -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.Internal; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.LittleEndianInputStream; -import org.apache.poi.util.RecordFormatException; - -/** - * This is the outer comment record that is recognized - * by the initial parse by {@link HemfRecordType#comment}. - * However, there are four types of comment: EMR_COMMENT, - * EMR_COMMENT_EMFPLUS, EMR_COMMENT_EMFSPOOL, and EMF_COMMENT_PUBLIC. - * To get the underlying comment, call {@link #getComment()}. - * - */ -@Internal -public class HemfCommentRecord implements HemfRecord { - - public final static long COMMENT_EMFSPOOL = 0x00000000; - public final static long COMMENT_EMFPLUS = 0x2B464D45; - public final static long COMMENT_PUBLIC = 0x43494447; - - - private AbstractHemfComment comment; - @Override - public HemfRecordType getRecordType() { - return HemfRecordType.comment; - } - - @Override - public long init(LittleEndianInputStream leis, long recordId, long recordSize) throws IOException { - long dataSize = leis.readUInt(); recordSize -= LittleEndian.INT_SIZE; - - byte[] optionalCommentIndentifierBuffer = new byte[4]; - leis.readFully(optionalCommentIndentifierBuffer); - dataSize = dataSize-LittleEndian.INT_SIZE; //size minus the first int which could be a comment identifier - recordSize -= LittleEndian.INT_SIZE; - long optionalCommentIdentifier = LittleEndian.getInt(optionalCommentIndentifierBuffer) & 0x00FFFFFFFFL; - if (optionalCommentIdentifier == COMMENT_EMFSPOOL) { - comment = new HemfCommentEMFSpool(readToByteArray(leis, dataSize, recordSize)); - } else if (optionalCommentIdentifier == COMMENT_EMFPLUS) { - comment = new HemfCommentEMFPlus(readToByteArray(leis, dataSize, recordSize)); - } else if (optionalCommentIdentifier == COMMENT_PUBLIC) { - comment = CommentPublicParser.parse(readToByteArray(leis, dataSize, recordSize)); - } else { - comment = new HemfComment(readToByteArray(optionalCommentIndentifierBuffer, leis, dataSize, recordSize)); - } - - return recordSize; - } - - //this prepends the initial "int" which turned out NOT to be - //a signifier of emfplus, spool, public. - private byte[] readToByteArray(byte[] initialBytes, LittleEndianInputStream leis, - long remainingDataSize, long remainingRecordSize) throws IOException { - if (remainingDataSize > Integer.MAX_VALUE) { - throw new RecordFormatException("Data size can't be > Integer.MAX_VALUE"); - } - - if (remainingRecordSize > Integer.MAX_VALUE) { - throw new RecordFormatException("Record size can't be > Integer.MAX_VALUE"); - } - if (remainingRecordSize == 0) { - return new byte[0]; - } - - int dataSize = (int)remainingDataSize; - int recordSize = (int)remainingRecordSize; - byte[] arr = new byte[dataSize+initialBytes.length]; - System.arraycopy(initialBytes,0,arr, 0, initialBytes.length); - IOUtils.readFully(leis, arr, initialBytes.length, dataSize); - IOUtils.skipFully(leis, recordSize-dataSize); - - return arr; - } - - private byte[] readToByteArray(LittleEndianInputStream leis, long dataSize, long recordSize) throws IOException { - assert dataSize < Integer.MAX_VALUE; - - if (recordSize == 0) { - return new byte[0]; - } - - byte[] arr = new byte[(int)dataSize]; - IOUtils.readFully(leis, arr); - IOUtils.skipFully(leis, recordSize-dataSize); - return arr; - } - - public AbstractHemfComment getComment() { - return comment; - } - - private static class CommentPublicParser { - private static final long WINDOWS_METAFILE = 0x80000001L; //wmf - private static final long BEGINGROUP = 0x00000002; //beginning of a group of drawing records - private static final long ENDGROUP = 0x00000003; //end of a group of drawing records - private static final long MULTIFORMATS = 0x40000004; //allows multiple definitions of an image, including encapsulated postscript - private static final long UNICODE_STRING = 0x00000040; //reserved. must not be used - private static final long UNICODE_END = 0x00000080; //reserved, must not be used - - private static AbstractHemfComment parse(byte[] bytes) { - long publicCommentIdentifier = LittleEndian.getUInt(bytes, 0); - if (publicCommentIdentifier == WINDOWS_METAFILE) { - return new HemfCommentPublic.WindowsMetafile(bytes); - } else if (publicCommentIdentifier == BEGINGROUP) { - return new HemfCommentPublic.BeginGroup(bytes); - } else if (publicCommentIdentifier == ENDGROUP) { - return new HemfCommentPublic.EndGroup(bytes); - } else if (publicCommentIdentifier == MULTIFORMATS) { - return new HemfCommentPublic.MultiFormats(bytes); - } else if (publicCommentIdentifier == UNICODE_STRING || publicCommentIdentifier == UNICODE_END) { - throw new RuntimeException("UNICODE_STRING/UNICODE_END values are reserved in CommentPublic records"); - } - throw new RuntimeException("Unrecognized public comment type:" +publicCommentIdentifier + " ; " + WINDOWS_METAFILE); - } - } -} diff --git a/src/scratchpad/src/org/apache/poi/hemf/record/HemfHeader.java b/src/scratchpad/src/org/apache/poi/hemf/record/HemfHeader.java deleted file mode 100644 index a23f4fdae..000000000 --- a/src/scratchpad/src/org/apache/poi/hemf/record/HemfHeader.java +++ /dev/null @@ -1,198 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hemf.record; - -import java.awt.Rectangle; -import java.io.IOException; - -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.Internal; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.LittleEndianInputStream; - -/** - * Extracts the full header from EMF files. - * @see org.apache.poi.sl.image.ImageHeaderEMF - */ -@Internal -public class HemfHeader implements HemfRecord { - - private Rectangle boundsRectangle; - private Rectangle frameRectangle; - private long bytes; - private long records; - private int handles; - private long nDescription; - private long offDescription; - private long nPalEntries; - private boolean hasExtension1; - private long cbPixelFormat; - private long offPixelFormat; - private long bOpenGL; - private boolean hasExtension2; - private long micrometersX; - private long micrometersY; - - public Rectangle getBoundsRectangle() { - return boundsRectangle; - } - - public Rectangle getFrameRectangle() { - return frameRectangle; - } - - public long getBytes() { - return bytes; - } - - public long getRecords() { - return records; - } - - public int getHandles() { - return handles; - } - - public long getnDescription() { - return nDescription; - } - - public long getOffDescription() { - return offDescription; - } - - public long getnPalEntries() { - return nPalEntries; - } - - public boolean isHasExtension1() { - return hasExtension1; - } - - public long getCbPixelFormat() { - return cbPixelFormat; - } - - public long getOffPixelFormat() { - return offPixelFormat; - } - - public long getbOpenGL() { - return bOpenGL; - } - - public boolean isHasExtension2() { - return hasExtension2; - } - - public long getMicrometersX() { - return micrometersX; - } - - public long getMicrometersY() { - return micrometersY; - } - - @Override - public String toString() { - return "HemfHeader{" + - "boundsRectangle=" + boundsRectangle + - ", frameRectangle=" + frameRectangle + - ", bytes=" + bytes + - ", records=" + records + - ", handles=" + handles + - ", nDescription=" + nDescription + - ", offDescription=" + offDescription + - ", nPalEntries=" + nPalEntries + - ", hasExtension1=" + hasExtension1 + - ", cbPixelFormat=" + cbPixelFormat + - ", offPixelFormat=" + offPixelFormat + - ", bOpenGL=" + bOpenGL + - ", hasExtension2=" + hasExtension2 + - ", micrometersX=" + micrometersX + - ", micrometersY=" + micrometersY + - '}'; - } - - @Override - public HemfRecordType getRecordType() { - return HemfRecordType.header; - } - - @Override - public long init(LittleEndianInputStream leis, long recordId, long recordSize) throws IOException { - if (recordId != 1L) { - throw new IOException("Not a valid EMF header. Record type:"+recordId); - } - //read the record--id and size (2 bytes) have already been read - byte[] data = new byte[(int)recordSize]; - IOUtils.readFully(leis, data); - - int offset = 0; - - //bounds - int boundsLeft = LittleEndian.getInt(data, offset); offset += LittleEndian.INT_SIZE; - int boundsTop = LittleEndian.getInt(data, offset); offset += LittleEndian.INT_SIZE; - int boundsRight = LittleEndian.getInt(data, offset); offset += LittleEndian.INT_SIZE; - int boundsBottom = LittleEndian.getInt(data, offset); offset += LittleEndian.INT_SIZE; - boundsRectangle = new Rectangle(boundsLeft, boundsTop, - boundsRight - boundsLeft, boundsBottom - boundsTop); - - int frameLeft = LittleEndian.getInt(data, offset); offset += LittleEndian.INT_SIZE; - int frameTop = LittleEndian.getInt(data, offset); offset += LittleEndian.INT_SIZE; - int frameRight = LittleEndian.getInt(data, offset); offset += LittleEndian.INT_SIZE; - int frameBottom = LittleEndian.getInt(data, offset); offset += LittleEndian.INT_SIZE; - frameRectangle = new Rectangle(frameLeft, frameTop, - frameRight - frameLeft, frameBottom - frameTop); - - long recordSignature = LittleEndian.getInt(data, offset); offset += LittleEndian.INT_SIZE; - if (recordSignature != 0x464D4520) { - throw new IOException("bad record signature: " + recordSignature); - } - - long version = LittleEndian.getInt(data, offset); offset += LittleEndian.INT_SIZE; - //According to the spec, MSOffice doesn't pay attention to this value. - //It _should_ be 0x00010000 - bytes = LittleEndian.getUInt(data, offset); offset += LittleEndian.INT_SIZE; - records = LittleEndian.getUInt(data, offset); offset += LittleEndian.INT_SIZE; - handles = LittleEndian.getUShort(data, offset);offset += LittleEndian.SHORT_SIZE; - offset += LittleEndian.SHORT_SIZE;//reserved - nDescription = LittleEndian.getUInt(data, offset); offset += LittleEndian.INT_SIZE; - offDescription = LittleEndian.getUInt(data, offset); offset += LittleEndian.INT_SIZE; - nPalEntries = LittleEndian.getUInt(data, offset); offset += LittleEndian.INT_SIZE; - - //should be skips - offset += 8;//device - offset += 8;//millimeters - - - if (recordSize+8 >= 100) { - hasExtension1 = true; - cbPixelFormat = LittleEndian.getUInt(data, offset); offset += LittleEndian.INT_SIZE; - offPixelFormat = LittleEndian.getUInt(data, offset); offset += LittleEndian.INT_SIZE; - bOpenGL= LittleEndian.getUInt(data, offset); offset += LittleEndian.INT_SIZE; - } - - if (recordSize+8 >= 108) { - hasExtension2 = true; - micrometersX = LittleEndian.getUInt(data, offset); offset += LittleEndian.INT_SIZE; - micrometersY = LittleEndian.getUInt(data, offset); offset += LittleEndian.INT_SIZE; - } - return recordSize; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hemf/record/HemfRecord.java b/src/scratchpad/src/org/apache/poi/hemf/record/HemfRecord.java deleted file mode 100644 index de1271e69..000000000 --- a/src/scratchpad/src/org/apache/poi/hemf/record/HemfRecord.java +++ /dev/null @@ -1,41 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hemf.record; - - -import java.io.IOException; - -import org.apache.poi.util.Internal; -import org.apache.poi.util.LittleEndianInputStream; - -@Internal -public interface HemfRecord { - - HemfRecordType getRecordType(); - - /** - * Init record from stream - * - * @param leis the little endian input stream - * @return count of processed bytes - * @throws IOException - */ - long init(LittleEndianInputStream leis, long recordId, long recordSize) throws IOException; - - -} diff --git a/src/scratchpad/src/org/apache/poi/hemf/record/HemfRecordType.java b/src/scratchpad/src/org/apache/poi/hemf/record/HemfRecordType.java deleted file mode 100644 index b1c585711..000000000 --- a/src/scratchpad/src/org/apache/poi/hemf/record/HemfRecordType.java +++ /dev/null @@ -1,159 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hemf.record; - -import org.apache.poi.util.Internal; - -@Internal -public enum HemfRecordType { - - header(0x00000001, UnimplementedHemfRecord.class), - polybeizer(0x00000002, UnimplementedHemfRecord.class), - polygon(0x00000003, UnimplementedHemfRecord.class), - polyline(0x00000004, UnimplementedHemfRecord.class), - polybezierto(0x00000005, UnimplementedHemfRecord.class), - polylineto(0x00000006, UnimplementedHemfRecord.class), - polypolyline(0x00000007, UnimplementedHemfRecord.class), - polypolygon(0x00000008, UnimplementedHemfRecord.class), - setwindowextex(0x00000009, UnimplementedHemfRecord.class), - setwindoworgex(0x0000000A, UnimplementedHemfRecord.class), - setviewportextex(0x0000000B, UnimplementedHemfRecord.class), - setviewportorgex(0x0000000C, UnimplementedHemfRecord.class), - setbrushorgex(0x0000000D, UnimplementedHemfRecord.class), - eof(0x0000000E, UnimplementedHemfRecord.class), - setpixelv(0x0000000F, UnimplementedHemfRecord.class), - setmapperflags(0x00000010, UnimplementedHemfRecord.class), - setmapmode(0x00000011, UnimplementedHemfRecord.class), - setbkmode(0x00000012, UnimplementedHemfRecord.class), - setpolyfillmode(0x00000013, UnimplementedHemfRecord.class), - setrop2(0x00000014, UnimplementedHemfRecord.class), - setstretchbltmode(0x00000015, UnimplementedHemfRecord.class), - settextalign(0x00000016, HemfText.SetTextAlign.class), - setcoloradjustment(0x00000017, UnimplementedHemfRecord.class), - settextcolor(0x00000018, HemfText.SetTextColor.class), - setbkcolor(0x00000019, UnimplementedHemfRecord.class), - setoffsetcliprgn(0x0000001A, UnimplementedHemfRecord.class), - setmovetoex(0x0000001B, UnimplementedHemfRecord.class), - setmetargn(0x0000001C, UnimplementedHemfRecord.class), - setexcludecliprect(0x0000001D, UnimplementedHemfRecord.class), - setintersectcliprect(0x0000001E, UnimplementedHemfRecord.class), - scaleviewportextex(0x0000001F, UnimplementedHemfRecord.class), - scalewindowextex(0x00000020, UnimplementedHemfRecord.class), - savedc(0x00000021, UnimplementedHemfRecord.class), - restoredc(0x00000022, UnimplementedHemfRecord.class), - setworldtransform(0x00000023, UnimplementedHemfRecord.class), - modifyworldtransform(0x00000024, UnimplementedHemfRecord.class), - selectobject(0x00000025, UnimplementedHemfRecord.class), - createpen(0x00000026, UnimplementedHemfRecord.class), - createbrushindirect(0x00000027, UnimplementedHemfRecord.class), - deleteobject(0x00000028, UnimplementedHemfRecord.class), - anglearc(0x00000029, UnimplementedHemfRecord.class), - ellipse(0x0000002A, UnimplementedHemfRecord.class), - rectangle(0x0000002B, UnimplementedHemfRecord.class), - roundirect(0x0000002C, UnimplementedHemfRecord.class), - arc(0x0000002D, UnimplementedHemfRecord.class), - chord(0x0000002E, UnimplementedHemfRecord.class), - pie(0x0000002F, UnimplementedHemfRecord.class), - selectpalette(0x00000030, UnimplementedHemfRecord.class), - createpalette(0x00000031, UnimplementedHemfRecord.class), - setpaletteentries(0x00000032, UnimplementedHemfRecord.class), - resizepalette(0x00000033, UnimplementedHemfRecord.class), - realizepalette(0x0000034, UnimplementedHemfRecord.class), - extfloodfill(0x00000035, UnimplementedHemfRecord.class), - lineto(0x00000036, UnimplementedHemfRecord.class), - arcto(0x00000037, UnimplementedHemfRecord.class), - polydraw(0x00000038, UnimplementedHemfRecord.class), - setarcdirection(0x00000039, UnimplementedHemfRecord.class), - setmiterlimit(0x0000003A, UnimplementedHemfRecord.class), - beginpath(0x0000003B, UnimplementedHemfRecord.class), - endpath(0x0000003C, UnimplementedHemfRecord.class), - closefigure(0x0000003D, UnimplementedHemfRecord.class), - fillpath(0x0000003E, UnimplementedHemfRecord.class), - strokeandfillpath(0x0000003F, UnimplementedHemfRecord.class), - strokepath(0x00000040, UnimplementedHemfRecord.class), - flattenpath(0x00000041, UnimplementedHemfRecord.class), - widenpath(0x00000042, UnimplementedHemfRecord.class), - selectclippath(0x00000043, UnimplementedHemfRecord.class), - abortpath(0x00000044, UnimplementedHemfRecord.class), //no 45?! - comment(0x00000046, HemfCommentRecord.class), - fillrgn(0x00000047, UnimplementedHemfRecord.class), - framergn(0x00000048, UnimplementedHemfRecord.class), - invertrgn(0x00000049, UnimplementedHemfRecord.class), - paintrgn(0x0000004A, UnimplementedHemfRecord.class), - extselectciprrgn(0x0000004B, UnimplementedHemfRecord.class), - bitblt(0x0000004C, UnimplementedHemfRecord.class), - stretchblt(0x0000004D, UnimplementedHemfRecord.class), - maskblt(0x0000004E, UnimplementedHemfRecord.class), - plgblt(0x0000004F, UnimplementedHemfRecord.class), - setbitstodevice(0x00000050, UnimplementedHemfRecord.class), - stretchdibits(0x00000051, UnimplementedHemfRecord.class), - extcreatefontindirectw(0x00000052, HemfText.ExtCreateFontIndirectW.class), - exttextouta(0x00000053, HemfText.ExtTextOutA.class), - exttextoutw(0x00000054, HemfText.ExtTextOutW.class), - polybezier16(0x00000055, UnimplementedHemfRecord.class), - polygon16(0x00000056, UnimplementedHemfRecord.class), - polyline16(0x00000057, UnimplementedHemfRecord.class), - polybezierto16(0x00000058, UnimplementedHemfRecord.class), - polylineto16(0x00000059, UnimplementedHemfRecord.class), - polypolyline16(0x0000005A, UnimplementedHemfRecord.class), - polypolygon16(0x0000005B, UnimplementedHemfRecord.class), - polydraw16(0x0000005C, UnimplementedHemfRecord.class), - createmonobrush16(0x0000005D, UnimplementedHemfRecord.class), - createdibpatternbrushpt(0x0000005E, UnimplementedHemfRecord.class), - extcreatepen(0x0000005F, UnimplementedHemfRecord.class), - polytextouta(0x00000060, HemfText.PolyTextOutA.class), - polytextoutw(0x00000061, HemfText.PolyTextOutW.class), - seticmmode(0x00000062, UnimplementedHemfRecord.class), - createcolorspace(0x00000063, UnimplementedHemfRecord.class), - setcolorspace(0x00000064, UnimplementedHemfRecord.class), - deletecolorspace(0x00000065, UnimplementedHemfRecord.class), - glsrecord(0x00000066, UnimplementedHemfRecord.class), - glsboundedrecord(0x00000067, UnimplementedHemfRecord.class), - pixelformat(0x00000068, UnimplementedHemfRecord.class), - drawescape(0x00000069, UnimplementedHemfRecord.class), - extescape(0x0000006A, UnimplementedHemfRecord.class),//no 6b?! - smalltextout(0x0000006C, UnimplementedHemfRecord.class), - forceufimapping(0x0000006D, UnimplementedHemfRecord.class), - namedescape(0x0000006E, UnimplementedHemfRecord.class), - colorcorrectpalette(0x0000006F, UnimplementedHemfRecord.class), - seticmprofilea(0x00000070, UnimplementedHemfRecord.class), - seticmprofilew(0x00000071, UnimplementedHemfRecord.class), - alphablend(0x00000072, UnimplementedHemfRecord.class), - setlayout(0x00000073, UnimplementedHemfRecord.class), - transparentblt(0x00000074, UnimplementedHemfRecord.class), - gradientfill(0x00000076, UnimplementedHemfRecord.class), //no 75?! - setlinkdufis(0x00000077, UnimplementedHemfRecord.class), - settextjustification(0x00000078, HemfText.SetTextJustification.class), - colormatchtargetw(0x00000079, UnimplementedHemfRecord.class), - createcolorspacew(0x0000007A, UnimplementedHemfRecord.class); - - public final long id; - public final Class clazz; - - HemfRecordType(long id, Class clazz) { - this.id = id; - this.clazz = clazz; - } - - public static HemfRecordType getById(long id) { - for (HemfRecordType wrt : values()) { - if (wrt.id == id) return wrt; - } - return null; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hemf/record/HemfText.java b/src/scratchpad/src/org/apache/poi/hemf/record/HemfText.java deleted file mode 100644 index c40e493bd..000000000 --- a/src/scratchpad/src/org/apache/poi/hemf/record/HemfText.java +++ /dev/null @@ -1,262 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hemf.record; - - -import java.io.ByteArrayInputStream; -import java.io.EOFException; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.Reader; -import java.nio.charset.Charset; - -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.Internal; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.LittleEndianInputStream; -import org.apache.poi.util.RecordFormatException; - -/** - * Container class to gather all text-related commands - * This is starting out as read only, and very little is actually - * implemented at this point! - */ -@Internal -public class HemfText { - - private final static Charset UTF16LE = Charset.forName("UTF-16LE"); - - public static class ExtCreateFontIndirectW extends UnimplementedHemfRecord { - } - - public static class ExtTextOutA implements HemfRecord { - - private long left,top,right,bottom; - - //TODO: translate this to a graphicsmode enum - private long graphicsMode; - - private long exScale; - private long eyScale; - EmrTextObject textObject; - - @Override - public HemfRecordType getRecordType() { - return HemfRecordType.exttextouta; - } - - @Override - public long init(LittleEndianInputStream leis, long recordId, long recordSize) throws IOException { - //note that the first 2 uInts have been read off and the recordsize has - //been decreased by 8 - left = leis.readInt(); - top = leis.readInt(); - right = leis.readInt(); - bottom = leis.readInt(); - graphicsMode = leis.readUInt(); - exScale = leis.readUInt(); - eyScale = leis.readUInt(); - - int recordSizeInt = -1; - if (recordSize < Integer.MAX_VALUE) { - recordSizeInt = (int)recordSize; - } else { - throw new RecordFormatException("can't have text length > Integer.MAX_VALUE"); - } - //guarantee to read the rest of the EMRTextObjectRecord - //emrtextbytes start after 7*4 bytes read above - byte[] emrTextBytes = new byte[recordSizeInt-(7*LittleEndian.INT_SIZE)]; - IOUtils.readFully(leis, emrTextBytes); - textObject = new EmrTextObject(emrTextBytes, getEncodingHint(), 20);//should be 28, but recordSizeInt has already subtracted 8 - return recordSize; - } - - protected Charset getEncodingHint() { - return null; - } - - /** - * - * To be implemented! We need to get the current character set - * from the current font for {@link ExtTextOutA}, - * which has to be tracked in the playback device. - * - * For {@link ExtTextOutW}, the charset is "UTF-16LE" - * - * @param charset the charset to be used to decode the character bytes - * @return text from this text element - * @throws IOException - */ - public String getText(Charset charset) throws IOException { - return textObject.getText(charset); - } - - /** - * - * @return the x offset for the EmrTextObject - */ - public long getX() { - return textObject.x; - } - - /** - * - * @return the y offset for the EmrTextObject - */ - public long getY() { - return textObject.y; - } - - public long getLeft() { - return left; - } - - public long getTop() { - return top; - } - - public long getRight() { - return right; - } - - public long getBottom() { - return bottom; - } - - public long getGraphicsMode() { - return graphicsMode; - } - - public long getExScale() { - return exScale; - } - - public long getEyScale() { - return eyScale; - } - - } - - public static class ExtTextOutW extends ExtTextOutA { - - @Override - public HemfRecordType getRecordType() { - return HemfRecordType.exttextoutw; - } - - @Override - protected Charset getEncodingHint() { - return UTF16LE; - } - - public String getText() throws IOException { - return getText(UTF16LE); - } - } - - /** - * Needs to be implemented. Couldn't find example. - */ - public static class PolyTextOutA extends UnimplementedHemfRecord { - - } - - /** - * Needs to be implemented. Couldn't find example. - */ - public static class PolyTextOutW extends UnimplementedHemfRecord { - - } - - public static class SetTextAlign extends UnimplementedHemfRecord { - } - - public static class SetTextColor extends UnimplementedHemfRecord { - } - - - public static class SetTextJustification extends UnimplementedHemfRecord { - - } - - private static class EmrTextObject { - long x; - long y; - int numChars; - byte[] rawTextBytes;//this stores _all_ of the bytes to the end of the EMRTextObject record. - //Because of potential variable length encodings, must - //carefully read only the numChars from this byte array. - - EmrTextObject(byte[] emrTextObjBytes, Charset charsetHint, int readSoFar) throws IOException { - - int offset = 0; - x = LittleEndian.getUInt(emrTextObjBytes, offset); offset+= LittleEndian.INT_SIZE; - y = LittleEndian.getUInt(emrTextObjBytes, offset); offset+= LittleEndian.INT_SIZE; - long numCharsLong = LittleEndian.getUInt(emrTextObjBytes, offset); offset += LittleEndian.INT_SIZE; - long offString = LittleEndian.getUInt(emrTextObjBytes, offset); offset += LittleEndian.INT_SIZE; - int start = (int)offString-offset-readSoFar; - - if (numCharsLong == 0) { - rawTextBytes = new byte[0]; - numChars = 0; - return; - } - if (numCharsLong > Integer.MAX_VALUE) { - throw new RecordFormatException("Number of characters can't be > Integer.MAX_VALUE"); - } - numChars = (int)numCharsLong; - rawTextBytes = new byte[emrTextObjBytes.length-start]; - System.arraycopy(emrTextObjBytes, start, rawTextBytes, 0, emrTextObjBytes.length-start); - } - - String getText(Charset charset) throws IOException { - StringBuilder sb = new StringBuilder(); - Reader r = null; - try { - r = new InputStreamReader(new ByteArrayInputStream(rawTextBytes), charset); - for (int i = 0; i < numChars; i++) { - sb.appendCodePoint(readCodePoint(r)); - } - } finally { - IOUtils.closeQuietly(r); - } - return sb.toString(); - } - - //TODO: move this to IOUtils? - private int readCodePoint(Reader r) throws IOException { - int c1 = r.read(); - if (c1 == -1) { - throw new EOFException("Tried to read beyond byte array"); - } - if (!Character.isHighSurrogate((char)c1)) { - return c1; - } - int c2 = r.read(); - if (c2 == -1) { - throw new EOFException("Tried to read beyond byte array"); - } - if (!Character.isLowSurrogate((char)c2)) { - throw new RecordFormatException("Expected low surrogate after high surrogate"); - } - return Character.toCodePoint((char)c1, (char)c2); - } - } - - -} diff --git a/src/scratchpad/src/org/apache/poi/hemf/record/UnimplementedHemfRecord.java b/src/scratchpad/src/org/apache/poi/hemf/record/UnimplementedHemfRecord.java deleted file mode 100644 index a951e0ec5..000000000 --- a/src/scratchpad/src/org/apache/poi/hemf/record/UnimplementedHemfRecord.java +++ /dev/null @@ -1,49 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hemf.record; - - -import java.io.IOException; - -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.Internal; -import org.apache.poi.util.LittleEndianInputStream; - -@Internal -public class UnimplementedHemfRecord implements HemfRecord { - - private long recordId; - public UnimplementedHemfRecord() { - - } - - @Override - public HemfRecordType getRecordType() { - return HemfRecordType.getById(recordId); - } - - @Override - public long init(LittleEndianInputStream leis, long recordId, long recordSize) throws IOException { - this.recordId = recordId; - long skipped = IOUtils.skipFully(leis, recordSize); - if (skipped < 0) { - throw new IOException("End of stream reached before record read"); - } - return skipped; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hmef/Attachment.java b/src/scratchpad/src/org/apache/poi/hmef/Attachment.java deleted file mode 100644 index 59c90a4dc..000000000 --- a/src/scratchpad/src/org/apache/poi/hmef/Attachment.java +++ /dev/null @@ -1,160 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hmef; - -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -import org.apache.poi.hmef.attribute.MAPIAttribute; -import org.apache.poi.hmef.attribute.MAPIStringAttribute; -import org.apache.poi.hmef.attribute.TNEFAttribute; -import org.apache.poi.hmef.attribute.TNEFDateAttribute; -import org.apache.poi.hmef.attribute.TNEFMAPIAttribute; -import org.apache.poi.hmef.attribute.TNEFProperty; -import org.apache.poi.hmef.attribute.TNEFStringAttribute; -import org.apache.poi.hsmf.datatypes.MAPIProperty; - - -/** - * An attachment within a {@link HMEFMessage}. Provides both helper - * methods to get at common parts and attributes of the attachment, - * and list methods to get all of them. - */ -public final class Attachment { - private final List attributes = new ArrayList(); - private final List mapiAttributes = new ArrayList(); - - protected void addAttribute(TNEFAttribute attr) { - attributes.add(attr); - - if(attr instanceof TNEFMAPIAttribute) { - TNEFMAPIAttribute tnefMAPI = (TNEFMAPIAttribute)attr; - mapiAttributes.addAll( tnefMAPI.getMAPIAttributes() ); - } - } - - /** - * Return the attachment attribute with the given ID, - * or null if there isn't one. - */ - public TNEFAttribute getAttribute(TNEFProperty id) { - for(TNEFAttribute attr : attributes) { - if(attr.getProperty() == id) { - return attr; - } - } - return null; - } - - /** - * Return the attachment MAPI Attribute with the given ID, - * or null if there isn't one. - */ - public MAPIAttribute getMAPIAttribute(MAPIProperty id) { - for(MAPIAttribute attr : mapiAttributes) { - if(attr.getProperty() == id) { - return attr; - } - } - return null; - } - - /** - * Returns all HMEF/TNEF attributes of the attachment, - * such as filename, icon and contents - */ - public List getAttributes() { - return attributes; - } - - /** - * Returns all MAPI attributes of the attachment, - * such as extension, encoding, size and position - */ - public List getMAPIAttributes() { - return mapiAttributes; - } - - - /** - * Return the string value of the mapi property, or null - * if it isn't set - */ - private String getString(MAPIProperty id) { - return MAPIStringAttribute.getAsString( getMAPIAttribute(id) ); - } - /** - * Returns the string value of the TNEF property, or - * null if it isn't set - */ - private String getString(TNEFProperty id) { - return TNEFStringAttribute.getAsString( getAttribute(id) ); - } - - /** - * Returns the short filename - */ - public String getFilename() { - return getString(TNEFProperty.ID_ATTACHTITLE); - } - /** - * Returns the long filename - */ - public String getLongFilename() { - return getString(MAPIProperty.ATTACH_LONG_FILENAME); - } - /** - * Returns the file extension - */ - public String getExtension() { - return getString(MAPIProperty.ATTACH_EXTENSION); - } - - /** - * Return when the file was last modified, if known. - */ - public Date getModifiedDate() { - return TNEFDateAttribute.getAsDate( - getAttribute(TNEFProperty.ID_ATTACHMODIFYDATE) - ); - } - - /** - * Returns the contents of the attachment. - * - * @throws IllegalArgumentException if there is no AttachmentData available in this Attachment - */ - public byte[] getContents() { - TNEFAttribute contents = getAttribute(TNEFProperty.ID_ATTACHDATA); - if(contents == null) { - throw new IllegalArgumentException("Attachment corrupt - no Data section"); - } - return contents.getData(); - } - - /** - * Returns the Meta File rendered representation - * of the attachment, or null if not set. - */ - public byte[] getRenderedMetaFile() { - TNEFAttribute meta = getAttribute(TNEFProperty.ID_ATTACHMETAFILE); - if(meta == null) return null; - return meta.getData(); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hmef/CompressedRTF.java b/src/scratchpad/src/org/apache/poi/hmef/CompressedRTF.java deleted file mode 100644 index ad38755a0..000000000 --- a/src/scratchpad/src/org/apache/poi/hmef/CompressedRTF.java +++ /dev/null @@ -1,127 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hmef; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.charset.Charset; - -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.LZWDecompresser; -import org.apache.poi.util.LittleEndian; - - -/** - * Within a {@link HMEFMessage}, the content is often - * stored in as RTF, but LZW compressed. This class - * handles decompressing it for you. - */ -public final class CompressedRTF extends LZWDecompresser { - public static final byte[] COMPRESSED_SIGNATURE = - new byte[] { (byte)'L', (byte)'Z', (byte)'F', (byte)'u' }; - public static final byte[] UNCOMPRESSED_SIGNATURE = - new byte[] { (byte)'M', (byte)'E', (byte)'L', (byte)'A' }; - public static final int COMPRESSED_SIGNATURE_INT = - LittleEndian.getInt(COMPRESSED_SIGNATURE); - public static final int UNCOMPRESSED_SIGNATURE_INT = - LittleEndian.getInt(UNCOMPRESSED_SIGNATURE); - - // The 4096 byte LZW dictionary is pre-loaded with some common - // RTF fragments. These come from RTFLIB32.LIB, which ships - // with older versions of Visual Studio or the EDK - public static final String LZW_RTF_PRELOAD = - "{\\rtf1\\ansi\\mac\\deff0\\deftab720{\\fonttbl;}{\\f0\\fnil \\froman \\fswiss " + - "\\fmodern \\fscript \\fdecor MS Sans SerifSymbolArialTimes New RomanCourier" + - "{\\colortbl\\red0\\green0\\blue0\n\r\\par \\pard\\plain\\f0\\fs20\\b\\i\\u\\tab\\tx"; - - private int compressedSize; - private int decompressedSize; - - public CompressedRTF() { - // Out flag has the normal meaning - // Length wise, we're 2 longer than we say, so the max len is 18 - // Endian wise, we're big endian, so 0x1234 is pos 0x123 - super(true, 2, true); - } - - /** - * Decompresses the whole of the compressed RTF - * stream, outputting the resulting RTF bytes. - * Note - will decompress any padding at the end of - * the input, if present, use {@link #getDeCompressedSize()} - * if you need to know how much of the result is - * real. (Padding may be up to 7 bytes). - */ - public void decompress(InputStream src, OutputStream res) throws IOException { - // Validate the header on the front of the RTF - compressedSize = LittleEndian.readInt(src); - decompressedSize = LittleEndian.readInt(src); - int compressionType = LittleEndian.readInt(src); - /* int dataCRC = */ LittleEndian.readInt(src); - - // TODO - Handle CRC checking on the output side - - // Do we need to do anything? - if(compressionType == UNCOMPRESSED_SIGNATURE_INT) { - // Nope, nothing fancy to do - IOUtils.copy(src, res); - } else if(compressionType == COMPRESSED_SIGNATURE_INT) { - // We need to decompress it below - } else { - throw new IllegalArgumentException("Invalid compression signature " + compressionType); - } - - // Have it processed - super.decompress(src, res); - } - - /** - * Returns how big the compressed version was. - */ - public int getCompressedSize() { - // Return the size less the header - return compressedSize - 12; - } - - /** - * Returns how big the decompressed version was. - */ - public int getDeCompressedSize() { - return decompressedSize; - } - - /** - * We use regular dictionary offsets, so no - * need to change anything - */ - @Override - protected int adjustDictionaryOffset(int offset) { - return offset; - } - - @Override - protected int populateDictionary(byte[] dict) { - // Copy in the RTF constants - byte[] preload = LZW_RTF_PRELOAD.getBytes(Charset.forName("US-ASCII")); - System.arraycopy(preload, 0, dict, 0, preload.length); - - // Start adding new codes after the constants - return preload.length; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hmef/HMEFMessage.java b/src/scratchpad/src/org/apache/poi/hmef/HMEFMessage.java deleted file mode 100644 index 5dd7a827f..000000000 --- a/src/scratchpad/src/org/apache/poi/hmef/HMEFMessage.java +++ /dev/null @@ -1,199 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hmef; - -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import org.apache.poi.hmef.attribute.MAPIAttribute; -import org.apache.poi.hmef.attribute.MAPIStringAttribute; -import org.apache.poi.hmef.attribute.TNEFAttribute; -import org.apache.poi.hmef.attribute.TNEFMAPIAttribute; -import org.apache.poi.hmef.attribute.TNEFProperty; -import org.apache.poi.hsmf.datatypes.MAPIProperty; -import org.apache.poi.util.LittleEndian; - -/** - * HMEF - Implementation of the Microsoft TNEF message - * encoding format (aka winmail.dat) - * See: - * http://support.microsoft.com/kb/241538 - * http://en.wikipedia.org/wiki/Transport_Neutral_Encapsulation_Format - * http://search.cpan.org/dist/Convert-TNEF/ - */ -public final class HMEFMessage { - public static final int HEADER_SIGNATURE = 0x223e9f78; - - @SuppressWarnings("unused") - private int fileId; - private final List messageAttributes = new ArrayList(); - private final List mapiAttributes = new ArrayList(); - private final List attachments = new ArrayList(); - - public HMEFMessage(InputStream inp) throws IOException { - try { - // Check the signature matches - int sig = LittleEndian.readInt(inp); - if (sig != HEADER_SIGNATURE) { - throw new IllegalArgumentException( - "TNEF signature not detected in file, " + - "expected " + HEADER_SIGNATURE + " but got " + sig - ); - } - - // Read the File ID - fileId = LittleEndian.readUShort(inp); - - // Now begin processing the contents - process(inp); - } finally { - inp.close(); - } - } - - private void process(InputStream inp) throws IOException { - int level; - do { - // Fetch the level - level = inp.read(); - - // Decide what to attach it to, based on the levels and IDs - switch (level) { - case TNEFProperty.LEVEL_MESSAGE: - processMessage(inp); - break; - case TNEFProperty.LEVEL_ATTACHMENT: - processAttachment(inp); - break; - // ignore trailing newline - case '\r': - case '\n': - case TNEFProperty.LEVEL_END_OF_FILE: - break; - default: - throw new IllegalStateException("Unhandled level " + level); - } - } while (level != TNEFProperty.LEVEL_END_OF_FILE); - } - - void processMessage(InputStream inp) throws IOException { - // Build the attribute - TNEFAttribute attr = TNEFAttribute.create(inp); - - messageAttributes.add(attr); - - if (attr instanceof TNEFMAPIAttribute) { - TNEFMAPIAttribute tnefMAPI = (TNEFMAPIAttribute) attr; - mapiAttributes.addAll(tnefMAPI.getMAPIAttributes()); - } - } - - void processAttachment(InputStream inp) throws IOException { - // Build the attribute - TNEFAttribute attr = TNEFAttribute.create(inp); - - // Previous attachment or a new one? - if (attachments.isEmpty() - || attr.getProperty() == TNEFProperty.ID_ATTACHRENDERDATA) { - attachments.add(new Attachment()); - } - - // Save the attribute for it - Attachment attach = attachments.get(attachments.size() - 1); - attach.addAttribute(attr); - } - - /** - * Returns all HMEF/TNEF attributes of the message. - * Note - In a typical message, most of the interesting properties - * are stored as {@link MAPIAttribute}s - see {@link #getMessageMAPIAttributes()} - */ - public List getMessageAttributes() { - return Collections.unmodifiableList(messageAttributes); - } - - /** - * Returns all MAPI attributes of the message. - * Note - A small number of HMEF/TNEF specific attributes normally - * apply to most messages, see {@link #getMessageAttributes()} - */ - public List getMessageMAPIAttributes() { - return Collections.unmodifiableList(mapiAttributes); - } - - /** - * Returns all the Attachments of the message. - */ - public List getAttachments() { - return Collections.unmodifiableList(attachments); - } - - /** - * Return the message attribute with the given ID, - * or null if there isn't one. - */ - public TNEFAttribute getMessageAttribute(TNEFProperty id) { - for (TNEFAttribute attr : messageAttributes) { - if (attr.getProperty() == id) { - return attr; - } - } - return null; - } - - /** - * Return the message MAPI Attribute with the given ID, - * or null if there isn't one. - */ - public MAPIAttribute getMessageMAPIAttribute(MAPIProperty id) { - for (MAPIAttribute attr : mapiAttributes) { - // Because of custom properties, match on ID not literal property object - if (attr.getProperty().id == id.id) { - return attr; - } - } - return null; - } - - /** - * Return the string value of the mapi property, or null - * if it isn't set - */ - private String getString(MAPIProperty id) { - return MAPIStringAttribute.getAsString( getMessageMAPIAttribute(id) ); - } - - /** - * Returns the Message Subject, or null if the mapi property - * for this isn't set - */ - public String getSubject() { - return getString(MAPIProperty.CONVERSATION_TOPIC); - } - - /** - * Returns the Message Body, as RTF, or null if the mapi property - * for this isn't set - */ - public String getBody() { - return getString(MAPIProperty.RTF_COMPRESSED); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hmef/attribute/MAPIAttribute.java b/src/scratchpad/src/org/apache/poi/hmef/attribute/MAPIAttribute.java deleted file mode 100644 index 84161f848..000000000 --- a/src/scratchpad/src/org/apache/poi/hmef/attribute/MAPIAttribute.java +++ /dev/null @@ -1,211 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hmef.attribute; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.hmef.Attachment; -import org.apache.poi.hmef.HMEFMessage; -import org.apache.poi.hsmf.datatypes.MAPIProperty; -import org.apache.poi.hsmf.datatypes.Types; -import org.apache.poi.hsmf.datatypes.Types.MAPIType; -import org.apache.poi.util.HexDump; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.StringUtil; - -/** - * A pure-MAPI attribute which applies to a {@link HMEFMessage} - * or one of its {@link Attachment}s. - */ -public class MAPIAttribute { - private final MAPIProperty property; - private final int type; - private final byte[] data; - - /** - * Constructs a single new attribute from - * the contents of the stream - */ - public MAPIAttribute(MAPIProperty property, int type, byte[] data) { - this.property = property; - this.type = type; - this.data = data.clone(); - } - - public MAPIProperty getProperty() { - return property; - } - - public int getType() { - return type; - } - - public byte[] getData() { - return data; - } - - public String toString() { - String hex; - if(data.length <= 16) { - hex = HexDump.toHex(data); - } else { - byte[] d = new byte[16]; - System.arraycopy(data, 0, d, 0, 16); - hex = HexDump.toHex(d); - hex = hex.substring(0, hex.length()-1) + ", ....]"; - } - - return property.toString() + " " + hex; - } - - /** - * Parses a MAPI Properties TNEF Attribute, and returns - * the list of MAPI Attributes contained within it - */ - public static List create(TNEFAttribute parent) throws IOException { - if(parent.getProperty() == TNEFProperty.ID_MAPIPROPERTIES) { - // Regular MAPI Properties, normally on the message - } - else if(parent.getProperty() == TNEFProperty.ID_ATTACHMENT) { - // MAPI Properties for an attachment - } - else { - // Something else, oh dear... - throw new IllegalArgumentException( - "Can only create from a MAPIProperty attribute, " + - "instead received a " + parent.getProperty() + " one" - ); - } - ByteArrayInputStream inp = new ByteArrayInputStream(parent.getData()); - - // First up, get the number of attributes - int count = LittleEndian.readInt(inp); - List attrs = new ArrayList(); - - // Now, read each one in in turn - for(int i=0; i= 0x8000 && id <= 0xFFFF) { - byte[] guid = new byte[16]; - IOUtils.readFully(inp, guid); - int mptype = LittleEndian.readInt(inp); - - // Get the name of it - String name; - if(mptype == 0) { - // It's based on a normal one - int mpid = LittleEndian.readInt(inp); - MAPIProperty base = MAPIProperty.get(mpid); - name = base.name; - } else { - // Custom name was stored - int mplen = LittleEndian.readInt(inp); - byte[] mpdata = new byte[mplen]; - IOUtils.readFully(inp, mpdata); - name = StringUtil.getFromUnicodeLE(mpdata, 0, (mplen/2)-1); - skipToBoundary(mplen, inp); - } - - // Now create - prop = MAPIProperty.createCustom(id, type, name); - } - if(prop == MAPIProperty.UNKNOWN) { - prop = MAPIProperty.createCustom(id, type, "(unknown " + Integer.toHexString(id) + ")"); - } - - // Now read in the value(s) - int values = 1; - if(isMV || isVL) { - values = LittleEndian.readInt(inp); - } - for(int j=0; j[MS-OXOMSG]: Email Object Protocol - * @see [MS-OXPROPS]: Exchange Server Protocols Master Property List - */ -public final class MAPIDateAttribute extends MAPIAttribute { - private final static POILogger logger = POILogFactory.getLogger(MAPIDateAttribute.class); - private Date data; - - /** - * Constructs a single new date attribute from the id, type, - * and the contents of the stream - */ - protected MAPIDateAttribute(MAPIProperty property, int type, byte[] data) { - super(property, type, data); - - // The value is a 64 bit Windows Filetime - this.data = Util.filetimeToDate( - LittleEndian.getLong(data, 0) - ); - } - - public Date getDate() { - return this.data; - } - - public String toString() { - DateFormatSymbols dfs = DateFormatSymbols.getInstance(Locale.ROOT); - DateFormat df = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", dfs); - df.setTimeZone(LocaleUtil.TIMEZONE_UTC); - return getProperty().toString() + " " + df.format(data); - } - - /** - * Returns the Date of a Attribute, converting as appropriate - */ - public static Date getAsDate(MAPIAttribute attr) { - if(attr == null) { - return null; - } - if(attr instanceof MAPIDateAttribute) { - return ((MAPIDateAttribute)attr).getDate(); - } - - logger.log(POILogger.WARN, "Warning, non date property found: " + attr.toString()); - return null; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hmef/attribute/MAPIRtfAttribute.java b/src/scratchpad/src/org/apache/poi/hmef/attribute/MAPIRtfAttribute.java deleted file mode 100644 index cd773838c..000000000 --- a/src/scratchpad/src/org/apache/poi/hmef/attribute/MAPIRtfAttribute.java +++ /dev/null @@ -1,78 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hmef.attribute; - -import java.io.ByteArrayInputStream; -import java.io.IOException; - -import org.apache.poi.hmef.Attachment; -import org.apache.poi.hmef.CompressedRTF; -import org.apache.poi.hmef.HMEFMessage; -import org.apache.poi.hsmf.datatypes.MAPIProperty; -import org.apache.poi.util.StringUtil; - -/** - * A pure-MAPI attribute holding RTF (compressed or not), which applies - * to a {@link HMEFMessage} or one of its {@link Attachment}s. - */ -public final class MAPIRtfAttribute extends MAPIAttribute { - private final byte[] decompressed; - private final String data; - - public MAPIRtfAttribute(MAPIProperty property, int type, byte[] data) throws IOException { - super(property, type, data); - - // Decompress it, removing any trailing padding as needed - CompressedRTF rtf = new CompressedRTF(); - byte[] tmp = rtf.decompress(new ByteArrayInputStream(data)); - if(tmp.length > rtf.getDeCompressedSize()) { - this.decompressed = new byte[rtf.getDeCompressedSize()]; - System.arraycopy(tmp, 0, decompressed, 0, decompressed.length); - } else { - this.decompressed = tmp; - } - - // Turn the RTF data into a more useful string - this.data = StringUtil.getFromCompressedUnicode(decompressed, 0, decompressed.length); - } - - /** - * Returns the original, compressed RTF - */ - public byte[] getRawData() { - return super.getData(); - } - - /** - * Returns the raw uncompressed RTF data - */ - public byte[] getData() { - return decompressed; - } - - /** - * Returns the uncompressed RTF as a string - */ - public String getDataString() { - return data; - } - - public String toString() { - return getProperty().toString() + " " + data; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hmef/attribute/MAPIStringAttribute.java b/src/scratchpad/src/org/apache/poi/hmef/attribute/MAPIStringAttribute.java deleted file mode 100644 index ef4e16b6e..000000000 --- a/src/scratchpad/src/org/apache/poi/hmef/attribute/MAPIStringAttribute.java +++ /dev/null @@ -1,83 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hmef.attribute; - -import java.nio.charset.Charset; - -import org.apache.poi.hmef.Attachment; -import org.apache.poi.hmef.HMEFMessage; -import org.apache.poi.hsmf.datatypes.MAPIProperty; -import org.apache.poi.hsmf.datatypes.Types; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.util.StringUtil; - -/** - * A pure-MAPI attribute holding a String, which applies - * to a {@link HMEFMessage} or one of its {@link Attachment}s. - */ -public final class MAPIStringAttribute extends MAPIAttribute { - private final static POILogger logger = POILogFactory.getLogger(MAPIStringAttribute.class); - private static final String CODEPAGE = "CP1252"; - private final String data; - - public MAPIStringAttribute(MAPIProperty property, int type, byte[] data) { - super(property, type, data); - - String tmpData = null; - if(type == Types.ASCII_STRING.getId()) { - tmpData = new String(data, Charset.forName(CODEPAGE)); - } else if(type == Types.UNICODE_STRING.getId()) { - tmpData = StringUtil.getFromUnicodeLE(data); - } else { - throw new IllegalArgumentException("Not a string type " + type); - } - - // Strip off the null terminator if present - if(tmpData.endsWith("\0")) { - tmpData = tmpData.substring(0, tmpData.length()-1); - } - this.data = tmpData; - } - - public String getDataString() { - return data; - } - - public String toString() { - return getProperty().toString() + " " + data; - } - - /** - * Returns the string of a Attribute, converting as appropriate - */ - public static String getAsString(MAPIAttribute attr) { - if(attr == null) { - return null; - } - if(attr instanceof MAPIStringAttribute) { - return ((MAPIStringAttribute)attr).getDataString(); - } - if(attr instanceof MAPIRtfAttribute) { - return ((MAPIRtfAttribute)attr).getDataString(); - } - - logger.log(POILogger.WARN, "Warning, non string property found: " + attr.toString()); - return null; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hmef/attribute/TNEFAttribute.java b/src/scratchpad/src/org/apache/poi/hmef/attribute/TNEFAttribute.java deleted file mode 100644 index af0ac3dcb..000000000 --- a/src/scratchpad/src/org/apache/poi/hmef/attribute/TNEFAttribute.java +++ /dev/null @@ -1,95 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hmef.attribute; - -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.hmef.Attachment; -import org.apache.poi.hmef.HMEFMessage; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.LittleEndian; - - -/** - * An attribute which applies to a {@link HMEFMessage} - * or one of its {@link Attachment}s. - * Note - the types and IDs differ from standard Outlook/MAPI - * ones, so we can't just re-use the HSMF ones. - */ -public class TNEFAttribute { - private final TNEFProperty property; - private final int type; - private final byte[] data; - private final int checksum; - - /** - * Constructs a single new attribute from the id, type, - * and the contents of the stream - */ - protected TNEFAttribute(int id, int type, InputStream inp) throws IOException { - this.type = type; - int length = LittleEndian.readInt(inp); - - property = TNEFProperty.getBest(id, type); - data = new byte[length]; - IOUtils.readFully(inp, data); - - checksum = LittleEndian.readUShort(inp); - } - - /** - * Creates a new TNEF Attribute by reading data from - * the stream within a {@link HMEFMessage} - */ - public static TNEFAttribute create(InputStream inp) throws IOException { - int id = LittleEndian.readUShort(inp); - int type = LittleEndian.readUShort(inp); - - // Create as appropriate - if(id == TNEFProperty.ID_MAPIPROPERTIES.id || - id == TNEFProperty.ID_ATTACHMENT.id) { - return new TNEFMAPIAttribute(id, type, inp); - } - if(type == TNEFProperty.TYPE_STRING || - type == TNEFProperty.TYPE_TEXT) { - return new TNEFStringAttribute(id, type, inp); - } - if(type == TNEFProperty.TYPE_DATE) { - return new TNEFDateAttribute(id, type, inp); - } - return new TNEFAttribute(id, type, inp); - } - - public TNEFProperty getProperty() { - return property; - } - - public int getType() { - return type; - } - - public byte[] getData() { - return data; - } - - public String toString() { - return "Attribute " + property.toString() + ", type=" + type + - ", data length=" + data.length; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hmef/attribute/TNEFDateAttribute.java b/src/scratchpad/src/org/apache/poi/hmef/attribute/TNEFDateAttribute.java deleted file mode 100644 index faedc4c7c..000000000 --- a/src/scratchpad/src/org/apache/poi/hmef/attribute/TNEFDateAttribute.java +++ /dev/null @@ -1,101 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hmef.attribute; - -import java.io.IOException; -import java.io.InputStream; -import java.text.DateFormat; -import java.text.DateFormatSymbols; -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.Date; -import java.util.Locale; - -import org.apache.poi.hmef.Attachment; -import org.apache.poi.hmef.HMEFMessage; -import org.apache.poi.hpsf.Util; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.LocaleUtil; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; - -/** - * A Date attribute which applies to a {@link HMEFMessage} - * or one of its {@link Attachment}s. - */ -public final class TNEFDateAttribute extends TNEFAttribute { - private final static POILogger logger = POILogFactory.getLogger(TNEFDateAttribute.class); - private Date data; - - /** - * Constructs a single new date attribute from the id, type, - * and the contents of the stream - */ - protected TNEFDateAttribute(int id, int type, InputStream inp) throws IOException { - super(id, type, inp); - - byte[] binData = getData(); - if(binData.length == 8) { - // The value is a 64 bit Windows Filetime - this.data = Util.filetimeToDate( - LittleEndian.getLong(getData(), 0) - ); - } else if(binData.length == 14) { - // It's the 7 date fields. We think it's in UTC... - Calendar c = LocaleUtil.getLocaleCalendar(LocaleUtil.TIMEZONE_UTC); - c.set(Calendar.YEAR, LittleEndian.getUShort(binData, 0)); - c.set(Calendar.MONTH, LittleEndian.getUShort(binData, 2) - 1); // Java months are 0 based! - c.set(Calendar.DAY_OF_MONTH, LittleEndian.getUShort(binData, 4)); - c.set(Calendar.HOUR_OF_DAY, LittleEndian.getUShort(binData, 6)); - c.set(Calendar.MINUTE, LittleEndian.getUShort(binData, 8)); - c.set(Calendar.SECOND, LittleEndian.getUShort(binData, 10)); - // The 7th field is day of week, which we don't require - c.clear(Calendar.MILLISECOND); // Not set in the file - this.data = c.getTime(); - } else { - throw new IllegalArgumentException("Invalid date, found " + binData.length + " bytes"); - } - } - - public Date getDate() { - return this.data; - } - - public String toString() { - DateFormatSymbols dfs = DateFormatSymbols.getInstance(Locale.ROOT); - DateFormat df = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", dfs); - df.setTimeZone(LocaleUtil.TIMEZONE_UTC); - return "Attribute " + getProperty().toString() + ", type=" + getType() + - ", date=" + df.format(data); - } - - /** - * Returns the Date of a Attribute, converting as appropriate - */ - public static Date getAsDate(TNEFAttribute attr) { - if(attr == null) { - return null; - } - if(attr instanceof TNEFDateAttribute) { - return ((TNEFDateAttribute)attr).getDate(); - } - - logger.log(POILogger.WARN, "Warning, non date property found: " + attr.toString()); - return null; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hmef/attribute/TNEFMAPIAttribute.java b/src/scratchpad/src/org/apache/poi/hmef/attribute/TNEFMAPIAttribute.java deleted file mode 100644 index 3144981fe..000000000 --- a/src/scratchpad/src/org/apache/poi/hmef/attribute/TNEFMAPIAttribute.java +++ /dev/null @@ -1,52 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hmef.attribute; - -import java.io.IOException; -import java.io.InputStream; -import java.util.List; - -import org.apache.poi.hmef.Attachment; -import org.apache.poi.hmef.HMEFMessage; - -/** - * A TNEF Attribute holding MAPI Attributes, which applies to a - * {@link HMEFMessage} or one of its {@link Attachment}s. - */ -public final class TNEFMAPIAttribute extends TNEFAttribute { - private final List attributes; - - /** - * Constructs a single new mapi containing attribute from the - * id, type, and the contents of the stream - */ - protected TNEFMAPIAttribute(int id, int type, InputStream inp) throws IOException { - super(id, type, inp); - - attributes = MAPIAttribute.create(this); - } - - public List getMAPIAttributes() { - return attributes; - } - - public String toString() { - return "Attribute " + getProperty().toString() + ", type=" + getType() + - ", " + attributes.size() + " MAPI Attributes"; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hmef/attribute/TNEFProperty.java b/src/scratchpad/src/org/apache/poi/hmef/attribute/TNEFProperty.java deleted file mode 100644 index de4d8a5fc..000000000 --- a/src/scratchpad/src/org/apache/poi/hmef/attribute/TNEFProperty.java +++ /dev/null @@ -1,216 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hmef.attribute; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * Holds the list of TNEF Attributes, and allows lookup - * by friendly name, ID and MAPI Property Name. - * - * Note - the types and IDs differ from standard Outlook/MAPI - * ones, so we can't just re-use the HSMF ones. - */ -public final class TNEFProperty { - private static Map> properties = new HashMap>(); - - // Types taken from http://msdn.microsoft.com/en-us/library/microsoft.exchange.data.contenttypes.tnef.tnefattributetype%28v=EXCHG.140%29.aspx - public static final int TYPE_TRIPLES = 0x0000; - public static final int TYPE_STRING = 0x0001; - public static final int TYPE_TEXT = 0x0002; - public static final int TYPE_DATE = 0x0003; - public static final int TYPE_SHORT = 0x0004; - public static final int TYPE_LONG = 0x0005; - public static final int TYPE_BYTE = 0x0006; - public static final int TYPE_WORD = 0x0007; - public static final int TYPE_DWORD = 0x0008; - public static final int TYPE_MAX = 0x0009; - - // Types taken from http://msdn.microsoft.com/en-us/library/microsoft.exchange.data.contenttypes.tnef.tnefpropertytype%28v=EXCHG.140%29.aspx - /** AppTime - application time value */ - public static final int PTYPE_APPTIME = 0x0007; - /** Binary - counted byte array */ - public static final int PTYPE_BINARY = 0x0102; - /** Boolean - 16-bit Boolean value. '0' is false. Non-zero is true */ - public static final int PTYPE_BOOLEAN = 0x000B; - /** ClassId - OLE GUID */ - public static final int PTYPE_CLASSID = 0x0048; - /** Currency - signed 64-bit integer that represents a base ten decimal with four digits to the right of the decimal point */ - public static final int PTYPE_CURRENCY = 0x0006; - /** Double - floating point double */ - public static final int PTYPE_DOUBLE = 0x0005; - /** Error - 32-bit error value */ - public static final int PTYPE_ERROR = 0x000A; - /** I2 - signed 16-bit value */ - public static final int PTYPE_I2 = 0x0002; - /** I8 - 8-byte signed integer */ - public static final int PTYPE_I8 = 0x0014; - /** Long - signed 32-bit value */ - public static final int PTYPE_LONG = 0x0003; - /** MultiValued - Value part contains multiple values */ - public static final int PTYPE_MULTIVALUED = 0x1000; - /** Null - NULL property value */ - public static final int PTYPE_NULL = 0x0001; - /** Object - embedded object in a property */ - public static final int PTYPE_OBJECT = 0x000D; - /** R4 - 4-byte floating point value */ - public static final int PTYPE_R4 = 0x0004; - /** String8 - null-terminated 8-bit character string */ - public static final int PTYPE_STRING8 = 0x001E; - /** SysTime - FILETIME 64-bit integer specifying the number of 100ns periods since Jan 1, 1601 */ - public static final int PTYPE_SYSTIME = 0x0040; - /** Unicode - null-terminated Unicode string */ - public static final int PTYPE_UNICODE = 0x001F; - /** Unspecified */ - public static final int PTYPE_UNSPECIFIED = 0x0000; - - - // Levels taken from http://msdn.microsoft.com/en-us/library/microsoft.exchange.data.contenttypes.tnef.tnefattributelevel%28v=EXCHG.140%29.aspx - public static final int LEVEL_MESSAGE = 0x01; - public static final int LEVEL_ATTACHMENT = 0x02; - public static final int LEVEL_END_OF_FILE = -0x01; - - // ID information taken from http://msdn.microsoft.com/en-us/library/microsoft.exchange.data.contenttypes.tnef.tnefattributetag%28v=EXCHG.140%29.aspx - public static final TNEFProperty ID_AIDOWNER = - new TNEFProperty(0x0008, TYPE_LONG, "AidOwner", "PR_OWNER_APPT_ID"); - public static final TNEFProperty ID_ATTACHCREATEDATE = - new TNEFProperty(0x8012, TYPE_DATE, "AttachCreateDate", "PR_CREATION_TIME"); - public static final TNEFProperty ID_ATTACHDATA = - new TNEFProperty(0x800F, TYPE_BYTE, "AttachData", "PR_ATTACH_DATA_BIN"); - public static final TNEFProperty ID_ATTACHMENT = - new TNEFProperty(0x9005, TYPE_BYTE, "Attachment", null); - public static final TNEFProperty ID_ATTACHMETAFILE = - new TNEFProperty(0x8011, TYPE_BYTE, "AttachMetaFile", "PR_ATTACH_RENDERING"); - public static final TNEFProperty ID_ATTACHMODIFYDATE = - new TNEFProperty(0x8013, TYPE_DATE, "AttachModifyDate", "PR_LAST_MODIFICATION_TIME"); - public static final TNEFProperty ID_ATTACHRENDERDATA = - new TNEFProperty(0x9002, TYPE_BYTE, "AttachRenderData", "attAttachRenddata"); - public static final TNEFProperty ID_ATTACHTITLE = - new TNEFProperty(0x8010, TYPE_STRING, "AttachTitle", "PR_ATTACH_FILENAME"); - public static final TNEFProperty ID_ATTACHTRANSPORTFILENAME = - new TNEFProperty(0x9001, TYPE_BYTE, "AttachTransportFilename", "PR_ATTACH_TRANSPORT_NAME"); - public static final TNEFProperty ID_BODY = - new TNEFProperty(0x800C, TYPE_TEXT, "Body", "PR_BODY"); - public static final TNEFProperty ID_CONVERSATIONID = - new TNEFProperty(0x800B, TYPE_STRING, "ConversationId", "PR_CONVERSATION_KEY"); - public static final TNEFProperty ID_DATEEND = - new TNEFProperty(0x0007, TYPE_DATE, "DateEnd", "PR_END_DATE"); - public static final TNEFProperty ID_DATEMODIFIED = - new TNEFProperty(0x8020, TYPE_DATE, "DateModified", "PR_LAST_MODIFICATION_TIME "); - public static final TNEFProperty ID_DATERECEIVED = - new TNEFProperty(0x8006, TYPE_DATE, "DateReceived", "PR_MESSAGE_DELIVERY_TIME "); - public static final TNEFProperty ID_DATESENT = - new TNEFProperty(0x8005, TYPE_DATE, "DateSent", "PR_CLIENT_SUBMIT_TIME "); - public static final TNEFProperty ID_DATESTART = - new TNEFProperty(0x0006, TYPE_DATE, "DateStart", "PR_START_DATE "); - public static final TNEFProperty ID_DELEGATE = - new TNEFProperty(0x0002, TYPE_BYTE, "Delegate", "PR_RCVD_REPRESENTING_xxx "); - public static final TNEFProperty ID_FROM = - new TNEFProperty(0x8000, TYPE_STRING, "From", "PR_SENDER_ENTRYID"); - public static final TNEFProperty ID_MAPIPROPERTIES = - new TNEFProperty(0x9003, TYPE_BYTE, "MapiProperties", null); - public static final TNEFProperty ID_MESSAGECLASS = - new TNEFProperty(0x8008, TYPE_WORD, "MessageClass", "PR_MESSAGE_CLASS "); - public static final TNEFProperty ID_MESSAGEID = - new TNEFProperty(0x8009, TYPE_STRING, "MessageId", "PR_SEARCH_KEY"); - public static final TNEFProperty ID_MESSAGESTATUS = - new TNEFProperty(0x8007, TYPE_BYTE, "MessageStatus", "PR_MESSAGE_FLAGS"); - public static final TNEFProperty ID_NULL = - new TNEFProperty(0x0000, -1, "Null", null); - public static final TNEFProperty ID_OEMCODEPAGE = - new TNEFProperty(0x9007, TYPE_BYTE, "OemCodepage", "AttOemCodepage"); - public static final TNEFProperty ID_ORIGINALMESSAGECLASS = - new TNEFProperty(0x0006, TYPE_WORD, "OriginalMessageClass", "PR_ORIG_MESSAGE_CLASS"); - public static final TNEFProperty ID_OWNER = - new TNEFProperty(0x0000, TYPE_BYTE, "Owner", "PR_RCVD_REPRESENTING_xxx"); - public static final TNEFProperty ID_PARENTID = - new TNEFProperty(0x800A, TYPE_STRING, "ParentId", "PR_PARENT_KEY"); - public static final TNEFProperty ID_PRIORITY = - new TNEFProperty(0x800D, TYPE_SHORT, "Priority", "PR_IMPORTANCE"); - public static final TNEFProperty ID_RECIPIENTTABLE = - new TNEFProperty(0x9004, TYPE_BYTE, "RecipientTable", "PR_MESSAGE_RECIPIENTS"); - public static final TNEFProperty ID_REQUESTRESPONSE = - new TNEFProperty(0x009, TYPE_SHORT, "RequestResponse", "PR_RESPONSE_REQUESTED"); - public static final TNEFProperty ID_SENTFOR = - new TNEFProperty(0x0001, TYPE_BYTE, "SentFor", "PR_SENT_REPRESENTING_xxx"); - public static final TNEFProperty ID_SUBJECT = - new TNEFProperty(0x8004, TYPE_STRING, "Subject", "PR_SUBJECT"); - public static final TNEFProperty ID_TNEFVERSION = - new TNEFProperty(0x9006, TYPE_DWORD, "TnefVersion", "attTnefVersion"); - public static final TNEFProperty ID_UNKNOWN = - new TNEFProperty(-1, -1, "Unknown", null); - - /** The TNEF Property ID */ - public final int id; - /** Usual Type */ - public final int usualType; - /** Property Name */ - public final String name; - /** Equivalent MAPI Property */ - public final String mapiProperty; - - private TNEFProperty(int id, int usualType, String name, String mapiProperty) { - this.id = id; - this.usualType = usualType; - this.name = name; - this.mapiProperty = mapiProperty; - - // Store it for lookup - if(! properties.containsKey(id)) { - properties.put(id, new ArrayList()); - } - properties.get(id).add(this); - } - - public static TNEFProperty getBest(int id, int type) { - List attrs = properties.get(id); - if(attrs == null) { - return ID_UNKNOWN; - } - - // If there's only one, it's easy - if(attrs.size() == 1) { - return attrs.get(0); - } - - // Try by type - for(TNEFProperty attr : attrs) { - if(attr.usualType == type) return attr; - } - - // Go for the first if we can't otherwise decide... - return attrs.get(0); - } - - public String toString() { - StringBuffer str = new StringBuffer(); - str.append(name); - str.append(" ["); - str.append(id); - str.append("]"); - if(mapiProperty != null) { - str.append(" ("); - str.append(mapiProperty); - str.append(")"); - } - return str.toString(); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hmef/attribute/TNEFStringAttribute.java b/src/scratchpad/src/org/apache/poi/hmef/attribute/TNEFStringAttribute.java deleted file mode 100644 index a63b0d12b..000000000 --- a/src/scratchpad/src/org/apache/poi/hmef/attribute/TNEFStringAttribute.java +++ /dev/null @@ -1,84 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hmef.attribute; - -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.hmef.Attachment; -import org.apache.poi.hmef.HMEFMessage; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.util.StringUtil; - -/** - * A String attribute which applies to a {@link HMEFMessage} - * or one of its {@link Attachment}s. - */ -public final class TNEFStringAttribute extends TNEFAttribute { - private final static POILogger logger = POILogFactory.getLogger(TNEFStringAttribute.class); - private String data; - - /** - * Constructs a single new string attribute from the id, type, - * and the contents of the stream - */ - protected TNEFStringAttribute(int id, int type, InputStream inp) throws IOException { - super(id, type, inp); - - String tmpData = null; - byte[] data = getData(); - if(getType() == TNEFProperty.TYPE_TEXT) { - tmpData = StringUtil.getFromUnicodeLE(data); - } else { - tmpData = StringUtil.getFromCompressedUnicode( - data, 0, data.length - ); - } - - // Strip off the null terminator if present - if(tmpData.endsWith("\0")) { - tmpData = tmpData.substring(0, tmpData.length()-1); - } - this.data = tmpData; - } - - public String getString() { - return this.data; - } - - public String toString() { - return "Attribute " + getProperty().toString() + ", type=" + getType() + - ", data=" + getString(); - } - - /** - * Returns the string of a Attribute, converting as appropriate - */ - public static String getAsString(TNEFAttribute attr) { - if(attr == null) { - return null; - } - if(attr instanceof TNEFStringAttribute) { - return ((TNEFStringAttribute)attr).getString(); - } - - logger.log(POILogger.WARN, "Warning, non string property found: " + attr.toString()); - return null; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hmef/dev/HMEFDumper.java b/src/scratchpad/src/org/apache/poi/hmef/dev/HMEFDumper.java deleted file mode 100644 index 2e64a9ab2..000000000 --- a/src/scratchpad/src/org/apache/poi/hmef/dev/HMEFDumper.java +++ /dev/null @@ -1,161 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hmef.dev; - -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.List; - -import org.apache.poi.hmef.HMEFMessage; -import org.apache.poi.hmef.attribute.MAPIAttribute; -import org.apache.poi.hmef.attribute.TNEFAttribute; -import org.apache.poi.hmef.attribute.TNEFDateAttribute; -import org.apache.poi.hmef.attribute.TNEFProperty; -import org.apache.poi.hmef.attribute.TNEFStringAttribute; -import org.apache.poi.util.HexDump; -import org.apache.poi.util.LittleEndian; - -/** - * Developer focused raw dumper - */ -public final class HMEFDumper { - public static void main(String[] args) throws Exception { - if(args.length < 1) { - throw new IllegalArgumentException("Filename must be given"); - } - - boolean truncatePropData = true; - for (String arg : args) { - if (arg.equalsIgnoreCase("--full")) { - truncatePropData = false; - continue; - } - - InputStream stream = new FileInputStream(arg); - try { - HMEFDumper dumper = new HMEFDumper(stream); - dumper.setTruncatePropertyData(truncatePropData); - dumper.dump(); - } finally { - stream.close(); - } - } - } - - private InputStream inp; - private boolean truncatePropertyData; - - public HMEFDumper(InputStream inp) throws IOException { - this.inp = inp; - - // Check the signature matches - int sig = LittleEndian.readInt(inp); - if(sig != HMEFMessage.HEADER_SIGNATURE) { - throw new IllegalArgumentException( - "TNEF signature not detected in file, " + - "expected " + HMEFMessage.HEADER_SIGNATURE + - " but got " + sig - ); - } - - // Skip over the File ID - LittleEndian.readUShort(inp); - } - - public void setTruncatePropertyData(boolean truncate) { - truncatePropertyData = truncate; - } - - private void dump() throws IOException { - int level; - int attachments = 0; - - while(true) { - // Fetch the level - level = inp.read(); - if(level == TNEFProperty.LEVEL_END_OF_FILE) { - break; - } - - // Build the attribute - TNEFAttribute attr = TNEFAttribute.create(inp); - - // Is it a new attachment? - if(level == TNEFProperty.LEVEL_ATTACHMENT && - attr.getProperty() == TNEFProperty.ID_ATTACHRENDERDATA) { - attachments++; - System.out.println(); - System.out.println("Attachment # " + attachments); - System.out.println(); - } - - // Print the attribute into - System.out.println( - "Level " + level + " : Type " + attr.getType() + - " : ID " + attr.getProperty().toString() - ); - - // Print the contents - String indent = " "; - - if(attr instanceof TNEFStringAttribute) { - System.out.println(indent + indent + indent + ((TNEFStringAttribute)attr).getString()); - } - if(attr instanceof TNEFDateAttribute) { - System.out.println(indent + indent + indent + ((TNEFDateAttribute)attr).getDate()); - } - - System.out.println(indent + "Data of length " + attr.getData().length); - if(attr.getData().length > 0) { - int len = attr.getData().length; - if(truncatePropertyData) { - len = Math.min( attr.getData().length, 48 ); - } - - int loops = len/16; - if(loops == 0) loops = 1; - - for(int i=0; i attrs = MAPIAttribute.create(attr); - for(MAPIAttribute ma : attrs) { - System.out.println(indent + indent + ma); - } - System.out.println(); - } - } - } -} diff --git a/src/scratchpad/src/org/apache/poi/hmef/extractor/HMEFContentsExtractor.java b/src/scratchpad/src/org/apache/poi/hmef/extractor/HMEFContentsExtractor.java deleted file mode 100644 index e945cbae4..000000000 --- a/src/scratchpad/src/org/apache/poi/hmef/extractor/HMEFContentsExtractor.java +++ /dev/null @@ -1,167 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hmef.extractor; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; - -import org.apache.poi.hmef.Attachment; -import org.apache.poi.hmef.HMEFMessage; -import org.apache.poi.hmef.attribute.MAPIAttribute; -import org.apache.poi.hmef.attribute.MAPIRtfAttribute; -import org.apache.poi.hmef.attribute.MAPIStringAttribute; -import org.apache.poi.hsmf.datatypes.MAPIProperty; -import org.apache.poi.hsmf.datatypes.Types; -import org.apache.poi.util.StringUtil; - -/** - * A utility for extracting out the message body, and all attachments - * from a HMEF/TNEF/winmail.dat file - */ -public final class HMEFContentsExtractor { - /** - * Usage: HMEFContentsExtractor <filename> <output dir> - */ - public static void main(String[] args) throws IOException { - if(args.length < 2) { - System.err.println("Use:"); - System.err.println(" HMEFContentsExtractor "); - System.err.println(""); - System.err.println(""); - System.err.println("Where is the winmail.dat file to extract,"); - System.err.println(" and is where to place the extracted files"); - System.exit(2); - } - - final String filename = args[0]; - final String outputDir = args[1]; - - HMEFContentsExtractor ext = new HMEFContentsExtractor(new File(filename)); - - File dir = new File(outputDir); - File rtf = new File(dir, "message.rtf"); - if(! dir.exists()) { - throw new FileNotFoundException("Output directory " + dir.getName() + " not found"); - } - - System.out.println("Extracting..."); - ext.extractMessageBody(rtf); - ext.extractAttachments(dir); - System.out.println("Extraction completed"); - } - - private final HMEFMessage message; - public HMEFContentsExtractor(File filename) throws IOException { - this(new HMEFMessage(new FileInputStream(filename))); - } - public HMEFContentsExtractor(HMEFMessage message) { - this.message = message; - } - - /** - * Extracts the RTF message body to the supplied file - */ - public void extractMessageBody(File dest) throws IOException { - MAPIAttribute body = getBodyAttribute(); - if (body == null) { - System.err.println("No message body found, " + dest + " not created"); - return; - } - if (body instanceof MAPIStringAttribute) { - String name = dest.toString(); - if (name.endsWith(".rtf")) { - name = name.substring(0, name.length()-4); - } - dest = new File(name + ".txt"); - } - - OutputStream fout = new FileOutputStream(dest); - try { - if (body instanceof MAPIStringAttribute) { - // Save in a predictable encoding, not raw bytes - String text = ((MAPIStringAttribute)body).getDataString(); - fout.write(text.getBytes(StringUtil.UTF8)); - } else { - // Save the raw bytes, should be raw RTF - fout.write(body.getData()); - } - } finally { - fout.close(); - } - } - - protected MAPIAttribute getBodyAttribute() { - MAPIAttribute body = message.getMessageMAPIAttribute(MAPIProperty.RTF_COMPRESSED); - if (body != null) return body; - - // See bug #59786 - we'd really like a test file to confirm if this - // is the right properties + if this is truely general or not! - MAPIProperty uncompressedBody = - MAPIProperty.createCustom(0x3fd9, Types.ASCII_STRING, "Uncompressed Body"); - // Return this uncompressed one, or null if that isn't their either - return message.getMessageMAPIAttribute(uncompressedBody); - } - - /** - * Extracts the RTF message body to the supplied stream. If there is no - * RTF message body, nothing will be written to the stream, but no - * errors or exceptions will be raised. - */ - public void extractMessageBody(OutputStream out) throws IOException { - MAPIRtfAttribute body = (MAPIRtfAttribute) - message.getMessageMAPIAttribute(MAPIProperty.RTF_COMPRESSED); - if (body != null) { - out.write(body.getData()); - } - } - - /** - * Extracts all the message attachments to the supplied directory - */ - public void extractAttachments(File dir) throws IOException { - int count = 0; - for(Attachment att : message.getAttachments()) { - count++; - - // Decide what to call it - String filename = att.getLongFilename(); - if(filename == null || filename.length() == 0) { - filename = att.getFilename(); - } - if(filename == null || filename.length() == 0) { - filename = "attachment" + count; - if(att.getExtension() != null) { - filename += att.getExtension(); - } - } - - // Save it - File file = new File(dir, filename); - OutputStream fout = new FileOutputStream(file); - try { - fout.write( att.getContents() ); - } finally { - fout.close(); - } - } - } -} diff --git a/src/scratchpad/src/org/apache/poi/hpbf/HPBFDocument.java b/src/scratchpad/src/org/apache/poi/hpbf/HPBFDocument.java deleted file mode 100644 index 764fa2150..000000000 --- a/src/scratchpad/src/org/apache/poi/hpbf/HPBFDocument.java +++ /dev/null @@ -1,85 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hpbf; - -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.POIReadOnlyDocument; -import org.apache.poi.hpbf.model.EscherDelayStm; -import org.apache.poi.hpbf.model.EscherStm; -import org.apache.poi.hpbf.model.MainContents; -import org.apache.poi.hpbf.model.QuillContents; -import org.apache.poi.poifs.filesystem.DirectoryNode; -import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; - -/** - * This class provides the basic functionality - * for HPBF, our implementation of the publisher - * file format. - */ -public final class HPBFDocument extends POIReadOnlyDocument { - private MainContents mainContents; - private QuillContents quillContents; - private EscherStm escherStm; - private EscherDelayStm escherDelayStm; - - /** - * Opens a new publisher document - */ - public HPBFDocument(POIFSFileSystem fs) throws IOException { - this(fs.getRoot()); - } - public HPBFDocument(NPOIFSFileSystem fs) throws IOException { - this(fs.getRoot()); - } - public HPBFDocument(InputStream inp) throws IOException { - this(new NPOIFSFileSystem(inp)); - } - - /** - * Opens an embedded publisher document, - * at the given directory. - */ - public HPBFDocument(DirectoryNode dir) throws IOException { - super(dir); - - // Go looking for our interesting child - // streams - mainContents = new MainContents(dir); - quillContents = new QuillContents(dir); - - // Now the Escher bits - escherStm = new EscherStm(dir); - escherDelayStm = new EscherDelayStm(dir); - } - - public MainContents getMainContents() { - return mainContents; - } - public QuillContents getQuillContents() { - return quillContents; - } - public EscherStm getEscherStm() { - return escherStm; - } - public EscherDelayStm getEscherDelayStm() { - return escherDelayStm; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hpbf/dev/HPBFDumper.java b/src/scratchpad/src/org/apache/poi/hpbf/dev/HPBFDumper.java deleted file mode 100644 index 48ad50973..000000000 --- a/src/scratchpad/src/org/apache/poi/hpbf/dev/HPBFDumper.java +++ /dev/null @@ -1,354 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hpbf.dev; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.ddf.DefaultEscherRecordFactory; -import org.apache.poi.ddf.EscherRecord; -import org.apache.poi.poifs.filesystem.DirectoryNode; -import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.LocaleUtil; -import org.apache.poi.util.StringUtil; - -/** - * For dumping out the contents of HPBF (Publisher) - * files, while we try to figure out how they're - * constructed. - */ -public final class HPBFDumper { - private NPOIFSFileSystem fs; - public HPBFDumper(NPOIFSFileSystem fs) { - this.fs = fs; - } - - @SuppressWarnings("resource") - public HPBFDumper(InputStream inp) throws IOException { - this(new NPOIFSFileSystem(inp)); - } - - private static byte[] getData(DirectoryNode dir, String name) throws IOException { - // Grab the document stream - InputStream is = dir.createDocumentInputStream(name); - byte[] d = IOUtils.toByteArray(is); - is.close(); - - // All done - return d; - } - - /** - * Dumps out the given number of bytes as hex, - * two chars - */ - private String dumpBytes(byte[] data, int offset, int len) { - StringBuffer ret = new StringBuffer(); - for(int i=0; i"); - System.exit(1); - } - HPBFDumper dump = new HPBFDumper(new NPOIFSFileSystem(new File(args[0]))); - - System.out.println("Dumping " + args[0]); - dump.dumpContents(); - dump.dumpEnvelope(); - dump.dumpEscher(); - dump.dump001CompObj(dump.fs.getRoot()); - dump.dumpQuill(); - - // Still to go: - // (0x03)Internal - // Objects - } - - /** - * Dump out the escher parts of the file. - * Escher -> EscherStm and EscherDelayStm - */ - public void dumpEscher() throws IOException { - DirectoryNode escherDir = (DirectoryNode) - fs.getRoot().getEntry("Escher"); - - dumpEscherStm(escherDir); - dumpEscherDelayStm(escherDir); - } - private void dumpEscherStream(byte[] data) { - DefaultEscherRecordFactory erf = - new DefaultEscherRecordFactory(); - - // Dump - int left = data.length; - while(left > 0) { - EscherRecord er = erf.createRecord(data, 0); - er.fillFields(data, 0, erf); - left -= er.getRecordSize(); - - System.out.println(er.toString()); - } - } - protected void dumpEscherStm(DirectoryNode escherDir) throws IOException { - byte[] data = getData(escherDir, "EscherStm"); - System.out.println(""); - System.out.println("EscherStm - " + data.length + " bytes long:"); - if(data.length > 0) - dumpEscherStream(data); - } - protected void dumpEscherDelayStm(DirectoryNode escherDir) throws IOException { - byte[] data = getData(escherDir, "EscherDelayStm"); - System.out.println(""); - System.out.println("EscherDelayStm - " + data.length + " bytes long:"); - if(data.length > 0) - dumpEscherStream(data); - } - - public void dumpEnvelope() throws IOException { - byte[] data = getData(fs.getRoot(), "Envelope"); - - System.out.println(""); - System.out.println("Envelope - " + data.length + " bytes long:"); - } - - public void dumpContents() throws IOException { - byte[] data = getData(fs.getRoot(), "Contents"); - - System.out.println(""); - System.out.println("Contents - " + data.length + " bytes long:"); - - // 8 bytes, always seems to be - // E8 AC 2C 00 E8 03 05 01 - // E8 AC 2C 00 E8 03 05 01 - - // 4 bytes - size of contents - // 13/15 00 00 01 - - // .... - - // E8 03 08 08 0C 20 03 00 00 00 00 88 16 00 00 00 ..... .......... - - // 01 18 27 00 03 20 00 00 E8 03 08 08 0C 20 03 00 ..'.. ....... .. - - // 01 18 30 00 03 20 00 00 - // E8 03 06 08 07 08 08 08 09 10 01 00 0C 20 04 00 - // 00 00 00 88 1E 00 00 00 - - // 01 18 31 00 03 20 00 00 - // E8 03 06 08 07 08 08 08 09 10 01 00 0C 20 04 00 - // 00 00 00 88 1E 00 00 00 - - // 01 18 32 00 03 20 00 00 - // E8 03 06 08 07 08 08 08 09 10 01 00 0C 20 04 00 - // 00 00 00 88 1E 00 00 00 - } - - public void dumpCONTENTSraw(DirectoryNode dir) throws IOException { - byte[] data = getData(dir, "CONTENTS"); - - System.out.println(""); - System.out.println("CONTENTS - " + data.length + " bytes long:"); - - // Between the start and 0x200 we have - // CHNKINK(space) + 24 bytes - // 0x1800 - // TEXT + 6 bytes - // TEXT + 8 bytes - // 0x1800 - // STSH + 6 bytes - // STSH + 8 bytes - // 0x1800 - // STSH + 6 bytes - // STSH + 8 bytes - // but towards 0x200 the pattern may - // break down a little bit - - // After the second of a given type, - // it seems to be 4 bytes giving the start, - // then 4 bytes giving the length, then - // 18 00 - System.out.println( - new String(data, 0, 8, LocaleUtil.CHARSET_1252) + - dumpBytes(data, 8, 0x20-8) - ); - - int pos = 0x20; - boolean sixNotEight = true; - while(pos < 0x200) { - if(sixNotEight) { - System.out.println( - dumpBytes(data, pos, 2) - ); - pos += 2; - } - String text = new String(data, pos, 4, LocaleUtil.CHARSET_1252); - int blen = 8; - if(sixNotEight) - blen = 6; - System.out.println( - text + " " + dumpBytes(data, pos+4, blen) - ); - - pos += 4 + blen; - sixNotEight = ! sixNotEight; - } - - // Text from 0x200 onwards until we get - // to \r(00)\n(00)(00)(00) - int textStop = -1; - for(int i=0x200; i 0) { - int len = (textStop - 0x200) / 2; - System.out.println(""); - System.out.println( - StringUtil.getFromUnicodeLE(data, 0x200, len) - ); - } - - // The font list comes slightly later - - // The hyperlinks may come before the fonts, - // or slightly in front - } - public void dumpCONTENTSguessed(DirectoryNode dir) throws IOException { - byte[] data = getData(dir, "CONTENTS"); - - System.out.println(""); - System.out.println("CONTENTS - " + data.length + " bytes long:"); - - String[] startType = new String[20]; - String[] endType = new String[20]; - int[] optA = new int[20]; - int[] optB = new int[20]; - int[] optC = new int[20]; - int[] from = new int[20]; - int[] len = new int[20]; - - for(int i=0; i<20; i++) { - int offset = 0x20 + i*24; - if(data[offset] == 0x18 && data[offset+1] == 0x00) { - // Has data - startType[i] = new String(data, offset+2, 4, LocaleUtil.CHARSET_1252); - optA[i] = LittleEndian.getUShort(data, offset+6); - optB[i] = LittleEndian.getUShort(data, offset+8); - optC[i] = LittleEndian.getUShort(data, offset+10); - endType[i] = new String(data, offset+12, 4, LocaleUtil.CHARSET_1252); - from[i] = (int)LittleEndian.getUInt(data, offset+16); - len[i] = (int)LittleEndian.getUInt(data, offset+20); - } else { - // Doesn't have data - } - } - - String text = StringUtil.getFromUnicodeLE( - data, from[0], len[0]/2 - ); - - // Dump - for(int i=0; i<20; i++) { - String num = Integer.toString(i); - if(i < 10) { - num = "0" + i; - } - System.out.print(num + " "); - - if(startType[i] == null) { - System.out.println("(not present)"); - } else { - System.out.println( - "\t" + - startType[i] + " " + - optA[i] + " " + - optB[i] + " " + - optC[i] - ); - System.out.println( - "\t" + - endType[i] + " " + - "from: " + - Integer.toHexString(from[i]) + - " (" + from[i] + ")" + - ", len: " + - Integer.toHexString(len[i]) + - " (" + len[i] + ")" - ); - } - } - - // Text - System.out.println(""); - System.out.println("TEXT:"); - System.out.println(text); - System.out.println(""); - - // All the others - for(int i=0; i<20; i++) { - if(startType[i] == null) { - continue; - } - int start = from[i]; - - System.out.println( - startType[i] + " -> " + endType[i] + - " @ " + Integer.toHexString(start) + - " (" + start + ")" - ); - System.out.println("\t" + dumpBytes(data, start, 4)); - System.out.println("\t" + dumpBytes(data, start+4, 4)); - System.out.println("\t" + dumpBytes(data, start+8, 4)); - System.out.println("\t(etc)"); - } - } - - protected void dump001CompObj(DirectoryNode dir) { - // TODO - } - - public void dumpQuill() throws IOException { - DirectoryNode quillDir = (DirectoryNode) - fs.getRoot().getEntry("Quill"); - DirectoryNode quillSubDir = (DirectoryNode) - quillDir.getEntry("QuillSub"); - - dump001CompObj(quillSubDir); - dumpCONTENTSraw(quillSubDir); - dumpCONTENTSguessed(quillSubDir); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hpbf/dev/PLCDumper.java b/src/scratchpad/src/org/apache/poi/hpbf/dev/PLCDumper.java deleted file mode 100644 index 7625a08b8..000000000 --- a/src/scratchpad/src/org/apache/poi/hpbf/dev/PLCDumper.java +++ /dev/null @@ -1,84 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hpbf.dev; - -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.hpbf.HPBFDocument; -import org.apache.poi.hpbf.model.QuillContents; -import org.apache.poi.hpbf.model.qcbits.QCBit; -import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; -import org.apache.poi.util.HexDump; - -/** - * For dumping out the PLC contents of QC Bits of a - * HPBF (Publisher) file, while we try to figure out - * what the format of them is. - */ -public final class PLCDumper { - private HPBFDocument doc; - private QuillContents qc; - - public PLCDumper(HPBFDocument hpbfDoc) { - doc = hpbfDoc; - qc = doc.getQuillContents(); - } - public PLCDumper(NPOIFSFileSystem fs) throws IOException { - this(new HPBFDocument(fs)); - } - public PLCDumper(InputStream inp) throws IOException { - this(new NPOIFSFileSystem(inp)); - } - - public static void main(String[] args) throws Exception { - if(args.length < 1) { - System.err.println("Use:"); - System.err.println(" PLCDumper "); - System.exit(1); - } - PLCDumper dump = new PLCDumper( - new FileInputStream(args[0]) - ); - - System.out.println("Dumping " + args[0]); - dump.dumpPLC(); - } - - private void dumpPLC() { - QCBit[] bits = qc.getBits(); - - for(int i=0; i\n"); - } - } - } - } - - // Get more text - // TODO - - return text.toString(); - } - - - public static void main(String[] args) throws Exception { - if(args.length == 0) { - System.err.println("Use:"); - System.err.println(" PublisherTextExtractor "); - } - - for(int i=0; i ec = new ArrayList(); - byte data[] = getData(); - int left = data.length; - while(left > 0) { - EscherRecord er = erf.createRecord(data, 0); - er.fillFields(data, 0, erf); - left -= er.getRecordSize(); - - ec.add(er); - } - - records = ec.toArray(new EscherRecord[ec.size()]); - } - - public EscherRecord[] getEscherRecords() { - return records; - } - - /** - * Serialises our Escher children back - * into bytes. - */ - protected void generateData() { - int size = 0; - for(int i=0; i QuillSub -> CONTENTS - */ -public final class QuillContents extends HPBFPart { - private static final String[] PATH = { "Quill", "QuillSub", "CONTENTS", }; - private QCBit[] bits; - - public QuillContents(DirectoryNode baseDir) throws IOException { - super(baseDir, PATH); - - // Now parse the first 512 bytes, and produce - // all our bits - byte data[] = getData(); - - // Check first 8 bytes - String f8 = new String(data, 0, 8, LocaleUtil.CHARSET_1252); - if(! f8.equals("CHNKINK ")) { - throw new IllegalArgumentException("Expecting 'CHNKINK ' but was '"+f8+"'"); - } - // Ignore the next 24, for now at least - - // Now, parse all our QC Bits - bits = new QCBit[20]; - for(int i=0; i<20; i++) { - int offset = 0x20 + i*24; - if(data[offset] == 0x18 && data[offset+1] == 0x00) { - // Has some data - String thingType = new String(data, offset+2, 4, LocaleUtil.CHARSET_1252); - int optA = LittleEndian.getUShort(data, offset+6); - int optB = LittleEndian.getUShort(data, offset+8); - int optC = LittleEndian.getUShort(data, offset+10); - String bitType = new String(data, offset+12, 4, LocaleUtil.CHARSET_1252); - int from = (int)LittleEndian.getUInt(data, offset+16); - int len = (int)LittleEndian.getUInt(data, offset+20); - - byte[] bitData = new byte[len]; - System.arraycopy(data, from, bitData, 0, len); - - // Create - if(bitType.equals("TEXT")) { - bits[i] = new QCTextBit(thingType, bitType, bitData); - } else if(bitType.equals("PLC ")) { - bits[i] = QCPLCBit.createQCPLCBit(thingType, bitType, bitData); - } else { - bits[i] = new UnknownQCBit(thingType, bitType, bitData); - } - bits[i].setOptA(optA); - bits[i].setOptB(optB); - bits[i].setOptC(optC); - bits[i].setDataOffset(from); - } else { - // Doesn't have data - } - } - } - - public QCBit[] getBits() { - return bits; - } - - protected void generateData() { - // TODO - throw new IllegalStateException("Not done yet!"); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hpbf/model/qcbits/QCBit.java b/src/scratchpad/src/org/apache/poi/hpbf/model/qcbits/QCBit.java deleted file mode 100644 index 5dd2a079f..000000000 --- a/src/scratchpad/src/org/apache/poi/hpbf/model/qcbits/QCBit.java +++ /dev/null @@ -1,86 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hpbf.model.qcbits; - -/** - * Parent of all Quill CONTENTS bits - */ -public abstract class QCBit { - private String thingType; - private String bitType; - private byte[] data; - - private int optA; - private int optB; - private int optC; - - private int dataOffset; - - public QCBit(String thingType, String bitType, byte[] data) { - this.thingType = thingType; - this.bitType = bitType; - this.data = data.clone(); - } - - /** - * Returns the type of the thing, eg TEXT, FONT - * or TOKN - */ - public String getThingType() { return thingType; } - /** - * Returns the type of the bit data, eg TEXT - * or PLC - */ - public String getBitType() { return bitType; } - public final byte[] getData() { return data; } - protected final void setData(byte data[]) { - this.data = data.clone(); - } - - public int getOptA() { - return optA; - } - public void setOptA(int optA) { - this.optA = optA; - } - - public int getOptB() { - return optB; - } - public void setOptB(int optB) { - this.optB = optB; - } - - public int getOptC() { - return optC; - } - public void setOptC(int optC) { - this.optC = optC; - } - - public int getDataOffset() { - return dataOffset; - } - public void setDataOffset(int offset) { - this.dataOffset = offset; - } - - public int getLength() { - return data.length; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hpbf/model/qcbits/QCPLCBit.java b/src/scratchpad/src/org/apache/poi/hpbf/model/qcbits/QCPLCBit.java deleted file mode 100644 index 29426cda7..000000000 --- a/src/scratchpad/src/org/apache/poi/hpbf/model/qcbits/QCPLCBit.java +++ /dev/null @@ -1,306 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hpbf.model.qcbits; - -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.StringUtil; - - -/** - * A "PLC " (PLC) based bit of Quill Contents. The exact - * format is determined by the type of the PLCs. - */ -public abstract class QCPLCBit extends QCBit { - private int numberOfPLCs; - private int typeOfPLCS; - /** - * The data which goes before the main PLC entries. - * This is apparently always made up of 2 byte - * un-signed ints.. - */ - private int[] preData; - /** The first value of each PLC, normally 4 bytes */ - private long[] plcValA; - /** The second value of each PLC, normally 4 bytes */ - private long[] plcValB; - - - private QCPLCBit(String thingType, String bitType, byte[] data) { - super(thingType, bitType, data); - - // First four bytes are the number - numberOfPLCs = (int)LittleEndian.getUInt(data, 0); - - // Next four bytes are the type - typeOfPLCS = (int)LittleEndian.getUInt(data, 4); - - // Init the arrays that we can - plcValA = new long[numberOfPLCs]; - plcValB = new long[numberOfPLCs]; - } - - - - public int getNumberOfPLCs() { - return numberOfPLCs; - } - public int getTypeOfPLCS() { - return typeOfPLCS; - } - - public int[] getPreData() { - return preData; - } - - public long[] getPlcValA() { - return plcValA; - } - public long[] getPlcValB() { - return plcValB; - } - - final void setPreData(int preData[]) { - this.preData = preData.clone(); - } - - final void setPlcValA(long[] plcValA) { - this.plcValA = plcValA.clone(); - } - - final void setPlcValB(long[] plcValB) { - this.plcValB = plcValB.clone(); - } - - - - public static QCPLCBit createQCPLCBit(String thingType, String bitType, byte[] data) { - // Grab the type - int type = (int)LittleEndian.getUInt(data, 4); - switch(type) { - case 0: - return new Type0(thingType, bitType, data); - case 4: - return new Type4(thingType, bitType, data); - case 8: - return new Type8(thingType, bitType, data); - case 12: // 0xc - return new Type12(thingType, bitType, data); - default: - throw new IllegalArgumentException("Sorry, I don't know how to deal with PLCs of type " + type); - } - } - - - /** - * Type 0 seem to be somewhat rare. They have 8 bytes of pre-data, - * then 2x 2 byte values. - */ - public static class Type0 extends QCPLCBit { - private Type0(String thingType, String bitType, byte[] data) { - super(thingType, bitType, data); - - // Grab our 4x pre-data - int preData[] = { - LittleEndian.getUShort(data, 8+0), - LittleEndian.getUShort(data, 8+2), - LittleEndian.getUShort(data, 8+4), - LittleEndian.getUShort(data, 8+6) - }; - setPreData(preData); - - // And grab the 2 byte values - int cntPlcs = getNumberOfPLCs(); - long plcValA[] = new long[cntPlcs], plcValB[] = new long[cntPlcs]; - for(int i=0; i= 2) { - until = twoStartsAt + (cntPlcs-2)*threePlusIncrement; - } - - long plcValA[] = new long[(until-at)/2]; - long plcValB[] = new long[0]; - for(int i=0; i=0 ) { - out.write(chunk,0,count); - } - inflater.close(); - return out.toByteArray(); - } catch (IOException e){ - throw new HSLFException(e); - } - } - - @Override - public void setData(byte[] data) throws IOException { - byte[] compressed = compress(data, 0, data.length); - - ImageHeaderEMF nHeader = new ImageHeaderEMF(data, 0); - - Header header = new Header(); - header.setWmfSize(data.length); - header.setBounds(nHeader.getBounds()); - Dimension nDim = nHeader.getSize(); - header.setDimension(new Dimension(Units.toEMU(nDim.getWidth()), Units.toEMU(nDim.getHeight()))); - header.setZipSize(compressed.length); - - byte[] checksum = getChecksum(data); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - out.write(checksum); - if (getUIDInstanceCount() == 2) { - out.write(checksum); - } - header.write(out); - out.write(compressed); - - setRawData(out.toByteArray()); - } - - @Override - public PictureType getType(){ - return PictureType.EMF; - } - - /** - * EMF signature is {@code 0x3D40} or {@code 0x3D50} - * - * @return EMF signature ({@code 0x3D40} or {@code 0x3D50}) - */ - public int getSignature(){ - return (getUIDInstanceCount() == 1 ? 0x3D40 : 0x3D50); - } - - /** - * Sets the EMF signature - either {@code 0x3D40} or {@code 0x3D50} - */ - public void setSignature(int signature) { - switch (signature) { - case 0x3D40: - setUIDInstanceCount(1); - break; - case 0x3D50: - setUIDInstanceCount(2); - break; - default: - throw new IllegalArgumentException(signature+" is not a valid instance/signature value for EMF"); - } - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/blip/JPEG.java b/src/scratchpad/src/org/apache/poi/hslf/blip/JPEG.java deleted file mode 100644 index 08ba6b73e..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/blip/JPEG.java +++ /dev/null @@ -1,79 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.blip; - - -/** - * Represents a JPEG picture data in a PPT file - */ -public final class JPEG extends Bitmap { - - public enum ColorSpace { rgb, cymk } - - private ColorSpace colorSpace = ColorSpace.rgb; - - @Override - public PictureType getType(){ - return PictureType.JPEG; - } - - public ColorSpace getColorSpace() { - return colorSpace; - } - - public void setColorSpace(ColorSpace colorSpace) { - this.colorSpace = colorSpace; - } - - /** - * JPEG signature is one of {@code 0x46A0, 0x46B0, 0x6E20, 0x6E30} - * - * @return JPEG signature ({@code 0x46A0, 0x46B0, 0x6E20, 0x6E30}) - */ - public int getSignature(){ - return (colorSpace == ColorSpace.rgb) - ? (getUIDInstanceCount() == 1 ? 0x46A0 : 0x46B0) - : (getUIDInstanceCount() == 1 ? 0x6E20 : 0x6E30); - } - - /** - * Sets the PICT signature - either {@code 0x5420} or {@code 0x5430} - */ - public void setSignature(int signature) { - switch (signature) { - case 0x46A0: - setUIDInstanceCount(1); - colorSpace = ColorSpace.rgb; - break; - case 0x46B0: - setUIDInstanceCount(2); - colorSpace = ColorSpace.rgb; - break; - case 0x6E20: - setUIDInstanceCount(1); - colorSpace = ColorSpace.cymk; - break; - case 0x6E30: - setUIDInstanceCount(2); - colorSpace = ColorSpace.cymk; - break; - default: - throw new IllegalArgumentException(signature+" is not a valid instance/signature value for JPEG"); - } - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/blip/Metafile.java b/src/scratchpad/src/org/apache/poi/hslf/blip/Metafile.java deleted file mode 100644 index 88d8a6198..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/blip/Metafile.java +++ /dev/null @@ -1,163 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.blip; - -import java.awt.Dimension; -import java.awt.Rectangle; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.util.zip.DeflaterOutputStream; - -import org.apache.poi.hslf.usermodel.HSLFPictureData; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.Units; - -/** - * Represents a metafile picture which can be one of the following types: EMF, WMF, or PICT. - * A metafile is stored compressed using the ZIP deflate/inflate algorithm. - * - * @author Yegor Kozlov - */ -public abstract class Metafile extends HSLFPictureData { - - /** - * A structure which represents a 34-byte header preceding the compressed metafile data - * - * @author Yegor Kozlov - */ - public static class Header{ - - /** - * size of the original file - */ - private int wmfsize; - - /** - * Boundary of the metafile drawing commands - */ - private final Rectangle bounds = new Rectangle(); - - /** - * Size of the metafile in EMUs - */ - private final Dimension size = new Dimension(); - - /** - * size of the compressed metafile data - */ - private int zipsize; - - /** - * Reserved. Always 0. - */ - private int compression = 0; - - /** - * Reserved. Always 254. - */ - private int filter = 254; - - public void read(byte[] data, int offset){ - int pos = offset; - wmfsize = LittleEndian.getInt(data, pos); pos += LittleEndian.INT_SIZE; - - int left = LittleEndian.getInt(data, pos); pos += LittleEndian.INT_SIZE; - int top = LittleEndian.getInt(data, pos); pos += LittleEndian.INT_SIZE; - int right = LittleEndian.getInt(data, pos); pos += LittleEndian.INT_SIZE; - int bottom = LittleEndian.getInt(data, pos); pos += LittleEndian.INT_SIZE; - - bounds.setBounds(left, top, right-left, bottom-top); - int width = LittleEndian.getInt(data, pos); pos += LittleEndian.INT_SIZE; - int height = LittleEndian.getInt(data, pos); pos += LittleEndian.INT_SIZE; - - size.setSize(width, height); - - zipsize = LittleEndian.getInt(data, pos); pos += LittleEndian.INT_SIZE; - - compression = LittleEndian.getUByte(data, pos); pos++; - filter = LittleEndian.getUByte(data, pos); pos++; - } - - public void write(OutputStream out) throws IOException { - byte[] header = new byte[34]; - int pos = 0; - LittleEndian.putInt(header, pos, wmfsize); pos += LittleEndian.INT_SIZE; //hmf - - LittleEndian.putInt(header, pos, bounds.x); pos += LittleEndian.INT_SIZE; //left - LittleEndian.putInt(header, pos, bounds.y); pos += LittleEndian.INT_SIZE; //top - LittleEndian.putInt(header, pos, bounds.x + bounds.width); pos += LittleEndian.INT_SIZE; //right - LittleEndian.putInt(header, pos, bounds.y + bounds.height); pos += LittleEndian.INT_SIZE; //bottom - LittleEndian.putInt(header, pos, size.width); pos += LittleEndian.INT_SIZE; //inch - LittleEndian.putInt(header, pos, size.height); pos += LittleEndian.INT_SIZE; //inch - LittleEndian.putInt(header, pos, zipsize); pos += LittleEndian.INT_SIZE; //inch - - header[pos] = 0; pos ++; - header[pos] = (byte)filter; pos ++; - - out.write(header); - } - - public int getSize(){ - return 34; - } - - public int getWmfSize() { - return wmfsize; - } - - protected void setWmfSize(int wmfSize) { - this.wmfsize = wmfSize; - } - - protected void setZipSize(int zipSize) { - this.zipsize = zipSize; - } - - public Rectangle getBounds() { - return (Rectangle)bounds.clone(); - } - - protected void setBounds(Rectangle bounds) { - this.bounds.setBounds(bounds); - } - - protected void setDimension(Dimension size) { - this.size.setSize(size); - } - } - - protected static byte[] compress(byte[] bytes, int offset, int length) throws IOException { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - DeflaterOutputStream deflater = new DeflaterOutputStream( out ); - deflater.write(bytes, offset, length); - deflater.close(); - return out.toByteArray(); - } - - @Override - public Dimension getImageDimension() { - int prefixLen = 16*getUIDInstanceCount(); - Header header = new Header(); - header.read(getRawData(), prefixLen); - return new Dimension( - (int)Math.round(Units.toPoints((long)header.size.getWidth())), - (int)Math.round(Units.toPoints((long)header.size.getHeight())) - ); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/blip/PICT.java b/src/scratchpad/src/org/apache/poi/hslf/blip/PICT.java deleted file mode 100644 index df55f4c68..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/blip/PICT.java +++ /dev/null @@ -1,169 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.blip; - -import java.awt.Dimension; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.EOFException; -import java.io.IOException; -import java.util.zip.InflaterInputStream; - -import org.apache.poi.hslf.exceptions.HSLFException; -import org.apache.poi.sl.image.ImageHeaderPICT; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.util.Units; - -/** - * Represents Macintosh PICT picture data. - */ -public final class PICT extends Metafile { - private static final POILogger LOG = POILogFactory.getLogger(PICT.class); - - - @Override - public byte[] getData(){ - byte[] rawdata = getRawData(); - try { - byte[] macheader = new byte[512]; - ByteArrayOutputStream out = new ByteArrayOutputStream(); - out.write(macheader); - int pos = CHECKSUM_SIZE*getUIDInstanceCount(); - byte[] pict = read(rawdata, pos); - out.write(pict); - return out.toByteArray(); - } catch (IOException e){ - throw new HSLFException(e); - } - } - - private byte[] read(byte[] data, int pos) throws IOException { - ByteArrayInputStream bis = new ByteArrayInputStream(data); - Header header = new Header(); - header.read(data, pos); - long bs_exp = (long)pos + header.getSize(); - long bs_act = bis.skip(bs_exp); - if (bs_exp != bs_act) { - throw new EOFException(); - } - byte[] chunk = new byte[4096]; - ByteArrayOutputStream out = new ByteArrayOutputStream(header.getWmfSize()); - InflaterInputStream inflater = new InflaterInputStream( bis ); - try { - int count; - while ((count = inflater.read(chunk)) >=0 ) { - out.write(chunk,0,count); - // PICT zip-stream can be erroneous, so we clear the array to determine - // the maximum of read bytes, after the inflater crashed - bytefill(chunk, (byte)0); - } - } catch (Exception e) { - int lastLen; - for (lastLen=chunk.length-1; lastLen>=0 && chunk[lastLen] == 0; lastLen--); - if (++lastLen > 0) { - if (header.getWmfSize() > out.size()) { - // sometimes the wmfsize is smaller than the amount of already successfully read bytes - // in this case we take the lastLen as-is, otherwise we truncate it to the given size - lastLen = Math.min(lastLen, header.getWmfSize() - out.size()); - } - out.write(chunk,0,lastLen); - } - // End of picture marker for PICT is 0x00 0xFF - LOG.log(POILogger.ERROR, "PICT zip-stream is invalid, read as much as possible. Uncompressed length of header: "+header.getWmfSize()+" / Read bytes: "+out.size(), e); - } finally { - inflater.close(); - } - return out.toByteArray(); - } - - @Override - public void setData(byte[] data) throws IOException { - // skip the first 512 bytes - they are MAC specific crap - final int nOffset = ImageHeaderPICT.PICT_HEADER_OFFSET; - ImageHeaderPICT nHeader = new ImageHeaderPICT(data, nOffset); - - Header header = new Header(); - int wmfSize = data.length - nOffset; - header.setWmfSize(wmfSize); - byte[] compressed = compress(data, nOffset, wmfSize); - header.setZipSize(compressed.length); - header.setBounds(nHeader.getBounds()); - Dimension nDim = nHeader.getSize(); - header.setDimension(new Dimension(Units.toEMU(nDim.getWidth()), Units.toEMU(nDim.getHeight()))); - - byte[] checksum = getChecksum(data); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - out.write(checksum); - if (getUIDInstanceCount() == 2) { - out.write(checksum); - } - header.write(out); - out.write(compressed); - - setRawData(out.toByteArray()); - } - - @Override - public PictureType getType(){ - return PictureType.PICT; - } - - /** - * PICT signature is {@code 0x5420} or {@code 0x5430} - * - * @return PICT signature ({@code 0x5420} or {@code 0x5430}) - */ - public int getSignature(){ - return (getUIDInstanceCount() == 1 ? 0x5420 : 0x5430); - } - - /** - * Sets the PICT signature - either {@code 0x5420} or {@code 0x5430} - */ - public void setSignature(int signature) { - switch (signature) { - case 0x5420: - setUIDInstanceCount(1); - break; - case 0x5430: - setUIDInstanceCount(2); - break; - default: - throw new IllegalArgumentException(signature+" is not a valid instance/signature value for PICT"); - } - } - - - /* - * initialize a smaller piece of the array and use the System.arraycopy - * call to fill in the rest of the array in an expanding binary fashion - */ - private static void bytefill(byte[] array, byte value) { - // http://stackoverflow.com/questions/9128737/fastest-way-to-set-all-values-of-an-array - int len = array.length; - - if (len > 0){ - array[0] = value; - } - - for (int i = 1; i < len; i += i) { - System.arraycopy(array, 0, array, i, ((len - i) < i) ? (len - i) : i); - } - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/blip/PNG.java b/src/scratchpad/src/org/apache/poi/hslf/blip/PNG.java deleted file mode 100644 index f2abc4068..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/blip/PNG.java +++ /dev/null @@ -1,71 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.blip; - -import org.apache.poi.util.PngUtils; - -/** - * Represents a PNG picture data in a PPT file - */ -public final class PNG extends Bitmap { - - @Override - public byte[] getData() { - byte[] data = super.getData(); - - //PNG created on MAC may have a 16-byte prefix which prevents successful reading. - //Just cut it off!. - if (PngUtils.matchesPngHeader(data, 16)) { - byte[] png = new byte[data.length-16]; - System.arraycopy(data, 16, png, 0, png.length); - data = png; - } - - return data; - } - - @Override - public PictureType getType(){ - return PictureType.PNG; - } - - /** - * PNG signature is {@code 0x6E00} or {@code 0x6E10} - * - * @return PNG signature ({@code 0x6E00} or {@code 0x6E10}) - */ - public int getSignature(){ - return (getUIDInstanceCount() == 1 ? 0x6E00 : 0x6E10); - } - - /** - * Sets the PNG signature - either {@code 0x6E00} or {@code 0x6E10} - */ - public void setSignature(int signature) { - switch (signature) { - case 0x6E00: - setUIDInstanceCount(1); - break; - case 0x6E10: - setUIDInstanceCount(2); - break; - default: - throw new IllegalArgumentException(signature+" is not a valid instance/signature value for PNG"); - } - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/blip/WMF.java b/src/scratchpad/src/org/apache/poi/hslf/blip/WMF.java deleted file mode 100644 index 8f02df41d..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/blip/WMF.java +++ /dev/null @@ -1,118 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.blip; - -import java.awt.Dimension; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.zip.InflaterInputStream; - -import org.apache.poi.hslf.exceptions.HSLFException; -import org.apache.poi.sl.image.ImageHeaderWMF; -import org.apache.poi.util.Units; - -/** - * Represents a WMF (Windows Metafile) picture data. - */ -public final class WMF extends Metafile { - - @Override - public byte[] getData(){ - try { - byte[] rawdata = getRawData(); - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - InputStream is = new ByteArrayInputStream( rawdata ); - Header header = new Header(); - header.read(rawdata, CHECKSUM_SIZE*getUIDInstanceCount()); - long len = is.skip(header.getSize() + (long)CHECKSUM_SIZE*getUIDInstanceCount()); - assert(len == header.getSize() + CHECKSUM_SIZE*getUIDInstanceCount()); - - ImageHeaderWMF aldus = new ImageHeaderWMF(header.getBounds()); - aldus.write(out); - - InflaterInputStream inflater = new InflaterInputStream( is ); - byte[] chunk = new byte[4096]; - int count; - while ((count = inflater.read(chunk)) >=0 ) { - out.write(chunk,0,count); - } - inflater.close(); - return out.toByteArray(); - } catch (IOException e){ - throw new HSLFException(e); - } - } - - @Override - public void setData(byte[] data) throws IOException { - int pos = 0; - ImageHeaderWMF nHeader = new ImageHeaderWMF(data, pos); - pos += nHeader.getLength(); - - byte[] compressed = compress(data, pos, data.length-pos); - - Header header = new Header(); - header.setWmfSize(data.length - nHeader.getLength()); - header.setBounds(nHeader.getBounds()); - Dimension nDim = nHeader.getSize(); - header.setDimension(new Dimension(Units.toEMU(nDim.getWidth()), Units.toEMU(nDim.getHeight()))); - header.setZipSize(compressed.length); - - byte[] checksum = getChecksum(data); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - out.write(checksum); - if (getUIDInstanceCount() == 2) { - out.write(checksum); - } - header.write(out); - out.write(compressed); - - setRawData(out.toByteArray()); - } - - @Override - public PictureType getType(){ - return PictureType.WMF; - } - - /** - * WMF signature is either {@code 0x2160} or {@code 0x2170} - */ - public int getSignature(){ - return (getUIDInstanceCount() == 1 ? 0x2160 : 0x2170); - } - - /** - * Sets the WMF signature - either {@code 0x2160} or {@code 0x2170} - */ - public void setSignature(int signature) { - switch (signature) { - case 0x2160: - setUIDInstanceCount(1); - break; - case 0x2170: - setUIDInstanceCount(2); - break; - default: - throw new IllegalArgumentException(signature+" is not a valid instance/signature value for WMF"); - } - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/dev/PPDrawingTextListing.java b/src/scratchpad/src/org/apache/poi/hslf/dev/PPDrawingTextListing.java deleted file mode 100644 index 380f9003b..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/dev/PPDrawingTextListing.java +++ /dev/null @@ -1,89 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.dev; - -import java.io.IOException; - -import org.apache.poi.hslf.record.EscherTextboxWrapper; -import org.apache.poi.hslf.record.PPDrawing; -import org.apache.poi.hslf.record.Record; -import org.apache.poi.hslf.record.TextBytesAtom; -import org.apache.poi.hslf.record.TextCharsAtom; -import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl; - - -/** - * Uses record level code to locate PPDrawing entries. - * Having found them, it sees if they have DDF Textbox records, and if so, - * searches those for text. Prints out any text it finds - */ -public final class PPDrawingTextListing { - public static void main(String[] args) throws IOException { - if(args.length < 1) { - System.err.println("Need to give a filename"); - System.exit(1); - } - - HSLFSlideShowImpl ss = new HSLFSlideShowImpl(args[0]); - - // Find PPDrawings at any second level position - Record[] records = ss.getRecords(); - for(int i=0; iWriter
    to write out - * @throws java.io.IOException - */ - public void dump(Writer outWriter) throws IOException { - this.out = outWriter; - - int padding = 0; - write(out, "" + CR, padding); - padding++; - if (pictstream != null){ - write(out, "" + CR, padding); - dumpPictures(pictstream, padding); - write(out, "" + CR, padding); - } - //dump the structure of the powerpoint document - write(out, "" + CR, padding); - padding++; - dump(docstream, 0, docstream.length, padding); - padding--; - write(out, "" + CR, padding); - padding--; - write(out, "", padding); - } - - /** - * Dump a part of the document stream into XML - * @param data PPT binary data - * @param offset offset from the beginning of the document - * @param length of the document - * @param padding used for formatting results - * @throws java.io.IOException - */ - public void dump(byte[] data, int offset, int length, int padding) throws IOException { - int pos = offset; - while (pos <= (offset + length - HEADER_SIZE)){ - if (pos < 0) { - break; - } - - //read record header - int info = LittleEndian.getUShort(data, pos); - pos += LittleEndian.SHORT_SIZE; - int type = LittleEndian.getUShort(data, pos); - pos += LittleEndian.SHORT_SIZE; - int size = (int)LittleEndian.getUInt(data, pos); - pos += LittleEndian.INT_SIZE; - - //get name of the record by type - String recname = RecordTypes.forTypeID(type).name(); - write(out, "<"+recname + " info=\""+info+"\" type=\""+type+"\" size=\""+size+"\" offset=\""+(pos-8)+"\"", padding); - if (hexHeader){ - out.write(" header=\""); - dump(out, data, pos-8, 8, 0, false); - out.write("\""); - } - out.write(">" + CR); - padding++; - //this check works both for Escher and PowerPoint records - boolean isContainer = (info & 0x000F) == 0x000F; - if (isContainer) { - //continue to dump child records - dump(data, pos, size, padding); - } else { - //dump first 100 bytes of the atom data - dump(out, data, pos, Math.min(size, data.length-pos), padding, true); - } - padding--; - write(out, "" + CR, padding); - - pos += size; - } - } - - /** - * Dumps the Pictures OLE stream into XML. - * - * @param data from the Pictures OLE data stream - * @param padding - * @throws java.io.IOException - */ - public void dumpPictures(byte[] data, int padding) throws IOException { - int pos = 0; - while (pos < data.length) { - byte[] header = new byte[PICT_HEADER_SIZE]; - - System.arraycopy(data, pos, header, 0, header.length); - int size = LittleEndian.getInt(header, 4) - 17; - byte[] pictdata = new byte[size]; - System.arraycopy(data, pos + PICT_HEADER_SIZE, pictdata, 0, pictdata.length); - pos += PICT_HEADER_SIZE + size; - - padding++; - write(out, "" + CR, padding); - padding++; - write(out, "
    " + CR, padding); - dump(out, header, 0, header.length, padding, true); - write(out, "
    " + CR, padding); - write(out, "" + CR, padding); - dump(out, pictdata, 0, Math.min(pictdata.length, 100), padding, true); - write(out, "" + CR, padding); - padding--; - write(out, "
    " + CR, padding); - padding--; - - } - } - - public static void main(String[] args) throws Exception { - if (args.length == 0){ - System.out.println( - "Usage: PPTXMLDump (options) pptfile\n" + - "Where options include:\n" + - " -f write output to .xml file in the current directory" - ); - return; - } - boolean outFile = false; - for (int i = 0; i < args.length; i++){ - - if (args[i].startsWith("-")) { - if ("-f".equals(args[i])){ - //write ouput to a file - outFile = true; - } - } else { - File ppt = new File(args[i]); - PPTXMLDump dump = new PPTXMLDump(ppt); - System.out.println("Dumping " + args[i]); - - if (outFile){ - FileOutputStream fos = new FileOutputStream(ppt.getName() + ".xml"); - OutputStreamWriter out = new OutputStreamWriter(fos, Charset.forName("UTF8")); - dump.dump(out); - out.close(); - } else { - StringWriter out = new StringWriter(); - dump.dump(out); - System.out.println(out.toString()); - } - } - - } - } - - - /** - * write a string to out with the specified padding - */ - private static void write(Writer out, String str, int padding) throws IOException { - for (int i = 0; i < padding; i++) out.write(" "); - out.write(str); - } - - private String getPictureType(byte[] header){ - String type; - int meta = LittleEndian.getUShort(header, 0); - - switch(meta){ - case 0x46A0: type = "jpeg"; break; - case 0x2160: type = "wmf"; break; - case 0x6E00: type = "png"; break; - default: type = "unknown"; break; - } - return type; - } - - /** - * dump binary data to out with the specified padding - */ - private static void dump(Writer out, byte[] data, int offset, int length, int padding, boolean nl) throws IOException { - int linesize = 25; - for (int i = 0; i < padding; i++) out.write(" "); - int i; - for (i = offset; i < (offset + length); i++) { - int c = data[i]; - out.write((char) hexval[(c & 0xF0) >> 4]); - out.write((char) hexval[(c & 0x0F) >> 0]); - out.write(' '); - if((i+1-offset) % linesize == 0 && i != (offset + length-1)) { - out.write(CR); - for (int j = 0; j < padding; j++) out.write(" "); - } - } - if(nl && length > 0)out.write(CR); - } - - private static final byte hexval[] = - {(byte) '0', (byte) '1', (byte) '2', (byte) '3', - (byte) '4', (byte) '5', (byte) '6', (byte) '7', - (byte) '8', (byte) '9', (byte) 'A', (byte) 'B', - (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F'}; - -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/dev/SLWTListing.java b/src/scratchpad/src/org/apache/poi/hslf/dev/SLWTListing.java deleted file mode 100644 index ff42ce0a4..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/dev/SLWTListing.java +++ /dev/null @@ -1,93 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.dev; - -import java.io.IOException; - -import org.apache.poi.hslf.record.Document; -import org.apache.poi.hslf.record.Record; -import org.apache.poi.hslf.record.RecordTypes; -import org.apache.poi.hslf.record.SlideListWithText; -import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl; - -/** - * Uses record level code to Documents. - * Having found them, it sees if they have any SlideListWithTexts, - * and reports how many, and what sorts of things they contain - */ -public final class SLWTListing { - public static void main(String[] args) throws IOException { - if(args.length < 1) { - System.err.println("Need to give a filename"); - System.exit(1); - } - - HSLFSlideShowImpl ss = new HSLFSlideShowImpl(args[0]); - - // Find the documents, and then their SLWT - Record[] records = ss.getRecords(); - for(int i=0; i 3) { - System.err.println("** Warning: Shouldn't have more than 3!"); - } - - // Check the SLWTs contain what we'd expect - for(int j=0; j 0) { - System.err.println(" ** SLWT " + j + " had " + numSAS + " SlideAtomSets! (expected 0)"); - } - } - - // Report the first 5 children, to give a flavour - int upTo = 5; - if(children.length < 5) { upTo = children.length; } - for(int k=0; k sheetOffsets = pph.getSlideLocationsLookup(); - for(int j=0; j"); - return; - } - - String filename = args[0]; - if(args.length > 1) { - filename = args[1]; - } - - NPOIFSFileSystem poifs = new NPOIFSFileSystem(new File(filename)); - SlideShowDumper foo = new SlideShowDumper(poifs, System.out); - poifs.close(); - - if(args.length > 1) { - if(args[0].equalsIgnoreCase("-escher")) { - foo.setDDFEscher(true); - } else { - foo.setBasicEscher(true); - } - } - - foo.printDump(); - } - - /** - * Constructs a Powerpoint dump from a POIFS Filesystem. Parses the - * document and dumps out the contents - * - * @param filesystem the POIFS FileSystem to read from - * @throws IOException if there is a problem while parsing the document. - */ - public SlideShowDumper(NPOIFSFileSystem filesystem, PrintStream out) throws IOException { - // Grab the document stream - InputStream is = filesystem.createDocumentInputStream("PowerPoint Document"); - docstream = IOUtils.toByteArray(is); - is.close(); - this.out = out; - } - - /** - * Control dumping of any Escher records found - should DDF be used? - */ - public void setDDFEscher(boolean grok) { - ddfEscher = grok; - basicEscher = !(grok); - } - - /** - * Control dumping of any Escher records found - should our built in - * basic groker be used? - */ - public void setBasicEscher(boolean grok) { - basicEscher = grok; - ddfEscher = !(grok); - } - - public void printDump() throws IOException { - // The format of records in a powerpoint file are: - // - // - // - // If it has a zero length, following it will be another record - // - // If it has a length, depending on its type it may have children or data - // If it has children, these will follow straight away - // > - // If it has data, this will come straigh after, and run for the length - // - // All lengths given exclude the 8 byte record header - // (Data records are known as Atoms) - - // Document should start with: - // 0F 00 E8 03 ## ## ## ## - // (type 1000 = document, info 00 0f is normal, rest is document length) - // 01 00 E9 03 28 00 00 00 - // (type 1001 = document atom, info 00 01 normal, 28 bytes long) - - // When parsing a document, look to see if you know about that type - // of the current record. If you know it's a type that has children, - // process the record's data area looking for more records - // If you know about the type and it doesn't have children, either do - // something with the data (eg TextRun) or skip over it - // Otherwise, check the first byte. If you do a BINARY_AND on it with - // 0x0f (15) and get back 0x0f, you know it has children. Otherwise - // it doesn't - - walkTree(0,0,docstream.length); -} - -public void walkTree(int depth, int startPos, int maxLen) throws IOException { - int pos = startPos; - int endPos = startPos + maxLen; - final String ind = (depth == 0) ? "%1$s" : "%1$"+depth+"s"; - while(pos <= endPos - 8) { - long type = LittleEndian.getUShort(docstream,pos+2); - long len = LittleEndian.getUInt(docstream,pos+4); - byte opt = docstream[pos]; - - String fmt = ind+"At position %2$d (%2$04x): type is %3$d (%3$04x), len is %4$d (%4$04x)"; - out.println(String.format(Locale.ROOT, fmt, "", pos, type, len)); - - // See if we know about the type of it - String recordName = RecordTypes.forTypeID((short)type).name(); - - // Jump over header, and think about going on more - pos += 8; - out.println(String.format(Locale.ROOT, ind+"That's a %2$s", "", recordName)); - - // Now check if it's a container or not - int container = opt & 0x0f; - - // BinaryTagData seems to contain records, but it - // isn't tagged as doing so. Try stepping in anyway - if(type == 5003L && opt == 0L) { - container = 0x0f; - } - - out.println(); - if (type != 0L && container == 0x0f) { - if (type == 1035L || type == 1036L) { - // Special Handling of 1035=PPDrawingGroup and 1036=PPDrawing - if(ddfEscher) { - // Seems to be: - walkEscherDDF((depth+3),pos+8,(int)len-8); - } else if(basicEscher) { - walkEscherBasic((depth+3),pos+8,(int)len-8); - } - } else { - // General container record handling code - walkTree((depth+2),pos,(int)len); - } - } - - pos += (int)len; - } - } - - /** - * Use the DDF code to walk the Escher records - */ - public void walkEscherDDF(int indent, int pos, int len) { - if(len < 8) { return; } - - final String ind = (indent == 0) ? "%1$s" : "%1$"+indent+"s"; - - byte[] contents = new byte[len]; - System.arraycopy(docstream,pos,contents,0,len); - DefaultEscherRecordFactory erf = new HSLFEscherRecordFactory(); - EscherRecord record = erf.createRecord(contents,0); - - // For now, try filling in the fields - record.fillFields(contents,0,erf); - - long atomType = LittleEndian.getUShort(contents,2); - // This lacks the 8 byte header size - long atomLen = LittleEndian.getUShort(contents,4); - // This (should) include the 8 byte header size - int recordLen = record.getRecordSize(); - - String fmt = ind+"At position %2$d (%2$04x): type is %3$d (%3$04x), len is %4$d (%4$04x) (%5$d) - record claims %6$d"; - out.println(String.format(Locale.ROOT, fmt, "", pos, atomType, atomLen, atomLen+8, recordLen)); - - - // Check for corrupt / lying ones - if(recordLen != 8 && (recordLen != (atomLen+8))) { - out.println(String.format(Locale.ROOT, ind+"** Atom length of $2d ($3d) doesn't match record length of %4d", "", atomLen, atomLen+8, recordLen)); - } - - // Print the record's details - String recordStr = record.toString().replace("\n", String.format(Locale.ROOT, "\n"+ind, "")); - out.println(String.format(Locale.ROOT, ind+"%2$s", "", recordStr)); - - if(record instanceof EscherContainerRecord) { - walkEscherDDF((indent+3), pos + 8, (int)atomLen ); - } - - // Handle records that seem to lie - if(atomType == 61451L) { - // Normally claims a size of 8 - recordLen = (int)atomLen + 8; - } - if(atomType == 61453L) { - // Returns EscherContainerRecord, but really msofbtClientTextbox - recordLen = (int)atomLen + 8; - record.fillFields( contents, 0, erf ); - if(! (record instanceof EscherTextboxRecord)) { - out.println(String.format(Locale.ROOT, ind+"%2$s", "", "** Really a msofbtClientTextbox !")); - } - } - - // Decide on what to do, based on how the lengths match up - if(recordLen == 8 && atomLen > 8 ) { - // Assume it has children, rather than being corrupted - walkEscherDDF((indent+3), pos + 8, (int)atomLen ); - - // Wind on our length + our header - pos += atomLen; - pos += 8; - len -= atomLen; - len -= 8; - } else { - // No children, wind on our real length - pos += atomLen; - pos += 8; - len -= atomLen; - len -= 8; - } - - // Move on to the next one, if we're not at the end yet - if(len >= 8) { - walkEscherDDF(indent, pos, len ); - } - } - - /** - * Use the basic record format groking code to walk the Escher records - */ - public void walkEscherBasic(int indent, int pos, int len) throws IOException { - if(len < 8) { return; } - - final String ind = (indent == 0) ? "%1$s" : "%1$"+indent+"s"; - - long type = LittleEndian.getUShort(docstream,pos+2); - long atomlen = LittleEndian.getUInt(docstream,pos+4); - - String fmt = ind+"At position %2$d ($2$04x): type is %3$d (%3$04x), len is %4$d (%4$04x)"; - out.println(String.format(Locale.ROOT, fmt, "", pos, type, atomlen)); - - String typeName = RecordTypes.forTypeID((short)type).name(); - out.println(String.format(Locale.ROOT, ind+"%2$s", "That's an Escher Record: ", typeName)); - - // Record specific dumps - if(type == 61453L) { - // Text Box. Print out first 8 bytes of data, then 8 4 later - HexDump.dump(docstream, 0, out, pos+8, 8); - HexDump.dump(docstream, 0, out, pos+20, 8); - out.println(); - } - - - // Blank line before next entry - out.println(); - - // Look in children if we are a container - if(type == 61443L || type == 61444L) { - walkEscherBasic((indent+3), pos+8, (int)atomlen); - } - - // Keep going if not yet at end - if(atomlen < len) { - int atomleni = (int)atomlen; - walkEscherBasic(indent, pos+atomleni+8, len-atomleni-8); - } - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/dev/SlideShowRecordDumper.java b/src/scratchpad/src/org/apache/poi/hslf/dev/SlideShowRecordDumper.java deleted file mode 100644 index cb3fe817f..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/dev/SlideShowRecordDumper.java +++ /dev/null @@ -1,290 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.dev; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.PrintStream; -import java.util.List; -import java.util.Locale; - -import org.apache.poi.ddf.DefaultEscherRecordFactory; -import org.apache.poi.ddf.EscherContainerRecord; -import org.apache.poi.ddf.EscherRecord; -import org.apache.poi.ddf.EscherTextboxRecord; -import org.apache.poi.hslf.record.EscherTextboxWrapper; -import org.apache.poi.hslf.record.HSLFEscherRecordFactory; -import org.apache.poi.hslf.record.Record; -import org.apache.poi.hslf.record.StyleTextPropAtom; -import org.apache.poi.hslf.record.TextBytesAtom; -import org.apache.poi.hslf.record.TextCharsAtom; -import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl; -import org.apache.poi.util.HexDump; - -/** - * This class provides a way to view the contents of a powerpoint file. - * It will use the recored layer to grok the contents of the file, and - * will print out what it finds. - * - * @author Nick Burch - */ -public final class SlideShowRecordDumper { - final static String tabs = "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t"; - - private boolean optVerbose; - private boolean optEscher; - private HSLFSlideShowImpl doc; - private final PrintStream ps; - - /** - * right now this function takes one parameter: a ppt file, and outputs a - * dump of what it contains - */ - public static void main(String args[]) throws IOException { - String filename = ""; - boolean verbose = false; - boolean escher = false; - - int ndx = 0; - for (; ndx < args.length; ndx++) { - if (!args[ndx].substring(0, 1).equals("-")) - break; - - if (args[ndx].equals("-escher")) { - escher = true; - } else if (args[ndx].equals("-verbose")) { - verbose = true; - } else { - printUsage(); - return; - } - } - - // parsed any options, expect exactly one remaining arg (filename) - if (ndx != args.length - 1) { - printUsage(); - return; - } - - filename = args[ndx]; - - SlideShowRecordDumper foo = new SlideShowRecordDumper(System.out, - filename, verbose, escher); - - foo.printDump(); - } - - public static void printUsage() { - System.err.println("Usage: SlideShowRecordDumper [-escher] [-verbose] "); - System.err.println("Valid Options:"); - System.err.println("-escher\t\t: dump contents of escher records"); - System.err.println("-verbose\t: dump binary contents of each record"); - } - - /** - * Constructs a Powerpoint dump from fileName. Parses the document - * and dumps out the contents - * - * @param fileName The name of the file to read. - * @throws IOException if there is a problem while parsing the document. - */ - public SlideShowRecordDumper(PrintStream ps, String fileName, boolean verbose, boolean escher) - throws IOException { - this.ps = ps; - optVerbose = verbose; - optEscher = escher; - doc = new HSLFSlideShowImpl(fileName); - } - - - public void printDump() throws IOException { - // Prints out the records in the tree - walkTree(0, 0, doc.getRecords(), 0); - } - - public String makeHex(int number, int padding) { - String hex = Integer.toHexString(number).toUpperCase(Locale.ROOT); - while (hex.length() < padding) { - hex = "0" + hex; - } - return hex; - } - - public String reverseHex(String s) { - StringBuilder ret = new StringBuilder(); - - // Get to a multiple of two - int pos = 0; - if ((s.length() & 1) == 1) { - ret.append(0); - pos++; - } - for (char c : s.toCharArray()) { - if (pos > 0 && (pos & 1) == 0) { - ret.append(' '); - } - ret.append(c); - pos++; - } - - return ret.toString(); - } - - public int getDiskLen(Record r) throws IOException { - int diskLen = 0; - if (r != null) { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - r.writeOut(baos); - diskLen = baos.size(); - } - return diskLen; - } - - public String getPrintableRecordContents(Record r) throws IOException { - if (r == null) { - return "<>"; - } - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - r.writeOut(baos); - byte[] b = baos.toByteArray(); - return HexDump.dump(b, 0, 0); - } - - public void printEscherRecord(EscherRecord er, int indent) { - if (er instanceof EscherContainerRecord) { - printEscherContainerRecord( (EscherContainerRecord)er, indent ); - } else if (er instanceof EscherTextboxRecord) { - printEscherTextBox( (EscherTextboxRecord)er, indent ); - } else { - ps.print( tabs.substring(0, indent) ); - ps.println( er.toString() ); - } - } - - private void printEscherTextBox( EscherTextboxRecord tbRecord, int indent ) { - String ind = tabs.substring(0, indent); - ps.println(ind+"EscherTextboxRecord:"); - - EscherTextboxWrapper etw = new EscherTextboxWrapper(tbRecord); - Record prevChild = null; - for (Record child : etw.getChildRecords()) { - if (child instanceof StyleTextPropAtom) { - // need preceding Text[Chars|Bytes]Atom to initialize the data structure - String text = null; - if (prevChild instanceof TextCharsAtom) { - text = ((TextCharsAtom)prevChild).getText(); - } else if (prevChild instanceof TextBytesAtom) { - text = ((TextBytesAtom)prevChild).getText(); - } else { - ps.println(ind+"Error! Couldn't find preceding TextAtom for style"); - continue; - } - - StyleTextPropAtom tsp = (StyleTextPropAtom)child; - tsp.setParentTextSize(text.length()); - } - ps.println(ind+child.toString()); - prevChild = child; - } - - } - - private void printEscherContainerRecord( EscherContainerRecord ecr, int indent ) { - String ind = tabs.substring(0, indent); - ps.println(ind + ecr.getClass().getName() + " (" + ecr.getRecordName() + "):"); - ps.println(ind + " isContainer: " + ecr.isContainerRecord()); - ps.println(ind + " options: 0x" + HexDump.toHex( ecr.getOptions() )); - ps.println(ind + " recordId: 0x" + HexDump.toHex( ecr.getRecordId() )); - - List childRecords = ecr.getChildRecords(); - ps.println(ind + " numchildren: " + childRecords.size()); - ps.println(ind + " children: "); - int count = 0; - for ( EscherRecord record : childRecords ) { - ps.println(ind + " Child " + count + ":"); - printEscherRecord(record, indent+1); - count++; - } - } - - - public void walkTree(int depth, int pos, Record[] records, int indent) throws IOException { - String ind = tabs.substring(0, indent); - - for (int i = 0; i < records.length; i++) { - Record r = records[i]; - if (r == null) { - ps.println(ind + "At position " + pos + " (" + makeHex(pos, 6) + "):"); - ps.println(ind + "Warning! Null record found."); - continue; - } - - // Figure out how big it is - int len = getDiskLen(r); - - // Grab the type as hex - String hexType = makeHex((int) r.getRecordType(), 4); - String rHexType = reverseHex(hexType); - - // Grab the hslf.record type - Class c = r.getClass(); - String cname = c.toString(); - if(cname.startsWith("class ")) { - cname = cname.substring(6); - } - if(cname.startsWith("org.apache.poi.hslf.record.")) { - cname = cname.substring(27); - } - - // Display the record - ps.println(ind + "At position " + pos + " (" + makeHex(pos,6) + "):"); - ps.println(ind + " Record is of type " + cname); - ps.println(ind + " Type is " + r.getRecordType() + " (" + hexType + " -> " + rHexType + " )"); - ps.println(ind + " Len is " + (len-8) + " (" + makeHex((len-8),8) + "), on disk len is " + len ); - - // print additional information for drawings and atoms - if (optEscher && cname.equals("PPDrawing")) { - DefaultEscherRecordFactory factory = new HSLFEscherRecordFactory(); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - r.writeOut(baos); - byte[] b = baos.toByteArray(); - - EscherRecord er = factory.createRecord(b, 0); - er.fillFields(b, 0, factory); - - printEscherRecord( er, indent+1 ); - - } else if(optVerbose && r.getChildRecords() == null) { - String recData = getPrintableRecordContents(r); - ps.println(ind + recData ); - } - - ps.println(); - - // If it has children, show them - if(r.getChildRecords() != null) { - walkTree((depth+3),pos+8,r.getChildRecords(), indent+1); - } - - // Wind on the position marker - pos += len; - } - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/dev/TextStyleListing.java b/src/scratchpad/src/org/apache/poi/hslf/dev/TextStyleListing.java deleted file mode 100644 index 3e313f90a..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/dev/TextStyleListing.java +++ /dev/null @@ -1,121 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.dev; - -import java.io.IOException; -import java.util.List; - -import org.apache.poi.hslf.model.textproperties.BitMaskTextProp; -import org.apache.poi.hslf.model.textproperties.TextProp; -import org.apache.poi.hslf.model.textproperties.TextPropCollection; -import org.apache.poi.hslf.record.Record; -import org.apache.poi.hslf.record.SlideListWithText; -import org.apache.poi.hslf.record.StyleTextPropAtom; -import org.apache.poi.hslf.record.TextBytesAtom; -import org.apache.poi.hslf.record.TextCharsAtom; -import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl; - -/** - * Uses record level code to locate StyleTextPropAtom entries. - * Having found them, it shows the contents - */ -public final class TextStyleListing { - public static void main(String[] args) throws IOException { - if(args.length < 1) { - System.err.println("Need to give a filename"); - System.exit(1); - } - - HSLFSlideShowImpl ss = new HSLFSlideShowImpl(args[0]); - - // Find the documents, and then their SLWT - Record[] records = ss.getRecords(); - for(int i=0; i paragraphStyles = stpa.getParagraphStyles(); - System.out.println("Contains " + paragraphStyles.size() + " paragraph styles:"); - for(int i=0; i charStyles = stpa.getCharacterStyles(); - System.out.println("Contains " + charStyles.size() + " character styles:"); - for(int i=0; i textProps = tpc.getTextPropList(); - System.out.println(" Contains " + textProps.size() + " TextProps"); - for(int i=0; i " + j + " - " + subPropNames[j]); - System.out.println(" " + j + " = " + subPropMatches[j]); - } - } - } - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/dev/UserEditAndPersistListing.java b/src/scratchpad/src/org/apache/poi/hslf/dev/UserEditAndPersistListing.java deleted file mode 100644 index 5f83d5688..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/dev/UserEditAndPersistListing.java +++ /dev/null @@ -1,131 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.dev; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.Map; - -import org.apache.poi.hslf.record.CurrentUserAtom; -import org.apache.poi.hslf.record.PersistPtrHolder; -import org.apache.poi.hslf.record.PositionDependentRecord; -import org.apache.poi.hslf.record.Record; -import org.apache.poi.hslf.record.UserEditAtom; -import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl; -import org.apache.poi.util.LittleEndian; - -/** - * Uses record level code to locate UserEditAtom records, and other - * persistence related atoms. Tries to match them together, to help - * illuminate quite what all the offsets mean - */ -public final class UserEditAndPersistListing { - private static byte[] fileContents; - - public static void main(String[] args) throws IOException { - if(args.length < 1) { - System.err.println("Need to give a filename"); - System.exit(1); - } - - - // Create the slideshow object, for normal working with - HSLFSlideShowImpl ss = new HSLFSlideShowImpl(args[0]); - fileContents = ss.getUnderlyingBytes(); - System.out.println(""); - - // Find any persist ones first - int pos = 0; - for(Record r : ss.getRecords()) { - if(r.getRecordType() == 6001l) { - // PersistPtrFullBlock - System.out.println("Found PersistPtrFullBlock at " + pos + " (" + Integer.toHexString(pos) + ")"); - } - if(r.getRecordType() == 6002l) { - // PersistPtrIncrementalBlock - System.out.println("Found PersistPtrIncrementalBlock at " + pos + " (" + Integer.toHexString(pos) + ")"); - PersistPtrHolder pph = (PersistPtrHolder)r; - - // Check the sheet offsets - Map sheetOffsets = pph.getSlideLocationsLookup(); - for(int id : pph.getKnownSlideIDs()) { - Integer offset = sheetOffsets.get(id); - - System.out.println(" Knows about sheet " + id); - System.out.println(" That sheet lives at " + offset); - - Record atPos = findRecordAtPos(offset.intValue()); - System.out.println(" The record at that pos is of type " + atPos.getRecordType()); - System.out.println(" The record at that pos has class " + atPos.getClass().getName()); - - if(! (atPos instanceof PositionDependentRecord)) { - System.out.println(" ** The record class isn't position aware! **"); - } - } - } - - // Increase the position by the on disk size - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - r.writeOut(baos); - pos += baos.size(); - } - - System.out.println(""); - - pos = 0; - // Now look for UserEditAtoms - for(Record r : ss.getRecords()) { - if(r instanceof UserEditAtom) { - UserEditAtom uea = (UserEditAtom)r; - System.out.println("Found UserEditAtom at " + pos + " (" + Integer.toHexString(pos) + ")"); - System.out.println(" lastUserEditAtomOffset = " + uea.getLastUserEditAtomOffset() ); - System.out.println(" persistPointersOffset = " + uea.getPersistPointersOffset() ); - System.out.println(" docPersistRef = " + uea.getDocPersistRef() ); - System.out.println(" maxPersistWritten = " + uea.getMaxPersistWritten() ); - } - - // Increase the position by the on disk size - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - r.writeOut(baos); - pos += baos.size(); - } - - System.out.println(""); - - - // Query the CurrentUserAtom - CurrentUserAtom cua = ss.getCurrentUserAtom(); - System.out.println("Checking Current User Atom"); - System.out.println(" Thinks the CurrentEditOffset is " + cua.getCurrentEditOffset()); - - System.out.println(""); - - ss.close(); - } - - - // Finds the record at a given position - public static Record findRecordAtPos(int pos) { - long type = LittleEndian.getUShort(fileContents, pos+2); - long rlen = LittleEndian.getUInt(fileContents, pos+4); - - Record r = Record.createRecordForType(type,fileContents,pos,(int)rlen+8); - - return r; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/exceptions/CorruptPowerPointFileException.java b/src/scratchpad/src/org/apache/poi/hslf/exceptions/CorruptPowerPointFileException.java deleted file mode 100644 index 3c6103948..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/exceptions/CorruptPowerPointFileException.java +++ /dev/null @@ -1,40 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.exceptions; - -/** - * This exception is thrown when we try to open a PowerPoint file, and - * something is fundamentally broken about it. - * - * @author Nick Burch - */ - -public final class CorruptPowerPointFileException extends IllegalStateException -{ - public CorruptPowerPointFileException(String s) { - super(s); - } - - public CorruptPowerPointFileException(String s, Throwable t) { - super(s,t); - } - - public CorruptPowerPointFileException(Throwable t) { - super(t); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/exceptions/EncryptedPowerPointFileException.java b/src/scratchpad/src/org/apache/poi/hslf/exceptions/EncryptedPowerPointFileException.java deleted file mode 100644 index de9d53477..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/exceptions/EncryptedPowerPointFileException.java +++ /dev/null @@ -1,39 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.exceptions; - -import org.apache.poi.EncryptedDocumentException; - -/** - * This exception is thrown when we try to open a PowerPoint file, and - * discover that it is encrypted - */ -public final class EncryptedPowerPointFileException extends EncryptedDocumentException -{ - public EncryptedPowerPointFileException(String s) { - super(s); - } - - public EncryptedPowerPointFileException(String s, Throwable t) { - super(s, t); - } - - public EncryptedPowerPointFileException(Throwable t) { - super(t); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/exceptions/HSLFException.java b/src/scratchpad/src/org/apache/poi/hslf/exceptions/HSLFException.java deleted file mode 100644 index f534d9ce0..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/exceptions/HSLFException.java +++ /dev/null @@ -1,42 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.exceptions; - -/** - * A generic exception that can be thrown by HSLF classes - * - * @author Yegor Kozlov - */ -public final class HSLFException extends RuntimeException { - - public HSLFException() { - super(); - } - - public HSLFException(String message) { - super(message); - } - - public HSLFException(String message, Throwable cause) { - super(message, cause); - } - - public HSLFException(Throwable cause) { - super(cause); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/exceptions/OldPowerPointFormatException.java b/src/scratchpad/src/org/apache/poi/hslf/exceptions/OldPowerPointFormatException.java deleted file mode 100644 index fbb2f6d5f..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/exceptions/OldPowerPointFormatException.java +++ /dev/null @@ -1,30 +0,0 @@ - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hslf.exceptions; - -import org.apache.poi.OldFileFormatException; - -/** - * This exception is thrown when we try to open a PowerPoint file, and - * it's too old for us. - */ -public class OldPowerPointFormatException extends OldFileFormatException { - public OldPowerPointFormatException(String s) { - super(s); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/extractor/ImageExtractor.java b/src/scratchpad/src/org/apache/poi/hslf/extractor/ImageExtractor.java deleted file mode 100644 index ffd3cc108..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/extractor/ImageExtractor.java +++ /dev/null @@ -1,54 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.extractor; - -import java.io.FileOutputStream; -import java.io.IOException; - -import org.apache.poi.hslf.usermodel.HSLFPictureData; -import org.apache.poi.hslf.usermodel.HSLFSlideShow; -import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl; -import org.apache.poi.sl.usermodel.PictureData.PictureType; - -/** - * Utility to extract pictures from a PowerPoint file. - */ -public final class ImageExtractor { - public static void main(String args[]) throws IOException { - if (args.length < 1) { - System.err.println("Usage:"); - System.err.println("\tImageExtractor "); - return; - } - HSLFSlideShow ppt = new HSLFSlideShow(new HSLFSlideShowImpl(args[0])); - - //extract all pictures contained in the presentation - int i = 0; - for (HSLFPictureData pict : ppt.getPictureData()) { - // picture data - byte[] data = pict.getData(); - - PictureType type = pict.getType(); - FileOutputStream out = new FileOutputStream("pict_" + i++ + type.extension); - out.write(data); - out.close(); - } - - ppt.close(); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/extractor/PowerPointExtractor.java b/src/scratchpad/src/org/apache/poi/hslf/extractor/PowerPointExtractor.java deleted file mode 100644 index 7e09764e1..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/extractor/PowerPointExtractor.java +++ /dev/null @@ -1,375 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.extractor; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.apache.poi.POIOLE2TextExtractor; -import org.apache.poi.hslf.model.Comment; -import org.apache.poi.hslf.model.HSLFMetroShape; -import org.apache.poi.hslf.model.HeadersFooters; -import org.apache.poi.hslf.model.OLEShape; -import org.apache.poi.hslf.usermodel.HSLFMasterSheet; -import org.apache.poi.hslf.usermodel.HSLFNotes; -import org.apache.poi.hslf.usermodel.HSLFShape; -import org.apache.poi.hslf.usermodel.HSLFSlide; -import org.apache.poi.hslf.usermodel.HSLFSlideMaster; -import org.apache.poi.hslf.usermodel.HSLFSlideShow; -import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl; -import org.apache.poi.hslf.usermodel.HSLFTable; -import org.apache.poi.hslf.usermodel.HSLFTableCell; -import org.apache.poi.hslf.usermodel.HSLFTextParagraph; -import org.apache.poi.hslf.usermodel.HSLFTextShape; -import org.apache.poi.poifs.filesystem.DirectoryNode; -import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; - -/** - * This class can be used to extract text from a PowerPoint file. Can optionally - * also get the notes from one. - */ -public final class PowerPointExtractor extends POIOLE2TextExtractor { - private static final POILogger LOG = POILogFactory.getLogger(PowerPointExtractor.class); - - private final HSLFSlideShow _show; - private final List _slides; - - private boolean _slidesByDefault = true; - private boolean _notesByDefault = false; - private boolean _commentsByDefault = false; - private boolean _masterByDefault = false; - - /** - * Basic extractor. Returns all the text, and optionally all the notes - */ - public static void main(String args[]) throws IOException { - if (args.length < 1) { - System.err.println("Useage:"); - System.err.println("\tPowerPointExtractor [-notes] "); - System.exit(1); - } - - boolean notes = false; - boolean comments = false; - boolean master = true; - - String file; - if (args.length > 1) { - notes = true; - file = args[1]; - if (args.length > 2) { - comments = true; - } - } else { - file = args[0]; - } - - PowerPointExtractor ppe = new PowerPointExtractor(file); - System.out.println(ppe.getText(true, notes, comments, master)); - ppe.close(); - } - - /** - * Creates a PowerPointExtractor, from a file - * - * @param fileName The name of the file to extract from - */ - public PowerPointExtractor(String fileName) throws IOException { - this(new NPOIFSFileSystem(new File(fileName))); - } - - /** - * Creates a PowerPointExtractor, from an Input Stream - * - * @param iStream The input stream containing the PowerPoint document - */ - public PowerPointExtractor(InputStream iStream) throws IOException { - this(new POIFSFileSystem(iStream)); - } - - /** - * Creates a PowerPointExtractor, from an open POIFSFileSystem - * - * @param fs the POIFSFileSystem containing the PowerPoint document - */ - public PowerPointExtractor(POIFSFileSystem fs) throws IOException { - this(fs.getRoot()); - } - - /** - * Creates a PowerPointExtractor, from an open NPOIFSFileSystem - * - * @param fs the NPOIFSFileSystem containing the PowerPoint document - */ - public PowerPointExtractor(NPOIFSFileSystem fs) throws IOException { - this(fs.getRoot()); - setFilesystem(fs); - } - - /** - * Creates a PowerPointExtractor, from a specific place - * inside an open NPOIFSFileSystem - * - * @param dir the POIFS Directory containing the PowerPoint document - */ - public PowerPointExtractor(DirectoryNode dir) throws IOException { - this(new HSLFSlideShowImpl(dir)); - } - - /** - * Creates a PowerPointExtractor, from a HSLFSlideShow - * - * @param ss the HSLFSlideShow to extract text from - */ - public PowerPointExtractor(HSLFSlideShowImpl ss) { - super(ss); - _show = new HSLFSlideShow(ss); - _slides = _show.getSlides(); - } - - /** - * Should a call to getText() return slide text? Default is yes - */ - public void setSlidesByDefault(boolean slidesByDefault) { - this._slidesByDefault = slidesByDefault; - } - - /** - * Should a call to getText() return notes text? Default is no - */ - public void setNotesByDefault(boolean notesByDefault) { - this._notesByDefault = notesByDefault; - } - - /** - * Should a call to getText() return comments text? Default is no - */ - public void setCommentsByDefault(boolean commentsByDefault) { - this._commentsByDefault = commentsByDefault; - } - - /** - * Should a call to getText() return text from master? Default is no - */ - public void setMasterByDefault(boolean masterByDefault) { - this._masterByDefault = masterByDefault; - } - - /** - * Fetches all the slide text from the slideshow, but not the notes, unless - * you've called setSlidesByDefault() and setNotesByDefault() to change this - */ - @Override - public String getText() { - return getText(_slidesByDefault, _notesByDefault, _commentsByDefault, _masterByDefault); - } - - /** - * Fetches all the notes text from the slideshow, but not the slide text - */ - public String getNotes() { - return getText(false, true); - } - - public List getOLEShapes() { - List list = new ArrayList(); - - for (HSLFSlide slide : _slides) { - for (HSLFShape shape : slide.getShapes()) { - if (shape instanceof OLEShape) { - list.add((OLEShape) shape); - } - } - } - - return list; - } - - /** - * Fetches text from the slideshow, be it slide text or note text. Because - * the final block of text in a TextRun normally have their last \n - * stripped, we add it back - * - * @param getSlideText fetch slide text - * @param getNoteText fetch note text - */ - public String getText(boolean getSlideText, boolean getNoteText) { - return getText(getSlideText, getNoteText, _commentsByDefault, _masterByDefault); - } - - public String getText(boolean getSlideText, boolean getNoteText, boolean getCommentText, boolean getMasterText) { - StringBuffer ret = new StringBuffer(); - - if (getSlideText) { - if (getMasterText) { - for (HSLFSlideMaster master : _show.getSlideMasters()) { - for(HSLFShape sh : master.getShapes()){ - if(sh instanceof HSLFTextShape){ - HSLFTextShape hsh = (HSLFTextShape)sh; - final String text = hsh.getText(); - if (text == null || "".equals(text) || "*".equals(text)) { - continue; - } - - if (HSLFMasterSheet.isPlaceholder(sh)) { - // check for metro shape of complex placeholder - boolean isMetro = new HSLFMetroShape(sh).hasMetroBlob(); - - if (!isMetro) { - // don't bother about boiler plate text on master sheets - LOG.log(POILogger.INFO, "Ignoring boiler plate (placeholder) text on slide master:", text); - continue; - } - } - - ret.append(text); - if (!text.endsWith("\n")) { - ret.append("\n"); - } - } - } - } - } - - for (HSLFSlide slide : _slides) { - String headerText = ""; - String footerText = ""; - HeadersFooters hf = slide.getHeadersFooters(); - if (hf != null) { - if (hf.isHeaderVisible()) { - headerText = safeLine(hf.getHeaderText()); - } - if (hf.isFooterVisible()) { - footerText = safeLine(hf.getFooterText()); - } - } - - // Slide header, if set - ret.append(headerText); - - // Slide text - textRunsToText(ret, slide.getTextParagraphs()); - - // Table text - for (HSLFShape shape : slide.getShapes()){ - if (shape instanceof HSLFTable){ - extractTableText(ret, (HSLFTable)shape); - } - } - // Slide footer, if set - ret.append(footerText); - - // Comments, if requested and present - if (getCommentText) { - for (Comment comment : slide.getComments()) { - ret.append(comment.getAuthor() + " - " + comment.getText() + "\n"); - } - } - } - if (getNoteText) { - ret.append('\n'); - } - } - - if (getNoteText) { - // Not currently using _notes, as that can have the notes of - // master sheets in. Grab Slide list, then work from there, - // but ensure no duplicates - Set seenNotes = new HashSet(); - String headerText = ""; - String footerText = ""; - HeadersFooters hf = _show.getNotesHeadersFooters(); - if (hf != null) { - if (hf.isHeaderVisible()) { - headerText = safeLine(hf.getHeaderText()); - } - if (hf.isFooterVisible()) { - footerText = safeLine(hf.getFooterText()); - } - } - - - for (HSLFSlide slide : _slides) { - HSLFNotes notes = slide.getNotes(); - if (notes == null) { - continue; - } - Integer id = Integer.valueOf(notes._getSheetNumber()); - if (seenNotes.contains(id)) { - continue; - } - seenNotes.add(id); - - // Repeat the Notes header, if set - ret.append(headerText); - - // Notes text - textRunsToText(ret, notes.getTextParagraphs()); - - // Repeat the notes footer, if set - ret.append(footerText); - } - } - - return ret.toString(); - } - - private static String safeLine(String text) { - return (text == null) ? "" : (text+'\n'); - } - - private void extractTableText(StringBuffer ret, HSLFTable table) { - final int nrows = table.getNumberOfRows(); - final int ncols = table.getNumberOfColumns(); - for (int row = 0; row < nrows; row++){ - for (int col = 0; col < ncols; col++){ - HSLFTableCell cell = table.getCell(row, col); - //defensive null checks; don't know if they're necessary - if (cell != null){ - String txt = cell.getText(); - txt = (txt == null) ? "" : txt; - ret.append(txt); - if (col < ncols-1){ - ret.append('\t'); - } - } - } - ret.append('\n'); - } - } - private void textRunsToText(StringBuffer ret, List> paragraphs) { - if (paragraphs==null) { - return; - } - - for (List lp : paragraphs) { - ret.append(HSLFTextParagraph.getText(lp)); - if (ret.length() > 0 && ret.charAt(ret.length()-1) != '\n') { - ret.append('\n'); - } - } - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/extractor/QuickButCruddyTextExtractor.java b/src/scratchpad/src/org/apache/poi/hslf/extractor/QuickButCruddyTextExtractor.java deleted file mode 100644 index 1ecc49a94..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/extractor/QuickButCruddyTextExtractor.java +++ /dev/null @@ -1,210 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.extractor; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.hslf.record.CString; -import org.apache.poi.hslf.record.Record; -import org.apache.poi.hslf.record.RecordTypes; -import org.apache.poi.hslf.record.TextBytesAtom; -import org.apache.poi.hslf.record.TextCharsAtom; -import org.apache.poi.hslf.usermodel.HSLFTextParagraph; -import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.LittleEndian; - -/** - * This class will get all the text from a Powerpoint Document, including - * all the bits you didn't want, and in a somewhat random order, but will - * do it very fast. - * The class ignores most of the hslf classes, and doesn't use - * HSLFSlideShow. Instead, it just does a very basic scan through the - * file, grabbing all the text records as it goes. It then returns the - * text, either as a single string, or as a vector of all the individual - * strings. - * Because of how it works, it will return a lot of "crud" text that you - * probably didn't want! It will return text from master slides. It will - * return duplicate text, and some mangled text (powerpoint files often - * have duplicate copies of slide text in them). You don't get any idea - * what the text was associated with. - * Almost everyone will want to use @see PowerPointExtractor instead. There - * are only a very small number of cases (eg some performance sensitive - * lucene indexers) that would ever want to use this! - */ -public final class QuickButCruddyTextExtractor { - private NPOIFSFileSystem fs; - private InputStream is; - private byte[] pptContents; - - /** - * Really basic text extractor, that will also return lots of crud text. - * Takes a single argument, the file to extract from - */ - public static void main(String args[]) throws IOException - { - if(args.length < 1) { - System.err.println("Useage:"); - System.err.println("\tQuickButCruddyTextExtractor "); - System.exit(1); - } - - String file = args[0]; - - QuickButCruddyTextExtractor ppe = new QuickButCruddyTextExtractor(file); - System.out.println(ppe.getTextAsString()); - ppe.close(); - } - - /** - * Creates an extractor from a given file name - * @param fileName - */ - @SuppressWarnings("resource") - public QuickButCruddyTextExtractor(String fileName) throws IOException { - this(new NPOIFSFileSystem(new File(fileName))); - } - - /** - * Creates an extractor from a given input stream - * @param iStream - */ - @SuppressWarnings("resource") - public QuickButCruddyTextExtractor(InputStream iStream) throws IOException { - this(new NPOIFSFileSystem(iStream)); - is = iStream; - } - - /** - * Creates an extractor from a POIFS Filesystem - * @param poifs - */ - public QuickButCruddyTextExtractor(NPOIFSFileSystem poifs) throws IOException { - fs = poifs; - - // Find the PowerPoint bit, and get out the bytes - InputStream pptIs = fs.createDocumentInputStream("PowerPoint Document"); - pptContents = IOUtils.toByteArray(pptIs); - pptIs.close(); - } - - - /** - * Shuts down the underlying streams - */ - public void close() throws IOException { - if(is != null) { is.close(); } - fs = null; - } - - /** - * Fetches the ALL the text of the powerpoint file, as a single string - */ - public String getTextAsString() { - StringBuffer ret = new StringBuffer(); - List textV = getTextAsVector(); - for(String text : textV) { - ret.append(text); - if(! text.endsWith("\n")) { - ret.append('\n'); - } - } - return ret.toString(); - } - - /** - * Fetches the ALL the text of the powerpoint file, in a List of - * strings, one per text record - */ - public List getTextAsVector() { - List textV = new ArrayList(); - - // Set to the start of the file - int walkPos = 0; - - // Start walking the file, looking for the records - while(walkPos != -1) { - int newPos = findTextRecords(walkPos,textV); - walkPos = newPos; - } - - // Return what we find - return textV; - } - - /** - * For the given position, look if the record is a text record, and wind - * on after. - * If it is a text record, grabs out the text. Whatever happens, returns - * the position of the next record, or -1 if no more. - */ - public int findTextRecords(int startPos, List textV) { - // Grab the length, and the first option byte - // Note that the length doesn't include the 8 byte atom header - int len = (int)LittleEndian.getUInt(pptContents,startPos+4); - byte opt = pptContents[startPos]; - - // If it's a container, step into it and return - // (If it's a container, option byte 1 BINARY_AND 0x0f will be 0x0f) - int container = opt & 0x0f; - if(container == 0x0f) { - return (startPos+8); - } - - // Otherwise, check the type to see if it's text - int type = LittleEndian.getUShort(pptContents,startPos+2); - - // TextBytesAtom - if(type == RecordTypes.TextBytesAtom.typeID) { - TextBytesAtom tba = (TextBytesAtom)Record.createRecordForType(type, pptContents, startPos, len+8); - String text = HSLFTextParagraph.toExternalString(tba.getText(), -1); - textV.add(text); - } - // TextCharsAtom - if(type == RecordTypes.TextCharsAtom.typeID) { - TextCharsAtom tca = (TextCharsAtom)Record.createRecordForType(type, pptContents, startPos, len+8); - String text = HSLFTextParagraph.toExternalString(tca.getText(), -1); - textV.add(text); - } - - // CString (doesn't go via a TextRun) - if(type == RecordTypes.CString.typeID) { - CString cs = (CString)Record.createRecordForType(type, pptContents, startPos, len+8); - String text = cs.getText(); - - // Ignore the ones we know to be rubbish - if(text.equals("___PPT10")) { - } else if(text.equals("Default Design")) { - } else { - textV.add(text); - } - } - - - // Wind on by the atom length, and check we're not at the end - int newPos = (startPos + 8 + len); - if(newPos > (pptContents.length - 8)) { - newPos = -1; - } - return newPos; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/model/ActiveXShape.java b/src/scratchpad/src/org/apache/poi/hslf/model/ActiveXShape.java deleted file mode 100644 index d82555a80..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/model/ActiveXShape.java +++ /dev/null @@ -1,160 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.model; - -import org.apache.poi.ddf.AbstractEscherOptRecord; -import org.apache.poi.ddf.EscherComplexProperty; -import org.apache.poi.ddf.EscherContainerRecord; -import org.apache.poi.ddf.EscherProperties; -import org.apache.poi.ddf.EscherSpRecord; -import org.apache.poi.hslf.exceptions.HSLFException; -import org.apache.poi.hslf.record.Document; -import org.apache.poi.hslf.record.ExControl; -import org.apache.poi.hslf.record.ExObjList; -import org.apache.poi.hslf.record.ExObjRefAtom; -import org.apache.poi.hslf.record.HSLFEscherClientDataRecord; -import org.apache.poi.hslf.record.Record; -import org.apache.poi.hslf.record.RecordTypes; -import org.apache.poi.hslf.usermodel.HSLFPictureData; -import org.apache.poi.hslf.usermodel.HSLFPictureShape; -import org.apache.poi.hslf.usermodel.HSLFShape; -import org.apache.poi.hslf.usermodel.HSLFSheet; -import org.apache.poi.hslf.usermodel.HSLFTextParagraph; -import org.apache.poi.sl.usermodel.ShapeContainer; -import org.apache.poi.sl.usermodel.ShapeType; -import org.apache.poi.util.StringUtil; - -/** - * Represents an ActiveX control in a PowerPoint document. - */ -public final class ActiveXShape extends HSLFPictureShape { - public static final int DEFAULT_ACTIVEX_THUMBNAIL = -1; - - /** - * Create a new Picture - * - * @param pictureData the picture data - */ - public ActiveXShape(int movieIdx, HSLFPictureData pictureData){ - super(pictureData, null); - setActiveXIndex(movieIdx); - } - - /** - * Create a Picture object - * - * @param escherRecord the EscherSpContainer record which holds information about - * this picture in the Slide - * @param parent the parent shape of this picture - */ - protected ActiveXShape(EscherContainerRecord escherRecord, ShapeContainer parent){ - super(escherRecord, parent); - } - - /** - * Create a new Placeholder and initialize internal structures - * - * @return the created EscherContainerRecord which holds shape data - */ - @Override - protected EscherContainerRecord createSpContainer(int idx, boolean isChild) { - EscherContainerRecord ecr = super.createSpContainer(idx, isChild); - - EscherSpRecord spRecord = ecr.getChildById(EscherSpRecord.RECORD_ID); - spRecord.setFlags(EscherSpRecord.FLAG_HAVEANCHOR | EscherSpRecord.FLAG_HASSHAPETYPE | EscherSpRecord.FLAG_OLESHAPE); - - setShapeType(ShapeType.HOST_CONTROL); - setEscherProperty(EscherProperties.BLIP__PICTUREID, idx); - setEscherProperty(EscherProperties.LINESTYLE__COLOR, 0x8000001); - setEscherProperty(EscherProperties.LINESTYLE__NOLINEDRAWDASH, 0x80008); - setEscherProperty(EscherProperties.SHADOWSTYLE__COLOR, 0x8000002); - setEscherProperty(EscherProperties.PROTECTION__LOCKAGAINSTGROUPING, -1); - - HSLFEscherClientDataRecord cldata = getClientData(true); - cldata.addChild(new ExObjRefAtom()); - - return ecr; - } - - /** - * Assign a control to this shape - * - * @see org.apache.poi.hslf.usermodel.HSLFSlideShow#addMovie(String, int) - * @param idx the index of the movie - */ - public void setActiveXIndex(int idx) { - ExObjRefAtom oe = getClientDataRecord(RecordTypes.ExObjRefAtom.typeID); - if (oe == null) { - throw new HSLFException("OEShapeAtom for ActiveX doesn't exist"); - } - oe.setExObjIdRef(idx); - } - - public int getControlIndex(){ - int idx = -1; - ExObjRefAtom oe = getClientDataRecord(RecordTypes.ExObjRefAtom.typeID); - if(oe != null) idx = oe.getExObjIdRef(); - return idx; - } - - /** - * Set a property of this ActiveX control - * @param key - * @param value - */ - public void setProperty(String key, String value){ - - } - - /** - * Document-level container that specifies information about an ActiveX control - * - * @return container that specifies information about an ActiveX control - */ - public ExControl getExControl(){ - int idx = getControlIndex(); - ExControl ctrl = null; - Document doc = getSheet().getSlideShow().getDocumentRecord(); - ExObjList lst = (ExObjList)doc.findFirstOfType(RecordTypes.ExObjList.typeID); - if(lst != null){ - Record[] ch = lst.getChildRecords(); - for (int i = 0; i < ch.length; i++) { - if(ch[i] instanceof ExControl){ - ExControl c = (ExControl)ch[i]; - if(c.getExOleObjAtom().getObjID() == idx){ - ctrl = c; - break; - } - } - } - } - return ctrl; - } - - @Override - protected void afterInsert(HSLFSheet sheet){ - ExControl ctrl = getExControl(); - ctrl.getExControlAtom().setSlideId(sheet._getSheetNumber()); - - String name = ctrl.getProgId() + "-" + getControlIndex() + '\u0000'; - byte[] data = StringUtil.getToUnicodeLE(name); - EscherComplexProperty prop = new EscherComplexProperty(EscherProperties.GROUPSHAPE__SHAPENAME, false, data); - AbstractEscherOptRecord opt = getEscherOptRecord(); - opt.addEscherProperty(prop); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/model/Comment.java b/src/scratchpad/src/org/apache/poi/hslf/model/Comment.java deleted file mode 100644 index 27afa47c8..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/model/Comment.java +++ /dev/null @@ -1,75 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.model; - -import org.apache.poi.hslf.record.Comment2000; - -/** - * - * @author Nick Burch - */ -public final class Comment { - private Comment2000 _comment2000; - - public Comment(Comment2000 comment2000) { - _comment2000 = comment2000; - } - - protected Comment2000 getComment2000() { - return _comment2000; - } - - /** - * Get the Author of this comment - */ - public String getAuthor() { - return _comment2000.getAuthor(); - } - /** - * Set the Author of this comment - */ - public void setAuthor(String author) { - _comment2000.setAuthor(author); - } - - /** - * Get the Author's Initials of this comment - */ - public String getAuthorInitials() { - return _comment2000.getAuthorInitials(); - } - /** - * Set the Author's Initials of this comment - */ - public void setAuthorInitials(String initials) { - _comment2000.setAuthorInitials(initials); - } - - /** - * Get the text of this comment - */ - public String getText() { - return _comment2000.getText(); - } - /** - * Set the text of this comment - */ - public void setText(String text) { - _comment2000.setText(text); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/model/HSLFMetroShape.java b/src/scratchpad/src/org/apache/poi/hslf/model/HSLFMetroShape.java deleted file mode 100644 index 205f3e6e5..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/model/HSLFMetroShape.java +++ /dev/null @@ -1,89 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.model; - -import java.lang.reflect.Method; - -import org.apache.poi.ddf.AbstractEscherOptRecord; -import org.apache.poi.ddf.EscherComplexProperty; -import org.apache.poi.ddf.EscherProperties; -import org.apache.poi.ddf.EscherTertiaryOptRecord; -import org.apache.poi.hslf.usermodel.HSLFShape; -import org.apache.poi.sl.usermodel.Shape; -import org.apache.poi.util.Internal; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; - -/** - * Experimental class for metro blobs, i.e. an alternative escher property - * containing an ooxml representation of the shape - */ -@Internal -public class HSLFMetroShape> { - private static final POILogger LOGGER = POILogFactory.getLogger(HSLFMetroShape.class); - - private final HSLFShape shape; - - public HSLFMetroShape(HSLFShape shape) { - this.shape = shape; - } - - /** - * @return the bytes of the metro blob, which are bytes of an OPCPackage, i.e. a zip stream - */ - public byte[] getMetroBytes() { - EscherComplexProperty ep = getMetroProp(); - return (ep == null) ? null : ep.getComplexData(); - } - - /** - * @return if there's a metro blob to extract - */ - public boolean hasMetroBlob() { - return getMetroProp() != null; - } - - private EscherComplexProperty getMetroProp() { - AbstractEscherOptRecord opt = shape.getEscherChild(EscherTertiaryOptRecord.RECORD_ID); - return (opt == null) ? null : (EscherComplexProperty)opt.lookup(EscherProperties.GROUPSHAPE__METROBLOB); - } - - /** - * @return the metro blob shape or null if either there's no metro blob or the ooxml classes - * aren't in the classpath - */ - @SuppressWarnings("unchecked") - public T getShape() { - byte metroBytes[] = getMetroBytes(); - if (metroBytes == null) { - return null; - } - - // org.apache.poi.xslf.usermodel.XSLFMetroShape - ClassLoader cl = Thread.currentThread().getContextClassLoader(); - try { - Class ms = cl.loadClass("org.apache.poi.xslf.usermodel.XSLFMetroShape"); - Method m = ms.getMethod("parseShape", byte[].class); - return (T)m.invoke(null, new Object[]{metroBytes}); - } catch (Exception e) { - LOGGER.log(POILogger.ERROR, "can't process metro blob, check if all dependencies for POI OOXML are in the classpath.", e); - return null; - } - } -} - diff --git a/src/scratchpad/src/org/apache/poi/hslf/model/HeadersFooters.java b/src/scratchpad/src/org/apache/poi/hslf/model/HeadersFooters.java deleted file mode 100644 index ab96c7dbe..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/model/HeadersFooters.java +++ /dev/null @@ -1,278 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.model; - -import org.apache.poi.hslf.record.CString; -import org.apache.poi.hslf.record.Document; -import org.apache.poi.hslf.record.HeadersFootersAtom; -import org.apache.poi.hslf.record.HeadersFootersContainer; -import org.apache.poi.hslf.record.Record; -import org.apache.poi.hslf.record.RecordTypes; -import org.apache.poi.hslf.record.SheetContainer; -import org.apache.poi.hslf.usermodel.HSLFSheet; -import org.apache.poi.hslf.usermodel.HSLFSimpleShape; -import org.apache.poi.hslf.usermodel.HSLFSlideShow; -import org.apache.poi.hslf.usermodel.HSLFTextShape; -import org.apache.poi.sl.usermodel.Placeholder; - -/** - * Header / Footer settings. - * - * You can get these on slides, or across all notes - */ -public final class HeadersFooters { - - private static final String _ppt2007tag = "___PPT12"; - - private final HeadersFootersContainer _container; - private final HSLFSheet _sheet; - private final boolean _ppt2007; - - - public HeadersFooters(HSLFSlideShow ppt, short headerFooterType) { - this(ppt.getSlideMasters().get(0), headerFooterType); - } - - public HeadersFooters(HSLFSheet sheet, short headerFooterType) { - _sheet = sheet; - - @SuppressWarnings("resource") - HSLFSlideShow ppt = _sheet.getSlideShow(); - Document doc = ppt.getDocumentRecord(); - - // detect if this ppt was saved in Office2007 - String tag = ppt.getSlideMasters().get(0).getProgrammableTag(); - _ppt2007 = _ppt2007tag.equals(tag); - - SheetContainer sc = _sheet.getSheetContainer(); - HeadersFootersContainer hdd = (HeadersFootersContainer)sc.findFirstOfType(RecordTypes.HeadersFooters.typeID); - // boolean ppt2007 = sc.findFirstOfType(RecordTypes.RoundTripContentMasterId.typeID) != null; - - if (hdd == null) { - for (Record ch : doc.getChildRecords()) { - if (ch instanceof HeadersFootersContainer - && ((HeadersFootersContainer) ch).getOptions() == headerFooterType) { - hdd = (HeadersFootersContainer) ch; - break; - } - } - } - - if (hdd == null) { - hdd = new HeadersFootersContainer(headerFooterType); - Record lst = doc.findFirstOfType(RecordTypes.List.typeID); - doc.addChildAfter(hdd, lst); - } - _container = hdd; - } - - /** - * Headers's text - * - * @return Headers's text - */ - public String getHeaderText(){ - CString cs = _container == null ? null : _container.getHeaderAtom(); - return getPlaceholderText(Placeholder.HEADER, cs); - } - - /** - * Sets headers's text - * - * @param text headers's text - */ - public void setHeaderText(String text){ - setHeaderVisible(true); - CString cs = _container.getHeaderAtom(); - if (cs == null) { - cs = _container.addHeaderAtom(); - } - - cs.setText(text); - } - - /** - * Footer's text - * - * @return Footer's text - */ - public String getFooterText(){ - CString cs = _container == null ? null : _container.getFooterAtom(); - return getPlaceholderText(Placeholder.FOOTER, cs); - } - - /** - * Sets footers's text - * - * @param text footers's text - */ - public void setFootersText(String text){ - setFooterVisible(true); - CString cs = _container.getFooterAtom(); - if (cs == null) { - cs = _container.addFooterAtom(); - } - - cs.setText(text); - } - - /** - * This is the date that the user wants in the footers, instead of today's date. - * - * @return custom user date - */ - public String getDateTimeText(){ - CString cs = _container == null ? null : _container.getUserDateAtom(); - return getPlaceholderText(Placeholder.DATETIME, cs); - } - - /** - * Sets custom user date to be displayed instead of today's date. - * - * @param text custom user date - */ - public void setDateTimeText(String text){ - setUserDateVisible(true); - setDateTimeVisible(true); - CString cs = _container.getUserDateAtom(); - if (cs == null) { - cs = _container.addUserDateAtom(); - } - - cs.setText(text); - } - - /** - * whether the footer text is displayed. - */ - public boolean isFooterVisible(){ - return isVisible(HeadersFootersAtom.fHasFooter, Placeholder.FOOTER); - } - - /** - * whether the footer text is displayed. - */ - public void setFooterVisible(boolean flag){ - setFlag(HeadersFootersAtom.fHasFooter, flag); - } - - /** - * whether the header text is displayed. - */ - public boolean isHeaderVisible(){ - return isVisible(HeadersFootersAtom.fHasHeader, Placeholder.HEADER); - } - - /** - * whether the header text is displayed. - */ - public void setHeaderVisible(boolean flag){ - setFlag(HeadersFootersAtom.fHasHeader, flag); - } - - /** - * whether the date is displayed in the footer. - */ - public boolean isDateTimeVisible(){ - return isVisible(HeadersFootersAtom.fHasDate, Placeholder.DATETIME); - } - - /** - * whether the date is displayed in the footer. - */ - public void setDateTimeVisible(boolean flag){ - setFlag(HeadersFootersAtom.fHasDate, flag); - } - - /** - * whether the custom user date is used instead of today's date. - */ - public boolean isUserDateVisible(){ - return isVisible(HeadersFootersAtom.fHasUserDate, Placeholder.DATETIME); - } - - /** - * whether the date is displayed in the footer. - */ - public void setUserDateVisible(boolean flag){ - setFlag(HeadersFootersAtom.fHasUserDate, flag); - } - - /** - * whether the slide number is displayed in the footer. - */ - public boolean isSlideNumberVisible(){ - return isVisible(HeadersFootersAtom.fHasSlideNumber, Placeholder.SLIDE_NUMBER); - } - - /** - * whether the slide number is displayed in the footer. - */ - public void setSlideNumberVisible(boolean flag){ - setFlag(HeadersFootersAtom.fHasSlideNumber, flag); - } - - /** - * An integer that specifies the format ID to be used to style the datetime. - * - * @return an integer that specifies the format ID to be used to style the datetime. - */ - public int getDateTimeFormat(){ - return _container.getHeadersFootersAtom().getFormatId(); - } - - /** - * An integer that specifies the format ID to be used to style the datetime. - * - * @param formatId an integer that specifies the format ID to be used to style the datetime. - */ - public void setDateTimeFormat(int formatId){ - _container.getHeadersFootersAtom().setFormatId(formatId); - } - - private boolean isVisible(int flag, Placeholder placeholderId){ - boolean visible; - if(_ppt2007){ - HSLFSimpleShape ss = _sheet.getPlaceholder(placeholderId); - visible = ss instanceof HSLFTextShape && ((HSLFTextShape)ss).getText() != null; - } else { - visible = _container.getHeadersFootersAtom().getFlag(flag); - } - return visible; - } - - private String getPlaceholderText(Placeholder ph, CString cs) { - String text; - if (_ppt2007) { - HSLFSimpleShape ss = _sheet.getPlaceholder(ph); - text = (ss instanceof HSLFTextShape) ? ((HSLFTextShape)ss).getText() : null; - - // default text in master placeholders is not visible - if("*".equals(text)) { - text = null; - } - } else { - text = (cs == null) ? null : cs.getText(); - } - return text; - } - - private void setFlag(int type, boolean flag) { - _container.getHeadersFootersAtom().setFlag(type, flag); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/model/MovieShape.java b/src/scratchpad/src/org/apache/poi/hslf/model/MovieShape.java deleted file mode 100644 index 4452e758c..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/model/MovieShape.java +++ /dev/null @@ -1,178 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.model; - -import org.apache.poi.ddf.EscherContainerRecord; -import org.apache.poi.ddf.EscherProperties; -import org.apache.poi.hslf.record.AnimationInfo; -import org.apache.poi.hslf.record.AnimationInfoAtom; -import org.apache.poi.hslf.record.ExMCIMovie; -import org.apache.poi.hslf.record.ExObjList; -import org.apache.poi.hslf.record.ExObjRefAtom; -import org.apache.poi.hslf.record.ExVideoContainer; -import org.apache.poi.hslf.record.HSLFEscherClientDataRecord; -import org.apache.poi.hslf.record.InteractiveInfo; -import org.apache.poi.hslf.record.InteractiveInfoAtom; -import org.apache.poi.hslf.record.Record; -import org.apache.poi.hslf.record.RecordTypes; -import org.apache.poi.hslf.usermodel.HSLFPictureData; -import org.apache.poi.hslf.usermodel.HSLFPictureShape; -import org.apache.poi.hslf.usermodel.HSLFShape; -import org.apache.poi.hslf.usermodel.HSLFSlideShow; -import org.apache.poi.hslf.usermodel.HSLFTextParagraph; -import org.apache.poi.sl.usermodel.ShapeContainer; - -/** - * Represents a movie in a PowerPoint document. - * - * @author Yegor Kozlov - */ -public final class MovieShape extends HSLFPictureShape { - public static final int DEFAULT_MOVIE_THUMBNAIL = -1; - - public static final int MOVIE_MPEG = 1; - public static final int MOVIE_AVI = 2; - - /** - * Create a new Picture - * - * @param pictureData the picture data - */ - public MovieShape(int movieIdx, HSLFPictureData pictureData){ - super(pictureData, null); - setMovieIndex(movieIdx); - setAutoPlay(true); - } - - /** - * Create a new Picture - * - * @param pictureData the picture data - * @param parent the parent shape - */ - public MovieShape(int movieIdx, HSLFPictureData pictureData, ShapeContainer parent) { - super(pictureData, parent); - setMovieIndex(movieIdx); - } - - /** - * Create a Picture object - * - * @param escherRecord the EscherSpContainer record which holds information about - * this picture in the Slide - * @param parent the parent shape of this picture - */ - public MovieShape(EscherContainerRecord escherRecord, ShapeContainer parent){ - super(escherRecord, parent); - } - - /** - * Create a new Placeholder and initialize internal structures - * - * @return the created EscherContainerRecord which holds shape data - */ - @Override - protected EscherContainerRecord createSpContainer(int idx, boolean isChild) { - EscherContainerRecord ecr = super.createSpContainer(idx, isChild); - - setEscherProperty(EscherProperties.PROTECTION__LOCKAGAINSTGROUPING, 0x1000100); - setEscherProperty(EscherProperties.FILL__NOFILLHITTEST, 0x10001); - - ExObjRefAtom oe = new ExObjRefAtom(); - InteractiveInfo info = new InteractiveInfo(); - InteractiveInfoAtom infoAtom = info.getInteractiveInfoAtom(); - infoAtom.setAction(InteractiveInfoAtom.ACTION_MEDIA); - infoAtom.setHyperlinkType(InteractiveInfoAtom.LINK_NULL); - - AnimationInfo an = new AnimationInfo(); - AnimationInfoAtom anAtom = an.getAnimationInfoAtom(); - anAtom.setFlag(AnimationInfoAtom.Automatic, true); - - HSLFEscherClientDataRecord cldata = getClientData(true); - cldata.addChild(oe); - cldata.addChild(an); - cldata.addChild(info); - - return ecr; - } - - /** - * Assign a movie to this shape - * - * @see org.apache.poi.hslf.usermodel.HSLFSlideShow#addMovie(String, int) - * @param idx the index of the movie - */ - public void setMovieIndex(int idx){ - ExObjRefAtom oe = getClientDataRecord(RecordTypes.ExObjRefAtom.typeID); - oe.setExObjIdRef(idx); - - AnimationInfo an = getClientDataRecord(RecordTypes.AnimationInfo.typeID); - if(an != null) { - AnimationInfoAtom ai = an.getAnimationInfoAtom(); - ai.setDimColor(0x07000000); - ai.setFlag(AnimationInfoAtom.Automatic, true); - ai.setFlag(AnimationInfoAtom.Play, true); - ai.setFlag(AnimationInfoAtom.Synchronous, true); - ai.setOrderID(idx + 1); - } - } - - public void setAutoPlay(boolean flag){ - AnimationInfo an = getClientDataRecord(RecordTypes.AnimationInfo.typeID); - if(an != null){ - an.getAnimationInfoAtom().setFlag(AnimationInfoAtom.Automatic, flag); - } - } - - public boolean isAutoPlay(){ - AnimationInfo an = getClientDataRecord(RecordTypes.AnimationInfo.typeID); - if(an != null){ - return an.getAnimationInfoAtom().getFlag(AnimationInfoAtom.Automatic); - } - return false; - } - - /** - * @return UNC or local path to a video file - */ - @SuppressWarnings("resource") - public String getPath(){ - ExObjRefAtom oe = getClientDataRecord(RecordTypes.ExObjRefAtom.typeID); - int idx = oe.getExObjIdRef(); - - HSLFSlideShow ppt = getSheet().getSlideShow(); - ExObjList lst = (ExObjList)ppt.getDocumentRecord().findFirstOfType(RecordTypes.ExObjList.typeID); - if(lst == null) { - return null; - } - - Record[] r = lst.getChildRecords(); - for (int i = 0; i < r.length; i++) { - if(r[i] instanceof ExMCIMovie){ - ExMCIMovie mci = (ExMCIMovie)r[i]; - ExVideoContainer exVideo = mci.getExVideo(); - int objectId = exVideo.getExMediaAtom().getObjectId(); - if(objectId == idx){ - return exVideo.getPathAtom().getText(); - } - } - - } - return null; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/model/OLEShape.java b/src/scratchpad/src/org/apache/poi/hslf/model/OLEShape.java deleted file mode 100644 index 4a473ae73..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/model/OLEShape.java +++ /dev/null @@ -1,211 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.model; - -import org.apache.poi.ddf.EscherContainerRecord; -import org.apache.poi.ddf.EscherProperties; -import org.apache.poi.ddf.EscherSpRecord; -import org.apache.poi.hslf.record.ExEmbed; -import org.apache.poi.hslf.record.ExObjList; -import org.apache.poi.hslf.record.ExObjRefAtom; -import org.apache.poi.hslf.record.HSLFEscherClientDataRecord; -import org.apache.poi.hslf.record.Record; -import org.apache.poi.hslf.record.RecordTypes; -import org.apache.poi.hslf.usermodel.HSLFObjectData; -import org.apache.poi.hslf.usermodel.HSLFPictureData; -import org.apache.poi.hslf.usermodel.HSLFPictureShape; -import org.apache.poi.hslf.usermodel.HSLFShape; -import org.apache.poi.hslf.usermodel.HSLFSlideShow; -import org.apache.poi.hslf.usermodel.HSLFTextParagraph; -import org.apache.poi.sl.usermodel.ShapeContainer; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; - - -/** - * A shape representing embedded OLE obejct. - */ -public final class OLEShape extends HSLFPictureShape { - private static final POILogger LOG = POILogFactory.getLogger(OLEShape.class); - - private ExEmbed _exEmbed; - - /** - * Create a new OLEShape - * - * @param data the picture data - */ - public OLEShape(HSLFPictureData data){ - super(data); - } - - /** - * Create a new OLEShape - * - * @param data the picture data - * @param parent the parent shape - */ - public OLEShape(HSLFPictureData data, ShapeContainer parent) { - super(data, parent); - } - - /** - * Create a OLEShape object - * - * @param escherRecord the EscherSpContainer record which holds information about - * this picture in the Slide - * @param parent the parent shape of this picture - */ - public OLEShape(EscherContainerRecord escherRecord, ShapeContainer parent){ - super(escherRecord, parent); - } - - /** - * Returns unique identifier for the OLE object. - * - * @return the unique identifier for the OLE object - */ - public int getObjectID(){ - return getEscherProperty(EscherProperties.BLIP__PICTUREID); - } - - /** - * Set the unique identifier for the OLE object and - * register it in the necessary structures - * - * @param objectId the unique identifier for the OLE object - */ - public void setObjectID(int objectId){ - setEscherProperty(EscherProperties.BLIP__PICTUREID, objectId); - - EscherContainerRecord ecr = getSpContainer(); - EscherSpRecord spRecord = ecr.getChildById(EscherSpRecord.RECORD_ID); - spRecord.setFlags(spRecord.getFlags()|EscherSpRecord.FLAG_OLESHAPE); - - HSLFEscherClientDataRecord cldata = getClientData(true); - ExObjRefAtom uer = null; - for (Record r : cldata.getHSLFChildRecords()) { - if (r.getRecordType() == RecordTypes.ExObjRefAtom.typeID) { - uer = (ExObjRefAtom)r; - break; - } - } - if (uer == null) { - uer = new ExObjRefAtom(); - cldata.addChild(uer); - } - uer.setExObjIdRef(objectId); - } - - - /** - * Returns unique identifier for the OLE object. - * - * @return the unique identifier for the OLE object - */ - @SuppressWarnings("resource") - public HSLFObjectData getObjectData(){ - HSLFSlideShow ppt = getSheet().getSlideShow(); - HSLFObjectData[] ole = ppt.getEmbeddedObjects(); - - //persist reference - ExEmbed exEmbed = getExEmbed(); - HSLFObjectData data = null; - if(exEmbed != null) { - int ref = exEmbed.getExOleObjAtom().getObjStgDataRef(); - - for (int i = 0; i < ole.length; i++) { - if(ole[i].getExOleObjStg().getPersistId() == ref) { - data=ole[i]; - } - } - } - if (data==null) { - LOG.log(POILogger.WARN, "OLE data not found"); - } - - return data; - } - - /** - * Return the record container for this embedded object. - * - *

    - * It contains: - * 1. ExEmbedAtom.(4045) - * 2. ExOleObjAtom (4035) - * 3. CString (4026), Instance MenuName (1) used for menus and the Links dialog box. - * 4. CString (4026), Instance ProgID (2) that stores the OLE Programmatic Identifier. - * A ProgID is a string that uniquely identifies a given object. - * 5. CString (4026), Instance ClipboardName (3) that appears in the paste special dialog. - * 6. MetaFile( 4033), optional - *

    - */ - @SuppressWarnings("resource") - public ExEmbed getExEmbed(){ - if(_exEmbed == null){ - HSLFSlideShow ppt = getSheet().getSlideShow(); - - ExObjList lst = ppt.getDocumentRecord().getExObjList(false); - if(lst == null){ - LOG.log(POILogger.WARN, "ExObjList not found"); - return null; - } - - int id = getObjectID(); - Record[] ch = lst.getChildRecords(); - for (int i = 0; i < ch.length; i++) { - if(ch[i] instanceof ExEmbed){ - ExEmbed embd = (ExEmbed)ch[i]; - if( embd.getExOleObjAtom().getObjID() == id) _exEmbed = embd; - } - } - } - return _exEmbed; - } - - /** - * Returns the instance name of the embedded object, e.g. "Document" or "Workbook". - * - * @return the instance name of the embedded object - */ - public String getInstanceName(){ - return getExEmbed().getMenuName(); - } - - /** - * Returns the full name of the embedded object, - * e.g. "Microsoft Word Document" or "Microsoft Office Excel Worksheet". - * - * @return the full name of the embedded object - */ - public String getFullName(){ - return getExEmbed().getClipboardName(); - } - - /** - * Returns the ProgID that stores the OLE Programmatic Identifier. - * A ProgID is a string that uniquely identifies a given object, for example, - * "Word.Document.8" or "Excel.Sheet.8". - * - * @return the ProgID - */ - public String getProgID(){ - return getExEmbed().getProgId(); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/model/PPFont.java b/src/scratchpad/src/org/apache/poi/hslf/model/PPFont.java deleted file mode 100644 index 7de68dc76..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/model/PPFont.java +++ /dev/null @@ -1,243 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.model; - -import org.apache.poi.hslf.record.FontEntityAtom; - -/** - * Represents a Font used in a presenation. - *

    - * In PowerPoint Font is a shared resource and can be shared among text object in the presentation. - *

    - * Some commonly used fonts are predefined in static constants. - * - * @author Yegor Kozlov - */ -public final class PPFont { - /** - * ANSI character set - */ - public final static byte ANSI_CHARSET = 0; - - /** - * Default character set. - */ - public final static byte DEFAULT_CHARSET = 1; - - /** - * Symbol character set - */ - public final static byte SYMBOL_CHARSET = 2; - - - /** - * Constants for the pitch and family of the font. - * The two low-order bits specify the pitch of the font and can be one of the following values - */ - public final static byte DEFAULT_PITCH = 0; - public final static byte FIXED_PITCH = 1; - public final static byte VARIABLE_PITCH = 2; - - /** - * Don't care or don't know. - */ - public final static byte FF_DONTCARE = 0; - /** - * Fonts with variable stroke width (proportional) and with serifs. Times New Roman is an example. - */ - public final static byte FF_ROMAN = 16; - /** - * Fonts with variable stroke width (proportional) and without serifs. Arial is an example. - */ - public final static byte FF_SWISS = 32; - /** - * Fonts designed to look like handwriting. Script and Cursive are examples. - */ - public final static byte FF_SCRIPT = 64; - /** - * Fonts with constant stroke width (monospace), with or without serifs. - * Monospace fonts are usually modern. CourierNew is an example - */ - public final static byte FF_MODERN = 48; - /** - * Novelty fonts. Old English is an example - */ - public final static byte FF_DECORATIVE = 80; - - - private int charset; - private int type; - private int flags; - private int pitch; - private String name; - - /** - * Creates a new instance of PPFont - */ - public PPFont(){ - - } - - /** - * Creates a new instance of PPFont and initialize it from the supplied font atom - */ - public PPFont(FontEntityAtom fontAtom){ - name = fontAtom.getFontName(); - charset = fontAtom.getCharSet(); - type = fontAtom.getFontType(); - flags = fontAtom.getFontFlags(); - pitch = fontAtom.getPitchAndFamily(); - } - - /** - * set the name for the font (i.e. Arial) - * - * @param val String representing the name of the font to use - */ - public void setFontName(String val){ - name = val; - } - - /** - * get the name for the font (i.e. Arial) - * - * @return String representing the name of the font to use - */ - public String getFontName(){ - return name; - } - - /** - * set the character set - * - * @param val - characterset - */ - public void setCharSet(int val){ - charset = val; - } - - /** - * get the character set - * - * @return charset - characterset - */ - public int getCharSet(){ - return charset; - } - - /** - * set the font flags - * Bit 1: If set, font is subsetted - * - * @param val - the font flags - */ - public void setFontFlags(int val){ - flags = val; - } - - /** - * get the character set - * Bit 1: If set, font is subsetted - * - * @return the font flags - */ - public int getFontFlags(){ - return flags; - } - - /** - * set the font type - *

    - * Bit 1: Raster Font - * Bit 2: Device Font - * Bit 3: TrueType Font - *

    - * - * @param val - the font type - */ - public void setFontType(int val){ - type = val; - } - - /** - * get the font type - *

    - * Bit 1: Raster Font - * Bit 2: Device Font - * Bit 3: TrueType Font - *

    - * - * @return the font type - */ - public int getFontType(){ - return type; - } - - /** - * set lfPitchAndFamily - * - * - * @param val - Corresponds to the lfPitchAndFamily field of the Win32 API LOGFONT structure - */ - public void setPitchAndFamily(int val){ - pitch = val; - } - - /** - * get lfPitchAndFamily - * - * @return corresponds to the lfPitchAndFamily field of the Win32 API LOGFONT structure - */ - public int getPitchAndFamily(){ - return pitch; - } - - public static final PPFont ARIAL; - public static final PPFont TIMES_NEW_ROMAN ; - public static final PPFont COURIER_NEW; - public static final PPFont WINGDINGS; - static { - ARIAL = new PPFont(); - ARIAL.setFontName("Arial"); - ARIAL.setCharSet(ANSI_CHARSET); - ARIAL.setFontType(4); - ARIAL.setFontFlags(0); - ARIAL.setPitchAndFamily(VARIABLE_PITCH | FF_SWISS); - - TIMES_NEW_ROMAN = new PPFont(); - TIMES_NEW_ROMAN.setFontName("Times New Roman"); - TIMES_NEW_ROMAN.setCharSet(ANSI_CHARSET); - TIMES_NEW_ROMAN.setFontType(4); - TIMES_NEW_ROMAN.setFontFlags(0); - TIMES_NEW_ROMAN.setPitchAndFamily(VARIABLE_PITCH | FF_ROMAN); - - COURIER_NEW = new PPFont(); - COURIER_NEW.setFontName("Courier New"); - COURIER_NEW.setCharSet(ANSI_CHARSET); - COURIER_NEW.setFontType(4); - COURIER_NEW.setFontFlags(0); - COURIER_NEW.setPitchAndFamily(FIXED_PITCH | FF_MODERN); - - WINGDINGS = new PPFont(); - WINGDINGS.setFontName("Wingdings"); - WINGDINGS.setCharSet(SYMBOL_CHARSET); - WINGDINGS.setFontType(4); - WINGDINGS.setFontFlags(0); - WINGDINGS.setPitchAndFamily(VARIABLE_PITCH | FF_DONTCARE); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/model/PPGraphics2D.java b/src/scratchpad/src/org/apache/poi/hslf/model/PPGraphics2D.java deleted file mode 100644 index 2d4e3aeca..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/model/PPGraphics2D.java +++ /dev/null @@ -1,1854 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.model; - - -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Composite; -import java.awt.Font; -import java.awt.FontMetrics; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.GraphicsConfiguration; -import java.awt.GraphicsEnvironment; -import java.awt.Image; -import java.awt.Paint; -import java.awt.Rectangle; -import java.awt.RenderingHints; -import java.awt.Shape; -import java.awt.Stroke; -import java.awt.Toolkit; -import java.awt.font.FontRenderContext; -import java.awt.font.GlyphVector; -import java.awt.font.TextLayout; -import java.awt.geom.AffineTransform; -import java.awt.geom.Arc2D; -import java.awt.geom.Ellipse2D; -import java.awt.geom.GeneralPath; -import java.awt.geom.Line2D; -import java.awt.geom.Path2D; -import java.awt.geom.RoundRectangle2D; -import java.awt.image.BufferedImage; -import java.awt.image.BufferedImageOp; -import java.awt.image.ImageObserver; -import java.awt.image.RenderedImage; -import java.awt.image.renderable.RenderableImage; -import java.text.AttributedCharacterIterator; -import java.util.Map; - -import org.apache.poi.hslf.exceptions.HSLFException; -import org.apache.poi.hslf.usermodel.HSLFFreeformShape; -import org.apache.poi.hslf.usermodel.HSLFGroupShape; -import org.apache.poi.hslf.usermodel.HSLFSimpleShape; -import org.apache.poi.hslf.usermodel.HSLFTextBox; -import org.apache.poi.hslf.usermodel.HSLFTextRun; -import org.apache.poi.sl.draw.DrawPaint; -import org.apache.poi.sl.usermodel.StrokeStyle; -import org.apache.poi.sl.usermodel.VerticalAlignment; -import org.apache.poi.util.NotImplemented; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.util.SuppressForbidden; - -/** - * Translates Graphics2D calls into PowerPoint. - */ -public final class PPGraphics2D extends Graphics2D implements Cloneable { - - private static final POILogger LOG = POILogFactory.getLogger(PPGraphics2D.class); - - //The ppt object to write into. - private HSLFGroupShape _group; - - private AffineTransform _transform; - private Stroke _stroke; - private Paint _paint; - private Font _font; - private Color _foreground; - private Color _background; - private RenderingHints _hints; - - /** - * Construct Java Graphics object which translates graphic calls in ppt drawing layer. - * - * @param group The shape group to write the graphics calls into. - */ - public PPGraphics2D(HSLFGroupShape group){ - this._group = group; - - _transform = new AffineTransform(); - _stroke = new BasicStroke(); - _paint = Color.black; - _font = new Font("Arial", Font.PLAIN, 12); - _background = Color.black; - _foreground = Color.white; - _hints = new RenderingHints(null); - } - - /** - * @return the shape group being used for drawing - */ - public HSLFGroupShape getShapeGroup(){ - return _group; - } - - /** - * Gets the current font. - * @return this graphics context's current font. - * @see java.awt.Font - * @see java.awt.Graphics#setFont(Font) - */ - public Font getFont(){ - return _font; - } - - /** - * Sets this graphics context's font to the specified font. - * All subsequent text operations using this graphics context - * use this font. - * @param font the font. - * @see java.awt.Graphics#getFont - * @see java.awt.Graphics#drawString(java.lang.String, int, int) - * @see java.awt.Graphics#drawBytes(byte[], int, int, int, int) - * @see java.awt.Graphics#drawChars(char[], int, int, int, int) - */ - public void setFont(Font font){ - this._font = font; - } - - /** - * Gets this graphics context's current color. - * @return this graphics context's current color. - * @see java.awt.Color - * @see java.awt.Graphics#setColor - */ - public Color getColor(){ - return _foreground; - } - - /** - * Sets this graphics context's current color to the specified - * color. All subsequent graphics operations using this graphics - * context use this specified color. - * @param c the new rendering color. - * @see java.awt.Color - * @see java.awt.Graphics#getColor - */ - public void setColor(Color c) { - setPaint(c); - } - - /** - * Returns the current Stroke in the - * Graphics2D context. - * @return the current Graphics2D Stroke, - * which defines the line style. - * @see #setStroke - */ - public Stroke getStroke(){ - return _stroke; - } - - /** - * Sets the Stroke for the Graphics2D context. - * @param s the Stroke object to be used to stroke a - * Shape during the rendering process - */ - public void setStroke(Stroke s){ - this._stroke = s; - } - - /** - * Returns the current Paint of the - * Graphics2D context. - * @return the current Graphics2D Paint, - * which defines a color or pattern. - * @see #setPaint - * @see java.awt.Graphics#setColor - */ - public Paint getPaint(){ - return _paint; - } - - /** - * Sets the Paint attribute for the - * Graphics2D context. Calling this method - * with a null Paint object does - * not have any effect on the current Paint attribute - * of this Graphics2D. - * @param paint the Paint object to be used to generate - * color during the rendering process, or null - * @see java.awt.Graphics#setColor - */ - public void setPaint(Paint paint){ - if(paint == null) return; - - this._paint = paint; - if (paint instanceof Color) _foreground = (Color)paint; - } - - /** - * Returns a copy of the current Transform in the - * Graphics2D context. - * @return the current AffineTransform in the - * Graphics2D context. - * @see #_transform - * @see #setTransform - */ - public AffineTransform getTransform(){ - return new AffineTransform(_transform); - } - - /** - * Sets the Transform in the Graphics2D - * context. - * @param Tx the AffineTransform object to be used in the - * rendering process - * @see #_transform - * @see AffineTransform - */ - public void setTransform(AffineTransform Tx) { - _transform = new AffineTransform(Tx); - } - - /** - * Strokes the outline of a Shape using the settings of the - * current Graphics2D context. The rendering attributes - * applied include the Clip, Transform, - * Paint, Composite and - * Stroke attributes. - * @param shape the Shape to be rendered - * @see #setStroke - * @see #setPaint - * @see java.awt.Graphics#setColor - * @see #_transform - * @see #setTransform - * @see #clip - * @see #setClip - * @see #setComposite - */ - public void draw(Shape shape){ - Path2D.Double path = new Path2D.Double(_transform.createTransformedShape(shape)); - HSLFFreeformShape p = new HSLFFreeformShape(_group); - p.setPath(path); - p.getFill().setForegroundColor(null); - applyStroke(p); - if (_paint instanceof Color) { - p.setLineColor((Color)_paint); - } - _group.addShape(p); - } - - /** - * Renders the text specified by the specified String, - * using the current text attribute state in the Graphics2D context. - * The baseline of the first character is at position - * (xy) in the User Space. - * The rendering attributes applied include the Clip, - * Transform, Paint, Font and - * Composite attributes. For characters in script systems - * such as Hebrew and Arabic, the glyphs can be rendered from right to - * left, in which case the coordinate supplied is the location of the - * leftmost character on the baseline. - * @param s the String to be rendered - * @param x the x coordinate of the location where the - * String should be rendered - * @param y the y coordinate of the location where the - * String should be rendered - * @throws NullPointerException if str is - * null - * @see #setPaint - * @see java.awt.Graphics#setColor - * @see java.awt.Graphics#setFont - * @see #setTransform - * @see #setComposite - * @see #setClip - */ - public void drawString(String s, float x, float y) { - HSLFTextBox txt = new HSLFTextBox(_group); - txt.setSheet(_group.getSheet()); - txt.setText(s); - - HSLFTextRun rt = txt.getTextParagraphs().get(0).getTextRuns().get(0); - rt.setFontSize((double)_font.getSize()); - rt.setFontFamily(_font.getFamily()); - - if (getColor() != null) rt.setFontColor(DrawPaint.createSolidPaint(getColor())); - if (_font.isBold()) rt.setBold(true); - if (_font.isItalic()) rt.setItalic(true); - - txt.setBottomInset(0); - txt.setTopInset(0); - txt.setLeftInset(0); - txt.setRightInset(0); - txt.setWordWrap(false); - txt.setHorizontalCentered(false); - txt.setVerticalAlignment(VerticalAlignment.MIDDLE); - - - TextLayout layout = new TextLayout(s, _font, getFontRenderContext()); - float ascent = layout.getAscent(); - - float width = (float) Math.floor(layout.getAdvance()); - /** - * Even if top and bottom margins are set to 0 PowerPoint - * always sets extra space between the text and its bounding box. - * - * The approximation height = ascent*2 works good enough in most cases - */ - float height = ascent * 2; - - /* - In powerpoint anchor of a shape is its top left corner. - Java graphics sets string coordinates by the baseline of the first character - so we need to shift up by the height of the textbox - */ - y -= height / 2 + ascent / 2; - - /* - In powerpoint anchor of a shape is its top left corner. - Java graphics sets string coordinates by the baseline of the first character - so we need to shift down by the height of the textbox - */ - txt.setAnchor(new Rectangle((int)x, (int)y, (int)width, (int)height)); - - _group.addShape(txt); - } - - /** - * Fills the interior of a Shape using the settings of the - * Graphics2D context. The rendering attributes applied - * include the Clip, Transform, - * Paint, and Composite. - * @param shape the Shape to be filled - * @see #setPaint - * @see java.awt.Graphics#setColor - * @see #_transform - * @see #setTransform - * @see #setComposite - * @see #clip - * @see #setClip - */ - public void fill(Shape shape){ - Path2D.Double path = new Path2D.Double(_transform.createTransformedShape(shape)); - HSLFFreeformShape p = new HSLFFreeformShape(_group); - p.setPath(path); - applyPaint(p); - p.setLineColor(null); //Fills must be "No Line" - _group.addShape(p); - } - - /** - * Translates the origin of the graphics context to the point - * (xy) in the current coordinate system. - * Modifies this graphics context so that its new origin corresponds - * to the point (xy) in this graphics context's - * original coordinate system. All coordinates used in subsequent - * rendering operations on this graphics context will be relative - * to this new origin. - * @param x the x coordinate. - * @param y the y coordinate. - */ - public void translate(int x, int y){ - _transform.translate(x, y); - } - - /** - * Intersects the current Clip with the interior of the - * specified Shape and sets the Clip to the - * resulting intersection. The specified Shape is - * transformed with the current Graphics2D - * Transform before being intersected with the current - * Clip. This method is used to make the current - * Clip smaller. - * To make the Clip larger, use setClip. - * The user clip modified by this method is independent of the - * clipping associated with device bounds and visibility. If no clip has - * previously been set, or if the clip has been cleared using - * {@link java.awt.Graphics#setClip(Shape) setClip} with a - * null argument, the specified Shape becomes - * the new user clip. - * @param s the Shape to be intersected with the current - * Clip. If s is null, - * this method clears the current Clip. - */ - @NotImplemented - public void clip(Shape s){ - if (LOG.check(POILogger.WARN)) { - LOG.log(POILogger.WARN, "Not implemented"); - } - } - - /** - * Gets the current clipping area. - * This method returns the user clip, which is independent of the - * clipping associated with device bounds and window visibility. - * If no clip has previously been set, or if the clip has been - * cleared using setClip(null), this method returns - * null. - * @return a Shape object representing the - * current clipping area, or null if - * no clip is set. - * @see java.awt.Graphics#getClipBounds() - * @see java.awt.Graphics#clipRect - * @see java.awt.Graphics#setClip(int, int, int, int) - * @see java.awt.Graphics#setClip(Shape) - * @since JDK1.1 - */ - @NotImplemented - public Shape getClip(){ - if (LOG.check(POILogger.WARN)) { - LOG.log(POILogger.WARN, "Not implemented"); - } - return null; - } - - /** - * Concatenates the current Graphics2D - * Transform with a scaling transformation - * Subsequent rendering is resized according to the specified scaling - * factors relative to the previous scaling. - * This is equivalent to calling transform(S), where S is an - * AffineTransform represented by the following matrix: - *
    -     *          [   sx   0    0   ]
    -     *          [   0    sy   0   ]
    -     *          [   0    0    1   ]
    -     * 
    - * @param sx the amount by which X coordinates in subsequent - * rendering operations are multiplied relative to previous - * rendering operations. - * @param sy the amount by which Y coordinates in subsequent - * rendering operations are multiplied relative to previous - * rendering operations. - */ - public void scale(double sx, double sy){ - _transform.scale(sx, sy); - } - - /** - * Draws an outlined round-cornered rectangle using this graphics - * context's current color. The left and right edges of the rectangle - * are at x and x + width, - * respectively. The top and bottom edges of the rectangle are at - * y and y + height. - * @param x the x coordinate of the rectangle to be drawn. - * @param y the y coordinate of the rectangle to be drawn. - * @param width the width of the rectangle to be drawn. - * @param height the height of the rectangle to be drawn. - * @param arcWidth the horizontal diameter of the arc - * at the four corners. - * @param arcHeight the vertical diameter of the arc - * at the four corners. - * @see java.awt.Graphics#fillRoundRect - */ - public void drawRoundRect(int x, int y, int width, int height, - int arcWidth, int arcHeight){ - RoundRectangle2D rect = new RoundRectangle2D.Float(x, y, width, height, arcWidth, arcHeight); - draw(rect); - } - - /** - * Draws the text given by the specified string, using this - * graphics context's current font and color. The baseline of the - * first character is at position (xy) in this - * graphics context's coordinate system. - * @param str the string to be drawn. - * @param x the x coordinate. - * @param y the y coordinate. - * @see java.awt.Graphics#drawBytes - * @see java.awt.Graphics#drawChars - */ - public void drawString(String str, int x, int y){ - drawString(str, (float)x, (float)y); - } - - /** - * Fills an oval bounded by the specified rectangle with the - * current color. - * @param x the x coordinate of the upper left corner - * of the oval to be filled. - * @param y the y coordinate of the upper left corner - * of the oval to be filled. - * @param width the width of the oval to be filled. - * @param height the height of the oval to be filled. - * @see java.awt.Graphics#drawOval - */ - public void fillOval(int x, int y, int width, int height){ - Ellipse2D oval = new Ellipse2D.Float(x, y, width, height); - fill(oval); - } - - /** - * Fills the specified rounded corner rectangle with the current color. - * The left and right edges of the rectangle - * are at x and x + width - 1, - * respectively. The top and bottom edges of the rectangle are at - * y and y + height - 1. - * @param x the x coordinate of the rectangle to be filled. - * @param y the y coordinate of the rectangle to be filled. - * @param width the width of the rectangle to be filled. - * @param height the height of the rectangle to be filled. - * @param arcWidth the horizontal diameter - * of the arc at the four corners. - * @param arcHeight the vertical diameter - * of the arc at the four corners. - * @see java.awt.Graphics#drawRoundRect - */ - public void fillRoundRect(int x, int y, int width, int height, - int arcWidth, int arcHeight){ - - RoundRectangle2D rect = new RoundRectangle2D.Float(x, y, width, height, arcWidth, arcHeight); - fill(rect); - } - - /** - * Fills a circular or elliptical arc covering the specified rectangle. - *

    - * The resulting arc begins at startAngle and extends - * for arcAngle degrees. - * Angles are interpreted such that 0 degrees - * is at the 3 o'clock position. - * A positive value indicates a counter-clockwise rotation - * while a negative value indicates a clockwise rotation. - *

    - * The center of the arc is the center of the rectangle whose origin - * is (xy) and whose size is specified by the - * width and height arguments. - *

    - * The resulting arc covers an area - * width + 1 pixels wide - * by height + 1 pixels tall. - *

    - * The angles are specified relative to the non-square extents of - * the bounding rectangle such that 45 degrees always falls on the - * line from the center of the ellipse to the upper right corner of - * the bounding rectangle. As a result, if the bounding rectangle is - * noticeably longer in one axis than the other, the angles to the - * start and end of the arc segment will be skewed farther along the - * longer axis of the bounds. - * @param x the x coordinate of the - * upper-left corner of the arc to be filled. - * @param y the y coordinate of the - * upper-left corner of the arc to be filled. - * @param width the width of the arc to be filled. - * @param height the height of the arc to be filled. - * @param startAngle the beginning angle. - * @param arcAngle the angular extent of the arc, - * relative to the start angle. - * @see java.awt.Graphics#drawArc - */ - public void fillArc(int x, int y, int width, int height, - int startAngle, int arcAngle){ - Arc2D arc = new Arc2D.Float(x, y, width, height, startAngle, arcAngle, Arc2D.PIE); - fill(arc); - } - - /** - * Draws the outline of a circular or elliptical arc - * covering the specified rectangle. - *

    - * The resulting arc begins at startAngle and extends - * for arcAngle degrees, using the current color. - * Angles are interpreted such that 0 degrees - * is at the 3 o'clock position. - * A positive value indicates a counter-clockwise rotation - * while a negative value indicates a clockwise rotation. - *

    - * The center of the arc is the center of the rectangle whose origin - * is (xy) and whose size is specified by the - * width and height arguments. - *

    - * The resulting arc covers an area - * width + 1 pixels wide - * by height + 1 pixels tall. - *

    - * The angles are specified relative to the non-square extents of - * the bounding rectangle such that 45 degrees always falls on the - * line from the center of the ellipse to the upper right corner of - * the bounding rectangle. As a result, if the bounding rectangle is - * noticeably longer in one axis than the other, the angles to the - * start and end of the arc segment will be skewed farther along the - * longer axis of the bounds. - * @param x the x coordinate of the - * upper-left corner of the arc to be drawn. - * @param y the y coordinate of the - * upper-left corner of the arc to be drawn. - * @param width the width of the arc to be drawn. - * @param height the height of the arc to be drawn. - * @param startAngle the beginning angle. - * @param arcAngle the angular extent of the arc, - * relative to the start angle. - * @see java.awt.Graphics#fillArc - */ - public void drawArc(int x, int y, int width, int height, - int startAngle, int arcAngle) { - Arc2D arc = new Arc2D.Float(x, y, width, height, startAngle, arcAngle, Arc2D.OPEN); - draw(arc); - } - - - /** - * Draws a sequence of connected lines defined by - * arrays of x and y coordinates. - * Each pair of (xy) coordinates defines a point. - * The figure is not closed if the first point - * differs from the last point. - * @param xPoints an array of x points - * @param yPoints an array of y points - * @param nPoints the total number of points - * @see java.awt.Graphics#drawPolygon(int[], int[], int) - * @since JDK1.1 - */ - public void drawPolyline(int[] xPoints, int[] yPoints, - int nPoints){ - if(nPoints > 0){ - GeneralPath path = new GeneralPath(); - path.moveTo(xPoints[0], yPoints[0]); - for(int i=1; ix, y, - * width, and height arguments. - *

    - * The oval covers an area that is - * width + 1 pixels wide - * and height + 1 pixels tall. - * @param x the x coordinate of the upper left - * corner of the oval to be drawn. - * @param y the y coordinate of the upper left - * corner of the oval to be drawn. - * @param width the width of the oval to be drawn. - * @param height the height of the oval to be drawn. - * @see java.awt.Graphics#fillOval - */ - public void drawOval(int x, int y, int width, int height){ - Ellipse2D oval = new Ellipse2D.Float(x, y, width, height); - draw(oval); - } - - /** - * Draws as much of the specified image as is currently available. - * The image is drawn with its top-left corner at - * (xy) in this graphics context's coordinate - * space. Transparent pixels are drawn in the specified - * background color. - *

    - * This operation is equivalent to filling a rectangle of the - * width and height of the specified image with the given color and then - * drawing the image on top of it, but possibly more efficient. - *

    - * This method returns immediately in all cases, even if the - * complete image has not yet been loaded, and it has not been dithered - * and converted for the current output device. - *

    - * If the image has not yet been completely loaded, then - * drawImage returns false. As more of - * the image becomes available, the process that draws the image notifies - * the specified image observer. - * @param img the specified image to be drawn. - * @param x the x coordinate. - * @param y the y coordinate. - * @param bgcolor the background color to paint under the - * non-opaque portions of the image. - * @param observer object to be notified as more of - * the image is converted. - * @see java.awt.Image - * @see java.awt.image.ImageObserver - * @see java.awt.image.ImageObserver#imageUpdate(java.awt.Image, int, int, int, int, int) - */ - @NotImplemented - public boolean drawImage(Image img, int x, int y, - Color bgcolor, - ImageObserver observer){ - if (LOG.check(POILogger.WARN)) { - LOG.log(POILogger.WARN, "Not implemented"); - } - - return false; - } - - /** - * Draws as much of the specified image as has already been scaled - * to fit inside the specified rectangle. - *

    - * The image is drawn inside the specified rectangle of this - * graphics context's coordinate space, and is scaled if - * necessary. Transparent pixels are drawn in the specified - * background color. - * This operation is equivalent to filling a rectangle of the - * width and height of the specified image with the given color and then - * drawing the image on top of it, but possibly more efficient. - *

    - * This method returns immediately in all cases, even if the - * entire image has not yet been scaled, dithered, and converted - * for the current output device. - * If the current output representation is not yet complete then - * drawImage returns false. As more of - * the image becomes available, the process that draws the image notifies - * the specified image observer. - *

    - * A scaled version of an image will not necessarily be - * available immediately just because an unscaled version of the - * image has been constructed for this output device. Each size of - * the image may be cached separately and generated from the original - * data in a separate image production sequence. - * @param img the specified image to be drawn. - * @param x the x coordinate. - * @param y the y coordinate. - * @param width the width of the rectangle. - * @param height the height of the rectangle. - * @param bgcolor the background color to paint under the - * non-opaque portions of the image. - * @param observer object to be notified as more of - * the image is converted. - * @see java.awt.Image - * @see java.awt.image.ImageObserver - * @see java.awt.image.ImageObserver#imageUpdate(java.awt.Image, int, int, int, int, int) - */ - @NotImplemented - public boolean drawImage(Image img, int x, int y, - int width, int height, - Color bgcolor, - ImageObserver observer){ - if (LOG.check(POILogger.WARN)) { - LOG.log(POILogger.WARN, "Not implemented"); - } - - return false; - } - - - /** - * Draws as much of the specified area of the specified image as is - * currently available, scaling it on the fly to fit inside the - * specified area of the destination drawable surface. Transparent pixels - * do not affect whatever pixels are already there. - *

    - * This method returns immediately in all cases, even if the - * image area to be drawn has not yet been scaled, dithered, and converted - * for the current output device. - * If the current output representation is not yet complete then - * drawImage returns false. As more of - * the image becomes available, the process that draws the image notifies - * the specified image observer. - *

    - * This method always uses the unscaled version of the image - * to render the scaled rectangle and performs the required - * scaling on the fly. It does not use a cached, scaled version - * of the image for this operation. Scaling of the image from source - * to destination is performed such that the first coordinate - * of the source rectangle is mapped to the first coordinate of - * the destination rectangle, and the second source coordinate is - * mapped to the second destination coordinate. The subimage is - * scaled and flipped as needed to preserve those mappings. - * @param img the specified image to be drawn - * @param dx1 the x coordinate of the first corner of the - * destination rectangle. - * @param dy1 the y coordinate of the first corner of the - * destination rectangle. - * @param dx2 the x coordinate of the second corner of the - * destination rectangle. - * @param dy2 the y coordinate of the second corner of the - * destination rectangle. - * @param sx1 the x coordinate of the first corner of the - * source rectangle. - * @param sy1 the y coordinate of the first corner of the - * source rectangle. - * @param sx2 the x coordinate of the second corner of the - * source rectangle. - * @param sy2 the y coordinate of the second corner of the - * source rectangle. - * @param observer object to be notified as more of the image is - * scaled and converted. - * @see java.awt.Image - * @see java.awt.image.ImageObserver - * @see java.awt.image.ImageObserver#imageUpdate(java.awt.Image, int, int, int, int, int) - * @since JDK1.1 - */ - @NotImplemented - public boolean drawImage(Image img, - int dx1, int dy1, int dx2, int dy2, - int sx1, int sy1, int sx2, int sy2, - ImageObserver observer){ - if (LOG.check(POILogger.WARN)) { - LOG.log(POILogger.WARN, "Not implemented"); - } - return false; - } - - /** - * Draws as much of the specified area of the specified image as is - * currently available, scaling it on the fly to fit inside the - * specified area of the destination drawable surface. - *

    - * Transparent pixels are drawn in the specified background color. - * This operation is equivalent to filling a rectangle of the - * width and height of the specified image with the given color and then - * drawing the image on top of it, but possibly more efficient. - *

    - * This method returns immediately in all cases, even if the - * image area to be drawn has not yet been scaled, dithered, and converted - * for the current output device. - * If the current output representation is not yet complete then - * drawImage returns false. As more of - * the image becomes available, the process that draws the image notifies - * the specified image observer. - *

    - * This method always uses the unscaled version of the image - * to render the scaled rectangle and performs the required - * scaling on the fly. It does not use a cached, scaled version - * of the image for this operation. Scaling of the image from source - * to destination is performed such that the first coordinate - * of the source rectangle is mapped to the first coordinate of - * the destination rectangle, and the second source coordinate is - * mapped to the second destination coordinate. The subimage is - * scaled and flipped as needed to preserve those mappings. - * @param img the specified image to be drawn - * @param dx1 the x coordinate of the first corner of the - * destination rectangle. - * @param dy1 the y coordinate of the first corner of the - * destination rectangle. - * @param dx2 the x coordinate of the second corner of the - * destination rectangle. - * @param dy2 the y coordinate of the second corner of the - * destination rectangle. - * @param sx1 the x coordinate of the first corner of the - * source rectangle. - * @param sy1 the y coordinate of the first corner of the - * source rectangle. - * @param sx2 the x coordinate of the second corner of the - * source rectangle. - * @param sy2 the y coordinate of the second corner of the - * source rectangle. - * @param bgcolor the background color to paint under the - * non-opaque portions of the image. - * @param observer object to be notified as more of the image is - * scaled and converted. - * @see java.awt.Image - * @see java.awt.image.ImageObserver - * @see java.awt.image.ImageObserver#imageUpdate(java.awt.Image, int, int, int, int, int) - * @since JDK1.1 - */ - @NotImplemented - public boolean drawImage(Image img, - int dx1, int dy1, int dx2, int dy2, - int sx1, int sy1, int sx2, int sy2, - Color bgcolor, - ImageObserver observer){ - if (LOG.check(POILogger.WARN)) { - LOG.log(POILogger.WARN, "Not implemented"); - } - return false; - } - - /** - * Draws as much of the specified image as is currently available. - * The image is drawn with its top-left corner at - * (xy) in this graphics context's coordinate - * space. Transparent pixels in the image do not affect whatever - * pixels are already there. - *

    - * This method returns immediately in all cases, even if the - * complete image has not yet been loaded, and it has not been dithered - * and converted for the current output device. - *

    - * If the image has completely loaded and its pixels are - * no longer being changed, then - * drawImage returns true. - * Otherwise, drawImage returns false - * and as more of - * the image becomes available - * or it is time to draw another frame of animation, - * the process that loads the image notifies - * the specified image observer. - * @param img the specified image to be drawn. This method does - * nothing if img is null. - * @param x the x coordinate. - * @param y the y coordinate. - * @param observer object to be notified as more of - * the image is converted. - * @return false if the image pixels are still changing; - * true otherwise. - * @see java.awt.Image - * @see java.awt.image.ImageObserver - * @see java.awt.image.ImageObserver#imageUpdate(java.awt.Image, int, int, int, int, int) - */ - @NotImplemented - public boolean drawImage(Image img, int x, int y, - ImageObserver observer) { - if (LOG.check(POILogger.WARN)) { - LOG.log(POILogger.WARN, "Not implemented"); - } - return false; - } - - /** - * Disposes of this graphics context and releases - * any system resources that it is using. - * A Graphics object cannot be used after - * disposehas been called. - *

    - * When a Java program runs, a large number of Graphics - * objects can be created within a short time frame. - * Although the finalization process of the garbage collector - * also disposes of the same system resources, it is preferable - * to manually free the associated resources by calling this - * method rather than to rely on a finalization process which - * may not run to completion for a long period of time. - *

    - * Graphics objects which are provided as arguments to the - * paint and update methods - * of components are automatically released by the system when - * those methods return. For efficiency, programmers should - * call dispose when finished using - * a Graphics object only if it was created - * directly from a component or another Graphics object. - * @see java.awt.Graphics#finalize - * @see java.awt.Component#paint - * @see java.awt.Component#update - * @see java.awt.Component#getGraphics - * @see java.awt.Graphics#create - */ - public void dispose() { - } - - /** - * Draws a line, using the current color, between the points - * (x1, y1) and (x2, y2) - * in this graphics context's coordinate system. - * @param x1 the first point's x coordinate. - * @param y1 the first point's y coordinate. - * @param x2 the second point's x coordinate. - * @param y2 the second point's y coordinate. - */ - public void drawLine(int x1, int y1, int x2, int y2){ - Line2D line = new Line2D.Float(x1, y1, x2, y2); - draw(line); - } - - /** - * Fills a closed polygon defined by - * arrays of x and y coordinates. - *

    - * This method draws the polygon defined by nPoint line - * segments, where the first nPoint - 1 - * line segments are line segments from - * (xPoints[i - 1], yPoints[i - 1]) - * to (xPoints[i], yPoints[i]), for - * 1 ≤ i ≤ nPoints. - * The figure is automatically closed by drawing a line connecting - * the final point to the first point, if those points are different. - *

    - * The area inside the polygon is defined using an - * even-odd fill rule, also known as the alternating rule. - * @param xPoints a an array of x coordinates. - * @param yPoints a an array of y coordinates. - * @param nPoints a the total number of points. - * @see java.awt.Graphics#drawPolygon(int[], int[], int) - */ - public void fillPolygon(int[] xPoints, int[] yPoints, - int nPoints){ - java.awt.Polygon polygon = new java.awt.Polygon(xPoints, yPoints, nPoints); - fill(polygon); - } - - /** - * Fills the specified rectangle. - * The left and right edges of the rectangle are at - * x and x + width - 1. - * The top and bottom edges are at - * y and y + height - 1. - * The resulting rectangle covers an area - * width pixels wide by - * height pixels tall. - * The rectangle is filled using the graphics context's current color. - * @param x the x coordinate - * of the rectangle to be filled. - * @param y the y coordinate - * of the rectangle to be filled. - * @param width the width of the rectangle to be filled. - * @param height the height of the rectangle to be filled. - * @see java.awt.Graphics#clearRect - * @see java.awt.Graphics#drawRect - */ - public void fillRect(int x, int y, int width, int height){ - Rectangle rect = new Rectangle(x, y, width, height); - fill(rect); - } - - /** - * Draws the outline of the specified rectangle. - * The left and right edges of the rectangle are at - * x and x + width. - * The top and bottom edges are at - * y and y + height. - * The rectangle is drawn using the graphics context's current color. - * @param x the x coordinate - * of the rectangle to be drawn. - * @param y the y coordinate - * of the rectangle to be drawn. - * @param width the width of the rectangle to be drawn. - * @param height the height of the rectangle to be drawn. - * @see java.awt.Graphics#fillRect - * @see java.awt.Graphics#clearRect - */ - public void drawRect(int x, int y, int width, int height) { - Rectangle rect = new Rectangle(x, y, width, height); - draw(rect); - } - - /** - * Draws a closed polygon defined by - * arrays of x and y coordinates. - * Each pair of (xy) coordinates defines a point. - *

    - * This method draws the polygon defined by nPoint line - * segments, where the first nPoint - 1 - * line segments are line segments from - * (xPoints[i - 1], yPoints[i - 1]) - * to (xPoints[i], yPoints[i]), for - * 1 ≤ i ≤ nPoints. - * The figure is automatically closed by drawing a line connecting - * the final point to the first point, if those points are different. - * @param xPoints a an array of x coordinates. - * @param yPoints a an array of y coordinates. - * @param nPoints a the total number of points. - * @see java.awt.Graphics#fillPolygon(int[],int[],int) - * @see java.awt.Graphics#drawPolyline - */ - public void drawPolygon(int[] xPoints, int[] yPoints, - int nPoints){ - java.awt.Polygon polygon = new java.awt.Polygon(xPoints, yPoints, nPoints); - draw(polygon); - } - - /** - * Intersects the current clip with the specified rectangle. - * The resulting clipping area is the intersection of the current - * clipping area and the specified rectangle. If there is no - * current clipping area, either because the clip has never been - * set, or the clip has been cleared using setClip(null), - * the specified rectangle becomes the new clip. - * This method sets the user clip, which is independent of the - * clipping associated with device bounds and window visibility. - * This method can only be used to make the current clip smaller. - * To set the current clip larger, use any of the setClip methods. - * Rendering operations have no effect outside of the clipping area. - * @param x the x coordinate of the rectangle to intersect the clip with - * @param y the y coordinate of the rectangle to intersect the clip with - * @param width the width of the rectangle to intersect the clip with - * @param height the height of the rectangle to intersect the clip with - * @see #setClip(int, int, int, int) - * @see #setClip(Shape) - */ - public void clipRect(int x, int y, int width, int height){ - clip(new Rectangle(x, y, width, height)); - } - - /** - * Sets the current clipping area to an arbitrary clip shape. - * Not all objects that implement the Shape - * interface can be used to set the clip. The only - * Shape objects that are guaranteed to be - * supported are Shape objects that are - * obtained via the getClip method and via - * Rectangle objects. This method sets the - * user clip, which is independent of the clipping associated - * with device bounds and window visibility. - * @param clip the Shape to use to set the clip - * @see java.awt.Graphics#getClip() - * @see java.awt.Graphics#clipRect - * @see java.awt.Graphics#setClip(int, int, int, int) - * @since JDK1.1 - */ - @NotImplemented - public void setClip(Shape clip) { - if (LOG.check(POILogger.WARN)) { - LOG.log(POILogger.WARN, "Not implemented"); - } - } - - /** - * Returns the bounding rectangle of the current clipping area. - * This method refers to the user clip, which is independent of the - * clipping associated with device bounds and window visibility. - * If no clip has previously been set, or if the clip has been - * cleared using setClip(null), this method returns - * null. - * The coordinates in the rectangle are relative to the coordinate - * system origin of this graphics context. - * @return the bounding rectangle of the current clipping area, - * or null if no clip is set. - * @see java.awt.Graphics#getClip - * @see java.awt.Graphics#clipRect - * @see java.awt.Graphics#setClip(int, int, int, int) - * @see java.awt.Graphics#setClip(Shape) - * @since JDK1.1 - */ - public Rectangle getClipBounds(){ - Shape c = getClip(); - if (c==null) { - return null; - } - return c.getBounds(); - } - - /** - * Draws the text given by the specified iterator, using this - * graphics context's current color. The iterator has to specify a font - * for each character. The baseline of the - * first character is at position (xy) in this - * graphics context's coordinate system. - * @param iterator the iterator whose text is to be drawn - * @param x the x coordinate. - * @param y the y coordinate. - * @see java.awt.Graphics#drawBytes - * @see java.awt.Graphics#drawChars - */ - public void drawString(AttributedCharacterIterator iterator, - int x, int y){ - drawString(iterator, (float)x, (float)y); - } - - /** - * Clears the specified rectangle by filling it with the background - * color of the current drawing surface. This operation does not - * use the current paint mode. - *

    - * Beginning with Java 1.1, the background color - * of offscreen images may be system dependent. Applications should - * use setColor followed by fillRect to - * ensure that an offscreen image is cleared to a specific color. - * @param x the x coordinate of the rectangle to clear. - * @param y the y coordinate of the rectangle to clear. - * @param width the width of the rectangle to clear. - * @param height the height of the rectangle to clear. - * @see java.awt.Graphics#fillRect(int, int, int, int) - * @see java.awt.Graphics#drawRect - * @see java.awt.Graphics#setColor(java.awt.Color) - * @see java.awt.Graphics#setPaintMode - * @see java.awt.Graphics#setXORMode(java.awt.Color) - */ - public void clearRect(int x, int y, int width, int height) { - Paint paint = getPaint(); - setColor(getBackground()); - fillRect(x, y, width, height); - setPaint(paint); - } - - public void copyArea(int x, int y, int width, int height, int dx, int dy) { - } - - /** - * Sets the current clip to the rectangle specified by the given - * coordinates. This method sets the user clip, which is - * independent of the clipping associated with device bounds - * and window visibility. - * Rendering operations have no effect outside of the clipping area. - * @param x the x coordinate of the new clip rectangle. - * @param y the y coordinate of the new clip rectangle. - * @param width the width of the new clip rectangle. - * @param height the height of the new clip rectangle. - * @see java.awt.Graphics#clipRect - * @see java.awt.Graphics#setClip(Shape) - * @since JDK1.1 - */ - public void setClip(int x, int y, int width, int height){ - setClip(new Rectangle(x, y, width, height)); - } - - /** - * Concatenates the current Graphics2D - * Transform with a rotation transform. - * Subsequent rendering is rotated by the specified radians relative - * to the previous origin. - * This is equivalent to calling transform(R), where R is an - * AffineTransform represented by the following matrix: - *

    -     *          [   cos(theta)    -sin(theta)    0   ]
    -     *          [   sin(theta)     cos(theta)    0   ]
    -     *          [       0              0         1   ]
    -     * 
    - * Rotating with a positive angle theta rotates points on the positive - * x axis toward the positive y axis. - * @param theta the angle of rotation in radians - */ - public void rotate(double theta){ - _transform.rotate(theta); - } - - /** - * Concatenates the current Graphics2D - * Transform with a translated rotation - * transform. Subsequent rendering is transformed by a transform - * which is constructed by translating to the specified location, - * rotating by the specified radians, and translating back by the same - * amount as the original translation. This is equivalent to the - * following sequence of calls: - *
    -     *          translate(x, y);
    -     *          rotate(theta);
    -     *          translate(-x, -y);
    -     * 
    - * Rotating with a positive angle theta rotates points on the positive - * x axis toward the positive y axis. - * @param theta the angle of rotation in radians - * @param x x coordinate of the origin of the rotation - * @param y y coordinate of the origin of the rotation - */ - public void rotate(double theta, double x, double y){ - _transform.rotate(theta, x, y); - } - - /** - * Concatenates the current Graphics2D - * Transform with a shearing transform. - * Subsequent renderings are sheared by the specified - * multiplier relative to the previous position. - * This is equivalent to calling transform(SH), where SH - * is an AffineTransform represented by the following - * matrix: - *
    -     *          [   1   shx   0   ]
    -     *          [  shy   1    0   ]
    -     *          [   0    0    1   ]
    -     * 
    - * @param shx the multiplier by which coordinates are shifted in - * the positive X axis direction as a function of their Y coordinate - * @param shy the multiplier by which coordinates are shifted in - * the positive Y axis direction as a function of their X coordinate - */ - public void shear(double shx, double shy){ - _transform.shear(shx, shy); - } - - /** - * Get the rendering context of the Font within this - * Graphics2D context. - * The {@link FontRenderContext} - * encapsulates application hints such as anti-aliasing and - * fractional metrics, as well as target device specific information - * such as dots-per-inch. This information should be provided by the - * application when using objects that perform typographical - * formatting, such as Font and - * TextLayout. This information should also be provided - * by applications that perform their own layout and need accurate - * measurements of various characteristics of glyphs such as advance - * and line height when various rendering hints have been applied to - * the text rendering. - * - * @return a reference to an instance of FontRenderContext. - * @see java.awt.font.FontRenderContext - * @see java.awt.Font#createGlyphVector(FontRenderContext,char[]) - * @see java.awt.font.TextLayout - * @since JDK1.2 - */ - public FontRenderContext getFontRenderContext() { - boolean isAntiAliased = RenderingHints.VALUE_TEXT_ANTIALIAS_ON.equals( - getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING)); - boolean usesFractionalMetrics = RenderingHints.VALUE_FRACTIONALMETRICS_ON.equals( - getRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS)); - - - return new FontRenderContext(new AffineTransform(), isAntiAliased, usesFractionalMetrics); - } - - /** - * Composes an AffineTransform object with the - * Transform in this Graphics2D according - * to the rule last-specified-first-applied. If the current - * Transform is Cx, the result of composition - * with Tx is a new Transform Cx'. Cx' becomes the - * current Transform for this Graphics2D. - * Transforming a point p by the updated Transform Cx' is - * equivalent to first transforming p by Tx and then transforming - * the result by the original Transform Cx. In other - * words, Cx'(p) = Cx(Tx(p)). A copy of the Tx is made, if necessary, - * so further modifications to Tx do not affect rendering. - * @param Tx the AffineTransform object to be composed with - * the current Transform - * @see #setTransform - * @see AffineTransform - */ - public void transform(AffineTransform Tx) { - _transform.concatenate(Tx); - } - - /** - * Renders a BufferedImage that is - * filtered with a - * {@link BufferedImageOp}. - * The rendering attributes applied include the Clip, - * Transform - * and Composite attributes. This is equivalent to: - *
    -     * img1 = op.filter(img, null);
    -     * drawImage(img1, new AffineTransform(1f,0f,0f,1f,x,y), null);
    -     * 
    - * @param img the BufferedImage to be rendered - * @param op the filter to be applied to the image before rendering - * @param x the x coordinate in user space where the image is rendered - * @param y the y coordinate in user space where the image is rendered - * @see #_transform - * @see #setTransform - * @see #setComposite - * @see #clip - * @see #setClip(Shape) - */ - public void drawImage(BufferedImage img, - BufferedImageOp op, - int x, - int y){ - img = op.filter(img, null); - drawImage(img, x, y, null); - } - - /** - * Sets the background color for the Graphics2D context. - * The background color is used for clearing a region. - * When a Graphics2D is constructed for a - * Component, the background color is - * inherited from the Component. Setting the background color - * in the Graphics2D context only affects the subsequent - * clearRect calls and not the background color of the - * Component. To change the background - * of the Component, use appropriate methods of - * the Component. - * @param color the background color that isused in - * subsequent calls to clearRect - * @see #getBackground - * @see java.awt.Graphics#clearRect - */ - public void setBackground(Color color) { - if(color == null) - return; - - _background = color; - } - - /** - * Returns the background color used for clearing a region. - * @return the current Graphics2D Color, - * which defines the background color. - * @see #setBackground - */ - public Color getBackground(){ - return _background; - } - - /** - * Sets the Composite for the Graphics2D context. - * The Composite is used in all drawing methods such as - * drawImage, drawString, draw, - * and fill. It specifies how new pixels are to be combined - * with the existing pixels on the graphics device during the rendering - * process. - *

    If this Graphics2D context is drawing to a - * Component on the display screen and the - * Composite is a custom object rather than an - * instance of the AlphaComposite class, and if - * there is a security manager, its checkPermission - * method is called with an AWTPermission("readDisplayPixels") - * permission. - * - * @param comp the Composite object to be used for rendering - * @throws SecurityException - * if a custom Composite object is being - * used to render to the screen and a security manager - * is set and its checkPermission method - * does not allow the operation. - * @see java.awt.Graphics#setXORMode - * @see java.awt.Graphics#setPaintMode - * @see java.awt.AlphaComposite - */ - @NotImplemented - public void setComposite(Composite comp){ - if (LOG.check(POILogger.WARN)) { - LOG.log(POILogger.WARN, "Not implemented"); - } - } - - /** - * Returns the current Composite in the - * Graphics2D context. - * @return the current Graphics2D Composite, - * which defines a compositing style. - * @see #setComposite - */ - @NotImplemented - public Composite getComposite(){ - if (LOG.check(POILogger.WARN)) { - LOG.log(POILogger.WARN, "Not implemented"); - } - return null; - } - - /** - * Returns the value of a single preference for the rendering algorithms. - * Hint categories include controls for rendering quality and overall - * time/quality trade-off in the rendering process. Refer to the - * RenderingHints class for definitions of some common - * keys and values. - * @param hintKey the key corresponding to the hint to get. - * @return an object representing the value for the specified hint key. - * Some of the keys and their associated values are defined in the - * RenderingHints class. - * @see RenderingHints - */ - public Object getRenderingHint(RenderingHints.Key hintKey){ - return _hints.get(hintKey); - } - - /** - * Sets the value of a single preference for the rendering algorithms. - * Hint categories include controls for rendering quality and overall - * time/quality trade-off in the rendering process. Refer to the - * RenderingHints class for definitions of some common - * keys and values. - * @param hintKey the key of the hint to be set. - * @param hintValue the value indicating preferences for the specified - * hint category. - * @see RenderingHints - */ - public void setRenderingHint(RenderingHints.Key hintKey, Object hintValue){ - _hints.put(hintKey, hintValue); - } - - - /** - * Renders the text of the specified - * {@link GlyphVector} using - * the Graphics2D context's rendering attributes. - * The rendering attributes applied include the Clip, - * Transform, Paint, and - * Composite attributes. The GlyphVector - * specifies individual glyphs from a {@link Font}. - * The GlyphVector can also contain the glyph positions. - * This is the fastest way to render a set of characters to the - * screen. - * - * @param g the GlyphVector to be rendered - * @param x the x position in user space where the glyphs should be - * rendered - * @param y the y position in user space where the glyphs should be - * rendered - * - * @see java.awt.Font#createGlyphVector(FontRenderContext, char[]) - * @see java.awt.font.GlyphVector - * @see #setPaint - * @see java.awt.Graphics#setColor - * @see #setTransform - * @see #setComposite - * @see #setClip(Shape) - */ - public void drawGlyphVector(GlyphVector g, float x, float y) { - Shape glyphOutline = g.getOutline(x, y); - fill(glyphOutline); - } - - /** - * Returns the device configuration associated with this - * Graphics2D. - * @return the device configuration - */ - public GraphicsConfiguration getDeviceConfiguration() { - return GraphicsEnvironment.getLocalGraphicsEnvironment(). - getDefaultScreenDevice().getDefaultConfiguration(); - } - - /** - * Sets the values of an arbitrary number of preferences for the - * rendering algorithms. - * Only values for the rendering hints that are present in the - * specified Map object are modified. - * All other preferences not present in the specified - * object are left unmodified. - * Hint categories include controls for rendering quality and - * overall time/quality trade-off in the rendering process. - * Refer to the RenderingHints class for definitions of - * some common keys and values. - * @param hints the rendering hints to be set - * @see RenderingHints - */ - public void addRenderingHints(Map hints){ - this._hints.putAll(hints); - } - - /** - * Concatenates the current - * Graphics2D Transform - * with a translation transform. - * Subsequent rendering is translated by the specified - * distance relative to the previous position. - * This is equivalent to calling transform(T), where T is an - * AffineTransform represented by the following matrix: - *

    -     *          [   1    0    tx  ]
    -     *          [   0    1    ty  ]
    -     *          [   0    0    1   ]
    -     * 
    - * @param tx the distance to translate along the x-axis - * @param ty the distance to translate along the y-axis - */ - public void translate(double tx, double ty){ - _transform.translate(tx, ty); - } - - /** - * Renders the text of the specified iterator, using the - * Graphics2D context's current Paint. The - * iterator must specify a font - * for each character. The baseline of the - * first character is at position (xy) in the - * User Space. - * The rendering attributes applied include the Clip, - * Transform, Paint, and - * Composite attributes. - * For characters in script systems such as Hebrew and Arabic, - * the glyphs can be rendered from right to left, in which case the - * coordinate supplied is the location of the leftmost character - * on the baseline. - * @param iterator the iterator whose text is to be rendered - * @param x the x coordinate where the iterator's text is to be - * rendered - * @param y the y coordinate where the iterator's text is to be - * rendered - * @see #setPaint - * @see java.awt.Graphics#setColor - * @see #setTransform - * @see #setComposite - * @see #setClip - */ - @NotImplemented - public void drawString(AttributedCharacterIterator iterator, float x, float y) { - if (LOG.check(POILogger.WARN)) { - LOG.log(POILogger.WARN, "Not implemented"); - } - } - - /** - * Checks whether or not the specified Shape intersects - * the specified {@link Rectangle}, which is in device - * space. If onStroke is false, this method checks - * whether or not the interior of the specified Shape - * intersects the specified Rectangle. If - * onStroke is true, this method checks - * whether or not the Stroke of the specified - * Shape outline intersects the specified - * Rectangle. - * The rendering attributes taken into account include the - * Clip, Transform, and Stroke - * attributes. - * @param rect the area in device space to check for a hit - * @param s the Shape to check for a hit - * @param onStroke flag used to choose between testing the - * stroked or the filled shape. If the flag is true, the - * Stroke oultine is tested. If the flag is - * false, the filled Shape is tested. - * @return true if there is a hit; false - * otherwise. - * @see #setStroke - * @see #fill(Shape) - * @see #draw(Shape) - * @see #_transform - * @see #setTransform - * @see #clip - * @see #setClip(Shape) - */ - public boolean hit(Rectangle rect, - Shape s, - boolean onStroke){ - if (onStroke) { - s = getStroke().createStrokedShape(s); - } - - s = getTransform().createTransformedShape(s); - - return s.intersects(rect); - } - - /** - * Gets the preferences for the rendering algorithms. Hint categories - * include controls for rendering quality and overall time/quality - * trade-off in the rendering process. - * Returns all of the hint key/value pairs that were ever specified in - * one operation. Refer to the - * RenderingHints class for definitions of some common - * keys and values. - * @return a reference to an instance of RenderingHints - * that contains the current preferences. - * @see RenderingHints - */ - public RenderingHints getRenderingHints(){ - return _hints; - } - - /** - * Replaces the values of all preferences for the rendering - * algorithms with the specified hints. - * The existing values for all rendering hints are discarded and - * the new set of known hints and values are initialized from the - * specified {@link Map} object. - * Hint categories include controls for rendering quality and - * overall time/quality trade-off in the rendering process. - * Refer to the RenderingHints class for definitions of - * some common keys and values. - * @param hints the rendering hints to be set - * @see RenderingHints - */ - public void setRenderingHints(Map hints){ - this._hints = new RenderingHints(null); - this._hints.putAll(hints); - } - - /** - * Renders an image, applying a transform from image space into user space - * before drawing. - * The transformation from user space into device space is done with - * the current Transform in the Graphics2D. - * The specified transformation is applied to the image before the - * transform attribute in the Graphics2D context is applied. - * The rendering attributes applied include the Clip, - * Transform, and Composite attributes. - * Note that no rendering is done if the specified transform is - * noninvertible. - * @param img the Image to be rendered - * @param xform the transformation from image space into user space - * @param obs the {@link ImageObserver} - * to be notified as more of the Image - * is converted - * @return true if the Image is - * fully loaded and completely rendered; - * false if the Image is still being loaded. - * @see #_transform - * @see #setTransform - * @see #setComposite - * @see #clip - * @see #setClip(Shape) - */ - @NotImplemented - public boolean drawImage(Image img, AffineTransform xform, ImageObserver obs) { - if (LOG.check(POILogger.WARN)) { - LOG.log(POILogger.WARN, "Not implemented"); - } - return false; - } - - /** - * Draws as much of the specified image as has already been scaled - * to fit inside the specified rectangle. - *

    - * The image is drawn inside the specified rectangle of this - * graphics context's coordinate space, and is scaled if - * necessary. Transparent pixels do not affect whatever pixels - * are already there. - *

    - * This method returns immediately in all cases, even if the - * entire image has not yet been scaled, dithered, and converted - * for the current output device. - * If the current output representation is not yet complete, then - * drawImage returns false. As more of - * the image becomes available, the process that loads the image notifies - * the image observer by calling its imageUpdate method. - *

    - * A scaled version of an image will not necessarily be - * available immediately just because an unscaled version of the - * image has been constructed for this output device. Each size of - * the image may be cached separately and generated from the original - * data in a separate image production sequence. - * @param img the specified image to be drawn. This method does - * nothing if img is null. - * @param x the x coordinate. - * @param y the y coordinate. - * @param width the width of the rectangle. - * @param height the height of the rectangle. - * @param observer object to be notified as more of - * the image is converted. - * @return false if the image pixels are still changing; - * true otherwise. - * @see java.awt.Image - * @see java.awt.image.ImageObserver - * @see java.awt.image.ImageObserver#imageUpdate(java.awt.Image, int, int, int, int, int) - */ - @NotImplemented - public boolean drawImage(Image img, int x, int y, - int width, int height, - ImageObserver observer) { - if (LOG.check(POILogger.WARN)) { - LOG.log(POILogger.WARN, "Not implemented"); - } - return false; - } - - /** - * Creates a new Graphics object that is - * a copy of this Graphics object. - * @return a new graphics context that is a copy of - * this graphics context. - */ - public Graphics create() { - try { - return (Graphics)clone(); - } catch (CloneNotSupportedException e){ - throw new HSLFException(e); - } - } - - /** - * Gets the font metrics for the specified font. - * @return the font metrics for the specified font. - * @param f the specified font - * @see java.awt.Graphics#getFont - * @see java.awt.FontMetrics - * @see java.awt.Graphics#getFontMetrics() - */ - @SuppressWarnings("deprecation") - @SuppressForbidden - public FontMetrics getFontMetrics(Font f) { - return Toolkit.getDefaultToolkit().getFontMetrics(f); - } - - /** - * Sets the paint mode of this graphics context to alternate between - * this graphics context's current color and the new specified color. - * This specifies that logical pixel operations are performed in the - * XOR mode, which alternates pixels between the current color and - * a specified XOR color. - *

    - * When drawing operations are performed, pixels which are the - * current color are changed to the specified color, and vice versa. - *

    - * Pixels that are of colors other than those two colors are changed - * in an unpredictable but reversible manner; if the same figure is - * drawn twice, then all pixels are restored to their original values. - * @param c1 the XOR alternation color - */ - @NotImplemented - public void setXORMode(Color c1) { - if (LOG.check(POILogger.WARN)) { - LOG.log(POILogger.WARN, "Not implemented"); - } - } - - /** - * Sets the paint mode of this graphics context to overwrite the - * destination with this graphics context's current color. - * This sets the logical pixel operation function to the paint or - * overwrite mode. All subsequent rendering operations will - * overwrite the destination with the current color. - */ - @NotImplemented - public void setPaintMode() { - if (LOG.check(POILogger.WARN)) { - LOG.log(POILogger.WARN, "Not implemented"); - } - } - - /** - * Renders a - * {@link RenderableImage}, - * applying a transform from image space into user space before drawing. - * The transformation from user space into device space is done with - * the current Transform in the Graphics2D. - * The specified transformation is applied to the image before the - * transform attribute in the Graphics2D context is applied. - * The rendering attributes applied include the Clip, - * Transform, and Composite attributes. Note - * that no rendering is done if the specified transform is - * noninvertible. - *

    - * Rendering hints set on the Graphics2D object might - * be used in rendering the RenderableImage. - * If explicit control is required over specific hints recognized by a - * specific RenderableImage, or if knowledge of which hints - * are used is required, then a RenderedImage should be - * obtained directly from the RenderableImage - * and rendered using - *{@link #drawRenderedImage(RenderedImage, AffineTransform) drawRenderedImage}. - * @param img the image to be rendered. This method does - * nothing if img is null. - * @param xform the transformation from image space into user space - * @see #_transform - * @see #setTransform - * @see #setComposite - * @see #clip - * @see #setClip - * @see #drawRenderedImage - */ - @NotImplemented - public void drawRenderedImage(RenderedImage img, AffineTransform xform) { - if (LOG.check(POILogger.WARN)) { - LOG.log(POILogger.WARN, "Not implemented"); - } - } - - /** - * Renders a {@link RenderedImage}, - * applying a transform from image - * space into user space before drawing. - * The transformation from user space into device space is done with - * the current Transform in the Graphics2D. - * The specified transformation is applied to the image before the - * transform attribute in the Graphics2D context is applied. - * The rendering attributes applied include the Clip, - * Transform, and Composite attributes. Note - * that no rendering is done if the specified transform is - * noninvertible. - * @param img the image to be rendered. This method does - * nothing if img is null. - * @param xform the transformation from image space into user space - * @see #_transform - * @see #setTransform - * @see #setComposite - * @see #clip - * @see #setClip - */ - @NotImplemented - public void drawRenderableImage(RenderableImage img, AffineTransform xform) { - if (LOG.check(POILogger.WARN)) { - LOG.log(POILogger.WARN, "Not implemented"); - } - } - - protected void applyStroke(HSLFSimpleShape shape) { - if (_stroke instanceof BasicStroke){ - BasicStroke bs = (BasicStroke)_stroke; - shape.setLineWidth(bs.getLineWidth()); - float[] dash = bs.getDashArray(); - if (dash != null) { - //TODO: implement more dashing styles - shape.setLineDash(StrokeStyle.LineDash.DASH); - } - } - } - - protected void applyPaint(HSLFSimpleShape shape) { - if (_paint instanceof Color) { - shape.getFill().setForegroundColor((Color)_paint); - } - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/model/Polygon.java b/src/scratchpad/src/org/apache/poi/hslf/model/Polygon.java deleted file mode 100644 index 5a0b4bff1..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/model/Polygon.java +++ /dev/null @@ -1,165 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.model; - -import org.apache.poi.ddf.*; -import org.apache.poi.hslf.usermodel.*; -import org.apache.poi.sl.usermodel.ShapeContainer; -import org.apache.poi.sl.usermodel.ShapeType; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.Units; - -import java.awt.geom.Point2D; - -/** - * A simple closed polygon shape - * - * @author Yegor Kozlov - */ -public final class Polygon extends HSLFAutoShape { - /** - * Create a Polygon object and initialize it from the supplied Record container. - * - * @param escherRecord EscherSpContainer container which holds information about this shape - * @param parent the parent of the shape - */ - protected Polygon(EscherContainerRecord escherRecord, ShapeContainer parent){ - super(escherRecord, parent); - - } - - /** - * Create a new Polygon. This constructor is used when a new shape is created. - * - * @param parent the parent of this Shape. For example, if this text box is a cell - * in a table then the parent is Table. - */ - public Polygon(ShapeContainer parent){ - super((EscherContainerRecord)null, parent); - createSpContainer(ShapeType.NOT_PRIMITIVE, parent instanceof HSLFGroupShape); - } - - /** - * Create a new Polygon. This constructor is used when a new shape is created. - * - */ - public Polygon(){ - this(null); - } - - /** - * Set the polygon vertices - * - * @param xPoints - * @param yPoints - */ - public void setPoints(float[] xPoints, float[] yPoints) - { - float right = findBiggest(xPoints); - float bottom = findBiggest(yPoints); - float left = findSmallest(xPoints); - float top = findSmallest(yPoints); - - AbstractEscherOptRecord opt = getEscherOptRecord(); - opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__RIGHT, Units.pointsToMaster(right - left))); - opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__BOTTOM, Units.pointsToMaster(bottom - top))); - - for (int i = 0; i < xPoints.length; i++) { - xPoints[i] += -left; - yPoints[i] += -top; - } - - int numpoints = xPoints.length; - - EscherArrayProperty verticesProp = new EscherArrayProperty(EscherProperties.GEOMETRY__VERTICES, false, new byte[0] ); - verticesProp.setNumberOfElementsInArray(numpoints+1); - verticesProp.setNumberOfElementsInMemory(numpoints+1); - verticesProp.setSizeOfElements(0xFFF0); - for (int i = 0; i < numpoints; i++) - { - byte[] data = new byte[4]; - LittleEndian.putShort(data, 0, (short)Units.pointsToMaster(xPoints[i])); - LittleEndian.putShort(data, 2, (short)Units.pointsToMaster(yPoints[i])); - verticesProp.setElement(i, data); - } - byte[] data = new byte[4]; - LittleEndian.putShort(data, 0, (short)Units.pointsToMaster(xPoints[0])); - LittleEndian.putShort(data, 2, (short)Units.pointsToMaster(yPoints[0])); - verticesProp.setElement(numpoints, data); - opt.addEscherProperty(verticesProp); - - EscherArrayProperty segmentsProp = new EscherArrayProperty(EscherProperties.GEOMETRY__SEGMENTINFO, false, null ); - segmentsProp.setSizeOfElements(0x0002); - segmentsProp.setNumberOfElementsInArray(numpoints * 2 + 4); - segmentsProp.setNumberOfElementsInMemory(numpoints * 2 + 4); - segmentsProp.setElement(0, new byte[] { (byte)0x00, (byte)0x40 } ); - segmentsProp.setElement(1, new byte[] { (byte)0x00, (byte)0xAC } ); - for (int i = 0; i < numpoints; i++) - { - segmentsProp.setElement(2 + i * 2, new byte[] { (byte)0x01, (byte)0x00 } ); - segmentsProp.setElement(3 + i * 2, new byte[] { (byte)0x00, (byte)0xAC } ); - } - segmentsProp.setElement(segmentsProp.getNumberOfElementsInArray() - 2, new byte[] { (byte)0x01, (byte)0x60 } ); - segmentsProp.setElement(segmentsProp.getNumberOfElementsInArray() - 1, new byte[] { (byte)0x00, (byte)0x80 } ); - opt.addEscherProperty(segmentsProp); - - opt.sortProperties(); - } - - /** - * Set the polygon vertices - * - * @param points the polygon vertices - */ - public void setPoints(Point2D[] points) - { - float[] xpoints = new float[points.length]; - float[] ypoints = new float[points.length]; - for (int i = 0; i < points.length; i++) { - xpoints[i] = (float)points[i].getX(); - ypoints[i] = (float)points[i].getY(); - - } - - setPoints(xpoints, ypoints); - } - - private float findBiggest( float[] values ) - { - float result = Float.MIN_VALUE; - for ( int i = 0; i < values.length; i++ ) - { - if (values[i] > result) - result = values[i]; - } - return result; - } - - private float findSmallest( float[] values ) - { - float result = Float.MAX_VALUE; - for ( int i = 0; i < values.length; i++ ) - { - if (values[i] < result) - result = values[i]; - } - return result; - } - - -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/model/textproperties/BitMaskTextProp.java b/src/scratchpad/src/org/apache/poi/hslf/model/textproperties/BitMaskTextProp.java deleted file mode 100644 index ec0140893..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/model/textproperties/BitMaskTextProp.java +++ /dev/null @@ -1,182 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.model.textproperties; - -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; - -/** - * Definition of a special kind of property of some text, or its - * paragraph. For these properties, a flag in the "contains" header - * field tells you the data property family will exist. The value - * of the property is itself a mask, encoding several different - * (but related) properties - */ -public abstract class BitMaskTextProp extends TextProp implements Cloneable { - protected static final POILogger logger = POILogFactory.getLogger(BitMaskTextProp.class); - - private String[] subPropNames; - private int[] subPropMasks; - private boolean[] subPropMatches; - - /** Fetch the list of the names of the sub properties */ - public String[] getSubPropNames() { return subPropNames; } - /** Fetch the list of if the sub properties match or not */ - public boolean[] getSubPropMatches() { return subPropMatches; } - - protected BitMaskTextProp(int sizeOfDataBlock, int maskInHeader, String overallName, String... subPropNames) { - super(sizeOfDataBlock,maskInHeader,overallName); - this.subPropNames = subPropNames; - subPropMasks = new int[subPropNames.length]; - subPropMatches = new boolean[subPropNames.length]; - - int LSB = Integer.lowestOneBit(maskInHeader); - - // Initialise the masks list - for(int i=0; i= TxMasterStyleAtom.MAX_INDENT || - indentLevel < 0) { - throw new IllegalArgumentException("Indent must be between 0 and 4"); - } - this.indentLevel = (short)indentLevel; - } - - /** - * Update the size of the text that this set of properties - * applies to - */ - public void updateTextSize(int textSize) { - charactersCovered = textSize; - } -} \ No newline at end of file diff --git a/src/scratchpad/src/org/apache/poi/hslf/model/textproperties/ParagraphFlagsTextProp.java b/src/scratchpad/src/org/apache/poi/hslf/model/textproperties/ParagraphFlagsTextProp.java deleted file mode 100644 index d7c6072ee..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/model/textproperties/ParagraphFlagsTextProp.java +++ /dev/null @@ -1,41 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.model.textproperties; - -/** - * Definition for the common paragraph text property bitset. - * - * @author Yegor Kozlov - */ -public final class ParagraphFlagsTextProp extends BitMaskTextProp { - public static final int BULLET_IDX = 0; - public static final int BULLET_HARDFONT_IDX = 1; - public static final int BULLET_HARDCOLOR_IDX = 2; - public static final int BULLET_HARDSIZE_IDX = 4; - - public static final String NAME = "paragraph_flags"; - - public ParagraphFlagsTextProp() { - super(2, 0xF, NAME, - "bullet", - "bullet.hardfont", - "bullet.hardcolor", - "bullet.hardsize" - ); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/model/textproperties/TabStopPropCollection.java b/src/scratchpad/src/org/apache/poi/hslf/model/textproperties/TabStopPropCollection.java deleted file mode 100644 index 55267eacf..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/model/textproperties/TabStopPropCollection.java +++ /dev/null @@ -1,123 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.model.textproperties; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.LittleEndianConsts; - -/** - * Container for tabstop lists - */ -public class TabStopPropCollection extends TextProp { - public enum TabStopType { - LEFT(0), CENTER(1), RIGHT(2), DECIMAL(3); - private final int val; - TabStopType(int val) { - this.val = val; - } - public static TabStopType fromRecordVal(int val) { - for (TabStopType tst : values()) { - if (tst.val == val) return tst; - } - return LEFT; - } - } - - public static class TabStop { - /** - * If the TextPFException record that contains this TabStop structure also contains a - * leftMargin, then the value of position is relative to the left margin of the paragraph; - * otherwise, the value is relative to the left side of the paragraph. - * - * If a TextRuler record contains this TabStop structure, the value is relative to the - * left side of the text ruler. - */ - private int position; - - /** - * A enumeration that specifies how text aligns at the tab stop. - */ - private TabStopType type; - - public TabStop(int position, TabStopType type) { - this.position = position; - this.type = type; - } - - public int getPosition() { - return position; - } - - public void setPosition(int position) { - this.position = position; - } - - public TabStopType getType() { - return type; - } - - public void setType(TabStopType type) { - this.type = type; - } - } - - private List tabStops = new ArrayList(); - - public TabStopPropCollection() { - super(0, 0x100000, "tabStops"); - } - - /** - * Parses the tabstops from TxMasterStyle record - * - * @param data the data stream - * @param offset the offset within the data - */ - public void parseProperty(byte data[], int offset) { - int count = LittleEndian.getUShort(data, offset); - int off = offset + LittleEndianConsts.SHORT_SIZE; - for (int i=0; i(); - for (TabStop ts : tabStops) { - TabStop tso = new TabStop(ts.getPosition(), ts.getType()); - other.tabStops.add(tso); - } - return other; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/model/textproperties/TextAlignmentProp.java b/src/scratchpad/src/org/apache/poi/hslf/model/textproperties/TextAlignmentProp.java deleted file mode 100644 index 82430f0de..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/model/textproperties/TextAlignmentProp.java +++ /dev/null @@ -1,66 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.model.textproperties; - -/** - * Definition for the text alignment property. - */ -public class TextAlignmentProp extends TextProp { - /** - * For horizontal text, left aligned. - * For vertical text, top aligned. - */ - public static final int LEFT = 0; - - /** - * For horizontal text, centered. - * For vertical text, middle aligned. - */ - public static final int CENTER = 1; - - /** - * For horizontal text, right aligned. - * For vertical text, bottom aligned. - */ - public static final int RIGHT = 2; - - /** - * For horizontal text, flush left and right. - * For vertical text, flush top and bottom. - */ - public static final int JUSTIFY = 3; - - /** - * Distribute space between characters. - */ - public static final int DISTRIBUTED = 4; - - /** - * Thai distribution justification. - */ - public static final int THAIDISTRIBUTED = 5; - - /** - * Kashida justify low. - */ - public static final int JUSTIFYLOW = 6; - - public TextAlignmentProp() { - super(2, 0x800, "alignment"); - } -} \ No newline at end of file diff --git a/src/scratchpad/src/org/apache/poi/hslf/model/textproperties/TextPFException9.java b/src/scratchpad/src/org/apache/poi/hslf/model/textproperties/TextPFException9.java deleted file mode 100644 index 128bc8365..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/model/textproperties/TextPFException9.java +++ /dev/null @@ -1,118 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -/** - * A structure that specifies additional paragraph-level formatting - * such as Bullet Auto Number Scheme. - */ -package org.apache.poi.hslf.model.textproperties; - -import org.apache.poi.sl.usermodel.AutoNumberingScheme; -import org.apache.poi.util.LittleEndian; - -/** - * This structure store text autonumber scheme and start number. - * If a paragraph has an autonumber(fBulletHasAutoNumber = 0x0001) but start number and scheme are empty, - * this means the default values will be used: statNumber=1 and sheme=ANM_ArabicPeriod - * @see - * http://social.msdn.microsoft.com/Forums/mr-IN/os_binaryfile/thread/650888db-fabd-4b95-88dc-f0455f6e2d28 - * - * @author Alex Nikiforov [mailto:anikif@gmail.com] - * - */ -public class TextPFException9 { - //private final byte mask1; - //private final byte mask2; - private final byte mask3; - private final byte mask4; - private final Short bulletBlipRef; - private final Short fBulletHasAutoNumber; - private final AutoNumberingScheme autoNumberScheme; - private final static AutoNumberingScheme DEFAULT_AUTONUMBER_SHEME = AutoNumberingScheme.arabicPeriod; - private final Short autoNumberStartNumber; - private final static Short DEFAULT_START_NUMBER = 1; - private final int recordLength; - public TextPFException9(final byte[] source, final int startIndex) { // NOSONAR - //this.mask1 = source[startIndex]; - //this.mask2 = source[startIndex + 1]; - this.mask3 = source[startIndex + 2]; - this.mask4 = source[startIndex + 3]; - int length = 4; - int index = startIndex + 4; - if (0 == (mask3 & (byte)0x80 )) { - this.bulletBlipRef = null; - } else { - this.bulletBlipRef = LittleEndian.getShort(source, index); - index +=2; - length = 6; - } - if (0 == (mask4 & 2)) { - this.fBulletHasAutoNumber = null; - } else { - this.fBulletHasAutoNumber = LittleEndian.getShort(source, index); - index +=2; - length +=2; - } - if (0 == (mask4 & 1)) { - this.autoNumberScheme = null; - this.autoNumberStartNumber = null; - } else { - this.autoNumberScheme = AutoNumberingScheme.forNativeID(LittleEndian.getShort(source, index)); - index +=2; - this.autoNumberStartNumber = LittleEndian.getShort(source, index); - index +=2; - length +=4; - } - this.recordLength = length; - } - public Short getBulletBlipRef() { - return bulletBlipRef; - } - public Short getfBulletHasAutoNumber() { - return fBulletHasAutoNumber; - } - public AutoNumberingScheme getAutoNumberScheme() { - if (null != this.autoNumberScheme) { - return this.autoNumberScheme; - } - if (null != this.fBulletHasAutoNumber && 1 == this.fBulletHasAutoNumber.shortValue()) { - return DEFAULT_AUTONUMBER_SHEME; - } - return null; - } - public Short getAutoNumberStartNumber() { - if (null != this.autoNumberStartNumber) { - return this.autoNumberStartNumber; - } - if (null != this.fBulletHasAutoNumber && 1 == this.fBulletHasAutoNumber.shortValue()) { - return DEFAULT_START_NUMBER; - } - return null; - } - public int getRecordLength() { - return recordLength; - } - @Override - public String toString() { - final StringBuilder sb = new StringBuilder("Record length: ").append(this.recordLength).append(" bytes\n"); - sb.append("bulletBlipRef: ").append(this.bulletBlipRef).append("\n"); - sb.append("fBulletHasAutoNumber: ").append(this.fBulletHasAutoNumber).append("\n"); - sb.append("autoNumberScheme: ").append(this.autoNumberScheme).append("\n"); - sb.append("autoNumberStartNumber: ").append(this.autoNumberStartNumber).append("\n"); - return sb.toString(); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/model/textproperties/TextProp.java b/src/scratchpad/src/org/apache/poi/hslf/model/textproperties/TextProp.java deleted file mode 100644 index 9333968f0..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/model/textproperties/TextProp.java +++ /dev/null @@ -1,155 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.model.textproperties; - -import java.util.Locale; - -/** - * Definition of a property of some text, or its paragraph. Defines - * how to find out if it's present (via the mask on the paragraph or - * character "contains" header field), how long the value of it is, - * and how to get and set the value. - * - * As the exact form of these (such as mask value, size of data - * block etc) is different for StyleTextProps and - * TxMasterTextProps, the definitions of the standard - * TextProps is stored in the different record classes - */ -public class TextProp implements Cloneable { - private int sizeOfDataBlock; // Number of bytes the data part uses - private String propName; - private int dataValue; - private int maskInHeader; - - /** - * Generate the definition of a given type of text property. - */ - public TextProp(int sizeOfDataBlock, int maskInHeader, String propName) { - this.sizeOfDataBlock = sizeOfDataBlock; - this.maskInHeader = maskInHeader; - this.propName = propName; - this.dataValue = 0; - } - - /** - * Clones the property - */ - public TextProp(TextProp other) { - this.sizeOfDataBlock = other.sizeOfDataBlock; - this.maskInHeader = other.maskInHeader; - this.propName = other.propName; - this.dataValue = other.dataValue; - } - - /** - * Name of the text property - */ - public String getName() { return propName; } - - /** - * Size of the data section of the text property (2 or 4 bytes) - */ - public int getSize() { return sizeOfDataBlock; } - - /** - * Mask in the paragraph or character "contains" header field - * that indicates that this text property is present. - */ - public int getMask() { return maskInHeader; } - /** - * Get the mask that's used at write time. Only differs from - * the result of getMask() for the mask based properties - */ - public int getWriteMask() { return getMask(); } - - /** - * Fetch the value of the text property (meaning is specific to - * each different kind of text property) - */ - public int getValue() { return dataValue; } - - /** - * Set the value of the text property. - */ - public void setValue(int val) { dataValue = val; } - - /** - * Clone, eg when you want to actually make use of one of these. - */ - @Override - public TextProp clone(){ - try { - return (TextProp)super.clone(); - } catch(CloneNotSupportedException e) { - throw new InternalError(e.getMessage()); - } - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + dataValue; - result = prime * result + maskInHeader; - result = prime * result + ((propName == null) ? 0 : propName.hashCode()); - result = prime * result + sizeOfDataBlock; - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - TextProp other = (TextProp) obj; - if (dataValue != other.dataValue) { - return false; - } - if (maskInHeader != other.maskInHeader) { - return false; - } - if (propName == null) { - if (other.propName != null) { - return false; - } - } else if (!propName.equals(other.propName)) { - return false; - } - if (sizeOfDataBlock != other.sizeOfDataBlock) { - return false; - } - return true; - } - - @Override - public String toString() { - int len; - switch (sizeOfDataBlock) { - case 1: len = 4; break; - case 2: len = 6; break; - default: len = 10; break; - } - return String.format(Locale.ROOT, "%s = %d (%0#"+len+"X mask / %d bytes)", propName, dataValue, maskInHeader, sizeOfDataBlock); - } -} \ No newline at end of file diff --git a/src/scratchpad/src/org/apache/poi/hslf/model/textproperties/TextPropCollection.java b/src/scratchpad/src/org/apache/poi/hslf/model/textproperties/TextPropCollection.java deleted file mode 100644 index e82b966e6..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/model/textproperties/TextPropCollection.java +++ /dev/null @@ -1,389 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.model.textproperties; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.poi.hslf.exceptions.HSLFException; -import org.apache.poi.hslf.record.StyleTextPropAtom; -import org.apache.poi.util.HexDump; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; - -/** - * For a given run of characters, holds the properties (which could - * be paragraph properties or character properties). - * Used to hold the number of characters affected, the list of active - * properties, and the indent level if required. - */ -public class TextPropCollection { - private static final POILogger LOG = POILogFactory.getLogger(TextPropCollection.class); - - /** All the different kinds of paragraph properties we might handle */ - private static final TextProp[] paragraphTextPropTypes = { - // TextProp order is according to 2.9.20 TextPFException, - // bitmask order can be different - new ParagraphFlagsTextProp(), - new TextProp(2, 0x80, "bullet.char"), - new TextProp(2, 0x10, "bullet.font"), - new TextProp(2, 0x40, "bullet.size"), - new TextProp(4, 0x20, "bullet.color"), - new TextAlignmentProp(), - new TextProp(2, 0x1000, "linespacing"), - new TextProp(2, 0x2000, "spacebefore"), - new TextProp(2, 0x4000, "spaceafter"), - new TextProp(2, 0x100, "text.offset"), // left margin - // 0x200 - Undefined and MUST be ignored - new TextProp(2, 0x400, "bullet.offset"), // indent - new TextProp(2, 0x8000, "defaultTabSize"), - new TabStopPropCollection(), // tabstops size is variable! - new FontAlignmentProp(), - new WrapFlagsTextProp(), - new TextProp(2, 0x200000, "textDirection"), - // 0x400000 MUST be zero and MUST be ignored - new TextProp(0, 0x800000, "bullet.blip"), // TODO: check size - new TextProp(0, 0x1000000, "bullet.scheme"), // TODO: check size - new TextProp(0, 0x2000000, "hasBulletScheme"), // TODO: check size - // 0xFC000000 MUST be zero and MUST be ignored - }; - - /** All the different kinds of character properties we might handle */ - private static final TextProp[] characterTextPropTypes = new TextProp[] { - new TextProp(0, 0x100000, "pp10ext"), - new TextProp(0, 0x1000000, "newAsian.font.index"), // A bit that specifies whether the newEAFontRef field of the TextCFException10 structure that contains this CFMasks exists. - new TextProp(0, 0x2000000, "cs.font.index"), // A bit that specifies whether the csFontRef field of the TextCFException10 structure that contains this CFMasks exists. - new TextProp(0, 0x4000000, "pp11ext"), // A bit that specifies whether the pp11ext field of the TextCFException10 structure that contains this CFMasks exists. - new CharFlagsTextProp(), - new TextProp(2, 0x10000, "font.index"), - new TextProp(2, 0x200000, "asian.font.index"), - new TextProp(2, 0x400000, "ansi.font.index"), - new TextProp(2, 0x800000, "symbol.font.index"), - new TextProp(2, 0x20000, "font.size"), - new TextProp(4, 0x40000, "font.color"), - new TextProp(2, 0x80000, "superscript") - }; - - public enum TextPropType { - paragraph, character - } - - private int charactersCovered; - - // indentLevel is only valid for paragraph collection - // if it's set to -1, it must be omitted - see 2.9.36 TextMasterStyleLevel - private short indentLevel = 0; - private final Map textProps = new HashMap(); - private int maskSpecial = 0; - private final TextPropType textPropType; - - /** - * Create a new collection of text properties (be they paragraph - * or character) which will be groked via a subsequent call to - * buildTextPropList(). - */ - public TextPropCollection(int charactersCovered, TextPropType textPropType) { - this.charactersCovered = charactersCovered; - this.textPropType = textPropType; - } - - public int getSpecialMask() { - return maskSpecial; - } - - /** Fetch the number of characters this styling applies to */ - public int getCharactersCovered() { - return charactersCovered; - } - - /** Fetch the TextProps that define this styling in the record order */ - public List getTextPropList() { - List orderedList = new ArrayList(); - for (TextProp potProp : getPotentialProperties()) { - TextProp textProp = textProps.get(potProp.getName()); - if (textProp != null) { - orderedList.add(textProp); - } - } - return orderedList; - } - - /** Fetch the TextProp with this name, or null if it isn't present */ - public final TextProp findByName(String textPropName) { - return textProps.get(textPropName); - } - - public final TextProp removeByName(String name) { - return textProps.remove(name); - } - - public final TextPropType getTextPropType() { - return textPropType; - } - - private TextProp[] getPotentialProperties() { - return (textPropType == TextPropType.paragraph) ? paragraphTextPropTypes : characterTextPropTypes; - } - - /** - * Checks the paragraph or character properties for the given property name. - * Throws a HSLFException, if the name doesn't belong into this set of properties - * - * @param name the property name - * @return if found, the property template to copy from - */ - private TextProp validatePropName(String name) { - for (TextProp tp : getPotentialProperties()) { - if (tp.getName().equals(name)) { - return tp; - } - } - String errStr = - "No TextProp with name " + name + " is defined to add from. " + - "Character and paragraphs have their own properties/names."; - throw new HSLFException(errStr); - } - - /** Add the TextProp with this name to the list */ - public final TextProp addWithName(String name) { - // Find the base TextProp to base on - TextProp existing = findByName(name); - if (existing != null) return existing; - - // Add a copy of this property - TextProp textProp = validatePropName(name).clone(); - textProps.put(name,textProp); - return textProp; - } - - /** - * Add the property at the correct position. Replaces an existing property with the same name. - * - * @param textProp the property to be added - */ - public final void addProp(TextProp textProp) { - if (textProp == null) { - throw new HSLFException("TextProp must not be null"); - } - - String propName = textProp.getName(); - validatePropName(propName); - - textProps.put(propName, textProp); - } - - /** - * For an existing set of text properties, build the list of - * properties coded for in a given run of properties. - * @return the number of bytes that were used encoding the properties list - */ - public int buildTextPropList(int containsField, byte[] data, int dataOffset) { - int bytesPassed = 0; - - // For each possible entry, see if we match the mask - // If we do, decode that, save it, and shuffle on - for(TextProp tp : getPotentialProperties()) { - // Check there's still data left to read - - // Check if this property is found in the mask - if((containsField & tp.getMask()) != 0) { - if(dataOffset+bytesPassed >= data.length) { - // Out of data, can't be any more properties to go - // remember the mask and return - maskSpecial |= tp.getMask(); - return bytesPassed; - } - - // Bingo, data contains this property - TextProp prop = tp.clone(); - int val = 0; - if (prop.getSize() == 2) { - val = LittleEndian.getShort(data,dataOffset+bytesPassed); - } else if(prop.getSize() == 4) { - val = LittleEndian.getInt(data,dataOffset+bytesPassed); - } else if (prop.getSize() == 0 && !(prop instanceof TabStopPropCollection)) { - //remember "special" bits. - maskSpecial |= tp.getMask(); - continue; - } - - if (prop instanceof BitMaskTextProp) { - ((BitMaskTextProp)prop).setValueWithMask(val, containsField); - } else if (prop instanceof TabStopPropCollection) { - ((TabStopPropCollection)prop).parseProperty(data, dataOffset+bytesPassed); - } else { - prop.setValue(val); - } - bytesPassed += prop.getSize(); - addProp(prop); - } - } - - // Return how many bytes were used - return bytesPassed; - } - - /** - * Clones the given text properties - */ - public void copy(TextPropCollection other) { - if (other == null) { - throw new HSLFException("trying to copy null TextPropCollection"); - } - if (this == other) return; - this.charactersCovered = other.charactersCovered; - this.indentLevel = other.indentLevel; - this.maskSpecial = other.maskSpecial; - this.textProps.clear(); - for (TextProp tp : other.textProps.values()) { - TextProp tpCopy = (tp instanceof BitMaskTextProp) - ? ((BitMaskTextProp)tp).cloneAll() - : tp.clone(); - addProp(tpCopy); - } - } - - /** - * Update the size of the text that this set of properties - * applies to - */ - public void updateTextSize(int textSize) { - charactersCovered = textSize; - } - - /** - * Writes out to disk the header, and then all the properties - */ - public void writeOut(OutputStream o) throws IOException { - writeOut(o, false); - } - - /** - * Writes out to disk the header, and then all the properties - */ - public void writeOut(OutputStream o, boolean isMasterStyle) throws IOException { - if (!isMasterStyle) { - // First goes the number of characters we affect - // MasterStyles don't have this field - StyleTextPropAtom.writeLittleEndian(charactersCovered,o); - } - - // Then we have the indentLevel field if it's a paragraph collection - if (textPropType == TextPropType.paragraph && indentLevel > -1) { - StyleTextPropAtom.writeLittleEndian(indentLevel, o); - } - - // Then the mask field - int mask = maskSpecial; - for (TextProp textProp : textProps.values()) { - mask |= textProp.getWriteMask(); - } - StyleTextPropAtom.writeLittleEndian(mask,o); - - // Then the contents of all the properties - for (TextProp textProp : getTextPropList()) { - int val = textProp.getValue(); - if (textProp instanceof BitMaskTextProp && textProp.getWriteMask() == 0) { - // don't add empty properties, as they can't be recognized while reading - continue; - } else if (textProp.getSize() == 2) { - StyleTextPropAtom.writeLittleEndian((short)val,o); - } else if (textProp.getSize() == 4) { - StyleTextPropAtom.writeLittleEndian(val,o); - } - } - } - - public short getIndentLevel(){ - return indentLevel; - } - - public void setIndentLevel(short indentLevel) { - if (textPropType == TextPropType.character) { - throw new RuntimeException("trying to set an indent on a character collection."); - } - this.indentLevel = indentLevel; - } - - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + charactersCovered; - result = prime * result + maskSpecial; - result = prime * result + indentLevel; - result = prime * result + ((textProps == null) ? 0 : textProps.hashCode()); - return result; - } - /** - * compares most properties apart of the covered characters length - */ - public boolean equals(Object other) { - if (this == other) return true; - if (other == null) return false; - if (getClass() != other.getClass()) return false; - - TextPropCollection o = (TextPropCollection)other; - if (o.maskSpecial != this.maskSpecial || o.indentLevel != this.indentLevel) { - return false; - } - - return textProps.equals(o.textProps); - } - - public String toString() { - StringBuilder out = new StringBuilder(); - out.append(" chars covered: " + getCharactersCovered()); - out.append(" special mask flags: 0x" + HexDump.toHex(getSpecialMask()) + "\n"); - if (textPropType == TextPropType.paragraph) { - out.append(" indent level: "+getIndentLevel()+"\n"); - } - for(TextProp p : getTextPropList()) { - out.append(" " + p.getName() + " = " + p.getValue() ); - out.append(" (0x" + HexDump.toHex(p.getValue()) + ")\n"); - if (p instanceof BitMaskTextProp) { - BitMaskTextProp bm = (BitMaskTextProp)p; - int i = 0; - for (String s : bm.getSubPropNames()) { - if (bm.getSubPropMatches()[i]) { - out.append(" " + s + " = " + bm.getSubValue(i) + "\n"); - } - i++; - } - } - } - - out.append(" bytes that would be written: \n"); - - try { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - writeOut(baos); - byte[] b = baos.toByteArray(); - out.append(HexDump.dump(b, 0, 0)); - } catch (IOException e ) { - LOG.log(POILogger.ERROR, "can't dump TextPropCollection", e); - } - - return out.toString(); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/model/textproperties/WrapFlagsTextProp.java b/src/scratchpad/src/org/apache/poi/hslf/model/textproperties/WrapFlagsTextProp.java deleted file mode 100644 index 88e88a82e..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/model/textproperties/WrapFlagsTextProp.java +++ /dev/null @@ -1,30 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.model.textproperties; - -public class WrapFlagsTextProp extends BitMaskTextProp { - public static final int CHAR_WRAP_IDX = 0; - public static final int WORD_WRAO_IDX = 1; - public static final int OVERFLOW_IDX = 2; - - public static final String NAME = "wrapFlags"; - - public WrapFlagsTextProp() { - super(2, 0xE0000, NAME, "charWrap", "wordWrap", "overflow"); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/AnimationInfo.java b/src/scratchpad/src/org/apache/poi/hslf/record/AnimationInfo.java deleted file mode 100644 index e9dc5cd95..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/AnimationInfo.java +++ /dev/null @@ -1,98 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import java.io.IOException; -import java.io.OutputStream; - -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.POILogger; - -/** - * A container record that specifies information about animation information for a shape. - * - * @author Yegor Kozlov - */ -public final class AnimationInfo extends RecordContainer { - private byte[] _header; - - // Links to our more interesting children - private AnimationInfoAtom animationAtom; - - /** - * Set things up, and find our more interesting children - */ - protected AnimationInfo(byte[] source, int start, int len) { - // Grab the header - _header = new byte[8]; - System.arraycopy(source,start,_header,0,8); - - // Find our children - _children = Record.findChildRecords(source,start+8,len-8); - findInterestingChildren(); - } - - /** - * Go through our child records, picking out the ones that are - * interesting, and saving those for use by the easy helper - * methods. - */ - private void findInterestingChildren() { - - // First child should be the ExMediaAtom - if(_children[0] instanceof AnimationInfoAtom) { - animationAtom = (AnimationInfoAtom)_children[0]; - } else { - logger.log(POILogger.ERROR, "First child record wasn't a AnimationInfoAtom, was of type " + _children[0].getRecordType()); - } - } - - /** - * Create a new AnimationInfo, with blank fields - */ - public AnimationInfo() { - // Setup our header block - _header = new byte[8]; - _header[0] = 0x0f; // We are a container record - LittleEndian.putShort(_header, 2, (short)getRecordType()); - - _children = new Record[1]; - _children[0] = animationAtom = new AnimationInfoAtom(); - } - - /** - * We are of type 4103 - */ - public long getRecordType() { return RecordTypes.AnimationInfo.typeID; } - - /** - * Write the contents of the record back, so it can be written - * to disk - */ - public void writeOut(OutputStream out) throws IOException { - writeOut(_header[0],_header[1],getRecordType(),_children,out); - } - - /** - * Returns the AnimationInfo - */ - public AnimationInfoAtom getAnimationInfoAtom() { - return animationAtom; - } - -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/AnimationInfoAtom.java b/src/scratchpad/src/org/apache/poi/hslf/record/AnimationInfoAtom.java deleted file mode 100644 index a2ed09c79..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/AnimationInfoAtom.java +++ /dev/null @@ -1,274 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import java.io.IOException; -import java.io.OutputStream; - -import org.apache.poi.util.LittleEndian; - -/** - * An atom record that specifies the animation information for a shape. - * - * @author Yegor Kozlov - */ -public final class AnimationInfoAtom extends RecordAtom { - - /** - * whether the animation plays in the reverse direction - */ - public static final int Reverse = 1; - /** - * whether the animation starts automatically - */ - public static final int Automatic = 4; - /** - * whether the animation has an associated sound - */ - public static final int Sound = 16; - /** - * whether all playing sounds are stopped when this animation begins - */ - public static final int StopSound = 64; - /** - * whether an associated sound, media or action verb is activated when the shape is clicked. - */ - public static final int Play = 256; - /** - * specifies that the animation, while playing, stops other slide show actions. - */ - public static final int Synchronous = 1024; - /** - * whether the shape is hidden while the animation is not playing - */ - public static final int Hide = 4096; - /** - * whether the background of the shape is animated - */ - public static final int AnimateBg = 16384; - - /** - * Record header. - */ - private byte[] _header; - - /** - * record data - */ - private byte[] _recdata; - - /** - * Constructs a brand new link related atom record. - */ - protected AnimationInfoAtom() { - _recdata = new byte[28]; - - _header = new byte[8]; - LittleEndian.putShort(_header, 0, (short)0x01); - LittleEndian.putShort(_header, 2, (short)getRecordType()); - LittleEndian.putInt(_header, 4, _recdata.length); - } - - /** - * Constructs the link related atom record from its - * source data. - * - * @param source the source data as a byte array. - * @param start the start offset into the byte array. - * @param len the length of the slice in the byte array. - */ - protected AnimationInfoAtom(byte[] source, int start, int len) { - // Get the header - _header = new byte[8]; - System.arraycopy(source,start,_header,0,8); - - // Grab the record data - _recdata = new byte[len-8]; - System.arraycopy(source,start+8,_recdata,0,len-8); - } - - /** - * Gets the record type. - * @return the record type. - */ - public long getRecordType() { - return RecordTypes.AnimationInfoAtom.typeID; - } - - /** - * Write the contents of the record back, so it can be written - * to disk - * - * @param out the output stream to write to. - * @throws java.io.IOException if an error occurs. - */ - public void writeOut(OutputStream out) throws IOException { - out.write(_header); - out.write(_recdata); - } - - /** - * A rgb structure that specifies a color for the dim effect after the animation is complete. - * - * @return color for the dim effect after the animation is complete - */ - public int getDimColor(){ - return LittleEndian.getInt(_recdata, 0); - } - - /** - * A rgb structure that specifies a color for the dim effect after the animation is complete. - * - * @param rgb color for the dim effect after the animation is complete - */ - public void setDimColor(int rgb){ - LittleEndian.putInt(_recdata, 0, rgb); - } - - /** - * A bit mask specifying options for displaying headers and footers - * - * @return A bit mask specifying options for displaying headers and footers - */ - public int getMask(){ - return LittleEndian.getInt(_recdata, 4); - } - - /** - * A bit mask specifying options for displaying video - * - * @param mask A bit mask specifying options for displaying video - */ - public void setMask(int mask){ - LittleEndian.putInt(_recdata, 4, mask); - } - - /** - * @param bit the bit to check - * @return whether the specified flag is set - */ - public boolean getFlag(int bit){ - return (getMask() & bit) != 0; - } - - /** - * @param bit the bit to set - * @param value whether the specified bit is set - */ - public void setFlag(int bit, boolean value){ - int mask = getMask(); - if(value) mask |= bit; - else mask &= ~bit; - setMask(mask); - } - - /** - * A 4-byte unsigned integer that specifies a reference to a sound - * in the SoundCollectionContainer record to locate the embedded audio - * - * @return reference to a sound - */ - public int getSoundIdRef(){ - return LittleEndian.getInt(_recdata, 8); - } - - /** - * A 4-byte unsigned integer that specifies a reference to a sound - * in the SoundCollectionContainer record to locate the embedded audio - * - * @param id reference to a sound - */ - public void setSoundIdRef(int id){ - LittleEndian.putInt(_recdata, 8, id); - } - - /** - * A signed integer that specifies the delay time, in milliseconds, before the animation starts to play. - * If {@link #Automatic} is 0x1, this value MUST be greater than or equal to 0; otherwise, this field MUST be ignored. - */ - public int getDelayTime(){ - return LittleEndian.getInt(_recdata, 12); - } - /** - * A signed integer that specifies the delay time, in milliseconds, before the animation starts to play. - * If {@link #Automatic} is 0x1, this value MUST be greater than or equal to 0; otherwise, this field MUST be ignored. - */ - public void setDelayTime(int id){ - LittleEndian.putInt(_recdata, 12, id); - } - - /** - * A signed integer that specifies the order of the animation in the slide. - * It MUST be greater than or equal to -2. The value -2 specifies that this animation follows the order of - * the corresponding placeholder shape on the main master slide or title master slide. - * The value -1 SHOULD NOT <105> be used. - */ - public int getOrderID(){ - return LittleEndian.getInt(_recdata, 16); - } - - /** - * A signed integer that specifies the order of the animation in the slide. - * It MUST be greater than or equal to -2. The value -2 specifies that this animation follows the order of - * the corresponding placeholder shape on the main master slide or title master slide. - * The value -1 SHOULD NOT <105> be used. - */ - public void setOrderID(int id){ - LittleEndian.putInt(_recdata, 16, id); - } - - /** - * An unsigned integer that specifies the number of slides that this animation continues playing. - * This field is utilized only in conjunction with media. - * The value 0xFFFFFFFF specifies that the animation plays for one slide. - */ - public int getSlideCount(){ - return LittleEndian.getInt(_recdata, 18); - } - - /** - * An unsigned integer that specifies the number of slides that this animation continues playing. - * This field is utilized only in conjunction with media. - * The value 0xFFFFFFFF specifies that the animation plays for one slide. - */ - public void setSlideCount(int id){ - LittleEndian.putInt(_recdata, 18, id); - } - - public String toString(){ - StringBuffer buf = new StringBuffer(); - buf.append("AnimationInfoAtom\n"); - buf.append("\tDimColor: " + getDimColor() + "\n"); - int mask = getMask(); - buf.append("\tMask: " + mask + ", 0x"+Integer.toHexString(mask)+"\n"); - buf.append("\t Reverse: " + getFlag(Reverse)+"\n"); - buf.append("\t Automatic: " + getFlag(Automatic)+"\n"); - buf.append("\t Sound: " + getFlag(Sound)+"\n"); - buf.append("\t StopSound: " + getFlag(StopSound)+"\n"); - buf.append("\t Play: " + getFlag(Play)+"\n"); - buf.append("\t Synchronous: " + getFlag(Synchronous)+"\n"); - buf.append("\t Hide: " + getFlag(Hide)+"\n"); - buf.append("\t AnimateBg: " + getFlag(AnimateBg)+"\n"); - buf.append("\tSoundIdRef: " + getSoundIdRef() + "\n"); - buf.append("\tDelayTime: " + getDelayTime() + "\n"); - buf.append("\tOrderID: " + getOrderID() + "\n"); - buf.append("\tSlideCount: " + getSlideCount() + "\n"); - return buf.toString(); - } - -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/BinaryTagDataBlob.java b/src/scratchpad/src/org/apache/poi/hslf/record/BinaryTagDataBlob.java deleted file mode 100644 index 160e2bdbd..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/BinaryTagDataBlob.java +++ /dev/null @@ -1,67 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import org.apache.poi.util.LittleEndian; -import java.io.IOException; -import java.io.OutputStream; - -/** - * If we come across a record we know has children of (potential) - * interest, but where the record itself is boring, but where other - * records may care about where this one lives, we create one - * of these. It allows us to get at the children, and track where on - * disk this is, but not much else. - * Anything done using this should quite quickly be transitioned to its - * own proper record class! - * - * @author Nick Burch - */ - -public final class BinaryTagDataBlob extends PositionDependentRecordContainer -{ - private byte[] _header; - private long _type; - - /** - * Create a new holder for a boring record with children, but with - * position dependent characteristics - */ - protected BinaryTagDataBlob(byte[] source, int start, int len) { - // Just grab the header, not the whole contents - _header = new byte[8]; - System.arraycopy(source,start,_header,0,8); - _type = LittleEndian.getUShort(_header,2); - - // Find our children - _children = Record.findChildRecords(source,start+8,len-8); - } - - /** - * Return the value we were given at creation - */ - public long getRecordType() { return _type; } - - /** - * Write the contents of the record back, so it can be written - * to disk - */ - public void writeOut(OutputStream out) throws IOException { - writeOut(_header[0],_header[1],_type,_children,out); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/CString.java b/src/scratchpad/src/org/apache/poi/hslf/record/CString.java deleted file mode 100644 index 0115438d2..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/CString.java +++ /dev/null @@ -1,123 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import java.io.IOException; -import java.io.OutputStream; - -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.StringUtil; - -/** - * A CString (type 4026). Holds a unicode string, and the first two bytes - * of the record header normally encode the count. Typically attached to - * some complex sequence of records, eg Commetns. - * - * @author Nick Burch - */ - -public final class CString extends RecordAtom { - private byte[] _header; - private static long _type = 4026l; - - /** The bytes that make up the text */ - private byte[] _text; - - /** Grabs the text. Never null */ - public String getText() { - return StringUtil.getFromUnicodeLE(_text); - } - - /** Updates the text in the Atom. */ - public void setText(String text) { - // Convert to little endian unicode - _text = new byte[text.length()*2]; - StringUtil.putUnicodeLE(text,_text,0); - - // Update the size (header bytes 5-8) - LittleEndian.putInt(_header,4,_text.length); - } - - /** - * Grabs the count, from the first two bytes of the header. - * The meaning of the count is specific to the type of the parent record - */ - public int getOptions() { - return LittleEndian.getShort(_header); - } - - /** - * Sets the count - * The meaning of the count is specific to the type of the parent record - */ - public void setOptions(int count) { - LittleEndian.putShort(_header, 0, (short)count); - } - - /* *************** record code follows ********************** */ - - /** - * For the CStrubg Atom - */ - protected CString(byte[] source, int start, int len) { - // Sanity Checking - if(len < 8) { len = 8; } - - // Get the header - _header = new byte[8]; - System.arraycopy(source,start,_header,0,8); - - // Grab the text - _text = new byte[len-8]; - System.arraycopy(source,start+8,_text,0,len-8); - } - /** - * Create an empty CString - */ - public CString() { - // 0 length header - _header = new byte[] { 0, 0, 0xBA-256, 0x0f, 0, 0, 0, 0 }; - // Empty text - _text = new byte[0]; - } - - /** - * We are of type 4026 - */ - public long getRecordType() { return _type; } - - /** - * Write the contents of the record back, so it can be written - * to disk - */ - public void writeOut(OutputStream out) throws IOException { - // Header - size or type unchanged - out.write(_header); - - // Write out our text - out.write(_text); - } - - /** - * Gets a string representation of this object, primarily for debugging. - * @return a string representation of this object. - */ - public String toString() { - return getText(); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/ColorSchemeAtom.java b/src/scratchpad/src/org/apache/poi/hslf/record/ColorSchemeAtom.java deleted file mode 100644 index c720a555c..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/ColorSchemeAtom.java +++ /dev/null @@ -1,221 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.OutputStream; - -import org.apache.poi.hslf.exceptions.HSLFException; -import org.apache.poi.util.LittleEndian; - -/** - * A ColorSchemeAtom (type 2032). Holds the 8 RGB values for the different - * colours of bits of text, that makes up a given colour scheme. - * Slides (presumably) link to a given colour scheme atom, and that - * defines the colours to be used - * - * @author Nick Burch - */ -public final class ColorSchemeAtom extends RecordAtom { - private byte[] _header; - private static long _type = 2032l; - - private int backgroundColourRGB; - private int textAndLinesColourRGB; - private int shadowsColourRGB; - private int titleTextColourRGB; - private int fillsColourRGB; - private int accentColourRGB; - private int accentAndHyperlinkColourRGB; - private int accentAndFollowingHyperlinkColourRGB; - - /** Fetch the RGB value for Background Colour */ - public int getBackgroundColourRGB() { return backgroundColourRGB; } - /** Set the RGB value for Background Colour */ - public void setBackgroundColourRGB(int rgb) { backgroundColourRGB = rgb; } - - /** Fetch the RGB value for Text And Lines Colour */ - public int getTextAndLinesColourRGB() { return textAndLinesColourRGB; } - /** Set the RGB value for Text And Lines Colour */ - public void setTextAndLinesColourRGB(int rgb) { textAndLinesColourRGB = rgb; } - - /** Fetch the RGB value for Shadows Colour */ - public int getShadowsColourRGB() { return shadowsColourRGB; } - /** Set the RGB value for Shadows Colour */ - public void setShadowsColourRGB(int rgb) { shadowsColourRGB = rgb; } - - /** Fetch the RGB value for Title Text Colour */ - public int getTitleTextColourRGB() { return titleTextColourRGB; } - /** Set the RGB value for Title Text Colour */ - public void setTitleTextColourRGB(int rgb) { titleTextColourRGB = rgb; } - - /** Fetch the RGB value for Fills Colour */ - public int getFillsColourRGB() { return fillsColourRGB; } - /** Set the RGB value for Fills Colour */ - public void setFillsColourRGB(int rgb) { fillsColourRGB = rgb; } - - /** Fetch the RGB value for Accent Colour */ - public int getAccentColourRGB() { return accentColourRGB; } - /** Set the RGB value for Accent Colour */ - public void setAccentColourRGB(int rgb) { accentColourRGB = rgb; } - - /** Fetch the RGB value for Accent And Hyperlink Colour */ - public int getAccentAndHyperlinkColourRGB() - { return accentAndHyperlinkColourRGB; } - /** Set the RGB value for Accent And Hyperlink Colour */ - public void setAccentAndHyperlinkColourRGB(int rgb) - { accentAndHyperlinkColourRGB = rgb; } - - /** Fetch the RGB value for Accent And Following Hyperlink Colour */ - public int getAccentAndFollowingHyperlinkColourRGB() - { return accentAndFollowingHyperlinkColourRGB; } - /** Set the RGB value for Accent And Following Hyperlink Colour */ - public void setAccentAndFollowingHyperlinkColourRGB(int rgb) - { accentAndFollowingHyperlinkColourRGB = rgb; } - - /* *************** record code follows ********************** */ - - /** - * For the Colour Scheme (ColorSchem) Atom - */ - protected ColorSchemeAtom(byte[] source, int start, int len) { - // Sanity Checking - we're always 40 bytes long - if(len < 40) { - len = 40; - if(source.length - start < 40) { - throw new HSLFException("Not enough data to form a ColorSchemeAtom (always 40 bytes long) - found " + (source.length - start)); - } - } - - // Get the header - _header = new byte[8]; - System.arraycopy(source,start,_header,0,8); - - // Grab the rgb values - backgroundColourRGB = LittleEndian.getInt(source,start+8+0); - textAndLinesColourRGB = LittleEndian.getInt(source,start+8+4); - shadowsColourRGB = LittleEndian.getInt(source,start+8+8); - titleTextColourRGB = LittleEndian.getInt(source,start+8+12); - fillsColourRGB = LittleEndian.getInt(source,start+8+16); - accentColourRGB = LittleEndian.getInt(source,start+8+20); - accentAndHyperlinkColourRGB = LittleEndian.getInt(source,start+8+24); - accentAndFollowingHyperlinkColourRGB = LittleEndian.getInt(source,start+8+28); - } - - /** - * Create a new ColorSchemeAtom, to go with a new Slide - */ - public ColorSchemeAtom(){ - _header = new byte[8]; - LittleEndian.putUShort(_header, 0, 16); - LittleEndian.putUShort(_header, 2, (int)_type); - LittleEndian.putInt(_header, 4, 32); - - // Setup the default rgb values - backgroundColourRGB = 16777215; - textAndLinesColourRGB = 0; - shadowsColourRGB = 8421504; - titleTextColourRGB = 0; - fillsColourRGB = 10079232; - accentColourRGB = 13382451; - accentAndHyperlinkColourRGB = 16764108; - accentAndFollowingHyperlinkColourRGB = 11711154; - } - - - /** - * We are of type 3999 - */ - @Override - public long getRecordType() { return _type; } - - - /** - * Convert from an integer RGB value to individual R, G, B 0-255 values - */ - public static byte[] splitRGB(int rgb) { - byte[] ret = new byte[3]; - - // Serialise to bytes, then grab the right ones out - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - try { - writeLittleEndian(rgb,baos); - } catch(IOException ie) { - // Should never happen - throw new HSLFException(ie); - } - byte[] b = baos.toByteArray(); - System.arraycopy(b,0,ret,0,3); - - return ret; - } - - /** - * Convert from split R, G, B values to an integer RGB value - */ - public static int joinRGB(byte r, byte g, byte b) { - return joinRGB(new byte[] { r,g,b }); - } - /** - * Convert from split R, G, B values to an integer RGB value - */ - public static int joinRGB(byte[] rgb) { - if(rgb.length != 3) { - throw new HSLFException("joinRGB accepts a byte array of 3 values, but got one of " + rgb.length + " values!"); - } - byte[] with_zero = new byte[4]; - System.arraycopy(rgb,0,with_zero,0,3); - with_zero[3] = 0; - int ret = LittleEndian.getInt(with_zero,0); - return ret; - } - - - /** - * Write the contents of the record back, so it can be written - * to disk - */ - @Override - public void writeOut(OutputStream out) throws IOException { - // Header - size or type unchanged - out.write(_header); - - // Write out the rgb values - writeLittleEndian(backgroundColourRGB,out); - writeLittleEndian(textAndLinesColourRGB,out); - writeLittleEndian(shadowsColourRGB,out); - writeLittleEndian(titleTextColourRGB,out); - writeLittleEndian(fillsColourRGB,out); - writeLittleEndian(accentColourRGB,out); - writeLittleEndian(accentAndHyperlinkColourRGB,out); - writeLittleEndian(accentAndFollowingHyperlinkColourRGB,out); - } - - /** - * Returns color by its index - * - * @param idx 0-based color index - * @return color by its index - */ - public int getColor(int idx){ - int[] clr = {backgroundColourRGB, textAndLinesColourRGB, shadowsColourRGB, titleTextColourRGB, - fillsColourRGB, accentColourRGB, accentAndHyperlinkColourRGB, accentAndFollowingHyperlinkColourRGB}; - return clr[idx]; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/Comment2000.java b/src/scratchpad/src/org/apache/poi/hslf/record/Comment2000.java deleted file mode 100644 index b64134b0d..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/Comment2000.java +++ /dev/null @@ -1,176 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import java.io.IOException; -import java.io.OutputStream; - -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.POILogger; - -/** - * This class represents a comment on a slide, in the format used by - * PPT 2000/XP/etc. (PPT 97 uses plain Escher Text Boxes for comments) - * @author Nick Burch - */ -public final class Comment2000 extends RecordContainer { - private byte[] _header; - private static long _type = 12000; - - // Links to our more interesting children - - /** - * An optional string that specifies the name of the author of the presentation comment. - */ - private CString authorRecord; - /** - * An optional string record that specifies the text of the presentation comment - */ - private CString authorInitialsRecord; - /** - * An optional string record that specifies the initials of the author of the presentation comment - */ - private CString commentRecord; - - /** - * A Comment2000Atom record that specifies the settings for displaying the presentation comment - */ - private Comment2000Atom commentAtom; - - /** - * Returns the Comment2000Atom of this Comment - */ - public Comment2000Atom getComment2000Atom() { return commentAtom; } - - /** - * Get the Author of this comment - */ - public String getAuthor() { - return authorRecord == null ? null : authorRecord.getText(); - } - /** - * Set the Author of this comment - */ - public void setAuthor(String author) { - authorRecord.setText(author); - } - - /** - * Get the Author's Initials of this comment - */ - public String getAuthorInitials() { - return authorInitialsRecord == null ? null : authorInitialsRecord.getText(); - } - /** - * Set the Author's Initials of this comment - */ - public void setAuthorInitials(String initials) { - authorInitialsRecord.setText(initials); - } - - /** - * Get the text of this comment - */ - public String getText() { - return commentRecord == null ? null : commentRecord.getText(); - } - /** - * Set the text of this comment - */ - public void setText(String text) { - commentRecord.setText(text); - } - - /** - * Set things up, and find our more interesting children - */ - protected Comment2000(byte[] source, int start, int len) { - // Grab the header - _header = new byte[8]; - System.arraycopy(source,start,_header,0,8); - - // Find our children - _children = Record.findChildRecords(source,start+8,len-8); - findInterestingChildren(); - } - - /** - * Go through our child records, picking out the ones that are - * interesting, and saving those for use by the easy helper - * methods. - */ - private void findInterestingChildren() { - - for(Record r : _children){ - if (r instanceof CString){ - CString cs = (CString)r; - int recInstance = cs.getOptions() >> 4; - switch(recInstance){ - case 0: authorRecord = cs; break; - case 1: commentRecord = cs; break; - case 2: authorInitialsRecord = cs; break; - default: break; - } - } else if (r instanceof Comment2000Atom){ - commentAtom = (Comment2000Atom)r; - } else { - logger.log(POILogger.WARN, "Unexpected record with type="+r.getRecordType()+" in Comment2000: " + r.getClass().getName()); - } - } - - } - - /** - * Create a new Comment2000, with blank fields - */ - public Comment2000() { - _header = new byte[8]; - _children = new Record[4]; - - // Setup our header block - _header[0] = 0x0f; // We are a container record - LittleEndian.putShort(_header, 2, (short)_type); - - // Setup our child records - CString csa = new CString(); - CString csb = new CString(); - CString csc = new CString(); - csa.setOptions(0x00); - csb.setOptions(0x10); - csc.setOptions(0x20); - _children[0] = csa; - _children[1] = csb; - _children[2] = csc; - _children[3] = new Comment2000Atom(); - findInterestingChildren(); - } - - /** - * We are of type 1200 - */ - public long getRecordType() { return _type; } - - /** - * Write the contents of the record back, so it can be written - * to disk - */ - public void writeOut(OutputStream out) throws IOException { - writeOut(_header[0],_header[1],_type,_children,out); - } - -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/Comment2000Atom.java b/src/scratchpad/src/org/apache/poi/hslf/record/Comment2000Atom.java deleted file mode 100644 index ab38e88d1..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/Comment2000Atom.java +++ /dev/null @@ -1,156 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import java.io.IOException; -import java.io.OutputStream; -import java.util.Date; - -import org.apache.poi.hslf.util.SystemTimeUtils; -import org.apache.poi.util.LittleEndian; - -/** - * An atomic record containing information about a comment. - * - * @author Daniel Noll - */ - -public final class Comment2000Atom extends RecordAtom -{ - /** - * Record header. - */ - private byte[] _header; - - /** - * Record data. - */ - private byte[] _data; - - /** - * Constructs a brand new comment atom record. - */ - protected Comment2000Atom() { - _header = new byte[8]; - _data = new byte[28]; - - LittleEndian.putShort(_header, 2, (short)getRecordType()); - LittleEndian.putInt(_header, 4, _data.length); - - // It is fine for the other values to be zero - } - - /** - * Constructs the comment atom record from its source data. - * - * @param source the source data as a byte array. - * @param start the start offset into the byte array. - * @param len the length of the slice in the byte array. - */ - protected Comment2000Atom(byte[] source, int start, int len) { - // Get the header. - _header = new byte[8]; - System.arraycopy(source,start,_header,0,8); - - // Get the record data. - _data = new byte[len-8]; - System.arraycopy(source,start+8,_data,0,len-8); - } - - /** - * Gets the comment number (note - each user normally has their own count). - * @return the comment number. - */ - public int getNumber() { - return LittleEndian.getInt(_data,0); - } - - /** - * Sets the comment number (note - each user normally has their own count). - * @param number the comment number. - */ - public void setNumber(int number) { - LittleEndian.putInt(_data,0,number); - } - - /** - * Gets the date the comment was made. - * @return the comment date. - */ - public Date getDate() { - return SystemTimeUtils.getDate(_data,4); - } - - /** - * Sets the date the comment was made. - * @param date the comment date. - */ - public void setDate(Date date) { - SystemTimeUtils.storeDate(date, _data, 4); - } - - /** - * Gets the X offset of the comment on the page. - * @return the X offset. - */ - public int getXOffset() { - return LittleEndian.getInt(_data,20); - } - - /** - * Sets the X offset of the comment on the page. - * @param xOffset the X offset. - */ - public void setXOffset(int xOffset) { - LittleEndian.putInt(_data,20,xOffset); - } - - /** - * Gets the Y offset of the comment on the page. - * @return the Y offset. - */ - public int getYOffset() { - return LittleEndian.getInt(_data,24); - } - - /** - * Sets the Y offset of the comment on the page. - * @param yOffset the Y offset. - */ - public void setYOffset(int yOffset) { - LittleEndian.putInt(_data,24,yOffset); - } - - /** - * Gets the record type. - * @return the record type. - */ - public long getRecordType() { return RecordTypes.Comment2000Atom.typeID; } - - /** - * Write the contents of the record back, so it can be written - * to disk - * - * @param out the output stream to write to. - * @throws IOException if an error occurs. - */ - public void writeOut(OutputStream out) throws IOException { - out.write(_header); - out.write(_data); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/CurrentUserAtom.java b/src/scratchpad/src/org/apache/poi/hslf/record/CurrentUserAtom.java deleted file mode 100644 index d05c5b2d1..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/CurrentUserAtom.java +++ /dev/null @@ -1,284 +0,0 @@ - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - - - -package org.apache.poi.hslf.record; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import org.apache.poi.hslf.exceptions.CorruptPowerPointFileException; -import org.apache.poi.hslf.exceptions.OldPowerPointFormatException; -import org.apache.poi.poifs.filesystem.DirectoryNode; -import org.apache.poi.poifs.filesystem.DocumentEntry; -import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.util.StringUtil; - -/** - * This is a special kind of Atom, because it doesn't live inside the - * PowerPoint document. Instead, it lives in a separate stream in the - * document. As such, it has to be treated specially - */ -public class CurrentUserAtom -{ - private final static POILogger logger = POILogFactory.getLogger(CurrentUserAtom.class); - - /** Standard Atom header */ - public static final byte[] atomHeader = new byte[] { 0, 0, -10, 15 }; - /** The PowerPoint magic number for a non-encrypted file */ - public static final byte[] headerToken = new byte[] { 95, -64, -111, -29 }; - /** The PowerPoint magic number for an encrypted file */ - public static final byte[] encHeaderToken = new byte[] { -33, -60, -47, -13 }; - /** The Powerpoint 97 version, major and minor numbers */ - public static final byte[] ppt97FileVer = new byte[] { 8, 00, -13, 03, 03, 00 }; - - /** The version, major and minor numbers */ - private int docFinalVersion; - private byte docMajorNo; - private byte docMinorNo; - - /** The Offset into the file for the current edit */ - private long currentEditOffset; - /** The Username of the last person to edit the file */ - private String lastEditUser; - /** The document release version. Almost always 8 */ - private long releaseVersion; - - /** Only correct after reading in or writing out */ - private byte[] _contents; - - /** Flag for encryption state of the whole file */ - private boolean isEncrypted; - - - /* ********************* getter/setter follows *********************** */ - - public int getDocFinalVersion() { return docFinalVersion; } - public byte getDocMajorNo() { return docMajorNo; } - public byte getDocMinorNo() { return docMinorNo; } - - public long getReleaseVersion() { return releaseVersion; } - public void setReleaseVersion(long rv) { releaseVersion = rv; } - - /** Points to the UserEditAtom */ - public long getCurrentEditOffset() { return currentEditOffset; } - public void setCurrentEditOffset(long id ) { currentEditOffset = id; } - - public String getLastEditUsername() { return lastEditUser; } - public void setLastEditUsername(String u) { lastEditUser = u; } - - public boolean isEncrypted() { return isEncrypted; } - public void setEncrypted(boolean isEncrypted) { this.isEncrypted = isEncrypted; } - - - /* ********************* real code follows *************************** */ - - /** - * Create a new Current User Atom - */ - public CurrentUserAtom() { - _contents = new byte[0]; - - // Initialise to empty - docFinalVersion = 0x03f4; - docMajorNo = 3; - docMinorNo = 0; - releaseVersion = 8; - currentEditOffset = 0; - lastEditUser = "Apache POI"; - isEncrypted = false; - } - - - /** - * Find the Current User in the filesystem, and create from that - */ - public CurrentUserAtom(DirectoryNode dir) throws IOException { - // Decide how big it is - DocumentEntry docProps = - (DocumentEntry)dir.getEntry("Current User"); - - // If it's clearly junk, bail out - if(docProps.getSize() > 131072) { - throw new CorruptPowerPointFileException("The Current User stream is implausably long. It's normally 28-200 bytes long, but was " + docProps.getSize() + " bytes"); - } - - // Grab the contents - int len = docProps.getSize(); - _contents = new byte[len]; - InputStream in = dir.createDocumentInputStream("Current User"); - int readLen = in.read(_contents); - in.close(); - - if (len != readLen) { - throw new IOException("Current User input stream ended prematurely - expected "+len+" bytes - received "+readLen+" bytes"); - } - - - // See how long it is. If it's under 28 bytes long, we can't - // read it - if(_contents.length < 28) { - boolean isPP95 = dir.hasEntry("PP40"); - // PPT95 has 4 byte size, then data - if (!isPP95 && _contents.length >= 4) { - int size = LittleEndian.getInt(_contents); - isPP95 = (size + 4 == _contents.length); - } - - if (isPP95) { - throw new OldPowerPointFormatException("Based on the Current User stream, you seem to have supplied a PowerPoint95 file, which isn't supported"); - } else { - throw new CorruptPowerPointFileException("The Current User stream must be at least 28 bytes long, but was only " + _contents.length); - } - } - - // Set everything up - init(); - } - - /** - * Actually do the creation from a block of bytes - */ - private void init() { - // First up is the size, in 4 bytes, which is fixed - // Then is the header - - isEncrypted = (LittleEndian.getInt(encHeaderToken) == LittleEndian.getInt(_contents,12)); - - // Grab the edit offset - currentEditOffset = LittleEndian.getUInt(_contents,16); - - // Grab the versions - docFinalVersion = LittleEndian.getUShort(_contents,22); - docMajorNo = _contents[24]; - docMinorNo = _contents[25]; - - // Get the username length - long usernameLen = LittleEndian.getUShort(_contents,20); - if(usernameLen > 512) { - // Handle the case of it being garbage - logger.log(POILogger.WARN, "Warning - invalid username length " + usernameLen + " found, treating as if there was no username set"); - usernameLen = 0; - } - - // Now we know the length of the username, - // use this to grab the revision - if(_contents.length >= 28+(int)usernameLen + 4) { - releaseVersion = LittleEndian.getUInt(_contents,28+(int)usernameLen); - } else { - // No revision given, as not enough data. Odd - releaseVersion = 0; - } - - // Grab the unicode username, if stored - int start = 28+(int)usernameLen+4; - int len = 2*(int)usernameLen; - - if(_contents.length >= start+len) { - byte[] textBytes = new byte[len]; - System.arraycopy(_contents,start,textBytes,0,len); - lastEditUser = StringUtil.getFromUnicodeLE(textBytes); - } else { - // Fake from the 8 bit version - byte[] textBytes = new byte[(int)usernameLen]; - System.arraycopy(_contents,28,textBytes,0,(int)usernameLen); - lastEditUser = StringUtil.getFromCompressedUnicode(textBytes,0,(int)usernameLen); - } - } - - - /** - * Writes ourselves back out - */ - public void writeOut(OutputStream out) throws IOException { - // Decide on the size - // 8 = atom header - // 20 = up to name - // 4 = revision - // 3 * len = ascii + unicode - int size = 8 + 20 + 4 + (3 * lastEditUser.length()); - _contents = new byte[size]; - - // First we have a 8 byte atom header - System.arraycopy(atomHeader,0,_contents,0,4); - // Size is 20+user len + revision len(4) - int atomSize = 20+4+lastEditUser.length(); - LittleEndian.putInt(_contents,4,atomSize); - - // Now we have the size of the details, which is 20 - LittleEndian.putInt(_contents,8,20); - - // Now the ppt un-encrypted header token (4 bytes) - System.arraycopy((isEncrypted ? encHeaderToken : headerToken),0,_contents,12,4); - - // Now the current edit offset - LittleEndian.putInt(_contents,16,(int)currentEditOffset); - - // The username gets stored twice, once as US - // ascii, and again as unicode laster on - byte[] asciiUN = new byte[lastEditUser.length()]; - StringUtil.putCompressedUnicode(lastEditUser,asciiUN,0); - - // Now we're able to do the length of the last edited user - LittleEndian.putShort(_contents,20,(short)asciiUN.length); - - // Now the file versions, 2+1+1 - LittleEndian.putShort(_contents,22,(short)docFinalVersion); - _contents[24] = docMajorNo; - _contents[25] = docMinorNo; - - // 2 bytes blank - _contents[26] = 0; - _contents[27] = 0; - - // At this point we have the username as us ascii - System.arraycopy(asciiUN,0,_contents,28,asciiUN.length); - - // 4 byte release version - LittleEndian.putInt(_contents,28+asciiUN.length,(int)releaseVersion); - - // username in unicode - byte [] ucUN = new byte[lastEditUser.length()*2]; - StringUtil.putUnicodeLE(lastEditUser,ucUN,0); - System.arraycopy(ucUN,0,_contents,28+asciiUN.length+4,ucUN.length); - - // Write out - out.write(_contents); - } - - /** - * Writes ourselves back out to a filesystem - */ - public void writeToFS(NPOIFSFileSystem fs) throws IOException { - // Grab contents - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - writeOut(baos); - ByteArrayInputStream bais = - new ByteArrayInputStream(baos.toByteArray()); - - // Write out - fs.createOrUpdateDocument(bais,"Current User"); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/DocInfoListContainer.java b/src/scratchpad/src/org/apache/poi/hslf/record/DocInfoListContainer.java deleted file mode 100644 index eed1de23f..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/DocInfoListContainer.java +++ /dev/null @@ -1,84 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import java.io.IOException; -import java.io.OutputStream; - -import org.apache.poi.util.LittleEndian; - -/** - * A container record that specifies information about the document and document display settings. - */ -public final class DocInfoListContainer extends RecordContainer { - private byte[] _header; - private static long _type = RecordTypes.List.typeID; - - // Links to our more interesting children - - /** - * Set things up, and find our more interesting children - */ - protected DocInfoListContainer(byte[] source, int start, int len) { - // Grab the header - _header = new byte[8]; - System.arraycopy(source,start,_header,0,8); - - // Find our children - _children = Record.findChildRecords(source,start+8,len-8); - findInterestingChildren(); - } - - /** - * Go through our child records, picking out the ones that are - * interesting, and saving those for use by the easy helper - * methods. - */ - private void findInterestingChildren() { - - } - - /** - * Create a new DocInfoListContainer, with blank fields - not yet supported - */ - private DocInfoListContainer() { - _header = new byte[8]; - _children = new Record[0]; - - // Setup our header block - _header[0] = 0x0f; // We are a container record - LittleEndian.putShort(_header, 2, (short)_type); - - // Setup our child records - findInterestingChildren(); - } - - /** - * We are of type 0x7D0 - */ - public long getRecordType() { return _type; } - - /** - * Write the contents of the record back, so it can be written - * to disk - */ - public void writeOut(OutputStream out) throws IOException { - writeOut(_header[0],_header[1],_type,_children,out); - } - -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/Document.java b/src/scratchpad/src/org/apache/poi/hslf/record/Document.java deleted file mode 100644 index 0c74ae2b4..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/Document.java +++ /dev/null @@ -1,231 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import org.apache.poi.util.POILogger; - -import java.io.IOException; -import java.io.OutputStream; -import java.util.ArrayList; - -/** - * Master container for Document. There is one of these for every - * slideshow, and it holds lots of definitions, and some summaries. - * - * @author Nick Burch - */ - -public final class Document extends PositionDependentRecordContainer -{ - private byte[] _header; - private static long _type = 1000; - - // Links to our more interesting children - private DocumentAtom documentAtom; - private Environment environment; - private PPDrawingGroup ppDrawing; - private SlideListWithText[] slwts; - private ExObjList exObjList; // Can be null - - /** - * Returns the DocumentAtom of this Document - */ - public DocumentAtom getDocumentAtom() { return documentAtom; } - - /** - * Returns the Environment of this Notes, which lots of - * settings for the document in it - */ - public Environment getEnvironment() { return environment; } - - /** - * Returns the PPDrawingGroup, which holds an Escher Structure - * that contains information on pictures in the slides. - */ - public PPDrawingGroup getPPDrawingGroup() { return ppDrawing; } - - /** - * Returns the ExObjList, which holds the references to - * external objects used in the slides. This may be null, if - * there are no external references. - * - * @param create if true, create an ExObjList if it doesn't exist - */ - public ExObjList getExObjList(boolean create) { - if (exObjList == null && create) { - exObjList = new ExObjList(); - addChildAfter(exObjList, getDocumentAtom()); - } - return exObjList; - } - - /** - * Returns all the SlideListWithTexts that are defined for - * this Document. They hold the text, and some of the text - * properties, which are referred to by the slides. - * This will normally return an array of size 2 or 3 - */ - public SlideListWithText[] getSlideListWithTexts() { return slwts; } - - /** - * Returns the SlideListWithText that deals with the - * Master Slides - */ - public SlideListWithText getMasterSlideListWithText() { - for (int i = 0; i < slwts.length; i++) { - if(slwts[i].getInstance() == SlideListWithText.MASTER) { - return slwts[i]; - } - } - return null; - } - - /** - * Returns the SlideListWithText that deals with the - * Slides, or null if there isn't one - */ - public SlideListWithText getSlideSlideListWithText() { - for (int i = 0; i < slwts.length; i++) { - if(slwts[i].getInstance() == SlideListWithText.SLIDES) { - return slwts[i]; - } - } - return null; - } - /** - * Returns the SlideListWithText that deals with the - * notes, or null if there isn't one - */ - public SlideListWithText getNotesSlideListWithText() { - for (int i = 0; i < slwts.length; i++) { - if(slwts[i].getInstance() == SlideListWithText.NOTES) { - return slwts[i]; - } - } - return null; - } - - - /** - * Set things up, and find our more interesting children - */ - protected Document(byte[] source, int start, int len) { - // Grab the header - _header = new byte[8]; - System.arraycopy(source,start,_header,0,8); - - // Find our children - _children = Record.findChildRecords(source,start+8,len-8); - - // Our first one should be a document atom - if(! (_children[0] instanceof DocumentAtom)) { - throw new IllegalStateException("The first child of a Document must be a DocumentAtom"); - } - documentAtom = (DocumentAtom)_children[0]; - - // Find how many SlideListWithTexts we have - // Also, grab the Environment and PPDrawing records - // on our way past - int slwtcount = 0; - for(int i=1; i<_children.length; i++) { - if(_children[i] instanceof SlideListWithText) { - slwtcount++; - } - if(_children[i] instanceof Environment) { - environment = (Environment)_children[i]; - } - if(_children[i] instanceof PPDrawingGroup) { - ppDrawing = (PPDrawingGroup)_children[i]; - } - if(_children[i] instanceof ExObjList) { - exObjList = (ExObjList)_children[i]; - } - } - - // You should only every have 1, 2 or 3 SLWTs - // (normally it's 2, or 3 if you have notes) - // Complain if it's not - if(slwtcount == 0) { - logger.log(POILogger.WARN, "No SlideListWithText's found - there should normally be at least one!"); - } - if(slwtcount > 3) { - logger.log(POILogger.WARN, "Found " + slwtcount + " SlideListWithTexts - normally there should only be three!"); - } - - // Now grab all the SLWTs - slwts = new SlideListWithText[slwtcount]; - slwtcount = 0; - for(int i=1; i<_children.length; i++) { - if(_children[i] instanceof SlideListWithText) { - slwts[slwtcount] = (SlideListWithText)_children[i]; - slwtcount++; - } - } - } - - /** - * Adds a new SlideListWithText record, at the appropriate - * point in the child records. - */ - public void addSlideListWithText(SlideListWithText slwt) { - // The new SlideListWithText should go in - // just before the EndDocumentRecord - Record endDoc = _children[_children.length - 1]; - if(endDoc.getRecordType() == RecordTypes.RoundTripCustomTableStyles12Atom.typeID) { - // last record can optionally be a RoundTripCustomTableStyles12Atom - endDoc = _children[_children.length - 2]; - } - if(endDoc.getRecordType() != RecordTypes.EndDocument.typeID) { - throw new IllegalStateException("The last child record of a Document should be EndDocument, but it was " + endDoc); - } - - // Add in the record - addChildBefore(slwt, endDoc); - - // Updated our cached list of SlideListWithText records - int newSize = slwts.length + 1; - SlideListWithText[] nl = new SlideListWithText[newSize]; - System.arraycopy(slwts, 0, nl, 0, slwts.length); - nl[nl.length-1] = slwt; - slwts = nl; - } - - public void removeSlideListWithText(SlideListWithText slwt) { - ArrayList lst = new ArrayList(); - for(SlideListWithText s : slwts) { - if(s != slwt) lst.add(s); - else { - removeChild(slwt); - } - } - slwts = lst.toArray(new SlideListWithText[lst.size()]); - } - - /** - * We are of type 1000 - */ - public long getRecordType() { return _type; } - - /** - * Write the contents of the record back, so it can be written - * to disk - */ - public void writeOut(OutputStream out) throws IOException { - writeOut(_header[0],_header[1],_type,_children,out); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/DocumentAtom.java b/src/scratchpad/src/org/apache/poi/hslf/record/DocumentAtom.java deleted file mode 100644 index 22a9b7c3e..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/DocumentAtom.java +++ /dev/null @@ -1,197 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import org.apache.poi.util.LittleEndian; -import java.io.IOException; -import java.io.OutputStream; - -/** - * A Document Atom (type 1001). Holds misc information on the PowerPoint - * document, lots of them size and scale related. - * - * @author Nick Burch - */ - -public final class DocumentAtom extends RecordAtom -{ - private byte[] _header; - private static long _type = 1001l; - - private long slideSizeX; // PointAtom, assume 1st 4 bytes = X - private long slideSizeY; // PointAtom, assume 2nd 4 bytes = Y - private long notesSizeX; // PointAtom, assume 1st 4 bytes = X - private long notesSizeY; // PointAtom, assume 2nd 4 bytes = Y - private long serverZoomFrom; // RatioAtom, assume 1st 4 bytes = from - private long serverZoomTo; // RatioAtom, assume 2nd 4 bytes = to - - private long notesMasterPersist; // ref to NotesMaster, 0 if none - private long handoutMasterPersist; // ref to HandoutMaster, 0 if none - - private int firstSlideNum; - private int slideSizeType; // see DocumentAtom.SlideSize - - private byte saveWithFonts; - private byte omitTitlePlace; - private byte rightToLeft; - private byte showComments; - - private byte[] reserved; - - - public long getSlideSizeX() { return slideSizeX; } - public long getSlideSizeY() { return slideSizeY; } - public long getNotesSizeX() { return notesSizeX; } - public long getNotesSizeY() { return notesSizeY; } - public void setSlideSizeX(long x) { slideSizeX = x; } - public void setSlideSizeY(long y) { slideSizeY = y; } - public void setNotesSizeX(long x) { notesSizeX = x; } - public void setNotesSizeY(long y) { notesSizeY = y; } - - public long getServerZoomFrom() { return serverZoomFrom; } - public long getServerZoomTo() { return serverZoomTo; } - public void setServerZoomFrom(long zoom) { serverZoomFrom = zoom; } - public void setServerZoomTo(long zoom) { serverZoomTo = zoom; } - - /** Returns a reference to the NotesMaster, or 0 if none */ - public long getNotesMasterPersist() { return notesMasterPersist; } - /** Returns a reference to the HandoutMaster, or 0 if none */ - public long getHandoutMasterPersist() { return handoutMasterPersist; } - - public int getFirstSlideNum() { return firstSlideNum; } - - /** The Size of the Document's slides, @see DocumentAtom.SlideSize for values */ - public int getSlideSizeType() { return slideSizeType; } - - /** Was the document saved with True Type fonts embeded? */ - public boolean getSaveWithFonts() { - return saveWithFonts != 0; - } - - /** Have the placeholders on the title slide been omitted? */ - public boolean getOmitTitlePlace() { - return omitTitlePlace != 0; - } - - /** Is this a Bi-Directional PPT Doc? */ - public boolean getRightToLeft() { - return rightToLeft != 0; - } - - /** Are comment shapes visible? */ - public boolean getShowComments() { - return showComments != 0; - } - - - /* *************** record code follows ********************** */ - - /** - * For the Document Atom - */ - protected DocumentAtom(byte[] source, int start, int len) { - // Sanity Checking - if(len < 48) { len = 48; } - - // Get the header - _header = new byte[8]; - System.arraycopy(source,start,_header,0,8); - - // Get the sizes and zoom ratios - slideSizeX = LittleEndian.getInt(source,start+0+8); - slideSizeY = LittleEndian.getInt(source,start+4+8); - notesSizeX = LittleEndian.getInt(source,start+8+8); - notesSizeY = LittleEndian.getInt(source,start+12+8); - serverZoomFrom = LittleEndian.getInt(source,start+16+8); - serverZoomTo = LittleEndian.getInt(source,start+20+8); - - // Get the master persists - notesMasterPersist = LittleEndian.getInt(source,start+24+8); - handoutMasterPersist = LittleEndian.getInt(source,start+28+8); - - // Get the ID of the first slide - firstSlideNum = LittleEndian.getShort(source,start+32+8); - - // Get the slide size type - slideSizeType = LittleEndian.getShort(source,start+34+8); - - // Get the booleans as bytes - saveWithFonts = source[start+36+8]; - omitTitlePlace = source[start+37+8]; - rightToLeft = source[start+38+8]; - showComments = source[start+39+8]; - - // If there's any other bits of data, keep them about - reserved = new byte[len-40-8]; - System.arraycopy(source,start+48,reserved,0,reserved.length); - } - - /** - * We are of type 1001 - */ - public long getRecordType() { return _type; } - - /** - * Write the contents of the record back, so it can be written - * to disk - */ - public void writeOut(OutputStream out) throws IOException { - // Header - out.write(_header); - - // The sizes and zoom ratios - writeLittleEndian((int)slideSizeX,out); - writeLittleEndian((int)slideSizeY,out); - writeLittleEndian((int)notesSizeX,out); - writeLittleEndian((int)notesSizeY,out); - writeLittleEndian((int)serverZoomFrom,out); - writeLittleEndian((int)serverZoomTo,out); - - // The master persists - writeLittleEndian((int)notesMasterPersist,out); - writeLittleEndian((int)handoutMasterPersist,out); - - // The ID of the first slide - writeLittleEndian((short)firstSlideNum,out); - - // The slide size type - writeLittleEndian((short)slideSizeType,out); - - // The booleans as bytes - out.write(saveWithFonts); - out.write(omitTitlePlace); - out.write(rightToLeft); - out.write(showComments); - - // Reserved data - out.write(reserved); - } - - /** - * Holds the different Slide Size values - */ - public static final class SlideSize { - public static final int ON_SCREEN = 0; - public static final int LETTER_SIZED_PAPER = 1; - public static final int A4_SIZED_PAPER = 2; - public static final int ON_35MM = 3; - public static final int OVERHEAD = 4; - public static final int BANNER = 5; - public static final int CUSTOM = 6; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/DocumentEncryptionAtom.java b/src/scratchpad/src/org/apache/poi/hslf/record/DocumentEncryptionAtom.java deleted file mode 100644 index 57f0f31ed..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/DocumentEncryptionAtom.java +++ /dev/null @@ -1,132 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.util.Map; - -import org.apache.poi.poifs.crypt.CipherAlgorithm; -import org.apache.poi.poifs.crypt.EncryptionInfo; -import org.apache.poi.poifs.crypt.EncryptionMode; -import org.apache.poi.poifs.crypt.HashAlgorithm; -import org.apache.poi.poifs.crypt.cryptoapi.CryptoAPIEncryptionHeader; -import org.apache.poi.poifs.crypt.cryptoapi.CryptoAPIEncryptionVerifier; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.LittleEndianByteArrayOutputStream; -import org.apache.poi.util.LittleEndianInputStream; - -/** - * A Document Encryption Atom (type 12052). Holds information - * on the Encryption of a Document - * - * @author Nick Burch - */ -public final class DocumentEncryptionAtom extends PositionDependentRecordAtom { - private static final long _type = 12052l; - private final byte[] _header; - private EncryptionInfo ei; - - /** - * For the Document Encryption Atom - */ - protected DocumentEncryptionAtom(byte[] source, int start, int len) throws IOException { - // Get the header - _header = new byte[8]; - System.arraycopy(source,start,_header,0,8); - - ByteArrayInputStream bis = new ByteArrayInputStream(source, start+8, len-8); - LittleEndianInputStream leis = new LittleEndianInputStream(bis); - ei = new EncryptionInfo(leis, EncryptionMode.cryptoAPI); - leis.close(); - } - - public DocumentEncryptionAtom() { - _header = new byte[8]; - LittleEndian.putShort(_header, 0, (short)0x000F); - LittleEndian.putShort(_header, 2, (short)_type); - // record length not yet known ... - - ei = new EncryptionInfo(EncryptionMode.cryptoAPI); - } - - /** - * Initializes the encryption settings - * - * @param keyBits see {@link CipherAlgorithm#rc4} for allowed values, use -1 for default size - */ - public void initializeEncryptionInfo(int keyBits) { - ei = new EncryptionInfo(EncryptionMode.cryptoAPI, CipherAlgorithm.rc4, HashAlgorithm.sha1, keyBits, -1, null); - } - - /** - * Return the length of the encryption key, in bits - */ - public int getKeyLength() { - return ei.getHeader().getKeySize(); - } - - /** - * Return the name of the encryption provider used - */ - public String getEncryptionProviderName() { - return ei.getHeader().getCspName(); - } - - /** - * @return the {@link EncryptionInfo} object for details about encryption settings - */ - public EncryptionInfo getEncryptionInfo() { - return ei; - } - - - /** - * We are of type 12052 - */ - public long getRecordType() { return _type; } - - /** - * Write the contents of the record back, so it can be written - * to disk - */ - public void writeOut(OutputStream out) throws IOException { - - // Data - byte data[] = new byte[1024]; - LittleEndianByteArrayOutputStream bos = new LittleEndianByteArrayOutputStream(data, 0); - bos.writeShort(ei.getVersionMajor()); - bos.writeShort(ei.getVersionMinor()); - bos.writeInt(ei.getEncryptionFlags()); - - ((CryptoAPIEncryptionHeader)ei.getHeader()).write(bos); - ((CryptoAPIEncryptionVerifier)ei.getVerifier()).write(bos); - - // Header - LittleEndian.putInt(_header, 4, bos.getWriteIndex()); - out.write(_header); - out.write(data, 0, bos.getWriteIndex()); - bos.close(); - } - - @Override - public void updateOtherRecordReferences(Map oldToNewReferencesLookup) { - // nothing to update - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/DummyPositionSensitiveRecordWithChildren.java b/src/scratchpad/src/org/apache/poi/hslf/record/DummyPositionSensitiveRecordWithChildren.java deleted file mode 100644 index 285f824b4..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/DummyPositionSensitiveRecordWithChildren.java +++ /dev/null @@ -1,67 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import org.apache.poi.util.LittleEndian; -import java.io.IOException; -import java.io.OutputStream; - -/** - * If we come across a record we know has children of (potential) - * interest, but where the record itself is boring, but where other - * records may care about where this one lives, we create one - * of these. It allows us to get at the children, and track where on - * disk this is, but not much else. - * Anything done using this should quite quickly be transitioned to its - * own proper record class! - * - * @author Nick Burch - */ - -public final class DummyPositionSensitiveRecordWithChildren extends PositionDependentRecordContainer -{ - private byte[] _header; - private long _type; - - /** - * Create a new holder for a boring record with children, but with - * position dependent characteristics - */ - protected DummyPositionSensitiveRecordWithChildren(byte[] source, int start, int len) { - // Just grab the header, not the whole contents - _header = new byte[8]; - System.arraycopy(source,start,_header,0,8); - _type = LittleEndian.getUShort(_header,2); - - // Find our children - _children = Record.findChildRecords(source,start+8,len-8); - } - - /** - * Return the value we were given at creation - */ - public long getRecordType() { return _type; } - - /** - * Write the contents of the record back, so it can be written - * to disk - */ - public void writeOut(OutputStream out) throws IOException { - writeOut(_header[0],_header[1],_type,_children,out); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/DummyRecordWithChildren.java b/src/scratchpad/src/org/apache/poi/hslf/record/DummyRecordWithChildren.java deleted file mode 100644 index 18dea5892..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/DummyRecordWithChildren.java +++ /dev/null @@ -1,62 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import org.apache.poi.util.LittleEndian; -import java.io.IOException; -import java.io.OutputStream; - -/** - * If we come across a record we know has children of (potential) - * interest, but where the record itself is boring, we create one - * of these. It allows us to get at the children, but not much else - * - * @author Nick Burch - */ - -public final class DummyRecordWithChildren extends RecordContainer -{ - private byte[] _header; - private long _type; - - /** - * Create a new holder for a boring record with children - */ - protected DummyRecordWithChildren(byte[] source, int start, int len) { - // Just grab the header, not the whole contents - _header = new byte[8]; - System.arraycopy(source,start,_header,0,8); - _type = LittleEndian.getUShort(_header,2); - - // Find our children - _children = Record.findChildRecords(source,start+8,len-8); - } - - /** - * Return the value we were given at creation - */ - public long getRecordType() { return _type; } - - /** - * Write the contents of the record back, so it can be written - * to disk - */ - public void writeOut(OutputStream out) throws IOException { - writeOut(_header[0],_header[1],_type,_children,out); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/Environment.java b/src/scratchpad/src/org/apache/poi/hslf/record/Environment.java deleted file mode 100644 index eb66f2a28..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/Environment.java +++ /dev/null @@ -1,86 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import java.io.IOException; -import java.io.OutputStream; - -/** - * Environment, which contains lots of settings for the document. - * - * @author Nick Burch - */ - -public final class Environment extends PositionDependentRecordContainer -{ - private byte[] _header; - private static long _type = 1010; - - // Links to our more interesting children - private FontCollection fontCollection; - //master style for text with type=TextHeaderAtom.OTHER_TYPE - private TxMasterStyleAtom txmaster; - - /** - * Returns the FontCollection of this Environment - */ - public FontCollection getFontCollection() { return fontCollection; } - - - /** - * Set things up, and find our more interesting children - */ - protected Environment(byte[] source, int start, int len) { - // Grab the header - _header = new byte[8]; - System.arraycopy(source,start,_header,0,8); - - // Find our children - _children = Record.findChildRecords(source,start+8,len-8); - - // Find our FontCollection record - for(int i=0; i<_children.length; i++) { - if(_children[i] instanceof FontCollection) { - fontCollection = (FontCollection)_children[i]; - } else if (_children[i] instanceof TxMasterStyleAtom){ - txmaster = (TxMasterStyleAtom)_children[i]; - } - } - - if(fontCollection == null) { - throw new IllegalStateException("Environment didn't contain a FontCollection record!"); - } - } - - public TxMasterStyleAtom getTxMasterStyleAtom(){ - return txmaster; - } - - /** - * We are of type 1010 - */ - public long getRecordType() { return _type; } - - /** - * Write the contents of the record back, so it can be written - * to disk - */ - public void writeOut(OutputStream out) throws IOException { - writeOut(_header[0],_header[1],_type,_children,out); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/EscherPlaceholder.java b/src/scratchpad/src/org/apache/poi/hslf/record/EscherPlaceholder.java deleted file mode 100644 index 4a944516b..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/EscherPlaceholder.java +++ /dev/null @@ -1,75 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import org.apache.poi.ddf.*; -import org.apache.poi.util.*; - -/** - * An atom record that specifies whether a shape is a placeholder shape. - * The number, position, and type of placeholder shapes are determined by - * the slide layout as specified in the SlideAtom record. - */ -public class EscherPlaceholder extends EscherRecord { - public static final short RECORD_ID = RecordTypes.OEPlaceholderAtom.typeID; - public static final String RECORD_DESCRIPTION = "msofbtClientTextboxPlaceholder"; - - private int position = -1; - private byte placementId = 0; - private byte size = 0; - private short unused = 0; - - public EscherPlaceholder() {} - - public int fillFields(byte[] data, int offset, EscherRecordFactory recordFactory) { - int bytesRemaining = readHeader( data, offset ); - - position = LittleEndian.getInt(data, offset+8); - placementId = data[offset+12]; - size = data[offset+13]; - unused = LittleEndian.getShort(data, offset+14); - - assert(bytesRemaining + 8 == 16); - return bytesRemaining + 8; - } - - public int serialize(int offset, byte[] data, EscherSerializationListener listener) { - listener.beforeRecordSerialize( offset, getRecordId(), this ); - - LittleEndian.putShort(data, offset, getOptions()); - LittleEndian.putShort(data, offset+2, getRecordId()); - LittleEndian.putInt(data, offset+4, 8); - LittleEndian.putInt(data, offset+8, position); - LittleEndian.putByte(data, offset+12, placementId); - LittleEndian.putByte(data, offset+13, size); - LittleEndian.putShort(data, offset+14, unused); - - listener.afterRecordSerialize( offset+getRecordSize(), getRecordId(), getRecordSize(), this ); - return getRecordSize(); - } - - public int getRecordSize() { - return 8 + 8; - } - - public String getRecordName() { - return "ClientTextboxPlaceholder"; - } - - -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/EscherTextboxWrapper.java b/src/scratchpad/src/org/apache/poi/hslf/record/EscherTextboxWrapper.java deleted file mode 100644 index 10744e49d..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/EscherTextboxWrapper.java +++ /dev/null @@ -1,121 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import org.apache.poi.ddf.*; - -import java.io.IOException; -import java.io.OutputStream; -import java.io.ByteArrayOutputStream; - -/** - * A wrapper around a DDF (Escher) EscherTextbox Record. Causes the DDF - * Record to be accessible as if it were a HSLF record. - * Note: when asked to write out, will simply put any child records correctly - * into the Escher layer. A call to the escher layer to write out (by the - * parent PPDrawing) will do the actual write out - * - * @author Nick Burch - */ -public final class EscherTextboxWrapper extends RecordContainer { - private EscherTextboxRecord _escherRecord; - private long _type; - private int shapeId; - private StyleTextPropAtom styleTextPropAtom; - private StyleTextProp9Atom styleTextProp9Atom; - - /** - * Returns the underlying DDF Escher Record - */ - public EscherTextboxRecord getEscherRecord() { return _escherRecord; } - - /** - * Creates the wrapper for the given DDF Escher Record and children - */ - public EscherTextboxWrapper(EscherTextboxRecord textbox) { - _escherRecord = textbox; - _type = _escherRecord.getRecordId(); - - // Find the child records in the escher data - byte[] data = _escherRecord.getData(); - _children = Record.findChildRecords(data,0,data.length); - for (Record r : this._children) { - if (r instanceof StyleTextPropAtom) { this.styleTextPropAtom = (StyleTextPropAtom) r; } - } - } - - /** - * Creates a new, empty wrapper for DDF Escher Records and their children - */ - public EscherTextboxWrapper() { - _escherRecord = new EscherTextboxRecord(); - _escherRecord.setRecordId(EscherTextboxRecord.RECORD_ID); - _escherRecord.setOptions((short)15); - - _children = new Record[0]; - } - - - /** - * Return the type of the escher record (normally in the 0xFnnn range) - */ - public long getRecordType() { return _type; } - - /** - * Stores the data for the child records back into the Escher layer. - * Doesn't actually do the writing out, that's left to the Escher - * layer to do. Must be called before writeOut/serialize is called - * on the underlying Escher object! - */ - public void writeOut(OutputStream out) throws IOException { - // Write out our children, and stuff them into the Escher layer - - // Grab the children's data - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - for (Record r : _children) r.writeOut(baos); - byte[] data = baos.toByteArray(); - - // Save in the escher layer - _escherRecord.setData(data); - } - - /** - * @return Shape ID - */ - public int getShapeId(){ - return shapeId; - } - - /** - * @param id Shape ID - */ - public void setShapeId(int id){ - shapeId = id; - } - - public StyleTextPropAtom getStyleTextPropAtom() { - return styleTextPropAtom; - } - - public void setStyleTextProp9Atom(final StyleTextProp9Atom nineAtom) { - this.styleTextProp9Atom = nineAtom; - } - public StyleTextProp9Atom getStyleTextProp9Atom() { - return this.styleTextProp9Atom; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/ExAviMovie.java b/src/scratchpad/src/org/apache/poi/hslf/record/ExAviMovie.java deleted file mode 100644 index 62a5c4bbe..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/ExAviMovie.java +++ /dev/null @@ -1,48 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - - -/** - * A container record that specifies information about a movie stored externally. - * - * @author Yegor Kozlov - */ -public final class ExAviMovie extends ExMCIMovie { - - /** - * Set things up, and find our more interesting children - */ - protected ExAviMovie(byte[] source, int start, int len) { - super(source, start, len); - } - - /** - * Create a new ExAviMovie, with blank fields - */ - public ExAviMovie() { - super(); - - } - /** - * We are of type 4102 - */ - public long getRecordType() { - return RecordTypes.ExAviMovie.typeID; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/ExControl.java b/src/scratchpad/src/org/apache/poi/hslf/record/ExControl.java deleted file mode 100644 index 58be5715e..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/ExControl.java +++ /dev/null @@ -1,75 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - - -/** - * A container record that specifies information about an ActiveX control. It contains: - *

    - * 1. ExControlAtom (4091) - * 2. ExOleObjAtom (4035) - * 3. CString (4026), Instance MenuName (1) used for menus and the Links dialog box. - * 4. CString (4026), Instance ProgID (2) that stores the OLE Programmatic Identifier. - * A ProgID is a string that uniquely identifies a given object. - * 5. CString (4026), Instance ClipboardName (3) that appears in the paste special dialog. - * 6. MetaFile( 4033), optional - *

    - * - * - * @author Yegor kozlov - */ -public final class ExControl extends ExEmbed { - - /** - * Set things up, and find our more interesting children - * - * @param source the source data as a byte array. - * @param start the start offset into the byte array. - * @param len the length of the slice in the byte array. - */ - protected ExControl(byte[] source, int start, int len) { - super(source, start, len); - } - - /** - * Create a new ExEmbed, with blank fields - */ - public ExControl() { - super(new ExControlAtom()); - } - - /** - * Gets the {@link ExControlAtom}. - * - * @return the {@link ExControlAtom}. - */ - public ExControlAtom getExControlAtom() - { - return (ExControlAtom)_children[0]; - } - - /** - * Returns the type (held as a little endian in bytes 3 and 4) - * that this class handles. - * - * @return the record type. - */ - public long getRecordType() { - return RecordTypes.ExControl.typeID; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/ExControlAtom.java b/src/scratchpad/src/org/apache/poi/hslf/record/ExControlAtom.java deleted file mode 100644 index b5540cee5..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/ExControlAtom.java +++ /dev/null @@ -1,117 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import java.io.IOException; -import java.io.OutputStream; - -import org.apache.poi.util.LittleEndian; - -/** - * An atom record that specifies an ActiveX control. - * - * @author Yegor Kozlov - */ -public final class ExControlAtom extends RecordAtom { - - - /** - * Record header. - */ - private byte[] _header; - - /** - * slideId. - */ - private int _id; - - /** - * Constructs a brand new embedded object atom record. - */ - protected ExControlAtom() { - _header = new byte[8]; - - LittleEndian.putShort(_header, 2, (short) getRecordType()); - LittleEndian.putInt(_header, 4, 4); - - } - - /** - * Constructs the ExControlAtom record from its source data. - * - * @param source the source data as a byte array. - * @param start the start offset into the byte array. - * @param len the length of the slice in the byte array. - */ - protected ExControlAtom(byte[] source, int start, int len) { - // Get the header. - _header = new byte[8]; - System.arraycopy(source, start, _header, 0, 8); - - _id = LittleEndian.getInt(source, start + 8); - } - - /** - * An integer that specifies which presentation slide is associated with the ActiveX control. - *

    - * It MUST be 0x00000000 or equal to the value of the slideId field of a SlidePersistAtom record. - * The value 0x00000000 specifies a null reference. - *

    - * - * @return an integer that specifies which presentation slide is associated with the ActiveX control - */ - public int getSlideId() { - return _id; - } - - /** - * Sets which presentation slide is associated with the ActiveX control. - * - * @param id an integer that specifies which presentation slide is associated with the ActiveX control - *

    - * It MUST be 0x00000000 or equal to the value of the slideId field of a SlidePersistAtom record. - * The value 0x00000000 specifies a null reference. - *

    - */ - public void setSlideId(int id) { - _id = id; - } - - /** - * Gets the record type. - * @return the record type. - */ - public long getRecordType() { - return RecordTypes.ExControlAtom.typeID; - } - - /** - * Write the contents of the record back, so it can be written - * to disk - * - * @param out the output stream to write to. - * @throws java.io.IOException if an error occurs. - */ - public void writeOut(OutputStream out) throws IOException { - out.write(_header); - byte[] data = new byte[4]; - LittleEndian.putInt(data, 0, _id); - out.write(data); - } - -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/ExEmbed.java b/src/scratchpad/src/org/apache/poi/hslf/record/ExEmbed.java deleted file mode 100644 index 7903bb32d..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/ExEmbed.java +++ /dev/null @@ -1,216 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import java.io.OutputStream; -import java.io.IOException; - -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.POILogger; - -/** - * This data represents an embedded object in the document. - */ -public class ExEmbed extends RecordContainer { - - /** - * Record header data. - */ - private byte[] _header; - - // Links to our more interesting children - private RecordAtom embedAtom; - private ExOleObjAtom oleObjAtom; - private CString menuName; - private CString progId; - private CString clipboardName; - - /** - * Set things up, and find our more interesting children - * - * @param source the source data as a byte array. - * @param start the start offset into the byte array. - * @param len the length of the slice in the byte array. - */ - protected ExEmbed(byte[] source, int start, int len) { - // Grab the header - _header = new byte[8]; - System.arraycopy(source,start,_header,0,8); - - // Find our children - _children = Record.findChildRecords(source,start+8,len-8); - findInterestingChildren(); - } - - /** - * Constructor for derived classes - * - * @param embedAtom the new embedAtom - */ - protected ExEmbed(RecordAtom embedAtom) { - this(); - _children[0] = this.embedAtom = embedAtom; - } - - - - /** - * Create a new ExEmbed, with blank fields - */ - public ExEmbed() { - _header = new byte[8]; - _children = new Record[5]; - - // Setup our header block - _header[0] = 0x0f; // We are a container record - LittleEndian.putShort(_header, 2, (short)getRecordType()); - - // Setup our child records - CString cs1 = new CString(); - cs1.setOptions(0x1 << 4); - CString cs2 = new CString(); - cs2.setOptions(0x2 << 4); - CString cs3 = new CString(); - cs3.setOptions(0x3 << 4); - _children[0] = new ExEmbedAtom(); - _children[1] = new ExOleObjAtom(); - _children[2] = cs1; - _children[3] = cs2; - _children[4] = cs3; - findInterestingChildren(); - } - - /** - * Go through our child records, picking out the ones that are - * interesting, and saving those for use by the easy helper methods. - */ - private void findInterestingChildren() { - - // First child should be the ExHyperlinkAtom - if(_children[0] instanceof ExEmbedAtom) { - embedAtom = (ExEmbedAtom)_children[0]; - } else { - logger.log(POILogger.ERROR, "First child record wasn't a ExEmbedAtom, was of type " + _children[0].getRecordType()); - } - - // Second child should be the ExOleObjAtom - if (_children[1] instanceof ExOleObjAtom) { - oleObjAtom = (ExOleObjAtom)_children[1]; - } else { - logger.log(POILogger.ERROR, "Second child record wasn't a ExOleObjAtom, was of type " + _children[1].getRecordType()); - } - - for (int i = 2; i < _children.length; i++) { - if (_children[i] instanceof CString){ - CString cs = (CString)_children[i]; - int opts = cs.getOptions() >> 4; - switch(opts){ - case 0x1: menuName = cs; break; - case 0x2: progId = cs; break; - case 0x3: clipboardName = cs; break; - default: break; - } - } - } - } - - /** - * Gets the {@link ExEmbedAtom}. - * - * @return the {@link ExEmbedAtom}. - */ - public ExEmbedAtom getExEmbedAtom() - { - return (ExEmbedAtom)embedAtom; - } - - /** - * Gets the {@link ExOleObjAtom}. - * - * @return the {@link ExOleObjAtom}. - */ - public ExOleObjAtom getExOleObjAtom() - { - return oleObjAtom; - } - - /** - * Gets the name used for menus and the Links dialog box. - * - * @return the name used for menus and the Links dialog box. - */ - public String getMenuName() - { - return menuName == null ? null : menuName.getText(); - } - - public void setMenuName(String s) - { - if(menuName != null) menuName.setText(s); - } - - /** - * Gets the OLE Programmatic Identifier. - * - * @return the OLE Programmatic Identifier. - */ - public String getProgId() - { - return progId == null ? null : progId.getText(); - } - - public void setProgId(String s) - { - if(progId != null) progId.setText(s); - } - /** - * Gets the name that appears in the paste special dialog. - * - * @return the name that appears in the paste special dialog. - */ - public String getClipboardName() - { - return clipboardName == null ? null : clipboardName.getText(); - } - - public void setClipboardName(String s) - { - if(clipboardName != null) clipboardName.setText(s); - } - - /** - * Returns the type (held as a little endian in bytes 3 and 4) - * that this class handles. - * - * @return the record type. - */ - public long getRecordType() { - return RecordTypes.ExEmbed.typeID; - } - - /** - * Have the contents printer out into an OutputStream, used when - * writing a file back out to disk. - * - * @param out the output stream. - * @throws IOException if there was an error writing to the stream. - */ - public void writeOut(OutputStream out) throws IOException { - writeOut(_header[0],_header[1],getRecordType(),_children,out); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/ExEmbedAtom.java b/src/scratchpad/src/org/apache/poi/hslf/record/ExEmbedAtom.java deleted file mode 100644 index 94aba471d..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/ExEmbedAtom.java +++ /dev/null @@ -1,165 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import java.io.IOException; -import java.io.OutputStream; - -import org.apache.poi.util.LittleEndian; - -/** - * The atom that holds metadata on a specific embedded object in the document. - * - * - * - * @author Daniel Noll - */ -public class ExEmbedAtom extends RecordAtom { - - /** - * Embedded document does not follow the color scheme. - */ - public static final int DOES_NOT_FOLLOW_COLOR_SCHEME = 0; - - /** - * Embedded document follows the entire color scheme. - */ - public static final int FOLLOWS_ENTIRE_COLOR_SCHEME = 1; - - /** - * Embedded document follows the text and background scheme. - */ - public static final int FOLLOWS_TEXT_AND_BACKGROUND_SCHEME = 2; - - /** - * Record header. - */ - private byte[] _header; - - /** - * Record data. - */ - private byte[] _data; - - /** - * Constructs a brand new embedded object atom record. - */ - protected ExEmbedAtom() { - _header = new byte[8]; - _data = new byte[8]; - - LittleEndian.putShort(_header, 2, (short)getRecordType()); - LittleEndian.putInt(_header, 4, _data.length); - - // It is fine for the other values to be zero - } - - /** - * Constructs the embedded object atom record from its source data. - * - * @param source the source data as a byte array. - * @param start the start offset into the byte array. - * @param len the length of the slice in the byte array. - */ - protected ExEmbedAtom(byte[] source, int start, int len) { - // Get the header. - _header = new byte[8]; - System.arraycopy(source,start,_header,0,8); - - // Get the record data. - _data = new byte[len-8]; - System.arraycopy(source,start+8,_data,0,len-8); - - // Must be at least 8 bytes long - if(_data.length < 8) { - throw new IllegalArgumentException("The length of the data for a ExEmbedAtom must be at least 4 bytes, but was only " + _data.length); - } - } - - /** - * Gets whether the object follows the color scheme. - * - * @return one of {@link #DOES_NOT_FOLLOW_COLOR_SCHEME}, - * {@link #FOLLOWS_ENTIRE_COLOR_SCHEME}, or - * {@link #FOLLOWS_TEXT_AND_BACKGROUND_SCHEME}. - */ - public int getFollowColorScheme() { - return LittleEndian.getInt(_data, 0); - } - - /** - * Gets whether the embedded server cannot be locked. - * - * @return {@code true} if the embedded server cannot be locked. - */ - public boolean getCantLockServerB() { - return _data[4] != 0; - } - - public void setCantLockServerB(boolean cantBeLocked) { - _data[4] = (byte)(cantBeLocked ? 1 : 0); - } - - /** - * Gets whether it is not required to send the dimensions to the embedded object. - * - * @return {@code true} if the embedded server does not require the object dimensions. - */ - public boolean getNoSizeToServerB() { - return _data[5] != 0; - } - - /** - * Getswhether the object is a Word table. - * - * @return {@code true} if the object is a Word table. - */ - public boolean getIsTable() { - return _data[6] != 0; - } - - /** - * Gets the record type. - * @return the record type. - */ - public long getRecordType() { - return RecordTypes.ExEmbedAtom.typeID; - } - - /** - * Write the contents of the record back, so it can be written - * to disk - * - * @param out the output stream to write to. - * @throws IOException if an error occurs. - */ - public void writeOut(OutputStream out) throws IOException { - out.write(_header); - out.write(_data); - } - -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/ExHyperlink.java b/src/scratchpad/src/org/apache/poi/hslf/record/ExHyperlink.java deleted file mode 100644 index ca9d68d78..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/ExHyperlink.java +++ /dev/null @@ -1,168 +0,0 @@ -/* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.apache.poi.hslf.record; - -import java.io.IOException; -import java.io.OutputStream; - -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.POILogger; - -/** - * This class represents the data of a link in the document. - * @author Nick Burch - */ -public class ExHyperlink extends RecordContainer { - private byte[] _header; - private static long _type = 4055; - - // Links to our more interesting children - private ExHyperlinkAtom linkAtom; - private CString linkDetailsA; - private CString linkDetailsB; - - /** - * Returns the ExHyperlinkAtom of this link - */ - public ExHyperlinkAtom getExHyperlinkAtom() { return linkAtom; } - - /** - * Returns the URL of the link. - * - * @return the URL of the link - */ - public String getLinkURL() { - return linkDetailsB == null ? null : linkDetailsB.getText(); - } - - /** - * Returns the hyperlink's user-readable name - * - * @return the hyperlink's user-readable name - */ - public String getLinkTitle() { - return linkDetailsA == null ? null : linkDetailsA.getText(); - } - - /** - * Sets the URL of the link - * TODO: Figure out if we should always set both - */ - public void setLinkURL(String url) { - if(linkDetailsB != null) { - linkDetailsB.setText(url); - } - } - - public void setLinkOptions(int options) { - if(linkDetailsB != null) { - linkDetailsB.setOptions(options); - } - } - - public void setLinkTitle(String title) { - if(linkDetailsA != null) { - linkDetailsA.setText(title); - } - } - - /** - * Get the link details (field A) - */ - public String _getDetailsA() { - return linkDetailsA == null ? null : linkDetailsA.getText(); - } - /** - * Get the link details (field B) - */ - public String _getDetailsB() { - return linkDetailsB == null ? null : linkDetailsB.getText(); - } - - /** - * Set things up, and find our more interesting children - */ - protected ExHyperlink(byte[] source, int start, int len) { - // Grab the header - _header = new byte[8]; - System.arraycopy(source,start,_header,0,8); - - // Find our children - _children = Record.findChildRecords(source,start+8,len-8); - findInterestingChildren(); - } - - /** - * Go through our child records, picking out the ones that are - * interesting, and saving those for use by the easy helper - * methods. - */ - private void findInterestingChildren() { - - // First child should be the ExHyperlinkAtom - if(_children[0] instanceof ExHyperlinkAtom) { - linkAtom = (ExHyperlinkAtom)_children[0]; - } else { - logger.log(POILogger.ERROR, "First child record wasn't a ExHyperlinkAtom, was of type " + _children[0].getRecordType()); - } - - for (int i = 1; i < _children.length; i++) { - if (_children[i] instanceof CString){ - if ( linkDetailsA == null) linkDetailsA = (CString)_children[i]; - else linkDetailsB = (CString)_children[i]; - } else { - logger.log(POILogger.ERROR, "Record after ExHyperlinkAtom wasn't a CString, was of type " + _children[1].getRecordType()); - } - - } - } - - /** - * Create a new ExHyperlink, with blank fields - */ - public ExHyperlink() { - _header = new byte[8]; - _children = new Record[3]; - - // Setup our header block - _header[0] = 0x0f; // We are a container record - LittleEndian.putShort(_header, 2, (short)_type); - - // Setup our child records - CString csa = new CString(); - CString csb = new CString(); - csa.setOptions(0x00); - csb.setOptions(0x10); - _children[0] = new ExHyperlinkAtom(); - _children[1] = csa; - _children[2] = csb; - findInterestingChildren(); - } - - /** - * We are of type 4055 - */ - public long getRecordType() { return _type; } - - /** - * Write the contents of the record back, so it can be written - * to disk - */ - public void writeOut(OutputStream out) throws IOException { - writeOut(_header[0],_header[1],_type,_children,out); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/ExHyperlinkAtom.java b/src/scratchpad/src/org/apache/poi/hslf/record/ExHyperlinkAtom.java deleted file mode 100644 index 99deafdbf..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/ExHyperlinkAtom.java +++ /dev/null @@ -1,112 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import java.io.IOException; -import java.io.OutputStream; - -import org.apache.poi.util.LittleEndian; - -/** - * Tne atom that holds metadata on a specific Link in the document. - * (The actual link is held in a sibling CString record) - * - * @author Nick Burch - */ -public final class ExHyperlinkAtom extends RecordAtom { - /** - * Record header. - */ - private byte[] _header; - - /** - * Record data. - */ - private byte[] _data; - - /** - * Constructs a brand new link related atom record. - */ - protected ExHyperlinkAtom() { - _header = new byte[8]; - _data = new byte[4]; - - LittleEndian.putShort(_header, 2, (short)getRecordType()); - LittleEndian.putInt(_header, 4, _data.length); - - // It is fine for the other values to be zero - } - - /** - * Constructs the link related atom record from its - * source data. - * - * @param source the source data as a byte array. - * @param start the start offset into the byte array. - * @param len the length of the slice in the byte array. - */ - protected ExHyperlinkAtom(byte[] source, int start, int len) { - // Get the header. - _header = new byte[8]; - System.arraycopy(source,start,_header,0,8); - - // Get the record data. - _data = new byte[len-8]; - System.arraycopy(source,start+8,_data,0,len-8); - - // Must be at least 4 bytes long - if(_data.length < 4) { - throw new IllegalArgumentException("The length of the data for a ExHyperlinkAtom must be at least 4 bytes, but was only " + _data.length); - } - } - - /** - * Gets the link number. This will match the one in the - * InteractiveInfoAtom which uses the link. - * @return the link number - */ - public int getNumber() { - return LittleEndian.getInt(_data,0); - } - - /** - * Sets the link number - * @param number the link number. - */ - public void setNumber(int number) { - LittleEndian.putInt(_data,0,number); - } - - /** - * Gets the record type. - * @return the record type. - */ - public long getRecordType() { return RecordTypes.ExHyperlinkAtom.typeID; } - - /** - * Write the contents of the record back, so it can be written - * to disk - * - * @param out the output stream to write to. - * @throws IOException if an error occurs. - */ - public void writeOut(OutputStream out) throws IOException { - out.write(_header); - out.write(_data); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/ExMCIMovie.java b/src/scratchpad/src/org/apache/poi/hslf/record/ExMCIMovie.java deleted file mode 100644 index 7d2417587..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/ExMCIMovie.java +++ /dev/null @@ -1,101 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import java.io.IOException; -import java.io.OutputStream; - -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.POILogger; - -/** - * A container record that specifies information about a movie stored externally. - * - * @author Yegor Kozlov - */ -public class ExMCIMovie extends RecordContainer { // TODO - instantiable superclass - private byte[] _header; - - //An ExVideoContainer record that specifies information about the MCI movie - private ExVideoContainer exVideo; - - /** - * Set things up, and find our more interesting children - */ - protected ExMCIMovie(byte[] source, int start, int len) { - // Grab the header - _header = new byte[8]; - System.arraycopy(source, start, _header, 0, 8); - - // Find our children - _children = Record.findChildRecords(source, start + 8, len - 8); - findInterestingChildren(); - } - - /** - * Create a new ExMCIMovie, with blank fields - */ - public ExMCIMovie() { - _header = new byte[8]; - // Setup our header block - _header[0] = 0x0f; // We are a container record - LittleEndian.putShort(_header, 2, (short) getRecordType()); - - exVideo = new ExVideoContainer(); - _children = new Record[]{exVideo}; - - } - - /** - * Go through our child records, picking out the ones that are - * interesting, and saving those for use by the easy helper - * methods. - */ - private void findInterestingChildren() { - - // First child should be the ExVideoContainer - if (_children[0] instanceof ExVideoContainer) { - exVideo = (ExVideoContainer) _children[0]; - } else { - logger.log(POILogger.ERROR, "First child record wasn't a ExVideoContainer, was of type " + _children[0].getRecordType()); - } - } - - /** - * We are of type 4103 - */ - public long getRecordType() { - return RecordTypes.ExMCIMovie.typeID; - } - - /** - * Write the contents of the record back, so it can be written - * to disk - */ - public void writeOut(OutputStream out) throws IOException { - writeOut(_header[0], _header[1], getRecordType(), _children, out); - } - - /** - * Returns the ExVideoContainer that specifies information about the MCI movie - */ - public ExVideoContainer getExVideo() { - return exVideo; } - - -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/ExMediaAtom.java b/src/scratchpad/src/org/apache/poi/hslf/record/ExMediaAtom.java deleted file mode 100644 index 058f27ea5..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/ExMediaAtom.java +++ /dev/null @@ -1,169 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import java.io.IOException; -import java.io.OutputStream; - -import org.apache.poi.util.LittleEndian; - -/** - * An atom record that specifies information about external audio or video data. - * - * @author Yegor Kozlov - */ -public final class ExMediaAtom extends RecordAtom -{ - - /** - * A bit that specifies whether the audio or video data is repeated continuously during playback. - */ - public static final int fLoop = 1; - /** - * A bit that specifies whether the audio or video data is rewound after playing. - */ - public static final int fRewind = 2; - /** - * A bit that specifies whether the audio data is recorded narration for the slide show. It MUST be FALSE if this ExMediaAtom record is contained by an ExVideoContainer record. - */ - public static final int fNarration = 4; - - /** - * Record header. - */ - private byte[] _header; - - /** - * record data - */ - private byte[] _recdata; - - /** - * Constructs a brand new link related atom record. - */ - protected ExMediaAtom() { - _recdata = new byte[8]; - - _header = new byte[8]; - LittleEndian.putShort(_header, 2, (short)getRecordType()); - LittleEndian.putInt(_header, 4, _recdata.length); - } - - /** - * Constructs the link related atom record from its - * source data. - * - * @param source the source data as a byte array. - * @param start the start offset into the byte array. - * @param len the length of the slice in the byte array. - */ - protected ExMediaAtom(byte[] source, int start, int len) { - // Get the header - _header = new byte[8]; - System.arraycopy(source,start,_header,0,8); - - // Grab the record data - _recdata = new byte[len-8]; - System.arraycopy(source,start+8,_recdata,0,len-8); - } - - /** - * Gets the record type. - * @return the record type. - */ - public long getRecordType() { return RecordTypes.ExMediaAtom.typeID; } - - /** - * Write the contents of the record back, so it can be written - * to disk - * - * @param out the output stream to write to. - * @throws java.io.IOException if an error occurs. - */ - public void writeOut(OutputStream out) throws IOException { - out.write(_header); - out.write(_recdata); - } - - /** - * A 4-byte unsigned integer that specifies an ID for an external object. - * - * @return A 4-byte unsigned integer that specifies an ID for an external object. - */ - public int getObjectId(){ - return LittleEndian.getInt(_recdata, 0); - } - - /** - * A 4-byte unsigned integer that specifies an ID for an external object. - * - * @param id A 4-byte unsigned integer that specifies an ID for an external object. - */ - public void setObjectId(int id){ - LittleEndian.putInt(_recdata, 0, id); - } - - /** - * A bit mask specifying options for displaying headers and footers - * - * @return A bit mask specifying options for displaying headers and footers - */ - public int getMask(){ - return LittleEndian.getInt(_recdata, 4); - } - - /** - * A bit mask specifying options for displaying video - * - * @param mask A bit mask specifying options for displaying video - */ - public void setMask(int mask){ - LittleEndian.putInt(_recdata, 4, mask); - } - - /** - * @param bit the bit to check - * @return whether the specified flag is set - */ - public boolean getFlag(int bit){ - return (getMask() & bit) != 0; - } - - /** - * @param bit the bit to set - * @param value whether the specified bit is set - */ - public void setFlag(int bit, boolean value){ - int mask = getMask(); - if(value) mask |= bit; - else mask &= ~bit; - setMask(mask); - } - - public String toString(){ - StringBuffer buf = new StringBuffer(); - buf.append("ExMediaAtom\n"); - buf.append("\tObjectId: " + getObjectId() + "\n"); - buf.append("\tMask : " + getMask() + "\n"); - buf.append("\t fLoop : " + getFlag(fLoop) + "\n"); - buf.append("\t fRewind : " + getFlag(fRewind) + "\n"); - buf.append("\t fNarration : " + getFlag(fNarration) + "\n"); - return buf.toString(); - } - -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/ExObjList.java b/src/scratchpad/src/org/apache/poi/hslf/record/ExObjList.java deleted file mode 100644 index 6c40ecf18..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/ExObjList.java +++ /dev/null @@ -1,129 +0,0 @@ -/* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.apache.poi.hslf.record; - -import java.io.IOException; -import java.io.OutputStream; -import java.util.ArrayList; - -import org.apache.poi.util.LittleEndian; - -/** - * This class holds the links to exernal objects referenced - * from the document. - * @author Nick Burch - */ -public class ExObjList extends RecordContainer { - private byte[] _header; - private static long _type = 1033; - - // Links to our more interesting children - private ExObjListAtom exObjListAtom; - - /** - * Returns the ExObjListAtom of this list - */ - public ExObjListAtom getExObjListAtom() { return exObjListAtom; } - - /** - * Returns all the ExHyperlinks - */ - public ExHyperlink[] getExHyperlinks() { - ArrayList links = new ArrayList(); - for(int i=0; i<_children.length; i++) { - if(_children[i] instanceof ExHyperlink) { - links.add( (ExHyperlink)_children[i] ); - } - } - - return links.toArray(new ExHyperlink[links.size()]); - } - - /** - * Set things up, and find our more interesting children - */ - protected ExObjList(byte[] source, int start, int len) { - // Grab the header - _header = new byte[8]; - System.arraycopy(source,start,_header,0,8); - - // Find our children - _children = Record.findChildRecords(source,start+8,len-8); - findInterestingChildren(); - } - - /** - * Go through our child records, picking out the ones that are - * interesting, and saving those for use by the easy helper - * methods. - */ - private void findInterestingChildren() { - // First child should be the atom - if(_children[0] instanceof ExObjListAtom) { - exObjListAtom = (ExObjListAtom)_children[0]; - } else { - throw new IllegalStateException("First child record wasn't a ExObjListAtom, was of type " + _children[0].getRecordType()); - } - } - - /** - * Create a new ExObjList, with blank fields - */ - public ExObjList() { - _header = new byte[8]; - _children = new Record[1]; - - // Setup our header block - _header[0] = 0x0f; // We are a container record - LittleEndian.putShort(_header, 2, (short)_type); - - // Setup our child records - _children[0] = new ExObjListAtom(); - findInterestingChildren(); - } - - /** - * We are of type 1033 - */ - public long getRecordType() { return _type; } - - /** - * Write the contents of the record back, so it can be written - * to disk - */ - public void writeOut(OutputStream out) throws IOException { - writeOut(_header[0],_header[1],_type,_children,out); - } - - /** - * Lookup a hyperlink by its unique id - * - * @param id hyperlink id - * @return found ExHyperlink or null - */ - public ExHyperlink get(int id){ - for(int i=0; i<_children.length; i++) { - if(_children[i] instanceof ExHyperlink) { - ExHyperlink rec = (ExHyperlink)_children[i]; - if (rec.getExHyperlinkAtom().getNumber() == id){ - return rec; - } - } - } - return null; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/ExObjListAtom.java b/src/scratchpad/src/org/apache/poi/hslf/record/ExObjListAtom.java deleted file mode 100644 index 51bb5b4ee..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/ExObjListAtom.java +++ /dev/null @@ -1,114 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - - -package org.apache.poi.hslf.record; - -import java.io.IOException; -import java.io.OutputStream; - -import org.apache.poi.util.LittleEndian; - -/** - * Tne atom that holds the seed info used by a ExObjList - * - * @author Nick Burch - */ - -public class ExObjListAtom extends RecordAtom -{ - /** - * Record header. - */ - private byte[] _header; - - /** - * Record data. - */ - private byte[] _data; - - /** - * Constructs a brand new link related atom record. - */ - protected ExObjListAtom() { - _header = new byte[8]; - _data = new byte[4]; - - LittleEndian.putShort(_header, 2, (short)getRecordType()); - LittleEndian.putInt(_header, 4, _data.length); - - // It is fine for the other values to be zero - } - - /** - * Constructs the link related atom record from its - * source data. - * - * @param source the source data as a byte array. - * @param start the start offset into the byte array. - * @param len the length of the slice in the byte array. - */ - protected ExObjListAtom(byte[] source, int start, int len) { - // Get the header. - _header = new byte[8]; - System.arraycopy(source,start,_header,0,8); - - // Get the record data. - _data = new byte[len-8]; - System.arraycopy(source,start+8,_data,0,len-8); - - // Must be at least 4 bytes long - if(_data.length < 4) { - throw new IllegalArgumentException("The length of the data for a ExObjListAtom must be at least 4 bytes, but was only " + _data.length); - } - } - - /** - * Gets the object ID seed, which will be used as the unique - * OLE identifier for the next OLE object added - * @return the object ID seed - */ - public long getObjectIDSeed() { - return LittleEndian.getUInt(_data,0); - } - - /** - * Sets the object ID seed - * @param seed the new ID seed - */ - public void setObjectIDSeed(int seed) { - LittleEndian.putInt(_data,0,seed); - } - - /** - * Gets the record type. - * @return the record type. - */ - public long getRecordType() { return RecordTypes.ExObjListAtom.typeID; } - - /** - * Write the contents of the record back, so it can be written - * to disk - * - * @param out the output stream to write to. - * @throws IOException if an error occurs. - */ - public void writeOut(OutputStream out) throws IOException { - out.write(_header); - out.write(_data); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/ExObjRefAtom.java b/src/scratchpad/src/org/apache/poi/hslf/record/ExObjRefAtom.java deleted file mode 100644 index 1381e6ab6..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/ExObjRefAtom.java +++ /dev/null @@ -1,94 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import org.apache.poi.util.LittleEndian; -import java.io.IOException; -import java.io.OutputStream; - -/** - * ExObjRefAtom (3009). - *

    - * An atom record that specifies a reference to an external object. - *

    - */ - -public final class ExObjRefAtom extends RecordAtom { - private byte[] _header; - - /** - * A 4-byte unsigned integer that specifies a reference to an external object. - * It MUST be equal to the value of the exObjId field of an ExMediaAtom record - * or the value of the exObjId field of an ExOleObjAtom record. - */ - private int exObjIdRef; - - /** - * Create a new instance of ExObjRefAtom - */ - public ExObjRefAtom() { - _header = new byte[8]; - LittleEndian.putUShort(_header, 0, 0); - LittleEndian.putUShort(_header, 2, (int)getRecordType()); - LittleEndian.putInt(_header, 4, 4); - exObjIdRef = 0; - } - - /** - * Build an instance of ExObjRefAtom from on-disk data - * - * @param source the source data as a byte array. - * @param start the start offset into the byte array. - * @param len the length of the slice in the byte array. - */ - protected ExObjRefAtom(byte[] source, int start, int len) { - _header = new byte[8]; - int offset = start; - System.arraycopy(source,start,_header,0,8); - offset += _header.length; - exObjIdRef = (int)LittleEndian.getUInt(source, offset); - } - - /** - * @return type of this record {@link RecordTypes#ExObjRefAtom}. - */ - public long getRecordType() { - return RecordTypes.ExObjRefAtom.typeID; - } - - public int getExObjIdRef(){ - return exObjIdRef; - } - - public void setExObjIdRef(int id){ - exObjIdRef = id; - } - - /** - * Write the contents of the record back, so it can be written - * to disk - */ - public void writeOut(OutputStream out) throws IOException { - out.write(_header); - - byte[] recdata = new byte[4]; - LittleEndian.putUInt(recdata, 0, exObjIdRef); - - out.write(recdata); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/ExOleObjAtom.java b/src/scratchpad/src/org/apache/poi/hslf/record/ExOleObjAtom.java deleted file mode 100644 index 9f412d249..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/ExOleObjAtom.java +++ /dev/null @@ -1,313 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import java.io.IOException; -import java.io.OutputStream; - -import org.apache.poi.util.LittleEndian; - -/** - * Atom storing information for an OLE object. - * - * - * - * @author Daniel Noll - */ -public class ExOleObjAtom extends RecordAtom { - - /** - * The object) is displayed as an embedded object inside of a container, - */ - public static final int DRAW_ASPECT_VISIBLE = 1; - /** - * The object is displayed as a thumbnail image. - */ - public static final int DRAW_ASPECT_THUMBNAIL = 2; - /** - * The object is displayed as an icon. - */ - public static final int DRAW_ASPECT_ICON = 4; - /** - * The object is displayed on the screen as though it were printed to a printer. - */ - public static final int DRAW_ASPECT_DOCPRINT = 8; - - /** - * An embedded OLE object; the object is serialized and saved within the file. - */ - public static final int TYPE_EMBEDDED = 0; - /** - * A linked OLE object; the object is saved outside of the file. - */ - public static final int TYPE_LINKED = 1; - /** - * The OLE object is an ActiveX control. - */ - public static final int TYPE_CONTROL = 2; - - public static final int SUBTYPE_DEFAULT = 0; - public static final int SUBTYPE_CLIPART_GALLERY = 1; - public static final int SUBTYPE_WORD_TABLE = 2; - public static final int SUBTYPE_EXCEL = 3; - public static final int SUBTYPE_GRAPH = 4; - public static final int SUBTYPE_ORGANIZATION_CHART = 5; - public static final int SUBTYPE_EQUATION = 6; - public static final int SUBTYPE_WORDART = 7; - public static final int SUBTYPE_SOUND = 8; - public static final int SUBTYPE_IMAGE = 9; - public static final int SUBTYPE_POWERPOINT_PRESENTATION = 10; - public static final int SUBTYPE_POWERPOINT_SLIDE = 11; - public static final int SUBTYPE_PROJECT = 12; - public static final int SUBTYPE_NOTEIT = 13; - public static final int SUBTYPE_EXCEL_CHART = 14; - public static final int SUBTYPE_MEDIA_PLAYER = 15; - - /** - * Record header. - */ - private byte[] _header; - - /** - * Record data. - */ - private byte[] _data; - - /** - * Constructs a brand new link related atom record. - */ - public ExOleObjAtom() { - _header = new byte[8]; - _data = new byte[24]; - - LittleEndian.putShort(_header, 0, (short)1); //MUST be 0x1 - LittleEndian.putShort(_header, 2, (short)getRecordType()); - LittleEndian.putInt(_header, 4, _data.length); - } - - /** - * Constructs the link related atom record from its - * source data. - * - * @param source the source data as a byte array. - * @param start the start offset into the byte array. - * @param len the length of the slice in the byte array. - */ - protected ExOleObjAtom(byte[] source, int start, int len) { - // Get the header. - _header = new byte[8]; - System.arraycopy(source,start,_header,0,8); - - // Get the record data. - _data = new byte[len-8]; - System.arraycopy(source,start+8,_data,0,len-8); - - // Must be at least 24 bytes long - if(_data.length < 24) { - throw new IllegalArgumentException("The length of the data for a ExOleObjAtom must be at least 24 bytes, but was only " + _data.length); - } - } - - /** - * Gets whether the object can be completely seen, or if only the - * icon is visible. - * - * @return the draw aspect, one of the {@code DRAW_ASPECT_*} constants. - */ - public int getDrawAspect() { - return LittleEndian.getInt(_data, 0); - } - - /** - * Sets whether the object can be completely seen, or if only the - * icon is visible. - * - * @param aspect the draw aspect, one of the {@code DRAW_ASPECT_*} constants. - */ - public void setDrawAspect(int aspect) { - LittleEndian.putInt(_data, 0, aspect); - } - - /** - * Gets whether the object is embedded or linked. - * - * @return the type, one of the {@code TYPE_EMBEDDED_*} constants. - */ - public int getType() { - return LittleEndian.getInt(_data, 4); - } - - /** - * Sets whether the object is embedded or linked. - * - * @param type the type, one of the {@code TYPE_EMBEDDED_*} constants. - */ - public void setType(int type) { - LittleEndian.putInt(_data, 4, type); - } - - /** - * Gets the unique identifier for the OLE object. - * - * @return the object ID. - */ - public int getObjID() { - return LittleEndian.getInt(_data, 8); - } - - /** - * Sets the unique identifier for the OLE object. - * - * @param id the object ID. - */ - public void setObjID(int id) { - LittleEndian.putInt(_data, 8, id); - } - - /** - * Gets the type of OLE object. - * - * @return the sub-type, one of the {@code SUBTYPE_*} constants. - */ - public int getSubType() { - return LittleEndian.getInt(_data, 12); - } - - /** - * Sets the type of OLE object. - * - * @param type the sub-type, one of the {@code SUBTYPE_*} constants. - */ - public void setSubType(int type) { - LittleEndian.putInt(_data, 12, type); - } - - /** - * Gets the reference to the persistent object - * - * @return the reference to the persistent object, corresponds with an - * {@code ExOleObjStg} storage container. - */ - public int getObjStgDataRef() { - return LittleEndian.getInt(_data, 16); - } - - /** - * Sets the reference to the persistent object - * - * @param ref the reference to the persistent object, corresponds with an - * {@code ExOleObjStg} storage container. - */ - public void setObjStgDataRef(int ref) { - LittleEndian.putInt(_data, 16, ref); - } - - /** - * Gets whether the object's image is blank. - * - * @return {@code true} if the object's image is blank. - */ - public boolean getIsBlank() { - // Even though this is a mere boolean, KOffice's code says it's an int. - return LittleEndian.getInt(_data, 20) != 0; - } - - /** - * Gets misc options (the last four bytes in the atom). - * - * @return {@code true} if the object's image is blank. - */ - public int getOptions() { - // Even though this is a mere boolean, KOffice's code says it's an int. - return LittleEndian.getInt(_data, 20); - } - - /** - * Sets misc options (the last four bytes in the atom). - */ - public void setOptions(int opts) { - // Even though this is a mere boolean, KOffice's code says it's an int. - LittleEndian.putInt(_data, 20, opts); - } - - /** - * Returns the type (held as a little endian in bytes 3 and 4) - * that this class handles. - */ - public long getRecordType() { - return RecordTypes.ExOleObjAtom.typeID; - } - - /** - * Have the contents printer out into an OutputStream, used when - * writing a file back out to disk - * (Normally, atom classes will keep their bytes around, but - * non atom classes will just request the bytes from their - * children, then chuck on their header and return) - */ - public void writeOut(OutputStream out) throws IOException { - out.write(_header); - out.write(_data); - } - - public String toString(){ - StringBuffer buf = new StringBuffer(); - buf.append("ExOleObjAtom\n"); - buf.append(" drawAspect: " + getDrawAspect() + "\n"); - buf.append(" type: " + getType() + "\n"); - buf.append(" objID: " + getObjID() + "\n"); - buf.append(" subType: " + getSubType() + "\n"); - buf.append(" objStgDataRef: " + getObjStgDataRef() + "\n"); - buf.append(" options: " + getOptions() + "\n"); - return buf.toString(); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/ExOleObjStg.java b/src/scratchpad/src/org/apache/poi/hslf/record/ExOleObjStg.java deleted file mode 100644 index 0ba89d723..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/ExOleObjStg.java +++ /dev/null @@ -1,184 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.Map; -import java.util.zip.DeflaterOutputStream; -import java.util.zip.InflaterInputStream; - -import org.apache.poi.util.BoundedInputStream; -import org.apache.poi.util.LittleEndian; - -/** - * Storage for embedded OLE objects. - */ -public class ExOleObjStg extends PositionDependentRecordAtom implements PersistRecord { - - private int _persistId; // Found from PersistPtrHolder - - /** - * Record header. - */ - private final byte[] _header; - - /** - * Record data. - */ - private byte[] _data; - - /** - * Constructs a new empty storage container. - */ - public ExOleObjStg() { - _header = new byte[8]; - _data = new byte[0]; - - LittleEndian.putShort(_header, 0, (short)0x10); - LittleEndian.putShort(_header, 2, (short)getRecordType()); - LittleEndian.putInt(_header, 4, _data.length); - } - - /** - * Constructs the link related atom record from its - * source data. - * - * @param source the source data as a byte array. - * @param start the start offset into the byte array. - * @param len the length of the slice in the byte array. - */ - protected ExOleObjStg(byte[] source, int start, int len) { - // Get the header. - _header = new byte[8]; - System.arraycopy(source,start,_header,0,8); - - // Get the record data. - _data = new byte[len-8]; - System.arraycopy(source,start+8,_data,0,len-8); - } - - public boolean isCompressed() { - return LittleEndian.getShort(_header, 0)!=0; - } - - /** - * Gets the uncompressed length of the data. - * - * @return the uncompressed length of the data. - */ - public int getDataLength() { - if (isCompressed()) { - return LittleEndian.getInt(_data, 0); - } else { - return _data.length; - } - } - - /** - * Opens an input stream which will decompress the data on the fly. - * - * @return the data input stream. - */ - public InputStream getData() { - if (isCompressed()) { - int size = LittleEndian.getInt(_data); - - InputStream compressedStream = new ByteArrayInputStream(_data, 4, _data.length); - return new BoundedInputStream(new InflaterInputStream(compressedStream), size); - } else { - return new ByteArrayInputStream(_data, 0, _data.length); - } - } - - public byte[] getRawData() { - return _data; - } - - /** - * Sets the embedded data. - * - * @param data the embedded data. - */ - public void setData(byte[] data) throws IOException { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - //first four bytes is the length of the raw data - byte[] b = new byte[4]; - LittleEndian.putInt(b, 0, data.length); - out.write(b); - - DeflaterOutputStream def = new DeflaterOutputStream(out); - def.write(data, 0, data.length); - def.finish(); - _data = out.toByteArray(); - LittleEndian.putInt(_header, 4, _data.length); - } - - /** - * Gets the record type. - * - * @return the record type. - */ - public long getRecordType() { - return RecordTypes.ExOleObjStg.typeID; - } - - /** - * Gets the record instance from the header - * - * @return record instance - */ - public int getRecordInstance() { - return (LittleEndian.getUShort(_header, 0) >>> 4); - } - - /** - * Write the contents of the record back, so it can be written - * to disk. - * - * @param out the output stream to write to. - * @throws IOException if an error occurs. - */ - public void writeOut(OutputStream out) throws IOException { - out.write(_header); - out.write(_data); - } - - /** - * Fetch our sheet ID, as found from a PersistPtrHolder. - * Should match the RefId of our matching SlidePersistAtom - */ - public int getPersistId() { - return _persistId; - } - - /** - * Set our sheet ID, as found from a PersistPtrHolder - */ - public void setPersistId(int id) { - _persistId = id; - } - - @Override - public void updateOtherRecordReferences(Map oldToNewReferencesLookup) { - // nothing to update - } -} \ No newline at end of file diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/ExVideoContainer.java b/src/scratchpad/src/org/apache/poi/hslf/record/ExVideoContainer.java deleted file mode 100644 index 473201f26..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/ExVideoContainer.java +++ /dev/null @@ -1,109 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import java.io.IOException; -import java.io.OutputStream; - -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.POILogger; - -/** - * A container record that specifies information about external video data. - * - * @author Yegor Kozlov - */ -public final class ExVideoContainer extends RecordContainer { - private byte[] _header; - - // Links to our more interesting children - private ExMediaAtom mediaAtom; - //the UNC or local path to a video file. - private CString pathAtom; - - /** - * Set things up, and find our more interesting children - */ - protected ExVideoContainer(byte[] source, int start, int len) { - // Grab the header - _header = new byte[8]; - System.arraycopy(source,start,_header,0,8); - - // Find our children - _children = Record.findChildRecords(source,start+8,len-8); - findInterestingChildren(); - } - - /** - * Go through our child records, picking out the ones that are - * interesting, and saving those for use by the easy helper - * methods. - */ - private void findInterestingChildren() { - - // First child should be the ExMediaAtom - if(_children[0] instanceof ExMediaAtom) { - mediaAtom = (ExMediaAtom)_children[0]; - } else { - logger.log(POILogger.ERROR, "First child record wasn't a ExMediaAtom, was of type " + _children[0].getRecordType()); - } - if(_children[1] instanceof CString) { - pathAtom = (CString)_children[1]; - } else { - logger.log(POILogger.ERROR, "Second child record wasn't a CString, was of type " + _children[1].getRecordType()); - } - } - - /** - * Create a new ExVideoContainer, with blank fields - */ - public ExVideoContainer() { - // Setup our header block - _header = new byte[8]; - _header[0] = 0x0f; // We are a container record - LittleEndian.putShort(_header, 2, (short)getRecordType()); - - _children = new Record[2]; - _children[0] = mediaAtom = new ExMediaAtom(); - _children[1] = pathAtom = new CString(); - } - - /** - * We are of type 4103 - */ - public long getRecordType() { return RecordTypes.ExVideoContainer.typeID; } - - /** - * Write the contents of the record back, so it can be written - * to disk - */ - public void writeOut(OutputStream out) throws IOException { - writeOut(_header[0],_header[1],getRecordType(),_children,out); - } - - /** - * Returns the ExMediaAtom of this link - */ - public ExMediaAtom getExMediaAtom() { return mediaAtom; } - - /** - * Returns the Path Atom (CString) of this link - */ - public CString getPathAtom() { return pathAtom; } - -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/FontCollection.java b/src/scratchpad/src/org/apache/poi/hslf/record/FontCollection.java deleted file mode 100644 index b90c698dd..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/FontCollection.java +++ /dev/null @@ -1,129 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import org.apache.poi.hslf.model.PPFont; -import org.apache.poi.util.POILogger; - -import java.io.*; -import java.util.*; - -/** - * FontCollection ia a container that holds information - * about all the fonts in the presentation. - * - * @author Yegor Kozlov - */ - -public final class FontCollection extends RecordContainer { - private List fonts; - private byte[] _header; - - protected FontCollection(byte[] source, int start, int len) { - // Grab the header - _header = new byte[8]; - System.arraycopy(source,start,_header,0,8); - - _children = Record.findChildRecords(source,start+8,len-8); - - // Save font names into List - fonts = new ArrayList(); - for (int i = 0; i < _children.length; i++){ - if(_children[i] instanceof FontEntityAtom) { - FontEntityAtom atom = (FontEntityAtom)_children[i]; - fonts.add(atom.getFontName()); - } else { - logger.log(POILogger.WARN, "Warning: FontCollection child wasn't a FontEntityAtom, was " + _children[i]); - } - } - } - - /** - * Return the type, which is 2005 - */ - public long getRecordType() { - return RecordTypes.FontCollection.typeID; - } - - /** - * Write the contents of the record back, so it can be written - * to disk - */ - public void writeOut(OutputStream out) throws IOException { - writeOut(_header[0],_header[1],getRecordType(),_children,out); - } - - /** - * Add font with the specified name to the font collection. - * If the font is already present return its index. - * @param name of the font - * @return zero based index of the font in the collection - */ - public int addFont(String name) { - int idx = getFontIndex(name); - if (idx != -1) return idx; - - return addFont(name, 0, 0, 4, PPFont.FF_SWISS | PPFont.VARIABLE_PITCH); - } - - public int addFont(String name, int charset, int flags, int type, int pitch) { - FontEntityAtom fnt = new FontEntityAtom(); - fnt.setFontIndex(fonts.size() << 4); - fnt.setFontName(name); - fnt.setCharSet(charset); - fnt.setFontFlags(flags); - fnt.setFontType(type); - fnt.setPitchAndFamily(pitch); - fonts.add(name); - - // Append new child to the end - appendChildRecord(fnt); - - return fonts.size()-1; //the added font is the last in the list - } - - /** - * @return zero based index of the font in the collection or -1 if not found - */ - public int getFontIndex(String name) { - for (int i = 0; i < fonts.size(); i++) { - if(fonts.get(i).equals(name)){ - //if the font is already present return its index - return i; - } - } - return -1; - } - - public int getNumberOfFonts() { - return fonts.size(); - } - - /** - * Get the name of the font at the given ID, or null if there is - * no font at that ID. - * @param id - */ - public String getFontWithId(int id) { - if(id >= fonts.size()) { - // No font with that id - return null; - } - return fonts.get(id); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/FontEntityAtom.java b/src/scratchpad/src/org/apache/poi/hslf/record/FontEntityAtom.java deleted file mode 100644 index 80126fdb9..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/FontEntityAtom.java +++ /dev/null @@ -1,217 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import java.io.IOException; -import java.io.OutputStream; - -import org.apache.poi.hslf.exceptions.HSLFException; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.StringUtil; - -/** - * This atom corresponds exactly to a Windows Logical Font (LOGFONT) structure. - * It keeps all the information needed to define the attributes of a font, - * such as height, width, etc. For more information, consult the - * Windows API Programmer's reference. - * - * @author Yegor Kozlov - */ - -public final class FontEntityAtom extends RecordAtom { - /** - * record header - */ - private byte[] _header; - - /** - * record data - */ - private byte[] _recdata; - - /** - * Build an instance of FontEntityAtom from on-disk data - */ - protected FontEntityAtom(byte[] source, int start, int len) { - // Get the header - _header = new byte[8]; - System.arraycopy(source,start,_header,0,8); - - // Grab the record data - _recdata = new byte[len-8]; - System.arraycopy(source,start+8,_recdata,0,len-8); - } - - /** - * Create a new instance of FontEntityAtom - */ - public FontEntityAtom() { - _recdata = new byte[68]; - - _header = new byte[8]; - LittleEndian.putShort(_header, 2, (short)getRecordType()); - LittleEndian.putInt(_header, 4, _recdata.length); - } - - @Override - public long getRecordType() { - return RecordTypes.FontEntityAtom.typeID; - } - - /** - * A null-terminated string that specifies the typeface name of the font. - * The length of this string must not exceed 32 characters - * including the null terminator. - * @return font name - */ - public String getFontName(){ - int maxLen = Math.min(_recdata.length,64); - for(int i = 0; i < maxLen; i+=2){ - //loop until find null-terminated end of the font name - if(_recdata[i] == 0 && _recdata[i + 1] == 0) { - return StringUtil.getFromUnicodeLE(_recdata, 0, i/2); - } - } - return null; - } - - /** - * Set the name of the font. - * The length of this string must not exceed 32 characters - * including the null terminator. - * Will be converted to null-terminated if not already - * @param name of the font - */ - public void setFontName(String name){ - // Add a null termination if required - if(! name.endsWith("\u0000")) { - name += '\u0000'; - } - - // Ensure it's not now too long - if(name.length() > 32) { - throw new HSLFException("The length of the font name, including null termination, must not exceed 32 characters"); - } - - // Everything's happy, so save the name - byte[] bytes = StringUtil.getToUnicodeLE(name); - System.arraycopy(bytes, 0, _recdata, 0, bytes.length); - } - - public void setFontIndex(int idx){ - LittleEndian.putShort(_header, 0, (short)idx); - } - - public int getFontIndex(){ - return LittleEndian.getShort(_header, 0) >> 4; - } - - /** - * set the character set - * - * @param charset - characterset - */ - public void setCharSet(int charset){ - _recdata[64] = (byte)charset; - } - - /** - * get the character set - * - * @return charset - characterset - */ - public int getCharSet(){ - return _recdata[64]; - } - - /** - * set the font flags - * Bit 1: If set, font is subsetted - * - * @param flags - the font flags - */ - public void setFontFlags(int flags){ - _recdata[65] = (byte)flags; - } - - /** - * get the character set - * Bit 1: If set, font is subsetted - * - * @return the font flags - */ - public int getFontFlags(){ - return _recdata[65]; - } - - /** - * set the font type - *

    - * Bit 1: Raster Font - * Bit 2: Device Font - * Bit 3: TrueType Font - *

    - * - * @param type - the font type - */ - public void setFontType(int type){ - _recdata[66] = (byte)type; - } - - /** - * get the font type - *

    - * Bit 1: Raster Font - * Bit 2: Device Font - * Bit 3: TrueType Font - *

    - * - * @return the font type - */ - public int getFontType(){ - return _recdata[66]; - } - - /** - * set lfPitchAndFamily - * - * - * @param val - Corresponds to the lfPitchAndFamily field of the Win32 API LOGFONT structure - */ - public void setPitchAndFamily(int val){ - _recdata[67] = (byte)val; - } - - /** - * get lfPitchAndFamily - * - * @return corresponds to the lfPitchAndFamily field of the Win32 API LOGFONT structure - */ - public int getPitchAndFamily(){ - return _recdata[67]; - } - - /** - * Write the contents of the record back, so it can be written to disk - */ - @Override - public void writeOut(OutputStream out) throws IOException { - out.write(_header); - out.write(_recdata); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/HSLFEscherClientDataRecord.java b/src/scratchpad/src/org/apache/poi/hslf/record/HSLFEscherClientDataRecord.java deleted file mode 100644 index e2975de78..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/HSLFEscherClientDataRecord.java +++ /dev/null @@ -1,120 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.apache.poi.ddf.EscherClientDataRecord; -import org.apache.poi.ddf.EscherRecordFactory; -import org.apache.poi.ddf.EscherSerializationListener; -import org.apache.poi.hslf.exceptions.HSLFException; -import org.apache.poi.util.LittleEndian; - -/** - * An atom record that specifies whether a shape is a placeholder shape. - * The number, position, and type of placeholder shapes are determined by - * the slide layout as specified in the SlideAtom record. - * - * @since POI 3.14-Beta2 - */ -public class HSLFEscherClientDataRecord extends EscherClientDataRecord { - - private final List _childRecords = new ArrayList(); - - public List getHSLFChildRecords() { - return _childRecords; - } - - public void removeChild(Class childClass) { - Iterator iter = _childRecords.iterator(); - while (iter.hasNext()) { - if (childClass.isInstance(iter.next())) { - iter.remove(); - } - } - } - - public void addChild(Record childRecord) { - _childRecords.add(childRecord); - } - - @Override - public int fillFields(byte[] data, int offset, EscherRecordFactory recordFactory) { - int bytesRemaining = readHeader( data, offset ); - byte remainingData[] = new byte[bytesRemaining]; - System.arraycopy(data, offset+8, remainingData, 0, bytesRemaining); - setRemainingData(remainingData); - return bytesRemaining + 8; - } - - @Override - public int serialize(int offset, byte[] data, EscherSerializationListener listener) { - listener.beforeRecordSerialize( offset, getRecordId(), this ); - - LittleEndian.putShort(data, offset, getOptions()); - LittleEndian.putShort(data, offset+2, getRecordId()); - - byte childBytes[] = getRemainingData(); - - LittleEndian.putInt(data, offset+4, childBytes.length); - System.arraycopy(childBytes, 0, data, offset+8, childBytes.length); - int recordSize = 8+childBytes.length; - listener.afterRecordSerialize( offset+recordSize, getRecordId(), recordSize, this ); - return recordSize; - } - - @Override - public int getRecordSize() { - return 8 + getRemainingData().length; - } - - @Override - public byte[] getRemainingData() { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - try { - for (Record r : _childRecords) { - r.writeOut(bos); - } - } catch (IOException e) { - throw new HSLFException(e); - } - return bos.toByteArray(); - } - - @Override - public void setRemainingData( byte[] remainingData ) { - _childRecords.clear(); - int offset = 0; - while (offset < remainingData.length) { - Record r = Record.buildRecordAtOffset(remainingData, offset); - _childRecords.add(r); - long rlen = LittleEndian.getUInt(remainingData,offset+4); - offset += 8 + rlen; - } - } - - public String getRecordName() { - return "HSLFClientData"; - } - - -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/HSLFEscherRecordFactory.java b/src/scratchpad/src/org/apache/poi/hslf/record/HSLFEscherRecordFactory.java deleted file mode 100644 index 0e23e4930..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/HSLFEscherRecordFactory.java +++ /dev/null @@ -1,67 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import java.lang.reflect.Constructor; -import java.util.Map; - -import org.apache.poi.ddf.*; -import org.apache.poi.util.LittleEndian; - -/** - * Generates escher records when provided the byte array containing those records. - * - * @see EscherRecordFactory - */ -public class HSLFEscherRecordFactory extends DefaultEscherRecordFactory { - private static Class[] escherRecordClasses = { EscherPlaceholder.class, HSLFEscherClientDataRecord.class }; - private static Map> recordsMap = recordsToMap( escherRecordClasses ); - - - /** - * Creates an instance of the escher record factory - */ - public HSLFEscherRecordFactory() { - // no instance initialisation - } - - @Override - public EscherRecord createRecord(byte[] data, int offset) { - short options = LittleEndian.getShort( data, offset ); - short recordId = LittleEndian.getShort( data, offset + 2 ); - // int remainingBytes = LittleEndian.getInt( data, offset + 4 ); - - Constructor recordConstructor = recordsMap.get(Short.valueOf(recordId)); - if (recordConstructor == null) { - return super.createRecord(data, offset); - } - EscherRecord escherRecord = null; - try { - escherRecord = recordConstructor.newInstance(new Object[] {}); - } catch (Exception e) { - return super.createRecord(data, offset); - } - escherRecord.setRecordId(recordId); - escherRecord.setOptions(options); - if (escherRecord instanceof EscherContainerRecord) { - ((EscherContainerRecord)escherRecord).fillFields(data, offset, this); - } - - return escherRecord; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/HeadersFootersAtom.java b/src/scratchpad/src/org/apache/poi/hslf/record/HeadersFootersAtom.java deleted file mode 100644 index b9006051d..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/HeadersFootersAtom.java +++ /dev/null @@ -1,211 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import org.apache.poi.util.LittleEndian; -import java.io.IOException; -import java.io.OutputStream; - -/** - * An atom record that specifies options for displaying headers and footers - * on a presentation slide or notes slide. - * - * @author Yegor Kozlov - */ - -public final class HeadersFootersAtom extends RecordAtom { - - /** - * A bit that specifies whether the date is displayed in the footer. - * @see #getMask() - * @see #setMask(int) - */ - public static final int fHasDate = 1; - - /** - * A bit that specifies whether the current datetime is used for displaying the datetime. - * @see #getMask() - * @see #setMask(int) - */ - public static final int fHasTodayDate = 2; - - /** - * A bit that specifies whether the date specified in UserDateAtom record - * is used for displaying the datetime. - * - * @see #getMask() - * @see #setMask(int) - */ - public static final int fHasUserDate = 4; - - /** - * A bit that specifies whether the slide number is displayed in the footer. - * - * @see #getMask() - * @see #setMask(int) - */ - public static final int fHasSlideNumber = 8; - - /** - * bit that specifies whether the header text is displayed. - * - * @see #getMask() - * @see #setMask(int) - */ - public static final int fHasHeader = 16; - - /** - * bit that specifies whether the footer text is displayed. - * - * @see #getMask() - * @see #setMask(int) - */ - public static final int fHasFooter = 32; - - /** - * record header - */ - private byte[] _header; - - /** - * record data - */ - private byte[] _recdata; - - /** - * Build an instance of HeadersFootersAtom from on-disk data - */ - protected HeadersFootersAtom(byte[] source, int start, int len) { - // Get the header - _header = new byte[8]; - System.arraycopy(source,start,_header,0,8); - - // Grab the record data - _recdata = new byte[len-8]; - System.arraycopy(source,start+8,_recdata,0,len-8); - } - - /** - * Create a new instance of HeadersFootersAtom - */ - public HeadersFootersAtom() { - _recdata = new byte[4]; - - _header = new byte[8]; - LittleEndian.putShort(_header, 2, (short)getRecordType()); - LittleEndian.putInt(_header, 4, _recdata.length); - } - - public long getRecordType() { - return RecordTypes.HeadersFootersAtom.typeID; - } - - /** - * Write the contents of the record back, so it can be written to disk - */ - public void writeOut(OutputStream out) throws IOException { - out.write(_header); - out.write(_recdata); - } - - /** - * A signed integer that specifies the format ID to be used to style the datetime. - *

    - * It MUST be in the range [0, 12].
    - * This value is converted into a string as specified by the index field of the DateTimeMCAtom record. - * It MUST be ignored unless fHasTodayDate is TRUE. - * - * - * @return A signed integer that specifies the format ID to be used to style the datetime. - */ - public int getFormatId(){ - return LittleEndian.getShort(_recdata, 0); - } - - /** - * A signed integer that specifies the format ID to be used to style the datetime. - * - * @param formatId A signed integer that specifies the format ID to be used to style the datetime. - */ - public void setFormatId(int formatId){ - LittleEndian.putUShort(_recdata, 0, formatId); - } - - /** - * A bit mask specifying options for displaying headers and footers - * - *

  • A - {@link #fHasDate} (1 bit): A bit that specifies whether the date is displayed in the footer. - *
  • B - {@link #fHasTodayDate} (1 bit): A bit that specifies whether the current datetime is used for - * displaying the datetime. - *
  • C - {@link #fHasUserDate} (1 bit): A bit that specifies whether the date specified in UserDateAtom record - * is used for displaying the datetime. - *
  • D - {@link #fHasSlideNumber} (1 bit): A bit that specifies whether the slide number is displayed in the footer. - *
  • E - {@link #fHasHeader} (1 bit): A bit that specifies whether the header text specified by HeaderAtom - * record is displayed. - *
  • F - {@link #fHasFooter} (1 bit): A bit that specifies whether the footer text specified by FooterAtom - * record is displayed. - *
  • reserved (10 bits): MUST be zero and MUST be ignored. - * - * @return A bit mask specifying options for displaying headers and footers - */ - public int getMask(){ - return LittleEndian.getShort(_recdata, 2); - } - - /** - * A bit mask specifying options for displaying headers and footers - * - * @param mask A bit mask specifying options for displaying headers and footers - */ - public void setMask(int mask){ - LittleEndian.putUShort(_recdata, 2, mask); - } - - /** - * @param bit the bit to check - * @return whether the specified flag is set - */ - public boolean getFlag(int bit){ - return (getMask() & bit) != 0; - } - - /** - * @param bit the bit to set - * @param value whether the specified bit is set - */ - public void setFlag(int bit, boolean value){ - int mask = getMask(); - if(value) mask |= bit; - else mask &= ~bit; - setMask(mask); - } - - public String toString(){ - StringBuffer buf = new StringBuffer(); - buf.append("HeadersFootersAtom\n"); - buf.append("\tFormatId: " + getFormatId() + "\n"); - buf.append("\tMask : " + getMask() + "\n"); - buf.append("\t fHasDate : " + getFlag(fHasDate) + "\n"); - buf.append("\t fHasTodayDate : " + getFlag(fHasTodayDate) + "\n"); - buf.append("\t fHasUserDate : " + getFlag(fHasUserDate) + "\n"); - buf.append("\t fHasSlideNumber : " + getFlag(fHasSlideNumber) + "\n"); - buf.append("\t fHasHeader : " + getFlag(fHasHeader) + "\n"); - buf.append("\t fHasFooter : " + getFlag(fHasFooter) + "\n"); - return buf.toString(); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/HeadersFootersContainer.java b/src/scratchpad/src/org/apache/poi/hslf/record/HeadersFootersContainer.java deleted file mode 100644 index 9f2a0eecd..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/HeadersFootersContainer.java +++ /dev/null @@ -1,211 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.POILogger; - -import java.io.OutputStream; -import java.io.IOException; - -/** - * A container record that specifies information about the footers on a presentation slide. - *

    - * It contains:
    - *

  • 1. {@link HeadersFootersAtom} - *
  • 2. {@link CString }, Instance UserDate (0), optional: Stores the user's date. - * This is the date that the user wants in the footers, instead of today's date. - *
  • 3. {@link CString }, Instance Header (1), optional: Stores the Header's contents. - *
  • 4. {@link CString }, Instance Footer (2), optional: Stores the Footer's contents. - *

    - * - * @author Yegor Kozlov - */ -public final class HeadersFootersContainer extends RecordContainer { - - /** - * "instance" field in the record header indicating that this HeadersFootersContaine - * is applied for slides - */ - public static final short SlideHeadersFootersContainer = 0x3F; - /** - * "instance" field in the record header indicating that this HeadersFootersContaine - * is applied for notes and handouts - */ - public static final short NotesHeadersFootersContainer = 0x4F; - - public static final int USERDATEATOM = 0; - public static final int HEADERATOM = 1; - public static final int FOOTERATOM = 2; - - private byte[] _header; - private HeadersFootersAtom hdAtom; - private CString csDate, csHeader, csFooter; - - protected HeadersFootersContainer(byte[] source, int start, int len) { - // Grab the header - _header = new byte[8]; - System.arraycopy(source,start,_header,0,8); - - _children = Record.findChildRecords(source,start+8,len-8); - for(int i=0; i < _children.length; i++){ - if(_children[i] instanceof HeadersFootersAtom) hdAtom = (HeadersFootersAtom)_children[i]; - else if(_children[i] instanceof CString) { - CString cs = (CString)_children[i]; - int opts = cs.getOptions() >> 4; - switch(opts){ - case USERDATEATOM: csDate = cs; break; - case HEADERATOM: csHeader = cs; break; - case FOOTERATOM: csFooter = cs; break; - default: - logger.log(POILogger.WARN, "Unexpected CString.Options in HeadersFootersContainer: " + opts); - break; - } - } else { - logger.log(POILogger.WARN, "Unexpected record in HeadersFootersContainer: " + _children[i]); - } - } - - } - - public HeadersFootersContainer(short options) { - _header = new byte[8]; - LittleEndian.putShort(_header, 0, options); - LittleEndian.putShort(_header, 2, (short)getRecordType()); - - hdAtom = new HeadersFootersAtom(); - _children = new Record[]{ - hdAtom - }; - csDate = csHeader = csFooter = null; - - } - - /** - * Return the type, which is {@link RecordTypes#HeadersFooters} - */ - public long getRecordType() { - return RecordTypes.HeadersFooters.typeID; - } - - /** - * Must be either {@link #SlideHeadersFootersContainer} or {@link #NotesHeadersFootersContainer} - * - * @return "instance" field in the record header - */ - public int getOptions(){ - return LittleEndian.getShort(_header, 0); - } - - /** - * Write the contents of the record back, so it can be written to disk - */ - public void writeOut(OutputStream out) throws IOException { - writeOut(_header[0],_header[1],getRecordType(),_children,out); - } - - /** - * HeadersFootersAtom stores the basic information of the header and footer structure. - * - * @return HeadersFootersAtom - */ - public HeadersFootersAtom getHeadersFootersAtom(){ - return hdAtom; - } - - /** - * A {@link CString} record that stores the user's date. - *

    This is the date that the user wants in the footers, instead of today's date.

    - * - * @return A {@link CString} record that stores the user's date or null - */ - public CString getUserDateAtom(){ - return csDate; - } - - /** - * A {@link CString} record that stores the Header's contents. - * - * @return A {@link CString} record that stores the Header's contents or null - */ - public CString getHeaderAtom(){ - return csHeader; - } - - /** - * A {@link CString} record that stores the Footers's contents. - * - * @return A {@link CString} record that stores the Footers's contents or null - */ - public CString getFooterAtom(){ - return csFooter; - } - - /** - * Insert a {@link CString} record that stores the user's date. - * - * @return the created {@link CString} record that stores the user's date. - */ - public CString addUserDateAtom(){ - if(csDate != null) return csDate; - - csDate = new CString(); - csDate.setOptions(USERDATEATOM << 4); - - addChildAfter(csDate, hdAtom); - - return csDate; - } - - /** - * Insert a {@link CString} record that stores the user's date. - * - * @return the created {@link CString} record that stores the user's date. - */ - public CString addHeaderAtom(){ - if(csHeader != null) return csHeader; - - csHeader = new CString(); - csHeader.setOptions(HEADERATOM << 4); - - Record r = hdAtom; - if(csDate != null) r = hdAtom; - addChildAfter(csHeader, r); - - return csHeader; - } - - /** - * Insert a {@link CString} record that stores the user's date. - * - * @return the created {@link CString} record that stores the user's date. - */ - public CString addFooterAtom(){ - if(csFooter != null) return csFooter; - - csFooter = new CString(); - csFooter.setOptions(FOOTERATOM << 4); - - Record r = hdAtom; - if(csHeader != null) r = csHeader; - else if(csDate != null) r = csDate; - addChildAfter(csFooter, r); - - return csFooter; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/InteractiveInfo.java b/src/scratchpad/src/org/apache/poi/hslf/record/InteractiveInfo.java deleted file mode 100644 index 8ca722d85..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/InteractiveInfo.java +++ /dev/null @@ -1,99 +0,0 @@ -/* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.apache.poi.hslf.record; - -import java.io.IOException; -import java.io.OutputStream; - -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.POILogger; - -/** - * This class represents the metadata of a link in a slide/notes/etc. - * It normally just holds a InteractiveInfoAtom, with the metadata - * in it. - * @author Nick Burch - */ -public class InteractiveInfo extends RecordContainer { - private byte[] _header; - private static long _type = 4082; - - // Links to our more interesting children - private InteractiveInfoAtom infoAtom; - - /** - * Returns the InteractiveInfoAtom of this InteractiveInfo - */ - public InteractiveInfoAtom getInteractiveInfoAtom() { return infoAtom; } - - /** - * Set things up, and find our more interesting children - */ - protected InteractiveInfo(byte[] source, int start, int len) { - // Grab the header - _header = new byte[8]; - System.arraycopy(source,start,_header,0,8); - - // Find our children - _children = Record.findChildRecords(source,start+8,len-8); - findInterestingChildren(); - } - - /** - * Go through our child records, picking out the ones that are - * interesting, and saving those for use by the easy helper - * methods. - */ - private void findInterestingChildren() { - // First child should be the InteractiveInfoAtom - if (_children == null || _children.length == 0 || !(_children[0] instanceof InteractiveInfoAtom)) { - logger.log(POILogger.WARN, "First child record wasn't a InteractiveInfoAtom - leaving this atom in an invalid state..."); - return; - } - - infoAtom = (InteractiveInfoAtom)_children[0]; - } - - /** - * Create a new InteractiveInfo, with blank fields - */ - public InteractiveInfo() { - _header = new byte[8]; - _children = new Record[1]; - - // Setup our header block - _header[0] = 0x0f; // We are a container record - LittleEndian.putShort(_header, 2, (short)_type); - - // Setup our child records - infoAtom = new InteractiveInfoAtom(); - _children[0] = infoAtom; - } - - /** - * We are of type 4802 - */ - public long getRecordType() { return _type; } - - /** - * Write the contents of the record back, so it can be written - * to disk - */ - public void writeOut(OutputStream out) throws IOException { - writeOut(_header[0],_header[1],_type,_children,out); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/InteractiveInfoAtom.java b/src/scratchpad/src/org/apache/poi/hslf/record/InteractiveInfoAtom.java deleted file mode 100644 index 6dd8fccf6..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/InteractiveInfoAtom.java +++ /dev/null @@ -1,278 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import java.io.IOException; -import java.io.OutputStream; - -import org.apache.poi.util.LittleEndian; - -/** - * Tne atom that holds metadata on Links in the document. - * (The actual link is held Document.ExObjList.ExHyperlink) - * - * @author Nick Burch - * @author Yegor Kozlov - */ -public class InteractiveInfoAtom extends RecordAtom { - - /** - * Action Table - */ - public static final byte ACTION_NONE = 0; - public static final byte ACTION_MACRO = 1; - public static final byte ACTION_RUNPROGRAM = 2; - public static final byte ACTION_JUMP = 3; - public static final byte ACTION_HYPERLINK = 4; - public static final byte ACTION_OLE = 5; - public static final byte ACTION_MEDIA = 6; - public static final byte ACTION_CUSTOMSHOW = 7; - - /** - * Jump Table - */ - public static final byte JUMP_NONE = 0; - public static final byte JUMP_NEXTSLIDE = 1; - public static final byte JUMP_PREVIOUSSLIDE = 2; - public static final byte JUMP_FIRSTSLIDE = 3; - public static final byte JUMP_LASTSLIDE = 4; - public static final byte JUMP_LASTSLIDEVIEWED = 5; - public static final byte JUMP_ENDSHOW = 6; - - /** - * Types of hyperlinks - */ - public static final byte LINK_NextSlide = 0x00; - public static final byte LINK_PreviousSlide = 0x01; - public static final byte LINK_FirstSlide = 0x02; - public static final byte LINK_LastSlide = 0x03; - public static final byte LINK_CustomShow = 0x06; - public static final byte LINK_SlideNumber = 0x07; - public static final byte LINK_Url = 0x08; - public static final byte LINK_OtherPresentation = 0x09; - public static final byte LINK_OtherFile = 0x0A; - public static final byte LINK_NULL = (byte)0xFF; - - /** - * Record header. - */ - private byte[] _header; - - /** - * Record data. - */ - private byte[] _data; - - /** - * Constructs a brand new link related atom record. - */ - protected InteractiveInfoAtom() { - _header = new byte[8]; - _data = new byte[16]; - - LittleEndian.putShort(_header, 2, (short)getRecordType()); - LittleEndian.putInt(_header, 4, _data.length); - - // It is fine for the other values to be zero - } - - /** - * Constructs the link related atom record from its - * source data. - * - * @param source the source data as a byte array. - * @param start the start offset into the byte array. - * @param len the length of the slice in the byte array. - */ - protected InteractiveInfoAtom(byte[] source, int start, int len) { - // Get the header. - _header = new byte[8]; - System.arraycopy(source,start,_header,0,8); - - // Get the record data. - _data = new byte[len-8]; - System.arraycopy(source,start+8,_data,0,len-8); - - // Must be at least 16 bytes long - if(_data.length < 16) { - throw new IllegalArgumentException("The length of the data for a InteractiveInfoAtom must be at least 16 bytes, but was only " + _data.length); - } - - // First 4 bytes - no idea, normally 0 - // Second 4 bytes - the id of the link (from 1 onwards) - // Third 4 bytes - no idea, normally 4 - // Fourth 4 bytes - no idea, normally 8 - } - - /** - * Gets the link number. You will normally look the - * ExHyperlink with this number to get the details. - * @return the link number - */ - public int getHyperlinkID() { - return LittleEndian.getInt(_data,4); - } - - /** - * Sets the persistent unique identifier of the link - * - * @param number the persistent unique identifier of the link - */ - public void setHyperlinkID(int number) { - LittleEndian.putInt(_data,4,number); - } - - /** - * a reference to a sound in the sound collection. - */ - public int getSoundRef() { - return LittleEndian.getInt(_data,0); - } - /** - * a reference to a sound in the sound collection. - * - * @param val a reference to a sound in the sound collection - */ - public void setSoundRef(int val) { - LittleEndian.putInt(_data, 0, val); - } - - /** - * Hyperlink Action. - *

    - * see ACTION_* constants for the list of actions - *

    - * - * @return hyperlink action. - */ - public byte getAction() { - return _data[8]; - } - - /** - * Hyperlink Action - *

    - * see ACTION_* constants for the list of actions - *

    - * - * @param val hyperlink action. - */ - public void setAction(byte val) { - _data[8] = val; - } - - /** - * Only valid when action == OLEAction. OLE verb to use, 0 = first verb, 1 = second verb, etc. - */ - public byte getOleVerb() { - return _data[9]; - } - - /** - * Only valid when action == OLEAction. OLE verb to use, 0 = first verb, 1 = second verb, etc. - */ - public void setOleVerb(byte val) { - _data[9] = val; - } - - /** - * Jump - *

    - * see JUMP_* constants for the list of actions - *

    - * - * @return jump - */ - public byte getJump() { - return _data[10]; - } - - /** - * Jump - *

    - * see JUMP_* constants for the list of actions - *

    - * - * @param val jump - */ - public void setJump(byte val) { - _data[10] = val; - } - - /** - * Flags - *

    - *

  • Bit 1: Animated. If 1, then button is animated - *
  • Bit 2: Stop sound. If 1, then stop current sound when button is pressed. - *
  • Bit 3: CustomShowReturn. If 1, and this is a jump to custom show, - * then return to this slide after custom show. - *

    - */ - public byte getFlags() { - return _data[11]; - } - - /** - * Flags - *

    - *

  • Bit 1: Animated. If 1, then button is animated - *
  • Bit 2: Stop sound. If 1, then stop current sound when button is pressed. - *
  • Bit 3: CustomShowReturn. If 1, and this is a jump to custom show, - * then return to this slide after custom show. - *

    - */ - public void setFlags(byte val) { - _data[11] = val; - } - - /** - * hyperlink type - * - * @return hyperlink type - */ - public byte getHyperlinkType() { - return _data[12]; - } - - /** - * hyperlink type - * - * @param val hyperlink type - */ - public void setHyperlinkType(byte val) { - _data[12] = val; - } - - /** - * Gets the record type. - * @return the record type. - */ - public long getRecordType() { return RecordTypes.InteractiveInfoAtom.typeID; } - - /** - * Write the contents of the record back, so it can be written - * to disk - * - * @param out the output stream to write to. - * @throws IOException if an error occurs. - */ - public void writeOut(OutputStream out) throws IOException { - out.write(_header); - out.write(_data); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/MainMaster.java b/src/scratchpad/src/org/apache/poi/hslf/record/MainMaster.java deleted file mode 100644 index eb1dade78..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/MainMaster.java +++ /dev/null @@ -1,105 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import java.io.IOException; -import java.io.OutputStream; -import java.util.ArrayList; - -/** - * Master slide - * - * @author Yegor Kozlov - */ -public final class MainMaster extends SheetContainer { - private byte[] _header; - private static long _type = 1016; - - // Links to our more interesting children - private SlideAtom slideAtom; - private PPDrawing ppDrawing; - private TxMasterStyleAtom[] txmasters; - private ColorSchemeAtom[] clrscheme; - private ColorSchemeAtom _colorScheme; - - /** - * Returns the SlideAtom of this Slide - */ - public SlideAtom getSlideAtom() { return slideAtom; } - - /** - * Returns the PPDrawing of this Slide, which has all the - * interesting data in it - */ - public PPDrawing getPPDrawing() { return ppDrawing; } - - public TxMasterStyleAtom[] getTxMasterStyleAtoms() { return txmasters; } - - public ColorSchemeAtom[] getColorSchemeAtoms() { return clrscheme; } - - /** - * Set things up, and find our more interesting children - */ - protected MainMaster(byte[] source, int start, int len) { - // Grab the header - _header = new byte[8]; - System.arraycopy(source,start,_header,0,8); - - // Find our children - _children = Record.findChildRecords(source,start+8,len-8); - - ArrayList tx = new ArrayList(); - ArrayList clr = new ArrayList(); - // Find the interesting ones in there - for(int i=0; i<_children.length; i++) { - if(_children[i] instanceof SlideAtom) { - slideAtom = (SlideAtom)_children[i]; - } else if(_children[i] instanceof PPDrawing) { - ppDrawing = (PPDrawing)_children[i]; - } else if(_children[i] instanceof TxMasterStyleAtom) { - tx.add( (TxMasterStyleAtom)_children[i] ); - } else if(_children[i] instanceof ColorSchemeAtom) { - clr.add( (ColorSchemeAtom)_children[i] ); - } - - if(ppDrawing != null && _children[i] instanceof ColorSchemeAtom) { - _colorScheme = (ColorSchemeAtom)_children[i]; - } - - } - txmasters = tx.toArray(new TxMasterStyleAtom[tx.size()]); - clrscheme = clr.toArray(new ColorSchemeAtom[clr.size()]); - } - - /** - * We are of type 1016 - */ - public long getRecordType() { return _type; } - - /** - * Write the contents of the record back, so it can be written - * to disk - */ - public void writeOut(OutputStream out) throws IOException { - writeOut(_header[0],_header[1],_type,_children,out); - } - - public ColorSchemeAtom getColorScheme(){ - return _colorScheme; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/MasterTextPropAtom.java b/src/scratchpad/src/org/apache/poi/hslf/record/MasterTextPropAtom.java deleted file mode 100644 index d38b390af..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/MasterTextPropAtom.java +++ /dev/null @@ -1,151 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import java.io.IOException; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import org.apache.poi.hslf.model.textproperties.IndentProp; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.POILogger; - -/** - * Specifies the Indent Level for the text - */ -public final class MasterTextPropAtom extends RecordAtom { - /** - * Record header. - */ - private byte[] _header; - - /** - * Record data. - */ - private byte[] _data; - - // indent details - private List indents; - - /** - * Constructs a new empty master text prop atom. - */ - public MasterTextPropAtom() { - _header = new byte[8]; - _data = new byte[0]; - - LittleEndian.putShort(_header, 2, (short)getRecordType()); - LittleEndian.putInt(_header, 4, _data.length); - - indents = new ArrayList(); - } - - /** - * Constructs the ruler atom record from its - * source data. - * - * @param source the source data as a byte array. - * @param start the start offset into the byte array. - * @param len the length of the slice in the byte array. - */ - protected MasterTextPropAtom(byte[] source, int start, int len) { - // Get the header. - _header = new byte[8]; - System.arraycopy(source,start,_header,0,8); - - // Get the record data. - _data = new byte[len-8]; - System.arraycopy(source,start+8,_data,0,len-8); - - try { - read(); - } catch (Exception e){ - logger.log(POILogger.ERROR, "Failed to parse MasterTextPropAtom", e); - } - } - - /** - * Gets the record type. - * - * @return the record type. - */ - public long getRecordType() { - return RecordTypes.MasterTextPropAtom.typeID; - } - - /** - * Write the contents of the record back, so it can be written - * to disk. - * - * @param out the output stream to write to. - * @throws java.io.IOException if an error occurs. - */ - public void writeOut(OutputStream out) throws IOException { - write(); - out.write(_header); - out.write(_data); - } - - /** - * Write the internal variables to the record bytes - */ - private void write() { - int pos = 0; - _data = new byte[indents.size()*6]; - for (IndentProp prop : indents) { - LittleEndian.putInt(_data, pos, prop.getCharactersCovered()); - LittleEndian.putShort(_data, pos+4, (short)prop.getIndentLevel()); - pos += 6; - } - } - - /** - * Read the record bytes and initialize the internal variables - */ - private void read() { - int pos = 0; - indents = new ArrayList(_data.length/6); - - while (pos <= _data.length - 6) { - int count = LittleEndian.getInt(_data, pos); - short indent = LittleEndian.getShort(_data, pos+4); - indents.add(new IndentProp(count, indent)); - pos += 6; - } - } - - /** - * Returns the indent that applies at the given text offset - */ - public int getIndentAt(int offset) { - int charsUntil = 0; - for (IndentProp prop : indents) { - charsUntil += prop.getCharactersCovered(); - if (offset < charsUntil) { - return prop.getIndentLevel(); - } - } - return -1; - } - - public List getIndents() { - return Collections.unmodifiableList(indents); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/Notes.java b/src/scratchpad/src/org/apache/poi/hslf/record/Notes.java deleted file mode 100644 index 80ee6039f..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/Notes.java +++ /dev/null @@ -1,94 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import java.io.IOException; -import java.io.OutputStream; - -/** - * Master container for Notes. There is one of these for every page of - * notes, and they have certain specific children - * - * @author Nick Burch - */ - -public final class Notes extends SheetContainer -{ - private byte[] _header; - private static long _type = 1008l; - - // Links to our more interesting children - private NotesAtom notesAtom; - private PPDrawing ppDrawing; - private ColorSchemeAtom _colorScheme; - - /** - * Returns the NotesAtom of this Notes - */ - public NotesAtom getNotesAtom() { return notesAtom; } - /** - * Returns the PPDrawing of this Notes, which has all the - * interesting data in it - */ - public PPDrawing getPPDrawing() { return ppDrawing; } - - - /** - * Set things up, and find our more interesting children - */ - protected Notes(byte[] source, int start, int len) { - // Grab the header - _header = new byte[8]; - System.arraycopy(source,start,_header,0,8); - - // Find our children - _children = Record.findChildRecords(source,start+8,len-8); - - // Find the interesting ones in there - for(int i=0; i<_children.length; i++) { - if(_children[i] instanceof NotesAtom) { - notesAtom = (NotesAtom)_children[i]; - //System.out.println("Found notes for sheet " + notesAtom.getSlideID()); - } - if(_children[i] instanceof PPDrawing) { - ppDrawing = (PPDrawing)_children[i]; - } - if(ppDrawing != null && _children[i] instanceof ColorSchemeAtom) { - _colorScheme = (ColorSchemeAtom)_children[i]; - } - } - } - - - /** - * We are of type 1008 - */ - public long getRecordType() { return _type; } - - /** - * Write the contents of the record back, so it can be written - * to disk - */ - public void writeOut(OutputStream out) throws IOException { - writeOut(_header[0],_header[1],_type,_children,out); - } - - public ColorSchemeAtom getColorScheme(){ - return _colorScheme; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/NotesAtom.java b/src/scratchpad/src/org/apache/poi/hslf/record/NotesAtom.java deleted file mode 100644 index 7aace8063..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/NotesAtom.java +++ /dev/null @@ -1,119 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import org.apache.poi.util.LittleEndian; -import java.io.IOException; -import java.io.OutputStream; - -/** - * A Notes Atom (type 1009). Holds information on the parent Notes, such - * as what slide it is tied to - * - * @author Nick Burch - */ - -public final class NotesAtom extends RecordAtom -{ - private byte[] _header; - private static long _type = 1009l; - - private int slideID; - private boolean followMasterObjects; - private boolean followMasterScheme; - private boolean followMasterBackground; - private byte[] reserved; - - - public int getSlideID() { return slideID; } - public void setSlideID(int id) { slideID = id; } - - public boolean getFollowMasterObjects() { return followMasterObjects; } - public boolean getFollowMasterScheme() { return followMasterScheme; } - public boolean getFollowMasterBackground() { return followMasterBackground; } - public void setFollowMasterObjects(boolean flag) { followMasterObjects = flag; } - public void setFollowMasterScheme(boolean flag) { followMasterScheme = flag; } - public void setFollowMasterBackground(boolean flag) { followMasterBackground = flag; } - - - /* *************** record code follows ********************** */ - - /** - * For the Notes Atom - */ - protected NotesAtom(byte[] source, int start, int len) { - // Sanity Checking - if(len < 8) { len = 8; } - - // Get the header - _header = new byte[8]; - System.arraycopy(source,start,_header,0,8); - - // Get the slide ID - slideID = LittleEndian.getInt(source,start+8); - - // Grok the flags, stored as bits - int flags = LittleEndian.getUShort(source,start+12); - if((flags&4) == 4) { - followMasterBackground = true; - } else { - followMasterBackground = false; - } - if((flags&2) == 2) { - followMasterScheme = true; - } else { - followMasterScheme = false; - } - if((flags&1) == 1) { - followMasterObjects = true; - } else { - followMasterObjects = false; - } - - // There might be 2 more bytes, which are a reserved field - reserved = new byte[len-14]; - System.arraycopy(source,start+14,reserved,0,reserved.length); - } - - /** - * We are of type 1009 - */ - public long getRecordType() { return _type; } - - /** - * Write the contents of the record back, so it can be written - * to disk - */ - public void writeOut(OutputStream out) throws IOException { - // Header - out.write(_header); - - // Slide ID - writeLittleEndian(slideID,out); - - // Flags - short flags = 0; - if(followMasterObjects) { flags += 1; } - if(followMasterScheme) { flags += 2; } - if(followMasterBackground) { flags += 4; } - writeLittleEndian(flags,out); - - // Reserved fields - out.write(reserved); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/OEPlaceholderAtom.java b/src/scratchpad/src/org/apache/poi/hslf/record/OEPlaceholderAtom.java deleted file mode 100644 index 3bdea4e4b..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/OEPlaceholderAtom.java +++ /dev/null @@ -1,179 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import java.io.IOException; -import java.io.OutputStream; - -import org.apache.poi.sl.usermodel.Placeholder; -import org.apache.poi.util.LittleEndian; - -/** - * OEPlaceholderAtom (3011).

    - * - * An atom record that specifies whether a shape is a placeholder shape. - * - * @see Placeholder - */ - -public final class OEPlaceholderAtom extends RecordAtom{ - - /** - * The full size of the master body text placeholder shape. - */ - public static final int PLACEHOLDER_FULLSIZE = 0; - - /** - * Half of the size of the master body text placeholder shape. - */ - public static final int PLACEHOLDER_HALFSIZE = 1; - - /** - * A quarter of the size of the master body text placeholder shape. - */ - public static final int PLACEHOLDER_QUARTSIZE = 2; - - private byte[] _header; - - private int placementId; - private int placeholderId; - private int placeholderSize; - private short unusedShort = 0; - - - /** - * Create a new instance of {@code OEPlaceholderAtom} - */ - public OEPlaceholderAtom(){ - _header = new byte[8]; - LittleEndian.putUShort(_header, 0, 0); - LittleEndian.putUShort(_header, 2, (int)getRecordType()); - LittleEndian.putInt(_header, 4, 8); - - placementId = 0; - placeholderId = 0; - placeholderSize = 0; - } - - /** - * Build an instance of {@code OEPlaceholderAtom} from on-disk data - */ - protected OEPlaceholderAtom(byte[] source, int start, int len) { - _header = new byte[8]; - int offset = start; - System.arraycopy(source,start,_header,0,8); - offset += _header.length; - - placementId = LittleEndian.getInt(source, offset); offset += 4; - placeholderId = LittleEndian.getUByte(source, offset); offset++; - placeholderSize = LittleEndian.getUByte(source, offset); offset++; - unusedShort = LittleEndian.getShort(source, offset); - } - - /** - * @return type of this record {@link RecordTypes#OEPlaceholderAtom}. - */ - @Override - public long getRecordType() { return RecordTypes.OEPlaceholderAtom.typeID; } - - /** - * Returns the placement Id.

    - * - * The placement Id is a number assigned to the placeholder. It goes from -1 to the number of placeholders. - * It SHOULD be unique among all PlacholderAtom records contained in the corresponding slide. - * The value 0xFFFFFFFF specifies that the corresponding shape is not a placeholder shape. - * - * @return the placement Id. - */ - public int getPlacementId(){ - return placementId; - } - - /** - * Sets the placement Id.

    - * - * The placement Id is a number assigned to the placeholder. It goes from -1 to the number of placeholders. - * It SHOULD be unique among all PlacholderAtom records contained in the corresponding slide. - * The value 0xFFFFFFFF specifies that the corresponding shape is not a placeholder shape. - * - * @param id the placement Id. - */ - public void setPlacementId(int id){ - placementId = id; - } - - /** - * Returns the placeholder Id.

    - * - * placeholder Id specifies the type of the placeholder shape. - * The value MUST be one of the static constants defined in this class - * - * @return the placeholder Id. - */ - public int getPlaceholderId(){ - return placeholderId; - } - - /** - * Sets the placeholder Id.

    - * - * placeholder Id specifies the type of the placeholder shape. - * The value MUST be one of the static constants defined in this class - * - * @param id the placeholder Id. - */ - public void setPlaceholderId(byte id){ - placeholderId = id; - } - - /** - * Returns the placeholder size. - * Must be one of the PLACEHOLDER_* static constants defined in this class. - * - * @return the placeholder size. - */ - public int getPlaceholderSize(){ - return placeholderSize; - } - - /** - * Sets the placeholder size. - * Must be one of the PLACEHOLDER_* static constants defined in this class. - * - * @param size the placeholder size. - */ - public void setPlaceholderSize(byte size){ - placeholderSize = size; - } - - /** - * Write the contents of the record back, so it can be written to disk - */ - @Override - public void writeOut(OutputStream out) throws IOException { - out.write(_header); - - byte[] recdata = new byte[8]; - LittleEndian.putInt(recdata, 0, placementId); - recdata[4] = (byte)placeholderId; - recdata[5] = (byte)placeholderSize; - LittleEndian.putShort(recdata, 6, unusedShort); - - out.write(recdata); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/OutlineTextRefAtom.java b/src/scratchpad/src/org/apache/poi/hslf/record/OutlineTextRefAtom.java deleted file mode 100644 index e44b360a5..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/OutlineTextRefAtom.java +++ /dev/null @@ -1,109 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import org.apache.poi.util.LittleEndian; - -import java.io.OutputStream; -import java.io.IOException; - -/** - * OEPlaceholderAtom (3998). - *
    - * What MSDN says about OutlineTextRefAtom: - *

    - * Appears in a slide to indicate a text that is already contained in the document, - * in a SlideListWithText containter. Sometimes slide texts are not contained - * within the slide container to be able to delay loading a slide and still display - * the title and body text in outline view. - *

    - * - * @author Yegor Kozlov - */ - -public final class OutlineTextRefAtom extends RecordAtom { - /** - * record header - */ - private byte[] _header; - - /** - * the text's index within the SlideListWithText (0 for title, 1..n for the nth body) - */ - private int _index; - - /** - * Build an instance of OutlineTextRefAtom from on-disk data - */ - protected OutlineTextRefAtom(byte[] source, int start, int len) { - // Get the header - _header = new byte[8]; - System.arraycopy(source,start,_header,0,8); - - // Grab the record data - _index = LittleEndian.getInt(source, start+8); - } - - /** - * Create a new instance of FontEntityAtom - */ - protected OutlineTextRefAtom() { - _index = 0; - - _header = new byte[8]; - LittleEndian.putUShort(_header, 0, 0); - LittleEndian.putUShort(_header, 2, (int)getRecordType()); - LittleEndian.putInt(_header, 4, 4); - } - - public long getRecordType() { - return RecordTypes.OutlineTextRefAtom.typeID; - } - - /** - * Write the contents of the record back, so it can be written to disk - */ - public void writeOut(OutputStream out) throws IOException { - out.write(_header); - - byte[] recdata = new byte[4]; - LittleEndian.putInt(recdata, 0, _index); - out.write(recdata); - } - - /** - * Sets text's index within the SlideListWithText container - * (0 for title, 1..n for the nth body). - * - * @param idx 0-based text's index - */ - public void setTextIndex(int idx){ - _index = idx; - } - - /** - * Return text's index within the SlideListWithText container - * (0 for title, 1..n for the nth body). - * - * @return idx text's index - */ - public int getTextIndex(){ - return _index; - } - -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/PPDrawing.java b/src/scratchpad/src/org/apache/poi/hslf/record/PPDrawing.java deleted file mode 100644 index ba36989bc..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/PPDrawing.java +++ /dev/null @@ -1,429 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import java.io.IOException; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; - -import org.apache.poi.ddf.DefaultEscherRecordFactory; -import org.apache.poi.ddf.EscherBoolProperty; -import org.apache.poi.ddf.EscherContainerRecord; -import org.apache.poi.ddf.EscherDgRecord; -import org.apache.poi.ddf.EscherOptRecord; -import org.apache.poi.ddf.EscherProperties; -import org.apache.poi.ddf.EscherRGBProperty; -import org.apache.poi.ddf.EscherRecord; -import org.apache.poi.ddf.EscherSimpleProperty; -import org.apache.poi.ddf.EscherSpRecord; -import org.apache.poi.ddf.EscherSpgrRecord; -import org.apache.poi.ddf.EscherTextboxRecord; -import org.apache.poi.sl.usermodel.ShapeType; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.POILogger; - -/** - * These are actually wrappers onto Escher drawings. Make use of - * the DDF classes to do useful things with them. - * For now, creates a tree of the Escher records, and then creates any - * PowerPoint (hslf) records found within the EscherTextboxRecord - * (msofbtClientTextbox) records. - * Also provides easy access to the EscherTextboxRecords, so that their - * text may be extracted and used in Sheets - */ - -// For now, pretending to be an atom. Might not always be, but that -// would require a wrapping class -public final class PPDrawing extends RecordAtom { - private byte[] _header; - private long _type; - - private final List childRecords = new ArrayList(); - private EscherTextboxWrapper[] textboxWrappers; - - //cached EscherDgRecord - private EscherDgRecord dg; - - /** - * Get access to the underlying Escher Records - */ - public List getEscherRecords() { return childRecords; } - - /** - * Get access to the atoms inside Textboxes - */ - public EscherTextboxWrapper[] getTextboxWrappers() { return textboxWrappers; } - - - /* ******************** record stuff follows ********************** */ - - /** - * Creates a new, empty, PPDrawing (typically for use with a new Slide - * or Notes) - */ - public PPDrawing() { - _header = new byte[8]; - LittleEndian.putUShort(_header, 0, 15); - LittleEndian.putUShort(_header, 2, RecordTypes.PPDrawing.typeID); - LittleEndian.putInt(_header, 4, 0); - - textboxWrappers = new EscherTextboxWrapper[]{}; - create(); - } - - /** - * Sets everything up, groks the escher etc - */ - protected PPDrawing(byte[] source, int start, int len) { - // Get the header - _header = new byte[8]; - System.arraycopy(source,start,_header,0,8); - - // Get the type - _type = LittleEndian.getUShort(_header,2); - - // Get the contents for now - final byte[] contents = new byte[len]; - System.arraycopy(source,start,contents,0,len); - - // Build up a tree of Escher records contained within - final DefaultEscherRecordFactory erf = new HSLFEscherRecordFactory(); - findEscherChildren(erf, contents, 8, len-8, childRecords); - EscherContainerRecord dgContainer = getDgContainer(); - - if (dgContainer != null) { - textboxWrappers = findInDgContainer(dgContainer); - } else { - // Find and EscherTextboxRecord's, and wrap them up - final List textboxes = new ArrayList(); - findEscherTextboxRecord(childRecords, textboxes); - this.textboxWrappers = textboxes.toArray(new EscherTextboxWrapper[textboxes.size()]); - } - } - private EscherTextboxWrapper[] findInDgContainer(final EscherContainerRecord dgContainer) { - final List found = new LinkedList(); - final EscherContainerRecord spgrContainer = findFirstEscherContainerRecordOfType(RecordTypes.EscherSpgrContainer, dgContainer); - final EscherContainerRecord[] spContainers = findAllEscherContainerRecordOfType(RecordTypes.EscherSpContainer, spgrContainer); - for (EscherContainerRecord spContainer : spContainers) { - EscherSpRecord sp = (EscherSpRecord)findFirstEscherRecordOfType(RecordTypes.EscherSp, spContainer); - EscherTextboxRecord clientTextbox = (EscherTextboxRecord)findFirstEscherRecordOfType(RecordTypes.EscherClientTextbox, spContainer); - if (null == clientTextbox) { continue; } - - EscherTextboxWrapper w = new EscherTextboxWrapper(clientTextbox); - StyleTextProp9Atom nineAtom = findInSpContainer(spContainer); - w.setStyleTextProp9Atom(nineAtom); - if (null != sp) { - w.setShapeId(sp.getShapeId()); - } - found.add(w); - } - return found.toArray(new EscherTextboxWrapper[found.size()]); - } - - private StyleTextProp9Atom findInSpContainer(final EscherContainerRecord spContainer) { - HSLFEscherClientDataRecord cldata = spContainer.getChildById(RecordTypes.EscherClientData.typeID); - if (cldata == null) { - return null; - } - DummyPositionSensitiveRecordWithChildren progTags = - getChildRecord(cldata.getHSLFChildRecords(), RecordTypes.ProgTags); - if (progTags == null) { - return null; - } - DummyPositionSensitiveRecordWithChildren progBinaryTag = - (DummyPositionSensitiveRecordWithChildren)progTags.findFirstOfType(RecordTypes.ProgBinaryTag.typeID); - if (progBinaryTag == null) { - return null; - } - int size = progBinaryTag.getChildRecords().length; - if (2 != size) { return null; } - - final Record r0 = progBinaryTag.getChildRecords()[0]; - final Record r1 = progBinaryTag.getChildRecords()[1]; - - if (!(r0 instanceof CString)) { return null; } - if (!("___PPT9".equals(((CString) r0).getText()))) { return null; } - if (!(r1 instanceof BinaryTagDataBlob )) { return null; } - final BinaryTagDataBlob blob = (BinaryTagDataBlob) r1; - if (1 != blob.getChildRecords().length) { return null; } - return (StyleTextProp9Atom) blob.findFirstOfType(RecordTypes.StyleTextProp9Atom.typeID); - } - - /** - * Tree walking way of finding Escher Child Records - */ - private void findEscherChildren(DefaultEscherRecordFactory erf, byte[] source, int startPos, int lenToGo, List found) { - - int escherBytes = LittleEndian.getInt( source, startPos + 4 ) + 8; - - // Find the record - EscherRecord r = erf.createRecord(source,startPos); - // Fill it in - r.fillFields( source, startPos, erf ); - // Save it - found.add(r); - - // Wind on - int size = r.getRecordSize(); - if(size < 8) { - logger.log(POILogger.WARN, "Hit short DDF record at " + startPos + " - " + size); - } - - /** - * Sanity check. Always advance the cursor by the correct value. - * - * getRecordSize() must return exactly the same number of bytes that was written in fillFields. - * Sometimes it is not so, see an example in bug #44770. Most likely reason is that one of ddf records calculates wrong size. - */ - if(size != escherBytes){ - logger.log(POILogger.WARN, "Record length=" + escherBytes + " but getRecordSize() returned " + r.getRecordSize() + "; record: " + r.getClass()); - size = escherBytes; - } - startPos += size; - lenToGo -= size; - if(lenToGo >= 8) { - findEscherChildren(erf, source, startPos, lenToGo, found); - } - } - - /** - * Look for EscherTextboxRecords - */ - private void findEscherTextboxRecord(List toSearch, List found) { - EscherSpRecord sp = null; - for (EscherRecord r : toSearch) { - if (r instanceof EscherSpRecord) { - sp = (EscherSpRecord)r; - } else if (r instanceof EscherTextboxRecord) { - EscherTextboxRecord tbr = (EscherTextboxRecord)r; - EscherTextboxWrapper w = new EscherTextboxWrapper(tbr); - if (sp != null) { - w.setShapeId(sp.getShapeId()); - } - found.add(w); - } else if (r.isContainerRecord()) { - // If it has children, walk them - List children = r.getChildRecords(); - findEscherTextboxRecord(children,found); - } - } - } - - /** - * We are type 1036 - */ - public long getRecordType() { return _type; } - - /** - * We're pretending to be an atom, so return null - */ - public Record[] getChildRecords() { return null; } - - /** - * Write the contents of the record back, so it can be written - * to disk - * Walks the escher layer to get the contents - */ - public void writeOut(OutputStream out) throws IOException { - // Ensure the escher layer reflects the text changes - for (EscherTextboxWrapper w : textboxWrappers) { - w.writeOut(null); - } - - // Find the new size of the escher children; - int newSize = 0; - for(EscherRecord er : childRecords) { - newSize += er.getRecordSize(); - } - - // Update the size (header bytes 5-8) - LittleEndian.putInt(_header,4,newSize); - - // Write out our header - out.write(_header); - - // Now grab the children's data - byte[] b = new byte[newSize]; - int done = 0; - for(EscherRecord r : childRecords) { - done += r.serialize( done, b ); - } - - // Finally, write out the children - out.write(b); - } - - /** - * Create the Escher records associated with a new PPDrawing - */ - private void create(){ - EscherContainerRecord dgContainer = new EscherContainerRecord(); - dgContainer.setRecordId( EscherContainerRecord.DG_CONTAINER ); - dgContainer.setOptions((short)15); - - dg = new EscherDgRecord(); - dg.setOptions((short)16); - dg.setNumShapes(1); - dgContainer.addChildRecord(dg); - - EscherContainerRecord spgrContainer = new EscherContainerRecord(); - spgrContainer.setOptions((short)15); - spgrContainer.setRecordId(EscherContainerRecord.SPGR_CONTAINER); - - EscherContainerRecord spContainer = new EscherContainerRecord(); - spContainer.setOptions((short)15); - spContainer.setRecordId(EscherContainerRecord.SP_CONTAINER); - - EscherSpgrRecord spgr = new EscherSpgrRecord(); - spgr.setOptions((short)1); - spContainer.addChildRecord(spgr); - - EscherSpRecord sp = new EscherSpRecord(); - sp.setOptions((short)((ShapeType.NOT_PRIMITIVE.nativeId << 4) + 2)); - sp.setFlags(EscherSpRecord.FLAG_PATRIARCH | EscherSpRecord.FLAG_GROUP); - spContainer.addChildRecord(sp); - spgrContainer.addChildRecord(spContainer); - dgContainer.addChildRecord(spgrContainer); - - spContainer = new EscherContainerRecord(); - spContainer.setOptions((short)15); - spContainer.setRecordId(EscherContainerRecord.SP_CONTAINER); - sp = new EscherSpRecord(); - sp.setOptions((short)((ShapeType.RECT.nativeId << 4) + 2)); - sp.setFlags(EscherSpRecord.FLAG_BACKGROUND | EscherSpRecord.FLAG_HASSHAPETYPE); - spContainer.addChildRecord(sp); - - EscherOptRecord opt = new EscherOptRecord(); - opt.setRecordId(EscherOptRecord.RECORD_ID); - opt.addEscherProperty(new EscherRGBProperty(EscherProperties.FILL__FILLCOLOR, 134217728)); - opt.addEscherProperty(new EscherRGBProperty(EscherProperties.FILL__FILLBACKCOLOR, 134217733)); - opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.FILL__RECTRIGHT, 10064750)); - opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.FILL__RECTBOTTOM, 7778750)); - opt.addEscherProperty(new EscherBoolProperty(EscherProperties.FILL__NOFILLHITTEST, 1179666)); - opt.addEscherProperty(new EscherBoolProperty(EscherProperties.LINESTYLE__NOLINEDRAWDASH, 524288)); - opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.SHAPE__BLACKANDWHITESETTINGS, 9)); - opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.SHAPE__BACKGROUNDSHAPE, 65537)); - spContainer.addChildRecord(opt); - - dgContainer.addChildRecord(spContainer); - - childRecords.add(dgContainer); - } - - /** - * Add a new EscherTextboxWrapper to this PPDrawing. - */ - public void addTextboxWrapper(EscherTextboxWrapper txtbox){ - EscherTextboxWrapper[] tw = new EscherTextboxWrapper[textboxWrappers.length + 1]; - System.arraycopy(textboxWrappers, 0, tw, 0, textboxWrappers.length); - - tw[textboxWrappers.length] = txtbox; - textboxWrappers = tw; - } - - /** - * @return the container record for drawings - * @since POI 3.14-Beta2 - */ - public EscherContainerRecord getDgContainer() { - if (childRecords.isEmpty()) { - return null; - } - EscherRecord r = childRecords.get(0); - if (r instanceof EscherContainerRecord && r.getRecordId() == RecordTypes.EscherDgContainer.typeID) { - return (EscherContainerRecord)r; - } else { - return null; - } - } - - /** - * Return EscherDgRecord which keeps track of the number of shapes and shapeId in this drawing group - * - * @return EscherDgRecord - */ - public EscherDgRecord getEscherDgRecord(){ - if(dg == null){ - for(EscherRecord r : getDgContainer().getChildRecords()){ - if(r instanceof EscherDgRecord){ - dg = (EscherDgRecord)r; - break; - } - } - } - return dg; - } - - protected EscherContainerRecord findFirstEscherContainerRecordOfType(RecordTypes type, EscherContainerRecord parent) { - if (null == parent) { return null; } - final List children = parent.getChildContainers(); - for (EscherContainerRecord child : children) { - if (type.typeID == child.getRecordId()) { - return child; - } - } - return null; - } - protected EscherRecord findFirstEscherRecordOfType(RecordTypes type, EscherContainerRecord parent) { - if (null == parent) { return null; } - final List children = parent.getChildRecords(); - for (EscherRecord child : children) { - if (type.typeID == child.getRecordId()) { - return child; - } - } - return null; - } - protected EscherContainerRecord[] findAllEscherContainerRecordOfType(RecordTypes type, EscherContainerRecord parent) { - if (null == parent) { return new EscherContainerRecord[0]; } - final List children = parent.getChildContainers(); - final List result = new LinkedList(); - for (EscherContainerRecord child : children) { - if (type.typeID == child.getRecordId()) { - result.add(child); - } - } - return result.toArray(new EscherContainerRecord[result.size()]); - } - - public StyleTextProp9Atom[] getNumberedListInfo() { - final List result = new LinkedList(); - EscherContainerRecord dgContainer = getDgContainer(); - final EscherContainerRecord spgrContainer = findFirstEscherContainerRecordOfType(RecordTypes.EscherSpgrContainer, dgContainer); - final EscherContainerRecord[] spContainers = findAllEscherContainerRecordOfType(RecordTypes.EscherSpContainer, spgrContainer); - for (EscherContainerRecord spContainer : spContainers) { - StyleTextProp9Atom prop9 = findInSpContainer(spContainer); - if (prop9 != null) { - result.add(prop9); - } - } - return result.toArray(new StyleTextProp9Atom[result.size()]); - } - - @SuppressWarnings("unchecked") - private static T getChildRecord(List children, RecordTypes type) { - for (Record r : children) { - if (r.getRecordType() == type.typeID) { - return (T)r; - } - } - return null; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/PPDrawingGroup.java b/src/scratchpad/src/org/apache/poi/hslf/record/PPDrawingGroup.java deleted file mode 100644 index d655e5a4f..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/PPDrawingGroup.java +++ /dev/null @@ -1,129 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import org.apache.poi.ddf.*; -import org.apache.poi.util.LittleEndian; - -import java.io.OutputStream; -import java.io.IOException; -import java.io.ByteArrayOutputStream; -import java.util.Iterator; - -/** - * Container records which always exists inside Document. - * It always acts as a holder for escher DGG container - * which may contain which Escher BStore container information - * about pictures containes in the presentation (if any). - * - * @author Yegor Kozlov - */ -public final class PPDrawingGroup extends RecordAtom { - - private byte[] _header; - private EscherContainerRecord dggContainer; - //cached dgg - private EscherDggRecord dgg; - - protected PPDrawingGroup(byte[] source, int start, int len) { - // Get the header - _header = new byte[8]; - System.arraycopy(source,start,_header,0,8); - - // Get the contents for now - byte[] contents = new byte[len]; - System.arraycopy(source,start,contents,0,len); - - DefaultEscherRecordFactory erf = new HSLFEscherRecordFactory(); - EscherRecord child = erf.createRecord(contents, 0); - child.fillFields( contents, 0, erf ); - dggContainer = (EscherContainerRecord)child.getChild(0); - } - - /** - * We are type 1035 - */ - public long getRecordType() { - return RecordTypes.PPDrawingGroup.typeID; - } - - /** - * We're pretending to be an atom, so return null - */ - public Record[] getChildRecords() { - return null; - } - - public void writeOut(OutputStream out) throws IOException { - ByteArrayOutputStream bout = new ByteArrayOutputStream(); - for (EscherRecord r : dggContainer) { - if (r.getRecordId() == EscherContainerRecord.BSTORE_CONTAINER){ - EscherContainerRecord bstore = (EscherContainerRecord)r; - - ByteArrayOutputStream b2 = new ByteArrayOutputStream(); - for (EscherRecord br : bstore) { - byte[] b = new byte[36+8]; - br.serialize(0, b); - b2.write(b); - } - byte[] bstorehead = new byte[8]; - LittleEndian.putShort(bstorehead, 0, bstore.getOptions()); - LittleEndian.putShort(bstorehead, 2, bstore.getRecordId()); - LittleEndian.putInt(bstorehead, 4, b2.size()); - bout.write(bstorehead); - bout.write(b2.toByteArray()); - - } else { - bout.write(r.serialize()); - } - } - int size = bout.size(); - - // Update the size (header bytes 5-8) - LittleEndian.putInt(_header,4,size+8); - - // Write out our header - out.write(_header); - - byte[] dgghead = new byte[8]; - LittleEndian.putShort(dgghead, 0, dggContainer.getOptions()); - LittleEndian.putShort(dgghead, 2, dggContainer.getRecordId()); - LittleEndian.putInt(dgghead, 4, size); - out.write(dgghead); - - // Finally, write out the children - out.write(bout.toByteArray()); - - } - - public EscherContainerRecord getDggContainer(){ - return dggContainer; - } - - public EscherDggRecord getEscherDggRecord(){ - if(dgg == null){ - for(EscherRecord r : dggContainer){ - if(r instanceof EscherDggRecord){ - dgg = (EscherDggRecord)r; - break; - } - } - } - return dgg; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/ParentAwareRecord.java b/src/scratchpad/src/org/apache/poi/hslf/record/ParentAwareRecord.java deleted file mode 100644 index c71699f35..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/ParentAwareRecord.java +++ /dev/null @@ -1,29 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -/** - * Interface to define how a record can indicate it cares about what its - * parent is, and how it wants to be told which record is its parent. - * - * @author Nick Burch (nick at torchbox dot com) - */ -public interface ParentAwareRecord { - public RecordContainer getParentRecord(); - public void setParentRecord(RecordContainer parentRecord); -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/PersistPtrHolder.java b/src/scratchpad/src/org/apache/poi/hslf/record/PersistPtrHolder.java deleted file mode 100644 index 8a1c48269..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/PersistPtrHolder.java +++ /dev/null @@ -1,246 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; -import java.util.TreeMap; - -import org.apache.poi.hslf.exceptions.CorruptPowerPointFileException; -import org.apache.poi.hslf.exceptions.HSLFException; -import org.apache.poi.util.BitField; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.POILogger; - -/** - * General holder for PersistPtrFullBlock and PersistPtrIncrementalBlock - * records. We need to handle them specially, since we have to go around - * updating UserEditAtoms if they shuffle about on disk - * These hold references to where slides "live". If the position of a slide - * moves, then we have update all of these. If we come up with a new version - * of a slide, then we have to add one of these to the end of the chain - * (via CurrentUserAtom and UserEditAtom) pointing to the new slide location - * - * @author Nick Burch - */ - -public final class PersistPtrHolder extends PositionDependentRecordAtom -{ - private final byte[] _header; - private byte[] _ptrData; // Will need to update this once we allow updates to _slideLocations - private long _type; - - /** - * Holds the lookup for slides to their position on disk. - * You always need to check the most recent PersistPtrHolder - * that knows about a given slide to find the right location - */ - private Map _slideLocations; - - private static final BitField persistIdFld = new BitField(0X000FFFFF); - private static final BitField cntPersistFld = new BitField(0XFFF00000); - - /** - * Return the value we were given at creation, be it 6001 or 6002 - */ - @Override - public long getRecordType() { return _type; } - - /** - * Get the list of slides that this PersistPtrHolder knows about. - * (They will be the keys in the map for looking up the positions - * of these slides) - */ - public int[] getKnownSlideIDs() { - int[] ids = new int[_slideLocations.size()]; - int i = 0; - for (Integer slideId : _slideLocations.keySet()) { - ids[i++] = slideId; - } - return ids; - } - - /** - * Get the lookup from slide numbers to byte offsets, for the slides - * known about by this PersistPtrHolder. - */ - public Map getSlideLocationsLookup() { - return Collections.unmodifiableMap(_slideLocations); - } - - /** - * Create a new holder for a PersistPtr record - */ - protected PersistPtrHolder(byte[] source, int start, int len) { - // Sanity Checking - including whole header, so treat - // length as based of 0, not 8 (including header size based) - if(len < 8) { len = 8; } - - // Treat as an atom, grab and hold everything - _header = new byte[8]; - System.arraycopy(source,start,_header,0,8); - _type = LittleEndian.getUShort(_header,2); - - // Try to make sense of the data part: - // Data part is made up of a number of these sets: - // 32 bit info value - // 12 bits count of # of entries - // base number for these entries - // count * 32 bit offsets - // Repeat as many times as you have data - _slideLocations = new HashMap(); - _ptrData = new byte[len-8]; - System.arraycopy(source,start+8,_ptrData,0,_ptrData.length); - - int pos = 0; - while(pos < _ptrData.length) { - // Grab the info field - int info = LittleEndian.getInt(_ptrData,pos); - - // First 20 bits = offset number - // Remaining 12 bits = offset count - int offset_no = persistIdFld.getValue(info); - int offset_count = cntPersistFld.getValue(info); - - // Wind on by the 4 byte info header - pos += 4; - - // Grab the offsets for each of the sheets - for(int i=0; i oldToNewReferencesLookup) { - // Loop over all the slides we know about - // Find where they used to live, and where they now live - for (Entry me : _slideLocations.entrySet()) { - Integer oldPos = me.getValue(); - Integer newPos = oldToNewReferencesLookup.get(oldPos); - - if (newPos == null) { - Integer id = me.getKey(); - logger.log(POILogger.WARN, "Couldn't find the new location of the \"slide\" with id " + id + " that used to be at " + oldPos); - logger.log(POILogger.WARN, "Not updating the position of it, you probably won't be able to find it any more (if you ever could!)"); - } else { - me.setValue(newPos); - } - } - } - - private void normalizePersistDirectory() { - TreeMap orderedSlideLocations = new TreeMap(_slideLocations); - - @SuppressWarnings("resource") - BufAccessBAOS bos = new BufAccessBAOS(); // NOSONAR - byte intbuf[] = new byte[4]; - int lastPersistEntry = -1; - int lastSlideId = -1; - for (Entry me : orderedSlideLocations.entrySet()) { - int nextSlideId = me.getKey(); - int offset = me.getValue(); - try { - // Building the info block - // First 20 bits = offset number = slide ID (persistIdFld, i.e. first slide ID of a continuous group) - // Remaining 12 bits = offset count = 1 (cntPersistFld, i.e. continuous entries in a group) - - if (lastSlideId+1 == nextSlideId) { - // use existing PersistDirectoryEntry, need to increase entry count - assert(lastPersistEntry != -1); - int infoBlock = LittleEndian.getInt(bos.getBuf(), lastPersistEntry); - int entryCnt = cntPersistFld.getValue(infoBlock); - infoBlock = cntPersistFld.setValue(infoBlock, entryCnt+1); - LittleEndian.putInt(bos.getBuf(), lastPersistEntry, infoBlock); - } else { - // start new PersistDirectoryEntry - lastPersistEntry = bos.size(); - int infoBlock = persistIdFld.setValue(0, nextSlideId); - infoBlock = cntPersistFld.setValue(infoBlock, 1); - LittleEndian.putInt(intbuf, 0, infoBlock); - bos.write(intbuf); - } - // Add to the ptrData offset lookup hash - LittleEndian.putInt(intbuf, 0, offset); - bos.write(intbuf); - lastSlideId = nextSlideId; - } catch (IOException e) { - // ByteArrayOutputStream is very unlikely throwing a IO exception (maybe because of OOM ...) - throw new HSLFException(e); - } - } - - // Save the new ptr data - _ptrData = bos.toByteArray(); - - // Update the atom header - LittleEndian.putInt(_header,4,bos.size()); - } - - /** - * Write the contents of the record back, so it can be written - * to disk - */ - @Override - public void writeOut(OutputStream out) throws IOException { - normalizePersistDirectory(); - out.write(_header); - out.write(_ptrData); - } - - private static class BufAccessBAOS extends ByteArrayOutputStream { - public byte[] getBuf() { - return buf; - } - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/PersistRecord.java b/src/scratchpad/src/org/apache/poi/hslf/record/PersistRecord.java deleted file mode 100644 index 339331865..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/PersistRecord.java +++ /dev/null @@ -1,36 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -/** - * A record that can be referenced in PersistPtr storage. - * - * @author Yegor Kozlov - */ -public interface PersistRecord { - - /** - * Fetch the persist ID - */ - public int getPersistId(); - - /** - * Set the persist ID - */ - public void setPersistId(int id); -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/PositionDependentRecord.java b/src/scratchpad/src/org/apache/poi/hslf/record/PositionDependentRecord.java deleted file mode 100644 index 844c14d45..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/PositionDependentRecord.java +++ /dev/null @@ -1,51 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; -import java.util.Map; - -/** - * Records which either care about where they are on disk, or have other - * records who care about where they are, will implement this interface. - * Normally, they'll subclass PositionDependentRecordAtom or - * PositionDependentRecordContainer, which will do the work of providing - * the setting and updating interfaces for them. - * This is a special (and dangerous) kind of Record. When created, they - * need to be pinged with their current location. When written out, they - * need to be given their new location, and offered the list of records - * which have changed their location. - * - * @author Nick Burch - */ - -public interface PositionDependentRecord -{ - /** Fetch our location on the disk, as of the last write out */ - public int getLastOnDiskOffset(); - - /** - * Update the Record's idea of where on disk it lives, after a write out. - * Use with care... - */ - public void setLastOnDiskOffset(int offset); - - /** - * Offer the record the list of records that have changed their - * location as part of the writeout. - */ - public void updateOtherRecordReferences(Map oldToNewReferencesLookup); -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/PositionDependentRecordAtom.java b/src/scratchpad/src/org/apache/poi/hslf/record/PositionDependentRecordAtom.java deleted file mode 100644 index dce90a981..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/PositionDependentRecordAtom.java +++ /dev/null @@ -1,50 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; -import java.util.Map; - -/** - * A special (and dangerous) kind of Record Atom that cares about where - * it lives on the disk, or who has other Atoms that care about where - * this is on the disk. - */ - -public abstract class PositionDependentRecordAtom extends RecordAtom implements PositionDependentRecord -{ - /** Our location on the disk, as of the last write out */ - private int myLastOnDiskOffset; - - /** Fetch our location on the disk, as of the last write out */ - public int getLastOnDiskOffset() { return myLastOnDiskOffset; } - - /** - * Update the Record's idea of where on disk it lives, after a write out. - * Use with care... - */ - public void setLastOnDiskOffset(int offset) { - myLastOnDiskOffset = offset; - } - - /** - * Offer the record the list of records that have changed their - * location as part of the writeout. - * Allows records to update their internal pointers to other records - * locations - */ - public abstract void updateOtherRecordReferences(Map oldToNewReferencesLookup); -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/PositionDependentRecordContainer.java b/src/scratchpad/src/org/apache/poi/hslf/record/PositionDependentRecordContainer.java deleted file mode 100644 index fdd61d9cf..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/PositionDependentRecordContainer.java +++ /dev/null @@ -1,63 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; -import java.util.Map; - -/** - * A special (and dangerous) kind of Record Container, for which other - * Atoms care about where this one lives on disk. - * Will track its position on disk. - */ - -public abstract class PositionDependentRecordContainer extends RecordContainer implements PositionDependentRecord -{ - private int sheetId; // Found from PersistPtrHolder - - /** - * Fetch our sheet ID, as found from a PersistPtrHolder. - * Should match the RefId of our matching SlidePersistAtom - */ - public int getSheetId() { return sheetId; } - - /** - * Set our sheet ID, as found from a PersistPtrHolder - */ - public void setSheetId(int id) { sheetId = id; } - - - /** Our location on the disk, as of the last write out */ - private int myLastOnDiskOffset; - - /** Fetch our location on the disk, as of the last write out */ - public int getLastOnDiskOffset() { return myLastOnDiskOffset; } - - /** - * Update the Record's idea of where on disk it lives, after a write out. - * Use with care... - */ - public void setLastOnDiskOffset(int offset) { - myLastOnDiskOffset = offset; - } - - /** - * Since we're a container, we don't mind if other records move about. - * If we're told they have, just return straight off. - */ - public void updateOtherRecordReferences(Map oldToNewReferencesLookup) { - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/Record.java b/src/scratchpad/src/org/apache/poi/hslf/record/Record.java deleted file mode 100644 index 73017b798..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/Record.java +++ /dev/null @@ -1,204 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import java.io.IOException; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.hslf.exceptions.CorruptPowerPointFileException; -import org.apache.poi.hslf.exceptions.HSLFException; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; - -/** - * This abstract class represents a record in the PowerPoint document. - * Record classes should extend with RecordContainer or RecordAtom, which - * extend this in turn. - * - * @author Nick Burch - */ - -public abstract class Record -{ - // For logging - protected static final POILogger logger = POILogFactory.getLogger(Record.class); - - /** - * Is this record type an Atom record (only has data), - * or is it a non-Atom record (has other records)? - */ - public abstract boolean isAnAtom(); - - /** - * Returns the type (held as a little endian in bytes 3 and 4) - * that this class handles - */ - public abstract long getRecordType(); - - /** - * Fetch all the child records of this record - * If this record is an atom, will return null - * If this record is a non-atom, but has no children, will return - * an empty array - */ - public abstract Record[] getChildRecords(); - - /** - * Have the contents printer out into an OutputStream, used when - * writing a file back out to disk - * (Normally, atom classes will keep their bytes around, but - * non atom classes will just request the bytes from their - * children, then chuck on their header and return) - */ - public abstract void writeOut(OutputStream o) throws IOException; - - /** - * When writing out, write out a signed int (32bit) in Little Endian format - */ - public static void writeLittleEndian(int i,OutputStream o) throws IOException { - byte[] bi = new byte[4]; - LittleEndian.putInt(bi,0,i); - o.write(bi); - } - /** - * When writing out, write out a signed short (16bit) in Little Endian format - */ - public static void writeLittleEndian(short s,OutputStream o) throws IOException { - byte[] bs = new byte[2]; - LittleEndian.putShort(bs,0,s); - o.write(bs); - } - - /** - * Build and return the Record at the given offset. - * Note - does less error checking and handling than findChildRecords - * @param b The byte array to build from - * @param offset The offset to build at - */ - public static Record buildRecordAtOffset(byte[] b, int offset) { - long type = LittleEndian.getUShort(b,offset+2); - long rlen = LittleEndian.getUInt(b,offset+4); - - // Sanity check the length - int rleni = (int)rlen; - if(rleni < 0) { rleni = 0; } - - return createRecordForType(type,b,offset,8+rleni); - } - - /** - * Default method for finding child records of a container record - */ - public static Record[] findChildRecords(byte[] b, int start, int len) { - List children = new ArrayList(5); - - // Jump our little way along, creating records as we go - int pos = start; - while(pos <= (start+len-8)) { - long type = LittleEndian.getUShort(b,pos+2); - long rlen = LittleEndian.getUInt(b,pos+4); - - // Sanity check the length - int rleni = (int)rlen; - if(rleni < 0) { rleni = 0; } - - // Abort if first record is of type 0000 and length FFFF, - // as that's a sign of a screwed up record - if(pos == 0 && type == 0l && rleni == 0xffff) { - throw new CorruptPowerPointFileException("Corrupt document - starts with record of type 0000 and length 0xFFFF"); - } - - Record r = createRecordForType(type,b,pos,8+rleni); - if(r != null) { - children.add(r); - } else { - // Record was horribly corrupt - } - pos += 8; - pos += rleni; - } - - // Turn the vector into an array, and return - Record[] cRecords = children.toArray( new Record[children.size()] ); - return cRecords; - } - - /** - * For a given type (little endian bytes 3 and 4 in record header), - * byte array, start position and length: - * will return a Record object that will handle that record - * - * Remember that while PPT stores the record lengths as 8 bytes short - * (not including the size of the header), this code assumes you're - * passing in corrected lengths - */ - public static Record createRecordForType(long type, byte[] b, int start, int len) { - Record toReturn = null; - - // Handle case of a corrupt last record, whose claimed length - // would take us passed the end of the file - if(start + len > b.length) { - logger.log(POILogger.WARN, "Warning: Skipping record of type " + type + " at position " + start + " which claims to be longer than the file! (" + len + " vs " + (b.length-start) + ")"); - return null; - } - - // We use the RecordTypes class to provide us with the right - // class to use for a given type - // A spot of reflection gets us the (byte[],int,int) constructor - // From there, we instanciate the class - // Any special record handling occurs once we have the class - Class c = null; - try { - c = RecordTypes.forTypeID((short)type).handlingClass; - if(c == null) { - // How odd. RecordTypes normally substitutes in - // a default handler class if it has heard of the record - // type but there's no support for it. Explicitly request - // that now - c = RecordTypes.UnknownRecordPlaceholder.handlingClass; - } - - // Grab the right constructor - java.lang.reflect.Constructor con = c.getDeclaredConstructor(new Class[] { byte[].class, Integer.TYPE, Integer.TYPE }); - // Instantiate - toReturn = con.newInstance(new Object[] { b, start, len }); - } catch(InstantiationException ie) { - throw new HSLFException("Couldn't instantiate the class for type with id " + type + " on class " + c + " : " + ie, ie); - } catch(java.lang.reflect.InvocationTargetException ite) { - throw new HSLFException("Couldn't instantiate the class for type with id " + type + " on class " + c + " : " + ite + "\nCause was : " + ite.getCause(), ite); - } catch(IllegalAccessException iae) { - throw new HSLFException("Couldn't access the constructor for type with id " + type + " on class " + c + " : " + iae, iae); - } catch(NoSuchMethodException nsme) { - throw new HSLFException("Couldn't access the constructor for type with id " + type + " on class " + c + " : " + nsme, nsme); - } - - // Handling for special kinds of records follow - - // If it's a position aware record, tell it where it is - if(toReturn instanceof PositionDependentRecord) { - PositionDependentRecord pdr = (PositionDependentRecord)toReturn; - pdr.setLastOnDiskOffset(start); - } - - // Return the created record - return toReturn; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/RecordAtom.java b/src/scratchpad/src/org/apache/poi/hslf/record/RecordAtom.java deleted file mode 100644 index 964d3d1c4..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/RecordAtom.java +++ /dev/null @@ -1,37 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -/** - * Abstract class which all atom records will extend. - * - * @author Nick Burch - */ - -public abstract class RecordAtom extends Record -{ - /** - * We are an atom - */ - public boolean isAnAtom() { return true; } - - /** - * We're an atom, returns null - */ - public Record[] getChildRecords() { return null; } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/RecordContainer.java b/src/scratchpad/src/org/apache/poi/hslf/record/RecordContainer.java deleted file mode 100644 index 3ad7b086c..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/RecordContainer.java +++ /dev/null @@ -1,344 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import org.apache.poi.util.ArrayUtil; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.hslf.util.MutableByteArrayOutputStream; - -import java.io.IOException; -import java.io.OutputStream; -import java.io.ByteArrayOutputStream; -import java.util.ArrayList; - -/** - * Abstract class which all container records will extend. Providers - * helpful methods for writing child records out to disk - * - * @author Nick Burch - */ - -public abstract class RecordContainer extends Record -{ - protected Record[] _children; - - /** - * Return any children - */ - public Record[] getChildRecords() { return _children; } - - /** - * We're not an atom - */ - public boolean isAnAtom() { return false; } - - - /* =============================================================== - * Internal Move Helpers - * =============================================================== - */ - - /** - * Finds the location of the given child record - */ - private int findChildLocation(Record child) { - int i=0; - for(Record r : _children) { - if (r.equals(child)) { - return i; - } - i++; - } - return -1; - } - - /** - * Adds a child record, at the very end. - * @param newChild The child record to add - */ - private void appendChild(Record newChild) { - // Copy over, and pop the child in at the end - Record[] nc = new Record[(_children.length + 1)]; - System.arraycopy(_children, 0, nc, 0, _children.length); - // Switch the arrays - nc[_children.length] = newChild; - _children = nc; - } - - /** - * Adds the given new Child Record at the given location, - * shuffling everything from there on down by one - * @param newChild - * @param position - */ - private void addChildAt(Record newChild, int position) { - // Firstly, have the child added in at the end - appendChild(newChild); - - // Now, have them moved to the right place - moveChildRecords( (_children.length-1), position, 1 ); - } - - /** - * Moves {@code number} child records from {@code oldLoc} to {@code newLoc}. - * @param oldLoc the current location of the records to move - * @param newLoc the new location for the records - * @param number the number of records to move - */ - private void moveChildRecords(int oldLoc, int newLoc, int number) { - if(oldLoc == newLoc) { return; } - if(number == 0) { return; } - - // Check that we're not asked to move too many - if(oldLoc+number > _children.length) { - throw new IllegalArgumentException("Asked to move more records than there are!"); - } - - // Do the move - ArrayUtil.arrayMoveWithin(_children, oldLoc, newLoc, number); - } - - - /** - * Finds the first child record of the given type, - * or null if none of the child records are of the - * given type. Does not descend. - */ - public Record findFirstOfType(long type) { - for (Record r : _children) { - if (r.getRecordType() == type) { - return r; - } - } - return null; - } - - /** - * Remove a child record from this record container - * - * @param ch the child to remove - * @return the removed record - */ - public Record removeChild(Record ch) { - Record rm = null; - ArrayList lst = new ArrayList(); - for(Record r : _children) { - if(r != ch) lst.add(r); - else rm = r; - } - _children = lst.toArray(new Record[lst.size()]); - return rm; - } - - /* =============================================================== - * External Move Methods - * =============================================================== - */ - - /** - * Add a new child record onto a record's list of children. - */ - public void appendChildRecord(Record newChild) { - appendChild(newChild); - } - - /** - * Adds the given Child Record after the supplied record - * @param newChild - * @param after - */ - public void addChildAfter(Record newChild, Record after) { - // Decide where we're going to put it - int loc = findChildLocation(after); - if(loc == -1) { - throw new IllegalArgumentException("Asked to add a new child after another record, but that record wasn't one of our children!"); - } - - // Add one place after the supplied record - addChildAt(newChild, loc+1); - } - - /** - * Adds the given Child Record before the supplied record - * @param newChild - * @param before - */ - public void addChildBefore(Record newChild, Record before) { - // Decide where we're going to put it - int loc = findChildLocation(before); - if(loc == -1) { - throw new IllegalArgumentException("Asked to add a new child before another record, but that record wasn't one of our children!"); - } - - // Add at the place of the supplied record - addChildAt(newChild, loc); - } - - /** - * Moves the given Child Record to before the supplied record - */ - public void moveChildBefore(Record child, Record before) { - moveChildrenBefore(child, 1, before); - } - - /** - * Moves the given Child Records to before the supplied record - */ - public void moveChildrenBefore(Record firstChild, int number, Record before) { - if(number < 1) { return; } - - // Decide where we're going to put them - int newLoc = findChildLocation(before); - if(newLoc == -1) { - throw new IllegalArgumentException("Asked to move children before another record, but that record wasn't one of our children!"); - } - - // Figure out where they are now - int oldLoc = findChildLocation(firstChild); - if(oldLoc == -1) { - throw new IllegalArgumentException("Asked to move a record that wasn't a child!"); - } - - // Actually move - moveChildRecords(oldLoc, newLoc, number); - } - - /** - * Moves the given Child Records to after the supplied record - */ - public void moveChildrenAfter(Record firstChild, int number, Record after) { - if(number < 1) { return; } - // Decide where we're going to put them - int newLoc = findChildLocation(after); - if(newLoc == -1) { - throw new IllegalArgumentException("Asked to move children before another record, but that record wasn't one of our children!"); - } - // We actually want after this though - newLoc++; - - // Figure out where they are now - int oldLoc = findChildLocation(firstChild); - if(oldLoc == -1) { - throw new IllegalArgumentException("Asked to move a record that wasn't a child!"); - } - - // Actually move - moveChildRecords(oldLoc, newLoc, number); - } - - /** - * Set child records. - * - * @param records the new child records - */ - public void setChildRecord(Record[] records) { - this._children = records.clone(); - } - - /* =============================================================== - * External Serialisation Methods - * =============================================================== - */ - - /** - * Write out our header, and our children. - * @param headerA the first byte of the header - * @param headerB the second byte of the header - * @param type the record type - * @param children our child records - * @param out the stream to write to - */ - public void writeOut(byte headerA, byte headerB, long type, Record[] children, OutputStream out) throws IOException { - // If we have a mutable output stream, take advantage of that - if(out instanceof MutableByteArrayOutputStream) { - MutableByteArrayOutputStream mout = - (MutableByteArrayOutputStream)out; - - // Grab current size - int oldSize = mout.getBytesWritten(); - - // Write out our header, less the size - mout.write(new byte[] {headerA,headerB}); - byte[] typeB = new byte[2]; - LittleEndian.putShort(typeB, 0, (short)type); - mout.write(typeB); - mout.write(new byte[4]); - - // Write out the children - for(int i=0; i PowerPoint records: 0 <= info <= 10002 (will carry class info) - *
  • Escher records: info >= 0xF000 (handled by DDF, so no class info) - */ -public enum RecordTypes { - Unknown(0,null), - UnknownRecordPlaceholder(-1, UnknownRecordPlaceholder.class), - Document(1000,Document.class), - DocumentAtom(1001,DocumentAtom.class), - EndDocument(1002,null), - Slide(1006,Slide.class), - SlideAtom(1007,SlideAtom.class), - Notes(1008,Notes.class), - NotesAtom(1009,NotesAtom.class), - Environment(1010,Environment.class), - SlidePersistAtom(1011,SlidePersistAtom.class), - SSlideLayoutAtom(1015,null), - MainMaster(1016,MainMaster.class), - SSSlideInfoAtom(1017,SSSlideInfoAtom.class), - SlideViewInfo(1018,null), - GuideAtom(1019,null), - ViewInfo(1020,null), - ViewInfoAtom(1021,null), - SlideViewInfoAtom(1022,null), - VBAInfo(1023,VBAInfoContainer.class), - VBAInfoAtom(1024,VBAInfoAtom.class), - SSDocInfoAtom(1025,null), - Summary(1026,null), - DocRoutingSlip(1030,null), - OutlineViewInfo(1031,null), - SorterViewInfo(1032,null), - ExObjList(1033,ExObjList.class), - ExObjListAtom(1034,ExObjListAtom.class), - PPDrawingGroup(1035,PPDrawingGroup.class), - PPDrawing(1036,PPDrawing.class), - NamedShows(1040,null), - NamedShow(1041,null), - NamedShowSlides(1042,null), - SheetProperties(1044,null), - RoundTripCustomTableStyles12Atom(1064,null), - List(2000,DocInfoListContainer.class), - FontCollection(2005,FontCollection.class), - BookmarkCollection(2019,null), - SoundCollection(2020,SoundCollection.class), - SoundCollAtom(2021,null), - Sound(2022,Sound.class), - SoundData(2023,SoundData.class), - BookmarkSeedAtom(2025,null), - ColorSchemeAtom(2032,ColorSchemeAtom.class), - ExObjRefAtom(3009,ExObjRefAtom.class), - OEPlaceholderAtom(3011,OEPlaceholderAtom.class), - GPopublicintAtom(3024,null), - GRatioAtom(3031,null), - OutlineTextRefAtom(3998,OutlineTextRefAtom.class), - TextHeaderAtom(3999,TextHeaderAtom.class), - TextCharsAtom(4000,TextCharsAtom.class), - StyleTextPropAtom(4001, StyleTextPropAtom.class),//0x0fa1 RT_StyleTextPropAtom - MasterTextPropAtom(4002, MasterTextPropAtom.class), - TxMasterStyleAtom(4003,TxMasterStyleAtom.class), - TxCFStyleAtom(4004,null), - TxPFStyleAtom(4005,null), - TextRulerAtom(4006,TextRulerAtom.class), - TextBookmarkAtom(4007,null), - TextBytesAtom(4008,TextBytesAtom.class), - TxSIStyleAtom(4009,null), - TextSpecInfoAtom(4010, TextSpecInfoAtom.class), - DefaultRulerAtom(4011,null), - StyleTextProp9Atom(4012, StyleTextProp9Atom.class), //0x0FAC RT_StyleTextProp9Atom - FontEntityAtom(4023,FontEntityAtom.class), - FontEmbeddedData(4024,null), - CString(4026,CString.class), - MetaFile(4033,null), - ExOleObjAtom(4035,ExOleObjAtom.class), - SrKinsoku(4040,null), - HandOut(4041,DummyPositionSensitiveRecordWithChildren.class), - ExEmbed(4044,ExEmbed.class), - ExEmbedAtom(4045,ExEmbedAtom.class), - ExLink(4046,null), - BookmarkEntityAtom(4048,null), - ExLinkAtom(4049,null), - SrKinsokuAtom(4050,null), - ExHyperlinkAtom(4051,ExHyperlinkAtom.class), - ExHyperlink(4055,ExHyperlink.class), - SlideNumberMCAtom(4056,null), - HeadersFooters(4057,HeadersFootersContainer.class), - HeadersFootersAtom(4058,HeadersFootersAtom.class), - TxInteractiveInfoAtom(4063,TxInteractiveInfoAtom.class), - CharFormatAtom(4066,null), - ParaFormatAtom(4067,null), - RecolorInfoAtom(4071,null), - ExQuickTimeMovie(4074,null), - ExQuickTimeMovieData(4075,null), - ExControl(4078,ExControl.class), - SlideListWithText(4080,SlideListWithText.class), - InteractiveInfo(4082,InteractiveInfo.class), - InteractiveInfoAtom(4083,InteractiveInfoAtom.class), - UserEditAtom(4085,UserEditAtom.class), - CurrentUserAtom(4086,null), - DateTimeMCAtom(4087,null), - GenericDateMCAtom(4088,null), - FooterMCAtom(4090,null), - ExControlAtom(4091,ExControlAtom.class), - ExMediaAtom(4100,ExMediaAtom.class), - ExVideoContainer(4101,ExVideoContainer.class), - ExAviMovie(4102,ExAviMovie.class), - ExMCIMovie(4103,ExMCIMovie.class), - ExMIDIAudio(4109,null), - ExCDAudio(4110,null), - ExWAVAudioEmbedded(4111,null), - ExWAVAudioLink(4112,null), - ExOleObjStg(4113,ExOleObjStg.class), - ExCDAudioAtom(4114,null), - ExWAVAudioEmbeddedAtom(4115,null), - AnimationInfo(4116,AnimationInfo.class), - AnimationInfoAtom(4081,AnimationInfoAtom.class), - RTFDateTimeMCAtom(4117,null), - ProgTags(5000,DummyPositionSensitiveRecordWithChildren.class), - ProgStringTag(5001,null), - ProgBinaryTag(5002,DummyPositionSensitiveRecordWithChildren.class), - BinaryTagData(5003, BinaryTagDataBlob.class),//0x138b RT_BinaryTagDataBlob - PrpublicintOptions(6000,null), - PersistPtrFullBlock(6001,PersistPtrHolder.class), - PersistPtrIncrementalBlock(6002,PersistPtrHolder.class), - GScalingAtom(10001,null), - GRColorAtom(10002,null), - - // Records ~12000 seem to be related to the Comments used in PPT 2000/XP - // (Comments in PPT97 are normal Escher text boxes) - Comment2000(12000,Comment2000.class), - Comment2000Atom(12001,Comment2000Atom.class), - Comment2000Summary(12004,null), - Comment2000SummaryAtom(12005,null), - - // Records ~12050 seem to be related to Document Encryption - DocumentEncryptionAtom(12052,DocumentEncryptionAtom.class), - - OriginalMainMasterId(1052,null), - CompositeMasterId(1052,null), - RoundTripContentMasterInfo12(1054,null), - RoundTripShapeId12(1055,null), - RoundTripHFPlaceholder12(1056,RoundTripHFPlaceholder12.class), - RoundTripContentMasterId(1058,null), - RoundTripOArtTextStyles12(1059,null), - RoundTripShapeCheckSumForCustomLayouts12(1062,null), - RoundTripNotesMasterTextStyles12(1063,null), - RoundTripCustomTableStyles12(1064,null), - - // records greater then 0xF000 belong to with Microsoft Office Drawing format also known as Escher - EscherDggContainer(0xF000,null), - EscherDgg(0xf006,null), - EscherCLSID(0xf016,null), - EscherOPT(0xf00b,null), - EscherBStoreContainer(0xf001,null), - EscherBSE(0xf007,null), - EscherBlip_START(0xf018,null), - EscherBlip_END(0xf117,null), - EscherDgContainer(0xf002,null), - EscherDg(0xf008,null), - EscherRegroupItems(0xf118,null), - EscherColorScheme(0xf120,null), - EscherSpgrContainer(0xf003,null), - EscherSpContainer(0xf004,null), - EscherSpgr(0xf009,null), - EscherSp(0xf00a,null), - EscherTextbox(0xf00c,null), - EscherClientTextbox(0xf00d,null), - EscherAnchor(0xf00e,null), - EscherChildAnchor(0xf00f,null), - EscherClientAnchor(0xf010,null), - EscherClientData(0xf011,null), - EscherSolverContainer(0xf005,null), - EscherConnectorRule(0xf012,null), - EscherAlignRule(0xf013,null), - EscherArcRule(0xf014,null), - EscherClientRule(0xf015,null), - EscherCalloutRule(0xf017,null), - EscherSelection(0xf119,null), - EscherColorMRU(0xf11a,null), - EscherDeletedPspl(0xf11d,null), - EscherSplitMenuColors(0xf11e,null), - EscherOleObject(0xf11f,null), - EscherUserDefined(0xf122,null); - - private static final Map LOOKUP; - - static { - LOOKUP = new HashMap(); - for(RecordTypes s : values()) { - LOOKUP.put(s.typeID, s); - } - } - - public final short typeID; - public final Class handlingClass; - - private RecordTypes(int typeID, Class handlingClass) { - this.typeID = (short)typeID; - this.handlingClass = handlingClass; - } - - public static RecordTypes forTypeID(int typeID) { - RecordTypes rt = LOOKUP.get((short)typeID); - return (rt != null) ? rt : UnknownRecordPlaceholder; - } - - - - /** - * Returns name of the record by its type - * - * @param type section of the record header - * @return name of the record - */ -// public static String recordName(int type) { -// String name = typeToName.get(Integer.valueOf(type)); -// return (name == null) ? ("Unknown" + type) : name; -// } - - /** - * Returns the class handling a record by its type. - * If given an un-handled PowerPoint record, will return a dummy - * placeholder class. If given an unknown PowerPoint record, or - * and Escher record, will return null. - * - * @param type section of the record header - * @return class to handle the record, or null if an unknown (eg Escher) record - */ -// public static Class recordHandlingClass(int type) { -// Class c = typeToClass.get(Integer.valueOf(type)); -// return c; -// } -// -// static { -// typeToName = new HashMap(); -// typeToClass = new HashMap>(); -// try { -// Field[] f = RecordTypes.class.getFields(); -// for (int i = 0; i < f.length; i++){ -// Object val = f[i].get(null); -// -// // Escher record, only store ID -> Name -// if (val instanceof Integer) { -// typeToName.put((Integer)val, f[i].getName()); -// } -// // PowerPoint record, store ID -> Name and ID -> Class -// if (val instanceof Type) { -// Type t = (Type)val; -// Class c = t.handlingClass; -// Integer id = Integer.valueOf(t.typeID); -// if(c == null) { c = UnknownRecordPlaceholder.class; } -// -// typeToName.put(id, f[i].getName()); -// typeToClass.put(id, c); -// } -// } -// } catch (IllegalAccessException e){ -// throw new HSLFException("Failed to initialize records types"); -// } -// } - - - /** - * Wrapper for the details of a PowerPoint or Escher record type. - * Contains both the type, and the handling class (if any), and - * offers methods to get either back out. - */ -// public static class Type { -// public final int typeID; -// public final Class handlingClass; -// public Type(int typeID, Class handlingClass) { -// this.typeID = typeID; -// this.handlingClass = handlingClass; -// } -// } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/RoundTripHFPlaceholder12.java b/src/scratchpad/src/org/apache/poi/hslf/record/RoundTripHFPlaceholder12.java deleted file mode 100644 index e843f1dd7..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/RoundTripHFPlaceholder12.java +++ /dev/null @@ -1,105 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import java.io.IOException; -import java.io.OutputStream; - -import org.apache.poi.util.LittleEndian; - -/** - * An atom record that specifies that a shape is a header or footer placeholder shape - * - * @since PowerPoint 2007 - * @author Yegor Kozlov - */ -public final class RoundTripHFPlaceholder12 extends RecordAtom { - /** - * Record header. - */ - private byte[] _header; - - /** - * Specifies the placeholder shape ID. - * - * MUST be {@link OEPlaceholderAtom#MasterDate}, {@link OEPlaceholderAtom#MasterSlideNumber}, - * {@link OEPlaceholderAtom#MasterFooter}, or {@link OEPlaceholderAtom#MasterHeader} - */ - private byte _placeholderId; - - /** - * Create a new instance of RoundTripHFPlaceholder12 - */ - public RoundTripHFPlaceholder12(){ - _header = new byte[8]; - LittleEndian.putUShort(_header, 0, 0); - LittleEndian.putUShort(_header, 2, (int)getRecordType()); - LittleEndian.putInt(_header, 4, 8); - _placeholderId = 0; - } - - /** - * Constructs the comment atom record from its source data. - * - * @param source the source data as a byte array. - * @param start the start offset into the byte array. - * @param len the length of the slice in the byte array. - */ - protected RoundTripHFPlaceholder12(byte[] source, int start, int len) { - // Get the header. - _header = new byte[8]; - System.arraycopy(source,start,_header,0,8); - - // Get the record data. - _placeholderId = source[start+8]; - } - - /** - * Gets the comment number (note - each user normally has their own count). - * @return the comment number. - */ - public int getPlaceholderId() { - return _placeholderId; - } - - /** - * Sets the comment number (note - each user normally has their own count). - * @param number the comment number. - */ - public void setPlaceholderId(int number) { - _placeholderId = (byte)number; - } - - /** - * Gets the record type. - * @return the record type. - */ - public long getRecordType() { return RecordTypes.RoundTripHFPlaceholder12.typeID; } - - /** - * Write the contents of the record back, so it can be written - * to disk - * - * @param out the output stream to write to. - * @throws java.io.IOException if an error occurs. - */ - public void writeOut(OutputStream out) throws IOException { - out.write(_header); - out.write(_placeholderId); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/SSSlideInfoAtom.java b/src/scratchpad/src/org/apache/poi/hslf/record/SSSlideInfoAtom.java deleted file mode 100644 index b087b66b0..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/SSSlideInfoAtom.java +++ /dev/null @@ -1,289 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import java.io.IOException; -import java.io.OutputStream; - -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.LittleEndianConsts; - -/** - * A SlideShowSlideInfo Atom (type 1017).
    - *
    - * - * An atom record that specifies which transition effects to perform - * during a slide show, and how to advance to the next presentation slide.
    - *
    - * - * Combination of effectType and effectDirection: - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
    typedescriptiondirection
    0cut0x00 = no transition, 0x01 = black transition
    1random0x00
    2blinds0x00 = vertical, 0x01 = horizontal
    3checkerlike blinds
    4cover0x00 = left, 0x01 = up, 0x02 = right, 0x03 = down, 0x04 = left/up, 0x05 = right/up, 0x06 left/down, 0x07 = left/down
    5dissolve0x00
    6fade0x00
    7uncoverlike cover
    8random barslike blinds
    9stripslike 0x04 - 0x07 of cover
    10wipelike 0x00 - 0x03 of cover
    11box in/out0x00 = out, 0x01 = in
    13split0x00 = horizontally out, 0x01 = horizontally in, 0x02 = vertically out, 0x03 = vertically in
    17diamond0x00
    18plus0x00
    19wedge0x00
    20pushlike 0x00 - 0x03 of cover
    21comblike blinds
    22newsflash0x00
    23alphafade0x00
    26wheelnumber of radial divisions (0x01,0x02,0x03,0x04,0x08)
    27circle0x00
    255undefined0x00
    - */ -public class SSSlideInfoAtom extends RecordAtom { - /** - * A bit that specifies whether the presentation slide can be - * manually advanced by the user during the slide show. - */ - public static final int MANUAL_ADVANCE_BIT = 1 << 0; - - /** - * A bit that specifies whether the corresponding slide is - * hidden and is not displayed during the slide show. - */ - public static final int HIDDEN_BIT = 1 << 2; - - /** - * A bit that specifies whether to play the sound specified by soundIfRef. - */ - public static final int SOUND_BIT = 1 << 4; - - /** - * A bit that specifies whether the sound specified by soundIdRef is - * looped continuously when playing until the next sound plays. - */ - public static final int LOOP_SOUND_BIT = 1 << 6; - - /** - * A bit that specifies whether to stop any currently playing - * sound when the transition starts. - */ - public static final int STOP_SOUND_BIT = 1 << 8; - - /** - * A bit that specifies whether the slide will automatically - * advance after slideTime milliseconds during the slide show. - */ - public static final int AUTO_ADVANCE_BIT = 1 << 10; - - /** - * A bit that specifies whether to display the cursor during - * the slide show. - */ - public static final int CURSOR_VISIBLE_BIT = 1 << 12; - - // public static int RESERVED1_BIT = 1 << 1; - // public static int RESERVED2_BIT = 1 << 3; - // public static int RESERVED3_BIT = 1 << 5; - // public static int RESERVED4_BIT = 1 << 7; - // public static int RESERVED5_BIT = 1 << 9; - // public static int RESERVED6_BIT = 1 << 11; - // public static int RESERVED7_BIT = 1 << 13 | 1 << 14 | 1 << 15; - - private static final long _type = RecordTypes.SSSlideInfoAtom.typeID; - - private byte[] _header; - - /** - * A signed integer that specifies an amount of time, in milliseconds, to wait - * before advancing to the next presentation slide. It MUST be greater than or equal to 0 and - * less than or equal to 86399000. It MUST be ignored unless AUTO_ADVANCE_BIT is TRUE. - */ - private int _slideTime = 0; - - /** - * A SoundIdRef that specifies which sound to play when the transition starts. - */ - private int _soundIdRef = 0; - - /** - * A byte that specifies the variant of effectType. In combination of the effectType - * there are further restriction and specification of this field. - */ - private short _effectDirection = 0; // byte - - /** - * A byte that specifies which transition is used when transitioning to the - * next presentation slide during a slide show. Exact rendering of any transition is - * determined by the rendering application. As such, the same transition can have - * many variations depending on the implementation. - */ - private short _effectType = 0; // byte - - /** - * Various flags - see bitmask for more details - */ - private short _effectTransitionFlags = 0; - - /** - * A byte value that specifies how long the transition takes to run. - * (0x00 = 0.75 seconds, 0x01 = 0.5 seconds, 0x02 = 0.25 seconds) - */ - private short _speed = 0; // byte - private byte[] _unused; // 3-byte - - public SSSlideInfoAtom() { - _header = new byte[8]; - LittleEndian.putShort(_header, 0, (short)0); - LittleEndian.putShort(_header, 2, (short)_type); - LittleEndian.putShort(_header, 4, (short)0x10); - LittleEndian.putShort(_header, 6, (short)0); - _unused = new byte[3]; - } - - public SSSlideInfoAtom(byte[] source, int offset, int len) { - int ofs = offset; - - // Sanity Checking - if(len != 24) len = 24; - assert(source.length >= offset+len); - - // Get the header - _header = LittleEndian.getByteArray(source,ofs,8); - ofs += _header.length; - - assert(LittleEndian.getShort(_header, 0) == 0); - assert(LittleEndian.getShort(_header, 2) == RecordTypes.SSSlideInfoAtom.typeID); - assert(LittleEndian.getShort(_header, 4) == 0x10); - assert(LittleEndian.getShort(_header, 6) == 0); - - _slideTime = LittleEndian.getInt(source, ofs); - assert(0 <= _slideTime && _slideTime <= 86399000); - ofs += LittleEndianConsts.INT_SIZE; - _soundIdRef = LittleEndian.getInt(source, ofs); - ofs += LittleEndianConsts.INT_SIZE; - _effectDirection = LittleEndian.getUByte(source, ofs); - ofs += LittleEndianConsts.BYTE_SIZE; - _effectType = LittleEndian.getUByte(source, ofs); - ofs += LittleEndianConsts.BYTE_SIZE; - _effectTransitionFlags = LittleEndian.getShort(source, ofs); - ofs += LittleEndianConsts.SHORT_SIZE; - _speed = LittleEndian.getUByte(source, ofs); - ofs += LittleEndianConsts.BYTE_SIZE; - _unused = LittleEndian.getByteArray(source,ofs,3); - } - - /** - * Write the contents of the record back, so it can be written - * to disk - */ - public void writeOut(OutputStream out) throws IOException { - // Header - size or type unchanged - out.write(_header); - writeLittleEndian(_slideTime, out); - writeLittleEndian(_soundIdRef, out); - - byte byteBuf[] = new byte[LittleEndianConsts.BYTE_SIZE]; - LittleEndian.putUByte(byteBuf, 0, _effectDirection); - out.write(byteBuf); - LittleEndian.putUByte(byteBuf, 0, _effectType); - out.write(byteBuf); - - writeLittleEndian(_effectTransitionFlags, out); - LittleEndian.putUByte(byteBuf, 0, _speed); - out.write(byteBuf); - - assert(_unused.length == 3); - out.write(_unused); - } - - /** - * We are of type 1017 - */ - public long getRecordType() { return _type; } - - - public int getSlideTime() { - return _slideTime; - } - - public void setSlideTime(int slideTime) { - this._slideTime = slideTime; - } - - public int getSoundIdRef() { - return _soundIdRef; - } - - public void setSoundIdRef(int soundIdRef) { - this._soundIdRef = soundIdRef; - } - - public short getEffectDirection() { - return _effectDirection; - } - - public void setEffectDirection(short effectDirection) { - this._effectDirection = effectDirection; - } - - public short getEffectType() { - return _effectType; - } - - public void setEffectType(short effectType) { - this._effectType = effectType; - } - - public short getEffectTransitionFlags() { - return _effectTransitionFlags; - } - - public void setEffectTransitionFlags(short effectTransitionFlags) { - this._effectTransitionFlags = effectTransitionFlags; - } - - /** - * Use one of the bitmasks MANUAL_ADVANCE_BIT ... CURSOR_VISIBLE_BIT - * @param bitmask - * @param enabled - */ - public void setEffectTransitionFlagByBit(int bitmask, boolean enabled) { - if (enabled) { - _effectTransitionFlags |= bitmask; - } else { - _effectTransitionFlags &= (0xFFFF ^ bitmask); - } - } - - public boolean getEffectTransitionFlagByBit(int bitmask) { - return ((_effectTransitionFlags & bitmask) != 0); - } - - public short getSpeed() { - return _speed; - } - - public void setSpeed(short speed) { - this._speed = speed; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/SheetContainer.java b/src/scratchpad/src/org/apache/poi/hslf/record/SheetContainer.java deleted file mode 100644 index 08c05c46a..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/SheetContainer.java +++ /dev/null @@ -1,33 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -/** - * The superclass of all sheet container records - Slide, Notes, MainMaster, etc. - */ -public abstract class SheetContainer extends PositionDependentRecordContainer { - - /** - * Returns the PPDrawing of this sheet, which has all the - * interesting data in it - */ - public abstract PPDrawing getPPDrawing(); - - public abstract ColorSchemeAtom getColorScheme(); - -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/Slide.java b/src/scratchpad/src/org/apache/poi/hslf/record/Slide.java deleted file mode 100644 index a833c4016..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/Slide.java +++ /dev/null @@ -1,118 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import java.io.IOException; -import java.io.OutputStream; - -import org.apache.poi.util.LittleEndian; - -/** - * Master container for Slides. There is one of these for every slide, - * and they have certain specific children - * - * @author Nick Burch - */ - -public final class Slide extends SheetContainer -{ - private byte[] _header; - private static long _type = 1006l; - - // Links to our more interesting children - private SlideAtom slideAtom; - private PPDrawing ppDrawing; - private ColorSchemeAtom _colorScheme; - - /** - * Returns the SlideAtom of this Slide - */ - public SlideAtom getSlideAtom() { return slideAtom; } - - /** - * Returns the PPDrawing of this Slide, which has all the - * interesting data in it - */ - public PPDrawing getPPDrawing() { return ppDrawing; } - - - /** - * Set things up, and find our more interesting children - */ - protected Slide(byte[] source, int start, int len) { - // Grab the header - _header = new byte[8]; - System.arraycopy(source,start,_header,0,8); - - // Find our children - _children = Record.findChildRecords(source,start+8,len-8); - - // Find the interesting ones in there - for(int i=0; i<_children.length; i++) { - if(_children[i] instanceof SlideAtom) { - slideAtom = (SlideAtom)_children[i]; - } - else if(_children[i] instanceof PPDrawing) { - ppDrawing = (PPDrawing)_children[i]; - } - - if(ppDrawing != null && _children[i] instanceof ColorSchemeAtom) { - _colorScheme = (ColorSchemeAtom)_children[i]; - } - } - } - - /** - * Create a new, empty, Slide, along with its required - * child records. - */ - public Slide(){ - _header = new byte[8]; - LittleEndian.putUShort(_header, 0, 15); - LittleEndian.putUShort(_header, 2, (int)_type); - LittleEndian.putInt(_header, 4, 0); - - slideAtom = new SlideAtom(); - ppDrawing = new PPDrawing(); - - ColorSchemeAtom colorAtom = new ColorSchemeAtom(); - - _children = new Record[] { - slideAtom, - ppDrawing, - colorAtom - }; - } - - /** - * We are of type 1006 - */ - public long getRecordType() { return _type; } - - /** - * Write the contents of the record back, so it can be written - * to disk - */ - public void writeOut(OutputStream out) throws IOException { - writeOut(_header[0],_header[1],_type,_children,out); - } - - public ColorSchemeAtom getColorScheme(){ - return _colorScheme; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/SlideAtom.java b/src/scratchpad/src/org/apache/poi/hslf/record/SlideAtom.java deleted file mode 100644 index 9d553740b..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/SlideAtom.java +++ /dev/null @@ -1,169 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import java.io.IOException; -import java.io.OutputStream; - -import org.apache.poi.hslf.record.SlideAtomLayout.SlideLayoutType; -import org.apache.poi.util.LittleEndian; - -/** - * A Slide Atom (type 1007). Holds information on the parent Slide, what - * Master Slide it uses, what Notes is attached to it, that sort of thing. - * It also has a SSlideLayoutAtom embedded in it, but without the Atom header - */ - -public final class SlideAtom extends RecordAtom { - public static final int USES_MASTER_SLIDE_ID = 0x80000000; - // private static final int MASTER_SLIDE_ID = 0x00000000; - - private byte[] _header; - private static long _type = 1007l; - - private int masterID; - private int notesID; - - private boolean followMasterObjects; - private boolean followMasterScheme; - private boolean followMasterBackground; - private SlideAtomLayout layoutAtom; - private byte[] reserved; - - - /** Get the ID of the master slide used. 0 if this is a master slide, otherwise -2147483648 */ - public int getMasterID() { return masterID; } - /** Change slide master. */ - public void setMasterID(int id) { masterID = id; } - /** Get the ID of the notes for this slide. 0 if doesn't have one */ - public int getNotesID() { return notesID; } - /** Get the embedded SSlideLayoutAtom */ - public SlideAtomLayout getSSlideLayoutAtom() { return layoutAtom; } - - /** Change the ID of the notes for this slide. 0 if it no longer has one */ - public void setNotesID(int id) { notesID = id; } - - public boolean getFollowMasterObjects() { return followMasterObjects; } - public boolean getFollowMasterScheme() { return followMasterScheme; } - public boolean getFollowMasterBackground() { return followMasterBackground; } - public void setFollowMasterObjects(boolean flag) { followMasterObjects = flag; } - public void setFollowMasterScheme(boolean flag) { followMasterScheme = flag; } - public void setFollowMasterBackground(boolean flag) { followMasterBackground = flag; } - - - /* *************** record code follows ********************** */ - - /** - * For the Slide Atom - */ - protected SlideAtom(byte[] source, int start, int len) { - // Sanity Checking - if(len < 30) { len = 30; } - - // Get the header - _header = new byte[8]; - System.arraycopy(source,start,_header,0,8); - - // Grab the 12 bytes that is "SSlideLayoutAtom" - byte[] SSlideLayoutAtomData = new byte[12]; - System.arraycopy(source,start+8,SSlideLayoutAtomData,0,12); - // Use them to build up the SSlideLayoutAtom - layoutAtom = new SlideAtomLayout(SSlideLayoutAtomData); - - // Get the IDs of the master and notes - masterID = LittleEndian.getInt(source,start+12+8); - notesID = LittleEndian.getInt(source,start+16+8); - - // Grok the flags, stored as bits - int flags = LittleEndian.getUShort(source,start+20+8); - if((flags&4) == 4) { - followMasterBackground = true; - } else { - followMasterBackground = false; - } - if((flags&2) == 2) { - followMasterScheme = true; - } else { - followMasterScheme = false; - } - if((flags&1) == 1) { - followMasterObjects = true; - } else { - followMasterObjects = false; - } - - // If there's any other bits of data, keep them about - // 8 bytes header + 20 bytes to flags + 2 bytes flags = 30 bytes - reserved = new byte[len-30]; - System.arraycopy(source,start+30,reserved,0,reserved.length); - } - - /** - * Create a new SlideAtom, to go with a new Slide - */ - public SlideAtom(){ - _header = new byte[8]; - LittleEndian.putUShort(_header, 0, 2); - LittleEndian.putUShort(_header, 2, (int)_type); - LittleEndian.putInt(_header, 4, 24); - - byte[] ssdate = new byte[12]; - layoutAtom = new SlideAtomLayout(ssdate); - layoutAtom.setGeometryType(SlideLayoutType.BLANK_SLIDE); - - followMasterObjects = true; - followMasterScheme = true; - followMasterBackground = true; - masterID = USES_MASTER_SLIDE_ID; // -2147483648; - notesID = 0; - reserved = new byte[2]; - } - - /** - * We are of type 1007 - */ - @Override - public long getRecordType() { return _type; } - - /** - * Write the contents of the record back, so it can be written - * to disk - */ - @Override - public void writeOut(OutputStream out) throws IOException { - // Header - out.write(_header); - - // SSSlideLayoutAtom stuff - layoutAtom.writeOut(out); - - // IDs - writeLittleEndian(masterID,out); - writeLittleEndian(notesID,out); - - // Flags - short flags = 0; - if(followMasterObjects) { flags += 1; } - if(followMasterScheme) { flags += 2; } - if(followMasterBackground) { flags += 4; } - writeLittleEndian(flags,out); - - // Reserved data - out.write(reserved); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/SlideAtomLayout.java b/src/scratchpad/src/org/apache/poi/hslf/record/SlideAtomLayout.java deleted file mode 100644 index c6bd79575..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/SlideAtomLayout.java +++ /dev/null @@ -1,133 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import java.io.IOException; -import java.io.OutputStream; - -import org.apache.poi.hslf.exceptions.HSLFException; -import org.apache.poi.util.Internal; -import org.apache.poi.util.LittleEndian; - -/** - * Holds the geometry of the Slide, and the ID of the placeholders on the slide. - * Embedded inside a SlideAtom is a SlideAtomLayout, without the usual record header. - * Since it's a fixed size and tied to the SlideAtom, we'll hold it here.

    - * - * This might eventually merged with the XSLF counterpart - */ -@Internal -public class SlideAtomLayout { - // The different kinds of geometry - public enum SlideLayoutType { - /** One title and one subtitle placeholder shapes. */ - TITLE_SLIDE(0x0000), - /** Presentation slide or main master slide layout with one title and one body placeholder shape. */ - TITLE_BODY(0x0001), - /** Title master slide layout with one title and one subtitle placeholder shape. */ - MASTER_TITLE(0x0002), - /** ??? (not documented in spec) */ - MASTER_SLIDE(0x0003), - /** ??? (not documented in spec) */ - MASTER_NOTES(0x0004), - /** ??? (not documented in spec) */ - NOTES_TITLE_BODY(0x0005), - /** Only header, footer and date placeholders */ - HANDOUT(0x0006), - /** Presentation slide layout with one title placeholder shape. */ - TITLE_ONLY(0x0007), - /** Presentation slide layout with one title and two body placeholder shapes stacked horizontally. */ - TWO_COLUMNS(0x0008), - /** Presentation slide layout with one title and two body placeholder shapes stacked vertically. */ - TWO_ROWS(0x0009), - /** Presentation slide layout with one title and three body placeholder shapes split into two columns. The right column has two rows. */ - COLUMN_TWO_ROWS(0x000A), - /** Presentation slide layout with one title and three body placeholder shapes split into two columns. The left column has two rows. */ - TWO_ROWS_COLUMN(0x000B), - /** ??? (not documented in spec) */ - TITLE_2_ROW_BOTTOM_2_COLUMN_BODY(0x000C), - /** Presentation slide layout with one title and three body placeholder shapes split into two rows. The top row has two columns. */ - TWO_COLUMNS_ROW(0x000D), - /** Presentation slide layout with one title and four body placeholder shapes. */ - FOUR_OBJECTS(0x000E), - /** Presentation slide layout with one body placeholder shape. */ - BIG_OBJECT(0x000F), - /** Presentation slide layout with no placeholder shape. */ - BLANK_SLIDE(0x0010), - /** Presentation slide layout with a vertical title placeholder shape on the right and a body placeholder shape on the left. */ - VERTICAL_TITLE_BODY(0x0011), - /** Presentation slide layout with a vertical title placeholder shape on the right and two body placeholder shapes in two columns on the left. */ - VERTICAL_TWO_ROWS(0x0012); - - private int nativeId; - SlideLayoutType(int nativeId) { - this.nativeId = nativeId; - } - - public int getNativeId() { - return nativeId; - } - - public static SlideLayoutType forNativeID(int nativeId) { - for (SlideLayoutType ans : values()) { - if (ans.nativeId == nativeId) { - return ans; - } - } - return null; - } - } - - /** What geometry type we are */ - private SlideLayoutType geometry; - /** What placeholder IDs we have */ - private byte[] placeholderIDs; - - /** Retrieve the geometry type */ - public SlideLayoutType getGeometryType() { return geometry; } - /** Set the geometry type */ - public void setGeometryType(SlideLayoutType geom) { geometry = geom; } - - /** - * Create a new Embedded SSlideLayoutAtom, from 12 bytes of data - */ - public SlideAtomLayout(byte[] data) { - if(data.length != 12) { - throw new HSLFException("SSlideLayoutAtom created with byte array not 12 bytes long - was " + data.length + " bytes in size"); - } - - // Grab out our data - geometry = SlideLayoutType.forNativeID(LittleEndian.getInt(data,0)); - placeholderIDs = new byte[8]; - System.arraycopy(data,4,placeholderIDs,0,8); - } - - /** - * Write the contents of the record back, so it can be written - * to disk. Skips the record header - */ - public void writeOut(OutputStream out) throws IOException { - // Write the geometry - byte[] buf = new byte[4]; - LittleEndian.putInt(buf, 0, geometry.getNativeId()); - out.write(buf); - // Write the placeholder IDs - out.write(placeholderIDs); - } - -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/SlideListWithText.java b/src/scratchpad/src/org/apache/poi/hslf/record/SlideListWithText.java deleted file mode 100644 index deeee6fe6..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/SlideListWithText.java +++ /dev/null @@ -1,202 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import java.io.IOException; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.util.LittleEndian; - -/** - * These are tricky beasts. They contain the text of potentially - * many (normal) slides. They are made up of several sets of - * - SlidePersistAtom - * - TextHeaderAtom - * - TextBytesAtom / TextCharsAtom - * - StyleTextPropAtom (optional) - * - TextSpecInfoAtom (optional) - * - InteractiveInfo (optional) - * - TxInteractiveInfoAtom (optional) - * and then the next SlidePersistAtom. - * - * Eventually, Slides will find the blocks that interest them from all - * the SlideListWithText entries, and refere to them - * - * For now, we scan through looking for interesting bits, then creating - * the helpful Sheet from model for them - * - * @author Nick Burch - */ - -// For now, pretend to be an atom -public final class SlideListWithText extends RecordContainer { - - /** - * Instance filed of the record header indicates that this SlideListWithText stores - * references to slides - */ - public static final int SLIDES = 0; - /** - * Instance filed of the record header indicates that this SlideListWithText stores - * references to master slides - */ - public static final int MASTER = 1; - /** - * Instance filed of the record header indicates that this SlideListWithText stores - * references to notes - */ - public static final int NOTES = 2; - - private byte[] _header; - private static long _type = 4080; - - private SlideAtomsSet[] slideAtomsSets; - - /** - * Create a new holder for slide records - */ - protected SlideListWithText(byte[] source, int start, int len) { - // Grab the header - _header = new byte[8]; - System.arraycopy(source,start,_header,0,8); - - // Find our children - _children = Record.findChildRecords(source,start+8,len-8); - - // Group our children together into SlideAtomsSets - // That way, model layer code can just grab the sets to use, - // without having to try to match the children together - List sets = new ArrayList(); - for(int i=0; i<_children.length; i++) { - if(_children[i] instanceof SlidePersistAtom) { - // Find where the next SlidePersistAtom is - int endPos = i+1; - while(endPos < _children.length && !(_children[endPos] instanceof SlidePersistAtom)) { - endPos += 1; - } - - int clen = endPos - i - 1; - - // Create a SlideAtomsSets, not caring if they're empty - //if(emptySet) { continue; } - Record[] spaChildren = new Record[clen]; - System.arraycopy(_children,i+1,spaChildren,0,clen); - SlideAtomsSet set = new SlideAtomsSet((SlidePersistAtom)_children[i],spaChildren); - sets.add(set); - - // Wind on - i += clen; - } - } - - // Turn the list into an array - slideAtomsSets = sets.toArray( new SlideAtomsSet[sets.size()] ); - } - - /** - * Create a new, empty, SlideListWithText - */ - public SlideListWithText(){ - _header = new byte[8]; - LittleEndian.putUShort(_header, 0, 15); - LittleEndian.putUShort(_header, 2, (int)_type); - LittleEndian.putInt(_header, 4, 0); - - // We have no children to start with - _children = new Record[0]; - slideAtomsSets = new SlideAtomsSet[0]; - } - - /** - * Add a new SlidePersistAtom, to the end of the current list, - * and update the internal list of SlidePersistAtoms - * @param spa - */ - public void addSlidePersistAtom(SlidePersistAtom spa) { - // Add the new SlidePersistAtom at the end - appendChildRecord(spa); - - SlideAtomsSet newSAS = new SlideAtomsSet(spa, new Record[0]); - - // Update our SlideAtomsSets with this - SlideAtomsSet[] sas = new SlideAtomsSet[slideAtomsSets.length+1]; - System.arraycopy(slideAtomsSets, 0, sas, 0, slideAtomsSets.length); - sas[sas.length-1] = newSAS; - slideAtomsSets = sas; - } - - public int getInstance(){ - return LittleEndian.getShort(_header, 0) >> 4; - } - - public void setInstance(int inst){ - LittleEndian.putShort(_header, 0, (short)((inst << 4) | 0xF)); - } - - /** - * Get access to the SlideAtomsSets of the children of this record - */ - public SlideAtomsSet[] getSlideAtomsSets() { - return slideAtomsSets; - } - - /** - * Get access to the SlideAtomsSets of the children of this record - */ - public void setSlideAtomsSets( SlideAtomsSet[] sas ) { - slideAtomsSets = sas.clone(); - } - - /** - * Return the value we were given at creation - */ - public long getRecordType() { return _type; } - - /** - * Write the contents of the record back, so it can be written - * to disk - */ - public void writeOut(OutputStream out) throws IOException { - writeOut(_header[0],_header[1],_type,_children,out); - } - - /** - * Inner class to wrap up a matching set of records that hold the - * text for a given sheet. Contains the leading SlidePersistAtom, - * and all of the records until the next SlidePersistAtom. This - * includes sets of TextHeaderAtom and TextBytesAtom/TextCharsAtom, - * along with some others. - */ - public static class SlideAtomsSet { - private SlidePersistAtom slidePersistAtom; - private Record[] slideRecords; - - /** Get the SlidePersistAtom, which gives details on the Slide this text is associated with */ - public SlidePersistAtom getSlidePersistAtom() { return slidePersistAtom; } - /** Get the Text related records for this slide */ - public Record[] getSlideRecords() { return slideRecords; } - - /** Create one to hold the Records for one Slide's text */ - public SlideAtomsSet(SlidePersistAtom s, Record[] r) { - slidePersistAtom = s; - slideRecords = r.clone(); - } - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/SlidePersistAtom.java b/src/scratchpad/src/org/apache/poi/hslf/record/SlidePersistAtom.java deleted file mode 100644 index 0ac22adf3..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/SlidePersistAtom.java +++ /dev/null @@ -1,138 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import org.apache.poi.util.LittleEndian; -import java.io.IOException; -import java.io.OutputStream; - -/** - * A SlidePersist Atom (type 1011). Holds information on the text of a - * given slide, which are stored in the same SlideListWithText - * - * @author Nick Burch - */ -public final class SlidePersistAtom extends RecordAtom { - private byte[] _header; - private static long _type = 1011l; - - /** - * Slide reference ID. Should correspond to the PersistPtr - * "sheet ID" of the matching slide/notes record - */ - private int refID; - private boolean hasShapesOtherThanPlaceholders; - /** Number of placeholder texts that will follow in the SlideListWithText */ - private int numPlaceholderTexts; - /** - * The internal identifier (256+), which is used to tie slides - * and notes together - */ - private int slideIdentifier; - /** Reserved fields. Who knows what they do */ - private byte[] reservedFields; - - public int getRefID() { return refID; } - public int getSlideIdentifier() { return slideIdentifier; } - public int getNumPlaceholderTexts() { return numPlaceholderTexts; } - public boolean getHasShapesOtherThanPlaceholders() { return hasShapesOtherThanPlaceholders; } - - // Only set these if you know what you're doing! - public void setRefID(int id) { - refID = id; - } - public void setSlideIdentifier(int id) { - slideIdentifier = id; - } - - /* *************** record code follows ********************** */ - - /** - * For the SlidePersist Atom - */ - protected SlidePersistAtom(byte[] source, int start, int len) { - // Sanity Checking - if(len < 8) { len = 8; } - - // Get the header - _header = new byte[8]; - System.arraycopy(source,start,_header,0,8); - - // Grab the reference ID - refID = LittleEndian.getInt(source,start+8); - - // Next up is a set of flags, but only bit 3 is used! - int flags = LittleEndian.getInt(source,start+12); - if(flags == 4) { - hasShapesOtherThanPlaceholders = true; - } else { - hasShapesOtherThanPlaceholders = false; - } - - // Now the number of Placeholder Texts - numPlaceholderTexts = LittleEndian.getInt(source,start+16); - - // Last useful one is the unique slide identifier - slideIdentifier = LittleEndian.getInt(source,start+20); - - // Finally you have typically 4 or 8 bytes of reserved fields, - // all zero running from 24 bytes in to the end - reservedFields = new byte[len-24]; - System.arraycopy(source,start+24,reservedFields,0,reservedFields.length); - } - - /** - * Create a new SlidePersistAtom, for use with a new Slide - */ - public SlidePersistAtom(){ - _header = new byte[8]; - LittleEndian.putUShort(_header, 0, 0); - LittleEndian.putUShort(_header, 2, (int)_type); - LittleEndian.putInt(_header, 4, 20); - - hasShapesOtherThanPlaceholders = true; - reservedFields = new byte[4]; - } - - /** - * We are of type 1011 - */ - public long getRecordType() { return _type; } - - /** - * Write the contents of the record back, so it can be written - * to disk - */ - public void writeOut(OutputStream out) throws IOException { - // Header - size or type unchanged - out.write(_header); - - // Compute the flags part - only bit 3 is used - int flags = 0; - if(hasShapesOtherThanPlaceholders) { - flags = 4; - } - - // Write out our fields - writeLittleEndian(refID,out); - writeLittleEndian(flags,out); - writeLittleEndian(numPlaceholderTexts,out); - writeLittleEndian(slideIdentifier,out); - out.write(reservedFields); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/Sound.java b/src/scratchpad/src/org/apache/poi/hslf/record/Sound.java deleted file mode 100644 index f454e4d20..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/Sound.java +++ /dev/null @@ -1,137 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import org.apache.poi.util.POILogger; - -import java.io.OutputStream; -import java.io.IOException; - -/** - * A container holding information about a sound. It contains: - *

    - *

  • 1. CString (4026), Instance 0: Name of sound (e.g. "crash") - *
  • 2. CString (4026), Instance 1: Type of sound (e.g. ".wav") - *
  • 3. CString (4026), Instance 2: Reference id of sound in sound collection - *
  • 4. CString (4026), Instance 3, optional: Built-in id of sound, for sounds we ship. This is the id that?s in the reg file. - *
  • 5. SoundData (2023), optional - *

    - * - * @author Yegor Kozlov - */ -public final class Sound extends RecordContainer { - /** - * Record header data. - */ - private byte[] _header; - - // Links to our more interesting children - private CString _name; - private CString _type; - private SoundData _data; - - - /** - * Set things up, and find our more interesting children - * - * @param source the source data as a byte array. - * @param start the start offset into the byte array. - * @param len the length of the slice in the byte array. - */ - protected Sound(byte[] source, int start, int len) { - // Grab the header - _header = new byte[8]; - System.arraycopy(source,start,_header,0,8); - - // Find our children - _children = Record.findChildRecords(source,start+8,len-8); - findInterestingChildren(); - } - - private void findInterestingChildren() { - // First child should be the ExHyperlinkAtom - if(_children[0] instanceof CString) { - _name = (CString)_children[0]; - } else { - logger.log(POILogger.ERROR, "First child record wasn't a CString, was of type " + _children[0].getRecordType()); - } - - // Second child should be the ExOleObjAtom - if (_children[1] instanceof CString) { - _type = (CString)_children[1]; - } else { - logger.log(POILogger.ERROR, "Second child record wasn't a CString, was of type " + _children[1].getRecordType()); - } - - for (int i = 2; i < _children.length; i++) { - if(_children[i] instanceof SoundData){ - _data = (SoundData)_children[i]; - break; - } - } - - } - - /** - * Returns the type (held as a little endian in bytes 3 and 4) - * that this class handles. - * - * @return the record type. - */ - public long getRecordType() { - return RecordTypes.Sound.typeID; - } - - /** - * Have the contents printer out into an OutputStream, used when - * writing a file back out to disk. - * - * @param out the output stream. - * @throws java.io.IOException if there was an error writing to the stream. - */ - public void writeOut(OutputStream out) throws IOException { - writeOut(_header[0],_header[1],getRecordType(),_children,out); - } - - /** - * Name of the sound (e.g. "crash") - * - * @return name of the sound - */ - public String getSoundName(){ - return _name.getText(); - } - - /** - * Type of the sound (e.g. ".wav") - * - * @return type of the sound - */ - public String getSoundType(){ - return _type.getText(); - } - - /** - * The sound data - * - * @return the sound data. - */ - public byte[] getSoundData(){ - return _data == null ? null : _data.getData(); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/SoundCollection.java b/src/scratchpad/src/org/apache/poi/hslf/record/SoundCollection.java deleted file mode 100644 index abea3887f..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/SoundCollection.java +++ /dev/null @@ -1,72 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import java.io.OutputStream; -import java.io.IOException; - -/** - * Is a container for all sound related atoms and containers. It contains: - *
  • 1. SoundCollAtom (2021) - *
  • 2. Sound (2022), for each sound, if any - * - * @author Yegor Kozlov - */ -public final class SoundCollection extends RecordContainer { - /** - * Record header data. - */ - private byte[] _header; - - /** - * Set things up, and find our more interesting children - * - * @param source the source data as a byte array. - * @param start the start offset into the byte array. - * @param len the length of the slice in the byte array. - */ - protected SoundCollection(byte[] source, int start, int len) { - // Grab the header - _header = new byte[8]; - System.arraycopy(source,start,_header,0,8); - - // Find our children - _children = Record.findChildRecords(source,start+8,len-8); - } - - /** - * Returns the type (held as a little endian in bytes 3 and 4) - * that this class handles. - * - * @return the record type. - */ - public long getRecordType() { - return RecordTypes.SoundCollection.typeID; - } - - /** - * Have the contents printer out into an OutputStream, used when - * writing a file back out to disk. - * - * @param out the output stream. - * @throws java.io.IOException if there was an error writing to the stream. - */ - public void writeOut(OutputStream out) throws IOException { - writeOut(_header[0],_header[1],getRecordType(),_children,out); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/SoundData.java b/src/scratchpad/src/org/apache/poi/hslf/record/SoundData.java deleted file mode 100644 index 32aa9592d..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/SoundData.java +++ /dev/null @@ -1,100 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import java.io.IOException; -import java.io.OutputStream; - -import org.apache.poi.util.LittleEndian; - -/** - * Storage for embedded sounds. - * - * @author Yegor Kozlov - */ -public final class SoundData extends RecordAtom { - - /** - * Record header. - */ - private byte[] _header; - - /** - * Record data. - */ - private byte[] _data; - - /** - * Constructs a new empty sound container. - */ - protected SoundData() { - _header = new byte[8]; - _data = new byte[0]; - - LittleEndian.putShort(_header, 2, (short)getRecordType()); - LittleEndian.putInt(_header, 4, _data.length); - } - - /** - * Constructs the link related atom record from its - * source data. - * - * @param source the source data as a byte array. - * @param start the start offset into the byte array. - * @param len the length of the slice in the byte array. - */ - protected SoundData(byte[] source, int start, int len) { - // Get the header. - _header = new byte[8]; - System.arraycopy(source,start,_header,0,8); - - // Get the record data. - _data = new byte[len-8]; - System.arraycopy(source,start+8,_data,0,len-8); - } - - /** - * Returns the sound data. - * - * @return the sound data - */ - public byte[] getData() { - return _data; - } - - /** - * Gets the record type. - * - * @return the record type. - */ - public long getRecordType() { - return RecordTypes.SoundData.typeID; - } - - /** - * Write the contents of the record back, so it can be written - * to disk. - * - * @param out the output stream to write to. - * @throws java.io.IOException if an error occurs. - */ - public void writeOut(OutputStream out) throws IOException { - out.write(_header); - out.write(_data); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/StyleTextProp9Atom.java b/src/scratchpad/src/org/apache/poi/hslf/record/StyleTextProp9Atom.java deleted file mode 100644 index 9a5cc7b48..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/StyleTextProp9Atom.java +++ /dev/null @@ -1,143 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import java.io.IOException; -import java.io.OutputStream; -import java.util.LinkedList; -import java.util.List; - -import org.apache.poi.hslf.model.textproperties.TextPFException9; -import org.apache.poi.util.LittleEndian; - -/** - * The atom record that specifies additional text formatting. - */ -public final class StyleTextProp9Atom extends RecordAtom { - private final TextPFException9[] autoNumberSchemes; - /** Record header. */ - private byte[] header; - /** Record data. */ - private byte[] data; - private short version; - private short recordId; - private int length; - - /** - * Constructs the link related atom record from its - * source data. - * - * @param source the source data as a byte array. - * @param start the start offset into the byte array. - * @param len the length of the slice in the byte array. - */ - protected StyleTextProp9Atom(byte[] source, int start, int len) { - // Get the header. - final List schemes = new LinkedList(); - header = new byte[8]; - System.arraycopy(source,start, header,0,8); - this.version = LittleEndian.getShort(header, 0); - this.recordId = LittleEndian.getShort(header, 2); - this.length = LittleEndian.getInt(header, 4); - - // Get the record data. - data = new byte[len-8]; - System.arraycopy(source, start+8, data, 0, len-8); - for (int i = 0; i < data.length; ) { - final TextPFException9 item = new TextPFException9(data, i); - schemes.add(item); - i += item.getRecordLength(); - - if (i+4 >= data.length) { - break; - } - int textCfException9 = LittleEndian.getInt(data, i ); - i += 4; - //TODO analyze textCfException when have some test data - - if (i+4 >= data.length) { - break; - } - int textSiException = LittleEndian.getInt(data, i ); - i += 4;//TextCFException9 + SIException - - if (0 != (textSiException & 0x40)) { - i += 2; //skip fBidi - } - if (i+4 >= data.length) { - break; - } - } - this.autoNumberSchemes = schemes.toArray(new TextPFException9[schemes.size()]); - } - - /** - * Gets the record type. - * @return the record type. - */ - public long getRecordType() { return this.recordId; } - - public short getVersion() { - return version; - } - - public int getLength() { - return length; - } - public TextPFException9[] getAutoNumberTypes() { - return this.autoNumberSchemes; - } - - /** - * Write the contents of the record back, so it can be written - * to disk - * - * @param out the output stream to write to. - * @throws java.io.IOException if an error occurs. - */ - public void writeOut(OutputStream out) throws IOException { - out.write(header); - out.write(data); - } - - /** - * Update the text length - * - * @param size the text length - */ - public void setTextSize(int size){ - LittleEndian.putInt(data, 0, size); - } - - /** - * Reset the content to one info run with the default values - * @param size the site of parent text - */ - public void reset(int size){ - data = new byte[10]; - // 01 00 00 00 - LittleEndian.putInt(data, 0, size); - // 01 00 00 00 - LittleEndian.putInt(data, 4, 1); //mask - // 00 00 - LittleEndian.putShort(data, 8, (short)0); //langId - - // Update the size (header bytes 5-8) - LittleEndian.putInt(header, 4, data.length); - } -} \ No newline at end of file diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/StyleTextPropAtom.java b/src/scratchpad/src/org/apache/poi/hslf/record/StyleTextPropAtom.java deleted file mode 100644 index 5291eb2fe..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/StyleTextPropAtom.java +++ /dev/null @@ -1,405 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.hslf.exceptions.HSLFException; -import org.apache.poi.hslf.model.textproperties.TextPropCollection; -import org.apache.poi.hslf.model.textproperties.TextPropCollection.TextPropType; -import org.apache.poi.util.HexDump; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.POILogger; - -/** - * A StyleTextPropAtom (type 4001). Holds basic character properties - * (bold, italic, underline, font size etc) and paragraph properties - * (alignment, line spacing etc) for the block of text (TextBytesAtom - * or TextCharsAtom) that this record follows. - * You will find two lists within this class. - * 1 - Paragraph style list (paragraphStyles) - * 2 - Character style list (charStyles) - * Both are lists of TextPropCollections. These define how many characters - * the style applies to, and what style elements make up the style (another - * list, this time of TextProps). Each TextProp has a value, which somehow - * encapsulates a property of the style - */ - -public final class StyleTextPropAtom extends RecordAtom { - public static final long _type = RecordTypes.StyleTextPropAtom.typeID; - private byte[] _header; - private byte[] reserved; - - private byte[] rawContents; // Holds the contents between write-outs - - /** - * Only set to true once setParentTextSize(int) is called. - * Until then, no stylings will have been decoded - */ - private boolean initialised = false; - - /** - * The list of all the different paragraph stylings we code for. - * Each entry is a TextPropCollection, which tells you how many - * Characters the paragraph covers, and also contains the TextProps - * that actually define the styling of the paragraph. - */ - private List paragraphStyles; - public List getParagraphStyles() { return paragraphStyles; } - /** - * Updates the link list of TextPropCollections which make up the - * paragraph stylings - */ - public void setParagraphStyles(List ps) { paragraphStyles = ps; } - /** - * The list of all the different character stylings we code for. - * Each entry is a TextPropCollection, which tells you how many - * Characters the character styling covers, and also contains the - * TextProps that actually define the styling of the characters. - */ - private List charStyles; - public List getCharacterStyles() { return charStyles; } - /** - * Updates the link list of TextPropCollections which make up the - * character stylings - */ - public void setCharacterStyles(List cs) { charStyles = cs; } - - /** - * Returns how many characters the paragraph's - * TextPropCollections cover. - * (May be one or two more than the underlying text does, - * due to having extra characters meaning something - * special to powerpoint) - */ - public int getParagraphTextLengthCovered() { - return getCharactersCovered(paragraphStyles); - } - /** - * Returns how many characters the character's - * TextPropCollections cover. - * (May be one or two more than the underlying text does, - * due to having extra characters meaning something - * special to powerpoint) - */ - public int getCharacterTextLengthCovered() { - return getCharactersCovered(charStyles); - } - private int getCharactersCovered(List styles) { - int length = 0; - for(TextPropCollection tpc : styles) { - length += tpc.getCharactersCovered(); - } - return length; - } - - /* *************** record code follows ********************** */ - - /** - * For the Text Style Properties (StyleTextProp) Atom - */ - public StyleTextPropAtom(byte[] source, int start, int len) { - // Sanity Checking - we're always at least 8+10 bytes long - if(len < 18) { - len = 18; - if(source.length - start < 18) { - throw new HSLFException("Not enough data to form a StyleTextPropAtom (min size 18 bytes long) - found " + (source.length - start)); - } - } - - // Get the header - _header = new byte[8]; - System.arraycopy(source,start,_header,0,8); - - // Save the contents of the atom, until we're asked to go and - // decode them (via a call to setParentTextSize(int) - rawContents = new byte[len-8]; - System.arraycopy(source,start+8,rawContents,0,rawContents.length); - reserved = new byte[0]; - - // Set empty lists, ready for when they call setParentTextSize - paragraphStyles = new ArrayList(); - charStyles = new ArrayList(); - } - - - /** - * A new set of text style properties for some text without any. - */ - public StyleTextPropAtom(int parentTextSize) { - _header = new byte[8]; - rawContents = new byte[0]; - reserved = new byte[0]; - - // Set our type - LittleEndian.putInt(_header,2,(short)_type); - // Our initial size is 10 - LittleEndian.putInt(_header,4,10); - - // Set empty paragraph and character styles - paragraphStyles = new ArrayList(); - charStyles = new ArrayList(); - - addParagraphTextPropCollection(parentTextSize); - addCharacterTextPropCollection(parentTextSize); - - // Set us as now initialised - initialised = true; - - try { - updateRawContents(); - } catch (IOException e) { - throw new HSLFException(e); - } - } - - - /** - * We are of type 4001 - */ - @Override - public long getRecordType() { return _type; } - - - /** - * Write the contents of the record back, so it can be written - * to disk - */ - @Override - public void writeOut(OutputStream out) throws IOException { - // First thing to do is update the raw bytes of the contents, based - // on the properties - updateRawContents(); - - // Write out the (new) header - out.write(_header); - - // Write out the styles - out.write(rawContents); - - // Write out any extra bits - out.write(reserved); - } - - - /** - * Tell us how much text the parent TextCharsAtom or TextBytesAtom - * contains, so we can go ahead and initialise ourselves. - */ - public void setParentTextSize(int size) { - if (initialised) { - return; - } - - int pos = 0; - int textHandled = 0; - - paragraphStyles.clear(); - charStyles.clear(); - - // While we have text in need of paragraph stylings, go ahead and - // grok the contents as paragraph formatting data - int prsize = size; - while(pos < rawContents.length && textHandled < prsize) { - // First up, fetch the number of characters this applies to - int textLen = LittleEndian.getInt(rawContents,pos); - textLen = checkTextLength(textLen, textHandled, size); - textHandled += textLen; - pos += 4; - - short indent = LittleEndian.getShort(rawContents,pos); - pos += 2; - - // Grab the 4 byte value that tells us what properties follow - int paraFlags = LittleEndian.getInt(rawContents,pos); - pos += 4; - - // Now make sense of those properties - TextPropCollection thisCollection = new TextPropCollection(textLen, TextPropType.paragraph); - thisCollection.setIndentLevel(indent); - int plSize = thisCollection.buildTextPropList(paraFlags, rawContents, pos); - pos += plSize; - - // Save this properties set - paragraphStyles.add(thisCollection); - - // Handle extra 1 paragraph styles at the end - if(pos < rawContents.length && textHandled == size) { - prsize++; - } - - } - if (rawContents.length > 0 && textHandled != (size+1)){ - logger.log(POILogger.WARN, "Problem reading paragraph style runs: textHandled = " + textHandled + ", text.size+1 = " + (size+1)); - } - - // Now do the character stylings - textHandled = 0; - int chsize = size; - while(pos < rawContents.length && textHandled < chsize) { - // First up, fetch the number of characters this applies to - int textLen = LittleEndian.getInt(rawContents,pos); - textLen = checkTextLength(textLen, textHandled, size); - textHandled += textLen; - pos += 4; - - // Grab the 4 byte value that tells us what properties follow - int charFlags = LittleEndian.getInt(rawContents,pos); - pos += 4; - - // Now make sense of those properties - // (Assuming we actually have some) - TextPropCollection thisCollection = new TextPropCollection(textLen, TextPropType.character); - int chSize = thisCollection.buildTextPropList(charFlags, rawContents, pos); - pos += chSize; - - // Save this properties set - charStyles.add(thisCollection); - - // Handle extra 1 char styles at the end - if(pos < rawContents.length && textHandled == size) { - chsize++; - } - } - if (rawContents.length > 0 && textHandled != (size+1)){ - logger.log(POILogger.WARN, "Problem reading character style runs: textHandled = " + textHandled + ", text.size+1 = " + (size+1)); - } - - // Handle anything left over - if(pos < rawContents.length) { - reserved = new byte[rawContents.length-pos]; - System.arraycopy(rawContents,pos,reserved,0,reserved.length); - } - - initialised = true; - } - - private int checkTextLength(int readLength, int handledSoFar, int overallSize) { - if (readLength + handledSoFar > overallSize + 1) { - logger.log(POILogger.WARN, "Style length of " + readLength + " at " + handledSoFar + - " larger than stated size of " + overallSize + ", truncating"); - return overallSize + 1 - handledSoFar; - } - return readLength; - } - - - /** - * Updates the cache of the raw contents. Serialised the styles out. - */ - private void updateRawContents() throws IOException { - if (initialised) { - // Only update the style bytes, if the styles have been potentially - // changed - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - - // First up, we need to serialise the paragraph properties - for(TextPropCollection tpc : paragraphStyles) { - tpc.writeOut(baos); - } - - // Now, we do the character ones - for(TextPropCollection tpc : charStyles) { - tpc.writeOut(baos); - } - - rawContents = baos.toByteArray(); - } - - // Now ensure that the header size is correct - int newSize = rawContents.length + reserved.length; - LittleEndian.putInt(_header,4,newSize); - } - - /** - * Clear styles, so new collections can be added - */ - public void clearStyles() { - paragraphStyles.clear(); - charStyles.clear(); - reserved = new byte[0]; - initialised = true; - } - - /** - * Create a new Paragraph TextPropCollection, and add it to the list - * @param charactersCovered The number of characters this TextPropCollection will cover - * @return the new TextPropCollection, which will then be in the list - */ - public TextPropCollection addParagraphTextPropCollection(int charactersCovered) { - TextPropCollection tpc = new TextPropCollection(charactersCovered, TextPropType.paragraph); - paragraphStyles.add(tpc); - return tpc; - } - /** - * Create a new Character TextPropCollection, and add it to the list - * @param charactersCovered The number of characters this TextPropCollection will cover - * @return the new TextPropCollection, which will then be in the list - */ - public TextPropCollection addCharacterTextPropCollection(int charactersCovered) { - TextPropCollection tpc = new TextPropCollection(charactersCovered, TextPropType.character); - charStyles.add(tpc); - return tpc; - } - - /* ************************************************************************ */ - - - /** - * Dump the record content into StringBuffer - * - * @return the string representation of the record data - */ - @Override - public String toString(){ - StringBuffer out = new StringBuffer(); - - out.append("StyleTextPropAtom:\n"); - if (!initialised) { - out.append("Uninitialised, dumping Raw Style Data\n"); - } else { - - out.append("Paragraph properties\n"); - for(TextPropCollection pr : getParagraphStyles()) { - out.append(pr); - } - - out.append("Character properties\n"); - for(TextPropCollection pr : getCharacterStyles()) { - out.append(pr); - } - - out.append("Reserved bytes\n"); - out.append( HexDump.dump(reserved, 0, 0) ); - } - - out.append(" original byte stream \n"); - - byte buf[] = new byte[rawContents.length+reserved.length]; - System.arraycopy(rawContents, 0, buf, 0, rawContents.length); - System.arraycopy(reserved, 0, buf, rawContents.length, reserved.length); - out.append( HexDump.dump(buf, 0, 0) ); - - return out.toString(); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/TextBytesAtom.java b/src/scratchpad/src/org/apache/poi/hslf/record/TextBytesAtom.java deleted file mode 100644 index 0badc3e31..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/TextBytesAtom.java +++ /dev/null @@ -1,115 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import java.io.IOException; -import java.io.OutputStream; - -import org.apache.poi.util.HexDump; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.StringUtil; - -/** - * A TextBytesAtom (type 4008). Holds text in ascii form (unknown - * code page, for now assumed to be the default of - * org.apache.poi.util.StringUtil, which is the Excel default). - * The trailing return character is always stripped from this - */ - -public final class TextBytesAtom extends RecordAtom { - public static final long _type = RecordTypes.TextBytesAtom.typeID; - private byte[] _header; - - /** The bytes that make up the text */ - private byte[] _text; - - /** Grabs the text. Uses the default codepage */ - public String getText() { - return StringUtil.getFromCompressedUnicode(_text,0,_text.length); - } - - /** Updates the text in the Atom. Must be 8 bit ascii */ - public void setText(byte[] b) { - // Set the text - _text = b.clone(); - - // Update the size (header bytes 5-8) - LittleEndian.putInt(_header,4,_text.length); - } - - /* *************** record code follows ********************** */ - - /** - * For the TextBytes Atom - */ - protected TextBytesAtom(byte[] source, int start, int len) { - // Sanity Checking - if(len < 8) { len = 8; } - - // Get the header - _header = new byte[8]; - System.arraycopy(source,start,_header,0,8); - - // Grab the text - _text = new byte[len-8]; - System.arraycopy(source,start+8,_text,0,len-8); - } - - /** - * Create an empty TextBytes Atom - */ - public TextBytesAtom() { - _header = new byte[8]; - LittleEndian.putUShort(_header, 0, 0); - LittleEndian.putUShort(_header, 2, (int)_type); - LittleEndian.putInt(_header, 4, 0); - - _text = new byte[]{}; - } - - /** - * We are of type 4008 - */ - @Override - public long getRecordType() { return _type; } - - /** - * Write the contents of the record back, so it can be written - * to disk - */ - @Override - public void writeOut(OutputStream out) throws IOException { - // Header - size or type unchanged - out.write(_header); - - // Write out our text - out.write(_text); - } - - /** - * dump debug info; use getText() to return a string - * representation of the atom - */ - @Override - public String toString() { - StringBuffer out = new StringBuffer(); - out.append( "TextBytesAtom:\n"); - out.append( HexDump.dump(_text, 0, 0) ); - return out.toString(); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/TextCharsAtom.java b/src/scratchpad/src/org/apache/poi/hslf/record/TextCharsAtom.java deleted file mode 100644 index fa8ff836d..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/TextCharsAtom.java +++ /dev/null @@ -1,111 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import java.io.IOException; -import java.io.OutputStream; - -import org.apache.poi.util.HexDump; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.StringUtil; - -/** - * A TextCharsAtom (type 4000). Holds text in byte swapped unicode form. - * The trailing return character is always stripped from this - */ - -public final class TextCharsAtom extends RecordAtom { - public static final long _type = RecordTypes.TextCharsAtom.typeID; - private byte[] _header; - - /** The bytes that make up the text */ - private byte[] _text; - - /** Grabs the text. */ - public String getText() { - return StringUtil.getFromUnicodeLE(_text); - } - - /** Updates the text in the Atom. */ - public void setText(String text) { - // Convert to little endian unicode - _text = new byte[text.length()*2]; - StringUtil.putUnicodeLE(text,_text,0); - - // Update the size (header bytes 5-8) - LittleEndian.putInt(_header,4,_text.length); - } - - /* *************** record code follows ********************** */ - - /** - * For the TextChars Atom - */ - protected TextCharsAtom(byte[] source, int start, int len) { - // Sanity Checking - if(len < 8) { len = 8; } - - // Get the header - _header = new byte[8]; - System.arraycopy(source,start,_header,0,8); - - // Grab the text - _text = new byte[len-8]; - System.arraycopy(source,start+8,_text,0,len-8); - } - /** - * Create an empty TextCharsAtom - */ - public TextCharsAtom() { - // 0 length header - _header = new byte[] { 0, 0, 0xA0-256, 0x0f, 0, 0, 0, 0 }; - // Empty text - _text = new byte[0]; - } - - /** - * We are of type 4000 - */ - @Override - public long getRecordType() { return _type; } - - /** - * Write the contents of the record back, so it can be written - * to disk - */ - @Override - public void writeOut(OutputStream out) throws IOException { - // Header - size or type unchanged - out.write(_header); - - // Write out our text - out.write(_text); - } - - /** - * dump debug info; use getText() to return a string - * representation of the atom - */ - @Override - public String toString() { - StringBuffer out = new StringBuffer(); - out.append( "TextCharsAtom:\n"); - out.append( HexDump.dump(_text, 0, 0) ); - return out.toString(); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/TextHeaderAtom.java b/src/scratchpad/src/org/apache/poi/hslf/record/TextHeaderAtom.java deleted file mode 100644 index 05c61a667..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/TextHeaderAtom.java +++ /dev/null @@ -1,121 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import java.io.IOException; -import java.io.OutputStream; - -import org.apache.poi.hslf.exceptions.HSLFException; -import org.apache.poi.util.LittleEndian; - -/** - * A TextHeaderAtom (type 3999). Holds information on what kind of - * text is contained in the TextBytesAtom / TextCharsAtom that follows - * straight after - */ - -public final class TextHeaderAtom extends RecordAtom implements ParentAwareRecord { - public static final long _type = RecordTypes.TextHeaderAtom.typeID; - private byte[] _header; - private RecordContainer parentRecord; - - public static final int TITLE_TYPE = 0; - public static final int BODY_TYPE = 1; - public static final int NOTES_TYPE = 2; - public static final int OTHER_TYPE = 4; - public static final int CENTRE_BODY_TYPE = 5; - public static final int CENTER_TITLE_TYPE = 6; - public static final int HALF_BODY_TYPE = 7; - public static final int QUARTER_BODY_TYPE = 8; - - /** The kind of text it is */ - private int textType; - /** position in the owning SlideListWithText */ - private int index = -1; - - public int getTextType() { return textType; } - public void setTextType(int type) { textType = type; } - - /** - * @return 0-based index of the text run in the SLWT container - */ - public int getIndex() { return index; } - - /** - * @param index 0-based index of the text run in the SLWT container - */ - public void setIndex(int index) { this.index = index; } - - @Override - public RecordContainer getParentRecord() { return parentRecord; } - @Override - public void setParentRecord(RecordContainer record) { this.parentRecord = record; } - - /* *************** record code follows ********************** */ - - /** - * For the TextHeader Atom - */ - protected TextHeaderAtom(byte[] source, int start, int len) { - // Sanity Checking - we're always 12 bytes long - if(len < 12) { - len = 12; - if(source.length - start < 12) { - throw new HSLFException("Not enough data to form a TextHeaderAtom (always 12 bytes long) - found " + (source.length - start)); - } - } - - // Get the header - _header = new byte[8]; - System.arraycopy(source,start,_header,0,8); - - // Grab the type - textType = LittleEndian.getInt(source,start+8); - } - - /** - * Create a new TextHeader Atom, for an unknown type of text - */ - public TextHeaderAtom() { - _header = new byte[8]; - LittleEndian.putUShort(_header, 0, 0); - LittleEndian.putUShort(_header, 2, (int)_type); - LittleEndian.putInt(_header, 4, 4); - - textType = OTHER_TYPE; - } - - /** - * We are of type 3999 - */ - @Override - public long getRecordType() { return _type; } - - /** - * Write the contents of the record back, so it can be written - * to disk - */ - @Override - public void writeOut(OutputStream out) throws IOException { - // Header - size or type unchanged - out.write(_header); - - // Write out our type - writeLittleEndian(textType,out); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/TextRulerAtom.java b/src/scratchpad/src/org/apache/poi/hslf/record/TextRulerAtom.java deleted file mode 100644 index 9b40a9893..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/TextRulerAtom.java +++ /dev/null @@ -1,204 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import java.io.IOException; -import java.io.OutputStream; - -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.POILogger; - -/** - * Ruler of a text as it differs from the style's ruler settings. - */ -public final class TextRulerAtom extends RecordAtom { - /** - * Record header. - */ - private byte[] _header; - - /** - * Record data. - */ - private byte[] _data; - - //ruler internals - private int defaultTabSize; - private int numLevels; - private int[] tabStops; - private int[] bulletOffsets = new int[5]; - private int[] textOffsets = new int[5]; - - /** - * Constructs a new empty ruler atom. - */ - public TextRulerAtom() { - _header = new byte[8]; - _data = new byte[0]; - - LittleEndian.putShort(_header, 2, (short)getRecordType()); - LittleEndian.putInt(_header, 4, _data.length); - } - - /** - * Constructs the ruler atom record from its - * source data. - * - * @param source the source data as a byte array. - * @param start the start offset into the byte array. - * @param len the length of the slice in the byte array. - */ - protected TextRulerAtom(byte[] source, int start, int len) { - // Get the header. - _header = new byte[8]; - System.arraycopy(source,start,_header,0,8); - - // Get the record data. - _data = new byte[len-8]; - System.arraycopy(source,start+8,_data,0,len-8); - - try { - read(); - } catch (Exception e){ - logger.log(POILogger.ERROR, "Failed to parse TextRulerAtom: " + e.getMessage()); - } - } - - /** - * Gets the record type. - * - * @return the record type. - */ - public long getRecordType() { - return RecordTypes.TextRulerAtom.typeID; - } - - /** - * Write the contents of the record back, so it can be written - * to disk. - * - * @param out the output stream to write to. - * @throws java.io.IOException if an error occurs. - */ - public void writeOut(OutputStream out) throws IOException { - out.write(_header); - out.write(_data); - } - - /** - * Read the record bytes and initialize the internal variables - */ - private void read(){ - int pos = 0; - short mask = LittleEndian.getShort(_data); pos += 4; - short val; - int[] bits = {1, 0, 2, 3, 8, 4, 9, 5, 10, 6, 11, 7, 12}; - for (int i = 0; i < bits.length; i++) { - if((mask & 1 << bits[i]) != 0){ - switch (bits[i]){ - case 0: - //defaultTabSize - defaultTabSize = LittleEndian.getShort(_data, pos); pos += 2; - break; - case 1: - //numLevels - numLevels = LittleEndian.getShort(_data, pos); pos += 2; - break; - case 2: - //tabStops - val = LittleEndian.getShort(_data, pos); pos += 2; - tabStops = new int[val*2]; - for (int j = 0; j < tabStops.length; j++) { - tabStops[j] = LittleEndian.getUShort(_data, pos); pos += 2; - } - break; - case 3: - case 4: - case 5: - case 6: - case 7: - //bullet.offset - val = LittleEndian.getShort(_data, pos); pos += 2; - bulletOffsets[bits[i]-3] = val; - break; - case 8: - case 9: - case 10: - case 11: - case 12: - //text.offset - val = LittleEndian.getShort(_data, pos); pos += 2; - textOffsets[bits[i]-8] = val; - break; - default: - break; - } - } - } - } - - /** - * Default distance between tab stops, in master coordinates (576 dpi). - */ - public int getDefaultTabSize(){ - return defaultTabSize; - } - - /** - * Number of indent levels (maximum 5). - */ - public int getNumberOfLevels(){ - return numLevels; - } - - /** - * Default distance between tab stops, in master coordinates (576 dpi). - */ - public int[] getTabStops(){ - return tabStops; - } - - /** - * Paragraph's distance from shape's left margin, in master coordinates (576 dpi). - */ - public int[] getTextOffsets(){ - return textOffsets; - } - - /** - * First line of paragraph's distance from shape's left margin, in master coordinates (576 dpi). - */ - public int[] getBulletOffsets(){ - return bulletOffsets; - } - - public static TextRulerAtom getParagraphInstance(){ - byte[] data = new byte[] { - 0x00, 0x00, (byte)0xA6, 0x0F, 0x0A, 0x00, 0x00, 0x00, - 0x10, 0x03, 0x00, 0x00, (byte)0xF9, 0x00, 0x41, 0x01, 0x41, 0x01 - }; - TextRulerAtom ruler = new TextRulerAtom(data, 0, data.length); - return ruler; - } - - public void setParagraphIndent(short tetxOffset, short bulletOffset){ - LittleEndian.putShort(_data, 4, tetxOffset); - LittleEndian.putShort(_data, 6, bulletOffset); - LittleEndian.putShort(_data, 8, bulletOffset); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/TextSpecInfoAtom.java b/src/scratchpad/src/org/apache/poi/hslf/record/TextSpecInfoAtom.java deleted file mode 100644 index 7f87086bf..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/TextSpecInfoAtom.java +++ /dev/null @@ -1,175 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.hslf.exceptions.HSLFException; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.LittleEndianByteArrayInputStream; - -/** - * The special info runs contained in this text. - * Special info runs consist of character properties which don?t follow styles. - * - * @author Yegor Kozlov - */ -public final class TextSpecInfoAtom extends RecordAtom { - private static final long _type = RecordTypes.TextSpecInfoAtom.typeID; - - /** - * Record header. - */ - private byte[] _header; - - /** - * Record data. - */ - private byte[] _data; - - /** - * Constructs an empty atom, with a default run of size 1 - */ - public TextSpecInfoAtom() { - _header = new byte[8]; - LittleEndian.putUInt(_header, 4, _type); - reset(1); - } - - /** - * Constructs the link related atom record from its - * source data. - * - * @param source the source data as a byte array. - * @param start the start offset into the byte array. - * @param len the length of the slice in the byte array. - */ - public TextSpecInfoAtom(byte[] source, int start, int len) { - // Get the header. - _header = new byte[8]; - System.arraycopy(source,start,_header,0,8); - - // Get the record data. - _data = new byte[len-8]; - System.arraycopy(source,start+8,_data,0,len-8); - - } - /** - * Gets the record type. - * @return the record type. - */ - @Override - public long getRecordType() { return _type; } - - /** - * Write the contents of the record back, so it can be written - * to disk - * - * @param out the output stream to write to. - * @throws java.io.IOException if an error occurs. - */ - @Override - public void writeOut(OutputStream out) throws IOException { - out.write(_header); - out.write(_data); - } - - /** - * Update the text length - * - * @param size the text length - */ - public void setTextSize(int size){ - LittleEndian.putInt(_data, 0, size); - } - - /** - * Reset the content to one info run with the default values - * @param size the site of parent text - */ - public void reset(int size){ - TextSpecInfoRun sir = new TextSpecInfoRun(size); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - try { - sir.writeOut(bos); - } catch (IOException e) { - throw new HSLFException(e); - } - _data = bos.toByteArray(); - - // Update the size (header bytes 5-8) - LittleEndian.putInt(_header, 4, _data.length); - } - - /** - * Adapts the size by enlarging the last {@link TextSpecInfoRun} - * or chopping the runs to the given length - * - * @param size - */ - public void setParentSize(int size) { - assert(size > 0); - int covered = 0; - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - TextSpecInfoRun runs[] = getTextSpecInfoRuns(); - assert(runs.length > 0); - for (int i=0; i size || i == runs.length-1) { - run.setLength(size-covered); - } - covered += run.getLength(); - try { - run.writeOut(bos); - } catch (IOException e) { - throw new HSLFException(e); - } - } - _data = bos.toByteArray(); - - // Update the size (header bytes 5-8) - LittleEndian.putInt(_header, 4, _data.length); - } - - /** - * Get the number of characters covered by this records - * - * @return the number of characters covered by this records - */ - public int getCharactersCovered(){ - int covered = 0; - for (TextSpecInfoRun r : getTextSpecInfoRuns()) { - covered += r.getLength(); - } - return covered; - } - - public TextSpecInfoRun[] getTextSpecInfoRuns(){ - LittleEndianByteArrayInputStream bis = new LittleEndianByteArrayInputStream(_data); // NOSONAR - List lst = new ArrayList(); - while (bis.available() > 0) { - lst.add(new TextSpecInfoRun(bis)); - } - return lst.toArray(new TextSpecInfoRun[lst.size()]); - } - -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/TextSpecInfoRun.java b/src/scratchpad/src/org/apache/poi/hslf/record/TextSpecInfoRun.java deleted file mode 100644 index c76699abd..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/TextSpecInfoRun.java +++ /dev/null @@ -1,346 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import java.io.IOException; -import java.io.OutputStream; - -import org.apache.poi.util.*; - -public class TextSpecInfoRun { - /** - * A enum that specifies the spelling status of a run of text. - */ - public enum SpellInfoEnum { - /** the text is spelled incorrectly. */ - error(new BitField(1)), - /** the text needs rechecking. */ - clean(new BitField(2)), - /** the text has a grammar error. */ - grammar(new BitField(4)), - /** the text is spelled correct */ - correct(new BitField(0)); - - final BitField bitField; - - SpellInfoEnum(BitField bitField) { - this.bitField = bitField; - } - } - - /** A bit that specifies whether the spellInfo field exists. */ - private static final BitField spellFld = new BitField(0X00000001); - /** A bit that specifies whether the lid field exists. */ - private static final BitField langFld = new BitField(0X00000002); - /** A bit that specifies whether the altLid field exists. */ - private static final BitField altLangFld = new BitField(0X00000004); - // unused1, unused2 - Undefined and MUST be ignored. - /** A bit that specifies whether the pp10runid, reserved3, and grammarError fields exist. */ - private static final BitField pp10extFld = new BitField(0X00000020); - /** A bit that specifies whether the bidi field exists. */ - private static final BitField bidiFld = new BitField(0X00000040); - // unused3 - Undefined and MUST be ignored. - // reserved1 - MUST be zero and MUST be ignored. - /** A bit that specifies whether the smartTags field exists. */ - private static final BitField smartTagFld = new BitField(0X00000200); - // reserved2 - MUST be zero and MUST be ignored. - - /** - * An optional unsigned integer that specifies an identifier for a character - * run that contains StyleTextProp11 data. It MUST exist if and only if pp10ext is TRUE. - **/ - private static final BitField pp10runidFld = new BitField(0X0000000F); - // reserved3 - An optional unsigned integer that MUST be zero, and MUST be ignored. It - // MUST exist if and only if fPp10ext is TRUE. - /** - * An optional bit that specifies a grammar error. It MUST exist if and - * only if fPp10ext is TRUE. - **/ - private static final BitField grammarErrorFld = new BitField(0X80000000); - - //Length of special info run. - private int length; - - //Special info mask of this run; - private int mask; - - // info fields as indicated by the mask. - // -1 means the bit is not set - - /** - * An optional SpellingFlags structure that specifies the spelling status of this - * text. It MUST exist if and only if spell is TRUE. - * The spellInfo.grammar sub-field MUST be zero. - *
    - * error (1 bit): A bit that specifies whether the text is spelled incorrectly.
    - * clean (1 bit): A bit that specifies whether the text needs rechecking.
    - * grammar (1 bit): A bit that specifies whether the text has a grammar error.
    - * reserved (13 bits): MUST be zero and MUST be ignored. - */ - private short spellInfo = -1; - - /** - * An optional TxLCID that specifies the language identifier of this text. - * It MUST exist if and only if lang is TRUE. - *
    - * 0x0000 = No language.
    - * 0x0013 = Any Dutch language is preferred over non-Dutch languages when proofing the text.
    - * 0x0400 = No proofing is performed on the text.
    - * > 0x0400 = A valid LCID as specified by [MS-LCID]. - */ - private short langId = -1; - - /** - * An optional TxLCID that specifies the alternate language identifier of this text. - * It MUST exist if and only if altLang is TRUE. - */ - private short altLangId = -1; - - /** - * An optional signed integer that specifies whether the text contains bidirectional - * characters. It MUST exist if and only if fBidi is TRUE. - * 0x0000 = Contains no bidirectional characters, - * 0x0001 = Contains bidirectional characters. - */ - private short bidi = -1; - - private int pp10extMask = -1; - private byte[] smartTagsBytes = null; - - /** - * Inits a TextSpecInfoRun with default values - * - * @param len the length of the one and only run - */ - public TextSpecInfoRun(int len) { - setLength(len); - setLangId((short)0); - } - - public TextSpecInfoRun(LittleEndianByteArrayInputStream source) { - length = source.readInt(); - mask = source.readInt(); - if (spellFld.isSet(mask)) { - spellInfo = source.readShort(); - } - if (langFld.isSet(mask)) { - langId = source.readShort(); - } - if (altLangFld.isSet(mask)) { - altLangId = source.readShort(); - } - if (bidiFld.isSet(mask)) { - bidi = source.readShort(); - } - if (pp10extFld.isSet(mask)) { - pp10extMask = source.readInt(); - } - if (smartTagFld.isSet(mask)) { - // An unsigned integer specifies the count of items in rgSmartTagIndex. - int count = source.readInt(); - smartTagsBytes = new byte[4+count*4]; - LittleEndian.putInt(smartTagsBytes, 0, count); - // An array of SmartTagIndex that specifies the indices. - // The count of items in the array is specified by count. - source.readFully(smartTagsBytes, 4, count*4); - } - } - - /** - * Write the contents of the record back, so it can be written - * to disk - * - * @param out the output stream to write to. - * @throws java.io.IOException if an error occurs. - */ - public void writeOut(OutputStream out) throws IOException { - final byte buf[] = new byte[4]; - LittleEndian.putInt(buf, 0, length); - out.write(buf); - LittleEndian.putInt(buf, 0, mask); - out.write(buf); - Object flds[] = { - spellFld, spellInfo, "spell info", - langFld, langId, "lang id", - altLangFld, altLangId, "alt lang id", - bidiFld, bidi, "bidi", - pp10extFld, pp10extMask, "pp10 extension field", - smartTagFld, smartTagsBytes, "smart tags" - }; - - for (int i=0; i 0; - out.write(bufB); - } else if (valO instanceof Integer) { - int valI = ((Integer)valO); - valid = (valI != -1); - LittleEndian.putInt(buf, 0, valI); - out.write(buf); - } else if (valO instanceof Short) { - short valS = ((Short)valO); - valid = (valS != -1); - LittleEndian.putShort(buf, 0, valS); - out.write(buf, 0, 2); - } else { - valid = false; - } - if (!valid) { - throw new IOException(flds[i+2]+" is activated, but its value is invalid"); - } - } - } - - /** - * @return Spelling status of this text. null if not defined. - */ - public SpellInfoEnum getSpellInfo(){ - if (spellInfo == -1) return null; - for (SpellInfoEnum si : new SpellInfoEnum[]{SpellInfoEnum.clean,SpellInfoEnum.error,SpellInfoEnum.grammar}) { - if (si.bitField.isSet(spellInfo)) return si; - } - return SpellInfoEnum.correct; - } - - /** - * @param spellInfo Spelling status of this text. null if not defined. - */ - public void setSpellInfo(SpellInfoEnum spellInfo) { - this.spellInfo = (spellInfo == null) - ? -1 - : (short)spellInfo.bitField.set(0); - mask = spellFld.setBoolean(mask, spellInfo != null); - } - - /** - * Windows LANGID for this text. - * - * @return Windows LANGID for this text, -1 if it's not set - */ - public short getLangId(){ - return langId; - } - - /** - * @param langId Windows LANGID for this text, -1 to unset - */ - public void setLangId(short langId) { - this.langId = langId; - mask = langFld.setBoolean(mask, langId != -1); - } - - /** - * Alternate Windows LANGID of this text; - * must be a valid non-East Asian LANGID if the text has an East Asian language, - * otherwise may be an East Asian LANGID or language neutral (zero). - * - * @return Alternate Windows LANGID of this text, -1 if it's not set - */ - public short getAltLangId(){ - return altLangId; - } - - public void setAltLangId(short altLangId) { - this.altLangId = altLangId; - mask = altLangFld.setBoolean(mask, altLangId != -1); - } - - /** - * @return Length of special info run. - */ - public int getLength() { - return length; - } - - /** - * @param length Length of special info run. - */ - public void setLength(int length) { - this.length = length; - } - - /** - * @return the bidirectional characters flag. false = not bidi, true = is bidi, null = not set - */ - public Boolean getBidi() { - return (bidi == -1 ? null : bidi != 0); - } - - /** - * @param bidi the bidirectional characters flag. false = not bidi, true = is bidi, null = not set - */ - public void setBidi(Boolean bidi) { - this.bidi = (bidi == null) ? -1 : (short)(bidi ? 1 : 0); - mask = bidiFld.setBoolean(mask, bidi != null); - } - - /** - * @return the unparsed smart tags - */ - public byte[] getSmartTagsBytes() { - return smartTagsBytes; - } - - /** - * @param smartTagsBytes the unparsed smart tags, null to unset - */ - public void setSmartTagsBytes(byte[] smartTagsBytes) { - this.smartTagsBytes = (smartTagsBytes == null) ? null : smartTagsBytes.clone(); - mask = smartTagFld.setBoolean(mask, smartTagsBytes != null); - } - - /** - * @return an identifier for a character run that contains StyleTextProp11 data. - */ - public int getPP10RunId() { - return (pp10extMask == -1 || !pp10extFld.isSet(mask)) ? -1 : pp10runidFld.getValue(pp10extMask); - - } - - /** - * @param pp10RunId an identifier for a character run that contains StyleTextProp11 data, -1 to unset - */ - public void setPP10RunId(int pp10RunId) { - if (pp10RunId == -1) { - pp10extMask = (getGrammarError() == null) ? -1 : pp10runidFld.clear(pp10extMask); - } else { - pp10extMask = pp10runidFld.setValue(pp10extMask, pp10RunId); - } - // if both parameters are invalid, remove the extension mask - mask = pp10extFld.setBoolean(mask, pp10extMask != -1); - } - - public Boolean getGrammarError() { - return (pp10extMask == -1 || !pp10extFld.isSet(mask)) ? null : grammarErrorFld.isSet(pp10extMask); - } - - public void getGrammarError(Boolean grammarError) { - if (grammarError == null) { - pp10extMask = (getPP10RunId() == -1) ? -1 : grammarErrorFld.clear(pp10extMask); - } else { - pp10extMask = grammarErrorFld.set(pp10extMask); - } - // if both parameters are invalid, remove the extension mask - mask = pp10extFld.setBoolean(mask, pp10extMask != -1); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/TxInteractiveInfoAtom.java b/src/scratchpad/src/org/apache/poi/hslf/record/TxInteractiveInfoAtom.java deleted file mode 100644 index eb9dd8e0c..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/TxInteractiveInfoAtom.java +++ /dev/null @@ -1,123 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import org.apache.poi.util.LittleEndian; - -import java.io.OutputStream; -import java.io.IOException; - -/** - * Tne atom that holds starting and ending character positions of a hyperlink - * - * @author Yegor Kozlov - */ -public final class TxInteractiveInfoAtom extends RecordAtom { - /** - * Record header. - */ - private byte[] _header; - - /** - * Record data. - */ - private byte[] _data; - - /** - * Constructs a brand new link related atom record. - */ - public TxInteractiveInfoAtom() { - _header = new byte[8]; - _data = new byte[8]; - - LittleEndian.putShort(_header, 2, (short)getRecordType()); - LittleEndian.putInt(_header, 4, _data.length); - } - - /** - * Constructs the link related atom record from its - * source data. - * - * @param source the source data as a byte array. - * @param start the start offset into the byte array. - * @param len the length of the slice in the byte array. - */ - protected TxInteractiveInfoAtom(byte[] source, int start, int len) { - // Get the header. - _header = new byte[8]; - System.arraycopy(source,start,_header,0,8); - - // Get the record data. - _data = new byte[len-8]; - System.arraycopy(source,start+8,_data,0,len-8); - - } - - /** - * Gets the beginning character position - * - * @return the beginning character position - */ - public int getStartIndex() { - return LittleEndian.getInt(_data, 0); - } - - /** - * Sets the beginning character position - * @param idx the beginning character position - */ - public void setStartIndex(int idx) { - LittleEndian.putInt(_data, 0, idx); - } - - /** - * Gets the ending character position - * - * @return the ending character position - */ - public int getEndIndex() { - return LittleEndian.getInt(_data, 4); - } - - /** - * Sets the ending character position - * - * @param idx the ending character position - */ - public void setEndIndex(int idx) { - LittleEndian.putInt(_data, 4, idx); - } - - /** - * Gets the record type. - * @return the record type. - */ - public long getRecordType() { return RecordTypes.TxInteractiveInfoAtom.typeID; } - - /** - * Write the contents of the record back, so it can be written - * to disk - * - * @param out the output stream to write to. - * @throws java.io.IOException if an error occurs. - */ - public void writeOut(OutputStream out) throws IOException { - out.write(_header); - out.write(_data); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/TxMasterStyleAtom.java b/src/scratchpad/src/org/apache/poi/hslf/record/TxMasterStyleAtom.java deleted file mode 100644 index b4b8e8004..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/TxMasterStyleAtom.java +++ /dev/null @@ -1,213 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.hslf.exceptions.HSLFException; -import org.apache.poi.hslf.model.textproperties.TextPropCollection; -import org.apache.poi.hslf.model.textproperties.TextPropCollection.TextPropType; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.LittleEndianOutputStream; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; - -/** - * TxMasterStyleAtom atom (4003). - *

    - * Stores default character and paragraph styles. - * The atom instance value is the text type and is encoded like the txstyle field in - * TextHeaderAtom. The text styles are located in the MainMaster container, - * except for the "other" style, which is in the Document.Environment container. - *

    - *

    - * This atom can store up to 5 pairs of paragraph+character styles, - * each pair describes an indent level. The first pair describes - * first-level paragraph with no indentation. - *

    - * - * @author Yegor Kozlov - */ -public final class TxMasterStyleAtom extends RecordAtom { - private static final POILogger LOG = POILogFactory.getLogger(TxMasterStyleAtom.class); - - /** - * Maximum number of indentation levels allowed in PowerPoint documents - */ - public static final int MAX_INDENT = 5; - - private byte[] _header; - private static long _type = 4003; - private byte[] _data; - - private List paragraphStyles; - private List charStyles; - - protected TxMasterStyleAtom(byte[] source, int start, int len) { - _header = new byte[8]; - System.arraycopy(source,start,_header,0,8); - - _data = new byte[len-8]; - System.arraycopy(source,start+8,_data,0,_data.length); - - //read available styles - try { - init(); - } catch (Exception e){ - LOG.log(POILogger.WARN, "Exception when reading available styles", e); - } - } - - /** - * We are of type 4003 - * - * @return type of this record - * @see RecordTypes#TxMasterStyleAtom - */ - public long getRecordType() { - return _type; - } - - /** - * Write the contents of the record back, so it can be written - * to disk - */ - public void writeOut(OutputStream out) throws IOException { - // Write out the (new) header - out.write(_header); - - // Write out the record data - out.write(_data); - - } - - /** - * Returns array of character styles defined in this record. - * - * @return character styles defined in this record - */ - public List getCharacterStyles(){ - return charStyles; - } - - /** - * Returns array of paragraph styles defined in this record. - * - * @return paragraph styles defined in this record - */ - public List getParagraphStyles(){ - return paragraphStyles; - } - - /** - * Return type of the text. - * Must be a constant defined in TextHeaderAtom - * - * @return type of the text - * @see TextHeaderAtom - */ - public int getTextType(){ - //The atom instance value is the text type - return LittleEndian.getShort(_header, 0) >> 4; - } - - /** - * parse the record data and initialize styles - */ - protected void init(){ - //type of the text - int type = getTextType(); - - int head; - int pos = 0; - - //number of indentation levels - short levels = LittleEndian.getShort(_data, 0); - pos += LittleEndian.SHORT_SIZE; - - paragraphStyles = new ArrayList(levels); - charStyles = new ArrayList(levels); - - for(short i = 0; i < levels; i++) { - TextPropCollection prprops = new TextPropCollection(0, TextPropType.paragraph); - if (type >= TextHeaderAtom.CENTRE_BODY_TYPE) { - // Fetch the 2 byte value, that is safe to ignore for some types of text - short indentLevel = LittleEndian.getShort(_data, pos); - prprops.setIndentLevel(indentLevel); - pos += LittleEndian.SHORT_SIZE; - } else { - prprops.setIndentLevel((short)-1); - } - - head = LittleEndian.getInt(_data, pos); - pos += LittleEndian.INT_SIZE; - - pos += prprops.buildTextPropList( head, _data, pos); - paragraphStyles.add(prprops); - - head = LittleEndian.getInt(_data, pos); - pos += LittleEndian.INT_SIZE; - TextPropCollection chprops = new TextPropCollection(0, TextPropType.character); - pos += chprops.buildTextPropList( head, _data, pos); - charStyles.add(chprops); - } - } - - /** - * Updates the rawdata from the modified paragraph/character styles - * - * @since POI 3.14-beta1 - */ - public void updateStyles() { - int type = getTextType(); - - try { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - LittleEndianOutputStream leos = new LittleEndianOutputStream(bos); - int levels = paragraphStyles.size(); - leos.writeShort(levels); - - TextPropCollection prdummy = new TextPropCollection(0, TextPropType.paragraph); - TextPropCollection chdummy = new TextPropCollection(0, TextPropType.character); - - for (int i=0; i= TextHeaderAtom.CENTRE_BODY_TYPE) { - leos.writeShort(prdummy.getIndentLevel()); - } - - // Indent level is not written for master styles - prdummy.setIndentLevel((short)-1); - prdummy.writeOut(bos, true); - chdummy.writeOut(bos, true); - } - - _data = bos.toByteArray(); - leos.close(); - - LittleEndian.putInt(_header, 4, _data.length); - } catch (IOException e) { - throw new HSLFException("error in updating master style properties", e); - } - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/UnknownRecordPlaceholder.java b/src/scratchpad/src/org/apache/poi/hslf/record/UnknownRecordPlaceholder.java deleted file mode 100644 index 6df2aa919..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/UnknownRecordPlaceholder.java +++ /dev/null @@ -1,63 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import org.apache.poi.util.LittleEndian; -import java.io.IOException; -import java.io.OutputStream; - -/** - * If we come across a record we don't know about, we create one of - * these. It allows us to keep track of what it contains, so we can - * write it back out to disk unchanged - * - * @author Nick Burch - */ - -public final class UnknownRecordPlaceholder extends RecordAtom -{ - private byte[] _contents; - private long _type; - - /** - * Create a new holder for a record we don't grok - */ - protected UnknownRecordPlaceholder(byte[] source, int start, int len) { - // Sanity Checking - including whole header, so treat - // length as based of 0, not 8 (including header size based) - if(len < 0) { len = 0; } - - // Treat as an atom, grab and hold everything - _contents = new byte[len]; - System.arraycopy(source,start,_contents,0,len); - _type = LittleEndian.getUShort(_contents,2); - } - - /** - * Return the value we were given at creation - */ - public long getRecordType() { return _type; } - - /** - * Write the contents of the record back, so it can be written - * to disk - */ - public void writeOut(OutputStream out) throws IOException { - out.write(_contents); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/UserEditAtom.java b/src/scratchpad/src/org/apache/poi/hslf/record/UserEditAtom.java deleted file mode 100644 index 54a0e5033..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/UserEditAtom.java +++ /dev/null @@ -1,193 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import java.io.IOException; -import java.io.OutputStream; -import java.util.Map; - -import org.apache.poi.hslf.exceptions.HSLFException; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.LittleEndianConsts; - -/** - * A UserEdit Atom (type 4085). Holds information which bits of the file - * were last used by powerpoint, the version of powerpoint last used etc. - * - * ** WARNING ** stores byte offsets from the start of the PPT stream to - * other records! If you change the size of any elements before one of - * these, you'll need to update the offsets! - * - * @author Nick Burch - */ - -public final class UserEditAtom extends PositionDependentRecordAtom -{ - public static final int LAST_VIEW_NONE = 0; - public static final int LAST_VIEW_SLIDE_VIEW = 1; - public static final int LAST_VIEW_OUTLINE_VIEW = 2; - public static final int LAST_VIEW_NOTES = 3; - - private byte[] _header; - private static long _type = 4085l; - private short unused; - - private int lastViewedSlideID; - private int pptVersion; - private int lastUserEditAtomOffset; - private int persistPointersOffset; - private int docPersistRef; - private int maxPersistWritten; - private short lastViewType; - private int encryptSessionPersistIdRef = -1; - - // Somewhat user facing getters - public int getLastViewedSlideID() { return lastViewedSlideID; } - public short getLastViewType() { return lastViewType; } - - // Scary internal getters - public int getLastUserEditAtomOffset() { return lastUserEditAtomOffset; } - public int getPersistPointersOffset() { return persistPointersOffset; } - public int getDocPersistRef() { return docPersistRef; } - public int getMaxPersistWritten() { return maxPersistWritten; } - public int getEncryptSessionPersistIdRef() { return encryptSessionPersistIdRef; } - - // More scary internal setters - public void setLastUserEditAtomOffset(int offset) { lastUserEditAtomOffset = offset; } - public void setPersistPointersOffset(int offset) { persistPointersOffset = offset; } - public void setLastViewType(short type) { lastViewType=type; } - public void setMaxPersistWritten(int max) { maxPersistWritten=max; } - public void setEncryptSessionPersistIdRef(int id) { - encryptSessionPersistIdRef=id; - LittleEndian.putInt(_header,4,(id == -1 ? 28 : 32)); - } - - /* *************** record code follows ********************** */ - - /** - * For the UserEdit Atom - */ - protected UserEditAtom(byte[] source, int start, int len) { - // Sanity Checking - if(len < 34) { len = 34; } - - int offset = start; - // Get the header - _header = new byte[8]; - System.arraycopy(source,offset,_header,0,8); - offset += 8; - - // Get the last viewed slide ID - lastViewedSlideID = LittleEndian.getInt(source,offset); - offset += LittleEndianConsts.INT_SIZE; - - // Get the PPT version - pptVersion = LittleEndian.getInt(source,offset); - offset += LittleEndianConsts.INT_SIZE; - - // Get the offset to the previous incremental save's UserEditAtom - // This will be the byte offset on disk where the previous one - // starts, or 0 if this is the first one - lastUserEditAtomOffset = LittleEndian.getInt(source,offset); - offset += LittleEndianConsts.INT_SIZE; - - // Get the offset to the persist pointers - // This will be the byte offset on disk where the preceding - // PersistPtrFullBlock or PersistPtrIncrementalBlock starts - persistPointersOffset = LittleEndian.getInt(source,offset); - offset += LittleEndianConsts.INT_SIZE; - - // Get the persist reference for the document persist object - // Normally seems to be 1 - docPersistRef = LittleEndian.getInt(source,offset); - offset += LittleEndianConsts.INT_SIZE; - - // Maximum number of persist objects written - maxPersistWritten = LittleEndian.getInt(source,offset); - offset += LittleEndianConsts.INT_SIZE; - - // Last view type - lastViewType = LittleEndian.getShort(source,offset); - offset += LittleEndianConsts.SHORT_SIZE; - - // unused - unused = LittleEndian.getShort(source,offset); - offset += LittleEndianConsts.SHORT_SIZE; - - // There might be a few more bytes, which are a reserved field - if (offset-start oldToNewReferencesLookup) { - // Look up the new positions of our preceding UserEditAtomOffset - if(lastUserEditAtomOffset != 0) { - Integer newLocation = oldToNewReferencesLookup.get(Integer.valueOf(lastUserEditAtomOffset)); - if(newLocation == null) { - throw new HSLFException("Couldn't find the new location of the UserEditAtom that used to be at " + lastUserEditAtomOffset); - } - lastUserEditAtomOffset = newLocation.intValue(); - } - - // Ditto for our PersistPtr - Integer newLocation = oldToNewReferencesLookup.get(Integer.valueOf(persistPointersOffset)); - if(newLocation == null) { - throw new HSLFException("Couldn't find the new location of the PersistPtr that used to be at " + persistPointersOffset); - } - persistPointersOffset = newLocation.intValue(); - } - - /** - * Write the contents of the record back, so it can be written - * to disk - */ - @Override - public void writeOut(OutputStream out) throws IOException { - // Header - out.write(_header); - - // Write out the values - writeLittleEndian(lastViewedSlideID,out); - writeLittleEndian(pptVersion,out); - writeLittleEndian(lastUserEditAtomOffset,out); - writeLittleEndian(persistPointersOffset,out); - writeLittleEndian(docPersistRef,out); - writeLittleEndian(maxPersistWritten,out); - writeLittleEndian(lastViewType,out); - writeLittleEndian(unused,out); - if (encryptSessionPersistIdRef != -1) { - // optional field - writeLittleEndian(encryptSessionPersistIdRef,out); - } - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/VBAInfoAtom.java b/src/scratchpad/src/org/apache/poi/hslf/record/VBAInfoAtom.java deleted file mode 100644 index d847c3853..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/VBAInfoAtom.java +++ /dev/null @@ -1,118 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.OutputStream; - -import org.apache.poi.util.LittleEndian; - -/** - * An atom record that specifies a reference to the VBA project storage. - */ -public final class VBAInfoAtom extends RecordAtom { - private static final long _type = RecordTypes.VBAInfoAtom.typeID; - - /** - * Record header. - */ - private byte[] _header; - - /** - * Record data. - */ - private long persistIdRef; - private boolean hasMacros; - private long version; - - /** - * Constructs an empty atom - not yet supported - */ - private VBAInfoAtom() { - _header = new byte[8]; - // TODO: fix me - LittleEndian.putUInt(_header, 0, _type); - persistIdRef = 0; - hasMacros = true; - version = 2; - } - - /** - * Constructs the vba atom record from its source data. - * - * @param source the source data as a byte array. - * @param start the start offset into the byte array. - * @param len the length of the slice in the byte array. - */ - public VBAInfoAtom(byte[] source, int start, int len) { - // Get the header. - _header = new byte[8]; - System.arraycopy(source,start,_header,0,8); - - // Get the record data. - persistIdRef = LittleEndian.getUInt(source, start+8); - hasMacros = (LittleEndian.getUInt(source, start+12) == 1); - version = LittleEndian.getUInt(source, start+16); - } - /** - * Gets the record type. - * @return the record type. - */ - public long getRecordType() { return _type; } - - /** - * Write the contents of the record back, so it can be written - * to disk - * - * @param out the output stream to write to. - * @throws java.io.IOException if an error occurs. - */ - public void writeOut(OutputStream out) throws IOException { - out.write(_header); - LittleEndian.putUInt(persistIdRef, out); - LittleEndian.putUInt(hasMacros ? 1 : 0, out); - LittleEndian.putUInt(version, out); - } - - public long getPersistIdRef() { - return persistIdRef; - } - - public void setPersistIdRef(long persistIdRef) { - this.persistIdRef = persistIdRef; - } - - public boolean isHasMacros() { - return hasMacros; - } - - public void setHasMacros(boolean hasMacros) { - this.hasMacros = hasMacros; - } - - public long getVersion() { - return version; - } - - public void setVersion(long version) { - this.version = version; - } - - -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/record/VBAInfoContainer.java b/src/scratchpad/src/org/apache/poi/hslf/record/VBAInfoContainer.java deleted file mode 100644 index 03577653e..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/record/VBAInfoContainer.java +++ /dev/null @@ -1,87 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import java.io.IOException; -import java.io.OutputStream; - -import org.apache.poi.util.LittleEndian; - -/** - * A container record that specifies VBA information for the document. - */ -public final class VBAInfoContainer extends RecordContainer { - private byte[] _header; - private static long _type = RecordTypes.VBAInfo.typeID; - - // Links to our more interesting children - - /** - * Set things up, and find our more interesting children - */ - protected VBAInfoContainer(byte[] source, int start, int len) { - // Grab the header - _header = new byte[8]; - System.arraycopy(source, start, _header, 0, 8); - - // Find our children - _children = Record.findChildRecords(source, start + 8, len - 8); - - findInterestingChildren(); - } - - /** - * Go through our child records, picking out the ones that are - * interesting, and saving those for use by the easy helper - * methods. - */ - private void findInterestingChildren() { - - } - - /** - * Create a new VBAInfoContainer, with blank fields - not yet supported - */ - private VBAInfoContainer() { - _header = new byte[8]; - _children = new Record[0]; - - // Setup our header block - _header[0] = 0x0f; // We are a container record - LittleEndian.putShort(_header, 2, (short) _type); - - // Setup our child records - findInterestingChildren(); - } - - /** - * We are of type 0x3FF - */ - public long getRecordType() { - return _type; - } - - /** - * Write the contents of the record back, so it can be written - * to disk - */ - public void writeOut(OutputStream out) throws IOException { - writeOut(_header[0], _header[1], _type, _children, out); - } - -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFAutoShape.java b/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFAutoShape.java deleted file mode 100644 index 910c8a0ad..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFAutoShape.java +++ /dev/null @@ -1,109 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.usermodel; - -import org.apache.poi.ddf.EscherContainerRecord; -import org.apache.poi.ddf.EscherProperties; -import org.apache.poi.sl.usermodel.*; -import org.apache.poi.ss.usermodel.ShapeTypes; - -/** - * Represents an AutoShape. - *

    - * AutoShapes are drawing objects with a particular shape that may be customized through smart resizing and adjustments. - * See {@link ShapeTypes} - *

    - * - * @author Yegor Kozlov - */ -public class HSLFAutoShape extends HSLFTextShape implements AutoShape { - - protected HSLFAutoShape(EscherContainerRecord escherRecord, ShapeContainer parent){ - super(escherRecord, parent); - } - - public HSLFAutoShape(ShapeType type, ShapeContainer parent){ - super(null, parent); - createSpContainer(type, parent instanceof HSLFGroupShape); - } - - public HSLFAutoShape(ShapeType type){ - this(type, null); - } - - protected EscherContainerRecord createSpContainer(ShapeType shapeType, boolean isChild){ - EscherContainerRecord ecr = super.createSpContainer(isChild); - - setShapeType(shapeType); - - //set default properties for an autoshape - setEscherProperty(EscherProperties.PROTECTION__LOCKAGAINSTGROUPING, 0x40000); - setEscherProperty(EscherProperties.FILL__FILLCOLOR, 0x8000004); - setEscherProperty(EscherProperties.FILL__FILLCOLOR, 0x8000004); - setEscherProperty(EscherProperties.FILL__FILLBACKCOLOR, 0x8000000); - setEscherProperty(EscherProperties.FILL__NOFILLHITTEST, 0x100010); - setEscherProperty(EscherProperties.LINESTYLE__COLOR, 0x8000001); - setEscherProperty(EscherProperties.LINESTYLE__NOLINEDRAWDASH, 0x80008); - setEscherProperty(EscherProperties.SHADOWSTYLE__COLOR, 0x8000002); - - return ecr; - } - - @Override - protected void setDefaultTextProperties(HSLFTextParagraph _txtrun){ - setVerticalAlignment(VerticalAlignment.MIDDLE); - setHorizontalCentered(true); - setWordWrap(false); - } - - /** - * Gets adjust value which controls smart resizing of the auto-shape. - * - *

    - * The adjustment values are given in shape coordinates: - * the origin is at the top-left, positive-x is to the right, positive-y is down. - * The region from (0,0) to (S,S) maps to the geometry box of the shape (S=21600 is a constant). - *

    - * - * @param idx the adjust index in the [0, 9] range - * @return the adjustment value - */ - public int getAdjustmentValue(int idx){ - if(idx < 0 || idx > 9) throw new IllegalArgumentException("The index of an adjustment value must be in the [0, 9] range"); - - return getEscherProperty((short)(EscherProperties.GEOMETRY__ADJUSTVALUE + idx)); - } - - /** - * Sets adjust value which controls smart resizing of the auto-shape. - * - *

    - * The adjustment values are given in shape coordinates: - * the origin is at the top-left, positive-x is to the right, positive-y is down. - * The region from (0,0) to (S,S) maps to the geometry box of the shape (S=21600 is a constant). - *

    - * - * @param idx the adjust index in the [0, 9] range - * @param val the adjustment value - */ - public void setAdjustmentValue(int idx, int val){ - if(idx < 0 || idx > 9) throw new IllegalArgumentException("The index of an adjustment value must be in the [0, 9] range"); - - setEscherProperty((short)(EscherProperties.GEOMETRY__ADJUSTVALUE + idx), val); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFBackground.java b/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFBackground.java deleted file mode 100644 index 8f477f956..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFBackground.java +++ /dev/null @@ -1,38 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.usermodel; - -import org.apache.poi.ddf.EscherContainerRecord; -import org.apache.poi.sl.usermodel.Background; -import org.apache.poi.sl.usermodel.ShapeContainer; - -/** - * Background shape - * - * @author Yegor Kozlov - */ -public final class HSLFBackground extends HSLFShape implements Background { - - protected HSLFBackground(EscherContainerRecord escherRecord, ShapeContainer parent) { - super(escherRecord, parent); - } - - protected EscherContainerRecord createSpContainer(boolean isChild) { - return null; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFConnectorShape.java b/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFConnectorShape.java deleted file mode 100644 index d87f24b01..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFConnectorShape.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.hslf.usermodel; - -import org.apache.poi.ddf.EscherContainerRecord; -import org.apache.poi.sl.usermodel.ConnectorShape; -import org.apache.poi.sl.usermodel.ShapeContainer; -import org.apache.poi.util.Beta; - -/** - * Specifies a connection shape. - * - * This is currently only a dummy implementation. - */ -@Beta -public class HSLFConnectorShape extends HSLFSimpleShape -implements ConnectorShape { - - /** - * Create a ConnectorShape object and initialize it from the supplied Record container. - * - * @param escherRecord EscherSpContainer container which holds information about this shape - * @param parent the parent of the shape - */ - protected HSLFConnectorShape(EscherContainerRecord escherRecord, ShapeContainer parent){ - super(escherRecord, parent); - - } - - /** - * Create a new ConnectorShape. This constructor is used when a new shape is created. - * - * @param parent the parent of this Shape. For example, if this text box is a cell - * in a table then the parent is Table. - */ - public HSLFConnectorShape(ShapeContainer parent){ - super(null, parent); - createSpContainer(parent instanceof HSLFGroupShape); - } - - /** - * Create a new ConnectorShape. This constructor is used when a new shape is created. - * - */ - public HSLFConnectorShape(){ - this(null); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFFill.java b/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFFill.java deleted file mode 100644 index b7d23871e..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFFill.java +++ /dev/null @@ -1,528 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.usermodel; - -import java.awt.Color; -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.util.List; - -import org.apache.poi.ddf.AbstractEscherOptRecord; -import org.apache.poi.ddf.EscherArrayProperty; -import org.apache.poi.ddf.EscherBSERecord; -import org.apache.poi.ddf.EscherColorRef; -import org.apache.poi.ddf.EscherContainerRecord; -import org.apache.poi.ddf.EscherProperties; -import org.apache.poi.ddf.EscherRecord; -import org.apache.poi.ddf.EscherSimpleProperty; -import org.apache.poi.hslf.record.Document; -import org.apache.poi.hslf.record.RecordTypes; -import org.apache.poi.sl.draw.DrawPaint; -import org.apache.poi.sl.usermodel.ColorStyle; -import org.apache.poi.sl.usermodel.FillStyle; -import org.apache.poi.sl.usermodel.PaintStyle; -import org.apache.poi.sl.usermodel.PaintStyle.GradientPaint; -import org.apache.poi.sl.usermodel.PaintStyle.GradientPaint.GradientType; -import org.apache.poi.sl.usermodel.PaintStyle.TexturePaint; -import org.apache.poi.util.BitField; -import org.apache.poi.util.BitFieldFactory; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.util.Units; - -/** - * Represents functionality provided by the 'Fill Effects' dialog in PowerPoint. - */ -public final class HSLFFill { - private static final POILogger LOG = POILogFactory.getLogger(HSLFFill.class); - - /** - * Fill with a solid color - */ - public static final int FILL_SOLID = 0; - - /** - * Fill with a pattern (bitmap) - */ - public static final int FILL_PATTERN = 1; - - /** - * A texture (pattern with its own color map) - */ - public static final int FILL_TEXTURE = 2; - - /** - * Center a picture in the shape - */ - public static final int FILL_PICTURE = 3; - - /** - * Shade from start to end points - */ - public static final int FILL_SHADE = 4; - - /** - * Shade from bounding rectangle to end point - */ - public static final int FILL_SHADE_CENTER = 5; - - /** - * Shade from shape outline to end point - */ - public static final int FILL_SHADE_SHAPE = 6; - - /** - * Similar to FILL_SHADE, but the fill angle - * is additionally scaled by the aspect ratio of - * the shape. If shape is square, it is the same as FILL_SHADE - */ - public static final int FILL_SHADE_SCALE = 7; - - /** - * shade to title - */ - public static final int FILL_SHADE_TITLE = 8; - - /** - * Use the background fill color/pattern - */ - public static final int FILL_BACKGROUND = 9; - - /** - * A bit that specifies whether the RecolorFillAsPicture bit is set. - * A value of 0x0 specifies that the fRecolorFillAsPicture MUST be ignored. - * The default value for this property is 0x0. - */ - private static final BitField FILL_USE_RECOLOR_FILL_AS_PICTURE = BitFieldFactory.getInstance(0x00400000); - - /** - * A bit that specifies whether the UseShapeAnchor bit is set. - * A value of 0x0 specifies that the fUseShapeAnchor MUST be ignored. - * The default value for this property is 0x0. - */ - private static final BitField FILL_USE_USE_SHAPE_ANCHOR = BitFieldFactory.getInstance(0x00200000); - - /** - * A bit that specifies whether the Filled bit is set. - * A value of 0x0 specifies that the Filled MUST be ignored. - * The default value for this property is 0x0. - */ - private static final BitField FILL_USE_FILLED = BitFieldFactory.getInstance(0x00100000); - - /** - * A bit that specifies whether the HitTestFill bit is set. - * A value of 0x0 specifies that the HitTestFill MUST be ignored. - * The default value for this property is 0x0. - */ - private static final BitField FILL_USE_HIT_TEST_FILL = BitFieldFactory.getInstance(0x00080000); - - /** - * A bit that specifies whether the fillShape bit is set. - * A value of 0x0 specifies that the fillShape MUST be ignored. - * The default value for this property is 0x0. - */ - private static final BitField FILL_USE_FILL_SHAPE = BitFieldFactory.getInstance(0x00040000); - - /** - * A bit that specifies whether the fillUseRect bit is set. - * A value of 0x0 specifies that the fillUseRect MUST be ignored. - * The default value for this property is 0x0. - */ - private static final BitField FILL_USE_FILL_USE_RECT = BitFieldFactory.getInstance(0x00020000); - - /** - * A bit that specifies whether the fNoFillHitTest bit is set. - * A value of 0x0 specifies that the fNoFillHitTest MUST be ignored. - * The default value for this property is 0x0. - */ - private static final BitField FILL_USE_NO_FILL_HIT_TEST = BitFieldFactory.getInstance(0x00010000); - - /** - * A bit that specifies how to recolor a picture fill. If this bit is set to 0x1, the pictureFillCrMod - * property of the picture fill is used for recoloring. If this bit is set to 0x0, the fillCrMod property, - * as defined in section 2.3.7.6, is used for recoloring. - * If UsefRecolorFillAsPicture equals 0x0, this value MUST be ignored. - * The default value for this property is 0x0. - */ - private static final BitField FILL_RECOLOR_FILL_AS_PICTURE = BitFieldFactory.getInstance(0x00000040); - - /** - * A bit that specifies whether the fill is rotated with the shape. - * If UseUseShapeAnchor equals 0x0, this value MUST be ignored. - * The default value for this property is 0x0. - */ - private static final BitField FILL_USE_SHAPE_ANCHOR = BitFieldFactory.getInstance(0x00000020); - - /** - * A bit that specifies whether the fill is rendered if the shape is a 2-D shape. - * If this bit is set to 0x1, the fill of this shape is rendered based on the properties of the Fill Style - * property set. If this bit is set to 0x0, the fill of this shape is not rendered. - * If UseFilled is 0x0, this value MUST be ignored. The default value for this property is 0x1. - */ - private static final BitField FILL_FILLED = BitFieldFactory.getInstance(0x00000010); - - /** - * A bit that specifies whether this fill will be hit tested. - * If UsefHitTestFill equals 0x0, this value MUST be ignored. - * The default value for this property is 0x1. - */ - private static final BitField FILL_HIT_TEST_FILL = BitFieldFactory.getInstance(0x00000008); - - /** - * A bit that specifies how the fill is aligned. If this bit is set to 0x1, the fill is - * aligned relative to the shape so that it moves with the shape. If this bit is set to 0x0, - * the fill is aligned with the origin of the view. If fUsefillShape equals 0x0, this value MUST be ignored. - * The default value for this property is 0x1. - */ - private static final BitField FILL_FILL_SHAPE = BitFieldFactory.getInstance(0x00000004); - - /** - * A bit that specifies whether to use the rectangle specified by the fillRectLeft, fillRectRight, - * fillRectTop, and fillRectBottom properties, rather than the bounding rectangle of the shape, - * as the filled area. If fUsefillUseRect equals 0x0, this value MUST be ignored. - * The default value for this property is 0x0. - */ - private static final BitField FILL_FILL_USE_RECT = BitFieldFactory.getInstance(0x00000002); - - /** - * A bit that specifies whether this shape will be hit tested as though it were filled. - * If UsefNoFillHitTest equals 0x0, this value MUST be ignored. - * The default value for this property is 0x0. - */ - private static final BitField FILL_NO_FILL_HIT_TEST = BitFieldFactory.getInstance(0x00000001); - - - /** - * The shape this background applies to - */ - private HSLFShape shape; - - /** - * Construct a Fill object for a shape. - * Fill information will be read from shape's escher properties. - * - * @param shape the shape this background applies to - */ - public HSLFFill(HSLFShape shape){ - this.shape = shape; - } - - - public FillStyle getFillStyle() { - return new FillStyle() { - @Override - public PaintStyle getPaint() { - final int fillType = getFillType(); - // TODO: fix gradient types, this mismatches with the MS-ODRAW definition ... - // need to handle (not only) the type (radial,rectangular,linear), - // the direction, e.g. top right, and bounds (e.g. for rectangular boxes) - switch (fillType) { - case FILL_SOLID: - return DrawPaint.createSolidPaint(getForegroundColor()); - case FILL_SHADE_SHAPE: - return getGradientPaint(GradientType.shape); - case FILL_SHADE_CENTER: - case FILL_SHADE_TITLE: - return getGradientPaint(GradientType.circular); - case FILL_SHADE: - case FILL_SHADE_SCALE: - return getGradientPaint(GradientType.linear); - case FILL_PICTURE: - return getTexturePaint(); - default: - LOG.log(POILogger.WARN, "unsuported fill type: " + fillType); - return null; - } - } - }; - } - - - - private GradientPaint getGradientPaint(final GradientType gradientType) { - AbstractEscherOptRecord opt = shape.getEscherOptRecord(); - final EscherArrayProperty ep = HSLFShape.getEscherProperty(opt, EscherProperties.FILL__SHADECOLORS); - final int colorCnt = (ep == null) ? 0 : ep.getNumberOfElementsInArray(); - - // NOFILLHITTEST can be in the normal escher opt record but also in the tertiary record - // the extended bit fields seem to be in the second - opt = (AbstractEscherOptRecord)shape.getEscherChild(RecordTypes.EscherUserDefined); - EscherSimpleProperty p = HSLFShape.getEscherProperty(opt, EscherProperties.FILL__NOFILLHITTEST); - int propVal = (p == null) ? 0 : p.getPropertyValue(); - final boolean rotateWithShape = FILL_USE_USE_SHAPE_ANCHOR.isSet(propVal) && FILL_USE_SHAPE_ANCHOR.isSet(propVal); - - return new GradientPaint() { - @Override - public double getGradientAngle() { - // A value of type FixedPoint, as specified in [MS-OSHARED] section 2.2.1.6, - // that specifies the angle of the gradient fill. Zero degrees represents a vertical vector from - // bottom to top. The default value for this property is 0x00000000. - int rot = shape.getEscherProperty(EscherProperties.FILL__ANGLE); - return 90-Units.fixedPointToDouble(rot); - } - - @Override - public ColorStyle[] getGradientColors() { - ColorStyle cs[]; - if (colorCnt == 0) { - cs = new ColorStyle[2]; - cs[0] = wrapColor(getBackgroundColor()); - cs[1] = wrapColor(getForegroundColor()); - } else { - cs = new ColorStyle[colorCnt]; - int idx = 0; - // TODO: handle palette colors and alpha(?) value - for (byte data[] : ep) { - EscherColorRef ecr = new EscherColorRef(data, 0, 4); - cs[idx++] = wrapColor(shape.getColor(ecr)); - } - } - return cs; - } - - private ColorStyle wrapColor(Color col) { - return (col == null) ? null : DrawPaint.createSolidPaint(col).getSolidColor(); - } - - @Override - public float[] getGradientFractions() { - float frc[]; - if (colorCnt == 0) { - frc = new float[]{0, 1}; - } else { - frc = new float[colorCnt]; - int idx = 0; - for (byte data[] : ep) { - double pos = Units.fixedPointToDouble(LittleEndian.getInt(data, 4)); - frc[idx++] = (float)pos; - } - } - return frc; - } - - @Override - public boolean isRotatedWithShape() { - return rotateWithShape; - } - - @Override - public GradientType getGradientType() { - return gradientType; - } - }; - } - - private TexturePaint getTexturePaint() { - final HSLFPictureData pd = getPictureData(); - if (pd == null) { - return null; - } - - return new TexturePaint() { - @Override - public InputStream getImageData() { - return new ByteArrayInputStream(pd.getData()); - } - - @Override - public String getContentType() { - return pd.getContentType(); - } - - @Override - public int getAlpha() { - return (int)(shape.getAlpha(EscherProperties.FILL__FILLOPACITY)*100000.0); - } - }; - } - - /** - * Returns fill type. - * Must be one of the FILL_* constants defined in this class. - * - * @return type of fill - */ - public int getFillType(){ - AbstractEscherOptRecord opt = shape.getEscherOptRecord(); - EscherSimpleProperty prop = HSLFShape.getEscherProperty(opt, EscherProperties.FILL__FILLTYPE); - return prop == null ? FILL_SOLID : prop.getPropertyValue(); - } - - /** - */ - protected void afterInsert(HSLFSheet sh){ - AbstractEscherOptRecord opt = shape.getEscherOptRecord(); - EscherSimpleProperty p = HSLFShape.getEscherProperty(opt, EscherProperties.FILL__PATTERNTEXTURE); - if(p != null) { - int idx = p.getPropertyValue(); - EscherBSERecord bse = getEscherBSERecord(idx); - bse.setRef(bse.getRef() + 1); - } - } - - @SuppressWarnings("resource") - protected EscherBSERecord getEscherBSERecord(int idx){ - HSLFSheet sheet = shape.getSheet(); - if(sheet == null) { - LOG.log(POILogger.DEBUG, "Fill has not yet been assigned to a sheet"); - return null; - } - HSLFSlideShow ppt = sheet.getSlideShow(); - Document doc = ppt.getDocumentRecord(); - EscherContainerRecord dggContainer = doc.getPPDrawingGroup().getDggContainer(); - EscherContainerRecord bstore = HSLFShape.getEscherChild(dggContainer, EscherContainerRecord.BSTORE_CONTAINER); - if(bstore == null) { - LOG.log(POILogger.DEBUG, "EscherContainerRecord.BSTORE_CONTAINER was not found "); - return null; - } - List lst = bstore.getChildRecords(); - return (EscherBSERecord)lst.get(idx-1); - } - - /** - * Sets fill type. - * Must be one of the FILL_* constants defined in this class. - * - * @param type type of the fill - */ - public void setFillType(int type){ - AbstractEscherOptRecord opt = shape.getEscherOptRecord(); - HSLFShape.setEscherProperty(opt, EscherProperties.FILL__FILLTYPE, type); - } - - /** - * Foreground color - */ - public Color getForegroundColor(){ - AbstractEscherOptRecord opt = shape.getEscherOptRecord(); - EscherSimpleProperty p = HSLFShape.getEscherProperty(opt, EscherProperties.FILL__NOFILLHITTEST); - int propVal = (p == null) ? 0 : p.getPropertyValue(); - - return (FILL_USE_FILLED.isSet(propVal) && !FILL_FILLED.isSet(propVal)) - ? null - : shape.getColor(EscherProperties.FILL__FILLCOLOR, EscherProperties.FILL__FILLOPACITY, -1); - } - - /** - * Foreground color - */ - public void setForegroundColor(Color color){ - AbstractEscherOptRecord opt = shape.getEscherOptRecord(); - opt.removeEscherProperty(EscherProperties.FILL__FILLOPACITY); - opt.removeEscherProperty(EscherProperties.FILL__FILLCOLOR); - - if (color != null) { - int rgb = new Color(color.getBlue(), color.getGreen(), color.getRed(), 0).getRGB(); - HSLFShape.setEscherProperty(opt, EscherProperties.FILL__FILLCOLOR, rgb); - int alpha = color.getAlpha(); - if (alpha < 255) { - int alphaFP = Units.doubleToFixedPoint(alpha/255d); - HSLFShape.setEscherProperty(opt, EscherProperties.FILL__FILLOPACITY, alphaFP); - } - } - - EscherSimpleProperty p = HSLFShape.getEscherProperty(opt, EscherProperties.FILL__NOFILLHITTEST); - int propVal = (p == null) ? 0 : p.getPropertyValue(); - propVal = FILL_FILLED.setBoolean(propVal, color != null); - propVal = FILL_NO_FILL_HIT_TEST.setBoolean(propVal, color != null); - propVal = FILL_USE_FILLED.set(propVal); - propVal = FILL_USE_FILL_SHAPE.set(propVal); - propVal = FILL_USE_NO_FILL_HIT_TEST.set(propVal); - // TODO: check why we always clear this ... - propVal = FILL_FILL_SHAPE.clear(propVal); - - HSLFShape.setEscherProperty(opt, EscherProperties.FILL__NOFILLHITTEST, propVal); - } - - /** - * Background color - */ - public Color getBackgroundColor(){ - AbstractEscherOptRecord opt = shape.getEscherOptRecord(); - EscherSimpleProperty p = HSLFShape.getEscherProperty(opt, EscherProperties.FILL__NOFILLHITTEST); - int propVal = (p == null) ? 0 : p.getPropertyValue(); - - return (FILL_USE_FILLED.isSet(propVal) && !FILL_FILLED.isSet(propVal)) - ? null - : shape.getColor(EscherProperties.FILL__FILLBACKCOLOR, EscherProperties.FILL__FILLOPACITY, -1); - } - - /** - * Background color - */ - public void setBackgroundColor(Color color){ - AbstractEscherOptRecord opt = shape.getEscherOptRecord(); - if (color == null) { - HSLFShape.setEscherProperty(opt, EscherProperties.FILL__FILLBACKCOLOR, -1); - } - else { - int rgb = new Color(color.getBlue(), color.getGreen(), color.getRed(), 0).getRGB(); - HSLFShape.setEscherProperty(opt, EscherProperties.FILL__FILLBACKCOLOR, rgb); - } - } - - /** - * PictureData object used in a texture, pattern of picture fill. - */ - @SuppressWarnings("resource") - public HSLFPictureData getPictureData(){ - AbstractEscherOptRecord opt = shape.getEscherOptRecord(); - EscherSimpleProperty p = HSLFShape.getEscherProperty(opt, EscherProperties.FILL__PATTERNTEXTURE); - if (p == null) { - return null; - } - - HSLFSlideShow ppt = shape.getSheet().getSlideShow(); - List pict = ppt.getPictureData(); - Document doc = ppt.getDocumentRecord(); - - EscherContainerRecord dggContainer = doc.getPPDrawingGroup().getDggContainer(); - EscherContainerRecord bstore = HSLFShape.getEscherChild(dggContainer, EscherContainerRecord.BSTORE_CONTAINER); - - java.util.List lst = bstore.getChildRecords(); - int idx = p.getPropertyValue(); - if (idx == 0){ - LOG.log(POILogger.WARN, "no reference to picture data found "); - } else { - EscherBSERecord bse = (EscherBSERecord)lst.get(idx - 1); - for (HSLFPictureData pd : pict) { - if (pd.getOffset() == bse.getOffset()){ - return pd; - } - } - } - - return null; - } - - /** - * Assign picture used to fill the underlying shape. - * - * @param data the picture data added to this ppt by {@link HSLFSlideShow#addPicture(byte[], org.apache.poi.sl.usermodel.PictureData.PictureType)} method. - */ - public void setPictureData(HSLFPictureData data){ - AbstractEscherOptRecord opt = shape.getEscherOptRecord(); - HSLFShape.setEscherProperty(opt, (short)(EscherProperties.FILL__PATTERNTEXTURE + 0x4000), (data == null ? 0 : data.getIndex())); - if(data != null && shape.getSheet() != null) { - EscherBSERecord bse = getEscherBSERecord(data.getIndex()); - bse.setRef(bse.getRef() + 1); - } - } - -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFFreeformShape.java b/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFFreeformShape.java deleted file mode 100644 index b7919160f..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFFreeformShape.java +++ /dev/null @@ -1,459 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.usermodel; - -import java.awt.geom.AffineTransform; -import java.awt.geom.Path2D; -import java.awt.geom.PathIterator; -import java.awt.geom.Point2D; -import java.awt.geom.Rectangle2D; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.apache.poi.ddf.AbstractEscherOptRecord; -import org.apache.poi.ddf.EscherArrayProperty; -import org.apache.poi.ddf.EscherContainerRecord; -import org.apache.poi.ddf.EscherProperties; -import org.apache.poi.ddf.EscherProperty; -import org.apache.poi.ddf.EscherSimpleProperty; -import org.apache.poi.sl.usermodel.FreeformShape; -import org.apache.poi.sl.usermodel.ShapeContainer; -import org.apache.poi.sl.usermodel.ShapeType; -import org.apache.poi.util.BitField; -import org.apache.poi.util.BitFieldFactory; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.util.Units; - -/** - * A "Freeform" shape. - * - *

    - * Shapes drawn with the "Freeform" tool have cubic bezier curve segments in the smooth sections - * and straight-line segments in the straight sections. This object closely corresponds to java.awt.geom.GeneralPath. - *

    - */ -public final class HSLFFreeformShape extends HSLFAutoShape implements FreeformShape { - private static final POILogger LOG = POILogFactory.getLogger(HSLFFreeformShape.class); - - private static final byte[] SEGMENTINFO_MOVETO = new byte[]{0x00, 0x40}; - private static final byte[] SEGMENTINFO_LINETO = new byte[]{0x00, (byte)0xAC}; - private static final byte[] SEGMENTINFO_ESCAPE = new byte[]{0x01, 0x00}; - private static final byte[] SEGMENTINFO_ESCAPE2 = new byte[]{0x01, 0x20}; - private static final byte[] SEGMENTINFO_CUBICTO = new byte[]{0x00, (byte)0xAD}; - // OpenOffice inserts 0xB3 instead of 0xAD. - // private static final byte[] SEGMENTINFO_CUBICTO2 = new byte[]{0x00, (byte)0xB3}; - private static final byte[] SEGMENTINFO_CLOSE = new byte[]{0x01, (byte)0x60}; - private static final byte[] SEGMENTINFO_END = new byte[]{0x00, (byte)0x80}; - - private static final BitField PATH_INFO = BitFieldFactory.getInstance(0xE000); - // private static final BitField ESCAPE_INFO = BitFieldFactory.getInstance(0x1F00); - - enum PathInfo { - lineTo(0),curveTo(1),moveTo(2),close(3),end(4),escape(5),clientEscape(6); - private final int flag; - PathInfo(int flag) { - this.flag = flag; - } - public int getFlag() { - return flag; - } - static PathInfo valueOf(int flag) { - for (PathInfo v : values()) { - if (v.flag == flag) { - return v; - } - } - return null; - } - } - - enum EscapeInfo { - EXTENSION(0x0000), - ANGLE_ELLIPSE_TO(0x0001), - ANGLE_ELLIPSE(0x0002), - ARC_TO(0x0003), - ARC(0x0004), - CLOCKWISE_ARC_TO(0x0005), - CLOCKWISE_ARC(0x0006), - ELLIPTICAL_QUADRANT_X(0x0007), - ELLIPTICAL_QUADRANT_Y(0x0008), - QUADRATIC_BEZIER(0x0009), - NO_FILL(0X000A), - NO_LINE(0X000B), - AUTO_LINE(0X000C), - AUTO_CURVE(0X000D), - CORNER_LINE(0X000E), - CORNER_CURVE(0X000F), - SMOOTH_LINE(0X0010), - SMOOTH_CURVE(0X0011), - SYMMETRIC_LINE(0X0012), - SYMMETRIC_CURVE(0X0013), - FREEFORM(0X0014), - FILL_COLOR(0X0015), - LINE_COLOR(0X0016); - - private final int flag; - EscapeInfo(int flag) { - this.flag = flag; - } - public int getFlag() { - return flag; - } - static EscapeInfo valueOf(int flag) { - for (EscapeInfo v : values()) { - if (v.flag == flag) { - return v; - } - } - return null; - } - } - - enum ShapePath { - LINES(0), - LINES_CLOSED(1), - CURVES(2), - CURVES_CLOSED(3), - COMPLEX(4); - - private final int flag; - ShapePath(int flag) { - this.flag = flag; - } - public int getFlag() { - return flag; - } - static ShapePath valueOf(int flag) { - for (ShapePath v : values()) { - if (v.flag == flag) { - return v; - } - } - return null; - } - } - - /** - * Create a Freeform object and initialize it from the supplied Record container. - * - * @param escherRecord EscherSpContainer container which holds information about this shape - * @param parent the parent of the shape - */ - protected HSLFFreeformShape(EscherContainerRecord escherRecord, ShapeContainer parent){ - super(escherRecord, parent); - - } - - /** - * Create a new Freeform. This constructor is used when a new shape is created. - * - * @param parent the parent of this Shape. For example, if this text box is a cell - * in a table then the parent is Table. - */ - public HSLFFreeformShape(ShapeContainer parent){ - super((EscherContainerRecord)null, parent); - createSpContainer(ShapeType.NOT_PRIMITIVE, parent instanceof HSLFGroupShape); - } - - /** - * Create a new Freeform. This constructor is used when a new shape is created. - * - */ - public HSLFFreeformShape(){ - this(null); - } - - @Override - public int setPath(Path2D.Double path) { - Rectangle2D bounds = path.getBounds2D(); - PathIterator it = path.getPathIterator(new AffineTransform()); - - List segInfo = new ArrayList(); - List pntInfo = new ArrayList(); - boolean isClosed = false; - int numPoints = 0; - while (!it.isDone()) { - double[] vals = new double[6]; - int type = it.currentSegment(vals); - switch (type) { - case PathIterator.SEG_MOVETO: - pntInfo.add(new Point2D.Double(vals[0], vals[1])); - segInfo.add(SEGMENTINFO_MOVETO); - numPoints++; - break; - case PathIterator.SEG_LINETO: - pntInfo.add(new Point2D.Double(vals[0], vals[1])); - segInfo.add(SEGMENTINFO_LINETO); - segInfo.add(SEGMENTINFO_ESCAPE); - numPoints++; - break; - case PathIterator.SEG_CUBICTO: - pntInfo.add(new Point2D.Double(vals[0], vals[1])); - pntInfo.add(new Point2D.Double(vals[2], vals[3])); - pntInfo.add(new Point2D.Double(vals[4], vals[5])); - segInfo.add(SEGMENTINFO_CUBICTO); - segInfo.add(SEGMENTINFO_ESCAPE2); - numPoints++; - break; - case PathIterator.SEG_QUADTO: - //TODO: figure out how to convert SEG_QUADTO into SEG_CUBICTO - LOG.log(POILogger.WARN, "SEG_QUADTO is not supported"); - break; - case PathIterator.SEG_CLOSE: - pntInfo.add(pntInfo.get(0)); - segInfo.add(SEGMENTINFO_LINETO); - segInfo.add(SEGMENTINFO_ESCAPE); - segInfo.add(SEGMENTINFO_LINETO); - segInfo.add(SEGMENTINFO_CLOSE); - isClosed = true; - numPoints++; - break; - default: - LOG.log(POILogger.WARN, "Ignoring invalid segment type "+type); - break; - } - - it.next(); - } - if(!isClosed) { - segInfo.add(SEGMENTINFO_LINETO); - } - segInfo.add(SEGMENTINFO_END); - - AbstractEscherOptRecord opt = getEscherOptRecord(); - opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__SHAPEPATH, 0x4)); - - EscherArrayProperty verticesProp = new EscherArrayProperty((short)(EscherProperties.GEOMETRY__VERTICES + 0x4000), false, null); - verticesProp.setNumberOfElementsInArray(pntInfo.size()); - verticesProp.setNumberOfElementsInMemory(pntInfo.size()); - verticesProp.setSizeOfElements(8); - for (int i = 0; i < pntInfo.size(); i++) { - Point2D.Double pnt = pntInfo.get(i); - byte[] data = new byte[8]; - LittleEndian.putInt(data, 0, Units.pointsToMaster(pnt.getX() - bounds.getX())); - LittleEndian.putInt(data, 4, Units.pointsToMaster(pnt.getY() - bounds.getY())); - verticesProp.setElement(i, data); - } - opt.addEscherProperty(verticesProp); - - EscherArrayProperty segmentsProp = new EscherArrayProperty((short)(EscherProperties.GEOMETRY__SEGMENTINFO + 0x4000), false, null); - segmentsProp.setNumberOfElementsInArray(segInfo.size()); - segmentsProp.setNumberOfElementsInMemory(segInfo.size()); - segmentsProp.setSizeOfElements(0x2); - for (int i = 0; i < segInfo.size(); i++) { - byte[] seg = segInfo.get(i); - segmentsProp.setElement(i, seg); - } - opt.addEscherProperty(segmentsProp); - - opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__RIGHT, Units.pointsToMaster(bounds.getWidth()))); - opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GEOMETRY__BOTTOM, Units.pointsToMaster(bounds.getHeight()))); - - opt.sortProperties(); - - setAnchor(bounds); - - return numPoints; - } - - @Override - public Path2D.Double getPath(){ - AbstractEscherOptRecord opt = getEscherOptRecord(); - - EscherArrayProperty verticesProp = getShapeProp(opt, EscherProperties.GEOMETRY__VERTICES); - EscherArrayProperty segmentsProp = getShapeProp(opt, EscherProperties.GEOMETRY__SEGMENTINFO); - - // return empty path if either GEOMETRY__VERTICES or GEOMETRY__SEGMENTINFO is missing, see Bugzilla 54188 - Path2D.Double path = new Path2D.Double(); - - //sanity check - if(verticesProp == null) { - LOG.log(POILogger.WARN, "Freeform is missing GEOMETRY__VERTICES "); - return path; - } - if(segmentsProp == null) { - LOG.log(POILogger.WARN, "Freeform is missing GEOMETRY__SEGMENTINFO "); - return path; - } - - Iterator vertIter = verticesProp.iterator(); - Iterator segIter = segmentsProp.iterator(); - double xyPoints[] = new double[2]; - - while (vertIter.hasNext() && segIter.hasNext()) { - byte[] segElem = segIter.next(); - PathInfo pi = getPathInfo(segElem); - switch (pi) { - case escape: { - // handleEscapeInfo(path, segElem, vertIter); - break; - } - case moveTo: { - fillPoint(vertIter.next(), xyPoints); - double x = xyPoints[0]; - double y = xyPoints[1]; - path.moveTo(x,y); - break; - } - case curveTo: { - fillPoint(vertIter.next(), xyPoints); - double x1 = xyPoints[0]; - double y1 = xyPoints[1]; - fillPoint(vertIter.next(), xyPoints); - double x2 = xyPoints[0]; - double y2 = xyPoints[1]; - fillPoint(vertIter.next(), xyPoints); - double x3 = xyPoints[0]; - double y3 = xyPoints[1]; - path.curveTo(x1,y1,x2,y2,x3,y3); - break; - } - case lineTo: - if (vertIter.hasNext()) { - fillPoint(vertIter.next(), xyPoints); - double x = xyPoints[0]; - double y = xyPoints[1]; - path.lineTo(x,y); - } - break; - case close: - path.closePath(); - break; - default: - break; - } - } - - EscherSimpleProperty shapePath = getShapeProp(opt, EscherProperties.GEOMETRY__SHAPEPATH); - ShapePath sp = ShapePath.valueOf(shapePath == null ? 1 : shapePath.getPropertyValue()); - if (sp == ShapePath.LINES_CLOSED || sp == ShapePath.CURVES_CLOSED) { - path.closePath(); - } - - Rectangle2D anchor = getAnchor(); - Rectangle2D bounds = path.getBounds2D(); - AffineTransform at = new AffineTransform(); - at.translate(anchor.getX(), anchor.getY()); - at.scale( - anchor.getWidth()/bounds.getWidth(), - anchor.getHeight()/bounds.getHeight() - ); - return new Path2D.Double(at.createTransformedShape(path)); - } - - private void fillPoint(byte xyMaster[], double xyPoints[]) { - if (xyMaster == null || xyPoints == null) { - LOG.log(POILogger.WARN, "Master bytes or points not set - ignore point"); - return; - } - if ((xyMaster.length != 4 && xyMaster.length != 8) || xyPoints.length != 2) { - LOG.log(POILogger.WARN, "Invalid number of master bytes for a single point - ignore point"); - return; - } - - int x, y; - if (xyMaster.length == 4) { - x = LittleEndian.getShort(xyMaster, 0); - y = LittleEndian.getShort(xyMaster, 2); - } else { - x = LittleEndian.getInt(xyMaster, 0); - y = LittleEndian.getInt(xyMaster, 4); - } - - xyPoints[0] = Units.masterToPoints(x); - xyPoints[1] = Units.masterToPoints(y); - } - - private static T getShapeProp(AbstractEscherOptRecord opt, int propId) { - T prop = getEscherProperty(opt, (short)(propId + 0x4000)); - if (prop == null) { - prop = getEscherProperty(opt, propId); - } - return prop; - } - -// private void handleEscapeInfo(Path2D path, byte segElem[], Iterator vertIter) { -// EscapeInfo ei = getEscapeInfo(segElem); -// switch (ei) { -// case EXTENSION: -// break; -// case ANGLE_ELLIPSE_TO: -// break; -// case ANGLE_ELLIPSE: -// break; -// case ARC_TO: -// break; -// case ARC: -// break; -// case CLOCKWISE_ARC_TO: -// break; -// case CLOCKWISE_ARC: -// break; -// case ELLIPTICAL_QUADRANT_X: -// break; -// case ELLIPTICAL_QUADRANT_Y: -// break; -// case QUADRATIC_BEZIER: -// break; -// case NO_FILL: -// break; -// case NO_LINE: -// break; -// case AUTO_LINE: -// break; -// case AUTO_CURVE: -// break; -// case CORNER_LINE: -// break; -// case CORNER_CURVE: -// break; -// case SMOOTH_LINE: -// break; -// case SMOOTH_CURVE: -// break; -// case SYMMETRIC_LINE: -// break; -// case SYMMETRIC_CURVE: -// break; -// case FREEFORM: -// break; -// case FILL_COLOR: -// break; -// case LINE_COLOR: -// break; -// default: -// break; -// } -// } - - - private static PathInfo getPathInfo(byte elem[]) { - int elemUS = LittleEndian.getUShort(elem, 0); - int pathInfo = PATH_INFO.getValue(elemUS); - return PathInfo.valueOf(pathInfo); - } - -// private static EscapeInfo getEscapeInfo(byte elem[]) { -// int elemUS = LittleEndian.getUShort(elem, 0); -// int escInfo = ESCAPE_INFO.getValue(elemUS); -// return EscapeInfo.valueOf(escInfo); -// } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFGroupShape.java b/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFGroupShape.java deleted file mode 100644 index 3d4d57fbd..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFGroupShape.java +++ /dev/null @@ -1,366 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.usermodel; - -import java.awt.geom.Rectangle2D; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.apache.poi.ddf.EscherChildAnchorRecord; -import org.apache.poi.ddf.EscherClientAnchorRecord; -import org.apache.poi.ddf.EscherContainerRecord; -import org.apache.poi.ddf.EscherRecord; -import org.apache.poi.ddf.EscherSpRecord; -import org.apache.poi.ddf.EscherSpgrRecord; -import org.apache.poi.sl.usermodel.GroupShape; -import org.apache.poi.sl.usermodel.PictureData; -import org.apache.poi.sl.usermodel.ShapeContainer; -import org.apache.poi.sl.usermodel.ShapeType; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.util.Units; - -/** - * Represents a group of shapes. - * - * @author Yegor Kozlov - */ -public class HSLFGroupShape extends HSLFShape -implements HSLFShapeContainer, GroupShape { - private static final POILogger LOG = POILogFactory.getLogger(HSLFGroupShape.class); - - /** - * Create a new ShapeGroup. This constructor is used when a new shape is created. - * - */ - public HSLFGroupShape(){ - this(null, null); - createSpContainer(false); - } - - /** - * Create a new ShapeGroup. This constructor is used when a new shape is created. - * - * @param parent the parent of the shape - */ - public HSLFGroupShape(ShapeContainer parent){ - this(null, parent); - createSpContainer(parent instanceof HSLFGroupShape); - } - - /** - * Create a ShapeGroup object and initialize it from the supplied Record container. - * - * @param escherRecord EscherSpContainer container which holds information about this shape - * @param parent the parent of the shape - */ - protected HSLFGroupShape(EscherContainerRecord escherRecord, ShapeContainer parent){ - super(escherRecord, parent); - } - - @Override - public void setAnchor(Rectangle2D anchor) { - EscherClientAnchorRecord clientAnchor = getEscherChild(EscherClientAnchorRecord.RECORD_ID); - boolean isInitialized = !(clientAnchor.getDx1() == 0 && clientAnchor.getRow1() == 0); - - if (isInitialized) { - moveAndScale(anchor); - } else { - setExteriorAnchor(anchor); - } - } - - @Override - public void setInteriorAnchor(Rectangle2D anchor){ - EscherSpgrRecord spgr = getEscherChild(EscherSpgrRecord.RECORD_ID); - - int x1 = Units.pointsToMaster(anchor.getX()); - int y1 = Units.pointsToMaster(anchor.getY()); - int x2 = Units.pointsToMaster(anchor.getX() + anchor.getWidth()); - int y2 = Units.pointsToMaster(anchor.getY() + anchor.getHeight()); - - spgr.setRectX1(x1); - spgr.setRectY1(y1); - spgr.setRectX2(x2); - spgr.setRectY2(y2); - } - - @Override - public Rectangle2D getInteriorAnchor(){ - EscherSpgrRecord rec = getEscherChild(EscherSpgrRecord.RECORD_ID); - double x1 = Units.masterToPoints(rec.getRectX1()); - double y1 = Units.masterToPoints(rec.getRectY1()); - double x2 = Units.masterToPoints(rec.getRectX2()); - double y2 = Units.masterToPoints(rec.getRectY2()); - return new Rectangle2D.Double(x1,y1,x2-x1,y2-y1); - } - - protected void setExteriorAnchor(Rectangle2D anchor) { - EscherClientAnchorRecord clientAnchor = getEscherChild(EscherClientAnchorRecord.RECORD_ID); - - //hack. internal variable EscherClientAnchorRecord.shortRecord can be - //initialized only in fillFields(). We need to set shortRecord=false; - byte[] header = new byte[16]; - LittleEndian.putUShort(header, 0, 0); - LittleEndian.putUShort(header, 2, 0); - LittleEndian.putInt(header, 4, 8); - clientAnchor.fillFields(header, 0, null); - - // All coordinates need to be converted to Master units (576 dpi) - clientAnchor.setFlag((short)Units.pointsToMaster(anchor.getY())); - clientAnchor.setCol1((short)Units.pointsToMaster(anchor.getX())); - clientAnchor.setDx1((short)Units.pointsToMaster(anchor.getWidth() + anchor.getX())); - clientAnchor.setRow1((short)Units.pointsToMaster(anchor.getHeight() + anchor.getY())); - - // TODO: does this make sense? - setInteriorAnchor(anchor); - } - - /** - * Create a new ShapeGroup and create an instance of EscherSpgrContainer which represents a group of shapes - */ - @Override - protected EscherContainerRecord createSpContainer(boolean isChild) { - EscherContainerRecord ecr = super.createSpContainer(isChild); - ecr.setRecordId(EscherContainerRecord.SPGR_CONTAINER); - - //The group itself is a shape, and always appears as the first EscherSpContainer in the group container. - EscherContainerRecord spcont = new EscherContainerRecord(); - spcont.setRecordId(EscherContainerRecord.SP_CONTAINER); - spcont.setOptions((short)15); - - EscherSpgrRecord spg = new EscherSpgrRecord(); - spg.setOptions((short)1); - spcont.addChildRecord(spg); - - EscherSpRecord sp = new EscherSpRecord(); - short type = (short)((ShapeType.NOT_PRIMITIVE.nativeId << 4) + 2); - sp.setOptions(type); - sp.setFlags(EscherSpRecord.FLAG_HAVEANCHOR | EscherSpRecord.FLAG_GROUP); - spcont.addChildRecord(sp); - - EscherClientAnchorRecord anchor = new EscherClientAnchorRecord(); - spcont.addChildRecord(anchor); - - ecr.addChildRecord(spcont); - return ecr; - } - - /** - * Add a shape to this group. - * - * @param shape - the Shape to add - */ - @Override - public void addShape(HSLFShape shape){ - getSpContainer().addChildRecord(shape.getSpContainer()); - - HSLFSheet sheet = getSheet(); - shape.setSheet(sheet); - shape.setShapeId(sheet.allocateShapeId()); - shape.afterInsert(sheet); - } - - /** - * Moves and scales this ShapeGroup to the specified anchor. - */ - protected void moveAndScale(Rectangle2D anchorDest){ - Rectangle2D anchorSrc = getAnchor(); - double scaleX = (anchorSrc.getWidth() == 0) ? 0 : anchorDest.getWidth() / anchorSrc.getWidth(); - double scaleY = (anchorSrc.getHeight() == 0) ? 0 : anchorDest.getHeight() / anchorSrc.getHeight(); - - setExteriorAnchor(anchorDest); - - for (HSLFShape shape : getShapes()) { - Rectangle2D chanchor = shape.getAnchor(); - double x = anchorDest.getX()+(chanchor.getX()-anchorSrc.getX())*scaleX; - double y = anchorDest.getY()+(chanchor.getY()-anchorSrc.getY())*scaleY; - double width = chanchor.getWidth()*scaleX; - double height = chanchor.getHeight()*scaleY; - shape.setAnchor(new Rectangle2D.Double(x, y, width, height)); - } - } - - /** - * Returns the anchor (the bounding box rectangle) of this shape group. - * All coordinates are expressed in points (72 dpi). - * - * @return the anchor of this shape group - */ - @Override - public Rectangle2D getAnchor(){ - EscherClientAnchorRecord clientAnchor = getEscherChild(EscherClientAnchorRecord.RECORD_ID); - int x1,y1,x2,y2; - if(clientAnchor == null){ - LOG.log(POILogger.INFO, "EscherClientAnchorRecord was not found for shape group. Searching for EscherChildAnchorRecord."); - EscherChildAnchorRecord rec = getEscherChild(EscherChildAnchorRecord.RECORD_ID); - x1 = rec.getDx1(); - y1 = rec.getDy1(); - x2 = rec.getDx2(); - y2 = rec.getDy2(); - } else { - x1 = clientAnchor.getCol1(); - y1 = clientAnchor.getFlag(); - x2 = clientAnchor.getDx1(); - y2 = clientAnchor.getRow1(); - } - Rectangle2D anchor= new Rectangle2D.Double( - (x1 == -1 ? -1 : Units.masterToPoints(x1)), - (y1 == -1 ? -1 : Units.masterToPoints(y1)), - (x2 == -1 ? -1 : Units.masterToPoints(x2-x1)), - (y2 == -1 ? -1 : Units.masterToPoints(y2-y1)) - ); - - return anchor; - } - - /** - * Return type of the shape. - * In most cases shape group type is {@link org.apache.poi.sl.usermodel.ShapeType#NOT_PRIMITIVE} - * - * @return type of the shape. - */ - @Override - public ShapeType getShapeType(){ - EscherSpRecord spRecord = getEscherChild(EscherSpRecord.RECORD_ID); - int nativeId = spRecord.getOptions() >> 4; - return ShapeType.forId(nativeId, false); - } - - /** - * Returns null - shape groups can't have hyperlinks - * - * @return null. - */ - public HSLFHyperlink getHyperlink(){ - return null; - } - - @Override - public T getEscherChild(int recordId){ - EscherContainerRecord groupInfoContainer = (EscherContainerRecord)getSpContainer().getChild(0); - return groupInfoContainer.getChildById((short)recordId); - } - - @Override - public Iterator iterator() { - return getShapes().iterator(); - } - - @Override - public boolean removeShape(HSLFShape shape) { - // TODO: implement! - throw new UnsupportedOperationException(); - } - - @Override - public List getShapes() { - // Our escher container record should contain several - // SpContainers, the first of which is the group shape itself - List shapeList = new ArrayList(); - boolean isFirst = true; - for (EscherRecord r : getSpContainer()) { - if (isFirst) { - // Don't include the first SpContainer, it is always NotPrimitive - isFirst = false; - continue; - } - - if(r instanceof EscherContainerRecord) { - // Create the Shape for it - EscherContainerRecord container = (EscherContainerRecord)r; - HSLFShape shape = HSLFShapeFactory.createShape(container, this); - shape.setSheet(getSheet()); - shapeList.add( shape ); - } else { - // Should we do anything special with these non - // Container records? - LOG.log(POILogger.ERROR, "Shape contained non container escher record, was " + r.getClass().getName()); - } - } - - return shapeList; - } - - @Override - public HSLFTextBox createTextBox() { - HSLFTextBox s = new HSLFTextBox(this); - s.setHorizontalCentered(true); - s.setAnchor(new Rectangle2D.Double(0, 0, 100, 100)); - addShape(s); - return s; - } - - @Override - public HSLFAutoShape createAutoShape() { - HSLFAutoShape s = new HSLFAutoShape(ShapeType.RECT, this); - s.setHorizontalCentered(true); - s.setAnchor(new Rectangle2D.Double(0, 0, 100, 100)); - addShape(s); - return s; - } - - @Override - public HSLFFreeformShape createFreeform() { - HSLFFreeformShape s = new HSLFFreeformShape(this); - s.setHorizontalCentered(true); - s.setAnchor(new Rectangle2D.Double(0, 0, 100, 100)); - addShape(s); - return s; - } - - @Override - public HSLFConnectorShape createConnector() { - HSLFConnectorShape s = new HSLFConnectorShape(this); - s.setAnchor(new Rectangle2D.Double(0, 0, 100, 100)); - addShape(s); - return s; - } - - @Override - public HSLFGroupShape createGroup() { - HSLFGroupShape s = new HSLFGroupShape(this); - s.setAnchor(new Rectangle2D.Double(0, 0, 100, 100)); - addShape(s); - return s; - } - - @Override - public HSLFPictureShape createPicture(PictureData pictureData) { - if (!(pictureData instanceof HSLFPictureData)) { - throw new IllegalArgumentException("pictureData needs to be of type HSLFPictureData"); - } - HSLFPictureShape s = new HSLFPictureShape((HSLFPictureData)pictureData, this); - s.setAnchor(new Rectangle2D.Double(0, 0, 100, 100)); - addShape(s); - return s; - } - - @Override - public HSLFTable createTable(int numRows, int numCols) { - if (numRows < 1 || numCols < 1) { - throw new IllegalArgumentException("numRows and numCols must be greater than 0"); - } - HSLFTable s = new HSLFTable(numRows,numCols,this); - s.setAnchor(new Rectangle2D.Double(0, 0, 100, 100)); - addShape(s); - return s; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFHyperlink.java b/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFHyperlink.java deleted file mode 100644 index 033f3bbeb..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFHyperlink.java +++ /dev/null @@ -1,402 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.usermodel; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.ListIterator; - -import org.apache.poi.common.usermodel.HyperlinkType; -import org.apache.poi.hslf.record.ExHyperlink; -import org.apache.poi.hslf.record.ExHyperlinkAtom; -import org.apache.poi.hslf.record.ExObjList; -import org.apache.poi.hslf.record.HSLFEscherClientDataRecord; -import org.apache.poi.hslf.record.InteractiveInfo; -import org.apache.poi.hslf.record.InteractiveInfoAtom; -import org.apache.poi.hslf.record.Record; -import org.apache.poi.hslf.record.TxInteractiveInfoAtom; -import org.apache.poi.sl.usermodel.Hyperlink; -import org.apache.poi.sl.usermodel.Slide; - -/** - * Represents a hyperlink in a PowerPoint document - */ -public final class HSLFHyperlink implements Hyperlink { - private final ExHyperlink exHyper; - private final InteractiveInfo info; - private TxInteractiveInfoAtom txinfo; - - protected HSLFHyperlink(ExHyperlink exHyper, InteractiveInfo info) { - this.info = info; - this.exHyper = exHyper; - } - - public ExHyperlink getExHyperlink() { - return exHyper; - } - - public InteractiveInfo getInfo() { - return info; - } - - public TxInteractiveInfoAtom getTextRunInfo() { - return txinfo; - } - - protected void setTextRunInfo(TxInteractiveInfoAtom txinfo) { - this.txinfo = txinfo; - } - - /** - * Creates a new Hyperlink and assign it to a shape - * This is only a helper method - use {@link HSLFSimpleShape#createHyperlink()} instead! - * - * @param shape the shape which receives the hyperlink - * @return the new hyperlink - * - * @see HSLFSimpleShape#createHyperlink() - */ - /* package */ static HSLFHyperlink createHyperlink(HSLFSimpleShape shape) { - // TODO: check if a hyperlink already exists - ExHyperlink exHyper = new ExHyperlink(); - int linkId = shape.getSheet().getSlideShow().addToObjListAtom(exHyper); - ExHyperlinkAtom obj = exHyper.getExHyperlinkAtom(); - obj.setNumber(linkId); - InteractiveInfo info = new InteractiveInfo(); - info.getInteractiveInfoAtom().setHyperlinkID(linkId); - HSLFEscherClientDataRecord cldata = shape.getClientData(true); - cldata.addChild(info); - HSLFHyperlink hyper = new HSLFHyperlink(exHyper, info); - hyper.linkToNextSlide(); - shape.setHyperlink(hyper); - return hyper; - } - - /** - * Creates a new Hyperlink for a textrun. - * This is only a helper method - use {@link HSLFTextRun#createHyperlink()} instead! - * - * @param run the run which receives the hyperlink - * @return the new hyperlink - * - * @see HSLFTextRun#createHyperlink() - */ - /* package */ static HSLFHyperlink createHyperlink(HSLFTextRun run) { - // TODO: check if a hyperlink already exists - ExHyperlink exHyper = new ExHyperlink(); - int linkId = run.getTextParagraph().getSheet().getSlideShow().addToObjListAtom(exHyper); - ExHyperlinkAtom obj = exHyper.getExHyperlinkAtom(); - obj.setNumber(linkId); - InteractiveInfo info = new InteractiveInfo(); - info.getInteractiveInfoAtom().setHyperlinkID(linkId); - // don't add the hyperlink now to text paragraph records - // this will be done, when the paragraph is saved - HSLFHyperlink hyper = new HSLFHyperlink(exHyper, info); - hyper.linkToNextSlide(); - - TxInteractiveInfoAtom txinfo = new TxInteractiveInfoAtom(); - int startIdx = run.getTextParagraph().getStartIdxOfTextRun(run); - int endIdx = startIdx + run.getLength(); - txinfo.setStartIndex(startIdx); - txinfo.setEndIndex(endIdx); - hyper.setTextRunInfo(txinfo); - - run.setHyperlink(hyper); - return hyper; - } - - - /** - * Gets the type of the hyperlink action. - * Must be a LINK_* constant - * - * @return the hyperlink URL - * @see InteractiveInfoAtom - * @deprecated POI 3.15 beta 3. Use {@link #getTypeEnum()} - */ - @Override - public int getType() { - return getTypeEnum().getCode(); - } - - /** - * Gets the type of the hyperlink action. - * Must be a LINK_* constant - * - * @return the hyperlink URL - * @see InteractiveInfoAtom - */ - @Override - public HyperlinkType getTypeEnum() { - switch (info.getInteractiveInfoAtom().getHyperlinkType()) { - case InteractiveInfoAtom.LINK_Url: - return (exHyper.getLinkURL().startsWith("mailto:")) ? HyperlinkType.EMAIL : HyperlinkType.URL; - case InteractiveInfoAtom.LINK_NextSlide: - case InteractiveInfoAtom.LINK_PreviousSlide: - case InteractiveInfoAtom.LINK_FirstSlide: - case InteractiveInfoAtom.LINK_LastSlide: - case InteractiveInfoAtom.LINK_SlideNumber: - return HyperlinkType.DOCUMENT; - case InteractiveInfoAtom.LINK_CustomShow: - case InteractiveInfoAtom.LINK_OtherPresentation: - case InteractiveInfoAtom.LINK_OtherFile: - return HyperlinkType.FILE; - default: - case InteractiveInfoAtom.LINK_NULL: - return HyperlinkType.NONE; - } - } - - @Override - public void linkToEmail(String emailAddress) { - InteractiveInfoAtom iia = info.getInteractiveInfoAtom(); - iia.setAction(InteractiveInfoAtom.ACTION_HYPERLINK); - iia.setJump(InteractiveInfoAtom.JUMP_NONE); - iia.setHyperlinkType(InteractiveInfoAtom.LINK_Url); - exHyper.setLinkURL("mailto:"+emailAddress); - exHyper.setLinkTitle(emailAddress); - exHyper.setLinkOptions(0x10); - } - - @Override - public void linkToUrl(String url) { - InteractiveInfoAtom iia = info.getInteractiveInfoAtom(); - iia.setAction(InteractiveInfoAtom.ACTION_HYPERLINK); - iia.setJump(InteractiveInfoAtom.JUMP_NONE); - iia.setHyperlinkType(InteractiveInfoAtom.LINK_Url); - exHyper.setLinkURL(url); - exHyper.setLinkTitle(url); - exHyper.setLinkOptions(0x10); - } - - @Override - public void linkToSlide(Slide slide) { - assert(slide instanceof HSLFSlide); - HSLFSlide sl = (HSLFSlide)slide; - int slideNum = slide.getSlideNumber(); - String alias = "Slide "+slideNum; - - InteractiveInfoAtom iia = info.getInteractiveInfoAtom(); - iia.setAction(InteractiveInfoAtom.ACTION_HYPERLINK); - iia.setJump(InteractiveInfoAtom.JUMP_NONE); - iia.setHyperlinkType(InteractiveInfoAtom.LINK_SlideNumber); - - linkToDocument(sl._getSheetNumber(),slideNum,alias,0x30); - } - - @Override - public void linkToNextSlide() { - InteractiveInfoAtom iia = info.getInteractiveInfoAtom(); - iia.setAction(InteractiveInfoAtom.ACTION_JUMP); - iia.setJump(InteractiveInfoAtom.JUMP_NEXTSLIDE); - iia.setHyperlinkType(InteractiveInfoAtom.LINK_NextSlide); - - linkToDocument(1,-1,"NEXT",0x10); - } - - @Override - public void linkToPreviousSlide() { - InteractiveInfoAtom iia = info.getInteractiveInfoAtom(); - iia.setAction(InteractiveInfoAtom.ACTION_JUMP); - iia.setJump(InteractiveInfoAtom.JUMP_PREVIOUSSLIDE); - iia.setHyperlinkType(InteractiveInfoAtom.LINK_PreviousSlide); - - linkToDocument(1,-1,"PREV",0x10); - } - - @Override - public void linkToFirstSlide() { - InteractiveInfoAtom iia = info.getInteractiveInfoAtom(); - iia.setAction(InteractiveInfoAtom.ACTION_JUMP); - iia.setJump(InteractiveInfoAtom.JUMP_FIRSTSLIDE); - iia.setHyperlinkType(InteractiveInfoAtom.LINK_FirstSlide); - - linkToDocument(1,-1,"FIRST",0x10); - } - - @Override - public void linkToLastSlide() { - InteractiveInfoAtom iia = info.getInteractiveInfoAtom(); - iia.setAction(InteractiveInfoAtom.ACTION_JUMP); - iia.setJump(InteractiveInfoAtom.JUMP_LASTSLIDE); - iia.setHyperlinkType(InteractiveInfoAtom.LINK_LastSlide); - - linkToDocument(1,-1,"LAST",0x10); - } - - private void linkToDocument(int sheetNumber, int slideNumber, String alias, int options) { - exHyper.setLinkURL(sheetNumber+","+slideNumber+","+alias); - exHyper.setLinkTitle(alias); - exHyper.setLinkOptions(options); - } - - @Override - public String getAddress() { - return exHyper.getLinkURL(); - } - - @Override - public void setAddress(String str) { - exHyper.setLinkURL(str); - } - - public int getId() { - return exHyper.getExHyperlinkAtom().getNumber(); - } - - @Override - public String getLabel() { - return exHyper.getLinkTitle(); - } - - @Override - public void setLabel(String label) { - exHyper.setLinkTitle(label); - } - - /** - * Gets the beginning character position - * - * @return the beginning character position - */ - public int getStartIndex() { - return (txinfo == null) ? -1 : txinfo.getStartIndex(); - } - - /** - * Sets the beginning character position - * - * @param startIndex the beginning character position - */ - public void setStartIndex(int startIndex) { - if (txinfo != null) { - txinfo.setStartIndex(startIndex); - } - } - - /** - * Gets the ending character position - * - * @return the ending character position - */ - public int getEndIndex() { - return (txinfo == null) ? -1 : txinfo.getEndIndex(); - } - - /** - * Sets the ending character position - * - * @param endIndex the ending character position - */ - public void setEndIndex(int endIndex) { - if (txinfo != null) { - txinfo.setEndIndex(endIndex); - } - } - - /** - * Find hyperlinks in a text shape - * - * @param shape TextRun to lookup hyperlinks in - * @return found hyperlinks or null if not found - */ - public static List find(HSLFTextShape shape){ - return find(shape.getTextParagraphs()); - } - - /** - * Find hyperlinks in a text paragraph - * - * @param paragraphs List of TextParagraph to lookup hyperlinks - * @return found hyperlinks - */ - @SuppressWarnings("resource") - protected static List find(List paragraphs){ - List lst = new ArrayList(); - if (paragraphs == null || paragraphs.isEmpty()) return lst; - - HSLFTextParagraph firstPara = paragraphs.get(0); - - HSLFSlideShow ppt = firstPara.getSheet().getSlideShow(); - //document-level container which stores info about all links in a presentation - ExObjList exobj = ppt.getDocumentRecord().getExObjList(false); - if (exobj != null) { - Record[] records = firstPara.getRecords(); - find(Arrays.asList(records), exobj, lst); - } - - return lst; - } - - /** - * Find hyperlink assigned to the supplied shape - * - * @param shape Shape to lookup hyperlink in - * @return found hyperlink or null - */ - @SuppressWarnings("resource") - protected static HSLFHyperlink find(HSLFShape shape){ - HSLFSlideShow ppt = shape.getSheet().getSlideShow(); - //document-level container which stores info about all links in a presentation - ExObjList exobj = ppt.getDocumentRecord().getExObjList(false); - HSLFEscherClientDataRecord cldata = shape.getClientData(false); - - if (exobj != null && cldata != null) { - List lst = new ArrayList(); - find(cldata.getHSLFChildRecords(), exobj, lst); - return lst.isEmpty() ? null : (HSLFHyperlink)lst.get(0); - } - - return null; - } - - private static void find(List records, ExObjList exobj, List out){ - ListIterator iter = records.listIterator(); - while (iter.hasNext()) { - Record r = iter.next(); - // see if we have InteractiveInfo in the textrun's records - if (!(r instanceof InteractiveInfo)) { - continue; - } - - InteractiveInfo hldr = (InteractiveInfo)r; - InteractiveInfoAtom info = hldr.getInteractiveInfoAtom(); - if (info == null) { - continue; - } - int id = info.getHyperlinkID(); - ExHyperlink exHyper = exobj.get(id); - if (exHyper == null) { - continue; - } - - HSLFHyperlink link = new HSLFHyperlink(exHyper, hldr); - out.add(link); - - if (iter.hasNext()) { - r = iter.next(); - if (!(r instanceof TxInteractiveInfoAtom)) { - iter.previous(); - continue; - } - link.setTextRunInfo((TxInteractiveInfoAtom)r); - } - } - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFLine.java b/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFLine.java deleted file mode 100644 index 668b3e88e..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFLine.java +++ /dev/null @@ -1,90 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.usermodel; - -import org.apache.poi.ddf.AbstractEscherOptRecord; -import org.apache.poi.ddf.EscherContainerRecord; -import org.apache.poi.ddf.EscherProperties; -import org.apache.poi.ddf.EscherSpRecord; -import org.apache.poi.sl.usermodel.Line; -import org.apache.poi.sl.usermodel.ShapeContainer; -import org.apache.poi.sl.usermodel.ShapeType; - -/** - * Represents a line in a PowerPoint drawing - * - * @author Yegor Kozlov - */ -public final class HSLFLine extends HSLFTextShape implements Line { - public HSLFLine(EscherContainerRecord escherRecord, ShapeContainer parent){ - super(escherRecord, parent); - } - - public HSLFLine(ShapeContainer parent){ - super(null, parent); - createSpContainer(parent instanceof HSLFGroupShape); - } - - public HSLFLine(){ - this(null); - } - - @Override - protected EscherContainerRecord createSpContainer(boolean isChild){ - EscherContainerRecord ecr = super.createSpContainer(isChild); - - setShapeType(ShapeType.LINE); - - EscherSpRecord spRecord = ecr.getChildById(EscherSpRecord.RECORD_ID); - short type = (short)((ShapeType.LINE.nativeId << 4) | 0x2); - spRecord.setOptions(type); - - //set default properties for a line - AbstractEscherOptRecord opt = getEscherOptRecord(); - - //default line properties - setEscherProperty(opt, EscherProperties.GEOMETRY__SHAPEPATH, 4); - setEscherProperty(opt, EscherProperties.GEOMETRY__FILLOK, 0x10000); - setEscherProperty(opt, EscherProperties.FILL__NOFILLHITTEST, 0x100000); - setEscherProperty(opt, EscherProperties.LINESTYLE__COLOR, 0x8000001); - setEscherProperty(opt, EscherProperties.LINESTYLE__NOLINEDRAWDASH, 0xA0008); - setEscherProperty(opt, EscherProperties.SHADOWSTYLE__COLOR, 0x8000002); - - return ecr; - } - -// /** -// * Sets the orientation of the line, if inverse is false, then line goes -// * from top-left to bottom-right, otherwise use inverse equals true -// * -// * @param inverse the orientation of the line -// */ -// public void setInverse(boolean inverse) { -// setShapeType(inverse ? ShapeType.LINE_INV : ShapeType.LINE); -// } -// -// /** -// * Gets the orientation of the line, if inverse is false, then line goes -// * from top-left to bottom-right, otherwise inverse equals true -// * -// * @return inverse the orientation of the line -// */ -// public boolean isInverse() { -// return (getShapeType() == ShapeType.LINE_INV); -// } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFMasterSheet.java b/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFMasterSheet.java deleted file mode 100644 index d73374620..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFMasterSheet.java +++ /dev/null @@ -1,56 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.usermodel; - -import org.apache.poi.hslf.record.SheetContainer; -import org.apache.poi.hslf.model.textproperties.TextProp; -import org.apache.poi.sl.usermodel.MasterSheet; - -/** - * The superclass of all master sheets - Slide masters, Notes masters, etc. - * - * For now it's empty. When we understand more about masters in ppt we will add the common functionality here. - * - * @author Yegor Kozlov - */ -public abstract class HSLFMasterSheet extends HSLFSheet implements MasterSheet { - public HSLFMasterSheet(SheetContainer container, int sheetNo){ - super(container, sheetNo); - } - - /** - * Pickup a style attribute from the master. - * This is the "workhorse" which returns the default style attrubutes. - */ - public abstract TextProp getStyleAttribute(int txtype, int level, String name, boolean isCharacter) ; - - - /** - * Checks if the shape is a placeholder. - * (placeholders aren't normal shapes, they are visible only in the Edit Master mode) - * - * - * @return true if the shape is a placeholder - */ - public static boolean isPlaceholder(HSLFShape shape){ - if(!(shape instanceof HSLFTextShape)) return false; - - HSLFTextShape tx = (HSLFTextShape)shape; - return tx.getPlaceholderAtom() != null; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFNotes.java b/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFNotes.java deleted file mode 100644 index d64775e11..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFNotes.java +++ /dev/null @@ -1,75 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.usermodel; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.sl.usermodel.Notes; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; - -/** - * This class represents a slide's notes in a PowerPoint Document. It - * allows access to the text within, and the layout. For now, it only - * does the text side of things though - * - * @author Nick Burch - */ - -public final class HSLFNotes extends HSLFSheet implements Notes { - protected static final POILogger logger = POILogFactory.getLogger(HSLFNotes.class); - - private List> _paragraphs = new ArrayList>(); - - /** - * Constructs a Notes Sheet from the given Notes record. - * Initialises TextRuns, to provide easier access to the text - * - * @param notes the Notes record to read from - */ - public HSLFNotes(org.apache.poi.hslf.record.Notes notes) { - super(notes, notes.getNotesAtom().getSlideID()); - - // Now, build up TextRuns from pairs of TextHeaderAtom and - // one of TextBytesAtom or TextCharsAtom, found inside - // EscherTextboxWrapper's in the PPDrawing - for (List l : HSLFTextParagraph.findTextParagraphs(getPPDrawing(), this)) { - if (!_paragraphs.contains(l)) _paragraphs.add(l); - } - - if (_paragraphs.isEmpty()) { - logger.log(POILogger.WARN, "No text records found for notes sheet"); - } - } - - /** - * Returns an array of all the TextParagraphs found - */ - @Override - public List> getTextParagraphs() { - return _paragraphs; - } - - /** - * Return null - Notes Masters are not yet supported - */ - public HSLFMasterSheet getMasterSheet() { - return null; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFObjectData.java b/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFObjectData.java deleted file mode 100644 index f02ddbe78..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFObjectData.java +++ /dev/null @@ -1,70 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hslf.usermodel; - -import java.io.InputStream; -import java.io.IOException; - -import org.apache.poi.hslf.record.ExOleObjStg; - -/** - * A class that represents object data embedded in a slide show. - * - * @author Daniel Noll - */ -public class HSLFObjectData { - /** - * The record that contains the object data. - */ - private ExOleObjStg storage; - - /** - * Creates the object data wrapping the record that contains the object data. - * - * @param storage the record that contains the object data. - */ - public HSLFObjectData(ExOleObjStg storage) { - this.storage = storage; - } - - /** - * Gets an input stream which returns the binary of the embedded data. - * - * @return the input stream which will contain the binary of the embedded data. - */ - public InputStream getData() { - return storage.getData(); - } - - /** - * Sets the embedded data. - * - * @param data the embedded data. - */ - public void setData(byte[] data) throws IOException { - storage.setData(data); - } - - /** - * Return the record that contains the object data. - * - * @return the record that contains the object data. - */ - public ExOleObjStg getExOleObjStg() { - return storage; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFPictureData.java b/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFPictureData.java deleted file mode 100644 index 1a8061d3c..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFPictureData.java +++ /dev/null @@ -1,229 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.usermodel; - -import java.awt.Dimension; -import java.io.IOException; -import java.io.OutputStream; -import java.security.MessageDigest; - -import org.apache.poi.hslf.blip.*; -import org.apache.poi.poifs.crypt.CryptoFunctions; -import org.apache.poi.poifs.crypt.HashAlgorithm; -import org.apache.poi.sl.usermodel.PictureData; -import org.apache.poi.util.*; - -/** - * A class that represents image data contained in a slide show. - */ -public abstract class HSLFPictureData implements PictureData { - - /** - * Size of the image checksum calculated using MD5 algorithm. - */ - protected static final int CHECKSUM_SIZE = 16; - - /** - * Binary data of the picture - */ - private byte[] rawdata; - /** - * The offset to the picture in the stream - */ - private int offset; - - /** - * The instance type/signatures defines if one or two UID instances will be included - */ - private int uidInstanceCount = 1; - - /** - * The 1-based index within the pictures stream - */ - private int index = -1; - - /** - * Blip signature. - */ - protected abstract int getSignature(); - - public abstract void setSignature(int signature); - - /** - * The instance type/signatures defines if one or two UID instances will be included - */ - protected int getUIDInstanceCount() { - return uidInstanceCount; - } - - /** - * The instance type/signatures defines if one or two UID instances will be included - * - * @param uidInstanceCount the number of uid sequences - */ - protected void setUIDInstanceCount(int uidInstanceCount) { - this.uidInstanceCount = uidInstanceCount; - } - - /** - * Returns the raw binary data of this Picture excluding the first 8 bytes - * which hold image signature and size of the image data. - * - * @return picture data - */ - public byte[] getRawData(){ - return rawdata; - } - - public void setRawData(byte[] data){ - rawdata = (data == null) ? null : data.clone(); - } - - /** - * File offset in the 'Pictures' stream - * - * @return offset in the 'Pictures' stream - */ - public int getOffset(){ - return offset; - } - - /** - * Set offset of this picture in the 'Pictures' stream. - * We need to set it when a new picture is created. - * - * @param offset in the 'Pictures' stream - */ - public void setOffset(int offset){ - this.offset = offset; - } - - /** - * Returns 16-byte checksum of this picture - */ - public byte[] getUID(){ - byte[] uid = new byte[16]; - System.arraycopy(rawdata, 0, uid, 0, uid.length); - return uid; - } - - @Override - public byte[] getChecksum() { - return getChecksum(getData()); - } - - /** - * Compute 16-byte checksum of this picture using MD5 algorithm. - */ - public static byte[] getChecksum(byte[] data) { - MessageDigest md5 = CryptoFunctions.getMessageDigest(HashAlgorithm.md5); - md5.update(data); - return md5.digest(); - } - - /** - * Write this picture into OutputStream - */ - public void write(OutputStream out) throws IOException { - byte[] data; - - data = new byte[LittleEndian.SHORT_SIZE]; - LittleEndian.putUShort(data, 0, getSignature()); - out.write(data); - - data = new byte[LittleEndian.SHORT_SIZE]; - PictureType pt = getType(); - LittleEndian.putUShort(data, 0, pt.nativeId + 0xF018); - out.write(data); - - byte[] rd = getRawData(); - - data = new byte[LittleEndian.INT_SIZE]; - LittleEndian.putInt(data, 0, rd.length); - out.write(data); - - out.write(rd); - } - - /** - * Create an instance of PictureData by type. - * - * @param type type of the picture data. - * Must be one of the static constants defined in the Picture class. - * @return concrete instance of PictureData - */ - public static HSLFPictureData create(PictureType type){ - HSLFPictureData pict; - switch (type){ - case EMF: pict = new EMF(); break; - case WMF: pict = new WMF(); break; - case PICT: pict = new PICT(); break; - case JPEG: pict = new JPEG(); break; - case PNG: pict = new PNG(); break; - case DIB: pict = new DIB(); break; - default: - throw new IllegalArgumentException("Unsupported picture type: " + type); - } - return pict; - } - - /** - * Return 24 byte header which preceeds the actual picture data. - *

    - * The header consists of 2-byte signature, 2-byte type, - * 4-byte image size and 16-byte checksum of the image data. - *

    - * - * @return the 24 byte header which preceeds the actual picture data. - */ - public byte[] getHeader() { - byte[] header = new byte[16 + 8]; - LittleEndian.putInt(header, 0, getSignature()); - LittleEndian.putInt(header, 4, getRawData().length); - System.arraycopy(rawdata, 0, header, 8, 16); - return header; - } - - /** - * @return the 1-based index of this pictures within the pictures stream - */ - public int getIndex() { - return index; - } - - /** - * @param index sets the 1-based index of this pictures within the pictures stream - */ - public void setIndex(int index) { - this.index = index; - } - - @Override - public final String getContentType() { - return getType().contentType; - } - - @Override - public Dimension getImageDimensionInPixels() { - Dimension dim = getImageDimension(); - return new Dimension( - Units.pointsToPixel(dim.getWidth()), - Units.pointsToPixel(dim.getHeight()) - ); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFPictureShape.java b/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFPictureShape.java deleted file mode 100644 index deee5e61f..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFPictureShape.java +++ /dev/null @@ -1,229 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.usermodel; - -import java.awt.Insets; -import java.awt.geom.Rectangle2D; -import java.util.List; - -import org.apache.poi.ddf.AbstractEscherOptRecord; -import org.apache.poi.ddf.EscherBSERecord; -import org.apache.poi.ddf.EscherComplexProperty; -import org.apache.poi.ddf.EscherContainerRecord; -import org.apache.poi.ddf.EscherProperties; -import org.apache.poi.ddf.EscherRecord; -import org.apache.poi.ddf.EscherSimpleProperty; -import org.apache.poi.ddf.EscherSpRecord; -import org.apache.poi.hslf.record.Document; -import org.apache.poi.sl.draw.DrawPictureShape; -import org.apache.poi.sl.usermodel.PictureShape; -import org.apache.poi.sl.usermodel.ShapeContainer; -import org.apache.poi.sl.usermodel.ShapeType; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.util.StringUtil; -import org.apache.poi.util.Units; - - -/** - * Represents a picture in a PowerPoint document. - */ -public class HSLFPictureShape extends HSLFSimpleShape implements PictureShape { - private static final POILogger LOG = POILogFactory.getLogger(HSLFPictureShape.class); - - /** - * Create a new Picture - * - * @param data the picture data - */ - public HSLFPictureShape(HSLFPictureData data){ - this(data, null); - } - - /** - * Create a new Picture - * - * @param data the picture data - * @param parent the parent shape - */ - public HSLFPictureShape(HSLFPictureData data, ShapeContainer parent) { - super(null, parent); - createSpContainer(data.getIndex(), parent instanceof HSLFGroupShape); - } - - /** - * Create a Picture object - * - * @param escherRecord the EscherSpContainer record which holds information about - * this picture in the Slide - * @param parent the parent shape of this picture - */ - protected HSLFPictureShape(EscherContainerRecord escherRecord, ShapeContainer parent){ - super(escherRecord, parent); - } - - /** - * Returns index associated with this picture. - * Index starts with 1 and points to a EscherBSE record which - * holds information about this picture. - * - * @return the index to this picture (1 based). - */ - public int getPictureIndex(){ - AbstractEscherOptRecord opt = getEscherOptRecord(); - EscherSimpleProperty prop = getEscherProperty(opt, EscherProperties.BLIP__BLIPTODISPLAY); - return prop == null ? 0 : prop.getPropertyValue(); - } - - /** - * Create a new Picture and populate the inital structure of the EscherSp record which holds information about this picture. - - * @param idx the index of the picture which refers to EscherBSE container. - * @return the create Picture object - */ - protected EscherContainerRecord createSpContainer(int idx, boolean isChild) { - EscherContainerRecord ecr = super.createSpContainer(isChild); - - EscherSpRecord spRecord = ecr.getChildById(EscherSpRecord.RECORD_ID); - spRecord.setOptions((short)((ShapeType.FRAME.nativeId << 4) | 0x2)); - - //set default properties for a picture - AbstractEscherOptRecord opt = getEscherOptRecord(); - setEscherProperty(opt, EscherProperties.PROTECTION__LOCKAGAINSTGROUPING, 0x800080); - - //another weird feature of powerpoint: for picture id we must add 0x4000. - setEscherProperty(opt, (short)(EscherProperties.BLIP__BLIPTODISPLAY + 0x4000), idx); - - return ecr; - } - - @SuppressWarnings("resource") - @Override - public HSLFPictureData getPictureData(){ - HSLFSlideShow ppt = getSheet().getSlideShow(); - List pict = ppt.getPictureData(); - - EscherBSERecord bse = getEscherBSERecord(); - if (bse == null){ - LOG.log(POILogger.ERROR, "no reference to picture data found "); - } else { - for (HSLFPictureData pd : pict) { - if (pd.getOffset() == bse.getOffset()){ - return pd; - } - } - LOG.log(POILogger.ERROR, "no picture found for our BSE offset " + bse.getOffset()); - } - return null; - } - - @SuppressWarnings("resource") - protected EscherBSERecord getEscherBSERecord(){ - HSLFSlideShow ppt = getSheet().getSlideShow(); - Document doc = ppt.getDocumentRecord(); - EscherContainerRecord dggContainer = doc.getPPDrawingGroup().getDggContainer(); - EscherContainerRecord bstore = HSLFShape.getEscherChild(dggContainer, EscherContainerRecord.BSTORE_CONTAINER); - if(bstore == null) { - LOG.log(POILogger.DEBUG, "EscherContainerRecord.BSTORE_CONTAINER was not found "); - return null; - } - List lst = bstore.getChildRecords(); - int idx = getPictureIndex(); - if (idx == 0){ - LOG.log(POILogger.DEBUG, "picture index was not found, returning "); - return null; - } - return (EscherBSERecord)lst.get(idx-1); - } - - /** - * Name of this picture. - * - * @return name of this picture - */ - public String getPictureName(){ - AbstractEscherOptRecord opt = getEscherOptRecord(); - EscherComplexProperty prop = getEscherProperty(opt, EscherProperties.BLIP__BLIPFILENAME); - if (prop == null) return null; - String name = StringUtil.getFromUnicodeLE(prop.getComplexData()); - return name.trim(); - } - - /** - * Name of this picture. - * - * @param name of this picture - */ - public void setPictureName(String name){ - AbstractEscherOptRecord opt = getEscherOptRecord(); - byte[] data = StringUtil.getToUnicodeLE(name + '\u0000'); - EscherComplexProperty prop = new EscherComplexProperty(EscherProperties.BLIP__BLIPFILENAME, false, data); - opt.addEscherProperty(prop); - } - - /** - * By default set the orininal image size - */ - @Override - protected void afterInsert(HSLFSheet sh){ - super.afterInsert(sh); - - EscherBSERecord bse = getEscherBSERecord(); - bse.setRef(bse.getRef() + 1); - - Rectangle2D anchor = getAnchor(); - if (anchor.isEmpty()){ - new DrawPictureShape(this).resize(); - } - } - - - @Override - public Insets getClipping() { - // The anchor specified by the escher properties is the displayed size, - // i.e. the size of the already clipped image - AbstractEscherOptRecord opt = getEscherOptRecord(); - - double top = getFractProp(opt, EscherProperties.BLIP__CROPFROMTOP); - double bottom = getFractProp(opt, EscherProperties.BLIP__CROPFROMBOTTOM); - double left = getFractProp(opt, EscherProperties.BLIP__CROPFROMLEFT); - double right = getFractProp(opt, EscherProperties.BLIP__CROPFROMRIGHT); - - // if all crop values are zero (the default) then no crop rectangle is set, return null - return (top==0 && bottom==0 && left==0 && right==0) - ? null - : new Insets((int)(top*100000), (int)(left*100000), (int)(bottom*100000), (int)(right*100000)); - } - - @Override - public ShapeType getShapeType() { - // this is kind of a hack, as picture/ole shapes can have a shape type of "frame" - // but rendering is handled like a rectangle - return ShapeType.RECT; - } - - /** - * @return the fractional property or 0 if not defined - */ - private static double getFractProp(AbstractEscherOptRecord opt, short propertyId) { - EscherSimpleProperty prop = getEscherProperty(opt, propertyId); - if (prop == null) return 0; - int fixedPoint = prop.getPropertyValue(); - return Units.fixedPointToDouble(fixedPoint); - } -} \ No newline at end of file diff --git a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFPlaceholder.java b/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFPlaceholder.java deleted file mode 100644 index 4b1330059..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFPlaceholder.java +++ /dev/null @@ -1,56 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.usermodel; - -import org.apache.poi.ddf.EscherContainerRecord; -import org.apache.poi.sl.usermodel.Placeholder; -import org.apache.poi.sl.usermodel.ShapeContainer; - -/** - * Represents a Placeholder in PowerPoint. - * - * @author Yegor Kozlov - */ -public final class HSLFPlaceholder extends HSLFTextBox { - - protected HSLFPlaceholder(EscherContainerRecord escherRecord, ShapeContainer parent){ - super(escherRecord, parent); - } - - public HSLFPlaceholder(ShapeContainer parent){ - super(parent); - } - - public HSLFPlaceholder(){ - super(); - } - - /** - * Create a new Placeholder and initialize internal structures - * - * @return the created EscherContainerRecord which holds shape data - */ - @Override - protected EscherContainerRecord createSpContainer(boolean isChild){ - EscherContainerRecord ecr = super.createSpContainer(isChild); - - setPlaceholder(Placeholder.BODY); - - return ecr; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFShape.java b/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFShape.java deleted file mode 100644 index 49b7ca567..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFShape.java +++ /dev/null @@ -1,659 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.usermodel; - -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.geom.Rectangle2D; -import java.util.Iterator; -import java.util.List; - -import org.apache.poi.ddf.AbstractEscherOptRecord; -import org.apache.poi.ddf.EscherChildAnchorRecord; -import org.apache.poi.ddf.EscherClientAnchorRecord; -import org.apache.poi.ddf.EscherClientDataRecord; -import org.apache.poi.ddf.EscherColorRef; -import org.apache.poi.ddf.EscherColorRef.SysIndexProcedure; -import org.apache.poi.ddf.EscherColorRef.SysIndexSource; -import org.apache.poi.ddf.EscherContainerRecord; -import org.apache.poi.ddf.EscherProperties; -import org.apache.poi.ddf.EscherProperty; -import org.apache.poi.ddf.EscherRecord; -import org.apache.poi.ddf.EscherSimpleProperty; -import org.apache.poi.ddf.EscherSpRecord; -import org.apache.poi.ddf.EscherTextboxRecord; -import org.apache.poi.hslf.record.ColorSchemeAtom; -import org.apache.poi.hslf.record.HSLFEscherClientDataRecord; -import org.apache.poi.hslf.record.Record; -import org.apache.poi.hslf.record.RecordTypes; -import org.apache.poi.sl.draw.DrawFactory; -import org.apache.poi.sl.usermodel.FillStyle; -import org.apache.poi.sl.usermodel.PresetColor; -import org.apache.poi.sl.usermodel.Shape; -import org.apache.poi.sl.usermodel.ShapeContainer; -import org.apache.poi.sl.usermodel.ShapeType; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.util.Units; - -/** - *

    - * Represents a Shape which is the elemental object that composes a drawing. - * This class is a wrapper around EscherSpContainer which holds all information - * about a shape in PowerPoint document. - *

    - *

    - * When you add a shape, you usually specify the dimensions of the shape and the position - * of the upper'left corner of the bounding box for the shape relative to the upper'left - * corner of the page, worksheet, or slide. Distances in the drawing layer are measured - * in points (72 points = 1 inch). - *

    - *

    - */ -public abstract class HSLFShape implements Shape { - private static final POILogger LOG = POILogFactory.getLogger(HSLFShape.class); - - /** - * Either EscherSpContainer or EscheSpgrContainer record - * which holds information about this shape. - */ - private EscherContainerRecord _escherContainer; - - /** - * Parent of this shape. - * null for the topmost shapes. - */ - private ShapeContainer _parent; - - /** - * The Sheet this shape belongs to - */ - private HSLFSheet _sheet; - - /** - * Fill - */ - private HSLFFill _fill; - - /** - * Create a Shape object. This constructor is used when an existing Shape is read from from a PowerPoint document. - * - * @param escherRecord EscherSpContainer container which holds information about this shape - * @param parent the parent of this Shape - */ - protected HSLFShape(EscherContainerRecord escherRecord, ShapeContainer parent){ - _escherContainer = escherRecord; - _parent = parent; - } - - /** - * Create and assign the lower level escher record to this shape - */ - protected EscherContainerRecord createSpContainer(boolean isChild) { - if (_escherContainer == null) { - _escherContainer = new EscherContainerRecord(); - _escherContainer.setOptions((short)15); - } - return _escherContainer; - } - - /** - * @return the parent of this shape - */ - @Override - public ShapeContainer getParent(){ - return _parent; - } - - /** - * @return name of the shape. - */ - public String getShapeName(){ - return getShapeType().nativeName; - } - - public ShapeType getShapeType(){ - EscherSpRecord spRecord = getEscherChild(EscherSpRecord.RECORD_ID); - return ShapeType.forId(spRecord.getShapeType(), false); - } - - public void setShapeType(ShapeType type){ - EscherSpRecord spRecord = getEscherChild(EscherSpRecord.RECORD_ID); - spRecord.setShapeType( (short) type.nativeId ); - spRecord.setVersion( (short) 0x2 ); - } - - /** - * Returns the anchor (the bounding box rectangle) of this shape. - * All coordinates are expressed in points (72 dpi). - * - * @return the anchor of this shape - */ - @Override - public Rectangle2D getAnchor() { - EscherSpRecord spRecord = getEscherChild(EscherSpRecord.RECORD_ID); - int flags = spRecord.getFlags(); - int x1,y1,x2,y2; - EscherChildAnchorRecord childRec = getEscherChild(EscherChildAnchorRecord.RECORD_ID); - boolean useChildRec = ((flags & EscherSpRecord.FLAG_CHILD) != 0); - if (useChildRec && childRec != null){ - x1 = childRec.getDx1(); - y1 = childRec.getDy1(); - x2 = childRec.getDx2(); - y2 = childRec.getDy2(); - } else { - if (useChildRec) { - LOG.log(POILogger.WARN, "EscherSpRecord.FLAG_CHILD is set but EscherChildAnchorRecord was not found"); - } - EscherClientAnchorRecord clientRec = getEscherChild(EscherClientAnchorRecord.RECORD_ID); - x1 = clientRec.getCol1(); - y1 = clientRec.getFlag(); - x2 = clientRec.getDx1(); - y2 = clientRec.getRow1(); - } - - // TODO: find out where this -1 value comes from at #57820 (link to ms docs?) - Rectangle2D anchor = new Rectangle2D.Double( - (x1 == -1 ? -1 : Units.masterToPoints(x1)), - (y1 == -1 ? -1 : Units.masterToPoints(y1)), - (x2 == -1 ? -1 : Units.masterToPoints(x2-x1)), - (y2 == -1 ? -1 : Units.masterToPoints(y2-y1)) - ); - - return anchor; - } - - /** - * Sets the anchor (the bounding box rectangle) of this shape. - * All coordinates should be expressed in points (72 dpi). - * - * @param anchor new anchor - */ - public void setAnchor(Rectangle2D anchor){ - int x = Units.pointsToMaster(anchor.getX()); - int y = Units.pointsToMaster(anchor.getY()); - int w = Units.pointsToMaster(anchor.getWidth() + anchor.getX()); - int h = Units.pointsToMaster(anchor.getHeight() + anchor.getY()); - EscherSpRecord spRecord = getEscherChild(EscherSpRecord.RECORD_ID); - int flags = spRecord.getFlags(); - if ((flags & EscherSpRecord.FLAG_CHILD) != 0){ - EscherChildAnchorRecord rec = (EscherChildAnchorRecord)getEscherChild(EscherChildAnchorRecord.RECORD_ID); - rec.setDx1(x); - rec.setDy1(y); - rec.setDx2(w); - rec.setDy2(h); - } else { - EscherClientAnchorRecord rec = (EscherClientAnchorRecord)getEscherChild(EscherClientAnchorRecord.RECORD_ID); - rec.setCol1((short)x); - rec.setFlag((short)y); - rec.setDx1((short)w); - rec.setRow1((short)h); - } - - } - - /** - * Moves the top left corner of the shape to the specified point. - * - * @param x the x coordinate of the top left corner of the shape - * @param y the y coordinate of the top left corner of the shape - */ - public final void moveTo(double x, double y) { - // This convenience method should be implemented via setAnchor in subclasses - // see HSLFGroupShape.setAnchor() for a reference - Rectangle2D anchor = getAnchor(); - anchor.setRect(x, y, anchor.getWidth(), anchor.getHeight()); - setAnchor(anchor); - } - - /** - * Helper method to return escher child by record ID - * - * @return escher record or null if not found. - */ - public static T getEscherChild(EscherContainerRecord owner, int recordId){ - return owner.getChildById((short)recordId); - } - - /** - * @since POI 3.14-Beta2 - */ - public static T getEscherChild(EscherContainerRecord owner, RecordTypes recordId){ - return getEscherChild(owner, recordId.typeID); - } - - public T getEscherChild(int recordId){ - return _escherContainer.getChildById((short)recordId); - } - - /** - * @since POI 3.14-Beta2 - */ - public T getEscherChild(RecordTypes recordId){ - return getEscherChild(recordId.typeID); - } - - /** - * Returns escher property by id. - * - * @return escher property or null if not found. - */ - public static T getEscherProperty(AbstractEscherOptRecord opt, int propId){ - return (opt == null) ? null : opt.lookup(propId); - } - - /** - * Set an escher property for this shape. - * - * @param opt The opt record to set the properties to. - * @param propId The id of the property. One of the constants defined in EscherOptRecord. - * @param value value of the property. If value = -1 then the property is removed. - */ - public static void setEscherProperty(AbstractEscherOptRecord opt, short propId, int value){ - java.util.List props = opt.getEscherProperties(); - for ( Iterator iterator = props.iterator(); iterator.hasNext(); ) { - if (iterator.next().getPropertyNumber() == propId){ - iterator.remove(); - break; - } - } - if (value != -1) { - opt.addEscherProperty(new EscherSimpleProperty(propId, value)); - opt.sortProperties(); - } - } - - /** - * Set an simple escher property for this shape. - * - * @param propId The id of the property. One of the constants defined in EscherOptRecord. - * @param value value of the property. If value = -1 then the property is removed. - */ - public void setEscherProperty(short propId, int value){ - AbstractEscherOptRecord opt = getEscherOptRecord(); - setEscherProperty(opt, propId, value); - } - - /** - * Get the value of a simple escher property for this shape. - * - * @param propId The id of the property. One of the constants defined in EscherOptRecord. - */ - public int getEscherProperty(short propId){ - AbstractEscherOptRecord opt = getEscherOptRecord(); - EscherSimpleProperty prop = getEscherProperty(opt, propId); - return prop == null ? 0 : prop.getPropertyValue(); - } - - /** - * Get the value of a simple escher property for this shape. - * - * @param propId The id of the property. One of the constants defined in EscherOptRecord. - */ - public int getEscherProperty(short propId, int defaultValue){ - AbstractEscherOptRecord opt = getEscherOptRecord(); - EscherSimpleProperty prop = getEscherProperty(opt, propId); - return prop == null ? defaultValue : prop.getPropertyValue(); - } - - /** - * @return The shape container and it's children that can represent this - * shape. - */ - public EscherContainerRecord getSpContainer(){ - return _escherContainer; - } - - /** - * Event which fires when a shape is inserted in the sheet. - * In some cases we need to propagate changes to upper level containers. - *
    - * Default implementation does nothing. - * - * @param sh - owning shape - */ - protected void afterInsert(HSLFSheet sh){ - if(_fill != null) { - _fill.afterInsert(sh); - } - } - - /** - * @return the SlideShow this shape belongs to - */ - @Override - public HSLFSheet getSheet(){ - return _sheet; - } - - /** - * Assign the SlideShow this shape belongs to - * - * @param sheet owner of this shape - */ - public void setSheet(HSLFSheet sheet){ - _sheet = sheet; - } - - Color getColor(short colorProperty, short opacityProperty, int defaultColor){ - AbstractEscherOptRecord opt = getEscherOptRecord(); - EscherSimpleProperty p = getEscherProperty(opt, colorProperty); - if(p == null && defaultColor == -1) return null; - - int val = (p == null) ? defaultColor : p.getPropertyValue(); - - EscherColorRef ecr = new EscherColorRef(val); - Color col = getColor(ecr); - if (col == null) { - return null; - } - - double alpha = getAlpha(opacityProperty); - return new Color(col.getRed(), col.getGreen(), col.getBlue(), (int)(alpha*255.0)); - } - - Color getColor(EscherColorRef ecr) { - boolean fPaletteIndex = ecr.hasPaletteIndexFlag(); - boolean fPaletteRGB = ecr.hasPaletteRGBFlag(); - boolean fSystemRGB = ecr.hasSystemRGBFlag(); - boolean fSchemeIndex = ecr.hasSchemeIndexFlag(); - boolean fSysIndex = ecr.hasSysIndexFlag(); - - int rgb[] = ecr.getRGB(); - - HSLFSheet sheet = getSheet(); - if (fSchemeIndex && sheet != null) { - //red is the index to the color scheme - ColorSchemeAtom ca = sheet.getColorScheme(); - int schemeColor = ca.getColor(ecr.getSchemeIndex()); - - rgb[0] = (schemeColor >> 0) & 0xFF; - rgb[1] = (schemeColor >> 8) & 0xFF; - rgb[2] = (schemeColor >> 16) & 0xFF; - } else if (fPaletteIndex) { - //TODO - } else if (fPaletteRGB) { - //TODO - } else if (fSystemRGB) { - //TODO - } else if (fSysIndex) { - Color col = getSysIndexColor(ecr); - col = applySysIndexProcedure(ecr, col); - return col; - } - - return new Color(rgb[0], rgb[1], rgb[2]); - } - - private Color getSysIndexColor(EscherColorRef ecr) { - SysIndexSource sis = ecr.getSysIndexSource(); - if (sis == null) { - int sysIdx = ecr.getSysIndex(); - PresetColor pc = PresetColor.valueOfNativeId(sysIdx); - return (pc != null) ? pc.color : null; - } - - // TODO: check for recursive loops, when color getter also reference - // a different color type - switch (sis) { - case FILL_COLOR: { - return getFill().getForegroundColor(); - } - case LINE_OR_FILL_COLOR: { - Color col = null; - if (this instanceof HSLFSimpleShape) { - col = ((HSLFSimpleShape)this).getLineColor(); - } - if (col == null) { - col = getFill().getForegroundColor(); - } - return col; - } - case LINE_COLOR: { - if (this instanceof HSLFSimpleShape) { - return ((HSLFSimpleShape)this).getLineColor(); - } - break; - } - case SHADOW_COLOR: { - if (this instanceof HSLFSimpleShape) { - return ((HSLFSimpleShape)this).getShadowColor(); - } - break; - } - case CURRENT_OR_LAST_COLOR: { - // TODO ... read from graphics context??? - break; - } - case FILL_BACKGROUND_COLOR: { - return getFill().getBackgroundColor(); - } - case LINE_BACKGROUND_COLOR: { - if (this instanceof HSLFSimpleShape) { - return ((HSLFSimpleShape)this).getLineBackgroundColor(); - } - break; - } - case FILL_OR_LINE_COLOR: { - Color col = getFill().getForegroundColor(); - if (col == null && this instanceof HSLFSimpleShape) { - col = ((HSLFSimpleShape)this).getLineColor(); - } - return col; - } - default: - break; - } - - return null; - } - - private Color applySysIndexProcedure(EscherColorRef ecr, Color col) { - - final SysIndexProcedure sip = ecr.getSysIndexProcedure(); - if (col == null || sip == null) { - return col; - } - - switch (sip) { - case DARKEN_COLOR: { - // see java.awt.Color#darken() - double FACTOR = (ecr.getRGB()[2])/255.; - int r = (int)Math.rint(col.getRed()*FACTOR); - int g = (int)Math.rint(col.getGreen()*FACTOR); - int b = (int)Math.rint(col.getBlue()*FACTOR); - return new Color(r,g,b); - } - case LIGHTEN_COLOR: { - double FACTOR = (0xFF-ecr.getRGB()[2])/255.; - - int r = col.getRed(); - int g = col.getGreen(); - int b = col.getBlue(); - - r += Math.rint((0xFF-r)*FACTOR); - g += Math.rint((0xFF-g)*FACTOR); - b += Math.rint((0xFF-b)*FACTOR); - - return new Color(r,g,b); - } - default: - // TODO ... - break; - } - - return col; - } - - double getAlpha(short opacityProperty) { - AbstractEscherOptRecord opt = getEscherOptRecord(); - EscherSimpleProperty op = getEscherProperty(opt, opacityProperty); - int defaultOpacity = 0x00010000; - int opacity = (op == null) ? defaultOpacity : op.getPropertyValue(); - return Units.fixedPointToDouble(opacity); - } - - Color toRGB(int val){ - int a = (val >> 24) & 0xFF; - int b = (val >> 16) & 0xFF; - int g = (val >> 8) & 0xFF; - int r = (val >> 0) & 0xFF; - - if(a == 0xFE){ - // Color is an sRGB value specified by red, green, and blue fields. - } else if (a == 0xFF){ - // Color is undefined. - } else { - // index in the color scheme - ColorSchemeAtom ca = getSheet().getColorScheme(); - int schemeColor = ca.getColor(a); - - r = (schemeColor >> 0) & 0xFF; - g = (schemeColor >> 8) & 0xFF; - b = (schemeColor >> 16) & 0xFF; - } - return new Color(r, g, b); - } - - /** - * @return id for the shape. - */ - public int getShapeId(){ - EscherSpRecord spRecord = getEscherChild(EscherSpRecord.RECORD_ID); - return spRecord == null ? 0 : spRecord.getShapeId(); - } - - /** - * Sets shape ID - * - * @param id of the shape - */ - public void setShapeId(int id){ - EscherSpRecord spRecord = getEscherChild(EscherSpRecord.RECORD_ID); - if(spRecord != null) spRecord.setShapeId(id); - } - - /** - * Fill properties of this shape - * - * @return fill properties of this shape - */ - public HSLFFill getFill(){ - if(_fill == null) { - _fill = new HSLFFill(this); - } - return _fill; - } - - public FillStyle getFillStyle() { - return getFill().getFillStyle(); - } - - @Override - public void draw(Graphics2D graphics, Rectangle2D bounds){ - DrawFactory.getInstance(graphics).drawShape(graphics, this, bounds); - } - - public AbstractEscherOptRecord getEscherOptRecord() { - AbstractEscherOptRecord opt = getEscherChild(RecordTypes.EscherOPT); - if (opt == null) { - opt = getEscherChild(RecordTypes.EscherUserDefined); - } - return opt; - } - - public boolean getFlipHorizontal(){ - EscherSpRecord spRecord = getEscherChild(EscherSpRecord.RECORD_ID); - return (spRecord.getFlags()& EscherSpRecord.FLAG_FLIPHORIZ) != 0; - } - - public void setFlipHorizontal(boolean flip) { - EscherSpRecord spRecord = getEscherChild(EscherSpRecord.RECORD_ID); - int flag = spRecord.getFlags() | EscherSpRecord.FLAG_FLIPHORIZ; - spRecord.setFlags(flag); - } - - public boolean getFlipVertical(){ - EscherSpRecord spRecord = getEscherChild(EscherSpRecord.RECORD_ID); - return (spRecord.getFlags()& EscherSpRecord.FLAG_FLIPVERT) != 0; - } - - public void setFlipVertical(boolean flip) { - EscherSpRecord spRecord = getEscherChild(EscherSpRecord.RECORD_ID); - int flag = spRecord.getFlags() | EscherSpRecord.FLAG_FLIPVERT; - spRecord.setFlags(flag); - } - - public double getRotation(){ - int rot = getEscherProperty(EscherProperties.TRANSFORM__ROTATION); - return Units.fixedPointToDouble(rot); - } - - public void setRotation(double theta){ - int rot = Units.doubleToFixedPoint(theta % 360.0); - setEscherProperty(EscherProperties.TRANSFORM__ROTATION, rot); - } - - public boolean isPlaceholder() { - return false; - } - - /** - * Find a record in the underlying EscherClientDataRecord - * - * @param recordType type of the record to search - */ - @SuppressWarnings("unchecked") - public T getClientDataRecord(int recordType) { - - List records = getClientRecords(); - if (records != null) for (Record r : records) { - if (r.getRecordType() == recordType){ - return (T)r; - } - } - return null; - } - - /** - * Search for EscherClientDataRecord, if found, convert its contents into an array of HSLF records - * - * @return an array of HSLF records contained in the shape's EscherClientDataRecord or null - */ - protected List getClientRecords() { - HSLFEscherClientDataRecord clientData = getClientData(false); - return (clientData == null) ? null : clientData.getHSLFChildRecords(); - } - - /** - * Create a new HSLF-specific EscherClientDataRecord - * - * @param create if true, create the missing record - * @return the client record or null if it was missing and create wasn't activated - */ - protected HSLFEscherClientDataRecord getClientData(boolean create) { - HSLFEscherClientDataRecord clientData = getEscherChild(EscherClientDataRecord.RECORD_ID); - if (clientData == null && create) { - clientData = new HSLFEscherClientDataRecord(); - clientData.setOptions((short)15); - clientData.setRecordId(EscherClientDataRecord.RECORD_ID); - getSpContainer().addChildBefore(clientData, EscherTextboxRecord.RECORD_ID); - } - return clientData; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFShapeContainer.java b/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFShapeContainer.java deleted file mode 100644 index 8152befe2..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFShapeContainer.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.hslf.usermodel; - -import org.apache.poi.sl.usermodel.PictureData; -import org.apache.poi.sl.usermodel.ShapeContainer; - -/** - * Common interface for shape containers, e.g. sheets or groups of shapes - */ -public interface HSLFShapeContainer extends ShapeContainer { - - @Override - HSLFAutoShape createAutoShape(); - - @Override - HSLFFreeformShape createFreeform(); - - @Override - HSLFTextBox createTextBox(); - - @Override - HSLFConnectorShape createConnector(); - - @Override - HSLFGroupShape createGroup(); - - @Override - HSLFPictureShape createPicture(PictureData pictureData); - - -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFShapeFactory.java b/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFShapeFactory.java deleted file mode 100644 index 4797ff5f5..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFShapeFactory.java +++ /dev/null @@ -1,173 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.usermodel; - -import java.util.List; - -import org.apache.poi.ddf.AbstractEscherOptRecord; -import org.apache.poi.ddf.EscherClientDataRecord; -import org.apache.poi.ddf.EscherContainerRecord; -import org.apache.poi.ddf.EscherOptRecord; -import org.apache.poi.ddf.EscherProperties; -import org.apache.poi.ddf.EscherProperty; -import org.apache.poi.ddf.EscherPropertyFactory; -import org.apache.poi.ddf.EscherRecord; -import org.apache.poi.ddf.EscherSimpleProperty; -import org.apache.poi.ddf.EscherSpRecord; -import org.apache.poi.ddf.EscherTextboxRecord; -import org.apache.poi.hslf.model.MovieShape; -import org.apache.poi.hslf.model.OLEShape; -import org.apache.poi.hslf.record.ExObjRefAtom; -import org.apache.poi.hslf.record.HSLFEscherClientDataRecord; -import org.apache.poi.hslf.record.InteractiveInfo; -import org.apache.poi.hslf.record.InteractiveInfoAtom; -import org.apache.poi.hslf.record.Record; -import org.apache.poi.hslf.record.RecordTypes; -import org.apache.poi.sl.usermodel.ShapeContainer; -import org.apache.poi.sl.usermodel.ShapeType; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; - -/** - * Create a Shape object depending on its type - * - * @author Yegor Kozlov - */ -public final class HSLFShapeFactory { - // For logging - protected static final POILogger logger = POILogFactory.getLogger(HSLFShapeFactory.class); - - /** - * Create a new shape from the data provided. - */ - public static HSLFShape createShape(EscherContainerRecord spContainer, ShapeContainer parent){ - if (spContainer.getRecordId() == EscherContainerRecord.SPGR_CONTAINER){ - return createShapeGroup(spContainer, parent); - } - return createSimpleShape(spContainer, parent); - } - - public static HSLFGroupShape createShapeGroup(EscherContainerRecord spContainer, ShapeContainer parent){ - boolean isTable = false; - EscherContainerRecord ecr = (EscherContainerRecord)spContainer.getChild(0); - EscherRecord opt = HSLFShape.getEscherChild(ecr, RecordTypes.EscherUserDefined); - - if (opt != null) { - EscherPropertyFactory f = new EscherPropertyFactory(); - List props = f.createProperties( opt.serialize(), 8, opt.getInstance() ); - for (EscherProperty ep : props) { - if (ep.getPropertyNumber() == EscherProperties.GROUPSHAPE__TABLEPROPERTIES - && ep instanceof EscherSimpleProperty - && (((EscherSimpleProperty)ep).getPropertyValue() & 1) == 1) { - isTable = true; - break; - } - } - } - - HSLFGroupShape group; - if (isTable) { - group = new HSLFTable(spContainer, parent); - - } else { - group = new HSLFGroupShape(spContainer, parent); - } - - return group; - } - - public static HSLFShape createSimpleShape(EscherContainerRecord spContainer, ShapeContainer parent){ - HSLFShape shape = null; - EscherSpRecord spRecord = spContainer.getChildById(EscherSpRecord.RECORD_ID); - - ShapeType type = ShapeType.forId(spRecord.getShapeType(), false); - switch (type){ - case TEXT_BOX: - shape = new HSLFTextBox(spContainer, parent); - break; - case HOST_CONTROL: - case FRAME: - shape = createFrame(spContainer, parent); - break; - case LINE: - shape = new HSLFLine(spContainer, parent); - break; - case NOT_PRIMITIVE: - shape = createNonPrimitive(spContainer, parent); - break; - default: - if (parent instanceof HSLFTable) { - EscherTextboxRecord etr = spContainer.getChildById(EscherTextboxRecord.RECORD_ID); - if (etr == null) { - logger.log(POILogger.WARN, "invalid ppt - add EscherTextboxRecord to cell"); - etr = new EscherTextboxRecord(); - etr.setRecordId(EscherTextboxRecord.RECORD_ID); - etr.setOptions((short)15); - spContainer.addChildRecord(etr); - } - shape = new HSLFTableCell(spContainer, (HSLFTable)parent); - } else { - shape = new HSLFAutoShape(spContainer, parent); - } - break; - } - return shape; - } - - private static HSLFShape createFrame(EscherContainerRecord spContainer, ShapeContainer parent) { - InteractiveInfo info = getClientDataRecord(spContainer, RecordTypes.InteractiveInfo.typeID); - if(info != null && info.getInteractiveInfoAtom() != null){ - switch(info.getInteractiveInfoAtom().getAction()){ - case InteractiveInfoAtom.ACTION_OLE: - return new OLEShape(spContainer, parent); - case InteractiveInfoAtom.ACTION_MEDIA: - return new MovieShape(spContainer, parent); - default: - break; - } - } - - ExObjRefAtom oes = getClientDataRecord(spContainer, RecordTypes.ExObjRefAtom.typeID); - return (oes != null) - ? new OLEShape(spContainer, parent) - : new HSLFPictureShape(spContainer, parent); - } - - private static HSLFShape createNonPrimitive(EscherContainerRecord spContainer, ShapeContainer parent) { - AbstractEscherOptRecord opt = HSLFShape.getEscherChild(spContainer, EscherOptRecord.RECORD_ID); - EscherProperty prop = HSLFShape.getEscherProperty(opt, EscherProperties.GEOMETRY__VERTICES); - if(prop != null) { - return new HSLFFreeformShape(spContainer, parent); - } - - logger.log(POILogger.INFO, "Creating AutoShape for a NotPrimitive shape"); - return new HSLFAutoShape(spContainer, parent); - } - - @SuppressWarnings("unchecked") - protected static T getClientDataRecord(EscherContainerRecord spContainer, int recordType) { - HSLFEscherClientDataRecord cldata = spContainer.getChildById(EscherClientDataRecord.RECORD_ID); - if (cldata != null) for (Record r : cldata.getHSLFChildRecords()) { - if (r.getRecordType() == recordType) { - return (T)r; - } - } - return null; - } - -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSheet.java b/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSheet.java deleted file mode 100644 index cc4170634..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSheet.java +++ /dev/null @@ -1,475 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.usermodel; - -import java.awt.Graphics2D; -import java.awt.geom.Rectangle2D; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.apache.poi.ddf.EscherContainerRecord; -import org.apache.poi.ddf.EscherDgRecord; -import org.apache.poi.ddf.EscherDggRecord; -import org.apache.poi.ddf.EscherRecord; -import org.apache.poi.hslf.exceptions.HSLFException; -import org.apache.poi.hslf.record.CString; -import org.apache.poi.hslf.record.ColorSchemeAtom; -import org.apache.poi.hslf.record.PPDrawing; -import org.apache.poi.hslf.record.RecordContainer; -import org.apache.poi.hslf.record.RecordTypes; -import org.apache.poi.hslf.record.SheetContainer; -import org.apache.poi.sl.draw.DrawFactory; -import org.apache.poi.sl.draw.Drawable; -import org.apache.poi.sl.usermodel.PictureData; -import org.apache.poi.sl.usermodel.Placeholder; -import org.apache.poi.sl.usermodel.ShapeType; -import org.apache.poi.sl.usermodel.Sheet; -import org.apache.poi.util.Internal; - -/** - * This class defines the common format of "Sheets" in a powerpoint - * document. Such sheets could be Slides, Notes, Master etc - * - * @author Nick Burch - * @author Yegor Kozlov - */ - -public abstract class HSLFSheet implements HSLFShapeContainer, Sheet { - /** - * The SlideShow we belong to - */ - private HSLFSlideShow _slideShow; - - /** - * Sheet background - */ - private HSLFBackground _background; - - /** - * Record container that holds sheet data. - * For slides it is org.apache.poi.hslf.record.Slide, - * for notes it is org.apache.poi.hslf.record.Notes, - * for slide masters it is org.apache.poi.hslf.record.SlideMaster, etc. - */ - private SheetContainer _container; - - private int _sheetNo; - - public HSLFSheet(SheetContainer container, int sheetNo) { - _container = container; - _sheetNo = sheetNo; - } - - /** - * Returns an array of all the TextRuns in the sheet. - */ - public abstract List> getTextParagraphs(); - - /** - * Returns the (internal, RefID based) sheet number, as used - * to in PersistPtr stuff. - */ - public int _getSheetRefId() { - return _container.getSheetId(); - } - - /** - * Returns the (internal, SlideIdentifier based) sheet number, as used - * to reference this sheet from other records. - */ - public int _getSheetNumber() { - return _sheetNo; - } - - /** - * Fetch the PPDrawing from the underlying record - */ - public PPDrawing getPPDrawing() { - return _container.getPPDrawing(); - } - - /** - * Fetch the SlideShow we're attached to - */ - @Override - public HSLFSlideShow getSlideShow() { - return _slideShow; - } - - /** - * Return record container for this sheet - */ - public SheetContainer getSheetContainer() { - return _container; - } - - /** - * Set the SlideShow we're attached to. - * Also passes it on to our child text paragraphs - */ - @Internal - protected void setSlideShow(HSLFSlideShow ss) { - if (_slideShow != null) { - throw new HSLFException("Can't change existing slideshow reference"); - } - - _slideShow = ss; - List> trs = getTextParagraphs(); - if (trs == null) { - return; - } - for (List ltp : trs) { - HSLFTextParagraph.supplySheet(ltp, this); - HSLFTextParagraph.applyHyperlinks(ltp); - } - } - - - /** - * Returns all shapes contained in this Sheet - * - * @return all shapes contained in this Sheet (Slide or Notes) - */ - @Override - public List getShapes() { - PPDrawing ppdrawing = getPPDrawing(); - - EscherContainerRecord dg = ppdrawing.getDgContainer(); - EscherContainerRecord spgr = null; - - for (EscherRecord rec : dg) { - if (rec.getRecordId() == EscherContainerRecord.SPGR_CONTAINER) { - spgr = (EscherContainerRecord) rec; - break; - } - } - if (spgr == null) { - throw new IllegalStateException("spgr not found"); - } - - List shapeList = new ArrayList(); - boolean isFirst = true; - for (EscherRecord r : spgr) { - if (isFirst) { - // skip first item - isFirst = false; - continue; - } - - EscherContainerRecord sp = (EscherContainerRecord)r; - HSLFShape sh = HSLFShapeFactory.createShape(sp, null); - sh.setSheet(this); - - if (sh instanceof HSLFSimpleShape) { - HSLFHyperlink link = HSLFHyperlink.find(sh); - if (link != null) { - ((HSLFSimpleShape)sh).setHyperlink(link); - } - } - - shapeList.add(sh); - } - - return shapeList; - } - - /** - * Add a new Shape to this Slide - * - * @param shape - the Shape to add - */ - @Override - public void addShape(HSLFShape shape) { - PPDrawing ppdrawing = getPPDrawing(); - - EscherContainerRecord dgContainer = ppdrawing.getDgContainer(); - EscherContainerRecord spgr = (EscherContainerRecord) HSLFShape.getEscherChild(dgContainer, EscherContainerRecord.SPGR_CONTAINER); - spgr.addChildRecord(shape.getSpContainer()); - - shape.setSheet(this); - shape.setShapeId(allocateShapeId()); - shape.afterInsert(this); - } - - /** - * Allocates new shape id for the new drawing group id. - * - * @return a new shape id. - */ - public int allocateShapeId() - { - EscherDggRecord dgg = _slideShow.getDocumentRecord().getPPDrawingGroup().getEscherDggRecord(); - EscherDgRecord dg = _container.getPPDrawing().getEscherDgRecord(); - - dgg.setNumShapesSaved( dgg.getNumShapesSaved() + 1 ); - - // Add to existing cluster if space available - for (int i = 0; i < dgg.getFileIdClusters().length; i++) - { - EscherDggRecord.FileIdCluster c = dgg.getFileIdClusters()[i]; - if (c.getDrawingGroupId() == dg.getDrawingGroupId() && c.getNumShapeIdsUsed() != 1024) - { - int result = c.getNumShapeIdsUsed() + (1024 * (i+1)); - c.incrementShapeId(); - dg.setNumShapes( dg.getNumShapes() + 1 ); - dg.setLastMSOSPID( result ); - if (result >= dgg.getShapeIdMax()) { - dgg.setShapeIdMax( result + 1 ); - } - return result; - } - } - - // Create new cluster - dgg.addCluster( dg.getDrawingGroupId(), 0, false ); - dgg.getFileIdClusters()[dgg.getFileIdClusters().length-1].incrementShapeId(); - dg.setNumShapes( dg.getNumShapes() + 1 ); - int result = (1024 * dgg.getFileIdClusters().length); - dg.setLastMSOSPID( result ); - if (result >= dgg.getShapeIdMax()) { - dgg.setShapeIdMax( result + 1 ); - } - return result; - } - - /** - * Removes the specified shape from this sheet. - * - * @param shape shape to be removed from this sheet, if present. - * @return true if the shape was deleted. - */ - @Override - public boolean removeShape(HSLFShape shape) { - PPDrawing ppdrawing = getPPDrawing(); - - EscherContainerRecord dg = ppdrawing.getDgContainer(); - EscherContainerRecord spgr = dg.getChildById(EscherContainerRecord.SPGR_CONTAINER); - if(spgr == null) { - return false; - } - - List lst = spgr.getChildRecords(); - boolean result = lst.remove(shape.getSpContainer()); - spgr.setChildRecords(lst); - return result; - } - - /** - * Called by SlideShow ater a new sheet is created - */ - public void onCreate(){ - - } - - /** - * Return the master sheet . - */ - @Override - public abstract HSLFMasterSheet getMasterSheet(); - - /** - * Color scheme for this sheet. - */ - public ColorSchemeAtom getColorScheme() { - return _container.getColorScheme(); - } - - /** - * Returns the background shape for this sheet. - * - * @return the background shape for this sheet. - */ - @Override - public HSLFBackground getBackground() { - if (_background == null) { - PPDrawing ppdrawing = getPPDrawing(); - - EscherContainerRecord dg = ppdrawing.getDgContainer(); - EscherContainerRecord spContainer = dg.getChildById(EscherContainerRecord.SP_CONTAINER); - _background = new HSLFBackground(spContainer, null); - _background.setSheet(this); - } - return _background; - } - - @Override - public void draw(Graphics2D graphics) { - DrawFactory drawFact = DrawFactory.getInstance(graphics); - Drawable draw = drawFact.getDrawable(this); - draw.draw(graphics); - } - - /** - * Subclasses should call this method and update the array of text runs - * when a text shape is added - * - * @param shape - */ - protected void onAddTextShape(HSLFTextShape shape) { - } - - /** - * Return placeholder by text type - * - * @param type type of text, See {@link org.apache.poi.hslf.record.TextHeaderAtom} - * @return TextShape or null - */ - public HSLFTextShape getPlaceholderByTextType(int type){ - for (HSLFShape shape : getShapes()) { - if(shape instanceof HSLFTextShape){ - HSLFTextShape tx = (HSLFTextShape)shape; - if (tx.getRunType() == type) { - return tx; - } - } - } - return null; - } - - /** - * Search placeholder by its type - * - * @param type type of placeholder to search. See {@link org.apache.poi.hslf.record.OEPlaceholderAtom} - * @return {@code SimpleShape} or {@code null} - */ - public HSLFSimpleShape getPlaceholder(Placeholder type){ - for (HSLFShape shape : getShapes()) { - if (shape instanceof HSLFSimpleShape) { - HSLFSimpleShape ss = (HSLFSimpleShape)shape; - if (type == ss.getPlaceholder()) { - return ss; - } - } - } - return null; - } - - /** - * Return programmable tag associated with this sheet, e.g. ___PPT12. - * - * @return programmable tag associated with this sheet. - */ - public String getProgrammableTag(){ - String tag = null; - RecordContainer progTags = (RecordContainer) - getSheetContainer().findFirstOfType( - RecordTypes.ProgTags.typeID - ); - if(progTags != null) { - RecordContainer progBinaryTag = (RecordContainer) - progTags.findFirstOfType( - RecordTypes.ProgBinaryTag.typeID - ); - if(progBinaryTag != null) { - CString binaryTag = (CString) - progBinaryTag.findFirstOfType( - RecordTypes.CString.typeID - ); - if(binaryTag != null) { - tag = binaryTag.getText(); - } - } - } - - return tag; - - } - - @Override - public Iterator iterator() { - return getShapes().iterator(); - } - - - /** - * @return whether shapes on the master sheet should be shown. By default master graphics is turned off. - * Sheets that support the notion of master (slide, slideLayout) should override it and - * check this setting - */ - @Override - public boolean getFollowMasterGraphics() { - return false; - } - - - @Override - public HSLFTextBox createTextBox() { - HSLFTextBox s = new HSLFTextBox(); - s.setHorizontalCentered(true); - s.setAnchor(new Rectangle2D.Double(0, 0, 100, 100)); - addShape(s); - return s; - } - - @Override - public HSLFAutoShape createAutoShape() { - HSLFAutoShape s = new HSLFAutoShape(ShapeType.RECT); - s.setHorizontalCentered(true); - s.setAnchor(new Rectangle2D.Double(0, 0, 100, 100)); - addShape(s); - return s; - } - - @Override - public HSLFFreeformShape createFreeform() { - HSLFFreeformShape s = new HSLFFreeformShape(); - s.setHorizontalCentered(true); - s.setAnchor(new Rectangle2D.Double(0, 0, 100, 100)); - addShape(s); - return s; - } - - @Override - public HSLFConnectorShape createConnector() { - HSLFConnectorShape s = new HSLFConnectorShape(); - s.setAnchor(new Rectangle2D.Double(0, 0, 100, 100)); - addShape(s); - return s; - } - - @Override - public HSLFGroupShape createGroup() { - HSLFGroupShape s = new HSLFGroupShape(); - s.setAnchor(new Rectangle2D.Double(0, 0, 100, 100)); - addShape(s); - return s; - } - - @Override - public HSLFPictureShape createPicture(PictureData pictureData) { - if (!(pictureData instanceof HSLFPictureData)) { - throw new IllegalArgumentException("pictureData needs to be of type HSLFPictureData"); - } - HSLFPictureShape s = new HSLFPictureShape((HSLFPictureData)pictureData); - s.setAnchor(new Rectangle2D.Double(0, 0, 100, 100)); - addShape(s); - return s; - } - - @Override - public HSLFTable createTable(int numRows, int numCols) { - if (numRows < 1 || numCols < 1) { - throw new IllegalArgumentException("numRows and numCols must be greater than 0"); - } - HSLFTable s = new HSLFTable(numRows,numCols); - // anchor is set in constructor based on numRows/numCols - addShape(s); - return s; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSimpleShape.java b/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSimpleShape.java deleted file mode 100644 index dd98a017b..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSimpleShape.java +++ /dev/null @@ -1,731 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.usermodel; - -import java.awt.Color; -import java.util.List; - -import org.apache.poi.ddf.AbstractEscherOptRecord; -import org.apache.poi.ddf.EscherChildAnchorRecord; -import org.apache.poi.ddf.EscherClientAnchorRecord; -import org.apache.poi.ddf.EscherContainerRecord; -import org.apache.poi.ddf.EscherOptRecord; -import org.apache.poi.ddf.EscherProperties; -import org.apache.poi.ddf.EscherProperty; -import org.apache.poi.ddf.EscherRecord; -import org.apache.poi.ddf.EscherSimpleProperty; -import org.apache.poi.ddf.EscherSpRecord; -import org.apache.poi.hslf.exceptions.HSLFException; -import org.apache.poi.hslf.record.HSLFEscherClientDataRecord; -import org.apache.poi.hslf.record.OEPlaceholderAtom; -import org.apache.poi.hslf.record.Record; -import org.apache.poi.hslf.record.RoundTripHFPlaceholder12; -import org.apache.poi.sl.draw.DrawPaint; -import org.apache.poi.sl.draw.geom.CustomGeometry; -import org.apache.poi.sl.draw.geom.Guide; -import org.apache.poi.sl.draw.geom.PresetGeometries; -import org.apache.poi.sl.usermodel.LineDecoration; -import org.apache.poi.sl.usermodel.LineDecoration.DecorationShape; -import org.apache.poi.sl.usermodel.LineDecoration.DecorationSize; -import org.apache.poi.sl.usermodel.MasterSheet; -import org.apache.poi.sl.usermodel.PaintStyle; -import org.apache.poi.sl.usermodel.PaintStyle.SolidPaint; -import org.apache.poi.sl.usermodel.Placeholder; -import org.apache.poi.sl.usermodel.Shadow; -import org.apache.poi.sl.usermodel.ShapeContainer; -import org.apache.poi.sl.usermodel.ShapeType; -import org.apache.poi.sl.usermodel.SimpleShape; -import org.apache.poi.sl.usermodel.StrokeStyle; -import org.apache.poi.sl.usermodel.StrokeStyle.LineCap; -import org.apache.poi.sl.usermodel.StrokeStyle.LineCompound; -import org.apache.poi.sl.usermodel.StrokeStyle.LineDash; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.util.Units; - -/** - * An abstract simple (non-group) shape. - * This is the parent class for all primitive shapes like Line, Rectangle, etc. - */ -public abstract class HSLFSimpleShape extends HSLFShape implements SimpleShape { - private static final POILogger LOG = POILogFactory.getLogger(HSLFSimpleShape.class); - - public final static double DEFAULT_LINE_WIDTH = 0.75; - - /** - * Hyperlink - */ - protected HSLFHyperlink _hyperlink; - - /** - * Create a SimpleShape object and initialize it from the supplied Record container. - * - * @param escherRecord EscherSpContainer container which holds information about this shape - * @param parent the parent of the shape - */ - protected HSLFSimpleShape(EscherContainerRecord escherRecord, ShapeContainer parent){ - super(escherRecord, parent); - } - - /** - * Create a new Shape - * - * @param isChild true if the Line is inside a group, false otherwise - * @return the record container which holds this shape - */ - @Override - protected EscherContainerRecord createSpContainer(boolean isChild) { - EscherContainerRecord ecr = super.createSpContainer(isChild); - ecr.setRecordId( EscherContainerRecord.SP_CONTAINER ); - - EscherSpRecord sp = new EscherSpRecord(); - int flags = EscherSpRecord.FLAG_HAVEANCHOR | EscherSpRecord.FLAG_HASSHAPETYPE; - if (isChild) { - flags |= EscherSpRecord.FLAG_CHILD; - } - sp.setFlags(flags); - ecr.addChildRecord(sp); - - AbstractEscherOptRecord opt = new EscherOptRecord(); - opt.setRecordId(EscherOptRecord.RECORD_ID); - ecr.addChildRecord(opt); - - EscherRecord anchor; - if(isChild) { - anchor = new EscherChildAnchorRecord(); - } else { - anchor = new EscherClientAnchorRecord(); - - //hack. internal variable EscherClientAnchorRecord.shortRecord can be - //initialized only in fillFields(). We need to set shortRecord=false; - byte[] header = new byte[16]; - LittleEndian.putUShort(header, 0, 0); - LittleEndian.putUShort(header, 2, 0); - LittleEndian.putInt(header, 4, 8); - anchor.fillFields(header, 0, null); - } - ecr.addChildRecord(anchor); - - return ecr; - } - - /** - * Returns width of the line in in points - */ - public double getLineWidth(){ - AbstractEscherOptRecord opt = getEscherOptRecord(); - EscherSimpleProperty prop = getEscherProperty(opt, EscherProperties.LINESTYLE__LINEWIDTH); - double width = (prop == null) ? DEFAULT_LINE_WIDTH : Units.toPoints(prop.getPropertyValue()); - return width; - } - - /** - * Sets the width of line in in points - * @param width the width of line in in points - */ - public void setLineWidth(double width){ - AbstractEscherOptRecord opt = getEscherOptRecord(); - setEscherProperty(opt, EscherProperties.LINESTYLE__LINEWIDTH, Units.toEMU(width)); - } - - /** - * Sets the color of line - * - * @param color new color of the line - */ - public void setLineColor(Color color){ - AbstractEscherOptRecord opt = getEscherOptRecord(); - if (color == null) { - setEscherProperty(opt, EscherProperties.LINESTYLE__NOLINEDRAWDASH, 0x80000); - } else { - int rgb = new Color(color.getBlue(), color.getGreen(), color.getRed(), 0).getRGB(); - setEscherProperty(opt, EscherProperties.LINESTYLE__COLOR, rgb); - setEscherProperty(opt, EscherProperties.LINESTYLE__NOLINEDRAWDASH, 0x180018); - } - } - - /** - * @return color of the line. If color is not set returns {@code null} - */ - public Color getLineColor(){ - AbstractEscherOptRecord opt = getEscherOptRecord(); - - EscherSimpleProperty p = getEscherProperty(opt, EscherProperties.LINESTYLE__NOLINEDRAWDASH); - if(p != null && (p.getPropertyValue() & 0x8) == 0) { - return null; - } - - Color clr = getColor(EscherProperties.LINESTYLE__COLOR, EscherProperties.LINESTYLE__OPACITY, -1); - return clr == null ? null : clr; - } - - /** - * @return background color of the line. If color is not set returns {@code null} - */ - public Color getLineBackgroundColor(){ - AbstractEscherOptRecord opt = getEscherOptRecord(); - - EscherSimpleProperty p = getEscherProperty(opt, EscherProperties.LINESTYLE__NOLINEDRAWDASH); - if(p != null && (p.getPropertyValue() & 0x8) == 0) { - return null; - } - - Color clr = getColor(EscherProperties.LINESTYLE__BACKCOLOR, EscherProperties.LINESTYLE__OPACITY, -1); - return clr == null ? null : clr; - } - - /** - * Sets the background color of line - * - * @param color new background color of the line - */ - public void setLineBackgroundColor(Color color){ - AbstractEscherOptRecord opt = getEscherOptRecord(); - if (color == null) { - setEscherProperty(opt, EscherProperties.LINESTYLE__NOLINEDRAWDASH, 0x80000); - opt.removeEscherProperty(EscherProperties.LINESTYLE__BACKCOLOR); - } else { - int rgb = new Color(color.getBlue(), color.getGreen(), color.getRed(), 0).getRGB(); - setEscherProperty(opt, EscherProperties.LINESTYLE__BACKCOLOR, rgb); - setEscherProperty(opt, EscherProperties.LINESTYLE__NOLINEDRAWDASH, 0x180018); - } - } - - /** - * Gets line cap. - * - * @return cap of the line. - */ - public LineCap getLineCap(){ - AbstractEscherOptRecord opt = getEscherOptRecord(); - EscherSimpleProperty prop = getEscherProperty(opt, EscherProperties.LINESTYLE__LINEENDCAPSTYLE); - return (prop == null) ? LineCap.FLAT : LineCap.fromNativeId(prop.getPropertyValue()); - } - - /** - * Sets line cap. - * - * @param pen new style of the line. - */ - public void setLineCap(LineCap pen){ - AbstractEscherOptRecord opt = getEscherOptRecord(); - setEscherProperty(opt, EscherProperties.LINESTYLE__LINEENDCAPSTYLE, pen == LineCap.FLAT ? -1 : pen.nativeId); - } - - /** - * Gets line dashing. - * - * @return dashing of the line. - */ - public LineDash getLineDash(){ - AbstractEscherOptRecord opt = getEscherOptRecord(); - EscherSimpleProperty prop = getEscherProperty(opt, EscherProperties.LINESTYLE__LINEDASHING); - return (prop == null) ? LineDash.SOLID : LineDash.fromNativeId(prop.getPropertyValue()); - } - - /** - * Sets line dashing. - * - * @param pen new style of the line. - */ - public void setLineDash(LineDash pen){ - AbstractEscherOptRecord opt = getEscherOptRecord(); - setEscherProperty(opt, EscherProperties.LINESTYLE__LINEDASHING, pen == LineDash.SOLID ? -1 : pen.nativeId); - } - - /** - * Gets the line compound style - * - * @return the compound style of the line. - */ - public LineCompound getLineCompound() { - AbstractEscherOptRecord opt = getEscherOptRecord(); - EscherSimpleProperty prop = getEscherProperty(opt, EscherProperties.LINESTYLE__LINESTYLE); - return (prop == null) ? LineCompound.SINGLE : LineCompound.fromNativeId(prop.getPropertyValue()); - } - - /** - * Sets the line compound style - * - * @param style new compound style of the line. - */ - public void setLineCompound(LineCompound style){ - AbstractEscherOptRecord opt = getEscherOptRecord(); - setEscherProperty(opt, EscherProperties.LINESTYLE__LINESTYLE, style == LineCompound.SINGLE ? -1 : style.nativeId); - } - - /** - * Returns line style. One of the constants defined in this class. - * - * @return style of the line. - */ - @Override - public StrokeStyle getStrokeStyle(){ - return new StrokeStyle() { - @Override - public PaintStyle getPaint() { - return DrawPaint.createSolidPaint(HSLFSimpleShape.this.getLineColor()); - } - - @Override - public LineCap getLineCap() { - return null; - } - - @Override - public LineDash getLineDash() { - return HSLFSimpleShape.this.getLineDash(); - } - - @Override - public LineCompound getLineCompound() { - return HSLFSimpleShape.this.getLineCompound(); - } - - @Override - public double getLineWidth() { - return HSLFSimpleShape.this.getLineWidth(); - } - - }; - } - - @Override - public Color getFillColor() { - return getFill().getForegroundColor(); - } - - @Override - public void setFillColor(Color color) { - getFill().setForegroundColor(color); - } - - @Override - public Guide getAdjustValue(String name) { - if (name == null || !name.matches("adj([1-9]|10)?")) { - LOG.log(POILogger.INFO, "Adjust value '"+name+"' not supported. Using default value."); - return null; - } - - name = name.replace("adj", ""); - if ("".equals(name)) { - name = "1"; - } - - short escherProp; - switch (Integer.parseInt(name)) { - case 1: escherProp = EscherProperties.GEOMETRY__ADJUSTVALUE; break; - case 2: escherProp = EscherProperties.GEOMETRY__ADJUST2VALUE; break; - case 3: escherProp = EscherProperties.GEOMETRY__ADJUST3VALUE; break; - case 4: escherProp = EscherProperties.GEOMETRY__ADJUST4VALUE; break; - case 5: escherProp = EscherProperties.GEOMETRY__ADJUST5VALUE; break; - case 6: escherProp = EscherProperties.GEOMETRY__ADJUST6VALUE; break; - case 7: escherProp = EscherProperties.GEOMETRY__ADJUST7VALUE; break; - case 8: escherProp = EscherProperties.GEOMETRY__ADJUST8VALUE; break; - case 9: escherProp = EscherProperties.GEOMETRY__ADJUST9VALUE; break; - case 10: escherProp = EscherProperties.GEOMETRY__ADJUST10VALUE; break; - default: throw new HSLFException(); - } - - // TODO: the adjust values need to be corrected somehow depending on the shape width/height - // see https://social.msdn.microsoft.com/Forums/en-US/3f69ebb3-62a0-4fdd-b367-64790dfb2491/presetshapedefinitionsxml-does-not-specify-width-and-height-form-some-autoshapes?forum=os_binaryfile - - // the adjust value can be format dependent, e.g. hexagon has different values, - // other shape types have the same adjust values in OOXML and native - int adjval = getEscherProperty(escherProp, -1); - - return (adjval == -1) ? null : new Guide(name, "val "+adjval); - } - - @Override - public CustomGeometry getGeometry() { - PresetGeometries dict = PresetGeometries.getInstance(); - ShapeType st = getShapeType(); - String name = (st != null) ? st.getOoxmlName() : null; - CustomGeometry geom = dict.get(name); - if (geom == null) { - if (name == null) { - name = (st != null) ? st.toString() : ""; - } - LOG.log(POILogger.WARN, "No preset shape definition for shapeType: "+name); - } - - return geom; - } - - - public double getShadowAngle() { - AbstractEscherOptRecord opt = getEscherOptRecord(); - EscherSimpleProperty prop = getEscherProperty(opt, EscherProperties.SHADOWSTYLE__OFFSETX); - int offX = (prop == null) ? 0 : prop.getPropertyValue(); - prop = getEscherProperty(opt, EscherProperties.SHADOWSTYLE__OFFSETY); - int offY = (prop == null) ? 0 : prop.getPropertyValue(); - return Math.toDegrees(Math.atan2(offY, offX)); - } - - public double getShadowDistance() { - AbstractEscherOptRecord opt = getEscherOptRecord(); - EscherSimpleProperty prop = getEscherProperty(opt, EscherProperties.SHADOWSTYLE__OFFSETX); - int offX = (prop == null) ? 0 : prop.getPropertyValue(); - prop = getEscherProperty(opt, EscherProperties.SHADOWSTYLE__OFFSETY); - int offY = (prop == null) ? 0 : prop.getPropertyValue(); - return Units.toPoints((long)Math.hypot(offX, offY)); - } - - /** - * @return color of the line. If color is not set returns java.awt.Color.black - */ - public Color getShadowColor(){ - Color clr = getColor(EscherProperties.SHADOWSTYLE__COLOR, EscherProperties.SHADOWSTYLE__OPACITY, -1); - return clr == null ? Color.black : clr; - } - - @Override - public Shadow getShadow() { - AbstractEscherOptRecord opt = getEscherOptRecord(); - if (opt == null) { - return null; - } - EscherProperty shadowType = opt.lookup(EscherProperties.SHADOWSTYLE__TYPE); - if (shadowType == null) { - return null; - } - - return new Shadow(){ - @Override - public SimpleShape getShadowParent() { - return HSLFSimpleShape.this; - } - - @Override - public double getDistance() { - return getShadowDistance(); - } - - @Override - public double getAngle() { - return getShadowAngle(); - } - - @Override - public double getBlur() { - // TODO Auto-generated method stub - return 0; - } - - @Override - public SolidPaint getFillStyle() { - return DrawPaint.createSolidPaint(getShadowColor()); - } - - }; - } - - public DecorationShape getLineHeadDecoration(){ - AbstractEscherOptRecord opt = getEscherOptRecord(); - EscherSimpleProperty prop = getEscherProperty(opt, EscherProperties.LINESTYLE__LINESTARTARROWHEAD); - return (prop == null) ? null : DecorationShape.fromNativeId(prop.getPropertyValue()); - } - - public void setLineHeadDecoration(DecorationShape decoShape){ - AbstractEscherOptRecord opt = getEscherOptRecord(); - setEscherProperty(opt, EscherProperties.LINESTYLE__LINESTARTARROWHEAD, decoShape == null ? -1 : decoShape.nativeId); - } - - public DecorationSize getLineHeadWidth(){ - AbstractEscherOptRecord opt = getEscherOptRecord(); - EscherSimpleProperty prop = getEscherProperty(opt, EscherProperties.LINESTYLE__LINESTARTARROWWIDTH); - return (prop == null) ? null : DecorationSize.fromNativeId(prop.getPropertyValue()); - } - - public void setLineHeadWidth(DecorationSize decoSize){ - AbstractEscherOptRecord opt = getEscherOptRecord(); - setEscherProperty(opt, EscherProperties.LINESTYLE__LINESTARTARROWWIDTH, decoSize == null ? -1 : decoSize.nativeId); - } - - public DecorationSize getLineHeadLength(){ - AbstractEscherOptRecord opt = getEscherOptRecord(); - EscherSimpleProperty prop = getEscherProperty(opt, EscherProperties.LINESTYLE__LINESTARTARROWLENGTH); - return (prop == null) ? null : DecorationSize.fromNativeId(prop.getPropertyValue()); - } - - public void setLineHeadLength(DecorationSize decoSize){ - AbstractEscherOptRecord opt = getEscherOptRecord(); - setEscherProperty(opt, EscherProperties.LINESTYLE__LINESTARTARROWLENGTH, decoSize == null ? -1 : decoSize.nativeId); - } - - public DecorationShape getLineTailDecoration(){ - AbstractEscherOptRecord opt = getEscherOptRecord(); - EscherSimpleProperty prop = getEscherProperty(opt, EscherProperties.LINESTYLE__LINEENDARROWHEAD); - return (prop == null) ? null : DecorationShape.fromNativeId(prop.getPropertyValue()); - } - - public void setLineTailDecoration(DecorationShape decoShape){ - AbstractEscherOptRecord opt = getEscherOptRecord(); - setEscherProperty(opt, EscherProperties.LINESTYLE__LINEENDARROWHEAD, decoShape == null ? -1 : decoShape.nativeId); - } - - public DecorationSize getLineTailWidth(){ - AbstractEscherOptRecord opt = getEscherOptRecord(); - EscherSimpleProperty prop = getEscherProperty(opt, EscherProperties.LINESTYLE__LINEENDARROWWIDTH); - return (prop == null) ? null : DecorationSize.fromNativeId(prop.getPropertyValue()); - } - - public void setLineTailWidth(DecorationSize decoSize){ - AbstractEscherOptRecord opt = getEscherOptRecord(); - setEscherProperty(opt, EscherProperties.LINESTYLE__LINEENDARROWWIDTH, decoSize == null ? -1 : decoSize.nativeId); - } - - public DecorationSize getLineTailLength(){ - AbstractEscherOptRecord opt = getEscherOptRecord(); - EscherSimpleProperty prop = getEscherProperty(opt, EscherProperties.LINESTYLE__LINEENDARROWLENGTH); - return (prop == null) ? null : DecorationSize.fromNativeId(prop.getPropertyValue()); - } - - public void setLineTailLength(DecorationSize decoSize){ - AbstractEscherOptRecord opt = getEscherOptRecord(); - setEscherProperty(opt, EscherProperties.LINESTYLE__LINEENDARROWLENGTH, decoSize == null ? -1 : decoSize.nativeId); - } - - - - @Override - public LineDecoration getLineDecoration() { - return new LineDecoration() { - - @Override - public DecorationShape getHeadShape() { - return HSLFSimpleShape.this.getLineHeadDecoration(); - } - - @Override - public DecorationSize getHeadWidth() { - return HSLFSimpleShape.this.getLineHeadWidth(); - } - - @Override - public DecorationSize getHeadLength() { - return HSLFSimpleShape.this.getLineHeadLength(); - } - - @Override - public DecorationShape getTailShape() { - return HSLFSimpleShape.this.getLineTailDecoration(); - } - - @Override - public DecorationSize getTailWidth() { - return HSLFSimpleShape.this.getLineTailWidth(); - } - - @Override - public DecorationSize getTailLength() { - return HSLFSimpleShape.this.getLineTailLength(); - } - }; - } - - @Override - public Placeholder getPlaceholder() { - List clRecords = getClientRecords(); - if (clRecords == null) { - return null; - } - int phSource; - HSLFSheet sheet = getSheet(); - if (sheet instanceof HSLFSlideMaster) { - phSource = 1; - } else if (sheet instanceof HSLFNotes) { - phSource = 2; - } else if (sheet instanceof MasterSheet) { - // notes master aren't yet supported ... - phSource = 3; - } else { - phSource = 0; - } - - for (Record r : clRecords) { - int phId; - if (r instanceof OEPlaceholderAtom) { - phId = ((OEPlaceholderAtom)r).getPlaceholderId(); - } else if (r instanceof RoundTripHFPlaceholder12) { - //special case for files saved in Office 2007 - phId = ((RoundTripHFPlaceholder12)r).getPlaceholderId(); - } else { - continue; - } - - switch (phSource) { - case 0: - return Placeholder.lookupNativeSlide(phId); - default: - case 1: - return Placeholder.lookupNativeSlideMaster(phId); - case 2: - return Placeholder.lookupNativeNotes(phId); - case 3: - return Placeholder.lookupNativeNotesMaster(phId); - } - } - - return null; - } - - @Override - public void setPlaceholder(Placeholder placeholder) { - EscherSpRecord spRecord = getEscherChild(EscherSpRecord.RECORD_ID); - int flags = spRecord.getFlags(); - if (placeholder == null) { - flags ^= EscherSpRecord.FLAG_HAVEMASTER; - } else { - flags |= EscherSpRecord.FLAG_HAVEANCHOR | EscherSpRecord.FLAG_HAVEMASTER; - } - spRecord.setFlags(flags); - - // Placeholders can't be grouped - setEscherProperty(EscherProperties.PROTECTION__LOCKAGAINSTGROUPING, (placeholder == null ? -1 : 262144)); - - HSLFEscherClientDataRecord clientData = getClientData(false); - if (placeholder == null) { - if (clientData != null) { - clientData.removeChild(OEPlaceholderAtom.class); - clientData.removeChild(RoundTripHFPlaceholder12.class); - // remove client data if the placeholder was the only child to be carried - if (clientData.getChildRecords().isEmpty()) { - getSpContainer().removeChildRecord(clientData); - } - } - return; - } - - if (clientData == null) { - clientData = getClientData(true); - } - - // OEPlaceholderAtom tells powerpoint that this shape is a placeholder - OEPlaceholderAtom oep = null; - RoundTripHFPlaceholder12 rtp = null; - for (Record r : clientData.getHSLFChildRecords()) { - if (r instanceof OEPlaceholderAtom) { - oep = (OEPlaceholderAtom)r; - break; - } - if (r instanceof RoundTripHFPlaceholder12) { - rtp = (RoundTripHFPlaceholder12)r; - break; - } - } - - /** - * Extract from MSDN: - * - * There is a special case when the placeholder does not have a position in the layout. - * This occurs when the user has moved the placeholder from its original position. - * In this case the placeholder ID is -1. - */ - byte phId; - HSLFSheet sheet = getSheet(); - // TODO: implement/switch NotesMaster - if (sheet instanceof HSLFSlideMaster) { - phId = (byte)placeholder.nativeSlideMasterId; - } else if (sheet instanceof HSLFNotes) { - phId = (byte)placeholder.nativeNotesId; - } else { - phId = (byte)placeholder.nativeSlideId; - } - - if (phId == -2) { - throw new HSLFException("Placeholder "+placeholder.name()+" not supported for this sheet type ("+sheet.getClass()+")"); - } - - switch (placeholder) { - case HEADER: - case FOOTER: - if (rtp == null) { - rtp = new RoundTripHFPlaceholder12(); - rtp.setPlaceholderId(phId); - clientData.addChild(rtp); - } - if (oep != null) { - clientData.removeChild(OEPlaceholderAtom.class); - } - break; - default: - if (rtp != null) { - clientData.removeChild(RoundTripHFPlaceholder12.class); - } - if (oep == null) { - oep = new OEPlaceholderAtom(); - oep.setPlaceholderSize((byte)OEPlaceholderAtom.PLACEHOLDER_FULLSIZE); - // TODO: placement id only "SHOULD" be unique ... check other placeholders on sheet for unique id - oep.setPlacementId(-1); - oep.setPlaceholderId(phId); - clientData.addChild(oep); - } - break; - } - } - - - @Override - public void setStrokeStyle(Object... styles) { - if (styles.length == 0) { - // remove stroke - setLineColor(null); - return; - } - - // TODO: handle PaintStyle - for (Object st : styles) { - if (st instanceof Number) { - setLineWidth(((Number)st).doubleValue()); - } else if (st instanceof LineCap) { - setLineCap((LineCap)st); - } else if (st instanceof LineDash) { - setLineDash((LineDash)st); - } else if (st instanceof LineCompound) { - setLineCompound((LineCompound)st); - } else if (st instanceof Color) { - setLineColor((Color)st); - } - } - } - - @Override - public HSLFHyperlink getHyperlink(){ - return _hyperlink; - } - - @Override - public HSLFHyperlink createHyperlink() { - if (_hyperlink == null) { - _hyperlink = HSLFHyperlink.createHyperlink(this); - } - return _hyperlink; - } - - /** - * Sets the hyperlink - used when the document is parsed - * - * @param link the hyperlink - */ - protected void setHyperlink(HSLFHyperlink link) { - _hyperlink = link; - } -} \ No newline at end of file diff --git a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSlide.java b/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSlide.java deleted file mode 100644 index 2a3e4fae1..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSlide.java +++ /dev/null @@ -1,528 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.usermodel; - -import java.awt.Graphics2D; -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.ddf.EscherContainerRecord; -import org.apache.poi.ddf.EscherDgRecord; -import org.apache.poi.ddf.EscherDggRecord; -import org.apache.poi.ddf.EscherSpRecord; -import org.apache.poi.hslf.exceptions.HSLFException; -import org.apache.poi.hslf.model.Comment; -import org.apache.poi.hslf.model.HeadersFooters; -import org.apache.poi.hslf.record.ColorSchemeAtom; -import org.apache.poi.hslf.record.Comment2000; -import org.apache.poi.hslf.record.EscherTextboxWrapper; -import org.apache.poi.hslf.record.HeadersFootersContainer; -import org.apache.poi.hslf.record.RecordContainer; -import org.apache.poi.hslf.record.RecordTypes; -import org.apache.poi.hslf.record.SSSlideInfoAtom; -import org.apache.poi.hslf.record.SlideAtom; -import org.apache.poi.hslf.record.SlideAtomLayout.SlideLayoutType; -import org.apache.poi.hslf.record.SlideListWithText.SlideAtomsSet; -import org.apache.poi.hslf.record.StyleTextProp9Atom; -import org.apache.poi.hslf.record.TextHeaderAtom; -import org.apache.poi.sl.draw.DrawFactory; -import org.apache.poi.sl.draw.Drawable; -import org.apache.poi.sl.usermodel.Notes; -import org.apache.poi.sl.usermodel.Placeholder; -import org.apache.poi.sl.usermodel.ShapeType; -import org.apache.poi.sl.usermodel.Slide; - -/** - * This class represents a slide in a PowerPoint Document. It allows - * access to the text within, and the layout. For now, it only does - * the text side of things though - * - * @author Nick Burch - * @author Yegor Kozlov - */ - -public final class HSLFSlide extends HSLFSheet implements Slide { - private int _slideNo; - private SlideAtomsSet _atomSet; - private final List> _paragraphs = new ArrayList>(); - private HSLFNotes _notes; // usermodel needs to set this - - /** - * Constructs a Slide from the Slide record, and the SlideAtomsSet - * containing the text. - * Initializes TextRuns, to provide easier access to the text - * - * @param slide the Slide record we're based on - * @param notes the Notes sheet attached to us - * @param atomSet the SlideAtomsSet to get the text from - */ - public HSLFSlide(org.apache.poi.hslf.record.Slide slide, HSLFNotes notes, SlideAtomsSet atomSet, int slideIdentifier, int slideNumber) { - super(slide, slideIdentifier); - - _notes = notes; - _atomSet = atomSet; - _slideNo = slideNumber; - - // For the text coming in from the SlideAtomsSet: - // Build up TextRuns from pairs of TextHeaderAtom and - // one of TextBytesAtom or TextCharsAtom - if (_atomSet != null && _atomSet.getSlideRecords().length > 0) { - // Grab text from SlideListWithTexts entries - _paragraphs.addAll(HSLFTextParagraph.findTextParagraphs(_atomSet.getSlideRecords())); - if (_paragraphs.isEmpty()) { - throw new HSLFException("No text records found for slide"); - } - } else { - // No text on the slide, must just be pictures - } - - // Grab text from slide's PPDrawing - for (List l : HSLFTextParagraph.findTextParagraphs(getPPDrawing(), this)) { - if (!_paragraphs.contains(l)) { - _paragraphs.add(l); - } - } - } - - /** - * Create a new Slide instance - * @param sheetNumber The internal number of the sheet, as used by PersistPtrHolder - * @param slideNumber The user facing number of the sheet - */ - public HSLFSlide(int sheetNumber, int sheetRefId, int slideNumber){ - super(new org.apache.poi.hslf.record.Slide(), sheetNumber); - _slideNo = slideNumber; - getSheetContainer().setSheetId(sheetRefId); - } - - /** - * Returns the Notes Sheet for this slide, or null if there isn't one - */ - @Override - public HSLFNotes getNotes() { - return _notes; - } - - /** - * Sets the Notes that are associated with this. Updates the - * references in the records to point to the new ID - */ - @Override - public void setNotes(Notes notes) { - if (notes != null && !(notes instanceof HSLFNotes)) { - throw new IllegalArgumentException("notes needs to be of type HSLFNotes"); - } - _notes = (HSLFNotes)notes; - - // Update the Slide Atom's ID of where to point to - SlideAtom sa = getSlideRecord().getSlideAtom(); - - if(_notes == null) { - // Set to 0 - sa.setNotesID(0); - } else { - // Set to the value from the notes' sheet id - sa.setNotesID(_notes._getSheetNumber()); - } - } - - /** - * Changes the Slide's (external facing) page number. - * @see org.apache.poi.hslf.usermodel.HSLFSlideShow#reorderSlide(int, int) - */ - public void setSlideNumber(int newSlideNumber) { - _slideNo = newSlideNumber; - } - - /** - * Called by SlideShow ater a new slide is created. - *

    - * For Slide we need to do the following: - *

  • set id of the drawing group. - *
  • set shapeId for the container descriptor and background - *

    - */ - @Override - public void onCreate(){ - //initialize drawing group id - EscherDggRecord dgg = getSlideShow().getDocumentRecord().getPPDrawingGroup().getEscherDggRecord(); - EscherContainerRecord dgContainer = getSheetContainer().getPPDrawing().getDgContainer(); - EscherDgRecord dg = (EscherDgRecord) HSLFShape.getEscherChild(dgContainer, EscherDgRecord.RECORD_ID); - int dgId = dgg.getMaxDrawingGroupId() + 1; - dg.setOptions((short)(dgId << 4)); - dgg.setDrawingsSaved(dgg.getDrawingsSaved() + 1); - dgg.setMaxDrawingGroupId(dgId); - - for (EscherContainerRecord c : dgContainer.getChildContainers()) { - EscherSpRecord spr = null; - switch(c.getRecordId()){ - case EscherContainerRecord.SPGR_CONTAINER: - EscherContainerRecord dc = (EscherContainerRecord)c.getChild(0); - spr = dc.getChildById(EscherSpRecord.RECORD_ID); - break; - case EscherContainerRecord.SP_CONTAINER: - spr = c.getChildById(EscherSpRecord.RECORD_ID); - break; - default: - break; - } - if(spr != null) { - spr.setShapeId(allocateShapeId()); - } - } - - //PPT doen't increment the number of saved shapes for group descriptor and background - dg.setNumShapes(1); - } - - /** - * Create a TextBox object that represents the slide's title. - * - * @return TextBox object that represents the slide's title. - */ - public HSLFTextBox addTitle() { - HSLFPlaceholder pl = new HSLFPlaceholder(); - pl.setShapeType(ShapeType.RECT); - pl.setPlaceholder(Placeholder.TITLE); - pl.setRunType(TextHeaderAtom.TITLE_TYPE); - pl.setText("Click to edit title"); - pl.setAnchor(new java.awt.Rectangle(54, 48, 612, 90)); - addShape(pl); - return pl; - } - - - // Complex Accesser methods follow - - /** - *

    - * The title is a run of text of type TextHeaderAtom.CENTER_TITLE_TYPE or - * TextHeaderAtom.TITLE_TYPE - *

    - * - * @see TextHeaderAtom - */ - @Override - public String getTitle(){ - for (List tp : getTextParagraphs()) { - if (tp.isEmpty()) { - continue; - } - int type = tp.get(0).getRunType(); - switch (type) { - case TextHeaderAtom.CENTER_TITLE_TYPE: - case TextHeaderAtom.TITLE_TYPE: - String str = HSLFTextParagraph.getRawText(tp); - return HSLFTextParagraph.toExternalString(str, type); - } - } - return null; - } - - // Simple Accesser methods follow - - /** - * Returns an array of all the TextRuns found - */ - @Override - public List> getTextParagraphs() { return _paragraphs; } - - /** - * Returns the (public facing) page number of this slide - */ - @Override - public int getSlideNumber() { return _slideNo; } - - /** - * Returns the underlying slide record - */ - public org.apache.poi.hslf.record.Slide getSlideRecord() { - return (org.apache.poi.hslf.record.Slide)getSheetContainer(); - } - - /** - * @return set of records inside SlideListWithtext container - * which hold text data for this slide (typically for placeholders). - */ - protected SlideAtomsSet getSlideAtomsSet() { return _atomSet; } - - /** - * Returns master sheet associated with this slide. - * It can be either SlideMaster or TitleMaster objects. - * - * @return the master sheet associated with this slide. - */ - @Override - public HSLFMasterSheet getMasterSheet(){ - int masterId = getSlideRecord().getSlideAtom().getMasterID(); - for (HSLFSlideMaster sm : getSlideShow().getSlideMasters()) { - if (masterId == sm._getSheetNumber()) { - return sm; - } - } - for (HSLFTitleMaster tm : getSlideShow().getTitleMasters()) { - if (masterId == tm._getSheetNumber()) { - return tm; - } - } - return null; - } - - /** - * Change Master of this slide. - */ - public void setMasterSheet(HSLFMasterSheet master){ - SlideAtom sa = getSlideRecord().getSlideAtom(); - int sheetNo = master._getSheetNumber(); - sa.setMasterID(sheetNo); - } - - /** - * Sets whether this slide follows master background - * - * @param flag true if the slide follows master, - * false otherwise - */ - @Override - public void setFollowMasterBackground(boolean flag){ - SlideAtom sa = getSlideRecord().getSlideAtom(); - sa.setFollowMasterBackground(flag); - } - - /** - * Whether this slide follows master sheet background - * - * @return true if the slide follows master background, - * false otherwise - */ - @Override - public boolean getFollowMasterBackground(){ - SlideAtom sa = getSlideRecord().getSlideAtom(); - return sa.getFollowMasterBackground(); - } - - /** - * Sets whether this slide draws master sheet objects - * - * @param flag true if the slide draws master sheet objects, - * false otherwise - */ - @Override - public void setFollowMasterObjects(boolean flag){ - SlideAtom sa = getSlideRecord().getSlideAtom(); - sa.setFollowMasterObjects(flag); - } - - /** - * Whether this slide follows master color scheme - * - * @return true if the slide follows master color scheme, - * false otherwise - */ - public boolean getFollowMasterScheme(){ - SlideAtom sa = getSlideRecord().getSlideAtom(); - return sa.getFollowMasterScheme(); - } - - /** - * Sets whether this slide draws master color scheme - * - * @param flag true if the slide draws master color scheme, - * false otherwise - */ - public void setFollowMasterScheme(boolean flag){ - SlideAtom sa = getSlideRecord().getSlideAtom(); - sa.setFollowMasterScheme(flag); - } - - /** - * Whether this slide draws master sheet objects - * - * @return true if the slide draws master sheet objects, - * false otherwise - */ - @Override - public boolean getFollowMasterObjects(){ - SlideAtom sa = getSlideRecord().getSlideAtom(); - return sa.getFollowMasterObjects(); - } - - /** - * Background for this slide. - */ - @Override - public HSLFBackground getBackground() { - if(getFollowMasterBackground()) { - return getMasterSheet().getBackground(); - } - return super.getBackground(); - } - - /** - * Color scheme for this slide. - */ - @Override - public ColorSchemeAtom getColorScheme() { - if(getFollowMasterScheme()){ - return getMasterSheet().getColorScheme(); - } - return super.getColorScheme(); - } - - /** - * Get the comment(s) for this slide. - * Note - for now, only works on PPT 2000 and - * PPT 2003 files. Doesn't work for PPT 97 - * ones, as they do their comments oddly. - */ - public Comment[] getComments() { - // If there are any, they're in - // ProgTags -> ProgBinaryTag -> BinaryTagData - RecordContainer progTags = (RecordContainer) - getSheetContainer().findFirstOfType( - RecordTypes.ProgTags.typeID - ); - if(progTags != null) { - RecordContainer progBinaryTag = (RecordContainer) - progTags.findFirstOfType( - RecordTypes.ProgBinaryTag.typeID - ); - if(progBinaryTag != null) { - RecordContainer binaryTags = (RecordContainer) - progBinaryTag.findFirstOfType( - RecordTypes.BinaryTagData.typeID - ); - if(binaryTags != null) { - // This is where they'll be - int count = 0; - for(int i=0; i newParas = shape.getTextParagraphs(); - _paragraphs.add(newParas); - } - - /** This will return an atom per TextBox, so if the page has two text boxes the method should return two atoms. */ - public StyleTextProp9Atom[] getNumberedListInfo() { - return this.getPPDrawing().getNumberedListInfo(); - } - - public EscherTextboxWrapper[] getTextboxWrappers() { - return this.getPPDrawing().getTextboxWrappers(); - } - - public void setHidden(boolean hidden) { - org.apache.poi.hslf.record.Slide cont = getSlideRecord(); - - SSSlideInfoAtom slideInfo = - (SSSlideInfoAtom)cont.findFirstOfType(RecordTypes.SSSlideInfoAtom.typeID); - if (slideInfo == null) { - slideInfo = new SSSlideInfoAtom(); - cont.addChildAfter(slideInfo, cont.findFirstOfType(RecordTypes.SlideAtom.typeID)); - } - - slideInfo.setEffectTransitionFlagByBit(SSSlideInfoAtom.HIDDEN_BIT, hidden); - } - - public boolean getHidden() { - SSSlideInfoAtom slideInfo = - (SSSlideInfoAtom)getSlideRecord().findFirstOfType(RecordTypes.SSSlideInfoAtom.typeID); - return (slideInfo == null) - ? false - : slideInfo.getEffectTransitionFlagByBit(SSSlideInfoAtom.HIDDEN_BIT); - } - - @Override - public void draw(Graphics2D graphics) { - DrawFactory drawFact = DrawFactory.getInstance(graphics); - Drawable draw = drawFact.getDrawable(this); - draw.draw(graphics); - } - - @Override - public boolean getFollowMasterColourScheme() { - return false; - } - - @Override - public void setFollowMasterColourScheme(boolean follow) { - } - - @Override - public boolean getFollowMasterGraphics() { - return getFollowMasterObjects(); - } - - @Override - public boolean getDisplayPlaceholder(Placeholder placeholder) { - HeadersFooters hf = getHeadersFooters(); - SlideLayoutType slt = getSlideRecord().getSlideAtom().getSSlideLayoutAtom().getGeometryType(); - boolean isTitle = - (slt == SlideLayoutType.TITLE_SLIDE || slt == SlideLayoutType.TITLE_ONLY || slt == SlideLayoutType.MASTER_TITLE); - if (hf != null) { - switch (placeholder) { - case DATETIME: - return hf.isDateTimeVisible() && !isTitle; - case SLIDE_NUMBER: - return hf.isSlideNumberVisible() && !isTitle; - case HEADER: - return hf.isHeaderVisible() && !isTitle; - case FOOTER: - return hf.isFooterVisible() && !isTitle; - default: - break; - } - } - return false; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSlideMaster.java b/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSlideMaster.java deleted file mode 100644 index 7919dc2c0..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSlideMaster.java +++ /dev/null @@ -1,169 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.usermodel; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.hslf.exceptions.HSLFException; -import org.apache.poi.hslf.model.textproperties.TextProp; -import org.apache.poi.hslf.model.textproperties.TextPropCollection; -import org.apache.poi.hslf.record.MainMaster; -import org.apache.poi.hslf.record.TextHeaderAtom; -import org.apache.poi.hslf.record.TxMasterStyleAtom; -import org.apache.poi.util.Internal; - -/** - * SlideMaster determines the graphics, layout, and formatting for all the slides in a given presentation. - * It stores information about default font styles, placeholder sizes and positions, - * background design, and color schemes. - * - * @author Yegor Kozlov - */ -public final class HSLFSlideMaster extends HSLFMasterSheet { - private final List> _paragraphs = new ArrayList>(); - - /** - * all TxMasterStyleAtoms available in this master - */ - private TxMasterStyleAtom[] _txmaster; - - /** - * Constructs a SlideMaster from the MainMaster record, - * - */ - public HSLFSlideMaster(MainMaster record, int sheetNo) { - super(record, sheetNo); - - for (List l : HSLFTextParagraph.findTextParagraphs(getPPDrawing(), this)) { - if (!_paragraphs.contains(l)) { - _paragraphs.add(l); - } - } - } - - /** - * Returns an array of all the TextRuns found - */ - @Override - public List> getTextParagraphs() { - return _paragraphs; - } - - /** - * Returns null since SlideMasters doen't have master sheet. - */ - @Override - public HSLFMasterSheet getMasterSheet() { - return null; - } - - /** - * Pickup a style attribute from the master. - * This is the "workhorse" which returns the default style attributes. - */ - @Override - public TextProp getStyleAttribute(int txtype, int level, String name, boolean isCharacter) { - if (_txmaster.length <= txtype) { - return null; - } - TxMasterStyleAtom t = _txmaster[txtype]; - List styles = isCharacter ? t.getCharacterStyles() : t.getParagraphStyles(); - - TextProp prop = null; - for (int i = Math.min(level, styles.size()-1); prop == null && i >= 0; i--) { - prop = styles.get(i).findByName(name); - } - - if (prop != null) { - return prop; - } - - switch (txtype) { - case TextHeaderAtom.CENTRE_BODY_TYPE: - case TextHeaderAtom.HALF_BODY_TYPE: - case TextHeaderAtom.QUARTER_BODY_TYPE: - txtype = TextHeaderAtom.BODY_TYPE; - break; - case TextHeaderAtom.CENTER_TITLE_TYPE: - txtype = TextHeaderAtom.TITLE_TYPE; - break; - default: - return null; - } - - return getStyleAttribute(txtype, level, name, isCharacter); - } - - /** - * Assign SlideShow for this slide master. - */ - @Internal - @Override - protected void setSlideShow(HSLFSlideShow ss) { - super.setSlideShow(ss); - - //after the slide show is assigned collect all available style records - assert (_txmaster == null); - _txmaster = new TxMasterStyleAtom[9]; - - TxMasterStyleAtom txdoc = getSlideShow().getDocumentRecord().getEnvironment().getTxMasterStyleAtom(); - _txmaster[txdoc.getTextType()] = txdoc; - - TxMasterStyleAtom[] txrec = ((MainMaster)getSheetContainer()).getTxMasterStyleAtoms(); - for (int i = 0; i < txrec.length; i++) { - int txType = txrec[i].getTextType(); - if (txType < _txmaster.length && _txmaster[txType] == null) { - _txmaster[txType] = txrec[i]; - } - } - - for (List paras : getTextParagraphs()) { - for (HSLFTextParagraph htp : paras) { - int txType = htp.getRunType(); - if (txType >= _txmaster.length || _txmaster[txType] == null) { - throw new HSLFException("Master styles not initialized"); - } - - int level = htp.getIndentLevel(); - - List charStyles = _txmaster[txType].getCharacterStyles(); - List paragraphStyles = _txmaster[txType].getParagraphStyles(); - if (charStyles == null || paragraphStyles == null || - charStyles.size() <= level || paragraphStyles.size() <= level) { - throw new HSLFException("Master styles not initialized"); - } - - htp.setMasterStyleReference(paragraphStyles.get(level)); - for (HSLFTextRun htr : htp.getTextRuns()) { - htr.setMasterStyleReference(charStyles.get(level)); - } - } - } - } - - @Override - protected void onAddTextShape(HSLFTextShape shape) { - List runs = shape.getTextParagraphs(); - _paragraphs.add(runs); - } - - public TxMasterStyleAtom[] getTxMasterStyleAtoms(){ - return _txmaster; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSlideShow.java b/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSlideShow.java deleted file mode 100644 index 17210bd9c..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSlideShow.java +++ /dev/null @@ -1,1150 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.usermodel; - -import java.awt.Dimension; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.Closeable; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.poi.ddf.EscherBSERecord; -import org.apache.poi.ddf.EscherContainerRecord; -import org.apache.poi.ddf.EscherOptRecord; -import org.apache.poi.hpsf.ClassID; -import org.apache.poi.hslf.exceptions.CorruptPowerPointFileException; -import org.apache.poi.hslf.exceptions.HSLFException; -import org.apache.poi.hslf.model.HeadersFooters; -import org.apache.poi.hslf.model.MovieShape; -import org.apache.poi.hslf.model.PPFont; -import org.apache.poi.hslf.record.*; -import org.apache.poi.hslf.record.SlideListWithText.SlideAtomsSet; -import org.apache.poi.poifs.filesystem.DirectoryNode; -import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.sl.usermodel.MasterSheet; -import org.apache.poi.sl.usermodel.PictureData.PictureType; -import org.apache.poi.sl.usermodel.Resources; -import org.apache.poi.sl.usermodel.SlideShow; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.Internal; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.util.Units; - -/** - * This class is a friendly wrapper on top of the more scary HSLFSlideShow. - * - * TODO: - figure out how to match notes to their correct sheet (will involve - * understanding DocSlideList and DocNotesList) - handle Slide creation cleaner - */ -public final class HSLFSlideShow implements SlideShow, Closeable { - enum LoadSavePhase { - INIT, LOADED - } - private static final ThreadLocal loadSavePhase = new ThreadLocal(); - - // What we're based on - private final HSLFSlideShowImpl _hslfSlideShow; - - // Pointers to the most recent versions of the core records - // (Document, Notes, Slide etc) - private Record[] _mostRecentCoreRecords; - // Lookup between the PersitPtr "sheet" IDs, and the position - // in the mostRecentCoreRecords array - private Map _sheetIdToCoreRecordsLookup; - - // Records that are interesting - private Document _documentRecord; - - // Friendly objects for people to deal with - private final List _masters = new ArrayList(); - private final List _titleMasters = new ArrayList(); - private final List _slides = new ArrayList(); - private final List _notes = new ArrayList(); - private FontCollection _fonts; - - // For logging - private static final POILogger logger = POILogFactory.getLogger(HSLFSlideShow.class); - - - /** - * Constructs a Powerpoint document from the underlying - * HSLFSlideShow object. Finds the model stuff from this - * - * @param hslfSlideShow the HSLFSlideShow to base on - */ - public HSLFSlideShow(HSLFSlideShowImpl hslfSlideShow) { - loadSavePhase.set(LoadSavePhase.INIT); - - // Get useful things from our base slideshow - _hslfSlideShow = hslfSlideShow; - - // Handle Parent-aware Records - for (Record record : _hslfSlideShow.getRecords()) { - if(record instanceof RecordContainer){ - RecordContainer.handleParentAwareRecords((RecordContainer)record); - } - } - - // Find the versions of the core records we'll want to use - findMostRecentCoreRecords(); - - // Build up the model level Slides and Notes - buildSlidesAndNotes(); - - loadSavePhase.set(LoadSavePhase.LOADED); - } - - /** - * Constructs a new, empty, Powerpoint document. - */ - public HSLFSlideShow() { - this(HSLFSlideShowImpl.create()); - } - - /** - * Constructs a Powerpoint document from an input stream. - */ - @SuppressWarnings("resource") - public HSLFSlideShow(InputStream inputStream) throws IOException { - this(new HSLFSlideShowImpl(inputStream)); - } - - /** - * Constructs a Powerpoint document from an POIFSFileSystem. - */ - @SuppressWarnings("resource") - public HSLFSlideShow(NPOIFSFileSystem npoifs) throws IOException { - this(new HSLFSlideShowImpl(npoifs)); - } - - /** - * Constructs a Powerpoint document from an DirectoryNode. - */ - @SuppressWarnings("resource") - public HSLFSlideShow(DirectoryNode root) throws IOException { - this(new HSLFSlideShowImpl(root)); - } - - /** - * @return the current loading/saving phase - */ - protected static LoadSavePhase getLoadSavePhase() { - return loadSavePhase.get(); - } - - /** - * Use the PersistPtrHolder entries to figure out what is the "most recent" - * version of all the core records (Document, Notes, Slide etc), and save a - * record of them. Do this by walking from the oldest PersistPtr to the - * newest, overwriting any references found along the way with newer ones - */ - private void findMostRecentCoreRecords() { - // To start with, find the most recent in the byte offset domain - Map mostRecentByBytes = new HashMap(); - for (Record record : _hslfSlideShow.getRecords()) { - if (record instanceof PersistPtrHolder) { - PersistPtrHolder pph = (PersistPtrHolder) record; - - // If we've already seen any of the "slide" IDs for this - // PersistPtr, remove their old positions - int[] ids = pph.getKnownSlideIDs(); - for (int id : ids) { - if (mostRecentByBytes.containsKey(id)) { - mostRecentByBytes.remove(id); - } - } - - // Now, update the byte level locations with their latest values - Map thisSetOfLocations = pph.getSlideLocationsLookup(); - for (int id : ids) { - mostRecentByBytes.put(id, thisSetOfLocations.get(id)); - } - } - } - - // We now know how many unique special records we have, so init - // the array - _mostRecentCoreRecords = new Record[mostRecentByBytes.size()]; - - // We'll also want to be able to turn the slide IDs into a position - // in this array - _sheetIdToCoreRecordsLookup = new HashMap(); - Integer[] allIDs = mostRecentByBytes.keySet().toArray(new Integer[mostRecentByBytes.size()]); - Arrays.sort(allIDs); - for (int i = 0; i < allIDs.length; i++) { - _sheetIdToCoreRecordsLookup.put(allIDs[i], i); - } - - Map mostRecentByBytesRev = new HashMap(mostRecentByBytes.size()); - for (Map.Entry me : mostRecentByBytes.entrySet()) { - mostRecentByBytesRev.put(me.getValue(), me.getKey()); - } - - // Now convert the byte offsets back into record offsets - for (Record record : _hslfSlideShow.getRecords()) { - if (!(record instanceof PositionDependentRecord)) { - continue; - } - - PositionDependentRecord pdr = (PositionDependentRecord) record; - int recordAt = pdr.getLastOnDiskOffset(); - - Integer thisID = mostRecentByBytesRev.get(recordAt); - - if (thisID == null) { - continue; - } - - // Bingo. Now, where do we store it? - int storeAt = _sheetIdToCoreRecordsLookup.get(thisID); - - // Tell it its Sheet ID, if it cares - if (pdr instanceof PositionDependentRecordContainer) { - PositionDependentRecordContainer pdrc = (PositionDependentRecordContainer) record; - pdrc.setSheetId(thisID); - } - - // Finally, save the record - _mostRecentCoreRecords[storeAt] = record; - } - - // Now look for the interesting records in there - for (Record record : _mostRecentCoreRecords) { - // Check there really is a record at this number - if (record != null) { - // Find the Document, and interesting things in it - if (record.getRecordType() == RecordTypes.Document.typeID) { - _documentRecord = (Document) record; - _fonts = _documentRecord.getEnvironment().getFontCollection(); - } - } /*else { - // No record at this number - // Odd, but not normally a problem - }*/ - } - } - - /** - * For a given SlideAtomsSet, return the core record, based on the refID - * from the SlidePersistAtom - */ - private Record getCoreRecordForSAS(SlideAtomsSet sas) { - SlidePersistAtom spa = sas.getSlidePersistAtom(); - int refID = spa.getRefID(); - return getCoreRecordForRefID(refID); - } - - /** - * For a given refID (the internal, 0 based numbering scheme), return the - * core record - * - * @param refID - * the refID - */ - private Record getCoreRecordForRefID(int refID) { - Integer coreRecordId = _sheetIdToCoreRecordsLookup.get(refID); - if (coreRecordId != null) { - return _mostRecentCoreRecords[coreRecordId]; - } - logger.log(POILogger.ERROR, - "We tried to look up a reference to a core record, but there was no core ID for reference ID " - + refID); - return null; - } - - /** - * Build up model level Slide and Notes objects, from the underlying - * records. - */ - private void buildSlidesAndNotes() { - // Ensure we really found a Document record earlier - // If we didn't, then the file is probably corrupt - if (_documentRecord == null) { - throw new CorruptPowerPointFileException( - "The PowerPoint file didn't contain a Document Record in its PersistPtr blocks. It is probably corrupt."); - } - - // Fetch the SlideListWithTexts in the most up-to-date Document Record - // - // As far as we understand it: - // * The first SlideListWithText will contain a SlideAtomsSet - // for each of the master slides - // * The second SlideListWithText will contain a SlideAtomsSet - // for each of the slides, in their current order - // These SlideAtomsSets will normally contain text - // * The third SlideListWithText (if present), will contain a - // SlideAtomsSet for each Notes - // These SlideAtomsSets will not normally contain text - // - // Having indentified the masters, slides and notes + their orders, - // we have to go and find their matching records - // We always use the latest versions of these records, and use the - // SlideAtom/NotesAtom to match them with the StyleAtomSet - - findMasterSlides(); - - // Having sorted out the masters, that leaves the notes and slides - Map slideIdToNotes = new HashMap(); - - // Start by finding the notes records - findNotesSlides(slideIdToNotes); - - // Now, do the same thing for our slides - findSlides(slideIdToNotes); - } - - /** - * Find master slides - * These can be MainMaster records, but oddly they can also be - * Slides or Notes, and possibly even other odd stuff.... - * About the only thing you can say is that the master details are in the first SLWT. - */ - private void findMasterSlides() { - SlideListWithText masterSLWT = _documentRecord.getMasterSlideListWithText(); - if (masterSLWT == null) { - return; - } - - for (SlideAtomsSet sas : masterSLWT.getSlideAtomsSets()) { - Record r = getCoreRecordForSAS(sas); - int sheetNo = sas.getSlidePersistAtom().getSlideIdentifier(); - if (r instanceof Slide) { - HSLFTitleMaster master = new HSLFTitleMaster((Slide)r, sheetNo); - master.setSlideShow(this); - _titleMasters.add(master); - } else if (r instanceof MainMaster) { - HSLFSlideMaster master = new HSLFSlideMaster((MainMaster)r, sheetNo); - master.setSlideShow(this); - _masters.add(master); - } - } - } - - private void findNotesSlides(Map slideIdToNotes) { - SlideListWithText notesSLWT = _documentRecord.getNotesSlideListWithText(); - - if (notesSLWT == null) { - return; - } - - // Match up the records and the SlideAtomSets - int idx = -1; - for (SlideAtomsSet notesSet : notesSLWT.getSlideAtomsSets()) { - idx++; - // Get the right core record - Record r = getCoreRecordForSAS(notesSet); - SlidePersistAtom spa = notesSet.getSlidePersistAtom(); - - String loggerLoc = "A Notes SlideAtomSet at "+idx+" said its record was at refID "+spa.getRefID(); - - // we need to add null-records, otherwise the index references to other existing don't work anymore - if (r == null) { - logger.log(POILogger.WARN, loggerLoc+", but that record didn't exist - record ignored."); - continue; - } - - // Ensure it really is a notes record - if (!(r instanceof Notes)) { - logger.log(POILogger.ERROR, loggerLoc+", but that was actually a " + r); - continue; - } - - Notes notesRecord = (Notes) r; - - // Record the match between slide id and these notes - int slideId = spa.getSlideIdentifier(); - slideIdToNotes.put(slideId, idx); - - HSLFNotes hn = new HSLFNotes(notesRecord); - hn.setSlideShow(this); - _notes.add(hn); - } - } - - private void findSlides(Map slideIdToNotes) { - SlideListWithText slidesSLWT = _documentRecord.getSlideSlideListWithText(); - if (slidesSLWT == null) { - return; - } - - // Match up the records and the SlideAtomSets - int idx = -1; - for (SlideAtomsSet sas : slidesSLWT.getSlideAtomsSets()) { - idx++; - // Get the right core record - SlidePersistAtom spa = sas.getSlidePersistAtom(); - Record r = getCoreRecordForSAS(sas); - - // Ensure it really is a slide record - if (!(r instanceof Slide)) { - logger.log(POILogger.ERROR, "A Slide SlideAtomSet at " + idx - + " said its record was at refID " - + spa.getRefID() - + ", but that was actually a " + r); - continue; - } - - Slide slide = (Slide)r; - - // Do we have a notes for this? - HSLFNotes notes = null; - // Slide.SlideAtom.notesId references the corresponding notes slide. - // 0 if slide has no notes. - int noteId = slide.getSlideAtom().getNotesID(); - if (noteId != 0) { - Integer notesPos = slideIdToNotes.get(noteId); - if (notesPos != null && 0 <= notesPos && notesPos < _notes.size()) { - notes = _notes.get(notesPos); - } else { - logger.log(POILogger.ERROR, "Notes not found for noteId=" + noteId); - } - } - - // Now, build our slide - int slideIdentifier = spa.getSlideIdentifier(); - HSLFSlide hs = new HSLFSlide(slide, notes, sas, slideIdentifier, (idx + 1)); - hs.setSlideShow(this); - _slides.add(hs); - } - } - - @Override - public void write(OutputStream out) throws IOException { - // check for text paragraph modifications - for (HSLFSlide sl : getSlides()) { - writeDirtyParagraphs(sl); - } - - for (HSLFSlideMaster sl : getSlideMasters()) { - boolean isDirty = false; - for (List paras : sl.getTextParagraphs()) { - for (HSLFTextParagraph p : paras) { - isDirty |= p.isDirty(); - } - } - if (isDirty) { - for (TxMasterStyleAtom sa : sl.getTxMasterStyleAtoms()) { - if (sa != null) { - // not all master style atoms are set - index 3 is typically null - sa.updateStyles(); - } - } - } - } - - _hslfSlideShow.write(out); - } - - private void writeDirtyParagraphs(HSLFShapeContainer container) { - for (HSLFShape sh : container.getShapes()) { - if (sh instanceof HSLFShapeContainer) { - writeDirtyParagraphs((HSLFShapeContainer)sh); - } else if (sh instanceof HSLFTextShape) { - HSLFTextShape hts = (HSLFTextShape)sh; - boolean isDirty = false; - for (HSLFTextParagraph p : hts.getTextParagraphs()) { - isDirty |= p.isDirty(); - } - if (isDirty) { - hts.storeText(); - } - } - } - } - - /** - * Returns an array of the most recent version of all the interesting - * records - */ - public Record[] getMostRecentCoreRecords() { - return _mostRecentCoreRecords; - } - - /** - * Returns an array of all the normal Slides found in the slideshow - */ - @Override - public List getSlides() { - return _slides; - } - - /** - * Returns an array of all the normal Notes found in the slideshow - */ - public List getNotes() { - return _notes; - } - - /** - * Returns an array of all the normal Slide Masters found in the slideshow - */ - @Override - public List getSlideMasters() { - return _masters; - } - - /** - * Returns an array of all the normal Title Masters found in the slideshow - */ - public List getTitleMasters() { - return _titleMasters; - } - - @Override - public List getPictureData() { - return _hslfSlideShow.getPictureData(); - } - - /** - * Returns the data of all the embedded OLE object in the SlideShow - */ - public HSLFObjectData[] getEmbeddedObjects() { - return _hslfSlideShow.getEmbeddedObjects(); - } - - /** - * Returns the data of all the embedded sounds in the SlideShow - */ - public HSLFSoundData[] getSoundData() { - return HSLFSoundData.find(_documentRecord); - } - - @Override - public Dimension getPageSize() { - DocumentAtom docatom = _documentRecord.getDocumentAtom(); - int pgx = (int)Units.masterToPoints((int)docatom.getSlideSizeX()); - int pgy = (int)Units.masterToPoints((int)docatom.getSlideSizeY()); - return new Dimension(pgx, pgy); - } - - @Override - public void setPageSize(Dimension pgsize) { - DocumentAtom docatom = _documentRecord.getDocumentAtom(); - docatom.setSlideSizeX(Units.pointsToMaster(pgsize.width)); - docatom.setSlideSizeY(Units.pointsToMaster(pgsize.height)); - } - - /** - * Helper method for usermodel: Get the font collection - */ - protected FontCollection getFontCollection() { - return _fonts; - } - - /** - * Helper method for usermodel and model: Get the document record - */ - public Document getDocumentRecord() { - return _documentRecord; - } - - /** - * Re-orders a slide, to a new position. - * - * @param oldSlideNumber - * The old slide number (1 based) - * @param newSlideNumber - * The new slide number (1 based) - */ - public void reorderSlide(int oldSlideNumber, int newSlideNumber) { - // Ensure these numbers are valid - if (oldSlideNumber < 1 || newSlideNumber < 1) { - throw new IllegalArgumentException("Old and new slide numbers must be greater than 0"); - } - if (oldSlideNumber > _slides.size() || newSlideNumber > _slides.size()) { - throw new IllegalArgumentException( - "Old and new slide numbers must not exceed the number of slides (" - + _slides.size() + ")"); - } - - // The order of slides is defined by the order of slide atom sets in the - // SlideListWithText container. - SlideListWithText slwt = _documentRecord.getSlideSlideListWithText(); - SlideAtomsSet[] sas = slwt.getSlideAtomsSets(); - - SlideAtomsSet tmp = sas[oldSlideNumber - 1]; - sas[oldSlideNumber - 1] = sas[newSlideNumber - 1]; - sas[newSlideNumber - 1] = tmp; - - Collections.swap(_slides, oldSlideNumber - 1, newSlideNumber - 1); - _slides.get(newSlideNumber - 1).setSlideNumber(newSlideNumber); - _slides.get(oldSlideNumber - 1).setSlideNumber(oldSlideNumber); - - ArrayList lst = new ArrayList(); - for (SlideAtomsSet s : sas) { - lst.add(s.getSlidePersistAtom()); - lst.addAll(Arrays.asList(s.getSlideRecords())); - } - - Record[] r = lst.toArray(new Record[lst.size()]); - slwt.setChildRecord(r); - } - - /** - * Removes the slide at the given index (0-based). - *

    - * Shifts any subsequent slides to the left (subtracts one from their slide - * numbers). - *

    - * - * @param index - * the index of the slide to remove (0-based) - * @return the slide that was removed from the slide show. - */ - public HSLFSlide removeSlide(int index) { - int lastSlideIdx = _slides.size() - 1; - if (index < 0 || index > lastSlideIdx) { - throw new IllegalArgumentException("Slide index (" + index + ") is out of range (0.." - + lastSlideIdx + ")"); - } - - SlideListWithText slwt = _documentRecord.getSlideSlideListWithText(); - SlideAtomsSet[] sas = slwt.getSlideAtomsSets(); - - List records = new ArrayList(); - List sa = new ArrayList(Arrays.asList(sas)); - - HSLFSlide removedSlide = _slides.remove(index); - _notes.remove(removedSlide.getNotes()); - sa.remove(index); - - int i=0; - for (HSLFSlide s : _slides) { - s.setSlideNumber(i++); - } - - for (SlideAtomsSet s : sa) { - records.add(s.getSlidePersistAtom()); - records.addAll(Arrays.asList(s.getSlideRecords())); - } - if (sa.isEmpty()) { - _documentRecord.removeSlideListWithText(slwt); - } else { - slwt.setSlideAtomsSets(sa.toArray(new SlideAtomsSet[sa.size()])); - slwt.setChildRecord(records.toArray(new Record[records.size()])); - } - - // if the removed slide had notes - remove references to them too - - int notesId = removedSlide.getSlideRecord().getSlideAtom().getNotesID(); - if (notesId != 0) { - SlideListWithText nslwt = _documentRecord.getNotesSlideListWithText(); - records = new ArrayList(); - ArrayList na = new ArrayList(); - for (SlideAtomsSet ns : nslwt.getSlideAtomsSets()) { - if (ns.getSlidePersistAtom().getSlideIdentifier() == notesId) { - continue; - } - na.add(ns); - records.add(ns.getSlidePersistAtom()); - if (ns.getSlideRecords() != null) { - records.addAll(Arrays.asList(ns.getSlideRecords())); - } - } - if (na.isEmpty()) { - _documentRecord.removeSlideListWithText(nslwt); - } else { - nslwt.setSlideAtomsSets(na.toArray(new SlideAtomsSet[na.size()])); - nslwt.setChildRecord(records.toArray(new Record[records.size()])); - } - } - - return removedSlide; - } - - /** - * Create a blank Slide. - * - * @return the created Slide - */ - @Override - public HSLFSlide createSlide() { - // We need to add the records to the SLWT that deals - // with Slides. - // Add it, if it doesn't exist - SlideListWithText slist = _documentRecord.getSlideSlideListWithText(); - if (slist == null) { - // Need to add a new one - slist = new SlideListWithText(); - slist.setInstance(SlideListWithText.SLIDES); - _documentRecord.addSlideListWithText(slist); - } - - // Grab the SlidePersistAtom with the highest Slide Number. - // (Will stay as null if no SlidePersistAtom exists yet in - // the slide, or only master slide's ones do) - SlidePersistAtom prev = null; - for (SlideAtomsSet sas : slist.getSlideAtomsSets()) { - SlidePersistAtom spa = sas.getSlidePersistAtom(); - if (spa.getSlideIdentifier() < 0) { - // This is for a master slide - // Odd, since we only deal with the Slide SLWT - } else { - // Must be for a real slide - if (prev == null) { - prev = spa; - } - if (prev.getSlideIdentifier() < spa.getSlideIdentifier()) { - prev = spa; - } - } - } - - // Set up a new SlidePersistAtom for this slide - SlidePersistAtom sp = new SlidePersistAtom(); - - // First slideId is always 256 - sp.setSlideIdentifier(prev == null ? 256 : (prev.getSlideIdentifier() + 1)); - - // Add this new SlidePersistAtom to the SlideListWithText - slist.addSlidePersistAtom(sp); - - // Create a new Slide - HSLFSlide slide = new HSLFSlide(sp.getSlideIdentifier(), sp.getRefID(), _slides.size() + 1); - slide.setSlideShow(this); - slide.onCreate(); - - // Add in to the list of Slides - _slides.add(slide); - logger.log(POILogger.INFO, "Added slide " + _slides.size() + " with ref " + sp.getRefID() - + " and identifier " + sp.getSlideIdentifier()); - - // Add the core records for this new Slide to the record tree - Slide slideRecord = slide.getSlideRecord(); - int psrId = addPersistentObject(slideRecord); - sp.setRefID(psrId); - slideRecord.setSheetId(psrId); - - slide.setMasterSheet(_masters.get(0)); - // All done and added - return slide; - } - - @Override - public HSLFPictureData addPicture(byte[] data, PictureType format) throws IOException { - if (format == null || format.nativeId == -1) { - throw new IllegalArgumentException("Unsupported picture format: " + format); - } - - HSLFPictureData pd = findPictureData(data); - if (pd != null) { - // identical picture was already added to the SlideShow - return pd; - } - - EscherContainerRecord bstore; - - EscherContainerRecord dggContainer = _documentRecord.getPPDrawingGroup().getDggContainer(); - bstore = (EscherContainerRecord) HSLFShape.getEscherChild(dggContainer, - EscherContainerRecord.BSTORE_CONTAINER); - if (bstore == null) { - bstore = new EscherContainerRecord(); - bstore.setRecordId(EscherContainerRecord.BSTORE_CONTAINER); - - dggContainer.addChildBefore(bstore, EscherOptRecord.RECORD_ID); - } - - HSLFPictureData pict = HSLFPictureData.create(format); - pict.setData(data); - - int offset = _hslfSlideShow.addPicture(pict); - - EscherBSERecord bse = new EscherBSERecord(); - bse.setRecordId(EscherBSERecord.RECORD_ID); - bse.setOptions((short) (0x0002 | (format.nativeId << 4))); - bse.setSize(pict.getRawData().length + 8); - byte[] uid = HSLFPictureData.getChecksum(data); - bse.setUid(uid); - - bse.setBlipTypeMacOS((byte) format.nativeId); - bse.setBlipTypeWin32((byte) format.nativeId); - - if (format == PictureType.EMF) { - bse.setBlipTypeMacOS((byte) PictureType.PICT.nativeId); - } else if (format == PictureType.WMF) { - bse.setBlipTypeMacOS((byte) PictureType.PICT.nativeId); - } else if (format == PictureType.PICT) { - bse.setBlipTypeWin32((byte) PictureType.WMF.nativeId); - } - - bse.setRef(0); - bse.setOffset(offset); - bse.setRemainingData(new byte[0]); - - bstore.addChildRecord(bse); - int count = bstore.getChildRecords().size(); - bstore.setOptions((short) ((count << 4) | 0xF)); - - return pict; - } - - /** - * Adds a picture to the presentation. - * - * @param is The stream to read the image from - * @param format The format of the picture. - * - * @return the picture data. - * @since 3.15 beta 2 - */ - @Override - public HSLFPictureData addPicture(InputStream is, PictureType format) throws IOException { - if (format == null || format.nativeId == -1) { // fail early - throw new IllegalArgumentException("Unsupported picture format: " + format); - } - return addPicture(IOUtils.toByteArray(is), format); - } - - /** - * Adds a picture to the presentation. - * - * @param pict - * the file containing the image to add - * @param format - * The format of the picture. - * - * @return the picture data. - * @since 3.15 beta 2 - */ - @Override - public HSLFPictureData addPicture(File pict, PictureType format) throws IOException { - if (format == null || format.nativeId == -1) { // fail early - throw new IllegalArgumentException("Unsupported picture format: " + format); - } - int length = (int) pict.length(); - byte[] data = new byte[length]; - FileInputStream is = new FileInputStream(pict); - try { - IOUtils.readFully(is, data); - } finally { - is.close(); - } - return addPicture(data, format); - } - - /** - * check if a picture with this picture data already exists in this presentation - * - * @param pictureData The picture data to find in the SlideShow - * @return {@code null} if picture data is not found in this slideshow - * @since 3.15 beta 3 - */ - @Override - public HSLFPictureData findPictureData(byte[] pictureData) { - byte[] uid = HSLFPictureData.getChecksum(pictureData); - - for (HSLFPictureData pic : getPictureData()) { - if (Arrays.equals(pic.getUID(), uid)) { - return pic; - } - } - return null; - } - - /** - * Add a font in this presentation - * - * @param font - * the font to add - * @return 0-based index of the font - */ - public int addFont(PPFont font) { - FontCollection fonts = getDocumentRecord().getEnvironment().getFontCollection(); - int idx = fonts.getFontIndex(font.getFontName()); - if (idx == -1) { - idx = fonts.addFont(font.getFontName(), font.getCharSet(), font.getFontFlags(), font - .getFontType(), font.getPitchAndFamily()); - } - return idx; - } - - /** - * Get a font by index - * - * @param idx - * 0-based index of the font - * @return of an instance of PPFont or null if not - * found - */ - public PPFont getFont(int idx) { - FontCollection fonts = getDocumentRecord().getEnvironment().getFontCollection(); - for (Record ch : fonts.getChildRecords()) { - if (ch instanceof FontEntityAtom) { - FontEntityAtom atom = (FontEntityAtom) ch; - if (atom.getFontIndex() == idx) { - return new PPFont(atom); - } - } - } - return null; - } - - /** - * get the number of fonts in the presentation - * - * @return number of fonts - */ - public int getNumberOfFonts() { - return getDocumentRecord().getEnvironment().getFontCollection().getNumberOfFonts(); - } - - /** - * Return Header / Footer settings for slides - * - * @return Header / Footer settings for slides - */ - public HeadersFooters getSlideHeadersFooters() { - return new HeadersFooters(this, HeadersFootersContainer.SlideHeadersFootersContainer); - } - - /** - * Return Header / Footer settings for notes - * - * @return Header / Footer settings for notes - */ - public HeadersFooters getNotesHeadersFooters() { - if (_notes.isEmpty()) { - return new HeadersFooters(this, HeadersFootersContainer.NotesHeadersFootersContainer); - } else { - return new HeadersFooters(_notes.get(0), HeadersFootersContainer.NotesHeadersFootersContainer); - } - } - - /** - * Add a movie in this presentation - * - * @param path - * the path or url to the movie - * @return 0-based index of the movie - */ - public int addMovie(String path, int type) { - ExMCIMovie mci; - switch (type) { - case MovieShape.MOVIE_MPEG: - mci = new ExMCIMovie(); - break; - case MovieShape.MOVIE_AVI: - mci = new ExAviMovie(); - break; - default: - throw new IllegalArgumentException("Unsupported Movie: " + type); - } - - ExVideoContainer exVideo = mci.getExVideo(); - exVideo.getExMediaAtom().setMask(0xE80000); - exVideo.getPathAtom().setText(path); - - int objectId = addToObjListAtom(mci); - exVideo.getExMediaAtom().setObjectId(objectId); - - return objectId; - } - - /** - * Add a control in this presentation - * - * @param name - * name of the control, e.g. "Shockwave Flash Object" - * @param progId - * OLE Programmatic Identifier, e.g. - * "ShockwaveFlash.ShockwaveFlash.9" - * @return 0-based index of the control - */ - public int addControl(String name, String progId) { - ExControl ctrl = new ExControl(); - ctrl.setProgId(progId); - ctrl.setMenuName(name); - ctrl.setClipboardName(name); - - ExOleObjAtom oleObj = ctrl.getExOleObjAtom(); - oleObj.setDrawAspect(ExOleObjAtom.DRAW_ASPECT_VISIBLE); - oleObj.setType(ExOleObjAtom.TYPE_CONTROL); - oleObj.setSubType(ExOleObjAtom.SUBTYPE_DEFAULT); - - int objectId = addToObjListAtom(ctrl); - oleObj.setObjID(objectId); - return objectId; - } - - /** - * Add a embedded object to this presentation - * - * @return 0-based index of the embedded object - */ - public int addEmbed(POIFSFileSystem poiData) { - DirectoryNode root = poiData.getRoot(); - - // prepare embedded data - if (new ClassID().equals(root.getStorageClsid())) { - // need to set class id - Map olemap = getOleMap(); - ClassID classID = null; - for (Map.Entry entry : olemap.entrySet()) { - if (root.hasEntry(entry.getKey())) { - classID = entry.getValue(); - break; - } - } - if (classID == null) { - throw new IllegalArgumentException("Unsupported embedded document"); - } - - root.setStorageClsid(classID); - } - - ExEmbed exEmbed = new ExEmbed(); - // remove unneccessary infos, so we don't need to specify the type - // of the ole object multiple times - Record children[] = exEmbed.getChildRecords(); - exEmbed.removeChild(children[2]); - exEmbed.removeChild(children[3]); - exEmbed.removeChild(children[4]); - - ExEmbedAtom eeEmbed = exEmbed.getExEmbedAtom(); - eeEmbed.setCantLockServerB(true); - - ExOleObjAtom eeAtom = exEmbed.getExOleObjAtom(); - eeAtom.setDrawAspect(ExOleObjAtom.DRAW_ASPECT_VISIBLE); - eeAtom.setType(ExOleObjAtom.TYPE_EMBEDDED); - // eeAtom.setSubType(ExOleObjAtom.SUBTYPE_EXCEL); - // should be ignored?!?, see MS-PPT ExOleObjAtom, but Libre Office sets it ... - eeAtom.setOptions(1226240); - - ExOleObjStg exOleObjStg = new ExOleObjStg(); - try { - final String OLESTREAM_NAME = "\u0001Ole"; - if (!root.hasEntry(OLESTREAM_NAME)) { - // the following data was taken from an example libre office document - // beside this "\u0001Ole" record there were several other records, e.g. CompObj, - // OlePresXXX, but it seems, that they aren't neccessary - byte oleBytes[] = { 1, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; - poiData.createDocument(new ByteArrayInputStream(oleBytes), OLESTREAM_NAME); - } - - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - poiData.writeFilesystem(bos); - exOleObjStg.setData(bos.toByteArray()); - } catch (IOException e) { - throw new HSLFException(e); - } - - int psrId = addPersistentObject(exOleObjStg); - exOleObjStg.setPersistId(psrId); - eeAtom.setObjStgDataRef(psrId); - - int objectId = addToObjListAtom(exEmbed); - eeAtom.setObjID(objectId); - return objectId; - } - - protected int addToObjListAtom(RecordContainer exObj) { - ExObjList lst = getDocumentRecord().getExObjList(true); - ExObjListAtom objAtom = lst.getExObjListAtom(); - // increment the object ID seed - int objectId = (int) objAtom.getObjectIDSeed() + 1; - objAtom.setObjectIDSeed(objectId); - - lst.addChildAfter(exObj, objAtom); - - return objectId; - } - - protected static Map getOleMap() { - Map olemap = new HashMap(); - olemap.put("PowerPoint Document", ClassID.PPT_SHOW); - olemap.put("Workbook", ClassID.EXCEL97); // as per BIFF8 spec - olemap.put("WORKBOOK", ClassID.EXCEL97); // Typically from third party programs - olemap.put("BOOK", ClassID.EXCEL97); // Typically odd Crystal Reports exports - // ... to be continued - return olemap; - } - - protected int addPersistentObject(PositionDependentRecord slideRecord) { - slideRecord.setLastOnDiskOffset(HSLFSlideShowImpl.UNSET_OFFSET); - _hslfSlideShow.appendRootLevelRecord((Record)slideRecord); - - // For position dependent records, hold where they were and now are - // As we go along, update, and hand over, to any Position Dependent - // records we happen across - Map interestingRecords = - new HashMap(); - - try { - _hslfSlideShow.updateAndWriteDependantRecords(null,interestingRecords); - } catch (IOException e) { - throw new HSLFException(e); - } - - PersistPtrHolder ptr = (PersistPtrHolder)interestingRecords.get(RecordTypes.PersistPtrIncrementalBlock); - UserEditAtom usr = (UserEditAtom)interestingRecords.get(RecordTypes.UserEditAtom); - - // persist ID is UserEditAtom.maxPersistWritten + 1 - int psrId = usr.getMaxPersistWritten() + 1; - - // Last view is now of the slide - usr.setLastViewType((short) UserEditAtom.LAST_VIEW_SLIDE_VIEW); - // increment the number of persistent objects - usr.setMaxPersistWritten(psrId); - - // Add the new slide into the last PersistPtr - // (Also need to tell it where it is) - int slideOffset = slideRecord.getLastOnDiskOffset(); - slideRecord.setLastOnDiskOffset(slideOffset); - ptr.addSlideLookup(psrId, slideOffset); - logger.log(POILogger.INFO, "New slide/object ended up at " + slideOffset); - - return psrId; - } - - @Override - public MasterSheet createMasterSheet() throws IOException { - // TODO Auto-generated method stub - return null; - } - - @Override - public Resources getResources() { - // TODO Auto-generated method stub - return null; - } - - /** - * @return the handler class which holds the hslf records - */ - @Internal - public HSLFSlideShowImpl getSlideShowImpl() { - return _hslfSlideShow; - } - - @Override - public void close() throws IOException { - _hslfSlideShow.close(); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSlideShowEncrypted.java b/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSlideShowEncrypted.java deleted file mode 100644 index 1251904b2..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSlideShowEncrypted.java +++ /dev/null @@ -1,574 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.usermodel; - -import java.io.Closeable; -import java.io.IOException; -import java.io.OutputStream; -import java.security.GeneralSecurityException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.NavigableMap; -import java.util.TreeMap; - -import org.apache.poi.EncryptedDocumentException; -import org.apache.poi.hslf.exceptions.CorruptPowerPointFileException; -import org.apache.poi.hslf.exceptions.EncryptedPowerPointFileException; -import org.apache.poi.hslf.record.DocumentEncryptionAtom; -import org.apache.poi.hslf.record.PersistPtrHolder; -import org.apache.poi.hslf.record.PositionDependentRecord; -import org.apache.poi.hslf.record.Record; -import org.apache.poi.hslf.record.UserEditAtom; -import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey; -import org.apache.poi.poifs.crypt.ChunkedCipherInputStream; -import org.apache.poi.poifs.crypt.ChunkedCipherOutputStream; -import org.apache.poi.poifs.crypt.Decryptor; -import org.apache.poi.poifs.crypt.EncryptionInfo; -import org.apache.poi.poifs.crypt.cryptoapi.CryptoAPIDecryptor; -import org.apache.poi.poifs.crypt.cryptoapi.CryptoAPIEncryptor; -import org.apache.poi.util.BitField; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.Internal; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.LittleEndianByteArrayInputStream; -import org.apache.poi.util.LittleEndianByteArrayOutputStream; - -/** - * This class provides helper functions for encrypted PowerPoint documents. - */ -@Internal -public class HSLFSlideShowEncrypted implements Closeable { - DocumentEncryptionAtom dea; - CryptoAPIEncryptor enc = null; - CryptoAPIDecryptor dec = null; -// Cipher cipher = null; - ChunkedCipherOutputStream cyos = null; - - private static final BitField fieldRecInst = new BitField(0xFFF0); - - private static final int BLIB_STORE_ENTRY_PARTS[] = { - 1, // btWin32 - 1, // btMacOS - 16, // rgbUid - 2, // tag - 4, // size - 4, // cRef - 4, // foDelay - 1, // unused1 - 1, // cbName (@ index 33) - 1, // unused2 - 1, // unused3 - }; - - protected HSLFSlideShowEncrypted(DocumentEncryptionAtom dea) { - this.dea = dea; - } - - protected HSLFSlideShowEncrypted(byte[] docstream, NavigableMap recordMap) { - // check for DocumentEncryptionAtom, which would be at the last offset - // need to ignore already set UserEdit and PersistAtoms - UserEditAtom userEditAtomWithEncryption = null; - for (Map.Entry me : recordMap.descendingMap().entrySet()) { - Record r = me.getValue(); - if (!(r instanceof UserEditAtom)) { - continue; - } - UserEditAtom uea = (UserEditAtom)r; - if (uea.getEncryptSessionPersistIdRef() != -1) { - userEditAtomWithEncryption = uea; - break; - } - } - - if (userEditAtomWithEncryption == null) { - dea = null; - return; - } - - Record r = recordMap.get(userEditAtomWithEncryption.getPersistPointersOffset()); - assert(r instanceof PersistPtrHolder); - PersistPtrHolder ptr = (PersistPtrHolder)r; - - Integer encOffset = ptr.getSlideLocationsLookup().get(userEditAtomWithEncryption.getEncryptSessionPersistIdRef()); - if (encOffset == null) { - // encryption info doesn't exist anymore - // SoftMaker Freeoffice produces such invalid files - check for "SMNativeObjData" ole stream - dea = null; - return; - } - - r = recordMap.get(encOffset); - if (r == null) { - r = Record.buildRecordAtOffset(docstream, encOffset); - recordMap.put(encOffset, r); - } - assert(r instanceof DocumentEncryptionAtom); - this.dea = (DocumentEncryptionAtom)r; - decryptInit(); - - String pass = Biff8EncryptionKey.getCurrentUserPassword(); - if(!dec.verifyPassword(pass != null ? pass : Decryptor.DEFAULT_PASSWORD)) { - throw new EncryptedPowerPointFileException("PowerPoint file is encrypted. The correct password needs to be set via Biff8EncryptionKey.setCurrentUserPassword()"); - } - } - - public DocumentEncryptionAtom getDocumentEncryptionAtom() { - return dea; - } - - protected void decryptInit() { - if (dec != null) { - return; - } - EncryptionInfo ei = dea.getEncryptionInfo(); - dec = (CryptoAPIDecryptor)ei.getDecryptor(); - } - - protected void encryptInit() { - if (enc != null) { - return; - } - EncryptionInfo ei = dea.getEncryptionInfo(); - enc = (CryptoAPIEncryptor)ei.getEncryptor(); - } - - - - protected OutputStream encryptRecord(OutputStream plainStream, int persistId, Record record) { - boolean isPlain = (dea == null - || record instanceof UserEditAtom - || record instanceof PersistPtrHolder - || record instanceof DocumentEncryptionAtom - ); - - try { - if (isPlain) { - if (cyos != null) { - // write cached data to stream - cyos.flush(); - } - return plainStream; - } - - encryptInit(); - - if (cyos == null) { - enc.setChunkSize(-1); - cyos = enc.getDataStream(plainStream, 0); - } - cyos.initCipherForBlock(persistId, false); - } catch (Exception e) { - throw new EncryptedPowerPointFileException(e); - } - return cyos; - } - - private static void readFully(ChunkedCipherInputStream ccis, byte[] docstream, int offset, int len) throws IOException { - if (IOUtils.readFully(ccis, docstream, offset, len) == -1) { - throw new EncryptedPowerPointFileException("unexpected EOF"); - } - } - - protected void decryptRecord(byte[] docstream, int persistId, int offset) { - if (dea == null) { - return; - } - - decryptInit(); - dec.setChunkSize(-1); - LittleEndianByteArrayInputStream lei = new LittleEndianByteArrayInputStream(docstream, offset); // NOSONAR - ChunkedCipherInputStream ccis = null; - try { - ccis = dec.getDataStream(lei, docstream.length-offset, 0); - ccis.initCipherForBlock(persistId); - - // decrypt header and read length to be decrypted - readFully(ccis, docstream, offset, 8); - // decrypt the rest of the record - int rlen = (int)LittleEndian.getUInt(docstream, offset+4); - readFully(ccis, docstream, offset+8, rlen); - - } catch (Exception e) { - throw new EncryptedPowerPointFileException(e); - } finally { - IOUtils.closeQuietly(ccis); - IOUtils.closeQuietly(lei); - } - } - - private void decryptPicBytes(byte[] pictstream, int offset, int len) - throws IOException, GeneralSecurityException { - // when reading the picture elements, each time a segment is read, the cipher needs - // to be reset (usually done when calling Cipher.doFinal) - LittleEndianByteArrayInputStream lei = new LittleEndianByteArrayInputStream(pictstream, offset); - ChunkedCipherInputStream ccis = dec.getDataStream(lei, len, 0); - readFully(ccis, pictstream, offset, len); - ccis.close(); - lei.close(); - } - - protected void decryptPicture(byte[] pictstream, int offset) { - if (dea == null) { - return; - } - - decryptInit(); - - try { - // decrypt header and read length to be decrypted - decryptPicBytes(pictstream, offset, 8); - int recInst = fieldRecInst.getValue(LittleEndian.getUShort(pictstream, offset)); - int recType = LittleEndian.getUShort(pictstream, offset+2); - int rlen = (int)LittleEndian.getUInt(pictstream, offset+4); - offset += 8; - int endOffset = offset + rlen; - - if (recType == 0xF007) { - // TOOD: get a real example file ... to actual test the FBSE entry - // not sure where the foDelay block is - - // File BLIP Store Entry (FBSE) - for (int part : BLIB_STORE_ENTRY_PARTS) { - decryptPicBytes(pictstream, offset, part); - } - offset += 36; - - int cbName = LittleEndian.getUShort(pictstream, offset-3); - if (cbName > 0) { - // read nameData - decryptPicBytes(pictstream, offset, cbName); - offset += cbName; - } - - if (offset == endOffset) { - return; // no embedded blip - } - // fall through, read embedded blip now - - // update header data - decryptPicBytes(pictstream, offset, 8); - recInst = fieldRecInst.getValue(LittleEndian.getUShort(pictstream, offset)); - recType = LittleEndian.getUShort(pictstream, offset+2); - // rlen = (int)LittleEndian.getUInt(pictstream, offset+4); - offset += 8; - } - - int rgbUidCnt = (recInst == 0x217 || recInst == 0x3D5 || recInst == 0x46B || recInst == 0x543 || - recInst == 0x6E1 || recInst == 0x6E3 || recInst == 0x6E5 || recInst == 0x7A9) ? 2 : 1; - - // rgbUid 1/2 - for (int i=0; i 0) { - ccos.write(pictstream, offset, cbName); - ccos.flush(); - offset += cbName; - } - - if (offset == endOffset) { - return; // no embedded blip - } - // fall through, read embedded blip now - - // update header data - recInst = fieldRecInst.getValue(LittleEndian.getUShort(pictstream, offset)); - recType = LittleEndian.getUShort(pictstream, offset+2); - ccos.write(pictstream, offset, 8); - ccos.flush(); - offset += 8; - } - - int rgbUidCnt = (recInst == 0x217 || recInst == 0x3D5 || recInst == 0x46B || recInst == 0x543 || - recInst == 0x6E1 || recInst == 0x6E3 || recInst == 0x6E5 || recInst == 0x7A9) ? 2 : 1; - - for (int i=0; i done - return records; - } else { - // need to remove password data - dea = null; - return removeEncryptionRecord(records); - } - } else { - // create password record - if (dea == null) { - dea = new DocumentEncryptionAtom(); - enc = null; - } - encryptInit(); - EncryptionInfo ei = dea.getEncryptionInfo(); - byte salt[] = ei.getVerifier().getSalt(); - if (salt == null) { - enc.confirmPassword(password); - } else { - byte verifier[] = ei.getDecryptor().getVerifier(); - enc.confirmPassword(password, null, null, verifier, salt, null); - } - - // move EncryptionRecord to last slide position - records = normalizeRecords(records); - return addEncryptionRecord(records, dea); - } - } - - /** - * remove duplicated UserEditAtoms and merge PersistPtrHolder. - * Before this method is called, make sure that the offsets are correct, - * i.e. call {@link HSLFSlideShowImpl#updateAndWriteDependantRecords(OutputStream, Map)} - */ - protected static Record[] normalizeRecords(Record records[]) { - // http://msdn.microsoft.com/en-us/library/office/gg615594(v=office.14).aspx - // repeated slideIds can be overwritten, i.e. ignored - - UserEditAtom uea = null; - PersistPtrHolder pph = null; - TreeMap slideLocations = new TreeMap(); - TreeMap recordMap = new TreeMap(); - List obsoleteOffsets = new ArrayList(); - int duplicatedCount = 0; - for (Record r : records) { - assert(r instanceof PositionDependentRecord); - PositionDependentRecord pdr = (PositionDependentRecord)r; - if (pdr instanceof UserEditAtom) { - uea = (UserEditAtom)pdr; - continue; - } - - if (pdr instanceof PersistPtrHolder) { - if (pph != null) { - duplicatedCount++; - } - pph = (PersistPtrHolder)pdr; - for (Map.Entry me : pph.getSlideLocationsLookup().entrySet()) { - Integer oldOffset = slideLocations.put(me.getKey(), me.getValue()); - if (oldOffset != null) { - obsoleteOffsets.add(oldOffset); - } - } - continue; - } - - recordMap.put(pdr.getLastOnDiskOffset(), r); - } - - if (uea == null || pph == null || uea.getPersistPointersOffset() != pph.getLastOnDiskOffset()) { - throw new EncryptedDocumentException("UserEditAtom and PersistPtrHolder must exist and their offset need to match."); - } - - recordMap.put(pph.getLastOnDiskOffset(), pph); - recordMap.put(uea.getLastOnDiskOffset(), uea); - - if (duplicatedCount == 0 && obsoleteOffsets.isEmpty()) { - return records; - } - - uea.setLastUserEditAtomOffset(0); - pph.clear(); - for (Map.Entry me : slideLocations.entrySet()) { - pph.addSlideLookup(me.getKey(), me.getValue()); - } - - for (Integer oldOffset : obsoleteOffsets) { - recordMap.remove(oldOffset); - } - - return recordMap.values().toArray(new Record[recordMap.size()]); - } - - - protected static Record[] removeEncryptionRecord(Record records[]) { - int deaSlideId = -1; - int deaOffset = -1; - PersistPtrHolder ptr = null; - UserEditAtom uea = null; - List recordList = new ArrayList(); - for (Record r : records) { - if (r instanceof DocumentEncryptionAtom) { - deaOffset = ((DocumentEncryptionAtom)r).getLastOnDiskOffset(); - continue; - } else if (r instanceof UserEditAtom) { - uea = (UserEditAtom)r; - deaSlideId = uea.getEncryptSessionPersistIdRef(); - uea.setEncryptSessionPersistIdRef(-1); - } else if (r instanceof PersistPtrHolder) { - ptr = (PersistPtrHolder)r; - } - recordList.add(r); - } - - if (ptr == null || uea == null) { - throw new EncryptedDocumentException("UserEditAtom or PersistPtrholder not found."); - } - if (deaSlideId == -1 && deaOffset == -1) { - return records; - } - - TreeMap tm = new TreeMap(ptr.getSlideLocationsLookup()); - ptr.clear(); - int maxSlideId = -1; - for (Map.Entry me : tm.entrySet()) { - if (me.getKey() == deaSlideId || me.getValue() == deaOffset) { - continue; - } - ptr.addSlideLookup(me.getKey(), me.getValue()); - maxSlideId = Math.max(me.getKey(), maxSlideId); - } - - uea.setMaxPersistWritten(maxSlideId); - - records = recordList.toArray(new Record[recordList.size()]); - - return records; - } - - - protected static Record[] addEncryptionRecord(Record records[], DocumentEncryptionAtom dea) { - assert(dea != null); - int ueaIdx = -1, ptrIdx = -1, deaIdx = -1, idx = -1; - for (Record r : records) { - idx++; - if (r instanceof UserEditAtom) { - ueaIdx = idx; - } else if (r instanceof PersistPtrHolder) { - ptrIdx = idx; - } else if (r instanceof DocumentEncryptionAtom) { - deaIdx = idx; - } - } - assert(ueaIdx != -1 && ptrIdx != -1 && ptrIdx < ueaIdx); - if (deaIdx != -1) { - DocumentEncryptionAtom deaOld = (DocumentEncryptionAtom)records[deaIdx]; - dea.setLastOnDiskOffset(deaOld.getLastOnDiskOffset()); - records[deaIdx] = dea; - return records; - } else { - PersistPtrHolder ptr = (PersistPtrHolder)records[ptrIdx]; - UserEditAtom uea = ((UserEditAtom)records[ueaIdx]); - dea.setLastOnDiskOffset(ptr.getLastOnDiskOffset()-1); - int nextSlideId = uea.getMaxPersistWritten()+1; - ptr.addSlideLookup(nextSlideId, ptr.getLastOnDiskOffset()-1); - uea.setEncryptSessionPersistIdRef(nextSlideId); - uea.setMaxPersistWritten(nextSlideId); - - Record newRecords[] = new Record[records.length+1]; - if (ptrIdx > 0) { - System.arraycopy(records, 0, newRecords, 0, ptrIdx); - } - if (ptrIdx < records.length-1) { - System.arraycopy(records, ptrIdx, newRecords, ptrIdx+1, records.length-ptrIdx); - } - newRecords[ptrIdx] = dea; - return newRecords; - } - } - - @Override - public void close() throws IOException { - if (cyos != null) { - cyos.close(); - } - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSlideShowFactory.java b/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSlideShowFactory.java deleted file mode 100644 index fb216f1af..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSlideShowFactory.java +++ /dev/null @@ -1,42 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.usermodel; - -import java.io.IOException; - -import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; -import org.apache.poi.sl.usermodel.SlideShow; -import org.apache.poi.sl.usermodel.SlideShowFactory; -import org.apache.poi.util.Internal; - -/** - * Helper class which is instantiated by reflection from - * {@link SlideShowFactory#create(java.io.File)} and similar - */ -@Internal -public class HSLFSlideShowFactory extends SlideShowFactory { - /** - * Creates a HSLFSlideShow from the given NPOIFSFileSystem - *

    Note that in order to properly release resources the - * SlideShow should be closed after use. - */ - public static SlideShow createSlideShow(NPOIFSFileSystem fs) throws IOException { - return new HSLFSlideShow(fs); - } - -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSlideShowImpl.java b/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSlideShowImpl.java deleted file mode 100644 index 3f1be1654..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSlideShowImpl.java +++ /dev/null @@ -1,925 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.usermodel; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.Closeable; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.security.GeneralSecurityException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.NavigableMap; -import java.util.TreeMap; - -import org.apache.poi.POIDocument; -import org.apache.poi.hpsf.PropertySet; -import org.apache.poi.hslf.exceptions.CorruptPowerPointFileException; -import org.apache.poi.hslf.exceptions.HSLFException; -import org.apache.poi.hslf.record.CurrentUserAtom; -import org.apache.poi.hslf.record.DocumentEncryptionAtom; -import org.apache.poi.hslf.record.ExOleObjStg; -import org.apache.poi.hslf.record.PersistPtrHolder; -import org.apache.poi.hslf.record.PersistRecord; -import org.apache.poi.hslf.record.PositionDependentRecord; -import org.apache.poi.hslf.record.Record; -import org.apache.poi.hslf.record.RecordTypes; -import org.apache.poi.hslf.record.UserEditAtom; -import org.apache.poi.poifs.crypt.cryptoapi.CryptoAPIEncryptor; -import org.apache.poi.poifs.filesystem.DirectoryNode; -import org.apache.poi.poifs.filesystem.DocumentEntry; -import org.apache.poi.poifs.filesystem.DocumentInputStream; -import org.apache.poi.poifs.filesystem.EntryUtils; -import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.sl.usermodel.PictureData.PictureType; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.LittleEndianConsts; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.util.Removal; - -/** - * This class contains the main functionality for the Powerpoint file - * "reader". It is only a very basic class for now - */ -public final class HSLFSlideShowImpl extends POIDocument implements Closeable { - public static final int UNSET_OFFSET = -1; - - // For logging - private POILogger logger = POILogFactory.getLogger(this.getClass()); - - // Holds metadata on where things are in our document - private CurrentUserAtom currentUser; - - // Low level contents of the file - private byte[] _docstream; - - // Low level contents - private Record[] _records; - - // Raw Pictures contained in the pictures stream - private List _pictures; - - // Embedded objects stored in storage records in the document stream, lazily populated. - private HSLFObjectData[] _objects; - - /** - * Returns the directory in the underlying POIFSFileSystem for the - * document that is open. - * - * @deprecated POI 3.16 beta 1. use {@link POIDocument#getDirectory()} instead - */ - @Deprecated - @Removal(version="3.18") - protected DirectoryNode getPOIFSDirectory() { - return getDirectory(); - } - - /** - * Constructs a Powerpoint document from fileName. Parses the document - * and places all the important stuff into data structures. - * - * @param fileName The name of the file to read. - * @throws IOException if there is a problem while parsing the document. - */ - @SuppressWarnings("resource") - public HSLFSlideShowImpl(String fileName) throws IOException { - this(new POIFSFileSystem(new File(fileName))); - } - - /** - * Constructs a Powerpoint document from an input stream. Parses the - * document and places all the important stuff into data structures. - * - * @param inputStream the source of the data - * @throws IOException if there is a problem while parsing the document. - */ - @SuppressWarnings("resource") - public HSLFSlideShowImpl(InputStream inputStream) throws IOException { - //do Ole stuff - this(new POIFSFileSystem(inputStream)); - } - - /** - * Constructs a Powerpoint document from a POIFS Filesystem. Parses the - * document and places all the important stuff into data structures. - * - * @param filesystem the POIFS FileSystem to read from - * @throws IOException if there is a problem while parsing the document. - */ - public HSLFSlideShowImpl(POIFSFileSystem filesystem) throws IOException { - this(filesystem.getRoot()); - } - - /** - * Constructs a Powerpoint document from a POIFS Filesystem. Parses the - * document and places all the important stuff into data structures. - * - * @param filesystem the POIFS FileSystem to read from - * @throws IOException if there is a problem while parsing the document. - */ - public HSLFSlideShowImpl(NPOIFSFileSystem filesystem) throws IOException { - this(filesystem.getRoot()); - } - - /** - * Constructs a Powerpoint document from a specific point in a - * POIFS Filesystem. Parses the document and places all the - * important stuff into data structures. - * - * @param dir the POIFS directory to read from - * @throws IOException if there is a problem while parsing the document. - */ - public HSLFSlideShowImpl(DirectoryNode dir) throws IOException { - super(handleDualStorage(dir)); - - // First up, grab the "Current User" stream - // We need this before we can detect Encrypted Documents - readCurrentUserStream(); - - // Next up, grab the data that makes up the - // PowerPoint stream - readPowerPointStream(); - - // Now, build records based on the PowerPoint stream - buildRecords(); - - // Look for any other streams - readOtherStreams(); - } - - private static DirectoryNode handleDualStorage(DirectoryNode dir) throws IOException { - // when there's a dual storage entry, use it, as the outer document can't be read quite probably ... - String dualName = "PP97_DUALSTORAGE"; - if (!dir.hasEntry(dualName)) { - return dir; - } - dir = (DirectoryNode) dir.getEntry(dualName); - return dir; - } - - /** - * Constructs a new, empty, Powerpoint document. - */ - public static final HSLFSlideShowImpl create() { - InputStream is = HSLFSlideShowImpl.class.getResourceAsStream("/org/apache/poi/hslf/data/empty.ppt"); - if (is == null) { - throw new HSLFException("Missing resource 'empty.ppt'"); - } - try { - try { - return new HSLFSlideShowImpl(is); - } finally { - is.close(); - } - } catch (IOException e) { - throw new HSLFException(e); - } - } - - /** - * Extracts the main PowerPoint document stream from the - * POI file, ready to be passed - * - * @throws IOException - */ - private void readPowerPointStream() throws IOException { - // Get the main document stream - DocumentEntry docProps = - (DocumentEntry) getDirectory().getEntry("PowerPoint Document"); - - // Grab the document stream - int len = docProps.getSize(); - InputStream is = getDirectory().createDocumentInputStream("PowerPoint Document"); - try { - _docstream = IOUtils.toByteArray(is, len); - } finally { - is.close(); - } - } - - /** - * Builds the list of records, based on the contents - * of the PowerPoint stream - */ - private void buildRecords() throws IOException { - // The format of records in a powerpoint file are: - // - // - // - // If it has a zero length, following it will be another record - // - // If it has a length, depending on its type it may have children or data - // If it has children, these will follow straight away - // > - // If it has data, this will come straigh after, and run for the length - // - // All lengths given exclude the 8 byte record header - // (Data records are known as Atoms) - - // Document should start with: - // 0F 00 E8 03 ## ## ## ## - // (type 1000 = document, info 00 0f is normal, rest is document length) - // 01 00 E9 03 28 00 00 00 - // (type 1001 = document atom, info 00 01 normal, 28 bytes long) - // 80 16 00 00 E0 10 00 00 xx xx xx xx xx xx xx xx - // 05 00 00 00 0A 00 00 00 xx xx xx - // (the contents of the document atom, not sure what it means yet) - // (records then follow) - - // When parsing a document, look to see if you know about that type - // of the current record. If you know it's a type that has children, - // process the record's data area looking for more records - // If you know about the type and it doesn't have children, either do - // something with the data (eg TextRun) or skip over it - // If you don't know about the type, play safe and skip over it (using - // its length to know where the next record will start) - // - - _records = read(_docstream, (int) currentUser.getCurrentEditOffset()); - } - - private Record[] read(byte[] docstream, int usrOffset) throws IOException { - //sort found records by offset. - //(it is not necessary but SlideShow.findMostRecentCoreRecords() expects them sorted) - NavigableMap records = new TreeMap(); // offset -> record - Map persistIds = new HashMap(); // offset -> persistId - initRecordOffsets(docstream, usrOffset, records, persistIds); - HSLFSlideShowEncrypted decryptData = new HSLFSlideShowEncrypted(docstream, records); - - for (Map.Entry entry : records.entrySet()) { - Integer offset = entry.getKey(); - Record record = entry.getValue(); - Integer persistId = persistIds.get(offset); - if (record == null) { - // all plain records have been already added, - // only new records need to be decrypted (tbd #35897) - decryptData.decryptRecord(docstream, persistId, offset); - record = Record.buildRecordAtOffset(docstream, offset); - entry.setValue(record); - } - - if (record instanceof PersistRecord) { - ((PersistRecord) record).setPersistId(persistId); - } - } - - decryptData.close(); - return records.values().toArray(new Record[records.size()]); - } - - private void initRecordOffsets(byte[] docstream, int usrOffset, NavigableMap recordMap, Map offset2id) { - while (usrOffset != 0) { - UserEditAtom usr = (UserEditAtom) Record.buildRecordAtOffset(docstream, usrOffset); - recordMap.put(usrOffset, usr); - - int psrOffset = usr.getPersistPointersOffset(); - PersistPtrHolder ptr = (PersistPtrHolder) Record.buildRecordAtOffset(docstream, psrOffset); - recordMap.put(psrOffset, ptr); - - for (Map.Entry entry : ptr.getSlideLocationsLookup().entrySet()) { - Integer offset = entry.getValue(); - Integer id = entry.getKey(); - recordMap.put(offset, null); // reserve a slot for the record - offset2id.put(offset, id); - } - - usrOffset = usr.getLastUserEditAtomOffset(); - - // check for corrupted user edit atom and try to repair it - // if the next user edit atom offset is already known, we would go into an endless loop - if (usrOffset > 0 && recordMap.containsKey(usrOffset)) { - // a user edit atom is usually located 36 byte before the smallest known record offset - usrOffset = recordMap.firstKey() - 36; - // check that we really are located on a user edit atom - int ver_inst = LittleEndian.getUShort(docstream, usrOffset); - int type = LittleEndian.getUShort(docstream, usrOffset + 2); - int len = LittleEndian.getInt(docstream, usrOffset + 4); - if (ver_inst == 0 && type == 4085 && (len == 0x1C || len == 0x20)) { - logger.log(POILogger.WARN, "Repairing invalid user edit atom"); - usr.setLastUserEditAtomOffset(usrOffset); - } else { - throw new CorruptPowerPointFileException("Powerpoint document contains invalid user edit atom"); - } - } - } - } - - public DocumentEncryptionAtom getDocumentEncryptionAtom() { - for (Record r : _records) { - if (r instanceof DocumentEncryptionAtom) { - return (DocumentEncryptionAtom) r; - } - } - return null; - } - - - /** - * Find the "Current User" stream, and load it - */ - private void readCurrentUserStream() { - try { - currentUser = new CurrentUserAtom(getDirectory()); - } catch (IOException ie) { - logger.log(POILogger.ERROR, "Error finding Current User Atom:\n" + ie); - currentUser = new CurrentUserAtom(); - } - } - - /** - * Find any other streams from the filesystem, and load them - */ - private void readOtherStreams() { - // Currently, there aren't any - } - - /** - * Find and read in pictures contained in this presentation. - * This is lazily called as and when we want to touch pictures. - */ - private void readPictures() throws IOException { - _pictures = new ArrayList(); - - // if the presentation doesn't contain pictures - will use a null set instead - if (!getDirectory().hasEntry("Pictures")) { - return; - } - - DocumentEntry entry = (DocumentEntry) getDirectory().getEntry("Pictures"); - DocumentInputStream is = getDirectory().createDocumentInputStream(entry); - byte[] pictstream = IOUtils.toByteArray(is, entry.getSize()); - is.close(); - - HSLFSlideShowEncrypted decryptData = new HSLFSlideShowEncrypted(getDocumentEncryptionAtom()); - try { - - int pos = 0; - // An empty picture record (length 0) will take up 8 bytes - while (pos <= (pictstream.length - 8)) { - int offset = pos; - - decryptData.decryptPicture(pictstream, offset); - - // Image signature - int signature = LittleEndian.getUShort(pictstream, pos); - pos += LittleEndianConsts.SHORT_SIZE; - // Image type + 0xF018 - int type = LittleEndian.getUShort(pictstream, pos); - pos += LittleEndianConsts.SHORT_SIZE; - // Image size (excluding the 8 byte header) - int imgsize = LittleEndian.getInt(pictstream, pos); - pos += LittleEndianConsts.INT_SIZE; - - // When parsing the BStoreDelay stream, [MS-ODRAW] says that we - // should terminate if the type isn't 0xf007 or 0xf018->0xf117 - if (!((type == 0xf007) || (type >= 0xf018 && type <= 0xf117))) { - break; - } - - // The image size must be 0 or greater - // (0 is allowed, but odd, since we do wind on by the header each - // time, so we won't get stuck) - if (imgsize < 0) { - throw new CorruptPowerPointFileException("The file contains a picture, at position " + _pictures.size() + ", which has a negatively sized data length, so we can't trust any of the picture data"); - } - - // If they type (including the bonus 0xF018) is 0, skip it - PictureType pt = PictureType.forNativeID(type - 0xF018); - if (pt == null) { - logger.log(POILogger.ERROR, "Problem reading picture: Invalid image type 0, on picture with length " + imgsize + ".\nYou document will probably become corrupted if you save it!"); - logger.log(POILogger.ERROR, "" + pos); - } else { - //The pictstream can be truncated halfway through a picture. - //This is not a problem if the pictstream contains extra pictures - //that are not used in any slide -- BUG-60305 - if (pos+imgsize > pictstream.length) { - logger.log(POILogger.WARN, "\"Pictures\" stream may have ended early. In some circumstances, this is not a problem; " + - "in others, this could indicate a corrupt file"); - break; - } - // Build the PictureData object from the data - try { - HSLFPictureData pict = HSLFPictureData.create(pt); - pict.setSignature(signature); - - // Copy the data, ready to pass to PictureData - byte[] imgdata = new byte[imgsize]; - System.arraycopy(pictstream, pos, imgdata, 0, imgdata.length); - pict.setRawData(imgdata); - - pict.setOffset(offset); - pict.setIndex(_pictures.size()); - _pictures.add(pict); - } catch (IllegalArgumentException e) { - logger.log(POILogger.ERROR, "Problem reading picture: " + e + "\nYou document will probably become corrupted if you save it!"); - } - } - - pos += imgsize; - } - } finally { - decryptData.close(); - } - } - - /** - * remove duplicated UserEditAtoms and merge PersistPtrHolder, i.e. - * remove document edit history - */ - public void normalizeRecords() { - try { - updateAndWriteDependantRecords(null, null); - } catch (IOException e) { - throw new CorruptPowerPointFileException(e); - } - _records = HSLFSlideShowEncrypted.normalizeRecords(_records); - } - - - /** - * This is a helper functions, which is needed for adding new position dependent records - * or finally write the slideshow to a file. - * - * @param os the stream to write to, if null only the references are updated - * @param interestingRecords a map of interesting records (PersistPtrHolder and UserEditAtom) - * referenced by their RecordType. Only the very last of each type will be saved to the map. - * May be null, if not needed. - * @throws IOException - */ - public void updateAndWriteDependantRecords(OutputStream os, Map interestingRecords) - throws IOException { - // For position dependent records, hold where they were and now are - // As we go along, update, and hand over, to any Position Dependent - // records we happen across - Map oldToNewPositions = new HashMap(); - - // First pass - figure out where all the position dependent - // records are going to end up, in the new scheme - // (Annoyingly, some powerpoint files have PersistPtrHolders - // that reference slides after the PersistPtrHolder) - UserEditAtom usr = null; - PersistPtrHolder ptr = null; - CountingOS cos = new CountingOS(); - for (Record record : _records) { - // all top level records are position dependent - assert (record instanceof PositionDependentRecord); - PositionDependentRecord pdr = (PositionDependentRecord) record; - int oldPos = pdr.getLastOnDiskOffset(); - int newPos = cos.size(); - pdr.setLastOnDiskOffset(newPos); - if (oldPos != UNSET_OFFSET) { - // new records don't need a mapping, as they aren't in a relation yet - oldToNewPositions.put(oldPos, newPos); - } - - // Grab interesting records as they come past - // this will only save the very last record of each type - RecordTypes saveme = null; - int recordType = (int) record.getRecordType(); - if (recordType == RecordTypes.PersistPtrIncrementalBlock.typeID) { - saveme = RecordTypes.PersistPtrIncrementalBlock; - ptr = (PersistPtrHolder) pdr; - } else if (recordType == RecordTypes.UserEditAtom.typeID) { - saveme = RecordTypes.UserEditAtom; - usr = (UserEditAtom) pdr; - } - if (interestingRecords != null && saveme != null) { - interestingRecords.put(saveme, pdr); - } - - // Dummy write out, so the position winds on properly - record.writeOut(cos); - } - cos.close(); - - if (usr == null || ptr == null) { - throw new HSLFException("UserEditAtom or PersistPtr can't be determined."); - } - - Map persistIds = new HashMap(); - for (Map.Entry entry : ptr.getSlideLocationsLookup().entrySet()) { - persistIds.put(oldToNewPositions.get(entry.getValue()), entry.getKey()); - } - - HSLFSlideShowEncrypted encData = new HSLFSlideShowEncrypted(getDocumentEncryptionAtom()); - - for (Record record : _records) { - assert (record instanceof PositionDependentRecord); - // We've already figured out their new location, and - // told them that - // Tell them of the positions of the other records though - PositionDependentRecord pdr = (PositionDependentRecord) record; - Integer persistId = persistIds.get(pdr.getLastOnDiskOffset()); - if (persistId == null) { - persistId = 0; - } - - // For now, we're only handling PositionDependentRecord's that - // happen at the top level. - // In future, we'll need the handle them everywhere, but that's - // a bit trickier - pdr.updateOtherRecordReferences(oldToNewPositions); - - // Whatever happens, write out that record tree - if (os != null) { - record.writeOut(encData.encryptRecord(os, persistId, record)); - } - } - - encData.close(); - - // Update and write out the Current User atom - int oldLastUserEditAtomPos = (int) currentUser.getCurrentEditOffset(); - Integer newLastUserEditAtomPos = oldToNewPositions.get(oldLastUserEditAtomPos); - if (newLastUserEditAtomPos == null || usr.getLastOnDiskOffset() != newLastUserEditAtomPos) { - throw new HSLFException("Couldn't find the new location of the last UserEditAtom that used to be at " + oldLastUserEditAtomPos); - } - currentUser.setCurrentEditOffset(usr.getLastOnDiskOffset()); - } - - /** - * Writes out the slideshow to the currently open file. - *

    - *

    This will fail (with an {@link IllegalStateException} if the - * slideshow was opened read-only, opened from an {@link InputStream} - * instead of a File, or if this is not the root document. For those cases, - * you must use {@link #write(OutputStream)} or {@link #write(File)} to - * write to a brand new document. - * - * @throws IOException thrown on errors writing to the file - * @throws IllegalStateException if this isn't from a writable File - * @since POI 3.15 beta 3 - */ - @Override - public void write() throws IOException { - validateInPlaceWritePossible(); - - // Write the PowerPoint streams to the current FileSystem - // No need to do anything to other streams, already there! - write(getDirectory().getFileSystem(), false); - - // Sync with the File on disk - getDirectory().getFileSystem().writeFilesystem(); - } - - /** - * Writes out the slideshow file the is represented by an instance - * of this class. - *

    This will write out only the common OLE2 streams. If you require all - * streams to be written out, use {@link #write(File, boolean)} - * with preserveNodes set to true. - * - * @param newFile The File to write to. - * @throws IOException If there is an unexpected IOException from writing to the File - */ - @Override - public void write(File newFile) throws IOException { - // Write out, but only the common streams - write(newFile, false); - } - - /** - * Writes out the slideshow file the is represented by an instance - * of this class. - * If you require all streams to be written out (eg Marcos, embeded - * documents), then set preserveNodes set to true - * - * @param newFile The File to write to. - * @param preserveNodes Should all OLE2 streams be written back out, or only the common ones? - * @throws IOException If there is an unexpected IOException from writing to the File - */ - public void write(File newFile, boolean preserveNodes) throws IOException { - // Get a new FileSystem to write into - POIFSFileSystem outFS = POIFSFileSystem.create(newFile); - - try { - // Write into the new FileSystem - write(outFS, preserveNodes); - - // Send the POIFSFileSystem object out to the underlying stream - outFS.writeFilesystem(); - } finally { - outFS.close(); - } - } - - /** - * Writes out the slideshow file the is represented by an instance - * of this class. - *

    This will write out only the common OLE2 streams. If you require all - * streams to be written out, use {@link #write(OutputStream, boolean)} - * with preserveNodes set to true. - * - * @param out The OutputStream to write to. - * @throws IOException If there is an unexpected IOException from - * the passed in OutputStream - */ - @Override - public void write(OutputStream out) throws IOException { - // Write out, but only the common streams - write(out, false); - } - - /** - * Writes out the slideshow file the is represented by an instance - * of this class. - * If you require all streams to be written out (eg Marcos, embeded - * documents), then set preserveNodes set to true - * - * @param out The OutputStream to write to. - * @param preserveNodes Should all OLE2 streams be written back out, or only the common ones? - * @throws IOException If there is an unexpected IOException from - * the passed in OutputStream - */ - public void write(OutputStream out, boolean preserveNodes) throws IOException { - // Get a new FileSystem to write into - POIFSFileSystem outFS = new POIFSFileSystem(); - - try { - // Write into the new FileSystem - write(outFS, preserveNodes); - - // Send the POIFSFileSystem object out to the underlying stream - outFS.writeFilesystem(out); - } finally { - outFS.close(); - } - } - - private void write(NPOIFSFileSystem outFS, boolean copyAllOtherNodes) throws IOException { - // read properties and pictures, with old encryption settings where appropriate - if (_pictures == null) { - readPictures(); - } - getDocumentSummaryInformation(); - - // set new encryption settings - HSLFSlideShowEncrypted encryptedSS = new HSLFSlideShowEncrypted(getDocumentEncryptionAtom()); - _records = encryptedSS.updateEncryptionRecord(_records); - - // The list of entries we've written out - List writtenEntries = new ArrayList(1); - - // Write out the Property Streams - writeProperties(outFS, writtenEntries); - - BufAccessBAOS baos = new BufAccessBAOS(); - - // For position dependent records, hold where they were and now are - // As we go along, update, and hand over, to any Position Dependent - // records we happen across - updateAndWriteDependantRecords(baos, null); - - // Update our cached copy of the bytes that make up the PPT stream - _docstream = new byte[baos.size()]; - System.arraycopy(baos.getBuf(), 0, _docstream, 0, baos.size()); - baos.close(); - - // Write the PPT stream into the POIFS layer - ByteArrayInputStream bais = new ByteArrayInputStream(_docstream); - outFS.createOrUpdateDocument(bais, "PowerPoint Document"); - writtenEntries.add("PowerPoint Document"); - - currentUser.setEncrypted(encryptedSS.getDocumentEncryptionAtom() != null); - currentUser.writeToFS(outFS); - writtenEntries.add("Current User"); - - - if (_pictures.size() > 0) { - BufAccessBAOS pict = new BufAccessBAOS(); - for (HSLFPictureData p : _pictures) { - int offset = pict.size(); - p.write(pict); - encryptedSS.encryptPicture(pict.getBuf(), offset); - } - outFS.createOrUpdateDocument( - new ByteArrayInputStream(pict.getBuf(), 0, pict.size()), "Pictures" - ); - writtenEntries.add("Pictures"); - pict.close(); - } - - encryptedSS.close(); - - // If requested, copy over any other streams we spot, eg Macros - if (copyAllOtherNodes) { - EntryUtils.copyNodes(getDirectory().getFileSystem(), outFS, writtenEntries); - } - } - - /** - * For a given named property entry, either return it or null if - * if it wasn't found - * - * @param setName The property to read - * @return The value of the given property or null if it wasn't found. - */ - @Override - protected PropertySet getPropertySet(String setName) { - DocumentEncryptionAtom dea = getDocumentEncryptionAtom(); - return (dea == null) - ? super.getPropertySet(setName) - : super.getPropertySet(setName, dea.getEncryptionInfo()); - } - - /** - * Writes out the standard Documment Information Properties (HPSF) - * - * @param outFS the POIFSFileSystem to write the properties into - * @param writtenEntries a list of POIFS entries to add the property names too - * @throws IOException if an error when writing to the - * {@link POIFSFileSystem} occurs - */ - @Override - protected void writeProperties(NPOIFSFileSystem outFS, List writtenEntries) throws IOException { - super.writeProperties(outFS, writtenEntries); - DocumentEncryptionAtom dea = getDocumentEncryptionAtom(); - if (dea != null) { - CryptoAPIEncryptor enc = (CryptoAPIEncryptor) dea.getEncryptionInfo().getEncryptor(); - try { - enc.getSummaryEntries(outFS.getRoot()); // ignore OutputStream - } catch (IOException e) { - throw e; - } catch (GeneralSecurityException e) { - throw new IOException(e); - } - } - } - - /* ******************* adding methods follow ********************* */ - - /** - * Adds a new root level record, at the end, but before the last - * PersistPtrIncrementalBlock. - */ - public synchronized int appendRootLevelRecord(Record newRecord) { - int addedAt = -1; - Record[] r = new Record[_records.length + 1]; - boolean added = false; - for (int i = (_records.length - 1); i >= 0; i--) { - if (added) { - // Just copy over - r[i] = _records[i]; - } else { - r[(i + 1)] = _records[i]; - if (_records[i] instanceof PersistPtrHolder) { - r[i] = newRecord; - added = true; - addedAt = i; - } - } - } - _records = r; - return addedAt; - } - - /** - * Add a new picture to this presentation. - * - * @return offset of this picture in the Pictures stream - */ - public int addPicture(HSLFPictureData img) { - // Process any existing pictures if we haven't yet - if (_pictures == null) { - try { - readPictures(); - } catch (IOException e) { - throw new CorruptPowerPointFileException(e.getMessage()); - } - } - - // Add the new picture in - int offset = 0; - if (_pictures.size() > 0) { - HSLFPictureData prev = _pictures.get(_pictures.size() - 1); - offset = prev.getOffset() + prev.getRawData().length + 8; - } - img.setOffset(offset); - img.setIndex(_pictures.size() + 1); - _pictures.add(img); - return offset; - } - - /* ******************* fetching methods follow ********************* */ - - - /** - * Returns an array of all the records found in the slideshow - */ - public Record[] getRecords() { - return _records; - } - - /** - * Returns an array of the bytes of the file. Only correct after a - * call to open or write - at all other times might be wrong! - */ - public byte[] getUnderlyingBytes() { - return _docstream; - } - - /** - * Fetch the Current User Atom of the document - */ - public CurrentUserAtom getCurrentUserAtom() { - return currentUser; - } - - /** - * Return list of pictures contained in this presentation - * - * @return list with the read pictures or an empty list if the - * presentation doesn't contain pictures. - */ - public List getPictureData() { - if (_pictures == null) { - try { - readPictures(); - } catch (IOException e) { - throw new CorruptPowerPointFileException(e.getMessage()); - } - } - - return Collections.unmodifiableList(_pictures); - } - - /** - * Gets embedded object data from the slide show. - * - * @return the embedded objects. - */ - public HSLFObjectData[] getEmbeddedObjects() { - if (_objects == null) { - List objects = new ArrayList(); - for (Record r : _records) { - if (r instanceof ExOleObjStg) { - objects.add(new HSLFObjectData((ExOleObjStg) r)); - } - } - _objects = objects.toArray(new HSLFObjectData[objects.size()]); - } - return _objects; - } - - @Override - public void close() throws IOException { - NPOIFSFileSystem fs = getDirectory().getFileSystem(); - if (fs != null) { - fs.close(); - } - } - - - private static class BufAccessBAOS extends ByteArrayOutputStream { - public byte[] getBuf() { - return buf; - } - } - - private static class CountingOS extends OutputStream { - int count = 0; - - @Override - public void write(int b) throws IOException { - count++; - } - - @Override - public void write(byte[] b) throws IOException { - count += b.length; - } - - @Override - public void write(byte[] b, int off, int len) throws IOException { - count += len; - } - - public int size() { - return count; - } - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSoundData.java b/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSoundData.java deleted file mode 100644 index 7750b25f1..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFSoundData.java +++ /dev/null @@ -1,94 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.usermodel; - -import org.apache.poi.hslf.record.*; - -import java.util.ArrayList; - -/** - * A class that represents sound data embedded in a slide show. - * - * @author Yegor Kozlov - */ -public final class HSLFSoundData { - /** - * The record that contains the object data. - */ - private Sound _container; - - /** - * Creates the object data wrapping the record that contains the sound data. - * - * @param container the record that contains the sound data. - */ - public HSLFSoundData(Sound container) { - this._container = container; - } - - /** - * Name of the sound (e.g. "crash") - * - * @return name of the sound - */ - public String getSoundName(){ - return _container.getSoundName(); - } - - /** - * Type of the sound (e.g. ".wav") - * - * @return type of the sound - */ - public String getSoundType(){ - return _container.getSoundType(); - } - - /** - * Gets an input stream which returns the binary of the sound data. - * - * @return the input stream which will contain the binary of the sound data. - */ - public byte[] getData() { - return _container.getSoundData(); - } - - /** - * Find all sound records in the supplied Document records - * - * @param document the document to find in - * @return the array with the sound data - */ - public static HSLFSoundData[] find(Document document){ - ArrayList lst = new ArrayList(); - Record[] ch = document.getChildRecords(); - for (int i = 0; i < ch.length; i++) { - if(ch[i].getRecordType() == RecordTypes.SoundCollection.typeID){ - RecordContainer col = (RecordContainer)ch[i]; - Record[] sr = col.getChildRecords(); - for (int j = 0; j < sr.length; j++) { - if(sr[j] instanceof Sound){ - lst.add(new HSLFSoundData((Sound)sr[j])); - } - } - } - - } - return lst.toArray(new HSLFSoundData[lst.size()]); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFTable.java b/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFTable.java deleted file mode 100644 index f90873908..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFTable.java +++ /dev/null @@ -1,468 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.usermodel; - -import java.awt.geom.Rectangle2D; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.SortedSet; -import java.util.TreeSet; - -import org.apache.poi.ddf.AbstractEscherOptRecord; -import org.apache.poi.ddf.EscherArrayProperty; -import org.apache.poi.ddf.EscherContainerRecord; -import org.apache.poi.ddf.EscherOptRecord; -import org.apache.poi.ddf.EscherProperties; -import org.apache.poi.ddf.EscherSimpleProperty; -import org.apache.poi.hslf.record.RecordTypes; -import org.apache.poi.sl.usermodel.ShapeContainer; -import org.apache.poi.sl.usermodel.TableShape; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.Units; - -/** - * Represents a table in a PowerPoint presentation - * - * @author Yegor Kozlov - */ -public final class HSLFTable extends HSLFGroupShape -implements HSLFShapeContainer, TableShape { - - protected static final int BORDERS_ALL = 5; - protected static final int BORDERS_OUTSIDE = 6; - protected static final int BORDERS_INSIDE = 7; - protected static final int BORDERS_NONE = 8; - - - protected HSLFTableCell[][] cells; - private int columnCount = -1; - - /** - * Create a new Table of the given number of rows and columns - * - * @param numRows the number of rows - * @param numCols the number of columns - */ - protected HSLFTable(int numRows, int numCols) { - this(numRows, numCols, null); - } - - /** - * Create a new Table of the given number of rows and columns - * - * @param numRows the number of rows - * @param numCols the number of columns - * @param parent the parent shape, or null if table is added to sheet - */ - protected HSLFTable(int numRows, int numCols, ShapeContainer parent) { - super(parent); - - if(numRows < 1) { - throw new IllegalArgumentException("The number of rows must be greater than 1"); - } - if(numCols < 1) { - throw new IllegalArgumentException("The number of columns must be greater than 1"); - } - - double x=0, y=0, tblWidth=0, tblHeight=0; - cells = new HSLFTableCell[numRows][numCols]; - for (int i = 0; i < cells.length; i++) { - x = 0; - for (int j = 0; j < cells[i].length; j++) { - cells[i][j] = new HSLFTableCell(this); - Rectangle2D anchor = new Rectangle2D.Double(x, y, HSLFTableCell.DEFAULT_WIDTH, HSLFTableCell.DEFAULT_HEIGHT); - cells[i][j].setAnchor(anchor); - x += HSLFTableCell.DEFAULT_WIDTH; - } - y += HSLFTableCell.DEFAULT_HEIGHT; - } - tblWidth = x; - tblHeight = y; - setExteriorAnchor(new Rectangle2D.Double(0, 0, tblWidth, tblHeight)); - - EscherContainerRecord spCont = (EscherContainerRecord) getSpContainer().getChild(0); - AbstractEscherOptRecord opt = new EscherOptRecord(); - opt.setRecordId(RecordTypes.EscherUserDefined.typeID); - opt.addEscherProperty(new EscherSimpleProperty(EscherProperties.GROUPSHAPE__TABLEPROPERTIES, 1)); - EscherArrayProperty p = new EscherArrayProperty((short)(0x4000 | EscherProperties.GROUPSHAPE__TABLEROWPROPERTIES), false, null); - p.setSizeOfElements(0x0004); - p.setNumberOfElementsInArray(numRows); - p.setNumberOfElementsInMemory(numRows); - opt.addEscherProperty(p); - spCont.addChildBefore(opt, RecordTypes.EscherClientAnchor.typeID); - } - - /** - * Create a Table object and initialize it from the supplied Record container. - * - * @param escherRecord EscherSpContainer container which holds information about this shape - * @param parent the parent of the shape - */ - protected HSLFTable(EscherContainerRecord escherRecord, ShapeContainer parent) { - super(escherRecord, parent); - } - - @Override - public HSLFTableCell getCell(int row, int col) { - if (row < 0 || cells.length <= row) { - return null; - } - HSLFTableCell[] r = cells[row]; - if (r == null || col < 0 || r.length <= col) { - // empty row - return null; - } - // cell can be potentially empty ... - return r[col]; - } - - @Override - public int getNumberOfColumns() { - if (columnCount == -1) { - // check all rows in case of merged rows - for (HSLFTableCell[] hc : cells) { - if (hc != null) { - columnCount = Math.max(columnCount, hc.length); - } - } - } - return columnCount; - } - - @Override - public int getNumberOfRows() { - return cells.length; - } - - @Override - protected void afterInsert(HSLFSheet sh){ - super.afterInsert(sh); - - Set lineSet = new HashSet(); - for (HSLFTableCell row[] : cells) { - for (HSLFTableCell c : row) { - addShape(c); - for (HSLFLine bt : new HSLFLine[]{ c.borderTop, c.borderRight, c.borderBottom, c.borderLeft }) { - if (bt != null) { - lineSet.add(bt); - } - } - } - } - - for (HSLFLine l : lineSet) { - addShape(l); - } - - updateRowHeightsProperty(); - } - - private void cellListToArray() { - List htc = new ArrayList(); - for (HSLFShape h : getShapes()) { - if (h instanceof HSLFTableCell) { - htc.add((HSLFTableCell)h); - } - } - - if (htc.isEmpty()) { - throw new IllegalStateException("HSLFTable without HSLFTableCells"); - } - - SortedSet colSet = new TreeSet(); - SortedSet rowSet = new TreeSet(); - - // #1 pass - determine cols and rows - for (HSLFTableCell sh : htc) { - Rectangle2D anchor = sh.getAnchor(); - colSet.add(anchor.getX()); - rowSet.add(anchor.getY()); - } - cells = new HSLFTableCell[rowSet.size()][colSet.size()]; - - List colLst = new ArrayList(colSet); - List rowLst = new ArrayList(rowSet); - - // #2 pass - assign shape to table cells - for (HSLFTableCell sh : htc) { - Rectangle2D anchor = sh.getAnchor(); - int row = rowLst.indexOf(anchor.getY()); - int col = colLst.indexOf(anchor.getX()); - assert(row != -1 && col != -1); - cells[row][col] = sh; - - // determine gridSpan / rowSpan - int gridSpan = calcSpan(colLst, anchor.getWidth(), col); - int rowSpan = calcSpan(rowLst, anchor.getHeight(), row); - - sh.setGridSpan(gridSpan); - sh.setRowSpan(rowSpan); - } - } - - private int calcSpan(List spaces, double totalSpace, int idx) { - if (idx == spaces.size()-1) { - return 1; - } - int span = 0; - double remainingSpace = totalSpace; - while (idx+1 < spaces.size() && remainingSpace > 0) { - remainingSpace -= spaces.get(idx+1)-spaces.get(idx); - span++; - idx++; - } - return span; - } - - static class LineRect { - final HSLFLine l; - final double lx1, lx2, ly1, ly2; - LineRect(HSLFLine l) { - this.l = l; - Rectangle2D r = l.getAnchor(); - lx1 = r.getMinX(); - lx2 = r.getMaxX(); - ly1 = r.getMinY(); - ly2 = r.getMaxY(); - } - int leftFit(double x1, double x2, double y1, double y2) { - return (int)(Math.abs(x1-lx1)+Math.abs(y1-ly1)+Math.abs(x1-lx2)+Math.abs(y2-ly2)); - } - int topFit(double x1, double x2, double y1, double y2) { - return (int)(Math.abs(x1-lx1)+Math.abs(y1-ly1)+Math.abs(x2-lx2)+Math.abs(y1-ly2)); - } - int rightFit(double x1, double x2, double y1, double y2) { - return (int)(Math.abs(x2-lx1)+Math.abs(y1-ly1)+Math.abs(x2-lx2)+Math.abs(y2-ly2)); - } - int bottomFit(double x1, double x2, double y1, double y2) { - return (int)(Math.abs(x1-lx1)+Math.abs(y2-ly1)+Math.abs(x2-lx2)+Math.abs(y2-ly2)); - } - } - - private void fitLinesToCells() { - List lines = new ArrayList(); - for (HSLFShape h : getShapes()) { - if (h instanceof HSLFLine) { - lines.add(new LineRect((HSLFLine)h)); - } - } - - final int threshold = 5; - - // TODO: this only works for non-rotated tables - for (HSLFTableCell[] tca : cells) { - for (HSLFTableCell tc : tca) { - if (tc == null) { - continue; - } - final Rectangle2D cellAnchor = tc.getAnchor(); - - /** - * x1/y1 --------+ - * | | - * +---------x2/y2 - */ - final double x1 = cellAnchor.getMinX(); - final double x2 = cellAnchor.getMaxX(); - final double y1 = cellAnchor.getMinY(); - final double y2 = cellAnchor.getMaxY(); - - LineRect lline = null, tline = null, rline = null, bline = null; - int lfit = Integer.MAX_VALUE, tfit = Integer.MAX_VALUE, rfit = Integer.MAX_VALUE, bfit = Integer.MAX_VALUE; - - for (LineRect lr : lines) { - // calculate border fit - int lfitx = lr.leftFit(x1, x2, y1, y2); - if (lfitx < lfit) { - lfit = lfitx; - lline = lr; - } - - int tfitx = lr.topFit(x1, x2, y1, y2); - if (tfitx < tfit) { - tfit = tfitx; - tline = lr; - } - - int rfitx = lr.rightFit(x1, x2, y1, y2); - if (rfitx < rfit) { - rfit = rfitx; - rline = lr; - } - - int bfitx = lr.bottomFit(x1, x2, y1, y2); - if (bfitx < bfit) { - bfit = bfitx; - bline = lr; - } - } - - if (lfit < threshold && lline != null) { - tc.borderLeft = lline.l; - } - if (tfit < threshold && tline != null) { - tc.borderTop = tline.l; - } - if (rfit < threshold && rline != null) { - tc.borderRight = rline.l; - } - if (bfit < threshold && bline != null) { - tc.borderBottom = bline.l; - } - } - } - } - - protected void initTable(){ - cellListToArray(); - fitLinesToCells(); - } - - /** - * Assign the SlideShow this shape belongs to - * - * @param sheet owner of this shape - */ - @Override - public void setSheet(HSLFSheet sheet){ - super.setSheet(sheet); - if (cells == null) { - initTable(); - } else { - for (HSLFTableCell cols[] : cells) { - for (HSLFTableCell col : cols) { - col.setSheet(sheet); - } - } - } - } - - @Override - public double getRowHeight(int row) { - if (row < 0 || row >= cells.length) { - throw new IllegalArgumentException("Row index '"+row+"' is not within range [0-"+(cells.length-1)+"]"); - } - - return cells[row][0].getAnchor().getHeight(); - } - - @Override - public void setRowHeight(int row, double height) { - if (row < 0 || row >= cells.length) { - throw new IllegalArgumentException("Row index '"+row+"' is not within range [0-"+(cells.length-1)+"]"); - } - - int pxHeight = Units.pointsToPixel(height); - double currentHeight = cells[row][0].getAnchor().getHeight(); - double dy = pxHeight - currentHeight; - - for (int i = row; i < cells.length; i++) { - for (int j = 0; j < cells[i].length; j++) { - Rectangle2D anchor = cells[i][j].getAnchor(); - if(i == row) { - anchor.setRect(anchor.getX(), anchor.getY(), anchor.getWidth(), pxHeight); - } else { - anchor.setRect(anchor.getX(), anchor.getY()+dy, anchor.getWidth(), pxHeight); - } - cells[i][j].setAnchor(anchor); - } - } - Rectangle2D tblanchor = getAnchor(); - tblanchor.setRect(tblanchor.getX(), tblanchor.getY(), tblanchor.getWidth(), tblanchor.getHeight() + dy); - setExteriorAnchor(tblanchor); - - } - - @Override - public double getColumnWidth(int col) { - if (col < 0 || col >= cells[0].length) { - throw new IllegalArgumentException("Column index '"+col+"' is not within range [0-"+(cells[0].length-1)+"]"); - } - - // TODO: check for merged cols - double width = cells[0][col].getAnchor().getWidth(); - return width; - } - - @Override - public void setColumnWidth(int col, final double width){ - if (col < 0 || col >= cells[0].length) { - throw new IllegalArgumentException("Column index '"+col+"' is not within range [0-"+(cells[0].length-1)+"]"); - } - double currentWidth = cells[0][col].getAnchor().getWidth(); - double dx = width - currentWidth; - for (HSLFTableCell cols[] : cells) { - Rectangle2D anchor = cols[col].getAnchor(); - anchor.setRect(anchor.getX(), anchor.getY(), width, anchor.getHeight()); - cols[col].setAnchor(anchor); - - if (col < cols.length - 1) { - for (int j = col+1; j < cols.length; j++) { - anchor = cols[j].getAnchor(); - anchor.setRect(anchor.getX()+dx, anchor.getY(), anchor.getWidth(), anchor.getHeight()); - cols[j].setAnchor(anchor); - } - } - } - Rectangle2D tblanchor = getAnchor(); - tblanchor.setRect(tblanchor.getX(), tblanchor.getY(), tblanchor.getWidth() + dx, tblanchor.getHeight()); - setExteriorAnchor(tblanchor); - } - - protected HSLFTableCell getRelativeCell(HSLFTableCell origin, int row, int col) { - int thisRow = 0, thisCol = 0; - boolean found = false; - outer: for (HSLFTableCell[] tca : cells) { - thisCol = 0; - for (HSLFTableCell tc : tca) { - if (tc == origin) { - found = true; - break outer; - } - thisCol++; - } - thisRow++; - } - - int otherRow = thisRow + row; - int otherCol = thisCol + col; - return (found - && 0 <= otherRow && otherRow < cells.length - && 0 <= otherCol && otherCol < cells[otherRow].length) - ? cells[otherRow][otherCol] : null; - } - - @Override - protected void moveAndScale(Rectangle2D anchorDest){ - super.moveAndScale(anchorDest); - updateRowHeightsProperty(); - } - - private void updateRowHeightsProperty() { - AbstractEscherOptRecord opt = getEscherOptRecord(); - EscherArrayProperty p = opt.lookup(EscherProperties.GROUPSHAPE__TABLEROWPROPERTIES); - byte[] val = new byte[4]; - for (int rowIdx = 0; rowIdx < cells.length; rowIdx++) { - int rowHeight = Units.pointsToMaster(cells[rowIdx][0].getAnchor().getHeight()); - LittleEndian.putInt(val, 0, rowHeight); - p.setElement(rowIdx, val); - } - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFTableCell.java b/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFTableCell.java deleted file mode 100644 index 8477cadde..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFTableCell.java +++ /dev/null @@ -1,454 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.usermodel; - -import java.awt.Color; -import java.awt.geom.Rectangle2D; - -import org.apache.poi.ddf.AbstractEscherOptRecord; -import org.apache.poi.ddf.EscherContainerRecord; -import org.apache.poi.ddf.EscherProperties; -import org.apache.poi.sl.draw.DrawPaint; -import org.apache.poi.sl.usermodel.PaintStyle; -import org.apache.poi.sl.usermodel.ShapeType; -import org.apache.poi.sl.usermodel.StrokeStyle; -import org.apache.poi.sl.usermodel.StrokeStyle.LineCompound; -import org.apache.poi.sl.usermodel.StrokeStyle.LineDash; -import org.apache.poi.sl.usermodel.TableCell; - -/** - * Represents a cell in a ppt table - */ -public final class HSLFTableCell extends HSLFTextBox implements TableCell { - protected static final int DEFAULT_WIDTH = 100; - protected static final int DEFAULT_HEIGHT = 40; - - /* package */ HSLFLine borderLeft; - /* package */ HSLFLine borderRight; - /* package */ HSLFLine borderTop; - /* package */ HSLFLine borderBottom; - - /** - * The number of columns to be spanned/merged - */ - private int gridSpan = 1; - - /** - * The number of columns to be spanned/merged - */ - private int rowSpan = 1; - - /** - * Create a TableCell object and initialize it from the supplied Record container. - * - * @param escherRecord EscherSpContainer which holds information about this shape - * @param parent the parent of the shape - */ - protected HSLFTableCell(EscherContainerRecord escherRecord, HSLFTable parent){ - super(escherRecord, parent); - } - - /** - * Create a new TableCell. This constructor is used when a new shape is created. - * - * @param parent the parent of this Shape. For example, if this text box is a cell - * in a table then the parent is Table. - */ - public HSLFTableCell(HSLFTable parent){ - super(parent); - - setShapeType(ShapeType.RECT); - //_txtrun.setRunType(TextHeaderAtom.HALF_BODY_TYPE); - //_txtrun.getRichTextRuns()[0].setFlag(false, 0, false); - } - - @Override - protected EscherContainerRecord createSpContainer(boolean isChild){ - EscherContainerRecord ecr = super.createSpContainer(isChild); - AbstractEscherOptRecord opt = getEscherOptRecord(); - setEscherProperty(opt, EscherProperties.TEXT__TEXTID, 0); - setEscherProperty(opt, EscherProperties.TEXT__SIZE_TEXT_TO_FIT_SHAPE, 0x20000); - setEscherProperty(opt, EscherProperties.FILL__NOFILLHITTEST, 0x150001); - setEscherProperty(opt, EscherProperties.SHADOWSTYLE__SHADOWOBSURED, 0x20000); - setEscherProperty(opt, EscherProperties.PROTECTION__LOCKAGAINSTGROUPING, 0x40000); - - return ecr; - } - - private void anchorBorder(BorderEdge edge, final HSLFLine line) { - if (line == null) { - return; - } - Rectangle2D cellAnchor = getAnchor(); - double x,y,w,h; - switch(edge){ - case top: - x = cellAnchor.getX(); - y = cellAnchor.getY(); - w = cellAnchor.getWidth(); - h = 0; - break; - case right: - x = cellAnchor.getX() + cellAnchor.getWidth(); - y = cellAnchor.getY(); - w = 0; - h = cellAnchor.getHeight(); - break; - case bottom: - x = cellAnchor.getX(); - y = cellAnchor.getY() + cellAnchor.getHeight(); - w = cellAnchor.getWidth(); - h = 0; - break; - case left: - x = cellAnchor.getX(); - y = cellAnchor.getY(); - w = 0; - h = cellAnchor.getHeight(); - break; - default: - throw new IllegalArgumentException(); - } - line.setAnchor(new Rectangle2D.Double(x,y,w,h)); - } - - @Override - public void setAnchor(Rectangle2D anchor){ - super.setAnchor(anchor); - - anchorBorder(BorderEdge.top, borderTop); - anchorBorder(BorderEdge.right, borderRight); - anchorBorder(BorderEdge.bottom, borderBottom); - anchorBorder(BorderEdge.left, borderLeft); - } - - @Override - public StrokeStyle getBorderStyle(final BorderEdge edge) { - final Double width = getBorderWidth(edge); - return (width == null) ? null : new StrokeStyle() { - @Override - public PaintStyle getPaint() { - return DrawPaint.createSolidPaint(getBorderColor(edge)); - } - - @Override - public LineCap getLineCap() { - return null; - } - - @Override - public LineDash getLineDash() { - return getBorderDash(edge); - } - - @Override - public LineCompound getLineCompound() { - return getBorderCompound(edge); - } - - @Override - public double getLineWidth() { - return width; - } - }; - } - - @Override - public void setBorderStyle(BorderEdge edge, StrokeStyle style) { - if (style == null) { - throw new IllegalArgumentException("StrokeStyle needs to be specified."); - } - - // setting the line cap is not implemented, as the border lines aren't connected - - LineCompound compound = style.getLineCompound(); - if (compound != null) { - setBorderCompound(edge, compound); - } - - LineDash dash = style.getLineDash(); - if (dash != null) { - setBorderDash(edge, dash); - } - - double width = style.getLineWidth(); - setBorderWidth(edge, width); - } - - - public Double getBorderWidth(BorderEdge edge) { - HSLFLine l; - switch (edge) { - case bottom: l = borderBottom; break; - case top: l = borderTop; break; - case right: l = borderRight; break; - case left: l = borderLeft; break; - default: throw new IllegalArgumentException(); - } - return (l == null) ? null : l.getLineWidth(); - } - - @Override - public void setBorderWidth(BorderEdge edge, double width) { - HSLFLine l = addLine(edge); - l.setLineWidth(width); - } - - public Color getBorderColor(BorderEdge edge) { - HSLFLine l; - switch (edge) { - case bottom: l = borderBottom; break; - case top: l = borderTop; break; - case right: l = borderRight; break; - case left: l = borderLeft; break; - default: throw new IllegalArgumentException(); - } - return (l == null) ? null : l.getLineColor(); - } - - @Override - public void setBorderColor(BorderEdge edge, Color color) { - if (edge == null || color == null) { - throw new IllegalArgumentException("BorderEdge and/or Color need to be specified."); - } - - HSLFLine l = addLine(edge); - l.setLineColor(color); - } - - public LineDash getBorderDash(BorderEdge edge) { - HSLFLine l; - switch (edge) { - case bottom: l = borderBottom; break; - case top: l = borderTop; break; - case right: l = borderRight; break; - case left: l = borderLeft; break; - default: throw new IllegalArgumentException(); - } - return (l == null) ? null : l.getLineDash(); - } - - @Override - public void setBorderDash(BorderEdge edge, LineDash dash) { - if (edge == null || dash == null) { - throw new IllegalArgumentException("BorderEdge and/or LineDash need to be specified."); - } - - HSLFLine l = addLine(edge); - l.setLineDash(dash); - } - - public LineCompound getBorderCompound(BorderEdge edge) { - HSLFLine l; - switch (edge) { - case bottom: l = borderBottom; break; - case top: l = borderTop; break; - case right: l = borderRight; break; - case left: l = borderLeft; break; - default: throw new IllegalArgumentException(); - } - return (l == null) ? null : l.getLineCompound(); - } - - @Override - public void setBorderCompound(BorderEdge edge, LineCompound compound) { - if (edge == null || compound == null) { - throw new IllegalArgumentException("BorderEdge and/or LineCompound need to be specified."); - } - - HSLFLine l = addLine(edge); - l.setLineCompound(compound); - } - - - protected HSLFLine addLine(BorderEdge edge) { - switch (edge) { - case bottom: { - if (borderBottom == null) { - borderBottom = createBorder(edge); - HSLFTableCell c = getSiblingCell(1,0); - if (c != null) { - assert(c.borderTop == null); - c.borderTop = borderBottom; - } - } - return borderBottom; - } - case top: { - if (borderTop == null) { - borderTop = createBorder(edge); - HSLFTableCell c = getSiblingCell(-1,0); - if (c != null) { - assert(c.borderBottom == null); - c.borderBottom = borderTop; - } - } - return borderTop; - } - case right: { - if (borderRight == null) { - borderRight = createBorder(edge); - HSLFTableCell c = getSiblingCell(0,1); - if (c != null) { - assert(c.borderLeft == null); - c.borderLeft = borderRight; - } - } - return borderRight; - } - case left: { - if (borderLeft == null) { - borderLeft = createBorder(edge); - HSLFTableCell c = getSiblingCell(0,-1); - if (c != null) { - assert(c.borderRight == null); - c.borderRight = borderLeft; - } - } - return borderLeft; - } - default: - throw new IllegalArgumentException(); - } - } - - @Override - public void removeBorder(BorderEdge edge) { - switch (edge) { - case bottom: { - if (borderBottom == null) break; - getParent().removeShape(borderBottom); - borderBottom = null; - HSLFTableCell c = getSiblingCell(1,0); - if (c != null) { - c.borderTop = null; - } - break; - } - case top: { - if (borderTop == null) break; - getParent().removeShape(borderTop); - borderTop = null; - HSLFTableCell c = getSiblingCell(-1,0); - if (c != null) { - c.borderBottom = null; - } - break; - } - case right: { - if (borderRight == null) break; - getParent().removeShape(borderRight); - borderRight = null; - HSLFTableCell c = getSiblingCell(0,1); - if (c != null) { - c.borderLeft = null; - } - break; - } - case left: { - if (borderLeft == null) break; - getParent().removeShape(borderLeft); - borderLeft = null; - HSLFTableCell c = getSiblingCell(0,-1); - if (c != null) { - c.borderRight = null; - } - break; - } - default: - throw new IllegalArgumentException(); - } - } - - protected HSLFTableCell getSiblingCell(int row, int col) { - return getParent().getRelativeCell(this, row, col); - } - - /** - * Create a border to format this table - * - * @return the created border - */ - private HSLFLine createBorder(BorderEdge edge) { - HSLFTable table = getParent(); - HSLFLine line = new HSLFLine(table); - table.addShape(line); - - AbstractEscherOptRecord opt = getEscherOptRecord(); - setEscherProperty(opt, EscherProperties.GEOMETRY__SHAPEPATH, -1); - setEscherProperty(opt, EscherProperties.GEOMETRY__FILLOK, -1); - setEscherProperty(opt, EscherProperties.SHADOWSTYLE__SHADOWOBSURED, 0x20000); - setEscherProperty(opt, EscherProperties.THREED__LIGHTFACE, 0x80000); - - anchorBorder(edge, line); - - return line; - } - - protected void applyLineProperties(BorderEdge edge, HSLFLine other) { - HSLFLine line = addLine(edge); - line.setLineWidth(other.getLineWidth()); - line.setLineColor(other.getLineColor()); - // line.setLineCompound(other.getLineCompound()); - // line.setLineDashing(other.getLineDashing()); - } - - @Override - public HSLFTable getParent() { - return (HSLFTable)super.getParent(); - } - - /** - * Set the gridSpan (aka col-span) - * - * @param gridSpan the number of columns to be spanned/merged - * - * @since POI 3.15-beta2 - */ - protected void setGridSpan(int gridSpan) { - this.gridSpan = gridSpan; - } - - /** - * Set the rowSpan - * - * @param rowSpan the number of rows to be spanned/merged - * - * @since POI 3.15-beta2 - */ - protected void setRowSpan(int rowSpan) { - this.rowSpan = rowSpan; - } - - @Override - public int getGridSpan() { - return gridSpan; - } - - @Override - public int getRowSpan() { - return rowSpan; - } - - @Override - public boolean isMerged() { - // if a hslf cell is merged, it won't appear in the cell matrix, i.e. it doesn't exist - // therefore this is always false - return false; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFTextBox.java b/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFTextBox.java deleted file mode 100644 index a76f98b3c..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFTextBox.java +++ /dev/null @@ -1,97 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.usermodel; - -import org.apache.poi.ddf.EscherContainerRecord; -import org.apache.poi.ddf.EscherProperties; -import org.apache.poi.sl.usermodel.ShapeContainer; -import org.apache.poi.sl.usermodel.ShapeType; -import org.apache.poi.sl.usermodel.TextBox; -import org.apache.poi.sl.usermodel.VerticalAlignment; - -/** - * Represents a TextFrame shape in PowerPoint. - *

    - * Contains the text in a text frame as well as the properties and methods - * that control alignment and anchoring of the text. - *

    - * - * @author Yegor Kozlov - */ -public class HSLFTextBox extends HSLFTextShape implements TextBox { - - /** - * Create a TextBox object and initialize it from the supplied Record container. - * - * @param escherRecord EscherSpContainer container which holds information about this shape - * @param parent the parent of the shape - */ - protected HSLFTextBox(EscherContainerRecord escherRecord, ShapeContainer parent){ - super(escherRecord, parent); - - } - - /** - * Create a new TextBox. This constructor is used when a new shape is created. - * - * @param parent the parent of this Shape. For example, if this text box is a cell - * in a table then the parent is Table. - */ - public HSLFTextBox(ShapeContainer parent){ - super(parent); - } - - /** - * Create a new TextBox. This constructor is used when a new shape is created. - * - */ - public HSLFTextBox(){ - this(null); - } - - /** - * Create a new TextBox and initialize its internal structures - * - * @return the created EscherContainerRecord which holds shape data - */ - @Override - protected EscherContainerRecord createSpContainer(boolean isChild){ - EscherContainerRecord ecr = super.createSpContainer(isChild); - - setShapeType(ShapeType.TEXT_BOX); - - //set default properties for a TextBox - setEscherProperty(EscherProperties.FILL__FILLCOLOR, 0x8000004); - setEscherProperty(EscherProperties.FILL__FILLBACKCOLOR, 0x8000000); - setEscherProperty(EscherProperties.FILL__NOFILLHITTEST, 0x100000); - setEscherProperty(EscherProperties.LINESTYLE__COLOR, 0x8000001); - setEscherProperty(EscherProperties.LINESTYLE__NOLINEDRAWDASH, 0x80000); - setEscherProperty(EscherProperties.SHADOWSTYLE__COLOR, 0x8000002); - - // init paragraphs - getTextParagraphs(); - - return ecr; - } - - @Override - protected void setDefaultTextProperties(HSLFTextParagraph _txtrun){ - setVerticalAlignment(VerticalAlignment.TOP); - setEscherProperty(EscherProperties.TEXT__SIZE_TEXT_TO_FIT_SHAPE, 0x20002); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFTextParagraph.java b/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFTextParagraph.java deleted file mode 100644 index 9d39d3e9d..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFTextParagraph.java +++ /dev/null @@ -1,1650 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.usermodel; - -import static org.apache.poi.hslf.record.RecordTypes.OutlineTextRefAtom; - -import java.awt.Color; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.apache.poi.hslf.exceptions.HSLFException; -import org.apache.poi.hslf.model.PPFont; -import org.apache.poi.hslf.model.textproperties.BitMaskTextProp; -import org.apache.poi.hslf.model.textproperties.FontAlignmentProp; -import org.apache.poi.hslf.model.textproperties.IndentProp; -import org.apache.poi.hslf.model.textproperties.ParagraphFlagsTextProp; -import org.apache.poi.hslf.model.textproperties.TextAlignmentProp; -import org.apache.poi.hslf.model.textproperties.TextPFException9; -import org.apache.poi.hslf.model.textproperties.TextProp; -import org.apache.poi.hslf.model.textproperties.TextPropCollection; -import org.apache.poi.hslf.model.textproperties.TextPropCollection.TextPropType; -import org.apache.poi.hslf.record.ColorSchemeAtom; -import org.apache.poi.hslf.record.EscherTextboxWrapper; -import org.apache.poi.hslf.record.FontCollection; -import org.apache.poi.hslf.record.InteractiveInfo; -import org.apache.poi.hslf.record.MasterTextPropAtom; -import org.apache.poi.hslf.record.OutlineTextRefAtom; -import org.apache.poi.hslf.record.PPDrawing; -import org.apache.poi.hslf.record.Record; -import org.apache.poi.hslf.record.RecordContainer; -import org.apache.poi.hslf.record.RecordTypes; -import org.apache.poi.hslf.record.RoundTripHFPlaceholder12; -import org.apache.poi.hslf.record.SlideListWithText; -import org.apache.poi.hslf.record.SlidePersistAtom; -import org.apache.poi.hslf.record.StyleTextProp9Atom; -import org.apache.poi.hslf.record.StyleTextPropAtom; -import org.apache.poi.hslf.record.TextBytesAtom; -import org.apache.poi.hslf.record.TextCharsAtom; -import org.apache.poi.hslf.record.TextHeaderAtom; -import org.apache.poi.hslf.record.TextRulerAtom; -import org.apache.poi.hslf.record.TextSpecInfoAtom; -import org.apache.poi.hslf.record.TxInteractiveInfoAtom; -import org.apache.poi.sl.draw.DrawPaint; -import org.apache.poi.sl.usermodel.AutoNumberingScheme; -import org.apache.poi.sl.usermodel.MasterSheet; -import org.apache.poi.sl.usermodel.PaintStyle; -import org.apache.poi.sl.usermodel.PaintStyle.SolidPaint; -import org.apache.poi.sl.usermodel.Placeholder; -import org.apache.poi.sl.usermodel.TextParagraph; -import org.apache.poi.util.Internal; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.util.StringUtil; -import org.apache.poi.util.Units; - -/** - * This class represents a run of text in a powerpoint document. That - * run could be text on a sheet, or text in a note. - * It is only a very basic class for now - */ - -public final class HSLFTextParagraph implements TextParagraph { - protected static final POILogger logger = POILogFactory.getLogger(HSLFTextParagraph.class); - - /** - * How to align the text - */ - /* package */static final int AlignLeft = 0; - /* package */static final int AlignCenter = 1; - /* package */static final int AlignRight = 2; - /* package */static final int AlignJustify = 3; - - // Note: These fields are protected to help with unit testing - // Other classes shouldn't really go playing with them! - private final TextHeaderAtom _headerAtom; - private TextBytesAtom _byteAtom; - private TextCharsAtom _charAtom; - private TextPropCollection _paragraphStyle = new TextPropCollection(1, TextPropType.paragraph); - private TextPropCollection _masterStyle; - - protected TextRulerAtom _ruler; - protected final List _runs = new ArrayList(); - protected HSLFTextShape _parentShape; - private HSLFSheet _sheet; - private int shapeId; - - private StyleTextProp9Atom styleTextProp9Atom; - - private boolean _dirty = false; - - private final List parentList; - - /** - * Constructs a Text Run from a Unicode text block. - * Either a {@link TextCharsAtom} or a {@link TextBytesAtom} needs to be provided. - * - * @param tha the TextHeaderAtom that defines what's what - * @param tba the TextBytesAtom containing the text or null if {@link TextCharsAtom} is provided - * @param tca the TextCharsAtom containing the text or null if {@link TextBytesAtom} is provided - * @param parentList the list which contains this paragraph - */ - /* package */ HSLFTextParagraph( - TextHeaderAtom tha, - TextBytesAtom tba, - TextCharsAtom tca, - List parentList - ) { - if (tha == null) { - throw new IllegalArgumentException("TextHeaderAtom must be set."); - } - _headerAtom = tha; - _byteAtom = tba; - _charAtom = tca; - this.parentList = parentList; - } - - /* package */HSLFTextParagraph(HSLFTextParagraph other) { - _headerAtom = other._headerAtom; - _byteAtom = other._byteAtom; - _charAtom = other._charAtom; - _parentShape = other._parentShape; - _sheet = other._sheet; - _ruler = other._ruler; - shapeId = other.shapeId; - _paragraphStyle.copy(other._paragraphStyle); - parentList = other.parentList; - } - - public void addTextRun(HSLFTextRun run) { - _runs.add(run); - } - - @Override - public List getTextRuns() { - return _runs; - } - - public TextPropCollection getParagraphStyle() { - return _paragraphStyle; - } - - public void setParagraphStyle(TextPropCollection paragraphStyle) { - _paragraphStyle.copy(paragraphStyle); - } - - /** - * Setting a master style reference - * - * @param paragraphStyle the master style reference - * - * @since POI 3.14-Beta1 - */ - @Internal - /* package */ void setMasterStyleReference(TextPropCollection masterStyle) { - _masterStyle = masterStyle; - } - - /** - * Supply the Sheet we belong to, which might have an assigned SlideShow - * Also passes it on to our child RichTextRuns - */ - public static void supplySheet(List paragraphs, HSLFSheet sheet) { - if (paragraphs == null) { - return; - } - for (HSLFTextParagraph p : paragraphs) { - p.supplySheet(sheet); - } - - assert(sheet.getSlideShow() != null); - } - - /** - * Supply the Sheet we belong to, which might have an assigned SlideShow - * Also passes it on to our child RichTextRuns - */ - private void supplySheet(HSLFSheet sheet) { - this._sheet = sheet; - - if (_runs == null) { - return; - } - for (HSLFTextRun rt : _runs) { - rt.updateSheet(); - } - } - - public HSLFSheet getSheet() { - return this._sheet; - } - - /** - * @return Shape ID - */ - protected int getShapeId() { - return shapeId; - } - - /** - * @param id Shape ID - */ - protected void setShapeId(int id) { - shapeId = id; - } - - /** - * @return 0-based index of the text run in the SLWT container - */ - protected int getIndex() { - return (_headerAtom != null) ? _headerAtom.getIndex() : -1; - } - - /** - * Sets the index of the paragraph in the SLWT container - * - * @param index - */ - protected void setIndex(int index) { - if (_headerAtom != null) { - _headerAtom.setIndex(index); - } - } - - /** - * Returns the type of the text, from the TextHeaderAtom. - * Possible values can be seen from TextHeaderAtom - * @see org.apache.poi.hslf.record.TextHeaderAtom - */ - public int getRunType() { - return (_headerAtom != null) ? _headerAtom.getTextType() : -1; - } - - public void setRunType(int runType) { - if (_headerAtom != null) { - _headerAtom.setTextType(runType); - } - } - - /** - * Is this Text Run one from a {@link PPDrawing}, or is it - * one from the {@link SlideListWithText}? - */ - public boolean isDrawingBased() { - return (getIndex() == -1); - } - - public TextRulerAtom getTextRuler() { - return _ruler; - } - - public TextRulerAtom createTextRuler() { - _ruler = getTextRuler(); - if (_ruler == null) { - _ruler = TextRulerAtom.getParagraphInstance(); - Record childAfter = _byteAtom; - if (childAfter == null) { - childAfter = _charAtom; - } - if (childAfter == null) { - childAfter = _headerAtom; - } - _headerAtom.getParentRecord().addChildAfter(_ruler, childAfter); - } - return _ruler; - } - - /** - * Returns records that make up the list of text paragraphs - * (there can be misc InteractiveInfo, TxInteractiveInfo and other records) - * - * @return text run records - */ - public Record[] getRecords() { - Record r[] = _headerAtom.getParentRecord().getChildRecords(); - return getRecords(r, new int[] { 0 }, _headerAtom); - } - - private static Record[] getRecords(Record[] records, int[] startIdx, TextHeaderAtom headerAtom) { - if (records == null) { - throw new NullPointerException("records need to be set."); - } - - for (; startIdx[0] < records.length; startIdx[0]++) { - Record r = records[startIdx[0]]; - if (r instanceof TextHeaderAtom && (headerAtom == null || r == headerAtom)) { - break; - } - } - - if (startIdx[0] >= records.length) { - logger.log(POILogger.INFO, "header atom wasn't found - container might contain only an OutlineTextRefAtom"); - return new Record[0]; - } - - int length; - for (length = 1; startIdx[0] + length < records.length; length++) { - Record r = records[startIdx[0]+length]; - if (r instanceof TextHeaderAtom || r instanceof SlidePersistAtom) { - break; - } - } - - Record result[] = new Record[length]; - System.arraycopy(records, startIdx[0], result, 0, length); - startIdx[0] += length; - - return result; - } - - /** Numbered List info */ - public void setStyleTextProp9Atom(final StyleTextProp9Atom styleTextProp9Atom) { - this.styleTextProp9Atom = styleTextProp9Atom; - } - - /** Numbered List info */ - public StyleTextProp9Atom getStyleTextProp9Atom() { - return this.styleTextProp9Atom; - } - - @Override - public Iterator iterator() { - return _runs.iterator(); - } - - @Override - public Double getLeftMargin() { - TextProp tp = getPropVal(_paragraphStyle, _masterStyle, "text.offset"); - return (tp == null) ? null : Units.masterToPoints(tp.getValue()); - } - - @Override - public void setLeftMargin(Double leftMargin) { - Integer val = (leftMargin == null) ? null : Units.pointsToMaster(leftMargin); - setParagraphTextPropVal("text.offset", val); - } - - @Override - public Double getRightMargin() { - // TODO: find out, how to determine this value - return null; - } - - @Override - public void setRightMargin(Double rightMargin) { - // TODO: find out, how to set this value - } - - @Override - public Double getIndent() { - TextProp tp = getPropVal(_paragraphStyle, _masterStyle, "bullet.offset"); - return (tp == null) ? null : Units.masterToPoints(tp.getValue()); - } - - @Override - public void setIndent(Double indent) { - Integer val = (indent == null) ? null : Units.pointsToMaster(indent); - setParagraphTextPropVal("bullet.offset", val); - } - - @Override - public String getDefaultFontFamily() { - String typeface = null; - if (!_runs.isEmpty()) { - typeface = _runs.get(0).getFontFamily(); - } - return (typeface != null) ? typeface : "Arial"; - } - - @Override - public Double getDefaultFontSize() { - Double d = null; - if (!_runs.isEmpty()) { - d = _runs.get(0).getFontSize(); - } - - return (d != null) ? d : 12d; - } - - @Override - public void setTextAlign(TextAlign align) { - Integer alignInt = null; - if (align != null) { - switch (align) { - default: - case LEFT: alignInt = TextAlignmentProp.LEFT;break; - case CENTER: alignInt = TextAlignmentProp.CENTER; break; - case RIGHT: alignInt = TextAlignmentProp.RIGHT; break; - case DIST: alignInt = TextAlignmentProp.DISTRIBUTED; break; - case JUSTIFY: alignInt = TextAlignmentProp.JUSTIFY; break; - case JUSTIFY_LOW: alignInt = TextAlignmentProp.JUSTIFYLOW; break; - case THAI_DIST: alignInt = TextAlignmentProp.THAIDISTRIBUTED; break; - } - } - setParagraphTextPropVal("alignment", alignInt); - } - - @Override - public TextAlign getTextAlign() { - TextProp tp = getPropVal(_paragraphStyle, _masterStyle, "alignment"); - if (tp == null) { - return null; - } - switch (tp.getValue()) { - default: - case TextAlignmentProp.LEFT: return TextAlign.LEFT; - case TextAlignmentProp.CENTER: return TextAlign.CENTER; - case TextAlignmentProp.RIGHT: return TextAlign.RIGHT; - case TextAlignmentProp.JUSTIFY: return TextAlign.JUSTIFY; - case TextAlignmentProp.JUSTIFYLOW: return TextAlign.JUSTIFY_LOW; - case TextAlignmentProp.DISTRIBUTED: return TextAlign.DIST; - case TextAlignmentProp.THAIDISTRIBUTED: return TextAlign.THAI_DIST; - } - } - - @Override - public FontAlign getFontAlign() { - TextProp tp = getPropVal(_paragraphStyle, _masterStyle, FontAlignmentProp.NAME); - if (tp == null) { - return null; - } - - switch (tp.getValue()) { - case FontAlignmentProp.BASELINE: return FontAlign.BASELINE; - case FontAlignmentProp.TOP: return FontAlign.TOP; - case FontAlignmentProp.CENTER: return FontAlign.CENTER; - case FontAlignmentProp.BOTTOM: return FontAlign.BOTTOM; - default: return FontAlign.AUTO; - } - } - - public AutoNumberingScheme getAutoNumberingScheme() { - if (styleTextProp9Atom == null) { - return null; - } - TextPFException9[] ant = styleTextProp9Atom.getAutoNumberTypes(); - int level = getIndentLevel(); - if (ant == null || level == -1 || level >= ant.length) { - return null; - } - return ant[level].getAutoNumberScheme(); - } - - public Integer getAutoNumberingStartAt() { - if (styleTextProp9Atom == null) { - return null; - } - TextPFException9[] ant = styleTextProp9Atom.getAutoNumberTypes(); - int level = getIndentLevel(); - if (ant == null || level >= ant.length) { - return null; - } - Short startAt = ant[level].getAutoNumberStartNumber(); - assert(startAt != null); - return startAt.intValue(); - } - - - @Override - public BulletStyle getBulletStyle() { - if (!isBullet() && getAutoNumberingScheme() == null) { - return null; - } - - return new BulletStyle() { - @Override - public String getBulletCharacter() { - Character chr = HSLFTextParagraph.this.getBulletChar(); - return (chr == null || chr == 0) ? "" : "" + chr; - } - - @Override - public String getBulletFont() { - return HSLFTextParagraph.this.getBulletFont(); - } - - @Override - public Double getBulletFontSize() { - return HSLFTextParagraph.this.getBulletSize(); - } - - @Override - public void setBulletFontColor(Color color) { - setBulletFontColor(DrawPaint.createSolidPaint(color)); - } - - @Override - public void setBulletFontColor(PaintStyle color) { - if (!(color instanceof SolidPaint)) { - throw new IllegalArgumentException("HSLF only supports SolidPaint"); - } - SolidPaint sp = (SolidPaint)color; - Color col = DrawPaint.applyColorTransform(sp.getSolidColor()); - HSLFTextParagraph.this.setBulletColor(col); - } - - @Override - public PaintStyle getBulletFontColor() { - Color col = HSLFTextParagraph.this.getBulletColor(); - return DrawPaint.createSolidPaint(col); - } - - @Override - public AutoNumberingScheme getAutoNumberingScheme() { - return HSLFTextParagraph.this.getAutoNumberingScheme(); - } - - @Override - public Integer getAutoNumberingStartAt() { - return HSLFTextParagraph.this.getAutoNumberingStartAt(); - } - }; - } - - @Override - public void setBulletStyle(Object... styles) { - if (styles.length == 0) { - setBullet(false); - } else { - setBullet(true); - for (Object ostyle : styles) { - if (ostyle instanceof Number) { - setBulletSize(((Number)ostyle).doubleValue()); - } else if (ostyle instanceof Color) { - setBulletColor((Color)ostyle); - } else if (ostyle instanceof Character) { - setBulletChar((Character)ostyle); - } else if (ostyle instanceof String) { - setBulletFont((String)ostyle); - } else if (ostyle instanceof AutoNumberingScheme) { - throw new HSLFException("setting bullet auto-numberin scheme for HSLF not supported ... yet"); - } - } - } - } - - @Override - public HSLFTextShape getParentShape() { - return _parentShape; - } - - public void setParentShape(HSLFTextShape parentShape) { - _parentShape = parentShape; - } - - @Override - public int getIndentLevel() { - return _paragraphStyle == null ? 0 : _paragraphStyle.getIndentLevel(); - } - - @Override - public void setIndentLevel(int level) { - if( _paragraphStyle != null ) { - _paragraphStyle.setIndentLevel((short)level); - } - } - - /** - * Sets whether this rich text run has bullets - */ - public void setBullet(boolean flag) { - setFlag(ParagraphFlagsTextProp.BULLET_IDX, flag); - } - - /** - * Returns whether this rich text run has bullets - */ - public boolean isBullet() { - return getFlag(ParagraphFlagsTextProp.BULLET_IDX); - } - - /** - * Sets the bullet character - */ - public void setBulletChar(Character c) { - Integer val = (c == null) ? null : (int)c.charValue(); - setParagraphTextPropVal("bullet.char", val); - } - - /** - * Returns the bullet character - */ - public Character getBulletChar() { - TextProp tp = getPropVal(_paragraphStyle, _masterStyle, "bullet.char"); - return (tp == null) ? null : (char)tp.getValue(); - } - - /** - * Sets the bullet size - */ - public void setBulletSize(Double size) { - setPctOrPoints("bullet.size", size); - } - - /** - * Returns the bullet size, null if unset - */ - public Double getBulletSize() { - return getPctOrPoints("bullet.size"); - } - - /** - * Sets the bullet color - */ - public void setBulletColor(Color color) { - Integer val = (color == null) ? null : new Color(color.getBlue(), color.getGreen(), color.getRed(), 254).getRGB(); - setParagraphTextPropVal("bullet.color", val); - setFlag(ParagraphFlagsTextProp.BULLET_HARDCOLOR_IDX, (color != null)); - } - - /** - * Returns the bullet color - */ - public Color getBulletColor() { - TextProp tp = getPropVal(_paragraphStyle, _masterStyle, "bullet.color"); - boolean hasColor = getFlag(ParagraphFlagsTextProp.BULLET_HARDCOLOR_IDX); - if (tp == null || !hasColor) { - // if bullet color is undefined, return color of first run - if (_runs.isEmpty()) { - return null; - } - - SolidPaint sp = _runs.get(0).getFontColor(); - if(sp == null) { - return null; - } - - return DrawPaint.applyColorTransform(sp.getSolidColor()); - } - - return getColorFromColorIndexStruct(tp.getValue(), _sheet); - } - - /** - * Sets the bullet font - */ - public void setBulletFont(String typeface) { - if (typeface == null) { - setPropVal(_paragraphStyle, _masterStyle, "bullet.font", null); - setFlag(ParagraphFlagsTextProp.BULLET_HARDFONT_IDX, false); - return; - } - - FontCollection fc = getSheet().getSlideShow().getFontCollection(); - int idx = fc.addFont(typeface); - - setParagraphTextPropVal("bullet.font", idx); - setFlag(ParagraphFlagsTextProp.BULLET_HARDFONT_IDX, true); - } - - /** - * Returns the bullet font - */ - public String getBulletFont() { - TextProp tp = getPropVal(_paragraphStyle, _masterStyle, "bullet.font"); - boolean hasFont = getFlag(ParagraphFlagsTextProp.BULLET_HARDFONT_IDX); - if (tp == null || !hasFont) { - return getDefaultFontFamily(); - } - PPFont ppFont = getSheet().getSlideShow().getFont(tp.getValue()); - assert(ppFont != null); - return ppFont.getFontName(); - } - - @Override - public void setLineSpacing(Double lineSpacing) { - setPctOrPoints("linespacing", lineSpacing); - } - - @Override - public Double getLineSpacing() { - return getPctOrPoints("linespacing"); - } - - @Override - public void setSpaceBefore(Double spaceBefore) { - setPctOrPoints("spacebefore", spaceBefore); - } - - @Override - public Double getSpaceBefore() { - return getPctOrPoints("spacebefore"); - } - - @Override - public void setSpaceAfter(Double spaceAfter) { - setPctOrPoints("spaceafter", spaceAfter); - } - - @Override - public Double getSpaceAfter() { - return getPctOrPoints("spaceafter"); - } - - @Override - public Double getDefaultTabSize() { - // TODO: implement - return null; - } - - private Double getPctOrPoints(String propName) { - TextProp tp = getPropVal(_paragraphStyle, _masterStyle, propName); - if (tp == null) { - return null; - } - int val = tp.getValue(); - return (val < 0) ? Units.masterToPoints(val) : val; - } - - private void setPctOrPoints(String propName, Double dval) { - Integer ival = null; - if (dval != null) { - ival = (dval < 0) ? Units.pointsToMaster(dval) : dval.intValue(); - } - setParagraphTextPropVal(propName, ival); - } - - private boolean getFlag(int index) { - BitMaskTextProp tp = (BitMaskTextProp)getPropVal(_paragraphStyle, _masterStyle, ParagraphFlagsTextProp.NAME); - return (tp == null) ? false : tp.getSubValue(index); - } - - private void setFlag(int index, boolean value) { - BitMaskTextProp tp = (BitMaskTextProp)_paragraphStyle.addWithName(ParagraphFlagsTextProp.NAME); - tp.setSubValue(value, index); - setDirty(); - } - - /** - * Fetch the value of the given Paragraph related TextProp. Returns null if - * that TextProp isn't present. If the TextProp isn't present, the value - * from the appropriate Master Sheet will apply. - * - * The propName can be a comma-separated list, in case multiple equivalent values - * are queried - */ - protected TextProp getPropVal(TextPropCollection props, TextPropCollection masterProps, String propName) { - String propNames[] = propName.split(","); - for (String pn : propNames) { - TextProp prop = props.findByName(pn); - if (prop == null) { - continue; - } - - // Font properties (maybe other too???) can have an index of -1 - // so we check the master for this font index then - if (pn.contains("font") && prop.getValue() == -1) { - return getMasterPropVal(props, masterProps, pn); - } - - return prop; - } - - return getMasterPropVal(props, masterProps, propName); - } - - private TextProp getMasterPropVal(TextPropCollection props, TextPropCollection masterProps, String propName) { - boolean isChar = props.getTextPropType() == TextPropType.character; - - // check if we can delegate to master for the property - if (!isChar) { - BitMaskTextProp maskProp = (BitMaskTextProp) props.findByName(ParagraphFlagsTextProp.NAME); - boolean hardAttribute = (maskProp != null && maskProp.getValue() == 0); - if (hardAttribute) { - return null; - } - } - - String propNames[] = propName.split(","); - if (masterProps == null) { - HSLFSheet sheet = getSheet(); - int txtype = getRunType(); - HSLFMasterSheet master = sheet.getMasterSheet(); - if (master == null) { - logger.log(POILogger.WARN, "MasterSheet is not available"); - return null; - } - - for (String pn : propNames) { - TextProp prop = master.getStyleAttribute(txtype, getIndentLevel(), pn, isChar); - if (prop != null) { - return prop; - } - } - } else { - for (String pn : propNames) { - TextProp prop = masterProps.findByName(pn); - if (prop != null) { - return prop; - } - } - } - - return null; - } - - /** - * Returns the named TextProp, either by fetching it (if it exists) or - * adding it (if it didn't) - * - * @param props the TextPropCollection to fetch from / add into - * @param name the name of the TextProp to fetch/add - * @param val the value, null if unset - */ - protected void setPropVal(TextPropCollection props, TextPropCollection masterProps, String name, Integer val) { - TextPropCollection pc = props; - if (getSheet() instanceof MasterSheet && masterProps != null) { - pc = masterProps; - } - - if (val == null) { - pc.removeByName(name); - return; - } - - // Fetch / Add the TextProp - TextProp tp = pc.addWithName(name); - tp.setValue(val); - } - - /** - * Check and add linebreaks to text runs leading other paragraphs - * - * @param paragraphs - */ - protected static void fixLineEndings(List paragraphs) { - HSLFTextRun lastRun = null; - for (HSLFTextParagraph p : paragraphs) { - if (lastRun != null && !lastRun.getRawText().endsWith("\r")) { - lastRun.setText(lastRun.getRawText() + "\r"); - } - List ltr = p.getTextRuns(); - if (ltr.isEmpty()) { - throw new HSLFException("paragraph without textruns found"); - } - lastRun = ltr.get(ltr.size() - 1); - assert (lastRun.getRawText() != null); - } - } - - /** - * Search for a StyleTextPropAtom is for this text header (list of paragraphs) - * - * @param header the header - * @param textLen the length of the rawtext, or -1 if the length is not known - */ - private static StyleTextPropAtom findStyleAtomPresent(TextHeaderAtom header, int textLen) { - boolean afterHeader = false; - StyleTextPropAtom style = null; - for (Record record : header.getParentRecord().getChildRecords()) { - long rt = record.getRecordType(); - if (afterHeader && rt == RecordTypes.TextHeaderAtom.typeID) { - // already on the next header, quit searching - break; - } - afterHeader |= (header == record); - if (afterHeader && rt == RecordTypes.StyleTextPropAtom.typeID) { - // found it - style = (StyleTextPropAtom) record; - } - } - - if (style == null) { - logger.log(POILogger.INFO, "styles atom doesn't exist. Creating dummy record for later saving."); - style = new StyleTextPropAtom((textLen < 0) ? 1 : textLen); - } else { - if (textLen >= 0) { - style.setParentTextSize(textLen); - } - } - - return style; - } - - /** - * Saves the modified paragraphs/textrun to the records. - * Also updates the styles to the correct text length. - */ - protected static void storeText(List paragraphs) { - fixLineEndings(paragraphs); - updateTextAtom(paragraphs); - updateStyles(paragraphs); - updateHyperlinks(paragraphs); - refreshRecords(paragraphs); - - for (HSLFTextParagraph p : paragraphs) { - p._dirty = false; - } - } - - /** - * Set the correct text atom depending on the multibyte usage - */ - private static void updateTextAtom(List paragraphs) { - final String rawText = toInternalString(getRawText(paragraphs)); - - // Will it fit in a 8 bit atom? - boolean isUnicode = StringUtil.hasMultibyte(rawText); - // isUnicode = true; - - TextHeaderAtom headerAtom = paragraphs.get(0)._headerAtom; - TextBytesAtom byteAtom = paragraphs.get(0)._byteAtom; - TextCharsAtom charAtom = paragraphs.get(0)._charAtom; - StyleTextPropAtom styleAtom = findStyleAtomPresent(headerAtom, rawText.length()); - - // Store in the appropriate record - Record oldRecord = null, newRecord = null; - if (isUnicode) { - if (byteAtom != null || charAtom == null) { - oldRecord = byteAtom; - charAtom = new TextCharsAtom(); - } - newRecord = charAtom; - charAtom.setText(rawText); - } else { - if (charAtom != null || byteAtom == null) { - oldRecord = charAtom; - byteAtom = new TextBytesAtom(); - } - newRecord = byteAtom; - byte[] byteText = new byte[rawText.length()]; - StringUtil.putCompressedUnicode(rawText, byteText, 0); - byteAtom.setText(byteText); - } - assert (newRecord != null); - - RecordContainer _txtbox = headerAtom.getParentRecord(); - Record[] cr = _txtbox.getChildRecords(); - int /* headerIdx = -1, */ textIdx = -1, styleIdx = -1; - for (int i = 0; i < cr.length; i++) { - Record r = cr[i]; - if (r == headerAtom) { - ; // headerIdx = i; - } else if (r == oldRecord || r == newRecord) { - textIdx = i; - } else if (r == styleAtom) { - styleIdx = i; - } - } - - if (textIdx == -1) { - // the old record was never registered, ignore it - _txtbox.addChildAfter(newRecord, headerAtom); - // textIdx = headerIdx + 1; - } else { - // swap not appropriated records - noop if unchanged - cr[textIdx] = newRecord; - } - - if (styleIdx == -1) { - // Add the new StyleTextPropAtom after the TextCharsAtom / TextBytesAtom - _txtbox.addChildAfter(styleAtom, newRecord); - } - - for (HSLFTextParagraph p : paragraphs) { - if (newRecord == byteAtom) { - p._byteAtom = byteAtom; - p._charAtom = null; - } else { - p._byteAtom = null; - p._charAtom = charAtom; - } - } - - } - - /** - * Update paragraph and character styles - merges them when subsequential styles match - */ - private static void updateStyles(List paragraphs) { - final String rawText = toInternalString(getRawText(paragraphs)); - TextHeaderAtom headerAtom = paragraphs.get(0)._headerAtom; - StyleTextPropAtom styleAtom = findStyleAtomPresent(headerAtom, rawText.length()); - - // Update the text length for its Paragraph and Character stylings - // * reset the length, to the new string's length - // * add on +1 if the last block - - styleAtom.clearStyles(); - - TextPropCollection lastPTPC = null, lastRTPC = null, ptpc = null, rtpc = null; - for (HSLFTextParagraph para : paragraphs) { - ptpc = para.getParagraphStyle(); - ptpc.updateTextSize(0); - if (!ptpc.equals(lastPTPC)) { - lastPTPC = styleAtom.addParagraphTextPropCollection(0); - lastPTPC.copy(ptpc); - } - for (HSLFTextRun tr : para.getTextRuns()) { - rtpc = tr.getCharacterStyle(); - rtpc.updateTextSize(0); - if (!rtpc.equals(lastRTPC)) { - lastRTPC = styleAtom.addCharacterTextPropCollection(0); - lastRTPC.copy(rtpc); - } - int len = tr.getLength(); - ptpc.updateTextSize(ptpc.getCharactersCovered() + len); - rtpc.updateTextSize(len); - lastPTPC.updateTextSize(lastPTPC.getCharactersCovered() + len); - lastRTPC.updateTextSize(lastRTPC.getCharactersCovered() + len); - } - } - - if (lastPTPC == null || lastRTPC == null || ptpc == null || rtpc == null) { // NOSONAR - throw new HSLFException("Not all TextPropCollection could be determined."); - } - - ptpc.updateTextSize(ptpc.getCharactersCovered() + 1); - rtpc.updateTextSize(rtpc.getCharactersCovered() + 1); - lastPTPC.updateTextSize(lastPTPC.getCharactersCovered() + 1); - lastRTPC.updateTextSize(lastRTPC.getCharactersCovered() + 1); - - /** - * If TextSpecInfoAtom is present, we must update the text size in it, - * otherwise the ppt will be corrupted - */ - for (Record r : paragraphs.get(0).getRecords()) { - if (r instanceof TextSpecInfoAtom) { - ((TextSpecInfoAtom) r).setParentSize(rawText.length() + 1); - break; - } - } - } - - private static void updateHyperlinks(List paragraphs) { - TextHeaderAtom headerAtom = paragraphs.get(0)._headerAtom; - RecordContainer _txtbox = headerAtom.getParentRecord(); - // remove existing hyperlink records - for (Record r : _txtbox.getChildRecords()) { - if (r instanceof InteractiveInfo || r instanceof TxInteractiveInfoAtom) { - _txtbox.removeChild(r); - } - } - // now go through all the textruns and check for hyperlinks - HSLFHyperlink lastLink = null; - for (HSLFTextParagraph para : paragraphs) { - for (HSLFTextRun run : para) { - HSLFHyperlink thisLink = run.getHyperlink(); - if (thisLink != null && thisLink == lastLink) { - // the hyperlink extends over this text run, increase its length - // TODO: the text run might be longer than the hyperlink - thisLink.setEndIndex(thisLink.getEndIndex()+run.getLength()); - } else { - if (lastLink != null) { - InteractiveInfo info = lastLink.getInfo(); - TxInteractiveInfoAtom txinfo = lastLink.getTextRunInfo(); - assert(info != null && txinfo != null); - _txtbox.appendChildRecord(info); - _txtbox.appendChildRecord(txinfo); - } - } - lastLink = thisLink; - } - } - - if (lastLink != null) { - InteractiveInfo info = lastLink.getInfo(); - TxInteractiveInfoAtom txinfo = lastLink.getTextRunInfo(); - assert(info != null && txinfo != null); - _txtbox.appendChildRecord(info); - _txtbox.appendChildRecord(txinfo); - } - } - - /** - * Writes the textbox records back to the document record - */ - private static void refreshRecords(List paragraphs) { - TextHeaderAtom headerAtom = paragraphs.get(0)._headerAtom; - RecordContainer _txtbox = headerAtom.getParentRecord(); - if (_txtbox instanceof EscherTextboxWrapper) { - try { - ((EscherTextboxWrapper) _txtbox).writeOut(null); - } catch (IOException e) { - throw new HSLFException("failed dummy write", e); - } - } - } - - /** - * Adds the supplied text onto the end of the TextParagraphs, - * creating a new RichTextRun for it to sit in. - * - * @param text the text string used by this object. - */ - protected static HSLFTextRun appendText(List paragraphs, String text, boolean newParagraph) { - text = toInternalString(text); - - // check paragraphs - assert(!paragraphs.isEmpty() && !paragraphs.get(0).getTextRuns().isEmpty()); - - HSLFTextParagraph htp = paragraphs.get(paragraphs.size() - 1); - HSLFTextRun htr = htp.getTextRuns().get(htp.getTextRuns().size() - 1); - - boolean addParagraph = newParagraph; - for (String rawText : text.split("(?<=\r)")) { - // special case, if last text paragraph or run is empty, we will reuse it - boolean lastRunEmpty = (htr.getLength() == 0); - boolean lastParaEmpty = lastRunEmpty && (htp.getTextRuns().size() == 1); - - if (addParagraph && !lastParaEmpty) { - TextPropCollection tpc = htp.getParagraphStyle(); - HSLFTextParagraph prevHtp = htp; - htp = new HSLFTextParagraph(htp._headerAtom, htp._byteAtom, htp._charAtom, paragraphs); - htp.getParagraphStyle().copy(tpc); - htp.setParentShape(prevHtp.getParentShape()); - htp.setShapeId(prevHtp.getShapeId()); - htp.supplySheet(prevHtp.getSheet()); - paragraphs.add(htp); - } - addParagraph = true; - - if (!lastRunEmpty) { - TextPropCollection tpc = htr.getCharacterStyle(); - htr = new HSLFTextRun(htp); - htr.getCharacterStyle().copy(tpc); - htp.addTextRun(htr); - } - htr.setText(rawText); - } - - storeText(paragraphs); - - return htr; - } - - /** - * Sets (overwrites) the current text. - * Uses the properties of the first paragraph / textrun - * - * @param text the text string used by this object. - */ - public static HSLFTextRun setText(List paragraphs, String text) { - // check paragraphs - assert(!paragraphs.isEmpty() && !paragraphs.get(0).getTextRuns().isEmpty()); - - Iterator paraIter = paragraphs.iterator(); - HSLFTextParagraph htp = paraIter.next(); // keep first - assert (htp != null); - while (paraIter.hasNext()) { - paraIter.next(); - paraIter.remove(); - } - - Iterator runIter = htp.getTextRuns().iterator(); - if (runIter.hasNext()) { - HSLFTextRun htr = runIter.next(); - htr.setText(""); - while (runIter.hasNext()) { - runIter.next(); - runIter.remove(); - } - } else { - HSLFTextRun trun = new HSLFTextRun(htp); - htp.addTextRun(trun); - } - - return appendText(paragraphs, text, false); - } - - public static String getText(List paragraphs) { - assert (!paragraphs.isEmpty()); - String rawText = getRawText(paragraphs); - return toExternalString(rawText, paragraphs.get(0).getRunType()); - } - - public static String getRawText(List paragraphs) { - StringBuilder sb = new StringBuilder(); - for (HSLFTextParagraph p : paragraphs) { - for (HSLFTextRun r : p.getTextRuns()) { - sb.append(r.getRawText()); - } - } - return sb.toString(); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - for (HSLFTextRun r : getTextRuns()) { - sb.append(r.getRawText()); - } - return toExternalString(sb.toString(), getRunType()); - } - - /** - * Returns a new string with line breaks converted into internal ppt - * representation - */ - protected static String toInternalString(String s) { - String ns = s.replaceAll("\\r?\\n", "\r"); - return ns; - } - - /** - * Converts raw text from the text paragraphs to a formatted string, - * i.e. it converts certain control characters used in the raw txt - * - * @param rawText the raw text - * @param runType the run type of the shape, paragraph or headerAtom. - * use -1 if unknown - * @return the formatted string - */ - public static String toExternalString(String rawText, int runType) { - // PowerPoint seems to store files with \r as the line break - // The messes things up on everything but a Mac, so translate - // them to \n - String text = rawText.replace('\r', '\n'); - - switch (runType) { - // 0xB acts like cariage return in page titles and like blank in the - // others - case -1: - case org.apache.poi.hslf.record.TextHeaderAtom.TITLE_TYPE: - case org.apache.poi.hslf.record.TextHeaderAtom.CENTER_TITLE_TYPE: - text = text.replace((char) 0x0B, '\n'); - break; - default: - text = text.replace((char) 0x0B, ' '); - break; - } - - return text; - } - - /** - * For a given PPDrawing, grab all the TextRuns - */ - public static List> findTextParagraphs(PPDrawing ppdrawing, HSLFSheet sheet) { - List> runsV = new ArrayList>(); - for (EscherTextboxWrapper wrapper : ppdrawing.getTextboxWrappers()) { - List p = findTextParagraphs(wrapper, sheet); - if (p != null) { - runsV.add(p); - } - } - return runsV; - } - - /** - * Scans through the supplied record array, looking for - * a TextHeaderAtom followed by one of a TextBytesAtom or - * a TextCharsAtom. Builds up TextRuns from these - * - * @param wrapper an EscherTextboxWrapper - */ - protected static List findTextParagraphs(EscherTextboxWrapper wrapper, HSLFSheet sheet) { - // propagate parents to parent-aware records - RecordContainer.handleParentAwareRecords(wrapper); - int shapeId = wrapper.getShapeId(); - List rv = null; - - OutlineTextRefAtom ota = (OutlineTextRefAtom)wrapper.findFirstOfType(OutlineTextRefAtom.typeID); - if (ota != null) { - // if we are based on an outline, there are no further records to be parsed from the wrapper - if (sheet == null) { - throw new HSLFException("Outline atom reference can't be solved without a sheet record"); - } - - List> sheetRuns = sheet.getTextParagraphs(); - assert (sheetRuns != null); - - int idx = ota.getTextIndex(); - for (List r : sheetRuns) { - if (r.isEmpty()) { - continue; - } - int ridx = r.get(0).getIndex(); - if (ridx > idx) { - break; - } - if (ridx == idx) { - if (rv == null) { - rv = r; - } else { - // create a new container - // TODO: ... is this case really happening? - rv = new ArrayList(rv); - rv.addAll(r); - } - } - } - if (rv == null || rv.isEmpty()) { - logger.log(POILogger.WARN, "text run not found for OutlineTextRefAtom.TextIndex=" + idx); - } - } else { - if (sheet != null) { - // check sheet runs first, so we get exactly the same paragraph list - List> sheetRuns = sheet.getTextParagraphs(); - assert (sheetRuns != null); - - for (List paras : sheetRuns) { - if (!paras.isEmpty() && paras.get(0)._headerAtom.getParentRecord() == wrapper) { - rv = paras; - break; - } - } - } - - if (rv == null) { - // if we haven't found the wrapper in the sheet runs, create a new paragraph list from its record - List> rvl = findTextParagraphs(wrapper.getChildRecords()); - switch (rvl.size()) { - case 0: break; // nothing found - case 1: rv = rvl.get(0); break; // normal case - default: - throw new HSLFException("TextBox contains more than one list of paragraphs."); - } - } - } - - if (rv != null) { - StyleTextProp9Atom styleTextProp9Atom = wrapper.getStyleTextProp9Atom(); - - for (HSLFTextParagraph htp : rv) { - htp.setShapeId(shapeId); - htp.setStyleTextProp9Atom(styleTextProp9Atom); - } - } - return rv; - } - - /** - * Scans through the supplied record array, looking for - * a TextHeaderAtom followed by one of a TextBytesAtom or - * a TextCharsAtom. Builds up TextRuns from these - * - * @param records the records to build from - */ - protected static List> findTextParagraphs(Record[] records) { - List> paragraphCollection = new ArrayList>(); - - int[] recordIdx = { 0 }; - - for (int slwtIndex = 0; recordIdx[0] < records.length; slwtIndex++) { - TextHeaderAtom header = null; - TextBytesAtom tbytes = null; - TextCharsAtom tchars = null; - TextRulerAtom ruler = null; - MasterTextPropAtom indents = null; - - for (Record r : getRecords(records, recordIdx, null)) { - long rt = r.getRecordType(); - if (RecordTypes.TextHeaderAtom.typeID == rt) { - header = (TextHeaderAtom) r; - } else if (RecordTypes.TextBytesAtom.typeID == rt) { - tbytes = (TextBytesAtom) r; - } else if (RecordTypes.TextCharsAtom.typeID == rt) { - tchars = (TextCharsAtom) r; - } else if (RecordTypes.TextRulerAtom.typeID == rt) { - ruler = (TextRulerAtom) r; - } else if (RecordTypes.MasterTextPropAtom.typeID == rt) { - indents = (MasterTextPropAtom) r; - } - // don't search for RecordTypes.StyleTextPropAtom.typeID here ... see findStyleAtomPresent below - } - - if (header == null) { - break; - } - - if (header.getParentRecord() instanceof SlideListWithText) { - // runs found in PPDrawing are not linked with SlideListWithTexts - header.setIndex(slwtIndex); - } - - if (tbytes == null && tchars == null) { - tbytes = new TextBytesAtom(); - // don't add record yet - set it in storeText - logger.log(POILogger.INFO, "bytes nor chars atom doesn't exist. Creating dummy record for later saving."); - } - - String rawText = (tchars != null) ? tchars.getText() : tbytes.getText(); - StyleTextPropAtom styles = findStyleAtomPresent(header, rawText.length()); - - List paragraphs = new ArrayList(); - paragraphCollection.add(paragraphs); - - // split, but keep delimiter - for (String para : rawText.split("(?<=\r)")) { - HSLFTextParagraph tpara = new HSLFTextParagraph(header, tbytes, tchars, paragraphs); - paragraphs.add(tpara); - tpara._ruler = ruler; - tpara.getParagraphStyle().updateTextSize(para.length()); - - HSLFTextRun trun = new HSLFTextRun(tpara); - tpara.addTextRun(trun); - trun.setText(para); - } - - applyCharacterStyles(paragraphs, styles.getCharacterStyles()); - applyParagraphStyles(paragraphs, styles.getParagraphStyles()); - if (indents != null) { - applyParagraphIndents(paragraphs, indents.getIndents()); - } - } - - if (paragraphCollection.isEmpty()) { - logger.log(POILogger.DEBUG, "No text records found."); - } - - return paragraphCollection; - } - - protected static void applyHyperlinks(List paragraphs) { - List links = HSLFHyperlink.find(paragraphs); - - for (HSLFHyperlink h : links) { - int csIdx = 0; - for (HSLFTextParagraph p : paragraphs) { - if (csIdx > h.getEndIndex()) { - break; - } - List runs = p.getTextRuns(); - for (int rlen=0,rIdx=0; rIdx < runs.size(); csIdx+=rlen, rIdx++) { - HSLFTextRun run = runs.get(rIdx); - rlen = run.getLength(); - if (csIdx < h.getEndIndex() && h.getStartIndex() < csIdx+rlen) { - String rawText = run.getRawText(); - int startIdx = h.getStartIndex()-csIdx; - if (startIdx > 0) { - // hyperlink starts within current textrun - HSLFTextRun newRun = new HSLFTextRun(p); - newRun.setCharacterStyle(run.getCharacterStyle()); - newRun.setText(rawText.substring(startIdx)); - run.setText(rawText.substring(0, startIdx)); - runs.add(rIdx+1, newRun); - rlen = startIdx; - continue; - } - int endIdx = Math.min(rlen, h.getEndIndex()-h.getStartIndex()); - if (endIdx < rlen) { - // hyperlink ends before end of current textrun - HSLFTextRun newRun = new HSLFTextRun(p); - newRun.setCharacterStyle(run.getCharacterStyle()); - newRun.setText(rawText.substring(0, endIdx)); - run.setText(rawText.substring(endIdx)); - runs.add(rIdx, newRun); - rlen = endIdx; - run = newRun; - } - run.setHyperlink(h); - } - } - } - } - } - - protected static void applyCharacterStyles(List paragraphs, List charStyles) { - int paraIdx = 0, runIdx = 0; - HSLFTextRun trun; - - for (int csIdx = 0; csIdx < charStyles.size(); csIdx++) { - TextPropCollection p = charStyles.get(csIdx); - for (int ccRun = 0, ccStyle = p.getCharactersCovered(); ccRun < ccStyle;) { - HSLFTextParagraph para = paragraphs.get(paraIdx); - List runs = para.getTextRuns(); - trun = runs.get(runIdx); - final int len = trun.getLength(); - - if (ccRun + len <= ccStyle) { - ccRun += len; - } else { - String text = trun.getRawText(); - trun.setText(text.substring(0, ccStyle - ccRun)); - - HSLFTextRun nextRun = new HSLFTextRun(para); - nextRun.setText(text.substring(ccStyle - ccRun)); - runs.add(runIdx + 1, nextRun); - - ccRun += ccStyle - ccRun; - } - - trun.setCharacterStyle(p); - - if (paraIdx == paragraphs.size()-1 && runIdx == runs.size()-1) { - if (csIdx < charStyles.size() - 1) { - // special case, empty trailing text run - HSLFTextRun nextRun = new HSLFTextRun(para); - nextRun.setText(""); - runs.add(nextRun); - ccRun++; - } else { - // need to add +1 to the last run of the last paragraph - trun.getCharacterStyle().updateTextSize(trun.getLength()+1); - ccRun++; - } - } - - // need to compare it again, in case a run has been added after - if (++runIdx == runs.size()) { - paraIdx++; - runIdx = 0; - } - } - } - } - - protected static void applyParagraphStyles(List paragraphs, List paraStyles) { - int paraIdx = 0; - for (TextPropCollection p : paraStyles) { - for (int ccPara = 0, ccStyle = p.getCharactersCovered(); ccPara < ccStyle; paraIdx++) { - if (paraIdx >= paragraphs.size()) { - return; - } - HSLFTextParagraph htp = paragraphs.get(paraIdx); - TextPropCollection pCopy = new TextPropCollection(0, TextPropType.paragraph); - pCopy.copy(p); - htp.setParagraphStyle(pCopy); - int len = 0; - for (HSLFTextRun trun : htp.getTextRuns()) { - len += trun.getLength(); - } - if (paraIdx == paragraphs.size()-1) { - len++; - } - pCopy.updateTextSize(len); - ccPara += len; - } - } - } - - protected static void applyParagraphIndents(List paragraphs, List paraStyles) { - int paraIdx = 0; - for (IndentProp p : paraStyles) { - for (int ccPara = 0, ccStyle = p.getCharactersCovered(); ccPara < ccStyle; paraIdx++) { - if (paraIdx >= paragraphs.size() || ccPara >= ccStyle-1) { - return; - } - HSLFTextParagraph para = paragraphs.get(paraIdx); - int len = 0; - for (HSLFTextRun trun : para.getTextRuns()) { - len += trun.getLength(); - } - para.setIndentLevel(p.getIndentLevel()); - ccPara += len + 1; - } - } - } - - public EscherTextboxWrapper getTextboxWrapper() { - return (EscherTextboxWrapper) _headerAtom.getParentRecord(); - } - - protected static Color getColorFromColorIndexStruct(int rgb, HSLFSheet sheet) { - int cidx = rgb >>> 24; - Color tmp; - switch (cidx) { - // Background ... Accent 3 color - case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: - if (sheet == null) { - return null; - } - ColorSchemeAtom ca = sheet.getColorScheme(); - tmp = new Color(ca.getColor(cidx), true); - break; - // Color is an sRGB value specified by red, green, and blue fields. - case 0xFE: - tmp = new Color(rgb, true); - break; - // Color is undefined. - default: - case 0xFF: - return null; - } - return new Color(tmp.getBlue(), tmp.getGreen(), tmp.getRed()); - } - - /** - * Sets the value of the given Paragraph TextProp, add if required - * @param propName The name of the Paragraph TextProp - * @param val The value to set for the TextProp - */ - public void setParagraphTextPropVal(String propName, Integer val) { - setPropVal(_paragraphStyle, _masterStyle, propName, val); - setDirty(); - } - - /** - * marks this paragraph dirty, so its records will be renewed on save - */ - public void setDirty() { - _dirty = true; - } - - public boolean isDirty() { - return _dirty; - } - - /** - * Calculates the start index of the given text run - * - * @param textrun the text run to search for - * @return the start index with the paragraph collection or -1 if not found - */ - /* package */ int getStartIdxOfTextRun(HSLFTextRun textrun) { - int idx = 0; - for (HSLFTextParagraph p : parentList) { - for (HSLFTextRun r : p) { - if (r == textrun) { - return idx; - } - idx += r.getLength(); - } - } - return -1; - } - - /** - * {@inheritDoc} - * - * @see RoundTripHFPlaceholder12 - */ - @Override - public boolean isHeaderOrFooter() { - HSLFTextShape s = getParentShape(); - if (s == null) { - return false; - } - Placeholder ph = s.getPlaceholder(); - if (ph == null) { - return false; - } - switch (ph) { - case DATETIME: - case SLIDE_NUMBER: - case FOOTER: - case HEADER: - return true; - default: - return false; - } - } -} \ No newline at end of file diff --git a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFTextRun.java b/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFTextRun.java deleted file mode 100644 index 0d887a412..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFTextRun.java +++ /dev/null @@ -1,461 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.usermodel; - -import java.awt.Color; -import java.util.List; - -import org.apache.poi.hslf.exceptions.HSLFException; -import org.apache.poi.hslf.model.textproperties.BitMaskTextProp; -import org.apache.poi.hslf.model.textproperties.CharFlagsTextProp; -import org.apache.poi.hslf.model.textproperties.TextProp; -import org.apache.poi.hslf.model.textproperties.TextPropCollection; -import org.apache.poi.hslf.model.textproperties.TextPropCollection.TextPropType; -import org.apache.poi.sl.draw.DrawPaint; -import org.apache.poi.sl.usermodel.MasterSheet; -import org.apache.poi.sl.usermodel.PaintStyle; -import org.apache.poi.sl.usermodel.PaintStyle.SolidPaint; -import org.apache.poi.sl.usermodel.Placeholder; -import org.apache.poi.sl.usermodel.TextParagraph; -import org.apache.poi.sl.usermodel.TextRun; -import org.apache.poi.sl.usermodel.TextShape; -import org.apache.poi.util.Internal; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; - - -/** - * Represents a run of text, all with the same style - * - */ -public final class HSLFTextRun implements TextRun { - protected POILogger logger = POILogFactory.getLogger(this.getClass()); - - /** The TextRun we belong to */ - private HSLFTextParagraph parentParagraph; - private String _runText = ""; - private String _fontFamily; - private HSLFHyperlink link; - - /** - * Our paragraph and character style. - * Note - we may share these styles with other RichTextRuns - */ - private TextPropCollection characterStyle = new TextPropCollection(1, TextPropType.character); - - private TextPropCollection masterStyle; - - /** - * Create a new wrapper around a rich text string - * @param parentParagraph the parent paragraph - */ - public HSLFTextRun(HSLFTextParagraph parentParagraph) { - this.parentParagraph = parentParagraph; - } - - public TextPropCollection getCharacterStyle() { - return characterStyle; - } - - public void setCharacterStyle(TextPropCollection characterStyle) { - this.characterStyle.copy(characterStyle); - this.characterStyle.updateTextSize(_runText.length()); - } - - /** - * Setting a master style reference - * - * @param characterStyle the master style reference - * - * @since POI 3.14-Beta1 - */ - @Internal - /* package */ void setMasterStyleReference(TextPropCollection masterStyle) { - this.masterStyle = masterStyle; - } - - - /** - * Supply the SlideShow we belong to - */ - public void updateSheet() { - if (_fontFamily != null) { - setFontFamily(_fontFamily); - _fontFamily = null; - } - } - - /** - * Get the length of the text - */ - public int getLength() { - return _runText.length(); - } - - /** - * Fetch the text, in raw storage form - */ - @Override - public String getRawText() { - return _runText; - } - - /** - * Change the text - */ - @Override - public void setText(String text) { - if (text == null) { - throw new HSLFException("text must not be null"); - } - String newText = HSLFTextParagraph.toInternalString(text); - if (!newText.equals(_runText)) { - _runText = newText; - if (HSLFSlideShow.getLoadSavePhase() == HSLFSlideShow.LoadSavePhase.LOADED) { - parentParagraph.setDirty(); - } - } - } - - // --------------- Internal helpers on rich text properties ------- - - /** - * Fetch the value of the given flag in the CharFlagsTextProp. - * Returns false if the CharFlagsTextProp isn't present, since the - * text property won't be set if there's no CharFlagsTextProp. - */ - private boolean isCharFlagsTextPropVal(int index) { - return getFlag(index); - } - - protected boolean getFlag(int index) { - if (characterStyle == null) { - return false; - } - - BitMaskTextProp prop = (BitMaskTextProp)characterStyle.findByName(CharFlagsTextProp.NAME); - - if (prop == null || !prop.getSubPropMatches()[index]) { - int txtype = parentParagraph.getRunType(); - HSLFSheet sheet = parentParagraph.getSheet(); - if (sheet != null) { - HSLFMasterSheet master = sheet.getMasterSheet(); - if (master != null){ - prop = (BitMaskTextProp)master.getStyleAttribute(txtype, parentParagraph.getIndentLevel(), CharFlagsTextProp.NAME, true); - } - } else { - logger.log(POILogger.WARN, "MasterSheet is not available"); - } - } - - return prop == null ? false : prop.getSubValue(index); - } - - /** - * Set the value of the given flag in the CharFlagsTextProp, adding - * it if required. - */ - private void setCharFlagsTextPropVal(int index, boolean value) { - // TODO: check if paragraph/chars can be handled the same ... - if (getFlag(index) != value) { - setFlag(index, value); - parentParagraph.setDirty(); - } - } - - /** - * Sets the value of the given Paragraph TextProp, add if required - * @param propName The name of the Paragraph TextProp - * @param val The value to set for the TextProp - */ - public void setCharTextPropVal(String propName, Integer val) { - getTextParagraph().setPropVal(characterStyle, masterStyle, propName, val); - getTextParagraph().setDirty(); - } - - - // --------------- Friendly getters / setters on rich text properties ------- - - @Override - public boolean isBold() { - return isCharFlagsTextPropVal(CharFlagsTextProp.BOLD_IDX); - } - - @Override - public void setBold(boolean bold) { - setCharFlagsTextPropVal(CharFlagsTextProp.BOLD_IDX, bold); - } - - @Override - public boolean isItalic() { - return isCharFlagsTextPropVal(CharFlagsTextProp.ITALIC_IDX); - } - - @Override - public void setItalic(boolean italic) { - setCharFlagsTextPropVal(CharFlagsTextProp.ITALIC_IDX, italic); - } - - @Override - public boolean isUnderlined() { - return isCharFlagsTextPropVal(CharFlagsTextProp.UNDERLINE_IDX); - } - - @Override - public void setUnderlined(boolean underlined) { - setCharFlagsTextPropVal(CharFlagsTextProp.UNDERLINE_IDX, underlined); - } - - /** - * Does the text have a shadow? - */ - public boolean isShadowed() { - return isCharFlagsTextPropVal(CharFlagsTextProp.SHADOW_IDX); - } - - /** - * Does the text have a shadow? - */ - public void setShadowed(boolean flag) { - setCharFlagsTextPropVal(CharFlagsTextProp.SHADOW_IDX, flag); - } - - /** - * Is this text embossed? - */ - public boolean isEmbossed() { - return isCharFlagsTextPropVal(CharFlagsTextProp.RELIEF_IDX); - } - - /** - * Is this text embossed? - */ - public void setEmbossed(boolean flag) { - setCharFlagsTextPropVal(CharFlagsTextProp.RELIEF_IDX, flag); - } - - @Override - public boolean isStrikethrough() { - return isCharFlagsTextPropVal(CharFlagsTextProp.STRIKETHROUGH_IDX); - } - - @Override - public void setStrikethrough(boolean flag) { - setCharFlagsTextPropVal(CharFlagsTextProp.STRIKETHROUGH_IDX, flag); - } - - /** - * Gets the subscript/superscript option - * - * @return the percentage of the font size. If the value is positive, it is superscript, otherwise it is subscript - */ - public int getSuperscript() { - TextProp tp = getTextParagraph().getPropVal(characterStyle, masterStyle, "superscript"); - return tp == null ? 0 : tp.getValue(); - } - - /** - * Sets the subscript/superscript option - * - * @param val the percentage of the font size. If the value is positive, it is superscript, otherwise it is subscript - */ - public void setSuperscript(int val) { - setCharTextPropVal("superscript", val); - } - - @Override - public Double getFontSize() { - TextProp tp = getTextParagraph().getPropVal(characterStyle, masterStyle, "font.size"); - return tp == null ? null : (double)tp.getValue(); - } - - - @Override - public void setFontSize(Double fontSize) { - Integer iFontSize = (fontSize == null) ? null : fontSize.intValue(); - setCharTextPropVal("font.size", iFontSize); - } - - /** - * Gets the font index - */ - public int getFontIndex() { - TextProp tp = getTextParagraph().getPropVal(characterStyle, masterStyle, "font.index"); - return tp == null ? -1 : tp.getValue(); - } - - /** - * Sets the font index - */ - public void setFontIndex(int idx) { - setCharTextPropVal("font.index", idx); - } - - @Override - public void setFontFamily(String fontFamily) { - HSLFSheet sheet = parentParagraph.getSheet(); - @SuppressWarnings("resource") - HSLFSlideShow slideShow = (sheet == null) ? null : sheet.getSlideShow(); - if (sheet == null || slideShow == null) { - //we can't set font since slideshow is not assigned yet - _fontFamily = fontFamily; - return; - } - // Get the index for this font (adding if needed) - Integer fontIdx = (fontFamily == null) ? null : slideShow.getFontCollection().addFont(fontFamily); - setCharTextPropVal("font.index", fontIdx); - } - - @Override - public String getFontFamily() { - HSLFSheet sheet = parentParagraph.getSheet(); - @SuppressWarnings("resource") - HSLFSlideShow slideShow = (sheet == null) ? null : sheet.getSlideShow(); - if (sheet == null || slideShow == null) { - return _fontFamily; - } - TextProp tp = getTextParagraph().getPropVal(characterStyle, masterStyle, "font.index,asian.font.index,ansi.font.index,symbol.font.index"); - if (tp == null) { return null; } - return slideShow.getFontCollection().getFontWithId(tp.getValue()); - } - - /** - * @return font color as PaintStyle - */ - @Override - public SolidPaint getFontColor() { - TextProp tp = getTextParagraph().getPropVal(characterStyle, masterStyle, "font.color"); - if (tp == null) { - return null; - } - Color color = HSLFTextParagraph.getColorFromColorIndexStruct(tp.getValue(), parentParagraph.getSheet()); - SolidPaint ps = DrawPaint.createSolidPaint(color); - return ps; - } - - /** - * Sets color of the text, as a int bgr. - * (PowerPoint stores as BlueGreenRed, not the more - * usual RedGreenBlue) - * @see java.awt.Color - */ - public void setFontColor(int bgr) { - setCharTextPropVal("font.color", bgr); - } - - - @Override - public void setFontColor(Color color) { - setFontColor(DrawPaint.createSolidPaint(color)); - } - - @Override - public void setFontColor(PaintStyle color) { - if (!(color instanceof SolidPaint)) { - throw new IllegalArgumentException("HSLF only supports solid paint"); - } - // In PowerPont RGB bytes are swapped, as BGR - SolidPaint sp = (SolidPaint)color; - Color c = DrawPaint.applyColorTransform(sp.getSolidColor()); - int rgb = new Color(c.getBlue(), c.getGreen(), c.getRed(), 254).getRGB(); - setFontColor(rgb); - } - - protected void setFlag(int index, boolean value) { - BitMaskTextProp prop = (BitMaskTextProp)characterStyle.addWithName(CharFlagsTextProp.NAME); - prop.setSubValue(value, index); - } - - public HSLFTextParagraph getTextParagraph() { - return parentParagraph; - } - - @Override - public TextCap getTextCap() { - return TextCap.NONE; - } - - @Override - public boolean isSubscript() { - return getSuperscript() < 0; - } - - @Override - public boolean isSuperscript() { - return getSuperscript() > 0; - } - - @Override - public byte getPitchAndFamily() { - return 0; - } - - /** - * Sets the hyperlink - used when parsing the document - * - * @param link the hyperlink - */ - protected void setHyperlink(HSLFHyperlink link) { - this.link = link; - } - - @Override - public HSLFHyperlink getHyperlink() { - return link; - } - - @Override - public HSLFHyperlink createHyperlink() { - if (link == null) { - link = HSLFHyperlink.createHyperlink(this); - parentParagraph.setDirty(); - } - return link; - } - - @Override - public FieldType getFieldType() { - HSLFTextShape ts = getTextParagraph().getParentShape(); - Placeholder ph = ts.getPlaceholder(); - - if (ph != null) { - switch (ph) { - case SLIDE_NUMBER: - return FieldType.SLIDE_NUMBER; - case DATETIME: - return FieldType.DATE_TIME; - default: - break; - } - } - - if (ts.getSheet() instanceof MasterSheet) { - TextShape> ms = ts.getMetroShape(); - if (ms == null || ms.getTextParagraphs().isEmpty()) { - return null; - } - List trList = ms.getTextParagraphs().get(0).getTextRuns(); - if (trList.isEmpty()) { - return null; - } - return trList.get(0).getFieldType(); - } - - return null; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFTextShape.java b/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFTextShape.java deleted file mode 100644 index d7b4e2773..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFTextShape.java +++ /dev/null @@ -1,934 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.usermodel; - -import static org.apache.poi.hslf.record.RecordTypes.OEPlaceholderAtom; -import static org.apache.poi.hslf.record.RecordTypes.RoundTripHFPlaceholder12; - -import java.awt.geom.Rectangle2D; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.apache.poi.ddf.AbstractEscherOptRecord; -import org.apache.poi.ddf.EscherContainerRecord; -import org.apache.poi.ddf.EscherProperties; -import org.apache.poi.ddf.EscherSimpleProperty; -import org.apache.poi.ddf.EscherTextboxRecord; -import org.apache.poi.hslf.exceptions.HSLFException; -import org.apache.poi.hslf.model.HSLFMetroShape; -import org.apache.poi.hslf.model.textproperties.TextPropCollection; -import org.apache.poi.hslf.record.EscherTextboxWrapper; -import org.apache.poi.hslf.record.OEPlaceholderAtom; -import org.apache.poi.hslf.record.PPDrawing; -import org.apache.poi.hslf.record.RoundTripHFPlaceholder12; -import org.apache.poi.hslf.record.StyleTextPropAtom; -import org.apache.poi.hslf.record.TextBytesAtom; -import org.apache.poi.hslf.record.TextCharsAtom; -import org.apache.poi.hslf.record.TextHeaderAtom; -import org.apache.poi.sl.draw.DrawFactory; -import org.apache.poi.sl.draw.DrawTextShape; -import org.apache.poi.sl.usermodel.Insets2D; -import org.apache.poi.sl.usermodel.Placeholder; -import org.apache.poi.sl.usermodel.ShapeContainer; -import org.apache.poi.sl.usermodel.TextParagraph; -import org.apache.poi.sl.usermodel.TextRun; -import org.apache.poi.sl.usermodel.TextShape; -import org.apache.poi.sl.usermodel.VerticalAlignment; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.util.Units; - -/** - * A common superclass of all shapes that can hold text. - */ -public abstract class HSLFTextShape extends HSLFSimpleShape -implements TextShape { - private static final POILogger LOG = POILogFactory.getLogger(HSLFTextShape.class); - - /** - * How to anchor the text - */ - private enum HSLFTextAnchor { - TOP (0, VerticalAlignment.TOP, false, false), - MIDDLE (1, VerticalAlignment.MIDDLE, false, false), - BOTTOM (2, VerticalAlignment.BOTTOM, false, false), - TOP_CENTER (3, VerticalAlignment.TOP, true, false), - MIDDLE_CENTER (4, VerticalAlignment.MIDDLE, true, false), - BOTTOM_CENTER (5, VerticalAlignment.BOTTOM, true, false), - TOP_BASELINE (6, VerticalAlignment.TOP, false, true), - BOTTOM_BASELINE (7, VerticalAlignment.BOTTOM, false, true), - TOP_CENTER_BASELINE (8, VerticalAlignment.TOP, true, true), - BOTTOM_CENTER_BASELINE(9, VerticalAlignment.BOTTOM, true, true); - - public final int nativeId; - public final VerticalAlignment vAlign; - public final boolean centered; - public final Boolean baseline; - - HSLFTextAnchor(int nativeId, VerticalAlignment vAlign, boolean centered, Boolean baseline) { - this.nativeId = nativeId; - this.vAlign = vAlign; - this.centered = centered; - this.baseline = baseline; - } - - static HSLFTextAnchor fromNativeId(int nativeId) { - for (HSLFTextAnchor ta : values()) { - if (ta.nativeId == nativeId) { - return ta; - } - } - return null; - } - } - - /** - * Specifies that a line of text will continue on subsequent lines instead - * of extending into or beyond a margin. - * Office Excel 2007, Excel 2010, PowerPoint 97, and PowerPoint 2010 read - * and use this value properly but do not write it. - */ - public static final int WrapSquare = 0; - /** - * Specifies a wrapping rule that is equivalent to that of WrapSquare - * Excel 97, Excel 2000, Excel 2002, and Office Excel 2003 use this value. - * All other product versions listed at the beginning of this appendix ignore this value. - */ - public static final int WrapByPoints = 1; - /** - * Specifies that a line of text will extend into or beyond a margin instead - * of continuing on subsequent lines. - * Excel 97, Word 97, Excel 2000, Word 2000, Excel 2002, - * and Office Excel 2003 do not use this value. - */ - public static final int WrapNone = 2; - /** - * Specifies a wrapping rule that is undefined and MUST be ignored. - */ - public static final int WrapTopBottom = 3; - /** - * Specifies a wrapping rule that is undefined and MUST be ignored. - */ - public static final int WrapThrough = 4; - - - /** - * TextRun object which holds actual text and format data - */ - private List _paragraphs = new ArrayList(); - - /** - * Escher container which holds text attributes such as - * TextHeaderAtom, TextBytesAtom or TextCharsAtom, StyleTextPropAtom etc. - */ - private EscherTextboxWrapper _txtbox; - - /** - * This setting is used for supporting a deprecated alignment - * - * @see - */ -// boolean alignToBaseline = false; - - /** - * Create a TextBox object and initialize it from the supplied Record container. - * - * @param escherRecord EscherSpContainer container which holds information about this shape - * @param parent the parent of the shape - */ - protected HSLFTextShape(EscherContainerRecord escherRecord, ShapeContainer parent){ - super(escherRecord, parent); - } - - /** - * Create a new TextBox. This constructor is used when a new shape is created. - * - * @param parent the parent of this Shape. For example, if this text box is a cell - * in a table then the parent is Table. - */ - public HSLFTextShape(ShapeContainer parent){ - super(null, parent); - createSpContainer(parent instanceof HSLFGroupShape); - } - - /** - * Create a new TextBox. This constructor is used when a new shape is created. - * - */ - public HSLFTextShape(){ - this(null); - } - - /** - * Set default properties for the TextRun. - * Depending on the text and shape type the defaults are different: - * TextBox: align=left, valign=top - * AutoShape: align=center, valign=middle - * - */ - protected void setDefaultTextProperties(HSLFTextParagraph _txtrun){ - - } - - /** - * When a textbox is added to a sheet we need to tell upper-level - * PPDrawing about it. - * - * @param sh the sheet we are adding to - */ - @Override - protected void afterInsert(HSLFSheet sh){ - super.afterInsert(sh); - - storeText(); - - EscherTextboxWrapper thisTxtbox = getEscherTextboxWrapper(); - if(thisTxtbox != null){ - getSpContainer().addChildRecord(thisTxtbox.getEscherRecord()); - - PPDrawing ppdrawing = sh.getPPDrawing(); - ppdrawing.addTextboxWrapper(thisTxtbox); - // Ensure the escher layer knows about the added records - try { - thisTxtbox.writeOut(null); - } catch (IOException e){ - throw new HSLFException(e); - } - boolean isInitialAnchor = getAnchor().equals(new Rectangle2D.Double()); - boolean isFilledTxt = !"".equals(getText()); - if (isInitialAnchor && isFilledTxt) { - resizeToFitText(); - } - } - for (HSLFTextParagraph htp : _paragraphs) { - htp.setShapeId(getShapeId()); - } - sh.onAddTextShape(this); - } - - protected EscherTextboxWrapper getEscherTextboxWrapper(){ - if(_txtbox != null) { - return _txtbox; - } - - EscherTextboxRecord textRecord = getEscherChild(EscherTextboxRecord.RECORD_ID); - if (textRecord == null) { - return null; - } - - HSLFSheet sheet = getSheet(); - if (sheet != null) { - PPDrawing drawing = sheet.getPPDrawing(); - if (drawing != null) { - EscherTextboxWrapper wrappers[] = drawing.getTextboxWrappers(); - if (wrappers != null) { - for (EscherTextboxWrapper w : wrappers) { - // check for object identity - if (textRecord == w.getEscherRecord()) { - _txtbox = w; - return _txtbox; - } - } - } - } - } - - _txtbox = new EscherTextboxWrapper(textRecord); - return _txtbox; - } - - private void createEmptyParagraph() { - TextHeaderAtom tha = (TextHeaderAtom)_txtbox.findFirstOfType(TextHeaderAtom._type); - if (tha == null) { - tha = new TextHeaderAtom(); - tha.setParentRecord(_txtbox); - _txtbox.appendChildRecord(tha); - } - - TextBytesAtom tba = (TextBytesAtom)_txtbox.findFirstOfType(TextBytesAtom._type); - TextCharsAtom tca = (TextCharsAtom)_txtbox.findFirstOfType(TextCharsAtom._type); - if (tba == null && tca == null) { - tba = new TextBytesAtom(); - tba.setText(new byte[0]); - _txtbox.appendChildRecord(tba); - } - - final String text = ((tba != null) ? tba.getText() : tca.getText()); - - StyleTextPropAtom sta = (StyleTextPropAtom)_txtbox.findFirstOfType(StyleTextPropAtom._type); - TextPropCollection paraStyle = null, charStyle = null; - if (sta == null) { - int parSiz = text.length(); - sta = new StyleTextPropAtom(parSiz+1); - if (_paragraphs.isEmpty()) { - paraStyle = sta.addParagraphTextPropCollection(parSiz+1); - charStyle = sta.addCharacterTextPropCollection(parSiz+1); - } else { - for (HSLFTextParagraph htp : _paragraphs) { - int runsLen = 0; - for (HSLFTextRun htr : htp.getTextRuns()) { - runsLen += htr.getLength(); - charStyle = sta.addCharacterTextPropCollection(htr.getLength()); - htr.setCharacterStyle(charStyle); - } - paraStyle = sta.addParagraphTextPropCollection(runsLen); - htp.setParagraphStyle(paraStyle); - } - assert (paraStyle != null && charStyle != null); - } - _txtbox.appendChildRecord(sta); - } else { - paraStyle = sta.getParagraphStyles().get(0); - charStyle = sta.getCharacterStyles().get(0); - } - - if (_paragraphs.isEmpty()) { - HSLFTextParagraph htp = new HSLFTextParagraph(tha, tba, tca, _paragraphs); - htp.setParagraphStyle(paraStyle); - htp.setParentShape(this); - _paragraphs.add(htp); - - HSLFTextRun htr = new HSLFTextRun(htp); - htr.setCharacterStyle(charStyle); - htr.setText(text); - htp.addTextRun(htr); - } - } - - - - /** - * Adjust the size of the shape so it encompasses the text inside it. - * - * @return a Rectangle2D that is the bounds of this shape. - */ - public Rectangle2D resizeToFitText(){ - Rectangle2D anchor = getAnchor(); - if(anchor.getWidth() == 0.) { - LOG.log(POILogger.WARN, "Width of shape wasn't set. Defaulting to 200px"); - anchor.setRect(anchor.getX(), anchor.getY(), 200., anchor.getHeight()); - setAnchor(anchor); - } - double height = getTextHeight(); - height += 1; // add a pixel to compensate rounding errors - - anchor.setRect(anchor.getX(), anchor.getY(), anchor.getWidth(), height); - setAnchor(anchor); - - return anchor; - } - - /** - * Returns the type of the text, from the TextHeaderAtom. - * Possible values can be seen from TextHeaderAtom - * @see org.apache.poi.hslf.record.TextHeaderAtom - */ - public int getRunType() { - getEscherTextboxWrapper(); - if (_txtbox == null) { - return -1; - } - List paras = HSLFTextParagraph.findTextParagraphs(_txtbox, getSheet()); - return (paras.isEmpty()) ? -1 : paras.get(0).getRunType(); - } - - /** - * Changes the type of the text. Values should be taken - * from TextHeaderAtom. No checking is done to ensure you - * set this to a valid value! - * @see org.apache.poi.hslf.record.TextHeaderAtom - */ - public void setRunType(int type) { - getEscherTextboxWrapper(); - if (_txtbox == null) { - return; - } - List paras = HSLFTextParagraph.findTextParagraphs(_txtbox, getSheet()); - if (!paras.isEmpty()) { - paras.get(0).setRunType(type); - } - } - - /** - * Returns the type of vertical alignment for the text. - * One of the Anchor* constants defined in this class. - * - * @return the type of alignment - */ - /* package */ HSLFTextAnchor getAlignment(){ - AbstractEscherOptRecord opt = getEscherOptRecord(); - EscherSimpleProperty prop = getEscherProperty(opt, EscherProperties.TEXT__ANCHORTEXT); - HSLFTextAnchor align = HSLFTextAnchor.TOP; - if (prop == null){ - /** - * If vertical alignment was not found in the shape properties then try to - * fetch the master shape and search for the align property there. - */ - int type = getRunType(); - HSLFSheet sh = getSheet(); - HSLFMasterSheet master = (sh != null) ? sh.getMasterSheet() : null; - HSLFTextShape masterShape = (master != null) ? master.getPlaceholderByTextType(type) : null; - if (masterShape != null && type != TextHeaderAtom.OTHER_TYPE) { - align = masterShape.getAlignment(); - } else { - //not found in the master sheet. Use the hardcoded defaults. - switch (type){ - case TextHeaderAtom.TITLE_TYPE: - case TextHeaderAtom.CENTER_TITLE_TYPE: - align = HSLFTextAnchor.MIDDLE; - break; - default: - align = HSLFTextAnchor.TOP; - break; - } - } - } else { - align = HSLFTextAnchor.fromNativeId(prop.getPropertyValue()); - } - - if (align == null) { - align = HSLFTextAnchor.TOP; - } - - return align; - } - - /** - * Sets the type of alignment for the text. - * One of the Anchor* constants defined in this class. - * - * @param isCentered horizontal centered? - * @param vAlign vertical alignment - * @param baseline aligned to baseline? - */ - /* package */ void setAlignment(Boolean isCentered, VerticalAlignment vAlign, boolean baseline) { - for (HSLFTextAnchor hta : HSLFTextAnchor.values()) { - if ( - (hta.centered == (isCentered != null && isCentered)) && - (hta.vAlign == vAlign) && - (hta.baseline == null || hta.baseline == baseline) - ) { - setEscherProperty(EscherProperties.TEXT__ANCHORTEXT, hta.nativeId); - break; - } - } - } - - /** - * @return true, if vertical alignment is relative to baseline - * this is only used for older versions less equals Office 2003 - */ - public boolean isAlignToBaseline() { - return getAlignment().baseline; - } - - /** - * Sets the vertical alignment relative to the baseline - * - * @param alignToBaseline if true, vertical alignment is relative to baseline - */ - public void setAlignToBaseline(boolean alignToBaseline) { - setAlignment(isHorizontalCentered(), getVerticalAlignment(), alignToBaseline); - } - - @Override - public boolean isHorizontalCentered() { - return getAlignment().centered; - } - - @Override - public void setHorizontalCentered(Boolean isCentered) { - setAlignment(isCentered, getVerticalAlignment(), getAlignment().baseline); - } - - @Override - public VerticalAlignment getVerticalAlignment() { - return getAlignment().vAlign; - } - - @Override - public void setVerticalAlignment(VerticalAlignment vAlign) { - setAlignment(isHorizontalCentered(), vAlign, getAlignment().baseline); - } - - /** - * Returns the distance (in points) between the bottom of the text frame - * and the bottom of the inscribed rectangle of the shape that contains the text. - * Default value is 1/20 inch. - * - * @return the botom margin - */ - public double getBottomInset(){ - return getInset(EscherProperties.TEXT__TEXTBOTTOM, .05); - } - - /** - * Sets the botom margin. - * @see #getBottomInset() - * - * @param margin the bottom margin - */ - public void setBottomInset(double margin){ - setInset(EscherProperties.TEXT__TEXTBOTTOM, margin); - } - - /** - * Returns the distance (in points) between the left edge of the text frame - * and the left edge of the inscribed rectangle of the shape that contains - * the text. - * Default value is 1/10 inch. - * - * @return the left margin - */ - public double getLeftInset(){ - return getInset(EscherProperties.TEXT__TEXTLEFT, .1); - } - - /** - * Sets the left margin. - * @see #getLeftInset() - * - * @param margin the left margin - */ - public void setLeftInset(double margin){ - setInset(EscherProperties.TEXT__TEXTLEFT, margin); - } - - /** - * Returns the distance (in points) between the right edge of the - * text frame and the right edge of the inscribed rectangle of the shape - * that contains the text. - * Default value is 1/10 inch. - * - * @return the right margin - */ - public double getRightInset(){ - return getInset(EscherProperties.TEXT__TEXTRIGHT, .1); - } - - /** - * Sets the right margin. - * @see #getRightInset() - * - * @param margin the right margin - */ - public void setRightInset(double margin){ - setInset(EscherProperties.TEXT__TEXTRIGHT, margin); - } - - /** - * Returns the distance (in points) between the top of the text frame - * and the top of the inscribed rectangle of the shape that contains the text. - * Default value is 1/20 inch. - * - * @return the top margin - */ - public double getTopInset(){ - return getInset(EscherProperties.TEXT__TEXTTOP, .05); - } - - /** - * Sets the top margin. - * @see #getTopInset() - * - * @param margin the top margin - */ - public void setTopInset(double margin){ - setInset(EscherProperties.TEXT__TEXTTOP, margin); - } - - /** - * Returns the distance (in points) between the edge of the text frame - * and the edge of the inscribed rectangle of the shape that contains the text. - * Default value is 1/20 inch. - * - * @param propId the id of the inset edge - * @return the inset in points - */ - private double getInset(short propId, double defaultInch) { - AbstractEscherOptRecord opt = getEscherOptRecord(); - EscherSimpleProperty prop = getEscherProperty(opt, propId); - int val = prop == null ? (int)(Units.toEMU(Units.POINT_DPI)*defaultInch) : prop.getPropertyValue(); - return Units.toPoints(val); - } - - /** - * @param propId the id of the inset edge - * @param margin the inset in points - */ - private void setInset(short propId, double margin){ - setEscherProperty(propId, Units.toEMU(margin)); - } - - /** - * Returns the value indicating word wrap. - * - * @return the value indicating word wrap. - * Must be one of the Wrap* constants defined in this class. - * - * @see MSOWRAPMODE - */ - public int getWordWrapEx() { - AbstractEscherOptRecord opt = getEscherOptRecord(); - EscherSimpleProperty prop = getEscherProperty(opt, EscherProperties.TEXT__WRAPTEXT); - return prop == null ? WrapSquare : prop.getPropertyValue(); - } - - /** - * Specifies how the text should be wrapped - * - * @param wrap the value indicating how the text should be wrapped. - * Must be one of the Wrap* constants defined in this class. - */ - public void setWordWrapEx(int wrap){ - setEscherProperty(EscherProperties.TEXT__WRAPTEXT, wrap); - } - - @Override - public boolean getWordWrap(){ - int ww = getWordWrapEx(); - return (ww != WrapNone); - } - - @Override - public void setWordWrap(boolean wrap) { - setWordWrapEx(wrap ? WrapSquare : WrapNone); - } - - /** - * @return id for the text. - */ - public int getTextId(){ - AbstractEscherOptRecord opt = getEscherOptRecord(); - EscherSimpleProperty prop = getEscherProperty(opt, EscherProperties.TEXT__TEXTID); - return prop == null ? 0 : prop.getPropertyValue(); - } - - /** - * Sets text ID - * - * @param id of the text - */ - public void setTextId(int id){ - setEscherProperty(EscherProperties.TEXT__TEXTID, id); - } - - @Override - public List getTextParagraphs(){ - if (!_paragraphs.isEmpty()) { - return _paragraphs; - } - - _txtbox = getEscherTextboxWrapper(); - if (_txtbox == null) { - _txtbox = new EscherTextboxWrapper(); - createEmptyParagraph(); - } else { - List pList = HSLFTextParagraph.findTextParagraphs(_txtbox, getSheet()); - if (pList == null) { - // there are actually TextBoxRecords without extra data - see #54722 - createEmptyParagraph(); - } else { - _paragraphs = pList; - } - - if (_paragraphs.isEmpty()) { - LOG.log(POILogger.WARN, "TextRecord didn't contained any text lines"); - } - } - - for (HSLFTextParagraph p : _paragraphs) { - p.setParentShape(this); - } - - return _paragraphs; - } - - - @Override - public void setSheet(HSLFSheet sheet) { - super.setSheet(sheet); - - // Initialize _txtrun object. - // (We can't do it in the constructor because the sheet - // is not assigned then, it's only built once we have - // all the records) - List ltp = getTextParagraphs(); - HSLFTextParagraph.supplySheet(ltp, sheet); - } - - /** - * Return {@link OEPlaceholderAtom}, the atom that describes a placeholder. - * - * @return {@link OEPlaceholderAtom} or {@code null} if not found - */ - public OEPlaceholderAtom getPlaceholderAtom(){ - return getClientDataRecord(OEPlaceholderAtom.typeID); - } - - /** - * Return {@link RoundTripHFPlaceholder12}, the atom that describes a header/footer placeholder. - * Compare the {@link RoundTripHFPlaceholder12#getPlaceholderId()} with - * {@link Placeholder#HEADER} or {@link Placeholder#FOOTER}, to find out - * what kind of placeholder this is. - * - * @return {@link RoundTripHFPlaceholder12} or {@code null} if not found - * - * @since POI 3.14-Beta2 - */ - public RoundTripHFPlaceholder12 getHFPlaceholderAtom() { - // special case for files saved in Office 2007 - return getClientDataRecord(RoundTripHFPlaceholder12.typeID); - } - - @Override - public boolean isPlaceholder() { - OEPlaceholderAtom oep = getPlaceholderAtom(); - if (oep != null) { - return true; - } - - //special case for files saved in Office 2007 - RoundTripHFPlaceholder12 hldr = getHFPlaceholderAtom(); - if (hldr != null) { - return true; - } - - return false; - } - - - @Override - public Iterator iterator() { - return _paragraphs.iterator(); - } - - @Override - public Insets2D getInsets() { - Insets2D insets = new Insets2D(getTopInset(), getLeftInset(), getBottomInset(), getRightInset()); - return insets; - } - - @Override - public void setInsets(Insets2D insets) { - setTopInset(insets.top); - setLeftInset(insets.left); - setBottomInset(insets.bottom); - setRightInset(insets.right); - } - - @Override - public double getTextHeight(){ - DrawFactory drawFact = DrawFactory.getInstance(null); - DrawTextShape dts = drawFact.getDrawable(this); - return dts.getTextHeight(); - } - - @Override - public TextDirection getTextDirection() { - // see 2.4.5 MSOTXFL - AbstractEscherOptRecord opt = getEscherOptRecord(); - EscherSimpleProperty prop = getEscherProperty(opt, EscherProperties.TEXT__TEXTFLOW); - int msotxfl = (prop == null) ? 0 : prop.getPropertyValue(); - switch (msotxfl) { - default: - case 0: // msotxflHorzN - case 4: // msotxflHorzA - return TextDirection.HORIZONTAL; - case 1: // msotxflTtoBA - case 3: // msotxflTtoBN - case 5: // msotxflVertN - return TextDirection.VERTICAL; - case 2: // msotxflBtoT - return TextDirection.VERTICAL_270; - // TextDirection.STACKED is not supported - } - } - - @Override - public void setTextDirection(TextDirection orientation) { - AbstractEscherOptRecord opt = getEscherOptRecord(); - int msotxfl; - if (orientation == null) { - msotxfl = -1; - } else { - switch (orientation) { - default: - case STACKED: - // not supported -> remove - msotxfl = -1; - break; - case HORIZONTAL: - msotxfl = 0; - break; - case VERTICAL: - msotxfl = 1; - break; - case VERTICAL_270: - // always interpreted as horizontal - msotxfl = 2; - break; - } - } - setEscherProperty(opt, EscherProperties.TEXT__TEXTFLOW, msotxfl); - } - - @Override - public Double getTextRotation() { - // see 2.4.6 MSOCDIR - AbstractEscherOptRecord opt = getEscherOptRecord(); - EscherSimpleProperty prop = getEscherProperty(opt, EscherProperties.TEXT__FONTROTATION); - return (prop == null) ? null : (90. * prop.getPropertyValue()); - } - - @Override - public void setTextRotation(Double rotation) { - AbstractEscherOptRecord opt = getEscherOptRecord(); - if (rotation == null) { - opt.removeEscherProperty(EscherProperties.TEXT__FONTROTATION); - } else { - int rot = (int)(Math.round(rotation / 90.) % 4L); - setEscherProperty(EscherProperties.TEXT__FONTROTATION, rot); - } - } - - /** - * Returns the raw text content of the shape. This hasn't had any - * changes applied to it, and so is probably unlikely to print - * out nicely. - */ - public String getRawText() { - return HSLFTextParagraph.getRawText(getTextParagraphs()); - } - - @Override - public String getText() { - String rawText = getRawText(); - return HSLFTextParagraph.toExternalString(rawText, getRunType()); - } - - @Override - public HSLFTextRun appendText(String text, boolean newParagraph) { - // init paragraphs - List paras = getTextParagraphs(); - HSLFTextRun htr = HSLFTextParagraph.appendText(paras, text, newParagraph); - setTextId(getRawText().hashCode()); - return htr; - } - - @Override - public HSLFTextRun setText(String text) { - // init paragraphs - List paras = getTextParagraphs(); - HSLFTextRun htr = HSLFTextParagraph.setText(paras, text); - setTextId(getRawText().hashCode()); - return htr; - } - - /** - * Saves the modified paragraphs/textrun to the records. - * Also updates the styles to the correct text length. - */ - protected void storeText() { - List paras = getTextParagraphs(); - HSLFTextParagraph.storeText(paras); - } - - /** - * Returns the array of all hyperlinks in this text run - * - * @return the array of all hyperlinks in this text run or null - * if not found. - */ - public List getHyperlinks() { - return HSLFHyperlink.find(this); - } - - @Override - public void setTextPlaceholder(TextPlaceholder placeholder) { - // TOOD: check for correct placeholder handling - see org.apache.poi.hslf.model.Placeholder - Placeholder ph = null; - int runType; - switch (placeholder) { - default: - case BODY: - runType = TextHeaderAtom.BODY_TYPE; - ph = Placeholder.BODY; - break; - case TITLE: - runType = TextHeaderAtom.TITLE_TYPE; - ph = Placeholder.TITLE; - break; - case CENTER_BODY: - runType = TextHeaderAtom.CENTRE_BODY_TYPE; - ph = Placeholder.BODY; - break; - case CENTER_TITLE: - runType = TextHeaderAtom.CENTER_TITLE_TYPE; - ph = Placeholder.TITLE; - break; - case HALF_BODY: - runType = TextHeaderAtom.HALF_BODY_TYPE; - ph = Placeholder.BODY; - break; - case QUARTER_BODY: - runType = TextHeaderAtom.QUARTER_BODY_TYPE; - ph = Placeholder.BODY; - break; - case NOTES: - runType = TextHeaderAtom.NOTES_TYPE; - break; - case OTHER: - runType = TextHeaderAtom.OTHER_TYPE; - break; - } - setRunType(runType); - if (ph != null) { - setPlaceholder(ph); - } - } - - @Override - public TextPlaceholder getTextPlaceholder() { - switch (getRunType()) { - default: - case TextHeaderAtom.BODY_TYPE: return TextPlaceholder.BODY; - case TextHeaderAtom.TITLE_TYPE: return TextPlaceholder.TITLE; - case TextHeaderAtom.NOTES_TYPE: return TextPlaceholder.NOTES; - case TextHeaderAtom.OTHER_TYPE: return TextPlaceholder.OTHER; - case TextHeaderAtom.CENTRE_BODY_TYPE: return TextPlaceholder.CENTER_BODY; - case TextHeaderAtom.CENTER_TITLE_TYPE: return TextPlaceholder.CENTER_TITLE; - case TextHeaderAtom.HALF_BODY_TYPE: return TextPlaceholder.HALF_BODY; - case TextHeaderAtom.QUARTER_BODY_TYPE: return TextPlaceholder.QUARTER_BODY; - } - } - - - /** - * Get alternative representation of text shape stored as metro blob escher property. - * The returned shape is the first shape in stored group shape of the metro blob - * - * @return null, if there's no alternative representation, otherwise the text shape - */ - public TextShape> getMetroShape() { - HSLFMetroShape>> mbs = new HSLFMetroShape>>(this); - return mbs.getShape(); - } -} \ No newline at end of file diff --git a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFTitleMaster.java b/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFTitleMaster.java deleted file mode 100644 index 2dfd3b05b..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/usermodel/HSLFTitleMaster.java +++ /dev/null @@ -1,77 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.usermodel; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.hslf.model.textproperties.TextProp; -import org.apache.poi.hslf.record.SlideAtom; - -/** - * Title masters define the design template for slides with a Title Slide layout. - */ -public final class HSLFTitleMaster extends HSLFMasterSheet { - private final List> _paragraphs = new ArrayList>(); - - /** - * Constructs a TitleMaster - * - */ - public HSLFTitleMaster(org.apache.poi.hslf.record.Slide record, int sheetNo) { - super(record, sheetNo); - - for (List l : HSLFTextParagraph.findTextParagraphs(getPPDrawing(), this)) { - if (!_paragraphs.contains(l)) { - _paragraphs.add(l); - } - } - } - - /** - * Returns an array of all the TextRuns found - */ - @Override - public List> getTextParagraphs() { - return _paragraphs; - } - - /** - * Delegate the call to the underlying slide master. - */ - @Override - public TextProp getStyleAttribute(int txtype, int level, String name, boolean isCharacter) { - HSLFMasterSheet master = getMasterSheet(); - return (master == null) ? null : master.getStyleAttribute(txtype, level, name, isCharacter); - } - - /** - * Returns the slide master for this title master. - */ - @Override - public HSLFMasterSheet getMasterSheet(){ - SlideAtom sa = ((org.apache.poi.hslf.record.Slide)getSheetContainer()).getSlideAtom(); - int masterId = sa.getMasterID(); - for (HSLFSlideMaster sm : getSlideShow().getSlideMasters()) { - if (masterId == sm._getSheetNumber()) { - return sm; - } - } - return null; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/util/MutableByteArrayOutputStream.java b/src/scratchpad/src/org/apache/poi/hslf/util/MutableByteArrayOutputStream.java deleted file mode 100644 index be7c04602..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/util/MutableByteArrayOutputStream.java +++ /dev/null @@ -1,41 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.util; - -import java.io.ByteArrayOutputStream; - -/** - * This class doesn't work yet, but is here to show the idea of a - * ByteArrayOutputStream where you can track how many bytes you've - * already written, and go back and write over a previous part of the stream - * - * @author Nick Burch - */ - -public final class MutableByteArrayOutputStream extends ByteArrayOutputStream -{ - /** Return how many bytes we've stuffed in so far */ - public int getBytesWritten() { return -1; } - - /** Write some bytes to the array */ - public void write(byte[] b) {} - public void write(int b) {} - - /** Write some bytes to an earlier bit of the array */ - public void overwrite(byte[] b, int startPos) {} -} diff --git a/src/scratchpad/src/org/apache/poi/hslf/util/SystemTimeUtils.java b/src/scratchpad/src/org/apache/poi/hslf/util/SystemTimeUtils.java deleted file mode 100644 index 10b566a8b..000000000 --- a/src/scratchpad/src/org/apache/poi/hslf/util/SystemTimeUtils.java +++ /dev/null @@ -1,86 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.util; - -import java.util.Calendar; -import java.util.Date; - -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.LocaleUtil; - -/** - * A helper class for dealing with SystemTime Structs, as defined at - * http://msdn.microsoft.com/library/en-us/sysinfo/base/systemtime_str.asp . - * - * Discrepancies between Calendar and SYSTEMTIME: - * - that January = 1 in SYSTEMTIME, 0 in Calendar. - * - that the day of the week (0) starts on Sunday in SYSTEMTIME, and Monday in Calendar - * It is also the case that this does not store the timezone, and no... it is not - * stored as UTC either, but rather the local system time (yuck.) - */ -public final class SystemTimeUtils { - /** - * Get the date found in the byte array, as a java Data object - */ - public static Date getDate(byte[] data) { - return getDate(data,0); - } - /** - * Get the date found in the byte array, as a java Data object - */ - public static Date getDate(byte[] data, int offset) { - Calendar cal = LocaleUtil.getLocaleCalendar(); - - cal.set(Calendar.YEAR, LittleEndian.getShort(data,offset)); - cal.set(Calendar.MONTH, LittleEndian.getShort(data,offset+2)-1); - // Not actually needed - can be found from day of month - //cal.set(Calendar.DAY_OF_WEEK, LittleEndian.getShort(data,offset+4)+1); - cal.set(Calendar.DAY_OF_MONTH, LittleEndian.getShort(data,offset+6)); - cal.set(Calendar.HOUR_OF_DAY, LittleEndian.getShort(data,offset+8)); - cal.set(Calendar.MINUTE, LittleEndian.getShort(data,offset+10)); - cal.set(Calendar.SECOND, LittleEndian.getShort(data,offset+12)); - cal.set(Calendar.MILLISECOND, LittleEndian.getShort(data,offset+14)); - - return cal.getTime(); - } - - /** - * Convert the supplied java Date into a SystemTime struct, and write it - * into the supplied byte array. - */ - public static void storeDate(Date date, byte[] dest) { - storeDate(date, dest, 0); - } - /** - * Convert the supplied java Date into a SystemTime struct, and write it - * into the supplied byte array. - */ - public static void storeDate(Date date, byte[] dest, int offset) { - Calendar cal = LocaleUtil.getLocaleCalendar(); - cal.setTime(date); - - LittleEndian.putShort(dest, offset + 0, (short) cal.get(Calendar.YEAR)); - LittleEndian.putShort(dest, offset + 2, (short)(cal.get(Calendar.MONTH) + 1)); - LittleEndian.putShort(dest, offset + 4, (short)(cal.get(Calendar.DAY_OF_WEEK)-1)); - LittleEndian.putShort(dest, offset + 6, (short) cal.get(Calendar.DAY_OF_MONTH)); - LittleEndian.putShort(dest, offset + 8, (short) cal.get(Calendar.HOUR_OF_DAY)); - LittleEndian.putShort(dest, offset + 10,(short) cal.get(Calendar.MINUTE)); - LittleEndian.putShort(dest, offset + 12,(short) cal.get(Calendar.SECOND)); - LittleEndian.putShort(dest, offset + 14,(short) cal.get(Calendar.MILLISECOND)); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hsmf/MAPIMessage.java b/src/scratchpad/src/org/apache/poi/hsmf/MAPIMessage.java deleted file mode 100644 index e770a40a3..000000000 --- a/src/scratchpad/src/org/apache/poi/hsmf/MAPIMessage.java +++ /dev/null @@ -1,677 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hsmf; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.UnsupportedEncodingException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Calendar; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.poi.POIReadOnlyDocument; -import org.apache.poi.hmef.attribute.MAPIRtfAttribute; -import org.apache.poi.hsmf.datatypes.AttachmentChunks; -import org.apache.poi.hsmf.datatypes.AttachmentChunks.AttachmentChunksSorter; -import org.apache.poi.hsmf.datatypes.ByteChunk; -import org.apache.poi.hsmf.datatypes.Chunk; -import org.apache.poi.hsmf.datatypes.ChunkGroup; -import org.apache.poi.hsmf.datatypes.Chunks; -import org.apache.poi.hsmf.datatypes.MAPIProperty; -import org.apache.poi.hsmf.datatypes.NameIdChunks; -import org.apache.poi.hsmf.datatypes.PropertyValue; -import org.apache.poi.hsmf.datatypes.PropertyValue.LongPropertyValue; -import org.apache.poi.hsmf.datatypes.PropertyValue.TimePropertyValue; -import org.apache.poi.hsmf.datatypes.RecipientChunks; -import org.apache.poi.hsmf.datatypes.RecipientChunks.RecipientChunksSorter; -import org.apache.poi.hsmf.datatypes.StringChunk; -import org.apache.poi.hsmf.datatypes.Types; -import org.apache.poi.hsmf.exceptions.ChunkNotFoundException; -import org.apache.poi.hsmf.parsers.POIFSChunkParser; -import org.apache.poi.poifs.filesystem.DirectoryNode; -import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; -import org.apache.poi.util.CodePageUtil; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.util.Removal; - -/** - * Reads an Outlook MSG File in and provides hooks into its data structure. - * - * If you want to develop with HSMF, you might find it worth getting - * some of the Microsoft public documentation, such as: - * - * [MS-OXCMSG]: Message and Attachment Object Protocol Specification - */ -public class MAPIMessage extends POIReadOnlyDocument { - - /** - * A MAPI file can be an email (NOTE) or a number of other types - */ - public enum MESSAGE_CLASS { - APPOINTMENT, - CONTACT, - NOTE, - POST, - STICKY_NOTE, - TASK, - UNKNOWN, - UNSPECIFIED - } - - /** For logging problems we spot with the file */ - private POILogger logger = POILogFactory.getLogger(MAPIMessage.class); - - private Chunks mainChunks; - private NameIdChunks nameIdChunks; - private RecipientChunks[] recipientChunks; - private AttachmentChunks[] attachmentChunks; - - private boolean returnNullOnMissingChunk = false; - - /** - * Constructor for creating new files. - */ - public MAPIMessage() { - // TODO - make writing possible - super(new NPOIFSFileSystem()); - } - - - /** - * Constructor for reading MSG Files from the file system. - * - * @param filename Name of the file to read - * @throws IOException - */ - public MAPIMessage(String filename) throws IOException { - this(new File(filename)); - } - /** - * Constructor for reading MSG Files from the file system. - * - * @param file The file to read from - * @throws IOException - */ - public MAPIMessage(File file) throws IOException { - this(new NPOIFSFileSystem(file)); - } - - /** - * Constructor for reading MSG Files from an input stream. - * - *

    Note - this will buffer the whole message into memory - * in order to process. For lower memory use, use {@link #MAPIMessage(File)} - * - * @param in The InputStream to buffer then read from - * @throws IOException - */ - public MAPIMessage(InputStream in) throws IOException { - this(new NPOIFSFileSystem(in)); - } - /** - * Constructor for reading MSG Files from a POIFS filesystem - * - * @param fs Open POIFS FileSystem containing the message - * @throws IOException - */ - public MAPIMessage(NPOIFSFileSystem fs) throws IOException { - this(fs.getRoot()); - } - /** - * Constructor for reading MSG Files from a certain - * point within a POIFS filesystem - * @param poifsDir Directory containing the message - * @throws IOException - */ - public MAPIMessage(DirectoryNode poifsDir) throws IOException { - super(poifsDir); - - // Grab all the chunks - ChunkGroup[] chunkGroups = POIFSChunkParser.parse(poifsDir); - - // Grab interesting bits - ArrayList attachments = new ArrayList(); - ArrayList recipients = new ArrayList(); - for(ChunkGroup group : chunkGroups) { - // Should only ever be one of each of these - if(group instanceof Chunks) { - mainChunks = (Chunks)group; - } else if(group instanceof NameIdChunks) { - nameIdChunks = (NameIdChunks)group; - } else if(group instanceof RecipientChunks) { - recipients.add( (RecipientChunks)group ); - } - - // Can be multiple of these - add to list(s) - if(group instanceof AttachmentChunks) { - attachments.add( (AttachmentChunks)group ); - } - } - attachmentChunks = attachments.toArray(new AttachmentChunks[attachments.size()]); - recipientChunks = recipients.toArray(new RecipientChunks[recipients.size()]); - - // Now sort these chunks lists so they're in ascending order, - // rather than in random filesystem order - Arrays.sort(attachmentChunks, new AttachmentChunksSorter()); - Arrays.sort(recipientChunks, new RecipientChunksSorter()); - } - - - /** - * Gets a string value based on the passed chunk. - * @throws ChunkNotFoundException if the chunk isn't there - */ - public String getStringFromChunk(StringChunk chunk) throws ChunkNotFoundException { - if(chunk == null) { - if(returnNullOnMissingChunk) { - return null; - } else { - throw new ChunkNotFoundException(); - } - } - return chunk.getValue(); - } - - - /** - * Gets the plain text body of this Outlook Message - * @return The string representation of the 'text' version of the body, if available. - * @throws ChunkNotFoundException - */ - public String getTextBody() throws ChunkNotFoundException { - return getStringFromChunk(mainChunks.getTextBodyChunk()); - } - - /** - * Gets the html body of this Outlook Message, if this email - * contains a html version. - * @return The string representation of the 'html' version of the body, if available. - * @throws ChunkNotFoundException - */ - public String getHtmlBody() throws ChunkNotFoundException { - if(mainChunks.getHtmlBodyChunkBinary() != null) { - return mainChunks.getHtmlBodyChunkBinary().getAs7bitString(); - } - return getStringFromChunk(mainChunks.getHtmlBodyChunkString()); - } - - /** - * Gets the RTF Rich Message body of this Outlook Message, if this email - * contains a RTF (rich) version. - * @return The string representation of the 'RTF' version of the body, if available. - * @throws ChunkNotFoundException - */ - public String getRtfBody() throws ChunkNotFoundException { - ByteChunk chunk = mainChunks.getRtfBodyChunk(); - if(chunk == null) { - if(returnNullOnMissingChunk) { - return null; - } else { - throw new ChunkNotFoundException(); - } - } - - try { - MAPIRtfAttribute rtf = new MAPIRtfAttribute( - MAPIProperty.RTF_COMPRESSED, Types.BINARY.getId(), chunk.getValue() - ); - return rtf.getDataString(); - } catch(IOException e) { - throw new RuntimeException("Shouldn't happen", e); - } - } - - /** - * Gets the subject line of the Outlook Message - * @throws ChunkNotFoundException - */ - public String getSubject() throws ChunkNotFoundException { - return getStringFromChunk(mainChunks.getSubjectChunk()); - } - - /** - * Gets the display value of the "FROM" line of the outlook message - * This is not the actual address that was sent from but the formated display of the user name. - * @throws ChunkNotFoundException - */ - public String getDisplayFrom() throws ChunkNotFoundException { - return getStringFromChunk(mainChunks.getDisplayFromChunk()); - } - - /** - * Gets the display value of the "TO" line of the outlook message. - * If there are multiple recipients, they will be separated - * by semicolons. - * This is not the actual list of addresses/values that will be - * sent to if you click Reply in the email - those are stored - * in {@link RecipientChunks}. - * @throws ChunkNotFoundException - */ - public String getDisplayTo() throws ChunkNotFoundException { - return getStringFromChunk(mainChunks.getDisplayToChunk()); - } - - /** - * Gets the display value of the "CC" line of the outlook message. - * If there are multiple recipients, they will be separated - * by semicolons. - * This is not the actual list of addresses/values that will be - * sent to if you click Reply in the email - those are stored - * in {@link RecipientChunks}. - * @throws ChunkNotFoundException - */ - public String getDisplayCC() throws ChunkNotFoundException { - return getStringFromChunk(mainChunks.getDisplayCCChunk()); - } - - /** - * Gets the display value of the "BCC" line of the outlook message. - * If there are multiple recipients, they will be separated - * by semicolons. - * This is not the actual list of addresses/values that will be - * sent to if you click Reply in the email - those are stored - * in {@link RecipientChunks}. - * This will only be present in sent emails, not received ones! - * @throws ChunkNotFoundException - */ - public String getDisplayBCC() throws ChunkNotFoundException { - return getStringFromChunk(mainChunks.getDisplayBCCChunk()); - } - - /** - * Returns all the recipients' email address, separated by - * semicolons. Checks all the likely chunks in search of - * the addresses. - */ - public String getRecipientEmailAddress() throws ChunkNotFoundException { - return toSemicolonList(getRecipientEmailAddressList()); - } - /** - * Returns an array of all the recipient's email address, normally - * in TO then CC then BCC order. - * Checks all the likely chunks in search of the addresses. - */ - public String[] getRecipientEmailAddressList() throws ChunkNotFoundException { - if(recipientChunks == null || recipientChunks.length == 0) { - throw new ChunkNotFoundException("No recipients section present"); - } - - String[] emails = new String[recipientChunks.length]; - for(int i=0; iMany messages store their strings as unicode, which is - * nice and easy. Some use one-byte encodings for their - * strings, but don't always store the encoding anywhere - * helpful in the file.

    - *

    This method checks for codepage properties, and failing that - * looks at the headers for the message, and uses these to - * guess the correct encoding for your file.

    - *

    Bug #49441 has more on why this is needed

    - */ - public void guess7BitEncoding() { - // First choice is a codepage property - for (MAPIProperty prop : new MAPIProperty[] { - MAPIProperty.MESSAGE_CODEPAGE, - MAPIProperty.INTERNET_CPID - }) { - List val = mainChunks.getProperties().get(prop); - if (val != null && val.size() > 0) { - int codepage = ((LongPropertyValue)val.get(0)).getValue(); - try { - String encoding = CodePageUtil.codepageToEncoding(codepage, true); - set7BitEncoding(encoding); - return; - } catch(UnsupportedEncodingException e) { - logger.log(POILogger.WARN, "Invalid codepage ID ", codepage, - " set for the message via ", prop, ", ignoring"); - } - } - } - - - // Second choice is a charset on a content type header - try { - String[] headers = getHeaders(); - if(headers != null && headers.length > 0) { - // Look for a content type with a charset - Pattern p = Pattern.compile("Content-Type:.*?charset=[\"']?([^;'\"]+)[\"']?", Pattern.CASE_INSENSITIVE); - - for(String header : headers) { - if(header.startsWith("Content-Type")) { - Matcher m = p.matcher(header); - if(m.matches()) { - // Found it! Tell all the string chunks - String charset = m.group(1); - - if (!charset.equalsIgnoreCase("utf-8")) { - set7BitEncoding(charset); - } - return; - } - } - } - } - } catch(ChunkNotFoundException e) {} - - // Nothing suitable in the headers, try HTML - try { - String html = getHtmlBody(); - if(html != null && html.length() > 0) { - // Look for a content type in the meta headers - Pattern p = Pattern.compile( - " val = mainChunks.getProperties().get(prop); - if (val != null && val.size() > 0) { - return ((TimePropertyValue)val.get(0)).getValue(); - } - } - } - - if(returnNullOnMissingChunk) - return null; - throw new ChunkNotFoundException(); - } - - - /** - * Gets the main, core details chunks - */ - public Chunks getMainChunks() { - return mainChunks; - } - /** - * Gets all the recipient details chunks. - * These will normally be in the order of: - * * TO recipients, in the order returned by {@link #getDisplayTo()} - * * CC recipients, in the order returned by {@link #getDisplayCC()} - * * BCC recipients, in the order returned by {@link #getDisplayBCC()} - */ - public RecipientChunks[] getRecipientDetailsChunks() { - return recipientChunks; - } - /** - * Gets the Name ID chunks, or - * null if there aren't any - */ - public NameIdChunks getNameIdChunks() { - return nameIdChunks; - } - /** - * Gets the message attachments. - */ - public AttachmentChunks[] getAttachmentFiles() { - return attachmentChunks; - } - - - /** - * Will you get a null on a missing chunk, or a - * {@link ChunkNotFoundException} (default is the - * exception). - */ - public boolean isReturnNullOnMissingChunk() { - return returnNullOnMissingChunk; - } - - /** - * Sets whether on asking for a missing chunk, - * you get back null or a {@link ChunkNotFoundException} - * (default is the exception). - */ - public void setReturnNullOnMissingChunk(boolean returnNullOnMissingChunk) { - this.returnNullOnMissingChunk = returnNullOnMissingChunk; - } - - - private String toSemicolonList(String[] l) { - StringBuffer list = new StringBuffer(); - boolean first = true; - - for(String s : l) { - if(s == null) continue; - if(first) { - first = false; - } else { - list.append("; "); - } - list.append(s); - } - - return list.toString(); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hsmf/datatypes/AttachmentChunks.java b/src/scratchpad/src/org/apache/poi/hsmf/datatypes/AttachmentChunks.java deleted file mode 100644 index 043ef88c2..000000000 --- a/src/scratchpad/src/org/apache/poi/hsmf/datatypes/AttachmentChunks.java +++ /dev/null @@ -1,231 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hsmf.datatypes; - -import static org.apache.poi.hsmf.datatypes.MAPIProperty.ATTACH_CONTENT_ID; -import static org.apache.poi.hsmf.datatypes.MAPIProperty.ATTACH_DATA; -import static org.apache.poi.hsmf.datatypes.MAPIProperty.ATTACH_EXTENSION; -import static org.apache.poi.hsmf.datatypes.MAPIProperty.ATTACH_FILENAME; -import static org.apache.poi.hsmf.datatypes.MAPIProperty.ATTACH_LONG_FILENAME; -import static org.apache.poi.hsmf.datatypes.MAPIProperty.ATTACH_MIME_TAG; -import static org.apache.poi.hsmf.datatypes.MAPIProperty.ATTACH_RENDERING; - -import java.io.IOException; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.List; - -import org.apache.poi.hsmf.MAPIMessage; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; - -/** - * Collection of convenience chunks for standard parts of the MSG file - * attachment. - */ -public class AttachmentChunks implements ChunkGroup { - private static final POILogger LOG = POILogFactory.getLogger(AttachmentChunks.class); - public static final String PREFIX = "__attach_version1.0_#"; - - private ByteChunk attachData; - private StringChunk attachExtension; - private StringChunk attachFileName; - private StringChunk attachLongFileName; - private StringChunk attachMimeTag; - private DirectoryChunk attachmentDirectory; - private StringChunk attachContentId; - - /** - * This is in WMF Format. You'll probably want to pass it to Apache Batik to - * turn it into a SVG that you can then display. - */ - public ByteChunk attachRenderingWMF; - - /** - * What the POIFS name of this attachment is. - */ - private String poifsName; - - /** Holds all the chunks that were found. */ - private List allChunks = new ArrayList(); - - public AttachmentChunks(String poifsName) { - this.poifsName = poifsName; - } - - /** - * Is this Attachment an embedded MAPI message? - */ - public boolean isEmbeddedMessage() { - return (attachmentDirectory != null); - } - - /** - * Returns the embedded MAPI message, if the attachment is an embedded - * message, or null otherwise - */ - public MAPIMessage getEmbeddedMessage() throws IOException { - if (attachmentDirectory != null) { - return attachmentDirectory.getAsEmbededMessage(); - } - return null; - } - - /** - * Returns the embedded object, if the attachment is an object based - * embedding (image, document etc), or null if it's an embedded message - */ - public byte[] getEmbeddedAttachmentObject() { - if (attachData != null) { - return attachData.getValue(); - } - return null; - } - - public Chunk[] getAll() { - return allChunks.toArray(new Chunk[allChunks.size()]); - } - - @Override - public Chunk[] getChunks() { - return getAll(); - } - - public String getPOIFSName() { - return poifsName; - } - - /** - * @return the ATTACH_DATA chunk - */ - public ByteChunk getAttachData() { - return attachData; - } - - /** - * @return the attachment extension - */ - public StringChunk getAttachExtension() { - return attachExtension; - } - - /** - * @return the attachment (short) filename - */ - public StringChunk getAttachFileName() { - return attachFileName; - } - - /** - * @return the attachment (long) filename - */ - public StringChunk getAttachLongFileName() { - return attachLongFileName; - } - - /** - * @return the attachment mimetag - */ - public StringChunk getAttachMimeTag() { - return attachMimeTag; - } - - /** - * @return the attachment directory - */ - public DirectoryChunk getAttachmentDirectory() { - return attachmentDirectory; - } - - /** - * @return the attachment preview bytes - */ - public ByteChunk getAttachRenderingWMF() { - return attachRenderingWMF; - } - - /** - * @return the attachment content ID - */ - public StringChunk getAttachContentId() { - return attachContentId; - } - - /** - * Called by the parser whenever a chunk is found. - */ - @Override - public void record(Chunk chunk) { - // TODO: add further members for other properties like: - // - ATTACH_ADDITIONAL_INFO - // - ATTACH_CONTENT_BASE - // - ATTACH_CONTENT_LOCATION - // - ATTACH_DISPOSITION - // - ATTACH_ENCODING - // - ATTACH_FLAGS - // - ATTACH_LONG_PATHNAME - // - ATTACH_SIZE - final int chunkId = chunk.getChunkId(); - if (chunkId == ATTACH_DATA.id) { - if (chunk instanceof ByteChunk) { - attachData = (ByteChunk) chunk; - } else if (chunk instanceof DirectoryChunk) { - attachmentDirectory = (DirectoryChunk) chunk; - } else { - LOG.log(POILogger.ERROR, "Unexpected data chunk of type " + chunk.getEntryName()); - } - } else if (chunkId == ATTACH_EXTENSION.id) { - attachExtension = (StringChunk) chunk; - } else if (chunkId == ATTACH_FILENAME.id) { - attachFileName = (StringChunk) chunk; - } else if (chunkId == ATTACH_LONG_FILENAME.id) { - attachLongFileName = (StringChunk) chunk; - } else if (chunkId == ATTACH_MIME_TAG.id) { - attachMimeTag = (StringChunk) chunk; - } else if (chunkId == ATTACH_RENDERING.id) { - attachRenderingWMF = (ByteChunk) chunk; - } else if (chunkId == ATTACH_CONTENT_ID.id) { - attachContentId = (StringChunk) chunk; - } else { - LOG.log(POILogger.WARN, "Currently unsupported attachment chunk property will be ignored. " + chunk.getEntryName()); - } - - // And add to the main list - allChunks.add(chunk); - } - - /** - * Used to flag that all the chunks of the attachment have now been located. - */ - @Override - public void chunksComplete() { - // Currently, we don't need to do anything special once - // all the chunks have been located - } - - /** - * Orders by the attachment number. - */ - public static class AttachmentChunksSorter - implements Comparator, Serializable { - @Override - public int compare(AttachmentChunks a, AttachmentChunks b) { - return a.poifsName.compareTo(b.poifsName); - } - } -} diff --git a/src/scratchpad/src/org/apache/poi/hsmf/datatypes/ByteChunk.java b/src/scratchpad/src/org/apache/poi/hsmf/datatypes/ByteChunk.java deleted file mode 100644 index 57f56ab29..000000000 --- a/src/scratchpad/src/org/apache/poi/hsmf/datatypes/ByteChunk.java +++ /dev/null @@ -1,115 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hsmf.datatypes; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import org.apache.poi.hsmf.datatypes.Types.MAPIType; -import org.apache.poi.util.IOUtils; - -/** - * A Chunk that holds binary data, normally unparsed. Generally as we know how - * to make sense of the contents, we create a new Chunk class and add a special - * case in the parser for them. - */ - -public class ByteChunk extends Chunk { - private byte[] value; - - /** - * Creates a Byte Chunk. - */ - public ByteChunk(String namePrefix, int chunkId, MAPIType type) { - super(namePrefix, chunkId, type); - } - - /** - * Create a Byte Chunk, with the specified type. - */ - public ByteChunk(int chunkId, MAPIType type) { - super(chunkId, type); - } - - @Override - public void readValue(InputStream value) throws IOException { - this.value = IOUtils.toByteArray(value); - } - - @Override - public void writeValue(OutputStream out) throws IOException { - out.write(value); - } - - public byte[] getValue() { - return value; - } - - public void setValue(byte[] value) { - this.value = value; - } - - /** - * Returns the data in a debug-friendly string format - */ - @Override - public String toString() { - return toDebugFriendlyString(value); - } - - /** - * Formats the byte array in a debug-friendly way, showing all of a short - * array, and the start of a longer one. - */ - protected static String toDebugFriendlyString(byte[] value) { - if (value == null) { - return "(Null Byte Array)"; - } - - StringBuffer text = new StringBuffer(); - text.append("Bytes len=").append(value.length); - text.append(" ["); - - int limit = Math.min(value.length, 16); - if (value.length > 16) { - limit = 12; - } - for (int i = 0; i < limit; i++) { - if (i > 0) { - text.append(','); - } - text.append(value[i]); - } - if (value.length > 16) { - text.append(",...."); - } - text.append("]"); - return text.toString(); - } - - /** - * Returns the data, formatted as a string assuming it was a non-unicode - * string. If your data isn't in fact stored as basically ASCII, don't - * expect this to return much of any sense.... - * - * @return the data formatted as a string - */ - public String getAs7bitString() { - return StringChunk.parseAs7BitData(value); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hsmf/datatypes/Chunk.java b/src/scratchpad/src/org/apache/poi/hsmf/datatypes/Chunk.java deleted file mode 100644 index 5073771fc..000000000 --- a/src/scratchpad/src/org/apache/poi/hsmf/datatypes/Chunk.java +++ /dev/null @@ -1,84 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hsmf.datatypes; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.Locale; - -import org.apache.poi.hsmf.datatypes.Types.MAPIType; - -public abstract class Chunk { - public static final String DEFAULT_NAME_PREFIX = "__substg1.0_"; - - private final int chunkId; - private final MAPIType type; - private final String namePrefix; - - protected Chunk(String namePrefix, int chunkId, MAPIType type) { - this.namePrefix = namePrefix; - this.chunkId = chunkId; - this.type = type; - } - - protected Chunk(int chunkId, MAPIType type) { - this(DEFAULT_NAME_PREFIX, chunkId, type); - } - - /** - * Gets the id of this chunk - */ - public int getChunkId() { - return this.chunkId; - } - - /** - * Gets the numeric type of this chunk. - */ - public MAPIType getType() { - return this.type; - } - - /** - * Creates a string to use to identify this chunk in the POI file system - * object. - */ - public String getEntryName() { - String type = this.type.asFileEnding(); - - String chunkId = Integer.toHexString(this.chunkId); - while (chunkId.length() < 4) { - chunkId = "0" + chunkId; - } - - return this.namePrefix - + chunkId.toUpperCase(Locale.ROOT) - + type.toUpperCase(Locale.ROOT); - } - - /** - * Writes the value of this chunk back out again. - */ - public abstract void writeValue(OutputStream out) throws IOException; - - /** - * Reads the value of this chunk using an InputStream - */ - public abstract void readValue(InputStream value) throws IOException; -} diff --git a/src/scratchpad/src/org/apache/poi/hsmf/datatypes/ChunkBasedPropertyValue.java b/src/scratchpad/src/org/apache/poi/hsmf/datatypes/ChunkBasedPropertyValue.java deleted file mode 100644 index 323065592..000000000 --- a/src/scratchpad/src/org/apache/poi/hsmf/datatypes/ChunkBasedPropertyValue.java +++ /dev/null @@ -1,42 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hsmf.datatypes; - -/** - * A variable length {@link PropertyValue} that is backed by a {@link Chunk} - * TODO Provide a way to link these up with the chunks - */ -public class ChunkBasedPropertyValue extends PropertyValue { - public ChunkBasedPropertyValue(MAPIProperty property, long flags, byte[] offsetData) { - super(property, flags, offsetData); - } - - @Override - public Chunk getValue() { - // TODO Decode the value into an offset - // TODO Look up the chunk based on that - return null; - } - - /** - * Stores the offset of the chunk as the property value - */ - public void setValue(Chunk chunk) { - // TODO - } -} diff --git a/src/scratchpad/src/org/apache/poi/hsmf/datatypes/ChunkGroup.java b/src/scratchpad/src/org/apache/poi/hsmf/datatypes/ChunkGroup.java deleted file mode 100644 index 273950b28..000000000 --- a/src/scratchpad/src/org/apache/poi/hsmf/datatypes/ChunkGroup.java +++ /dev/null @@ -1,39 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hsmf.datatypes; - -/** - * A group of chunks, that are at the same point in the file structure. - */ -public interface ChunkGroup { - /** - * Returns the chunks that make up the group. Should certainly contain all - * the interesting Chunks, but needn't always contain all of the Chunks. - */ - public Chunk[] getChunks(); - - /** - * Called by the parser whenever a chunk is found. - */ - public void record(Chunk chunk); - - /** - * Called by the parser when all chunks have been found. - */ - public void chunksComplete(); -} diff --git a/src/scratchpad/src/org/apache/poi/hsmf/datatypes/ChunkGroupWithProperties.java b/src/scratchpad/src/org/apache/poi/hsmf/datatypes/ChunkGroupWithProperties.java deleted file mode 100644 index e29d01b80..000000000 --- a/src/scratchpad/src/org/apache/poi/hsmf/datatypes/ChunkGroupWithProperties.java +++ /dev/null @@ -1,35 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hsmf.datatypes; - -import java.util.List; -import java.util.Map; - -/** - * A group of chunks which is indexable by {@link MAPIProperty} entries. - */ -public interface ChunkGroupWithProperties extends ChunkGroup { - /** - * Returns all the Properties contained in the Chunk, along with their - * Values. Normally, each property will have one value, sometimes none, and - * rarely multiple (normally for Unknown etc). For fixed sized properties, - * the value can be fetched straight from the {@link PropertyValue}. For - * variable sized properties, you'll need to go via the chunk. - */ - public Map> getProperties(); -} diff --git a/src/scratchpad/src/org/apache/poi/hsmf/datatypes/Chunks.java b/src/scratchpad/src/org/apache/poi/hsmf/datatypes/Chunks.java deleted file mode 100644 index aee1e88c8..000000000 --- a/src/scratchpad/src/org/apache/poi/hsmf/datatypes/Chunks.java +++ /dev/null @@ -1,257 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hsmf.datatypes; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; - -/** - * Collection of convenience chunks for standard parts of the MSG file. - * - * Not all of these will be present in any given file. - * - * A partial list is available at: - * http://msdn.microsoft.com/en-us/library/ms526356%28v=exchg.10%29.aspx - * - * TODO Deprecate the public Chunks in favour of Property Lookups - */ -public final class Chunks implements ChunkGroupWithProperties { - private static final POILogger LOG = POILogFactory.getLogger(Chunks.class); - - /** - * Holds all the chunks that were found, indexed by their MAPIProperty. - * Normally a property will have zero chunks (fixed sized) or one chunk - * (variable size), but in some cases (eg Unknown) you may get more. - */ - private Map> allChunks = new HashMap>(); - - /** Type of message that the MSG represents (ie. IPM.Note) */ - private StringChunk messageClass; - /** BODY Chunk, for plain/text messages */ - private StringChunk textBodyChunk; - /** BODY Html Chunk, for html messages */ - private StringChunk htmlBodyChunkString; - private ByteChunk htmlBodyChunkBinary; - /** BODY Rtf Chunk, for Rtf (Rich) messages */ - private ByteChunk rtfBodyChunk; - /** Subject link chunk, in plain/text */ - private StringChunk subjectChunk; - /** - * Value that is in the TO field (not actually the addresses as they are - * stored in recip directory nodes - */ - private StringChunk displayToChunk; - /** Value that is in the FROM field */ - private StringChunk displayFromChunk; - /** value that shows in the CC field */ - private StringChunk displayCCChunk; - /** Value that shows in the BCC field */ - private StringChunk displayBCCChunk; - /** Sort of like the subject line, but without the RE: and FWD: parts. */ - private StringChunk conversationTopic; - /** Type of server that the message originated from (SMTP, etc). */ - private StringChunk sentByServerType; - /** The email headers */ - private StringChunk messageHeaders; - /** TODO */ - private MessageSubmissionChunk submissionChunk; - /** TODO */ - private StringChunk emailFromChunk; - /** The message ID */ - private StringChunk messageId; - /** The message properties */ - private MessagePropertiesChunk messageProperties; - - @Override - public Map> getProperties() { - if (messageProperties != null) { - return messageProperties.getProperties(); - } else { - return Collections.emptyMap(); - } - } - - public Map getRawProperties() { - if (messageProperties != null) { - return messageProperties.getRawProperties(); - } else { - return Collections.emptyMap(); - } - } - - public Map> getAll() { - return allChunks; - } - - @Override - public Chunk[] getChunks() { - ArrayList chunks = new ArrayList(allChunks.size()); - for (List c : allChunks.values()) { - chunks.addAll(c); - } - return chunks.toArray(new Chunk[chunks.size()]); - } - - public StringChunk getMessageClass() { - return messageClass; - } - - public StringChunk getTextBodyChunk() { - return textBodyChunk; - } - - public StringChunk getHtmlBodyChunkString() { - return htmlBodyChunkString; - } - - public ByteChunk getHtmlBodyChunkBinary() { - return htmlBodyChunkBinary; - } - - public ByteChunk getRtfBodyChunk() { - return rtfBodyChunk; - } - - public StringChunk getSubjectChunk() { - return subjectChunk; - } - - public StringChunk getDisplayToChunk() { - return displayToChunk; - } - - public StringChunk getDisplayFromChunk() { - return displayFromChunk; - } - - public StringChunk getDisplayCCChunk() { - return displayCCChunk; - } - - public StringChunk getDisplayBCCChunk() { - return displayBCCChunk; - } - - public StringChunk getConversationTopic() { - return conversationTopic; - } - - public StringChunk getSentByServerType() { - return sentByServerType; - } - - public StringChunk getMessageHeaders() { - return messageHeaders; - } - - public MessageSubmissionChunk getSubmissionChunk() { - return submissionChunk; - } - - public StringChunk getEmailFromChunk() { - return emailFromChunk; - } - - public StringChunk getMessageId() { - return messageId; - } - - public MessagePropertiesChunk getMessageProperties() { - return messageProperties; - } - - /** - * Called by the parser whenever a chunk is found. - */ - @Override - public void record(Chunk chunk) { - // Work out what MAPIProperty this corresponds to - MAPIProperty prop = MAPIProperty.get(chunk.getChunkId()); - - // Assign it for easy lookup, as best we can - if (prop == MAPIProperty.MESSAGE_CLASS) { - messageClass = (StringChunk) chunk; - } else if (prop == MAPIProperty.INTERNET_MESSAGE_ID) { - messageId = (StringChunk) chunk; - } else if (prop == MAPIProperty.MESSAGE_SUBMISSION_ID) { - // TODO - parse - submissionChunk = (MessageSubmissionChunk) chunk; - } else if (prop == MAPIProperty.RECEIVED_BY_ADDRTYPE) { - sentByServerType = (StringChunk) chunk; - } else if (prop == MAPIProperty.TRANSPORT_MESSAGE_HEADERS) { - messageHeaders = (StringChunk) chunk; - } - - else if (prop == MAPIProperty.CONVERSATION_TOPIC) { - conversationTopic = (StringChunk) chunk; - } else if (prop == MAPIProperty.SUBJECT) { - subjectChunk = (StringChunk) chunk; - } else if (prop == MAPIProperty.ORIGINAL_SUBJECT) { - // TODO - } - - else if (prop == MAPIProperty.DISPLAY_TO) { - displayToChunk = (StringChunk) chunk; - } else if (prop == MAPIProperty.DISPLAY_CC) { - displayCCChunk = (StringChunk) chunk; - } else if (prop == MAPIProperty.DISPLAY_BCC) { - displayBCCChunk = (StringChunk) chunk; - } - - else if (prop == MAPIProperty.SENDER_EMAIL_ADDRESS) { - emailFromChunk = (StringChunk) chunk; - } else if (prop == MAPIProperty.SENDER_NAME) { - displayFromChunk = (StringChunk) chunk; - } else if (prop == MAPIProperty.BODY) { - textBodyChunk = (StringChunk) chunk; - } else if (prop == MAPIProperty.BODY_HTML) { - if (chunk instanceof StringChunk) { - htmlBodyChunkString = (StringChunk) chunk; - } - if (chunk instanceof ByteChunk) { - htmlBodyChunkBinary = (ByteChunk) chunk; - } - } else if (prop == MAPIProperty.RTF_COMPRESSED) { - rtfBodyChunk = (ByteChunk) chunk; - } else if (chunk instanceof MessagePropertiesChunk) { - messageProperties = (MessagePropertiesChunk) chunk; - } - - // And add to the main list - if (allChunks.get(prop) == null) { - allChunks.put(prop, new ArrayList()); - } - allChunks.get(prop).add(chunk); - } - - @Override - public void chunksComplete() { - if (messageProperties != null) { - messageProperties.matchVariableSizedPropertiesToChunks(); - } else { - LOG.log(POILogger.WARN, - "Message didn't contain a root list of properties!"); - } - } -} \ No newline at end of file diff --git a/src/scratchpad/src/org/apache/poi/hsmf/datatypes/DirectoryChunk.java b/src/scratchpad/src/org/apache/poi/hsmf/datatypes/DirectoryChunk.java deleted file mode 100644 index 2be65a93d..000000000 --- a/src/scratchpad/src/org/apache/poi/hsmf/datatypes/DirectoryChunk.java +++ /dev/null @@ -1,64 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hsmf.datatypes; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import org.apache.poi.hsmf.MAPIMessage; -import org.apache.poi.hsmf.datatypes.Types.MAPIType; -import org.apache.poi.poifs.filesystem.DirectoryNode; - -/** - * A Chunk that is just a placeholder in the MAPIMessage directory structure, - * which contains children. This is most commonly used with nested MAPIMessages - */ -public class DirectoryChunk extends Chunk { - private DirectoryNode dir; - - public DirectoryChunk(DirectoryNode dir, String namePrefix, int chunkId, MAPIType type) { - super(namePrefix, chunkId, type); - this.dir = dir; - } - - /** - * Returns the directory entry for this chunk. You can then use standard - * POIFS methods to enumerate the entries in it. - */ - public DirectoryNode getDirectory() { - return dir; - } - - /** - * Treats the directory as an embeded MAPIMessage (it normally is one), and - * returns a MAPIMessage object to process it with. - */ - public MAPIMessage getAsEmbededMessage() throws IOException { - return new MAPIMessage(dir); - } - - @Override - public void readValue(InputStream value) { - // DirectoryChunks have 0 byte contents - } - - @Override - public void writeValue(OutputStream out) { - // DirectoryChunks have 0 byte contents - } -} diff --git a/src/scratchpad/src/org/apache/poi/hsmf/datatypes/MAPIProperty.java b/src/scratchpad/src/org/apache/poi/hsmf/datatypes/MAPIProperty.java deleted file mode 100644 index 21b07da32..000000000 --- a/src/scratchpad/src/org/apache/poi/hsmf/datatypes/MAPIProperty.java +++ /dev/null @@ -1,1111 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hsmf.datatypes; - -import static org.apache.poi.hsmf.datatypes.Types.ASCII_STRING; -import static org.apache.poi.hsmf.datatypes.Types.BINARY; -import static org.apache.poi.hsmf.datatypes.Types.BOOLEAN; -import static org.apache.poi.hsmf.datatypes.Types.CLS_ID; -import static org.apache.poi.hsmf.datatypes.Types.DIRECTORY; -import static org.apache.poi.hsmf.datatypes.Types.LONG; -import static org.apache.poi.hsmf.datatypes.Types.LONG_LONG; -import static org.apache.poi.hsmf.datatypes.Types.SHORT; -import static org.apache.poi.hsmf.datatypes.Types.TIME; - -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; - -import org.apache.poi.hsmf.datatypes.Types.MAPIType; - -/** - * Holds the list of MAPI Attributes, and allows lookup by friendly name, ID and - * MAPI Property Name. - * - * These are taken from the following MSDN resources: - * https://msdn.microsoft.com/en-us/library/microsoft.exchange.data.contenttypes.tnef.tnefpropertyid(v=exchg.150).aspx - * http://msdn.microsoft.com/en-us/library/ms526356%28v=exchg.10%29.aspx - */ -public class MAPIProperty { - private static Map attributes = new HashMap(); - - public static final MAPIProperty AB_DEFAULT_DIR = - new MAPIProperty(0x3d06, BINARY, "AbDefaultDir", "PR_AB_DEFAULT_DIR"); - public static final MAPIProperty AB_DEFAULT_PAB = - new MAPIProperty(0x3d07, BINARY, "AbDefaultPab", "PR_AB_DEFAULT_PAB"); - public static final MAPIProperty AB_PROVIDER_ID = - new MAPIProperty(0x3615, BINARY, "AbProviderId", "PR_AB_PROVIDER_ID"); - public static final MAPIProperty AB_PROVIDERS = - new MAPIProperty(0x3d01, BINARY, "AbProviders", "PR_AB_PROVIDERS"); - public static final MAPIProperty AB_SEARCH_PATH = - new MAPIProperty(0x3d05, Types.createCustom(4354), "AbSearchPath", "PR_AB_SEARCH_PATH"); - public static final MAPIProperty AB_SEARCH_PATH_UPDATE = - new MAPIProperty(0x3d11, BINARY, "AbSearchPathUpdate", "PR_AB_SEARCH_PATH_UPDATE"); - public static final MAPIProperty ACCESS = - new MAPIProperty(0xff4, LONG, "Access", "PR_ACCESS"); - public static final MAPIProperty ACCESS_LEVEL = - new MAPIProperty(0xff7, LONG, "AccessLevel", "PR_ACCESS_LEVEL"); - public static final MAPIProperty ACCOUNT = - new MAPIProperty(0x3a00, ASCII_STRING, "Account", "PR_ACCOUNT"); - public static final MAPIProperty ADDRTYPE = - new MAPIProperty(0x3002, ASCII_STRING, "Addrtype", "PR_ADDRTYPE"); - public static final MAPIProperty ALTERNATE_RECIPIENT = - new MAPIProperty(0x3a01, BINARY, "AlternateRecipient", "PR_ALTERNATE_RECIPIENT"); - public static final MAPIProperty ALTERNATE_RECIPIENT_ALLOWED = - new MAPIProperty(2, BOOLEAN, "AlternateRecipientAllowed", "PR_ALTERNATE_RECIPIENT_ALLOWED"); - public static final MAPIProperty ANR = - new MAPIProperty(0x360c, ASCII_STRING, "Anr", "PR_ANR"); - public static final MAPIProperty ASSISTANT = - new MAPIProperty(0x3a30, ASCII_STRING, "Assistant", "PR_ASSISTANT"); - public static final MAPIProperty ASSISTANT_TELEPHONE_NUMBER = - new MAPIProperty(0x3a2e, ASCII_STRING, "AssistantTelephoneNumber", "PR_ASSISTANT_TELEPHONE_NUMBER"); - public static final MAPIProperty ASSOC_CONTENT_COUNT = - new MAPIProperty(0x3617, LONG, "AssocContentCount", "PR_ASSOC_CONTENT_COUNT"); - public static final MAPIProperty ATTACH_ADDITIONAL_INFO = - new MAPIProperty(0x370f, BINARY, "AttachAdditionalInfo", "PR_ATTACH_ADDITIONAL_INFO"); - public static final MAPIProperty ATTACH_CONTENT_BASE = - new MAPIProperty(0x3711, Types.UNKNOWN, "AttachContentBase", "PR_ATTACH_CONTENT_BASE"); - public static final MAPIProperty ATTACH_CONTENT_ID = - new MAPIProperty(0x3712, Types.UNKNOWN, "AttachContentId", "PR_ATTACH_CONTENT_ID"); - public static final MAPIProperty ATTACH_CONTENT_LOCATION = - new MAPIProperty(0x3713, Types.UNKNOWN, "AttachContentLocation", "PR_ATTACH_CONTENT_LOCATION"); - public static final MAPIProperty ATTACH_DATA = - new MAPIProperty(0x3701, BINARY, "AttachData", "PR_ATTACH_DATA_OBJ"); - public static final MAPIProperty ATTACH_DISPOSITION = - new MAPIProperty(0x3716, Types.UNKNOWN, "AttachDisposition", "PR_ATTACH_DISPOSITION"); - public static final MAPIProperty ATTACH_ENCODING = - new MAPIProperty(0x3702, BINARY, "AttachEncoding", "PR_ATTACH_ENCODING"); - public static final MAPIProperty ATTACH_EXTENSION = - new MAPIProperty(0x3703, ASCII_STRING, "AttachExtension", "PR_ATTACH_EXTENSION"); - public static final MAPIProperty ATTACH_FILENAME = - new MAPIProperty(0x3704, ASCII_STRING, "AttachFilename", "PR_ATTACH_FILENAME"); - public static final MAPIProperty ATTACH_FLAGS = - new MAPIProperty(0x3714, Types.UNKNOWN, "AttachFlags", "PR_ATTACH_FLAGS"); - public static final MAPIProperty ATTACH_LONG_FILENAME = - new MAPIProperty(0x3707, ASCII_STRING, "AttachLongFilename", "PR_ATTACH_LONG_FILENAME"); - public static final MAPIProperty ATTACH_LONG_PATHNAME = - new MAPIProperty(0x370d, ASCII_STRING, "AttachLongPathname", "PR_ATTACH_LONG_PATHNAME"); - public static final MAPIProperty ATTACH_METHOD = - new MAPIProperty(0x3705, LONG, "AttachMethod", "PR_ATTACH_METHOD"); - public static final MAPIProperty ATTACH_MIME_SEQUENCE = - new MAPIProperty(0x3710, Types.UNKNOWN, "AttachMimeSequence", "PR_ATTACH_MIME_SEQUENCE"); - public static final MAPIProperty ATTACH_MIME_TAG = - new MAPIProperty(0x370e, ASCII_STRING, "AttachMimeTag", "PR_ATTACH_MIME_TAG"); - public static final MAPIProperty ATTACH_NETSCAPE_MAC_INFO = - new MAPIProperty(0x3715, Types.UNKNOWN, "AttachNetscapeMacInfo", "PR_ATTACH_NETSCAPE_MAC_INFO"); - public static final MAPIProperty ATTACH_NUM = - new MAPIProperty(0xe21, LONG, "AttachNum", "PR_ATTACH_NUM"); - public static final MAPIProperty ATTACH_PATHNAME = - new MAPIProperty(0x3708, ASCII_STRING, "AttachPathname", "PR_ATTACH_PATHNAME"); - public static final MAPIProperty ATTACH_RENDERING = - new MAPIProperty(0x3709, BINARY, "AttachRendering", "PR_ATTACH_RENDERING"); - public static final MAPIProperty ATTACH_SIZE = - new MAPIProperty(0xe20, LONG, "AttachSize", "PR_ATTACH_SIZE"); - public static final MAPIProperty ATTACH_TAG = - new MAPIProperty(0x370a, BINARY, "AttachTag", "PR_ATTACH_TAG"); - public static final MAPIProperty ATTACH_TRANSPORT_NAME = - new MAPIProperty(0x370c, ASCII_STRING, "AttachTransportName", "PR_ATTACH_TRANSPORT_NAME"); - public static final MAPIProperty ATTACHMENT_X400_PARAMETERS = - new MAPIProperty(0x3700, BINARY, "AttachmentX400Parameters", "PR_ATTACHMENT_X400_PARAMETERS"); - public static final MAPIProperty AUTHORIZING_USERS = - new MAPIProperty(3, BINARY, "AuthorizingUsers", "PR_AUTHORIZING_USERS"); - public static final MAPIProperty AUTO_FORWARD_COMMENT = - new MAPIProperty(4, ASCII_STRING, "AutoForwardComment", "PR_AUTO_FORWARD_COMMENT"); - public static final MAPIProperty AUTO_FORWARDED = - new MAPIProperty(5, BOOLEAN, "AutoForwarded", "PR_AUTO_FORWARDED"); - public static final MAPIProperty AUTO_RESPONSE_SUPPRESS = - new MAPIProperty(0x3fdf, Types.UNKNOWN, "AutoResponseSuppress", "PR_AUTO_RESPONSE_SUPPRESS"); - public static final MAPIProperty BIRTHDAY = - new MAPIProperty(0x3a42, TIME, "Birthday", "PR_BIRTHDAY"); - public static final MAPIProperty BODY = - new MAPIProperty(0x1000, ASCII_STRING, "Body", "PR_BODY"); - public static final MAPIProperty BODY_CONTENT_ID = - new MAPIProperty(0x1015, Types.UNKNOWN, "BodyContentId", "PR_BODY_CONTENT_ID"); - public static final MAPIProperty BODY_CONTENT_LOCATION = - new MAPIProperty(0x1014, Types.UNKNOWN, "BodyContentLocation", "PR_BODY_CONTENT_LOCATION"); - public static final MAPIProperty BODY_CRC = - new MAPIProperty(0xe1c, LONG, "BodyCrc", "PR_BODY_CRC"); - public static final MAPIProperty BODY_HTML = - new MAPIProperty(0x1013, Types.UNKNOWN, "BodyHtml", "data"); - public static final MAPIProperty BUSINESS_FAX_NUMBER = - new MAPIProperty(0x3a24, ASCII_STRING, "BusinessFaxNumber", "PR_BUSINESS_FAX_NUMBER"); - public static final MAPIProperty BUSINESS_HOME_PAGE = - new MAPIProperty(0x3a51, ASCII_STRING, "BusinessHomePage", "PR_BUSINESS_HOME_PAGE"); - public static final MAPIProperty CALLBACK_TELEPHONE_NUMBER = - new MAPIProperty(0x3a02, ASCII_STRING, "CallbackTelephoneNumber", "PR_CALLBACK_TELEPHONE_NUMBER"); - public static final MAPIProperty CAR_TELEPHONE_NUMBER = - new MAPIProperty(0x3a1e, ASCII_STRING, "CarTelephoneNumber", "PR_CAR_TELEPHONE_NUMBER"); - public static final MAPIProperty CHILDRENS_NAMES = - new MAPIProperty(0x3a58, Types.createCustom(4126), "ChildrensNames", "PR_CHILDRENS_NAMES"); - public static final MAPIProperty CLIENT_SUBMIT_TIME = - new MAPIProperty(0x39, TIME, "ClientSubmitTime", "PR_CLIENT_SUBMIT_TIME"); - public static final MAPIProperty COMMENT = - new MAPIProperty(0x3004, ASCII_STRING, "Comment", "PR_COMMENT"); - public static final MAPIProperty COMMON_VIEWS_ENTRY_ID = - new MAPIProperty(0x35e6, BINARY, "CommonViewsEntryId", "PR_COMMON_VIEWS_ENTRYID"); - public static final MAPIProperty COMPANY_MAIN_PHONE_NUMBER = - new MAPIProperty(0x3a57, ASCII_STRING, "CompanyMainPhoneNumber", "PR_COMPANY_MAIN_PHONE_NUMBER"); - public static final MAPIProperty COMPANY_NAME = - new MAPIProperty(0x3a16, ASCII_STRING, "CompanyName", "PR_COMPANY_NAME"); - public static final MAPIProperty COMPUTER_NETWORK_NAME = - new MAPIProperty(0x3a49, ASCII_STRING, "ComputerNetworkName", "PR_COMPUTER_NETWORK_NAME"); - public static final MAPIProperty CONTACT_ADDRTYPES = - new MAPIProperty(0x3a54, Types.createCustom(4126), "ContactAddrtypes", "PR_CONTACT_ADDRTYPES"); - public static final MAPIProperty CONTACT_DEFAULT_ADDRESS_INDEX = - new MAPIProperty(0x3a55, LONG, "ContactDefaultAddressIndex", "PR_CONTACT_DEFAULT_ADDRESS_INDEX"); - public static final MAPIProperty CONTACT_EMAIL_ADDRESSES = - new MAPIProperty(0x3a56, Types.createCustom(4126), "ContactEmailAddresses", "PR_CONTACT_EMAIL_ADDRESSES"); - public static final MAPIProperty CONTACT_ENTRY_IDS = - new MAPIProperty(0x3a53, Types.createCustom(4354), "ContactEntryIds", "PR_CONTACT_ENTRYIDS"); - public static final MAPIProperty CONTACT_VERSION = - new MAPIProperty(0x3a52, CLS_ID, "ContactVersion", "PR_CONTACT_VERSION"); - public static final MAPIProperty CONTAINER_CLASS = - new MAPIProperty(0x3613, ASCII_STRING, "ContainerClass", "PR_CONTAINER_CLASS"); - public static final MAPIProperty CONTAINER_CONTENTS = - new MAPIProperty(0x360f, DIRECTORY, "ContainerContents", "PR_CONTAINER_CONTENTS"); - public static final MAPIProperty CONTAINER_FLAGS = - new MAPIProperty(0x3600, LONG, "ContainerFlags", "PR_CONTAINER_FLAGS"); - public static final MAPIProperty CONTAINER_HIERARCHY = - new MAPIProperty(0x360e, DIRECTORY, "ContainerHierarchy", "PR_CONTAINER_HIERARCHY"); - public static final MAPIProperty CONTAINER_MODIFY_VERSION = - new MAPIProperty(0x3614, LONG_LONG, "ContainerModifyVersion", "PR_CONTAINER_MODIFY_VERSION"); - public static final MAPIProperty CONTENT_CONFIDENTIALITY_ALGORITHM_ID = - new MAPIProperty(6, BINARY, "ContentConfidentialityAlgorithmId", "PR_CONTENT_CONFIDENTIALITY_ALGORITHM_ID"); - public static final MAPIProperty CONTENT_CORRELATOR = - new MAPIProperty(7, BINARY, "ContentCorrelator", "PR_CONTENT_CORRELATOR"); - public static final MAPIProperty CONTENT_COUNT = - new MAPIProperty(0x3602, LONG, "ContentCount", "PR_CONTENT_COUNT"); - public static final MAPIProperty CONTENT_IDENTIFIER = - new MAPIProperty(8, ASCII_STRING, "ContentIdentifier", "PR_CONTENT_IDENTIFIER"); - public static final MAPIProperty CONTENT_INTEGRITY_CHECK = - new MAPIProperty(0xc00, BINARY, "ContentIntegrityCheck", "PR_CONTENT_INTEGRITY_CHECK"); - public static final MAPIProperty CONTENT_LENGTH = - new MAPIProperty(9, LONG, "ContentLength", "PR_CONTENT_LENGTH"); - public static final MAPIProperty CONTENT_RETURN_REQUESTED = - new MAPIProperty(10, BOOLEAN, "ContentReturnRequested", "PR_CONTENT_RETURN_REQUESTED"); - public static final MAPIProperty CONTENT_UNREAD = - new MAPIProperty(0x3603, LONG, "ContentUnread", "PR_CONTENT_UNREAD"); - public static final MAPIProperty CONTENTS_SORT_ORDER = - new MAPIProperty(0x360d, Types.createCustom(4099), "ContentsSortOrder", "PR_CONTENTS_SORT_ORDER"); - public static final MAPIProperty CONTROL_FLAGS = - new MAPIProperty(0x3f00, LONG, "ControlFlags", "PR_CONTROL_FLAGS"); - public static final MAPIProperty CONTROL_ID = - new MAPIProperty(0x3f07, BINARY, "ControlId", "PR_CONTROL_ID"); - public static final MAPIProperty CONTROL_STRUCTURE = - new MAPIProperty(0x3f01, BINARY, "ControlStructure", "PR_CONTROL_STRUCTURE"); - public static final MAPIProperty CONTROL_TYPE = - new MAPIProperty(0x3f02, LONG, "ControlType", "PR_CONTROL_TYPE"); - public static final MAPIProperty CONVERSATION_INDEX = - new MAPIProperty(0x71, BINARY, "ConversationIndex", "PR_CONVERSATION_INDEX"); - public static final MAPIProperty CONVERSATION_KEY = - new MAPIProperty(11, BINARY, "ConversationKey", "PR_CONVERSATION_KEY"); - public static final MAPIProperty CONVERSATION_TOPIC = - new MAPIProperty(0x70, ASCII_STRING, "ConversationTopic", "PR_CONVERSATION_TOPIC"); - public static final MAPIProperty CONVERSION_EITS = - new MAPIProperty(12, BINARY, "ConversionEits", "PR_CONVERSION_EITS"); - public static final MAPIProperty CONVERSION_PROHIBITED = - new MAPIProperty(0x3a03, BOOLEAN, "ConversionProhibited", "PR_CONVERSION_PROHIBITED"); - public static final MAPIProperty CONVERSION_WITH_LOSS_PROHIBITED = - new MAPIProperty(13, BOOLEAN, "ConversionWithLossProhibited", "PR_CONVERSION_WITH_LOSS_PROHIBITED"); - public static final MAPIProperty CONVERTED_EITS = - new MAPIProperty(14, BINARY, "ConvertedEits", "PR_CONVERTED_EITS"); - public static final MAPIProperty CORRELATE = - new MAPIProperty(0xe0c, BOOLEAN, "Correlate", "PR_CORRELATE"); - public static final MAPIProperty CORRELATE_MTSID = - new MAPIProperty(0xe0d, BINARY, "CorrelateMtsid", "PR_CORRELATE_MTSID"); - public static final MAPIProperty COUNTRY = - new MAPIProperty(0x3a26, ASCII_STRING, "Country", "PR_COUNTRY"); - public static final MAPIProperty CREATE_TEMPLATES = - new MAPIProperty(0x3604, DIRECTORY, "CreateTemplates", "PR_CREATE_TEMPLATES"); - public static final MAPIProperty CREATION_TIME = - new MAPIProperty(0x3007, TIME, "CreationTime", "PR_CREATION_TIME"); - public static final MAPIProperty CREATION_VERSION = - new MAPIProperty(0xe19, LONG_LONG, "CreationVersion", "PR_CREATION_VERSION"); - public static final MAPIProperty CURRENT_VERSION = - new MAPIProperty(0xe00, LONG_LONG, "CurrentVersion", "PR_CURRENT_VERSION"); - public static final MAPIProperty CUSTOMER_ID = - new MAPIProperty(0x3a4a, ASCII_STRING, "CustomerId", "PR_CUSTOMER_ID"); - public static final MAPIProperty DEF_CREATE_DL = - new MAPIProperty(0x3611, BINARY, "DefCreateDl", "PR_DEF_CREATE_DL"); - public static final MAPIProperty DEF_CREATE_MAILUSER = - new MAPIProperty(0x3612, BINARY, "DefCreateMailuser", "PR_DEF_CREATE_MAILUSER"); - public static final MAPIProperty DEFAULT_PROFILE = - new MAPIProperty(0x3d04, BOOLEAN, "DefaultProfile", "PR_DEFAULT_PROFILE"); - public static final MAPIProperty DEFAULT_STORE = - new MAPIProperty(0x3400, BOOLEAN, "DefaultStore", "PR_DEFAULT_STORE"); - public static final MAPIProperty DEFAULT_VIEW_ENTRY_ID = - new MAPIProperty(0x3616, BINARY, "DefaultViewEntryId", "PR_DEFAULT_VIEW_ENTRYID"); - public static final MAPIProperty DEFERRED_DELIVERY_TIME = - new MAPIProperty(15, TIME, "DeferredDeliveryTime", "PR_DEFERRED_DELIVERY_TIME"); - public static final MAPIProperty DELEGATION = - new MAPIProperty(0x7e, BINARY, "Delegation", "PR_DELEGATION"); - public static final MAPIProperty DELETE_AFTER_SUBMIT = - new MAPIProperty(0xe01, BOOLEAN, "DeleteAfterSubmit", "PR_DELETE_AFTER_SUBMIT"); - public static final MAPIProperty DELIVER_TIME = - new MAPIProperty(0x10, TIME, "DeliverTime", "PR_DELIVER_TIME"); - public static final MAPIProperty DELIVERY_POINT = - new MAPIProperty(0xc07, LONG, "DeliveryPoint", "PR_DELIVERY_POINT"); - public static final MAPIProperty DELTAX = - new MAPIProperty(0x3f03, LONG, "Deltax", "PR_DELTAX"); - public static final MAPIProperty DELTAY = - new MAPIProperty(0x3f04, LONG, "Deltay", "PR_DELTAY"); - public static final MAPIProperty DEPARTMENT_NAME = - new MAPIProperty(0x3a18, ASCII_STRING, "DepartmentName", "PR_DEPARTMENT_NAME"); - public static final MAPIProperty DEPTH = - new MAPIProperty(0x3005, LONG, "Depth", "PR_DEPTH"); - public static final MAPIProperty DETAILS_TABLE = - new MAPIProperty(0x3605, DIRECTORY, "DetailsTable", "PR_DETAILS_TABLE"); - public static final MAPIProperty DISC_VAL = - new MAPIProperty(0x4a, BOOLEAN, "DiscVal", "PR_DISC_VAL"); - public static final MAPIProperty DISCARD_REASON = - new MAPIProperty(0x11, LONG, "DiscardReason", "PR_DISCARD_REASON"); - public static final MAPIProperty DISCLOSE_RECIPIENTS = - new MAPIProperty(0x3a04, BOOLEAN, "DiscloseRecipients", "PR_DISCLOSE_RECIPIENTS"); - public static final MAPIProperty DISCLOSURE_OF_RECIPIENTS = - new MAPIProperty(0x12, BOOLEAN, "DisclosureOfRecipients", "PR_DISCLOSURE_OF_RECIPIENTS"); - public static final MAPIProperty DISCRETE_VALUES = - new MAPIProperty(0xe0e, BOOLEAN, "DiscreteValues", "PR_DISCRETE_VALUES"); - public static final MAPIProperty DISPLAY_BCC = - new MAPIProperty(0xe02, ASCII_STRING, "DisplayBcc", "PR_DISPLAY_BCC"); - public static final MAPIProperty DISPLAY_CC = - new MAPIProperty(0xe03, ASCII_STRING, "DisplayCc", "PR_DISPLAY_CC"); - public static final MAPIProperty DISPLAY_NAME = - new MAPIProperty(0x3001, ASCII_STRING, "DisplayName", "PR_DISPLAY_NAME"); - public static final MAPIProperty DISPLAY_NAME_PREFIX = - new MAPIProperty(0x3a45, ASCII_STRING, "DisplayNamePrefix", "PR_DISPLAY_NAME_PREFIX"); - public static final MAPIProperty DISPLAY_TO = - new MAPIProperty(0xe04, ASCII_STRING, "DisplayTo", "PR_DISPLAY_TO"); - public static final MAPIProperty DISPLAY_TYPE = - new MAPIProperty(0x3900, LONG, "DisplayType", "PR_DISPLAY_TYPE"); - public static final MAPIProperty DL_EXPANSION_HISTORY = - new MAPIProperty(0x13, BINARY, "DlExpansionHistory", "PR_DL_EXPANSION_HISTORY"); - public static final MAPIProperty DL_EXPANSION_PROHIBITED = - new MAPIProperty(20, BOOLEAN, "DlExpansionProhibited", "PR_DL_EXPANSION_PROHIBITED"); - public static final MAPIProperty EMAIL_ADDRESS = - new MAPIProperty(0x3003, ASCII_STRING, "EmailAddress", "PR_EMAIL_ADDRESS"); - public static final MAPIProperty END_DATE = - new MAPIProperty(0x61, TIME, "EndDate", "PR_END_DATE"); - public static final MAPIProperty ENTRY_ID = - new MAPIProperty(0xfff, BINARY, "EntryId", "PR_ENTRYID"); - public static final MAPIProperty EXPAND_BEGIN_TIME = - new MAPIProperty(0x3618, Types.UNKNOWN, "ExpandBeginTime", "PR_EXPAND_BEGIN_TIME"); - public static final MAPIProperty EXPAND_END_TIME = - new MAPIProperty(0x3619, Types.UNKNOWN, "ExpandEndTime", "PR_EXPAND_END_TIME"); - public static final MAPIProperty EXPANDED_BEGIN_TIME = - new MAPIProperty(0x361a, Types.UNKNOWN, "ExpandedBeginTime", "PR_EXPANDED_BEGIN_TIME"); - public static final MAPIProperty EXPANDED_END_TIME = - new MAPIProperty(0x361b, Types.UNKNOWN, "ExpandedEndTime", "PR_EXPANDED_END_TIME"); - public static final MAPIProperty EXPIRY_TIME = - new MAPIProperty(0x15, TIME, "ExpiryTime", "PR_EXPIRY_TIME"); - public static final MAPIProperty EXPLICIT_CONVERSION = - new MAPIProperty(0xc01, LONG, "ExplicitConversion", "PR_EXPLICIT_CONVERSION"); - public static final MAPIProperty FILTERING_HOOKS = - new MAPIProperty(0x3d08, BINARY, "FilteringHooks", "PR_FILTERING_HOOKS"); - public static final MAPIProperty FINDER_ENTRY_ID = - new MAPIProperty(0x35e7, BINARY, "FinderEntryId", "PR_FINDER_ENTRYID"); - public static final MAPIProperty FOLDER_ASSOCIATED_CONTENTS = - new MAPIProperty(0x3610, DIRECTORY, "FolderAssociatedContents", "PR_FOLDER_ASSOCIATED_CONTENTS"); - public static final MAPIProperty FOLDER_TYPE = - new MAPIProperty(0x3601, LONG, "FolderType", "PR_FOLDER_TYPE"); - public static final MAPIProperty FORM_CATEGORY = - new MAPIProperty(0x3304, ASCII_STRING, "FormCategory", "PR_FORM_CATEGORY"); - public static final MAPIProperty FORM_CATEGORY_SUB = - new MAPIProperty(0x3305, ASCII_STRING, "FormCategorySub", "PR_FORM_CATEGORY_SUB"); - public static final MAPIProperty FORM_CLSID = - new MAPIProperty(0x3302, CLS_ID, "FormClsid", "PR_FORM_ClsID"); - public static final MAPIProperty FORM_CONTACT_NAME = - new MAPIProperty(0x3303, ASCII_STRING, "FormContactName", "PR_FORM_CONTACT_NAME"); - public static final MAPIProperty FORM_DESIGNER_GUID = - new MAPIProperty(0x3309, CLS_ID, "FormDesignerGuid", "PR_FORM_DESIGNER_GUID"); - public static final MAPIProperty FORM_DESIGNER_NAME = - new MAPIProperty(0x3308, ASCII_STRING, "FormDesignerName", "PR_FORM_DESIGNER_NAME"); - public static final MAPIProperty FORM_HIDDEN = - new MAPIProperty(0x3307, BOOLEAN, "FormHidden", "PR_FORM_HIDDEN"); - public static final MAPIProperty FORM_HOST_MAP = - new MAPIProperty(0x3306, Types.createCustom(4099), "FormHostMap", "PR_FORM_HOST_MAP"); - public static final MAPIProperty FORM_MESSAGE_BEHAVIOR = - new MAPIProperty(0x330a, LONG, "FormMessageBehavior", "PR_FORM_MESSAGE_BEHAVIOR"); - public static final MAPIProperty FORM_VERSION = - new MAPIProperty(0x3301, ASCII_STRING, "FormVersion", "PR_FORM_VERSION"); - public static final MAPIProperty FTP_SITE = - new MAPIProperty(0x3a4c, ASCII_STRING, "FtpSite", "PR_FTP_SITE"); - public static final MAPIProperty GENDER = - new MAPIProperty(0x3a4d, SHORT, "Gender", "PR_GENDER"); - public static final MAPIProperty GENERATION = - new MAPIProperty(0x3a05, ASCII_STRING, "Generation", "PR_GENERATION"); - public static final MAPIProperty GIVEN_NAME = - new MAPIProperty(0x3a06, ASCII_STRING, "GivenName", "PR_GIVEN_NAME"); - public static final MAPIProperty GOVERNMENT_ID_NUMBER = - new MAPIProperty(0x3a07, ASCII_STRING, "GovernmentIdNumber", "PR_GOVERNMENT_ID_NUMBER"); - public static final MAPIProperty HASATTACH = - new MAPIProperty(0xe1b, BOOLEAN, "Hasattach", "PR_HASATTACH"); - public static final MAPIProperty HEADER_FOLDER_ENTRY_ID = - new MAPIProperty(0x3e0a, BINARY, "HeaderFolderEntryId", "PR_HEADER_FOLDER_ENTRYID"); - public static final MAPIProperty HOBBIES = - new MAPIProperty(0x3a43, ASCII_STRING, "Hobbies", "PR_HOBBIES"); - public static final MAPIProperty HOME2_TELEPHONE_NUMBER = - new MAPIProperty(0x3a2f, ASCII_STRING, "Home2TelephoneNumber", "PR_HOME2_TELEPHONE_NUMBER"); - public static final MAPIProperty HOME_ADDRESS_CITY = - new MAPIProperty(0x3a59, ASCII_STRING, "HomeAddressCity", "PR_HOME_ADDRESS_CITY"); - public static final MAPIProperty HOME_ADDRESS_COUNTRY = - new MAPIProperty(0x3a5a, ASCII_STRING, "HomeAddressCountry", "PR_HOME_ADDRESS_COUNTRY"); - public static final MAPIProperty HOME_ADDRESS_POST_OFFICE_BOX = - new MAPIProperty(0x3a5e, ASCII_STRING, "HomeAddressPostOfficeBox", "PR_HOME_ADDRESS_POST_OFFICE_BOX"); - public static final MAPIProperty HOME_ADDRESS_POSTAL_CODE = - new MAPIProperty(0x3a5b, ASCII_STRING, "HomeAddressPostalCode", "PR_HOME_ADDRESS_POSTAL_CODE"); - public static final MAPIProperty HOME_ADDRESS_STATE_OR_PROVINCE = - new MAPIProperty(0x3a5c, ASCII_STRING, "HomeAddressStateOrProvince", "PR_HOME_ADDRESS_STATE_OR_PROVINCE"); - public static final MAPIProperty HOME_ADDRESS_STREET = - new MAPIProperty(0x3a5d, ASCII_STRING, "HomeAddressStreet", "PR_HOME_ADDRESS_STREET"); - public static final MAPIProperty HOME_FAX_NUMBER = - new MAPIProperty(0x3a25, ASCII_STRING, "HomeFaxNumber", "PR_HOME_FAX_NUMBER"); - public static final MAPIProperty HOME_TELEPHONE_NUMBER = - new MAPIProperty(0x3a09, ASCII_STRING, "HomeTelephoneNumber", "PR_HOME_TELEPHONE_NUMBER"); - public static final MAPIProperty INET_MAIL_OVERRIDE_CHARSET = - new MAPIProperty(0x5903, Types.UNKNOWN, "INetMailOverrideCharset", "Charset"); - public static final MAPIProperty INET_MAIL_OVERRIDE_FORMAT = - new MAPIProperty(0x5902, Types.UNKNOWN, "INetMailOverrideFormat", "Format"); - public static final MAPIProperty ICON = - new MAPIProperty(0xffd, BINARY, "Icon", "PR_ICON"); - public static final MAPIProperty IDENTITY_DISPLAY = - new MAPIProperty(0x3e00, ASCII_STRING, "IdentityDisplay", "PR_IDENTITY_DISPLAY"); - public static final MAPIProperty IDENTITY_ENTRY_ID = - new MAPIProperty(0x3e01, BINARY, "IdentityEntryId", "PR_IDENTITY_ENTRYID"); - public static final MAPIProperty IDENTITY_SEARCH_KEY = - new MAPIProperty(0x3e05, BINARY, "IdentitySearchKey", "PR_IDENTITY_SEARCH_KEY"); - public static final MAPIProperty IMPLICIT_CONVERSION_PROHIBITED = - new MAPIProperty(0x16, BOOLEAN, "ImplicitConversionProhibited", "PR_IMPLICIT_CONVERSION_PROHIBITED"); - public static final MAPIProperty IMPORTANCE = - new MAPIProperty(0x17, LONG, "Importance", "PR_IMPORTANCE"); - public static final MAPIProperty IN_REPLY_TO_ID = - new MAPIProperty(0x1042, Types.UNKNOWN, "InReplyToId", "PR_IN_REPLY_TO_ID"); - public static final MAPIProperty INCOMPLETE_COPY = - new MAPIProperty(0x35, BOOLEAN, "IncompleteCopy", "PR_INCOMPLETE_COPY"); - public static final MAPIProperty INITIAL_DETAILS_PANE = - new MAPIProperty(0x3f08, LONG, "InitialDetailsPane", "PR_INITIAL_DETAILS_PANE"); - public static final MAPIProperty INITIALS = - new MAPIProperty(0x3a0a, ASCII_STRING, "Initials", "PR_INITIALS"); - public static final MAPIProperty INSTANCE_KEY = - new MAPIProperty(0xff6, BINARY, "InstanceKey", "PR_INSTANCE_KEY"); - public static final MAPIProperty INTERNET_APPROVED = - new MAPIProperty(0x1030, ASCII_STRING, "InternetApproved", "PR_INTERNET_APPROVED"); - public static final MAPIProperty INTERNET_ARTICLE_NUMBER = - new MAPIProperty(0xe23, LONG, "InternetArticleNumber", "PR_INTERNET_ARTICLE_NUMBER"); - public static final MAPIProperty INTERNET_CPID = - new MAPIProperty(0x3fde, Types.LONG, "InternetCPID", "PR_INTERNET_CPID"); - public static final MAPIProperty INTERNET_CONTROL = - new MAPIProperty(0x1031, ASCII_STRING, "InternetControl", "PR_INTERNET_CONTROL"); - public static final MAPIProperty INTERNET_DISTRIBUTION = - new MAPIProperty(0x1032, ASCII_STRING, "InternetDistribution", "PR_INTERNET_DISTRIBUTION"); - public static final MAPIProperty INTERNET_FOLLOWUP_TO = - new MAPIProperty(0x1033, ASCII_STRING, "InternetFollowupTo", "PR_INTERNET_FOLLOWUP_TO"); - public static final MAPIProperty INTERNET_LINES = - new MAPIProperty(0x1034, LONG, "InternetLines", "PR_INTERNET_LINES"); - public static final MAPIProperty INTERNET_MESSAGE_ID = - new MAPIProperty(0x1035, ASCII_STRING, "InternetMessageId", "PR_INTERNET_MESSAGE_ID"); - public static final MAPIProperty INTERNET_NEWSGROUPS = - new MAPIProperty(0x1036, ASCII_STRING, "InternetNewsgroups", "PR_INTERNET_NEWSGROUPS"); - public static final MAPIProperty INTERNET_NNTP_PATH = - new MAPIProperty(0x1038, ASCII_STRING, "InternetNntpPath", "PR_INTERNET_NNTP_PATH"); - public static final MAPIProperty INTERNET_ORGANIZATION = - new MAPIProperty(0x1037, ASCII_STRING, "InternetOrganization", "PR_INTERNET_ORGANIZATION"); - public static final MAPIProperty INTERNET_PRECEDENCE = - new MAPIProperty(0x1041, ASCII_STRING, "InternetPrecedence", "PR_INTERNET_PRECEDENCE"); - public static final MAPIProperty INTERNET_REFERENCES = - new MAPIProperty(0x1039, ASCII_STRING, "InternetReferences", "PR_INTERNET_REFERENCES"); - public static final MAPIProperty IPM_ID = - new MAPIProperty(0x18, BINARY, "IpmId", "PR_IPM_ID"); - public static final MAPIProperty IPM_OUTBOX_ENTRY_ID = - new MAPIProperty(0x35e2, BINARY, "IpmOutboxEntryId", "PR_IPM_OUTBOX_ENTRYID"); - public static final MAPIProperty IPM_OUTBOX_SEARCH_KEY = - new MAPIProperty(0x3411, BINARY, "IpmOutboxSearchKey", "PR_IPM_OUTBOX_SEARCH_KEY"); - public static final MAPIProperty IPM_RETURN_REQUESTED = - new MAPIProperty(0xc02, BOOLEAN, "IpmReturnRequested", "PR_IPM_RETURN_REQUESTED"); - public static final MAPIProperty IPM_SENTMAIL_ENTRY_ID = - new MAPIProperty(0x35e4, BINARY, "IpmSentmailEntryId", "PR_IPM_SENTMAIL_ENTRYID"); - public static final MAPIProperty IPM_SENTMAIL_SEARCH_KEY = - new MAPIProperty(0x3413, BINARY, "IpmSentmailSearchKey", "PR_IPM_SENTMAIL_SEARCH_KEY"); - public static final MAPIProperty IPM_SUBTREE_ENTRY_ID = - new MAPIProperty(0x35e0, BINARY, "IpmSubtreeEntryId", "PR_IPM_SUBTREE_ENTRYID"); - public static final MAPIProperty IPM_SUBTREE_SEARCH_KEY = - new MAPIProperty(0x3410, BINARY, "IpmSubtreeSearchKey", "PR_IPM_SUBTREE_SEARCH_KEY"); - public static final MAPIProperty IPM_WASTEBASKET_ENTRY_ID = - new MAPIProperty(0x35e3, BINARY, "IpmWastebasketEntryId", "PR_IPM_WASTEBASKET_ENTRYID"); - public static final MAPIProperty IPM_WASTEBASKET_SEARCH_KEY = - new MAPIProperty(0x3412, BINARY, "IpmWastebasketSearchKey", "PR_IPM_WASTEBASKET_SEARCH_KEY"); - public static final MAPIProperty ISDN_NUMBER = - new MAPIProperty(0x3a2d, ASCII_STRING, "IsdnNumber", "PR_ISDN_NUMBER"); - public static final MAPIProperty KEYWORD = - new MAPIProperty(0x3a0b, ASCII_STRING, "Keyword", "PR_KEYWORD"); - public static final MAPIProperty LANGUAGE = - new MAPIProperty(0x3a0c, ASCII_STRING, "Language", "PR_LANGUAGE"); - public static final MAPIProperty LANGUAGES = - new MAPIProperty(0x2f, ASCII_STRING, "Languages", "PR_LANGUAGES"); - public static final MAPIProperty LAST_MODIFICATION_TIME = - new MAPIProperty(0x3008, TIME, "LastModificationTime", "PR_LAST_MODIFICATION_TIME"); - public static final MAPIProperty LATEST_DELIVERY_TIME = - new MAPIProperty(0x19, TIME, "LatestDeliveryTime", "PR_LATEST_DELIVERY_TIME"); - public static final MAPIProperty LIST_HELP = - new MAPIProperty(0x1043, Types.UNKNOWN, "ListHelp", "PR_LIST_HELP"); - public static final MAPIProperty LIST_SUBSCRIBE = - new MAPIProperty(0x1044, Types.UNKNOWN, "ListSubscribe", "PR_LIST_SUBSCRIBE"); - public static final MAPIProperty LIST_UNSUBSCRIBE = - new MAPIProperty(0x1045, Types.UNKNOWN, "ListUnsubscribe", "PR_LIST_UNSUBSCRIBE"); - public static final MAPIProperty LOCALITY = - new MAPIProperty(0x3a27, ASCII_STRING, "Locality", "PR_LOCALITY"); - public static final MAPIProperty LOCALLY_DELIVERED = - new MAPIProperty(0x6745, Types.UNKNOWN, "LocallyDelivered", "ptagLocallyDelivered"); - public static final MAPIProperty LOCATION = - new MAPIProperty(0x3a0d, ASCII_STRING, "Location", "PR_LOCATION"); - public static final MAPIProperty LOCK_BRANCH_ID = - new MAPIProperty(0x3800, Types.UNKNOWN, "LockBranchId", "PR_LOCK_BRANCH_ID"); - public static final MAPIProperty LOCK_DEPTH = - new MAPIProperty(0x3808, Types.UNKNOWN, "LockDepth", "PR_LOCK_DEPTH"); - public static final MAPIProperty LOCK_ENLISTMENT_CONTEXT = - new MAPIProperty(0x3804, Types.UNKNOWN, "LockEnlistmentContext", "PR_LOCK_ENLISTMENT_CONTEXT"); - public static final MAPIProperty LOCK_EXPIRY_TIME = - new MAPIProperty(0x380a, Types.UNKNOWN, "LockExpiryTime", "PR_LOCK_EXPIRY_TIME"); - public static final MAPIProperty LOCK_PERSISTENT = - new MAPIProperty(0x3807, Types.UNKNOWN, "LockPersistent", "PR_LOCK_PERSISTENT"); - public static final MAPIProperty LOCK_RESOURCE_DID = - new MAPIProperty(0x3802, Types.UNKNOWN, "LockResourceDid", "PR_LOCK_RESOURCE_DID"); - public static final MAPIProperty LOCK_RESOURCE_FID = - new MAPIProperty(0x3801, Types.UNKNOWN, "LockResourceFid", "PR_LOCK_RESOURCE_FID"); - public static final MAPIProperty LOCK_RESOURCE_MID = - new MAPIProperty(0x3803, Types.UNKNOWN, "LockResourceMid", "PR_LOCK_RESOURCE_MID"); - public static final MAPIProperty LOCK_SCOPE = - new MAPIProperty(0x3806, Types.UNKNOWN, "LockScope", "PR_LOCK_SCOPE"); - public static final MAPIProperty LOCK_TIMEOUT = - new MAPIProperty(0x3809, Types.UNKNOWN, "LockTimeout", "PR_LOCK_TIMEOUT"); - public static final MAPIProperty LOCK_TYPE = - new MAPIProperty(0x3805, Types.UNKNOWN, "LockType", "PR_LOCK_TYPE"); - public static final MAPIProperty MAIL_PERMISSION = - new MAPIProperty(0x3a0e, BOOLEAN, "MailPermission", "PR_MAIL_PERMISSION"); - public static final MAPIProperty MANAGER_NAME = - new MAPIProperty(0x3a4e, ASCII_STRING, "ManagerName", "PR_MANAGER_NAME"); - public static final MAPIProperty MAPPING_SIGNATURE = - new MAPIProperty(0xff8, BINARY, "MappingSignature", "PR_MAPPING_SIGNATURE"); - public static final MAPIProperty MDB_PROVIDER = - new MAPIProperty(0x3414, BINARY, "MdbProvider", "PR_MDB_PROVIDER"); - public static final MAPIProperty MESSAGE_ATTACHMENTS = - new MAPIProperty(0xe13, DIRECTORY, "MessageAttachments", "PR_MESSAGE_ATTACHMENTS"); - public static final MAPIProperty MESSAGE_CC_ME = - new MAPIProperty(0x58, BOOLEAN, "MessageCcMe", "PR_MESSAGE_CC_ME"); - public static final MAPIProperty MESSAGE_CLASS = - new MAPIProperty(0x1a, ASCII_STRING, "MessageClass", "PR_MESSAGE_CLASS"); - public static final MAPIProperty MESSAGE_CODEPAGE = - new MAPIProperty(0x3ffd, Types.LONG, "MessageCodepage", "PR_MESSAGE_CODEPAGE"); - public static final MAPIProperty MESSAGE_DELIVERY_ID = - new MAPIProperty(0x1b, BINARY, "MessageDeliveryId", "PR_MESSAGE_DELIVERY_ID"); - public static final MAPIProperty MESSAGE_DELIVERY_TIME = - new MAPIProperty(0xe06, TIME, "MessageDeliveryTime", "PR_MESSAGE_DELIVERY_TIME"); - public static final MAPIProperty MESSAGE_DOWNLOAD_TIME = - new MAPIProperty(0xe18, LONG, "MessageDownloadTime", "PR_MESSAGE_DOWNLOAD_TIME"); - public static final MAPIProperty MESSAGE_FLAGS = - new MAPIProperty(0xe07, LONG, "MessageFlags", "PR_MESSAGE_FLAGS"); - public static final MAPIProperty MESSAGE_RECIP_ME = - new MAPIProperty(0x59, BOOLEAN, "MessageRecipMe", "PR_MESSAGE_RECIP_ME"); - public static final MAPIProperty MESSAGE_RECIPIENTS = - new MAPIProperty(0xe12, DIRECTORY, "MessageRecipients", "PR_MESSAGE_RECIPIENTS"); - public static final MAPIProperty MESSAGE_SECURITY_LABEL = - new MAPIProperty(30, BINARY, "MessageSecurityLabel", "PR_MESSAGE_SECURITY_LABEL"); - public static final MAPIProperty MESSAGE_SIZE = - new MAPIProperty(0xe08, LONG, "MessageSize", "PR_MESSAGE_SIZE"); - public static final MAPIProperty MESSAGE_SUBMISSION_ID = - new MAPIProperty(0x47, BINARY, "MessageSubmissionId", "PR_MESSAGE_SUBMISSION_ID"); - public static final MAPIProperty MESSAGE_TO_ME = - new MAPIProperty(0x57, BOOLEAN, "MessageToMe", "PR_MESSAGE_TO_ME"); - public static final MAPIProperty MESSAGE_TOKEN = - new MAPIProperty(0xc03, BINARY, "MessageToken", "PR_MESSAGE_TOKEN"); - public static final MAPIProperty MHS_COMMON_NAME = - new MAPIProperty(0x3a0f, ASCII_STRING, "MhsCommonName", "PR_MHS_COMMON_NAME"); - public static final MAPIProperty MIDDLE_NAME = - new MAPIProperty(0x3a44, ASCII_STRING, "MiddleName", "PR_MIDDLE_NAME"); - public static final MAPIProperty MINI_ICON = - new MAPIProperty(0xffc, BINARY, "MiniIcon", "PR_MINI_ICON"); - public static final MAPIProperty MOBILE_TELEPHONE_NUMBER = - new MAPIProperty(0x3a1c, ASCII_STRING, "MobileTelephoneNumber", "PR_MOBILE_TELEPHONE_NUMBER"); - public static final MAPIProperty MODIFY_VERSION = - new MAPIProperty(0xe1a, LONG_LONG, "ModifyVersion", "PR_MODIFY_VERSION"); - public static final MAPIProperty MSG_STATUS = - new MAPIProperty(0xe17, LONG, "MsgStatus", "PR_MSG_STATUS"); - public static final MAPIProperty NDR_DIAG_CODE = - new MAPIProperty(0xc05, LONG, "NdrDiagCode", "PR_NDR_DIAG_CODE"); - public static final MAPIProperty NDR_REASON_CODE = - new MAPIProperty(0xc04, LONG, "NdrReasonCode", "PR_NDR_REASON_CODE"); - public static final MAPIProperty NDR_STATUS_CODE = - new MAPIProperty(0xc20, Types.UNKNOWN, "NdrStatusCode", "PR_NDR_STATUS_CODE"); - public static final MAPIProperty NEWSGROUP_NAME = - new MAPIProperty(0xe24, ASCII_STRING, "NewsgroupName", "PR_NEWSGROUP_NAME"); - public static final MAPIProperty NICKNAME = - new MAPIProperty(0x3a4f, ASCII_STRING, "Nickname", "PR_NICKNAME"); - public static final MAPIProperty NNTP_XREF = - new MAPIProperty(0x1040, ASCII_STRING, "NntpXref", "PR_NNTP_XREF"); - public static final MAPIProperty NON_RECEIPT_NOTIFICATION_REQUESTED = - new MAPIProperty(0xc06, BOOLEAN, "NonReceiptNotificationRequested", "PR_NON_RECEIPT_NOTIFICATION_REQUESTED"); - public static final MAPIProperty NON_RECEIPT_REASON = - new MAPIProperty(0x3e, LONG, "NonReceiptReason", "PR_NON_RECEIPT_REASON"); - public static final MAPIProperty NORMALIZED_SUBJECT = - new MAPIProperty(0xe1d, ASCII_STRING, "NormalizedSubject", "PR_NORMALIZED_SUBJECT"); - public static final MAPIProperty NT_SECURITY_DESCRIPTOR = - new MAPIProperty(0xe27, Types.UNKNOWN, "NtSecurityDescriptor", "PR_NT_SECURITY_DESCRIPTOR"); - public static final MAPIProperty NULL = - new MAPIProperty(1, LONG, "Null", "PR_NULL"); - public static final MAPIProperty OBJECT_TYPE = - new MAPIProperty(0xffe, LONG, "ObjectType", "PR_Object_TYPE"); - public static final MAPIProperty OBSOLETED_IPMS = - new MAPIProperty(0x1f, BINARY, "ObsoletedIpms", "PR_OBSOLETED_IPMS"); - public static final MAPIProperty OFFICE2_TELEPHONE_NUMBER = - new MAPIProperty(0x3a1b, ASCII_STRING, "Office2TelephoneNumber", "PR_OFFICE2_TELEPHONE_NUMBER"); - public static final MAPIProperty OFFICE_LOCATION = - new MAPIProperty(0x3a19, ASCII_STRING, "OfficeLocation", "PR_OFFICE_LOCATION"); - public static final MAPIProperty OFFICE_TELEPHONE_NUMBER = - new MAPIProperty(0x3a08, ASCII_STRING, "OfficeTelephoneNumber", "PR_OFFICE_TELEPHONE_NUMBER"); - public static final MAPIProperty OOF_REPLY_TYPE = - new MAPIProperty(0x4080, Types.UNKNOWN, "OofReplyType", "PR_OOF_REPLY_TYPE"); - public static final MAPIProperty ORGANIZATIONAL_ID_NUMBER = - new MAPIProperty(0x3a10, ASCII_STRING, "OrganizationalIdNumber", "PR_ORGANIZATIONAL_ID_NUMBER"); - public static final MAPIProperty ORIG_ENTRY_ID = - new MAPIProperty(0x300f, Types.UNKNOWN, "OrigEntryId", "PR_ORIG_ENTRYID"); - public static final MAPIProperty ORIG_MESSAGE_CLASS = - new MAPIProperty(0x4b, ASCII_STRING, "OrigMessageClass", "PR_ORIG_MESSAGE_CLASS"); - public static final MAPIProperty ORIGIN_CHECK = - new MAPIProperty(0x27, BINARY, "OriginCheck", "PR_ORIGIN_CHECK"); - public static final MAPIProperty ORIGINAL_AUTHOR_ADDRTYPE = - new MAPIProperty(0x79, ASCII_STRING, "OriginalAuthorAddrtype", "PR_ORIGINAL_AUTHOR_ADDRTYPE"); - public static final MAPIProperty ORIGINAL_AUTHOR_EMAIL_ADDRESS = - new MAPIProperty(0x7a, ASCII_STRING, "OriginalAuthorEmailAddress", "PR_ORIGINAL_AUTHOR_EMAIL_ADDRESS"); - public static final MAPIProperty ORIGINAL_AUTHOR_ENTRY_ID = - new MAPIProperty(0x4c, BINARY, "OriginalAuthorEntryId", "PR_ORIGINAL_AUTHOR_ENTRYID"); - public static final MAPIProperty ORIGINAL_AUTHOR_NAME = - new MAPIProperty(0x4d, ASCII_STRING, "OriginalAuthorName", "PR_ORIGINAL_AUTHOR_NAME"); - public static final MAPIProperty ORIGINAL_AUTHOR_SEARCH_KEY = - new MAPIProperty(0x56, BINARY, "OriginalAuthorSearchKey", "PR_ORIGINAL_AUTHOR_SEARCH_KEY"); - public static final MAPIProperty ORIGINAL_DELIVERY_TIME = - new MAPIProperty(0x55, TIME, "OriginalDeliveryTime", "PR_ORIGINAL_DELIVERY_TIME"); - public static final MAPIProperty ORIGINAL_DISPLAY_BCC = - new MAPIProperty(0x72, ASCII_STRING, "OriginalDisplayBcc", "PR_ORIGINAL_DISPLAY_BCC"); - public static final MAPIProperty ORIGINAL_DISPLAY_CC = - new MAPIProperty(0x73, ASCII_STRING, "OriginalDisplayCc", "PR_ORIGINAL_DISPLAY_CC"); - public static final MAPIProperty ORIGINAL_DISPLAY_NAME = - new MAPIProperty(0x3a13, ASCII_STRING, "OriginalDisplayName", "PR_ORIGINAL_DISPLAY_NAME"); - public static final MAPIProperty ORIGINAL_DISPLAY_TO = - new MAPIProperty(0x74, ASCII_STRING, "OriginalDisplayTo", "PR_ORIGINAL_DISPLAY_TO"); - public static final MAPIProperty ORIGINAL_EITS = - new MAPIProperty(0x21, BINARY, "OriginalEits", "PR_ORIGINAL_EITS"); - public static final MAPIProperty ORIGINAL_ENTRY_ID = - new MAPIProperty(0x3a12, BINARY, "OriginalEntryId", "PR_ORIGINAL_ENTRYID"); - public static final MAPIProperty ORIGINAL_SEARCH_KEY = - new MAPIProperty(0x3a14, BINARY, "OriginalSearchKey", "PR_ORIGINAL_SEARCH_KEY"); - public static final MAPIProperty ORIGINAL_SENDER_ADDRTYPE = - new MAPIProperty(0x66, ASCII_STRING, "OriginalSenderAddrtype", "PR_ORIGINAL_SENDER_ADDRTYPE"); - public static final MAPIProperty ORIGINAL_SENDER_EMAIL_ADDRESS = - new MAPIProperty(0x67, ASCII_STRING, "OriginalSenderEmailAddress", "PR_ORIGINAL_SENDER_EMAIL_ADDRESS"); - public static final MAPIProperty ORIGINAL_SENDER_ENTRY_ID = - new MAPIProperty(0x5b, BINARY, "OriginalSenderEntryId", "PR_ORIGINAL_SENDER_ENTRYID"); - public static final MAPIProperty ORIGINAL_SENDER_NAME = - new MAPIProperty(90, ASCII_STRING, "OriginalSenderName", "PR_ORIGINAL_SENDER_NAME"); - public static final MAPIProperty ORIGINAL_SENDER_SEARCH_KEY = - new MAPIProperty(0x5c, BINARY, "OriginalSenderSearchKey", "PR_ORIGINAL_SENDER_SEARCH_KEY"); - public static final MAPIProperty ORIGINAL_SENSITIVITY = - new MAPIProperty(0x2e, LONG, "OriginalSensitivity", "PR_ORIGINAL_SENSITIVITY"); - public static final MAPIProperty ORIGINAL_SENT_REPRESENTING_ADDRTYPE = - new MAPIProperty(0x68, ASCII_STRING, "OriginalSentRepresentingAddrtype", "PR_ORIGINAL_SENT_REPRESENTING_ADDRTYPE"); - public static final MAPIProperty ORIGINAL_SENT_REPRESENTING_EMAIL_ADDRESS = - new MAPIProperty(0x69, ASCII_STRING, "OriginalSentRepresentingEmailAddress", "PR_ORIGINAL_SENT_REPRESENTING_EMAIL_ADDRESS"); - public static final MAPIProperty ORIGINAL_SENT_REPRESENTING_ENTRY_ID = - new MAPIProperty(0x5e, BINARY, "OriginalSentRepresentingEntryId", "PR_ORIGINAL_SENT_REPRESENTING_ENTRYID"); - public static final MAPIProperty ORIGINAL_SENT_REPRESENTING_NAME = - new MAPIProperty(0x5d, ASCII_STRING, "OriginalSentRepresentingName", "PR_ORIGINAL_SENT_REPRESENTING_NAME"); - public static final MAPIProperty ORIGINAL_SENT_REPRESENTING_SEARCH_KEY = - new MAPIProperty(0x5f, BINARY, "OriginalSentRepresentingSearchKey", "PR_ORIGINAL_SENT_REPRESENTING_SEARCH_KEY"); - public static final MAPIProperty ORIGINAL_SUBJECT = - new MAPIProperty(0x49, ASCII_STRING, "OriginalSubject", "PR_ORIGINAL_SUBJECT"); - public static final MAPIProperty ORIGINAL_SUBMIT_TIME = - new MAPIProperty(0x4e, TIME, "OriginalSubmitTime", "PR_ORIGINAL_SUBMIT_TIME"); - public static final MAPIProperty ORIGINALLY_INTENDED_RECIP_ADDRTYPE = - new MAPIProperty(0x7b, ASCII_STRING, "OriginallyIntendedRecipAddrtype", "PR_ORIGINALLY_INTENDED_RECIP_ADDRTYPE"); - public static final MAPIProperty ORIGINALLY_INTENDED_RECIP_EMAIL_ADDRESS = - new MAPIProperty(0x7c, ASCII_STRING, "OriginallyIntendedRecipEmailAddress", "PR_ORIGINALLY_INTENDED_RECIP_EMAIL_ADDRESS"); - public static final MAPIProperty ORIGINALLY_INTENDED_RECIP_ENTRY_ID = - new MAPIProperty(0x1012, BINARY, "OriginallyIntendedRecipEntryId", "PR_ORIGINALLY_INTENDED_RECIP_ENTRYID"); - public static final MAPIProperty ORIGINALLY_INTENDED_RECIPIENT_NAME = - new MAPIProperty(0x20, BINARY, "OriginallyIntendedRecipientName", "PR_ORIGINALLY_INTENDED_RECIPIENT_NAME"); - public static final MAPIProperty ORIGINATING_MTA_CERTIFICATE = - new MAPIProperty(0xe25, BINARY, "OriginatingMtaCertificate", "PR_ORIGINATING_MTA_CERTIFICATE"); - public static final MAPIProperty ORIGINATOR_AND_DL_EXPANSION_HISTORY = - new MAPIProperty(0x1002, BINARY, "OriginatorAndDlExpansionHistory", "PR_ORIGINATOR_AND_DL_EXPANSION_HISTORY"); - public static final MAPIProperty ORIGINATOR_CERTIFICATE = - new MAPIProperty(0x22, BINARY, "OriginatorCertificate", "PR_ORIGINATOR_CERTIFICATE"); - public static final MAPIProperty ORIGINATOR_DELIVERY_REPORT_REQUESTED = - new MAPIProperty(0x23, BOOLEAN, "OriginatorDeliveryReportRequested", "PR_ORIGINATOR_DELIVERY_REPORT_REQUESTED"); - public static final MAPIProperty ORIGINATOR_NON_DELIVERY_REPORT_REQUESTED = - new MAPIProperty(0xc08, BOOLEAN, "OriginatorNonDeliveryReportRequested", "PR_ORIGINATOR_NON_DELIVERY_REPORT_REQUESTED"); - public static final MAPIProperty ORIGINATOR_REQUESTED_ALTERNATE_RECIPIENT = - new MAPIProperty(0xc09, BINARY, "OriginatorRequestedAlternateRecipient", "PR_ORIGINATOR_REQUESTED_ALTERNATE_RECIPIENT"); - public static final MAPIProperty ORIGINATOR_RETURN_ADDRESS = - new MAPIProperty(0x24, BINARY, "OriginatorReturnAddress", "PR_ORIGINATOR_RETURN_ADDRESS"); - public static final MAPIProperty OTHER_ADDRESS_CITY = - new MAPIProperty(0x3a5f, ASCII_STRING, "OtherAddressCity", "PR_OTHER_ADDRESS_CITY"); - public static final MAPIProperty OTHER_ADDRESS_COUNTRY = - new MAPIProperty(0x3a60, ASCII_STRING, "OtherAddressCountry", "PR_OTHER_ADDRESS_COUNTRY"); - public static final MAPIProperty OTHER_ADDRESS_POST_OFFICE_BOX = - new MAPIProperty(0x3a64, ASCII_STRING, "OtherAddressPostOfficeBox", "PR_OTHER_ADDRESS_POST_OFFICE_BOX"); - public static final MAPIProperty OTHER_ADDRESS_POSTAL_CODE = - new MAPIProperty(0x3a61, ASCII_STRING, "OtherAddressPostalCode", "PR_OTHER_ADDRESS_POSTAL_CODE"); - public static final MAPIProperty OTHER_ADDRESS_STATE_OR_PROVINCE = - new MAPIProperty(0x3a62, ASCII_STRING, "OtherAddressStateOrProvince", "PR_OTHER_ADDRESS_STATE_OR_PROVINCE"); - public static final MAPIProperty OTHER_ADDRESS_STREET = - new MAPIProperty(0x3a63, ASCII_STRING, "OtherAddressStreet", "PR_OTHER_ADDRESS_STREET"); - public static final MAPIProperty OTHER_TELEPHONE_NUMBER = - new MAPIProperty(0x3a1f, ASCII_STRING, "OtherTelephoneNumber", "PR_OTHER_TELEPHONE_NUMBER"); - public static final MAPIProperty OWN_STORE_ENTRY_ID = - new MAPIProperty(0x3e06, BINARY, "OwnStoreEntryId", "PR_OWN_STORE_ENTRYID"); - public static final MAPIProperty OWNER_APPT_ID = - new MAPIProperty(0x62, LONG, "OwnerApptId", "PR_OWNER_APPT_ID"); - public static final MAPIProperty PAGER_TELEPHONE_NUMBER = - new MAPIProperty(0x3a21, ASCII_STRING, "PagerTelephoneNumber", "PR_PAGER_TELEPHONE_NUMBER"); - public static final MAPIProperty PARENT_DISPLAY = - new MAPIProperty(0xe05, ASCII_STRING, "ParentDisplay", "PR_PARENT_DISPLAY"); - public static final MAPIProperty PARENT_ENTRY_ID = - new MAPIProperty(0xe09, BINARY, "ParentEntryId", "PR_PARENT_ENTRYID"); - public static final MAPIProperty PARENT_KEY = - new MAPIProperty(0x25, BINARY, "ParentKey", "PR_PARENT_KEY"); - public static final MAPIProperty PERSONAL_HOME_PAGE = - new MAPIProperty(0x3a50, ASCII_STRING, "PersonalHomePage", "PR_PERSONAL_HOME_PAGE"); - public static final MAPIProperty PHYSICAL_DELIVERY_BUREAU_FAX_DELIVERY = - new MAPIProperty(0xc0a, BOOLEAN, "PhysicalDeliveryBureauFaxDelivery", "PR_PHYSICAL_DELIVERY_BUREAU_FAX_DELIVERY"); - public static final MAPIProperty PHYSICAL_DELIVERY_MODE = - new MAPIProperty(0xc0b, LONG, "PhysicalDeliveryMode", "PR_PHYSICAL_DELIVERY_MODE"); - public static final MAPIProperty PHYSICAL_DELIVERY_REPORT_REQUEST = - new MAPIProperty(0xc0c, LONG, "PhysicalDeliveryReportRequest", "PR_PHYSICAL_DELIVERY_REPORT_REQUEST"); - public static final MAPIProperty PHYSICAL_FORWARDING_ADDRESS = - new MAPIProperty(0xc0d, BINARY, "PhysicalForwardingAddress", "PR_PHYSICAL_FORWARDING_ADDRESS"); - public static final MAPIProperty PHYSICAL_FORWARDING_ADDRESS_REQUESTED = - new MAPIProperty(0xc0e, BOOLEAN, "PhysicalForwardingAddressRequested", "PR_PHYSICAL_FORWARDING_ADDRESS_REQUESTED"); - public static final MAPIProperty PHYSICAL_FORWARDING_PROHIBITED = - new MAPIProperty(0xc0f, BOOLEAN, "PhysicalForwardingProhibited", "PR_PHYSICAL_FORWARDING_PROHIBITED"); - public static final MAPIProperty PHYSICAL_RENDITION_ATTRIBUTES = - new MAPIProperty(0xc10, BINARY, "PhysicalRenditionAttributes", "PR_PHYSICAL_RENDITION_ATTRIBUTES"); - public static final MAPIProperty POST_FOLDER_ENTRIES = - new MAPIProperty(0x103b, BINARY, "PostFolderEntries", "PR_POST_FOLDER_ENTRIES"); - public static final MAPIProperty POST_FOLDER_NAMES = - new MAPIProperty(0x103c, ASCII_STRING, "PostFolderNames", "PR_POST_FOLDER_NAMES"); - public static final MAPIProperty POST_OFFICE_BOX = - new MAPIProperty(0x3a2b, ASCII_STRING, "PostOfficeBox", "PR_POST_OFFICE_BOX"); - public static final MAPIProperty POST_REPLY_DENIED = - new MAPIProperty(0x103f, BINARY, "PostReplyDenied", "PR_POST_REPLY_DENIED"); - public static final MAPIProperty POST_REPLY_FOLDER_ENTRIES = - new MAPIProperty(0x103d, BINARY, "PostReplyFolderEntries", "PR_POST_REPLY_FOLDER_ENTRIES"); - public static final MAPIProperty POST_REPLY_FOLDER_NAMES = - new MAPIProperty(0x103e, ASCII_STRING, "PostReplyFolderNames", "PR_POST_REPLY_FOLDER_NAMES"); - public static final MAPIProperty POSTAL_ADDRESS = - new MAPIProperty(0x3a15, ASCII_STRING, "PostalAddress", "PR_POSTAL_ADDRESS"); - public static final MAPIProperty POSTAL_CODE = - new MAPIProperty(0x3a2a, ASCII_STRING, "PostalCode", "PR_POSTAL_CODE"); - public static final MAPIProperty PREPROCESS = - new MAPIProperty(0xe22, BOOLEAN, "Preprocess", "PR_PREPROCESS"); - public static final MAPIProperty PRIMARY_CAPABILITY = - new MAPIProperty(0x3904, BINARY, "PrimaryCapability", "PR_PRIMARY_CAPABILITY"); - public static final MAPIProperty PRIMARY_FAX_NUMBER = - new MAPIProperty(0x3a23, ASCII_STRING, "PrimaryFaxNumber", "PR_PRIMARY_FAX_NUMBER"); - public static final MAPIProperty PRIMARY_TELEPHONE_NUMBER = - new MAPIProperty(0x3a1a, ASCII_STRING, "PrimaryTelephoneNumber", "PR_PRIMARY_TELEPHONE_NUMBER"); - public static final MAPIProperty PRIORITY = - new MAPIProperty(0x26, LONG, "Priority", "PR_PRIORITY"); - public static final MAPIProperty PROFESSION = - new MAPIProperty(0x3a46, ASCII_STRING, "Profession", "PR_PROFESSION"); - public static final MAPIProperty PROFILE_NAME = - new MAPIProperty(0x3d12, ASCII_STRING, "ProfileName", "PR_PROFILE_NAME"); - public static final MAPIProperty PROOF_OF_DELIVERY = - new MAPIProperty(0xc11, BINARY, "ProofOfDelivery", "PR_PROOF_OF_DELIVERY"); - public static final MAPIProperty PROOF_OF_DELIVERY_REQUESTED = - new MAPIProperty(0xc12, BOOLEAN, "ProofOfDeliveryRequested", "PR_PROOF_OF_DELIVERY_REQUESTED"); - public static final MAPIProperty PROOF_OF_SUBMISSION = - new MAPIProperty(0xe26, BINARY, "ProofOfSubmission", "PR_PROOF_OF_SUBMISSION"); - public static final MAPIProperty PROOF_OF_SUBMISSION_REQUESTED = - new MAPIProperty(40, BOOLEAN, "ProofOfSubmissionRequested", "PR_PROOF_OF_SUBMISSION_REQUESTED"); - public static final MAPIProperty PROP_ID_SECURE_MAX = - new MAPIProperty(0x67ff, Types.UNKNOWN, "PropIdSecureMax", "PROP_ID_SECURE_MAX"); - public static final MAPIProperty PROP_ID_SECURE_MIN = - new MAPIProperty(0x67f0, Types.UNKNOWN, "PropIdSecureMin", "PROP_ID_SECURE_MIN"); - public static final MAPIProperty PROVIDER_DISPLAY = - new MAPIProperty(0x3006, ASCII_STRING, "ProviderDisplay", "PR_PROVIDER_DISPLAY"); - public static final MAPIProperty PROVIDER_DLL_NAME = - new MAPIProperty(0x300a, ASCII_STRING, "ProviderDllName", "PR_PROVIDER_DLL_NAME"); - public static final MAPIProperty PROVIDER_ORDINAL = - new MAPIProperty(0x300d, LONG, "ProviderOrdinal", "PR_PROVIDER_ORDINAL"); - public static final MAPIProperty PROVIDER_SUBMIT_TIME = - new MAPIProperty(0x48, TIME, "ProviderSubmitTime", "PR_PROVIDER_SUBMIT_TIME"); - public static final MAPIProperty PROVIDER_UID = - new MAPIProperty(0x300c, BINARY, "ProviderUid", "PR_PROVIDER_UID"); - public static final MAPIProperty PUID = - new MAPIProperty(0x300e, Types.UNKNOWN, "Puid", "PR_PUID"); - public static final MAPIProperty RADIO_TELEPHONE_NUMBER = - new MAPIProperty(0x3a1d, ASCII_STRING, "RadioTelephoneNumber", "PR_RADIO_TELEPHONE_NUMBER"); - public static final MAPIProperty RCVD_REPRESENTING_ADDRTYPE = - new MAPIProperty(0x77, ASCII_STRING, "RcvdRepresentingAddrtype", "PR_RCVD_REPRESENTING_ADDRTYPE"); - public static final MAPIProperty RCVD_REPRESENTING_EMAIL_ADDRESS = - new MAPIProperty(120, ASCII_STRING, "RcvdRepresentingEmailAddress", "PR_RCVD_REPRESENTING_EMAIL_ADDRESS"); - public static final MAPIProperty RCVD_REPRESENTING_ENTRY_ID = - new MAPIProperty(0x43, BINARY, "RcvdRepresentingEntryId", "PR_RCVD_REPRESENTING_ENTRYID"); - public static final MAPIProperty RCVD_REPRESENTING_NAME = - new MAPIProperty(0x44, ASCII_STRING, "RcvdRepresentingName", "PR_RCVD_REPRESENTING_NAME"); - public static final MAPIProperty RCVD_REPRESENTING_SEARCH_KEY = - new MAPIProperty(0x52, BINARY, "RcvdRepresentingSearchKey", "PR_RCVD_REPRESENTING_SEARCH_KEY"); - public static final MAPIProperty READ_RECEIPT_ENTRY_ID = - new MAPIProperty(70, BINARY, "ReadReceiptEntryId", "PR_READ_RECEIPT_ENTRYID"); - public static final MAPIProperty READ_RECEIPT_REQUESTED = - new MAPIProperty(0x29, BOOLEAN, "ReadReceiptRequested", "PR_READ_RECEIPT_REQUESTED"); - public static final MAPIProperty READ_RECEIPT_SEARCH_KEY = - new MAPIProperty(0x53, BINARY, "ReadReceiptSearchKey", "PR_READ_RECEIPT_SEARCH_KEY"); - public static final MAPIProperty RECEIPT_TIME = - new MAPIProperty(0x2a, TIME, "ReceiptTime", "PR_RECEIPT_TIME"); - public static final MAPIProperty RECEIVE_FOLDER_SETTINGS = - new MAPIProperty(0x3415, DIRECTORY, "ReceiveFolderSettings", "PR_RECEIVE_FOLDER_SETTINGS"); - public static final MAPIProperty RECEIVED_BY_ADDRTYPE = - new MAPIProperty(0x75, ASCII_STRING, "ReceivedByAddrtype", "PR_RECEIVED_BY_ADDRTYPE"); - public static final MAPIProperty RECEIVED_BY_EMAIL_ADDRESS = - new MAPIProperty(0x76, ASCII_STRING, "ReceivedByEmailAddress", "PR_RECEIVED_BY_EMAIL_ADDRESS"); - public static final MAPIProperty RECEIVED_BY_ENTRY_ID = - new MAPIProperty(0x3f, BINARY, "ReceivedByEntryId", "PR_RECEIVED_BY_ENTRYID"); - public static final MAPIProperty RECEIVED_BY_NAME = - new MAPIProperty(0x40, ASCII_STRING, "ReceivedByName", "PR_RECEIVED_BY_NAME"); - public static final MAPIProperty RECIPIENT_DISPLAY_NAME = - new MAPIProperty(0x5ff6, Types.UNICODE_STRING, "RecipientDisplayName", null); - public static final MAPIProperty RECIPIENT_ENTRY_ID = - new MAPIProperty(0x5ff7, Types.UNKNOWN, "RecipientEntryId", null); - public static final MAPIProperty RECIPIENT_FLAGS = - new MAPIProperty(0x5ffd, Types.UNKNOWN, "RecipientFlags", null); - public static final MAPIProperty RECEIVED_BY_SEARCH_KEY = - new MAPIProperty(0x51, BINARY, "ReceivedBySearchKey", "PR_RECEIVED_BY_SEARCH_KEY"); - public static final MAPIProperty RECIPIENT_CERTIFICATE = - new MAPIProperty(0xc13, BINARY, "RecipientCertificate", "PR_RECIPIENT_CERTIFICATE"); - public static final MAPIProperty RECIPIENT_NUMBER_FOR_ADVICE = - new MAPIProperty(0xc14, ASCII_STRING, "RecipientNumberForAdvice", "PR_RECIPIENT_NUMBER_FOR_ADVICE"); - public static final MAPIProperty RECIPIENT_REASSIGNMENT_PROHIBITED = - new MAPIProperty(0x2b, BOOLEAN, "RecipientReassignmentProhibited", "PR_RECIPIENT_REASSIGNMENT_PROHIBITED"); - public static final MAPIProperty RECIPIENT_STATUS = - new MAPIProperty(0xe15, LONG, "RecipientStatus", "PR_RECIPIENT_STATUS"); - public static final MAPIProperty RECIPIENT_TYPE = - new MAPIProperty(0xc15, LONG, "RecipientType", "PR_RECIPIENT_TYPE"); - public static final MAPIProperty RECORD_KEY = - new MAPIProperty(0xff9, BINARY, "RecordKey", "PR_RECORD_KEY"); - public static final MAPIProperty REDIRECTION_HISTORY = - new MAPIProperty(0x2c, BINARY, "RedirectionHistory", "PR_REDIRECTION_HISTORY"); - public static final MAPIProperty REFERRED_BY_NAME = - new MAPIProperty(0x3a47, ASCII_STRING, "ReferredByName", "PR_REFERRED_BY_NAME"); - public static final MAPIProperty REGISTERED_MAIL_TYPE = - new MAPIProperty(0xc16, LONG, "RegisteredMailType", "PR_REGISTERED_MAIL_TYPE"); - public static final MAPIProperty RELATED_IPMS = - new MAPIProperty(0x2d, BINARY, "RelatedIpms", "PR_RELATED_IPMS"); - public static final MAPIProperty REMOTE_PROGRESS = - new MAPIProperty(0x3e0b, LONG, "RemoteProgress", "PR_REMOTE_PROGRESS"); - public static final MAPIProperty REMOTE_PROGRESS_TEXT = - new MAPIProperty(0x3e0c, ASCII_STRING, "RemoteProgressText", "PR_REMOTE_PROGRESS_TEXT"); - public static final MAPIProperty REMOTE_VALIDATE_OK = - new MAPIProperty(0x3e0d, BOOLEAN, "RemoteValidateOk", "PR_REMOTE_VALIDATE_OK"); - public static final MAPIProperty RENDERING_POSITION = - new MAPIProperty(0x370b, LONG, "RenderingPosition", "PR_RENDERING_POSITION"); - public static final MAPIProperty REPLY_RECIPIENT_ENTRIES = - new MAPIProperty(0x4f, BINARY, "ReplyRecipientEntries", "PR_REPLY_RECIPIENT_ENTRIES"); - public static final MAPIProperty REPLY_RECIPIENT_NAMES = - new MAPIProperty(80, ASCII_STRING, "ReplyRecipientNames", "PR_REPLY_RECIPIENT_NAMES"); - public static final MAPIProperty REPLY_REQUESTED = - new MAPIProperty(0xc17, BOOLEAN, "ReplyRequested", "PR_REPLY_REQUESTED"); - public static final MAPIProperty REPLY_TIME = - new MAPIProperty(0x30, TIME, "ReplyTime", "PR_REPLY_TIME"); - public static final MAPIProperty REPORT_ENTRY_ID = - new MAPIProperty(0x45, BINARY, "ReportEntryId", "PR_REPORT_ENTRYID"); - public static final MAPIProperty REPORT_NAME = - new MAPIProperty(0x3a, ASCII_STRING, "ReportName", "PR_REPORT_NAME"); - public static final MAPIProperty REPORT_SEARCH_KEY = - new MAPIProperty(0x54, BINARY, "ReportSearchKey", "PR_REPORT_SEARCH_KEY"); - public static final MAPIProperty REPORT_TAG = - new MAPIProperty(0x31, BINARY, "ReportTag", "PR_REPORT_TAG"); - public static final MAPIProperty REPORT_TEXT = - new MAPIProperty(0x1001, ASCII_STRING, "ReportText", "PR_REPORT_TEXT"); - public static final MAPIProperty REPORT_TIME = - new MAPIProperty(50, TIME, "ReportTime", "PR_REPORT_TIME"); - public static final MAPIProperty REPORTING_DL_NAME = - new MAPIProperty(0x1003, BINARY, "ReportingDlName", "PR_REPORTING_DL_NAME"); - public static final MAPIProperty REPORTING_MTA_CERTIFICATE = - new MAPIProperty(0x1004, BINARY, "ReportingMtaCertificate", "PR_REPORTING_MTA_CERTIFICATE"); - public static final MAPIProperty REQUESTED_DELIVERY_METHOD = - new MAPIProperty(0xc18, LONG, "RequestedDeliveryMethod", "PR_REQUESTED_DELIVERY_METHOD"); - public static final MAPIProperty RESOURCE_FLAGS = - new MAPIProperty(0x3009, LONG, "ResourceFlags", "PR_RESOURCE_FLAGS"); - public static final MAPIProperty RESOURCE_METHODS = - new MAPIProperty(0x3e02, LONG, "ResourceMethods", "PR_RESOURCE_METHODS"); - public static final MAPIProperty RESOURCE_PATH = - new MAPIProperty(0x3e07, ASCII_STRING, "ResourcePath", "PR_RESOURCE_PATH"); - public static final MAPIProperty RESOURCE_TYPE = - new MAPIProperty(0x3e03, LONG, "ResourceType", "PR_RESOURCE_TYPE"); - public static final MAPIProperty RESPONSE_REQUESTED = - new MAPIProperty(0x63, BOOLEAN, "ResponseRequested", "PR_RESPONSE_REQUESTED"); - public static final MAPIProperty RESPONSIBILITY = - new MAPIProperty(0xe0f, BOOLEAN, "Responsibility", "PR_RESPONSIBILITY"); - public static final MAPIProperty RETURNED_IPM = - new MAPIProperty(0x33, BOOLEAN, "ReturnedIpm", "PR_RETURNED_IPM"); - public static final MAPIProperty ROW_TYPE = - new MAPIProperty(0xff5, LONG, "RowType", "PR_ROW_TYPE"); - public static final MAPIProperty ROWID = - new MAPIProperty(0x3000, LONG, "Rowid", "PR_ROWID"); - public static final MAPIProperty RTF_COMPRESSED = - new MAPIProperty(0x1009, BINARY, "RtfCompressed", "PR_RTF_COMPRESSED"); - public static final MAPIProperty RTF_IN_SYNC = - new MAPIProperty(0xe1f, BOOLEAN, "RtfInSync", "PR_RTF_IN_SYNC"); - public static final MAPIProperty RTF_SYNC_BODY_COUNT = - new MAPIProperty(0x1007, LONG, "RtfSyncBodyCount", "PR_RTF_SYNC_BODY_COUNT"); - public static final MAPIProperty RTF_SYNC_BODY_CRC = - new MAPIProperty(0x1006, LONG, "RtfSyncBodyCrc", "PR_RTF_SYNC_BODY_CRC"); - public static final MAPIProperty RTF_SYNC_BODY_TAG = - new MAPIProperty(0x1008, ASCII_STRING, "RtfSyncBodyTag", "PR_RTF_SYNC_BODY_TAG"); - public static final MAPIProperty RTF_SYNC_PREFIX_COUNT = - new MAPIProperty(0x1010, LONG, "RtfSyncPrefixCount", "PR_RTF_SYNC_PREFIX_COUNT"); - public static final MAPIProperty RTF_SYNC_TRAILING_COUNT = - new MAPIProperty(0x1011, LONG, "RtfSyncTrailingCount", "PR_RTF_SYNC_TRAILING_COUNT"); - public static final MAPIProperty SEARCH = - new MAPIProperty(0x3607, DIRECTORY, "Search", "PR_SEARCH"); - public static final MAPIProperty SEARCH_KEY = - new MAPIProperty(0x300b, BINARY, "SearchKey", "PR_SEARCH_KEY"); - public static final MAPIProperty SECURITY = - new MAPIProperty(0x34, LONG, "Security", "PR_SECURITY"); - public static final MAPIProperty SELECTABLE = - new MAPIProperty(0x3609, BOOLEAN, "Selectable", "PR_SELECTABLE"); - public static final MAPIProperty SEND_INTERNET_ENCODING = - new MAPIProperty(0x3a71, LONG, "SendInternetEncoding", "PR_SEND_INTERNET_ENCODING"); - public static final MAPIProperty SEND_RECALL_REPORT = - new MAPIProperty(0x6803, Types.UNKNOWN, "SendRecallReport", "messages"); - public static final MAPIProperty SEND_RICH_INFO = - new MAPIProperty(0x3a40, BOOLEAN, "SendRichInfo", "PR_SEND_RICH_INFO"); - public static final MAPIProperty SENDER_ADDRTYPE = - new MAPIProperty(0xc1e, ASCII_STRING, "SenderAddrtype", "PR_SENDER_ADDRTYPE"); - public static final MAPIProperty SENDER_EMAIL_ADDRESS = - new MAPIProperty(0xc1f, ASCII_STRING, "SenderEmailAddress", "PR_SENDER_EMAIL_ADDRESS"); - public static final MAPIProperty SENDER_ENTRY_ID = - new MAPIProperty(0xc19, BINARY, "SenderEntryId", "PR_SENDER_ENTRYID"); - public static final MAPIProperty SENDER_NAME = - new MAPIProperty(0xc1a, ASCII_STRING, "SenderName", "PR_SENDER_NAME"); - public static final MAPIProperty SENDER_SEARCH_KEY = - new MAPIProperty(0xc1d, BINARY, "SenderSearchKey", "PR_SENDER_SEARCH_KEY"); - public static final MAPIProperty SENSITIVITY = - new MAPIProperty(0x36, LONG, "Sensitivity", "PR_SENSITIVITY"); - public static final MAPIProperty SENT_REPRESENTING_ADDRTYPE = - new MAPIProperty(100, ASCII_STRING, "SentRepresentingAddrtype", "PR_SENT_REPRESENTING_ADDRTYPE"); - public static final MAPIProperty SENT_REPRESENTING_EMAIL_ADDRESS = - new MAPIProperty(0x65, ASCII_STRING, "SentRepresentingEmailAddress", "PR_SENT_REPRESENTING_EMAIL_ADDRESS"); - public static final MAPIProperty SENT_REPRESENTING_ENTRY_ID = - new MAPIProperty(0x41, BINARY, "SentRepresentingEntryId", "PR_SENT_REPRESENTING_ENTRYID"); - public static final MAPIProperty SENT_REPRESENTING_NAME = - new MAPIProperty(0x42, ASCII_STRING, "SentRepresentingName", "PR_SENT_REPRESENTING_NAME"); - public static final MAPIProperty SENT_REPRESENTING_SEARCH_KEY = - new MAPIProperty(0x3b, BINARY, "SentRepresentingSearchKey", "PR_SENT_REPRESENTING_SEARCH_KEY"); - public static final MAPIProperty SENTMAIL_ENTRY_ID = - new MAPIProperty(0xe0a, BINARY, "SentmailEntryId", "PR_SENTMAIL_ENTRYID"); - public static final MAPIProperty SERVICE_DELETE_FILES = - new MAPIProperty(0x3d10, Types.createCustom(4126), "ServiceDeleteFiles", "PR_SERVICE_DELETE_FILES"); - public static final MAPIProperty SERVICE_DLL_NAME = - new MAPIProperty(0x3d0a, ASCII_STRING, "ServiceDllName", "PR_SERVICE_DLL_NAME"); - public static final MAPIProperty SERVICE_ENTRY_NAME = - new MAPIProperty(0x3d0b, ASCII_STRING, "ServiceEntryName", "PR_SERVICE_ENTRY_NAME"); - public static final MAPIProperty SERVICE_EXTRA_UIDS = - new MAPIProperty(0x3d0d, BINARY, "ServiceExtraUids", "PR_SERVICE_EXTRA_UIDS"); - public static final MAPIProperty SERVICE_NAME = - new MAPIProperty(0x3d09, ASCII_STRING, "ServiceName", "PR_SERVICE_NAME"); - public static final MAPIProperty SERVICE_SUPPORT_FILES = - new MAPIProperty(0x3d0f, Types.createCustom(4126), "ServiceSupportFiles", "PR_SERVICE_SUPPORT_FILES"); - public static final MAPIProperty SERVICE_UID = - new MAPIProperty(0x3d0c, BINARY, "ServiceUid", "PR_SERVICE_UID"); - public static final MAPIProperty SERVICES = - new MAPIProperty(0x3d0e, BINARY, "Services", "PR_SERVICES"); - public static final MAPIProperty SEVEN_BIT_DISPLAY_NAME = - new MAPIProperty(0x39ff, ASCII_STRING, "SevenBitDisplayName", "PR_SEVEN_BIT_DISPLAY_NAME"); - public static final MAPIProperty SMTP_ADDRESS = - new MAPIProperty(0x39fe, Types.UNICODE_STRING, "SmtpAddress", "PR_SMTP_ADDRESS"); - public static final MAPIProperty SPOOLER_STATUS = - new MAPIProperty(0xe10, LONG, "SpoolerStatus", "PR_SPOOLER_STATUS"); - public static final MAPIProperty SPOUSE_NAME = - new MAPIProperty(0x3a48, ASCII_STRING, "SpouseName", "PR_SPOUSE_NAME"); - public static final MAPIProperty START_DATE = - new MAPIProperty(0x60, TIME, "StartDate", "PR_START_DATE"); - public static final MAPIProperty STATE_OR_PROVINCE = - new MAPIProperty(0x3a28, ASCII_STRING, "StateOrProvince", "PR_STATE_OR_PROVINCE"); - public static final MAPIProperty STATUS = - new MAPIProperty(0x360b, LONG, "Status", "PR_STATUS"); - public static final MAPIProperty STATUS_CODE = - new MAPIProperty(0x3e04, LONG, "StatusCode", "PR_STATUS_CODE"); - public static final MAPIProperty STATUS_STRING = - new MAPIProperty(0x3e08, ASCII_STRING, "StatusString", "PR_STATUS_STRING"); - public static final MAPIProperty STORE_ENTRY_ID = - new MAPIProperty(0xffb, BINARY, "StoreEntryId", "PR_STORE_ENTRYID"); - public static final MAPIProperty STORE_PROVIDERS = - new MAPIProperty(0x3d00, BINARY, "StoreProviders", "PR_STORE_PROVIDERS"); - public static final MAPIProperty STORE_RECORD_KEY = - new MAPIProperty(0xffa, BINARY, "StoreRecordKey", "PR_STORE_RECORD_KEY"); - public static final MAPIProperty STORE_STATE = - new MAPIProperty(0x340e, LONG, "StoreState", "PR_STORE_STATE"); - public static final MAPIProperty STORE_SUPPORT_MASK = - new MAPIProperty(0x340d, LONG, "StoreSupportMask", "PR_STORE_SUPPORT_MASK"); - public static final MAPIProperty STREET_ADDRESS = - new MAPIProperty(0x3a29, ASCII_STRING, "StreetAddress", "PR_STREET_ADDRESS"); - public static final MAPIProperty SUBFOLDERS = - new MAPIProperty(0x360a, BOOLEAN, "Subfolders", "PR_SUBFOLDERS"); - public static final MAPIProperty SUBJECT = - new MAPIProperty(0x37, ASCII_STRING, "Subject", "PR_SUBJECT"); - public static final MAPIProperty SUBJECT_IPM = - new MAPIProperty(0x38, BINARY, "SubjectIpm", "PR_SUBJECT_IPM"); - public static final MAPIProperty SUBJECT_PREFIX = - new MAPIProperty(0x3d, ASCII_STRING, "SubjectPrefix", "PR_SUBJECT_PREFIX"); - public static final MAPIProperty SUBMIT_FLAGS = - new MAPIProperty(0xe14, LONG, "SubmitFlags", "PR_SUBMIT_FLAGS"); - public static final MAPIProperty SUPERSEDES = - new MAPIProperty(0x103a, ASCII_STRING, "Supersedes", "PR_SUPERSEDES"); - public static final MAPIProperty SUPPLEMENTARY_INFO = - new MAPIProperty(0xc1b, ASCII_STRING, "SupplementaryInfo", "PR_SUPPLEMENTARY_INFO"); - public static final MAPIProperty SURNAME = - new MAPIProperty(0x3a11, ASCII_STRING, "Surname", "PR_SURNAME"); - public static final MAPIProperty TELEX_NUMBER = - new MAPIProperty(0x3a2c, ASCII_STRING, "TelexNumber", "PR_TELEX_NUMBER"); - public static final MAPIProperty TEMPLATEID = - new MAPIProperty(0x3902, BINARY, "Templateid", "PR_TEMPLATEID"); - public static final MAPIProperty TITLE = - new MAPIProperty(0x3a17, ASCII_STRING, "Title", "PR_TITLE"); - public static final MAPIProperty TNEF_CORRELATION_KEY = - new MAPIProperty(0x7f, BINARY, "TnefCorrelationKey", "PR_TNEF_CORRELATION_KEY"); - public static final MAPIProperty TRANSMITABLE_DISPLAY_NAME = - new MAPIProperty(0x3a20, ASCII_STRING, "TransmitableDisplayName", "PR_TRANSMITABLE_DISPLAY_NAME"); - public static final MAPIProperty TRANSPORT_KEY = - new MAPIProperty(0xe16, LONG, "TransportKey", "PR_TRANSPORT_KEY"); - public static final MAPIProperty TRANSPORT_MESSAGE_HEADERS = - new MAPIProperty(0x7d, ASCII_STRING, "TransportMessageHeaders", "PR_TRANSPORT_MESSAGE_HEADERS"); - public static final MAPIProperty TRANSPORT_PROVIDERS = - new MAPIProperty(0x3d02, BINARY, "TransportProviders", "PR_TRANSPORT_PROVIDERS"); - public static final MAPIProperty TRANSPORT_STATUS = - new MAPIProperty(0xe11, LONG, "TransportStatus", "PR_TRANSPORT_STATUS"); - public static final MAPIProperty TTYTDD_PHONE_NUMBER = - new MAPIProperty(0x3a4b, ASCII_STRING, "TtytddPhoneNumber", "PR_TTYTDD_PHONE_NUMBER"); - public static final MAPIProperty TYPE_OF_MTS_USER = - new MAPIProperty(0xc1c, LONG, "TypeOfMtsUser", "PR_TYPE_OF_MTS_USER"); - public static final MAPIProperty USER_CERTIFICATE = - new MAPIProperty(0x3a22, BINARY, "UserCertificate", "PR_USER_CERTIFICATE"); - public static final MAPIProperty USER_X509_CERTIFICATE = - new MAPIProperty(0x3a70, Types.createCustom(4354), "UserX509Certificate", "PR_USER_X509_CERTIFICATE"); - public static final MAPIProperty VALID_FOLDER_MASK = - new MAPIProperty(0x35df, LONG, "ValidFolderMask", "PR_VALID_FOLDER_MASK"); - public static final MAPIProperty VIEWS_ENTRY_ID = - new MAPIProperty(0x35e5, BINARY, "ViewsEntryId", "PR_VIEWS_ENTRYID"); - public static final MAPIProperty WEDDING_ANNIVERSARY = - new MAPIProperty(0x3a41, TIME, "WeddingAnniversary", "PR_WEDDING_ANNIVERSARY"); - public static final MAPIProperty X400_CONTENT_TYPE = - new MAPIProperty(60, BINARY, "X400ContentType", "PR_X400_CONTENT_TYPE"); - public static final MAPIProperty X400_DEFERRED_DELIVERY_CANCEL = - new MAPIProperty(0x3e09, BOOLEAN, "X400DeferredDeliveryCancel", "PR_X400_DEFERRED_DELIVERY_CANCEL"); - public static final MAPIProperty XPOS = - new MAPIProperty(0x3f05, LONG, "Xpos", "PR_XPOS"); - public static final MAPIProperty YPOS = - new MAPIProperty(0x3f06, LONG, "Ypos", "PR_YPOS"); - - public static final MAPIProperty UNKNOWN = - new MAPIProperty(-1, Types.UNKNOWN, "Unknown", null); - - // 0x8??? ones are outlook specific, and not standard MAPI - // TODO See http://msdn.microsoft.com/en-us/library/ee157150%28v=exchg.80%29 - // for some - // info on how we might decode them properly in the future - private static final int ID_FIRST_CUSTOM = 0x8000; - private static final int ID_LAST_CUSTOM = 0xFFFE; - - /* --------------------------------------------------------------------- */ - - public final int id; - public final MAPIType usualType; - public final String name; - public final String mapiProperty; - - private MAPIProperty(int id, MAPIType usualType, String name, - String mapiProperty) { - this.id = id; - this.usualType = usualType; - this.name = name; - this.mapiProperty = mapiProperty; - - // If it isn't unknown or custom, store it for lookup - if (id == -1 - || (id >= ID_FIRST_CUSTOM && id <= ID_LAST_CUSTOM) - || (this instanceof CustomMAPIProperty)) { - // Custom/Unknown, skip - } else { - if (attributes.containsKey(id)) { - throw new IllegalArgumentException( - "Duplicate MAPI Property with ID " + id + " : " - + toString() + " vs " - + attributes.get(id).toString()); - } - attributes.put(id, this); - } - } - - public String asFileName() { - String str = Integer.toHexString(id).toUpperCase(Locale.ROOT); - while (str.length() < 4) { - str = "0" + str; - } - return str + usualType.asFileEnding(); - } - - @Override - public String toString() { - StringBuffer str = new StringBuffer(); - str.append(name); - str.append(" ["); - str.append(id); - str.append("]"); - if (mapiProperty != null) { - str.append(" ("); - str.append(mapiProperty); - str.append(")"); - } - return str.toString(); - } - - public static MAPIProperty get(int id) { - MAPIProperty attr = attributes.get(id); - if (attr != null) { - return attr; - } else { - return UNKNOWN; - } - } - - public static Collection getAll() { - return Collections.unmodifiableCollection(attributes.values()); - } - - public static MAPIProperty createCustom(int id, MAPIType type, String name) { - return new CustomMAPIProperty(id, type, name, null); - } - - private static class CustomMAPIProperty extends MAPIProperty { - private CustomMAPIProperty(int id, MAPIType usualType, String name, String mapiProperty) { - super(id, usualType, name, mapiProperty); - } - } -} diff --git a/src/scratchpad/src/org/apache/poi/hsmf/datatypes/MessagePropertiesChunk.java b/src/scratchpad/src/org/apache/poi/hsmf/datatypes/MessagePropertiesChunk.java deleted file mode 100644 index ecc11a176..000000000 --- a/src/scratchpad/src/org/apache/poi/hsmf/datatypes/MessagePropertiesChunk.java +++ /dev/null @@ -1,91 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hsmf.datatypes; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import org.apache.poi.util.LittleEndian; - -/** - * A {@link PropertiesChunk} for a Message or Embedded-Message. This has a 32 - * byte header - */ -public class MessagePropertiesChunk extends PropertiesChunk { - private long nextRecipientId; - private long nextAttachmentId; - private long recipientCount; - private long attachmentCount; - - public MessagePropertiesChunk(ChunkGroup parentGroup) { - super(parentGroup); - } - - public long getNextRecipientId() { - return nextRecipientId; - } - - public long getNextAttachmentId() { - return nextAttachmentId; - } - - public long getRecipientCount() { - return recipientCount; - } - - public long getAttachmentCount() { - return attachmentCount; - } - - @Override - public void readValue(InputStream stream) throws IOException { - // 8 bytes of reserved zeros - LittleEndian.readLong(stream); - - // Nexts and counts - nextRecipientId = LittleEndian.readUInt(stream); - nextAttachmentId = LittleEndian.readUInt(stream); - recipientCount = LittleEndian.readUInt(stream); - attachmentCount = LittleEndian.readUInt(stream); - - // 8 bytes of reserved zeros - LittleEndian.readLong(stream); - - // Now properties - readProperties(stream); - } - - @Override - public void writeValue(OutputStream out) throws IOException { - // 8 bytes of reserved zeros - out.write(new byte[8]); - - // Nexts and counts - LittleEndian.putUInt(nextRecipientId, out); - LittleEndian.putUInt(nextAttachmentId, out); - LittleEndian.putUInt(recipientCount, out); - LittleEndian.putUInt(attachmentCount, out); - - // 8 bytes of reserved zeros - out.write(new byte[8]); - - // Now properties - writeProperties(out); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hsmf/datatypes/MessageSubmissionChunk.java b/src/scratchpad/src/org/apache/poi/hsmf/datatypes/MessageSubmissionChunk.java deleted file mode 100644 index d92391b49..000000000 --- a/src/scratchpad/src/org/apache/poi/hsmf/datatypes/MessageSubmissionChunk.java +++ /dev/null @@ -1,137 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hsmf.datatypes; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.charset.Charset; -import java.util.Calendar; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.poi.hsmf.datatypes.Types.MAPIType; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.LocaleUtil; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; - -/** - * A Chunk that holds the details given back by the server at submission time. - * This includes the date the message was given to the server, and an ID that's - * used if you want to cancel a message or similar - */ -public class MessageSubmissionChunk extends Chunk { - private static final POILogger LOG = POILogFactory.getLogger(MessageSubmissionChunk.class); - private String rawId; - private Calendar date; - - private static final Pattern datePatern = Pattern - .compile("(\\d\\d)(\\d\\d)(\\d\\d)(\\d\\d)(\\d\\d)(\\d\\d)Z?"); - - /** - * Creates a Byte Chunk. - */ - public MessageSubmissionChunk(String namePrefix, int chunkId, - MAPIType type) { - super(namePrefix, chunkId, type); - } - - /** - * Create a Byte Chunk, with the specified type. - */ - public MessageSubmissionChunk(int chunkId, MAPIType type) { - super(chunkId, type); - } - - @Override - public void readValue(InputStream value) throws IOException { - // Stored in the file as us-ascii - byte[] data = IOUtils.toByteArray(value); - rawId = new String(data, Charset.forName("ASCII")); - - // Now process the date - String[] parts = rawId.split(";"); - for (String part : parts) { - if (part.startsWith("l=")) { - // Format of this bit appears to be l=-
  • "Set to 0 for variant 1"
  • "Set to 1 for variant 2" - */ - private static BitField _fComplex = new BitField( 0x0001 ); - - /** - * "Index to a grpprl stored in CLX portion of file" - */ - private static BitField _figrpprl = new BitField( 0xfffe ); - - /** - * "Index to entry into rgsprmPrm" - */ - private static BitField _fisprm = new BitField( 0x00fe ); - - /** - * "sprm's operand" - */ - private static BitField _fval = new BitField( 0xff00 ); - - private short value; - - public PropertyModifier( short value ) - { - this.value = value; - } - - @Override - protected PropertyModifier clone() throws CloneNotSupportedException - { - return new PropertyModifier( value ); - } - - @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - return true; - if ( obj == null ) - return false; - if ( getClass() != obj.getClass() ) - return false; - PropertyModifier other = (PropertyModifier) obj; - if ( value != other.value ) - return false; - return true; - } - - /** - * "Index to a grpprl stored in CLX portion of file" - */ - public short getIgrpprl() - { - if ( !isComplex() ) - throw new IllegalStateException( "Not complex" ); - - return _figrpprl.getShortValue( value ); - } - - public short getIsprm() - { - if ( isComplex() ) - throw new IllegalStateException( "Not simple" ); - - return _fisprm.getShortValue( value ); - } - - public short getVal() - { - if ( isComplex() ) - throw new IllegalStateException( "Not simple" ); - - return _fval.getShortValue( value ); - } - - public short getValue() - { - return value; - } - - @Override - public int hashCode() - { - final int prime = 31; - int result = 1; - result = prime * result + value; - return result; - } - - public boolean isComplex() - { - return _fComplex.isSet( value ); - } - - @Override - public String toString() - { - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append( "[PRM] (complex: " ); - stringBuilder.append( isComplex() ); - stringBuilder.append( "; " ); - if ( isComplex() ) - { - stringBuilder.append( "igrpprl: " ); - stringBuilder.append( getIgrpprl() ); - stringBuilder.append( "; " ); - } - else - { - stringBuilder.append( "isprm: " ); - stringBuilder.append( getIsprm() ); - stringBuilder.append( "; " ); - stringBuilder.append( "val: " ); - stringBuilder.append( getVal() ); - stringBuilder.append( "; " ); - } - stringBuilder.append( ")" ); - return stringBuilder.toString(); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/model/PropertyNode.java b/src/scratchpad/src/org/apache/poi/hwpf/model/PropertyNode.java deleted file mode 100644 index 2b307e199..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/model/PropertyNode.java +++ /dev/null @@ -1,186 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.model; - -import java.util.Arrays; -import java.util.Comparator; - -import org.apache.poi.util.Internal; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; - -/** - * Represents a lightweight node in the Trees used to store content - * properties. - * This only ever works in characters. For the few odd cases when - * the start and end aren't in characters (eg PAPX and CHPX), use - * {@link BytePropertyNode} between you and this. - * - * @author Ryan Ackley - */ -@Internal -public abstract class PropertyNode> implements Comparable, Cloneable { - - public static final class EndComparator implements - Comparator> { - public static final EndComparator instance = new EndComparator(); - - public int compare(PropertyNode o1, PropertyNode o2) { - int thisVal = o1.getEnd(); - int anotherVal = o2.getEnd(); - return (thisVal < anotherVal ? -1 : (thisVal == anotherVal ? 0 - : 1)); - } - } - - public static final class StartComparator implements - Comparator> { - public static final StartComparator instance = new StartComparator(); - - public int compare(PropertyNode o1, PropertyNode o2) { - int thisVal = o1.getStart(); - int anotherVal = o2.getStart(); - return (thisVal < anotherVal ? -1 : (thisVal == anotherVal ? 0 - : 1)); - } - } - - private final static POILogger _logger = POILogFactory.getLogger(PropertyNode.class); - protected Object _buf; - /** - * The start, in characters - */ - private int _cpStart; - /** - * The end, in characters - */ - private int _cpEnd; - - - /** - * @param fcStart The start of the text for this property, in characters. - * @param fcEnd The end of the text for this property, in characters. - * @param buf FIXME: Old documentation is: "grpprl The property description in compressed form." - */ - protected PropertyNode(int fcStart, int fcEnd, Object buf) { - _cpStart = fcStart; - _cpEnd = fcEnd; - _buf = buf; - - if (_cpStart < 0) { - _logger.log(POILogger.WARN, "A property claimed to start before zero, at " + _cpStart + "! Resetting it to zero, and hoping for the best"); - _cpStart = 0; - } - - if (_cpEnd < _cpStart) { - _logger.log(POILogger.WARN, "A property claimed to end (" + _cpEnd - + ") before start! " - + "Resetting end to start, and hoping for the best"); - _cpEnd = _cpStart; - } - } - - /** - * @return The start offset of this property's text. - */ - public int getStart() { - return _cpStart; - } - - public void setStart(int start) { - _cpStart = start; - } - - /** - * @return The offset of the end of this property's text. - */ - public int getEnd() { - return _cpEnd; - } - - public void setEnd(int end) { - _cpEnd = end; - } - - /** - * Adjust for a deletion that can span multiple PropertyNodes. - * - * @param start - * @param length - */ - public void adjustForDelete(int start, int length) { - int end = start + length; - - if (_cpEnd > start) { - // The start of the change is before we end - - if (_cpStart < end) { - // The delete was somewhere in the middle of us - _cpEnd = end >= _cpEnd ? start : _cpEnd - length; - _cpStart = Math.min(start, _cpStart); - } else { - // The delete was before us - _cpEnd -= length; - _cpStart -= length; - } - } - } - - protected boolean limitsAreEqual(Object o) { - return ((PropertyNode) o).getStart() == _cpStart && - ((PropertyNode) o).getEnd() == _cpEnd; - - } - - @Override - public int hashCode() { - return this._cpStart * 31 + this._buf.hashCode(); - } - - public boolean equals(Object o) { - if (!(o instanceof PropertyNode)) return false; - - if (limitsAreEqual(o)) { - Object testBuf = ((PropertyNode) o)._buf; - if (testBuf instanceof byte[] && _buf instanceof byte[]) { - return Arrays.equals((byte[]) testBuf, (byte[]) _buf); - } - return _buf.equals(testBuf); - } - return false; - } - - @SuppressWarnings("unchecked") - public T clone() throws CloneNotSupportedException { - return (T) super.clone(); - } - - /** - * Used for sorting in collections. - */ - public int compareTo(T o) { - int cpEnd = o.getEnd(); - if (_cpEnd == cpEnd) { - return 0; - } else if (_cpEnd < cpEnd) { - return -1; - } else { - return 1; - } - } -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/model/RevisionMarkAuthorTable.java b/src/scratchpad/src/org/apache/poi/hwpf/model/RevisionMarkAuthorTable.java deleted file mode 100644 index b1347d0e7..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/model/RevisionMarkAuthorTable.java +++ /dev/null @@ -1,96 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.model; - -import java.io.IOException; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import org.apache.poi.hwpf.model.io.HWPFOutputStream; -import org.apache.poi.util.Internal; - -/** - * String table containing the names of authors of revision marks, e-mails and - * comments in this document. - * - * @author Ryan Lauck - */ -@Internal -public final class RevisionMarkAuthorTable { - /** - * Array of entries. - */ - private String[] entries; - - /** - * Constructor to read the table from the table stream. - * - * @param tableStream the table stream. - * @param offset the offset into the byte array. - * @param size the size of the table in the byte array. - */ - public RevisionMarkAuthorTable( byte[] tableStream, int offset, int size ) - throws IOException - { - entries = SttbUtils.readSttbfRMark( tableStream, offset ); - } - - /** - * Gets the entries. The returned list cannot be modified. - * - * @return the list of entries. - */ - public List getEntries() { - return Collections.unmodifiableList(Arrays.asList(entries)); - } - - /** - * Get an author by its index. Returns null if it does not exist. - * - * @return the revision mark author - */ - public String getAuthor(int index) { - String auth = null; - if(index >= 0 && index < entries.length) { - auth = entries[index]; - } - return auth; - } - - /** - * Gets the number of entries. - * - * @return the number of entries. - */ - public int getSize() { - return entries.length; - } - - /** - * Writes this table to the table stream. - * - * @param tableStream the table stream to write to. - * @throws IOException if an error occurs while writing. - */ - public void writeTo( HWPFOutputStream tableStream ) throws IOException - { - SttbUtils.writeSttbfRMark( entries, tableStream ); - } - -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/model/SEPX.java b/src/scratchpad/src/org/apache/poi/hwpf/model/SEPX.java deleted file mode 100644 index b9bdff1af..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/model/SEPX.java +++ /dev/null @@ -1,89 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.model; - -import org.apache.poi.hwpf.sprm.SectionSprmCompressor; -import org.apache.poi.hwpf.sprm.SectionSprmUncompressor; -import org.apache.poi.hwpf.sprm.SprmBuffer; -import org.apache.poi.hwpf.usermodel.SectionProperties; -import org.apache.poi.util.Internal; - -@Internal -public final class SEPX extends PropertyNode -{ - - SectionProperties sectionProperties; - - SectionDescriptor _sed; - - public SEPX( SectionDescriptor sed, int start, int end, byte[] grpprl ) - { - super( start, end, new SprmBuffer( grpprl, 0 ) ); - _sed = sed; - } - - public byte[] getGrpprl() - { - if ( sectionProperties != null ) - { - byte[] grpprl = SectionSprmCompressor - .compressSectionProperty( sectionProperties ); - _buf = new SprmBuffer( grpprl, 0 ); - } - - return ( (SprmBuffer) _buf ).toByteArray(); - } - - public SectionDescriptor getSectionDescriptor() - { - return _sed; - } - - public SectionProperties getSectionProperties() - { - if ( sectionProperties == null ) - { - sectionProperties = SectionSprmUncompressor.uncompressSEP( - ( (SprmBuffer) _buf ).toByteArray(), 0 ); - } - return sectionProperties; - } - - @Override - public boolean equals( Object o ) - { - if (!(o instanceof SEPX)) return false; - SEPX sepx = (SEPX) o; - if ( super.equals( o ) ) - { - return sepx._sed.equals( _sed ); - } - return false; - } - - @Override - public int hashCode() { - assert false : "hashCode not designed"; - return 42; // any arbitrary constant will do - } - - public String toString() - { - return "SEPX from " + getStart() + " to " + getEnd(); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/model/SavedByEntry.java b/src/scratchpad/src/org/apache/poi/hwpf/model/SavedByEntry.java deleted file mode 100644 index 2e15092a9..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/model/SavedByEntry.java +++ /dev/null @@ -1,88 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.model; - -import org.apache.poi.util.Internal; - - -/** - * A single entry in the {@link SavedByTable}. - * - * @author Daniel Noll - */ -@Internal -public final class SavedByEntry -{ - private String userName; - private String saveLocation; - - public SavedByEntry(String userName, String saveLocation) - { - this.userName = userName; - this.saveLocation = saveLocation; - } - - public String getUserName() - { - return userName; - } - - public String getSaveLocation() - { - return saveLocation; - } - - /** - * Compares this object with another, for equality. - * - * @param other the object to compare to this one. - * @return true iff the other object is equal to this one. - */ - public boolean equals(Object other) - { - if (other == this) return true; - if (!(other instanceof SavedByEntry)) return false; - SavedByEntry that = (SavedByEntry) other; - return that.userName.equals(userName) && - that.saveLocation.equals(saveLocation); - } - - /** - * Generates a hash code for consistency with {@link #equals(Object)}. - * - * @return the hash code. - */ - public int hashCode() - { - int hash = 29; - hash = hash * 13 + userName.hashCode(); - hash = hash * 13 + saveLocation.hashCode(); - return hash; - } - - /** - * Returns a string for display. - * - * @return the string. - */ - public String toString() - { - return "SavedByEntry[userName=" + getUserName() + - ",saveLocation=" + getSaveLocation() + "]"; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/model/SavedByTable.java b/src/scratchpad/src/org/apache/poi/hwpf/model/SavedByTable.java deleted file mode 100644 index 87c7a8ef9..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/model/SavedByTable.java +++ /dev/null @@ -1,92 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hwpf.model; - -import java.io.IOException; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import org.apache.poi.hwpf.model.io.HWPFOutputStream; -import org.apache.poi.util.Internal; - -/** - * String table containing the history of the last few revisions ("saves") of - * the document. Read-only for the time being. - * - * @author Daniel Noll - */ -@Internal -public final class SavedByTable -{ - /** - * Array of entries. - */ - private SavedByEntry[] entries; - - /** - * Constructor to read the table from the table stream. - * - * @param tableStream - * the table stream. - * @param offset - * the offset into the byte array. - * @param size - * the size of the table in the byte array. - */ - public SavedByTable( byte[] tableStream, int offset, int size ) - { - String[] strings = SttbUtils.readSttbSavedBy( tableStream, offset ); - int numEntries = strings.length / 2; - entries = new SavedByEntry[numEntries]; - for ( int i = 0; i < numEntries; i++ ) - { - entries[i] = new SavedByEntry( strings[i * 2], strings[i * 2 + 1] ); - } - } - - /** - * Gets the entries. The returned list cannot be modified. - * - * @return the list of entries. - */ - public List getEntries() - { - return Collections.unmodifiableList( Arrays.asList( entries ) ); - } - - /** - * Writes this table to the table stream. - * - * @param tableStream - * the table stream to write to. - * @throws IOException - * if an error occurs while writing. - */ - public void writeTo( HWPFOutputStream tableStream ) throws IOException - { - String[] toSave = new String[entries.length * 2]; - int counter = 0; - for ( SavedByEntry entry : entries ) - { - toSave[counter++] = entry.getUserName(); - toSave[counter++] = entry.getSaveLocation(); - } - SttbUtils.writeSttbSavedBy( toSave, tableStream ); - } - -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/model/SectionDescriptor.java b/src/scratchpad/src/org/apache/poi/hwpf/model/SectionDescriptor.java deleted file mode 100644 index fead9ebcc..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/model/SectionDescriptor.java +++ /dev/null @@ -1,116 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.model; - -import org.apache.poi.util.Internal; -import org.apache.poi.util.LittleEndian; - -/** - * Section Descriptor (SED) - * - * See page 186 for details. - */ -@Internal -public final class SectionDescriptor -{ - - /** - * "Used internally by Word" - */ - private short fn; - - /** - * "File offset in main stream to beginning of SEPX stored for section. If - * sed.fcSepx==0xFFFFFFFF, the section properties for the section are equal - * to the standard SEP (see SEP definition)." - */ - private int fcSepx; - - /** - * "Used internally by Word" - */ - private short fnMpr; - - /** - * "Points to offset in FC space of main stream where the Macintosh Print - * Record for a document created on a Macintosh will be stored" - */ - private int fcMpr; - - public SectionDescriptor() - { - } - - public SectionDescriptor(byte[] buf, int offset) - { - fn = LittleEndian.getShort(buf, offset); - offset += LittleEndian.SHORT_SIZE; - fcSepx = LittleEndian.getInt(buf, offset); - offset += LittleEndian.INT_SIZE; - fnMpr = LittleEndian.getShort(buf, offset); - offset += LittleEndian.SHORT_SIZE; - fcMpr = LittleEndian.getInt(buf, offset); - } - - public int getFc() - { - return fcSepx; - } - - public void setFc(int fc) - { - this.fcSepx = fc; - } - - @Override - public boolean equals(Object o) - { - if (!(o instanceof SectionDescriptor)) return false; - SectionDescriptor sed = (SectionDescriptor)o; - return sed.fn == fn && sed.fnMpr == fnMpr; - } - - @Override - public int hashCode() { - assert false : "hashCode not designed"; - return 42; // any arbitrary constant will do - } - - public byte[] toByteArray() - { - int offset = 0; - byte[] buf = new byte[12]; - - LittleEndian.putShort(buf, offset, fn); - offset += LittleEndian.SHORT_SIZE; - LittleEndian.putInt(buf, offset, fcSepx); - offset += LittleEndian.INT_SIZE; - LittleEndian.putShort(buf, offset, fnMpr); - offset += LittleEndian.SHORT_SIZE; - LittleEndian.putInt(buf, offset, fcMpr); - - return buf; - } - - @Override - public String toString() - { - return "[SED] (fn: " + fn + "; fcSepx: " + fcSepx + "; fnMpr: " + fnMpr - + "; fcMpr: " + fcMpr + ")"; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/model/SectionTable.java b/src/scratchpad/src/org/apache/poi/hwpf/model/SectionTable.java deleted file mode 100644 index ec93d56e5..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/model/SectionTable.java +++ /dev/null @@ -1,227 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.model; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import org.apache.poi.hwpf.model.io.HWPFFileSystem; -import org.apache.poi.hwpf.model.io.HWPFOutputStream; -import org.apache.poi.util.Internal; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; - -/** - * @author Ryan Ackley - */ -@Internal -public class SectionTable -{ - private final static POILogger _logger = POILogFactory.getLogger(SectionTable.class); - private static final int SED_SIZE = 12; - - protected List _sections = new ArrayList(); - protected List _text; - - /** So we can know if things are unicode or not */ - //private TextPieceTable tpt; - - public SectionTable() - { - } - - - public SectionTable( - byte[] documentStream, byte[] tableStream, - int offset, int size, int fcMin, TextPieceTable tpt, int mainLength) - { - PlexOfCps sedPlex = new PlexOfCps(tableStream, offset, size, SED_SIZE); - //this.tpt = tpt; - this._text = tpt.getTextPieces(); - - int length = sedPlex.length(); - - for (int x = 0; x < length; x++) - { - GenericPropertyNode node = sedPlex.getProperty(x); - SectionDescriptor sed = new SectionDescriptor(node.getBytes(), 0); - - int fileOffset = sed.getFc(); - // int startAt = CPtoFC(node.getStart()); - // int endAt = CPtoFC(node.getEnd()); - int startAt = node.getStart(); - int endAt = node.getEnd(); - - // check for the optimization - if (fileOffset == 0xffffffff) - { - _sections.add(new SEPX(sed, startAt, endAt, new byte[0])); - } - else - { - // The first short at the offset is the size of the grpprl. - int sepxSize = LittleEndian.getShort(documentStream, fileOffset); - byte[] buf = new byte[sepxSize]; - fileOffset += LittleEndian.SHORT_SIZE; - System.arraycopy(documentStream, fileOffset, buf, 0, buf.length); - _sections.add(new SEPX(sed, startAt, endAt, buf)); - } - } - - // Some files seem to lie about their unicode status, which - // is very very pesky. Try to work around these, but this - // is getting on for black magic... - int mainEndsAt = mainLength; - boolean matchAt = false; - boolean matchHalf = false; - for (int i=0; i<_sections.size(); i++) { - SEPX s = _sections.get(i); - if (s.getEnd() == mainEndsAt) { - matchAt = true; - } else if(s.getEnd() == mainEndsAt || s.getEnd() == mainEndsAt-1) { - matchHalf = true; - } - } - if(! matchAt && matchHalf) { - _logger.log(POILogger.WARN, "Your document seemed to be mostly unicode, but the section definition was in bytes! Trying anyway, but things may well go wrong!"); - for(int i=0; i<_sections.size(); i++) { - SEPX s = _sections.get(i); - GenericPropertyNode node = sedPlex.getProperty(i); - - // s.setStart( CPtoFC(node.getStart()) ); - // s.setEnd( CPtoFC(node.getEnd()) ); - int startAt = node.getStart(); - int endAt = node.getEnd(); - s.setStart( startAt ); - s.setEnd( endAt ); - } - } - - Collections.sort( _sections, PropertyNode.StartComparator.instance ); - } - - public void adjustForInsert(int listIndex, int length) - { - int size = _sections.size(); - SEPX sepx = _sections.get(listIndex); - sepx.setEnd(sepx.getEnd() + length); - - for (int x = listIndex + 1; x < size; x++) - { - sepx = _sections.get(x); - sepx.setStart(sepx.getStart() + length); - sepx.setEnd(sepx.getEnd() + length); - } - } - - // goss version of CPtoFC - this takes into account non-contiguous textpieces - // that we have come across in real world documents. Tests against the example - // code in HWPFDocument show no variation to Ryan's version of the code in - // normal use, but this version works with our non-contiguous test case. - // So far unable to get this test case to be written out as well due to - // other issues. - piers - // - // i'm commenting this out, because it just doesn't work with non-contiguous - // textpieces :( Usual (as for PAPX and CHPX) call to TextPiecesTable does. - // private int CPtoFC(int CP) - // { - // TextPiece TP = null; - // - // for(int i=_text.size()-1; i>-1; i--) - // { - // TP = _text.get(i); - // - // if(CP >= TP.getCP()) break; - // } - // int FC = TP.getPieceDescriptor().getFilePosition(); - // int offset = CP - TP.getCP(); - // if (TP.isUnicode()) { - // offset = offset*2; - // } - // FC = FC+offset; - // return FC; - // } - - public List getSections() - { - return _sections; - } - - @Deprecated - public void writeTo( HWPFFileSystem sys, int fcMin ) throws IOException - { - HWPFOutputStream docStream = sys.getStream( "WordDocument" ); - HWPFOutputStream tableStream = sys.getStream( "1Table" ); - - writeTo( docStream, tableStream ); - } - - public void writeTo( - HWPFOutputStream wordDocumentStream, - HWPFOutputStream tableStream ) throws IOException - { - - int offset = wordDocumentStream.getOffset(); - int len = _sections.size(); - PlexOfCps plex = new PlexOfCps(SED_SIZE); - - for (int x = 0; x < len; x++) - { - SEPX sepx = _sections.get(x); - byte[] grpprl = sepx.getGrpprl(); - - // write the sepx to the document stream. starts with a 2 byte size - // followed by the grpprl - byte[] shortBuf = new byte[2]; - LittleEndian.putShort(shortBuf, 0, (short)grpprl.length); - - wordDocumentStream.write(shortBuf); - wordDocumentStream.write(grpprl); - - // set the fc in the section descriptor - SectionDescriptor sed = sepx.getSectionDescriptor(); - sed.setFc(offset); - - // add the section descriptor bytes to the PlexOfCps. - - /* original line */ - GenericPropertyNode property = new GenericPropertyNode( - sepx.getStart(), sepx.getEnd(), sed.toByteArray() ); - /* - * Line using Ryan's FCtoCP() conversion method - unable to observe - * any effect on our testcases when using this code - piers - */ - /* - * there is an effect on Bug45743.doc actually. writeoutreadback - * changes byte offset of chars (but preserve string offsets). - * Changing back to original lines - sergey - */ - // GenericPropertyNode property = new GenericPropertyNode( - // tpt.getCharIndex( sepx.getStartBytes() ), - // tpt.getCharIndex( sepx.getEndBytes() ), sed.toByteArray() ); - - plex.addProperty(property); - - offset = wordDocumentStream.getOffset(); - } - tableStream.write(plex.toByteArray()); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/model/SinglentonTextPiece.java b/src/scratchpad/src/org/apache/poi/hwpf/model/SinglentonTextPiece.java deleted file mode 100644 index 9388a1437..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/model/SinglentonTextPiece.java +++ /dev/null @@ -1,65 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hwpf.model; - -import org.apache.poi.util.Internal; -import org.apache.poi.util.StringUtil; - -@Internal -public class SinglentonTextPiece extends TextPiece -{ - - public SinglentonTextPiece( StringBuilder buffer ) - { - super( 0, buffer.length(), StringUtil.getToUnicodeLE(buffer.toString()), new PieceDescriptor( new byte[8], 0 ) ); - } - - @Override - public int bytesLength() - { - return getStringBuilder().length() * 2; - } - - @Override - public int characterLength() - { - return getStringBuilder().length(); - } - - @Override - public int getCP() - { - return 0; - } - - @Override - public int getEnd() - { - return characterLength(); - } - - @Override - public int getStart() - { - return 0; - } - - public String toString() - { - return "SinglentonTextPiece (" + characterLength() + " chars)"; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/model/StdfBase.java b/src/scratchpad/src/org/apache/poi/hwpf/model/StdfBase.java deleted file mode 100644 index e4c18b7b4..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/model/StdfBase.java +++ /dev/null @@ -1,80 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hwpf.model; - -import org.apache.poi.hwpf.model.types.StdfBaseAbstractType; -import org.apache.poi.util.Internal; - -/** - * The StdfBase structure specifies general information about a style. - */ -@Internal -class StdfBase extends StdfBaseAbstractType -{ - - public StdfBase() - { - } - - public StdfBase( byte[] std, int offset ) - { - fillFields( std, offset ); - } - - @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - return true; - if ( obj == null ) - return false; - if ( getClass() != obj.getClass() ) - return false; - StdfBase other = (StdfBase) obj; - if ( field_1_info1 != other.field_1_info1 ) - return false; - if ( field_2_info2 != other.field_2_info2 ) - return false; - if ( field_3_info3 != other.field_3_info3 ) - return false; - if ( field_4_bchUpe != other.field_4_bchUpe ) - return false; - if ( field_5_grfstd != other.field_5_grfstd ) - return false; - return true; - } - - @Override - public int hashCode() - { - final int prime = 31; - int result = 1; - result = prime * result + field_1_info1; - result = prime * result + field_2_info2; - result = prime * result + field_3_info3; - result = prime * result + field_4_bchUpe; - result = prime * result + field_5_grfstd; - return result; - } - - public byte[] serialize() - { - byte[] result = new byte[getSize()]; - serialize( result, 0 ); - return result; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/model/StdfPost2000.java b/src/scratchpad/src/org/apache/poi/hwpf/model/StdfPost2000.java deleted file mode 100644 index 479271819..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/model/StdfPost2000.java +++ /dev/null @@ -1,75 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hwpf.model; - -import org.apache.poi.hwpf.model.types.StdfPost2000AbstractType; -import org.apache.poi.util.Internal; - -/** - * The StdfBase structure specifies general information about a style. - */ -@Internal -class StdfPost2000 extends StdfPost2000AbstractType -{ - - public StdfPost2000() - { - } - - public StdfPost2000( byte[] std, int offset ) - { - fillFields( std, offset ); - } - - @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - return true; - if ( obj == null ) - return false; - if ( getClass() != obj.getClass() ) - return false; - StdfPost2000 other = (StdfPost2000) obj; - if ( field_1_info1 != other.field_1_info1 ) - return false; - if ( field_2_rsid != other.field_2_rsid ) - return false; - if ( field_3_info3 != other.field_3_info3 ) - return false; - return true; - } - - @Override - public int hashCode() - { - final int prime = 31; - int result = 1; - result = prime * result + field_1_info1; - result = prime * result - + (int) ( field_2_rsid ^ ( field_2_rsid >>> 32 ) ); - result = prime * result + field_3_info3; - return result; - } - - public byte[] serialize() - { - byte[] result = new byte[getSize()]; - serialize( result, 0 ); - return result; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/model/Stshif.java b/src/scratchpad/src/org/apache/poi/hwpf/model/Stshif.java deleted file mode 100644 index 448da7b3b..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/model/Stshif.java +++ /dev/null @@ -1,92 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hwpf.model; - -import org.apache.poi.hwpf.model.types.StshifAbstractType; -import org.apache.poi.util.Internal; - -/** - * The StdfBase structure specifies general information about a style. - */ -@Internal -class Stshif extends StshifAbstractType -{ - - public Stshif() - { - } - - public Stshif( byte[] std, int offset ) - { - fillFields( std, offset ); - } - - @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - return true; - if ( obj == null ) - return false; - if ( getClass() != obj.getClass() ) - return false; - Stshif other = (Stshif) obj; - if ( field_1_cstd != other.field_1_cstd ) - return false; - if ( field_2_cbSTDBaseInFile != other.field_2_cbSTDBaseInFile ) - return false; - if ( field_3_info3 != other.field_3_info3 ) - return false; - if ( field_4_stiMaxWhenSaved != other.field_4_stiMaxWhenSaved ) - return false; - if ( field_5_istdMaxFixedWhenSaved != other.field_5_istdMaxFixedWhenSaved ) - return false; - if ( field_6_nVerBuiltInNamesWhenSaved != other.field_6_nVerBuiltInNamesWhenSaved ) - return false; - if ( field_7_ftcAsci != other.field_7_ftcAsci ) - return false; - if ( field_8_ftcFE != other.field_8_ftcFE ) - return false; - if ( field_9_ftcOther != other.field_9_ftcOther ) - return false; - return true; - } - - @Override - public int hashCode() - { - final int prime = 31; - int result = 1; - result = prime * result + field_1_cstd; - result = prime * result + field_2_cbSTDBaseInFile; - result = prime * result + field_3_info3; - result = prime * result + field_4_stiMaxWhenSaved; - result = prime * result + field_5_istdMaxFixedWhenSaved; - result = prime * result + field_6_nVerBuiltInNamesWhenSaved; - result = prime * result + field_7_ftcAsci; - result = prime * result + field_8_ftcFE; - result = prime * result + field_9_ftcOther; - return result; - } - - public byte[] serialize() - { - byte[] result = new byte[getSize()]; - serialize( result, 0 ); - return result; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/model/Sttb.java b/src/scratchpad/src/org/apache/poi/hwpf/model/Sttb.java deleted file mode 100644 index f36519c9f..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/model/Sttb.java +++ /dev/null @@ -1,258 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hwpf.model; - -import java.util.Arrays; - -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.util.StringUtil; - -/** - * The STTB is a string table that is made up of a header that is followed by an - * array of elements. The cData value specifies the number of elements that are - * contained in the array. - *

    - * Class and fields descriptions are quoted from [MS-DOC] -- v20121003 Word - * (.doc) Binary File Format; Copyright (c) 2012 Microsoft Corporation; Release: - * October 8, 2012 - *

    - * This class is internal. It content or properties may change without notice - * due to changes in our knowledge of internal Microsoft Word binary structures. - * - * @author Sergey Vladimirov; according to [MS-DOC] -- v20121003 Word (.doc) - * Binary File Format; Copyright (c) 2012 Microsoft Corporation; - * Release: October 8, 2012 - */ -public class Sttb -{ - - private int _cbExtra; - - private final int _cDataLength; - - private String[] _data; - - private byte[][] _extraData; - - private final boolean _fExtend = true; - - public Sttb( byte[] buffer, int startOffset ) - { - this( 2, buffer, startOffset ); - } - - public Sttb( int cDataLength, byte[] buffer, int startOffset ) - { - this._cDataLength = cDataLength; - fillFields( buffer, startOffset ); - } - - public Sttb( int cDataLength, String[] data ) - { - this._cDataLength = cDataLength; - - this._data = Arrays.copyOf(data, data.length); - - this._cbExtra = 0; - this._extraData = null; - } - - public void fillFields( byte[] buffer, int startOffset ) - { - short ffff = LittleEndian.getShort( buffer, startOffset ); - int offset = startOffset + LittleEndian.SHORT_SIZE; - - if ( ffff != (short) 0xffff ) - { - POILogFactory.getLogger(Sttb.class).log( - POILogger.WARN, - "Non-extended character Pascal strings are not supported right now. " - + "Creating empty values in the RevisionMarkAuthorTable for now. " + - "Please, contact POI developers for update."); - //set data and extraData to empty values to avoid - //downstream NPE in case someone calls getEntries on RevisionMarkAuthorTable - _data = new String[0]; - _extraData = new byte[0][]; - - return; - } - // strings are extended character strings - - int cData = _cDataLength == 2 ? LittleEndian.getUShort( buffer, offset ) - : LittleEndian.getInt( buffer, offset ); - offset += _cDataLength; - - this._cbExtra = LittleEndian.getUShort( buffer, offset ); - offset += 2; - - _data = new String[cData]; - _extraData = new byte[cData][]; - - for ( int i = 0; i < cData; i++ ) - { - int cchData = LittleEndian.getShort( buffer, offset ); - offset += 2; - - if ( cchData < 0 ) - continue; - - _data[i] = StringUtil.getFromUnicodeLE( buffer, offset, cchData ); - offset += cchData * 2; - - _extraData[i] = LittleEndian - .getByteArray( buffer, offset, _cbExtra ); - offset += _cbExtra; - } - } - - /** - * The definition of each STTB specifies the meaning of this field. If this - * STTB uses extended characters, the size of this field is 2*cchData bytes - * and it is a Unicode string unless otherwise specified by the STTB - * definition. If this STTB does not use extended characters, then the size - * of this field is cchData bytes and it is an ANSI string, unless otherwise - * specified by the STTB definition. - */ - public String[] getData() - { - return _data; - } - - public int getSize() - { - // ffff - int size = LittleEndian.SHORT_SIZE; - - // cData - size += _cDataLength; - - // cbExtra - size += LittleEndian.SHORT_SIZE; - - if ( this._fExtend ) - { - for ( String data : _data ) - { - // cchData - size += LittleEndian.SHORT_SIZE; - // data - size += 2 * data.length(); - } - } - else - { - for ( String data : _data ) - { - // cchData - size += LittleEndian.BYTE_SIZE; - // data - size += 1 * data.length(); - } - } - - // extraData - if ( _extraData != null ) - { - size += _cbExtra * _data.length; - } - - return size; - } - - public byte[] serialize() - { - final byte[] buffer = new byte[getSize()]; - - LittleEndian.putShort( buffer, 0, (short) 0xffff ); - - if ( _data == null || _data.length == 0 ) - { - if ( _cDataLength == 4 ) - { - LittleEndian.putInt( buffer, 2, 0 ); - LittleEndian.putUShort( buffer, 6, _cbExtra ); - return buffer; - } - - LittleEndian.putUShort( buffer, 2, 0 ); - LittleEndian.putUShort( buffer, 4, _cbExtra ); - return buffer; - } - - int offset; - if ( _cDataLength == 4 ) - { - LittleEndian.putInt( buffer, 2, _data.length ); - LittleEndian.putUShort( buffer, 6, _cbExtra ); - offset = 2 + LittleEndian.INT_SIZE + LittleEndian.SHORT_SIZE; - } - else - { - LittleEndian.putUShort( buffer, 2, _data.length ); - LittleEndian.putUShort( buffer, 4, _cbExtra ); - offset = 2 + LittleEndian.SHORT_SIZE + LittleEndian.SHORT_SIZE; - } - - for ( int i = 0; i < _data.length; i++ ) - { - String entry = _data[i]; - if ( entry == null ) - { - // is it correct? - buffer[offset] = -1; - buffer[offset + 1] = 0; - offset += 2; - continue; - } - - if ( _fExtend ) - { - LittleEndian.putUShort( buffer, offset, entry.length() ); - offset += LittleEndian.SHORT_SIZE; - - StringUtil.putUnicodeLE( entry, buffer, offset ); - offset += 2 * entry.length(); - } - else - { - throw new UnsupportedOperationException( - "ANSI STTB is not supported yet" ); - } - - if ( _cbExtra != 0 ) - { - if ( _extraData[i] != null && _extraData[i].length != 0 ) - { - System.arraycopy( _extraData[i], 0, buffer, offset, - Math.min( _extraData[i].length, _cbExtra ) ); - } - offset += _cbExtra; - } - } - - return buffer; - } - - public int serialize( byte[] buffer, int offset ) - { - byte[] bs = serialize(); - System.arraycopy( bs, 0, buffer, offset, bs.length ); - return bs.length; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/model/SttbUtils.java b/src/scratchpad/src/org/apache/poi/hwpf/model/SttbUtils.java deleted file mode 100644 index fba473f9c..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/model/SttbUtils.java +++ /dev/null @@ -1,76 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hwpf.model; - -import java.io.IOException; - -import org.apache.poi.hwpf.model.io.HWPFOutputStream; -import org.apache.poi.util.Internal; - -/** - * Utils class for storing and reading "STring TaBle stored in File" - * - * @author Sergey Vladimirov (vlsergey {at} gmail {dot} com) - */ -@Internal -class SttbUtils -{ - - private static final int CDATA_SIZE_STTB_SAVED_BY = 2; // bytes - - private static final int CDATA_SIZE_STTBF_BKMK = 2; // bytes - - private static final int CDATA_SIZE_STTBF_R_MARK = 2; // bytes - - static String[] readSttbfBkmk( byte[] buffer, int startOffset ) - { - return new Sttb( CDATA_SIZE_STTBF_BKMK, buffer, startOffset ).getData(); - } - - static String[] readSttbfRMark( byte[] buffer, int startOffset ) - { - return new Sttb( CDATA_SIZE_STTBF_R_MARK, buffer, startOffset ) - .getData(); - } - - static String[] readSttbSavedBy( byte[] buffer, int startOffset ) - { - return new Sttb( CDATA_SIZE_STTB_SAVED_BY, buffer, startOffset ) - .getData(); - } - - static void writeSttbfBkmk( String[] data, HWPFOutputStream tableStream ) - throws IOException - { - tableStream.write( new Sttb( CDATA_SIZE_STTBF_BKMK, data ).serialize() ); - } - - static void writeSttbfRMark( String[] data, HWPFOutputStream tableStream ) - throws IOException - { - tableStream.write( new Sttb( CDATA_SIZE_STTBF_R_MARK, data ) - .serialize() ); - } - - static void writeSttbSavedBy( String[] data, HWPFOutputStream tableStream ) - throws IOException - { - tableStream.write( new Sttb( CDATA_SIZE_STTB_SAVED_BY, data ) - .serialize() ); - } - -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/model/StyleDescription.java b/src/scratchpad/src/org/apache/poi/hwpf/model/StyleDescription.java deleted file mode 100644 index d4415c46b..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/model/StyleDescription.java +++ /dev/null @@ -1,298 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.model; - -import java.util.Arrays; - -import org.apache.poi.hwpf.usermodel.CharacterProperties; -import org.apache.poi.hwpf.usermodel.ParagraphProperties; -import org.apache.poi.util.Internal; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.util.StringUtil; - -/** - * Comment me - * - * @author Ryan Ackley - */ -@Internal -public final class StyleDescription implements HDFType -{ - - private static final POILogger logger = POILogFactory.getLogger( StyleDescription.class ); - - private final static int PARAGRAPH_STYLE = 1; - private final static int CHARACTER_STYLE = 2; - // private final static int TABLE_STYLE = 3; - // private final static int NUMBERING_STYLE = 4; - - private int _baseLength; - private StdfBase _stdfBase; - private StdfPost2000 _stdfPost2000; - - UPX[] _upxs; - String _name; - @Deprecated - ParagraphProperties _pap; - @Deprecated - CharacterProperties _chp; - - public StyleDescription() - { -// _pap = new ParagraphProperties(); -// _chp = new CharacterProperties(); - } - public StyleDescription(byte[] std, int baseLength, int offset, boolean word9) - { - _baseLength = baseLength; - int nameStart = offset + baseLength; - - boolean readStdfPost2000 = false; - if ( baseLength == 0x0012 ) - { - readStdfPost2000 = true; - } - else if ( baseLength == 0x000A ) - { - readStdfPost2000 = false; - } - else - { - logger.log( POILogger.WARN, - "Style definition has non-standard size of ", - Integer.valueOf( baseLength ) ); - } - - _stdfBase = new StdfBase(std, offset); - offset += StdfBase.getSize(); - - if ( readStdfPost2000 ) - { - _stdfPost2000 = new StdfPost2000( std, offset ); - // offset += StdfPost2000.getSize(); - } - - //first byte(s) of variable length section of std is the length of the - //style name and aliases string - int nameLength = 0; - int multiplier = 1; - if(word9) - { - nameLength = LittleEndian.getShort(std, nameStart); - multiplier = 2; - nameStart += LittleEndian.SHORT_SIZE; - } - else - { - nameLength = std[nameStart]; - } - - _name = StringUtil.getFromUnicodeLE(std, nameStart, (nameLength*multiplier)/2); - - //length then null terminator. - int grupxStart = ((nameLength + 1) * multiplier) + nameStart; - - // the spec only refers to two possible upxs but it mentions - // that more may be added in the future - int varOffset = grupxStart; - int countOfUPX = _stdfBase.getCupx(); - _upxs = new UPX[countOfUPX]; - for(int x = 0; x < countOfUPX; x++) - { - int upxSize = LittleEndian.getShort(std, varOffset); - varOffset += LittleEndian.SHORT_SIZE; - - byte[] upx = new byte[upxSize]; - System.arraycopy(std, varOffset, upx, 0, upxSize); - _upxs[x] = new UPX(upx); - varOffset += upxSize; - - - // the upx will always start on a word boundary. - if((upxSize & 1) == 1) - { - ++varOffset; - } - - } - - - } - public int getBaseStyle() - { - return _stdfBase.getIstdBase(); - } - public byte[] getCHPX() - { - switch (_stdfBase.getStk()) - { - case PARAGRAPH_STYLE: - if (_upxs.length > 1) - { - return _upxs[1].getUPX(); - } - return null; - case CHARACTER_STYLE: - return _upxs[0].getUPX(); - default: - return null; - } - - } - public byte[] getPAPX() - { - switch (_stdfBase.getStk()) - { - case PARAGRAPH_STYLE: - return _upxs[0].getUPX(); - default: - return null; - } - } - @Deprecated - public ParagraphProperties getPAP() - { - return _pap; - } - @Deprecated - public CharacterProperties getCHP() - { - return _chp; - } - @Deprecated - void setPAP(ParagraphProperties pap) - { - _pap = pap; - } - @Deprecated - void setCHP(CharacterProperties chp) - { - _chp = chp; - } - - public String getName() - { - return _name; - } - - public byte[] toByteArray() - { - // size equals _baseLength bytes for known variables plus 2 bytes for name - // length plus name length * 2 plus 2 bytes for null plus upx's preceded by - // length - int size = _baseLength + 2 + ((_name.length() + 1) * 2); - - // determine the size needed for the upxs. They always fall on word - // boundaries. - size += _upxs[0].size() + 2; - for (int x = 1; x < _upxs.length; x++) - { - size += _upxs[x-1].size() % 2; - size += _upxs[x].size() + 2; - } - - - byte[] buf = new byte[size]; - _stdfBase.serialize( buf, 0 ); - - int offset = _baseLength; - - char[] letters = _name.toCharArray(); - LittleEndian.putShort(buf, _baseLength, (short)letters.length); - offset += LittleEndian.SHORT_SIZE; - for (int x = 0; x < letters.length; x++) - { - LittleEndian.putShort(buf, offset, (short)letters[x]); - offset += LittleEndian.SHORT_SIZE; - } - // get past the null delimiter for the name. - offset += LittleEndian.SHORT_SIZE; - - for (int x = 0; x < _upxs.length; x++) - { - short upxSize = (short)_upxs[x].size(); - LittleEndian.putShort(buf, offset, upxSize); - offset += LittleEndian.SHORT_SIZE; - System.arraycopy(_upxs[x].getUPX(), 0, buf, offset, upxSize); - offset += upxSize + (upxSize % 2); - } - - return buf; - } - - @Override - public int hashCode() - { - final int prime = 31; - int result = 1; - result = prime * result + ( ( _name == null ) ? 0 : _name.hashCode() ); - result = prime * result - + ( ( _stdfBase == null ) ? 0 : _stdfBase.hashCode() ); - result = prime * result + Arrays.hashCode( _upxs ); - return result; - } - - @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - return true; - if ( obj == null ) - return false; - if ( getClass() != obj.getClass() ) - return false; - StyleDescription other = (StyleDescription) obj; - if ( _name == null ) - { - if ( other._name != null ) - return false; - } - else if ( !_name.equals( other._name ) ) - return false; - if ( _stdfBase == null ) - { - if ( other._stdfBase != null ) - return false; - } - else if ( !_stdfBase.equals( other._stdfBase ) ) - return false; - if ( !Arrays.equals( _upxs, other._upxs ) ) - return false; - return true; - } - - @Override - public String toString() - { - StringBuilder result = new StringBuilder(); - result.append( "[STD]: '" ); - result.append( _name ); - result.append( "'" ); - result.append( ( "\nStdfBase:\t" + _stdfBase ).replaceAll( "\n", - "\n " ) ); - result.append( ( "\nStdfPost2000:\t" + _stdfPost2000 ).replaceAll( - "\n", "\n " ) ); - for ( UPX upx : _upxs ) - { - result.append( ( "\nUPX:\t" + upx ).replaceAll( "\n", "\n " ) ); - } - return result.toString(); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/model/StyleSheet.java b/src/scratchpad/src/org/apache/poi/hwpf/model/StyleSheet.java deleted file mode 100644 index f8ec76b67..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/model/StyleSheet.java +++ /dev/null @@ -1,408 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.model; - -import java.io.IOException; - -import org.apache.poi.hwpf.model.io.HWPFOutputStream; -import org.apache.poi.hwpf.sprm.CharacterSprmUncompressor; -import org.apache.poi.hwpf.sprm.ParagraphSprmUncompressor; -import org.apache.poi.hwpf.usermodel.CharacterProperties; -import org.apache.poi.hwpf.usermodel.ParagraphProperties; -import org.apache.poi.util.Internal; -import org.apache.poi.util.LittleEndian; - -/** - * Represents a document's stylesheet. A word documents formatting is stored as - * compressed styles that are based on styles contained in the stylesheet. This - * class also contains static utility functions to uncompress different - * formatting properties. - *

    - * Fields documentation is quotes from Microsoft Office Word 97-2007 Binary File - * Format (.doc) Specification, page 36 of 210 - * - * @author Ryan Ackley - */ -@Internal -public final class StyleSheet implements HDFType { - - public static final int NIL_STYLE = 4095; -// private static final int PAP_TYPE = 1; -// private static final int CHP_TYPE = 2; -// private static final int SEP_TYPE = 4; -// private static final int TAP_TYPE = 5; - - @Deprecated - private final static ParagraphProperties NIL_PAP = new ParagraphProperties(); - @Deprecated - private final static CharacterProperties NIL_CHP = new CharacterProperties(); - - private final static byte[] NIL_CHPX = new byte[] {}; - private final static byte[] NIL_PAPX = new byte[] {0, 0}; - - /** - * Size of the STSHI structure - */ - private int _cbStshi; - - /** - * General information about a stylesheet - */ - private Stshif _stshif; - - StyleDescription[] _styleDescriptions; - - /** - * StyleSheet constructor. Loads a document's stylesheet information, - * - * @param tableStream A byte array containing a document's raw stylesheet - * info. Found by using FileInformationBlock.getFcStshf() and - * FileInformationBLock.getLcbStshf() - */ - public StyleSheet(byte[] tableStream, int offset) - { - int startOffset = offset; - _cbStshi = LittleEndian.getShort( tableStream, offset ); - offset += LittleEndian.SHORT_SIZE; - - /* - * Count of styles in stylesheet - * - * The number of styles in this style sheet. There will be stshi.cstd - * (cbSTD, STD) pairs in the file following the STSHI. Note: styles can - * be empty, i.e. cbSTD==0. - */ - - _stshif = new Stshif( tableStream, offset ); - offset += Stshif.getSize(); - - // shall we discard cbLSD and mpstilsd? - - offset = startOffset + LittleEndian.SHORT_SIZE + _cbStshi; - _styleDescriptions = new StyleDescription[_stshif.getCstd()]; - for(int x = 0; x < _stshif.getCstd(); x++) - { - int stdSize = LittleEndian.getShort(tableStream, offset); - //get past the size - offset += 2; - if(stdSize > 0) - { - //byte[] std = new byte[stdSize]; - - StyleDescription aStyle = new StyleDescription(tableStream, - _stshif.getCbSTDBaseInFile(), offset, true); - - _styleDescriptions[x] = aStyle; - } - - offset += stdSize; - - } - for(int x = 0; x < _styleDescriptions.length; x++) - { - if(_styleDescriptions[x] != null) - { - createPap(x); - createChp(x); - } - } - } - - public void writeTo(HWPFOutputStream out) - throws IOException - { - - int offset = 0; - - /* - * we don't support 2003 Word extensions in STSHI (but may be we should - * at least not delete them, shouldn't we?), so our structure is always - * 18 bytes in length -- sergey - */ - this._cbStshi = 18; - - // add two bytes so we can prepend the stylesheet w/ its size - byte[] buf = new byte[_cbStshi + 2]; - - LittleEndian.putUShort(buf, offset, (short)_cbStshi); - offset += LittleEndian.SHORT_SIZE; - - _stshif.setCstd( _styleDescriptions.length ); - _stshif.serialize( buf, offset ); - // offset += Stshif.getSize(); - - out.write(buf); - - byte[] sizeHolder = new byte[2]; - for (int x = 0; x < _styleDescriptions.length; x++) - { - if(_styleDescriptions[x] != null) - { - byte[] std = _styleDescriptions[x].toByteArray(); - - // adjust the size so it is always on a word boundary - LittleEndian.putShort(sizeHolder, 0, (short)((std.length) + (std.length % 2))); - out.write(sizeHolder); - out.write(std); - - // Must always start on a word boundary. - if (std.length % 2 == 1) - { - out.write('\0'); - } - } - else - { - sizeHolder[0] = 0; - sizeHolder[1] = 0; - out.write(sizeHolder); - } - } - } - - @Override - public boolean equals(Object o) - { - if (!(o instanceof StyleSheet)) return false; - StyleSheet ss = (StyleSheet)o; - - if (!ss._stshif.equals( this._stshif ) - || ss._cbStshi != this._cbStshi - || ss._styleDescriptions.length != this._styleDescriptions.length - ) return false; - - for (int i=0; i<_styleDescriptions.length; i++) { - StyleDescription tsd = this._styleDescriptions[i]; - StyleDescription osd = ss._styleDescriptions[i]; - if (tsd == null && osd == null) continue; - if (tsd == null || osd == null || !osd.equals(tsd)) return false; - } - - return true; - } - - @Override - public int hashCode() { - assert false : "hashCode not designed"; - return 42; // any arbitrary constant will do - } - - /** - * Creates a PartagraphProperties object from a papx stored in the - * StyleDescription at the index istd in the StyleDescription array. The PAP - * is placed in the StyleDescription at istd after its been created. Not - * every StyleDescription will contain a papx. In these cases this function - * does nothing - * - * @param istd The index of the StyleDescription to create the - * ParagraphProperties from (and also place the finished PAP in) - */ - @Deprecated - private void createPap(int istd) - { - StyleDescription sd = _styleDescriptions[istd]; - ParagraphProperties pap = sd.getPAP(); - byte[] papx = sd.getPAPX(); - int baseIndex = sd.getBaseStyle(); - if(pap == null && papx != null) - { - ParagraphProperties parentPAP = new ParagraphProperties(); - if(baseIndex != NIL_STYLE) - { - - parentPAP = _styleDescriptions[baseIndex].getPAP(); - if(parentPAP == null) { - if(baseIndex == istd) { - // Oh dear, style claims that it is its own parent - throw new IllegalStateException("Pap style " + istd + " claimed to have itself as its parent, which isn't allowed"); - } - // Create the parent style - createPap(baseIndex); - parentPAP = _styleDescriptions[baseIndex].getPAP(); - } - - } - - if (parentPAP == null) { - parentPAP = new ParagraphProperties(); - } - - pap = ParagraphSprmUncompressor.uncompressPAP(parentPAP, papx, 2); - sd.setPAP(pap); - } - } - /** - * Creates a CharacterProperties object from a chpx stored in the - * StyleDescription at the index istd in the StyleDescription array. The - * CharacterProperties object is placed in the StyleDescription at istd after - * its been created. Not every StyleDescription will contain a chpx. In these - * cases this function does nothing. - * - * @param istd The index of the StyleDescription to create the - * CharacterProperties object from. - */ - @Deprecated - private void createChp(int istd) - { - StyleDescription sd = _styleDescriptions[istd]; - CharacterProperties chp = sd.getCHP(); - byte[] chpx = sd.getCHPX(); - int baseIndex = sd.getBaseStyle(); - - if(baseIndex == istd) { - // Oh dear, this isn't allowed... - // The word file seems to be corrupted - // Switch to using the nil style so that - // there's a chance we can read it - baseIndex = NIL_STYLE; - } - - // Build and decompress the Chp if required - if(chp == null && chpx != null) - { - CharacterProperties parentCHP = new CharacterProperties(); - if(baseIndex != NIL_STYLE) - { - parentCHP = _styleDescriptions[baseIndex].getCHP(); - if(parentCHP == null) - { - createChp(baseIndex); - parentCHP = _styleDescriptions[baseIndex].getCHP(); - } - if(parentCHP == null) { - parentCHP = new CharacterProperties(); - } - } - - chp = CharacterSprmUncompressor.uncompressCHP(parentCHP, chpx, 0); - sd.setCHP(chp); - } - } - - /** - * Gets the number of styles in the style sheet. - * @return The number of styles in the style sheet. - */ - public int numStyles() { - return _styleDescriptions.length; - } - - /** - * Gets the StyleDescription at index x. - * - * @param styleIndex - * the index of the desired StyleDescription. - */ - public StyleDescription getStyleDescription( int styleIndex ) - { - return _styleDescriptions[styleIndex]; - } - - @Deprecated - public CharacterProperties getCharacterStyle( int styleIndex ) - { - if ( styleIndex == NIL_STYLE ) - { - return NIL_CHP; - } - - if ( styleIndex >= _styleDescriptions.length ) - { - return NIL_CHP; - } - - return ( _styleDescriptions[styleIndex] != null ? _styleDescriptions[styleIndex] - .getCHP() : NIL_CHP ); - } - - @Deprecated - public ParagraphProperties getParagraphStyle( int styleIndex ) - { - if ( styleIndex == NIL_STYLE ) - { - return NIL_PAP; - } - - if ( styleIndex >= _styleDescriptions.length ) - { - return NIL_PAP; - } - - if ( _styleDescriptions[styleIndex] == null ) - { - return NIL_PAP; - } - - if ( _styleDescriptions[styleIndex].getPAP() == null ) - { - return NIL_PAP; - } - - return _styleDescriptions[styleIndex].getPAP(); - } - - public byte[] getCHPX( int styleIndex ) - { - if ( styleIndex == NIL_STYLE ) - { - return NIL_CHPX; - } - - if ( styleIndex >= _styleDescriptions.length ) - { - return NIL_CHPX; - } - - if ( _styleDescriptions[styleIndex] == null ) - { - return NIL_CHPX; - } - - if ( _styleDescriptions[styleIndex].getCHPX() == null ) - { - return NIL_CHPX; - } - - return _styleDescriptions[styleIndex].getCHPX(); - } - - public byte[] getPAPX( int styleIndex ) - { - if ( styleIndex == NIL_STYLE ) - { - return NIL_PAPX; - } - - if ( styleIndex >= _styleDescriptions.length ) - { - return NIL_PAPX; - } - - if ( _styleDescriptions[styleIndex] == null ) - { - return NIL_PAPX; - } - - if ( _styleDescriptions[styleIndex].getPAPX() == null ) - { - return NIL_PAPX; - } - - return _styleDescriptions[styleIndex].getPAPX(); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/model/SubdocumentType.java b/src/scratchpad/src/org/apache/poi/hwpf/model/SubdocumentType.java deleted file mode 100644 index 89d16d2e0..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/model/SubdocumentType.java +++ /dev/null @@ -1,57 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hwpf.model; - -import org.apache.poi.util.Internal; - -/** - * Document text parts that can have text pieces (CPs) - * - * @author Sergey Vladimirov (vlsergey {at} gmail {dot} com) - */ -@Internal -public enum SubdocumentType { - MAIN(), - - FOOTNOTE(), - - HEADER(), - - @Deprecated - MACRO(), - - ANNOTATION(), - - ENDNOTE(), - - TEXTBOX(), - - HEADER_TEXTBOX(); - - /** - * Array of {@link SubdocumentType}s ordered by document position and FIB - * field order - */ - public static final SubdocumentType[] ORDERED = new SubdocumentType[] { - MAIN, FOOTNOTE, HEADER, MACRO, ANNOTATION, ENDNOTE, TEXTBOX, - HEADER_TEXTBOX }; - - private SubdocumentType() - { - } - -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/model/TabDescriptor.java b/src/scratchpad/src/org/apache/poi/hwpf/model/TabDescriptor.java deleted file mode 100644 index 472b667b5..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/model/TabDescriptor.java +++ /dev/null @@ -1,46 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hwpf.model; - -import org.apache.poi.hwpf.model.types.TBDAbstractType; -import org.apache.poi.hwpf.usermodel.ParagraphProperties; - -/** - * Tab descriptor. Part of {@link ParagraphProperties}. - * - * @author vlsergey - */ -public class TabDescriptor extends TBDAbstractType -{ - - public TabDescriptor() - { - } - - public TabDescriptor( byte[] bytes, int offset ) - { - fillFields( bytes, offset ); - } - - public byte[] toByteArray() - { - byte[] buf = new byte[getSize()]; - serialize( buf, 0 ); - return buf; - } - -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/model/TextPiece.java b/src/scratchpad/src/org/apache/poi/hwpf/model/TextPiece.java deleted file mode 100644 index e137727fd..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/model/TextPiece.java +++ /dev/null @@ -1,216 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.model; - - -import java.nio.charset.Charset; - -import org.apache.poi.util.CodePageUtil; -import org.apache.poi.util.Internal; -import org.apache.poi.util.StringUtil; - -/** - * Lightweight representation of a text piece. - * Works in the character domain, not the byte domain, so you - * need to have turned byte references into character - * references before getting here. - * - * @author Ryan Ackley - */ -@Internal -public class TextPiece extends PropertyNode { - private boolean _usesUnicode; - - private PieceDescriptor _pd; - - /** - * @param start Beginning offset in main document stream, in characters. - * @param end Ending offset in main document stream, in characters. - * @param text The raw bytes of our text - * instead - */ - public TextPiece(int start, int end, byte[] text, PieceDescriptor pd, - int cpStart) { - this(start, end, text, pd); - } - - /** - * @param start Beginning offset in main document stream, in characters. - * @param end Ending offset in main document stream, in characters. - * @param text The raw bytes of our text - */ - public TextPiece(int start, int end, byte[] text, PieceDescriptor pd) { - super(start, end, buildInitSB(text, pd)); - _usesUnicode = pd.isUnicode(); - _pd = pd; - - // Validate - int textLength = ((CharSequence) _buf).length(); - if (end - start != textLength) { - throw new IllegalStateException("Told we're for characters " + start + " -> " + end + ", but actually covers " + textLength + " characters!"); - } - if (end < start) { - throw new IllegalStateException("Told we're of negative size! start=" + start + " end=" + end); - } - } - - /** - * Create the StringBuilder from the text and unicode flag - */ - private static StringBuilder buildInitSB(byte[] text, PieceDescriptor pd) { - byte[] textBuffer = text; - if (StringUtil.BIG5.equals(pd.getCharset())) { - return new StringBuilder(CodePageUtil.cp950ToString(text, 0, text.length)); - } - - String str = new String(textBuffer, 0, textBuffer.length, (pd.isUnicode()) ? StringUtil.UTF16LE : pd.getCharset()); - return new StringBuilder(str); - } - - /** - * @return If this text piece is unicode - */ - public boolean isUnicode() { - return _usesUnicode; - } - - public PieceDescriptor getPieceDescriptor() { - return _pd; - } - - @Deprecated - public StringBuffer getStringBuffer() { - return new StringBuffer(getStringBuilder()); - } - - public StringBuilder getStringBuilder() { - return (StringBuilder) _buf; - } - - public byte[] getRawBytes() { - return ((CharSequence) _buf).toString().getBytes( - Charset.forName(_usesUnicode ? "UTF-16LE" : "Cp1252") - ); - } - - /** - * Returns part of the string. - * Works only in characters, not in bytes! - * - * @param start Local start position, in characters - * @param end Local end position, in characters - */ - @Deprecated - public String substring(int start, int end) { - StringBuilder buf = (StringBuilder) _buf; - - // Validate - if (start < 0) { - throw new StringIndexOutOfBoundsException("Can't request a substring before 0 - asked for " + start); - } - if (end > buf.length()) { - throw new StringIndexOutOfBoundsException("Index " + end + " out of range 0 -> " + buf.length()); - } - if (end < start) { - throw new StringIndexOutOfBoundsException("Asked for text from " + start + " to " + end + ", which has an end before the start!"); - } - return buf.substring(start, end); - } - - /** - * Adjusts the internal string for deletinging - * some characters within this. - * - * @param start The start position for the delete, in characters - * @param length The number of characters to delete - */ - @Deprecated - public void adjustForDelete(int start, int length) { - int myStart = getStart(); - int myEnd = getEnd(); - int end = start + length; - - /* do we have to delete from this text piece? */ - if (start <= myEnd && end >= myStart) { - - /* find where the deleted area overlaps with this text piece */ - int overlapStart = Math.max(myStart, start); - int overlapEnd = Math.min(myEnd, end); - - int bufStart = overlapStart - myStart; - int bufEnd = overlapEnd - myStart; - ((StringBuilder) _buf).delete(bufStart, bufEnd); - } - - // We need to invoke this even if text from this piece is not being - // deleted because the adjustment must propagate to all subsequent - // text pieces i.e., if text from tp[n] is being deleted, then - // tp[n + 1], tp[n + 2], etc. will need to be adjusted. - // The superclass is expected to use a separate sentry for this. - super.adjustForDelete(start, length); - } - - /** - * Returns the length, in characters - */ - @Deprecated - public int characterLength() { - return (getEnd() - getStart()); - } - - /** - * Returns the length, in bytes - */ - public int bytesLength() { - return (getEnd() - getStart()) * (_usesUnicode ? 2 : 1); - } - - @Override - public boolean equals(Object o) { - if (!(o instanceof TextPiece)) return false; - TextPiece tp = (TextPiece) o; - assert (_buf != null && tp._buf != null && _pd != null && tp._pd != null); - - return ( - limitsAreEqual(o) - && tp._usesUnicode == this._usesUnicode - && tp._buf.toString().equals(this._buf.toString()) - && tp._pd.equals(this._pd) - ); - } - - @Override - public int hashCode() { - assert false : "hashCode not designed"; - return 42; // any arbitrary constant will do - } - - - /** - * Returns the character position we start at. - */ - public int getCP() { - return getStart(); - } - - public String toString() { - return "TextPiece from " + getStart() + " to " + getEnd() + " (" - + getPieceDescriptor() + ")"; - } - -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/model/TextPieceTable.java b/src/scratchpad/src/org/apache/poi/hwpf/model/TextPieceTable.java deleted file mode 100644 index bbddd8645..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/model/TextPieceTable.java +++ /dev/null @@ -1,463 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hwpf.model; - -import java.io.IOException; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.LinkedList; -import java.util.List; - -import org.apache.poi.hwpf.model.io.HWPFOutputStream; -import org.apache.poi.poifs.common.POIFSConstants; -import org.apache.poi.util.Internal; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; - -/** - * The piece table for matching up character positions to bits of text. This - * mostly works in bytes, but the TextPieces themselves work in characters. This - * does the icky convertion. - * - * @author Ryan Ackley - */ -@Internal -public class TextPieceTable implements CharIndexTranslator { - private static final POILogger logger = POILogFactory - .getLogger(TextPieceTable.class); - - // int _multiple; - int _cpMin; - protected ArrayList _textPieces = new ArrayList(); - protected ArrayList _textPiecesFCOrder = new ArrayList(); - - public TextPieceTable() { - } - - public TextPieceTable(byte[] documentStream, byte[] tableStream, - int offset, int size, int fcMin) { - // get our plex of PieceDescriptors - PlexOfCps pieceTable = new PlexOfCps(tableStream, offset, size, - PieceDescriptor.getSizeInBytes()); - - int length = pieceTable.length(); - PieceDescriptor[] pieces = new PieceDescriptor[length]; - - // iterate through piece descriptors raw bytes and create - // PieceDescriptor objects - for (int x = 0; x < length; x++) { - GenericPropertyNode node = pieceTable.getProperty(x); - pieces[x] = new PieceDescriptor(node.getBytes(), 0); - } - - // Figure out the cp of the earliest text piece - // Note that text pieces don't have to be stored in order! - _cpMin = pieces[0].getFilePosition() - fcMin; - for (PieceDescriptor piece : pieces) { - int start = piece.getFilePosition() - fcMin; - if (start < _cpMin) { - _cpMin = start; - } - } - - // using the PieceDescriptors, build our list of TextPieces. - for (int x = 0; x < pieces.length; x++) { - int start = pieces[x].getFilePosition(); - GenericPropertyNode node = pieceTable.getProperty(x); - - // Grab the start and end, which are in characters - int nodeStartChars = node.getStart(); - int nodeEndChars = node.getEnd(); - - // What's the relationship between bytes and characters? - boolean unicode = pieces[x].isUnicode(); - int multiple = 1; - if (unicode) { - multiple = 2; - } - - // Figure out the length, in bytes and chars - int textSizeChars = (nodeEndChars - nodeStartChars); - int textSizeBytes = textSizeChars * multiple; - - // Grab the data that makes up the piece - byte[] buf = new byte[textSizeBytes]; - System.arraycopy(documentStream, start, buf, 0, textSizeBytes); - - // And now build the piece - final TextPiece newTextPiece = newTextPiece(nodeStartChars, nodeEndChars, buf, - pieces[x]); - - _textPieces.add(newTextPiece); - } - - // In the interest of our sanity, now sort the text pieces - // into order, if they're not already - Collections.sort(_textPieces); - _textPiecesFCOrder = new ArrayList(_textPieces); - Collections.sort(_textPiecesFCOrder, new FCComparator()); - } - - protected TextPiece newTextPiece(int nodeStartChars, int nodeEndChars, byte[] buf, PieceDescriptor pd) { - return new TextPiece(nodeStartChars, nodeEndChars, buf, pd); - } - - public void add(TextPiece piece) { - _textPieces.add(piece); - _textPiecesFCOrder.add(piece); - Collections.sort(_textPieces); - Collections.sort(_textPiecesFCOrder, new FCComparator()); - } - - /** - * Adjust all the text piece after inserting some text into one of them - * - * @param listIndex The TextPiece that had characters inserted into - * @param length The number of characters inserted - */ - public int adjustForInsert(int listIndex, int length) { - int size = _textPieces.size(); - - TextPiece tp = _textPieces.get(listIndex); - - // Update with the new end - tp.setEnd(tp.getEnd() + length); - - // Now change all subsequent ones - for (int x = listIndex + 1; x < size; x++) { - tp = _textPieces.get(x); - tp.setStart(tp.getStart() + length); - tp.setEnd(tp.getEnd() + length); - } - - // All done - return length; - } - - public boolean equals(Object o) { - if (!(o instanceof TextPieceTable)) return false; - TextPieceTable tpt = (TextPieceTable) o; - - int size = tpt._textPieces.size(); - if (size == _textPieces.size()) { - for (int x = 0; x < size; x++) { - if (!tpt._textPieces.get(x).equals(_textPieces.get(x))) { - return false; - } - } - return true; - } - return false; - } - - public int getByteIndex(int charPos) { - int byteCount = 0; - for (TextPiece tp : _textPieces) { - if (charPos >= tp.getEnd()) { - byteCount = tp.getPieceDescriptor().getFilePosition() - + (tp.getEnd() - tp.getStart()) - * (tp.isUnicode() ? 2 : 1); - - if (charPos == tp.getEnd()) - break; - - continue; - } - if (charPos < tp.getEnd()) { - int left = charPos - tp.getStart(); - byteCount = tp.getPieceDescriptor().getFilePosition() + left - * (tp.isUnicode() ? 2 : 1); - break; - } - } - return byteCount; - } - - @Deprecated - public int getCharIndex(int bytePos) { - return getCharIndex(bytePos, 0); - } - - @Deprecated - public int getCharIndex(int startBytePos, int startCP) { - int charCount = 0; - - int bytePos = lookIndexForward(startBytePos); - - for (TextPiece tp : _textPieces) { - int pieceStart = tp.getPieceDescriptor().getFilePosition(); - - int bytesLength = tp.bytesLength(); - int pieceEnd = pieceStart + bytesLength; - - int toAdd; - - if (bytePos < pieceStart || bytePos > pieceEnd) { - toAdd = bytesLength; - } else if (bytePos > pieceStart && bytePos < pieceEnd) { - toAdd = (bytePos - pieceStart); - } else { - toAdd = bytesLength - (pieceEnd - bytePos); - } - - if (tp.isUnicode()) { - charCount += toAdd / 2; - } else { - charCount += toAdd; - } - - if (bytePos >= pieceStart && bytePos <= pieceEnd - && charCount >= startCP) { - break; - } - } - - return charCount; - } - - @Override - public int[][] getCharIndexRanges(int startBytePosInclusive, - int endBytePosExclusive) { - List result = new LinkedList(); - for (TextPiece textPiece : _textPiecesFCOrder) { - final int tpStart = textPiece.getPieceDescriptor() - .getFilePosition(); - final int tpEnd = textPiece.getPieceDescriptor().getFilePosition() - + textPiece.bytesLength(); - if (startBytePosInclusive > tpEnd) - continue; - if (endBytePosExclusive <= tpStart) - break; - - final int rangeStartBytes = Math.max(tpStart, - startBytePosInclusive); - final int rangeEndBytes = Math.min(tpEnd, endBytePosExclusive); - final int rangeLengthBytes = rangeEndBytes - rangeStartBytes; - - if (rangeStartBytes > rangeEndBytes) - continue; - - final int encodingMultiplier = getEncodingMultiplier(textPiece); - - final int rangeStartCp = textPiece.getStart() - + (rangeStartBytes - tpStart) / encodingMultiplier; - final int rangeEndCp = rangeStartCp + rangeLengthBytes - / encodingMultiplier; - - result.add(new int[]{rangeStartCp, rangeEndCp}); - } - - return result.toArray(new int[result.size()][]); - } - - protected int getEncodingMultiplier(TextPiece textPiece) { - return textPiece.isUnicode() ? 2 : 1; - } - - public int getCpMin() { - return _cpMin; - } - - public StringBuilder getText() { - final long start = System.currentTimeMillis(); - - // rebuild document paragraphs structure - StringBuilder docText = new StringBuilder(); - for (TextPiece textPiece : _textPieces) { - String toAppend = textPiece.getStringBuilder().toString(); - int toAppendLength = toAppend.length(); - - if (toAppendLength != textPiece.getEnd() - textPiece.getStart()) { - logger.log( - POILogger.WARN, - "Text piece has boundaries [", - Integer.valueOf(textPiece.getStart()), - "; ", - Integer.valueOf(textPiece.getEnd()), - ") but length ", - Integer.valueOf(textPiece.getEnd() - - textPiece.getStart())); - } - - docText.replace(textPiece.getStart(), textPiece.getStart() - + toAppendLength, toAppend); - } - - logger.log(POILogger.DEBUG, "Document text were rebuilded in ", - Long.valueOf(System.currentTimeMillis() - start), " ms (", - Integer.valueOf(docText.length()), " chars)"); - - return docText; - } - - public List getTextPieces() { - return _textPieces; - } - - @Override - public int hashCode() { - return _textPieces.size(); - } - - public boolean isIndexInTable(int bytePos) { - for (TextPiece tp : _textPiecesFCOrder) { - int pieceStart = tp.getPieceDescriptor().getFilePosition(); - - if (bytePos > pieceStart + tp.bytesLength()) { - continue; - } - - if (pieceStart > bytePos) { - return false; - } - - return true; - } - - return false; - } - - boolean isIndexInTable(int startBytePos, int endBytePos) { - for (TextPiece tp : _textPiecesFCOrder) { - int pieceStart = tp.getPieceDescriptor().getFilePosition(); - - if (startBytePos >= pieceStart + tp.bytesLength()) { - continue; - } - - int left = Math.max(startBytePos, pieceStart); - int right = Math.min(endBytePos, pieceStart + tp.bytesLength()); - - if (left >= right) - return false; - - return true; - } - - return false; - } - - public int lookIndexBackward(final int startBytePos) { - int bytePos = startBytePos; - int lastEnd = 0; - - for (TextPiece tp : _textPiecesFCOrder) { - int pieceStart = tp.getPieceDescriptor().getFilePosition(); - - if (bytePos > pieceStart + tp.bytesLength()) { - lastEnd = pieceStart + tp.bytesLength(); - continue; - } - - if (pieceStart > bytePos) { - bytePos = lastEnd; - } - - break; - } - - return bytePos; - } - - public int lookIndexForward(final int startBytePos) { - if (_textPiecesFCOrder.isEmpty()) - throw new IllegalStateException("Text pieces table is empty"); - - if (_textPiecesFCOrder.get(0).getPieceDescriptor().getFilePosition() > startBytePos) - return _textPiecesFCOrder.get(0).getPieceDescriptor().getFilePosition(); - - if (_textPiecesFCOrder.get(_textPiecesFCOrder.size() - 1) - .getPieceDescriptor().getFilePosition() <= startBytePos) - return startBytePos; - - int low = 0; - int high = _textPiecesFCOrder.size() - 1; - - while (low <= high) { - int mid = (low + high) >>> 1; - final TextPiece textPiece = _textPiecesFCOrder.get(mid); - int midVal = textPiece.getPieceDescriptor().getFilePosition(); - - if (midVal < startBytePos) - low = mid + 1; - else if (midVal > startBytePos) - high = mid - 1; - else - // found piece with exact start - return textPiece.getPieceDescriptor().getFilePosition(); - } - assert low == high; - assert _textPiecesFCOrder.get(low).getPieceDescriptor() - .getFilePosition() < startBytePos; - // last line can't be current, can it? - assert _textPiecesFCOrder.get(low + 1).getPieceDescriptor() - .getFilePosition() > startBytePos; - - // shifting to next piece start - return _textPiecesFCOrder.get(low + 1).getPieceDescriptor().getFilePosition(); - } - - public byte[] writeTo(HWPFOutputStream docStream) throws IOException { - PlexOfCps textPlex = new PlexOfCps(PieceDescriptor.getSizeInBytes()); - // int fcMin = docStream.getOffset(); - - for (TextPiece next : _textPieces) { - PieceDescriptor pd = next.getPieceDescriptor(); - - int offset = docStream.getOffset(); - int mod = (offset % POIFSConstants.SMALLER_BIG_BLOCK_SIZE); - if (mod != 0) { - mod = POIFSConstants.SMALLER_BIG_BLOCK_SIZE - mod; - byte[] buf = new byte[mod]; - docStream.write(buf); - } - - // set the text piece position to the current docStream offset. - pd.setFilePosition(docStream.getOffset()); - - // write the text to the docstream and save the piece descriptor to - // the - // plex which will be written later to the tableStream. - docStream.write(next.getRawBytes()); - - // The TextPiece is already in characters, which - // makes our life much easier - int nodeStart = next.getStart(); - int nodeEnd = next.getEnd(); - textPlex.addProperty(new GenericPropertyNode(nodeStart, nodeEnd, - pd.toByteArray())); - } - - return textPlex.toByteArray(); - } - - protected static class FCComparator implements Comparator, Serializable { - public int compare(TextPiece textPiece, TextPiece textPiece1) { - if (textPiece.getPieceDescriptor().fc > textPiece1 - .getPieceDescriptor().fc) { - return 1; - } else if (textPiece.getPieceDescriptor().fc < textPiece1 - .getPieceDescriptor().fc) { - return -1; - } else { - return 0; - } - } - } -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/model/UPX.java b/src/scratchpad/src/org/apache/poi/hwpf/model/UPX.java deleted file mode 100644 index 5de2fe524..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/model/UPX.java +++ /dev/null @@ -1,62 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.model; - -import java.util.Arrays; - -import org.apache.poi.util.Internal; - -@Internal -public final class UPX -{ - private byte[] _upx; - - public UPX(byte[] upx) - { - _upx = upx; - } - - public byte[] getUPX() - { - return _upx; - } - public int size() - { - return _upx.length; - } - - @Override - public boolean equals(Object o) - { - if (!(o instanceof UPX)) return false; - UPX upx = (UPX)o; - return Arrays.equals(_upx, upx._upx); - } - - @Override - public int hashCode() { - assert false : "hashCode not designed"; - return 42; // any arbitrary constant will do - } - - @Override - public String toString() - { - return "[UPX] " + Arrays.toString( _upx ); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/model/UnhandledDataStructure.java b/src/scratchpad/src/org/apache/poi/hwpf/model/UnhandledDataStructure.java deleted file mode 100644 index 89d5c492f..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/model/UnhandledDataStructure.java +++ /dev/null @@ -1,59 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.model; - -import java.util.Arrays; - -import org.apache.poi.util.Internal; - -/** - * A data structure used to hold some data we don't - * understand / can't handle, so we have it available - * for when we come to write back out again - */ -@Internal -public final class UnhandledDataStructure -{ - private final byte[] _buf; - - public UnhandledDataStructure(byte[] buf, int offset, int length) - { - // Sanity check the size they've asked for - int offsetEnd = offset + length; - if (offsetEnd > buf.length || offsetEnd < 0) - { - throw new IndexOutOfBoundsException("Buffer Length is " + buf.length + " " + - "but code is tried to read " + length + " " + - "from offset " + offset + " to " + offsetEnd); - } - if (offset < 0 || length < 0) - { - throw new IndexOutOfBoundsException("Offset and Length must both be >= 0, negative " + - "indicies are not permitted - code is tried to read " + length + " from offset " + offset); - } - - // Save that requested portion of the data - _buf = Arrays.copyOfRange(buf, offset, offsetEnd); - - } - - /*package*/ byte[] getBuf() - { - return _buf; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/model/Xst.java b/src/scratchpad/src/org/apache/poi/hwpf/model/Xst.java deleted file mode 100644 index 69e30af57..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/model/Xst.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -package org.apache.poi.hwpf.model; - -import java.util.Arrays; - -import org.apache.poi.util.LittleEndian; - -/** - * The Xst structure is a string. The string is prepended by its length and is - * not null-terminated. - *

    - * Documentation quoted from Page 424 of 621. [MS-DOC] -- v20110315 Word (.doc) - * Binary File Format - * - * @author Sergey Vladimirov (vlsergey {at} gmail {dot} com) - */ -public class Xst -{ - - /** - * An unsigned integer that specifies the number of characters that are - * contained in the rgtchar array. - */ - private int _cch; - - /** - * An array of 16-bit Unicode characters that make up a string. - */ - private char[] _rgtchar; - - public Xst() - { - _cch = 0; - _rgtchar = new char[0]; - } - - public Xst( byte[] data, int startOffset ) - { - int offset = startOffset; - - _cch = LittleEndian.getUShort( data, offset ); - offset += LittleEndian.SHORT_SIZE; - - _rgtchar = new char[_cch]; - for ( int x = 0; x < _cch; x++ ) - { - _rgtchar[x] = (char) LittleEndian.getShort( data, offset ); - offset += LittleEndian.SHORT_SIZE; - } - - } - - public Xst( String str ) - { - _cch = str.length(); - _rgtchar = str.toCharArray(); - } - - @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - return true; - if ( obj == null ) - return false; - if ( getClass() != obj.getClass() ) - return false; - Xst other = (Xst) obj; - if ( _cch != other._cch ) - return false; - if ( !Arrays.equals( _rgtchar, other._rgtchar ) ) - return false; - return true; - } - - public String getAsJavaString() - { - return new String( _rgtchar ); - } - - /** - * An unsigned integer that specifies the number of characters that are - * contained in the rgtchar array. - */ - public int getCch() - { - return _cch; - } - - /** - * An array of 16-bit Unicode characters that make up a string. - */ - public char[] getRgtchar() - { - return _rgtchar; - } - - public int getSize() - { - return LittleEndian.SHORT_SIZE + _rgtchar.length * 2; - } - - @Override - public int hashCode() - { - final int prime = 31; - int result = 1; - result = prime * result + _cch; - result = prime * result + Arrays.hashCode( _rgtchar ); - return result; - } - - public void serialize( byte[] data, int startOffset ) - { - int offset = startOffset; - - LittleEndian.putUShort( data, offset, _cch ); - offset += LittleEndian.SHORT_SIZE; - - for ( char c : _rgtchar ) - { - LittleEndian.putShort( data, offset, (short) c ); - offset += LittleEndian.SHORT_SIZE; - } - } - - @Override - public String toString() - { - return "Xst [" + _cch + "; " + Arrays.toString(_rgtchar) + "]"; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/model/Xstz.java b/src/scratchpad/src/org/apache/poi/hwpf/model/Xstz.java deleted file mode 100644 index f7aeb10dd..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/model/Xstz.java +++ /dev/null @@ -1,87 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hwpf.model; - -import org.apache.poi.util.Internal; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; - -@Internal -public class Xstz -{ - private static final POILogger log = POILogFactory.getLogger( Xstz.class ); - - private final short _chTerm = 0; - private Xst _xst; - - public Xstz() - { - _xst = new Xst(); - } - - public Xstz( byte[] data, int startOffset ) - { - fillFields( data, startOffset ); - } - - public void fillFields( byte[] data, int startOffset ) - { - int offset = startOffset; - - _xst = new Xst( data, offset ); - offset += _xst.getSize(); - - short term = LittleEndian.getShort( data, offset ); - if ( term != 0 ) - { - if (log.check(POILogger.WARN)) { - log.log(POILogger.WARN, "chTerm at the end of Xstz at offset ", - offset, " is not 0"); - } - } - } - - public String getAsJavaString() - { - return _xst.getAsJavaString(); - } - - public int getSize() - { - return _xst.getSize() + LittleEndian.SHORT_SIZE; - } - - public int serialize( byte[] data, int startOffset ) - { - int offset = startOffset; - - _xst.serialize( data, offset ); - offset += _xst.getSize(); - - LittleEndian.putUShort( data, offset, _chTerm ); - offset += LittleEndian.SHORT_SIZE; - - return offset - startOffset; - } - - @Override - public String toString() - { - return "[Xstz]" + _xst.getAsJavaString() + "[/Xstz]"; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/model/io/HWPFFileSystem.java b/src/scratchpad/src/org/apache/poi/hwpf/model/io/HWPFFileSystem.java deleted file mode 100644 index 9663f0177..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/model/io/HWPFFileSystem.java +++ /dev/null @@ -1,43 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.model.io; - - -import java.util.HashMap; -import java.util.Map; - -import org.apache.poi.util.Internal; - -@Internal -public final class HWPFFileSystem -{ - Map _streams = new HashMap(); - - public HWPFFileSystem() - { - _streams.put("WordDocument", new HWPFOutputStream()); - _streams.put("1Table", new HWPFOutputStream()); - _streams.put("Data", new HWPFOutputStream()); - } - - public HWPFOutputStream getStream(String name) - { - return _streams.get(name); - } - -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/model/io/HWPFOutputStream.java b/src/scratchpad/src/org/apache/poi/hwpf/model/io/HWPFOutputStream.java deleted file mode 100644 index 0264cae0e..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/model/io/HWPFOutputStream.java +++ /dev/null @@ -1,51 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.model.io; - -import java.io.ByteArrayOutputStream; - -import org.apache.poi.util.Internal; - -@Internal -public final class HWPFOutputStream extends ByteArrayOutputStream { - - int _offset; - - public HWPFOutputStream() { - super(); - } - - public int getOffset() { - return _offset; - } - - public synchronized void reset() { - super.reset(); - _offset = 0; - } - - public synchronized void write(byte[] buf, int off, int len) { - super.write(buf, off, len); - _offset += len; - } - - public synchronized void write(int b) { - super.write(b); - _offset++; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/model/types/BKFAbstractType.java b/src/scratchpad/src/org/apache/poi/hwpf/model/types/BKFAbstractType.java deleted file mode 100644 index 20ab5ecb8..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/model/types/BKFAbstractType.java +++ /dev/null @@ -1,192 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.model.types; - -import org.apache.poi.util.BitField; -import org.apache.poi.util.Internal; -import org.apache.poi.util.LittleEndian; - -/** - * BooKmark First descriptor (BKF). - *

    - * Class and fields descriptions are quoted from Microsoft Office Word 97-2007 - * Binary File Format (.doc) Specification - * - * NOTE: This source is automatically generated please do not modify this file. - * Either subclass or remove the record in src/types/definitions. - * - * @author Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary - * File Format (.doc) Specification - */ -@Internal -public abstract class BKFAbstractType -{ - - protected short field_1_ibkl; - protected short field_2_bkf_flags; - /**/private static BitField itcFirst = new BitField( 0x007F ); - /**/private static BitField fPub = new BitField( 0x0080 ); - /**/private static BitField itcLim = new BitField( 0x7F00 ); - /**/private static BitField fCol = new BitField( 0x8000 ); - - protected BKFAbstractType() - { - } - - protected void fillFields( byte[] data, int offset ) - { - field_1_ibkl = LittleEndian.getShort(data, 0x0 + offset); - field_2_bkf_flags = LittleEndian.getShort(data, 0x2 + offset); - } - - public void serialize( byte[] data, int offset ) - { - LittleEndian.putShort(data, 0x0 + offset, field_1_ibkl); - LittleEndian.putShort(data, 0x2 + offset, field_2_bkf_flags); - } - - /** - * Size of record - */ - public static int getSize() - { - return 0 + 2 + 2; - } - - public String toString() - { - StringBuilder builder = new StringBuilder(); - builder.append("[BKF]\n"); - builder.append(" .ibkl = "); - builder.append(" (").append(getIbkl()).append(" )\n"); - builder.append(" .bkf_flags = "); - builder.append(" (").append(getBkf_flags()).append(" )\n"); - builder.append(" .itcFirst = ").append(getItcFirst()).append('\n'); - builder.append(" .fPub = ").append(isFPub()).append('\n'); - builder.append(" .itcLim = ").append(getItcLim()).append('\n'); - builder.append(" .fCol = ").append(isFCol()).append('\n'); - - builder.append("[/BKF]\n"); - return builder.toString(); - } - - /** - * Index to BKL entry in plcfbkl that describes the ending position of this bookmark in the CP stream. - */ - public short getIbkl() - { - return field_1_ibkl; - } - - /** - * Index to BKL entry in plcfbkl that describes the ending position of this bookmark in the CP stream. - */ - public void setIbkl( short field_1_ibkl ) - { - this.field_1_ibkl = field_1_ibkl; - } - - /** - * Get the bkf_flags field for the BKF record. - */ - public short getBkf_flags() - { - return field_2_bkf_flags; - } - - /** - * Set the bkf_flags field for the BKF record. - */ - public void setBkf_flags( short field_2_bkf_flags ) - { - this.field_2_bkf_flags = field_2_bkf_flags; - } - - /** - * Sets the itcFirst field value. - * When bkf.fCol==1, this is the index to the first column of a table column bookmark - */ - public void setItcFirst( byte value ) - { - field_2_bkf_flags = (short)itcFirst.setValue(field_2_bkf_flags, value); - } - - /** - * When bkf.fCol==1, this is the index to the first column of a table column bookmark - * @return the itcFirst field value. - */ - public byte getItcFirst() - { - return ( byte )itcFirst.getValue(field_2_bkf_flags); - } - - /** - * Sets the fPub field value. - * When 1, this indicates that this bookmark is marking the range of a Macintosh Publisher section - */ - public void setFPub( boolean value ) - { - field_2_bkf_flags = (short)fPub.setBoolean(field_2_bkf_flags, value); - } - - /** - * When 1, this indicates that this bookmark is marking the range of a Macintosh Publisher section - * @return the fPub field value. - */ - public boolean isFPub() - { - return fPub.isSet(field_2_bkf_flags); - } - - /** - * Sets the itcLim field value. - * When bkf.fCol==1, this is the index to limit column of a table column bookmark - */ - public void setItcLim( byte value ) - { - field_2_bkf_flags = (short)itcLim.setValue(field_2_bkf_flags, value); - } - - /** - * When bkf.fCol==1, this is the index to limit column of a table column bookmark - * @return the itcLim field value. - */ - public byte getItcLim() - { - return ( byte )itcLim.getValue(field_2_bkf_flags); - } - - /** - * Sets the fCol field value. - * When 1, this bookmark marks a range of columns in a table specified by (bkf.itcFirst, bkf.itcLim) - */ - public void setFCol( boolean value ) - { - field_2_bkf_flags = (short)fCol.setBoolean(field_2_bkf_flags, value); - } - - /** - * When 1, this bookmark marks a range of columns in a table specified by (bkf.itcFirst, bkf.itcLim) - * @return the fCol field value. - */ - public boolean isFCol() - { - return fCol.isSet(field_2_bkf_flags); - } - -} // END OF CLASS diff --git a/src/scratchpad/src/org/apache/poi/hwpf/model/types/CHPAbstractType.java b/src/scratchpad/src/org/apache/poi/hwpf/model/types/CHPAbstractType.java deleted file mode 100644 index 92e001ae4..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/model/types/CHPAbstractType.java +++ /dev/null @@ -1,3033 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.model.types; - - -import java.util.Arrays; - -import org.apache.poi.hwpf.model.Colorref; -import org.apache.poi.hwpf.model.Hyphenation; -import org.apache.poi.hwpf.usermodel.BorderCode; -import org.apache.poi.hwpf.usermodel.DateAndTime; -import org.apache.poi.hwpf.usermodel.ShadingDescriptor; -import org.apache.poi.util.BitField; -import org.apache.poi.util.Internal; - -/** - * Character Properties. - *

    - * NOTE: This source is automatically generated please do not modify this file. Either subclass or - * remove the record in src/types/definitions. - *

    - * This class is internal. It content or properties may change without notice - * due to changes in our knowledge of internal Microsoft Word binary structures. - - * @author S. Ryan Ackley - */ -@Internal -public abstract class CHPAbstractType -{ - - protected int field_1_grpfChp; - /**/private static final BitField fBold = new BitField(0x00000001); - /**/private static final BitField fItalic = new BitField(0x00000002); - /**/private static final BitField fRMarkDel = new BitField(0x00000004); - /**/private static final BitField fOutline = new BitField(0x00000008); - /**/private static final BitField fFldVanish = new BitField(0x00000010); - /**/private static final BitField fSmallCaps = new BitField(0x00000020); - /**/private static final BitField fCaps = new BitField(0x00000040); - /**/private static final BitField fVanish = new BitField(0x00000080); - /**/private static final BitField fRMark = new BitField(0x00000100); - /**/private static final BitField fSpec = new BitField(0x00000200); - /**/private static final BitField fStrike = new BitField(0x00000400); - /**/private static final BitField fObj = new BitField(0x00000800); - /**/private static final BitField fShadow = new BitField(0x00001000); - /**/private static final BitField fLowerCase = new BitField(0x00002000); - /**/private static final BitField fData = new BitField(0x00004000); - /**/private static final BitField fOle2 = new BitField(0x00008000); - /**/private static final BitField fEmboss = new BitField(0x00010000); - /**/private static final BitField fImprint = new BitField(0x00020000); - /**/private static final BitField fDStrike = new BitField(0x00040000); - /**/private static final BitField fUsePgsuSettings = new BitField(0x00080000); - /**/private static final BitField fBoldBi = new BitField(0x00100000); - /**/private static final BitField fComplexScripts = new BitField(0x00100000); - /**/private static final BitField fItalicBi = new BitField(0x00200000); - /**/private static final BitField fBiDi = new BitField(0x00400000); - /**/private static final BitField fIcoBi = new BitField(0x00800000); - /**/private static final BitField fNonGlyph = new BitField(0x01000000); - /**/private static final BitField fBoldOther = new BitField(0x02000000); - /**/private static final BitField fItalicOther = new BitField(0x04000000); - /**/private static final BitField fNoProof = new BitField(0x08000000); - /**/private static final BitField fWebHidden = new BitField(0x10000000); - /**/private static final BitField fFitText = new BitField(0x20000000); - /**/private static final BitField fCalc = new BitField(0x40000000); - /**/private static final BitField fFmtLineProp = new BitField(0x80000000); - protected int field_2_hps; - protected int field_3_ftcAscii; - protected int field_4_ftcFE; - protected int field_5_ftcOther; - protected int field_6_ftcBi; - protected int field_7_dxaSpace; - protected Colorref field_8_cv; - protected byte field_9_ico; - protected int field_10_pctCharWidth; - protected int field_11_lidDefault; - protected int field_12_lidFE; - protected byte field_13_kcd; - /**/protected final static byte KCD_NON = 0; - /**/protected final static byte KCD_DOT = 1; - /**/protected final static byte KCD_COMMA = 2; - /**/protected final static byte KCD_CIRCLE = 3; - /**/protected final static byte KCD_UNDER_DOT = 4; - protected boolean field_14_fUndetermine; - protected byte field_15_iss; - /**/protected final static byte ISS_NONE = 0; - /**/protected final static byte ISS_SUPERSCRIPTED = 1; - /**/protected final static byte ISS_SUBSCRIPTED = 2; - protected boolean field_16_fSpecSymbol; - protected byte field_17_idct; - protected byte field_18_idctHint; - protected byte field_19_kul; - /**/protected final static byte KUL_NONE = 0; - /**/protected final static byte KUL_SINGLE = 1; - /**/protected final static byte KUL_BY_WORD = 2; - /**/protected final static byte KUL_DOUBLE = 3; - /**/protected final static byte KUL_DOTTED = 4; - /**/protected final static byte KUL_HIDDEN = 5; - /**/protected final static byte KUL_THICK = 6; - /**/protected final static byte KUL_DASH = 7; - /**/protected final static byte KUL_DOT = 8; - /**/protected final static byte KUL_DOT_DASH = 9; - /**/protected final static byte KUL_DOT_DOT_DASH = 10; - /**/protected final static byte KUL_WAVE = 11; - /**/protected final static byte KUL_DOTTED_HEAVY = 20; - /**/protected final static byte KUL_DASHED_HEAVY = 23; - /**/protected final static byte KUL_DOT_DASH_HEAVY = 25; - /**/protected final static byte KUL_DOT_DOT_DASH_HEAVY = 26; - /**/protected final static byte KUL_WAVE_HEAVY = 27; - /**/protected final static byte KUL_DASH_LONG = 39; - /**/protected final static byte KUL_WAVE_DOUBLE = 43; - /**/protected final static byte KUL_DASH_LONG_HEAVY = 55; - protected Hyphenation field_20_hresi; - protected int field_21_hpsKern; - protected short field_22_hpsPos; - protected ShadingDescriptor field_23_shd; - protected BorderCode field_24_brc; - protected int field_25_ibstRMark; - protected byte field_26_sfxtText; - /**/protected final static byte SFXTTEXT_NO = 0; - /**/protected final static byte SFXTTEXT_LAS_VEGAS_LIGHTS = 1; - /**/protected final static byte SFXTTEXT_BACKGROUND_BLINK = 2; - /**/protected final static byte SFXTTEXT_SPARKLE_TEXT = 3; - /**/protected final static byte SFXTTEXT_MARCHING_ANTS = 4; - /**/protected final static byte SFXTTEXT_MARCHING_RED_ANTS = 5; - /**/protected final static byte SFXTTEXT_SHIMMER = 6; - protected boolean field_27_fDblBdr; - protected boolean field_28_fBorderWS; - protected short field_29_ufel; - /**/private static final BitField itypFELayout = new BitField(0x00ff); - /**/private static final BitField fTNY = new BitField(0x0100); - /**/private static final BitField fWarichu = new BitField(0x0200); - /**/private static final BitField fKumimoji = new BitField(0x0400); - /**/private static final BitField fRuby = new BitField(0x0800); - /**/private static final BitField fLSFitText = new BitField(0x1000); - /**/private static final BitField spare = new BitField(0xe000); - protected byte field_30_copt; - /**/private static final BitField iWarichuBracket = new BitField(0x07); - /**/private static final BitField fWarichuNoOpenBracket = new BitField(0x08); - /**/private static final BitField fTNYCompress = new BitField(0x10); - /**/private static final BitField fTNYFetchTxm = new BitField(0x20); - /**/private static final BitField fCellFitText = new BitField(0x40); - /**/private static final BitField unused = new BitField(0x80); - protected int field_31_hpsAsci; - protected int field_32_hpsFE; - protected int field_33_hpsBi; - protected int field_34_ftcSym; - protected int field_35_xchSym; - protected int field_36_fcPic; - protected int field_37_fcObj; - protected int field_38_lTagObj; - protected int field_39_fcData; - protected Hyphenation field_40_hresiOld; - protected int field_41_ibstRMarkDel; - protected DateAndTime field_42_dttmRMark; - protected DateAndTime field_43_dttmRMarkDel; - protected int field_44_istd; - protected int field_45_idslRMReason; - protected int field_46_idslReasonDel; - protected int field_47_cpg; - protected short field_48_Highlight; - /**/private static final BitField icoHighlight = new BitField(0x001f); - /**/private static final BitField fHighlight = new BitField(0x0020); - protected short field_49_CharsetFlags; - /**/private static final BitField fChsDiff = new BitField(0x0001); - /**/private static final BitField fMacChs = new BitField(0x0020); - protected short field_50_chse; - protected boolean field_51_fPropRMark; - protected int field_52_ibstPropRMark; - protected DateAndTime field_53_dttmPropRMark; - protected boolean field_54_fConflictOrig; - protected boolean field_55_fConflictOtherDel; - protected int field_56_wConflict; - protected int field_57_IbstConflict; - protected DateAndTime field_58_dttmConflict; - protected boolean field_59_fDispFldRMark; - protected int field_60_ibstDispFldRMark; - protected DateAndTime field_61_dttmDispFldRMark; - protected byte[] field_62_xstDispFldRMark; - protected int field_63_fcObjp; - protected byte field_64_lbrCRJ; - /**/protected final static byte LBRCRJ_NONE = 0; - /**/protected final static byte LBRCRJ_LEFT = 1; - /**/protected final static byte LBRCRJ_RIGHT = 2; - /**/protected final static byte LBRCRJ_BOTH = 3; - protected boolean field_65_fSpecVanish; - protected boolean field_66_fHasOldProps; - protected boolean field_67_fSdtVanish; - protected int field_68_wCharScale; - - protected CHPAbstractType() - { - this.field_2_hps = 20; - this.field_8_cv = new Colorref(); - this.field_11_lidDefault = 0x0400; - this.field_12_lidFE = 0x0400; - this.field_20_hresi = new Hyphenation(); - this.field_23_shd = new ShadingDescriptor(); - this.field_24_brc = new BorderCode(); - this.field_36_fcPic = -1; - this.field_40_hresiOld = new Hyphenation(); - this.field_42_dttmRMark = new DateAndTime(); - this.field_43_dttmRMarkDel = new DateAndTime(); - this.field_44_istd = 10; - this.field_53_dttmPropRMark = new DateAndTime(); - this.field_58_dttmConflict = new DateAndTime(); - this.field_61_dttmDispFldRMark = new DateAndTime(); - this.field_62_xstDispFldRMark = new byte[32]; - this.field_68_wCharScale = 100; - } - - - @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - return true; - if ( obj == null ) - return false; - if ( getClass() != obj.getClass() ) - return false; - CHPAbstractType other = (CHPAbstractType) obj; - if ( field_1_grpfChp != other.field_1_grpfChp ) - return false; - if ( field_2_hps != other.field_2_hps ) - return false; - if ( field_3_ftcAscii != other.field_3_ftcAscii ) - return false; - if ( field_4_ftcFE != other.field_4_ftcFE ) - return false; - if ( field_5_ftcOther != other.field_5_ftcOther ) - return false; - if ( field_6_ftcBi != other.field_6_ftcBi ) - return false; - if ( field_7_dxaSpace != other.field_7_dxaSpace ) - return false; - if ( field_8_cv == null ) - { - if ( other.field_8_cv != null ) - return false; - } - else if ( !field_8_cv.equals( other.field_8_cv ) ) - return false; - if ( field_9_ico != other.field_9_ico ) - return false; - if ( field_10_pctCharWidth != other.field_10_pctCharWidth ) - return false; - if ( field_11_lidDefault != other.field_11_lidDefault ) - return false; - if ( field_12_lidFE != other.field_12_lidFE ) - return false; - if ( field_13_kcd != other.field_13_kcd ) - return false; - if ( field_14_fUndetermine != other.field_14_fUndetermine ) - return false; - if ( field_15_iss != other.field_15_iss ) - return false; - if ( field_16_fSpecSymbol != other.field_16_fSpecSymbol ) - return false; - if ( field_17_idct != other.field_17_idct ) - return false; - if ( field_18_idctHint != other.field_18_idctHint ) - return false; - if ( field_19_kul != other.field_19_kul ) - return false; - if ( field_20_hresi == null ) - { - if ( other.field_20_hresi != null ) - return false; - } - else if ( !field_20_hresi.equals( other.field_20_hresi ) ) - return false; - if ( field_21_hpsKern != other.field_21_hpsKern ) - return false; - if ( field_22_hpsPos != other.field_22_hpsPos ) - return false; - if ( field_23_shd == null ) - { - if ( other.field_23_shd != null ) - return false; - } - else if ( !field_23_shd.equals( other.field_23_shd ) ) - return false; - if ( field_24_brc == null ) - { - if ( other.field_24_brc != null ) - return false; - } - else if ( !field_24_brc.equals( other.field_24_brc ) ) - return false; - if ( field_25_ibstRMark != other.field_25_ibstRMark ) - return false; - if ( field_26_sfxtText != other.field_26_sfxtText ) - return false; - if ( field_27_fDblBdr != other.field_27_fDblBdr ) - return false; - if ( field_28_fBorderWS != other.field_28_fBorderWS ) - return false; - if ( field_29_ufel != other.field_29_ufel ) - return false; - if ( field_30_copt != other.field_30_copt ) - return false; - if ( field_31_hpsAsci != other.field_31_hpsAsci ) - return false; - if ( field_32_hpsFE != other.field_32_hpsFE ) - return false; - if ( field_33_hpsBi != other.field_33_hpsBi ) - return false; - if ( field_34_ftcSym != other.field_34_ftcSym ) - return false; - if ( field_35_xchSym != other.field_35_xchSym ) - return false; - if ( field_36_fcPic != other.field_36_fcPic ) - return false; - if ( field_37_fcObj != other.field_37_fcObj ) - return false; - if ( field_38_lTagObj != other.field_38_lTagObj ) - return false; - if ( field_39_fcData != other.field_39_fcData ) - return false; - if ( field_40_hresiOld == null ) - { - if ( other.field_40_hresiOld != null ) - return false; - } - else if ( !field_40_hresiOld.equals( other.field_40_hresiOld ) ) - return false; - if ( field_41_ibstRMarkDel != other.field_41_ibstRMarkDel ) - return false; - if ( field_42_dttmRMark == null ) - { - if ( other.field_42_dttmRMark != null ) - return false; - } - else if ( !field_42_dttmRMark.equals( other.field_42_dttmRMark ) ) - return false; - if ( field_43_dttmRMarkDel == null ) - { - if ( other.field_43_dttmRMarkDel != null ) - return false; - } - else if ( !field_43_dttmRMarkDel.equals( other.field_43_dttmRMarkDel ) ) - return false; - if ( field_44_istd != other.field_44_istd ) - return false; - if ( field_45_idslRMReason != other.field_45_idslRMReason ) - return false; - if ( field_46_idslReasonDel != other.field_46_idslReasonDel ) - return false; - if ( field_47_cpg != other.field_47_cpg ) - return false; - if ( field_48_Highlight != other.field_48_Highlight ) - return false; - if ( field_49_CharsetFlags != other.field_49_CharsetFlags ) - return false; - if ( field_50_chse != other.field_50_chse ) - return false; - if ( field_51_fPropRMark != other.field_51_fPropRMark ) - return false; - if ( field_52_ibstPropRMark != other.field_52_ibstPropRMark ) - return false; - if ( field_53_dttmPropRMark == null ) - { - if ( other.field_53_dttmPropRMark != null ) - return false; - } - else if ( !field_53_dttmPropRMark.equals( other.field_53_dttmPropRMark ) ) - return false; - if ( field_54_fConflictOrig != other.field_54_fConflictOrig ) - return false; - if ( field_55_fConflictOtherDel != other.field_55_fConflictOtherDel ) - return false; - if ( field_56_wConflict != other.field_56_wConflict ) - return false; - if ( field_57_IbstConflict != other.field_57_IbstConflict ) - return false; - if ( field_58_dttmConflict == null ) - { - if ( other.field_58_dttmConflict != null ) - return false; - } - else if ( !field_58_dttmConflict.equals( other.field_58_dttmConflict ) ) - return false; - if ( field_59_fDispFldRMark != other.field_59_fDispFldRMark ) - return false; - if ( field_60_ibstDispFldRMark != other.field_60_ibstDispFldRMark ) - return false; - if ( field_61_dttmDispFldRMark == null ) - { - if ( other.field_61_dttmDispFldRMark != null ) - return false; - } - else if ( !field_61_dttmDispFldRMark.equals( other.field_61_dttmDispFldRMark ) ) - return false; - if ( !Arrays.equals( field_62_xstDispFldRMark, other.field_62_xstDispFldRMark ) ) - return false; - if ( field_63_fcObjp != other.field_63_fcObjp ) - return false; - if ( field_64_lbrCRJ != other.field_64_lbrCRJ ) - return false; - if ( field_65_fSpecVanish != other.field_65_fSpecVanish ) - return false; - if ( field_66_fHasOldProps != other.field_66_fHasOldProps ) - return false; - if ( field_67_fSdtVanish != other.field_67_fSdtVanish ) - return false; - if ( field_68_wCharScale != other.field_68_wCharScale ) - return false; - return true; - } - - @Override - public int hashCode() - { - final int prime = 31; - int result = 1; - result = prime * result + field_1_grpfChp; - result = prime * result + field_2_hps; - result = prime * result + field_3_ftcAscii; - result = prime * result + field_4_ftcFE; - result = prime * result + field_5_ftcOther; - result = prime * result + field_6_ftcBi; - result = prime * result + field_7_dxaSpace; - result = prime * result - + ((field_8_cv == null) ? 0 : field_8_cv.hashCode()); - result = prime * result + field_9_ico; - result = prime * result + field_10_pctCharWidth; - result = prime * result + field_11_lidDefault; - result = prime * result + field_12_lidFE; - result = prime * result + field_13_kcd; - result = prime * result + ( field_14_fUndetermine? 1231 : 1237 ); - result = prime * result + field_15_iss; - result = prime * result + ( field_16_fSpecSymbol? 1231 : 1237 ); - result = prime * result + field_17_idct; - result = prime * result + field_18_idctHint; - result = prime * result + field_19_kul; - result = prime * result - + ((field_20_hresi == null) ? 0 : field_20_hresi.hashCode()); - result = prime * result + field_21_hpsKern; - result = prime * result + field_22_hpsPos; - result = prime * result - + ((field_23_shd == null) ? 0 : field_23_shd.hashCode()); - result = prime * result - + ((field_24_brc == null) ? 0 : field_24_brc.hashCode()); - result = prime * result + field_25_ibstRMark; - result = prime * result + field_26_sfxtText; - result = prime * result + ( field_27_fDblBdr? 1231 : 1237 ); - result = prime * result + ( field_28_fBorderWS? 1231 : 1237 ); - result = prime * result + field_29_ufel; - result = prime * result + field_30_copt; - result = prime * result + field_31_hpsAsci; - result = prime * result + field_32_hpsFE; - result = prime * result + field_33_hpsBi; - result = prime * result + field_34_ftcSym; - result = prime * result + field_35_xchSym; - result = prime * result + field_36_fcPic; - result = prime * result + field_37_fcObj; - result = prime * result + field_38_lTagObj; - result = prime * result + field_39_fcData; - result = prime * result - + ((field_40_hresiOld == null) ? 0 : field_40_hresiOld.hashCode()); - result = prime * result + field_41_ibstRMarkDel; - result = prime * result - + ((field_42_dttmRMark == null) ? 0 : field_42_dttmRMark.hashCode()); - result = prime * result - + ((field_43_dttmRMarkDel == null) ? 0 : field_43_dttmRMarkDel.hashCode()); - result = prime * result + field_44_istd; - result = prime * result + field_45_idslRMReason; - result = prime * result + field_46_idslReasonDel; - result = prime * result + field_47_cpg; - result = prime * result + field_48_Highlight; - result = prime * result + field_49_CharsetFlags; - result = prime * result + field_50_chse; - result = prime * result + ( field_51_fPropRMark? 1231 : 1237 ); - result = prime * result + field_52_ibstPropRMark; - result = prime * result - + ((field_53_dttmPropRMark == null) ? 0 : field_53_dttmPropRMark.hashCode()); - result = prime * result + ( field_54_fConflictOrig? 1231 : 1237 ); - result = prime * result + ( field_55_fConflictOtherDel? 1231 : 1237 ); - result = prime * result + field_56_wConflict; - result = prime * result + field_57_IbstConflict; - result = prime * result - + ((field_58_dttmConflict == null) ? 0 : field_58_dttmConflict.hashCode()); - result = prime * result + ( field_59_fDispFldRMark? 1231 : 1237 ); - result = prime * result + field_60_ibstDispFldRMark; - result = prime * result - + ((field_61_dttmDispFldRMark == null) ? 0 : field_61_dttmDispFldRMark.hashCode()); - result = prime * result + Arrays.hashCode( field_62_xstDispFldRMark ); - result = prime * result + field_63_fcObjp; - result = prime * result + field_64_lbrCRJ; - result = prime * result + ( field_65_fSpecVanish? 1231 : 1237 ); - result = prime * result + ( field_66_fHasOldProps? 1231 : 1237 ); - result = prime * result + ( field_67_fSdtVanish? 1231 : 1237 ); - result = prime * result + field_68_wCharScale; - return result; - } - - public String toString() - { - StringBuilder builder = new StringBuilder(); - builder.append("[CHP]\n"); - builder.append(" .grpfChp = "); - builder.append(" (").append(getGrpfChp()).append(" )\n"); - builder.append(" .fBold = ").append(isFBold()).append('\n'); - builder.append(" .fItalic = ").append(isFItalic()).append('\n'); - builder.append(" .fRMarkDel = ").append(isFRMarkDel()).append('\n'); - builder.append(" .fOutline = ").append(isFOutline()).append('\n'); - builder.append(" .fFldVanish = ").append(isFFldVanish()).append('\n'); - builder.append(" .fSmallCaps = ").append(isFSmallCaps()).append('\n'); - builder.append(" .fCaps = ").append(isFCaps()).append('\n'); - builder.append(" .fVanish = ").append(isFVanish()).append('\n'); - builder.append(" .fRMark = ").append(isFRMark()).append('\n'); - builder.append(" .fSpec = ").append(isFSpec()).append('\n'); - builder.append(" .fStrike = ").append(isFStrike()).append('\n'); - builder.append(" .fObj = ").append(isFObj()).append('\n'); - builder.append(" .fShadow = ").append(isFShadow()).append('\n'); - builder.append(" .fLowerCase = ").append(isFLowerCase()).append('\n'); - builder.append(" .fData = ").append(isFData()).append('\n'); - builder.append(" .fOle2 = ").append(isFOle2()).append('\n'); - builder.append(" .fEmboss = ").append(isFEmboss()).append('\n'); - builder.append(" .fImprint = ").append(isFImprint()).append('\n'); - builder.append(" .fDStrike = ").append(isFDStrike()).append('\n'); - builder.append(" .fUsePgsuSettings = ").append(isFUsePgsuSettings()).append('\n'); - builder.append(" .fBoldBi = ").append(isFBoldBi()).append('\n'); - builder.append(" .fComplexScripts = ").append(isFComplexScripts()).append('\n'); - builder.append(" .fItalicBi = ").append(isFItalicBi()).append('\n'); - builder.append(" .fBiDi = ").append(isFBiDi()).append('\n'); - builder.append(" .fIcoBi = ").append(isFIcoBi()).append('\n'); - builder.append(" .fNonGlyph = ").append(isFNonGlyph()).append('\n'); - builder.append(" .fBoldOther = ").append(isFBoldOther()).append('\n'); - builder.append(" .fItalicOther = ").append(isFItalicOther()).append('\n'); - builder.append(" .fNoProof = ").append(isFNoProof()).append('\n'); - builder.append(" .fWebHidden = ").append(isFWebHidden()).append('\n'); - builder.append(" .fFitText = ").append(isFFitText()).append('\n'); - builder.append(" .fCalc = ").append(isFCalc()).append('\n'); - builder.append(" .fFmtLineProp = ").append(isFFmtLineProp()).append('\n'); - builder.append(" .hps = "); - builder.append(" (").append(getHps()).append(" )\n"); - builder.append(" .ftcAscii = "); - builder.append(" (").append(getFtcAscii()).append(" )\n"); - builder.append(" .ftcFE = "); - builder.append(" (").append(getFtcFE()).append(" )\n"); - builder.append(" .ftcOther = "); - builder.append(" (").append(getFtcOther()).append(" )\n"); - builder.append(" .ftcBi = "); - builder.append(" (").append(getFtcBi()).append(" )\n"); - builder.append(" .dxaSpace = "); - builder.append(" (").append(getDxaSpace()).append(" )\n"); - builder.append(" .cv = "); - builder.append(" (").append(getCv()).append(" )\n"); - builder.append(" .ico = "); - builder.append(" (").append(getIco()).append(" )\n"); - builder.append(" .pctCharWidth = "); - builder.append(" (").append(getPctCharWidth()).append(" )\n"); - builder.append(" .lidDefault = "); - builder.append(" (").append(getLidDefault()).append(" )\n"); - builder.append(" .lidFE = "); - builder.append(" (").append(getLidFE()).append(" )\n"); - builder.append(" .kcd = "); - builder.append(" (").append(getKcd()).append(" )\n"); - builder.append(" .fUndetermine = "); - builder.append(" (").append(getFUndetermine()).append(" )\n"); - builder.append(" .iss = "); - builder.append(" (").append(getIss()).append(" )\n"); - builder.append(" .fSpecSymbol = "); - builder.append(" (").append(getFSpecSymbol()).append(" )\n"); - builder.append(" .idct = "); - builder.append(" (").append(getIdct()).append(" )\n"); - builder.append(" .idctHint = "); - builder.append(" (").append(getIdctHint()).append(" )\n"); - builder.append(" .kul = "); - builder.append(" (").append(getKul()).append(" )\n"); - builder.append(" .hresi = "); - builder.append(" (").append(getHresi()).append(" )\n"); - builder.append(" .hpsKern = "); - builder.append(" (").append(getHpsKern()).append(" )\n"); - builder.append(" .hpsPos = "); - builder.append(" (").append(getHpsPos()).append(" )\n"); - builder.append(" .shd = "); - builder.append(" (").append(getShd()).append(" )\n"); - builder.append(" .brc = "); - builder.append(" (").append(getBrc()).append(" )\n"); - builder.append(" .ibstRMark = "); - builder.append(" (").append(getIbstRMark()).append(" )\n"); - builder.append(" .sfxtText = "); - builder.append(" (").append(getSfxtText()).append(" )\n"); - builder.append(" .fDblBdr = "); - builder.append(" (").append(getFDblBdr()).append(" )\n"); - builder.append(" .fBorderWS = "); - builder.append(" (").append(getFBorderWS()).append(" )\n"); - builder.append(" .ufel = "); - builder.append(" (").append(getUfel()).append(" )\n"); - builder.append(" .itypFELayout = ").append(getItypFELayout()).append('\n'); - builder.append(" .fTNY = ").append(isFTNY()).append('\n'); - builder.append(" .fWarichu = ").append(isFWarichu()).append('\n'); - builder.append(" .fKumimoji = ").append(isFKumimoji()).append('\n'); - builder.append(" .fRuby = ").append(isFRuby()).append('\n'); - builder.append(" .fLSFitText = ").append(isFLSFitText()).append('\n'); - builder.append(" .spare = ").append(getSpare()).append('\n'); - builder.append(" .copt = "); - builder.append(" (").append(getCopt()).append(" )\n"); - builder.append(" .iWarichuBracket = ").append(getIWarichuBracket()).append('\n'); - builder.append(" .fWarichuNoOpenBracket = ").append(isFWarichuNoOpenBracket()).append('\n'); - builder.append(" .fTNYCompress = ").append(isFTNYCompress()).append('\n'); - builder.append(" .fTNYFetchTxm = ").append(isFTNYFetchTxm()).append('\n'); - builder.append(" .fCellFitText = ").append(isFCellFitText()).append('\n'); - builder.append(" .unused = ").append(isUnused()).append('\n'); - builder.append(" .hpsAsci = "); - builder.append(" (").append(getHpsAsci()).append(" )\n"); - builder.append(" .hpsFE = "); - builder.append(" (").append(getHpsFE()).append(" )\n"); - builder.append(" .hpsBi = "); - builder.append(" (").append(getHpsBi()).append(" )\n"); - builder.append(" .ftcSym = "); - builder.append(" (").append(getFtcSym()).append(" )\n"); - builder.append(" .xchSym = "); - builder.append(" (").append(getXchSym()).append(" )\n"); - builder.append(" .fcPic = "); - builder.append(" (").append(getFcPic()).append(" )\n"); - builder.append(" .fcObj = "); - builder.append(" (").append(getFcObj()).append(" )\n"); - builder.append(" .lTagObj = "); - builder.append(" (").append(getLTagObj()).append(" )\n"); - builder.append(" .fcData = "); - builder.append(" (").append(getFcData()).append(" )\n"); - builder.append(" .hresiOld = "); - builder.append(" (").append(getHresiOld()).append(" )\n"); - builder.append(" .ibstRMarkDel = "); - builder.append(" (").append(getIbstRMarkDel()).append(" )\n"); - builder.append(" .dttmRMark = "); - builder.append(" (").append(getDttmRMark()).append(" )\n"); - builder.append(" .dttmRMarkDel = "); - builder.append(" (").append(getDttmRMarkDel()).append(" )\n"); - builder.append(" .istd = "); - builder.append(" (").append(getIstd()).append(" )\n"); - builder.append(" .idslRMReason = "); - builder.append(" (").append(getIdslRMReason()).append(" )\n"); - builder.append(" .idslReasonDel = "); - builder.append(" (").append(getIdslReasonDel()).append(" )\n"); - builder.append(" .cpg = "); - builder.append(" (").append(getCpg()).append(" )\n"); - builder.append(" .Highlight = "); - builder.append(" (").append(getHighlight()).append(" )\n"); - builder.append(" .icoHighlight = ").append(getIcoHighlight()).append('\n'); - builder.append(" .fHighlight = ").append(isFHighlight()).append('\n'); - builder.append(" .CharsetFlags = "); - builder.append(" (").append(getCharsetFlags()).append(" )\n"); - builder.append(" .fChsDiff = ").append(isFChsDiff()).append('\n'); - builder.append(" .fMacChs = ").append(isFMacChs()).append('\n'); - builder.append(" .chse = "); - builder.append(" (").append(getChse()).append(" )\n"); - builder.append(" .fPropRMark = "); - builder.append(" (").append(getFPropRMark()).append(" )\n"); - builder.append(" .ibstPropRMark = "); - builder.append(" (").append(getIbstPropRMark()).append(" )\n"); - builder.append(" .dttmPropRMark = "); - builder.append(" (").append(getDttmPropRMark()).append(" )\n"); - builder.append(" .fConflictOrig = "); - builder.append(" (").append(getFConflictOrig()).append(" )\n"); - builder.append(" .fConflictOtherDel = "); - builder.append(" (").append(getFConflictOtherDel()).append(" )\n"); - builder.append(" .wConflict = "); - builder.append(" (").append(getWConflict()).append(" )\n"); - builder.append(" .IbstConflict = "); - builder.append(" (").append(getIbstConflict()).append(" )\n"); - builder.append(" .dttmConflict = "); - builder.append(" (").append(getDttmConflict()).append(" )\n"); - builder.append(" .fDispFldRMark = "); - builder.append(" (").append(getFDispFldRMark()).append(" )\n"); - builder.append(" .ibstDispFldRMark = "); - builder.append(" (").append(getIbstDispFldRMark()).append(" )\n"); - builder.append(" .dttmDispFldRMark = "); - builder.append(" (").append(getDttmDispFldRMark()).append(" )\n"); - builder.append(" .xstDispFldRMark = "); - builder.append(" (").append(Arrays.toString(getXstDispFldRMark())).append(" )\n"); - builder.append(" .fcObjp = "); - builder.append(" (").append(getFcObjp()).append(" )\n"); - builder.append(" .lbrCRJ = "); - builder.append(" (").append(getLbrCRJ()).append(" )\n"); - builder.append(" .fSpecVanish = "); - builder.append(" (").append(getFSpecVanish()).append(" )\n"); - builder.append(" .fHasOldProps = "); - builder.append(" (").append(getFHasOldProps()).append(" )\n"); - builder.append(" .fSdtVanish = "); - builder.append(" (").append(getFSdtVanish()).append(" )\n"); - builder.append(" .wCharScale = "); - builder.append(" (").append(getWCharScale()).append(" )\n"); - - builder.append("[/CHP]\n"); - return builder.toString(); - } - - /** - * Collection of the 32 flags. - */ - @Internal - public int getGrpfChp() - { - return field_1_grpfChp; - } - - /** - * Collection of the 32 flags. - */ - @Internal - public void setGrpfChp( int field_1_grpfChp ) - { - this.field_1_grpfChp = field_1_grpfChp; - } - - /** - * Font size in half points. - */ - @Internal - public int getHps() - { - return field_2_hps; - } - - /** - * Font size in half points. - */ - @Internal - public void setHps( int field_2_hps ) - { - this.field_2_hps = field_2_hps; - } - - /** - * Font for ASCII text. - */ - @Internal - public int getFtcAscii() - { - return field_3_ftcAscii; - } - - /** - * Font for ASCII text. - */ - @Internal - public void setFtcAscii( int field_3_ftcAscii ) - { - this.field_3_ftcAscii = field_3_ftcAscii; - } - - /** - * Font for East Asian text. - */ - @Internal - public int getFtcFE() - { - return field_4_ftcFE; - } - - /** - * Font for East Asian text. - */ - @Internal - public void setFtcFE( int field_4_ftcFE ) - { - this.field_4_ftcFE = field_4_ftcFE; - } - - /** - * Font for non-East Asian text. - */ - @Internal - public int getFtcOther() - { - return field_5_ftcOther; - } - - /** - * Font for non-East Asian text. - */ - @Internal - public void setFtcOther( int field_5_ftcOther ) - { - this.field_5_ftcOther = field_5_ftcOther; - } - - /** - * Font for Complex Scripts text. - */ - @Internal - public int getFtcBi() - { - return field_6_ftcBi; - } - - /** - * Font for Complex Scripts text. - */ - @Internal - public void setFtcBi( int field_6_ftcBi ) - { - this.field_6_ftcBi = field_6_ftcBi; - } - - /** - * Space following each character in the run expressed in twip units.. - */ - @Internal - public int getDxaSpace() - { - return field_7_dxaSpace; - } - - /** - * Space following each character in the run expressed in twip units.. - */ - @Internal - public void setDxaSpace( int field_7_dxaSpace ) - { - this.field_7_dxaSpace = field_7_dxaSpace; - } - - /** - * 24-bit color. - */ - @Internal - public Colorref getCv() - { - return field_8_cv; - } - - /** - * 24-bit color. - */ - @Internal - public void setCv( Colorref field_8_cv ) - { - this.field_8_cv = field_8_cv; - } - - /** - * Color of text for Word 97. - */ - @Internal - public byte getIco() - { - return field_9_ico; - } - - /** - * Color of text for Word 97. - */ - @Internal - public void setIco( byte field_9_ico ) - { - this.field_9_ico = field_9_ico; - } - - /** - * Character scale. - */ - @Internal - public int getPctCharWidth() - { - return field_10_pctCharWidth; - } - - /** - * Character scale. - */ - @Internal - public void setPctCharWidth( int field_10_pctCharWidth ) - { - this.field_10_pctCharWidth = field_10_pctCharWidth; - } - - /** - * Get the lidDefault field for the CHP record. - */ - @Internal - public int getLidDefault() - { - return field_11_lidDefault; - } - - /** - * Set the lidDefault field for the CHP record. - */ - @Internal - public void setLidDefault( int field_11_lidDefault ) - { - this.field_11_lidDefault = field_11_lidDefault; - } - - /** - * Get the lidFE field for the CHP record. - */ - @Internal - public int getLidFE() - { - return field_12_lidFE; - } - - /** - * Set the lidFE field for the CHP record. - */ - @Internal - public void setLidFE( int field_12_lidFE ) - { - this.field_12_lidFE = field_12_lidFE; - } - - /** - * Emphasis mark. - * - * @return One of - *

  • {@link #KCD_NON} - *
  • {@link #KCD_DOT} - *
  • {@link #KCD_COMMA} - *
  • {@link #KCD_CIRCLE} - *
  • {@link #KCD_UNDER_DOT} - */ - @Internal - public byte getKcd() - { - return field_13_kcd; - } - - /** - * Emphasis mark. - * - * @param field_13_kcd - * One of - *
  • {@link #KCD_NON} - *
  • {@link #KCD_DOT} - *
  • {@link #KCD_COMMA} - *
  • {@link #KCD_CIRCLE} - *
  • {@link #KCD_UNDER_DOT} - */ - @Internal - public void setKcd( byte field_13_kcd ) - { - this.field_13_kcd = field_13_kcd; - } - - /** - * Character is undetermined. - */ - @Internal - public boolean getFUndetermine() - { - return field_14_fUndetermine; - } - - /** - * Character is undetermined. - */ - @Internal - public void setFUndetermine( boolean field_14_fUndetermine ) - { - this.field_14_fUndetermine = field_14_fUndetermine; - } - - /** - * Superscript/subscript indices. - * - * @return One of - *
  • {@link #ISS_NONE} - *
  • {@link #ISS_SUPERSCRIPTED} - *
  • {@link #ISS_SUBSCRIPTED} - */ - @Internal - public byte getIss() - { - return field_15_iss; - } - - /** - * Superscript/subscript indices. - * - * @param field_15_iss - * One of - *
  • {@link #ISS_NONE} - *
  • {@link #ISS_SUPERSCRIPTED} - *
  • {@link #ISS_SUBSCRIPTED} - */ - @Internal - public void setIss( byte field_15_iss ) - { - this.field_15_iss = field_15_iss; - } - - /** - * Used by Word internally. - */ - @Internal - public boolean getFSpecSymbol() - { - return field_16_fSpecSymbol; - } - - /** - * Used by Word internally. - */ - @Internal - public void setFSpecSymbol( boolean field_16_fSpecSymbol ) - { - this.field_16_fSpecSymbol = field_16_fSpecSymbol; - } - - /** - * Not stored in file. - */ - @Internal - public byte getIdct() - { - return field_17_idct; - } - - /** - * Not stored in file. - */ - @Internal - public void setIdct( byte field_17_idct ) - { - this.field_17_idct = field_17_idct; - } - - /** - * Identifier of Character type. - */ - @Internal - public byte getIdctHint() - { - return field_18_idctHint; - } - - /** - * Identifier of Character type. - */ - @Internal - public void setIdctHint( byte field_18_idctHint ) - { - this.field_18_idctHint = field_18_idctHint; - } - - /** - * Underline code. - * - * @return One of - *
  • {@link #KUL_NONE} - *
  • {@link #KUL_SINGLE} - *
  • {@link #KUL_BY_WORD} - *
  • {@link #KUL_DOUBLE} - *
  • {@link #KUL_DOTTED} - *
  • {@link #KUL_HIDDEN} - *
  • {@link #KUL_THICK} - *
  • {@link #KUL_DASH} - *
  • {@link #KUL_DOT} - *
  • {@link #KUL_DOT_DASH} - *
  • {@link #KUL_DOT_DOT_DASH} - *
  • {@link #KUL_WAVE} - *
  • {@link #KUL_DOTTED_HEAVY} - *
  • {@link #KUL_DASHED_HEAVY} - *
  • {@link #KUL_DOT_DASH_HEAVY} - *
  • {@link #KUL_DOT_DOT_DASH_HEAVY} - *
  • {@link #KUL_WAVE_HEAVY} - *
  • {@link #KUL_DASH_LONG} - *
  • {@link #KUL_WAVE_DOUBLE} - *
  • {@link #KUL_DASH_LONG_HEAVY} - */ - @Internal - public byte getKul() - { - return field_19_kul; - } - - /** - * Underline code. - * - * @param field_19_kul - * One of - *
  • {@link #KUL_NONE} - *
  • {@link #KUL_SINGLE} - *
  • {@link #KUL_BY_WORD} - *
  • {@link #KUL_DOUBLE} - *
  • {@link #KUL_DOTTED} - *
  • {@link #KUL_HIDDEN} - *
  • {@link #KUL_THICK} - *
  • {@link #KUL_DASH} - *
  • {@link #KUL_DOT} - *
  • {@link #KUL_DOT_DASH} - *
  • {@link #KUL_DOT_DOT_DASH} - *
  • {@link #KUL_WAVE} - *
  • {@link #KUL_DOTTED_HEAVY} - *
  • {@link #KUL_DASHED_HEAVY} - *
  • {@link #KUL_DOT_DASH_HEAVY} - *
  • {@link #KUL_DOT_DOT_DASH_HEAVY} - *
  • {@link #KUL_WAVE_HEAVY} - *
  • {@link #KUL_DASH_LONG} - *
  • {@link #KUL_WAVE_DOUBLE} - *
  • {@link #KUL_DASH_LONG_HEAVY} - */ - @Internal - public void setKul( byte field_19_kul ) - { - this.field_19_kul = field_19_kul; - } - - /** - * Get the hresi field for the CHP record. - */ - @Internal - public Hyphenation getHresi() - { - return field_20_hresi; - } - - /** - * Set the hresi field for the CHP record. - */ - @Internal - public void setHresi( Hyphenation field_20_hresi ) - { - this.field_20_hresi = field_20_hresi; - } - - /** - * Kerning distance for characters in run recorded in half points. - */ - @Internal - public int getHpsKern() - { - return field_21_hpsKern; - } - - /** - * Kerning distance for characters in run recorded in half points. - */ - @Internal - public void setHpsKern( int field_21_hpsKern ) - { - this.field_21_hpsKern = field_21_hpsKern; - } - - /** - * Reserved (actually used as vertical offset(?) value). - */ - @Internal - public short getHpsPos() - { - return field_22_hpsPos; - } - - /** - * Reserved (actually used as vertical offset(?) value). - */ - @Internal - public void setHpsPos( short field_22_hpsPos ) - { - this.field_22_hpsPos = field_22_hpsPos; - } - - /** - * Shading. - */ - @Internal - public ShadingDescriptor getShd() - { - return field_23_shd; - } - - /** - * Shading. - */ - @Internal - public void setShd( ShadingDescriptor field_23_shd ) - { - this.field_23_shd = field_23_shd; - } - - /** - * Border. - */ - @Internal - public BorderCode getBrc() - { - return field_24_brc; - } - - /** - * Border. - */ - @Internal - public void setBrc( BorderCode field_24_brc ) - { - this.field_24_brc = field_24_brc; - } - - /** - * Index to author IDs stored in hsttbfRMark. Used when text in run was newly typed when revision marking was enabled. - */ - @Internal - public int getIbstRMark() - { - return field_25_ibstRMark; - } - - /** - * Index to author IDs stored in hsttbfRMark. Used when text in run was newly typed when revision marking was enabled. - */ - @Internal - public void setIbstRMark( int field_25_ibstRMark ) - { - this.field_25_ibstRMark = field_25_ibstRMark; - } - - /** - * Text animation. - * - * @return One of - *
  • {@link #SFXTTEXT_NO} - *
  • {@link #SFXTTEXT_LAS_VEGAS_LIGHTS} - *
  • {@link #SFXTTEXT_BACKGROUND_BLINK} - *
  • {@link #SFXTTEXT_SPARKLE_TEXT} - *
  • {@link #SFXTTEXT_MARCHING_ANTS} - *
  • {@link #SFXTTEXT_MARCHING_RED_ANTS} - *
  • {@link #SFXTTEXT_SHIMMER} - */ - @Internal - public byte getSfxtText() - { - return field_26_sfxtText; - } - - /** - * Text animation. - * - * @param field_26_sfxtText - * One of - *
  • {@link #SFXTTEXT_NO} - *
  • {@link #SFXTTEXT_LAS_VEGAS_LIGHTS} - *
  • {@link #SFXTTEXT_BACKGROUND_BLINK} - *
  • {@link #SFXTTEXT_SPARKLE_TEXT} - *
  • {@link #SFXTTEXT_MARCHING_ANTS} - *
  • {@link #SFXTTEXT_MARCHING_RED_ANTS} - *
  • {@link #SFXTTEXT_SHIMMER} - */ - @Internal - public void setSfxtText( byte field_26_sfxtText ) - { - this.field_26_sfxtText = field_26_sfxtText; - } - - /** - * Used internally by Word. - */ - @Internal - public boolean getFDblBdr() - { - return field_27_fDblBdr; - } - - /** - * Used internally by Word. - */ - @Internal - public void setFDblBdr( boolean field_27_fDblBdr ) - { - this.field_27_fDblBdr = field_27_fDblBdr; - } - - /** - * Used internally by Word. - */ - @Internal - public boolean getFBorderWS() - { - return field_28_fBorderWS; - } - - /** - * Used internally by Word. - */ - @Internal - public void setFBorderWS( boolean field_28_fBorderWS ) - { - this.field_28_fBorderWS = field_28_fBorderWS; - } - - /** - * Collection properties represented by itypFELayout and copt (East Asian layout properties). - */ - @Internal - public short getUfel() - { - return field_29_ufel; - } - - /** - * Collection properties represented by itypFELayout and copt (East Asian layout properties). - */ - @Internal - public void setUfel( short field_29_ufel ) - { - this.field_29_ufel = field_29_ufel; - } - - /** - * Collection of the 5 flags. - */ - @Internal - public byte getCopt() - { - return field_30_copt; - } - - /** - * Collection of the 5 flags. - */ - @Internal - public void setCopt( byte field_30_copt ) - { - this.field_30_copt = field_30_copt; - } - - /** - * Font size for ASCII font. - */ - @Internal - public int getHpsAsci() - { - return field_31_hpsAsci; - } - - /** - * Font size for ASCII font. - */ - @Internal - public void setHpsAsci( int field_31_hpsAsci ) - { - this.field_31_hpsAsci = field_31_hpsAsci; - } - - /** - * Font size for East Asian text. - */ - @Internal - public int getHpsFE() - { - return field_32_hpsFE; - } - - /** - * Font size for East Asian text. - */ - @Internal - public void setHpsFE( int field_32_hpsFE ) - { - this.field_32_hpsFE = field_32_hpsFE; - } - - /** - * Font size for Complex Scripts text. - */ - @Internal - public int getHpsBi() - { - return field_33_hpsBi; - } - - /** - * Font size for Complex Scripts text. - */ - @Internal - public void setHpsBi( int field_33_hpsBi ) - { - this.field_33_hpsBi = field_33_hpsBi; - } - - /** - * an index into the rgffn structure. When chp.fSpec is 1 and the character recorded for the run in the document stream is chSymbol (0x28), chp.ftcSym identifies the font code of the symbol font that will be used to display the symbol character recorded in chp.xchSym.. - */ - @Internal - public int getFtcSym() - { - return field_34_ftcSym; - } - - /** - * an index into the rgffn structure. When chp.fSpec is 1 and the character recorded for the run in the document stream is chSymbol (0x28), chp.ftcSym identifies the font code of the symbol font that will be used to display the symbol character recorded in chp.xchSym.. - */ - @Internal - public void setFtcSym( int field_34_ftcSym ) - { - this.field_34_ftcSym = field_34_ftcSym; - } - - /** - * When chp.fSpec==1 and the character recorded for the run in the document stream is chSymbol (0x28), the character stored chp.xchSym will be displayed using the font specified in chp.ftcSym.. - */ - @Internal - public int getXchSym() - { - return field_35_xchSym; - } - - /** - * When chp.fSpec==1 and the character recorded for the run in the document stream is chSymbol (0x28), the character stored chp.xchSym will be displayed using the font specified in chp.ftcSym.. - */ - @Internal - public void setXchSym( int field_35_xchSym ) - { - this.field_35_xchSym = field_35_xchSym; - } - - /** - * Offset in data stream pointing to beginning of a picture when character is a picture character (character is 0x01 and chp.fSpec is 1).. - */ - @Internal - public int getFcPic() - { - return field_36_fcPic; - } - - /** - * Offset in data stream pointing to beginning of a picture when character is a picture character (character is 0x01 and chp.fSpec is 1).. - */ - @Internal - public void setFcPic( int field_36_fcPic ) - { - this.field_36_fcPic = field_36_fcPic; - } - - /** - * Offset in data stream pointing to beginning of a picture when character is an OLE1 object character (character is 0x20 and chp.fSpec is 1, chp.fOle2 is 0).. - */ - @Internal - public int getFcObj() - { - return field_37_fcObj; - } - - /** - * Offset in data stream pointing to beginning of a picture when character is an OLE1 object character (character is 0x20 and chp.fSpec is 1, chp.fOle2 is 0).. - */ - @Internal - public void setFcObj( int field_37_fcObj ) - { - this.field_37_fcObj = field_37_fcObj; - } - - /** - * An object ID for an OLE object, only set if chp.fSpec and chp.fOle2 are both true, and chp.fObj.. - */ - @Internal - public int getLTagObj() - { - return field_38_lTagObj; - } - - /** - * An object ID for an OLE object, only set if chp.fSpec and chp.fOle2 are both true, and chp.fObj.. - */ - @Internal - public void setLTagObj( int field_38_lTagObj ) - { - this.field_38_lTagObj = field_38_lTagObj; - } - - /** - * Points to location of picture data, only if chp.fSpec is true.. - */ - @Internal - public int getFcData() - { - return field_39_fcData; - } - - /** - * Points to location of picture data, only if chp.fSpec is true.. - */ - @Internal - public void setFcData( int field_39_fcData ) - { - this.field_39_fcData = field_39_fcData; - } - - /** - * Get the hresiOld field for the CHP record. - */ - @Internal - public Hyphenation getHresiOld() - { - return field_40_hresiOld; - } - - /** - * Set the hresiOld field for the CHP record. - */ - @Internal - public void setHresiOld( Hyphenation field_40_hresiOld ) - { - this.field_40_hresiOld = field_40_hresiOld; - } - - /** - * Index to author IDs stored in hsttbfRMark. Used when text in run was deleted when revision marking was enabled.. - */ - @Internal - public int getIbstRMarkDel() - { - return field_41_ibstRMarkDel; - } - - /** - * Index to author IDs stored in hsttbfRMark. Used when text in run was deleted when revision marking was enabled.. - */ - @Internal - public void setIbstRMarkDel( int field_41_ibstRMarkDel ) - { - this.field_41_ibstRMarkDel = field_41_ibstRMarkDel; - } - - /** - * Date/time at which this run of text was entered/modified by the author (Only recorded when revision marking is on.). - */ - @Internal - public DateAndTime getDttmRMark() - { - return field_42_dttmRMark; - } - - /** - * Date/time at which this run of text was entered/modified by the author (Only recorded when revision marking is on.). - */ - @Internal - public void setDttmRMark( DateAndTime field_42_dttmRMark ) - { - this.field_42_dttmRMark = field_42_dttmRMark; - } - - /** - * Date/time at which this run of text was deleted by the author (Only recorded when revision marking is on.). - */ - @Internal - public DateAndTime getDttmRMarkDel() - { - return field_43_dttmRMarkDel; - } - - /** - * Date/time at which this run of text was deleted by the author (Only recorded when revision marking is on.). - */ - @Internal - public void setDttmRMarkDel( DateAndTime field_43_dttmRMarkDel ) - { - this.field_43_dttmRMarkDel = field_43_dttmRMarkDel; - } - - /** - * Index to character style descriptor in the stylesheet that tags this run of text. When istd is istdNormalChar (10 decimal), characters in run are not affected by a character style. If chp.istd contains any other value, chpx of the specified character style are applied to CHP for this run before any other exceptional properties are applied.. - */ - @Internal - public int getIstd() - { - return field_44_istd; - } - - /** - * Index to character style descriptor in the stylesheet that tags this run of text. When istd is istdNormalChar (10 decimal), characters in run are not affected by a character style. If chp.istd contains any other value, chpx of the specified character style are applied to CHP for this run before any other exceptional properties are applied.. - */ - @Internal - public void setIstd( int field_44_istd ) - { - this.field_44_istd = field_44_istd; - } - - /** - * An index to strings displayed as reasons for actions taken by Word's AutoFormat code. - */ - @Internal - public int getIdslRMReason() - { - return field_45_idslRMReason; - } - - /** - * An index to strings displayed as reasons for actions taken by Word's AutoFormat code. - */ - @Internal - public void setIdslRMReason( int field_45_idslRMReason ) - { - this.field_45_idslRMReason = field_45_idslRMReason; - } - - /** - * An index to strings displayed as reasons for actions taken by Word's AutoFormat code. - */ - @Internal - public int getIdslReasonDel() - { - return field_46_idslReasonDel; - } - - /** - * An index to strings displayed as reasons for actions taken by Word's AutoFormat code. - */ - @Internal - public void setIdslReasonDel( int field_46_idslReasonDel ) - { - this.field_46_idslReasonDel = field_46_idslReasonDel; - } - - /** - * Code page of run in pre-Unicode files. - */ - @Internal - public int getCpg() - { - return field_47_cpg; - } - - /** - * Code page of run in pre-Unicode files. - */ - @Internal - public void setCpg( int field_47_cpg ) - { - this.field_47_cpg = field_47_cpg; - } - - /** - * Get the Highlight field for the CHP record. - */ - @Internal - public short getHighlight() - { - return field_48_Highlight; - } - - /** - * Set the Highlight field for the CHP record. - */ - @Internal - public void setHighlight( short field_48_Highlight ) - { - this.field_48_Highlight = field_48_Highlight; - } - - /** - * Get the CharsetFlags field for the CHP record. - */ - @Internal - public short getCharsetFlags() - { - return field_49_CharsetFlags; - } - - /** - * Set the CharsetFlags field for the CHP record. - */ - @Internal - public void setCharsetFlags( short field_49_CharsetFlags ) - { - this.field_49_CharsetFlags = field_49_CharsetFlags; - } - - /** - * Get the chse field for the CHP record. - */ - @Internal - public short getChse() - { - return field_50_chse; - } - - /** - * Set the chse field for the CHP record. - */ - @Internal - public void setChse( short field_50_chse ) - { - this.field_50_chse = field_50_chse; - } - - /** - * properties have been changed with revision marking on. - */ - @Internal - public boolean getFPropRMark() - { - return field_51_fPropRMark; - } - - /** - * properties have been changed with revision marking on. - */ - @Internal - public void setFPropRMark( boolean field_51_fPropRMark ) - { - this.field_51_fPropRMark = field_51_fPropRMark; - } - - /** - * Index to author IDs stored in hsttbfRMark. Used when properties have been changed when revision marking was enabled.. - */ - @Internal - public int getIbstPropRMark() - { - return field_52_ibstPropRMark; - } - - /** - * Index to author IDs stored in hsttbfRMark. Used when properties have been changed when revision marking was enabled.. - */ - @Internal - public void setIbstPropRMark( int field_52_ibstPropRMark ) - { - this.field_52_ibstPropRMark = field_52_ibstPropRMark; - } - - /** - * Date/time at which properties of this were changed for this run of text by the author. (Only recorded when revision marking is on.). - */ - @Internal - public DateAndTime getDttmPropRMark() - { - return field_53_dttmPropRMark; - } - - /** - * Date/time at which properties of this were changed for this run of text by the author. (Only recorded when revision marking is on.). - */ - @Internal - public void setDttmPropRMark( DateAndTime field_53_dttmPropRMark ) - { - this.field_53_dttmPropRMark = field_53_dttmPropRMark; - } - - /** - * When chp.wConflict!=0, this is TRUE when text is part of the original version of text. When FALSE, text is alternative introduced by reconciliation operation.. - */ - @Internal - public boolean getFConflictOrig() - { - return field_54_fConflictOrig; - } - - /** - * When chp.wConflict!=0, this is TRUE when text is part of the original version of text. When FALSE, text is alternative introduced by reconciliation operation.. - */ - @Internal - public void setFConflictOrig( boolean field_54_fConflictOrig ) - { - this.field_54_fConflictOrig = field_54_fConflictOrig; - } - - /** - * When fConflictOtherDel==fTrue, the other side of a reconciliation conflict causes this text to be deleted. - */ - @Internal - public boolean getFConflictOtherDel() - { - return field_55_fConflictOtherDel; - } - - /** - * When fConflictOtherDel==fTrue, the other side of a reconciliation conflict causes this text to be deleted. - */ - @Internal - public void setFConflictOtherDel( boolean field_55_fConflictOtherDel ) - { - this.field_55_fConflictOtherDel = field_55_fConflictOtherDel; - } - - /** - * When != 0, index number that identifies all text participating in a particular conflict incident. - */ - @Internal - public int getWConflict() - { - return field_56_wConflict; - } - - /** - * When != 0, index number that identifies all text participating in a particular conflict incident. - */ - @Internal - public void setWConflict( int field_56_wConflict ) - { - this.field_56_wConflict = field_56_wConflict; - } - - /** - * Who made this change for this side of the conflict.. - */ - @Internal - public int getIbstConflict() - { - return field_57_IbstConflict; - } - - /** - * Who made this change for this side of the conflict.. - */ - @Internal - public void setIbstConflict( int field_57_IbstConflict ) - { - this.field_57_IbstConflict = field_57_IbstConflict; - } - - /** - * When the change was made. - */ - @Internal - public DateAndTime getDttmConflict() - { - return field_58_dttmConflict; - } - - /** - * When the change was made. - */ - @Internal - public void setDttmConflict( DateAndTime field_58_dttmConflict ) - { - this.field_58_dttmConflict = field_58_dttmConflict; - } - - /** - * the number for a ListNum field is being tracked in xstDispFldRMark. If that number is different from the current value, the number has changed. Only valid for ListNum fields.. - */ - @Internal - public boolean getFDispFldRMark() - { - return field_59_fDispFldRMark; - } - - /** - * the number for a ListNum field is being tracked in xstDispFldRMark. If that number is different from the current value, the number has changed. Only valid for ListNum fields.. - */ - @Internal - public void setFDispFldRMark( boolean field_59_fDispFldRMark ) - { - this.field_59_fDispFldRMark = field_59_fDispFldRMark; - } - - /** - * Index to author IDs stored in hsttbfRMark. Used when ListNum field numbering has been changed when revision marking was enabled.. - */ - @Internal - public int getIbstDispFldRMark() - { - return field_60_ibstDispFldRMark; - } - - /** - * Index to author IDs stored in hsttbfRMark. Used when ListNum field numbering has been changed when revision marking was enabled.. - */ - @Internal - public void setIbstDispFldRMark( int field_60_ibstDispFldRMark ) - { - this.field_60_ibstDispFldRMark = field_60_ibstDispFldRMark; - } - - /** - * The date for the ListNum field number change. - */ - @Internal - public DateAndTime getDttmDispFldRMark() - { - return field_61_dttmDispFldRMark; - } - - /** - * The date for the ListNum field number change. - */ - @Internal - public void setDttmDispFldRMark( DateAndTime field_61_dttmDispFldRMark ) - { - this.field_61_dttmDispFldRMark = field_61_dttmDispFldRMark; - } - - /** - * The string value of the ListNum field when revision mark tracking began. - */ - @Internal - public byte[] getXstDispFldRMark() - { - return field_62_xstDispFldRMark; - } - - /** - * The string value of the ListNum field when revision mark tracking began. - */ - @Internal - public void setXstDispFldRMark( byte[] field_62_xstDispFldRMark ) - { - this.field_62_xstDispFldRMark = field_62_xstDispFldRMark; - } - - /** - * Offset in the data stream indicating the location of OLE object data. - */ - @Internal - public int getFcObjp() - { - return field_63_fcObjp; - } - - /** - * Offset in the data stream indicating the location of OLE object data. - */ - @Internal - public void setFcObjp( int field_63_fcObjp ) - { - this.field_63_fcObjp = field_63_fcObjp; - } - - /** - * Line BReak code for xchCRJ. - * - * @return One of - *
  • {@link #LBRCRJ_NONE} - *
  • {@link #LBRCRJ_LEFT} - *
  • {@link #LBRCRJ_RIGHT} - *
  • {@link #LBRCRJ_BOTH} - */ - @Internal - public byte getLbrCRJ() - { - return field_64_lbrCRJ; - } - - /** - * Line BReak code for xchCRJ. - * - * @param field_64_lbrCRJ - * One of - *
  • {@link #LBRCRJ_NONE} - *
  • {@link #LBRCRJ_LEFT} - *
  • {@link #LBRCRJ_RIGHT} - *
  • {@link #LBRCRJ_BOTH} - */ - @Internal - public void setLbrCRJ( byte field_64_lbrCRJ ) - { - this.field_64_lbrCRJ = field_64_lbrCRJ; - } - - /** - * Special hidden for leading emphasis (always hidden). - */ - @Internal - public boolean getFSpecVanish() - { - return field_65_fSpecVanish; - } - - /** - * Special hidden for leading emphasis (always hidden). - */ - @Internal - public void setFSpecVanish( boolean field_65_fSpecVanish ) - { - this.field_65_fSpecVanish = field_65_fSpecVanish; - } - - /** - * Used for character property revision marking. The chp at the time fHasOldProps is set to 1, the is the old chp.. - */ - @Internal - public boolean getFHasOldProps() - { - return field_66_fHasOldProps; - } - - /** - * Used for character property revision marking. The chp at the time fHasOldProps is set to 1, the is the old chp.. - */ - @Internal - public void setFHasOldProps( boolean field_66_fHasOldProps ) - { - this.field_66_fHasOldProps = field_66_fHasOldProps; - } - - /** - * Mark the character as hidden.. - */ - @Internal - public boolean getFSdtVanish() - { - return field_67_fSdtVanish; - } - - /** - * Mark the character as hidden.. - */ - @Internal - public void setFSdtVanish( boolean field_67_fSdtVanish ) - { - this.field_67_fSdtVanish = field_67_fSdtVanish; - } - - /** - * Get the wCharScale field for the CHP record. - */ - @Internal - public int getWCharScale() - { - return field_68_wCharScale; - } - - /** - * Set the wCharScale field for the CHP record. - */ - @Internal - public void setWCharScale( int field_68_wCharScale ) - { - this.field_68_wCharScale = field_68_wCharScale; - } - - /** - * Sets the fBold field value. - * Text is bold - */ - @Internal - public void setFBold( boolean value ) - { - field_1_grpfChp = fBold.setBoolean(field_1_grpfChp, value); - } - - /** - * Text is bold - * @return the fBold field value. - */ - @Internal - public boolean isFBold() - { - return fBold.isSet(field_1_grpfChp); - } - - /** - * Sets the fItalic field value. - * Italic - */ - @Internal - public void setFItalic( boolean value ) - { - field_1_grpfChp = fItalic.setBoolean(field_1_grpfChp, value); - } - - /** - * Italic - * @return the fItalic field value. - */ - @Internal - public boolean isFItalic() - { - return fItalic.isSet(field_1_grpfChp); - } - - /** - * Sets the fRMarkDel field value. - * has been deleted and will be displayed with strikethrough when revision marked text is to be displayed - */ - @Internal - public void setFRMarkDel( boolean value ) - { - field_1_grpfChp = fRMarkDel.setBoolean(field_1_grpfChp, value); - } - - /** - * has been deleted and will be displayed with strikethrough when revision marked text is to be displayed - * @return the fRMarkDel field value. - */ - @Internal - public boolean isFRMarkDel() - { - return fRMarkDel.isSet(field_1_grpfChp); - } - - /** - * Sets the fOutline field value. - * Outlined - */ - @Internal - public void setFOutline( boolean value ) - { - field_1_grpfChp = fOutline.setBoolean(field_1_grpfChp, value); - } - - /** - * Outlined - * @return the fOutline field value. - */ - @Internal - public boolean isFOutline() - { - return fOutline.isSet(field_1_grpfChp); - } - - /** - * Sets the fFldVanish field value. - * Used internally by Word - */ - @Internal - public void setFFldVanish( boolean value ) - { - field_1_grpfChp = fFldVanish.setBoolean(field_1_grpfChp, value); - } - - /** - * Used internally by Word - * @return the fFldVanish field value. - */ - @Internal - public boolean isFFldVanish() - { - return fFldVanish.isSet(field_1_grpfChp); - } - - /** - * Sets the fSmallCaps field value. - * Displayed with small caps - */ - @Internal - public void setFSmallCaps( boolean value ) - { - field_1_grpfChp = fSmallCaps.setBoolean(field_1_grpfChp, value); - } - - /** - * Displayed with small caps - * @return the fSmallCaps field value. - */ - @Internal - public boolean isFSmallCaps() - { - return fSmallCaps.isSet(field_1_grpfChp); - } - - /** - * Sets the fCaps field value. - * Displayed with caps - */ - @Internal - public void setFCaps( boolean value ) - { - field_1_grpfChp = fCaps.setBoolean(field_1_grpfChp, value); - } - - /** - * Displayed with caps - * @return the fCaps field value. - */ - @Internal - public boolean isFCaps() - { - return fCaps.isSet(field_1_grpfChp); - } - - /** - * Sets the fVanish field value. - * text has hidden format, and is not displayed unless fPagHidden is set in the DOP - */ - @Internal - public void setFVanish( boolean value ) - { - field_1_grpfChp = fVanish.setBoolean(field_1_grpfChp, value); - } - - /** - * text has hidden format, and is not displayed unless fPagHidden is set in the DOP - * @return the fVanish field value. - */ - @Internal - public boolean isFVanish() - { - return fVanish.isSet(field_1_grpfChp); - } - - /** - * Sets the fRMark field value. - * text is newly typed since the last time revision marks have been accepted and will be displayed with an underline when revision marked text is to be displayed - */ - @Internal - public void setFRMark( boolean value ) - { - field_1_grpfChp = fRMark.setBoolean(field_1_grpfChp, value); - } - - /** - * text is newly typed since the last time revision marks have been accepted and will be displayed with an underline when revision marked text is to be displayed - * @return the fRMark field value. - */ - @Internal - public boolean isFRMark() - { - return fRMark.isSet(field_1_grpfChp); - } - - /** - * Sets the fSpec field value. - * Character is a Word special character - */ - @Internal - public void setFSpec( boolean value ) - { - field_1_grpfChp = fSpec.setBoolean(field_1_grpfChp, value); - } - - /** - * Character is a Word special character - * @return the fSpec field value. - */ - @Internal - public boolean isFSpec() - { - return fSpec.isSet(field_1_grpfChp); - } - - /** - * Sets the fStrike field value. - * Displayed with strikethrough - */ - @Internal - public void setFStrike( boolean value ) - { - field_1_grpfChp = fStrike.setBoolean(field_1_grpfChp, value); - } - - /** - * Displayed with strikethrough - * @return the fStrike field value. - */ - @Internal - public boolean isFStrike() - { - return fStrike.isSet(field_1_grpfChp); - } - - /** - * Sets the fObj field value. - * Embedded objec - */ - @Internal - public void setFObj( boolean value ) - { - field_1_grpfChp = fObj.setBoolean(field_1_grpfChp, value); - } - - /** - * Embedded objec - * @return the fObj field value. - */ - @Internal - public boolean isFObj() - { - return fObj.isSet(field_1_grpfChp); - } - - /** - * Sets the fShadow field value. - * Character is drawn with a shadow - */ - @Internal - public void setFShadow( boolean value ) - { - field_1_grpfChp = fShadow.setBoolean(field_1_grpfChp, value); - } - - /** - * Character is drawn with a shadow - * @return the fShadow field value. - */ - @Internal - public boolean isFShadow() - { - return fShadow.isSet(field_1_grpfChp); - } - - /** - * Sets the fLowerCase field value. - * Character is displayed in lower case. This field may be set to 1 only when chp.fSmallCaps is 1. - */ - @Internal - public void setFLowerCase( boolean value ) - { - field_1_grpfChp = fLowerCase.setBoolean(field_1_grpfChp, value); - } - - /** - * Character is displayed in lower case. This field may be set to 1 only when chp.fSmallCaps is 1. - * @return the fLowerCase field value. - */ - @Internal - public boolean isFLowerCase() - { - return fLowerCase.isSet(field_1_grpfChp); - } - - /** - * Sets the fData field value. - * chp.fcPic points to an FFDATA, the data structure binary data used by Word to describe a form field. The bit chp.fData may only be 1 when chp.fSpec is also 1 and the special character in the document stream that has this property is a chPicture (0x01) - */ - @Internal - public void setFData( boolean value ) - { - field_1_grpfChp = fData.setBoolean(field_1_grpfChp, value); - } - - /** - * chp.fcPic points to an FFDATA, the data structure binary data used by Word to describe a form field. The bit chp.fData may only be 1 when chp.fSpec is also 1 and the special character in the document stream that has this property is a chPicture (0x01) - * @return the fData field value. - */ - @Internal - public boolean isFData() - { - return fData.isSet(field_1_grpfChp); - } - - /** - * Sets the fOle2 field value. - * chp.lTagObj specifies a particular object in the object stream that specifies the particular OLE object in the stream that should be displayed when the chPicture fSpec character that is tagged with the fOle2 is encountered. The bit chp.fOle2 may only be 1 when chp.fSpec is also 1 and the special character in the document stream that has this property is a chPicture (0x01). - */ - @Internal - public void setFOle2( boolean value ) - { - field_1_grpfChp = fOle2.setBoolean(field_1_grpfChp, value); - } - - /** - * chp.lTagObj specifies a particular object in the object stream that specifies the particular OLE object in the stream that should be displayed when the chPicture fSpec character that is tagged with the fOle2 is encountered. The bit chp.fOle2 may only be 1 when chp.fSpec is also 1 and the special character in the document stream that has this property is a chPicture (0x01). - * @return the fOle2 field value. - */ - @Internal - public boolean isFOle2() - { - return fOle2.isSet(field_1_grpfChp); - } - - /** - * Sets the fEmboss field value. - * Text is embossed - */ - @Internal - public void setFEmboss( boolean value ) - { - field_1_grpfChp = fEmboss.setBoolean(field_1_grpfChp, value); - } - - /** - * Text is embossed - * @return the fEmboss field value. - */ - @Internal - public boolean isFEmboss() - { - return fEmboss.isSet(field_1_grpfChp); - } - - /** - * Sets the fImprint field value. - * Text is engraved - */ - @Internal - public void setFImprint( boolean value ) - { - field_1_grpfChp = fImprint.setBoolean(field_1_grpfChp, value); - } - - /** - * Text is engraved - * @return the fImprint field value. - */ - @Internal - public boolean isFImprint() - { - return fImprint.isSet(field_1_grpfChp); - } - - /** - * Sets the fDStrike field value. - * Displayed with double strikethrough - */ - @Internal - public void setFDStrike( boolean value ) - { - field_1_grpfChp = fDStrike.setBoolean(field_1_grpfChp, value); - } - - /** - * Displayed with double strikethrough - * @return the fDStrike field value. - */ - @Internal - public boolean isFDStrike() - { - return fDStrike.isSet(field_1_grpfChp); - } - - /** - * Sets the fUsePgsuSettings field value. - * Used internally by Word - */ - @Internal - public void setFUsePgsuSettings( boolean value ) - { - field_1_grpfChp = fUsePgsuSettings.setBoolean(field_1_grpfChp, value); - } - - /** - * Used internally by Word - * @return the fUsePgsuSettings field value. - */ - @Internal - public boolean isFUsePgsuSettings() - { - return fUsePgsuSettings.isSet(field_1_grpfChp); - } - - /** - * Sets the fBoldBi field value. - * Complex Scripts text is bold - */ - @Internal - public void setFBoldBi( boolean value ) - { - field_1_grpfChp = fBoldBi.setBoolean(field_1_grpfChp, value); - } - - /** - * Complex Scripts text is bold - * @return the fBoldBi field value. - */ - @Internal - public boolean isFBoldBi() - { - return fBoldBi.isSet(field_1_grpfChp); - } - - /** - * Sets the fComplexScripts field value. - * Complex Scripts text that requires special processing to display and process - */ - @Internal - public void setFComplexScripts( boolean value ) - { - field_1_grpfChp = fComplexScripts.setBoolean(field_1_grpfChp, value); - } - - /** - * Complex Scripts text that requires special processing to display and process - * @return the fComplexScripts field value. - */ - @Internal - public boolean isFComplexScripts() - { - return fComplexScripts.isSet(field_1_grpfChp); - } - - /** - * Sets the fItalicBi field value. - * Complex Scripts text is italics - */ - @Internal - public void setFItalicBi( boolean value ) - { - field_1_grpfChp = fItalicBi.setBoolean(field_1_grpfChp, value); - } - - /** - * Complex Scripts text is italics - * @return the fItalicBi field value. - */ - @Internal - public boolean isFItalicBi() - { - return fItalicBi.isSet(field_1_grpfChp); - } - - /** - * Sets the fBiDi field value. - * Complex Scripts right-to-left text that requires special processing to display and process (character reordering; contextual shaping; display of combining characters and diacritics; specialized justification rules; cursor positioning) - */ - @Internal - public void setFBiDi( boolean value ) - { - field_1_grpfChp = fBiDi.setBoolean(field_1_grpfChp, value); - } - - /** - * Complex Scripts right-to-left text that requires special processing to display and process (character reordering; contextual shaping; display of combining characters and diacritics; specialized justification rules; cursor positioning) - * @return the fBiDi field value. - */ - @Internal - public boolean isFBiDi() - { - return fBiDi.isSet(field_1_grpfChp); - } - - /** - * Sets the fIcoBi field value. - * Used internally by Word - */ - @Internal - public void setFIcoBi( boolean value ) - { - field_1_grpfChp = fIcoBi.setBoolean(field_1_grpfChp, value); - } - - /** - * Used internally by Word - * @return the fIcoBi field value. - */ - @Internal - public boolean isFIcoBi() - { - return fIcoBi.isSet(field_1_grpfChp); - } - - /** - * Sets the fNonGlyph field value. - * Used internally by Word - */ - @Internal - public void setFNonGlyph( boolean value ) - { - field_1_grpfChp = fNonGlyph.setBoolean(field_1_grpfChp, value); - } - - /** - * Used internally by Word - * @return the fNonGlyph field value. - */ - @Internal - public boolean isFNonGlyph() - { - return fNonGlyph.isSet(field_1_grpfChp); - } - - /** - * Sets the fBoldOther field value. - * Used internally by Word 97 and earlier versions - */ - @Internal - public void setFBoldOther( boolean value ) - { - field_1_grpfChp = fBoldOther.setBoolean(field_1_grpfChp, value); - } - - /** - * Used internally by Word 97 and earlier versions - * @return the fBoldOther field value. - */ - @Internal - public boolean isFBoldOther() - { - return fBoldOther.isSet(field_1_grpfChp); - } - - /** - * Sets the fItalicOther field value. - * Used internally by Word 97 and earlier versions - */ - @Internal - public void setFItalicOther( boolean value ) - { - field_1_grpfChp = fItalicOther.setBoolean(field_1_grpfChp, value); - } - - /** - * Used internally by Word 97 and earlier versions - * @return the fItalicOther field value. - */ - @Internal - public boolean isFItalicOther() - { - return fItalicOther.isSet(field_1_grpfChp); - } - - /** - * Sets the fNoProof field value. - * When set to 1, do not check spelling or grammar - */ - @Internal - public void setFNoProof( boolean value ) - { - field_1_grpfChp = fNoProof.setBoolean(field_1_grpfChp, value); - } - - /** - * When set to 1, do not check spelling or grammar - * @return the fNoProof field value. - */ - @Internal - public boolean isFNoProof() - { - return fNoProof.isSet(field_1_grpfChp); - } - - /** - * Sets the fWebHidden field value. - * Text should be hidden in Web View when set to 1 - */ - @Internal - public void setFWebHidden( boolean value ) - { - field_1_grpfChp = fWebHidden.setBoolean(field_1_grpfChp, value); - } - - /** - * Text should be hidden in Web View when set to 1 - * @return the fWebHidden field value. - */ - @Internal - public boolean isFWebHidden() - { - return fWebHidden.isSet(field_1_grpfChp); - } - - /** - * Sets the fFitText field value. - * Fit text when set to 1 - */ - @Internal - public void setFFitText( boolean value ) - { - field_1_grpfChp = fFitText.setBoolean(field_1_grpfChp, value); - } - - /** - * Fit text when set to 1 - * @return the fFitText field value. - */ - @Internal - public boolean isFFitText() - { - return fFitText.isSet(field_1_grpfChp); - } - - /** - * Sets the fCalc field value. - * Used internally by Word - */ - @Internal - public void setFCalc( boolean value ) - { - field_1_grpfChp = fCalc.setBoolean(field_1_grpfChp, value); - } - - /** - * Used internally by Word - * @return the fCalc field value. - */ - @Internal - public boolean isFCalc() - { - return fCalc.isSet(field_1_grpfChp); - } - - /** - * Sets the fFmtLineProp field value. - * Used internally by Word - */ - @Internal - public void setFFmtLineProp( boolean value ) - { - field_1_grpfChp = fFmtLineProp.setBoolean(field_1_grpfChp, value); - } - - /** - * Used internally by Word - * @return the fFmtLineProp field value. - */ - @Internal - public boolean isFFmtLineProp() - { - return fFmtLineProp.isSet(field_1_grpfChp); - } - - /** - * Sets the itypFELayout field value. - * - */ - @Internal - public void setItypFELayout( short value ) - { - field_29_ufel = (short)itypFELayout.setValue(field_29_ufel, value); - } - - /** - * - * @return the itypFELayout field value. - */ - @Internal - public short getItypFELayout() - { - return ( short )itypFELayout.getValue(field_29_ufel); - } - - /** - * Sets the fTNY field value. - * Tatenakayoko: Horizontal-in-vertical (range of text in a direction perpendicular to the text flow) is used - */ - @Internal - public void setFTNY( boolean value ) - { - field_29_ufel = (short)fTNY.setBoolean(field_29_ufel, value); - } - - /** - * Tatenakayoko: Horizontal-in-vertical (range of text in a direction perpendicular to the text flow) is used - * @return the fTNY field value. - */ - @Internal - public boolean isFTNY() - { - return fTNY.isSet(field_29_ufel); - } - - /** - * Sets the fWarichu field value. - * Two lines in one (text in the group is displayed as two half-height lines within a line) - */ - @Internal - public void setFWarichu( boolean value ) - { - field_29_ufel = (short)fWarichu.setBoolean(field_29_ufel, value); - } - - /** - * Two lines in one (text in the group is displayed as two half-height lines within a line) - * @return the fWarichu field value. - */ - @Internal - public boolean isFWarichu() - { - return fWarichu.isSet(field_29_ufel); - } - - /** - * Sets the fKumimoji field value. - * combine characters - */ - @Internal - public void setFKumimoji( boolean value ) - { - field_29_ufel = (short)fKumimoji.setBoolean(field_29_ufel, value); - } - - /** - * combine characters - * @return the fKumimoji field value. - */ - @Internal - public boolean isFKumimoji() - { - return fKumimoji.isSet(field_29_ufel); - } - - /** - * Sets the fRuby field value. - * Phonetic guide - */ - @Internal - public void setFRuby( boolean value ) - { - field_29_ufel = (short)fRuby.setBoolean(field_29_ufel, value); - } - - /** - * Phonetic guide - * @return the fRuby field value. - */ - @Internal - public boolean isFRuby() - { - return fRuby.isSet(field_29_ufel); - } - - /** - * Sets the fLSFitText field value. - * fit text - */ - @Internal - public void setFLSFitText( boolean value ) - { - field_29_ufel = (short)fLSFitText.setBoolean(field_29_ufel, value); - } - - /** - * fit text - * @return the fLSFitText field value. - */ - @Internal - public boolean isFLSFitText() - { - return fLSFitText.isSet(field_29_ufel); - } - - /** - * Sets the spare field value. - * Unused - */ - @Internal - public void setSpare( byte value ) - { - field_29_ufel = (short)spare.setValue(field_29_ufel, value); - } - - /** - * Unused - * @return the spare field value. - */ - @Internal - public byte getSpare() - { - return ( byte )spare.getValue(field_29_ufel); - } - - /** - * Sets the iWarichuBracket field value. - * Bracket character for two-lines-in-one - */ - @Internal - public void setIWarichuBracket( byte value ) - { - field_30_copt = (byte)iWarichuBracket.setValue(field_30_copt, value); - } - - /** - * Bracket character for two-lines-in-one - * @return the iWarichuBracket field value. - */ - @Internal - public byte getIWarichuBracket() - { - return ( byte )iWarichuBracket.getValue(field_30_copt); - } - - /** - * Sets the fWarichuNoOpenBracket field value. - * Two-lines-in-one uses no open - */ - @Internal - public void setFWarichuNoOpenBracket( boolean value ) - { - field_30_copt = (byte)fWarichuNoOpenBracket.setBoolean(field_30_copt, value); - } - - /** - * Two-lines-in-one uses no open - * @return the fWarichuNoOpenBracket field value. - */ - @Internal - public boolean isFWarichuNoOpenBracket() - { - return fWarichuNoOpenBracket.isSet(field_30_copt); - } - - /** - * Sets the fTNYCompress field value. - * fit text in line - */ - @Internal - public void setFTNYCompress( boolean value ) - { - field_30_copt = (byte)fTNYCompress.setBoolean(field_30_copt, value); - } - - /** - * fit text in line - * @return the fTNYCompress field value. - */ - @Internal - public boolean isFTNYCompress() - { - return fTNYCompress.isSet(field_30_copt); - } - - /** - * Sets the fTNYFetchTxm field value. - * fetch text metrics - */ - @Internal - public void setFTNYFetchTxm( boolean value ) - { - field_30_copt = (byte)fTNYFetchTxm.setBoolean(field_30_copt, value); - } - - /** - * fetch text metrics - * @return the fTNYFetchTxm field value. - */ - @Internal - public boolean isFTNYFetchTxm() - { - return fTNYFetchTxm.isSet(field_30_copt); - } - - /** - * Sets the fCellFitText field value. - * Fit text in cell - */ - @Internal - public void setFCellFitText( boolean value ) - { - field_30_copt = (byte)fCellFitText.setBoolean(field_30_copt, value); - } - - /** - * Fit text in cell - * @return the fCellFitText field value. - */ - @Internal - public boolean isFCellFitText() - { - return fCellFitText.isSet(field_30_copt); - } - - /** - * Sets the unused field value. - * Not used - */ - @Internal - public void setUnused( boolean value ) - { - field_30_copt = (byte)unused.setBoolean(field_30_copt, value); - } - - /** - * Not used - * @return the unused field value. - */ - @Internal - public boolean isUnused() - { - return unused.isSet(field_30_copt); - } - - /** - * Sets the icoHighlight field value. - * Highlight color (see chp.ico) - */ - @Internal - public void setIcoHighlight( byte value ) - { - field_48_Highlight = (short)icoHighlight.setValue(field_48_Highlight, value); - } - - /** - * Highlight color (see chp.ico) - * @return the icoHighlight field value. - */ - @Internal - public byte getIcoHighlight() - { - return ( byte )icoHighlight.getValue(field_48_Highlight); - } - - /** - * Sets the fHighlight field value. - * When 1, characters are highlighted with color specified by chp.icoHighlight - */ - @Internal - public void setFHighlight( boolean value ) - { - field_48_Highlight = (short)fHighlight.setBoolean(field_48_Highlight, value); - } - - /** - * When 1, characters are highlighted with color specified by chp.icoHighlight - * @return the fHighlight field value. - */ - @Internal - public boolean isFHighlight() - { - return fHighlight.isSet(field_48_Highlight); - } - - /** - * Sets the fChsDiff field value. - * Pre-Unicode files, char's char set different from FIB char set - */ - @Internal - public void setFChsDiff( boolean value ) - { - field_49_CharsetFlags = (short)fChsDiff.setBoolean(field_49_CharsetFlags, value); - } - - /** - * Pre-Unicode files, char's char set different from FIB char set - * @return the fChsDiff field value. - */ - @Internal - public boolean isFChsDiff() - { - return fChsDiff.isSet(field_49_CharsetFlags); - } - - /** - * Sets the fMacChs field value. - * fTrue if char's are Macintosh char set - */ - @Internal - public void setFMacChs( boolean value ) - { - field_49_CharsetFlags = (short)fMacChs.setBoolean(field_49_CharsetFlags, value); - } - - /** - * fTrue if char's are Macintosh char set - * @return the fMacChs field value. - */ - @Internal - public boolean isFMacChs() - { - return fMacChs.isSet(field_49_CharsetFlags); - } - -} // END OF CLASS diff --git a/src/scratchpad/src/org/apache/poi/hwpf/model/types/DOPAbstractType.java b/src/scratchpad/src/org/apache/poi/hwpf/model/types/DOPAbstractType.java deleted file mode 100644 index 773f731d4..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/model/types/DOPAbstractType.java +++ /dev/null @@ -1,3314 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.model.types; - - -import java.util.Arrays; - -import org.apache.poi.util.BitField; -import org.apache.poi.util.Internal; -import org.apache.poi.util.LittleEndian; - -/** - * Document Properties. - * NOTE: This source is automatically generated please do not modify this file. Either subclass or - * remove the record in src/records/definitions. - * - * @author S. Ryan Ackley - */ -@Internal -public abstract class DOPAbstractType { - - protected byte field_1_formatFlags; - private static final BitField fFacingPages = new BitField(0x01); - private static final BitField fWidowControl = new BitField(0x02); - private static final BitField fPMHMainDoc = new BitField(0x04); - private static final BitField grfSupression = new BitField(0x18); - private static final BitField fpc = new BitField(0x60); - private static final BitField unused1 = new BitField(0x80); - protected byte field_2_unused2; - protected short field_3_footnoteInfo; - private static final BitField rncFtn = new BitField(0x0003); - private static final BitField nFtn = new BitField(0xfffc); - protected byte field_4_fOutlineDirtySave; - protected byte field_5_docinfo; - private static final BitField fOnlyMacPics = new BitField(0x01); - private static final BitField fOnlyWinPics = new BitField(0x02); - private static final BitField fLabelDoc = new BitField(0x04); - private static final BitField fHyphCapitals = new BitField(0x08); - private static final BitField fAutoHyphen = new BitField(0x10); - private static final BitField fFormNoFields = new BitField(0x20); - private static final BitField fLinkStyles = new BitField(0x40); - private static final BitField fRevMarking = new BitField(0x80); - protected byte field_6_docinfo1; - private static final BitField fBackup = new BitField(0x01); - private static final BitField fExactCWords = new BitField(0x02); - private static final BitField fPagHidden = new BitField(0x04); - private static final BitField fPagResults = new BitField(0x08); - private static final BitField fLockAtn = new BitField(0x10); - private static final BitField fMirrorMargins = new BitField(0x20); - private static final BitField unused3 = new BitField(0x40); - private static final BitField fDfltTrueType = new BitField(0x80); - protected byte field_7_docinfo2; - private static final BitField fPagSupressTopSpacing = new BitField(0x01); - private static final BitField fProtEnabled = new BitField(0x02); - private static final BitField fDispFormFldSel = new BitField(0x04); - private static final BitField fRMView = new BitField(0x08); - private static final BitField fRMPrint = new BitField(0x10); - private static final BitField unused4 = new BitField(0x20); - private static final BitField fLockRev = new BitField(0x40); - private static final BitField fEmbedFonts = new BitField(0x80); - protected short field_8_docinfo3; - private static final BitField oldfNoTabForInd = new BitField(0x0001); - private static final BitField oldfNoSpaceRaiseLower = new BitField(0x0002); - private static final BitField oldfSuppressSpbfAfterPageBreak = new BitField(0x0004); - private static final BitField oldfWrapTrailSpaces = new BitField(0x0008); - private static final BitField oldfMapPrintTextColor = new BitField(0x0010); - private static final BitField oldfNoColumnBalance = new BitField(0x0020); - private static final BitField oldfConvMailMergeEsc = new BitField(0x0040); - private static final BitField oldfSupressTopSpacing = new BitField(0x0080); - private static final BitField oldfOrigWordTableRules = new BitField(0x0100); - private static final BitField oldfTransparentMetafiles = new BitField(0x0200); - private static final BitField oldfShowBreaksInFrames = new BitField(0x0400); - private static final BitField oldfSwapBordersFacingPgs = new BitField(0x0800); - private static final BitField unused5 = new BitField(0xf000); - protected int field_9_dxaTab; - protected int field_10_wSpare; - protected int field_11_dxaHotz; - protected int field_12_cConsexHypLim; - protected int field_13_wSpare2; - protected int field_14_dttmCreated; - protected int field_15_dttmRevised; - protected int field_16_dttmLastPrint; - protected int field_17_nRevision; - protected int field_18_tmEdited; - protected int field_19_cWords; - protected int field_20_cCh; - protected int field_21_cPg; - protected int field_22_cParas; - protected short field_23_Edn; - private static final BitField rncEdn = new BitField(0x0003); - private static final BitField nEdn = new BitField(0xfffc); - protected short field_24_Edn1; - private static final BitField epc = new BitField(0x0003); - private static final BitField nfcFtnRef1 = new BitField(0x003c); - private static final BitField nfcEdnRef1 = new BitField(0x03c0); - private static final BitField fPrintFormData = new BitField(0x0400); - private static final BitField fSaveFormData = new BitField(0x0800); - private static final BitField fShadeFormData = new BitField(0x1000); - private static final BitField fWCFtnEdn = new BitField(0x8000); - protected int field_25_cLines; - protected int field_26_cWordsFtnEnd; - protected int field_27_cChFtnEdn; - protected short field_28_cPgFtnEdn; - protected int field_29_cParasFtnEdn; - protected int field_30_cLinesFtnEdn; - protected int field_31_lKeyProtDoc; - protected short field_32_view; - private static final BitField wvkSaved = new BitField(0x0007); - private static final BitField wScaleSaved = new BitField(0x0ff8); - private static final BitField zkSaved = new BitField(0x3000); - private static final BitField fRotateFontW6 = new BitField(0x4000); - private static final BitField iGutterPos = new BitField(0x8000); - protected int field_33_docinfo4; - private static final BitField fNoTabForInd = new BitField(0x00000001); - private static final BitField fNoSpaceRaiseLower = new BitField(0x00000002); - private static final BitField fSupressSpdfAfterPageBreak = new BitField(0x00000004); - private static final BitField fWrapTrailSpaces = new BitField(0x00000008); - private static final BitField fMapPrintTextColor = new BitField(0x00000010); - private static final BitField fNoColumnBalance = new BitField(0x00000020); - private static final BitField fConvMailMergeEsc = new BitField(0x00000040); - private static final BitField fSupressTopSpacing = new BitField(0x00000080); - private static final BitField fOrigWordTableRules = new BitField(0x00000100); - private static final BitField fTransparentMetafiles = new BitField(0x00000200); - private static final BitField fShowBreaksInFrames = new BitField(0x00000400); - private static final BitField fSwapBordersFacingPgs = new BitField(0x00000800); - private static final BitField fSuppressTopSPacingMac5 = new BitField(0x00010000); - private static final BitField fTruncDxaExpand = new BitField(0x00020000); - private static final BitField fPrintBodyBeforeHdr = new BitField(0x00040000); - private static final BitField fNoLeading = new BitField(0x00080000); - private static final BitField fMWSmallCaps = new BitField(0x00200000); - protected short field_34_adt; - protected byte[] field_35_doptypography; - protected byte[] field_36_dogrid; - protected short field_37_docinfo5; - private static final BitField lvl = new BitField(0x001e); - private static final BitField fGramAllDone = new BitField(0x0020); - private static final BitField fGramAllClean = new BitField(0x0040); - private static final BitField fSubsetFonts = new BitField(0x0080); - private static final BitField fHideLastVersion = new BitField(0x0100); - private static final BitField fHtmlDoc = new BitField(0x0200); - private static final BitField fSnapBorder = new BitField(0x0800); - private static final BitField fIncludeHeader = new BitField(0x1000); - private static final BitField fIncludeFooter = new BitField(0x2000); - private static final BitField fForcePageSizePag = new BitField(0x4000); - private static final BitField fMinFontSizePag = new BitField(0x8000); - protected short field_38_docinfo6; - private static final BitField fHaveVersions = new BitField(0x0001); - private static final BitField fAutoVersions = new BitField(0x0002); - protected byte[] field_39_asumyi; - protected int field_40_cChWS; - protected int field_41_cChWSFtnEdn; - protected int field_42_grfDocEvents; - protected int field_43_virusinfo; - private static final BitField fVirusPrompted = new BitField(0x0001); - private static final BitField fVirusLoadSafe = new BitField(0x0002); - private static final BitField KeyVirusSession30 = new BitField(0xfffffffc); - protected byte[] field_44_Spare; - protected int field_45_reserved1; - protected int field_46_reserved2; - protected int field_47_cDBC; - protected int field_48_cDBCFtnEdn; - protected int field_49_reserved; - protected short field_50_nfcFtnRef; - protected short field_51_nfcEdnRef; - protected short field_52_hpsZoonFontPag; - protected short field_53_dywDispPag; - - protected DOPAbstractType() - { - this.field_35_doptypography = new byte[0]; - this.field_36_dogrid = new byte[0]; - this.field_39_asumyi = new byte[0]; - this.field_44_Spare = new byte[0]; - } - - protected void fillFields( byte[] data, int offset ) - { - field_1_formatFlags = data[ 0x0 + offset ]; - field_2_unused2 = data[ 0x1 + offset ]; - field_3_footnoteInfo = LittleEndian.getShort(data, 0x2 + offset); - field_4_fOutlineDirtySave = data[ 0x4 + offset ]; - field_5_docinfo = data[ 0x5 + offset ]; - field_6_docinfo1 = data[ 0x6 + offset ]; - field_7_docinfo2 = data[ 0x7 + offset ]; - field_8_docinfo3 = LittleEndian.getShort(data, 0x8 + offset); - field_9_dxaTab = LittleEndian.getShort(data, 0xa + offset); - field_10_wSpare = LittleEndian.getShort(data, 0xc + offset); - field_11_dxaHotz = LittleEndian.getShort(data, 0xe + offset); - field_12_cConsexHypLim = LittleEndian.getShort(data, 0x10 + offset); - field_13_wSpare2 = LittleEndian.getShort(data, 0x12 + offset); - field_14_dttmCreated = LittleEndian.getInt(data, 0x14 + offset); - field_15_dttmRevised = LittleEndian.getInt(data, 0x18 + offset); - field_16_dttmLastPrint = LittleEndian.getInt(data, 0x1c + offset); - field_17_nRevision = LittleEndian.getShort(data, 0x20 + offset); - field_18_tmEdited = LittleEndian.getInt(data, 0x22 + offset); - field_19_cWords = LittleEndian.getInt(data, 0x26 + offset); - field_20_cCh = LittleEndian.getInt(data, 0x2a + offset); - field_21_cPg = LittleEndian.getShort(data, 0x2e + offset); - field_22_cParas = LittleEndian.getInt(data, 0x30 + offset); - field_23_Edn = LittleEndian.getShort(data, 0x34 + offset); - field_24_Edn1 = LittleEndian.getShort(data, 0x36 + offset); - field_25_cLines = LittleEndian.getInt(data, 0x38 + offset); - field_26_cWordsFtnEnd = LittleEndian.getInt(data, 0x3c + offset); - field_27_cChFtnEdn = LittleEndian.getInt(data, 0x40 + offset); - field_28_cPgFtnEdn = LittleEndian.getShort(data, 0x44 + offset); - field_29_cParasFtnEdn = LittleEndian.getInt(data, 0x46 + offset); - field_30_cLinesFtnEdn = LittleEndian.getInt(data, 0x4a + offset); - field_31_lKeyProtDoc = LittleEndian.getInt(data, 0x4e + offset); - field_32_view = LittleEndian.getShort(data, 0x52 + offset); - field_33_docinfo4 = LittleEndian.getInt(data, 0x54 + offset); - field_34_adt = LittleEndian.getShort(data, 0x58 + offset); - field_35_doptypography = LittleEndian.getByteArray(data, 0x5a + offset,310); - field_36_dogrid = LittleEndian.getByteArray(data, 0x190 + offset,10); - field_37_docinfo5 = LittleEndian.getShort(data, 0x19a + offset); - field_38_docinfo6 = LittleEndian.getShort(data, 0x19c + offset); - field_39_asumyi = LittleEndian.getByteArray(data, 0x19e + offset,12); - field_40_cChWS = LittleEndian.getInt(data, 0x1aa + offset); - field_41_cChWSFtnEdn = LittleEndian.getInt(data, 0x1ae + offset); - field_42_grfDocEvents = LittleEndian.getInt(data, 0x1b2 + offset); - field_43_virusinfo = LittleEndian.getInt(data, 0x1b6 + offset); - field_44_Spare = LittleEndian.getByteArray(data, 0x1ba + offset,30); - field_45_reserved1 = LittleEndian.getInt(data, 0x1d8 + offset); - field_46_reserved2 = LittleEndian.getInt(data, 0x1dc + offset); - field_47_cDBC = LittleEndian.getInt(data, 0x1e0 + offset); - field_48_cDBCFtnEdn = LittleEndian.getInt(data, 0x1e4 + offset); - field_49_reserved = LittleEndian.getInt(data, 0x1e8 + offset); - field_50_nfcFtnRef = LittleEndian.getShort(data, 0x1ec + offset); - field_51_nfcEdnRef = LittleEndian.getShort(data, 0x1ee + offset); - field_52_hpsZoonFontPag = LittleEndian.getShort(data, 0x1f0 + offset); - field_53_dywDispPag = LittleEndian.getShort(data, 0x1f2 + offset); - } - - public void serialize( byte[] data, int offset ) - { - data[ 0x0 + offset] = field_1_formatFlags; - data[ 0x1 + offset] = field_2_unused2; - LittleEndian.putShort(data, 0x2 + offset, field_3_footnoteInfo); - data[ 0x4 + offset] = field_4_fOutlineDirtySave; - data[ 0x5 + offset] = field_5_docinfo; - data[ 0x6 + offset] = field_6_docinfo1; - data[ 0x7 + offset] = field_7_docinfo2; - LittleEndian.putShort(data, 0x8 + offset, field_8_docinfo3); - LittleEndian.putShort(data, 0xa + offset, (short)field_9_dxaTab); - LittleEndian.putShort(data, 0xc + offset, (short)field_10_wSpare); - LittleEndian.putShort(data, 0xe + offset, (short)field_11_dxaHotz); - LittleEndian.putShort(data, 0x10 + offset, (short)field_12_cConsexHypLim); - LittleEndian.putShort(data, 0x12 + offset, (short)field_13_wSpare2); - LittleEndian.putInt(data, 0x14 + offset, field_14_dttmCreated); - LittleEndian.putInt(data, 0x18 + offset, field_15_dttmRevised); - LittleEndian.putInt(data, 0x1c + offset, field_16_dttmLastPrint); - LittleEndian.putShort(data, 0x20 + offset, (short)field_17_nRevision); - LittleEndian.putInt(data, 0x22 + offset, field_18_tmEdited); - LittleEndian.putInt(data, 0x26 + offset, field_19_cWords); - LittleEndian.putInt(data, 0x2a + offset, field_20_cCh); - LittleEndian.putShort(data, 0x2e + offset, (short)field_21_cPg); - LittleEndian.putInt(data, 0x30 + offset, field_22_cParas); - LittleEndian.putShort(data, 0x34 + offset, field_23_Edn); - LittleEndian.putShort(data, 0x36 + offset, field_24_Edn1); - LittleEndian.putInt(data, 0x38 + offset, field_25_cLines); - LittleEndian.putInt(data, 0x3c + offset, field_26_cWordsFtnEnd); - LittleEndian.putInt(data, 0x40 + offset, field_27_cChFtnEdn); - LittleEndian.putShort(data, 0x44 + offset, field_28_cPgFtnEdn); - LittleEndian.putInt(data, 0x46 + offset, field_29_cParasFtnEdn); - LittleEndian.putInt(data, 0x4a + offset, field_30_cLinesFtnEdn); - LittleEndian.putInt(data, 0x4e + offset, field_31_lKeyProtDoc); - LittleEndian.putShort(data, 0x52 + offset, field_32_view); - LittleEndian.putInt(data, 0x54 + offset, field_33_docinfo4); - LittleEndian.putShort(data, 0x58 + offset, field_34_adt); - System.arraycopy(field_35_doptypography, 0, data, 0x5a + offset, field_35_doptypography.length); - System.arraycopy(field_36_dogrid, 0, data, 0x190 + offset, field_36_dogrid.length); - LittleEndian.putShort(data, 0x19a + offset, field_37_docinfo5); - LittleEndian.putShort(data, 0x19c + offset, field_38_docinfo6); - System.arraycopy(field_39_asumyi, 0, data, 0x19e + offset, field_39_asumyi.length); - LittleEndian.putInt(data, 0x1aa + offset, field_40_cChWS); - LittleEndian.putInt(data, 0x1ae + offset, field_41_cChWSFtnEdn); - LittleEndian.putInt(data, 0x1b2 + offset, field_42_grfDocEvents); - LittleEndian.putInt(data, 0x1b6 + offset, field_43_virusinfo); - System.arraycopy(field_44_Spare, 0, data, 0x1ba + offset, field_44_Spare.length); - LittleEndian.putInt(data, 0x1d8 + offset, field_45_reserved1); - LittleEndian.putInt(data, 0x1dc + offset, field_46_reserved2); - LittleEndian.putInt(data, 0x1e0 + offset, field_47_cDBC); - LittleEndian.putInt(data, 0x1e4 + offset, field_48_cDBCFtnEdn); - LittleEndian.putInt(data, 0x1e8 + offset, field_49_reserved); - LittleEndian.putShort(data, 0x1ec + offset, field_50_nfcFtnRef); - LittleEndian.putShort(data, 0x1ee + offset, field_51_nfcEdnRef); - LittleEndian.putShort(data, 0x1f0 + offset, field_52_hpsZoonFontPag); - LittleEndian.putShort(data, 0x1f2 + offset, field_53_dywDispPag); - } - - /** - * Size of record - */ - public static int getSize() - { - return 0 + 1 + 1 + 2 + 1 + 1 + 1 + 1 + 2 + 2 + 2 + 2 + 2 + 2 + 4 + 4 + 4 + 2 + 4 + 4 + 4 + 2 + 4 + 2 + 2 + 4 + 4 + 4 + 2 + 4 + 4 + 4 + 2 + 4 + 2 + 310 + 10 + 2 + 2 + 12 + 4 + 4 + 4 + 4 + 30 + 4 + 4 + 4 + 4 + 4 + 2 + 2 + 2 + 2; - } - - public String toString() - { - StringBuilder builder = new StringBuilder(); - builder.append("[DOP]\n"); - builder.append(" .formatFlags = "); - builder.append(" (").append(getFormatFlags()).append(" )\n"); - builder.append(" .fFacingPages = ").append(isFFacingPages()).append('\n'); - builder.append(" .fWidowControl = ").append(isFWidowControl()).append('\n'); - builder.append(" .fPMHMainDoc = ").append(isFPMHMainDoc()).append('\n'); - builder.append(" .grfSupression = ").append(getGrfSupression()).append('\n'); - builder.append(" .fpc = ").append(getFpc()).append('\n'); - builder.append(" .unused1 = ").append(isUnused1()).append('\n'); - builder.append(" .unused2 = "); - builder.append(" (").append(getUnused2()).append(" )\n"); - builder.append(" .footnoteInfo = "); - builder.append(" (").append(getFootnoteInfo()).append(" )\n"); - builder.append(" .rncFtn = ").append(getRncFtn()).append('\n'); - builder.append(" .nFtn = ").append(getNFtn()).append('\n'); - builder.append(" .fOutlineDirtySave = "); - builder.append(" (").append(getFOutlineDirtySave()).append(" )\n"); - builder.append(" .docinfo = "); - builder.append(" (").append(getDocinfo()).append(" )\n"); - builder.append(" .fOnlyMacPics = ").append(isFOnlyMacPics()).append('\n'); - builder.append(" .fOnlyWinPics = ").append(isFOnlyWinPics()).append('\n'); - builder.append(" .fLabelDoc = ").append(isFLabelDoc()).append('\n'); - builder.append(" .fHyphCapitals = ").append(isFHyphCapitals()).append('\n'); - builder.append(" .fAutoHyphen = ").append(isFAutoHyphen()).append('\n'); - builder.append(" .fFormNoFields = ").append(isFFormNoFields()).append('\n'); - builder.append(" .fLinkStyles = ").append(isFLinkStyles()).append('\n'); - builder.append(" .fRevMarking = ").append(isFRevMarking()).append('\n'); - builder.append(" .docinfo1 = "); - builder.append(" (").append(getDocinfo1()).append(" )\n"); - builder.append(" .fBackup = ").append(isFBackup()).append('\n'); - builder.append(" .fExactCWords = ").append(isFExactCWords()).append('\n'); - builder.append(" .fPagHidden = ").append(isFPagHidden()).append('\n'); - builder.append(" .fPagResults = ").append(isFPagResults()).append('\n'); - builder.append(" .fLockAtn = ").append(isFLockAtn()).append('\n'); - builder.append(" .fMirrorMargins = ").append(isFMirrorMargins()).append('\n'); - builder.append(" .unused3 = ").append(isUnused3()).append('\n'); - builder.append(" .fDfltTrueType = ").append(isFDfltTrueType()).append('\n'); - builder.append(" .docinfo2 = "); - builder.append(" (").append(getDocinfo2()).append(" )\n"); - builder.append(" .fPagSupressTopSpacing = ").append(isFPagSupressTopSpacing()).append('\n'); - builder.append(" .fProtEnabled = ").append(isFProtEnabled()).append('\n'); - builder.append(" .fDispFormFldSel = ").append(isFDispFormFldSel()).append('\n'); - builder.append(" .fRMView = ").append(isFRMView()).append('\n'); - builder.append(" .fRMPrint = ").append(isFRMPrint()).append('\n'); - builder.append(" .unused4 = ").append(isUnused4()).append('\n'); - builder.append(" .fLockRev = ").append(isFLockRev()).append('\n'); - builder.append(" .fEmbedFonts = ").append(isFEmbedFonts()).append('\n'); - builder.append(" .docinfo3 = "); - builder.append(" (").append(getDocinfo3()).append(" )\n"); - builder.append(" .oldfNoTabForInd = ").append(isOldfNoTabForInd()).append('\n'); - builder.append(" .oldfNoSpaceRaiseLower = ").append(isOldfNoSpaceRaiseLower()).append('\n'); - builder.append(" .oldfSuppressSpbfAfterPageBreak = ").append(isOldfSuppressSpbfAfterPageBreak()).append('\n'); - builder.append(" .oldfWrapTrailSpaces = ").append(isOldfWrapTrailSpaces()).append('\n'); - builder.append(" .oldfMapPrintTextColor = ").append(isOldfMapPrintTextColor()).append('\n'); - builder.append(" .oldfNoColumnBalance = ").append(isOldfNoColumnBalance()).append('\n'); - builder.append(" .oldfConvMailMergeEsc = ").append(isOldfConvMailMergeEsc()).append('\n'); - builder.append(" .oldfSupressTopSpacing = ").append(isOldfSupressTopSpacing()).append('\n'); - builder.append(" .oldfOrigWordTableRules = ").append(isOldfOrigWordTableRules()).append('\n'); - builder.append(" .oldfTransparentMetafiles = ").append(isOldfTransparentMetafiles()).append('\n'); - builder.append(" .oldfShowBreaksInFrames = ").append(isOldfShowBreaksInFrames()).append('\n'); - builder.append(" .oldfSwapBordersFacingPgs = ").append(isOldfSwapBordersFacingPgs()).append('\n'); - builder.append(" .unused5 = ").append(getUnused5()).append('\n'); - builder.append(" .dxaTab = "); - builder.append(" (").append(getDxaTab()).append(" )\n"); - builder.append(" .wSpare = "); - builder.append(" (").append(getWSpare()).append(" )\n"); - builder.append(" .dxaHotz = "); - builder.append(" (").append(getDxaHotz()).append(" )\n"); - builder.append(" .cConsexHypLim = "); - builder.append(" (").append(getCConsexHypLim()).append(" )\n"); - builder.append(" .wSpare2 = "); - builder.append(" (").append(getWSpare2()).append(" )\n"); - builder.append(" .dttmCreated = "); - builder.append(" (").append(getDttmCreated()).append(" )\n"); - builder.append(" .dttmRevised = "); - builder.append(" (").append(getDttmRevised()).append(" )\n"); - builder.append(" .dttmLastPrint = "); - builder.append(" (").append(getDttmLastPrint()).append(" )\n"); - builder.append(" .nRevision = "); - builder.append(" (").append(getNRevision()).append(" )\n"); - builder.append(" .tmEdited = "); - builder.append(" (").append(getTmEdited()).append(" )\n"); - builder.append(" .cWords = "); - builder.append(" (").append(getCWords()).append(" )\n"); - builder.append(" .cCh = "); - builder.append(" (").append(getCCh()).append(" )\n"); - builder.append(" .cPg = "); - builder.append(" (").append(getCPg()).append(" )\n"); - builder.append(" .cParas = "); - builder.append(" (").append(getCParas()).append(" )\n"); - builder.append(" .Edn = "); - builder.append(" (").append(getEdn()).append(" )\n"); - builder.append(" .rncEdn = ").append(getRncEdn()).append('\n'); - builder.append(" .nEdn = ").append(getNEdn()).append('\n'); - builder.append(" .Edn1 = "); - builder.append(" (").append(getEdn1()).append(" )\n"); - builder.append(" .epc = ").append(getEpc()).append('\n'); - builder.append(" .nfcFtnRef1 = ").append(getNfcFtnRef1()).append('\n'); - builder.append(" .nfcEdnRef1 = ").append(getNfcEdnRef1()).append('\n'); - builder.append(" .fPrintFormData = ").append(isFPrintFormData()).append('\n'); - builder.append(" .fSaveFormData = ").append(isFSaveFormData()).append('\n'); - builder.append(" .fShadeFormData = ").append(isFShadeFormData()).append('\n'); - builder.append(" .fWCFtnEdn = ").append(isFWCFtnEdn()).append('\n'); - builder.append(" .cLines = "); - builder.append(" (").append(getCLines()).append(" )\n"); - builder.append(" .cWordsFtnEnd = "); - builder.append(" (").append(getCWordsFtnEnd()).append(" )\n"); - builder.append(" .cChFtnEdn = "); - builder.append(" (").append(getCChFtnEdn()).append(" )\n"); - builder.append(" .cPgFtnEdn = "); - builder.append(" (").append(getCPgFtnEdn()).append(" )\n"); - builder.append(" .cParasFtnEdn = "); - builder.append(" (").append(getCParasFtnEdn()).append(" )\n"); - builder.append(" .cLinesFtnEdn = "); - builder.append(" (").append(getCLinesFtnEdn()).append(" )\n"); - builder.append(" .lKeyProtDoc = "); - builder.append(" (").append(getLKeyProtDoc()).append(" )\n"); - builder.append(" .view = "); - builder.append(" (").append(getView()).append(" )\n"); - builder.append(" .wvkSaved = ").append(getWvkSaved()).append('\n'); - builder.append(" .wScaleSaved = ").append(getWScaleSaved()).append('\n'); - builder.append(" .zkSaved = ").append(getZkSaved()).append('\n'); - builder.append(" .fRotateFontW6 = ").append(isFRotateFontW6()).append('\n'); - builder.append(" .iGutterPos = ").append(isIGutterPos()).append('\n'); - builder.append(" .docinfo4 = "); - builder.append(" (").append(getDocinfo4()).append(" )\n"); - builder.append(" .fNoTabForInd = ").append(isFNoTabForInd()).append('\n'); - builder.append(" .fNoSpaceRaiseLower = ").append(isFNoSpaceRaiseLower()).append('\n'); - builder.append(" .fSupressSpdfAfterPageBreak = ").append(isFSupressSpdfAfterPageBreak()).append('\n'); - builder.append(" .fWrapTrailSpaces = ").append(isFWrapTrailSpaces()).append('\n'); - builder.append(" .fMapPrintTextColor = ").append(isFMapPrintTextColor()).append('\n'); - builder.append(" .fNoColumnBalance = ").append(isFNoColumnBalance()).append('\n'); - builder.append(" .fConvMailMergeEsc = ").append(isFConvMailMergeEsc()).append('\n'); - builder.append(" .fSupressTopSpacing = ").append(isFSupressTopSpacing()).append('\n'); - builder.append(" .fOrigWordTableRules = ").append(isFOrigWordTableRules()).append('\n'); - builder.append(" .fTransparentMetafiles = ").append(isFTransparentMetafiles()).append('\n'); - builder.append(" .fShowBreaksInFrames = ").append(isFShowBreaksInFrames()).append('\n'); - builder.append(" .fSwapBordersFacingPgs = ").append(isFSwapBordersFacingPgs()).append('\n'); - builder.append(" .fSuppressTopSPacingMac5 = ").append(isFSuppressTopSPacingMac5()).append('\n'); - builder.append(" .fTruncDxaExpand = ").append(isFTruncDxaExpand()).append('\n'); - builder.append(" .fPrintBodyBeforeHdr = ").append(isFPrintBodyBeforeHdr()).append('\n'); - builder.append(" .fNoLeading = ").append(isFNoLeading()).append('\n'); - builder.append(" .fMWSmallCaps = ").append(isFMWSmallCaps()).append('\n'); - builder.append(" .adt = "); - builder.append(" (").append(getAdt()).append(" )\n"); - builder.append(" .doptypography = "); - builder.append(" (").append(Arrays.toString(getDoptypography())).append(" )\n"); - builder.append(" .dogrid = "); - builder.append(" (").append(Arrays.toString(getDogrid())).append(" )\n"); - builder.append(" .docinfo5 = "); - builder.append(" (").append(getDocinfo5()).append(" )\n"); - builder.append(" .lvl = ").append(getLvl()).append('\n'); - builder.append(" .fGramAllDone = ").append(isFGramAllDone()).append('\n'); - builder.append(" .fGramAllClean = ").append(isFGramAllClean()).append('\n'); - builder.append(" .fSubsetFonts = ").append(isFSubsetFonts()).append('\n'); - builder.append(" .fHideLastVersion = ").append(isFHideLastVersion()).append('\n'); - builder.append(" .fHtmlDoc = ").append(isFHtmlDoc()).append('\n'); - builder.append(" .fSnapBorder = ").append(isFSnapBorder()).append('\n'); - builder.append(" .fIncludeHeader = ").append(isFIncludeHeader()).append('\n'); - builder.append(" .fIncludeFooter = ").append(isFIncludeFooter()).append('\n'); - builder.append(" .fForcePageSizePag = ").append(isFForcePageSizePag()).append('\n'); - builder.append(" .fMinFontSizePag = ").append(isFMinFontSizePag()).append('\n'); - builder.append(" .docinfo6 = "); - builder.append(" (").append(getDocinfo6()).append(" )\n"); - builder.append(" .fHaveVersions = ").append(isFHaveVersions()).append('\n'); - builder.append(" .fAutoVersions = ").append(isFAutoVersions()).append('\n'); - builder.append(" .asumyi = "); - builder.append(" (").append(Arrays.toString(getAsumyi())).append(" )\n"); - builder.append(" .cChWS = "); - builder.append(" (").append(getCChWS()).append(" )\n"); - builder.append(" .cChWSFtnEdn = "); - builder.append(" (").append(getCChWSFtnEdn()).append(" )\n"); - builder.append(" .grfDocEvents = "); - builder.append(" (").append(getGrfDocEvents()).append(" )\n"); - builder.append(" .virusinfo = "); - builder.append(" (").append(getVirusinfo()).append(" )\n"); - builder.append(" .fVirusPrompted = ").append(isFVirusPrompted()).append('\n'); - builder.append(" .fVirusLoadSafe = ").append(isFVirusLoadSafe()).append('\n'); - builder.append(" .KeyVirusSession30 = ").append(getKeyVirusSession30()).append('\n'); - builder.append(" .Spare = "); - builder.append(" (").append(Arrays.toString(getSpare())).append(" )\n"); - builder.append(" .reserved1 = "); - builder.append(" (").append(getReserved1()).append(" )\n"); - builder.append(" .reserved2 = "); - builder.append(" (").append(getReserved2()).append(" )\n"); - builder.append(" .cDBC = "); - builder.append(" (").append(getCDBC()).append(" )\n"); - builder.append(" .cDBCFtnEdn = "); - builder.append(" (").append(getCDBCFtnEdn()).append(" )\n"); - builder.append(" .reserved = "); - builder.append(" (").append(getReserved()).append(" )\n"); - builder.append(" .nfcFtnRef = "); - builder.append(" (").append(getNfcFtnRef()).append(" )\n"); - builder.append(" .nfcEdnRef = "); - builder.append(" (").append(getNfcEdnRef()).append(" )\n"); - builder.append(" .hpsZoonFontPag = "); - builder.append(" (").append(getHpsZoonFontPag()).append(" )\n"); - builder.append(" .dywDispPag = "); - builder.append(" (").append(getDywDispPag()).append(" )\n"); - - builder.append("[/DOP]\n"); - return builder.toString(); - } - - /** - * Get the formatFlags field for the DOP record. - */ - @Internal - public byte getFormatFlags() - { - return field_1_formatFlags; - } - - /** - * Set the formatFlags field for the DOP record. - */ - @Internal - public void setFormatFlags( byte field_1_formatFlags ) - { - this.field_1_formatFlags = field_1_formatFlags; - } - - /** - * Get the unused2 field for the DOP record. - */ - @Internal - public byte getUnused2() - { - return field_2_unused2; - } - - /** - * Set the unused2 field for the DOP record. - */ - @Internal - public void setUnused2( byte field_2_unused2 ) - { - this.field_2_unused2 = field_2_unused2; - } - - /** - * Get the footnoteInfo field for the DOP record. - */ - @Internal - public short getFootnoteInfo() - { - return field_3_footnoteInfo; - } - - /** - * Set the footnoteInfo field for the DOP record. - */ - @Internal - public void setFootnoteInfo( short field_3_footnoteInfo ) - { - this.field_3_footnoteInfo = field_3_footnoteInfo; - } - - /** - * Get the fOutlineDirtySave field for the DOP record. - */ - @Internal - public byte getFOutlineDirtySave() - { - return field_4_fOutlineDirtySave; - } - - /** - * Set the fOutlineDirtySave field for the DOP record. - */ - @Internal - public void setFOutlineDirtySave( byte field_4_fOutlineDirtySave ) - { - this.field_4_fOutlineDirtySave = field_4_fOutlineDirtySave; - } - - /** - * Get the docinfo field for the DOP record. - */ - @Internal - public byte getDocinfo() - { - return field_5_docinfo; - } - - /** - * Set the docinfo field for the DOP record. - */ - @Internal - public void setDocinfo( byte field_5_docinfo ) - { - this.field_5_docinfo = field_5_docinfo; - } - - /** - * Get the docinfo1 field for the DOP record. - */ - @Internal - public byte getDocinfo1() - { - return field_6_docinfo1; - } - - /** - * Set the docinfo1 field for the DOP record. - */ - @Internal - public void setDocinfo1( byte field_6_docinfo1 ) - { - this.field_6_docinfo1 = field_6_docinfo1; - } - - /** - * Get the docinfo2 field for the DOP record. - */ - @Internal - public byte getDocinfo2() - { - return field_7_docinfo2; - } - - /** - * Set the docinfo2 field for the DOP record. - */ - @Internal - public void setDocinfo2( byte field_7_docinfo2 ) - { - this.field_7_docinfo2 = field_7_docinfo2; - } - - /** - * Get the docinfo3 field for the DOP record. - */ - @Internal - public short getDocinfo3() - { - return field_8_docinfo3; - } - - /** - * Set the docinfo3 field for the DOP record. - */ - @Internal - public void setDocinfo3( short field_8_docinfo3 ) - { - this.field_8_docinfo3 = field_8_docinfo3; - } - - /** - * Get the dxaTab field for the DOP record. - */ - @Internal - public int getDxaTab() - { - return field_9_dxaTab; - } - - /** - * Set the dxaTab field for the DOP record. - */ - @Internal - public void setDxaTab( int field_9_dxaTab ) - { - this.field_9_dxaTab = field_9_dxaTab; - } - - /** - * Get the wSpare field for the DOP record. - */ - @Internal - public int getWSpare() - { - return field_10_wSpare; - } - - /** - * Set the wSpare field for the DOP record. - */ - @Internal - public void setWSpare( int field_10_wSpare ) - { - this.field_10_wSpare = field_10_wSpare; - } - - /** - * Get the dxaHotz field for the DOP record. - */ - @Internal - public int getDxaHotz() - { - return field_11_dxaHotz; - } - - /** - * Set the dxaHotz field for the DOP record. - */ - @Internal - public void setDxaHotz( int field_11_dxaHotz ) - { - this.field_11_dxaHotz = field_11_dxaHotz; - } - - /** - * Get the cConsexHypLim field for the DOP record. - */ - @Internal - public int getCConsexHypLim() - { - return field_12_cConsexHypLim; - } - - /** - * Set the cConsexHypLim field for the DOP record. - */ - @Internal - public void setCConsexHypLim( int field_12_cConsexHypLim ) - { - this.field_12_cConsexHypLim = field_12_cConsexHypLim; - } - - /** - * Get the wSpare2 field for the DOP record. - */ - @Internal - public int getWSpare2() - { - return field_13_wSpare2; - } - - /** - * Set the wSpare2 field for the DOP record. - */ - @Internal - public void setWSpare2( int field_13_wSpare2 ) - { - this.field_13_wSpare2 = field_13_wSpare2; - } - - /** - * Get the dttmCreated field for the DOP record. - */ - @Internal - public int getDttmCreated() - { - return field_14_dttmCreated; - } - - /** - * Set the dttmCreated field for the DOP record. - */ - @Internal - public void setDttmCreated( int field_14_dttmCreated ) - { - this.field_14_dttmCreated = field_14_dttmCreated; - } - - /** - * Get the dttmRevised field for the DOP record. - */ - @Internal - public int getDttmRevised() - { - return field_15_dttmRevised; - } - - /** - * Set the dttmRevised field for the DOP record. - */ - @Internal - public void setDttmRevised( int field_15_dttmRevised ) - { - this.field_15_dttmRevised = field_15_dttmRevised; - } - - /** - * Get the dttmLastPrint field for the DOP record. - */ - @Internal - public int getDttmLastPrint() - { - return field_16_dttmLastPrint; - } - - /** - * Set the dttmLastPrint field for the DOP record. - */ - @Internal - public void setDttmLastPrint( int field_16_dttmLastPrint ) - { - this.field_16_dttmLastPrint = field_16_dttmLastPrint; - } - - /** - * Get the nRevision field for the DOP record. - */ - @Internal - public int getNRevision() - { - return field_17_nRevision; - } - - /** - * Set the nRevision field for the DOP record. - */ - @Internal - public void setNRevision( int field_17_nRevision ) - { - this.field_17_nRevision = field_17_nRevision; - } - - /** - * Get the tmEdited field for the DOP record. - */ - @Internal - public int getTmEdited() - { - return field_18_tmEdited; - } - - /** - * Set the tmEdited field for the DOP record. - */ - @Internal - public void setTmEdited( int field_18_tmEdited ) - { - this.field_18_tmEdited = field_18_tmEdited; - } - - /** - * Get the cWords field for the DOP record. - */ - @Internal - public int getCWords() - { - return field_19_cWords; - } - - /** - * Set the cWords field for the DOP record. - */ - @Internal - public void setCWords( int field_19_cWords ) - { - this.field_19_cWords = field_19_cWords; - } - - /** - * Get the cCh field for the DOP record. - */ - @Internal - public int getCCh() - { - return field_20_cCh; - } - - /** - * Set the cCh field for the DOP record. - */ - @Internal - public void setCCh( int field_20_cCh ) - { - this.field_20_cCh = field_20_cCh; - } - - /** - * Get the cPg field for the DOP record. - */ - @Internal - public int getCPg() - { - return field_21_cPg; - } - - /** - * Set the cPg field for the DOP record. - */ - @Internal - public void setCPg( int field_21_cPg ) - { - this.field_21_cPg = field_21_cPg; - } - - /** - * Get the cParas field for the DOP record. - */ - @Internal - public int getCParas() - { - return field_22_cParas; - } - - /** - * Set the cParas field for the DOP record. - */ - @Internal - public void setCParas( int field_22_cParas ) - { - this.field_22_cParas = field_22_cParas; - } - - /** - * Get the Edn field for the DOP record. - */ - @Internal - public short getEdn() - { - return field_23_Edn; - } - - /** - * Set the Edn field for the DOP record. - */ - @Internal - public void setEdn( short field_23_Edn ) - { - this.field_23_Edn = field_23_Edn; - } - - /** - * Get the Edn1 field for the DOP record. - */ - @Internal - public short getEdn1() - { - return field_24_Edn1; - } - - /** - * Set the Edn1 field for the DOP record. - */ - @Internal - public void setEdn1( short field_24_Edn1 ) - { - this.field_24_Edn1 = field_24_Edn1; - } - - /** - * Get the cLines field for the DOP record. - */ - @Internal - public int getCLines() - { - return field_25_cLines; - } - - /** - * Set the cLines field for the DOP record. - */ - @Internal - public void setCLines( int field_25_cLines ) - { - this.field_25_cLines = field_25_cLines; - } - - /** - * Get the cWordsFtnEnd field for the DOP record. - */ - @Internal - public int getCWordsFtnEnd() - { - return field_26_cWordsFtnEnd; - } - - /** - * Set the cWordsFtnEnd field for the DOP record. - */ - @Internal - public void setCWordsFtnEnd( int field_26_cWordsFtnEnd ) - { - this.field_26_cWordsFtnEnd = field_26_cWordsFtnEnd; - } - - /** - * Get the cChFtnEdn field for the DOP record. - */ - @Internal - public int getCChFtnEdn() - { - return field_27_cChFtnEdn; - } - - /** - * Set the cChFtnEdn field for the DOP record. - */ - @Internal - public void setCChFtnEdn( int field_27_cChFtnEdn ) - { - this.field_27_cChFtnEdn = field_27_cChFtnEdn; - } - - /** - * Get the cPgFtnEdn field for the DOP record. - */ - @Internal - public short getCPgFtnEdn() - { - return field_28_cPgFtnEdn; - } - - /** - * Set the cPgFtnEdn field for the DOP record. - */ - @Internal - public void setCPgFtnEdn( short field_28_cPgFtnEdn ) - { - this.field_28_cPgFtnEdn = field_28_cPgFtnEdn; - } - - /** - * Get the cParasFtnEdn field for the DOP record. - */ - @Internal - public int getCParasFtnEdn() - { - return field_29_cParasFtnEdn; - } - - /** - * Set the cParasFtnEdn field for the DOP record. - */ - @Internal - public void setCParasFtnEdn( int field_29_cParasFtnEdn ) - { - this.field_29_cParasFtnEdn = field_29_cParasFtnEdn; - } - - /** - * Get the cLinesFtnEdn field for the DOP record. - */ - @Internal - public int getCLinesFtnEdn() - { - return field_30_cLinesFtnEdn; - } - - /** - * Set the cLinesFtnEdn field for the DOP record. - */ - @Internal - public void setCLinesFtnEdn( int field_30_cLinesFtnEdn ) - { - this.field_30_cLinesFtnEdn = field_30_cLinesFtnEdn; - } - - /** - * Get the lKeyProtDoc field for the DOP record. - */ - @Internal - public int getLKeyProtDoc() - { - return field_31_lKeyProtDoc; - } - - /** - * Set the lKeyProtDoc field for the DOP record. - */ - @Internal - public void setLKeyProtDoc( int field_31_lKeyProtDoc ) - { - this.field_31_lKeyProtDoc = field_31_lKeyProtDoc; - } - - /** - * Get the view field for the DOP record. - */ - @Internal - public short getView() - { - return field_32_view; - } - - /** - * Set the view field for the DOP record. - */ - @Internal - public void setView( short field_32_view ) - { - this.field_32_view = field_32_view; - } - - /** - * Get the docinfo4 field for the DOP record. - */ - @Internal - public int getDocinfo4() - { - return field_33_docinfo4; - } - - /** - * Set the docinfo4 field for the DOP record. - */ - @Internal - public void setDocinfo4( int field_33_docinfo4 ) - { - this.field_33_docinfo4 = field_33_docinfo4; - } - - /** - * Get the adt field for the DOP record. - */ - @Internal - public short getAdt() - { - return field_34_adt; - } - - /** - * Set the adt field for the DOP record. - */ - @Internal - public void setAdt( short field_34_adt ) - { - this.field_34_adt = field_34_adt; - } - - /** - * Get the doptypography field for the DOP record. - */ - @Internal - public byte[] getDoptypography() - { - return field_35_doptypography; - } - - /** - * Set the doptypography field for the DOP record. - */ - @Internal - public void setDoptypography( byte[] field_35_doptypography ) - { - this.field_35_doptypography = field_35_doptypography; - } - - /** - * Get the dogrid field for the DOP record. - */ - @Internal - public byte[] getDogrid() - { - return field_36_dogrid; - } - - /** - * Set the dogrid field for the DOP record. - */ - @Internal - public void setDogrid( byte[] field_36_dogrid ) - { - this.field_36_dogrid = field_36_dogrid; - } - - /** - * Get the docinfo5 field for the DOP record. - */ - @Internal - public short getDocinfo5() - { - return field_37_docinfo5; - } - - /** - * Set the docinfo5 field for the DOP record. - */ - @Internal - public void setDocinfo5( short field_37_docinfo5 ) - { - this.field_37_docinfo5 = field_37_docinfo5; - } - - /** - * Get the docinfo6 field for the DOP record. - */ - @Internal - public short getDocinfo6() - { - return field_38_docinfo6; - } - - /** - * Set the docinfo6 field for the DOP record. - */ - @Internal - public void setDocinfo6( short field_38_docinfo6 ) - { - this.field_38_docinfo6 = field_38_docinfo6; - } - - /** - * Get the asumyi field for the DOP record. - */ - @Internal - public byte[] getAsumyi() - { - return field_39_asumyi; - } - - /** - * Set the asumyi field for the DOP record. - */ - @Internal - public void setAsumyi( byte[] field_39_asumyi ) - { - this.field_39_asumyi = field_39_asumyi; - } - - /** - * Get the cChWS field for the DOP record. - */ - @Internal - public int getCChWS() - { - return field_40_cChWS; - } - - /** - * Set the cChWS field for the DOP record. - */ - @Internal - public void setCChWS( int field_40_cChWS ) - { - this.field_40_cChWS = field_40_cChWS; - } - - /** - * Get the cChWSFtnEdn field for the DOP record. - */ - @Internal - public int getCChWSFtnEdn() - { - return field_41_cChWSFtnEdn; - } - - /** - * Set the cChWSFtnEdn field for the DOP record. - */ - @Internal - public void setCChWSFtnEdn( int field_41_cChWSFtnEdn ) - { - this.field_41_cChWSFtnEdn = field_41_cChWSFtnEdn; - } - - /** - * Get the grfDocEvents field for the DOP record. - */ - @Internal - public int getGrfDocEvents() - { - return field_42_grfDocEvents; - } - - /** - * Set the grfDocEvents field for the DOP record. - */ - @Internal - public void setGrfDocEvents( int field_42_grfDocEvents ) - { - this.field_42_grfDocEvents = field_42_grfDocEvents; - } - - /** - * Get the virusinfo field for the DOP record. - */ - @Internal - public int getVirusinfo() - { - return field_43_virusinfo; - } - - /** - * Set the virusinfo field for the DOP record. - */ - @Internal - public void setVirusinfo( int field_43_virusinfo ) - { - this.field_43_virusinfo = field_43_virusinfo; - } - - /** - * Get the Spare field for the DOP record. - */ - @Internal - public byte[] getSpare() - { - return field_44_Spare; - } - - /** - * Set the Spare field for the DOP record. - */ - @Internal - public void setSpare( byte[] field_44_Spare ) - { - this.field_44_Spare = field_44_Spare; - } - - /** - * Get the reserved1 field for the DOP record. - */ - @Internal - public int getReserved1() - { - return field_45_reserved1; - } - - /** - * Set the reserved1 field for the DOP record. - */ - @Internal - public void setReserved1( int field_45_reserved1 ) - { - this.field_45_reserved1 = field_45_reserved1; - } - - /** - * Get the reserved2 field for the DOP record. - */ - @Internal - public int getReserved2() - { - return field_46_reserved2; - } - - /** - * Set the reserved2 field for the DOP record. - */ - @Internal - public void setReserved2( int field_46_reserved2 ) - { - this.field_46_reserved2 = field_46_reserved2; - } - - /** - * Get the cDBC field for the DOP record. - */ - @Internal - public int getCDBC() - { - return field_47_cDBC; - } - - /** - * Set the cDBC field for the DOP record. - */ - @Internal - public void setCDBC( int field_47_cDBC ) - { - this.field_47_cDBC = field_47_cDBC; - } - - /** - * Get the cDBCFtnEdn field for the DOP record. - */ - @Internal - public int getCDBCFtnEdn() - { - return field_48_cDBCFtnEdn; - } - - /** - * Set the cDBCFtnEdn field for the DOP record. - */ - @Internal - public void setCDBCFtnEdn( int field_48_cDBCFtnEdn ) - { - this.field_48_cDBCFtnEdn = field_48_cDBCFtnEdn; - } - - /** - * Get the reserved field for the DOP record. - */ - @Internal - public int getReserved() - { - return field_49_reserved; - } - - /** - * Set the reserved field for the DOP record. - */ - @Internal - public void setReserved( int field_49_reserved ) - { - this.field_49_reserved = field_49_reserved; - } - - /** - * Get the nfcFtnRef field for the DOP record. - */ - @Internal - public short getNfcFtnRef() - { - return field_50_nfcFtnRef; - } - - /** - * Set the nfcFtnRef field for the DOP record. - */ - @Internal - public void setNfcFtnRef( short field_50_nfcFtnRef ) - { - this.field_50_nfcFtnRef = field_50_nfcFtnRef; - } - - /** - * Get the nfcEdnRef field for the DOP record. - */ - @Internal - public short getNfcEdnRef() - { - return field_51_nfcEdnRef; - } - - /** - * Set the nfcEdnRef field for the DOP record. - */ - @Internal - public void setNfcEdnRef( short field_51_nfcEdnRef ) - { - this.field_51_nfcEdnRef = field_51_nfcEdnRef; - } - - /** - * Get the hpsZoonFontPag field for the DOP record. - */ - @Internal - public short getHpsZoonFontPag() - { - return field_52_hpsZoonFontPag; - } - - /** - * Set the hpsZoonFontPag field for the DOP record. - */ - @Internal - public void setHpsZoonFontPag( short field_52_hpsZoonFontPag ) - { - this.field_52_hpsZoonFontPag = field_52_hpsZoonFontPag; - } - - /** - * Get the dywDispPag field for the DOP record. - */ - @Internal - public short getDywDispPag() - { - return field_53_dywDispPag; - } - - /** - * Set the dywDispPag field for the DOP record. - */ - @Internal - public void setDywDispPag( short field_53_dywDispPag ) - { - this.field_53_dywDispPag = field_53_dywDispPag; - } - - /** - * Sets the fFacingPages field value. - * - */ - @Internal - public void setFFacingPages( boolean value ) - { - field_1_formatFlags = (byte)fFacingPages.setBoolean(field_1_formatFlags, value); - } - - /** - * - * @return the fFacingPages field value. - */ - @Internal - public boolean isFFacingPages() - { - return fFacingPages.isSet(field_1_formatFlags); - } - - /** - * Sets the fWidowControl field value. - * - */ - @Internal - public void setFWidowControl( boolean value ) - { - field_1_formatFlags = (byte)fWidowControl.setBoolean(field_1_formatFlags, value); - } - - /** - * - * @return the fWidowControl field value. - */ - @Internal - public boolean isFWidowControl() - { - return fWidowControl.isSet(field_1_formatFlags); - } - - /** - * Sets the fPMHMainDoc field value. - * - */ - @Internal - public void setFPMHMainDoc( boolean value ) - { - field_1_formatFlags = (byte)fPMHMainDoc.setBoolean(field_1_formatFlags, value); - } - - /** - * - * @return the fPMHMainDoc field value. - */ - @Internal - public boolean isFPMHMainDoc() - { - return fPMHMainDoc.isSet(field_1_formatFlags); - } - - /** - * Sets the grfSupression field value. - * - */ - @Internal - public void setGrfSupression( byte value ) - { - field_1_formatFlags = (byte)grfSupression.setValue(field_1_formatFlags, value); - } - - /** - * - * @return the grfSupression field value. - */ - @Internal - public byte getGrfSupression() - { - return ( byte )grfSupression.getValue(field_1_formatFlags); - } - - /** - * Sets the fpc field value. - * - */ - @Internal - public void setFpc( byte value ) - { - field_1_formatFlags = (byte)fpc.setValue(field_1_formatFlags, value); - } - - /** - * - * @return the fpc field value. - */ - @Internal - public byte getFpc() - { - return ( byte )fpc.getValue(field_1_formatFlags); - } - - /** - * Sets the unused1 field value. - * - */ - @Internal - public void setUnused1( boolean value ) - { - field_1_formatFlags = (byte)unused1.setBoolean(field_1_formatFlags, value); - } - - /** - * - * @return the unused1 field value. - */ - @Internal - public boolean isUnused1() - { - return unused1.isSet(field_1_formatFlags); - } - - /** - * Sets the rncFtn field value. - * - */ - @Internal - public void setRncFtn( byte value ) - { - field_3_footnoteInfo = (short)rncFtn.setValue(field_3_footnoteInfo, value); - } - - /** - * - * @return the rncFtn field value. - */ - @Internal - public byte getRncFtn() - { - return ( byte )rncFtn.getValue(field_3_footnoteInfo); - } - - /** - * Sets the nFtn field value. - * - */ - @Internal - public void setNFtn( short value ) - { - field_3_footnoteInfo = (short)nFtn.setValue(field_3_footnoteInfo, value); - } - - /** - * - * @return the nFtn field value. - */ - @Internal - public short getNFtn() - { - return ( short )nFtn.getValue(field_3_footnoteInfo); - } - - /** - * Sets the fOnlyMacPics field value. - * - */ - @Internal - public void setFOnlyMacPics( boolean value ) - { - field_5_docinfo = (byte)fOnlyMacPics.setBoolean(field_5_docinfo, value); - } - - /** - * - * @return the fOnlyMacPics field value. - */ - @Internal - public boolean isFOnlyMacPics() - { - return fOnlyMacPics.isSet(field_5_docinfo); - } - - /** - * Sets the fOnlyWinPics field value. - * - */ - @Internal - public void setFOnlyWinPics( boolean value ) - { - field_5_docinfo = (byte)fOnlyWinPics.setBoolean(field_5_docinfo, value); - } - - /** - * - * @return the fOnlyWinPics field value. - */ - @Internal - public boolean isFOnlyWinPics() - { - return fOnlyWinPics.isSet(field_5_docinfo); - } - - /** - * Sets the fLabelDoc field value. - * - */ - @Internal - public void setFLabelDoc( boolean value ) - { - field_5_docinfo = (byte)fLabelDoc.setBoolean(field_5_docinfo, value); - } - - /** - * - * @return the fLabelDoc field value. - */ - @Internal - public boolean isFLabelDoc() - { - return fLabelDoc.isSet(field_5_docinfo); - } - - /** - * Sets the fHyphCapitals field value. - * - */ - @Internal - public void setFHyphCapitals( boolean value ) - { - field_5_docinfo = (byte)fHyphCapitals.setBoolean(field_5_docinfo, value); - } - - /** - * - * @return the fHyphCapitals field value. - */ - @Internal - public boolean isFHyphCapitals() - { - return fHyphCapitals.isSet(field_5_docinfo); - } - - /** - * Sets the fAutoHyphen field value. - * - */ - @Internal - public void setFAutoHyphen( boolean value ) - { - field_5_docinfo = (byte)fAutoHyphen.setBoolean(field_5_docinfo, value); - } - - /** - * - * @return the fAutoHyphen field value. - */ - @Internal - public boolean isFAutoHyphen() - { - return fAutoHyphen.isSet(field_5_docinfo); - } - - /** - * Sets the fFormNoFields field value. - * - */ - @Internal - public void setFFormNoFields( boolean value ) - { - field_5_docinfo = (byte)fFormNoFields.setBoolean(field_5_docinfo, value); - } - - /** - * - * @return the fFormNoFields field value. - */ - @Internal - public boolean isFFormNoFields() - { - return fFormNoFields.isSet(field_5_docinfo); - } - - /** - * Sets the fLinkStyles field value. - * - */ - @Internal - public void setFLinkStyles( boolean value ) - { - field_5_docinfo = (byte)fLinkStyles.setBoolean(field_5_docinfo, value); - } - - /** - * - * @return the fLinkStyles field value. - */ - @Internal - public boolean isFLinkStyles() - { - return fLinkStyles.isSet(field_5_docinfo); - } - - /** - * Sets the fRevMarking field value. - * - */ - @Internal - public void setFRevMarking( boolean value ) - { - field_5_docinfo = (byte)fRevMarking.setBoolean(field_5_docinfo, value); - } - - /** - * - * @return the fRevMarking field value. - */ - @Internal - public boolean isFRevMarking() - { - return fRevMarking.isSet(field_5_docinfo); - } - - /** - * Sets the fBackup field value. - * - */ - @Internal - public void setFBackup( boolean value ) - { - field_6_docinfo1 = (byte)fBackup.setBoolean(field_6_docinfo1, value); - } - - /** - * - * @return the fBackup field value. - */ - @Internal - public boolean isFBackup() - { - return fBackup.isSet(field_6_docinfo1); - } - - /** - * Sets the fExactCWords field value. - * - */ - @Internal - public void setFExactCWords( boolean value ) - { - field_6_docinfo1 = (byte)fExactCWords.setBoolean(field_6_docinfo1, value); - } - - /** - * - * @return the fExactCWords field value. - */ - @Internal - public boolean isFExactCWords() - { - return fExactCWords.isSet(field_6_docinfo1); - } - - /** - * Sets the fPagHidden field value. - * - */ - @Internal - public void setFPagHidden( boolean value ) - { - field_6_docinfo1 = (byte)fPagHidden.setBoolean(field_6_docinfo1, value); - } - - /** - * - * @return the fPagHidden field value. - */ - @Internal - public boolean isFPagHidden() - { - return fPagHidden.isSet(field_6_docinfo1); - } - - /** - * Sets the fPagResults field value. - * - */ - @Internal - public void setFPagResults( boolean value ) - { - field_6_docinfo1 = (byte)fPagResults.setBoolean(field_6_docinfo1, value); - } - - /** - * - * @return the fPagResults field value. - */ - @Internal - public boolean isFPagResults() - { - return fPagResults.isSet(field_6_docinfo1); - } - - /** - * Sets the fLockAtn field value. - * - */ - @Internal - public void setFLockAtn( boolean value ) - { - field_6_docinfo1 = (byte)fLockAtn.setBoolean(field_6_docinfo1, value); - } - - /** - * - * @return the fLockAtn field value. - */ - @Internal - public boolean isFLockAtn() - { - return fLockAtn.isSet(field_6_docinfo1); - } - - /** - * Sets the fMirrorMargins field value. - * - */ - @Internal - public void setFMirrorMargins( boolean value ) - { - field_6_docinfo1 = (byte)fMirrorMargins.setBoolean(field_6_docinfo1, value); - } - - /** - * - * @return the fMirrorMargins field value. - */ - @Internal - public boolean isFMirrorMargins() - { - return fMirrorMargins.isSet(field_6_docinfo1); - } - - /** - * Sets the unused3 field value. - * - */ - @Internal - public void setUnused3( boolean value ) - { - field_6_docinfo1 = (byte)unused3.setBoolean(field_6_docinfo1, value); - } - - /** - * - * @return the unused3 field value. - */ - @Internal - public boolean isUnused3() - { - return unused3.isSet(field_6_docinfo1); - } - - /** - * Sets the fDfltTrueType field value. - * - */ - @Internal - public void setFDfltTrueType( boolean value ) - { - field_6_docinfo1 = (byte)fDfltTrueType.setBoolean(field_6_docinfo1, value); - } - - /** - * - * @return the fDfltTrueType field value. - */ - @Internal - public boolean isFDfltTrueType() - { - return fDfltTrueType.isSet(field_6_docinfo1); - } - - /** - * Sets the fPagSupressTopSpacing field value. - * - */ - @Internal - public void setFPagSupressTopSpacing( boolean value ) - { - field_7_docinfo2 = (byte)fPagSupressTopSpacing.setBoolean(field_7_docinfo2, value); - } - - /** - * - * @return the fPagSupressTopSpacing field value. - */ - @Internal - public boolean isFPagSupressTopSpacing() - { - return fPagSupressTopSpacing.isSet(field_7_docinfo2); - } - - /** - * Sets the fProtEnabled field value. - * - */ - @Internal - public void setFProtEnabled( boolean value ) - { - field_7_docinfo2 = (byte)fProtEnabled.setBoolean(field_7_docinfo2, value); - } - - /** - * - * @return the fProtEnabled field value. - */ - @Internal - public boolean isFProtEnabled() - { - return fProtEnabled.isSet(field_7_docinfo2); - } - - /** - * Sets the fDispFormFldSel field value. - * - */ - @Internal - public void setFDispFormFldSel( boolean value ) - { - field_7_docinfo2 = (byte)fDispFormFldSel.setBoolean(field_7_docinfo2, value); - } - - /** - * - * @return the fDispFormFldSel field value. - */ - @Internal - public boolean isFDispFormFldSel() - { - return fDispFormFldSel.isSet(field_7_docinfo2); - } - - /** - * Sets the fRMView field value. - * - */ - @Internal - public void setFRMView( boolean value ) - { - field_7_docinfo2 = (byte)fRMView.setBoolean(field_7_docinfo2, value); - } - - /** - * - * @return the fRMView field value. - */ - @Internal - public boolean isFRMView() - { - return fRMView.isSet(field_7_docinfo2); - } - - /** - * Sets the fRMPrint field value. - * - */ - @Internal - public void setFRMPrint( boolean value ) - { - field_7_docinfo2 = (byte)fRMPrint.setBoolean(field_7_docinfo2, value); - } - - /** - * - * @return the fRMPrint field value. - */ - @Internal - public boolean isFRMPrint() - { - return fRMPrint.isSet(field_7_docinfo2); - } - - /** - * Sets the unused4 field value. - * - */ - @Internal - public void setUnused4( boolean value ) - { - field_7_docinfo2 = (byte)unused4.setBoolean(field_7_docinfo2, value); - } - - /** - * - * @return the unused4 field value. - */ - @Internal - public boolean isUnused4() - { - return unused4.isSet(field_7_docinfo2); - } - - /** - * Sets the fLockRev field value. - * - */ - @Internal - public void setFLockRev( boolean value ) - { - field_7_docinfo2 = (byte)fLockRev.setBoolean(field_7_docinfo2, value); - } - - /** - * - * @return the fLockRev field value. - */ - @Internal - public boolean isFLockRev() - { - return fLockRev.isSet(field_7_docinfo2); - } - - /** - * Sets the fEmbedFonts field value. - * - */ - @Internal - public void setFEmbedFonts( boolean value ) - { - field_7_docinfo2 = (byte)fEmbedFonts.setBoolean(field_7_docinfo2, value); - } - - /** - * - * @return the fEmbedFonts field value. - */ - @Internal - public boolean isFEmbedFonts() - { - return fEmbedFonts.isSet(field_7_docinfo2); - } - - /** - * Sets the oldfNoTabForInd field value. - * - */ - @Internal - public void setOldfNoTabForInd( boolean value ) - { - field_8_docinfo3 = (short)oldfNoTabForInd.setBoolean(field_8_docinfo3, value); - } - - /** - * - * @return the oldfNoTabForInd field value. - */ - @Internal - public boolean isOldfNoTabForInd() - { - return oldfNoTabForInd.isSet(field_8_docinfo3); - } - - /** - * Sets the oldfNoSpaceRaiseLower field value. - * - */ - @Internal - public void setOldfNoSpaceRaiseLower( boolean value ) - { - field_8_docinfo3 = (short)oldfNoSpaceRaiseLower.setBoolean(field_8_docinfo3, value); - } - - /** - * - * @return the oldfNoSpaceRaiseLower field value. - */ - @Internal - public boolean isOldfNoSpaceRaiseLower() - { - return oldfNoSpaceRaiseLower.isSet(field_8_docinfo3); - } - - /** - * Sets the oldfSuppressSpbfAfterPageBreak field value. - * - */ - @Internal - public void setOldfSuppressSpbfAfterPageBreak( boolean value ) - { - field_8_docinfo3 = (short)oldfSuppressSpbfAfterPageBreak.setBoolean(field_8_docinfo3, value); - } - - /** - * - * @return the oldfSuppressSpbfAfterPageBreak field value. - */ - @Internal - public boolean isOldfSuppressSpbfAfterPageBreak() - { - return oldfSuppressSpbfAfterPageBreak.isSet(field_8_docinfo3); - } - - /** - * Sets the oldfWrapTrailSpaces field value. - * - */ - @Internal - public void setOldfWrapTrailSpaces( boolean value ) - { - field_8_docinfo3 = (short)oldfWrapTrailSpaces.setBoolean(field_8_docinfo3, value); - } - - /** - * - * @return the oldfWrapTrailSpaces field value. - */ - @Internal - public boolean isOldfWrapTrailSpaces() - { - return oldfWrapTrailSpaces.isSet(field_8_docinfo3); - } - - /** - * Sets the oldfMapPrintTextColor field value. - * - */ - @Internal - public void setOldfMapPrintTextColor( boolean value ) - { - field_8_docinfo3 = (short)oldfMapPrintTextColor.setBoolean(field_8_docinfo3, value); - } - - /** - * - * @return the oldfMapPrintTextColor field value. - */ - @Internal - public boolean isOldfMapPrintTextColor() - { - return oldfMapPrintTextColor.isSet(field_8_docinfo3); - } - - /** - * Sets the oldfNoColumnBalance field value. - * - */ - @Internal - public void setOldfNoColumnBalance( boolean value ) - { - field_8_docinfo3 = (short)oldfNoColumnBalance.setBoolean(field_8_docinfo3, value); - } - - /** - * - * @return the oldfNoColumnBalance field value. - */ - @Internal - public boolean isOldfNoColumnBalance() - { - return oldfNoColumnBalance.isSet(field_8_docinfo3); - } - - /** - * Sets the oldfConvMailMergeEsc field value. - * - */ - @Internal - public void setOldfConvMailMergeEsc( boolean value ) - { - field_8_docinfo3 = (short)oldfConvMailMergeEsc.setBoolean(field_8_docinfo3, value); - } - - /** - * - * @return the oldfConvMailMergeEsc field value. - */ - @Internal - public boolean isOldfConvMailMergeEsc() - { - return oldfConvMailMergeEsc.isSet(field_8_docinfo3); - } - - /** - * Sets the oldfSupressTopSpacing field value. - * - */ - @Internal - public void setOldfSupressTopSpacing( boolean value ) - { - field_8_docinfo3 = (short)oldfSupressTopSpacing.setBoolean(field_8_docinfo3, value); - } - - /** - * - * @return the oldfSupressTopSpacing field value. - */ - @Internal - public boolean isOldfSupressTopSpacing() - { - return oldfSupressTopSpacing.isSet(field_8_docinfo3); - } - - /** - * Sets the oldfOrigWordTableRules field value. - * - */ - @Internal - public void setOldfOrigWordTableRules( boolean value ) - { - field_8_docinfo3 = (short)oldfOrigWordTableRules.setBoolean(field_8_docinfo3, value); - } - - /** - * - * @return the oldfOrigWordTableRules field value. - */ - @Internal - public boolean isOldfOrigWordTableRules() - { - return oldfOrigWordTableRules.isSet(field_8_docinfo3); - } - - /** - * Sets the oldfTransparentMetafiles field value. - * - */ - @Internal - public void setOldfTransparentMetafiles( boolean value ) - { - field_8_docinfo3 = (short)oldfTransparentMetafiles.setBoolean(field_8_docinfo3, value); - } - - /** - * - * @return the oldfTransparentMetafiles field value. - */ - @Internal - public boolean isOldfTransparentMetafiles() - { - return oldfTransparentMetafiles.isSet(field_8_docinfo3); - } - - /** - * Sets the oldfShowBreaksInFrames field value. - * - */ - @Internal - public void setOldfShowBreaksInFrames( boolean value ) - { - field_8_docinfo3 = (short)oldfShowBreaksInFrames.setBoolean(field_8_docinfo3, value); - } - - /** - * - * @return the oldfShowBreaksInFrames field value. - */ - @Internal - public boolean isOldfShowBreaksInFrames() - { - return oldfShowBreaksInFrames.isSet(field_8_docinfo3); - } - - /** - * Sets the oldfSwapBordersFacingPgs field value. - * - */ - @Internal - public void setOldfSwapBordersFacingPgs( boolean value ) - { - field_8_docinfo3 = (short)oldfSwapBordersFacingPgs.setBoolean(field_8_docinfo3, value); - } - - /** - * - * @return the oldfSwapBordersFacingPgs field value. - */ - @Internal - public boolean isOldfSwapBordersFacingPgs() - { - return oldfSwapBordersFacingPgs.isSet(field_8_docinfo3); - } - - /** - * Sets the unused5 field value. - * - */ - @Internal - public void setUnused5( byte value ) - { - field_8_docinfo3 = (short)unused5.setValue(field_8_docinfo3, value); - } - - /** - * - * @return the unused5 field value. - */ - @Internal - public byte getUnused5() - { - return ( byte )unused5.getValue(field_8_docinfo3); - } - - /** - * Sets the rncEdn field value. - * - */ - @Internal - public void setRncEdn( byte value ) - { - field_23_Edn = (short)rncEdn.setValue(field_23_Edn, value); - } - - /** - * - * @return the rncEdn field value. - */ - @Internal - public byte getRncEdn() - { - return ( byte )rncEdn.getValue(field_23_Edn); - } - - /** - * Sets the nEdn field value. - * - */ - @Internal - public void setNEdn( short value ) - { - field_23_Edn = (short)nEdn.setValue(field_23_Edn, value); - } - - /** - * - * @return the nEdn field value. - */ - @Internal - public short getNEdn() - { - return ( short )nEdn.getValue(field_23_Edn); - } - - /** - * Sets the epc field value. - * - */ - @Internal - public void setEpc( byte value ) - { - field_24_Edn1 = (short)epc.setValue(field_24_Edn1, value); - } - - /** - * - * @return the epc field value. - */ - @Internal - public byte getEpc() - { - return ( byte )epc.getValue(field_24_Edn1); - } - - /** - * Sets the nfcFtnRef1 field value. - * - */ - @Internal - public void setNfcFtnRef1( byte value ) - { - field_24_Edn1 = (short)nfcFtnRef1.setValue(field_24_Edn1, value); - } - - /** - * - * @return the nfcFtnRef1 field value. - */ - @Internal - public byte getNfcFtnRef1() - { - return ( byte )nfcFtnRef1.getValue(field_24_Edn1); - } - - /** - * Sets the nfcEdnRef1 field value. - * - */ - @Internal - public void setNfcEdnRef1( byte value ) - { - field_24_Edn1 = (short)nfcEdnRef1.setValue(field_24_Edn1, value); - } - - /** - * - * @return the nfcEdnRef1 field value. - */ - @Internal - public byte getNfcEdnRef1() - { - return ( byte )nfcEdnRef1.getValue(field_24_Edn1); - } - - /** - * Sets the fPrintFormData field value. - * - */ - @Internal - public void setFPrintFormData( boolean value ) - { - field_24_Edn1 = (short)fPrintFormData.setBoolean(field_24_Edn1, value); - } - - /** - * - * @return the fPrintFormData field value. - */ - @Internal - public boolean isFPrintFormData() - { - return fPrintFormData.isSet(field_24_Edn1); - } - - /** - * Sets the fSaveFormData field value. - * - */ - @Internal - public void setFSaveFormData( boolean value ) - { - field_24_Edn1 = (short)fSaveFormData.setBoolean(field_24_Edn1, value); - } - - /** - * - * @return the fSaveFormData field value. - */ - @Internal - public boolean isFSaveFormData() - { - return fSaveFormData.isSet(field_24_Edn1); - } - - /** - * Sets the fShadeFormData field value. - * - */ - @Internal - public void setFShadeFormData( boolean value ) - { - field_24_Edn1 = (short)fShadeFormData.setBoolean(field_24_Edn1, value); - } - - /** - * - * @return the fShadeFormData field value. - */ - @Internal - public boolean isFShadeFormData() - { - return fShadeFormData.isSet(field_24_Edn1); - } - - /** - * Sets the fWCFtnEdn field value. - * - */ - @Internal - public void setFWCFtnEdn( boolean value ) - { - field_24_Edn1 = (short)fWCFtnEdn.setBoolean(field_24_Edn1, value); - } - - /** - * - * @return the fWCFtnEdn field value. - */ - @Internal - public boolean isFWCFtnEdn() - { - return fWCFtnEdn.isSet(field_24_Edn1); - } - - /** - * Sets the wvkSaved field value. - * - */ - @Internal - public void setWvkSaved( byte value ) - { - field_32_view = (short)wvkSaved.setValue(field_32_view, value); - } - - /** - * - * @return the wvkSaved field value. - */ - @Internal - public byte getWvkSaved() - { - return ( byte )wvkSaved.getValue(field_32_view); - } - - /** - * Sets the wScaleSaved field value. - * - */ - @Internal - public void setWScaleSaved( short value ) - { - field_32_view = (short)wScaleSaved.setValue(field_32_view, value); - } - - /** - * - * @return the wScaleSaved field value. - */ - @Internal - public short getWScaleSaved() - { - return ( short )wScaleSaved.getValue(field_32_view); - } - - /** - * Sets the zkSaved field value. - * - */ - @Internal - public void setZkSaved( byte value ) - { - field_32_view = (short)zkSaved.setValue(field_32_view, value); - } - - /** - * - * @return the zkSaved field value. - */ - @Internal - public byte getZkSaved() - { - return ( byte )zkSaved.getValue(field_32_view); - } - - /** - * Sets the fRotateFontW6 field value. - * - */ - @Internal - public void setFRotateFontW6( boolean value ) - { - field_32_view = (short)fRotateFontW6.setBoolean(field_32_view, value); - } - - /** - * - * @return the fRotateFontW6 field value. - */ - @Internal - public boolean isFRotateFontW6() - { - return fRotateFontW6.isSet(field_32_view); - } - - /** - * Sets the iGutterPos field value. - * - */ - @Internal - public void setIGutterPos( boolean value ) - { - field_32_view = (short)iGutterPos.setBoolean(field_32_view, value); - } - - /** - * - * @return the iGutterPos field value. - */ - @Internal - public boolean isIGutterPos() - { - return iGutterPos.isSet(field_32_view); - } - - /** - * Sets the fNoTabForInd field value. - * - */ - @Internal - public void setFNoTabForInd( boolean value ) - { - field_33_docinfo4 = fNoTabForInd.setBoolean(field_33_docinfo4, value); - } - - /** - * - * @return the fNoTabForInd field value. - */ - @Internal - public boolean isFNoTabForInd() - { - return fNoTabForInd.isSet(field_33_docinfo4); - } - - /** - * Sets the fNoSpaceRaiseLower field value. - * - */ - @Internal - public void setFNoSpaceRaiseLower( boolean value ) - { - field_33_docinfo4 = fNoSpaceRaiseLower.setBoolean(field_33_docinfo4, value); - } - - /** - * - * @return the fNoSpaceRaiseLower field value. - */ - @Internal - public boolean isFNoSpaceRaiseLower() - { - return fNoSpaceRaiseLower.isSet(field_33_docinfo4); - } - - /** - * Sets the fSupressSpdfAfterPageBreak field value. - * - */ - @Internal - public void setFSupressSpdfAfterPageBreak( boolean value ) - { - field_33_docinfo4 = fSupressSpdfAfterPageBreak.setBoolean(field_33_docinfo4, value); - } - - /** - * - * @return the fSupressSpdfAfterPageBreak field value. - */ - @Internal - public boolean isFSupressSpdfAfterPageBreak() - { - return fSupressSpdfAfterPageBreak.isSet(field_33_docinfo4); - } - - /** - * Sets the fWrapTrailSpaces field value. - * - */ - @Internal - public void setFWrapTrailSpaces( boolean value ) - { - field_33_docinfo4 = fWrapTrailSpaces.setBoolean(field_33_docinfo4, value); - } - - /** - * - * @return the fWrapTrailSpaces field value. - */ - @Internal - public boolean isFWrapTrailSpaces() - { - return fWrapTrailSpaces.isSet(field_33_docinfo4); - } - - /** - * Sets the fMapPrintTextColor field value. - * - */ - @Internal - public void setFMapPrintTextColor( boolean value ) - { - field_33_docinfo4 = fMapPrintTextColor.setBoolean(field_33_docinfo4, value); - } - - /** - * - * @return the fMapPrintTextColor field value. - */ - @Internal - public boolean isFMapPrintTextColor() - { - return fMapPrintTextColor.isSet(field_33_docinfo4); - } - - /** - * Sets the fNoColumnBalance field value. - * - */ - @Internal - public void setFNoColumnBalance( boolean value ) - { - field_33_docinfo4 = fNoColumnBalance.setBoolean(field_33_docinfo4, value); - } - - /** - * - * @return the fNoColumnBalance field value. - */ - @Internal - public boolean isFNoColumnBalance() - { - return fNoColumnBalance.isSet(field_33_docinfo4); - } - - /** - * Sets the fConvMailMergeEsc field value. - * - */ - @Internal - public void setFConvMailMergeEsc( boolean value ) - { - field_33_docinfo4 = fConvMailMergeEsc.setBoolean(field_33_docinfo4, value); - } - - /** - * - * @return the fConvMailMergeEsc field value. - */ - @Internal - public boolean isFConvMailMergeEsc() - { - return fConvMailMergeEsc.isSet(field_33_docinfo4); - } - - /** - * Sets the fSupressTopSpacing field value. - * - */ - @Internal - public void setFSupressTopSpacing( boolean value ) - { - field_33_docinfo4 = fSupressTopSpacing.setBoolean(field_33_docinfo4, value); - } - - /** - * - * @return the fSupressTopSpacing field value. - */ - @Internal - public boolean isFSupressTopSpacing() - { - return fSupressTopSpacing.isSet(field_33_docinfo4); - } - - /** - * Sets the fOrigWordTableRules field value. - * - */ - @Internal - public void setFOrigWordTableRules( boolean value ) - { - field_33_docinfo4 = fOrigWordTableRules.setBoolean(field_33_docinfo4, value); - } - - /** - * - * @return the fOrigWordTableRules field value. - */ - @Internal - public boolean isFOrigWordTableRules() - { - return fOrigWordTableRules.isSet(field_33_docinfo4); - } - - /** - * Sets the fTransparentMetafiles field value. - * - */ - @Internal - public void setFTransparentMetafiles( boolean value ) - { - field_33_docinfo4 = fTransparentMetafiles.setBoolean(field_33_docinfo4, value); - } - - /** - * - * @return the fTransparentMetafiles field value. - */ - @Internal - public boolean isFTransparentMetafiles() - { - return fTransparentMetafiles.isSet(field_33_docinfo4); - } - - /** - * Sets the fShowBreaksInFrames field value. - * - */ - @Internal - public void setFShowBreaksInFrames( boolean value ) - { - field_33_docinfo4 = fShowBreaksInFrames.setBoolean(field_33_docinfo4, value); - } - - /** - * - * @return the fShowBreaksInFrames field value. - */ - @Internal - public boolean isFShowBreaksInFrames() - { - return fShowBreaksInFrames.isSet(field_33_docinfo4); - } - - /** - * Sets the fSwapBordersFacingPgs field value. - * - */ - @Internal - public void setFSwapBordersFacingPgs( boolean value ) - { - field_33_docinfo4 = fSwapBordersFacingPgs.setBoolean(field_33_docinfo4, value); - } - - /** - * - * @return the fSwapBordersFacingPgs field value. - */ - @Internal - public boolean isFSwapBordersFacingPgs() - { - return fSwapBordersFacingPgs.isSet(field_33_docinfo4); - } - - /** - * Sets the fSuppressTopSPacingMac5 field value. - * - */ - @Internal - public void setFSuppressTopSPacingMac5( boolean value ) - { - field_33_docinfo4 = fSuppressTopSPacingMac5.setBoolean(field_33_docinfo4, value); - } - - /** - * - * @return the fSuppressTopSPacingMac5 field value. - */ - @Internal - public boolean isFSuppressTopSPacingMac5() - { - return fSuppressTopSPacingMac5.isSet(field_33_docinfo4); - } - - /** - * Sets the fTruncDxaExpand field value. - * - */ - @Internal - public void setFTruncDxaExpand( boolean value ) - { - field_33_docinfo4 = fTruncDxaExpand.setBoolean(field_33_docinfo4, value); - } - - /** - * - * @return the fTruncDxaExpand field value. - */ - @Internal - public boolean isFTruncDxaExpand() - { - return fTruncDxaExpand.isSet(field_33_docinfo4); - } - - /** - * Sets the fPrintBodyBeforeHdr field value. - * - */ - @Internal - public void setFPrintBodyBeforeHdr( boolean value ) - { - field_33_docinfo4 = fPrintBodyBeforeHdr.setBoolean(field_33_docinfo4, value); - } - - /** - * - * @return the fPrintBodyBeforeHdr field value. - */ - @Internal - public boolean isFPrintBodyBeforeHdr() - { - return fPrintBodyBeforeHdr.isSet(field_33_docinfo4); - } - - /** - * Sets the fNoLeading field value. - * - */ - @Internal - public void setFNoLeading( boolean value ) - { - field_33_docinfo4 = fNoLeading.setBoolean(field_33_docinfo4, value); - } - - /** - * - * @return the fNoLeading field value. - */ - @Internal - public boolean isFNoLeading() - { - return fNoLeading.isSet(field_33_docinfo4); - } - - /** - * Sets the fMWSmallCaps field value. - * - */ - @Internal - public void setFMWSmallCaps( boolean value ) - { - field_33_docinfo4 = fMWSmallCaps.setBoolean(field_33_docinfo4, value); - } - - /** - * - * @return the fMWSmallCaps field value. - */ - @Internal - public boolean isFMWSmallCaps() - { - return fMWSmallCaps.isSet(field_33_docinfo4); - } - - /** - * Sets the lvl field value. - * - */ - @Internal - public void setLvl( byte value ) - { - field_37_docinfo5 = (short)lvl.setValue(field_37_docinfo5, value); - } - - /** - * - * @return the lvl field value. - */ - @Internal - public byte getLvl() - { - return ( byte )lvl.getValue(field_37_docinfo5); - } - - /** - * Sets the fGramAllDone field value. - * - */ - @Internal - public void setFGramAllDone( boolean value ) - { - field_37_docinfo5 = (short)fGramAllDone.setBoolean(field_37_docinfo5, value); - } - - /** - * - * @return the fGramAllDone field value. - */ - @Internal - public boolean isFGramAllDone() - { - return fGramAllDone.isSet(field_37_docinfo5); - } - - /** - * Sets the fGramAllClean field value. - * - */ - @Internal - public void setFGramAllClean( boolean value ) - { - field_37_docinfo5 = (short)fGramAllClean.setBoolean(field_37_docinfo5, value); - } - - /** - * - * @return the fGramAllClean field value. - */ - @Internal - public boolean isFGramAllClean() - { - return fGramAllClean.isSet(field_37_docinfo5); - } - - /** - * Sets the fSubsetFonts field value. - * - */ - @Internal - public void setFSubsetFonts( boolean value ) - { - field_37_docinfo5 = (short)fSubsetFonts.setBoolean(field_37_docinfo5, value); - } - - /** - * - * @return the fSubsetFonts field value. - */ - @Internal - public boolean isFSubsetFonts() - { - return fSubsetFonts.isSet(field_37_docinfo5); - } - - /** - * Sets the fHideLastVersion field value. - * - */ - @Internal - public void setFHideLastVersion( boolean value ) - { - field_37_docinfo5 = (short)fHideLastVersion.setBoolean(field_37_docinfo5, value); - } - - /** - * - * @return the fHideLastVersion field value. - */ - @Internal - public boolean isFHideLastVersion() - { - return fHideLastVersion.isSet(field_37_docinfo5); - } - - /** - * Sets the fHtmlDoc field value. - * - */ - @Internal - public void setFHtmlDoc( boolean value ) - { - field_37_docinfo5 = (short)fHtmlDoc.setBoolean(field_37_docinfo5, value); - } - - /** - * - * @return the fHtmlDoc field value. - */ - @Internal - public boolean isFHtmlDoc() - { - return fHtmlDoc.isSet(field_37_docinfo5); - } - - /** - * Sets the fSnapBorder field value. - * - */ - @Internal - public void setFSnapBorder( boolean value ) - { - field_37_docinfo5 = (short)fSnapBorder.setBoolean(field_37_docinfo5, value); - } - - /** - * - * @return the fSnapBorder field value. - */ - @Internal - public boolean isFSnapBorder() - { - return fSnapBorder.isSet(field_37_docinfo5); - } - - /** - * Sets the fIncludeHeader field value. - * - */ - @Internal - public void setFIncludeHeader( boolean value ) - { - field_37_docinfo5 = (short)fIncludeHeader.setBoolean(field_37_docinfo5, value); - } - - /** - * - * @return the fIncludeHeader field value. - */ - @Internal - public boolean isFIncludeHeader() - { - return fIncludeHeader.isSet(field_37_docinfo5); - } - - /** - * Sets the fIncludeFooter field value. - * - */ - @Internal - public void setFIncludeFooter( boolean value ) - { - field_37_docinfo5 = (short)fIncludeFooter.setBoolean(field_37_docinfo5, value); - } - - /** - * - * @return the fIncludeFooter field value. - */ - @Internal - public boolean isFIncludeFooter() - { - return fIncludeFooter.isSet(field_37_docinfo5); - } - - /** - * Sets the fForcePageSizePag field value. - * - */ - @Internal - public void setFForcePageSizePag( boolean value ) - { - field_37_docinfo5 = (short)fForcePageSizePag.setBoolean(field_37_docinfo5, value); - } - - /** - * - * @return the fForcePageSizePag field value. - */ - @Internal - public boolean isFForcePageSizePag() - { - return fForcePageSizePag.isSet(field_37_docinfo5); - } - - /** - * Sets the fMinFontSizePag field value. - * - */ - @Internal - public void setFMinFontSizePag( boolean value ) - { - field_37_docinfo5 = (short)fMinFontSizePag.setBoolean(field_37_docinfo5, value); - } - - /** - * - * @return the fMinFontSizePag field value. - */ - @Internal - public boolean isFMinFontSizePag() - { - return fMinFontSizePag.isSet(field_37_docinfo5); - } - - /** - * Sets the fHaveVersions field value. - * - */ - @Internal - public void setFHaveVersions( boolean value ) - { - field_38_docinfo6 = (short)fHaveVersions.setBoolean(field_38_docinfo6, value); - } - - /** - * - * @return the fHaveVersions field value. - */ - @Internal - public boolean isFHaveVersions() - { - return fHaveVersions.isSet(field_38_docinfo6); - } - - /** - * Sets the fAutoVersions field value. - * - */ - @Internal - public void setFAutoVersions( boolean value ) - { - field_38_docinfo6 = (short)fAutoVersions.setBoolean(field_38_docinfo6, value); - } - - /** - * - * @return the fAutoVersions field value. - */ - @Internal - public boolean isFAutoVersions() - { - return fAutoVersions.isSet(field_38_docinfo6); - } - - /** - * Sets the fVirusPrompted field value. - * - */ - @Internal - public void setFVirusPrompted( boolean value ) - { - field_43_virusinfo = fVirusPrompted.setBoolean(field_43_virusinfo, value); - } - - /** - * - * @return the fVirusPrompted field value. - */ - @Internal - public boolean isFVirusPrompted() - { - return fVirusPrompted.isSet(field_43_virusinfo); - } - - /** - * Sets the fVirusLoadSafe field value. - * - */ - @Internal - public void setFVirusLoadSafe( boolean value ) - { - field_43_virusinfo = fVirusLoadSafe.setBoolean(field_43_virusinfo, value); - } - - /** - * - * @return the fVirusLoadSafe field value. - */ - @Internal - public boolean isFVirusLoadSafe() - { - return fVirusLoadSafe.isSet(field_43_virusinfo); - } - - /** - * Sets the KeyVirusSession30 field value. - * - */ - @Internal - public void setKeyVirusSession30( int value ) - { - field_43_virusinfo = KeyVirusSession30.setValue(field_43_virusinfo, value); - } - - /** - * - * @return the KeyVirusSession30 field value. - */ - @Internal - public int getKeyVirusSession30() - { - return KeyVirusSession30.getValue(field_43_virusinfo); - } - -} // END OF CLASS diff --git a/src/scratchpad/src/org/apache/poi/hwpf/model/types/FFDataBaseAbstractType.java b/src/scratchpad/src/org/apache/poi/hwpf/model/types/FFDataBaseAbstractType.java deleted file mode 100644 index 20c410614..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/model/types/FFDataBaseAbstractType.java +++ /dev/null @@ -1,428 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.model.types; - - -import org.apache.poi.util.BitField; -import org.apache.poi.util.Internal; -import org.apache.poi.util.LittleEndian; - -/** - * The FFData structure specifies form field data for a text - box, check box, or drop-down list box.

    Class and fields - descriptions are quoted from [MS-DOC] -- v20121003 Word (.doc) Binary - File Format; Copyright (c) 2012 Microsoft Corporation; Release: - October 8, 2012 - - *

    - * NOTE: This source is automatically generated please do not modify this file. Either subclass or - * remove the record in src/types/definitions. - *

    - * This class is internal. It content or properties may change without notice - * due to changes in our knowledge of internal Microsoft Word binary structures. - - * @author Sergey Vladimirov; according to [MS-DOC] -- v20121003 Word - (.doc) Binary File Format; Copyright (c) 2012 Microsoft Corporation; - Release: October 8, 2012 - - */ -@Internal -public abstract class FFDataBaseAbstractType -{ - - protected long field_1_version; - protected short field_2_bits; - /**/private static final BitField iType = new BitField(0x0003); - /** Specifies that the form field is a textbox. */ - /* */public final static byte ITYPE_TEXT = 0; - /** Specifies that the form field is a checkbox. */ - /* */public final static byte ITYPE_CHCK = 1; - /** Specifies that the form field is a dropdown list box. */ - /* */public final static byte ITYPE_DROP = 2; - /**/private static final BitField iRes = new BitField(0x007C); - /**/private static final BitField fOwnHelp = new BitField(0x0080); - /**/private static final BitField fOwnStat = new BitField(0x0100); - /**/private static final BitField fProt = new BitField(0x0200); - /**/private static final BitField iSize = new BitField(0x0400); - /**/private static final BitField iTypeTxt = new BitField(0x3800); - /** Specifies that the textbox value is regular text. */ - /* */public final static byte ITYPETXT_REG = 0; - /** Specifies that the textbox value is a number. */ - /* */public final static byte ITYPETXT_NUM = 0; - /** Specifies that the textbox value is a date or time. */ - /* */public final static byte ITYPETXT_DATE = 0; - /** Specifies that the textbox value is the current date. */ - /* */public final static byte ITYPETXT_CURDATE = 0; - /** Specifies that the textbox value is the current time. */ - /* */public final static byte ITYPETXT_CURTIME = 0; - /** Specifies that the textbox value is calculated from an expression. The expression is given by FFData.xstzTextDef. */ - /* */protected final static byte ITYPETXT_CALC = 0; - /**/private static final BitField fRecalc = new BitField(0x4000); - /**/private static final BitField fHasListBox = new BitField(0x8000); - protected int field_3_cch; - protected int field_4_hps; - - protected FFDataBaseAbstractType() - { - } - - protected void fillFields( byte[] data, int offset ) - { - field_1_version = LittleEndian.getUInt( data, 0x0 + offset ); - field_2_bits = LittleEndian.getShort( data, 0x4 + offset ); - field_3_cch = LittleEndian.getShort( data, 0x6 + offset ); - field_4_hps = LittleEndian.getShort( data, 0x8 + offset ); - } - - public void serialize( byte[] data, int offset ) - { - LittleEndian.putUInt( data, 0x0 + offset, field_1_version ); - LittleEndian.putShort( data, 0x4 + offset, field_2_bits ); - LittleEndian.putUShort( data, 0x6 + offset, field_3_cch ); - LittleEndian.putUShort( data, 0x8 + offset, field_4_hps ); - } - - public byte[] serialize() - { - final byte[] result = new byte[ getSize() ]; - serialize( result, 0 ); - return result; - } - - /** - * Size of record - */ - public static int getSize() - { - return 0 + 4 + 2 + 2 + 2; - } - - @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - return true; - if ( obj == null ) - return false; - if ( getClass() != obj.getClass() ) - return false; - FFDataBaseAbstractType other = (FFDataBaseAbstractType) obj; - if ( field_1_version != other.field_1_version ) - return false; - if ( field_2_bits != other.field_2_bits ) - return false; - if ( field_3_cch != other.field_3_cch ) - return false; - if ( field_4_hps != other.field_4_hps ) - return false; - return true; - } - - @Override - public int hashCode() - { - final int prime = 31; - int result = 1; - result = prime * result - + (int) ( field_1_version ^ ( field_1_version >>> 32 ) ); - result = prime * result + field_2_bits; - result = prime * result + field_3_cch; - result = prime * result + field_4_hps; - return result; - } - - public String toString() - { - StringBuilder builder = new StringBuilder(); - - builder.append("[FFDataBase]\n"); - builder.append( " .version = " ); - builder.append(" ( ").append( field_1_version ).append( " )\n" ); - builder.append( " .bits = " ); - builder.append(" ( ").append( field_2_bits ).append( " )\n" ); - builder.append(" .iType = ").append(getIType()).append('\n'); - builder.append(" .iRes = ").append(getIRes()).append('\n'); - builder.append(" .fOwnHelp = ").append(isFOwnHelp()).append('\n'); - builder.append(" .fOwnStat = ").append(isFOwnStat()).append('\n'); - builder.append(" .fProt = ").append(isFProt()).append('\n'); - builder.append(" .iSize = ").append(isISize()).append('\n'); - builder.append(" .iTypeTxt = ").append(getITypeTxt()).append('\n'); - builder.append(" .fRecalc = ").append(isFRecalc()).append('\n'); - builder.append(" .fHasListBox = ").append(isFHasListBox()).append('\n'); - builder.append( " .cch = " ); - builder.append(" ( ").append( field_3_cch ).append( " )\n" ); - builder.append( " .hps = " ); - builder.append(" ( ").append( field_4_hps ).append( " )\n" ); - - builder.append("[/FFDataBase]"); - return builder.toString(); - } - - /** - * An unsigned integer that MUST be 0xFFFFFFFF. - */ - @Internal - public long getVersion() - { - return field_1_version; - } - - /** - * An unsigned integer that MUST be 0xFFFFFFFF. - */ - @Internal - public void setVersion( long field_1_version ) - { - this.field_1_version = field_1_version; - } - - /** - * An FFDataBits that specifies the type and state of this form field. - */ - @Internal - public short getBits() - { - return field_2_bits; - } - - /** - * An FFDataBits that specifies the type and state of this form field. - */ - @Internal - public void setBits( short field_2_bits ) - { - this.field_2_bits = field_2_bits; - } - - /** - * An unsigned integer that specifies the maximum length, in characters, of the value of the textbox. This value MUST NOT exceed 32767. A value of 0 means there is no maximum length of the value of the textbox. If bits.iType is not iTypeText (0), this value MUST be 0.. - */ - @Internal - public int getCch() - { - return field_3_cch; - } - - /** - * An unsigned integer that specifies the maximum length, in characters, of the value of the textbox. This value MUST NOT exceed 32767. A value of 0 means there is no maximum length of the value of the textbox. If bits.iType is not iTypeText (0), this value MUST be 0.. - */ - @Internal - public void setCch( int field_3_cch ) - { - this.field_3_cch = field_3_cch; - } - - /** - * An unsigned integer. If bits.iType is iTypeChck (1), hps specifies the size, in half-points, of the checkbox and MUST be between 2 and 3168, inclusive. If bits.iType is not iTypeChck (1), hps is undefined and MUST be ignored.. - */ - @Internal - public int getHps() - { - return field_4_hps; - } - - /** - * An unsigned integer. If bits.iType is iTypeChck (1), hps specifies the size, in half-points, of the checkbox and MUST be between 2 and 3168, inclusive. If bits.iType is not iTypeChck (1), hps is undefined and MUST be ignored.. - */ - @Internal - public void setHps( int field_4_hps ) - { - this.field_4_hps = field_4_hps; - } - - /** - * Sets the iType field value. - * An unsigned integer that specifies the type of the form field. - */ - @Internal - public void setIType( byte value ) - { - field_2_bits = (short)iType.setValue(field_2_bits, value); - } - - /** - * An unsigned integer that specifies the type of the form field. - * @return the iType field value. - */ - @Internal - public byte getIType() - { - return ( byte )iType.getValue(field_2_bits); - } - - /** - * Sets the iRes field value. - * An unsigned integer. If iType is iTypeText (0), then iRes MUST be 0. If iType is iTypeChck (1), iRes specifies the state of the checkbox and MUST be 0 (unchecked), 1 (checked), or 25 (undefined). Undefined checkboxes are treated as unchecked. If iType is iTypeDrop (2), iRes specifies the current selected list box item. A value of 25 specifies the selection is undefined. Otherwise, iRes is a zero-based index into FFData.hsttbDropList. - */ - @Internal - public void setIRes( byte value ) - { - field_2_bits = (short)iRes.setValue(field_2_bits, value); - } - - /** - * An unsigned integer. If iType is iTypeText (0), then iRes MUST be 0. If iType is iTypeChck (1), iRes specifies the state of the checkbox and MUST be 0 (unchecked), 1 (checked), or 25 (undefined). Undefined checkboxes are treated as unchecked. If iType is iTypeDrop (2), iRes specifies the current selected list box item. A value of 25 specifies the selection is undefined. Otherwise, iRes is a zero-based index into FFData.hsttbDropList. - * @return the iRes field value. - */ - @Internal - public byte getIRes() - { - return ( byte )iRes.getValue(field_2_bits); - } - - /** - * Sets the fOwnHelp field value. - * A bit that specifies whether the form field has custom help text in FFData.xstzHelpText. If fOwnHelp is 0, FFData.xstzHelpText contains an empty or auto-generated string. - */ - @Internal - public void setFOwnHelp( boolean value ) - { - field_2_bits = (short)fOwnHelp.setBoolean(field_2_bits, value); - } - - /** - * A bit that specifies whether the form field has custom help text in FFData.xstzHelpText. If fOwnHelp is 0, FFData.xstzHelpText contains an empty or auto-generated string. - * @return the fOwnHelp field value. - */ - @Internal - public boolean isFOwnHelp() - { - return fOwnHelp.isSet(field_2_bits); - } - - /** - * Sets the fOwnStat field value. - * A bit that specifies whether the form field has custom status bar text in FFData.xstzStatText. If fOwnStat is 0, FFData.xstzStatText contains an empty or auto-generated string. - */ - @Internal - public void setFOwnStat( boolean value ) - { - field_2_bits = (short)fOwnStat.setBoolean(field_2_bits, value); - } - - /** - * A bit that specifies whether the form field has custom status bar text in FFData.xstzStatText. If fOwnStat is 0, FFData.xstzStatText contains an empty or auto-generated string. - * @return the fOwnStat field value. - */ - @Internal - public boolean isFOwnStat() - { - return fOwnStat.isSet(field_2_bits); - } - - /** - * Sets the fProt field value. - * A bit that specifies whether the form field is protected and its value cannot be changed. - */ - @Internal - public void setFProt( boolean value ) - { - field_2_bits = (short)fProt.setBoolean(field_2_bits, value); - } - - /** - * A bit that specifies whether the form field is protected and its value cannot be changed. - * @return the fProt field value. - */ - @Internal - public boolean isFProt() - { - return fProt.isSet(field_2_bits); - } - - /** - * Sets the iSize field value. - * A bit that specifies whether the size of a checkbox is automatically determined by the text size where the checkbox is located. This value MUST be 0 if iType is not iTypeChck (1). - */ - @Internal - public void setISize( boolean value ) - { - field_2_bits = (short)iSize.setBoolean(field_2_bits, value); - } - - /** - * A bit that specifies whether the size of a checkbox is automatically determined by the text size where the checkbox is located. This value MUST be 0 if iType is not iTypeChck (1). - * @return the iSize field value. - */ - @Internal - public boolean isISize() - { - return iSize.isSet(field_2_bits); - } - - /** - * Sets the iTypeTxt field value. - * An unsigned integer that specifies the type of the textbox. If iType is not iTypeText (0), iTypeTxt MUST be 0 and MUST be ignored. - */ - @Internal - public void setITypeTxt( byte value ) - { - field_2_bits = (short)iTypeTxt.setValue(field_2_bits, value); - } - - /** - * An unsigned integer that specifies the type of the textbox. If iType is not iTypeText (0), iTypeTxt MUST be 0 and MUST be ignored. - * @return the iTypeTxt field value. - */ - @Internal - public byte getITypeTxt() - { - return ( byte )iTypeTxt.getValue(field_2_bits); - } - - /** - * Sets the fRecalc field value. - * A bit that specifies whether the value of the field is automatically calculated after the field is modified. - */ - @Internal - public void setFRecalc( boolean value ) - { - field_2_bits = (short)fRecalc.setBoolean(field_2_bits, value); - } - - /** - * A bit that specifies whether the value of the field is automatically calculated after the field is modified. - * @return the fRecalc field value. - */ - @Internal - public boolean isFRecalc() - { - return fRecalc.isSet(field_2_bits); - } - - /** - * Sets the fHasListBox field value. - * A bit that specifies that the form field has a list box. This value MUST be 1 if iType is iTypeDrop (2). Otherwise, this value MUST be 0. - */ - @Internal - public void setFHasListBox( boolean value ) - { - field_2_bits = (short)fHasListBox.setBoolean(field_2_bits, value); - } - - /** - * A bit that specifies that the form field has a list box. This value MUST be 1 if iType is iTypeDrop (2). Otherwise, this value MUST be 0. - * @return the fHasListBox field value. - */ - @Internal - public boolean isFHasListBox() - { - return fHasListBox.isSet(field_2_bits); - } - -} // END OF CLASS diff --git a/src/scratchpad/src/org/apache/poi/hwpf/model/types/FLDAbstractType.java b/src/scratchpad/src/org/apache/poi/hwpf/model/types/FLDAbstractType.java deleted file mode 100644 index 04adf1a42..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/model/types/FLDAbstractType.java +++ /dev/null @@ -1,352 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.model.types; - -import org.apache.poi.util.BitField; -import org.apache.poi.util.Internal; - -/** - * Field Descriptor (FLD). - *

    - * Class and fields descriptions are quoted from Microsoft Office Word 97-2007 - * Binary File Format - * - * NOTE: This source is automatically generated please do not modify this file. - * Either subclass or remove the record in src/records/definitions. - * - * @author Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary - * File Format Specification [*.doc] - */ -@Internal -public abstract class FLDAbstractType -{ - - protected byte field_1_chHolder; - private static final BitField ch = new BitField( 0x1f ); - private static final BitField reserved = new BitField( 0xe0 ); - protected byte field_2_flt; - private static final BitField fDiffer = new BitField( 0x01 ); - private static final BitField fZombieEmbed = new BitField( 0x02 ); - private static final BitField fResultDirty = new BitField( 0x04 ); - private static final BitField fResultEdited = new BitField( 0x08 ); - private static final BitField fLocked = new BitField( 0x10 ); - private static final BitField fPrivateResult = new BitField( 0x20 ); - private static final BitField fNested = new BitField( 0x40 ); - private static final BitField fHasSep = new BitField( 0x40 ); - - public FLDAbstractType() - { - - } - - protected void fillFields( byte[] data, int offset ) - { - field_1_chHolder = data[0x0 + offset]; - field_2_flt = data[0x1 + offset]; - } - - public void serialize( byte[] data, int offset ) - { - data[0x0 + offset] = field_1_chHolder; - data[0x1 + offset] = field_2_flt; - } - - public String toString() - { - StringBuffer buffer = new StringBuffer(); - - buffer.append( "[FLD]\n" ); - - buffer.append( " .chHolder = " ); - buffer.append( " (" ).append( getChHolder() ).append( " )\n" ); - buffer.append( " .ch = " ) - .append( getCh() ).append( '\n' ); - buffer.append( " .reserved = " ) - .append( getReserved() ).append( '\n' ); - - buffer.append( " .flt = " ); - buffer.append( " (" ).append( getFlt() ).append( " )\n" ); - buffer.append( " .fDiffer = " ) - .append( isFDiffer() ).append( '\n' ); - buffer.append( " .fZombieEmbed = " ) - .append( isFZombieEmbed() ).append( '\n' ); - buffer.append( " .fResultDirty = " ) - .append( isFResultDirty() ).append( '\n' ); - buffer.append( " .fResultEdited = " ) - .append( isFResultEdited() ).append( '\n' ); - buffer.append( " .fLocked = " ) - .append( isFLocked() ).append( '\n' ); - buffer.append( " .fPrivateResult = " ) - .append( isFPrivateResult() ).append( '\n' ); - buffer.append( " .fNested = " ) - .append( isFNested() ).append( '\n' ); - buffer.append( " .fHasSep = " ) - .append( isFHasSep() ).append( '\n' ); - - buffer.append( "[/FLD]\n" ); - return buffer.toString(); - } - - /** - * Size of record (exluding 4 byte header) - */ - public static int getSize() - { - return 4 + +1 + 1; - } - - /** - * ch field holder (along with reserved bits). - */ - public byte getChHolder() - { - return field_1_chHolder; - } - - /** - * ch field holder (along with reserved bits). - */ - public void setChHolder( byte field_1_chHolder ) - { - this.field_1_chHolder = field_1_chHolder; - } - - /** - * Field type when ch == 19 OR field flags when ch == 21 . - */ - public byte getFlt() - { - return field_2_flt; - } - - /** - * Field type when ch == 19 OR field flags when ch == 21 . - */ - public void setFlt( byte field_2_flt ) - { - this.field_2_flt = field_2_flt; - } - - /** - * Sets the ch field value. Type of field boundary the FLD describes: 19 -- - * field begin mark, 20 -- field separation mark; 21 -- field end mark - */ - public void setCh( byte value ) - { - field_1_chHolder = (byte) ch.setValue( field_1_chHolder, value ); - - } - - /** - * Type of field boundary the FLD describes: 19 -- field begin mark, 20 -- - * field separation mark; 21 -- field end mark - * - * @return the ch field value. - */ - public byte getCh() - { - return (byte) ch.getValue( field_1_chHolder ); - - } - - /** - * Sets the reserved field value. Reserved - */ - public void setReserved( byte value ) - { - field_1_chHolder = (byte) reserved.setValue( field_1_chHolder, value ); - - } - - /** - * Reserved - * - * @return the reserved field value. - */ - public byte getReserved() - { - return (byte) reserved.getValue( field_1_chHolder ); - - } - - /** - * Sets the fDiffer field value. Ignored for saved file - */ - public void setFDiffer( boolean value ) - { - field_2_flt = (byte) fDiffer.setBoolean( field_2_flt, value ); - - } - - /** - * Ignored for saved file - * - * @return the fDiffer field value. - */ - public boolean isFDiffer() - { - return fDiffer.isSet( field_2_flt ); - - } - - /** - * Sets the fZombieEmbed field value. ==1 when result still believes this - * field is an EMBED or LINK field - */ - public void setFZombieEmbed( boolean value ) - { - field_2_flt = (byte) fZombieEmbed.setBoolean( field_2_flt, value ); - - } - - /** - * ==1 when result still believes this field is an EMBED or LINK field - * - * @return the fZombieEmbed field value. - */ - public boolean isFZombieEmbed() - { - return fZombieEmbed.isSet( field_2_flt ); - - } - - /** - * Sets the fResultDirty field value. ==1 when user has edited or formatted - * the result. == 0 otherwise - */ - public void setFResultDirty( boolean value ) - { - field_2_flt = (byte) fResultDirty.setBoolean( field_2_flt, value ); - - } - - /** - * ==1 when user has edited or formatted the result. == 0 otherwise - * - * @return the fResultDirty field value. - */ - public boolean isFResultDirty() - { - return fResultDirty.isSet( field_2_flt ); - - } - - /** - * Sets the fResultEdited field value. ==1 when user has inserted text into - * or deleted text from the result - */ - public void setFResultEdited( boolean value ) - { - field_2_flt = (byte) fResultEdited.setBoolean( field_2_flt, value ); - - } - - /** - * ==1 when user has inserted text into or deleted text from the result - * - * @return the fResultEdited field value. - */ - public boolean isFResultEdited() - { - return fResultEdited.isSet( field_2_flt ); - - } - - /** - * Sets the fLocked field value. ==1 when field is locked from recalculation - */ - public void setFLocked( boolean value ) - { - field_2_flt = (byte) fLocked.setBoolean( field_2_flt, value ); - - } - - /** - * ==1 when field is locked from recalculation - * - * @return the fLocked field value. - */ - public boolean isFLocked() - { - return fLocked.isSet( field_2_flt ); - - } - - /** - * Sets the fPrivateResult field value. ==1 whenever the result of the field - * is never to be shown - */ - public void setFPrivateResult( boolean value ) - { - field_2_flt = (byte) fPrivateResult.setBoolean( field_2_flt, value ); - - } - - /** - * ==1 whenever the result of the field is never to be shown - * - * @return the fPrivateResult field value. - */ - public boolean isFPrivateResult() - { - return fPrivateResult.isSet( field_2_flt ); - - } - - /** - * Sets the fNested field value. ==1 when field is nested within another - * field - */ - public void setFNested( boolean value ) - { - field_2_flt = (byte) fNested.setBoolean( field_2_flt, value ); - - } - - /** - * ==1 when field is nested within another field - * - * @return the fNested field value. - */ - public boolean isFNested() - { - return fNested.isSet( field_2_flt ); - - } - - /** - * Sets the fHasSep field value. ==1 when field has a field separator - */ - public void setFHasSep( boolean value ) - { - field_2_flt = (byte) fHasSep.setBoolean( field_2_flt, value ); - - } - - /** - * ==1 when field has a field separator - * - * @return the fHasSep field value. - */ - public boolean isFHasSep() - { - return fHasSep.isSet( field_2_flt ); - - } -} // END OF CLASS - diff --git a/src/scratchpad/src/org/apache/poi/hwpf/model/types/FRDAbstractType.java b/src/scratchpad/src/org/apache/poi/hwpf/model/types/FRDAbstractType.java deleted file mode 100644 index 8ebaab766..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/model/types/FRDAbstractType.java +++ /dev/null @@ -1,91 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hwpf.model.types; - -import org.apache.poi.util.Internal; -import org.apache.poi.util.LittleEndian; - -/** - * Footnote Reference Descriptor (FRD). - *

    - * Class and fields descriptions are quoted from Microsoft Office Word 97-2007 - * Binary File Format (.doc) Specification - * - * NOTE: This source is automatically generated please do not modify this file. - * Either subclass or remove the record in src/types/definitions. - * - * @author Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary - * File Format (.doc) Specification - */ -@Internal -public abstract class FRDAbstractType -{ - - protected short field_1_nAuto; - - protected FRDAbstractType() - { - } - - protected void fillFields( byte[] data, int offset ) - { - field_1_nAuto = LittleEndian.getShort( data, 0x0 + offset ); - } - - public void serialize( byte[] data, int offset ) - { - LittleEndian.putShort( data, 0x0 + offset, field_1_nAuto ); - } - - /** - * Size of record - */ - public static int getSize() - { - return 0 + 2; - } - - public String toString() - { - StringBuilder builder = new StringBuilder(); - builder.append( "[FRD]\n" ); - builder.append( " .nAuto = " ); - builder.append( " (" ).append( getNAuto() ).append( " )\n" ); - - builder.append( "[/FRD]\n" ); - return builder.toString(); - } - - /** - * If > 0, the note is an automatically numbered note, otherwise it has a - * custom mark. - */ - public short getNAuto() - { - return field_1_nAuto; - } - - /** - * If > 0, the note is an automatically numbered note, otherwise it has a - * custom mark. - */ - public void setNAuto( short field_1_nAuto ) - { - this.field_1_nAuto = field_1_nAuto; - } - -} // END OF CLASS diff --git a/src/scratchpad/src/org/apache/poi/hwpf/model/types/FSPAAbstractType.java b/src/scratchpad/src/org/apache/poi/hwpf/model/types/FSPAAbstractType.java deleted file mode 100644 index 8d7df40e3..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/model/types/FSPAAbstractType.java +++ /dev/null @@ -1,411 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hwpf.model.types; - - -import org.apache.poi.util.BitField; -import org.apache.poi.util.Internal; -import org.apache.poi.util.LittleEndian; - -/** - * File Shape Address (FSPA). - *

    - * Class and fields descriptions are quoted from Microsoft Office Word 97-2007 - * Binary File Format - * - *

    - * NOTE: This source is automatically generated please do not modify this file. - * Either subclass or remove the record in src/types/definitions. - *

    - * This class is internal. It content or properties may change without notice - * due to changes in our knowledge of internal Microsoft Word binary structures. - * - * @author Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary - * File Format Specification [*.doc] - */ -@Internal -public abstract class FSPAAbstractType -{ - - protected int field_1_spid; - protected int field_2_xaLeft; - protected int field_3_yaTop; - protected int field_4_xaRight; - protected int field_5_yaBottom; - protected short field_6_flags; - /**/private static BitField fHdr = new BitField(0x0001); - /**/private static BitField bx = new BitField(0x0006); - /**/private static BitField by = new BitField(0x0018); - /**/private static BitField wr = new BitField(0x01E0); - /**/private static BitField wrk = new BitField(0x1E00); - /**/private static BitField fRcaSimple = new BitField(0x2000); - /**/private static BitField fBelowText = new BitField(0x4000); - /**/private static BitField fAnchorLock = new BitField(0x8000); - protected int field_7_cTxbx; - - protected FSPAAbstractType() - { - } - - protected void fillFields( byte[] data, int offset ) - { - field_1_spid = LittleEndian.getInt(data, 0x0 + offset); - field_2_xaLeft = LittleEndian.getInt(data, 0x4 + offset); - field_3_yaTop = LittleEndian.getInt(data, 0x8 + offset); - field_4_xaRight = LittleEndian.getInt(data, 0xc + offset); - field_5_yaBottom = LittleEndian.getInt(data, 0x10 + offset); - field_6_flags = LittleEndian.getShort(data, 0x14 + offset); - field_7_cTxbx = LittleEndian.getInt(data, 0x16 + offset); - } - - public void serialize( byte[] data, int offset ) - { - LittleEndian.putInt(data, 0x0 + offset, field_1_spid); - LittleEndian.putInt(data, 0x4 + offset, field_2_xaLeft); - LittleEndian.putInt(data, 0x8 + offset, field_3_yaTop); - LittleEndian.putInt(data, 0xc + offset, field_4_xaRight); - LittleEndian.putInt(data, 0x10 + offset, field_5_yaBottom); - LittleEndian.putShort(data, 0x14 + offset, field_6_flags); - LittleEndian.putInt(data, 0x16 + offset, field_7_cTxbx); - } - - /** - * Size of record - */ - public static int getSize() - { - return 0 + 4 + 4 + 4 + 4 + 4 + 2 + 4; - } - - public String toString() - { - StringBuilder builder = new StringBuilder(); - builder.append("[FSPA]\n"); - builder.append(" .spid = "); - builder.append(" (").append(getSpid()).append(" )\n"); - builder.append(" .xaLeft = "); - builder.append(" (").append(getXaLeft()).append(" )\n"); - builder.append(" .yaTop = "); - builder.append(" (").append(getYaTop()).append(" )\n"); - builder.append(" .xaRight = "); - builder.append(" (").append(getXaRight()).append(" )\n"); - builder.append(" .yaBottom = "); - builder.append(" (").append(getYaBottom()).append(" )\n"); - builder.append(" .flags = "); - builder.append(" (").append(getFlags()).append(" )\n"); - builder.append(" .fHdr = ").append(isFHdr()).append('\n'); - builder.append(" .bx = ").append(getBx()).append('\n'); - builder.append(" .by = ").append(getBy()).append('\n'); - builder.append(" .wr = ").append(getWr()).append('\n'); - builder.append(" .wrk = ").append(getWrk()).append('\n'); - builder.append(" .fRcaSimple = ").append(isFRcaSimple()).append('\n'); - builder.append(" .fBelowText = ").append(isFBelowText()).append('\n'); - builder.append(" .fAnchorLock = ").append(isFAnchorLock()).append('\n'); - builder.append(" .cTxbx = "); - builder.append(" (").append(getCTxbx()).append(" )\n"); - - builder.append("[/FSPA]\n"); - return builder.toString(); - } - - /** - * Shape Identifier. Used in conjunction with the office art data (found via fcDggInfo in the FIB) to find the actual data for this shape. - */ - @Internal - public int getSpid() - { - return field_1_spid; - } - - /** - * Shape Identifier. Used in conjunction with the office art data (found via fcDggInfo in the FIB) to find the actual data for this shape. - */ - @Internal - public void setSpid( int field_1_spid ) - { - this.field_1_spid = field_1_spid; - } - - /** - * Left of rectangle enclosing shape relative to the origin of the shape. - */ - @Internal - public int getXaLeft() - { - return field_2_xaLeft; - } - - /** - * Left of rectangle enclosing shape relative to the origin of the shape. - */ - @Internal - public void setXaLeft( int field_2_xaLeft ) - { - this.field_2_xaLeft = field_2_xaLeft; - } - - /** - * Top of rectangle enclosing shape relative to the origin of the shape. - */ - @Internal - public int getYaTop() - { - return field_3_yaTop; - } - - /** - * Top of rectangle enclosing shape relative to the origin of the shape. - */ - @Internal - public void setYaTop( int field_3_yaTop ) - { - this.field_3_yaTop = field_3_yaTop; - } - - /** - * Right of rectangle enclosing shape relative to the origin of the shape. - */ - @Internal - public int getXaRight() - { - return field_4_xaRight; - } - - /** - * Right of rectangle enclosing shape relative to the origin of the shape. - */ - @Internal - public void setXaRight( int field_4_xaRight ) - { - this.field_4_xaRight = field_4_xaRight; - } - - /** - * Bottom of the rectangle enclosing shape relative to the origin of the shape. - */ - @Internal - public int getYaBottom() - { - return field_5_yaBottom; - } - - /** - * Bottom of the rectangle enclosing shape relative to the origin of the shape. - */ - @Internal - public void setYaBottom( int field_5_yaBottom ) - { - this.field_5_yaBottom = field_5_yaBottom; - } - - /** - * Get the flags field for the FSPA record. - */ - @Internal - public short getFlags() - { - return field_6_flags; - } - - /** - * Set the flags field for the FSPA record. - */ - @Internal - public void setFlags( short field_6_flags ) - { - this.field_6_flags = field_6_flags; - } - - /** - * Count of textboxes in shape (undo doc only). - */ - @Internal - public int getCTxbx() - { - return field_7_cTxbx; - } - - /** - * Count of textboxes in shape (undo doc only). - */ - @Internal - public void setCTxbx( int field_7_cTxbx ) - { - this.field_7_cTxbx = field_7_cTxbx; - } - - /** - * Sets the fHdr field value. - * 1 in the undo doc when shape is from the header doc, 0 otherwise (undefined when not in the undo doc) - */ - @Internal - public void setFHdr( boolean value ) - { - field_6_flags = (short)fHdr.setBoolean(field_6_flags, value); - } - - /** - * 1 in the undo doc when shape is from the header doc, 0 otherwise (undefined when not in the undo doc) - * @return the fHdr field value. - */ - @Internal - public boolean isFHdr() - { - return fHdr.isSet(field_6_flags); - } - - /** - * Sets the bx field value. - * X position of shape relative to anchor CP - */ - @Internal - public void setBx( byte value ) - { - field_6_flags = (short)bx.setValue(field_6_flags, value); - } - - /** - * X position of shape relative to anchor CP - * @return the bx field value. - */ - @Internal - public byte getBx() - { - return ( byte )bx.getValue(field_6_flags); - } - - /** - * Sets the by field value. - * Y position of shape relative to anchor CP - */ - @Internal - public void setBy( byte value ) - { - field_6_flags = (short)by.setValue(field_6_flags, value); - } - - /** - * Y position of shape relative to anchor CP - * @return the by field value. - */ - @Internal - public byte getBy() - { - return ( byte )by.getValue(field_6_flags); - } - - /** - * Sets the wr field value. - * Text wrapping mode - */ - @Internal - public void setWr( byte value ) - { - field_6_flags = (short)wr.setValue(field_6_flags, value); - } - - /** - * Text wrapping mode - * @return the wr field value. - */ - @Internal - public byte getWr() - { - return ( byte )wr.getValue(field_6_flags); - } - - /** - * Sets the wrk field value. - * Text wrapping mode type (valid only for wrapping modes 2 and 4 - */ - @Internal - public void setWrk( byte value ) - { - field_6_flags = (short)wrk.setValue(field_6_flags, value); - } - - /** - * Text wrapping mode type (valid only for wrapping modes 2 and 4 - * @return the wrk field value. - */ - @Internal - public byte getWrk() - { - return ( byte )wrk.getValue(field_6_flags); - } - - /** - * Sets the fRcaSimple field value. - * When set, temporarily overrides bx, by, forcing the xaLeft, xaRight, yaTop, and yaBottom fields to all be page relative. - */ - @Internal - public void setFRcaSimple( boolean value ) - { - field_6_flags = (short)fRcaSimple.setBoolean(field_6_flags, value); - } - - /** - * When set, temporarily overrides bx, by, forcing the xaLeft, xaRight, yaTop, and yaBottom fields to all be page relative. - * @return the fRcaSimple field value. - */ - @Internal - public boolean isFRcaSimple() - { - return fRcaSimple.isSet(field_6_flags); - } - - /** - * Sets the fBelowText field value. - * - */ - @Internal - public void setFBelowText( boolean value ) - { - field_6_flags = (short)fBelowText.setBoolean(field_6_flags, value); - } - - /** - * - * @return the fBelowText field value. - */ - @Internal - public boolean isFBelowText() - { - return fBelowText.isSet(field_6_flags); - } - - /** - * Sets the fAnchorLock field value. - * - */ - @Internal - public void setFAnchorLock( boolean value ) - { - field_6_flags = (short)fAnchorLock.setBoolean(field_6_flags, value); - } - - /** - * - * @return the fAnchorLock field value. - */ - @Internal - public boolean isFAnchorLock() - { - return fAnchorLock.isSet(field_6_flags); - } - -} // END OF CLASS diff --git a/src/scratchpad/src/org/apache/poi/hwpf/model/types/FibBaseAbstractType.java b/src/scratchpad/src/org/apache/poi/hwpf/model/types/FibBaseAbstractType.java deleted file mode 100644 index de588af3d..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/model/types/FibBaseAbstractType.java +++ /dev/null @@ -1,837 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.model.types; - -import org.apache.poi.util.BitField; -import org.apache.poi.util.Internal; -import org.apache.poi.util.LittleEndian; - -/** - * Base part of the File information Block (FibBase). Holds the core part of the FIB, - from the first 32 bytes.

    Class and fields descriptions are quoted from Microsoft - Office Word 97-2007 Binary File Format and [MS-DOC] - v20110608 Word (.doc) Binary File - Format - - *

    - * NOTE: This source is automatically generated please do not modify this file. Either subclass or - * remove the record in src/types/definitions. - *

    - * This class is internal. It content or properties may change without notice - * due to changes in our knowledge of internal Microsoft Word binary structures. - - * @author Andrew C. Oliver; Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary - File Format Specification [*.doc] and [MS-DOC] - v20110608 Word (.doc) Binary File Format - - */ -@Internal -public abstract class FibBaseAbstractType -{ - - protected int field_1_wIdent; - protected int field_2_nFib; - protected int field_3_unused; - protected int field_4_lid; - protected int field_5_pnNext; - protected short field_6_flags1; - /**/private static final BitField fDot = new BitField(0x0001); - /**/private static final BitField fGlsy = new BitField(0x0002); - /**/private static final BitField fComplex = new BitField(0x0004); - /**/private static final BitField fHasPic = new BitField(0x0008); - /**/private static final BitField cQuickSaves = new BitField(0x00F0); - /**/private static final BitField fEncrypted = new BitField(0x0100); - /**/private static final BitField fWhichTblStm = new BitField(0x0200); - /**/private static final BitField fReadOnlyRecommended = new BitField(0x0400); - /**/private static final BitField fWriteReservation = new BitField(0x0800); - /**/private static final BitField fExtChar = new BitField(0x1000); - /**/private static final BitField fLoadOverride = new BitField(0x2000); - /**/private static final BitField fFarEast = new BitField(0x4000); - /**/private static final BitField fObfuscated = new BitField(0x8000); - protected int field_7_nFibBack; - protected int field_8_lKey; - @Deprecated - protected byte field_9_envr; - protected byte field_10_flags2; - /**/private static final BitField fMac = new BitField(0x01); - /**/private static final BitField fEmptySpecial = new BitField(0x02); - /**/private static final BitField fLoadOverridePage = new BitField(0x04); - /**/private static final BitField reserved1 = new BitField(0x08); - /**/private static final BitField reserved2 = new BitField(0x10); - /**/private static final BitField fSpare0 = new BitField(0xFE); - @Deprecated - protected short field_11_Chs; - @Deprecated - protected short field_12_chsTables; - @Deprecated - protected int field_13_fcMin; - @Deprecated - protected int field_14_fcMac; - - protected FibBaseAbstractType() - { - } - - protected void fillFields( byte[] data, int offset ) - { - field_1_wIdent = LittleEndian.getShort( data, 0x0 + offset ); - field_2_nFib = LittleEndian.getShort( data, 0x2 + offset ); - field_3_unused = LittleEndian.getShort( data, 0x4 + offset ); - field_4_lid = LittleEndian.getShort( data, 0x6 + offset ); - field_5_pnNext = LittleEndian.getShort( data, 0x8 + offset ); - field_6_flags1 = LittleEndian.getShort( data, 0xa + offset ); - field_7_nFibBack = LittleEndian.getShort( data, 0xc + offset ); - field_8_lKey = LittleEndian.getInt( data, 0xe + offset ); - field_9_envr = data[ 0x12 + offset ]; - field_10_flags2 = data[ 0x13 + offset ]; - field_11_Chs = LittleEndian.getShort( data, 0x14 + offset ); - field_12_chsTables = LittleEndian.getShort( data, 0x16 + offset ); - field_13_fcMin = LittleEndian.getInt( data, 0x18 + offset ); - field_14_fcMac = LittleEndian.getInt( data, 0x1c + offset ); - } - - public void serialize( byte[] data, int offset ) - { - LittleEndian.putUShort( data, 0x0 + offset, field_1_wIdent ); - LittleEndian.putUShort( data, 0x2 + offset, field_2_nFib ); - LittleEndian.putUShort( data, 0x4 + offset, field_3_unused ); - LittleEndian.putUShort( data, 0x6 + offset, field_4_lid ); - LittleEndian.putUShort( data, 0x8 + offset, field_5_pnNext ); - LittleEndian.putShort( data, 0xa + offset, field_6_flags1 ); - LittleEndian.putUShort( data, 0xc + offset, field_7_nFibBack ); - LittleEndian.putInt( data, 0xe + offset, field_8_lKey ); - data[ 0x12 + offset ] = field_9_envr; - data[ 0x13 + offset ] = field_10_flags2; - LittleEndian.putShort( data, 0x14 + offset, field_11_Chs ); - LittleEndian.putShort( data, 0x16 + offset, field_12_chsTables ); - LittleEndian.putInt( data, 0x18 + offset, field_13_fcMin ); - LittleEndian.putInt( data, 0x1c + offset, field_14_fcMac ); - } - - public byte[] serialize() - { - final byte[] result = new byte[ getSize() ]; - serialize( result, 0 ); - return result; - } - - /** - * Size of record - */ - public static int getSize() - { - return 0 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 4 + 1 + 1 + 2 + 2 + 4 + 4; - } - - public String toString() - { - StringBuilder builder = new StringBuilder(); - builder.append("[FibBase]\n"); - builder.append(" .wIdent = "); - builder.append(" (").append(getWIdent()).append(" )\n"); - builder.append(" .nFib = "); - builder.append(" (").append(getNFib()).append(" )\n"); - builder.append(" .unused = "); - builder.append(" (").append(getUnused()).append(" )\n"); - builder.append(" .lid = "); - builder.append(" (").append(getLid()).append(" )\n"); - builder.append(" .pnNext = "); - builder.append(" (").append(getPnNext()).append(" )\n"); - builder.append(" .flags1 = "); - builder.append(" (").append(getFlags1()).append(" )\n"); - builder.append(" .fDot = ").append(isFDot()).append('\n'); - builder.append(" .fGlsy = ").append(isFGlsy()).append('\n'); - builder.append(" .fComplex = ").append(isFComplex()).append('\n'); - builder.append(" .fHasPic = ").append(isFHasPic()).append('\n'); - builder.append(" .cQuickSaves = ").append(getCQuickSaves()).append('\n'); - builder.append(" .fEncrypted = ").append(isFEncrypted()).append('\n'); - builder.append(" .fWhichTblStm = ").append(isFWhichTblStm()).append('\n'); - builder.append(" .fReadOnlyRecommended = ").append(isFReadOnlyRecommended()).append('\n'); - builder.append(" .fWriteReservation = ").append(isFWriteReservation()).append('\n'); - builder.append(" .fExtChar = ").append(isFExtChar()).append('\n'); - builder.append(" .fLoadOverride = ").append(isFLoadOverride()).append('\n'); - builder.append(" .fFarEast = ").append(isFFarEast()).append('\n'); - builder.append(" .fObfuscated = ").append(isFObfuscated()).append('\n'); - builder.append(" .nFibBack = "); - builder.append(" (").append(getNFibBack()).append(" )\n"); - builder.append(" .lKey = "); - builder.append(" (").append(getLKey()).append(" )\n"); - builder.append(" .envr = "); - builder.append(" (").append(getEnvr()).append(" )\n"); - builder.append(" .flags2 = "); - builder.append(" (").append(getFlags2()).append(" )\n"); - builder.append(" .fMac = ").append(isFMac()).append('\n'); - builder.append(" .fEmptySpecial = ").append(isFEmptySpecial()).append('\n'); - builder.append(" .fLoadOverridePage = ").append(isFLoadOverridePage()).append('\n'); - builder.append(" .reserved1 = ").append(isReserved1()).append('\n'); - builder.append(" .reserved2 = ").append(isReserved2()).append('\n'); - builder.append(" .fSpare0 = ").append(getFSpare0()).append('\n'); - builder.append(" .Chs = "); - builder.append(" (").append(getChs()).append(" )\n"); - builder.append(" .chsTables = "); - builder.append(" (").append(getChsTables()).append(" )\n"); - builder.append(" .fcMin = "); - builder.append(" (").append(getFcMin()).append(" )\n"); - builder.append(" .fcMac = "); - builder.append(" (").append(getFcMac()).append(" )\n"); - - builder.append("[/FibBase]\n"); - return builder.toString(); - } - - /** - * An unsigned integer that specifies that this is a Word Binary File. This value MUST be 0xA5EC. - */ - @Internal - public int getWIdent() - { - return field_1_wIdent; - } - - /** - * An unsigned integer that specifies that this is a Word Binary File. This value MUST be 0xA5EC. - */ - @Internal - public void setWIdent( int field_1_wIdent ) - { - this.field_1_wIdent = field_1_wIdent; - } - - /** - * An unsigned integer that specifies the version number of the file format used. Superseded by FibRgCswNew.nFibNew if it is present. This value SHOULD be 0x00C1. - */ - @Internal - public int getNFib() - { - return field_2_nFib; - } - - /** - * An unsigned integer that specifies the version number of the file format used. Superseded by FibRgCswNew.nFibNew if it is present. This value SHOULD be 0x00C1. - */ - @Internal - public void setNFib( int field_2_nFib ) - { - this.field_2_nFib = field_2_nFib; - } - - /** - * This value is undefined and MUST be ignored. - */ - @Internal - public int getUnused() - { - return field_3_unused; - } - - /** - * This value is undefined and MUST be ignored. - */ - @Internal - public void setUnused( int field_3_unused ) - { - this.field_3_unused = field_3_unused; - } - - /** - * A LID that specifies the install language of the application that is producing the document. If nFib is 0x00D9 or greater, then any East Asian install lid or any install lid with a base language of Spanish, German or French MUST be recorded as lidAmerican. If the nFib is 0x0101 or greater, then any install lid with a base language of Vietnamese, Thai, or Hindi MUST be recorded as lidAmerican.. - */ - @Internal - public int getLid() - { - return field_4_lid; - } - - /** - * A LID that specifies the install language of the application that is producing the document. If nFib is 0x00D9 or greater, then any East Asian install lid or any install lid with a base language of Spanish, German or French MUST be recorded as lidAmerican. If the nFib is 0x0101 or greater, then any install lid with a base language of Vietnamese, Thai, or Hindi MUST be recorded as lidAmerican.. - */ - @Internal - public void setLid( int field_4_lid ) - { - this.field_4_lid = field_4_lid; - } - - /** - * An unsigned integer that specifies the offset in the WordDocument stream of the FIB for the document which contains all the AutoText items. - */ - @Internal - public int getPnNext() - { - return field_5_pnNext; - } - - /** - * An unsigned integer that specifies the offset in the WordDocument stream of the FIB for the document which contains all the AutoText items. - */ - @Internal - public void setPnNext( int field_5_pnNext ) - { - this.field_5_pnNext = field_5_pnNext; - } - - /** - * Get the flags1 field for the FibBase record. - */ - @Internal - public short getFlags1() - { - return field_6_flags1; - } - - /** - * Set the flags1 field for the FibBase record. - */ - @Internal - public void setFlags1( short field_6_flags1 ) - { - this.field_6_flags1 = field_6_flags1; - } - - /** - * This value SHOULD be 0x00BF. This value MUST be 0x00BF or 0x00C1. - */ - @Internal - public int getNFibBack() - { - return field_7_nFibBack; - } - - /** - * This value SHOULD be 0x00BF. This value MUST be 0x00BF or 0x00C1. - */ - @Internal - public void setNFibBack( int field_7_nFibBack ) - { - this.field_7_nFibBack = field_7_nFibBack; - } - - /** - * If fEncryption is 1 and fObfuscation is 1, this value specifies the XOR obfuscation password verifier. If fEncryption is 1 and fObfuscation is 0, this value specifies the size of the EncryptionHeader that is stored at the beginning of the Table stream as described in Encryption and Obfuscation. Otherwise, this value MUST be 0. - */ - @Internal - public int getLKey() - { - return field_8_lKey; - } - - /** - * If fEncryption is 1 and fObfuscation is 1, this value specifies the XOR obfuscation password verifier. If fEncryption is 1 and fObfuscation is 0, this value specifies the size of the EncryptionHeader that is stored at the beginning of the Table stream as described in Encryption and Obfuscation. Otherwise, this value MUST be 0. - */ - @Internal - public void setLKey( int field_8_lKey ) - { - this.field_8_lKey = field_8_lKey; - } - - /** - * This value MUST be 0, and MUST be ignored. - */ - @Internal - public byte getEnvr() - { - return field_9_envr; - } - - /** - * This value MUST be 0, and MUST be ignored. - */ - @Internal - public void setEnvr( byte field_9_envr ) - { - this.field_9_envr = field_9_envr; - } - - /** - * Get the flags2 field for the FibBase record. - */ - @Internal - public byte getFlags2() - { - return field_10_flags2; - } - - /** - * Set the flags2 field for the FibBase record. - */ - @Internal - public void setFlags2( byte field_10_flags2 ) - { - this.field_10_flags2 = field_10_flags2; - } - - /** - * This value MUST be 0 and MUST be ignored. - */ - @Internal - public short getChs() - { - return field_11_Chs; - } - - /** - * This value MUST be 0 and MUST be ignored. - */ - @Internal - public void setChs( short field_11_Chs ) - { - this.field_11_Chs = field_11_Chs; - } - - /** - * This value MUST be 0 and MUST be ignored. - */ - @Internal - public short getChsTables() - { - return field_12_chsTables; - } - - /** - * This value MUST be 0 and MUST be ignored. - */ - @Internal - public void setChsTables( short field_12_chsTables ) - { - this.field_12_chsTables = field_12_chsTables; - } - - /** - * This value is undefined and MUST be ignored. - */ - @Internal - public int getFcMin() - { - return field_13_fcMin; - } - - /** - * This value is undefined and MUST be ignored. - */ - @Internal - public void setFcMin( int field_13_fcMin ) - { - this.field_13_fcMin = field_13_fcMin; - } - - /** - * This value is undefined and MUST be ignored. - */ - @Internal - public int getFcMac() - { - return field_14_fcMac; - } - - /** - * This value is undefined and MUST be ignored. - */ - @Internal - public void setFcMac( int field_14_fcMac ) - { - this.field_14_fcMac = field_14_fcMac; - } - - /** - * Sets the fDot field value. - * Specifies whether this is a document template - */ - @Internal - public void setFDot( boolean value ) - { - field_6_flags1 = (short)fDot.setBoolean(field_6_flags1, value); - } - - /** - * Specifies whether this is a document template - * @return the fDot field value. - */ - @Internal - public boolean isFDot() - { - return fDot.isSet(field_6_flags1); - } - - /** - * Sets the fGlsy field value. - * Specifies whether this is a document that contains only AutoText items - */ - @Internal - public void setFGlsy( boolean value ) - { - field_6_flags1 = (short)fGlsy.setBoolean(field_6_flags1, value); - } - - /** - * Specifies whether this is a document that contains only AutoText items - * @return the fGlsy field value. - */ - @Internal - public boolean isFGlsy() - { - return fGlsy.isSet(field_6_flags1); - } - - /** - * Sets the fComplex field value. - * Specifies that the last save operation that was performed on this document was an incremental save operation - */ - @Internal - public void setFComplex( boolean value ) - { - field_6_flags1 = (short)fComplex.setBoolean(field_6_flags1, value); - } - - /** - * Specifies that the last save operation that was performed on this document was an incremental save operation - * @return the fComplex field value. - */ - @Internal - public boolean isFComplex() - { - return fComplex.isSet(field_6_flags1); - } - - /** - * Sets the fHasPic field value. - * When set to 0, there SHOULD be no pictures in the document - */ - @Internal - public void setFHasPic( boolean value ) - { - field_6_flags1 = (short)fHasPic.setBoolean(field_6_flags1, value); - } - - /** - * When set to 0, there SHOULD be no pictures in the document - * @return the fHasPic field value. - */ - @Internal - public boolean isFHasPic() - { - return fHasPic.isSet(field_6_flags1); - } - - /** - * Sets the cQuickSaves field value. - * An unsigned integer. If nFib is less than 0x00D9, then cQuickSaves specifies the number of consecutive times this document was incrementally saved. If nFib is 0x00D9 or greater, then cQuickSaves MUST be 0xF - */ - @Internal - public void setCQuickSaves( byte value ) - { - field_6_flags1 = (short)cQuickSaves.setValue(field_6_flags1, value); - } - - /** - * An unsigned integer. If nFib is less than 0x00D9, then cQuickSaves specifies the number of consecutive times this document was incrementally saved. If nFib is 0x00D9 or greater, then cQuickSaves MUST be 0xF - * @return the cQuickSaves field value. - */ - @Internal - public byte getCQuickSaves() - { - return ( byte )cQuickSaves.getValue(field_6_flags1); - } - - /** - * Sets the fEncrypted field value. - * Specifies whether the document is encrypted or obfuscated as specified in Encryption and Obfuscation - */ - @Internal - public void setFEncrypted( boolean value ) - { - field_6_flags1 = (short)fEncrypted.setBoolean(field_6_flags1, value); - } - - /** - * Specifies whether the document is encrypted or obfuscated as specified in Encryption and Obfuscation - * @return the fEncrypted field value. - */ - @Internal - public boolean isFEncrypted() - { - return fEncrypted.isSet(field_6_flags1); - } - - /** - * Sets the fWhichTblStm field value. - * Specifies the Table stream to which the FIB refers. When this value is set to 1, use 1Table; when this value is set to 0, use 0Table. - */ - @Internal - public void setFWhichTblStm( boolean value ) - { - field_6_flags1 = (short)fWhichTblStm.setBoolean(field_6_flags1, value); - } - - /** - * Specifies the Table stream to which the FIB refers. When this value is set to 1, use 1Table; when this value is set to 0, use 0Table. - * @return the fWhichTblStm field value. - */ - @Internal - public boolean isFWhichTblStm() - { - return fWhichTblStm.isSet(field_6_flags1); - } - - /** - * Sets the fReadOnlyRecommended field value. - * Specifies whether the document author recommended that the document be opened in read-only mode - */ - @Internal - public void setFReadOnlyRecommended( boolean value ) - { - field_6_flags1 = (short)fReadOnlyRecommended.setBoolean(field_6_flags1, value); - } - - /** - * Specifies whether the document author recommended that the document be opened in read-only mode - * @return the fReadOnlyRecommended field value. - */ - @Internal - public boolean isFReadOnlyRecommended() - { - return fReadOnlyRecommended.isSet(field_6_flags1); - } - - /** - * Sets the fWriteReservation field value. - * Specifies whether the document has a write-reservation password - */ - @Internal - public void setFWriteReservation( boolean value ) - { - field_6_flags1 = (short)fWriteReservation.setBoolean(field_6_flags1, value); - } - - /** - * Specifies whether the document has a write-reservation password - * @return the fWriteReservation field value. - */ - @Internal - public boolean isFWriteReservation() - { - return fWriteReservation.isSet(field_6_flags1); - } - - /** - * Sets the fExtChar field value. - * This value MUST be 1 - */ - @Internal - public void setFExtChar( boolean value ) - { - field_6_flags1 = (short)fExtChar.setBoolean(field_6_flags1, value); - } - - /** - * This value MUST be 1 - * @return the fExtChar field value. - */ - @Internal - public boolean isFExtChar() - { - return fExtChar.isSet(field_6_flags1); - } - - /** - * Sets the fLoadOverride field value. - * Specifies whether to override the language information and font that are specified in the paragraph style at istd 0 (the normal style) with the defaults that are appropriate for the installation language of the application - */ - @Internal - public void setFLoadOverride( boolean value ) - { - field_6_flags1 = (short)fLoadOverride.setBoolean(field_6_flags1, value); - } - - /** - * Specifies whether to override the language information and font that are specified in the paragraph style at istd 0 (the normal style) with the defaults that are appropriate for the installation language of the application - * @return the fLoadOverride field value. - */ - @Internal - public boolean isFLoadOverride() - { - return fLoadOverride.isSet(field_6_flags1); - } - - /** - * Sets the fFarEast field value. - * Specifies whether the installation language of the application that created the document was an East Asian language - */ - @Internal - public void setFFarEast( boolean value ) - { - field_6_flags1 = (short)fFarEast.setBoolean(field_6_flags1, value); - } - - /** - * Specifies whether the installation language of the application that created the document was an East Asian language - * @return the fFarEast field value. - */ - @Internal - public boolean isFFarEast() - { - return fFarEast.isSet(field_6_flags1); - } - - /** - * Sets the fObfuscated field value. - * If fEncrypted is 1, this bit specifies whether the document is obfuscated by using XOR obfuscation; otherwise, this bit MUST be ignored - */ - @Internal - public void setFObfuscated( boolean value ) - { - field_6_flags1 = (short)fObfuscated.setBoolean(field_6_flags1, value); - } - - /** - * If fEncrypted is 1, this bit specifies whether the document is obfuscated by using XOR obfuscation; otherwise, this bit MUST be ignored - * @return the fObfuscated field value. - */ - @Internal - public boolean isFObfuscated() - { - return fObfuscated.isSet(field_6_flags1); - } - - /** - * Sets the fMac field value. - * This value MUST be 0, and MUST be ignored - */ - @Internal - public void setFMac( boolean value ) - { - field_10_flags2 = (byte)fMac.setBoolean(field_10_flags2, value); - } - - /** - * This value MUST be 0, and MUST be ignored - * @return the fMac field value. - * @deprecated This field should not be used according to specification - */ - @Internal - @Deprecated - public boolean isFMac() - { - return fMac.isSet(field_10_flags2); - } - - /** - * Sets the fEmptySpecial field value. - * This value SHOULD be 0 and SHOULD be ignored - */ - @Internal - public void setFEmptySpecial( boolean value ) - { - field_10_flags2 = (byte)fEmptySpecial.setBoolean(field_10_flags2, value); - } - - /** - * This value SHOULD be 0 and SHOULD be ignored - * @return the fEmptySpecial field value. - * @deprecated This field should not be used according to specification - */ - @Internal - @Deprecated - public boolean isFEmptySpecial() - { - return fEmptySpecial.isSet(field_10_flags2); - } - - /** - * Sets the fLoadOverridePage field value. - * Specifies whether to override the section properties for page size, orientation, and margins with the defaults that are appropriate for the installation language of the application - */ - @Internal - public void setFLoadOverridePage( boolean value ) - { - field_10_flags2 = (byte)fLoadOverridePage.setBoolean(field_10_flags2, value); - } - - /** - * Specifies whether to override the section properties for page size, orientation, and margins with the defaults that are appropriate for the installation language of the application - * @return the fLoadOverridePage field value. - */ - @Internal - public boolean isFLoadOverridePage() - { - return fLoadOverridePage.isSet(field_10_flags2); - } - - /** - * Sets the reserved1 field value. - * This value is undefined and MUST be ignored - */ - @Internal - public void setReserved1( boolean value ) - { - field_10_flags2 = (byte)reserved1.setBoolean(field_10_flags2, value); - } - - /** - * This value is undefined and MUST be ignored - * @return the reserved1 field value. - * @deprecated This field should not be used according to specification - */ - @Internal - @Deprecated - public boolean isReserved1() - { - return reserved1.isSet(field_10_flags2); - } - - /** - * Sets the reserved2 field value. - * This value is undefined and MUST be ignored - */ - @Internal - public void setReserved2( boolean value ) - { - field_10_flags2 = (byte)reserved2.setBoolean(field_10_flags2, value); - } - - /** - * This value is undefined and MUST be ignored - * @return the reserved2 field value. - * @deprecated This field should not be used according to specification - */ - @Internal - @Deprecated - public boolean isReserved2() - { - return reserved2.isSet(field_10_flags2); - } - - /** - * Sets the fSpare0 field value. - * This value is undefined and MUST be ignored - */ - @Internal - public void setFSpare0( byte value ) - { - field_10_flags2 = (byte)fSpare0.setValue(field_10_flags2, value); - } - - /** - * This value is undefined and MUST be ignored - * @return the fSpare0 field value. - * @deprecated This field should not be used according to specification - */ - @Internal - @Deprecated - public byte getFSpare0() - { - return ( byte )fSpare0.getValue(field_10_flags2); - } - -} // END OF CLASS diff --git a/src/scratchpad/src/org/apache/poi/hwpf/model/types/FibRgLw95AbstractType.java b/src/scratchpad/src/org/apache/poi/hwpf/model/types/FibRgLw95AbstractType.java deleted file mode 100644 index d1a03a6b8..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/model/types/FibRgLw95AbstractType.java +++ /dev/null @@ -1,468 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - - -package org.apache.poi.hwpf.model.types; - -import org.apache.poi.util.Internal; -import org.apache.poi.util.LittleEndian; - -/** - * The FibRgLw95 structure is the third section of the FIB for Word95. - - *

    - * NOTE: This source is automatically generated please do not modify this file. Either subclass or - * remove the record in src/types/definitions. - *

    - * This class is internal. It content or properties may change without notice - * due to changes in our knowledge of internal Microsoft Word binary structures. - - * @author Sergey Vladimirov - - */ -@Internal -public abstract class FibRgLw95AbstractType -{ - - protected int field_1_cbMac; - @Deprecated - protected int field_2_reserved1; - @Deprecated - protected int field_3_reserved2; - @Deprecated - protected int field_4_reserved3; - @Deprecated - protected int field_5_reserved4; - protected int field_6_ccpText; - protected int field_7_ccpFtn; - protected int field_8_ccpHdd; - protected int field_9_ccpMcr; - protected int field_10_ccpAtn; - protected int field_11_ccpEdn; - protected int field_12_ccpTxbx; - protected int field_13_ccpHdrTxbx; - @Deprecated - protected int field_14_reserved5; - - protected FibRgLw95AbstractType() - { - } - - protected void fillFields( byte[] data, int offset ) - { - field_1_cbMac = LittleEndian.getInt( data, 0x0 + offset ); - field_2_reserved1 = LittleEndian.getInt( data, 0x4 + offset ); - field_3_reserved2 = LittleEndian.getInt( data, 0x8 + offset ); - field_4_reserved3 = LittleEndian.getInt( data, 0xc + offset ); - field_5_reserved4 = LittleEndian.getInt( data, 0x10 + offset ); - field_6_ccpText = LittleEndian.getInt( data, 0x14 + offset ); - field_7_ccpFtn = LittleEndian.getInt( data, 0x18 + offset ); - field_8_ccpHdd = LittleEndian.getInt( data, 0x1c + offset ); - field_9_ccpMcr = LittleEndian.getInt( data, 0x20 + offset ); - field_10_ccpAtn = LittleEndian.getInt( data, 0x24 + offset ); - field_11_ccpEdn = LittleEndian.getInt( data, 0x28 + offset ); - field_12_ccpTxbx = LittleEndian.getInt( data, 0x2c + offset ); - field_13_ccpHdrTxbx = LittleEndian.getInt( data, 0x30 + offset ); - field_14_reserved5 = LittleEndian.getInt( data, 0x34 + offset ); - } - - public void serialize( byte[] data, int offset ) - { - LittleEndian.putInt( data, 0x0 + offset, field_1_cbMac ); - LittleEndian.putInt( data, 0x4 + offset, field_2_reserved1 ); - LittleEndian.putInt( data, 0x8 + offset, field_3_reserved2 ); - LittleEndian.putInt( data, 0xc + offset, field_4_reserved3 ); - LittleEndian.putInt( data, 0x10 + offset, field_5_reserved4 ); - LittleEndian.putInt( data, 0x14 + offset, field_6_ccpText ); - LittleEndian.putInt( data, 0x18 + offset, field_7_ccpFtn ); - LittleEndian.putInt( data, 0x1c + offset, field_8_ccpHdd ); - LittleEndian.putInt( data, 0x20 + offset, field_9_ccpMcr ); - LittleEndian.putInt( data, 0x24 + offset, field_10_ccpAtn ); - LittleEndian.putInt( data, 0x28 + offset, field_11_ccpEdn ); - LittleEndian.putInt( data, 0x2c + offset, field_12_ccpTxbx ); - LittleEndian.putInt( data, 0x30 + offset, field_13_ccpHdrTxbx ); - LittleEndian.putInt( data, 0x34 + offset, field_14_reserved5 ); - } - - public byte[] serialize() - { - final byte[] result = new byte[ getSize() ]; - serialize( result, 0 ); - return result; - } - - /** - * Size of record - */ - public static int getSize() - { - return 0 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + 4; - } - - @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - return true; - if ( obj == null ) - return false; - if ( getClass() != obj.getClass() ) - return false; - FibRgLw95AbstractType other = (FibRgLw95AbstractType) obj; - if ( field_1_cbMac != other.field_1_cbMac ) - return false; - if ( field_2_reserved1 != other.field_2_reserved1 ) - return false; - if ( field_3_reserved2 != other.field_3_reserved2 ) - return false; - if ( field_4_reserved3 != other.field_4_reserved3 ) - return false; - if ( field_5_reserved4 != other.field_5_reserved4 ) - return false; - if ( field_6_ccpText != other.field_6_ccpText ) - return false; - if ( field_7_ccpFtn != other.field_7_ccpFtn ) - return false; - if ( field_8_ccpHdd != other.field_8_ccpHdd ) - return false; - if ( field_9_ccpMcr != other.field_9_ccpMcr ) - return false; - if ( field_10_ccpAtn != other.field_10_ccpAtn ) - return false; - if ( field_11_ccpEdn != other.field_11_ccpEdn ) - return false; - if ( field_12_ccpTxbx != other.field_12_ccpTxbx ) - return false; - if ( field_13_ccpHdrTxbx != other.field_13_ccpHdrTxbx ) - return false; - if ( field_14_reserved5 != other.field_14_reserved5 ) - return false; - return true; - } - - @Override - public int hashCode() - { - final int prime = 31; - int result = 1; - result = prime * result + field_1_cbMac; - result = prime * result + field_2_reserved1; - result = prime * result + field_3_reserved2; - result = prime * result + field_4_reserved3; - result = prime * result + field_5_reserved4; - result = prime * result + field_6_ccpText; - result = prime * result + field_7_ccpFtn; - result = prime * result + field_8_ccpHdd; - result = prime * result + field_9_ccpMcr; - result = prime * result + field_10_ccpAtn; - result = prime * result + field_11_ccpEdn; - result = prime * result + field_12_ccpTxbx; - result = prime * result + field_13_ccpHdrTxbx; - result = prime * result + field_14_reserved5; - return result; - } - - public String toString() - { - StringBuilder builder = new StringBuilder(); - builder.append("[FibRgLw95]\n"); - builder.append(" .cbMac = "); - builder.append(" (").append(getCbMac()).append(" )\n"); - builder.append(" .reserved1 = "); - builder.append(" (").append(getReserved1()).append(" )\n"); - builder.append(" .reserved2 = "); - builder.append(" (").append(getReserved2()).append(" )\n"); - builder.append(" .reserved3 = "); - builder.append(" (").append(getReserved3()).append(" )\n"); - builder.append(" .reserved4 = "); - builder.append(" (").append(getReserved4()).append(" )\n"); - builder.append(" .ccpText = "); - builder.append(" (").append(getCcpText()).append(" )\n"); - builder.append(" .ccpFtn = "); - builder.append(" (").append(getCcpFtn()).append(" )\n"); - builder.append(" .ccpHdd = "); - builder.append(" (").append(getCcpHdd()).append(" )\n"); - builder.append(" .ccpMcr = "); - builder.append(" (").append(getCcpMcr()).append(" )\n"); - builder.append(" .ccpAtn = "); - builder.append(" (").append(getCcpAtn()).append(" )\n"); - builder.append(" .ccpEdn = "); - builder.append(" (").append(getCcpEdn()).append(" )\n"); - builder.append(" .ccpTxbx = "); - builder.append(" (").append(getCcpTxbx()).append(" )\n"); - builder.append(" .ccpHdrTxbx = "); - builder.append(" (").append(getCcpHdrTxbx()).append(" )\n"); - builder.append(" .reserved5 = "); - builder.append(" (").append(getReserved5()).append(" )\n"); - - builder.append("[/FibRgLw95]\n"); - return builder.toString(); - } - - /** - * Get the cbMac field for the FibRgLw95 record. - */ - @Internal - public int getCbMac() - { - return field_1_cbMac; - } - - /** - * Set the cbMac field for the FibRgLw95 record. - */ - @Internal - public void setCbMac( int field_1_cbMac ) - { - this.field_1_cbMac = field_1_cbMac; - } - - /** - * Get the reserved1 field for the FibRgLw95 record. - */ - @Internal - public int getReserved1() - { - return field_2_reserved1; - } - - /** - * Set the reserved1 field for the FibRgLw95 record. - */ - @Internal - public void setReserved1( int field_2_reserved1 ) - { - this.field_2_reserved1 = field_2_reserved1; - } - - /** - * Get the reserved2 field for the FibRgLw95 record. - */ - @Internal - public int getReserved2() - { - return field_3_reserved2; - } - - /** - * Set the reserved2 field for the FibRgLw95 record. - */ - @Internal - public void setReserved2( int field_3_reserved2 ) - { - this.field_3_reserved2 = field_3_reserved2; - } - - /** - * Get the reserved3 field for the FibRgLw95 record. - */ - @Internal - public int getReserved3() - { - return field_4_reserved3; - } - - /** - * Set the reserved3 field for the FibRgLw95 record. - */ - @Internal - public void setReserved3( int field_4_reserved3 ) - { - this.field_4_reserved3 = field_4_reserved3; - } - - /** - * Get the reserved4 field for the FibRgLw95 record. - */ - @Internal - public int getReserved4() - { - return field_5_reserved4; - } - - /** - * Set the reserved4 field for the FibRgLw95 record. - */ - @Internal - public void setReserved4( int field_5_reserved4 ) - { - this.field_5_reserved4 = field_5_reserved4; - } - - /** - * Get the ccpText field for the FibRgLw95 record. - */ - @Internal - public int getCcpText() - { - return field_6_ccpText; - } - - /** - * Set the ccpText field for the FibRgLw95 record. - */ - @Internal - public void setCcpText( int field_6_ccpText ) - { - this.field_6_ccpText = field_6_ccpText; - } - - /** - * Get the ccpFtn field for the FibRgLw95 record. - */ - @Internal - public int getCcpFtn() - { - return field_7_ccpFtn; - } - - /** - * Set the ccpFtn field for the FibRgLw95 record. - */ - @Internal - public void setCcpFtn( int field_7_ccpFtn ) - { - this.field_7_ccpFtn = field_7_ccpFtn; - } - - /** - * Get the ccpHdd field for the FibRgLw95 record. - */ - @Internal - public int getCcpHdd() - { - return field_8_ccpHdd; - } - - /** - * Set the ccpHdd field for the FibRgLw95 record. - */ - @Internal - public void setCcpHdd( int field_8_ccpHdd ) - { - this.field_8_ccpHdd = field_8_ccpHdd; - } - - /** - * Get the ccpMcr field for the FibRgLw95 record. - */ - @Internal - public int getCcpMcr() - { - return field_9_ccpMcr; - } - - /** - * Set the ccpMcr field for the FibRgLw95 record. - */ - @Internal - public void setCcpMcr( int field_9_ccpMcr ) - { - this.field_9_ccpMcr = field_9_ccpMcr; - } - - /** - * Get the ccpAtn field for the FibRgLw95 record. - */ - @Internal - public int getCcpAtn() - { - return field_10_ccpAtn; - } - - /** - * Set the ccpAtn field for the FibRgLw95 record. - */ - @Internal - public void setCcpAtn( int field_10_ccpAtn ) - { - this.field_10_ccpAtn = field_10_ccpAtn; - } - - /** - * Get the ccpEdn field for the FibRgLw95 record. - */ - @Internal - public int getCcpEdn() - { - return field_11_ccpEdn; - } - - /** - * Set the ccpEdn field for the FibRgLw95 record. - */ - @Internal - public void setCcpEdn( int field_11_ccpEdn ) - { - this.field_11_ccpEdn = field_11_ccpEdn; - } - - /** - * Get the ccpTxbx field for the FibRgLw95 record. - */ - @Internal - public int getCcpTxbx() - { - return field_12_ccpTxbx; - } - - /** - * Set the ccpTxbx field for the FibRgLw95 record. - */ - @Internal - public void setCcpTxbx( int field_12_ccpTxbx ) - { - this.field_12_ccpTxbx = field_12_ccpTxbx; - } - - /** - * Get the ccpHdrTxbx field for the FibRgLw95 record. - */ - @Internal - public int getCcpHdrTxbx() - { - return field_13_ccpHdrTxbx; - } - - /** - * Set the ccpHdrTxbx field for the FibRgLw95 record. - */ - @Internal - public void setCcpHdrTxbx( int field_13_ccpHdrTxbx ) - { - this.field_13_ccpHdrTxbx = field_13_ccpHdrTxbx; - } - - /** - * Get the reserved5 field for the FibRgLw95 record. - */ - @Internal - public int getReserved5() - { - return field_14_reserved5; - } - - /** - * Set the reserved5 field for the FibRgLw95 record. - */ - @Internal - public void setReserved5( int field_14_reserved5 ) - { - this.field_14_reserved5 = field_14_reserved5; - } - -} // END OF CLASS diff --git a/src/scratchpad/src/org/apache/poi/hwpf/model/types/FibRgLw97AbstractType.java b/src/scratchpad/src/org/apache/poi/hwpf/model/types/FibRgLw97AbstractType.java deleted file mode 100644 index f81c9bc86..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/model/types/FibRgLw97AbstractType.java +++ /dev/null @@ -1,686 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hwpf.model.types; - -import org.apache.poi.util.Internal; -import org.apache.poi.util.LittleEndian; - -/** - * The FibRgLw97 structure is the third section of the FIB. This contains an array of - 4-byte values.

    Class and fields descriptions are quoted from Microsoft Office Word - 97-2007 Binary File Format and [MS-DOC] - v20110608 Word (.doc) Binary File Format - - *

    - * NOTE: This source is automatically generated please do not modify this file. Either subclass or - * remove the record in src/types/definitions. - *

    - * This class is internal. It content or properties may change without notice - * due to changes in our knowledge of internal Microsoft Word binary structures. - - * @author Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary File Format - Specification [*.doc] and [MS-DOC] - v20110608 Word (.doc) Binary File Format - - */ -@Internal -public abstract class FibRgLw97AbstractType -{ - - protected int field_1_cbMac; - @Deprecated - protected int field_2_reserved1; - @Deprecated - protected int field_3_reserved2; - protected int field_4_ccpText; - protected int field_5_ccpFtn; - protected int field_6_ccpHdd; - @Deprecated - protected int field_7_reserved3; - protected int field_8_ccpAtn; - protected int field_9_ccpEdn; - protected int field_10_ccpTxbx; - protected int field_11_ccpHdrTxbx; - @Deprecated - protected int field_12_reserved4; - @Deprecated - protected int field_13_reserved5; - @Deprecated - protected int field_14_reserved6; - @Deprecated - protected int field_15_reserved7; - @Deprecated - protected int field_16_reserved8; - @Deprecated - protected int field_17_reserved9; - @Deprecated - protected int field_18_reserved10; - @Deprecated - protected int field_19_reserved11; - @Deprecated - protected int field_20_reserved12; - @Deprecated - protected int field_21_reserved13; - @Deprecated - protected int field_22_reserved14; - - protected FibRgLw97AbstractType() - { - } - - protected void fillFields( byte[] data, int offset ) - { - field_1_cbMac = LittleEndian.getInt( data, 0x0 + offset ); - field_2_reserved1 = LittleEndian.getInt( data, 0x4 + offset ); - field_3_reserved2 = LittleEndian.getInt( data, 0x8 + offset ); - field_4_ccpText = LittleEndian.getInt( data, 0xc + offset ); - field_5_ccpFtn = LittleEndian.getInt( data, 0x10 + offset ); - field_6_ccpHdd = LittleEndian.getInt( data, 0x14 + offset ); - field_7_reserved3 = LittleEndian.getInt( data, 0x18 + offset ); - field_8_ccpAtn = LittleEndian.getInt( data, 0x1c + offset ); - field_9_ccpEdn = LittleEndian.getInt( data, 0x20 + offset ); - field_10_ccpTxbx = LittleEndian.getInt( data, 0x24 + offset ); - field_11_ccpHdrTxbx = LittleEndian.getInt( data, 0x28 + offset ); - field_12_reserved4 = LittleEndian.getInt( data, 0x2c + offset ); - field_13_reserved5 = LittleEndian.getInt( data, 0x30 + offset ); - field_14_reserved6 = LittleEndian.getInt( data, 0x34 + offset ); - field_15_reserved7 = LittleEndian.getInt( data, 0x38 + offset ); - field_16_reserved8 = LittleEndian.getInt( data, 0x3c + offset ); - field_17_reserved9 = LittleEndian.getInt( data, 0x40 + offset ); - field_18_reserved10 = LittleEndian.getInt( data, 0x44 + offset ); - field_19_reserved11 = LittleEndian.getInt( data, 0x48 + offset ); - field_20_reserved12 = LittleEndian.getInt( data, 0x4c + offset ); - field_21_reserved13 = LittleEndian.getInt( data, 0x50 + offset ); - field_22_reserved14 = LittleEndian.getInt( data, 0x54 + offset ); - } - - public void serialize( byte[] data, int offset ) - { - LittleEndian.putInt( data, 0x0 + offset, field_1_cbMac ); - LittleEndian.putInt( data, 0x4 + offset, field_2_reserved1 ); - LittleEndian.putInt( data, 0x8 + offset, field_3_reserved2 ); - LittleEndian.putInt( data, 0xc + offset, field_4_ccpText ); - LittleEndian.putInt( data, 0x10 + offset, field_5_ccpFtn ); - LittleEndian.putInt( data, 0x14 + offset, field_6_ccpHdd ); - LittleEndian.putInt( data, 0x18 + offset, field_7_reserved3 ); - LittleEndian.putInt( data, 0x1c + offset, field_8_ccpAtn ); - LittleEndian.putInt( data, 0x20 + offset, field_9_ccpEdn ); - LittleEndian.putInt( data, 0x24 + offset, field_10_ccpTxbx ); - LittleEndian.putInt( data, 0x28 + offset, field_11_ccpHdrTxbx ); - LittleEndian.putInt( data, 0x2c + offset, field_12_reserved4 ); - LittleEndian.putInt( data, 0x30 + offset, field_13_reserved5 ); - LittleEndian.putInt( data, 0x34 + offset, field_14_reserved6 ); - LittleEndian.putInt( data, 0x38 + offset, field_15_reserved7 ); - LittleEndian.putInt( data, 0x3c + offset, field_16_reserved8 ); - LittleEndian.putInt( data, 0x40 + offset, field_17_reserved9 ); - LittleEndian.putInt( data, 0x44 + offset, field_18_reserved10 ); - LittleEndian.putInt( data, 0x48 + offset, field_19_reserved11 ); - LittleEndian.putInt( data, 0x4c + offset, field_20_reserved12 ); - LittleEndian.putInt( data, 0x50 + offset, field_21_reserved13 ); - LittleEndian.putInt( data, 0x54 + offset, field_22_reserved14 ); - } - - public byte[] serialize() - { - final byte[] result = new byte[ getSize() ]; - serialize( result, 0 ); - return result; - } - - /** - * Size of record - */ - public static int getSize() - { - return 0 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + 4; - } - - @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - return true; - if ( obj == null ) - return false; - if ( getClass() != obj.getClass() ) - return false; - FibRgLw97AbstractType other = (FibRgLw97AbstractType) obj; - if ( field_1_cbMac != other.field_1_cbMac ) - return false; - if ( field_2_reserved1 != other.field_2_reserved1 ) - return false; - if ( field_3_reserved2 != other.field_3_reserved2 ) - return false; - if ( field_4_ccpText != other.field_4_ccpText ) - return false; - if ( field_5_ccpFtn != other.field_5_ccpFtn ) - return false; - if ( field_6_ccpHdd != other.field_6_ccpHdd ) - return false; - if ( field_7_reserved3 != other.field_7_reserved3 ) - return false; - if ( field_8_ccpAtn != other.field_8_ccpAtn ) - return false; - if ( field_9_ccpEdn != other.field_9_ccpEdn ) - return false; - if ( field_10_ccpTxbx != other.field_10_ccpTxbx ) - return false; - if ( field_11_ccpHdrTxbx != other.field_11_ccpHdrTxbx ) - return false; - if ( field_12_reserved4 != other.field_12_reserved4 ) - return false; - if ( field_13_reserved5 != other.field_13_reserved5 ) - return false; - if ( field_14_reserved6 != other.field_14_reserved6 ) - return false; - if ( field_15_reserved7 != other.field_15_reserved7 ) - return false; - if ( field_16_reserved8 != other.field_16_reserved8 ) - return false; - if ( field_17_reserved9 != other.field_17_reserved9 ) - return false; - if ( field_18_reserved10 != other.field_18_reserved10 ) - return false; - if ( field_19_reserved11 != other.field_19_reserved11 ) - return false; - if ( field_20_reserved12 != other.field_20_reserved12 ) - return false; - if ( field_21_reserved13 != other.field_21_reserved13 ) - return false; - if ( field_22_reserved14 != other.field_22_reserved14 ) - return false; - return true; - } - - @Override - public int hashCode() - { - final int prime = 31; - int result = 1; - result = prime * result + field_1_cbMac; - result = prime * result + field_2_reserved1; - result = prime * result + field_3_reserved2; - result = prime * result + field_4_ccpText; - result = prime * result + field_5_ccpFtn; - result = prime * result + field_6_ccpHdd; - result = prime * result + field_7_reserved3; - result = prime * result + field_8_ccpAtn; - result = prime * result + field_9_ccpEdn; - result = prime * result + field_10_ccpTxbx; - result = prime * result + field_11_ccpHdrTxbx; - result = prime * result + field_12_reserved4; - result = prime * result + field_13_reserved5; - result = prime * result + field_14_reserved6; - result = prime * result + field_15_reserved7; - result = prime * result + field_16_reserved8; - result = prime * result + field_17_reserved9; - result = prime * result + field_18_reserved10; - result = prime * result + field_19_reserved11; - result = prime * result + field_20_reserved12; - result = prime * result + field_21_reserved13; - result = prime * result + field_22_reserved14; - return result; - } - - public String toString() - { - StringBuilder builder = new StringBuilder(); - builder.append("[FibRgLw97]\n"); - builder.append(" .cbMac = "); - builder.append(" (").append(getCbMac()).append(" )\n"); - builder.append(" .reserved1 = "); - builder.append(" (").append(getReserved1()).append(" )\n"); - builder.append(" .reserved2 = "); - builder.append(" (").append(getReserved2()).append(" )\n"); - builder.append(" .ccpText = "); - builder.append(" (").append(getCcpText()).append(" )\n"); - builder.append(" .ccpFtn = "); - builder.append(" (").append(getCcpFtn()).append(" )\n"); - builder.append(" .ccpHdd = "); - builder.append(" (").append(getCcpHdd()).append(" )\n"); - builder.append(" .reserved3 = "); - builder.append(" (").append(getReserved3()).append(" )\n"); - builder.append(" .ccpAtn = "); - builder.append(" (").append(getCcpAtn()).append(" )\n"); - builder.append(" .ccpEdn = "); - builder.append(" (").append(getCcpEdn()).append(" )\n"); - builder.append(" .ccpTxbx = "); - builder.append(" (").append(getCcpTxbx()).append(" )\n"); - builder.append(" .ccpHdrTxbx = "); - builder.append(" (").append(getCcpHdrTxbx()).append(" )\n"); - builder.append(" .reserved4 = "); - builder.append(" (").append(getReserved4()).append(" )\n"); - builder.append(" .reserved5 = "); - builder.append(" (").append(getReserved5()).append(" )\n"); - builder.append(" .reserved6 = "); - builder.append(" (").append(getReserved6()).append(" )\n"); - builder.append(" .reserved7 = "); - builder.append(" (").append(getReserved7()).append(" )\n"); - builder.append(" .reserved8 = "); - builder.append(" (").append(getReserved8()).append(" )\n"); - builder.append(" .reserved9 = "); - builder.append(" (").append(getReserved9()).append(" )\n"); - builder.append(" .reserved10 = "); - builder.append(" (").append(getReserved10()).append(" )\n"); - builder.append(" .reserved11 = "); - builder.append(" (").append(getReserved11()).append(" )\n"); - builder.append(" .reserved12 = "); - builder.append(" (").append(getReserved12()).append(" )\n"); - builder.append(" .reserved13 = "); - builder.append(" (").append(getReserved13()).append(" )\n"); - builder.append(" .reserved14 = "); - builder.append(" (").append(getReserved14()).append(" )\n"); - - builder.append("[/FibRgLw97]\n"); - return builder.toString(); - } - - /** - * Specifies the count of bytes of those written to the WordDocument stream of the file that have any meaning. All bytes in the WordDocument stream at offset cbMac and greater MUST be ignored.. - */ - @Internal - public int getCbMac() - { - return field_1_cbMac; - } - - /** - * Specifies the count of bytes of those written to the WordDocument stream of the file that have any meaning. All bytes in the WordDocument stream at offset cbMac and greater MUST be ignored.. - */ - @Internal - public void setCbMac( int field_1_cbMac ) - { - this.field_1_cbMac = field_1_cbMac; - } - - /** - * This value is undefined and MUST be ignored. - */ - @Internal - public int getReserved1() - { - return field_2_reserved1; - } - - /** - * This value is undefined and MUST be ignored. - */ - @Internal - public void setReserved1( int field_2_reserved1 ) - { - this.field_2_reserved1 = field_2_reserved1; - } - - /** - * This value is undefined and MUST be ignored. - */ - @Internal - public int getReserved2() - { - return field_3_reserved2; - } - - /** - * This value is undefined and MUST be ignored. - */ - @Internal - public void setReserved2( int field_3_reserved2 ) - { - this.field_3_reserved2 = field_3_reserved2; - } - - /** - * A signed integer that specifies the count of CPs in the main document. This value MUST be zero, 1, or greater. - */ - @Internal - public int getCcpText() - { - return field_4_ccpText; - } - - /** - * A signed integer that specifies the count of CPs in the main document. This value MUST be zero, 1, or greater. - */ - @Internal - public void setCcpText( int field_4_ccpText ) - { - this.field_4_ccpText = field_4_ccpText; - } - - /** - * A signed integer that specifies the count of CPs in the footnote subdocument. This value MUST be zero, 1, or greater. - */ - @Internal - public int getCcpFtn() - { - return field_5_ccpFtn; - } - - /** - * A signed integer that specifies the count of CPs in the footnote subdocument. This value MUST be zero, 1, or greater. - */ - @Internal - public void setCcpFtn( int field_5_ccpFtn ) - { - this.field_5_ccpFtn = field_5_ccpFtn; - } - - /** - * A signed integer that specifies the count of CPs in the header subdocument. This value MUST be zero, 1, or greater. - */ - @Internal - public int getCcpHdd() - { - return field_6_ccpHdd; - } - - /** - * A signed integer that specifies the count of CPs in the header subdocument. This value MUST be zero, 1, or greater. - */ - @Internal - public void setCcpHdd( int field_6_ccpHdd ) - { - this.field_6_ccpHdd = field_6_ccpHdd; - } - - /** - * This value is undefined and MUST be ignored. - */ - @Internal - public int getReserved3() - { - return field_7_reserved3; - } - - /** - * This value is undefined and MUST be ignored. - */ - @Internal - public void setReserved3( int field_7_reserved3 ) - { - this.field_7_reserved3 = field_7_reserved3; - } - - /** - * A signed integer that specifies the count of CPs in the comment subdocument. This value MUST be zero, 1, or greater. - */ - @Internal - public int getCcpAtn() - { - return field_8_ccpAtn; - } - - /** - * A signed integer that specifies the count of CPs in the comment subdocument. This value MUST be zero, 1, or greater. - */ - @Internal - public void setCcpAtn( int field_8_ccpAtn ) - { - this.field_8_ccpAtn = field_8_ccpAtn; - } - - /** - * A signed integer that specifies the count of CPs in the endnote subdocument. This value MUST be zero, 1, or greater. - */ - @Internal - public int getCcpEdn() - { - return field_9_ccpEdn; - } - - /** - * A signed integer that specifies the count of CPs in the endnote subdocument. This value MUST be zero, 1, or greater. - */ - @Internal - public void setCcpEdn( int field_9_ccpEdn ) - { - this.field_9_ccpEdn = field_9_ccpEdn; - } - - /** - * A signed integer that specifies the count of CPs in the textbox subdocument of the main document. This value MUST be zero, 1, or greater. - */ - @Internal - public int getCcpTxbx() - { - return field_10_ccpTxbx; - } - - /** - * A signed integer that specifies the count of CPs in the textbox subdocument of the main document. This value MUST be zero, 1, or greater. - */ - @Internal - public void setCcpTxbx( int field_10_ccpTxbx ) - { - this.field_10_ccpTxbx = field_10_ccpTxbx; - } - - /** - * A signed integer that specifies the count of CPs in the textbox subdocument of the header. This value MUST be zero, 1, or greater. - */ - @Internal - public int getCcpHdrTxbx() - { - return field_11_ccpHdrTxbx; - } - - /** - * A signed integer that specifies the count of CPs in the textbox subdocument of the header. This value MUST be zero, 1, or greater. - */ - @Internal - public void setCcpHdrTxbx( int field_11_ccpHdrTxbx ) - { - this.field_11_ccpHdrTxbx = field_11_ccpHdrTxbx; - } - - /** - * This value is undefined and MUST be ignored. - */ - @Internal - public int getReserved4() - { - return field_12_reserved4; - } - - /** - * This value is undefined and MUST be ignored. - */ - @Internal - public void setReserved4( int field_12_reserved4 ) - { - this.field_12_reserved4 = field_12_reserved4; - } - - /** - * This value is undefined and MUST be ignored. - */ - @Internal - public int getReserved5() - { - return field_13_reserved5; - } - - /** - * This value is undefined and MUST be ignored. - */ - @Internal - public void setReserved5( int field_13_reserved5 ) - { - this.field_13_reserved5 = field_13_reserved5; - } - - /** - * This value MUST be equal or less than the number of data elements in PlcBteChpx, as specified by FibRgFcLcb97.fcPlcfBteChpx and FibRgFcLcb97.lcbPlcfBteChpx. This value MUST be ignored. - */ - @Internal - public int getReserved6() - { - return field_14_reserved6; - } - - /** - * This value MUST be equal or less than the number of data elements in PlcBteChpx, as specified by FibRgFcLcb97.fcPlcfBteChpx and FibRgFcLcb97.lcbPlcfBteChpx. This value MUST be ignored. - */ - @Internal - public void setReserved6( int field_14_reserved6 ) - { - this.field_14_reserved6 = field_14_reserved6; - } - - /** - * This value is undefined and MUST be ignored. - */ - @Internal - public int getReserved7() - { - return field_15_reserved7; - } - - /** - * This value is undefined and MUST be ignored. - */ - @Internal - public void setReserved7( int field_15_reserved7 ) - { - this.field_15_reserved7 = field_15_reserved7; - } - - /** - * This value is undefined and MUST be ignored. - */ - @Internal - public int getReserved8() - { - return field_16_reserved8; - } - - /** - * This value is undefined and MUST be ignored. - */ - @Internal - public void setReserved8( int field_16_reserved8 ) - { - this.field_16_reserved8 = field_16_reserved8; - } - - /** - * This value MUST be less than or equal to the number of data elements in PlcBtePapx, as specified by FibRgFcLcb97.fcPlcfBtePapx and FibRgFcLcb97.lcbPlcfBtePapx. This value MUST be ignored. - */ - @Internal - public int getReserved9() - { - return field_17_reserved9; - } - - /** - * This value MUST be less than or equal to the number of data elements in PlcBtePapx, as specified by FibRgFcLcb97.fcPlcfBtePapx and FibRgFcLcb97.lcbPlcfBtePapx. This value MUST be ignored. - */ - @Internal - public void setReserved9( int field_17_reserved9 ) - { - this.field_17_reserved9 = field_17_reserved9; - } - - /** - * This value is undefined and MUST be ignored. - */ - @Internal - public int getReserved10() - { - return field_18_reserved10; - } - - /** - * This value is undefined and MUST be ignored. - */ - @Internal - public void setReserved10( int field_18_reserved10 ) - { - this.field_18_reserved10 = field_18_reserved10; - } - - /** - * This value is undefined and MUST be ignored. - */ - @Internal - public int getReserved11() - { - return field_19_reserved11; - } - - /** - * This value is undefined and MUST be ignored. - */ - @Internal - public void setReserved11( int field_19_reserved11 ) - { - this.field_19_reserved11 = field_19_reserved11; - } - - /** - * This value SHOULD be zero, and MUST be ignored. - */ - @Internal - public int getReserved12() - { - return field_20_reserved12; - } - - /** - * This value SHOULD be zero, and MUST be ignored. - */ - @Internal - public void setReserved12( int field_20_reserved12 ) - { - this.field_20_reserved12 = field_20_reserved12; - } - - /** - * This value MUST be zero and MUST be ignored. - */ - @Internal - public int getReserved13() - { - return field_21_reserved13; - } - - /** - * This value MUST be zero and MUST be ignored. - */ - @Internal - public void setReserved13( int field_21_reserved13 ) - { - this.field_21_reserved13 = field_21_reserved13; - } - - /** - * This value MUST be zero and MUST be ignored. - */ - @Internal - public int getReserved14() - { - return field_22_reserved14; - } - - /** - * This value MUST be zero and MUST be ignored. - */ - @Internal - public void setReserved14( int field_22_reserved14 ) - { - this.field_22_reserved14 = field_22_reserved14; - } - -} // END OF CLASS diff --git a/src/scratchpad/src/org/apache/poi/hwpf/model/types/FibRgW97AbstractType.java b/src/scratchpad/src/org/apache/poi/hwpf/model/types/FibRgW97AbstractType.java deleted file mode 100644 index 21d2e4ae1..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/model/types/FibRgW97AbstractType.java +++ /dev/null @@ -1,415 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hwpf.model.types; - - -import org.apache.poi.util.Internal; -import org.apache.poi.util.LittleEndian; - -/** - * The FibRgW97 structure is a variable-length portion of the Fib.

    Class and - fields descriptions are quoted from Microsoft Office Word 97-2007 Binary File Format and - [MS-DOC] - v20110608 Word (.doc) Binary File Format - - *

    - * NOTE: This source is automatically generated please do not modify this file. Either subclass or - * remove the record in src/types/definitions. - *

    - * This class is internal. It content or properties may change without notice - * due to changes in our knowledge of internal Microsoft Word binary structures. - - * @author Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary File Format - Specification [*.doc] and [MS-DOC] - v20110608 Word (.doc) Binary File Format - - */ -@Internal -public abstract class FibRgW97AbstractType -{ - - @Deprecated - protected short field_1_reserved1; - @Deprecated - protected short field_2_reserved2; - @Deprecated - protected short field_3_reserved3; - @Deprecated - protected short field_4_reserved4; - @Deprecated - protected short field_5_reserved5; - @Deprecated - protected short field_6_reserved6; - @Deprecated - protected short field_7_reserved7; - @Deprecated - protected short field_8_reserved8; - @Deprecated - protected short field_9_reserved9; - @Deprecated - protected short field_10_reserved10; - @Deprecated - protected short field_11_reserved11; - @Deprecated - protected short field_12_reserved12; - @Deprecated - protected short field_13_reserved13; - protected short field_14_lidFE; - - protected FibRgW97AbstractType() - { - } - - protected void fillFields( byte[] data, int offset ) - { - field_1_reserved1 = LittleEndian.getShort( data, 0x0 + offset ); - field_2_reserved2 = LittleEndian.getShort( data, 0x2 + offset ); - field_3_reserved3 = LittleEndian.getShort( data, 0x4 + offset ); - field_4_reserved4 = LittleEndian.getShort( data, 0x6 + offset ); - field_5_reserved5 = LittleEndian.getShort( data, 0x8 + offset ); - field_6_reserved6 = LittleEndian.getShort( data, 0xa + offset ); - field_7_reserved7 = LittleEndian.getShort( data, 0xc + offset ); - field_8_reserved8 = LittleEndian.getShort( data, 0xe + offset ); - field_9_reserved9 = LittleEndian.getShort( data, 0x10 + offset ); - field_10_reserved10 = LittleEndian.getShort( data, 0x12 + offset ); - field_11_reserved11 = LittleEndian.getShort( data, 0x14 + offset ); - field_12_reserved12 = LittleEndian.getShort( data, 0x16 + offset ); - field_13_reserved13 = LittleEndian.getShort( data, 0x18 + offset ); - field_14_lidFE = LittleEndian.getShort( data, 0x1a + offset ); - } - - public void serialize( byte[] data, int offset ) - { - LittleEndian.putShort( data, 0x0 + offset, field_1_reserved1 ); - LittleEndian.putShort( data, 0x2 + offset, field_2_reserved2 ); - LittleEndian.putShort( data, 0x4 + offset, field_3_reserved3 ); - LittleEndian.putShort( data, 0x6 + offset, field_4_reserved4 ); - LittleEndian.putShort( data, 0x8 + offset, field_5_reserved5 ); - LittleEndian.putShort( data, 0xa + offset, field_6_reserved6 ); - LittleEndian.putShort( data, 0xc + offset, field_7_reserved7 ); - LittleEndian.putShort( data, 0xe + offset, field_8_reserved8 ); - LittleEndian.putShort( data, 0x10 + offset, field_9_reserved9 ); - LittleEndian.putShort( data, 0x12 + offset, field_10_reserved10 ); - LittleEndian.putShort( data, 0x14 + offset, field_11_reserved11 ); - LittleEndian.putShort( data, 0x16 + offset, field_12_reserved12 ); - LittleEndian.putShort( data, 0x18 + offset, field_13_reserved13 ); - LittleEndian.putShort( data, 0x1a + offset, field_14_lidFE ); - } - - public byte[] serialize() - { - final byte[] result = new byte[ getSize() ]; - serialize( result, 0 ); - return result; - } - - /** - * Size of record - */ - public static int getSize() - { - return 0 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2; - } - - public String toString() - { - StringBuilder builder = new StringBuilder(); - builder.append("[FibRgW97]\n"); - builder.append(" .reserved1 = "); - builder.append(" (").append(getReserved1()).append(" )\n"); - builder.append(" .reserved2 = "); - builder.append(" (").append(getReserved2()).append(" )\n"); - builder.append(" .reserved3 = "); - builder.append(" (").append(getReserved3()).append(" )\n"); - builder.append(" .reserved4 = "); - builder.append(" (").append(getReserved4()).append(" )\n"); - builder.append(" .reserved5 = "); - builder.append(" (").append(getReserved5()).append(" )\n"); - builder.append(" .reserved6 = "); - builder.append(" (").append(getReserved6()).append(" )\n"); - builder.append(" .reserved7 = "); - builder.append(" (").append(getReserved7()).append(" )\n"); - builder.append(" .reserved8 = "); - builder.append(" (").append(getReserved8()).append(" )\n"); - builder.append(" .reserved9 = "); - builder.append(" (").append(getReserved9()).append(" )\n"); - builder.append(" .reserved10 = "); - builder.append(" (").append(getReserved10()).append(" )\n"); - builder.append(" .reserved11 = "); - builder.append(" (").append(getReserved11()).append(" )\n"); - builder.append(" .reserved12 = "); - builder.append(" (").append(getReserved12()).append(" )\n"); - builder.append(" .reserved13 = "); - builder.append(" (").append(getReserved13()).append(" )\n"); - builder.append(" .lidFE = "); - builder.append(" (").append(getLidFE()).append(" )\n"); - - builder.append("[/FibRgW97]\n"); - return builder.toString(); - } - - /** - * This value is undefined and MUST be ignored. - */ - @Internal - public short getReserved1() - { - return field_1_reserved1; - } - - /** - * This value is undefined and MUST be ignored. - */ - @Internal - public void setReserved1( short field_1_reserved1 ) - { - this.field_1_reserved1 = field_1_reserved1; - } - - /** - * This value is undefined and MUST be ignored. - */ - @Internal - public short getReserved2() - { - return field_2_reserved2; - } - - /** - * This value is undefined and MUST be ignored. - */ - @Internal - public void setReserved2( short field_2_reserved2 ) - { - this.field_2_reserved2 = field_2_reserved2; - } - - /** - * This value is undefined and MUST be ignored. - */ - @Internal - public short getReserved3() - { - return field_3_reserved3; - } - - /** - * This value is undefined and MUST be ignored. - */ - @Internal - public void setReserved3( short field_3_reserved3 ) - { - this.field_3_reserved3 = field_3_reserved3; - } - - /** - * This value is undefined and MUST be ignored. - */ - @Internal - public short getReserved4() - { - return field_4_reserved4; - } - - /** - * This value is undefined and MUST be ignored. - */ - @Internal - public void setReserved4( short field_4_reserved4 ) - { - this.field_4_reserved4 = field_4_reserved4; - } - - /** - * This value is undefined and MUST be ignored. - */ - @Internal - public short getReserved5() - { - return field_5_reserved5; - } - - /** - * This value is undefined and MUST be ignored. - */ - @Internal - public void setReserved5( short field_5_reserved5 ) - { - this.field_5_reserved5 = field_5_reserved5; - } - - /** - * This value is undefined and MUST be ignored. - */ - @Internal - public short getReserved6() - { - return field_6_reserved6; - } - - /** - * This value is undefined and MUST be ignored. - */ - @Internal - public void setReserved6( short field_6_reserved6 ) - { - this.field_6_reserved6 = field_6_reserved6; - } - - /** - * This value is undefined and MUST be ignored. - */ - @Internal - public short getReserved7() - { - return field_7_reserved7; - } - - /** - * This value is undefined and MUST be ignored. - */ - @Internal - public void setReserved7( short field_7_reserved7 ) - { - this.field_7_reserved7 = field_7_reserved7; - } - - /** - * This value is undefined and MUST be ignored. - */ - @Internal - public short getReserved8() - { - return field_8_reserved8; - } - - /** - * This value is undefined and MUST be ignored. - */ - @Internal - public void setReserved8( short field_8_reserved8 ) - { - this.field_8_reserved8 = field_8_reserved8; - } - - /** - * This value is undefined and MUST be ignored. - */ - @Internal - public short getReserved9() - { - return field_9_reserved9; - } - - /** - * This value is undefined and MUST be ignored. - */ - @Internal - public void setReserved9( short field_9_reserved9 ) - { - this.field_9_reserved9 = field_9_reserved9; - } - - /** - * This value is undefined and MUST be ignored. - */ - @Internal - public short getReserved10() - { - return field_10_reserved10; - } - - /** - * This value is undefined and MUST be ignored. - */ - @Internal - public void setReserved10( short field_10_reserved10 ) - { - this.field_10_reserved10 = field_10_reserved10; - } - - /** - * This value is undefined and MUST be ignored. - */ - @Internal - public short getReserved11() - { - return field_11_reserved11; - } - - /** - * This value is undefined and MUST be ignored. - */ - @Internal - public void setReserved11( short field_11_reserved11 ) - { - this.field_11_reserved11 = field_11_reserved11; - } - - /** - * This value is undefined and MUST be ignored. - */ - @Internal - public short getReserved12() - { - return field_12_reserved12; - } - - /** - * This value is undefined and MUST be ignored. - */ - @Internal - public void setReserved12( short field_12_reserved12 ) - { - this.field_12_reserved12 = field_12_reserved12; - } - - /** - * This value is undefined and MUST be ignored. - */ - @Internal - public short getReserved13() - { - return field_13_reserved13; - } - - /** - * This value is undefined and MUST be ignored. - */ - @Internal - public void setReserved13( short field_13_reserved13 ) - { - this.field_13_reserved13 = field_13_reserved13; - } - - /** - * A LID whose meaning depends on the nFib value. - */ - @Internal - public short getLidFE() - { - return field_14_lidFE; - } - - /** - * A LID whose meaning depends on the nFib value. - */ - @Internal - public void setLidFE( short field_14_lidFE ) - { - this.field_14_lidFE = field_14_lidFE; - } - -} // END OF CLASS diff --git a/src/scratchpad/src/org/apache/poi/hwpf/model/types/GrfhicAbstractType.java b/src/scratchpad/src/org/apache/poi/hwpf/model/types/GrfhicAbstractType.java deleted file mode 100644 index 8aace00d8..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/model/types/GrfhicAbstractType.java +++ /dev/null @@ -1,307 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.model.types; - - -import org.apache.poi.util.BitField; -import org.apache.poi.util.Internal; - -/** - * The grfhic structure is a set of HTML incompatibility flags that specify the HTML - incompatibilities of a list structure. The values specify possible incompatibilities between - an LVL or LVLF and HTML lists. The values do not define list properties.

    Class and - fields descriptions are quoted from [MS-DOC] -- v20110315 Word (.doc) Binary File Format - specification - - *

    - * NOTE: This source is automatically generated please do not modify this file. Either subclass or - * remove the record in src/types/definitions. - *

    - * This class is internal. It content or properties may change without notice - * due to changes in our knowledge of internal Microsoft Word binary structures. - - * @author Sergey Vladimirov; according to [MS-DOC] -- v20110315 Word (.doc) Binary File Format - specification - - */ -@Internal -public abstract class GrfhicAbstractType -{ - - protected byte field_1_grfhic; - /**/private static final BitField fHtmlChecked = new BitField(0x01); - /**/private static final BitField fHtmlUnsupported = new BitField(0x02); - /**/private static final BitField fHtmlListTextNotSharpDot = new BitField(0x04); - /**/private static final BitField fHtmlNotPeriod = new BitField(0x08); - /**/private static final BitField fHtmlFirstLineMismatch = new BitField(0x10); - /**/private static final BitField fHtmlTabLeftIndentMismatch = new BitField(0x20); - /**/private static final BitField fHtmlHangingIndentBeneathNumber = new BitField(0x40); - /**/private static final BitField fHtmlBuiltInBullet = new BitField(0x80); - - protected GrfhicAbstractType() - { - } - - protected void fillFields( byte[] data, int offset ) - { - field_1_grfhic = data[ 0x0 + offset ]; - } - - public void serialize( byte[] data, int offset ) - { - data[ 0x0 + offset ] = field_1_grfhic; - } - - public byte[] serialize() - { - final byte[] result = new byte[ getSize() ]; - serialize( result, 0 ); - return result; - } - - /** - * Size of record - */ - public static int getSize() - { - return 0 + 1; - } - - @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - return true; - if ( obj == null ) - return false; - if ( getClass() != obj.getClass() ) - return false; - GrfhicAbstractType other = (GrfhicAbstractType) obj; - if ( field_1_grfhic != other.field_1_grfhic ) - return false; - return true; - } - - @Override - public int hashCode() - { - final int prime = 31; - int result = 1; - result = prime * result + field_1_grfhic; - return result; - } - - public String toString() - { - StringBuilder builder = new StringBuilder(); - - builder.append("[Grfhic]\n"); - builder.append( " .grfhic = " ); - builder.append(" ( ").append( field_1_grfhic ).append( " )\n" ); - builder.append(" .fHtmlChecked = ").append(isFHtmlChecked()).append('\n'); - builder.append(" .fHtmlUnsupported = ").append(isFHtmlUnsupported()).append('\n'); - builder.append(" .fHtmlListTextNotSharpDot = ").append(isFHtmlListTextNotSharpDot()).append('\n'); - builder.append(" .fHtmlNotPeriod = ").append(isFHtmlNotPeriod()).append('\n'); - builder.append(" .fHtmlFirstLineMismatch = ").append(isFHtmlFirstLineMismatch()).append('\n'); - builder.append(" .fHtmlTabLeftIndentMismatch = ").append(isFHtmlTabLeftIndentMismatch()).append('\n'); - builder.append(" .fHtmlHangingIndentBeneathNumber = ").append(isFHtmlHangingIndentBeneathNumber()).append('\n'); - builder.append(" .fHtmlBuiltInBullet = ").append(isFHtmlBuiltInBullet()).append('\n'); - - builder.append("[/Grfhic]"); - return builder.toString(); - } - - /** - * HTML compatibility flags. - */ - @Internal - public byte getGrfhic() - { - return field_1_grfhic; - } - - /** - * HTML compatibility flags. - */ - @Internal - public void setGrfhic( byte field_1_grfhic ) - { - this.field_1_grfhic = field_1_grfhic; - } - - /** - * Sets the fHtmlChecked field value. - * Checked - */ - @Internal - public void setFHtmlChecked( boolean value ) - { - field_1_grfhic = (byte)fHtmlChecked.setBoolean(field_1_grfhic, value); - } - - /** - * Checked - * @return the fHtmlChecked field value. - */ - @Internal - public boolean isFHtmlChecked() - { - return fHtmlChecked.isSet(field_1_grfhic); - } - - /** - * Sets the fHtmlUnsupported field value. - * The numbering sequence or format is unsupported (includes tab & size) - */ - @Internal - public void setFHtmlUnsupported( boolean value ) - { - field_1_grfhic = (byte)fHtmlUnsupported.setBoolean(field_1_grfhic, value); - } - - /** - * The numbering sequence or format is unsupported (includes tab & size) - * @return the fHtmlUnsupported field value. - */ - @Internal - public boolean isFHtmlUnsupported() - { - return fHtmlUnsupported.isSet(field_1_grfhic); - } - - /** - * Sets the fHtmlListTextNotSharpDot field value. - * The list text is not "#." - */ - @Internal - public void setFHtmlListTextNotSharpDot( boolean value ) - { - field_1_grfhic = (byte)fHtmlListTextNotSharpDot.setBoolean(field_1_grfhic, value); - } - - /** - * The list text is not "#." - * @return the fHtmlListTextNotSharpDot field value. - */ - @Internal - public boolean isFHtmlListTextNotSharpDot() - { - return fHtmlListTextNotSharpDot.isSet(field_1_grfhic); - } - - /** - * Sets the fHtmlNotPeriod field value. - * Something other than a period is used - */ - @Internal - public void setFHtmlNotPeriod( boolean value ) - { - field_1_grfhic = (byte)fHtmlNotPeriod.setBoolean(field_1_grfhic, value); - } - - /** - * Something other than a period is used - * @return the fHtmlNotPeriod field value. - */ - @Internal - public boolean isFHtmlNotPeriod() - { - return fHtmlNotPeriod.isSet(field_1_grfhic); - } - - /** - * Sets the fHtmlFirstLineMismatch field value. - * First line indent mismatch - */ - @Internal - public void setFHtmlFirstLineMismatch( boolean value ) - { - field_1_grfhic = (byte)fHtmlFirstLineMismatch.setBoolean(field_1_grfhic, value); - } - - /** - * First line indent mismatch - * @return the fHtmlFirstLineMismatch field value. - */ - @Internal - public boolean isFHtmlFirstLineMismatch() - { - return fHtmlFirstLineMismatch.isSet(field_1_grfhic); - } - - /** - * Sets the fHtmlTabLeftIndentMismatch field value. - * The list tab and the dxaLeft don't match (need table?) - */ - @Internal - public void setFHtmlTabLeftIndentMismatch( boolean value ) - { - field_1_grfhic = (byte)fHtmlTabLeftIndentMismatch.setBoolean(field_1_grfhic, value); - } - - /** - * The list tab and the dxaLeft don't match (need table?) - * @return the fHtmlTabLeftIndentMismatch field value. - */ - @Internal - public boolean isFHtmlTabLeftIndentMismatch() - { - return fHtmlTabLeftIndentMismatch.isSet(field_1_grfhic); - } - - /** - * Sets the fHtmlHangingIndentBeneathNumber field value. - * The hanging indent falls beneath the number (need plain text) - */ - @Internal - public void setFHtmlHangingIndentBeneathNumber( boolean value ) - { - field_1_grfhic = (byte)fHtmlHangingIndentBeneathNumber.setBoolean(field_1_grfhic, value); - } - - /** - * The hanging indent falls beneath the number (need plain text) - * @return the fHtmlHangingIndentBeneathNumber field value. - */ - @Internal - public boolean isFHtmlHangingIndentBeneathNumber() - { - return fHtmlHangingIndentBeneathNumber.isSet(field_1_grfhic); - } - - /** - * Sets the fHtmlBuiltInBullet field value. - * A built-in HTML bullet - */ - @Internal - public void setFHtmlBuiltInBullet( boolean value ) - { - field_1_grfhic = (byte)fHtmlBuiltInBullet.setBoolean(field_1_grfhic, value); - } - - /** - * A built-in HTML bullet - * @return the fHtmlBuiltInBullet field value. - */ - @Internal - public boolean isFHtmlBuiltInBullet() - { - return fHtmlBuiltInBullet.isSet(field_1_grfhic); - } - -} // END OF CLASS diff --git a/src/scratchpad/src/org/apache/poi/hwpf/model/types/HRESIAbstractType.java b/src/scratchpad/src/org/apache/poi/hwpf/model/types/HRESIAbstractType.java deleted file mode 100644 index 0e9bd5fb6..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/model/types/HRESIAbstractType.java +++ /dev/null @@ -1,136 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.model.types; - -import org.apache.poi.util.Internal; - -/** - * Hyphenation (HRESI). - *

    - * Class and fields descriptions are quoted from Microsoft Office Word 97-2007 - * Binary File Format (.doc) Specification - * - * NOTE: This source is automatically generated please do not modify this file. - * Either subclass or remove the record in src/types/definitions. - * - * @author Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary - * File Format (.doc) Specification - */ -@Internal -public abstract class HRESIAbstractType -{ - - protected byte field_1_hres; - /**/public final static byte HRES_NO = 0; - /**/public final static byte HRES_NORMAL = 1; - /**/public final static byte HRES_ADD_LETTER_BEFORE = 2; - /**/public final static byte HRES_CHANGE_LETTER_BEFORE = 3; - /**/public final static byte HRES_DELETE_LETTER_BEFORE = 4; - /**/public final static byte HRES_CHANGE_LETTER_AFTER = 5; - /**/public final static byte HRES_DELETE_BEFORE_CHANGE_BEFORE = 6; - protected byte field_2_chHres; - - protected HRESIAbstractType() - { - } - - protected void fillFields( byte[] data, int offset ) - { - field_1_hres = data[ 0x0 + offset ]; - field_2_chHres = data[ 0x1 + offset ]; - } - - public void serialize( byte[] data, int offset ) - { - data[ 0x0 + offset] = field_1_hres; - data[ 0x1 + offset] = field_2_chHres; - } - - /** - * Size of record (exluding 4 byte header) - */ - public static int getSize() - { - return 4 + + 1 + 1; - } - - public String toString() - { - StringBuilder builder = new StringBuilder(); - builder.append("[HRESI]\n"); - builder.append(" .hres = "); - builder.append(" (").append(getHres()).append(" )\n"); - builder.append(" .chHres = "); - builder.append(" (").append(getChHres()).append(" )\n"); - - builder.append("[/HRESI]\n"); - return builder.toString(); - } - - /** - * Hyphenation rule. - * - * @return One of - *

  • {@link #HRES_NO} - *
  • {@link #HRES_NORMAL} - *
  • {@link #HRES_ADD_LETTER_BEFORE} - *
  • {@link #HRES_CHANGE_LETTER_BEFORE} - *
  • {@link #HRES_DELETE_LETTER_BEFORE} - *
  • {@link #HRES_CHANGE_LETTER_AFTER} - *
  • {@link #HRES_DELETE_BEFORE_CHANGE_BEFORE} - */ - public byte getHres() - { - return field_1_hres; - } - - /** - * Hyphenation rule. - * - * @param field_1_hres - * One of - *
  • {@link #HRES_NO} - *
  • {@link #HRES_NORMAL} - *
  • {@link #HRES_ADD_LETTER_BEFORE} - *
  • {@link #HRES_CHANGE_LETTER_BEFORE} - *
  • {@link #HRES_DELETE_LETTER_BEFORE} - *
  • {@link #HRES_CHANGE_LETTER_AFTER} - *
  • {@link #HRES_DELETE_BEFORE_CHANGE_BEFORE} - */ - public void setHres( byte field_1_hres ) - { - this.field_1_hres = field_1_hres; - } - - /** - * The character that will be used to add or change a letter when hres is 2, 3, 5 or 6. - */ - public byte getChHres() - { - return field_2_chHres; - } - - /** - * The character that will be used to add or change a letter when hres is 2, 3, 5 or 6. - */ - public void setChHres( byte field_2_chHres ) - { - this.field_2_chHres = field_2_chHres; - } - -} // END OF CLASS diff --git a/src/scratchpad/src/org/apache/poi/hwpf/model/types/LFOAbstractType.java b/src/scratchpad/src/org/apache/poi/hwpf/model/types/LFOAbstractType.java deleted file mode 100644 index 879bfe0be..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/model/types/LFOAbstractType.java +++ /dev/null @@ -1,290 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hwpf.model.types; - -import org.apache.poi.hwpf.model.Grfhic; -import org.apache.poi.util.Internal; -import org.apache.poi.util.LittleEndian; - -/** - * List Format Override (LFO).

    Class and fields descriptions are quoted from - [MS-DOC] --v20110315; Word (.doc) Binary File Format - - *

    - * NOTE: This source is automatically generated please do not modify this file. Either subclass or - * remove the record in src/types/definitions. - *

    - * This class is internal. It content or properties may change without notice - * due to changes in our knowledge of internal Microsoft Word binary structures. - - * @author Sergey Vladimirov; according to [MS-DOC] --v20110315; Word (.doc) Binary File Format; - Copyright (c) Microsoft Corporation - - */ -@Internal -public abstract class LFOAbstractType -{ - - protected int field_1_lsid; - protected int field_2_unused1; - protected int field_3_unused2; - protected byte field_4_clfolvl; - protected byte field_5_ibstFltAutoNum; - protected Grfhic field_6_grfhic; - protected byte field_7_unused3; - - protected LFOAbstractType() - { - this.field_6_grfhic = new Grfhic(); - } - - protected void fillFields( byte[] data, int offset ) - { - field_1_lsid = LittleEndian.getInt( data, 0x0 + offset ); - field_2_unused1 = LittleEndian.getInt( data, 0x4 + offset ); - field_3_unused2 = LittleEndian.getInt( data, 0x8 + offset ); - field_4_clfolvl = data[ 0xc + offset ]; - field_5_ibstFltAutoNum = data[ 0xd + offset ]; - field_6_grfhic = new Grfhic( data, 0xe + offset ); - field_7_unused3 = data[ 0xf + offset ]; - } - - public void serialize( byte[] data, int offset ) - { - LittleEndian.putInt( data, 0x0 + offset, field_1_lsid ); - LittleEndian.putInt( data, 0x4 + offset, field_2_unused1 ); - LittleEndian.putInt( data, 0x8 + offset, field_3_unused2 ); - data[ 0xc + offset ] = field_4_clfolvl; - data[ 0xd + offset ] = field_5_ibstFltAutoNum; - field_6_grfhic.serialize( data, 0xe + offset ); - data[ 0xf + offset ] = field_7_unused3; - } - - public byte[] serialize() - { - final byte[] result = new byte[ getSize() ]; - serialize( result, 0 ); - return result; - } - - /** - * Size of record - */ - public static int getSize() - { - return 0 + 4 + 4 + 4 + 1 + 1 + 1 + 1; - } - - @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - return true; - if ( obj == null ) - return false; - if ( getClass() != obj.getClass() ) - return false; - LFOAbstractType other = (LFOAbstractType) obj; - if ( field_1_lsid != other.field_1_lsid ) - return false; - if ( field_2_unused1 != other.field_2_unused1 ) - return false; - if ( field_3_unused2 != other.field_3_unused2 ) - return false; - if ( field_4_clfolvl != other.field_4_clfolvl ) - return false; - if ( field_5_ibstFltAutoNum != other.field_5_ibstFltAutoNum ) - return false; - if ( field_6_grfhic == null ) - { - if ( other.field_6_grfhic != null ) - return false; - } - else if ( !field_6_grfhic.equals( other.field_6_grfhic ) ) - return false; - if ( field_7_unused3 != other.field_7_unused3 ) - return false; - return true; - } - - @Override - public int hashCode() - { - final int prime = 31; - int result = 1; - result = prime * result + field_1_lsid; - result = prime * result + field_2_unused1; - result = prime * result + field_3_unused2; - result = prime * result + field_4_clfolvl; - result = prime * result + field_5_ibstFltAutoNum; - result = prime * result - + ((field_6_grfhic == null) ? 0 : field_6_grfhic.hashCode()); - result = prime * result + field_7_unused3; - return result; - } - - public String toString() - { - StringBuilder builder = new StringBuilder(); - - builder.append("[LFO]\n"); - builder.append( " .lsid = " ); - builder.append(" ( ").append( field_1_lsid ).append( " )\n" ); - builder.append( " .unused1 = " ); - builder.append(" ( ").append( field_2_unused1 ).append( " )\n" ); - builder.append( " .unused2 = " ); - builder.append(" ( ").append( field_3_unused2 ).append( " )\n" ); - builder.append( " .clfolvl = " ); - builder.append(" ( ").append( field_4_clfolvl ).append( " )\n" ); - builder.append( " .ibstFltAutoNum = " ); - builder.append(" ( ").append( field_5_ibstFltAutoNum ).append( " )\n" ); - builder.append( " .grfhic = " ); - builder.append(" ( ").append( field_6_grfhic == null ? "null" : field_6_grfhic.toString().replaceAll( "\n", "\n " ) ).append( " )\n" ); - builder.append( " .unused3 = " ); - builder.append(" ( ").append( field_7_unused3 ).append( " )\n" ); - - builder.append("[/LFO]"); - return builder.toString(); - } - - /** - * A signed integer that specifies the list identifier of an LSTF. This LFO corresponds to the LSTF in PlfLst.rgLstf that has an lsid whose value is equal to this value.. - */ - @Internal - public int getLsid() - { - return field_1_lsid; - } - - /** - * A signed integer that specifies the list identifier of an LSTF. This LFO corresponds to the LSTF in PlfLst.rgLstf that has an lsid whose value is equal to this value.. - */ - @Internal - public void setLsid( int field_1_lsid ) - { - this.field_1_lsid = field_1_lsid; - } - - /** - * This field MUST be ignored. - */ - @Internal - public int getUnused1() - { - return field_2_unused1; - } - - /** - * This field MUST be ignored. - */ - @Internal - public void setUnused1( int field_2_unused1 ) - { - this.field_2_unused1 = field_2_unused1; - } - - /** - * This field MUST be ignored. - */ - @Internal - public int getUnused2() - { - return field_3_unused2; - } - - /** - * This field MUST be ignored. - */ - @Internal - public void setUnused2( int field_3_unused2 ) - { - this.field_3_unused2 = field_3_unused2; - } - - /** - * An unsigned integer that specifies the field that this LFO represents.. - */ - @Internal - public byte getClfolvl() - { - return field_4_clfolvl; - } - - /** - * An unsigned integer that specifies the field that this LFO represents.. - */ - @Internal - public void setClfolvl( byte field_4_clfolvl ) - { - this.field_4_clfolvl = field_4_clfolvl; - } - - /** - * Used for AUTONUM field emulation. - */ - @Internal - public byte getIbstFltAutoNum() - { - return field_5_ibstFltAutoNum; - } - - /** - * Used for AUTONUM field emulation. - */ - @Internal - public void setIbstFltAutoNum( byte field_5_ibstFltAutoNum ) - { - this.field_5_ibstFltAutoNum = field_5_ibstFltAutoNum; - } - - /** - * HTML compatibility flags. - */ - @Internal - public Grfhic getGrfhic() - { - return field_6_grfhic; - } - - /** - * HTML compatibility flags. - */ - @Internal - public void setGrfhic( Grfhic field_6_grfhic ) - { - this.field_6_grfhic = field_6_grfhic; - } - - /** - * This field MUST be ignored. - */ - @Internal - public byte getUnused3() - { - return field_7_unused3; - } - - /** - * This field MUST be ignored. - */ - @Internal - public void setUnused3( byte field_7_unused3 ) - { - this.field_7_unused3 = field_7_unused3; - } - -} // END OF CLASS diff --git a/src/scratchpad/src/org/apache/poi/hwpf/model/types/LFOLVLBaseAbstractType.java b/src/scratchpad/src/org/apache/poi/hwpf/model/types/LFOLVLBaseAbstractType.java deleted file mode 100644 index 6826b3d05..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/model/types/LFOLVLBaseAbstractType.java +++ /dev/null @@ -1,290 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hwpf.model.types; - -import org.apache.poi.util.BitField; -import org.apache.poi.util.Internal; -import org.apache.poi.util.LittleEndian; - -/** - * The LFOLVL structure contains information that is used to override the formatting - information of a corresponding LVL.

    Class and fields descriptions are quoted from - Microsoft Office Word 97-2007 Binary File Format and [MS-DOC] - v20110608 Word (.doc) Binary - File Format - - *

    - * NOTE: This source is automatically generated please do not modify this file. Either subclass or - * remove the record in src/types/definitions. - *

    - * This class is internal. It content or properties may change without notice - * due to changes in our knowledge of internal Microsoft Word binary structures. - - * @author Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary File Format - Specification [*.doc] and [MS-DOC] - v20110608 Word (.doc) Binary File Format - - */ -@Internal -public abstract class LFOLVLBaseAbstractType -{ - - protected int field_1_iStartAt; - protected int field_2_flags; - /**/private static final BitField iLvl = new BitField(0x0000000F); - /**/private static final BitField fStartAt = new BitField(0x00000010); - /**/private static final BitField fFormatting = new BitField(0x00000020); - /**/private static final BitField grfhic = new BitField(0x00003FC0); - /**/private static final BitField unused1 = new BitField(0x1FFFC000); - /**/private static final BitField unused2 = new BitField(0xE0000000); - - protected LFOLVLBaseAbstractType() - { - } - - protected void fillFields( byte[] data, int offset ) - { - field_1_iStartAt = LittleEndian.getInt( data, 0x0 + offset ); - field_2_flags = LittleEndian.getInt( data, 0x4 + offset ); - } - - public void serialize( byte[] data, int offset ) - { - LittleEndian.putInt( data, 0x0 + offset, field_1_iStartAt ); - LittleEndian.putInt( data, 0x4 + offset, field_2_flags ); - } - - public byte[] serialize() - { - final byte[] result = new byte[ getSize() ]; - serialize( result, 0 ); - return result; - } - - /** - * Size of record - */ - public static int getSize() - { - return 0 + 4 + 4; - } - - @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - return true; - if ( obj == null ) - return false; - if ( getClass() != obj.getClass() ) - return false; - LFOLVLBaseAbstractType other = (LFOLVLBaseAbstractType) obj; - if ( field_1_iStartAt != other.field_1_iStartAt ) - return false; - if ( field_2_flags != other.field_2_flags ) - return false; - return true; - } - - @Override - public int hashCode() - { - final int prime = 31; - int result = 1; - result = prime * result + field_1_iStartAt; - result = prime * result + field_2_flags; - return result; - } - - public String toString() - { - StringBuilder builder = new StringBuilder(); - builder.append("[LFOLVLBase]\n"); - builder.append(" .iStartAt = "); - builder.append(" (").append(getIStartAt()).append(" )\n"); - builder.append(" .flags = "); - builder.append(" (").append(getFlags()).append(" )\n"); - builder.append(" .iLvl = ").append(getILvl()).append('\n'); - builder.append(" .fStartAt = ").append(isFStartAt()).append('\n'); - builder.append(" .fFormatting = ").append(isFFormatting()).append('\n'); - builder.append(" .grfhic = ").append(getGrfhic()).append('\n'); - builder.append(" .unused1 = ").append(getUnused1()).append('\n'); - builder.append(" .unused2 = ").append(getUnused2()).append('\n'); - - builder.append("[/LFOLVLBase]\n"); - return builder.toString(); - } - - /** - * If fStartAt is set to 0x1, this is a signed integer that specifies the start-at value that overrides lvlf.iStartAt of the corresponding LVL. This value MUST be less than or equal to 0x7FFF and MUST be greater than or equal to zero. If both fStartAt and fFormatting are set to 0x1, or if fStartAt is set to 0x0, this value is undefined and MUST be ignored. - */ - @Internal - public int getIStartAt() - { - return field_1_iStartAt; - } - - /** - * If fStartAt is set to 0x1, this is a signed integer that specifies the start-at value that overrides lvlf.iStartAt of the corresponding LVL. This value MUST be less than or equal to 0x7FFF and MUST be greater than or equal to zero. If both fStartAt and fFormatting are set to 0x1, or if fStartAt is set to 0x0, this value is undefined and MUST be ignored. - */ - @Internal - public void setIStartAt( int field_1_iStartAt ) - { - this.field_1_iStartAt = field_1_iStartAt; - } - - /** - * Get the flags field for the LFOLVLBase record. - */ - @Internal - public int getFlags() - { - return field_2_flags; - } - - /** - * Set the flags field for the LFOLVLBase record. - */ - @Internal - public void setFlags( int field_2_flags ) - { - this.field_2_flags = field_2_flags; - } - - /** - * Sets the iLvl field value. - * An unsigned integer that specifies the zero-based level of the list that this overrides. This LFOLVL overrides the LVL that specifies the level formatting of this level of the LSTF that is specified by the lsid field of the LFO to which this LFOLVL corresponds. This value MUST be less than or equal to 0x08 - */ - @Internal - public void setILvl( byte value ) - { - field_2_flags = iLvl.setValue(field_2_flags, value); - } - - /** - * An unsigned integer that specifies the zero-based level of the list that this overrides. This LFOLVL overrides the LVL that specifies the level formatting of this level of the LSTF that is specified by the lsid field of the LFO to which this LFOLVL corresponds. This value MUST be less than or equal to 0x08 - * @return the iLvl field value. - */ - @Internal - public byte getILvl() - { - return ( byte )iLvl.getValue(field_2_flags); - } - - /** - * Sets the fStartAt field value. - * A bit that specifies whether this LFOLVL overrides the start-at value of the level. - */ - @Internal - public void setFStartAt( boolean value ) - { - field_2_flags = fStartAt.setBoolean(field_2_flags, value); - } - - /** - * A bit that specifies whether this LFOLVL overrides the start-at value of the level. - * @return the fStartAt field value. - */ - @Internal - public boolean isFStartAt() - { - return fStartAt.isSet(field_2_flags); - } - - /** - * Sets the fFormatting field value. - * A bit that specifies whether lvl is an LVL that overrides the corresponding LVL - */ - @Internal - public void setFFormatting( boolean value ) - { - field_2_flags = fFormatting.setBoolean(field_2_flags, value); - } - - /** - * A bit that specifies whether lvl is an LVL that overrides the corresponding LVL - * @return the fFormatting field value. - */ - @Internal - public boolean isFFormatting() - { - return fFormatting.isSet(field_2_flags); - } - - /** - * Sets the grfhic field value. - * A grfhic that specifies the HTML incompatibilities of the overriding level formatting - */ - @Internal - public void setGrfhic( short value ) - { - field_2_flags = grfhic.setValue(field_2_flags, value); - } - - /** - * A grfhic that specifies the HTML incompatibilities of the overriding level formatting - * @return the grfhic field value. - */ - @Internal - public short getGrfhic() - { - return ( short )grfhic.getValue(field_2_flags); - } - - /** - * Sets the unused1 field value. - * This MUST be ignored - */ - @Internal - public void setUnused1( short value ) - { - field_2_flags = unused1.setValue(field_2_flags, value); - } - - /** - * This MUST be ignored - * @return the unused1 field value. - * @deprecated This field should not be used according to specification - */ - @Internal - @Deprecated - public short getUnused1() - { - return ( short )unused1.getValue(field_2_flags); - } - - /** - * Sets the unused2 field value. - * This MUST be ignored - */ - @Internal - public void setUnused2( byte value ) - { - field_2_flags = unused2.setValue(field_2_flags, value); - } - - /** - * This MUST be ignored - * @return the unused2 field value. - * @deprecated This field should not be used according to specification - */ - @Internal - @Deprecated - public byte getUnused2() - { - return ( byte )unused2.getValue(field_2_flags); - } - -} // END OF CLASS diff --git a/src/scratchpad/src/org/apache/poi/hwpf/model/types/LSTFAbstractType.java b/src/scratchpad/src/org/apache/poi/hwpf/model/types/LSTFAbstractType.java deleted file mode 100644 index 8500073c3..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/model/types/LSTFAbstractType.java +++ /dev/null @@ -1,379 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hwpf.model.types; - -import java.util.Arrays; - -import org.apache.poi.hwpf.model.Grfhic; -import org.apache.poi.util.BitField; -import org.apache.poi.util.Internal; -import org.apache.poi.util.LittleEndian; - -/** - * The LSTF structure contains formatting properties that apply to an entire list. -

    Class and fields descriptions are quoted from Microsoft Office Word 97-2007 Binary - File Format and [MS-DOC] - v20110608 Word (.doc) Binary File Format - - *

    - * NOTE: This source is automatically generated please do not modify this file. Either subclass or - * remove the record in src/types/definitions. - *

    - * This class is internal. It content or properties may change without notice - * due to changes in our knowledge of internal Microsoft Word binary structures. - - * @author Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary File Format - Specification [*.doc] and [MS-DOC] - v20110608 Word (.doc) Binary File Format - - */ -@Internal -public abstract class LSTFAbstractType -{ - - protected int field_1_lsid; - protected int field_2_tplc; - protected short[] field_3_rgistdPara; - protected byte field_4_flags; - /**/private static final BitField fSimpleList = new BitField(0x01); - /**/private static final BitField unused1 = new BitField(0x02); - /**/private static final BitField fAutoNum = new BitField(0x04); - /**/private static final BitField unused2 = new BitField(0x08); - /**/private static final BitField fHybrid = new BitField(0x10); - /**/private static final BitField reserved1 = new BitField(0xE0); - protected Grfhic field_5_grfhic; - - protected LSTFAbstractType() - { - this.field_3_rgistdPara = new short[0]; - this.field_5_grfhic = new Grfhic(); - } - - protected void fillFields( byte[] data, int offset ) - { - field_1_lsid = LittleEndian.getInt( data, 0x0 + offset ); - field_2_tplc = LittleEndian.getInt( data, 0x4 + offset ); - field_3_rgistdPara = LittleEndian.getShortArray( data, 0x8 + offset, 18 ); - field_4_flags = data[ 0x1a + offset ]; - field_5_grfhic = new Grfhic( data, 0x1b + offset ); - } - - public void serialize( byte[] data, int offset ) - { - LittleEndian.putInt( data, 0x0 + offset, field_1_lsid ); - LittleEndian.putInt( data, 0x4 + offset, field_2_tplc ); - LittleEndian.putShortArray( data, 0x8 + offset, field_3_rgistdPara ); - data[ 0x1a + offset ] = field_4_flags; - field_5_grfhic.serialize( data, 0x1b + offset ); - } - - public byte[] serialize() - { - final byte[] result = new byte[ getSize() ]; - serialize( result, 0 ); - return result; - } - - /** - * Size of record - */ - public static int getSize() - { - return 0 + 4 + 4 + 18 + 1 + 1; - } - - @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - return true; - if ( obj == null ) - return false; - if ( getClass() != obj.getClass() ) - return false; - LSTFAbstractType other = (LSTFAbstractType) obj; - if ( field_1_lsid != other.field_1_lsid ) - return false; - if ( field_2_tplc != other.field_2_tplc ) - return false; - if ( !Arrays.equals( field_3_rgistdPara, other.field_3_rgistdPara ) ) - return false; - if ( field_4_flags != other.field_4_flags ) - return false; - if ( field_5_grfhic == null ) - { - if ( other.field_5_grfhic != null ) - return false; - } - else if ( !field_5_grfhic.equals( other.field_5_grfhic ) ) - return false; - return true; - } - - @Override - public int hashCode() - { - final int prime = 31; - int result = 1; - result = prime * result + field_1_lsid; - result = prime * result + field_2_tplc; - result = prime * result + Arrays.hashCode( field_3_rgistdPara ); - result = prime * result + field_4_flags; - result = prime * result + field_5_grfhic.hashCode(); - return result; - } - - public String toString() - { - StringBuilder builder = new StringBuilder(); - builder.append("[LSTF]\n"); - builder.append(" .lsid = "); - builder.append(" (").append(getLsid()).append(" )\n"); - builder.append(" .tplc = "); - builder.append(" (").append(getTplc()).append(" )\n"); - builder.append(" .rgistdPara = "); - builder.append(" (").append(Arrays.toString(getRgistdPara())).append(" )\n"); - builder.append(" .flags = "); - builder.append(" (").append(getFlags()).append(" )\n"); - builder.append(" .fSimpleList = ").append(isFSimpleList()).append('\n'); - builder.append(" .unused1 = ").append(isUnused1()).append('\n'); - builder.append(" .fAutoNum = ").append(isFAutoNum()).append('\n'); - builder.append(" .unused2 = ").append(isUnused2()).append('\n'); - builder.append(" .fHybrid = ").append(isFHybrid()).append('\n'); - builder.append(" .reserved1 = ").append(getReserved1()).append('\n'); - builder.append(" .grfhic = "); - builder.append(" (").append(getGrfhic()).append(" )\n"); - - builder.append("[/LSTF]\n"); - return builder.toString(); - } - - /** - * A signed integer that specifies the list identifier. This MUST be unique for each LSTF. This value MUST not be 0xFFFFFFFF. - */ - @Internal - public int getLsid() - { - return field_1_lsid; - } - - /** - * A signed integer that specifies the list identifier. This MUST be unique for each LSTF. This value MUST not be 0xFFFFFFFF. - */ - @Internal - public void setLsid( int field_1_lsid ) - { - this.field_1_lsid = field_1_lsid; - } - - /** - * A Tplc that specifies a unique identifier for this LSTF that MAY be used for user interface purposes. If fHybrid is nonzero, this MUST be ignored. - */ - @Internal - public int getTplc() - { - return field_2_tplc; - } - - /** - * A Tplc that specifies a unique identifier for this LSTF that MAY be used for user interface purposes. If fHybrid is nonzero, this MUST be ignored. - */ - @Internal - public void setTplc( int field_2_tplc ) - { - this.field_2_tplc = field_2_tplc; - } - - /** - * An array of nine 16-bit signed integers. Each element of rgistdPara specifies the ISTD of the style that is linked to the corresponding level in the list. If no style is linked to a given level, the value of the corresponding element of rgistdPara MUST be 0x0FFF. - */ - @Internal - public short[] getRgistdPara() - { - return field_3_rgistdPara; - } - - /** - * An array of nine 16-bit signed integers. Each element of rgistdPara specifies the ISTD of the style that is linked to the corresponding level in the list. If no style is linked to a given level, the value of the corresponding element of rgistdPara MUST be 0x0FFF. - */ - @Internal - public void setRgistdPara( short[] field_3_rgistdPara ) - { - this.field_3_rgistdPara = field_3_rgistdPara; - } - - /** - * Get the flags field for the LSTF record. - */ - @Internal - public byte getFlags() - { - return field_4_flags; - } - - /** - * Set the flags field for the LSTF record. - */ - @Internal - public void setFlags( byte field_4_flags ) - { - this.field_4_flags = field_4_flags; - } - - /** - * A grfhic that specifies the HTML incompatibilities of the list.. - */ - @Internal - public Grfhic getGrfhic() - { - return field_5_grfhic; - } - - /** - * A grfhic that specifies the HTML incompatibilities of the list.. - */ - @Internal - public void setGrfhic( Grfhic field_5_grfhic ) - { - this.field_5_grfhic = field_5_grfhic; - } - - /** - * Sets the fSimpleList field value. - * A bit that, when set to 0x1, specifies that this LSTF represents a simple (one-level) list that has one corresponding LVL (see the fcPlfLst field of FibRgFcLcb97). Otherwise, this LSTF represents a multi-level list that has nine corresponding LVLs - */ - @Internal - public void setFSimpleList( boolean value ) - { - field_4_flags = (byte)fSimpleList.setBoolean(field_4_flags, value); - } - - /** - * A bit that, when set to 0x1, specifies that this LSTF represents a simple (one-level) list that has one corresponding LVL (see the fcPlfLst field of FibRgFcLcb97). Otherwise, this LSTF represents a multi-level list that has nine corresponding LVLs - * @return the fSimpleList field value. - */ - @Internal - public boolean isFSimpleList() - { - return fSimpleList.isSet(field_4_flags); - } - - /** - * Sets the unused1 field value. - * This bit MUST be ignored - */ - @Internal - public void setUnused1( boolean value ) - { - field_4_flags = (byte)unused1.setBoolean(field_4_flags, value); - } - - /** - * This bit MUST be ignored - * @return the unused1 field value. - * @deprecated This field should not be used according to specification - */ - @Internal - @Deprecated - public boolean isUnused1() - { - return unused1.isSet(field_4_flags); - } - - /** - * Sets the fAutoNum field value. - * A bit that specifies whether the list that this LSTF represents is used for the AUTONUMOUT, AUTONUMLGL, and AUTONUM fields (see AUTONUMOUT, AUTONUMLGL, and AUTONUM in flt) - */ - @Internal - public void setFAutoNum( boolean value ) - { - field_4_flags = (byte)fAutoNum.setBoolean(field_4_flags, value); - } - - /** - * A bit that specifies whether the list that this LSTF represents is used for the AUTONUMOUT, AUTONUMLGL, and AUTONUM fields (see AUTONUMOUT, AUTONUMLGL, and AUTONUM in flt) - * @return the fAutoNum field value. - */ - @Internal - public boolean isFAutoNum() - { - return fAutoNum.isSet(field_4_flags); - } - - /** - * Sets the unused2 field value. - * This bit MUST be ignored - */ - @Internal - public void setUnused2( boolean value ) - { - field_4_flags = (byte)unused2.setBoolean(field_4_flags, value); - } - - /** - * This bit MUST be ignored - * @return the unused2 field value. - * @deprecated This field should not be used according to specification - */ - @Internal - @Deprecated - public boolean isUnused2() - { - return unused2.isSet(field_4_flags); - } - - /** - * Sets the fHybrid field value. - * A bit that specifies whether the list this LSTF defines is a hybrid list - */ - @Internal - public void setFHybrid( boolean value ) - { - field_4_flags = (byte)fHybrid.setBoolean(field_4_flags, value); - } - - /** - * A bit that specifies whether the list this LSTF defines is a hybrid list - * @return the fHybrid field value. - */ - @Internal - public boolean isFHybrid() - { - return fHybrid.isSet(field_4_flags); - } - - /** - * Sets the reserved1 field value. - * This MUST be zero, and MUST be ignored. - */ - @Internal - public void setReserved1( byte value ) - { - field_4_flags = (byte)reserved1.setValue(field_4_flags, value); - } - - /** - * This MUST be zero, and MUST be ignored. - * @return the reserved1 field value. - * @deprecated This field should not be used according to specification - */ - @Internal - @Deprecated - public byte getReserved1() - { - return ( byte )reserved1.getValue(field_4_flags); - } - -} // END OF CLASS diff --git a/src/scratchpad/src/org/apache/poi/hwpf/model/types/LVLFAbstractType.java b/src/scratchpad/src/org/apache/poi/hwpf/model/types/LVLFAbstractType.java deleted file mode 100644 index 785854313..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/model/types/LVLFAbstractType.java +++ /dev/null @@ -1,554 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hwpf.model.types; - - -import java.util.Arrays; - -import org.apache.poi.hwpf.model.Grfhic; -import org.apache.poi.util.BitField; -import org.apache.poi.util.Internal; -import org.apache.poi.util.LittleEndian; - -/** - * The LVLF structure contains formatting properties for an individual level in a - list.

    Class and fields descriptions are quoted from Microsoft Office Word 97-2007 - Binary File Format and [MS-DOC] - v20110608 Word (.doc) Binary File Format - - *

    - * NOTE: This source is automatically generated please do not modify this file. Either subclass or - * remove the record in src/types/definitions. - *

    - * This class is internal. It content or properties may change without notice - * due to changes in our knowledge of internal Microsoft Word binary structures. - - * @author Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary File Format - Specification [*.doc] and [MS-DOC] - v20110608 Word (.doc) Binary File Format - - */ -@Internal -public abstract class LVLFAbstractType -{ - - protected int field_1_iStartAt; - protected byte field_2_nfc; - protected byte field_3_info; - /**/private static final BitField jc = new BitField(0x03); - /**/private static final BitField fLegal = new BitField(0x04); - /**/private static final BitField fNoRestart = new BitField(0x08); - /**/private static final BitField fIndentSav = new BitField(0x10); - /**/private static final BitField fConverted = new BitField(0x20); - /**/private static final BitField unused1 = new BitField(0x40); - /**/private static final BitField fTentative = new BitField(0x80); - protected byte[] field_4_rgbxchNums; - protected byte field_5_ixchFollow; - protected int field_6_dxaIndentSav; - protected int field_7_unused2; - protected short field_8_cbGrpprlChpx; - protected short field_9_cbGrpprlPapx; - protected short field_10_ilvlRestartLim; - protected Grfhic field_11_grfhic; - - protected LVLFAbstractType() - { - this.field_4_rgbxchNums = new byte[9]; - this.field_11_grfhic = new Grfhic(); - } - - protected void fillFields( byte[] data, int offset ) - { - field_1_iStartAt = LittleEndian.getInt( data, 0x0 + offset ); - field_2_nfc = data[ 0x4 + offset ]; - field_3_info = data[ 0x5 + offset ]; - field_4_rgbxchNums = LittleEndian.getByteArray( data, 0x6 + offset,9 ); - field_5_ixchFollow = data[ 0xf + offset ]; - field_6_dxaIndentSav = LittleEndian.getInt( data, 0x10 + offset ); - field_7_unused2 = LittleEndian.getInt( data, 0x14 + offset ); - field_8_cbGrpprlChpx = LittleEndian.getUByte( data, 0x18 + offset ); - field_9_cbGrpprlPapx = LittleEndian.getUByte( data, 0x19 + offset ); - field_10_ilvlRestartLim = LittleEndian.getUByte( data, 0x1a + offset ); - field_11_grfhic = new Grfhic( data, 0x1b + offset ); - } - - public void serialize( byte[] data, int offset ) - { - LittleEndian.putInt( data, 0x0 + offset, field_1_iStartAt ); - data[ 0x4 + offset ] = field_2_nfc; - data[ 0x5 + offset ] = field_3_info; - System.arraycopy( field_4_rgbxchNums, 0, data, 0x6 + offset, field_4_rgbxchNums.length ); - data[ 0xf + offset ] = field_5_ixchFollow; - LittleEndian.putInt( data, 0x10 + offset, field_6_dxaIndentSav ); - LittleEndian.putInt( data, 0x14 + offset, field_7_unused2 ); - LittleEndian.putUByte( data, 0x18 + offset, field_8_cbGrpprlChpx ); - LittleEndian.putUByte( data, 0x19 + offset, field_9_cbGrpprlPapx ); - LittleEndian.putUByte( data, 0x1a + offset, field_10_ilvlRestartLim ); - field_11_grfhic.serialize( data, 0x1b + offset ); - } - - public byte[] serialize() - { - final byte[] result = new byte[ getSize() ]; - serialize( result, 0 ); - return result; - } - - /** - * Size of record - */ - public static int getSize() - { - return 0 + 4 + 1 + 1 + 9 + 1 + 4 + 4 + 1 + 1 + 1 + 1; - } - - @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - return true; - if ( obj == null ) - return false; - if ( getClass() != obj.getClass() ) - return false; - LVLFAbstractType other = (LVLFAbstractType) obj; - if ( field_1_iStartAt != other.field_1_iStartAt ) - return false; - if ( field_2_nfc != other.field_2_nfc ) - return false; - if ( field_3_info != other.field_3_info ) - return false; - if ( !Arrays.equals( field_4_rgbxchNums, other.field_4_rgbxchNums ) ) - return false; - if ( field_5_ixchFollow != other.field_5_ixchFollow ) - return false; - if ( field_6_dxaIndentSav != other.field_6_dxaIndentSav ) - return false; - if ( field_7_unused2 != other.field_7_unused2 ) - return false; - if ( field_8_cbGrpprlChpx != other.field_8_cbGrpprlChpx ) - return false; - if ( field_9_cbGrpprlPapx != other.field_9_cbGrpprlPapx ) - return false; - if ( field_10_ilvlRestartLim != other.field_10_ilvlRestartLim ) - return false; - if ( field_11_grfhic == null ) - { - if ( other.field_11_grfhic != null ) - return false; - } - else if ( !field_11_grfhic.equals( other.field_11_grfhic ) ) - return false; - return true; - } - - @Override - public int hashCode() - { - final int prime = 31; - int result = 1; - result = prime * result + field_1_iStartAt; - result = prime * result + field_2_nfc; - result = prime * result + field_3_info; - result = prime * result + Arrays.hashCode( field_4_rgbxchNums ); - result = prime * result + field_5_ixchFollow; - result = prime * result + field_6_dxaIndentSav; - result = prime * result + field_7_unused2; - result = prime * result + field_8_cbGrpprlChpx; - result = prime * result + field_9_cbGrpprlPapx; - result = prime * result + field_10_ilvlRestartLim; - result = prime * result + field_11_grfhic.hashCode(); - return result; - } - - public String toString() - { - StringBuilder builder = new StringBuilder(); - builder.append("[LVLF]\n"); - builder.append(" .iStartAt = "); - builder.append(" (").append(getIStartAt()).append(" )\n"); - builder.append(" .nfc = "); - builder.append(" (").append(getNfc()).append(" )\n"); - builder.append(" .info = "); - builder.append(" (").append(getInfo()).append(" )\n"); - builder.append(" .jc = ").append(getJc()).append('\n'); - builder.append(" .fLegal = ").append(isFLegal()).append('\n'); - builder.append(" .fNoRestart = ").append(isFNoRestart()).append('\n'); - builder.append(" .fIndentSav = ").append(isFIndentSav()).append('\n'); - builder.append(" .fConverted = ").append(isFConverted()).append('\n'); - builder.append(" .unused1 = ").append(isUnused1()).append('\n'); - builder.append(" .fTentative = ").append(isFTentative()).append('\n'); - builder.append(" .rgbxchNums = "); - builder.append(" (").append(Arrays.toString(getRgbxchNums())).append(" )\n"); - builder.append(" .ixchFollow = "); - builder.append(" (").append(getIxchFollow()).append(" )\n"); - builder.append(" .dxaIndentSav = "); - builder.append(" (").append(getDxaIndentSav()).append(" )\n"); - builder.append(" .unused2 = "); - builder.append(" (").append(getUnused2()).append(" )\n"); - builder.append(" .cbGrpprlChpx = "); - builder.append(" (").append(getCbGrpprlChpx()).append(" )\n"); - builder.append(" .cbGrpprlPapx = "); - builder.append(" (").append(getCbGrpprlPapx()).append(" )\n"); - builder.append(" .ilvlRestartLim = "); - builder.append(" (").append(getIlvlRestartLim()).append(" )\n"); - builder.append(" .grfhic = "); - builder.append(" (").append(getGrfhic()).append(" )\n"); - - builder.append("[/LVLF]\n"); - return builder.toString(); - } - - /** - * A signed integer that specifies the beginning number for the number sequence belonging to this level. This value MUST be less than or equal to 0x7FFF and MUST be greater than or equal to zero. If this level does not have a number sequence (see nfc), this MUST be ignored. - */ - @Internal - public int getIStartAt() - { - return field_1_iStartAt; - } - - /** - * A signed integer that specifies the beginning number for the number sequence belonging to this level. This value MUST be less than or equal to 0x7FFF and MUST be greater than or equal to zero. If this level does not have a number sequence (see nfc), this MUST be ignored. - */ - @Internal - public void setIStartAt( int field_1_iStartAt ) - { - this.field_1_iStartAt = field_1_iStartAt; - } - - /** - * An MSONFC, as specified in [MS-OSHARED] section 2.2.1.3, that specifies the format of the level numbers that replace the placeholders for this level in the xst fields of the LVLs in this list. This value MUST not be equal to 0x08, 0x09, 0x0F, or 0x13. If this is equal to 0xFF or 0x17, this level does not have a number sequence and therefore has no number formatting. If this is equal to 0x17, the level uses bullets. - */ - @Internal - public byte getNfc() - { - return field_2_nfc; - } - - /** - * An MSONFC, as specified in [MS-OSHARED] section 2.2.1.3, that specifies the format of the level numbers that replace the placeholders for this level in the xst fields of the LVLs in this list. This value MUST not be equal to 0x08, 0x09, 0x0F, or 0x13. If this is equal to 0xFF or 0x17, this level does not have a number sequence and therefore has no number formatting. If this is equal to 0x17, the level uses bullets. - */ - @Internal - public void setNfc( byte field_2_nfc ) - { - this.field_2_nfc = field_2_nfc; - } - - /** - * Get the info field for the LVLF record. - */ - @Internal - public byte getInfo() - { - return field_3_info; - } - - /** - * Set the info field for the LVLF record. - */ - @Internal - public void setInfo( byte field_3_info ) - { - this.field_3_info = field_3_info; - } - - /** - * An array of 8-bit integers. Each integer specifies a one-based character offset to a level placeholder in the xst.rgtchar of the LVL that contains this LVLF. This array is zero-terminated, unless it is full. The count of elements in this array, before to the first terminating zero, MUST be less than or equal to the one-based level of the list to which this LVL corresponds. The integers in this array, before the first terminating zero, MUST be in ascending order, and MUST be unique. - */ - @Internal - public byte[] getRgbxchNums() - { - return field_4_rgbxchNums; - } - - /** - * An array of 8-bit integers. Each integer specifies a one-based character offset to a level placeholder in the xst.rgtchar of the LVL that contains this LVLF. This array is zero-terminated, unless it is full. The count of elements in this array, before to the first terminating zero, MUST be less than or equal to the one-based level of the list to which this LVL corresponds. The integers in this array, before the first terminating zero, MUST be in ascending order, and MUST be unique. - */ - @Internal - public void setRgbxchNums( byte[] field_4_rgbxchNums ) - { - this.field_4_rgbxchNums = field_4_rgbxchNums; - } - - /** - * An unsigned integer that specifies the character that follows the number text. - */ - @Internal - public byte getIxchFollow() - { - return field_5_ixchFollow; - } - - /** - * An unsigned integer that specifies the character that follows the number text. - */ - @Internal - public void setIxchFollow( byte field_5_ixchFollow ) - { - this.field_5_ixchFollow = field_5_ixchFollow; - } - - /** - * If fIndentSav is nonzero, this is a signed integer that specifies the size, in twips, of the indent that needs to be removed when the numbering is removed. This MUST be less than or equal to 0x00007BC0 or greater than or equal to 0xFFFF8440. If fIndentSav is zero, this MUST be ignored. - */ - @Internal - public int getDxaIndentSav() - { - return field_6_dxaIndentSav; - } - - /** - * If fIndentSav is nonzero, this is a signed integer that specifies the size, in twips, of the indent that needs to be removed when the numbering is removed. This MUST be less than or equal to 0x00007BC0 or greater than or equal to 0xFFFF8440. If fIndentSav is zero, this MUST be ignored. - */ - @Internal - public void setDxaIndentSav( int field_6_dxaIndentSav ) - { - this.field_6_dxaIndentSav = field_6_dxaIndentSav; - } - - /** - * This field MUST be ignored. - */ - @Internal - public int getUnused2() - { - return field_7_unused2; - } - - /** - * This field MUST be ignored. - */ - @Internal - public void setUnused2( int field_7_unused2 ) - { - this.field_7_unused2 = field_7_unused2; - } - - /** - * An unsigned integer that specifies the size, in bytes, of the grpprlChpx in the LVL that contains this LVLF. - */ - @Internal - public short getCbGrpprlChpx() - { - return field_8_cbGrpprlChpx; - } - - /** - * An unsigned integer that specifies the size, in bytes, of the grpprlChpx in the LVL that contains this LVLF. - */ - @Internal - public void setCbGrpprlChpx( short field_8_cbGrpprlChpx ) - { - this.field_8_cbGrpprlChpx = field_8_cbGrpprlChpx; - } - - /** - * An unsigned integer that specifies the size, in bytes, of the grpprlPapx in the LVL that contains this LVLF. - */ - @Internal - public short getCbGrpprlPapx() - { - return field_9_cbGrpprlPapx; - } - - /** - * An unsigned integer that specifies the size, in bytes, of the grpprlPapx in the LVL that contains this LVLF. - */ - @Internal - public void setCbGrpprlPapx( short field_9_cbGrpprlPapx ) - { - this.field_9_cbGrpprlPapx = field_9_cbGrpprlPapx; - } - - /** - * An unsigned integer that specifies the first (most-significant) zero-based level after which the number sequence of this level does not restart. The number sequence of this level does restart after any level that is more significant than the specified level. This MUST be less than or equal to the zero-based level of the list to which this LVLF corresponds. If fNoRestart is zero, this MUST be ignored. If this level does not have a number sequence (see nfc), this MUST be ignored. - */ - @Internal - public short getIlvlRestartLim() - { - return field_10_ilvlRestartLim; - } - - /** - * An unsigned integer that specifies the first (most-significant) zero-based level after which the number sequence of this level does not restart. The number sequence of this level does restart after any level that is more significant than the specified level. This MUST be less than or equal to the zero-based level of the list to which this LVLF corresponds. If fNoRestart is zero, this MUST be ignored. If this level does not have a number sequence (see nfc), this MUST be ignored. - */ - @Internal - public void setIlvlRestartLim( short field_10_ilvlRestartLim ) - { - this.field_10_ilvlRestartLim = field_10_ilvlRestartLim; - } - - /** - * A grfhic that specifies the HTML incompatibilities of the level.. - */ - @Internal - public Grfhic getGrfhic() - { - return field_11_grfhic; - } - - /** - * A grfhic that specifies the HTML incompatibilities of the level.. - */ - @Internal - public void setGrfhic( Grfhic field_11_grfhic ) - { - this.field_11_grfhic = field_11_grfhic; - } - - /** - * Sets the jc field value. - * An unsigned integer that specifies the justification of this level - */ - @Internal - public void setJc( byte value ) - { - field_3_info = (byte)jc.setValue(field_3_info, value); - } - - /** - * An unsigned integer that specifies the justification of this level - * @return the jc field value. - */ - @Internal - public byte getJc() - { - return ( byte )jc.getValue(field_3_info); - } - - /** - * Sets the fLegal field value. - * A bit that specifies whether this level overrides the nfc of all inherited level numbers. If the original nfc of a level number is msonfcArabicLZ, it is preserved. Otherwise, the nfc of the level number is overridden by msonfcArabic. - */ - @Internal - public void setFLegal( boolean value ) - { - field_3_info = (byte)fLegal.setBoolean(field_3_info, value); - } - - /** - * A bit that specifies whether this level overrides the nfc of all inherited level numbers. If the original nfc of a level number is msonfcArabicLZ, it is preserved. Otherwise, the nfc of the level number is overridden by msonfcArabic. - * @return the fLegal field value. - */ - @Internal - public boolean isFLegal() - { - return fLegal.isSet(field_3_info); - } - - /** - * Sets the fNoRestart field value. - * A bit that specifies whether the number sequence of the level does not restart after a level is encountered that is more significant than the level to which this LVLF corresponds - */ - @Internal - public void setFNoRestart( boolean value ) - { - field_3_info = (byte)fNoRestart.setBoolean(field_3_info, value); - } - - /** - * A bit that specifies whether the number sequence of the level does not restart after a level is encountered that is more significant than the level to which this LVLF corresponds - * @return the fNoRestart field value. - */ - @Internal - public boolean isFNoRestart() - { - return fNoRestart.isSet(field_3_info); - } - - /** - * Sets the fIndentSav field value. - * A bit that specifies whether the level indented the text it was applied to and that the indent needs to be removed when numbering is removed. The indent to be removed is stored in dxaIndentSav - */ - @Internal - public void setFIndentSav( boolean value ) - { - field_3_info = (byte)fIndentSav.setBoolean(field_3_info, value); - } - - /** - * A bit that specifies whether the level indented the text it was applied to and that the indent needs to be removed when numbering is removed. The indent to be removed is stored in dxaIndentSav - * @return the fIndentSav field value. - */ - @Internal - public boolean isFIndentSav() - { - return fIndentSav.isSet(field_3_info); - } - - /** - * Sets the fConverted field value. - * A bit that specifies whether the nfc of this LVLF structure was previously a temporary value used for bidirectional compatibility that was converted into a standard MSONFC - */ - @Internal - public void setFConverted( boolean value ) - { - field_3_info = (byte)fConverted.setBoolean(field_3_info, value); - } - - /** - * A bit that specifies whether the nfc of this LVLF structure was previously a temporary value used for bidirectional compatibility that was converted into a standard MSONFC - * @return the fConverted field value. - */ - @Internal - public boolean isFConverted() - { - return fConverted.isSet(field_3_info); - } - - /** - * Sets the unused1 field value. - * This bit MUST be ignored - */ - @Internal - public void setUnused1( boolean value ) - { - field_3_info = (byte)unused1.setBoolean(field_3_info, value); - } - - /** - * This bit MUST be ignored - * @return the unused1 field value. - * @deprecated This field should not be used according to specification - */ - @Internal - @Deprecated - public boolean isUnused1() - { - return unused1.isSet(field_3_info); - } - - /** - * Sets the fTentative field value. - * A bit that specifies whether the format of the level is tentative - */ - @Internal - public void setFTentative( boolean value ) - { - field_3_info = (byte)fTentative.setBoolean(field_3_info, value); - } - - /** - * A bit that specifies whether the format of the level is tentative - * @return the fTentative field value. - */ - @Internal - public boolean isFTentative() - { - return fTentative.isSet(field_3_info); - } - -} // END OF CLASS diff --git a/src/scratchpad/src/org/apache/poi/hwpf/model/types/PAPAbstractType.java b/src/scratchpad/src/org/apache/poi/hwpf/model/types/PAPAbstractType.java deleted file mode 100644 index 1363a837a..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/model/types/PAPAbstractType.java +++ /dev/null @@ -1,1911 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.model.types; - - -import java.util.Arrays; - -import org.apache.poi.hwpf.model.TabDescriptor; -import org.apache.poi.hwpf.usermodel.BorderCode; -import org.apache.poi.hwpf.usermodel.DateAndTime; -import org.apache.poi.hwpf.usermodel.DropCapSpecifier; -import org.apache.poi.hwpf.usermodel.LineSpacingDescriptor; -import org.apache.poi.hwpf.usermodel.ShadingDescriptor; -import org.apache.poi.util.BitField; -import org.apache.poi.util.Internal; - -/** - * Paragraph Properties. - *

    - * NOTE: This source is automatically generated please do not modify this file. Either subclass or - * remove the record in src/types/definitions. - *

    - * This class is internal. It content or properties may change without notice - * due to changes in our knowledge of internal Microsoft Word binary structures. - - * @author S. Ryan Ackley - */ -@Internal -public abstract class PAPAbstractType -{ - - protected int field_1_istd; - protected boolean field_2_fSideBySide; - protected boolean field_3_fKeep; - protected boolean field_4_fKeepFollow; - protected boolean field_5_fPageBreakBefore; - protected byte field_6_brcl; - /**/protected final static byte BRCL_SINGLE = 0; - /**/protected final static byte BRCL_THICK = 1; - /**/protected final static byte BRCL_DOUBLE = 2; - /**/protected final static byte BRCL_SHADOW = 3; - protected byte field_7_brcp; - /**/protected final static byte BRCP_NONE = 0; - /**/protected final static byte BRCP_BORDER_ABOVE = 1; - /**/protected final static byte BRCP_BORDER_BELOW = 2; - /**/protected final static byte BRCP_BOX_AROUND = 15; - /**/protected final static byte BRCP_BAR_TO_LEFT_OF_PARAGRAPH = 16; - protected byte field_8_ilvl; - protected int field_9_ilfo; - protected boolean field_10_fNoLnn; - protected LineSpacingDescriptor field_11_lspd; - protected int field_12_dyaBefore; - protected int field_13_dyaAfter; - protected boolean field_14_fInTable; - protected boolean field_15_finTableW97; - protected boolean field_16_fTtp; - protected int field_17_dxaAbs; - protected int field_18_dyaAbs; - protected int field_19_dxaWidth; - protected boolean field_20_fBrLnAbove; - protected boolean field_21_fBrLnBelow; - protected byte field_22_pcVert; - protected byte field_23_pcHorz; - protected byte field_24_wr; - protected boolean field_25_fNoAutoHyph; - protected int field_26_dyaHeight; - protected boolean field_27_fMinHeight; - /**/protected final static boolean FMINHEIGHT_EXACT = false; - /**/protected final static boolean FMINHEIGHT_AT_LEAST = true; - protected DropCapSpecifier field_28_dcs; - protected int field_29_dyaFromText; - protected int field_30_dxaFromText; - protected boolean field_31_fLocked; - protected boolean field_32_fWidowControl; - protected boolean field_33_fKinsoku; - protected boolean field_34_fWordWrap; - protected boolean field_35_fOverflowPunct; - protected boolean field_36_fTopLinePunct; - protected boolean field_37_fAutoSpaceDE; - protected boolean field_38_fAutoSpaceDN; - protected int field_39_wAlignFont; - /**/protected final static byte WALIGNFONT_HANGING = 0; - /**/protected final static byte WALIGNFONT_CENTERED = 1; - /**/protected final static byte WALIGNFONT_ROMAN = 2; - /**/protected final static byte WALIGNFONT_VARIABLE = 3; - /**/protected final static byte WALIGNFONT_AUTO = 4; - protected short field_40_fontAlign; - /**/private static BitField fVertical = new BitField(0x0001); - /**/private static BitField fBackward = new BitField(0x0002); - /**/private static BitField fRotateFont = new BitField(0x0004); - protected byte field_41_lvl; - protected boolean field_42_fBiDi; - protected boolean field_43_fNumRMIns; - protected boolean field_44_fCrLf; - protected boolean field_45_fUsePgsuSettings; - protected boolean field_46_fAdjustRight; - protected int field_47_itap; - protected boolean field_48_fInnerTableCell; - protected boolean field_49_fOpenTch; - protected boolean field_50_fTtpEmbedded; - protected short field_51_dxcRight; - protected short field_52_dxcLeft; - protected short field_53_dxcLeft1; - protected boolean field_54_fDyaBeforeAuto; - protected boolean field_55_fDyaAfterAuto; - protected int field_56_dxaRight; - protected int field_57_dxaLeft; - protected int field_58_dxaLeft1; - protected byte field_59_jc; - protected BorderCode field_60_brcTop; - protected BorderCode field_61_brcLeft; - protected BorderCode field_62_brcBottom; - protected BorderCode field_63_brcRight; - protected BorderCode field_64_brcBetween; - protected BorderCode field_65_brcBar; - protected ShadingDescriptor field_66_shd; - protected byte[] field_67_anld; - protected byte[] field_68_phe; - protected boolean field_69_fPropRMark; - protected int field_70_ibstPropRMark; - protected DateAndTime field_71_dttmPropRMark; - protected int field_72_itbdMac; - protected int[] field_73_rgdxaTab; - protected TabDescriptor[] field_74_rgtbd; - protected byte[] field_75_numrm; - protected byte[] field_76_ptap; - protected boolean field_77_fNoAllowOverlap; - protected long field_78_ipgp; - protected long field_79_rsid; - - protected PAPAbstractType() - { - this.field_11_lspd = new LineSpacingDescriptor(); - this.field_11_lspd = new LineSpacingDescriptor(); - this.field_28_dcs = new DropCapSpecifier(); - this.field_32_fWidowControl = true; - this.field_41_lvl = 9; - this.field_60_brcTop = new BorderCode(); - this.field_61_brcLeft = new BorderCode(); - this.field_62_brcBottom = new BorderCode(); - this.field_63_brcRight = new BorderCode(); - this.field_64_brcBetween = new BorderCode(); - this.field_65_brcBar = new BorderCode(); - this.field_66_shd = new ShadingDescriptor(); - this.field_67_anld = new byte[0]; - this.field_68_phe = new byte[0]; - this.field_71_dttmPropRMark = new DateAndTime(); - this.field_73_rgdxaTab = new int[0]; - this.field_74_rgtbd = new TabDescriptor[0]; - this.field_75_numrm = new byte[0]; - this.field_76_ptap = new byte[0]; - } - - - public String toString() - { - StringBuilder builder = new StringBuilder(); - builder.append("[PAP]\n"); - builder.append(" .istd = "); - builder.append(" (").append(getIstd()).append(" )\n"); - builder.append(" .fSideBySide = "); - builder.append(" (").append(getFSideBySide()).append(" )\n"); - builder.append(" .fKeep = "); - builder.append(" (").append(getFKeep()).append(" )\n"); - builder.append(" .fKeepFollow = "); - builder.append(" (").append(getFKeepFollow()).append(" )\n"); - builder.append(" .fPageBreakBefore = "); - builder.append(" (").append(getFPageBreakBefore()).append(" )\n"); - builder.append(" .brcl = "); - builder.append(" (").append(getBrcl()).append(" )\n"); - builder.append(" .brcp = "); - builder.append(" (").append(getBrcp()).append(" )\n"); - builder.append(" .ilvl = "); - builder.append(" (").append(getIlvl()).append(" )\n"); - builder.append(" .ilfo = "); - builder.append(" (").append(getIlfo()).append(" )\n"); - builder.append(" .fNoLnn = "); - builder.append(" (").append(getFNoLnn()).append(" )\n"); - builder.append(" .lspd = "); - builder.append(" (").append(getLspd()).append(" )\n"); - builder.append(" .dyaBefore = "); - builder.append(" (").append(getDyaBefore()).append(" )\n"); - builder.append(" .dyaAfter = "); - builder.append(" (").append(getDyaAfter()).append(" )\n"); - builder.append(" .fInTable = "); - builder.append(" (").append(getFInTable()).append(" )\n"); - builder.append(" .finTableW97 = "); - builder.append(" (").append(getFinTableW97()).append(" )\n"); - builder.append(" .fTtp = "); - builder.append(" (").append(getFTtp()).append(" )\n"); - builder.append(" .dxaAbs = "); - builder.append(" (").append(getDxaAbs()).append(" )\n"); - builder.append(" .dyaAbs = "); - builder.append(" (").append(getDyaAbs()).append(" )\n"); - builder.append(" .dxaWidth = "); - builder.append(" (").append(getDxaWidth()).append(" )\n"); - builder.append(" .fBrLnAbove = "); - builder.append(" (").append(getFBrLnAbove()).append(" )\n"); - builder.append(" .fBrLnBelow = "); - builder.append(" (").append(getFBrLnBelow()).append(" )\n"); - builder.append(" .pcVert = "); - builder.append(" (").append(getPcVert()).append(" )\n"); - builder.append(" .pcHorz = "); - builder.append(" (").append(getPcHorz()).append(" )\n"); - builder.append(" .wr = "); - builder.append(" (").append(getWr()).append(" )\n"); - builder.append(" .fNoAutoHyph = "); - builder.append(" (").append(getFNoAutoHyph()).append(" )\n"); - builder.append(" .dyaHeight = "); - builder.append(" (").append(getDyaHeight()).append(" )\n"); - builder.append(" .fMinHeight = "); - builder.append(" (").append(getFMinHeight()).append(" )\n"); - builder.append(" .dcs = "); - builder.append(" (").append(getDcs()).append(" )\n"); - builder.append(" .dyaFromText = "); - builder.append(" (").append(getDyaFromText()).append(" )\n"); - builder.append(" .dxaFromText = "); - builder.append(" (").append(getDxaFromText()).append(" )\n"); - builder.append(" .fLocked = "); - builder.append(" (").append(getFLocked()).append(" )\n"); - builder.append(" .fWidowControl = "); - builder.append(" (").append(getFWidowControl()).append(" )\n"); - builder.append(" .fKinsoku = "); - builder.append(" (").append(getFKinsoku()).append(" )\n"); - builder.append(" .fWordWrap = "); - builder.append(" (").append(getFWordWrap()).append(" )\n"); - builder.append(" .fOverflowPunct = "); - builder.append(" (").append(getFOverflowPunct()).append(" )\n"); - builder.append(" .fTopLinePunct = "); - builder.append(" (").append(getFTopLinePunct()).append(" )\n"); - builder.append(" .fAutoSpaceDE = "); - builder.append(" (").append(getFAutoSpaceDE()).append(" )\n"); - builder.append(" .fAutoSpaceDN = "); - builder.append(" (").append(getFAutoSpaceDN()).append(" )\n"); - builder.append(" .wAlignFont = "); - builder.append(" (").append(getWAlignFont()).append(" )\n"); - builder.append(" .fontAlign = "); - builder.append(" (").append(getFontAlign()).append(" )\n"); - builder.append(" .fVertical = ").append(isFVertical()).append('\n'); - builder.append(" .fBackward = ").append(isFBackward()).append('\n'); - builder.append(" .fRotateFont = ").append(isFRotateFont()).append('\n'); - builder.append(" .lvl = "); - builder.append(" (").append(getLvl()).append(" )\n"); - builder.append(" .fBiDi = "); - builder.append(" (").append(getFBiDi()).append(" )\n"); - builder.append(" .fNumRMIns = "); - builder.append(" (").append(getFNumRMIns()).append(" )\n"); - builder.append(" .fCrLf = "); - builder.append(" (").append(getFCrLf()).append(" )\n"); - builder.append(" .fUsePgsuSettings = "); - builder.append(" (").append(getFUsePgsuSettings()).append(" )\n"); - builder.append(" .fAdjustRight = "); - builder.append(" (").append(getFAdjustRight()).append(" )\n"); - builder.append(" .itap = "); - builder.append(" (").append(getItap()).append(" )\n"); - builder.append(" .fInnerTableCell = "); - builder.append(" (").append(getFInnerTableCell()).append(" )\n"); - builder.append(" .fOpenTch = "); - builder.append(" (").append(getFOpenTch()).append(" )\n"); - builder.append(" .fTtpEmbedded = "); - builder.append(" (").append(getFTtpEmbedded()).append(" )\n"); - builder.append(" .dxcRight = "); - builder.append(" (").append(getDxcRight()).append(" )\n"); - builder.append(" .dxcLeft = "); - builder.append(" (").append(getDxcLeft()).append(" )\n"); - builder.append(" .dxcLeft1 = "); - builder.append(" (").append(getDxcLeft1()).append(" )\n"); - builder.append(" .fDyaBeforeAuto = "); - builder.append(" (").append(getFDyaBeforeAuto()).append(" )\n"); - builder.append(" .fDyaAfterAuto = "); - builder.append(" (").append(getFDyaAfterAuto()).append(" )\n"); - builder.append(" .dxaRight = "); - builder.append(" (").append(getDxaRight()).append(" )\n"); - builder.append(" .dxaLeft = "); - builder.append(" (").append(getDxaLeft()).append(" )\n"); - builder.append(" .dxaLeft1 = "); - builder.append(" (").append(getDxaLeft1()).append(" )\n"); - builder.append(" .jc = "); - builder.append(" (").append(getJc()).append(" )\n"); - builder.append(" .brcTop = "); - builder.append(" (").append(getBrcTop()).append(" )\n"); - builder.append(" .brcLeft = "); - builder.append(" (").append(getBrcLeft()).append(" )\n"); - builder.append(" .brcBottom = "); - builder.append(" (").append(getBrcBottom()).append(" )\n"); - builder.append(" .brcRight = "); - builder.append(" (").append(getBrcRight()).append(" )\n"); - builder.append(" .brcBetween = "); - builder.append(" (").append(getBrcBetween()).append(" )\n"); - builder.append(" .brcBar = "); - builder.append(" (").append(getBrcBar()).append(" )\n"); - builder.append(" .shd = "); - builder.append(" (").append(getShd()).append(" )\n"); - builder.append(" .anld = "); - builder.append(" (").append(Arrays.toString(getAnld())).append(" )\n"); - builder.append(" .phe = "); - builder.append(" (").append(Arrays.toString(getPhe())).append(" )\n"); - builder.append(" .fPropRMark = "); - builder.append(" (").append(getFPropRMark()).append(" )\n"); - builder.append(" .ibstPropRMark = "); - builder.append(" (").append(getIbstPropRMark()).append(" )\n"); - builder.append(" .dttmPropRMark = "); - builder.append(" (").append(getDttmPropRMark()).append(" )\n"); - builder.append(" .itbdMac = "); - builder.append(" (").append(getItbdMac()).append(" )\n"); - builder.append(" .rgdxaTab = "); - builder.append(" (").append(Arrays.toString(getRgdxaTab())).append(" )\n"); - builder.append(" .rgtbd = "); - builder.append(" (").append(Arrays.toString(getRgtbd())).append(" )\n"); - builder.append(" .numrm = "); - builder.append(" (").append(Arrays.toString(getNumrm())).append(" )\n"); - builder.append(" .ptap = "); - builder.append(" (").append(Arrays.toString(getPtap())).append(" )\n"); - builder.append(" .fNoAllowOverlap = "); - builder.append(" (").append(getFNoAllowOverlap()).append(" )\n"); - builder.append(" .ipgp = "); - builder.append(" (").append(getIpgp()).append(" )\n"); - builder.append(" .rsid = "); - builder.append(" (").append(getRsid()).append(" )\n"); - - builder.append("[/PAP]\n"); - return builder.toString(); - } - - /** - * Index to style descriptor. - */ - @Internal - public int getIstd() - { - return field_1_istd; - } - - /** - * Index to style descriptor. - */ - @Internal - public void setIstd( int field_1_istd ) - { - this.field_1_istd = field_1_istd; - } - - /** - * Get the fSideBySide field for the PAP record. - */ - @Internal - public boolean getFSideBySide() - { - return field_2_fSideBySide; - } - - /** - * Set the fSideBySide field for the PAP record. - */ - @Internal - public void setFSideBySide( boolean field_2_fSideBySide ) - { - this.field_2_fSideBySide = field_2_fSideBySide; - } - - /** - * Get the fKeep field for the PAP record. - */ - @Internal - public boolean getFKeep() - { - return field_3_fKeep; - } - - /** - * Set the fKeep field for the PAP record. - */ - @Internal - public void setFKeep( boolean field_3_fKeep ) - { - this.field_3_fKeep = field_3_fKeep; - } - - /** - * Get the fKeepFollow field for the PAP record. - */ - @Internal - public boolean getFKeepFollow() - { - return field_4_fKeepFollow; - } - - /** - * Set the fKeepFollow field for the PAP record. - */ - @Internal - public void setFKeepFollow( boolean field_4_fKeepFollow ) - { - this.field_4_fKeepFollow = field_4_fKeepFollow; - } - - /** - * Get the fPageBreakBefore field for the PAP record. - */ - @Internal - public boolean getFPageBreakBefore() - { - return field_5_fPageBreakBefore; - } - - /** - * Set the fPageBreakBefore field for the PAP record. - */ - @Internal - public void setFPageBreakBefore( boolean field_5_fPageBreakBefore ) - { - this.field_5_fPageBreakBefore = field_5_fPageBreakBefore; - } - - /** - * Border line style. - * - * @return One of - *

  • {@link #BRCL_SINGLE} - *
  • {@link #BRCL_THICK} - *
  • {@link #BRCL_DOUBLE} - *
  • {@link #BRCL_SHADOW} - */ - @Internal - public byte getBrcl() - { - return field_6_brcl; - } - - /** - * Border line style. - * - * @param field_6_brcl - * One of - *
  • {@link #BRCL_SINGLE} - *
  • {@link #BRCL_THICK} - *
  • {@link #BRCL_DOUBLE} - *
  • {@link #BRCL_SHADOW} - */ - @Internal - public void setBrcl( byte field_6_brcl ) - { - this.field_6_brcl = field_6_brcl; - } - - /** - * Rectangle border codes. - * - * @return One of - *
  • {@link #BRCP_NONE} - *
  • {@link #BRCP_BORDER_ABOVE} - *
  • {@link #BRCP_BORDER_BELOW} - *
  • {@link #BRCP_BOX_AROUND} - *
  • {@link #BRCP_BAR_TO_LEFT_OF_PARAGRAPH} - */ - @Internal - public byte getBrcp() - { - return field_7_brcp; - } - - /** - * Rectangle border codes. - * - * @param field_7_brcp - * One of - *
  • {@link #BRCP_NONE} - *
  • {@link #BRCP_BORDER_ABOVE} - *
  • {@link #BRCP_BORDER_BELOW} - *
  • {@link #BRCP_BOX_AROUND} - *
  • {@link #BRCP_BAR_TO_LEFT_OF_PARAGRAPH} - */ - @Internal - public void setBrcp( byte field_7_brcp ) - { - this.field_7_brcp = field_7_brcp; - } - - /** - * List level if non-zero. - */ - @Internal - public byte getIlvl() - { - return field_8_ilvl; - } - - /** - * List level if non-zero. - */ - @Internal - public void setIlvl( byte field_8_ilvl ) - { - this.field_8_ilvl = field_8_ilvl; - } - - /** - * "A 16-bit signed integer value that is used to determine which list - * contains the paragraph. This value MUST be one of the following: - * - * 0x0000 -- This paragraph is not in a list, and any list formatting on the - * paragraph is removed. - * - * 0x0001 - 0x07FE -- The value is a 1-based index into PlfLfo.rgLfo. The - * LFO at this index defines the list that this paragraph is in. - * - * 0xF801 -- This paragraph is not in a list. - * - * 0xF802 - 0xFFFF -- The value is the negation of a 1-based index into - * PlfLfo.rgLfo. The LFO at this index defines the list that this paragraph - * is in. The logical left indentation (see sprmPDxaLeft) and the logical - * left first line indentation (see sprmPDxaLeft1) of the paragraph MUST be - * preserved despite any list formatting. - * - * By default, a paragraph is not in a list." - * - * Quote from [MS-DOC] -- v20110315, page 125 - */ - @Internal - public int getIlfo() - { - return field_9_ilfo; - } - - /** - * "A 16-bit signed integer value that is used to determine which list - * contains the paragraph. This value MUST be one of the following: - * - * 0x0000 -- This paragraph is not in a list, and any list formatting on the - * paragraph is removed. - * - * 0x0001 - 0x07FE -- The value is a 1-based index into PlfLfo.rgLfo. The - * LFO at this index defines the list that this paragraph is in. - * - * 0xF801 -- This paragraph is not in a list. - * - * 0xF802 - 0xFFFF -- The value is the negation of a 1-based index into - * PlfLfo.rgLfo. The LFO at this index defines the list that this paragraph - * is in. The logical left indentation (see sprmPDxaLeft) and the logical - * left first line indentation (see sprmPDxaLeft1) of the paragraph MUST be - * preserved despite any list formatting. By default, a paragraph is not in - * a list." - * - * Quote from [MS-DOC] -- v20110315, page 125 - */ - @Internal - public void setIlfo( int field_9_ilfo ) - { - this.field_9_ilfo = field_9_ilfo; - } - - /** - * No line numbering. - */ - @Internal - public boolean getFNoLnn() - { - return field_10_fNoLnn; - } - - /** - * No line numbering. - */ - @Internal - public void setFNoLnn( boolean field_10_fNoLnn ) - { - this.field_10_fNoLnn = field_10_fNoLnn; - } - - /** - * Line spacing descriptor. - */ - @Internal - public LineSpacingDescriptor getLspd() - { - return field_11_lspd; - } - - /** - * Line spacing descriptor. - */ - @Internal - public void setLspd( LineSpacingDescriptor field_11_lspd ) - { - this.field_11_lspd = field_11_lspd; - } - - /** - * Space before paragraph. - */ - @Internal - public int getDyaBefore() - { - return field_12_dyaBefore; - } - - /** - * Space before paragraph. - */ - @Internal - public void setDyaBefore( int field_12_dyaBefore ) - { - this.field_12_dyaBefore = field_12_dyaBefore; - } - - /** - * Space after paragraph. - */ - @Internal - public int getDyaAfter() - { - return field_13_dyaAfter; - } - - /** - * Space after paragraph. - */ - @Internal - public void setDyaAfter( int field_13_dyaAfter ) - { - this.field_13_dyaAfter = field_13_dyaAfter; - } - - /** - * Paragraph is in table flag. - */ - @Internal - public boolean getFInTable() - { - return field_14_fInTable; - } - - /** - * Paragraph is in table flag. - */ - @Internal - public void setFInTable( boolean field_14_fInTable ) - { - this.field_14_fInTable = field_14_fInTable; - } - - /** - * Archaic paragraph is in table flag. - */ - @Internal - public boolean getFinTableW97() - { - return field_15_finTableW97; - } - - /** - * Archaic paragraph is in table flag. - */ - @Internal - public void setFinTableW97( boolean field_15_finTableW97 ) - { - this.field_15_finTableW97 = field_15_finTableW97; - } - - /** - * Table trailer paragraph (last in table row). - */ - @Internal - public boolean getFTtp() - { - return field_16_fTtp; - } - - /** - * Table trailer paragraph (last in table row). - */ - @Internal - public void setFTtp( boolean field_16_fTtp ) - { - this.field_16_fTtp = field_16_fTtp; - } - - /** - * Get the dxaAbs field for the PAP record. - */ - @Internal - public int getDxaAbs() - { - return field_17_dxaAbs; - } - - /** - * Set the dxaAbs field for the PAP record. - */ - @Internal - public void setDxaAbs( int field_17_dxaAbs ) - { - this.field_17_dxaAbs = field_17_dxaAbs; - } - - /** - * Get the dyaAbs field for the PAP record. - */ - @Internal - public int getDyaAbs() - { - return field_18_dyaAbs; - } - - /** - * Set the dyaAbs field for the PAP record. - */ - @Internal - public void setDyaAbs( int field_18_dyaAbs ) - { - this.field_18_dyaAbs = field_18_dyaAbs; - } - - /** - * Get the dxaWidth field for the PAP record. - */ - @Internal - public int getDxaWidth() - { - return field_19_dxaWidth; - } - - /** - * Set the dxaWidth field for the PAP record. - */ - @Internal - public void setDxaWidth( int field_19_dxaWidth ) - { - this.field_19_dxaWidth = field_19_dxaWidth; - } - - /** - * Get the fBrLnAbove field for the PAP record. - */ - @Internal - public boolean getFBrLnAbove() - { - return field_20_fBrLnAbove; - } - - /** - * Set the fBrLnAbove field for the PAP record. - */ - @Internal - public void setFBrLnAbove( boolean field_20_fBrLnAbove ) - { - this.field_20_fBrLnAbove = field_20_fBrLnAbove; - } - - /** - * Get the fBrLnBelow field for the PAP record. - */ - @Internal - public boolean getFBrLnBelow() - { - return field_21_fBrLnBelow; - } - - /** - * Set the fBrLnBelow field for the PAP record. - */ - @Internal - public void setFBrLnBelow( boolean field_21_fBrLnBelow ) - { - this.field_21_fBrLnBelow = field_21_fBrLnBelow; - } - - /** - * Get the pcVert field for the PAP record. - */ - @Internal - public byte getPcVert() - { - return field_22_pcVert; - } - - /** - * Set the pcVert field for the PAP record. - */ - @Internal - public void setPcVert( byte field_22_pcVert ) - { - this.field_22_pcVert = field_22_pcVert; - } - - /** - * Get the pcHorz field for the PAP record. - */ - @Internal - public byte getPcHorz() - { - return field_23_pcHorz; - } - - /** - * Set the pcHorz field for the PAP record. - */ - @Internal - public void setPcHorz( byte field_23_pcHorz ) - { - this.field_23_pcHorz = field_23_pcHorz; - } - - /** - * Get the wr field for the PAP record. - */ - @Internal - public byte getWr() - { - return field_24_wr; - } - - /** - * Set the wr field for the PAP record. - */ - @Internal - public void setWr( byte field_24_wr ) - { - this.field_24_wr = field_24_wr; - } - - /** - * Get the fNoAutoHyph field for the PAP record. - */ - @Internal - public boolean getFNoAutoHyph() - { - return field_25_fNoAutoHyph; - } - - /** - * Set the fNoAutoHyph field for the PAP record. - */ - @Internal - public void setFNoAutoHyph( boolean field_25_fNoAutoHyph ) - { - this.field_25_fNoAutoHyph = field_25_fNoAutoHyph; - } - - /** - * Get the dyaHeight field for the PAP record. - */ - @Internal - public int getDyaHeight() - { - return field_26_dyaHeight; - } - - /** - * Set the dyaHeight field for the PAP record. - */ - @Internal - public void setDyaHeight( int field_26_dyaHeight ) - { - this.field_26_dyaHeight = field_26_dyaHeight; - } - - /** - * Minimum height is exact or auto. - * - * @return One of - *
  • {@link #FMINHEIGHT_EXACT} - *
  • {@link #FMINHEIGHT_AT_LEAST} - */ - @Internal - public boolean getFMinHeight() - { - return field_27_fMinHeight; - } - - /** - * Minimum height is exact or auto. - * - * @param field_27_fMinHeight - * One of - *
  • {@link #FMINHEIGHT_EXACT} - *
  • {@link #FMINHEIGHT_AT_LEAST} - */ - @Internal - public void setFMinHeight( boolean field_27_fMinHeight ) - { - this.field_27_fMinHeight = field_27_fMinHeight; - } - - /** - * Get the dcs field for the PAP record. - */ - @Internal - public DropCapSpecifier getDcs() - { - return field_28_dcs; - } - - /** - * Set the dcs field for the PAP record. - */ - @Internal - public void setDcs( DropCapSpecifier field_28_dcs ) - { - this.field_28_dcs = field_28_dcs; - } - - /** - * Vertical distance between text and absolutely positioned object. - */ - @Internal - public int getDyaFromText() - { - return field_29_dyaFromText; - } - - /** - * Vertical distance between text and absolutely positioned object. - */ - @Internal - public void setDyaFromText( int field_29_dyaFromText ) - { - this.field_29_dyaFromText = field_29_dyaFromText; - } - - /** - * Horizontal distance between text and absolutely positioned object. - */ - @Internal - public int getDxaFromText() - { - return field_30_dxaFromText; - } - - /** - * Horizontal distance between text and absolutely positioned object. - */ - @Internal - public void setDxaFromText( int field_30_dxaFromText ) - { - this.field_30_dxaFromText = field_30_dxaFromText; - } - - /** - * Anchor of an absolutely positioned frame is locked. - */ - @Internal - public boolean getFLocked() - { - return field_31_fLocked; - } - - /** - * Anchor of an absolutely positioned frame is locked. - */ - @Internal - public void setFLocked( boolean field_31_fLocked ) - { - this.field_31_fLocked = field_31_fLocked; - } - - /** - * 1, Word will prevent widowed lines in this paragraph from being placed at the beginning of a page. - */ - @Internal - public boolean getFWidowControl() - { - return field_32_fWidowControl; - } - - /** - * 1, Word will prevent widowed lines in this paragraph from being placed at the beginning of a page. - */ - @Internal - public void setFWidowControl( boolean field_32_fWidowControl ) - { - this.field_32_fWidowControl = field_32_fWidowControl; - } - - /** - * apply Kinsoku rules when performing line wrapping. - */ - @Internal - public boolean getFKinsoku() - { - return field_33_fKinsoku; - } - - /** - * apply Kinsoku rules when performing line wrapping. - */ - @Internal - public void setFKinsoku( boolean field_33_fKinsoku ) - { - this.field_33_fKinsoku = field_33_fKinsoku; - } - - /** - * perform word wrap. - */ - @Internal - public boolean getFWordWrap() - { - return field_34_fWordWrap; - } - - /** - * perform word wrap. - */ - @Internal - public void setFWordWrap( boolean field_34_fWordWrap ) - { - this.field_34_fWordWrap = field_34_fWordWrap; - } - - /** - * apply overflow punctuation rules when performing line wrapping. - */ - @Internal - public boolean getFOverflowPunct() - { - return field_35_fOverflowPunct; - } - - /** - * apply overflow punctuation rules when performing line wrapping. - */ - @Internal - public void setFOverflowPunct( boolean field_35_fOverflowPunct ) - { - this.field_35_fOverflowPunct = field_35_fOverflowPunct; - } - - /** - * perform top line punctuation processing. - */ - @Internal - public boolean getFTopLinePunct() - { - return field_36_fTopLinePunct; - } - - /** - * perform top line punctuation processing. - */ - @Internal - public void setFTopLinePunct( boolean field_36_fTopLinePunct ) - { - this.field_36_fTopLinePunct = field_36_fTopLinePunct; - } - - /** - * auto space East Asian and alphabetic characters. - */ - @Internal - public boolean getFAutoSpaceDE() - { - return field_37_fAutoSpaceDE; - } - - /** - * auto space East Asian and alphabetic characters. - */ - @Internal - public void setFAutoSpaceDE( boolean field_37_fAutoSpaceDE ) - { - this.field_37_fAutoSpaceDE = field_37_fAutoSpaceDE; - } - - /** - * auto space East Asian and numeric characters. - */ - @Internal - public boolean getFAutoSpaceDN() - { - return field_38_fAutoSpaceDN; - } - - /** - * auto space East Asian and numeric characters. - */ - @Internal - public void setFAutoSpaceDN( boolean field_38_fAutoSpaceDN ) - { - this.field_38_fAutoSpaceDN = field_38_fAutoSpaceDN; - } - - /** - * Get the wAlignFont field for the PAP record. - * - * @return One of - *
  • {@link #WALIGNFONT_HANGING} - *
  • {@link #WALIGNFONT_CENTERED} - *
  • {@link #WALIGNFONT_ROMAN} - *
  • {@link #WALIGNFONT_VARIABLE} - *
  • {@link #WALIGNFONT_AUTO} - */ - @Internal - public int getWAlignFont() - { - return field_39_wAlignFont; - } - - /** - * Set the wAlignFont field for the PAP record. - * - * @param field_39_wAlignFont - * One of - *
  • {@link #WALIGNFONT_HANGING} - *
  • {@link #WALIGNFONT_CENTERED} - *
  • {@link #WALIGNFONT_ROMAN} - *
  • {@link #WALIGNFONT_VARIABLE} - *
  • {@link #WALIGNFONT_AUTO} - */ - @Internal - public void setWAlignFont( int field_39_wAlignFont ) - { - this.field_39_wAlignFont = field_39_wAlignFont; - } - - /** - * Used internally by Word. - */ - @Internal - public short getFontAlign() - { - return field_40_fontAlign; - } - - /** - * Used internally by Word. - */ - @Internal - public void setFontAlign( short field_40_fontAlign ) - { - this.field_40_fontAlign = field_40_fontAlign; - } - - /** - * Outline level. - */ - @Internal - public byte getLvl() - { - return field_41_lvl; - } - - /** - * Outline level. - */ - @Internal - public void setLvl( byte field_41_lvl ) - { - this.field_41_lvl = field_41_lvl; - } - - /** - * Get the fBiDi field for the PAP record. - */ - @Internal - public boolean getFBiDi() - { - return field_42_fBiDi; - } - - /** - * Set the fBiDi field for the PAP record. - */ - @Internal - public void setFBiDi( boolean field_42_fBiDi ) - { - this.field_42_fBiDi = field_42_fBiDi; - } - - /** - * Get the fNumRMIns field for the PAP record. - */ - @Internal - public boolean getFNumRMIns() - { - return field_43_fNumRMIns; - } - - /** - * Set the fNumRMIns field for the PAP record. - */ - @Internal - public void setFNumRMIns( boolean field_43_fNumRMIns ) - { - this.field_43_fNumRMIns = field_43_fNumRMIns; - } - - /** - * Get the fCrLf field for the PAP record. - */ - @Internal - public boolean getFCrLf() - { - return field_44_fCrLf; - } - - /** - * Set the fCrLf field for the PAP record. - */ - @Internal - public void setFCrLf( boolean field_44_fCrLf ) - { - this.field_44_fCrLf = field_44_fCrLf; - } - - /** - * Get the fUsePgsuSettings field for the PAP record. - */ - @Internal - public boolean getFUsePgsuSettings() - { - return field_45_fUsePgsuSettings; - } - - /** - * Set the fUsePgsuSettings field for the PAP record. - */ - @Internal - public void setFUsePgsuSettings( boolean field_45_fUsePgsuSettings ) - { - this.field_45_fUsePgsuSettings = field_45_fUsePgsuSettings; - } - - /** - * Get the fAdjustRight field for the PAP record. - */ - @Internal - public boolean getFAdjustRight() - { - return field_46_fAdjustRight; - } - - /** - * Set the fAdjustRight field for the PAP record. - */ - @Internal - public void setFAdjustRight( boolean field_46_fAdjustRight ) - { - this.field_46_fAdjustRight = field_46_fAdjustRight; - } - - /** - * Table nesting level. - */ - @Internal - public int getItap() - { - return field_47_itap; - } - - /** - * Table nesting level. - */ - @Internal - public void setItap( int field_47_itap ) - { - this.field_47_itap = field_47_itap; - } - - /** - * When 1, the end of paragraph mark is really an end of cell mark for a nested table cell. - */ - @Internal - public boolean getFInnerTableCell() - { - return field_48_fInnerTableCell; - } - - /** - * When 1, the end of paragraph mark is really an end of cell mark for a nested table cell. - */ - @Internal - public void setFInnerTableCell( boolean field_48_fInnerTableCell ) - { - this.field_48_fInnerTableCell = field_48_fInnerTableCell; - } - - /** - * Ensure the Table Cell char doesn't show up as zero height. - */ - @Internal - public boolean getFOpenTch() - { - return field_49_fOpenTch; - } - - /** - * Ensure the Table Cell char doesn't show up as zero height. - */ - @Internal - public void setFOpenTch( boolean field_49_fOpenTch ) - { - this.field_49_fOpenTch = field_49_fOpenTch; - } - - /** - * Word 97 compatibility indicates this end of paragraph mark is really an end of row marker for a nested table. - */ - @Internal - public boolean getFTtpEmbedded() - { - return field_50_fTtpEmbedded; - } - - /** - * Word 97 compatibility indicates this end of paragraph mark is really an end of row marker for a nested table. - */ - @Internal - public void setFTtpEmbedded( boolean field_50_fTtpEmbedded ) - { - this.field_50_fTtpEmbedded = field_50_fTtpEmbedded; - } - - /** - * Right indent in character units. - */ - @Internal - public short getDxcRight() - { - return field_51_dxcRight; - } - - /** - * Right indent in character units. - */ - @Internal - public void setDxcRight( short field_51_dxcRight ) - { - this.field_51_dxcRight = field_51_dxcRight; - } - - /** - * Left indent in character units. - */ - @Internal - public short getDxcLeft() - { - return field_52_dxcLeft; - } - - /** - * Left indent in character units. - */ - @Internal - public void setDxcLeft( short field_52_dxcLeft ) - { - this.field_52_dxcLeft = field_52_dxcLeft; - } - - /** - * First line indent in character units. - */ - @Internal - public short getDxcLeft1() - { - return field_53_dxcLeft1; - } - - /** - * First line indent in character units. - */ - @Internal - public void setDxcLeft1( short field_53_dxcLeft1 ) - { - this.field_53_dxcLeft1 = field_53_dxcLeft1; - } - - /** - * Vertical spacing before is automatic. - */ - @Internal - public boolean getFDyaBeforeAuto() - { - return field_54_fDyaBeforeAuto; - } - - /** - * Vertical spacing before is automatic. - */ - @Internal - public void setFDyaBeforeAuto( boolean field_54_fDyaBeforeAuto ) - { - this.field_54_fDyaBeforeAuto = field_54_fDyaBeforeAuto; - } - - /** - * Vertical spacing after is automatic. - */ - @Internal - public boolean getFDyaAfterAuto() - { - return field_55_fDyaAfterAuto; - } - - /** - * Vertical spacing after is automatic. - */ - @Internal - public void setFDyaAfterAuto( boolean field_55_fDyaAfterAuto ) - { - this.field_55_fDyaAfterAuto = field_55_fDyaAfterAuto; - } - - /** - * Get the dxaRight field for the PAP record. - */ - @Internal - public int getDxaRight() - { - return field_56_dxaRight; - } - - /** - * Set the dxaRight field for the PAP record. - */ - @Internal - public void setDxaRight( int field_56_dxaRight ) - { - this.field_56_dxaRight = field_56_dxaRight; - } - - /** - * Get the dxaLeft field for the PAP record. - */ - @Internal - public int getDxaLeft() - { - return field_57_dxaLeft; - } - - /** - * Set the dxaLeft field for the PAP record. - */ - @Internal - public void setDxaLeft( int field_57_dxaLeft ) - { - this.field_57_dxaLeft = field_57_dxaLeft; - } - - /** - * Get the dxaLeft1 field for the PAP record. - */ - @Internal - public int getDxaLeft1() - { - return field_58_dxaLeft1; - } - - /** - * Set the dxaLeft1 field for the PAP record. - */ - @Internal - public void setDxaLeft1( int field_58_dxaLeft1 ) - { - this.field_58_dxaLeft1 = field_58_dxaLeft1; - } - - /** - * Get the jc field for the PAP record. - */ - @Internal - public byte getJc() - { - return field_59_jc; - } - - /** - * Set the jc field for the PAP record. - */ - @Internal - public void setJc( byte field_59_jc ) - { - this.field_59_jc = field_59_jc; - } - - /** - * Get the brcTop field for the PAP record. - */ - @Internal - public BorderCode getBrcTop() - { - return field_60_brcTop; - } - - /** - * Set the brcTop field for the PAP record. - */ - @Internal - public void setBrcTop( BorderCode field_60_brcTop ) - { - this.field_60_brcTop = field_60_brcTop; - } - - /** - * Get the brcLeft field for the PAP record. - */ - @Internal - public BorderCode getBrcLeft() - { - return field_61_brcLeft; - } - - /** - * Set the brcLeft field for the PAP record. - */ - @Internal - public void setBrcLeft( BorderCode field_61_brcLeft ) - { - this.field_61_brcLeft = field_61_brcLeft; - } - - /** - * Get the brcBottom field for the PAP record. - */ - @Internal - public BorderCode getBrcBottom() - { - return field_62_brcBottom; - } - - /** - * Set the brcBottom field for the PAP record. - */ - @Internal - public void setBrcBottom( BorderCode field_62_brcBottom ) - { - this.field_62_brcBottom = field_62_brcBottom; - } - - /** - * Get the brcRight field for the PAP record. - */ - @Internal - public BorderCode getBrcRight() - { - return field_63_brcRight; - } - - /** - * Set the brcRight field for the PAP record. - */ - @Internal - public void setBrcRight( BorderCode field_63_brcRight ) - { - this.field_63_brcRight = field_63_brcRight; - } - - /** - * Get the brcBetween field for the PAP record. - */ - @Internal - public BorderCode getBrcBetween() - { - return field_64_brcBetween; - } - - /** - * Set the brcBetween field for the PAP record. - */ - @Internal - public void setBrcBetween( BorderCode field_64_brcBetween ) - { - this.field_64_brcBetween = field_64_brcBetween; - } - - /** - * Get the brcBar field for the PAP record. - */ - @Internal - public BorderCode getBrcBar() - { - return field_65_brcBar; - } - - /** - * Set the brcBar field for the PAP record. - */ - @Internal - public void setBrcBar( BorderCode field_65_brcBar ) - { - this.field_65_brcBar = field_65_brcBar; - } - - /** - * Get the shd field for the PAP record. - */ - @Internal - public ShadingDescriptor getShd() - { - return field_66_shd; - } - - /** - * Set the shd field for the PAP record. - */ - @Internal - public void setShd( ShadingDescriptor field_66_shd ) - { - this.field_66_shd = field_66_shd; - } - - /** - * Get the anld field for the PAP record. - */ - @Internal - public byte[] getAnld() - { - return field_67_anld; - } - - /** - * Set the anld field for the PAP record. - */ - @Internal - public void setAnld( byte[] field_67_anld ) - { - this.field_67_anld = field_67_anld; - } - - /** - * Get the phe field for the PAP record. - */ - @Internal - public byte[] getPhe() - { - return field_68_phe; - } - - /** - * Set the phe field for the PAP record. - */ - @Internal - public void setPhe( byte[] field_68_phe ) - { - this.field_68_phe = field_68_phe; - } - - /** - * Get the fPropRMark field for the PAP record. - */ - @Internal - public boolean getFPropRMark() - { - return field_69_fPropRMark; - } - - /** - * Set the fPropRMark field for the PAP record. - */ - @Internal - public void setFPropRMark( boolean field_69_fPropRMark ) - { - this.field_69_fPropRMark = field_69_fPropRMark; - } - - /** - * Get the ibstPropRMark field for the PAP record. - */ - @Internal - public int getIbstPropRMark() - { - return field_70_ibstPropRMark; - } - - /** - * Set the ibstPropRMark field for the PAP record. - */ - @Internal - public void setIbstPropRMark( int field_70_ibstPropRMark ) - { - this.field_70_ibstPropRMark = field_70_ibstPropRMark; - } - - /** - * Get the dttmPropRMark field for the PAP record. - */ - @Internal - public DateAndTime getDttmPropRMark() - { - return field_71_dttmPropRMark; - } - - /** - * Set the dttmPropRMark field for the PAP record. - */ - @Internal - public void setDttmPropRMark( DateAndTime field_71_dttmPropRMark ) - { - this.field_71_dttmPropRMark = field_71_dttmPropRMark; - } - - /** - * Number of tabs stops defined for paragraph. Must be >= 0 and <= 64.. - */ - @Internal - public int getItbdMac() - { - return field_72_itbdMac; - } - - /** - * Number of tabs stops defined for paragraph. Must be >= 0 and <= 64.. - */ - @Internal - public void setItbdMac( int field_72_itbdMac ) - { - this.field_72_itbdMac = field_72_itbdMac; - } - - /** - * Array of positions of itbdMac tab stops. itbdMax==64. - */ - @Internal - public int[] getRgdxaTab() - { - return field_73_rgdxaTab; - } - - /** - * Array of positions of itbdMac tab stops. itbdMax==64. - */ - @Internal - public void setRgdxaTab( int[] field_73_rgdxaTab ) - { - this.field_73_rgdxaTab = field_73_rgdxaTab; - } - - /** - * Array of itbdMac tab descriptors. - */ - @Internal - public TabDescriptor[] getRgtbd() - { - return field_74_rgtbd; - } - - /** - * Array of itbdMac tab descriptors. - */ - @Internal - public void setRgtbd( TabDescriptor[] field_74_rgtbd ) - { - this.field_74_rgtbd = field_74_rgtbd; - } - - /** - * Get the numrm field for the PAP record. - */ - @Internal - public byte[] getNumrm() - { - return field_75_numrm; - } - - /** - * Set the numrm field for the PAP record. - */ - @Internal - public void setNumrm( byte[] field_75_numrm ) - { - this.field_75_numrm = field_75_numrm; - } - - /** - * Get the ptap field for the PAP record. - */ - @Internal - public byte[] getPtap() - { - return field_76_ptap; - } - - /** - * Set the ptap field for the PAP record. - */ - @Internal - public void setPtap( byte[] field_76_ptap ) - { - this.field_76_ptap = field_76_ptap; - } - - /** - * When 1, absolutely positioned paragraph cannot overlap with another paragraph. - */ - @Internal - public boolean getFNoAllowOverlap() - { - return field_77_fNoAllowOverlap; - } - - /** - * When 1, absolutely positioned paragraph cannot overlap with another paragraph. - */ - @Internal - public void setFNoAllowOverlap( boolean field_77_fNoAllowOverlap ) - { - this.field_77_fNoAllowOverlap = field_77_fNoAllowOverlap; - } - - /** - * HTML DIV ID for this paragraph. - */ - @Internal - public long getIpgp() - { - return field_78_ipgp; - } - - /** - * HTML DIV ID for this paragraph. - */ - @Internal - public void setIpgp( long field_78_ipgp ) - { - this.field_78_ipgp = field_78_ipgp; - } - - /** - * Save ID for last time this PAP was revised. - */ - @Internal - public long getRsid() - { - return field_79_rsid; - } - - /** - * Save ID for last time this PAP was revised. - */ - @Internal - public void setRsid( long field_79_rsid ) - { - this.field_79_rsid = field_79_rsid; - } - - /** - * Sets the fVertical field value. - * - */ - @Internal - public void setFVertical( boolean value ) - { - field_40_fontAlign = (short)fVertical.setBoolean(field_40_fontAlign, value); - } - - /** - * - * @return the fVertical field value. - */ - @Internal - public boolean isFVertical() - { - return fVertical.isSet(field_40_fontAlign); - } - - /** - * Sets the fBackward field value. - * - */ - @Internal - public void setFBackward( boolean value ) - { - field_40_fontAlign = (short)fBackward.setBoolean(field_40_fontAlign, value); - } - - /** - * - * @return the fBackward field value. - */ - @Internal - public boolean isFBackward() - { - return fBackward.isSet(field_40_fontAlign); - } - - /** - * Sets the fRotateFont field value. - * - */ - @Internal - public void setFRotateFont( boolean value ) - { - field_40_fontAlign = (short)fRotateFont.setBoolean(field_40_fontAlign, value); - } - - /** - * - * @return the fRotateFont field value. - */ - @Internal - public boolean isFRotateFont() - { - return fRotateFont.isSet(field_40_fontAlign); - } - -} // END OF CLASS diff --git a/src/scratchpad/src/org/apache/poi/hwpf/model/types/PICFAbstractType.java b/src/scratchpad/src/org/apache/poi/hwpf/model/types/PICFAbstractType.java deleted file mode 100644 index b41b2ba83..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/model/types/PICFAbstractType.java +++ /dev/null @@ -1,710 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -package org.apache.poi.hwpf.model.types; - - -import java.util.Arrays; - -import org.apache.poi.util.*; - -/** - * The PICF structure specifies the type of a picture, as well as the size of the - picture and information about its border.

    Class and fields descriptions are quoted - from Microsoft Office Word 97-2007 - Binary File Format and [MS-DOC] - v20110608 Word (.doc) - Binary File Format - - *

    - * NOTE: This source is automatically generated please do not modify this file. Either subclass or - * remove the record in src/types/definitions. - *

    - * This class is internal. It content or properties may change without notice - * due to changes in our knowledge of internal Microsoft Word binary structures. - - * @author Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary File Format - Specification [*.doc] and [MS-DOC] - v20110608 Word (.doc) Binary File Format - - */ -@Internal -public abstract class PICFAbstractType -{ - - protected int field_1_lcb; - protected int field_2_cbHeader; - protected short field_3_mm; - protected short field_4_xExt; - protected short field_5_yExt; - protected short field_6_swHMF; - protected int field_7_grf; - protected int field_8_padding; - protected int field_9_mmPM; - protected int field_10_padding2; - protected short field_11_dxaGoal; - protected short field_12_dyaGoal; - protected int field_13_mx; - protected int field_14_my; - protected short field_15_dxaReserved1; - protected short field_16_dyaReserved1; - protected short field_17_dxaReserved2; - protected short field_18_dyaReserved2; - protected byte field_19_fReserved; - protected byte field_20_bpp; - protected byte[] field_21_brcTop80; - protected byte[] field_22_brcLeft80; - protected byte[] field_23_brcBottom80; - protected byte[] field_24_brcRight80; - protected short field_25_dxaReserved3; - protected short field_26_dyaReserved3; - protected short field_27_cProps; - - protected PICFAbstractType() - { - this.field_21_brcTop80 = new byte[4]; - this.field_22_brcLeft80 = new byte[4]; - this.field_23_brcBottom80 = new byte[4]; - this.field_24_brcRight80 = new byte[4]; - } - - protected void fillFields( byte[] data, int offset ) - { - field_1_lcb = LittleEndian.getInt( data, 0x0 + offset ); - field_2_cbHeader = LittleEndian.getShort( data, 0x4 + offset ); - field_3_mm = LittleEndian.getShort( data, 0x6 + offset ); - field_4_xExt = LittleEndian.getShort( data, 0x8 + offset ); - field_5_yExt = LittleEndian.getShort( data, 0xa + offset ); - field_6_swHMF = LittleEndian.getShort( data, 0xc + offset ); - field_7_grf = LittleEndian.getInt( data, 0xe + offset ); - field_8_padding = LittleEndian.getInt( data, 0x12 + offset ); - field_9_mmPM = LittleEndian.getShort( data, 0x16 + offset ); - field_10_padding2 = LittleEndian.getInt( data, 0x18 + offset ); - field_11_dxaGoal = LittleEndian.getShort( data, 0x1c + offset ); - field_12_dyaGoal = LittleEndian.getShort( data, 0x1e + offset ); - field_13_mx = LittleEndian.getShort( data, 0x20 + offset ); - field_14_my = LittleEndian.getShort( data, 0x22 + offset ); - field_15_dxaReserved1 = LittleEndian.getShort( data, 0x24 + offset ); - field_16_dyaReserved1 = LittleEndian.getShort( data, 0x26 + offset ); - field_17_dxaReserved2 = LittleEndian.getShort( data, 0x28 + offset ); - field_18_dyaReserved2 = LittleEndian.getShort( data, 0x2a + offset ); - field_19_fReserved = data[ 0x2c + offset ]; - field_20_bpp = data[ 0x2d + offset ]; - field_21_brcTop80 = LittleEndian.getByteArray( data, 0x2e + offset,4 ); - field_22_brcLeft80 = LittleEndian.getByteArray( data, 0x32 + offset,4 ); - field_23_brcBottom80 = LittleEndian.getByteArray( data, 0x36 + offset,4 ); - field_24_brcRight80 = LittleEndian.getByteArray( data, 0x3a + offset,4 ); - field_25_dxaReserved3 = LittleEndian.getShort( data, 0x3e + offset ); - field_26_dyaReserved3 = LittleEndian.getShort( data, 0x40 + offset ); - field_27_cProps = LittleEndian.getShort( data, 0x42 + offset ); - } - - public void serialize( byte[] data, int offset ) - { - LittleEndian.putInt( data, 0x0 + offset, field_1_lcb ); - LittleEndian.putUShort( data, 0x4 + offset, field_2_cbHeader ); - LittleEndian.putShort( data, 0x6 + offset, field_3_mm ); - LittleEndian.putShort( data, 0x8 + offset, field_4_xExt ); - LittleEndian.putShort( data, 0xa + offset, field_5_yExt ); - LittleEndian.putShort( data, 0xc + offset, field_6_swHMF ); - LittleEndian.putInt( data, 0xe + offset, field_7_grf ); - LittleEndian.putInt( data, 0x12 + offset, field_8_padding ); - LittleEndian.putUShort( data, 0x16 + offset, field_9_mmPM ); - LittleEndian.putInt( data, 0x18 + offset, field_10_padding2 ); - LittleEndian.putShort( data, 0x1c + offset, field_11_dxaGoal ); - LittleEndian.putShort( data, 0x1e + offset, field_12_dyaGoal ); - LittleEndian.putUShort( data, 0x20 + offset, field_13_mx ); - LittleEndian.putUShort( data, 0x22 + offset, field_14_my ); - LittleEndian.putShort( data, 0x24 + offset, field_15_dxaReserved1 ); - LittleEndian.putShort( data, 0x26 + offset, field_16_dyaReserved1 ); - LittleEndian.putShort( data, 0x28 + offset, field_17_dxaReserved2 ); - LittleEndian.putShort( data, 0x2a + offset, field_18_dyaReserved2 ); - data[ 0x2c + offset ] = field_19_fReserved; - data[ 0x2d + offset ] = field_20_bpp; - System.arraycopy( field_21_brcTop80, 0, data, 0x2e + offset, field_21_brcTop80.length ); - System.arraycopy( field_22_brcLeft80, 0, data, 0x32 + offset, field_22_brcLeft80.length ); - System.arraycopy( field_23_brcBottom80, 0, data, 0x36 + offset, field_23_brcBottom80.length ); - System.arraycopy( field_24_brcRight80, 0, data, 0x3a + offset, field_24_brcRight80.length ); - LittleEndian.putShort( data, 0x3e + offset, field_25_dxaReserved3 ); - LittleEndian.putShort( data, 0x40 + offset, field_26_dyaReserved3 ); - LittleEndian.putShort( data, 0x42 + offset, field_27_cProps ); - } - - public byte[] serialize() - { - final byte[] result = new byte[ getSize() ]; - serialize( result, 0 ); - return result; - } - - /** - * Size of record - */ - public static int getSize() - { - return 0 + 4 + 2 + 2 + 2 + 2 + 2 + 4 + 4 + 2 + 4 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 1 + 1 + 4 + 4 + 4 + 4 + 2 + 2 + 2; - } - - public String toString() - { - StringBuilder builder = new StringBuilder(); - builder.append("[PICF]\n"); - builder.append(" .lcb = "); - builder.append(" (").append(getLcb()).append(" )\n"); - builder.append(" .cbHeader = "); - builder.append(" (").append(getCbHeader()).append(" )\n"); - builder.append(" .mm = "); - builder.append(" (").append(getMm()).append(" )\n"); - builder.append(" .xExt = "); - builder.append(" (").append(getXExt()).append(" )\n"); - builder.append(" .yExt = "); - builder.append(" (").append(getYExt()).append(" )\n"); - builder.append(" .swHMF = "); - builder.append(" (").append(getSwHMF()).append(" )\n"); - builder.append(" .grf = "); - builder.append(" (").append(getGrf()).append(" )\n"); - builder.append(" .padding = "); - builder.append(" (").append(getPadding()).append(" )\n"); - builder.append(" .mmPM = "); - builder.append(" (").append(getMmPM()).append(" )\n"); - builder.append(" .padding2 = "); - builder.append(" (").append(getPadding2()).append(" )\n"); - builder.append(" .dxaGoal = "); - builder.append(" (").append(getDxaGoal()).append(" )\n"); - builder.append(" .dyaGoal = "); - builder.append(" (").append(getDyaGoal()).append(" )\n"); - builder.append(" .mx = "); - builder.append(" (").append(getMx()).append(" )\n"); - builder.append(" .my = "); - builder.append(" (").append(getMy()).append(" )\n"); - builder.append(" .dxaReserved1 = "); - builder.append(" (").append(getDxaReserved1()).append(" )\n"); - builder.append(" .dyaReserved1 = "); - builder.append(" (").append(getDyaReserved1()).append(" )\n"); - builder.append(" .dxaReserved2 = "); - builder.append(" (").append(getDxaReserved2()).append(" )\n"); - builder.append(" .dyaReserved2 = "); - builder.append(" (").append(getDyaReserved2()).append(" )\n"); - builder.append(" .fReserved = "); - builder.append(" (").append(getFReserved()).append(" )\n"); - builder.append(" .bpp = "); - builder.append(" (").append(getBpp()).append(" )\n"); - builder.append(" .brcTop80 = "); - builder.append(" (").append(Arrays.toString(getBrcTop80())).append(" )\n"); - builder.append(" .brcLeft80 = "); - builder.append(" (").append(Arrays.toString(getBrcLeft80())).append(" )\n"); - builder.append(" .brcBottom80 = "); - builder.append(" (").append(Arrays.toString(getBrcBottom80())).append(" )\n"); - builder.append(" .brcRight80 = "); - builder.append(" (").append(Arrays.toString(getBrcRight80())).append(" )\n"); - builder.append(" .dxaReserved3 = "); - builder.append(" (").append(getDxaReserved3()).append(" )\n"); - builder.append(" .dyaReserved3 = "); - builder.append(" (").append(getDyaReserved3()).append(" )\n"); - builder.append(" .cProps = "); - builder.append(" (").append(getCProps()).append(" )\n"); - - builder.append("[/PICF]\n"); - return builder.toString(); - } - - /** - * A signed integer that specifies the size, in bytes, of this PICF structure and the subsequent data. - */ - @Internal - public int getLcb() - { - return field_1_lcb; - } - - /** - * A signed integer that specifies the size, in bytes, of this PICF structure and the subsequent data. - */ - @Internal - public void setLcb( int field_1_lcb ) - { - this.field_1_lcb = field_1_lcb; - } - - /** - * An unsigned integer that specifies the size, in bytes, of this PICF structure. This value MUST be 0x44. - */ - @Internal - public int getCbHeader() - { - return field_2_cbHeader; - } - - /** - * An unsigned integer that specifies the size, in bytes, of this PICF structure. This value MUST be 0x44. - */ - @Internal - public void setCbHeader( int field_2_cbHeader ) - { - this.field_2_cbHeader = field_2_cbHeader; - } - - /** - * A signed integer that specifies the format of the picture data. - */ - @Internal - public short getMm() - { - return field_3_mm; - } - - /** - * A signed integer that specifies the format of the picture data. - */ - @Internal - public void setMm( short field_3_mm ) - { - this.field_3_mm = field_3_mm; - } - - /** - * This field is unused and MUST be ignored. - */ - @Internal - public short getXExt() - { - return field_4_xExt; - } - - /** - * This field is unused and MUST be ignored. - */ - @Internal - public void setXExt( short field_4_xExt ) - { - this.field_4_xExt = field_4_xExt; - } - - /** - * This field is unused and MUST be ignored. - */ - @Internal - public short getYExt() - { - return field_5_yExt; - } - - /** - * This field is unused and MUST be ignored. - */ - @Internal - public void setYExt( short field_5_yExt ) - { - this.field_5_yExt = field_5_yExt; - } - - /** - * This field is unused and MUST be ignored. - */ - @Internal - public short getSwHMF() - { - return field_6_swHMF; - } - - /** - * This field is unused and MUST be ignored. - */ - @Internal - public void setSwHMF( short field_6_swHMF ) - { - this.field_6_swHMF = field_6_swHMF; - } - - /** - * This field MUST be ignored. - */ - @Internal - public int getGrf() - { - return field_7_grf; - } - - /** - * This field MUST be ignored. - */ - @Internal - public void setGrf( int field_7_grf ) - { - this.field_7_grf = field_7_grf; - } - - /** - * This value MUST be zero and MUST be ignored. - */ - @Internal - public int getPadding() - { - return field_8_padding; - } - - /** - * This value MUST be zero and MUST be ignored. - */ - @Internal - public void setPadding( int field_8_padding ) - { - this.field_8_padding = field_8_padding; - } - - /** - * This field MUST be ignored. - */ - @Internal - public int getMmPM() - { - return field_9_mmPM; - } - - /** - * This field MUST be ignored. - */ - @Internal - public void setMmPM( int field_9_mmPM ) - { - this.field_9_mmPM = field_9_mmPM; - } - - /** - * This value MUST be zero and MUST be ignored. - */ - @Internal - public int getPadding2() - { - return field_10_padding2; - } - - /** - * This value MUST be zero and MUST be ignored. - */ - @Internal - public void setPadding2( int field_10_padding2 ) - { - this.field_10_padding2 = field_10_padding2; - } - - /** - * Get the dxaGoal field for the PICF record. - */ - @Internal - public short getDxaGoal() - { - return field_11_dxaGoal; - } - - /** - * Set the dxaGoal field for the PICF record. - */ - @Internal - public void setDxaGoal( short field_11_dxaGoal ) - { - this.field_11_dxaGoal = field_11_dxaGoal; - } - - /** - * Get the dyaGoal field for the PICF record. - */ - @Internal - public short getDyaGoal() - { - return field_12_dyaGoal; - } - - /** - * Set the dyaGoal field for the PICF record. - */ - @Internal - public void setDyaGoal( short field_12_dyaGoal ) - { - this.field_12_dyaGoal = field_12_dyaGoal; - } - - /** - * Get the mx field for the PICF record. - */ - @Internal - public int getMx() - { - return field_13_mx; - } - - /** - * Set the mx field for the PICF record. - */ - @Internal - public void setMx( int field_13_mx ) - { - this.field_13_mx = field_13_mx; - } - - /** - * Get the my field for the PICF record. - */ - @Internal - public int getMy() - { - return field_14_my; - } - - /** - * Set the my field for the PICF record. - */ - @Internal - public void setMy( int field_14_my ) - { - this.field_14_my = field_14_my; - } - - /** - * Get the dxaReserved1 field for the PICF record. - */ - @Internal - public short getDxaReserved1() - { - return field_15_dxaReserved1; - } - - /** - * Set the dxaReserved1 field for the PICF record. - */ - @Internal - public void setDxaReserved1( short field_15_dxaReserved1 ) - { - this.field_15_dxaReserved1 = field_15_dxaReserved1; - } - - /** - * Get the dyaReserved1 field for the PICF record. - */ - @Internal - public short getDyaReserved1() - { - return field_16_dyaReserved1; - } - - /** - * Set the dyaReserved1 field for the PICF record. - */ - @Internal - public void setDyaReserved1( short field_16_dyaReserved1 ) - { - this.field_16_dyaReserved1 = field_16_dyaReserved1; - } - - /** - * Get the dxaReserved2 field for the PICF record. - */ - @Internal - public short getDxaReserved2() - { - return field_17_dxaReserved2; - } - - /** - * Set the dxaReserved2 field for the PICF record. - */ - @Internal - public void setDxaReserved2( short field_17_dxaReserved2 ) - { - this.field_17_dxaReserved2 = field_17_dxaReserved2; - } - - /** - * Get the dyaReserved2 field for the PICF record. - */ - @Internal - public short getDyaReserved2() - { - return field_18_dyaReserved2; - } - - /** - * Set the dyaReserved2 field for the PICF record. - */ - @Internal - public void setDyaReserved2( short field_18_dyaReserved2 ) - { - this.field_18_dyaReserved2 = field_18_dyaReserved2; - } - - /** - * Get the fReserved field for the PICF record. - */ - @Internal - public byte getFReserved() - { - return field_19_fReserved; - } - - /** - * Set the fReserved field for the PICF record. - */ - @Internal - public void setFReserved( byte field_19_fReserved ) - { - this.field_19_fReserved = field_19_fReserved; - } - - /** - * Get the bpp field for the PICF record. - */ - @Internal - public byte getBpp() - { - return field_20_bpp; - } - - /** - * Set the bpp field for the PICF record. - */ - @Internal - public void setBpp( byte field_20_bpp ) - { - this.field_20_bpp = field_20_bpp; - } - - /** - * Get the brcTop80 field for the PICF record. - */ - @Internal - public byte[] getBrcTop80() - { - return field_21_brcTop80; - } - - /** - * Set the brcTop80 field for the PICF record. - */ - @Internal - public void setBrcTop80( byte[] field_21_brcTop80 ) - { - this.field_21_brcTop80 = field_21_brcTop80; - } - - /** - * Get the brcLeft80 field for the PICF record. - */ - @Internal - public byte[] getBrcLeft80() - { - return field_22_brcLeft80; - } - - /** - * Set the brcLeft80 field for the PICF record. - */ - @Internal - public void setBrcLeft80( byte[] field_22_brcLeft80 ) - { - this.field_22_brcLeft80 = field_22_brcLeft80; - } - - /** - * Get the brcBottom80 field for the PICF record. - */ - @Internal - public byte[] getBrcBottom80() - { - return field_23_brcBottom80; - } - - /** - * Set the brcBottom80 field for the PICF record. - */ - @Internal - public void setBrcBottom80( byte[] field_23_brcBottom80 ) - { - this.field_23_brcBottom80 = field_23_brcBottom80; - } - - /** - * Get the brcRight80 field for the PICF record. - */ - @Internal - public byte[] getBrcRight80() - { - return field_24_brcRight80; - } - - /** - * Set the brcRight80 field for the PICF record. - */ - @Internal - public void setBrcRight80( byte[] field_24_brcRight80 ) - { - this.field_24_brcRight80 = field_24_brcRight80; - } - - /** - * Get the dxaReserved3 field for the PICF record. - */ - @Internal - public short getDxaReserved3() - { - return field_25_dxaReserved3; - } - - /** - * Set the dxaReserved3 field for the PICF record. - */ - @Internal - public void setDxaReserved3( short field_25_dxaReserved3 ) - { - this.field_25_dxaReserved3 = field_25_dxaReserved3; - } - - /** - * Get the dyaReserved3 field for the PICF record. - */ - @Internal - public short getDyaReserved3() - { - return field_26_dyaReserved3; - } - - /** - * Set the dyaReserved3 field for the PICF record. - */ - @Internal - public void setDyaReserved3( short field_26_dyaReserved3 ) - { - this.field_26_dyaReserved3 = field_26_dyaReserved3; - } - - /** - * This value MUST be 0 and MUST be ignored. - */ - @Internal - public short getCProps() - { - return field_27_cProps; - } - - /** - * This value MUST be 0 and MUST be ignored. - */ - @Internal - public void setCProps( short field_27_cProps ) - { - this.field_27_cProps = field_27_cProps; - } - -} // END OF CLASS diff --git a/src/scratchpad/src/org/apache/poi/hwpf/model/types/SEPAbstractType.java b/src/scratchpad/src/org/apache/poi/hwpf/model/types/SEPAbstractType.java deleted file mode 100644 index c2f0f9ce7..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/model/types/SEPAbstractType.java +++ /dev/null @@ -1,1253 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.model.types; - - -import java.util.Arrays; - -import org.apache.poi.hwpf.usermodel.BorderCode; -import org.apache.poi.hwpf.usermodel.DateAndTime; -import org.apache.poi.util.Internal; - -/** - * Section Properties. - * NOTE: This source is automatically generated please do not modify this file. Either subclass or - * remove the record in src/records/definitions. - * - * @author S. Ryan Ackley - */ -@Internal -public abstract class SEPAbstractType -{ - - protected byte field_1_bkc; - /** No break */ - /**/public final static byte BKC_NO_BREAK = 0; - /** New column */ - /**/public final static byte BKC_NEW_COLUMN = 1; - /** New page */ - /**/public final static byte BKC_NEW_PAGE = 2; - /** Even page */ - /**/public final static byte BKC_EVEN_PAGE = 3; - /** Odd page */ - /**/public final static byte BKC_ODD_PAGE = 4; - protected boolean field_2_fTitlePage; - protected boolean field_3_fAutoPgn; - protected byte field_4_nfcPgn; - /** Arabic */ - /**/public final static byte NFCPGN_ARABIC = 0; - /** Roman (upper case) */ - /**/public final static byte NFCPGN_ROMAN_UPPER_CASE = 1; - /** Roman (lower case) */ - /**/public final static byte NFCPGN_ROMAN_LOWER_CASE = 2; - /** Letter (upper case) */ - /**/public final static byte NFCPGN_LETTER_UPPER_CASE = 3; - /** Letter (lower case) */ - /**/public final static byte NFCPGN_LETTER_LOWER_CASE = 4; - protected boolean field_5_fUnlocked; - protected byte field_6_cnsPgn; - protected boolean field_7_fPgnRestart; - protected boolean field_8_fEndNote; - protected byte field_9_lnc; - protected byte field_10_grpfIhdt; - protected int field_11_nLnnMod; - protected int field_12_dxaLnn; - protected int field_13_dxaPgn; - protected int field_14_dyaPgn; - protected boolean field_15_fLBetween; - protected byte field_16_vjc; - protected int field_17_dmBinFirst; - protected int field_18_dmBinOther; - protected int field_19_dmPaperReq; - protected BorderCode field_20_brcTop; - protected BorderCode field_21_brcLeft; - protected BorderCode field_22_brcBottom; - protected BorderCode field_23_brcRight; - protected boolean field_24_fPropMark; - protected int field_25_ibstPropRMark; - protected DateAndTime field_26_dttmPropRMark; - protected int field_27_dxtCharSpace; - protected int field_28_dyaLinePitch; - protected int field_29_clm; - protected int field_30_unused2; - protected boolean field_31_dmOrientPage; - /**/public final static boolean DMORIENTPAGE_LANDSCAPE = false; - /**/public final static boolean DMORIENTPAGE_PORTRAIT = true; - protected byte field_32_iHeadingPgn; - protected int field_33_pgnStart; - protected int field_34_lnnMin; - protected int field_35_wTextFlow; - protected short field_36_unused3; - protected int field_37_pgbProp; - protected short field_38_unused4; - protected int field_39_xaPage; - protected int field_40_yaPage; - protected int field_41_xaPageNUp; - protected int field_42_yaPageNUp; - protected int field_43_dxaLeft; - protected int field_44_dxaRight; - protected int field_45_dyaTop; - protected int field_46_dyaBottom; - protected int field_47_dzaGutter; - protected int field_48_dyaHdrTop; - protected int field_49_dyaHdrBottom; - protected int field_50_ccolM1; - protected boolean field_51_fEvenlySpaced; - protected byte field_52_unused5; - protected int field_53_dxaColumns; - protected int[] field_54_rgdxaColumn; - protected int field_55_dxaColumnWidth; - protected byte field_56_dmOrientFirst; - protected byte field_57_fLayout; - protected short field_58_unused6; - protected byte[] field_59_olstAnm; - - protected SEPAbstractType() - { - this.field_1_bkc = 2; - this.field_8_fEndNote = true; - this.field_13_dxaPgn = 720; - this.field_14_dyaPgn = 720; - this.field_31_dmOrientPage = true; - this.field_33_pgnStart = 1; - this.field_39_xaPage = 12240; - this.field_40_yaPage = 15840; - this.field_41_xaPageNUp = 12240; - this.field_42_yaPageNUp = 15840; - this.field_43_dxaLeft = 1800; - this.field_44_dxaRight = 1800; - this.field_45_dyaTop = 1440; - this.field_46_dyaBottom = 1440; - this.field_48_dyaHdrTop = 720; - this.field_49_dyaHdrBottom = 720; - this.field_51_fEvenlySpaced = true; - this.field_53_dxaColumns = 720; - } - - - public String toString() - { - StringBuilder builder = new StringBuilder(); - builder.append("[SEP]\n"); - builder.append(" .bkc = "); - builder.append(" (").append(getBkc()).append(" )\n"); - builder.append(" .fTitlePage = "); - builder.append(" (").append(getFTitlePage()).append(" )\n"); - builder.append(" .fAutoPgn = "); - builder.append(" (").append(getFAutoPgn()).append(" )\n"); - builder.append(" .nfcPgn = "); - builder.append(" (").append(getNfcPgn()).append(" )\n"); - builder.append(" .fUnlocked = "); - builder.append(" (").append(getFUnlocked()).append(" )\n"); - builder.append(" .cnsPgn = "); - builder.append(" (").append(getCnsPgn()).append(" )\n"); - builder.append(" .fPgnRestart = "); - builder.append(" (").append(getFPgnRestart()).append(" )\n"); - builder.append(" .fEndNote = "); - builder.append(" (").append(getFEndNote()).append(" )\n"); - builder.append(" .lnc = "); - builder.append(" (").append(getLnc()).append(" )\n"); - builder.append(" .grpfIhdt = "); - builder.append(" (").append(getGrpfIhdt()).append(" )\n"); - builder.append(" .nLnnMod = "); - builder.append(" (").append(getNLnnMod()).append(" )\n"); - builder.append(" .dxaLnn = "); - builder.append(" (").append(getDxaLnn()).append(" )\n"); - builder.append(" .dxaPgn = "); - builder.append(" (").append(getDxaPgn()).append(" )\n"); - builder.append(" .dyaPgn = "); - builder.append(" (").append(getDyaPgn()).append(" )\n"); - builder.append(" .fLBetween = "); - builder.append(" (").append(getFLBetween()).append(" )\n"); - builder.append(" .vjc = "); - builder.append(" (").append(getVjc()).append(" )\n"); - builder.append(" .dmBinFirst = "); - builder.append(" (").append(getDmBinFirst()).append(" )\n"); - builder.append(" .dmBinOther = "); - builder.append(" (").append(getDmBinOther()).append(" )\n"); - builder.append(" .dmPaperReq = "); - builder.append(" (").append(getDmPaperReq()).append(" )\n"); - builder.append(" .brcTop = "); - builder.append(" (").append(getBrcTop()).append(" )\n"); - builder.append(" .brcLeft = "); - builder.append(" (").append(getBrcLeft()).append(" )\n"); - builder.append(" .brcBottom = "); - builder.append(" (").append(getBrcBottom()).append(" )\n"); - builder.append(" .brcRight = "); - builder.append(" (").append(getBrcRight()).append(" )\n"); - builder.append(" .fPropMark = "); - builder.append(" (").append(getFPropMark()).append(" )\n"); - builder.append(" .ibstPropRMark = "); - builder.append(" (").append(getIbstPropRMark()).append(" )\n"); - builder.append(" .dttmPropRMark = "); - builder.append(" (").append(getDttmPropRMark()).append(" )\n"); - builder.append(" .dxtCharSpace = "); - builder.append(" (").append(getDxtCharSpace()).append(" )\n"); - builder.append(" .dyaLinePitch = "); - builder.append(" (").append(getDyaLinePitch()).append(" )\n"); - builder.append(" .clm = "); - builder.append(" (").append(getClm()).append(" )\n"); - builder.append(" .unused2 = "); - builder.append(" (").append(getUnused2()).append(" )\n"); - builder.append(" .dmOrientPage = "); - builder.append(" (").append(getDmOrientPage()).append(" )\n"); - builder.append(" .iHeadingPgn = "); - builder.append(" (").append(getIHeadingPgn()).append(" )\n"); - builder.append(" .pgnStart = "); - builder.append(" (").append(getPgnStart()).append(" )\n"); - builder.append(" .lnnMin = "); - builder.append(" (").append(getLnnMin()).append(" )\n"); - builder.append(" .wTextFlow = "); - builder.append(" (").append(getWTextFlow()).append(" )\n"); - builder.append(" .unused3 = "); - builder.append(" (").append(getUnused3()).append(" )\n"); - builder.append(" .pgbProp = "); - builder.append(" (").append(getPgbProp()).append(" )\n"); - builder.append(" .unused4 = "); - builder.append(" (").append(getUnused4()).append(" )\n"); - builder.append(" .xaPage = "); - builder.append(" (").append(getXaPage()).append(" )\n"); - builder.append(" .yaPage = "); - builder.append(" (").append(getYaPage()).append(" )\n"); - builder.append(" .xaPageNUp = "); - builder.append(" (").append(getXaPageNUp()).append(" )\n"); - builder.append(" .yaPageNUp = "); - builder.append(" (").append(getYaPageNUp()).append(" )\n"); - builder.append(" .dxaLeft = "); - builder.append(" (").append(getDxaLeft()).append(" )\n"); - builder.append(" .dxaRight = "); - builder.append(" (").append(getDxaRight()).append(" )\n"); - builder.append(" .dyaTop = "); - builder.append(" (").append(getDyaTop()).append(" )\n"); - builder.append(" .dyaBottom = "); - builder.append(" (").append(getDyaBottom()).append(" )\n"); - builder.append(" .dzaGutter = "); - builder.append(" (").append(getDzaGutter()).append(" )\n"); - builder.append(" .dyaHdrTop = "); - builder.append(" (").append(getDyaHdrTop()).append(" )\n"); - builder.append(" .dyaHdrBottom = "); - builder.append(" (").append(getDyaHdrBottom()).append(" )\n"); - builder.append(" .ccolM1 = "); - builder.append(" (").append(getCcolM1()).append(" )\n"); - builder.append(" .fEvenlySpaced = "); - builder.append(" (").append(getFEvenlySpaced()).append(" )\n"); - builder.append(" .unused5 = "); - builder.append(" (").append(getUnused5()).append(" )\n"); - builder.append(" .dxaColumns = "); - builder.append(" (").append(getDxaColumns()).append(" )\n"); - builder.append(" .rgdxaColumn = "); - builder.append(" (").append(Arrays.toString(getRgdxaColumn())).append(" )\n"); - builder.append(" .dxaColumnWidth = "); - builder.append(" (").append(getDxaColumnWidth()).append(" )\n"); - builder.append(" .dmOrientFirst = "); - builder.append(" (").append(getDmOrientFirst()).append(" )\n"); - builder.append(" .fLayout = "); - builder.append(" (").append(getFLayout()).append(" )\n"); - builder.append(" .unused6 = "); - builder.append(" (").append(getUnused6()).append(" )\n"); - builder.append(" .olstAnm = "); - builder.append(" (").append(Arrays.toString(getOlstAnm())).append(" )\n"); - - builder.append("[/SEP]\n"); - return builder.toString(); - } - - /** - * Break code. - * - * @return One of - *

  • {@link #BKC_NO_BREAK} - *
  • {@link #BKC_NEW_COLUMN} - *
  • {@link #BKC_NEW_PAGE} - *
  • {@link #BKC_EVEN_PAGE} - *
  • {@link #BKC_ODD_PAGE} - */ - public byte getBkc() - { - return field_1_bkc; - } - - /** - * Break code. - * - * @param field_1_bkc - * One of - *
  • {@link #BKC_NO_BREAK} - *
  • {@link #BKC_NEW_COLUMN} - *
  • {@link #BKC_NEW_PAGE} - *
  • {@link #BKC_EVEN_PAGE} - *
  • {@link #BKC_ODD_PAGE} - */ - public void setBkc(byte field_1_bkc) - { - this.field_1_bkc = field_1_bkc; - } - - /** - * Set to 1 when a title page is to be displayed. - */ - public boolean getFTitlePage() - { - return field_2_fTitlePage; - } - - /** - * Set to 1 when a title page is to be displayed. - */ - public void setFTitlePage(boolean field_2_fTitlePage) - { - this.field_2_fTitlePage = field_2_fTitlePage; - } - - /** - * Only for Macintosh compatibility, used only during open, when 1, sep.dxaPgn and sep.dyaPgn are valid page number locations. - */ - public boolean getFAutoPgn() - { - return field_3_fAutoPgn; - } - - /** - * Only for Macintosh compatibility, used only during open, when 1, sep.dxaPgn and sep.dyaPgn are valid page number locations. - */ - public void setFAutoPgn(boolean field_3_fAutoPgn) - { - this.field_3_fAutoPgn = field_3_fAutoPgn; - } - - /** - * Page number format code. - * - * @return One of - *
  • {@link #NFCPGN_ARABIC} - *
  • {@link #NFCPGN_ROMAN_UPPER_CASE} - *
  • {@link #NFCPGN_ROMAN_LOWER_CASE} - *
  • {@link #NFCPGN_LETTER_UPPER_CASE} - *
  • {@link #NFCPGN_LETTER_LOWER_CASE} - */ - public byte getNfcPgn() - { - return field_4_nfcPgn; - } - - /** - * Page number format code. - * - * @param field_4_nfcPgn - * One of - *
  • {@link #NFCPGN_ARABIC} - *
  • {@link #NFCPGN_ROMAN_UPPER_CASE} - *
  • {@link #NFCPGN_ROMAN_LOWER_CASE} - *
  • {@link #NFCPGN_LETTER_UPPER_CASE} - *
  • {@link #NFCPGN_LETTER_LOWER_CASE} - */ - public void setNfcPgn(byte field_4_nfcPgn) - { - this.field_4_nfcPgn = field_4_nfcPgn; - } - - /** - * Get the fUnlocked field for the SEP record. - */ - public boolean getFUnlocked() - { - return field_5_fUnlocked; - } - - /** - * Set the fUnlocked field for the SEP record. - */ - public void setFUnlocked(boolean field_5_fUnlocked) - { - this.field_5_fUnlocked = field_5_fUnlocked; - } - - /** - * Get the cnsPgn field for the SEP record. - */ - public byte getCnsPgn() - { - return field_6_cnsPgn; - } - - /** - * Set the cnsPgn field for the SEP record. - */ - public void setCnsPgn(byte field_6_cnsPgn) - { - this.field_6_cnsPgn = field_6_cnsPgn; - } - - /** - * Get the fPgnRestart field for the SEP record. - */ - public boolean getFPgnRestart() - { - return field_7_fPgnRestart; - } - - /** - * Set the fPgnRestart field for the SEP record. - */ - public void setFPgnRestart(boolean field_7_fPgnRestart) - { - this.field_7_fPgnRestart = field_7_fPgnRestart; - } - - /** - * Get the fEndNote field for the SEP record. - */ - public boolean getFEndNote() - { - return field_8_fEndNote; - } - - /** - * Set the fEndNote field for the SEP record. - */ - public void setFEndNote(boolean field_8_fEndNote) - { - this.field_8_fEndNote = field_8_fEndNote; - } - - /** - * Get the lnc field for the SEP record. - */ - public byte getLnc() - { - return field_9_lnc; - } - - /** - * Set the lnc field for the SEP record. - */ - public void setLnc(byte field_9_lnc) - { - this.field_9_lnc = field_9_lnc; - } - - /** - * Get the grpfIhdt field for the SEP record. - */ - public byte getGrpfIhdt() - { - return field_10_grpfIhdt; - } - - /** - * Set the grpfIhdt field for the SEP record. - */ - public void setGrpfIhdt(byte field_10_grpfIhdt) - { - this.field_10_grpfIhdt = field_10_grpfIhdt; - } - - /** - * Get the nLnnMod field for the SEP record. - */ - public int getNLnnMod() - { - return field_11_nLnnMod; - } - - /** - * Set the nLnnMod field for the SEP record. - */ - public void setNLnnMod(int field_11_nLnnMod) - { - this.field_11_nLnnMod = field_11_nLnnMod; - } - - /** - * Get the dxaLnn field for the SEP record. - */ - public int getDxaLnn() - { - return field_12_dxaLnn; - } - - /** - * Set the dxaLnn field for the SEP record. - */ - public void setDxaLnn(int field_12_dxaLnn) - { - this.field_12_dxaLnn = field_12_dxaLnn; - } - - /** - * Get the dxaPgn field for the SEP record. - */ - public int getDxaPgn() - { - return field_13_dxaPgn; - } - - /** - * Set the dxaPgn field for the SEP record. - */ - public void setDxaPgn(int field_13_dxaPgn) - { - this.field_13_dxaPgn = field_13_dxaPgn; - } - - /** - * Get the dyaPgn field for the SEP record. - */ - public int getDyaPgn() - { - return field_14_dyaPgn; - } - - /** - * Set the dyaPgn field for the SEP record. - */ - public void setDyaPgn(int field_14_dyaPgn) - { - this.field_14_dyaPgn = field_14_dyaPgn; - } - - /** - * Get the fLBetween field for the SEP record. - */ - public boolean getFLBetween() - { - return field_15_fLBetween; - } - - /** - * Set the fLBetween field for the SEP record. - */ - public void setFLBetween(boolean field_15_fLBetween) - { - this.field_15_fLBetween = field_15_fLBetween; - } - - /** - * Get the vjc field for the SEP record. - */ - public byte getVjc() - { - return field_16_vjc; - } - - /** - * Set the vjc field for the SEP record. - */ - public void setVjc(byte field_16_vjc) - { - this.field_16_vjc = field_16_vjc; - } - - /** - * Get the dmBinFirst field for the SEP record. - */ - public int getDmBinFirst() - { - return field_17_dmBinFirst; - } - - /** - * Set the dmBinFirst field for the SEP record. - */ - public void setDmBinFirst(int field_17_dmBinFirst) - { - this.field_17_dmBinFirst = field_17_dmBinFirst; - } - - /** - * Get the dmBinOther field for the SEP record. - */ - public int getDmBinOther() - { - return field_18_dmBinOther; - } - - /** - * Set the dmBinOther field for the SEP record. - */ - public void setDmBinOther(int field_18_dmBinOther) - { - this.field_18_dmBinOther = field_18_dmBinOther; - } - - /** - * Get the dmPaperReq field for the SEP record. - */ - public int getDmPaperReq() - { - return field_19_dmPaperReq; - } - - /** - * Set the dmPaperReq field for the SEP record. - */ - public void setDmPaperReq(int field_19_dmPaperReq) - { - this.field_19_dmPaperReq = field_19_dmPaperReq; - } - - /** - * Get the brcTop field for the SEP record. - */ - public BorderCode getBrcTop() - { - return field_20_brcTop; - } - - /** - * Set the brcTop field for the SEP record. - */ - public void setBrcTop(BorderCode field_20_brcTop) - { - this.field_20_brcTop = field_20_brcTop; - } - - /** - * Get the brcLeft field for the SEP record. - */ - public BorderCode getBrcLeft() - { - return field_21_brcLeft; - } - - /** - * Set the brcLeft field for the SEP record. - */ - public void setBrcLeft(BorderCode field_21_brcLeft) - { - this.field_21_brcLeft = field_21_brcLeft; - } - - /** - * Get the brcBottom field for the SEP record. - */ - public BorderCode getBrcBottom() - { - return field_22_brcBottom; - } - - /** - * Set the brcBottom field for the SEP record. - */ - public void setBrcBottom(BorderCode field_22_brcBottom) - { - this.field_22_brcBottom = field_22_brcBottom; - } - - /** - * Get the brcRight field for the SEP record. - */ - public BorderCode getBrcRight() - { - return field_23_brcRight; - } - - /** - * Set the brcRight field for the SEP record. - */ - public void setBrcRight(BorderCode field_23_brcRight) - { - this.field_23_brcRight = field_23_brcRight; - } - - /** - * Get the fPropMark field for the SEP record. - */ - public boolean getFPropMark() - { - return field_24_fPropMark; - } - - /** - * Set the fPropMark field for the SEP record. - */ - public void setFPropMark(boolean field_24_fPropMark) - { - this.field_24_fPropMark = field_24_fPropMark; - } - - /** - * Get the ibstPropRMark field for the SEP record. - */ - public int getIbstPropRMark() - { - return field_25_ibstPropRMark; - } - - /** - * Set the ibstPropRMark field for the SEP record. - */ - public void setIbstPropRMark(int field_25_ibstPropRMark) - { - this.field_25_ibstPropRMark = field_25_ibstPropRMark; - } - - /** - * Get the dttmPropRMark field for the SEP record. - */ - public DateAndTime getDttmPropRMark() - { - return field_26_dttmPropRMark; - } - - /** - * Set the dttmPropRMark field for the SEP record. - */ - public void setDttmPropRMark(DateAndTime field_26_dttmPropRMark) - { - this.field_26_dttmPropRMark = field_26_dttmPropRMark; - } - - /** - * Get the dxtCharSpace field for the SEP record. - */ - public int getDxtCharSpace() - { - return field_27_dxtCharSpace; - } - - /** - * Set the dxtCharSpace field for the SEP record. - */ - public void setDxtCharSpace(int field_27_dxtCharSpace) - { - this.field_27_dxtCharSpace = field_27_dxtCharSpace; - } - - /** - * Get the dyaLinePitch field for the SEP record. - */ - public int getDyaLinePitch() - { - return field_28_dyaLinePitch; - } - - /** - * Set the dyaLinePitch field for the SEP record. - */ - public void setDyaLinePitch(int field_28_dyaLinePitch) - { - this.field_28_dyaLinePitch = field_28_dyaLinePitch; - } - - /** - * Get the clm field for the SEP record. - */ - public int getClm() - { - return field_29_clm; - } - - /** - * Set the clm field for the SEP record. - */ - public void setClm(int field_29_clm) - { - this.field_29_clm = field_29_clm; - } - - /** - * Get the unused2 field for the SEP record. - */ - public int getUnused2() - { - return field_30_unused2; - } - - /** - * Set the unused2 field for the SEP record. - */ - public void setUnused2(int field_30_unused2) - { - this.field_30_unused2 = field_30_unused2; - } - - /** - * Get the dmOrientPage field for the SEP record. - * - * @return One of - *
  • {@link #DMORIENTPAGE_LANDSCAPE} - *
  • {@link #DMORIENTPAGE_PORTRAIT} - */ - public boolean getDmOrientPage() - { - return field_31_dmOrientPage; - } - - /** - * Set the dmOrientPage field for the SEP record. - * - * @param field_31_dmOrientPage - * One of - *
  • {@link #DMORIENTPAGE_LANDSCAPE} - *
  • {@link #DMORIENTPAGE_PORTRAIT} - */ - public void setDmOrientPage(boolean field_31_dmOrientPage) - { - this.field_31_dmOrientPage = field_31_dmOrientPage; - } - - /** - * Get the iHeadingPgn field for the SEP record. - */ - public byte getIHeadingPgn() - { - return field_32_iHeadingPgn; - } - - /** - * Set the iHeadingPgn field for the SEP record. - */ - public void setIHeadingPgn(byte field_32_iHeadingPgn) - { - this.field_32_iHeadingPgn = field_32_iHeadingPgn; - } - - /** - * Get the pgnStart field for the SEP record. - */ - public int getPgnStart() - { - return field_33_pgnStart; - } - - /** - * Set the pgnStart field for the SEP record. - */ - public void setPgnStart(int field_33_pgnStart) - { - this.field_33_pgnStart = field_33_pgnStart; - } - - /** - * Get the lnnMin field for the SEP record. - */ - public int getLnnMin() - { - return field_34_lnnMin; - } - - /** - * Set the lnnMin field for the SEP record. - */ - public void setLnnMin(int field_34_lnnMin) - { - this.field_34_lnnMin = field_34_lnnMin; - } - - /** - * Get the wTextFlow field for the SEP record. - */ - public int getWTextFlow() - { - return field_35_wTextFlow; - } - - /** - * Set the wTextFlow field for the SEP record. - */ - public void setWTextFlow(int field_35_wTextFlow) - { - this.field_35_wTextFlow = field_35_wTextFlow; - } - - /** - * Get the unused3 field for the SEP record. - */ - public short getUnused3() - { - return field_36_unused3; - } - - /** - * Set the unused3 field for the SEP record. - */ - public void setUnused3(short field_36_unused3) - { - this.field_36_unused3 = field_36_unused3; - } - - /** - * Get the pgbProp field for the SEP record. - */ - public int getPgbProp() - { - return field_37_pgbProp; - } - - /** - * Set the pgbProp field for the SEP record. - */ - public void setPgbProp(int field_37_pgbProp) - { - this.field_37_pgbProp = field_37_pgbProp; - } - - /** - * Get the unused4 field for the SEP record. - */ - public short getUnused4() - { - return field_38_unused4; - } - - /** - * Set the unused4 field for the SEP record. - */ - public void setUnused4(short field_38_unused4) - { - this.field_38_unused4 = field_38_unused4; - } - - /** - * Get the xaPage field for the SEP record. - */ - public int getXaPage() - { - return field_39_xaPage; - } - - /** - * Set the xaPage field for the SEP record. - */ - public void setXaPage(int field_39_xaPage) - { - this.field_39_xaPage = field_39_xaPage; - } - - /** - * Get the yaPage field for the SEP record. - */ - public int getYaPage() - { - return field_40_yaPage; - } - - /** - * Set the yaPage field for the SEP record. - */ - public void setYaPage(int field_40_yaPage) - { - this.field_40_yaPage = field_40_yaPage; - } - - /** - * Get the xaPageNUp field for the SEP record. - */ - public int getXaPageNUp() - { - return field_41_xaPageNUp; - } - - /** - * Set the xaPageNUp field for the SEP record. - */ - public void setXaPageNUp(int field_41_xaPageNUp) - { - this.field_41_xaPageNUp = field_41_xaPageNUp; - } - - /** - * Get the yaPageNUp field for the SEP record. - */ - public int getYaPageNUp() - { - return field_42_yaPageNUp; - } - - /** - * Set the yaPageNUp field for the SEP record. - */ - public void setYaPageNUp(int field_42_yaPageNUp) - { - this.field_42_yaPageNUp = field_42_yaPageNUp; - } - - /** - * Get the dxaLeft field for the SEP record. - */ - public int getDxaLeft() - { - return field_43_dxaLeft; - } - - /** - * Set the dxaLeft field for the SEP record. - */ - public void setDxaLeft(int field_43_dxaLeft) - { - this.field_43_dxaLeft = field_43_dxaLeft; - } - - /** - * Get the dxaRight field for the SEP record. - */ - public int getDxaRight() - { - return field_44_dxaRight; - } - - /** - * Set the dxaRight field for the SEP record. - */ - public void setDxaRight(int field_44_dxaRight) - { - this.field_44_dxaRight = field_44_dxaRight; - } - - /** - * Get the dyaTop field for the SEP record. - */ - public int getDyaTop() - { - return field_45_dyaTop; - } - - /** - * Set the dyaTop field for the SEP record. - */ - public void setDyaTop(int field_45_dyaTop) - { - this.field_45_dyaTop = field_45_dyaTop; - } - - /** - * Get the dyaBottom field for the SEP record. - */ - public int getDyaBottom() - { - return field_46_dyaBottom; - } - - /** - * Set the dyaBottom field for the SEP record. - */ - public void setDyaBottom(int field_46_dyaBottom) - { - this.field_46_dyaBottom = field_46_dyaBottom; - } - - /** - * Get the dzaGutter field for the SEP record. - */ - public int getDzaGutter() - { - return field_47_dzaGutter; - } - - /** - * Set the dzaGutter field for the SEP record. - */ - public void setDzaGutter(int field_47_dzaGutter) - { - this.field_47_dzaGutter = field_47_dzaGutter; - } - - /** - * Get the dyaHdrTop field for the SEP record. - */ - public int getDyaHdrTop() - { - return field_48_dyaHdrTop; - } - - /** - * Set the dyaHdrTop field for the SEP record. - */ - public void setDyaHdrTop(int field_48_dyaHdrTop) - { - this.field_48_dyaHdrTop = field_48_dyaHdrTop; - } - - /** - * Get the dyaHdrBottom field for the SEP record. - */ - public int getDyaHdrBottom() - { - return field_49_dyaHdrBottom; - } - - /** - * Set the dyaHdrBottom field for the SEP record. - */ - public void setDyaHdrBottom(int field_49_dyaHdrBottom) - { - this.field_49_dyaHdrBottom = field_49_dyaHdrBottom; - } - - /** - * Get the ccolM1 field for the SEP record. - */ - public int getCcolM1() - { - return field_50_ccolM1; - } - - /** - * Set the ccolM1 field for the SEP record. - */ - public void setCcolM1(int field_50_ccolM1) - { - this.field_50_ccolM1 = field_50_ccolM1; - } - - /** - * Get the fEvenlySpaced field for the SEP record. - */ - public boolean getFEvenlySpaced() - { - return field_51_fEvenlySpaced; - } - - /** - * Set the fEvenlySpaced field for the SEP record. - */ - public void setFEvenlySpaced(boolean field_51_fEvenlySpaced) - { - this.field_51_fEvenlySpaced = field_51_fEvenlySpaced; - } - - /** - * Get the unused5 field for the SEP record. - */ - public byte getUnused5() - { - return field_52_unused5; - } - - /** - * Set the unused5 field for the SEP record. - */ - public void setUnused5(byte field_52_unused5) - { - this.field_52_unused5 = field_52_unused5; - } - - /** - * Get the dxaColumns field for the SEP record. - */ - public int getDxaColumns() - { - return field_53_dxaColumns; - } - - /** - * Set the dxaColumns field for the SEP record. - */ - public void setDxaColumns(int field_53_dxaColumns) - { - this.field_53_dxaColumns = field_53_dxaColumns; - } - - /** - * Get the rgdxaColumn field for the SEP record. - */ - public int[] getRgdxaColumn() - { - return field_54_rgdxaColumn; - } - - /** - * Set the rgdxaColumn field for the SEP record. - */ - public void setRgdxaColumn(int[] field_54_rgdxaColumn) - { - this.field_54_rgdxaColumn = field_54_rgdxaColumn; - } - - /** - * Get the dxaColumnWidth field for the SEP record. - */ - public int getDxaColumnWidth() - { - return field_55_dxaColumnWidth; - } - - /** - * Set the dxaColumnWidth field for the SEP record. - */ - public void setDxaColumnWidth(int field_55_dxaColumnWidth) - { - this.field_55_dxaColumnWidth = field_55_dxaColumnWidth; - } - - /** - * Get the dmOrientFirst field for the SEP record. - */ - public byte getDmOrientFirst() - { - return field_56_dmOrientFirst; - } - - /** - * Set the dmOrientFirst field for the SEP record. - */ - public void setDmOrientFirst(byte field_56_dmOrientFirst) - { - this.field_56_dmOrientFirst = field_56_dmOrientFirst; - } - - /** - * Get the fLayout field for the SEP record. - */ - public byte getFLayout() - { - return field_57_fLayout; - } - - /** - * Set the fLayout field for the SEP record. - */ - public void setFLayout(byte field_57_fLayout) - { - this.field_57_fLayout = field_57_fLayout; - } - - /** - * Get the unused6 field for the SEP record. - */ - public short getUnused6() - { - return field_58_unused6; - } - - /** - * Set the unused6 field for the SEP record. - */ - public void setUnused6(short field_58_unused6) - { - this.field_58_unused6 = field_58_unused6; - } - - /** - * Get the olstAnm field for the SEP record. - */ - public byte[] getOlstAnm() - { - return field_59_olstAnm; - } - - /** - * Set the olstAnm field for the SEP record. - */ - public void setOlstAnm(byte[] field_59_olstAnm) - { - this.field_59_olstAnm = field_59_olstAnm; - } - -} // END OF CLASS diff --git a/src/scratchpad/src/org/apache/poi/hwpf/model/types/SHD80AbstractType.java b/src/scratchpad/src/org/apache/poi/hwpf/model/types/SHD80AbstractType.java deleted file mode 100644 index 1a617073d..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/model/types/SHD80AbstractType.java +++ /dev/null @@ -1,194 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.model.types; - -import org.apache.poi.util.BitField; -import org.apache.poi.util.Internal; -import org.apache.poi.util.LittleEndian; - -/** - * The Shd80 structure specifies the colors and pattern that are used for background - shading. As an exception to the constraints that are specified by Ico and Ipat, a Shd80 can - be set to Shd80Nil and specifies that no shading is applied.

    Class and fields - descriptions are quoted from Word (.doc) Binary File Format by Microsoft Corporation - - *

    - * NOTE: This source is automatically generated please do not modify this file. Either subclass or - * remove the record in src/types/definitions. - *

    - * This class is internal. It content or properties may change without notice - * due to changes in our knowledge of internal Microsoft Word binary structures. - - * @author Sergey Vladimirov; according to Word (.doc) Binary File Format by Microsoft Corporation. - - */ -@Internal -public abstract class SHD80AbstractType -{ - - protected short field_1_value; - /**/private static final BitField icoFore = new BitField(0x001F); - /**/private static final BitField icoBack = new BitField(0x03E0); - /**/private static final BitField ipat = new BitField(0xFC00); - - protected SHD80AbstractType() - { - } - - protected void fillFields( byte[] data, int offset ) - { - field_1_value = LittleEndian.getShort( data, 0x0 + offset ); - } - - public void serialize( byte[] data, int offset ) - { - LittleEndian.putShort( data, 0x0 + offset, field_1_value ); - } - - public byte[] serialize() - { - final byte[] result = new byte[ getSize() ]; - serialize( result, 0 ); - return result; - } - - /** - * Size of record - */ - public static int getSize() - { - return 0 + 2; - } - - @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - return true; - if ( obj == null ) - return false; - if ( getClass() != obj.getClass() ) - return false; - SHD80AbstractType other = (SHD80AbstractType) obj; - if ( field_1_value != other.field_1_value ) - return false; - return true; - } - - @Override - public int hashCode() - { - final int prime = 31; - int result = 1; - result = prime * result + field_1_value; - return result; - } - - public String toString() - { - StringBuilder builder = new StringBuilder(); - builder.append("[SHD80]\n"); - builder.append(" .value = "); - builder.append(" (").append(getValue()).append(" )\n"); - builder.append(" .icoFore = ").append(getIcoFore()).append('\n'); - builder.append(" .icoBack = ").append(getIcoBack()).append('\n'); - builder.append(" .ipat = ").append(getIpat()).append('\n'); - - builder.append("[/SHD80]\n"); - return builder.toString(); - } - - /** - * Get the value field for the SHD80 record. - */ - @Internal - public short getValue() - { - return field_1_value; - } - - /** - * Set the value field for the SHD80 record. - */ - @Internal - public void setValue( short field_1_value ) - { - this.field_1_value = field_1_value; - } - - /** - * Sets the icoFore field value. - * Foreground color - */ - @Internal - public void setIcoFore( byte value ) - { - field_1_value = (short)icoFore.setValue(field_1_value, value); - } - - /** - * Foreground color - * @return the icoFore field value. - */ - @Internal - public byte getIcoFore() - { - return ( byte )icoFore.getValue(field_1_value); - } - - /** - * Sets the icoBack field value. - * Background color - */ - @Internal - public void setIcoBack( byte value ) - { - field_1_value = (short)icoBack.setValue(field_1_value, value); - } - - /** - * Background color - * @return the icoBack field value. - */ - @Internal - public byte getIcoBack() - { - return ( byte )icoBack.getValue(field_1_value); - } - - /** - * Sets the ipat field value. - * Shading pattern - */ - @Internal - public void setIpat( byte value ) - { - field_1_value = (short)ipat.setValue(field_1_value, value); - } - - /** - * Shading pattern - * @return the ipat field value. - */ - @Internal - public byte getIpat() - { - return ( byte )ipat.getValue(field_1_value); - } - -} // END OF CLASS diff --git a/src/scratchpad/src/org/apache/poi/hwpf/model/types/SHDAbstractType.java b/src/scratchpad/src/org/apache/poi/hwpf/model/types/SHDAbstractType.java deleted file mode 100644 index 13603ae7b..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/model/types/SHDAbstractType.java +++ /dev/null @@ -1,182 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.model.types; - - -import org.apache.poi.hwpf.model.Colorref; -import org.apache.poi.util.Internal; -import org.apache.poi.util.LittleEndian; - -/** - * The Shd structure specifies the colors and pattern that are used for background shading.

    Class - and - fields descriptions are quoted from Word (.doc) Binary File Format by Microsoft Corporation - - *

    - * NOTE: This source is automatically generated please do not modify this file. Either subclass or - * remove the record in src/types/definitions. - *

    - * This class is internal. It content or properties may change without notice - * due to changes in our knowledge of internal Microsoft Word binary structures. - - * @author Sergey Vladimirov; according to Word (.doc) Binary File Format by Microsoft Corporation. - - */ -@Internal -public abstract class SHDAbstractType -{ - - protected Colorref field_1_cvFore; - protected Colorref field_2_cvBack; - protected int field_3_ipat; - - protected SHDAbstractType() - { - this.field_1_cvFore = new Colorref(); - this.field_2_cvBack = new Colorref(); - } - - protected void fillFields( byte[] data, int offset ) - { - field_1_cvFore = new Colorref( data, 0x0 + offset ); - field_2_cvBack = new Colorref( data, 0x4 + offset ); - field_3_ipat = LittleEndian.getShort( data, 0x8 + offset ); - } - - public void serialize( byte[] data, int offset ) - { - field_1_cvFore.serialize( data, 0x0 + offset ); - field_2_cvBack.serialize( data, 0x4 + offset ); - LittleEndian.putUShort( data, 0x8 + offset, field_3_ipat ); - } - - public byte[] serialize() - { - final byte[] result = new byte[ getSize() ]; - serialize( result, 0 ); - return result; - } - - /** - * Size of record - */ - public static int getSize() - { - return 0 + 4 + 4 + 2; - } - - @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - return true; - if ( obj == null ) - return false; - if ( getClass() != obj.getClass() ) - return false; - SHDAbstractType other = (SHDAbstractType) obj; - if ( field_1_cvFore != other.field_1_cvFore ) - return false; - if ( field_2_cvBack != other.field_2_cvBack ) - return false; - if ( field_3_ipat != other.field_3_ipat ) - return false; - return true; - } - - @Override - public int hashCode() - { - final int prime = 31; - int result = 1; - result = prime * result + field_1_cvFore.hashCode(); - result = prime * result + field_2_cvBack.hashCode(); - result = prime * result + field_3_ipat; - return result; - } - - public String toString() - { - StringBuilder builder = new StringBuilder(); - builder.append("[SHD]\n"); - builder.append(" .cvFore = "); - builder.append(" (").append(getCvFore()).append(" )\n"); - builder.append(" .cvBack = "); - builder.append(" (").append(getCvBack()).append(" )\n"); - builder.append(" .ipat = "); - builder.append(" (").append(getIpat()).append(" )\n"); - - builder.append("[/SHD]\n"); - return builder.toString(); - } - - /** - * A COLORREF that specifies the foreground color of ipat. - */ - @Internal - public Colorref getCvFore() - { - return field_1_cvFore; - } - - /** - * A COLORREF that specifies the foreground color of ipat. - */ - @Internal - public void setCvFore( Colorref field_1_cvFore ) - { - this.field_1_cvFore = field_1_cvFore; - } - - /** - * A COLORREF that specifies the background color of ipat. - */ - @Internal - public Colorref getCvBack() - { - return field_2_cvBack; - } - - /** - * A COLORREF that specifies the background color of ipat. - */ - @Internal - public void setCvBack( Colorref field_2_cvBack ) - { - this.field_2_cvBack = field_2_cvBack; - } - - /** - * An Ipat that specifies the pattern used for shading. - */ - @Internal - public int getIpat() - { - return field_3_ipat; - } - - /** - * An Ipat that specifies the pattern used for shading. - */ - @Internal - public void setIpat( int field_3_ipat ) - { - this.field_3_ipat = field_3_ipat; - } - -} // END OF CLASS diff --git a/src/scratchpad/src/org/apache/poi/hwpf/model/types/StdfBaseAbstractType.java b/src/scratchpad/src/org/apache/poi/hwpf/model/types/StdfBaseAbstractType.java deleted file mode 100644 index 8282e3893..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/model/types/StdfBaseAbstractType.java +++ /dev/null @@ -1,695 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.model.types; - -import org.apache.poi.util.BitField; -import org.apache.poi.util.Internal; -import org.apache.poi.util.LittleEndian; - -/** - * The StdfBase structure specifies general information about a style.

    Class - and fields descriptions are quoted from Microsoft Office Word 97-2007 Binary File Format and - [MS-DOC] - v20110608 Word (.doc) Binary File Format - - *

    - * NOTE: This source is automatically generated please do not modify this file. Either subclass or - * remove the record in src/types/definitions. - *

    - * This class is internal. It content or properties may change without notice - * due to changes in our knowledge of internal Microsoft Word binary structures. - - * @author Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary File Format - Specification [*.doc] and [MS-DOC] - v20110608 Word (.doc) Binary File Format - - */ -@Internal -public abstract class StdfBaseAbstractType -{ - - protected short field_1_info1; - /**/private static final BitField sti = new BitField(0x0FFF); - /**/private static final BitField fScratch = new BitField(0x1000); - /**/private static final BitField fInvalHeight = new BitField(0x2000); - /**/private static final BitField fHasUpe = new BitField(0x4000); - /**/private static final BitField fMassCopy = new BitField(0x8000); - protected short field_2_info2; - /**/private static final BitField stk = new BitField(0x000F); - /**/private static final BitField istdBase = new BitField(0xFFF0); - protected short field_3_info3; - /**/private static final BitField cupx = new BitField(0x000F); - /**/private static final BitField istdNext = new BitField(0xFFF0); - protected int field_4_bchUpe; - protected short field_5_grfstd; - /**/private static final BitField fAutoRedef = new BitField(0x0001); - /**/private static final BitField fHidden = new BitField(0x0002); - /**/private static final BitField f97LidsSet = new BitField(0x0004); - /**/private static final BitField fCopyLang = new BitField(0x0008); - /**/private static final BitField fPersonalCompose = new BitField(0x0010); - /**/private static final BitField fPersonalReply = new BitField(0x0020); - /**/private static final BitField fPersonal = new BitField(0x0040); - /**/private static final BitField fNoHtmlExport = new BitField(0x0080); - /**/private static final BitField fSemiHidden = new BitField(0x0100); - /**/private static final BitField fLocked = new BitField(0x0200); - /**/private static final BitField fInternalUse = new BitField(0x0400); - /**/private static final BitField fUnhideWhenUsed = new BitField(0x0800); - /**/private static final BitField fQFormat = new BitField(0x1000); - /**/private static final BitField fReserved = new BitField(0xE000); - - protected StdfBaseAbstractType() - { - } - - protected void fillFields( byte[] data, int offset ) - { - field_1_info1 = LittleEndian.getShort(data, 0x0 + offset); - field_2_info2 = LittleEndian.getShort(data, 0x2 + offset); - field_3_info3 = LittleEndian.getShort(data, 0x4 + offset); - field_4_bchUpe = LittleEndian.getShort(data, 0x6 + offset); - field_5_grfstd = LittleEndian.getShort(data, 0x8 + offset); - } - - public void serialize( byte[] data, int offset ) - { - LittleEndian.putShort(data, 0x0 + offset, field_1_info1); - LittleEndian.putShort(data, 0x2 + offset, field_2_info2); - LittleEndian.putShort(data, 0x4 + offset, field_3_info3); - LittleEndian.putUShort(data, 0x6 + offset, field_4_bchUpe); - LittleEndian.putShort(data, 0x8 + offset, field_5_grfstd); - } - - /** - * Size of record - */ - public static int getSize() - { - return 0 + 2 + 2 + 2 + 2 + 2; - } - - public String toString() - { - StringBuilder builder = new StringBuilder(); - builder.append("[StdfBase]\n"); - builder.append(" .info1 = "); - builder.append(" (").append(getInfo1()).append(" )\n"); - builder.append(" .sti = ").append(getSti()).append('\n'); - builder.append(" .fScratch = ").append(isFScratch()).append('\n'); - builder.append(" .fInvalHeight = ").append(isFInvalHeight()).append('\n'); - builder.append(" .fHasUpe = ").append(isFHasUpe()).append('\n'); - builder.append(" .fMassCopy = ").append(isFMassCopy()).append('\n'); - builder.append(" .info2 = "); - builder.append(" (").append(getInfo2()).append(" )\n"); - builder.append(" .stk = ").append(getStk()).append('\n'); - builder.append(" .istdBase = ").append(getIstdBase()).append('\n'); - builder.append(" .info3 = "); - builder.append(" (").append(getInfo3()).append(" )\n"); - builder.append(" .cupx = ").append(getCupx()).append('\n'); - builder.append(" .istdNext = ").append(getIstdNext()).append('\n'); - builder.append(" .bchUpe = "); - builder.append(" (").append(getBchUpe()).append(" )\n"); - builder.append(" .grfstd = "); - builder.append(" (").append(getGrfstd()).append(" )\n"); - builder.append(" .fAutoRedef = ").append(isFAutoRedef()).append('\n'); - builder.append(" .fHidden = ").append(isFHidden()).append('\n'); - builder.append(" .f97LidsSet = ").append(isF97LidsSet()).append('\n'); - builder.append(" .fCopyLang = ").append(isFCopyLang()).append('\n'); - builder.append(" .fPersonalCompose = ").append(isFPersonalCompose()).append('\n'); - builder.append(" .fPersonalReply = ").append(isFPersonalReply()).append('\n'); - builder.append(" .fPersonal = ").append(isFPersonal()).append('\n'); - builder.append(" .fNoHtmlExport = ").append(isFNoHtmlExport()).append('\n'); - builder.append(" .fSemiHidden = ").append(isFSemiHidden()).append('\n'); - builder.append(" .fLocked = ").append(isFLocked()).append('\n'); - builder.append(" .fInternalUse = ").append(isFInternalUse()).append('\n'); - builder.append(" .fUnhideWhenUsed = ").append(isFUnhideWhenUsed()).append('\n'); - builder.append(" .fQFormat = ").append(isFQFormat()).append('\n'); - builder.append(" .fReserved = ").append(getFReserved()).append('\n'); - - builder.append("[/StdfBase]\n"); - return builder.toString(); - } - - /** - * Get the info1 field for the StdfBase record. - */ - @Internal - public short getInfo1() - { - return field_1_info1; - } - - /** - * Set the info1 field for the StdfBase record. - */ - @Internal - public void setInfo1( short field_1_info1 ) - { - this.field_1_info1 = field_1_info1; - } - - /** - * Get the info2 field for the StdfBase record. - */ - @Internal - public short getInfo2() - { - return field_2_info2; - } - - /** - * Set the info2 field for the StdfBase record. - */ - @Internal - public void setInfo2( short field_2_info2 ) - { - this.field_2_info2 = field_2_info2; - } - - /** - * Get the info3 field for the StdfBase record. - */ - @Internal - public short getInfo3() - { - return field_3_info3; - } - - /** - * Set the info3 field for the StdfBase record. - */ - @Internal - public void setInfo3( short field_3_info3 ) - { - this.field_3_info3 = field_3_info3; - } - - /** - * An unsigned integer that specifies the size, in bytes, of std in LPStd. This value MUST be equal to cbStd in LPStd. - */ - @Internal - public int getBchUpe() - { - return field_4_bchUpe; - } - - /** - * An unsigned integer that specifies the size, in bytes, of std in LPStd. This value MUST be equal to cbStd in LPStd. - */ - @Internal - public void setBchUpe( int field_4_bchUpe ) - { - this.field_4_bchUpe = field_4_bchUpe; - } - - /** - * A GRFSTD that specifies miscellaneous style properties. - */ - @Internal - public short getGrfstd() - { - return field_5_grfstd; - } - - /** - * A GRFSTD that specifies miscellaneous style properties. - */ - @Internal - public void setGrfstd( short field_5_grfstd ) - { - this.field_5_grfstd = field_5_grfstd; - } - - /** - * Sets the sti field value. - * An unsigned integer that specifies the invariant style identifier for application-defined styles, or 0x0FFE for user-defined styles - */ - @Internal - public void setSti( short value ) - { - field_1_info1 = (short)sti.setValue(field_1_info1, value); - } - - /** - * An unsigned integer that specifies the invariant style identifier for application-defined styles, or 0x0FFE for user-defined styles - * @return the sti field value. - */ - @Internal - public short getSti() - { - return ( short )sti.getValue(field_1_info1); - } - - /** - * Sets the fScratch field value. - * spare field for any temporary use, always reset back to zero! - */ - @Internal - public void setFScratch( boolean value ) - { - field_1_info1 = (short)fScratch.setBoolean(field_1_info1, value); - } - - /** - * spare field for any temporary use, always reset back to zero! - * @return the fScratch field value. - */ - @Internal - public boolean isFScratch() - { - return fScratch.isSet(field_1_info1); - } - - /** - * Sets the fInvalHeight field value. - * Specifies whether the paragraph height information in the fcPlcfPhe field of FibRgFcLcb97, for any paragraphs having this paragraph style, MUST be ignored. SHOULD be 0 - */ - @Internal - public void setFInvalHeight( boolean value ) - { - field_1_info1 = (short)fInvalHeight.setBoolean(field_1_info1, value); - } - - /** - * Specifies whether the paragraph height information in the fcPlcfPhe field of FibRgFcLcb97, for any paragraphs having this paragraph style, MUST be ignored. SHOULD be 0 - * @return the fInvalHeight field value. - */ - @Internal - public boolean isFInvalHeight() - { - return fInvalHeight.isSet(field_1_info1); - } - - /** - * Sets the fHasUpe field value. - * This bit is undefined and MUST be ignored - */ - @Internal - public void setFHasUpe( boolean value ) - { - field_1_info1 = (short)fHasUpe.setBoolean(field_1_info1, value); - } - - /** - * This bit is undefined and MUST be ignored - * @return the fHasUpe field value. - */ - @Internal - public boolean isFHasUpe() - { - return fHasUpe.isSet(field_1_info1); - } - - /** - * Sets the fMassCopy field value. - * This bit is undefined and MUST be ignored - */ - @Internal - public void setFMassCopy( boolean value ) - { - field_1_info1 = (short)fMassCopy.setBoolean(field_1_info1, value); - } - - /** - * This bit is undefined and MUST be ignored - * @return the fMassCopy field value. - */ - @Internal - public boolean isFMassCopy() - { - return fMassCopy.isSet(field_1_info1); - } - - /** - * Sets the stk field value. - * style kind - */ - @Internal - public void setStk( byte value ) - { - field_2_info2 = (short)stk.setValue(field_2_info2, value); - } - - /** - * style kind - * @return the stk field value. - */ - @Internal - public byte getStk() - { - return ( byte )stk.getValue(field_2_info2); - } - - /** - * Sets the istdBase field value. - * base style - */ - @Internal - public void setIstdBase( short value ) - { - field_2_info2 = (short)istdBase.setValue(field_2_info2, value); - } - - /** - * base style - * @return the istdBase field value. - */ - @Internal - public short getIstdBase() - { - return ( short )istdBase.getValue(field_2_info2); - } - - /** - * Sets the cupx field value. - * number of UPXs (and UPEs) - */ - @Internal - public void setCupx( byte value ) - { - field_3_info3 = (short)cupx.setValue(field_3_info3, value); - } - - /** - * number of UPXs (and UPEs) - * @return the cupx field value. - */ - @Internal - public byte getCupx() - { - return ( byte )cupx.getValue(field_3_info3); - } - - /** - * Sets the istdNext field value. - * next style - */ - @Internal - public void setIstdNext( short value ) - { - field_3_info3 = (short)istdNext.setValue(field_3_info3, value); - } - - /** - * next style - * @return the istdNext field value. - */ - @Internal - public short getIstdNext() - { - return ( short )istdNext.getValue(field_3_info3); - } - - /** - * Sets the fAutoRedef field value. - * number of UPXs (and UPEs) - */ - @Internal - public void setFAutoRedef( boolean value ) - { - field_5_grfstd = (short)fAutoRedef.setBoolean(field_5_grfstd, value); - } - - /** - * number of UPXs (and UPEs) - * @return the fAutoRedef field value. - */ - @Internal - public boolean isFAutoRedef() - { - return fAutoRedef.isSet(field_5_grfstd); - } - - /** - * Sets the fHidden field value. - * Specifies whether this style is not shown in the application UI - */ - @Internal - public void setFHidden( boolean value ) - { - field_5_grfstd = (short)fHidden.setBoolean(field_5_grfstd, value); - } - - /** - * Specifies whether this style is not shown in the application UI - * @return the fHidden field value. - */ - @Internal - public boolean isFHidden() - { - return fHidden.isSet(field_5_grfstd); - } - - /** - * Sets the f97LidsSet field value. - * Specifies whether sprmCRgLid0_80 and sprmCRgLid1_80 were applied, as appropriate, to this paragraph or character style for compatibility with applications that do not support sprmCRgLid0, sprmCRgLid1, and sprmCFNoProof - */ - @Internal - public void setF97LidsSet( boolean value ) - { - field_5_grfstd = (short)f97LidsSet.setBoolean(field_5_grfstd, value); - } - - /** - * Specifies whether sprmCRgLid0_80 and sprmCRgLid1_80 were applied, as appropriate, to this paragraph or character style for compatibility with applications that do not support sprmCRgLid0, sprmCRgLid1, and sprmCFNoProof - * @return the f97LidsSet field value. - */ - @Internal - public boolean isF97LidsSet() - { - return f97LidsSet.isSet(field_5_grfstd); - } - - /** - * Sets the fCopyLang field value. - * If f97LidsSet is 1, this value specifies whether the applied compatibility sprmCRgLid0_80 or sprmCRgLid1_80 specified an actual language or a special LID value (0x0400) signifying that no proofing is needed for the text. This MUST be ignored if f97LidsSet is 0 - */ - @Internal - public void setFCopyLang( boolean value ) - { - field_5_grfstd = (short)fCopyLang.setBoolean(field_5_grfstd, value); - } - - /** - * If f97LidsSet is 1, this value specifies whether the applied compatibility sprmCRgLid0_80 or sprmCRgLid1_80 specified an actual language or a special LID value (0x0400) signifying that no proofing is needed for the text. This MUST be ignored if f97LidsSet is 0 - * @return the fCopyLang field value. - */ - @Internal - public boolean isFCopyLang() - { - return fCopyLang.isSet(field_5_grfstd); - } - - /** - * Sets the fPersonalCompose field value. - * Specifies whether this character style can be used to automatically format the new message text in a new e-mail - */ - @Internal - public void setFPersonalCompose( boolean value ) - { - field_5_grfstd = (short)fPersonalCompose.setBoolean(field_5_grfstd, value); - } - - /** - * Specifies whether this character style can be used to automatically format the new message text in a new e-mail - * @return the fPersonalCompose field value. - */ - @Internal - public boolean isFPersonalCompose() - { - return fPersonalCompose.isSet(field_5_grfstd); - } - - /** - * Sets the fPersonalReply field value. - * Specifies whether this character style can be used to automatically format the new message text when replying to an e-mail - */ - @Internal - public void setFPersonalReply( boolean value ) - { - field_5_grfstd = (short)fPersonalReply.setBoolean(field_5_grfstd, value); - } - - /** - * Specifies whether this character style can be used to automatically format the new message text when replying to an e-mail - * @return the fPersonalReply field value. - */ - @Internal - public boolean isFPersonalReply() - { - return fPersonalReply.isSet(field_5_grfstd); - } - - /** - * Sets the fPersonal field value. - * Specifies whether this character style was applied to format all message text from one or more users in an e-mail - */ - @Internal - public void setFPersonal( boolean value ) - { - field_5_grfstd = (short)fPersonal.setBoolean(field_5_grfstd, value); - } - - /** - * Specifies whether this character style was applied to format all message text from one or more users in an e-mail - * @return the fPersonal field value. - */ - @Internal - public boolean isFPersonal() - { - return fPersonal.isSet(field_5_grfstd); - } - - /** - * Sets the fNoHtmlExport field value. - * This value MUST be 0 and MUST be ignored - */ - @Internal - public void setFNoHtmlExport( boolean value ) - { - field_5_grfstd = (short)fNoHtmlExport.setBoolean(field_5_grfstd, value); - } - - /** - * This value MUST be 0 and MUST be ignored - * @return the fNoHtmlExport field value. - */ - @Internal - public boolean isFNoHtmlExport() - { - return fNoHtmlExport.isSet(field_5_grfstd); - } - - /** - * Sets the fSemiHidden field value. - * Specifies whether this style is not shown in the simplified main styles UI of the application - */ - @Internal - public void setFSemiHidden( boolean value ) - { - field_5_grfstd = (short)fSemiHidden.setBoolean(field_5_grfstd, value); - } - - /** - * Specifies whether this style is not shown in the simplified main styles UI of the application - * @return the fSemiHidden field value. - */ - @Internal - public boolean isFSemiHidden() - { - return fSemiHidden.isSet(field_5_grfstd); - } - - /** - * Sets the fLocked field value. - * Specifies whether this style is prevented from being applied by using the application UI - */ - @Internal - public void setFLocked( boolean value ) - { - field_5_grfstd = (short)fLocked.setBoolean(field_5_grfstd, value); - } - - /** - * Specifies whether this style is prevented from being applied by using the application UI - * @return the fLocked field value. - */ - @Internal - public boolean isFLocked() - { - return fLocked.isSet(field_5_grfstd); - } - - /** - * Sets the fInternalUse field value. - * This bit is undefined and MUST be ignored - */ - @Internal - public void setFInternalUse( boolean value ) - { - field_5_grfstd = (short)fInternalUse.setBoolean(field_5_grfstd, value); - } - - /** - * This bit is undefined and MUST be ignored - * @return the fInternalUse field value. - */ - @Internal - public boolean isFInternalUse() - { - return fInternalUse.isSet(field_5_grfstd); - } - - /** - * Sets the fUnhideWhenUsed field value. - * Specifies whether the fSemiHidden property is to be set to 0 when this style is used - */ - @Internal - public void setFUnhideWhenUsed( boolean value ) - { - field_5_grfstd = (short)fUnhideWhenUsed.setBoolean(field_5_grfstd, value); - } - - /** - * Specifies whether the fSemiHidden property is to be set to 0 when this style is used - * @return the fUnhideWhenUsed field value. - */ - @Internal - public boolean isFUnhideWhenUsed() - { - return fUnhideWhenUsed.isSet(field_5_grfstd); - } - - /** - * Sets the fQFormat field value. - * Specifies whether this style is shown in the Ribbon Style gallery - */ - @Internal - public void setFQFormat( boolean value ) - { - field_5_grfstd = (short)fQFormat.setBoolean(field_5_grfstd, value); - } - - /** - * Specifies whether this style is shown in the Ribbon Style gallery - * @return the fQFormat field value. - */ - @Internal - public boolean isFQFormat() - { - return fQFormat.isSet(field_5_grfstd); - } - - /** - * Sets the fReserved field value. - * This value MUST be 0 and MUST be ignored - */ - @Internal - public void setFReserved( byte value ) - { - field_5_grfstd = (short)fReserved.setValue(field_5_grfstd, value); - } - - /** - * This value MUST be 0 and MUST be ignored - * @return the fReserved field value. - */ - @Internal - public byte getFReserved() - { - return ( byte )fReserved.getValue(field_5_grfstd); - } - -} // END OF CLASS diff --git a/src/scratchpad/src/org/apache/poi/hwpf/model/types/StdfPost2000AbstractType.java b/src/scratchpad/src/org/apache/poi/hwpf/model/types/StdfPost2000AbstractType.java deleted file mode 100644 index 26e5fd68f..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/model/types/StdfPost2000AbstractType.java +++ /dev/null @@ -1,274 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hwpf.model.types; - -import org.apache.poi.util.BitField; -import org.apache.poi.util.Internal; -import org.apache.poi.util.LittleEndian; - -/** - * The StdfPost2000 structure specifies general information about a style. -

    Class and fields descriptions are quoted from Microsoft Office Word 97-2007 Binary - File Format and [MS-DOC] - v20110608 Word (.doc) Binary File Format - - *

    - * NOTE: This source is automatically generated please do not modify this file. Either subclass or - * remove the record in src/types/definitions. - *

    - * This class is internal. It content or properties may change without notice - * due to changes in our knowledge of internal Microsoft Word binary structures. - - * @author Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary File Format - Specification [*.doc] and [MS-DOC] - v20110608 Word (.doc) Binary File Format - - */ -@Internal -public abstract class StdfPost2000AbstractType -{ - - protected short field_1_info1; - /**/private static final BitField istdLink = new BitField(0x0FFF); - /**/private static final BitField fHasOriginalStyle = new BitField(0x1000); - /**/private static final BitField fSpare = new BitField(0xE000); - protected long field_2_rsid; - protected short field_3_info3; - /**/private static final BitField iftcHtml = new BitField(0x0007); - /**/private static final BitField unused = new BitField(0x0008); - /**/private static final BitField iPriority = new BitField(0xFFF0); - - protected StdfPost2000AbstractType() - { - } - - protected void fillFields( byte[] data, int offset ) - { - field_1_info1 = LittleEndian.getShort(data, 0x0 + offset); - field_2_rsid = LittleEndian.getUInt(data, 0x2 + offset); - field_3_info3 = LittleEndian.getShort(data, 0x6 + offset); - } - - public void serialize( byte[] data, int offset ) - { - LittleEndian.putShort(data, 0x0 + offset, field_1_info1); - LittleEndian.putUInt(data, 0x2 + offset, field_2_rsid); - LittleEndian.putShort(data, 0x6 + offset, field_3_info3); - } - - /** - * Size of record - */ - public static int getSize() - { - return 0 + 2 + 4 + 2; - } - - public String toString() - { - StringBuilder builder = new StringBuilder(); - builder.append("[StdfPost2000]\n"); - builder.append(" .info1 = "); - builder.append(" (").append(getInfo1()).append(" )\n"); - builder.append(" .istdLink = ").append(getIstdLink()).append('\n'); - builder.append(" .fHasOriginalStyle = ").append(isFHasOriginalStyle()).append('\n'); - builder.append(" .fSpare = ").append(getFSpare()).append('\n'); - builder.append(" .rsid = "); - builder.append(" (").append(getRsid()).append(" )\n"); - builder.append(" .info3 = "); - builder.append(" (").append(getInfo3()).append(" )\n"); - builder.append(" .iftcHtml = ").append(getIftcHtml()).append('\n'); - builder.append(" .unused = ").append(isUnused()).append('\n'); - builder.append(" .iPriority = ").append(getIPriority()).append('\n'); - - builder.append("[/StdfPost2000]\n"); - return builder.toString(); - } - - /** - * Get the info1 field for the StdfPost2000 record. - */ - @Internal - public short getInfo1() - { - return field_1_info1; - } - - /** - * Set the info1 field for the StdfPost2000 record. - */ - @Internal - public void setInfo1( short field_1_info1 ) - { - this.field_1_info1 = field_1_info1; - } - - /** - * An unsigned integer that specifies the revision save identifier of the session when this style definition was last modified. - */ - @Internal - public long getRsid() - { - return field_2_rsid; - } - - /** - * An unsigned integer that specifies the revision save identifier of the session when this style definition was last modified. - */ - @Internal - public void setRsid( long field_2_rsid ) - { - this.field_2_rsid = field_2_rsid; - } - - /** - * Get the info3 field for the StdfPost2000 record. - */ - @Internal - public short getInfo3() - { - return field_3_info3; - } - - /** - * Set the info3 field for the StdfPost2000 record. - */ - @Internal - public void setInfo3( short field_3_info3 ) - { - this.field_3_info3 = field_3_info3; - } - - /** - * Sets the istdLink field value. - * An unsigned integer that specifies the istd of the style that is linked to this one, or 0x0000 if this style is not linked to any other style in the document. - */ - @Internal - public void setIstdLink( short value ) - { - field_1_info1 = (short)istdLink.setValue(field_1_info1, value); - } - - /** - * An unsigned integer that specifies the istd of the style that is linked to this one, or 0x0000 if this style is not linked to any other style in the document. - * @return the istdLink field value. - */ - @Internal - public short getIstdLink() - { - return ( short )istdLink.getValue(field_1_info1); - } - - /** - * Sets the fHasOriginalStyle field value. - * Specifies whether the style is revision-marked. A revision-marked style stores the pre-revision formatting in addition to the current formatting. If this bit is set to 1, the cupx member of StdfBase MUST include the formatting sets that specify that pre-revision formatting - */ - @Internal - public void setFHasOriginalStyle( boolean value ) - { - field_1_info1 = (short)fHasOriginalStyle.setBoolean(field_1_info1, value); - } - - /** - * Specifies whether the style is revision-marked. A revision-marked style stores the pre-revision formatting in addition to the current formatting. If this bit is set to 1, the cupx member of StdfBase MUST include the formatting sets that specify that pre-revision formatting - * @return the fHasOriginalStyle field value. - */ - @Internal - public boolean isFHasOriginalStyle() - { - return fHasOriginalStyle.isSet(field_1_info1); - } - - /** - * Sets the fSpare field value. - * Specifies whether the paragraph height information in the fcPlcfPhe field of FibRgFcLcb97 - */ - @Internal - public void setFSpare( byte value ) - { - field_1_info1 = (short)fSpare.setValue(field_1_info1, value); - } - - /** - * Specifies whether the paragraph height information in the fcPlcfPhe field of FibRgFcLcb97 - * @return the fSpare field value. - */ - @Internal - public byte getFSpare() - { - return ( byte )fSpare.getValue(field_1_info1); - } - - /** - * Sets the iftcHtml field value. - * This field is undefined and MUST be ignored - */ - @Internal - public void setIftcHtml( byte value ) - { - field_3_info3 = (short)iftcHtml.setValue(field_3_info3, value); - } - - /** - * This field is undefined and MUST be ignored - * @return the iftcHtml field value. - */ - @Internal - public byte getIftcHtml() - { - return ( byte )iftcHtml.getValue(field_3_info3); - } - - /** - * Sets the unused field value. - * This value MUST be zero and MUST be ignored - */ - @Internal - public void setUnused( boolean value ) - { - field_3_info3 = (short)unused.setBoolean(field_3_info3, value); - } - - /** - * This value MUST be zero and MUST be ignored - * @return the unused field value. - */ - @Internal - public boolean isUnused() - { - return unused.isSet(field_3_info3); - } - - /** - * Sets the iPriority field value. - * An unsigned integer that specifies the priority value that is assigned to this style and that is used when ordering the styles by priority in the user interface - */ - @Internal - public void setIPriority( short value ) - { - field_3_info3 = (short)iPriority.setValue(field_3_info3, value); - } - - /** - * An unsigned integer that specifies the priority value that is assigned to this style and that is used when ordering the styles by priority in the user interface - * @return the iPriority field value. - */ - @Internal - public short getIPriority() - { - return ( short )iPriority.getValue(field_3_info3); - } - -} // END OF CLASS diff --git a/src/scratchpad/src/org/apache/poi/hwpf/model/types/StshifAbstractType.java b/src/scratchpad/src/org/apache/poi/hwpf/model/types/StshifAbstractType.java deleted file mode 100644 index 5b72d2e5c..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/model/types/StshifAbstractType.java +++ /dev/null @@ -1,325 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hwpf.model.types; - - -import org.apache.poi.util.BitField; -import org.apache.poi.util.Internal; -import org.apache.poi.util.LittleEndian; - -/** - * The Stshif structure specifies general stylesheet information.

    Class and - fields descriptions are quoted from Microsoft Office Word 97-2007 Binary File Format and - [MS-DOC] - v20110608 Word (.doc) Binary File Format - - *

    - * NOTE: This source is automatically generated please do not modify this file. Either subclass or - * remove the record in src/types/definitions. - *

    - * This class is internal. It content or properties may change without notice - * due to changes in our knowledge of internal Microsoft Word binary structures. - - * @author Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary File Format - Specification [*.doc] and [MS-DOC] - v20110608 Word (.doc) Binary File Format - - */ -@Internal -public abstract class StshifAbstractType -{ - - protected int field_1_cstd; - protected int field_2_cbSTDBaseInFile; - protected int field_3_info3; - /**/private static final BitField fHasOriginalStyle = new BitField(0x0001); - /**/private static final BitField fReserved = new BitField(0xFFFE); - protected int field_4_stiMaxWhenSaved; - protected int field_5_istdMaxFixedWhenSaved; - protected int field_6_nVerBuiltInNamesWhenSaved; - protected short field_7_ftcAsci; - protected short field_8_ftcFE; - protected short field_9_ftcOther; - - protected StshifAbstractType() - { - } - - protected void fillFields( byte[] data, int offset ) - { - field_1_cstd = LittleEndian.getShort(data, 0x0 + offset); - field_2_cbSTDBaseInFile = LittleEndian.getShort(data, 0x2 + offset); - field_3_info3 = LittleEndian.getShort(data, 0x4 + offset); - field_4_stiMaxWhenSaved = LittleEndian.getShort(data, 0x6 + offset); - field_5_istdMaxFixedWhenSaved = LittleEndian.getShort(data, 0x8 + offset); - field_6_nVerBuiltInNamesWhenSaved = LittleEndian.getShort(data, 0xa + offset); - field_7_ftcAsci = LittleEndian.getShort(data, 0xc + offset); - field_8_ftcFE = LittleEndian.getShort(data, 0xe + offset); - field_9_ftcOther = LittleEndian.getShort(data, 0x10 + offset); - } - - public void serialize( byte[] data, int offset ) - { - LittleEndian.putUShort(data, 0x0 + offset, field_1_cstd); - LittleEndian.putUShort(data, 0x2 + offset, field_2_cbSTDBaseInFile); - LittleEndian.putUShort(data, 0x4 + offset, field_3_info3); - LittleEndian.putUShort(data, 0x6 + offset, field_4_stiMaxWhenSaved); - LittleEndian.putUShort(data, 0x8 + offset, field_5_istdMaxFixedWhenSaved); - LittleEndian.putUShort(data, 0xa + offset, field_6_nVerBuiltInNamesWhenSaved); - LittleEndian.putShort(data, 0xc + offset, field_7_ftcAsci); - LittleEndian.putShort(data, 0xe + offset, field_8_ftcFE); - LittleEndian.putShort(data, 0x10 + offset, field_9_ftcOther); - } - - /** - * Size of record - */ - public static int getSize() - { - return 0 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2; - } - - public String toString() - { - StringBuilder builder = new StringBuilder(); - builder.append("[Stshif]\n"); - builder.append(" .cstd = "); - builder.append(" (").append(getCstd()).append(" )\n"); - builder.append(" .cbSTDBaseInFile = "); - builder.append(" (").append(getCbSTDBaseInFile()).append(" )\n"); - builder.append(" .info3 = "); - builder.append(" (").append(getInfo3()).append(" )\n"); - builder.append(" .fHasOriginalStyle = ").append(isFHasOriginalStyle()).append('\n'); - builder.append(" .fReserved = ").append(getFReserved()).append('\n'); - builder.append(" .stiMaxWhenSaved = "); - builder.append(" (").append(getStiMaxWhenSaved()).append(" )\n"); - builder.append(" .istdMaxFixedWhenSaved = "); - builder.append(" (").append(getIstdMaxFixedWhenSaved()).append(" )\n"); - builder.append(" .nVerBuiltInNamesWhenSaved = "); - builder.append(" (").append(getNVerBuiltInNamesWhenSaved()).append(" )\n"); - builder.append(" .ftcAsci = "); - builder.append(" (").append(getFtcAsci()).append(" )\n"); - builder.append(" .ftcFE = "); - builder.append(" (").append(getFtcFE()).append(" )\n"); - builder.append(" .ftcOther = "); - builder.append(" (").append(getFtcOther()).append(" )\n"); - - builder.append("[/Stshif]\n"); - return builder.toString(); - } - - /** - * An unsigned integer that specifies the count of elements in STSH.rglpstd. This value MUST be equal to or greater than 0x000F, and MUST be less than 0x0FFE. - */ - @Internal - public int getCstd() - { - return field_1_cstd; - } - - /** - * An unsigned integer that specifies the count of elements in STSH.rglpstd. This value MUST be equal to or greater than 0x000F, and MUST be less than 0x0FFE. - */ - @Internal - public void setCstd( int field_1_cstd ) - { - this.field_1_cstd = field_1_cstd; - } - - /** - * An unsigned integer that specifies the size, in bytes, of the Stdf structure. The Stdf structure contains an StdfBase structure that is followed by a StdfPost2000OrNone structure which contains an optional StdfPost2000 structure. This value MUST be 0x000A when the Stdf structure does not contain an StdfPost2000 structure and MUST be 0x0012 when the Stdf structure does contain an StdfPost2000 structure.. - */ - @Internal - public int getCbSTDBaseInFile() - { - return field_2_cbSTDBaseInFile; - } - - /** - * An unsigned integer that specifies the size, in bytes, of the Stdf structure. The Stdf structure contains an StdfBase structure that is followed by a StdfPost2000OrNone structure which contains an optional StdfPost2000 structure. This value MUST be 0x000A when the Stdf structure does not contain an StdfPost2000 structure and MUST be 0x0012 when the Stdf structure does contain an StdfPost2000 structure.. - */ - @Internal - public void setCbSTDBaseInFile( int field_2_cbSTDBaseInFile ) - { - this.field_2_cbSTDBaseInFile = field_2_cbSTDBaseInFile; - } - - /** - * Get the info3 field for the Stshif record. - */ - @Internal - public int getInfo3() - { - return field_3_info3; - } - - /** - * Set the info3 field for the Stshif record. - */ - @Internal - public void setInfo3( int field_3_info3 ) - { - this.field_3_info3 = field_3_info3; - } - - /** - * An unsigned integer that specifies a value that is 1 larger than the largest StdfBase.sti index of any application-defined style. This SHOULD be equal to the largest sti index that is defined in the application, incremented by 1. - */ - @Internal - public int getStiMaxWhenSaved() - { - return field_4_stiMaxWhenSaved; - } - - /** - * An unsigned integer that specifies a value that is 1 larger than the largest StdfBase.sti index of any application-defined style. This SHOULD be equal to the largest sti index that is defined in the application, incremented by 1. - */ - @Internal - public void setStiMaxWhenSaved( int field_4_stiMaxWhenSaved ) - { - this.field_4_stiMaxWhenSaved = field_4_stiMaxWhenSaved; - } - - /** - * An unsigned integer that specifies the count of elements at the start of STSH.rglpstd that are reserved for fixed-index application-defined styles. This value MUST be 0x000F. - */ - @Internal - public int getIstdMaxFixedWhenSaved() - { - return field_5_istdMaxFixedWhenSaved; - } - - /** - * An unsigned integer that specifies the count of elements at the start of STSH.rglpstd that are reserved for fixed-index application-defined styles. This value MUST be 0x000F. - */ - @Internal - public void setIstdMaxFixedWhenSaved( int field_5_istdMaxFixedWhenSaved ) - { - this.field_5_istdMaxFixedWhenSaved = field_5_istdMaxFixedWhenSaved; - } - - /** - * An unsigned integer that specifies the version number of the style names as defined by the application that writes the file. - */ - @Internal - public int getNVerBuiltInNamesWhenSaved() - { - return field_6_nVerBuiltInNamesWhenSaved; - } - - /** - * An unsigned integer that specifies the version number of the style names as defined by the application that writes the file. - */ - @Internal - public void setNVerBuiltInNamesWhenSaved( int field_6_nVerBuiltInNamesWhenSaved ) - { - this.field_6_nVerBuiltInNamesWhenSaved = field_6_nVerBuiltInNamesWhenSaved; - } - - /** - * A signed integer that specifies an operand value for the sprmCRgFtc0 for default document formatting. - */ - @Internal - public short getFtcAsci() - { - return field_7_ftcAsci; - } - - /** - * A signed integer that specifies an operand value for the sprmCRgFtc0 for default document formatting. - */ - @Internal - public void setFtcAsci( short field_7_ftcAsci ) - { - this.field_7_ftcAsci = field_7_ftcAsci; - } - - /** - * A signed integer that specifies an operand value for the sprmCRgFtc1 for default document formatting, as defined in the section Determining Formatting Properties. - */ - @Internal - public short getFtcFE() - { - return field_8_ftcFE; - } - - /** - * A signed integer that specifies an operand value for the sprmCRgFtc1 for default document formatting, as defined in the section Determining Formatting Properties. - */ - @Internal - public void setFtcFE( short field_8_ftcFE ) - { - this.field_8_ftcFE = field_8_ftcFE; - } - - /** - * A signed integer that specifies an operand value for the sprmCRgFtc2 for default document formatting, as defined in the section Determining Formatting Properties. - */ - @Internal - public short getFtcOther() - { - return field_9_ftcOther; - } - - /** - * A signed integer that specifies an operand value for the sprmCRgFtc2 for default document formatting, as defined in the section Determining Formatting Properties. - */ - @Internal - public void setFtcOther( short field_9_ftcOther ) - { - this.field_9_ftcOther = field_9_ftcOther; - } - - /** - * Sets the fHasOriginalStyle field value. - * This value MUST be 1 and MUST be ignored - */ - @Internal - public void setFHasOriginalStyle( boolean value ) - { - field_3_info3 = fHasOriginalStyle.setBoolean(field_3_info3, value); - } - - /** - * This value MUST be 1 and MUST be ignored - * @return the fHasOriginalStyle field value. - */ - @Internal - public boolean isFHasOriginalStyle() - { - return fHasOriginalStyle.isSet(field_3_info3); - } - - /** - * Sets the fReserved field value. - * This value MUST be zero and MUST be ignored - */ - @Internal - public void setFReserved( short value ) - { - field_3_info3 = fReserved.setValue(field_3_info3, value); - } - - /** - * This value MUST be zero and MUST be ignored - * @return the fReserved field value. - */ - @Internal - public short getFReserved() - { - return ( short )fReserved.getValue(field_3_info3); - } - -} // END OF CLASS diff --git a/src/scratchpad/src/org/apache/poi/hwpf/model/types/TAPAbstractType.java b/src/scratchpad/src/org/apache/poi/hwpf/model/types/TAPAbstractType.java deleted file mode 100644 index d295f420f..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/model/types/TAPAbstractType.java +++ /dev/null @@ -1,2327 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.model.types; - - -import java.util.Arrays; - -import org.apache.poi.hwpf.usermodel.BorderCode; -import org.apache.poi.hwpf.usermodel.ShadingDescriptor; -import org.apache.poi.hwpf.usermodel.TableAutoformatLookSpecifier; -import org.apache.poi.hwpf.usermodel.TableCellDescriptor; -import org.apache.poi.util.BitField; -import org.apache.poi.util.Internal; - -/** - * Table Properties. Properties descriptions quoted from official 97-2007 binary file - format specification. - - *

    - * NOTE: This source is automatically generated please do not modify this file. Either subclass or - * remove the record in src/types/definitions. - *

    - * This class is internal. It content or properties may change without notice - * due to changes in our knowledge of internal Microsoft Word binary structures. - - * @author S. Ryan Ackley - */ -@Internal -public abstract class TAPAbstractType -{ - - protected short field_1_istd; - protected short field_2_jc; - protected int field_3_dxaGapHalf; - protected int field_4_dyaRowHeight; - protected boolean field_5_fCantSplit; - protected boolean field_6_fCantSplit90; - protected boolean field_7_fTableHeader; - protected TableAutoformatLookSpecifier field_8_tlp; - protected short field_9_wWidth; - protected short field_10_wWidthIndent; - protected short field_11_wWidthBefore; - protected short field_12_wWidthAfter; - protected int field_13_widthAndFitsFlags; - /**/private static BitField fAutofit = new BitField(0x00000001); - /**/private static BitField fKeepFollow = new BitField(0x00000002); - /**/private static BitField ftsWidth = new BitField(0x0000001c); - /**/private static BitField ftsWidthIndent = new BitField(0x000000e0); - /**/private static BitField ftsWidthBefore = new BitField(0x00000700); - /**/private static BitField ftsWidthAfter = new BitField(0x00003800); - /**/private static BitField fNeverBeenAutofit = new BitField(0x00004000); - /**/private static BitField fInvalAutofit = new BitField(0x00008000); - /**/private static BitField widthAndFitsFlags_empty1 = new BitField(0x00070000); - /**/private static BitField fVert = new BitField(0x00080000); - /**/private static BitField pcVert = new BitField(0x00300000); - /**/private static BitField pcHorz = new BitField(0x00c00000); - /**/private static BitField widthAndFitsFlags_empty2 = new BitField(0xff000000); - protected int field_14_dxaAbs; - protected int field_15_dyaAbs; - protected int field_16_dxaFromText; - protected int field_17_dyaFromText; - protected int field_18_dxaFromTextRight; - protected int field_19_dyaFromTextBottom; - protected byte field_20_fBiDi; - protected byte field_21_fRTL; - protected byte field_22_fNoAllowOverlap; - protected byte field_23_fSpare; - protected int field_24_grpfTap; - protected int field_25_internalFlags; - /**/private static BitField fFirstRow = new BitField(0x0001); - /**/private static BitField fLastRow = new BitField(0x0002); - /**/private static BitField fOutline = new BitField(0x0004); - /**/private static BitField fOrigWordTableRules = new BitField(0x0008); - /**/private static BitField fCellSpacing = new BitField(0x0010); - /**/private static BitField grpfTap_unused = new BitField(0xffe0); - protected short field_26_itcMac; - protected int field_27_dxaAdjust; - protected int field_28_dxaWebView; - protected int field_29_dxaRTEWrapWidth; - protected int field_30_dxaColWidthWwd; - protected short field_31_pctWwd; - protected int field_32_viewFlags; - /**/private static BitField fWrapToWwd = new BitField(0x0001); - /**/private static BitField fNotPageView = new BitField(0x0002); - /**/private static BitField viewFlags_unused1 = new BitField(0x0004); - /**/private static BitField fWebView = new BitField(0x0008); - /**/private static BitField fAdjusted = new BitField(0x0010); - /**/private static BitField viewFlags_unused2 = new BitField(0xffe0); - protected short[] field_33_rgdxaCenter; - protected short[] field_34_rgdxaCenterPrint; - protected ShadingDescriptor field_35_shdTable; - protected BorderCode field_36_brcBottom; - protected BorderCode field_37_brcTop; - protected BorderCode field_38_brcLeft; - protected BorderCode field_39_brcRight; - protected BorderCode field_40_brcVertical; - protected BorderCode field_41_brcHorizontal; - protected short field_42_wCellPaddingDefaultTop; - protected short field_43_wCellPaddingDefaultLeft; - protected short field_44_wCellPaddingDefaultBottom; - protected short field_45_wCellPaddingDefaultRight; - protected byte field_46_ftsCellPaddingDefaultTop; - protected byte field_47_ftsCellPaddingDefaultLeft; - protected byte field_48_ftsCellPaddingDefaultBottom; - protected byte field_49_ftsCellPaddingDefaultRight; - protected short field_50_wCellSpacingDefaultTop; - protected short field_51_wCellSpacingDefaultLeft; - protected short field_52_wCellSpacingDefaultBottom; - protected short field_53_wCellSpacingDefaultRight; - protected byte field_54_ftsCellSpacingDefaultTop; - protected byte field_55_ftsCellSpacingDefaultLeft; - protected byte field_56_ftsCellSpacingDefaultBottom; - protected byte field_57_ftsCellSpacingDefaultRight; - protected short field_58_wCellPaddingOuterTop; - protected short field_59_wCellPaddingOuterLeft; - protected short field_60_wCellPaddingOuterBottom; - protected short field_61_wCellPaddingOuterRight; - protected byte field_62_ftsCellPaddingOuterTop; - protected byte field_63_ftsCellPaddingOuterLeft; - protected byte field_64_ftsCellPaddingOuterBottom; - protected byte field_65_ftsCellPaddingOuterRight; - protected short field_66_wCellSpacingOuterTop; - protected short field_67_wCellSpacingOuterLeft; - protected short field_68_wCellSpacingOuterBottom; - protected short field_69_wCellSpacingOuterRight; - protected byte field_70_ftsCellSpacingOuterTop; - protected byte field_71_ftsCellSpacingOuterLeft; - protected byte field_72_ftsCellSpacingOuterBottom; - protected byte field_73_ftsCellSpacingOuterRight; - protected TableCellDescriptor[] field_74_rgtc; - protected ShadingDescriptor[] field_75_rgshd; - protected byte field_76_fPropRMark; - protected byte field_77_fHasOldProps; - protected short field_78_cHorzBands; - protected short field_79_cVertBands; - protected BorderCode field_80_rgbrcInsideDefault_0; - protected BorderCode field_81_rgbrcInsideDefault_1; - - protected TAPAbstractType() - { - this.field_8_tlp = new TableAutoformatLookSpecifier(); - this.field_33_rgdxaCenter = new short[0]; - this.field_34_rgdxaCenterPrint = new short[0]; - this.field_35_shdTable = new ShadingDescriptor(); - this.field_36_brcBottom = new BorderCode(); - this.field_37_brcTop = new BorderCode(); - this.field_38_brcLeft = new BorderCode(); - this.field_39_brcRight = new BorderCode(); - this.field_40_brcVertical = new BorderCode(); - this.field_41_brcHorizontal = new BorderCode(); - this.field_74_rgtc = new TableCellDescriptor[0]; - this.field_75_rgshd = new ShadingDescriptor[0]; - this.field_80_rgbrcInsideDefault_0 = new BorderCode(); - this.field_81_rgbrcInsideDefault_1 = new BorderCode(); - } - - - public String toString() - { - StringBuilder builder = new StringBuilder(); - builder.append("[TAP]\n"); - builder.append(" .istd = "); - builder.append(" (").append(getIstd()).append(" )\n"); - builder.append(" .jc = "); - builder.append(" (").append(getJc()).append(" )\n"); - builder.append(" .dxaGapHalf = "); - builder.append(" (").append(getDxaGapHalf()).append(" )\n"); - builder.append(" .dyaRowHeight = "); - builder.append(" (").append(getDyaRowHeight()).append(" )\n"); - builder.append(" .fCantSplit = "); - builder.append(" (").append(getFCantSplit()).append(" )\n"); - builder.append(" .fCantSplit90 = "); - builder.append(" (").append(getFCantSplit90()).append(" )\n"); - builder.append(" .fTableHeader = "); - builder.append(" (").append(getFTableHeader()).append(" )\n"); - builder.append(" .tlp = "); - builder.append(" (").append(getTlp()).append(" )\n"); - builder.append(" .wWidth = "); - builder.append(" (").append(getWWidth()).append(" )\n"); - builder.append(" .wWidthIndent = "); - builder.append(" (").append(getWWidthIndent()).append(" )\n"); - builder.append(" .wWidthBefore = "); - builder.append(" (").append(getWWidthBefore()).append(" )\n"); - builder.append(" .wWidthAfter = "); - builder.append(" (").append(getWWidthAfter()).append(" )\n"); - builder.append(" .widthAndFitsFlags = "); - builder.append(" (").append(getWidthAndFitsFlags()).append(" )\n"); - builder.append(" .fAutofit = ").append(isFAutofit()).append('\n'); - builder.append(" .fKeepFollow = ").append(isFKeepFollow()).append('\n'); - builder.append(" .ftsWidth = ").append(getFtsWidth()).append('\n'); - builder.append(" .ftsWidthIndent = ").append(getFtsWidthIndent()).append('\n'); - builder.append(" .ftsWidthBefore = ").append(getFtsWidthBefore()).append('\n'); - builder.append(" .ftsWidthAfter = ").append(getFtsWidthAfter()).append('\n'); - builder.append(" .fNeverBeenAutofit = ").append(isFNeverBeenAutofit()).append('\n'); - builder.append(" .fInvalAutofit = ").append(isFInvalAutofit()).append('\n'); - builder.append(" .widthAndFitsFlags_empty1 = ").append(getWidthAndFitsFlags_empty1()).append('\n'); - builder.append(" .fVert = ").append(isFVert()).append('\n'); - builder.append(" .pcVert = ").append(getPcVert()).append('\n'); - builder.append(" .pcHorz = ").append(getPcHorz()).append('\n'); - builder.append(" .widthAndFitsFlags_empty2 = ").append(getWidthAndFitsFlags_empty2()).append('\n'); - builder.append(" .dxaAbs = "); - builder.append(" (").append(getDxaAbs()).append(" )\n"); - builder.append(" .dyaAbs = "); - builder.append(" (").append(getDyaAbs()).append(" )\n"); - builder.append(" .dxaFromText = "); - builder.append(" (").append(getDxaFromText()).append(" )\n"); - builder.append(" .dyaFromText = "); - builder.append(" (").append(getDyaFromText()).append(" )\n"); - builder.append(" .dxaFromTextRight = "); - builder.append(" (").append(getDxaFromTextRight()).append(" )\n"); - builder.append(" .dyaFromTextBottom = "); - builder.append(" (").append(getDyaFromTextBottom()).append(" )\n"); - builder.append(" .fBiDi = "); - builder.append(" (").append(getFBiDi()).append(" )\n"); - builder.append(" .fRTL = "); - builder.append(" (").append(getFRTL()).append(" )\n"); - builder.append(" .fNoAllowOverlap = "); - builder.append(" (").append(getFNoAllowOverlap()).append(" )\n"); - builder.append(" .fSpare = "); - builder.append(" (").append(getFSpare()).append(" )\n"); - builder.append(" .grpfTap = "); - builder.append(" (").append(getGrpfTap()).append(" )\n"); - builder.append(" .internalFlags = "); - builder.append(" (").append(getInternalFlags()).append(" )\n"); - builder.append(" .fFirstRow = ").append(isFFirstRow()).append('\n'); - builder.append(" .fLastRow = ").append(isFLastRow()).append('\n'); - builder.append(" .fOutline = ").append(isFOutline()).append('\n'); - builder.append(" .fOrigWordTableRules = ").append(isFOrigWordTableRules()).append('\n'); - builder.append(" .fCellSpacing = ").append(isFCellSpacing()).append('\n'); - builder.append(" .grpfTap_unused = ").append(getGrpfTap_unused()).append('\n'); - builder.append(" .itcMac = "); - builder.append(" (").append(getItcMac()).append(" )\n"); - builder.append(" .dxaAdjust = "); - builder.append(" (").append(getDxaAdjust()).append(" )\n"); - builder.append(" .dxaWebView = "); - builder.append(" (").append(getDxaWebView()).append(" )\n"); - builder.append(" .dxaRTEWrapWidth = "); - builder.append(" (").append(getDxaRTEWrapWidth()).append(" )\n"); - builder.append(" .dxaColWidthWwd = "); - builder.append(" (").append(getDxaColWidthWwd()).append(" )\n"); - builder.append(" .pctWwd = "); - builder.append(" (").append(getPctWwd()).append(" )\n"); - builder.append(" .viewFlags = "); - builder.append(" (").append(getViewFlags()).append(" )\n"); - builder.append(" .fWrapToWwd = ").append(isFWrapToWwd()).append('\n'); - builder.append(" .fNotPageView = ").append(isFNotPageView()).append('\n'); - builder.append(" .viewFlags_unused1 = ").append(isViewFlags_unused1()).append('\n'); - builder.append(" .fWebView = ").append(isFWebView()).append('\n'); - builder.append(" .fAdjusted = ").append(isFAdjusted()).append('\n'); - builder.append(" .viewFlags_unused2 = ").append(getViewFlags_unused2()).append('\n'); - builder.append(" .rgdxaCenter = "); - builder.append(" (").append(Arrays.toString(getRgdxaCenter())).append(" )\n"); - builder.append(" .rgdxaCenterPrint = "); - builder.append(" (").append(Arrays.toString(getRgdxaCenterPrint())).append(" )\n"); - builder.append(" .shdTable = "); - builder.append(" (").append(getShdTable()).append(" )\n"); - builder.append(" .brcBottom = "); - builder.append(" (").append(getBrcBottom()).append(" )\n"); - builder.append(" .brcTop = "); - builder.append(" (").append(getBrcTop()).append(" )\n"); - builder.append(" .brcLeft = "); - builder.append(" (").append(getBrcLeft()).append(" )\n"); - builder.append(" .brcRight = "); - builder.append(" (").append(getBrcRight()).append(" )\n"); - builder.append(" .brcVertical = "); - builder.append(" (").append(getBrcVertical()).append(" )\n"); - builder.append(" .brcHorizontal = "); - builder.append(" (").append(getBrcHorizontal()).append(" )\n"); - builder.append(" .wCellPaddingDefaultTop = "); - builder.append(" (").append(getWCellPaddingDefaultTop()).append(" )\n"); - builder.append(" .wCellPaddingDefaultLeft = "); - builder.append(" (").append(getWCellPaddingDefaultLeft()).append(" )\n"); - builder.append(" .wCellPaddingDefaultBottom = "); - builder.append(" (").append(getWCellPaddingDefaultBottom()).append(" )\n"); - builder.append(" .wCellPaddingDefaultRight = "); - builder.append(" (").append(getWCellPaddingDefaultRight()).append(" )\n"); - builder.append(" .ftsCellPaddingDefaultTop = "); - builder.append(" (").append(getFtsCellPaddingDefaultTop()).append(" )\n"); - builder.append(" .ftsCellPaddingDefaultLeft = "); - builder.append(" (").append(getFtsCellPaddingDefaultLeft()).append(" )\n"); - builder.append(" .ftsCellPaddingDefaultBottom = "); - builder.append(" (").append(getFtsCellPaddingDefaultBottom()).append(" )\n"); - builder.append(" .ftsCellPaddingDefaultRight = "); - builder.append(" (").append(getFtsCellPaddingDefaultRight()).append(" )\n"); - builder.append(" .wCellSpacingDefaultTop = "); - builder.append(" (").append(getWCellSpacingDefaultTop()).append(" )\n"); - builder.append(" .wCellSpacingDefaultLeft = "); - builder.append(" (").append(getWCellSpacingDefaultLeft()).append(" )\n"); - builder.append(" .wCellSpacingDefaultBottom = "); - builder.append(" (").append(getWCellSpacingDefaultBottom()).append(" )\n"); - builder.append(" .wCellSpacingDefaultRight = "); - builder.append(" (").append(getWCellSpacingDefaultRight()).append(" )\n"); - builder.append(" .ftsCellSpacingDefaultTop = "); - builder.append(" (").append(getFtsCellSpacingDefaultTop()).append(" )\n"); - builder.append(" .ftsCellSpacingDefaultLeft = "); - builder.append(" (").append(getFtsCellSpacingDefaultLeft()).append(" )\n"); - builder.append(" .ftsCellSpacingDefaultBottom = "); - builder.append(" (").append(getFtsCellSpacingDefaultBottom()).append(" )\n"); - builder.append(" .ftsCellSpacingDefaultRight = "); - builder.append(" (").append(getFtsCellSpacingDefaultRight()).append(" )\n"); - builder.append(" .wCellPaddingOuterTop = "); - builder.append(" (").append(getWCellPaddingOuterTop()).append(" )\n"); - builder.append(" .wCellPaddingOuterLeft = "); - builder.append(" (").append(getWCellPaddingOuterLeft()).append(" )\n"); - builder.append(" .wCellPaddingOuterBottom = "); - builder.append(" (").append(getWCellPaddingOuterBottom()).append(" )\n"); - builder.append(" .wCellPaddingOuterRight = "); - builder.append(" (").append(getWCellPaddingOuterRight()).append(" )\n"); - builder.append(" .ftsCellPaddingOuterTop = "); - builder.append(" (").append(getFtsCellPaddingOuterTop()).append(" )\n"); - builder.append(" .ftsCellPaddingOuterLeft = "); - builder.append(" (").append(getFtsCellPaddingOuterLeft()).append(" )\n"); - builder.append(" .ftsCellPaddingOuterBottom = "); - builder.append(" (").append(getFtsCellPaddingOuterBottom()).append(" )\n"); - builder.append(" .ftsCellPaddingOuterRight = "); - builder.append(" (").append(getFtsCellPaddingOuterRight()).append(" )\n"); - builder.append(" .wCellSpacingOuterTop = "); - builder.append(" (").append(getWCellSpacingOuterTop()).append(" )\n"); - builder.append(" .wCellSpacingOuterLeft = "); - builder.append(" (").append(getWCellSpacingOuterLeft()).append(" )\n"); - builder.append(" .wCellSpacingOuterBottom = "); - builder.append(" (").append(getWCellSpacingOuterBottom()).append(" )\n"); - builder.append(" .wCellSpacingOuterRight = "); - builder.append(" (").append(getWCellSpacingOuterRight()).append(" )\n"); - builder.append(" .ftsCellSpacingOuterTop = "); - builder.append(" (").append(getFtsCellSpacingOuterTop()).append(" )\n"); - builder.append(" .ftsCellSpacingOuterLeft = "); - builder.append(" (").append(getFtsCellSpacingOuterLeft()).append(" )\n"); - builder.append(" .ftsCellSpacingOuterBottom = "); - builder.append(" (").append(getFtsCellSpacingOuterBottom()).append(" )\n"); - builder.append(" .ftsCellSpacingOuterRight = "); - builder.append(" (").append(getFtsCellSpacingOuterRight()).append(" )\n"); - builder.append(" .rgtc = "); - builder.append(" (").append(Arrays.toString(getRgtc())).append(" )\n"); - builder.append(" .rgshd = "); - builder.append(" (").append(Arrays.toString(getRgshd())).append(" )\n"); - builder.append(" .fPropRMark = "); - builder.append(" (").append(getFPropRMark()).append(" )\n"); - builder.append(" .fHasOldProps = "); - builder.append(" (").append(getFHasOldProps()).append(" )\n"); - builder.append(" .cHorzBands = "); - builder.append(" (").append(getCHorzBands()).append(" )\n"); - builder.append(" .cVertBands = "); - builder.append(" (").append(getCVertBands()).append(" )\n"); - builder.append(" .rgbrcInsideDefault_0 = "); - builder.append(" (").append(getRgbrcInsideDefault_0()).append(" )\n"); - builder.append(" .rgbrcInsideDefault_1 = "); - builder.append(" (").append(getRgbrcInsideDefault_1()).append(" )\n"); - - builder.append("[/TAP]\n"); - return builder.toString(); - } - - /** - * Table style for the Table. - */ - @Internal - public short getIstd() - { - return field_1_istd; - } - - /** - * Table style for the Table. - */ - @Internal - public void setIstd( short field_1_istd ) - { - this.field_1_istd = field_1_istd; - } - - /** - * Justification code. specifies how table row should be justified within its column. 0 -- left justify, 1 -- center, 2 -- right justify. - */ - @Internal - public short getJc() - { - return field_2_jc; - } - - /** - * Justification code. specifies how table row should be justified within its column. 0 -- left justify, 1 -- center, 2 -- right justify. - */ - @Internal - public void setJc( short field_2_jc ) - { - this.field_2_jc = field_2_jc; - } - - /** - * Measures half of the white space that will be maintained between text in adjacent columns of a table row. A dxaGapHalf width of white space will be maintained on both sides of a column boundary.. - */ - @Internal - public int getDxaGapHalf() - { - return field_3_dxaGapHalf; - } - - /** - * Measures half of the white space that will be maintained between text in adjacent columns of a table row. A dxaGapHalf width of white space will be maintained on both sides of a column boundary.. - */ - @Internal - public void setDxaGapHalf( int field_3_dxaGapHalf ) - { - this.field_3_dxaGapHalf = field_3_dxaGapHalf; - } - - /** - * When greater than 0, guarantees that the height of the table will be at least dyaRowHeight high. When less than 0, guarantees that the height of the table will be exactly absolute value of dyaRowHeight high. When 0, table will be given a height large enough to represent all of the text in all of the cells of the table. Cells with vertical text flow make no contribution to the computation of the height of rows with auto or at least height. Neither do vertically merged cells, except in the last row of the vertical merge. If an auto height row consists entirely of cells which have vertical text direction or are vertically merged, and the row does not contain the last cell in any vertical cell merge, then the row is given height equal to that of the end of cell mark in the first cell.. - */ - @Internal - public int getDyaRowHeight() - { - return field_4_dyaRowHeight; - } - - /** - * When greater than 0, guarantees that the height of the table will be at least dyaRowHeight high. When less than 0, guarantees that the height of the table will be exactly absolute value of dyaRowHeight high. When 0, table will be given a height large enough to represent all of the text in all of the cells of the table. Cells with vertical text flow make no contribution to the computation of the height of rows with auto or at least height. Neither do vertically merged cells, except in the last row of the vertical merge. If an auto height row consists entirely of cells which have vertical text direction or are vertically merged, and the row does not contain the last cell in any vertical cell merge, then the row is given height equal to that of the end of cell mark in the first cell.. - */ - @Internal - public void setDyaRowHeight( int field_4_dyaRowHeight ) - { - this.field_4_dyaRowHeight = field_4_dyaRowHeight; - } - - /** - * When 1, table row may not be split across page bounds. - */ - @Internal - public boolean getFCantSplit() - { - return field_5_fCantSplit; - } - - /** - * When 1, table row may not be split across page bounds. - */ - @Internal - public void setFCantSplit( boolean field_5_fCantSplit ) - { - this.field_5_fCantSplit = field_5_fCantSplit; - } - - /** - * When 1, table row may not be split across page bounds. Used for Word 2000 and Word 97.. - */ - @Internal - public boolean getFCantSplit90() - { - return field_6_fCantSplit90; - } - - /** - * When 1, table row may not be split across page bounds. Used for Word 2000 and Word 97.. - */ - @Internal - public void setFCantSplit90( boolean field_6_fCantSplit90 ) - { - this.field_6_fCantSplit90 = field_6_fCantSplit90; - } - - /** - * When 1, table row is to be used as the header of the table. - */ - @Internal - public boolean getFTableHeader() - { - return field_7_fTableHeader; - } - - /** - * When 1, table row is to be used as the header of the table. - */ - @Internal - public void setFTableHeader( boolean field_7_fTableHeader ) - { - this.field_7_fTableHeader = field_7_fTableHeader; - } - - /** - * Table look specifier. - */ - @Internal - public TableAutoformatLookSpecifier getTlp() - { - return field_8_tlp; - } - - /** - * Table look specifier. - */ - @Internal - public void setTlp( TableAutoformatLookSpecifier field_8_tlp ) - { - this.field_8_tlp = field_8_tlp; - } - - /** - * Preferred table width. - */ - @Internal - public short getWWidth() - { - return field_9_wWidth; - } - - /** - * Preferred table width. - */ - @Internal - public void setWWidth( short field_9_wWidth ) - { - this.field_9_wWidth = field_9_wWidth; - } - - /** - * Left Indent. - */ - @Internal - public short getWWidthIndent() - { - return field_10_wWidthIndent; - } - - /** - * Left Indent. - */ - @Internal - public void setWWidthIndent( short field_10_wWidthIndent ) - { - this.field_10_wWidthIndent = field_10_wWidthIndent; - } - - /** - * Width of invisible cell (used for layout purposes) before the first visible cell in the row.. - */ - @Internal - public short getWWidthBefore() - { - return field_11_wWidthBefore; - } - - /** - * Width of invisible cell (used for layout purposes) before the first visible cell in the row.. - */ - @Internal - public void setWWidthBefore( short field_11_wWidthBefore ) - { - this.field_11_wWidthBefore = field_11_wWidthBefore; - } - - /** - * Width of invisible cell (used for layout purposes) after the last visible cell in the row.. - */ - @Internal - public short getWWidthAfter() - { - return field_12_wWidthAfter; - } - - /** - * Width of invisible cell (used for layout purposes) after the last visible cell in the row.. - */ - @Internal - public void setWWidthAfter( short field_12_wWidthAfter ) - { - this.field_12_wWidthAfter = field_12_wWidthAfter; - } - - /** - * Get the widthAndFitsFlags field for the TAP record. - */ - @Internal - public int getWidthAndFitsFlags() - { - return field_13_widthAndFitsFlags; - } - - /** - * Set the widthAndFitsFlags field for the TAP record. - */ - @Internal - public void setWidthAndFitsFlags( int field_13_widthAndFitsFlags ) - { - this.field_13_widthAndFitsFlags = field_13_widthAndFitsFlags; - } - - /** - * Absolute horizontal position. - */ - @Internal - public int getDxaAbs() - { - return field_14_dxaAbs; - } - - /** - * Absolute horizontal position. - */ - @Internal - public void setDxaAbs( int field_14_dxaAbs ) - { - this.field_14_dxaAbs = field_14_dxaAbs; - } - - /** - * Absolute vertical position. - */ - @Internal - public int getDyaAbs() - { - return field_15_dyaAbs; - } - - /** - * Absolute vertical position. - */ - @Internal - public void setDyaAbs( int field_15_dyaAbs ) - { - this.field_15_dyaAbs = field_15_dyaAbs; - } - - /** - * Left distance from surrounding text when absolutely positioned. - */ - @Internal - public int getDxaFromText() - { - return field_16_dxaFromText; - } - - /** - * Left distance from surrounding text when absolutely positioned. - */ - @Internal - public void setDxaFromText( int field_16_dxaFromText ) - { - this.field_16_dxaFromText = field_16_dxaFromText; - } - - /** - * Top distance from surrounding text when absolutely positioned. - */ - @Internal - public int getDyaFromText() - { - return field_17_dyaFromText; - } - - /** - * Top distance from surrounding text when absolutely positioned. - */ - @Internal - public void setDyaFromText( int field_17_dyaFromText ) - { - this.field_17_dyaFromText = field_17_dyaFromText; - } - - /** - * Right distance from surrounding text when absolutely positioned. - */ - @Internal - public int getDxaFromTextRight() - { - return field_18_dxaFromTextRight; - } - - /** - * Right distance from surrounding text when absolutely positioned. - */ - @Internal - public void setDxaFromTextRight( int field_18_dxaFromTextRight ) - { - this.field_18_dxaFromTextRight = field_18_dxaFromTextRight; - } - - /** - * Bottom distance from surrounding text when absolutely positioned. - */ - @Internal - public int getDyaFromTextBottom() - { - return field_19_dyaFromTextBottom; - } - - /** - * Bottom distance from surrounding text when absolutely positioned. - */ - @Internal - public void setDyaFromTextBottom( int field_19_dyaFromTextBottom ) - { - this.field_19_dyaFromTextBottom = field_19_dyaFromTextBottom; - } - - /** - * When 1, table is right-to-left. Logical right-to-left table: The CP stream of a right-to-left table is meant to be displayed from right to left. So for example the first table cell is displayed on the right side of the table instead of the left.. - */ - @Internal - public byte getFBiDi() - { - return field_20_fBiDi; - } - - /** - * When 1, table is right-to-left. Logical right-to-left table: The CP stream of a right-to-left table is meant to be displayed from right to left. So for example the first table cell is displayed on the right side of the table instead of the left.. - */ - @Internal - public void setFBiDi( byte field_20_fBiDi ) - { - this.field_20_fBiDi = field_20_fBiDi; - } - - /** - * Word 2000 style right-to-left table. Visual right-to-left table: The CP stream of a right-to-left table is displayed from left to right just as for a normal table. So, the text which is meant to be in the first (rightmost) table cell must be placed in the last table cell in the CP stream.. - */ - @Internal - public byte getFRTL() - { - return field_21_fRTL; - } - - /** - * Word 2000 style right-to-left table. Visual right-to-left table: The CP stream of a right-to-left table is displayed from left to right just as for a normal table. So, the text which is meant to be in the first (rightmost) table cell must be placed in the last table cell in the CP stream.. - */ - @Internal - public void setFRTL( byte field_21_fRTL ) - { - this.field_21_fRTL = field_21_fRTL; - } - - /** - * When set to 1, do not allow absolutely positioned table to overlap with other tables. - */ - @Internal - public byte getFNoAllowOverlap() - { - return field_22_fNoAllowOverlap; - } - - /** - * When set to 1, do not allow absolutely positioned table to overlap with other tables. - */ - @Internal - public void setFNoAllowOverlap( byte field_22_fNoAllowOverlap ) - { - this.field_22_fNoAllowOverlap = field_22_fNoAllowOverlap; - } - - /** - * Not used. - */ - @Internal - public byte getFSpare() - { - return field_23_fSpare; - } - - /** - * Not used. - */ - @Internal - public void setFSpare( byte field_23_fSpare ) - { - this.field_23_fSpare = field_23_fSpare; - } - - /** - * Used internally by Word. - */ - @Internal - public int getGrpfTap() - { - return field_24_grpfTap; - } - - /** - * Used internally by Word. - */ - @Internal - public void setGrpfTap( int field_24_grpfTap ) - { - this.field_24_grpfTap = field_24_grpfTap; - } - - /** - * Used internally by Word. - */ - @Internal - public int getInternalFlags() - { - return field_25_internalFlags; - } - - /** - * Used internally by Word. - */ - @Internal - public void setInternalFlags( int field_25_internalFlags ) - { - this.field_25_internalFlags = field_25_internalFlags; - } - - /** - * Count of cells defined for this row. itcMac must be >= 0 and less than or equal to 64.. - */ - @Internal - public short getItcMac() - { - return field_26_itcMac; - } - - /** - * Count of cells defined for this row. itcMac must be >= 0 and less than or equal to 64.. - */ - @Internal - public void setItcMac( short field_26_itcMac ) - { - this.field_26_itcMac = field_26_itcMac; - } - - /** - * Used internally by Word. - */ - @Internal - public int getDxaAdjust() - { - return field_27_dxaAdjust; - } - - /** - * Used internally by Word. - */ - @Internal - public void setDxaAdjust( int field_27_dxaAdjust ) - { - this.field_27_dxaAdjust = field_27_dxaAdjust; - } - - /** - * Used internally by Word. - */ - @Internal - public int getDxaWebView() - { - return field_28_dxaWebView; - } - - /** - * Used internally by Word. - */ - @Internal - public void setDxaWebView( int field_28_dxaWebView ) - { - this.field_28_dxaWebView = field_28_dxaWebView; - } - - /** - * Used internally by Word. - */ - @Internal - public int getDxaRTEWrapWidth() - { - return field_29_dxaRTEWrapWidth; - } - - /** - * Used internally by Word. - */ - @Internal - public void setDxaRTEWrapWidth( int field_29_dxaRTEWrapWidth ) - { - this.field_29_dxaRTEWrapWidth = field_29_dxaRTEWrapWidth; - } - - /** - * Used internally by Word. - */ - @Internal - public int getDxaColWidthWwd() - { - return field_30_dxaColWidthWwd; - } - - /** - * Used internally by Word. - */ - @Internal - public void setDxaColWidthWwd( int field_30_dxaColWidthWwd ) - { - this.field_30_dxaColWidthWwd = field_30_dxaColWidthWwd; - } - - /** - * Used internally by Word: percent of Window size for AutoFit in WebView. - */ - @Internal - public short getPctWwd() - { - return field_31_pctWwd; - } - - /** - * Used internally by Word: percent of Window size for AutoFit in WebView. - */ - @Internal - public void setPctWwd( short field_31_pctWwd ) - { - this.field_31_pctWwd = field_31_pctWwd; - } - - /** - * Used internally by Word. - */ - @Internal - public int getViewFlags() - { - return field_32_viewFlags; - } - - /** - * Used internally by Word. - */ - @Internal - public void setViewFlags( int field_32_viewFlags ) - { - this.field_32_viewFlags = field_32_viewFlags; - } - - /** - * rgdxaCenter[0] is the left boundary of cell 0 measured relative to margin rgdxaCenter[tap.itcMac - 1] is left boundary of last cell rgdxaCenter[tap.itcMac] is right boundary of last cell.. - */ - @Internal - public short[] getRgdxaCenter() - { - return field_33_rgdxaCenter; - } - - /** - * rgdxaCenter[0] is the left boundary of cell 0 measured relative to margin rgdxaCenter[tap.itcMac - 1] is left boundary of last cell rgdxaCenter[tap.itcMac] is right boundary of last cell.. - */ - @Internal - public void setRgdxaCenter( short[] field_33_rgdxaCenter ) - { - this.field_33_rgdxaCenter = field_33_rgdxaCenter; - } - - /** - * Used internally by Word. - */ - @Internal - public short[] getRgdxaCenterPrint() - { - return field_34_rgdxaCenterPrint; - } - - /** - * Used internally by Word. - */ - @Internal - public void setRgdxaCenterPrint( short[] field_34_rgdxaCenterPrint ) - { - this.field_34_rgdxaCenterPrint = field_34_rgdxaCenterPrint; - } - - /** - * Table shading. - */ - @Internal - public ShadingDescriptor getShdTable() - { - return field_35_shdTable; - } - - /** - * Table shading. - */ - @Internal - public void setShdTable( ShadingDescriptor field_35_shdTable ) - { - this.field_35_shdTable = field_35_shdTable; - } - - /** - * Get the brcBottom field for the TAP record. - */ - @Internal - public BorderCode getBrcBottom() - { - return field_36_brcBottom; - } - - /** - * Set the brcBottom field for the TAP record. - */ - @Internal - public void setBrcBottom( BorderCode field_36_brcBottom ) - { - this.field_36_brcBottom = field_36_brcBottom; - } - - /** - * Get the brcTop field for the TAP record. - */ - @Internal - public BorderCode getBrcTop() - { - return field_37_brcTop; - } - - /** - * Set the brcTop field for the TAP record. - */ - @Internal - public void setBrcTop( BorderCode field_37_brcTop ) - { - this.field_37_brcTop = field_37_brcTop; - } - - /** - * Get the brcLeft field for the TAP record. - */ - @Internal - public BorderCode getBrcLeft() - { - return field_38_brcLeft; - } - - /** - * Set the brcLeft field for the TAP record. - */ - @Internal - public void setBrcLeft( BorderCode field_38_brcLeft ) - { - this.field_38_brcLeft = field_38_brcLeft; - } - - /** - * Get the brcRight field for the TAP record. - */ - @Internal - public BorderCode getBrcRight() - { - return field_39_brcRight; - } - - /** - * Set the brcRight field for the TAP record. - */ - @Internal - public void setBrcRight( BorderCode field_39_brcRight ) - { - this.field_39_brcRight = field_39_brcRight; - } - - /** - * Get the brcVertical field for the TAP record. - */ - @Internal - public BorderCode getBrcVertical() - { - return field_40_brcVertical; - } - - /** - * Set the brcVertical field for the TAP record. - */ - @Internal - public void setBrcVertical( BorderCode field_40_brcVertical ) - { - this.field_40_brcVertical = field_40_brcVertical; - } - - /** - * Get the brcHorizontal field for the TAP record. - */ - @Internal - public BorderCode getBrcHorizontal() - { - return field_41_brcHorizontal; - } - - /** - * Set the brcHorizontal field for the TAP record. - */ - @Internal - public void setBrcHorizontal( BorderCode field_41_brcHorizontal ) - { - this.field_41_brcHorizontal = field_41_brcHorizontal; - } - - /** - * Default top cell margin/padding. - */ - @Internal - public short getWCellPaddingDefaultTop() - { - return field_42_wCellPaddingDefaultTop; - } - - /** - * Default top cell margin/padding. - */ - @Internal - public void setWCellPaddingDefaultTop( short field_42_wCellPaddingDefaultTop ) - { - this.field_42_wCellPaddingDefaultTop = field_42_wCellPaddingDefaultTop; - } - - /** - * Default left cell margin/padding. - */ - @Internal - public short getWCellPaddingDefaultLeft() - { - return field_43_wCellPaddingDefaultLeft; - } - - /** - * Default left cell margin/padding. - */ - @Internal - public void setWCellPaddingDefaultLeft( short field_43_wCellPaddingDefaultLeft ) - { - this.field_43_wCellPaddingDefaultLeft = field_43_wCellPaddingDefaultLeft; - } - - /** - * Default bottom cell margin/padding. - */ - @Internal - public short getWCellPaddingDefaultBottom() - { - return field_44_wCellPaddingDefaultBottom; - } - - /** - * Default bottom cell margin/padding. - */ - @Internal - public void setWCellPaddingDefaultBottom( short field_44_wCellPaddingDefaultBottom ) - { - this.field_44_wCellPaddingDefaultBottom = field_44_wCellPaddingDefaultBottom; - } - - /** - * Default right cell margin/padding. - */ - @Internal - public short getWCellPaddingDefaultRight() - { - return field_45_wCellPaddingDefaultRight; - } - - /** - * Default right cell margin/padding. - */ - @Internal - public void setWCellPaddingDefaultRight( short field_45_wCellPaddingDefaultRight ) - { - this.field_45_wCellPaddingDefaultRight = field_45_wCellPaddingDefaultRight; - } - - /** - * Default top cell margin/padding units. 0 -- null; 1-2 -- not relevant; 3 -- twips.. - */ - @Internal - public byte getFtsCellPaddingDefaultTop() - { - return field_46_ftsCellPaddingDefaultTop; - } - - /** - * Default top cell margin/padding units. 0 -- null; 1-2 -- not relevant; 3 -- twips.. - */ - @Internal - public void setFtsCellPaddingDefaultTop( byte field_46_ftsCellPaddingDefaultTop ) - { - this.field_46_ftsCellPaddingDefaultTop = field_46_ftsCellPaddingDefaultTop; - } - - /** - * Default left cell margin/padding units. 0 -- null; 1-2 -- not relevant; 3 -- twips.. - */ - @Internal - public byte getFtsCellPaddingDefaultLeft() - { - return field_47_ftsCellPaddingDefaultLeft; - } - - /** - * Default left cell margin/padding units. 0 -- null; 1-2 -- not relevant; 3 -- twips.. - */ - @Internal - public void setFtsCellPaddingDefaultLeft( byte field_47_ftsCellPaddingDefaultLeft ) - { - this.field_47_ftsCellPaddingDefaultLeft = field_47_ftsCellPaddingDefaultLeft; - } - - /** - * Default bottom cell margin/padding units. 0 -- null; 1-2 -- not relevant; 3 -- twips.. - */ - @Internal - public byte getFtsCellPaddingDefaultBottom() - { - return field_48_ftsCellPaddingDefaultBottom; - } - - /** - * Default bottom cell margin/padding units. 0 -- null; 1-2 -- not relevant; 3 -- twips.. - */ - @Internal - public void setFtsCellPaddingDefaultBottom( byte field_48_ftsCellPaddingDefaultBottom ) - { - this.field_48_ftsCellPaddingDefaultBottom = field_48_ftsCellPaddingDefaultBottom; - } - - /** - * Default right cell margin/padding units. 0 -- null; 1-2 -- not relevant; 3 -- twips.. - */ - @Internal - public byte getFtsCellPaddingDefaultRight() - { - return field_49_ftsCellPaddingDefaultRight; - } - - /** - * Default right cell margin/padding units. 0 -- null; 1-2 -- not relevant; 3 -- twips.. - */ - @Internal - public void setFtsCellPaddingDefaultRight( byte field_49_ftsCellPaddingDefaultRight ) - { - this.field_49_ftsCellPaddingDefaultRight = field_49_ftsCellPaddingDefaultRight; - } - - /** - * Default top cell spacings. - */ - @Internal - public short getWCellSpacingDefaultTop() - { - return field_50_wCellSpacingDefaultTop; - } - - /** - * Default top cell spacings. - */ - @Internal - public void setWCellSpacingDefaultTop( short field_50_wCellSpacingDefaultTop ) - { - this.field_50_wCellSpacingDefaultTop = field_50_wCellSpacingDefaultTop; - } - - /** - * Default left cell spacings. - */ - @Internal - public short getWCellSpacingDefaultLeft() - { - return field_51_wCellSpacingDefaultLeft; - } - - /** - * Default left cell spacings. - */ - @Internal - public void setWCellSpacingDefaultLeft( short field_51_wCellSpacingDefaultLeft ) - { - this.field_51_wCellSpacingDefaultLeft = field_51_wCellSpacingDefaultLeft; - } - - /** - * Default bottom cell spacings. - */ - @Internal - public short getWCellSpacingDefaultBottom() - { - return field_52_wCellSpacingDefaultBottom; - } - - /** - * Default bottom cell spacings. - */ - @Internal - public void setWCellSpacingDefaultBottom( short field_52_wCellSpacingDefaultBottom ) - { - this.field_52_wCellSpacingDefaultBottom = field_52_wCellSpacingDefaultBottom; - } - - /** - * Default right cell spacings. - */ - @Internal - public short getWCellSpacingDefaultRight() - { - return field_53_wCellSpacingDefaultRight; - } - - /** - * Default right cell spacings. - */ - @Internal - public void setWCellSpacingDefaultRight( short field_53_wCellSpacingDefaultRight ) - { - this.field_53_wCellSpacingDefaultRight = field_53_wCellSpacingDefaultRight; - } - - /** - * Default top cell spacings units. 0 -- null; 1-2 -- not relevant; 3 -- twips.. - */ - @Internal - public byte getFtsCellSpacingDefaultTop() - { - return field_54_ftsCellSpacingDefaultTop; - } - - /** - * Default top cell spacings units. 0 -- null; 1-2 -- not relevant; 3 -- twips.. - */ - @Internal - public void setFtsCellSpacingDefaultTop( byte field_54_ftsCellSpacingDefaultTop ) - { - this.field_54_ftsCellSpacingDefaultTop = field_54_ftsCellSpacingDefaultTop; - } - - /** - * Default left cell spacings units. 0 -- null; 1-2 -- not relevant; 3 -- twips.. - */ - @Internal - public byte getFtsCellSpacingDefaultLeft() - { - return field_55_ftsCellSpacingDefaultLeft; - } - - /** - * Default left cell spacings units. 0 -- null; 1-2 -- not relevant; 3 -- twips.. - */ - @Internal - public void setFtsCellSpacingDefaultLeft( byte field_55_ftsCellSpacingDefaultLeft ) - { - this.field_55_ftsCellSpacingDefaultLeft = field_55_ftsCellSpacingDefaultLeft; - } - - /** - * Default bottom cell spacings units. 0 -- null; 1-2 -- not relevant; 3 -- twips.. - */ - @Internal - public byte getFtsCellSpacingDefaultBottom() - { - return field_56_ftsCellSpacingDefaultBottom; - } - - /** - * Default bottom cell spacings units. 0 -- null; 1-2 -- not relevant; 3 -- twips.. - */ - @Internal - public void setFtsCellSpacingDefaultBottom( byte field_56_ftsCellSpacingDefaultBottom ) - { - this.field_56_ftsCellSpacingDefaultBottom = field_56_ftsCellSpacingDefaultBottom; - } - - /** - * Default right cell spacings units. 0 -- null; 1-2 -- not relevant; 3 -- twips.. - */ - @Internal - public byte getFtsCellSpacingDefaultRight() - { - return field_57_ftsCellSpacingDefaultRight; - } - - /** - * Default right cell spacings units. 0 -- null; 1-2 -- not relevant; 3 -- twips.. - */ - @Internal - public void setFtsCellSpacingDefaultRight( byte field_57_ftsCellSpacingDefaultRight ) - { - this.field_57_ftsCellSpacingDefaultRight = field_57_ftsCellSpacingDefaultRight; - } - - /** - * Default outer top cell margin/padding. - */ - @Internal - public short getWCellPaddingOuterTop() - { - return field_58_wCellPaddingOuterTop; - } - - /** - * Default outer top cell margin/padding. - */ - @Internal - public void setWCellPaddingOuterTop( short field_58_wCellPaddingOuterTop ) - { - this.field_58_wCellPaddingOuterTop = field_58_wCellPaddingOuterTop; - } - - /** - * Default outer left cell margin/padding. - */ - @Internal - public short getWCellPaddingOuterLeft() - { - return field_59_wCellPaddingOuterLeft; - } - - /** - * Default outer left cell margin/padding. - */ - @Internal - public void setWCellPaddingOuterLeft( short field_59_wCellPaddingOuterLeft ) - { - this.field_59_wCellPaddingOuterLeft = field_59_wCellPaddingOuterLeft; - } - - /** - * Default outer bottom cell margin/padding. - */ - @Internal - public short getWCellPaddingOuterBottom() - { - return field_60_wCellPaddingOuterBottom; - } - - /** - * Default outer bottom cell margin/padding. - */ - @Internal - public void setWCellPaddingOuterBottom( short field_60_wCellPaddingOuterBottom ) - { - this.field_60_wCellPaddingOuterBottom = field_60_wCellPaddingOuterBottom; - } - - /** - * Default outer right cell margin/padding. - */ - @Internal - public short getWCellPaddingOuterRight() - { - return field_61_wCellPaddingOuterRight; - } - - /** - * Default outer right cell margin/padding. - */ - @Internal - public void setWCellPaddingOuterRight( short field_61_wCellPaddingOuterRight ) - { - this.field_61_wCellPaddingOuterRight = field_61_wCellPaddingOuterRight; - } - - /** - * Default outer top cell margin/padding units. 0 -- null; 1-2 -- not relevant; 3 -- twips.. - */ - @Internal - public byte getFtsCellPaddingOuterTop() - { - return field_62_ftsCellPaddingOuterTop; - } - - /** - * Default outer top cell margin/padding units. 0 -- null; 1-2 -- not relevant; 3 -- twips.. - */ - @Internal - public void setFtsCellPaddingOuterTop( byte field_62_ftsCellPaddingOuterTop ) - { - this.field_62_ftsCellPaddingOuterTop = field_62_ftsCellPaddingOuterTop; - } - - /** - * Default outer left cell margin/padding units. 0 -- null; 1-2 -- not relevant; 3 -- twips.. - */ - @Internal - public byte getFtsCellPaddingOuterLeft() - { - return field_63_ftsCellPaddingOuterLeft; - } - - /** - * Default outer left cell margin/padding units. 0 -- null; 1-2 -- not relevant; 3 -- twips.. - */ - @Internal - public void setFtsCellPaddingOuterLeft( byte field_63_ftsCellPaddingOuterLeft ) - { - this.field_63_ftsCellPaddingOuterLeft = field_63_ftsCellPaddingOuterLeft; - } - - /** - * Default outer bottom cell margin/padding units. 0 -- null; 1-2 -- not relevant; 3 -- twips.. - */ - @Internal - public byte getFtsCellPaddingOuterBottom() - { - return field_64_ftsCellPaddingOuterBottom; - } - - /** - * Default outer bottom cell margin/padding units. 0 -- null; 1-2 -- not relevant; 3 -- twips.. - */ - @Internal - public void setFtsCellPaddingOuterBottom( byte field_64_ftsCellPaddingOuterBottom ) - { - this.field_64_ftsCellPaddingOuterBottom = field_64_ftsCellPaddingOuterBottom; - } - - /** - * Default outer right cell margin/padding units. 0 -- null; 1-2 -- not relevant; 3 -- twips.. - */ - @Internal - public byte getFtsCellPaddingOuterRight() - { - return field_65_ftsCellPaddingOuterRight; - } - - /** - * Default outer right cell margin/padding units. 0 -- null; 1-2 -- not relevant; 3 -- twips.. - */ - @Internal - public void setFtsCellPaddingOuterRight( byte field_65_ftsCellPaddingOuterRight ) - { - this.field_65_ftsCellPaddingOuterRight = field_65_ftsCellPaddingOuterRight; - } - - /** - * Default outer top cell spacing. - */ - @Internal - public short getWCellSpacingOuterTop() - { - return field_66_wCellSpacingOuterTop; - } - - /** - * Default outer top cell spacing. - */ - @Internal - public void setWCellSpacingOuterTop( short field_66_wCellSpacingOuterTop ) - { - this.field_66_wCellSpacingOuterTop = field_66_wCellSpacingOuterTop; - } - - /** - * Default outer left cell spacing. - */ - @Internal - public short getWCellSpacingOuterLeft() - { - return field_67_wCellSpacingOuterLeft; - } - - /** - * Default outer left cell spacing. - */ - @Internal - public void setWCellSpacingOuterLeft( short field_67_wCellSpacingOuterLeft ) - { - this.field_67_wCellSpacingOuterLeft = field_67_wCellSpacingOuterLeft; - } - - /** - * Default outer bottom cell spacing. - */ - @Internal - public short getWCellSpacingOuterBottom() - { - return field_68_wCellSpacingOuterBottom; - } - - /** - * Default outer bottom cell spacing. - */ - @Internal - public void setWCellSpacingOuterBottom( short field_68_wCellSpacingOuterBottom ) - { - this.field_68_wCellSpacingOuterBottom = field_68_wCellSpacingOuterBottom; - } - - /** - * Default outer right cell spacing. - */ - @Internal - public short getWCellSpacingOuterRight() - { - return field_69_wCellSpacingOuterRight; - } - - /** - * Default outer right cell spacing. - */ - @Internal - public void setWCellSpacingOuterRight( short field_69_wCellSpacingOuterRight ) - { - this.field_69_wCellSpacingOuterRight = field_69_wCellSpacingOuterRight; - } - - /** - * Default outer top cell spacings units. 0 -- null; 1-2 -- not relevant; 3 -- twips.. - */ - @Internal - public byte getFtsCellSpacingOuterTop() - { - return field_70_ftsCellSpacingOuterTop; - } - - /** - * Default outer top cell spacings units. 0 -- null; 1-2 -- not relevant; 3 -- twips.. - */ - @Internal - public void setFtsCellSpacingOuterTop( byte field_70_ftsCellSpacingOuterTop ) - { - this.field_70_ftsCellSpacingOuterTop = field_70_ftsCellSpacingOuterTop; - } - - /** - * Default outer left cell spacings units. 0 -- null; 1-2 -- not relevant; 3 -- twips.. - */ - @Internal - public byte getFtsCellSpacingOuterLeft() - { - return field_71_ftsCellSpacingOuterLeft; - } - - /** - * Default outer left cell spacings units. 0 -- null; 1-2 -- not relevant; 3 -- twips.. - */ - @Internal - public void setFtsCellSpacingOuterLeft( byte field_71_ftsCellSpacingOuterLeft ) - { - this.field_71_ftsCellSpacingOuterLeft = field_71_ftsCellSpacingOuterLeft; - } - - /** - * Default outer bottom cell spacings units. 0 -- null; 1-2 -- not relevant; 3 -- twips.. - */ - @Internal - public byte getFtsCellSpacingOuterBottom() - { - return field_72_ftsCellSpacingOuterBottom; - } - - /** - * Default outer bottom cell spacings units. 0 -- null; 1-2 -- not relevant; 3 -- twips.. - */ - @Internal - public void setFtsCellSpacingOuterBottom( byte field_72_ftsCellSpacingOuterBottom ) - { - this.field_72_ftsCellSpacingOuterBottom = field_72_ftsCellSpacingOuterBottom; - } - - /** - * Default outer right cell spacings units. 0 -- null; 1-2 -- not relevant; 3 -- twips.. - */ - @Internal - public byte getFtsCellSpacingOuterRight() - { - return field_73_ftsCellSpacingOuterRight; - } - - /** - * Default outer right cell spacings units. 0 -- null; 1-2 -- not relevant; 3 -- twips.. - */ - @Internal - public void setFtsCellSpacingOuterRight( byte field_73_ftsCellSpacingOuterRight ) - { - this.field_73_ftsCellSpacingOuterRight = field_73_ftsCellSpacingOuterRight; - } - - /** - * Get the rgtc field for the TAP record. - */ - @Internal - public TableCellDescriptor[] getRgtc() - { - return field_74_rgtc; - } - - /** - * Set the rgtc field for the TAP record. - */ - @Internal - public void setRgtc( TableCellDescriptor[] field_74_rgtc ) - { - this.field_74_rgtc = field_74_rgtc; - } - - /** - * Get the rgshd field for the TAP record. - */ - @Internal - public ShadingDescriptor[] getRgshd() - { - return field_75_rgshd; - } - - /** - * Set the rgshd field for the TAP record. - */ - @Internal - public void setRgshd( ShadingDescriptor[] field_75_rgshd ) - { - this.field_75_rgshd = field_75_rgshd; - } - - /** - * Set to 1 if property revision. - */ - @Internal - public byte getFPropRMark() - { - return field_76_fPropRMark; - } - - /** - * Set to 1 if property revision. - */ - @Internal - public void setFPropRMark( byte field_76_fPropRMark ) - { - this.field_76_fPropRMark = field_76_fPropRMark; - } - - /** - * Has old properties. - */ - @Internal - public byte getFHasOldProps() - { - return field_77_fHasOldProps; - } - - /** - * Has old properties. - */ - @Internal - public void setFHasOldProps( byte field_77_fHasOldProps ) - { - this.field_77_fHasOldProps = field_77_fHasOldProps; - } - - /** - * Size of each horizontal style band, in number of rows. - */ - @Internal - public short getCHorzBands() - { - return field_78_cHorzBands; - } - - /** - * Size of each horizontal style band, in number of rows. - */ - @Internal - public void setCHorzBands( short field_78_cHorzBands ) - { - this.field_78_cHorzBands = field_78_cHorzBands; - } - - /** - * Size of a vertical style band, in number of columns. - */ - @Internal - public short getCVertBands() - { - return field_79_cVertBands; - } - - /** - * Size of a vertical style band, in number of columns. - */ - @Internal - public void setCVertBands( short field_79_cVertBands ) - { - this.field_79_cVertBands = field_79_cVertBands; - } - - /** - * Border definition for inside horizontal borders. - */ - @Internal - public BorderCode getRgbrcInsideDefault_0() - { - return field_80_rgbrcInsideDefault_0; - } - - /** - * Border definition for inside horizontal borders. - */ - @Internal - public void setRgbrcInsideDefault_0( BorderCode field_80_rgbrcInsideDefault_0 ) - { - this.field_80_rgbrcInsideDefault_0 = field_80_rgbrcInsideDefault_0; - } - - /** - * Border definition for inside vertical borders. - */ - @Internal - public BorderCode getRgbrcInsideDefault_1() - { - return field_81_rgbrcInsideDefault_1; - } - - /** - * Border definition for inside vertical borders. - */ - @Internal - public void setRgbrcInsideDefault_1( BorderCode field_81_rgbrcInsideDefault_1 ) - { - this.field_81_rgbrcInsideDefault_1 = field_81_rgbrcInsideDefault_1; - } - - /** - * Sets the fAutofit field value. - * When set to 1, AutoFit this table - */ - @Internal - public void setFAutofit( boolean value ) - { - field_13_widthAndFitsFlags = fAutofit.setBoolean(field_13_widthAndFitsFlags, value); - } - - /** - * When set to 1, AutoFit this table - * @return the fAutofit field value. - */ - @Internal - public boolean isFAutofit() - { - return fAutofit.isSet(field_13_widthAndFitsFlags); - } - - /** - * Sets the fKeepFollow field value. - * When set to 1, keep this row with the following row - */ - @Internal - public void setFKeepFollow( boolean value ) - { - field_13_widthAndFitsFlags = fKeepFollow.setBoolean(field_13_widthAndFitsFlags, value); - } - - /** - * When set to 1, keep this row with the following row - * @return the fKeepFollow field value. - */ - @Internal - public boolean isFKeepFollow() - { - return fKeepFollow.isSet(field_13_widthAndFitsFlags); - } - - /** - * Sets the ftsWidth field value. - * Units for wWidth: 0 -- null; 1 -- auto, ignores wWidth, 2 -- percentage (in 50ths of a percent), 3 -- twips - */ - @Internal - public void setFtsWidth( byte value ) - { - field_13_widthAndFitsFlags = ftsWidth.setValue(field_13_widthAndFitsFlags, value); - } - - /** - * Units for wWidth: 0 -- null; 1 -- auto, ignores wWidth, 2 -- percentage (in 50ths of a percent), 3 -- twips - * @return the ftsWidth field value. - */ - @Internal - public byte getFtsWidth() - { - return ( byte )ftsWidth.getValue(field_13_widthAndFitsFlags); - } - - /** - * Sets the ftsWidthIndent field value. - * Units for wWidthIndent: 0 -- null; 1 -- auto, ignores wWidthIndent, 2 -- percentage (in 50ths of a percent), 3 -- twips - */ - @Internal - public void setFtsWidthIndent( byte value ) - { - field_13_widthAndFitsFlags = ftsWidthIndent.setValue(field_13_widthAndFitsFlags, value); - } - - /** - * Units for wWidthIndent: 0 -- null; 1 -- auto, ignores wWidthIndent, 2 -- percentage (in 50ths of a percent), 3 -- twips - * @return the ftsWidthIndent field value. - */ - @Internal - public byte getFtsWidthIndent() - { - return ( byte )ftsWidthIndent.getValue(field_13_widthAndFitsFlags); - } - - /** - * Sets the ftsWidthBefore field value. - * Units for wWidthBefore: 0 -- null; 1 -- auto, ignores wWidthBefore, 2 -- percentage (in 50ths of a percent), 3 -- twips - */ - @Internal - public void setFtsWidthBefore( byte value ) - { - field_13_widthAndFitsFlags = ftsWidthBefore.setValue(field_13_widthAndFitsFlags, value); - } - - /** - * Units for wWidthBefore: 0 -- null; 1 -- auto, ignores wWidthBefore, 2 -- percentage (in 50ths of a percent), 3 -- twips - * @return the ftsWidthBefore field value. - */ - @Internal - public byte getFtsWidthBefore() - { - return ( byte )ftsWidthBefore.getValue(field_13_widthAndFitsFlags); - } - - /** - * Sets the ftsWidthAfter field value. - * Units for wWidthAfter: 0 -- null; 1 -- auto, ignores wWidthAfter, 2 -- percentage (in 50ths of a percent), 3 -- twips - */ - @Internal - public void setFtsWidthAfter( byte value ) - { - field_13_widthAndFitsFlags = ftsWidthAfter.setValue(field_13_widthAndFitsFlags, value); - } - - /** - * Units for wWidthAfter: 0 -- null; 1 -- auto, ignores wWidthAfter, 2 -- percentage (in 50ths of a percent), 3 -- twips - * @return the ftsWidthAfter field value. - */ - @Internal - public byte getFtsWidthAfter() - { - return ( byte )ftsWidthAfter.getValue(field_13_widthAndFitsFlags); - } - - /** - * Sets the fNeverBeenAutofit field value. - * When 1, table has never been autofit - */ - @Internal - public void setFNeverBeenAutofit( boolean value ) - { - field_13_widthAndFitsFlags = fNeverBeenAutofit.setBoolean(field_13_widthAndFitsFlags, value); - } - - /** - * When 1, table has never been autofit - * @return the fNeverBeenAutofit field value. - */ - @Internal - public boolean isFNeverBeenAutofit() - { - return fNeverBeenAutofit.isSet(field_13_widthAndFitsFlags); - } - - /** - * Sets the fInvalAutofit field value. - * When 1, TAP is still valid, but autofit properties aren't - */ - @Internal - public void setFInvalAutofit( boolean value ) - { - field_13_widthAndFitsFlags = fInvalAutofit.setBoolean(field_13_widthAndFitsFlags, value); - } - - /** - * When 1, TAP is still valid, but autofit properties aren't - * @return the fInvalAutofit field value. - */ - @Internal - public boolean isFInvalAutofit() - { - return fInvalAutofit.isSet(field_13_widthAndFitsFlags); - } - - /** - * Sets the widthAndFitsFlags_empty1 field value. - * Not used - */ - @Internal - public void setWidthAndFitsFlags_empty1( byte value ) - { - field_13_widthAndFitsFlags = widthAndFitsFlags_empty1.setValue(field_13_widthAndFitsFlags, value); - } - - /** - * Not used - * @return the widthAndFitsFlags_empty1 field value. - */ - @Internal - public byte getWidthAndFitsFlags_empty1() - { - return ( byte )widthAndFitsFlags_empty1.getValue(field_13_widthAndFitsFlags); - } - - /** - * Sets the fVert field value. - * When 1, positioned in vertical text flow - */ - @Internal - public void setFVert( boolean value ) - { - field_13_widthAndFitsFlags = fVert.setBoolean(field_13_widthAndFitsFlags, value); - } - - /** - * When 1, positioned in vertical text flow - * @return the fVert field value. - */ - @Internal - public boolean isFVert() - { - return fVert.isSet(field_13_widthAndFitsFlags); - } - - /** - * Sets the pcVert field value. - * Vertical position code. Specifies coordinate frame to use when paragraphs are absolutely positioned. 0 -- vertical position coordinates are relative to margin; 1 -- coordinates are relative to page; 2 -- coordinates are relative to text. This means: relative to where the next non-APO text would have been placed if this APO did not exist. - */ - @Internal - public void setPcVert( byte value ) - { - field_13_widthAndFitsFlags = pcVert.setValue(field_13_widthAndFitsFlags, value); - } - - /** - * Vertical position code. Specifies coordinate frame to use when paragraphs are absolutely positioned. 0 -- vertical position coordinates are relative to margin; 1 -- coordinates are relative to page; 2 -- coordinates are relative to text. This means: relative to where the next non-APO text would have been placed if this APO did not exist. - * @return the pcVert field value. - */ - @Internal - public byte getPcVert() - { - return ( byte )pcVert.getValue(field_13_widthAndFitsFlags); - } - - /** - * Sets the pcHorz field value. - * Horizontal position code. Specifies coordinate frame to use when paragraphs are absolutely positioned. 0 -- horizontal position coordinates are relative to column; 1 -- coordinates are relative to margin; 2 -- coordinates are relative to page - */ - @Internal - public void setPcHorz( byte value ) - { - field_13_widthAndFitsFlags = pcHorz.setValue(field_13_widthAndFitsFlags, value); - } - - /** - * Horizontal position code. Specifies coordinate frame to use when paragraphs are absolutely positioned. 0 -- horizontal position coordinates are relative to column; 1 -- coordinates are relative to margin; 2 -- coordinates are relative to page - * @return the pcHorz field value. - */ - @Internal - public byte getPcHorz() - { - return ( byte )pcHorz.getValue(field_13_widthAndFitsFlags); - } - - /** - * Sets the widthAndFitsFlags_empty2 field value. - * Not used - */ - @Internal - public void setWidthAndFitsFlags_empty2( short value ) - { - field_13_widthAndFitsFlags = widthAndFitsFlags_empty2.setValue(field_13_widthAndFitsFlags, value); - } - - /** - * Not used - * @return the widthAndFitsFlags_empty2 field value. - */ - @Internal - public short getWidthAndFitsFlags_empty2() - { - return ( short )widthAndFitsFlags_empty2.getValue(field_13_widthAndFitsFlags); - } - - /** - * Sets the fFirstRow field value. - * Used internally by Word: first row - */ - @Internal - public void setFFirstRow( boolean value ) - { - field_25_internalFlags = fFirstRow.setBoolean(field_25_internalFlags, value); - } - - /** - * Used internally by Word: first row - * @return the fFirstRow field value. - */ - @Internal - public boolean isFFirstRow() - { - return fFirstRow.isSet(field_25_internalFlags); - } - - /** - * Sets the fLastRow field value. - * Used internally by Word: last row - */ - @Internal - public void setFLastRow( boolean value ) - { - field_25_internalFlags = fLastRow.setBoolean(field_25_internalFlags, value); - } - - /** - * Used internally by Word: last row - * @return the fLastRow field value. - */ - @Internal - public boolean isFLastRow() - { - return fLastRow.isSet(field_25_internalFlags); - } - - /** - * Sets the fOutline field value. - * Used internally by Word: row was cached for outline mode - */ - @Internal - public void setFOutline( boolean value ) - { - field_25_internalFlags = fOutline.setBoolean(field_25_internalFlags, value); - } - - /** - * Used internally by Word: row was cached for outline mode - * @return the fOutline field value. - */ - @Internal - public boolean isFOutline() - { - return fOutline.isSet(field_25_internalFlags); - } - - /** - * Sets the fOrigWordTableRules field value. - * Used internally by Word: table combining like Word 5.x for the Macintosh and WinWord 1.x - */ - @Internal - public void setFOrigWordTableRules( boolean value ) - { - field_25_internalFlags = fOrigWordTableRules.setBoolean(field_25_internalFlags, value); - } - - /** - * Used internally by Word: table combining like Word 5.x for the Macintosh and WinWord 1.x - * @return the fOrigWordTableRules field value. - */ - @Internal - public boolean isFOrigWordTableRules() - { - return fOrigWordTableRules.isSet(field_25_internalFlags); - } - - /** - * Sets the fCellSpacing field value. - * Used internally by Word: When set to 1 cell spacing is allowed - */ - @Internal - public void setFCellSpacing( boolean value ) - { - field_25_internalFlags = fCellSpacing.setBoolean(field_25_internalFlags, value); - } - - /** - * Used internally by Word: When set to 1 cell spacing is allowed - * @return the fCellSpacing field value. - */ - @Internal - public boolean isFCellSpacing() - { - return fCellSpacing.isSet(field_25_internalFlags); - } - - /** - * Sets the grpfTap_unused field value. - * Not used - */ - @Internal - public void setGrpfTap_unused( short value ) - { - field_25_internalFlags = grpfTap_unused.setValue(field_25_internalFlags, value); - } - - /** - * Not used - * @return the grpfTap_unused field value. - */ - @Internal - public short getGrpfTap_unused() - { - return ( short )grpfTap_unused.getValue(field_25_internalFlags); - } - - /** - * Sets the fWrapToWwd field value. - * Used internally by Word: Wrap to window is on when set to 1 - */ - @Internal - public void setFWrapToWwd( boolean value ) - { - field_32_viewFlags = fWrapToWwd.setBoolean(field_32_viewFlags, value); - } - - /** - * Used internally by Word: Wrap to window is on when set to 1 - * @return the fWrapToWwd field value. - */ - @Internal - public boolean isFWrapToWwd() - { - return fWrapToWwd.isSet(field_32_viewFlags); - } - - /** - * Sets the fNotPageView field value. - * Used internally by Word: when set to 1 we are not in Page View - */ - @Internal - public void setFNotPageView( boolean value ) - { - field_32_viewFlags = fNotPageView.setBoolean(field_32_viewFlags, value); - } - - /** - * Used internally by Word: when set to 1 we are not in Page View - * @return the fNotPageView field value. - */ - @Internal - public boolean isFNotPageView() - { - return fNotPageView.isSet(field_32_viewFlags); - } - - /** - * Sets the viewFlags_unused1 field value. - * Not used - */ - @Internal - public void setViewFlags_unused1( boolean value ) - { - field_32_viewFlags = viewFlags_unused1.setBoolean(field_32_viewFlags, value); - } - - /** - * Not used - * @return the viewFlags_unused1 field value. - */ - @Internal - public boolean isViewFlags_unused1() - { - return viewFlags_unused1.isSet(field_32_viewFlags); - } - - /** - * Sets the fWebView field value. - * Used internally by Word: Web View is on when set to 1 - */ - @Internal - public void setFWebView( boolean value ) - { - field_32_viewFlags = fWebView.setBoolean(field_32_viewFlags, value); - } - - /** - * Used internally by Word: Web View is on when set to 1 - * @return the fWebView field value. - */ - @Internal - public boolean isFWebView() - { - return fWebView.isSet(field_32_viewFlags); - } - - /** - * Sets the fAdjusted field value. - * Used internally by Word - */ - @Internal - public void setFAdjusted( boolean value ) - { - field_32_viewFlags = fAdjusted.setBoolean(field_32_viewFlags, value); - } - - /** - * Used internally by Word - * @return the fAdjusted field value. - */ - @Internal - public boolean isFAdjusted() - { - return fAdjusted.isSet(field_32_viewFlags); - } - - /** - * Sets the viewFlags_unused2 field value. - * Not used - */ - @Internal - public void setViewFlags_unused2( short value ) - { - field_32_viewFlags = viewFlags_unused2.setValue(field_32_viewFlags, value); - } - - /** - * Not used - * @return the viewFlags_unused2 field value. - */ - @Internal - public short getViewFlags_unused2() - { - return ( short )viewFlags_unused2.getValue(field_32_viewFlags); - } - -} // END OF CLASS diff --git a/src/scratchpad/src/org/apache/poi/hwpf/model/types/TBDAbstractType.java b/src/scratchpad/src/org/apache/poi/hwpf/model/types/TBDAbstractType.java deleted file mode 100644 index 2d11178d7..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/model/types/TBDAbstractType.java +++ /dev/null @@ -1,162 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.model.types; - - -import org.apache.poi.util.BitField; -import org.apache.poi.util.Internal; - -/** - * The TBD is a substructure of the PAP.

    Class and fields descriptions are quoted from - Microsoft Office Word 97-2007 Binary File Format - - *

    - * NOTE: This source is automatically generated please do not modify this file. Either subclass or - * remove the record in src/types/definitions. - *

    - * This class is internal. It content or properties may change without notice - * due to changes in our knowledge of internal Microsoft Word binary structures. - - * @author Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary File Format - Specification [*.doc] - - */ -@Internal -public abstract class TBDAbstractType -{ - - protected byte field_1_value; - /**/private static BitField jc = new BitField(0x07); - /**/private static BitField tlc = new BitField(0x38); - /**/private static BitField reserved = new BitField(0xc0); - - protected TBDAbstractType() - { - } - - protected void fillFields( byte[] data, int offset ) - { - field_1_value = data[ 0x0 + offset ]; - } - - public void serialize( byte[] data, int offset ) - { - data[ 0x0 + offset] = field_1_value; - } - - /** - * Size of record - */ - public static int getSize() - { - return 0 + 1; - } - - public String toString() - { - StringBuilder builder = new StringBuilder(); - builder.append("[TBD]\n"); - builder.append(" .value = "); - builder.append(" (").append(getValue()).append(" )\n"); - builder.append(" .jc = ").append(getJc()).append('\n'); - builder.append(" .tlc = ").append(getTlc()).append('\n'); - builder.append(" .reserved = ").append(getReserved()).append('\n'); - - builder.append("[/TBD]\n"); - return builder.toString(); - } - - /** - * Get the value field for the TBD record. - */ - @Internal - public byte getValue() - { - return field_1_value; - } - - /** - * Set the value field for the TBD record. - */ - @Internal - public void setValue( byte field_1_value ) - { - this.field_1_value = field_1_value; - } - - /** - * Sets the jc field value. - * Justification code - */ - @Internal - public void setJc( byte value ) - { - field_1_value = (byte)jc.setValue(field_1_value, value); - } - - /** - * Justification code - * @return the jc field value. - */ - @Internal - public byte getJc() - { - return ( byte )jc.getValue(field_1_value); - } - - /** - * Sets the tlc field value. - * Tab leader code - */ - @Internal - public void setTlc( byte value ) - { - field_1_value = (byte)tlc.setValue(field_1_value, value); - } - - /** - * Tab leader code - * @return the tlc field value. - */ - @Internal - public byte getTlc() - { - return ( byte )tlc.getValue(field_1_value); - } - - /** - * Sets the reserved field value. - * - */ - @Internal - public void setReserved( byte value ) - { - field_1_value = (byte)reserved.setValue(field_1_value, value); - } - - /** - * - * @return the reserved field value. - */ - @Internal - public byte getReserved() - { - return ( byte )reserved.getValue(field_1_value); - } - -} // END OF CLASS diff --git a/src/scratchpad/src/org/apache/poi/hwpf/model/types/TCAbstractType.java b/src/scratchpad/src/org/apache/poi/hwpf/model/types/TCAbstractType.java deleted file mode 100644 index a87165316..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/model/types/TCAbstractType.java +++ /dev/null @@ -1,808 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.model.types; - - -import org.apache.poi.hwpf.usermodel.*; -import org.apache.poi.util.*; - -/** - * Table Cell Descriptor. - *

    - * NOTE: This source is automatically generated please do not modify this file. Either subclass or - * remove the record in src/types/definitions. - *

    - * This class is internal. It content or properties may change without notice - * due to changes in our knowledge of internal Microsoft Word binary structures. - - * @author S. Ryan Ackley. Field descriptions are quoted from Microsoft Office Word 97-2007 Binary - File Format (.doc) Specification - - */ -@Internal -public abstract class TCAbstractType -{ - - protected short field_1_rgf; - /**/private static BitField fFirstMerged = new BitField(0x0001); - /**/private static BitField fMerged = new BitField(0x0002); - /**/private static BitField fVertical = new BitField(0x0004); - /**/private static BitField fBackward = new BitField(0x0008); - /**/private static BitField fRotateFont = new BitField(0x0010); - /**/private static BitField fVertMerge = new BitField(0x0020); - /**/private static BitField fVertRestart = new BitField(0x0040); - /**/private static BitField vertAlign = new BitField(0x0180); - /**/private static BitField ftsWidth = new BitField(0x0E00); - /**/private static BitField fFitText = new BitField(0x1000); - /**/private static BitField fNoWrap = new BitField(0x2000); - /**/private static BitField fUnused = new BitField(0xC000); - protected short field_2_wWidth; - protected ShadingDescriptor field_3_shd; - protected short field_4_wCellPaddingLeft; - protected short field_5_wCellPaddingTop; - protected short field_6_wCellPaddingBottom; - protected short field_7_wCellPaddingRight; - protected byte field_8_ftsCellPaddingLeft; - protected byte field_9_ftsCellPaddingTop; - protected byte field_10_ftsCellPaddingBottom; - protected byte field_11_ftsCellPaddingRight; - protected short field_12_wCellSpacingLeft; - protected short field_13_wCellSpacingTop; - protected short field_14_wCellSpacingBottom; - protected short field_15_wCellSpacingRight; - protected byte field_16_ftsCellSpacingLeft; - protected byte field_17_ftsCellSpacingTop; - protected byte field_18_ftsCellSpacingBottom; - protected byte field_19_ftsCellSpacingRight; - protected BorderCode field_20_brcTop; - protected BorderCode field_21_brcLeft; - protected BorderCode field_22_brcBottom; - protected BorderCode field_23_brcRight; - - protected TCAbstractType() - { - this.field_3_shd = new ShadingDescriptor(); - this.field_20_brcTop = new BorderCode(); - this.field_21_brcLeft = new BorderCode(); - this.field_22_brcBottom = new BorderCode(); - this.field_23_brcRight = new BorderCode(); - } - - - public String toString() - { - StringBuilder builder = new StringBuilder(); - builder.append("[TC]\n"); - builder.append(" .rgf = "); - builder.append(" (").append(getRgf()).append(" )\n"); - builder.append(" .fFirstMerged = ").append(isFFirstMerged()).append('\n'); - builder.append(" .fMerged = ").append(isFMerged()).append('\n'); - builder.append(" .fVertical = ").append(isFVertical()).append('\n'); - builder.append(" .fBackward = ").append(isFBackward()).append('\n'); - builder.append(" .fRotateFont = ").append(isFRotateFont()).append('\n'); - builder.append(" .fVertMerge = ").append(isFVertMerge()).append('\n'); - builder.append(" .fVertRestart = ").append(isFVertRestart()).append('\n'); - builder.append(" .vertAlign = ").append(getVertAlign()).append('\n'); - builder.append(" .ftsWidth = ").append(getFtsWidth()).append('\n'); - builder.append(" .fFitText = ").append(isFFitText()).append('\n'); - builder.append(" .fNoWrap = ").append(isFNoWrap()).append('\n'); - builder.append(" .fUnused = ").append(getFUnused()).append('\n'); - builder.append(" .wWidth = "); - builder.append(" (").append(getWWidth()).append(" )\n"); - builder.append(" .shd = "); - builder.append(" (").append(getShd()).append(" )\n"); - builder.append(" .wCellPaddingLeft = "); - builder.append(" (").append(getWCellPaddingLeft()).append(" )\n"); - builder.append(" .wCellPaddingTop = "); - builder.append(" (").append(getWCellPaddingTop()).append(" )\n"); - builder.append(" .wCellPaddingBottom = "); - builder.append(" (").append(getWCellPaddingBottom()).append(" )\n"); - builder.append(" .wCellPaddingRight = "); - builder.append(" (").append(getWCellPaddingRight()).append(" )\n"); - builder.append(" .ftsCellPaddingLeft = "); - builder.append(" (").append(getFtsCellPaddingLeft()).append(" )\n"); - builder.append(" .ftsCellPaddingTop = "); - builder.append(" (").append(getFtsCellPaddingTop()).append(" )\n"); - builder.append(" .ftsCellPaddingBottom = "); - builder.append(" (").append(getFtsCellPaddingBottom()).append(" )\n"); - builder.append(" .ftsCellPaddingRight = "); - builder.append(" (").append(getFtsCellPaddingRight()).append(" )\n"); - builder.append(" .wCellSpacingLeft = "); - builder.append(" (").append(getWCellSpacingLeft()).append(" )\n"); - builder.append(" .wCellSpacingTop = "); - builder.append(" (").append(getWCellSpacingTop()).append(" )\n"); - builder.append(" .wCellSpacingBottom = "); - builder.append(" (").append(getWCellSpacingBottom()).append(" )\n"); - builder.append(" .wCellSpacingRight = "); - builder.append(" (").append(getWCellSpacingRight()).append(" )\n"); - builder.append(" .ftsCellSpacingLeft = "); - builder.append(" (").append(getFtsCellSpacingLeft()).append(" )\n"); - builder.append(" .ftsCellSpacingTop = "); - builder.append(" (").append(getFtsCellSpacingTop()).append(" )\n"); - builder.append(" .ftsCellSpacingBottom = "); - builder.append(" (").append(getFtsCellSpacingBottom()).append(" )\n"); - builder.append(" .ftsCellSpacingRight = "); - builder.append(" (").append(getFtsCellSpacingRight()).append(" )\n"); - builder.append(" .brcTop = "); - builder.append(" (").append(getBrcTop()).append(" )\n"); - builder.append(" .brcLeft = "); - builder.append(" (").append(getBrcLeft()).append(" )\n"); - builder.append(" .brcBottom = "); - builder.append(" (").append(getBrcBottom()).append(" )\n"); - builder.append(" .brcRight = "); - builder.append(" (").append(getBrcRight()).append(" )\n"); - - builder.append("[/TC]\n"); - return builder.toString(); - } - - /** - * Get the rgf field for the TC record. - */ - @Internal - public short getRgf() - { - return field_1_rgf; - } - - /** - * Set the rgf field for the TC record. - */ - @Internal - public void setRgf( short field_1_rgf ) - { - this.field_1_rgf = field_1_rgf; - } - - /** - * Preferred cell width. - */ - @Internal - public short getWWidth() - { - return field_2_wWidth; - } - - /** - * Preferred cell width. - */ - @Internal - public void setWWidth( short field_2_wWidth ) - { - this.field_2_wWidth = field_2_wWidth; - } - - /** - * Cell shading. - */ - @Internal - public ShadingDescriptor getShd() - { - return field_3_shd; - } - - /** - * Cell shading. - */ - @Internal - public void setShd( ShadingDescriptor field_3_shd ) - { - this.field_3_shd = field_3_shd; - } - - /** - * Left cell margin/padding. - */ - @Internal - public short getWCellPaddingLeft() - { - return field_4_wCellPaddingLeft; - } - - /** - * Left cell margin/padding. - */ - @Internal - public void setWCellPaddingLeft( short field_4_wCellPaddingLeft ) - { - this.field_4_wCellPaddingLeft = field_4_wCellPaddingLeft; - } - - /** - * Top cell margin/padding. - */ - @Internal - public short getWCellPaddingTop() - { - return field_5_wCellPaddingTop; - } - - /** - * Top cell margin/padding. - */ - @Internal - public void setWCellPaddingTop( short field_5_wCellPaddingTop ) - { - this.field_5_wCellPaddingTop = field_5_wCellPaddingTop; - } - - /** - * Bottom cell margin/padding. - */ - @Internal - public short getWCellPaddingBottom() - { - return field_6_wCellPaddingBottom; - } - - /** - * Bottom cell margin/padding. - */ - @Internal - public void setWCellPaddingBottom( short field_6_wCellPaddingBottom ) - { - this.field_6_wCellPaddingBottom = field_6_wCellPaddingBottom; - } - - /** - * Right cell margin/padding. - */ - @Internal - public short getWCellPaddingRight() - { - return field_7_wCellPaddingRight; - } - - /** - * Right cell margin/padding. - */ - @Internal - public void setWCellPaddingRight( short field_7_wCellPaddingRight ) - { - this.field_7_wCellPaddingRight = field_7_wCellPaddingRight; - } - - /** - * Left cell margin/padding units. - */ - @Internal - public byte getFtsCellPaddingLeft() - { - return field_8_ftsCellPaddingLeft; - } - - /** - * Left cell margin/padding units. - */ - @Internal - public void setFtsCellPaddingLeft( byte field_8_ftsCellPaddingLeft ) - { - this.field_8_ftsCellPaddingLeft = field_8_ftsCellPaddingLeft; - } - - /** - * Top cell margin/padding units. - */ - @Internal - public byte getFtsCellPaddingTop() - { - return field_9_ftsCellPaddingTop; - } - - /** - * Top cell margin/padding units. - */ - @Internal - public void setFtsCellPaddingTop( byte field_9_ftsCellPaddingTop ) - { - this.field_9_ftsCellPaddingTop = field_9_ftsCellPaddingTop; - } - - /** - * Bottom cell margin/padding units. - */ - @Internal - public byte getFtsCellPaddingBottom() - { - return field_10_ftsCellPaddingBottom; - } - - /** - * Bottom cell margin/padding units. - */ - @Internal - public void setFtsCellPaddingBottom( byte field_10_ftsCellPaddingBottom ) - { - this.field_10_ftsCellPaddingBottom = field_10_ftsCellPaddingBottom; - } - - /** - * Right cell margin/padding units. - */ - @Internal - public byte getFtsCellPaddingRight() - { - return field_11_ftsCellPaddingRight; - } - - /** - * Right cell margin/padding units. - */ - @Internal - public void setFtsCellPaddingRight( byte field_11_ftsCellPaddingRight ) - { - this.field_11_ftsCellPaddingRight = field_11_ftsCellPaddingRight; - } - - /** - * Left cell spacing. - */ - @Internal - public short getWCellSpacingLeft() - { - return field_12_wCellSpacingLeft; - } - - /** - * Left cell spacing. - */ - @Internal - public void setWCellSpacingLeft( short field_12_wCellSpacingLeft ) - { - this.field_12_wCellSpacingLeft = field_12_wCellSpacingLeft; - } - - /** - * Top cell spacing. - */ - @Internal - public short getWCellSpacingTop() - { - return field_13_wCellSpacingTop; - } - - /** - * Top cell spacing. - */ - @Internal - public void setWCellSpacingTop( short field_13_wCellSpacingTop ) - { - this.field_13_wCellSpacingTop = field_13_wCellSpacingTop; - } - - /** - * Bottom cell spacing. - */ - @Internal - public short getWCellSpacingBottom() - { - return field_14_wCellSpacingBottom; - } - - /** - * Bottom cell spacing. - */ - @Internal - public void setWCellSpacingBottom( short field_14_wCellSpacingBottom ) - { - this.field_14_wCellSpacingBottom = field_14_wCellSpacingBottom; - } - - /** - * Right cell spacing. - */ - @Internal - public short getWCellSpacingRight() - { - return field_15_wCellSpacingRight; - } - - /** - * Right cell spacing. - */ - @Internal - public void setWCellSpacingRight( short field_15_wCellSpacingRight ) - { - this.field_15_wCellSpacingRight = field_15_wCellSpacingRight; - } - - /** - * Left cell spacing units. - */ - @Internal - public byte getFtsCellSpacingLeft() - { - return field_16_ftsCellSpacingLeft; - } - - /** - * Left cell spacing units. - */ - @Internal - public void setFtsCellSpacingLeft( byte field_16_ftsCellSpacingLeft ) - { - this.field_16_ftsCellSpacingLeft = field_16_ftsCellSpacingLeft; - } - - /** - * Top cell spacing units. - */ - @Internal - public byte getFtsCellSpacingTop() - { - return field_17_ftsCellSpacingTop; - } - - /** - * Top cell spacing units. - */ - @Internal - public void setFtsCellSpacingTop( byte field_17_ftsCellSpacingTop ) - { - this.field_17_ftsCellSpacingTop = field_17_ftsCellSpacingTop; - } - - /** - * Bottom cell spacing units. - */ - @Internal - public byte getFtsCellSpacingBottom() - { - return field_18_ftsCellSpacingBottom; - } - - /** - * Bottom cell spacing units. - */ - @Internal - public void setFtsCellSpacingBottom( byte field_18_ftsCellSpacingBottom ) - { - this.field_18_ftsCellSpacingBottom = field_18_ftsCellSpacingBottom; - } - - /** - * Right cell spacing units. - */ - @Internal - public byte getFtsCellSpacingRight() - { - return field_19_ftsCellSpacingRight; - } - - /** - * Right cell spacing units. - */ - @Internal - public void setFtsCellSpacingRight( byte field_19_ftsCellSpacingRight ) - { - this.field_19_ftsCellSpacingRight = field_19_ftsCellSpacingRight; - } - - /** - * Top border. - */ - @Internal - public BorderCode getBrcTop() - { - return field_20_brcTop; - } - - /** - * Top border. - */ - @Internal - public void setBrcTop( BorderCode field_20_brcTop ) - { - this.field_20_brcTop = field_20_brcTop; - } - - /** - * Left border. - */ - @Internal - public BorderCode getBrcLeft() - { - return field_21_brcLeft; - } - - /** - * Left border. - */ - @Internal - public void setBrcLeft( BorderCode field_21_brcLeft ) - { - this.field_21_brcLeft = field_21_brcLeft; - } - - /** - * Bottom border. - */ - @Internal - public BorderCode getBrcBottom() - { - return field_22_brcBottom; - } - - /** - * Bottom border. - */ - @Internal - public void setBrcBottom( BorderCode field_22_brcBottom ) - { - this.field_22_brcBottom = field_22_brcBottom; - } - - /** - * Right border. - */ - @Internal - public BorderCode getBrcRight() - { - return field_23_brcRight; - } - - /** - * Right border. - */ - @Internal - public void setBrcRight( BorderCode field_23_brcRight ) - { - this.field_23_brcRight = field_23_brcRight; - } - - /** - * Sets the fFirstMerged field value. - * When 1, cell is first cell of a range of cells that have been merged. When a cell is merged, the display areas of the merged cells are consolidated and the text within the cells is interpreted as belonging to one text stream for purposes of calculating line breaks. - */ - @Internal - public void setFFirstMerged( boolean value ) - { - field_1_rgf = (short)fFirstMerged.setBoolean(field_1_rgf, value); - } - - /** - * When 1, cell is first cell of a range of cells that have been merged. When a cell is merged, the display areas of the merged cells are consolidated and the text within the cells is interpreted as belonging to one text stream for purposes of calculating line breaks. - * @return the fFirstMerged field value. - */ - @Internal - public boolean isFFirstMerged() - { - return fFirstMerged.isSet(field_1_rgf); - } - - /** - * Sets the fMerged field value. - * When 1, cell has been merged with preceding cell - */ - @Internal - public void setFMerged( boolean value ) - { - field_1_rgf = (short)fMerged.setBoolean(field_1_rgf, value); - } - - /** - * When 1, cell has been merged with preceding cell - * @return the fMerged field value. - */ - @Internal - public boolean isFMerged() - { - return fMerged.isSet(field_1_rgf); - } - - /** - * Sets the fVertical field value. - * When 1, cell has vertical text flow - */ - @Internal - public void setFVertical( boolean value ) - { - field_1_rgf = (short)fVertical.setBoolean(field_1_rgf, value); - } - - /** - * When 1, cell has vertical text flow - * @return the fVertical field value. - */ - @Internal - public boolean isFVertical() - { - return fVertical.isSet(field_1_rgf); - } - - /** - * Sets the fBackward field value. - * For a vertical table cell, text flow is bottom to top when 1 and is bottom to top when 0 - */ - @Internal - public void setFBackward( boolean value ) - { - field_1_rgf = (short)fBackward.setBoolean(field_1_rgf, value); - } - - /** - * For a vertical table cell, text flow is bottom to top when 1 and is bottom to top when 0 - * @return the fBackward field value. - */ - @Internal - public boolean isFBackward() - { - return fBackward.isSet(field_1_rgf); - } - - /** - * Sets the fRotateFont field value. - * When 1, cell has rotated characters (i.e. uses @font) - */ - @Internal - public void setFRotateFont( boolean value ) - { - field_1_rgf = (short)fRotateFont.setBoolean(field_1_rgf, value); - } - - /** - * When 1, cell has rotated characters (i.e. uses @font) - * @return the fRotateFont field value. - */ - @Internal - public boolean isFRotateFont() - { - return fRotateFont.isSet(field_1_rgf); - } - - /** - * Sets the fVertMerge field value. - * When 1, cell is vertically merged with the cell(s) above and/or below. When cells are vertically merged, the display area of the merged cells are consolidated. The consolidated area is used to display the contents of the first vertically merged cell (the cell with fVertRestart set to 1), and all other vertically merged cells (those with fVertRestart set to 0) must be empty. Cells can only be merged vertically if their left and right boundaries are (nearly) identical (i.e. if corresponding entries in rgdxaCenter of the table rows differ by at most 3). - */ - @Internal - public void setFVertMerge( boolean value ) - { - field_1_rgf = (short)fVertMerge.setBoolean(field_1_rgf, value); - } - - /** - * When 1, cell is vertically merged with the cell(s) above and/or below. When cells are vertically merged, the display area of the merged cells are consolidated. The consolidated area is used to display the contents of the first vertically merged cell (the cell with fVertRestart set to 1), and all other vertically merged cells (those with fVertRestart set to 0) must be empty. Cells can only be merged vertically if their left and right boundaries are (nearly) identical (i.e. if corresponding entries in rgdxaCenter of the table rows differ by at most 3). - * @return the fVertMerge field value. - */ - @Internal - public boolean isFVertMerge() - { - return fVertMerge.isSet(field_1_rgf); - } - - /** - * Sets the fVertRestart field value. - * When 1, the cell is the first of a set of vertically merged cells. The contents of a cell with fVertStart set to 1 are displayed in the consolidated area belonging to the entire set of vertically merged cells. Vertically merged cells with fVertRestart set to 0 must be empty. - */ - @Internal - public void setFVertRestart( boolean value ) - { - field_1_rgf = (short)fVertRestart.setBoolean(field_1_rgf, value); - } - - /** - * When 1, the cell is the first of a set of vertically merged cells. The contents of a cell with fVertStart set to 1 are displayed in the consolidated area belonging to the entire set of vertically merged cells. Vertically merged cells with fVertRestart set to 0 must be empty. - * @return the fVertRestart field value. - */ - @Internal - public boolean isFVertRestart() - { - return fVertRestart.isSet(field_1_rgf); - } - - /** - * Sets the vertAlign field value. - * Specifies the alignment of the cell contents relative to text flow (e.g. in a cell with bottom to top text flow and bottom vertical alignment, the text is shifted horizontally to match the cell's right boundary) - */ - @Internal - public void setVertAlign( byte value ) - { - field_1_rgf = (short)vertAlign.setValue(field_1_rgf, value); - } - - /** - * Specifies the alignment of the cell contents relative to text flow (e.g. in a cell with bottom to top text flow and bottom vertical alignment, the text is shifted horizontally to match the cell's right boundary) - * @return the vertAlign field value. - */ - @Internal - public byte getVertAlign() - { - return ( byte )vertAlign.getValue(field_1_rgf); - } - - /** - * Sets the ftsWidth field value. - * Units for wWidth - */ - @Internal - public void setFtsWidth( byte value ) - { - field_1_rgf = (short)ftsWidth.setValue(field_1_rgf, value); - } - - /** - * Units for wWidth - * @return the ftsWidth field value. - */ - @Internal - public byte getFtsWidth() - { - return ( byte )ftsWidth.getValue(field_1_rgf); - } - - /** - * Sets the fFitText field value. - * When 1, make the text fit the table cell - */ - @Internal - public void setFFitText( boolean value ) - { - field_1_rgf = (short)fFitText.setBoolean(field_1_rgf, value); - } - - /** - * When 1, make the text fit the table cell - * @return the fFitText field value. - */ - @Internal - public boolean isFFitText() - { - return fFitText.isSet(field_1_rgf); - } - - /** - * Sets the fNoWrap field value. - * When 1, do not allow text to wrap in the table cell - */ - @Internal - public void setFNoWrap( boolean value ) - { - field_1_rgf = (short)fNoWrap.setBoolean(field_1_rgf, value); - } - - /** - * When 1, do not allow text to wrap in the table cell - * @return the fNoWrap field value. - */ - @Internal - public boolean isFNoWrap() - { - return fNoWrap.isSet(field_1_rgf); - } - - /** - * Sets the fUnused field value. - * Not used - */ - @Internal - public void setFUnused( byte value ) - { - field_1_rgf = (short)fUnused.setValue(field_1_rgf, value); - } - - /** - * Not used - * @return the fUnused field value. - */ - @Internal - public byte getFUnused() - { - return ( byte )fUnused.getValue(field_1_rgf); - } - -} // END OF CLASS diff --git a/src/scratchpad/src/org/apache/poi/hwpf/model/types/TLPAbstractType.java b/src/scratchpad/src/org/apache/poi/hwpf/model/types/TLPAbstractType.java deleted file mode 100644 index 0e6ad3a88..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/model/types/TLPAbstractType.java +++ /dev/null @@ -1,292 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.model.types; - -import org.apache.poi.util.BitField; -import org.apache.poi.util.Internal; -import org.apache.poi.util.LittleEndian; - -/** - * Table Autoformat Look sPecifier (TLP). - *

    - * Class and fields descriptions are quoted from Microsoft Office Word 97-2007 - * Binary File Format - * - * NOTE: This source is automatically generated please do not modify this file. - * Either subclass or remove the record in src/records/definitions. - * - * @author Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary - * File Format Specification [*.doc] - */ -@Internal -public abstract class TLPAbstractType -{ - - protected short field_1_itl; - protected byte field_2_tlp_flags; - private static final BitField fBorders = new BitField( 0x0001 ); - private static final BitField fShading = new BitField( 0x0002 ); - private static final BitField fFont = new BitField( 0x0004 ); - private static final BitField fColor = new BitField( 0x0008 ); - private static final BitField fBestFit = new BitField( 0x0010 ); - private static final BitField fHdrRows = new BitField( 0x0020 ); - private static final BitField fLastRow = new BitField( 0x0040 ); - - public TLPAbstractType() - { - - } - - protected void fillFields( byte[] data, int offset ) - { - field_1_itl = LittleEndian.getShort( data, 0x0 + offset ); - field_2_tlp_flags = data[0x2 + offset]; - } - - public void serialize( byte[] data, int offset ) - { - LittleEndian.putShort( data, 0x0 + offset, field_1_itl ); - data[0x2 + offset] = field_2_tlp_flags; - } - - public String toString() - { - StringBuffer buffer = new StringBuffer(); - - buffer.append( "[TLP]\n" ); - - buffer.append( " .itl = " ); - buffer.append( " (" ).append( getItl() ).append( " )\n" ); - - buffer.append( " .tlp_flags = " ); - buffer.append( " (" ).append( getTlp_flags() ).append( " )\n" ); - buffer.append( " .fBorders = " ) - .append( isFBorders() ).append( '\n' ); - buffer.append( " .fShading = " ) - .append( isFShading() ).append( '\n' ); - buffer.append( " .fFont = " ) - .append( isFFont() ).append( '\n' ); - buffer.append( " .fColor = " ) - .append( isFColor() ).append( '\n' ); - buffer.append( " .fBestFit = " ) - .append( isFBestFit() ).append( '\n' ); - buffer.append( " .fHdrRows = " ) - .append( isFHdrRows() ).append( '\n' ); - buffer.append( " .fLastRow = " ) - .append( isFLastRow() ).append( '\n' ); - - buffer.append( "[/TLP]\n" ); - return buffer.toString(); - } - - /** - * Size of record (exluding 4 byte header) - */ - public int getSize() - { - return 4 + +2 + 1; - } - - /** - * Get the itl field for the TLP record. - */ - public short getItl() - { - return field_1_itl; - } - - /** - * Set the itl field for the TLP record. - */ - public void setItl( short field_1_itl ) - { - this.field_1_itl = field_1_itl; - } - - /** - * Get the tlp_flags field for the TLP record. - */ - public byte getTlp_flags() - { - return field_2_tlp_flags; - } - - /** - * Set the tlp_flags field for the TLP record. - */ - public void setTlp_flags( byte field_2_tlp_flags ) - { - this.field_2_tlp_flags = field_2_tlp_flags; - } - - /** - * Sets the fBorders field value. When == 1, use the border properties from - * the selected table look - */ - public void setFBorders( boolean value ) - { - field_2_tlp_flags = (byte) fBorders.setBoolean( field_2_tlp_flags, - value ); - - } - - /** - * When == 1, use the border properties from the selected table look - * - * @return the fBorders field value. - */ - public boolean isFBorders() - { - return fBorders.isSet( field_2_tlp_flags ); - - } - - /** - * Sets the fShading field value. When == 1, use the shading properties from - * the selected table look - */ - public void setFShading( boolean value ) - { - field_2_tlp_flags = (byte) fShading.setBoolean( field_2_tlp_flags, - value ); - - } - - /** - * When == 1, use the shading properties from the selected table look - * - * @return the fShading field value. - */ - public boolean isFShading() - { - return fShading.isSet( field_2_tlp_flags ); - - } - - /** - * Sets the fFont field value. When == 1, use the font from the selected - * table look - */ - public void setFFont( boolean value ) - { - field_2_tlp_flags = (byte) fFont.setBoolean( field_2_tlp_flags, value ); - - } - - /** - * When == 1, use the font from the selected table look - * - * @return the fFont field value. - */ - public boolean isFFont() - { - return fFont.isSet( field_2_tlp_flags ); - - } - - /** - * Sets the fColor field value. When == 1, use the color from the selected - * table look - */ - public void setFColor( boolean value ) - { - field_2_tlp_flags = (byte) fColor.setBoolean( field_2_tlp_flags, value ); - - } - - /** - * When == 1, use the color from the selected table look - * - * @return the fColor field value. - */ - public boolean isFColor() - { - return fColor.isSet( field_2_tlp_flags ); - - } - - /** - * Sets the fBestFit field value. When == 1, do best fit from the selected - * table look - */ - public void setFBestFit( boolean value ) - { - field_2_tlp_flags = (byte) fBestFit.setBoolean( field_2_tlp_flags, - value ); - - } - - /** - * When == 1, do best fit from the selected table look - * - * @return the fBestFit field value. - */ - public boolean isFBestFit() - { - return fBestFit.isSet( field_2_tlp_flags ); - - } - - /** - * Sets the fHdrRows field value. When == 1, apply properties from the - * selected table look to the header rows in the table - */ - public void setFHdrRows( boolean value ) - { - field_2_tlp_flags = (byte) fHdrRows.setBoolean( field_2_tlp_flags, - value ); - - } - - /** - * When == 1, apply properties from the selected table look to the header - * rows in the table - * - * @return the fHdrRows field value. - */ - public boolean isFHdrRows() - { - return fHdrRows.isSet( field_2_tlp_flags ); - - } - - /** - * Sets the fLastRow field value. When == 1, apply properties from the - * selected table look to the last row in the table - */ - public void setFLastRow( boolean value ) - { - field_2_tlp_flags = (byte) fLastRow.setBoolean( field_2_tlp_flags, - value ); - - } - - /** - * When == 1, apply properties from the selected table look to the last row - * in the table - * - * @return the fLastRow field value. - */ - public boolean isFLastRow() - { - return fLastRow.isSet( field_2_tlp_flags ); - - } - -} // END OF CLASS - diff --git a/src/scratchpad/src/org/apache/poi/hwpf/sprm/CharacterSprmCompressor.java b/src/scratchpad/src/org/apache/poi/hwpf/sprm/CharacterSprmCompressor.java deleted file mode 100644 index 5e744bbe6..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/sprm/CharacterSprmCompressor.java +++ /dev/null @@ -1,293 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.sprm; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.hwpf.usermodel.CharacterProperties; -import org.apache.poi.util.Internal; -import org.apache.poi.util.LittleEndian; - -@Internal -public final class CharacterSprmCompressor -{ - public CharacterSprmCompressor() - { - } - public static byte[] compressCharacterProperty(CharacterProperties newCHP, CharacterProperties oldCHP) - { - List sprmList = new ArrayList(); - int size = 0; - - if (newCHP.isFRMarkDel() != oldCHP.isFRMarkDel()) - { - int value = 0; - if (newCHP.isFRMarkDel()) - { - value = 0x01; - } - size += SprmUtils.addSprm((short)0x0800, value, null, sprmList); - } - if (newCHP.isFRMark() != oldCHP.isFRMark()) - { - int value = 0; - if (newCHP.isFRMark()) - { - value = 0x01; - } - size += SprmUtils.addSprm((short)0x0801, value, null, sprmList); - } - if (newCHP.isFFldVanish() != oldCHP.isFFldVanish()) - { - int value = 0; - if (newCHP.isFFldVanish()) - { - value = 0x01; - } - size += SprmUtils.addSprm((short)0x0802, value, null, sprmList); - } - if (newCHP.isFSpec() != oldCHP.isFSpec() || newCHP.getFcPic() != oldCHP.getFcPic()) - { - size += SprmUtils.addSprm((short)0x6a03, newCHP.getFcPic(), null, sprmList); - } - if (newCHP.getIbstRMark() != oldCHP.getIbstRMark()) - { - size += SprmUtils.addSprm((short)0x4804, newCHP.getIbstRMark(), null, sprmList); - } - if (!newCHP.getDttmRMark().equals(oldCHP.getDttmRMark())) - { - byte[] buf = new byte[4]; - newCHP.getDttmRMark().serialize(buf, 0); - - size += SprmUtils.addSprm((short)0x6805, LittleEndian.getInt(buf), null, sprmList); - } - if (newCHP.isFData() != oldCHP.isFData()) - { - int value = 0; - if (newCHP.isFData()) - { - value = 0x01; - } - size += SprmUtils.addSprm((short)0x0806, value, null, sprmList); - } - if (newCHP.isFSpec() && newCHP.getFtcSym() != 0) - { - byte[] varParam = new byte[4]; - LittleEndian.putShort(varParam, 0, (short)newCHP.getFtcSym()); - LittleEndian.putShort(varParam, 2, (short)newCHP.getXchSym()); - - size += SprmUtils.addSprm((short)0x6a09, 0, varParam, sprmList); - } - if (newCHP.isFOle2() != newCHP.isFOle2()) - { - int value = 0; - if (newCHP.isFOle2()) - { - value = 0x01; - } - size += SprmUtils.addSprm((short)0x080a, value, null, sprmList); - } - if (newCHP.getIcoHighlight() != oldCHP.getIcoHighlight()) - { - size += SprmUtils.addSprm((short)0x2a0c, newCHP.getIcoHighlight(), null, sprmList); - } - if (newCHP.getFcObj() != oldCHP.getFcObj()) - { - size += SprmUtils.addSprm((short)0x680e, newCHP.getFcObj(), null, sprmList); - } - if (newCHP.getIstd() != oldCHP.getIstd()) - { - size += SprmUtils.addSprm((short)0x4a30, newCHP.getIstd(), null, sprmList); - } - if (newCHP.isFBold() != oldCHP.isFBold()) - { - int value = 0; - if (newCHP.isFBold()) - { - value = 0x01; - } - size += SprmUtils.addSprm((short)0x0835, value, null, sprmList); - } - if (newCHP.isFItalic() != oldCHP.isFItalic()) - { - int value = 0; - if (newCHP.isFItalic()) - { - value = 0x01; - } - size += SprmUtils.addSprm((short)0x0836, value, null, sprmList); - } - if (newCHP.isFStrike() != oldCHP.isFStrike()) - { - int value = 0; - if (newCHP.isFStrike()) - { - value = 0x01; - } - size += SprmUtils.addSprm((short)0x0837, value, null, sprmList); - } - if (newCHP.isFOutline() != oldCHP.isFOutline()) - { - int value = 0; - if (newCHP.isFOutline()) - { - value = 0x01; - } - size += SprmUtils.addSprm((short)0x0838, value, null, sprmList); - } - if (newCHP.isFShadow() != oldCHP.isFShadow()) - { - int value = 0; - if (newCHP.isFShadow()) - { - value = 0x01; - } - size += SprmUtils.addSprm((short)0x0839, value, null, sprmList); - } - if (newCHP.isFSmallCaps() != oldCHP.isFSmallCaps()) - { - int value = 0; - if (newCHP.isFSmallCaps()) - { - value = 0x01; - } - size += SprmUtils.addSprm((short)0x083a, value, null, sprmList); - } - if (newCHP.isFCaps() != oldCHP.isFCaps()) - { - int value = 0; - if (newCHP.isFCaps()) - { - value = 0x01; - } - size += SprmUtils.addSprm((short)0x083b, value, null, sprmList); - } - if (newCHP.isFVanish() != oldCHP.isFVanish()) - { - int value = 0; - if (newCHP.isFVanish()) - { - value = 0x01; - } - size += SprmUtils.addSprm((short)0x083c, value, null, sprmList); - } - if (newCHP.getKul() != oldCHP.getKul()) - { - size += SprmUtils.addSprm((short)0x2a3e, newCHP.getKul(), null, sprmList); - } - if (newCHP.getDxaSpace() != oldCHP.getDxaSpace()) - { - size += SprmUtils.addSprm((short)0x8840, newCHP.getDxaSpace(), null, sprmList); - } - if (newCHP.getIco() != oldCHP.getIco()) - { - size += SprmUtils.addSprm((short)0x2a42, newCHP.getIco(), null, sprmList); - } - if (newCHP.getHps() != oldCHP.getHps()) - { - size += SprmUtils.addSprm((short)0x4a43, newCHP.getHps(), null, sprmList); - } - if (newCHP.getHpsPos() != oldCHP.getHpsPos()) - { - size += SprmUtils.addSprm((short)0x4845, newCHP.getHpsPos(), null, sprmList); - } - if (newCHP.getHpsKern() != oldCHP.getHpsKern()) - { - size += SprmUtils.addSprm((short)0x484b, newCHP.getHpsKern(), null, sprmList); - } - if (newCHP.getHresi().equals( oldCHP.getHresi() )) - { - size += SprmUtils.addSprm((short)0x484e, newCHP.getHresi().getValue(), null, sprmList); - } - if (newCHP.getFtcAscii() != oldCHP.getFtcAscii()) - { - size += SprmUtils.addSprm((short)0x4a4f, newCHP.getFtcAscii(), null, sprmList); - } - if (newCHP.getFtcFE() != oldCHP.getFtcFE()) - { - size += SprmUtils.addSprm((short)0x4a50, newCHP.getFtcFE(), null, sprmList); - } - if (newCHP.getFtcOther() != oldCHP.getFtcOther()) - { - size += SprmUtils.addSprm((short)0x4a51, newCHP.getFtcOther(), null, sprmList); - } - - if (newCHP.isFDStrike() != oldCHP.isFDStrike()) - { - int value = 0; - if (newCHP.isFDStrike()) - { - value = 0x01; - } - size += SprmUtils.addSprm((short)0x2a53, value, null, sprmList); - } - if (newCHP.isFImprint() != oldCHP.isFImprint()) - { - int value = 0; - if (newCHP.isFImprint()) - { - value = 0x01; - } - size += SprmUtils.addSprm((short)0x0854, value, null, sprmList); - } - if (newCHP.isFSpec() != oldCHP.isFSpec()) - { - int value = 0; - if (newCHP.isFSpec()) - { - value = 0x01; - } - size += SprmUtils.addSprm((short)0x0855, value, null, sprmList); - } - if (newCHP.isFObj() != oldCHP.isFObj()) - { - int value = 0; - if (newCHP.isFObj()) - { - value = 0x01; - } - size += SprmUtils.addSprm((short)0x0856, value, null, sprmList); - } - if (newCHP.isFEmboss() != oldCHP.isFEmboss()) - { - int value = 0; - if (newCHP.isFEmboss()) - { - value = 0x01; - } - size += SprmUtils.addSprm((short)0x0858, value, null, sprmList); - } - if (newCHP.getSfxtText() != oldCHP.getSfxtText()) - { - size += SprmUtils.addSprm((short)0x2859, newCHP.getSfxtText(), null, sprmList); - } - if ( !newCHP.getCv().equals( oldCHP.getCv() ) ) - { - // don't add a sprm if we're looking at an ico = Auto - if ( !newCHP.getCv().isEmpty() ) - size += SprmUtils.addSprm( CharacterProperties.SPRM_CCV, newCHP - .getCv().getValue(), null, sprmList ); - } - - return SprmUtils.getGrpprl(sprmList, size); - } - - - -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/sprm/CharacterSprmUncompressor.java b/src/scratchpad/src/org/apache/poi/hwpf/sprm/CharacterSprmUncompressor.java deleted file mode 100644 index e382ffe09..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/sprm/CharacterSprmUncompressor.java +++ /dev/null @@ -1,759 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.sprm; - -import org.apache.poi.hwpf.usermodel.ShadingDescriptor80; - -import org.apache.poi.hwpf.model.Colorref; -import org.apache.poi.hwpf.model.Hyphenation; -import org.apache.poi.hwpf.model.StyleSheet; -import org.apache.poi.hwpf.usermodel.BorderCode; -import org.apache.poi.hwpf.usermodel.CharacterProperties; -import org.apache.poi.hwpf.usermodel.DateAndTime; -import org.apache.poi.hwpf.usermodel.ShadingDescriptor; -import org.apache.poi.util.Internal; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; - -@Internal -public final class CharacterSprmUncompressor extends SprmUncompressor -{ - private static final POILogger logger = POILogFactory - .getLogger( CharacterSprmUncompressor.class ); - - public CharacterSprmUncompressor() - { - } - - @Deprecated - public static CharacterProperties uncompressCHP( - CharacterProperties parent, byte[] grpprl, int offset ) - { - CharacterProperties newProperties = parent.clone(); - applySprms( parent, grpprl, offset, true, newProperties ); - return newProperties; - } - - public static CharacterProperties uncompressCHP( StyleSheet styleSheet, - CharacterProperties parStyle, byte[] grpprl, int offset ) - { - CharacterProperties newProperties; - if ( parStyle == null ) - { - parStyle = new CharacterProperties(); - newProperties = new CharacterProperties(); - } - else - { - newProperties = parStyle.clone(); - } - - /* - * not fully conform to specification, but the fastest way to make it - * work. Shall be rewritten if any errors would be found -- vlsergey - */ - Integer style = getIstd( grpprl, offset ); - if ( style != null ) - { - try - { - applySprms( parStyle, styleSheet.getCHPX( style ), 0, false, - newProperties ); - } - catch ( Exception exc ) - { - logger.log( POILogger.ERROR, "Unable to apply all style ", - style, " CHP SPRMs to CHP: ", exc, exc ); - } - } - - CharacterProperties styleProperties = newProperties; - newProperties = styleProperties.clone(); - - try - { - applySprms( styleProperties, grpprl, offset, true, newProperties ); - } - catch ( Exception exc ) - { - logger.log( POILogger.ERROR, - "Unable to process all direct CHP SPRMs: ", exc, exc ); - } - return newProperties; - } - - private static void applySprms( CharacterProperties parentProperties, - byte[] grpprl, int offset, boolean warnAboutNonChpSprms, - CharacterProperties targetProperties ) - { - SprmIterator sprmIt = new SprmIterator( grpprl, offset ); - - while ( sprmIt.hasNext() ) - { - SprmOperation sprm = sprmIt.next(); - - if ( sprm.getType() != 2 ) - { - if ( warnAboutNonChpSprms ) - { - logger.log( POILogger.WARN, - "Non-CHP SPRM returned by SprmIterator: " + sprm ); - } - continue; - } - - unCompressCHPOperation( parentProperties, targetProperties, sprm ); - } - } - - private static Integer getIstd( byte[] grpprl, int offset ) - { - Integer style = null; - try - { - SprmIterator sprmIt = new SprmIterator( grpprl, offset ); - while ( sprmIt.hasNext() ) - { - SprmOperation sprm = sprmIt.next(); - - if ( sprm.getType() == 2 && sprm.getOperation() == 0x30 ) - { - // sprmCIstd (0x4A30) - style = Integer.valueOf( sprm.getOperand() ); - } - } - } - catch ( Exception exc ) - { - logger.log( POILogger.ERROR, - "Unable to extract istd from direct CHP SPRM: ", exc, exc ); - } - return style; - } - - /** - * Used in decompression of a chpx. This performs an operation defined by - * a single sprm. - * - * @param oldCHP The base CharacterProperties. - * @param newCHP The current CharacterProperties. - * @param operand The operand defined by the sprm (See Word file format spec) - * @param param The parameter defined by the sprm (See Word file format spec) - * @param varParam The variable length parameter defined by the sprm. (See - * Word file format spec) - * @param grpprl The entire chpx that this operation is a part of. - * @param offset The offset in the grpprl of the next sprm - * @param styleSheet The StyleSheet for this document. - */ - static void unCompressCHPOperation (CharacterProperties oldCHP, - CharacterProperties newCHP, - SprmOperation sprm) - { - - switch (sprm.getOperation()) - { - case 0: - newCHP.setFRMarkDel (getFlag (sprm.getOperand())); - break; - case 0x1: - newCHP.setFRMark (getFlag (sprm.getOperand())); - break; - case 0x2: - newCHP.setFFldVanish (getFlag (sprm.getOperand())); - break; - case 0x3: - // sprmCPicLocation -- 0x6A03 - /* - * [MS-DOC] - * - * Page 104 of 622 - * - * A signed 32-bit integer that specifies either the position in the - * Data Stream of a picture or binary data or the name of an OLE - * object storage. - */ - newCHP.setFcPic( sprm.getOperand() ); - newCHP.setFSpec( true ); - break; - case 0x4: - newCHP.setIbstRMark ((short) sprm.getOperand()); - break; - case 0x5: - newCHP.setDttmRMark (new DateAndTime(sprm.getGrpprl(), sprm.getGrpprlOffset())); - break; - case 0x6: - newCHP.setFData (getFlag (sprm.getOperand())); - break; - case 0x7: - //don't care about this - break; - case 0x8: - //short chsDiff = (short)((param & 0xff0000) >>> 16); - int operand =sprm.getOperand(); - short chsDiff = (short) (operand & 0x0000ff); - newCHP.setFChsDiff (getFlag (chsDiff)); - newCHP.setChse ((short) (operand & 0xffff00)); - break; - case 0x9: - newCHP.setFSpec (true); - newCHP.setFtcSym (LittleEndian.getShort (sprm.getGrpprl(), sprm.getGrpprlOffset())); - newCHP.setXchSym (LittleEndian.getShort (sprm.getGrpprl(), sprm.getGrpprlOffset() + 2)); - break; - case 0xa: - newCHP.setFOle2 (getFlag (sprm.getOperand())); - break; - case 0xb: - - // Obsolete - break; - case 0xc: - newCHP.setIcoHighlight ((byte) sprm.getOperand()); - newCHP.setFHighlight (getFlag (sprm.getOperand())); - break; - case 0xd: - - // undocumented - break; - case 0xe: - newCHP.setFcObj (sprm.getOperand()); - break; - case 0xf: - - // undocumented - break; - case 0x10: - - // undocumented - break; - - // undocumented till 0x30 - - case 0x11: - // sprmCFWebHidden - break; - case 0x12: - break; - case 0x13: - break; - case 0x14: - break; - case 0x15: - // sprmCRsidProp - break; - case 0x16: - // sprmCRsidText - break; - case 0x17: - // sprmCRsidRMDel - break; - case 0x18: - // sprmCFSpecVanish - break; - case 0x19: - break; - case 0x1a: - // sprmCFMathPr - break; - case 0x1b: - break; - case 0x1c: - break; - case 0x1d: - break; - case 0x1e: - break; - case 0x1f: - break; - case 0x20: - break; - case 0x21: - break; - case 0x22: - break; - case 0x23: - break; - case 0x24: - break; - case 0x25: - break; - case 0x26: - break; - case 0x27: - break; - case 0x28: - break; - case 0x29: - break; - case 0x2a: - break; - case 0x2b: - break; - case 0x2c: - break; - case 0x2d: - break; - case 0x2e: - break; - case 0x2f: - break; - case 0x30: - newCHP.setIstd( sprm.getOperand() ); - // 0x30 is supported by uncompressCHP(...) - break; - case 0x31: - - //permutation vector for fast saves, who cares! - break; - case 0x32: - newCHP.setFBold (false); - newCHP.setFItalic (false); - newCHP.setFOutline (false); - newCHP.setFStrike (false); - newCHP.setFShadow (false); - newCHP.setFSmallCaps (false); - newCHP.setFCaps (false); - newCHP.setFVanish (false); - newCHP.setKul ((byte) 0); - newCHP.setIco ((byte) 0); - break; - case 0x33: - // preserve the fSpec setting from the original CHP - boolean fSpec = newCHP.isFSpec(); - newCHP = oldCHP.clone(); - newCHP.setFSpec( fSpec ); - return; - case 0x34: - // sprmCKcd - break; - case 0x35: - newCHP.setFBold (getCHPFlag ((byte) sprm.getOperand(), oldCHP.isFBold ())); - break; - case 0x36: - newCHP.setFItalic (getCHPFlag ((byte) sprm.getOperand(), oldCHP.isFItalic ())); - break; - case 0x37: - newCHP.setFStrike (getCHPFlag ((byte) sprm.getOperand(), oldCHP.isFStrike ())); - break; - case 0x38: - newCHP.setFOutline (getCHPFlag ((byte) sprm.getOperand(), oldCHP.isFOutline ())); - break; - case 0x39: - newCHP.setFShadow (getCHPFlag ((byte) sprm.getOperand(), oldCHP.isFShadow ())); - break; - case 0x3a: - newCHP.setFSmallCaps (getCHPFlag ((byte) sprm.getOperand(), oldCHP.isFSmallCaps ())); - break; - case 0x3b: - newCHP.setFCaps (getCHPFlag ((byte) sprm.getOperand(), oldCHP.isFCaps ())); - break; - case 0x3c: - newCHP.setFVanish (getCHPFlag ((byte) sprm.getOperand(), oldCHP.isFVanish ())); - break; - case 0x3d: - newCHP.setFtcAscii ((short) sprm.getOperand()); - break; - case 0x3e: - newCHP.setKul ((byte) sprm.getOperand()); - break; - case 0x3f: - operand = sprm.getOperand(); - int hps = operand & 0xff; - if (hps != 0) - { - newCHP.setHps (hps); - } - - //byte cInc = (byte)(((byte)(param & 0xfe00) >>> 4) >> 1); - byte cInc = (byte) ((operand & 0xff00) >>> 8); - cInc >>>= 1; - if (cInc != 0) - { - newCHP.setHps (Math.max (newCHP.getHps () + (cInc * 2), 2)); - } - - //byte hpsPos = (byte)((param & 0xff0000) >>> 8); - byte hpsPos = (byte) ((operand & 0xff0000) >>> 16); - if (hpsPos != (byte)0x80) - { - newCHP.setHpsPos (hpsPos); - } - boolean fAdjust = (operand & 0x0100) > 0; - if (fAdjust && (hpsPos & 0xFF) != 128 && hpsPos != 0 && oldCHP.getHpsPos () == 0) - { - newCHP.setHps (Math.max (newCHP.getHps () + ( -2), 2)); - } - if (fAdjust && hpsPos == 0 && oldCHP.getHpsPos () != 0) - { - newCHP.setHps (Math.max (newCHP.getHps () + 2, 2)); - } - break; - case 0x40: - newCHP.setDxaSpace (sprm.getOperand()); - break; - case 0x41: - newCHP.setLidDefault ((short) sprm.getOperand()); - break; - case 0x42: - newCHP.setIco ((byte) sprm.getOperand()); - break; - case 0x43: - newCHP.setHps (sprm.getOperand()); - break; - case 0x44: - byte hpsLvl = (byte) sprm.getOperand(); - newCHP.setHps (Math.max (newCHP.getHps () + (hpsLvl * 2), 2)); - break; - case 0x45: - newCHP.setHpsPos ((short) sprm.getOperand()); - break; - case 0x46: - if (sprm.getOperand() != 0) - { - if (oldCHP.getHpsPos () == 0) - { - newCHP.setHps (Math.max (newCHP.getHps () + ( -2), 2)); - } - } - else - { - if (oldCHP.getHpsPos () != 0) - { - newCHP.setHps (Math.max (newCHP.getHps () + 2, 2)); - } - } - break; - case 0x47: - /*CharacterProperties genCHP = new CharacterProperties (); - genCHP.setFtcAscii (4); - genCHP = (CharacterProperties) unCompressProperty (varParam, genCHP, - styleSheet); - CharacterProperties styleCHP = styleSheet.getStyleDescription (oldCHP. - getBaseIstd ()).getCHP (); - if (genCHP.isFBold () == newCHP.isFBold ()) - { - newCHP.setFBold (styleCHP.isFBold ()); - } - if (genCHP.isFItalic () == newCHP.isFItalic ()) - { - newCHP.setFItalic (styleCHP.isFItalic ()); - } - if (genCHP.isFSmallCaps () == newCHP.isFSmallCaps ()) - { - newCHP.setFSmallCaps (styleCHP.isFSmallCaps ()); - } - if (genCHP.isFVanish () == newCHP.isFVanish ()) - { - newCHP.setFVanish (styleCHP.isFVanish ()); - } - if (genCHP.isFStrike () == newCHP.isFStrike ()) - { - newCHP.setFStrike (styleCHP.isFStrike ()); - } - if (genCHP.isFCaps () == newCHP.isFCaps ()) - { - newCHP.setFCaps (styleCHP.isFCaps ()); - } - if (genCHP.getFtcAscii () == newCHP.getFtcAscii ()) - { - newCHP.setFtcAscii (styleCHP.getFtcAscii ()); - } - if (genCHP.getFtcFE () == newCHP.getFtcFE ()) - { - newCHP.setFtcFE (styleCHP.getFtcFE ()); - } - if (genCHP.getFtcOther () == newCHP.getFtcOther ()) - { - newCHP.setFtcOther (styleCHP.getFtcOther ()); - } - if (genCHP.getHps () == newCHP.getHps ()) - { - newCHP.setHps (styleCHP.getHps ()); - } - if (genCHP.getHpsPos () == newCHP.getHpsPos ()) - { - newCHP.setHpsPos (styleCHP.getHpsPos ()); - } - if (genCHP.getKul () == newCHP.getKul ()) - { - newCHP.setKul (styleCHP.getKul ()); - } - if (genCHP.getDxaSpace () == newCHP.getDxaSpace ()) - { - newCHP.setDxaSpace (styleCHP.getDxaSpace ()); - } - if (genCHP.getIco () == newCHP.getIco ()) - { - newCHP.setIco (styleCHP.getIco ()); - } - if (genCHP.getLidDefault () == newCHP.getLidDefault ()) - { - newCHP.setLidDefault (styleCHP.getLidDefault ()); - } - if (genCHP.getLidFE () == newCHP.getLidFE ()) - { - newCHP.setLidFE (styleCHP.getLidFE ()); - }*/ - break; - case 0x48: - newCHP.setIss ((byte) sprm.getOperand()); - break; - case 0x49: - newCHP.setHps (LittleEndian.getShort (sprm.getGrpprl(), sprm.getGrpprlOffset())); - break; - case 0x4a: - int increment = LittleEndian.getShort (sprm.getGrpprl(), sprm.getGrpprlOffset()); - newCHP.setHps (Math.max (newCHP.getHps () + increment, 8)); - break; - case 0x4b: - newCHP.setHpsKern (sprm.getOperand()); - break; - // Microsoft Office Word 97-2007 Binary File Format (.doc) Specification - // Page 59 of 210 - case 0x4c: - // sprmCMajority50 -- 0xCA4C - // unCompressCHPOperation (oldCHP, newCHP, 0x47, param, varParam, - // styleSheet, opSize); - break; - case 0x4d: - // sprmCHpsMul -- 0x4A4D - float percentage = sprm.getOperand() / 100.0f; - int add = (int) ( percentage * newCHP.getHps() ); - newCHP.setHps( newCHP.getHps() + add ); - break; - case 0x4e: - // sprmCHresi -- 0x484e - Hyphenation hyphenation = new Hyphenation( - (short) sprm.getOperand() ); - newCHP.setHresi( hyphenation ); - break; - case 0x4f: - newCHP.setFtcAscii ((short) sprm.getOperand()); - break; - case 0x50: - newCHP.setFtcFE ((short) sprm.getOperand()); - break; - case 0x51: - newCHP.setFtcOther ((short) sprm.getOperand()); - break; - case 0x52: - // sprmCCharScale - break; - case 0x53: - newCHP.setFDStrike (getFlag (sprm.getOperand())); - break; - case 0x54: - newCHP.setFImprint (getFlag (sprm.getOperand())); - break; - case 0x55: - // sprmCFSpec -- 0x0855 - newCHP.setFSpec( getFlag( sprm.getOperand() ) ); - break; - case 0x56: - newCHP.setFObj (getFlag (sprm.getOperand())); - break; - case 0x57: - // sprmCPropRMark -- 0xCA57 - /* - * Microsoft Office Word 97-2007 Binary File Format (.doc) - * Specification - * - * Page 78 of 210 - * - * sprmCPropRMark (opcode 0xCA57) is interpreted by moving the first - * parameter byte to chp.fPropRMark, the next two bytes to - * chp.ibstPropRMark, and the remaining four bytes to - * chp.dttmPropRMark. - */ - byte[] buf = sprm.getGrpprl(); - int offset = sprm.getGrpprlOffset(); - newCHP.setFPropRMark( buf[offset] != 0 ); - newCHP.setIbstPropRMark( LittleEndian.getShort( buf, offset + 1 ) ); - newCHP.setDttmPropRMark( new DateAndTime( buf, offset + 3 ) ); - break; - case 0x58: - newCHP.setFEmboss (getFlag (sprm.getOperand())); - break; - case 0x59: - newCHP.setSfxtText ((byte) sprm.getOperand()); - break; - case 0x5a: - // sprmCFBiDi - break; - case 0x5b: - break; - case 0x5c: - // sprmCFBoldBi - break; - case 0x5d: - // sprmCFItalicBi - break; - case 0x5e: - // sprmCFtcBi - break; - case 0x5f: - // sprmCLidBi - break; - case 0x60: - // sprmCIcoBi - break; - case 0x61: - // sprmCHpsBi - break; - case 0x62: - // sprmCDispFldRMark -- 0xCA62 - /* - * Microsoft Office Word 97-2007 Binary File Format (.doc) - * Specification - * - * Page 78 of 210 - * - * sprmCDispFldRMark (opcode 0xCA62) is interpreted by moving the - * first parameter byte to chp.fDispFldRMark, the next two bytes to - * chp.ibstDispFldRMark, the next four bytes to - * chp.dttmDispFldRMark, and the remaining 32 bytes to - * chp.xstDispFldRMark. - */ - byte[] xstDispFldRMark = new byte[32]; - buf = sprm.getGrpprl(); - offset = sprm.getGrpprlOffset(); - newCHP.setFDispFldRMark( 0 != buf[offset] ); - newCHP.setIbstDispFldRMark( LittleEndian.getShort( buf, offset + 1 ) ); - newCHP.setDttmDispFldRMark( new DateAndTime( buf, offset + 3 ) ); - System.arraycopy( buf, offset + 7, xstDispFldRMark, 0, 32 ); - newCHP.setXstDispFldRMark( xstDispFldRMark ); - break; - case 0x63: - newCHP.setIbstRMarkDel ((short) sprm.getOperand()); - break; - case 0x64: - newCHP.setDttmRMarkDel (new DateAndTime(sprm.getGrpprl(), sprm.getGrpprlOffset())); - break; - case 0x65: - newCHP.setBrc (new BorderCode(sprm.getGrpprl(), sprm.getGrpprlOffset())); - break; - case 0x66: - // sprmCShd80 - /* - * "A Shd80 structure that specifies the background shading for the text. By default, text is not shaded." - * - * Word (.doc) Binary File Format. Copyright (c) 2011 Microsoft - * Corporation. Release: Tuesday, March 15, 2011 - */ - ShadingDescriptor80 oldDescriptor = new ShadingDescriptor80( - sprm.getGrpprl(), sprm.getGrpprlOffset() ); - ShadingDescriptor newDescriptor = oldDescriptor - .toShadingDescriptor(); - newCHP.setShd( newDescriptor ); - break; - case 0x67: - // Obsolete - break; - case 0x68: - // sprmCFUsePgsuSettings - break; - case 0x69: - break; - case 0x6a: - break; - case 0x6b: - break; - case 0x6c: - break; - case 0x6d: - newCHP.setLidDefault ((short) sprm.getOperand()); - break; - case 0x6e: - newCHP.setLidFE ((short) sprm.getOperand()); - break; - case 0x6f: - newCHP.setIdctHint ((byte) sprm.getOperand()); - break; - case 0x70: - // sprmCCv -- 0x6870 - newCHP.setCv( new Colorref( sprm.getOperand() ) ); - break; - case 0x71: - // sprmCShd - break; - case 0x72: - // sprmCBrc - break; - case 0x73: - // sprmCRgLid0 - break; - case 0x74: - // sprmCRgLid1 - break; - case 0x75: - // sprmCFNoProof -- 0x875 - /* - * "A ToggleOperand value that specifies whether the text is excluded from the proofing analysis. By default, text is not excluded from the proofing analysis." - * - * Word (.doc) Binary File Format. Copyright (c) 2012 Microsoft - * Corporation. Released: October 8, 2012 - */ - newCHP.setFNoProof(getCHPFlag((byte) sprm.getOperand(), - oldCHP.isFNoProof())); - break; - default: - logger.log( POILogger.DEBUG, "Unknown CHP sprm ignored: " + sprm ); - break; - } - } - - private static boolean getCHPFlag (byte x, boolean oldVal) - { - /* - switch(x) - { - case 0: - return false; - case 1: - return true; - case (byte)0x80: - return oldVal; - case (byte)0x81: - return !oldVal; - default: - return false; - } - */ - if (x == 0) - { - return false; - } - else if (x == 1) - { - return true; - } - else if ((x & 0x81) == 0x80) - { - return oldVal; - } - else if ((x & 0x81) == 0x81) - { - return!oldVal; - } - else - { - return false; - } - } - -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/sprm/ParagraphSprmCompressor.java b/src/scratchpad/src/org/apache/poi/hwpf/sprm/ParagraphSprmCompressor.java deleted file mode 100644 index 2f60b536f..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/sprm/ParagraphSprmCompressor.java +++ /dev/null @@ -1,398 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.sprm; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.apache.poi.hwpf.usermodel.ParagraphProperties; -import org.apache.poi.util.Internal; -import org.apache.poi.util.LittleEndian; - -@Internal -public final class ParagraphSprmCompressor -{ - public ParagraphSprmCompressor() - { - } - - public static byte[] compressParagraphProperty(ParagraphProperties newPAP, - ParagraphProperties oldPAP) - { - // page numbers links to Word97-2007BinaryFileFormat(doc)Specification.pdf, accessible from microsoft.com - - List sprmList = new ArrayList(); - int size = 0; - - // Page 50 of public specification begins - if (newPAP.getIstd() != oldPAP.getIstd()) - { - // sprmPIstd - size += SprmUtils.addSprm((short)0x4600, newPAP.getIstd(), null, sprmList); - } - if (newPAP.getJc() != oldPAP.getJc()) - { - // sprmPJc80 - size += SprmUtils.addSprm((short)0x2403, newPAP.getJc(), null, sprmList); - } - if (newPAP.getFSideBySide() != oldPAP.getFSideBySide()) - { - // sprmPFSideBySide - size += SprmUtils.addSprm((short)0x2404, newPAP.getFSideBySide(), sprmList); - } - if (newPAP.getFKeep() != oldPAP.getFKeep()) - { - size += SprmUtils.addSprm((short)0x2405, newPAP.getFKeep(), sprmList); - } - if (newPAP.getFKeepFollow() != oldPAP.getFKeepFollow()) - { - size += SprmUtils.addSprm((short)0x2406, newPAP.getFKeepFollow(), sprmList); - } - if (newPAP.getFPageBreakBefore() != oldPAP.getFPageBreakBefore()) - { - size += SprmUtils.addSprm((short)0x2407, newPAP.getFPageBreakBefore(), sprmList); - } - if (newPAP.getBrcl() != oldPAP.getBrcl()) - { - size += SprmUtils.addSprm((short)0x2408, newPAP.getBrcl(), null, sprmList); - } - if (newPAP.getBrcp() != oldPAP.getBrcp()) - { - size += SprmUtils.addSprm((short)0x2409, newPAP.getBrcp(), null, sprmList); - } - if (newPAP.getIlvl() != oldPAP.getIlvl()) - { - size += SprmUtils.addSprm((short)0x260A, newPAP.getIlvl(), null, sprmList); - } - if (newPAP.getIlfo() != oldPAP.getIlfo()) - { - size += SprmUtils.addSprm((short)0x460b, newPAP.getIlfo(), null, sprmList); - } - if (newPAP.getFNoLnn() != oldPAP.getFNoLnn()) - { - size += SprmUtils.addSprm((short)0x240C, newPAP.getFNoLnn(), sprmList); - } - if (newPAP.getItbdMac() != oldPAP.getItbdMac() || - !Arrays.equals(newPAP.getRgdxaTab(), oldPAP.getRgdxaTab()) || - !Arrays.equals(newPAP.getRgtbd(), oldPAP.getRgtbd())) - { - /** @todo revisit this */ -// byte[] oldTabArray = oldPAP.getRgdxaTab(); -// byte[] newTabArray = newPAP.getRgdxaTab(); -// byte[] newTabDescriptors = newPAP.getRgtbd(); -// byte[] varParam = new byte[2 + oldTabArray.length + newTabArray.length + -// newTabDescriptors.length]; -// varParam[0] = (byte)(oldTabArray.length/2); -// int offset = 1; -// System.arraycopy(oldTabArray, 0, varParam, offset, oldTabArray.length); -// offset += oldTabArray.length; -// varParam[offset] = (byte)(newTabArray.length/2); -// offset += 1; -// System.arraycopy(newTabArray, 0, varParam, offset, newTabArray.length); -// offset += newTabArray.length; -// System.arraycopy(newTabDescriptors, 0, varParam, offset, newTabDescriptors.length); - // -// size += SprmUtils.addSprm((short)0xC60D, 0, varParam, sprmList); - } - if (newPAP.getDxaLeft() != oldPAP.getDxaLeft()) - { - // sprmPDxaLeft80 - size += SprmUtils.addSprm((short)0x840F, newPAP.getDxaLeft(), null, sprmList); - } - - // Page 51 of public specification begins - if (newPAP.getDxaLeft1() != oldPAP.getDxaLeft1()) - { - // sprmPDxaLeft180 - size += SprmUtils.addSprm((short)0x8411, newPAP.getDxaLeft1(), null, sprmList); - } - if (newPAP.getDxaRight() != oldPAP.getDxaRight()) - { - // sprmPDxaRight80 - size += SprmUtils.addSprm((short)0x840E, newPAP.getDxaRight(), null, sprmList); - } - if (newPAP.getDxcLeft() != oldPAP.getDxcLeft()) - { - // sprmPDxcLeft - size += SprmUtils.addSprm((short)0x4456, newPAP.getDxcLeft(), null, sprmList); - } - if (newPAP.getDxcLeft1() != oldPAP.getDxcLeft1()) - { - // sprmPDxcLeft1 - size += SprmUtils.addSprm((short)0x4457, newPAP.getDxcLeft1(), null, sprmList); - } - if (newPAP.getDxcRight() != oldPAP.getDxcRight()) - { - // sprmPDxcRight - size += SprmUtils.addSprm((short)0x4455, newPAP.getDxcRight(), null, sprmList); - } - if (!newPAP.getLspd().equals(oldPAP.getLspd())) - { - // sprmPDyaLine - byte[] buf = new byte[4]; - newPAP.getLspd().serialize(buf, 0); - - size += SprmUtils.addSprm((short)0x6412, LittleEndian.getInt(buf), null, sprmList); - } - if (newPAP.getDyaBefore() != oldPAP.getDyaBefore()) - { - // sprmPDyaBefore - size += SprmUtils.addSprm((short)0xA413, newPAP.getDyaBefore(), null, sprmList); - } - if (newPAP.getDyaAfter() != oldPAP.getDyaAfter()) - { - // sprmPDyaAfter - size += SprmUtils.addSprm((short)0xA414, newPAP.getDyaAfter(), null, sprmList); - } - if (newPAP.getFDyaBeforeAuto() != oldPAP.getFDyaBeforeAuto()) - { - // sprmPFDyaBeforeAuto - size += SprmUtils.addSprm((short)0x245B, newPAP.getFDyaBeforeAuto(), sprmList); - } - if (newPAP.getFDyaAfterAuto() != oldPAP.getFDyaAfterAuto()) - { - // sprmPFDyaAfterAuto - size += SprmUtils.addSprm((short)0x245C, newPAP.getFDyaAfterAuto(), sprmList); - } - if (newPAP.getFInTable() != oldPAP.getFInTable()) - { - // sprmPFInTable - size += SprmUtils.addSprm((short)0x2416, newPAP.getFInTable(), sprmList); - } - if (newPAP.getFTtp() != oldPAP.getFTtp()) - { - // sprmPFTtp - size += SprmUtils.addSprm((short)0x2417, newPAP.getFTtp(), sprmList); - } - if (newPAP.getDxaAbs() != oldPAP.getDxaAbs()) - { - // sprmPDxaAbs - size += SprmUtils.addSprm((short)0x8418, newPAP.getDxaAbs(), null, sprmList); - } - if (newPAP.getDyaAbs() != oldPAP.getDyaAbs()) - { - // sprmPDyaAbs - size += SprmUtils.addSprm((short)0x8419, newPAP.getDyaAbs(), null, sprmList); - } - if (newPAP.getDxaWidth() != oldPAP.getDxaWidth()) - { - // sprmPDxaWidth - size += SprmUtils.addSprm((short)0x841A, newPAP.getDxaWidth(), null, sprmList); - } - - // Page 52 of public specification begins - if (newPAP.getWr() != oldPAP.getWr()) - { - size += SprmUtils.addSprm((short)0x2423, newPAP.getWr(), null, sprmList); - } - - if (newPAP.getBrcBar().equals(oldPAP.getBrcBar())) - { - // XXX: sprm code 0x6428 is sprmPBrcBetween80, but accessed property linked to sprmPBrcBar80 (0x6629) - int brc = newPAP.getBrcBar().toInt(); - size += SprmUtils.addSprm((short)0x6428, brc, null, sprmList); - } - if (!newPAP.getBrcBottom().equals(oldPAP.getBrcBottom())) - { - // sprmPBrcBottom80 - int brc = newPAP.getBrcBottom().toInt(); - size += SprmUtils.addSprm((short)0x6426, brc, null, sprmList); - } - if (!newPAP.getBrcLeft().equals(oldPAP.getBrcLeft())) - { - // sprmPBrcLeft80 - int brc = newPAP.getBrcLeft().toInt(); - size += SprmUtils.addSprm((short)0x6425, brc, null, sprmList); - } - - // Page 53 of public specification begins - if (!newPAP.getBrcRight().equals(oldPAP.getBrcRight())) - { - // sprmPBrcRight80 - int brc = newPAP.getBrcRight().toInt(); - size += SprmUtils.addSprm((short)0x6427, brc, null, sprmList); - } - if (!newPAP.getBrcTop().equals(oldPAP.getBrcTop())) - { - // sprmPBrcTop80 - int brc = newPAP.getBrcTop().toInt(); - size += SprmUtils.addSprm((short)0x6424, brc, null, sprmList); - } - if (newPAP.getFNoAutoHyph() != oldPAP.getFNoAutoHyph()) - { - size += SprmUtils.addSprm((short)0x242A, newPAP.getFNoAutoHyph(), sprmList); - } - if (newPAP.getDyaHeight() != oldPAP.getDyaHeight() || - newPAP.getFMinHeight() != oldPAP.getFMinHeight()) - { - // sprmPWHeightAbs - short val = (short)newPAP.getDyaHeight(); - if (newPAP.getFMinHeight()) - { - val |= 0x8000; - } - size += SprmUtils.addSprm((short)0x442B, val, null, sprmList); - } - if (newPAP.getDcs() != null && !newPAP.getDcs().equals(oldPAP.getDcs())) - { - // sprmPDcs - size += SprmUtils.addSprm((short)0x442C, newPAP.getDcs().toShort(), null, sprmList); - } - if (newPAP.getDyaFromText() != oldPAP.getDyaFromText()) - { - // sprmPDyaFromText - size += SprmUtils.addSprm((short)0x842E, newPAP.getDyaFromText(), null, sprmList); - } - if (newPAP.getDxaFromText() != oldPAP.getDxaFromText()) - { - // sprmPDxaFromText - size += SprmUtils.addSprm((short)0x842F, newPAP.getDxaFromText(), null, sprmList); - } - if (newPAP.getFLocked() != oldPAP.getFLocked()) - { - // sprmPFLocked - size += SprmUtils.addSprm((short)0x2430, newPAP.getFLocked(), sprmList); - } - if (newPAP.getFWidowControl() != oldPAP.getFWidowControl()) - { - // sprmPFWidowControl - size += SprmUtils.addSprm((short)0x2431, newPAP.getFWidowControl(), sprmList); - } - if (newPAP.getFKinsoku() != oldPAP.getFKinsoku()) - { - size += SprmUtils.addSprm((short)0x2433, newPAP.getDyaBefore(), null, sprmList); - } - if (newPAP.getFWordWrap() != oldPAP.getFWordWrap()) - { - size += SprmUtils.addSprm((short)0x2434, newPAP.getFWordWrap(), sprmList); - } - if (newPAP.getFOverflowPunct() != oldPAP.getFOverflowPunct()) - { - size += SprmUtils.addSprm((short)0x2435, newPAP.getFOverflowPunct(), sprmList); - } - if (newPAP.getFTopLinePunct() != oldPAP.getFTopLinePunct()) - { - size += SprmUtils.addSprm((short)0x2436, newPAP.getFTopLinePunct(), sprmList); - } - if (newPAP.getFAutoSpaceDE() != oldPAP.getFAutoSpaceDE()) - { - size += SprmUtils.addSprm((short)0x2437, newPAP.getFAutoSpaceDE(), sprmList); - } - if (newPAP.getFAutoSpaceDN() != oldPAP.getFAutoSpaceDN()) - { - size += SprmUtils.addSprm((short)0x2438, newPAP.getFAutoSpaceDN(), sprmList); - } - if (newPAP.getWAlignFont() != oldPAP.getWAlignFont()) - { - size += SprmUtils.addSprm((short)0x4439, newPAP.getWAlignFont(), null, sprmList); - } - - // Page 54 of public specification begins - if (newPAP.isFBackward() != oldPAP.isFBackward() || - newPAP.isFVertical() != oldPAP.isFVertical() || - newPAP.isFRotateFont() != oldPAP.isFRotateFont()) - { - int val = 0; - if (newPAP.isFBackward()) - { - val |= 0x2; - } - if (newPAP.isFVertical()) - { - val |= 0x1; - } - if (newPAP.isFRotateFont()) - { - val |= 0x4; - } - size += SprmUtils.addSprm((short)0x443A, val, null, sprmList); - } - if (!Arrays.equals(newPAP.getAnld(), oldPAP.getAnld())) - { - // sprmPAnld80 - size += SprmUtils.addSprm((short)0xC63E, 0, newPAP.getAnld(), sprmList); - } - if (newPAP.getFPropRMark() != oldPAP.getFPropRMark() || - newPAP.getIbstPropRMark() != oldPAP.getIbstPropRMark() || - !newPAP.getDttmPropRMark().equals(oldPAP.getDttmPropRMark())) - { - // sprmPPropRMark - byte[] buf = new byte[7]; - buf[0] = (byte) ( newPAP.getFPropRMark() ? 1 : 0 ); - LittleEndian.putShort(buf, 1, (short)newPAP.getIbstPropRMark()); - newPAP.getDttmPropRMark().serialize(buf, 3); - size += SprmUtils.addSprm((short)0xC63F, 0, buf, sprmList); - } - if (newPAP.getLvl() != oldPAP.getLvl()) - { - // sprmPOutLvl - size += SprmUtils.addSprm((short)0x2640, newPAP.getLvl(), null, sprmList); - } - if (newPAP.getFBiDi() != oldPAP.getFBiDi()) - { - // sprmPFBiDi - size += SprmUtils.addSprm((short)0x2441, newPAP.getFBiDi(), sprmList); - } - if (newPAP.getFNumRMIns() != oldPAP.getFNumRMIns()) - { - // sprmPFNumRMIns - size += SprmUtils.addSprm((short)0x2443, newPAP.getFNumRMIns(), sprmList); - } - if (!Arrays.equals(newPAP.getNumrm(), oldPAP.getNumrm())) - { - // sprmPNumRM - size += SprmUtils.addSprm((short)0xC645, 0, newPAP.getNumrm(), sprmList); - } - if (newPAP.getFInnerTableCell() != oldPAP.getFInnerTableCell()) - { - // sprmPFInnerTableCell - size += SprmUtils.addSprm((short)0x244b, newPAP.getFInnerTableCell(), sprmList); - } - if (newPAP.getFTtpEmbedded() != oldPAP.getFTtpEmbedded()) - { - // sprmPFInnerTtp - size += SprmUtils.addSprm((short)0x244c, newPAP.getFTtpEmbedded(), sprmList); - } - - if (newPAP.getShd() != null && !newPAP.getShd().equals(oldPAP.getShd())) - { - // size += SprmUtils.addSprm((short)0x442D, newPAP.getShd().toShort(), null, sprmList); - // sprmPShd -- 0xc64d - size += SprmUtils.addSprm( (short) 0xc64d, 0, newPAP.getShd().serialize(), sprmList ); - } - - // Page 55 of public specification begins - if (newPAP.getItap() != oldPAP.getItap()) - { - // sprmPItap - size += SprmUtils.addSprm((short)0x6649, newPAP.getItap(), null, sprmList); - } - - if ( newPAP.getRsid() != oldPAP.getRsid() ) - { - // sprmPRsid - byte[] value = new byte[4]; - LittleEndian.putUInt( value, 0, newPAP.getRsid() ); - size += SprmUtils.addSprm( (short) 0x6467, 0, value, sprmList ); - } - - return SprmUtils.getGrpprl(sprmList, size); - - } -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/sprm/ParagraphSprmUncompressor.java b/src/scratchpad/src/org/apache/poi/hwpf/sprm/ParagraphSprmUncompressor.java deleted file mode 100644 index 6634aa4d0..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/sprm/ParagraphSprmUncompressor.java +++ /dev/null @@ -1,535 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.sprm; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.poi.hwpf.model.TabDescriptor; -import org.apache.poi.hwpf.usermodel.BorderCode; -import org.apache.poi.hwpf.usermodel.DateAndTime; -import org.apache.poi.hwpf.usermodel.DropCapSpecifier; -import org.apache.poi.hwpf.usermodel.LineSpacingDescriptor; -import org.apache.poi.hwpf.usermodel.ParagraphProperties; -import org.apache.poi.hwpf.usermodel.ShadingDescriptor; -import org.apache.poi.hwpf.usermodel.ShadingDescriptor80; -import org.apache.poi.util.Internal; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; - -@Internal -public final class ParagraphSprmUncompressor - extends SprmUncompressor -{ - private static final POILogger logger = POILogFactory - .getLogger( ParagraphSprmUncompressor.class ); - - public ParagraphSprmUncompressor() - { - } - - public static ParagraphProperties uncompressPAP(ParagraphProperties parent, - byte[] grpprl, - int offset) - { - ParagraphProperties newProperties = null; - try - { - newProperties = (ParagraphProperties) parent.clone(); - } - catch (CloneNotSupportedException cnse) - { - throw new RuntimeException("There is no way this exception should happen!!"); - } - SprmIterator sprmIt = new SprmIterator(grpprl, offset); - - while (sprmIt.hasNext()) - { - SprmOperation sprm = sprmIt.next(); - - // PAPXs can contain table sprms if the paragraph marks the end of a - // table row - if (sprm.getType() == SprmOperation.TYPE_PAP) - { - try - { - unCompressPAPOperation( newProperties, sprm ); - } - catch ( Exception exc ) - { - logger.log( - POILogger.ERROR, - "Unable to apply SPRM operation '" - + sprm.getOperation() + "': ", exc ); - } - } - } - - return newProperties; - } - - /** - * Performs an operation on a ParagraphProperties object. Used to uncompress - * from a papx. - * - * @param newPAP The ParagraphProperties object to perform the operation on. - * @param operand The operand that defines the operation. - * @param param The operation's parameter. - * @param varParam The operation's variable length parameter. - * @param grpprl The original papx. - * @param offset The current offset in the papx. - * @param spra A part of the sprm that defined this operation. - */ - static void unCompressPAPOperation (ParagraphProperties newPAP, SprmOperation sprm) - { - switch (sprm.getOperation()) - { - case 0: - newPAP.setIstd (sprm.getOperand()); - break; - case 0x1: - - // Used only for piece table grpprl's not for PAPX -// int istdFirst = LittleEndian.getShort (varParam, 2); -// int istdLast = LittleEndian.getShort (varParam, 4); -// if ((newPAP.getIstd () > istdFirst) || (newPAP.getIstd () <= istdLast)) -// { -// permuteIstd (newPAP, varParam, opSize); -// } - break; - case 0x2: - if (newPAP.getIstd () <= 9 || newPAP.getIstd () >= 1) - { - byte paramTmp = (byte) sprm.getOperand(); - newPAP.setIstd (newPAP.getIstd () + paramTmp); - newPAP.setLvl ((byte) (newPAP.getLvl () + paramTmp)); - - if (((paramTmp >> 7) & 0x01) == 1) - { - newPAP.setIstd (Math.max (newPAP.getIstd (), 1)); - } - else - { - newPAP.setIstd (Math.min (newPAP.getIstd (), 9)); - } - - } - break; - case 0x3: - // Physical justification of the paragraph - newPAP.setJc ((byte) sprm.getOperand()); - break; - case 0x4: - newPAP.setFSideBySide (sprm.getOperand() != 0); - break; - case 0x5: - newPAP.setFKeep (sprm.getOperand() != 0); - break; - case 0x6: - newPAP.setFKeepFollow (sprm.getOperand() != 0); - break; - case 0x7: - newPAP.setFPageBreakBefore (sprm.getOperand() != 0); - break; - case 0x8: - newPAP.setBrcl ((byte) sprm.getOperand()); - break; - case 0x9: - newPAP.setBrcp ((byte) sprm.getOperand()); - break; - case 0xa: - newPAP.setIlvl ((byte) sprm.getOperand()); - break; - case 0xb: - /* sprmPIlfo -- 0x460B */ - newPAP.setIlfo( sprm.getOperandShortSigned() ); - break; - case 0xc: - newPAP.setFNoLnn (sprm.getOperand() != 0); - break; - case 0xd: - /**handle tabs . variable parameter. seperate processing needed*/ - handleTabs(newPAP, sprm); - break; - case 0xe: - newPAP.setDxaRight (sprm.getOperand()); - break; - case 0xf: - newPAP.setDxaLeft (sprm.getOperand()); - break; - case 0x10: - - // sprmPNest is only stored in grpprls linked to a piece table. - newPAP.setDxaLeft (newPAP.getDxaLeft () + sprm.getOperand()); - newPAP.setDxaLeft (Math.max (0, newPAP.getDxaLeft ())); - break; - case 0x11: - newPAP.setDxaLeft1 (sprm.getOperand()); - break; - case 0x12: - newPAP.setLspd(new LineSpacingDescriptor(sprm.getGrpprl(), sprm.getGrpprlOffset())); - break; - case 0x13: - newPAP.setDyaBefore (sprm.getOperand()); - break; - case 0x14: - newPAP.setDyaAfter (sprm.getOperand()); - break; - case 0x15: - // fast saved only - //applySprmPChgTabs (newPAP, varParam, opSize); - break; - case 0x16: - // sprmPFInTable -- 0x2416 - newPAP.setFInTable( sprm.getOperand() != 0); - break; - case 0x17: - newPAP.setFTtp ( sprm.getOperand() != 0); - break; - case 0x18: - newPAP.setDxaAbs (sprm.getOperand()); - break; - case 0x19: - newPAP.setDyaAbs (sprm.getOperand()); - break; - case 0x1a: - newPAP.setDxaWidth (sprm.getOperand()); - break; - case 0x1b: - byte param = (byte)sprm.getOperand(); - /** @todo handle paragraph postioning*/ - byte pcVert = (byte) ((param & 0x0c) >> 2); - byte pcHorz = (byte) (param & 0x03); - if (pcVert != 3) - { - newPAP.setPcVert (pcVert); - } - if (pcHorz != 3) - { - newPAP.setPcHorz (pcHorz); - } - break; - - // BrcXXX1 is older Version. Brc is used - // case 0x1c: - // newPAP.setBrcTop1((short)param); - // break; - // case 0x1d: - // newPAP.setBrcLeft1((short)param); - // break; - // case 0x1e: - // newPAP.setBrcBottom1((short)param); - // break; - // case 0x1f: - // newPAP.setBrcRight1((short)param); - // break; - // case 0x20: - // newPAP.setBrcBetween1((short)param); - // break; - // case 0x21: - // newPAP.setBrcBar1((byte)param); - // break; - - case 0x22: - newPAP.setDxaFromText (sprm.getOperand()); - break; - case 0x23: - newPAP.setWr((byte)sprm.getOperand()); - break; - case 0x24: - newPAP.setBrcTop(new BorderCode(sprm.getGrpprl(), sprm.getGrpprlOffset())); - break; - case 0x25: - newPAP.setBrcLeft(new BorderCode(sprm.getGrpprl(), sprm.getGrpprlOffset())); - break; - case 0x26: - newPAP.setBrcBottom (new BorderCode(sprm.getGrpprl(), sprm.getGrpprlOffset())); - break; - case 0x27: - newPAP.setBrcRight (new BorderCode(sprm.getGrpprl(), sprm.getGrpprlOffset())); - break; - case 0x28: - newPAP.setBrcBetween (new BorderCode(sprm.getGrpprl(), sprm.getGrpprlOffset())); - break; - case 0x29: - newPAP.setBrcBar (new BorderCode(sprm.getGrpprl(), sprm.getGrpprlOffset())); - break; - case 0x2a: - newPAP.setFNoAutoHyph (sprm.getOperand() != 0); - break; - case 0x2b: - newPAP.setDyaHeight (sprm.getOperand()); - break; - case 0x2c: - newPAP.setDcs (new DropCapSpecifier((short)sprm.getOperand())); - break; - case 0x2d: - newPAP.setShd( new ShadingDescriptor80( (short) sprm.getOperand() ) - .toShadingDescriptor() ); - break; - case 0x2e: - newPAP.setDyaFromText (sprm.getOperand()); - break; - case 0x2f: - newPAP.setDxaFromText (sprm.getOperand()); - break; - case 0x30: - newPAP.setFLocked (sprm.getOperand() != 0); - break; - case 0x31: - newPAP.setFWidowControl (sprm.getOperand() != 0); - break; - case 0x33: - newPAP.setFKinsoku (sprm.getOperand() != 0); - break; - case 0x34: - newPAP.setFWordWrap (sprm.getOperand() != 0); - break; - case 0x35: - newPAP.setFOverflowPunct (sprm.getOperand() != 0); - break; - case 0x36: - newPAP.setFTopLinePunct (sprm.getOperand() != 0); - break; - case 0x37: - newPAP.setFAutoSpaceDE (sprm.getOperand() != 0); - break; - case 0x38: - newPAP.setFAutoSpaceDN (sprm.getOperand() != 0); - break; - case 0x39: - newPAP.setWAlignFont (sprm.getOperand()); - break; - case 0x3a: - newPAP.setFontAlign ((short) sprm.getOperand()); - break; - case 0x3b: - //obsolete - break; - case 0x3e: - { - byte[] buf = new byte[sprm.size() - 3]; - System.arraycopy(buf, 0, sprm.getGrpprl(), sprm.getGrpprlOffset(), - buf.length); - newPAP.setAnld(buf); - break; - } - case 0x3f: - //don't really need this. spec is confusing regarding this - //sprm - byte[] varParam = sprm.getGrpprl(); - int offset = sprm.getGrpprlOffset(); - newPAP.setFPropRMark (varParam[offset] != 0 ); - newPAP.setIbstPropRMark (LittleEndian.getShort (varParam, offset + 1)); - newPAP.setDttmPropRMark (new DateAndTime(varParam, offset + 3)); - break; - case 0x40: - // This condition commented out, as Word seems to set outline levels even for - // paragraph with other styles than Heading 1..9, even though specification - // does not say so. See bug 49820 for discussion. - //if (newPAP.getIstd () < 1 && newPAP.getIstd () > 9) - { - newPAP.setLvl ((byte) sprm.getOperand()); - } - break; - case 0x41: - // sprmPFBiDi - newPAP.setFBiDi(sprm.getOperand() != 0); - break; - case 0x43: - - //pap.fNumRMIns - newPAP.setFNumRMIns (sprm.getOperand() != 0); - break; - case 0x44: - - //undocumented - break; - case 0x45: - if (sprm.getSizeCode() == 6) - { - byte[] buf = new byte[sprm.size() - 3]; - System.arraycopy(buf, 0, sprm.getGrpprl(), sprm.getGrpprlOffset(), buf.length); - newPAP.setNumrm (buf); - } - else - { - /**@todo handle large PAPX from data stream*/ - } - break; - - case 0x47: - newPAP.setFUsePgsuSettings (sprm.getOperand() != 0); - break; - case 0x48: - newPAP.setFAdjustRight (sprm.getOperand() != 0); - break; - case 0x49: - // sprmPItap -- 0x6649 - newPAP.setItap( sprm.getOperand() ); - break; - case 0x4a: - // sprmPDtap -- 0x664a - newPAP.setItap( (byte) ( newPAP.getItap() + sprm.getOperand() ) ); - break; - case 0x4b: - // sprmPFInnerTableCell -- 0x244b - newPAP.setFInnerTableCell( sprm.getOperand() != 0); - break; - case 0x4c: - // sprmPFInnerTtp -- 0x244c - newPAP.setFTtpEmbedded( sprm.getOperand() != 0); - break; - case 0x4d: - // sprmPShd -- 0xc64d - ShadingDescriptor shadingDescriptor = new ShadingDescriptor( - sprm.getGrpprl(), 3 ); - newPAP.setShading( shadingDescriptor ); - break; - case 0x5d: - // sprmPDxaRight -- 0x845d - newPAP.setDxaRight( sprm.getOperand() ); - break; - case 0x5e: - // sprmPDxaLeft -- 0x845e - newPAP.setDxaLeft( sprm.getOperand() ); - break; - case 0x60: - // sprmPDxaLeft1 -- 0x8460 - newPAP.setDxaLeft1( sprm.getOperand() ); - break; - case 0x61: - // sprmPJc - newPAP.setJustificationLogical((byte) sprm.getOperand()); - break; - case 0x67: - // sprmPRsid -- 0x6467 - newPAP.setRsid( sprm.getOperand() ); - break; - default: - logger.log( POILogger.DEBUG, "Unknown PAP sprm ignored: " + sprm ); - break; - } - } - - private static void handleTabs(ParagraphProperties pap, SprmOperation sprm) - { - byte[] grpprl = sprm.getGrpprl(); - int offset = sprm.getGrpprlOffset(); - int delSize = grpprl[offset++]; - int[] tabPositions = pap.getRgdxaTab(); - TabDescriptor[] tabDescriptors = pap.getRgtbd(); - - Map tabMap = new HashMap(); - for (int x = 0; x < tabPositions.length; x++) - { - tabMap.put(Integer.valueOf(tabPositions[x]), tabDescriptors[x]); - } - - for (int x = 0; x < delSize; x++) - { - tabMap.remove(Integer.valueOf(LittleEndian.getShort(grpprl, offset))); - offset += LittleEndian.SHORT_SIZE; - } - - int addSize = grpprl[offset++]; - int start = offset; - for (int x = 0; x < addSize; x++) - { - Integer key = Integer.valueOf(LittleEndian.getShort(grpprl, offset)); - TabDescriptor val = new TabDescriptor( grpprl, start + ((TabDescriptor.getSize() * addSize) + x) ); - tabMap.put(key, val); - offset += LittleEndian.SHORT_SIZE; - } - - tabPositions = new int[tabMap.size()]; - tabDescriptors = new TabDescriptor[tabPositions.length]; - - List list = new ArrayList(tabMap.keySet()); - Collections.sort(list); - - for (int x = 0; x < tabPositions.length; x++) - { - Integer key = list.get(x); - tabPositions[x] = key.intValue(); - if (tabMap.containsKey( key )) - tabDescriptors[x] = tabMap.get(key); - else - tabDescriptors[x] = new TabDescriptor(); - } - - pap.setRgdxaTab(tabPositions); - pap.setRgtbd(tabDescriptors); - } - -// private static void handleTabsAgain(ParagraphProperties pap, SprmOperation sprm) -// { -// byte[] grpprl = sprm.getGrpprl(); -// int offset = sprm.getGrpprlOffset(); -// int delSize = grpprl[offset++]; -// int[] tabPositions = pap.getRgdxaTab(); -// byte[] tabDescriptors = pap.getRgtbd(); -// -// HashMap tabMap = new HashMap(); -// for (int x = 0; x < tabPositions.length; x++) -// { -// tabMap.put(Integer.valueOf(tabPositions[x]), Byte.valueOf(tabDescriptors[x])); -// } -// -// for (int x = 0; x < delSize; x++) -// { -// tabMap.remove(Integer.valueOf(LittleEndian.getInt(grpprl, offset))); -// offset += LittleEndian.INT_SIZE;; -// } -// -// int addSize = grpprl[offset++]; -// for (int x = 0; x < addSize; x++) -// { -// Integer key = Integer.valueOf(LittleEndian.getInt(grpprl, offset)); -// Byte val = Byte.valueOf(grpprl[(LittleEndian.INT_SIZE * (addSize - x)) + x]); -// tabMap.put(key, val); -// offset += LittleEndian.INT_SIZE; -// } -// -// tabPositions = new int[tabMap.size()]; -// tabDescriptors = new byte[tabPositions.length]; -// ArrayList list = new ArrayList(); -// -// Iterator keyIT = tabMap.keySet().iterator(); -// while (keyIT.hasNext()) -// { -// list.add(keyIT.next()); -// } -// Collections.sort(list); -// -// for (int x = 0; x < tabPositions.length; x++) -// { -// Integer key = ((Integer)list.get(x)); -// tabPositions[x] = key.intValue(); -// tabDescriptors[x] = ((Byte)tabMap.get(key)).byteValue(); -// } -// -// pap.setRgdxaTab(tabPositions); -// pap.setRgtbd(tabDescriptors); -// } - -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/sprm/SectionSprmCompressor.java b/src/scratchpad/src/org/apache/poi/hwpf/sprm/SectionSprmCompressor.java deleted file mode 100644 index 8d20a7490..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/sprm/SectionSprmCompressor.java +++ /dev/null @@ -1,236 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.sprm; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.apache.poi.hwpf.usermodel.SectionProperties; -import org.apache.poi.util.Internal; -import org.apache.poi.util.LittleEndian; - -@Internal -public final class SectionSprmCompressor -{ - private final static SectionProperties DEFAULT_SEP = new SectionProperties(); - public SectionSprmCompressor() - { - } - public static byte[] compressSectionProperty(SectionProperties newSEP) - { - int size = 0; - List sprmList = new ArrayList(); - - if (newSEP.getCnsPgn() != DEFAULT_SEP.getCnsPgn()) - { - size += SprmUtils.addSprm((short)0x3000, newSEP.getCnsPgn(), null, sprmList); - } - if (newSEP.getIHeadingPgn() != DEFAULT_SEP.getIHeadingPgn()) - { - size += SprmUtils.addSprm((short)0x3001, newSEP.getIHeadingPgn(), null, sprmList); - } - if (!Arrays.equals(newSEP.getOlstAnm(), DEFAULT_SEP.getOlstAnm())) - { - size += SprmUtils.addSprm((short)0xD202, 0, newSEP.getOlstAnm(), sprmList); - } - if (newSEP.getFEvenlySpaced() != DEFAULT_SEP.getFEvenlySpaced()) - { - size += SprmUtils.addSprm((short)0x3005, newSEP.getFEvenlySpaced() ? 1 : 0, null, sprmList); - } - if (newSEP.getFUnlocked() != DEFAULT_SEP.getFUnlocked()) - { - size += SprmUtils.addSprm((short)0x3006, newSEP.getFUnlocked() ? 1 :0, null, sprmList); - } - if (newSEP.getDmBinFirst() != DEFAULT_SEP.getDmBinFirst()) - { - size += SprmUtils.addSprm((short)0x5007, newSEP.getDmBinFirst(), null, sprmList); - } - if (newSEP.getDmBinOther() != DEFAULT_SEP.getDmBinOther()) - { - size += SprmUtils.addSprm((short)0x5008, newSEP.getDmBinOther(), null, sprmList); - } - if (newSEP.getBkc() != DEFAULT_SEP.getBkc()) - { - size += SprmUtils.addSprm((short)0x3009, newSEP.getBkc(), null, sprmList); - } - if (newSEP.getFTitlePage() != DEFAULT_SEP.getFTitlePage()) - { - size += SprmUtils.addSprm((short)0x300A, newSEP.getFTitlePage() ? 1 : 0, null, sprmList); - } - if (newSEP.getCcolM1() != DEFAULT_SEP.getCcolM1()) - { - size += SprmUtils.addSprm((short)0x500B, newSEP.getCcolM1(), null, sprmList); - } - if (newSEP.getDxaColumns() != DEFAULT_SEP.getDxaColumns()) - { - size += SprmUtils.addSprm((short)0x900C, newSEP.getDxaColumns(), null, sprmList); - } - if (newSEP.getFAutoPgn() != DEFAULT_SEP.getFAutoPgn()) - { - size += SprmUtils.addSprm((short)0x300D, newSEP.getFAutoPgn() ? 1 : 0, null, sprmList); - } - if (newSEP.getNfcPgn() != DEFAULT_SEP.getNfcPgn()) - { - size += SprmUtils.addSprm((short)0x300E, newSEP.getNfcPgn(), null, sprmList); - } - if (newSEP.getDyaPgn() != DEFAULT_SEP.getDyaPgn()) - { - size += SprmUtils.addSprm((short)0xB00F, newSEP.getDyaPgn(), null, sprmList); - } - if (newSEP.getDxaPgn() != DEFAULT_SEP.getDxaPgn()) - { - size += SprmUtils.addSprm((short)0xB010, newSEP.getDxaPgn(), null, sprmList); - } - if (newSEP.getFPgnRestart() != DEFAULT_SEP.getFPgnRestart()) - { - size += SprmUtils.addSprm((short)0x3011, newSEP.getFPgnRestart() ? 1 : 0, null, sprmList); - } - if (newSEP.getFEndNote() != DEFAULT_SEP.getFEndNote()) - { - size += SprmUtils.addSprm((short)0x3012, newSEP.getFEndNote() ? 1 : 0, null, sprmList); - } - if (newSEP.getLnc() != DEFAULT_SEP.getLnc()) - { - size += SprmUtils.addSprm((short)0x3013, newSEP.getLnc(), null, sprmList); - } - if (newSEP.getGrpfIhdt() != DEFAULT_SEP.getGrpfIhdt()) - { - size += SprmUtils.addSprm((short)0x3014, newSEP.getGrpfIhdt(), null, sprmList); - } - if (newSEP.getNLnnMod() != DEFAULT_SEP.getNLnnMod()) - { - size += SprmUtils.addSprm((short)0x5015, newSEP.getNLnnMod(), null, sprmList); - } - if (newSEP.getDxaLnn() != DEFAULT_SEP.getDxaLnn()) - { - size += SprmUtils.addSprm((short)0x9016, newSEP.getDxaLnn(), null, sprmList); - } - if (newSEP.getDyaHdrTop() != DEFAULT_SEP.getDyaHdrTop()) - { - size += SprmUtils.addSprm((short)0xB017, newSEP.getDyaHdrTop(), null, sprmList); - } - if (newSEP.getDyaHdrBottom() != DEFAULT_SEP.getDyaHdrBottom()) - { - size += SprmUtils.addSprm((short)0xB018, newSEP.getDyaHdrBottom(), null, sprmList); - } - if (newSEP.getFLBetween() != DEFAULT_SEP.getFLBetween()) - { - size += SprmUtils.addSprm((short)0x3019, newSEP.getFLBetween() ? 1 : 0, null, sprmList); - } - if (newSEP.getVjc() != DEFAULT_SEP.getVjc()) - { - size += SprmUtils.addSprm((short)0x301A, newSEP.getVjc(), null, sprmList); - } - if (newSEP.getLnnMin() != DEFAULT_SEP.getLnnMin()) - { - size += SprmUtils.addSprm((short)0x501B, newSEP.getLnnMin(), null, sprmList); - } - if (newSEP.getPgnStart() != DEFAULT_SEP.getPgnStart()) - { - size += SprmUtils.addSprm((short)0x501C, newSEP.getPgnStart(), null, sprmList); - } - if (newSEP.getDmOrientPage() != DEFAULT_SEP.getDmOrientPage()) - { - size += SprmUtils.addSprm((short)0x301D, newSEP.getDmOrientPage() ? 1 : 0, null, sprmList); - } - if (newSEP.getXaPage() != DEFAULT_SEP.getXaPage()) - { - size += SprmUtils.addSprm((short)0xB01F, newSEP.getXaPage(), null, sprmList); - } - if (newSEP.getYaPage() != DEFAULT_SEP.getYaPage()) - { - size += SprmUtils.addSprm((short)0xB020, newSEP.getYaPage(), null, sprmList); - } - if (newSEP.getDxaLeft() != DEFAULT_SEP.getDxaLeft()) - { - size += SprmUtils.addSprm((short)0xB021, newSEP.getDxaLeft(), null, sprmList); - } - if (newSEP.getDxaRight() != DEFAULT_SEP.getDxaRight()) - { - size += SprmUtils.addSprm((short)0xB022, newSEP.getDxaRight(), null, sprmList); - } - if (newSEP.getDyaTop() != DEFAULT_SEP.getDyaTop()) - { - size += SprmUtils.addSprm((short)0x9023, newSEP.getDyaTop(), null, sprmList); - } - if (newSEP.getDyaBottom() != DEFAULT_SEP.getDyaBottom()) - { - size += SprmUtils.addSprm((short)0x9024, newSEP.getDyaBottom(), null, sprmList); - } - if (newSEP.getDzaGutter() != DEFAULT_SEP.getDzaGutter()) - { - size += SprmUtils.addSprm((short)0xB025, newSEP.getDzaGutter(), null, sprmList); - } - if (newSEP.getDmPaperReq() != DEFAULT_SEP.getDmPaperReq()) - { - size += SprmUtils.addSprm((short)0x5026, newSEP.getDmPaperReq(), null, sprmList); - } - if (newSEP.getFPropMark() != DEFAULT_SEP.getFPropMark() || - newSEP.getIbstPropRMark() != DEFAULT_SEP.getIbstPropRMark() || - !newSEP.getDttmPropRMark().equals(DEFAULT_SEP.getDttmPropRMark())) - { - byte[] buf = new byte[7]; - buf[0] = (byte)(newSEP.getFPropMark() ? 1 : 0); - int offset = LittleEndian.BYTE_SIZE; - LittleEndian.putShort(buf, 0, (short)newSEP.getIbstPropRMark()); - offset += LittleEndian.SHORT_SIZE; - newSEP.getDttmPropRMark().serialize(buf, offset); - size += SprmUtils.addSprm((short)0xD227, -1, buf, sprmList); - } - if (!newSEP.getBrcTop().equals( DEFAULT_SEP.getBrcTop())) - { - size += SprmUtils.addSprm((short)0x702B, newSEP.getBrcTop().toInt(), null, sprmList); - } - if (!newSEP.getBrcLeft().equals(DEFAULT_SEP.getBrcLeft())) - { - size += SprmUtils.addSprm((short)0x702C, newSEP.getBrcLeft().toInt(), null, sprmList); - } - if (!newSEP.getBrcBottom().equals(DEFAULT_SEP.getBrcBottom())) - { - size += SprmUtils.addSprm((short)0x702D, newSEP.getBrcBottom().toInt(), null, sprmList); - } - if (!newSEP.getBrcRight().equals(DEFAULT_SEP.getBrcRight())) - { - size += SprmUtils.addSprm((short)0x702E, newSEP.getBrcRight().toInt(), null, sprmList); - } - if (newSEP.getPgbProp() != DEFAULT_SEP.getPgbProp()) - { - size += SprmUtils.addSprm((short)0x522F, newSEP.getPgbProp(), null, sprmList); - } - if (newSEP.getDxtCharSpace() != DEFAULT_SEP.getDxtCharSpace()) - { - size += SprmUtils.addSprm((short)0x7030, newSEP.getDxtCharSpace(), null, sprmList); - } - if (newSEP.getDyaLinePitch() != DEFAULT_SEP.getDyaLinePitch()) - { - size += SprmUtils.addSprm((short)0x9031, newSEP.getDyaLinePitch(), null, sprmList); - } - if (newSEP.getClm() != DEFAULT_SEP.getClm()) - { - size += SprmUtils.addSprm((short)0x5032, newSEP.getClm(), null, sprmList); - } - if (newSEP.getWTextFlow() != DEFAULT_SEP.getWTextFlow()) - { - size += SprmUtils.addSprm((short)0x5033, newSEP.getWTextFlow(), null, sprmList); - } - - return SprmUtils.getGrpprl(sprmList, size); - } -} - diff --git a/src/scratchpad/src/org/apache/poi/hwpf/sprm/SectionSprmUncompressor.java b/src/scratchpad/src/org/apache/poi/hwpf/sprm/SectionSprmUncompressor.java deleted file mode 100644 index 0b186b56b..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/sprm/SectionSprmUncompressor.java +++ /dev/null @@ -1,250 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.sprm; - -import org.apache.poi.hwpf.usermodel.BorderCode; -import org.apache.poi.hwpf.usermodel.SectionProperties; -import org.apache.poi.util.HexDump; -import org.apache.poi.util.Internal; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; - - -@Internal -public final class SectionSprmUncompressor extends SprmUncompressor -{ - private static final POILogger logger = POILogFactory.getLogger(SectionSprmUncompressor.class); - - public SectionSprmUncompressor() - { - } - public static SectionProperties uncompressSEP(byte[] grpprl, int offset) - { - SectionProperties newProperties = new SectionProperties(); - - SprmIterator sprmIt = new SprmIterator(grpprl, offset); - - while (sprmIt.hasNext()) - { - SprmOperation sprm = sprmIt.next(); - unCompressSEPOperation(newProperties, sprm); - } - - return newProperties; - } - - /** - * Used in decompression of a sepx. This performs an operation defined by - * a single sprm. - * - * @param newSEP The SectionProperty to perform the operation on. - * @param operand The operation to perform. - * @param param The operation's parameter. - * @param varParam The operation variable length parameter. - */ - static void unCompressSEPOperation (SectionProperties newSEP, SprmOperation sprm) - { - int operation = sprm.getOperation(); - switch (operation) - { - case 0: - newSEP.setCnsPgn ((byte) sprm.getOperand()); - break; - case 0x1: - newSEP.setIHeadingPgn ((byte) sprm.getOperand()); - break; - case 0x2: - byte[] buf = new byte[sprm.size() - 3]; - System.arraycopy(sprm.getGrpprl(), sprm.getGrpprlOffset(), buf, 0, buf.length); - newSEP.setOlstAnm (buf); - break; - case 0x3: - //not quite sure - break; - case 0x4: - //not quite sure - break; - case 0x5: - newSEP.setFEvenlySpaced (getFlag (sprm.getOperand())); - break; - case 0x6: - newSEP.setFUnlocked (getFlag (sprm.getOperand())); - break; - case 0x7: - newSEP.setDmBinFirst ((short) sprm.getOperand()); - break; - case 0x8: - newSEP.setDmBinOther ((short) sprm.getOperand()); - break; - case 0x9: - newSEP.setBkc ((byte) sprm.getOperand()); - break; - case 0xa: - newSEP.setFTitlePage (getFlag (sprm.getOperand())); - break; - case 0xb: - newSEP.setCcolM1 ((short) sprm.getOperand()); - break; - case 0xc: - newSEP.setDxaColumns (sprm.getOperand()); - break; - case 0xd: - newSEP.setFAutoPgn (getFlag (sprm.getOperand())); - break; - case 0xe: - newSEP.setNfcPgn ((byte) sprm.getOperand()); - break; - case 0xf: - newSEP.setDyaPgn ((short) sprm.getOperand()); - break; - case 0x10: - newSEP.setDxaPgn ((short) sprm.getOperand()); - break; - case 0x11: - newSEP.setFPgnRestart (getFlag (sprm.getOperand())); - break; - case 0x12: - newSEP.setFEndNote (getFlag (sprm.getOperand())); - break; - case 0x13: - newSEP.setLnc ((byte) sprm.getOperand()); - break; - case 0x14: - newSEP.setGrpfIhdt ((byte) sprm.getOperand()); - break; - case 0x15: - newSEP.setNLnnMod ((short) sprm.getOperand()); - break; - case 0x16: - newSEP.setDxaLnn (sprm.getOperand()); - break; - case 0x17: - newSEP.setDyaHdrTop (sprm.getOperand()); - break; - case 0x18: - newSEP.setDyaHdrBottom (sprm.getOperand()); - break; - case 0x19: - newSEP.setFLBetween (getFlag (sprm.getOperand())); - break; - case 0x1a: - newSEP.setVjc ((byte) sprm.getOperand()); - break; - case 0x1b: - newSEP.setLnnMin ((short) sprm.getOperand()); - break; - case 0x1c: - newSEP.setPgnStart ((short) sprm.getOperand()); - break; - case 0x1d: - newSEP.setDmOrientPage( sprm.getOperand() != 0 ); - break; - case 0x1e: - - //nothing - break; - case 0x1f: - newSEP.setXaPage (sprm.getOperand()); - break; - case 0x20: - newSEP.setYaPage (sprm.getOperand()); - break; - case 0x21: - newSEP.setDxaLeft (sprm.getOperand()); - break; - case 0x22: - newSEP.setDxaRight (sprm.getOperand()); - break; - case 0x23: - newSEP.setDyaTop (sprm.getOperand()); - break; - case 0x24: - newSEP.setDyaBottom (sprm.getOperand()); - break; - case 0x25: - newSEP.setDzaGutter (sprm.getOperand()); - break; - case 0x26: - newSEP.setDmPaperReq ((short) sprm.getOperand()); - break; - case 0x27: - newSEP.setFPropMark (getFlag (sprm.getOperand())); - break; - case 0x28: - break; - case 0x29: - break; - case 0x2a: - break; - case 0x2b: - newSEP.setBrcTop(new BorderCode(sprm.getGrpprl(), sprm.getGrpprlOffset())); - break; - case 0x2c: - newSEP.setBrcLeft(new BorderCode(sprm.getGrpprl(), sprm.getGrpprlOffset())); - break; - case 0x2d: - newSEP.setBrcBottom(new BorderCode(sprm.getGrpprl(), sprm.getGrpprlOffset())); - break; - case 0x2e: - newSEP.setBrcRight(new BorderCode(sprm.getGrpprl(), sprm.getGrpprlOffset())); - break; - case 0x2f: - newSEP.setPgbProp (sprm.getOperand()); - break; - case 0x30: - newSEP.setDxtCharSpace (sprm.getOperand()); - break; - case 0x31: - newSEP.setDyaLinePitch (sprm.getOperand()); - break; - case 0x33: - newSEP.setWTextFlow ((short) sprm.getOperand()); - break; - case 0x3C: - // [MS-DOC], v20140721, 2.6.4, sprmSRncFtn - newSEP.setRncFtn((short) sprm.getOperand()); - break; - case 0x3E: - // [MS-DOC], v20140721, 2.6.4, sprmSRncEdn - newSEP.setRncEdn((short) sprm.getOperand()); - break; - case 0x3F: - // [MS-DOC], v20140721, 2.6.4, sprmSNFtn - newSEP.setNFtn((int) sprm.getOperand()); - break; - case 0x40: - // [MS-DOC], v20140721, 2.6.4, sprmSNFtnRef - newSEP.setNfcFtnRef((int) sprm.getOperand()); - break; - case 0x41: - // [MS-DOC], v20140721, 2.6.4, sprmSNEdn - newSEP.setNEdn((int) sprm.getOperand()); - break; - case 0x42: - // [MS-DOC], v20140721, 2.6.4, sprmSNEdnRef - newSEP.setNfcEdnRef((int) sprm.getOperand()); - break; - default: - logger.log(POILogger.INFO, "Unsupported Sprm operation: " + operation + " (" + HexDump.byteToHex(operation) + ")"); - break; - } - - } - - -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/sprm/SprmBuffer.java b/src/scratchpad/src/org/apache/poi/hwpf/sprm/SprmBuffer.java deleted file mode 100644 index 24ef823c4..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/sprm/SprmBuffer.java +++ /dev/null @@ -1,270 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.sprm; - -import java.util.Arrays; - -import org.apache.poi.util.Internal; -import org.apache.poi.util.LittleEndian; - -@Internal -public final class SprmBuffer implements Cloneable -{ - byte[] _buf; - boolean _istd; - int _offset; - - private final int _sprmsStartOffset; - - /** - * @deprecated Use {@link #SprmBuffer(int)} instead - */ - @Deprecated - public SprmBuffer() - { - this( 0 ); - } - - /** - * @deprecated Use {@link #SprmBuffer(byte[],int)} instead - */ - @Deprecated - public SprmBuffer( byte[] buf ) - { - this( buf, 0 ); - } - - /** - * @deprecated Use {@link #SprmBuffer(byte[],boolean,int)} instead - */ - @Deprecated - public SprmBuffer( byte[] buf, boolean istd ) - { - this( buf, istd, 0 ); - } - - public SprmBuffer( byte[] buf, boolean istd, int sprmsStartOffset ) - { - _offset = buf.length; - _buf = buf; - _istd = istd; - _sprmsStartOffset = sprmsStartOffset; - } - - public SprmBuffer( byte[] buf, int _sprmsStartOffset ) - { - this( buf, false, _sprmsStartOffset ); - } - - public SprmBuffer( int sprmsStartOffset ) - { - _buf = new byte[sprmsStartOffset + 4]; - _offset = sprmsStartOffset; - _sprmsStartOffset = sprmsStartOffset; - } - - public void addSprm(short opcode, byte operand) - { - int addition = LittleEndian.SHORT_SIZE + LittleEndian.BYTE_SIZE; - ensureCapacity(addition); - LittleEndian.putShort(_buf, _offset, opcode); - _offset += LittleEndian.SHORT_SIZE; - _buf[_offset++] = operand; - } - - public void addSprm(short opcode, byte[] operand) - { - int addition = LittleEndian.SHORT_SIZE + LittleEndian.BYTE_SIZE + operand.length; - ensureCapacity(addition); - LittleEndian.putShort(_buf, _offset, opcode); - _offset += LittleEndian.SHORT_SIZE; - _buf[_offset++] = (byte)operand.length; - System.arraycopy(operand, 0, _buf, _offset, operand.length); - } - - public void addSprm(short opcode, int operand) - { - int addition = LittleEndian.SHORT_SIZE + LittleEndian.INT_SIZE; - ensureCapacity(addition); - LittleEndian.putShort(_buf, _offset, opcode); - _offset += LittleEndian.SHORT_SIZE; - LittleEndian.putInt(_buf, _offset, operand); - _offset += LittleEndian.INT_SIZE; - } - - public void addSprm(short opcode, short operand) - { - int addition = LittleEndian.SHORT_SIZE + LittleEndian.SHORT_SIZE; - ensureCapacity(addition); - LittleEndian.putShort(_buf, _offset, opcode); - _offset += LittleEndian.SHORT_SIZE; - LittleEndian.putShort(_buf, _offset, operand); - _offset += LittleEndian.SHORT_SIZE; - } - - public void append( byte[] grpprl ) -{ - append( grpprl, 0 ); -} - - public void append( byte[] grpprl, int offset ) -{ - ensureCapacity( grpprl.length - offset ); - System.arraycopy( grpprl, offset, _buf, _offset, grpprl.length - offset ); - _offset += grpprl.length - offset; -} - public SprmBuffer clone() - { - try { - SprmBuffer retVal = (SprmBuffer)super.clone(); - retVal._buf = new byte[_buf.length]; - System.arraycopy(_buf, 0, retVal._buf, 0, _buf.length); - return retVal; - } catch (CloneNotSupportedException e) { - throw new RuntimeException(e); - } - } - private void ensureCapacity( int addition ) -{ - if ( _offset + addition >= _buf.length ) - { - // add 6 more than they need for use the next iteration - // - // commented - buffer shall not contain any additional bytes -- - // sergey - // byte[] newBuf = new byte[_offset + addition + 6]; - byte[] newBuf = new byte[_offset + addition]; - System.arraycopy( _buf, 0, newBuf, 0, _buf.length ); - _buf = newBuf; - } -} - - @Override - public boolean equals(Object obj) - { - if (!(obj instanceof SprmBuffer)) return false; - SprmBuffer sprmBuf = (SprmBuffer)obj; - return (Arrays.equals(_buf, sprmBuf._buf)); - } - - @Override - public int hashCode() { - assert false : "hashCode not designed"; - return 42; // any arbitrary constant will do - } - - public SprmOperation findSprm( short opcode ) -{ - int operation = SprmOperation.getOperationFromOpcode( opcode ); - int type = SprmOperation.getTypeFromOpcode( opcode ); - - SprmIterator si = new SprmIterator( _buf, 2 ); - while ( si.hasNext() ) - { - SprmOperation i = si.next(); - if ( i.getOperation() == operation && i.getType() == type ) - return i; - } - return null; -} - - private int findSprmOffset( short opcode ) -{ - SprmOperation sprmOperation = findSprm( opcode ); - if ( sprmOperation == null ) - return -1; - - return sprmOperation.getGrpprlOffset(); -} - - public byte[] toByteArray() - { - return _buf; - } - - public SprmIterator iterator() - { - return new SprmIterator( _buf, _sprmsStartOffset ); - } - - public void updateSprm(short opcode, byte operand) - { - int grpprlOffset = findSprmOffset(opcode); - if(grpprlOffset != -1) - { - _buf[grpprlOffset] = operand; - return; - } - addSprm(opcode, operand); - } - - public void updateSprm( short opcode, boolean operand ) - { - int grpprlOffset = findSprmOffset( opcode ); - if ( grpprlOffset != -1 ) - { - _buf[grpprlOffset] = (byte) ( operand ? 1 : 0 ); - return; - } - addSprm( opcode, operand ? 1 : 0 ); - } - - public void updateSprm(short opcode, int operand) - { - int grpprlOffset = findSprmOffset(opcode); - if(grpprlOffset != -1) - { - LittleEndian.putInt(_buf, grpprlOffset, operand); - return; - } - addSprm(opcode, operand); - } - - public void updateSprm(short opcode, short operand) - { - int grpprlOffset = findSprmOffset(opcode); - if(grpprlOffset != -1) - { - LittleEndian.putShort(_buf, grpprlOffset, operand); - return; - } - addSprm(opcode, operand); - } - - @Override - public String toString() - { - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append( "Sprms (" ); - stringBuilder.append( _buf.length ); - stringBuilder.append( " byte(s)): " ); - for ( SprmIterator iterator = iterator(); iterator.hasNext(); ) - { - try - { - stringBuilder.append( iterator.next() ); - } - catch ( Exception exc ) - { - stringBuilder.append( "error" ); - } - stringBuilder.append( "; " ); - } - return stringBuilder.toString(); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/sprm/SprmIterator.java b/src/scratchpad/src/org/apache/poi/hwpf/sprm/SprmIterator.java deleted file mode 100644 index dd4ba7962..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/sprm/SprmIterator.java +++ /dev/null @@ -1,54 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.sprm; - -import org.apache.poi.util.Internal; - -/** - * This class is used to iterate through a list of sprms from a Word 97/2000/XP - * document. - * @author Ryan Ackley - * @version 1.0 - */ -@Internal -public final class SprmIterator -{ - private byte[] _grpprl; - int _offset; - - public SprmIterator(byte[] grpprl, int offset) - { - _grpprl = grpprl; - _offset = offset; - } - - public boolean hasNext() - { - // A Sprm is at least 2 bytes long - return _offset < (_grpprl.length-1); - } - - public SprmOperation next() - { - SprmOperation op = new SprmOperation(_grpprl, _offset); - _offset += op.size(); - return op; - } - - -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/sprm/SprmOperation.java b/src/scratchpad/src/org/apache/poi/hwpf/sprm/SprmOperation.java deleted file mode 100644 index 5a557ef84..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/sprm/SprmOperation.java +++ /dev/null @@ -1,207 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.sprm; - -import org.apache.poi.util.BitField; -import org.apache.poi.util.BitFieldFactory; -import org.apache.poi.util.Internal; -import org.apache.poi.util.LittleEndian; - -/** - * This class is used to represent a sprm operation from a Word 97/2000/XP - * document. - */ -@Internal(since="3.8 beta 4") -public final class SprmOperation -{ - private static final BitField BITFIELD_OP = BitFieldFactory - .getInstance( 0x1ff ); - private static final BitField BITFIELD_SIZECODE = BitFieldFactory - .getInstance( 0xe000 ); - private static final BitField BITFIELD_SPECIAL = BitFieldFactory - .getInstance( 0x200 ); - private static final BitField BITFIELD_TYPE = BitFieldFactory - .getInstance( 0x1c00 ); - - final static private short SPRM_LONG_PARAGRAPH = (short) 0xc615; - final static private short SPRM_LONG_TABLE = (short) 0xd608; - - public static final int TYPE_PAP = 1; - public static final int TYPE_CHP = 2; - public static final int TYPE_PIC = 3; - public static final int TYPE_SEP = 4; - public static final int TYPE_TAP = 5; - - public static int getOperationFromOpcode( short opcode ) - { - return BITFIELD_OP.getValue( opcode ); - } - - public static int getTypeFromOpcode( short opcode ) - { - return BITFIELD_TYPE.getValue( opcode ); - } - - private final int _offset; - private int _gOffset; - private final byte[] _grpprl; - private final int _size; - private final short _value; - - public SprmOperation( byte[] grpprl, int offset ) - { - _grpprl = grpprl; - _value = LittleEndian.getShort( grpprl, offset ); - _offset = offset; - _gOffset = offset + 2; - _size = initSize( _value ); - } - - public byte[] toByteArray() - { - byte[] result = new byte[size()]; - System.arraycopy( _grpprl, _offset, result, 0, size() ); - return result; - } - - public byte[] getGrpprl() - { - return _grpprl; - } - - public int getGrpprlOffset() - { - return _gOffset; - } - - public int getOperand() - { - switch ( getSizeCode() ) - { - case 0: - case 1: - return _grpprl[_gOffset]; - case 2: - case 4: - case 5: - return LittleEndian.getShort( _grpprl, _gOffset ); - case 3: - return LittleEndian.getInt( _grpprl, _gOffset ); - case 6: - // surely shorter than an int... - byte operandLength = _grpprl[_gOffset + 1]; - - // initialized to zeros by JVM - byte[] codeBytes = new byte[LittleEndian.INT_SIZE]; - for ( int i = 0; i < operandLength; i++ ) - if ( _gOffset + i < _grpprl.length ) - codeBytes[i] = _grpprl[_gOffset + 1 + i]; - - return LittleEndian.getInt( codeBytes, 0 ); - case 7: - byte threeByteInt[] = new byte[4]; - threeByteInt[0] = _grpprl[_gOffset]; - threeByteInt[1] = _grpprl[_gOffset + 1]; - threeByteInt[2] = _grpprl[_gOffset + 2]; - threeByteInt[3] = (byte) 0; - return LittleEndian.getInt( threeByteInt, 0 ); - default: - throw new IllegalArgumentException( - "SPRM contains an invalid size code" ); - } - } - - public short getOperandShortSigned() - { - int sizeCode = getSizeCode(); - if ( sizeCode != 2 && sizeCode != 4 && sizeCode != 5 ) - throw new UnsupportedOperationException( - "Current SPRM doesn't have signed short operand: " + this ); - - return LittleEndian.getShort( _grpprl, _gOffset ); - } - - public int getOperation() - { - return BITFIELD_OP.getValue( _value ); - } - - public int getSizeCode() - { - return BITFIELD_SIZECODE.getValue( _value ); - } - - public int getType() - { - return BITFIELD_TYPE.getValue( _value ); - } - - private int initSize( short sprm ) - { - switch ( getSizeCode() ) - { - case 0: - case 1: - return 3; - case 2: - case 4: - case 5: - return 4; - case 3: - return 6; - case 6: - int offset = _gOffset; - if ( sprm == SPRM_LONG_TABLE || sprm == SPRM_LONG_PARAGRAPH ) - { - int retVal = ( 0x0000ffff & - LittleEndian.getShort( _grpprl, offset ) ) + 3; - _gOffset += 2; - return retVal; - } - return ( 0x000000ff & _grpprl[_gOffset++] ) + 3; - case 7: - return 5; - default: - throw new IllegalArgumentException( - "SPRM contains an invalid size code" ); - } - } - - public int size() - { - return _size; - } - - @Override - public String toString() - { - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append( "[SPRM] (0x" ); - stringBuilder.append( Integer.toHexString( _value & 0xffff ) ); - stringBuilder.append( "): " ); - try - { - stringBuilder.append( getOperand() ); - } - catch ( Exception exc ) - { - stringBuilder.append( "(error)" ); - } - return stringBuilder.toString(); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/sprm/SprmUncompressor.java b/src/scratchpad/src/org/apache/poi/hwpf/sprm/SprmUncompressor.java deleted file mode 100644 index ef2e117ea..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/sprm/SprmUncompressor.java +++ /dev/null @@ -1,49 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.sprm; - -import org.apache.poi.util.Internal; - - - -@Internal -public abstract class SprmUncompressor -{ - protected SprmUncompressor() - { - } - - /** - * Converts an int into a boolean. If the int is non-zero, it returns true. - * Otherwise it returns false. - * - * @param x The int to convert. - * - * @return A boolean whose value depends on x. - */ - public static boolean getFlag (int x) - { - if (x != 0) - { - return true; - } - return false; - } - - -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/sprm/SprmUtils.java b/src/scratchpad/src/org/apache/poi/hwpf/sprm/SprmUtils.java deleted file mode 100644 index 338342788..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/sprm/SprmUtils.java +++ /dev/null @@ -1,131 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.sprm; - -import java.util.List; - -import org.apache.poi.util.Internal; -import org.apache.poi.util.LittleEndian; - - -@Internal -public final class SprmUtils -{ - public SprmUtils() - { - } - - public static byte[] shortArrayToByteArray(short[] convert) - { - byte[] buf = new byte[convert.length * LittleEndian.SHORT_SIZE]; - - for (int x = 0; x < convert.length; x++) - { - LittleEndian.putShort(buf, x * LittleEndian.SHORT_SIZE, convert[x]); - } - - return buf; - } - - public static int addSpecialSprm(short instruction, byte[] varParam, List list) - { - byte[] sprm = new byte[varParam.length + 4]; - System.arraycopy(varParam, 0, sprm, 4, varParam.length); - LittleEndian.putShort(sprm, 0, instruction); - LittleEndian.putShort(sprm, 2, (short)(varParam.length + 1)); - list.add(sprm); - return sprm.length; - } - - public static int addSprm( short instruction, boolean param, - List list ) - { - return addSprm( instruction, param ? 1 : 0, null, list ); - } - - public static int addSprm(short instruction, int param, byte[] varParam, List list) - { - int type = (instruction & 0xe000) >> 13; - - byte[] sprm = null; - switch(type) - { - case 0: - case 1: - sprm = new byte[3]; - sprm[2] = (byte)param; - break; - case 2: - sprm = new byte[4]; - LittleEndian.putShort(sprm, 2, (short)param); - break; - case 3: - sprm = new byte[6]; - LittleEndian.putInt(sprm, 2, param); - break; - case 4: - case 5: - sprm = new byte[4]; - LittleEndian.putShort(sprm, 2, (short)param); - break; - case 6: - sprm = new byte[3 + varParam.length]; - sprm[2] = (byte)varParam.length; - System.arraycopy(varParam, 0, sprm, 3, varParam.length); - break; - case 7: - sprm = new byte[5]; - // this is a three byte int so it has to be handled special - byte[] temp = new byte[4]; - LittleEndian.putInt(temp, 0, param); - System.arraycopy(temp, 0, sprm, 2, 3); - break; - default: - //should never happen - throw new RuntimeException("Invalid sprm type"); - } - LittleEndian.putShort(sprm, 0, instruction); - list.add(sprm); - return sprm.length; - } - - public static byte[] getGrpprl(List sprmList, int size) - { - // spit out the final grpprl - byte[] grpprl = new byte[size]; - int listSize = sprmList.size() - 1; - int index = 0; - for (; listSize >= 0; listSize--) - { - byte[] sprm = sprmList.remove(0); - System.arraycopy(sprm, 0, grpprl, index, sprm.length); - index += sprm.length; - } - - return grpprl; - - } - - public static int convertBrcToInt(short[] brc) - { - byte[] buf = new byte[4]; - LittleEndian.putShort(buf, 0, brc[0]); - LittleEndian.putShort(buf, LittleEndian.SHORT_SIZE, brc[1]); - return LittleEndian.getInt(buf); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/sprm/TableSprmCompressor.java b/src/scratchpad/src/org/apache/poi/hwpf/sprm/TableSprmCompressor.java deleted file mode 100644 index ec5fe937d..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/sprm/TableSprmCompressor.java +++ /dev/null @@ -1,116 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.sprm; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.apache.poi.hwpf.usermodel.BorderCode; -import org.apache.poi.hwpf.usermodel.TableAutoformatLookSpecifier; -import org.apache.poi.hwpf.usermodel.TableCellDescriptor; -import org.apache.poi.hwpf.usermodel.TableProperties; -import org.apache.poi.util.Internal; -import org.apache.poi.util.LittleEndian; - -@Internal -public final class TableSprmCompressor -{ - public TableSprmCompressor() - { - } - public static byte[] compressTableProperty(TableProperties newTAP) - { - int size = 0; - List sprmList = new ArrayList(); - - if (newTAP.getJc() != 0) - { - size += SprmUtils.addSprm((short)0x5400, newTAP.getJc(), null, sprmList); - } - if (newTAP.getFCantSplit()) - { - size += SprmUtils.addSprm((short)0x3403, 1, null, sprmList); - } - if (newTAP.getFTableHeader()) - { - size += SprmUtils.addSprm((short)0x3404, 1, null, sprmList); - } - byte[] brcBuf = new byte[6 * BorderCode.SIZE]; - int offset = 0; - newTAP.getBrcTop().serialize(brcBuf, offset); - offset += BorderCode.SIZE; - newTAP.getBrcLeft().serialize(brcBuf, offset); - offset += BorderCode.SIZE; - newTAP.getBrcBottom().serialize(brcBuf, offset); - offset += BorderCode.SIZE; - newTAP.getBrcRight().serialize(brcBuf, offset); - offset += BorderCode.SIZE; - newTAP.getBrcHorizontal().serialize(brcBuf, offset); - offset += BorderCode.SIZE; - newTAP.getBrcVertical().serialize(brcBuf, offset); - byte[] compare = new byte[6 * BorderCode.SIZE]; - if (!Arrays.equals(brcBuf, compare)) - { - size += SprmUtils.addSprm((short)0xD605, 0, brcBuf, sprmList); - } - if (newTAP.getDyaRowHeight() != 0) - { - size += SprmUtils.addSprm((short)0x9407, newTAP.getDyaRowHeight(), null, sprmList); - } - if (newTAP.getItcMac() > 0) - { - int itcMac = newTAP.getItcMac(); - byte[] buf = new byte[1 + (LittleEndian.SHORT_SIZE*(itcMac + 1)) + (TableCellDescriptor.SIZE*itcMac)]; - buf[0] = (byte)itcMac; - - short[] dxaCenters = newTAP.getRgdxaCenter(); - for (int x = 0; x < dxaCenters.length; x++) - { - LittleEndian.putShort(buf, 1 + (x * LittleEndian.SHORT_SIZE), - dxaCenters[x]); - } - - TableCellDescriptor[] cellDescriptors = newTAP.getRgtc(); - for (int x = 0; x < cellDescriptors.length; x++) - { - cellDescriptors[x].serialize(buf, - 1+((itcMac+1)*LittleEndian.SHORT_SIZE)+(x*TableCellDescriptor.SIZE)); - } - size += SprmUtils.addSpecialSprm((short)0xD608, buf, sprmList); - -// buf = new byte[(itcMac * ShadingDescriptor.SIZE) + 1]; -// buf[0] = (byte)itcMac; -// ShadingDescriptor[] shds = newTAP.getRgshd(); -// for (int x = 0; x < itcMac; x++) -// { -// shds[x].serialize(buf, 1 + (x * ShadingDescriptor.SIZE)); -// } -// size += SprmUtils.addSpecialSprm((short)0xD609, buf, sprmList); - } - - if ( newTAP.getTlp() != null && !newTAP.getTlp().isEmpty() ) - { - byte[] buf = new byte[TableAutoformatLookSpecifier.SIZE]; - newTAP.getTlp().serialize( buf, 0 ); - size += SprmUtils.addSprm( (short) 0x740a, 0, buf, sprmList ); - } - - return SprmUtils.getGrpprl(sprmList, size); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/sprm/TableSprmUncompressor.java b/src/scratchpad/src/org/apache/poi/hwpf/sprm/TableSprmUncompressor.java deleted file mode 100644 index 4bad5bb8c..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/sprm/TableSprmUncompressor.java +++ /dev/null @@ -1,319 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.sprm; - -import org.apache.poi.hwpf.usermodel.BorderCode; -import org.apache.poi.hwpf.usermodel.TableCellDescriptor; -import org.apache.poi.hwpf.usermodel.TableProperties; -import org.apache.poi.util.Internal; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; - -@Internal -public final class TableSprmUncompressor - extends SprmUncompressor -{ - private static final POILogger logger = POILogFactory.getLogger( TableSprmUncompressor.class ); - - public TableSprmUncompressor() - { - } - - public static TableProperties uncompressTAP( SprmBuffer sprmBuffer ) - { - TableProperties tableProperties; - - SprmOperation sprmOperation = sprmBuffer.findSprm( (short) 0xd608 ); - if ( sprmOperation != null ) - { - byte[] grpprl = sprmOperation.getGrpprl(); - int offset = sprmOperation.getGrpprlOffset(); - short itcMac = grpprl[offset]; - tableProperties = new TableProperties( itcMac ); - } - else - { - logger.log( POILogger.WARN, - "Some table rows didn't specify number of columns in SPRMs" ); - tableProperties = new TableProperties( (short) 1 ); - } - - for ( SprmIterator iterator = sprmBuffer.iterator(); iterator.hasNext(); ) - { - SprmOperation sprm = iterator.next(); - - /* - * TAPXs are actually PAPXs so we have to make sure we are only - * trying to uncompress the right type of sprm. - */ - if ( sprm.getType() == SprmOperation.TYPE_TAP ) - { - try - { - unCompressTAPOperation( tableProperties, sprm ); - } - catch ( ArrayIndexOutOfBoundsException ex ) - { - logger.log( POILogger.ERROR, "Unable to apply ", sprm, - ": ", ex, ex ); - } - } - } - return tableProperties; - } - - /** - * Used to uncompress a table property. Performs an operation defined - * by a sprm stored in a tapx. - * - * @param newTAP The TableProperties object to perform the operation on. - * @param operand The operand that defines this operation. - * @param param The parameter for this operation. - * @param varParam Variable length parameter for this operation. - */ - static void unCompressTAPOperation (TableProperties newTAP, SprmOperation sprm) - { - switch (sprm.getOperation()) - { - case 0: - newTAP.setJc ((short) sprm.getOperand()); - break; - case 0x01: - { - short[] rgdxaCenter = newTAP.getRgdxaCenter (); - short itcMac = newTAP.getItcMac (); - int adjust = sprm.getOperand() - (rgdxaCenter[0] + newTAP.getDxaGapHalf ()); - for (int x = 0; x < itcMac; x++) - { - rgdxaCenter[x] += adjust; - } - break; - } - case 0x02: - { - short[] rgdxaCenter = newTAP.getRgdxaCenter (); - if (rgdxaCenter != null) - { - int adjust = newTAP.getDxaGapHalf () - sprm.getOperand(); - rgdxaCenter[0] += adjust; - } - newTAP.setDxaGapHalf (sprm.getOperand()); - break; - } - case 0x03: - newTAP.setFCantSplit (getFlag(sprm.getOperand())); - break; - case 0x04: - newTAP.setFTableHeader (getFlag (sprm.getOperand())); - break; - case 0x05: - { - byte[] buf = sprm.getGrpprl(); - int offset = sprm.getGrpprlOffset(); - newTAP.setBrcTop(new BorderCode(buf, offset)); - offset += BorderCode.SIZE; - newTAP.setBrcLeft(new BorderCode(buf, offset)); - offset += BorderCode.SIZE; - newTAP.setBrcBottom(new BorderCode(buf, offset)); - offset += BorderCode.SIZE; - newTAP.setBrcRight(new BorderCode(buf, offset)); - offset += BorderCode.SIZE; - newTAP.setBrcHorizontal(new BorderCode(buf, offset)); - offset += BorderCode.SIZE; - newTAP.setBrcVertical(new BorderCode(buf, offset)); - break; - } - case 0x06: - - //obsolete, used in word 1.x - break; - case 0x07: - newTAP.setDyaRowHeight (sprm.getOperand()); - break; - case 0x08: - { - byte[] grpprl = sprm.getGrpprl(); - int offset = sprm.getGrpprlOffset(); - short itcMac = grpprl[offset]; - short[] rgdxaCenter = new short[itcMac + 1]; - TableCellDescriptor[] rgtc = new TableCellDescriptor[itcMac]; - //I use varParam[0] and newTAP._itcMac interchangably - newTAP.setItcMac (itcMac); - newTAP.setRgdxaCenter (rgdxaCenter); - newTAP.setRgtc (rgtc); - - // get the rgdxaCenters - for (int x = 0; x < itcMac; x++) - { - rgdxaCenter[x] = LittleEndian.getShort (grpprl, offset + (1 + (x * 2))); - } - - // only try to get the TC entries if they exist... - int endOfSprm = offset+sprm.size()-6; // -2 bytes for sprm - 2 for size short - 2 to correct offsets being 0 based - int startOfTCs = offset + (1 + (itcMac + 1) * 2); - - boolean hasTCs = startOfTCs < endOfSprm; - - for (int x = 0; x < itcMac; x++) - { - // Sometimes, the grpprl does not contain data at every offset. I have no idea why this happens. - if(hasTCs && offset + (1 + ( (itcMac + 1) * 2) + (x * 20)) < grpprl.length) - rgtc[x] = TableCellDescriptor.convertBytesToTC(grpprl, - offset + (1 + ( (itcMac + 1) * 2) + (x * 20))); - else - rgtc[x] = new TableCellDescriptor(); - } - - rgdxaCenter[itcMac] = LittleEndian.getShort (grpprl, offset + (1 + (itcMac * 2))); - break; - } - case 0x09: - - /** @todo handle cell shading*/ - break; - case 0x0a: - - /** @todo handle word defined table styles*/ - break; - case 0x20: -// { -// TableCellDescriptor[] rgtc = newTAP.getRgtc(); -// -// for (int x = varParam[0]; x < varParam[1]; x++) -// { -// -// if ((varParam[2] & 0x08) > 0) -// { -// short[] brcRight = rgtc[x].getBrcRight (); -// brcRight[0] = LittleEndian.getShort (varParam, 6); -// brcRight[1] = LittleEndian.getShort (varParam, 8); -// } -// else if ((varParam[2] & 0x04) > 0) -// { -// short[] brcBottom = rgtc[x].getBrcBottom (); -// brcBottom[0] = LittleEndian.getShort (varParam, 6); -// brcBottom[1] = LittleEndian.getShort (varParam, 8); -// } -// else if ((varParam[2] & 0x02) > 0) -// { -// short[] brcLeft = rgtc[x].getBrcLeft (); -// brcLeft[0] = LittleEndian.getShort (varParam, 6); -// brcLeft[1] = LittleEndian.getShort (varParam, 8); -// } -// else if ((varParam[2] & 0x01) > 0) -// { -// short[] brcTop = rgtc[x].getBrcTop (); -// brcTop[0] = LittleEndian.getShort (varParam, 6); -// brcTop[1] = LittleEndian.getShort (varParam, 8); -// } -// } -// break; -// } - break; - case 0x21: - { - int param = sprm.getOperand(); - int index = (param & 0xff000000) >> 24; - int count = (param & 0x00ff0000) >> 16; - int width = (param & 0x0000ffff); - int itcMac = newTAP.getItcMac(); - - short[] rgdxaCenter = new short[itcMac + count + 1]; - TableCellDescriptor[] rgtc = new TableCellDescriptor[itcMac + count]; - if (index >= itcMac) - { - index = itcMac; - System.arraycopy(newTAP.getRgdxaCenter(), 0, rgdxaCenter, 0, - itcMac + 1); - System.arraycopy(newTAP.getRgtc(), 0, rgtc, 0, itcMac); - } - else - { - //copy rgdxaCenter - System.arraycopy(newTAP.getRgdxaCenter(), 0, rgdxaCenter, 0, - index + 1); - System.arraycopy(newTAP.getRgdxaCenter(), index + 1, rgdxaCenter, - index + count, itcMac - (index)); - //copy rgtc - System.arraycopy(newTAP.getRgtc(), 0, rgtc, 0, index); - System.arraycopy(newTAP.getRgtc(), index, rgtc, index + count, - itcMac - index); - } - - for (int x = index; x < index + count; x++) - { - rgtc[x] = new TableCellDescriptor(); - rgdxaCenter[x] = (short)(rgdxaCenter[x - 1] + width); - } - rgdxaCenter[index + - count] = (short)(rgdxaCenter[(index + count) - 1] + width); - break; - } - /**@todo handle table sprms from complex files*/ - case 0x22: - case 0x23: - case 0x24: - case 0x25: - case 0x26: - case 0x27: - case 0x28: - case 0x29: - case 0x2a: - case 0x2b: - case 0x2c: - break; - case 0x34: - // sprmTCellPaddingDefault -- (0xd634) - // TODO: extract into CSSA structure - byte itcFirst = sprm.getGrpprl()[sprm.getGrpprlOffset()]; - byte itcLim = sprm.getGrpprl()[sprm.getGrpprlOffset() + 1]; - byte grfbrc = sprm.getGrpprl()[sprm.getGrpprlOffset() + 2]; - byte ftsWidth = sprm.getGrpprl()[sprm.getGrpprlOffset() + 3]; - short wWidth = LittleEndian.getShort(sprm.getGrpprl(), - sprm.getGrpprlOffset() + 4); - - for (int c = itcFirst; c < itcLim; c++) { - TableCellDescriptor tableCellDescriptor = newTAP.getRgtc()[c]; - - if ((grfbrc & 0x01) != 0) { - tableCellDescriptor.setFtsCellPaddingTop(ftsWidth); - tableCellDescriptor.setWCellPaddingTop(wWidth); - } - if ((grfbrc & 0x02) != 0) { - tableCellDescriptor.setFtsCellPaddingLeft(ftsWidth); - tableCellDescriptor.setWCellPaddingLeft(wWidth); - } - if ((grfbrc & 0x04) != 0) { - tableCellDescriptor.setFtsCellPaddingBottom(ftsWidth); - tableCellDescriptor.setWCellPaddingBottom(wWidth); - } - if ((grfbrc & 0x08) != 0) { - tableCellDescriptor.setFtsCellPaddingRight(ftsWidth); - tableCellDescriptor.setWCellPaddingRight(wWidth); - } - } - break; - default: - break; - } - } - - - -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/Bookmark.java b/src/scratchpad/src/org/apache/poi/hwpf/usermodel/Bookmark.java deleted file mode 100644 index 1836d8906..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/Bookmark.java +++ /dev/null @@ -1,33 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hwpf.usermodel; - -/** - * User friendly interface to access information about document bookmarks - * - * @author Sergey Vladimirov (vlsergey {at} gmail {doc} com) - */ -public interface Bookmark -{ - int getEnd(); - - String getName(); - - int getStart(); - - void setName( String name ); -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/Bookmarks.java b/src/scratchpad/src/org/apache/poi/hwpf/usermodel/Bookmarks.java deleted file mode 100644 index c4dae5e9d..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/Bookmarks.java +++ /dev/null @@ -1,58 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hwpf.usermodel; - -import java.util.List; -import java.util.Map; - -/** - * User-friendly interface to access document bookmarks - * - * @author Sergey Vladimirov (vlsergey {at} gmail {dot} com) - */ -public interface Bookmarks -{ - /** - * @param index - * bookmark document index - * @return {@link Bookmark} with specified index - * @throws IndexOutOfBoundsException - * if bookmark with specified index not present in document - */ - Bookmark getBookmark( int index ) throws IndexOutOfBoundsException; - - /** - * @return count of {@link Bookmark}s in document - */ - int getBookmarksCount(); - - /** - * @return {@link Map} of bookmarks started in specified range, where key is - * start position and value is sorted {@link List} of - * {@link Bookmark} - */ - Map> getBookmarksStartedBetween( - int startInclusive, int endExclusive ); - - /** - * Remove bookmark from document (but not the bookmark text) - * - * @param index - * bookmark document index to be removed - */ - void remove( int index ); -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/BookmarksImpl.java b/src/scratchpad/src/org/apache/poi/hwpf/usermodel/BookmarksImpl.java deleted file mode 100644 index ce4df164b..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/BookmarksImpl.java +++ /dev/null @@ -1,259 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hwpf.usermodel; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -import org.apache.poi.hwpf.model.BookmarksTables; -import org.apache.poi.hwpf.model.GenericPropertyNode; -import org.apache.poi.hwpf.model.PropertyNode; - -/** - * Implementation of user-friendly interface for document bookmarks - * - * @author Sergey Vladimirov (vlsergey {at} gmail {doc} com) - */ -public class BookmarksImpl implements Bookmarks -{ - - private final class BookmarkImpl implements Bookmark - { - private final GenericPropertyNode first; - - private BookmarkImpl( GenericPropertyNode first ) - { - this.first = first; - } - - @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - return true; - if ( obj == null ) - return false; - if ( getClass() != obj.getClass() ) - return false; - BookmarkImpl other = (BookmarkImpl) obj; - if ( first == null ) - { - if ( other.first != null ) - return false; - } - else if ( !first.equals( other.first ) ) - return false; - return true; - } - - public int getEnd() - { - int currentIndex = bookmarksTables.getDescriptorFirstIndex( first ); - try - { - GenericPropertyNode descriptorLim = bookmarksTables - .getDescriptorLim( currentIndex ); - return descriptorLim.getStart(); - } - catch ( IndexOutOfBoundsException exc ) - { - return first.getEnd(); - } - } - - public String getName() - { - int currentIndex = bookmarksTables.getDescriptorFirstIndex( first ); - try - { - return bookmarksTables.getName( currentIndex ); - } - catch ( ArrayIndexOutOfBoundsException exc ) - { - return ""; - } - } - - public int getStart() - { - return first.getStart(); - } - - @Override - public int hashCode() - { - return 31 + ( first == null ? 0 : first.hashCode() ); - } - - public void setName( String name ) - { - int currentIndex = bookmarksTables.getDescriptorFirstIndex( first ); - bookmarksTables.setName( currentIndex, name ); - } - - @Override - public String toString() - { - return "Bookmark [" + getStart() + "; " + getEnd() + "): name: " - + getName(); - } - - } - - private final BookmarksTables bookmarksTables; - - private Map> sortedDescriptors = null; - - private int[] sortedStartPositions = null; - - public BookmarksImpl( BookmarksTables bookmarksTables ) - { - this.bookmarksTables = bookmarksTables; - reset(); - } - - void afterDelete( int startCp, int length ) - { - bookmarksTables.afterDelete( startCp, length ); - reset(); - } - - void afterInsert( int startCp, int length ) - { - bookmarksTables.afterInsert( startCp, length ); - reset(); - } - - private Bookmark getBookmark( final GenericPropertyNode first ) - { - return new BookmarkImpl( first ); - } - - public Bookmark getBookmark( int index ) - { - final GenericPropertyNode first = bookmarksTables - .getDescriptorFirst( index ); - return getBookmark( first ); - } - - public List getBookmarksAt( int startCp ) - { - updateSortedDescriptors(); - - List nodes = sortedDescriptors.get( Integer - .valueOf( startCp ) ); - if ( nodes == null || nodes.isEmpty() ) - return Collections.emptyList(); - - List result = new ArrayList( nodes.size() ); - for ( GenericPropertyNode node : nodes ) - { - result.add( getBookmark( node ) ); - } - return Collections.unmodifiableList( result ); - } - - public int getBookmarksCount() - { - return bookmarksTables.getDescriptorsFirstCount(); - } - - public Map> getBookmarksStartedBetween( - int startInclusive, int endExclusive ) - { - updateSortedDescriptors(); - - int startLookupIndex = Arrays.binarySearch( this.sortedStartPositions, - startInclusive ); - if ( startLookupIndex < 0 ) - startLookupIndex = -( startLookupIndex + 1 ); - int endLookupIndex = Arrays.binarySearch( this.sortedStartPositions, - endExclusive ); - if ( endLookupIndex < 0 ) - endLookupIndex = -( endLookupIndex + 1 ); - - Map> result = new LinkedHashMap>(); - for ( int lookupIndex = startLookupIndex; lookupIndex < endLookupIndex; lookupIndex++ ) - { - int s = sortedStartPositions[lookupIndex]; - if ( s < startInclusive ) - continue; - if ( s >= endExclusive ) - break; - - List startedAt = getBookmarksAt( s ); - if ( startedAt != null ) - result.put( Integer.valueOf( s ), startedAt ); - } - - return Collections.unmodifiableMap( result ); - } - - public void remove( int index ) - { - bookmarksTables.remove( index ); - } - - private void reset() - { - sortedDescriptors = null; - sortedStartPositions = null; - } - - private void updateSortedDescriptors() - { - if ( sortedDescriptors != null ) - return; - - Map> result = new HashMap>(); - for ( int b = 0; b < bookmarksTables.getDescriptorsFirstCount(); b++ ) - { - GenericPropertyNode property = bookmarksTables - .getDescriptorFirst( b ); - Integer positionKey = Integer.valueOf( property.getStart() ); - List atPositionList = result.get( positionKey ); - if ( atPositionList == null ) - { - atPositionList = new LinkedList(); - result.put( positionKey, atPositionList ); - } - atPositionList.add( property ); - } - - int counter = 0; - int[] indices = new int[result.size()]; - for ( Map.Entry> entry : result - .entrySet() ) - { - indices[counter++] = entry.getKey().intValue(); - List updated = new ArrayList( - entry.getValue() ); - Collections.sort( updated, PropertyNode.EndComparator.instance ); - entry.setValue( updated ); - } - Arrays.sort( indices ); - - this.sortedDescriptors = result; - this.sortedStartPositions = indices; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/BorderCode.java b/src/scratchpad/src/org/apache/poi/hwpf/usermodel/BorderCode.java deleted file mode 100644 index 0f5a94995..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/BorderCode.java +++ /dev/null @@ -1,243 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.usermodel; - -import org.apache.poi.util.BitField; -import org.apache.poi.util.BitFieldFactory; -import org.apache.poi.util.LittleEndian; - -/** - * Mapping class for BRC80 structure (Border Code for Word 97) - * - *

    Comments are copied out from the binary format specification. - */ -public final class BorderCode implements Cloneable { - - public static final int SIZE = 4; - - private short _info; - private static final BitField _dptLineWidth = BitFieldFactory.getInstance(0x00ff); - private static final BitField _brcType = BitFieldFactory.getInstance(0xff00); - - private short _info2; - private static final BitField _ico = BitFieldFactory.getInstance(0x00ff); - private static final BitField _dptSpace = BitFieldFactory.getInstance(0x1f00); - private static final BitField _fShadow = BitFieldFactory.getInstance(0x2000); - private static final BitField _fFrame = BitFieldFactory.getInstance(0x4000); - - public BorderCode() - { - } - - public BorderCode(byte[] buf, int offset) - { - _info = LittleEndian.getShort(buf, offset); - _info2 = LittleEndian.getShort(buf, offset + LittleEndian.SHORT_SIZE); - } - - public void serialize(byte[] buf, int offset) - { - LittleEndian.putShort(buf, offset, _info); - LittleEndian.putShort(buf, offset + LittleEndian.SHORT_SIZE, _info2); - } - - public int toInt() - { - byte[] buf = new byte[4]; - serialize(buf, 0); - return LittleEndian.getInt(buf); - } - - public boolean isEmpty() - { - return _info == 0 && _info2 == 0 || _info == -1; - } - - @Override - public boolean equals(Object o) - { - if (!(o instanceof BorderCode)) return false; - BorderCode brc = (BorderCode)o; - return _info == brc._info && _info2 == brc._info2; - } - - @Override - public int hashCode() { - assert false : "hashCode not designed"; - return 42; // any arbitrary constant will do - } - - public Object clone() - throws CloneNotSupportedException - { - return super.clone(); - } - - /** - * Width of a single line in 1/8 pt, max of 32 pt. - */ - public int getLineWidth() { - return _dptLineWidth.getShortValue(_info); - } - - /** - * @param lineWidth the width of the line to set - */ - public void setLineWidth(int lineWidth) { - _info = _dptLineWidth.setShortValue(_info, (short)lineWidth); - } - - /** - * Border type code: - *

      - *
    • 0 none
    • - *
    • 1 single
    • - *
    • 2 thick
    • - *
    • 3 double
    • - *
    • 5 hairline
    • - *
    • 6 dot
    • - *
    • 7 dash large gap
    • - *
    • 8 dot dash
    • - *
    • 9 dot dot dash
    • - *
    • 10 triple
    • - *
    • 11 thin-thick small gap
    • - *
    • 12 thick-thin small gap
    • - *
    • 13 thin-thick-thin small gap
    • - *
    • 14 thin-thick medium gap
    • - *
    • 15 thick-thin medium gap
    • - *
    • 16 thin-thick-thin medium gap
    • - *
    • 17 thin-thick large gap
    • - *
    • 18 thick-thin large gap
    • - *
    • 19 thin-thick-thin large gap
    • - *
    • 20 wave
    • - *
    • 21 double wave
    • - *
    • 22 dash small gap
    • - *
    • 23 dash dot stroked
    • - *
    • 24 emboss 3D
    • - *
    • 25 engrave 3D
    • - *
    • codes 64 - 230 represent border art types and are used only for page borders
    • - *
    - */ - public int getBorderType() { - return _brcType.getShortValue(_info); - } - - public void setBorderType(int borderType) { - _info = _brcType.setShortValue(_info, (short)borderType); - } - - /** - * Color: - *
      - *
    • 0 Auto
    • - *
    • 1 Black
    • - *
    • 2 Blue
    • - *
    • 3 Cyan
    • - *
    • 4 Green
    • - *
    • 5 Magenta
    • - *
    • 6 Red
    • - *
    • 7 Yellow
    • - *
    • 8 White
    • - *
    • 9 DkBlue
    • - *
    • 10 DkCyan
    • - *
    • 11 DkGreen
    • - *
    • 12 DkMagenta
    • - *
    • 13 DkRed
    • - *
    • 14 DkYellow
    • - *
    • 15 DkGray
    • - *
    • 16 LtGray
    • - *
    - */ - public short getColor() { - return _ico.getShortValue(_info2); - } - - public void setColor(short color) { - _info2 = _ico.setShortValue(_info2, color); - } - - /** - * Width of space to maintain between border and text within border. - * - *

    Must be 0 when BRC is a substructure of TC. - * - *

    Stored in points. - */ - public int getSpace() { - return _dptSpace.getShortValue(_info2); - } - - public void setSpace(int space) { - _info2 = (short)_dptSpace.setValue(_info2, space); - } - - /** - * When true, border is drawn with shadow - * Must be false when BRC is a substructure of the TC. - */ - public boolean isShadow() { - return _fShadow.getValue(_info2) != 0; - } - - public void setShadow(boolean shadow) { - _info2 = (short)_fShadow.setValue(_info2, shadow ? 1 : 0); - } - - /** - * Don't reverse the border. - */ - public boolean isFrame() { - return _fFrame.getValue(_info2) != 0; - } - - public void setFrame(boolean frame) { - _info2 = (short)_fFrame.setValue(_info2, frame ? 1 : 0); - } - - @Override - public String toString() - { - if ( isEmpty() ) - return "[BRC] EMPTY"; - - StringBuffer buffer = new StringBuffer(); - - buffer.append( "[BRC]\n" ); - - buffer.append( " .dptLineWidth = " ); - buffer.append( " (" ).append( getLineWidth() ).append( " )\n" ); - - buffer.append( " .brcType = " ); - buffer.append( " (" ).append( getBorderType() ).append( " )\n" ); - - buffer.append( " .ico = " ); - buffer.append( " (" ).append( getColor() ).append( " )\n" ); - - buffer.append( " .dptSpace = " ); - buffer.append( " (" ).append( getSpace() ).append( " )\n" ); - - buffer.append( " .fShadow = " ); - buffer.append( " (" ).append( isShadow() ).append( " )\n" ); - - buffer.append( " .fFrame = " ); - buffer.append( " (" ).append( isFrame() ).append( " )\n" ); - - return buffer.toString(); - } - -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/CharacterProperties.java b/src/scratchpad/src/org/apache/poi/hwpf/usermodel/CharacterProperties.java deleted file mode 100644 index 3c5e25fb6..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/CharacterProperties.java +++ /dev/null @@ -1,396 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.usermodel; - -import org.apache.poi.hwpf.model.Colorref; -import org.apache.poi.hwpf.model.types.CHPAbstractType; - -/** - * @author Ryan Ackley - */ -public final class CharacterProperties - extends CHPAbstractType implements Cloneable -{ - public final static short SPRM_FRMARKDEL = (short)0x0800; - public final static short SPRM_FRMARK = 0x0801; - public final static short SPRM_FFLDVANISH = 0x0802; - public final static short SPRM_PICLOCATION = 0x6A03; - public final static short SPRM_IBSTRMARK = 0x4804; - public final static short SPRM_DTTMRMARK = 0x6805; - public final static short SPRM_FDATA = 0x0806; - public final static short SPRM_SYMBOL = 0x6A09; - public final static short SPRM_FOLE2 = 0x080A; - public final static short SPRM_HIGHLIGHT = 0x2A0C; - public final static short SPRM_OBJLOCATION = 0x680E; - public final static short SPRM_ISTD = 0x4A30; - public final static short SPRM_FBOLD = 0x0835; - public final static short SPRM_FITALIC = 0x0836; - public final static short SPRM_FSTRIKE = 0x0837; - public final static short SPRM_FOUTLINE = 0x0838; - public final static short SPRM_FSHADOW = 0x0839; - public final static short SPRM_FSMALLCAPS = 0x083A; - public final static short SPRM_FCAPS = 0x083B; - public final static short SPRM_FVANISH = 0x083C; - public final static short SPRM_KUL = 0x2A3E; - public final static short SPRM_DXASPACE = (short)0x8840; - public final static short SPRM_LID = 0x4A41; - public final static short SPRM_ICO = 0x2A42; - public final static short SPRM_HPS = 0x4A43; - public final static short SPRM_HPSPOS = 0x4845; - public final static short SPRM_ISS = 0x2A48; - public final static short SPRM_HPSKERN = 0x484B; - public final static short SPRM_YSRI = 0x484E; - public final static short SPRM_RGFTCASCII = 0x4A4F; - public final static short SPRM_RGFTCFAREAST = 0x4A50; - public final static short SPRM_RGFTCNOTFAREAST = 0x4A51; - public final static short SPRM_CHARSCALE = 0x4852; - public final static short SPRM_FDSTRIKE = 0x2A53; - public final static short SPRM_FIMPRINT = 0x0854; - public final static short SPRM_FSPEC = 0x0855; - public final static short SPRM_FOBJ = 0x0856; - public final static short SPRM_PROPRMARK = (short)0xCA57; - public final static short SPRM_FEMBOSS = 0x0858; - public final static short SPRM_SFXTEXT = 0x2859; - /* - * Microsoft Office Word 97-2007 Binary File Format (.doc) Specification; - * Page 60 of 210 - */ - public final static short SPRM_DISPFLDRMARK = (short)0xCA62; - public final static short SPRM_IBSTRMARKDEL = 0x4863; - public final static short SPRM_DTTMRMARKDEL = 0x6864; - public final static short SPRM_BRC = 0x6865; - public final static short SPRM_SHD = 0x4866; - public final static short SPRM_IDSIRMARKDEL = 0x4867; - public final static short SPRM_CPG = 0x486B; - public final static short SPRM_NONFELID = 0x486D; - public final static short SPRM_FELID = 0x486E; - public final static short SPRM_IDCTHINT = 0x286F; - /** - * change chp.cv - */ - public final static short SPRM_CCV = 0x6870; - - public CharacterProperties() - { - setFUsePgsuSettings( true ); - setXstDispFldRMark( new byte[36] ); - } - - public boolean isMarkedDeleted() - { - return isFRMarkDel(); - } - - public void markDeleted(boolean mark) - { - super.setFRMarkDel(mark); - } - - public boolean isBold() - { - return isFBold(); - } - - public void setBold(boolean bold) - { - super.setFBold(bold); - } - - public boolean isItalic() - { - return isFItalic(); - } - - public void setItalic(boolean italic) - { - super.setFItalic(italic); - } - - public boolean isOutlined() - { - return isFOutline(); - } - - public void setOutline(boolean outlined) - { - super.setFOutline(outlined); - } - - public boolean isFldVanished() - { - return isFFldVanish(); - } - - public void setFldVanish(boolean fldVanish) - { - super.setFFldVanish(fldVanish); - } - - public boolean isSmallCaps() - { - return isFSmallCaps(); - } - - public void setSmallCaps(boolean smallCaps) - { - super.setFSmallCaps(smallCaps); - } - - public boolean isCapitalized() - { - return isFCaps(); - } - - public void setCapitalized(boolean caps) - { - super.setFCaps(caps); - } - - public boolean isVanished() - { - return isFVanish(); - } - - public void setVanished(boolean vanish) - { - super.setFVanish(vanish); - - } - public boolean isMarkedInserted() - { - return isFRMark(); - } - - public void markInserted(boolean mark) - { - super.setFRMark(mark); - } - - public boolean isStrikeThrough() - { - return isFStrike(); - } - - public void strikeThrough(boolean strike) - { - super.setFStrike(strike); - } - - public boolean isShadowed() - { - return isFShadow(); - } - - public void setShadow(boolean shadow) - { - super.setFShadow(shadow); - - } - - public boolean isEmbossed() - { - return isFEmboss(); - } - - public void setEmbossed(boolean emboss) - { - super.setFEmboss(emboss); - } - - public boolean isImprinted() - { - return isFImprint(); - } - - public void setImprinted(boolean imprint) - { - super.setFImprint(imprint); - } - - public boolean isDoubleStrikeThrough() - { - return isFDStrike(); - } - - public void setDoubleStrikeThrough(boolean dstrike) - { - super.setFDStrike(dstrike); - } - - public int getFontSize() - { - return getHps(); - } - - public void setFontSize(int halfPoints) - { - super.setHps(halfPoints); - } - - public int getCharacterSpacing() - { - return getDxaSpace(); - } - - public void setCharacterSpacing(int twips) - { - super.setDxaSpace(twips); - } - - public short getSubSuperScriptIndex() - { - return getIss(); - } - - public void setSubSuperScriptIndex(short iss) - { - super.setDxaSpace(iss); - } - - public int getUnderlineCode() - { - return super.getKul(); - } - - public void setUnderlineCode(int kul) - { - super.setKul((byte)kul); - } - - public int getColor() - { - return super.getIco(); - } - - public void setColor(int color) - { - super.setIco((byte)color); - } - - public int getVerticalOffset() - { - return super.getHpsPos(); - } - - public void setVerticalOffset(int hpsPos) - { - super.setHpsPos((short) hpsPos); - } - - public int getKerning() - { - return super.getHpsKern(); - } - - public void setKerning(int kern) - { - super.setHpsKern(kern); - } - - public boolean isHighlighted() - { - return super.isFHighlight(); - } - - public void setHighlighted(byte color) - { - super.setIcoHighlight(color); - } - - /** - * Get the ico24 field for the CHP record. - */ - public int getIco24() - { - if ( !getCv().isEmpty() ) - return getCv().getValue(); - - // convert word 97 colour numbers to 0xBBRRGGRR value - switch ( getIco() ) - { - case 0: // auto - return -1; - case 1: // black - return 0x00000000; - case 2: // blue - return 0x00FF0000; - case 3: // cyan - return 0x00FFFF00; - case 4: // green - return 0x0000FF00; - case 5: // magenta - return 0x00FF00FF; - case 6: // red - return 0x000000FF; - case 7: // yellow - return 0x0000FFFF; - case 8: // white - return 0x00FFFFFF; - case 9: // dark blue - return 0x00800000; - case 10: // dark cyan - return 0x00808000; - case 11: // dark green - return 0x00008000; - case 12: // dark magenta - return 0x00800080; - case 13: // dark red - return 0x00000080; - case 14: // dark yellow - return 0x00008080; - case 15: // dark grey - return 0x00808080; - case 16: // light grey - return 0x00C0C0C0; - } - - return -1; - } - - /** - * Set the ico24 field for the CHP record. - */ - public void setIco24( int colour24 ) - { - setCv( new Colorref( colour24 & 0xFFFFFF ) ); - } - - public CharacterProperties clone() - { - try - { - CharacterProperties cp = (CharacterProperties) super.clone(); - - cp.setCv( getCv().clone() ); - cp.setDttmRMark( (DateAndTime) getDttmRMark().clone() ); - cp.setDttmRMarkDel( (DateAndTime) getDttmRMarkDel().clone() ); - cp.setDttmPropRMark( (DateAndTime) getDttmPropRMark().clone() ); - cp.setDttmDispFldRMark( (DateAndTime) getDttmDispFldRMark().clone() ); - cp.setXstDispFldRMark( getXstDispFldRMark().clone() ); - cp.setShd( getShd().clone() ); - cp.setBrc( (BorderCode) getBrc().clone() ); - - return cp; - } - catch ( CloneNotSupportedException exc ) - { - throw new UnsupportedOperationException( - "Impossible CloneNotSupportedException occured", exc ); - } - } -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/CharacterRun.java b/src/scratchpad/src/org/apache/poi/hwpf/usermodel/CharacterRun.java deleted file mode 100644 index 5c2dc4749..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/CharacterRun.java +++ /dev/null @@ -1,685 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.usermodel; - -import org.apache.poi.hwpf.HWPFDocument; -import org.apache.poi.hwpf.HWPFOldDocument; -import org.apache.poi.hwpf.model.CHPX; -import org.apache.poi.hwpf.model.FFData; -import org.apache.poi.hwpf.model.Ffn; -import org.apache.poi.hwpf.model.NilPICFAndBinData; -import org.apache.poi.hwpf.model.StyleSheet; -import org.apache.poi.hwpf.sprm.SprmBuffer; - -/** - * This class represents a run of text that share common properties. - */ -public final class CharacterRun extends Range - implements Cloneable, org.apache.poi.wp.usermodel.CharacterRun -{ - public final static short SPRM_FRMARKDEL = (short)0x0800; - public final static short SPRM_FRMARK = 0x0801; - public final static short SPRM_FFLDVANISH = 0x0802; - public final static short SPRM_PICLOCATION = 0x6A03; - public final static short SPRM_IBSTRMARK = 0x4804; - public final static short SPRM_DTTMRMARK = 0x6805; - public final static short SPRM_FDATA = 0x0806; - public final static short SPRM_SYMBOL = 0x6A09; - public final static short SPRM_FOLE2 = 0x080A; - public final static short SPRM_HIGHLIGHT = 0x2A0C; - public final static short SPRM_OBJLOCATION = 0x680E; - public final static short SPRM_ISTD = 0x4A30; - public final static short SPRM_FBOLD = 0x0835; - public final static short SPRM_FITALIC = 0x0836; - public final static short SPRM_FSTRIKE = 0x0837; - public final static short SPRM_FOUTLINE = 0x0838; - public final static short SPRM_FSHADOW = 0x0839; - public final static short SPRM_FSMALLCAPS = 0x083A; - public final static short SPRM_FCAPS = 0x083B; - public final static short SPRM_FVANISH = 0x083C; - public final static short SPRM_KUL = 0x2A3E; - public final static short SPRM_DXASPACE = (short)0x8840; - public final static short SPRM_LID = 0x4A41; - public final static short SPRM_ICO = 0x2A42; - public final static short SPRM_HPS = 0x4A43; - public final static short SPRM_HPSPOS = 0x4845; - public final static short SPRM_ISS = 0x2A48; - public final static short SPRM_HPSKERN = 0x484B; - public final static short SPRM_YSRI = 0x484E; - public final static short SPRM_RGFTCASCII = 0x4A4F; - public final static short SPRM_RGFTCFAREAST = 0x4A50; - public final static short SPRM_RGFTCNOTFAREAST = 0x4A51; - public final static short SPRM_CHARSCALE = 0x4852; - public final static short SPRM_FDSTRIKE = 0x2A53; - public final static short SPRM_FIMPRINT = 0x0854; - public final static short SPRM_FSPEC = 0x0855; - public final static short SPRM_FOBJ = 0x0856; - public final static short SPRM_PROPRMARK = (short)0xCA57; - public final static short SPRM_FEMBOSS = 0x0858; - public final static short SPRM_SFXTEXT = 0x2859; - public final static short SPRM_DISPFLDRMARK = (short)0xCA62; - public final static short SPRM_IBSTRMARKDEL = 0x4863; - public final static short SPRM_DTTMRMARKDEL = 0x6864; - public final static short SPRM_BRC = 0x6865; - public final static short SPRM_SHD = 0x4866; - public final static short SPRM_IDSIRMARKDEL = 0x4867; - public final static short SPRM_CPG = 0x486B; - public final static short SPRM_NONFELID = 0x486D; - public final static short SPRM_FELID = 0x486E; - public final static short SPRM_IDCTHINT = 0x286F; - - protected short _istd; - protected SprmBuffer _chpx; - protected CharacterProperties _props; - - /** - * - * @param chpx The chpx this object is based on. - * @param ss The stylesheet for the document this run belongs to. - * @param istd The style index if this run's base style. - * @param parent The parent range of this character run (usually a paragraph). - */ - CharacterRun(CHPX chpx, StyleSheet ss, short istd, Range parent) - { - super(Math.max(parent._start, chpx.getStart()), Math.min(parent._end, chpx.getEnd()), parent); - _props = chpx.getCharacterProperties(ss, istd); - _chpx = chpx.getSprmBuf(); - _istd = istd; - } - - /** - * Here for runtime type determination using a switch statement convenient. - * - * @return TYPE_CHARACTER - */ - @SuppressWarnings("deprecation") - public int type() - { - return TYPE_CHARACTER; - } - - public boolean isMarkedDeleted() - { - return _props.isFRMarkDel(); - } - - public void markDeleted(boolean mark) - { - _props.setFRMarkDel(mark); - - byte newVal = (byte)(mark ? 1 : 0); - _chpx.updateSprm(SPRM_FRMARKDEL, newVal); - - } - - public boolean isBold() - { - return _props.isFBold(); - } - - public void setBold(boolean bold) - { - _props.setFBold(bold); - - byte newVal = (byte)(bold ? 1 : 0); - _chpx.updateSprm(SPRM_FBOLD, newVal); - - } - - public boolean isItalic() - { - return _props.isFItalic(); - } - - public void setItalic(boolean italic) - { - _props.setFItalic(italic); - - byte newVal = (byte)(italic ? 1 : 0); - _chpx.updateSprm(SPRM_FITALIC, newVal); - - } - - public boolean isOutlined() - { - return _props.isFOutline(); - } - - public void setOutline(boolean outlined) - { - _props.setFOutline(outlined); - - byte newVal = (byte)(outlined ? 1 : 0); - _chpx.updateSprm(SPRM_FOUTLINE, newVal); - - } - - public boolean isFldVanished() - { - return _props.isFFldVanish(); - } - - public void setFldVanish(boolean fldVanish) - { - _props.setFFldVanish(fldVanish); - - byte newVal = (byte)(fldVanish ? 1 : 0); - _chpx.updateSprm(SPRM_FFLDVANISH, newVal); - - } - - public boolean isSmallCaps() - { - return _props.isFSmallCaps(); - } - - public void setSmallCaps(boolean smallCaps) - { - _props.setFSmallCaps(smallCaps); - - byte newVal = (byte)(smallCaps ? 1 : 0); - _chpx.updateSprm(SPRM_FSMALLCAPS, newVal); - - } - - public boolean isCapitalized() - { - return _props.isFCaps(); - } - - public void setCapitalized(boolean caps) - { - _props.setFCaps(caps); - - byte newVal = (byte)(caps ? 1 : 0); - _chpx.updateSprm(SPRM_FCAPS, newVal); - - } - - public boolean isVanished() - { - return _props.isFVanish(); - } - - public void setVanished(boolean vanish) - { - _props.setFVanish(vanish); - - byte newVal = (byte)(vanish ? 1 : 0); - _chpx.updateSprm(SPRM_FVANISH, newVal); - - } - - public boolean isMarkedInserted() - { - return _props.isFRMark(); - } - - public void markInserted(boolean mark) - { - _props.setFRMark(mark); - - byte newVal = (byte)(mark ? 1 : 0); - _chpx.updateSprm(SPRM_FRMARK, newVal); - - } - - public boolean isStrikeThrough() - { - return _props.isFStrike(); - } - - public void setStrikeThrough(boolean strike) - { - strikeThrough(strike); - } - public void strikeThrough(boolean strike) - { - _props.setFStrike(strike); - - byte newVal = (byte)(strike ? 1 : 0); - _chpx.updateSprm(SPRM_FSTRIKE, newVal); - - } - - public boolean isShadowed() - { - return _props.isFShadow(); - } - - public void setShadow(boolean shadow) - { - _props.setFShadow(shadow); - - byte newVal = (byte)(shadow ? 1 : 0); - _chpx.updateSprm(SPRM_FSHADOW, newVal); - - } - - public boolean isEmbossed() - { - return _props.isFEmboss(); - } - - public void setEmbossed(boolean emboss) - { - _props.setFEmboss(emboss); - - byte newVal = (byte)(emboss ? 1 : 0); - _chpx.updateSprm(SPRM_FEMBOSS, newVal); - - } - - public boolean isImprinted() - { - return _props.isFImprint(); - } - - public void setImprinted(boolean imprint) - { - _props.setFImprint(imprint); - - byte newVal = (byte)(imprint ? 1 : 0); - _chpx.updateSprm(SPRM_FIMPRINT, newVal); - - } - - public boolean isDoubleStrikeThrough() - { - return _props.isFDStrike(); - } - - public void setDoubleStrikethrough(boolean dstrike) - { - _props.setFDStrike(dstrike); - - byte newVal = (byte)(dstrike ? 1 : 0); - _chpx.updateSprm(SPRM_FDSTRIKE, newVal); - - } - - public void setFtcAscii(int ftcAscii) - { - _props.setFtcAscii(ftcAscii); - - _chpx.updateSprm(SPRM_RGFTCASCII, (short)ftcAscii); - - } - - public void setFtcFE(int ftcFE) - { - _props.setFtcFE(ftcFE); - - _chpx.updateSprm(SPRM_RGFTCFAREAST, (short)ftcFE); - - } - - public void setFtcOther(int ftcOther) - { - _props.setFtcOther(ftcOther); - - _chpx.updateSprm(SPRM_RGFTCNOTFAREAST, (short)ftcOther); - - } - - public int getFontSize() - { - return _props.getHps(); - } - - public void setFontSize(int halfPoints) - { - _props.setHps(halfPoints); - - _chpx.updateSprm(SPRM_HPS, (short)halfPoints); - - } - - public int getCharacterSpacing() - { - return _props.getDxaSpace(); - } - - public void setCharacterSpacing(int twips) - { - _props.setDxaSpace(twips); - - _chpx.updateSprm(SPRM_DXASPACE, twips); - - } - - public short getSubSuperScriptIndex() - { - return _props.getIss(); - } - - public void setSubSuperScriptIndex(short iss) - { - _props.setDxaSpace(iss); - - _chpx.updateSprm(SPRM_DXASPACE, iss); - - } - - public int getUnderlineCode() - { - return _props.getKul(); - } - - public void setUnderlineCode(int kul) - { - _props.setKul((byte)kul); - _chpx.updateSprm(SPRM_KUL, (byte)kul); - } - - public int getColor() - { - return _props.getIco(); - } - - public void setColor(int color) - { - _props.setIco((byte)color); - _chpx.updateSprm(SPRM_ICO, (byte)color); - } - - public int getVerticalOffset() - { - return _props.getHpsPos(); - } - - public void setVerticalOffset(int hpsPos) - { - _props.setHpsPos((short) hpsPos); - _chpx.updateSprm(SPRM_HPSPOS, (byte)hpsPos); - } - - public int getKerning() - { - return _props.getHpsKern(); - } - - public void setKerning(int kern) - { - _props.setHpsKern(kern); - _chpx.updateSprm(SPRM_HPSKERN, (short)kern); - } - - public boolean isHighlighted() - { - return _props.isFHighlight(); - } - - public byte getHighlightedColor() - { - return _props.getIcoHighlight(); - } - - public void setHighlighted(byte color) - { - _props.setFHighlight(true); - _props.setIcoHighlight(color); - _chpx.updateSprm(SPRM_HIGHLIGHT, color); - } - - public String getFontName() - { - if (_doc instanceof HWPFOldDocument) { - return ((HWPFOldDocument) _doc).getOldFontTable().getMainFont(_props.getFtcAscii()); - } - - if (_doc.getFontTable() == null) - // old word format - return null; - - return _doc.getFontTable().getMainFont(_props.getFtcAscii()); - } - - public boolean isSpecialCharacter() - { - return _props.isFSpec(); - } - - public void setSpecialCharacter(boolean spec) - { - _props.setFSpec(spec); - - byte newVal = (byte)(spec ? 1 : 0); - _chpx.updateSprm(SPRM_FSPEC, newVal); - } - - public boolean isObj() - { - return _props.isFObj(); - } - - public void setObj(boolean obj) - { - _props.setFObj(obj); - - byte newVal = (byte)(obj ? 1 : 0); - _chpx.updateSprm(SPRM_FOBJ, newVal); - } - - public int getPicOffset() - { - return _props.getFcPic(); - } - - public void setPicOffset(int offset) - { - _props.setFcPic(offset); - _chpx.updateSprm(SPRM_PICLOCATION, offset); - } - - /** - * Does the picture offset represent picture - * or binary data? - * If it's set, then the picture offset refers to - * a NilPICFAndBinData structure, otherwise to a - * PICFAndOfficeArtData - */ - public boolean isData() - { - return _props.isFData(); - } - - public void setData(boolean data) - { - _props.setFData(data); - - byte newVal = (byte)(data ? 1 : 0); - _chpx.updateSprm(SPRM_FOBJ, newVal); - } - - public boolean isOle2() - { - return _props.isFOle2(); - } - - public void setOle2(boolean ole) - { - _props.setFOle2(ole); - - byte newVal = (byte)(ole ? 1 : 0); - _chpx.updateSprm(SPRM_FOBJ, newVal); - } - - public int getObjOffset() - { - return _props.getFcObj(); - } - - public void setObjOffset(int obj) - { - _props.setFcObj(obj); - _chpx.updateSprm(SPRM_OBJLOCATION, obj); - } - - /** - * Get the ico24 field for the CHP record. - */ - public int getIco24() - { - return _props.getIco24(); - } - - /** - * Set the ico24 field for the CHP record. - */ - public void setIco24(int colour24) - { - _props.setIco24(colour24); - } - - /** - * Used to create a deep copy of this object. - * - * @return A deep copy. - * @throws CloneNotSupportedException never - */ - public Object clone() - throws CloneNotSupportedException - { - CharacterRun cp = (CharacterRun)super.clone(); - cp._props.setDttmRMark((DateAndTime)_props.getDttmRMark().clone()); - cp._props.setDttmRMarkDel((DateAndTime)_props.getDttmRMarkDel().clone()); - cp._props.setDttmPropRMark((DateAndTime)_props.getDttmPropRMark().clone()); - cp._props.setDttmDispFldRMark((DateAndTime)_props.getDttmDispFldRMark(). - clone()); - cp._props.setXstDispFldRMark(_props.getXstDispFldRMark().clone()); - cp._props.setShd(_props.getShd().clone()); - - return cp; - } - - /** - * Returns true, if the CharacterRun is a special character run containing a symbol, otherwise false. - * - *

    In case of a symbol, the {@link #text()} method always returns a single character 0x0028, but word actually stores - * the character in a different field. Use {@link #getSymbolCharacter()} to get that character and {@link #getSymbolFont()} - * to determine its font. - */ - public boolean isSymbol() - { - return isSpecialCharacter() && text().equals("\u0028"); - } - - /** - * Returns the symbol character, if this is a symbol character run. - * - * @see #isSymbol() - * @throws IllegalStateException If this is not a symbol character run: call {@link #isSymbol()} first. - */ - public char getSymbolCharacter() - { - if (isSymbol()) { - return (char)_props.getXchSym(); - } else - throw new IllegalStateException("Not a symbol CharacterRun"); - } - - /** - * Returns the symbol font, if this is a symbol character run. Might return null, if the font index is not found in the font table. - * - * @see #isSymbol() - * @throws IllegalStateException If this is not a symbol character run: call {@link #isSymbol()} first. - */ - public Ffn getSymbolFont() - { - if (isSymbol()) { - if (_doc.getFontTable() == null) - return null; - - // Fetch all font names - Ffn[] fontNames = _doc.getFontTable().getFontNames(); - - // Try to find the name of the font for our symbol - if (fontNames.length <= _props.getFtcSym()) - return null; - - return fontNames[_props.getFtcSym()]; - } else - throw new IllegalStateException("Not a symbol CharacterRun"); - } - - public BorderCode getBorder() { - return _props.getBrc(); - } - - public int getLanguageCode() { - return _props.getLidDefault(); - } - - /** - *

    Returns the index of the base style which applies to - * this Run. Details of the style can be looked up - * from the {@link StyleSheet}, via - * {@link StyleSheet#getStyleDescription(int)}.

    - *

    Note that runs typically override some of the style - * properties from the base, so normally style information - * should be fetched directly from the {@link CharacterRun} - * itself.

    - */ - public short getStyleIndex() { - return _istd; - } - - public String toString() { - String text = text(); - return "CharacterRun of " + text.length() + " characters - " + text; - } - - public String[] getDropDownListValues() - { - if ( getDocument() instanceof HWPFDocument ) - { - char c = _text.charAt( _start ); - if ( c == 0x01 ) - { - NilPICFAndBinData data = new NilPICFAndBinData( - ( (HWPFDocument) getDocument() ).getDataStream(), - getPicOffset() ); - FFData ffData = new FFData( data.getBinData(), 0 ); - - String[] values = ffData.getDropList(); - return values; - } - } - return null; - } - - public Integer getDropDownListDefaultItemIndex() - { - if ( getDocument() instanceof HWPFDocument ) - { - char c = _text.charAt( _start ); - if ( c == 0x01 ) - { - NilPICFAndBinData data = new NilPICFAndBinData( - ( (HWPFDocument) getDocument() ).getDataStream(), - getPicOffset() ); - FFData ffData = new FFData( data.getBinData(), 0 ); - - return Integer.valueOf( ffData.getDefaultDropDownItemIndex() ); - } - } - return null; - } - -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/DateAndTime.java b/src/scratchpad/src/org/apache/poi/hwpf/usermodel/DateAndTime.java deleted file mode 100644 index b812b6667..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/DateAndTime.java +++ /dev/null @@ -1,107 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.usermodel; - -import java.util.Calendar; - -import org.apache.poi.util.BitField; -import org.apache.poi.util.BitFieldFactory; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.LocaleUtil; - -/** - * This class is used to represent a date and time in a Word document. - * - * @author Ryan Ackley - */ -public final class DateAndTime - implements Cloneable -{ - public static final int SIZE = 4; - private short _info; - private static final BitField _minutes = BitFieldFactory.getInstance(0x3f); - private static final BitField _hours = BitFieldFactory.getInstance(0x7c0); - private static final BitField _dom = BitFieldFactory.getInstance(0xf800); - private short _info2; - private static final BitField _months = BitFieldFactory.getInstance(0xf); - private static final BitField _years = BitFieldFactory.getInstance(0x1ff0); - // private static final BitField _weekday = BitFieldFactory.getInstance(0xe000); - - public DateAndTime() - { - } - - public DateAndTime(byte[] buf, int offset) - { - _info = LittleEndian.getShort(buf, offset); - _info2 = LittleEndian.getShort(buf, offset + LittleEndian.SHORT_SIZE); - } - - public Calendar getDate() { - // TODO Discover if the timezone is stored somewhere else or not - Calendar cal = LocaleUtil.getLocaleCalendar( - _years.getValue(_info2)+1900, - _months.getValue(_info2)-1, - _dom.getValue(_info), - _hours.getValue(_info), - _minutes.getValue(_info), - 0 - ); - return cal; - } - - public void serialize(byte[] buf, int offset) - { - LittleEndian.putShort(buf, offset, _info); - LittleEndian.putShort(buf, offset + LittleEndian.SHORT_SIZE, _info2); - } - - @Override - public boolean equals(Object o) - { - if (!(o instanceof DateAndTime)) return false; - DateAndTime dttm = (DateAndTime)o; - return _info == dttm._info && _info2 == dttm._info2; - } - - @Override - public int hashCode() { - assert false : "hashCode not designed"; - return 42; // any arbitrary constant will do - } - - public Object clone() - throws CloneNotSupportedException - { - return super.clone(); - } - - public boolean isEmpty() - { - return _info == 0 && _info2 == 0; - } - - @Override - public String toString() - { - if ( isEmpty() ) - return "[DTTM] EMPTY"; - - return "[DTTM] " + getDate(); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/DropCapSpecifier.java b/src/scratchpad/src/org/apache/poi/hwpf/usermodel/DropCapSpecifier.java deleted file mode 100644 index 5ba4e0728..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/DropCapSpecifier.java +++ /dev/null @@ -1,118 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.usermodel; - -import org.apache.poi.util.BitField; -import org.apache.poi.util.BitFieldFactory; -import org.apache.poi.util.LittleEndian; - -/** - * This data structure is used by a paragraph to determine how it should drop - * its first letter. I think its the visual effect that will show a giant first - * letter to a paragraph. I've seen this used in the first paragraph of a book - * - * @author Ryan Ackley - */ -public final class DropCapSpecifier implements Cloneable -{ - private short _fdct; - private static BitField _lines = BitFieldFactory.getInstance( 0xf8 ); - private static BitField _type = BitFieldFactory.getInstance( 0x07 ); - - public DropCapSpecifier() - { - this._fdct = 0; - } - - public DropCapSpecifier( byte[] buf, int offset ) - { - this( LittleEndian.getShort( buf, offset ) ); - } - - public DropCapSpecifier( short fdct ) - { - this._fdct = fdct; - } - - @Override - public DropCapSpecifier clone() - { - return new DropCapSpecifier( _fdct ); - } - - @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - return true; - if ( obj == null ) - return false; - if ( getClass() != obj.getClass() ) - return false; - DropCapSpecifier other = (DropCapSpecifier) obj; - if ( _fdct != other._fdct ) - return false; - return true; - } - - public byte getCountOfLinesToDrop() - { - return (byte) _lines.getValue( _fdct ); - } - - public byte getDropCapType() - { - return (byte) _type.getValue( _fdct ); - } - - @Override - public int hashCode() - { - return _fdct; - } - - public boolean isEmpty() - { - return _fdct == 0; - } - - public void setCountOfLinesToDrop( byte value ) - { - _fdct = (short) _lines.setValue( _fdct, value ); - } - - public void setDropCapType( byte value ) - { - _fdct = (short) _type.setValue( _fdct, value ); - } - - public short toShort() - { - return _fdct; - } - - @Override - public String toString() - { - if ( isEmpty() ) - return "[DCS] EMPTY"; - - return "[DCS] (type: " + getDropCapType() + "; count: " - + getCountOfLinesToDrop() + ")"; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/Field.java b/src/scratchpad/src/org/apache/poi/hwpf/usermodel/Field.java deleted file mode 100644 index de7ebcd3f..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/Field.java +++ /dev/null @@ -1,77 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hwpf.usermodel; - -public interface Field -{ - - Range firstSubrange( Range parent ); - - /** - * @return character position of first character after field (i.e. - * {@link #getMarkEndOffset()} + 1) - */ - int getFieldEndOffset(); - - /** - * @return character position of first character in field (i.e. - * {@link #getFieldStartOffset()}) - */ - int getFieldStartOffset(); - - CharacterRun getMarkEndCharacterRun( Range parent ); - - /** - * @return character position of end field mark - */ - int getMarkEndOffset(); - - CharacterRun getMarkSeparatorCharacterRun( Range parent ); - - /** - * @return character position of separator field mark (if present, - * {@link NullPointerException} otherwise) - */ - int getMarkSeparatorOffset(); - - CharacterRun getMarkStartCharacterRun( Range parent ); - - /** - * @return character position of start field mark - */ - int getMarkStartOffset(); - - int getType(); - - boolean hasSeparator(); - - boolean isHasSep(); - - boolean isLocked(); - - boolean isNested(); - - boolean isPrivateResult(); - - boolean isResultDirty(); - - boolean isResultEdited(); - - boolean isZombieEmbed(); - - Range secondSubrange( Range parent ); -} \ No newline at end of file diff --git a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/FieldImpl.java b/src/scratchpad/src/org/apache/poi/hwpf/usermodel/FieldImpl.java deleted file mode 100644 index 37131c3e1..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/FieldImpl.java +++ /dev/null @@ -1,230 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hwpf.usermodel; - -import org.apache.poi.hwpf.model.FieldDescriptor; -import org.apache.poi.hwpf.model.PlexOfField; -import org.apache.poi.util.Internal; - -/** - * TODO: document me - * - * @author Sergey Vladimirov (vlsergey {at} gmail {dot} com) - */ -@Internal -class FieldImpl implements Field -{ - private PlexOfField endPlex; - private PlexOfField separatorPlex; - private PlexOfField startPlex; - - public FieldImpl( PlexOfField startPlex, PlexOfField separatorPlex, - PlexOfField endPlex ) - { - if ( startPlex == null ) - throw new IllegalArgumentException( "startPlex == null" ); - if ( endPlex == null ) - throw new IllegalArgumentException( "endPlex == null" ); - - if ( startPlex.getFld().getBoundaryType() != FieldDescriptor.FIELD_BEGIN_MARK ) - throw new IllegalArgumentException( "startPlex (" + startPlex - + ") is not type of FIELD_BEGIN" ); - - if ( separatorPlex != null - && separatorPlex.getFld().getBoundaryType() != FieldDescriptor.FIELD_SEPARATOR_MARK ) - throw new IllegalArgumentException( "separatorPlex" + separatorPlex - + ") is not type of FIELD_SEPARATOR" ); - - if ( endPlex.getFld().getBoundaryType() != FieldDescriptor.FIELD_END_MARK ) - throw new IllegalArgumentException( "endPlex (" + endPlex - + ") is not type of FIELD_END" ); - - this.startPlex = startPlex; - this.separatorPlex = separatorPlex; - this.endPlex = endPlex; - } - - public Range firstSubrange( Range parent ) - { - if ( hasSeparator() ) - { - if ( getMarkStartOffset() + 1 == getMarkSeparatorOffset() ) - return null; - - return new Range( getMarkStartOffset() + 1, - getMarkSeparatorOffset(), parent ) - { - @Override - public String toString() - { - return "FieldSubrange1 (" + super.toString() + ")"; - } - }; - } - - if ( getMarkStartOffset() + 1 == getMarkEndOffset() ) - return null; - - return new Range( getMarkStartOffset() + 1, getMarkEndOffset(), parent ) - { - @Override - public String toString() - { - return "FieldSubrange1 (" + super.toString() + ")"; - } - }; - } - - /** - * @return character position of first character after field (i.e. - * {@link #getMarkEndOffset()} + 1) - */ - public int getFieldEndOffset() - { - /* - * sometimes plex looks like [100, 2000), where 100 is the position of - * field-end character, and 2000 - some other char position, far away - * from field (not inside). So taking into account only start --sergey - */ - return endPlex.getFcStart() + 1; - } - - /** - * @return character position of first character in field (i.e. - * {@link #getFieldStartOffset()}) - */ - public int getFieldStartOffset() - { - return startPlex.getFcStart(); - } - - public CharacterRun getMarkEndCharacterRun( Range parent ) - { - return new Range( getMarkEndOffset(), getMarkEndOffset() + 1, parent ) - .getCharacterRun( 0 ); - } - - /** - * @return character position of end field mark - */ - public int getMarkEndOffset() - { - return endPlex.getFcStart(); - } - - public CharacterRun getMarkSeparatorCharacterRun( Range parent ) - { - if ( !hasSeparator() ) - return null; - - return new Range( getMarkSeparatorOffset(), - getMarkSeparatorOffset() + 1, parent ).getCharacterRun( 0 ); - } - - /** - * @return character position of separator field mark (if present, - * {@link NullPointerException} otherwise) - */ - public int getMarkSeparatorOffset() - { - return separatorPlex.getFcStart(); - } - - public CharacterRun getMarkStartCharacterRun( Range parent ) - { - return new Range( getMarkStartOffset(), getMarkStartOffset() + 1, - parent ).getCharacterRun( 0 ); - } - - /** - * @return character position of start field mark - */ - public int getMarkStartOffset() - { - return startPlex.getFcStart(); - } - - public int getType() - { - return startPlex.getFld().getFieldType(); - } - - public boolean hasSeparator() - { - return separatorPlex != null; - } - - public boolean isHasSep() - { - return endPlex.getFld().isFHasSep(); - } - - public boolean isLocked() - { - return endPlex.getFld().isFLocked(); - } - - public boolean isNested() - { - return endPlex.getFld().isFNested(); - } - - public boolean isPrivateResult() - { - return endPlex.getFld().isFPrivateResult(); - } - - public boolean isResultDirty() - { - return endPlex.getFld().isFResultDirty(); - } - - public boolean isResultEdited() - { - return endPlex.getFld().isFResultEdited(); - } - - public boolean isZombieEmbed() - { - return endPlex.getFld().isFZombieEmbed(); - } - - public Range secondSubrange( Range parent ) - { - if ( !hasSeparator() - || getMarkSeparatorOffset() + 1 == getMarkEndOffset() ) - return null; - - return new Range( getMarkSeparatorOffset() + 1, getMarkEndOffset(), - parent ) - { - @Override - public String toString() - { - return "FieldSubrange2 (" + super.toString() + ")"; - } - }; - } - - @Override - public String toString() - { - return "Field [" + getFieldStartOffset() + "; " + getFieldEndOffset() - + "] (type: 0x" + Integer.toHexString( getType() ) + " = " - + getType() + " )"; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/Fields.java b/src/scratchpad/src/org/apache/poi/hwpf/usermodel/Fields.java deleted file mode 100644 index 2db551e5e..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/Fields.java +++ /dev/null @@ -1,33 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hwpf.usermodel; - -import java.util.Collection; - -import org.apache.poi.hwpf.model.FieldsDocumentPart; - -/** - * User-friendly interface to access document {@link Field}s - * - * @author Sergey Vladimirov (vlsergey {at} gmail {dot} com) - */ -public interface Fields -{ - Field getFieldByStartOffset( FieldsDocumentPart documentPart, int offset ); - - Collection getFields( FieldsDocumentPart part ); -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/FieldsImpl.java b/src/scratchpad/src/org/apache/poi/hwpf/usermodel/FieldsImpl.java deleted file mode 100644 index 7f73e5918..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/FieldsImpl.java +++ /dev/null @@ -1,275 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hwpf.usermodel; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.poi.hwpf.model.FieldDescriptor; -import org.apache.poi.hwpf.model.FieldsDocumentPart; -import org.apache.poi.hwpf.model.FieldsTables; -import org.apache.poi.hwpf.model.PlexOfField; -import org.apache.poi.util.Internal; - -/** - * Default implementation of {@link Field} - * - * @author Sergey Vladimirov (vlsergey {at} gmail {dot} com) - */ -@Internal -public class FieldsImpl implements Fields -{ - /** - * This is port and adaptation of Arrays.binarySearch from Java 6 (Apache - * Harmony). - */ - private static int binarySearch( List list, - int startIndex, int endIndex, int requiredStartOffset ) - { - checkIndexForBinarySearch( list.size(), startIndex, endIndex ); - - int low = startIndex, mid = -1, high = endIndex - 1, result = 0; - while ( low <= high ) - { - mid = ( low + high ) >>> 1; - int midStart = list.get( mid ).getFcStart(); - - if ( midStart == requiredStartOffset ) - { - return mid; - } - else if ( midStart < requiredStartOffset ) - { - low = mid + 1; - } - else - { - high = mid - 1; - } - } - if ( mid < 0 ) - { - int insertPoint = endIndex; - for ( int index = startIndex; index < endIndex; index++ ) - { - if ( requiredStartOffset < list.get( index ).getFcStart() ) - { - insertPoint = index; - } - } - return -insertPoint - 1; - } - return -mid - ( result >= 0 ? 1 : 2 ); - } - - private static void checkIndexForBinarySearch( int length, int start, - int end ) - { - if ( start > end ) - { - throw new IllegalArgumentException(); - } - if ( length < end || 0 > start ) - { - throw new ArrayIndexOutOfBoundsException(); - } - } - - private Map> _fieldsByOffset; - - private PlexOfFieldComparator comparator = new PlexOfFieldComparator(); - - public FieldsImpl( FieldsTables fieldsTables ) - { - _fieldsByOffset = new HashMap>( - FieldsDocumentPart.values().length ); - - for ( FieldsDocumentPart part : FieldsDocumentPart.values() ) - { - List plexOfCps = fieldsTables.getFieldsPLCF( part ); - _fieldsByOffset.put( part, parseFieldStructure( plexOfCps ) ); - } - } - - public Collection getFields( FieldsDocumentPart part ) - { - Map map = _fieldsByOffset.get( part ); - if ( map == null || map.isEmpty() ) - return Collections.emptySet(); - - return Collections. unmodifiableCollection( map.values() ); - } - - public FieldImpl getFieldByStartOffset( FieldsDocumentPart documentPart, - int offset ) - { - Map map = _fieldsByOffset.get( documentPart ); - if ( map == null || map.isEmpty() ) - return null; - - return map.get( Integer.valueOf( offset ) ); - } - - private Map parseFieldStructure( - List plexOfFields ) - { - if ( plexOfFields == null || plexOfFields.isEmpty() ) - return new HashMap(); - - Collections.sort( plexOfFields, comparator ); - List fields = new ArrayList( - plexOfFields.size() / 3 + 1 ); - parseFieldStructureImpl( plexOfFields, 0, plexOfFields.size(), fields ); - - HashMap result = new HashMap( - fields.size() ); - for ( FieldImpl field : fields ) - { - result.put( Integer.valueOf( field.getFieldStartOffset() ), field ); - } - return result; - } - - private void parseFieldStructureImpl( List plexOfFields, - int startOffsetInclusive, int endOffsetExclusive, - List result ) - { - int next = startOffsetInclusive; - while ( next < endOffsetExclusive ) - { - PlexOfField startPlexOfField = plexOfFields.get( next ); - if ( startPlexOfField.getFld().getBoundaryType() != FieldDescriptor.FIELD_BEGIN_MARK ) - { - /* Start mark seems to be missing */ - next++; - continue; - } - - /* - * we have start node. end offset points to next node, separator or - * end - */ - int nextNodePositionInList = binarySearch( plexOfFields, next + 1, - endOffsetExclusive, startPlexOfField.getFcEnd() ); - if ( nextNodePositionInList < 0 ) - { - /* - * too bad, this start field mark doesn't have corresponding end - * field mark or separator field mark in fields table - */ - next++; - continue; - } - PlexOfField nextPlexOfField = plexOfFields - .get( nextNodePositionInList ); - - switch ( nextPlexOfField.getFld().getBoundaryType() ) - { - case FieldDescriptor.FIELD_SEPARATOR_MARK: - { - PlexOfField separatorPlexOfField = nextPlexOfField; - - int endNodePositionInList = binarySearch( plexOfFields, - nextNodePositionInList, endOffsetExclusive, - separatorPlexOfField.getFcEnd() ); - if ( endNodePositionInList < 0 ) - { - /* - * too bad, this separator field mark doesn't have - * corresponding end field mark in fields table - */ - next++; - continue; - } - PlexOfField endPlexOfField = plexOfFields - .get( endNodePositionInList ); - - if ( endPlexOfField.getFld().getBoundaryType() != FieldDescriptor.FIELD_END_MARK ) - { - /* Not and ending mark */ - next++; - continue; - } - - FieldImpl field = new FieldImpl( startPlexOfField, - separatorPlexOfField, endPlexOfField ); - result.add( field ); - - // adding included fields - if ( startPlexOfField.getFcStart() + 1 < separatorPlexOfField - .getFcStart() - 1 ) - { - parseFieldStructureImpl( plexOfFields, next + 1, - nextNodePositionInList, result ); - } - if ( separatorPlexOfField.getFcStart() + 1 < endPlexOfField - .getFcStart() - 1 ) - { - parseFieldStructureImpl( plexOfFields, - nextNodePositionInList + 1, endNodePositionInList, - result ); - } - - next = endNodePositionInList + 1; - - break; - } - case FieldDescriptor.FIELD_END_MARK: - { - // we have no separator - FieldImpl field = new FieldImpl( startPlexOfField, null, - nextPlexOfField ); - result.add( field ); - - // adding included fields - if ( startPlexOfField.getFcStart() + 1 < nextPlexOfField - .getFcStart() - 1 ) - { - parseFieldStructureImpl( plexOfFields, next + 1, - nextNodePositionInList, result ); - } - - next = nextNodePositionInList + 1; - break; - } - case FieldDescriptor.FIELD_BEGIN_MARK: - default: - { - /* something is wrong, ignoring this mark along with start mark */ - next++; - continue; - } - } - } - } - - private static final class PlexOfFieldComparator implements Comparator, Serializable { - public int compare( PlexOfField o1, PlexOfField o2 ) - { - int thisVal = o1.getFcStart(); - int anotherVal = o2.getFcStart(); - return thisVal < anotherVal ? -1 : thisVal == anotherVal ? 0 : 1; - } - } - -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/HWPFList.java b/src/scratchpad/src/org/apache/poi/hwpf/usermodel/HWPFList.java deleted file mode 100644 index 3364aecb0..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/HWPFList.java +++ /dev/null @@ -1,239 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.usermodel; - -import org.apache.poi.hwpf.model.ListTables; - -import org.apache.poi.util.Internal; - -import org.apache.poi.hwpf.model.LFO; -import org.apache.poi.hwpf.model.LFOData; -import org.apache.poi.hwpf.model.ListData; -import org.apache.poi.hwpf.model.ListFormatOverrideLevel; -import org.apache.poi.hwpf.model.ListLevel; -import org.apache.poi.hwpf.model.StyleSheet; -import org.apache.poi.hwpf.sprm.CharacterSprmCompressor; -import org.apache.poi.hwpf.sprm.ParagraphSprmCompressor; - -/** - * This class is used to create a list in a Word document. It is used in - * conjunction with - * {@link org.apache.poi.hwpf.HWPFDocument#registerList(HWPFList) registerList} - * in {@link org.apache.poi.hwpf.HWPFDocument HWPFDocument}. - * - * In Word, lists are not ranged entities, meaning you can't actually add one to - * the document. Lists only act as properties for list entries. Once you - * register a list, you can add list entries to a document that are a part of - * the list. - * - * The only benefit of this that I see, is that you can add a list entry - * anywhere in the document and continue numbering from the previous list. - * - * @author Ryan Ackley - */ -public final class HWPFList -{ - private boolean _ignoreLogicalLeftIdentation = false; - private LFO _lfo; - private LFOData _lfoData; - private ListData _listData; - private ListTables _listTables; - private StyleSheet _styleSheet; - - /** - * - * @param numbered - * true if the list should be numbered; false if it should be - * bulleted. - * @param styleSheet - * The document's stylesheet. - */ - public HWPFList( boolean numbered, StyleSheet styleSheet ) - { - _listData = new ListData( - (int) ( Math.random() * System.currentTimeMillis() ), numbered ); - _lfo = new LFO(); - _lfo.setLsid( _listData.getLsid() ); - _lfoData = new LFOData(); - _styleSheet = styleSheet; - } - - public HWPFList( StyleSheet styleSheet, ListTables listTables, int ilfo ) - { - _listTables = listTables; - _styleSheet = styleSheet; - - /* See documentation for sprmPIlfo (0x460B) */ - if ( ilfo == 0 || ilfo == 0xF801 ) - { - throw new IllegalArgumentException( "Paragraph not in list" ); - } - else if ( 0x0001 <= ilfo && ilfo <= 0x07FE ) - { - _lfo = listTables.getLfo( ilfo ); - _lfoData = listTables.getLfoData( ilfo ); - } - else if ( 0xF802 <= ilfo && ilfo <= 0xFFFF ) - { - int nilfo = ilfo ^ 0xFFFF; - _lfo = listTables.getLfo( nilfo ); - _lfoData = listTables.getLfoData( nilfo ); - _ignoreLogicalLeftIdentation = true; - } - else - { - throw new IllegalArgumentException( "Incorrect ilfo: " + ilfo ); - } - - _listData = listTables.getListData( _lfo.getLsid() ); - } - - @Internal - public LFO getLFO() - { - return _lfo; - } - - @Internal - public LFOData getLFOData() - { - return _lfoData; - } - - @Internal - public ListData getListData() - { - return _listData; - } - - public int getLsid() - { - return _lfo.getLsid(); - } - - @Internal - ListLevel getLVL( char level ) - { - if ( level >= _listData.numLevels() ) - { - throw new IllegalArgumentException( "Required level " - + ( (int) level ) - + " is more than number of level for list (" - + _listData.numLevels() + ")" ); - } - ListLevel lvl = _listData.getLevels()[level]; - return lvl; - } - - /** - * An MSONFC, as specified in [MS-OSHARED] section 2.2.1.3, that specifies - * the format of the level numbers that replace the placeholders for this - * level in the xst fields of the LVLs in this list. This value MUST not be - * equal to 0x08, 0x09, 0x0F, or 0x13. If this is equal to 0xFF or 0x17, - * this level does not have a number sequence and therefore has no number - * formatting. If this is equal to 0x17, the level uses bullets. - */ - public int getNumberFormat( char level ) - { - return getLVL( level ).getNumberFormat(); - } - - public String getNumberText( char level ) - { - return getLVL( level ).getNumberText(); - } - - public int getStartAt( char level ) - { - if ( isStartAtOverriden( level ) ) - { - return _lfoData.getRgLfoLvl()[level].getIStartAt(); - } - - return getLVL( level ).getStartAt(); - } - - /** - * "The type of character following the number text for the paragraph: 0 == tab, 1 == space, 2 == nothing." - */ - public byte getTypeOfCharFollowingTheNumber( char level ) - { - return getLVL( level ).getTypeOfCharFollowingTheNumber(); - } - - public boolean isIgnoreLogicalLeftIdentation() - { - return _ignoreLogicalLeftIdentation; - } - - public boolean isStartAtOverriden( char level ) - { - ListFormatOverrideLevel lfolvl = _lfoData.getRgLfoLvl().length > level ? _lfoData - .getRgLfoLvl()[level] : null; - - return lfolvl != null && lfolvl.getIStartAt() != 0 - && !lfolvl.isFormatting(); - } - - public void setIgnoreLogicalLeftIdentation( - boolean ignoreLogicalLeftIdentation ) - { - this._ignoreLogicalLeftIdentation = ignoreLogicalLeftIdentation; - } - - /** - * Sets the character properties of the list numbers. - * - * @param level - * the level number that the properties should apply to. - * @param chp - * The character properties. - */ - public void setLevelNumberProperties( int level, CharacterProperties chp ) - { - ListLevel listLevel = _listData.getLevel( level ); - int styleIndex = _listData.getLevelStyle( level ); - CharacterProperties base = _styleSheet.getCharacterStyle( styleIndex ); - - byte[] grpprl = CharacterSprmCompressor.compressCharacterProperty( chp, base ); - listLevel.setNumberProperties( grpprl ); - } - - /** - * Sets the paragraph properties for a particular level of the list. - * - * @param level - * The level number. - * @param pap - * The paragraph properties - */ - public void setLevelParagraphProperties( int level, ParagraphProperties pap ) - { - ListLevel listLevel = _listData.getLevel( level ); - int styleIndex = _listData.getLevelStyle( level ); - ParagraphProperties base = _styleSheet.getParagraphStyle( styleIndex ); - - byte[] grpprl = ParagraphSprmCompressor.compressParagraphProperty( pap, base ); - listLevel.setLevelProperties( grpprl ); - } - - public void setLevelStyle( int level, int styleIndex ) - { - _listData.setLevelStyle( level, styleIndex ); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/HeaderStories.java b/src/scratchpad/src/org/apache/poi/hwpf/usermodel/HeaderStories.java deleted file mode 100644 index 84a0e9b34..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/HeaderStories.java +++ /dev/null @@ -1,384 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.usermodel; - -import org.apache.poi.hwpf.HWPFDocument; -import org.apache.poi.hwpf.model.FileInformationBlock; -import org.apache.poi.hwpf.model.GenericPropertyNode; -import org.apache.poi.hwpf.model.PlexOfCps; -import org.apache.poi.hwpf.model.SubdocumentType; - -/** - * A HeaderStory is a Header, a Footer, or footnote/endnote - * separator. - * All the Header Stories get stored in the same Range in the - * document, and this handles getting out all the individual - * parts. - * - * WARNING - you shouldn't change the headers or footers, - * as offsets are not yet updated! - */ -public final class HeaderStories { - private Range headerStories; - private PlexOfCps plcfHdd; - - private boolean stripFields = false; - - public HeaderStories(HWPFDocument doc) { - this.headerStories = doc.getHeaderStoryRange(); - FileInformationBlock fib = doc.getFileInformationBlock(); - -// // If there's no PlcfHdd, nothing to do -// if(fib.getCcpHdd() == 0) { -// return; -// } - - if (fib.getSubdocumentTextStreamLength( SubdocumentType.HEADER ) == 0) - return; - - if(fib.getPlcfHddSize() == 0) { - return; - } - - // Handle the PlcfHdd - /* - * Page 88: - * - * "The plcfhdd, a table whose location and length within the file is - * stored in fib.fcPlcfhdd and fib.cbPlcfhdd, describes where the text - * of each header/footer begins. If there are n headers/footers stored - * in the Word file, the plcfhdd consists of n+2 CP entries. The - * beginning CP of the ith header/footer is the ith CP in the plcfhdd. - * The limit CP (the CP of character 1 position past the end of a - * header/footer) of the ith header/footer is the i+1st CP in the - * plcfhdd. Note: at the limit CP - 1, Word always places a chEop as a - * placeholder which is never displayed as part of the header/footer. - * This allows Word to change an existing header/footer to be empty. - * - * If there are n header/footers, the n+2nd CP entry value is always 1 - * greater than the n+1st CP entry value. A paragraph end (ASCII 13) is - * always stored at the file position marked by the n+1st CP value. - * - * The transformation in a full saved file from a header/footer CP to an - * offset from the beginning of a file (fc) is - * fc=fib.fcMin+ccpText+ccpFtn+cp." - */ - plcfHdd = new PlexOfCps( doc.getTableStream(), fib.getPlcfHddOffset(), - fib.getPlcfHddSize(), 0 ); - } - - /** - * @deprecated 3.8 beta 4 - */ - @Deprecated - public String getFootnoteSeparator() - { - return getAt( 0 ); - } - - /** - * @deprecated 3.8 beta 4 - */ - @Deprecated - public String getFootnoteContSeparator() - { - return getAt( 1 ); - } - - /** - * @deprecated 3.8 beta 4 - */ - @Deprecated - public String getFootnoteContNote() - { - return getAt( 2 ); - } - - /** - * @deprecated 3.8 beta 4 - */ - @Deprecated - public String getEndnoteSeparator() - { - return getAt( 3 ); - } - - /** - * @deprecated 3.8 beta 4 - */ - @Deprecated - public String getEndnoteContSeparator() - { - return getAt( 4 ); - } - - /** - * @deprecated 3.8 beta 4 - */ - @Deprecated - public String getEndnoteContNote() - { - return getAt( 5 ); - } - - public Range getFootnoteSeparatorSubrange() - { - return getSubrangeAt( 0 ); - } - - public Range getFootnoteContSeparatorSubrange() - { - return getSubrangeAt( 1 ); - } - - public Range getFootnoteContNoteSubrange() - { - return getSubrangeAt( 2 ); - } - - public Range getEndnoteSeparatorSubrange() - { - return getSubrangeAt( 3 ); - } - - public Range getEndnoteContSeparatorSubrange() - { - return getSubrangeAt( 4 ); - } - - public Range getEndnoteContNoteSubrange() - { - return getSubrangeAt( 5 ); - } - - /** - * @deprecated 3.8 beta 4 - */ - @Deprecated - public String getEvenHeader() { - return getAt(6+0); - } - /** - * @deprecated 3.8 beta 4 - */ - @Deprecated - public String getOddHeader() { - return getAt(6+1); - } - /** - * @deprecated 3.8 beta 4 - */ - @Deprecated - public String getFirstHeader() { - return getAt(6+4); - } - - - public Range getEvenHeaderSubrange() { - return getSubrangeAt(6+0); - } - public Range getOddHeaderSubrange() { - return getSubrangeAt(6+1); - } - public Range getFirstHeaderSubrange() { - return getSubrangeAt(6+4); - } - - /** - * Returns the correct, defined header for the given - * one based page - * @param pageNumber The one based page number - */ - public String getHeader(int pageNumber) { - // First page header is optional, only return - // if it's set - if(pageNumber == 1) { - if(getFirstHeader().length() > 0) { - return getFirstHeader(); - } - } - // Even page header is optional, only return - // if it's set - if(pageNumber % 2 == 0) { - if(getEvenHeader().length() > 0) { - return getEvenHeader(); - } - } - // Odd is the default - return getOddHeader(); - } - - /** - * @deprecated 3.8 beta 4 - */ - @Deprecated - public String getEvenFooter() - { - return getAt( 6 + 2 ); - } - - /** - * @deprecated 3.8 beta 4 - */ - @Deprecated - public String getOddFooter() - { - return getAt( 6 + 3 ); - } - - /** - * @deprecated 3.8 beta 4 - */ - @Deprecated - public String getFirstFooter() - { - return getAt( 6 + 5 ); - } - - public Range getEvenFooterSubrange() - { - return getSubrangeAt( 6 + 2 ); - } - - public Range getOddFooterSubrange() - { - return getSubrangeAt( 6 + 3 ); - } - - public Range getFirstFooterSubrange() - { - return getSubrangeAt( 6 + 5 ); - } - - /** - * Returns the correct, defined footer for the given - * one based page - * @param pageNumber The one based page number - */ - public String getFooter(int pageNumber) { - // First page footer is optional, only return - // if it's set - if(pageNumber == 1) { - if(getFirstFooter().length() > 0) { - return getFirstFooter(); - } - } - // Even page footer is optional, only return - // if it's set - if(pageNumber % 2 == 0) { - if(getEvenFooter().length() > 0) { - return getEvenFooter(); - } - } - // Odd is the default - return getOddFooter(); - } - - - /** - * Get the string that's pointed to by the - * given plcfHdd index - * @deprecated 3.8 beta 4 - */ - @Deprecated - private String getAt(int plcfHddIndex) { - if(plcfHdd == null) return null; - - GenericPropertyNode prop = plcfHdd.getProperty(plcfHddIndex); - if(prop.getStart() == prop.getEnd()) { - // Empty story - return ""; - } - if(prop.getEnd() < prop.getStart()) { - // Broken properties? - return ""; - } - - // Ensure we're getting a sensible length - String rawText = headerStories.text(); - int start = Math.min(prop.getStart(), rawText.length()); - int end = Math.min(prop.getEnd(), rawText.length()); - - // Grab the contents - String text = rawText.substring(start, end); - - // Strip off fields and macros if requested - if(stripFields) { - return Range.stripFields(text); - } - // If you create a header/footer, then remove it again, word - // will leave \r\r. Turn these back into an empty string, - // which is more what you'd expect - if(text.equals("\r\r")) { - return ""; - } - - return text; - } - - private Range getSubrangeAt( int plcfHddIndex ) - { - if ( plcfHdd == null ) - return null; - - GenericPropertyNode prop = plcfHdd.getProperty( plcfHddIndex ); - if ( prop.getStart() == prop.getEnd() ) - { - // Empty story - return null; - } - if ( prop.getEnd() < prop.getStart() ) - { - // Broken properties? - return null; - } - - final int headersLength = headerStories.getEndOffset() - - headerStories.getStartOffset(); - int start = Math.min( prop.getStart(), headersLength ); - int end = Math.min( prop.getEnd(), headersLength ); - - return new Range( headerStories.getStartOffset() + start, - headerStories.getStartOffset() + end, headerStories ); - } - - public Range getRange() { - return headerStories; - } - protected PlexOfCps getPlcfHdd() { - return plcfHdd; - } - - /** - * Are fields currently being stripped from - * the text that this {@link HeaderStories} returns? - * Default is false, but can be changed - */ - public boolean areFieldsStripped() { - return stripFields; - } - /** - * Should fields (eg macros) be stripped from - * the text that this class returns? - * Default is not to strip. - * @param stripFields - */ - public void setAreFieldsStripped(boolean stripFields) { - this.stripFields = stripFields; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/LineSpacingDescriptor.java b/src/scratchpad/src/org/apache/poi/hwpf/usermodel/LineSpacingDescriptor.java deleted file mode 100644 index 6e6b8020a..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/LineSpacingDescriptor.java +++ /dev/null @@ -1,104 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.usermodel; - -import org.apache.poi.util.LittleEndian; - -/** - * This class is used to determine line spacing for a paragraph. - * - * @author Ryan Ackley - */ -public final class LineSpacingDescriptor - implements Cloneable -{ - short _dyaLine; - short _fMultiLinespace; - - public LineSpacingDescriptor() - { - //see page 181 - _dyaLine = 240; - _fMultiLinespace = 1; - } - - public LineSpacingDescriptor(byte[] buf, int offset) - { - _dyaLine = LittleEndian.getShort(buf, offset); - _fMultiLinespace = LittleEndian.getShort(buf, offset + LittleEndian.SHORT_SIZE); - } - - public Object clone() - throws CloneNotSupportedException - { - return super.clone(); - } - - public void setMultiLinespace(short fMultiLinespace) - { - _fMultiLinespace = fMultiLinespace; - } - - public int toInt() - { - byte[] intHolder = new byte[4]; - serialize(intHolder, 0); - return LittleEndian.getInt(intHolder); - } - - public void serialize(byte[] buf, int offset) - { - LittleEndian.putShort(buf, offset, _dyaLine); - LittleEndian.putShort(buf, offset + LittleEndian.SHORT_SIZE, _fMultiLinespace); - } - - public void setDyaLine(short dyaLine) - { - _dyaLine = dyaLine; - } - - @Override - public boolean equals(Object o) - { - if (!(o instanceof LineSpacingDescriptor)) return false; - LineSpacingDescriptor lspd = (LineSpacingDescriptor)o; - - return _dyaLine == lspd._dyaLine && _fMultiLinespace == lspd._fMultiLinespace; - } - - @Override - public int hashCode() { - assert false : "hashCode not designed"; - return 42; // any arbitrary constant will do - } - - public boolean isEmpty() - { - return _dyaLine == 0 && _fMultiLinespace == 0; - } - - @Override - public String toString() - { - if ( isEmpty() ) - return "[LSPD] EMPTY"; - - return "[LSPD] (dyaLine: " + _dyaLine + "; fMultLinespace: " - + _fMultiLinespace + ")"; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/ListEntry.java b/src/scratchpad/src/org/apache/poi/hwpf/usermodel/ListEntry.java deleted file mode 100644 index d7158fac7..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/ListEntry.java +++ /dev/null @@ -1,30 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.usermodel; - -import org.apache.poi.hwpf.model.PAPX; -import org.apache.poi.util.Internal; - -public final class ListEntry extends Paragraph -{ - @Internal - ListEntry( PAPX papx, ParagraphProperties properties, Range parent ) - { - super( papx, properties, parent ); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/Notes.java b/src/scratchpad/src/org/apache/poi/hwpf/usermodel/Notes.java deleted file mode 100644 index 9e6cf567f..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/Notes.java +++ /dev/null @@ -1,53 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hwpf.usermodel; - -/** - * User-friendly interface to access document notes information - * - * @author Sergey Vladimirov (vlsergey {at} gmail {doc} com) - */ -public interface Notes -{ - /** - * Returns the location of note anchor in main textspace - */ - int getNoteAnchorPosition( int index ); - - /** - * Returns count of notes in document - */ - int getNotesCount(); - - /** - * Returns index of note (if exists, otherwise -1) with specified anchor - * position - */ - int getNoteIndexByAnchorPosition( int anchorPosition ); - - /** - * Returns the end offset of the text corresponding to the reference within - * the footnote text address space - */ - int getNoteTextEndOffset( int index ); - - /** - * Returns the start offset of the text corresponding to the reference - * within the footnote text address space - */ - int getNoteTextStartOffset( int index ); -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/NotesImpl.java b/src/scratchpad/src/org/apache/poi/hwpf/usermodel/NotesImpl.java deleted file mode 100644 index ec3b17f69..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/NotesImpl.java +++ /dev/null @@ -1,85 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hwpf.usermodel; - -import java.util.HashMap; -import java.util.Map; - -import org.apache.poi.hwpf.model.NotesTables; - -/** - * Default implementation of {@link Notes} interface - * - * @author Sergey Vladimirov (vlsergey {at} gmail {doc} com) - */ -public class NotesImpl implements Notes -{ - private Map anchorToIndexMap = null; - - private final NotesTables notesTables; - - public NotesImpl( NotesTables notesTables ) - { - this.notesTables = notesTables; - } - - public int getNoteAnchorPosition( int index ) - { - return notesTables.getDescriptor( index ).getStart(); - } - - public int getNoteIndexByAnchorPosition( int anchorPosition ) - { - updateAnchorToIndexMap(); - - Integer index = anchorToIndexMap - .get( Integer.valueOf( anchorPosition ) ); - if ( index == null ) - return -1; - - return index.intValue(); - } - - public int getNotesCount() - { - return notesTables.getDescriptorsCount(); - } - - public int getNoteTextEndOffset( int index ) - { - return notesTables.getTextPosition( index ).getEnd(); - } - - public int getNoteTextStartOffset( int index ) - { - return notesTables.getTextPosition( index ).getStart(); - } - - private void updateAnchorToIndexMap() - { - if ( anchorToIndexMap != null ) - return; - - Map result = new HashMap(); - for ( int n = 0; n < notesTables.getDescriptorsCount(); n++ ) - { - int anchorPosition = notesTables.getDescriptor( n ).getStart(); - result.put( Integer.valueOf( anchorPosition ), Integer.valueOf( n ) ); - } - this.anchorToIndexMap = result; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/ObjectPoolImpl.java b/src/scratchpad/src/org/apache/poi/hwpf/usermodel/ObjectPoolImpl.java deleted file mode 100644 index c672134ec..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/ObjectPoolImpl.java +++ /dev/null @@ -1,59 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hwpf.usermodel; - -import java.io.FileNotFoundException; -import java.io.IOException; - -import org.apache.poi.poifs.filesystem.DirectoryEntry; -import org.apache.poi.poifs.filesystem.Entry; -import org.apache.poi.poifs.filesystem.EntryUtils; -import org.apache.poi.util.Internal; - -@Internal -public class ObjectPoolImpl implements ObjectsPool -{ - private DirectoryEntry _objectPool; - - public ObjectPoolImpl( DirectoryEntry _objectPool ) - { - super(); - this._objectPool = _objectPool; - } - - public Entry getObjectById( String objId ) - { - if ( _objectPool == null ) - return null; - - try - { - return _objectPool.getEntry( objId ); - } - catch ( FileNotFoundException exc ) - { - return null; - } - } - - @Internal - public void writeTo( DirectoryEntry directoryEntry ) throws IOException - { - if ( _objectPool != null ) - EntryUtils.copyNodeRecursively( _objectPool, directoryEntry ); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/ObjectsPool.java b/src/scratchpad/src/org/apache/poi/hwpf/usermodel/ObjectsPool.java deleted file mode 100644 index d9f39d754..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/ObjectsPool.java +++ /dev/null @@ -1,24 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hwpf.usermodel; - -import org.apache.poi.poifs.filesystem.Entry; - -public interface ObjectsPool -{ - public Entry getObjectById( String objId ); -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/OfficeDrawing.java b/src/scratchpad/src/org/apache/poi/hwpf/usermodel/OfficeDrawing.java deleted file mode 100644 index 4bed04e49..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/OfficeDrawing.java +++ /dev/null @@ -1,190 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hwpf.usermodel; - -import org.apache.poi.ddf.EscherContainerRecord; - -/** - * User-friendly interface to office drawing objects. - *

    - * Some properties and enumeration constants description are quotes from the - * following sources: - *

      - *
    • [MS-ODRAW] -- v20110608; Office Drawing Binary File Format; Copyright (c) - * 2011 Microsoft Corporation. - *
    - * - * @author Sergey Vladimirov (vlsergey {at} gmail {dot} com) - */ -public interface OfficeDrawing -{ - - public enum HorizontalPositioning { - - /** - * The shape is horizontally offset by an absolute distance from the - * page element. - */ - ABSOLUTE, - - /** - * The shape is horizontally positioned at the center of the page - * element. - */ - CENTER, - - /** - * The shape is horizontally positioned like {@link #LEFT} on - * odd-numbered pages and like {@link #RIGHT} on even-numbered pages. - */ - INSIDE, - - /** - * The shape is horizontally positioned at the left side of the page - * element. - */ - LEFT, - - /** - * The shape is horizontally positioned like {@link #RIGHT} on - * odd-numbered pages and like {@link #LEFT} on even-numbered pages. - */ - OUTSIDE, - - /** - * The shape is horizontally positioned at the right side of the page - * element. - */ - RIGHT - } - - public enum HorizontalRelativeElement { - CHAR, MARGIN, PAGE, TEXT - } - - public enum VerticalPositioning { - - /** - * The shape is vertically offset by an absolute distance from the page - * element - */ - ABSOLUTE, - - /** - * The shape is vertically positioned at the bottom of the page element - */ - BOTTOM, - - /** - * The shape is vertically positioned in the center of the page element - */ - CENTER, - - /** - * The shape is vertically positioned like msopvTop on odd-numbered - * pages and like msopvBottom on even-numbered pages - */ - INSIDE, - - /** - * The shape is vertically positioned like {@link #BOTTOM} on - * odd-numbered pages and like {@link #TOP} on even-numbered pages - */ - OUTSIDE, - - /** - * The shape is vertically positioned at the top of the page element - */ - TOP - } - - public enum VerticalRelativeElement { - LINE, MARGIN, PAGE, TEXT - } - - /** - * Returns the type of horizontal positioning to use for a shape - * - * @return the type of horizontal positioning to use for a shape - */ - public HorizontalPositioning getHorizontalPositioning(); - - /** - * Specifies a page element relative to which a shape is horizontally - * positioned - * - * @return a page element relative to which a shape is horizontally - * positioned - */ - public HorizontalRelativeElement getHorizontalRelative(); - - /** - * Returns escher record that represent shape container (record type is - * 0xF004). Returned record has a child with record type - * 0xF00A and value of shape id equals to {@link #getShapeId()}. - * - * @return Returns office art shape container or null if not found - */ - public EscherContainerRecord getOfficeArtSpContainer(); - - /** - * Returns picture data if this shape has (single?) associated picture data - */ - byte[] getPictureData(); - - /** - * Bottom of the rectangle enclosing shape relative to the origin of the - * shape - */ - int getRectangleBottom(); - - /** - * Left of rectangle enclosing shape relative to the origin of the shape - */ - int getRectangleLeft(); - - /** - * Right of rectangle enclosing shape relative to the origin of the shape - */ - int getRectangleRight(); - - /** - * Top of rectangle enclosing shape relative to the origin of the shape - */ - int getRectangleTop(); - - /** - * Shape Identifier - */ - int getShapeId(); - - /** - * Specifies the type of vertical positioning to use for a shape - * - * @return return the type of vertical positioning to use for a shape - */ - public VerticalPositioning getVerticalPositioning(); - - /** - * Specifies a page element relative to which a shape is vertically - * positioned - * - * @return a page element relative to which a shape is vertically positioned - */ - public VerticalRelativeElement getVerticalRelativeElement(); - -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/OfficeDrawings.java b/src/scratchpad/src/org/apache/poi/hwpf/usermodel/OfficeDrawings.java deleted file mode 100644 index 58661aa8d..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/OfficeDrawings.java +++ /dev/null @@ -1,31 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hwpf.usermodel; - -import java.util.Collection; - -/** - * User-friendly interface to access document part's office drawings - * - * @author Sergey Vladimirov (vlsergey {at} gmail {dot} com) - */ -public interface OfficeDrawings -{ - OfficeDrawing getOfficeDrawingAt( int characterPosition ); - - Collection getOfficeDrawings(); -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/OfficeDrawingsImpl.java b/src/scratchpad/src/org/apache/poi/hwpf/usermodel/OfficeDrawingsImpl.java deleted file mode 100644 index 732879add..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/OfficeDrawingsImpl.java +++ /dev/null @@ -1,315 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hwpf.usermodel; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; - -import org.apache.poi.ddf.EscherTertiaryOptRecord; - -import org.apache.poi.ddf.DefaultEscherRecordFactory; -import org.apache.poi.ddf.EscherBSERecord; -import org.apache.poi.ddf.EscherBlipRecord; -import org.apache.poi.ddf.EscherContainerRecord; -import org.apache.poi.ddf.EscherOptRecord; -import org.apache.poi.ddf.EscherProperties; -import org.apache.poi.ddf.EscherRecord; -import org.apache.poi.ddf.EscherRecordFactory; -import org.apache.poi.ddf.EscherSimpleProperty; -import org.apache.poi.ddf.EscherSpRecord; -import org.apache.poi.hwpf.model.EscherRecordHolder; -import org.apache.poi.hwpf.model.FSPA; -import org.apache.poi.hwpf.model.FSPATable; - -public class OfficeDrawingsImpl implements OfficeDrawings -{ - private final EscherRecordHolder _escherRecordHolder; - private final FSPATable _fspaTable; - private final byte[] _mainStream; - - public OfficeDrawingsImpl( FSPATable fspaTable, - EscherRecordHolder escherRecordHolder, byte[] mainStream ) - { - this._fspaTable = fspaTable; - this._escherRecordHolder = escherRecordHolder; - this._mainStream = mainStream; - } - - private EscherBlipRecord getBitmapRecord( int bitmapIndex ) - { - List bContainers = _escherRecordHolder - .getBStoreContainers(); - if ( bContainers == null || bContainers.size() != 1 ) - return null; - - EscherContainerRecord bContainer = bContainers.get( 0 ); - final List bitmapRecords = bContainer.getChildRecords(); - - if ( bitmapRecords.size() < bitmapIndex ) - return null; - - EscherRecord imageRecord = bitmapRecords.get( bitmapIndex - 1 ); - - if ( imageRecord instanceof EscherBlipRecord ) - { - return (EscherBlipRecord) imageRecord; - } - - if ( imageRecord instanceof EscherBSERecord ) - { - EscherBSERecord bseRecord = (EscherBSERecord) imageRecord; - - EscherBlipRecord blip = bseRecord.getBlipRecord(); - if ( blip != null ) - { - return blip; - } - - if ( bseRecord.getOffset() > 0 ) - { - /* - * Blip stored in delay stream, which in a word doc, is the main - * stream - */ - EscherRecordFactory recordFactory = new DefaultEscherRecordFactory(); - EscherRecord record = recordFactory.createRecord( _mainStream, - bseRecord.getOffset() ); - - if ( record instanceof EscherBlipRecord ) - { - record.fillFields( _mainStream, bseRecord.getOffset(), - recordFactory ); - return (EscherBlipRecord) record; - } - } - } - - return null; - } - - private EscherContainerRecord getEscherShapeRecordContainer( - final int shapeId ) - { - for ( EscherContainerRecord spContainer : _escherRecordHolder - .getSpContainers() ) - { - EscherSpRecord escherSpRecord = spContainer - .getChildById( (short) 0xF00A ); - if ( escherSpRecord != null - && escherSpRecord.getShapeId() == shapeId ) - return spContainer; - } - - return null; - } - - private OfficeDrawing getOfficeDrawing( final FSPA fspa ) - { - return new OfficeDrawing() - { - public HorizontalPositioning getHorizontalPositioning() - { - int value = getTertiaryPropertyValue( - EscherProperties.GROUPSHAPE__POSH, -1 ); - - switch ( value ) - { - case 0: - return HorizontalPositioning.ABSOLUTE; - case 1: - return HorizontalPositioning.LEFT; - case 2: - return HorizontalPositioning.CENTER; - case 3: - return HorizontalPositioning.RIGHT; - case 4: - return HorizontalPositioning.INSIDE; - case 5: - return HorizontalPositioning.OUTSIDE; - } - - return HorizontalPositioning.ABSOLUTE; - } - - public HorizontalRelativeElement getHorizontalRelative() - { - int value = getTertiaryPropertyValue( - EscherProperties.GROUPSHAPE__POSRELH, -1 ); - - switch ( value ) - { - case 1: - return HorizontalRelativeElement.MARGIN; - case 2: - return HorizontalRelativeElement.PAGE; - case 3: - return HorizontalRelativeElement.TEXT; - case 4: - return HorizontalRelativeElement.CHAR; - } - - return HorizontalRelativeElement.TEXT; - } - - public EscherContainerRecord getOfficeArtSpContainer() - { - return getEscherShapeRecordContainer( getShapeId() ); - } - - public byte[] getPictureData() - { - EscherContainerRecord shapeDescription = getEscherShapeRecordContainer( getShapeId() ); - if ( shapeDescription == null ) - return null; - - EscherOptRecord escherOptRecord = shapeDescription - .getChildById( EscherOptRecord.RECORD_ID ); - if ( escherOptRecord == null ) - return null; - - EscherSimpleProperty escherProperty = escherOptRecord - .lookup( EscherProperties.BLIP__BLIPTODISPLAY ); - if ( escherProperty == null ) - return null; - - int bitmapIndex = escherProperty.getPropertyValue(); - EscherBlipRecord escherBlipRecord = getBitmapRecord( bitmapIndex ); - if ( escherBlipRecord == null ) - return null; - - return escherBlipRecord.getPicturedata(); - } - - public int getRectangleBottom() - { - return fspa.getYaBottom(); - } - - public int getRectangleLeft() - { - return fspa.getXaLeft(); - } - - public int getRectangleRight() - { - return fspa.getXaRight(); - } - - public int getRectangleTop() - { - return fspa.getYaTop(); - } - - public int getShapeId() - { - return fspa.getSpid(); - } - - private int getTertiaryPropertyValue( int propertyId, - int defaultValue ) - { - EscherContainerRecord shapeDescription = getEscherShapeRecordContainer( getShapeId() ); - if ( shapeDescription == null ) - return defaultValue; - - EscherTertiaryOptRecord escherTertiaryOptRecord = shapeDescription - .getChildById( EscherTertiaryOptRecord.RECORD_ID ); - if ( escherTertiaryOptRecord == null ) - return defaultValue; - - EscherSimpleProperty escherProperty = escherTertiaryOptRecord - .lookup( propertyId ); - if ( escherProperty == null ) - return defaultValue; - int value = escherProperty.getPropertyValue(); - - return value; - } - - public VerticalPositioning getVerticalPositioning() - { - int value = getTertiaryPropertyValue( - EscherProperties.GROUPSHAPE__POSV, -1 ); - - switch ( value ) - { - case 0: - return VerticalPositioning.ABSOLUTE; - case 1: - return VerticalPositioning.TOP; - case 2: - return VerticalPositioning.CENTER; - case 3: - return VerticalPositioning.BOTTOM; - case 4: - return VerticalPositioning.INSIDE; - case 5: - return VerticalPositioning.OUTSIDE; - } - - return VerticalPositioning.ABSOLUTE; - } - - public VerticalRelativeElement getVerticalRelativeElement() - { - int value = getTertiaryPropertyValue( - EscherProperties.GROUPSHAPE__POSV, -1 ); - - switch ( value ) - { - case 1: - return VerticalRelativeElement.MARGIN; - case 2: - return VerticalRelativeElement.PAGE; - case 3: - return VerticalRelativeElement.TEXT; - case 4: - return VerticalRelativeElement.LINE; - } - - return VerticalRelativeElement.TEXT; - } - - @Override - public String toString() - { - return "OfficeDrawingImpl: " + fspa.toString(); - } - }; - } - - public OfficeDrawing getOfficeDrawingAt( int characterPosition ) - { - final FSPA fspa = _fspaTable.getFspaFromCp( characterPosition ); - if ( fspa == null ) - return null; - - return getOfficeDrawing( fspa ); - } - - public Collection getOfficeDrawings() - { - List result = new ArrayList(); - for ( FSPA fspa : _fspaTable.getShapes() ) - { - result.add( getOfficeDrawing( fspa ) ); - } - return Collections.unmodifiableList( result ); - } -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/Paragraph.java b/src/scratchpad/src/org/apache/poi/hwpf/usermodel/Paragraph.java deleted file mode 100644 index 9da19fd3b..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/Paragraph.java +++ /dev/null @@ -1,628 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.usermodel; - -import java.util.NoSuchElementException; - -import org.apache.poi.hwpf.HWPFDocumentCore; -import org.apache.poi.hwpf.model.LFO; -import org.apache.poi.hwpf.model.ListLevel; -import org.apache.poi.hwpf.model.ListTables; -import org.apache.poi.hwpf.model.PAPX; -import org.apache.poi.hwpf.model.StyleSheet; -import org.apache.poi.hwpf.sprm.ParagraphSprmUncompressor; -import org.apache.poi.hwpf.sprm.SprmBuffer; -import org.apache.poi.hwpf.sprm.TableSprmCompressor; -import org.apache.poi.util.Internal; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; - -public class Paragraph extends Range implements Cloneable { - private final static POILogger log = POILogFactory.getLogger( Paragraph.class ); - - public final static short SPRM_JC = 0x2403; - public final static short SPRM_FSIDEBYSIDE = 0x2404; - public final static short SPRM_FKEEP = 0x2405; - public final static short SPRM_FKEEPFOLLOW = 0x2406; - public final static short SPRM_FPAGEBREAKBEFORE = 0x2407; - public final static short SPRM_BRCL = 0x2408; - public final static short SPRM_BRCP = 0x2409; - public final static short SPRM_ILVL = 0x260A; - public final static short SPRM_ILFO = 0x460B; - public final static short SPRM_FNOLINENUMB = 0x240C; - public final static short SPRM_CHGTABSPAPX = (short)0xC60D; - public final static short SPRM_DXARIGHT = (short)0x840E; - public final static short SPRM_DXALEFT = (short)0x840F; - public final static short SPRM_DXALEFT1 = (short)0x8411; - public final static short SPRM_DYALINE = 0x6412; - public final static short SPRM_DYABEFORE = (short)0xA413; - public final static short SPRM_DYAAFTER = (short)0xA414; - public final static short SPRM_CHGTABS = (short)0xC615; - public final static short SPRM_FINTABLE = 0x2416; - public final static short SPRM_FTTP = 0x2417; - public final static short SPRM_DXAABS = (short)0x8418; - public final static short SPRM_DYAABS = (short)0x8419; - public final static short SPRM_DXAWIDTH = (short)0x841A; - public final static short SPRM_PC = 0x261B; - public final static short SPRM_WR = 0x2423; - public final static short SPRM_BRCTOP = 0x6424; - public final static short SPRM_BRCLEFT = 0x6425; - public final static short SPRM_BRCBOTTOM = 0x6426; - public final static short SPRM_BRCRIGHT = 0x6427; - public final static short SPRM_BRCBAR = 0x6629; - public final static short SPRM_FNOAUTOHYPH = 0x242A; - public final static short SPRM_WHEIGHTABS = 0x442B; - public final static short SPRM_DCS = 0x442C; - public final static short SPRM_SHD80 = 0x442D; - public final static short SPRM_SHD = (short)0xC64D; - public final static short SPRM_DYAFROMTEXT = (short)0x842E; - public final static short SPRM_DXAFROMTEXT = (short)0x842F; - public final static short SPRM_FLOCKED = 0x2430; - public final static short SPRM_FWIDOWCONTROL = 0x2431; - public final static short SPRM_RULER = (short)0xC632; - public final static short SPRM_FKINSOKU = 0x2433; - public final static short SPRM_FWORDWRAP = 0x2434; - public final static short SPRM_FOVERFLOWPUNCT = 0x2435; - public final static short SPRM_FTOPLINEPUNCT = 0x2436; - public final static short SPRM_AUTOSPACEDE = 0x2437; - public final static short SPRM_AUTOSPACEDN = 0x2438; - public final static short SPRM_WALIGNFONT = 0x4439; - public final static short SPRM_FRAMETEXTFLOW = 0x443A; - public final static short SPRM_ANLD = (short)0xC63E; - public final static short SPRM_PROPRMARK = (short)0xC63F; - public final static short SPRM_OUTLVL = 0x2640; - public final static short SPRM_FBIDI = 0x2441; - public final static short SPRM_FNUMRMLNS = 0x2443; - public final static short SPRM_CRLF = 0x2444; - public final static short SPRM_NUMRM = (short)0xC645; - public final static short SPRM_USEPGSUSETTINGS = 0x2447; - public final static short SPRM_FADJUSTRIGHT = 0x2448; - - @Internal - public static Paragraph newParagraph( Range parent, PAPX papx ) - { - HWPFDocumentCore doc = parent._doc; - ListTables listTables = doc.getListTables(); - StyleSheet styleSheet = doc.getStyleSheet(); - - ParagraphProperties properties = new ParagraphProperties(); - properties.setIstd( papx.getIstd() ); - - properties = newParagraph_applyStyleProperties( styleSheet, papx, - properties ); - properties = ParagraphSprmUncompressor.uncompressPAP( properties, - papx.getGrpprl(), 2 ); - - if ( properties.getIlfo() != 0 && listTables != null ) - { - LFO lfo = null; - try - { - lfo = listTables.getLfo( properties.getIlfo() ); - } - catch ( NoSuchElementException exc ) - { - log.log( POILogger.WARN, "Paragraph refers to LFO #", - properties.getIlfo(), " that does not exists" ); - } - if ( lfo != null ) - { - final ListLevel listLevel = listTables.getLevel( lfo.getLsid(), - properties.getIlvl() ); - - if ( listLevel != null && listLevel.getGrpprlPapx() != null ) - { - properties = ParagraphSprmUncompressor.uncompressPAP( - properties, listLevel.getGrpprlPapx(), 0 ); - // reapply style and local PAPX properties - properties = newParagraph_applyStyleProperties( styleSheet, - papx, properties ); - properties = ParagraphSprmUncompressor.uncompressPAP( - properties, papx.getGrpprl(), 2 ); - } - } - } - - if ( properties.getIlfo() > 0 ) - return new ListEntry( papx, properties, parent ); - - return new Paragraph( papx, properties, parent ); - } - - protected static ParagraphProperties newParagraph_applyStyleProperties( - StyleSheet styleSheet, PAPX papx, ParagraphProperties properties ) - { - if ( styleSheet == null ) - return properties; - - int style = papx.getIstd(); - byte[] grpprl = styleSheet.getPAPX( style ); - return ParagraphSprmUncompressor.uncompressPAP( properties, grpprl, 2 ); - } - - protected short _istd; - protected ParagraphProperties _props; - protected SprmBuffer _papx; - - @Internal - Paragraph( PAPX papx, ParagraphProperties properties, Range parent ) - { - super( Math.max( parent._start, papx.getStart() ), Math.min( - parent._end, papx.getEnd() ), parent ); - _props = properties; - _papx = papx.getSprmBuf(); - _istd = papx.getIstd(); - } - - /** - * Returns the index of the style which applies to this - * Paragraph. Details of the style can be looked up - * from the {@link StyleSheet}, via - * {@link StyleSheet#getStyleDescription(int)} - */ - public short getStyleIndex() - { - return _istd; - } - - public boolean isInTable() - { - return _props.getFInTable(); - } - - /** - * @return true, if table trailer paragraph (last in table row), - * false otherwise - */ - public boolean isTableRowEnd() - { - return _props.getFTtp() || _props.getFTtpEmbedded(); - } - - public int getTableLevel() - { - return _props.getItap(); - } - - /** - * @return true, if the end of paragraph mark is really an end of - * cell mark for a nested table cell, false otherwise - */ - public boolean isEmbeddedCellMark() - { - return _props.getFInnerTableCell(); - } - - public int getJustification() - { - return _props.getJc(); - } - - public void setJustification(byte jc) - { - _props.setJc(jc); - _papx.updateSprm(SPRM_JC, jc); - } - - public boolean keepOnPage() - { - return _props.getFKeep(); - } - - public void setKeepOnPage(boolean fKeep) - { - _props.setFKeep(fKeep); - _papx.updateSprm(SPRM_FKEEP, fKeep); - } - - public boolean keepWithNext() - { - return _props.getFKeepFollow(); - } - - public void setKeepWithNext(boolean fKeepFollow) - { - _props.setFKeepFollow(fKeepFollow); - _papx.updateSprm(SPRM_FKEEPFOLLOW, fKeepFollow); - } - - public boolean pageBreakBefore() - { - return _props.getFPageBreakBefore(); - } - - public void setPageBreakBefore(boolean fPageBreak) - { - _props.setFPageBreakBefore(fPageBreak); - _papx.updateSprm(SPRM_FPAGEBREAKBEFORE, fPageBreak); - } - - public boolean isLineNotNumbered() - { - return _props.getFNoLnn(); - } - - public void setLineNotNumbered(boolean fNoLnn) - { - _props.setFNoLnn(fNoLnn); - _papx.updateSprm(SPRM_FNOLINENUMB, fNoLnn); - } - - public boolean isSideBySide() - { - return _props.getFSideBySide(); - } - - public void setSideBySide(boolean fSideBySide) - { - _props.setFSideBySide(fSideBySide); - _papx.updateSprm(SPRM_FSIDEBYSIDE, fSideBySide); - } - - public boolean isAutoHyphenated() - { - return !_props.getFNoAutoHyph(); - } - - public void setAutoHyphenated(boolean autoHyph) - { - _props.setFNoAutoHyph(!autoHyph); - _papx.updateSprm(SPRM_FNOAUTOHYPH, !autoHyph); - } - - public boolean isWidowControlled() - { - return _props.getFWidowControl(); - } - - public void setWidowControl(boolean widowControl) - { - _props.setFWidowControl(widowControl); - _papx.updateSprm(SPRM_FWIDOWCONTROL, widowControl); - } - - public int getIndentFromRight() - { - return _props.getDxaRight(); - } - - public void setIndentFromRight(int dxaRight) - { - _props.setDxaRight(dxaRight); - _papx.updateSprm(SPRM_DXARIGHT, (short)dxaRight); - } - - public int getIndentFromLeft() - { - return _props.getDxaLeft(); - } - - public void setIndentFromLeft(int dxaLeft) - { - _props.setDxaLeft(dxaLeft); - _papx.updateSprm(SPRM_DXALEFT, (short)dxaLeft); - } - - public int getFirstLineIndent() - { - return _props.getDxaLeft1(); - } - - public void setFirstLineIndent(int first) - { - _props.setDxaLeft1(first); - _papx.updateSprm(SPRM_DXALEFT1, (short)first); - } - - public LineSpacingDescriptor getLineSpacing() - { - return _props.getLspd(); - } - - public void setLineSpacing(LineSpacingDescriptor lspd) - { - _props.setLspd(lspd); - _papx.updateSprm(SPRM_DYALINE, lspd.toInt()); - } - - public int getSpacingBefore() - { - return _props.getDyaBefore(); - } - - public void setSpacingBefore(int before) - { - _props.setDyaBefore(before); - _papx.updateSprm(SPRM_DYABEFORE, (short)before); - } - - public int getSpacingAfter() - { - return _props.getDyaAfter(); - } - - public void setSpacingAfter(int after) - { - _props.setDyaAfter(after); - _papx.updateSprm(SPRM_DYAAFTER, (short)after); - } - - public boolean isKinsoku() - { - return _props.getFKinsoku(); - } - - public void setKinsoku(boolean kinsoku) - { - _props.setFKinsoku(kinsoku); - _papx.updateSprm(SPRM_FKINSOKU, kinsoku); - } - - public boolean isWordWrapped() - { - return _props.getFWordWrap(); - } - - public void setWordWrapped(boolean wrap) - { - _props.setFWordWrap(wrap); - _papx.updateSprm(SPRM_FWORDWRAP, wrap); - } - - public int getFontAlignment() - { - return _props.getWAlignFont(); - } - - public void setFontAlignment(int align) - { - _props.setWAlignFont(align); - _papx.updateSprm(SPRM_WALIGNFONT, (short)align); - } - - public boolean isVertical() - { - return _props.isFVertical(); - } - - public void setVertical(boolean vertical) - { - _props.setFVertical(vertical); - _papx.updateSprm(SPRM_FRAMETEXTFLOW, getFrameTextFlow()); - } - - public boolean isBackward() - { - return _props.isFBackward(); - } - - public void setBackward(boolean bward) - { - _props.setFBackward(bward); - _papx.updateSprm(SPRM_FRAMETEXTFLOW, getFrameTextFlow()); - } - - public BorderCode getTopBorder() - { - return _props.getBrcTop(); - } - - public void setTopBorder(BorderCode top) - { - _props.setBrcTop(top); - _papx.updateSprm(SPRM_BRCTOP, top.toInt()); - } - - public BorderCode getLeftBorder() - { - return _props.getBrcLeft(); - } - - public void setLeftBorder(BorderCode left) - { - _props.setBrcLeft(left); - _papx.updateSprm(SPRM_BRCLEFT, left.toInt()); - } - - public BorderCode getBottomBorder() - { - return _props.getBrcBottom(); - } - - public void setBottomBorder(BorderCode bottom) - { - _props.setBrcBottom(bottom); - _papx.updateSprm(SPRM_BRCBOTTOM, bottom.toInt()); - } - - public BorderCode getRightBorder() - { - return _props.getBrcRight(); - } - - public void setRightBorder(BorderCode right) - { - _props.setBrcRight(right); - _papx.updateSprm(SPRM_BRCRIGHT, right.toInt()); - } - - public BorderCode getBarBorder() - { - return _props.getBrcBar(); - } - - public void setBarBorder(BorderCode bar) - { - _props.setBrcBar(bar); - _papx.updateSprm(SPRM_BRCBAR, bar.toInt()); - } - - public ShadingDescriptor getShading() - { - return _props.getShd(); - } - - public void setShading(ShadingDescriptor shd) - { - _props.setShd(shd); - //TODO: remove old one - _papx.addSprm( SPRM_SHD, shd.serialize() ); - } - - public DropCapSpecifier getDropCap() - { - return _props.getDcs(); - } - - public void setDropCap(DropCapSpecifier dcs) - { - _props.setDcs(dcs); - _papx.updateSprm(SPRM_DCS, dcs.toShort()); - } - - /** - * Returns the ilfo, an index to the document's hpllfo, which - * describes the automatic number formatting of the paragraph. - * A value of zero means it isn't numbered. - */ - public int getIlfo() - { - return _props.getIlfo(); - } - - /** - * Returns the multi-level indent for the paragraph. Will be - * zero for non-list paragraphs, and the first level of any - * list. Subsequent levels in hold values 1-8. - */ - public int getIlvl() - { - return _props.getIlvl(); - } - - /** - * Returns the heading level (1-8), or 9 if the paragraph - * isn't in a heading style. - */ - public int getLvl() - { - return _props.getLvl(); - } - - void setTableRowEnd(TableProperties props) - { - setTableRowEnd(true); - byte[] grpprl = TableSprmCompressor.compressTableProperty(props); - _papx.append(grpprl); - } - - private void setTableRowEnd(boolean val) - { - _props.setFTtp(val); - _papx.updateSprm(SPRM_FTTP, val); - } - - /** - * Returns number of tabs stops defined for paragraph. Must be >= 0 and <= - * 64. - * - * @return number of tabs stops defined for paragraph. Must be >= 0 and <= - * 64 - */ - public int getTabStopsNumber() - { - return _props.getItbdMac(); - } - - /** - * Returns array of positions of itbdMac tab stops - * - * @return array of positions of itbdMac tab stops - */ - public int[] getTabStopsPositions() - { - return _props.getRgdxaTab(); - } - - public HWPFList getList() - { - if ( getIlfo() == 0x000 || getIlfo() == 0xF801 ) - { - throw new IllegalStateException( "Paragraph not in list" ); - } - HWPFList hwpfList = new HWPFList( getDocument().getStyleSheet(), - getDocument().getListTables(), getIlfo() ); - return hwpfList; - } - - public boolean isInList() - { - return getIlfo() != 0x000 && getIlfo() != 0xF801; - } - - /** - * Clone the ParagraphProperties object associated with this - * Paragraph, so that you can apply the same properties to - * another Paragraph. - */ - public ParagraphProperties cloneProperties() { - try { - return (ParagraphProperties)_props.clone(); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - public Object clone() throws CloneNotSupportedException - { - Paragraph p = (Paragraph)super.clone(); - p._props = (ParagraphProperties)_props.clone(); - //p._baseStyle = _baseStyle; - p._papx = new SprmBuffer(0); - return p; - } - - private short getFrameTextFlow() - { - short retVal = 0; - if (_props.isFVertical()) - { - retVal |= 1; - } - if (_props.isFBackward()) - { - retVal |= 2; - } - if (_props.isFRotateFont()) - { - retVal |= 4; - } - return retVal; - } - - @Override - public String toString() - { - return "Paragraph [" + getStartOffset() + "; " + getEndOffset() + ")"; - } - - @Internal - public ParagraphProperties getProps() { - return _props; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/ParagraphProperties.java b/src/scratchpad/src/org/apache/poi/hwpf/usermodel/ParagraphProperties.java deleted file mode 100644 index 1dbeae4f8..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/ParagraphProperties.java +++ /dev/null @@ -1,334 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.usermodel; - -import org.apache.poi.hwpf.model.types.PAPAbstractType; - -public final class ParagraphProperties extends PAPAbstractType implements - Cloneable -{ - - private boolean jcLogical = false; - - public ParagraphProperties() - { - setAnld( new byte[84] ); - setPhe( new byte[12] ); - } - - public Object clone() throws CloneNotSupportedException - { - ParagraphProperties pp = (ParagraphProperties) super.clone(); - pp.setAnld( getAnld().clone() ); - pp.setBrcTop( (BorderCode) getBrcTop().clone() ); - pp.setBrcLeft( (BorderCode) getBrcLeft().clone() ); - pp.setBrcBottom( (BorderCode) getBrcBottom().clone() ); - pp.setBrcRight( (BorderCode) getBrcRight().clone() ); - pp.setBrcBetween( (BorderCode) getBrcBetween().clone() ); - pp.setBrcBar( (BorderCode) getBrcBar().clone() ); - pp.setDcs( getDcs().clone() ); - pp.setLspd( (LineSpacingDescriptor) getLspd().clone() ); - pp.setShd( getShd().clone() ); - pp.setPhe( getPhe().clone() ); - return pp; - } - - public BorderCode getBarBorder() - { - return super.getBrcBar(); - } - - public BorderCode getBottomBorder() - { - return super.getBrcBottom(); - } - - public DropCapSpecifier getDropCap() - { - return super.getDcs(); - } - - public int getFirstLineIndent() - { - return super.getDxaLeft1(); - } - - public int getFontAlignment() - { - return super.getWAlignFont(); - } - - public int getIndentFromLeft() - { - return super.getDxaLeft(); - } - - public int getIndentFromRight() - { - return super.getDxaRight(); - } - - public int getJustification() - { - if ( jcLogical ) - { - if ( !getFBiDi() ) - return getJc(); - - switch ( getJc() ) - { - case 0: - return 2; - case 2: - return 0; - default: - return getJc(); - } - } - - return getJc(); - } - - public BorderCode getLeftBorder() - { - return super.getBrcLeft(); - } - - public LineSpacingDescriptor getLineSpacing() - { - return super.getLspd(); - } - - public BorderCode getRightBorder() - { - return super.getBrcRight(); - } - - public ShadingDescriptor getShading() - { - return super.getShd(); - } - - public int getSpacingAfter() - { - return super.getDyaAfter(); - } - - public int getSpacingBefore() - { - return super.getDyaBefore(); - } - - public BorderCode getTopBorder() - { - return super.getBrcTop(); - } - - public boolean isAutoHyphenated() - { - return !super.getFNoAutoHyph(); - } - - public boolean isBackward() - { - return super.isFBackward(); - } - - public boolean isKinsoku() - { - return super.getFKinsoku(); - } - - public boolean isLineNotNumbered() - { - return super.getFNoLnn(); - } - - public boolean isSideBySide() - { - return super.getFSideBySide(); - } - - public boolean isVertical() - { - return super.isFVertical(); - } - - public boolean isWidowControlled() - { - return super.getFWidowControl(); - } - - public boolean isWordWrapped() - { - return super.getFWordWrap(); - } - - public boolean keepOnPage() - { - return super.getFKeep(); - } - - public boolean keepWithNext() - { - return super.getFKeepFollow(); - } - - public boolean pageBreakBefore() - { - return super.getFPageBreakBefore(); - } - - public void setAutoHyphenated( boolean auto ) - { - super.setFNoAutoHyph( !auto ); - } - - public void setBackward( boolean bward ) - { - super.setFBackward( bward ); - } - - public void setBarBorder( BorderCode bar ) - { - super.setBrcBar( bar ); - } - - public void setBottomBorder( BorderCode bottom ) - { - super.setBrcBottom( bottom ); - } - - public void setDropCap( DropCapSpecifier dcs ) - { - super.setDcs( dcs ); - } - - public void setFirstLineIndent( int first ) - { - super.setDxaLeft1( first ); - } - - public void setFontAlignment( int align ) - { - super.setWAlignFont( align ); - } - - public void setIndentFromLeft( int dxaLeft ) - { - super.setDxaLeft( dxaLeft ); - } - - public void setIndentFromRight( int dxaRight ) - { - super.setDxaRight( dxaRight ); - } - - public void setJustification( byte jc ) - { - super.setJc( jc ); - this.jcLogical = false; - } - - public void setJustificationLogical( byte jc ) - { - super.setJc( jc ); - this.jcLogical = true; - } - - public void setKeepOnPage( boolean fKeep ) - { - super.setFKeep( fKeep ); - } - - public void setKeepWithNext( boolean fKeepFollow ) - { - super.setFKeepFollow( fKeepFollow ); - } - - public void setKinsoku( boolean kinsoku ) - { - super.setFKinsoku( kinsoku ); - } - - public void setLeftBorder( BorderCode left ) - { - super.setBrcLeft( left ); - } - - public void setLineNotNumbered( boolean fNoLnn ) - { - super.setFNoLnn( fNoLnn ); - } - - public void setLineSpacing( LineSpacingDescriptor lspd ) - { - super.setLspd( lspd ); - } - - public void setPageBreakBefore( boolean fPageBreak ) - { - super.setFPageBreakBefore( fPageBreak ); - } - - public void setRightBorder( BorderCode right ) - { - super.setBrcRight( right ); - } - - public void setShading( ShadingDescriptor shd ) - { - super.setShd( shd ); - } - - public void setSideBySide( boolean fSideBySide ) - { - super.setFSideBySide( fSideBySide ); - } - - public void setSpacingAfter( int after ) - { - super.setDyaAfter( after ); - } - - public void setSpacingBefore( int before ) - { - super.setDyaBefore( before ); - } - - public void setTopBorder( BorderCode top ) - { - super.setBrcTop( top ); - } - - public void setVertical( boolean vertical ) - { - super.setFVertical( vertical ); - } - - public void setWidowControl( boolean widowControl ) - { - super.setFWidowControl( widowControl ); - } - - public void setWordWrapped( boolean wrap ) - { - super.setFWordWrap( wrap ); - } - -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/Picture.java b/src/scratchpad/src/org/apache/poi/hwpf/usermodel/Picture.java deleted file mode 100644 index a7ed1adc4..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/Picture.java +++ /dev/null @@ -1,598 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.usermodel; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.util.Collections; -import java.util.List; -import java.util.zip.InflaterInputStream; - -import org.apache.poi.ddf.EscherBSERecord; -import org.apache.poi.ddf.EscherBlipRecord; -import org.apache.poi.ddf.EscherComplexProperty; -import org.apache.poi.ddf.EscherOptRecord; -import org.apache.poi.ddf.EscherProperties; -import org.apache.poi.ddf.EscherProperty; -import org.apache.poi.ddf.EscherRecord; -import org.apache.poi.hwpf.model.PICF; -import org.apache.poi.hwpf.model.PICFAndOfficeArtData; -import org.apache.poi.util.PngUtils; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.apache.poi.util.StringUtil; - -/** - * Represents embedded picture extracted from Word Document - */ -public final class Picture { - private static final POILogger log = POILogFactory - .getLogger( Picture.class ); - - public static final byte[] COMPRESSED1 = { (byte) 0xFE, 0x78, (byte) 0xDA }; - - public static final byte[] COMPRESSED2 = { (byte) 0xFE, 0x78, (byte) 0x9C }; - - public static final byte[] IHDR = new byte[] { 'I', 'H', 'D', 'R' }; - - @Deprecated - private static final byte[] PNG = new byte[] { (byte) 0x89, 0x50, 0x4E, - 0x47, 0x0D, 0x0A, 0x1A, 0x0A }; - - private static int getBigEndianInt( byte[] data, int offset ) - { - return ( ( ( data[offset] & 0xFF ) << 24 ) - + ( ( data[offset + 1] & 0xFF ) << 16 ) - + ( ( data[offset + 2] & 0xFF ) << 8 ) + ( data[offset + 3] & 0xFF ) ); - } - - private static int getBigEndianShort( byte[] data, int offset ) - { - return ( ( ( data[offset] & 0xFF ) << 8 ) + ( data[offset + 1] & 0xFF ) ); - } - - private static boolean matchSignature( byte[] pictureData, - byte[] signature, int offset ) - { - boolean matched = offset < pictureData.length; - for ( int i = 0; ( i + offset ) < pictureData.length - && i < signature.length; i++ ) - { - if ( pictureData[i + offset] != signature[i] ) - { - matched = false; - break; - } - } - return matched; - } - - private PICF _picf; - private PICFAndOfficeArtData _picfAndOfficeArtData; - private final List _blipRecords; - - private byte[] content; - private int dataBlockStartOfsset; - - private int height = -1; - private int width = -1; - - /** - * Builds a Picture object for a Picture stored as - * Escher. - * TODO We need to pass in the PICF data too somehow! - */ - public Picture( EscherBlipRecord blipRecord ) - { - this._blipRecords = Collections.singletonList(blipRecord); - } - - /** - * Builds a Picture object for a Picture stored in the - * DataStream - */ - public Picture( int dataBlockStartOfsset, byte[] _dataStream, boolean fillBytes ) { // NOSONAR - _picfAndOfficeArtData = new PICFAndOfficeArtData( _dataStream, dataBlockStartOfsset ); - _picf = _picfAndOfficeArtData.getPicf(); - - this.dataBlockStartOfsset = dataBlockStartOfsset; - - if ( _picfAndOfficeArtData.getBlipRecords() != null) { - _blipRecords = _picfAndOfficeArtData.getBlipRecords(); - } else { - _blipRecords = Collections.emptyList(); - } - - if ( fillBytes ) { - fillImageContent(); - } - } - - private void fillImageContent() - { - if ( content != null && content.length > 0 ) - return; - - byte[] rawContent = getRawContent(); - - /* - * HACK: Detect compressed images. In reality there should be some way - * to determine this from the first 32 bytes, but I can't see any - * similarity between all the samples I have obtained, nor any - * similarity in the data block contents. - */ - if ( matchSignature( rawContent, COMPRESSED1, 32 ) - || matchSignature( rawContent, COMPRESSED2, 32 ) ) - { - try - { - InflaterInputStream in = new InflaterInputStream( - new ByteArrayInputStream( rawContent, 33, - rawContent.length - 33 ) ); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - byte[] buf = new byte[4096]; - int readBytes; - while ( ( readBytes = in.read( buf ) ) > 0 ) - { - out.write( buf, 0, readBytes ); - } - content = out.toByteArray(); - } - catch ( IOException e ) - { - /* - * Problems reading from the actual ByteArrayInputStream should - * never happen so this will only ever be a ZipException. - */ - log.log( POILogger.INFO, - "Possibly corrupt compression or non-compressed data", - e ); - } - } - else - { - // Raw data is not compressed. - content = rawContent; - - //PNG created on MAC may have a 16-byte prefix which prevents successful reading. - //Just cut it off!. - if (PngUtils.matchesPngHeader(content, 16)) - { - byte[] png = new byte[content.length-16]; - System.arraycopy(content, 16, png, 0, png.length); - content = png; - } - } - } - - private void fillJPGWidthHeight() - { - /* - * http://www.codecomments.com/archive281-2004-3-158083.html - * - * Algorithm proposed by Patrick TJ McPhee: - * - * read 2 bytes make sure they are 'ffd8'x repeatedly: read 2 bytes make - * sure the first one is 'ff'x if the second one is 'd9'x stop else if - * the second one is c0 or c2 (or possibly other values ...) skip 2 - * bytes read one byte into depth read two bytes into height read two - * bytes into width else read two bytes into length skip forward - * length-2 bytes - * - * Also used Ruby code snippet from: - * http://www.bigbold.com/snippets/posts/show/805 for reference - */ - byte[] jpegContent = getContent(); - - int pointer = 2; - int firstByte = jpegContent[pointer]; - int secondByte = jpegContent[pointer + 1]; - int endOfPicture = jpegContent.length; - while ( pointer < endOfPicture - 1 ) - { - do - { - firstByte = jpegContent[pointer]; - secondByte = jpegContent[pointer + 1]; - pointer += 2; - } - while ( !( firstByte == (byte) 0xFF ) && pointer < endOfPicture - 1 ); - - if ( firstByte == ( (byte) 0xFF ) && pointer < endOfPicture - 1 ) - { - if ( secondByte == (byte) 0xD9 || secondByte == (byte) 0xDA ) - { - break; - } - else if ( ( secondByte & 0xF0 ) == 0xC0 - && secondByte != (byte) 0xC4 - && secondByte != (byte) 0xC8 - && secondByte != (byte) 0xCC ) - { - pointer += 5; - this.height = getBigEndianShort( jpegContent, pointer ); - this.width = getBigEndianShort( jpegContent, pointer + 2 ); - break; - } - else - { - pointer++; - pointer++; - int length = getBigEndianShort( jpegContent, pointer ); - pointer += length; - } - } - else - { - pointer++; - } - } - } - - void fillPNGWidthHeight() - { - byte[] pngContent = getContent(); - /* - * Used PNG file format description from - * http://www.wotsit.org/download.asp?f=png - */ - int HEADER_START = PNG.length + 4; - if ( matchSignature( pngContent, IHDR, HEADER_START ) ) - { - int IHDR_CHUNK_WIDTH = HEADER_START + 4; - this.width = getBigEndianInt( pngContent, IHDR_CHUNK_WIDTH ); - this.height = getBigEndianInt( pngContent, IHDR_CHUNK_WIDTH + 4 ); - } - } - - private void fillWidthHeight() - { - PictureType pictureType = suggestPictureType(); - // trying to extract width and height from pictures content: - switch ( pictureType ) - { - case JPEG: - fillJPGWidthHeight(); - break; - case PNG: - fillPNGWidthHeight(); - break; - default: - // unsupported; - break; - } - } - - /** - * @return picture's content as byte array - */ - public byte[] getContent() - { - fillImageContent(); - return content; - } - - /** - * @return The amount the picture has been cropped on the left in twips - * @deprecated POI 3.8 beta 4. - */ - @Deprecated - public int getDxaCropLeft() - { - // TODO: use new properties - // if (_picfAndOfficeArtData == null || _picfAndOfficeArtData.getShape() - // == null) - // return 0; - // - // final EscherContainerRecord shape = _picfAndOfficeArtData.getShape(); - // EscherOptRecord optRecord = shape.getChildById( (short) 0xF00B ); - // if (optRecord == null) - // return 0; - // - // EscherProperty property = optRecord.lookup( 0x0102 ); - // if (property == null || !(property instanceof EscherSimpleProperty)) - // return 0; - // - // EscherSimpleProperty simpleProperty = (EscherSimpleProperty) - // property; - // return simpleProperty.getPropertyValue(); - - return _picf.getDxaReserved1(); - } - - /** - * @return The amount the picture has been cropped on the right in twips - * @deprecated POI 3.8 beta 4. - */ - @Deprecated - public int getDxaCropRight() - { - return _picf.getDxaReserved2(); - } - - /** - * Gets the initial width of the picture, in twips, prior to cropping or - * scaling. - * - * @return the initial width of the picture in twips - */ - public int getDxaGoal() - { - return _picf.getDxaGoal(); - } - - /** - * @return The amount the picture has been cropped on the bottom in twips - * @deprecated POI 3.8 beta 5. - */ - @Deprecated - public int getDyaCropBottom() - { - return _picf.getDyaReserved2(); - } - - /** - * @return The amount the picture has been cropped on the top in twips - * @deprecated POI 3.8 beta 5. - */ - @Deprecated - public int getDyaCropTop() - { - return _picf.getDyaReserved1(); - } - - /** - * Gets the initial height of the picture, in twips, prior to cropping or - * scaling. - * - * @return the initial width of the picture in twips - */ - public int getDyaGoal() - { - return _picf.getDyaGoal(); - } - - /** - * returns pixel height of the picture or -1 if dimensions determining was - * failed - */ - public int getHeight() - { - if ( height == -1 ) - { - fillWidthHeight(); - } - return height; - } - - /** - * @return Horizontal scaling factor supplied by user expressed in .001% - * units - */ - public int getHorizontalScalingFactor() - { - return _picf.getMx(); - } - - /** - * Returns the MIME type for the image - * - * @return MIME-type for known types of image or "image/unknown" if unknown - */ - public String getMimeType() - { - return suggestPictureType().getMime(); - } - - /** - * Returns picture's content as stored in the Word file, i.e. possibly in - * compressed form. - * - * @return picture's content as it stored in Word file or an empty byte array - * if it cannot be read. - */ - public byte[] getRawContent() - { - if (_blipRecords == null || _blipRecords.size() != 1) { - return new byte[0]; - } - - EscherRecord escherRecord = _blipRecords.get( 0 ); - if ( escherRecord instanceof EscherBlipRecord ) - { - return ( (EscherBlipRecord) escherRecord ).getPicturedata(); - } - - if ( escherRecord instanceof EscherBSERecord ) - { - EscherBlipRecord blip = ( (EscherBSERecord) escherRecord ).getBlipRecord(); - if (blip != null) { - return blip.getPicturedata(); - - } - } - return new byte[0]; - } - - /** - * - * @return size in bytes of the picture - */ - public int getSize() - { - return getContent().length; - } - - /** - * @return The offset of this picture in the picture bytes, used when - * matching up with {@link CharacterRun#getPicOffset()} - */ - public int getStartOffset() - { - return dataBlockStartOfsset; - } - - /** - * @return Vertical scaling factor supplied by user expressed in .001% units - */ - public int getVerticalScalingFactor() - { - return _picf.getMy(); - } - - /** - * returns pixel width of the picture or -1 if dimensions determining was - * failed - */ - public int getWidth() - { - if ( width == -1 ) - { - fillWidthHeight(); - } - return width; - } - - /** - * returns the description stored in the alternative text - * - * @return pictue description - */ - public String getDescription() - { - for(EscherRecord escherRecord : _picfAndOfficeArtData.getShape().getChildRecords()){ - if(escherRecord instanceof EscherOptRecord){ - EscherOptRecord escherOptRecord = (EscherOptRecord) escherRecord; - for(EscherProperty property : escherOptRecord.getEscherProperties()){ - if(EscherProperties.GROUPSHAPE__DESCRIPTION == property.getPropertyNumber()){ - byte[] complexData = ((EscherComplexProperty)property).getComplexData(); - return StringUtil.getFromUnicodeLE(complexData,0,complexData.length/2-1); - } - } - } - } - - return null; - } - - /** - * tries to suggest extension for picture's file by matching signatures of - * popular image formats to first bytes of picture's contents - * - * @return suggested file extension - */ - public String suggestFileExtension() - { - return suggestPictureType().getExtension(); - } - - /** - * Tries to suggest a filename: hex representation of picture structure - * offset in "Data" stream plus extension that is tried to determine from - * first byte of picture's content. - * - * @return suggested file name - */ - public String suggestFullFileName() - { - String fileExt = suggestFileExtension(); - return Integer.toHexString( dataBlockStartOfsset ) - + ( fileExt.length() > 0 ? "." + fileExt : "" ); - } - - public PictureType suggestPictureType() - { - if (_blipRecords == null || _blipRecords.size() != 1 ) { - return PictureType.UNKNOWN; - } - - EscherRecord escherRecord = _blipRecords.get( 0 ); - switch ( escherRecord.getRecordId() ) - { - case (short) 0xF007: - { - EscherBSERecord bseRecord = (EscherBSERecord) escherRecord; - switch ( bseRecord.getBlipTypeWin32() ) - { - case 0x00: - return PictureType.UNKNOWN; - case 0x01: - return PictureType.UNKNOWN; - case 0x02: - return PictureType.EMF; - case 0x03: - return PictureType.WMF; - case 0x04: - return PictureType.PICT; - case 0x05: - return PictureType.JPEG; - case 0x06: - return PictureType.PNG; - case 0x07: - return PictureType.BMP; - case 0x11: - return PictureType.TIFF; - case 0x12: - return PictureType.JPEG; - default: - return PictureType.UNKNOWN; - } - } - case (short) 0xF01A: - return PictureType.EMF; - case (short) 0xF01B: - return PictureType.WMF; - case (short) 0xF01C: - return PictureType.PICT; - case (short) 0xF01D: - return PictureType.JPEG; - case (short) 0xF01E: - return PictureType.PNG; - case (short) 0xF01F: - return PictureType.BMP; - case (short) 0xF029: - return PictureType.TIFF; - case (short) 0xF02A: - return PictureType.JPEG; - default: - return PictureType.UNKNOWN; - } - } - - /** - * Writes Picture's content bytes to specified OutputStream. Is useful when - * there is need to write picture bytes directly to stream, omitting its - * representation in memory as distinct byte array. - * - * @param out - * a stream to write to - * @throws IOException - * if some exception is occured while writing to specified out - */ - public void writeImageContent( OutputStream out ) throws IOException - { - byte[] c = getContent(); - if ( c != null && c.length > 0 ) - { - out.write( c, 0, c.length ); - } - } - -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/PictureType.java b/src/scratchpad/src/org/apache/poi/hwpf/usermodel/PictureType.java deleted file mode 100644 index e630925dc..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/PictureType.java +++ /dev/null @@ -1,106 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hwpf.usermodel; - -/** - * Picture types supported by MS Word format - * - * @author Sergey Vladimirov (vlsergey {at} gmail {dot} com) - */ -public enum PictureType -{ - BMP( "image/bmp", "bmp", new byte[][] { { 'B', 'M' } } ), - - EMF( "image/x-emf", "emf", new byte[][] { { 0x01, 0x00, 0x00, 0x00 } } ), - - GIF( "image/gif", "gif", new byte[][] { { 'G', 'I', 'F' } } ), - - JPEG( "image/jpeg", "jpg", new byte[][] { { (byte) 0xFF, (byte) 0xD8 } } ), - - PICT( "image/pict", ".pict", new byte[0][] ), - - PNG( "image/png", "png", new byte[][] { { (byte) 0x89, 0x50, 0x4E, 0x47, - 0x0D, 0x0A, 0x1A, 0x0A } } ), - - TIFF( "image/tiff", "tiff", new byte[][] { { 0x49, 0x49, 0x2A, 0x00 }, - { 0x4D, 0x4D, 0x00, 0x2A } } ), - - UNKNOWN( "image/unknown", "", new byte[][] {} ), - - WMF( "image/x-wmf", "wmf", new byte[][] { - { (byte) 0xD7, (byte) 0xCD, (byte) 0xC6, (byte) 0x9A, 0x00, 0x00 }, - { 0x01, 0x00, 0x09, 0x00, 0x00, 0x03 } } ); - - public static PictureType findMatchingType( byte[] pictureContent ) - { - for ( PictureType pictureType : PictureType.values() ) - for ( byte[] signature : pictureType.getSignatures() ) - if ( matchSignature( pictureContent, signature ) ) - return pictureType; - - // TODO: DIB, PICT - return PictureType.UNKNOWN; - } - - private static boolean matchSignature( byte[] pictureData, byte[] signature ) - { - if ( pictureData.length < signature.length ) - return false; - - for ( int i = 0; i < signature.length; i++ ) - if ( pictureData[i] != signature[i] ) - return false; - - return true; - } - - private String _extension; - - private String _mime; - - private byte[][] _signatures; - - private PictureType( String mime, String extension, byte[][] signatures ) - { - this._mime = mime; - this._extension = extension; - this._signatures = signatures.clone(); - } - - public String getExtension() - { - return _extension; - } - - public String getMime() - { - return _mime; - } - - public byte[][] getSignatures() - { - return _signatures; - } - - public boolean matchSignature( byte[] pictureData ) - { - for ( byte[] signature : getSignatures() ) - if ( matchSignature( signature, pictureData ) ) - return true; - return false; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/Range.java b/src/scratchpad/src/org/apache/poi/hwpf/usermodel/Range.java deleted file mode 100644 index 10b3f963c..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/Range.java +++ /dev/null @@ -1,1195 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.usermodel; - -import java.lang.ref.WeakReference; -import java.util.List; - -import org.apache.poi.hwpf.HWPFDocument; -import org.apache.poi.hwpf.HWPFDocumentCore; -import org.apache.poi.hwpf.model.CHPX; -import org.apache.poi.hwpf.model.FileInformationBlock; -import org.apache.poi.hwpf.model.PAPX; -import org.apache.poi.hwpf.model.PropertyNode; -import org.apache.poi.hwpf.model.SEPX; -import org.apache.poi.hwpf.model.StyleSheet; -import org.apache.poi.hwpf.model.SubdocumentType; -import org.apache.poi.hwpf.sprm.CharacterSprmCompressor; -import org.apache.poi.hwpf.sprm.ParagraphSprmCompressor; -import org.apache.poi.hwpf.sprm.SprmBuffer; -import org.apache.poi.util.Internal; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; - -/** - * This class is the central class of the HWPF object model. All properties that - * apply to a range of characters in a Word document extend this class. - * - * It is possible to insert text and/or properties at the beginning or end of a - * range. - * - * Ranges are only valid if there hasn't been an insert in a prior Range since - * the Range's creation. Once an element (text, paragraph, etc.) has been - * inserted into a Range, subsequent Ranges become unstable. - * - * @author Ryan Ackley - */ -public class Range { // TODO -instantiable superclass - - private POILogger logger = POILogFactory.getLogger( Range.class ); - - /** - * @deprecated POI 3.8 beta 5 - */ - @Deprecated - public static final int TYPE_PARAGRAPH = 0; - - /** - * @deprecated POI 3.8 beta 5 - */ - @Deprecated - public static final int TYPE_CHARACTER = 1; - - /** - * @deprecated POI 3.8 beta 5 - */ - @Deprecated - public static final int TYPE_SECTION = 2; - - /** - * @deprecated POI 3.8 beta 5 - */ - @Deprecated - public static final int TYPE_TEXT = 3; - - /** - * @deprecated POI 3.8 beta 5 - */ - @Deprecated - public static final int TYPE_LISTENTRY = 4; - - /** - * @deprecated POI 3.8 beta 5 - */ - @Deprecated - public static final int TYPE_TABLE = 5; - - /** - * @deprecated POI 3.8 beta 5 - */ - @Deprecated - public static final int TYPE_UNDEFINED = 6; - - /** Needed so inserts and deletes will ripple up through containing Ranges */ - private final WeakReference _parent; - - /** The starting character offset of this range. */ - protected final int _start; - - /** The ending character offset of this range. */ - protected int _end; - - /** The document this range belongs to. */ - protected final HWPFDocumentCore _doc; - - /** Have we loaded the section indexes yet */ - boolean _sectionRangeFound; - - /** All sections that belong to the document this Range belongs to. */ - protected final List _sections; - - /** The start index in the sections list for this Range */ - protected int _sectionStart; - - /** The end index in the sections list for this Range. */ - protected int _sectionEnd; - - /** Have we loaded the paragraph indexes yet. */ - protected boolean _parRangeFound; - - /** All paragraphs that belong to the document this Range belongs to. */ - protected final List _paragraphs; - - /** The start index in the paragraphs list for this Range, inclusive */ - protected int _parStart; - - /** The end index in the paragraphs list for this Range, exclusive */ - protected int _parEnd; - - /** Have we loaded the characterRun indexes yet. */ - protected boolean _charRangeFound; - - /** All CharacterRuns that belong to the document this Range belongs to. */ - protected List _characters; - - /** The start index in the characterRuns list for this Range */ - protected int _charStart; - - /** The end index in the characterRuns list for this Range. */ - protected int _charEnd; - - protected StringBuilder _text; - - /** - * Used to construct a Range from a document. This is generally used to - * create a Range that spans the whole document, or at least one whole part - * of the document (eg main text, header, comment) - * - * @param start - * Starting character offset of the range. - * @param end - * Ending character offset of the range. - * @param doc - * The HWPFDocument the range is based on. - */ - public Range(int start, int end, HWPFDocumentCore doc) { - _start = start; - _end = end; - _doc = doc; - _sections = _doc.getSectionTable().getSections(); - _paragraphs = _doc.getParagraphTable().getParagraphs(); - _characters = _doc.getCharacterTable().getTextRuns(); - _text = _doc.getText(); - _parent = new WeakReference(null); - - sanityCheckStartEnd(); - } - - /** - * Used to create Ranges that are children of other Ranges. - * - * @param start - * Starting character offset of the range. - * @param end - * Ending character offset of the range. - * @param parent - * The parent this range belongs to. - */ - protected Range(int start, int end, Range parent) { - _start = start; - _end = end; - _doc = parent._doc; - _sections = parent._sections; - _paragraphs = parent._paragraphs; - _characters = parent._characters; - _text = parent._text; - _parent = new WeakReference(parent); - - sanityCheckStartEnd(); - assert sanityCheck(); - } - - - /** - * Ensures that the start and end were were given are actually valid, to - * avoid issues later on if they're not - */ - private void sanityCheckStartEnd() { - if (_start < 0) { - throw new IllegalArgumentException("Range start must not be negative. Given " + _start); - } - if (_end < _start) { - throw new IllegalArgumentException("The end (" + _end - + ") must not be before the start (" + _start + ")"); - } - } - - /** - * Gets the text that this Range contains. - * - * @return The text for this range. - */ - public String text() { - return _text.substring( _start, _end ); - } - - /** - * Removes any fields (eg macros, page markers etc) from the string. - * Normally used to make some text suitable for showing to humans, and the - * resultant text should not normally be saved back into the document! - */ - public static String stripFields(String text) { - // First up, fields can be nested... - // A field can be 0x13 [contents] 0x15 - // Or it can be 0x13 [contents] 0x14 [real text] 0x15 - - // If there are no fields, all easy - if (text.indexOf('\u0013') == -1) - return text; - - // Loop over until they're all gone - // That's when we're out of both 0x13s and 0x15s - while (text.indexOf('\u0013') > -1 && text.indexOf('\u0015') > -1) { - int first13 = text.indexOf('\u0013'); - int next13 = text.indexOf('\u0013', first13 + 1); - int first14 = text.indexOf('\u0014', first13 + 1); - int last15 = text.lastIndexOf('\u0015'); - - // If they're the wrong way around, give up - if (last15 < first13) { - break; - } - - // If no more 13s and 14s, just zap - if (next13 == -1 && first14 == -1) { - text = text.substring(0, first13) + text.substring(last15 + 1); - break; - } - - // If a 14 comes before the next 13, then - // zap from the 13 to the 14, and remove - // the 15 - if (first14 != -1 && (first14 < next13 || next13 == -1)) { - text = text.substring(0, first13) + text.substring(first14 + 1, last15) - + text.substring(last15 + 1); - continue; - } - - // Another 13 comes before the next 14. - // This means there's nested stuff, so we - // can just zap the lot - text = text.substring(0, first13) + text.substring(last15 + 1); - } - - return text; - } - - /** - * Used to get the number of sections in a range. If this range is smaller - * than a section, it will return 1 for its containing section. - * - * @return The number of sections in this range. - */ - public int numSections() { - initSections(); - return _sectionEnd - _sectionStart; - } - - /** - * Used to get the number of paragraphs in a range. If this range is smaller - * than a paragraph, it will return 1 for its containing paragraph. - * - * @return The number of paragraphs in this range. - */ - - public int numParagraphs() { - initParagraphs(); - return _parEnd - _parStart; - } - - /** - * - * @return The number of characterRuns in this range. - */ - - public int numCharacterRuns() { - initCharacterRuns(); - return _charEnd - _charStart; - } - - /** - * Inserts text into the front of this range. - * - * @param text - * The text to insert - * @return The character run that text was inserted into. - */ - public CharacterRun insertBefore( String text ) - { - initAll(); - - _text.insert( _start, text ); - _doc.getCharacterTable().adjustForInsert( _charStart, text.length() ); - _doc.getParagraphTable().adjustForInsert( _parStart, text.length() ); - _doc.getSectionTable().adjustForInsert( _sectionStart, text.length() ); - if ( _doc instanceof HWPFDocument ) - { - ( (BookmarksImpl) ( (HWPFDocument) _doc ).getBookmarks() ) - .afterInsert( _start, text.length() ); - } - adjustForInsert( text.length() ); - - // update the FIB.CCPText + friends fields - adjustFIB( text.length() ); - - assert sanityCheck(); - - return getCharacterRun( 0 ); - } - - /** - * Inserts text onto the end of this range - * - * @param text - * The text to insert - * @return The character run the text was inserted into. - */ - public CharacterRun insertAfter( String text ) - { - initAll(); - - _text.insert( _end, text ); - - _doc.getCharacterTable().adjustForInsert( _charEnd - 1, text.length() ); - _doc.getParagraphTable().adjustForInsert( _parEnd - 1, text.length() ); - _doc.getSectionTable().adjustForInsert( _sectionEnd - 1, text.length() ); - if ( _doc instanceof HWPFDocument ) - { - ( (BookmarksImpl) ( (HWPFDocument) _doc ).getBookmarks() ) - .afterInsert( _end, text.length() ); - } - adjustForInsert( text.length() ); - - assert sanityCheck(); - return getCharacterRun( numCharacterRuns() - 1 ); - } - - /** - * Inserts text into the front of this range and it gives that text the - * CharacterProperties specified in props. - * - * @param text - * The text to insert. - * @param props - * The CharacterProperties to give the text. - * @return A new CharacterRun that has the given text and properties and is - * n ow a part of the document. - * @deprecated POI 3.8 beta 4. User code should not work with {@link CharacterProperties} - */ - @Deprecated - private CharacterRun insertBefore(String text, CharacterProperties props) - { - initAll(); - PAPX papx = _paragraphs.get(_parStart); - short istd = papx.getIstd(); - - StyleSheet ss = _doc.getStyleSheet(); - CharacterProperties baseStyle = ss.getCharacterStyle(istd); - byte[] grpprl = CharacterSprmCompressor.compressCharacterProperty(props, baseStyle); - SprmBuffer buf = new SprmBuffer(grpprl, 0); - _doc.getCharacterTable().insert(_charStart, _start, buf); - - return insertBefore(text); - } - - /** - * Inserts text onto the end of this range and gives that text the - * CharacterProperties specified in props. - * - * @param text - * The text to insert. - * @param props - * The CharacterProperties to give the text. - * @return A new CharacterRun that has the given text and properties and is - * n ow a part of the document. - * @deprecated POI 3.8 beta 4. User code should not work with {@link CharacterProperties} - */ - @Deprecated - private CharacterRun insertAfter(String text, CharacterProperties props) - { - initAll(); - PAPX papx = _paragraphs.get(_parEnd - 1); - short istd = papx.getIstd(); - - StyleSheet ss = _doc.getStyleSheet(); - CharacterProperties baseStyle = ss.getCharacterStyle(istd); - byte[] grpprl = CharacterSprmCompressor.compressCharacterProperty(props, baseStyle); - SprmBuffer buf = new SprmBuffer(grpprl, 0); - _doc.getCharacterTable().insert(_charEnd, _end, buf); - _charEnd++; - return insertAfter(text); - } - - /** - * Inserts and empty paragraph into the front of this range. - * - * @param props - * The properties that the new paragraph will have. - * @param styleIndex - * The index into the stylesheet for the new paragraph. - * @return The newly inserted paragraph. - * @deprecated POI 3.8 beta 4. Use code shall not work with {@link ParagraphProperties} - */ - @Deprecated - private Paragraph insertBefore(ParagraphProperties props, int styleIndex) - { - return this.insertBefore(props, styleIndex, "\r"); - } - - /** - * Inserts a paragraph into the front of this range. The paragraph will - * contain one character run that has the default properties for the - * paragraph's style. - * - * It is necessary for the text to end with the character '\r' - * - * @param props - * The paragraph's properties. - * @param styleIndex - * The index of the paragraph's style in the style sheet. - * @param text - * The text to insert. - * @return A newly inserted paragraph. - * @deprecated POI 3.8 beta 4. Use code shall not work with {@link ParagraphProperties} - */ - @Deprecated - private Paragraph insertBefore(ParagraphProperties props, int styleIndex, String text) - { - initAll(); - StyleSheet ss = _doc.getStyleSheet(); - ParagraphProperties baseStyle = ss.getParagraphStyle(styleIndex); - CharacterProperties baseChp = ss.getCharacterStyle(styleIndex); - - byte[] grpprl = ParagraphSprmCompressor.compressParagraphProperty(props, baseStyle); - byte[] withIndex = new byte[grpprl.length + LittleEndian.SHORT_SIZE]; - LittleEndian.putShort(withIndex, 0, (short) styleIndex); - System.arraycopy(grpprl, 0, withIndex, LittleEndian.SHORT_SIZE, grpprl.length); - SprmBuffer buf = new SprmBuffer(withIndex, 2); - - _doc.getParagraphTable().insert(_parStart, _start, buf); - insertBefore(text, baseChp); - return getParagraph(0); - } - - /** - * Inserts and empty paragraph into the end of this range. - * - * @param props - * The properties that the new paragraph will have. - * @param styleIndex - * The index into the stylesheet for the new paragraph. - * @return The newly inserted paragraph. - * @deprecated POI 3.8 beta 4. Use code shall not work with {@link ParagraphProperties} - */ - @Deprecated - protected Paragraph insertAfter(ParagraphProperties props, int styleIndex) - { - return this.insertAfter(props, styleIndex, "\r"); - } - - /** - * Inserts a paragraph into the end of this range. The paragraph will - * contain one character run that has the default properties for the - * paragraph's style. - * - * It is necessary for the text to end with the character '\r' - * - * @param props - * The paragraph's properties. - * @param styleIndex - * The index of the paragraph's style in the style sheet. - * @param text - * The text to insert. - * @return A newly inserted paragraph. - * @deprecated POI 3.8 beta 4. Use code shall not work with {@link ParagraphProperties} - */ - @Deprecated - protected Paragraph insertAfter(ParagraphProperties props, int styleIndex, String text) - { - initAll(); - StyleSheet ss = _doc.getStyleSheet(); - ParagraphProperties baseStyle = ss.getParagraphStyle(styleIndex); - CharacterProperties baseChp = ss.getCharacterStyle(styleIndex); - - byte[] grpprl = ParagraphSprmCompressor.compressParagraphProperty(props, baseStyle); - byte[] withIndex = new byte[grpprl.length + LittleEndian.SHORT_SIZE]; - LittleEndian.putShort(withIndex, 0, (short) styleIndex); - System.arraycopy(grpprl, 0, withIndex, LittleEndian.SHORT_SIZE, grpprl.length); - SprmBuffer buf = new SprmBuffer(withIndex, 2); - - _doc.getParagraphTable().insert(_parEnd, _end, buf); - _parEnd++; - insertAfter(text, baseChp); - return getParagraph(numParagraphs() - 1); - } - - public void delete() { - - initAll(); - - int numSections = _sections.size(); - int numRuns = _characters.size(); - int numParagraphs = _paragraphs.size(); - - for (int x = _charStart; x < numRuns; x++) { - CHPX chpx = _characters.get(x); - chpx.adjustForDelete(_start, _end - _start); - } - - for (int x = _parStart; x < numParagraphs; x++) { - PAPX papx = _paragraphs.get(x); - // System.err.println("Paragraph " + x + " was " + papx.getStart() + - // " -> " + papx.getEnd()); - papx.adjustForDelete(_start, _end - _start); - // System.err.println("Paragraph " + x + " is now " + - // papx.getStart() + " -> " + papx.getEnd()); - } - - for (int x = _sectionStart; x < numSections; x++) { - SEPX sepx = _sections.get(x); - // System.err.println("Section " + x + " was " + sepx.getStart() + - // " -> " + sepx.getEnd()); - sepx.adjustForDelete(_start, _end - _start); - // System.err.println("Section " + x + " is now " + sepx.getStart() - // + " -> " + sepx.getEnd()); - } - - if ( _doc instanceof HWPFDocument ) - { - ( (BookmarksImpl) ( (HWPFDocument) _doc ).getBookmarks() ) - .afterDelete( _start, ( _end - _start ) ); - } - - _text.delete( _start, _end ); - Range parent = _parent.get(); - if ( parent != null ) - { - parent.adjustForInsert( -( _end - _start ) ); - } - - // update the FIB.CCPText + friends field - adjustFIB(-(_end - _start)); - } - - /** - * Inserts a simple table into the beginning of this range. - * - * @param columns - * The number of columns - * @param rows - * The number of rows. - * @return The empty Table that is now part of the document. - */ - public Table insertTableBefore(short columns, int rows) { - ParagraphProperties parProps = new ParagraphProperties(); - parProps.setFInTable(true); - parProps.setItap( 1 ); - - final int oldEnd = this._end; - - for ( int x = 0; x < rows; x++ ) - { - Paragraph cell = this.insertBefore( parProps, StyleSheet.NIL_STYLE ); - cell.insertAfter( String.valueOf( '\u0007' ) ); - for ( int y = 1; y < columns; y++ ) - { - cell = cell.insertAfter( parProps, StyleSheet.NIL_STYLE ); - cell.insertAfter( String.valueOf( '\u0007' ) ); - } - cell = cell.insertAfter( parProps, StyleSheet.NIL_STYLE, - String.valueOf( '\u0007' ) ); - cell.setTableRowEnd( new TableProperties( columns ) ); - } - - final int newEnd = this._end; - final int diff = newEnd - oldEnd; - - return new Table( _start, _start + diff, this, 1 ); - } - - /** - * Replace range text with new one, adding it to the range and deleting - * original text from document - * - * @param newText - * The text to be replaced with - * @param addAfter - * if true the text will be added at the end of current - * range, otherwise to the beginning - */ - public void replaceText( String newText, boolean addAfter ) - { - if ( addAfter ) - { - int originalEnd = getEndOffset(); - insertAfter( newText ); - new Range( getStartOffset(), originalEnd, this ).delete(); - } - else - { - int originalStart = getStartOffset(); - int originalEnd = getEndOffset(); - - insertBefore( newText ); - new Range( originalStart + newText.length(), originalEnd - + newText.length(), this ).delete(); - } - } - - /** - * Replace (one instance of) a piece of text with another... - * - * @param pPlaceHolder - * The text to be replaced (e.g., "${organization}") - * @param pValue - * The replacement text (e.g., "Apache Software Foundation") - * @param pOffset - * The offset or index where the text to be replaced begins - * (relative to/within this Range) - */ - @Internal - public void replaceText(String pPlaceHolder, String pValue, int pOffset) { - int absPlaceHolderIndex = getStartOffset() + pOffset; - - Range subRange = new Range(absPlaceHolderIndex, - (absPlaceHolderIndex + pPlaceHolder.length()), this); - subRange.insertBefore(pValue); - - // re-create the sub-range so we can delete it - subRange = new Range((absPlaceHolderIndex + pValue.length()), (absPlaceHolderIndex - + pPlaceHolder.length() + pValue.length()), this); - - // deletes are automagically propagated - subRange.delete(); - } - - /** - * Replace (all instances of) a piece of text with another... - * - * @param pPlaceHolder - * The text to be replaced (e.g., "${organization}") - * @param pValue - * The replacement text (e.g., "Apache Software Foundation") - */ - public void replaceText(String pPlaceHolder, String pValue) { - while (true) { - String text = text(); - int offset = text.indexOf(pPlaceHolder); - if (offset >= 0) { - replaceText(pPlaceHolder, pValue, offset); - } else { - break; - } - } - } - - /** - * Gets the character run at index. The index is relative to this range. - * - * @param index - * The index of the character run to get. - * @return The character run at the specified index in this range. - */ - public CharacterRun getCharacterRun( int index ) - { - initCharacterRuns(); - - if ( index + _charStart >= _charEnd ) - throw new IndexOutOfBoundsException( "CHPX #" + index + " (" - + ( index + _charStart ) + ") not in range [" + _charStart - + "; " + _charEnd + ")" ); - - CHPX chpx = _characters.get( index + _charStart ); - if ( chpx == null ) - { - return null; - } - - short istd; - if ( this instanceof Paragraph ) - { - istd = ((Paragraph) this)._istd; - } - else - { - int[] point = findRange( _paragraphs, - Math.max( chpx.getStart(), _start ), - Math.min( chpx.getEnd(), _end ) ); - - initParagraphs(); - int parStart = Math.max( point[0], _parStart ); - - if ( parStart >= _paragraphs.size() ) - { - return null; - } - - PAPX papx = _paragraphs.get( point[0] ); - istd = papx.getIstd(); - } - - return new CharacterRun( chpx, _doc.getStyleSheet(), istd, - this); - } - - /** - * Gets the section at index. The index is relative to this range. - * - * @param index - * The index of the section to get. - * @return The section at the specified index in this range. - */ - public Section getSection(int index) { - initSections(); - SEPX sepx = _sections.get(index + _sectionStart); - return new Section(sepx, this); - } - - /** - * Gets the paragraph at index. The index is relative to this range. - * - * @param index - * The index of the paragraph to get. - * @return The paragraph at the specified index in this range. - */ - - public Paragraph getParagraph(int index) { - initParagraphs(); - - if ( index + _parStart >= _parEnd ) - throw new IndexOutOfBoundsException( "Paragraph #" + index + " (" - + (index + _parStart) + ") not in range [" + _parStart - + "; " + _parEnd + ")" ); - - PAPX papx = _paragraphs.get(index + _parStart); - return Paragraph.newParagraph( this, papx ); - } - - /** - * Gets the table that starts with paragraph. In a Word file, a table - * consists of a group of paragraphs with certain flags set. - * - * @param paragraph - * The paragraph that is the first paragraph in the table. - * @return The table that starts with paragraph - */ - public Table getTable(Paragraph paragraph) { - if (!paragraph.isInTable()) { - throw new IllegalArgumentException("This paragraph doesn't belong to a table"); - } - - Range r = paragraph; - if (r._parent.get() != this) { - throw new IllegalArgumentException("This paragraph is not a child of this range instance"); - } - - r.initAll(); - int tableLevel = paragraph.getTableLevel(); - int tableEndInclusive = r._parStart; - - if ( r._parStart != 0 ) - { - Paragraph previous = Paragraph.newParagraph( this, - _paragraphs.get( r._parStart - 1 ) ); - if ( previous.isInTable() && // - previous.getTableLevel() == tableLevel // - && previous._sectionEnd >= r._sectionStart ) - { - throw new IllegalArgumentException( - "This paragraph is not the first one in the table" ); - } - } - - Range overallRange = _doc.getOverallRange(); - int limit = _paragraphs.size(); - for ( ; tableEndInclusive < limit - 1; tableEndInclusive++ ) - { - Paragraph next = Paragraph.newParagraph( overallRange, - _paragraphs.get( tableEndInclusive + 1 ) ); - if ( !next.isInTable() || next.getTableLevel() < tableLevel ) - break; - } - - initAll(); - if ( tableEndInclusive >= this._parEnd ) - { - logger.log( POILogger.WARN, "The table's bounds ", "[" - + this._parStart + "; " + tableEndInclusive + ")", - " fall outside of this Range paragraphs numbers ", "[" - + this._parStart + "; " + this._parEnd + ")" ); - } - - if ( tableEndInclusive < 0 ) - { - throw new ArrayIndexOutOfBoundsException( - "The table's end is negative, which isn't allowed!" ); - } - - int endOffsetExclusive = _paragraphs.get( tableEndInclusive ).getEnd(); - - return new Table( paragraph.getStartOffset(), endOffsetExclusive, - this, paragraph.getTableLevel() ); - } - - /** - * loads all of the list indexes. - */ - protected void initAll() { - initCharacterRuns(); - initParagraphs(); - initSections(); - } - - /** - * inits the paragraph list indexes. - */ - private void initParagraphs() { - if (!_parRangeFound) { - int[] point = findRange(_paragraphs, _start, _end); - _parStart = point[0]; - _parEnd = point[1]; - _parRangeFound = true; - } - } - - /** - * inits the character run list indexes. - */ - private void initCharacterRuns() { - if (!_charRangeFound) { - int[] point = findRange(_characters, _start, _end); - _charStart = point[0]; - _charEnd = point[1]; - _charRangeFound = true; - } - } - - /** - * inits the section list indexes. - */ - private void initSections() { - if (!_sectionRangeFound) { - int[] point = findRange(_sections, _sectionStart, _start, _end); - _sectionStart = point[0]; - _sectionEnd = point[1]; - _sectionRangeFound = true; - } - } - - private static int binarySearchStart( List> rpl, - int start ) - { - if ( rpl.size() == 0 ) - return -1; - if ( rpl.get( 0 ).getStart() >= start ) - return 0; - - int low = 0; - int high = rpl.size() - 1; - - while ( low <= high ) - { - int mid = ( low + high ) >>> 1; - PropertyNode node = rpl.get( mid ); - - if ( node.getStart() < start ) - { - low = mid + 1; - } - else if ( node.getStart() > start ) - { - high = mid - 1; - } - else - { - assert node.getStart() == start; - return mid; - } - } - assert low != 0; - return low - 1; - } - - private static int binarySearchEnd( List> rpl, - int foundStart, int end ) - { - if ( rpl.get( rpl.size() - 1 ).getEnd() <= end ) - return rpl.size() - 1; - - int low = foundStart; - int high = rpl.size() - 1; - - while ( low <= high ) - { - int mid = ( low + high ) >>> 1; - PropertyNode node = rpl.get( mid ); - - if ( node.getEnd() < end ) - { - low = mid + 1; - } - else if ( node.getEnd() > end ) - { - high = mid - 1; - } - else - { - assert node.getEnd() == end; - return mid; - } - } - assert 0 <= low && low < rpl.size(); - - return low; - } - - /** - * Used to find the list indexes of a particular property. - * - * @param rpl - * A list of property nodes. - * @param start - * The starting character offset. - * @param end - * The ending character offset. - * @return An int array of length 2. The first int is the start index and - * the second int is the end index. - */ - private int[] findRange( List> rpl, int start, - int end ) - { - int startIndex = binarySearchStart( rpl, start ); - while ( startIndex > 0 && rpl.get( startIndex - 1 ).getStart() >= start ) - startIndex--; - - int endIndex = binarySearchEnd( rpl, startIndex, end ); - while ( endIndex < rpl.size() - 1 - && rpl.get( endIndex + 1 ).getEnd() <= end ) - endIndex++; - - if ( startIndex < 0 || startIndex >= rpl.size() - || startIndex > endIndex || endIndex < 0 - || endIndex >= rpl.size() ) - throw new AssertionError(); - - return new int[] { startIndex, endIndex + 1 }; - } - - /** - * Used to find the list indexes of a particular property. - * - * @param rpl - * A list of property nodes. - * @param min - * A hint on where to start looking. - * @param start - * The starting character offset. - * @param end - * The ending character offset. - * @return An int array of length 2. The first int is the start index and - * the second int is the end index. - */ - private int[] findRange(List> rpl, int min, int start, int end) { - int x = min; - - if ( rpl.size() == min ) - return new int[] { min, min }; - - PropertyNode node = rpl.get( x ); - - while (node==null || (node.getEnd() <= start && x < rpl.size() - 1)) { - x++; - - if (x>=rpl.size()) { - return new int[] {0, 0}; - } - - node = rpl.get(x); - } - - if ( node.getStart() > end ) - { - return new int[] { 0, 0 }; - } - - if ( node.getEnd() <= start ) - { - return new int[] { rpl.size(), rpl.size() }; - } - - for ( int y = x; y < rpl.size(); y++ ) - { - node = rpl.get( y ); - if ( node == null ) - continue; - - if ( node.getStart() < end && node.getEnd() <= end ) - continue; - - if ( node.getStart() < end ) - return new int[] { x, y +1 }; - - return new int[] { x, y }; - } - return new int[] { x, rpl.size() }; - } - - /** - * resets the list indexes. - */ - protected void reset() { - _charRangeFound = false; - _parRangeFound = false; - _sectionRangeFound = false; - } - - /** - * Adjust the value of the various FIB character count fields, eg - * FIB.CCPText after an insert or a delete... - * - * Works on all CCP fields from this range onwards - * - * @param adjustment - * The (signed) value that should be added to the FIB CCP fields - */ - protected void adjustFIB( int adjustment ) - { - assert ( _doc instanceof HWPFDocument ); - - // update the FIB.CCPText field (this should happen once per adjustment, - // so we don't want it in - // adjustForInsert() or it would get updated multiple times if the range - // has a parent) - // without this, OpenOffice.org (v. 2.2.x) does not see all the text in - // the document - - FileInformationBlock fib = _doc.getFileInformationBlock(); - - // // Do for each affected part - // if (_start < cpS.getMainDocumentEnd()) { - // fib.setCcpText(fib.getCcpText() + adjustment); - // } - // - // if (_start < cpS.getCommentsEnd()) { - // fib.setCcpAtn(fib.getCcpAtn() + adjustment); - // } - // if (_start < cpS.getEndNoteEnd()) { - // fib.setCcpEdn(fib.getCcpEdn() + adjustment); - // } - // if (_start < cpS.getFootnoteEnd()) { - // fib.setCcpFtn(fib.getCcpFtn() + adjustment); - // } - // if (_start < cpS.getHeaderStoryEnd()) { - // fib.setCcpHdd(fib.getCcpHdd() + adjustment); - // } - // if (_start < cpS.getHeaderTextboxEnd()) { - // fib.setCcpHdrTxtBx(fib.getCcpHdrTxtBx() + adjustment); - // } - // if (_start < cpS.getMainTextboxEnd()) { - // fib.setCcpTxtBx(fib.getCcpTxtBx() + adjustment); - // } - - // much simple implementation base on SubdocumentType --sergey - - int currentEnd = 0; - for ( SubdocumentType type : SubdocumentType.ORDERED ) - { - int currentLength = fib.getSubdocumentTextStreamLength( type ); - currentEnd += currentLength; - - // do we need to shift this part? - if ( _start > currentEnd ) - continue; - - fib.setSubdocumentTextStreamLength( type, currentLength - + adjustment ); - - break; - } - } - - /** - * adjust this range after an insert happens. - * - * @param length - * the length to adjust for (expected to be a count of - * code-points, not necessarily chars) - */ - private void adjustForInsert(int length) { - _end += length; - - reset(); - Range parent = _parent.get(); - if (parent != null) { - parent.adjustForInsert(length); - } - } - - /** - * @return Starting character offset of the range - */ - public int getStartOffset() { - return _start; - } - - /** - * @return The ending character offset of this range - */ - public int getEndOffset() { - return _end; - } - - protected HWPFDocumentCore getDocument() { - return _doc; - } - - @Override - public String toString() - { - return "Range from " + getStartOffset() + " to " + getEndOffset() - + " (chars)"; - } - - /** - * Method for debug purposes. Checks that all resolved elements are inside - * of current range. - */ - public boolean sanityCheck() - { - if ( _start < 0 ) - throw new AssertionError(); - if ( _start > _text.length() ) - throw new AssertionError(); - if ( _end < 0 ) - throw new AssertionError(); - if ( _end > _text.length() ) - throw new AssertionError(); - if ( _start > _end ) - throw new AssertionError(); - - if ( _charRangeFound ) - { - for ( int c = _charStart; c < _charEnd; c++ ) - { - CHPX chpx = _characters.get( c ); - - int left = Math.max( this._start, chpx.getStart() ); - int right = Math.min( this._end, chpx.getEnd() ); - - if ( left >= right ) - throw new AssertionError(); - } - } - if ( _parRangeFound ) - { - for ( int p = _parStart; p < _parEnd; p++ ) - { - PAPX papx = _paragraphs.get( p ); - - int left = Math.max( this._start, papx.getStart() ); - int right = Math.min( this._end, papx.getEnd() ); - - if ( left >= right ) - throw new AssertionError(); - } - } - - return true; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/Section.java b/src/scratchpad/src/org/apache/poi/hwpf/usermodel/Section.java deleted file mode 100644 index 71ab5017e..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/Section.java +++ /dev/null @@ -1,239 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.usermodel; - -import org.apache.poi.hwpf.HWPFOldDocument; -import org.apache.poi.hwpf.model.SEPX; - -public final class Section extends Range -{ - private SectionProperties _props; - - public Section( SEPX sepx, Range parent ) - { - super( Math.max( parent._start, sepx.getStart() ), Math.min( - parent._end, sepx.getEnd() ), parent ); - - // XXX: temporary workaround for old Word95 document - if ( parent.getDocument() instanceof HWPFOldDocument ) - _props = new SectionProperties(); - else - _props = sepx.getSectionProperties(); - } - - public Object clone() throws CloneNotSupportedException - { - Section s = (Section) super.clone(); - s._props = (SectionProperties) _props.clone(); - return s; - } - - /** - * @return distance to be maintained between columns, in twips. Used when - * {@link #isColumnsEvenlySpaced()} == true - */ - public int getDistanceBetweenColumns() - { - return _props.getDxaColumns(); - } - - public int getMarginBottom() - { - return _props.getDyaBottom(); - } - - public int getMarginLeft() - { - return _props.getDxaLeft(); - } - - public int getMarginRight() - { - return _props.getDxaRight(); - } - - public int getMarginTop() - { - return _props.getDyaTop(); - } - - public int getNumColumns() - { - return _props.getCcolM1() + 1; - } - - /** - * @return page height (in twips) in current section. Default value is 15840 - * twips - */ - public int getPageHeight() - { - return _props.getYaPage(); - } - - /** - * @return page width (in twips) in current section. Default value is 12240 - * twips - */ - public int getPageWidth() - { - return _props.getXaPage(); - } - - /** - * Set the height of the bottom margin in twips. In the AbstractWordUtils class, a constant - * is defined that indicates how many twips there are per inch and it can be used in setting - * the margins width a little like this; - * - * section.setMarginBottom( (int) 1.5 * AbstractWordUtils.TWIPS_PER_INCH ); - * - * @param marginWidth A primitive int whose value will indciate how high the margin should - * be - in twips. - */ - public void setMarginBottom(int marginWidth) - { - this._props.setDyaBottom(marginWidth); - } - - /** - * Set the width of the left hand margin in twips. In the AbstractWordUtils class, a constant - * is defined that indicates how many twips there are per inch and it can be used in setting - * the margins width a little like this; - * - * section.setMarginLeft( (int) 1.5 * AbstractWordUtils.TWIPS_PER_INCH ); - * - * @param marginWidth A primitive int whose value will indciate how high the margin should - * be - in twips. - */ - public void setMarginLeft(int marginWidth) - { - this._props.setDxaLeft(marginWidth); - } - - /** - * Set the width of the right hand margin in twips. In the AbstractWordUtils class, a constant - * is defined that indicates how many twips there are per inch and it can be used in setting - * the margins width a little like this; - * - * section.setMarginRight( (int) 1.5 * AbstractWordUtils.TWIPS_PER_INCH ); - * - * @param marginWidth A primitive int whose value will indciate how high the margin should - * be - in twips. - */ - public void setMarginRight(int marginWidth) - { - this._props.setDxaRight(marginWidth); - } - - /** - * Set the height of the top margin in twips. In the AbstractWordUtils class, a constant - * is defined that indicates how many twips there are per inch and it can be used in setting - * the margins width a little like this; - * - * section.setMarginTop( (int) 1.5 * AbstractWordUtils.TWIPS_PER_INCH ); - * - * @param marginWidth A primitive int whose value will indciate how high the margin should - * be - in twips. - */ - public void setMarginTop(int marginWidth) - { - this._props.setDyaTop(marginWidth); - } - - public boolean isColumnsEvenlySpaced() - { - return _props.getFEvenlySpaced(); - } - - /** - * Get the footnote restart qualifier - * - *
    - *
    {@code 0x00}
    If the numbering is continuous throughout the entire document
    - *
    {@code 0x01}
    If the numbering restarts at the beginning of this section
    - *
    {@code 0x02}
    If the numbering restarts on every page
    - *
    - * - * @return an Rnc, as decribed above, specifying when and where footnote numbering restarts - */ - public short getFootnoteRestartQualifier() { - return _props.getRncFtn(); - } - - /** - * @return an offset to be added to footnote numbers - */ - public int getFootnoteNumberingOffset() { - return _props.getNFtn(); - } - - /** - * Get the numbering format of embedded footnotes - * - *

    The full list of possible return values is given in [MS-OSHARED], v20140428, 2.2.1.3

    - * - * @return an Nfc specifying the numbering format for footnotes - */ - public int getFootnoteNumberingFormat() { - return _props.getNfcFtnRef(); - } - - /** - * Get the endnote restart qualifier - * - *
    - *
    {@code 0x00}
    If the numbering is continuous throughout the entire document
    - *
    {@code 0x01}
    If the numbering restarts at the beginning of this section
    - *
    {@code 0x02}
    If the numbering restarts on every page
    - *
    - * - * @return an Rnc, as decribed above, specifying when and where endnote numbering restarts - */ - public short getEndnoteRestartQualifier() { - return _props.getRncEdn(); - } - - /** - * @return an offset to be added to endnote numbers - */ - public int getEndnoteNumberingOffset() { - return _props.getNEdn(); - } - - /** - * Get the numbering format of embedded endnotes - * - *

    The full list of possible return values is given in [MS-OSHARED], v20140428, 2.2.1.3

    - * - * @return an Nfc specifying the numbering format for endnotes - */ - public int getEndnoteNumberingFormat() { - return _props.getNfcEdnRef(); - } - - @Override - public String toString() - { - return "Section [" + getStartOffset() + "; " + getEndOffset() + ")"; - } - - public int type() - { - return TYPE_SECTION; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/SectionProperties.java b/src/scratchpad/src/org/apache/poi/hwpf/usermodel/SectionProperties.java deleted file mode 100644 index 47aad84d2..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/SectionProperties.java +++ /dev/null @@ -1,157 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.usermodel; - -import org.apache.poi.hwpf.model.types.SEPAbstractType; - -public final class SectionProperties extends SEPAbstractType implements Cloneable -{ - private short field_60_rncftn; - private short field_61_rncedn; - private int field_62_nftn; - private int field_63_nfcftnref = 0x00; // initialize with default value; msonfcArabic - private int field_64_nedn; - private int field_65_nfcednref = 0x02; // initialize with default value; msonfcLCRoman - - public SectionProperties() - { - field_20_brcTop = new BorderCode(); - field_21_brcLeft = new BorderCode(); - field_22_brcBottom = new BorderCode(); - field_23_brcRight = new BorderCode(); - field_26_dttmPropRMark = new DateAndTime(); - } - - @Override - public Object clone() throws CloneNotSupportedException - { - SectionProperties copy = (SectionProperties) super.clone(); - copy.field_20_brcTop = (BorderCode) field_20_brcTop.clone(); - copy.field_21_brcLeft = (BorderCode) field_21_brcLeft.clone(); - copy.field_22_brcBottom = (BorderCode) field_22_brcBottom.clone(); - copy.field_23_brcRight = (BorderCode) field_23_brcRight.clone(); - copy.field_26_dttmPropRMark = (DateAndTime) field_26_dttmPropRMark - .clone(); - - return copy; - } - - /** - * sprmSRncFtn, [MS-DOC], 20140721, 2.6.4 - * - * @param field_60_rncftn unsigned 8-bit integer specifying the footnote numbering restart condition - */ - public void setRncFtn(final short field_60_rncftn) { - this.field_60_rncftn = field_60_rncftn; - } - - /** - * @see #setRncFtn(short) - * @return an Rnc value specifying when and where footnote numbering restarts - */ - public short getRncFtn() { - return this.field_60_rncftn; - } - - /** - * sprmSRncEdn, [MS-DOC], 20140721, 2.6.4 - * - * @param field_61_rncedn unsigned 8-bit integer specifying the endnote numbering restart condition - */ - public void setRncEdn(final short field_61_rncedn) { - this.field_61_rncedn = field_61_rncedn; - } - - /** - * @see #setRncEdn(short) - * @return an Rnc value specifying when and where endnote numbering restarts - */ - public short getRncEdn() { - return this.field_61_rncedn; - } - - /** - * sprmSNftn, [MS-DOC], v20140721, 2.6.4 - * - * @param field_62_nftn a number specifying the offset to add to footnote numbers - */ - public void setNFtn(final int field_62_nftn) { - this.field_62_nftn = field_62_nftn; - } - - /** - * @see #setNFtn(int) - * @return a 16-bit integer specifying the offset to add to footnote numbering - */ - public int getNFtn() { - return this.field_62_nftn; - } - - /** - * sprmSNfcFtnRef, [MS-DOC], v20140721 - * - * @param field_63_nfcftnref an Nfc specifying the numbering format for footnotes - */ - public void setNfcFtnRef(final int field_63_nfcftnref) { - this.field_63_nfcftnref = field_63_nfcftnref; - } - - /** - * - * @see #setNfcFtnRef(int) - * @return a 16-bit integer with an Nfc specifying the numbering format for footnotes - */ - public int getNfcFtnRef() { - return this.field_63_nfcftnref; - } - - /** - * sprmSNEdn, [MS-DOC], v20140721, 2.6.4 - * - * @param field_64_nedn a number specifying the offset to add to footnote numbers - */ - public void setNEdn(final int field_64_nedn) { - this.field_64_nedn = field_64_nedn; - } - - /** - * @see #setNEdn(int) - * @return a 16-bit integer specifying the offset to add to endnote numbering - */ - public int getNEdn() { - return this.field_64_nedn; - } - - /** - * sprmSNfcEdnRef, [MS-DOC], v20140721 - * - * @param field_65_nfcednref an Nfc specifying the numbering format for endnotes - */ - public void setNfcEdnRef(final int field_65_nfcednref) { - this.field_65_nfcednref = field_65_nfcednref; - } - - /** - * - * @see #setNfcEdnRef(int) - * @return a 16-bit integer with an Nfc specifying the numbering format for endnotes - */ - public int getNfcEdnRef() { - return this.field_65_nfcednref; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/ShadingDescriptor.java b/src/scratchpad/src/org/apache/poi/hwpf/usermodel/ShadingDescriptor.java deleted file mode 100644 index e15cd7d5d..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/ShadingDescriptor.java +++ /dev/null @@ -1,68 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.usermodel; - -import org.apache.poi.hwpf.model.types.SHDAbstractType; - -/** - * The SHD is a substructure of the CHP, PAP, and TC for Word 2000. - * - * @author vlsergey - */ -public final class ShadingDescriptor extends SHDAbstractType implements - Cloneable -{ - - public ShadingDescriptor() - { - } - - public ShadingDescriptor( byte[] buf, int offset ) - { - super(); - fillFields( buf, offset ); - } - - public ShadingDescriptor clone() throws CloneNotSupportedException - { - return (ShadingDescriptor) super.clone(); - } - - public boolean isEmpty() - { - return field_3_ipat == 0; - } - - public byte[] serialize() - { - byte[] result = new byte[getSize()]; - serialize( result, 0 ); - return result; - } - - @Override - public String toString() - { - if ( isEmpty() ) - return "[SHD] EMPTY"; - - return "[SHD] (cvFore: " + getCvFore() + "; cvBack: " + getCvBack() - + "; iPat: " + getIpat() + ")"; - } - -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/ShadingDescriptor80.java b/src/scratchpad/src/org/apache/poi/hwpf/usermodel/ShadingDescriptor80.java deleted file mode 100644 index 40a6fac3f..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/ShadingDescriptor80.java +++ /dev/null @@ -1,83 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.usermodel; - -import org.apache.poi.hwpf.model.Colorref; - -import org.apache.poi.hwpf.model.types.SHD80AbstractType; - -/** - * The SHD80 is a substructure of the CHP and PAP, and TC for Word 97. - */ -public final class ShadingDescriptor80 extends SHD80AbstractType implements - Cloneable -{ - - public ShadingDescriptor80() - { - } - - public ShadingDescriptor80( byte[] buf, int offset ) - { - super(); - fillFields( buf, offset ); - } - - public ShadingDescriptor80( short value ) - { - super(); - field_1_value = value; - } - - public ShadingDescriptor80 clone() throws CloneNotSupportedException - { - return (ShadingDescriptor80) super.clone(); - } - - public boolean isEmpty() - { - return field_1_value == 0; - } - - public byte[] serialize() - { - byte[] result = new byte[getSize()]; - serialize( result, 0 ); - return result; - } - - public ShadingDescriptor toShadingDescriptor() - { - ShadingDescriptor result = new ShadingDescriptor(); - result.setCvFore( Colorref.valueOfIco( getIcoFore() ) ); - result.setCvBack( Colorref.valueOfIco( getIcoBack() ) ); - result.setIpat( getIpat() ); - return result; - } - - @Override - public String toString() - { - if ( isEmpty() ) - return "[SHD80] EMPTY"; - - return "[SHD80] (icoFore: " + getIcoFore() + "; icoBack: " - + getIcoBack() + "; iPat: " + getIpat() + ")"; - } - -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/Table.java b/src/scratchpad/src/org/apache/poi/hwpf/usermodel/Table.java deleted file mode 100644 index fb99df52f..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/Table.java +++ /dev/null @@ -1,91 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.usermodel; - -import java.util.ArrayList; - -public final class Table extends Range -{ - private ArrayList _rows; - - private boolean _rowsFound = false; - - private int _tableLevel; - - Table( int startIdxInclusive, int endIdxExclusive, Range parent, - int levelNum ) - { - super( startIdxInclusive, endIdxExclusive, parent ); - _tableLevel = levelNum; - initRows(); - } - - public TableRow getRow( int index ) - { - initRows(); - return _rows.get( index ); - } - - public int getTableLevel() - { - return _tableLevel; - } - - private void initRows() - { - if ( _rowsFound ) - return; - - _rows = new ArrayList(); - int rowStart = 0; - int rowEnd = 0; - - int numParagraphs = numParagraphs(); - while ( rowEnd < numParagraphs ) - { - Paragraph startRowP = getParagraph( rowStart ); - Paragraph endRowP = getParagraph( rowEnd ); - rowEnd++; - if ( endRowP.isTableRowEnd() - && endRowP.getTableLevel() == _tableLevel ) - { - _rows.add( new TableRow( startRowP.getStartOffset(), endRowP - .getEndOffset(), this, _tableLevel ) ); - rowStart = rowEnd; - } - } - _rowsFound = true; - } - - public int numRows() - { - initRows(); - return _rows.size(); - } - - @Override - protected void reset() - { - _rowsFound = false; - } - - public int type() - { - return TYPE_TABLE; - } -} \ No newline at end of file diff --git a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/TableAutoformatLookSpecifier.java b/src/scratchpad/src/org/apache/poi/hwpf/usermodel/TableAutoformatLookSpecifier.java deleted file mode 100644 index fbe68d4ea..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/TableAutoformatLookSpecifier.java +++ /dev/null @@ -1,81 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hwpf.usermodel; - -import org.apache.poi.hwpf.model.types.TLPAbstractType; - -public class TableAutoformatLookSpecifier extends TLPAbstractType implements - Cloneable -{ - public static final int SIZE = 4; - - public TableAutoformatLookSpecifier() - { - super(); - } - - public TableAutoformatLookSpecifier( byte[] data, int offset ) - { - super(); - fillFields( data, offset ); - } - - @Override - public TableAutoformatLookSpecifier clone() - { - try - { - return (TableAutoformatLookSpecifier) super.clone(); - } - catch ( CloneNotSupportedException e ) - { - throw new Error( e.getMessage(), e ); - } - } - - @Override - public boolean equals( Object obj ) - { - if ( this == obj ) - return true; - if ( obj == null ) - return false; - if ( getClass() != obj.getClass() ) - return false; - TableAutoformatLookSpecifier other = (TableAutoformatLookSpecifier) obj; - if ( field_1_itl != other.field_1_itl ) - return false; - if ( field_2_tlp_flags != other.field_2_tlp_flags ) - return false; - return true; - } - - @Override - public int hashCode() - { - final int prime = 31; - int result = 1; - result = prime * result + field_1_itl; - result = prime * result + field_2_tlp_flags; - return result; - } - - public boolean isEmpty() - { - return field_1_itl == 0 && field_2_tlp_flags == 0; - } -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/TableCell.java b/src/scratchpad/src/org/apache/poi/hwpf/usermodel/TableCell.java deleted file mode 100644 index 83a7b0bce..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/TableCell.java +++ /dev/null @@ -1,114 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.usermodel; - -public final class TableCell - extends Range -{ - private int _levelNum; - private TableCellDescriptor _tcd; - private int _leftEdge; - private int _width; - - public TableCell( int startIdxInclusive, int endIdxExclusive, - TableRow parent, int levelNum, TableCellDescriptor tcd, - int leftEdge, int width ) - { - super( startIdxInclusive, endIdxExclusive, parent ); - _tcd = tcd; - _leftEdge = leftEdge; - _width = width; - _levelNum = levelNum; - } - - public boolean isFirstMerged() - { - return _tcd.isFFirstMerged(); - } - - public boolean isMerged() - { - return _tcd.isFMerged(); - } - - public boolean isVertical() - { - return _tcd.isFVertical(); - } - - public boolean isBackward() - { - return _tcd.isFBackward(); - } - - public boolean isRotateFont() - { - return _tcd.isFRotateFont(); - } - - public boolean isVerticallyMerged() - { - return _tcd.isFVertMerge(); - } - - public boolean isFirstVerticallyMerged() - { - return _tcd.isFVertRestart(); - } - - public byte getVertAlign() - { - return _tcd.getVertAlign(); - } - - public BorderCode getBrcTop() - { - return _tcd.getBrcTop(); - } - - public BorderCode getBrcBottom() - { - return _tcd.getBrcBottom(); - } - - public BorderCode getBrcLeft() - { - return _tcd.getBrcLeft(); - } - - public BorderCode getBrcRight() - { - return _tcd.getBrcRight(); - } - - public int getLeftEdge() // twips - { - return _leftEdge; - } - - public int getWidth() // twips - { - return _width; - } - - /** Returns the TableCellDescriptor for this cell.*/ - public TableCellDescriptor getDescriptor(){ - return _tcd; - } - -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/TableCellDescriptor.java b/src/scratchpad/src/org/apache/poi/hwpf/usermodel/TableCellDescriptor.java deleted file mode 100644 index 4d01ec891..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/TableCellDescriptor.java +++ /dev/null @@ -1,71 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.usermodel; - -import org.apache.poi.hwpf.model.types.TCAbstractType; -import org.apache.poi.util.LittleEndian; - -public final class TableCellDescriptor extends TCAbstractType implements - Cloneable -{ - public static final int SIZE = 20; - - public TableCellDescriptor() - { - } - - protected void fillFields(byte[] data, int offset) - { - field_1_rgf = LittleEndian.getShort(data, 0x0 + offset); - field_2_wWidth = LittleEndian.getShort(data, 0x2 + offset); - setBrcTop(new BorderCode(data, 0x4 + offset)); - setBrcLeft(new BorderCode(data, 0x8 + offset)); - setBrcBottom(new BorderCode(data, 0xc + offset)); - setBrcRight(new BorderCode(data, 0x10 + offset)); - } - - public void serialize(byte[] data, int offset) - { - LittleEndian.putShort(data, 0x0 + offset, field_1_rgf); - LittleEndian.putShort(data, 0x2 + offset, field_2_wWidth); - getBrcTop().serialize(data, 0x4 + offset); - getBrcLeft().serialize(data, 0x8 + offset); - getBrcBottom().serialize(data, 0xc + offset); - getBrcRight().serialize(data, 0x10 + offset); - } - - public Object clone() - throws CloneNotSupportedException - { - TableCellDescriptor tc = (TableCellDescriptor)super.clone(); - tc.setShd( getShd().clone() ); - tc.setBrcTop((BorderCode)getBrcTop().clone()); - tc.setBrcLeft((BorderCode)getBrcLeft().clone()); - tc.setBrcBottom((BorderCode)getBrcBottom().clone()); - tc.setBrcRight((BorderCode)getBrcRight().clone()); - return tc; - } - - public static TableCellDescriptor convertBytesToTC(byte[] buf, int offset) - { - TableCellDescriptor tc = new TableCellDescriptor(); - tc.fillFields(buf, offset); - return tc; - } - -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/TableIterator.java b/src/scratchpad/src/org/apache/poi/hwpf/usermodel/TableIterator.java deleted file mode 100644 index b2b11d288..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/TableIterator.java +++ /dev/null @@ -1,74 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.usermodel; - - -public final class TableIterator -{ - Range _range; - int _index; - int _levelNum; - - TableIterator(Range range, int levelNum) - { - _range = range; - _index = 0; - _levelNum = levelNum; - } - - public TableIterator(Range range) - { - this(range, 1); - } - - - public boolean hasNext() - { - int numParagraphs = _range.numParagraphs(); - for (;_index < numParagraphs; _index++) - { - Paragraph paragraph = _range.getParagraph(_index); - if (paragraph.isInTable() && paragraph.getTableLevel() == _levelNum) - { - return true; - } - } - return false; - } - - public Table next() - { - int numParagraphs = _range.numParagraphs(); - int startIndex = _index; - int endIndex = _index; - - for (;_index < numParagraphs; _index++) - { - Paragraph paragraph = _range.getParagraph(_index); - if (!paragraph.isInTable() || paragraph.getTableLevel() < _levelNum) - { - endIndex = _index; - break; - } - } - return new Table( _range.getParagraph( startIndex ).getStartOffset(), - _range.getParagraph( endIndex - 1 ).getEndOffset(), _range, - _levelNum ); - } - -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/TableProperties.java b/src/scratchpad/src/org/apache/poi/hwpf/usermodel/TableProperties.java deleted file mode 100644 index 001b3cfb2..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/TableProperties.java +++ /dev/null @@ -1,102 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.usermodel; - -import org.apache.poi.hwpf.model.types.TAPAbstractType; - -public final class TableProperties extends TAPAbstractType implements Cloneable -{ - - public TableProperties() - { - setTlp( new TableAutoformatLookSpecifier() ); - setShdTable( new ShadingDescriptor() ); - setBrcBottom( new BorderCode() ); - setBrcHorizontal( new BorderCode() ); - setBrcLeft( new BorderCode() ); - setBrcRight( new BorderCode() ); - setBrcTop( new BorderCode() ); - setBrcVertical( new BorderCode() ); - setRgbrcInsideDefault_0( new BorderCode() ); - setRgbrcInsideDefault_1( new BorderCode() ); - setRgdxaCenter( new short[0] ); - setRgdxaCenterPrint( new short[0] ); - setRgshd( new ShadingDescriptor[0] ); - setRgtc( new TableCellDescriptor[0] ); - } - - public TableProperties( short columns ) - { - this(); - - setItcMac( columns ); - setRgshd( new ShadingDescriptor[columns] ); - - for ( int x = 0; x < columns; x++ ) - { - getRgshd()[x] = new ShadingDescriptor(); - } - - TableCellDescriptor[] tableCellDescriptors = new TableCellDescriptor[columns]; - for ( int x = 0; x < columns; x++ ) - { - tableCellDescriptors[x] = new TableCellDescriptor(); - } - setRgtc( tableCellDescriptors ); - - setRgdxaCenter( new short[columns] ); - setRgdxaCenterPrint( new short[columns] ); - } - - public Object clone() throws CloneNotSupportedException - { - TableProperties tap = (TableProperties) super.clone(); - - tap.setTlp( getTlp().clone() ); - tap.setRgshd( new ShadingDescriptor[getRgshd().length] ); - for ( int x = 0; x < getRgshd().length; x++ ) - { - tap.getRgshd()[x] = getRgshd()[x].clone(); - } - - tap.setBrcBottom( (BorderCode) getBrcBottom().clone() ); - tap.setBrcHorizontal( (BorderCode) getBrcHorizontal().clone() ); - tap.setBrcLeft( (BorderCode) getBrcLeft().clone() ); - tap.setBrcRight( (BorderCode) getBrcRight().clone() ); - tap.setBrcTop( (BorderCode) getBrcTop().clone() ); - tap.setBrcVertical( (BorderCode) getBrcVertical().clone() ); - - tap.setShdTable( getShdTable().clone() ); - - tap.setRgbrcInsideDefault_0( (BorderCode) getRgbrcInsideDefault_0() - .clone() ); - tap.setRgbrcInsideDefault_1( (BorderCode) getRgbrcInsideDefault_1() - .clone() ); - - tap.setRgdxaCenter( getRgdxaCenter().clone() ); - tap.setRgdxaCenterPrint( getRgdxaCenterPrint().clone() ); - - tap.setRgtc( new TableCellDescriptor[getRgtc().length] ); - for ( int x = 0; x < getRgtc().length; x++ ) - { - tap.getRgtc()[x] = (TableCellDescriptor) getRgtc()[x].clone(); - } - return tap; - } - -} diff --git a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/TableRow.java b/src/scratchpad/src/org/apache/poi/hwpf/usermodel/TableRow.java deleted file mode 100644 index a12dc63be..000000000 --- a/src/scratchpad/src/org/apache/poi/hwpf/usermodel/TableRow.java +++ /dev/null @@ -1,250 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.usermodel; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.hwpf.sprm.SprmBuffer; -import org.apache.poi.hwpf.sprm.TableSprmUncompressor; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; - -public final class TableRow extends Range -{ - private static final POILogger logger = POILogFactory - .getLogger( TableRow.class ); - - private final static short SPRM_DXAGAPHALF = (short) 0x9602; - private final static short SPRM_DYAROWHEIGHT = (short) 0x9407; - private final static short SPRM_FCANTSPLIT = 0x3403; - private final static short SPRM_FTABLEHEADER = 0x3404; - private final static short SPRM_TJC = 0x5400; - - private final static char TABLE_CELL_MARK = '\u0007'; - - private TableCell[] _cells; - private boolean _cellsFound = false; - - int _levelNum; - private SprmBuffer _papx; - private TableProperties _tprops; - - public TableRow( int startIdxInclusive, int endIdxExclusive, Table parent, - int levelNum ) - { - super( startIdxInclusive, endIdxExclusive, parent ); - - Paragraph last = getParagraph( numParagraphs() - 1 ); - _papx = last._papx; - _tprops = TableSprmUncompressor.uncompressTAP( _papx ); - _levelNum = levelNum; - initCells(); - } - - public boolean cantSplit() - { - return _tprops.getFCantSplit(); - } - - public BorderCode getBarBorder() - { - throw new UnsupportedOperationException( "not applicable for TableRow" ); - } - - public BorderCode getBottomBorder() - { - return _tprops.getBrcBottom(); - } - - public TableCell getCell( int index ) - { - initCells(); - return _cells[index]; - } - - public int getGapHalf() - { - return _tprops.getDxaGapHalf(); - } - - public BorderCode getHorizontalBorder() - { - return _tprops.getBrcHorizontal(); - } - - public BorderCode getLeftBorder() - { - return _tprops.getBrcLeft(); - } - - public BorderCode getRightBorder() - { - return _tprops.getBrcRight(); - } - - public int getRowHeight() - { - return _tprops.getDyaRowHeight(); - } - - public int getRowJustification() - { - return _tprops.getJc(); - } - - public BorderCode getTopBorder() - { - return _tprops.getBrcTop(); - } - - public BorderCode getVerticalBorder() - { - return _tprops.getBrcVertical(); - } - - private void initCells() - { - if ( _cellsFound ) - return; - - final short expectedCellsCount = _tprops.getItcMac(); - - int lastCellStart = 0; - List cells = new ArrayList( - expectedCellsCount + 1 ); - for ( int p = 0; p < numParagraphs(); p++ ) - { - Paragraph paragraph = getParagraph( p ); - String s = paragraph.text(); - - if ( ( ( s.length() > 0 && s.charAt( s.length() - 1 ) == TABLE_CELL_MARK ) || paragraph - .isEmbeddedCellMark() ) - && paragraph.getTableLevel() == _levelNum ) - { - TableCellDescriptor tableCellDescriptor = _tprops.getRgtc() != null - && _tprops.getRgtc().length > cells.size() ? _tprops - .getRgtc()[cells.size()] : new TableCellDescriptor(); - final short leftEdge = _tprops.getRgdxaCenter() != null - && _tprops.getRgdxaCenter().length > cells.size() ? _tprops - .getRgdxaCenter()[cells.size()] : 0; - final short rightEdge = _tprops.getRgdxaCenter() != null - && _tprops.getRgdxaCenter().length > cells.size() + 1 ? _tprops - .getRgdxaCenter()[cells.size() + 1] : 0; - - TableCell tableCell = new TableCell( getParagraph( - lastCellStart ).getStartOffset(), getParagraph( p ) - .getEndOffset(), this, _levelNum, tableCellDescriptor, - leftEdge, rightEdge - leftEdge ); - cells.add( tableCell ); - lastCellStart = p + 1; - } - } - - if ( lastCellStart < ( numParagraphs() - 1 ) ) - { - TableCellDescriptor tableCellDescriptor = _tprops.getRgtc() != null - && _tprops.getRgtc().length > cells.size() ? _tprops - .getRgtc()[cells.size()] : new TableCellDescriptor(); - final short leftEdge = _tprops.getRgdxaCenter() != null - && _tprops.getRgdxaCenter().length > cells.size() ? _tprops - .getRgdxaCenter()[cells.size()] : 0; - final short rightEdge = _tprops.getRgdxaCenter() != null - && _tprops.getRgdxaCenter().length > cells.size() + 1 ? _tprops - .getRgdxaCenter()[cells.size() + 1] : 0; - - TableCell tableCell = new TableCell( lastCellStart, - ( numParagraphs() - 1 ), this, _levelNum, - tableCellDescriptor, leftEdge, rightEdge - leftEdge ); - cells.add( tableCell ); - } - - if ( !cells.isEmpty() ) - { - TableCell lastCell = cells.get( cells.size() - 1 ); - if ( lastCell.numParagraphs() == 1 - && ( lastCell.getParagraph( 0 ).isTableRowEnd() ) ) - { - // remove "fake" cell - cells.remove( cells.size() - 1 ); - } - } - - if ( cells.size() != expectedCellsCount ) - { - logger.log( POILogger.WARN, - "Number of found table cells (" + cells.size() - + ") for table row [" + getStartOffset() + "c; " - + getEndOffset() - + "c] not equals to stored property value " - + expectedCellsCount ); - _tprops.setItcMac( (short) cells.size() ); - } - - _cells = cells.toArray( new TableCell[cells.size()] ); - _cellsFound = true; - } - - public boolean isTableHeader() - { - return _tprops.getFTableHeader(); - } - - public int numCells() - { - initCells(); - return _cells.length; - } - - @Override - protected void reset() - { - _cellsFound = false; - } - - public void setCantSplit( boolean cantSplit ) - { - _tprops.setFCantSplit( cantSplit ); - _papx.updateSprm( SPRM_FCANTSPLIT, (byte) ( cantSplit ? 1 : 0 ) ); - } - - public void setGapHalf( int dxaGapHalf ) - { - _tprops.setDxaGapHalf( dxaGapHalf ); - _papx.updateSprm( SPRM_DXAGAPHALF, (short) dxaGapHalf ); - } - - public void setRowHeight( int dyaRowHeight ) - { - _tprops.setDyaRowHeight( dyaRowHeight ); - _papx.updateSprm( SPRM_DYAROWHEIGHT, (short) dyaRowHeight ); - } - - public void setRowJustification( int jc ) - { - _tprops.setJc( (short) jc ); - _papx.updateSprm( SPRM_TJC, (short) jc ); - } - - public void setTableHeader( boolean tableHeader ) - { - _tprops.setFTableHeader( tableHeader ); - _papx.updateSprm( SPRM_FTABLEHEADER, (byte) ( tableHeader ? 1 : 0 ) ); - } - -} diff --git a/src/scratchpad/testcases/dummy.txt b/src/scratchpad/testcases/dummy.txt deleted file mode 100644 index e69de29bb..000000000 diff --git a/src/scratchpad/testcases/log4j.properties b/src/scratchpad/testcases/log4j.properties deleted file mode 100644 index ac2be6850..000000000 --- a/src/scratchpad/testcases/log4j.properties +++ /dev/null @@ -1,21 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -log4j.rootLogger=ALL,CONSOLE - -log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender -log4j.appender.CONSOLE.target=System.out -log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout -log4j.appender.CONSOLE.layout.ConversionPattern=%d{dd.MM HH:mm:ss} %-30.30c %5p %m%n diff --git a/src/scratchpad/testcases/org/apache/poi/TestPOIDocumentScratchpad.java b/src/scratchpad/testcases/org/apache/poi/TestPOIDocumentScratchpad.java deleted file mode 100644 index 152fd0405..000000000 --- a/src/scratchpad/testcases/org/apache/poi/TestPOIDocumentScratchpad.java +++ /dev/null @@ -1,122 +0,0 @@ - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - - - -package org.apache.poi; - - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -import org.apache.poi.hpsf.HPSFPropertiesOnlyDocument; -import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl; -import org.apache.poi.hwpf.HWPFTestDataSamples; -import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.junit.Before; -import org.junit.Test; - -/** - * Tests that POIDocument correctly loads and saves the common - * (hspf) Document Properties - * - * This is part 2 of 2 of the tests - it only does the POIDocuments - * which are part of the scratchpad (not main) - */ -public final class TestPOIDocumentScratchpad { - // The POI Documents to work on - private POIDocument doc; - private POIDocument doc2; - - /** - * Set things up, using a PowerPoint document and - * a Word Document for our testing - */ - @Before - public void setUp() throws IOException { - doc = new HSLFSlideShowImpl(POIDataSamples.getSlideShowInstance().openResourceAsStream("basic_test_ppt_file.ppt")); - doc2 = HWPFTestDataSamples.openSampleFile("test2.doc"); - } - - @Test - public void testReadProperties() { - testReadPropertiesHelper(doc); - } - - private void testReadPropertiesHelper(POIDocument docPH) { - // We should have both sets - assertNotNull(docPH.getDocumentSummaryInformation()); - assertNotNull(docPH.getSummaryInformation()); - - // Check they are as expected for the test doc - assertEquals("Hogwarts", docPH.getSummaryInformation().getAuthor()); - assertEquals(10598, docPH.getDocumentSummaryInformation().getByteCount()); - } - - @Test - public void testReadProperties2() { - // Check again on the word one - assertNotNull(doc2.getDocumentSummaryInformation()); - assertNotNull(doc2.getSummaryInformation()); - - assertEquals("Hogwarts", doc2.getSummaryInformation().getAuthor()); - assertEquals("", doc2.getSummaryInformation().getKeywords()); - assertEquals(0, doc2.getDocumentSummaryInformation().getByteCount()); - } - - @Test - public void testWriteProperties() throws IOException { - // Just check we can write them back out into a filesystem - NPOIFSFileSystem outFS = new NPOIFSFileSystem(); - doc.writeProperties(outFS); - - // Should now hold them - assertNotNull(outFS.createDocumentInputStream("\005SummaryInformation")); - assertNotNull(outFS.createDocumentInputStream("\005DocumentSummaryInformation")); - outFS.close(); - } - - @Test - public void testWriteReadProperties() throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - - // Write them out - NPOIFSFileSystem outFS = new NPOIFSFileSystem(); - doc.writeProperties(outFS); - outFS.writeFilesystem(baos); - - // Create a new version - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - POIFSFileSystem inFS = new POIFSFileSystem(bais); - - // Check they're still there - POIDocument ppt = new HPSFPropertiesOnlyDocument(inFS); - ppt.readProperties(); - - // Delegate test - testReadPropertiesHelper(ppt); - - ppt.close(); - inFS.close(); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hdgf/TestHDGFCore.java b/src/scratchpad/testcases/org/apache/poi/hdgf/TestHDGFCore.java deleted file mode 100644 index ad3888d19..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hdgf/TestHDGFCore.java +++ /dev/null @@ -1,137 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hdgf; - -import junit.framework.TestCase; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hdgf.extractor.VisioTextExtractor; -import org.apache.poi.hdgf.streams.PointerContainingStream; -import org.apache.poi.hdgf.streams.TrailerStream; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; - -public final class TestHDGFCore extends TestCase { - private static POIDataSamples _dgTests = POIDataSamples.getDiagramInstance(); - - private POIFSFileSystem fs; - private HDGFDiagram hdgf; - private VisioTextExtractor textExtractor; - - @Override - protected void setUp() throws Exception { - fs = new POIFSFileSystem(_dgTests.openResourceAsStream("Test_Visio-Some_Random_Text.vsd")); - } - @Override - protected void tearDown() throws Exception { - if (textExtractor != null) textExtractor.close(); - if (hdgf != null) hdgf.close(); - } - - - public void testCreate() throws Exception { - hdgf = new HDGFDiagram(fs); - } - - public void testTrailer() throws Exception { - hdgf = new HDGFDiagram(fs); - assertNotNull(hdgf); - assertNotNull(hdgf.getTrailerStream()); - - // Check it has what we'd expect - TrailerStream trailer = hdgf.getTrailerStream(); - assertEquals(0x8a94, trailer.getPointer().getOffset()); - - assertNotNull(trailer.getPointedToStreams()); - assertEquals(20, trailer.getPointedToStreams().length); - - assertEquals(20, hdgf.getTopLevelStreams().length); - - // 9th one should have children - assertNotNull(trailer.getPointedToStreams()[8]); - assertNotNull(trailer.getPointedToStreams()[8].getPointer()); - PointerContainingStream ps8 = (PointerContainingStream) - trailer.getPointedToStreams()[8]; - assertNotNull(ps8.getPointedToStreams()); - assertEquals(8, ps8.getPointedToStreams().length); - } - - /** - * Tests that we can open a problematic file, that used to - * break with a negative chunk length - */ - public void testNegativeChunkLength() throws Exception { - fs = new POIFSFileSystem(_dgTests.openResourceAsStream("NegativeChunkLength.vsd")); - - hdgf = new HDGFDiagram(fs); - assertNotNull(hdgf); - - // And another file - fs = new POIFSFileSystem(_dgTests.openResourceAsStream("NegativeChunkLength2.vsd")); - hdgf = new HDGFDiagram(fs); - assertNotNull(hdgf); - } - - /** - * Tests that we can open a problematic file that triggers - * an ArrayIndexOutOfBoundsException when processing the - * chunk commands. - * @throws Exception - */ - public void DISABLEDtestAIOOB() throws Exception { - fs = new POIFSFileSystem(_dgTests.openResourceAsStream("44501.vsd")); - - hdgf = new HDGFDiagram(fs); - assertNotNull(hdgf); - } - - public void testV5() throws Exception { - fs = new POIFSFileSystem(_dgTests.openResourceAsStream("v5_Connection_Types.vsd")); - - hdgf = new HDGFDiagram(fs); - assertNotNull(hdgf); - - textExtractor = new VisioTextExtractor(hdgf); - String text = textExtractor.getText().replace("\u0000", "").trim(); - - assertEquals("Static to Static\nDynamic to Static\nDynamic to Dynamic", text); - } - - public void testV6NonUtf16LE() throws Exception { - fs = new POIFSFileSystem(_dgTests.openResourceAsStream("v6-non-utf16le.vsd")); - - hdgf = new HDGFDiagram(fs); - assertNotNull(hdgf); - - textExtractor = new VisioTextExtractor(hdgf); - String text = textExtractor.getText().replace("\u0000", "").trim(); - - assertEquals("Table\n\n\nPropertySheet\n\n\n\nPropertySheetField", text); - } - - public void testUtf16LE() throws Exception { - fs = new POIFSFileSystem(_dgTests.openResourceAsStream("Test_Visio-Some_Random_Text.vsd")); - - hdgf = new HDGFDiagram(fs); - assertNotNull(hdgf); - - textExtractor = new VisioTextExtractor(hdgf); - String text = textExtractor.getText().trim(); - - assertEquals("text\nView\nTest View\nI am a test view\nSome random text, on a page", text); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hdgf/TestHDGFLZW.java b/src/scratchpad/testcases/org/apache/poi/hdgf/TestHDGFLZW.java deleted file mode 100644 index 7f89a050f..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hdgf/TestHDGFLZW.java +++ /dev/null @@ -1,268 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hdgf; - -import java.io.ByteArrayInputStream; - -import junit.framework.TestCase; - -public final class TestHDGFLZW extends TestCase { - public static final byte[] testTrailerComp = new byte[] { - 123, // *mask bit* - -60, 2, - -21, -16, // 3 @ 4093 - 1, 0, 0, -72, - -13, -16, // 3 @ 5 - 78, // *mask bit* 2,3,4,7 - -32, -5, // 14 @ 4082 - 1, 0, 3, - -21, -16, // 3 @ 4093 - 10, 5, // 8 @ 28 - 4, - -21, -16, // 3 @ 4093 - 21, // *mask bit* 1,3,5 - 9, - -21, -16, // 3 @ 4093 - 103, - -21, -16, // 3 @ 4093 - 34, - -36, -1, // 18 @ 4078 - 52, 15, // 18 @ 70 - 70, 15, // 18 @ 88 - 120, // *mask bit* - 88, 15, // 18 @ 106 - -7, -2, // 17 @ 11 - -28, -9, // 10 @ 4086 - -123, 21, 0, 44, - -122, 1, // 4 @ 152 - -4, // *mask bit* - 104, 15, // 18 @ 122 - -24, -13, 40, -98, 32, - 78, 102, -67, -1, -2, -30, 64, 40, -67, -113, -73, 116, -98, - -85, 2, 66, 123, 9, 109, -85, 2, -89, 14, -56, -69, -83, -79, - -34, -3, 120, 110, 75, -9, -10, 20, -6, -25, -12, 22, -21, -16, - -12, -81, 67, 1, -128, -70, -21, -16, 84, -21, -16, 70, 0, 23, - -21, -16, 76, 47, -40, 79, 1, -44, -21, -16, 32, 3, 18, 12, 17, - -43, -68, 17, 16, -8, 21, 22, -1, -21, -16, -84, -1, -35, 79, - -9, -10, 96, 0, 46, -21, -16, 44, -39, -41, 79, 1, 119, -13, - -16, -106, -13, -16, 84, 0, 125, 26, -21, -16, 68, -38, 79, 1, - 17, 10, 0, -97, 50, 10, 0, 0, -42, -108, 15, 118, 31, 0, -3, 29, - -21, -16, -100, -25, 79, 1, -18, 97, -36, 76, 16, -21, -16, 86, - 0, 36, -5, 1, -5, 79, 63, 1, -124, 98, 0, 0, 28, 3, 20, -34, -3, - 125, 33, -21, -16, 100, -4, 79, 1, -92, -91, 16, -22, 24, 19, 41, - -21, -16, -44, -59, 16, 108, 100, 0, -21, 0, 71, -105, 18, 39, 85, - 17, -3, 79, 1, 95, -108, 113, 0, 0, 104, 3, 18, 49, 49, 17, -1, 64, - 85, 1, 0, 114, 0, 0, -93, -36, -21, -16, 100, 31, 0, 0, -40, -21, - -16, -92, 66, 127, 85, 1, 98, 119, 0, 0, -48, 79, 18, -3, 50, -17, - 1, 67, 85, 1, 81, -127, 0, -41, 0, 14, 6, 4, 17, 63, -63, 17, 68, - 85, -65, 1, 30, -120, 0, 0, 42, 79, 18, 68, 126, -21, -16, -76, 69, - 85, 1, 102, -119, 72, 37, 0, 97, 33 }; - public static final byte[] testTrailerDecomp = new byte[] { - -60, 2, 0, 0, 0, 1, 0, 0, -72, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 1, 0, 3, 0, 0, 0, 3, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, - 0, 9, 0, 0, 0, 103, 0, 0, 0, 34, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - -123, 21, 0, 44, -123, 21, 0, 44, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 40, -98, 32, 78, 102, -67, - -2, -30, 64, 40, -67, -113, -73, 116, -67, -2, -30, 64, 40, 66, - 123, 9, 109, -67, -2, -30, 64, 40, -98, 32, 78, 102, -67, -2, -30, - 64, 40, -67, -113, -73, 116, -67, -2, -30, 64, -56, -83, -79, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 120, 110, 75, 1, 0, 0, 0, - 0, 0, 0, 0, 0, 20, 0, 0, 0, 0, 0, 0, 0, 22, 0, 0, 0, -12, -81, 67, - 1, -128, 0, 0, 0, 84, 0, 0, 0, 70, 0, 23, 0, 0, 0, 76, -40, 79, 1, - -44, 0, 0, 0, 32, 0, 0, 0, 84, 0, 23, 0, 0, 0, -68, -40, 79, 1, -8, - 0, 0, 0, 32, 0, 0, 0, 84, 0, -1, 0, 0, 0, -84, -1, 79, 1, 0, 0, 0, - 0, 0, 0, 0, 0, 96, 0, 46, 0, 0, 0, 44, -39, 79, 1, 119, 1, 0, 0, - -106, 1, 0, 0, 84, 0, 26, 0, 0, 0, 68, -38, 79, 1, 17, 3, 0, 0, - 50, 10, 0, 0, -42, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 29, 0, 0, 0, -100, -25, 79, 1, -18, 97, 0, 0, -106, 0, 0, 0, 86, 0, - 36, 0, 0, 0, -12, -5, 79, 1, -124, 98, 0, 0, 28, 0, 0, 0, 84, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 33, 0, 0, 0, 100, - -4, 79, 1, -92, 98, 0, 0, 32, 0, 0, 0, 84, 0, 41, 0, 0, 0, -44, -4, - 79, 1, 108, 100, 0, 0, 71, 0, 0, 0, 86, 0, 39, 0, 0, 0, 68, -3, 79, - 1, -108, 113, 0, 0, 104, 0, 0, 0, 84, 0, 49, 0, 0, 0, -84, 64, 85, - 1, 0, 114, 0, 0, -93, 0, 0, 0, -42, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, -40, 0, 0, 0, -92, 66, 85, 1, 98, 119, - 0, 0, -48, 1, 0, 0, 84, 0, 50, 0, 0, 0, 20, 67, 85, 1, 81, -127, - 0, 0, 14, 6, 0, 0, 84, 0, 63, 0, 0, 0, 100, 68, 85, 1, 30, -120, - 0, 0, 42, 1, 0, 0, 84, 0, 68, 0, 0, 0, -76, 69, 85, 1, 102, -119, - 0, 0, 42, 1, 0, 0, 84, 0, 0, 0, 0, 0 - }; - - public void testFromToInt() { - byte b255 = -1; - assertEquals(255, HDGFLZW.fromByte(b255)); - assertEquals(-1, HDGFLZW.fromInt( HDGFLZW.fromByte(b255) )); - assertEquals(-1, HDGFLZW.fromInt( 255 )); - - byte b11 = 11; - assertEquals(11, HDGFLZW.fromByte(b11)); - assertEquals(11, HDGFLZW.fromInt( HDGFLZW.fromByte(b11) )); - assertEquals(11, HDGFLZW.fromInt( 11 )); - - byte b0 = 0; - assertEquals(0, HDGFLZW.fromByte(b0)); - assertEquals(0, HDGFLZW.fromInt( HDGFLZW.fromByte(b0) )); - assertEquals(0, HDGFLZW.fromInt( 0 )); - - byte b127 = 127; - assertEquals(127, HDGFLZW.fromByte(b127)); - assertEquals(127, HDGFLZW.fromInt( HDGFLZW.fromByte(b127) )); - assertEquals(127, HDGFLZW.fromInt( 127 )); - - byte b128 = -128; - assertEquals(128, HDGFLZW.fromByte(b128)); - assertEquals(-128, HDGFLZW.fromInt( HDGFLZW.fromByte(b128) )); - assertEquals(-128, HDGFLZW.fromInt( 128 )); - } - - public void testCounts() throws Exception { - assertEquals(339, testTrailerComp.length); - assertEquals(632, testTrailerDecomp.length); - - // decompress it using our engine - HDGFLZW lzw = new HDGFLZW(); - byte[] dec = lzw.decompress(new ByteArrayInputStream(testTrailerComp)); - - // Check it's of the right size - assertEquals(632, dec.length); - -/* - // Encode it again using our engine - byte[] comp = lzw.compress(new ByteArrayInputStream(testTrailerDecomp)); - - // Check it's of the right size - assertEquals(339, comp.length); -*/ - } - - public void testDecompress() throws Exception { - assertEquals(339, testTrailerComp.length); - assertEquals(632, testTrailerDecomp.length); - - // decompress it using our engine - HDGFLZW lzw = new HDGFLZW(); - byte[] dec = lzw.decompress(new ByteArrayInputStream(testTrailerComp)); - - // Now check it's the right data - assertEquals(632, dec.length); - for(int i=0; i 11 - // Next 32 -> 13 - byte[] sourceComp = new byte[24]; - byte[] sourceDecomp = new byte[44]; - System.arraycopy(testTrailerComp, 0, sourceComp, 0, sourceComp.length); - System.arraycopy(testTrailerDecomp, 0, sourceDecomp, 0, sourceDecomp.length); - - // Compress it using our engine - HDGFLZW lzw = new HDGFLZW(); - byte[] comp = lzw.compress(new ByteArrayInputStream(sourceDecomp)); - - // We should be 3 characters bigger, as - // we split one compressed bit into two - assertEquals(27, comp.length); - - // Now decompress it again - byte[] decomp = lzw.decompress(new ByteArrayInputStream(comp)); - - // We can only check the round-tripping, as for now - // visio cheats on re-using a block - assertEquals(44, decomp.length); - for(int i=0; i 4 -> 5 -> 1 -> 0 == String - assertNotNull(ts.getPointedToStreams()[8]); - assertTrue(ts.getPointedToStreams()[8] instanceof PointerContainingStream); - - PointerContainingStream s8 = - (PointerContainingStream)ts.getPointedToStreams()[8]; - assertNotNull(s8.getPointedToStreams()); - - assertNotNull(s8.getPointedToStreams()[4]); - assertTrue(s8.getPointedToStreams()[4] instanceof PointerContainingStream); - - PointerContainingStream s84 = - (PointerContainingStream)s8.getPointedToStreams()[4]; - assertNotNull(s84.getPointedToStreams()); - - assertNotNull(s84.getPointedToStreams()[5]); - assertTrue(s84.getPointedToStreams()[5] instanceof PointerContainingStream); - - PointerContainingStream s845 = - (PointerContainingStream)s84.getPointedToStreams()[5]; - assertNotNull(s845.getPointedToStreams()); - - assertNotNull(s845.getPointedToStreams()[1]); - assertTrue(s845.getPointedToStreams()[1] instanceof PointerContainingStream); - - PointerContainingStream s8451 = - (PointerContainingStream)s845.getPointedToStreams()[1]; - assertNotNull(s8451.getPointedToStreams()); - - assertNotNull(s8451.getPointedToStreams()[0]); - assertTrue(s8451.getPointedToStreams()[0] instanceof StringsStream); - assertTrue(s8451.getPointedToStreams()[1] instanceof StringsStream); - } - - @Test - public void testChunkWithText() { - // Parent ChunkStream is at 0x7194 - // This is one of the last children of the trailer - Pointer trailerPtr = ptrFactory.createPointer(contents, trailerPointerAt); - TrailerStream ts = (TrailerStream) - Stream.createStream(trailerPtr, contents, chunkFactory, ptrFactory); - - ts.findChildren(contents); - - assertNotNull(ts.getChildPointers()); - assertNotNull(ts.getPointedToStreams()); - assertEquals(20, ts.getChildPointers().length); - assertEquals(20, ts.getPointedToStreams().length); - - assertEquals(0x7194, ts.getChildPointers()[13].getOffset()); - assertEquals(0x7194, ts.getPointedToStreams()[13].getPointer().getOffset()); - - PointerContainingStream ps7194 = (PointerContainingStream) - ts.getPointedToStreams()[13]; - - // First child is at 0x64b3 - assertEquals(0x64b3, ps7194.getChildPointers()[0].getOffset()); - assertEquals(0x64b3, ps7194.getPointedToStreams()[0].getPointer().getOffset()); - - ChunkStream cs = (ChunkStream)ps7194.getPointedToStreams()[0]; - - // Should be 26bc bytes un-compressed - assertEquals(0x26bc, cs.getStore().getContents().length); - // And should have lots of children - assertEquals(131, cs.getChunks().length); - - // One of which is Text - boolean hasText = false; - for(int i=0; i -1 && lastY != extTextOutW.getY()) { - sb.append("\n"); - lastX = -1; - } - if (lastX > -1 && extTextOutW.getX() - lastX > fudgeFactorX) { - sb.append(" "); - } - sb.append(extTextOutW.getText()); - lastY = extTextOutW.getY(); - lastX = extTextOutW.getX(); - } - } - String txt = sb.toString(); - assertContains(txt, "Tika http://incubator.apache.org"); - assertContains(txt, "Latest News\n"); - } - - @Test - public void testWindowsText() throws Exception { - InputStream is = POIDataSamples.getSpreadSheetInstance().openResourceAsStream("SimpleEMF_windows.emf"); - HemfExtractor ex = new HemfExtractor(is); - long lastY = -1; - long lastX = -1; - long fudgeFactorX = 1000;//derive this from the font or frame/bounds information - StringBuilder sb = new StringBuilder(); - Set expectedParts = new HashSet(); - expectedParts.add("C:\\Users\\tallison\\"); - expectedParts.add("testPDF.pdf"); - int foundExpected = 0; - for (HemfRecord record : ex) { - if (record.getRecordType().equals(HemfRecordType.exttextoutw)) { - HemfText.ExtTextOutW extTextOutW = (HemfText.ExtTextOutW) record; - if (lastY > -1 && lastY != extTextOutW.getY()) { - sb.append("\n"); - lastX = -1; - } - if (lastX > -1 && extTextOutW.getX() - lastX > fudgeFactorX) { - sb.append(" "); - } - String txt = extTextOutW.getText(); - if (expectedParts.contains(txt)) { - foundExpected++; - } - sb.append(txt); - lastY = extTextOutW.getY(); - lastX = extTextOutW.getX(); - } - } - String txt = sb.toString(); - assertContains(txt, "C:\\Users\\tallison\\\n"); - assertContains(txt, "asf2-git-1.x\\tika-\n"); - assertEquals(expectedParts.size(), foundExpected); - } - - /* - govdocs1 064213.doc-0.emf contains an example of extextouta - */ - -} \ No newline at end of file diff --git a/src/scratchpad/testcases/org/apache/poi/hemf/hemfplus/extractor/HemfPlusExtractorTest.java b/src/scratchpad/testcases/org/apache/poi/hemf/hemfplus/extractor/HemfPlusExtractorTest.java deleted file mode 100644 index c42233ab7..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hemf/hemfplus/extractor/HemfPlusExtractorTest.java +++ /dev/null @@ -1,96 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hemf.hemfplus.extractor; - - -import static org.junit.Assert.assertEquals; - -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hemf.extractor.HemfExtractor; -import org.apache.poi.hemf.hemfplus.record.HemfPlusHeader; -import org.apache.poi.hemf.hemfplus.record.HemfPlusRecord; -import org.apache.poi.hemf.hemfplus.record.HemfPlusRecordType; -import org.apache.poi.hemf.record.HemfCommentEMFPlus; -import org.apache.poi.hemf.record.HemfCommentRecord; -import org.apache.poi.hemf.record.HemfRecord; -import org.junit.Test; - -public class HemfPlusExtractorTest { - - @Test - public void testBasic() throws Exception { - //test header - HemfCommentEMFPlus emfPlus = getCommentRecord("SimpleEMF_windows.emf", 0); - List records = emfPlus.getRecords(); - assertEquals(1, records.size()); - assertEquals(HemfPlusRecordType.header, records.get(0).getRecordType()); - - HemfPlusHeader header = (HemfPlusHeader)records.get(0); - assertEquals(240, header.getLogicalDpiX()); - assertEquals(240, header.getLogicalDpiY()); - assertEquals(1, header.getFlags()); - assertEquals(1, header.getEmfPlusFlags()); - - - - //test that the HemfCommentEMFPlus record at offset 1 - //contains 6 HemfCommentEMFPlus records within it - List expected = new ArrayList(); - expected.add(HemfPlusRecordType.setPixelOffsetMode); - expected.add(HemfPlusRecordType.setAntiAliasMode); - expected.add(HemfPlusRecordType.setCompositingQuality); - expected.add(HemfPlusRecordType.setPageTransform); - expected.add(HemfPlusRecordType.setInterpolationMode); - expected.add(HemfPlusRecordType.getDC); - - emfPlus = getCommentRecord("SimpleEMF_windows.emf", 1); - records = emfPlus.getRecords(); - assertEquals(expected.size(), records.size()); - - for (int i = 0; i < expected.size(); i++) { - assertEquals(expected.get(i), records.get(i).getRecordType()); - } - } - - - private HemfCommentEMFPlus getCommentRecord(String testFileName, int recordIndex) throws Exception { - InputStream is = null; - HemfCommentEMFPlus returnRecord = null; - - try { - is = POIDataSamples.getSpreadSheetInstance().openResourceAsStream(testFileName); - HemfExtractor ex = new HemfExtractor(is); - int i = 0; - for (HemfRecord record : ex) { - if (i == recordIndex) { - HemfCommentRecord commentRecord = ((HemfCommentRecord) record); - returnRecord = (HemfCommentEMFPlus) commentRecord.getComment(); - break; - } - i++; - } - } finally { - is.close(); - } - return returnRecord; - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hmef/HMEFTest.java b/src/scratchpad/testcases/org/apache/poi/hmef/HMEFTest.java deleted file mode 100644 index 4dde7b3bc..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hmef/HMEFTest.java +++ /dev/null @@ -1,50 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hmef; - -import java.io.IOException; -import java.io.InputStream; - -import junit.framework.TestCase; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.util.IOUtils; - -public abstract class HMEFTest extends TestCase { - protected static final POIDataSamples _samples = POIDataSamples.getHMEFInstance(); - - protected void assertContents(String filename, Attachment attachment) - throws IOException { - assertEquals(filename, attachment.getLongFilename()); - assertContents(filename, attachment.getContents()); - } - protected void assertContents(String filename, byte[] actual) - throws IOException { - InputStream stream = _samples.openResourceAsStream("quick-contents/" + filename); - try { - byte[] expected = IOUtils.toByteArray(stream); - - assertEquals(expected.length, actual.length); - for(int i=0; i attachments = quick.getAttachments(); - - // Word first - assertEquals("quick.doc", attachments.get(0).getFilename()); - assertEquals("quick.doc", attachments.get(0).getLongFilename()); - assertEquals(".doc", attachments.get(0).getExtension()); - - // Then HTML - assertEquals("QUICK~1.HTM", attachments.get(1).getFilename()); - assertEquals("quick.html", attachments.get(1).getLongFilename()); - assertEquals(".html", attachments.get(1).getExtension()); - - // Then PDF - assertEquals("quick.pdf", attachments.get(2).getFilename()); - assertEquals("quick.pdf", attachments.get(2).getLongFilename()); - assertEquals(".pdf", attachments.get(2).getExtension()); - - // Then Text - assertEquals("quick.txt", attachments.get(3).getFilename()); - assertEquals("quick.txt", attachments.get(3).getLongFilename()); - assertEquals(".txt", attachments.get(3).getExtension()); - - // And finally XML - assertEquals("quick.xml", attachments.get(4).getFilename()); - assertEquals("quick.xml", attachments.get(4).getLongFilename()); - assertEquals(".xml", attachments.get(4).getExtension()); - } - - /** - * Query the attachments in detail, and check we see - * the right values for key things - */ - public void testAttachmentDetails() throws Exception { - List attachments = quick.getAttachments(); - - // Pick a predictable date format + timezone - DateFormat fmt = DateFormat.getDateTimeInstance( - DateFormat.MEDIUM, DateFormat.MEDIUM, Locale.UK - ); - fmt.setTimeZone(LocaleUtil.TIMEZONE_UTC); - - // They should all have the same date on them - assertEquals("28-Apr-2010 12:40:56", fmt.format( attachments.get(0).getModifiedDate())); - assertEquals("28-Apr-2010 12:40:56", fmt.format( attachments.get(1).getModifiedDate())); - assertEquals("28-Apr-2010 12:40:56", fmt.format( attachments.get(2).getModifiedDate())); - assertEquals("28-Apr-2010 12:40:56", fmt.format( attachments.get(3).getModifiedDate())); - assertEquals("28-Apr-2010 12:40:56", fmt.format( attachments.get(4).getModifiedDate())); - - // They should all have a 3512 byte metafile rendered version - assertEquals(3512, attachments.get(0).getRenderedMetaFile().length); - assertEquals(3512, attachments.get(1).getRenderedMetaFile().length); - assertEquals(3512, attachments.get(2).getRenderedMetaFile().length); - assertEquals(3512, attachments.get(3).getRenderedMetaFile().length); - assertEquals(3512, attachments.get(4).getRenderedMetaFile().length); - } - - /** - * Ensure the attachment contents come back as they should do - */ - public void testAttachmentContents() throws Exception { - List attachments = quick.getAttachments(); - - assertContents("quick.doc", attachments.get(0)); - assertContents("quick.html", attachments.get(1)); - assertContents("quick.pdf", attachments.get(2)); - assertContents("quick.txt", attachments.get(3)); - assertContents("quick.xml", attachments.get(4)); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hmef/TestBugs.java b/src/scratchpad/testcases/org/apache/poi/hmef/TestBugs.java deleted file mode 100644 index 27d69f69f..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hmef/TestBugs.java +++ /dev/null @@ -1,69 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hmef; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hmef.attribute.MAPIAttribute; -import org.apache.poi.hmef.attribute.TNEFAttribute; -import org.apache.poi.hmef.attribute.TNEFProperty; -import org.apache.poi.hsmf.datatypes.MAPIProperty; -import org.apache.poi.util.LittleEndian; - -import org.junit.Test; - -public class TestBugs { - @Test - public void test52400ReadSimpleTNEF() throws Exception { - POIDataSamples samples = POIDataSamples.getHMEFInstance(); - String testFile = "bug52400-winmail-simple.dat"; - HMEFMessage tnefDat = new HMEFMessage(samples.openResourceAsStream(testFile)); - MAPIAttribute bodyHtml = tnefDat.getMessageMAPIAttribute(MAPIProperty.BODY_HTML); - String bodyStr = new String(bodyHtml.getData(), getEncoding(tnefDat)); - assertTrue(bodyStr.contains("This is the message body.")); - } - - @Test - public void test52400ReadAttachedTNEF() throws Exception { - POIDataSamples samples = POIDataSamples.getHMEFInstance(); - String testFile = "bug52400-winmail-with-attachments.dat"; - HMEFMessage tnefDat = new HMEFMessage(samples.openResourceAsStream(testFile)); - MAPIAttribute bodyHtml = tnefDat.getMessageMAPIAttribute(MAPIProperty.BODY_HTML); - String bodyStr = new String(bodyHtml.getData(), getEncoding(tnefDat)); - assertTrue(bodyStr.contains("There are also two attachments.")); - assertEquals(2, tnefDat.getAttachments().size()); - } - - private String getEncoding(HMEFMessage tnefDat) { - TNEFAttribute oemCP = tnefDat.getMessageAttribute(TNEFProperty.ID_OEMCODEPAGE); - MAPIAttribute cpId = tnefDat.getMessageMAPIAttribute(MAPIProperty.INTERNET_CPID); - int codePage = 1252; - if (oemCP != null) { - codePage = LittleEndian.getInt(oemCP.getData()); - } else if (cpId != null) { - codePage = LittleEndian.getInt(cpId.getData()); - } - switch (codePage) { - // see http://en.wikipedia.org/wiki/Code_page for more - case 1252: return "Windows-1252"; - case 20127: return "US-ASCII"; - default: return "cp"+codePage; - } - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hmef/TestCompressedRTF.java b/src/scratchpad/testcases/org/apache/poi/hmef/TestCompressedRTF.java deleted file mode 100644 index c010a6bf2..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hmef/TestCompressedRTF.java +++ /dev/null @@ -1,194 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hmef; - -import java.io.ByteArrayInputStream; -import java.io.InputStream; - -import junit.framework.TestCase; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hmef.attribute.MAPIAttribute; -import org.apache.poi.hmef.attribute.MAPIRtfAttribute; -import org.apache.poi.hsmf.datatypes.MAPIProperty; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.StringUtil; - -public final class TestCompressedRTF extends TestCase { - private static final POIDataSamples _samples = POIDataSamples.getHMEFInstance(); - - private static final String block1 = "{\\rtf1\\adeflang102"; - private static final String block2 = block1 + "5\\ansi\\ansicpg1252"; - - /** - * Check that things are as we expected. If this fails, - * then decoding has no hope... - */ - public void testQuickBasics() throws Exception { - HMEFMessage msg = new HMEFMessage( - _samples.openResourceAsStream("quick-winmail.dat") - ); - - MAPIAttribute rtfAttr = msg.getMessageMAPIAttribute(MAPIProperty.RTF_COMPRESSED); - assertNotNull(rtfAttr); - assertTrue(rtfAttr instanceof MAPIRtfAttribute); - - // Check the start of the compressed version - byte[] data = ((MAPIRtfAttribute)rtfAttr).getRawData(); - assertEquals(5907, data.length); - - // First 16 bytes is header stuff - // Check it has the length + compressed marker - assertEquals(5907-4, LittleEndian.getShort(data)); - assertEquals( - "LZFu", - StringUtil.getFromCompressedUnicode(data, 8, 4) - ); - - - // Now Look at the code - assertEquals((byte)0x07, data[16+0]); // Flag: cccUUUUU - assertEquals((byte)0x00, data[16+1]); // c1a: offset 0 / 0x000 - assertEquals((byte)0x06, data[16+2]); // c1b: length 6+2 -> {\rtf1\a - assertEquals((byte)0x01, data[16+3]); // c2a: offset 16 / 0x010 - assertEquals((byte)0x01, data[16+4]); // c2b: length 1+2 -> def - assertEquals((byte)0x0b, data[16+5]); // c3a: offset 182 / 0xb6 - assertEquals((byte)0x60, data[16+6]); // c3b: length 0+2 -> la - assertEquals((byte)0x6e, data[16+7]); // n - assertEquals((byte)0x67, data[16+8]); // g - assertEquals((byte)0x31, data[16+9]); // 1 - assertEquals((byte)0x30, data[16+10]); // 0 - assertEquals((byte)0x32, data[16+11]); // 2 - - assertEquals((byte)0x66, data[16+12]); // Flag: UccUUccU - assertEquals((byte)0x35, data[16+13]); // 5 - assertEquals((byte)0x00, data[16+14]); // c2a: offset 6 / 0x006 - assertEquals((byte)0x64, data[16+15]); // c2b: length 4+2 -> \ansi\a - assertEquals((byte)0x00, data[16+16]); // c3a: offset 7 / 0x007 - assertEquals((byte)0x72, data[16+17]); // c3b: length 2+2 -> nsi - assertEquals((byte)0x63, data[16+18]); // c - assertEquals((byte)0x70, data[16+19]); // p - assertEquals((byte)0x0d, data[16+20]); // c6a: offset 221 / 0x0dd - assertEquals((byte)0xd0, data[16+21]); // c6b: length 0+2 -> g1 - assertEquals((byte)0x0e, data[16+22]); // c7a: offset 224 / 0x0e0 - assertEquals((byte)0x00, data[16+23]); // c7b: length 0+2 -> 25 - assertEquals((byte)0x32, data[16+24]); // 2 - } - - /** - * Check that we can decode the first 8 codes - * (1 flag byte + 8 codes) - */ - public void testFirstBlock() throws Exception { - HMEFMessage msg = new HMEFMessage( - _samples.openResourceAsStream("quick-winmail.dat") - ); - - MAPIAttribute attr = msg.getMessageMAPIAttribute(MAPIProperty.RTF_COMPRESSED); - assertNotNull(attr); - MAPIRtfAttribute rtfAttr = (MAPIRtfAttribute)attr; - - // Truncate to header + flag + data for flag - byte[] data = new byte[16+12]; - System.arraycopy(rtfAttr.getRawData(), 0, data, 0, data.length); - - // Decompress it - CompressedRTF comp = new CompressedRTF(); - byte[] decomp = comp.decompress(new ByteArrayInputStream(data)); - String decompStr = new String(decomp, "ASCII"); - - // Test - assertEquals(block1.length(), decomp.length); - assertEquals(block1, decompStr); - } - - /** - * Check that we can decode the first 16 codes - * (flag + 8 codes, flag + 8 codes) - */ - public void testFirstTwoBlocks() throws Exception { - HMEFMessage msg = new HMEFMessage( - _samples.openResourceAsStream("quick-winmail.dat") - ); - - MAPIAttribute attr = msg.getMessageMAPIAttribute(MAPIProperty.RTF_COMPRESSED); - assertNotNull(attr); - MAPIRtfAttribute rtfAttr = (MAPIRtfAttribute)attr; - - // Truncate to header + flag + data for flag + flag + data - byte[] data = new byte[16+12+13]; - System.arraycopy(rtfAttr.getRawData(), 0, data, 0, data.length); - - // Decompress it - CompressedRTF comp = new CompressedRTF(); - byte[] decomp = comp.decompress(new ByteArrayInputStream(data)); - String decompStr = new String(decomp, "ASCII"); - - // Test - assertEquals(block2.length(), decomp.length); - assertEquals(block2, decompStr); - } - - /** - * Check that we can correctly decode the whole file - * TODO Fix what looks like a padding issue - */ - public void testFull() throws Exception { - HMEFMessage msg = new HMEFMessage( - _samples.openResourceAsStream("quick-winmail.dat") - ); - - MAPIAttribute attr = msg.getMessageMAPIAttribute(MAPIProperty.RTF_COMPRESSED); - assertNotNull(attr); - MAPIRtfAttribute rtfAttr = (MAPIRtfAttribute)attr; - - InputStream stream = _samples.openResourceAsStream("quick-contents/message.rtf"); - try { - byte[] expected = IOUtils.toByteArray(stream); - - CompressedRTF comp = new CompressedRTF(); - byte[] data = rtfAttr.getRawData(); - byte[] decomp = comp.decompress(new ByteArrayInputStream(data)); - - // Check the length was as expected - assertEquals(data.length, comp.getCompressedSize() + 16); - assertEquals(expected.length, comp.getDeCompressedSize()); - - // Will have been padded though - assertEquals(expected.length+2, decomp.length); - byte[] tmp = new byte[expected.length]; - System.arraycopy(decomp, 0, tmp, 0, tmp.length); - decomp = tmp; - - // By byte - assertEquals(expected.length, decomp.length); - for(int i=0; i= 20); - assertTrue("Should be 20-25 mapi attributes, found " + mapiAttrCount, mapiAttrCount <= 25); - } - } - - public void testBasicMessageAttributes() throws Exception { - HMEFMessage msg = new HMEFMessage( - _samples.openResourceAsStream("quick-winmail.dat") - ); - - // Should have version, codepage, class and MAPI - assertEquals(4, msg.getMessageAttributes().size()); - assertNotNull(msg.getMessageAttribute(TNEFProperty.ID_TNEFVERSION)); - assertNotNull(msg.getMessageAttribute(TNEFProperty.ID_OEMCODEPAGE)); - assertNotNull(msg.getMessageAttribute(TNEFProperty.ID_MESSAGECLASS)); - assertNotNull(msg.getMessageAttribute(TNEFProperty.ID_MAPIPROPERTIES)); - - // Check the order - assertEquals(TNEFProperty.ID_TNEFVERSION, msg.getMessageAttributes().get(0).getProperty()); - assertEquals(TNEFProperty.ID_OEMCODEPAGE, msg.getMessageAttributes().get(1).getProperty()); - assertEquals(TNEFProperty.ID_MESSAGECLASS, msg.getMessageAttributes().get(2).getProperty()); - assertEquals(TNEFProperty.ID_MAPIPROPERTIES, msg.getMessageAttributes().get(3).getProperty()); - - // Check some that aren't there - assertNull(msg.getMessageAttribute(TNEFProperty.ID_AIDOWNER)); - assertNull(msg.getMessageAttribute(TNEFProperty.ID_ATTACHDATA)); - - // Now check the details of one or two - assertEquals( - 0x010000, - LittleEndian.getInt( msg.getMessageAttribute(TNEFProperty.ID_TNEFVERSION).getData() ) - ); - assertEquals( - "IPM.Microsoft Mail.Note\0", - new String(msg.getMessageAttribute(TNEFProperty.ID_MESSAGECLASS).getData(), "ASCII") - ); - } - - public void testBasicMessageMAPIAttributes() throws Exception { - HMEFMessage msg = new HMEFMessage( - _samples.openResourceAsStream("quick-winmail.dat") - ); - - assertEquals("This is a test message", msg.getSubject()); - assertEquals("{\\rtf1", msg.getBody().substring(0, 6)); - } - - /** - * Checks that the compressed RTF message contents - * can be correctly extracted - */ - public void testMessageContents() throws Exception { - HMEFMessage msg = new HMEFMessage( - _samples.openResourceAsStream("quick-winmail.dat") - ); - - // Firstly by byte - MAPIRtfAttribute rtf = (MAPIRtfAttribute) - msg.getMessageMAPIAttribute(MAPIProperty.RTF_COMPRESSED); - assertContents("message.rtf", rtf.getData()); - - // Then by String - String contents = msg.getBody(); - // It's all low bytes - byte[] contentsBytes = contents.getBytes("ASCII"); - assertContents("message.rtf", contentsBytes); - - // try to get a message id that does not exist - assertNull(msg.getMessageMAPIAttribute(MAPIProperty.AB_DEFAULT_DIR)); - } - - public void testMessageSample1() throws Exception { - HMEFMessage msg = new HMEFMessage( - _samples.openResourceAsStream("winmail-sample1.dat")); - - // Firstly by byte - MAPIRtfAttribute rtf = (MAPIRtfAttribute) msg - .getMessageMAPIAttribute(MAPIProperty.RTF_COMPRESSED); - // assertContents("message.rtf", rtf.getData()); - assertNotNull(rtf); - - // Then by String - String contents = msg.getBody(); - //System.out.println(contents); - // It's all low bytes - byte[] contentsBytes = contents.getBytes("ASCII"); - // assertContents("message.rtf", contentsBytes); - assertNotNull(contentsBytes); - - assertNotNull(msg.getSubject()); - assertNotNull(msg.getBody()); - } - - public void testInvalidMessage() throws Exception { - InputStream str = new ByteArrayInputStream(new byte[] {0, 0, 0, 0}); - try { - assertNotNull(new HMEFMessage(str)); - fail("Should catch an exception here"); - } catch (IllegalArgumentException e) { - assertTrue(e.getMessage().contains("TNEF signature not detected in file, expected 574529400 but got 0")); - } - } - - - public void testNoData() throws Exception { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - - // Header - LittleEndian.putInt(HMEFMessage.HEADER_SIGNATURE, out); - - // field - LittleEndian.putUShort(0, out); - - byte[] bytes = out.toByteArray(); - InputStream str = new ByteArrayInputStream(bytes); - HMEFMessage msg = new HMEFMessage(str); - assertNull(msg.getSubject()); - assertNull(msg.getBody()); - } - - public void testInvalidLevel() throws Exception { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - - // Header - LittleEndian.putInt(HMEFMessage.HEADER_SIGNATURE, out); - - // field - LittleEndian.putUShort(0, out); - - // invalid level - LittleEndian.putUShort(90, out); - - byte[] bytes = out.toByteArray(); - InputStream str = new ByteArrayInputStream(bytes); - try { - assertNotNull(new HMEFMessage(str)); - fail("Should catch an exception here"); - } catch (IllegalStateException e) { - assertTrue(e.getMessage().contains("Unhandled level 90")); - } - } - - public void testCustomProperty() throws Exception { - HMEFMessage msg = new HMEFMessage( - _samples.openResourceAsStream("quick-winmail.dat") - ); - - // Should have non-standard properties with IDs 0xE28 and 0xE29 - boolean hasE28 = false; - boolean hasE29 = false; - for (MAPIAttribute attr : msg.getMessageMAPIAttributes()) { - if (attr.getProperty().id == 0xe28) hasE28 = true; - if (attr.getProperty().id == 0xe29) hasE29 = true; - } - assertEquals(true, hasE28); - assertEquals(true, hasE29); - - // Ensure we can fetch those as custom ones - MAPIProperty propE28 = MAPIProperty.createCustom(0xe28, Types.ASCII_STRING, "Custom E28"); - MAPIProperty propE29 = MAPIProperty.createCustom(0xe29, Types.ASCII_STRING, "Custom E29"); - assertNotNull(msg.getMessageMAPIAttribute(propE28)); - assertNotNull(msg.getMessageMAPIAttribute(propE29)); - - assertEquals(MAPIStringAttribute.class, msg.getMessageMAPIAttribute(propE28).getClass()); - assertEquals( - "Zimbra - Mark Rogers", - ((MAPIStringAttribute)msg.getMessageMAPIAttribute(propE28)).getDataString().substring(10) - ); - } -} - diff --git a/src/scratchpad/testcases/org/apache/poi/hmef/attribute/TestMAPIAttributes.java b/src/scratchpad/testcases/org/apache/poi/hmef/attribute/TestMAPIAttributes.java deleted file mode 100644 index f85439481..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hmef/attribute/TestMAPIAttributes.java +++ /dev/null @@ -1,187 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hmef.attribute; - -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.text.DateFormat; -import java.util.Locale; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hmef.HMEFMessage; -import org.apache.poi.hsmf.datatypes.MAPIProperty; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.LocaleUtil; - -import junit.framework.TestCase; - -public final class TestMAPIAttributes extends TestCase { - private static final POIDataSamples _samples = POIDataSamples.getHMEFInstance(); - private HMEFMessage quick; - private InputStream stream; - - @Override - protected void setUp() throws Exception { - super.setUp(); - - stream = _samples.openResourceAsStream("quick-winmail.dat"); - quick = new HMEFMessage(stream); - } - - - @Override -protected void tearDown() throws Exception { - stream.close(); - - super.tearDown(); - } - - -/** - * Test counts - */ - public void testCounts() throws Exception { - // Message should have 54 - assertEquals(54, quick.getMessageMAPIAttributes().size()); - - // First attachment should have 22 - assertEquals(22, quick.getAttachments().get(0).getMAPIAttributes().size()); - } - - /** - * Test various general ones - */ - public void testBasics() throws Exception { - // Try constructing two attributes - byte[] data = new byte[] { - // Level one, id 36867, type 6 - 0x01, 0x03, (byte)0x90, 0x06, 0x00, - // Length 24 - 0x24, 0x00, 0x00, 0x00, - - // Three attributes - 0x03, 0x00, 0x00, 0x00, - // AlternateRecipientAllowed = 01 00 - 0x0B, 0x00, 0x02, 0x00, - 0x01, 0x00, 0x00, 0x00, - // Priority = 00 00 00 00 - 0x03, 0x00, 0x26, 0x00, - 0x00, 0x00, 0x00, 0x00, - // ConversationTopic = Test - 0x1E, 0x00, 0x70, 0x00, - 0x01, 0x00, 0x00, 0x00, - 0x04, 0x00, 0x00, 0x00, - (byte)'T', (byte)'e', - (byte)'s', (byte)'t', - // Checksum (may be wrong...) - 0x01, 0x00 - }; - ByteArrayInputStream bais = new ByteArrayInputStream(data); - - // Create it - int level = bais.read(); - assertEquals(1, level); - TNEFAttribute attr = TNEFAttribute.create(bais); - - // Check it - assertNotNull(attr); - assertEquals(TNEFMAPIAttribute.class, attr.getClass()); - - TNEFMAPIAttribute mapi = (TNEFMAPIAttribute)attr; - assertEquals(3, mapi.getMAPIAttributes().size()); - - assertEquals( - MAPIProperty.ALTERNATE_RECIPIENT_ALLOWED, - mapi.getMAPIAttributes().get(0).getProperty() - ); - assertEquals(1, LittleEndian.getUShort( - mapi.getMAPIAttributes().get(0).getData() - )); - - assertEquals( - MAPIProperty.PRIORITY, - mapi.getMAPIAttributes().get(1).getProperty() - ); - assertEquals(0, LittleEndian.getUShort( - mapi.getMAPIAttributes().get(1).getData() - )); - - assertEquals( - MAPIProperty.CONVERSATION_TOPIC, - mapi.getMAPIAttributes().get(2).getProperty() - ); - assertEquals( - "Test", - ((MAPIStringAttribute)mapi.getMAPIAttributes().get(2)).getDataString() - ); - } - - /** - * Test String, Date and RTF ones - */ - public void testTyped() throws Exception { - MAPIAttribute attr; - - // String - // ConversationTopic -> This is a test message - attr = quick.getMessageMAPIAttribute(MAPIProperty.CONVERSATION_TOPIC); - assertNotNull(attr); - assertEquals(MAPIStringAttribute.class, attr.getClass()); - - MAPIStringAttribute str = (MAPIStringAttribute)attr; - assertEquals("This is a test message", str.getDataString()); - - // Date - // (Unknown/Custom) 32955 -> Wed Dec 15 2010 @ 14:46:31 UTC - attr = null; - for(MAPIAttribute a : quick.getMessageMAPIAttributes()) { - if(a.getProperty().id == 32955) { - attr = a; - break; - } - } - assertNotNull(attr); - assertEquals(MAPIDateAttribute.class, attr.getClass()); - - MAPIDateAttribute date = (MAPIDateAttribute)attr; - DateFormat fmt = DateFormat.getDateTimeInstance( - DateFormat.MEDIUM, DateFormat.MEDIUM, Locale.UK - ); - fmt.setTimeZone(LocaleUtil.TIMEZONE_UTC); - assertEquals("15-Dec-2010 14:46:31", fmt.format(date.getDate())); - - // RTF - // RtfCompressed -> {\rtf1... - attr = quick.getMessageMAPIAttribute(MAPIProperty.RTF_COMPRESSED); - assertNotNull(attr); - assertEquals(MAPIRtfAttribute.class, attr.getClass()); - - MAPIRtfAttribute rtf = (MAPIRtfAttribute)attr; - assertEquals("{\\rtf1", rtf.getDataString().substring(0, 6)); - } - - /** - * Check common ones via helper accessors - */ - public void testCommon() throws Exception { - assertEquals("This is a test message", quick.getSubject()); - - assertEquals("quick.doc", quick.getAttachments().get(0).getLongFilename()); - assertEquals(".doc", quick.getAttachments().get(0).getExtension()); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hmef/attribute/TestTNEFAttributes.java b/src/scratchpad/testcases/org/apache/poi/hmef/attribute/TestTNEFAttributes.java deleted file mode 100644 index cd13b94b3..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hmef/attribute/TestTNEFAttributes.java +++ /dev/null @@ -1,210 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hmef.attribute; - -import java.io.ByteArrayInputStream; -import java.text.DateFormat; -import java.util.Locale; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hmef.Attachment; -import org.apache.poi.hmef.HMEFMessage; -import org.apache.poi.hsmf.datatypes.MAPIProperty; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.LocaleUtil; - -import junit.framework.TestCase; - -public final class TestTNEFAttributes extends TestCase { - private static final POIDataSamples _samples = POIDataSamples.getHMEFInstance(); - private HMEFMessage quick; - - @Override - protected void setUp() throws Exception { - super.setUp(); - - quick = new HMEFMessage( - _samples.openResourceAsStream("quick-winmail.dat") - ); - } - - /** - * Test counts - */ - public void testCounts() throws Exception { - // The message should have 4 attributes - assertEquals(4, quick.getMessageAttributes().size()); - - // Each attachment should have 6 attributes - for(Attachment attach : quick.getAttachments()) { - assertEquals(6, attach.getAttributes().size()); - } - } - - /** - * Test the basics - */ - public void testBasics() throws Exception { - // An int one - assertEquals( - 0x010000, - LittleEndian.getInt( quick.getMessageAttribute(TNEFProperty.ID_TNEFVERSION).getData() ) - ); - - // Claims not to be text, but really is - assertEquals( - "IPM.Microsoft Mail.Note\0", - new String(quick.getMessageAttribute(TNEFProperty.ID_MESSAGECLASS).getData(), "ASCII") - ); - - // Try constructing two attributes - byte[] data = new byte[] { - // Level one, id 36870, type 8 - 0x01, 0x06, (byte)0x90, 0x08, 0x00, - // Length 4 - 0x04, 0x00, 0x00, 0x00, - // Data - 0x00, 0x00, 0x01, 0x00, - // Checksum - 0x01, 0x00, - - // level one, id 36871, type 6 - 0x01, 0x07, (byte)0x90, 0x06, 0x00, - // Length 8 - 0x08, 0x00, 0x00, 0x00, - // Data - (byte)0xe4, 0x04, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, - // Checksum - (byte)0xe8, 0x00 - }; - ByteArrayInputStream bais = new ByteArrayInputStream(data); - - // Create them - int level = bais.read(); - assertEquals(1, level); - TNEFAttribute attr1 = TNEFAttribute.create(bais); - - level = bais.read(); - assertEquals(1, level); - TNEFAttribute attr2 = TNEFAttribute.create(bais); - - assertEquals(-1, bais.read()); - - // Check them - assertEquals(TNEFProperty.ID_TNEFVERSION, attr1.getProperty()); - assertEquals(8, attr1.getType()); - assertEquals(4, attr1.getData().length); - assertEquals(0x010000, LittleEndian.getInt( attr1.getData() )); - - assertEquals(TNEFProperty.ID_OEMCODEPAGE, attr2.getProperty()); - assertEquals(6, attr2.getType()); - assertEquals(8, attr2.getData().length); - assertEquals(0x04e4, LittleEndian.getInt( attr2.getData() )); - } - - /** - * Test string based ones - */ - public void testString() throws Exception { - TNEFAttribute attr = quick.getAttachments().get(0).getAttribute( - TNEFProperty.ID_ATTACHTITLE - ); - assertNotNull(attr); - assertEquals(TNEFStringAttribute.class, attr.getClass()); - - // It is a null terminated string - assertEquals("quick.doc\u0000", new String(attr.getData(), "ASCII")); - - // But when we ask for the string, that is sorted for us - TNEFStringAttribute str = (TNEFStringAttribute)attr; - assertEquals("quick.doc", str.getString()); - } - - /** - * Test date based ones - */ - public void testDate() throws Exception { - TNEFAttribute attr = quick.getAttachments().get(0).getAttribute( - TNEFProperty.ID_ATTACHMODIFYDATE - ); - assertNotNull(attr); - assertEquals(TNEFDateAttribute.class, attr.getClass()); - - // It is a series of date parts - // Weds 28th April 2010 @ 12:40:56 UTC - assertEquals(2010, LittleEndian.getUShort(attr.getData(), 0)); - assertEquals(04, LittleEndian.getUShort(attr.getData(), 2)); - assertEquals(28, LittleEndian.getUShort(attr.getData(), 4)); - assertEquals(12, LittleEndian.getUShort(attr.getData(), 6)); - assertEquals(40, LittleEndian.getUShort(attr.getData(), 8)); - assertEquals(56, LittleEndian.getUShort(attr.getData(), 10)); - assertEquals(3, LittleEndian.getUShort(attr.getData(), 12)); // Weds - - // Ask for it as a Java date, and have it converted - // Pick a predictable format + location + timezone - TNEFDateAttribute date = (TNEFDateAttribute)attr; - DateFormat fmt = DateFormat.getDateTimeInstance( - DateFormat.MEDIUM, DateFormat.MEDIUM, Locale.UK - ); - fmt.setTimeZone(LocaleUtil.TIMEZONE_UTC); - assertEquals("28-Apr-2010 12:40:56", fmt.format(date.getDate())); - } - - /** - * Test a bit of mapi - */ - public void testMAPI() throws Exception { - // Message MAPI - TNEFAttribute attr = quick.getMessageAttribute( - TNEFProperty.ID_MAPIPROPERTIES - ); - assertNotNull(attr); - assertEquals(TNEFMAPIAttribute.class, attr.getClass()); - - TNEFMAPIAttribute mapi = (TNEFMAPIAttribute)attr; - assertEquals(54, mapi.getMAPIAttributes().size()); - assertEquals( - MAPIProperty.ALTERNATE_RECIPIENT_ALLOWED, - mapi.getMAPIAttributes().get(0).getProperty() - ); - - - // Attribute MAPI - attr = quick.getAttachments().get(0).getAttribute( - TNEFProperty.ID_ATTACHMENT - ); - assertNotNull(attr); - assertEquals(TNEFMAPIAttribute.class, attr.getClass()); - - mapi = (TNEFMAPIAttribute)attr; - assertEquals(22, mapi.getMAPIAttributes().size()); - assertEquals( - MAPIProperty.ATTACH_SIZE, - mapi.getMAPIAttributes().get(0).getProperty() - ); - } - - /** - * Test common ones via helpers - */ - public void testCommon() throws Exception { - assertEquals("This is a test message", quick.getSubject()); - assertEquals("quick.doc", quick.getAttachments().get(0).getFilename()); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hmef/dev/TestHMEFDumper.java b/src/scratchpad/testcases/org/apache/poi/hmef/dev/TestHMEFDumper.java deleted file mode 100644 index 5d956b0cb..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hmef/dev/TestHMEFDumper.java +++ /dev/null @@ -1,50 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - - 2012 - Alfresco Software, Ltd. - Alfresco Software has modified source of this file - The details of changes as svn diff can be found in svn at location root/projects/3rd-party/src -==================================================================== */ -package org.apache.poi.hmef.dev; - -import org.apache.poi.POIDataSamples; -import org.junit.Test; - -import java.io.File; - -public class TestHMEFDumper { - @Test(expected = IllegalArgumentException.class) - public void noArguments() throws Exception { - HMEFDumper.main(new String[] {}); - } - - @Test - public void main() throws Exception { - File file = POIDataSamples.getHMEFInstance().getFile("quick-winmail.dat"); - HMEFDumper.main(new String[] { - file.getAbsolutePath() - }); - } - - @Test - public void mainFull() throws Exception { - File file = POIDataSamples.getHMEFInstance().getFile("quick-winmail.dat"); - HMEFDumper.main(new String[] { - "--full", - file.getAbsolutePath() - }); - } -} \ No newline at end of file diff --git a/src/scratchpad/testcases/org/apache/poi/hmef/extractor/TestHMEFContentsExtractor.java b/src/scratchpad/testcases/org/apache/poi/hmef/extractor/TestHMEFContentsExtractor.java deleted file mode 100644 index 2cfd64490..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hmef/extractor/TestHMEFContentsExtractor.java +++ /dev/null @@ -1,78 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hmef.extractor; - -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.assertArrayEquals; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.util.Arrays; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.util.TempFile; -import org.junit.Test; - -public class TestHMEFContentsExtractor { - @Test - public void TestMain() throws IOException { - POIDataSamples samples = POIDataSamples.getHMEFInstance(); - File message = samples.getFile("quick-winmail.dat"); - File outputDirectory = TempFile.createTempDirectory("quick-winmail-main"); - String[] args = new String[] { message.getAbsolutePath(), outputDirectory.getAbsolutePath() }; - HMEFContentsExtractor.main(args); - - String[] contents = new String[] { - "message.rtf", // from extractMessageBody - "quick.txt", "quick.pdf", "quick.xml", "quick.doc", "quick.html" // from extractAttachments - }; - - for (String filename : contents) { - File f = new File(outputDirectory, filename); - assertTrue(f + " does not exist", f.exists()); - } - - outputDirectory.delete(); - } - - @Test - public void TestExtractMessageBody_OutputStream() throws IOException { - POIDataSamples samples = POIDataSamples.getHMEFInstance(); - File winmailTNEFFile = samples.getFile("quick-winmail.dat"); - HMEFContentsExtractor extractor = new HMEFContentsExtractor(winmailTNEFFile); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - extractor.extractMessageBody(out); - assertTrue(out.size() > 0); - byte[] expectedMagic = new byte[] { '{', '\\', 'r', 't', 'f' }; - byte[] magic = Arrays.copyOf(out.toByteArray(), 5); - assertArrayEquals("RTF magic number", expectedMagic, magic); - out.close(); - } - - @Test - public void TestExtractMessageBody_File() throws IOException { - POIDataSamples samples = POIDataSamples.getHMEFInstance(); - File winmailTNEFFile = samples.getFile("quick-winmail.dat"); - HMEFContentsExtractor extractor = new HMEFContentsExtractor(winmailTNEFFile); - File rtf = TempFile.createTempFile("quick-winmail-message-body", ".rtf"); - assertTrue(rtf.delete()); - extractor.extractMessageBody(rtf); - assertTrue("RTF message body is empty", rtf.length() > 0); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hpbf/TestHPBFDocument.java b/src/scratchpad/testcases/org/apache/poi/hpbf/TestHPBFDocument.java deleted file mode 100644 index ff290d711..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hpbf/TestHPBFDocument.java +++ /dev/null @@ -1,63 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hpbf; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.POIDataSamples; -import org.junit.Test; - -public final class TestHPBFDocument { - private static final POIDataSamples _samples = POIDataSamples.getPublisherInstance(); - - @Test - public void testOpen() throws IOException { - InputStream is = _samples.openResourceAsStream("Sample.pub"); - HPBFDocument doc = new HPBFDocument(is); - is.close(); - assertNotNull(doc); - doc.close(); - } - - @Test - public void testBits() throws IOException { - InputStream is = _samples.openResourceAsStream("Sample.pub"); - HPBFDocument doc = new HPBFDocument(is); - is.close(); - - assertNotNull(doc.getMainContents()); - assertNotNull(doc.getQuillContents()); - assertNotNull(doc.getEscherStm()); - assertNotNull(doc.getEscherDelayStm()); - - assertTrue(doc.getMainContents().getData().length > 0); - assertTrue(doc.getQuillContents().getData().length > 0); - assertTrue(doc.getEscherStm().getData().length > 0); - assertTrue(doc.getEscherDelayStm().getData().length == 0); - - doc.close(); - } - - // TODO -// public void testWrite() throws Exception { -// } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hpbf/extractor/TestPublisherTextExtractor.java b/src/scratchpad/testcases/org/apache/poi/hpbf/extractor/TestPublisherTextExtractor.java deleted file mode 100644 index 35920b577..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hpbf/extractor/TestPublisherTextExtractor.java +++ /dev/null @@ -1,187 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hpbf.extractor; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hpbf.HPBFDocument; -import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; -import org.junit.Test; - -public final class TestPublisherTextExtractor { - private static final POIDataSamples _samples = POIDataSamples.getPublisherInstance(); - - private static final String SAMPLE_TEXT = - "This is some text on the first page\n" + - "It\u2019s in times new roman, font size 10, all normal\n" + - "" + - "This is in bold and italic\n" + - "It\u2019s Arial, 20 point font\n" + - "It\u2019s in the second textbox on the first page\n" + - "" + - "This is the second page\n\n" + - "" + - "It is also times new roman, 10 point\n" + - "" + - "Table on page 2\nTop right\n" + - "P2 table left\nP2 table right\n" + - "Bottom Left\nBottom Right\n" + - "" + - "This text is on page two\n" + - "#This is a link to Apache POI\n" + - "More normal text\n" + - "Link to a file\n" + - "" + - "More text, more hyperlinks\n" + - "email link\n" + - "Final hyperlink\n" + - "Within doc to page 1\n"; - - private static final String SIMPLE_TEXT = - "0123456789\n" + - "0123456789abcdef\n" + - "0123456789abcdef0123456789abcdef\n" + - "0123456789\n" + - "0123456789abcdef\n" + - "0123456789abcdef0123456789abcdef\n" + - "0123456789abcdef0123456789abcdef0123456789abcdef\n"; - - @Test - public void testBasics() throws IOException { - InputStream sample = _samples.openResourceAsStream("Sample.pub"); - HPBFDocument doc = new HPBFDocument(sample); - PublisherTextExtractor ext = new PublisherTextExtractor(doc); - assertNotNull(ext.getText()); - ext.close(); - doc.close(); - sample.close(); - - InputStream simple = _samples.openResourceAsStream("Simple.pub"); - ext = new PublisherTextExtractor(simple); - assertNotNull(ext.getText()); - ext.close(); - simple.close(); - } - - @Test - public void testContents() throws IOException { - // Check this complicated file using POIFS - InputStream sample = _samples.openResourceAsStream("Sample.pub"); - HPBFDocument docOPOIFS = new HPBFDocument(sample); - PublisherTextExtractor ext = new PublisherTextExtractor(docOPOIFS); - assertEquals(SAMPLE_TEXT, ext.getText()); - ext.close(); - docOPOIFS.close(); - sample.close(); - - // And with NPOIFS - sample = _samples.openResourceAsStream("Sample.pub"); - NPOIFSFileSystem fs = new NPOIFSFileSystem(sample); - HPBFDocument docNPOIFS = new HPBFDocument(fs); - ext = new PublisherTextExtractor(docNPOIFS); - assertEquals(SAMPLE_TEXT, ext.getText()); - ext.close(); - docNPOIFS.close(); - fs.close(); - sample.close(); - - // Now a simpler file - InputStream simple = _samples.openResourceAsStream("Simple.pub"); - ext = new PublisherTextExtractor(simple); - assertEquals(SIMPLE_TEXT, ext.getText()); - ext.close(); - } - - /** - * We have the same file saved for Publisher 98, Publisher 2000 and - * Publisher 2007. Check they all agree. - * - * @throws Exception - */ - @Test - public void testMultipleVersions() throws Exception { - InputStream sample = _samples.openResourceAsStream("Sample.pub"); - HPBFDocument doc = new HPBFDocument(sample); - PublisherTextExtractor ext = new PublisherTextExtractor(doc); - String s2007 = ext.getText(); - ext.close(); - doc.close(); - sample.close(); - - InputStream sample2000 = _samples.openResourceAsStream("Sample2000.pub"); - doc = new HPBFDocument(sample2000); - ext = new PublisherTextExtractor(doc); - String s2000 = ext.getText(); - ext.close(); - doc.close(); - sample2000.close(); - - InputStream sample98 = _samples.openResourceAsStream("Sample98.pub"); - doc = new HPBFDocument(sample98); - ext = new PublisherTextExtractor(doc); - String s98 = ext.getText(); - ext.close(); - doc.close(); - sample98.close(); - - // Check they all agree - assertEquals(s2007, s2000); - assertEquals(s2007, s98); - } - - /** - * Test that the hyperlink extraction stuff works as well as we can hope it - * to. - */ - @Test - public void testWithHyperlinks() throws Exception { - InputStream linkAt = _samples.openResourceAsStream("LinkAt10.pub"); - HPBFDocument doc = new HPBFDocument(linkAt); - - PublisherTextExtractor ext = new PublisherTextExtractor(doc); - - // Default is no hyperlinks - assertEquals("1234567890LINK\n", ext.getText()); - - // Turn on - ext.setHyperlinksByDefault(true); - assertEquals("1234567890LINK\n\n", ext.getText()); - ext.close(); - doc.close(); - linkAt.close(); - - // Now a much more complex document - InputStream sample = _samples.openResourceAsStream("Sample.pub"); - ext = new PublisherTextExtractor(sample); - ext.setHyperlinksByDefault(true); - String text = ext.getText(); - ext.close(); - sample.close(); - - assertTrue(text.endsWith("\n" - + "\n" - + "<>\n" + "\n" - + "\n")); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hpbf/model/TestEscherParts.java b/src/scratchpad/testcases/org/apache/poi/hpbf/model/TestEscherParts.java deleted file mode 100644 index 28e1eeca6..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hpbf/model/TestEscherParts.java +++ /dev/null @@ -1,85 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hpbf.model; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hpbf.HPBFDocument; -import org.junit.Test; - -public final class TestEscherParts { - private static final POIDataSamples _samples = POIDataSamples.getPublisherInstance(); - - @Test - public void testBasics() throws IOException { - InputStream is = _samples.openResourceAsStream("Sample.pub"); - HPBFDocument doc = new HPBFDocument(is); - is.close(); - - EscherStm es = doc.getEscherStm(); - EscherDelayStm eds = doc.getEscherDelayStm(); - - assertNotNull(es); - assertNotNull(eds); - - assertEquals(13, es.getEscherRecords().length); - assertEquals(0, eds.getEscherRecords().length); - - // TODO - check the contents - doc.close(); - } - - @Test - public void testComplex() throws Exception { - InputStream is = _samples.openResourceAsStream("SampleBrochure.pub"); - HPBFDocument doc1 = new HPBFDocument(is); - is.close(); - - EscherStm es = doc1.getEscherStm(); - EscherDelayStm eds = doc1.getEscherDelayStm(); - - assertNotNull(es); - assertNotNull(eds); - - assertEquals(30, es.getEscherRecords().length); - assertEquals(19, eds.getEscherRecords().length); - - // TODO - check contents - doc1.close(); - - // Now do another complex file - InputStream is2 = _samples.openResourceAsStream("SampleNewsletter.pub"); - HPBFDocument doc2 = new HPBFDocument(is2); - is2.close(); - - es = doc2.getEscherStm(); - eds = doc2.getEscherDelayStm(); - - assertNotNull(es); - assertNotNull(eds); - - assertEquals(51, es.getEscherRecords().length); - assertEquals(92, eds.getEscherRecords().length); - doc2.close(); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hpbf/model/TestQuillContents.java b/src/scratchpad/testcases/org/apache/poi/hpbf/model/TestQuillContents.java deleted file mode 100644 index a251d0527..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hpbf/model/TestQuillContents.java +++ /dev/null @@ -1,446 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hpbf.model; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hpbf.HPBFDocument; -import org.apache.poi.hpbf.model.qcbits.QCPLCBit.Type0; -import org.apache.poi.hpbf.model.qcbits.QCPLCBit.Type12; -import org.apache.poi.hpbf.model.qcbits.QCPLCBit.Type4; -import org.apache.poi.hpbf.model.qcbits.QCPLCBit.Type8; -import org.apache.poi.hpbf.model.qcbits.QCTextBit; -import org.junit.Test; - -public final class TestQuillContents { - private static final POIDataSamples _samples = POIDataSamples.getPublisherInstance(); - - @Test - public void testBasics() throws IOException { - HPBFDocument doc = new HPBFDocument( - _samples.openResourceAsStream("Sample.pub") - ); - - QuillContents qc = doc.getQuillContents(); - assertEquals(20, qc.getBits().length); - for(int i=0; i<19; i++) { - assertNotNull(qc.getBits()[i]); - } - // Last one is blank - assertNull(qc.getBits()[19]); - - // Should be text, then three STSHs - assertEquals("TEXT", qc.getBits()[0].getThingType()); - assertEquals("TEXT", qc.getBits()[0].getBitType()); - assertEquals(0, qc.getBits()[0].getOptA()); - - assertEquals("STSH", qc.getBits()[1].getThingType()); - assertEquals("STSH", qc.getBits()[1].getBitType()); - assertEquals(0, qc.getBits()[1].getOptA()); - - assertEquals("STSH", qc.getBits()[2].getThingType()); - assertEquals("STSH", qc.getBits()[2].getBitType()); - assertEquals(1, qc.getBits()[2].getOptA()); - - assertEquals("STSH", qc.getBits()[3].getThingType()); - assertEquals("STSH", qc.getBits()[3].getBitType()); - assertEquals(2, qc.getBits()[3].getOptA()); - - doc.close(); - } - - @Test - public void testText() throws IOException { - HPBFDocument doc = new HPBFDocument( - _samples.openResourceAsStream("Sample.pub") - ); - - QuillContents qc = doc.getQuillContents(); - assertEquals(20, qc.getBits().length); - - QCTextBit text = (QCTextBit)qc.getBits()[0]; - String t = text.getText(); - assertTrue(t.startsWith("This is some text on the first page")); - assertTrue(t.endsWith("Within doc to page 1\r")); - - doc.close(); - } - - @Test - public void testPLC() throws IOException { - HPBFDocument doc = new HPBFDocument( - _samples.openResourceAsStream("Simple.pub") - ); - - QuillContents qc = doc.getQuillContents(); - assertEquals(20, qc.getBits().length); - - assertTrue(qc.getBits()[9] instanceof Type4); - assertTrue(qc.getBits()[10] instanceof Type4); - assertTrue(qc.getBits()[12] instanceof Type8); - - Type4 plc9 = (Type4)qc.getBits()[9]; - Type4 plc10 = (Type4)qc.getBits()[10]; - Type8 plc12 = (Type8)qc.getBits()[12]; - - - assertEquals(1, plc9.getNumberOfPLCs()); - assertEquals(4, plc9.getPreData().length); - assertEquals(1, plc9.getPlcValA().length); - assertEquals(1, plc9.getPlcValB().length); - - assertEquals(0, plc9.getPreData()[0]); - assertEquals(0, plc9.getPreData()[1]); - assertEquals(0, plc9.getPreData()[2]); - assertEquals(0, plc9.getPreData()[3]); - assertEquals(0x356, plc9.getPlcValA()[0]); - assertEquals(0x600, plc9.getPlcValB()[0]); - - - assertEquals(1, plc10.getNumberOfPLCs()); - assertEquals(4, plc10.getPreData().length); - assertEquals(1, plc10.getPlcValA().length); - assertEquals(1, plc10.getPlcValB().length); - - assertEquals(0, plc10.getPreData()[0]); - assertEquals(0, plc10.getPreData()[1]); - assertEquals(0, plc10.getPreData()[2]); - assertEquals(0, plc10.getPreData()[3]); - assertEquals(0x356, plc10.getPlcValA()[0]); - assertEquals(0x800, plc10.getPlcValB()[0]); - - assertEquals(2, plc12.getNumberOfPLCs()); - assertEquals(7, plc12.getPreData().length); - assertEquals(2, plc12.getPlcValA().length); - assertEquals(2, plc12.getPlcValB().length); - - assertEquals(0xff, plc12.getPreData()[0]); - assertEquals(0, plc12.getPreData()[1]); - assertEquals(0x3d, plc12.getPreData()[2]); - assertEquals(0, plc12.getPreData()[3]); - assertEquals(0x6e, plc12.getPreData()[4]); - assertEquals(0, plc12.getPreData()[5]); - assertEquals(0, plc12.getPreData()[6]); - assertEquals(0xa0000, plc12.getPlcValA()[0]); - assertEquals(0x22000000, plc12.getPlcValB()[0]); - assertEquals(0x05, plc12.getPlcValA()[1]); - assertEquals(0x04, plc12.getPlcValB()[1]); - - doc.close(); - } - - @SuppressWarnings("unused") - @Test - public void testComplexPLC() throws IOException { - HPBFDocument doc = new HPBFDocument( - _samples.openResourceAsStream("Sample.pub") - ); - - QuillContents qc = doc.getQuillContents(); - assertEquals(20, qc.getBits().length); - - assertTrue(qc.getBits()[10] instanceof Type4); - assertTrue(qc.getBits()[11] instanceof Type4); - assertTrue(qc.getBits()[13] instanceof Type0); - assertTrue(qc.getBits()[14] instanceof Type12); - assertTrue(qc.getBits()[15] instanceof Type12); - assertTrue(qc.getBits()[16] instanceof Type8); - - Type4 plc10 = (Type4)qc.getBits()[10]; - Type4 plc11 = (Type4)qc.getBits()[11]; - Type0 plc13 = (Type0)qc.getBits()[13]; - Type12 plc14 = (Type12)qc.getBits()[14]; - Type12 plc15 = (Type12)qc.getBits()[15]; - Type8 plc16 = (Type8)qc.getBits()[16]; - - - assertEquals(1, plc10.getNumberOfPLCs()); - assertEquals(4, plc10.getPreData().length); - assertEquals(1, plc10.getPlcValA().length); - assertEquals(1, plc10.getPlcValB().length); - - assertEquals(0, plc10.getPreData()[0]); - assertEquals(0, plc10.getPreData()[1]); - assertEquals(0, plc10.getPreData()[2]); - assertEquals(0, plc10.getPreData()[3]); - assertEquals(0x5d0, plc10.getPlcValA()[0]); - assertEquals(0x800, plc10.getPlcValB()[0]); - - - assertEquals(2, plc11.getNumberOfPLCs()); - assertEquals(4, plc11.getPreData().length); - assertEquals(2, plc11.getPlcValA().length); - assertEquals(2, plc11.getPlcValB().length); - - assertEquals(0, plc11.getPreData()[0]); - assertEquals(0, plc11.getPreData()[1]); - assertEquals(0, plc11.getPreData()[2]); - assertEquals(0, plc11.getPreData()[3]); - assertEquals(0x53a, plc11.getPlcValA()[0]); - assertEquals(0x5d0, plc11.getPlcValB()[0]); - assertEquals(0xa00, plc11.getPlcValA()[1]); - assertEquals(0xc00, plc11.getPlcValB()[1]); - - - assertEquals(5, plc13.getNumberOfPLCs()); - assertEquals(4, plc13.getPreData().length); - assertEquals(5, plc13.getPlcValA().length); - assertEquals(5, plc13.getPlcValB().length); - - assertEquals(0xff00, plc13.getPreData()[0]); - assertEquals(0, plc13.getPreData()[1]); - assertEquals(0xf, plc13.getPreData()[2]); - assertEquals(0, plc13.getPreData()[3]); - assertEquals(0x19, plc13.getPlcValA()[0]); - assertEquals(0x00, plc13.getPlcValB()[0]); - assertEquals(0x27, plc13.getPlcValA()[1]); - assertEquals(0x00, plc13.getPlcValB()[1]); - assertEquals(0x36, plc13.getPlcValA()[2]); - assertEquals(0x00, plc13.getPlcValB()[2]); - assertEquals(0x42, plc13.getPlcValA()[3]); - assertEquals(0x00, plc13.getPlcValB()[3]); - assertEquals(0x50, plc13.getPlcValA()[4]); - assertEquals(0x00, plc13.getPlcValB()[4]); - - - // TODO - test the type 12s - - - assertEquals(6, plc16.getNumberOfPLCs()); - assertEquals(7, plc16.getPreData().length); - assertEquals(6, plc16.getPlcValA().length); - assertEquals(6, plc16.getPlcValB().length); - - assertEquals(0xff, plc16.getPreData()[0]); - assertEquals(0, plc16.getPreData()[1]); - assertEquals(0x56, plc16.getPreData()[2]); - assertEquals(0, plc16.getPreData()[3]); - assertEquals(0x62, plc16.getPreData()[4]); - assertEquals(0, plc16.getPreData()[5]); - assertEquals(0x3e, plc16.getPreData()[6]); - assertEquals(0x500000, plc16.getPlcValA()[0]); - assertEquals(0x570000, plc16.getPlcValB()[0]); - assertEquals(0x4b0000, plc16.getPlcValA()[1]); - assertEquals(0x000000, plc16.getPlcValB()[1]); - assertEquals(0x0a0000, plc16.getPlcValA()[2]); - assertEquals(0x22000000, plc16.getPlcValB()[2]); - assertEquals(0x000005, plc16.getPlcValA()[3]); - assertEquals(0x000004, plc16.getPlcValB()[3]); - assertEquals(0x000004, plc16.getPlcValA()[4]); - assertEquals(0x000004, plc16.getPlcValB()[4]); - assertEquals(0x000004, plc16.getPlcValA()[5]); - assertEquals(0x000004, plc16.getPlcValB()[5]); - - doc.close(); - } - - @Test - public void testNoHyperlinks() throws IOException { - HPBFDocument doc = new HPBFDocument( - _samples.openResourceAsStream("SampleNewsletter.pub") - ); - - QuillContents qc = doc.getQuillContents(); - assertEquals(20, qc.getBits().length); - - Type12 plc18 = (Type12)qc.getBits()[18]; - - assertEquals(1, plc18.getNumberOfPLCs()); - assertEquals(0, plc18.getNumberOfHyperlinks()); - assertEquals(0, plc18.getTextStartAt(0)); - assertEquals(601, plc18.getAllTextEndAt()); - - doc.close(); - } - - @Test - public void testSimpleHyperlink() throws IOException { - HPBFDocument doc; - QuillContents qc; - Type12 hlBit; - - // Link at 10 - doc = new HPBFDocument( - _samples.openResourceAsStream("LinkAt10.pub") - ); - qc = doc.getQuillContents(); - - hlBit = (Type12)qc.getBits()[12]; - assertEquals(1, hlBit.getNumberOfPLCs()); - assertEquals(1, hlBit.getNumberOfHyperlinks()); - - assertEquals(10, hlBit.getTextStartAt(0)); - assertEquals(15, hlBit.getAllTextEndAt()); - assertEquals("http://poi.apache.org/", hlBit.getHyperlink(0)); - doc.close(); - - // Longer link at 10 - doc = new HPBFDocument( - _samples.openResourceAsStream("LinkAt10Longer.pub") - ); - qc = doc.getQuillContents(); - - hlBit = (Type12)qc.getBits()[12]; - assertEquals(1, hlBit.getNumberOfPLCs()); - assertEquals(1, hlBit.getNumberOfHyperlinks()); - - assertEquals(10, hlBit.getTextStartAt(0)); - assertEquals(15, hlBit.getAllTextEndAt()); - assertEquals("http://poi.apache.org/hpbf/", hlBit.getHyperlink(0)); - doc.close(); - - // Link at 20 - doc = new HPBFDocument( - _samples.openResourceAsStream("LinkAt20.pub") - ); - qc = doc.getQuillContents(); - - hlBit = (Type12)qc.getBits()[12]; - assertEquals(1, hlBit.getNumberOfPLCs()); - assertEquals(1, hlBit.getNumberOfHyperlinks()); - - assertEquals(20, hlBit.getTextStartAt(0)); - assertEquals(25, hlBit.getAllTextEndAt()); - assertEquals("http://poi.apache.org/", hlBit.getHyperlink(0)); - doc.close(); - } - - @Test - public void testManyHyperlinks() throws IOException { - HPBFDocument doc; - QuillContents qc; - Type12 hlBit; - - // Link at 10 - doc = new HPBFDocument( - _samples.openResourceAsStream("LinkAt10.pub") - ); - qc = doc.getQuillContents(); - - hlBit = (Type12)qc.getBits()[12]; - assertEquals(1, hlBit.getNumberOfPLCs()); - assertEquals(1, hlBit.getNumberOfHyperlinks()); - - assertEquals(10, hlBit.getTextStartAt(0)); - assertEquals(15, hlBit.getAllTextEndAt()); - assertEquals("http://poi.apache.org/", hlBit.getHyperlink(0)); - - doc.close(); - } - - @Test - public void testHyperlinkDifferentVersions() throws IOException { - HPBFDocument doc; - QuillContents qc; - Type12 hlBitA; - Type12 hlBitB; - - // Latest version - doc = new HPBFDocument( - _samples.openResourceAsStream("Sample.pub") - ); - qc = doc.getQuillContents(); - - hlBitA = (Type12)qc.getBits()[14]; - assertEquals(2, hlBitA.getNumberOfPLCs()); - assertEquals(2, hlBitA.getNumberOfHyperlinks()); - - assertEquals(25, hlBitA.getTextStartAt(0)); - assertEquals(72, hlBitA.getTextStartAt(1)); - assertEquals(87, hlBitA.getAllTextEndAt()); - assertEquals("http://poi.apache.org/", hlBitA.getHyperlink(0)); - assertEquals("C:\\Documents and Settings\\Nick\\My Documents\\Booleans.xlsx", hlBitA.getHyperlink(1)); - - hlBitB = (Type12)qc.getBits()[15]; - assertEquals(3, hlBitB.getNumberOfPLCs()); - assertEquals(3, hlBitB.getNumberOfHyperlinks()); - - assertEquals(27, hlBitB.getTextStartAt(0)); - assertEquals(37, hlBitB.getTextStartAt(1)); - assertEquals(54, hlBitB.getTextStartAt(2)); - assertEquals(75, hlBitB.getAllTextEndAt()); - assertEquals("", hlBitB.getHyperlink(0)); - assertEquals("mailto:dev@poi.apache.org?subject=HPBF", hlBitB.getHyperlink(1)); - assertEquals("mailto:dev@poi.apache.org?subject=HPBF", hlBitB.getHyperlink(2)); - doc.close(); - - // 2000 version - doc = new HPBFDocument( - _samples.openResourceAsStream("Sample2000.pub") - ); - qc = doc.getQuillContents(); - - hlBitA = (Type12)qc.getBits()[13]; - assertEquals(2, hlBitA.getNumberOfPLCs()); - assertEquals(2, hlBitA.getNumberOfHyperlinks()); - - assertEquals(25, hlBitA.getTextStartAt(0)); - assertEquals(72, hlBitA.getTextStartAt(1)); - assertEquals(87, hlBitA.getAllTextEndAt()); - assertEquals("http://poi.apache.org/", hlBitA.getHyperlink(0)); - assertEquals("C:\\Documents and Settings\\Nick\\My Documents\\Booleans.xlsx", hlBitA.getHyperlink(1)); - - hlBitB = (Type12)qc.getBits()[14]; - assertEquals(3, hlBitB.getNumberOfPLCs()); - assertEquals(3, hlBitB.getNumberOfHyperlinks()); - - assertEquals(27, hlBitB.getTextStartAt(0)); - assertEquals(37, hlBitB.getTextStartAt(1)); - assertEquals(54, hlBitB.getTextStartAt(2)); - assertEquals(75, hlBitB.getAllTextEndAt()); - assertEquals("", hlBitB.getHyperlink(0)); - assertEquals("mailto:dev@poi.apache.org?subject=HPBF", hlBitB.getHyperlink(1)); - assertEquals("mailto:dev@poi.apache.org?subject=HPBF", hlBitB.getHyperlink(2)); - doc.close(); - - // 98 version - doc = new HPBFDocument( - _samples.openResourceAsStream("Sample98.pub") - ); - qc = doc.getQuillContents(); - - hlBitA = (Type12)qc.getBits()[13]; - assertEquals(2, hlBitA.getNumberOfPLCs()); - assertEquals(2, hlBitA.getNumberOfHyperlinks()); - - assertEquals(25, hlBitA.getTextStartAt(0)); - assertEquals(72, hlBitA.getTextStartAt(1)); - assertEquals(87, hlBitA.getAllTextEndAt()); - assertEquals("http://poi.apache.org/", hlBitA.getHyperlink(0)); - assertEquals("C:\\Documents and Settings\\Nick\\My Documents\\Booleans.xlsx", hlBitA.getHyperlink(1)); - - hlBitB = (Type12)qc.getBits()[14]; - assertEquals(3, hlBitB.getNumberOfPLCs()); - assertEquals(3, hlBitB.getNumberOfHyperlinks()); - - assertEquals(27, hlBitB.getTextStartAt(0)); - assertEquals(37, hlBitB.getTextStartAt(1)); - assertEquals(54, hlBitB.getTextStartAt(2)); - assertEquals(75, hlBitB.getAllTextEndAt()); - assertEquals("", hlBitB.getHyperlink(0)); - assertEquals("mailto:dev@poi.apache.org?subject=HPBF", hlBitB.getHyperlink(1)); - assertEquals("mailto:dev@poi.apache.org?subject=HPBF", hlBitB.getHyperlink(2)); - doc.close(); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/AllHSLFTests.java b/src/scratchpad/testcases/org/apache/poi/hslf/AllHSLFTests.java deleted file mode 100644 index e24b093de..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/AllHSLFTests.java +++ /dev/null @@ -1,46 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf; - -import org.apache.poi.hslf.extractor.TestCruddyExtractor; -import org.apache.poi.hslf.extractor.TestExtractor; -import org.apache.poi.hslf.model.AllHSLFModelTests; -import org.apache.poi.hslf.record.AllHSLFRecordTests; -import org.apache.poi.hslf.usermodel.AllHSLFUserModelTests; -import org.apache.poi.hslf.util.TestSystemTimeUtils; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -/** - * Collects all tests from the package org.apache.poi.hslf and all sub-packages. - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestEncryptedFile.class, - TestRecordCounts.class, - TestReWrite.class, - TestReWriteSanity.class, - TestCruddyExtractor.class, - TestExtractor.class, - AllHSLFModelTests.class, - AllHSLFRecordTests.class, - AllHSLFUserModelTests.class, - TestSystemTimeUtils.class -}) -public class AllHSLFTests { -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/HSLFTestDataSamples.java b/src/scratchpad/testcases/org/apache/poi/hslf/HSLFTestDataSamples.java deleted file mode 100644 index b70f0d70d..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/HSLFTestDataSamples.java +++ /dev/null @@ -1,86 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hslf.usermodel.HSLFSlideShow; -import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl; - -public class HSLFTestDataSamples { - - private static final POIDataSamples _inst = POIDataSamples.getSlideShowInstance(); - - public static InputStream openSampleFileStream(String sampleFileName) { - return _inst.openResourceAsStream(sampleFileName); - } - - public static File getSampleFile(String sampleFileName) { - return _inst.getFile(sampleFileName); - } - - public static byte[] getTestDataFileContent(String fileName) { - return _inst.readFile(fileName); - } - - public static HSLFSlideShow getSlideShow(String fileName) throws IOException { - InputStream is = openSampleFileStream(fileName); - try { - return new HSLFSlideShow(is); - } finally { - is.close(); - } - } - - /** - * Writes a slideshow to a ByteArrayOutputStream and reads it back - * from a ByteArrayInputStream.

    - * Useful for verifying that the serialisation round trip - */ - public static HSLFSlideShowImpl writeOutAndReadBack(HSLFSlideShowImpl original) { - try { - ByteArrayOutputStream baos = new ByteArrayOutputStream(4096); - original.write(baos); - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - return new HSLFSlideShowImpl(bais); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - /** - * Writes a slideshow to a ByteArrayOutputStream and reads it back - * from a ByteArrayInputStream.

    - * Useful for verifying that the serialisation round trip - */ - public static HSLFSlideShow writeOutAndReadBack(HSLFSlideShow original) { - try { - ByteArrayOutputStream baos = new ByteArrayOutputStream(4096); - original.write(baos); - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - return new HSLFSlideShow(bais); - } catch (IOException e) { - throw new RuntimeException(e); - } - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/TestEncryptedFile.java b/src/scratchpad/testcases/org/apache/poi/hslf/TestEncryptedFile.java deleted file mode 100644 index a8060e7d3..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/TestEncryptedFile.java +++ /dev/null @@ -1,75 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf; - - -import static org.junit.Assert.assertNotNull; - -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hslf.exceptions.EncryptedPowerPointFileException; -import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl; -import org.junit.Test; - -/** - * Tests that HSLFSlideShow does the right thing with an encrypted file - */ -public final class TestEncryptedFile { - private static final POIDataSamples slTests = POIDataSamples.getSlideShowInstance(); - - @Test - public void testLoadNonEncrypted() throws IOException { - InputStream is = slTests.openResourceAsStream("basic_test_ppt_file.ppt"); - HSLFSlideShowImpl hss = new HSLFSlideShowImpl(is); - assertNotNull(hss); - hss.close(); - is.close(); - } - - @Test(expected=EncryptedPowerPointFileException.class) - public void testLoadEncrypted1() throws IOException { - InputStream is = slTests.openResourceAsStream("Password_Protected-hello.ppt"); - try { - new HSLFSlideShowImpl(is).close(); - } finally { - is.close(); - } - } - - @Test(expected=EncryptedPowerPointFileException.class) - public void testLoadEncrypted2() throws IOException { - InputStream is = slTests.openResourceAsStream("Password_Protected-np-hello.ppt"); - try { - new HSLFSlideShowImpl(is).close(); - } finally { - is.close(); - } - } - - @Test(expected=EncryptedPowerPointFileException.class) - public void testLoadEncrypted3() throws IOException { - InputStream is = slTests.openResourceAsStream("Password_Protected-56-hello.ppt"); - try { - new HSLFSlideShowImpl(is).close(); - } finally { - is.close(); - } - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/TestReWrite.java b/src/scratchpad/testcases/org/apache/poi/hslf/TestReWrite.java deleted file mode 100644 index e54cc0cac..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/TestReWrite.java +++ /dev/null @@ -1,210 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hslf.usermodel.HSLFSlideShow; -import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl; -import org.apache.poi.poifs.filesystem.DocumentEntry; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.util.TempFile; -import org.junit.Before; -import org.junit.Test; - -/** - * Tests that HSLFSlideShow writes the powerpoint bit of data back out - * correctly. Currently, that means being the same as what it read in - * - * @author Nick Burch (nick at torchbox dot com) - */ -public final class TestReWrite { - // HSLFSlideShow primed on the test data - private HSLFSlideShowImpl hssA; - private HSLFSlideShowImpl hssB; - private HSLFSlideShowImpl hssC; - // POIFS primed on the test data - private POIFSFileSystem pfsA; - private POIFSFileSystem pfsB; - private POIFSFileSystem pfsC; - - @Before - public void setUp() throws Exception { - - POIDataSamples slTests = POIDataSamples.getSlideShowInstance(); - - pfsA = new POIFSFileSystem(slTests.openResourceAsStream("basic_test_ppt_file.ppt")); - hssA = new HSLFSlideShowImpl(pfsA); - - pfsB = new POIFSFileSystem(slTests.openResourceAsStream("ParagraphStylesShorterThanCharStyles.ppt")); - hssB = new HSLFSlideShowImpl(pfsB); - - pfsC = new POIFSFileSystem(slTests.openResourceAsStream("WithMacros.ppt")); - hssC = new HSLFSlideShowImpl(pfsC); - } - - @Test - public void testWritesOutTheSame() throws Exception { - assertWritesOutTheSame(hssA, pfsA); - assertWritesOutTheSame(hssB, pfsB); - } - - public void assertWritesOutTheSame(HSLFSlideShowImpl hss, POIFSFileSystem pfs) throws Exception { - // Write out to a byte array, and to a temp file - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - hss.write(baos); - - final File file = TempFile.createTempFile("TestHSLF", ".ppt"); - final File file2 = TempFile.createTempFile("TestHSLF", ".ppt"); - hss.write(file); - hss.write(file2); - - - // Build an input stream of it, and read back as a POIFS from the stream - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - POIFSFileSystem npfS = new POIFSFileSystem(bais); - - // And the same on the temp file - POIFSFileSystem npfF = new POIFSFileSystem(file); - - // And another where we do an in-place write - POIFSFileSystem npfRF = new POIFSFileSystem(file2, false); - HSLFSlideShowImpl hssRF = new HSLFSlideShowImpl(npfRF); - hssRF.write(); - hssRF.close(); - npfRF = new POIFSFileSystem(file2); - - // Check all of them in turn - for (POIFSFileSystem npf : new POIFSFileSystem[] { npfS, npfF, npfRF }) { - // Check that the "PowerPoint Document" sections have the same size - DocumentEntry oProps = (DocumentEntry)pfs.getRoot().getEntry("PowerPoint Document"); - DocumentEntry nProps = (DocumentEntry)npf.getRoot().getEntry("PowerPoint Document"); - assertEquals(oProps.getSize(),nProps.getSize()); - - // Check that they contain the same data - byte[] _oData = new byte[oProps.getSize()]; - byte[] _nData = new byte[nProps.getSize()]; - pfs.createDocumentInputStream("PowerPoint Document").read(_oData); - npf.createDocumentInputStream("PowerPoint Document").read(_nData); - for(int i=0; i<_oData.length; i++) { - //System.out.println(i + "\t" + Integer.toHexString(i)); - assertEquals(_oData[i], _nData[i]); - } - npf.close(); - } - } - - @Test - public void testWithMacroStreams() throws IOException { - // Check that they're apparently the same - assertSlideShowWritesOutTheSame(hssC, pfsC); - - // Currently has a Macros stream - assertNotNull( pfsC.getRoot().getEntry("Macros") ); - - // Write out normally, will loose the macro stream - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - hssC.write(baos); - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - POIFSFileSystem pfsNew = new POIFSFileSystem(bais); - assertFalse(pfsNew.getRoot().hasEntry("Macros")); - pfsNew.close(); - - // But if we write out with nodes preserved, will be there - baos.reset(); - hssC.write(baos, true); - bais = new ByteArrayInputStream(baos.toByteArray()); - pfsNew = new POIFSFileSystem(bais); - assertTrue( pfsNew.getRoot().hasEntry("Macros") ); - pfsNew.close(); - } - - /** - * Ensure that simply opening a slideshow (usermodel) view of it - * doesn't change things - */ - @Test - public void testSlideShowWritesOutTheSame() throws Exception { - assertSlideShowWritesOutTheSame(hssA, pfsA); - - // Some bug in StyleTextPropAtom rewriting means this will fail - // We need to identify and fix that first - //assertSlideShowWritesOutTheSame(hssB, pfsB); - } - - public void assertSlideShowWritesOutTheSame(HSLFSlideShowImpl hss, POIFSFileSystem pfs) throws IOException { - // Create a slideshow covering it - @SuppressWarnings("resource") - HSLFSlideShow ss = new HSLFSlideShow(hss); - ss.getSlides(); - ss.getNotes(); - - // Now write out to a byte array - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - hss.write(baos); - - // Build an input stream of it - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - - // Use POIFS to query that lot - POIFSFileSystem npfs = new POIFSFileSystem(bais); - - // Check that the "PowerPoint Document" sections have the same size - DocumentEntry oProps = (DocumentEntry)pfs.getRoot().getEntry("PowerPoint Document"); - DocumentEntry nProps = (DocumentEntry)npfs.getRoot().getEntry("PowerPoint Document"); - assertEquals(oProps.getSize(),nProps.getSize()); - - // Check that they contain the same data - byte[] _oData = new byte[oProps.getSize()]; - byte[] _nData = new byte[nProps.getSize()]; - pfs.createDocumentInputStream("PowerPoint Document").read(_oData); - npfs.createDocumentInputStream("PowerPoint Document").read(_nData); - for(int i=0; i<_oData.length; i++) { - if(_oData[i] != _nData[i]) - System.out.println(i + "\t" + Integer.toHexString(i)); - assertEquals(_oData[i], _nData[i]); - } - npfs.close(); - } - - @Test - public void test48593() throws IOException { - HSLFSlideShow ppt1 = new HSLFSlideShow(); - ppt1.createSlide(); - HSLFSlideShow ppt2 = HSLFTestDataSamples.writeOutAndReadBack(ppt1); - ppt2.createSlide(); - HSLFSlideShow ppt3 = HSLFTestDataSamples.writeOutAndReadBack(ppt2); - ppt3.createSlide(); - HSLFSlideShow ppt4 = HSLFTestDataSamples.writeOutAndReadBack(ppt3); - ppt4.createSlide(); - HSLFTestDataSamples.writeOutAndReadBack(ppt4).close(); - ppt4.close(); - ppt3.close(); - ppt2.close(); - ppt1.close(); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/TestReWriteSanity.java b/src/scratchpad/testcases/org/apache/poi/hslf/TestReWriteSanity.java deleted file mode 100644 index f6d18a981..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/TestReWriteSanity.java +++ /dev/null @@ -1,119 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf; - - -import static org.apache.poi.POITestCase.assertContains; -import static org.junit.Assert.assertEquals; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.util.HashMap; -import java.util.Map; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hslf.record.CurrentUserAtom; -import org.apache.poi.hslf.record.PersistPtrHolder; -import org.apache.poi.hslf.record.Record; -import org.apache.poi.hslf.record.UserEditAtom; -import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -/** - * Tests that HSLFSlideShow writes the powerpoint bit of data back out - * in a sane manner - i.e. records end up in the right place - * - * @author Nick Burch (nick at torchbox dot com) - */ -public final class TestReWriteSanity { - // HSLFSlideShow primed on the test data - private HSLFSlideShowImpl ss; - // POIFS primed on the test data - private POIFSFileSystem pfs; - - @Before - public void setUp() throws Exception { - POIDataSamples slTests = POIDataSamples.getSlideShowInstance(); - pfs = new POIFSFileSystem(slTests.openResourceAsStream("basic_test_ppt_file.ppt")); - ss = new HSLFSlideShowImpl(pfs); - } - - @After - public void tearDown() throws Exception { - pfs.close(); - ss.close(); - } - - @Test - public void testUserEditAtomsRight() throws Exception { - // Write out to a byte array - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ss.write(baos); - - // Build an input stream of it - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - - // Create a new one from that - HSLFSlideShowImpl wss = new HSLFSlideShowImpl(bais); - - // Find the location of the PersistPtrIncrementalBlocks and - // UserEditAtoms - Record[] r = wss.getRecords(); - Map pp = new HashMap(); - Map ue = new HashMap(); - ue.put(Integer.valueOf(0),Integer.valueOf(0)); // Will show 0 if first - int pos = 0; - int lastUEPos = -1; - - for (final Record rec : r) { - if(rec instanceof PersistPtrHolder) { - pp.put(Integer.valueOf(pos), rec); - } - if(rec instanceof UserEditAtom) { - ue.put(Integer.valueOf(pos), rec); - lastUEPos = pos; - } - - ByteArrayOutputStream bc = new ByteArrayOutputStream(); - rec.writeOut(bc); - pos += bc.size(); - } - - // Check that the UserEditAtom's point to right stuff - for (final Record rec : r) { - if(rec instanceof UserEditAtom) { - UserEditAtom uea = (UserEditAtom)rec; - int luPos = uea.getLastUserEditAtomOffset(); - int ppPos = uea.getPersistPointersOffset(); - - assertContains(ue, Integer.valueOf(luPos)); - assertContains(pp, Integer.valueOf(ppPos)); - } - } - - // Check that the CurrentUserAtom points to the right UserEditAtom - CurrentUserAtom cua = wss.getCurrentUserAtom(); - int listedUEPos = (int)cua.getCurrentEditOffset(); - assertEquals(lastUEPos,listedUEPos); - - wss.close(); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/TestRecordCounts.java b/src/scratchpad/testcases/org/apache/poi/hslf/TestRecordCounts.java deleted file mode 100644 index 473c9d330..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/TestRecordCounts.java +++ /dev/null @@ -1,84 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf; - - -import junit.framework.TestCase; - -import org.apache.poi.hslf.record.*; -import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl; -import org.apache.poi.POIDataSamples; - -/** - * Tests that HSLFSlideShow returns the right numbers of key records when - * it parses the test file - * - * @author Nick Burch (nick at torchbox dot com) - */ -public final class TestRecordCounts extends TestCase { - // HSLFSlideShow primed on the test data - private final HSLFSlideShowImpl ss; - - public TestRecordCounts() throws Exception { - POIDataSamples slTests = POIDataSamples.getSlideShowInstance(); - ss = new HSLFSlideShowImpl(slTests.openResourceAsStream("basic_test_ppt_file.ppt")); - } - - public void testSheetsCount() { - // Top level - Record[] r = ss.getRecords(); - - int count = 0; - for (final Record rec : r) { - if(rec instanceof Slide) { - count++; - } - } - // Currently still sees the Master Sheet, but might not in the future - assertEquals(3,count); - } - - public void testNotesCount() { - // Top level - Record[] r = ss.getRecords(); - - int count = 0; - for (final Record rec : r) { - if (rec instanceof Notes && rec.getRecordType() == 1008l) { - count++; - } - } - // Two real sheets, plus the master sheet - assertEquals(3,count); - } - - public void testSlideListWithTextCount() { - // Second level - Record[] rt = ss.getRecords(); - Record[] r = rt[0].getChildRecords(); - - int count = 0; - for (final Record rec : r) { - if (rec instanceof SlideListWithText && rec.getRecordType() == 4080l) { - count++; - } - } - // Two real sheets, plus the master sheet - assertEquals(3,count); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/extractor/TestCruddyExtractor.java b/src/scratchpad/testcases/org/apache/poi/hslf/extractor/TestCruddyExtractor.java deleted file mode 100644 index 33807ac57..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/extractor/TestCruddyExtractor.java +++ /dev/null @@ -1,89 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.extractor; - - -import java.util.List; - -import junit.framework.TestCase; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.util.StringUtil; - -/** - * Tests that the QuickButCruddyTextExtractor works correctly - * - * @author Nick Burch (nick at torchbox dot com) - */ -public final class TestCruddyExtractor extends TestCase { - // Extractor primed on the test data - private final QuickButCruddyTextExtractor te; - // All the text to be found in the file - String[] allTheText = new String[] { - "This is a test title", - "This is a test subtitle\nThis is on page 1", - "Click to edit Master title style", - "Click to edit Master text styles\nSecond level\nThird level\nFourth level\nFifth level", - "*", - "*", - "*", - "*", - "*", - "Click to edit Master text styles\nSecond level\nThird level\nFourth level\nFifth level", - "*", - "*", - "These are the notes for page 1", - "This is a test title", - "This is a test subtitle\nThis is on page 1", - "This is the title on page 2", - "This is page two\nIt has several blocks of text\nNone of them have formattingT", - "These are the notes on page two, again lacking formatting", - "This is a test title", - "This is a test subtitle\nThis is on page 1", - "This is the title on page 2", - "This is page two\nIt has several blocks of text\nNone of them have formatting", - }; - - public TestCruddyExtractor() throws Exception { - POIDataSamples slTests = POIDataSamples.getSlideShowInstance(); - te = new QuickButCruddyTextExtractor(slTests.openResourceAsStream("basic_test_ppt_file.ppt")); - } - - public void testReadAsVector() { - // Extract the text from the file as a vector - List foundTextV = te.getTextAsVector(); - - // Ensure they match - assertEquals(allTheText.length,foundTextV.size()); - for(int i=0; i shapes = ppe.getOLEShapes(); - assertEquals("Expected 6 ole shapes", 6, shapes.size()); - int num_ppt = 0, num_doc = 0, num_xls = 0; - for (OLEShape ole : shapes) { - String name = ole.getInstanceName(); - InputStream data = ole.getObjectData().getData(); - if ("Worksheet".equals(name)) { - HSSFWorkbook wb = new HSSFWorkbook(data); - num_xls++; - wb.close(); - } else if ("Document".equals(name)) { - HWPFDocument doc = new HWPFDocument(data); - num_doc++; - doc.close(); - } else if ("Presentation".equals(name)) { - num_ppt++; - HSLFSlideShow ppt = new HSLFSlideShow(data); - ppt.close(); - } - data.close(); - } - assertEquals("Expected 2 embedded Word Documents", 2, num_doc); - assertEquals("Expected 2 embedded Excel Spreadsheets", 2, num_xls); - assertEquals("Expected 2 embedded PowerPoint Presentations", 2, num_ppt); - ppe.close(); - } - - /** - * A powerpoint file with embeded powerpoint files - */ - @Test - public void test52991() throws IOException { - PowerPointExtractor ppe = openExtractor("badzip.ppt"); - for (OLEShape shape : ppe.getOLEShapes()) { - IOUtils.copy(shape.getObjectData().getData(), new ByteArrayOutputStream()); - } - ppe.close(); - } - - /** - * From bug #45543 - */ - @Test - public void testWithComments() throws IOException { - PowerPointExtractor ppe1 = openExtractor("WithComments.ppt"); - String text = ppe1.getText(); - assertFalse("Comments not in by default", text.contains("This is a test comment")); - - ppe1.setCommentsByDefault(true); - - text = ppe1.getText(); - assertContains(text, "This is a test comment"); - ppe1.close(); - - - // And another file - PowerPointExtractor ppe2 = openExtractor("45543.ppt"); - text = ppe2.getText(); - assertFalse("Comments not in by default", text.contains("testdoc")); - - ppe2.setCommentsByDefault(true); - - text = ppe2.getText(); - assertContains(text, "testdoc"); - ppe2.close(); - } - - /** - * From bug #45537 - */ - @Test - public void testHeaderFooter() throws IOException { - String text; - - // With a header on the notes - InputStream is1 = slTests.openResourceAsStream("45537_Header.ppt"); - HSLFSlideShow ppt1 = new HSLFSlideShow(is1); - is1.close(); - assertNotNull(ppt1.getNotesHeadersFooters()); - assertEquals("testdoc test phrase", ppt1.getNotesHeadersFooters().getHeaderText()); - - PowerPointExtractor ppe1 = new PowerPointExtractor(ppt1.getSlideShowImpl()); - - text = ppe1.getText(); - assertFalse("Header shouldn't be there by default\n" + text, text.contains("testdoc")); - assertFalse("Header shouldn't be there by default\n" + text, text.contains("test phrase")); - - ppe1.setNotesByDefault(true); - text = ppe1.getText(); - assertContains(text, "testdoc"); - assertContains(text, "test phrase"); - ppe1.close(); - ppt1.close(); - - // And with a footer, also on notes - InputStream is2 = slTests.openResourceAsStream("45537_Footer.ppt"); - HSLFSlideShow ppt2 = new HSLFSlideShow(is2); - is2.close(); - - assertNotNull(ppt2.getNotesHeadersFooters()); - assertEquals("testdoc test phrase", ppt2.getNotesHeadersFooters().getFooterText()); - ppt2.close(); - - PowerPointExtractor ppe2 = openExtractor("45537_Footer.ppt"); - - text = ppe2.getText(); - assertFalse("Header shouldn't be there by default\n" + text, text.contains("testdoc")); - assertFalse("Header shouldn't be there by default\n" + text, text.contains("test phrase")); - - ppe2.setNotesByDefault(true); - text = ppe2.getText(); - assertContains(text, "testdoc"); - assertContains(text, "test phrase"); - ppe2.close(); - } - - @SuppressWarnings("unused") - @Test - public void testSlideMasterText() throws IOException { - String masterTitleText = "This is the Master Title"; - String masterRandomText = "This text comes from the Master Slide"; - String masterFooterText = "Footer from the master slide"; - PowerPointExtractor ppe = openExtractor("WithMaster.ppt"); - ppe.setMasterByDefault(true); - - String text = ppe.getText(); - assertContains(text, masterRandomText); - assertContains(text, masterFooterText); - ppe.close(); - } - - @Test - public void testMasterText() throws IOException { - PowerPointExtractor ppe1 = openExtractor("master_text.ppt"); - - // Initially not there - String text = ppe1.getText(); - assertFalse(text.contains("Text that I added to the master slide")); - - // Enable, shows up - ppe1.setMasterByDefault(true); - text = ppe1.getText(); - assertTrue(text.contains("Text that I added to the master slide")); - - // Make sure placeholder text does not come out - assertFalse(text.contains("Click to edit Master")); - ppe1.close(); - - // Now with another file only containing master text - // Will always show up - PowerPointExtractor ppe2 = openExtractor("WithMaster.ppt"); - String masterText = "Footer from the master slide"; - - text = ppe2.getText(); - assertContainsIgnoreCase(text, "master"); - assertContains(text, masterText); - ppe2.close(); - } - - /** - * Bug #54880 Chinese text not extracted properly - */ - @Test - public void testChineseText() throws IOException { - PowerPointExtractor ppe = openExtractor("54880_chinese.ppt"); - - String text = ppe.getText(); - - // Check for the english text line - assertContains(text, "Single byte"); - - // Check for the english text in the mixed line - assertContains(text, "Mix"); - - // Check for the chinese text in the mixed line - assertContains(text, "\u8868"); - - // Check for the chinese only text line - assertContains(text, "\uff8a\uff9d\uff76\uff78"); - ppe.close(); - } - - /** - * Tests that we can work with both {@link POIFSFileSystem} - * and {@link NPOIFSFileSystem} - */ - @SuppressWarnings("resource") - @Test - public void testDifferentPOIFS() throws IOException { - // Open the two filesystems - File pptFile = slTests.getFile("basic_test_ppt_file.ppt"); - InputStream is1 = new FileInputStream(pptFile); - OPOIFSFileSystem opoifs = new OPOIFSFileSystem(is1); - is1.close(); - NPOIFSFileSystem npoifs = new NPOIFSFileSystem(pptFile); - - DirectoryNode[] files = { opoifs.getRoot(), npoifs.getRoot() }; - - // Open directly - for (DirectoryNode dir : files) { - PowerPointExtractor extractor = new PowerPointExtractor(dir); - assertEquals(expectText, extractor.getText()); - } - - // Open via a HSLFSlideShow - for (DirectoryNode dir : files) { - HSLFSlideShowImpl slideshow = new HSLFSlideShowImpl(dir); - PowerPointExtractor extractor = new PowerPointExtractor(slideshow); - assertEquals(expectText, extractor.getText()); - extractor.close(); - slideshow.close(); - } - - npoifs.close(); - } - - @Test - public void testTable() throws Exception { - PowerPointExtractor ppe1 = openExtractor("54111.ppt"); - String text1 = ppe1.getText(); - String target1 = "TH Cell 1\tTH Cell 2\tTH Cell 3\tTH Cell 4\n"+ - "Row 1, Cell 1\tRow 1, Cell 2\tRow 1, Cell 3\tRow 1, Cell 4\n"+ - "Row 2, Cell 1\tRow 2, Cell 2\tRow 2, Cell 3\tRow 2, Cell 4\n"+ - "Row 3, Cell 1\tRow 3, Cell 2\tRow 3, Cell 3\tRow 3, Cell 4\n"+ - "Row 4, Cell 1\tRow 4, Cell 2\tRow 4, Cell 3\tRow 4, Cell 4\n"+ - "Row 5, Cell 1\tRow 5, Cell 2\tRow 5, Cell 3\tRow 5, Cell 4\n"; - assertTrue(text1.contains(target1)); - ppe1.close(); - - PowerPointExtractor ppe2 = openExtractor("54722.ppt"); - String text2 = ppe2.getText(); - - String target2 = "this\tText\tis\twithin\ta\n" + - "table\t1\t2\t3\t4"; - assertTrue(text2.contains(target2)); - ppe2.close(); - } - - // bug 60003 - @Test - public void testExtractMasterSlideFooterText() throws Exception { - PowerPointExtractor ppe = openExtractor("60003.ppt"); - ppe.setMasterByDefault(true); - - String text = ppe.getText(); - assertContains(text, "Prague"); - ppe.close(); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/model/AllHSLFModelTests.java b/src/scratchpad/testcases/org/apache/poi/hslf/model/AllHSLFModelTests.java deleted file mode 100644 index 14301af2b..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/model/AllHSLFModelTests.java +++ /dev/null @@ -1,47 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.model; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -/** - * Collects all tests from the package org.apache.poi.hslf.model. - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestBackground.class, - TestFreeform.class, - TestHeadersFooters.class, - TestHyperlink.class, - TestLine.class, - TestMovieShape.class, - TestOleEmbedding.class, - TestPPFont.class, - TestPPGraphics2D.class, - TestSetBoldItalic.class, - TestShapes.class, - TestSheet.class, - TestSlideChangeNotes.class, - TestSlideMaster.class, - TestSlides.class, - TestTable.class, - TestTextRunReWrite.class -}) -public class AllHSLFModelTests { -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestBackground.java b/src/scratchpad/testcases/org/apache/poi/hslf/model/TestBackground.java deleted file mode 100644 index faf61fbc5..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestBackground.java +++ /dev/null @@ -1,227 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.model; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.awt.Color; -import java.io.IOException; -import java.util.List; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.ddf.AbstractEscherOptRecord; -import org.apache.poi.ddf.EscherBSERecord; -import org.apache.poi.ddf.EscherContainerRecord; -import org.apache.poi.ddf.EscherProperties; -import org.apache.poi.ddf.EscherRecord; -import org.apache.poi.ddf.EscherSimpleProperty; -import org.apache.poi.hslf.HSLFTestDataSamples; -import org.apache.poi.hslf.record.Document; -import org.apache.poi.hslf.usermodel.HSLFAutoShape; -import org.apache.poi.hslf.usermodel.HSLFFill; -import org.apache.poi.hslf.usermodel.HSLFPictureData; -import org.apache.poi.hslf.usermodel.HSLFShape; -import org.apache.poi.hslf.usermodel.HSLFSheet; -import org.apache.poi.hslf.usermodel.HSLFSlide; -import org.apache.poi.hslf.usermodel.HSLFSlideShow; -import org.apache.poi.sl.usermodel.PictureData.PictureType; -import org.apache.poi.sl.usermodel.ShapeType; -import org.junit.Test; - - -/** - * Test Fill object. - * - * @author Yegor Kozlov - */ -public final class TestBackground { - private static POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); - - /** - * Default background for slide, shape and slide master. - */ - @Test - public void defaults() throws IOException { - HSLFSlideShow ppt = new HSLFSlideShow(); - - assertEquals(HSLFFill.FILL_SOLID, ppt.getSlideMasters().get(0).getBackground().getFill().getFillType()); - - HSLFSlide slide = ppt.createSlide(); - assertTrue(slide.getFollowMasterBackground()); - assertEquals(HSLFFill.FILL_SOLID, slide.getBackground().getFill().getFillType()); - - HSLFShape shape = new HSLFAutoShape(ShapeType.RECT); - assertEquals(HSLFFill.FILL_SOLID, shape.getFill().getFillType()); - ppt.close(); - } - - /** - * Read fill information from an reference ppt file - */ - @Test - public void readBackground() throws IOException { - HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow("backgrounds.ppt"); - HSLFFill fill; - HSLFShape shape; - - List slide = ppt.getSlides(); - - fill = slide.get(0).getBackground().getFill(); - assertEquals(HSLFFill.FILL_PICTURE, fill.getFillType()); - shape = slide.get(0).getShapes().get(0); - assertEquals(HSLFFill.FILL_SOLID, shape.getFill().getFillType()); - - fill = slide.get(1).getBackground().getFill(); - assertEquals(HSLFFill.FILL_PATTERN, fill.getFillType()); - shape = slide.get(1).getShapes().get(0); - assertEquals(HSLFFill.FILL_BACKGROUND, shape.getFill().getFillType()); - - fill = slide.get(2).getBackground().getFill(); - assertEquals(HSLFFill.FILL_TEXTURE, fill.getFillType()); - shape = slide.get(2).getShapes().get(0); - assertEquals(HSLFFill.FILL_PICTURE, shape.getFill().getFillType()); - - fill = slide.get(3).getBackground().getFill(); - assertEquals(HSLFFill.FILL_SHADE_CENTER, fill.getFillType()); - shape = slide.get(3).getShapes().get(0); - assertEquals(HSLFFill.FILL_SHADE, shape.getFill().getFillType()); - ppt.close(); - } - - /** - * Create a ppt with various fill effects - */ - @Test - public void backgroundPicture() throws IOException { - HSLFSlideShow ppt1 = new HSLFSlideShow(); - HSLFSlide slide; - HSLFFill fill; - HSLFShape shape; - HSLFPictureData data; - - //slide 1 - slide = ppt1.createSlide(); - slide.setFollowMasterBackground(false); - fill = slide.getBackground().getFill(); - data = ppt1.addPicture(_slTests.readFile("tomcat.png"), PictureType.PNG); - fill.setFillType(HSLFFill.FILL_PICTURE); - fill.setPictureData(data); - - shape = new HSLFAutoShape(ShapeType.RECT); - shape.setAnchor(new java.awt.Rectangle(100, 100, 200, 200)); - fill = shape.getFill(); - fill.setFillType(HSLFFill.FILL_SOLID); - slide.addShape(shape); - - //slide 2 - slide = ppt1.createSlide(); - slide.setFollowMasterBackground(false); - fill = slide.getBackground().getFill(); - data = ppt1.addPicture(_slTests.readFile("tomcat.png"), PictureType.PNG); - fill.setFillType(HSLFFill.FILL_PATTERN); - fill.setPictureData(data); - fill.setBackgroundColor(Color.green); - fill.setForegroundColor(Color.red); - - shape = new HSLFAutoShape(ShapeType.RECT); - shape.setAnchor(new java.awt.Rectangle(100, 100, 200, 200)); - fill = shape.getFill(); - fill.setFillType(HSLFFill.FILL_BACKGROUND); - slide.addShape(shape); - - //slide 3 - slide = ppt1.createSlide(); - slide.setFollowMasterBackground(false); - fill = slide.getBackground().getFill(); - data = ppt1.addPicture(_slTests.readFile("tomcat.png"), PictureType.PNG); - fill.setFillType(HSLFFill.FILL_TEXTURE); - fill.setPictureData(data); - - shape = new HSLFAutoShape(ShapeType.RECT); - shape.setAnchor(new java.awt.Rectangle(100, 100, 200, 200)); - fill = shape.getFill(); - fill.setFillType(HSLFFill.FILL_PICTURE); - data = ppt1.addPicture(_slTests.readFile("clock.jpg"), PictureType.JPEG); - fill.setPictureData(data); - slide.addShape(shape); - - // slide 4 - slide = ppt1.createSlide(); - slide.setFollowMasterBackground(false); - fill = slide.getBackground().getFill(); - fill.setFillType(HSLFFill.FILL_SHADE_CENTER); - fill.setBackgroundColor(Color.white); - fill.setForegroundColor(Color.darkGray); - - shape = new HSLFAutoShape(ShapeType.RECT); - shape.setAnchor(new java.awt.Rectangle(100, 100, 200, 200)); - fill = shape.getFill(); - fill.setFillType(HSLFFill.FILL_SHADE); - fill.setBackgroundColor(Color.red); - fill.setForegroundColor(Color.green); - slide.addShape(shape); - - //serialize and read again - HSLFSlideShow ppt2 = HSLFTestDataSamples.writeOutAndReadBack(ppt1); - List slides = ppt2.getSlides(); - - fill = slides.get(0).getBackground().getFill(); - assertEquals(HSLFFill.FILL_PICTURE, fill.getFillType()); - assertEquals(3, getFillPictureRefCount(slides.get(0).getBackground(), fill)); - shape = slides.get(0).getShapes().get(0); - assertEquals(HSLFFill.FILL_SOLID, shape.getFill().getFillType()); - - fill = slides.get(1).getBackground().getFill(); - assertEquals(HSLFFill.FILL_PATTERN, fill.getFillType()); - shape = slides.get(1).getShapes().get(0); - assertEquals(HSLFFill.FILL_BACKGROUND, shape.getFill().getFillType()); - - fill = slides.get(2).getBackground().getFill(); - assertEquals(HSLFFill.FILL_TEXTURE, fill.getFillType()); - assertEquals(3, getFillPictureRefCount(slides.get(2).getBackground(), fill)); - shape = slides.get(2).getShapes().get(0); - assertEquals(HSLFFill.FILL_PICTURE, shape.getFill().getFillType()); - assertEquals(1, getFillPictureRefCount(shape, fill)); - - fill = slides.get(3).getBackground().getFill(); - assertEquals(HSLFFill.FILL_SHADE_CENTER, fill.getFillType()); - shape = slides.get(3).getShapes().get(0); - assertEquals(HSLFFill.FILL_SHADE, shape.getFill().getFillType()); - ppt2.close(); - ppt1.close(); - } - - private int getFillPictureRefCount(HSLFShape shape, HSLFFill fill) { - AbstractEscherOptRecord opt = shape.getEscherOptRecord(); - EscherSimpleProperty p = HSLFShape.getEscherProperty(opt, EscherProperties.FILL__PATTERNTEXTURE); - if(p != null) { - int idx = p.getPropertyValue(); - - HSLFSheet sheet = shape.getSheet(); - HSLFSlideShow ppt = sheet.getSlideShow(); - Document doc = ppt.getDocumentRecord(); - EscherContainerRecord dggContainer = doc.getPPDrawingGroup().getDggContainer(); - EscherContainerRecord bstore = HSLFShape.getEscherChild(dggContainer, EscherContainerRecord.BSTORE_CONTAINER); - List lst = bstore.getChildRecords(); - return ((EscherBSERecord)lst.get(idx-1)).getRef(); - } - return 0; - } - -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestFreeform.java b/src/scratchpad/testcases/org/apache/poi/hslf/model/TestFreeform.java deleted file mode 100644 index 91d23664d..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestFreeform.java +++ /dev/null @@ -1,94 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.model; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.awt.geom.Area; -import java.awt.geom.Line2D; -import java.awt.geom.Path2D; -import java.awt.geom.Rectangle2D; - -import org.apache.poi.hslf.usermodel.HSLFFreeformShape; -import org.junit.Test; - -/** - * Test Freeform object. - * The Freeform shape is constructed from java.awt.GeneralPath. - * Check that the get/set path accessors are consistent. - * (TODO: verification of Bezier curves is more difficult due to rounding error. Figure out a test approach for that) - * - * @author Yegor Kozlov - */ -public final class TestFreeform { - - @Test - public void testClosedPath() { - - Path2D.Double path1 = new Path2D.Double(); - path1.moveTo(100, 100); - path1.lineTo(200, 100); - path1.lineTo(200, 200); - path1.lineTo(100, 200); - path1.closePath(); - - HSLFFreeformShape p = new HSLFFreeformShape(); - p.setPath(path1); - - java.awt.Shape path2 = p.getPath(); - assertTrue(new Area(path1).equals(new Area(path2))); - } - - @Test - public void testLine() { - - Path2D.Double path1 = new Path2D.Double(new Line2D.Double(100, 100, 200, 100)); - - HSLFFreeformShape p = new HSLFFreeformShape(); - p.setPath(path1); - - java.awt.Shape path2 = p.getPath(); - assertTrue(new Area(path1).equals(new Area(path2))); - } - - @Test - public void testRectangle() { - - Path2D.Double path1 = new Path2D.Double(new Rectangle2D.Double(100, 100, 200, 50)); - - HSLFFreeformShape p = new HSLFFreeformShape(); - p.setPath(path1); - - java.awt.Shape path2 = p.getPath(); - assertTrue(new Area(path1).equals(new Area(path2))); - } - - /** - * Avoid NPE in Freeform.getOutline() if either GEOMETRY__VERTICES or - * GEOMETRY__SEGMENTINFO is missing, see Bugzilla 54188 - */ - @Test - public void test54188() { - - HSLFFreeformShape p = new HSLFFreeformShape(); - Path2D.Double path = p.getPath(); - Path2D.Double emptyPath = new Path2D.Double(); - assertEquals(emptyPath.getBounds2D(), path.getBounds2D()); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestHeadersFooters.java b/src/scratchpad/testcases/org/apache/poi/hslf/model/TestHeadersFooters.java deleted file mode 100644 index 333b7a829..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestHeadersFooters.java +++ /dev/null @@ -1,231 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.model; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.io.InputStream; -import java.util.List; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hslf.HSLFTestDataSamples; -import org.apache.poi.hslf.usermodel.HSLFSlide; -import org.apache.poi.hslf.usermodel.HSLFSlideShow; -import org.junit.Test; - -/** - * Test {@link org.apache.poi.hslf.model.HeadersFooters} object - */ -public final class TestHeadersFooters -{ - - private static POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); - - @Test - public void testRead() throws IOException { - InputStream is = _slTests.openResourceAsStream("headers_footers.ppt"); - HSLFSlideShow ppt = new HSLFSlideShow(is); - is.close(); - - HeadersFooters slideHdd = ppt.getSlideHeadersFooters(); - assertTrue(slideHdd.isFooterVisible()); - assertEquals("Global Slide Footer", slideHdd.getFooterText()); - assertTrue(slideHdd.isSlideNumberVisible()); - assertFalse(slideHdd.isHeaderVisible()); - assertNull(slideHdd.getHeaderText()); - assertFalse(slideHdd.isUserDateVisible()); - assertNull(slideHdd.getDateTimeText()); - - - HeadersFooters notesHdd = ppt.getNotesHeadersFooters(); - assertTrue(notesHdd.isFooterVisible()); - assertEquals("Notes Footer", notesHdd.getFooterText()); - assertTrue(notesHdd.isHeaderVisible()); - assertEquals("Notes Header", notesHdd.getHeaderText()); - assertTrue(notesHdd.isUserDateVisible()); - assertNull(notesHdd.getDateTimeText()); - - List slide = ppt.getSlides(); - //the first slide uses presentation-scope headers / footers - HeadersFooters hd1 = slide.get(0).getHeadersFooters(); - assertEquals(slideHdd.isFooterVisible(), hd1.isFooterVisible()); - assertEquals(slideHdd.getFooterText(), hd1.getFooterText()); - assertEquals(slideHdd.isSlideNumberVisible(), hd1.isSlideNumberVisible()); - assertEquals(slideHdd.isHeaderVisible(), hd1.isHeaderVisible()); - assertEquals(slideHdd.getHeaderText(), hd1.getHeaderText()); - assertEquals(slideHdd.isUserDateVisible(), hd1.isUserDateVisible()); - assertEquals(slideHdd.getDateTimeText(), hd1.getDateTimeText()); - - //the first slide uses per-slide headers / footers - HeadersFooters hd2 = slide.get(1).getHeadersFooters(); - assertEquals(true, hd2.isFooterVisible()); - assertEquals("per-slide footer", hd2.getFooterText()); - assertEquals(true, hd2.isUserDateVisible()); - assertEquals("custom date format", hd2.getDateTimeText()); - - ppt.close(); - } - - /** - * If Headers / Footers are not set, all the getters should return false or null - */ - @Test - public void testReadNoHeadersFooters() throws Exception { - InputStream is = _slTests.openResourceAsStream("basic_test_ppt_file.ppt"); - HSLFSlideShow ppt = new HSLFSlideShow(is); - is.close(); - - HeadersFooters slideHdd = ppt.getSlideHeadersFooters(); - assertFalse(slideHdd.isFooterVisible()); - assertNull(slideHdd.getFooterText()); - assertFalse(slideHdd.isSlideNumberVisible()); - assertFalse(slideHdd.isHeaderVisible()); - assertNull(slideHdd.getHeaderText()); - assertFalse(slideHdd.isUserDateVisible()); - assertNull(slideHdd.getDateTimeText()); - - - HeadersFooters notesHdd = ppt.getNotesHeadersFooters(); - assertFalse(notesHdd.isFooterVisible()); - assertNull(notesHdd.getFooterText()); - assertFalse(notesHdd.isHeaderVisible()); - assertNull(notesHdd.getHeaderText()); - assertFalse(notesHdd.isUserDateVisible()); - assertNull(notesHdd.getDateTimeText()); - - for(HSLFSlide s : ppt.getSlides()) { - HeadersFooters hd1 = s.getHeadersFooters(); - assertFalse(hd1.isFooterVisible()); - assertNull(hd1.getFooterText()); - assertFalse(hd1.isHeaderVisible()); - assertNull(hd1.getHeaderText()); - assertFalse(hd1.isUserDateVisible()); - assertNull(hd1.getDateTimeText()); - } - - ppt.close(); - } - - /** - * Test extraction of headers / footers from PPTs saved in Office 2007 - */ - @Test - public void testRead2007() throws IOException { - InputStream is = _slTests.openResourceAsStream("headers_footers_2007.ppt"); - HSLFSlideShow ppt = new HSLFSlideShow(is); - is.close(); - - HeadersFooters slideHdd = ppt.getSlideHeadersFooters(); - assertTrue(slideHdd.isFooterVisible()); - assertEquals("THE FOOTER TEXT", slideHdd.getFooterText()); - assertTrue(slideHdd.isSlideNumberVisible()); - assertFalse(slideHdd.isHeaderVisible()); - assertNull(slideHdd.getHeaderText()); - assertTrue(slideHdd.isUserDateVisible()); - assertEquals("Wednesday, August 06, 2008", slideHdd.getDateTimeText()); - - - HeadersFooters notesHdd = ppt.getNotesHeadersFooters(); - assertTrue(notesHdd.isFooterVisible()); - assertEquals("THE NOTES FOOTER TEXT", notesHdd.getFooterText()); - assertTrue(notesHdd.isHeaderVisible()); - assertEquals("THE NOTES HEADER TEXT", notesHdd.getHeaderText()); - assertTrue(notesHdd.isUserDateVisible()); - assertTrue(notesHdd.isDateTimeVisible()); - //TODO: depending on the formatId getDateTimeText() should return formatted date - //assertEquals("08/12/08", notesHdd.getDateTimeText()); - - //per-slide headers / footers - List slide = ppt.getSlides(); - //the first slide uses presentation-scope headers / footers - HeadersFooters hd1 = slide.get(0).getHeadersFooters(); - assertTrue(hd1.isFooterVisible()); - assertEquals("THE FOOTER TEXT", hd1.getFooterText()); - assertTrue(hd1.isSlideNumberVisible()); - assertFalse(hd1.isHeaderVisible()); - assertNull(hd1.getHeaderText()); - assertTrue(hd1.isUserDateVisible()); - assertTrue(hd1.isDateTimeVisible()); - assertEquals("Wednesday, August 06, 2008", hd1.getDateTimeText()); - - //the second slide uses custom per-slide headers / footers - HeadersFooters hd2 = slide.get(1).getHeadersFooters(); - assertTrue(hd2.isFooterVisible()); - assertEquals("THE FOOTER TEXT FOR SLIDE 2", hd2.getFooterText()); - assertTrue(hd2.isSlideNumberVisible()); - assertFalse(hd2.isHeaderVisible()); - assertNull(hd2.getHeaderText()); - assertTrue(hd2.isUserDateVisible()); - assertTrue(hd2.isDateTimeVisible()); - assertEquals("August 06, 2008", hd2.getDateTimeText()); - - //the third slide uses per-slide headers / footers - HeadersFooters hd3 = slide.get(2).getHeadersFooters(); - assertTrue(hd3.isFooterVisible()); - assertEquals("THE FOOTER TEXT", hd3.getFooterText()); - assertTrue(hd3.isSlideNumberVisible()); - assertFalse(hd3.isHeaderVisible()); - assertNull(hd3.getHeaderText()); - assertTrue(hd3.isUserDateVisible()); - assertTrue(hd3.isDateTimeVisible()); - assertEquals("Wednesday, August 06, 2008", hd3.getDateTimeText()); - - ppt.close(); - } - - @Test - public void testCreateSlideFooters() throws IOException { - HSLFSlideShow ppt1 = new HSLFSlideShow(); - HeadersFooters hdd = ppt1.getSlideHeadersFooters(); - hdd.setFootersText("My slide footer"); - hdd.setSlideNumberVisible(true); - - HSLFSlideShow ppt2 = HSLFTestDataSamples.writeOutAndReadBack(ppt1); - HeadersFooters hdd2 = ppt2.getSlideHeadersFooters(); - assertTrue(hdd2.isSlideNumberVisible()); - assertTrue(hdd2.isFooterVisible()); - assertEquals("My slide footer", hdd2.getFooterText()); - - ppt2.close(); - ppt1.close(); - } - - @Test - public void testCreateNotesFooters() throws IOException { - HSLFSlideShow ppt1 = new HSLFSlideShow(); - HeadersFooters hdd = ppt1.getNotesHeadersFooters(); - hdd.setFootersText("My notes footer"); - hdd.setHeaderText("My notes header"); - hdd.setSlideNumberVisible(true); - - HSLFSlideShow ppt2 = HSLFTestDataSamples.writeOutAndReadBack(ppt1); - HeadersFooters hdd2 = ppt2.getNotesHeadersFooters(); - assertTrue(hdd2.isSlideNumberVisible()); - assertTrue(hdd2.isFooterVisible()); - assertEquals("My notes footer", hdd2.getFooterText()); - assertTrue(hdd2.isHeaderVisible()); - assertEquals("My notes header", hdd2.getHeaderText()); - - ppt2.close(); - ppt1.close(); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestHyperlink.java b/src/scratchpad/testcases/org/apache/poi/hslf/model/TestHyperlink.java deleted file mode 100644 index 7aeb42ccf..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestHyperlink.java +++ /dev/null @@ -1,173 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.model; - -import static org.apache.poi.hslf.usermodel.HSLFTextParagraph.getRawText; -import static org.apache.poi.hslf.usermodel.HSLFTextParagraph.toExternalString; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import java.awt.geom.Rectangle2D; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.common.usermodel.HyperlinkType; -import org.apache.poi.hslf.HSLFTestDataSamples; -import org.apache.poi.hslf.record.InteractiveInfoAtom; -import org.apache.poi.hslf.usermodel.HSLFHyperlink; -import org.apache.poi.hslf.usermodel.HSLFSlide; -import org.apache.poi.hslf.usermodel.HSLFSlideShow; -import org.apache.poi.hslf.usermodel.HSLFTextBox; -import org.apache.poi.hslf.usermodel.HSLFTextParagraph; -import org.apache.poi.hslf.usermodel.HSLFTextRun; -import org.apache.poi.sl.usermodel.Hyperlink; -import org.junit.Test; - -/** - * Test Hyperlink. - */ -public final class TestHyperlink { - private static POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); - - @Test - public void testTextRunHyperlinks() throws Exception { - HSLFSlideShow ppt = new HSLFSlideShow(_slTests.openResourceAsStream("WithLinks.ppt")); - - HSLFSlide slide = ppt.getSlides().get(0); - List para = slide.getTextParagraphs().get(1); - - String rawText = toExternalString(getRawText(para), para.get(0).getRunType()); - String expected = - "This page has two links:\n"+ - "http://jakarta.apache.org/poi/\n"+ - "\n"+ - "http://slashdot.org/\n"+ - "\n"+ - "In addition, its notes has one link"; - assertEquals(expected, rawText); - - List links = findHyperlinks(para); - assertEquals(2, links.size()); - - assertEquals("http://jakarta.apache.org/poi/", links.get(0).getLabel()); - assertEquals("http://jakarta.apache.org/poi/", links.get(0).getAddress()); - assertEquals("http://jakarta.apache.org/poi/", rawText.substring(links.get(0).getStartIndex(), links.get(0).getEndIndex()-1)); - - assertEquals("http://slashdot.org/", links.get(1).getLabel()); - assertEquals("http://slashdot.org/", links.get(1).getAddress()); - assertEquals("http://slashdot.org/", rawText.substring(links.get(1).getStartIndex(), links.get(1).getEndIndex()-1)); - - slide = ppt.getSlides().get(1); - para = slide.getTextParagraphs().get(1); - rawText = toExternalString(getRawText(para), para.get(0).getRunType()); - expected = - "I have the one link:\n" + - "Jakarta HSSF"; - assertEquals(expected, rawText); - - links.clear(); - - links = findHyperlinks(para); - assertNotNull(links); - assertEquals(1, links.size()); - - assertEquals("Open Jakarta POI HSSF module test ", links.get(0).getLabel()); - assertEquals("http://jakarta.apache.org/poi/hssf/", links.get(0).getAddress()); - assertEquals("Jakarta HSSF", rawText.substring(links.get(0).getStartIndex(), links.get(0).getEndIndex()-1)); - - ppt.close(); - } - - @Test - public void bug47291() throws IOException { - HSLFSlideShow ppt1 = new HSLFSlideShow(); - HSLFSlide slide1 = ppt1.createSlide(); - HSLFTextRun r1 = slide1.createTextBox().setText("page1"); - HSLFHyperlink hl1 = r1.createHyperlink(); - hl1.linkToEmail("dev@poi.apache.org"); - HSLFTextRun r2 = ppt1.createSlide().createTextBox().setText("page2"); - HSLFHyperlink hl2 = r2.createHyperlink(); - hl2.linkToLastSlide(); - HSLFSlide sl1 = ppt1.createSlide(); - HSLFTextBox tb1 = sl1.createTextBox(); - tb1.setAnchor(new Rectangle2D.Double(100,100,100,100)); - tb1.appendText("text1 ", false); - HSLFTextRun r3 = tb1.appendText("lin\u000bk", false); - tb1.appendText(" text2", false); - HSLFHyperlink hl3 = r3.createHyperlink(); - hl3.linkToSlide(slide1); - HSLFTextRun r4 = ppt1.createSlide().createTextBox().setText("page4"); - HSLFHyperlink hl4 = r4.createHyperlink(); - hl4.linkToUrl("http://poi.apache.org"); - HSLFTextBox tb5 = ppt1.createSlide().createTextBox(); - tb5.setText("page5"); - HSLFHyperlink hl5 = tb5.createHyperlink(); - hl5.linkToFirstSlide(); - - HSLFSlideShow ppt2 = HSLFTestDataSamples.writeOutAndReadBack(ppt1); - ppt1.close(); - - List slides = ppt2.getSlides(); - tb1 = (HSLFTextBox)slides.get(0).getShapes().get(0); - hl1 = tb1.getTextParagraphs().get(0).getTextRuns().get(0).getHyperlink(); - assertNotNull(hl1); - assertEquals("dev@poi.apache.org", hl1.getLabel()); - assertEquals(HyperlinkType.EMAIL, hl1.getTypeEnum()); - - HSLFTextBox tb2 = (HSLFTextBox)slides.get(1).getShapes().get(0); - hl2 = tb2.getTextParagraphs().get(0).getTextRuns().get(0).getHyperlink(); - assertNotNull(hl2); - assertEquals(InteractiveInfoAtom.LINK_LastSlide, hl2.getInfo().getInteractiveInfoAtom().getHyperlinkType()); - assertEquals(HyperlinkType.DOCUMENT, hl2.getTypeEnum()); - - HSLFTextBox tb3 = (HSLFTextBox)slides.get(2).getShapes().get(0); - hl3 = tb3.getTextParagraphs().get(0).getTextRuns().get(1).getHyperlink(); - assertNotNull(hl3); - assertEquals(ppt2.getSlides().get(0)._getSheetNumber(), Integer.parseInt(hl3.getAddress().split(",")[0])); - assertEquals(HyperlinkType.DOCUMENT, hl3.getTypeEnum()); - - HSLFTextBox tb4 = (HSLFTextBox)slides.get(3).getShapes().get(0); - hl4 = tb4.getTextParagraphs().get(0).getTextRuns().get(0).getHyperlink(); - assertNotNull(hl4); - assertEquals("http://poi.apache.org", hl4.getLabel()); - assertEquals(HyperlinkType.URL, hl4.getTypeEnum()); - - tb5 = (HSLFTextBox)slides.get(4).getShapes().get(0); - hl5 = tb5.getHyperlink(); - assertNotNull(hl5); - assertEquals(InteractiveInfoAtom.LINK_FirstSlide, hl5.getInfo().getInteractiveInfoAtom().getHyperlinkType()); - assertEquals(HyperlinkType.DOCUMENT, hl5.getTypeEnum()); - - ppt2.close(); - } - - private static List findHyperlinks(List paras) { - List links = new ArrayList(); - for (HSLFTextParagraph p : paras) { - for (HSLFTextRun r : p) { - HSLFHyperlink hl = r.getHyperlink(); - if (hl != null) { - links.add(hl); - } - } - } - return links; - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestLine.java b/src/scratchpad/testcases/org/apache/poi/hslf/model/TestLine.java deleted file mode 100644 index c601ca04b..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestLine.java +++ /dev/null @@ -1,131 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.model; - -import java.awt.Color; - -import org.apache.poi.hslf.usermodel.HSLFSlide; -import org.apache.poi.hslf.usermodel.HSLFSlideShow; -import org.apache.poi.hslf.usermodel.HSLFLine; -import org.apache.poi.sl.usermodel.StrokeStyle.LineCompound; -import org.apache.poi.sl.usermodel.StrokeStyle.LineDash; -import org.junit.Test; - -/** - * Test Line shape. - * - * @author Yegor Kozlov - */ -public final class TestLine { - - @Test - public void testCreateLines() { - HSLFSlideShow ppt = new HSLFSlideShow(); - - HSLFSlide slide = ppt.createSlide(); - - slide.addTitle().setText("Lines tester"); - - HSLFLine line; - - /** - * line styles - */ - line = new HSLFLine(); - line.setAnchor(new java.awt.Rectangle(75, 200, 300, 0)); - line.setLineCompound(LineCompound.SINGLE); - line.setLineColor(Color.blue); - slide.addShape(line); - - line = new HSLFLine(); - line.setAnchor(new java.awt.Rectangle(75, 230, 300, 0)); - line.setLineCompound(LineCompound.DOUBLE); - line.setLineWidth(3.5); - slide.addShape(line); - - line = new HSLFLine(); - line.setAnchor(new java.awt.Rectangle(75, 260, 300, 0)); - line.setLineCompound(LineCompound.TRIPLE); - line.setLineWidth(6); - slide.addShape(line); - - line = new HSLFLine(); - line.setAnchor(new java.awt.Rectangle(75, 290, 300, 0)); - line.setLineCompound(LineCompound.THICK_THIN); - line.setLineWidth(4.5); - slide.addShape(line); - - line = new HSLFLine(); - line.setAnchor(new java.awt.Rectangle(75, 320, 300, 0)); - line.setLineCompound(LineCompound.THIN_THICK); - line.setLineWidth(5.5); - slide.addShape(line); - - /** - * line dashing - */ - line = new HSLFLine(); - line.setAnchor(new java.awt.Rectangle(450, 200, 300, 0)); - line.setLineDash(LineDash.SOLID); - slide.addShape(line); - - line = new HSLFLine(); - line.setAnchor(new java.awt.Rectangle(450, 230, 300, 0)); - line.setLineDash(LineDash.DASH); - slide.addShape(line); - - line = new HSLFLine(); - line.setAnchor(new java.awt.Rectangle(450, 260, 300, 0)); - line.setLineDash(LineDash.DOT); - slide.addShape(line); - - line = new HSLFLine(); - line.setAnchor(new java.awt.Rectangle(450, 290, 300, 0)); - line.setLineDash(LineDash.DASH_DOT); - slide.addShape(line); - - line = new HSLFLine(); - line.setAnchor(new java.awt.Rectangle(450, 320, 300, 0)); - line.setLineDash(LineDash.LG_DASH_DOT_DOT); - slide.addShape(line); - - /** - * Combinations - */ - line = new HSLFLine(); - line.setAnchor(new java.awt.Rectangle(75, 400, 300, 0)); - line.setLineDash(LineDash.DASH_DOT); - line.setLineCompound(LineCompound.TRIPLE); - line.setLineWidth(5.0); - slide.addShape(line); - - line = new HSLFLine(); - line.setAnchor(new java.awt.Rectangle(75, 430, 300, 0)); - line.setLineDash(LineDash.DASH); - line.setLineCompound(LineCompound.THICK_THIN); - line.setLineWidth(4.0); - slide.addShape(line); - - line = new HSLFLine(); - line.setAnchor(new java.awt.Rectangle(75, 460, 300, 0)); - line.setLineDash(LineDash.DOT); - line.setLineCompound(LineCompound.DOUBLE); - line.setLineWidth(8.0); - slide.addShape(line); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestMovieShape.java b/src/scratchpad/testcases/org/apache/poi/hslf/model/TestMovieShape.java deleted file mode 100644 index 7e96707d1..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestMovieShape.java +++ /dev/null @@ -1,70 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.model; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.awt.geom.Rectangle2D; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hslf.usermodel.HSLFPictureData; -import org.apache.poi.hslf.usermodel.HSLFSlide; -import org.apache.poi.hslf.usermodel.HSLFSlideShow; -import org.apache.poi.sl.usermodel.PictureData.PictureType; -import org.junit.Test; - -/** - * Test MovieShape object. - */ -public final class TestMovieShape { - - private static POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); - - @Test - public void testCreate() throws Exception { - HSLFSlideShow ppt = new HSLFSlideShow(); - - HSLFSlide slide = ppt.createSlide(); - - String path = "/test-movie.mpg"; - int movieIdx = ppt.addMovie(path, MovieShape.MOVIE_MPEG); - HSLFPictureData thumbnailData = ppt.addPicture(_slTests.readFile("tomcat.png"), PictureType.PNG); - - MovieShape shape = new MovieShape(movieIdx, thumbnailData); - shape.setAnchor(new Rectangle2D.Double(300,225,120,90)); - slide.addShape(shape); - - assertEquals(path, shape.getPath()); - assertTrue(shape.isAutoPlay()); - shape.setAutoPlay(false); - assertFalse(shape.isAutoPlay()); - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ppt.write(out); - - ppt = new HSLFSlideShow(new ByteArrayInputStream(out.toByteArray())); - slide = ppt.getSlides().get(0); - shape = (MovieShape)slide.getShapes().get(0); - assertEquals(path, shape.getPath()); - assertFalse(shape.isAutoPlay()); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestOleEmbedding.java b/src/scratchpad/testcases/org/apache/poi/hslf/model/TestOleEmbedding.java deleted file mode 100644 index d8c331b7f..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestOleEmbedding.java +++ /dev/null @@ -1,170 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.model; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; - -import java.awt.geom.Rectangle2D; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.util.List; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hslf.usermodel.HSLFObjectData; -import org.apache.poi.hslf.usermodel.HSLFPictureData; -import org.apache.poi.hslf.usermodel.HSLFShape; -import org.apache.poi.hslf.usermodel.HSLFSlide; -import org.apache.poi.hslf.usermodel.HSLFSlideShow; -import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.hwpf.HWPFDocument; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.sl.usermodel.PictureData.PictureType; -import org.apache.poi.util.IOUtils; -import org.junit.Test; - -public final class TestOleEmbedding { - private static POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); - /** - * Tests support for OLE objects. - * - * @throws Exception if an error occurs. - */ - @Test - public void testOleEmbedding2003() throws IOException { - HSLFSlideShowImpl slideShow = new HSLFSlideShowImpl(_slTests.openResourceAsStream("ole2-embedding-2003.ppt")); - // Placeholder EMFs for clients that don't support the OLE components. - List pictures = slideShow.getPictureData(); - assertEquals("Should be two pictures", 2, pictures.size()); - - long checkSums[] = { 0xD37A4204l, 0x26A62F68l, 0x82853169l, 0xE0E45D2Bl }; - int checkId = 0; - - // check for checksum to be uptodate - for (HSLFPictureData pd : pictures) { - long checkEMF = IOUtils.calculateChecksum(pd.getData()); - assertEquals(checkSums[checkId++], checkEMF); - } - - // Actual embedded objects. - HSLFObjectData[] objects = slideShow.getEmbeddedObjects(); - assertEquals("Should be two objects", 2, objects.length); - for (HSLFObjectData od : objects) { - long checkEMF = IOUtils.calculateChecksum(od.getData()); - assertEquals(checkSums[checkId++], checkEMF); - } - - slideShow.close(); - } - - - - @Test - public void testOLEShape() throws IOException { - HSLFSlideShow ppt = new HSLFSlideShow(_slTests.openResourceAsStream("ole2-embedding-2003.ppt")); - - HSLFSlide slide = ppt.getSlides().get(0); - int cnt = 0; - for (HSLFShape sh : slide.getShapes()) { - if(sh instanceof OLEShape){ - cnt++; - OLEShape ole = (OLEShape)sh; - HSLFObjectData data = ole.getObjectData(); - if("Worksheet".equals(ole.getInstanceName())){ - //Voila! we created a workbook from the embedded OLE data - HSSFWorkbook wb = new HSSFWorkbook(data.getData()); - HSSFSheet sheet = wb.getSheetAt(0); - //verify we can access the xls data - assertEquals(1, sheet.getRow(0).getCell(0).getNumericCellValue(), 0); - assertEquals(1, sheet.getRow(1).getCell(0).getNumericCellValue(), 0); - assertEquals(2, sheet.getRow(2).getCell(0).getNumericCellValue(), 0); - assertEquals(3, sheet.getRow(3).getCell(0).getNumericCellValue(), 0); - assertEquals(8, sheet.getRow(5).getCell(0).getNumericCellValue(), 0); - wb.close(); - } else if ("Document".equals(ole.getInstanceName())){ - //creating a HWPF document - HWPFDocument doc = new HWPFDocument(data.getData()); - String txt = doc.getRange().getParagraph(0).text(); - assertEquals("OLE embedding is thoroughly unremarkable.\r", txt); - doc.close(); - } - } - - } - assertEquals("Expected 2 OLE shapes", 2, cnt); - ppt.close(); - } - - @Test - public void testEmbedding() throws IOException { - HSLFSlideShow ppt = new HSLFSlideShow(); - - File pict = POIDataSamples.getSlideShowInstance().getFile("clock.jpg"); - HSLFPictureData pictData = ppt.addPicture(pict, PictureType.JPEG); - - InputStream is = POIDataSamples.getSpreadSheetInstance().openResourceAsStream("Employee.xls"); - POIFSFileSystem poiData1 = new POIFSFileSystem(is); - is.close(); - - int oleObjectId1 = ppt.addEmbed(poiData1); - - HSLFSlide slide1 = ppt.createSlide(); - OLEShape oleShape1 = new OLEShape(pictData); - oleShape1.setObjectID(oleObjectId1); - slide1.addShape(oleShape1); - oleShape1.setAnchor(new Rectangle2D.Double(100,100,100,100)); - - // add second slide with different order in object creation - HSLFSlide slide2 = ppt.createSlide(); - OLEShape oleShape2 = new OLEShape(pictData); - - is = POIDataSamples.getSpreadSheetInstance().openResourceAsStream("SimpleWithImages.xls"); - POIFSFileSystem poiData2 = new POIFSFileSystem(is); - is.close(); - - int oleObjectId2 = ppt.addEmbed(poiData2); - - oleShape2.setObjectID(oleObjectId2); - slide2.addShape(oleShape2); - oleShape2.setAnchor(new Rectangle2D.Double(100,100,100,100)); - - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - ppt.write(bos); - - ppt = new HSLFSlideShow(new ByteArrayInputStream(bos.toByteArray())); - OLEShape comp = (OLEShape)ppt.getSlides().get(0).getShapes().get(0); - byte compData[] = IOUtils.toByteArray(comp.getObjectData().getData()); - - bos.reset(); - poiData1.writeFilesystem(bos); - byte expData[] = bos.toByteArray(); - - assertArrayEquals(expData, compData); - - poiData1.close(); - poiData2.close(); - ppt.close(); - } - - -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestPPFont.java b/src/scratchpad/testcases/org/apache/poi/hslf/model/TestPPFont.java deleted file mode 100644 index 4c69862c3..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestPPFont.java +++ /dev/null @@ -1,57 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.model; - -import static org.junit.Assert.assertEquals; - -import org.apache.poi.hslf.usermodel.HSLFSlideShow; -import org.junit.Test; - - -/** - * Test adding fonts to the presenataion resources - * - * @author Yegor Kozlov - */ -public final class TestPPFont { - - @Test - public void testCreate() { - HSLFSlideShow ppt = new HSLFSlideShow(); - assertEquals(1, ppt.getNumberOfFonts()); - assertEquals("Arial", ppt.getFont(0).getFontName()); - - //adding the same font twice - assertEquals(0, ppt.addFont(PPFont.ARIAL)); - assertEquals(1, ppt.getNumberOfFonts()); - - assertEquals(1, ppt.addFont(PPFont.TIMES_NEW_ROMAN)); - assertEquals(2, ppt.addFont(PPFont.COURIER_NEW)); - assertEquals(3, ppt.addFont(PPFont.WINGDINGS)); - - assertEquals(4, ppt.getNumberOfFonts()); - - assertEquals(PPFont.TIMES_NEW_ROMAN.getFontName(), ppt.getFont(1).getFontName()); - assertEquals(PPFont.COURIER_NEW.getFontName(), ppt.getFont(2).getFontName()); - - PPFont font3 = ppt.getFont(3); - assertEquals(PPFont.WINGDINGS.getFontName(), font3.getFontName()); - assertEquals(PPFont.SYMBOL_CHARSET, font3.getCharSet()); - assertEquals(PPFont.VARIABLE_PITCH, font3.getPitchAndFamily()); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestPPGraphics2D.java b/src/scratchpad/testcases/org/apache/poi/hslf/model/TestPPGraphics2D.java deleted file mode 100644 index cd5c3f797..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestPPGraphics2D.java +++ /dev/null @@ -1,95 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.model; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.awt.*; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.util.List; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hslf.usermodel.*; -import org.junit.Before; -import org.junit.Test; - -/** - * Test drawing shapes via Graphics2D - * - * @author Yegor Kozlov - */ -public final class TestPPGraphics2D { - private static POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); - private HSLFSlideShow ppt; - - @Before - public void setUp() throws Exception { - ppt = new HSLFSlideShow(_slTests.openResourceAsStream("empty.ppt")); - } - - @Test - public void testGraphics() throws Exception { - // Starts off empty - assertTrue(ppt.getSlides().isEmpty()); - - // Add a slide - HSLFSlide slide = ppt.createSlide(); - assertEquals(1, ppt.getSlides().size()); - - // Add some stuff into it - HSLFGroupShape group = new HSLFGroupShape(); - Dimension pgsize = ppt.getPageSize(); - java.awt.Rectangle bounds = new java.awt.Rectangle(0, 0, (int)pgsize.getWidth(), (int)pgsize.getHeight()); - group.setAnchor(bounds); - slide.addShape(group); - - PPGraphics2D graphics = new PPGraphics2D(group); - graphics.setColor(Color.blue); - graphics.draw(new Rectangle(1296, 2544, 1344, 0)); - - graphics.setColor(Color.red); - graphics.setStroke(new BasicStroke((float)2.5)); - graphics.drawLine(500, 500, 1500, 2500); - - graphics.setColor(Color.green); - graphics.setPaint(Color.gray); - graphics.drawOval(4000, 1000, 1000, 1000); - - // Write the file out - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ppt.write(out); - out.close(); - - // And read it back in - ppt = new HSLFSlideShow(new HSLFSlideShowImpl(new ByteArrayInputStream(out.toByteArray()))); - assertEquals(1, ppt.getSlides().size()); - - slide = ppt.getSlides().get(0); - List shape = slide.getShapes(); - assertEquals(shape.size(), 1); //group shape - - assertTrue(shape.get(0) instanceof HSLFGroupShape); //group shape - - group = (HSLFGroupShape)shape.get(0); - shape = group.getShapes(); - assertEquals(shape.size(), 3); - } - -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestSetBoldItalic.java b/src/scratchpad/testcases/org/apache/poi/hslf/model/TestSetBoldItalic.java deleted file mode 100644 index e593eb8b5..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestSetBoldItalic.java +++ /dev/null @@ -1,82 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.model; - -import static org.junit.Assert.*; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; - -import org.apache.poi.hslf.usermodel.*; -import org.junit.Test; - -/** - * Test setting text properties of newly added TextBoxes - * - * @author Yegor Kozlov - */ -public final class TestSetBoldItalic { - /** - * Verify that we can add TextBox shapes to a slide - * and set some of the style attributes - */ - @Test - public void testTextBoxWrite() throws Exception { - HSLFSlideShow ppt = new HSLFSlideShow(); - HSLFSlide sl = ppt.createSlide(); - HSLFTextRun rt; - - String val = "Hello, World!"; - - // Create a new textbox, and give it lots of properties - HSLFTextBox txtbox = new HSLFTextBox(); - rt = txtbox.getTextParagraphs().get(0).getTextRuns().get(0); - txtbox.setText(val); - rt.setFontSize(42d); - rt.setBold(true); - rt.setItalic(true); - rt.setUnderlined(false); - sl.addShape(txtbox); - - // Check it before save - rt = txtbox.getTextParagraphs().get(0).getTextRuns().get(0); - assertEquals(val, rt.getRawText()); - assertEquals(42, rt.getFontSize(), 0); - assertTrue(rt.isBold()); - assertTrue(rt.isItalic()); - - // Serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ppt.write(out); - out.close(); - - ppt = new HSLFSlideShow(new HSLFSlideShowImpl(new ByteArrayInputStream(out.toByteArray()))); - sl = ppt.getSlides().get(0); - - txtbox = (HSLFTextBox)sl.getShapes().get(0); - rt = txtbox.getTextParagraphs().get(0).getTextRuns().get(0); - - // Check after save - assertEquals(val, rt.getRawText()); - assertEquals(42, rt.getFontSize(), 0); - assertTrue(rt.isBold()); - assertTrue(rt.isItalic()); - assertFalse(rt.isUnderlined()); - } - -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestShapes.java b/src/scratchpad/testcases/org/apache/poi/hslf/model/TestShapes.java deleted file mode 100644 index bf23bd403..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestShapes.java +++ /dev/null @@ -1,498 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.model; - -import static org.apache.poi.sl.TestCommonSL.sameColor; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.geom.Rectangle2D; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.ddf.AbstractEscherOptRecord; -import org.apache.poi.ddf.EscherDgRecord; -import org.apache.poi.ddf.EscherDggRecord; -import org.apache.poi.ddf.EscherProperties; -import org.apache.poi.ddf.EscherSimpleProperty; -import org.apache.poi.hslf.usermodel.HSLFAutoShape; -import org.apache.poi.hslf.usermodel.HSLFGroupShape; -import org.apache.poi.hslf.usermodel.HSLFLine; -import org.apache.poi.hslf.usermodel.HSLFPictureData; -import org.apache.poi.hslf.usermodel.HSLFPictureShape; -import org.apache.poi.hslf.usermodel.HSLFShape; -import org.apache.poi.hslf.usermodel.HSLFSimpleShape; -import org.apache.poi.hslf.usermodel.HSLFSlide; -import org.apache.poi.hslf.usermodel.HSLFSlideShow; -import org.apache.poi.hslf.usermodel.HSLFTextBox; -import org.apache.poi.hslf.usermodel.HSLFTextParagraph; -import org.apache.poi.hslf.usermodel.HSLFTextRun; -import org.apache.poi.hslf.usermodel.HSLFTextShape; -import org.apache.poi.sl.usermodel.PictureData.PictureType; -import org.apache.poi.sl.usermodel.ShapeType; -import org.apache.poi.sl.usermodel.StrokeStyle.LineDash; -import org.junit.Before; -import org.junit.Test; - -/** - * Test drawing shapes via Graphics2D - */ -public final class TestShapes { - private static POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); - - private HSLFSlideShow ppt; - private HSLFSlideShow pptB; - - @Before - public void setUp() throws Exception { - InputStream is1 = null, is2 = null; - try { - is1 = _slTests.openResourceAsStream("empty.ppt"); - ppt = new HSLFSlideShow(is1); - is2 = _slTests.openResourceAsStream("empty_textbox.ppt"); - pptB = new HSLFSlideShow(is2); - } finally { - is1.close(); - is2.close(); - } - } - - @Test - public void graphics() throws IOException { - HSLFSlide slide = ppt.createSlide(); - - HSLFLine line = new HSLFLine(); - java.awt.Rectangle lineAnchor = new java.awt.Rectangle(100, 200, 50, 60); - line.setAnchor(lineAnchor); - line.setLineWidth(3); - line.setLineDash(LineDash.DASH); - line.setLineColor(Color.red); - slide.addShape(line); - - HSLFAutoShape ellipse = new HSLFAutoShape(ShapeType.ELLIPSE); - Rectangle2D ellipseAnchor = new Rectangle2D.Double(320, 154, 55, 111); - ellipse.setAnchor(ellipseAnchor); - ellipse.setLineWidth(2); - ellipse.setLineDash(LineDash.SOLID); - ellipse.setLineColor(Color.green); - ellipse.setFillColor(Color.lightGray); - slide.addShape(ellipse); - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ppt.write(out); - out.close(); - - //read ppt from byte array - - HSLFSlideShow ppt2 = new HSLFSlideShow(new ByteArrayInputStream(out.toByteArray())); - assertEquals(1, ppt2.getSlides().size()); - - slide = ppt2.getSlides().get(0); - List shape = slide.getShapes(); - assertEquals(2, shape.size()); - - assertTrue(shape.get(0) instanceof HSLFLine); //group shape - assertEquals(lineAnchor, shape.get(0).getAnchor()); //group shape - - assertTrue(shape.get(1) instanceof HSLFAutoShape); //group shape - assertEquals(ellipseAnchor, shape.get(1).getAnchor()); //group shape - - ppt2.close(); - } - - /** - * Verify that we can read TextBox shapes - * @throws Exception - */ - @Test - public void textBoxRead() throws IOException { - ppt = new HSLFSlideShow(_slTests.openResourceAsStream("with_textbox.ppt")); - HSLFSlide sl = ppt.getSlides().get(0); - for (HSLFShape sh : sl.getShapes()) { - assertTrue(sh instanceof HSLFTextBox); - HSLFTextBox txtbox = (HSLFTextBox)sh; - String text = txtbox.getText(); - assertNotNull(text); - - assertEquals(txtbox.getTextParagraphs().get(0).getTextRuns().size(), 1); - HSLFTextRun rt = txtbox.getTextParagraphs().get(0).getTextRuns().get(0); - - if (text.equals("Hello, World!!!")){ - assertEquals(32, rt.getFontSize(), 0); - assertTrue(rt.isBold()); - assertTrue(rt.isItalic()); - } else if (text.equals("I am just a poor boy")){ - assertEquals(44, rt.getFontSize(), 0); - assertTrue(rt.isBold()); - } else if (text.equals("This is Times New Roman")){ - assertEquals(16, rt.getFontSize(), 0); - assertTrue(rt.isBold()); - assertTrue(rt.isItalic()); - assertTrue(rt.isUnderlined()); - } else if (text.equals("Plain Text")){ - assertEquals(18, rt.getFontSize(), 0); - } - } - } - - @SuppressWarnings("unused") - @Test - public void testParagraphs() throws IOException { - HSLFSlideShow ss = new HSLFSlideShow(); - HSLFSlide slide = ss.createSlide(); - HSLFTextBox shape = new HSLFTextBox(); - HSLFTextRun p1r1 = shape.setText("para 1 run 1. "); - HSLFTextRun p1r2 = shape.appendText("para 1 run 2.", false); - HSLFTextRun p2r1 = shape.appendText("para 2 run 1. ", true); - HSLFTextRun p2r2 = shape.appendText("para 2 run 2. ", false); - p1r1.setFontColor(Color.black); - p1r2.setFontColor(Color.red); - p2r1.setFontColor(Color.yellow); - p2r2.setStrikethrough(true); - // run 3 has same text properties as run 2 and will be merged when saving - HSLFTextRun p2r3 = shape.appendText("para 2 run 3.", false); - shape.setAnchor(new Rectangle2D.Double(100,100,100,10)); - slide.addShape(shape); - shape.resizeToFitText(); - - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - ss.write(bos); - - ss = new HSLFSlideShow(new ByteArrayInputStream(bos.toByteArray())); - slide = ss.getSlides().get(0); - HSLFTextBox tb = (HSLFTextBox)slide.getShapes().get(0); - List para = tb.getTextParagraphs(); - HSLFTextRun tr = para.get(0).getTextRuns().get(0); - assertEquals("para 1 run 1. ", tr.getRawText()); - assertTrue(sameColor(Color.black, tr.getFontColor())); - tr = para.get(0).getTextRuns().get(1); - assertEquals("para 1 run 2.\r", tr.getRawText()); - assertTrue(sameColor(Color.red, tr.getFontColor())); - tr = para.get(1).getTextRuns().get(0); - assertEquals("para 2 run 1. ", tr.getRawText()); - assertTrue(sameColor(Color.yellow, tr.getFontColor())); - tr = para.get(1).getTextRuns().get(1); - assertEquals("para 2 run 2. para 2 run 3.", tr.getRawText()); - assertTrue(sameColor(Color.black, tr.getFontColor())); - assertTrue(tr.isStrikethrough()); - } - - - /** - * Verify that we can add TextBox shapes to a slide - * and set some of the style attributes - */ - @Test - public void textBoxWriteBytes() throws IOException { - ppt = new HSLFSlideShow(); - HSLFSlide sl = ppt.createSlide(); - HSLFTextRun rt; - - String val = "Hello, World!"; - - // Create a new textbox, and give it lots of properties - HSLFTextBox txtbox = new HSLFTextBox(); - rt = txtbox.getTextParagraphs().get(0).getTextRuns().get(0); - txtbox.setText(val); - rt.setFontFamily("Arial"); - rt.setFontSize(42d); - rt.setBold(true); - rt.setItalic(true); - rt.setUnderlined(false); - rt.setFontColor(Color.red); - sl.addShape(txtbox); - - // Check it before save - rt = txtbox.getTextParagraphs().get(0).getTextRuns().get(0); - assertEquals(val, rt.getRawText()); - assertEquals(42, rt.getFontSize(), 0); - assertTrue(rt.isBold()); - assertTrue(rt.isItalic()); - assertFalse(rt.isUnderlined()); - assertEquals("Arial", rt.getFontFamily()); - assertTrue(sameColor(Color.red, rt.getFontColor())); - - // Serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ppt.write(out); - out.close(); - - HSLFSlideShow ppt2 = new HSLFSlideShow(new ByteArrayInputStream(out.toByteArray())); - sl = ppt2.getSlides().get(0); - - txtbox = (HSLFTextBox)sl.getShapes().get(0); - rt = txtbox.getTextParagraphs().get(0).getTextRuns().get(0); - - // Check after save - assertEquals(val, rt.getRawText()); - assertEquals(42, rt.getFontSize(), 0); - assertTrue(rt.isBold()); - assertTrue(rt.isItalic()); - assertFalse(rt.isUnderlined()); - assertEquals("Arial", rt.getFontFamily()); - assertTrue(sameColor(Color.red, rt.getFontColor())); - - ppt2.close(); - } - - /** - * Test with an empty text box - */ - @Test - public void emptyTextBox() { - assertEquals(2, pptB.getSlides().size()); - HSLFSlide s1 = pptB.getSlides().get(0); - HSLFSlide s2 = pptB.getSlides().get(1); - - // Check we can get the shapes count - assertEquals(2, s1.getShapes().size()); - assertEquals(2, s2.getShapes().size()); - } - - /** - * If you iterate over text shapes in a slide and collect them in a set - * it must be the same as returned by Slide.getTextRuns(). - */ - @Test - public void textBoxSet() throws IOException { - textBoxSet("with_textbox.ppt"); - textBoxSet("basic_test_ppt_file.ppt"); - textBoxSet("next_test_ppt_file.ppt"); - textBoxSet("Single_Coloured_Page.ppt"); - textBoxSet("Single_Coloured_Page_With_Fonts_and_Alignments.ppt"); - textBoxSet("incorrect_slide_order.ppt"); - } - - private void textBoxSet(String filename) throws IOException { - HSLFSlideShow ss = new HSLFSlideShow(_slTests.openResourceAsStream(filename)); - for (HSLFSlide sld : ss.getSlides()) { - ArrayList lst1 = new ArrayList(); - for (List txt : sld.getTextParagraphs()) { - for (HSLFTextParagraph p : txt) { - for (HSLFTextRun r : p) { - lst1.add(r.getRawText()); - } - } - } - - ArrayList lst2 = new ArrayList(); - for (HSLFShape sh : sld.getShapes()) { - if (sh instanceof HSLFTextShape){ - HSLFTextShape tbox = (HSLFTextShape)sh; - for (HSLFTextParagraph p : tbox.getTextParagraphs()) { - for (HSLFTextRun r : p) { - lst2.add(r.getRawText()); - } - } - } - } - assertTrue(lst1.containsAll(lst2)); - assertTrue(lst2.containsAll(lst1)); - } - ss.close(); - } - - /** - * Test adding shapes to ShapeGroup - */ - @Test - public void shapeGroup() throws IOException { - HSLFSlideShow ss = new HSLFSlideShow(); - - HSLFSlide slide = ss.createSlide(); - Dimension pgsize = ss.getPageSize(); - - HSLFGroupShape group = new HSLFGroupShape(); - - group.setAnchor(new Rectangle2D.Double(0, 0, pgsize.getWidth(), pgsize.getHeight())); - slide.addShape(group); - - HSLFPictureData data = ss.addPicture(_slTests.readFile("clock.jpg"), PictureType.JPEG); - HSLFPictureShape pict = new HSLFPictureShape(data, group); - pict.setAnchor(new Rectangle2D.Double(0, 0, 200, 200)); - group.addShape(pict); - - HSLFLine line = new HSLFLine(group); - line.setAnchor(new Rectangle2D.Double(300, 300, 500, 0)); - group.addShape(line); - - //serialize and read again. - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ss.write(out); - out.close(); - ss.close(); - - ByteArrayInputStream is = new ByteArrayInputStream(out.toByteArray()); - ss = new HSLFSlideShow(is); - is.close(); - - slide = ss.getSlides().get(0); - - List shape = slide.getShapes(); - assertEquals(1, shape.size()); - assertTrue(shape.get(0) instanceof HSLFGroupShape); - - group = (HSLFGroupShape)shape.get(0); - List grshape = group.getShapes(); - assertEquals(2, grshape.size()); - assertTrue(grshape.get(0) instanceof HSLFPictureShape); - assertTrue(grshape.get(1) instanceof HSLFLine); - - pict = (HSLFPictureShape)grshape.get(0); - assertEquals(new Rectangle2D.Double(0, 0, 200, 200), pict.getAnchor()); - - line = (HSLFLine)grshape.get(1); - assertEquals(new Rectangle2D.Double(300, 300, 500, 0), line.getAnchor()); - - ss.close(); - } - - /** - * Test functionality of Sheet.removeShape(Shape shape) - */ - @Test - public void removeShapes() throws IOException { - String file = "with_textbox.ppt"; - HSLFSlideShow ss = new HSLFSlideShow(_slTests.openResourceAsStream(file)); - HSLFSlide sl = ss.getSlides().get(0); - List sh = sl.getShapes(); - assertEquals("expected four shaped in " + file, 4, sh.size()); - //remove all - for (int i = 0; i < sh.size(); i++) { - boolean ok = sl.removeShape(sh.get(i)); - assertTrue("Failed to delete shape #" + i, ok); - } - //now Slide.getShapes() should return an empty array - assertEquals("expected 0 shaped in " + file, 0, sl.getShapes().size()); - - //serialize and read again. The file should be readable and contain no shapes - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ss.write(out); - out.close(); - ss.close(); - - ss = new HSLFSlideShow(new ByteArrayInputStream(out.toByteArray())); - sl = ss.getSlides().get(0); - assertEquals("expected 0 shaped in " + file, 0, sl.getShapes().size()); - ss.close(); - } - - @Test - public void lineWidth() { - HSLFSimpleShape sh = new HSLFAutoShape(ShapeType.RT_TRIANGLE); - - AbstractEscherOptRecord opt = sh.getEscherOptRecord(); - EscherSimpleProperty prop = HSLFSimpleShape.getEscherProperty(opt, EscherProperties.LINESTYLE__LINEWIDTH); - assertNull(prop); - assertEquals(HSLFSimpleShape.DEFAULT_LINE_WIDTH, sh.getLineWidth(), 0); - - sh.setLineWidth(1.0); - prop = HSLFSimpleShape.getEscherProperty(opt, EscherProperties.LINESTYLE__LINEWIDTH); - assertNotNull(prop); - assertEquals(1.0, sh.getLineWidth(), 0); - } - - @Test - public void shapeId() throws IOException { - HSLFSlideShow ss = new HSLFSlideShow(); - HSLFSlide slide = ss.createSlide(); - HSLFShape shape = null; - - //EscherDgg is a document-level record which keeps track of the drawing groups - EscherDggRecord dgg = ss.getDocumentRecord().getPPDrawingGroup().getEscherDggRecord(); - EscherDgRecord dg = slide.getSheetContainer().getPPDrawing().getEscherDgRecord(); - - int dggShapesUsed = dgg.getNumShapesSaved(); //total number of shapes in the ppt - int dggMaxId = dgg.getShapeIdMax(); //max number of shapeId - - int dgMaxId = dg.getLastMSOSPID(); //max shapeId in the slide - int dgShapesUsed = dg.getNumShapes(); // number of shapes in the slide - //insert 3 shapes and make sure the Ids are properly incremented - for (int i = 0; i < 3; i++) { - shape = new HSLFLine(); - assertEquals(0, shape.getShapeId()); - slide.addShape(shape); - assertTrue(shape.getShapeId() > 0); - - //check that EscherDgRecord is updated - assertEquals(shape.getShapeId(), dg.getLastMSOSPID()); - assertEquals(dgMaxId + 1, dg.getLastMSOSPID()); - assertEquals(dgShapesUsed + 1, dg.getNumShapes()); - - //check that EscherDggRecord is updated - assertEquals(shape.getShapeId() + 1, dgg.getShapeIdMax()); - assertEquals(dggMaxId + 1, dgg.getShapeIdMax()); - assertEquals(dggShapesUsed + 1, dgg.getNumShapesSaved()); - - dggShapesUsed = dgg.getNumShapesSaved(); - dggMaxId = dgg.getShapeIdMax(); - dgMaxId = dg.getLastMSOSPID(); - dgShapesUsed = dg.getNumShapes(); - } - - - //For each drawing group PPT allocates clusters with size=1024 - //if the number of shapes is greater that 1024 a new cluster is allocated - //make sure it is so - int numClusters = dgg.getNumIdClusters(); - for (int i = 0; i < 1025; i++) { - shape = new HSLFLine(); - slide.addShape(shape); - } - assertEquals(numClusters + 1, dgg.getNumIdClusters()); - ss.close(); - } - - @Test - public void lineColor() throws IOException { - HSLFSlideShow ss = new HSLFSlideShow(_slTests.openResourceAsStream("51731.ppt")); - List shape = ss.getSlides().get(0).getShapes(); - - assertEquals(4, shape.size()); - - HSLFTextShape sh1 = (HSLFTextShape)shape.get(0); - assertEquals("Hello Apache POI", sh1.getText()); - assertNull(sh1.getLineColor()); - - HSLFTextShape sh2 = (HSLFTextShape)shape.get(1); - assertEquals("Why are you showing this border?", sh2.getText()); - assertNull(sh2.getLineColor()); - - HSLFTextShape sh3 = (HSLFTextShape)shape.get(2); - assertEquals("Text in a black border", sh3.getText()); - assertEquals(Color.black, sh3.getLineColor()); - assertEquals(0.75, sh3.getLineWidth(), 0); - - HSLFTextShape sh4 = (HSLFTextShape)shape.get(3); - assertEquals("Border width is 5 pt", sh4.getText()); - assertEquals(Color.black, sh4.getLineColor()); - assertEquals(5.0, sh4.getLineWidth(), 0); - - ss.close(); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestSheet.java b/src/scratchpad/testcases/org/apache/poi/hslf/model/TestSheet.java deleted file mode 100644 index 1b5aa8dcc..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestSheet.java +++ /dev/null @@ -1,103 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.model; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.util.List; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hslf.exceptions.EncryptedPowerPointFileException; -import org.apache.poi.hslf.record.ColorSchemeAtom; -import org.apache.poi.hslf.record.PPDrawing; -import org.apache.poi.hslf.usermodel.*; -import org.junit.Test; - -/** - * Test common functionality of the Sheet object. - * For each ppt in the test directory check that all sheets are properly initialized - * - * @author Yegor Kozlov - */ -public final class TestSheet { - private static POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); - - /** - * For each ppt in the test directory check that all sheets are properly initialized - */ - @Test - public void testSheet() throws Exception { - String[] tests = {"SampleShow.ppt", "backgrounds.ppt", "text_shapes.ppt", "pictures.ppt"}; - for (String file : tests) { - try { - HSLFSlideShow ppt = new HSLFSlideShow(_slTests.openResourceAsStream(file)); - doSlideShow(ppt); - } catch (EncryptedPowerPointFileException e){ - //skip encrypted ppt - } - } - } - - private void doSlideShow(HSLFSlideShow ppt) { - for (HSLFSlide slide : ppt.getSlides()) { - verify(slide); - - HSLFNotes notes = slide.getNotes(); - if(notes != null) verify(notes); - - HSLFMasterSheet master = slide.getMasterSheet(); - assertNotNull(master); - verify(master); - } - } - - private void verify(HSLFSheet sheet){ - assertNotNull(sheet.getSlideShow()); - - ColorSchemeAtom colorscheme = sheet.getColorScheme(); - assertNotNull(colorscheme); - - PPDrawing ppdrawing = sheet.getPPDrawing(); - assertNotNull(ppdrawing); - - HSLFBackground background = sheet.getBackground(); - assertNotNull(background); - - assertTrue(sheet._getSheetNumber() != 0); - assertTrue(sheet._getSheetRefId() != 0); - - List> txt = sheet.getTextParagraphs(); - // assertTrue("no text runs", txt != null && !txt.isEmpty()); - // backgrounds.ppt has no texts - for (List t : txt) { - for (HSLFTextParagraph tp : t) { - assertNotNull(tp.getSheet()); - } - } - - List shape = sheet.getShapes(); - assertTrue("no shapes", shape != null && !shape.isEmpty()); - for (HSLFShape s : shape) { - assertNotNull(s.getSpContainer()); - assertNotNull(s.getSheet()); - assertNotNull(s.getShapeName()); - assertNotNull(s.getAnchor()); - } - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestSlideChangeNotes.java b/src/scratchpad/testcases/org/apache/poi/hslf/model/TestSlideChangeNotes.java deleted file mode 100644 index 57f6f5adb..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestSlideChangeNotes.java +++ /dev/null @@ -1,65 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.model; - - -import static org.junit.Assert.assertEquals; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hslf.record.SlideAtom; -import org.apache.poi.hslf.usermodel.*; -import org.junit.Before; -import org.junit.Test; - -/** - * Tests that changing a slide's idea of what notes sheet is its works right - * - * @author Nick Burch (nick at torchbox dot com) - */ -public final class TestSlideChangeNotes { - // SlideShow primed on the test data - private HSLFSlideShow ss; - - @Before - public void init() throws Exception { - POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); - HSLFSlideShowImpl hss = new HSLFSlideShowImpl(_slTests.openResourceAsStream("basic_test_ppt_file.ppt")); - ss = new HSLFSlideShow(hss); - } - - @Test - public void testSetToNone() { - HSLFSlide slideOne = ss.getSlides().get(0); - SlideAtom sa = slideOne.getSlideRecord().getSlideAtom(); - - slideOne.setNotes(null); - - assertEquals(0, sa.getNotesID()); - } - - @Test - public void testSetToSomething() { - HSLFSlide slideOne = ss.getSlides().get(0); - HSLFNotes notesOne = ss.getNotes().get(1); - SlideAtom sa = slideOne.getSlideRecord().getSlideAtom(); - - slideOne.setNotes(notesOne); - - assertEquals(notesOne._getSheetNumber(), sa.getNotesID()); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestSlideMaster.java b/src/scratchpad/testcases/org/apache/poi/hslf/model/TestSlideMaster.java deleted file mode 100644 index 23a3d156f..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestSlideMaster.java +++ /dev/null @@ -1,244 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.model; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.util.List; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hslf.model.textproperties.CharFlagsTextProp; -import org.apache.poi.hslf.record.Environment; -import org.apache.poi.hslf.record.TextHeaderAtom; -import org.apache.poi.hslf.usermodel.*; -import org.junit.Test; - -/** - * Tests for SlideMaster - * - * @author Yegor Kozlov - */ -public final class TestSlideMaster { - private static POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); - - /** - * The reference ppt has two masters. - * Check we can read their attributes. - */ - @Test - public void testSlideMaster() throws Exception { - HSLFSlideShow ppt = new HSLFSlideShow(_slTests.openResourceAsStream("slide_master.ppt")); - - Environment env = ppt.getDocumentRecord().getEnvironment(); - - List master = ppt.getSlideMasters(); - assertEquals(2, master.size()); - - //character attributes - assertEquals(40, master.get(0).getStyleAttribute(TextHeaderAtom.TITLE_TYPE, 0, "font.size", true).getValue()); - assertEquals(48, master.get(1).getStyleAttribute(TextHeaderAtom.TITLE_TYPE, 0, "font.size", true).getValue()); - - int font1 = master.get(0).getStyleAttribute(TextHeaderAtom.TITLE_TYPE, 0, "font.index", true).getValue(); - int font2 = master.get(1).getStyleAttribute(TextHeaderAtom.TITLE_TYPE, 0, "font.index", true).getValue(); - assertEquals("Arial", env.getFontCollection().getFontWithId(font1)); - assertEquals("Georgia", env.getFontCollection().getFontWithId(font2)); - - CharFlagsTextProp prop1 = (CharFlagsTextProp)master.get(0).getStyleAttribute(TextHeaderAtom.TITLE_TYPE, 0, "char_flags", true); - assertEquals(false, prop1.getSubValue(CharFlagsTextProp.BOLD_IDX)); - assertEquals(false, prop1.getSubValue(CharFlagsTextProp.ITALIC_IDX)); - assertEquals(true, prop1.getSubValue(CharFlagsTextProp.UNDERLINE_IDX)); - - CharFlagsTextProp prop2 = (CharFlagsTextProp)master.get(1).getStyleAttribute(TextHeaderAtom.TITLE_TYPE, 0, "char_flags", true); - assertEquals(false, prop2.getSubValue(CharFlagsTextProp.BOLD_IDX)); - assertEquals(true, prop2.getSubValue(CharFlagsTextProp.ITALIC_IDX)); - assertEquals(false, prop2.getSubValue(CharFlagsTextProp.UNDERLINE_IDX)); - - //now paragraph attributes - assertEquals(0x266B, master.get(0).getStyleAttribute(TextHeaderAtom.BODY_TYPE, 0, "bullet.char", false).getValue()); - assertEquals(0x2022, master.get(1).getStyleAttribute(TextHeaderAtom.BODY_TYPE, 0, "bullet.char", false).getValue()); - - int b1 = master.get(0).getStyleAttribute(TextHeaderAtom.BODY_TYPE, 0, "bullet.font", false).getValue(); - int b2 = master.get(1).getStyleAttribute(TextHeaderAtom.BODY_TYPE, 0, "bullet.font", false).getValue(); - assertEquals("Arial", env.getFontCollection().getFontWithId(b1)); - assertEquals("Georgia", env.getFontCollection().getFontWithId(b2)); - } - - /** - * Test we can read default text attributes for a title master sheet - */ - @Test - public void testTitleMasterTextAttributes() throws Exception { - HSLFSlideShow ppt = new HSLFSlideShow(_slTests.openResourceAsStream("slide_master.ppt")); - List master = ppt.getTitleMasters(); - assertEquals(1, master.size()); - - assertEquals(32, master.get(0).getStyleAttribute(TextHeaderAtom.CENTER_TITLE_TYPE, 0, "font.size", true).getValue()); - CharFlagsTextProp prop1 = (CharFlagsTextProp)master.get(0).getStyleAttribute(TextHeaderAtom.CENTER_TITLE_TYPE, 0, "char_flags", true); - assertEquals(true, prop1.getSubValue(CharFlagsTextProp.BOLD_IDX)); - assertEquals(false, prop1.getSubValue(CharFlagsTextProp.ITALIC_IDX)); - assertEquals(true, prop1.getSubValue(CharFlagsTextProp.UNDERLINE_IDX)); - - assertEquals(20, master.get(0).getStyleAttribute(TextHeaderAtom.CENTRE_BODY_TYPE, 0, "font.size", true).getValue()); - CharFlagsTextProp prop2 = (CharFlagsTextProp)master.get(0).getStyleAttribute(TextHeaderAtom.CENTRE_BODY_TYPE, 0, "char_flags", true); - assertEquals(true, prop2.getSubValue(CharFlagsTextProp.BOLD_IDX)); - assertEquals(false, prop2.getSubValue(CharFlagsTextProp.ITALIC_IDX)); - assertEquals(false, prop2.getSubValue(CharFlagsTextProp.UNDERLINE_IDX)); - } - - /** - * Slide 3 has title layout and follows the TitleMaster. Verify that. - */ - @Test - public void testTitleMaster() throws Exception { - HSLFSlideShow ppt = new HSLFSlideShow(_slTests.openResourceAsStream("slide_master.ppt")); - HSLFSlide slide = ppt.getSlides().get(2); - HSLFMasterSheet masterSheet = slide.getMasterSheet(); - assertTrue(masterSheet instanceof HSLFTitleMaster); - - for (List txt : slide.getTextParagraphs()) { - HSLFTextRun rt = txt.get(0).getTextRuns().get(0); - switch(txt.get(0).getRunType()){ - case TextHeaderAtom.CENTER_TITLE_TYPE: - assertEquals("Arial", rt.getFontFamily()); - assertEquals(32, rt.getFontSize(), 0); - assertEquals(true, rt.isBold()); - assertEquals(true, rt.isUnderlined()); - break; - case TextHeaderAtom.CENTRE_BODY_TYPE: - assertEquals("Courier New", rt.getFontFamily()); - assertEquals(20, rt.getFontSize(), 0); - assertEquals(true, rt.isBold()); - assertEquals(false, rt.isUnderlined()); - break; - } - - } - } - /** - * If a style attribute is not set ensure it is read from the master - */ - @Test - public void testMasterAttributes() throws Exception { - HSLFSlideShow ppt = new HSLFSlideShow(_slTests.openResourceAsStream("slide_master.ppt")); - List slide = ppt.getSlides(); - assertEquals(3, slide.size()); - for (List tparas : slide.get(0).getTextParagraphs()) { - HSLFTextParagraph tpara = tparas.get(0); - if (tpara.getRunType() == TextHeaderAtom.TITLE_TYPE){ - HSLFTextRun rt = tpara.getTextRuns().get(0); - assertEquals(40, rt.getFontSize(), 0); - assertEquals(true, rt.isUnderlined()); - assertEquals("Arial", rt.getFontFamily()); - } else if (tpara.getRunType() == TextHeaderAtom.BODY_TYPE){ - HSLFTextRun rt = tpara.getTextRuns().get(0); - assertEquals(0, tpara.getIndentLevel()); - assertEquals(32, rt.getFontSize(), 0); - assertEquals("Arial", rt.getFontFamily()); - - tpara = tparas.get(1); - rt = tpara.getTextRuns().get(0); - assertEquals(1, tpara.getIndentLevel()); - assertEquals(28, rt.getFontSize(), 0); - assertEquals("Arial", rt.getFontFamily()); - - } - } - - for (List tparas : slide.get(1).getTextParagraphs()) { - HSLFTextParagraph tpara = tparas.get(0); - if (tpara.getRunType() == TextHeaderAtom.TITLE_TYPE){ - HSLFTextRun rt = tpara.getTextRuns().get(0); - assertEquals(48, rt.getFontSize(), 0); - assertEquals(true, rt.isItalic()); - assertEquals("Georgia", rt.getFontFamily()); - } else if (tpara.getRunType() == TextHeaderAtom.BODY_TYPE){ - HSLFTextRun rt; - rt = tpara.getTextRuns().get(0); - assertEquals(0, tpara.getIndentLevel()); - assertEquals(32, rt.getFontSize(), 0); - assertEquals("Courier New", rt.getFontFamily()); - } - } - - } - - /** - * Check we can dynamically assign a slide master to a slide. - */ - @Test - public void testChangeSlideMaster() throws Exception { - HSLFSlideShow ppt = new HSLFSlideShow(_slTests.openResourceAsStream("slide_master.ppt")); - List master = ppt.getSlideMasters(); - List slide = ppt.getSlides(); - int sheetNo; - - //each slide uses its own master - assertEquals(slide.get(0).getMasterSheet()._getSheetNumber(), master.get(0)._getSheetNumber()); - assertEquals(slide.get(1).getMasterSheet()._getSheetNumber(), master.get(1)._getSheetNumber()); - - //all slides use the first master slide - sheetNo = master.get(0)._getSheetNumber(); - for (HSLFSlide s : slide) { - s.setMasterSheet(master.get(0)); - } - - ByteArrayOutputStream out; - - out = new ByteArrayOutputStream(); - ppt.write(out); - out.close(); - - ppt = new HSLFSlideShow(new HSLFSlideShowImpl(new ByteArrayInputStream(out.toByteArray()))); - master = ppt.getSlideMasters(); - slide = ppt.getSlides(); - for (HSLFSlide s : slide) { - assertEquals(sheetNo, s.getMasterSheet()._getSheetNumber()); - } - } - - /** - * Varify we can read attrubutes for different identtation levels. - * (typical for the "bullted body" placeholder) - */ - @Test - public void testIndentation() throws Exception { - HSLFSlideShow ppt = new HSLFSlideShow(_slTests.openResourceAsStream("slide_master.ppt")); - HSLFSlide slide = ppt.getSlides().get(0); - - for (List tparas : slide.getTextParagraphs()) { - HSLFTextParagraph tpara = tparas.get(0); - if (tpara.getRunType() == TextHeaderAtom.TITLE_TYPE){ - HSLFTextRun rt = tpara.getTextRuns().get(0); - assertEquals(40, rt.getFontSize(), 0); - assertEquals(true, rt.isUnderlined()); - assertEquals("Arial", rt.getFontFamily()); - } else if (tpara.getRunType() == TextHeaderAtom.BODY_TYPE){ - int indents[] = { 32, 28, 24 }; - for (HSLFTextRun rt : tpara.getTextRuns()) { - int indent = tpara.getIndentLevel(); - assertEquals(indents[indent], rt.getFontSize(), 0); - } - } - } - - } - -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestSlides.java b/src/scratchpad/testcases/org/apache/poi/hslf/model/TestSlides.java deleted file mode 100644 index 5ced9945c..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestSlides.java +++ /dev/null @@ -1,191 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.model; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hslf.usermodel.*; -import org.junit.Test; - -/** - * Test adding new slides to a ppt. - * - * Note - uses the same empty PPT file as the core "new Slideshow" - * stuff does - * @author Yegor Kozlov - */ -public final class TestSlides { - - /** - * Add 1 slide to an empty ppt. - * @throws Exception - */ - @Test - public void testAddSlides1() throws Exception { - HSLFSlideShow ppt = new HSLFSlideShow(new HSLFSlideShowImpl( TestSlides.class.getResourceAsStream("/org/apache/poi/hslf/data/empty.ppt") )); - assertTrue(ppt.getSlides().isEmpty()); - - HSLFSlide s1 = ppt.createSlide(); - assertEquals(1, ppt.getSlides().size()); - assertEquals(3, s1._getSheetRefId()); - assertEquals(256, s1._getSheetNumber()); - assertEquals(1, s1.getSlideNumber()); - - //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ppt.write(out); - out.close(); - - ppt = new HSLFSlideShow(new HSLFSlideShowImpl(new ByteArrayInputStream(out.toByteArray()))); - assertEquals(1, ppt.getSlides().size()); - } - - /** - * Add 2 slides to an empty ppt - * @throws Exception - */ - @Test - public void testAddSlides2() throws Exception { - HSLFSlideShow ppt = new HSLFSlideShow(new HSLFSlideShowImpl( TestSlides.class.getResourceAsStream("/org/apache/poi/hslf/data/empty.ppt") )); - assertTrue(ppt.getSlides().isEmpty()); - - HSLFSlide s1 = ppt.createSlide(); - assertEquals(1, ppt.getSlides().size()); - assertEquals(3, s1._getSheetRefId()); - assertEquals(256, s1._getSheetNumber()); - assertEquals(1, s1.getSlideNumber()); - - HSLFSlide s2 = ppt.createSlide(); - assertEquals(2, ppt.getSlides().size()); - assertEquals(4, s2._getSheetRefId()); - assertEquals(257, s2._getSheetNumber()); - assertEquals(2, s2.getSlideNumber()); - - //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ppt.write(out); - out.close(); - - ppt = new HSLFSlideShow(new HSLFSlideShowImpl(new ByteArrayInputStream(out.toByteArray()))); - assertEquals(2, ppt.getSlides().size()); - } - - /** - * Add 3 slides to an empty ppt - * @throws Exception - */ - @Test - public void testAddSlides3() throws Exception { - HSLFSlideShow ppt = new HSLFSlideShow(new HSLFSlideShowImpl( TestSlides.class.getResourceAsStream("/org/apache/poi/hslf/data/empty.ppt") )); - assertTrue(ppt.getSlides().isEmpty()); - - HSLFSlide s1 = ppt.createSlide(); - assertEquals(1, ppt.getSlides().size()); - assertEquals(3, s1._getSheetRefId()); - assertEquals(256, s1._getSheetNumber()); - assertEquals(1, s1.getSlideNumber()); - - HSLFSlide s2 = ppt.createSlide(); - assertEquals(2, ppt.getSlides().size()); - assertEquals(4, s2._getSheetRefId()); - assertEquals(257, s2._getSheetNumber()); - assertEquals(2, s2.getSlideNumber()); - - HSLFSlide s3 = ppt.createSlide(); - assertEquals(3, ppt.getSlides().size()); - assertEquals(5, s3._getSheetRefId()); - assertEquals(258, s3._getSheetNumber()); - assertEquals(3, s3.getSlideNumber()); - - - //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ppt.write(out); - out.close(); - - ppt = new HSLFSlideShow(new HSLFSlideShowImpl(new ByteArrayInputStream(out.toByteArray()))); - assertEquals(3, ppt.getSlides().size()); - - // Check IDs are still right - s1 = ppt.getSlides().get(0); - assertEquals(256, s1._getSheetNumber()); - assertEquals(3, s1._getSheetRefId()); - s2 = ppt.getSlides().get(1); - assertEquals(257, s2._getSheetNumber()); - assertEquals(4, s2._getSheetRefId()); - s3 = ppt.getSlides().get(2); - assertEquals(3, ppt.getSlides().size()); - assertEquals(258, s3._getSheetNumber()); - assertEquals(5, s3._getSheetRefId()); - } - - /** - * Add slides to ppt which already has two slides - */ - @Test - public void testAddSlides2to3() throws Exception { - POIDataSamples slTests = POIDataSamples.getSlideShowInstance(); - HSLFSlideShow ppt = new HSLFSlideShow(slTests.openResourceAsStream("basic_test_ppt_file.ppt")); - - assertEquals(2, ppt.getSlides().size()); - - // First slide is 256 / 4 - HSLFSlide s1 = ppt.getSlides().get(0); - assertEquals(256, s1._getSheetNumber()); - assertEquals(4, s1._getSheetRefId()); - - // Last slide is 257 / 6 - HSLFSlide s2 = ppt.getSlides().get(1); - assertEquals(257, s2._getSheetNumber()); - assertEquals(6, s2._getSheetRefId()); - - // Add another slide, goes in at the end - HSLFSlide s3 = ppt.createSlide(); - assertEquals(3, ppt.getSlides().size()); - assertEquals(258, s3._getSheetNumber()); - assertEquals(8, s3._getSheetRefId()); - - - // Serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ppt.write(out); - out.close(); - - ppt = new HSLFSlideShow(new HSLFSlideShowImpl(new ByteArrayInputStream(out.toByteArray()))); - assertEquals(3, ppt.getSlides().size()); - - - // Check IDs are still right - s1 = ppt.getSlides().get(0); - assertEquals(256, s1._getSheetNumber()); - assertEquals(4, s1._getSheetRefId()); - s2 = ppt.getSlides().get(1); - assertEquals(257, s2._getSheetNumber()); - assertEquals(6, s2._getSheetRefId()); - s3 = ppt.getSlides().get(2); - assertEquals(3, ppt.getSlides().size()); - assertEquals(258, s3._getSheetNumber()); - assertEquals(8, s3._getSheetRefId()); - } - -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestTable.java b/src/scratchpad/testcases/org/apache/poi/hslf/model/TestTable.java deleted file mode 100644 index 3c7bc9c9a..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestTable.java +++ /dev/null @@ -1,152 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.model; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.List; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hslf.record.TextHeaderAtom; -import org.apache.poi.hslf.usermodel.HSLFShape; -import org.apache.poi.hslf.usermodel.HSLFSlide; -import org.apache.poi.hslf.usermodel.HSLFSlideShow; -import org.apache.poi.hslf.usermodel.HSLFTable; -import org.apache.poi.hslf.usermodel.HSLFTableCell; -import org.apache.poi.sl.usermodel.Shape; -import org.apache.poi.sl.usermodel.Slide; -import org.apache.poi.sl.usermodel.SlideShow; -import org.apache.poi.sl.usermodel.TableShape; -import org.junit.Test; - -/** - * Test Table object. - */ -public final class TestTable { - private static POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); - - /** - * Test that ShapeFactory works properly and returns Table - */ - @Test - public void testShapeFactory() throws IOException { - HSLFSlideShow ppt = new HSLFSlideShow(); - - HSLFSlide slide = ppt.createSlide(); - - HSLFTable tbl = slide.createTable(2, 5); - - HSLFTableCell cell = tbl.getCell(0, 0); - //table cells have type=TextHeaderAtom.OTHER_TYPE, see bug #46033 - assertEquals(TextHeaderAtom.OTHER_TYPE, cell.getTextParagraphs().get(0).getRunType()); - - HSLFShape tblSh = slide.getShapes().get(0); - assertTrue(tblSh instanceof HSLFTable); - HSLFTable tbl2 = (HSLFTable)tblSh; - assertEquals(tbl.getNumberOfColumns(), tbl2.getNumberOfColumns()); - assertEquals(tbl.getNumberOfRows(), tbl2.getNumberOfRows()); - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ppt.write(out); - out.close(); - ppt.close(); - - ppt = new HSLFSlideShow(new ByteArrayInputStream(out.toByteArray())); - slide = ppt.getSlides().get(0); - assertTrue(slide.getShapes().get(0) instanceof HSLFTable); - HSLFTable tbl3 = (HSLFTable)slide.getShapes().get(0); - assertEquals(tbl.getNumberOfColumns(), tbl3.getNumberOfColumns()); - assertEquals(tbl.getNumberOfRows(), tbl3.getNumberOfRows()); - ppt.close(); - } - - /** - * Error constructing Table when rownum=1 - */ - @Test - public void test45889() throws IOException { - HSLFSlideShow ppt = new HSLFSlideShow(); - HSLFSlide slide = ppt.createSlide(); - List shapes; - HSLFTable tbl1 = slide.createTable(1, 5); - assertEquals(5, tbl1.getNumberOfColumns()); - assertEquals(1, tbl1.getNumberOfRows()); - - shapes = slide.getShapes(); - assertEquals(1, shapes.size()); - - HSLFTable tbl2 = (HSLFTable)shapes.get(0); - assertSame(tbl1.getSpContainer(), tbl2.getSpContainer()); - - assertEquals(tbl1.getNumberOfColumns(), tbl2.getNumberOfColumns()); - assertEquals(tbl1.getNumberOfRows(), tbl2.getNumberOfRows()); - ppt.close(); - } - - @Test(expected=IllegalArgumentException.class) - public void testIllegalRowCnstruction() throws IOException { - HSLFSlideShow ppt = new HSLFSlideShow(); - HSLFSlide slide = ppt.createSlide(); - slide.createTable(0, 5); - fail("Table(rownum, colnum) must throw IllegalArgumentException if any of tghe arguments is less than 1"); - ppt.close(); - } - - @Test(expected=IllegalArgumentException.class) - public void testIllegalColConstruction() throws IOException { - HSLFSlideShow ppt = new HSLFSlideShow(); - HSLFSlide slide = ppt.createSlide(); - slide.createTable(5, 0); - fail("Table(rownum, colnum) must throw IllegalArgumentException if any of tghe arguments is less than 1"); - ppt.close(); - } - - /** - * Bug 57820: initTable throws NullPointerException - * when the table is positioned with its top at -1 - */ - @Test - public void test57820() throws IOException { - SlideShow ppt = new HSLFSlideShow(_slTests.openResourceAsStream("bug57820-initTableNullRefrenceException.ppt")); - - List> slides = ppt.getSlides(); - assertEquals(1, slides.size()); - - List> shapes = slides.get(0).getShapes(); //throws NullPointerException - - TableShape tbl = null; - for(Shape s : shapes) { - if(s instanceof TableShape) { - tbl = (TableShape)s; - break; - } - } - - assertNotNull(tbl); - assertEquals(-1, tbl.getAnchor().getY(), 0); - - ppt.close(); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestTextRunReWrite.java b/src/scratchpad/testcases/org/apache/poi/hslf/model/TestTextRunReWrite.java deleted file mode 100644 index 85070a3d5..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/model/TestTextRunReWrite.java +++ /dev/null @@ -1,177 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.model; - -import static org.junit.Assert.assertEquals; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.util.List; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hslf.usermodel.*; -import org.apache.poi.poifs.filesystem.DocumentEntry; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.junit.Before; -import org.junit.Test; - -/** - * Tests that if we load something up, get a TextRun, set the text - * to be the same as it was before, and write it all back out again, - * that we don't break anything in the process. - * - * @author Nick Burch (nick at torchbox dot com) - */ -public final class TestTextRunReWrite { - // HSLFSlideShow primed on the test data - private HSLFSlideShowImpl hss; - // HSLFSlideShow primed on the test data - private HSLFSlideShow ss; - // POIFS primed on the test data - private POIFSFileSystem pfs; - - /** - * Load up a test PPT file with rich data - */ - @Before - public void setUp() throws Exception { - POIDataSamples slTests = POIDataSamples.getSlideShowInstance(); - String filename = "Single_Coloured_Page_With_Fonts_and_Alignments.ppt"; - pfs = new POIFSFileSystem(slTests.openResourceAsStream(filename)); - hss = new HSLFSlideShowImpl(pfs); - ss = new HSLFSlideShow(hss); - } - - @Test - public void testWritesOutTheSameNonRich() throws Exception { - // Ensure the text lengths are as we'd expect to start with - assertEquals(1, ss.getSlides().size()); - assertEquals(2, ss.getSlides().get(0).getTextParagraphs().size()); - - // Grab the first text run on the first sheet - List tr1 = ss.getSlides().get(0).getTextParagraphs().get(0); - List tr2 = ss.getSlides().get(0).getTextParagraphs().get(1); - - - assertEquals(30, HSLFTextParagraph.getRawText(tr1).length()); - assertEquals(179, HSLFTextParagraph.getRawText(tr2).length()); - - assertEquals(1, tr1.size()); - assertEquals(30, HSLFTextParagraph.getText(tr1).length()); - assertEquals(30, HSLFTextParagraph.getRawText(tr1).length()); - assertEquals(31, tr1.get(0).getTextRuns().get(0).getCharacterStyle().getCharactersCovered()); - assertEquals(31, tr1.get(0).getParagraphStyle().getCharactersCovered()); - - // Set the text to be as it is now - HSLFTextParagraph.setText(tr1, HSLFTextParagraph.getRawText(tr1)); - tr1 = ss.getSlides().get(0).getTextParagraphs().get(0); - - // Check the text lengths are still right - assertEquals(30, HSLFTextParagraph.getRawText(tr1).length()); - assertEquals(179, HSLFTextParagraph.getRawText(tr2).length()); - - assertEquals(1, tr1.size()); - assertEquals(30, HSLFTextParagraph.getText(tr1).length()); - assertEquals(30, HSLFTextParagraph.getRawText(tr1).length()); - assertEquals(31, tr1.get(0).getTextRuns().get(0).getCharacterStyle().getCharactersCovered()); - assertEquals(31, tr1.get(0).getParagraphStyle().getCharactersCovered()); - - - // Write the slideshow out to a byte array - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ss.write(baos); - - // Build an input stream of it - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - - // Use POIFS to query that lot - POIFSFileSystem npfs = new POIFSFileSystem(bais); - - // Check that the "PowerPoint Document" sections have the same size - DocumentEntry oProps = (DocumentEntry)pfs.getRoot().getEntry("PowerPoint Document"); - DocumentEntry nProps = (DocumentEntry)npfs.getRoot().getEntry("PowerPoint Document"); - assertEquals(oProps.getSize(),nProps.getSize()); - - // Check that they contain the same data - byte[] _oData = new byte[oProps.getSize()]; - byte[] _nData = new byte[nProps.getSize()]; - pfs.createDocumentInputStream("PowerPoint Document").read(_oData); - npfs.createDocumentInputStream("PowerPoint Document").read(_nData); - for(int i=0; i<_oData.length; i++) { -// System.out.println(i + "\t" + Integer.toHexString(i)); - assertEquals(_oData[i], _nData[i]); - } - } - - @Test - public void testWritesOutTheSameRich() throws Exception { - // Grab the first text run on the first sheet - List tr1 = ss.getSlides().get(0).getTextParagraphs().get(0); - - // Get the first rich text run - HSLFTextRun rtr1 = tr1.get(0).getTextRuns().get(0); - - - // Check that the text sizes are as expected - assertEquals(1, tr1.get(0).getTextRuns().size()); - assertEquals(30, HSLFTextParagraph.getRawText(tr1).length()); - assertEquals(30, rtr1.getLength()); - assertEquals(30, rtr1.getRawText().length()); - assertEquals(31, rtr1.getCharacterStyle().getCharactersCovered()); - assertEquals(31, tr1.get(0).getParagraphStyle().getCharactersCovered()); - - // Set the text to be as it is now - rtr1.setText( rtr1.getRawText() ); - rtr1 = tr1.get(0).getTextRuns().get(0); - - // Check that the text sizes are still as expected - assertEquals(1, tr1.get(0).getTextRuns().size()); - assertEquals(30, HSLFTextParagraph.getRawText(tr1).length()); - assertEquals(30, tr1.get(0).getTextRuns().get(0).getRawText().length()); - assertEquals(30, rtr1.getLength()); - assertEquals(30, rtr1.getRawText().length()); - assertEquals(31, rtr1.getCharacterStyle().getCharactersCovered()); - assertEquals(31, tr1.get(0).getParagraphStyle().getCharactersCovered()); - - - // Write the slideshow out to a byte array - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ss.write(baos); - - // Build an input stream of it - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - - // Use POIFS to query that lot - POIFSFileSystem npfs = new POIFSFileSystem(bais); - - // Check that the "PowerPoint Document" sections have the same size - DocumentEntry oProps = (DocumentEntry)pfs.getRoot().getEntry("PowerPoint Document"); - DocumentEntry nProps = (DocumentEntry)npfs.getRoot().getEntry("PowerPoint Document"); - assertEquals(oProps.getSize(),nProps.getSize()); - - // Check that they contain the same data - byte[] _oData = new byte[oProps.getSize()]; - byte[] _nData = new byte[nProps.getSize()]; - pfs.createDocumentInputStream("PowerPoint Document").read(_oData); - npfs.createDocumentInputStream("PowerPoint Document").read(_nData); - for(int i=0; i<_oData.length; i++) { -// System.out.println(i + "\t" + Integer.toHexString(i) + "\t" + _oData[i]); - assertEquals(_oData[i], _nData[i]); - } - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/record/AllHSLFRecordTests.java b/src/scratchpad/testcases/org/apache/poi/hslf/record/AllHSLFRecordTests.java deleted file mode 100644 index 81bcefcb6..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/record/AllHSLFRecordTests.java +++ /dev/null @@ -1,70 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -/** - * Collects all tests from the package org.apache.poi.hslf.record. - * - * @author Josh Micich - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestAnimationInfoAtom.class, - TestCString.class, - TestColorSchemeAtom.class, - TestComment2000.class, - TestComment2000Atom.class, - TestCurrentUserAtom.class, - TestDocument.class, - TestDocumentAtom.class, - TestDocumentEncryptionAtom.class, - TestExControl.class, - TestExHyperlink.class, - TestExHyperlinkAtom.class, - TestExMediaAtom.class, - TestExObjList.class, - TestExObjListAtom.class, - TestExOleObjAtom.class, - TestExOleObjStg.class, - TestExVideoContainer.class, - TestFontCollection.class, - TestHeadersFootersAtom.class, - TestHeadersFootersContainer.class, - TestInteractiveInfo.class, - TestInteractiveInfoAtom.class, - TestNotesAtom.class, - TestRecordContainer.class, - TestRecordTypes.class, - TestSlideAtom.class, - TestSlidePersistAtom.class, - TestSound.class, - TestStyleTextPropAtom.class, - TestTextBytesAtom.class, - TestTextCharsAtom.class, - TestTextHeaderAtom.class, - TestTextRulerAtom.class, - TestTextSpecInfoAtom.class, - TestTxInteractiveInfoAtom.class, - TestTxMasterStyleAtom.class, - TestUserEditAtom.class -}) -public class AllHSLFRecordTests { -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestAnimationInfoAtom.java b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestAnimationInfoAtom.java deleted file mode 100644 index df3150c59..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestAnimationInfoAtom.java +++ /dev/null @@ -1,87 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - - -import static org.junit.Assert.assertArrayEquals; - -import java.io.ByteArrayOutputStream; - -import junit.framework.TestCase; - -/** - * Tests that {@link HeadersFootersAtom} works properly - * - * @author Yegor Kozlov - */ -public final class TestAnimationInfoAtom extends TestCase { - // From a real file - /* - - 00 00 00 07 04 05 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 - 00 00 00 - - */ - private final byte[] data = new byte[] { - 0x01, 0x00, (byte)0xF1, 0x0F, 0x1C, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x07, 0x04, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 - }; - - public void testRead() { - AnimationInfoAtom record = new AnimationInfoAtom(data, 0, data.length); - assertEquals(RecordTypes.AnimationInfoAtom.typeID, record.getRecordType()); - assertTrue(record.getFlag(AnimationInfoAtom.Automatic)); - assertTrue(record.getFlag(AnimationInfoAtom.Play)); - assertTrue(record.getFlag(AnimationInfoAtom.Synchronous)); - assertFalse(record.getFlag(AnimationInfoAtom.Reverse)); - assertFalse(record.getFlag(AnimationInfoAtom.Sound)); - assertFalse(record.getFlag(AnimationInfoAtom.StopSound)); - assertFalse(record.getFlag(AnimationInfoAtom.Hide)); - assertFalse(record.getFlag(AnimationInfoAtom.AnimateBg)); - assertEquals(0x07000000, record.getDimColor()); - assertEquals(0, record.getSoundIdRef()); - assertEquals(0, record.getDelayTime()); - assertEquals(2, record.getOrderID()); - assertEquals(0, record.getSlideCount()); - } - - public void testWrite() throws Exception { - AnimationInfoAtom record = new AnimationInfoAtom(data, 0, data.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - record.writeOut(baos); - byte[] b = baos.toByteArray(); - - assertArrayEquals(data, b); - } - - public void testNewRecord() throws Exception { - AnimationInfoAtom record = new AnimationInfoAtom(); - record.setDimColor(0x07000000); - record.setOrderID(2); - record.setFlag(AnimationInfoAtom.Automatic, true); - record.setFlag(AnimationInfoAtom.Play, true); - record.setFlag(AnimationInfoAtom.Synchronous, true); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - record.writeOut(baos); - byte[] b = baos.toByteArray(); - - assertArrayEquals(data, b); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestCString.java b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestCString.java deleted file mode 100644 index 4289c2771..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestCString.java +++ /dev/null @@ -1,111 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - - -import junit.framework.TestCase; -import java.io.ByteArrayOutputStream; - -/** - * Tests that CString works properly - * - * @author Nick Burch (nick at torchbox dot com) - */ -public final class TestCString extends TestCase { - // From a real file - private final byte[] data_a = new byte[] { 0, 0, 0xBA-256, 0x0f, 0x10, 0, 0, 0, - 0x48, 00, 0x6F, 00, 0x67, 00, 0x77, 00, - 0x61, 00, 0x72, 00, 0x74, 00, 0x73, 00 }; - private final byte[] data_b = new byte[] { 0x10, 0, 0xBA-256, 0x0f, 0x10, 0, 0, 0, - 0x43, 00, 0x6F, 00, 0x6D, 00, 0x6D, 00, - 0x65, 00, 0x6E, 00, 0x74, 00, 0x73, 00 }; - - public void testRecordType() { - CString ca = new CString(data_a, 0, data_a.length); - assertEquals(4026l, ca.getRecordType()); - CString cb = new CString(data_b, 0, data_a.length); - assertEquals(4026l, cb.getRecordType()); - } - public void testCount() { - CString ca = new CString(data_a, 0, data_a.length); - assertEquals(0, ca.getOptions()); - CString cb = new CString(data_b, 0, data_a.length); - assertEquals(0x10, cb.getOptions()); - - ca.setOptions(28); - assertEquals(28, ca.getOptions()); - } - - public void testText() { - CString ca = new CString(data_a, 0, data_a.length); - assertEquals("Hogwarts", ca.getText()); - CString cb = new CString(data_b, 0, data_a.length); - assertEquals("Comments", cb.getText()); - - ca.setText("FooBar"); - assertEquals("FooBar", ca.getText()); - } - - public void testWrite() throws Exception { - CString ca = new CString(data_a, 0, data_a.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ca.writeOut(baos); - byte[] b = baos.toByteArray(); - - assertEquals(data_a.length, b.length); - for(int i=0; i> 4); - assertTrue(ch[1] instanceof CString); - assertEquals(2, ((CString)ch[1]).getOptions() >> 4); - assertTrue(ch[2] instanceof Comment2000Atom); - - assertEquals("NESS", ca.getAuthor()); - assertEquals("N", ca.getAuthorInitials()); - assertNull(ca.getText()); //commentTextAtom is missing - } - -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestComment2000Atom.java b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestComment2000Atom.java deleted file mode 100644 index 05a3a671b..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestComment2000Atom.java +++ /dev/null @@ -1,172 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - - -import static org.junit.Assert.assertEquals; - -import java.io.ByteArrayOutputStream; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Locale; - -import org.apache.poi.util.LocaleUtil; -import org.junit.BeforeClass; -import org.junit.Test; - -/** - * Tests that Comment2000Atom works properly. - * - * @author Nick Burch (nick at torchbox dot com) - */ -public final class TestComment2000Atom { - // From a real file - private final byte[] data_a = new byte[] { - 00, 00, 0xE1-256, 0x2E, 0x1C, 00, 00, 00, - 01, 00, 00, 00, 0xD6-256, 07, 01, 00, - 02, 00, 0x18, 00, 0x0A, 00, 0x1A, 00, - 0x0F, 00, 0xCD-256, 00, 0x92-256, 00, - 00, 00, 0x92-256, 00, 00, 00 - }; - private final byte[] data_b = new byte[] { - 00, 00, 0xE1-256, 0x2E, 0x1C, 00, 00, 00, - 05, 00, 00, 00, 0xD6-256, 0x07, 01, 00, - 02, 00, 0x18, 00, 0x15, 00, 0x19, 00, 03, - 00, 0xD5-256, 02, 0x0A, 00, 00, 00, - 0x0E, 00, 00, 00 - }; - - private static SimpleDateFormat sdf; - - @BeforeClass - public static void initDateFormat() { - sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.ROOT); - sdf.setTimeZone(LocaleUtil.getUserTimeZone()); - } - - @Test - public void testRecordType() { - Comment2000Atom ca = new Comment2000Atom(data_a, 0, data_a.length); - assertEquals(12001l, ca.getRecordType()); - } - - @Test - public void testGetDate() throws Exception { - Comment2000Atom ca = new Comment2000Atom(data_a, 0, data_a.length); - Comment2000Atom cb = new Comment2000Atom(data_b, 0, data_b.length); - - // A is 2006-01-24 (2nd day of week) 10:26:15.205 - Date exp_a = sdf.parse("2006-01-24 10:26:15.205"); - // B is 2006-01-24 (2nd day of week) 21:25:03.725 - Date exp_b = sdf.parse("2006-01-24 21:25:03.725"); - - assertEquals(exp_a, ca.getDate()); - assertEquals(exp_b, cb.getDate()); - } - - @Test - public void testGetNums() { - Comment2000Atom ca = new Comment2000Atom(data_a, 0, data_a.length); - Comment2000Atom cb = new Comment2000Atom(data_b, 0, data_b.length); - - // A is number 1 - assertEquals(1, ca.getNumber()); - // B is number 5 - assertEquals(5, cb.getNumber()); - } - - @Test - public void testGetPos() { - Comment2000Atom ca = new Comment2000Atom(data_a, 0, data_a.length); - Comment2000Atom cb = new Comment2000Atom(data_b, 0, data_b.length); - - // A is at 0x92, 0x92 - assertEquals(0x92, ca.getXOffset()); - assertEquals(0x92, ca.getYOffset()); - - // B is at 0x0A, 0x0E - assertEquals(0x0A, cb.getXOffset()); - assertEquals(0x0E, cb.getYOffset()); - } - - @Test - public void testWrite() throws Exception { - Comment2000Atom ca = new Comment2000Atom(data_a, 0, data_a.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ca.writeOut(baos); - byte[] b = baos.toByteArray(); - - assertEquals(data_a.length, b.length); - for(int i=0; i= 0; i--) { - if (r[i] instanceof Document) { - return (Document) r[i]; - } - } - throw new IllegalStateException("No Document record found"); - } - - public void testRecordType() { - Document dr = getDocRecord(); - assertEquals(1000, dr.getRecordType()); - } - - public void testChildRecords() { - Document dr = getDocRecord(); - assertNotNull(dr.getDocumentAtom()); - - assertNotNull(dr.getEnvironment()); - - assertNotNull(dr.getSlideListWithTexts()); - assertEquals(3, dr.getSlideListWithTexts().length); - assertNotNull(dr.getSlideListWithTexts()[0]); - assertNotNull(dr.getSlideListWithTexts()[1]); - assertNotNull(dr.getSlideListWithTexts()[2]); - } - - public void testEnvironment() { - Document dr = getDocRecord(); - Environment env = dr.getEnvironment(); - - assertEquals(1010, env.getRecordType()); - assertNotNull(env.getFontCollection()); - } - - // No need to check re-writing - hslf.TestReWrite does all that for us -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestDocumentAtom.java b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestDocumentAtom.java deleted file mode 100644 index 40f4cd787..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestDocumentAtom.java +++ /dev/null @@ -1,80 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - - -import junit.framework.TestCase; -import java.io.ByteArrayOutputStream; - -/** - * Tests that DocumentAtom works properly - * - * @author Nick Burch (nick at torchbox dot com) - */ -public final class TestDocumentAtom extends TestCase { - // From a real file - private final byte[] data_a = new byte[] { 1, 0, 0xE9-256, 3, 0x28, 0, 0, 0, - 0x80-256, 0x16, 0, 0, 0xE0-256, 0x10, 0, 0, - 0xE0-256, 0x10, 0, 0, 0x80-256, 0x16, 0, 0, - 0x05, 0, 0, 0, 0x0A, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, - 1, 0, 0, 0, 0, 0, 0, 1 }; - - public void testRecordType() { - DocumentAtom da = new DocumentAtom(data_a, 0, data_a.length); - assertEquals(1001l, da.getRecordType()); - } - public void testSizeAndZoom() { - DocumentAtom da = new DocumentAtom(data_a, 0, data_a.length); - assertEquals(5760l, da.getSlideSizeX()); - assertEquals(4320l, da.getSlideSizeY()); - assertEquals(4320l, da.getNotesSizeX()); - assertEquals(5760l, da.getNotesSizeY()); - - assertEquals(5l, da.getServerZoomFrom()); - assertEquals(10l, da.getServerZoomTo()); - } - public void testMasterPersist() { - DocumentAtom da = new DocumentAtom(data_a, 0, data_a.length); - assertEquals(2l, da.getNotesMasterPersist()); - assertEquals(0l, da.getHandoutMasterPersist()); - } - public void testSlideDetails() { - DocumentAtom da = new DocumentAtom(data_a, 0, data_a.length); - assertEquals(1, da.getFirstSlideNum()); - assertEquals(0, da.getSlideSizeType()); - } - public void testBooleans() { - DocumentAtom da = new DocumentAtom(data_a, 0, data_a.length); - assertEquals(false, da.getSaveWithFonts()); - assertEquals(false, da.getOmitTitlePlace()); - assertEquals(false, da.getRightToLeft()); - assertEquals(true, da.getShowComments()); - } - - public void testWrite() throws Exception { - DocumentAtom da = new DocumentAtom(data_a, 0, data_a.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - da.writeOut(baos); - byte[] b = baos.toByteArray(); - - assertEquals(data_a.length, b.length); - for(int i=0; i picsExpected = hss.getPictureData(); - hss.getDocumentSummaryInformation(); - EncryptionInfo ei = hss.getDocumentEncryptionAtom().getEncryptionInfo(); - ((CryptoAPIEncryptionHeader)ei.getHeader()).setKeySize(0x78); - - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - hss.write(bos); - hss.close(); - fs.close(); - - fs = new NPOIFSFileSystem(new ByteArrayInputStream(bos.toByteArray())); - hss = new HSLFSlideShowImpl(fs); - List picsActual = hss.getPictureData(); - - assertEquals(picsExpected.size(), picsActual.size()); - for (int i=0; i - - 00 01 00 00 - - - 01 00 00 00 02 00 00 00 01 00 00 00 00 00 00 00 02 00 00 00 00 96 13 00 - - - 53 00 68 00 6F 00 63 00 6B 00 77 00 61 00 76 00 65 00 20 00 46 00 6C 00 61 - 00 73 00 68 00 20 00 4F 00 62 00 6A 00 65 00 63 00 74 00 - - - 53 00 68 00 6F 00 63 00 6B 00 77 00 61 00 76 00 65 00 46 00 6C 00 61 00 73 - 00 68 00 2E 00 53 00 68 00 6F 00 63 00 6B 00 77 00 61 00 76 00 65 00 46 00 - 6C 00 61 00 73 00 68 00 2E 00 39 00 - - - 53 00 68 00 6F 00 63 00 6B 00 77 00 61 00 76 00 65 00 20 00 46 00 6C 00 61 - 00 73 00 68 00 20 00 4F 00 62 00 6A 00 65 00 63 00 74 00 - - - */ - private final byte[] data = new byte[] { - 0x0F, 0x00, (byte)0xEE, 0x0F, (byte)0xDA, 0x00, 0x00, 0x00, 0x00, 0x00, (byte)0xFB, 0x0F, 0x04, 0x00, 0x00, 0x00, - 0x00, 0x01, 0x00, 0x00, 0x01, 0x00, (byte)0xC3, 0x0F, 0x18, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, - 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, (byte)0x96, 0x13, 0x00, - 0x10, 0x00, (byte)0xBA, 0x0F, 0x2C, 0x00, 0x00, 0x00, 0x53, 0x00, 0x68, 0x00, 0x6F, 0x00, 0x63, 0x00, 0x6B, 0x00, - 0x77, 0x00, 0x61, 0x00, 0x76, 0x00, 0x65, 0x00, 0x20, 0x00, 0x46, 0x00, 0x6C, 0x00, 0x61, 0x00, 0x73, 0x00, 0x68, - 0x00, 0x20, 0x00, 0x4F, 0x00, 0x62, 0x00, 0x6A, 0x00, 0x65, 0x00, 0x63, 0x00, 0x74, 0x00, 0x20, 0x00, (byte)0xBA, - 0x0F, 0x3E, 0x00, 0x00, 0x00, 0x53, 0x00, 0x68, 0x00, 0x6F, 0x00, 0x63, 0x00, 0x6B, 0x00, 0x77, 0x00, 0x61, 0x00, - 0x76, 0x00, 0x65, 0x00, 0x46, 0x00, 0x6C, 0x00, 0x61, 0x00, 0x73, 0x00, 0x68, 0x00, 0x2E, 0x00, 0x53, 0x00, 0x68, - 0x00, 0x6F, 0x00, 0x63, 0x00, 0x6B, 0x00, 0x77, 0x00, 0x61, 0x00, 0x76, 0x00, 0x65, 0x00, 0x46, 0x00, 0x6C, 0x00, - 0x61, 0x00, 0x73, 0x00, 0x68, 0x00, 0x2E, 0x00, 0x39, 0x00, 0x30, 0x00, (byte)0xBA, 0x0F, 0x2C, 0x00, 0x00, 0x00, - 0x53, 0x00, 0x68, 0x00, 0x6F, 0x00, 0x63, 0x00, 0x6B, 0x00, 0x77, 0x00, 0x61, 0x00, 0x76, 0x00, 0x65, 0x00, 0x20, - 0x00, 0x46, 0x00, 0x6C, 0x00, 0x61, 0x00, 0x73, 0x00, 0x68, 0x00, 0x20, 0x00, 0x4F, 0x00, 0x62, 0x00, 0x6A, 0x00, - 0x65, 0x00, 0x63, 0x00, 0x74, 0x00 - }; - - public void testRead() { - ExControl record = new ExControl(data, 0, data.length); - assertEquals(RecordTypes.ExControl.typeID, record.getRecordType()); - - assertNotNull(record.getExControlAtom()); - assertEquals(256, record.getExControlAtom().getSlideId()); - - ExOleObjAtom oleObj = record.getExOleObjAtom(); - assertNotNull(oleObj); - assertEquals(oleObj.getDrawAspect(), ExOleObjAtom.DRAW_ASPECT_VISIBLE); - assertEquals(oleObj.getType(), ExOleObjAtom.TYPE_CONTROL); - assertEquals(oleObj.getSubType(), ExOleObjAtom.SUBTYPE_DEFAULT); - - assertEquals("Shockwave Flash Object", record.getMenuName()); - assertEquals("ShockwaveFlash.ShockwaveFlash.9", record.getProgId()); - assertEquals("Shockwave Flash Object", record.getClipboardName()); - } - - public void testWrite() throws Exception { - ExControl record = new ExControl(data, 0, data.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - record.writeOut(baos); - byte[] b = baos.toByteArray(); - - assertArrayEquals(data, b); - } - - public void testNewRecord() throws Exception { - ExControl record = new ExControl(); - ExControlAtom ctrl = record.getExControlAtom(); - ctrl.setSlideId(256); - - ExOleObjAtom oleObj = record.getExOleObjAtom(); - oleObj.setDrawAspect(ExOleObjAtom.DRAW_ASPECT_VISIBLE); - oleObj.setType(ExOleObjAtom.TYPE_CONTROL); - oleObj.setObjID(1); - oleObj.setSubType(ExOleObjAtom.SUBTYPE_DEFAULT); - oleObj.setObjStgDataRef(2); - oleObj.setOptions(1283584); - - record.setMenuName("Shockwave Flash Object"); - record.setProgId("ShockwaveFlash.ShockwaveFlash.9"); - record.setClipboardName("Shockwave Flash Object"); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - record.writeOut(baos); - byte[] b = baos.toByteArray(); - - assertEquals(data.length, b.length); - assertArrayEquals(data, b); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestExHyperlink.java b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestExHyperlink.java deleted file mode 100644 index dfd840b1b..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestExHyperlink.java +++ /dev/null @@ -1,149 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - - -import java.io.ByteArrayOutputStream; -import java.util.ArrayList; -import java.util.List; - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -import org.apache.poi.hslf.usermodel.HSLFSlideShow; -import org.apache.poi.hslf.usermodel.HSLFSlideShowImpl; -import org.apache.poi.POIDataSamples; - -/** - * Tests that ExHyperlink works properly. - * - * @author Nick Burch (nick at torchbox dot com) - */ -public final class TestExHyperlink extends TestCase { - // From a real file - private final byte[] data_a = new byte[] { - 0x0F, 00, 0xD7-256, 0x0F, 0xA8-256, 00, 00, 00, - - 00, 00, 0xD3-256, 0x0F, 04, 00, 00, 00, - 03, 00, 00, 00, - - 00, 00, 0xBA-256, 0x0F, 0x46, 00, 00, 00, - 0x68, 00, 0x74, 00, 0x74, 00, 0x70, 00, - 0x3A, 00, 0x2F, 00, 0x2F, 00, 0x6A, 00, - 0x61, 00, 0x6B, 00, 0x61, 00, 0x72, 00, - 0x74, 00, 0x61, 00, 0x2E, 00, 0x61, 00, - 0x70, 00, 0x61, 00, 0x63, 00, 0x68, 00, - 0x65, 00, 0x2E, 00, 0x6F, 00, 0x72, 00, - 0x67, 00, 0x2F, 00, 0x70, 00, 0x6F, 00, - 0x69, 00, 0x2F, 00, 0x68, 00, 0x73, 00, - 0x73, 00, 0x66, 00, 0x2F, 00, - - 0x10, 00, 0xBA-256, 0x0F, 0x46, 00, 00, 00, - 0x68, 00, 0x74, 00, 0x74, 00, 0x70, 00, - 0x3A, 00, 0x2F, 00, 0x2F, 00, 0x6A, 00, - 0x61, 00, 0x6B, 00, 0x61, 00, 0x72, 00, - 0x74, 00, 0x61, 00, 0x2E, 00, 0x61, 00, - 0x70, 00, 0x61, 00, 0x63, 00, 0x68, 00, - 0x65, 00, 0x2E, 00, 0x6F, 00, 0x72, 00, - 0x67, 00, 0x2F, 00, 0x70, 00, 0x6F, 00, - 0x69, 00, 0x2F, 00, 0x68, 00, 0x73, 00, - 0x73, 00, 0x66, 00, 0x2F, 00 - }; - - public void testRecordType() { - ExHyperlink eh = new ExHyperlink(data_a, 0, data_a.length); - assertEquals(4055l, eh.getRecordType()); - } - - public void testNumber() { - ExHyperlink eh = new ExHyperlink(data_a, 0, data_a.length); - assertEquals(3, eh.getExHyperlinkAtom().getNumber()); - } - - public void testLinkURL() { - ExHyperlink eh = new ExHyperlink(data_a, 0, data_a.length); - assertEquals("http://jakarta.apache.org/poi/hssf/", eh.getLinkURL()); - } - public void testDetails() { - ExHyperlink eh = new ExHyperlink(data_a, 0, data_a.length); - assertEquals("http://jakarta.apache.org/poi/hssf/", eh._getDetailsA()); - assertEquals("http://jakarta.apache.org/poi/hssf/", eh._getDetailsB()); - } - - public void testWrite() throws Exception { - ExHyperlink eh = new ExHyperlink(data_a, 0, data_a.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - eh.writeOut(baos); - byte[] b = baos.toByteArray(); - - assertEquals(data_a.length, b.length); - for(int i=0; i linksA = new ArrayList(); - for (Record ch : exObjList._children) { - if(ch instanceof ExHyperlink) { - linksA.add((ExHyperlink) ch); - } - } - - // Should be 4 of them - assertEquals(4, linksA.size()); - ExHyperlink[] links = new ExHyperlink[linksA.size()]; - linksA.toArray(links); - - assertEquals(4, exObjList.getExHyperlinks().length); - - // Check the other way - - // Check they have what we expect in them - assertEquals(1, links[0].getExHyperlinkAtom().getNumber()); - assertEquals("http://jakarta.apache.org/poi/", links[0].getLinkURL()); - - assertEquals(2, links[1].getExHyperlinkAtom().getNumber()); - assertEquals("http://slashdot.org/", links[1].getLinkURL()); - - assertEquals(3, links[2].getExHyperlinkAtom().getNumber()); - assertEquals("http://jakarta.apache.org/poi/hssf/", links[2].getLinkURL()); - - assertEquals(4, links[3].getExHyperlinkAtom().getNumber()); - assertEquals("http://jakarta.apache.org/hslf/", links[3].getLinkURL()); - - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestExHyperlinkAtom.java b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestExHyperlinkAtom.java deleted file mode 100644 index eba79e05a..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestExHyperlinkAtom.java +++ /dev/null @@ -1,101 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - - -import junit.framework.TestCase; -import java.io.ByteArrayOutputStream; - -/** - * Tests that ExHyperlinkAtom works properly. - * - * @author Nick Burch (nick at torchbox dot com) - */ -public class TestExHyperlinkAtom extends TestCase { - // From a real file - private final byte[] data_a = new byte[] { - 00, 00, 0xD3-256, 0x0F, 04, 00, 00, 00, - 01, 00, 00, 00 - }; - private final byte[] data_b = new byte[] { - 00, 00, 0xD3-256, 0x0F, 04, 00, 00, 00, - 04, 00, 00, 00 - }; - - public void testRecordType() { - ExHyperlinkAtom eha = new ExHyperlinkAtom(data_a, 0, data_a.length); - assertEquals(4051l, eha.getRecordType()); - } - - public void testGetNumber() { - ExHyperlinkAtom eha = new ExHyperlinkAtom(data_a, 0, data_a.length); - ExHyperlinkAtom ehb = new ExHyperlinkAtom(data_b, 0, data_b.length); - - assertEquals(1, eha.getNumber()); - assertEquals(4, ehb.getNumber()); - } - - public void testWrite() throws Exception { - ExHyperlinkAtom eha = new ExHyperlinkAtom(data_a, 0, data_a.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - eha.writeOut(baos); - byte[] b = baos.toByteArray(); - - assertEquals(data_a.length, b.length); - for(int i=0; i.... - private static byte[] data; - - @BeforeClass - public static void init() throws IOException { - data = org.apache.poi.poifs.storage.RawDataUtil.decompress( - "H4sIAAAAAAAAAAFjAZz+EAAREFsBAAAADgAAeJy7cF7wwcKNUg8Z0IAdAzPDv/+cDGxIYoxAzATjCDAwsEDF/"+ - "v3//x8kxAzE/0fBkAJBDPlAWMKgwODKkAekixgq0ZMCXiDGwAqPc1BayLtdcyl33XnBaTtcXINDUNUGvEgvK2"+ - "Y4ycgOZDswQsScgbaD7E0Fk8Uk2Q0CQgxMjMj+IVafAiPJVuEE5NhPTUCJ/aC8+xdLuvgHxaNgeAN65v8JZ1k"+ - "bQfmflWE0/1MTUGI/TB+sHBjN9yMLwNp0oLYbqD03GvcjC6SHpoUKABtkbzghmAPawudgkAGSaQw5DGUMBUAy"+ - "EVgvpAJrBz1gGV0OFCdOBR+QDGfIBJbtKcByvhzI4wbj//85GLiALA+gXDpDBlgtqKfhwxACl4e4AuYaYHeDI"+ - "RioEmSKI9C2HLhZyKqQ9fBilHXcwN4KN1wdM1Q1iJcINZGDgQfsJxC/GOib4Q8AvWU91AJ49g1jAQAA" - ); - } - - @Test - public void testRead() throws Exception { - ExOleObjStg record = new ExOleObjStg(data, 0, data.length); - assertEquals(RecordTypes.ExOleObjStg.typeID, record.getRecordType()); - - int len = record.getDataLength(); - byte[] oledata = readAll(record.getData()); - assertEquals(len, oledata.length); - - POIFSFileSystem fs = new POIFSFileSystem(record.getData()); - assertTrue("Constructed POIFS from ExOleObjStg data", true); - DocumentEntry doc = (DocumentEntry)fs.getRoot().getEntry("Contents"); - assertNotNull(doc); - assertTrue("Fetched the Contents stream containing OLE properties", true); - fs.close(); - } - - @Test - public void testWrite() throws Exception { - ExOleObjStg record = new ExOleObjStg(data, 0, data.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - record.writeOut(baos); - byte[] b = baos.toByteArray(); - - assertArrayEquals(data, b); - } - - @Test - public void testNewRecord() throws Exception { - ExOleObjStg src = new ExOleObjStg(data, 0, data.length); - byte[] oledata = readAll(src.getData()); - - ExOleObjStg tgt = new ExOleObjStg(); - tgt.setData(oledata); - - - assertEquals(src.getDataLength(), tgt.getDataLength()); - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - tgt.writeOut(out); - byte[] b = out.toByteArray(); - - assertEquals(data.length, b.length); - assertArrayEquals(data, b); - } - - private byte[] readAll(InputStream is) throws IOException { - int pos; - byte[] chunk = new byte[1024]; - ByteArrayOutputStream out = new ByteArrayOutputStream(); - while((pos = is.read(chunk)) > 0){ - out.write(chunk, 0, pos); - } - return out.toByteArray(); - - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestExVideoContainer.java b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestExVideoContainer.java deleted file mode 100644 index 10dc9404c..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestExVideoContainer.java +++ /dev/null @@ -1,89 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - - -import static org.junit.Assert.assertArrayEquals; - -import java.io.ByteArrayOutputStream; - -import junit.framework.TestCase; - -/** - * Tests that {@link HeadersFootersAtom} works properly - * - * @author Yegor Kozlov - */ -public final class TestExVideoContainer extends TestCase { - - // From a real file - private final byte[] data = new byte[]{ - 0x0F, 0x00, 0x05, 0x10, (byte) 0x9E, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x04, 0x10, 0x08, 0x00, 0x00, 0x00, - 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, (byte)0xBA, 0x0F, (byte)0x86, 0x00, 0x00, 0x00, - 0x44, 0x00, 0x3A, 0x00, 0x5C, 0x00, 0x70, 0x00, 0x72, 0x00, 0x6F, 0x00, 0x6A, 0x00, 0x65, 0x00, - 0x63, 0x00, 0x74, 0x00, 0x73, 0x00, 0x5C, 0x00, 0x53, 0x00, 0x63, 0x00, 0x68, 0x00, 0x75, 0x00, - 0x6C, 0x00, 0x65, 0x00, 0x72, 0x00, 0x41, 0x00, 0x47, 0x00, 0x5C, 0x00, 0x6D, 0x00, 0x63, 0x00, - 0x6F, 0x00, 0x6D, 0x00, 0x5F, 0x00, 0x76, 0x00, 0x5F, 0x00, 0x31, 0x00, 0x5F, 0x00, 0x30, 0x00, - 0x5F, 0x00, 0x34, 0x00, 0x5C, 0x00, 0x76, 0x00, 0x69, 0x00, 0x65, 0x00, 0x77, 0x00, 0x5C, 0x00, - 0x64, 0x00, 0x61, 0x00, 0x74, 0x00, 0x61, 0x00, 0x5C, 0x00, 0x74, 0x00, 0x65, 0x00, 0x73, 0x00, - 0x74, 0x00, 0x73, 0x00, 0x5C, 0x00, 0x69, 0x00, 0x6D, 0x00, 0x61, 0x00, 0x67, 0x00, 0x65, 0x00, - 0x73, 0x00, 0x5C, 0x00, 0x63, 0x00, 0x61, 0x00, 0x72, 0x00, 0x64, 0x00, 0x73, 0x00, 0x2E, 0x00, - 0x6D, 0x00, 0x70, 0x00, 0x67, 0x00}; - - - - - public void testRead() { - ExVideoContainer record = new ExVideoContainer(data, 0, data.length); - assertEquals(RecordTypes.ExVideoContainer.typeID, record.getRecordType()); - - ExMediaAtom exMedia = record.getExMediaAtom(); - assertEquals(1, exMedia.getObjectId()); - assertNotNull(exMedia); - assertFalse(exMedia.getFlag(ExMediaAtom.fLoop)); - assertFalse(exMedia.getFlag(ExMediaAtom.fNarration)); - assertFalse(exMedia.getFlag(ExMediaAtom.fRewind)); - - CString path = record.getPathAtom(); - assertNotNull(exMedia); - assertEquals("D:\\projects\\SchulerAG\\mcom_v_1_0_4\\view\\data\\tests\\images\\cards.mpg", path.getText()); - } - - public void testWrite() throws Exception { - ExVideoContainer record = new ExVideoContainer(data, 0, data.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - record.writeOut(baos); - byte[] b = baos.toByteArray(); - - assertArrayEquals(data, b); - } - - public void testNewRecord() throws Exception { - ExVideoContainer record = new ExVideoContainer(); - record.getExMediaAtom().setObjectId(1); - record.getPathAtom().setText("D:\\projects\\SchulerAG\\mcom_v_1_0_4\\view\\data\\tests\\images\\cards.mpg"); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - record.writeOut(baos); - byte[] b = baos.toByteArray(); - - assertArrayEquals(data, b); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestFontCollection.java b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestFontCollection.java deleted file mode 100644 index 2d595f332..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestFontCollection.java +++ /dev/null @@ -1,82 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - -import static org.junit.Assert.assertArrayEquals; - -import java.io.ByteArrayOutputStream; - -import junit.framework.TestCase; - -/** - * Tests FontCollection and FontEntityAtom records - * - * @author Yegor Kozlov - */ -public final class TestFontCollection extends TestCase { - // From a real file - private final byte[] data = new byte[] { - 0x0F, 0x00, 0xD5-256, 0x07, 0x4C, 0x00, 0x00, 0x00, - 0x00, 0x00, 0xB7-256, 0x0F, 0x44, 0x00, 0x00, 0x00, - 0x54, 0x00, 0x69, 0x00, 0x6D, 0x00, 0x65, 0x00, 0x73, 0x00, - 0x20, 0x00, 0x4E, 0x00, 0x65, 0x00, 0x77, 0x00, 0x20, 0x00, - 0x52, 0x00, 0x6F, 0x00, 0x6D, 0x00, 0x61, 0x00, 0x6E, 0x00, - 0x00, 0x00, 0x74, 0x34, 0xB8-256, 0x00, 0x7C, 0xDA-256, 0x12, 0x00, - 0x64, 0xDA-256, 0x12, 0x00, 0x76, 0xC7-256, 0x0B, 0x30, 0x08, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0xDA-256, 0x12, 0x00, - 0x28, 0xDD-256, 0x0D, 0x30, 0x00, 0x00, 0x04, 0x00 }; - - public void testFonts() { - FontCollection fonts = new FontCollection(data, 0, data.length); - Record[] child = fonts.getChildRecords(); - assertEquals(child.length, 1); - - FontEntityAtom fnt = (FontEntityAtom)child[0]; - assertEquals(fnt.getFontName(), "Times New Roman"); - } - - public void testAddFont() { - FontCollection fonts = new FontCollection(data, 0, data.length); - int idx = fonts.addFont("Times New Roman"); - assertEquals(idx, 0); - idx = fonts.addFont("Helvetica"); - assertEquals(idx, 1); - idx = fonts.addFont("Arial"); - assertEquals(idx, 2); - idx = fonts.addFont("Arial"); //the font being added twice - assertEquals(idx, 2); - - // Font collection should contain 3 fonts - Record[] child = fonts.getChildRecords(); - assertEquals(child.length, 3); - - // Check we get the right font name for the indicies - assertEquals("Times New Roman", fonts.getFontWithId(0)); - assertEquals("Helvetica", fonts.getFontWithId(1)); - assertEquals("Arial", fonts.getFontWithId(2)); - assertNull(fonts.getFontWithId(3)); - } - - public void testWrite() throws Exception { - FontCollection fonts = new FontCollection(data, 0, data.length); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - fonts.writeOut(out); - byte[] recdata = out.toByteArray(); - assertArrayEquals(recdata, data); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestHeadersFootersAtom.java b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestHeadersFootersAtom.java deleted file mode 100644 index c694b90d4..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestHeadersFootersAtom.java +++ /dev/null @@ -1,93 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - - -import static org.junit.Assert.assertArrayEquals; - -import java.io.ByteArrayOutputStream; - -import junit.framework.TestCase; - -/** - * Tests that {@link HeadersFootersAtom} works properly - * - * @author Yegor Kozlov - */ -public final class TestHeadersFootersAtom extends TestCase { - // From a real file - private final byte[] data = new byte[] { - 0x00, 0x00, (byte)0xDA, 0x0F, 0x04, 0x00, 0x00, 00, - 0x00, 0x00, 0x23, 0x00 }; - - public void testRead() { - HeadersFootersAtom record = new HeadersFootersAtom(data, 0, data.length); - assertEquals(RecordTypes.HeadersFootersAtom.typeID, record.getRecordType()); - - assertEquals(0, record.getFormatId()); - assertEquals(0x23, record.getMask()); - - assertTrue(record.getFlag(HeadersFootersAtom.fHasDate)); - assertTrue(record.getFlag(HeadersFootersAtom.fHasTodayDate)); - assertFalse(record.getFlag(HeadersFootersAtom.fHasUserDate)); - assertFalse(record.getFlag(HeadersFootersAtom.fHasSlideNumber)); - assertFalse(record.getFlag(HeadersFootersAtom.fHasHeader)); - assertTrue(record.getFlag(HeadersFootersAtom.fHasFooter)); - } - - public void testWrite() throws Exception { - HeadersFootersAtom record = new HeadersFootersAtom(data, 0, data.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - record.writeOut(baos); - byte[] b = baos.toByteArray(); - - assertArrayEquals(data, b); - } - - public void testNewRecord() throws Exception { - HeadersFootersAtom record = new HeadersFootersAtom(); - record.setFlag(HeadersFootersAtom.fHasDate, true); - record.setFlag(HeadersFootersAtom.fHasTodayDate, true); - record.setFlag(HeadersFootersAtom.fHasFooter, true); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - record.writeOut(baos); - byte[] b = baos.toByteArray(); - - assertArrayEquals(data, b); - } - - public void testFlags() { - HeadersFootersAtom record = new HeadersFootersAtom(); - - //in a new record all the bits are 0 - for(int i = 0; i < 6; i++) assertFalse(record.getFlag(1 << i)); - - record.setFlag(HeadersFootersAtom.fHasTodayDate, true); - assertTrue(record.getFlag(HeadersFootersAtom.fHasTodayDate)); - - record.setFlag(HeadersFootersAtom.fHasTodayDate, true); - assertTrue(record.getFlag(HeadersFootersAtom.fHasTodayDate)); - - record.setFlag(HeadersFootersAtom.fHasTodayDate, false); - assertFalse(record.getFlag(HeadersFootersAtom.fHasTodayDate)); - - record.setFlag(HeadersFootersAtom.fHasTodayDate, false); - assertFalse(record.getFlag(HeadersFootersAtom.fHasTodayDate)); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestHeadersFootersContainer.java b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestHeadersFootersContainer.java deleted file mode 100644 index 6e787e7c8..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestHeadersFootersContainer.java +++ /dev/null @@ -1,170 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - - -import static org.junit.Assert.assertArrayEquals; - -import java.io.ByteArrayOutputStream; - -import junit.framework.TestCase; - -/** - * Tests that {@link HeadersFootersContainer} works properly - * - * @author Yegor Kozlov - */ -public final class TestHeadersFootersContainer extends TestCase { - // SlideHeadersFootersContainer - private final byte[] slideData = new byte[] { - 0x3F, 0x00, (byte)0xD9, 0x0F, 0x2E, 0x00, 0x00, 0x00, - 0x00, 0x00, (byte)0xDA, 0x0F, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x23, 0x00, - 0x20, 0x00, (byte)0xBA, 0x0F, 0x1A, 0x00, 0x00, 0x00, - 0x4D, 0x00, 0x79, 0x00, 0x20, 0x00, 0x46, 0x00, 0x6F, 0x00, 0x6F, 0x00, 0x74, - 0x00, 0x65, 0x00, 0x72, 0x00, 0x20, 0x00, 0x2D, 0x00, 0x20, 0x00, 0x31, 0x00 - - }; - - // NotesHeadersFootersContainer - private final byte[] notesData = new byte[] { - 0x4F, 0x00, (byte)0xD9, 0x0F, 0x48, 0x00, 0x00, 0x00, - 0x00, 0x00, (byte)0xDA, 0x0F, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3D, 0x00, - 0x10, 0x00, (byte)0xBA, 0x0F, 0x16, 0x00, 0x00, 0x00, - 0x4E, 0x00, 0x6F, 0x00, 0x74, 0x00, 0x65, 0x00, 0x20, 0x00, 0x48, 0x00, - 0x65, 0x00, 0x61, 0x00, 0x64, 0x00, 0x65, 0x00, 0x72, 0x00, - 0x20, 0x00, (byte)0xBA, 0x0F, 0x16, 0x00, 0x00, 0x00, - 0x4E, 0x00, 0x6F, 0x00, 0x74, 0x00, 0x65, 0x00, 0x20, 0x00, 0x46, 0x00, - 0x6F, 0x00, 0x6F, 0x00, 0x74, 0x00, 0x65, 0x00, 0x72, 0x00 - }; - - public void testReadSlideHeadersFootersContainer() { - HeadersFootersContainer record = new HeadersFootersContainer(slideData, 0, slideData.length); - assertEquals(RecordTypes.HeadersFooters.typeID, record.getRecordType()); - assertEquals(HeadersFootersContainer.SlideHeadersFootersContainer, record.getOptions()); - assertEquals(2, record.getChildRecords().length); - - HeadersFootersAtom hdd = record.getHeadersFootersAtom(); - assertNotNull(hdd); - - CString csFooter = record.getFooterAtom(); - assertNotNull(csFooter); - assertEquals(HeadersFootersContainer.FOOTERATOM, csFooter.getOptions() >> 4); - - assertEquals("My Footer - 1", csFooter.getText()); - - assertNull(record.getUserDateAtom()); - assertNull(record.getHeaderAtom()); - } - - public void testWriteSlideHeadersFootersContainer() throws Exception { - HeadersFootersContainer record = new HeadersFootersContainer(slideData, 0, slideData.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - record.writeOut(baos); - byte[] b = baos.toByteArray(); - - assertArrayEquals(slideData, b); - } - - public void testNewSlideHeadersFootersContainer() throws Exception { - HeadersFootersContainer record = new HeadersFootersContainer(HeadersFootersContainer.SlideHeadersFootersContainer); - - assertNotNull(record.getHeadersFootersAtom()); - assertNull(record.getUserDateAtom()); - assertNull(record.getHeaderAtom()); - assertNull(record.getFooterAtom()); - - HeadersFootersAtom hd = record.getHeadersFootersAtom(); - hd.setFlag(HeadersFootersAtom.fHasDate, true); - hd.setFlag(HeadersFootersAtom.fHasTodayDate, true); - hd.setFlag(HeadersFootersAtom.fHasFooter, true); - - CString csFooter = record.addFooterAtom(); - assertNotNull(csFooter); - assertEquals(HeadersFootersContainer.FOOTERATOM, csFooter.getOptions() >> 4); - csFooter.setText("My Footer - 1"); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - record.writeOut(baos); - byte[] b = baos.toByteArray(); - - assertArrayEquals(slideData, b); - } - - public void testReadNotesHeadersFootersContainer() { - HeadersFootersContainer record = new HeadersFootersContainer(notesData, 0, notesData.length); - assertEquals(RecordTypes.HeadersFooters.typeID, record.getRecordType()); - assertEquals(HeadersFootersContainer.NotesHeadersFootersContainer, record.getOptions()); - assertEquals(3, record.getChildRecords().length); - - HeadersFootersAtom hdd = record.getHeadersFootersAtom(); - assertNotNull(hdd); - - CString csHeader = record.getHeaderAtom(); - assertNotNull(csHeader); - assertEquals(HeadersFootersContainer.HEADERATOM, csHeader.getOptions() >> 4); - assertEquals("Note Header", csHeader.getText()); - - CString csFooter = record.getFooterAtom(); - assertNotNull(csFooter); - assertEquals(HeadersFootersContainer.FOOTERATOM, csFooter.getOptions() >> 4); - assertEquals("Note Footer", csFooter.getText()); - } - - public void testWriteNotesHeadersFootersContainer() throws Exception { - HeadersFootersContainer record = new HeadersFootersContainer(notesData, 0, notesData.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - record.writeOut(baos); - byte[] b = baos.toByteArray(); - - assertArrayEquals(notesData, b); - } - - public void testNewNotesHeadersFootersContainer() throws Exception { - HeadersFootersContainer record = new HeadersFootersContainer(HeadersFootersContainer.NotesHeadersFootersContainer); - - assertNotNull(record.getHeadersFootersAtom()); - assertNull(record.getUserDateAtom()); - assertNull(record.getHeaderAtom()); - assertNull(record.getFooterAtom()); - - HeadersFootersAtom hd = record.getHeadersFootersAtom(); - hd.setFlag(HeadersFootersAtom.fHasDate, true); - hd.setFlag(HeadersFootersAtom.fHasTodayDate, false); - hd.setFlag(HeadersFootersAtom.fHasUserDate, true); - hd.setFlag(HeadersFootersAtom.fHasSlideNumber, true); - hd.setFlag(HeadersFootersAtom.fHasHeader, true); - hd.setFlag(HeadersFootersAtom.fHasFooter, true); - - CString csHeader = record.addHeaderAtom(); - assertNotNull(csHeader); - assertEquals(HeadersFootersContainer.HEADERATOM, csHeader.getOptions() >> 4); - csHeader.setText("Note Header"); - - CString csFooter = record.addFooterAtom(); - assertNotNull(csFooter); - assertEquals(HeadersFootersContainer.FOOTERATOM, csFooter.getOptions() >> 4); - csFooter.setText("Note Footer"); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - record.writeOut(baos); - byte[] b = baos.toByteArray(); - - assertArrayEquals(notesData, b); - } - -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestInteractiveInfo.java b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestInteractiveInfo.java deleted file mode 100644 index 24278fa14..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestInteractiveInfo.java +++ /dev/null @@ -1,87 +0,0 @@ - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - - - -package org.apache.poi.hslf.record; - - -import java.io.ByteArrayOutputStream; - -import junit.framework.TestCase; - -/** - * Tests that InteractiveInfoAtom works properly. - * - * @author Nick Burch (nick at torchbox dot com) - */ -public class TestInteractiveInfo extends TestCase { - // From a real file - private final byte[] data_a = new byte[] { - 0x0F, 00, 0xF2-256, 0x0F, 0x18, 00, 00, 00, - 00, 00, 0xF3-256, 0x0F, 0x10, 00, 00, 00, - 00, 00, 00, 00, 01, 00, 00, 00, - 04, 00, 00, 00, 8, 00, 00, 00 - }; - - public void testRecordType() { - InteractiveInfo ii = new InteractiveInfo(data_a, 0, data_a.length); - assertEquals(4082, ii.getRecordType()); - } - - public void testGetChildDetails() { - InteractiveInfo ii = new InteractiveInfo(data_a, 0, data_a.length); - InteractiveInfoAtom ia = ii.getInteractiveInfoAtom(); - - assertEquals(1, ia.getHyperlinkID()); - } - - public void testWrite() throws Exception { - InteractiveInfo ii = new InteractiveInfo(data_a, 0, data_a.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ii.writeOut(baos); - byte[] b = baos.toByteArray(); - - assertEquals(data_a.length, b.length); - for(int i=0; i a_ch_l = stpa.getCharacterStyles(); - TextPropCollection a_ch_1 = a_ch_l.get(0); - TextPropCollection a_ch_2 = a_ch_l.get(1); - TextPropCollection a_ch_3 = a_ch_l.get(2); - assertEquals(21, a_ch_1.getCharactersCovered()); - assertEquals(17, a_ch_2.getCharactersCovered()); - assertEquals(16, a_ch_3.getCharactersCovered()); - - // 179 chars, 30 + 28 + 25 - List b_ch_l = stpb.getCharacterStyles(); - TextPropCollection b_ch_1 = b_ch_l.get(0); - TextPropCollection b_ch_2 = b_ch_l.get(1); - TextPropCollection b_ch_3 = b_ch_l.get(2); - TextPropCollection b_ch_4 = b_ch_l.get(3); - assertEquals(30, b_ch_1.getCharactersCovered()); - assertEquals(28, b_ch_2.getCharactersCovered()); - assertEquals(25, b_ch_3.getCharactersCovered()); - assertEquals(96, b_ch_4.getCharactersCovered()); - } - - - @Test - public void testCharacterPropOrdering() { - StyleTextPropAtom stpb = new StyleTextPropAtom(data_b,0,data_b.length); - stpb.setParentTextSize(data_b_text_len); - - List b_ch_l = stpb.getCharacterStyles(); - TextPropCollection b_ch_1 = b_ch_l.get(0); - TextPropCollection b_ch_2 = b_ch_l.get(1); - TextPropCollection b_ch_3 = b_ch_l.get(2); - TextPropCollection b_ch_4 = b_ch_l.get(3); - - // In first set, we get a CharFlagsTextProp and a font.size - assertEquals(2,b_ch_1.getTextPropList().size()); - TextProp tp_1_1 = b_ch_1.getTextPropList().get(0); - TextProp tp_1_2 = b_ch_1.getTextPropList().get(1); - assertEquals(true, tp_1_1 instanceof CharFlagsTextProp); - assertEquals("font.size", tp_1_2.getName()); - assertEquals(20, tp_1_2.getValue()); - - // In second set, we get a CharFlagsTextProp and a font.size and a font.color - assertEquals(3,b_ch_2.getTextPropList().size()); - TextProp tp_2_1 = b_ch_2.getTextPropList().get(0); - TextProp tp_2_2 = b_ch_2.getTextPropList().get(1); - TextProp tp_2_3 = b_ch_2.getTextPropList().get(2); - assertEquals(true, tp_2_1 instanceof CharFlagsTextProp); - assertEquals("font.size", tp_2_2.getName()); - assertEquals("font.color", tp_2_3.getName()); - assertEquals(20, tp_2_2.getValue()); - - // In third set, it's just a font.size and a font.color - assertEquals(2,b_ch_3.getTextPropList().size()); - TextProp tp_3_1 = b_ch_3.getTextPropList().get(0); - TextProp tp_3_2 = b_ch_3.getTextPropList().get(1); - assertEquals("font.size", tp_3_1.getName()); - assertEquals("font.color", tp_3_2.getName()); - assertEquals(20, tp_3_1.getValue()); - - // In fourth set, we get a CharFlagsTextProp and a font.index and a font.size - assertEquals(3,b_ch_4.getTextPropList().size()); - TextProp tp_4_1 = b_ch_4.getTextPropList().get(0); - TextProp tp_4_2 = b_ch_4.getTextPropList().get(1); - TextProp tp_4_3 = b_ch_4.getTextPropList().get(2); - assertEquals(true, tp_4_1 instanceof CharFlagsTextProp); - assertEquals("font.index", tp_4_2.getName()); - assertEquals("font.size", tp_4_3.getName()); - assertEquals(24, tp_4_3.getValue()); - } - - @Test - public void testParagraphProps() { - StyleTextPropAtom stpb = new StyleTextPropAtom(data_b,0,data_b.length); - stpb.setParentTextSize(data_b_text_len); - - List b_p_l = stpb.getParagraphStyles(); - TextPropCollection b_p_1 = b_p_l.get(0); - TextPropCollection b_p_2 = b_p_l.get(1); - TextPropCollection b_p_3 = b_p_l.get(2); - TextPropCollection b_p_4 = b_p_l.get(3); - - // 1st is left aligned + normal line spacing - assertEquals(2,b_p_1.getTextPropList().size()); - TextProp tp_1_1 = b_p_1.getTextPropList().get(0); - TextProp tp_1_2 = b_p_1.getTextPropList().get(1); - assertEquals("alignment", tp_1_1.getName()); - assertEquals("linespacing", tp_1_2.getName()); - assertEquals(0, tp_1_1.getValue()); - assertEquals(80, tp_1_2.getValue()); - - // 2nd is centre aligned (default) + normal line spacing - assertEquals(1,b_p_2.getTextPropList().size()); - TextProp tp_2_1 = b_p_2.getTextPropList().get(0); - assertEquals("linespacing", tp_2_1.getName()); - assertEquals(80, tp_2_1.getValue()); - - // 3rd is right aligned + normal line spacing - assertEquals(2,b_p_3.getTextPropList().size()); - TextProp tp_3_1 = b_p_3.getTextPropList().get(0); - TextProp tp_3_2 = b_p_3.getTextPropList().get(1); - assertEquals("alignment", tp_3_1.getName()); - assertEquals("linespacing", tp_3_2.getName()); - assertEquals(2, tp_3_1.getValue()); - assertEquals(80, tp_3_2.getValue()); - - // 4st is left aligned + normal line spacing (despite differing font) - assertEquals(2,b_p_4.getTextPropList().size()); - TextProp tp_4_1 = b_p_4.getTextPropList().get(0); - TextProp tp_4_2 = b_p_4.getTextPropList().get(1); - assertEquals("alignment", tp_4_1.getName()); - assertEquals("linespacing", tp_4_2.getName()); - assertEquals(0, tp_4_1.getValue()); - assertEquals(80, tp_4_2.getValue()); - } - - @Test - public void testCharacterProps() { - StyleTextPropAtom stpb = new StyleTextPropAtom(data_b,0,data_b.length); - stpb.setParentTextSize(data_b_text_len); - - List b_ch_l = stpb.getCharacterStyles(); - TextPropCollection b_ch_1 = b_ch_l.get(0); - TextPropCollection b_ch_2 = b_ch_l.get(1); - TextPropCollection b_ch_3 = b_ch_l.get(2); - TextPropCollection b_ch_4 = b_ch_l.get(3); - - // 1st is bold - CharFlagsTextProp cf_1_1 = (CharFlagsTextProp)b_ch_1.getTextPropList().get(0); - assertEquals(true,cf_1_1.getSubValue(CharFlagsTextProp.BOLD_IDX)); - assertEquals(false,cf_1_1.getSubValue(CharFlagsTextProp.ITALIC_IDX)); - assertEquals(false,cf_1_1.getSubValue(CharFlagsTextProp.ENABLE_NUMBERING_1_IDX)); - assertEquals(false,cf_1_1.getSubValue(CharFlagsTextProp.ENABLE_NUMBERING_2_IDX)); - assertEquals(false,cf_1_1.getSubValue(CharFlagsTextProp.RELIEF_IDX)); - assertEquals(false,cf_1_1.getSubValue(CharFlagsTextProp.RESET_NUMBERING_IDX)); - assertEquals(false,cf_1_1.getSubValue(CharFlagsTextProp.SHADOW_IDX)); - assertEquals(false,cf_1_1.getSubValue(CharFlagsTextProp.STRIKETHROUGH_IDX)); - assertEquals(false,cf_1_1.getSubValue(CharFlagsTextProp.UNDERLINE_IDX)); - - // 2nd is italic - CharFlagsTextProp cf_2_1 = (CharFlagsTextProp)b_ch_2.getTextPropList().get(0); - assertEquals(false,cf_2_1.getSubValue(CharFlagsTextProp.BOLD_IDX)); - assertEquals(true,cf_2_1.getSubValue(CharFlagsTextProp.ITALIC_IDX)); - assertEquals(false,cf_2_1.getSubValue(CharFlagsTextProp.ENABLE_NUMBERING_1_IDX)); - assertEquals(false,cf_2_1.getSubValue(CharFlagsTextProp.ENABLE_NUMBERING_2_IDX)); - assertEquals(false,cf_2_1.getSubValue(CharFlagsTextProp.RELIEF_IDX)); - assertEquals(false,cf_2_1.getSubValue(CharFlagsTextProp.RESET_NUMBERING_IDX)); - assertEquals(false,cf_2_1.getSubValue(CharFlagsTextProp.SHADOW_IDX)); - assertEquals(false,cf_2_1.getSubValue(CharFlagsTextProp.STRIKETHROUGH_IDX)); - assertEquals(false,cf_2_1.getSubValue(CharFlagsTextProp.UNDERLINE_IDX)); - - // 3rd is normal, so lacks a CharFlagsTextProp - assertFalse(b_ch_3.getTextPropList().get(0) instanceof CharFlagsTextProp); - - // 4th is underlined - CharFlagsTextProp cf_4_1 = (CharFlagsTextProp)b_ch_4.getTextPropList().get(0); - assertEquals(false,cf_4_1.getSubValue(CharFlagsTextProp.BOLD_IDX)); - assertEquals(false,cf_4_1.getSubValue(CharFlagsTextProp.ITALIC_IDX)); - assertEquals(false,cf_4_1.getSubValue(CharFlagsTextProp.ENABLE_NUMBERING_1_IDX)); - assertEquals(false,cf_4_1.getSubValue(CharFlagsTextProp.ENABLE_NUMBERING_2_IDX)); - assertEquals(false,cf_4_1.getSubValue(CharFlagsTextProp.RELIEF_IDX)); - assertEquals(false,cf_4_1.getSubValue(CharFlagsTextProp.RESET_NUMBERING_IDX)); - assertEquals(false,cf_4_1.getSubValue(CharFlagsTextProp.SHADOW_IDX)); - assertEquals(false,cf_4_1.getSubValue(CharFlagsTextProp.STRIKETHROUGH_IDX)); - assertEquals(true,cf_4_1.getSubValue(CharFlagsTextProp.UNDERLINE_IDX)); - - // The value for this should be 4 - assertEquals(0x0004, cf_4_1.getValue()); - - // Now make the 4th bold, italic and not underlined - cf_4_1.setSubValue(true, CharFlagsTextProp.BOLD_IDX); - cf_4_1.setSubValue(true, CharFlagsTextProp.ITALIC_IDX); - cf_4_1.setSubValue(false, CharFlagsTextProp.UNDERLINE_IDX); - - assertEquals(true,cf_4_1.getSubValue(CharFlagsTextProp.BOLD_IDX)); - assertEquals(true,cf_4_1.getSubValue(CharFlagsTextProp.ITALIC_IDX)); - assertEquals(false,cf_4_1.getSubValue(CharFlagsTextProp.ENABLE_NUMBERING_1_IDX)); - assertEquals(false,cf_4_1.getSubValue(CharFlagsTextProp.ENABLE_NUMBERING_2_IDX)); - assertEquals(false,cf_4_1.getSubValue(CharFlagsTextProp.RELIEF_IDX)); - assertEquals(false,cf_4_1.getSubValue(CharFlagsTextProp.RESET_NUMBERING_IDX)); - assertEquals(false,cf_4_1.getSubValue(CharFlagsTextProp.SHADOW_IDX)); - assertEquals(false,cf_4_1.getSubValue(CharFlagsTextProp.STRIKETHROUGH_IDX)); - assertEquals(false,cf_4_1.getSubValue(CharFlagsTextProp.UNDERLINE_IDX)); - - // The value should now be 3 - assertEquals(0x0003, cf_4_1.getValue()); - } - - @Test(expected=HSLFException.class) - public void testFindAddTextProp() { - StyleTextPropAtom stpb = new StyleTextPropAtom(data_b,0,data_b.length); - stpb.setParentTextSize(data_b_text_len); - - List b_p_l = stpb.getParagraphStyles(); - TextPropCollection b_p_1 = b_p_l.get(0); - TextPropCollection b_p_2 = b_p_l.get(1); - TextPropCollection b_p_3 = b_p_l.get(2); - TextPropCollection b_p_4 = b_p_l.get(3); - - List b_ch_l = stpb.getCharacterStyles(); - TextPropCollection b_ch_1 = b_ch_l.get(0); - TextPropCollection b_ch_2 = b_ch_l.get(1); - TextPropCollection b_ch_3 = b_ch_l.get(2); - TextPropCollection b_ch_4 = b_ch_l.get(3); - - assertNotNull(b_p_1); - assertNotNull(b_p_2); - assertNotNull(b_p_3); - assertNotNull(b_p_4); - - assertNotNull(b_ch_1); - assertNotNull(b_ch_2); - assertNotNull(b_ch_3); - assertNotNull(b_ch_4); - - // CharFlagsTextProp: 3 doesn't have, 4 does - assertNull(b_ch_3.findByName("char_flags")); - assertNotNull(b_ch_4.findByName("char_flags")); - - // Now add in on 3, should go to front - assertEquals(2, b_ch_3.getTextPropList().size()); - TextProp new_cftp = b_ch_3.addWithName("char_flags"); - assertEquals(3, b_ch_3.getTextPropList().size()); - assertEquals(new_cftp, b_ch_3.getTextPropList().get(0)); - - // alignment: 1 does have, 2 doesn't - assertNotNull(b_p_1.findByName("alignment")); - assertNull(b_p_2.findByName("alignment")); - - // Now add in on 2, should go to the front - assertEquals(1, b_p_2.getTextPropList().size()); - TextProp new_al = b_p_2.addWithName("alignment"); - assertEquals(2, b_p_2.getTextPropList().size()); - assertEquals(new_al, b_p_2.getTextPropList().get(0)); - - // This should go at the end - TextProp new_sa = b_p_2.addWithName("spaceafter"); - assertEquals(3, b_p_2.getTextPropList().size()); - assertEquals(new_sa, b_p_2.getTextPropList().get(2)); - - // Check we get an error with a made up one - b_p_2.addWithName("madeUpOne"); - } - - /** - * Try to recreate an existing StyleTextPropAtom (a) from the empty - * constructor, and setting the required properties - */ - @Test - public void testCreateAFromScatch() throws Exception { - // Start with an empty one - StyleTextPropAtom stpa = new StyleTextPropAtom(54); - - // Don't need to touch the paragraph styles - // Add two more character styles - List cs = stpa.getCharacterStyles(); - - // First char style is boring, and 21 long - TextPropCollection tpca = cs.get(0); - tpca.updateTextSize(21); - - // Second char style is coloured, 00 00 00 05, and 17 long - TextPropCollection tpcb = stpa.addCharacterTextPropCollection(17); - TextProp tpb = tpcb.addWithName("font.color"); - tpb.setValue(0x05000000); - - // Third char style is coloured, FF 33 00 FE, and 16 long - TextPropCollection tpcc = stpa.addCharacterTextPropCollection(16); - TextProp tpc = tpcc.addWithName("font.color"); - tpc.setValue(0xFE0033FF); - - // Should now be the same as data_a - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - stpa.writeOut(baos); - byte[] b = baos.toByteArray(); - - assertEquals(data_a.length, b.length); - for(int i=0; i ps = stpa.getParagraphStyles(); - - // First is 30 long, left aligned, normal spacing - TextPropCollection tppa = ps.get(0); - tppa.updateTextSize(30); - - TextProp tp = tppa.addWithName("alignment"); - tp.setValue(0); - tp = tppa.addWithName("linespacing"); - tp.setValue(80); - - // Second is 28 long, centre aligned and normal spacing - TextPropCollection tppb = stpa.addParagraphTextPropCollection(28); - - tp = tppb.addWithName("linespacing"); - tp.setValue(80); - - // Third is 25 long, right aligned and normal spacing - TextPropCollection tppc = stpa.addParagraphTextPropCollection(25); - - tp = tppc.addWithName("alignment"); - tp.setValue(2); - tp = tppc.addWithName("linespacing"); - tp.setValue(80); - - // Forth is left aligned + normal line spacing (despite differing font) - TextPropCollection tppd = stpa.addParagraphTextPropCollection(97); - - tp = tppd.addWithName("alignment"); - tp.setValue(0); - tp = tppd.addWithName("linespacing"); - tp.setValue(80); - - - // Now do 4 character styles - List cs = stpa.getCharacterStyles(); - - // First is 30 long, bold and font size - TextPropCollection tpca = cs.get(0); - tpca.updateTextSize(30); - - tp = tpca.addWithName("font.size"); - tp.setValue(20); - CharFlagsTextProp cftp = (CharFlagsTextProp) - tpca.addWithName("char_flags"); - assertEquals(0, cftp.getValue()); - cftp.setSubValue(true, CharFlagsTextProp.BOLD_IDX); - assertEquals(1, cftp.getValue()); - - // Second is 28 long, blue and italic - TextPropCollection tpcb = stpa.addCharacterTextPropCollection(28); - - tp = tpcb.addWithName("font.size"); - tp.setValue(20); - tp = tpcb.addWithName("font.color"); - tp.setValue(0x05000000); - cftp = (CharFlagsTextProp)tpcb.addWithName("char_flags"); - cftp.setSubValue(true, CharFlagsTextProp.ITALIC_IDX); - assertEquals(2, cftp.getValue()); - - // Third is 25 long and red - TextPropCollection tpcc = stpa.addCharacterTextPropCollection(25); - - tp = tpcc.addWithName("font.size"); - tp.setValue(20); - tp = tpcc.addWithName("font.color"); - tp.setValue(0xfe0033ff); - - // Fourth is 96 long, underlined and different+bigger font - TextPropCollection tpcd = stpa.addCharacterTextPropCollection(96); - - tp = tpcd.addWithName("font.size"); - tp.setValue(24); - tp = tpcd.addWithName("font.index"); - tp.setValue(1); - cftp = (CharFlagsTextProp)tpcd.addWithName("char_flags"); - cftp.setSubValue(true, CharFlagsTextProp.UNDERLINE_IDX); - assertEquals(4, cftp.getValue()); - - // Fifth is 1 long, underlined and different+bigger font + red - TextPropCollection tpce = stpa.addCharacterTextPropCollection(1); - - tp = tpce.addWithName("font.size"); - tp.setValue(24); - tp = tpce.addWithName("font.index"); - tp.setValue(1); - tp = tpce.addWithName("font.color"); - tp.setValue(0xfe0033ff); - cftp = (CharFlagsTextProp)tpce.addWithName("char_flags"); - cftp.setSubValue(true, CharFlagsTextProp.UNDERLINE_IDX); - assertEquals(4, cftp.getValue()); - - - // Check it's as expected - assertEquals(4, stpa.getParagraphStyles().size()); - assertEquals(5, stpa.getCharacterStyles().size()); - - // Compare in detail to b - StyleTextPropAtom stpb = new StyleTextPropAtom(data_b,0,data_b.length); - stpb.setParentTextSize(data_b_text_len); - List psb = stpb.getParagraphStyles(); - List csb = stpb.getCharacterStyles(); - - assertEquals(psb.size(), ps.size()); - assertEquals(csb.size(), cs.size()); - - // Ensure Paragraph Character styles match - for(int z=0; z<2; z++) { - List lla = cs; - List llb = csb; - int upto = 5; - if(z == 1) { - lla = ps; - llb = psb; - upto = 4; - } - - for(int i=0; i - * 14 00 00 00 00 00 41 00 0A 00 06 00 50 00 07 00 01 00 00 00 00 00 00 00 02 - * 00 00 00 01 04 00 00 01 04 01 00 00 00 01 08 00 00 01 08 0C 00 00 00 01 0C - * 00 00 01 0C 01 00 00 00 01 10 00 00 01 10 01 00 00 00 01 14 00 00 01 14 01 - * 00 00 00 01 18 00 00 01 18 01 00 00 00 01 1C 00 00 01 1C - * - */ - @Test - public void test45815() { - int length = 19; - byte[] data = { - 0x00, 0x00, (byte)0xA1, 0x0F, 0x5E, 0x00, 0x00, 0x00, 0x14, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x41, 0x00, 0x0A, 0x00, 0x06, 0x00, - 0x50, 0x00, 0x07, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x01, 0x04, 0x00, 0x00, - 0x01, 0x04, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x00, 0x00, - 0x01, 0x08, 0x0C, 0x00, 0x00, 0x00, 0x01, 0x0C, 0x00, 0x00, - 0x01, 0x0C, 0x01, 0x00, 0x00, 0x00, 0x01, 0x10, 0x00, 0x00, - 0x01, 0x10, 0x01, 0x00, 0x00, 0x00, 0x01, 0x14, 0x00, 0x00, - 0x01, 0x14, 0x01, 0x00, 0x00, 0x00, 0x01, 0x18, 0x00, 0x00, - 0x01, 0x18, 0x01, 0x00, 0x00, 0x00, 0x01, 0x1C, 0x00, 0x00, - 0x01, 0x1C - }; - - // changed original data: ... 0x41 and 0x06 don't match - // the bitmask text properties will sanitize the bytes and thus the bytes differ - byte[] exptected = data.clone(); - exptected[18] = 0; - - doReadWrite(data, exptected, length); - } - -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestTextBytesAtom.java b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestTextBytesAtom.java deleted file mode 100644 index 9078bd166..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestTextBytesAtom.java +++ /dev/null @@ -1,81 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - - -import junit.framework.TestCase; -import java.io.ByteArrayOutputStream; - -/** - * Tests that TextBytesAtom works properly - * - * @author Nick Burch (nick at torchbox dot com) - */ -public final class TestTextBytesAtom extends TestCase { - // From a real file - private final byte[] data = new byte[] { 0, 0, 0xA8-256, 0x0f, 0x1c, 0, 0, 0, - 0x54, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x74, 0x68, - 0x65, 0x20, 0x74, 0x69, 0x74, 0x6C, 0x65, 0x20, 0x6F, 0x6E, - 0x20, 0x70, 0x61, 0x67, 0x65, 0x20, 0x32 }; - private final String data_text = "This is the title on page 2"; - private final byte[] alt_data = new byte[] { 0, 0, 0xA8-256, 0x0F, 0x14, 0, 0, 0, - 0x54, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x61, 0x20, - 0x74, 0x65, 0x73, 0x74, 0x20, 0x74, 0x69, 0x74, 0x6C, 0x65 }; - private final String alt_text = "This is a test title"; - - public void testRecordType() { - TextBytesAtom tba = new TextBytesAtom(data,0,data.length); - assertEquals(4008l, tba.getRecordType()); - } - - public void testTextA() { - TextBytesAtom tba = new TextBytesAtom(data,0,data.length); - assertEquals(data_text, tba.getText()); - } - public void testTextB() { - TextBytesAtom tba = new TextBytesAtom(alt_data,0,alt_data.length); - assertEquals(alt_text, tba.getText()); - } - - public void testChangeText() throws Exception { - TextBytesAtom tba = new TextBytesAtom(data,0,data.length); - tba.setText(alt_text.getBytes("ISO-8859-1")); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - tba.writeOut(baos); - byte[] b = baos.toByteArray(); - - // Compare the header and the text - assertEquals(alt_data.length, b.length); - for(int i=0; iTestTxMasterStyleAtom record. - * Check master style for the empty ppt which is created - * by the default constructor of SlideShow - * - * @author Yegor Kozlov - */ -public final class TestTxMasterStyleAtom extends TestCase { - protected HSLFSlideShow _ppt; - - @Override - public void setUp() { - _ppt = new HSLFSlideShow(); - } - - public void testDefaultStyles() { - TxMasterStyleAtom[] txmaster = getMasterStyles(); - for (final TxMasterStyleAtom atom : txmaster) { - final int txtype = atom.getTextType(); - switch (txtype){ - case TextHeaderAtom.TITLE_TYPE: - checkTitleType(atom); - break; - case TextHeaderAtom.BODY_TYPE: - checkBodyType(atom); - break; - case TextHeaderAtom.NOTES_TYPE: - checkNotesType(atom); - break; - case TextHeaderAtom.OTHER_TYPE: - checkOtherType(atom); - break; - case TextHeaderAtom.CENTRE_BODY_TYPE: - break; - case TextHeaderAtom.CENTER_TITLE_TYPE: - break; - case TextHeaderAtom.HALF_BODY_TYPE: - break; - case TextHeaderAtom.QUARTER_BODY_TYPE: - break; - default: - fail("Unknown text type: " + txtype); - } - - } - } - - - - /** - * Test styles for type=TextHeaderAtom.TITLE_TYPE - */ - private void checkTitleType(TxMasterStyleAtom txmaster){ - TextPropCollection props; - TextProp prop; - - //paragraph styles - props = txmaster.getParagraphStyles().get(0); - - prop = props.findByName("alignment"); - assertEquals(1, prop.getValue()); //title has center alignment - - //character styles - props = txmaster.getCharacterStyles().get(0); - - prop = props.findByName("font.color"); - assertEquals(0x3000000, prop.getValue()); - - prop = props.findByName("font.index"); - assertEquals(0, prop.getValue()); - - prop = props.findByName("font.size"); - assertEquals(44, prop.getValue()); - - } - - /** - * Test styles for type=TextHeaderAtom.BODY_TYPE - */ - private void checkBodyType(TxMasterStyleAtom txmaster){ - TextPropCollection props; - TextProp prop; - - List prstyles = txmaster.getParagraphStyles(); - List chstyles = txmaster.getCharacterStyles(); - assertEquals("TxMasterStyleAtom for TextHeaderAtom.BODY_TYPE " + - "must contain styles for 5 indentation levels", 5, prstyles.size()); - assertEquals("TxMasterStyleAtom for TextHeaderAtom.BODY_TYPE " + - "must contain styles for 5 indentation levels", 5, chstyles.size()); - - //paragraph styles - props = prstyles.get(0); - - prop = props.findByName("alignment"); - assertEquals(0, prop.getValue()); - - - for (int i = 0; i < prstyles.size(); i++) { - assertNotNull("text.offset is null for indentation level " + i, prstyles.get(i).findByName("text.offset")); - assertNotNull("bullet.offset is null for indentation level " + i, prstyles.get(i).findByName("bullet.offset")); - } - - //character styles - props = chstyles.get(0); - - prop = props.findByName("font.color"); - assertEquals(0x1000000, prop.getValue()); - - prop = props.findByName("font.index"); - assertEquals(0, prop.getValue()); - - prop = props.findByName("font.size"); - assertEquals(32, prop.getValue()); - } - - /** - * Test styles for type=TextHeaderAtom.OTHER_TYPE - */ - private void checkOtherType(TxMasterStyleAtom txmaster){ - TextPropCollection props; - TextProp prop; - - //paragraph styles - props = txmaster.getParagraphStyles().get(0); - - prop = props.findByName("alignment"); - assertEquals(0, prop.getValue()); - - //character styles - props = txmaster.getCharacterStyles().get(0); - - prop = props.findByName("font.color"); - assertEquals(0x1000000, prop.getValue()); - - prop = props.findByName("font.index"); - assertEquals(0, prop.getValue()); - - prop = props.findByName("font.size"); - assertEquals(18, prop.getValue()); - } - - /** - * Test styles for type=TextHeaderAtom.NOTES_TYPE - */ - private void checkNotesType(TxMasterStyleAtom txmaster){ - TextPropCollection props; - TextProp prop; - - //paragraph styles - props = txmaster.getParagraphStyles().get(0); - - prop = props.findByName("alignment"); - assertEquals(0, prop.getValue()); //title has center alignment - - //character styles - props = txmaster.getCharacterStyles().get(0); - - prop = props.findByName("font.color"); - assertEquals(0x1000000, prop.getValue()); - - prop = props.findByName("font.index"); - assertEquals(0, prop.getValue()); - - prop = props.findByName("font.size"); - assertEquals(12, prop.getValue()); - - } - - /** - * Collect all TxMasterStyleAtom records contained in the supplied slide show. - * There must be a TxMasterStyleAtom per each type of text defined in TextHeaderAtom - */ - protected TxMasterStyleAtom[] getMasterStyles(){ - List lst = new ArrayList(); - - Record[] coreRecs = _ppt.getMostRecentCoreRecords(); - for (final Record coreRec : coreRecs) { - if(coreRec.getRecordType() == RecordTypes.MainMaster.typeID){ - Record[] recs = coreRec.getChildRecords(); - int cnt = 0; - for (final Record rec : recs) { - if (rec instanceof TxMasterStyleAtom) { - lst.add((TxMasterStyleAtom) rec); - cnt++; - } - } - assertEquals("MainMaster must contain 7 TxMasterStyleAtoms ", 7, cnt); - } else if(coreRec.getRecordType() == RecordTypes.Document.typeID){ - TxMasterStyleAtom txstyle = null; - Document doc = (Document)coreRec; - Record[] rec = doc.getEnvironment().getChildRecords(); - for (final Record atom : rec) { - if (atom instanceof TxMasterStyleAtom) { - if (txstyle != null) fail("Document.Environment must contain 1 TxMasterStyleAtom"); - txstyle = (TxMasterStyleAtom)atom; - } - } - if (txstyle == null) { - throw new AssertionFailedError("TxMasterStyleAtom not found in Document.Environment"); - } - - assertEquals("Document.Environment must contain TxMasterStyleAtom with type=TextHeaderAtom.OTHER_TYPE", - TextHeaderAtom.OTHER_TYPE, txstyle.getTextType()); - lst.add(txstyle); - } - } - - return lst.toArray(new TxMasterStyleAtom[lst.size()]); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestUserEditAtom.java b/src/scratchpad/testcases/org/apache/poi/hslf/record/TestUserEditAtom.java deleted file mode 100644 index fca70287c..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/record/TestUserEditAtom.java +++ /dev/null @@ -1,63 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.record; - - -import junit.framework.TestCase; -import java.io.ByteArrayOutputStream; - -/** - * Tests that UserEditAtom works properly - * - * @author Nick Burch (nick at torchbox dot com) - */ -public final class TestUserEditAtom extends TestCase { - // From a real file - private final byte[] data_a = new byte[] { 0, 0, 0xF5-256, 0x0F, 0x1C, 0, 0, 0, - 00, 01, 00, 00, 0xD9-256, 18, 00, 03, - 00, 00, 00, 00, 00, 0x18, 00, 00, 01, 00, 00, 00, - 05, 00, 00, 00, 01, 00, 0xF6-256, 77 }; - - public void testRecordType() { - UserEditAtom uea = new UserEditAtom(data_a, 0, data_a.length); - assertEquals(4085l, uea.getRecordType()); - } - public void testFlags() { - UserEditAtom uea = new UserEditAtom(data_a, 0, data_a.length); - - assertEquals(256, uea.getLastViewedSlideID() ); - //assertEquals(0x030018D9, uea.getPPTVersion() ); - assertEquals(0, uea.getLastUserEditAtomOffset() ); - assertEquals(0x1800, uea.getPersistPointersOffset() ); - assertEquals(1, uea.getDocPersistRef() ); - assertEquals(5, uea.getMaxPersistWritten() ); - assertEquals((short)1, uea.getLastViewType() ); - } - - public void testWrite() throws Exception { - UserEditAtom uea = new UserEditAtom(data_a, 0, data_a.length); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - uea.writeOut(baos); - byte[] b = baos.toByteArray(); - - assertEquals(data_a.length, b.length); - for(int i=0; iorg.apache.poi.hslf.usermodel. - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestAddingSlides.class, - TestBugs.class, - TestCounts.class, - TestMostRecentRecords.class, - TestNotesText.class, - TestPictures.class, - TestReOrderingSlides.class, - TestRecordSetup.class, - TestRichTextRun.class, - TestSheetText.class, - TestSlideOrdering.class, - TestSoundData.class, - TestFontRendering.class, - TestPicture.class, - TestTextRun.class, - TestTextShape.class -}) -public class AllHSLFUserModelTests { -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestAddingSlides.java b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestAddingSlides.java deleted file mode 100644 index 523f6ad7d..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestAddingSlides.java +++ /dev/null @@ -1,286 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.IOException; -import java.util.List; - -import org.apache.poi.hslf.HSLFTestDataSamples; -import org.apache.poi.hslf.record.Document; -import org.apache.poi.hslf.record.Record; -import org.apache.poi.hslf.record.RecordTypes; -import org.apache.poi.hslf.record.UserEditAtom; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -/** - * Tests that SlideShow adds additional sheets properly - */ -public final class TestAddingSlides { - // An empty SlideShow - private HSLFSlideShow ss_empty; - - // A SlideShow with one slide - private HSLFSlideShow ss_one; - - // A SlideShow with two slides - private HSLFSlideShow ss_two; - - /** - * Create/open the slideshows - */ - @Before - public void setUp() throws IOException { - ss_empty = new HSLFSlideShow(); - ss_one = HSLFTestDataSamples.getSlideShow("Single_Coloured_Page.ppt"); - ss_two = HSLFTestDataSamples.getSlideShow("basic_test_ppt_file.ppt"); - } - - @After - public void tearDown() throws IOException { - ss_two.close(); - ss_one.close(); - ss_empty.close(); - } - - /** - * Test adding a slide to an empty slideshow - */ - @Test - public void testAddSlideToEmpty() throws IOException { - // Doesn't have any slides - assertEquals(0, ss_empty.getSlides().size()); - - // Should only have a master SLWT - assertEquals(1, - ss_empty.getDocumentRecord().getSlideListWithTexts().length); - - // grab UserEditAtom - UserEditAtom usredit = null; - Record[] _records = ss_empty.getSlideShowImpl().getRecords(); - for (Record record : _records) { - if (record.getRecordType() == RecordTypes.UserEditAtom.typeID) { - usredit = (UserEditAtom) record; - } - } - assertNotNull(usredit); - - // Add one - HSLFSlide slide = ss_empty.createSlide(); - assertEquals(1, ss_empty.getSlides().size()); - assertEquals(256, slide._getSheetNumber()); - assertEquals(3, slide._getSheetRefId()); - assertEquals(1, slide.getSlideNumber()); - assertEquals(usredit.getMaxPersistWritten(), slide._getSheetRefId()); - - // Write out, and read back in - HSLFSlideShow ss_read = HSLFTestDataSamples - .writeOutAndReadBack(ss_empty); - - // Check it now has a slide - assertEquals(1, ss_read.getSlides().size()); - - // Check it now has two SLWTs - assertEquals(2, - ss_empty.getDocumentRecord().getSlideListWithTexts().length); - - // And check it's as expected - slide = ss_read.getSlides().get(0); - assertEquals(256, slide._getSheetNumber()); - assertEquals(3, slide._getSheetRefId()); - assertEquals(1, slide.getSlideNumber()); - ss_read.close(); - } - - /** - * Test adding a slide to an existing slideshow - */ - @Test - public void testAddSlideToExisting() throws IOException { - // Has one slide - assertEquals(1, ss_one.getSlides().size()); - HSLFSlide s1 = ss_one.getSlides().get(0); - - // Should have two SLTWs - assertEquals(2, ss_one.getDocumentRecord().getSlideListWithTexts().length); - - // Check slide 1 is as expected - assertEquals(256, s1._getSheetNumber()); - assertEquals(3, s1._getSheetRefId()); - assertEquals(1, s1.getSlideNumber()); - - // Add a second one - HSLFSlide s2 = ss_one.createSlide(); - assertEquals(2, ss_one.getSlides().size()); - assertEquals(257, s2._getSheetNumber()); - assertEquals(4, s2._getSheetRefId()); - assertEquals(2, s2.getSlideNumber()); - - // Write out, and read back in - HSLFSlideShow ss_read = HSLFTestDataSamples.writeOutAndReadBack(ss_one); - - // Check it now has two slides - assertEquals(2, ss_read.getSlides().size()); - - // Should still have two SLTWs - assertEquals(2, - ss_read.getDocumentRecord().getSlideListWithTexts().length); - - // And check it's as expected - s1 = ss_read.getSlides().get(0); - s2 = ss_read.getSlides().get(1); - assertEquals(256, s1._getSheetNumber()); - assertEquals(3, s1._getSheetRefId()); - assertEquals(1, s1.getSlideNumber()); - assertEquals(257, s2._getSheetNumber()); - assertEquals(4, s2._getSheetRefId()); - assertEquals(2, s2.getSlideNumber()); - ss_read.close(); - } - - /** - * Test adding a slide to an existing slideshow, with two slides already - */ - @Test - public void testAddSlideToExisting2() throws IOException { - // grab UserEditAtom - UserEditAtom usredit = null; - Record[] _records = ss_two.getSlideShowImpl().getRecords(); - for (Record record : _records) { - if (record.getRecordType() == RecordTypes.UserEditAtom.typeID) { - usredit = (UserEditAtom) record; - } - } - assertNotNull(usredit); - - // Has two slides - assertEquals(2, ss_two.getSlides().size()); - HSLFSlide s1 = ss_two.getSlides().get(0); - HSLFSlide s2 = ss_two.getSlides().get(1); - - // Check slide 1 is as expected - assertEquals(256, s1._getSheetNumber()); - assertEquals(4, s1._getSheetRefId()); // master has notes - assertEquals(1, s1.getSlideNumber()); - // Check slide 2 is as expected - assertEquals(257, s2._getSheetNumber()); - assertEquals(6, s2._getSheetRefId()); // master and 1 have notes - assertEquals(2, s2.getSlideNumber()); - - // Add a third one - HSLFSlide s3 = ss_two.createSlide(); - assertEquals(3, ss_two.getSlides().size()); - assertEquals(258, s3._getSheetNumber()); - assertEquals(8, s3._getSheetRefId()); // lots of notes before us - assertEquals(3, s3.getSlideNumber()); - assertEquals(usredit.getMaxPersistWritten(), s3._getSheetRefId()); - - // Write out, and read back in - HSLFSlideShow ss_read = HSLFTestDataSamples.writeOutAndReadBack(ss_two); - - // Check it now has three slides - assertEquals(3, ss_read.getSlides().size()); - - // And check it's as expected - s1 = ss_read.getSlides().get(0); - s2 = ss_read.getSlides().get(1); - s3 = ss_read.getSlides().get(2); - assertEquals(256, s1._getSheetNumber()); - assertEquals(4, s1._getSheetRefId()); - assertEquals(1, s1.getSlideNumber()); - assertEquals(257, s2._getSheetNumber()); - assertEquals(6, s2._getSheetRefId()); - assertEquals(2, s2.getSlideNumber()); - assertEquals(258, s3._getSheetNumber()); - assertEquals(8, s3._getSheetRefId()); - assertEquals(3, s3.getSlideNumber()); - ss_read.close(); - } - - /** - * Test SlideShow#removeSlide - */ - @Test - public void testRemoving() throws IOException { - HSLFSlide slide1 = ss_empty.createSlide(); - HSLFSlide slide2 = ss_empty.createSlide(); - - List s1 = ss_empty.getSlides(); - assertEquals(2, s1.size()); - try { - ss_empty.removeSlide(-1); - fail("expected exception"); - } catch (Exception e) { - } - - try { - ss_empty.removeSlide(2); - fail("expected exception"); - } catch (Exception e) { - } - - assertEquals(1, slide1.getSlideNumber()); - - HSLFSlide removedSlide = ss_empty.removeSlide(0); - List s2 = ss_empty.getSlides(); - assertEquals(1, s2.size()); - assertSame(slide1, removedSlide); - assertSame(slide2, s2.get(0)); - - assertEquals(0, slide2.getSlideNumber()); - - HSLFSlideShow ss_read = HSLFTestDataSamples - .writeOutAndReadBack(ss_empty); - - List s3 = ss_read.getSlides(); - assertEquals(1, s3.size()); - ss_read.close(); - } - - @Test - public void test47261() throws IOException { - HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow("47261.ppt"); - List slides = ppt.getSlides(); - Document doc = ppt.getDocumentRecord(); - assertNotNull(doc.getSlideSlideListWithText()); - assertEquals(14, ppt.getSlides().size()); - int notesId = slides.get(0).getSlideRecord().getSlideAtom() - .getNotesID(); - assertTrue(notesId > 0); - assertNotNull(doc.getNotesSlideListWithText()); - assertEquals(14, doc.getNotesSlideListWithText().getSlideAtomsSets().length); - - // remove all slides, corresponding notes should be removed too - for (int i = slides.size(); i > 0; i--) { - ppt.removeSlide(0); - } - assertEquals(0, ppt.getSlides().size()); - assertEquals(0, ppt.getNotes().size()); - assertNull(doc.getSlideSlideListWithText()); - assertNull(doc.getNotesSlideListWithText()); - ppt.close(); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestBugs.java b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestBugs.java deleted file mode 100644 index df99363dc..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestBugs.java +++ /dev/null @@ -1,1039 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.usermodel; - -import static org.apache.poi.POITestCase.assertContains; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.geom.Ellipse2D; -import java.awt.geom.Path2D; -import java.awt.geom.Rectangle2D; -import java.awt.image.BufferedImage; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.PrintStream; -import java.text.AttributedCharacterIterator; -import java.text.AttributedCharacterIterator.Attribute; -import java.text.CharacterIterator; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.ddf.AbstractEscherOptRecord; -import org.apache.poi.ddf.EscherArrayProperty; -import org.apache.poi.ddf.EscherColorRef; -import org.apache.poi.ddf.EscherProperties; -import org.apache.poi.hslf.HSLFTestDataSamples; -import org.apache.poi.hslf.exceptions.OldPowerPointFormatException; -import org.apache.poi.hslf.extractor.PowerPointExtractor; -import org.apache.poi.hslf.model.HeadersFooters; -import org.apache.poi.hslf.record.DocInfoListContainer; -import org.apache.poi.hslf.record.Document; -import org.apache.poi.hslf.record.Record; -import org.apache.poi.hslf.record.RecordTypes; -import org.apache.poi.hslf.record.SlideListWithText; -import org.apache.poi.hslf.record.SlideListWithText.SlideAtomsSet; -import org.apache.poi.hslf.record.TextHeaderAtom; -import org.apache.poi.hslf.record.VBAInfoAtom; -import org.apache.poi.hslf.record.VBAInfoContainer; -import org.apache.poi.hssf.usermodel.DummyGraphics2d; -import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; -import org.apache.poi.poifs.macros.VBAMacroReader; -import org.apache.poi.sl.draw.DrawFactory; -import org.apache.poi.sl.draw.DrawPaint; -import org.apache.poi.sl.draw.DrawTextParagraph; -import org.apache.poi.sl.usermodel.ColorStyle; -import org.apache.poi.sl.usermodel.PaintStyle; -import org.apache.poi.sl.usermodel.PaintStyle.SolidPaint; -import org.apache.poi.sl.usermodel.PictureData.PictureType; -import org.apache.poi.sl.usermodel.Placeholder; -import org.apache.poi.sl.usermodel.ShapeType; -import org.apache.poi.sl.usermodel.Slide; -import org.apache.poi.sl.usermodel.SlideShow; -import org.apache.poi.sl.usermodel.SlideShowFactory; -import org.apache.poi.sl.usermodel.TextBox; -import org.apache.poi.sl.usermodel.TextParagraph; -import org.apache.poi.sl.usermodel.TextParagraph.TextAlign; -import org.apache.poi.sl.usermodel.TextRun; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.StringUtil; -import org.apache.poi.util.Units; -import org.junit.Test; - -/** - * Testcases for bugs entered in bugzilla - * the Test name contains the bugzilla bug id - */ -public final class TestBugs { - /** - * Bug 41384: Array index wrong in record creation - */ - @Test - public void bug41384() throws IOException { - HSLFSlideShow ppt = open("41384.ppt"); - - assertEquals(1, ppt.getSlides().size()); - - List pict = ppt.getPictureData(); - assertEquals(2, pict.size()); - assertEquals(PictureType.JPEG, pict.get(0).getType()); - assertEquals(PictureType.JPEG, pict.get(1).getType()); - - ppt.close(); - } - - /** - * First fix from Bug 42474: NPE in RichTextRun.isBold() - * when the RichTextRun comes from a Notes model object - */ - @Test - public void bug42474_1() throws IOException { - HSLFSlideShow ppt = open("42474-1.ppt"); - assertEquals(2, ppt.getSlides().size()); - - List txrun; - HSLFNotes notes; - - notes = ppt.getSlides().get(0).getNotes(); - assertNotNull(notes); - txrun = notes.getTextParagraphs().get(0); - assertEquals("Notes-1", HSLFTextParagraph.getRawText(txrun)); - assertEquals(false, txrun.get(0).getTextRuns().get(0).isBold()); - - //notes for the second slide are in bold - notes = ppt.getSlides().get(1).getNotes(); - assertNotNull(notes); - txrun = notes.getTextParagraphs().get(0); - assertEquals("Notes-2", HSLFTextParagraph.getRawText(txrun)); - assertEquals(true, txrun.get(0).getTextRuns().get(0).isBold()); - - ppt.close(); - } - - /** - * Second fix from Bug 42474: Incorrect matching of notes to slides - */ - @Test - public void bug42474_2() throws IOException { - HSLFSlideShow ppt = open("42474-2.ppt"); - - //map slide number and starting phrase of its notes - Map notesMap = new HashMap(); - notesMap.put(Integer.valueOf(4), "For decades before calculators"); - notesMap.put(Integer.valueOf(5), "Several commercial applications"); - notesMap.put(Integer.valueOf(6), "There are three variations of LNS that are discussed here"); - notesMap.put(Integer.valueOf(7), "Although multiply and square root are easier"); - notesMap.put(Integer.valueOf(8), "The bus Z is split into Z_H and Z_L"); - - for (HSLFSlide slide : ppt.getSlides()) { - Integer slideNumber = Integer.valueOf(slide.getSlideNumber()); - HSLFNotes notes = slide.getNotes(); - if (notesMap.containsKey(slideNumber)){ - assertNotNull(notes); - String text = HSLFTextParagraph.getRawText(notes.getTextParagraphs().get(0)); - String startingPhrase = notesMap.get(slideNumber); - assertTrue("Notes for slide " + slideNumber + " must start with " + - startingPhrase , text.startsWith(startingPhrase)); - } - } - - ppt.close(); - } - - /** - * Bug 42485: All TextBoxes inside ShapeGroups have null TextRuns - */ - @Test - public void bug42485 () throws IOException { - HSLFSlideShow ppt = open("42485.ppt"); - for (HSLFShape shape : ppt.getSlides().get(0).getShapes()) { - if(shape instanceof HSLFGroupShape){ - HSLFGroupShape group = (HSLFGroupShape)shape; - for (HSLFShape sh : group.getShapes()) { - if(sh instanceof HSLFTextBox){ - HSLFTextBox txt = (HSLFTextBox)sh; - assertNotNull(txt.getTextParagraphs()); - } - } - } - } - ppt.close(); - } - - /** - * Bug 42484: NullPointerException from ShapeGroup.getAnchor() - */ - @Test - public void bug42484 () throws IOException { - HSLFSlideShow ppt = open("42485.ppt"); - for (HSLFShape shape : ppt.getSlides().get(0).getShapes()) { - if(shape instanceof HSLFGroupShape){ - HSLFGroupShape group = (HSLFGroupShape)shape; - assertNotNull(group.getAnchor()); - for (HSLFShape sh : group.getShapes()) { - assertNotNull(sh.getAnchor()); - } - } - } - ppt.close(); - } - - /** - * Bug 41381: Exception from Slide.getMasterSheet() on a seemingly valid PPT file - */ - @Test - public void bug41381() throws IOException { - HSLFSlideShow ppt = open("alterman_security.ppt"); - assertTrue("No Exceptions while reading file", true); - - assertEquals(1, ppt.getSlideMasters().size()); - assertEquals(1, ppt.getTitleMasters().size()); - boolean isFirst = true; - for (HSLFSlide slide : ppt.getSlides()) { - HSLFMasterSheet master = slide.getMasterSheet(); - // the first slide follows TitleMaster - assertTrue(isFirst ? master instanceof HSLFTitleMaster : master instanceof HSLFSlideMaster); - isFirst = false; - } - ppt.close(); - } - - /** - * Bug 42486: Failure parsing a seemingly valid PPT - */ - @SuppressWarnings("unused") - @Test - public void bug42486 () throws IOException { - HSLFSlideShow ppt = open("42486.ppt"); - for (HSLFSlide slide : ppt.getSlides()) { - List shape = slide.getShapes(); - } - ppt.close(); - } - - /** - * Bug 42524: NPE in Shape.getShapeType() - */ - @Test - public void bug42524 () throws IOException { - HSLFSlideShow ppt = open("42486.ppt"); - //walk down the tree and see if there were no errors while reading - for (HSLFSlide slide : ppt.getSlides()) { - for (HSLFShape shape : slide.getShapes()) { - assertNotNull(shape.getShapeName()); - if (shape instanceof HSLFGroupShape){ - HSLFGroupShape group = (HSLFGroupShape)shape; - for (HSLFShape comps : group.getShapes()) { - assertNotNull(comps.getShapeName()); - } - } - } - - } - ppt.close(); - } - - /** - * Bug 42520: NPE in Picture.getPictureData() - */ - @SuppressWarnings("unused") - @Test - public void bug42520 () throws IOException { - HSLFSlideShow ppt = open("42520.ppt"); - - //test case from the bug report - HSLFGroupShape shapeGroup = (HSLFGroupShape)ppt.getSlides().get(11).getShapes().get(10); - HSLFPictureShape picture = (HSLFPictureShape)shapeGroup.getShapes().get(0); - picture.getPictureData(); - - //walk down the tree and see if there were no errors while reading - for (HSLFSlide slide : ppt.getSlides()) { - for (HSLFShape shape : slide.getShapes()) { - if (shape instanceof HSLFGroupShape){ - HSLFGroupShape group = (HSLFGroupShape)shape; - for (HSLFShape comp : group.getShapes()) { - if (comp instanceof HSLFPictureShape){ - HSLFPictureData pict = ((HSLFPictureShape)comp).getPictureData(); - } - } - } - } - } - - ppt.close(); - } - - /** - * Bug 38256: RuntimeException: Couldn't instantiate the class for type with id 0. - * ( also fixed followup: getTextRuns() returns no text ) - */ - @Test - public void bug38256 () throws IOException { - HSLFSlideShow ppt = open("38256.ppt"); - - List slide = ppt.getSlides(); - assertEquals(1, slide.size()); - List> paras = slide.get(0).getTextParagraphs(); - assertEquals(4, paras.size()); - - Set txt = new HashSet(); - txt.add("\u201CHAPPY BIRTHDAY SCOTT\u201D"); - txt.add("Have a HAPPY DAY"); - txt.add("PS Nobody is allowed to hassle Scott TODAY\u2026"); - txt.add("Drinks will be in the Boardroom at 5pm today to celebrate Scott\u2019s B\u2019Day\u2026 See you all there!"); - - for (List para : paras) { - String text = HSLFTextParagraph.getRawText(para); - assertTrue(text, txt.contains(text)); - } - - ppt.close(); - } - - /** - * Bug 38256: RuntimeException: Couldn't instantiate the class for type with id 0. - * ( also fixed followup: getTextRuns() returns no text ) - */ - @Test - public void bug43781() throws IOException { - HSLFSlideShow ppt = open("43781.ppt"); - - // Check the first slide - HSLFSlide slide = ppt.getSlides().get(0); - List> slTr = slide.getTextParagraphs(); - - // Has 3 text paragraphs, two from slide text (empty title / filled body), one from drawing - assertEquals(3, slTr.size()); - assertFalse(slTr.get(0).get(0).isDrawingBased()); - assertFalse(slTr.get(1).get(0).isDrawingBased()); - assertTrue(slTr.get(2).get(0).isDrawingBased()); - assertEquals("", HSLFTextParagraph.getRawText(slTr.get(0))); - assertEquals("First run", HSLFTextParagraph.getRawText(slTr.get(1))); - assertEquals("Second run", HSLFTextParagraph.getRawText(slTr.get(2))); - - // Check the shape based text runs - List lst = new ArrayList(); - for (HSLFShape shape : slide.getShapes()) { - if (shape instanceof HSLFTextShape){ - List textRun = ((HSLFTextShape)shape).getTextParagraphs(); - lst.addAll(textRun); - } - - } - - // There are two shapes in the ppt - assertEquals(2, lst.size()); - assertEquals("First runSecond run", HSLFTextParagraph.getRawText(lst)); - ppt.close(); - } - - /** - * Bug 44296: HSLF Not Extracting Slide Background Image - */ - @Test - public void bug44296 () throws IOException { - HSLFSlideShow ppt = open("44296.ppt"); - - HSLFSlide slide = ppt.getSlides().get(0); - - HSLFBackground b = slide.getBackground(); - HSLFFill f = b.getFill(); - assertEquals(HSLFFill.FILL_PICTURE, f.getFillType()); - - HSLFPictureData pict = f.getPictureData(); - assertNotNull(pict); - assertEquals(PictureType.JPEG, pict.getType()); - - ppt.close(); - } - - /** - * Bug 44770: java.lang.RuntimeException: Couldn't instantiate the class for - * type with id 1036 on class class org.apache.poi.hslf.record.PPDrawing - */ - @Test - public void bug44770() throws IOException { - open("44770.ppt").close(); - } - - /** - * Bug 41071: Will not extract text from Powerpoint TextBoxes - */ - @Test - public void bug41071() throws IOException { - HSLFSlideShow ppt = open("41071.ppt"); - - HSLFSlide slide = ppt.getSlides().get(0); - List sh = slide.getShapes(); - assertEquals(1, sh.size()); - assertTrue(sh.get(0) instanceof HSLFTextShape); - HSLFTextShape tx = (HSLFTextShape)sh.get(0); - assertEquals("Fundera, planera och involvera.", HSLFTextParagraph.getRawText(tx.getTextParagraphs())); - - List> run = slide.getTextParagraphs(); - assertEquals(3, run.size()); - assertEquals("Fundera, planera och involvera.", HSLFTextParagraph.getRawText(run.get(2))); - - ppt.close(); - } - - /** - * PowerPoint 95 files should throw a more helpful exception - * @throws IOException - */ - @Test(expected=OldPowerPointFormatException.class) - public void bug41711() throws IOException { - // New file is fine - open("SampleShow.ppt").close(); - - // PowerPoint 95 gives an old format exception - open("PPT95.ppt").close(); - } - - /** - * Changing text from Ascii to Unicode - */ - @Test - public void bug49648() throws IOException { - HSLFSlideShow ppt = open("49648.ppt"); - for (HSLFSlide slide : ppt.getSlides()) { - for (List run : slide.getTextParagraphs()) { - String text = HSLFTextParagraph.getRawText(run); - text.replace("{txtTot}", "With \u0123\u1234\u5678 unicode"); - HSLFTextParagraph.setText(run, text); - } - } - ppt.close(); - } - - /** - * Bug 41246: AIOOB with illegal note references - */ - @Test - public void bug41246a() throws IOException { - HSLFSlideShow ppt = open("41246-1.ppt"); - - HSLFTestDataSamples.writeOutAndReadBack(ppt).close(); - - ppt.close(); - } - - @Test - public void bug41246b() throws IOException { - HSLFSlideShow ppt = open("41246-2.ppt"); - - HSLFTestDataSamples.writeOutAndReadBack(ppt).close(); - - ppt.close(); - } - - /** - * Bug 45776: Fix corrupt file problem using TextRun.setText - */ - @Test - public void bug45776() throws IOException { - HSLFSlideShow ppt = open("45776.ppt"); - - // get slides - for (HSLFSlide slide : ppt.getSlides()) { - for (HSLFShape shape : slide.getShapes()) { - if (!(shape instanceof HSLFTextBox)) { - continue; - } - HSLFTextBox tb = (HSLFTextBox) shape; - // work with TextBox - String str = tb.getText(); - - if (!str.contains("$$DATE$$")) { - continue; - } - str = str.replace("$$DATE$$", new Date().toString()); - tb.setText(str); - - List tr = tb.getTextParagraphs(); - assertEquals(str.length()+1,tr.get(0).getParagraphStyle().getCharactersCovered()); - assertEquals(str.length()+1,tr.get(0).getTextRuns().get(0).getCharacterStyle().getCharactersCovered()); - } - } - - ppt.close(); - } - - @Test - public void bug55732() throws IOException { - HSLFSlideShow ppt = open("bug55732.ppt"); - - List _slides = ppt.getSlides(); - - /* Iterate over slides and extract text */ - for( HSLFSlide slide : _slides ) { - HeadersFooters hf = slide.getHeadersFooters(); - /*boolean visible =*/ hf.isHeaderVisible(); // exception happens here - } - - ppt.close(); - } - - @Test - public void bug56260() throws IOException { - HSLFSlideShow ppt = open("56260.ppt"); - List _slides = ppt.getSlides(); - assertEquals(13, _slides.size()); - - // Check the number of TextHeaderAtoms on Slide 1 - Document dr = ppt.getDocumentRecord(); - SlideListWithText slidesSLWT = dr.getSlideSlideListWithText(); - SlideAtomsSet s1 = slidesSLWT.getSlideAtomsSets()[0]; - - int tha = 0; - for (Record r : s1.getSlideRecords()) { - if (r instanceof TextHeaderAtom) { - tha++; - } - } - assertEquals(2, tha); - - // Check to see that we have a pair next to each other - assertEquals(TextHeaderAtom.class, s1.getSlideRecords()[0].getClass()); - assertEquals(TextHeaderAtom.class, s1.getSlideRecords()[1].getClass()); - - - // Check the number of text runs based on the slide (not textbox) - // Will have skipped the empty one - int str = 0; - for (List tr : _slides.get(0).getTextParagraphs()) { - if (! tr.get(0).isDrawingBased()) { - str++; - } - } - assertEquals(2, str); - - ppt.close(); - } - - @Test - public void bug37625() throws IOException { - HSLFSlideShow ppt1 = open("37625.ppt"); - assertEquals(29, ppt1.getSlides().size()); - - HSLFSlideShow ppt2 = HSLFTestDataSamples.writeOutAndReadBack(ppt1); - assertNotNull(ppt2); - assertEquals(29, ppt2.getSlides().size()); - ppt2.close(); - ppt1.close(); - } - - @Test - public void bug57272() throws IOException { - HSLFSlideShow ppt1 = open("57272_corrupted_usereditatom.ppt"); - assertEquals(6, ppt1.getSlides().size()); - - HSLFSlideShow ppt2 = HSLFTestDataSamples.writeOutAndReadBack(ppt1); - assertNotNull(ppt2); - assertEquals(6, ppt2.getSlides().size()); - ppt2.close(); - ppt1.close(); - } - - @Test - public void bug49541() throws IOException { - HSLFSlideShow ppt = open("49541_symbol_map.ppt"); - HSLFSlide slide = ppt.getSlides().get(0); - HSLFGroupShape sg = (HSLFGroupShape)slide.getShapes().get(0); - HSLFTextBox tb = (HSLFTextBox)sg.getShapes().get(0); - String text = StringUtil.mapMsCodepointString(tb.getText()); - assertEquals("\u226575 years", text); - ppt.close(); - } - - @Test - public void bug47261() throws IOException { - HSLFSlideShow ppt = open("bug47261.ppt"); - ppt.removeSlide(0); - ppt.createSlide(); - HSLFTestDataSamples.writeOutAndReadBack(ppt).close(); - ppt.close(); - } - - @Test - public void bug56240() throws IOException { - HSLFSlideShow ppt = open("bug56240.ppt"); - int slideCnt = ppt.getSlides().size(); - assertEquals(105, slideCnt); - HSLFTestDataSamples.writeOutAndReadBack(ppt).close(); - ppt.close(); - } - - @Test - public void bug46441() throws IOException { - HSLFSlideShow ppt = open("bug46441.ppt"); - HSLFAutoShape as = (HSLFAutoShape)ppt.getSlides().get(0).getShapes().get(0); - AbstractEscherOptRecord opt = as.getEscherOptRecord(); - EscherArrayProperty ep = HSLFShape.getEscherProperty(opt, EscherProperties.FILL__SHADECOLORS); - double exp[][] = { - // r, g, b, position - { 94, 158, 255, 0 }, - { 133, 194, 255, 0.399994 }, - { 196, 214, 235, 0.699997 }, - { 255, 235, 250, 1 } - }; - - int i = 0; - for (byte data[] : ep) { - EscherColorRef ecr = new EscherColorRef(data, 0, 4); - int rgb[] = ecr.getRGB(); - double pos = Units.fixedPointToDouble(LittleEndian.getInt(data, 4)); - assertEquals((int)exp[i][0], rgb[0]); - assertEquals((int)exp[i][1], rgb[1]); - assertEquals((int)exp[i][2], rgb[2]); - assertEquals(exp[i][3], pos, 0.01); - i++; - } - ppt.close(); - } - - @Test - public void bug58516() throws IOException { - open("bug58516.ppt").close(); - } - - @Test - public void bug45124() throws IOException { - SlideShow ppt = open("bug45124.ppt"); - Slide slide1 = ppt.getSlides().get(1); - - TextBox res = slide1.createTextBox(); - res.setAnchor(new java.awt.Rectangle(60, 150, 700, 100)); - res.setText("I am italic-false, bold-true inserted text"); - - - TextParagraph tp = res.getTextParagraphs().get(0); - TextRun rt = tp.getTextRuns().get(0); - rt.setItalic(false); - assertTrue(rt.isBold()); - - tp.setBulletStyle(Color.red, 'A'); - - SlideShow ppt2 = HSLFTestDataSamples.writeOutAndReadBack((HSLFSlideShow)ppt); - ppt.close(); - - res = (TextBox)ppt2.getSlides().get(1).getShapes().get(1); - tp = res.getTextParagraphs().get(0); - rt = tp.getTextRuns().get(0); - - assertFalse(rt.isItalic()); - assertTrue(rt.isBold()); - PaintStyle ps = tp.getBulletStyle().getBulletFontColor(); - assertTrue(ps instanceof SolidPaint); - Color actColor = DrawPaint.applyColorTransform(((SolidPaint)ps).getSolidColor()); - assertEquals(Color.red, actColor); - assertEquals("A", tp.getBulletStyle().getBulletCharacter()); - - ppt2.close(); - } - - @Test - public void bug45088() throws IOException { - String template = "[SYSDATE]"; - String textExp = "REPLACED_DATE_WITH_A_LONG_ONE"; - - HSLFSlideShow ppt1 = open("bug45088.ppt"); - for (HSLFSlide slide : ppt1.getSlides()) { - for (List paraList : slide.getTextParagraphs()) { - for (HSLFTextParagraph para : paraList) { - for (HSLFTextRun run : para.getTextRuns()) { - String text = run.getRawText(); - if (text != null && text.contains(template)) { - String replacedText = text.replace(template, textExp); - run.setText(replacedText); - para.setDirty(); - } - } - } - } - } - - HSLFSlideShow ppt2 = HSLFTestDataSamples.writeOutAndReadBack(ppt1); - ppt1.close(); - - HSLFTextBox tb = (HSLFTextBox)ppt2.getSlides().get(0).getShapes().get(1); - String textAct = tb.getTextParagraphs().get(0).getTextRuns().get(0).getRawText().trim(); - assertEquals(textExp, textAct); - ppt2.close(); - } - - @Test - public void bug45908() throws IOException { - HSLFSlideShow ppt1 = open("bug45908.ppt"); - - HSLFSlide slide = ppt1.getSlides().get(0); - HSLFAutoShape styleShape = (HSLFAutoShape)slide.getShapes().get(1); - HSLFTextParagraph tp0 = styleShape.getTextParagraphs().get(0); - HSLFTextRun tr0 = tp0.getTextRuns().get(0); - - - int rows = 5; - int cols = 2; - HSLFTable table = slide.createTable(rows, cols); - for (int i = 0; i < rows; i++) { - for (int j = 0; j < cols; j++) { - - HSLFTableCell cell = table.getCell(i, j); - cell.setText("Test"); - - HSLFTextParagraph tp = cell.getTextParagraphs().get(0); - tp.setBulletStyle('%', tp0.getBulletColor(), tp0.getBulletFont(), tp0.getBulletSize()); - tp.setIndent(tp0.getIndent()); - tp.setTextAlign(tp0.getTextAlign()); - tp.setIndentLevel(tp0.getIndentLevel()); - tp.setSpaceAfter(tp0.getSpaceAfter()); - tp.setSpaceBefore(tp0.getSpaceBefore()); - tp.setBulletStyle(); - - HSLFTextRun tr = tp.getTextRuns().get(0); - tr.setBold(tr0.isBold()); - // rt.setEmbossed(); - tr.setFontColor(Color.BLACK); - tr.setFontFamily(tr0.getFontFamily()); - tr.setFontSize(tr0.getFontSize()); - tr.setItalic(tr0.isItalic()); - tr.setShadowed(tr0.isShadowed()); - tr.setStrikethrough(tr0.isStrikethrough()); - tr.setUnderlined(tr0.isUnderlined()); - } - } - - table.moveTo(100, 100); - - HSLFSlideShow ppt2 = HSLFTestDataSamples.writeOutAndReadBack(ppt1); - ppt1.close(); - - HSLFTable tab = (HSLFTable)ppt2.getSlides().get(0).getShapes().get(2); - HSLFTableCell c2 = tab.getCell(0, 0); - HSLFTextParagraph tp1 = c2.getTextParagraphs().get(0); - HSLFTextRun tr1 = tp1.getTextRuns().get(0); - assertFalse(tp1.isBullet()); - assertEquals(tp0.getBulletColor(), tp1.getBulletColor()); - assertEquals(tp0.getBulletFont(), tp1.getBulletFont()); - assertEquals(tp0.getBulletSize(), tp1.getBulletSize()); - assertEquals(tp0.getIndent(), tp1.getIndent()); - assertEquals(tp0.getTextAlign(), tp1.getTextAlign()); - assertEquals(tp0.getIndentLevel(), tp1.getIndentLevel()); - assertEquals(tp0.getSpaceAfter(), tp1.getSpaceAfter()); - assertEquals(tp0.getSpaceBefore(), tp1.getSpaceBefore()); - assertEquals(tr0.isBold(), tr1.isBold()); - assertEquals(Color.black, DrawPaint.applyColorTransform(tr1.getFontColor().getSolidColor())); - assertEquals(tr0.getFontFamily(), tr1.getFontFamily()); - assertEquals(tr0.getFontSize(), tr1.getFontSize()); - assertEquals(tr0.isItalic(), tr1.isItalic()); - assertEquals(tr0.isShadowed(), tr1.isShadowed()); - assertEquals(tr0.isStrikethrough(), tr1.isStrikethrough()); - assertEquals(tr0.isUnderlined(), tr1.isUnderlined()); - - ppt2.close(); - } - - @Test - public void bug47904() throws IOException { - HSLFSlideShow ppt1 = new HSLFSlideShow(); - HSLFSlideMaster sm = ppt1.getSlideMasters().get(0); - HSLFAutoShape as = (HSLFAutoShape)sm.getPlaceholder(Placeholder.TITLE); - HSLFTextParagraph tp = as.getTextParagraphs().get(0); - HSLFTextRun tr = tp.getTextRuns().get(0); - tr.setFontFamily("Tahoma"); - tr.setShadowed(true); - tr.setFontSize(44.); - tr.setFontColor(Color.red); - tp.setTextAlign(TextAlign.RIGHT); - HSLFTextBox tb = ppt1.createSlide().addTitle(); - tb.setText("foobaa"); - - HSLFSlideShow ppt2 = HSLFTestDataSamples.writeOutAndReadBack(ppt1); - ppt1.close(); - - HSLFTextShape ts = (HSLFTextShape)ppt2.getSlides().get(0).getShapes().get(0); - tp = ts.getTextParagraphs().get(0); - tr = tp.getTextRuns().get(0); - assertEquals(44., tr.getFontSize(), 0); - assertEquals("Tahoma", tr.getFontFamily()); - Color colorAct = DrawPaint.applyColorTransform(tr.getFontColor().getSolidColor()); - assertEquals(Color.red, colorAct); - assertEquals(TextAlign.RIGHT, tp.getTextAlign()); - assertEquals("foobaa", tr.getRawText()); - ppt2.close(); - } - - @Test - public void bug58718() throws IOException { - String files[] = { "bug58718_008524.ppt","bug58718_008558.ppt","bug58718_349008.ppt","bug58718_008495.ppt", }; - for (String f : files) { - File sample = HSLFTestDataSamples.getSampleFile(f); - PowerPointExtractor ex = new PowerPointExtractor(sample.getAbsolutePath()); - assertNotNull(ex.getText()); - ex.close(); - } - } - - @Test - public void bug58733() throws IOException { - File sample = HSLFTestDataSamples.getSampleFile("bug58733_671884.ppt"); - PowerPointExtractor ex = new PowerPointExtractor(sample.getAbsolutePath()); - assertNotNull(ex.getText()); - ex.close(); - } - - @Test - public void bug58159() throws IOException { - HSLFSlideShow ppt = open("bug58159_headers-and-footers.ppt"); - HeadersFooters hf = ppt.getSlideHeadersFooters(); - assertNull(hf.getHeaderText()); - assertEquals("Slide footer", hf.getFooterText()); - hf = ppt.getNotesHeadersFooters(); - assertEquals("Notes header", hf.getHeaderText()); - assertEquals("Notes footer", hf.getFooterText()); - HSLFSlide sl = ppt.getSlides().get(0); - hf = sl.getHeadersFooters(); - assertNull(hf.getHeaderText()); - assertEquals("Slide footer", hf.getFooterText()); - for (HSLFShape shape : sl.getShapes()) { - if (shape instanceof HSLFTextShape) { - HSLFTextShape ts = (HSLFTextShape)shape; - Placeholder ph = ts.getPlaceholder(); - if (Placeholder.FOOTER == ph) { - assertEquals("Slide footer", ts.getText()); - } - } - } - ppt.close(); - } - - @Test - public void bug55030() throws IOException { - HSLFSlideShow ppt = open("bug55030.ppt"); - - String expFamily = "\u96b6\u4e66"; - - HSLFSlide sl = ppt.getSlides().get(0); - for (List paraList : sl.getTextParagraphs()) { - for (HSLFTextParagraph htp : paraList) { - for (HSLFTextRun htr : htp) { - String actFamily = htr.getFontFamily(); - assertEquals(expFamily, actFamily); - } - } - } - - ppt.close(); - } - - @Test - public void bug57796() throws IOException { - HSLFSlideShow ppt = open("WithLinks.ppt"); - HSLFSlide slide = ppt.getSlides().get(0); - HSLFTextShape shape = (HSLFTextShape)slide.getShapes().get(1); - List hlList = HSLFHyperlink.find(shape); - HSLFHyperlink hlShape = hlList.get(0); - HSLFTextRun r = shape.getTextParagraphs().get(1).getTextRuns().get(0); - HSLFHyperlink hlRun = r.getHyperlink(); - assertEquals(hlRun.getId(), hlShape.getId()); - assertEquals(hlRun.getAddress(), hlShape.getAddress()); - assertEquals(hlRun.getLabel(), hlShape.getLabel()); - assertEquals(hlRun.getTypeEnum(), hlShape.getTypeEnum()); - assertEquals(hlRun.getStartIndex(), hlShape.getStartIndex()); - assertEquals(hlRun.getEndIndex(), hlShape.getEndIndex()); - - OutputStream nullOutput = new OutputStream(){ - @Override - public void write(int b) throws IOException {} - }; - - final boolean found[] = { false }; - DummyGraphics2d dgfx = new DummyGraphics2d(new PrintStream(nullOutput)){ - @Override - public void drawString(AttributedCharacterIterator iterator, float x, float y) { - // For the test file, common sl draws textruns one by one and not mixed - // so we evaluate the whole iterator - Map attributes = null; - StringBuffer sb = new StringBuffer(); - - for (char c = iterator.first(); - c != CharacterIterator.DONE; - c = iterator.next()) { - sb.append(c); - attributes = iterator.getAttributes(); - } - - if ("Jakarta HSSF".equals(sb.toString())) { - // this is a test for a manually modified ppt, for real hyperlink label - // one would need to access the screen tip record - String href = (String)attributes.get(DrawTextParagraph.HYPERLINK_HREF); - String label = (String)attributes.get(DrawTextParagraph.HYPERLINK_LABEL); - assertEquals("http://jakarta.apache.org/poi/hssf/", href); - assertEquals("Open Jakarta POI HSSF module test ", label); - found[0] = true; - } - } - }; - - ppt.getSlides().get(1).draw(dgfx); - assertTrue(found[0]); - - ppt.close(); - } - - @Test - public void bug59056() throws IOException { - HSLFSlideShow ppt = open("54541_cropped_bitmap.ppt"); - - for (HSLFShape shape : ppt.getSlides().get(0).getShapes()) { - BufferedImage img = new BufferedImage(500, 300, BufferedImage.TYPE_INT_ARGB); - Graphics2D graphics = img.createGraphics(); - Rectangle2D box = new Rectangle2D.Double(50,50,300,100); - graphics.setPaint(Color.red); - graphics.fill(box); - box = new Rectangle2D.Double(box.getX()+1,box.getY()+1,box.getWidth()-2,box.getHeight()-2); - DrawFactory.getInstance(graphics).drawShape(graphics, shape, box); - graphics.dispose(); - // ImageIO.write(img, "png", new File("bla"+shape.getShapeId()+".png")); - } - - ppt.close(); - - } - - private static HSLFSlideShow open(String fileName) throws IOException { - File sample = HSLFTestDataSamples.getSampleFile(fileName); - return (HSLFSlideShow)SlideShowFactory.create(sample); - } - - @Test - public void bug55983() throws IOException { - HSLFSlideShow ppt1 = new HSLFSlideShow(); - HSLFSlide sl = ppt1.createSlide(); - sl.getBackground().getFill().setForegroundColor(Color.blue); - HSLFFreeformShape fs = sl.createFreeform(); - Ellipse2D.Double el = new Ellipse2D.Double(0,0,300,200); - fs.setAnchor(new Rectangle2D.Double(100,100,300,200)); - fs.setPath(new Path2D.Double(el)); - Color cExp = new Color(50,100,150,200); - fs.setFillColor(cExp); - - HSLFSlideShow ppt2 = HSLFTestDataSamples.writeOutAndReadBack(ppt1); - ppt1.close(); - - sl = ppt2.getSlides().get(0); - fs = (HSLFFreeformShape)sl.getShapes().get(0); - Color cAct = fs.getFillColor(); - assertEquals(cExp.getRed(), cAct.getRed()); - assertEquals(cExp.getGreen(), cAct.getGreen()); - assertEquals(cExp.getBlue(), cAct.getBlue()); - assertEquals(cExp.getAlpha(), cAct.getAlpha(), 1); - - PaintStyle ps = fs.getFillStyle().getPaint(); - assertTrue(ps instanceof SolidPaint); - ColorStyle cs = ((SolidPaint)ps).getSolidColor(); - cAct = cs.getColor(); - assertEquals(cExp.getRed(), cAct.getRed()); - assertEquals(cExp.getGreen(), cAct.getGreen()); - assertEquals(cExp.getBlue(), cAct.getBlue()); - assertEquals(255, cAct.getAlpha()); - assertEquals(cExp.getAlpha()*100000./255., cs.getAlpha(), 1); - - ppt2.close(); - } - - @Test - public void bug59302() throws IOException { - //add extraction from PPT - Map macros = getMacrosFromHSLF("59302.ppt"); - assertNotNull("couldn't find macros", macros); - assertNotNull("couldn't find second module", macros.get("Module2")); - assertContains(macros.get("Module2"), "newMacro in Module2"); - - assertNotNull("couldn't find first module", macros.get("Module1")); - assertContains(macros.get("Module1"), "Italicize"); - - macros = getMacrosFromHSLF("SimpleMacro.ppt"); - assertNotNull(macros.get("Module1")); - assertContains(macros.get("Module1"), "This is a macro slideshow"); - } - - //It isn't pretty, but it works... - private Map getMacrosFromHSLF(String fileName) throws IOException { - InputStream is = null; - NPOIFSFileSystem npoifs = null; - try { - is = new FileInputStream(POIDataSamples.getSlideShowInstance().getFile(fileName)); - npoifs = new NPOIFSFileSystem(is); - //TODO: should we run the VBAMacroReader on this npoifs? - //TBD: We know that ppt typically don't store macros in the regular place, - //but _can_ they? - - HSLFSlideShow ppt = new HSLFSlideShow(npoifs); - - //get macro persist id - DocInfoListContainer list = (DocInfoListContainer)ppt.getDocumentRecord().findFirstOfType(RecordTypes.List.typeID); - VBAInfoContainer vbaInfo = (VBAInfoContainer)list.findFirstOfType(RecordTypes.VBAInfo.typeID); - VBAInfoAtom vbaAtom = (VBAInfoAtom)vbaInfo.findFirstOfType(RecordTypes.VBAInfoAtom.typeID); - long persistId = vbaAtom.getPersistIdRef(); - for (HSLFObjectData objData : ppt.getEmbeddedObjects()) { - if (objData.getExOleObjStg().getPersistId() == persistId) { - VBAMacroReader mr = new VBAMacroReader(objData.getData()); - try { - return mr.readMacros(); - } finally { - mr.close(); - } - } - } - - ppt.close(); - - } finally { - IOUtils.closeQuietly(npoifs); - IOUtils.closeQuietly(is); - } - return null; - } - - /** - * Bug 60294: Add "unknown" ShapeType for 4095 - */ - @Test - public void bug60294() throws IOException { - HSLFSlideShow ppt = open("60294.ppt"); - List shList = ppt.getSlides().get(0).getShapes(); - assertEquals(ShapeType.NOT_PRIMITIVE, ((HSLFAutoShape)shList.get(2)).getShapeType()); - ppt.close(); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestCounts.java b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestCounts.java deleted file mode 100644 index baed0386d..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestCounts.java +++ /dev/null @@ -1,79 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.usermodel; - - -import static org.junit.Assert.assertEquals; - -import java.io.IOException; -import java.util.List; - -import org.apache.poi.hslf.HSLFTestDataSamples; -import org.junit.Test; - -/** - * Tests that SlideShow returns the right number of Sheets and MetaSheets - */ -public final class TestCounts { - @Test - public void testSheetsCount() throws IOException { - HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow("basic_test_ppt_file.ppt"); - - List slides = ppt.getSlides(); - // Two sheets - master sheet is separate - assertEquals(2, slides.size()); - - // They are slides 1+2 - assertEquals(1, slides.get(0).getSlideNumber()); - assertEquals(2, slides.get(1).getSlideNumber()); - - // The ref IDs are 4 and 6 - assertEquals(4, slides.get(0)._getSheetRefId()); - assertEquals(6, slides.get(1)._getSheetRefId()); - - // These are slides 1+2 -> 256+257 - assertEquals(256, slides.get(0)._getSheetNumber()); - assertEquals(257, slides.get(1)._getSheetNumber()); - - ppt.close(); - } - - @Test - public void testNotesCount() throws IOException { - HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow("basic_test_ppt_file.ppt"); - - List notes = ppt.getNotes(); - // Two sheets -> two notes - // Note: there are also notes on the slide master - //assertEquals(3, notes.length); // When we do slide masters - assertEquals(2, notes.size()); - - // First is for master - //assertEquals(-2147483648, notes.get(0)._getSheetNumber()); // When we do slide masters - - // Next two are for the two slides - assertEquals(256, notes.get(0)._getSheetNumber()); - assertEquals(257, notes.get(1)._getSheetNumber()); - - // They happen to go between the two slides in Ref terms - assertEquals(5, notes.get(0)._getSheetRefId()); - assertEquals(7, notes.get(1)._getSheetRefId()); - - ppt.close(); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestFontRendering.java b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestFontRendering.java deleted file mode 100644 index e768d7935..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestFontRendering.java +++ /dev/null @@ -1,121 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.usermodel; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assume.assumeTrue; - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Font; -import java.awt.Graphics2D; -import java.awt.GraphicsEnvironment; -import java.awt.RenderingHints; -import java.awt.geom.AffineTransform; -import java.awt.geom.Rectangle2D; -import java.awt.image.BufferedImage; -import java.awt.image.DataBufferByte; -import java.io.File; -import java.io.InputStream; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -import javax.imageio.ImageIO; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.sl.draw.Drawable; -import org.apache.poi.util.TempFile; -import org.junit.Test; - -/** - * Test font rendering of alternative and fallback fonts - */ -public class TestFontRendering { - private static POIDataSamples slTests = POIDataSamples.getSlideShowInstance(); - - // @Ignore2("This fails on some systems because fonts are rendered slightly different") - @Test - public void bug55902mixedFontWithChineseCharacters() throws Exception { - // font files need to be downloaded first via - // ant test-scratchpad-download-resources - String fontFiles[][] = { - // Calibri is not available on *nix systems, so we need to use another similar free font - { "build/scratchpad-test-resources/Cabin-Regular.ttf", "mapped", "Calibri" }, - - // use "MS PGothic" if available (Windows only) ... - // for the junit test not all chars are rendered - { "build/scratchpad-test-resources/mona.ttf", "fallback", "Cabin" } - }; - - // setup fonts (especially needed, when run under *nix systems) - GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); - Map fontMap = new HashMap(); - Map fallbackMap = new HashMap(); - - for (String fontFile[] : fontFiles) { - File f = new File(fontFile[0]); - assumeTrue("necessary font file "+f.getName()+" not downloaded.", f.exists()); - - Font font = Font.createFont(Font.TRUETYPE_FONT, f); - ge.registerFont(font); - - Map map = ("mapped".equals(fontFile[1]) ? fontMap : fallbackMap); - map.put(fontFile[2], font.getFamily()); - } - - InputStream is = slTests.openResourceAsStream("bug55902-mixedFontChineseCharacters.ppt"); - HSLFSlideShow ss = new HSLFSlideShow(is); - is.close(); - - Dimension pgsize = ss.getPageSize(); - - HSLFSlide slide = ss.getSlides().get(0); - - // render it - double zoom = 1; - AffineTransform at = new AffineTransform(); - at.setToScale(zoom, zoom); - - BufferedImage imgActual = new BufferedImage((int)Math.ceil(pgsize.width*zoom), (int)Math.ceil(pgsize.height*zoom), BufferedImage.TYPE_3BYTE_BGR); - Graphics2D graphics = imgActual.createGraphics(); - graphics.setRenderingHint(Drawable.FONT_FALLBACK, fallbackMap); - graphics.setRenderingHint(Drawable.FONT_MAP, fontMap); - graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); - graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); - graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); - graphics.setTransform(at); - graphics.setPaint(Color.white); - graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height)); - slide.draw(graphics); - - BufferedImage imgExpected = ImageIO.read(slTests.getFile("bug55902-mixedChars.png")); - DataBufferByte expectedDB = (DataBufferByte)imgExpected.getRaster().getDataBuffer(); - DataBufferByte actualDB = (DataBufferByte)imgActual.getRaster().getDataBuffer(); - byte[] expectedData = expectedDB.getData(0); - byte[] actualData = actualDB.getData(0); - - // allow to find out what the actual difference is in CI where this fails currently - if(!Arrays.equals(expectedData, actualData)) { - ImageIO.write(imgActual, "PNG", TempFile.createTempFile("TestFontRendering", ".png")); - } - - assertArrayEquals("Expected to have matching raster-arrays, but found differences", expectedData, actualData); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestHSLFSlideShow.java b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestHSLFSlideShow.java deleted file mode 100644 index 7f5385e35..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestHSLFSlideShow.java +++ /dev/null @@ -1,35 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hslf.usermodel; - -import static org.junit.Assert.assertNotNull; - -import org.apache.poi.sl.usermodel.BaseTestSlideShow; -import org.junit.Test; - -public class TestHSLFSlideShow extends BaseTestSlideShow { - @Override - public HSLFSlideShow createSlideShow() { - return new HSLFSlideShow(); - } - - // make sure junit4 executes this test class - @Test - public void dummy() { - assertNotNull(createSlideShow()); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestHSLFSlideShowFactory.java b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestHSLFSlideShowFactory.java deleted file mode 100644 index 9c305ef6b..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestHSLFSlideShowFactory.java +++ /dev/null @@ -1,28 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.usermodel; - -import org.apache.poi.sl.usermodel.BaseTestSlideShowFactory; -import org.junit.Test; - -public final class TestHSLFSlideShowFactory extends BaseTestSlideShowFactory { - @Test - public void testFactory() throws Exception { - testFactory("pictures.ppt", "Password_Protected-hello.ppt", "hello"); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestMostRecentRecords.java b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestMostRecentRecords.java deleted file mode 100644 index a7e2a62d5..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestMostRecentRecords.java +++ /dev/null @@ -1,97 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.usermodel; - - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hslf.record.Record; - -import junit.framework.TestCase; - -/** - * Tests that SlideShow finds the right records as its most recent ones - * - * @author Nick Burch (nick at torchbox dot com) - */ -public final class TestMostRecentRecords extends TestCase { - // HSLFSlideShow primed on the test data - private final HSLFSlideShowImpl hss; - // SlideShow primed on the test data - private final HSLFSlideShow ss; - - public TestMostRecentRecords() throws Exception { - POIDataSamples slTests = POIDataSamples.getSlideShowInstance(); - hss = new HSLFSlideShowImpl(slTests.openResourceAsStream("basic_test_ppt_file.ppt")); - ss = new HSLFSlideShow(hss); - } - - public void testCount() { - // Most recent core records - Record[] mrcr = ss.getMostRecentCoreRecords(); - - // Master sheet + master notes + 2 slides + 2 notes + document - assertEquals(7, mrcr.length); - } - - public void testRightRecordTypes() { - // Most recent core records - Record[] mrcr = ss.getMostRecentCoreRecords(); - - // Document - assertEquals(1000, mrcr[0].getRecordType()); - // Notes of master - assertEquals(1008, mrcr[1].getRecordType()); - // Master - assertEquals(1016, mrcr[2].getRecordType()); - - // Slide - assertEquals(1006, mrcr[3].getRecordType()); - // Notes - assertEquals(1008, mrcr[4].getRecordType()); - // Slide - assertEquals(1006, mrcr[5].getRecordType()); - // Notes - assertEquals(1008, mrcr[6].getRecordType()); - } - - public void testCorrectRecords() { - // Most recent core records - Record[] mrcr = ss.getMostRecentCoreRecords(); - - // All records - Record[] allr = hss.getRecords(); - - // Ensure they are the right (latest) version of each - - // Document - late version - assertEquals(allr[12], mrcr[0]); - // Notes of master - unchanged - assertEquals(allr[2], mrcr[1]); - // Master - unchanged - assertEquals(allr[1], mrcr[2]); - - // Slide - added at start - assertEquals(allr[3], mrcr[3]); - // Notes - added at start - assertEquals(allr[4], mrcr[4]); - // Slide - added later and then changed - assertEquals(allr[13], mrcr[5]); - // Notes - added later but not changed - assertEquals(allr[9], mrcr[6]); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestNotesText.java b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestNotesText.java deleted file mode 100644 index 59c5c65a7..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestNotesText.java +++ /dev/null @@ -1,58 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.usermodel; - - -import org.apache.poi.POIDataSamples; - -import junit.framework.TestCase; - -/** - * Tests that SlideShow returns MetaSheets which have the right text in them - * - * @author Nick Burch (nick at torchbox dot com) - */ -public final class TestNotesText extends TestCase { - // SlideShow primed on the test data - private final HSLFSlideShow ss; - - public TestNotesText() throws Exception { - POIDataSamples slTests = POIDataSamples.getSlideShowInstance(); - HSLFSlideShowImpl hss = new HSLFSlideShowImpl(slTests.openResourceAsStream("basic_test_ppt_file.ppt")); - ss = new HSLFSlideShow(hss); - } - - public void testNotesOne() { - HSLFNotes notes = ss.getNotes().get(0); - - String[] expectText = new String[] {"These are the notes for page 1"}; - assertEquals(expectText.length, notes.getTextParagraphs().size()); - for(int i=0; i slides = ppt.getSlides(); - assertEquals(2, slides.size()); - checkSlide0(slides.get(0)); - checkSlide1(slides.get(1)); - ppt.close(); - } - - private void checkSlide0(final HSLFSlide s) { - final StyleTextProp9Atom[] numberedListArray = s.getNumberedListInfo(); - assertNotNull(numberedListArray); - assertEquals(1, numberedListArray.length);//Just one text box here - final StyleTextProp9Atom numberedListInfo = numberedListArray[0]; - assertNotNull(numberedListInfo); - final TextPFException9[] autoNumbers = numberedListInfo.getAutoNumberTypes(); - assertNotNull(autoNumbers); - assertEquals(4, autoNumbers.length); - assertTrue(4 == autoNumbers[0].getAutoNumberStartNumber()); - assertNull(autoNumbers[1].getAutoNumberStartNumber()); - assertTrue(3 == autoNumbers[2].getAutoNumberStartNumber()); - assertTrue(AutoNumberingScheme.arabicPeriod == autoNumbers[0].getAutoNumberScheme()); - assertNull(autoNumbers[1].getAutoNumberScheme()); - assertTrue(AutoNumberingScheme.alphaLcParenRight == autoNumbers[2].getAutoNumberScheme()); - - List> textParass = s.getTextParagraphs(); - assertEquals(2, textParass.size()); - - List textParas = textParass.get(0); - assertEquals("titTe", HSLFTextParagraph.getRawText(textParas)); - assertEquals(1, textParas.size()); - assertFalse(textParas.get(0).isBullet()); - - String expected = - "This is a text placeholder that \r" + - "follows the design pattern\r" + - "Just a test\rWithout any paragraph\r" + - "Second paragraph first line c) ;\r" + - "Second paragraph second line d) . \r"; - assertEquals(expected, HSLFTextParagraph.getRawText(textParass.get(1))); - - final EscherTextboxWrapper[] styleAtoms = s.getTextboxWrappers(); - assertEquals(textParass.size(), styleAtoms.length); - final EscherTextboxWrapper wrapper = styleAtoms[1]; - final StyleTextPropAtom styleTextPropAtom = wrapper.getStyleTextPropAtom(); - final List textProps = styleTextPropAtom.getCharacterStyles(); - assertEquals(60, textProps.get(0).getCharactersCovered()); - assertEquals(34, textProps.get(1).getCharactersCovered()); - assertEquals(68, textProps.get(2).getCharactersCovered()); - } - - private void checkSlide1(final HSLFSlide s) { - final StyleTextProp9Atom[] numberedListArray = s.getNumberedListInfo(); - assertNotNull(numberedListArray); - assertEquals(1, numberedListArray.length);//Just one text box here - final StyleTextProp9Atom numberedListInfo = numberedListArray[0]; - assertNotNull(numberedListInfo); - final TextPFException9[] autoNumbers = numberedListInfo.getAutoNumberTypes(); - assertNotNull(autoNumbers); - assertEquals(4, autoNumbers.length); - assertTrue(9 == autoNumbers[0].getAutoNumberStartNumber()); - assertNull(autoNumbers[1].getAutoNumberStartNumber()); - assertTrue(3 == autoNumbers[2].getAutoNumberStartNumber()); - assertTrue(AutoNumberingScheme.arabicParenRight == autoNumbers[0].getAutoNumberScheme()); - assertNull(autoNumbers[1].getAutoNumberScheme()); - assertTrue(AutoNumberingScheme.alphaUcPeriod == autoNumbers[2].getAutoNumberScheme()); - - final List> textParass = s.getTextParagraphs(); - assertEquals(2, textParass.size()); - - List textParas = textParass.get(0); - assertEquals("Second Slide Title", HSLFTextParagraph.getRawText(textParas)); - assertEquals(1, textParas.size()); - assertFalse(textParas.get(0).isBullet()); - - String expected = - "This is a text placeholder that \r" + - "follows the design pattern\r" + - "Just a test\rWithout any paragraph\r" + - "Second paragraph first line c) ;\r" + - "Second paragraph second line d) . \r"; - assertEquals(expected, HSLFTextParagraph.getRawText(textParass.get(1))); - - final EscherTextboxWrapper[] styleAtoms = s.getTextboxWrappers(); - assertEquals(textParass.size(), styleAtoms.length); - final EscherTextboxWrapper wrapper = styleAtoms[1]; - final StyleTextPropAtom styleTextPropAtom = wrapper.getStyleTextPropAtom(); - final List textProps = styleTextPropAtom.getCharacterStyles(); - - assertEquals(33, textProps.get(0).getCharactersCovered()); - assertEquals(61, textProps.get(1).getCharactersCovered()); - assertEquals(68, textProps.get(2).getCharactersCovered()); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestNumberedList2.java b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestNumberedList2.java deleted file mode 100644 index 297f57c61..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestNumberedList2.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.hslf.usermodel; - -import static org.junit.Assert.*; - -import java.util.List; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hslf.model.textproperties.TextPFException9; -import org.apache.poi.hslf.model.textproperties.TextPropCollection; -import org.apache.poi.hslf.record.*; -import org.apache.poi.sl.usermodel.AutoNumberingScheme; -import org.junit.Test; - - -/** - * Test that checks numbered list functionality. - * if a paragraph has autonumber () - * @see - * PPT: Missing TextAutoNumberScheme structure providing the style of the number bullets - * - * @author Alex Nikiforov [mailto:anikif@gmail.com] - */ -public final class TestNumberedList2 { - private static POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); - - @Test - public void testNumberedList() throws Exception { - HSLFSlideShow ppt = new HSLFSlideShow(_slTests.openResourceAsStream("numbers2.ppt")); - assertTrue("No Exceptions while reading file", true); - - final List slides = ppt.getSlides(); - assertEquals(2, slides.size()); - checkSlide0(slides.get(0)); - checkSlide1(slides.get(1)); - } - private void checkSlide0(final HSLFSlide s) { - final StyleTextProp9Atom[] numberedListArray = s.getNumberedListInfo(); - assertNotNull(numberedListArray); - assertEquals(2, numberedListArray.length); - final StyleTextProp9Atom numberedListInfoForTextBox0 = numberedListArray[0]; - final StyleTextProp9Atom numberedListInfoForTextBox1 = numberedListArray[1]; - assertNotNull(numberedListInfoForTextBox0); - assertNotNull(numberedListInfoForTextBox1); - final TextPFException9[] autoNumbersOfTextBox0 = numberedListInfoForTextBox0.getAutoNumberTypes(); - assertEquals(Short.valueOf((short)1), autoNumbersOfTextBox0[0].getfBulletHasAutoNumber()); - assertEquals(Short.valueOf((short)1), autoNumbersOfTextBox0[0].getAutoNumberStartNumber());//Default value = 1 will be used - assertTrue(AutoNumberingScheme.arabicPeriod == autoNumbersOfTextBox0[0].getAutoNumberScheme()); - final TextPFException9[] autoNumbersOfTextBox1 = numberedListInfoForTextBox1.getAutoNumberTypes(); - assertEquals(Short.valueOf((short)1), autoNumbersOfTextBox1[0].getfBulletHasAutoNumber()); - assertEquals(Short.valueOf((short)6), autoNumbersOfTextBox1[0].getAutoNumberStartNumber());//Default value = 1 will be used - assertTrue(AutoNumberingScheme.arabicPeriod == autoNumbersOfTextBox1[0].getAutoNumberScheme()); - - - List> textParass = s.getTextParagraphs(); - assertEquals(2, textParass.size()); - - List textParas = textParass.get(0); - assertEquals("List Item One\rList Item Two\rList Item Three", HSLFTextParagraph.getRawText(textParas)); - assertEquals(3, textParas.size()); - assertTrue(textParas.get(0).isBullet()); - - String expected = - "A numbered list may start at any number \r" + - "This would be used as a continuation list on another page\r" + - "This list should start with #6"; - assertEquals(expected, HSLFTextParagraph.getRawText(textParass.get(1))); - - final EscherTextboxWrapper[] styleAtoms = s.getTextboxWrappers(); - assertEquals(textParass.size(), styleAtoms.length); - checkSingleRunWrapper(44, styleAtoms[0]); - checkSingleRunWrapper(130, styleAtoms[1]); - } - private void checkSlide1(final HSLFSlide s) { - final StyleTextProp9Atom[] numberedListArray = s.getNumberedListInfo(); - assertNotNull(numberedListArray); - assertEquals(1, numberedListArray.length); - final StyleTextProp9Atom numberedListInfoForTextBox = numberedListArray[0]; - assertNotNull(numberedListInfoForTextBox); - final TextPFException9[] autoNumbersOfTextBox = numberedListInfoForTextBox.getAutoNumberTypes(); - assertEquals(Short.valueOf((short)1), autoNumbersOfTextBox[0].getfBulletHasAutoNumber()); - assertEquals(Short.valueOf((short)1), autoNumbersOfTextBox[0].getAutoNumberStartNumber());//Default value = 1 will be used - assertTrue(AutoNumberingScheme.arabicPeriod == autoNumbersOfTextBox[0].getAutoNumberScheme()); - - List> textParass = s.getTextParagraphs(); - assertEquals(3, textParass.size()); - - List textParas = textParass.get(0); - assertEquals("Bulleted list\rMore bullets", HSLFTextParagraph.getRawText(textParas)); - assertEquals(2, textParas.size()); - assertTrue(textParas.get(0).isBullet()); - - String expected = "Numbered list between two bulleted lists\rSecond numbered list item"; - assertEquals(expected, HSLFTextParagraph.getRawText(textParass.get(1))); - expected = "Second bulleted list \u2013 should appear after numbered list\rMore bullets"; - assertEquals(expected, HSLFTextParagraph.getRawText(textParass.get(2))); - - final EscherTextboxWrapper[] styleAtoms = s.getTextboxWrappers(); - assertEquals(textParass.size(), styleAtoms.length); - checkSingleRunWrapper(27, styleAtoms[0]); - checkSingleRunWrapper(67, styleAtoms[1]); - checkSingleRunWrapper(70, styleAtoms[2]); - } - private void checkSingleRunWrapper(final int exceptedLength, final EscherTextboxWrapper wrapper) { - final StyleTextPropAtom styleTextPropAtom = wrapper.getStyleTextPropAtom(); - final List textProps = styleTextPropAtom.getCharacterStyles(); - assertEquals(1, textProps.size()); - assertEquals(exceptedLength, textProps.get(0).getCharactersCovered()); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestNumberedList3.java b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestNumberedList3.java deleted file mode 100644 index 36832c69e..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestNumberedList3.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.hslf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.util.List; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hslf.model.textproperties.TextPFException9; -import org.apache.poi.hslf.model.textproperties.TextPropCollection; -import org.apache.poi.hslf.record.EscherTextboxWrapper; -import org.apache.poi.hslf.record.StyleTextProp9Atom; -import org.apache.poi.hslf.record.StyleTextPropAtom; -import org.apache.poi.sl.usermodel.AutoNumberingScheme; -import org.junit.Test; - - -/** - * Test that checks numbered list functionality. - * if a paragraph has autonumber () - * @see - * PPT: Missing TextAutoNumberScheme structure providing the style of the number bullets - * - * @author Alex Nikiforov [mailto:anikif@gmail.com] - */ -public final class TestNumberedList3 { - private static POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); - - @Test - public void testNumberedList() throws IOException { - HSLFSlideShow ppt = new HSLFSlideShow(_slTests.openResourceAsStream("numbers3.ppt")); - assertTrue("No Exceptions while reading file", true); - - final List slides = ppt.getSlides(); - assertEquals(1, slides.size()); - final HSLFSlide slide = slides.get(0); - checkSlide(slide); - ppt.close(); - } - private void checkSlide(final HSLFSlide s) { - final StyleTextProp9Atom[] numberedListArray = s.getNumberedListInfo(); - assertNotNull(numberedListArray); - assertEquals(1, numberedListArray.length); - final StyleTextProp9Atom numberedListInfoForTextBox = numberedListArray[0]; - assertNotNull(numberedListInfoForTextBox); - final TextPFException9[] autoNumbersOfTextBox0 = numberedListInfoForTextBox.getAutoNumberTypes(); - assertEquals(Short.valueOf((short)1), autoNumbersOfTextBox0[0].getfBulletHasAutoNumber()); - assertEquals(Short.valueOf((short)1), autoNumbersOfTextBox0[0].getAutoNumberStartNumber());//Default value = 1 will be used - assertTrue(AutoNumberingScheme.arabicPeriod == autoNumbersOfTextBox0[0].getAutoNumberScheme()); - - final List> textParass = s.getTextParagraphs(); - assertEquals(3, textParass.size()); - assertEquals("Bulleted list\rMore bullets\rNo bullets here", HSLFTextParagraph.getRawText(textParass.get(0))); - assertEquals("Numbered list between two bulleted lists\rSecond numbered list item", HSLFTextParagraph.getRawText(textParass.get(1))); - assertEquals("Second bulleted list \u2013 should appear after numbered list\rMore bullets", HSLFTextParagraph.getRawText(textParass.get(2))); - assertEquals(3, textParass.get(0).size()); - assertEquals(2, textParass.get(1).size()); - assertEquals(2, textParass.get(2).size()); - assertNull(textParass.get(0).get(0).getStyleTextProp9Atom()); - assertNotNull(textParass.get(1).get(0).getStyleTextProp9Atom()); - assertNull(textParass.get(2).get(0).getStyleTextProp9Atom()); - final TextPFException9[] autoNumbers = textParass.get(1).get(0).getStyleTextProp9Atom().getAutoNumberTypes(); - assertEquals(1, autoNumbers.length); - assertEquals(Short.valueOf((short)1), autoNumbers[0].getfBulletHasAutoNumber()); - assertEquals(Short.valueOf((short)1), autoNumbers[0].getAutoNumberStartNumber());//Default value = 1 will be used - assertTrue(AutoNumberingScheme.arabicPeriod == autoNumbersOfTextBox0[0].getAutoNumberScheme()); - - int chCovered = 0; - for (HSLFTextParagraph htp : textParass.get(1)) { - for (HSLFTextRun htr : htp.getTextRuns()) { - TextPropCollection textProp = htr.getCharacterStyle(); - chCovered += textProp.getCharactersCovered(); - } - } - assertEquals(67, chCovered); - - assertTrue(textParass.get(0).get(0).isBullet()); - - final EscherTextboxWrapper[] styleAtoms = s.getTextboxWrappers(); - assertEquals(textParass.size(), styleAtoms.length); - checkSingleRunWrapper(43, styleAtoms[0]); - checkSingleRunWrapper(67, styleAtoms[1]); - } - private void checkSingleRunWrapper(final int exceptedLength, final EscherTextboxWrapper wrapper) { - final StyleTextPropAtom styleTextPropAtom = wrapper.getStyleTextPropAtom(); - final List textProps = styleTextPropAtom.getCharacterStyles(); - assertEquals(1, textProps.size()); - assertEquals(exceptedLength, textProps.get(0).getCharactersCovered()); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestPicture.java b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestPicture.java deleted file mode 100644 index 7a7a7b452..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestPicture.java +++ /dev/null @@ -1,219 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; - -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Graphics2D; -import java.awt.Rectangle; -import java.awt.geom.Rectangle2D; -import java.awt.image.BufferedImage; -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.util.BitSet; -import java.util.List; - -import javax.imageio.ImageIO; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.ddf.EscherBSERecord; -import org.apache.poi.hssf.usermodel.DummyGraphics2d; -import org.apache.poi.sl.draw.DrawFactory; -import org.apache.poi.sl.usermodel.PictureData.PictureType; -import org.apache.poi.sl.usermodel.Slide; -import org.apache.poi.sl.usermodel.SlideShow; -import org.junit.Ignore; -import org.junit.Test; - -/** - * Test Picture shape. - * - * @author Yegor Kozlov - */ -public final class TestPicture { - private static POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); - - /** - * Test that the reference count of a blip is incremented every time the picture is inserted. - * This is important when the same image appears multiple times in a slide show. - * - */ - @Test - public void multiplePictures() throws IOException { - HSLFSlideShow ppt = new HSLFSlideShow(); - - HSLFSlide s = ppt.createSlide(); - HSLFSlide s2 = ppt.createSlide(); - HSLFSlide s3 = ppt.createSlide(); - - HSLFPictureData data = ppt.addPicture(_slTests.readFile("clock.jpg"), PictureType.JPEG); - HSLFPictureShape pict = new HSLFPictureShape(data); - HSLFPictureShape pict2 = new HSLFPictureShape(data); - HSLFPictureShape pict3 = new HSLFPictureShape(data); - - pict.setAnchor(new Rectangle(10,10,100,100)); - s.addShape(pict); - EscherBSERecord bse1 = pict.getEscherBSERecord(); - assertEquals(1, bse1.getRef()); - - pict2.setAnchor(new Rectangle(10,10,100,100)); - s2.addShape(pict2); - EscherBSERecord bse2 = pict.getEscherBSERecord(); - assertSame(bse1, bse2); - assertEquals(2, bse1.getRef()); - - pict3.setAnchor(new Rectangle(10,10,100,100)); - s3.addShape(pict3); - EscherBSERecord bse3 = pict.getEscherBSERecord(); - assertSame(bse2, bse3); - assertEquals(3, bse1.getRef()); - - ppt.close(); - } - - /** - * Picture#getEscherBSERecord threw NullPointerException if EscherContainerRecord.BSTORE_CONTAINER - * was not found. The correct behaviour is to return null. - */ - @Test - public void bug46122() throws IOException { - HSLFSlideShow ppt = new HSLFSlideShow(); - HSLFSlide slide = ppt.createSlide(); - HSLFPictureData pd = HSLFPictureData.create(PictureType.PNG); - - HSLFPictureShape pict = new HSLFPictureShape(pd); //index to non-existing picture data - pict.setAnchor(new Rectangle2D.Double(50,50,100,100)); - pict.setSheet(slide); - HSLFPictureData data = pict.getPictureData(); - assertNull(data); - - BufferedImage img = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); - Graphics2D graphics = img.createGraphics(); - pict.draw(graphics, null); - - ppt.close(); - } - - @Test - public void macImages() throws IOException { - HSLFSlideShowImpl hss = new HSLFSlideShowImpl(_slTests.openResourceAsStream("53446.ppt")); - - List pictures = hss.getPictureData(); - assertEquals(15, pictures.size()); - - int[][] expectedSizes = { - null, // WMF - { 427, 428 }, // PNG - { 371, 370 }, // PNG - { 288, 183 }, // PNG - { 285, 97 }, // PNG - { 288, 168 }, // PNG - null, // WMF - null, // WMF - { 199, 259 }, // PNG - { 432, 244 }, // PNG - { 261, 258 }, // PNG - null, // WMF - null, // WMF - null, // WMF - null // EMF - }; - - int i = 0; - for (HSLFPictureData pd : pictures) { - int[] dimensions = expectedSizes[i++]; - BufferedImage image = ImageIO.read(new ByteArrayInputStream(pd.getData())); - switch (pd.getType()) { - case WMF: - case EMF: - break; - default: - assertNotNull(image); - assertEquals(dimensions[0], image.getWidth()); - assertEquals(dimensions[1], image.getHeight()); - break; - } - } - - hss.close(); - } - - @Test - @Ignore("Just for visual validation - antialiasing is different on various systems") - public void bug54541() - throws IOException, ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException { - String files[] = { -// "sample_pptx_grouping_issues.pptx", -// "54542_cropped_bitmap.pptx", -// "54541_cropped_bitmap.ppt", -// "54541_cropped_bitmap2.ppt", - "alterman_security.ppt", -// "alterman_security3.pptx", - }; - - BitSet pages = new BitSet(); - pages.set(2); - - for (String file : files) { - InputStream is = _slTests.openResourceAsStream(file); - SlideShow ss; - if (file.endsWith("pptx")) { - Class cls = Class.forName("org.apache.poi.xslf.usermodel.XMLSlideShow"); - Constructor ct = cls.getDeclaredConstructor(InputStream.class); - ss = (SlideShow)ct.newInstance(is); - } else { - ss = new HSLFSlideShow(is); - } - is.close(); - - boolean debugOut = false; - Dimension pg = ss.getPageSize(); - for (Slide slide : ss.getSlides()) { - int slideNo = slide.getSlideNumber(); - if (!pages.get(slideNo-1)) { - if (pages.nextSetBit(slideNo-1) == -1) break; else continue; - } - if (debugOut) { - DummyGraphics2d graphics = new DummyGraphics2d(); - slide.draw(graphics); - } else { - BufferedImage img = new BufferedImage(pg.width, pg.height, BufferedImage.TYPE_INT_ARGB); - Graphics2D graphics = img.createGraphics(); - DrawFactory.getInstance(graphics).fixFonts(graphics); - slide.draw(graphics); - graphics.setColor(Color.BLACK); - graphics.setStroke(new BasicStroke(1)); - graphics.drawRect(0, 0, (int)pg.getWidth()-1, (int)pg.getHeight()-1); - ImageIO.write(img, "PNG", new File(file.replaceFirst(".pptx?", "-")+slideNo+".png")); - } - } - - ss.close(); - } - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestPictures.java b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestPictures.java deleted file mode 100644 index 398603cb7..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestPictures.java +++ /dev/null @@ -1,548 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.usermodel; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.awt.Dimension; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.net.URL; -import java.util.List; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hslf.blip.DIB; -import org.apache.poi.hslf.blip.EMF; -import org.apache.poi.hslf.blip.JPEG; -import org.apache.poi.hslf.blip.PICT; -import org.apache.poi.hslf.blip.PNG; -import org.apache.poi.hslf.blip.WMF; -import org.apache.poi.sl.image.ImageHeaderEMF; -import org.apache.poi.sl.image.ImageHeaderPICT; -import org.apache.poi.sl.image.ImageHeaderWMF; -import org.apache.poi.sl.usermodel.PictureData.PictureType; -import org.apache.poi.util.Units; -import org.junit.Ignore; -import org.junit.Test; - -/** - * Test adding/reading pictures - * - * @author Yegor Kozlov - */ -public final class TestPictures { - private static POIDataSamples slTests = POIDataSamples.getSlideShowInstance(); - - /** - * Test read/write Macintosh PICT - */ - @Test - public void testPICT() throws IOException { - HSLFSlideShow ppt = new HSLFSlideShow(); - - HSLFSlide slide = ppt.createSlide(); - byte[] src_bytes = slTests.readFile("cow.pict"); - HSLFPictureData data = ppt.addPicture(src_bytes, PictureType.PICT); - ImageHeaderPICT nHeader = new ImageHeaderPICT(src_bytes, 512); - final int expWidth = 197, expHeight = 137; - Dimension nDim = nHeader.getSize(); - assertEquals(expWidth, nDim.getWidth(), 0); - assertEquals(expHeight, nDim.getHeight(), 0); - - Dimension dim = data.getImageDimensionInPixels(); - assertEquals(Units.pointsToPixel(expWidth), dim.getWidth(), 0); - assertEquals(Units.pointsToPixel(expHeight), dim.getHeight(), 0); - - HSLFPictureShape pict = new HSLFPictureShape(data); - assertEquals(data.getIndex(), pict.getPictureIndex()); - slide.addShape(pict); - - //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ppt.write(out); - out.close(); - - ppt = new HSLFSlideShow(new HSLFSlideShowImpl(new ByteArrayInputStream(out.toByteArray()))); - - //make sure we can read this picture shape and it refers to the correct picture data - List sh = ppt.getSlides().get(0).getShapes(); - assertEquals(1, sh.size()); - pict = (HSLFPictureShape)sh.get(0); - assertEquals(data.getIndex(), pict.getPictureIndex()); - - //check picture data - List pictures = ppt.getPictureData(); - assertEquals(1, pictures.size()); - - HSLFPictureData pd = pictures.get(0); - dim = pd.getImageDimension(); - assertEquals(expWidth, dim.width); - assertEquals(expHeight, dim.height); - - //the Picture shape refers to the PictureData object in the Presentation - assertEquals(pict.getPictureData(), pd); - - assertEquals(1, pictures.size()); - assertEquals(PictureType.PICT, pd.getType()); - assertTrue(pd instanceof PICT); - //compare the content of the initial file with what is stored in the PictureData - byte[] ppt_bytes = pd.getData(); - assertEquals(src_bytes.length, ppt_bytes.length); - //in PICT the first 512 bytes are MAC specific and may not be preserved, ignore them - byte[] b1 = new byte[src_bytes.length-512]; - System.arraycopy(src_bytes, 512, b1, 0, b1.length); - byte[] b2 = new byte[ppt_bytes.length-512]; - System.arraycopy(ppt_bytes, 512, b2, 0, b2.length); - assertArrayEquals(b1, b2); - } - - /** - * Test read/write WMF - */ - @Test - public void testWMF() throws IOException { - HSLFSlideShow ppt = new HSLFSlideShow(); - - HSLFSlide slide = ppt.createSlide(); - byte[] src_bytes = slTests.readFile("santa.wmf"); - HSLFPictureData data = ppt.addPicture(src_bytes, PictureType.WMF); - ImageHeaderWMF nHeader = new ImageHeaderWMF(src_bytes, 0); - final int expWidth = 136, expHeight = 146; - Dimension nDim = nHeader.getSize(); - assertEquals(expWidth, nDim.getWidth(), 0); - assertEquals(expHeight, nDim.getHeight(), 0); - - Dimension dim = data.getImageDimensionInPixels(); - assertEquals(Units.pointsToPixel(expWidth), dim.getWidth(), 0); - assertEquals(Units.pointsToPixel(expHeight), dim.getHeight(), 0); - - HSLFPictureShape pict = new HSLFPictureShape(data); - assertEquals(data.getIndex(), pict.getPictureIndex()); - slide.addShape(pict); - - //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ppt.write(out); - out.close(); - - ppt = new HSLFSlideShow(new HSLFSlideShowImpl(new ByteArrayInputStream(out.toByteArray()))); - - //make sure we can read this picture shape and it refers to the correct picture data - List sh = ppt.getSlides().get(0).getShapes(); - assertEquals(1, sh.size()); - pict = (HSLFPictureShape)sh.get(0); - assertEquals(data.getIndex(), pict.getPictureIndex()); - - //check picture data - List pictures = ppt.getPictureData(); - assertEquals(1, pictures.size()); - - HSLFPictureData pd = pictures.get(0); - dim = pd.getImageDimension(); - assertEquals(expWidth, dim.width); - assertEquals(expHeight, dim.height); - - //the Picture shape refers to the PictureData object in the Presentation - assertEquals(pict.getPictureData(), pd); - - assertEquals(PictureType.WMF, pd.getType()); - assertTrue(pd instanceof WMF); - //compare the content of the initial file with what is stored in the PictureData - byte[] ppt_bytes = pd.getData(); - assertEquals(src_bytes.length, ppt_bytes.length); - //in WMF the first 22 bytes - is a metafile header - byte[] b1 = new byte[src_bytes.length-22]; - System.arraycopy(src_bytes, 22, b1, 0, b1.length); - byte[] b2 = new byte[ppt_bytes.length-22]; - System.arraycopy(ppt_bytes, 22, b2, 0, b2.length); - assertArrayEquals(b1, b2); - } - - /** - * Test read/write EMF - */ - @Test - public void testEMF() throws IOException { - HSLFSlideShow ppt = new HSLFSlideShow(); - - HSLFSlide slide = ppt.createSlide(); - byte[] src_bytes = slTests.readFile("wrench.emf"); - HSLFPictureData data = ppt.addPicture(src_bytes, PictureType.EMF); - ImageHeaderEMF nHeader = new ImageHeaderEMF(src_bytes, 0); - final int expWidth = 190, expHeight = 115; - Dimension nDim = nHeader.getSize(); - assertEquals(expWidth, nDim.getWidth(), 0); - assertEquals(expHeight, nDim.getHeight(), 0); - - Dimension dim = data.getImageDimensionInPixels(); - assertEquals(Units.pointsToPixel(expWidth), dim.getWidth(), 0); - assertEquals(Units.pointsToPixel(expHeight), dim.getHeight(), 0); - - HSLFPictureShape pict = new HSLFPictureShape(data); - assertEquals(data.getIndex(), pict.getPictureIndex()); - slide.addShape(pict); - - //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ppt.write(out); - out.close(); - - ppt = new HSLFSlideShow(new HSLFSlideShowImpl(new ByteArrayInputStream(out.toByteArray()))); - - //make sure we can get this picture shape and it refers to the correct picture data - List sh = ppt.getSlides().get(0).getShapes(); - assertEquals(1, sh.size()); - pict = (HSLFPictureShape)sh.get(0); - assertEquals(data.getIndex(), pict.getPictureIndex()); - - //check picture data - List pictures = ppt.getPictureData(); - assertEquals(1, pictures.size()); - - HSLFPictureData pd = pictures.get(0); - dim = pd.getImageDimension(); - assertEquals(expWidth, dim.width); - assertEquals(expHeight, dim.height); - - //the Picture shape refers to the PictureData object in the Presentation - assertEquals(pict.getPictureData(), pd); - - assertEquals(1, pictures.size()); - assertEquals(PictureType.EMF, pd.getType()); - assertTrue(pd instanceof EMF); - //compare the content of the initial file with what is stored in the PictureData - byte[] ppt_bytes = pd.getData(); - assertArrayEquals(src_bytes, ppt_bytes); - } - - /** - * Test read/write PNG - */ - @Test - public void testPNG() throws IOException { - HSLFSlideShow ppt = new HSLFSlideShow(); - - HSLFSlide slide = ppt.createSlide(); - byte[] src_bytes = slTests.readFile("tomcat.png"); - HSLFPictureData data = ppt.addPicture(src_bytes, PictureType.PNG); - HSLFPictureShape pict = new HSLFPictureShape(data); - assertEquals(data.getIndex(), pict.getPictureIndex()); - slide.addShape(pict); - - //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ppt.write(out); - out.close(); - - ppt = new HSLFSlideShow(new HSLFSlideShowImpl(new ByteArrayInputStream(out.toByteArray()))); - - //make sure we can read this picture shape and it refers to the correct picture data - List sh = ppt.getSlides().get(0).getShapes(); - assertEquals(1, sh.size()); - pict = (HSLFPictureShape)sh.get(0); - assertEquals(data.getIndex(), pict.getPictureIndex()); - - //check picture data - List pictures = ppt.getPictureData(); - //the Picture shape refers to the PictureData object in the Presentation - assertEquals(pict.getPictureData(), pictures.get(0)); - - assertEquals(1, pictures.size()); - assertEquals(PictureType.PNG, pictures.get(0).getType()); - assertTrue(pictures.get(0) instanceof PNG); - //compare the content of the initial file with what is stored in the PictureData - byte[] ppt_bytes = pictures.get(0).getData(); - assertArrayEquals(src_bytes, ppt_bytes); - } - - /** - * Test read/write JPEG - */ - @Test - public void testJPEG() throws IOException { - HSLFSlideShow ppt = new HSLFSlideShow(); - - HSLFSlide slide = ppt.createSlide(); - byte[] src_bytes = slTests.readFile("clock.jpg"); - HSLFPictureData data = ppt.addPicture(src_bytes, PictureType.JPEG); - - HSLFPictureShape pict = new HSLFPictureShape(data); - assertEquals(data.getIndex(), pict.getPictureIndex()); - slide.addShape(pict); - - //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ppt.write(out); - out.close(); - - ppt = new HSLFSlideShow(new HSLFSlideShowImpl(new ByteArrayInputStream(out.toByteArray()))); - - //make sure we can read this picture shape and it refers to the correct picture data - List sh = ppt.getSlides().get(0).getShapes(); - assertEquals(1, sh.size()); - pict = (HSLFPictureShape)sh.get(0); - assertEquals(data.getIndex(), pict.getPictureIndex()); - - //check picture data - List pictures = ppt.getPictureData(); - //the Picture shape refers to the PictureData object in the Presentation - assertEquals(pict.getPictureData(), pictures.get(0)); - - assertEquals(1, pictures.size()); - assertEquals(PictureType.JPEG, pictures.get(0).getType()); - assertTrue(pictures.get(0) instanceof JPEG); - //compare the content of the initial file with what is stored in the PictureData - byte[] ppt_bytes = pictures.get(0).getData(); - assertArrayEquals(src_bytes, ppt_bytes); - } - - /** - * Test read/write DIB - */ - @Test - public void testDIB() throws IOException { - HSLFSlideShow ppt = new HSLFSlideShow(); - - HSLFSlide slide = ppt.createSlide(); - byte[] src_bytes = slTests.readFile("clock.dib"); - HSLFPictureData data = ppt.addPicture(src_bytes, PictureType.DIB); - HSLFPictureShape pict = new HSLFPictureShape(data); - assertEquals(data.getIndex(), pict.getPictureIndex()); - slide.addShape(pict); - - //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ppt.write(out); - out.close(); - - ppt = new HSLFSlideShow(new HSLFSlideShowImpl(new ByteArrayInputStream(out.toByteArray()))); - - //make sure we can read this picture shape and it refers to the correct picture data - List sh = ppt.getSlides().get(0).getShapes(); - assertEquals(1, sh.size()); - pict = (HSLFPictureShape)sh.get(0); - assertEquals(data.getIndex(), pict.getPictureIndex()); - - //check picture data - List pictures = ppt.getPictureData(); - //the Picture shape refers to the PictureData object in the Presentation - assertEquals(pict.getPictureData(), pictures.get(0)); - - assertEquals(1, pictures.size()); - assertEquals(PictureType.DIB, pictures.get(0).getType()); - assertTrue(pictures.get(0) instanceof DIB); - //compare the content of the initial file with what is stored in the PictureData - byte[] ppt_bytes = pictures.get(0).getData(); - assertArrayEquals(src_bytes, ppt_bytes); - } - - /** - * Read pictures in different formats from a reference slide show - */ - @Test - public void testReadPictures() throws IOException { - - byte[] src_bytes, ppt_bytes, b1, b2; - HSLFPictureShape pict; - HSLFPictureData pdata; - - HSLFSlideShow ppt = new HSLFSlideShow(slTests.openResourceAsStream("pictures.ppt")); - List slides = ppt.getSlides(); - List pictures = ppt.getPictureData(); - assertEquals(5, pictures.size()); - - pict = (HSLFPictureShape)slides.get(0).getShapes().get(0); //the first slide contains JPEG - pdata = pict.getPictureData(); - assertTrue(pdata instanceof JPEG); - assertEquals(PictureType.JPEG, pdata.getType()); - src_bytes = pdata.getData(); - ppt_bytes = slTests.readFile("clock.jpg"); - assertArrayEquals(src_bytes, ppt_bytes); - - pict = (HSLFPictureShape)slides.get(1).getShapes().get(0); //the second slide contains PNG - pdata = pict.getPictureData(); - assertTrue(pdata instanceof PNG); - assertEquals(PictureType.PNG, pdata.getType()); - src_bytes = pdata.getData(); - ppt_bytes = slTests.readFile("tomcat.png"); - assertArrayEquals(src_bytes, ppt_bytes); - - pict = (HSLFPictureShape)slides.get(2).getShapes().get(0); //the third slide contains WMF - pdata = pict.getPictureData(); - assertTrue(pdata instanceof WMF); - assertEquals(PictureType.WMF, pdata.getType()); - src_bytes = pdata.getData(); - ppt_bytes = slTests.readFile("santa.wmf"); - assertEquals(src_bytes.length, ppt_bytes.length); - //ignore the first 22 bytes - it is a WMF metafile header - b1 = new byte[src_bytes.length-22]; - System.arraycopy(src_bytes, 22, b1, 0, b1.length); - b2 = new byte[ppt_bytes.length-22]; - System.arraycopy(ppt_bytes, 22, b2, 0, b2.length); - assertArrayEquals(b1, b2); - - pict = (HSLFPictureShape)slides.get(3).getShapes().get(0); //the forth slide contains PICT - pdata = pict.getPictureData(); - assertTrue(pdata instanceof PICT); - assertEquals(PictureType.PICT, pdata.getType()); - src_bytes = pdata.getData(); - ppt_bytes = slTests.readFile("cow.pict"); - assertEquals(src_bytes.length, ppt_bytes.length); - //ignore the first 512 bytes - it is a MAC specific crap - b1 = new byte[src_bytes.length-512]; - System.arraycopy(src_bytes, 512, b1, 0, b1.length); - b2 = new byte[ppt_bytes.length-512]; - System.arraycopy(ppt_bytes, 512, b2, 0, b2.length); - assertArrayEquals(b1, b2); - - pict = (HSLFPictureShape)slides.get(4).getShapes().get(0); //the fifth slide contains EMF - pdata = pict.getPictureData(); - assertTrue(pdata instanceof EMF); - assertEquals(PictureType.EMF, pdata.getType()); - src_bytes = pdata.getData(); - ppt_bytes = slTests.readFile("wrench.emf"); - assertArrayEquals(src_bytes, ppt_bytes); - - ppt.close(); - } - - /** - * Test that on a party corrupt powerpoint document, which has - * crazy pictures of type 0, we do our best. - */ - @Test - public void testZeroPictureType() throws IOException { - HSLFSlideShowImpl hslf = new HSLFSlideShowImpl(slTests.openResourceAsStream("PictureTypeZero.ppt")); - - // Should still have 2 real pictures - assertEquals(2, hslf.getPictureData().size()); - // Both are real pictures, both WMF - assertEquals(PictureType.WMF, hslf.getPictureData().get(0).getType()); - assertEquals(PictureType.WMF, hslf.getPictureData().get(1).getType()); - - // Now test what happens when we use the SlideShow interface - HSLFSlideShow ppt = new HSLFSlideShow(hslf); - List slides = ppt.getSlides(); - List pictures = ppt.getPictureData(); - assertEquals(12, slides.size()); - assertEquals(2, pictures.size()); - - HSLFPictureShape pict; - HSLFPictureData pdata; - - pict = (HSLFPictureShape)slides.get(0).getShapes().get(1); // 2nd object on 1st slide - pdata = pict.getPictureData(); - assertTrue(pdata instanceof WMF); - assertEquals(PictureType.WMF, pdata.getType()); - - pict = (HSLFPictureShape)slides.get(0).getShapes().get(2); // 3rd object on 1st slide - pdata = pict.getPictureData(); - assertTrue(pdata instanceof WMF); - assertEquals(PictureType.WMF, pdata.getType()); - - ppt.close(); - } - - /** - * YK: The test is disabled because the owner asked to delete the test file from POI svn. - * See "Please remove my file from your svn" on @poi-dev from Dec 12, 2013 - */ - @Test - @Ignore - public void testZeroPictureLength() throws IOException { - // take the data from www instead of test directory - URL url = new URL("http://www.cs.sfu.ca/~anoop/courses/CMPT-882-Fall-2002/chris.ppt"); - HSLFSlideShowImpl hslf = new HSLFSlideShowImpl(url.openStream()); - - // Should still have 2 real pictures - assertEquals(2, hslf.getPictureData().size()); - // Both are real pictures, both WMF - assertEquals(PictureType.WMF, hslf.getPictureData().get(0).getType()); - assertEquals(PictureType.WMF, hslf.getPictureData().get(1).getType()); - - // Now test what happens when we use the SlideShow interface - HSLFSlideShow ppt = new HSLFSlideShow(hslf); - List slides = ppt.getSlides(); - List pictures = ppt.getPictureData(); - assertEquals(27, slides.size()); - assertEquals(2, pictures.size()); - - HSLFPictureShape pict; - HSLFPictureData pdata; - - pict = (HSLFPictureShape)slides.get(6).getShapes().get(13); - pdata = pict.getPictureData(); - assertTrue(pdata instanceof WMF); - assertEquals(PictureType.WMF, pdata.getType()); - - pict = (HSLFPictureShape)slides.get(7).getShapes().get(13); - pdata = pict.getPictureData(); - assertTrue(pdata instanceof WMF); - assertEquals(PictureType.WMF, pdata.getType()); - - //add a new picture, it should be correctly appended to the Pictures stream - ByteArrayOutputStream out = new ByteArrayOutputStream(); - for(HSLFPictureData p : pictures) p.write(out); - out.close(); - - int streamSize = out.size(); - - HSLFPictureData data = HSLFPictureData.create(PictureType.JPEG); - data.setData(new byte[100]); - int offset = hslf.addPicture(data); - assertEquals(streamSize, offset); - assertEquals(3, ppt.getPictureData().size()); - - ppt.close(); - } - - @Test - public void testGetPictureName() throws IOException { - HSLFSlideShow ppt = new HSLFSlideShow(slTests.openResourceAsStream("ppt_with_png.ppt")); - HSLFSlide slide = ppt.getSlides().get(0); - - HSLFPictureShape p = (HSLFPictureShape)slide.getShapes().get(0); //the first slide contains JPEG - assertEquals("test", p.getPictureName()); - ppt.close(); - } - - @Test - public void testSetPictureName() throws IOException { - HSLFSlideShow ppt = new HSLFSlideShow(); - - HSLFSlide slide = ppt.createSlide(); - byte[] img = slTests.readFile("tomcat.png"); - HSLFPictureData data = ppt.addPicture(img, PictureType.PNG); - HSLFPictureShape pict = new HSLFPictureShape(data); - pict.setPictureName("tomcat.png"); - slide.addShape(pict); - - //serialize and read again - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ppt.write(out); - out.close(); - - ppt = new HSLFSlideShow(new ByteArrayInputStream(out.toByteArray())); - - HSLFPictureShape p = (HSLFPictureShape)ppt.getSlides().get(0).getShapes().get(0); - assertEquals("tomcat.png", p.getPictureName()); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestReOrderingSlides.java b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestReOrderingSlides.java deleted file mode 100644 index c8a3d3761..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestReOrderingSlides.java +++ /dev/null @@ -1,315 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.usermodel; - - -import static org.junit.Assert.assertEquals; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; - -import org.apache.poi.POIDataSamples; -import org.junit.Before; -import org.junit.Test; - -/** - * Tests that SlideShow can re-order slides properly - * - * @author Nick Burch (nick at torchbox dot com) - */ -public final class TestReOrderingSlides { - // A SlideShow with one slide - private HSLFSlideShowImpl hss_one; - private HSLFSlideShow ss_one; - - // A SlideShow with two slides - private HSLFSlideShowImpl hss_two; - private HSLFSlideShow ss_two; - - // A SlideShow with three slides - private HSLFSlideShowImpl hss_three; - private HSLFSlideShow ss_three; - - /** - * Create/open the slideshows - */ - @Before - public void setUp() throws Exception { - POIDataSamples slTests = POIDataSamples.getSlideShowInstance(); - - hss_one = new HSLFSlideShowImpl(slTests.openResourceAsStream("Single_Coloured_Page.ppt")); - ss_one = new HSLFSlideShow(hss_one); - - hss_two = new HSLFSlideShowImpl(slTests.openResourceAsStream("basic_test_ppt_file.ppt")); - ss_two = new HSLFSlideShow(hss_two); - - hss_three = new HSLFSlideShowImpl(slTests.openResourceAsStream("incorrect_slide_order.ppt")); - ss_three = new HSLFSlideShow(hss_three); - } - - /** - * Test that we can "re-order" a slideshow with only 1 slide on it - */ - @Test - public void testReOrder1() throws Exception { - // Has one slide - assertEquals(1, ss_one.getSlides().size()); - HSLFSlide s1 = ss_one.getSlides().get(0); - - // Check slide 1 is as expected - assertEquals(256, s1._getSheetNumber()); - assertEquals(3, s1._getSheetRefId()); - assertEquals(1, s1.getSlideNumber()); - - // Now move it to one - ss_one.reorderSlide(1, 1); - - // Write out, and read back in - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - hss_one.write(baos); - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - - HSLFSlideShowImpl hss_read = new HSLFSlideShowImpl(bais); - HSLFSlideShow ss_read = new HSLFSlideShow(hss_read); - - // Check it still has 1 slide - assertEquals(1, ss_read.getSlides().size()); - - // And check it's as expected - s1 = ss_read.getSlides().get(0); - assertEquals(256, s1._getSheetNumber()); - assertEquals(3, s1._getSheetRefId()); - assertEquals(1, s1.getSlideNumber()); - } - - /** - * Test doing a dummy re-order on a slideshow with - * two slides in it - */ - @Test - public void testReOrder2() throws Exception { - // Has two slides - assertEquals(2, ss_two.getSlides().size()); - HSLFSlide s1 = ss_two.getSlides().get(0); - HSLFSlide s2 = ss_two.getSlides().get(1); - - // Check slide 1 is as expected - assertEquals(256, s1._getSheetNumber()); - assertEquals(4, s1._getSheetRefId()); // master has notes - assertEquals(1, s1.getSlideNumber()); - // Check slide 2 is as expected - assertEquals(257, s2._getSheetNumber()); - assertEquals(6, s2._getSheetRefId()); // master and 1 have notes - assertEquals(2, s2.getSlideNumber()); - - // Don't swap them around - ss_two.reorderSlide(2, 2); - - // Write out, and read back in - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - hss_two.write(baos); - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - - HSLFSlideShowImpl hss_read = new HSLFSlideShowImpl(bais); - HSLFSlideShow ss_read = new HSLFSlideShow(hss_read); - - // Check it still has 2 slides - assertEquals(2, ss_read.getSlides().size()); - - // And check it's as expected - s1 = ss_read.getSlides().get(0); - s2 = ss_read.getSlides().get(1); - assertEquals(256, s1._getSheetNumber()); - assertEquals(4, s1._getSheetRefId()); - assertEquals(1, s1.getSlideNumber()); - assertEquals(257, s2._getSheetNumber()); - assertEquals(6, s2._getSheetRefId()); - assertEquals(2, s2.getSlideNumber()); - } - - /** - * Test re-ordering slides in a slideshow with 2 slides on it - */ - @Test - public void testReOrder2swap() throws Exception { - // Has two slides - assertEquals(2, ss_two.getSlides().size()); - HSLFSlide s1 = ss_two.getSlides().get(0); - HSLFSlide s2 = ss_two.getSlides().get(1); - - // Check slide 1 is as expected - assertEquals(256, s1._getSheetNumber()); - assertEquals(4, s1._getSheetRefId()); // master has notes - assertEquals(1, s1.getSlideNumber()); - // Check slide 2 is as expected - assertEquals(257, s2._getSheetNumber()); - assertEquals(6, s2._getSheetRefId()); // master and 1 have notes - assertEquals(2, s2.getSlideNumber()); - - // Swap them around - ss_two.reorderSlide(2, 1); - - // Write out, and read back in - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - hss_two.write(baos); - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - - HSLFSlideShowImpl hss_read = new HSLFSlideShowImpl(bais); - HSLFSlideShow ss_read = new HSLFSlideShow(hss_read); - - // Check it still has 2 slides - assertEquals(2, ss_read.getSlides().size()); - - // And check it's as expected - s1 = ss_read.getSlides().get(0); - s2 = ss_read.getSlides().get(1); - assertEquals(257, s1._getSheetNumber()); - assertEquals(6, s1._getSheetRefId()); - assertEquals(1, s1.getSlideNumber()); - assertEquals(256, s2._getSheetNumber()); - assertEquals(4, s2._getSheetRefId()); - assertEquals(2, s2.getSlideNumber()); - } - - /** - * Test doing a dummy re-order on a slideshow with - * three slides in it - */ - @Test - public void testReOrder3() throws Exception { - // Has three slides - assertEquals(3, ss_three.getSlides().size()); - HSLFSlide s1 = ss_three.getSlides().get(0); - HSLFSlide s2 = ss_three.getSlides().get(1); - HSLFSlide s3 = ss_three.getSlides().get(2); - - // Check slide 1 is as expected - assertEquals(256, s1._getSheetNumber()); - assertEquals(3, s1._getSheetRefId()); // no notes on master - assertEquals(1, s1.getSlideNumber()); - // Check slide 2 is as expected (was re-ordered from 3) - assertEquals(258, s2._getSheetNumber()); - assertEquals(5, s2._getSheetRefId()); // no notes on slide - assertEquals(2, s2.getSlideNumber()); - // Check slide 3 is as expected (was re-ordered from 2) - assertEquals(257, s3._getSheetNumber()); - assertEquals(4, s3._getSheetRefId()); // no notes on slide - assertEquals(3, s3.getSlideNumber()); - - // Don't swap them around - ss_three.reorderSlide(2, 2); - - // Write out, and read back in - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - hss_three.write(baos); - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - - HSLFSlideShowImpl hss_read = new HSLFSlideShowImpl(bais); - HSLFSlideShow ss_read = new HSLFSlideShow(hss_read); - - // Check it still has 3 slides - assertEquals(3, ss_read.getSlides().size()); - - // And check it's as expected - s1 = ss_read.getSlides().get(0); - s2 = ss_read.getSlides().get(1); - s3 = ss_read.getSlides().get(2); - - assertEquals(256, s1._getSheetNumber()); - assertEquals(3, s1._getSheetRefId()); - assertEquals(1, s1.getSlideNumber()); - assertEquals(258, s2._getSheetNumber()); - assertEquals(5, s2._getSheetRefId()); - assertEquals(2, s2.getSlideNumber()); - assertEquals(257, s3._getSheetNumber()); - assertEquals(4, s3._getSheetRefId()); - assertEquals(3, s3.getSlideNumber()); - } - - /** - * Test re-ordering slides in a slideshow with 3 slides on it - */ - @Test - public void testReOrder3swap() throws Exception { - // Has three slides - assertEquals(3, ss_three.getSlides().size()); - HSLFSlide s1 = ss_three.getSlides().get(0); - HSLFSlide s2 = ss_three.getSlides().get(1); - HSLFSlide s3 = ss_three.getSlides().get(2); - - // Check slide 1 is as expected - assertEquals(256, s1._getSheetNumber()); - assertEquals(3, s1._getSheetRefId()); // no notes on master - assertEquals(1, s1.getSlideNumber()); - // Check slide 2 is as expected (was re-ordered from 3) - assertEquals(258, s2._getSheetNumber()); - assertEquals(5, s2._getSheetRefId()); // no notes on slide - assertEquals(2, s2.getSlideNumber()); - // Check slide 3 is as expected (was re-ordered from 2) - assertEquals(257, s3._getSheetNumber()); - assertEquals(4, s3._getSheetRefId()); // no notes on slide - assertEquals(3, s3.getSlideNumber()); - - // Put 3 in place of 1 - // (1 -> 2, 2 -> 3) - ss_three.reorderSlide(3, 1); - - // refresh the slides - s1 = ss_three.getSlides().get(0); - s2 = ss_three.getSlides().get(1); - s3 = ss_three.getSlides().get(2); - - assertEquals(1, s1.getSlideNumber()); - assertEquals(2, s2.getSlideNumber()); - assertEquals(3, s3.getSlideNumber()); - - assertEquals("Slide 3", ((HSLFTextShape)s1.getShapes().get(0)).getText()); - assertEquals("Slide 1", ((HSLFTextShape)s3.getShapes().get(0)).getText()); - - // Write out, and read back in - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - hss_three.write(baos); - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - - HSLFSlideShowImpl hss_read = new HSLFSlideShowImpl(bais); - HSLFSlideShow ss_read = new HSLFSlideShow(hss_read); - - // Check it still has 3 slides - assertEquals(3, ss_read.getSlides().size()); - - // And check it's as expected - HSLFSlide _s1 = ss_read.getSlides().get(0); - HSLFSlide _s2 = ss_read.getSlides().get(1); - HSLFSlide _s3 = ss_read.getSlides().get(2); - - // 1 --> 3 - assertEquals(s1._getSheetNumber(), _s1._getSheetNumber()); - assertEquals(s1._getSheetRefId(), _s1._getSheetRefId()); - assertEquals(1, s1.getSlideNumber()); - - // 2nd slide is not updated - assertEquals(s2._getSheetNumber(), _s2._getSheetNumber()); - assertEquals(s2._getSheetRefId(), _s2._getSheetRefId()); - assertEquals(2, s2.getSlideNumber()); - - // 3 --> 1 - assertEquals(s3._getSheetNumber(), _s3._getSheetNumber()); - assertEquals(s3._getSheetRefId(), _s3._getSheetRefId()); - assertEquals(3, s3.getSlideNumber()); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestRecordSetup.java b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestRecordSetup.java deleted file mode 100644 index b707df223..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestRecordSetup.java +++ /dev/null @@ -1,67 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.usermodel; - -import static org.junit.Assert.assertEquals; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hslf.record.*; -import org.junit.Before; -import org.junit.Test; - -/** - * Tests that the record setup done by SlideShow - * has worked correctly - * Note: most recent record stuff has its own test - * - * @author Nick Burch (nick at torchbox dot com) - */ -public final class TestRecordSetup { - // SlideShow primed on the test data - @SuppressWarnings("unused") - private HSLFSlideShow ss; - private HSLFSlideShowImpl hss; - - @Before - public void init() throws Exception { - POIDataSamples slTests = POIDataSamples.getSlideShowInstance(); - hss = new HSLFSlideShowImpl(slTests.openResourceAsStream("basic_test_ppt_file.ppt")); - ss = new HSLFSlideShow(hss); - } - - @Test - public void testHandleParentAwareRecords() { - Record[] records = hss.getRecords(); - for (Record record : records) { - ensureParentAware(record,null); - } - } - private void ensureParentAware(Record r,RecordContainer parent) { - if(r instanceof ParentAwareRecord) { - ParentAwareRecord pr = (ParentAwareRecord)r; - assertEquals(parent, pr.getParentRecord()); - } - if(r instanceof RecordContainer) { - RecordContainer rc = (RecordContainer)r; - Record[] children = rc.getChildRecords(); - for (Record rec : children) { - ensureParentAware(rec, rc); - } - } - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestRichTextRun.java b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestRichTextRun.java deleted file mode 100644 index b32a20182..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestRichTextRun.java +++ /dev/null @@ -1,650 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.usermodel; - -import static org.apache.poi.POITestCase.assertContains; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.List; - -import org.apache.poi.hslf.HSLFTestDataSamples; -import org.apache.poi.hslf.record.Record; -import org.apache.poi.hslf.record.SlideListWithText; -import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; -import org.apache.poi.util.IOUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -/** - * Test that the friendly getters and setters on RichTextRun - * behave as expected. - * (model.TestTextRun tests the other functionality) - */ -public final class TestRichTextRun { - // SlideShow primed on the test data - private HSLFSlideShow ss; - private HSLFSlideShow ssRichA; - private HSLFSlideShow ssRichB; - private HSLFSlideShow ssRichC; - private HSLFSlideShow ssChinese; - private static String filenameC; - - @Before - public void setUp() throws IOException { - // Basic (non rich) test file - ss = HSLFTestDataSamples.getSlideShow("basic_test_ppt_file.ppt"); - - // Rich test file A - ssRichA = HSLFTestDataSamples.getSlideShow("Single_Coloured_Page.ppt"); - - // Rich test file B - ssRichB = HSLFTestDataSamples.getSlideShow("Single_Coloured_Page_With_Fonts_and_Alignments.ppt"); - - // Rich test file C - has paragraph styles that run out before - // the character ones do - filenameC = "ParagraphStylesShorterThanCharStyles.ppt"; - ssRichC = HSLFTestDataSamples.getSlideShow(filenameC); - - // Rich test file with Chinese + English text in it - ssChinese = HSLFTestDataSamples.getSlideShow("54880_chinese.ppt"); - } - - @After - public void tearDown() throws IOException { - ss.close(); - ssRichA.close(); - ssRichB.close(); - ssRichC.close(); - ssChinese.close(); - } - - /** - * Test the stuff about getting/setting bold - * on a non rich text run - */ - @Test - public void testBoldNonRich() { - HSLFSlide slideOne = ss.getSlides().get(0); - List> textParass = slideOne.getTextParagraphs(); - List textParas = textParass.get(0); - HSLFTextRun rtr = textParas.get(0).getTextRuns().get(0); - - assertNotNull(rtr.getCharacterStyle()); - assertNotNull(textParas.get(0).getParagraphStyle()); - assertFalse(rtr.isBold()); - - // Now set it to not bold - rtr.setBold(false); - // in Pre 3.12: setting bold=false doesn't change the internal state - // now: also allow explicitly disable styles and there aren't any non rich text runs anymore - assertNotNull(rtr.getCharacterStyle()); - assertNotNull(textParas.get(0).getParagraphStyle()); - - assertFalse(rtr.isBold()); - - // And now make it bold - rtr.setBold(true); - assertNotNull(rtr.getCharacterStyle()); - assertNotNull(textParas.get(0).getParagraphStyle()); - assertTrue(rtr.isBold()); - } - - /** - * Test the stuff about getting/setting bold - * on a rich text run - */ - @Test - public void testBoldRich() { - HSLFSlide slideOneR = ssRichA.getSlides().get(0); - List> textParass = slideOneR.getTextParagraphs(); - List textParas = textParass.get(1); - assertEquals(3, textParas.size()); - - assertTrue(textParas.get(0).getTextRuns().get(0).isBold()); - assertFalse(textParas.get(1).getTextRuns().get(0).isBold()); - assertFalse(textParas.get(2).getTextRuns().get(0).isBold()); - - textParas.get(0).getTextRuns().get(0).setBold(true); - textParas.get(1).getTextRuns().get(0).setBold(true); - - assertTrue(textParas.get(0).getTextRuns().get(0).isBold()); - assertTrue(textParas.get(1).getTextRuns().get(0).isBold()); - - textParas.get(0).getTextRuns().get(0).setBold(false); - textParas.get(1).getTextRuns().get(0).setBold(false); - - assertFalse(textParas.get(0).getTextRuns().get(0).isBold()); - assertFalse(textParas.get(1).getTextRuns().get(0).isBold()); - } - - /** - * Tests getting and setting the font size on rich and non - * rich text runs - */ - @Test - public void testFontSize() { - - HSLFSlide slideOne = ss.getSlides().get(0); - List> textParass = slideOne.getTextParagraphs(); - HSLFTextRun rtr = textParass.get(0).get(0).getTextRuns().get(0); - - HSLFSlide slideOneR = ssRichB.getSlides().get(0); - List> textParassR = slideOneR.getTextParagraphs(); - HSLFTextRun rtrRa = textParassR.get(0).get(0).getTextRuns().get(0); - HSLFTextRun rtrRb = textParassR.get(1).get(0).getTextRuns().get(0); - HSLFTextRun rtrRc = textParassR.get(1).get(3).getTextRuns().get(0); - - String defaultFont = "Arial"; - - // Start off with rich one - // First run has defaults - assertEquals(44, rtrRa.getFontSize(), 0); - assertEquals(defaultFont, rtrRa.getFontFamily()); - - // Second is size 20, default font - assertEquals(20, rtrRb.getFontSize(), 0); - assertEquals(defaultFont, rtrRb.getFontFamily()); - // Third is size 24, alt font - assertEquals(24, rtrRc.getFontSize(), 0); - assertEquals("Times New Roman", rtrRc.getFontFamily()); - - // Change 2nd to different size and font - assertEquals(2, ssRichB.getFontCollection().getChildRecords().length); // Default + TNR - rtrRb.setFontSize(18d); - rtrRb.setFontFamily("Courier"); - assertEquals(3, ssRichB.getFontCollection().getChildRecords().length); // Default + TNR + Courier - assertEquals(18, rtrRb.getFontSize(), 0); - assertEquals("Courier", rtrRb.getFontFamily()); - - - // Now do non rich one - assertEquals(44, rtr.getFontSize(), 0); - assertEquals(defaultFont, rtr.getFontFamily()); - assertEquals(1, ss.getFontCollection().getChildRecords().length); // Default - assertNotNull(rtr.getCharacterStyle()); - assertNotNull(rtr.getTextParagraph().getParagraphStyle()); - - // Change Font size - rtr.setFontSize(99d); - assertEquals(99, rtr.getFontSize(), 0); - assertEquals(defaultFont, rtr.getFontFamily()); - assertNotNull(rtr.getCharacterStyle()); - assertNotNull(rtr.getTextParagraph().getParagraphStyle()); - assertEquals(1, ss.getFontCollection().getChildRecords().length); // Default - - // Change Font size and name - rtr.setFontSize(25d); - rtr.setFontFamily("Times New Roman"); - assertEquals(25, rtr.getFontSize(), 0); - assertEquals("Times New Roman", rtr.getFontFamily()); - assertNotNull(rtr.getCharacterStyle()); - assertNotNull(rtr.getTextParagraph().getParagraphStyle()); - assertEquals(2, ss.getFontCollection().getChildRecords().length); - } - - @Test - public void testChangeWriteRead() throws IOException { - for(HSLFSlideShow h : new HSLFSlideShow[] { ss, ssRichA, ssRichB }) { - // Change - HSLFSlide slideOne = h.getSlides().get(0); - List> textParass = slideOne.getTextParagraphs(); - HSLFTextRun rtr = textParass.get(0).get(0).getTextRuns().get(0); - - rtr.setBold(true); - rtr.setFontSize(18d); - rtr.setFontFamily("Courier"); - HSLFTextParagraph.storeText(textParass.get(0)); - - // Check it took those - assertTrue(rtr.isBold()); - assertEquals(18., rtr.getFontSize(), 0); - assertEquals("Courier", rtr.getFontFamily()); - - // Write out and back in - HSLFSlideShow readS = HSLFTestDataSamples.writeOutAndReadBack(h); - - // Tweak existing one again, to ensure really worked - rtr.setBold(false); - rtr.setFontSize(17d); - rtr.setFontFamily("CourierZZ"); - - // Check it took those changes - assertFalse(rtr.isBold()); - assertEquals(17., rtr.getFontSize(), 0); - assertEquals("CourierZZ", rtr.getFontFamily()); - - - // Now, look at the one we changed, wrote out, and read back in - // Ensure it does contain our original modifications - HSLFSlide slideOneRR = readS.getSlides().get(0); - List> textParassRR = slideOneRR.getTextParagraphs(); - HSLFTextRun rtrRRa = textParassRR.get(0).get(0).getTextRuns().get(0); - - assertTrue(rtrRRa.isBold()); - assertEquals(18., rtrRRa.getFontSize(), 0); - assertEquals("Courier", rtrRRa.getFontFamily()); - readS.close(); - } - } - - /** - * Test that we can do the right things when the paragraph styles - * run out before the character styles do - */ - @Test - public void testParagraphStylesShorterTheCharStyles() { - // Check we have the right number of sheets - List slides = ssRichC.getSlides(); - assertEquals(14, slides.size()); - - // Check the number of text runs on interesting sheets - HSLFSlide slideThreeC = ssRichC.getSlides().get(2); - HSLFSlide slideSevenC = ssRichC.getSlides().get(6); - assertEquals(4, slideThreeC.getTextParagraphs().size()); - assertEquals(5, slideSevenC.getTextParagraphs().size()); - - // On slide three, we should have: - // TR: - // You are an important supplier of various items that I need - // . - // TR: - // Source: Internal focus groups - // TR: - // Illustrative Example - // . - - List> s3tr = slideThreeC.getTextParagraphs(); - List s3rtr0 = s3tr.get(0).get(0).getTextRuns(); - List s3rtr1 = s3tr.get(2).get(0).getTextRuns(); - List s3rtr2 = s3tr.get(3).get(0).getTextRuns(); - - assertEquals(2, s3rtr0.size()); - assertEquals(1, s3rtr1.size()); - assertEquals(2, s3rtr2.size()); - - assertEquals("You are an important supplier of various items that I need", s3rtr0.get(0).getRawText()); - assertEquals("", s3rtr0.get(1).getRawText()); - assertEquals("Source: Internal focus groups", s3rtr1.get(0).getRawText()); - assertEquals("Illustrative Example", s3rtr2.get(0).getRawText()); - assertEquals("", s3rtr2.get(1).getRawText()); - - // On slide seven, we have: - // TR: - // (text) - // TR: - // (text a)(text a)(text b) - // TR: - // (text) - List> s7tr = slideSevenC.getTextParagraphs(); - List s7rtr0 = s7tr.get(0); - List s7rtr1 = s7tr.get(1); - List s7rtr2 = s7tr.get(2); - - assertEquals(1, s7rtr0.size()); - assertEquals(8, s7rtr1.size()); - assertEquals(1, s7rtr2.size()); - } - - /** - * Test that we can do the right things when the paragraph styles - * run out before the character styles do, when we tweak something - * and write back out. - */ - @Test - @SuppressWarnings("unused") - public void testParagraphStylesShorterTheCharStylesWrite() throws IOException { - assertMatchesSLTWC(ssRichC); - assertMatchesFileC(ssRichC); - - HSLFSlide slideSevenC = ssRichC.getSlides().get(6); - List> s7tr = slideSevenC.getTextParagraphs(); - List s7rtr0 = s7tr.get(0).get(0).getTextRuns(); - List s7rtr1 = s7tr.get(1).get(0).getTextRuns(); - List s7rtr2 = s7tr.get(2).get(0).getTextRuns(); - - String oldText; - - // Reset the text on the last run - // Need to ensure it's a run that really has styles! - oldText = s7rtr2.get(0).getRawText(); - s7rtr2.get(0).setText( oldText ); - HSLFTextParagraph.storeText(s7tr.get(2)); - assertEquals(oldText, s7rtr2.get(0).getRawText()); - assertEquals(oldText, HSLFTextParagraph.getRawText(s7tr.get(2))); - assertEquals(oldText.length() + 1, s7rtr2.get(0).getCharacterStyle().getCharactersCovered()); - assertEquals(oldText.length() + 1, s7rtr2.get(0).getTextParagraph().getParagraphStyle().getCharactersCovered()); - assertMatchesSLTWC(ssRichC); - assertMatchesFileC(ssRichC); - - // Reset the text on a shared paragraph - oldText = s7rtr1.get(0).getRawText(); - s7rtr1.get(0).setText( oldText ); - HSLFTextParagraph.storeText(s7tr.get(1)); - assertEquals(oldText, s7rtr1.get(0).getRawText()); - assertEquals(oldText.length(), s7rtr1.get(0).getCharacterStyle().getCharactersCovered()); - assertMatchesSLTWC(ssRichC); - assertMatchesFileC(ssRichC); - - // Reset the text on a shared paragraph+character - s7rtr1.get(0).setText( s7rtr1.get(0).getRawText() ); - HSLFTextParagraph.storeText(s7tr.get(1)); - assertMatchesSLTWC(ssRichC); - assertMatchesFileC(ssRichC); - } - - /** - * Opens a new copy of SlideShow C, writes the active - * SlideListWithText out, and compares it to the write - * out of the supplied SlideShow. Also compares the - * contents. - * @param s - */ - private void assertMatchesSLTWC(HSLFSlideShow s) throws IOException { - // Grab a new copy of slideshow C - HSLFSlideShow refC = HSLFTestDataSamples.getSlideShow(filenameC); - - // Write out the 2nd SLWT in the active document - SlideListWithText refSLWT = refC.getDocumentRecord().getSlideListWithTexts()[1]; - byte[] raw_slwt = writeRecord(refSLWT); - - // Write out the same for the supplied slideshow - SlideListWithText s_SLWT = s.getDocumentRecord().getSlideListWithTexts()[1]; - byte[] s_slwt = writeRecord(s_SLWT); - - // Check the records are the same - assertEquals(refSLWT.getChildRecords().length, s_SLWT.getChildRecords().length); - for(int i=0; i txt : sl.getTextParagraphs()) { - for (HSLFTextParagraph p : txt) { - int indent = p.getIndentLevel(); - assertTrue(indent >= 0 && indent <= 4 ); - } - - } - } - ppt.close(); - } - - @Test - public void testReadParagraphStyles() throws Exception { - HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow("bullets.ppt"); - assertTrue("No Exceptions while reading file", true); - - HSLFTextParagraph rt; - List> txt; - List slide = ppt.getSlides(); - assertEquals(2, slide.size()); - - txt = slide.get(0).getTextParagraphs(); - assertEquals(2, txt.size()); - - assertEquals("Title text", HSLFTextParagraph.getRawText(txt.get(0))); - assertEquals(1, txt.get(0).size()); - rt = txt.get(0).get(0); - assertFalse(rt.isBullet()); - - String expected = - "This is a text placeholder that \r" + - "follows the design pattern\r" + - "Defined in the slide master\r" + - "and has bullets by default"; - assertEquals(expected, HSLFTextParagraph.getRawText(txt.get(1))); - assertEquals(4, txt.get(1).size()); - rt = txt.get(1).get(0); - assertEquals('\u2022', (char)rt.getBulletChar()); - assertTrue(rt.isBullet()); - - - txt = slide.get(1).getTextParagraphs(); - assertEquals(2, txt.size()); - - expected = - "I\u2019m a text box\r" + - "With bullets\r" + - "That follow the design pattern\r" + - "From the slide master"; - assertEquals(expected, HSLFTextParagraph.getRawText(txt.get(0))); - assertEquals(4, txt.get(0).size()); - rt = txt.get(0).get(0); - assertTrue(rt.isBullet()); - assertEquals('\u2022', (char)rt.getBulletChar()); - - expected = - "I\u2019m a text box with user-defined\r" + - "bullet character"; - assertEquals(expected, HSLFTextParagraph.getRawText(txt.get(1))); - assertEquals(2, txt.get(1).size()); - rt = txt.get(1).get(0); - assertTrue(rt.isBullet()); - assertEquals('\u263A', (char)rt.getBulletChar()); - ppt.close(); - } - - @Test - public void testSetParagraphStyles() throws IOException { - HSLFSlideShow ppt1 = new HSLFSlideShow(); - - HSLFSlide slide = ppt1.createSlide(); - - HSLFTextBox shape = new HSLFTextBox(); - shape.setText( - "Hello, World!\r" + - "This should be\r" + - "Multiline text"); - HSLFTextParagraph rt = shape.getTextParagraphs().get(0); - HSLFTextRun tr = rt.getTextRuns().get(0); - tr.setFontSize(42d); - rt.setBullet(true); - rt.setLeftMargin(50d); - rt.setIndent(0d); - rt.setBulletChar('\u263A'); - slide.addShape(shape); - - assertEquals(42.0, tr.getFontSize(), 0); - assertEquals(true, rt.isBullet()); - assertEquals(50.0, rt.getLeftMargin(), 0); - assertEquals(0, rt.getIndent(), 0); - assertEquals('\u263A', (char)rt.getBulletChar()); - - shape.setAnchor(new java.awt.Rectangle(50, 50, 500, 300)); - slide.addShape(shape); - - //serialize and read again - HSLFSlideShow ppt2 = HSLFTestDataSamples.writeOutAndReadBack(ppt1); - slide = ppt2.getSlides().get(0); - shape = (HSLFTextBox)slide.getShapes().get(0); - rt = shape.getTextParagraphs().get(0); - tr = rt.getTextRuns().get(0); - assertEquals(42.0, tr.getFontSize(), 0); - assertEquals(true, rt.isBullet()); - assertEquals(50.0, rt.getLeftMargin(), 0); - assertEquals(0, rt.getIndent(), 0); - assertEquals('\u263A', (char)rt.getBulletChar()); - ppt2.close(); - ppt1.close(); - } - - @Test - public void testAddText() throws Exception { - HSLFSlideShow ppt1 = HSLFTestDataSamples.getSlideShow("bullets.ppt"); - assertTrue("No Exceptions while reading file", true); - - HSLFTextParagraph rt; - HSLFTextRun tr; - List> txt; - List slides = ppt1.getSlides(); - - assertEquals(2, slides.size()); - txt = slides.get(0).getTextParagraphs(); - assertEquals(2, txt.size()); - - assertEquals("Title text", HSLFTextParagraph.getRawText(txt.get(0))); - assertEquals(1, txt.get(0).size()); - rt = txt.get(0).get(0); - assertFalse(rt.isBullet()); - - // Add some new text - HSLFTextParagraph.appendText(txt.get(0), "Foo! I'm new!", true); - assertEquals(2, txt.get(0).size()); - - rt = txt.get(0).get(0); - tr = rt.getTextRuns().get(0); - assertFalse(tr.isBold()); - assertEquals("Title text\r", tr.getRawText()); - rt = txt.get(0).get(1); - tr = rt.getTextRuns().get(0); - assertFalse(tr.isBold()); - assertEquals("Foo! I'm new!", tr.getRawText()); - tr.setBold(true); - HSLFTextParagraph.storeText(txt.get(0)); - - // And some more, attributes will be copied from previous run - HSLFTextParagraph.appendText(txt.get(0), "Me too!", true); - HSLFTextParagraph.storeText(txt.get(0)); - assertEquals(3, txt.get(0).size()); - rt = txt.get(0).get(0); - tr = rt.getTextRuns().get(0); - assertFalse(tr.isBold()); - assertEquals("Title text\r", tr.getRawText()); - rt = txt.get(0).get(1); - tr = rt.getTextRuns().get(0); - assertTrue(tr.isBold()); - assertEquals("Foo! I'm new!\r", tr.getRawText()); - rt = txt.get(0).get(2); - tr = rt.getTextRuns().get(0); - assertTrue(tr.isBold()); - assertEquals("Me too!", tr.getRawText()); - - // Save and re-open - HSLFSlideShow ppt2 = HSLFTestDataSamples.writeOutAndReadBack(ppt1); - slides = ppt2.getSlides(); - - assertEquals(2, slides.size()); - - txt = slides.get(0).getTextParagraphs(); - assertEquals(2, txt.size()); - assertEquals(3, txt.get(0).size()); - rt = txt.get(0).get(0); - tr = rt.getTextRuns().get(0); - assertFalse(tr.isBold()); - assertEquals("Title text\r", tr.getRawText()); - rt = txt.get(0).get(1); - tr = rt.getTextRuns().get(0); - assertTrue(tr.isBold()); - assertEquals("Foo! I'm new!\r", tr.getRawText()); - rt = txt.get(0).get(2); - tr = rt.getTextRuns().get(0); - assertTrue(tr.isBold()); - assertEquals("Me too!", tr.getRawText()); - ppt2.close(); - ppt1.close(); - } - - @Test - public void testChineseParagraphs() throws Exception { - List rts; - HSLFTextRun rt; - List> txt; - List slides = ssChinese.getSlides(); - - // One slide - assertEquals(1, slides.size()); - - // One block of text within that - txt = slides.get(0).getTextParagraphs(); - assertEquals(1, txt.size()); - - // One rich block of text in that - text is all the same style - // TODO Is this completely correct? - rts = txt.get(0).get(0).getTextRuns(); - assertEquals(1, rts.size()); - rt = rts.get(0); - - // Check we can get the english text out of that - String text = rt.getRawText(); - assertContains(text, "Single byte"); - // And the chinese - assertContains(txt.get(0).get(3).getTextRuns().get(0).getRawText(), "\uff8a\uff9d\uff76\uff78"); - - // It isn't bold or italic - assertFalse(rt.isBold()); - assertFalse(rt.isItalic()); - - // Font is Calibri - assertEquals("Calibri", rt.getFontFamily()); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestSheetText.java b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestSheetText.java deleted file mode 100644 index 7d2e6ed26..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestSheetText.java +++ /dev/null @@ -1,96 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.usermodel; - -import static org.junit.Assert.assertEquals; - -import java.io.IOException; -import java.util.List; - -import org.apache.poi.hslf.HSLFTestDataSamples; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -/** - * Tests that SlideShow returns Sheets which have the right text in them - */ -public final class TestSheetText { - // SlideShow primed on the test data - private HSLFSlideShow ss; - - @Before - public void init() throws IOException { - ss = HSLFTestDataSamples.getSlideShow("basic_test_ppt_file.ppt"); - } - - @After - public void tearDown() throws IOException { - ss.close(); - } - - @Test - public void testSheetOne() { - HSLFSheet slideOne = ss.getSlides().get(0); - - String[] expectText = new String[] {"This is a test title","This is a test subtitle\rThis is on page 1"}; - assertEquals(expectText.length, slideOne.getTextParagraphs().size()); - int i = 0; - for(List textParas : slideOne.getTextParagraphs()) { - assertEquals(expectText[i++], HSLFTextParagraph.getRawText(textParas)); - } - } - - public void testSheetTwo() { - HSLFSheet slideTwo = ss.getSlides().get(1); - String[] expectText = new String[] {"This is the title on page 2","This is page two\rIt has several blocks of text\rNone of them have formatting"}; - assertEquals(expectText.length, slideTwo.getTextParagraphs().size()); - int i = 0; - for(List textParas : slideTwo.getTextParagraphs()) { - assertEquals(expectText[i++], HSLFTextParagraph.getRawText(textParas)); - } - } - - /** - * Check we can still get the text from a file where the - * TextProps don't have enough data. - * (Make sure we don't screw up / throw an exception etc) - */ - public void testWithShortTextPropData() throws IOException { - HSLFSlideShow sss = HSLFTestDataSamples.getSlideShow("iisd_report.ppt"); - - // Should come out with 10 slides, no notes - assertEquals(10, sss.getSlides().size()); - assertEquals(0, sss.getNotes().size()); - - // Check text on first slide - HSLFSlide s = sss.getSlides().get(0); - String exp = - "Realizing the Development Dividend:\n" + - "Community Capacity Building and CDM.\n" + - "Can they co-exist?\n\n" + - "Gay Harley\n" + - "Clean Development Alliance\n" + - "COP 11 \u2013 MOP 1\n" + // special long hyphen - "December 5, 2005\n"; - - assertEquals(1, s.getTextParagraphs().size()); - assertEquals(exp, HSLFTextParagraph.getRawText(s.getTextParagraphs().get(0))); - sss.close(); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestSlideOrdering.java b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestSlideOrdering.java deleted file mode 100644 index d4a6e49c8..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestSlideOrdering.java +++ /dev/null @@ -1,134 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.usermodel; - -import static org.junit.Assert.assertEquals; - -import java.io.IOException; -import java.util.List; - -import org.apache.poi.hslf.HSLFTestDataSamples; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -/** - * Tests that SlideShow returns Sheets in the right order - */ -public final class TestSlideOrdering { - // Simple slideshow, record order matches slide order - private HSLFSlideShow ssA; - // Complex slideshow, record order doesn't match slide order - private HSLFSlideShow ssB; - - @Before - public void init() throws IOException { - ssA = HSLFTestDataSamples.getSlideShow("basic_test_ppt_file.ppt"); - ssB = HSLFTestDataSamples.getSlideShow("incorrect_slide_order.ppt"); - } - - @After - public void tearDown() throws IOException { - ssA.close(); - ssB.close(); - } - - /** - * Test the simple case - record order matches slide order - */ - @Test - public void testSimpleCase() { - assertEquals(2, ssA.getSlides().size()); - - HSLFSlide s1 = ssA.getSlides().get(0); - HSLFSlide s2 = ssA.getSlides().get(1); - - String[] firstTRs = new String[] { "This is a test title", "This is the title on page 2" }; - - assertEquals(firstTRs[0], HSLFTextParagraph.getRawText(s1.getTextParagraphs().get(0))); - assertEquals(firstTRs[1], HSLFTextParagraph.getRawText(s2.getTextParagraphs().get(0))); - } - - /** - * Test the complex case - record order differs from slide order - */ - @Test - public void testComplexCase() { - assertEquals(3, ssB.getSlides().size()); - int i=1; - for (HSLFSlide s : ssB.getSlides()) { - assertEquals("Slide "+(i++), HSLFTextParagraph.getRawText(s.getTextParagraphs().get(0))); - } - } - - /** - * Assert that the order of slides is correct. - * - * @param filename - * file name of the slide show to assert - * @param titles - * array of reference slide titles - */ - protected void assertSlideOrdering(String filename, String[] titles) throws IOException { - HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow(filename); - List slide = ppt.getSlides(); - - assertEquals(titles.length, slide.size()); - for (int i = 0; i < slide.size(); i++) { - String title = slide.get(i).getTitle(); - assertEquals("Wrong slide title in " + filename, titles[i], title); - } - ppt.close(); - } - - @Test - public void testTitles() throws Exception { - assertSlideOrdering("basic_test_ppt_file.ppt", new String[] { - "This is a test title", "This is the title on page 2" }); - - assertSlideOrdering("incorrect_slide_order.ppt", new String[] { "Slide 1", - "Slide 2", "Slide 3" }); - - assertSlideOrdering("next_test_ppt_file.ppt", new String[] { - "This is a test title", "This is the title on page 2" }); - - assertSlideOrdering("Single_Coloured_Page.ppt", - new String[] { "This is a title, it" + (char) 0x2019 + "s in black" }); - - assertSlideOrdering("Single_Coloured_Page_With_Fonts_and_Alignments.ppt", - new String[] { "This is a title, it" + (char) 0x2019 + "s in black" }); - - assertSlideOrdering( - "ParagraphStylesShorterThanCharStyles.ppt", - new String[] { - "ROMANCE: AN ANALYSIS", - "AGENDA", - "You are an important supplier of various items that I need", - '\n' + "Although The Psycho set back my relationship process, recovery is luckily enough under way", - "Since the time that we seriously go out together, you rank highly among existing relationships", - "Although our personal interests are mostly compatible, the greatest gap exists in Sex and Shopping", - "Your physical characteristics are strong when compared with your competition", - "The combination of your high physical appearance and personality rank you highly, although your sister is also a top prospect", - "When people found out that we were going out, their responses have been mixed", - "The benchmark of relationship lifecycles, suggests that we are on schedule", - "In summary we can say that we are on the right track, but we must remain aware of possible roadblocks ", - "THE ANSWER", - "Unfortunately a huge disconnect exists between my needs and your existing service", - "SUMMARY", }); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestSoundData.java b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestSoundData.java deleted file mode 100644 index 8a47f6568..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestSoundData.java +++ /dev/null @@ -1,46 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.usermodel; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; - -import org.apache.poi.hslf.HSLFTestDataSamples; -import org.junit.Test; - -/** - * Test reading sound data from a ppt - */ -public final class TestSoundData { - /** - * Read a reference sound file from disk and compare it from the data extracted from the slide show - */ - @Test - public void testSounds() throws Exception { - //read the reference sound file - byte[] ref_data = HSLFTestDataSamples.getTestDataFileContent("ringin.wav"); - - HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow("sound.ppt"); - - HSLFSoundData[] sound = ppt.getSoundData(); - assertEquals("Expected 1 sound", 1, sound.length); - - assertArrayEquals(ref_data, sound[0].getData()); - ppt.close(); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestTable.java b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestTable.java deleted file mode 100644 index 7fe7d269f..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestTable.java +++ /dev/null @@ -1,157 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.hslf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.awt.Color; -import java.awt.geom.Rectangle2D; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.List; - -import org.apache.poi.hslf.HSLFTestDataSamples; -import org.apache.poi.sl.draw.DrawTableShape; -import org.apache.poi.sl.usermodel.StrokeStyle; -import org.junit.Test; - - -/** - * Table related tests - */ -public class TestTable { - @Test - public void moveTable() throws IOException { - HSLFSlideShow ppt = new HSLFSlideShow(); - HSLFSlide slide = ppt.createSlide(); - int rows = 3, cols = 5; - HSLFTable table = slide.createTable(rows, cols); - for (int row=0; row slides = ppt.getSlides(); - assertEquals(1, slides.size()); - checkSlide(slides.get(0)); - ppt.close(); - } - - private void checkSlide(final HSLFSlide s) { - List> textRuns = s.getTextParagraphs(); - assertEquals(2, textRuns.size()); - - HSLFTextRun textRun = textRuns.get(0).get(0).getTextRuns().get(0); - assertEquals("Table sample", textRun.getRawText().trim()); - assertEquals(1, textRuns.get(0).get(0).getTextRuns().size()); - assertFalse(textRun.getTextParagraph().isBullet()); - - assertEquals("Dummy text", HSLFTextParagraph.getRawText(textRuns.get(1))); - - List shapes = s.getShapes(); - assertNotNull(shapes); - assertEquals(3, shapes.size()); - assertTrue(shapes.get(2) instanceof HSLFTable); - final HSLFTable table = (HSLFTable) shapes.get(2); - assertEquals(4, table.getNumberOfColumns()); - assertEquals(6, table.getNumberOfRows()); - for (int x = 0; x < 4; x ++) { - assertEquals("TH Cell " + (x + 1), HSLFTextParagraph.getRawText(table.getCell(0, x).getTextParagraphs())); - for (int y = 1; y < 6; y++) { - assertEquals("Row " + y + ", Cell " + (x + 1), table.getCell(y, x).getText()); - } - } - } - - @Test - public void testAddText() throws IOException { - HSLFSlideShow ppt1 = new HSLFSlideShow(); - HSLFSlide slide = ppt1.createSlide(); - HSLFTable tab = slide.createTable(4, 5); - - int rows = tab.getNumberOfRows(); - int cols = tab.getNumberOfColumns(); - for (int row=0; row> textParas = slideOne.getTextParagraphs(); - - assertEquals(2, textParas.size()); - - // Get text works with \n - assertEquals("This is a test title", HSLFTextParagraph.getText(textParas.get(0))); - assertEquals("This is a test subtitle\nThis is on page 1", HSLFTextParagraph.getText(textParas.get(1))); - - // Raw text has \r instead - assertEquals("This is a test title", HSLFTextParagraph.getRawText(textParas.get(0))); - assertEquals("This is a test subtitle\rThis is on page 1", HSLFTextParagraph.getRawText(textParas.get(1))); - - - // Now check on a rich text run - HSLFSlide slideOneR = ssRich.getSlides().get(0); - textParas = slideOneR.getTextParagraphs(); - - assertEquals(2, textParas.size()); - assertEquals("This is a title, it\u2019s in black", HSLFTextParagraph.getText(textParas.get(0))); - assertEquals("This is the subtitle, in bold\nThis bit is blue and italic\nThis bit is red (normal)", HSLFTextParagraph.getText(textParas.get(1))); - assertEquals("This is a title, it\u2019s in black", HSLFTextParagraph.getRawText(textParas.get(0))); - assertEquals("This is the subtitle, in bold\rThis bit is blue and italic\rThis bit is red (normal)", HSLFTextParagraph.getRawText(textParas.get(1))); - } - - /** - * Test to ensure changing non rich text bytes->bytes works correctly - */ - @Test - public void testSetText() { - HSLFSlide slideOne = ss.getSlides().get(0); - List> textRuns = slideOne.getTextParagraphs(); - HSLFTextParagraph run = textRuns.get(0).get(0); - HSLFTextRun tr = run.getTextRuns().get(0); - - // Check current text - assertEquals("This is a test title", tr.getRawText()); - - // Change - String changeTo = "New test title"; - tr.setText(changeTo); - assertEquals(changeTo, tr.getRawText()); - - // Ensure trailing \n's are NOT stripped, it is legal to set a text with a trailing '\r' - tr.setText(changeTo + "\n"); - assertEquals(changeTo + "\r", tr.getRawText()); - } - - /** - * Test to ensure that changing non rich text between bytes and - * chars works correctly - */ - @SuppressWarnings("unused") - @Test - public void testAdvancedSetText() { - HSLFSlide slideOne = ss.getSlides().get(0); - List paras = slideOne.getTextParagraphs().get(0); - HSLFTextParagraph para = paras.get(0); - - TextHeaderAtom tha = null; - TextBytesAtom tba = null; - TextCharsAtom tca = null; - for (Record r : para.getRecords()) { - if (r instanceof TextHeaderAtom) tha = (TextHeaderAtom)r; - else if (r instanceof TextBytesAtom) tba = (TextBytesAtom)r; - else if (r instanceof TextCharsAtom) tca = (TextCharsAtom)r; - } - - // Bytes -> Bytes - assertNull(tca); - assertNotNull(tba); - // assertFalse(run._isUnicode); - assertEquals("This is a test title", para.getTextRuns().get(0).getRawText()); - - String changeBytesOnly = "New Test Title"; - HSLFTextParagraph.setText(paras, changeBytesOnly); - para = paras.get(0); - tha = null; tba = null; tca = null; - for (Record r : para.getRecords()) { - if (r instanceof TextHeaderAtom) tha = (TextHeaderAtom)r; - else if (r instanceof TextBytesAtom) tba = (TextBytesAtom)r; - else if (r instanceof TextCharsAtom) tca = (TextCharsAtom)r; - } - - assertEquals(changeBytesOnly, HSLFTextParagraph.getRawText(paras)); - assertNull(tca); - assertNotNull(tba); - - // Bytes -> Chars - assertNull(tca); - assertNotNull(tba); - assertEquals(changeBytesOnly, HSLFTextParagraph.getRawText(paras)); - - String changeByteChar = "This is a test title with a '\u0121' g with a dot"; - HSLFTextParagraph.setText(paras, changeByteChar); - para = paras.get(0); - tha = null; tba = null; tca = null; - for (Record r : para.getRecords()) { - if (r instanceof TextHeaderAtom) tha = (TextHeaderAtom)r; - else if (r instanceof TextBytesAtom) tba = (TextBytesAtom)r; - else if (r instanceof TextCharsAtom) tca = (TextCharsAtom)r; - } - - assertEquals(changeByteChar, HSLFTextParagraph.getRawText(paras)); - assertNotNull(tca); - assertNull(tba); - - // Chars -> Chars - assertNull(tba); - assertNotNull(tca); - assertEquals(changeByteChar, HSLFTextParagraph.getRawText(paras)); - - String changeCharChar = "This is a test title with a '\u0147' N with a hat"; - HSLFTextParagraph.setText(paras, changeCharChar); - para = paras.get(0); - tha = null; tba = null; tca = null; - for (Record r : para.getRecords()) { - if (r instanceof TextHeaderAtom) tha = (TextHeaderAtom)r; - else if (r instanceof TextBytesAtom) tba = (TextBytesAtom)r; - else if (r instanceof TextCharsAtom) tca = (TextCharsAtom)r; - } - - assertEquals(changeCharChar, HSLFTextParagraph.getRawText(paras)); - assertNotNull(tca); - assertNull(tba); - } - - /** - * Tests to ensure that non rich text has the right default rich text run - * set up for it - */ - @Test - public void testGetRichTextNonRich() { - HSLFSlide slideOne = ss.getSlides().get(0); - List> textParass = slideOne.getTextParagraphs(); - - assertEquals(2, textParass.size()); - - List trA = textParass.get(0); - List trB = textParass.get(1); - - assertEquals(1, trA.size()); - assertEquals(2, trB.size()); - - HSLFTextRun rtrA = trA.get(0).getTextRuns().get(0); - HSLFTextRun rtrB = trB.get(0).getTextRuns().get(0); - - assertEquals(HSLFTextParagraph.getRawText(trA), rtrA.getRawText()); - assertEquals(HSLFTextParagraph.getRawText(trB.subList(0, 1)), rtrB.getRawText()); - } - - /** - * Tests to ensure that the rich text runs are built up correctly - */ - @Test - public void testGetRichText() { - HSLFSlide slideOne = ssRich.getSlides().get(0); - List> textParass = slideOne.getTextParagraphs(); - - assertEquals(2, textParass.size()); - - List trA = textParass.get(0); - List trB = textParass.get(1); - - assertEquals(1, trA.size()); - assertEquals(3, trB.size()); - - HSLFTextRun rtrA = trA.get(0).getTextRuns().get(0); - HSLFTextRun rtrB = trB.get(0).getTextRuns().get(0); - HSLFTextRun rtrC = trB.get(1).getTextRuns().get(0); - HSLFTextRun rtrD = trB.get(2).getTextRuns().get(0); - - assertEquals(HSLFTextParagraph.getRawText(trA), rtrA.getRawText()); - - String trBstr = HSLFTextParagraph.getRawText(trB); - assertEquals(trBstr.substring(0, 30), rtrB.getRawText()); - assertEquals(trBstr.substring(30,58), rtrC.getRawText()); - assertEquals(trBstr.substring(58,82), rtrD.getRawText()); - - // Same paragraph styles - assertEquals(trB.get(0).getParagraphStyle(), trB.get(1).getParagraphStyle()); - assertEquals(trB.get(0).getParagraphStyle(), trB.get(2).getParagraphStyle()); - - // Different char styles - assertNotEquals(rtrB.getCharacterStyle(), rtrC.getCharacterStyle()); - assertNotEquals(rtrB.getCharacterStyle(), rtrD.getCharacterStyle()); - assertNotEquals(rtrC.getCharacterStyle(), rtrD.getCharacterStyle()); - } - - /** - * Tests to ensure that setting the text where the text isn't rich, - * ensuring that everything stays with the same default styling - */ - @Test - public void testSetTextWhereNotRich() { - HSLFSlide slideOne = ss.getSlides().get(0); - List> textParass = slideOne.getTextParagraphs(); - List trB = textParass.get(0); - assertEquals(1, trB.size()); - - HSLFTextRun rtrB = trB.get(0).getTextRuns().get(0); - assertEquals(HSLFTextParagraph.getText(trB), rtrB.getRawText()); - - // Change text via normal - HSLFTextParagraph.setText(trB, "Test Foo Test"); - rtrB = trB.get(0).getTextRuns().get(0); - assertEquals("Test Foo Test", HSLFTextParagraph.getRawText(trB)); - assertEquals("Test Foo Test", rtrB.getRawText()); - } - - /** - * Tests to ensure that setting the text where the text is rich - * sets everything to the same styling - */ - @Test - public void testSetTextWhereRich() { - HSLFSlide slideOne = ssRich.getSlides().get(0); - List> textParass = slideOne.getTextParagraphs(); - List trB = textParass.get(1); - assertEquals(3, trB.size()); - - HSLFTextRun rtrB = trB.get(0).getTextRuns().get(0); - HSLFTextRun rtrC = trB.get(1).getTextRuns().get(0); - HSLFTextRun rtrD = trB.get(2).getTextRuns().get(0); - TextPropCollection tpBP = rtrB.getTextParagraph().getParagraphStyle(); - TextPropCollection tpBC = rtrB.getCharacterStyle(); - TextPropCollection tpCP = rtrC.getTextParagraph().getParagraphStyle(); - TextPropCollection tpCC = rtrC.getCharacterStyle(); - TextPropCollection tpDP = rtrD.getTextParagraph().getParagraphStyle(); - TextPropCollection tpDC = rtrD.getCharacterStyle(); - -// assertEquals(trB.getRawText().substring(0, 30), rtrB.getRawText()); - assertNotNull(tpBP); - assertNotNull(tpBC); - assertNotNull(tpCP); - assertNotNull(tpCC); - assertNotNull(tpDP); - assertNotNull(tpDC); - assertEquals(tpBP,tpCP); - assertEquals(tpBP,tpDP); - assertEquals(tpCP,tpDP); - assertNotEquals(tpBC,tpCC); - assertNotEquals(tpBC,tpDC); - assertNotEquals(tpCC,tpDC); - - // Change text via normal - HSLFTextParagraph.setText(trB, "Test Foo Test"); - - // Ensure now have first style - assertEquals(1, trB.get(0).getTextRuns().size()); - rtrB = trB.get(0).getTextRuns().get(0); - assertEquals("Test Foo Test", HSLFTextParagraph.getRawText(trB)); - assertEquals("Test Foo Test", rtrB.getRawText()); - assertNotNull(rtrB.getCharacterStyle()); - assertNotNull(rtrB.getTextParagraph().getParagraphStyle()); - assertEquals( tpBP, rtrB.getTextParagraph().getParagraphStyle() ); - assertEquals( tpBC, rtrB.getCharacterStyle() ); - } - - /** - * Test to ensure the right stuff happens if we change the text - * in a rich text run, that doesn't happen to actually be rich - */ - @Test - public void testChangeTextInRichTextRunNonRich() { - HSLFSlide slideOne = ss.getSlides().get(0); - List> textRuns = slideOne.getTextParagraphs(); - List trB = textRuns.get(1); - assertEquals(1, trB.get(0).getTextRuns().size()); - - HSLFTextRun rtrB = trB.get(0).getTextRuns().get(0); - assertEquals(HSLFTextParagraph.getRawText(trB.subList(0, 1)), rtrB.getRawText()); - assertNotNull(rtrB.getCharacterStyle()); - assertNotNull(rtrB.getTextParagraph().getParagraphStyle()); - - // Change text via rich - rtrB.setText("Test Test Test"); - assertEquals("Test Test Test", HSLFTextParagraph.getRawText(trB.subList(0, 1))); - assertEquals("Test Test Test", rtrB.getRawText()); - - // Will now have dummy props - assertNotNull(rtrB.getCharacterStyle()); - assertNotNull(rtrB.getTextParagraph().getParagraphStyle()); - } - - /** - * Tests to ensure changing the text within rich text runs works - * correctly - */ - @Test - public void testChangeTextInRichTextRun() { - HSLFSlide slideOne = ssRich.getSlides().get(0); - List> textParass = slideOne.getTextParagraphs(); - List trB = textParass.get(1); - assertEquals(3, trB.size()); - - // We start with 3 text runs, each with their own set of styles, - // but all sharing the same paragraph styles - HSLFTextRun rtrB = trB.get(0).getTextRuns().get(0); - HSLFTextRun rtrC = trB.get(1).getTextRuns().get(0); - HSLFTextRun rtrD = trB.get(2).getTextRuns().get(0); - TextPropCollection tpBP = rtrB.getTextParagraph().getParagraphStyle(); - TextPropCollection tpBC = rtrB.getCharacterStyle(); - TextPropCollection tpCP = rtrC.getTextParagraph().getParagraphStyle(); - TextPropCollection tpCC = rtrC.getCharacterStyle(); - TextPropCollection tpDP = rtrD.getTextParagraph().getParagraphStyle(); - TextPropCollection tpDC = rtrD.getCharacterStyle(); - - // Check text and stylings - assertEquals(HSLFTextParagraph.getRawText(trB).substring(0, 30), rtrB.getRawText()); - assertNotNull(tpBP); - assertNotNull(tpBC); - assertNotNull(tpCP); - assertNotNull(tpCC); - assertNotNull(tpDP); - assertNotNull(tpDC); - assertEquals(tpBP, tpCP); - assertEquals(tpBP, tpDP); - assertEquals(tpCP, tpDP); - assertNotEquals(tpBC, tpCC); - assertNotEquals(tpBC, tpDC); - assertNotEquals(tpCC, tpDC); - - // Check text in the rich runs - assertEquals("This is the subtitle, in bold\r", rtrB.getRawText()); - assertEquals("This bit is blue and italic\r", rtrC.getRawText()); - assertEquals("This bit is red (normal)", rtrD.getRawText()); - - String newBText = "New Subtitle, will still be bold\n"; - String newCText = "New blue and italic text\n"; - String newDText = "Funky new normal red text"; - rtrB.setText(newBText); - rtrC.setText(newCText); - rtrD.setText(newDText); - HSLFTextParagraph.storeText(trB); - - assertEquals(newBText.replace('\n','\r'), rtrB.getRawText()); - assertEquals(newCText.replace('\n','\r'), rtrC.getRawText()); - assertEquals(newDText.replace('\n','\r'), rtrD.getRawText()); - - assertEquals(newBText.replace('\n','\r') + newCText.replace('\n','\r') + newDText.replace('\n','\r'), HSLFTextParagraph.getRawText(trB)); - - // The styles should have been updated for the new sizes - assertEquals(newBText.length(), tpBC.getCharactersCovered()); - assertEquals(newCText.length(), tpCC.getCharactersCovered()); - assertEquals(newDText.length()+1, tpDC.getCharactersCovered()); // Last one is always one larger - - // Paragraph style should be sum of text length - assertEquals( - newBText.length() + newCText.length() + newDText.length() +1, - tpBP.getCharactersCovered() + tpCP.getCharactersCovered() + tpDP.getCharactersCovered() - ); - - // Check stylings still as expected - TextPropCollection ntpBC = rtrB.getCharacterStyle(); - TextPropCollection ntpCC = rtrC.getCharacterStyle(); - TextPropCollection ntpDC = rtrD.getCharacterStyle(); - assertEquals(tpBC.getTextPropList(), ntpBC.getTextPropList()); - assertEquals(tpCC.getTextPropList(), ntpCC.getTextPropList()); - assertEquals(tpDC.getTextPropList(), ntpDC.getTextPropList()); - } - - - /** - * Test case for Bug 41015. - * - * In some cases RichTextRun.getText() threw StringIndexOutOfBoundsException because - * of the wrong list of potential paragraph properties defined in StyleTextPropAtom. - * - */ - @Test - public void testBug41015() throws IOException { - List rt; - - HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow("bug-41015.ppt"); - HSLFSlide sl = ppt.getSlides().get(0); - List> textParass = sl.getTextParagraphs(); - assertEquals(2, textParass.size()); - - List textParas = textParass.get(0); - rt = textParass.get(0).get(0).getTextRuns(); - assertEquals(1, rt.size()); - assertEquals(0, textParass.get(0).get(0).getIndentLevel()); - assertEquals("sdfsdfsdf", rt.get(0).getRawText()); - - textParas = textParass.get(1); - String texts[] = {"Sdfsdfsdf\r","Dfgdfg\r","Dfgdfgdfg\r","Sdfsdfs\r","Sdfsdf\r"}; - int indents[] = {0,0,0,1,1}; - int i=0; - for (HSLFTextParagraph p : textParas) { - assertEquals(texts[i], p.getTextRuns().get(0).getRawText()); - assertEquals(indents[i], p.getIndentLevel()); - i++; - } - ppt.close(); - } - - /** - * Test creation of TextRun objects. - */ - @Test - public void testAddTextRun() throws IOException { - HSLFSlideShow ppt = new HSLFSlideShow(); - HSLFSlide slide = ppt.createSlide(); - - assertEquals(0, slide.getTextParagraphs().size()); - - HSLFTextBox shape1 = new HSLFTextBox(); - List run1 = shape1.getTextParagraphs(); - shape1.setText("Text 1"); - slide.addShape(shape1); - - //The array of Slide's text runs must be updated when new text shapes are added. - List> runs = slide.getTextParagraphs(); - assertNotNull(runs); - assertSame(run1, runs.get(0)); - - HSLFTextBox shape2 = new HSLFTextBox(); - List run2 = shape2.getTextParagraphs(); - shape2.setText("Text 2"); - slide.addShape(shape2); - - runs = slide.getTextParagraphs(); - assertEquals(2, runs.size()); - - assertSame(run1, runs.get(0)); - assertSame(run2, runs.get(1)); - - // as getShapes() - List sh = slide.getShapes(); - assertEquals(2, sh.size()); - assertTrue(sh.get(0) instanceof HSLFTextBox); - HSLFTextBox box1 = (HSLFTextBox)sh.get(0); - assertSame(run1, box1.getTextParagraphs()); - HSLFTextBox box2 = (HSLFTextBox)sh.get(1); - assertSame(run2, box2.getTextParagraphs()); - - // test Table - a complex group of shapes containing text objects - HSLFSlide slide2 = ppt.createSlide(); - assertTrue(slide2.getTextParagraphs().isEmpty()); - HSLFTable table = new HSLFTable(2, 2); - slide2.addShape(table); - runs = slide2.getTextParagraphs(); - assertNotNull(runs); - assertEquals(4, runs.size()); - ppt.close(); - } - - @Test - public void test48916() throws IOException { - HSLFSlideShow ppt1 = HSLFTestDataSamples.getSlideShow("SampleShow.ppt"); - List slides = ppt1.getSlides(); - for(HSLFSlide slide : slides){ - for(HSLFShape sh : slide.getShapes()){ - if (!(sh instanceof HSLFTextShape)) continue; - HSLFTextShape tx = (HSLFTextShape)sh; - List paras = tx.getTextParagraphs(); - //verify that records cached in TextRun and EscherTextboxWrapper are the same - Record[] runChildren = paras.get(0).getRecords(); - Record[] txboxChildren = tx.getEscherTextboxWrapper().getChildRecords(); - assertEquals(runChildren.length, txboxChildren.length); - for(int i=0; i < txboxChildren.length; i++){ - assertSame(txboxChildren[i], runChildren[i]); - } - // caused NPE prior to fix of Bugzilla #48916 - for (HSLFTextParagraph p : paras) { - for (HSLFTextRun rt : p.getTextRuns()) { - rt.setBold(true); - rt.setFontColor(Color.RED); - } - } - // tx.storeText(); - } - } - - HSLFSlideShow ppt2 = HSLFTestDataSamples.writeOutAndReadBack(ppt1); - for(HSLFSlide slide : ppt2.getSlides()){ - for(HSLFShape sh : slide.getShapes()){ - if(sh instanceof HSLFTextShape){ - HSLFTextShape tx = (HSLFTextShape)sh; - List run = tx.getTextParagraphs(); - HSLFTextRun rt = run.get(0).getTextRuns().get(0); - assertTrue(rt.isBold()); - assertTrue(sameColor(Color.RED, rt.getFontColor())); - } - } - } - ppt2.close(); - ppt1.close(); - } - - @Test - public void test52244() throws IOException { - HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow("52244.ppt"); - HSLFSlide slide = ppt.getSlides().get(0); - - int sizes[] = { 36, 24, 12, 32, 12, 12 }; - - int i=0; - for (List textParas : slide.getTextParagraphs()) { - assertEquals("Arial", textParas.get(0).getTextRuns().get(0).getFontFamily()); - assertEquals(sizes[i++], textParas.get(0).getTextRuns().get(0).getFontSize().intValue()); - } - ppt.close(); - } - - @Test - public void testAppendEmpty() throws IOException { - HSLFSlideShow ppt = new HSLFSlideShow(); - HSLFSlide s = ppt.createSlide(); - HSLFTextBox title = s.addTitle(); - title.setText(""); - title.appendText("\n", true); - title.appendText("para", true); - ppt.close(); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestTextShape.java b/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestTextShape.java deleted file mode 100644 index 1cfe61379..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/usermodel/TestTextShape.java +++ /dev/null @@ -1,224 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.poi.hslf.HSLFTestDataSamples; -import org.apache.poi.hslf.record.TextHeaderAtom; -import org.apache.poi.sl.usermodel.ShapeType; -import org.junit.Test; - -/** - * Verify behavior of TextShape and its sub-classes - */ -public final class TestTextShape { - @Test - public void createAutoShape(){ - HSLFTextShape shape = new HSLFAutoShape(ShapeType.TRAPEZOID); - assertNull(shape.getEscherTextboxWrapper()); - assertNotNull(shape.getTextParagraphs()); - assertNotNull(shape.getEscherTextboxWrapper()); - assertEquals("", shape.getText()); - assertEquals(-1, shape.getTextParagraphs().get(0).getIndex()); - } - - @Test - public void createTextBox(){ - HSLFTextShape shape = new HSLFTextBox(); - List paras = shape.getTextParagraphs(); - assertNotNull(paras); - assertNotNull(shape.getText()); - assertNotNull(shape.getEscherTextboxWrapper()); - - assertNotNull(shape.getTextParagraphs()); - assertNotNull(shape.getEscherTextboxWrapper()); - assertEquals("", shape.getText()); - - } - - /** - * Verify we can get text from TextShape in the following cases: - * - placeholders - * - normal TextBox object - * - text in auto-shapes - */ - @Test - public void read() throws IOException { - HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow("text_shapes.ppt"); - - List lst1 = new ArrayList(); - HSLFSlide slide = ppt.getSlides().get(0); - for (HSLFShape shape : slide.getShapes()) { - assertTrue("Expected TextShape but found " + shape.getClass().getName(), shape instanceof HSLFTextShape); - HSLFTextShape tx = (HSLFTextShape)shape; - List paras = tx.getTextParagraphs(); - assertNotNull(paras); - int runType = paras.get(0).getRunType(); - - ShapeType type = shape.getShapeType(); - String rawText = HSLFTextParagraph.getRawText(paras); - switch (type){ - case TEXT_BOX: - assertEquals("Text in a TextBox", rawText); - break; - case RECT: - if(runType == TextHeaderAtom.OTHER_TYPE) { - assertEquals("Rectangle", rawText); - } else if(runType == TextHeaderAtom.TITLE_TYPE) { - assertEquals("Title Placeholder", rawText); - } - break; - case OCTAGON: - assertEquals("Octagon", rawText); - break; - case ELLIPSE: - assertEquals("Ellipse", rawText); - break; - case ROUND_RECT: - assertEquals("RoundRectangle", rawText); - break; - default: - fail("Unexpected shape: " + shape.getShapeName()); - - } - lst1.add(rawText); - } - - List lst2 = new ArrayList(); - for (List paras : slide.getTextParagraphs()) { - lst2.add(HSLFTextParagraph.getRawText(paras)); - } - - assertTrue(lst1.containsAll(lst2)); - ppt.close(); - } - - @Test - public void readWrite() throws IOException { - HSLFSlideShow ppt = new HSLFSlideShow(); - HSLFSlide slide = ppt.createSlide(); - - HSLFTextShape shape1 = new HSLFTextBox(); - shape1.setText("Hello, World!"); - slide.addShape(shape1); - - shape1.moveTo(100, 100); - - HSLFTextShape shape2 = new HSLFAutoShape(ShapeType.RIGHT_ARROW); - shape2.setText("Testing TextShape"); - slide.addShape(shape2); - shape2.moveTo(300, 300); - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ppt.write(out); - out.close(); - - ppt = new HSLFSlideShow(new ByteArrayInputStream(out.toByteArray())); - slide = ppt.getSlides().get(0); - List shape = slide.getShapes(); - - assertTrue(shape.get(0) instanceof HSLFTextShape); - shape1 = (HSLFTextShape)shape.get(0); - assertEquals(ShapeType.TEXT_BOX, shape1.getShapeType()); - assertEquals("Hello, World!", shape1.getText()); - - assertTrue(shape.get(1) instanceof HSLFTextShape); - shape1 = (HSLFTextShape)shape.get(1); - assertEquals(ShapeType.RIGHT_ARROW, shape1.getShapeType()); - assertEquals("Testing TextShape", shape1.getText()); - ppt.close(); - } - - @Test - public void margins() throws IOException { - HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow("text-margins.ppt"); - - HSLFSlide slide = ppt.getSlides().get(0); - - Map map = new HashMap(); - for (HSLFShape shape : slide.getShapes()) { - if(shape instanceof HSLFTextShape){ - HSLFTextShape tx = (HSLFTextShape)shape; - map.put(tx.getText(), tx); - } - } - - HSLFTextShape tx; - - tx = map.get("TEST1"); - assertEquals(7.2, tx.getLeftInset(), 0); - assertEquals(7.2, tx.getRightInset(), 0); - assertEquals(28.34, tx.getTopInset(), 0.01); - assertEquals(3.6, tx.getBottomInset(), 0); - - tx = map.get("TEST2"); - assertEquals(7.2, tx.getLeftInset(), 0); - assertEquals(7.2, tx.getRightInset(), 0); - assertEquals(3.6, tx.getTopInset(), 0); - assertEquals(28.34, tx.getBottomInset(), 0.01); - - tx = map.get("TEST3"); - assertEquals(28.34, tx.getLeftInset(), 0.01); - assertEquals(7.2, tx.getRightInset(), 0); - assertEquals(3.6, tx.getTopInset(), 0); - assertEquals(3.6, tx.getBottomInset(), 0); - - tx = map.get("TEST4"); - assertEquals(7.2, tx.getLeftInset(), 0); - assertEquals(28.34, tx.getRightInset(), 0.01); - assertEquals(3.6, tx.getTopInset(), 0); - assertEquals(3.6, tx.getBottomInset(), 0); - - ppt.close(); - } - - @Test - public void bug52599() throws IOException { - HSLFSlideShow ppt = HSLFTestDataSamples.getSlideShow("52599.ppt"); - - HSLFSlide slide = ppt.getSlides().get(0); - List sh = slide.getShapes(); - assertEquals(3, sh.size()); - - HSLFTextShape sh0 = (HSLFTextShape)sh.get(0); - assertNotNull(sh0.getTextParagraphs()); - assertEquals("", sh0.getText()); - - HSLFTextShape sh1 = (HSLFTextShape)sh.get(1); - assertNotNull(sh1.getTextParagraphs()); - assertEquals("", sh1.getText()); - - HSLFTextShape sh2 = (HSLFTextShape)sh.get(2); - assertEquals("this box should be shown just once", sh2.getText()); - assertEquals(-1, sh2.getTextParagraphs().get(0).getIndex()); - ppt.close(); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hslf/util/TestSystemTimeUtils.java b/src/scratchpad/testcases/org/apache/poi/hslf/util/TestSystemTimeUtils.java deleted file mode 100644 index 776da2fc5..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hslf/util/TestSystemTimeUtils.java +++ /dev/null @@ -1,104 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hslf.util; - - -import static org.junit.Assert.assertEquals; - -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Locale; - -import org.apache.poi.util.LocaleUtil; -import org.junit.BeforeClass; -import org.junit.Test; - -/** - * Tests that SystemTimeUtils works properly. - * - * @author Nick Burch (nick at torchbox dot com) - */ -public final class TestSystemTimeUtils { - // From real files - private final byte[] data_a = new byte[] { - 0xD6-256, 07, 01, 00, - 02, 00, 0x18, 00, 0x0A, 00, 0x1A, 00, - 0x0F, 00, 0xCD-256, 00 - }; - private final byte[] data_b = new byte[] { - 00, 00, 0xE1-256, 0x2E, 0x1C, 00, 00, 00, - 01, 00, 00, 00, 0xD6-256, 0x07, 01, 00, - 02, 00, 0x18, 00, 0x15, 00, 0x19, 00, 03, - 00, 0xD5-256, 02, 0x0A, 00, 00, 00, - 0x0A, 00, 00, 00 - }; - - private static SimpleDateFormat sdf; - - @BeforeClass - public static void initDateFormat() { - sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.ROOT); - sdf.setTimeZone(LocaleUtil.getUserTimeZone()); - } - - @Test - public void testGetDateA() throws Exception { - Date date = SystemTimeUtils.getDate(data_a); - - // Is 2006-01-24 (2nd day of week) 10:26:15.205 - Date exp = sdf.parse("2006-01-24 10:26:15.205"); - assertEquals(exp.getTime(), date.getTime()); - assertEquals(exp, date); - } - - @Test - public void testGetDateB() throws Exception { - Date date = SystemTimeUtils.getDate(data_b, 8+4); - - // Is 2006-01-24 (2nd day of week) 21:25:03.725 - Date exp = sdf.parse("2006-01-24 21:25:03.725"); - assertEquals(exp.getTime(), date.getTime()); - assertEquals(exp, date); - } - - @Test - public void testWriteDateA() throws Exception { - byte[] out_a = new byte[data_a.length]; - Date date = sdf.parse("2006-01-24 10:26:15.205"); - SystemTimeUtils.storeDate(date, out_a); - - for(int i=0; i\r\n\r\n"); - assertContains(outlook30.getHtmlBody(), "

    " + text + "

    "); - assertEquals(-654938715, outlook30.getHtmlBody().hashCode()); - - assertStartsWith(outlook30.getRtfBody(), "{\\rtf1\\adeflang1025\\ansi\\ansicpg1252\\uc1\\adeff3150"); - assertContains(outlook30.getRtfBody(), "{\\rtlch\\fcs1 \\af31507 \\ltrch\\fcs0 \\cf0\\insrsid5003910 " + text + "\r\n\\par \r\n\\par"); - assertEquals(891652290, outlook30.getRtfBody().hashCode()); - } - - /** - * Test attachments - */ - public void testAttachments() throws Exception { - assertEquals(0, simple.getAttachmentFiles().length); - assertEquals(0, quick.getAttachmentFiles().length); - assertEquals(0, outlook30.getAttachmentFiles().length); - assertEquals(2, attachments.getAttachmentFiles().length); - } - - /** - * Test missing chunks. - * Use a file with no HTML body - */ - public void testMissingChunks() throws Exception { - assertFalse(attachments.isReturnNullOnMissingChunk()); - - try { - attachments.getHtmlBody(); - fail(); - } catch(ChunkNotFoundException e) { - // Good - } - - attachments.setReturnNullOnMissingChunk(true); - - assertNull(attachments.getHtmlBody()); - - attachments.setReturnNullOnMissingChunk(false); - - try { - attachments.getHtmlBody(); - fail(); - } catch(ChunkNotFoundException e) { - // Good - } - } - - /** - * More missing chunk testing, this time for - * missing recipient email address - */ - public void testMissingAddressChunk() throws Exception { - assertFalse(noRecipientAddress.isReturnNullOnMissingChunk()); - - try { - noRecipientAddress.getRecipientEmailAddress(); - fail(); - } catch(ChunkNotFoundException e) { - // Good - } - try { - noRecipientAddress.getRecipientEmailAddressList(); - fail(); - } catch(ChunkNotFoundException e) { - // Good - } - - noRecipientAddress.setReturnNullOnMissingChunk(true); - - noRecipientAddress.getRecipientEmailAddress(); - noRecipientAddress.getRecipientEmailAddressList(); - assertEquals("", noRecipientAddress.getRecipientEmailAddress()); - assertEquals(1, noRecipientAddress.getRecipientEmailAddressList().length); - assertNull(noRecipientAddress.getRecipientEmailAddressList()[0]); - - // Check a few other bits too - assertEquals("Microsoft Outlook 2003 Team", noRecipientAddress.getDisplayFrom()); - assertEquals("New Outlook User", noRecipientAddress.getDisplayTo()); - - noRecipientAddress.setReturnNullOnMissingChunk(false); - } - - /** - * Test the 7 bit detection - */ - public void test7BitDetection() throws Exception { - assertFalse(unicode.has7BitEncodingStrings()); - assertTrue(simple.has7BitEncodingStrings()); - assertTrue(chinese.has7BitEncodingStrings()); - assertTrue(cyrillic.has7BitEncodingStrings()); - } - - /** - * We default to CP1252, but can sometimes do better - * if needed. - * This file is really CP1251, according to the person - * who submitted it in bug #49441 - */ - public void testEncoding() throws Exception { - assertEquals(2, cyrillic.getRecipientDetailsChunks().length); - assertEquals("CP1252", cyrillic.getRecipientDetailsChunks()[0].recipientDisplayNameChunk.get7BitEncoding()); - assertEquals("CP1252", cyrillic.getRecipientDetailsChunks()[1].recipientDisplayNameChunk.get7BitEncoding()); - - cyrillic.guess7BitEncoding(); - - assertEquals("Cp1251", cyrillic.getRecipientDetailsChunks()[0].recipientDisplayNameChunk.get7BitEncoding()); - assertEquals("Cp1251", cyrillic.getRecipientDetailsChunks()[1].recipientDisplayNameChunk.get7BitEncoding()); - - // Override it, check it's taken - cyrillic.set7BitEncoding("UTF-8"); - assertEquals("UTF-8", cyrillic.getRecipientDetailsChunks()[0].recipientDisplayNameChunk.get7BitEncoding()); - assertEquals("UTF-8", cyrillic.getRecipientDetailsChunks()[1].recipientDisplayNameChunk.get7BitEncoding()); - - - // Check with a file that has no headers - try { - chinese.getHeaders(); - fail("File doesn't have headers!"); - } catch(ChunkNotFoundException e) {} - - String html = chinese.getHtmlBody(); - assertTrue("Charset not found:\n" + html, html.contains("text/html; charset=big5")); - - // Defaults to CP1251 - assertEquals("CP1252", chinese.getRecipientDetailsChunks()[0].recipientDisplayNameChunk.get7BitEncoding()); - - // But after guessing goes to the correct one, cp950 (Windows Traditional Chinese) - chinese.guess7BitEncoding(); - assertEquals("cp950", chinese.getRecipientDetailsChunks()[0].recipientDisplayNameChunk.get7BitEncoding()); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hsmf/TestBlankFileRead.java b/src/scratchpad/testcases/org/apache/poi/hsmf/TestBlankFileRead.java deleted file mode 100644 index c4f13a627..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hsmf/TestBlankFileRead.java +++ /dev/null @@ -1,121 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hsmf; - -import java.io.IOException; - -import org.apache.poi.hsmf.MAPIMessage; -import org.apache.poi.hsmf.exceptions.ChunkNotFoundException; -import org.apache.poi.POIDataSamples; - -import junit.framework.TestCase; - - -/** - * Tests to verify that the library can read blank msg files. - */ -public final class TestBlankFileRead extends TestCase { - private final MAPIMessage mapiMessage; - - /** - * Initialize this test, load up the blank.msg mapi message. - */ - public TestBlankFileRead() throws IOException { - POIDataSamples samples = POIDataSamples.getHSMFInstance(); - this.mapiMessage = new MAPIMessage(samples.openResourceAsStream("blank.msg")); - } - - /** - * Check if we can read the body of the blank message, we expect "". - */ - public void testReadBody() { - try { - mapiMessage.getTextBody(); - } catch(ChunkNotFoundException exp) { - return; - } - - TestCase.fail("Should have thrown a ChunkNotFoundException but didn't"); - } - - - /** - * Test to see if we can read the CC Chunk. - */ - public void testReadDisplayCC() throws ChunkNotFoundException { - String obtained = mapiMessage.getDisplayCC(); - String expected = ""; - - TestCase.assertEquals(expected, obtained); - } - - /** - * Test to see if we can read the CC Chunk. - */ - public void testReadDisplayTo() throws ChunkNotFoundException { - String obtained = mapiMessage.getDisplayTo(); - String expected = ""; - - TestCase.assertEquals(expected, obtained); - } - - /** - * Test to see if we can read the FROM Chunk. - */ - public void testReadDisplayFrom() { - try { - mapiMessage.getDisplayFrom(); - } catch(ChunkNotFoundException exp) { - return; - } - - TestCase.fail("Should have thrown a ChunkNotFoundException but didn't"); - } - - /** - * Test to see if we can read the CC Chunk. - */ - public void testReadDisplayBCC() throws ChunkNotFoundException { - String obtained = mapiMessage.getDisplayBCC(); - String expected = ""; - - TestCase.assertEquals(expected, obtained); - } - - - /** - * Check if we can read the subject line of the blank message, we expect "" - */ - public void testReadSubject() throws Exception { - String obtained = mapiMessage.getSubject(); - TestCase.assertEquals("", obtained); - } - - - /** - * Check if we can read the subject line of the blank message, we expect "" - */ - public void testReadConversationTopic() { - try { - mapiMessage.getConversationTopic(); - } catch(ChunkNotFoundException exp) { - return; - } - TestCase.fail("We shouldn't have a ConversationTopic node on the blank.msg file."); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hsmf/TestFileWithAttachmentsRead.java b/src/scratchpad/testcases/org/apache/poi/hsmf/TestFileWithAttachmentsRead.java deleted file mode 100644 index 004fadd39..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hsmf/TestFileWithAttachmentsRead.java +++ /dev/null @@ -1,181 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hsmf; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; - -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hsmf.datatypes.AttachmentChunks; -import org.apache.poi.hsmf.exceptions.ChunkNotFoundException; - -/** - * Tests to verify that we can read attachments from msg file - */ -public class TestFileWithAttachmentsRead { - private static MAPIMessage twoSimpleAttachments; - private static MAPIMessage pdfMsgAttachments; - private static MAPIMessage inlineImgMsgAttachments; - - /** - * Initialize this test, load up the attachment_test_msg.msg mapi message. - * - * @throws Exception - */ - @BeforeClass - public static void setUp() throws IOException { - POIDataSamples samples = POIDataSamples.getHSMFInstance(); - twoSimpleAttachments = new MAPIMessage(samples.openResourceAsStream("attachment_test_msg.msg")); - pdfMsgAttachments = new MAPIMessage(samples.openResourceAsStream("attachment_msg_pdf.msg")); - inlineImgMsgAttachments = new MAPIMessage(samples.openResourceAsStream("attachment_msg_inlineImg.msg")); - } - - @AfterClass - public static void tearDown() throws IOException { - twoSimpleAttachments.close(); - pdfMsgAttachments.close(); - inlineImgMsgAttachments.close(); - } - - /** - * Test to see if we can retrieve attachments. - * - * @throws ChunkNotFoundException - * - */ - @Test - public void testRetrieveAttachments() { - // Simple file - AttachmentChunks[] attachments = twoSimpleAttachments.getAttachmentFiles(); - assertEquals(2, attachments.length); - - // Other file - attachments = pdfMsgAttachments.getAttachmentFiles(); - assertEquals(2, attachments.length); - } - - /** - * Bug 60550: Test to see if we get the correct Content-IDs of inline images`. - */ - @Test - public void testReadContentIDField() throws IOException { - AttachmentChunks[] attachments = inlineImgMsgAttachments.getAttachmentFiles(); - - AttachmentChunks attachment; - - // Check in Content-ID field - attachment = inlineImgMsgAttachments.getAttachmentFiles()[0]; - assertEquals("image001.png", attachment.getAttachFileName().getValue()); - assertEquals(".png", attachment.getAttachExtension().getValue()); - assertEquals("image001.png@01D0A524.96D40F30", attachment.getAttachContentId().getValue()); - - attachment = inlineImgMsgAttachments.getAttachmentFiles()[1]; - assertEquals("image002.png", attachment.getAttachFileName().getValue()); - assertEquals(".png", attachment.getAttachExtension().getValue()); - assertEquals("image002.png@01D0A524.96D40F30", attachment.getAttachContentId().getValue()); - - attachment = inlineImgMsgAttachments.getAttachmentFiles()[2]; - assertEquals("image003.png", attachment.getAttachFileName().getValue()); - assertEquals(".png", attachment.getAttachExtension().getValue()); - assertEquals("image003.png@01D0A526.B4C739C0", attachment.getAttachContentId().getValue()); - - attachment = inlineImgMsgAttachments.getAttachmentFiles()[3]; - assertEquals("image006.jpg", attachment.getAttachFileName().getValue()); - assertEquals(".jpg", attachment.getAttachExtension().getValue()); - assertEquals("image006.jpg@01D0A526.B649E220", attachment.getAttachContentId().getValue()); - } - - - /** - * Test to see if attachments are not empty. - */ - @Test - public void testReadAttachments() throws IOException { - AttachmentChunks[] attachments = twoSimpleAttachments.getAttachmentFiles(); - - // Basic checks - for (AttachmentChunks attachment : attachments) { - assertTrue(attachment.getAttachFileName().getValue().length() > 0); - assertTrue(attachment.getAttachLongFileName().getValue().length() > 0); - assertTrue(attachment.getAttachExtension().getValue().length() > 0); - if (attachment.getAttachMimeTag() != null) { - assertTrue(attachment.getAttachMimeTag().getValue().length() > 0); - } - } - - AttachmentChunks attachment; - - // Now check in detail - attachment = twoSimpleAttachments.getAttachmentFiles()[0]; - assertEquals("TEST-U~1.DOC", attachment.getAttachFileName().getValue()); - assertEquals("test-unicode.doc", attachment.getAttachLongFileName().getValue()); - assertEquals(".doc", attachment.getAttachExtension().getValue()); - assertNull(attachment.getAttachMimeTag()); - assertEquals(24064, attachment.getAttachData().getValue().length); // or compare the hashes of the attachment data - - attachment = twoSimpleAttachments.getAttachmentFiles()[1]; - assertEquals("pj1.txt", attachment.getAttachFileName().getValue()); - assertEquals("pj1.txt", attachment.getAttachLongFileName().getValue()); - assertEquals(".txt", attachment.getAttachExtension().getValue()); - assertNull(attachment.getAttachMimeTag()); - assertEquals(89, attachment.getAttachData().getValue().length); // or compare the hashes of the attachment data - } - - /** - * Test that we can handle both PDF and MSG attachments - */ - @Test - public void testReadMsgAttachments() throws Exception { - AttachmentChunks[] attachments = pdfMsgAttachments.getAttachmentFiles(); - assertEquals(2, attachments.length); - - AttachmentChunks attachment; - - // Second is a PDF - attachment = pdfMsgAttachments.getAttachmentFiles()[1]; - assertEquals("smbprn~1.pdf", attachment.getAttachFileName().getValue()); - assertEquals("smbprn.00009008.KdcPjl.pdf", attachment.getAttachLongFileName().getValue()); - assertEquals(".pdf", attachment.getAttachExtension().getValue()); - assertNull(attachment.getAttachMimeTag()); - assertNull(attachment.getAttachmentDirectory()); - assertEquals(13539, attachment.getAttachData().getValue().length); //or compare the hashes of the attachment data - - // First in a nested message - attachment = pdfMsgAttachments.getAttachmentFiles()[0]; - assertEquals("Test Attachment", attachment.getAttachFileName().getValue()); - assertNull(attachment.getAttachLongFileName()); - assertNull(attachment.getAttachExtension()); - assertNull(attachment.getAttachMimeTag()); - assertNull(attachment.getAttachData()); - assertNotNull(attachment.getAttachmentDirectory()); - - // Check we can see some bits of it - MAPIMessage nested = attachment.getAttachmentDirectory().getAsEmbededMessage(); - assertEquals(1, nested.getRecipientNamesList().length); - assertEquals("Nick Booth", nested.getRecipientNames()); - assertEquals("Test Attachment", nested.getConversationTopic()); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hsmf/TestFixedSizedProperties.java b/src/scratchpad/testcases/org/apache/poi/hsmf/TestFixedSizedProperties.java deleted file mode 100644 index ecedca384..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hsmf/TestFixedSizedProperties.java +++ /dev/null @@ -1,211 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hsmf; - -import static org.apache.poi.POITestCase.assertContains; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.PrintStream; -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.TimeZone; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hsmf.datatypes.ChunkBasedPropertyValue; -import org.apache.poi.hsmf.datatypes.Chunks; -import org.apache.poi.hsmf.datatypes.MAPIProperty; -import org.apache.poi.hsmf.datatypes.PropertyValue; -import org.apache.poi.hsmf.datatypes.PropertyValue.LongPropertyValue; -import org.apache.poi.hsmf.datatypes.PropertyValue.TimePropertyValue; -import org.apache.poi.hsmf.dev.HSMFDump; -import org.apache.poi.hsmf.extractor.OutlookTextExtactor; -import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; -import org.apache.poi.util.LocaleUtil; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; - -/** - * Tests that we can read fixed sized properties, as well as variable - * ones, for example Submission Dates - */ -public final class TestFixedSizedProperties { - private static final String messageSucceeds = "53784_succeeds.msg"; - private static final String messageFails = "53784_fails.msg"; - private static MAPIMessage mapiMessageSucceeds; - private static MAPIMessage mapiMessageFails; - private static NPOIFSFileSystem fsMessageSucceeds; - private static NPOIFSFileSystem fsMessageFails; - private static SimpleDateFormat messageDateFormat; - private static TimeZone userTimeZone; - - /** - * Initialize this test, load up the messages. - */ - @BeforeClass - public static void initMapi() throws Exception { - POIDataSamples samples = POIDataSamples.getHSMFInstance(); - fsMessageSucceeds = new NPOIFSFileSystem(samples.getFile(messageSucceeds)); - fsMessageFails = new NPOIFSFileSystem(samples.getFile(messageFails)); - - mapiMessageSucceeds = new MAPIMessage(fsMessageSucceeds); - mapiMessageFails = new MAPIMessage(fsMessageFails); - - messageDateFormat = new SimpleDateFormat("E, d MMM yyyy HH:mm:ss", Locale.ROOT); - messageDateFormat.setTimeZone(LocaleUtil.TIMEZONE_UTC); - - userTimeZone = LocaleUtil.getUserTimeZone(); - LocaleUtil.setUserTimeZone(LocaleUtil.TIMEZONE_UTC); - } - - - @AfterClass - public static void closeFS() throws Exception { - LocaleUtil.setUserTimeZone(userTimeZone); - fsMessageSucceeds.close(); - fsMessageFails.close(); - } - - /** - * Check we can find a sensible number of properties on a few - * of our test files - */ - @Test - public void testPropertiesFound() throws Exception { - Map> props; - - props = mapiMessageSucceeds.getMainChunks().getProperties(); - assertTrue(props.toString(), props.size() > 10); - - props = mapiMessageFails.getMainChunks().getProperties(); - assertTrue(props.toString(), props.size() > 10); - } - - /** - * Check we find properties of a variety of different types - */ - @Test - public void testPropertyValueTypes() throws Exception { - Chunks mainChunks = mapiMessageSucceeds.getMainChunks(); - - // Ask to have the values looked up - Map> props = mainChunks.getProperties(); - HashSet> seenTypes = - new HashSet>(); - for (List pvs : props.values()) { - for (PropertyValue pv : pvs) { - seenTypes.add(pv.getClass()); - } - } - assertTrue(seenTypes.toString(), seenTypes.size() > 3); - assertTrue(seenTypes.toString(), seenTypes.contains(LongPropertyValue.class)); - assertTrue(seenTypes.toString(), seenTypes.contains(TimePropertyValue.class)); - assertFalse(seenTypes.toString(), seenTypes.contains(ChunkBasedPropertyValue.class)); - - // Ask for the raw values - seenTypes.clear(); - for (PropertyValue pv : mainChunks.getRawProperties().values()) { - seenTypes.add(pv.getClass()); - } - assertTrue(seenTypes.toString(), seenTypes.size() > 3); - assertTrue(seenTypes.toString(), seenTypes.contains(LongPropertyValue.class)); - assertTrue(seenTypes.toString(), seenTypes.contains(TimePropertyValue.class)); - assertTrue(seenTypes.toString(), seenTypes.contains(ChunkBasedPropertyValue.class)); - } - - /** - * Test to see if we can read the Date Chunk with OutlookTextExtractor. - */ - @Test - // @Ignore("TODO Work out why the Fri 22nd vs Monday 25th problem is occurring and fix") - public void testReadMessageDateSucceedsWithOutlookTextExtractor() throws Exception { - OutlookTextExtactor ext = new OutlookTextExtactor(mapiMessageSucceeds); - ext.setFilesystem(null); // Don't close re-used test resources here - - String text = ext.getText(); - assertContains(text, "Date: Fri, 22 Jun 2012 18:32:54 +0000\n"); - ext.close(); - } - - /** - * Test to see if we can read the Date Chunk with OutlookTextExtractor. - */ - @Test - // @Ignore("TODO Work out why the Thu 21st vs Monday 25th problem is occurring and fix") - public void testReadMessageDateFailsWithOutlookTextExtractor() throws Exception { - OutlookTextExtactor ext = new OutlookTextExtactor(mapiMessageFails); - ext.setFilesystem(null); // Don't close re-used test resources here - - String text = ext.getText(); - assertContains(text, "Date: Thu, 21 Jun 2012 14:14:04 +0000\n"); - ext.close(); - } - - /** - * Test to see if we can read the Date Chunk with HSMFDump. - */ - @Test - public void testReadMessageDateSucceedsWithHSMFDump() throws IOException { - PrintStream stream = new PrintStream(new ByteArrayOutputStream()); - HSMFDump dump = new HSMFDump(fsMessageSucceeds); - dump.dump(stream); - } - - /** - * Test to see if we can read the Date Chunk with HSMFDump. - */ - @Test - public void testReadMessageDateFailsWithHSMFDump() throws Exception { - PrintStream stream = new PrintStream(new ByteArrayOutputStream()); - HSMFDump dump = new HSMFDump(fsMessageFails); - dump.dump(stream); - } - - /** - * Will be based on the ClientSubmit time - */ - @Test - public void testClientSubmitTime() throws Exception { - // Check via the message date - Calendar clientSubmitTime = mapiMessageSucceeds.getMessageDate(); - assertEquals( - "Fri, 22 Jun 2012 18:32:54", - messageDateFormat.format(clientSubmitTime.getTime())); - - // Fetch the property value directly - Map> props = - mapiMessageSucceeds.getMainChunks().getProperties(); - List pv = props.get(MAPIProperty.CLIENT_SUBMIT_TIME); - assertNotNull(pv); - assertEquals(1, pv.size()); - - clientSubmitTime = (Calendar)pv.get(0).getValue(); - assertEquals( - "Fri, 22 Jun 2012 18:32:54", - messageDateFormat.format(clientSubmitTime.getTime())); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hsmf/TestMessageSubmissionChunk.java b/src/scratchpad/testcases/org/apache/poi/hsmf/TestMessageSubmissionChunk.java deleted file mode 100644 index d3ed7d49c..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hsmf/TestMessageSubmissionChunk.java +++ /dev/null @@ -1,58 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hsmf; - -import java.io.IOException; - -import org.apache.poi.hsmf.MAPIMessage; -import org.apache.poi.hsmf.exceptions.ChunkNotFoundException; -import org.apache.poi.POIDataSamples; - -import java.util.Calendar; - -import junit.framework.TestCase; - -public final class TestMessageSubmissionChunk extends TestCase { - - private final MAPIMessage mapiMessageExtraHyphenSubmissionChunk; - private final MAPIMessage mapiMessageNormalSubmissionChunk; - - /** - * Initialise this test, load up the test messages. - * @throws Exception - */ - public TestMessageSubmissionChunk() throws IOException { - POIDataSamples samples = POIDataSamples.getHSMFInstance(); - this.mapiMessageExtraHyphenSubmissionChunk = new MAPIMessage(samples.openResourceAsStream("message_extra_hyphen_submission_chunk.msg")); - this.mapiMessageNormalSubmissionChunk = new MAPIMessage(samples.openResourceAsStream("message_normal_submission_chunk.msg")); - } - - public void testReadMessageDateExtraHyphenSubmissionChunk() throws ChunkNotFoundException { - final Calendar date = mapiMessageExtraHyphenSubmissionChunk.getMessageDate(); - TestCase.assertNotNull(date); - final int year = date.get(Calendar.YEAR); - TestCase.assertEquals(2007, year); - } - - public void testReadMessageDateNormalSubmissionChunk() throws ChunkNotFoundException { - final Calendar date = mapiMessageNormalSubmissionChunk.getMessageDate(); - TestCase.assertNotNull(date); - final int year = date.get(Calendar.YEAR); - TestCase.assertEquals(2007, year); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hsmf/TestMessageSubmissionChunkY2KRead.java b/src/scratchpad/testcases/org/apache/poi/hsmf/TestMessageSubmissionChunkY2KRead.java deleted file mode 100644 index dd1d8f929..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hsmf/TestMessageSubmissionChunkY2KRead.java +++ /dev/null @@ -1,67 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hsmf; - -import java.io.IOException; - -import org.apache.poi.hsmf.MAPIMessage; -import org.apache.poi.hsmf.exceptions.ChunkNotFoundException; -import org.apache.poi.POIDataSamples; - -import java.util.Calendar; - -import junit.framework.TestCase; - -public final class TestMessageSubmissionChunkY2KRead extends TestCase { - - private final MAPIMessage mapiMessage1979; - private final MAPIMessage mapiMessage1980; - private final MAPIMessage mapiMessage1981; - - /** - * Initialise this test, load up the three test messages. - * @throws Exception - */ - public TestMessageSubmissionChunkY2KRead() throws IOException { - POIDataSamples samples = POIDataSamples.getHSMFInstance(); - this.mapiMessage1979 = new MAPIMessage(samples.openResourceAsStream("message_1979.msg")); - this.mapiMessage1980 = new MAPIMessage(samples.openResourceAsStream("message_1980.msg")); - this.mapiMessage1981 = new MAPIMessage(samples.openResourceAsStream("message_1981.msg")); - } - - // 1979 is one year before our pivot year (so this is an expected "failure") - public void testReadMessageDate1979() throws ChunkNotFoundException { - final Calendar date = mapiMessage1979.getMessageDate(); - final int year = date.get(Calendar.YEAR); - TestCase.assertEquals(2079, year); - } - - // 1980 is our pivot year (so this is an expected "failure") - public void testReadMessageDate1980() throws ChunkNotFoundException { - final Calendar date = mapiMessage1980.getMessageDate(); - final int year = date.get(Calendar.YEAR); - TestCase.assertEquals(2080, year); - } - - // 1981 is one year after our pivot year (so this starts working) - public void testReadMessageDate1981() throws ChunkNotFoundException { - final Calendar date = mapiMessage1981.getMessageDate(); - final int year = date.get(Calendar.YEAR); - TestCase.assertEquals(1981, year); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hsmf/TestOutlook30FileRead.java b/src/scratchpad/testcases/org/apache/poi/hsmf/TestOutlook30FileRead.java deleted file mode 100644 index 1496e082d..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hsmf/TestOutlook30FileRead.java +++ /dev/null @@ -1,145 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hsmf; - -import java.io.IOException; - -import org.apache.poi.hsmf.MAPIMessage; -import org.apache.poi.hsmf.exceptions.ChunkNotFoundException; -import org.apache.poi.POIDataSamples; - -import junit.framework.TestCase; - -/** - * Tests to verify that we can still work on the newer Outlook 3.0 files. - */ -public final class TestOutlook30FileRead extends TestCase { - private final MAPIMessage mapiMessage; - - /** - * Initialize this test, load up the blank.msg mapi message. - * @throws Exception - */ - public TestOutlook30FileRead() throws IOException { - POIDataSamples samples = POIDataSamples.getHSMFInstance(); - this.mapiMessage = new MAPIMessage(samples.openResourceAsStream("outlook_30_msg.msg")); - } - - /** - * Test to see if we can read the CC Chunk. - * @throws ChunkNotFoundException - * - */ - public void testReadDisplayCC() throws ChunkNotFoundException { - String obtained = mapiMessage.getDisplayCC(); - String expected = ""; - - TestCase.assertEquals(obtained, expected); - } - - /** - * Test to see if we can read the CC Chunk. - * @throws ChunkNotFoundException - * - */ - public void testReadDisplayTo() throws ChunkNotFoundException { - String obtained = mapiMessage.getDisplayTo(); - - assertTrue(obtained.startsWith("Bohn, Shawn")); - } - - /** - * Test to see if we can read the From Chunk. - * @throws ChunkNotFoundException - * - */ - public void testReadDisplayFrom() throws ChunkNotFoundException { - String obtained = mapiMessage.getDisplayFrom(); - String expected = "Cramer, Nick"; - - TestCase.assertEquals(obtained, expected); - } - - /** - * Test to see if we can read the CC Chunk. - * @throws ChunkNotFoundException - * - */ - public void testReadDisplayBCC() throws ChunkNotFoundException { - String obtained = mapiMessage.getDisplayBCC(); - String expected = ""; - - TestCase.assertEquals(obtained, expected); - } - - - /** - * Check if we can read the body of the blank message, we expect "". - * - * @throws Exception - */ - public void testReadBody() throws Exception { - String obtained = mapiMessage.getTextBody(); - assertTrue(obtained.startsWith("I am shutting down")); - } - - /** - * Check if we can read the subject line of the blank message, we expect "" - * - * @throws Exception - */ - public void testReadSubject() throws Exception { - String obtained = mapiMessage.getSubject(); - String expected = "IN-SPIRE servers going down for a bit, back up around 8am"; - - TestCase.assertEquals(expected, obtained); - } - - /** - * Check if we can read the subject line of the blank message, we expect "" - * - * @throws Exception - */ - public void testReadConversationTopic() throws Exception { - String obtained = mapiMessage.getConversationTopic(); - TestCase.assertEquals("IN-SPIRE servers going down for a bit, back up around 8am", obtained); - } - - /** - * Check if we can read the subject line of the blank message, we expect "" - * - * @throws Exception - */ - public void testReadMessageClass() throws Exception { - String obtained = mapiMessage.getMessageClass(); - TestCase.assertEquals("IPM.Note", obtained); - } - - /** - * Ensure we can get the HTML and RTF versions - */ - public void testReadBodyContents() throws Exception { - String html = mapiMessage.getHtmlBody(); - String rtf = mapiMessage.getRtfBody(); - assertNotNull(html); - assertNotNull(rtf); - - assertTrue("Wrong text:\n" + html, html.startsWith(" all = MAPIProperty.getAll(); - assertEquals(true, all.contains(MAPIProperty.DISPLAY_NAME)); - assertEquals(true, all.contains(MAPIProperty.DISPLAY_CC)); - - // Won't contain custom - assertEquals(false, all.contains(MAPIProperty.createCustom(1, Types.UNSPECIFIED, ""))); - - // Won't contain unknown - assertEquals(false, all.contains(MAPIProperty.UNKNOWN)); - } - - public void testCustom() throws Exception { - MAPIProperty c1 = MAPIProperty.createCustom(1, Types.UNSPECIFIED, ""); - MAPIProperty c2a = MAPIProperty.createCustom(2, Types.UNSPECIFIED, "2"); - MAPIProperty c2b = MAPIProperty.createCustom(2, Types.UNSPECIFIED, "2"); - - // New object each time - assertNotSame(c1, c2a); - assertNotSame(c1, c2b); - assertNotSame(c2a, c2b); - - // Won't be in all list - Collection all = MAPIProperty.getAll(); - assertEquals(false, all.contains(c1)); - assertEquals(false, all.contains(c2a)); - assertEquals(false, all.contains(c2b)); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hsmf/datatypes/TestSorters.java b/src/scratchpad/testcases/org/apache/poi/hsmf/datatypes/TestSorters.java deleted file mode 100644 index 815fb2d66..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hsmf/datatypes/TestSorters.java +++ /dev/null @@ -1,97 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hsmf.datatypes; - -import java.util.Arrays; - -import org.apache.poi.hsmf.datatypes.AttachmentChunks.AttachmentChunksSorter; -import org.apache.poi.hsmf.datatypes.RecipientChunks.RecipientChunksSorter; - -import junit.framework.TestCase; - -/** - * Checks that the sorters on the chunk groups order - * chunks properly. - */ -public final class TestSorters extends TestCase { - public void testAttachmentChunksSorter() { - AttachmentChunks[] chunks; - - // Simple - chunks = new AttachmentChunks[] { - new AttachmentChunks("__attach_version1.0_#00000001"), - new AttachmentChunks("__attach_version1.0_#00000000"), - }; - Arrays.sort(chunks, new AttachmentChunksSorter()); - assertEquals("__attach_version1.0_#00000000", chunks[0].getPOIFSName()); - assertEquals("__attach_version1.0_#00000001", chunks[1].getPOIFSName()); - - // Lots, with gaps - chunks = new AttachmentChunks[] { - new AttachmentChunks("__attach_version1.0_#00000101"), - new AttachmentChunks("__attach_version1.0_#00000001"), - new AttachmentChunks("__attach_version1.0_#00000002"), - new AttachmentChunks("__attach_version1.0_#00000005"), - new AttachmentChunks("__attach_version1.0_#00000026"), - new AttachmentChunks("__attach_version1.0_#00000000"), - new AttachmentChunks("__attach_version1.0_#000000AB"), - }; - Arrays.sort(chunks, new AttachmentChunksSorter()); - assertEquals("__attach_version1.0_#00000000", chunks[0].getPOIFSName()); - assertEquals("__attach_version1.0_#00000001", chunks[1].getPOIFSName()); - assertEquals("__attach_version1.0_#00000002", chunks[2].getPOIFSName()); - assertEquals("__attach_version1.0_#00000005", chunks[3].getPOIFSName()); - assertEquals("__attach_version1.0_#00000026", chunks[4].getPOIFSName()); - assertEquals("__attach_version1.0_#000000AB", chunks[5].getPOIFSName()); - assertEquals("__attach_version1.0_#00000101", chunks[6].getPOIFSName()); - } - - public void testRecipientChunksSorter() { - RecipientChunks[] chunks; - - // Simple - chunks = new RecipientChunks[] { - new RecipientChunks("__recip_version1.0_#00000001"), - new RecipientChunks("__recip_version1.0_#00000000"), - }; - Arrays.sort(chunks, new RecipientChunksSorter()); - assertEquals(0, chunks[0].recipientNumber); - assertEquals(1, chunks[1].recipientNumber); - - // Lots, with gaps - chunks = new RecipientChunks[] { - new RecipientChunks("__recip_version1.0_#00020001"), - new RecipientChunks("__recip_version1.0_#000000FF"), - new RecipientChunks("__recip_version1.0_#00000205"), - new RecipientChunks("__recip_version1.0_#00000001"), - new RecipientChunks("__recip_version1.0_#00000005"), - new RecipientChunks("__recip_version1.0_#00000009"), - new RecipientChunks("__recip_version1.0_#00000404"), - new RecipientChunks("__recip_version1.0_#00000000"), - }; - Arrays.sort(chunks, new RecipientChunksSorter()); - assertEquals(0, chunks[0].recipientNumber); - assertEquals(1, chunks[1].recipientNumber); - assertEquals(5, chunks[2].recipientNumber); - assertEquals(9, chunks[3].recipientNumber); - assertEquals(0xFF, chunks[4].recipientNumber); - assertEquals(0x205, chunks[5].recipientNumber); - assertEquals(0x404, chunks[6].recipientNumber); - assertEquals(0x20001, chunks[7].recipientNumber); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hsmf/datatypes/TestTypes.java b/src/scratchpad/testcases/org/apache/poi/hsmf/datatypes/TestTypes.java deleted file mode 100644 index 8a58639d7..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hsmf/datatypes/TestTypes.java +++ /dev/null @@ -1,59 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hsmf.datatypes; - -import org.apache.poi.hsmf.datatypes.Types; - -import junit.framework.TestCase; - -/** - * Verifies that the Types class is behaving properly. - * Also check that no changes have been made that will - * break the library. - */ -public final class TestTypes extends TestCase { - public void testTypeIds() { - assertEquals(0x1e, Types.ASCII_STRING.getId()); - assertEquals(0x1f, Types.UNICODE_STRING.getId()); - - assertEquals(0x0102, Types.BINARY.getId()); - assertEquals(0x000B, Types.BOOLEAN.getId()); - assertEquals(0x0003, Types.LONG.getId()); - assertEquals(0x0040, Types.TIME.getId()); - - assertEquals(Types.ASCII_STRING, Types.getById(0x1e)); - assertEquals(Types.UNICODE_STRING, Types.getById(0x1f)); - - assertEquals(Types.BINARY, Types.getById(0x0102)); - assertEquals(Types.BOOLEAN, Types.getById(0x000B)); - assertEquals(Types.LONG, Types.getById(0x0003)); - assertEquals(Types.TIME, Types.getById(0x0040)); - } - - public void testTypeFormatting() { - assertEquals("0000", Types.asFileEnding(0x0000)); - assertEquals("0020", Types.asFileEnding(0x0020)); - assertEquals("0102", Types.asFileEnding(0x0102)); - assertEquals("FEDC", Types.asFileEnding(0xfedc)); - } - - public void testName() { - assertEquals("ASCII String", Types.ASCII_STRING.getName()); - assertEquals("Boolean", Types.BOOLEAN.getName()); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hsmf/extractor/TestOutlookTextExtractor.java b/src/scratchpad/testcases/org/apache/poi/hsmf/extractor/TestOutlookTextExtractor.java deleted file mode 100644 index 755bb6380..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hsmf/extractor/TestOutlookTextExtractor.java +++ /dev/null @@ -1,269 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hsmf.extractor; - -import static org.apache.poi.POITestCase.assertContains; -import static org.apache.poi.POITestCase.assertNotContained; -import static org.junit.Assert.assertEquals; - -import java.io.FileInputStream; -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.Locale; -import java.util.TimeZone; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hsmf.MAPIMessage; -import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; -import org.apache.poi.util.LocaleUtil; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; - -/** - * Tests to verify that the text extractor works - */ -public final class TestOutlookTextExtractor { - private final POIDataSamples samples = POIDataSamples.getHSMFInstance(); - - private static TimeZone userTZ; - - @BeforeClass - public static void initTimeZone() { - userTZ = LocaleUtil.getUserTimeZone(); - LocaleUtil.setUserTimeZone(LocaleUtil.TIMEZONE_UTC); - } - - @AfterClass - public static void resetTimeZone() { - LocaleUtil.setUserTimeZone(userTZ); - } - - @Test - public void testQuick() throws Exception { - NPOIFSFileSystem poifs = new NPOIFSFileSystem(samples.getFile("quick.msg"), true); - MAPIMessage msg = new MAPIMessage(poifs); - - OutlookTextExtactor ext = new OutlookTextExtactor(msg); - String text = ext.getText(); - - assertContains(text, "From: Kevin Roast\n"); - assertContains(text, "To: Kevin Roast \n"); - assertEquals(-1, text.indexOf("CC:")); - assertEquals(-1, text.indexOf("BCC:")); - assertEquals(-1, text.indexOf("Attachment:")); - assertContains(text, "Subject: Test the content transformer\n"); - Calendar cal = LocaleUtil.getLocaleCalendar(2007, 5, 14, 9, 42, 55); - SimpleDateFormat f = new SimpleDateFormat("E, d MMM yyyy HH:mm:ss Z", Locale.ROOT); - f.setTimeZone(LocaleUtil.getUserTimeZone()); - String dateText = f.format(cal.getTime()); - assertContains(text, "Date: " + dateText + "\n"); - assertContains(text, "The quick brown fox jumps over the lazy dog"); - - ext.close(); - poifs.close(); - } - - @Test - public void testSimple() throws Exception { - NPOIFSFileSystem poifs = new NPOIFSFileSystem(samples.getFile("simple_test_msg.msg"), true); - MAPIMessage msg = new MAPIMessage(poifs); - - OutlookTextExtactor ext = new OutlookTextExtactor(msg); - String text = ext.getText(); - - assertContains(text, "From: Travis Ferguson\n"); - assertContains(text, "To: travis@overwrittenstack.com\n"); - assertEquals(-1, text.indexOf("CC:")); - assertEquals(-1, text.indexOf("BCC:")); - assertContains(text, "Subject: test message\n"); - assertContains(text, "Date: Fri, 6 Jul 2007 05:27:17 +0000\n"); - assertContains(text, "This is a test message."); - - ext.close(); - poifs.close(); - } - - @Test - public void testConstructors() throws Exception { - FileInputStream fis = new FileInputStream(samples.getFile("simple_test_msg.msg")); - OutlookTextExtactor ext = new OutlookTextExtactor(fis); - String inp = ext.getText(); - ext.close(); - fis.close(); - - NPOIFSFileSystem poifs = new NPOIFSFileSystem(samples.getFile("simple_test_msg.msg"), true); - ext = new OutlookTextExtactor(poifs); - String poifsTxt = ext.getText(); - ext.close(); - poifs.close(); - - fis = new FileInputStream(samples.getFile("simple_test_msg.msg")); - ext = new OutlookTextExtactor(new MAPIMessage(fis)); - String mapi = ext.getText(); - ext.close(); - fis.close(); - - assertEquals(inp, poifsTxt); - assertEquals(inp, mapi); - } - - /** - * Test that we correctly handle multiple To+CC+BCC - * recipients in an email we sent. - */ - @Test - public void testSentWithMulipleRecipients() throws Exception { - // To: 'Ashutosh Dandavate' , - // 'Paul Holmes-Higgin' , - // 'Mike Farman' - // Cc: nickb@alfresco.com, nick.burch@alfresco.com, - // 'Roy Wetherall' - // Bcc: 'David Caruana' , - // 'Vonka Jan' - - String[] files = new String[] { - "example_sent_regular.msg", "example_sent_unicode.msg" - }; - for(String file : files) { - NPOIFSFileSystem poifs = new NPOIFSFileSystem(samples.getFile(file), true); - MAPIMessage msg = new MAPIMessage(poifs); - - OutlookTextExtactor ext = new OutlookTextExtactor(msg); - String text = ext.getText(); - - assertContains(text, "From: Mike Farman\n"); - assertContains(text, "To: 'Ashutosh Dandavate' ; " + - "'Paul Holmes-Higgin' ; 'Mike Farman' \n"); - assertContains(text, "CC: 'nickb@alfresco.com' ; " + - "'nick.burch@alfresco.com' ; 'Roy Wetherall' \n"); - assertContains(text, "BCC: 'David Caruana' ; " + - "'Vonka Jan' \n"); - assertContains(text, "Subject: This is a test message please ignore\n"); - assertContains(text, "Date:"); - assertContains(text, "The quick brown fox jumps over the lazy dog"); - - ext.close(); - poifs.close(); - } - } - - /** - * Test that we correctly handle multiple To+CC - * recipients in an email we received. - */ - @Test - public void testReceivedWithMultipleRecipients() throws Exception { - // To: 'Ashutosh Dandavate' , - // 'Paul Holmes-Higgin' , - // 'Mike Farman' - // Cc: nickb@alfresco.com, nick.burch@alfresco.com, - // 'Roy Wetherall' - // (No BCC shown) - - - String[] files = new String[] { - "example_received_regular.msg", "example_received_unicode.msg" - }; - for(String file : files) { - NPOIFSFileSystem poifs = new NPOIFSFileSystem(samples.getFile(file), true); - MAPIMessage msg = new MAPIMessage(poifs); - - - OutlookTextExtactor ext = new OutlookTextExtactor(msg); - String text = ext.getText(); - - assertContains(text, "From: Mike Farman\n"); - assertContains(text, "To: 'Ashutosh Dandavate' ; " + - "'Paul Holmes-Higgin' ; 'Mike Farman' \n"); - assertContains(text, "CC: nickb@alfresco.com; " + - "nick.burch@alfresco.com; 'Roy Wetherall' \n"); - assertEquals(-1, text.indexOf("BCC:")); - assertContains(text, "Subject: This is a test message please ignore\n"); - assertContains(text, "Date: Mon, 11 Jan 2010 16:2"); // Exact times differ slightly - assertContains(text, "The quick brown fox jumps over the lazy dog"); - - ext.close(); - poifs.close(); - } - } - - /** - * See also {@link org.apache.poi.extractor.TestExtractorFactory#testEmbeded()} - */ - public void testWithAttachments() throws Exception { - NPOIFSFileSystem poifs = new NPOIFSFileSystem(samples.getFile("attachment_test_msg.msg"), true); - MAPIMessage msg = new MAPIMessage(poifs); - OutlookTextExtactor ext = new OutlookTextExtactor(msg); - - // Check the normal bits - String text = ext.getText(); - - assertContains(text, "From: Nicolas1"); - assertContains(text, "To: 'nicolas1.23456@free.fr'"); - assertEquals(-1, text.indexOf("CC:")); - assertEquals(-1, text.indexOf("BCC:")); - assertContains(text, "Subject: test"); - assertContains(text, "Date: Wed, 22 Apr"); - assertContains(text, "Attachment: test-unicode.doc\n"); - assertContains(text, "Attachment: pj1.txt\n"); - assertContains(text, "contenu"); - - // Embeded bits are checked in - // TestExtractorFactory - - ext.close(); - poifs.close(); - } - - public void testWithAttachedMessage() throws Exception { - NPOIFSFileSystem poifs = new NPOIFSFileSystem(samples.getFile("58214_with_attachment.msg"), true); - MAPIMessage msg = new MAPIMessage(poifs); - OutlookTextExtactor ext = new OutlookTextExtactor(msg); - String text = ext.getText(); - - // Check we got bits from the main message - assertContains(text, "Master mail"); - assertContains(text, "ante in lacinia euismod"); - - // But not the attached message - assertNotContained(text, "Test mail attachment"); - assertNotContained(text, "Lorem ipsum dolor sit"); - - ext.close(); - poifs.close(); - } - - public void testEncodings() throws Exception { - NPOIFSFileSystem poifs = new NPOIFSFileSystem(samples.getFile("chinese-traditional.msg"), true); - MAPIMessage msg = new MAPIMessage(poifs); - OutlookTextExtactor ext = new OutlookTextExtactor(msg); - String text = ext.getText(); - - // Check the english bits - assertContains(text, "From: Tests Chang@FT"); - assertContains(text, "tests.chang@fengttt.com"); - - // And check some chinese bits - assertContains(text, "(\u5f35\u6bd3\u502b)"); - assertContains(text, "( MSG \u683c\u5f0f\u6e2c\u8a66 )"); - - ext.close(); - poifs.close(); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hsmf/parsers/TestPOIFSChunkParser.java b/src/scratchpad/testcases/org/apache/poi/hsmf/parsers/TestPOIFSChunkParser.java deleted file mode 100644 index 5928e5a8f..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hsmf/parsers/TestPOIFSChunkParser.java +++ /dev/null @@ -1,326 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hsmf.parsers; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.util.Arrays; -import java.util.Calendar; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hsmf.MAPIMessage; -import org.apache.poi.hsmf.datatypes.AttachmentChunks; -import org.apache.poi.hsmf.datatypes.ChunkGroup; -import org.apache.poi.hsmf.datatypes.Chunks; -import org.apache.poi.hsmf.datatypes.MAPIProperty; -import org.apache.poi.hsmf.datatypes.NameIdChunks; -import org.apache.poi.hsmf.datatypes.RecipientChunks; -import org.apache.poi.hsmf.datatypes.RecipientChunks.RecipientChunksSorter; -import org.apache.poi.hsmf.datatypes.StringChunk; -import org.apache.poi.hsmf.datatypes.Types; -import org.apache.poi.hsmf.exceptions.ChunkNotFoundException; -import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; -import org.apache.poi.util.LocaleUtil; -import org.junit.Test; - -/** - * Tests to verify that the chunk parser works properly - */ -public final class TestPOIFSChunkParser { - private final POIDataSamples samples = POIDataSamples.getHSMFInstance(); - - @Test - public void testFindsCore() throws Exception { - NPOIFSFileSystem simple = new NPOIFSFileSystem(samples.getFile("quick.msg"), true); - - // Check a few core things are present - simple.getRoot().getEntry( - (new StringChunk(MAPIProperty.SUBJECT.id, Types.ASCII_STRING)).getEntryName() - ); - simple.getRoot().getEntry( - (new StringChunk(MAPIProperty.SENDER_NAME.id, Types.ASCII_STRING)).getEntryName() - ); - - // Now load the file - MAPIMessage msg = new MAPIMessage(simple); - assertEquals("Kevin Roast", msg.getDisplayTo()); - assertEquals("Kevin Roast", msg.getDisplayFrom()); - assertEquals("Test the content transformer", msg.getSubject()); - - // Check date too - Calendar calExp = LocaleUtil.getLocaleCalendar(2007,5,14,9,42,55); - Calendar calAct = msg.getMessageDate(); - assertEquals( calExp, calAct ); - - simple.close(); - } - - public void testFindsRecips() throws IOException, ChunkNotFoundException { - NPOIFSFileSystem simple = new NPOIFSFileSystem(samples.getFile("quick.msg"), true); - - simple.getRoot().getEntry("__recip_version1.0_#00000000"); - - ChunkGroup[] groups = POIFSChunkParser.parse(simple.getRoot()); - assertEquals(3, groups.length); - assertTrue(groups[0] instanceof Chunks); - assertTrue(groups[1] instanceof RecipientChunks); - assertTrue(groups[2] instanceof NameIdChunks); - - RecipientChunks recips = (RecipientChunks)groups[1]; - assertEquals("kevin.roast@alfresco.org", recips.recipientSMTPChunk.getValue()); - assertEquals("/O=HOSTEDSERVICE2/OU=FIRST ADMINISTRATIVE GROUP/CN=RECIPIENTS/CN=Kevin.roast@ben", - recips.recipientEmailChunk.getValue()); - - String search = new String(recips.recipientSearchChunk.getValue(), "ASCII"); - assertEquals("CN=KEVIN.ROAST@BEN\0", search.substring(search.length()-19)); - - // Now via MAPIMessage - MAPIMessage msg = new MAPIMessage(simple); - assertNotNull(msg.getRecipientDetailsChunks()); - assertEquals(1, msg.getRecipientDetailsChunks().length); - - assertEquals("kevin.roast@alfresco.org", msg.getRecipientDetailsChunks()[0].recipientSMTPChunk.getValue()); - assertEquals("kevin.roast@alfresco.org", msg.getRecipientDetailsChunks()[0].getRecipientEmailAddress()); - assertEquals("Kevin Roast", msg.getRecipientDetailsChunks()[0].getRecipientName()); - assertEquals("kevin.roast@alfresco.org", msg.getRecipientEmailAddress()); - - - // Try both SMTP and EX files for recipient - assertEquals("EX", msg.getRecipientDetailsChunks()[0].deliveryTypeChunk.getValue()); - assertEquals("kevin.roast@alfresco.org", msg.getRecipientDetailsChunks()[0].recipientSMTPChunk.getValue()); - assertEquals("/O=HOSTEDSERVICE2/OU=FIRST ADMINISTRATIVE GROUP/CN=RECIPIENTS/CN=Kevin.roast@ben", - msg.getRecipientDetailsChunks()[0].recipientEmailChunk.getValue()); - simple.close(); - - - // Now look at another message - simple = new NPOIFSFileSystem(samples.getFile("simple_test_msg.msg"), true); - msg = new MAPIMessage(simple); - assertNotNull(msg.getRecipientDetailsChunks()); - assertEquals(1, msg.getRecipientDetailsChunks().length); - - assertEquals("SMTP", msg.getRecipientDetailsChunks()[0].deliveryTypeChunk.getValue()); - assertEquals(null, msg.getRecipientDetailsChunks()[0].recipientSMTPChunk); - assertEquals(null, msg.getRecipientDetailsChunks()[0].recipientNameChunk); - assertEquals("travis@overwrittenstack.com", msg.getRecipientDetailsChunks()[0].recipientEmailChunk.getValue()); - assertEquals("travis@overwrittenstack.com", msg.getRecipientEmailAddress()); - - simple.close(); - } - - public void testFindsMultipleRecipients() throws IOException, ChunkNotFoundException { - NPOIFSFileSystem multiple = new NPOIFSFileSystem(samples.getFile("example_received_unicode.msg"), true); - - multiple.getRoot().getEntry("__recip_version1.0_#00000000"); - multiple.getRoot().getEntry("__recip_version1.0_#00000001"); - multiple.getRoot().getEntry("__recip_version1.0_#00000002"); - multiple.getRoot().getEntry("__recip_version1.0_#00000003"); - multiple.getRoot().getEntry("__recip_version1.0_#00000004"); - multiple.getRoot().getEntry("__recip_version1.0_#00000005"); - - ChunkGroup[] groups = POIFSChunkParser.parse(multiple.getRoot()); - assertEquals(9, groups.length); - assertTrue(groups[0] instanceof Chunks); - assertTrue(groups[1] instanceof RecipientChunks); - assertTrue(groups[2] instanceof RecipientChunks); - assertTrue(groups[3] instanceof RecipientChunks); - assertTrue(groups[4] instanceof RecipientChunks); - assertTrue(groups[5] instanceof AttachmentChunks); - assertTrue(groups[6] instanceof RecipientChunks); - assertTrue(groups[7] instanceof RecipientChunks); - assertTrue(groups[8] instanceof NameIdChunks); - - // In FS order initially - RecipientChunks[] chunks = new RecipientChunks[] { - (RecipientChunks)groups[1], - (RecipientChunks)groups[2], - (RecipientChunks)groups[3], - (RecipientChunks)groups[4], - (RecipientChunks)groups[6], - (RecipientChunks)groups[7], - }; - assertEquals(6, chunks.length); - assertEquals(0, chunks[0].recipientNumber); - assertEquals(2, chunks[1].recipientNumber); - assertEquals(4, chunks[2].recipientNumber); - assertEquals(5, chunks[3].recipientNumber); - assertEquals(3, chunks[4].recipientNumber); - assertEquals(1, chunks[5].recipientNumber); - - // Check - assertEquals("'Ashutosh Dandavate'", chunks[0].getRecipientName()); - assertEquals("ashutosh.dandavate@alfresco.com", chunks[0].getRecipientEmailAddress()); - assertEquals("'Mike Farman'", chunks[1].getRecipientName()); - assertEquals("mikef@alfresco.com", chunks[1].getRecipientEmailAddress()); - assertEquals("nick.burch@alfresco.com", chunks[2].getRecipientName()); - assertEquals("nick.burch@alfresco.com", chunks[2].getRecipientEmailAddress()); - assertEquals("'Roy Wetherall'", chunks[3].getRecipientName()); - assertEquals("roy.wetherall@alfresco.com", chunks[3].getRecipientEmailAddress()); - assertEquals("nickb@alfresco.com", chunks[4].getRecipientName()); - assertEquals("nickb@alfresco.com", chunks[4].getRecipientEmailAddress()); - assertEquals("'Paul Holmes-Higgin'", chunks[5].getRecipientName()); - assertEquals("paul.hh@alfresco.com", chunks[5].getRecipientEmailAddress()); - - // Now sort, and re-check - Arrays.sort(chunks, new RecipientChunksSorter()); - - assertEquals("'Ashutosh Dandavate'", chunks[0].getRecipientName()); - assertEquals("ashutosh.dandavate@alfresco.com", chunks[0].getRecipientEmailAddress()); - assertEquals("'Paul Holmes-Higgin'", chunks[1].getRecipientName()); - assertEquals("paul.hh@alfresco.com", chunks[1].getRecipientEmailAddress()); - assertEquals("'Mike Farman'", chunks[2].getRecipientName()); - assertEquals("mikef@alfresco.com", chunks[2].getRecipientEmailAddress()); - assertEquals("nickb@alfresco.com", chunks[3].getRecipientName()); - assertEquals("nickb@alfresco.com", chunks[3].getRecipientEmailAddress()); - assertEquals("nick.burch@alfresco.com", chunks[4].getRecipientName()); - assertEquals("nick.burch@alfresco.com", chunks[4].getRecipientEmailAddress()); - assertEquals("'Roy Wetherall'", chunks[5].getRecipientName()); - assertEquals("roy.wetherall@alfresco.com", chunks[5].getRecipientEmailAddress()); - - // Finally check on message - MAPIMessage msg = new MAPIMessage(multiple); - assertEquals(6, msg.getRecipientEmailAddressList().length); - assertEquals(6, msg.getRecipientNamesList().length); - - assertEquals("'Ashutosh Dandavate'", msg.getRecipientNamesList()[0]); - assertEquals("'Paul Holmes-Higgin'", msg.getRecipientNamesList()[1]); - assertEquals("'Mike Farman'", msg.getRecipientNamesList()[2]); - assertEquals("nickb@alfresco.com", msg.getRecipientNamesList()[3]); - assertEquals("nick.burch@alfresco.com", msg.getRecipientNamesList()[4]); - assertEquals("'Roy Wetherall'", msg.getRecipientNamesList()[5]); - - assertEquals("ashutosh.dandavate@alfresco.com", msg.getRecipientEmailAddressList()[0]); - assertEquals("paul.hh@alfresco.com", msg.getRecipientEmailAddressList()[1]); - assertEquals("mikef@alfresco.com", msg.getRecipientEmailAddressList()[2]); - assertEquals("nickb@alfresco.com", msg.getRecipientEmailAddressList()[3]); - assertEquals("nick.burch@alfresco.com", msg.getRecipientEmailAddressList()[4]); - assertEquals("roy.wetherall@alfresco.com", msg.getRecipientEmailAddressList()[5]); - - multiple.close(); - } - - public void testFindsNameId() throws IOException { - NPOIFSFileSystem simple = new NPOIFSFileSystem(samples.getFile("quick.msg"), true); - - simple.getRoot().getEntry("__nameid_version1.0"); - - ChunkGroup[] groups = POIFSChunkParser.parse(simple.getRoot()); - assertEquals(3, groups.length); - assertTrue(groups[0] instanceof Chunks); - assertTrue(groups[1] instanceof RecipientChunks); - assertTrue(groups[2] instanceof NameIdChunks); - - NameIdChunks nameId = (NameIdChunks)groups[2]; - assertEquals(10, nameId.getAll().length); - - // Now via MAPIMessage - MAPIMessage msg = new MAPIMessage(simple); - assertNotNull(msg.getNameIdChunks()); - assertEquals(10, msg.getNameIdChunks().getAll().length); - - simple.close(); - } - - public void testFindsAttachments() throws Exception { - NPOIFSFileSystem with = new NPOIFSFileSystem(samples.getFile("attachment_test_msg.msg"), true); - NPOIFSFileSystem without = new NPOIFSFileSystem(samples.getFile("quick.msg"), true); - AttachmentChunks attachment; - - - // Check raw details on the one with - with.getRoot().getEntry("__attach_version1.0_#00000000"); - with.getRoot().getEntry("__attach_version1.0_#00000001"); - POIFSChunkParser.parse(with.getRoot()); - - ChunkGroup[] groups = POIFSChunkParser.parse(with.getRoot()); - assertEquals(5, groups.length); - assertTrue(groups[0] instanceof Chunks); - assertTrue(groups[1] instanceof RecipientChunks); - assertTrue(groups[2] instanceof AttachmentChunks); - assertTrue(groups[3] instanceof AttachmentChunks); - assertTrue(groups[4] instanceof NameIdChunks); - - attachment = (AttachmentChunks)groups[2]; - assertEquals("TEST-U~1.DOC", attachment.getAttachFileName().toString()); - assertEquals("test-unicode.doc", attachment.getAttachLongFileName().toString()); - assertEquals(24064, attachment.getAttachData().getValue().length); - - attachment = (AttachmentChunks)groups[3]; - assertEquals("pj1.txt", attachment.getAttachFileName().toString()); - assertEquals("pj1.txt", attachment.getAttachLongFileName().toString()); - assertEquals(89, attachment.getAttachData().getValue().length); - - - // Check raw details on one without - assertFalse(without.getRoot().hasEntry("__attach_version1.0_#00000000")); - assertFalse(without.getRoot().hasEntry("__attach_version1.0_#00000001")); - - // One with, from the top - MAPIMessage msgWith = new MAPIMessage(with); - assertEquals(2, msgWith.getAttachmentFiles().length); - - attachment = msgWith.getAttachmentFiles()[0]; - assertEquals("TEST-U~1.DOC", attachment.getAttachFileName().toString()); - assertEquals("test-unicode.doc", attachment.getAttachLongFileName().toString()); - assertEquals(24064, attachment.getAttachData().getValue().length); - - attachment = msgWith.getAttachmentFiles()[1]; - assertEquals("pj1.txt", attachment.getAttachFileName().toString()); - assertEquals("pj1.txt", attachment.getAttachLongFileName().toString()); - assertEquals(89, attachment.getAttachData().getValue().length); - - // Plus check core details are there - assertEquals("'nicolas1.23456@free.fr'", msgWith.getDisplayTo()); - assertEquals("Nicolas1 23456", msgWith.getDisplayFrom()); - assertEquals("test pi\u00e8ce jointe 1", msgWith.getSubject()); - - // One without, from the top - MAPIMessage msgWithout = new MAPIMessage(without); - - // No attachments - assertEquals(0, msgWithout.getAttachmentFiles().length); - - // But has core details - assertEquals("Kevin Roast", msgWithout.getDisplayTo()); - assertEquals("Kevin Roast", msgWithout.getDisplayFrom()); - assertEquals("Test the content transformer", msgWithout.getSubject()); - - without.close(); - with.close(); - } - - /** - * Bugzilla #51873 - Outlook 2002 files created with dragging and - * dropping files to the disk include a non-standard named streams - * such as "Olk10SideProps_0001" - */ - public void testOlk10SideProps() throws Exception { - NPOIFSFileSystem poifs = new NPOIFSFileSystem(samples.getFile("51873.msg"), true); - MAPIMessage msg = new MAPIMessage(poifs); - - // Check core details came through - assertEquals("bubba@bubbasmith.com", msg.getDisplayTo()); - assertEquals("Test with Olk10SideProps_ Chunk", msg.getSubject()); - - poifs.close(); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hssf/converter/TestExcelConverterSuite.java b/src/scratchpad/testcases/org/apache/poi/hssf/converter/TestExcelConverterSuite.java deleted file mode 100644 index 799a44c07..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hssf/converter/TestExcelConverterSuite.java +++ /dev/null @@ -1,132 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hssf.converter; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.util.XMLHelper; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; -import java.io.File; -import java.io.FilenameFilter; -import java.io.StringWriter; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import static org.junit.Assert.assertNotNull; - -@RunWith(Parameterized.class) -public class TestExcelConverterSuite -{ - /** - * YK: a quick hack to exclude failing documents from the suite. - */ - @SuppressWarnings("ArraysAsListWithZeroOrOneArgument") - private static List failingFiles = Arrays.asList( - /* not failing, but requires more memory */ - "ex45698-22488.xls" ); - - @Parameterized.Parameters(name="{index}: {0}") - public static Iterable files() { - List files = new ArrayList(); - File directory = POIDataSamples.getDocumentInstance().getFile( - "../spreadsheet" ); - for ( final File child : directory.listFiles( new FilenameFilter() - { - @Override - public boolean accept( File dir, String name ) - { - return name.endsWith( ".xls" ) && !failingFiles.contains( name ); - } - } ) ) - { - files.add(new Object[] { child }); - } - - return files; - } - - - @Parameterized.Parameter - public File child; - - @Test - public void testFo() throws Exception - { - HSSFWorkbook workbook; - try { - workbook = ExcelToHtmlUtils.loadXls( child ); - } catch ( Exception exc ) { - // unable to parse file -- not ExcelToFoConverter fault - return; - } - - ExcelToHtmlConverter excelToHtmlConverter = new ExcelToHtmlConverter( - XMLHelper.getDocumentBuilderFactory().newDocumentBuilder().newDocument() ); - excelToHtmlConverter.processWorkbook( workbook ); - - StringWriter stringWriter = new StringWriter(); - - Transformer transformer = TransformerFactory.newInstance() - .newTransformer(); - transformer.setOutputProperty( OutputKeys.ENCODING, "utf-8" ); - transformer.setOutputProperty( OutputKeys.INDENT, "yes" ); - transformer.setOutputProperty( OutputKeys.METHOD, "xml" ); - transformer.transform( - new DOMSource( excelToHtmlConverter.getDocument() ), - new StreamResult( stringWriter ) ); - - assertNotNull(stringWriter.toString()); - } - - @Test - public void testHtml() throws Exception - { - HSSFWorkbook workbook; - try { - workbook = ExcelToHtmlUtils.loadXls( child ); - } catch ( Exception exc ) { - // unable to parse file -- not ExcelToFoConverter fault - return; - } - - ExcelToHtmlConverter excelToHtmlConverter = new ExcelToHtmlConverter( - XMLHelper.getDocumentBuilderFactory().newDocumentBuilder().newDocument() ); - excelToHtmlConverter.processWorkbook( workbook ); - - StringWriter stringWriter = new StringWriter(); - - Transformer transformer = TransformerFactory.newInstance() - .newTransformer(); - transformer.setOutputProperty( OutputKeys.ENCODING, "utf-8" ); - transformer.setOutputProperty( OutputKeys.INDENT, "no" ); - transformer.setOutputProperty( OutputKeys.METHOD, "html" ); - transformer.transform( - new DOMSource( excelToHtmlConverter.getDocument() ), - new StreamResult( stringWriter ) ); - - assertNotNull(stringWriter.toString()); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hssf/usermodel/TestHSSFChart.java b/src/scratchpad/testcases/org/apache/poi/hssf/usermodel/TestHSSFChart.java deleted file mode 100644 index 987741f4c..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hssf/usermodel/TestHSSFChart.java +++ /dev/null @@ -1,273 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertNull; - -import java.io.IOException; - -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.record.chart.SeriesRecord; -import org.apache.poi.hssf.usermodel.HSSFChart.HSSFSeries; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.CellRangeAddressBase; -import org.junit.Test; - -/** - * Tests for {@link HSSFChart} - */ -public final class TestHSSFChart { - - @Test - public void testSingleChart() { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("WithChart.xls"); - - HSSFSheet s1 = wb.getSheetAt(0); - HSSFSheet s2 = wb.getSheetAt(1); - HSSFSheet s3 = wb.getSheetAt(2); - - assertEquals(0, HSSFChart.getSheetCharts(s1).length); - assertEquals(1, HSSFChart.getSheetCharts(s2).length); - assertEquals(0, HSSFChart.getSheetCharts(s3).length); - - HSSFChart[] charts; - - // Check the chart on the 2nd sheet - charts = HSSFChart.getSheetCharts(s2); - assertEquals(1, charts.length); - - assertEquals(2, charts[0].getSeries().length); - assertEquals("1st Column", charts[0].getSeries()[0].getSeriesTitle()); - assertEquals("2nd Column", charts[0].getSeries()[1].getSeriesTitle()); - assertNull(charts[0].getChartTitle()); - - // Check x, y, width, height - assertEquals(0, charts[0].getChartX()); - assertEquals(0, charts[0].getChartY()); - assertEquals(26492928, charts[0].getChartWidth()); - assertEquals(15040512, charts[0].getChartHeight()); - } - - @Test - public void testTwoCharts() { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("WithTwoCharts.xls"); - - HSSFSheet s1 = wb.getSheetAt(0); - HSSFSheet s2 = wb.getSheetAt(1); - HSSFSheet s3 = wb.getSheetAt(2); - - assertEquals(0, HSSFChart.getSheetCharts(s1).length); - assertEquals(1, HSSFChart.getSheetCharts(s2).length); - assertEquals(1, HSSFChart.getSheetCharts(s3).length); - - HSSFChart[] charts; - - // Check the chart on the 2nd sheet - charts = HSSFChart.getSheetCharts(s2); - assertEquals(1, charts.length); - - assertEquals(2, charts[0].getSeries().length); - assertEquals("1st Column", charts[0].getSeries()[0].getSeriesTitle()); - assertEquals("2nd Column", charts[0].getSeries()[1].getSeriesTitle()); - assertNull(charts[0].getChartTitle()); - - // And the third sheet - charts = HSSFChart.getSheetCharts(s3); - assertEquals(1, charts.length); - - assertEquals(2, charts[0].getSeries().length); - assertEquals("Squares", charts[0].getSeries()[0].getSeriesTitle()); - assertEquals("Base Numbers", charts[0].getSeries()[1].getSeriesTitle()); - assertNull(charts[0].getChartTitle()); - } - - @Test - public void testThreeCharts() { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("WithThreeCharts.xls"); - - HSSFSheet s1 = wb.getSheetAt(0); - HSSFSheet s2 = wb.getSheetAt(1); - HSSFSheet s3 = wb.getSheetAt(2); - - assertEquals(0, HSSFChart.getSheetCharts(s1).length); - assertEquals(2, HSSFChart.getSheetCharts(s2).length); - assertEquals(1, HSSFChart.getSheetCharts(s3).length); - - HSSFChart[] charts; - - // Check the charts on the 2nd sheet - charts = HSSFChart.getSheetCharts(s2); - assertEquals(2, charts.length); - - assertEquals(2, charts[0].getSeries().length); - assertEquals("1st Column", charts[0].getSeries()[0].getSeriesTitle()); - assertEquals("2nd Column", charts[0].getSeries()[1].getSeriesTitle()); - assertEquals(6, charts[0].getSeries()[0].getNumValues()); - assertEquals(6, charts[0].getSeries()[1].getNumValues()); - assertEquals(SeriesRecord.CATEGORY_DATA_TYPE_NUMERIC, charts[0].getSeries()[0].getValueType()); - assertEquals(SeriesRecord.CATEGORY_DATA_TYPE_NUMERIC, charts[0].getSeries()[1].getValueType()); - assertNull(charts[0].getChartTitle()); - - assertEquals(1, charts[1].getSeries().length); - assertNull(charts[1].getSeries()[0].getSeriesTitle()); - assertEquals("Pie Chart Title Thingy", charts[1].getChartTitle()); - - // And the third sheet - charts = HSSFChart.getSheetCharts(s3); - assertEquals(1, charts.length); - - assertEquals(2, charts[0].getSeries().length); - assertEquals("Squares", charts[0].getSeries()[0].getSeriesTitle()); - assertEquals("Base Numbers", charts[0].getSeries()[1].getSeriesTitle()); - assertEquals("Sheet 3 Chart with Title", charts[0].getChartTitle()); - } - - @Test - public void testExistingSheet3() throws Exception { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("49581.xls"); - - HSSFSheet sheet = wb.getSheetAt( 2 ) ; - HSSFChart[] charts = HSSFChart.getSheetCharts( sheet ) ; - assertEquals(1, charts.length); - - for ( HSSFChart chart : charts ) { - for ( HSSFSeries series : chart.getSeries() ) { - chart.removeSeries( series ) ; - } - } - - // Save and re-check - wb = HSSFITestDataProvider.instance.writeOutAndReadBack(wb); - sheet = wb.getSheetAt( 2 ) ; - assertEquals(1, HSSFChart.getSheetCharts(sheet).length); - - HSSFChart c = HSSFChart.getSheetCharts(sheet)[0]; - assertEquals(0, c.getSeries().length); - } - - @Test - public void testExistingSheet2() throws Exception { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("49581.xls"); - HSSFSheet sheet = wb.getSheetAt( 1 ) ; - HSSFChart[] charts = HSSFChart.getSheetCharts( sheet ) ; - - assertEquals(1, charts.length); - for ( HSSFChart chart : charts ) { - HSSFSeries series ; - - // Starts with one - assertEquals(1, chart.getSeries().length); - - // Add two more - series = chart.createSeries() ; - series.setCategoryLabelsCellRange( new CellRangeAddress( 3, 4, 0, 0 ) ) ; - series.setValuesCellRange( new CellRangeAddress( 3, 4, 1, 1 ) ) ; - - series = chart.createSeries() ; - series.setCategoryLabelsCellRange( new CellRangeAddress( 6, 7, 0, 0 ) ) ; - series.setValuesCellRange( new CellRangeAddress( 6, 7, 1, 1 ) ) ; - } - - // Save and re-check - wb = HSSFITestDataProvider.instance.writeOutAndReadBack(wb); - sheet = wb.getSheetAt( 1 ) ; - assertEquals(1, HSSFChart.getSheetCharts(sheet).length); - - HSSFChart c = HSSFChart.getSheetCharts(sheet)[0]; - assertEquals(3, c.getSeries().length); - } - - @Test - public void testExistingSheet1() throws Exception { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("49581.xls"); - HSSFSheet sheet = wb.getSheetAt( 0 ) ; - HSSFChart[] charts = HSSFChart.getSheetCharts( sheet ) ; - - for ( HSSFChart chart : charts ) { - //System.out.println( chart.getType() ) ; - HSSFSeries[] seriesArray = chart.getSeries() ; - //System.out.println( "seriesArray.length=" + seriesArray.length ) ; - for ( HSSFSeries series : seriesArray ) - { - //System.out.println( "serie.getNumValues()=" + series.getNumValues() ) ; - CellRangeAddressBase range ; - - range = series.getValuesCellRange() ; - //System.out.println( range.toString() ) ; - range.setLastRow( range.getLastRow() + 1 ) ; - series.setValuesCellRange( range ) ; - - range = series.getCategoryLabelsCellRange() ; - //System.out.println( range.toString() ) ; - range.setLastRow( range.getLastRow() + 1 ) ; - series.setCategoryLabelsCellRange( range ) ; - } - - for ( int id = 0 ; id < 2 ; id++ ) - { - HSSFSeries newSeries = chart.createSeries() ; - newSeries.setValuesCellRange( new CellRangeAddress( 1 + id, 4, 3, 3 ) ) ; - String oldSeriesTitle = newSeries.getSeriesTitle() ; - if ( oldSeriesTitle != null ) - { - //System.out.println( "old series title: " + oldSeriesTitle ) ; - newSeries.setSeriesTitle( "new series" ) ; - } - } - } - - HSSFChart chart = charts[ 2 ] ; - chart.removeSeries( chart.getSeries()[ 0 ] ) ; - } - - /** - * Bug 26862: HSSFWorkbook.cloneSheet copies charts - */ - @Test - public void test26862() throws IOException, Exception { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("SimpleChart.xls"); - HSSFSheet srcSheet = wb.getSheetAt(0); - HSSFChart[] srcCharts = HSSFChart.getSheetCharts(srcSheet); - assertEquals(1, srcCharts.length); - HSSFChart srcChart = srcCharts[0]; - - // Clone the sheet - HSSFSheet clonedSheet = wb.cloneSheet(0); - - // Verify the chart was copied - HSSFChart[] clonedCharts = HSSFChart.getSheetCharts(clonedSheet); - assertEquals(1, clonedCharts.length); - HSSFChart clonedChart = clonedCharts[0]; - assertNotSame(srcChart, clonedChart); //refer to different objects - assertEquals(srcChart.getType(), clonedChart.getType()); - assertEquals(srcChart.getChartTitle(), clonedChart.getChartTitle()); - assertEquals(srcChart.getChartWidth(), clonedChart.getChartWidth()); - assertEquals(srcChart.getChartHeight(), clonedChart.getChartHeight()); - assertEquals(srcChart.getChartX(), clonedChart.getChartX()); - assertEquals(srcChart.getChartY(), clonedChart.getChartY()); - - // Check if chart was shallow copied or deep copied - clonedChart.setChartWidth(clonedChart.getChartWidth()+10); - assertEquals(srcChart.getChartWidth()+10, clonedChart.getChartWidth()); - - wb.close(); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hwmf/TestHwmfParsing.java b/src/scratchpad/testcases/org/apache/poi/hwmf/TestHwmfParsing.java deleted file mode 100644 index 07d251e2d..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hwmf/TestHwmfParsing.java +++ /dev/null @@ -1,251 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwmf; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import javax.imageio.ImageIO; -import java.awt.Dimension; -import java.awt.Graphics2D; -import java.awt.RenderingHints; -import java.awt.geom.Rectangle2D; -import java.awt.image.BufferedImage; -import java.io.File; -import java.io.FileFilter; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.FilterInputStream; -import java.io.IOException; -import java.net.URL; -import java.nio.charset.Charset; -import java.util.List; -import java.util.Locale; -import java.util.zip.ZipEntry; -import java.util.zip.ZipInputStream; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hwmf.record.HwmfFill.HwmfImageRecord; -import org.apache.poi.hwmf.record.HwmfFont; -import org.apache.poi.hwmf.record.HwmfRecord; -import org.apache.poi.hwmf.record.HwmfRecordType; -import org.apache.poi.hwmf.record.HwmfText; -import org.apache.poi.hwmf.usermodel.HwmfPicture; -import org.apache.poi.sl.usermodel.PictureData; -import org.apache.poi.sl.usermodel.PictureData.PictureType; -import org.apache.poi.sl.usermodel.SlideShow; -import org.apache.poi.sl.usermodel.SlideShowFactory; -import org.apache.poi.util.LocaleUtil; -import org.apache.poi.util.Units; -import org.junit.Ignore; -import org.junit.Test; - -public class TestHwmfParsing { - @Test - public void parse() throws IOException { - File f = POIDataSamples.getSlideShowInstance().getFile("santa.wmf"); - FileInputStream fis = new FileInputStream(f); - HwmfPicture wmf = new HwmfPicture(fis); - fis.close(); - List records = wmf.getRecords(); - assertEquals(581, records.size()); - } - - @Test - @Ignore("This is work-in-progress and not a real unit test ...") - public void paint() throws IOException { - File f = POIDataSamples.getSlideShowInstance().getFile("santa.wmf"); - // File f = new File("bla.wmf"); - FileInputStream fis = new FileInputStream(f); - HwmfPicture wmf = new HwmfPicture(fis); - fis.close(); - - Dimension dim = wmf.getSize(); - int width = Units.pointsToPixel(dim.getWidth()); - // keep aspect ratio for height - int height = Units.pointsToPixel(dim.getHeight()); - double max = Math.max(width, height); - if (max > 1500) { - width *= 1500/max; - height *= 1500/max; - } - - BufferedImage bufImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); - Graphics2D g = bufImg.createGraphics(); - g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); - g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); - g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); - - wmf.draw(g, new Rectangle2D.Double(0,0,width,height)); - - g.dispose(); - - ImageIO.write(bufImg, "PNG", new File("bla.png")); - } - - @Test - @Ignore("This is work-in-progress and not a real unit test ...") - public void fetchWmfFromGovdocs() throws IOException { - URL url = new URL("http://digitalcorpora.org/corpora/files/govdocs1/by_type/ppt.zip"); - File outdir = new File("build/ppt"); - outdir.mkdirs(); - ZipInputStream zis = new ZipInputStream(url.openStream()); - ZipEntry ze; - while ((ze = zis.getNextEntry()) != null) { - String basename = ze.getName().replaceAll(".*?([^/]+)\\.wmf", "$1"); - FilterInputStream fis = new FilterInputStream(zis){ - @Override - public void close() throws IOException {} - }; - try { - SlideShow ss = SlideShowFactory.create(fis); - int wmfIdx = 1; - for (PictureData pd : ss.getPictureData()) { - if (pd.getType() != PictureType.WMF) continue; - byte wmfData[] = pd.getData(); - String filename = String.format(Locale.ROOT, "%s-%04d.wmf", basename, wmfIdx); - FileOutputStream fos = new FileOutputStream(new File(outdir, filename)); - fos.write(wmfData); - fos.close(); - wmfIdx++; - } - ss.close(); - } catch (Exception e) { - System.out.println(ze.getName()+" ignored."); - } - } - } - - @Test - @Ignore("This is work-in-progress and not a real unit test ...") - public void parseWmfs() throws IOException { - // parse and render the extracted wmfs from the fetchWmfFromGovdocs step - boolean outputFiles = false; - boolean renderWmf = true; - File indir = new File("E:\\project\\poi\\misc\\govdocs-ppt"); - File outdir = new File("build/wmf"); - outdir.mkdirs(); - final String startFile = ""; - File files[] = indir.listFiles(new FileFilter() { - boolean foundStartFile = false; - @Override - public boolean accept(File pathname) { - foundStartFile |= startFile.isEmpty() || pathname.getName().contains(startFile); - return foundStartFile && pathname.getName().matches("(?i).*\\.wmf?$"); - } - }); - for (File f : files) { - try { - String basename = f.getName().replaceAll(".*?([^/]+)\\.wmf", "$1"); - FileInputStream fis = new FileInputStream(f); - HwmfPicture wmf = new HwmfPicture(fis); - fis.close(); - - int bmpIndex = 1; - for (HwmfRecord r : wmf.getRecords()) { - if (r instanceof HwmfImageRecord) { - BufferedImage bi = ((HwmfImageRecord)r).getImage(); - if (bi != null && outputFiles) { - String filename = String.format(Locale.ROOT, "%s-%04d.png", basename, bmpIndex); - ImageIO.write(bi, "PNG", new File(outdir, filename)); - } - bmpIndex++; - } - } - - if (renderWmf) { - Dimension dim = wmf.getSize(); - int width = Units.pointsToPixel(dim.getWidth()); - // keep aspect ratio for height - int height = Units.pointsToPixel(dim.getHeight()); - - BufferedImage bufImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); - Graphics2D g = bufImg.createGraphics(); - g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); - g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); - g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); - - wmf.draw(g); - - g.dispose(); - - ImageIO.write(bufImg, "PNG", new File(outdir, basename+".png")); - } - } catch (Exception e) { - System.out.println(f.getName()+" ignored."); - } - } - } - - @Test - @Ignore("If we decide we can use common crawl file specified, we can turn this back on") - public void testCyrillic() throws Exception { - //TODO: move test file to framework and fix this - File dir = new File("C:/somethingOrOther"); - File f = new File(dir, "ZMLH54SPLI76NQ7XMKVB7SMUJA2HTXTS-2.wmf"); - HwmfPicture wmf = new HwmfPicture(new FileInputStream(f)); - - Charset charset = LocaleUtil.CHARSET_1252; - StringBuilder sb = new StringBuilder(); - //this is pure hackery for specifying the font - //this happens to work on this test file, but you need to - //do what Graphics does by maintaining the stack, etc.! - for (HwmfRecord r : wmf.getRecords()) { - if (r.getRecordType().equals(HwmfRecordType.createFontIndirect)) { - HwmfFont font = ((HwmfText.WmfCreateFontIndirect)r).getFont(); - charset = (font.getCharSet().getCharset() == null) ? LocaleUtil.CHARSET_1252 : font.getCharSet().getCharset(); - } - if (r.getRecordType().equals(HwmfRecordType.extTextOut)) { - HwmfText.WmfExtTextOut textOut = (HwmfText.WmfExtTextOut)r; - sb.append(textOut.getText(charset)).append("\n"); - } - } - String txt = sb.toString(); - assertTrue(txt.contains("\u041E\u0431\u0449\u043E")); - assertTrue(txt.contains("\u0411\u0430\u043B\u0430\u043D\u0441")); - } - - @Test - @Ignore("If we decide we can use the common crawl file attached to Bug 60677, " + - "we can turn this back on") - public void testShift_JIS() throws Exception { - //TODO: move test file to framework and fix this - File f = new File("C:/data/file8.wmf"); - HwmfPicture wmf = new HwmfPicture(new FileInputStream(f)); - - Charset charset = LocaleUtil.CHARSET_1252; - StringBuilder sb = new StringBuilder(); - //this is pure hackery for specifying the font - //this happens to work on this test file, but you need to - //do what Graphics does by maintaining the stack, etc.! - for (HwmfRecord r : wmf.getRecords()) { - if (r.getRecordType().equals(HwmfRecordType.createFontIndirect)) { - HwmfFont font = ((HwmfText.WmfCreateFontIndirect)r).getFont(); - charset = (font.getCharSet().getCharset() == null) ? LocaleUtil.CHARSET_1252 : font.getCharSet().getCharset(); - } - if (r.getRecordType().equals(HwmfRecordType.extTextOut)) { - HwmfText.WmfExtTextOut textOut = (HwmfText.WmfExtTextOut)r; - sb.append(textOut.getText(charset)).append("\n"); - } - } - String txt = sb.toString(); - assertTrue(txt.contains("\u822A\u7A7A\u60C5\u5831\u696D\u52D9\u3078\u306E\uFF27\uFF29\uFF33")); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/AllHWPFTests.java b/src/scratchpad/testcases/org/apache/poi/hwpf/AllHWPFTests.java deleted file mode 100644 index 53ab56719..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/AllHWPFTests.java +++ /dev/null @@ -1,118 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf; - -import org.apache.poi.hwpf.converter.AbstractWordUtilsTest; -import org.apache.poi.hwpf.converter.TestWordToFoConverter; -import org.apache.poi.hwpf.converter.TestWordToHtmlConverter; -import org.apache.poi.hwpf.extractor.TestDifferentRoutes; -import org.apache.poi.hwpf.extractor.TestWordExtractor; -import org.apache.poi.hwpf.extractor.TestWordExtractorBugs; -import org.apache.poi.hwpf.model.TestBookmarksTables; -import org.apache.poi.hwpf.model.TestCHPBinTable; -import org.apache.poi.hwpf.model.TestDocumentProperties; -import org.apache.poi.hwpf.model.TestFileInformationBlock; -import org.apache.poi.hwpf.model.TestFontTable; -import org.apache.poi.hwpf.model.TestListTables; -import org.apache.poi.hwpf.model.TestNotesTables; -import org.apache.poi.hwpf.model.TestPAPBinTable; -import org.apache.poi.hwpf.model.TestPlexOfCps; -import org.apache.poi.hwpf.model.TestRevisionMarkAuthorTable; -import org.apache.poi.hwpf.model.TestSavedByTable; -import org.apache.poi.hwpf.model.TestSectionTable; -import org.apache.poi.hwpf.model.TestStyleSheet; -import org.apache.poi.hwpf.model.TestTextPieceTable; -import org.apache.poi.hwpf.sprm.TestSprms; -import org.apache.poi.hwpf.usermodel.TestBorderCode; -import org.apache.poi.hwpf.usermodel.TestBug46610; -import org.apache.poi.hwpf.usermodel.TestBug49820; -import org.apache.poi.hwpf.usermodel.TestBug50075; -import org.apache.poi.hwpf.usermodel.TestBugs; -import org.apache.poi.hwpf.usermodel.TestHWPFOldDocument; -import org.apache.poi.hwpf.usermodel.TestHeaderStories; -import org.apache.poi.hwpf.usermodel.TestLists; -import org.apache.poi.hwpf.usermodel.TestPictures; -import org.apache.poi.hwpf.usermodel.TestProblems; -import org.apache.poi.hwpf.usermodel.TestRange; -import org.apache.poi.hwpf.usermodel.TestRangeDelete; -import org.apache.poi.hwpf.usermodel.TestRangeInsertion; -import org.apache.poi.hwpf.usermodel.TestRangeProperties; -import org.apache.poi.hwpf.usermodel.TestRangeReplacement; -import org.apache.poi.hwpf.usermodel.TestRangeSymbols; -import org.apache.poi.hwpf.usermodel.TestTableRow; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -@RunWith(Suite.class) -@Suite.SuiteClasses({ - // org.apache.poi.hwpf - TestFieldsTables.class, - TestHWPFPictures.class, - TestHWPFRangeParts.class, - - // org.apache.poi.hwpf.converter - // TestWordToConverterSuite.class, - AbstractWordUtilsTest.class, - TestWordToFoConverter.class, - TestWordToHtmlConverter.class, - - // org.apache.poi.hwpf.extractor - TestDifferentRoutes.class, - TestWordExtractor.class, - TestWordExtractorBugs.class, - - // org.apache.poi.hwpf.model - TestBookmarksTables.class, - TestCHPBinTable.class, - TestDocumentProperties.class, - TestFileInformationBlock.class, - TestFontTable.class, - TestListTables.class, - TestNotesTables.class, - TestPAPBinTable.class, - TestPlexOfCps.class, - TestRevisionMarkAuthorTable.class, - TestSavedByTable.class, - TestSectionTable.class, - TestStyleSheet.class, - TestTextPieceTable.class, - - // org.apache.poi.hwpf.sprm - TestSprms.class, - - // org.apache.poi.hwpf.usermodel - TestBorderCode.class, - TestBug46610.class, - TestBug49820.class, - TestBug50075.class, - TestBugs.class, - TestHeaderStories.class, - TestHWPFOldDocument.class, - TestLists.class, - TestPictures.class, - TestProblems.class, - TestRange.class, - TestRangeDelete.class, - TestRangeInsertion.class, - TestRangeProperties.class, - TestRangeReplacement.class, - TestRangeSymbols.class, - TestTableRow.class -}) -public final class AllHWPFTests { -} diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/HWPFDocFixture.java b/src/scratchpad/testcases/org/apache/poi/hwpf/HWPFDocFixture.java deleted file mode 100644 index 763ec672c..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/HWPFDocFixture.java +++ /dev/null @@ -1,73 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf; - -import org.apache.poi.hwpf.model.FileInformationBlock; -import org.apache.poi.poifs.filesystem.DocumentEntry; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.POIDataSamples; - -import java.io.IOException; - - -public final class HWPFDocFixture -{ - public static final String DEFAULT_TEST_FILE = "test.doc"; - - public byte[] _tableStream; - public byte[] _mainStream; - public FileInformationBlock _fib; - private final String _testFile; - - public HWPFDocFixture(Object obj, String testFile) - { - _testFile = testFile; - } - - public void setUp() throws IOException { - POIFSFileSystem filesystem = new POIFSFileSystem( - POIDataSamples.getDocumentInstance().openResourceAsStream(_testFile)); - - DocumentEntry documentProps = - (DocumentEntry) filesystem.getRoot().getEntry("WordDocument"); - _mainStream = new byte[documentProps.getSize()]; - filesystem.createDocumentInputStream("WordDocument").read(_mainStream); - - // use the fib to determine the name of the table stream. - _fib = new FileInformationBlock(_mainStream); - - String name = "0Table"; - if (_fib.getFibBase().isFWhichTblStm()) - { - name = "1Table"; - } - - // read in the table stream. - DocumentEntry tableProps = - (DocumentEntry) filesystem.getRoot().getEntry(name); - _tableStream = new byte[tableProps.getSize()]; - filesystem.createDocumentInputStream(name).read(_tableStream); - - _fib.fillVariableFields(_mainStream, _tableStream); - } - - public void tearDown() - { - } - -} diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/HWPFTestCase.java b/src/scratchpad/testcases/org/apache/poi/hwpf/HWPFTestCase.java deleted file mode 100644 index 4dd62318e..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/HWPFTestCase.java +++ /dev/null @@ -1,63 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -import org.junit.After; -import org.junit.Before; - -public abstract class HWPFTestCase { - protected HWPFDocFixture _hWPFDocFixture; - - @Before - public void setUp() throws Exception { - /** @todo verify the constructors */ - _hWPFDocFixture = new HWPFDocFixture(this, getTestFile()); - - _hWPFDocFixture.setUp(); - } - - protected String getTestFile() { - return HWPFDocFixture.DEFAULT_TEST_FILE; - } - - @After - public void tearDown() throws Exception { - if (_hWPFDocFixture != null) { - _hWPFDocFixture.tearDown(); - } - - _hWPFDocFixture = null; - } - - public HWPFDocument writeOutAndRead(HWPFDocument doc) { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - HWPFDocument newDoc; - try { - doc.write(baos); - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - newDoc = new HWPFDocument(bais); - } catch (IOException e) { - throw new RuntimeException(e); - } - return newDoc; - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/HWPFTestDataSamples.java b/src/scratchpad/testcases/org/apache/poi/hwpf/HWPFTestDataSamples.java deleted file mode 100644 index 9cefffa01..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/HWPFTestDataSamples.java +++ /dev/null @@ -1,171 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hwpf; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.util.zip.ZipInputStream; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; - -public class HWPFTestDataSamples { - - private static final POILogger logger = POILogFactory - .getLogger( HWPFTestDataSamples.class ); - - public static HWPFDocument openSampleFile(String sampleFileName) { - try { - InputStream is = POIDataSamples.getDocumentInstance().openResourceAsStream(sampleFileName); - return new HWPFDocument(is); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - public static HWPFDocument openSampleFileFromArchive( String sampleFileName ) - { - final long start = System.currentTimeMillis(); - try - { - ZipInputStream is = new ZipInputStream( POIDataSamples - .getDocumentInstance() - .openResourceAsStream( sampleFileName ) ); - try - { - is.getNextEntry(); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - try - { - IOUtils.copy( is, baos ); - } - finally - { - baos.close(); - } - - final long endUnzip = System.currentTimeMillis(); - byte[] byteArray = baos.toByteArray(); - - logger.log( POILogger.DEBUG, "Unzipped in ", - Long.valueOf( endUnzip - start ), " ms -- ", - Long.valueOf( byteArray.length ), " byte(s)" ); - - ByteArrayInputStream bais = new ByteArrayInputStream( byteArray ); - HWPFDocument doc = new HWPFDocument( bais ); - final long endParse = System.currentTimeMillis(); - - logger.log( POILogger.DEBUG, "Parsed in ", - Long.valueOf( endParse - start ), " ms" ); - - return doc; - } - finally - { - is.close(); - } - } - catch ( IOException e ) - { - throw new RuntimeException( e ); - } - } - - /** - * Open a remote sample from URL. opening is performd in two phases: - * (1) download content into a byte array - * (2) construct HWPFDocument - * - * @param sampleFileUrl the url to open - */ - public static HWPFDocument openRemoteFile( String sampleFileUrl ) - { - final long start = System.currentTimeMillis(); - try - { - logger.log(POILogger.DEBUG, "Downloading ", sampleFileUrl, " ..."); - - InputStream is = new URL( sampleFileUrl ).openStream(); - try - { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - try - { - IOUtils.copy( is, baos ); - } - finally - { - baos.close(); - } - - final long endDownload = System.currentTimeMillis(); - byte[] byteArray = baos.toByteArray(); - - logger.log( POILogger.DEBUG, "Downloaded in ", - Long.valueOf( endDownload - start ), " ms -- ", - Long.valueOf( byteArray.length ), " byte(s)" ); - - ByteArrayInputStream bais = new ByteArrayInputStream( byteArray ); - HWPFDocument doc = new HWPFDocument( bais ); - final long endParse = System.currentTimeMillis(); - - logger.log( POILogger.DEBUG, "Parsed in ", - Long.valueOf( endParse - start ), " ms" ); - - return doc; - } - finally - { - is.close(); - } - } - catch ( IOException e ) - { - throw new RuntimeException( e ); - } - } - - public static HWPFOldDocument openOldSampleFile(String sampleFileName) { - try { - InputStream is = POIDataSamples.getDocumentInstance().openResourceAsStream(sampleFileName); - return new HWPFOldDocument(new POIFSFileSystem(is)); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - /** - * Writes a spreadsheet to a ByteArrayOutputStream and reads it back - * from a ByteArrayInputStream.

    - * Useful for verifying that the serialisation round trip - */ - public static HWPFDocument writeOutAndReadBack(HWPFDocument original) { - try { - ByteArrayOutputStream baos = new ByteArrayOutputStream(4096); - original.write(baos); - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - return new HWPFDocument(bais); - } catch (IOException e) { - throw new RuntimeException(e); - } - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/TestFieldsTables.java b/src/scratchpad/testcases/org/apache/poi/hwpf/TestFieldsTables.java deleted file mode 100644 index ddf778016..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/TestFieldsTables.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.hwpf; - -import static org.junit.Assert.assertEquals; - -import java.util.ArrayList; - -import org.apache.poi.hwpf.model.FieldsDocumentPart; -import org.apache.poi.hwpf.model.FieldsTables; -import org.apache.poi.hwpf.model.FileInformationBlock; -import org.apache.poi.hwpf.model.PlexOfField; -import org.junit.Test; - -/** - * Test case for the fields tables, this test is based on the test-fields.doc - * file instead of the usual test.doc. - */ -public class TestFieldsTables extends HWPFTestCase { - - private static final String EXPECTED[] = { - "[19, 43) - FLD - 0x13; 0x1f\n" + "[43, 54) - FLD - 0x14; 0xff\n" - + "[54, 59) - FLD - 0x15; 0x81\n", - - "[31, 59) - FLD - 0x13; 0x45\n" + "[59, 61) - FLD - 0x14; 0xff\n" - + "[61, 66) - FLD - 0x15; 0x80\n", - - "[23, 49) - FLD - 0x13; 0x11\n" + "[49, 64) - FLD - 0x14; 0xff\n" - + "[64, 69) - FLD - 0x15; 0x80\n", - - "[18, 42) - FLD - 0x13; 0x21\n" + "[42, 44) - FLD - 0x14; 0xff\n" - + "[44, 47) - FLD - 0x15; 0x81\n" - + "[47, 75) - FLD - 0x13; 0x1d\n" - + "[75, 85) - FLD - 0x14; 0xff\n" - + "[85, 91) - FLD - 0x15; 0x81\n", - - "[30, 54) - FLD - 0x13; 0x20\n" + "[54, 62) - FLD - 0x14; 0xff\n" - + "[62, 68) - FLD - 0x15; 0x81\n", - - "[1, 31) - FLD - 0x13; 0x15\n" + "[31, 51) - FLD - 0x14; 0xff\n" - + "[51, 541) - FLD - 0x15; 0x81\n", - - "[19, 47) - FLD - 0x13; 0x19\n" + "[47, 49) - FLD - 0x14; 0xff\n" - + "[49, 55) - FLD - 0x15; 0x81\n" - }; - - @Override - protected String getTestFile() { - return "test-fields.doc"; - } - - @Test - public void testReadFields() { - FileInformationBlock fib = _hWPFDocFixture._fib; - byte[] tableStream = _hWPFDocFixture._tableStream; - - FieldsTables fieldsTables = new FieldsTables(tableStream, fib); - - int i = 0; - for (FieldsDocumentPart part : FieldsDocumentPart.values()) { - String result = dumpPlexes(fieldsTables.getFieldsPLCF(part)); - assertEquals(EXPECTED[i++], result); - } - } - - private String dumpPlexes(ArrayList fieldsPlexes) { - StringBuilder dump = new StringBuilder(); - for (PlexOfField flds : fieldsPlexes) { - dump.append(flds.toString() + "\n"); - } - return dump.toString(); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/TestHWPFPictures.java b/src/scratchpad/testcases/org/apache/poi/hwpf/TestHWPFPictures.java deleted file mode 100644 index 9b48b2322..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/TestHWPFPictures.java +++ /dev/null @@ -1,190 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf; - -import java.awt.image.BufferedImage; -import java.io.ByteArrayInputStream; -import java.util.List; - -import javax.imageio.ImageIO; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hwpf.model.PicturesTable; -import org.apache.poi.hwpf.usermodel.Picture; - -import junit.framework.TestCase; - -/** - * Test picture support in HWPF - * @author nick - */ -public final class TestHWPFPictures extends TestCase { - private String docAFile; - private String docBFile; - private String docCFile; - private String docDFile; - - private String imgAFile; - private String imgBFile; - private String imgCFile; - private String imgDFile; - - @Override - protected void setUp() throws Exception { - super.setUp(); - - docAFile = "testPictures.doc"; - docBFile = "two_images.doc"; - docCFile = "vector_image.doc"; - docDFile = "GaiaTest.doc"; - - imgAFile = "simple_image.jpg"; - imgBFile = "simple_image.png"; - imgCFile = "vector_image.emf"; - imgDFile = "GaiaTestImg.png"; - } - - /** - * Test just opening the files - */ - public void testOpen() { - HWPFTestDataSamples.openSampleFile(docAFile); - HWPFTestDataSamples.openSampleFile(docBFile); - } - - /** - * Test that we have the right numbers of images in each file - */ - public void testImageCount() { - HWPFDocument docA = HWPFTestDataSamples.openSampleFile(docAFile); - HWPFDocument docB = HWPFTestDataSamples.openSampleFile(docBFile); - - assertNotNull(docA.getPicturesTable()); - assertNotNull(docB.getPicturesTable()); - - PicturesTable picA = docA.getPicturesTable(); - PicturesTable picB = docB.getPicturesTable(); - - List picturesA = picA.getAllPictures(); - List picturesB = picB.getAllPictures(); - - assertEquals(7, picturesA.size()); - assertEquals(2, picturesB.size()); - } - - /** - * Test that we have the right images in at least one file - */ - public void testImageData() { - HWPFDocument docB = HWPFTestDataSamples.openSampleFile(docBFile); - PicturesTable picB = docB.getPicturesTable(); - List picturesB = picB.getAllPictures(); - - assertEquals(2, picturesB.size()); - - Picture pic1 = picturesB.get(0); - Picture pic2 = picturesB.get(1); - - assertNotNull(pic1); - assertNotNull(pic2); - - // Check the same - byte[] pic1B = readFile(imgAFile); - byte[] pic2B = readFile(imgBFile); - - assertEquals(pic1B.length, pic1.getContent().length); - assertEquals(pic2B.length, pic2.getContent().length); - - assertBytesSame(pic1B, pic1.getContent()); - assertBytesSame(pic2B, pic2.getContent()); - } - - /** - * Test that compressed image data is correctly returned. - */ - public void testCompressedImageData() { - HWPFDocument docC = HWPFTestDataSamples.openSampleFile(docCFile); - PicturesTable picC = docC.getPicturesTable(); - List picturesC = picC.getAllPictures(); - - assertEquals(1, picturesC.size()); - - Picture pic = picturesC.get(0); - assertNotNull(pic); - - // Check the same - byte[] picBytes = readFile(imgCFile); - - assertEquals(picBytes.length, pic.getContent().length); - assertBytesSame(picBytes, pic.getContent()); - } - - public void testMacImages() throws Exception { - HWPFDocument docC = HWPFTestDataSamples.openSampleFile("53446.doc"); - PicturesTable picturesTable = docC.getPicturesTable(); - List pictures = picturesTable.getAllPictures(); - - assertEquals(4, pictures.size()); - - int[][] expectedSizes = { - { 185, 42 }, // PNG - { 260, 114 }, // PNG - { 185, 42 }, // PNG - { 260, 114 }, // PNG - }; - - for (int i = 0; i < pictures.size(); i++) { - BufferedImage image = ImageIO.read(new ByteArrayInputStream(pictures.get(i).getContent())); - assertNotNull(image); - - int[] dimensions = expectedSizes[i]; - assertEquals(dimensions[0], image.getWidth()); - assertEquals(dimensions[1], image.getHeight()); - } - } - - /** - * Pending the missing files being uploaded to - * bug #44937 - */ - public void testEscherDrawing() { - HWPFDocument docD = HWPFTestDataSamples.openSampleFile(docDFile); - List allPictures = docD.getPicturesTable().getAllPictures(); - - assertEquals(1, allPictures.size()); - - Picture pic = allPictures.get(0); - assertNotNull(pic); - byte[] picD = readFile(imgDFile); - - assertEquals(picD.length, pic.getContent().length); - - assertBytesSame(picD, pic.getContent()); - } - - private void assertBytesSame(byte[] a, byte[] b) { - assertEquals(a.length, b.length); - for(int i=0; i failingFiles = Arrays - .asList( "ProblemExtracting.doc", - "Bug50955.doc" //basic extraction works, - // but these extractors modify the document, - // which is a no-go for this Word 6.0 file - ); - - @Parameterized.Parameters(name="{index}: {0}") - public static Iterable files() { - List files = new ArrayList(); - File directory = POIDataSamples.getDocumentInstance().getFile( - "../document" ); - for ( final File child : directory.listFiles( new FilenameFilter() - { - @Override - public boolean accept( File dir, String name ) - { - return name.endsWith( ".doc" ) && !failingFiles.contains( name ); - } - } ) ) - { - files.add(new Object[] { child }); - } - - return files; - } - - @Parameterized.Parameter - public File child; - - @Test - public void testFo() throws Exception { - HWPFDocumentCore hwpfDocument; - try { - hwpfDocument = AbstractWordUtils.loadDoc( child ); - } catch ( Exception exc ) { - return; - } - - WordToFoConverter wordToFoConverter = new WordToFoConverter( - XMLHelper.getDocumentBuilderFactory().newDocumentBuilder().newDocument() ); - wordToFoConverter.processDocument( hwpfDocument ); - - StringWriter stringWriter = new StringWriter(); - - Transformer transformer = TransformerFactory.newInstance() - .newTransformer(); - transformer.setOutputProperty( OutputKeys.ENCODING, "utf-8" ); - transformer.setOutputProperty( OutputKeys.INDENT, "false" ); - transformer.transform( - new DOMSource( wordToFoConverter.getDocument() ), - new StreamResult( stringWriter ) ); - - // no exceptions - assertNotNull(stringWriter.toString()); - } - - @Test - public void testHtml() throws Exception - { - HWPFDocumentCore hwpfDocument; - try { - hwpfDocument = AbstractWordUtils.loadDoc( child ); - } catch ( Exception exc ) { - return; - } - - WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter( - XMLHelper.getDocumentBuilderFactory().newDocumentBuilder().newDocument() ); - wordToHtmlConverter.processDocument( hwpfDocument ); - - StringWriter stringWriter = new StringWriter(); - - Transformer transformer = TransformerFactory.newInstance() - .newTransformer(); - transformer.setOutputProperty( OutputKeys.ENCODING, "utf-8" ); - transformer.setOutputProperty( OutputKeys.INDENT, "false" ); - transformer.setOutputProperty( OutputKeys.METHOD, "html" ); - transformer.transform( - new DOMSource( wordToHtmlConverter.getDocument() ), - new StreamResult( stringWriter ) ); - - // no exceptions - assertNotNull(stringWriter.toString()); - } - - @Test - public void testText() throws Exception - { - HWPFDocumentCore wordDocument; - try { - wordDocument = AbstractWordUtils.loadDoc( child ); - } catch ( Exception exc ) { - return; - } - - WordToTextConverter wordToTextConverter = new WordToTextConverter( - XMLHelper.getDocumentBuilderFactory().newDocumentBuilder().newDocument() ); - wordToTextConverter.processDocument( wordDocument ); - - StringWriter stringWriter = new StringWriter(); - - Transformer transformer = TransformerFactory.newInstance() - .newTransformer(); - transformer.setOutputProperty( OutputKeys.ENCODING, "utf-8" ); - transformer.setOutputProperty( OutputKeys.INDENT, "yes" ); - transformer.setOutputProperty( OutputKeys.METHOD, "text" ); - transformer.transform( - new DOMSource( wordToTextConverter.getDocument() ), - new StreamResult( stringWriter ) ); - - // no exceptions - assertNotNull(stringWriter.toString()); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/converter/TestWordToFoConverter.java b/src/scratchpad/testcases/org/apache/poi/hwpf/converter/TestWordToFoConverter.java deleted file mode 100644 index 7dd60b0b8..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/converter/TestWordToFoConverter.java +++ /dev/null @@ -1,152 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -package org.apache.poi.hwpf.converter; - -import static org.apache.poi.POITestCase.assertContains; - -import java.io.StringWriter; - -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hwpf.HWPFDocument; -import org.apache.poi.util.XMLHelper; -import org.junit.Test; - -/** - * Test cases for {@link WordToFoConverter} - */ -public class TestWordToFoConverter -{ - private static String getFoText( final String sampleFileName ) - throws Exception - { - HWPFDocument hwpfDocument = new HWPFDocument( POIDataSamples - .getDocumentInstance().openResourceAsStream( sampleFileName ) ); - - WordToFoConverter wordToFoConverter = new WordToFoConverter( - XMLHelper.getDocumentBuilderFactory().newDocumentBuilder().newDocument() ); - wordToFoConverter.processDocument( hwpfDocument ); - - StringWriter stringWriter = new StringWriter(); - - Transformer transformer = TransformerFactory.newInstance() - .newTransformer(); - transformer.setOutputProperty( OutputKeys.INDENT, "yes" ); - transformer.transform( - new DOMSource( wordToFoConverter.getDocument() ), - new StreamResult( stringWriter ) ); - - String result = stringWriter.toString(); - return result; - } - - @Test - public void testDocumentProperties() throws Exception - { - String result = getFoText( "documentProperties.doc" ); - - assertContains( - result, - "This is document title" ); - assertContains( - result, - "This is document keywords" ); - } - - @Test - public void testEndnote() throws Exception - { - String result = getFoText( "endingnote.doc" ); - - assertContains( result, - "" ); - assertContains( result, - "1" ); - assertContains( result, - "" ); - assertContains( result, - "1 " ); - assertContains( result, "Ending note text" ); - } - - @Test - public void testEquation() throws Exception - { - final String sampleFileName = "equation.doc"; - String result = getFoText( sampleFileName ); - - assertContains( result, "" ); - } - - @Test - public void testHyperlink() throws Exception - { - final String sampleFileName = "hyperlink.doc"; - String result = getFoText( sampleFileName ); - - assertContains( result, - "" ); - assertContains( result, "Hyperlink text" ); - } - - @Test - public void testInnerTable() throws Exception - { - final String sampleFileName = "innertable.doc"; - String result = getFoText( sampleFileName ); - - assertContains( result, - "padding-end=\"0.0in\" padding-start=\"0.0in\" width=\"1.0770833in\"" ); - } - - @Test - public void testPageBreak() throws Exception - { - final String sampleFileName = "page-break.doc"; - String result = getFoText( sampleFileName ); - - assertContains( result, "" ); - assertContains( result, "1" ); - assertContains( result, "" ); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/converter/TestWordToHtmlConverter.java b/src/scratchpad/testcases/org/apache/poi/hwpf/converter/TestWordToHtmlConverter.java deleted file mode 100644 index 12c37bc6b..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/converter/TestWordToHtmlConverter.java +++ /dev/null @@ -1,284 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hwpf.converter; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hwpf.HWPFDocument; -import org.apache.poi.hwpf.usermodel.PictureType; -import org.apache.poi.util.XMLHelper; -import org.junit.Test; -import org.w3c.dom.Document; - -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; -import java.io.StringWriter; - -import static org.apache.poi.POITestCase.assertContains; -import static org.junit.Assert.assertFalse; - -/** - * Test cases for {@link WordToHtmlConverter} - */ -public class TestWordToHtmlConverter { - private static String getHtmlText(final String sampleFileName) throws Exception { - return getHtmlText(sampleFileName, false); - } - - private static String getHtmlText(final String sampleFileName, - boolean emulatePictureStorage) throws Exception { - HWPFDocument hwpfDocument = new HWPFDocument(POIDataSamples - .getDocumentInstance().openResourceAsStream(sampleFileName)); - - Document newDocument = XMLHelper.getDocumentBuilderFactory().newDocumentBuilder().newDocument(); - WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter( - newDocument); - - if (emulatePictureStorage) - { - wordToHtmlConverter.setPicturesManager(new PicturesManager() - { - @Override - public String savePicture(byte[] content, - PictureType pictureType, String suggestedName, - float widthInches, float heightInches) - { - return suggestedName; - } - }); - } - - wordToHtmlConverter.processDocument(hwpfDocument); - - StringWriter stringWriter = new StringWriter(); - - Transformer transformer = TransformerFactory.newInstance() - .newTransformer(); - transformer.setOutputProperty(OutputKeys.INDENT, "yes"); - transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8"); - transformer.setOutputProperty(OutputKeys.METHOD, "html"); - transformer.transform( - new DOMSource(wordToHtmlConverter.getDocument()), - new StreamResult(stringWriter)); - - return stringWriter.toString(); - } - - @Test - public void testAIOOBTap() throws Exception - { - String result = getHtmlText("AIOOB-Tap.doc"); - assertContains(result.substring(0, 6000), ""); - } - - @Test - public void testBug33519() throws Exception - { - String result = getHtmlText("Bug33519.doc"); - assertContains( - result, - "\u041F\u043B\u0430\u043D\u0438\u043D\u0441\u043A\u0438 \u0442\u0443\u0440\u043E\u0432\u0435"); - assertContains(result, - "\u042F\u0432\u043E\u0440 \u0410\u0441\u0435\u043D\u043E\u0432"); - } - - @Test - public void testBug46610_2() throws Exception - { - String result = getHtmlText("Bug46610_2.doc"); - assertContains( - result, - "012345678911234567892123456789312345678941234567890123456789112345678921234567893123456789412345678"); - } - - @Test - public void testBug46817() throws Exception - { - String result = getHtmlText("Bug46817.doc"); - final String substring = "
    "; - assertContains(result, substring); - } - - @Test - public void testBug47286() throws Exception - { - String result = getHtmlText("Bug47286.doc"); - - assertFalse(result.contains("FORMTEXT")); - - assertContains(result, "color:#4f6228;"); - assertContains(result, "Passport No and the date of expire"); - assertContains(result, "mfa.gov.cy"); - } - - @Test - public void testBug48075() throws Exception - { - getHtmlText("Bug48075.doc"); - } - - @Test - public void testBug52583() throws Exception - { - String result = getHtmlText("Bug52583.doc"); - assertContains( - result, - ""); - } - - @Test - public void testBug53182() throws Exception - { - String result = getHtmlText("Bug53182.doc"); - assertFalse(result.contains("italic")); - } - - @Test - public void testDocumentProperties() throws Exception - { - String result = getHtmlText("documentProperties.doc"); - - assertContains(result, "This is document title"); - assertContains(result, - ""); - } - - @Test - public void testEmailhyperlink() throws Exception - { - String result = getHtmlText("Bug47286.doc"); - final String substring = "provisastpet@mfa.gov.cy"; - assertContains(result, substring); - } - - @Test - public void testEndnote() throws Exception - { - String result = getHtmlText("endingnote.doc"); - - assertContains( - result, - "1"); - assertContains( - // starting with JDK 9 such unimportant whitespaces may be trimmed - result.replace("1"); - } - - @Test - public void testHyperlink() throws Exception - { - String result = getHtmlText("hyperlink.doc"); - - assertContains(result, "Before text; Hyperlink text"); - assertContains(result, "; after text"); - } - - @Test - public void testInnerTable() throws Exception - { - getHtmlText("innertable.doc"); - } - - @Test - public void testListsMargins() throws Exception - { - String result = getHtmlText("lists-margins.doc"); - - assertContains(result, - ".s1{display: inline-block; text-indent: 0; min-width: 0.4861111in;}"); - assertContains(result, - ".s2{display: inline-block; text-indent: 0; min-width: 0.23055555in;}"); - assertContains(result, - ".s3{display: inline-block; text-indent: 0; min-width: 0.28541666in;}"); - assertContains(result, - ".s4{display: inline-block; text-indent: 0; min-width: 0.28333333in;}"); - assertContains(result, - ".p4{text-indent:-0.59652776in;margin-left:-0.70069444in;"); - } - - @Test - public void testO_kurs_doc() throws Exception - { - getHtmlText("o_kurs.doc"); - } - - @Test - public void testPageref() throws Exception - { - String result = getHtmlText("pageref.doc"); - - assertContains(result, ""); - assertContains(result, ""); - assertContains(result, "1"); - } - - @Test - public void testPicture() throws Exception - { - String result = getHtmlText("picture.doc", true); - - // picture - assertContains(result, "src=\"0.emf\""); - // visible size - assertContains(result, "width:3.1293333in;height:1.7247736in;"); - // shift due to crop - assertContains(result, "left:-0.09433333;top:-0.2573611;"); - // size without crop - assertContains(result, "width:3.4125in;height:2.3253334in;"); - } - - @Test - public void testPicturesEscher() throws Exception - { - String result = getHtmlText("pictures_escher.doc", true); - assertContains(result, ""); - assertContains(result, ""); - } - - @Test - public void testTableMerges() throws Exception - { - String result = getHtmlText("table-merges.doc"); - - assertContains(result, ""; - - System.out.println(line); - } - } - - - - private static void replaceNaNs(byte[] fileContent, long[] replacementNaNs) { - int countFound = 0; - for(int i=0; i> 56); - bb[i+6] = (byte) (val >> 48); - bb[i+5] = (byte) (val >> 40); - bb[i+4] = (byte) (val >> 32); - bb[i+3] = (byte) (val >> 24); - bb[i+2] = (byte) (val >> 16); - bb[i+1] = (byte) (val >> 8); - bb[i+0] = (byte) (val >> 0); -// if (false) { -// String newVal = interpretLong(bb, i); -// System.out.println("changed offset " + i + " from " + oldVal + " to " + newVal); -// } - - } - - private static String interpretLong(byte[] fileContent, int offset) { - InputStream is = new ByteArrayInputStream(fileContent, offset, 8); - long l; - try { - l = new DataInputStream(is).readLong(); - } catch (IOException e) { - throw new RuntimeException(e); - } - return "0x" + Long.toHexString(l).toUpperCase(Locale.ROOT); - } - - private static boolean isNaNBytes(byte[] fileContent, int offset) { - if(offset + JAVA_NAN_BYTES.length > fileContent.length) { - return false; - } - // excel NaN bits: 0xFFFF0420003C0000L - // java NaN bits :0x7ff8000000000000L - return areArraySectionsEqual(fileContent, offset, JAVA_NAN_BYTES); - } - private static boolean areArraySectionsEqual(byte[] bb, int off, byte[] section) { - for (int i=section.length-1; i>=0; i--) { - if (bb[off+i] != section[i]){ - return false; - } - } - return true; - } -} diff --git a/src/testcases/org/apache/poi/ss/util/NumberToTextConversionExamples.java b/src/testcases/org/apache/poi/ss/util/NumberToTextConversionExamples.java deleted file mode 100644 index 1dcedc97a..000000000 --- a/src/testcases/org/apache/poi/ss/util/NumberToTextConversionExamples.java +++ /dev/null @@ -1,278 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.util; - -import java.util.Locale; - -/** - * Contains specific examples of double values and their rendering in Excel. - */ -final class NumberToTextConversionExamples { - - private NumberToTextConversionExamples() { - // no instances of this class - } - - public static final class ExampleConversion { - private final String _javaRendering; - private final String _excelRendering; - private final double _doubleValue; - private final long _rawDoubleBits; - - ExampleConversion(long rawDoubleBits, String javaRendering, String excelRendering) { - double d = Double.longBitsToDouble(rawDoubleBits); - if ("NaN".equals(javaRendering)) { - if (!Double.isNaN(d)) { - throw new IllegalArgumentException("value must be NaN"); - } - } else { - if (Double.isNaN(d)) { - throw new IllegalArgumentException("value must not be NaN"); - } - // just to be dead sure test conversion in java both ways - boolean javaToStringOk = javaRendering.equals(Double.toString(d)); - boolean javaParseOk = Double.parseDouble(javaRendering) == d; - if(!javaToStringOk || !javaParseOk) { - String msgA = "Specified rawDoubleBits " + doubleToHexString(d) + " encodes to double '" + d + "'."; - String msgB = "Specified javaRendering '" + javaRendering+ "' parses as double with rawDoubleBits " - + doubleToHexString(Double.parseDouble(javaRendering)); - System.err.println(msgA); - System.err.println(msgB); - - throw new RuntimeException(msgA + msgB); - } - } - _rawDoubleBits = rawDoubleBits; - _javaRendering = javaRendering; - _excelRendering = excelRendering; - _doubleValue = d; - } - private static String doubleToHexString(double d) { - return "0x" + Long.toHexString(Double.doubleToLongBits(d)).toUpperCase(Locale.ROOT) + "L"; - } - public String getJavaRendering() { - return _javaRendering; - } - public String getExcelRendering() { - return _excelRendering; - } - public double getDoubleValue() { - return _doubleValue; - } - public boolean isNaN() { - return Double.isNaN(_doubleValue); - } - public long getRawDoubleBits() { - return _rawDoubleBits; - } - } - - - /** - * Number rendering examples as observed from Excel. - * TODO - some are currently disabled because POI does not pass these cases yet - */ - private static final ExampleConversion[] examples = { - - // basic numbers - ec(0x0000000000000000L, "0.0", "0"), - ec(0x3FF0000000000000L, "1.0", "1"), - ec(0x3FF00068DB8BAC71L, "1.0001", "1.0001"), - ec(0x4087A00000000000L, "756.0", "756"), - ec(0x401E3D70A3D70A3DL, "7.56", "7.56"), - - ec(0x405EDD3C07FB4C8CL, "123.4567890123455", "123.456789012345"), - ec(0x405EDD3C07FB4C99L, "123.45678901234568", "123.456789012346"), - ec(0x405EDD3C07FB4CAEL, "123.45678901234598", "123.456789012346"), - ec(0x4132D687E3DF2180L, "1234567.8901234567", "1234567.89012346"), - - ec(0x3F543A272D9E0E49L, "0.001234567890123455", "0.00123456789012345"), - ec(0x3F543A272D9E0E4AL, "0.0012345678901234552", "0.00123456789012346"), - ec(0x3F543A272D9E0E55L, "0.0012345678901234576", "0.00123456789012346"), - ec(0x3F543A272D9E0E72L, "0.0012345678901234639", "0.00123456789012346"), - ec(0x3F543A272D9E0E76L, "0.0012345678901234647", "0.00123456789012346"), - ec(0x3F543A272D9E0E77L, "0.001234567890123465", "0.00123456789012346"), - - ec(0x3F543A272D9E0E78L, "0.0012345678901234652", "0.00123456789012347"), - - ec(0x3F543A272D9E0EA5L, "0.001234567890123475", "0.00123456789012347"), - ec(0x3F543A272D9E0EA6L, "0.0012345678901234751", "0.00123456789012348"), - - - ec(0x544CE6345CF3209CL, "1.2345678901234549E98", "1.23456789012345E+98"), - ec(0x544CE6345CF3209DL, "1.234567890123455E98", "1.23456789012346E+98"), - ec(0x544CE6345CF320DEL, "1.2345678901234649E98", "1.23456789012346E+98"), - ec(0x544CE6345CF320DFL, "1.234567890123465E98", "1.23456789012347E+98"), - ec(0x544CE6345CF32120L, "1.234567890123475E98", "1.23456789012347E+98"), - ec(0x544CE6345CF32121L, "1.2345678901234751E98", "1.23456789012348E+98"), - - - ec(0x54820FE0BA17F5E9L, "1.23456789012355E99", "1.2345678901236E+99"), - ec(0x54820FE0BA17F5EAL, "1.2345678901235502E99", "1.2345678901236E+99"), - ec(0x54820FE0BA17F784L, "1.2345678901236498E99", "1.2345678901237E+99"), - ec(0x54820FE0BA17F785L, "1.23456789012365E99", "1.2345678901237E+99"), - ec(0x54820FE0BA17F920L, "1.2345678901237498E99", "1.2345678901238E+99"), - ec(0x54820FE0BA17F921L, "1.23456789012375E99", "1.2345678901238E+99"), - - - // transitions around the E98,E99,E100 boundaries - ec(0x547D42AEA2879F19L,"9.999999999999974E98", "9.99999999999997E+98"), - ec(0x547D42AEA2879F1AL,"9.999999999999975E98", "9.99999999999998E+98"), - ec(0x547D42AEA2879F21L,"9.999999999999984E98", "9.99999999999998E+98"), - ec(0x547D42AEA2879F22L,"9.999999999999985E98", "9.99999999999999E+98"), - ec(0x547D42AEA2879F2AL,"9.999999999999995E98", "9.99999999999999E+98"), - ec(0x547D42AEA2879F2BL,"9.999999999999996E98", "1E+99"), - ec(0x547D42AEA287A0A0L,"1.0000000000000449E99", "1E+99"), - ec(0x547D42AEA287A0A1L,"1.000000000000045E99", "1.0000000000001E+99"), - ec(0x547D42AEA287A3D8L,"1.0000000000001449E99", "1.0000000000001E+99"), - ec(0x547D42AEA287A3D9L,"1.000000000000145E99", "1.0000000000002E+99"), - ec(0x547D42AEA287A710L,"1.000000000000245E99", "1.0000000000002E+99"), - ec(0x547D42AEA287A711L,"1.0000000000002451E99", "1.0000000000003E+99"), - - - ec(0x54B249AD2594C2F9L,"9.999999999999744E99", "9.9999999999997E+99"), - ec(0x54B249AD2594C2FAL,"9.999999999999746E99", "9.9999999999998E+99"), - ec(0x54B249AD2594C32DL,"9.999999999999845E99", "9.9999999999998E+99"), - ec(0x54B249AD2594C32EL,"9.999999999999847E99", "9.9999999999999E+99"), - ec(0x54B249AD2594C360L,"9.999999999999944E99", "9.9999999999999E+99"), - ec(0x54B249AD2594C361L,"9.999999999999946E99", "1E+100"), - ec(0x54B249AD2594C464L,"1.0000000000000449E100","1E+100"), - ec(0x54B249AD2594C465L,"1.000000000000045E100", "1.0000000000001E+100"), - ec(0x54B249AD2594C667L,"1.000000000000145E100", "1.0000000000001E+100"), - ec(0x54B249AD2594C668L,"1.0000000000001451E100","1.0000000000002E+100"), - ec(0x54B249AD2594C86AL,"1.000000000000245E100", "1.0000000000002E+100"), - ec(0x54B249AD2594C86BL,"1.0000000000002452E100","1.0000000000003E+100"), - - - ec(0x2B95DF5CA28EF4A8L,"1.0000000000000251E-98","1.00000000000003E-98"), - ec(0x2B95DF5CA28EF4A7L,"1.000000000000025E-98", "1.00000000000002E-98"), - ec(0x2B95DF5CA28EF46AL,"1.000000000000015E-98", "1.00000000000002E-98"), - ec(0x2B95DF5CA28EF469L,"1.0000000000000149E-98","1.00000000000001E-98"), - ec(0x2B95DF5CA28EF42DL,"1.0000000000000051E-98","1.00000000000001E-98"), - ec(0x2B95DF5CA28EF42CL,"1.000000000000005E-98", "1E-98"), - ec(0x2B95DF5CA28EF3ECL,"9.999999999999946E-99", "1E-98"), - ec(0x2B95DF5CA28EF3EBL,"9.999999999999944E-99", "9.9999999999999E-99"), - ec(0x2B95DF5CA28EF3AEL,"9.999999999999845E-99", "9.9999999999999E-99"), - ec(0x2B95DF5CA28EF3ADL,"9.999999999999843E-99", "9.9999999999998E-99"), - ec(0x2B95DF5CA28EF371L,"9.999999999999746E-99", "9.9999999999998E-99"), - ec(0x2B95DF5CA28EF370L,"9.999999999999744E-99", "9.9999999999997E-99"), - - - ec(0x2B617F7D4ED8C7F5L,"1.000000000000245E-99", "1.0000000000003E-99"), - ec(0x2B617F7D4ED8C7F4L,"1.0000000000002449E-99","1.0000000000002E-99"), - ec(0x2B617F7D4ED8C609L,"1.0000000000001452E-99","1.0000000000002E-99"), - ec(0x2B617F7D4ED8C608L,"1.000000000000145E-99", "1.0000000000001E-99"), - ec(0x2B617F7D4ED8C41CL,"1.000000000000045E-99", "1.0000000000001E-99"), - ec(0x2B617F7D4ED8C41BL,"1.0000000000000449E-99","1E-99"), - ec(0x2B617F7D4ED8C323L,"9.999999999999945E-100","1E-99"), - ec(0x2B617F7D4ED8C322L,"9.999999999999943E-100","9.9999999999999E-100"), - ec(0x2B617F7D4ED8C2F2L,"9.999999999999846E-100","9.9999999999999E-100"), - ec(0x2B617F7D4ED8C2F1L,"9.999999999999844E-100","9.9999999999998E-100"), - ec(0x2B617F7D4ED8C2C1L,"9.999999999999746E-100","9.9999999999998E-100"), - ec(0x2B617F7D4ED8C2C0L,"9.999999999999744E-100","9.9999999999997E-100"), - - - - // small numbers - ec(0x3EE9E409302678BAL, "1.2345678901234568E-5", "1.23456789012346E-05"), - ec(0x3F202E85BE180B74L, "1.2345678901234567E-4", "0.000123456789012346"), - ec(0x3F543A272D9E0E51L, "0.0012345678901234567", "0.00123456789012346"), - ec(0x3F8948B0F90591E6L, "0.012345678901234568", "0.0123456789012346"), - - ec(0x3EE9E409301B5A02L, "1.23456789E-5", "0.0000123456789"), - - ec(0x3E6E7D05BDABDE50L, "5.6789012345E-8", "0.000000056789012345"), - ec(0x3E6E7D05BDAD407EL, "5.67890123456E-8", "5.67890123456E-08"), - ec(0x3E6E7D06029F18BEL, "5.678902E-8", "0.00000005678902"), - - ec(0x2BCB5733CB32AE6EL, "9.999999999999123E-98", "9.99999999999912E-98"), - ec(0x2B617F7D4ED8C59EL, "1.0000000000001235E-99", "1.0000000000001E-99"), - ec(0x0036319916D67853L, "1.2345678901234578E-307", "1.2345678901235E-307"), - - ec(0x359DEE7A4AD4B81FL, "2.0E-50", "2E-50"), - - // large numbers - ec(0x41678C29DCD6E9E0L, "1.2345678901234567E7", "12345678.9012346"), - ec(0x42A674E79C5FE523L, "1.2345678901234568E13", "12345678901234.6"), - ec(0x42DC12218377DE6BL, "1.2345678901234567E14", "123456789012346"), - ec(0x43118B54F22AEB03L, "1.2345678901234568E15", "1234567890123460"), - ec(0x43E56A95319D63E1L, "1.2345678901234567E19", "12345678901234600000"), - ec(0x441AC53A7E04BCDAL, "1.2345678901234568E20", "1.23456789012346E+20"), - ec(0xC3E56A95319D63E1L, "-1.2345678901234567E19", "-12345678901234600000"), - ec(0xC41AC53A7E04BCDAL, "-1.2345678901234568E20", "-1.23456789012346E+20"), - - ec(0x54820FE0BA17F46DL, "1.2345678901234577E99", "1.2345678901235E+99"), - ec(0x54B693D8E89DF188L, "1.2345678901234576E100", "1.2345678901235E+100"), - - ec(0x4A611B0EC57E649AL, "2.0E50", "2E+50"), - - // range extremities - ec(0x7FEFFFFFFFFFFFFFL, "1.7976931348623157E308", "1.7976931348623E+308"), - ec(0x0010000000000000L, "2.2250738585072014E-308", "2.2250738585072E-308"), - ec(0x000FFFFFFFFFFFFFL, "2.225073858507201E-308", "0"), - ec(0x0000000000000001L, "4.9E-324", "0"), - - // infinity - ec(0x7FF0000000000000L, "Infinity", "1.7976931348623E+308"), - ec(0xFFF0000000000000L, "-Infinity", "1.7976931348623E+308"), - - // shortening due to rounding - ec(0x441AC7A08EAD02F2L, "1.234999999999999E20", "1.235E+20"), - ec(0x40FE26BFFFFFFFF9L, "123499.9999999999", "123500"), - ec(0x3E4A857BFB2F2809L, "1.234999999999999E-8", "0.00000001235"), - ec(0x3BCD291DEF868C89L, "1.234999999999999E-20", "1.235E-20"), - - // carry up due to rounding - // For clarity these tests choose values that don't round in java, - // but will round in excel. In some cases there is almost no difference - // between excel and java (e.g. 9.9..9E-8) - ec(0x444B1AE4D6E2EF4FL, "9.999999999999999E20", "1E+21"), - ec(0x412E847FFFFFFFFFL, "999999.9999999999", "1000000"), - ec(0x3E45798EE2308C39L, "9.999999999999999E-9", "0.00000001"), - ec(0x3C32725DD1D243ABL, "9.999999999999999E-19", "0.000000000000000001"), - ec(0x3BFD83C94FB6D2ABL, "9.999999999999999E-20", "1E-19"), - - ec(0xC44B1AE4D6E2EF4FL, "-9.999999999999999E20", "-1E+21"), - ec(0xC12E847FFFFFFFFFL, "-999999.9999999999", "-1000000"), - ec(0xBE45798EE2308C39L, "-9.999999999999999E-9", "-0.00000001"), - ec(0xBC32725DD1D243ABL, "-9.999999999999999E-19", "-0.000000000000000001"), - ec(0xBBFD83C94FB6D2ABL, "-9.999999999999999E-20", "-1E-19"), - - - // NaNs - // Currently these test cases are not critical, since other limitations prevent any variety in - // or control of the bit patterns used to encode NaNs in evaluations. - ec(0xFFFF0420003C0000L, "NaN", "3.484840871308E+308"), - ec(0x7FF8000000000000L, "NaN", "2.6965397022935E+308"), - ec(0x7FFF0420003C0000L, "NaN", "3.484840871308E+308"), - ec(0xFFF8000000000000L, "NaN", "2.6965397022935E+308"), - ec(0xFFFF0AAAAAAAAAAAL, "NaN", "3.4877119413344E+308"), - ec(0x7FF80AAAAAAAAAAAL, "NaN", "2.7012211948322E+308"), - ec(0xFFFFFFFFFFFFFFFFL, "NaN", "3.5953862697246E+308"), - ec(0x7FFFFFFFFFFFFFFFL, "NaN", "3.5953862697246E+308"), - ec(0xFFF7FFFFFFFFFFFFL, "NaN", "2.6965397022935E+308"), - }; - - private static ExampleConversion ec(long rawDoubleBits, String javaRendering, String excelRendering) { - return new ExampleConversion(rawDoubleBits, javaRendering, excelRendering); - } - - public static ExampleConversion[] getExampleConversions() { - return examples.clone(); - } -} diff --git a/src/testcases/org/apache/poi/ss/util/TestAreaReference.java b/src/testcases/org/apache/poi/ss/util/TestAreaReference.java deleted file mode 100644 index de2226d6a..000000000 --- a/src/testcases/org/apache/poi/ss/util/TestAreaReference.java +++ /dev/null @@ -1,71 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.util; - -import org.apache.poi.ss.SpreadsheetVersion; - -import junit.framework.TestCase; - -/** - * Test for {@link AreaReference} handling of max rows. - * - * @author David North - */ -public class TestAreaReference extends TestCase { - - public void testWholeColumn() { - AreaReference oldStyle = AreaReference.getWholeColumn(SpreadsheetVersion.EXCEL97, "A", "B"); - assertEquals(0, oldStyle.getFirstCell().getCol()); - assertEquals(0, oldStyle.getFirstCell().getRow()); - assertEquals(1, oldStyle.getLastCell().getCol()); - assertEquals(SpreadsheetVersion.EXCEL97.getLastRowIndex(), oldStyle.getLastCell().getRow()); - assertTrue(oldStyle.isWholeColumnReference()); - - AreaReference oldStyleNonWholeColumn = new AreaReference("A1:B23", SpreadsheetVersion.EXCEL97); - assertFalse(oldStyleNonWholeColumn.isWholeColumnReference()); - - AreaReference newStyle = AreaReference.getWholeColumn(SpreadsheetVersion.EXCEL2007, "A", "B"); - assertEquals(0, newStyle.getFirstCell().getCol()); - assertEquals(0, newStyle.getFirstCell().getRow()); - assertEquals(1, newStyle.getLastCell().getCol()); - assertEquals(SpreadsheetVersion.EXCEL2007.getLastRowIndex(), newStyle.getLastCell().getRow()); - assertTrue(newStyle.isWholeColumnReference()); - - AreaReference newStyleNonWholeColumn = new AreaReference("A1:B23", SpreadsheetVersion.EXCEL2007); - assertFalse(newStyleNonWholeColumn.isWholeColumnReference()); - } - - public void testWholeRow() { - AreaReference oldStyle = AreaReference.getWholeRow(SpreadsheetVersion.EXCEL97, "1", "2"); - assertEquals(0, oldStyle.getFirstCell().getCol()); - assertEquals(0, oldStyle.getFirstCell().getRow()); - assertEquals(SpreadsheetVersion.EXCEL97.getLastColumnIndex(), oldStyle.getLastCell().getCol()); - assertEquals(1, oldStyle.getLastCell().getRow()); - - AreaReference newStyle = AreaReference.getWholeRow(SpreadsheetVersion.EXCEL2007, "1", "2"); - assertEquals(0, newStyle.getFirstCell().getCol()); - assertEquals(0, newStyle.getFirstCell().getRow()); - assertEquals(SpreadsheetVersion.EXCEL2007.getLastColumnIndex(), newStyle.getLastCell().getCol()); - assertEquals(1, newStyle.getLastCell().getRow()); - } - - @SuppressWarnings("deprecation") // deliberate test for behaviour if deprecated constructor used. - public void testFallbackToExcel97IfVersionNotSupplied() { - assertTrue(new AreaReference("A:B").isWholeColumnReference()); - assertTrue(AreaReference.isWholeColumnReference(null, new CellReference("A$1"), new CellReference("A$" + SpreadsheetVersion.EXCEL97.getMaxRows()))); - } -} diff --git a/src/testcases/org/apache/poi/ss/util/TestCellAddress.java b/src/testcases/org/apache/poi/ss/util/TestCellAddress.java deleted file mode 100644 index 6ca6f65be..000000000 --- a/src/testcases/org/apache/poi/ss/util/TestCellAddress.java +++ /dev/null @@ -1,110 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.util; - -import org.apache.poi.ss.util.CellAddress; - -import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assume.assumeTrue; - -import java.util.Arrays; - -/** - * Tests that the common CellAddress works as we need it to. - * Note - some additional testing is also done in the HSSF class, - * {@link org.apache.poi.hssf.util.TestCellAddress} - */ -public final class TestCellAddress { - @Test - public void testConstructors() { - CellAddress cellAddress; - final CellReference cellRef = new CellReference("Sheet1", 0, 0, true, true); - final String address = "A1"; - final int row = 0; - final int col = 0; - - cellAddress = new CellAddress(row, col); - assertEquals(CellAddress.A1, cellAddress); - - cellAddress = new CellAddress(address); - assertEquals(CellAddress.A1, cellAddress); - - cellAddress = new CellAddress(cellRef); - assertEquals(CellAddress.A1, cellAddress); - } - - @Test - public void testFormatAsString() { - assertEquals("A1", CellAddress.A1.formatAsString()); - } - - @Test - public void testEquals() { - assertEquals(new CellReference(6, 4), new CellReference(6, 4)); - assertNotEquals(new CellReference(4, 6), new CellReference(6, 4)); - } - - @Test - public void testCompareTo() { - final CellAddress A1 = new CellAddress(0, 0); - final CellAddress A2 = new CellAddress(1, 0); - final CellAddress B1 = new CellAddress(0, 1); - final CellAddress B2 = new CellAddress(1, 1); - - assertEquals(0, A1.compareTo(A1)); - assertEquals(-1, A1.compareTo(B1)); - assertEquals(-1, A1.compareTo(A2)); - assertEquals(-1, A1.compareTo(B2)); - - assertEquals(1, B1.compareTo(A1)); - assertEquals(0, B1.compareTo(B1)); - assertEquals(-1, B1.compareTo(A2)); - assertEquals(-1, B1.compareTo(B2)); - - assertEquals(1, A2.compareTo(A1)); - assertEquals(1, A2.compareTo(B1)); - assertEquals(0, A2.compareTo(A2)); - assertEquals(-1, A2.compareTo(B2)); - - assertEquals(1, B2.compareTo(A1)); - assertEquals(1, B2.compareTo(B1)); - assertEquals(1, B2.compareTo(A2)); - assertEquals(0, B2.compareTo(B2)); - - CellAddress[] sorted = {A1, B1, A2, B2}; - CellAddress[] unsorted = {B1, B2, A1, A2}; - assumeTrue(!sorted.equals(unsorted)); - Arrays.sort(unsorted); - assertArrayEquals(sorted, unsorted); - } - - @Test - public void testGetRow() { - final CellAddress addr = new CellAddress(6, 4); - assertEquals(6, addr.getRow()); - } - - @Test - public void testGetColumn() { - final CellAddress addr = new CellAddress(6, 4); - assertEquals(4, addr.getColumn()); - } -} diff --git a/src/testcases/org/apache/poi/ss/util/TestCellRangeAddress.java b/src/testcases/org/apache/poi/ss/util/TestCellRangeAddress.java deleted file mode 100644 index 3f0f44145..000000000 --- a/src/testcases/org/apache/poi/ss/util/TestCellRangeAddress.java +++ /dev/null @@ -1,283 +0,0 @@ -/* ==================================================================== -Licensed to the Apache Software Foundation (ASF) under one or more -contributor license agreements. See the NOTICE file distributed with -this work for additional information regarding copyright ownership. -The ASF licenses this file to You under the Apache License, Version 2.0 -(the "License"); you may not use this file except in compliance with -the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.util; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.apache.poi.util.LittleEndianOutputStream; - -import org.junit.Test; - -public final class TestCellRangeAddress { - static final byte[] data = new byte[] { - 0x02, 0x00, 0x04, 0x00, - 0x00, 0x00, 0x03, 0x00, - }; - - @Test - public void testLoad() { - CellRangeAddress ref = new CellRangeAddress( - TestcaseRecordInputStream.create(0x000, data)); - assertEquals(2, ref.getFirstRow()); - assertEquals(4, ref.getLastRow()); - assertEquals(0, ref.getFirstColumn()); - assertEquals(3, ref.getLastColumn()); - - assertEquals(8, CellRangeAddress.ENCODED_SIZE); - } - - @Test - public void testLoadInvalid() { - try { - assertNotNull(new CellRangeAddress( - TestcaseRecordInputStream.create(0x000, new byte[] { (byte)0x02 }))); - } catch (RuntimeException e) { - assertTrue("Had: " + e, e.getMessage().contains("Ran out of data")); - } - } - - @Test - public void testStore() throws IOException { - CellRangeAddress ref = new CellRangeAddress(0, 0, 0, 0); - - byte[] recordBytes; - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - LittleEndianOutputStream out = new LittleEndianOutputStream(baos); - try { - // With nothing set - ref.serialize(out); - recordBytes = baos.toByteArray(); - assertEquals(recordBytes.length, data.length); - for (int i = 0; i < data.length; i++) { - assertEquals("At offset " + i, 0, recordBytes[i]); - } - - // Now set the flags - ref.setFirstRow((short) 2); - ref.setLastRow((short) 4); - ref.setFirstColumn((short) 0); - ref.setLastColumn((short) 3); - - // Re-test - baos.reset(); - ref.serialize(out); - recordBytes = baos.toByteArray(); - - assertEquals(recordBytes.length, data.length); - for (int i = 0; i < data.length; i++) { - assertEquals("At offset " + i, data[i], recordBytes[i]); - } - } finally { - out.close(); - } - } - - @Test - public void testCreateIllegal() throws IOException { - // for some combinations we expected exceptions - try { - assertNotNull(new CellRangeAddress(1, 0, 0, 0)); - fail("Expect to catch an exception"); - } catch (IllegalArgumentException e) { - // expected here - } - try { - assertNotNull(new CellRangeAddress(0, 0, 1, 0)); - fail("Expect to catch an exception"); - } catch (IllegalArgumentException e) { - // expected here - } - } - - @Test - public void testCopy() throws IOException { - CellRangeAddress ref = new CellRangeAddress(1, 2, 3, 4); - CellRangeAddress copy = ref.copy(); - assertEquals(ref.toString(), copy.toString()); - } - - @Test - public void testGetEncodedSize() throws IOException { - assertEquals(2*CellRangeAddress.ENCODED_SIZE, CellRangeAddress.getEncodedSize(2)); - } - - @Test - public void testFormatAsString() throws IOException { - CellRangeAddress ref = new CellRangeAddress(1, 2, 3, 4); - - assertEquals("D2:E3", ref.formatAsString()); - assertEquals("D2:E3", CellRangeAddress.valueOf(ref.formatAsString()).formatAsString()); - - assertEquals("sheet1!$D$2:$E$3", ref.formatAsString("sheet1", true)); - assertEquals("sheet1!$D$2:$E$3", CellRangeAddress.valueOf(ref.formatAsString()).formatAsString("sheet1", true)); - assertEquals("sheet1!$D$2:$E$3", CellRangeAddress.valueOf(ref.formatAsString("sheet1", true)).formatAsString("sheet1", true)); - - assertEquals("sheet1!D2:E3", ref.formatAsString("sheet1", false)); - assertEquals("sheet1!D2:E3", CellRangeAddress.valueOf(ref.formatAsString()).formatAsString("sheet1", false)); - assertEquals("sheet1!D2:E3", CellRangeAddress.valueOf(ref.formatAsString("sheet1", false)).formatAsString("sheet1", false)); - - assertEquals("D2:E3", ref.formatAsString(null, false)); - assertEquals("D2:E3", CellRangeAddress.valueOf(ref.formatAsString()).formatAsString(null, false)); - assertEquals("D2:E3", CellRangeAddress.valueOf(ref.formatAsString(null, false)).formatAsString(null, false)); - - assertEquals("$D$2:$E$3", ref.formatAsString(null, true)); - assertEquals("$D$2:$E$3", CellRangeAddress.valueOf(ref.formatAsString()).formatAsString(null, true)); - assertEquals("$D$2:$E$3", CellRangeAddress.valueOf(ref.formatAsString(null, true)).formatAsString(null, true)); - - ref = new CellRangeAddress(-1, -1, 3, 4); - assertEquals("D:E", ref.formatAsString()); - assertEquals("sheet1!$D:$E", CellRangeAddress.valueOf(ref.formatAsString()).formatAsString("sheet1", true)); - assertEquals("sheet1!$D:$E", CellRangeAddress.valueOf(ref.formatAsString("sheet1", true)).formatAsString("sheet1", true)); - assertEquals("$D:$E", CellRangeAddress.valueOf(ref.formatAsString()).formatAsString(null, true)); - assertEquals("$D:$E", CellRangeAddress.valueOf(ref.formatAsString(null, true)).formatAsString(null, true)); - assertEquals("sheet1!D:E", CellRangeAddress.valueOf(ref.formatAsString()).formatAsString("sheet1", false)); - assertEquals("sheet1!D:E", CellRangeAddress.valueOf(ref.formatAsString("sheet1", false)).formatAsString("sheet1", false)); - - ref = new CellRangeAddress(1, 2, -1, -1); - assertEquals("2:3", ref.formatAsString()); - assertEquals("sheet1!$2:$3", CellRangeAddress.valueOf(ref.formatAsString()).formatAsString("sheet1", true)); - assertEquals("sheet1!$2:$3", CellRangeAddress.valueOf(ref.formatAsString("sheet1", true)).formatAsString("sheet1", true)); - assertEquals("$2:$3", CellRangeAddress.valueOf(ref.formatAsString()).formatAsString(null, true)); - assertEquals("$2:$3", CellRangeAddress.valueOf(ref.formatAsString(null, true)).formatAsString(null, true)); - assertEquals("sheet1!2:3", CellRangeAddress.valueOf(ref.formatAsString()).formatAsString("sheet1", false)); - assertEquals("sheet1!2:3", CellRangeAddress.valueOf(ref.formatAsString("sheet1", false)).formatAsString("sheet1", false)); - - ref = new CellRangeAddress(1, 1, 2, 2); - assertEquals("C2", ref.formatAsString()); - assertEquals("sheet1!$C$2", CellRangeAddress.valueOf(ref.formatAsString()).formatAsString("sheet1", true)); - assertEquals("sheet1!$C$2", CellRangeAddress.valueOf(ref.formatAsString("sheet1", true)).formatAsString("sheet1", true)); - assertEquals("$C$2", CellRangeAddress.valueOf(ref.formatAsString()).formatAsString(null, true)); - assertEquals("$C$2", CellRangeAddress.valueOf(ref.formatAsString(null, true)).formatAsString(null, true)); - assertEquals("sheet1!C2", CellRangeAddress.valueOf(ref.formatAsString()).formatAsString("sheet1", false)); - assertEquals("sheet1!C2", CellRangeAddress.valueOf(ref.formatAsString("sheet1", false)).formatAsString("sheet1", false)); - - // is this a valid address? - ref = new CellRangeAddress(-1, -1, -1, -1); - assertEquals(":", ref.formatAsString()); - } - - @Test - public void testEquals() { - final CellRangeAddress ref1 = new CellRangeAddress(1, 2, 3, 4); - final CellRangeAddress ref2 = new CellRangeAddress(1, 2, 3, 4); - assertEquals(ref1, ref2); - - // Invert first/last row, but refer to same area - ref2.setFirstRow(2); - ref2.setLastRow(1); - assertEquals(ref1, ref2); - - // Invert first/last column, but refer to same area - ref2.setFirstColumn(4); - ref2.setLastColumn(3); - assertEquals(ref1, ref2); - - // Refer to a different area - assertNotEquals(ref1, new CellRangeAddress(3, 4, 1, 2)); - } - - @Test - public void testGetMinMaxRow() { - final CellRangeAddress ref = new CellRangeAddress(1, 2, 3, 4); - assertEquals(1, ref.getMinRow()); - assertEquals(2, ref.getMaxRow()); - - ref.setFirstRow(10); - //now ref is CellRangeAddress(10, 2, 3, 4) - assertEquals(2, ref.getMinRow()); - assertEquals(10, ref.getMaxRow()); - } - - @Test - public void testGetMinMaxColumn() { - final CellRangeAddress ref = new CellRangeAddress(1, 2, 3, 4); - assertEquals(3, ref.getMinColumn()); - assertEquals(4, ref.getMaxColumn()); - - ref.setFirstColumn(10); - //now ref is CellRangeAddress(1, 2, 10, 4) - assertEquals(4, ref.getMinColumn()); - assertEquals(10, ref.getMaxColumn()); - } - - @Test - public void testIntersects() { - final CellRangeAddress baseRegion = new CellRangeAddress(0, 1, 0, 1); - - final CellRangeAddress duplicateRegion = new CellRangeAddress(0, 1, 0, 1); - assertIntersects(baseRegion, duplicateRegion); - - final CellRangeAddress partiallyOverlappingRegion = new CellRangeAddress(1, 2, 1, 2); - assertIntersects(baseRegion, partiallyOverlappingRegion); - - final CellRangeAddress subsetRegion = new CellRangeAddress(0, 1, 0, 0); - assertIntersects(baseRegion, subsetRegion); - - final CellRangeAddress supersetRegion = new CellRangeAddress(0, 2, 0, 2); - assertIntersects(baseRegion, supersetRegion); - - final CellRangeAddress disjointRegion = new CellRangeAddress(10, 11, 10, 11); - assertNotIntersects(baseRegion, disjointRegion); - } - - @Test - public void containsRow() { - final CellRangeAddress region = new CellRangeAddress(10, 12, 3, 5); - - assertFalse(region.containsRow(9)); - assertTrue(region.containsRow(10)); - assertTrue(region.containsRow(11)); - assertTrue(region.containsRow(12)); - assertFalse(region.containsRow(13)); - } - - @Test - public void containsColumn() { - final CellRangeAddress region = new CellRangeAddress(10, 12, 3, 5); - - assertFalse(region.containsColumn(2)); - assertTrue(region.containsColumn(3)); - assertTrue(region.containsColumn(4)); - assertTrue(region.containsColumn(5)); - assertFalse(region.containsColumn(6)); - } - - private static void assertIntersects(CellRangeAddress regionA, CellRangeAddress regionB) { - if (!(regionA.intersects(regionB) && regionB.intersects(regionA))) { - final String A = regionA.formatAsString(); - final String B = regionB.formatAsString(); - fail("expected: regions "+A+" and "+B+" intersect"); - } - } - private static void assertNotIntersects(CellRangeAddress regionA, CellRangeAddress regionB) { - if ((regionA.intersects(regionB) || regionB.intersects(regionA))) { - final String A = regionA.formatAsString(); - final String B = regionB.formatAsString(); - fail("expected: regions "+A+" and "+B+" do not intersect"); - } - } -} diff --git a/src/testcases/org/apache/poi/ss/util/TestCellReference.java b/src/testcases/org/apache/poi/ss/util/TestCellReference.java deleted file mode 100644 index d2f2e462a..000000000 --- a/src/testcases/org/apache/poi/ss/util/TestCellReference.java +++ /dev/null @@ -1,406 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.util; - -import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.ss.util.CellReference; - -import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -/** - * Tests that the common CellReference works as we need it to. - * Note - some additional testing is also done in the HSSF class, - * {@link org.apache.poi.hssf.util.TestCellReference} - */ -public final class TestCellReference { - @Test - public void testConstructors() { - CellReference cellReference; - final String sheet = "Sheet1"; - final String cellRef = "A1"; - final int row = 0; - final int col = 0; - final boolean absRow = true; - final boolean absCol = false; - - cellReference = new CellReference(row, col); - assertEquals("A1", cellReference.formatAsString()); - - cellReference = new CellReference(row, col, absRow, absCol); - assertEquals("A$1", cellReference.formatAsString()); - - cellReference = new CellReference(row, (short)col); - assertEquals("A1", cellReference.formatAsString()); - - cellReference = new CellReference(cellRef); - assertEquals("A1", cellReference.formatAsString()); - - cellReference = new CellReference(sheet, row, col, absRow, absCol); - assertEquals("Sheet1!A$1", cellReference.formatAsString()); - } - - @Test - public void testFormatAsString() { - CellReference cellReference; - - cellReference = new CellReference(null, 0, 0, false, false); - assertEquals("A1", cellReference.formatAsString()); - - //absolute references - cellReference = new CellReference(null, 0, 0, true, false); - assertEquals("A$1", cellReference.formatAsString()); - - //sheet name with no spaces - cellReference = new CellReference("Sheet1", 0, 0, true, false); - assertEquals("Sheet1!A$1", cellReference.formatAsString()); - - //sheet name with spaces - cellReference = new CellReference("Sheet 1", 0, 0, true, false); - assertEquals("'Sheet 1'!A$1", cellReference.formatAsString()); - } - - @Test - public void testGetCellRefParts() { - CellReference cellReference; - String[] parts; - - String cellRef = "A1"; - cellReference = new CellReference(cellRef); - assertEquals(0, cellReference.getCol()); - parts = cellReference.getCellRefParts(); - assertNotNull(parts); - assertEquals(null, parts[0]); - assertEquals("1", parts[1]); - assertEquals("A", parts[2]); - - cellRef = "AA1"; - cellReference = new CellReference(cellRef); - assertEquals(26, cellReference.getCol()); - parts = cellReference.getCellRefParts(); - assertNotNull(parts); - assertEquals(null, parts[0]); - assertEquals("1", parts[1]); - assertEquals("AA", parts[2]); - - cellRef = "AA100"; - cellReference = new CellReference(cellRef); - assertEquals(26, cellReference.getCol()); - parts = cellReference.getCellRefParts(); - assertNotNull(parts); - assertEquals(null, parts[0]); - assertEquals("100", parts[1]); - assertEquals("AA", parts[2]); - - cellRef = "AAA300"; - cellReference = new CellReference(cellRef); - assertEquals(702, cellReference.getCol()); - parts = cellReference.getCellRefParts(); - assertNotNull(parts); - assertEquals(null, parts[0]); - assertEquals("300", parts[1]); - assertEquals("AAA", parts[2]); - - cellRef = "ZZ100521"; - cellReference = new CellReference(cellRef); - assertEquals(26*26+25, cellReference.getCol()); - parts = cellReference.getCellRefParts(); - assertNotNull(parts); - assertEquals(null, parts[0]); - assertEquals("100521", parts[1]); - assertEquals("ZZ", parts[2]); - - cellRef = "ZYX987"; - cellReference = new CellReference(cellRef); - assertEquals(26*26*26 + 25*26 + 24 - 1, cellReference.getCol()); - parts = cellReference.getCellRefParts(); - assertNotNull(parts); - assertEquals(null, parts[0]); - assertEquals("987", parts[1]); - assertEquals("ZYX", parts[2]); - - cellRef = "AABC10065"; - cellReference = new CellReference(cellRef); - parts = cellReference.getCellRefParts(); - assertNotNull(parts); - assertEquals(null, parts[0]); - assertEquals("10065", parts[1]); - assertEquals("AABC", parts[2]); - } - - @Test - public void testGetColNumFromRef() { - String cellRef = "A1"; - CellReference cellReference = new CellReference(cellRef); - assertEquals(0, cellReference.getCol()); - - cellRef = "AA1"; - cellReference = new CellReference(cellRef); - assertEquals(26, cellReference.getCol()); - - cellRef = "AB1"; - cellReference = new CellReference(cellRef); - assertEquals(27, cellReference.getCol()); - - cellRef = "BA1"; - cellReference = new CellReference(cellRef); - assertEquals(26+26, cellReference.getCol()); - - cellRef = "CA1"; - cellReference = new CellReference(cellRef); - assertEquals(26+26+26, cellReference.getCol()); - - cellRef = "ZA1"; - cellReference = new CellReference(cellRef); - assertEquals(26*26, cellReference.getCol()); - - cellRef = "ZZ1"; - cellReference = new CellReference(cellRef); - assertEquals(26*26+25, cellReference.getCol()); - - cellRef = "AAA1"; - cellReference = new CellReference(cellRef); - assertEquals(26*26+26, cellReference.getCol()); - - - cellRef = "A1100"; - cellReference = new CellReference(cellRef); - assertEquals(0, cellReference.getCol()); - - cellRef = "BC15"; - cellReference = new CellReference(cellRef); - assertEquals(54, cellReference.getCol()); - } - - @Test - public void testGetRowNumFromRef() { - String cellRef = "A1"; - CellReference cellReference = new CellReference(cellRef); - assertEquals(0, cellReference.getRow()); - - cellRef = "A12"; - cellReference = new CellReference(cellRef); - assertEquals(11, cellReference.getRow()); - - cellRef = "AS121"; - cellReference = new CellReference(cellRef); - assertEquals(120, cellReference.getRow()); - } - - @Test - public void testConvertNumToColString() { - short col = 702; - String collRef = new CellReference(0, col).formatAsString(); - assertEquals("AAA1", collRef); - - short col2 = 0; - String collRef2 = new CellReference(0, col2).formatAsString(); - assertEquals("A1", collRef2); - - short col3 = 27; - String collRef3 = new CellReference(0, col3).formatAsString(); - assertEquals("AB1", collRef3); - - short col4 = 2080; - String collRef4 = new CellReference(0, col4).formatAsString(); - assertEquals("CBA1", collRef4); - } - - @Test - public void testBadRowNumber() { - SpreadsheetVersion v97 = SpreadsheetVersion.EXCEL97; - SpreadsheetVersion v2007 = SpreadsheetVersion.EXCEL2007; - - confirmCrInRange(true, "A", "1", v97); - confirmCrInRange(true, "IV", "65536", v97); - confirmCrInRange(false, "IV", "65537", v97); - confirmCrInRange(false, "IW", "65536", v97); - - confirmCrInRange(true, "A", "1", v2007); - confirmCrInRange(true, "XFD", "1048576", v2007); - confirmCrInRange(false, "XFD", "1048577", v2007); - confirmCrInRange(false, "XFE", "1048576", v2007); - - assertFalse("Identified bug 47312a", CellReference.cellReferenceIsWithinRange("B", "0", v97)); - - confirmCrInRange(false, "A", "0", v97); - confirmCrInRange(false, "A", "0", v2007); - } - - @Test - public void testInvalidReference() { - try { - new CellReference("Sheet1!#REF!"); - fail("Shouldn't be able to create a #REF! refence"); - } catch(IllegalArgumentException expected) {} - - try { - new CellReference("'MySheetName'!#REF!"); - fail("Shouldn't be able to create a #REF! refence"); - } catch(IllegalArgumentException expected) {} - - try { - new CellReference("#REF!"); - fail("Shouldn't be able to create a #REF! refence"); - } catch(IllegalArgumentException expected) {} - } - - private static void confirmCrInRange(boolean expResult, String colStr, String rowStr, - SpreadsheetVersion sv) { - if (expResult == CellReference.cellReferenceIsWithinRange(colStr, rowStr, sv)) { - return; - } - fail("expected (c='" + colStr + "', r='" + rowStr + "' to be " - + (expResult ? "within" : "out of") + " bounds for version " + sv.name()); - } - - @Test - public void testConvertColStringToIndex() { - assertEquals(0, CellReference.convertColStringToIndex("A")); - assertEquals(1, CellReference.convertColStringToIndex("B")); - assertEquals(14, CellReference.convertColStringToIndex("O")); - assertEquals(701, CellReference.convertColStringToIndex("ZZ")); - assertEquals(18252, CellReference.convertColStringToIndex("ZZA")); - - assertEquals(0, CellReference.convertColStringToIndex("$A")); - assertEquals(1, CellReference.convertColStringToIndex("$B")); - - try { - CellReference.convertColStringToIndex("A$"); - fail("Should throw exception here"); - } catch (IllegalArgumentException expected) { - assertTrue(expected.getMessage().contains("A$")); - } - } - - @Test - public void testConvertNumColColString() { - assertEquals("A", CellReference.convertNumToColString(0)); - assertEquals("AV", CellReference.convertNumToColString(47)); - assertEquals("AW", CellReference.convertNumToColString(48)); - assertEquals("BF", CellReference.convertNumToColString(57)); - - assertEquals("", CellReference.convertNumToColString(-1)); - assertEquals("", CellReference.convertNumToColString(Integer.MIN_VALUE)); - assertEquals("", CellReference.convertNumToColString(Integer.MAX_VALUE)); - assertEquals("FXSHRXW", CellReference.convertNumToColString(Integer.MAX_VALUE-1)); - } - - /** - * bug 59684: separateRefParts fails on entire-column references - */ - @Test - public void entireColumnReferences() { - CellReference ref = new CellReference("HOME!$169"); - assertEquals("HOME", ref.getSheetName()); - assertEquals(168, ref.getRow()); - assertEquals(-1, ref.getCol()); - assertTrue("row absolute", ref.isRowAbsolute()); - //assertFalse("column absolute/relative is undefined", ref.isColAbsolute()); - } - - @Test - public void getSheetName() { - assertEquals(null, new CellReference("A5").getSheetName()); - assertEquals(null, new CellReference(null, 0, 0, false, false).getSheetName()); - // FIXME: CellReference is inconsistent - assertEquals("", new CellReference("", 0, 0, false, false).getSheetName()); - assertEquals("Sheet1", new CellReference("Sheet1!A5").getSheetName()); - assertEquals("Sheet 1", new CellReference("'Sheet 1'!A5").getSheetName()); - } - - @Test - public void testToString() { - CellReference ref = new CellReference("'Sheet 1'!A5"); - assertEquals("org.apache.poi.ss.util.CellReference ['Sheet 1'!A5]", ref.toString()); - } - - @Test - public void testEqualsAndHashCode() { - CellReference ref1 = new CellReference("'Sheet 1'!A5"); - CellReference ref2 = new CellReference("Sheet 1", 4, 0, false, false); - assertEquals("equals", ref1, ref2); - assertEquals("hash code", ref1.hashCode(), ref2.hashCode()); - - assertFalse("null", ref1.equals(null)); - assertFalse("3D vs 2D", ref1.equals(new CellReference("A5"))); - assertFalse("type", ref1.equals(new Integer(0))); - } - - @Test - public void isRowWithinRange() { - SpreadsheetVersion ss = SpreadsheetVersion.EXCEL2007; - assertFalse("1 before first row", CellReference.isRowWithinRange("0", ss)); - assertTrue("first row", CellReference.isRowWithinRange("1", ss)); - assertTrue("last row", CellReference.isRowWithinRange("1048576", ss)); - assertFalse("1 beyond last row", CellReference.isRowWithinRange("1048577", ss)); - } - - @Test - public void isColWithinRange() { - SpreadsheetVersion ss = SpreadsheetVersion.EXCEL2007; - assertTrue("(empty)", CellReference.isColumnWithinRange("", ss)); - assertTrue("first column (A)", CellReference.isColumnWithinRange("A", ss)); - assertTrue("last column (XFD)", CellReference.isColumnWithinRange("XFD", ss)); - assertFalse("1 beyond last column (XFE)", CellReference.isColumnWithinRange("XFE", ss)); - } - - @Test(expected=IllegalArgumentException.class) - public void unquotedSheetName() { - new CellReference("'Sheet 1!A5"); - } - @Test(expected=IllegalArgumentException.class) - public void mismatchedQuotesSheetName() { - new CellReference("Sheet 1!A5"); - } - - @Test - public void escapedSheetName() { - String escapedName = "'Don''t Touch'!A5"; - String unescapedName = "'Don't Touch'!A5"; - new CellReference(escapedName); - try { - new CellReference(unescapedName); - fail("Sheet names containing apostrophe's must be escaped via a repeated apostrophe"); - } catch (IllegalArgumentException e) { - assertTrue(e.getMessage().startsWith("Bad sheet name quote escaping: ")); - } - } - - @Test(expected=IllegalArgumentException.class) - public void negativeRow() { - new CellReference("sheet", -2, 0, false, false); - } - @Test(expected=IllegalArgumentException.class) - public void negativeColumn() { - new CellReference("sheet", 0, -2, false, false); - } - - @Test(expected=IllegalArgumentException.class) - public void classifyEmptyStringCellReference() { - CellReference.classifyCellReference("", SpreadsheetVersion.EXCEL2007); - } - @Test(expected=IllegalArgumentException.class) - public void classifyInvalidFirstCharCellReference() { - CellReference.classifyCellReference("!A5", SpreadsheetVersion.EXCEL2007); - } -} diff --git a/src/testcases/org/apache/poi/ss/util/TestDateFormatConverter.java b/src/testcases/org/apache/poi/ss/util/TestDateFormatConverter.java deleted file mode 100644 index 2b6e6e312..000000000 --- a/src/testcases/org/apache/poi/ss/util/TestDateFormatConverter.java +++ /dev/null @@ -1,151 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.ss.util; - -import java.io.File; -import java.io.FileOutputStream; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Arrays; -import java.util.Date; -import java.util.Locale; - -import junit.framework.TestCase; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.DataFormat; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.util.TempFile; - -public final class TestDateFormatConverter extends TestCase { - private void outputLocaleDataFormats( Date date, boolean dates, boolean times, int style, String styleName ) throws Exception { - - Workbook workbook = new HSSFWorkbook(); - try { - String sheetName; - if( dates ) { - if( times ) { - sheetName = "DateTimes"; - } else { - sheetName = "Dates"; - } - } else { - sheetName = "Times"; - } - Sheet sheet = workbook.createSheet(sheetName); - Row header = sheet.createRow(0); - header.createCell(0).setCellValue("locale"); - header.createCell(1).setCellValue("DisplayName"); - header.createCell(2).setCellValue("Excel " + styleName); - header.createCell(3).setCellValue("java.text.DateFormat"); - header.createCell(4).setCellValue("Equals"); - header.createCell(5).setCellValue("Java pattern"); - header.createCell(6).setCellValue("Excel pattern"); - - int rowNum = 1; - for( Locale locale : DateFormat.getAvailableLocales() ) { - try { - Row row = sheet.createRow(rowNum++); - - row.createCell(0).setCellValue(locale.toString()); - row.createCell(1).setCellValue(locale.getDisplayName(Locale.ROOT)); - - DateFormat dateFormat; - if( dates ) { - if( times ) { - dateFormat = DateFormat.getDateTimeInstance(style, style, locale); - } else { - dateFormat = DateFormat.getDateInstance(style, locale); - } - } else { - dateFormat = DateFormat.getTimeInstance(style, locale); - } - - Cell cell = row.createCell(2); - - cell.setCellValue(date); - CellStyle cellStyle = row.getSheet().getWorkbook().createCellStyle(); - - String javaDateFormatPattern = ((SimpleDateFormat)dateFormat).toPattern(); - String excelFormatPattern = DateFormatConverter.convert(locale, javaDateFormatPattern); - - DataFormat poiFormat = row.getSheet().getWorkbook().createDataFormat(); - cellStyle.setDataFormat(poiFormat.getFormat(excelFormatPattern)); - row.createCell(3).setCellValue(dateFormat.format(date)); - - cell.setCellStyle(cellStyle); - - // the formula returns TRUE is the formatted date in column C equals to the string in column D - row.createCell(4).setCellFormula("TEXT(C"+rowNum+",G"+rowNum+")=D" + rowNum); - row.createCell(5).setCellValue(javaDateFormatPattern); - row.createCell(6).setCellValue(excelFormatPattern); - } catch (Exception e) { - throw new RuntimeException("Failed for locale: " + locale + ", having locales: " + - Arrays.toString(DateFormat.getAvailableLocales()), e); - } - } - - File outputFile = TempFile.createTempFile("Locale" + sheetName + styleName, ".xlsx"); - FileOutputStream outputStream = new FileOutputStream(outputFile); - try { - workbook.write(outputStream); - } finally { - outputStream.close(); - } - - System.out.println("Open " + outputFile.getAbsolutePath()+" in Excel"); - } finally { - workbook.close(); - } - } - - public void testJavaDateFormatsInExcel() throws Exception { - Date date = new Date(); - - outputLocaleDataFormats(date, true, false, DateFormat.DEFAULT, "Default" ); - outputLocaleDataFormats(date, true, false, DateFormat.SHORT, "Short" ); - outputLocaleDataFormats(date, true, false, DateFormat.MEDIUM, "Medium" ); - outputLocaleDataFormats(date, true, false, DateFormat.LONG, "Long" ); - outputLocaleDataFormats(date, true, false, DateFormat.FULL, "Full" ); - - outputLocaleDataFormats(date, true, true, DateFormat.DEFAULT, "Default" ); - outputLocaleDataFormats(date, true, true, DateFormat.SHORT, "Short" ); - outputLocaleDataFormats(date, true, true, DateFormat.MEDIUM, "Medium" ); - outputLocaleDataFormats(date, true, true, DateFormat.LONG, "Long" ); - outputLocaleDataFormats(date, true, true, DateFormat.FULL, "Full" ); - - outputLocaleDataFormats(date, false, true, DateFormat.DEFAULT, "Default" ); - outputLocaleDataFormats(date, false, true, DateFormat.SHORT, "Short" ); - outputLocaleDataFormats(date, false, true, DateFormat.MEDIUM, "Medium" ); - outputLocaleDataFormats(date, false, true, DateFormat.LONG, "Long" ); - outputLocaleDataFormats(date, false, true, DateFormat.FULL, "Full" ); - } - - public void testJDK8EmptyLocale() { - // JDK 8 seems to add an empty locale-string to the list returned via DateFormat.getAvailableLocales() - // therefore we now cater for this special locale as well - DateFormatConverter.getPrefixForLocale(new Locale("")); - } - -} diff --git a/src/testcases/org/apache/poi/ss/util/TestExpandedDouble.java b/src/testcases/org/apache/poi/ss/util/TestExpandedDouble.java deleted file mode 100644 index d4d63192d..000000000 --- a/src/testcases/org/apache/poi/ss/util/TestExpandedDouble.java +++ /dev/null @@ -1,230 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.util; - -import static org.junit.Assert.assertEquals; - -import java.math.BigDecimal; -import java.math.BigInteger; - -import org.apache.poi.util.HexDump; -import org.junit.Test; - -import junit.framework.AssertionFailedError; -/** - * Tests for {@link ExpandedDouble} - * - * @author Josh Micich - */ -public final class TestExpandedDouble { - private static final BigInteger BIG_POW_10 = BigInteger.valueOf(1000000000); - - @Test - public void testNegative() { - ExpandedDouble hd = new ExpandedDouble(0xC010000000000000L); - - if (hd.getBinaryExponent() == -2046) { - throw new AssertionFailedError("identified bug - sign bit not masked out of exponent"); - } - assertEquals(2, hd.getBinaryExponent()); - BigInteger frac = hd.getSignificand(); - assertEquals(64, frac.bitLength()); - assertEquals(1, frac.bitCount()); - } - - @Test - public void testSubnormal() { - ExpandedDouble hd = new ExpandedDouble(0x0000000000000001L); - - if (hd.getBinaryExponent() == -1023) { - throw new AssertionFailedError("identified bug - subnormal numbers not decoded properly"); - } - assertEquals(-1086, hd.getBinaryExponent()); - BigInteger frac = hd.getSignificand(); - assertEquals(64, frac.bitLength()); - assertEquals(1, frac.bitCount()); - } - - /** - * Tests specific values for conversion from {@link ExpandedDouble} to {@link NormalisedDecimal} and back - */ - @Test - public void testRoundTripShifting() { - long[] rawValues = { - 0x4010000000000004L, - 0x7010000000000004L, - 0x1010000000000004L, - 0x0010000000000001L, // near lowest normal number - 0x0010000000000000L, // lowest normal number - 0x000FFFFFFFFFFFFFL, // highest subnormal number - 0x0008000000000000L, // subnormal number - - 0xC010000000000004L, - 0xE230100010001004L, - 0x403CE0FFFFFFFFF2L, - 0x0000000000000001L, // smallest non-zero number (subnormal) - 0x6230100010000FFEL, - 0x6230100010000FFFL, - 0x6230100010001000L, - 0x403CE0FFFFFFFFF0L, // has single digit round trip error - 0x2B2BFFFF10001079L, - }; - boolean success = true; - for (int i = 0; i < rawValues.length; i++) { - success &= confirmRoundTrip(i, rawValues[i]); - } - if (!success) { - throw new AssertionFailedError("One or more test examples failed. See stderr."); - } - } - - public static boolean confirmRoundTrip(int i, long rawBitsA) { - double a = Double.longBitsToDouble(rawBitsA); - if (a == 0.0) { - // Can't represent 0.0 or -0.0 with NormalisedDecimal - return true; - } - ExpandedDouble ed1; - NormalisedDecimal nd2; - ExpandedDouble ed3; - try { - ed1 = new ExpandedDouble(rawBitsA); - nd2 = ed1.normaliseBaseTen(); - checkNormaliseBaseTenResult(ed1, nd2); - - ed3 = nd2.normaliseBaseTwo(); - } catch (RuntimeException e) { - System.err.println("example[" + i + "] (" - + formatDoubleAsHex(a) + ") exception:"); - e.printStackTrace(); - return false; - } - if (ed3.getBinaryExponent() != ed1.getBinaryExponent()) { - System.err.println("example[" + i + "] (" - + formatDoubleAsHex(a) + ") bin exp mismatch"); - return false; - } - BigInteger diff = ed3.getSignificand().subtract(ed1.getSignificand()).abs(); - if (diff.signum() == 0) { - return true; - } - // original quantity only has 53 bits of precision - // these quantities may have errors in the 64th bit, which hopefully don't make any difference - - if (diff.bitLength() < 2) { - // errors in the 64th bit happen from time to time - // this is well below the 53 bits of precision required - return true; - } - - // but bigger errors are a concern - System.out.println("example[" + i + "] (" - + formatDoubleAsHex(a) + ") frac mismatch: " + diff.toString()); - - for (int j=-2; j<3; j++) { - System.out.println((j<0?"":"+") + j + ": " + getNearby(ed1, j)); - } - for (int j=-2; j<3; j++) { - System.out.println((j<0?"":"+") + j + ": " + getNearby(nd2, j)); - } - - - return false; - } - - public static String getBaseDecimal(ExpandedDouble hd) { - int gg = 64 - hd.getBinaryExponent() - 1; - BigDecimal bd = new BigDecimal(hd.getSignificand()).divide(new BigDecimal(BigInteger.ONE.shiftLeft(gg))); - int excessPrecision = bd.precision() - 23; - if (excessPrecision > 0) { - bd = bd.setScale(bd.scale() - excessPrecision, BigDecimal.ROUND_HALF_UP); - } - return bd.unscaledValue().toString(); - } - - public static BigInteger getNearby(NormalisedDecimal md, int offset) { - BigInteger frac = md.composeFrac(); - int be = frac.bitLength() - 24 - 1; - int sc = frac.bitLength() - 64; - return getNearby(frac.shiftRight(sc), be, offset); - } - - public static BigInteger getNearby(ExpandedDouble hd, int offset) { - return getNearby(hd.getSignificand(), hd.getBinaryExponent(), offset); - } - - private static BigInteger getNearby(BigInteger significand, int binExp, int offset) { - int nExtraBits = 1; - int nDec = (int) Math.round(3.0 + (64+nExtraBits) * Math.log10(2.0)); - BigInteger newFrac = significand.shiftLeft(nExtraBits).add(BigInteger.valueOf(offset)); - - int gg = 64 + nExtraBits - binExp - 1; - - BigDecimal bd = new BigDecimal(newFrac); - if (gg > 0) { - bd = bd.divide(new BigDecimal(BigInteger.ONE.shiftLeft(gg))); - } else { - BigInteger frac = newFrac; - while (frac.bitLength() + binExp < 180) { - frac = frac.multiply(BigInteger.TEN); - } - int binaryExp = binExp - newFrac.bitLength() + frac.bitLength(); - - bd = new BigDecimal( frac.shiftRight(frac.bitLength()-binaryExp-1)); - } - int excessPrecision = bd.precision() - nDec; - if (excessPrecision > 0) { - bd = bd.setScale(bd.scale() - excessPrecision, BigDecimal.ROUND_HALF_UP); - } - return bd.unscaledValue(); - } - - private static void checkNormaliseBaseTenResult(ExpandedDouble orig, NormalisedDecimal result) { - String sigDigs = result.getSignificantDecimalDigits(); - BigInteger frac = orig.getSignificand(); - while (frac.bitLength() + orig.getBinaryExponent() < 200) { - frac = frac.multiply(BIG_POW_10); - } - int binaryExp = orig.getBinaryExponent() - orig.getSignificand().bitLength(); - - String origDigs = frac.shiftLeft(binaryExp+1).toString(10); - - if (!origDigs.startsWith(sigDigs)) { - throw new AssertionFailedError("Expected '" + origDigs + "' but got '" + sigDigs + "'."); - } - - double dO = Double.parseDouble("0." + origDigs.substring(sigDigs.length())); - double d1 = Double.parseDouble(result.getFractionalPart().toPlainString()); - BigInteger subDigsO = BigInteger.valueOf((int) (dO * 32768 + 0.5)); - BigInteger subDigsB = BigInteger.valueOf((int) (d1 * 32768 + 0.5)); - - if (subDigsO.equals(subDigsB)) { - return; - } - BigInteger diff = subDigsB.subtract(subDigsO).abs(); - if (diff.intValue() > 100) { - // 100/32768 ~= 0.003 - throw new AssertionFailedError("minor mistake"); - } - } - - private static String formatDoubleAsHex(double d) { - long l = Double.doubleToLongBits(d); - return HexDump.longToHex(l)+'L'; - } -} diff --git a/src/testcases/org/apache/poi/ss/util/TestHSSFCellUtil.java b/src/testcases/org/apache/poi/ss/util/TestHSSFCellUtil.java deleted file mode 100644 index 848d32a11..000000000 --- a/src/testcases/org/apache/poi/ss/util/TestHSSFCellUtil.java +++ /dev/null @@ -1,26 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - ==================================================================== */ - -package org.apache.poi.ss.util; - -import org.apache.poi.hssf.HSSFITestDataProvider; - -public class TestHSSFCellUtil extends BaseTestCellUtil { - public TestHSSFCellUtil() { - super(HSSFITestDataProvider.instance); - } -} \ No newline at end of file diff --git a/src/testcases/org/apache/poi/ss/util/TestNumberComparer.java b/src/testcases/org/apache/poi/ss/util/TestNumberComparer.java deleted file mode 100644 index 506df6749..000000000 --- a/src/testcases/org/apache/poi/ss/util/TestNumberComparer.java +++ /dev/null @@ -1,107 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.util; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import org.apache.poi.ss.util.NumberComparisonExamples.ComparisonExample; -import org.apache.poi.util.HexDump; -import org.junit.Test; -/** - * Tests for {@link NumberComparer} - * - * @author Josh Micich - */ -public final class TestNumberComparer { - - @Test - public void testAllComparisonExamples() { - ComparisonExample[] examples = NumberComparisonExamples.getComparisonExamples(); - boolean success = true; - - for(int i=0;i 0 ? +1 : 0; - if (sgnActRes != expRes) { - System.err.println("Mismatch example[" + i + "] (" - + formatDoubleAsHex(a) + ", " + formatDoubleAsHex(b) + ") expected " - + expRes + " but got " + sgnActRes); - return false; - } - return true; - } - private static String formatDoubleAsHex(double d) { - long l = Double.doubleToLongBits(d); - return HexDump.longToHex(l)+'L'; - } -} diff --git a/src/testcases/org/apache/poi/ss/util/TestNumberToTextConverter.java b/src/testcases/org/apache/poi/ss/util/TestNumberToTextConverter.java deleted file mode 100644 index f33ece477..000000000 --- a/src/testcases/org/apache/poi/ss/util/TestNumberToTextConverter.java +++ /dev/null @@ -1,128 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.util; - -import junit.framework.AssertionFailedError; -import junit.framework.ComparisonFailure; -import junit.framework.TestCase; - -import java.util.Locale; - -import org.apache.poi.hssf.record.FormulaRecord; -import org.apache.poi.ss.formula.constant.ConstantValueParser; -import org.apache.poi.ss.formula.ptg.NumberPtg; -import org.apache.poi.ss.util.NumberToTextConversionExamples.ExampleConversion; -/** - * Tests for {@link NumberToTextConverter} - * - * @author Josh Micich - */ -public final class TestNumberToTextConverter extends TestCase { - - - /** - * Confirms that ExcelNumberToTextConverter.toText(d) produces the right results. - * As part of preparing this test class, the ExampleConversion instances should be set - * up to contain the rendering as produced by Excel. - */ - public void testAll() { - int failureCount = 0; - - ExampleConversion[] examples = NumberToTextConversionExamples.getExampleConversions(); - - for (int i = 0; i < examples.length; i++) { - ExampleConversion example = examples[i]; - try { - if (example.isNaN()) { - confirmNaN(example.getRawDoubleBits(), example.getExcelRendering()); - continue; - } - String actual = NumberToTextConverter.toText(example.getDoubleValue()); - if (!example.getExcelRendering().equals(actual)) { - failureCount++; - String msg = "Error rendering for examples[" + i + "] " - + formatExample(example) + " " - + " bad-result='" + actual + "' " - + new ComparisonFailure(null, example.getExcelRendering(), actual).getMessage(); - System.err.println(msg); - continue; - } - } catch (RuntimeException e) { - failureCount++; - System.err.println("Error in excel rendering for examples[" + i + "] " - + formatExample(example) + "':" + e.getMessage()); - e.printStackTrace(); - } - } - if (failureCount > 0) { - throw new AssertionFailedError(failureCount - + " error(s) in excel number to text conversion (see std-err)"); - } - } - - private static String formatExample(ExampleConversion example) { - String hexLong = Long.toHexString(example.getRawDoubleBits()).toUpperCase(Locale.ROOT); - String longRep = "0x" + "0000000000000000".substring(hexLong.length()) + hexLong+ "L"; - return "ec(" + longRep + ", \"" + example.getJavaRendering() + "\", \"" + example.getExcelRendering() + "\")"; - } - - /** - * Excel's abnormal rendering of NaNs is both difficult to test and even reproduce in java. In - * general, Excel does not attempt to use raw NaN in the IEEE sense. In {@link FormulaRecord}s, - * Excel uses the NaN bit pattern to flag non-numeric (text, boolean, error) cached results. - * If the formula result actually evaluates to raw NaN, Excel transforms it to #NUM!. - * In other places (e.g. {@link NumberRecord}, {@link NumberPtg}, array items (via {@link - * ConstantValueParser}), there seems to be no special NaN translation scheme. If a NaN bit - * pattern is somehow encoded into any of these places Excel actually attempts to render the - * values as a plain number. That is the unusual functionality that this method is testing.

    - * - * There are multiple encodings (bit patterns) for NaN, and CPUs and applications can convert - * to a preferred NaN encoding (Java prefers 0x7FF8000000000000L). Besides the - * special encoding in {@link FormulaRecord.SpecialCachedValue}, it is not known how/whether - * Excel attempts to encode NaN values. - * - * Observed NaN behaviour on HotSpot/Windows: - * Double.longBitsToDouble() will set one bit 51 (the NaN signaling flag) if it isn't - * already. Double.doubleToLongBits() will return a double with bit pattern - * 0x7FF8000000000000L for any NaN bit pattern supplied.
    - * Differences are likely to be observed with other architectures.

    - * - *

    - * The few test case examples calling this method represent functionality which may not be - * important for POI to support. - */ - private void confirmNaN(long l, String excelRep) { - double d = Double.longBitsToDouble(l); - assertEquals("NaN", Double.toString(d)); - - String strExcel = NumberToTextConverter.rawDoubleBitsToText(l); - - assertEquals(excelRep, strExcel); - } - - public void testSimpleRendering_bug56156() { - double dResult = 0.05+0.01; // values chosen to produce rounding anomaly - String actualText = NumberToTextConverter.toText(dResult); - String jdkText = Double.toString(dResult); - if (jdkText.equals(actualText)) { - // "0.060000000000000005" - throw new AssertionFailedError("Should not use default JDK IEEE double rendering"); - } - assertEquals("0.06", actualText); - } -} diff --git a/src/testcases/org/apache/poi/ss/util/TestPropertyTemplate.java b/src/testcases/org/apache/poi/ss/util/TestPropertyTemplate.java deleted file mode 100644 index 6325c6568..000000000 --- a/src/testcases/org/apache/poi/ss/util/TestPropertyTemplate.java +++ /dev/null @@ -1,949 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.util; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotSame; - -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.BorderExtent; -import org.apache.poi.ss.usermodel.BorderStyle; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.IndexedColors; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.junit.Test; - -/** - * Tests Spreadsheet PropertyTemplate - * - * @see org.apache.poi.ss.util.PropertyTemplate - */ -public final class TestPropertyTemplate { - @Test - public void getNumBorders() throws IOException { - CellRangeAddress a1 = new CellRangeAddress(0, 0, 0, 0); - PropertyTemplate pt = new PropertyTemplate(); - pt.drawBorders(a1, BorderStyle.THIN, BorderExtent.TOP); - assertEquals(1, pt.getNumBorders(0, 0)); - pt.drawBorders(a1, BorderStyle.MEDIUM, BorderExtent.BOTTOM); - assertEquals(2, pt.getNumBorders(0, 0)); - pt.drawBorders(a1, BorderStyle.MEDIUM, BorderExtent.NONE); - assertEquals(0, pt.getNumBorders(0, 0)); - } - - @Test - public void getNumBorderColors() throws IOException { - CellRangeAddress a1 = new CellRangeAddress(0, 0, 0, 0); - PropertyTemplate pt = new PropertyTemplate(); - pt.drawBorderColors(a1, IndexedColors.RED.getIndex(), BorderExtent.TOP); - assertEquals(1, pt.getNumBorderColors(0, 0)); - pt.drawBorderColors(a1, IndexedColors.RED.getIndex(), BorderExtent.BOTTOM); - assertEquals(2, pt.getNumBorderColors(0, 0)); - pt.drawBorderColors(a1, IndexedColors.RED.getIndex(), BorderExtent.NONE); - assertEquals(0, pt.getNumBorderColors(0, 0)); - } - - @Test - public void getTemplateProperties() throws IOException { - CellRangeAddress a1 = new CellRangeAddress(0, 0, 0, 0); - PropertyTemplate pt = new PropertyTemplate(); - pt.drawBorders(a1, BorderStyle.THIN, BorderExtent.TOP); - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(0, 0, CellUtil.BORDER_TOP)); - pt.drawBorders(a1, BorderStyle.MEDIUM, BorderExtent.BOTTOM); - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(0, 0, CellUtil.BORDER_BOTTOM)); - pt.drawBorderColors(a1, IndexedColors.RED.getIndex(), BorderExtent.TOP); - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(0, 0, CellUtil.TOP_BORDER_COLOR)); - pt.drawBorderColors(a1, IndexedColors.BLUE.getIndex(), BorderExtent.BOTTOM); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(0, 0, CellUtil.BOTTOM_BORDER_COLOR)); - } - - @Test - public void drawBorders() throws IOException { - CellRangeAddress a1c3 = new CellRangeAddress(0, 2, 0, 2); - PropertyTemplate pt = new PropertyTemplate(); - pt.drawBorders(a1c3, BorderStyle.THIN, - BorderExtent.ALL); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - assertEquals(4, pt.getNumBorders(i, j)); - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, CellUtil.BORDER_TOP)); - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, CellUtil.BORDER_BOTTOM)); - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, CellUtil.BORDER_LEFT)); - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, CellUtil.BORDER_RIGHT)); - } - } - pt.drawBorders(a1c3, BorderStyle.MEDIUM, - BorderExtent.OUTSIDE); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - assertEquals(4, pt.getNumBorders(i, j)); - if (i == 0) { - if (j == 0) { - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, - CellUtil.BORDER_TOP)); - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, - CellUtil.BORDER_BOTTOM)); - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, - CellUtil.BORDER_LEFT)); - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, - CellUtil.BORDER_RIGHT)); - } else if (j == 2) { - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, - CellUtil.BORDER_TOP)); - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, - CellUtil.BORDER_BOTTOM)); - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, - CellUtil.BORDER_LEFT)); - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, - CellUtil.BORDER_RIGHT)); - } else { - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, - CellUtil.BORDER_TOP)); - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, - CellUtil.BORDER_BOTTOM)); - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, - CellUtil.BORDER_LEFT)); - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, - CellUtil.BORDER_RIGHT)); - } - } else if (i == 2) { - if (j == 0) { - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, - CellUtil.BORDER_TOP)); - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, - CellUtil.BORDER_BOTTOM)); - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, - CellUtil.BORDER_LEFT)); - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, - CellUtil.BORDER_RIGHT)); - } else if (j == 2) { - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, - CellUtil.BORDER_TOP)); - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, - CellUtil.BORDER_BOTTOM)); - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, - CellUtil.BORDER_LEFT)); - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, - CellUtil.BORDER_RIGHT)); - } else { - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, - CellUtil.BORDER_TOP)); - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, - CellUtil.BORDER_BOTTOM)); - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, - CellUtil.BORDER_LEFT)); - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, - CellUtil.BORDER_RIGHT)); - } - } else { - if (j == 0) { - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, - CellUtil.BORDER_TOP)); - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, - CellUtil.BORDER_BOTTOM)); - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, - CellUtil.BORDER_LEFT)); - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, - CellUtil.BORDER_RIGHT)); - } else if (j == 2) { - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, - CellUtil.BORDER_TOP)); - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, - CellUtil.BORDER_BOTTOM)); - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, - CellUtil.BORDER_LEFT)); - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, - CellUtil.BORDER_RIGHT)); - } else { - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, - CellUtil.BORDER_TOP)); - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, - CellUtil.BORDER_BOTTOM)); - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, - CellUtil.BORDER_LEFT)); - assertEquals(BorderStyle.THIN, - pt.getBorderStyle(i, j, - CellUtil.BORDER_RIGHT)); - } - } - } - } - pt.drawBorders(a1c3, BorderStyle.NONE, - BorderExtent.NONE); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - assertEquals(0, pt.getNumBorders(i, j)); - } - } - pt.drawBorders(a1c3, BorderStyle.MEDIUM, - BorderExtent.TOP); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - if (i == 0) { - assertEquals(1, pt.getNumBorders(i, j)); - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, CellUtil.BORDER_TOP)); - } else { - assertEquals(0, pt.getNumBorders(i, j)); - } - } - } - pt.drawBorders(a1c3, BorderStyle.NONE, - BorderExtent.NONE); - pt.drawBorders(a1c3, BorderStyle.MEDIUM, - BorderExtent.BOTTOM); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - if (i == 2) { - assertEquals(1, pt.getNumBorders(i, j)); - assertEquals(BorderStyle.MEDIUM, pt - .getBorderStyle(i, j, CellUtil.BORDER_BOTTOM)); - } else { - assertEquals(0, pt.getNumBorders(i, j)); - } - } - } - pt.drawBorders(a1c3, BorderStyle.NONE, - BorderExtent.NONE); - pt.drawBorders(a1c3, BorderStyle.MEDIUM, - BorderExtent.LEFT); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - if (j == 0) { - assertEquals(1, pt.getNumBorders(i, j)); - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, CellUtil.BORDER_LEFT)); - } else { - assertEquals(0, pt.getNumBorders(i, j)); - } - } - } - pt.drawBorders(a1c3, BorderStyle.NONE, - BorderExtent.NONE); - pt.drawBorders(a1c3, BorderStyle.MEDIUM, - BorderExtent.RIGHT); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - if (j == 2) { - assertEquals(1, pt.getNumBorders(i, j)); - assertEquals(BorderStyle.MEDIUM, pt - .getBorderStyle(i, j, CellUtil.BORDER_RIGHT)); - } else { - assertEquals(0, pt.getNumBorders(i, j)); - } - } - } - pt.drawBorders(a1c3, BorderStyle.NONE, - BorderExtent.NONE); - pt.drawBorders(a1c3, BorderStyle.MEDIUM, - BorderExtent.HORIZONTAL); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - assertEquals(2, pt.getNumBorders(i, j)); - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, CellUtil.BORDER_TOP)); - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, CellUtil.BORDER_BOTTOM)); - } - } - pt.drawBorders(a1c3, BorderStyle.NONE, - BorderExtent.NONE); - pt.drawBorders(a1c3, BorderStyle.MEDIUM, - BorderExtent.INSIDE_HORIZONTAL); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - if (i == 0) { - assertEquals(1, pt.getNumBorders(i, j)); - assertEquals(BorderStyle.MEDIUM, pt - .getBorderStyle(i, j, CellUtil.BORDER_BOTTOM)); - } else if (i == 2) { - assertEquals(1, pt.getNumBorders(i, j)); - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, CellUtil.BORDER_TOP)); - } else { - assertEquals(2, pt.getNumBorders(i, j)); - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, CellUtil.BORDER_TOP)); - assertEquals(BorderStyle.MEDIUM, pt - .getBorderStyle(i, j, CellUtil.BORDER_BOTTOM)); - } - } - } - pt.drawBorders(a1c3, BorderStyle.NONE, - BorderExtent.NONE); - pt.drawBorders(a1c3, BorderStyle.MEDIUM, - BorderExtent.OUTSIDE_HORIZONTAL); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - if (i == 0) { - assertEquals(1, pt.getNumBorders(i, j)); - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, CellUtil.BORDER_TOP)); - } else if (i == 2) { - assertEquals(1, pt.getNumBorders(i, j)); - assertEquals(BorderStyle.MEDIUM, pt - .getBorderStyle(i, j, CellUtil.BORDER_BOTTOM)); - } else { - assertEquals(0, pt.getNumBorders(i, j)); - } - } - } - pt.drawBorders(a1c3, BorderStyle.NONE, - BorderExtent.NONE); - pt.drawBorders(a1c3, BorderStyle.MEDIUM, - BorderExtent.VERTICAL); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - assertEquals(2, pt.getNumBorders(i, j)); - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, CellUtil.BORDER_LEFT)); - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, CellUtil.BORDER_RIGHT)); - } - } - pt.drawBorders(a1c3, BorderStyle.NONE, - BorderExtent.NONE); - pt.drawBorders(a1c3, BorderStyle.MEDIUM, - BorderExtent.INSIDE_VERTICAL); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - if (j == 0) { - assertEquals(1, pt.getNumBorders(i, j)); - assertEquals(BorderStyle.MEDIUM, pt - .getBorderStyle(i, j, CellUtil.BORDER_RIGHT)); - } else if (j == 2) { - assertEquals(1, pt.getNumBorders(i, j)); - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, CellUtil.BORDER_LEFT)); - } else { - assertEquals(2, pt.getNumBorders(i, j)); - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, CellUtil.BORDER_LEFT)); - assertEquals(BorderStyle.MEDIUM, pt - .getBorderStyle(i, j, CellUtil.BORDER_RIGHT)); - } - } - } - pt.drawBorders(a1c3, BorderStyle.NONE, - BorderExtent.NONE); - pt.drawBorders(a1c3, BorderStyle.MEDIUM, - BorderExtent.OUTSIDE_VERTICAL); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - if (j == 0) { - assertEquals(1, pt.getNumBorders(i, j)); - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, CellUtil.BORDER_LEFT)); - } else if (j == 2) { - assertEquals(1, pt.getNumBorders(i, j)); - assertEquals(BorderStyle.MEDIUM, pt - .getBorderStyle(i, j, CellUtil.BORDER_RIGHT)); - } else { - assertEquals(0, pt.getNumBorders(i, j)); - } - } - } - } - - @Test - public void drawBorderColors() throws IOException { - CellRangeAddress a1c3 = new CellRangeAddress(0, 2, 0, 2); - PropertyTemplate pt = new PropertyTemplate(); - pt.drawBorderColors(a1c3, IndexedColors.RED.getIndex(), - BorderExtent.ALL); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - assertEquals(4, pt.getNumBorders(i, j)); - assertEquals(4, pt.getNumBorderColors(i, j)); - assertEquals(IndexedColors.RED.getIndex(), pt - .getTemplateProperty(i, j, CellUtil.TOP_BORDER_COLOR)); - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.BOTTOM_BORDER_COLOR)); - assertEquals(IndexedColors.RED.getIndex(), pt - .getTemplateProperty(i, j, CellUtil.LEFT_BORDER_COLOR)); - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.RIGHT_BORDER_COLOR)); - } - } - pt.drawBorderColors(a1c3, IndexedColors.BLUE.getIndex(), - BorderExtent.OUTSIDE); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - assertEquals(4, pt.getNumBorders(i, j)); - assertEquals(4, pt.getNumBorderColors(i, j)); - if (i == 0) { - if (j == 0) { - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.TOP_BORDER_COLOR)); - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.BOTTOM_BORDER_COLOR)); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.LEFT_BORDER_COLOR)); - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.RIGHT_BORDER_COLOR)); - } else if (j == 2) { - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.TOP_BORDER_COLOR)); - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.BOTTOM_BORDER_COLOR)); - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.LEFT_BORDER_COLOR)); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.RIGHT_BORDER_COLOR)); - } else { - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.TOP_BORDER_COLOR)); - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.BOTTOM_BORDER_COLOR)); - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.LEFT_BORDER_COLOR)); - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.RIGHT_BORDER_COLOR)); - } - } else if (i == 2) { - if (j == 0) { - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.TOP_BORDER_COLOR)); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.BOTTOM_BORDER_COLOR)); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.LEFT_BORDER_COLOR)); - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.RIGHT_BORDER_COLOR)); - } else if (j == 2) { - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.TOP_BORDER_COLOR)); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.BOTTOM_BORDER_COLOR)); - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.LEFT_BORDER_COLOR)); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.RIGHT_BORDER_COLOR)); - } else { - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.TOP_BORDER_COLOR)); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.BOTTOM_BORDER_COLOR)); - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.LEFT_BORDER_COLOR)); - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.RIGHT_BORDER_COLOR)); - } - } else { - if (j == 0) { - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.TOP_BORDER_COLOR)); - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.BOTTOM_BORDER_COLOR)); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.LEFT_BORDER_COLOR)); - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.RIGHT_BORDER_COLOR)); - } else if (j == 2) { - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.TOP_BORDER_COLOR)); - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.BOTTOM_BORDER_COLOR)); - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.LEFT_BORDER_COLOR)); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.RIGHT_BORDER_COLOR)); - } else { - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.TOP_BORDER_COLOR)); - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.BOTTOM_BORDER_COLOR)); - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.LEFT_BORDER_COLOR)); - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.RIGHT_BORDER_COLOR)); - } - } - } - } - pt.drawBorders(a1c3, BorderStyle.NONE, - BorderExtent.NONE); - pt.drawBorderColors(a1c3, IndexedColors.AUTOMATIC.getIndex(), - BorderExtent.NONE); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - assertEquals(0, pt.getNumBorders(i, j)); - assertEquals(0, pt.getNumBorderColors(i, j)); - } - } - pt.drawBorderColors(a1c3, IndexedColors.BLUE.getIndex(), - BorderExtent.TOP); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - if (i == 0) { - assertEquals(1, pt.getNumBorders(i, j)); - assertEquals(1, pt.getNumBorderColors(i, j)); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.TOP_BORDER_COLOR)); - } else { - assertEquals(0, pt.getNumBorders(i, j)); - assertEquals(0, pt.getNumBorderColors(i, j)); - } - } - } - pt.drawBorders(a1c3, BorderStyle.NONE, - BorderExtent.NONE); - pt.drawBorderColors(a1c3, IndexedColors.AUTOMATIC.getIndex(), - BorderExtent.NONE); - pt.drawBorderColors(a1c3, IndexedColors.BLUE.getIndex(), - BorderExtent.BOTTOM); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - if (i == 2) { - assertEquals(1, pt.getNumBorders(i, j)); - assertEquals(1, pt.getNumBorderColors(i, j)); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.BOTTOM_BORDER_COLOR)); - } else { - assertEquals(0, pt.getNumBorders(i, j)); - assertEquals(0, pt.getNumBorderColors(i, j)); - } - } - } - pt.drawBorders(a1c3, BorderStyle.NONE, - BorderExtent.NONE); - pt.drawBorderColors(a1c3, IndexedColors.AUTOMATIC.getIndex(), - BorderExtent.NONE); - pt.drawBorderColors(a1c3, IndexedColors.BLUE.getIndex(), - BorderExtent.LEFT); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - if (j == 0) { - assertEquals(1, pt.getNumBorders(i, j)); - assertEquals(1, pt.getNumBorderColors(i, j)); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.LEFT_BORDER_COLOR)); - } else { - assertEquals(0, pt.getNumBorders(i, j)); - assertEquals(0, pt.getNumBorderColors(i, j)); - } - } - } - pt.drawBorders(a1c3, BorderStyle.NONE, - BorderExtent.NONE); - pt.drawBorderColors(a1c3, IndexedColors.AUTOMATIC.getIndex(), - BorderExtent.NONE); - pt.drawBorderColors(a1c3, IndexedColors.BLUE.getIndex(), - BorderExtent.RIGHT); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - if (j == 2) { - assertEquals(1, pt.getNumBorders(i, j)); - assertEquals(1, pt.getNumBorderColors(i, j)); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.RIGHT_BORDER_COLOR)); - } else { - assertEquals(0, pt.getNumBorders(i, j)); - assertEquals(0, pt.getNumBorderColors(i, j)); - } - } - } - pt.drawBorders(a1c3, BorderStyle.NONE, - BorderExtent.NONE); - pt.drawBorderColors(a1c3, IndexedColors.AUTOMATIC.getIndex(), - BorderExtent.NONE); - pt.drawBorderColors(a1c3, IndexedColors.BLUE.getIndex(), - BorderExtent.HORIZONTAL); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - assertEquals(2, pt.getNumBorders(i, j)); - assertEquals(2, pt.getNumBorderColors(i, j)); - assertEquals(IndexedColors.BLUE.getIndex(), pt - .getTemplateProperty(i, j, CellUtil.TOP_BORDER_COLOR)); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.BOTTOM_BORDER_COLOR)); - } - } - pt.drawBorders(a1c3, BorderStyle.NONE, - BorderExtent.NONE); - pt.drawBorderColors(a1c3, IndexedColors.AUTOMATIC.getIndex(), - BorderExtent.NONE); - pt.drawBorderColors(a1c3, IndexedColors.BLUE.getIndex(), - BorderExtent.INSIDE_HORIZONTAL); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - if (i == 0) { - assertEquals(1, pt.getNumBorders(i, j)); - assertEquals(1, pt.getNumBorderColors(i, j)); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.BOTTOM_BORDER_COLOR)); - } else if (i == 2) { - assertEquals(1, pt.getNumBorders(i, j)); - assertEquals(1, pt.getNumBorderColors(i, j)); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.TOP_BORDER_COLOR)); - } else { - assertEquals(2, pt.getNumBorders(i, j)); - assertEquals(2, pt.getNumBorderColors(i, j)); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.TOP_BORDER_COLOR)); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.BOTTOM_BORDER_COLOR)); - } - } - } - pt.drawBorders(a1c3, BorderStyle.NONE, - BorderExtent.NONE); - pt.drawBorderColors(a1c3, IndexedColors.AUTOMATIC.getIndex(), - BorderExtent.NONE); - pt.drawBorderColors(a1c3, IndexedColors.BLUE.getIndex(), - BorderExtent.OUTSIDE_HORIZONTAL); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - if (i == 0) { - assertEquals(1, pt.getNumBorders(i, j)); - assertEquals(1, pt.getNumBorderColors(i, j)); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.TOP_BORDER_COLOR)); - } else if (i == 2) { - assertEquals(1, pt.getNumBorders(i, j)); - assertEquals(1, pt.getNumBorderColors(i, j)); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.BOTTOM_BORDER_COLOR)); - } else { - assertEquals(0, pt.getNumBorders(i, j)); - assertEquals(0, pt.getNumBorderColors(i, j)); - } - } - } - pt.drawBorders(a1c3, BorderStyle.NONE, - BorderExtent.NONE); - pt.drawBorderColors(a1c3, IndexedColors.AUTOMATIC.getIndex(), - BorderExtent.NONE); - pt.drawBorderColors(a1c3, IndexedColors.BLUE.getIndex(), - BorderExtent.VERTICAL); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - assertEquals(2, pt.getNumBorders(i, j)); - assertEquals(2, pt.getNumBorderColors(i, j)); - assertEquals(IndexedColors.BLUE.getIndex(), pt - .getTemplateProperty(i, j, CellUtil.LEFT_BORDER_COLOR)); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.RIGHT_BORDER_COLOR)); - } - } - pt.drawBorders(a1c3, BorderStyle.NONE, - BorderExtent.NONE); - pt.drawBorderColors(a1c3, IndexedColors.AUTOMATIC.getIndex(), - BorderExtent.NONE); - pt.drawBorderColors(a1c3, IndexedColors.BLUE.getIndex(), - BorderExtent.INSIDE_VERTICAL); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - if (j == 0) { - assertEquals(1, pt.getNumBorders(i, j)); - assertEquals(1, pt.getNumBorderColors(i, j)); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.RIGHT_BORDER_COLOR)); - } else if (j == 2) { - assertEquals(1, pt.getNumBorders(i, j)); - assertEquals(1, pt.getNumBorderColors(i, j)); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.LEFT_BORDER_COLOR)); - } else { - assertEquals(2, pt.getNumBorders(i, j)); - assertEquals(2, pt.getNumBorderColors(i, j)); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.LEFT_BORDER_COLOR)); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.RIGHT_BORDER_COLOR)); - } - } - } - pt.drawBorders(a1c3, BorderStyle.NONE, - BorderExtent.NONE); - pt.drawBorderColors(a1c3, IndexedColors.AUTOMATIC.getIndex(), - BorderExtent.NONE); - pt.drawBorderColors(a1c3, IndexedColors.BLUE.getIndex(), - BorderExtent.OUTSIDE_VERTICAL); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - if (j == 0) { - assertEquals(1, pt.getNumBorders(i, j)); - assertEquals(1, pt.getNumBorderColors(i, j)); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.LEFT_BORDER_COLOR)); - } else if (j == 2) { - assertEquals(1, pt.getNumBorders(i, j)); - assertEquals(1, pt.getNumBorderColors(i, j)); - assertEquals(IndexedColors.BLUE.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.RIGHT_BORDER_COLOR)); - } else { - assertEquals(0, pt.getNumBorders(i, j)); - assertEquals(0, pt.getNumBorderColors(i, j)); - } - } - } - } - - @Test - public void drawBordersWithColors() throws IOException { - CellRangeAddress a1c3 = new CellRangeAddress(0, 2, 0, 2); - PropertyTemplate pt = new PropertyTemplate(); - - pt.drawBorders(a1c3, BorderStyle.MEDIUM, IndexedColors.RED.getIndex(), BorderExtent.ALL); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - assertEquals(4, pt.getNumBorders(i, j)); - assertEquals(4, pt.getNumBorderColors(i, j)); - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, CellUtil.BORDER_TOP)); - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, CellUtil.BORDER_BOTTOM)); - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, CellUtil.BORDER_LEFT)); - assertEquals(BorderStyle.MEDIUM, - pt.getBorderStyle(i, j, CellUtil.BORDER_RIGHT)); - assertEquals(IndexedColors.RED.getIndex(), pt - .getTemplateProperty(i, j, CellUtil.TOP_BORDER_COLOR)); - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.BOTTOM_BORDER_COLOR)); - assertEquals(IndexedColors.RED.getIndex(), pt - .getTemplateProperty(i, j, CellUtil.LEFT_BORDER_COLOR)); - assertEquals(IndexedColors.RED.getIndex(), - pt.getTemplateProperty(i, j, - CellUtil.RIGHT_BORDER_COLOR)); - } - } - pt.drawBorders(a1c3, BorderStyle.NONE, BorderExtent.NONE); - pt.drawBorders(a1c3, BorderStyle.NONE, IndexedColors.RED.getIndex(), BorderExtent.ALL); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - assertEquals(4, pt.getNumBorders(i, j)); - assertEquals(0, pt.getNumBorderColors(i, j)); - assertEquals(BorderStyle.NONE, - pt.getBorderStyle(i, j, CellUtil.BORDER_TOP)); - assertEquals(BorderStyle.NONE, - pt.getBorderStyle(i, j, CellUtil.BORDER_BOTTOM)); - assertEquals(BorderStyle.NONE, - pt.getBorderStyle(i, j, CellUtil.BORDER_LEFT)); - assertEquals(BorderStyle.NONE, - pt.getBorderStyle(i, j, CellUtil.BORDER_RIGHT)); - } - } - } - - @Test - public void applyBorders() throws IOException { - CellRangeAddress a1c3 = new CellRangeAddress(0, 2, 0, 2); - CellRangeAddress b2 = new CellRangeAddress(1, 1, 1, 1); - PropertyTemplate pt = new PropertyTemplate(); - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - - pt.drawBorders(a1c3, BorderStyle.THIN, IndexedColors.RED.getIndex(), BorderExtent.ALL); - pt.applyBorders(sheet); - - for (Row row: sheet) { - for (Cell cell: row) { - CellStyle cs = cell.getCellStyle(); - assertEquals(BorderStyle.THIN, cs.getBorderTopEnum()); - assertEquals(IndexedColors.RED.getIndex(), cs.getTopBorderColor()); - assertEquals(BorderStyle.THIN, cs.getBorderBottomEnum()); - assertEquals(IndexedColors.RED.getIndex(), cs.getBottomBorderColor()); - assertEquals(BorderStyle.THIN, cs.getBorderLeftEnum()); - assertEquals(IndexedColors.RED.getIndex(), cs.getLeftBorderColor()); - assertEquals(BorderStyle.THIN, cs.getBorderRightEnum()); - assertEquals(IndexedColors.RED.getIndex(), cs.getRightBorderColor()); - } - } - - pt.drawBorders(b2, BorderStyle.NONE, BorderExtent.ALL); - pt.applyBorders(sheet); - - for (Row row: sheet) { - for (Cell cell: row) { - CellStyle cs = cell.getCellStyle(); - if (cell.getColumnIndex() != 1 || row.getRowNum() == 0) { - assertEquals(BorderStyle.THIN, cs.getBorderTopEnum()); - assertEquals(IndexedColors.RED.getIndex(), cs.getTopBorderColor()); - } else { - assertEquals(BorderStyle.NONE, cs.getBorderTopEnum()); - } - if (cell.getColumnIndex() != 1 || row.getRowNum() == 2) { - assertEquals(BorderStyle.THIN, cs.getBorderBottomEnum()); - assertEquals(IndexedColors.RED.getIndex(), cs.getBottomBorderColor()); - } else { - assertEquals(BorderStyle.NONE, cs.getBorderBottomEnum()); - } - if (cell.getColumnIndex() == 0 || row.getRowNum() != 1) { - assertEquals(BorderStyle.THIN, cs.getBorderLeftEnum()); - assertEquals(IndexedColors.RED.getIndex(), cs.getLeftBorderColor()); - } else { - assertEquals(BorderStyle.NONE, cs.getBorderLeftEnum()); - } - if (cell.getColumnIndex() == 2 || row.getRowNum() != 1) { - assertEquals(BorderStyle.THIN, cs.getBorderRightEnum()); - assertEquals(IndexedColors.RED.getIndex(), cs.getRightBorderColor()); - } else { - assertEquals(BorderStyle.NONE, cs.getBorderRightEnum()); - } - } - } - - wb.close(); - } - - @Test - public void clonePropertyTemplate() throws IOException { - CellRangeAddress a1c3 = new CellRangeAddress(0, 2, 0, 2); - PropertyTemplate pt = new PropertyTemplate(); - pt.drawBorders(a1c3, BorderStyle.MEDIUM, IndexedColors.RED.getIndex(), BorderExtent.ALL); - PropertyTemplate pt2 = new PropertyTemplate(pt); - assertNotSame(pt2, pt); - for (int i = 0; i <= 2; i++) { - for (int j = 0; j <= 2; j++) { - assertEquals(4, pt2.getNumBorderColors(i, j)); - assertEquals(4, pt2.getNumBorderColors(i, j)); - } - } - - CellRangeAddress b2 = new CellRangeAddress(1,1,1,1); - pt2.drawBorders(b2, BorderStyle.THIN, BorderExtent.ALL); - - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - pt.applyBorders(sheet); - - for (Row row : sheet) { - for (Cell cell : row) { - CellStyle cs = cell.getCellStyle(); - assertEquals(BorderStyle.MEDIUM, cs.getBorderTopEnum()); - assertEquals(BorderStyle.MEDIUM, cs.getBorderBottomEnum()); - assertEquals(BorderStyle.MEDIUM, cs.getBorderLeftEnum()); - assertEquals(BorderStyle.MEDIUM, cs.getBorderRightEnum()); - assertEquals(IndexedColors.RED.getIndex(), cs.getTopBorderColor()); - assertEquals(IndexedColors.RED.getIndex(), cs.getBottomBorderColor()); - assertEquals(IndexedColors.RED.getIndex(), cs.getLeftBorderColor()); - assertEquals(IndexedColors.RED.getIndex(), cs.getRightBorderColor()); - } - } - - wb.close(); - } -} diff --git a/src/testcases/org/apache/poi/ss/util/TestRegionUtil.java b/src/testcases/org/apache/poi/ss/util/TestRegionUtil.java deleted file mode 100644 index 13fad63bf..000000000 --- a/src/testcases/org/apache/poi/ss/util/TestRegionUtil.java +++ /dev/null @@ -1,163 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.util; - -import static org.junit.Assert.*; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.BorderStyle; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.IndexedColors; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import java.io.IOException; - -/** - * Tests that the common RegionUtil works as we need it to. - */ -public final class TestRegionUtil { - private static final CellRangeAddress A1C3 = new CellRangeAddress(0, 2, 0, 2); - private static final BorderStyle NONE = BorderStyle.NONE; - private static final BorderStyle THIN = BorderStyle.THIN; - private static final int RED = IndexedColors.RED.getIndex(); - private static final int DEFAULT_COLOR = 0; - private Workbook wb; - private Sheet sheet; - - @Before - public void setUp() { - wb = new HSSFWorkbook(); - sheet = wb.createSheet(); - } - - @After - public void tearDown() throws IOException { - wb.close(); - } - - private CellStyle getCellStyle(int rowIndex, int columnIndex) { - Row row = sheet.getRow(rowIndex); - if (row == null) row = sheet.createRow(rowIndex); - Cell cell = row.getCell(columnIndex); - if (cell == null) cell = row.createCell(columnIndex); - return cell.getCellStyle(); - } - - @Test - public void setBorderTop() { - assertEquals(NONE, getCellStyle(0, 0).getBorderTopEnum()); - assertEquals(NONE, getCellStyle(0, 1).getBorderTopEnum()); - assertEquals(NONE, getCellStyle(0, 2).getBorderTopEnum()); - RegionUtil.setBorderTop(THIN, A1C3, sheet); - assertEquals(THIN, getCellStyle(0, 0).getBorderTopEnum()); - assertEquals(THIN, getCellStyle(0, 1).getBorderTopEnum()); - assertEquals(THIN, getCellStyle(0, 2).getBorderTopEnum()); - } - @Test - public void setBorderBottom() { - assertEquals(NONE, getCellStyle(2, 0).getBorderBottomEnum()); - assertEquals(NONE, getCellStyle(2, 1).getBorderBottomEnum()); - assertEquals(NONE, getCellStyle(2, 2).getBorderBottomEnum()); - RegionUtil.setBorderBottom(THIN, A1C3, sheet); - assertEquals(THIN, getCellStyle(2, 0).getBorderBottomEnum()); - assertEquals(THIN, getCellStyle(2, 1).getBorderBottomEnum()); - assertEquals(THIN, getCellStyle(2, 2).getBorderBottomEnum()); - } - @Test - public void setBorderRight() { - assertEquals(NONE, getCellStyle(0, 2).getBorderRightEnum()); - assertEquals(NONE, getCellStyle(1, 2).getBorderRightEnum()); - assertEquals(NONE, getCellStyle(2, 2).getBorderRightEnum()); - RegionUtil.setBorderRight(THIN, A1C3, sheet); - assertEquals(THIN, getCellStyle(0, 2).getBorderRightEnum()); - assertEquals(THIN, getCellStyle(1, 2).getBorderRightEnum()); - assertEquals(THIN, getCellStyle(2, 2).getBorderRightEnum()); - } - @Test - public void setBorderLeft() { - assertEquals(NONE, getCellStyle(0, 0).getBorderLeftEnum()); - assertEquals(NONE, getCellStyle(1, 0).getBorderLeftEnum()); - assertEquals(NONE, getCellStyle(2, 0).getBorderLeftEnum()); - RegionUtil.setBorderLeft(THIN, A1C3, sheet); - assertEquals(THIN, getCellStyle(0, 0).getBorderLeftEnum()); - assertEquals(THIN, getCellStyle(1, 0).getBorderLeftEnum()); - assertEquals(THIN, getCellStyle(2, 0).getBorderLeftEnum()); - } - - @Test - public void setTopBorderColor() { - assertEquals(DEFAULT_COLOR, getCellStyle(0, 0).getTopBorderColor()); - assertEquals(DEFAULT_COLOR, getCellStyle(0, 1).getTopBorderColor()); - assertEquals(DEFAULT_COLOR, getCellStyle(0, 2).getTopBorderColor()); - RegionUtil.setTopBorderColor(RED, A1C3, sheet); - assertEquals(RED, getCellStyle(0, 0).getTopBorderColor()); - assertEquals(RED, getCellStyle(0, 1).getTopBorderColor()); - assertEquals(RED, getCellStyle(0, 2).getTopBorderColor()); - } - @Test - public void setBottomBorderColor() { - assertEquals(DEFAULT_COLOR, getCellStyle(2, 0).getBottomBorderColor()); - assertEquals(DEFAULT_COLOR, getCellStyle(2, 1).getBottomBorderColor()); - assertEquals(DEFAULT_COLOR, getCellStyle(2, 2).getBottomBorderColor()); - RegionUtil.setBottomBorderColor(RED, A1C3, sheet); - assertEquals(RED, getCellStyle(2, 0).getBottomBorderColor()); - assertEquals(RED, getCellStyle(2, 1).getBottomBorderColor()); - assertEquals(RED, getCellStyle(2, 2).getBottomBorderColor()); - } - @Test - public void setRightBorderColor() { - assertEquals(DEFAULT_COLOR, getCellStyle(0, 2).getRightBorderColor()); - assertEquals(DEFAULT_COLOR, getCellStyle(1, 2).getRightBorderColor()); - assertEquals(DEFAULT_COLOR, getCellStyle(2, 2).getRightBorderColor()); - RegionUtil.setRightBorderColor(RED, A1C3, sheet); - assertEquals(RED, getCellStyle(0, 2).getRightBorderColor()); - assertEquals(RED, getCellStyle(1, 2).getRightBorderColor()); - assertEquals(RED, getCellStyle(2, 2).getRightBorderColor()); - } - @Test - public void setLeftBorderColor() { - assertEquals(DEFAULT_COLOR, getCellStyle(0, 0).getLeftBorderColor()); - assertEquals(DEFAULT_COLOR, getCellStyle(1, 0).getLeftBorderColor()); - assertEquals(DEFAULT_COLOR, getCellStyle(2, 0).getLeftBorderColor()); - RegionUtil.setLeftBorderColor(RED, A1C3, sheet); - assertEquals(RED, getCellStyle(0, 0).getLeftBorderColor()); - assertEquals(RED, getCellStyle(1, 0).getLeftBorderColor()); - assertEquals(RED, getCellStyle(2, 0).getLeftBorderColor()); - } - - @Test - public void bordersCanBeAddedToNonExistantCells() { - RegionUtil.setBorderTop(THIN, A1C3, sheet); - assertEquals(THIN, getCellStyle(0, 0).getBorderTopEnum()); - assertEquals(THIN, getCellStyle(0, 1).getBorderTopEnum()); - assertEquals(THIN, getCellStyle(0, 2).getBorderTopEnum()); - } - @Test - public void borderColorsCanBeAddedToNonExistantCells() { - RegionUtil.setTopBorderColor(RED, A1C3, sheet); - assertEquals(RED, getCellStyle(0, 0).getTopBorderColor()); - assertEquals(RED, getCellStyle(0, 1).getTopBorderColor()); - assertEquals(RED, getCellStyle(0, 2).getTopBorderColor()); - } -} diff --git a/src/testcases/org/apache/poi/ss/util/TestSheetBuilder.java b/src/testcases/org/apache/poi/ss/util/TestSheetBuilder.java deleted file mode 100644 index d081db0fc..000000000 --- a/src/testcases/org/apache/poi/ss/util/TestSheetBuilder.java +++ /dev/null @@ -1,85 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - ==================================================================== */ - -package org.apache.poi.ss.util; - -import java.util.Date; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; - -import junit.framework.TestCase; - -/** - * Tests SheetBuilder. - * - * @see org.apache.poi.ss.util.SheetBuilder - */ -public final class TestSheetBuilder extends TestCase { - - private static Object[][] testData = new Object[][]{ - {1, 2, 3}, - {new Date(), null, null}, - {"one", "two", "=A1+B2"} - }; - - public void testNotCreateEmptyCells() { - Workbook wb = new HSSFWorkbook(); - Sheet sheet = new SheetBuilder(wb, testData).build(); - - assertEquals(sheet.getPhysicalNumberOfRows(), 3); - - Row firstRow = sheet.getRow(0); - Cell firstCell = firstRow.getCell(0); - - assertEquals(firstCell.getCellTypeEnum(), CellType.NUMERIC); - assertEquals(1.0, firstCell.getNumericCellValue(), 0.00001); - - - Row secondRow = sheet.getRow(1); - assertNotNull(secondRow.getCell(0)); - assertNull(secondRow.getCell(2)); - - Row thirdRow = sheet.getRow(2); - assertEquals(CellType.STRING, thirdRow.getCell(0).getCellTypeEnum()); - String cellValue = thirdRow.getCell(0).getStringCellValue(); - assertEquals(testData[2][0].toString(), cellValue); - - assertEquals(CellType.FORMULA, thirdRow.getCell(2).getCellTypeEnum()); - assertEquals("A1+B2", thirdRow.getCell(2).getCellFormula()); - } - - public void testEmptyCells() { - Workbook wb = new HSSFWorkbook(); - Sheet sheet = new SheetBuilder(wb, testData).setCreateEmptyCells(true).build(); - - Cell emptyCell = sheet.getRow(1).getCell(1); - assertNotNull(emptyCell); - assertEquals(CellType.BLANK, emptyCell.getCellTypeEnum()); - } - - public void testSheetName() { - final String sheetName = "TEST SHEET NAME"; - Workbook wb = new HSSFWorkbook(); - Sheet sheet = new SheetBuilder(wb, testData).setSheetName(sheetName).build(); - assertEquals(sheetName, sheet.getSheetName()); - } -} \ No newline at end of file diff --git a/src/testcases/org/apache/poi/ss/util/TestSheetUtil.java b/src/testcases/org/apache/poi/ss/util/TestSheetUtil.java deleted file mode 100644 index e1c788436..000000000 --- a/src/testcases/org/apache/poi/ss/util/TestSheetUtil.java +++ /dev/null @@ -1,149 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - ==================================================================== */ - -package org.apache.poi.ss.util; - -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; - -import junit.framework.TestCase; - -/** - * Tests SheetUtil. - * - * @see org.apache.poi.ss.util.SheetUtil - */ -public final class TestSheetUtil extends TestCase { - public void testCellWithMerges() throws Exception { - Workbook wb = new HSSFWorkbook(); - Sheet s = wb.createSheet(); - - // Create some test data - Row r2 = s.createRow(1); - r2.createCell(0).setCellValue(10); - r2.createCell(1).setCellValue(11); - Row r3 = s.createRow(2); - r3.createCell(0).setCellValue(20); - r3.createCell(1).setCellValue(21); - - s.addMergedRegion(new CellRangeAddress(2, 3, 0, 0)); - s.addMergedRegion(new CellRangeAddress(2, 2, 1, 4)); - - // With a cell that isn't defined, we'll get null - assertEquals(null, SheetUtil.getCellWithMerges(s, 0, 0)); - - // With a cell that's not in a merged region, we'll get that - assertEquals(10.0, SheetUtil.getCellWithMerges(s, 1, 0).getNumericCellValue()); - assertEquals(11.0, SheetUtil.getCellWithMerges(s, 1, 1).getNumericCellValue()); - - // With a cell that's the primary one of a merged region, we get that cell - assertEquals(20.0, SheetUtil.getCellWithMerges(s, 2, 0).getNumericCellValue()); - assertEquals(21., SheetUtil.getCellWithMerges(s, 2, 1).getNumericCellValue()); - - // With a cell elsewhere in the merged region, get top-left - assertEquals(20.0, SheetUtil.getCellWithMerges(s, 3, 0).getNumericCellValue()); - assertEquals(21.0, SheetUtil.getCellWithMerges(s, 2, 2).getNumericCellValue()); - assertEquals(21.0, SheetUtil.getCellWithMerges(s, 2, 3).getNumericCellValue()); - assertEquals(21.0, SheetUtil.getCellWithMerges(s, 2, 4).getNumericCellValue()); - - wb.close(); - } - - public void testCanComputeWidthHSSF() throws IOException { - Workbook wb = new HSSFWorkbook(); - - // cannot check on result because on some machines we get back false here! - SheetUtil.canComputeColumnWidth(wb.getFontAt((short)0)); - - wb.close(); - } - - public void testGetCellWidthEmpty() throws IOException { - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet("sheet"); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - - // no contents: cell.setCellValue("sometext"); - - assertEquals(-1.0, SheetUtil.getCellWidth(cell, 1, null, true)); - - wb.close(); - } - - public void testGetCellWidthString() throws IOException { - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet("sheet"); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - - cell.setCellValue("sometext"); - - assertTrue(SheetUtil.getCellWidth(cell, 1, null, true) > 0); - - wb.close(); - } - - public void testGetCellWidthNumber() throws IOException { - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet("sheet"); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - - cell.setCellValue(88.234); - - assertTrue(SheetUtil.getCellWidth(cell, 1, null, true) > 0); - - wb.close(); - } - - public void testGetCellWidthBoolean() throws IOException { - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet("sheet"); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - - cell.setCellValue(false); - - assertTrue(SheetUtil.getCellWidth(cell, 1, null, false) > 0); - - wb.close(); - } - - public void testGetColumnWidthString() throws IOException { - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet("sheet"); - Row row = sheet.createRow(0); - sheet.createRow(1); - sheet.createRow(2); - Cell cell = row.createCell(0); - - cell.setCellValue("sometext"); - - assertTrue("Having some width for rows with actual cells", - SheetUtil.getColumnWidth(sheet, 0, true) > 0); - assertEquals("Not having any widht for rows with all empty cells", - -1.0, SheetUtil.getColumnWidth(sheet, 0, true, 1, 2)); - - wb.close(); - } -} diff --git a/src/testcases/org/apache/poi/ss/util/TestWorkbookUtil.java b/src/testcases/org/apache/poi/ss/util/TestWorkbookUtil.java deleted file mode 100644 index 2bd305c43..000000000 --- a/src/testcases/org/apache/poi/ss/util/TestWorkbookUtil.java +++ /dev/null @@ -1,87 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.util; - -import junit.framework.TestCase; - -/** - * Tests WorkbookUtil. - * - * @see org.apache.poi.ss.util.WorkbookUtil - */ -public final class TestWorkbookUtil extends TestCase { - /** - * borrowed test cases from - * {@link org.apache.poi.hssf.record.TestBoundSheetRecord#testValidNames()} - */ - public void testCreateSafeNames() { - - String p = "Sheet1"; - String actual = WorkbookUtil.createSafeSheetName(p); - assertEquals(p, actual); - - p = "O'Brien's sales"; - actual = WorkbookUtil.createSafeSheetName(p); - assertEquals(p, actual); - - p = " data # "; - actual = WorkbookUtil.createSafeSheetName(p); - assertEquals(p, actual); - - p = "data $1.00"; - actual = WorkbookUtil.createSafeSheetName(p); - assertEquals(p, actual); - - // now the replaced versions ... - actual = WorkbookUtil.createSafeSheetName("data?"); - assertEquals("data ", actual); - - actual = WorkbookUtil.createSafeSheetName("abc/def"); - assertEquals("abc def", actual); - - actual = WorkbookUtil.createSafeSheetName("data[0]"); - assertEquals("data 0 ", actual); - - actual = WorkbookUtil.createSafeSheetName("data*"); - assertEquals("data ", actual); - - actual = WorkbookUtil.createSafeSheetName("abc\\def"); - assertEquals("abc def", actual); - - actual = WorkbookUtil.createSafeSheetName("'data"); - assertEquals(" data", actual); - - actual = WorkbookUtil.createSafeSheetName("data'"); - assertEquals("data ", actual); - - actual = WorkbookUtil.createSafeSheetName("d'at'a"); - assertEquals("d'at'a", actual); - - actual = WorkbookUtil.createSafeSheetName(null); - assertEquals("null", actual); - - actual = WorkbookUtil.createSafeSheetName(""); - assertEquals("empty", actual); - - actual = WorkbookUtil.createSafeSheetName("1234567890123456789012345678901TOOLONG"); - assertEquals("1234567890123456789012345678901", actual); - - actual = WorkbookUtil.createSafeSheetName("sheet:a4"); - assertEquals("sheet a4", actual); - } -} diff --git a/src/testcases/org/apache/poi/ss/util/cellwalk/TestCellWalk.java b/src/testcases/org/apache/poi/ss/util/cellwalk/TestCellWalk.java deleted file mode 100644 index d3adcce0c..000000000 --- a/src/testcases/org/apache/poi/ss/util/cellwalk/TestCellWalk.java +++ /dev/null @@ -1,79 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - ==================================================================== */ -package org.apache.poi.ss.util.cellwalk; - -import junit.framework.TestCase; - -import java.util.Date; - -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.SheetBuilder; - -public class TestCellWalk extends TestCase { - - private static Object[][] testData = new Object[][] { - { 1, 2, null}, - {null, new Date(), null}, - {null, null, "str"} - }; - - private final CountCellHandler countCellHandler = new CountCellHandler(); - - public void testNotTraverseEmptyCells() { - Workbook wb = new HSSFWorkbook(); - Sheet sheet = new SheetBuilder(wb, testData).build(); - CellRangeAddress range = CellRangeAddress.valueOf("A1:C3"); - - CellWalk cellWalk = new CellWalk(sheet, range); - countCellHandler.reset(); - cellWalk.traverse(countCellHandler); - - assertEquals(4, countCellHandler.getVisitedCellsNumber()); - /* 1 + 2 + 5 + 9 */ - assertEquals(17L, countCellHandler.getOrdinalNumberSum()); - } - - - private static class CountCellHandler implements CellHandler { - - private int cellsVisited = 0; - private long ordinalNumberSum = 0L; - - @Override - public void onCell(Cell cell, CellWalkContext ctx) { - ++cellsVisited; - ordinalNumberSum += ctx.getOrdinalNumber(); - } - - public int getVisitedCellsNumber() { - return cellsVisited; - } - - public long getOrdinalNumberSum() { - return ordinalNumberSum; - } - - public void reset() { - cellsVisited = 0; - ordinalNumberSum = 0L; - } - } -} \ No newline at end of file diff --git a/src/testcases/org/apache/poi/util/AllPOIUtilTests.java b/src/testcases/org/apache/poi/util/AllPOIUtilTests.java deleted file mode 100644 index f018b0229..000000000 --- a/src/testcases/org/apache/poi/util/AllPOIUtilTests.java +++ /dev/null @@ -1,43 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.util; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -/** - * Test suite for all sub-packages of org.apache.poi.util
    - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestArrayUtil.class - , TestBitField.class - , TestByteField.class - , TestHexDump.class - , TestIntegerField.class - , TestIntList.class - , TestLittleEndian.class - , TestLongField.class - , TestPOILogFactory.class - , TestPOILogger.class - , TestShortField.class - , TestStringUtil.class - , TestTempFile.class -}) -public final class AllPOIUtilTests { -} diff --git a/src/testcases/org/apache/poi/util/DummyPOILogger.java b/src/testcases/org/apache/poi/util/DummyPOILogger.java deleted file mode 100644 index 7da48ce26..000000000 --- a/src/testcases/org/apache/poi/util/DummyPOILogger.java +++ /dev/null @@ -1,51 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.util; - -import java.util.ArrayList; -import java.util.List; - -/** - * POILogger which logs into an ArrayList, so that - * tests can see what got logged - */ -@Internal -public class DummyPOILogger extends POILogger { - public Listlogged = new ArrayList(); - - public void reset() { - logged = new ArrayList(); - } - - @Override - public boolean check(int level) { - return true; - } - - @Override - public void initialize(String cat) {} - - @Override - protected void _log(int level, Object obj1) { - logged.add(level + " - " + obj1); - } - - @Override - protected void _log(int level, Object obj1, Throwable exception) { - logged.add(level + " - " + obj1 + " - " + exception); - } -} diff --git a/src/testcases/org/apache/poi/util/NullOutputStream.java b/src/testcases/org/apache/poi/util/NullOutputStream.java deleted file mode 100644 index ac76123a3..000000000 --- a/src/testcases/org/apache/poi/util/NullOutputStream.java +++ /dev/null @@ -1,41 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.util; - -import java.io.OutputStream; - -/** - * Implementation of an OutputStream which does nothing, used - * to redirect stdout to avoid spamming the console with output - */ -public final class NullOutputStream extends OutputStream { - public NullOutputStream() { - } - - @Override - public void write(byte[] b, int off, int len) { - } - - @Override - public void write(int b) { - } - - @Override - public void write(byte[] b) { - } -} diff --git a/src/testcases/org/apache/poi/util/TestArrayUtil.java b/src/testcases/org/apache/poi/util/TestArrayUtil.java deleted file mode 100644 index 2af048151..000000000 --- a/src/testcases/org/apache/poi/util/TestArrayUtil.java +++ /dev/null @@ -1,294 +0,0 @@ - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.util; - -import junit.framework.TestCase; - -/** - * Unit test for ArrayUtil - * - * @author Nick Burch - */ -public class TestArrayUtil extends TestCase { - /** - * Test to ensure that our own arraycopy behaves as it should do - */ - public void testarraycopy() { - byte[] bytes = new byte[] { 0x01, 0x02, 0x03, 0x04 }; - - // Test copy whole thing - byte[] dest = new byte[4]; - ArrayUtil.arraycopy(bytes, 0, dest, 0, 4); - - assertEquals(dest.length, bytes.length); - for(int i=0; i?")); - - dump = HexDump.dump(testArray, 2, 1); - //System.out.println("Hex: \n" + dump); - assertTrue("Had: \n" + dump, - dump.contains("123456789:;<=>?@")); - } - - @Test(expected=ArrayIndexOutOfBoundsException.class) - public void testDumpToStringOutOfIndex1() throws Exception { - HexDump.dump(new byte[1], 0, -1); - } - - @Test(expected=ArrayIndexOutOfBoundsException.class) - public void testDumpToStringOutOfIndex2() throws Exception { - HexDump.dump(new byte[1], 0, 2); - } - - @Test(expected=ArrayIndexOutOfBoundsException.class) - public void testDumpToStringOutOfIndex3() throws Exception { - HexDump.dump(new byte[1], 0, 1); - } - - @Test - public void testDumpToStringNoDataEOL1() throws Exception { - HexDump.dump(new byte[0], 0, 1); - } - - @Test - public void testDumpToStringNoDataEOL2() throws Exception { - HexDump.dump(new byte[0], 0, 0); - } - - @Test - public void testDumpToPrintStream() throws IOException { - byte[] testArray = testArray(); - ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); - PrintStream out = new PrintStream(byteOut,true,LocaleUtil.CHARSET_1252.name()); - ByteArrayInputStream byteIn = new ByteArrayInputStream(testArray); - byteIn.mark(256); - String str; - - byteIn.reset(); - byteOut.reset(); - HexDump.dump(byteIn, out, 0, 256); - str = new String(byteOut.toByteArray(), LocaleUtil.CHARSET_1252); - assertTrue("Had: \n" + str, str.contains("0123456789:;<=>?")); - - // test with more than we have - byteIn.reset(); - byteOut.reset(); - HexDump.dump(byteIn, out, 0, 1000); - str = new String(byteOut.toByteArray(), LocaleUtil.CHARSET_1252); - assertTrue("Had: \n" + str, str.contains("0123456789:;<=>?")); - - // test with -1 - byteIn.reset(); - byteOut.reset(); - HexDump.dump(byteIn, out, 0, -1); - str = new String(byteOut.toByteArray(), LocaleUtil.CHARSET_1252); - assertTrue("Had: \n" + str, str.contains("0123456789:;<=>?")); - - byteIn.reset(); - byteOut.reset(); - HexDump.dump(byteIn, out, 1, 235); - str = new String(byteOut.toByteArray(), LocaleUtil.CHARSET_1252); - assertTrue("Line contents should be moved by one now, but Had: \n" + str, - str.contains("123456789:;<=>?@")); - - byteIn.close(); - byteOut.close(); - } - - @Test - public void testMain() throws Exception { - File file = TempFile.createTempFile("HexDump", ".dat"); - try { - FileOutputStream out = new FileOutputStream(file); - try { - IOUtils.copy(new ByteArrayInputStream("teststring".getBytes(LocaleUtil.CHARSET_1252)), out); - } finally { - out.close(); - } - assertTrue(file.exists()); - assertTrue(file.length() > 0); - - HexDump.main(new String[] { file.getAbsolutePath() }); - } finally { - assertTrue(file.exists() && file.delete()); - } - } - - private static byte[] testArray() { - byte[] testArray = new byte[ 256 ]; - - for (int j = 0; j < 256; j++) { - testArray[ j ] = ( byte ) j; - } - - return testArray; - } -} diff --git a/src/testcases/org/apache/poi/util/TestIntList.java b/src/testcases/org/apache/poi/util/TestIntList.java deleted file mode 100644 index abf50158b..000000000 --- a/src/testcases/org/apache/poi/util/TestIntList.java +++ /dev/null @@ -1,568 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.util; - -import junit.framework.TestCase; - -/** - * Class to test IntList - * - * @author Marc Johnson - */ -public final class TestIntList extends TestCase { - - public void testConstructors() { - IntList list = new IntList(); - - assertTrue(list.isEmpty()); - list.add(0); - list.add(1); - IntList list2 = new IntList(list); - - assertEquals(list, list2); - IntList list3 = new IntList(2); - - assertTrue(list3.isEmpty()); - } - - public void testAdd() { - IntList list = new IntList(); - int[] testArray = - { - 0, 1, 2, 3, 5 - }; - - for (int element : testArray) { - list.add(element); - } - for (int j = 0; j < testArray.length; j++) - { - assertEquals(testArray[ j ], list.get(j)); - } - assertEquals(testArray.length, list.size()); - - // add at the beginning - list.add(0, -1); - assertEquals(-1, list.get(0)); - assertEquals(testArray.length + 1, list.size()); - for (int j = 0; j < testArray.length; j++) - { - assertEquals(testArray[ j ], list.get(j + 1)); - } - - // add in the middle - list.add(5, 4); - assertEquals(4, list.get(5)); - assertEquals(testArray.length + 2, list.size()); - for (int j = 0; j < list.size(); j++) - { - assertEquals(j - 1, list.get(j)); - } - - // add at the end - list.add(list.size(), 6); - assertEquals(testArray.length + 3, list.size()); - for (int j = 0; j < list.size(); j++) - { - assertEquals(j - 1, list.get(j)); - } - - // add past end - try - { - list.add(list.size() + 1, 8); - fail("should have thrown exception"); - } - catch (IndexOutOfBoundsException e) - { - - // as expected - } - - // test growth - list = new IntList(0); - for (int j = 0; j < 1000; j++) - { - list.add(j); - } - assertEquals(1000, list.size()); - for (int j = 0; j < 1000; j++) - { - assertEquals(j, list.get(j)); - } - list = new IntList(0); - for (int j = 0; j < 1000; j++) - { - list.add(0, j); - } - assertEquals(1000, list.size()); - for (int j = 0; j < 1000; j++) - { - assertEquals(j, list.get(999 - j)); - } - } - - public void testAddAll() { - IntList list = new IntList(); - - for (int j = 0; j < 5; j++) - { - list.add(j); - } - IntList list2 = new IntList(0); - - list2.addAll(list); - list2.addAll(list); - assertEquals(2 * list.size(), list2.size()); - for (int j = 0; j < 5; j++) - { - assertEquals(list2.get(j), j); - assertEquals(list2.get(j + list.size()), j); - } - IntList empty = new IntList(); - int limit = list.size(); - - for (int j = 0; j < limit; j++) - { - assertTrue(list.addAll(j, empty)); - assertEquals(limit, list.size()); - } - try - { - list.addAll(limit + 1, empty); - fail("should have thrown an exception"); - } - catch (IndexOutOfBoundsException e) - { - - // as expected - } - - // try add at beginning - empty.addAll(0, list); - assertEquals(empty, list); - - // try in the middle - empty.addAll(1, list); - assertEquals(2 * list.size(), empty.size()); - assertEquals(list.get(0), empty.get(0)); - assertEquals(list.get(0), empty.get(1)); - assertEquals(list.get(1), empty.get(2)); - assertEquals(list.get(1), empty.get(6)); - assertEquals(list.get(2), empty.get(3)); - assertEquals(list.get(2), empty.get(7)); - assertEquals(list.get(3), empty.get(4)); - assertEquals(list.get(3), empty.get(8)); - assertEquals(list.get(4), empty.get(5)); - assertEquals(list.get(4), empty.get(9)); - - // try at the end - empty.addAll(empty.size(), list); - assertEquals(3 * list.size(), empty.size()); - assertEquals(list.get(0), empty.get(0)); - assertEquals(list.get(0), empty.get(1)); - assertEquals(list.get(0), empty.get(10)); - assertEquals(list.get(1), empty.get(2)); - assertEquals(list.get(1), empty.get(6)); - assertEquals(list.get(1), empty.get(11)); - assertEquals(list.get(2), empty.get(3)); - assertEquals(list.get(2), empty.get(7)); - assertEquals(list.get(2), empty.get(12)); - assertEquals(list.get(3), empty.get(4)); - assertEquals(list.get(3), empty.get(8)); - assertEquals(list.get(3), empty.get(13)); - assertEquals(list.get(4), empty.get(5)); - assertEquals(list.get(4), empty.get(9)); - assertEquals(list.get(4), empty.get(14)); - } - - public void testClear() { - IntList list = new IntList(); - - for (int j = 0; j < 500; j++) - { - list.add(j); - } - assertEquals(500, list.size()); - list.clear(); - assertEquals(0, list.size()); - for (int j = 0; j < 500; j++) - { - list.add(j + 1); - } - assertEquals(500, list.size()); - for (int j = 0; j < 500; j++) - { - assertEquals(j + 1, list.get(j)); - } - } - - public void testContains() { - IntList list = new IntList(); - - for (int j = 0; j < 1000; j += 2) - { - list.add(j); - } - for (int j = 0; j < 1000; j++) - { - if (j % 2 == 0) - { - assertTrue(list.contains(j)); - } - else - { - assertTrue(!list.contains(j)); - } - } - } - - public void testContainsAll() { - IntList list = new IntList(); - - assertTrue(list.containsAll(list)); - for (int j = 0; j < 10; j++) - { - list.add(j); - } - IntList list2 = new IntList(list); - - assertTrue(list2.containsAll(list)); - assertTrue(list.containsAll(list2)); - list2.add(10); - assertTrue(list2.containsAll(list)); - assertTrue(!list.containsAll(list2)); - list.add(11); - assertTrue(!list2.containsAll(list)); - assertTrue(!list.containsAll(list2)); - } - - public void testEquals() { - IntList list = new IntList(); - - assertEquals(list, list); - assertTrue(!list.equals(null)); - IntList list2 = new IntList(200); - - assertEquals(list, list2); - assertEquals(list2, list); - assertEquals(list.hashCode(), list2.hashCode()); - list.add(0); - list.add(1); - list2.add(1); - list2.add(0); - assertTrue(!list.equals(list2)); - list2.removeValue(1); - list2.add(1); - assertEquals(list, list2); - assertEquals(list2, list); - list2.add(2); - assertTrue(!list.equals(list2)); - assertTrue(!list2.equals(list)); - } - - public void testGet() { - IntList list = new IntList(); - - for (int j = 0; j < 1000; j++) - { - list.add(j); - } - for (int j = 0; j < 1001; j++) - { - try - { - assertEquals(j, list.get(j)); - if (j == 1000) - { - fail("should have gotten exception"); - } - } - catch (IndexOutOfBoundsException e) - { - if (j != 1000) - { - fail("unexpected IndexOutOfBoundsException"); - } - } - } - } - - public void testIndexOf() { - IntList list = new IntList(); - - for (int j = 0; j < 1000; j++) - { - list.add(j / 2); - } - for (int j = 0; j < 1000; j++) - { - if (j < 500) - { - assertEquals(j * 2, list.indexOf(j)); - } - else - { - assertEquals(-1, list.indexOf(j)); - } - } - } - - public void testIsEmpty() { - IntList list1 = new IntList(); - IntList list2 = new IntList(1000); - IntList list3 = new IntList(list1); - - assertTrue(list1.isEmpty()); - assertTrue(list2.isEmpty()); - assertTrue(list3.isEmpty()); - list1.add(1); - list2.add(2); - list3 = new IntList(list2); - assertTrue(!list1.isEmpty()); - assertTrue(!list2.isEmpty()); - assertTrue(!list3.isEmpty()); - list1.clear(); - list2.remove(0); - list3.removeValue(2); - assertTrue(list1.isEmpty()); - assertTrue(list2.isEmpty()); - assertTrue(list3.isEmpty()); - } - - public void testLastIndexOf() { - IntList list = new IntList(); - - for (int j = 0; j < 1000; j++) - { - list.add(j / 2); - } - for (int j = 0; j < 1000; j++) - { - if (j < 500) - { - assertEquals(1 + j * 2, list.lastIndexOf(j)); - } - else - { - assertEquals(-1, list.indexOf(j)); - } - } - } - - public void testRemove() { - IntList list = new IntList(); - - for (int j = 0; j < 1000; j++) - { - list.add(j); - } - for (int j = 0; j < 1000; j++) - { - assertEquals(j, list.remove(0)); - assertEquals(999 - j, list.size()); - } - for (int j = 0; j < 1000; j++) - { - list.add(j); - } - for (int j = 0; j < 1000; j++) - { - assertEquals(999 - j, list.remove(999 - j)); - assertEquals(999 - j, list.size()); - } - try - { - list.remove(0); - fail("should have caught IndexOutOfBoundsException"); - } - catch (IndexOutOfBoundsException e) - { - - // as expected - } - } - - public void testRemoveValue() { - IntList list = new IntList(); - - for (int j = 0; j < 1000; j++) - { - list.add(j / 2); - } - for (int j = 0; j < 1000; j++) - { - if (j < 500) - { - assertTrue(list.removeValue(j)); - assertTrue(list.removeValue(j)); - } - assertTrue(!list.removeValue(j)); - } - } - - public void testRemoveAll() { - IntList list = new IntList(); - - for (int j = 0; j < 1000; j++) - { - list.add(j); - } - IntList listCopy = new IntList(list); - IntList listOdd = new IntList(); - IntList listEven = new IntList(); - - for (int j = 0; j < 1000; j++) - { - if (j % 2 == 0) - { - listEven.add(j); - } - else - { - listOdd.add(j); - } - } - list.removeAll(listEven); - assertEquals(list, listOdd); - list.removeAll(listOdd); - assertTrue(list.isEmpty()); - listCopy.removeAll(listOdd); - assertEquals(listCopy, listEven); - listCopy.removeAll(listEven); - assertTrue(listCopy.isEmpty()); - } - - public void testRetainAll() { - IntList list = new IntList(); - - for (int j = 0; j < 1000; j++) - { - list.add(j); - } - IntList listCopy = new IntList(list); - IntList listOdd = new IntList(); - IntList listEven = new IntList(); - - for (int j = 0; j < 1000; j++) - { - if (j % 2 == 0) - { - listEven.add(j); - } - else - { - listOdd.add(j); - } - } - list.retainAll(listOdd); - assertEquals(list, listOdd); - list.retainAll(listEven); - assertTrue(list.isEmpty()); - listCopy.retainAll(listEven); - assertEquals(listCopy, listEven); - listCopy.retainAll(listOdd); - assertTrue(listCopy.isEmpty()); - } - - public void testSet() { - IntList list = new IntList(); - - for (int j = 0; j < 1000; j++) - { - list.add(j); - } - for (int j = 0; j < 1001; j++) - { - try - { - list.set(j, j + 1); - if (j == 1000) - { - fail("Should have gotten exception"); - } - assertEquals(j + 1, list.get(j)); - } - catch (IndexOutOfBoundsException e) - { - if (j != 1000) - { - fail("premature exception"); - } - } - } - } - - public void testSize() { - IntList list = new IntList(); - - for (int j = 0; j < 1000; j++) - { - assertEquals(j, list.size()); - list.add(j); - assertEquals(j + 1, list.size()); - } - for (int j = 0; j < 1000; j++) - { - assertEquals(1000 - j, list.size()); - list.removeValue(j); - assertEquals(999 - j, list.size()); - } - } - - public void testToArray() { - IntList list = new IntList(); - - for (int j = 0; j < 1000; j++) - { - list.add(j); - } - int[] a1 = list.toArray(); - - assertEquals(a1.length, list.size()); - for (int j = 0; j < 1000; j++) - { - assertEquals(a1[ j ], list.get(j)); - } - int[] a2 = new int[ list.size() ]; - int[] a3 = list.toArray(a2); - - assertSame(a2, a3); - for (int j = 0; j < 1000; j++) - { - assertEquals(a2[ j ], list.get(j)); - } - int[] aShort = new int[ list.size() - 1 ]; - int[] aLong = new int[ list.size() + 1 ]; - int[] a4 = list.toArray(aShort); - int[] a5 = list.toArray(aLong); - - assertTrue(a4 != aShort); - assertTrue(a5 != aLong); - assertEquals(a4.length, list.size()); - for (int j = 0; j < 1000; j++) - { - assertEquals(a3[ j ], list.get(j)); - } - assertEquals(a5.length, list.size()); - for (int j = 0; j < 1000; j++) - { - assertEquals(a5[ j ], list.get(j)); - } - } -} diff --git a/src/testcases/org/apache/poi/util/TestIntegerField.java b/src/testcases/org/apache/poi/util/TestIntegerField.java deleted file mode 100644 index 228d398ea..000000000 --- a/src/testcases/org/apache/poi/util/TestIntegerField.java +++ /dev/null @@ -1,186 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.util; - -import java.io.ByteArrayInputStream; -import java.io.IOException; - -import junit.framework.TestCase; - -/** - * Test IntegerField code - * - * @author Marc Johnson (mjohnson at apache dot org) - */ -public final class TestIntegerField extends TestCase { - - private static final int[] _test_array = - { - Integer.MIN_VALUE, -1, 0, 1, Integer.MAX_VALUE - }; - - public void testConstructors() { - try - { - new IntegerField(-1); - fail("Should have caught ArrayIndexOutOfBoundsException"); - } - catch (ArrayIndexOutOfBoundsException ignored_e) - { - - // as expected - } - IntegerField field = new IntegerField(2); - - assertEquals(0, field.get()); - try - { - new IntegerField(-1, 1); - fail("Should have caught ArrayIndexOutOfBoundsException"); - } - catch (ArrayIndexOutOfBoundsException ignored_e) - { - - // as expected - } - field = new IntegerField(2, 0x12345678); - assertEquals(0x12345678, field.get()); - byte[] array = new byte[ 6 ]; - - try - { - new IntegerField(-1, 1, array); - fail("Should have caught ArrayIndexOutOfBoundsException"); - } - catch (ArrayIndexOutOfBoundsException ignored_e) - { - - // as expected - } - field = new IntegerField(2, 0x12345678, array); - assertEquals(0x12345678, field.get()); - assertEquals(( byte ) 0x78, array[ 2 ]); - assertEquals(( byte ) 0x56, array[ 3 ]); - assertEquals(( byte ) 0x34, array[ 4 ]); - assertEquals(( byte ) 0x12, array[ 5 ]); - array = new byte[ 5 ]; - try - { - new IntegerField(2, 5, array); - fail("should have gotten ArrayIndexOutOfBoundsException"); - } - catch (ArrayIndexOutOfBoundsException ignored_e) - { - - // as expected - } - for (int element : _test_array) { - array = new byte[ 4 ]; - new IntegerField(0, element, array); - assertEquals(element, new IntegerField(0, array).get()); - } - } - - public void testSet() { - IntegerField field = new IntegerField(0); - byte[] array = new byte[ 4 ]; - - for (int j = 0; j < _test_array.length; j++) - { - field.set(_test_array[ j ]); - assertEquals("testing _1 " + j, _test_array[ j ], field.get()); - field = new IntegerField(0); - field.set(_test_array[ j ], array); - assertEquals("testing _2 ", _test_array[ j ], field.get()); - assertEquals("testing _3.0 " + _test_array[ j ], - ( byte ) (_test_array[ j ] % 256), array[ 0 ]); - assertEquals("testing _3.1 " + _test_array[ j ], - ( byte ) ((_test_array[ j ] >> 8) % 256), - array[ 1 ]); - assertEquals("testing _3.2 " + _test_array[ j ], - ( byte ) ((_test_array[ j ] >> 16) % 256), - array[ 2 ]); - assertEquals("testing _3.3 " + _test_array[ j ], - ( byte ) ((_test_array[ j ] >> 24) % 256), - array[ 3 ]); - } - } - - public void testReadFromBytes() { - IntegerField field = new IntegerField(1); - byte[] array = new byte[ 4 ]; - - try - { - field.readFromBytes(array); - fail("should have caught ArrayIndexOutOfBoundsException"); - } - catch (ArrayIndexOutOfBoundsException ignored_e) - { - - // as expected - } - field = new IntegerField(0); - for (int j = 0; j < _test_array.length; j++) - { - array[ 0 ] = ( byte ) (_test_array[ j ] % 256); - array[ 1 ] = ( byte ) ((_test_array[ j ] >> 8) % 256); - array[ 2 ] = ( byte ) ((_test_array[ j ] >> 16) % 256); - array[ 3 ] = ( byte ) ((_test_array[ j ] >> 24) % 256); - field.readFromBytes(array); - assertEquals("testing " + j, _test_array[ j ], field.get()); - } - } - - public void testReadFromStream() throws IOException { - IntegerField field = new IntegerField(0); - byte[] buffer = new byte[ _test_array.length * 4 ]; - - for (int j = 0; j < _test_array.length; j++) - { - buffer[ (j * 4) + 0 ] = ( byte ) (_test_array[ j ] % 256); - buffer[ (j * 4) + 1 ] = ( byte ) ((_test_array[ j ] >> 8) % 256); - buffer[ (j * 4) + 2 ] = ( byte ) ((_test_array[ j ] >> 16) % 256); - buffer[ (j * 4) + 3 ] = ( byte ) ((_test_array[ j ] >> 24) % 256); - } - ByteArrayInputStream stream = new ByteArrayInputStream(buffer); - - for (int j = 0; j < buffer.length / 4; j++) - { - field.readFromStream(stream); - assertEquals("Testing " + j, _test_array[ j ], field.get()); - } - } - - public void testWriteToBytes() { - IntegerField field = new IntegerField(0); - byte[] array = new byte[ 4 ]; - - for (int b : _test_array) { - field.set(b); - field.writeToBytes(array); - int val = array[ 3 ] << 24; - - val &= 0xFF000000; - val += (array[ 2 ] << 16) & 0x00FF0000; - val += (array[ 1 ] << 8) & 0x0000FF00; - val += (array[ 0 ] & 0x000000FF); - assertEquals("testing ", b, val); - } - } -} diff --git a/src/testcases/org/apache/poi/util/TestLittleEndian.java b/src/testcases/org/apache/poi/util/TestLittleEndian.java deleted file mode 100644 index e6b7b46c4..000000000 --- a/src/testcases/org/apache/poi/util/TestLittleEndian.java +++ /dev/null @@ -1,364 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.util; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.util.LittleEndian.BufferUnderrunException; -import org.junit.Test; - -/** - * Class to test LittleEndian functionality - */ -public final class TestLittleEndian { - - /** - * test the getShort() method - */ - @Test - public void testGetShort() { - byte[] testdata = new byte[ LittleEndianConsts.SHORT_SIZE + 1 ]; - - testdata[0] = 0x01; - testdata[1] = (byte) 0xFF; - testdata[2] = 0x02; - short expected[] = new short[2]; - - expected[0] = ( short ) 0xFF01; - expected[1] = 0x02FF; - assertEquals(expected[0], LittleEndian.getShort(testdata)); - assertEquals(expected[1], LittleEndian.getShort(testdata, 1)); - } - - @Test - public void testGetUShort() { - byte[] testdata = { - (byte) 0x01, - (byte) 0xFF, - (byte) 0x02, - }; - byte[] testdata2 = { - (byte) 0x0D, - (byte) 0x93, - (byte) 0xFF, - }; - - int expected0 = 0xFF01; - int expected1 = 0x02FF; - int expected2 = 0x930D; - int expected3 = 0xFF93; - assertEquals(expected0, LittleEndian.getUShort(testdata)); - assertEquals(expected1, LittleEndian.getUShort(testdata, 1)); - assertEquals(expected2, LittleEndian.getUShort(testdata2)); - assertEquals(expected3, LittleEndian.getUShort(testdata2, 1)); - - byte[] testdata3 = new byte[ LittleEndianConsts.SHORT_SIZE + 1 ]; - LittleEndian.putUShort(testdata3, 0, expected2); - LittleEndian.putUShort(testdata3, 1, expected3); - assertEquals(testdata3[0], 0x0D); - assertEquals(testdata3[1], (byte)0x93); - assertEquals(testdata3[2], (byte)0xFF); - assertEquals(expected2, LittleEndian.getUShort(testdata3)); - assertEquals(expected3, LittleEndian.getUShort(testdata3, 1)); - - } - - private static final byte[] _double_array = - { - 56, 50, -113, -4, -63, -64, -13, 63, 76, -32, -42, -35, 60, -43, 3, 64 - }; - /** 0x7ff8000000000000 encoded in little endian order */ - private static final byte[] _nan_double_array = HexRead.readFromString("00 00 00 00 00 00 F8 7F"); - private static final double[] _doubles = - { - 1.23456, 2.47912, Double.NaN - }; - - /** - * test the getDouble() method - */ - @Test - public void testGetDouble() { - assertEquals(_doubles[0], LittleEndian.getDouble(_double_array, 0), 0.000001 ); - assertEquals(_doubles[1], LittleEndian.getDouble( _double_array, LittleEndianConsts.DOUBLE_SIZE), 0.000001); - assertTrue(Double.isNaN(LittleEndian.getDouble(_nan_double_array, 0))); - - double nan = LittleEndian.getDouble(_nan_double_array, 0); - byte[] data = new byte[8]; - LittleEndian.putDouble(data, 0, nan); - for ( int i = 0; i < data.length; i++ ) { - assertEquals(data[i], _nan_double_array[i]); - } - } - - /** - * test the getInt() method - */ - @Test - public void testGetInt() { - // reading 4 byte data from a 5 byte buffer - byte[] testdata = { - (byte) 0x01, - (byte) 0xFF, - (byte) 0xFF, - (byte) 0xFF, - (byte) 0x02, - }; - - assertEquals(0xFFFFFF01, LittleEndian.getInt(testdata)); - assertEquals(0x02FFFFFF, LittleEndian.getInt(testdata, 1)); - } - - /** - * test the getLong method - */ - @Test - public void testGetLong() { - - // reading 8 byte values from a 9 byte buffer - byte[] testdata = { - (byte) 0x01, - (byte) 0xFF, - (byte) 0xFF, - (byte) 0xFF, - (byte) 0xFF, - (byte) 0xFF, - (byte) 0xFF, - (byte) 0xFF, - (byte) 0x02, - }; - - assertEquals(0xFFFFFFFFFFFFFF01L, LittleEndian.getLong(testdata, 0)); - assertEquals(0x02FFFFFFFFFFFFFFL, LittleEndian.getLong(testdata, 1)); - } - - /** - * test the PutShort method - */ - @Test - public void testPutShort() { - byte[] expected = new byte[ LittleEndianConsts.SHORT_SIZE + 1 ]; - - expected[0] = 0x01; - expected[1] = (byte) 0xFF; - expected[2] = 0x02; - byte[] received = new byte[ LittleEndianConsts.SHORT_SIZE + 1 ]; - short testdata[] = new short[2]; - - testdata[0] = ( short ) 0xFF01; - testdata[1] = 0x02FF; - LittleEndian.putShort(received, 0, testdata[0]); - assertTrue(compareByteArrays(received, expected, 0, LittleEndianConsts.SHORT_SIZE)); - LittleEndian.putShort(received, 1, testdata[1]); - assertTrue(compareByteArrays(received, expected, 1, LittleEndianConsts.SHORT_SIZE)); - } - - /** - * test the putInt method - */ - @Test - public void testPutInt() { - // writing 4 byte data to a 5 byte buffer - byte[] expected = { - (byte) 0x01, - (byte) 0xFF, - (byte) 0xFF, - (byte) 0xFF, - (byte) 0x02, - }; - byte[] received = new byte[ LittleEndianConsts.INT_SIZE + 1 ]; - - LittleEndian.putInt(received, 0, 0xFFFFFF01); - assertTrue(compareByteArrays(received, expected, 0, LittleEndianConsts.INT_SIZE)); - LittleEndian.putInt(received, 1, 0x02FFFFFF); - assertTrue(compareByteArrays(received, expected, 1, LittleEndianConsts.INT_SIZE)); - } - - /** - * test the putDouble methods - */ - @Test - public void testPutDouble() { - byte[] received = new byte[ LittleEndianConsts.DOUBLE_SIZE + 1 ]; - - LittleEndian.putDouble(received, 0, _doubles[0]); - assertTrue(compareByteArrays(received, _double_array, 0, LittleEndianConsts.DOUBLE_SIZE)); - LittleEndian.putDouble(received, 1, _doubles[1]); - byte[] expected = new byte[ LittleEndianConsts.DOUBLE_SIZE + 1 ]; - - System.arraycopy(_double_array, LittleEndianConsts.DOUBLE_SIZE, expected, - 1, LittleEndianConsts.DOUBLE_SIZE); - assertTrue(compareByteArrays(received, expected, 1, LittleEndianConsts.DOUBLE_SIZE)); - } - - /** - * test the putLong method - */ - @Test - public void testPutLong() { - // writing 8 byte values to a 9 byte buffer - byte[] expected = { - (byte) 0x01, - (byte) 0xFF, - (byte) 0xFF, - (byte) 0xFF, - (byte) 0xFF, - (byte) 0xFF, - (byte) 0xFF, - (byte) 0xFF, - (byte) 0x02, - }; - byte[] received = new byte[ LittleEndianConsts.LONG_SIZE + 1 ]; - - long testdata0 = 0xFFFFFFFFFFFFFF01L; - long testdata1 = 0x02FFFFFFFFFFFFFFL; - LittleEndian.putLong(received, 0, testdata0); - assertTrue(compareByteArrays(received, expected, 0, LittleEndianConsts.LONG_SIZE)); - LittleEndian.putLong(received, 1, testdata1); - assertTrue(compareByteArrays(received, expected, 1, LittleEndianConsts.LONG_SIZE)); - } - - private static byte[] _good_array = { - 0x01, 0x02, 0x01, 0x02, - 0x01, 0x02, 0x01, 0x02, - 0x01, 0x02, 0x01, 0x02, - 0x01, 0x02, 0x01, 0x02, - }; - private static byte[] _bad_array = { - 0x01 - }; - - /** - * test the readShort method - */ - @Test - public void testReadShort() throws IOException { - short expected_value = 0x0201; - InputStream stream = new ByteArrayInputStream(_good_array); - int count = 0; - - while (stream.available() > 0) { - short value = LittleEndian.readShort(stream); - assertEquals(value, expected_value); - count++; - } - assertEquals(count, - _good_array.length / LittleEndianConsts.SHORT_SIZE); - stream = new ByteArrayInputStream(_bad_array); - try { - LittleEndian.readShort(stream); - fail("Should have caught BufferUnderrunException"); - } catch (BufferUnderrunException ignored) { - // as expected - } - } - - /** - * test the readInt method - */ - @Test - public void testReadInt() throws IOException { - int expected_value = 0x02010201; - InputStream stream = new ByteArrayInputStream(_good_array); - int count = 0; - - while (stream.available() > 0) { - int value = LittleEndian.readInt(stream); - assertEquals(value, expected_value); - count++; - } - assertEquals(count, _good_array.length / LittleEndianConsts.INT_SIZE); - stream = new ByteArrayInputStream(_bad_array); - try { - LittleEndian.readInt(stream); - fail("Should have caught BufferUnderrunException"); - } catch (BufferUnderrunException ignored) { - - // as expected - } - } - - /** - * test the readLong method - */ - @Test - public void testReadLong() throws IOException { - long expected_value = 0x0201020102010201L; - InputStream stream = new ByteArrayInputStream(_good_array); - int count = 0; - - while (stream.available() > 0) { - long value = LittleEndian.readLong(stream); - assertEquals(value, expected_value); - count++; - } - assertEquals(count, - _good_array.length / LittleEndianConsts.LONG_SIZE); - stream = new ByteArrayInputStream(_bad_array); - try { - LittleEndian.readLong(stream); - fail("Should have caught BufferUnderrunException"); - } catch (BufferUnderrunException ignored) { - // as expected - } - } - -// public void testReadFromStream() throws IOException { -// int actual; -// actual = LittleEndian.readUShort(new ByteArrayInputStream(new byte[] { 5, -128, })); -// assertEquals(32773, actual); -// -// actual = LittleEndian.readUShort(new ByteArrayInputStream(new byte[] { 1, 2, 3, 4, })); -// assertEquals(513, actual); -// -// try { -// LittleEndian.readInt(new ByteArrayInputStream(new byte[] { 1, 2, 3, })); -// fail("Should have caught BufferUnderrunException"); -// } catch (BufferUnderrunException ignored) { -// // as expected -// } -// } - - @Test - public void testUnsignedByteToInt() { - assertEquals(255, LittleEndian.ubyteToInt((byte)255)); - } - - private static boolean compareByteArrays(byte [] received, byte [] expected, - int offset, int size) { - - for (int j = offset; j < offset + size; j++) { - if (received[j] != expected[j]) { - System.out.println("difference at index " + j); - return false; - } - } - return true; - } - - @Test - public void testUnsignedShort() { - assertEquals(0xffff, LittleEndian.getUShort(new byte[] { (byte)0xff, (byte)0xff }, 0)); - } -} diff --git a/src/testcases/org/apache/poi/util/TestLittleEndianCP950Reader.java b/src/testcases/org/apache/poi/util/TestLittleEndianCP950Reader.java deleted file mode 100644 index 96106dc75..000000000 --- a/src/testcases/org/apache/poi/util/TestLittleEndianCP950Reader.java +++ /dev/null @@ -1,77 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.util; - - -import static org.junit.Assert.assertEquals; - -import java.io.IOException; -import java.io.Reader; - -import org.junit.Test; - -public class TestLittleEndianCP950Reader { - - @Test - public void testPersonalUseMappings() throws Exception { - //ftp://ftp.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WindowsBestFit/bestfit950.txt - byte[] data = new byte[2]; - data[1] = (byte) 0xfe; - data[0] = (byte) 0xd3; - assertCharEquals('\uE2E5', data); - - data[1] = (byte) 0x90; - data[0] = (byte) 0xb6; - assertCharEquals('\uE49F', data); - - //actually found in document - //but this disagrees with file above - data[1] = (byte) 0x8E; - data[0] = (byte) 0xA8; - assertCharEquals('\uE357', data); - - data[1] = (byte) 0x8E; - data[0] = (byte) 0xE6; - assertCharEquals('\uE395', data); - - /* - //TODO: figure out why this isn't working - data[0] = (byte)0xF9; - data[1] = (byte)0xD8; - assertCharEquals('\u88CF', data); - */ - - } - - @Test - public void one() { - byte b = (byte) 0xfe; - byte c = (byte) 0xd3; - - int i = ((b & 0xff) << 8) + (c & 0xff); - System.out.println(i); - } - - private void assertCharEquals(char expected, byte[] data) throws IOException { - Reader reader = new LittleEndianCP950Reader(data); - int c = reader.read(); - assertEquals((int) expected, c); - int eof = reader.read(); - assertEquals("should be end of stream", -1, eof); - } -} diff --git a/src/testcases/org/apache/poi/util/TestLittleEndianStreams.java b/src/testcases/org/apache/poi/util/TestLittleEndianStreams.java deleted file mode 100644 index c05e365a9..000000000 --- a/src/testcases/org/apache/poi/util/TestLittleEndianStreams.java +++ /dev/null @@ -1,84 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.util; - -import static org.junit.Assert.assertArrayEquals; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -/** - * Class to test {@link LittleEndianInputStream} and {@link LittleEndianOutputStream} - * - * @author Josh Micich - */ -public final class TestLittleEndianStreams extends TestCase { - - public void testRead() throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - LittleEndianOutput leo = new LittleEndianOutputStream(baos); - leo.writeInt(12345678); - leo.writeShort(12345); - leo.writeByte(123); - leo.writeShort(40000); - leo.writeByte(200); - leo.writeLong(1234567890123456789L); - leo.writeDouble(123.456); - ((LittleEndianOutputStream)leo).close(); - - LittleEndianInput lei = new LittleEndianInputStream(new ByteArrayInputStream(baos.toByteArray())); - - assertEquals(12345678, lei.readInt()); - assertEquals(12345, lei.readShort()); - assertEquals(123, lei.readByte()); - assertEquals(40000, lei.readUShort()); - assertEquals(200, lei.readUByte()); - assertEquals(1234567890123456789L, lei.readLong()); - assertEquals(123.456, lei.readDouble(), 0.0); - ((LittleEndianInputStream)lei).close(); - } - - /** - * Up until svn r836101 {@link LittleEndianByteArrayInputStream#readFully(byte[], int, int)} - * had an error which resulted in the data being read and written back to the source byte - * array. - */ - public void testReadFully() { - byte[] srcBuf = HexRead.readFromString("99 88 77 66 55 44 33"); - LittleEndianInput lei = new LittleEndianByteArrayInputStream(srcBuf); - - // do initial read to increment the read index beyond zero - assertEquals(0x8899, lei.readUShort()); - - byte[] actBuf = new byte[4]; - lei.readFully(actBuf); - - if (actBuf[0] == 0x00 && srcBuf[0] == 0x77 && srcBuf[3] == 0x44) { - throw new AssertionFailedError("Identified bug in readFully() - source buffer was modified"); - } - - byte[] expBuf = HexRead.readFromString("77 66 55 44"); - assertArrayEquals(actBuf, expBuf); - assertEquals(0x33, lei.readUByte()); - assertEquals(0, lei.available()); - } -} diff --git a/src/testcases/org/apache/poi/util/TestLocaleUtil.java b/src/testcases/org/apache/poi/util/TestLocaleUtil.java deleted file mode 100644 index 3a7c65a6a..000000000 --- a/src/testcases/org/apache/poi/util/TestLocaleUtil.java +++ /dev/null @@ -1,127 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.util; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assume.assumeFalse; - -import java.util.Calendar; -import java.util.Locale; -import java.util.TimeZone; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - - -public class TestLocaleUtil { - // This unit test assumes that the user's locale isn't ja-JP and timezone isn't Asia/Tokyo - // If this is the case, change the values to something else - private static final Locale ja_JP = Locale.JAPAN; - private static final TimeZone TOKYO = TimeZone.getTimeZone("Asia/Tokyo"); - private static final Calendar JAPAN_CALENDAR = Calendar.getInstance(TOKYO, ja_JP); - - /** - * Reset the Locale to the user default before the test so that it isn't influenced - * by the LocaleUtil's state being changed by previous tests. - */ - @Before - @SuppressForbidden("implementation around default locales in POI") - public void setUp() { - // reset the user locale and time zone so that tests do not interfere with each other - // the other and better way would be to run each test in its own thread since - // LocaleUtil uses per-thread settings. - // Helpful, but not ASL 2.0 licensed: - // http://www.codeaffine.com/2014/07/21/a-junit-rule-to-run-a-test-in-its-own-thread/ - LocaleUtil.setUserLocale(Locale.getDefault()); - LocaleUtil.setUserTimeZone(TimeZone.getDefault()); - - assumeFalse(ja_JP.equals(LocaleUtil.getUserLocale())); - assumeFalse(TOKYO.equals(LocaleUtil.getUserTimeZone())); - } - - /** - * Reset the Locale to the user default after the test so that it doesn't influence - * other tests. - */ - @After - public void tearDown() { - LocaleUtil.resetUserLocale(); - LocaleUtil.resetUserTimeZone(); - } - - @Test - @SuppressForbidden("implementation around default locales in POI") - public void userLocale() { - Locale DEFAULT_LOCALE = LocaleUtil.getUserLocale(); - - assertEquals(DEFAULT_LOCALE, LocaleUtil.getUserLocale()); - assertNotEquals(ja_JP, LocaleUtil.getUserLocale()); - - LocaleUtil.setUserLocale(ja_JP); - assertEquals(ja_JP, LocaleUtil.getUserLocale()); - - LocaleUtil.resetUserLocale(); - assertEquals(DEFAULT_LOCALE, LocaleUtil.getUserLocale()); - } - - @Test - @SuppressForbidden("implementation around default locales in POI") - public void userTimeZone() { - TimeZone DEFAULT_TIME_ZONE = LocaleUtil.getUserTimeZone(); - - assertEquals(DEFAULT_TIME_ZONE, LocaleUtil.getUserTimeZone()); - assertNotEquals(TOKYO, LocaleUtil.getUserLocale()); - - LocaleUtil.setUserTimeZone(TOKYO); - assertEquals(TOKYO, LocaleUtil.getUserTimeZone()); - } - - @Test - @SuppressForbidden("implementation around default locales in POI") - public void localeCalendar() { - Locale DEFAULT_LOCALE = LocaleUtil.getUserLocale(); - TimeZone DEFAULT_TIME_ZONE = LocaleUtil.getUserTimeZone(); - Calendar DEFAULT_CALENDAR = LocaleUtil.getLocaleCalendar(); - - assertEquals(DEFAULT_LOCALE, LocaleUtil.getUserLocale()); - assertEquals(DEFAULT_TIME_ZONE, LocaleUtil.getUserTimeZone()); - assertCalendarEquals(DEFAULT_CALENDAR, LocaleUtil.getLocaleCalendar()); - assertNotEquals(ja_JP, LocaleUtil.getUserLocale()); - assertNotEquals(TOKYO, LocaleUtil.getUserTimeZone()); - assertCalendarNotEquals(JAPAN_CALENDAR, LocaleUtil.getLocaleCalendar()); - - LocaleUtil.setUserLocale(ja_JP); - LocaleUtil.setUserTimeZone(TOKYO); - assertCalendarEquals(JAPAN_CALENDAR, LocaleUtil.getLocaleCalendar()); - assertCalendarEquals(JAPAN_CALENDAR, LocaleUtil.getLocaleCalendar(TOKYO)); - // FIXME: These might affect the time zone due to daylight savings: - //assertCalendarEquals(JAPAN_CALENDAR, LocaleUtil.getLocaleCalendar(2016, 00, 01)); - //assertCalendarEquals(JAPAN_CALENDAR, LocaleUtil.getLocaleCalendar(2016, 00, 01, 00, 00, 00)); - } - - private static void assertCalendarNotEquals(Calendar expected, Calendar actual) { - // FIXME: add more tests to compare calendars, ignoring whether the dates are equal - assertNotEquals("time zone", expected.getTimeZone(), actual.getTimeZone()); - } - private static void assertCalendarEquals(Calendar expected, Calendar actual) { - // FIXME: add more tests to compare calendars, ignoring whether the set dates are equal - assertEquals("time zone", expected.getTimeZone(), actual.getTimeZone()); - } -} diff --git a/src/testcases/org/apache/poi/util/TestLongField.java b/src/testcases/org/apache/poi/util/TestLongField.java deleted file mode 100644 index f613bae1c..000000000 --- a/src/testcases/org/apache/poi/util/TestLongField.java +++ /dev/null @@ -1,219 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.util; - -import junit.framework.*; - -import java.io.*; - -/** - * Test LongField code - * - * @author Marc Johnson (mjohnson at apache dot org) - */ -public final class TestLongField extends TestCase { - - static private final long[] _test_array = - { - Long.MIN_VALUE, -1L, 0L, 1L, Long.MAX_VALUE - }; - - public void testConstructors() - { - try - { - new LongField(-1); - fail("Should have caught ArrayIndexOutOfBoundsException"); - } - catch (ArrayIndexOutOfBoundsException ignored_e) - { - - // as expected - } - LongField field = new LongField(2); - - assertEquals(0L, field.get()); - try - { - new LongField(-1, 1L); - fail("Should have caught ArrayIndexOutOfBoundsException"); - } - catch (ArrayIndexOutOfBoundsException ignored_e) - { - - // as expected - } - field = new LongField(2, 0x123456789ABCDEF0L); - assertEquals(0x123456789ABCDEF0L, field.get()); - byte[] array = new byte[ 10 ]; - - try - { - new LongField(-1, 1L, array); - fail("Should have caught ArrayIndexOutOfBoundsException"); - } - catch (ArrayIndexOutOfBoundsException ignored_e) - { - - // as expected - } - field = new LongField(2, 0x123456789ABCDEF0L, array); - assertEquals(0x123456789ABCDEF0L, field.get()); - assertEquals(( byte ) 0xF0, array[ 2 ]); - assertEquals(( byte ) 0xDE, array[ 3 ]); - assertEquals(( byte ) 0xBC, array[ 4 ]); - assertEquals(( byte ) 0x9A, array[ 5 ]); - assertEquals(( byte ) 0x78, array[ 6 ]); - assertEquals(( byte ) 0x56, array[ 7 ]); - assertEquals(( byte ) 0x34, array[ 8 ]); - assertEquals(( byte ) 0x12, array[ 9 ]); - array = new byte[ 9 ]; - try - { - new LongField(2, 5L, array); - fail("should have gotten ArrayIndexOutOfBoundsException"); - } - catch (ArrayIndexOutOfBoundsException ignored_e) - { - - // as expected - } - for (long element : _test_array) { - array = new byte[ 8 ]; - new LongField(0, element, array); - assertEquals(element, new LongField(0, array).get()); - } - } - - public void testSet() - { - LongField field = new LongField(0); - byte[] array = new byte[ 8 ]; - - for (int j = 0; j < _test_array.length; j++) - { - field.set(_test_array[ j ]); - assertEquals("testing _1 " + j, _test_array[ j ], field.get()); - field = new LongField(0); - field.set(_test_array[ j ], array); - assertEquals("testing _2 ", _test_array[ j ], field.get()); - assertEquals("testing _3.0 " + _test_array[ j ], - ( byte ) (_test_array[ j ] % 256), array[ 0 ]); - assertEquals("testing _3.1 " + _test_array[ j ], - ( byte ) ((_test_array[ j ] >> 8) % 256), - array[ 1 ]); - assertEquals("testing _3.2 " + _test_array[ j ], - ( byte ) ((_test_array[ j ] >> 16) % 256), - array[ 2 ]); - assertEquals("testing _3.3 " + _test_array[ j ], - ( byte ) ((_test_array[ j ] >> 24) % 256), - array[ 3 ]); - assertEquals("testing _3.4 " + _test_array[ j ], - ( byte ) ((_test_array[ j ] >> 32) % 256), - array[ 4 ]); - assertEquals("testing _3.5 " + _test_array[ j ], - ( byte ) ((_test_array[ j ] >> 40) % 256), - array[ 5 ]); - assertEquals("testing _3.6 " + _test_array[ j ], - ( byte ) ((_test_array[ j ] >> 48) % 256), - array[ 6 ]); - assertEquals("testing _3.7 " + _test_array[ j ], - ( byte ) ((_test_array[ j ] >> 56) % 256), - array[ 7 ]); - } - } - - public void testReadFromBytes() - { - LongField field = new LongField(1); - byte[] array = new byte[ 8 ]; - - try - { - field.readFromBytes(array); - fail("should have caught ArrayIndexOutOfBoundsException"); - } - catch (ArrayIndexOutOfBoundsException ignored_e) - { - - // as expected - } - field = new LongField(0); - for (int j = 0; j < _test_array.length; j++) - { - array[ 0 ] = ( byte ) (_test_array[ j ] % 256); - array[ 1 ] = ( byte ) ((_test_array[ j ] >> 8) % 256); - array[ 2 ] = ( byte ) ((_test_array[ j ] >> 16) % 256); - array[ 3 ] = ( byte ) ((_test_array[ j ] >> 24) % 256); - array[ 4 ] = ( byte ) ((_test_array[ j ] >> 32) % 256); - array[ 5 ] = ( byte ) ((_test_array[ j ] >> 40) % 256); - array[ 6 ] = ( byte ) ((_test_array[ j ] >> 48) % 256); - array[ 7 ] = ( byte ) ((_test_array[ j ] >> 56) % 256); - field.readFromBytes(array); - assertEquals("testing " + j, _test_array[ j ], field.get()); - } - } - - public void testReadFromStream() - throws IOException - { - LongField field = new LongField(0); - byte[] buffer = new byte[ _test_array.length * 8 ]; - - for (int j = 0; j < _test_array.length; j++) - { - buffer[ (j * 8) + 0 ] = ( byte ) ((_test_array[ j ] >> 0) % 256); - buffer[ (j * 8) + 1 ] = ( byte ) ((_test_array[ j ] >> 8) % 256); - buffer[ (j * 8) + 2 ] = ( byte ) ((_test_array[ j ] >> 16) % 256); - buffer[ (j * 8) + 3 ] = ( byte ) ((_test_array[ j ] >> 24) % 256); - buffer[ (j * 8) + 4 ] = ( byte ) ((_test_array[ j ] >> 32) % 256); - buffer[ (j * 8) + 5 ] = ( byte ) ((_test_array[ j ] >> 40) % 256); - buffer[ (j * 8) + 6 ] = ( byte ) ((_test_array[ j ] >> 48) % 256); - buffer[ (j * 8) + 7 ] = ( byte ) ((_test_array[ j ] >> 56) % 256); - } - ByteArrayInputStream stream = new ByteArrayInputStream(buffer); - - for (int j = 0; j < buffer.length / 8; j++) - { - field.readFromStream(stream); - assertEquals("Testing " + j, _test_array[ j ], field.get()); - } - } - - public void testWriteToBytes() - { - LongField field = new LongField(0); - byte[] array = new byte[ 8 ]; - - for (long element : _test_array) { - field.set(element); - field.writeToBytes(array); - long val = (( long ) array[ 7 ]) << 56; - - val &= 0xFF00000000000000L; - val += ((( long ) array[ 6 ]) << 48) & 0x00FF000000000000L; - val += ((( long ) array[ 5 ]) << 40) & 0x0000FF0000000000L; - val += ((( long ) array[ 4 ]) << 32) & 0x000000FF00000000L; - val += ((( long ) array[ 3 ]) << 24) & 0x00000000FF000000L; - val += ((( long ) array[ 2 ]) << 16) & 0x0000000000FF0000L; - val += ((( long ) array[ 1 ]) << 8) & 0x000000000000FF00L; - val += (array[ 0 ] & 0x00000000000000FFL); - assertEquals("testing ", element, val); - } - } -} diff --git a/src/testcases/org/apache/poi/util/TestPOILogFactory.java b/src/testcases/org/apache/poi/util/TestPOILogFactory.java deleted file mode 100644 index 115ec733e..000000000 --- a/src/testcases/org/apache/poi/util/TestPOILogFactory.java +++ /dev/null @@ -1,54 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.util; - -import junit.framework.TestCase; - -/** - * @author Marc Johnson (mjohnson at apache dot org) - * @author Glen Stampoultzis (glens at apache.org) - * @author Nicola Ken Barozzi (nicolaken at apache.org) - */ -public final class TestPOILogFactory extends TestCase { - - - /** - * test log creation - */ - public void testLog() { - //NKB Testing only that logging classes use gives no exception - // Since logging can be disabled, no checking of logging - // output is done. - - POILogger l1 = POILogFactory.getLogger( "org.apache.poi.hssf.test" ); - POILogger l2 = POILogFactory.getLogger( "org.apache.poi.hdf.test" ); - - l1.log( POILogger.FATAL, "testing cat org.apache.poi.hssf.*:FATAL" ); - l1.log( POILogger.ERROR, "testing cat org.apache.poi.hssf.*:ERROR" ); - l1.log( POILogger.WARN, "testing cat org.apache.poi.hssf.*:WARN" ); - l1.log( POILogger.INFO, "testing cat org.apache.poi.hssf.*:INFO" ); - l1.log( POILogger.DEBUG, "testing cat org.apache.poi.hssf.*:DEBUG" ); - - l2.log( POILogger.FATAL, "testing cat org.apache.poi.hdf.*:FATAL" ); - l2.log( POILogger.ERROR, "testing cat org.apache.poi.hdf.*:ERROR" ); - l2.log( POILogger.WARN, "testing cat org.apache.poi.hdf.*:WARN" ); - l2.log( POILogger.INFO, "testing cat org.apache.poi.hdf.*:INFO" ); - l2.log( POILogger.DEBUG, "testing cat org.apache.poi.hdf.*:DEBUG" ); - - } -} diff --git a/src/testcases/org/apache/poi/util/TestPOILogger.java b/src/testcases/org/apache/poi/util/TestPOILogger.java deleted file mode 100644 index 6650ed9e6..000000000 --- a/src/testcases/org/apache/poi/util/TestPOILogger.java +++ /dev/null @@ -1,83 +0,0 @@ - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.util; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import org.junit.Test; - -/** - * Tests the log class. - */ -public final class TestPOILogger extends POILogger { - private String lastLog = ""; - private Throwable lastEx = null; - - /** - * Test different types of log output. - */ - @Test - public void testVariousLogTypes() throws Exception { - String oldLCN = POILogFactory._loggerClassName; - try { - POILogFactory._loggerClassName = TestPOILogger.class.getName(); - POILogger log = POILogFactory.getLogger( "foo" ); - assertTrue(log instanceof TestPOILogger); - - TestPOILogger tlog = (TestPOILogger)log; - - log.log(POILogger.WARN, "Test = ", 1); - assertEquals("Test = 1", tlog.lastLog); - - log.log(POILogger.ERROR, "Test ", 1,2,new Exception("bla")); - assertEquals("Test 12", tlog.lastLog); - assertNotNull(tlog.lastEx); - - log.log(POILogger.ERROR, "log\nforging", "\nevil","\nlog"); - assertEquals("log forging evil log", tlog.lastLog); - } finally { - POILogFactory._loggerClassName = oldLCN; - } - } - - // ---------- POI Logger methods implemented for testing ---------- - - @Override - public void initialize(String cat) { - } - - @Override - protected void _log(int level, Object obj1) { - lastLog = (obj1 == null) ? "" : obj1.toString(); - lastEx = null; - } - - @Override - protected void _log(int level, Object obj1, Throwable exception) { - lastLog = (obj1 == null) ? "" : obj1.toString(); - lastEx = exception; - } - - @Override - public boolean check(int level) { - return true; - } -} diff --git a/src/testcases/org/apache/poi/util/TestRLEDecompressingInputStream.java b/src/testcases/org/apache/poi/util/TestRLEDecompressingInputStream.java deleted file mode 100644 index b403fc53a..000000000 --- a/src/testcases/org/apache/poi/util/TestRLEDecompressingInputStream.java +++ /dev/null @@ -1,172 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.util; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.UnsupportedEncodingException; - -import org.junit.Test; - -public class TestRLEDecompressingInputStream { - - /** - * Section 3.2.1 No Compression Example - * - * The following string illustrates an ASCII text string with a set of characters that cannot be compressed - * by the compression algorithm specified in section 2.4.1. - * - * abcdefghijklmnopqrstuv. - * - * This example is provided to demonstrate the results of compressing and decompressing the string - * using an interoperable implementation of the algorithm specified in section 2.4.1. - * - * The following hex array represents the compressed byte array of the example string as compressed by - * the compression algorithm. - * - * 01 19 B0 00 61 62 63 64 65 66 67 68 00 69 6A 6B 6C - * 6D 6E 6F 70 00 71 72 73 74 75 76 2E - * - * The following hex array represents the decompressed byte array of the example string as - * decompressed by the decompression algorithm. - * - * 61 62 63 64 65 66 67 68 69 6A 6B 6C 6D 6E 6F 70 71 - * 72 73 74 75 76 2E - * - */ - @Test - public void noCompressionExample() { - final byte[] compressed = { - 0x01, 0x19, (byte)0xB0, 0x00, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x00, 0x69, 0x6A, 0x6B, 0x6C, - 0x6D, 0x6E, 0x6F, 0x70, 0x00, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x2E - }; - final String expected = "abcdefghijklmnopqrstuv."; - checkRLEDecompression(expected, compressed); - } - - /** - * Section 3.2.2 Normal Compression Example - * - * The following string illustrates an ASCII text string with a typical set of characters that can be - * compressed by the compression algorithm. - * - * #aaabcdefaaaaghijaaaaaklaaamnopqaaaaaaaaaaaarstuvwxyzaaa - * - * This example is provided to demonstrate the results of compressing and decompressing the example - * string using an interoperable implementation of the algorithm specified in section 2.4.1. - * - * The following hex array represents the compressed byte array of the example string as compressed by - * the compression algorithm: - * - * 01 2F B0 00 23 61 61 61 62 63 64 65 82 66 00 70 - * 61 67 68 69 6A 01 38 08 61 6B 6C 00 30 6D 6E 6F - * 70 06 71 02 70 04 10 72 73 74 75 76 10 77 78 79 - * 7A 00 3C - * - * The following hex array represents the decompressed byte array of the example string as - * decompressed by the decompression algorithm: - * - * 23 61 61 61 62 63 64 65 66 61 61 61 61 67 68 69 - * 6a 61 61 61 61 61 6B 6C 61 61 61 6D 6E 6F 70 71 - * 61 61 61 61 61 61 61 61 61 61 61 61 72 73 74 75 - * 76 77 78 79 7A 61 61 61 - */ - @Test - public void normalCompressionExample() { - final byte[] compressed = { - 0x01, 0x2F, (byte)0xB0, 0x00, 0x23, 0x61, 0x61, 0x61, 0x62, 0x63, 0x64, 0x65, (byte)0x82, 0x66, 0x00, 0x70, - 0x61, 0x67, 0x68, 0x69, 0x6A, 0x01, 0x38, 0x08, 0x61, 0x6B, 0x6C, 0x00, 0x30, 0x6D, 0x6E, 0x6F, - 0x70, 0x06, 0x71, 0x02, 0x70, 0x04, 0x10, 0x72, 0x73, 0x74, 0x75, 0x76, 0x10, 0x77, 0x78, 0x79, - 0x7A, 0x00, 0x3C - }; - final String expected = "#aaabcdefaaaaghijaaaaaklaaamnopqaaaaaaaaaaaarstuvwxyzaaa"; - checkRLEDecompression(expected, compressed); - } - - /** - * Section 3.2.3 Maximum Compression Example - * - * The following string illustrates an ASCII text string with a typical set of characters that can be - * compressed by the compression algorithm. - * - * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - * - * This example is provided to demonstrate the results of compressing and decompressing the example - * string using an interoperable implementation of the algorithm specified in section 2.4.1. - * - * The following hex array represents the compressed byte array of the example string as compressed by - * the compression algorithm: - * - * 01 03 B0 02 61 45 00 - * - * The following hex array represents the decompressed byte array of the example string as - * decompressed by the decompression algorithm: - * - * 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 - * 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 - * 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 - * 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 - * 61 61 61 61 61 61 61 61 61 - */ - @Test - public void maximumCompressionExample() { - final byte[] compressed = { - 0x01, 0x03, (byte)0xB0, 0x02, 0x61, 0x45, 0x00 - }; - final String expected = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; - checkRLEDecompression(expected, compressed); - } - - @Test - public void decompress() throws IOException { - final byte[] compressed = { - 0x01, 0x03, (byte)0xB0, 0x02, 0x61, 0x45, 0x00 - }; - final byte[] expanded = RLEDecompressingInputStream.decompress(compressed); - final byte[] expected = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".getBytes(StringUtil.UTF8); - assertArrayEquals(expected, expanded); - } - - private static void checkRLEDecompression(String expected, byte[] runLengthEncodedData) { - InputStream compressedStream = new ByteArrayInputStream(runLengthEncodedData); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - try { - InputStream stream = new RLEDecompressingInputStream(compressedStream); - try { - IOUtils.copy(stream, out); - } finally { - out.close(); - stream.close(); - } - } catch (final IOException e) { - throw new RuntimeException(e); - } - String expanded; - try { - expanded = out.toString(StringUtil.UTF8.name()); - } catch (final UnsupportedEncodingException e) { - throw new RuntimeException(e); - } - assertEquals(expected, expanded); - } -} diff --git a/src/testcases/org/apache/poi/util/TestShortField.java b/src/testcases/org/apache/poi/util/TestShortField.java deleted file mode 100644 index 9e1fec64b..000000000 --- a/src/testcases/org/apache/poi/util/TestShortField.java +++ /dev/null @@ -1,172 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.util; - -import junit.framework.*; - -import java.io.*; - -/** - * Test ShortField code - * - * @author Marc Johnson (mjohnson at apache dot org) - */ -public final class TestShortField extends TestCase { - - private static final short[] _test_array = - { - Short.MIN_VALUE, ( short ) -1, ( short ) 0, ( short ) 1, - Short.MAX_VALUE - }; - - public void testConstructors() { - try - { - new ShortField(-1); - fail("Should have caught ArrayIndexOutOfBoundsException"); - } - catch (ArrayIndexOutOfBoundsException ignored_e) - { - - // as expected - } - ShortField field = new ShortField(2); - - assertEquals(0, field.get()); - try - { - new ShortField(-1, ( short ) 1); - fail("Should have caught ArrayIndexOutOfBoundsException"); - } - catch (ArrayIndexOutOfBoundsException ignored_e) - { - - // as expected - } - field = new ShortField(2, ( short ) 0x1234); - assertEquals(0x1234, field.get()); - byte[] array = new byte[ 4 ]; - - try - { - new ShortField(-1, ( short ) 1, array); - fail("Should have caught ArrayIndexOutOfBoundsException"); - } - catch (ArrayIndexOutOfBoundsException ignored_e) - { - - // as expected - } - field = new ShortField(2, ( short ) 0x1234, array); - assertEquals(( short ) 0x1234, field.get()); - assertEquals(( byte ) 0x34, array[ 2 ]); - assertEquals(( byte ) 0x12, array[ 3 ]); - array = new byte[ 3 ]; - try - { - new ShortField(2, ( short ) 5, array); - fail("should have gotten ArrayIndexOutOfBoundsException"); - } - catch (ArrayIndexOutOfBoundsException ignored_e) - { - - // as expected - } - for (short element : _test_array) { - array = new byte[ 2 ]; - new ShortField(0, element, array); - assertEquals(element, new ShortField(0, array).get()); - } - } - - public void testSet() { - ShortField field = new ShortField(0); - byte[] array = new byte[ 2 ]; - - for (int j = 0; j < _test_array.length; j++) - { - field.set(_test_array[ j ]); - assertEquals("testing _1 " + j, _test_array[ j ], field.get()); - field = new ShortField(0); - field.set(_test_array[ j ], array); - assertEquals("testing _2 ", _test_array[ j ], field.get()); - assertEquals("testing _3.0 " + _test_array[ j ], - ( byte ) (_test_array[ j ] % 256), array[ 0 ]); - assertEquals("testing _3.1 " + _test_array[ j ], - ( byte ) ((_test_array[ j ] >> 8) % 256), - array[ 1 ]); - } - } - - public void testReadFromBytes() { - ShortField field = new ShortField(1); - byte[] array = new byte[ 2 ]; - - try - { - field.readFromBytes(array); - fail("should have caught ArrayIndexOutOfBoundsException"); - } - catch (ArrayIndexOutOfBoundsException ignored_e) - { - - // as expected - } - field = new ShortField(0); - for (int j = 0; j < _test_array.length; j++) - { - array[ 0 ] = ( byte ) (_test_array[ j ] % 256); - array[ 1 ] = ( byte ) ((_test_array[ j ] >> 8) % 256); - field.readFromBytes(array); - assertEquals("testing " + j, _test_array[ j ], field.get()); - } - } - - public void testReadFromStream() throws IOException { - ShortField field = new ShortField(0); - byte[] buffer = new byte[ _test_array.length * 2 ]; - - for (int j = 0; j < _test_array.length; j++) - { - buffer[ (j * 2) + 0 ] = ( byte ) (_test_array[ j ] % 256); - buffer[ (j * 2) + 1 ] = ( byte ) ((_test_array[ j ] >> 8) % 256); - } - ByteArrayInputStream stream = new ByteArrayInputStream(buffer); - - for (int j = 0; j < buffer.length / 2; j++) - { - field.readFromStream(stream); - assertEquals("Testing " + j, _test_array[ j ], field.get()); - } - } - - public void testWriteToBytes() { - ShortField field = new ShortField(0); - byte[] array = new byte[ 2 ]; - - for (short element : _test_array) { - field.set(element); - field.writeToBytes(array); - short val = ( short ) (array[ 1 ] << 8); - - val &= ( short ) 0xFF00; - val += ( short ) (array[ 0 ] & 0x00FF); - assertEquals("testing ", element, val); - } - } -} diff --git a/src/testcases/org/apache/poi/util/TestStringUtil.java b/src/testcases/org/apache/poi/util/TestStringUtil.java deleted file mode 100644 index ec9792a25..000000000 --- a/src/testcases/org/apache/poi/util/TestStringUtil.java +++ /dev/null @@ -1,219 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.util; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.nio.charset.Charset; - -import org.apache.poi.util.StringUtil.StringsIterator; -import org.junit.Test; - -/** - * Unit test for StringUtil - */ -public class TestStringUtil { - - /** - * test getFromUnicodeHigh for symbols with code below and more 127 - */ - @Test - public void testGetFromUnicodeHighSymbolsWithCodesMoreThan127() { - byte[] test_data = new byte[]{0x22, 0x04, - 0x35, 0x04, - 0x41, 0x04, - 0x42, 0x04, - 0x20, 0x00, - 0x74, 0x00, - 0x65, 0x00, - 0x73, 0x00, - 0x74, 0x00, - }; - - - assertEquals( "\u0422\u0435\u0441\u0442 test", - StringUtil.getFromUnicodeLE( test_data ) ); - } - - @Test - public void testPutCompressedUnicode() { - byte[] output = new byte[100]; - byte[] expected_output = - { - (byte) 'H', (byte) 'e', (byte) 'l', (byte) 'l', - (byte) 'o', (byte) ' ', (byte) 'W', (byte) 'o', - (byte) 'r', (byte) 'l', (byte) 'd', (byte) 0xAE - }; - String input = new String( expected_output, Charset.forName(StringUtil.getPreferredEncoding()) ); - - StringUtil.putCompressedUnicode( input, output, 0 ); - for ( int j = 0; j < expected_output.length; j++ ) - { - assertEquals( "testing offset " + j, expected_output[j], - output[j] ); - } - StringUtil.putCompressedUnicode( input, output, - 100 - expected_output.length ); - for ( int j = 0; j < expected_output.length; j++ ) - { - assertEquals( "testing offset " + j, expected_output[j], - output[100 + j - expected_output.length] ); - } - try - { - StringUtil.putCompressedUnicode( input, output, - 101 - expected_output.length ); - fail( "Should have caught ArrayIndexOutOfBoundsException" ); - } - catch ( ArrayIndexOutOfBoundsException ignored ) - { - // as expected - } - } - - @Test - public void testPutUncompressedUnicode() { - byte[] output = new byte[100]; - String input = "Hello World"; - byte[] expected_output = - { - (byte) 'H', (byte) 0, (byte) 'e', (byte) 0, (byte) 'l', - (byte) 0, (byte) 'l', (byte) 0, (byte) 'o', (byte) 0, - (byte) ' ', (byte) 0, (byte) 'W', (byte) 0, (byte) 'o', - (byte) 0, (byte) 'r', (byte) 0, (byte) 'l', (byte) 0, - (byte) 'd', (byte) 0 - }; - - StringUtil.putUnicodeLE( input, output, 0 ); - for ( int j = 0; j < expected_output.length; j++ ) - { - assertEquals( "testing offset " + j, expected_output[j], - output[j] ); - } - StringUtil.putUnicodeLE( input, output, - 100 - expected_output.length ); - for ( int j = 0; j < expected_output.length; j++ ) - { - assertEquals( "testing offset " + j, expected_output[j], - output[100 + j - expected_output.length] ); - } - try - { - StringUtil.putUnicodeLE( input, output, - 101 - expected_output.length ); - fail( "Should have caught ArrayIndexOutOfBoundsException" ); - } - catch ( ArrayIndexOutOfBoundsException ignored ) - { - // as expected - } - } - - @Test - public void testStringsIterator() { - StringsIterator i; - - - i = new StringsIterator(new String[0]); - assertFalse(i.hasNext()); - try { - i.next(); - fail(); - } catch(ArrayIndexOutOfBoundsException e) {} - - - i = new StringsIterator(new String[] {"1"}); - assertTrue(i.hasNext()); - assertEquals("1", i.next()); - - assertFalse(i.hasNext()); - try { - i.next(); - fail(); - } catch(ArrayIndexOutOfBoundsException e) {} - - - i = new StringsIterator(new String[] {"1","2","3"}); - assertTrue(i.hasNext()); - assertEquals("1", i.next()); - assertTrue(i.hasNext()); - assertEquals("2", i.next()); - assertTrue(i.hasNext()); - assertEquals("3", i.next()); - - assertFalse(i.hasNext()); - try { - i.next(); - fail(); - } catch(ArrayIndexOutOfBoundsException e) {} - } - - - @Test - public void startsWithIgnoreCase() { - assertTrue("same string", StringUtil.startsWithIgnoreCase("Apache POI", "Apache POI")); - assertTrue("longer string", StringUtil.startsWithIgnoreCase("Apache POI project", "Apache POI")); - assertTrue("different case", StringUtil.startsWithIgnoreCase("APACHE POI", "Apache POI")); - assertFalse("leading whitespace should not be ignored", StringUtil.startsWithIgnoreCase(" Apache POI project", "Apache POI")); - assertFalse("shorter string", StringUtil.startsWithIgnoreCase("Apache", "Apache POI"));; - } - - @Test - public void endsWithIgnoreCase() { - assertTrue("same string", StringUtil.endsWithIgnoreCase("Apache POI", "Apache POI")); - assertTrue("longer string", StringUtil.endsWithIgnoreCase("Project Apache POI", "Apache POI")); - assertTrue("different case", StringUtil.endsWithIgnoreCase("APACHE POI", "Apache POI")); - assertFalse("trailing whitespace should not be ignored", StringUtil.endsWithIgnoreCase("Apache POI project ", "Apache POI")); - assertFalse("shorter string", StringUtil.endsWithIgnoreCase("Apache", "Apache POI")); - } - - @Test - public void join() { - assertEquals("", StringUtil.join(",")); // degenerate case: nothing to join - assertEquals("abc", StringUtil.join(",", "abc")); // degenerate case: one thing to join, no trailing comma - assertEquals("abc|def|ghi", StringUtil.join("|", "abc", "def", "ghi")); - assertEquals("5|8.5|true|string", StringUtil.join("|", 5, 8.5, true, "string")); //assumes Locale prints number decimal point as a period rather than a comma - - String[] arr = new String[] { "Apache", "POI", "project" }; - assertEquals("no separator", "ApachePOIproject", StringUtil.join(arr)); - assertEquals("separator", "Apache POI project", StringUtil.join(arr, " ")); - } - - @Test - public void count() { - String test = "Apache POI project\n\u00a9 Copyright 2016"; - // supports search in null or empty string - assertEquals("null", 0, StringUtil.countMatches(null, 'A')); - assertEquals("empty string", 0, StringUtil.countMatches("", 'A')); - - assertEquals("normal", 2, StringUtil.countMatches(test, 'e')); - assertEquals("normal, should not find a in escaped copyright", 1, StringUtil.countMatches(test, 'a')); - - // search for non-printable characters - assertEquals("null character", 0, StringUtil.countMatches(test, '\0')); - assertEquals("CR", 0, StringUtil.countMatches(test, '\r')); - assertEquals("LF", 1, StringUtil.countMatches(test, '\n')); - - // search for unicode characters - assertEquals("Unicode", 1, StringUtil.countMatches(test, '\u00a9')); - } -} - diff --git a/src/testcases/org/apache/poi/util/TestTempFile.java b/src/testcases/org/apache/poi/util/TestTempFile.java deleted file mode 100644 index e893f00c5..000000000 --- a/src/testcases/org/apache/poi/util/TestTempFile.java +++ /dev/null @@ -1,144 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.util; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Arrays; - -import org.apache.poi.poifs.dev.TestPOIFSDump; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; - -public class TestTempFile { - private String previousTempDir; - private File tempDir; - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Before - public void setUp() throws IOException { - previousTempDir = System.getProperty(TempFile.JAVA_IO_TMPDIR); - - // use a separate tempdir for the tests to be able to check for leftover files - tempDir = File.createTempFile("TestTempFile", ".tst"); - assertTrue(tempDir.delete()); - assertTrue(tempDir.mkdirs()); - System.setProperty(TempFile.JAVA_IO_TMPDIR, tempDir.getAbsolutePath()); - } - - @After - public void tearDown() throws IOException { - String[] files = tempDir.list(); - // can have the "poifiles" subdir - if(files.length == 1) { - assertEquals("Had: " + Arrays.toString(files), DefaultTempFileCreationStrategy.POIFILES, files[0]); - files = new File(tempDir, files[0]).list(); - assertEquals("Had: " + Arrays.toString(files), 0, files.length); - } else { - assertEquals("Had: " + Arrays.toString(files), 0, files.length); - } - - // remove the directory after the tests - TestPOIFSDump.deleteDirectory(tempDir); - - if(previousTempDir == null) { - System.clearProperty(TempFile.JAVA_IO_TMPDIR); - } else { - System.setProperty(TempFile.JAVA_IO_TMPDIR, previousTempDir); - } - - // reset strategy to re-create the directory - TempFile.setTempFileCreationStrategy(new DefaultTempFileCreationStrategy()); - - // check that we can still create a tempfile - File testFile = TempFile.createTempFile("test", ".tst"); - assertTrue(testFile.exists()); - assertTrue(testFile.delete()); - } - - @Test - public void testCreateTempFile() throws IOException - { - File tempFile = TempFile.createTempFile("test", ".txt"); - FileOutputStream fos = new FileOutputStream(tempFile); - fos.write(1); //file can be written to - fos.close(); - assertTrue("temp file exists", tempFile.exists()); - assertTrue("temp file is a file", tempFile.isFile()); - assertTrue("temp file's name should start with test", - tempFile.getName().startsWith("test")); - assertTrue("temp file's name should end with .txt", - tempFile.getName().endsWith(".txt")); - assertEquals("temp file is saved in poifiles directory", - DefaultTempFileCreationStrategy.POIFILES, tempFile.getParentFile().getName()); - - // Can't think of a good way to check whether a file is actually deleted since it would require the VM to stop. - // Solution: set TempFileCreationStrategy to something that the unit test can trigger a deletion" - assertTrue("Unable to delete temp file", tempFile.delete()); - } - - @Test - public void createTempFileWithDefaultSuffix() throws IOException { - File tempFile = TempFile.createTempFile("test", null); - assertTrue("temp file's name should end with .tmp", - tempFile.getName().endsWith(".tmp")); - } - - @Test - public void testCreateTempDirectory() throws IOException - { - File tempDir = TempFile.createTempDirectory("testDir"); - assertTrue("testDir exists", tempDir.exists()); - assertTrue("testDir is a directory", tempDir.isDirectory()); - assertTrue("testDir's name starts with testDir", - tempDir.getName().startsWith("testDir")); - assertEquals("tempDir is saved in poifiles directory", - DefaultTempFileCreationStrategy.POIFILES, tempDir.getParentFile().getName()); - - // Can't think of a good way to check whether a directory is actually deleted since it would require the VM to stop. - // Solution: set TempFileCreationStrategy to something that the unit test can trigger a deletion" - assertTrue("Unable to delete tempDir", tempDir.delete()); - } - - @Test - public void testSetTempFileCreationStrategy() throws IOException { - TempFile.setTempFileCreationStrategy(new DefaultTempFileCreationStrategy()); - - // Should be able to create two tempfiles with same prefix and suffix - File file1 = TempFile.createTempFile("TestTempFile", ".tst"); - File file2 = TempFile.createTempFile("TestTempFile", ".tst"); - assertFalse(file1.equals(file2)); - assertNotNull(file2); - assertTrue(file2.delete()); - assertNotNull(file1); - assertTrue(file1.delete()); - - thrown.expect(IllegalArgumentException.class); - TempFile.setTempFileCreationStrategy(null); - } -} diff --git a/src/testcases/org/apache/poi/util/data/test_properties1 b/src/testcases/org/apache/poi/util/data/test_properties1 deleted file mode 100644 index 5c88809b7..000000000 --- a/src/testcases/org/apache/poi/util/data/test_properties1 +++ /dev/null @@ -1,26 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Set root category priority to DEBUG and its only appender to A1. -log4j.rootCategory=DEBUG, A1 - -# A1 is set to be a FileAppender. -log4j.appender.A1=org.apache.log4j.FileAppender -log4j.appender.A1.File=p1.log - -# A1 uses PatternLayout. -log4j.appender.A1.layout=org.apache.log4j.PatternLayout -log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n -#log4j.category.org.apache.cocoon.poi=WARN diff --git a/src/testcases/org/apache/poi/util/data/test_properties2 b/src/testcases/org/apache/poi/util/data/test_properties2 deleted file mode 100644 index dbf3f81e1..000000000 --- a/src/testcases/org/apache/poi/util/data/test_properties2 +++ /dev/null @@ -1,26 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Set root category priority to DEBUG and its only appender to A2. -log4j.rootCategory=DEBUG, A2 - -# A2 is set to be a FileAppender. -log4j.appender.A2=org.apache.log4j.FileAppender -log4j.appender.A2.File=p2.log - -# A2 uses PatternLayout. -log4j.appender.A2.layout=org.apache.log4j.PatternLayout -log4j.appender.A2.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n -#log4j.category.org.apache.cocoon.poi=WARN diff --git a/src/testcases/org/apache/poi/util/data/test_properties3 b/src/testcases/org/apache/poi/util/data/test_properties3 deleted file mode 100644 index 84ba40da0..000000000 --- a/src/testcases/org/apache/poi/util/data/test_properties3 +++ /dev/null @@ -1,26 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. -# The ASF licenses this file to You under the Apache License, Version 2.0 -# (the "License"); you may not use this file except in compliance with -# the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Set root category priority to DEBUG and its only appender to A3. -log4j.rootCategory=DEBUG, A3 - -# A3 is set to be a FileAppender. -log4j.appender.A3=org.apache.log4j.FileAppender -log4j.appender.A3.File=POILogger.log - -# A3 uses PatternLayout. -log4j.appender.A3.layout=org.apache.log4j.PatternLayout -log4j.appender.A3.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n -#log4j.category.org.apache.cocoon.poi=WARN diff --git a/src/types/definitions/FFData_type.xml b/src/types/definitions/FFData_type.xml deleted file mode 100644 index 2016adb6d..000000000 --- a/src/types/definitions/FFData_type.xml +++ /dev/null @@ -1,81 +0,0 @@ - - - - AbstractType - The FFData structure specifies form field data for a text - box, check box, or drop-down list box. <p>Class and fields - descriptions are quoted from [MS-DOC] -- v20121003 Word (.doc) Binary - File Format; Copyright (c) 2012 Microsoft Corporation; Release: - October 8, 2012 - - Sergey Vladimirov; according to [MS-DOC] -- v20121003 Word - (.doc) Binary File Format; Copyright (c) 2012 Microsoft Corporation; - Release: October 8, 2012 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/types/definitions/FibBase_type.xml b/src/types/definitions/FibBase_type.xml deleted file mode 100644 index 37c81a446..000000000 --- a/src/types/definitions/FibBase_type.xml +++ /dev/null @@ -1,94 +0,0 @@ - - - - AbstractType - Base part of the File information Block (FibBase). Holds the core part of the FIB, - from the first 32 bytes. <p>Class and fields descriptions are quoted from Microsoft - Office Word 97-2007 Binary File Format and [MS-DOC] - v20110608 Word (.doc) Binary File - Format - - Andrew C. Oliver; Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary - File Format Specification [*.doc] and [MS-DOC] - v20110608 Word (.doc) Binary File Format - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/types/definitions/FibRgLw95_type.xml b/src/types/definitions/FibRgLw95_type.xml deleted file mode 100644 index 74c5dc53a..000000000 --- a/src/types/definitions/FibRgLw95_type.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - - AbstractType - The FibRgLw95 structure is the third section of the FIB for Word95. - - Sergey Vladimirov - - - - - - - - - - - - - - - - - - - - - diff --git a/src/types/definitions/FibRgLw97_type.xml b/src/types/definitions/FibRgLw97_type.xml deleted file mode 100644 index 0fafcc9c8..000000000 --- a/src/types/definitions/FibRgLw97_type.xml +++ /dev/null @@ -1,82 +0,0 @@ - - - - AbstractType - The FibRgLw97 structure is the third section of the FIB. This contains an array of - 4-byte values. <p>Class and fields descriptions are quoted from Microsoft Office Word - 97-2007 Binary File Format and [MS-DOC] - v20110608 Word (.doc) Binary File Format - - Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary File Format - Specification [*.doc] and [MS-DOC] - v20110608 Word (.doc) Binary File Format - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/types/definitions/FibRgW97_type.xml b/src/types/definitions/FibRgW97_type.xml deleted file mode 100644 index 7f902d2f3..000000000 --- a/src/types/definitions/FibRgW97_type.xml +++ /dev/null @@ -1,58 +0,0 @@ - - - - AbstractType - The FibRgW97 structure is a variable-length portion of the Fib. <p>Class and - fields descriptions are quoted from Microsoft Office Word 97-2007 Binary File Format and - [MS-DOC] - v20110608 Word (.doc) Binary File Format - - Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary File Format - Specification [*.doc] and [MS-DOC] - v20110608 Word (.doc) Binary File Format - - - - - - - - - - - - - - - - - - diff --git a/src/types/definitions/LFOLVLBase_type.xml b/src/types/definitions/LFOLVLBase_type.xml deleted file mode 100644 index 1cafd752d..000000000 --- a/src/types/definitions/LFOLVLBase_type.xml +++ /dev/null @@ -1,46 +0,0 @@ - - - - AbstractType - The LFOLVL structure contains information that is used to override the formatting - information of a corresponding LVL. <p>Class and fields descriptions are quoted from - Microsoft Office Word 97-2007 Binary File Format and [MS-DOC] - v20110608 Word (.doc) Binary - File Format - - Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary File Format - Specification [*.doc] and [MS-DOC] - v20110608 Word (.doc) Binary File Format - - - - - - - - - - - - - diff --git a/src/types/definitions/StdfBase_type.xml b/src/types/definitions/StdfBase_type.xml deleted file mode 100644 index 5b9918ffe..000000000 --- a/src/types/definitions/StdfBase_type.xml +++ /dev/null @@ -1,78 +0,0 @@ - - - - AbstractType - The StdfBase structure specifies general information about a style. <p>Class - and fields descriptions are quoted from Microsoft Office Word 97-2007 Binary File Format and - [MS-DOC] - v20110608 Word (.doc) Binary File Format - - Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary File Format - Specification [*.doc] and [MS-DOC] - v20110608 Word (.doc) Binary File Format - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/types/definitions/StdfPost2000_type.xml b/src/types/definitions/StdfPost2000_type.xml deleted file mode 100644 index 277962f08..000000000 --- a/src/types/definitions/StdfPost2000_type.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - - AbstractType - The StdfPost2000 structure specifies general information about a style. - <p>Class and fields descriptions are quoted from Microsoft Office Word 97-2007 Binary - File Format and [MS-DOC] - v20110608 Word (.doc) Binary File Format - - Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary File Format - Specification [*.doc] and [MS-DOC] - v20110608 Word (.doc) Binary File Format - - - - - - - - - - - - - - - diff --git a/src/types/definitions/Stshif_type.xml b/src/types/definitions/Stshif_type.xml deleted file mode 100644 index cab40209f..000000000 --- a/src/types/definitions/Stshif_type.xml +++ /dev/null @@ -1,51 +0,0 @@ - - - - AbstractType - The Stshif structure specifies general stylesheet information. <p>Class and - fields descriptions are quoted from Microsoft Office Word 97-2007 Binary File Format and - [MS-DOC] - v20110608 Word (.doc) Binary File Format - - Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary File Format - Specification [*.doc] and [MS-DOC] - v20110608 Word (.doc) Binary File Format - - - - - - - - - - - - - - - - diff --git a/src/types/definitions/bkf_type.xml b/src/types/definitions/bkf_type.xml deleted file mode 100644 index 32a4b1ca2..000000000 --- a/src/types/definitions/bkf_type.xml +++ /dev/null @@ -1,44 +0,0 @@ - - - - AbstractType - HDFType - BooKmark First descriptor (BKF). <p>Class and fields descriptions are - quoted - from Microsoft Office Word 97-2007 Binary File Format (.doc) Specification - - Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary File Format (.doc) - Specification - - - - - - - - - - - diff --git a/src/types/definitions/chp_type.xml b/src/types/definitions/chp_type.xml deleted file mode 100644 index 5d77786e1..000000000 --- a/src/types/definitions/chp_type.xml +++ /dev/null @@ -1,358 +0,0 @@ - - - - AbstractType - HDFType - Character Properties. - S. Ryan Ackley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/types/definitions/dml-shapeGeometry.xjb b/src/types/definitions/dml-shapeGeometry.xjb deleted file mode 100644 index 8d05c6291..000000000 --- a/src/types/definitions/dml-shapeGeometry.xjb +++ /dev/null @@ -1,26 +0,0 @@ - - - - - diff --git a/src/types/definitions/dop_type.xml b/src/types/definitions/dop_type.xml deleted file mode 100644 index 77de331bf..000000000 --- a/src/types/definitions/dop_type.xml +++ /dev/null @@ -1,188 +0,0 @@ - - - - AbstractType - HDFType - Document Properties. - S. Ryan Ackley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/types/definitions/fld_type.xml b/src/types/definitions/fld_type.xml deleted file mode 100644 index 2c7a0b945..000000000 --- a/src/types/definitions/fld_type.xml +++ /dev/null @@ -1,52 +0,0 @@ - - - - AbstractType - HDFType - Field Descriptor (FLD). <p>Class and fields descriptions are - quoted from - Microsoft Office Word 97-2007 Binary File Format - - Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary File Format - Specification [*.doc] - - - - - - - - - - - - - - - - - - diff --git a/src/types/definitions/frd_type.xml b/src/types/definitions/frd_type.xml deleted file mode 100644 index a44741343..000000000 --- a/src/types/definitions/frd_type.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - - AbstractType - HDFType - Footnote Reference Descriptor (FRD). <p>Class and fields descriptions are - quoted from Microsoft Office Word 97-2007 Binary File Format (.doc) Specification - - Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary File Format (.doc) - Specification - - - - - diff --git a/src/types/definitions/fspa_type.xml b/src/types/definitions/fspa_type.xml deleted file mode 100644 index 42e464aa5..000000000 --- a/src/types/definitions/fspa_type.xml +++ /dev/null @@ -1,74 +0,0 @@ - - - - AbstractType - HDFType - File Shape Address (FSPA). <p>Class and fields descriptions are quoted from - Microsoft Office Word 97-2007 Binary File Format - - Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary File Format - Specification [*.doc] - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/types/definitions/grfhic_type.xml b/src/types/definitions/grfhic_type.xml deleted file mode 100644 index 0c1cf5c7c..000000000 --- a/src/types/definitions/grfhic_type.xml +++ /dev/null @@ -1,46 +0,0 @@ - - - - AbstractType - The grfhic structure is a set of HTML incompatibility flags that specify the HTML - incompatibilities of a list structure. The values specify possible incompatibilities between - an LVL or LVLF and HTML lists. The values do not define list properties. <p>Class and - fields descriptions are quoted from [MS-DOC] -- v20110315 Word (.doc) Binary File Format - specification - - Sergey Vladimirov; according to [MS-DOC] -- v20110315 Word (.doc) Binary File Format - specification - - - - - - - - - - - - - - diff --git a/src/types/definitions/hresi_type.xml b/src/types/definitions/hresi_type.xml deleted file mode 100644 index aef96bdf6..000000000 --- a/src/types/definitions/hresi_type.xml +++ /dev/null @@ -1,42 +0,0 @@ - - - - AbstractType - Hyphenation (HRESI). <p>Class and fields descriptions are - quoted from - Microsoft Office Word 97-2007 Binary File Format (.doc) Specification - - Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary File Format (.doc) - Specification - - - - - - - - - - - - - - diff --git a/src/types/definitions/lfo_type.xml b/src/types/definitions/lfo_type.xml deleted file mode 100644 index 911f6ce6f..000000000 --- a/src/types/definitions/lfo_type.xml +++ /dev/null @@ -1,40 +0,0 @@ - - - - AbstractType - HDFType - List Format Override (LFO). <p>Class and fields descriptions are quoted from - [MS-DOC] --v20110315; Word (.doc) Binary File Format - - Sergey Vladimirov; according to [MS-DOC] --v20110315; Word (.doc) Binary File Format; - Copyright (c) Microsoft Corporation - - - - - - - - - - - diff --git a/src/types/definitions/lstf_type.xml b/src/types/definitions/lstf_type.xml deleted file mode 100644 index 5c7f1d334..000000000 --- a/src/types/definitions/lstf_type.xml +++ /dev/null @@ -1,51 +0,0 @@ - - - - AbstractType - The LSTF structure contains formatting properties that apply to an entire list. - <p>Class and fields descriptions are quoted from Microsoft Office Word 97-2007 Binary - File Format and [MS-DOC] - v20110608 Word (.doc) Binary File Format - - Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary File Format - Specification [*.doc] and [MS-DOC] - v20110608 Word (.doc) Binary File Format - - - - - - - - - - - - - - - - diff --git a/src/types/definitions/lvlf_type.xml b/src/types/definitions/lvlf_type.xml deleted file mode 100644 index c60a4f1b3..000000000 --- a/src/types/definitions/lvlf_type.xml +++ /dev/null @@ -1,65 +0,0 @@ - - - - AbstractType - The LVLF structure contains formatting properties for an individual level in a - list. <p>Class and fields descriptions are quoted from Microsoft Office Word 97-2007 - Binary File Format and [MS-DOC] - v20110608 Word (.doc) Binary File Format - - Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary File Format - Specification [*.doc] and [MS-DOC] - v20110608 Word (.doc) Binary File Format - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/types/definitions/pap_type.xml b/src/types/definitions/pap_type.xml deleted file mode 100644 index 710425a4e..000000000 --- a/src/types/definitions/pap_type.xml +++ /dev/null @@ -1,160 +0,0 @@ - - - - AbstractType - HDFType - Paragraph Properties. - S. Ryan Ackley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/types/definitions/picf_type.xml b/src/types/definitions/picf_type.xml deleted file mode 100644 index cdda96502..000000000 --- a/src/types/definitions/picf_type.xml +++ /dev/null @@ -1,71 +0,0 @@ - - - - AbstractType - The PICF structure specifies the type of a picture, as well as the size of the - picture and information about its border. <p>Class and fields descriptions are quoted - from Microsoft Office Word 97-2007 - Binary File Format and [MS-DOC] - v20110608 Word (.doc) - Binary File Format - - Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary File Format - Specification [*.doc] and [MS-DOC] - v20110608 Word (.doc) Binary File Format - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/types/definitions/sep_type.xml b/src/types/definitions/sep_type.xml deleted file mode 100644 index ff0689bde..000000000 --- a/src/types/definitions/sep_type.xml +++ /dev/null @@ -1,102 +0,0 @@ - - - - AbstractType - HDFType - Section Properties. - S. Ryan Ackley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/types/definitions/shd80_type.xml b/src/types/definitions/shd80_type.xml deleted file mode 100644 index 22210ce7b..000000000 --- a/src/types/definitions/shd80_type.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - AbstractType - The Shd80 structure specifies the colors and pattern that are used for background - shading. As an exception to the constraints that are specified by Ico and Ipat, a Shd80 can - be set to Shd80Nil and specifies that no shading is applied. <p>Class and fields - descriptions are quoted from Word (.doc) Binary File Format by Microsoft Corporation - - Sergey Vladimirov; according to Word (.doc) Binary File Format by Microsoft Corporation. - - - - - - - - - diff --git a/src/types/definitions/shd_type.xml b/src/types/definitions/shd_type.xml deleted file mode 100644 index a2c1ba624..000000000 --- a/src/types/definitions/shd_type.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - - AbstractType - The Shd structure specifies the colors and pattern that are used for background shading. <p>Class - and - fields descriptions are quoted from Word (.doc) Binary File Format by Microsoft Corporation - - Sergey Vladimirov; according to Word (.doc) Binary File Format by Microsoft Corporation. - - - - - - - diff --git a/src/types/definitions/tap_type.xml b/src/types/definitions/tap_type.xml deleted file mode 100644 index 2a56ddc5e..000000000 --- a/src/types/definitions/tap_type.xml +++ /dev/null @@ -1,244 +0,0 @@ - - - - AbstractType - HDFType - Table Properties. Properties descriptions quoted from official 97-2007 binary file - format specification. - - S. Ryan Ackley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/types/definitions/tbd_type.xml b/src/types/definitions/tbd_type.xml deleted file mode 100644 index 7faeb01bf..000000000 --- a/src/types/definitions/tbd_type.xml +++ /dev/null @@ -1,48 +0,0 @@ - - - - AbstractType - The TBD is a substructure of the PAP. <p>Class and fields descriptions are quoted from - Microsoft Office Word 97-2007 Binary File Format - - Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary File Format - Specification [*.doc] - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/types/definitions/tc_type.xml b/src/types/definitions/tc_type.xml deleted file mode 100644 index 7df82bd65..000000000 --- a/src/types/definitions/tc_type.xml +++ /dev/null @@ -1,76 +0,0 @@ - - - - AbstractType - HDFType - Table Cell Descriptor. - S. Ryan Ackley. Field descriptions are quoted from Microsoft Office Word 97-2007 Binary - File Format (.doc) Specification - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/types/definitions/tlp_type.xml b/src/types/definitions/tlp_type.xml deleted file mode 100644 index b915e6e9b..000000000 --- a/src/types/definitions/tlp_type.xml +++ /dev/null @@ -1,49 +0,0 @@ - - - - AbstractType - HDFType - Table Autoformat Look sPecifier (TLP). <p>Class and fields descriptions are - quoted from Microsoft Office Word 97-2007 Binary File Format - - Sergey Vladimirov; according to Microsoft Office Word 97-2007 Binary File Format - Specification [*.doc] - - - - - - - - - - - - - - diff --git a/src/types/styles/hdftype.xsl b/src/types/styles/hdftype.xsl deleted file mode 100644 index d8c90e752..000000000 --- a/src/types/styles/hdftype.xsl +++ /dev/null @@ -1,642 +0,0 @@ - - - - - - - - - - - - - /* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - - - -package ; - - -import org.apache.poi.hwpf.usermodel.*; -import org.apache.poi.util.*; - -/** - * - * <p> - * NOTE: This source is automatically generated please do not modify this file. Either subclass or - * remove the record in src/types/definitions. - * <p> - * This class is internal. It content or properties may change without notice - * due to changes in our knowledge of internal Microsoft Word binary structures. - - */ -@Internal -public abstract class -{ - - - - - - @Deprecated - - - - protected - - field_ - - _ - - ; - - - - - - - - protected - - AbstractType() - - - { - - - - - - - this. - - = - - ; - - - - - - - - - - - - this. - - = new byte[ - - ]; - - - - - - this. - - = new - - [0]; - - - - - - this. - - = new - - (); - - - - - - } - - - - - -protected void fillFields( byte[] data, int offset ) - { - - - - - - - = - - ; - - - - } - - - - - - public void serialize( byte[] data, int offset ) - { - - - - - - - - - - } - - - public byte[] serialize() - { - final byte[] result = new byte[ getSize() ]; - serialize( result, 0 ); - return result; - } - - - /** - * Size of record - */ - public static int getSize() - { - - - - return 0 - - - - - ; - - - } - - - - - - - @Override - - - public boolean equals( Object obj ) - { - if ( this == obj ) - return true; - if ( obj == null ) - return false; - if ( getClass() != obj.getClass() ) - return false; - - - - - other = ( - - ) obj; - - - - - - - - if ( - !Arrays.equals( - - , other. - - ) - ) - - - - - return false; - - - - if ( - - != other. - - ) - - - - - return false; - - - - if ( - - == null ) - - - - { - - - - - if ( other. - - != null ) - - - - - - return false; - - - - } - - - - else if ( ! - - .equals( other. - - ) ) - - - - - return false; - - - - - - - return true; - - - } - - - - - - @Override - - - public int hashCode() - { - final int prime = 31; - int result = 1; - - - - - result = prime * result - - - - + - Arrays.hashCode( - - ) - - - + - ( - - ? 1231 : 1237 ) - - - + - - - - - - - - - + (int) ( - - ^ ( - - >>> 32 ) ) - - - - - - - - + (( - - == null) ? 0 : - - .hashCode()) - - - ; - - - - - return result; - - - } - - - - - - - - - -} // END OF CLASS - - - - - - - /** - * Sets the field value. - * - */ - @Internal - public void set( value ) - { - = ; - } - - /** - * - * @return the field value. - - - - * @deprecated This field should not be used according to specification - - - - */ - - - @Internal - - - - @Deprecated - - - - public () - { - return - } - - - - - - /**/private static final BitField - - = new BitField( - - ); - - - - - - - - - - /** - - - /** - - - - */ - - - - - - /* */ - - - /**/ - - - protected final static - - - - = - - ; - - - - - - - * <li>{@link # - - } - - - - - - - - - - - - - /** - * - - - - - Get the - - field for the - - record - - - . - - * - * @return One of - */ - @Internal - public get() - { - return ; - } - - /** - * - - - - - Set the - - field for the - - record - - - . - - * - * @param - * One of - */ - @Internal - public void set( ) - { - this. = ; - } - - - - - public String toString() - - - - { - - - - - StringBuilder builder = new StringBuilder(); - - - - - - builder.append("[ - - ]\n"); - - - - - - - - builder.append("[/ - - ]"); - return builder.toString(); - } - - - - - - - - - builder.append( " . - - = " ); - - - - - builder.append(" ( ").append( - - - - - - - == null ? "null" : - - .toString().replaceAll( "\n", "\n " ) - - - ).append( " )\n" ); - - - - - - - - - builder.append(" . - - = ").append( - - ()).append('\n'); - - - - - * @author - - - diff --git a/src/types/styles/hdftype_document.xsl b/src/types/styles/hdftype_document.xsl deleted file mode 100644 index f7bfb720c..000000000 --- a/src/types/styles/hdftype_document.xsl +++ /dev/null @@ -1,69 +0,0 @@ - - - - - - -

    - <xsl:value-of select="@name"/> Documentation For HDF Type -
    - - - -

    -

    -
    - -
    "); - assertContains(result, ""); - } - - @Test - public void testBug52420() throws Exception { - String result = getHtmlText("52420.doc"); - - assertFalse(result.contains("FORMTEXT")); - - assertContains(result, "\u0417\u0410\u0414\u0410\u041d\u0418\u0415"); - assertContains(result, "\u041f\u0440\u0435\u043f\u043e\u0434\u0430\u0432\u0430\u0442\u0435\u043b\u044c"); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/converter/TestWordToTextConverter.java b/src/scratchpad/testcases/org/apache/poi/hwpf/converter/TestWordToTextConverter.java deleted file mode 100644 index 00a46f642..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/converter/TestWordToTextConverter.java +++ /dev/null @@ -1,60 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hwpf.converter; - -import junit.framework.TestCase; -import org.apache.poi.hwpf.HWPFDocument; -import org.apache.poi.hwpf.HWPFTestDataSamples; - -public class TestWordToTextConverter extends TestCase -{ - - /** - * [FAILING] Bug 47731 - Word Extractor considers text copied from some - * website as an embedded object - */ - public void testBug47731() throws Exception - { - HWPFDocument doc = HWPFTestDataSamples.openSampleFile( "Bug47731.doc" ); - String foundText = WordToTextConverter.getText( doc ); - - assertTrue( foundText - .contains( "Soak the rice in water for three to four hours" ) ); - } - - public void testBug52311() throws Exception - { - HWPFDocument doc = HWPFTestDataSamples.openSampleFile( "Bug52311.doc" ); - String result = WordToTextConverter.getText( doc ); - - assertTrue( result.contains( "2.1\tHeader 2.1" ) ); - assertTrue( result.contains( "2.2\tHeader 2.2" ) ); - assertTrue( result.contains( "2.3\tHeader 2.3" ) ); - assertTrue( result.contains( "2.3.1\tHeader 2.3.1" ) ); - assertTrue( result.contains( "2.99\tHeader 2.99" ) ); - assertTrue( result.contains( "2.99.1\tHeader 2.99.1" ) ); - assertTrue( result.contains( "2.100\tHeader 2.100" ) ); - assertTrue( result.contains( "2.101\tHeader 2.101" ) ); - } - - public void testBug53380_3() throws Exception - { - HWPFDocument doc = HWPFTestDataSamples - .openSampleFile( "Bug53380_3.doc" ); - WordToTextConverter.getText( doc ); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/dev/TestHWPFLister.java b/src/scratchpad/testcases/org/apache/poi/hwpf/dev/TestHWPFLister.java deleted file mode 100644 index 83a0356a7..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/dev/TestHWPFLister.java +++ /dev/null @@ -1,54 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hwpf.dev; - -import org.apache.poi.POIDataSamples; -import org.junit.After; -import org.junit.Test; - -import java.io.File; - -public class TestHWPFLister { - @After - public void tearDown() { - // the main-method sets these properties, we need to revert them here to not affect other tests - System.clearProperty("org.apache.poi.hwpf.preserveBinTables"); - System.clearProperty("org.apache.poi.hwpf.preserveTextTable"); - } - - @Test - public void main() throws Exception { - File file = POIDataSamples.getDocumentInstance().getFile("SampleDoc.doc"); - HWPFLister.main(new String[] { file.getAbsolutePath() }); - } - - @Test - public void mainAll() throws Exception { - File file = POIDataSamples.getDocumentInstance().getFile("SampleDoc.doc"); - HWPFLister.main(new String[] { - file.getAbsolutePath(), - "--dop", "--textPieces", "--textPiecesText", - "--chpx", "--chpxProperties", "--chpxSprms", - "--papx", "--papxProperties", "--papxSprms", - "--paragraphs", "--paragraphsText", - "--bookmarks", "--escher", - "--fields", "--pictures", - "--officeDrawings", "--styles", - "--writereadback" - }); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/extractor/TestDifferentRoutes.java b/src/scratchpad/testcases/org/apache/poi/hwpf/extractor/TestDifferentRoutes.java deleted file mode 100644 index ca1b54e00..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/extractor/TestDifferentRoutes.java +++ /dev/null @@ -1,94 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.extractor; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; - -import java.io.IOException; - -import org.junit.Test; - -import org.apache.poi.hwpf.HWPFDocument; -import org.apache.poi.hwpf.HWPFTestDataSamples; -import org.apache.poi.hwpf.usermodel.Paragraph; -import org.apache.poi.hwpf.usermodel.Range; -import org.apache.poi.util.StringUtil; -import org.junit.After; -import org.junit.Before; - -/** - * Test the different routes to extracting text - * - * @author Nick Burch (nick at torchbox dot com) - */ -public final class TestDifferentRoutes { - private static final String[] p_text = new String[] { - "This is a simple word document\r", - "\r", - "It has a number of paragraphs in it\r", - "\r", - "Some of them even feature bold, italic and underlined text\r", - "\r", - "\r", - "This bit is in a different font and size\r", - "\r", - "\r", - "This bit features some red text.\r", - "\r", - "\r", - "It is otherwise very very boring.\r" - }; - - private HWPFDocument doc; - - @Before - public void setUp() { - doc = HWPFTestDataSamples.openSampleFile("test2.doc"); - } - - @After - public void tearDown() throws IOException { - doc.close(); - } - - /** - * Test model based extraction - */ - @Test - public void testExtractFromModel() { - Range r = doc.getRange(); - - String[] text = new String[r.numParagraphs()]; - for (int i = 0; i < r.numParagraphs(); i++) { - Paragraph p = r.getParagraph(i); - text[i] = p.text(); - } - - assertArrayEquals(p_text, text); - } - - /** - * Test textPieces based extraction - */ - @Test - public void testExtractFromTextPieces() throws Exception { - String expected = StringUtil.join(p_text, ""); - assertEquals(expected, doc.getDocumentText()); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/extractor/TestWordExtractor.java b/src/scratchpad/testcases/org/apache/poi/hwpf/extractor/TestWordExtractor.java deleted file mode 100644 index f13daf326..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/extractor/TestWordExtractor.java +++ /dev/null @@ -1,429 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.extractor; - -import static org.apache.poi.POITestCase.assertContains; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.POITextExtractor; -import org.apache.poi.hwpf.HWPFDocument; -import org.apache.poi.hwpf.HWPFTestDataSamples; -import org.apache.poi.hwpf.OldWordFileFormatException; -import org.apache.poi.poifs.filesystem.DirectoryNode; -import org.apache.poi.poifs.filesystem.Entry; -import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; -import org.apache.poi.poifs.filesystem.OPOIFSFileSystem; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.util.StringUtil; -import org.junit.Test; - -/** - * Test the different routes to extracting text - */ -public final class TestWordExtractor { - - private static POIDataSamples docTests = POIDataSamples.getDocumentInstance(); - - public static void assertEqualsTrim( String expected, String actual ) - { - String newExpected = expected.replaceAll( "\r\n", "\n" ) - .replaceAll( "\r", "\n" ).trim(); - String newActual = actual.replaceAll( "\r\n", "\n" ) - .replaceAll( "\r", "\n" ).trim(); - assertEquals( newExpected, newActual ); - } - - private static void assertExtractedContains(String[] extracted, String needle) { - String endnote = StringUtil.join(extracted, ""); - assertContains(endnote, needle); - } - - private final String[] p_text1 = new String[] { - "This is a simple word document\r\n", - "\r\n", - "It has a number of paragraphs in it\r\n", - "\r\n", - "Some of them even feature bold, italic and underlined text\r\n", - "\r\n", - "\r\n", - "This bit is in a different font and size\r\n", - "\r\n", - "\r\n", - "This bit features some red text.\r\n", - "\r\n", - "\r\n", - "It is otherwise very very boring.\r\n" - }; - - // Build splat'd out text version - private final String p_text1_block = StringUtil.join(p_text1, ""); - - /** - * Test paragraph based extraction - */ - @Test - public void testExtractFromParagraphs() throws IOException { - WordExtractor extractor = openExtractor("test2.doc"); - String[] text = extractor.getParagraphText(); - - assertEquals(p_text1.length, text.length); - for (int i = 0; i < p_text1.length; i++) { - assertEquals(p_text1[i], text[i]); - } - extractor.close(); - - // Lots of paragraphs with only a few lines in them - WordExtractor extractor2 = openExtractor("test.doc"); - assertEquals(24, extractor2.getParagraphText().length); - assertEquals("as d\r\n", extractor2.getParagraphText()[16]); - assertEquals("as d\r\n", extractor2.getParagraphText()[17]); - assertEquals("as d\r\n", extractor2.getParagraphText()[18]); - extractor2.close(); - } - - /** - * Test the paragraph -> flat extraction - */ - @Test - public void testGetText() throws IOException { - WordExtractor extractor = openExtractor("test2.doc"); - assertEqualsTrim(p_text1_block, extractor.getText()); - - // For the 2nd, should give similar answers for - // the two methods, differing only in line endings - - // nope, they must have different results, because of garbage - // assertEquals( - // extractor2.getTextFromPieces().replaceAll("[\\r\\n]", ""), - // extractor2.getText().replaceAll("[\\r\\n]", "")); - extractor.close(); - } - - /** - * Test textPieces based extraction - */ - @Test - public void testExtractFromTextPieces() throws IOException { - WordExtractor extractor = openExtractor("test2.doc"); - String text = extractor.getTextFromPieces(); - assertEquals(p_text1_block, text); - extractor.close(); - } - - - /** - * Test that we can get data from two different embedded word documents - */ - @Test - public void testExtractFromEmbeded() throws IOException { - InputStream is = POIDataSamples.getSpreadSheetInstance().openResourceAsStream("excel_with_embeded.xls"); - POIFSFileSystem fs = new POIFSFileSystem(is); - is.close(); - - DirectoryNode dirA = (DirectoryNode) fs.getRoot().getEntry("MBD0000A3B7"); - DirectoryNode dirB = (DirectoryNode) fs.getRoot().getEntry("MBD0000A3B2"); - - // Should have WordDocument and 1Table - assertNotNull(dirA.getEntry("1Table")); - assertNotNull(dirA.getEntry("WordDocument")); - - assertNotNull(dirB.getEntry("1Table")); - assertNotNull(dirB.getEntry("WordDocument")); - - // Check each in turn - HWPFDocument docA = new HWPFDocument(dirA); - WordExtractor extractorA = new WordExtractor(docA); - - assertNotNull(extractorA.getText()); - assertTrue(extractorA.getText().length() > 20); - assertEqualsTrim("I am a sample document\r\nNot much on me\r\nI am document 1\r\n", extractorA.getText()); - assertEquals("Sample Doc 1", extractorA.getSummaryInformation().getTitle()); - assertEquals("Sample Test", extractorA.getSummaryInformation().getSubject()); - - HWPFDocument docB = new HWPFDocument(dirB); - WordExtractor extractorB = new WordExtractor(docB); - - assertNotNull(extractorB.getText()); - assertTrue(extractorB.getText().length() > 20); - assertEqualsTrim("I am another sample document\r\nNot much on me\r\nI am document 2\r\n", extractorB.getText()); - assertEquals("Sample Doc 2", extractorB.getSummaryInformation().getTitle()); - assertEquals("Another Sample Test", extractorB.getSummaryInformation().getSubject()); - - extractorA.close(); - docA.close(); - - extractorB.close(); - docB.close(); - - fs.close(); - } - - @Test - public void testWithHeader() throws IOException { - // Non-unicode - HWPFDocument doc1 = HWPFTestDataSamples.openSampleFile("ThreeColHeadFoot.doc"); - WordExtractor extractor1 = new WordExtractor(doc1); - - assertEquals("First header column!\tMid header Right header!\n", extractor1.getHeaderText()); - assertContains(extractor1.getText(), "First header column!"); - extractor1.close(); - doc1.close(); - - // Unicode - HWPFDocument doc2 = HWPFTestDataSamples.openSampleFile("HeaderFooterUnicode.doc"); - WordExtractor extractor2 = new WordExtractor(doc2); - - assertEquals("This is a simple header, with a \u20ac euro symbol in it.\n\n", extractor2.getHeaderText()); - assertContains(extractor2.getText(), "This is a simple header"); - extractor2.close(); - doc2.close(); - } - - @Test - public void testWithFooter() throws IOException { - // Non-unicode - HWPFDocument doc1 = HWPFTestDataSamples.openSampleFile("ThreeColHeadFoot.doc"); - WordExtractor extractor1 = new WordExtractor(doc1); - - assertEquals("Footer Left\tFooter Middle Footer Right\n", extractor1.getFooterText()); - assertContains(extractor1.getText(), "Footer Left"); - extractor1.close(); - doc1.close(); - - // Unicode - HWPFDocument doc2 = HWPFTestDataSamples.openSampleFile("HeaderFooterUnicode.doc"); - WordExtractor extractor2 = new WordExtractor(doc2); - - assertEquals("The footer, with Moli\u00e8re, has Unicode in it.\n", extractor2.getFooterText()); - assertContains(extractor2.getText(), "The footer, with"); - extractor2.close(); - doc2.close(); - } - - @Test - public void testFootnote() throws IOException { - HWPFDocument doc = HWPFTestDataSamples.openSampleFile("footnote.doc"); - WordExtractor extractor = new WordExtractor(doc); - - assertExtractedContains(extractor.getFootnoteText(), "TestFootnote"); - assertEquals(0x00, doc.getRange().getSection(0).getFootnoteNumberingFormat()); // msonfcArabic - assertEquals(0x00, doc.getRange().getSection(0).getFootnoteRestartQualifier()); // rncCont - assertEquals(0, doc.getRange().getSection(0).getFootnoteNumberingOffset()); - assertEquals(1, doc.getFootnotes().getNotesCount()); - extractor.close(); - doc.close(); - } - - @Test - public void testEndnote() throws IOException { - HWPFDocument doc = HWPFTestDataSamples.openSampleFile("footnote.doc"); - WordExtractor extractor = new WordExtractor(doc); - - assertExtractedContains(extractor.getEndnoteText(), "TestEndnote"); - assertEquals(0x02, doc.getRange().getSection(0).getEndnoteNumberingFormat()); // msonfcLCRoman - assertEquals(0x00, doc.getRange().getSection(0).getEndnoteRestartQualifier()); // rncCont - assertEquals(0, doc.getRange().getSection(0).getEndnoteNumberingOffset()); - assertEquals(1, doc.getEndnotes().getNotesCount()); - extractor.close(); - doc.close(); - } - - @Test - public void testComments() throws IOException { - WordExtractor extractor = openExtractor("footnote.doc"); - assertExtractedContains(extractor.getCommentsText(), "TestComment"); - extractor.close(); - } - - @Test(expected=OldWordFileFormatException.class) - public void testWord95_WordExtractor() throws Exception { - // Too old for the default - openExtractor("Word95.doc").close(); - } - - @Test - public void testWord95() throws Exception { - // Can work with the special one - InputStream is = docTests.openResourceAsStream("Word95.doc"); - Word6Extractor w6e = new Word6Extractor(is); - is.close(); - - String text = w6e.getText(); - - assertTrue(text.contains("The quick brown fox jumps over the lazy dog")); - assertTrue(text.contains("Paragraph 2")); - assertTrue(text.contains("Paragraph 3. Has some RED text and some BLUE BOLD text in it")); - assertTrue(text.contains("Last (4th) paragraph")); - - String[] tp = w6e.getParagraphText(); - assertEquals(7, tp.length); - assertEquals("The quick brown fox jumps over the lazy dog\r\n", tp[0]); - assertEquals("\r\n", tp[1]); - assertEquals("Paragraph 2\r\n", tp[2]); - assertEquals("\r\n", tp[3]); - assertEquals("Paragraph 3. Has some RED text and some BLUE BOLD text in it.\r\n", tp[4]); - assertEquals("\r\n", tp[5]); - assertEquals("Last (4th) paragraph.\r\n", tp[6]); - w6e.close(); - } - - @Test(expected=OldWordFileFormatException.class) - public void testWord6_WordExtractor() throws IOException { - // Too old for the default - openExtractor("Word6.doc").close(); - } - - @Test - public void testWord6() throws Exception { - InputStream is = docTests.openResourceAsStream("Word6.doc"); - Word6Extractor w6e = new Word6Extractor(is); - is.close(); - String text = w6e.getText(); - - assertTrue(text.contains("The quick brown fox jumps over the lazy dog")); - - String[] tp = w6e.getParagraphText(); - assertEquals(1, tp.length); - assertEquals("The quick brown fox jumps over the lazy dog\r\n", tp[0]); - w6e.close(); - } - - @Test - public void testFastSaved() throws Exception { - WordExtractor extractor = openExtractor("rasp.doc"); - - String text = extractor.getText(); - assertTrue(text.contains("\u0425\u0425\u0425\u0425\u0425")); - assertTrue(text.contains("\u0423\u0423\u0423\u0423\u0423")); - - extractor.close(); - } - - @Test - public void testFirstParagraphFix() throws Exception { - WordExtractor extractor = openExtractor("Bug48075.doc"); - - String text = extractor.getText(); - - assertTrue(text.startsWith("\u041f\u0440\u0438\u043b\u043e\u0436\u0435\u043d\u0438\u0435")); - extractor.close(); - } - - /** - * Tests that we can work with both {@link POIFSFileSystem} - * and {@link NPOIFSFileSystem} - */ - @Test - public void testDifferentPOIFS() throws Exception { - // Open the two filesystems - File file = docTests.getFile("test2.doc"); - InputStream is = new FileInputStream(file); - OPOIFSFileSystem opoifs = new OPOIFSFileSystem(is); - is.close(); - NPOIFSFileSystem npoifs = new NPOIFSFileSystem(file); - - DirectoryNode[] files = { opoifs.getRoot(), npoifs.getRoot() }; - - // Open directly - for(DirectoryNode dir : files) { - @SuppressWarnings("resource") - WordExtractor extractor = new WordExtractor(dir); - assertEqualsTrim(p_text1_block, extractor.getText()); - // extractor.close(); - } - - // Open via a HWPFDocument - for(DirectoryNode dir : files) { - HWPFDocument doc = new HWPFDocument(dir); - WordExtractor extractor = new WordExtractor(doc); - assertEqualsTrim(p_text1_block, extractor.getText()); - extractor.close(); - } - - npoifs.close(); - } - - /** - * [RESOLVED FIXED] Bug 51686 - Update to POI 3.8 beta 4 causes - * ConcurrentModificationException in Tika's OfficeParser - */ - @Test - public void testBug51686() throws IOException { - InputStream is = docTests.openResourceAsStream( "Bug51686.doc" ); - POIFSFileSystem fs = new POIFSFileSystem(is); - is.close(); - - String text = null; - - for (Entry entry : fs.getRoot()) { - if ("WordDocument".equals(entry.getName())) { - WordExtractor ex = new WordExtractor(fs); - try { - text = ex.getText(); - } finally { - ex.close(); - } - } - } - - assertNotNull(text); - fs.close(); - } - - @Test - public void testExtractorFromWord6Extractor() throws Exception { - InputStream is = POIDataSamples.getHPSFInstance().openResourceAsStream("TestMickey.doc"); - POIFSFileSystem fs = new POIFSFileSystem(is); - is.close(); - Word6Extractor wExt = new Word6Extractor(fs); - try { - POITextExtractor ext = wExt.getMetadataTextExtractor(); - try { - // Now overall - String text = ext.getText(); - assertContains(text, "TEMPLATE = Normal"); - assertContains(text, "SUBJECT = sample subject"); - assertContains(text, "MANAGER = sample manager"); - assertContains(text, "COMPANY = sample company"); - } finally { - ext.close(); - } - } finally { - wExt.close(); - fs.close(); - } - } - - private WordExtractor openExtractor(String fileName) throws IOException { - InputStream is = docTests.openResourceAsStream(fileName); - try { - return new WordExtractor(is); - } finally { - is.close(); - } - - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/extractor/TestWordExtractorBugs.java b/src/scratchpad/testcases/org/apache/poi/hwpf/extractor/TestWordExtractorBugs.java deleted file mode 100644 index fc1011470..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/extractor/TestWordExtractorBugs.java +++ /dev/null @@ -1,55 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.extractor; - -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.POIDataSamples; -import org.junit.Test; - -/** - * Tests for bugs with the WordExtractor - */ -public final class TestWordExtractorBugs { - private static final POIDataSamples SAMPLES = POIDataSamples.getDocumentInstance(); - - @Test - public void testProblemMetadata() throws IOException { - InputStream is = SAMPLES.openResourceAsStream("ProblemExtracting.doc"); - WordExtractor extractor = new WordExtractor(is); - is.close(); - - // Check it gives text without error - extractor.getText(); - extractor.getParagraphText(); - extractor.getTextFromPieces(); - extractor.close(); - } - - @Test - public void testBug50688() throws Exception { - InputStream is = SAMPLES.openResourceAsStream("parentinvguid.doc"); - WordExtractor extractor = new WordExtractor(is); - is.close(); - - // Check it gives text without error - extractor.getText(); - extractor.close(); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/model/PlfLfoTest.java b/src/scratchpad/testcases/org/apache/poi/hwpf/model/PlfLfoTest.java deleted file mode 100644 index b9dafae62..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/model/PlfLfoTest.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -package org.apache.poi.hwpf.model; - -import org.junit.Test; - -import static org.junit.Assert.*; - -public class PlfLfoTest { - @Test - public void testAdd() { - PlfLfo p = new PlfLfo(new byte[] {0, 0, 0, 0}, 0, 0); - assertEquals(0, p.getLfoMac()); - p.add(new LFO(new byte[] {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, 0), new LFOData()); - assertEquals(1, p.getLfoMac()); - assertNotNull(p.getLfo(1)); - assertNotNull(p.getLfoData(1)); - } - - @Test - public void testEquals() { - PlfLfo p = new PlfLfo(new byte[] {0, 0, 0, 0}, 0, 0); - PlfLfo p2 = new PlfLfo(new byte[] {0, 0, 0, 0}, 0, 0); - assertEquals(0, p.getLfoMac()); - assertEquals(0, p2.getLfoMac()); - - assertTrue(p.equals(p2)); - //noinspection ObjectEqualsNull - assertFalse(p.equals(null)); - - p.add(new LFO(new byte[] {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, 0), new LFOData()); - assertEquals(1, p.getLfoMac()); - - assertFalse(p.equals(p2)); - - p2.add(new LFO(new byte[] {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, 0), new LFOData()); - assertEquals(1, p2.getLfoMac()); - assertTrue(p.equals(p2)); - } -} \ No newline at end of file diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestBookmarksTables.java b/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestBookmarksTables.java deleted file mode 100644 index 4e013b3b7..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestBookmarksTables.java +++ /dev/null @@ -1,96 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hwpf.model; - -import org.apache.poi.hwpf.usermodel.Range; - -import junit.framework.TestCase; - -import org.apache.poi.hwpf.HWPFDocument; -import org.apache.poi.hwpf.HWPFTestDataSamples; -import org.apache.poi.hwpf.usermodel.Bookmark; -import org.apache.poi.hwpf.usermodel.Bookmarks; - -/** - * Test cases for {@link BookmarksTables} and default implementation of - * {@link Bookmarks} - * - * @author Sergey Vladimirov (vlsergey {at} gmail {dot} com) - */ -public class TestBookmarksTables extends TestCase -{ - public void test() - { - HWPFDocument doc = HWPFTestDataSamples.openSampleFile( "pageref.doc" ); - Bookmarks bookmarks = doc.getBookmarks(); - - assertEquals( 1, bookmarks.getBookmarksCount() ); - - Bookmark bookmark = bookmarks.getBookmark( 0 ); - assertEquals( "userref", bookmark.getName() ); - assertEquals( 27, bookmark.getStart() ); - assertEquals( 38, bookmark.getEnd() ); - } - - public void testDeleteRange() - { - HWPFDocument doc = HWPFTestDataSamples.openSampleFile( "pageref.doc" ); - Range range = new Range( 27, 41, doc ); - range.delete(); - - assertEquals( 0, doc.getBookmarks().getBookmarksCount() ); - } - - public void testReplaceTextAfter() - { - HWPFDocument doc = HWPFTestDataSamples.openSampleFile( "pageref.doc" ); - Bookmark bookmark = doc.getBookmarks().getBookmark( 0 ); - Range range = new Range( bookmark.getStart(), bookmark.getEnd(), doc ); - range.replaceText( "1destin2ation3", true ); - - bookmark = doc.getBookmarks().getBookmark( 0 ); - assertEquals( "userref", bookmark.getName() ); - assertEquals( 27, bookmark.getStart() ); - assertEquals( 41, bookmark.getEnd() ); - } - - public void testReplaceTextBefore() - { - HWPFDocument doc = HWPFTestDataSamples.openSampleFile( "pageref.doc" ); - Bookmark bookmark = doc.getBookmarks().getBookmark( 0 ); - Range range = new Range( bookmark.getStart(), bookmark.getEnd(), doc ); - range.replaceText( "1destin2ation3", false ); - - bookmark = doc.getBookmarks().getBookmark( 0 ); - assertEquals( "userref", bookmark.getName() ); - assertEquals( 27, bookmark.getStart() ); - assertEquals( 41, bookmark.getEnd() ); - } - - public void testUpdateText() - { - HWPFDocument doc = HWPFTestDataSamples.openSampleFile( "pageref.doc" ); - Bookmark bookmark = doc.getBookmarks().getBookmark( 0 ); - Range range = new Range( bookmark.getStart(), bookmark.getEnd(), doc ); - range.replaceText( "destination", "1destin2ation3" ); - - bookmark = doc.getBookmarks().getBookmark( 0 ); - assertEquals( "userref", bookmark.getName() ); - assertEquals( 27, bookmark.getStart() ); - assertEquals( 41, bookmark.getEnd() ); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestCHPBinTable.java b/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestCHPBinTable.java deleted file mode 100644 index 759e1afb0..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestCHPBinTable.java +++ /dev/null @@ -1,97 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.model; - -import java.io.ByteArrayOutputStream; -import java.util.List; - -import junit.framework.TestCase; - -import org.apache.poi.hwpf.HWPFDocFixture; -import org.apache.poi.hwpf.model.io.HWPFFileSystem; - -public final class TestCHPBinTable - extends TestCase -{ - private CHPBinTable _cHPBinTable = null; - private HWPFDocFixture _hWPFDocFixture; - - private final TextPieceTable fakeTPT = new TextPieceTable() { - @Override - public boolean isIndexInTable(int bytePos) { - return true; - } - }; - - public void testReadWrite() - throws Exception - { - FileInformationBlock fib = _hWPFDocFixture._fib; - byte[] mainStream = _hWPFDocFixture._mainStream; - byte[] tableStream = _hWPFDocFixture._tableStream; - int fcMin = fib.getFibBase().getFcMin(); - - _cHPBinTable = new CHPBinTable(mainStream, tableStream, fib.getFcPlcfbteChpx(), fib.getLcbPlcfbteChpx(), fakeTPT); - - HWPFFileSystem fileSys = new HWPFFileSystem(); - - _cHPBinTable.writeTo(fileSys, 0, fakeTPT); - ByteArrayOutputStream tableOut = fileSys.getStream("1Table"); - ByteArrayOutputStream mainOut = fileSys.getStream("WordDocument"); - - byte[] newTableStream = tableOut.toByteArray(); - byte[] newMainStream = mainOut.toByteArray(); - - CHPBinTable newBinTable = new CHPBinTable(newMainStream, newTableStream, 0, newTableStream.length, fakeTPT); - - List oldTextRuns = _cHPBinTable._textRuns; - List newTextRuns = newBinTable._textRuns; - - assertEquals(oldTextRuns.size(), newTextRuns.size()); - - int size = oldTextRuns.size(); - for (int x = 0; x < size; x++) - { - CHPX oldNode = oldTextRuns.get(x); - CHPX newNode = newTextRuns.get(x); - assertTrue(oldNode.equals(newNode)); - } - - } - @Override -protected void setUp() - throws Exception - { - super.setUp(); - _hWPFDocFixture = new HWPFDocFixture(this, HWPFDocFixture.DEFAULT_TEST_FILE); - - _hWPFDocFixture.setUp(); - } - - @Override -protected void tearDown() - throws Exception - { - _cHPBinTable = null; - _hWPFDocFixture.tearDown(); - - _hWPFDocFixture = null; - super.tearDown(); - } - -} diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestDocumentProperties.java b/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestDocumentProperties.java deleted file mode 100644 index 9dfc57208..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestDocumentProperties.java +++ /dev/null @@ -1,58 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.model; - -import static org.apache.poi.POITestCase.assertReflectEquals; - -import org.apache.poi.hwpf.HWPFDocFixture; -import org.apache.poi.hwpf.model.types.DOPAbstractType; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -// TODO: Add DocumentProperties#equals ??? - -public final class TestDocumentProperties { - private DocumentProperties _documentProperties = null; - private HWPFDocFixture _hWPFDocFixture; - - @Test - public void testReadWrite() throws Exception { - int size = DOPAbstractType.getSize(); - byte[] buf = new byte[size]; - _documentProperties.serialize(buf, 0); - DocumentProperties newDocProperties = new DocumentProperties(buf, 0, size); - - assertReflectEquals(_documentProperties, newDocProperties); - } - - @Before - public void setUp() throws Exception { - /** TODO verify the constructors*/ - _hWPFDocFixture = new HWPFDocFixture(this, HWPFDocFixture.DEFAULT_TEST_FILE); - _hWPFDocFixture.setUp(); - _documentProperties = new DocumentProperties(_hWPFDocFixture._tableStream, _hWPFDocFixture._fib.getFcDop(), _hWPFDocFixture._fib.getLcbDop()); - } - - @After - public void tearDown() throws Exception { - _documentProperties = null; - _hWPFDocFixture.tearDown(); - _hWPFDocFixture = null; - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestFileInformationBlock.java b/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestFileInformationBlock.java deleted file mode 100644 index e6e21458c..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestFileInformationBlock.java +++ /dev/null @@ -1,60 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.model; - -import static org.apache.poi.POITestCase.assertReflectEquals; -import static org.junit.Assert.assertNotNull; - -import org.apache.poi.hwpf.HWPFDocFixture; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public final class TestFileInformationBlock { - private FileInformationBlock _fileInformationBlock = null; - private HWPFDocFixture _hWPFDocFixture; - - @Test - public void testReadWrite() throws Exception { - final FibBase expected = _fileInformationBlock.getFibBase(); - int size = _fileInformationBlock.getSize(); - byte[] buf = new byte[size]; - expected.serialize(buf, 0); - - FileInformationBlock newFileInformationBlock = new FileInformationBlock(buf); - FibBase actual = newFileInformationBlock.getFibBase(); - - assertReflectEquals(expected, actual); - assertNotNull(_fileInformationBlock.toString()); - } - - @Before - public void setUp() throws Exception { - /** @todo verify the constructors */ - _hWPFDocFixture = new HWPFDocFixture(this, HWPFDocFixture.DEFAULT_TEST_FILE); - _hWPFDocFixture.setUp(); - _fileInformationBlock = _hWPFDocFixture._fib; - } - - @After - public void tearDown() throws Exception { - _fileInformationBlock = null; - _hWPFDocFixture.tearDown(); - _hWPFDocFixture = null; - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestFontTable.java b/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestFontTable.java deleted file mode 100644 index fa4dc3e12..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestFontTable.java +++ /dev/null @@ -1,78 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.model; - -import junit.framework.*; -import org.apache.poi.hwpf.*; -import org.apache.poi.hwpf.model.io.*; - -public final class TestFontTable - extends TestCase -{ - private FontTable _fontTable = null; - private HWPFDocFixture _hWPFDocFixture; - - public void testReadWrite() - throws Exception - { - FileInformationBlock fib = _hWPFDocFixture._fib; - byte[] tableStream = _hWPFDocFixture._tableStream; - - int fcSttbfffn = fib.getFcSttbfffn(); - int lcbSttbfffn = fib.getLcbSttbfffn(); - - _fontTable = new FontTable(tableStream, fcSttbfffn, lcbSttbfffn); - - HWPFFileSystem fileSys = new HWPFFileSystem(); - - _fontTable.writeTo(fileSys); - HWPFOutputStream tableOut = fileSys.getStream("1Table"); - - - byte[] newTableStream = tableOut.toByteArray(); - - - FontTable newFontTable = new FontTable(newTableStream, 0, newTableStream.length); - - assertTrue(_fontTable.equals(newFontTable)); - - } - - @Override -protected void setUp() - throws Exception - { - super.setUp(); - /**@todo verify the constructors*/ - _hWPFDocFixture = new HWPFDocFixture(this, HWPFDocFixture.DEFAULT_TEST_FILE); - - _hWPFDocFixture.setUp(); - } - - @Override -protected void tearDown() - throws Exception - { - _hWPFDocFixture.tearDown(); - - _hWPFDocFixture = null; - super.tearDown(); - } - -} - diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestListTables.java b/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestListTables.java deleted file mode 100644 index aed56038e..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestListTables.java +++ /dev/null @@ -1,57 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.model; - -import static org.junit.Assert.assertEquals; - -import java.io.IOException; - -import org.apache.poi.hwpf.HWPFTestCase; -import org.apache.poi.hwpf.model.io.HWPFFileSystem; -import org.apache.poi.hwpf.model.io.HWPFOutputStream; -import org.junit.Test; - -public final class TestListTables extends HWPFTestCase { - - @Test - public void testReadWrite() throws IOException { - FileInformationBlock fib = _hWPFDocFixture._fib; - byte[] tableStream = _hWPFDocFixture._tableStream; - - int listOffset = fib.getFcPlfLst(); - int lfoOffset = fib.getFcPlfLfo(); - int bLfoOffset = fib.getLcbPlfLfo(); - - if (listOffset != 0 && bLfoOffset != 0) { - // TODO: this is actually never executed ... - - ListTables listTables = new ListTables(tableStream, listOffset, lfoOffset, bLfoOffset); - HWPFFileSystem fileSys = new HWPFFileSystem(); - - HWPFOutputStream tableOut = fileSys.getStream("1Table"); - - listTables.writeListDataTo(fib, tableOut); - listTables.writeListOverridesTo(fib, tableOut); - - ListTables newTables = new ListTables(tableOut.toByteArray(), - fib.getFcPlfLst(), fib.getFcPlfLfo(), fib.getLcbPlfLfo()); - - assertEquals(listTables, newTables); - } - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestNotesTables.java b/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestNotesTables.java deleted file mode 100644 index 4679d24f6..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestNotesTables.java +++ /dev/null @@ -1,45 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hwpf.model; - -import junit.framework.TestCase; - -import org.apache.poi.hwpf.HWPFDocument; -import org.apache.poi.hwpf.HWPFTestDataSamples; -import org.apache.poi.hwpf.usermodel.Notes; - -/** - * Test cases for {@link NotesTables} and default implementation of - * {@link Notes} - * - * @author Sergey Vladimirov (vlsergey {at} gmail {dot} com) - */ -public class TestNotesTables extends TestCase -{ - public void test() - { - HWPFDocument doc = HWPFTestDataSamples - .openSampleFile( "endingnote.doc" ); - Notes notes = doc.getEndnotes(); - - assertEquals( 1, notes.getNotesCount() ); - - assertEquals( 10, notes.getNoteAnchorPosition( 0 ) ); - assertEquals( 0, notes.getNoteTextStartOffset( 0 ) ); - assertEquals( 19, notes.getNoteTextEndOffset( 0 ) ); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestPAPBinTable.java b/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestPAPBinTable.java deleted file mode 100644 index a642d1900..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestPAPBinTable.java +++ /dev/null @@ -1,81 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.model; - -import java.util.List; - -import junit.framework.TestCase; - -import org.apache.poi.hwpf.HWPFDocFixture; -import org.apache.poi.hwpf.HWPFTestDataSamples; -import org.apache.poi.hwpf.model.io.HWPFFileSystem; -import org.apache.poi.hwpf.model.io.HWPFOutputStream; - -public final class TestPAPBinTable extends TestCase -{ - - public void testObIs() - { - // shall not fail with assertions on - HWPFTestDataSamples.openSampleFile( "ob_is.doc" ); - } - - public void testReadWrite() throws Exception - { - /** @todo verify the constructors */ - HWPFDocFixture _hWPFDocFixture = new HWPFDocFixture( this, - HWPFDocFixture.DEFAULT_TEST_FILE ); - - _hWPFDocFixture.setUp(); - TextPieceTable fakeTPT = new TextPieceTable(); - - FileInformationBlock fib = _hWPFDocFixture._fib; - byte[] mainStream = _hWPFDocFixture._mainStream; - byte[] tableStream = _hWPFDocFixture._tableStream; - - PAPBinTable _pAPBinTable = new PAPBinTable( mainStream, tableStream, - null, fib.getFcPlcfbtePapx(), fib.getLcbPlcfbtePapx(), fakeTPT ); - - HWPFFileSystem fileSys = new HWPFFileSystem(); - HWPFOutputStream tableOut = fileSys.getStream( "1Table" ); - HWPFOutputStream mainOut = fileSys.getStream( "WordDocument" ); - _pAPBinTable.writeTo( mainOut, tableOut, fakeTPT ); - - byte[] newTableStream = tableOut.toByteArray(); - byte[] newMainStream = mainOut.toByteArray(); - - PAPBinTable newBinTable = new PAPBinTable( newMainStream, - newTableStream, null, 0, newTableStream.length, fakeTPT ); - - List oldTextRuns = _pAPBinTable.getParagraphs(); - List newTextRuns = newBinTable.getParagraphs(); - - assertEquals( oldTextRuns.size(), newTextRuns.size() ); - - int size = oldTextRuns.size(); - for ( int x = 0; x < size; x++ ) - { - PAPX oldNode = oldTextRuns.get( x ); - PAPX newNode = newTextRuns.get( x ); - - assertTrue( oldNode.equals( newNode ) ); - } - - _hWPFDocFixture.tearDown(); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestPlexOfCps.java b/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestPlexOfCps.java deleted file mode 100644 index 07540541e..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestPlexOfCps.java +++ /dev/null @@ -1,81 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.model; - -import junit.framework.*; -import org.apache.poi.hwpf.*; - -import org.apache.poi.util.LittleEndian; - -public final class TestPlexOfCps - extends TestCase -{ - private PlexOfCps _plexOfCps = null; - private HWPFDocFixture _hWPFDocFixture; - - public void testWriteRead() { - _plexOfCps = new PlexOfCps(4); - - int last = 0; - for (int x = 0; x < 110; x++) - { - byte[] intHolder = new byte[4]; - int span = (int)(110.0f * Math.random()); - LittleEndian.putInt(intHolder, 0, span); - _plexOfCps.addProperty(new GenericPropertyNode(last, last + span, intHolder)); - last += span; - } - - byte[] output = _plexOfCps.toByteArray(); - _plexOfCps = new PlexOfCps(output, 0, output.length, 4); - int len = _plexOfCps.length(); - assertEquals(len, 110); - - last = 0; - for (int x = 0; x < len; x++) - { - GenericPropertyNode node = _plexOfCps.getProperty(x); - assertEquals(node.getStart(), last); - last = node.getEnd(); - int span = LittleEndian.getInt(node.getBytes()); - assertEquals(node.getEnd()-node.getStart(), span); - } - } - @Override -protected void setUp() - throws Exception - { - super.setUp(); - /**@todo verify the constructors*/ - _hWPFDocFixture = new HWPFDocFixture(this, HWPFDocFixture.DEFAULT_TEST_FILE); - - _hWPFDocFixture.setUp(); - } - - @Override -protected void tearDown() - throws Exception - { - _plexOfCps = null; - _hWPFDocFixture.tearDown(); - - _hWPFDocFixture = null; - super.tearDown(); - } - -} diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestRevisionMarkAuthorTable.java b/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestRevisionMarkAuthorTable.java deleted file mode 100644 index 6ef2d2b90..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestRevisionMarkAuthorTable.java +++ /dev/null @@ -1,74 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.model; - -import junit.framework.TestCase; - -import org.apache.poi.hwpf.HWPFDocument; -import org.apache.poi.hwpf.HWPFTestDataSamples; - -/** - * Test the table which handles author revision marks - */ -public final class TestRevisionMarkAuthorTable extends TestCase { - /** - * Tests that an empty file doesn't have one - */ - public void testEmptyDocument() { - HWPFDocument doc = HWPFTestDataSamples.openSampleFile("empty.doc"); - - RevisionMarkAuthorTable rmt = doc.getRevisionMarkAuthorTable(); - assertNull(rmt); - } - - /** - * Tests that we can load a document with - * only simple entries in the table - */ - public void testSimpleDocument() { - HWPFDocument doc = HWPFTestDataSamples.openSampleFile("two_images.doc"); - - RevisionMarkAuthorTable rmt = doc.getRevisionMarkAuthorTable(); - assertNotNull(rmt); - assertEquals(1, rmt.getSize()); - assertEquals("Unknown", rmt.getAuthor(0)); - - assertEquals(null, rmt.getAuthor(1)); - assertEquals(null, rmt.getAuthor(2)); - assertEquals(null, rmt.getAuthor(3)); - } - - /** - * Several authors, one of whom has no name - */ - public void testMultipleAuthors() { - HWPFDocument doc = HWPFTestDataSamples.openSampleFile("MarkAuthorsTable.doc"); - - RevisionMarkAuthorTable rmt = doc.getRevisionMarkAuthorTable(); - assertNotNull(rmt); - assertEquals(4, rmt.getSize()); - assertEquals("Unknown", rmt.getAuthor(0)); - assertEquals("BSanders", rmt.getAuthor(1)); - assertEquals(" ", rmt.getAuthor(2)); - assertEquals("Ryan Lauck", rmt.getAuthor(3)); - - assertEquals(null, rmt.getAuthor(4)); - assertEquals(null, rmt.getAuthor(5)); - assertEquals(null, rmt.getAuthor(6)); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestSavedByTable.java b/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestSavedByTable.java deleted file mode 100644 index e10640a91..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestSavedByTable.java +++ /dev/null @@ -1,83 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.model; - -import static org.junit.Assert.assertEquals; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.Arrays; -import java.util.List; - -import org.apache.poi.hwpf.HWPFDocument; -import org.apache.poi.hwpf.HWPFTestDataSamples; -import org.junit.Test; - -/** - * Unit test for {@link SavedByTable} and {@link SavedByEntry}. - */ -public final class TestSavedByTable { - - /** The expected entries in the test document. */ - private final List expected = Arrays.asList( - new SavedByEntry("cic22", "C:\\DOCUME~1\\phamill\\LOCALS~1\\Temp\\AutoRecovery save of Iraq - security.asd"), - new SavedByEntry("cic22", "C:\\DOCUME~1\\phamill\\LOCALS~1\\Temp\\AutoRecovery save of Iraq - security.asd"), - new SavedByEntry("cic22", "C:\\DOCUME~1\\phamill\\LOCALS~1\\Temp\\AutoRecovery save of Iraq - security.asd"), - new SavedByEntry("JPratt", "C:\\TEMP\\Iraq - security.doc"), - new SavedByEntry("JPratt", "A:\\Iraq - security.doc"), - new SavedByEntry("ablackshaw", "C:\\ABlackshaw\\Iraq - security.doc"), - new SavedByEntry("ablackshaw", "C:\\ABlackshaw\\A;Iraq - security.doc"), - new SavedByEntry("ablackshaw", "A:\\Iraq - security.doc"), - new SavedByEntry("MKhan", "C:\\TEMP\\Iraq - security.doc"), - new SavedByEntry("MKhan", "C:\\WINNT\\Profiles\\mkhan\\Desktop\\Iraq.doc") - ); - - /** - * Tests reading in the entries, comparing them against the expected - * entries. Then tests writing the document out and reading the entries yet - * again. - * - * @throws Exception if an unexpected error occurs. - */ - @Test - public void testReadWrite() throws IOException { - // This document is widely available on the internet as "blair.doc". - // I tried stripping the content and saving the document but my version - // of Word (from Office XP) strips this table out. - HWPFDocument doc = HWPFTestDataSamples.openSampleFile("saved-by-table.doc"); - - // Check what we just read. - assertEquals("List of saved-by entries was not as expected", expected, - doc.getSavedByTable().getEntries()); - - // Now write the entire document out, and read it back in... - ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); - doc.write(byteStream); - InputStream copyStream = new ByteArrayInputStream(byteStream.toByteArray()); - doc.close(); - HWPFDocument copy = new HWPFDocument(copyStream); - - // And check again. - assertEquals("List of saved-by entries was incorrect after writing", - expected, copy.getSavedByTable().getEntries()); - - copy.close(); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestSectionTable.java b/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestSectionTable.java deleted file mode 100644 index 1ca57b098..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestSectionTable.java +++ /dev/null @@ -1,109 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.model; - -import junit.framework.*; - -import java.io.ByteArrayOutputStream; -import java.util.List; - -import org.apache.poi.hwpf.*; -import org.apache.poi.hwpf.model.io.*; - -public final class TestSectionTable - extends TestCase -{ - private HWPFDocFixture _hWPFDocFixture; - - public void testReadWrite() - throws Exception - { - FileInformationBlock fib = _hWPFDocFixture._fib; - byte[] mainStream = _hWPFDocFixture._mainStream; - byte[] tableStream = _hWPFDocFixture._tableStream; - int fcMin = fib.getFibBase().getFcMin(); - - ComplexFileTable cft = new ComplexFileTable(mainStream, tableStream, fib.getFcClx(), fcMin); - TextPieceTable tpt = cft.getTextPieceTable(); - - SectionTable sectionTable = new SectionTable(mainStream, tableStream, - fib.getFcPlcfsed(), - fib.getLcbPlcfsed(), - fcMin, tpt, fib.getSubdocumentTextStreamLength( SubdocumentType.MAIN )); - HWPFFileSystem fileSys = new HWPFFileSystem(); - - sectionTable.writeTo(fileSys, 0); - ByteArrayOutputStream tableOut = fileSys.getStream("1Table"); - ByteArrayOutputStream mainOut = fileSys.getStream("WordDocument"); - - byte[] newTableStream = tableOut.toByteArray(); - byte[] newMainStream = mainOut.toByteArray(); - - SectionTable newSectionTable = new SectionTable( - newMainStream, newTableStream, 0, - newTableStream.length, 0, tpt, fib.getSubdocumentTextStreamLength( SubdocumentType.MAIN )); - - List oldSections = sectionTable.getSections(); - List newSections = newSectionTable.getSections(); - - assertEquals(oldSections.size(), newSections.size()); - - //test for proper char offset conversions - PlexOfCps oldSedPlex = new PlexOfCps(tableStream, fib.getFcPlcfsed(), - fib.getLcbPlcfsed(), 12); - PlexOfCps newSedPlex = new PlexOfCps(newTableStream, 0, - newTableStream.length, 12); - assertEquals(oldSedPlex.length(), newSedPlex.length()); - - for (int x = 0; x < oldSedPlex.length(); x++) - { - assertEquals(oldSedPlex.getProperty(x).getStart(), newSedPlex.getProperty(x).getStart()); - assertEquals(oldSedPlex.getProperty(x).getEnd(), newSedPlex.getProperty(x).getEnd()); - } - - int size = oldSections.size(); - for (int x = 0; x < size; x++) - { - SEPX oldNode = oldSections.get(x); - SEPX newNode = newSections.get(x); - assertEquals(oldNode, newNode); - } - } - - @Override -protected void setUp() - throws Exception - { - super.setUp(); - /**@todo verify the constructors*/ - _hWPFDocFixture = new HWPFDocFixture(this, HWPFDocFixture.DEFAULT_TEST_FILE); - - _hWPFDocFixture.setUp(); - } - - @Override -protected void tearDown() - throws Exception - { - _hWPFDocFixture.tearDown(); - - _hWPFDocFixture = null; - super.tearDown(); - } - -} diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestStyleSheet.java b/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestStyleSheet.java deleted file mode 100644 index 41677ddfb..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestStyleSheet.java +++ /dev/null @@ -1,91 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.model; - -import junit.framework.*; - -import org.apache.poi.hwpf.*; -import org.apache.poi.hwpf.model.io.*; - -public final class TestStyleSheet - extends TestCase -{ - private StyleSheet _styleSheet = null; - private HWPFDocFixture _hWPFDocFixture; - - public void testReadWrite() - throws Exception - { - HWPFFileSystem fileSys = new HWPFFileSystem(); - - - HWPFOutputStream tableOut = fileSys.getStream("1Table"); - HWPFOutputStream mainOut = fileSys.getStream("WordDocument"); - - _styleSheet.writeTo(tableOut); - - byte[] newTableStream = tableOut.toByteArray(); - - StyleSheet newStyleSheet = new StyleSheet(newTableStream, 0); - assertEquals(newStyleSheet, _styleSheet); - - } - - public void testReadWriteFromNonZeroOffset() - throws Exception - { - HWPFFileSystem fileSys = new HWPFFileSystem(); - HWPFOutputStream tableOut = fileSys.getStream("1Table"); - - tableOut.write(new byte[20]); // 20 bytes of whatever at the front. - _styleSheet.writeTo(tableOut); - - byte[] newTableStream = tableOut.toByteArray(); - - StyleSheet newStyleSheet = new StyleSheet(newTableStream, 20); - assertEquals(newStyleSheet, _styleSheet); - } - - @Override -protected void setUp() - throws Exception - { - super.setUp(); - /**@todo verify the constructors*/ - _hWPFDocFixture = new HWPFDocFixture(this, HWPFDocFixture.DEFAULT_TEST_FILE); - _hWPFDocFixture.setUp(); - FileInformationBlock fib = _hWPFDocFixture._fib; - byte[] mainStream = _hWPFDocFixture._mainStream; - byte[] tableStream = _hWPFDocFixture._tableStream; - - _hWPFDocFixture.setUp(); - _styleSheet = new StyleSheet(tableStream, fib.getFcStshf()); - } - - @Override -protected void tearDown() - throws Exception - { - _styleSheet = null; - _hWPFDocFixture.tearDown(); - - _hWPFDocFixture = null; - super.tearDown(); - } - -} diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestTextPieceTable.java b/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestTextPieceTable.java deleted file mode 100644 index 11857915a..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/model/TestTextPieceTable.java +++ /dev/null @@ -1,249 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.model; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; - -import org.apache.poi.hwpf.HWPFDocFixture; -import org.apache.poi.hwpf.HWPFDocument; -import org.apache.poi.hwpf.HWPFTestDataSamples; -import org.apache.poi.hwpf.model.io.HWPFFileSystem; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -@SuppressWarnings("deprecation") -public final class TestTextPieceTable { - private HWPFDocFixture _hWPFDocFixture; - - @Before - public void setUp() throws Exception { - System.setProperty("org.apache.poi.hwpf.preserveTextTable", - Boolean.TRUE.toString()); - - _hWPFDocFixture = new HWPFDocFixture(this, - HWPFDocFixture.DEFAULT_TEST_FILE); - _hWPFDocFixture.setUp(); - } - - @After - public void tearDown() throws Exception { - _hWPFDocFixture.tearDown(); - _hWPFDocFixture = null; - - System.setProperty("org.apache.poi.hwpf.preserveTextTable", - Boolean.FALSE.toString()); - } - - @Test - public void testReadWrite() throws Exception { - FileInformationBlock fib = _hWPFDocFixture._fib; - byte[] mainStream = _hWPFDocFixture._mainStream; - byte[] tableStream = _hWPFDocFixture._tableStream; - int fcMin = fib.getFibBase().getFcMin(); - - ComplexFileTable cft = new ComplexFileTable(mainStream, tableStream, - fib.getFcClx(), fcMin); - - HWPFFileSystem fileSys = new HWPFFileSystem(); - - cft.writeTo(fileSys); - ByteArrayOutputStream tableOut = fileSys.getStream("1Table"); - ByteArrayOutputStream mainOut = fileSys.getStream("WordDocument"); - - byte[] newTableStream = tableOut.toByteArray(); - byte[] newMainStream = mainOut.toByteArray(); - - ComplexFileTable newCft = new ComplexFileTable(newMainStream, - newTableStream, 0, 0); - - TextPieceTable oldTextPieceTable = cft.getTextPieceTable(); - TextPieceTable newTextPieceTable = newCft.getTextPieceTable(); - - assertEquals(oldTextPieceTable, newTextPieceTable); - } - - /** - * Check that we do the positions correctly when working with pure-ascii - */ - @Test - public void testAsciiParts() throws Exception { - HWPFDocument doc = HWPFTestDataSamples - .openSampleFile("ThreeColHeadFoot.doc"); - TextPieceTable tbl = doc.getTextTable(); - - // All ascii, so stored in one big lump - assertEquals(1, tbl.getTextPieces().size()); - TextPiece tp = tbl.getTextPieces().get(0); - - assertEquals(0, tp.getStart()); - assertEquals(339, tp.getEnd()); - assertEquals(339, tp.characterLength()); - assertEquals(339, tp.bytesLength()); - assertTrue(tp.getStringBuilder().toString() - .startsWith("This is a sample word document")); - - // Save and re-load - HWPFDocument docB = saveAndReload(doc); - tbl = docB.getTextTable(); - - assertEquals(1, tbl.getTextPieces().size()); - tp = tbl.getTextPieces().get(0); - - assertEquals(0, tp.getStart()); - assertEquals(339, tp.getEnd()); - assertEquals(339, tp.characterLength()); - assertEquals(339, tp.bytesLength()); - assertTrue(tp.getStringBuilder().toString() - .startsWith("This is a sample word document")); - } - - /** - * Check that we do the positions correctly when working with a mix ascii, - * unicode file - */ - @Test - public void testUnicodeParts() throws Exception { - HWPFDocument doc = HWPFTestDataSamples - .openSampleFile("HeaderFooterUnicode.doc"); - TextPieceTable tbl = doc.getTextTable(); - - // In three bits, split every 512 bytes - assertEquals(3, tbl.getTextPieces().size()); - TextPiece tpA = tbl.getTextPieces().get(0); - TextPiece tpB = tbl.getTextPieces().get(1); - TextPiece tpC = tbl.getTextPieces().get(2); - - assertTrue(tpA.isUnicode()); - assertTrue(tpB.isUnicode()); - assertTrue(tpC.isUnicode()); - - assertEquals(256, tpA.characterLength()); - assertEquals(256, tpB.characterLength()); - assertEquals(19, tpC.characterLength()); - - assertEquals(512, tpA.bytesLength()); - assertEquals(512, tpB.bytesLength()); - assertEquals(38, tpC.bytesLength()); - - assertEquals(0, tpA.getStart()); - assertEquals(256, tpA.getEnd()); - assertEquals(256, tpB.getStart()); - assertEquals(512, tpB.getEnd()); - assertEquals(512, tpC.getStart()); - assertEquals(531, tpC.getEnd()); - - // Save and re-load - HWPFDocument docB = saveAndReload(doc); - tbl = docB.getTextTable(); - - assertEquals(3, tbl.getTextPieces().size()); - tpA = tbl.getTextPieces().get(0); - tpB = tbl.getTextPieces().get(1); - tpC = tbl.getTextPieces().get(2); - - assertTrue(tpA.isUnicode()); - assertTrue(tpB.isUnicode()); - assertTrue(tpC.isUnicode()); - - assertEquals(256, tpA.characterLength()); - assertEquals(256, tpB.characterLength()); - assertEquals(19, tpC.characterLength()); - - assertEquals(512, tpA.bytesLength()); - assertEquals(512, tpB.bytesLength()); - assertEquals(38, tpC.bytesLength()); - - assertEquals(0, tpA.getStart()); - assertEquals(256, tpA.getEnd()); - assertEquals(256, tpB.getStart()); - assertEquals(512, tpB.getEnd()); - assertEquals(512, tpC.getStart()); - assertEquals(531, tpC.getEnd()); - } - - protected HWPFDocument saveAndReload(HWPFDocument doc) throws Exception { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - doc.write(baos); - - return new HWPFDocument(new ByteArrayInputStream(baos.toByteArray())); - } - - @Test - public void test56549_CharIndexRange() { - HWPFDocument doc = HWPFTestDataSamples.openSampleFile("ThreeColHeadFoot.doc"); - - // there is one range from 2048 - 2387 - - TextPieceTable tbl = doc.getTextTable(); - int[][] range = tbl.getCharIndexRanges(0, 0); - assertEquals(0, range.length); - - range = tbl.getCharIndexRanges(0, 1); - assertEquals(0, range.length); - - range = tbl.getCharIndexRanges(0, 338); - assertEquals(0, range.length); - - range = tbl.getCharIndexRanges(0, 339); - assertEquals(0, range.length); - - range = tbl.getCharIndexRanges(0, 340); - assertEquals(0, range.length); - - range = tbl.getCharIndexRanges(2030, 2048); - assertEquals(0, range.length); - - range = tbl.getCharIndexRanges(2030, 2049); - assertEquals(1, range.length); - assertArrayEquals(new int[] {0,1}, range[0]); - - range = tbl.getCharIndexRanges(2048, 2049); - assertEquals(1, range.length); - assertArrayEquals(new int[] {0,1}, range[0]); - - range = tbl.getCharIndexRanges(2048, 2300); - assertEquals(1, range.length); - assertArrayEquals(new int[] {0,252}, range[0]); - - range = tbl.getCharIndexRanges(2049, 2300); - assertEquals(1, range.length); - assertArrayEquals(new int[] {1,252}, range[0]); - - range = tbl.getCharIndexRanges(2049, 2300); - assertEquals(1, range.length); - assertArrayEquals(new int[] {1,252}, range[0]); - - range = tbl.getCharIndexRanges(2049, 2387); - assertEquals(1, range.length); - assertArrayEquals(new int[] {1,339}, range[0]); - - range = tbl.getCharIndexRanges(2049, 2388); - assertEquals(1, range.length); - assertArrayEquals(new int[] {1,339}, range[0]); - - range = tbl.getCharIndexRanges(2387, 2388); - assertEquals(1, range.length); - assertArrayEquals(new int[] {339,339}, range[0]); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/model/types/LFOLVLBaseAbstractTypeTest.java b/src/scratchpad/testcases/org/apache/poi/hwpf/model/types/LFOLVLBaseAbstractTypeTest.java deleted file mode 100644 index 90919cfcc..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/model/types/LFOLVLBaseAbstractTypeTest.java +++ /dev/null @@ -1,34 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hwpf.model.types; - -import junit.framework.TestCase; - -/** - * Test cases for {@link LFOLVLBaseAbstractType} - * - * @author Sergey Vladimirov (vlsergey {at} gmail {dot} com) - */ -public class LFOLVLBaseAbstractTypeTest extends TestCase -{ - - public void testGetSize() - { - assertEquals( 8, LFOLVLBaseAbstractType.getSize() ); - } - -} diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/model/types/LVLFAbstractTypeTest.java b/src/scratchpad/testcases/org/apache/poi/hwpf/model/types/LVLFAbstractTypeTest.java deleted file mode 100644 index b2e96426f..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/model/types/LVLFAbstractTypeTest.java +++ /dev/null @@ -1,34 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hwpf.model.types; - -import junit.framework.TestCase; - -/** - * Test cases for {@link LVLFAbstractType} - * - * @author Sergey Vladimirov (vlsergey {at} gmail {dot} com) - */ -public class LVLFAbstractTypeTest extends TestCase -{ - - public void testGetSize() - { - assertEquals( 28, LVLFAbstractType.getSize() ); - } - -} diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/sprm/TableSprmUncompressorTest.java b/src/scratchpad/testcases/org/apache/poi/hwpf/sprm/TableSprmUncompressorTest.java deleted file mode 100644 index 77c6e86c8..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/sprm/TableSprmUncompressorTest.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -package org.apache.poi.hwpf.sprm; - -import org.apache.poi.hwpf.usermodel.TableProperties; - -import junit.framework.TestCase; - -public class TableSprmUncompressorTest extends TestCase -{ - public void testSprmTDefTable() - { - final byte[] example = { (byte) 0x08, (byte) 0xD6, (byte) 0x2F, - (byte) 0x00, (byte) 0x02, (byte) 0x94, (byte) 0xFF, - (byte) 0x53, (byte) 0x03, (byte) 0x60, (byte) 0x13, - (byte) 0x00, (byte) 0x06, (byte) 0xBF, (byte) 0x03, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x06, (byte) 0x0D, (byte) 0x10, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00 }; - - SprmOperation sprmOperation = new SprmOperation( example, 0 ); - assertEquals( SprmOperation.TYPE_TAP, sprmOperation.getType() ); - assertEquals( (short) 0x08, sprmOperation.getOperation() ); - - TableProperties tableProperties = new TableProperties(); - TableSprmUncompressor.unCompressTAPOperation( tableProperties, - sprmOperation ); - - assertEquals( 2, tableProperties.getItcMac() ); - assertEquals( 3, tableProperties.getRgdxaCenter().length ); - assertEquals( (short) 0xff94, tableProperties.getRgdxaCenter()[0] ); - assertEquals( (short) 0x0353, tableProperties.getRgdxaCenter()[1] ); - assertEquals( (short) 0x1360, tableProperties.getRgdxaCenter()[2] ); - - assertEquals( 2, tableProperties.getRgtc().length ); - assertEquals( (short) 0x03bf, tableProperties.getRgtc()[0].getWWidth() ); - assertEquals( (short) 0x100d, tableProperties.getRgtc()[1].getWWidth() ); - } -} \ No newline at end of file diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/sprm/TestSprms.java b/src/scratchpad/testcases/org/apache/poi/hwpf/sprm/TestSprms.java deleted file mode 100644 index e83dbeeaa..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/sprm/TestSprms.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.hwpf.sprm; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.Locale; - -import junit.framework.TestCase; -import org.apache.poi.POIDataSamples; -import org.apache.poi.hwpf.HWPFDocument; -import org.apache.poi.hwpf.usermodel.Paragraph; -import org.apache.poi.hwpf.usermodel.Range; - -public class TestSprms extends TestCase -{ - private static HWPFDocument reload( HWPFDocument hwpfDocument ) - throws IOException - { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - hwpfDocument.write( baos ); - return new HWPFDocument( new ByteArrayInputStream( baos.toByteArray() ) ); - } - - /** - * Test correct processing of "sprmPItap" (0x6649) and "sprmPFInTable" - * (0x2416) - */ - public void testInnerTable() throws Exception - { - InputStream resourceAsStream = POIDataSamples.getDocumentInstance() - .openResourceAsStream( "innertable.doc" ); - HWPFDocument hwpfDocument = new HWPFDocument( resourceAsStream ); - resourceAsStream.close(); - - testInnerTable( hwpfDocument ); - hwpfDocument = reload( hwpfDocument ); - testInnerTable( hwpfDocument ); - } - - private void testInnerTable( HWPFDocument hwpfDocument ) - { - Range range = hwpfDocument.getRange(); - for ( int p = 0; p < range.numParagraphs(); p++ ) - { - Paragraph paragraph = range.getParagraph( p ); - char first = paragraph.text().toLowerCase(Locale.ROOT).charAt( 0 ); - if ( '1' <= first && first < '4' ) - { - assertTrue( paragraph.isInTable() ); - assertEquals( 2, paragraph.getTableLevel() ); - } - - if ( 'a' <= first && first < 'z' ) - { - assertTrue( paragraph.isInTable() ); - assertEquals( 1, paragraph.getTableLevel() ); - } - } - } - - /** - * Test correct processing of "sprmPJc" by uncompressor - */ - public void testSprmPJc() throws IOException - { - InputStream resourceAsStream = POIDataSamples.getDocumentInstance() - .openResourceAsStream( "Bug49820.doc" ); - HWPFDocument hwpfDocument = new HWPFDocument( resourceAsStream ); - resourceAsStream.close(); - - assertEquals( 1, hwpfDocument.getStyleSheet().getParagraphStyle( 8 ) - .getJustification() ); - - hwpfDocument = reload( hwpfDocument ); - - assertEquals( 1, hwpfDocument.getStyleSheet().getParagraphStyle( 8 ) - .getJustification() ); - - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestBorderCode.java b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestBorderCode.java deleted file mode 100644 index 4adf93996..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestBorderCode.java +++ /dev/null @@ -1,113 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.usermodel; - -import junit.framework.TestCase; - -import org.apache.poi.hwpf.HWPFDocument; -import org.apache.poi.hwpf.HWPFTestDataSamples; - -/** - * API for BorderCode, see Bugzill 49919 - */ -public final class TestBorderCode extends TestCase { - - private int pos = 0; - private Range range; - - public void test() { - HWPFDocument doc = HWPFTestDataSamples.openSampleFile("Bug49919.doc"); - range = doc.getRange(); - - Paragraph par = findParagraph("Paragraph normal\r"); - assertEquals(0, par.getLeftBorder().getBorderType()); - assertEquals(0, par.getRightBorder().getBorderType()); - assertEquals(0, par.getTopBorder().getBorderType()); - assertEquals(0, par.getBottomBorder().getBorderType()); - - par = findParagraph("Paragraph with border\r"); - assertEquals(18, par.getLeftBorder().getBorderType()); - assertEquals(17, par.getRightBorder().getBorderType()); - assertEquals(18, par.getTopBorder().getBorderType()); - assertEquals(17, par.getBottomBorder().getBorderType()); - assertEquals(15, par.getLeftBorder().getColor()); - - par = findParagraph("Paragraph with red border\r"); - assertEquals(1, par.getLeftBorder().getBorderType()); - assertEquals(1, par.getRightBorder().getBorderType()); - assertEquals(1, par.getTopBorder().getBorderType()); - assertEquals(1, par.getBottomBorder().getBorderType()); - assertEquals(6, par.getLeftBorder().getColor()); - - par = findParagraph("Paragraph with bordered words.\r"); - assertEquals(0, par.getLeftBorder().getBorderType()); - assertEquals(0, par.getRightBorder().getBorderType()); - assertEquals(0, par.getTopBorder().getBorderType()); - assertEquals(0, par.getBottomBorder().getBorderType()); - - assertEquals(3, par.numCharacterRuns()); - CharacterRun chr = par.getCharacterRun(0); - assertEquals(0, chr.getBorder().getBorderType()); - chr = par.getCharacterRun(1); - assertEquals(1, chr.getBorder().getBorderType()); - assertEquals(0, chr.getBorder().getColor()); - chr = par.getCharacterRun(2); - assertEquals(0, chr.getBorder().getBorderType()); - - while (pos < range.numParagraphs() - 1) { - par = range.getParagraph(pos++); - if (par.isInTable()) - break; - } - - assertEquals(true, par.isInTable()); - Table tab = range.getTable(par); - - // Border could be defined for the entire row, or for each cell, with the same visual appearance. - assertEquals(2, tab.numRows()); - TableRow row = tab.getRow(0); - assertEquals(1, row.getLeftBorder().getBorderType()); - assertEquals(1, row.getRightBorder().getBorderType()); - assertEquals(1, row.getTopBorder().getBorderType()); - assertEquals(1, row.getBottomBorder().getBorderType()); - - assertEquals(2, row.numCells()); - TableCell cell = row.getCell(1); - assertEquals(3, cell.getBrcTop().getBorderType()); - - row = tab.getRow(1); - cell = row.getCell(0); - // 255 clears border inherited from row - assertEquals(255, cell.getBrcBottom().getBorderType()); - } - - private Paragraph findParagraph(String expectedText) { - while (pos < range.numParagraphs() - 1) { - Paragraph par = range.getParagraph(pos); - pos++; - if (par.text().equals(expectedText)) - return par; - } - - fail("Expected paragraph not found"); - - // should never come here - throw null; - } - -} diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestBug46610.java b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestBug46610.java deleted file mode 100644 index be231dad2..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestBug46610.java +++ /dev/null @@ -1,59 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.usermodel; - -import junit.framework.TestCase; - -import org.apache.poi.hwpf.usermodel.CharacterRun; -import org.apache.poi.hwpf.usermodel.Paragraph; -import org.apache.poi.hwpf.usermodel.Range; -import org.apache.poi.hwpf.HWPFDocument; -import org.apache.poi.hwpf.HWPFTestDataSamples; - -public final class TestBug46610 extends TestCase { - - public void testUtf() { - runExtract("Bug46610_1.doc"); - } - - public void testUtf2() { - runExtract("Bug46610_2.doc"); - } - - public void testExtraction() { - String text = runExtract("Bug46610_3.doc"); - assertTrue(text.contains("\u0421\u0412\u041e\u042e")); - } - - private static String runExtract(String sampleName) { - HWPFDocument doc = HWPFTestDataSamples.openSampleFile(sampleName); - StringBuffer out = new StringBuffer(); - - Range globalRange = doc.getRange(); - for (int i = 0; i < globalRange.numParagraphs(); i++) { - Paragraph p = globalRange.getParagraph(i); - out.append(p.text()); - out.append("\n"); - for (int j = 0; j < p.numCharacterRuns(); j++) { - CharacterRun characterRun = p.getCharacterRun(j); - characterRun.text(); - } - } - return out.toString(); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestBug47563.java b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestBug47563.java deleted file mode 100644 index 5dbef749d..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestBug47563.java +++ /dev/null @@ -1,85 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hwpf.usermodel; - -import junit.framework.TestCase; - -import org.apache.poi.hwpf.HWPFDocument; -import org.apache.poi.hwpf.HWPFTestDataSamples; - -/** - * Bug 47563 - Exception when working with table - */ -public class TestBug47563 extends TestCase { - - public void test() throws Exception { - test(1, 5); - test(1, 6); - test(5, 1); - test(6, 1); - test(2, 2); - test(3, 2); - test(2, 3); - test(3, 3); - } - - private void test(int rows, int columns) throws Exception { - // POI apparently can't create a document from scratch, - // so we need an existing empty dummy document - HWPFDocument doc = HWPFTestDataSamples.openSampleFile("empty.doc"); - - Range range = doc.getRange(); - range.sanityCheck(); - - Table table = range.insertTableBefore((short) columns, rows); - table.sanityCheck(); - - for (int rowIdx = 0; rowIdx < table.numRows(); rowIdx++) { - TableRow row = table.getRow(rowIdx); - row.sanityCheck(); - - System.out.println("row " + rowIdx); - for (int colIdx = 0; colIdx < row.numCells(); colIdx++) { - TableCell cell = row.getCell(colIdx); - cell.sanityCheck(); - - System.out.println("column " + colIdx + ", num paragraphs " - + cell.numParagraphs()); - - Paragraph par = cell.getParagraph(0); - par.sanityCheck(); - - par.insertBefore("" + (rowIdx * row.numCells() + colIdx)); - par.sanityCheck(); - - row.sanityCheck(); - table.sanityCheck(); - range.sanityCheck(); - - } - } - - String text = range.text(); - int mustBeAfter = 0; - for (int i = 0; i < rows * columns; i++) { - int next = text.indexOf(Integer.toString(i), mustBeAfter); - assertTrue("Test with " + rows + "/" + columns + ": Should not find " + i + " but found it at " + next + " in " + text, - next != -1); - mustBeAfter = next; - } - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestBug49820.java b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestBug49820.java deleted file mode 100644 index 92d99c386..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestBug49820.java +++ /dev/null @@ -1,63 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.usermodel; - -import java.io.IOException; -import junit.framework.TestCase; - -import org.apache.poi.hwpf.HWPFDocument; -import org.apache.poi.hwpf.HWPFTestDataSamples; -import org.apache.poi.hwpf.model.StyleSheet; - -public final class TestBug49820 extends TestCase { - - public void test() throws IOException { - HWPFDocument doc = HWPFTestDataSamples.openSampleFile("Bug49820.doc"); - - Range documentRange = doc.getRange(); - StyleSheet styleSheet = doc.getStyleSheet(); - - // JUnit asserts - assertLevels(documentRange, styleSheet, 0, 0, 0); - assertLevels(documentRange, styleSheet, 1, 1, 1); - assertLevels(documentRange, styleSheet, 2, 2, 2); - assertLevels(documentRange, styleSheet, 3, 3, 3); - assertLevels(documentRange, styleSheet, 4, 4, 4); - assertLevels(documentRange, styleSheet, 5, 5, 5); - assertLevels(documentRange, styleSheet, 6, 6, 6); - assertLevels(documentRange, styleSheet, 7, 7, 7); - assertLevels(documentRange, styleSheet, 8, 8, 8); - assertLevels(documentRange, styleSheet, 9, 9, 9); - assertLevels(documentRange, styleSheet, 10, 9, 0); - assertLevels(documentRange, styleSheet, 11, 9, 4); - - // output to console - /*for (int i=0; i pics = doc.getPicturesTable().getAllPictures(); - - assertNotNull(pics); - assertEquals(1, pics.size()); - - Picture pic = pics.get(0); - assertNotNull(pic.suggestFileExtension()); - assertNotNull(pic.suggestFullFileName()); - - assertNotNull(pic.getContent()); - assertNotNull(pic.getRawContent()); - - /* - * This is a file with empty EMF image, but present Office Drawing - * --sergey - */ - final Collection officeDrawings = doc - .getOfficeDrawingsMain().getOfficeDrawings(); - assertNotNull(officeDrawings); - assertEquals(1, officeDrawings.size()); - - OfficeDrawing officeDrawing = officeDrawings.iterator().next(); - assertNotNull(officeDrawing); - assertEquals(1044, officeDrawing.getShapeId()); - doc.close(); - } - - /** - * Bug 44331 - HWPFDocument.write destroys fields - */ - @SuppressWarnings("deprecation") - @Test - public void test44431() throws IOException - { - HWPFDocument doc1 = HWPFTestDataSamples.openSampleFile("Bug44431.doc"); - - WordExtractor extractor1 = new WordExtractor(doc1); - try { - HWPFDocument doc2 = HWPFTestDataSamples.writeOutAndReadBack(doc1); - - WordExtractor extractor2 = new WordExtractor(doc2); - try { - assertEqualsIgnoreNewline(extractor1.getFooterText(), extractor2.getFooterText()); - assertEqualsIgnoreNewline(extractor1.getHeaderText(), extractor2.getHeaderText()); - assertEqualsIgnoreNewline(Arrays.toString(extractor1.getParagraphText() ), - Arrays.toString(extractor2.getParagraphText())); - - assertEqualsIgnoreNewline(extractor1.getText(), extractor2.getText()); - } finally { - extractor2.close(); - } - } finally { - extractor1.close(); - doc1.close(); - } - } - - /** - * Bug 44331 - HWPFDocument.write destroys fields - */ - @Test - public void test44431_2() throws IOException - { - assertEqualsIgnoreNewline("File name=FieldsTest.doc\n" + - "\n" + - "\n" + - "STYLEREF test\n" + - "\n" + - "\n" + - "\n" + - "TEST TABLE OF CONTENTS\n" + - "\n" + - "Heading paragraph in next page\t2\n" + - "Another heading paragraph in further page\t3\n" + - "Another heading paragraph in further page\t3\n" + - "\n" + - "\n" + - "Heading paragraph in next page\n" + - "Another heading paragraph in further page\n" + - "\n" + - "\n" + - "\n" + - "Page 3 of 3", getText("Bug44431.doc")); - } - - /** - * Bug 45473 - HWPF cannot read file after save - */ - @Test - public void test45473() throws IOException - { - // Fetch the current text - HWPFDocument doc1 = HWPFTestDataSamples.openSampleFile("Bug45473.doc"); - WordExtractor wordExtractor = new WordExtractor(doc1); - final String text1; - try { - text1 = wordExtractor.getText().trim(); - } finally { - wordExtractor.close(); - doc1.close(); - } - - // Re-load, then re-save and re-check - doc1 = HWPFTestDataSamples.openSampleFile("Bug45473.doc"); - HWPFDocument doc2 = HWPFTestDataSamples.writeOutAndReadBack(doc1); - WordExtractor wordExtractor2 = new WordExtractor(doc2); - final String text2; - try { - text2 = wordExtractor2.getText().trim(); - } finally { - wordExtractor2.close(); - doc1.close(); - } - - // the text in the saved document has some differences in line - // separators but we tolerate that - assertEqualsIgnoreNewline(text1.replaceAll("\n", "" ), text2.replaceAll("\n", "")); - } - - /** - * Bug 46220 - images are not properly extracted - */ - @Test - public void test46220() throws IOException { - HWPFDocument doc = HWPFTestDataSamples.openSampleFile("Bug46220.doc"); - // reference checksums as in Bugzilla - String[] md5 = { "851be142bce6d01848e730cb6903f39e", - "7fc6d8fb58b09ababd036d10a0e8c039", - "a7dc644c40bc2fbf17b2b62d07f99248", - "72d07b8db5fad7099d90bc4c304b4666" }; - List pics = doc.getPicturesTable().getAllPictures(); - assertEquals(4, pics.size()); - for (int i = 0; i < pics.size(); i++ ) - { - Picture pic = pics.get(i); - byte[] data = pic.getRawContent(); - // use Apache Commons Codec utils to compute md5 - assertEqualsIgnoreNewline(md5[i], DigestUtils.md5Hex(data)); - } - doc.close(); - } - - /** - * [RESOLVED FIXED] Bug 46817 - Regression: Text from some table cells - * missing - */ - @Test - public void test46817() throws IOException - { - String text = getText("Bug46817.doc").trim(); - - assertTrue(text.contains("Nazwa wykonawcy")); - assertTrue(text.contains("kujawsko-pomorskie")); - assertTrue(text.contains("ekomel@ekomel.com.pl")); - } - - /** - * [FAILING] Bug 47286 - Word documents saves in wrong format if source - * contains form elements - */ - @SuppressWarnings("deprecation") - @Test - public void test47286() throws IOException - { - // Fetch the current text - HWPFDocument doc1 = HWPFTestDataSamples.openSampleFile("Bug47286.doc"); - WordExtractor wordExtractor = new WordExtractor(doc1); - final String text1; - try { - text1 = wordExtractor.getText().trim(); - } finally { - wordExtractor.close(); - doc1.close(); - } - - // Re-load, then re-save and re-check - doc1 = HWPFTestDataSamples.openSampleFile("Bug47286.doc"); - HWPFDocument doc2 = HWPFTestDataSamples.writeOutAndReadBack(doc1); - WordExtractor wordExtractor2 = new WordExtractor(doc2); - final String text2; - try { - text2 = wordExtractor2.getText().trim(); - } finally { - wordExtractor2.close(); - doc1.close(); - } - - // the text in the saved document has some differences in line - // separators but we tolerate that - assertEqualsIgnoreNewline(text1.replaceAll("\n", "" ), text2.replaceAll("\n", "")); - - assertEquals(doc1.getCharacterTable().getTextRuns().size(), doc2 - .getCharacterTable().getTextRuns().size()); - - List expectedFields = doc1.getFieldsTables() - .getFieldsPLCF(FieldsDocumentPart.MAIN); - List actualFields = doc2.getFieldsTables().getFieldsPLCF( - FieldsDocumentPart.MAIN); - assertEquals(expectedFields.size(), actualFields.size()); - - assertTableStructures(doc1.getRange(), doc2.getRange()); - } - - /** - * [RESOLVED FIXED] Bug 47287 - StringIndexOutOfBoundsException in - * CharacterRun.replaceText() - */ - @Test - public void test47287() - { - HWPFDocument doc = HWPFTestDataSamples.openSampleFile("Bug47287.doc"); - String[] values = { "1-1", "1-2", "1-3", "1-4", "1-5", "1-6", "1-7", - "1-8", "1-9", "1-10", "1-11", "1-12", "1-13", "1-14", "1-15", }; - int usedVal = 0; - String PLACEHOLDER = "\u2002\u2002\u2002\u2002\u2002"; - Range r = doc.getRange(); - for (int x = 0; x < r.numSections(); x++ ) - { - Section s = r.getSection(x); - for (int y = 0; y < s.numParagraphs(); y++ ) - { - Paragraph p = s.getParagraph(y); - - for (int z = 0; z < p.numCharacterRuns(); z++ ) - { - boolean isFound = false; - - // character run - CharacterRun run = p.getCharacterRun(z); - // character run text - String text = run.text(); - String oldText = text; - int c = text.indexOf("FORMTEXT "); - if (c < 0 ) - { - int k = text.indexOf(PLACEHOLDER); - if (k >= 0 ) - { - text = text.substring(0, k ) + values[usedVal] - + text.substring(k + PLACEHOLDER.length()); - usedVal++; - isFound = true; - } - } - else - { - for (; c >= 0; c = text.indexOf("FORMTEXT ", c - + "FORMTEXT ".length() ) ) - { - int k = text.indexOf(PLACEHOLDER, c); - if (k >= 0 ) - { - text = text.substring(0, k ) - + values[usedVal] - + text.substring(k - + PLACEHOLDER.length()); - usedVal++; - isFound = true; - } - } - } - if (isFound ) - { - run.replaceText(oldText, text, 0); - } - - } - } - } - - String docText = r.text(); - - assertTrue(docText.contains("1-1")); - assertTrue(docText.contains("1-12")); - - assertFalse(docText.contains("1-13")); - assertFalse(docText.contains("1-15")); - } - - /** - * [RESOLVED FIXED] Bug 47731 - Word Extractor considers text copied from - * some website as an embedded object - */ - @Test - public void test47731() throws Exception - { - String foundText = getText("Bug47731.doc"); - - assertTrue(foundText - .contains("Soak the rice in water for three to four hours")); - } - - /** - * Bug 4774 - text extracted by WordExtractor is broken - */ - @Test - public void test47742() throws Exception - { - // (1) extract text from MS Word document via POI - String foundText = getText("Bug47742.doc"); - - // (2) read text from text document (retrieved by saving the word - // document as text file using encoding UTF-8) - InputStream is = POIDataSamples.getDocumentInstance() - .openResourceAsStream("Bug47742-text.txt"); - try { - byte[] expectedBytes = IOUtils.toByteArray(is); - String expectedText = new String(expectedBytes, "utf-8" ) - .substring(1); // strip-off the unicode marker - - assertEqualsIgnoreNewline(expectedText, foundText); - } finally { - is.close(); - } - } - - /** - * Bug 47958 - Exception during Escher walk of pictures - */ - @Test - public void test47958() - { - HWPFDocument doc = HWPFTestDataSamples.openSampleFile("Bug47958.doc"); - doc.getPicturesTable().getAllPictures(); - } - - /** - * [RESOLVED FIXED] Bug 48065 - Problems with save output of HWPF (losing - * formatting) - */ - @Test - public void test48065() - { - HWPFDocument doc1 = HWPFTestDataSamples.openSampleFile("Bug48065.doc"); - HWPFDocument doc2 = HWPFTestDataSamples.writeOutAndReadBack(doc1); - - Range expected = doc1.getRange(); - Range actual = doc2.getRange(); - - assertEqualsIgnoreNewline( - expected.text().replace("\r", "\n").replaceAll("\n\n", "\n" ), - actual.text().replace("\r", "\n").replaceAll("\n\n", "\n")); - - assertTableStructures(expected, actual); - } - - @Test - public void test49933() throws IOException - { - String text = getTextOldFile("Bug49933.doc"); - - assertTrue( text.contains( "best.wine.jump.ru" ) ); - } - - /** - * Bug 50936 - Exception parsing MS Word 8.0 file - */ - @Test - public void test50936_1() - { - HWPFDocument hwpfDocument = HWPFTestDataSamples - .openSampleFile("Bug50936_1.doc"); - hwpfDocument.getPicturesTable().getAllPictures(); - } - - /** - * Bug 50936 - Exception parsing MS Word 8.0 file - */ - @Test - public void test50936_2() - { - HWPFDocument hwpfDocument = HWPFTestDataSamples - .openSampleFile("Bug50936_2.doc"); - hwpfDocument.getPicturesTable().getAllPictures(); - } - - /** - * Bug 50936 - Exception parsing MS Word 8.0 file - */ - @Test - public void test50936_3() - { - HWPFDocument hwpfDocument = HWPFTestDataSamples - .openSampleFile("Bug50936_3.doc"); - hwpfDocument.getPicturesTable().getAllPictures(); - } - - - /** - * [RESOLVED FIXED] Bug 51604 - replace text fails for doc (poi 3.8 beta - * release from download site ) - */ - @Test - public void test51604() - { - HWPFDocument document = HWPFTestDataSamples - .openSampleFile("Bug51604.doc"); - - Range range = document.getRange(); - int numParagraph = range.numParagraphs(); - int counter = 0; - for (int i = 0; i < numParagraph; i++ ) - { - Paragraph paragraph = range.getParagraph(i); - int numCharRuns = paragraph.numCharacterRuns(); - for (int j = 0; j < numCharRuns; j++ ) - { - CharacterRun charRun = paragraph.getCharacterRun(j); - String text = charRun.text(); - charRun.replaceText(text, "+" + (++counter)); - } - } - - document = HWPFTestDataSamples.writeOutAndReadBack(document); - String text = document.getDocumentText(); - assertEqualsIgnoreNewline("+1+2+3+4+5+6+7+8+9+10+11+12", text); - } - - /** - * [RESOLVED FIXED] Bug 51604 - replace text fails for doc (poi 3.8 beta - * release from download site ) - */ - @Test - public void test51604p2() throws Exception - { - HWPFDocument doc = HWPFTestDataSamples.openSampleFile("Bug51604.doc"); - - Range range = doc.getRange(); - int numParagraph = range.numParagraphs(); - replaceText(range, numParagraph); - - doc = HWPFTestDataSamples.writeOutAndReadBack(doc); - final FileInformationBlock fileInformationBlock = doc - .getFileInformationBlock(); - - int totalLength = 0; - for (SubdocumentType type : SubdocumentType.values() ) - { - final int partLength = fileInformationBlock - .getSubdocumentTextStreamLength(type); - assert (partLength >= 0); - - totalLength += partLength; - } - assertEquals(doc.getText().length(), totalLength); - } - - private void replaceText(Range range, int numParagraph) { - for (int i = 0; i < numParagraph; i++ ) - { - Paragraph paragraph = range.getParagraph(i); - int numCharRuns = paragraph.numCharacterRuns(); - for (int j = 0; j < numCharRuns; j++ ) - { - CharacterRun charRun = paragraph.getCharacterRun(j); - String text = charRun.text(); - if (text.contains("Header" ) ) { - charRun.replaceText(text, "added"); - } - } - } - } - - /** - * [RESOLVED FIXED] Bug 51604 - replace text fails for doc (poi 3.8 beta - * release from download site ) - */ - @Test - public void test51604p3() throws Exception - { - HWPFDocument doc = HWPFTestDataSamples.openSampleFile("Bug51604.doc"); - - byte[] originalData = new byte[doc.getFileInformationBlock() - .getLcbDop()]; - System.arraycopy(doc.getTableStream(), doc.getFileInformationBlock() - .getFcDop(), originalData, 0, originalData.length); - - HWPFOutputStream outputStream = new HWPFOutputStream(); - doc.getDocProperties().writeTo(outputStream); - final byte[] oldData = outputStream.toByteArray(); - - assertEqualsIgnoreNewline(Arrays.toString(originalData ), - Arrays.toString(oldData)); - - Range range = doc.getRange(); - int numParagraph = range.numParagraphs(); - replaceText(range, numParagraph); - - doc = HWPFTestDataSamples.writeOutAndReadBack(doc); - - outputStream = new HWPFOutputStream(); - doc.getDocProperties().writeTo(outputStream); - final byte[] newData = outputStream.toByteArray(); - - assertEqualsIgnoreNewline(Arrays.toString(oldData ), Arrays.toString(newData)); - } - - /** - * [RESOLVED FIXED] Bug 51671 - HWPFDocument.write based on NPOIFSFileSystem - * throws a NullPointerException - */ - @Test - public void test51671() throws Exception - { - InputStream is = POIDataSamples.getDocumentInstance() - .openResourceAsStream("empty.doc"); - NPOIFSFileSystem npoifsFileSystem = new NPOIFSFileSystem(is); - try { - HWPFDocument hwpfDocument = new HWPFDocument( - npoifsFileSystem.getRoot()); - hwpfDocument.write(new ByteArrayOutputStream()); - hwpfDocument.close(); - } finally { - npoifsFileSystem.close(); - } - } - - /** - * Bug 51678 - Extracting text from Bug51524.zip is slow Bug 51524 - - * PapBinTable constructor is slow - */ - @Test - public void test51678And51524() throws IOException - { - // YK: the test will run only if the poi.test.remote system property is - // set. - // TODO: refactor into something nicer! - if (System.getProperty("poi.test.remote" ) != null ) - { - String href = "http://domex.nps.edu/corp/files/govdocs1/007/007488.doc"; - HWPFDocument hwpfDocument = HWPFTestDataSamples - .openRemoteFile(href); - - WordExtractor wordExtractor = new WordExtractor(hwpfDocument); - try { - wordExtractor.getText(); - } finally { - wordExtractor.close(); - } - } - } - - /** - * [FIXED] Bug 51902 - Picture.fillRawImageContent - - * ArrayIndexOutOfBoundsException - */ - @Test - public void testBug51890() - { - HWPFDocument doc = HWPFTestDataSamples.openSampleFile("Bug51890.doc"); - for (Picture picture : doc.getPicturesTable().getAllPictures() ) - { - PictureType pictureType = picture.suggestPictureType(); - logger.log(POILogger.DEBUG, - "Picture at offset " + picture.getStartOffset() - + " has type " + pictureType); - } - } - - /** - * [RESOLVED FIXED] Bug 51834 - Opening and Writing .doc file results in - * corrupt document - */ - @Test - public void testBug51834() throws Exception - { - /* - * we don't have Java test for this file - it should be checked using - * Microsoft BFF Validator. But check read-write-read anyway. -- sergey - */ - HWPFTestDataSamples.openSampleFile("Bug51834.doc"); - HWPFTestDataSamples.writeOutAndReadBack(HWPFTestDataSamples - .openSampleFile("Bug51834.doc")); - } - - /** - * Bug 51944 - PAPFormattedDiskPage.getPAPX - IndexOutOfBounds - */ - @Test - public void testBug51944() throws Exception - { - HWPFOldDocument doc = HWPFTestDataSamples.openOldSampleFile("Bug51944.doc"); - assertNotNull(WordToTextConverter.getText(doc)); - } - - /** - * Bug 52032 - [BUG] & [partial-PATCH] HWPF - ArrayIndexOutofBoundsException - * with no stack trace (broken after revision 1178063) - */ - @Test - public void testBug52032_1() throws Exception - { - assertNotNull(getText("Bug52032_1.doc")); - } - - /** - * Bug 52032 - [BUG] & [partial-PATCH] HWPF - ArrayIndexOutofBoundsException - * with no stack trace (broken after revision 1178063) - */ - @Test - public void testBug52032_2() throws Exception - { - assertNotNull(getText("Bug52032_2.doc")); - } - - /** - * Bug 52032 - [BUG] & [partial-PATCH] HWPF - ArrayIndexOutofBoundsException - * with no stack trace (broken after revision 1178063) - */ - @Test - public void testBug52032_3() throws Exception - { - assertNotNull(getText("Bug52032_3.doc")); - } - - /** - * Bug 53380 - ArrayIndexOutOfBounds Exception parsing word 97 document - */ - @Test - public void testBug53380_1() throws Exception - { - assertNotNull(getText("Bug53380_1.doc")); - } - - /** - * Bug 53380 - ArrayIndexOutOfBounds Exception parsing word 97 document - */ - @Test - public void testBug53380_2() throws Exception - { - assertNotNull(getText("Bug53380_2.doc")); - } - - /** - * Bug 53380 - ArrayIndexOutOfBounds Exception parsing word 97 document - */ - @Test - public void testBug53380_3() throws Exception - { - assertNotNull(getText("Bug53380_3.doc")); - } - - /** - * Bug 53380 - ArrayIndexOutOfBounds Exception parsing word 97 document - */ - @Test - public void testBug53380_4() throws Exception - { - assertNotNull(getText("Bug53380_4.doc")); - } - - /** - * java.lang.UnsupportedOperationException: Non-extended character - * Pascal strings are not supported right now - * - * Disabled pending a fix for the bug - */ - @Test - public void test56880() throws Exception { - HWPFDocument doc = - HWPFTestDataSamples.openSampleFile("56880.doc"); - assertEqualsIgnoreNewline("Check Request", doc.getRange().text()); - } - - - // These are the values the are expected to be read when the file - // is checked. - private final int section1LeftMargin = 1440; - private final int section1RightMargin = 1440; - private final int section1TopMargin = 1440; - private final int section1BottomMargin = 1440; - private final int section1NumColumns = 1; - private int section2LeftMargin = 1440; - private int section2RightMargin = 1440; - private int section2TopMargin = 1440; - private int section2BottomMargin = 1440; - private final int section2NumColumns = 3; - - @Test - @SuppressWarnings("SuspiciousNameCombination") - public void testHWPFSections() { - HWPFDocument document = HWPFTestDataSamples.openSampleFile("Bug53453Section.doc"); - Range overallRange = document.getOverallRange(); - int numParas = overallRange.numParagraphs(); - for(int i = 0; i < numParas; i++) { - Paragraph para = overallRange.getParagraph(i); - int numSections = para.numSections(); - for(int j = 0; j < numSections; j++) { - Section section = para.getSection(j); - if(para.text().trim().equals("Section1")) { - assertSection1Margin(section); - } - else if(para.text().trim().equals("Section2")) { - assertSection2Margin(section); - - // Change the margin widths - this.section2BottomMargin = (int)(1.5 * AbstractWordUtils.TWIPS_PER_INCH); - this.section2TopMargin = (int)(1.75 * AbstractWordUtils.TWIPS_PER_INCH); - this.section2LeftMargin = (int)(0.5 * AbstractWordUtils.TWIPS_PER_INCH); - this.section2RightMargin = (int)(0.75 * AbstractWordUtils.TWIPS_PER_INCH); - section.setMarginBottom(this.section2BottomMargin); - section.setMarginLeft(this.section2LeftMargin); - section.setMarginRight(this.section2RightMargin); - section.setMarginTop(this.section2TopMargin); - } - } - } - - // Save away and re-read the document to prove the chages are permanent - document = HWPFTestDataSamples.writeOutAndReadBack(document); - overallRange = document.getOverallRange(); - numParas = overallRange.numParagraphs(); - for(int i = 0; i < numParas; i++) { - Paragraph para = overallRange.getParagraph(i); - int numSections = para.numSections(); - for(int j = 0; j < numSections; j++) { - Section section = para.getSection(j); - if(para.text().trim().equals("Section1")) { - // No changes to the margins in Section1 - assertSection1Margin(section); - } - else if(para.text().trim().equals("Section2")) { - // The margins in Section2 have kept the new settings. - assertSection2Margin(section); - } - } - } - } - - @SuppressWarnings("Duplicates") - private void assertSection1Margin(Section section) { - assertEquals(section1BottomMargin, section.getMarginBottom()); - assertEquals(section1LeftMargin, section.getMarginLeft()); - assertEquals(section1RightMargin, section.getMarginRight()); - assertEquals(section1TopMargin, section.getMarginTop()); - assertEquals(section1NumColumns, section.getNumColumns()); - } - - @SuppressWarnings("Duplicates") - private void assertSection2Margin(Section section) { - assertEquals(section2BottomMargin, section.getMarginBottom()); - assertEquals(section2LeftMargin, section.getMarginLeft()); - assertEquals(section2RightMargin, section.getMarginRight()); - assertEquals(section2TopMargin, section.getMarginTop()); - assertEquals(section2NumColumns, section.getNumColumns()); - } - - @Test - public void testRegressionIn315beta2() { - HWPFDocument hwpfDocument = HWPFTestDataSamples.openSampleFile("cap.stanford.edu_profiles_viewbiosketch_facultyid=4009&name=m_maciver.doc"); - assertNotNull(hwpfDocument); - } - - @Test(expected=ArrayIndexOutOfBoundsException.class) - public void test57603SevenRowTable() throws Exception { - HWPFDocument hwpfDocument = HWPFTestDataSamples.openSampleFile("57603-seven_columns.doc"); - HWPFDocument hwpfDocument2 = HWPFTestDataSamples.writeOutAndReadBack(hwpfDocument); - assertNotNull(hwpfDocument2); - hwpfDocument2.close(); - hwpfDocument.close(); - } - - @Test(expected=ArrayIndexOutOfBoundsException.class) - public void test57843() throws IOException { - File f = POIDataSamples.getDocumentInstance().getFile("57843.doc"); - POIFSFileSystem fs = new POIFSFileSystem(f, true); - try { - HWPFOldDocument doc = new HWPFOldDocument(fs); - assertNotNull(doc); - doc.close(); - } finally { - fs.close(); - } - } - - @Test - public void testCommonCrawlRegression() throws IOException { - HWPFDocument document = HWPFTestDataSamples.openSampleFile("ca.kwsymphony.www_education_School_Concert_Seat_Booking_Form_2011-12.doc"); - document.close(); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestHWPFOldDocument.java b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestHWPFOldDocument.java deleted file mode 100644 index 925b8d056..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestHWPFOldDocument.java +++ /dev/null @@ -1,254 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.usermodel; - -import static org.apache.poi.POITestCase.assertContains; -import static org.junit.Assert.assertEquals; - -import java.io.IOException; -import java.nio.charset.Charset; - -import org.apache.poi.OldFileFormatException; -import org.apache.poi.hwmf.record.HwmfFont; -import org.apache.poi.hwpf.HWPFOldDocument; -import org.apache.poi.hwpf.HWPFTestCase; -import org.apache.poi.hwpf.HWPFTestDataSamples; -import org.apache.poi.hwpf.extractor.Word6Extractor; -import org.apache.poi.hwpf.model.OldFontTable; -import org.junit.Test; - -/** - * Tests for Word 6 and Word 95 support - */ -public final class TestHWPFOldDocument extends HWPFTestCase { - /** - * Test a simple Word 6 document - */ - @Test(expected=OldFileFormatException.class) - public void testWord6hwpf() throws IOException { - // Can't open as HWPFDocument - HWPFTestDataSamples.openSampleFile("Word6.doc"); - } - - @Test - public void testWord6hwpfOld() throws IOException { - // Open - HWPFOldDocument doc = HWPFTestDataSamples.openOldSampleFile("Word6.doc"); - - // Check - assertEquals(1, doc.getRange().numSections()); - assertEquals(1, doc.getRange().numParagraphs()); - assertEquals(1, doc.getRange().numCharacterRuns()); - - assertEquals("The quick brown fox jumps over the lazy dog\r", - doc.getRange().getParagraph(0).text()); - doc.close(); - } - - - - /** - * Test a simple Word 95 document - */ - @Test(expected=OldFileFormatException.class) - public void testWord95hwpf() throws IOException { - // Can't open as HWPFDocument - HWPFTestDataSamples.openSampleFile("Word95.doc"); - } - - @Test - public void testWord95hwpfOld() throws IOException { - // Open - HWPFOldDocument doc = HWPFTestDataSamples - .openOldSampleFile("Word95.doc"); - - // Check - assertEquals(1, doc.getRange().numSections()); - assertEquals(7, doc.getRange().numParagraphs()); - - assertEquals("The quick brown fox jumps over the lazy dog\r", - doc.getRange().getParagraph(0).text()); - assertEquals("\r", doc.getRange().getParagraph(1).text()); - assertEquals("Paragraph 2\r", doc.getRange().getParagraph(2).text()); - assertEquals("\r", doc.getRange().getParagraph(3).text()); - assertEquals( - "Paragraph 3. Has some RED text and some " - + "BLUE BOLD text in it.\r", - doc.getRange().getParagraph(4).text()); - assertEquals("\r", doc.getRange().getParagraph(5).text()); - assertEquals("Last (4th) paragraph.\r", - doc.getRange().getParagraph(6).text()); - - assertEquals(1, doc.getRange().getParagraph(0).numCharacterRuns()); - assertEquals(1, doc.getRange().getParagraph(1).numCharacterRuns()); - assertEquals(1, doc.getRange().getParagraph(2).numCharacterRuns()); - assertEquals(1, doc.getRange().getParagraph(3).numCharacterRuns()); - // Normal, red, normal, blue+bold, normal - assertEquals(5, doc.getRange().getParagraph(4).numCharacterRuns()); - assertEquals(1, doc.getRange().getParagraph(5).numCharacterRuns()); - // Normal, superscript for 4th, normal - assertEquals(3, doc.getRange().getParagraph(6).numCharacterRuns()); - - doc.close(); - } - - /** - * Test a word document that has sections, as well as the usual paragraph - * stuff. - */ - @Test - public void testWord6Sections() throws IOException { - HWPFOldDocument doc = HWPFTestDataSamples.openOldSampleFile("Word6_sections.doc"); - - assertEquals(3, doc.getRange().numSections()); - assertEquals(6, doc.getRange().numParagraphs()); - - assertEquals("This is a test.\r", - doc.getRange().getParagraph(0).text()); - assertEquals("\r", doc.getRange().getParagraph(1).text()); - // Section / line? - assertEquals("\u000c", doc.getRange().getParagraph(2).text()); - assertEquals("This is a new section.\r", - doc.getRange().getParagraph(3).text()); - // Section / line? - assertEquals("\u000c", doc.getRange().getParagraph(4).text()); - assertEquals("\r", doc.getRange().getParagraph(5).text()); - doc.close(); - } - - /** - * Another word document with sections, this time with a few more section - * properties set on it - */ - @Test - public void testWord6Sections2() throws IOException { - HWPFOldDocument doc = HWPFTestDataSamples - .openOldSampleFile("Word6_sections2.doc"); - - assertEquals(1, doc.getRange().numSections()); - assertEquals(57, doc.getRange().numParagraphs()); - - assertEquals("\r", doc.getRange().getParagraph(0).text()); - assertEquals("STATEMENT OF INSOLVENCY PRACTICE 10 (SCOTLAND)\r", - doc.getRange().getParagraph(1).text()); - doc.close(); - } - - @Test - public void testDefaultCodePageEncoding() throws IOException { - HWPFOldDocument doc = HWPFTestDataSamples.openOldSampleFile("Bug60942.doc"); - Word6Extractor ex = new Word6Extractor(doc); - String txt = ex.getText(); - assertContains(txt, "BERTHOD"); - assertContains(txt, "APPLICOLOR"); - assertContains(txt, "les meilleurs"); - assertContains(txt, "GUY LECOLE"); - } - - - @Test - public void testCodePageBug50955() throws IOException { - //windows 1251 - HWPFOldDocument doc = HWPFTestDataSamples.openOldSampleFile("Bug50955.doc"); - Word6Extractor ex = new Word6Extractor(doc); - - StringBuilder sb = new StringBuilder(); - for (String p : ex.getParagraphText()) { - sb.append(p); - } - assertContains(sb.toString(), "\u043F\u0440\u0438\u0432\u0435\u0442");//Greetings! - } - - @Test - public void testCodePageBug60936() throws IOException { - //windows 1250 -- this test file was generated with OpenOffice - //see https://bz.apache.org/ooo/show_bug.cgi?id=12445 for the inspiration - - - HWPFOldDocument doc = HWPFTestDataSamples.openOldSampleFile("Bug60936.doc"); - Word6Extractor ex = new Word6Extractor(doc); - StringBuilder sb = new StringBuilder(); - for (String p : ex.getParagraphText()) { - sb.append(p); - } - assertContains(sb.toString(), "4 sk\u00f3re a p\u0159ed 7 lety");//Greetings! - } - - @Test - public void testOldFontTableEncoding() throws IOException { - HWPFOldDocument doc = HWPFTestDataSamples.openOldSampleFile("Bug51944.doc"); - OldFontTable oldFontTable = doc.getOldFontTable(); - assertEquals(5, oldFontTable.getFontNames().length); - assertEquals("\u7D30\u660E\u9AD4", oldFontTable.getFontNames()[0].getMainFontName()); - assertEquals(HwmfFont.WmfCharset.CHINESEBIG5_CHARSET.getCharset(), Charset.forName("Big5")); - assertEquals("Times New Roman", oldFontTable.getFontNames()[1].getMainFontName()); - doc.close(); - - } - - @Test - public void testOldFontTableAltName() throws IOException { - HWPFOldDocument doc = HWPFTestDataSamples.openOldSampleFile("Bug60942b.doc"); - OldFontTable oldFontTable = doc.getOldFontTable(); - assertEquals(5, oldFontTable.getFontNames().length); - assertEquals("Roboto", oldFontTable.getFontNames()[3].getMainFontName()); - assertEquals("arial", oldFontTable.getFontNames()[3].getAltFontName()); - assertEquals("Roboto", oldFontTable.getFontNames()[4].getMainFontName()); - assertEquals("arial", oldFontTable.getFontNames()[4].getAltFontName()); - } - - - @Test - public void test51944() throws IOException { - HWPFOldDocument doc = HWPFTestDataSamples.openOldSampleFile("Bug51944.doc"); - Word6Extractor ex = new Word6Extractor(doc); - StringBuilder sb = new StringBuilder(); - for (String p : ex.getParagraphText()) { - sb.append(p.replaceAll("[\r\n]+", "\n")); - } - String txt = sb.toString(); - assertContains(txt, "Post and Fax"); - assertContains(txt, "also maintain");//this is at a critical juncture - assertContains(txt, "which are available for");//this too - - /* - The bytes for the following test: - 170 : 78 : x - 171 : 0 : - 172 : d : - 173 : 35 : 5 - 174 : 39 : 9 - 175 : 0 : - 176 : 2d : - - 177 : 0 : - 178 : 35 : 5 - 179 : 0 : - 180 : 35 : 5 - - Note that we are skipping over the value "5" at offset 173. - This is an apparently invalid sequence in MS's encoding scheme - - When I open the document in MSWord, I also see "\r9-55" - */ - assertContains(txt, "\n9-55 xxxxx block5"); - //TODO: figure out why these two aren't passing - //assertContains(txt, "\u2019\u0078 block2");//make sure smart quote is extracted correctly - //assertContains(txt, "We are able to");//not sure if we can get this easily? - } - -} diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestHWPFWrite.java b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestHWPFWrite.java deleted file mode 100644 index 76c71bab0..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestHWPFWrite.java +++ /dev/null @@ -1,173 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.usermodel; - -import static org.junit.Assert.assertEquals; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hwpf.HWPFDocument; -import org.apache.poi.hwpf.HWPFTestCase; -import org.apache.poi.hwpf.HWPFTestDataSamples; -import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; -import org.apache.poi.poifs.filesystem.OPOIFSFileSystem; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.TempFile; -import org.junit.Test; - -/** - * Test various write situations - */ -public final class TestHWPFWrite extends HWPFTestCase { - private static final POIDataSamples SAMPLES = POIDataSamples.getDocumentInstance(); - - /** - * Write to a stream - */ - @Test - public void testWriteStream() throws IOException { - HWPFDocument doc = HWPFTestDataSamples.openSampleFile("SampleDoc.doc"); - - Range r = doc.getRange(); - assertEquals("I am a test document\r", r.getParagraph(0).text()); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - doc.write(baos); - doc.close(); - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - - doc = new HWPFDocument(bais); - r = doc.getRange(); - assertEquals("I am a test document\r", r.getParagraph(0).text()); - doc.close(); - } - - /** - * Write to a new file - */ - @Test - public void testWriteNewFile() throws IOException { - HWPFDocument doc = HWPFTestDataSamples.openSampleFile("SampleDoc.doc"); - - Range r = doc.getRange(); - assertEquals("I am a test document\r", r.getParagraph(0).text()); - - File file = TempFile.createTempFile("TestDocument", ".doc"); - doc.write(file); - doc.close(); - - // Check reading from File and Stream - doc = new HWPFDocument(new FileInputStream(file)); - r = doc.getRange(); - assertEquals("I am a test document\r", r.getParagraph(0).text()); - doc.close(); - - doc = new HWPFDocument(new POIFSFileSystem(file)); - r = doc.getRange(); - assertEquals("I am a test document\r", r.getParagraph(0).text()); - doc.close(); - } - - /** - * Writing to the file we opened from - note, uses a temp file to avoid - * changing our test files! - */ - @Test - public void testInPlaceWrite() throws Exception { - // Setup as a copy of a known-good file - final File file = TempFile.createTempFile("TestDocument", ".doc"); - InputStream inputStream = SAMPLES.openResourceAsStream("SampleDoc.doc"); - try { - FileOutputStream outputStream = new FileOutputStream(file); - try { - IOUtils.copy(inputStream, outputStream); - } finally { - outputStream.close(); - } - } finally { - inputStream.close(); - } - - // Open from the temp file in read-write mode - NPOIFSFileSystem poifs = new NPOIFSFileSystem(file, false); - HWPFDocument doc = new HWPFDocument(poifs.getRoot()); - Range r = doc.getRange(); - assertEquals("I am a test document\r", r.getParagraph(0).text()); - - // Change - r.replaceText("X XX a test document\r", false); - - // Save in-place, close, re-open and check - doc.write(); - doc.close(); - poifs.close(); - - poifs = new NPOIFSFileSystem(file); - doc = new HWPFDocument(poifs.getRoot()); - r = doc.getRange(); - assertEquals("X XX a test document\r", r.getParagraph(0).text()); - doc.close(); - poifs.close(); - } - - @Test(expected=IllegalStateException.class) - public void testInvalidInPlaceWriteInputStream() throws IOException { - // Can't work for InputStream opened files - InputStream is = SAMPLES.openResourceAsStream("SampleDoc.doc"); - HWPFDocument doc = new HWPFDocument(is); - is.close(); - try { - doc.write(); - } finally { - doc.close(); - } - } - - @Test(expected=IllegalStateException.class) - public void testInvalidInPlaceWriteOPOIFS() throws Exception { - // Can't work for OPOIFS - OPOIFSFileSystem ofs = new OPOIFSFileSystem(SAMPLES.openResourceAsStream("SampleDoc.doc")); - HWPFDocument doc = new HWPFDocument(ofs.getRoot()); - try { - doc.write(); - } finally { - doc.close(); - } - } - - @Test(expected=IllegalStateException.class) - public void testInvalidInPlaceWriteNPOIFS() throws Exception { - // Can't work for Read-Only files - NPOIFSFileSystem fs = new NPOIFSFileSystem(SAMPLES.getFile("SampleDoc.doc"), true); - HWPFDocument doc = new HWPFDocument(fs.getRoot()); - try { - doc.write(); - } finally { - doc.close(); - fs.close(); - } - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestHeaderStories.java b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestHeaderStories.java deleted file mode 100644 index 0aa4b3162..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestHeaderStories.java +++ /dev/null @@ -1,190 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.usermodel; - -import junit.framework.TestCase; - -import org.apache.poi.hwpf.HWPFDocument; -import org.apache.poi.hwpf.HWPFTestDataSamples; - -/** - * Tests for the handling of header stories into headers, footers etc - */ -public final class TestHeaderStories extends TestCase { - private HWPFDocument none; - private HWPFDocument header; - private HWPFDocument footer; - private HWPFDocument headerFooter; - private HWPFDocument oddEven; - private HWPFDocument diffFirst; - private HWPFDocument unicode; - private HWPFDocument withFields; - - @Override - protected void setUp() { - - none = HWPFTestDataSamples.openSampleFile("NoHeadFoot.doc"); - header = HWPFTestDataSamples.openSampleFile("ThreeColHead.doc"); - footer = HWPFTestDataSamples.openSampleFile("ThreeColFoot.doc"); - headerFooter = HWPFTestDataSamples.openSampleFile("SimpleHeadThreeColFoot.doc"); - oddEven = HWPFTestDataSamples.openSampleFile("PageSpecificHeadFoot.doc"); - diffFirst = HWPFTestDataSamples.openSampleFile("DiffFirstPageHeadFoot.doc"); - unicode = HWPFTestDataSamples.openSampleFile("HeaderFooterUnicode.doc"); - withFields = HWPFTestDataSamples.openSampleFile("HeaderWithMacros.doc"); - } - - public void testNone() { - HeaderStories hs = new HeaderStories(none); - - assertNull(hs.getPlcfHdd()); - assertEquals(0, hs.getRange().text().length()); - } - - public void testHeader() { - HeaderStories hs = new HeaderStories(header); - - assertEquals(60, hs.getRange().text().length()); - - // Should have the usual 6 separaters - // Then all 6 of the different header/footer kinds - // Finally a terminater - assertEquals(13, hs.getPlcfHdd().length()); - - assertEquals(215, hs.getRange().getStartOffset()); - - assertEquals(0, hs.getPlcfHdd().getProperty(0).getStart()); - assertEquals(3, hs.getPlcfHdd().getProperty(1).getStart()); - assertEquals(6, hs.getPlcfHdd().getProperty(2).getStart()); - assertEquals(6, hs.getPlcfHdd().getProperty(3).getStart()); - assertEquals(9, hs.getPlcfHdd().getProperty(4).getStart()); - assertEquals(12, hs.getPlcfHdd().getProperty(5).getStart()); - - assertEquals(12, hs.getPlcfHdd().getProperty(6).getStart()); - assertEquals(12, hs.getPlcfHdd().getProperty(7).getStart()); - assertEquals(59, hs.getPlcfHdd().getProperty(8).getStart()); - assertEquals(59, hs.getPlcfHdd().getProperty(9).getStart()); - assertEquals(59, hs.getPlcfHdd().getProperty(10).getStart()); - assertEquals(59, hs.getPlcfHdd().getProperty(11).getStart()); - - assertEquals(59, hs.getPlcfHdd().getProperty(12).getStart()); - - assertEquals("\u0003\r\r", hs.getFootnoteSeparator()); - assertEquals("\u0004\r\r", hs.getFootnoteContSeparator()); - assertEquals("", hs.getFootnoteContNote()); - assertEquals("\u0003\r\r", hs.getEndnoteSeparator()); - assertEquals("\u0004\r\r", hs.getEndnoteContSeparator()); - assertEquals("", hs.getEndnoteContNote()); - - assertEquals("", hs.getFirstHeader()); - assertEquals("", hs.getEvenHeader()); - assertEquals("First header column!\tMid header Right header!\r\r", hs.getOddHeader()); - - assertEquals("", hs.getFirstFooter()); - assertEquals("", hs.getEvenFooter()); - assertEquals("", hs.getOddFooter()); - } - - public void testFooter() { - HeaderStories hs = new HeaderStories(footer); - - assertEquals("", hs.getFirstHeader()); - assertEquals("", hs.getEvenHeader()); - assertEquals("", hs.getOddHeader()); // Was \r\r but gets emptied - - assertEquals("", hs.getFirstFooter()); - assertEquals("", hs.getEvenFooter()); - assertEquals("Footer Left\tFooter Middle Footer Right\r\r", hs.getOddFooter()); - } - - public void testHeaderFooter() { - HeaderStories hs = new HeaderStories(headerFooter); - - assertEquals("", hs.getFirstHeader()); - assertEquals("", hs.getEvenHeader()); - assertEquals("I am some simple header text here\r\r\r", hs.getOddHeader()); - - assertEquals("", hs.getFirstFooter()); - assertEquals("", hs.getEvenFooter()); - assertEquals("Footer Left\tFooter Middle Footer Right\r\r", hs.getOddFooter()); - } - - public void testOddEven() { - HeaderStories hs = new HeaderStories(oddEven); - - assertEquals("", hs.getFirstHeader()); - assertEquals("[This is an Even Page, with a Header]\u0007August 20, 2008\u0007\u0007\r\r", - hs.getEvenHeader()); - assertEquals("August 20, 2008\u0007[ODD Page Header text]\u0007\u0007\r\r", hs - .getOddHeader()); - - assertEquals("", hs.getFirstFooter()); - assertEquals( - "\u0007Page \u0013 PAGE \\* MERGEFORMAT \u00142\u0015\u0007\u0007\u0007\u0007\u0007\u0007\u0007This is a simple footer on the second page\r\r", - hs.getEvenFooter()); - assertEquals("Footer Left\tFooter Middle Footer Right\r\r", hs.getOddFooter()); - - assertEquals("Footer Left\tFooter Middle Footer Right\r\r", hs.getFooter(1)); - assertEquals( - "\u0007Page \u0013 PAGE \\* MERGEFORMAT \u00142\u0015\u0007\u0007\u0007\u0007\u0007\u0007\u0007This is a simple footer on the second page\r\r", - hs.getFooter(2)); - assertEquals("Footer Left\tFooter Middle Footer Right\r\r", hs.getFooter(3)); - } - - public void testFirst() { - HeaderStories hs = new HeaderStories(diffFirst); - - assertEquals("I am the header on the first page, and I\u2019m nice and simple\r\r", hs - .getFirstHeader()); - assertEquals("", hs.getEvenHeader()); - assertEquals("First header column!\tMid header Right header!\r\r", hs.getOddHeader()); - - assertEquals("The footer of the first page\r\r", hs.getFirstFooter()); - assertEquals("", hs.getEvenFooter()); - assertEquals("Footer Left\tFooter Middle Footer Right\r\r", hs.getOddFooter()); - - assertEquals("The footer of the first page\r\r", hs.getFooter(1)); - assertEquals("Footer Left\tFooter Middle Footer Right\r\r", hs.getFooter(2)); - assertEquals("Footer Left\tFooter Middle Footer Right\r\r", hs.getFooter(3)); - } - - public void testUnicode() { - HeaderStories hs = new HeaderStories(unicode); - - assertEquals("", hs.getFirstHeader()); - assertEquals("", hs.getEvenHeader()); - assertEquals("This is a simple header, with a \u20ac euro symbol in it.\r\r\r", hs - .getOddHeader()); - - assertEquals("", hs.getFirstFooter()); - assertEquals("", hs.getEvenFooter()); - assertEquals("The footer, with Moli\u00e8re, has Unicode in it.\r\r", hs.getOddFooter()); - } - - public void testWithFields() { - HeaderStories hs = new HeaderStories(withFields); - assertFalse(hs.areFieldsStripped()); - - assertEquals( - "HEADER GOES HERE. 8/12/2008 \u0013 AUTHOR \\* MERGEFORMAT \u0014Eric Roch\u0015\r\r\r", - hs.getOddHeader()); - - // Now turn on stripping - hs.setAreFieldsStripped(true); - assertEquals("HEADER GOES HERE. 8/12/2008 Eric Roch\r\r\r", hs.getOddHeader()); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestLists.java b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestLists.java deleted file mode 100644 index d2c9ac95c..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestLists.java +++ /dev/null @@ -1,254 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.usermodel; - -import java.io.IOException; - -import junit.framework.TestCase; - -import org.apache.poi.hwpf.HWPFDocument; -import org.apache.poi.hwpf.HWPFTestDataSamples; -import org.apache.poi.hwpf.model.ListLevel; - -/** - * Tests for our handling of lists - */ -public final class TestLists extends TestCase { - public void testBasics() { - HWPFDocument doc = HWPFTestDataSamples.openSampleFile("Lists.doc"); - Range r = doc.getRange(); - - assertEquals(40, r.numParagraphs()); - assertEquals("Heading Level 1\r", r.getParagraph(0).text()); - assertEquals("This document has different lists in it for testing\r", r.getParagraph(1).text()); - assertEquals("The end!\r", r.getParagraph(38).text()); - assertEquals("\r", r.getParagraph(39).text()); - - assertEquals(0, r.getParagraph(0).getLvl()); - assertEquals(9, r.getParagraph(1).getLvl()); - assertEquals(9, r.getParagraph(38).getLvl()); - assertEquals(9, r.getParagraph(39).getLvl()); - } - - public void testUnorderedLists() { - HWPFDocument doc = HWPFTestDataSamples.openSampleFile("Lists.doc"); - Range r = doc.getRange(); - assertEquals(40, r.numParagraphs()); - - // Normal bullet points - assertEquals("This document has different lists in it for testing\r", r.getParagraph(1).text()); - assertEquals("Unordered list 1\r", r.getParagraph(2).text()); - assertEquals("UL 2\r", r.getParagraph(3).text()); - assertEquals("UL 3\r", r.getParagraph(4).text()); - assertEquals("Next up is an ordered list:\r", r.getParagraph(5).text()); - - assertEquals(9, r.getParagraph(1).getLvl()); - assertEquals(9, r.getParagraph(2).getLvl()); - assertEquals(9, r.getParagraph(3).getLvl()); - assertEquals(9, r.getParagraph(4).getLvl()); - assertEquals(9, r.getParagraph(5).getLvl()); - - assertEquals(0, r.getParagraph(1).getIlvl()); - assertEquals(0, r.getParagraph(2).getIlvl()); - assertEquals(0, r.getParagraph(3).getIlvl()); - assertEquals(0, r.getParagraph(4).getIlvl()); - assertEquals(0, r.getParagraph(5).getIlvl()); - - // Tick bullets - assertEquals("Now for an un-ordered list with a different bullet style:\r", r.getParagraph(9).text()); - assertEquals("Tick 1\r", r.getParagraph(10).text()); - assertEquals("Tick 2\r", r.getParagraph(11).text()); - assertEquals("Multi-level un-ordered list:\r", r.getParagraph(12).text()); - - assertEquals(9, r.getParagraph(9).getLvl()); - assertEquals(9, r.getParagraph(10).getLvl()); - assertEquals(9, r.getParagraph(11).getLvl()); - assertEquals(9, r.getParagraph(12).getLvl()); - - assertEquals(0, r.getParagraph(9).getIlvl()); - assertEquals(0, r.getParagraph(10).getIlvl()); - assertEquals(0, r.getParagraph(11).getIlvl()); - assertEquals(0, r.getParagraph(12).getIlvl()); - - // TODO Test for tick not bullet - } - - public void testOrderedLists() { - HWPFDocument doc = HWPFTestDataSamples.openSampleFile("Lists.doc"); - Range r = doc.getRange(); - assertEquals(40, r.numParagraphs()); - - assertEquals("Next up is an ordered list:\r", r.getParagraph(5).text()); - assertEquals("Ordered list 1\r", r.getParagraph(6).text()); - assertEquals("OL 2\r", r.getParagraph(7).text()); - assertEquals("OL 3\r", r.getParagraph(8).text()); - assertEquals("Now for an un-ordered list with a different bullet style:\r", r.getParagraph(9).text()); - - assertEquals(9, r.getParagraph(5).getLvl()); - assertEquals(9, r.getParagraph(6).getLvl()); - assertEquals(9, r.getParagraph(7).getLvl()); - assertEquals(9, r.getParagraph(8).getLvl()); - assertEquals(9, r.getParagraph(9).getLvl()); - - assertEquals(0, r.getParagraph(5).getIlvl()); - assertEquals(0, r.getParagraph(6).getIlvl()); - assertEquals(0, r.getParagraph(7).getIlvl()); - assertEquals(0, r.getParagraph(8).getIlvl()); - assertEquals(0, r.getParagraph(9).getIlvl()); - } - - public void testMultiLevelLists() { - HWPFDocument doc = HWPFTestDataSamples.openSampleFile("Lists.doc"); - Range r = doc.getRange(); - assertEquals(40, r.numParagraphs()); - - assertEquals("Multi-level un-ordered list:\r", r.getParagraph(12).text()); - assertEquals("ML 1:1\r", r.getParagraph(13).text()); - assertEquals("ML 1:2\r", r.getParagraph(14).text()); - assertEquals("ML 2:1\r", r.getParagraph(15).text()); - assertEquals("ML 2:2\r", r.getParagraph(16).text()); - assertEquals("ML 2:3\r", r.getParagraph(17).text()); - assertEquals("ML 3:1\r", r.getParagraph(18).text()); - assertEquals("ML 4:1\r", r.getParagraph(19).text()); - assertEquals("ML 5:1\r", r.getParagraph(20).text()); - assertEquals("ML 5:2\r", r.getParagraph(21).text()); - assertEquals("ML 2:4\r", r.getParagraph(22).text()); - assertEquals("ML 1:3\r", r.getParagraph(23).text()); - assertEquals("Multi-level ordered list:\r", r.getParagraph(24).text()); - assertEquals("OL 1\r", r.getParagraph(25).text()); - assertEquals("OL 2\r", r.getParagraph(26).text()); - assertEquals("OL 2.1\r", r.getParagraph(27).text()); - assertEquals("OL 2.2\r", r.getParagraph(28).text()); - assertEquals("OL 2.2.1\r", r.getParagraph(29).text()); - assertEquals("OL 2.2.2\r", r.getParagraph(30).text()); - assertEquals("OL 2.2.2.1\r", r.getParagraph(31).text()); - assertEquals("OL 2.2.3\r", r.getParagraph(32).text()); - assertEquals("OL 3\r", r.getParagraph(33).text()); - assertEquals("Finally we want some indents, to tell the difference\r", r.getParagraph(34).text()); - - for(int i=12; i<=34; i++) { - assertEquals(9, r.getParagraph(12).getLvl()); - } - assertEquals(0, r.getParagraph(12).getIlvl()); - assertEquals(0, r.getParagraph(13).getIlvl()); - assertEquals(0, r.getParagraph(14).getIlvl()); - assertEquals(1, r.getParagraph(15).getIlvl()); - assertEquals(1, r.getParagraph(16).getIlvl()); - assertEquals(1, r.getParagraph(17).getIlvl()); - assertEquals(2, r.getParagraph(18).getIlvl()); - assertEquals(3, r.getParagraph(19).getIlvl()); - assertEquals(4, r.getParagraph(20).getIlvl()); - assertEquals(4, r.getParagraph(21).getIlvl()); - assertEquals(1, r.getParagraph(22).getIlvl()); - assertEquals(0, r.getParagraph(23).getIlvl()); - assertEquals(0, r.getParagraph(24).getIlvl()); - assertEquals(0, r.getParagraph(25).getIlvl()); - assertEquals(0, r.getParagraph(26).getIlvl()); - assertEquals(1, r.getParagraph(27).getIlvl()); - assertEquals(1, r.getParagraph(28).getIlvl()); - assertEquals(2, r.getParagraph(29).getIlvl()); - assertEquals(2, r.getParagraph(30).getIlvl()); - assertEquals(3, r.getParagraph(31).getIlvl()); - assertEquals(2, r.getParagraph(32).getIlvl()); - assertEquals(0, r.getParagraph(33).getIlvl()); - assertEquals(0, r.getParagraph(34).getIlvl()); - } - - public void testIndentedText() { - HWPFDocument doc = HWPFTestDataSamples.openSampleFile("Lists.doc"); - Range r = doc.getRange(); - - assertEquals(40, r.numParagraphs()); - assertEquals("Finally we want some indents, to tell the difference\r", r.getParagraph(34).text()); - assertEquals("Indented once\r", r.getParagraph(35).text()); - assertEquals("Indented twice\r", r.getParagraph(36).text()); - assertEquals("Indented three times\r", r.getParagraph(37).text()); - assertEquals("The end!\r", r.getParagraph(38).text()); - - assertEquals(9, r.getParagraph(34).getLvl()); - assertEquals(9, r.getParagraph(35).getLvl()); - assertEquals(9, r.getParagraph(36).getLvl()); - assertEquals(9, r.getParagraph(37).getLvl()); - assertEquals(9, r.getParagraph(38).getLvl()); - assertEquals(9, r.getParagraph(39).getLvl()); - - assertEquals(0, r.getParagraph(34).getIlvl()); - assertEquals(0, r.getParagraph(35).getIlvl()); - assertEquals(0, r.getParagraph(36).getIlvl()); - assertEquals(0, r.getParagraph(37).getIlvl()); - assertEquals(0, r.getParagraph(38).getIlvl()); - assertEquals(0, r.getParagraph(39).getIlvl()); - - // TODO Test the indent - } - - public void testWriteRead() throws IOException { - HWPFDocument doc = HWPFTestDataSamples.openSampleFile("Lists.doc"); - doc = HWPFTestDataSamples.writeOutAndReadBack(doc); - - Range r = doc.getRange(); - - // Check a couple at random - assertEquals(4, r.getParagraph(21).getIlvl()); - assertEquals(1, r.getParagraph(22).getIlvl()); - assertEquals(0, r.getParagraph(23).getIlvl()); - } - - public void testSpecificNumberedOrderedListFeatures() throws IOException { - HWPFDocument doc = HWPFTestDataSamples.openSampleFile("Lists.doc"); - - Range r = doc.getRange(); - //these are in the numbered ordered list - //26 = OL 2 - //27 = OL 2.1 - //28 = OL 2.2 - //29 = OL 2.2.1 - for (int i = 26; i < 30; i++) { - Paragraph p = r.getParagraph(i); - assertTrue(p.isInList()); - HWPFList list = p.getList(); - ListLevel level = list.getLVL((char) p.getIlvl()); - assertFalse(level.isLegalNumbering()); - assertEquals(-1, level.getRestart()); - } - Paragraph p = r.getParagraph(26); - HWPFList list = p.getList(); - ListLevel level = list.getLVL((char) p.getIlvl()); - byte[] lvl = level.getLevelNumberingPlaceholderOffsets(); - - assertEquals((byte)1, lvl[0]); - assertEquals((byte)0, lvl[1]); - - p = r.getParagraph(27); - list = p.getList(); - level = list.getLVL((char) p.getIlvl()); - lvl = level.getLevelNumberingPlaceholderOffsets(); - assertEquals((byte)1, lvl[0]); - assertEquals((byte)3, lvl[1]); - - p = r.getParagraph(29); - list = p.getList(); - level = list.getLVL((char) p.getIlvl()); - lvl = level.getLevelNumberingPlaceholderOffsets(); - - assertEquals((byte)1, lvl[0]); - assertEquals((byte)3, lvl[1]); - assertEquals((byte)5, lvl[2]); - } - -} diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestOfficeDrawings.java b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestOfficeDrawings.java deleted file mode 100644 index ca0caf5b0..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestOfficeDrawings.java +++ /dev/null @@ -1,55 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hwpf.usermodel; - -import junit.framework.TestCase; - -import org.apache.poi.ddf.EscherComplexProperty; -import org.apache.poi.ddf.EscherContainerRecord; -import org.apache.poi.ddf.EscherOptRecord; -import org.apache.poi.hwpf.HWPFDocument; -import org.apache.poi.hwpf.HWPFTestDataSamples; -import org.apache.poi.util.StringUtil; - -/** - * Test cases for {@link OfficeDrawing} and {@link OfficeDrawingsImpl} classes. - * - * @author Sergey Vladimirov (vlsergey {at} gmail {dot} com) - */ -public class TestOfficeDrawings extends TestCase -{ - /** - * Tests watermark text extraction - */ - public void testWatermark() throws Exception - { - HWPFDocument hwpfDocument = HWPFTestDataSamples - .openSampleFile( "watermark.doc" ); - OfficeDrawing drawing = hwpfDocument.getOfficeDrawingsHeaders() - .getOfficeDrawings().iterator().next(); - EscherContainerRecord escherContainerRecord = drawing - .getOfficeArtSpContainer(); - - EscherOptRecord officeArtFOPT = escherContainerRecord - .getChildById( (short) 0xF00B ); - EscherComplexProperty gtextUNICODE = (EscherComplexProperty) officeArtFOPT - .lookup( 0x00c0 ); - - String text = StringUtil.getFromUnicodeLE(gtextUNICODE.getComplexData()); - assertEquals( "DRAFT CONTRACT\0", text ); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestPictures.java b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestPictures.java deleted file mode 100644 index f60b010ef..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestPictures.java +++ /dev/null @@ -1,398 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.FileOutputStream; -import java.io.OutputStream; -import java.util.List; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hwpf.HWPFDocument; -import org.apache.poi.hwpf.HWPFTestDataSamples; -import org.apache.poi.hwpf.model.PicturesTable; -import org.junit.Ignore; -import org.junit.Test; - -/** - * Test the picture handling - * - * @author Nick Burch - */ -public final class TestPictures { - - /** - * two jpegs - */ - @Test - public void testTwoImages() { - HWPFDocument doc = HWPFTestDataSamples.openSampleFile("two_images.doc"); - List pics = doc.getPicturesTable().getAllPictures(); - - assertNotNull(pics); - assertEquals(pics.size(), 2); - for(int i=0; i pics = doc.getPicturesTable().getAllPictures(); - - assertNotNull(pics); - assertEquals(7, pics.size()); - for(Picture pic : pics) { - assertNotNull(pic.suggestFileExtension()); - assertNotNull(pic.suggestFullFileName()); - } - - assertEquals("jpg", pics.get(0).suggestFileExtension()); - assertEquals("image/jpeg", pics.get(0).getMimeType()); - assertEquals("jpg", pics.get(1).suggestFileExtension()); - assertEquals("image/jpeg", pics.get(1).getMimeType()); - assertEquals("png", pics.get(3).suggestFileExtension()); - assertEquals("image/png", pics.get(3).getMimeType()); - assertEquals("png", pics.get(4).suggestFileExtension()); - assertEquals("image/png", pics.get(4).getMimeType()); - assertEquals("wmf", pics.get(5).suggestFileExtension()); - assertEquals("image/x-wmf", pics.get(5).getMimeType()); - assertEquals("jpg", pics.get(6).suggestFileExtension()); - assertEquals("image/jpeg", pics.get(6).getMimeType()); - } - - /** - * emf image, nice and simple - */ - @Test - public void testEmfImage() { - HWPFDocument doc = HWPFTestDataSamples.openSampleFile("vector_image.doc"); - List pics = doc.getPicturesTable().getAllPictures(); - - assertNotNull(pics); - assertEquals(1, pics.size()); - - Picture pic = pics.get(0); - assertNotNull(pic.suggestFileExtension()); - assertNotNull(pic.suggestFullFileName()); - assertTrue(pic.getSize() > 128); - - // Check right contents - byte[] emf = POIDataSamples.getDocumentInstance().readFile("vector_image.emf"); - byte[] pemf = pic.getContent(); - assertEquals(emf.length, pemf.length); - for(int i=0; i pics = doc.getPicturesTable().getAllPictures(); - assertEquals(2, pics.size()); - } - - @Test - public void testPicturesInHeader() { - HWPFDocument doc = HWPFTestDataSamples.openSampleFile("header_image.doc"); - - List pics = doc.getPicturesTable().getAllPictures(); - assertEquals(2, pics.size()); - } - - @Test - public void testFastSaved() { - HWPFDocument doc = HWPFTestDataSamples.openSampleFile("rasp.doc"); - - doc.getPicturesTable().getAllPictures(); // just check that we do not throw Exception - } - - @Test - public void testFastSaved2() { - HWPFDocument doc = HWPFTestDataSamples.openSampleFile("o_kurs.doc"); - - doc.getPicturesTable().getAllPictures(); // just check that we do not throw Exception - } - - @Test - public void testFastSaved3() { - HWPFDocument doc = HWPFTestDataSamples.openSampleFile("ob_is.doc"); - - doc.getPicturesTable().getAllPictures(); // just check that we do not throw Exception - } - - /** - * When you embed another office document into Word, it stores - * a rendered "icon" picture of what that document looks like. - * This image is re-created when you edit the embeded document, - * then used as-is to speed things up. - * Check that we can properly read one of these - */ - @Test - public void testEmbededDocumentIcon() { - // This file has two embeded excel files, an embeded powerpoint - // file and an embeded word file, in that order - HWPFDocument doc = HWPFTestDataSamples.openSampleFile("word_with_embeded.doc"); - - // Check we don't break loading the pictures - doc.getPicturesTable().getAllPictures(); - PicturesTable pictureTable = doc.getPicturesTable(); - - // Check the text, and its embeded images - Paragraph p; - Range r = doc.getRange(); - assertEquals(1, r.numSections()); - assertEquals(5, r.numParagraphs()); - - p = r.getParagraph(0); - assertEquals(2, p.numCharacterRuns()); - assertEquals("I have lots of embedded files in me\r", p.text()); - assertEquals(false, pictureTable.hasPicture(p.getCharacterRun(0))); - assertEquals(false, pictureTable.hasPicture(p.getCharacterRun(1))); - - p = r.getParagraph(1); - assertEquals(5, p.numCharacterRuns()); - assertEquals("\u0013 EMBED Excel.Sheet.8 \u0014\u0001\u0015\r", p.text()); - assertEquals(false, pictureTable.hasPicture(p.getCharacterRun(0))); - assertEquals(false, pictureTable.hasPicture(p.getCharacterRun(1))); - assertEquals(false, pictureTable.hasPicture(p.getCharacterRun(2))); - assertEquals(true, pictureTable.hasPicture(p.getCharacterRun(3))); - assertEquals(false, pictureTable.hasPicture(p.getCharacterRun(4))); - - p = r.getParagraph(2); - assertEquals(6, p.numCharacterRuns()); - assertEquals("\u0013 EMBED Excel.Sheet.8 \u0014\u0001\u0015\r", p.text()); - assertEquals(false, pictureTable.hasPicture(p.getCharacterRun(0))); - assertEquals(false, pictureTable.hasPicture(p.getCharacterRun(1))); - assertEquals(false, pictureTable.hasPicture(p.getCharacterRun(2))); - assertEquals(true, pictureTable.hasPicture(p.getCharacterRun(3))); - assertEquals(false, pictureTable.hasPicture(p.getCharacterRun(4))); - assertEquals(false, pictureTable.hasPicture(p.getCharacterRun(5))); - - p = r.getParagraph(3); - assertEquals(6, p.numCharacterRuns()); - assertEquals("\u0013 EMBED PowerPoint.Show.8 \u0014\u0001\u0015\r", p.text()); - assertEquals(false, pictureTable.hasPicture(p.getCharacterRun(0))); - assertEquals(false, pictureTable.hasPicture(p.getCharacterRun(1))); - assertEquals(false, pictureTable.hasPicture(p.getCharacterRun(2))); - assertEquals(true, pictureTable.hasPicture(p.getCharacterRun(3))); - assertEquals(false, pictureTable.hasPicture(p.getCharacterRun(4))); - assertEquals(false, pictureTable.hasPicture(p.getCharacterRun(5))); - - p = r.getParagraph(4); - assertEquals(6, p.numCharacterRuns()); - assertEquals("\u0013 EMBED Word.Document.8 \\s \u0014\u0001\u0015\r", p.text()); - assertEquals(false, pictureTable.hasPicture(p.getCharacterRun(0))); - assertEquals(false, pictureTable.hasPicture(p.getCharacterRun(1))); - assertEquals(false, pictureTable.hasPicture(p.getCharacterRun(2))); - assertEquals(true, pictureTable.hasPicture(p.getCharacterRun(3))); - assertEquals(false, pictureTable.hasPicture(p.getCharacterRun(4))); - assertEquals(false, pictureTable.hasPicture(p.getCharacterRun(5))); - - // Look at the pictures table - List pictures = pictureTable.getAllPictures(); - assertEquals(4, pictures.size()); - - Picture picture = pictures.get( 0 ); - assertEquals( "emf", picture.suggestFileExtension() ); - assertEquals( "0.emf", picture.suggestFullFileName() ); - assertEquals( "image/x-emf", picture.getMimeType() ); - - picture = pictures.get( 1 ); - assertEquals( "emf", picture.suggestFileExtension() ); - assertEquals( "469.emf", picture.suggestFullFileName() ); - assertEquals( "image/x-emf", picture.getMimeType() ); - - picture = pictures.get( 2 ); - assertEquals( "emf", picture.suggestFileExtension() ); - assertEquals( "8c7.emf", picture.suggestFullFileName() ); - assertEquals( "image/x-emf", picture.getMimeType() ); - - picture = pictures.get( 3 ); - assertEquals( "emf", picture.suggestFileExtension() ); - assertEquals( "10a8.emf", picture.suggestFullFileName() ); - assertEquals( "image/x-emf", picture.getMimeType() ); - } - - @Test - public void testEquation() - { - HWPFDocument doc = HWPFTestDataSamples.openSampleFile( "equation.doc" ); - PicturesTable pictures = doc.getPicturesTable(); - - final List allPictures = pictures.getAllPictures(); - assertEquals( 1, allPictures.size() ); - - Picture picture = allPictures.get( 0 ); - assertNotNull( picture ); - assertEquals( PictureType.EMF, picture.suggestPictureType() ); - assertEquals( PictureType.EMF.getExtension(), - picture.suggestFileExtension() ); - assertEquals( PictureType.EMF.getMime(), picture.getMimeType() ); - assertEquals( "0.emf", picture.suggestFullFileName() ); - } - - /** - * In word you can have floating or fixed pictures. - * Fixed have a \u0001 in place with an offset to the - * picture data. - * Floating have a \u0008 in place, which references a - * \u0001 which has the offset. More than one can - * reference the same \u0001 - */ - @Test - public void testFloatingPictures() { - HWPFDocument doc = HWPFTestDataSamples.openSampleFile("FloatingPictures.doc"); - PicturesTable pictures = doc.getPicturesTable(); - - // There are 19 images in the picture, but some are - // duplicate floating ones - assertEquals(17, pictures.getAllPictures().size()); - - int plain8s = 0; - int escher8s = 0; - int image1s = 0; - - Range r = doc.getRange(); - for(int np=0; np < r.numParagraphs(); np++) { - Paragraph p = r.getParagraph(np); - for(int nc=0; nc < p.numCharacterRuns(); nc++) { - CharacterRun cr = p.getCharacterRun(nc); - if(pictures.hasPicture(cr)) { - image1s++; - } else if(pictures.hasEscherPicture(cr)) { - escher8s++; - } else if(cr.text().startsWith("\u0008")) { - plain8s++; - } - } - } - // Total is 20, as the 4 escher 8s all reference - // the same regular image - assertEquals(16, image1s); - assertEquals(4, escher8s); - assertEquals(0, plain8s); - } - - @SuppressWarnings( "deprecation" ) - @Test - public void testCroppedPictures() { - HWPFDocument doc = HWPFTestDataSamples.openSampleFile("testCroppedPictures.doc"); - List pics = doc.getPicturesTable().getAllPictures(); - - assertNotNull(pics); - assertEquals(2, pics.size()); - - Picture pic1 = pics.get(0); - assertEquals("FIXME: unable to get image width", -1, pic1.getWidth()); - assertEquals(270, pic1.getHorizontalScalingFactor()); - assertEquals(271, pic1.getVerticalScalingFactor()); - assertEquals(12000, pic1.getDxaGoal()); // 21.17 cm / 2.54 cm/inch * 72dpi * 20 = 12000 - assertEquals(9000, pic1.getDyaGoal()); // 15.88 cm / 2.54 cm/inch * 72dpi * 20 = 9000 - assertEquals(0, pic1.getDxaCropLeft()); - assertEquals(0, pic1.getDxaCropRight()); - assertEquals(0, pic1.getDyaCropTop()); - assertEquals(0, pic1.getDyaCropBottom()); - - Picture pic2 = pics.get(1); - assertEquals("FIXME: unable to get image width", -1, pic2.getWidth()); - assertEquals(764, pic2.getHorizontalScalingFactor()); - assertEquals(685, pic2.getVerticalScalingFactor()); - assertEquals(12000, pic2.getDxaGoal()); // 21.17 cm / 2.54 cm/inch * 72dpi * 20 = 12000 - assertEquals(9000, pic2.getDyaGoal()); // 15.88 cm / 2.54 cm/inch * 72dpi * 20 = 9000 - assertEquals(0, pic2.getDxaCropLeft()); // TODO YK: The Picture is cropped but HWPF reads the crop parameters all zeros - assertEquals(0, pic2.getDxaCropRight()); - assertEquals(0, pic2.getDyaCropTop()); - assertEquals(0, pic2.getDyaCropBottom()); - } - - @Test - public void testPictureDetectionWithPNG() { - HWPFDocument document = HWPFTestDataSamples.openSampleFile("PngPicture.doc"); - PicturesTable pictureTable = document.getPicturesTable(); - - assertEquals(1, pictureTable.getAllPictures().size()); - - Picture p = pictureTable.getAllPictures().get(0); - assertEquals(PictureType.PNG, p.suggestPictureType()); - assertEquals("png", p.suggestFileExtension()); - } - - @Test - public void testPictureWithAlternativeText() { - HWPFDocument document = HWPFTestDataSamples.openSampleFile("Picture_Alternative_Text.doc"); - PicturesTable pictureTable = document.getPicturesTable(); - Picture picture = pictureTable.getAllPictures().get(0); - - assertEquals("This is the alternative text for the picture.", picture.getDescription()); - } - - @Ignore("This bug is not fixed yet") - @Test - public void test58804_1() throws Exception { - HWPFDocument docA = HWPFTestDataSamples.openSampleFile("58804_1.doc"); - - expectImages(docA, 1); - - HWPFDocument docB = HWPFTestDataSamples.writeOutAndReadBack(docA); - - OutputStream out = new FileOutputStream("/tmp/58804_1_out.doc"); - try { - docB.write(out); - } finally { - out.close(); - } - - expectImages(docB, 1); - } - - @Ignore("This bug is not fixed yet") - @Test - public void test58804() throws Exception { - HWPFDocument docA = HWPFTestDataSamples.openSampleFile("58804.doc"); - - expectImages(docA, 7); - - HWPFDocument docB = HWPFTestDataSamples.writeOutAndReadBack(docA); - - expectImages(docB, 7); - } - - private void expectImages(HWPFDocument docA, int expectedCount) { - assertNotNull(docA.getPicturesTable()); - PicturesTable picA = docA.getPicturesTable(); - List picturesA = picA.getAllPictures(); - assertEquals(expectedCount, picturesA.size()); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestProblems.java b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestProblems.java deleted file mode 100644 index 3979a442c..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestProblems.java +++ /dev/null @@ -1,434 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import java.io.IOException; - -import org.apache.poi.EncryptedDocumentException; -import org.apache.poi.hwpf.HWPFDocument; -import org.apache.poi.hwpf.HWPFTestCase; -import org.apache.poi.hwpf.HWPFTestDataSamples; -import org.apache.poi.hwpf.extractor.WordExtractor; -import org.apache.poi.hwpf.model.StyleSheet; -import org.junit.Test; - -/** - * Test various problem documents - */ -public final class TestProblems extends HWPFTestCase { - - /** - * ListEntry passed no ListTable - */ - @Test - public void testListEntryNoListTable() throws IOException { - HWPFDocument doc = HWPFTestDataSamples.openSampleFile("ListEntryNoListTable.doc"); - - Range r = doc.getRange(); - for (int x = 0; x < r.numSections(); x++) { - Section s = r.getSection(x); - for (int y = 0; y < s.numParagraphs(); y++) { - s.getParagraph(y); - } - } - - doc.close(); - } - - /** - * AIOOB for TableSprmUncompressor.unCompressTAPOperation - */ - @Test - public void testSprmAIOOB() throws IOException { - HWPFDocument doc = HWPFTestDataSamples.openSampleFile("AIOOB-Tap.doc"); - - StyleSheet styleSheet = doc.getStyleSheet(); - assertNotNull(styleSheet); - - Range r = doc.getRange(); - for (int x = 0; x < r.numSections(); x++) { - Section s = r.getSection(x); - for (int y = 0; y < s.numParagraphs(); y++) { - Paragraph paragraph = s.getParagraph(y); - assertNotNull(paragraph); - } - } - doc.close(); - } - - /** - * Test for TableCell not skipping the last paragraph. Bugs #45062 and - * #44292 - */ - @Test - public void testTableCellLastParagraph() throws IOException { - HWPFDocument doc = HWPFTestDataSamples.openSampleFile("Bug44292.doc"); - Range r = doc.getRange(); - assertEquals(6, r.numParagraphs()); - assertEquals(0, r.getStartOffset()); - assertEquals(87, r.getEndOffset()); - - // Paragraph with table - Paragraph p = r.getParagraph(0); - assertEquals(0, p.getStartOffset()); - assertEquals(20, p.getEndOffset()); - - // Check a few bits of the table directly - assertEquals("One paragraph is ok\7", r.getParagraph(0).text()); - assertEquals("First para is ok\r", r.getParagraph(1).text()); - assertEquals("Second paragraph is skipped\7", r.getParagraph(2).text()); - assertEquals("One paragraph is ok\7", r.getParagraph(3).text()); - assertEquals("\7", r.getParagraph(4).text()); - assertEquals("\r", r.getParagraph(5).text()); - - // Get the table - Table t = r.getTable(p); - - // get the only row - assertEquals(1, t.numRows()); - TableRow row = t.getRow(0); - - // sanity check our row - assertEquals(5, row.numParagraphs()); - assertEquals(0, row._parStart); - assertEquals(5, row._parEnd); - assertEquals(0, row.getStartOffset()); - assertEquals(86, row.getEndOffset()); - - // get the first cell - TableCell cell = row.getCell(0); - // First cell should have one paragraph - assertEquals(1, cell.numParagraphs()); - assertEquals("One paragraph is ok\7", cell.getParagraph(0).text()); - assertEquals(0, cell._parStart); - assertEquals(1, cell._parEnd); - assertEquals(0, cell.getStartOffset()); - assertEquals(20, cell.getEndOffset()); - - // get the second - cell = row.getCell(1); - // Second cell should be detected as having two paragraphs - assertEquals(2, cell.numParagraphs()); - assertEquals("First para is ok\r", cell.getParagraph(0).text()); - assertEquals("Second paragraph is skipped\7", - cell.getParagraph(1).text()); - assertEquals(1, cell._parStart); - assertEquals(3, cell._parEnd); - assertEquals(20, cell.getStartOffset()); - assertEquals(65, cell.getEndOffset()); - - // get the last cell - cell = row.getCell(2); - // Last cell should have one paragraph - assertEquals(1, cell.numParagraphs()); - assertEquals("One paragraph is ok\7", cell.getParagraph(0).text()); - assertEquals(3, cell._parStart); - assertEquals(4, cell._parEnd); - assertEquals(65, cell.getStartOffset()); - assertEquals(85, cell.getEndOffset()); - - doc.close(); - } - - @Test - public void testRangeDelete() throws IOException { - HWPFDocument doc = HWPFTestDataSamples.openSampleFile("Bug28627.doc"); - - Range range = doc.getRange(); - int numParagraphs = range.numParagraphs(); - - int totalLength = 0, deletedLength = 0; - - for (int i = 0; i < numParagraphs; i++) { - Paragraph para = range.getParagraph(i); - String text = para.text(); - - totalLength += text.length(); - if (text.indexOf("{delete me}") > -1) { - para.delete(); - deletedLength = text.length(); - } - } - - // check the text length after deletion - int newLength = 0; - range = doc.getRange(); - numParagraphs = range.numParagraphs(); - - for (int i = 0; i < numParagraphs; i++) { - Paragraph para = range.getParagraph(i); - String text = para.text(); - - newLength += text.length(); - } - - assertEquals(newLength, totalLength - deletedLength); - - doc.close(); - } - - /** - * With an encrypted file, we should give a suitable exception, and not OOM - */ - @Test(expected=EncryptedDocumentException.class) - public void testEncryptedFile() throws IOException { - HWPFTestDataSamples.openSampleFile("PasswordProtected.doc"); - } - - @Test - public void testWriteProperties() throws IOException { - HWPFDocument doc = HWPFTestDataSamples.openSampleFile("SampleDoc.doc"); - assertEquals("Nick Burch", doc.getSummaryInformation().getAuthor()); - - // Write and read - HWPFDocument doc2 = writeOutAndRead(doc); - assertEquals("Nick Burch", doc2.getSummaryInformation().getAuthor()); - doc2.close(); - doc.close(); - } - - /** - * Test for reading paragraphs from Range after replacing some text in this - * Range. Bug #45269 - */ - @Test - public void testReadParagraphsAfterReplaceText() throws IOException { - HWPFDocument doc = HWPFTestDataSamples.openSampleFile("Bug45269.doc"); - Range range = doc.getRange(); - - String toFind = "campo1"; - String longer = " foi porraaaaa "; - String shorter = " foi "; - - // check replace with longer text - for (int x = 0; x < range.numParagraphs(); x++) { - Paragraph para = range.getParagraph(x); - int offset = para.text().indexOf(toFind); - if (offset >= 0) { - para.replaceText(toFind, longer, offset); - assertEquals(offset, para.text().indexOf(longer)); - } - } - - doc = HWPFTestDataSamples.openSampleFile("Bug45269.doc"); - range = doc.getRange(); - - // check replace with shorter text - for (int x = 0; x < range.numParagraphs(); x++) { - Paragraph para = range.getParagraph(x); - int offset = para.text().indexOf(toFind); - if (offset >= 0) { - para.replaceText(toFind, shorter, offset); - assertEquals(offset, para.text().indexOf(shorter)); - } - } - - doc.close(); - } - - /** - * Bug #49936 - Problems with reading the header out of the Header Stories - */ - @SuppressWarnings("deprecation") - @Test - public void testProblemHeaderStories49936() throws IOException { - HWPFDocument doc = HWPFTestDataSamples.openSampleFile("HeaderFooterProblematic.doc"); - HeaderStories hs = new HeaderStories(doc); - - assertEquals("", hs.getFirstHeader()); - assertEquals("\r", hs.getEvenHeader()); - assertEquals("", hs.getOddHeader()); - - assertEquals("", hs.getFirstFooter()); - assertEquals("", hs.getEvenFooter()); - assertEquals("", hs.getOddFooter()); - - WordExtractor ext = new WordExtractor(doc); - assertEquals("\n", ext.getHeaderText()); - assertEquals("", ext.getFooterText()); - ext.close(); - doc.close(); - } - - /** - * Bug #45877 - problematic PAPX with no parent set - */ - @Test - public void testParagraphPAPXNoParent45877() throws IOException { - HWPFDocument doc = HWPFTestDataSamples.openSampleFile("Bug45877.doc"); - assertEquals(17, doc.getRange().numParagraphs()); - - assertEquals("First paragraph\r", - doc.getRange().getParagraph(0).text()); - assertEquals("After Crashing Part\r", - doc.getRange().getParagraph(13).text()); - - doc.close(); - } - - /** - * Bug #48245 - don't include the text from the next cell in the current one - */ - @Test - public void testTableIterator() throws IOException { - HWPFDocument doc = HWPFTestDataSamples.openSampleFile("simple-table2.doc"); - Range r = doc.getRange(); - - // Check the text is as we'd expect - assertEquals(13, r.numParagraphs()); - assertEquals("Row 1/Cell 1\u0007", r.getParagraph(0).text()); - assertEquals("Row 1/Cell 2\u0007", r.getParagraph(1).text()); - assertEquals("Row 1/Cell 3\u0007", r.getParagraph(2).text()); - assertEquals("\u0007", r.getParagraph(3).text()); - assertEquals("Row 2/Cell 1\u0007", r.getParagraph(4).text()); - assertEquals("Row 2/Cell 2\u0007", r.getParagraph(5).text()); - assertEquals("Row 2/Cell 3\u0007", r.getParagraph(6).text()); - assertEquals("\u0007", r.getParagraph(7).text()); - assertEquals("Row 3/Cell 1\u0007", r.getParagraph(8).text()); - assertEquals("Row 3/Cell 2\u0007", r.getParagraph(9).text()); - assertEquals("Row 3/Cell 3\u0007", r.getParagraph(10).text()); - assertEquals("\u0007", r.getParagraph(11).text()); - assertEquals("\r", r.getParagraph(12).text()); - - Paragraph p; - - // Take a look in detail at the first couple of - // paragraphs - p = r.getParagraph(0); - assertEquals(1, p.numParagraphs()); - assertEquals(0, p.getStartOffset()); - assertEquals(13, p.getEndOffset()); - assertEquals(0, p._parStart); - assertEquals(1, p._parEnd); - - p = r.getParagraph(1); - assertEquals(1, p.numParagraphs()); - assertEquals(13, p.getStartOffset()); - assertEquals(26, p.getEndOffset()); - assertEquals(1, p._parStart); - assertEquals(2, p._parEnd); - - p = r.getParagraph(2); - assertEquals(1, p.numParagraphs()); - assertEquals(26, p.getStartOffset()); - assertEquals(39, p.getEndOffset()); - assertEquals(2, p._parStart); - assertEquals(3, p._parEnd); - - // Now look at the table - Table table = r.getTable(r.getParagraph(0)); - assertEquals(3, table.numRows()); - - TableRow row; - TableCell cell; - - row = table.getRow(0); - assertEquals(0, row._parStart); - assertEquals(4, row._parEnd); - - cell = row.getCell(0); - assertEquals(1, cell.numParagraphs()); - assertEquals(0, cell._parStart); - assertEquals(1, cell._parEnd); - assertEquals(0, cell.getStartOffset()); - assertEquals(13, cell.getEndOffset()); - assertEquals("Row 1/Cell 1\u0007", cell.text()); - assertEquals("Row 1/Cell 1\u0007", cell.getParagraph(0).text()); - - cell = row.getCell(1); - assertEquals(1, cell.numParagraphs()); - assertEquals(1, cell._parStart); - assertEquals(2, cell._parEnd); - assertEquals(13, cell.getStartOffset()); - assertEquals(26, cell.getEndOffset()); - assertEquals("Row 1/Cell 2\u0007", cell.text()); - assertEquals("Row 1/Cell 2\u0007", cell.getParagraph(0).text()); - - cell = row.getCell(2); - assertEquals(1, cell.numParagraphs()); - assertEquals(2, cell._parStart); - assertEquals(3, cell._parEnd); - assertEquals(26, cell.getStartOffset()); - assertEquals(39, cell.getEndOffset()); - assertEquals("Row 1/Cell 3\u0007", cell.text()); - assertEquals("Row 1/Cell 3\u0007", cell.getParagraph(0).text()); - - // Onto row #2 - row = table.getRow(1); - assertEquals(4, row._parStart); - assertEquals(8, row._parEnd); - - cell = row.getCell(0); - assertEquals(1, cell.numParagraphs()); - assertEquals(4, cell._parStart); - assertEquals(5, cell._parEnd); - assertEquals(40, cell.getStartOffset()); - assertEquals(53, cell.getEndOffset()); - assertEquals("Row 2/Cell 1\u0007", cell.text()); - - cell = row.getCell(1); - assertEquals(1, cell.numParagraphs()); - assertEquals(5, cell._parStart); - assertEquals(6, cell._parEnd); - assertEquals(53, cell.getStartOffset()); - assertEquals(66, cell.getEndOffset()); - assertEquals("Row 2/Cell 2\u0007", cell.text()); - - cell = row.getCell(2); - assertEquals(1, cell.numParagraphs()); - assertEquals(6, cell._parStart); - assertEquals(7, cell._parEnd); - assertEquals(66, cell.getStartOffset()); - assertEquals(79, cell.getEndOffset()); - assertEquals("Row 2/Cell 3\u0007", cell.text()); - - // Finally row 3 - row = table.getRow(2); - assertEquals(8, row._parStart); - assertEquals(12, row._parEnd); - - cell = row.getCell(0); - assertEquals(1, cell.numParagraphs()); - assertEquals(8, cell._parStart); - assertEquals(9, cell._parEnd); - assertEquals(80, cell.getStartOffset()); - assertEquals(93, cell.getEndOffset()); - assertEquals("Row 3/Cell 1\u0007", cell.text()); - - cell = row.getCell(1); - assertEquals(1, cell.numParagraphs()); - assertEquals(9, cell._parStart); - assertEquals(10, cell._parEnd); - assertEquals(93, cell.getStartOffset()); - assertEquals(106, cell.getEndOffset()); - assertEquals("Row 3/Cell 2\u0007", cell.text()); - - cell = row.getCell(2); - assertEquals(1, cell.numParagraphs()); - assertEquals(10, cell._parStart); - assertEquals(11, cell._parEnd); - assertEquals(106, cell.getStartOffset()); - assertEquals(119, cell.getEndOffset()); - assertEquals("Row 3/Cell 3\u0007", cell.text()); - - doc.close(); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestRange.java b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestRange.java deleted file mode 100644 index 2fa5aa292..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestRange.java +++ /dev/null @@ -1,96 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.io.InputStream; -import java.util.List; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hwpf.HWPFDocument; -import org.apache.poi.hwpf.model.SEPX; -import org.junit.Test; - -/** - * Tests for Range which aren't around deletion, insertion, text replacement or - * textual contents - */ -public final class TestRange { - private static final POIDataSamples SAMPLES = POIDataSamples.getDocumentInstance(); - - @Test - public void testFieldStripping() { - String exp = "This is some text."; - - String single = "This is some \u0013Blah!\u0015text."; - String with14 = "This is \u0013Blah!\u0014some\u0015 text."; - String withNested = "This is \u0013Blah!\u0013Blah!\u0015\u0015some text."; - String withNested14 = "This is \u0013Blah!\u0013Blah!\u0014don't see me\u0015 blah!\u0015some text."; - String withNestedIn14 = "This is \u0013Blah!\u0014some\u0013Blah!\u0015 \u0015text."; - - // Check all comes out right - assertEquals( exp, Range.stripFields( exp ) ); - assertEquals( exp, Range.stripFields( single ) ); - assertEquals( exp, Range.stripFields( with14 ) ); - assertEquals( exp, Range.stripFields( withNested ) ); - assertEquals( exp, Range.stripFields( withNested14 ) ); - assertEquals( exp, Range.stripFields( withNestedIn14 ) ); - - // Ones that are odd and we won't change - String odd1 = "This\u0015 is \u0013 odd"; - String odd2 = "This\u0015 is \u0014 also \u0013 odd"; - - assertEquals( odd1, Range.stripFields( odd1 ) ); - assertEquals( odd2, Range.stripFields( odd2 ) ); - } - - @Test - public void testBug46817() throws IOException { - InputStream is = SAMPLES.openResourceAsStream( "Bug46817.doc" ); - HWPFDocument hwpfDocument = new HWPFDocument( is ); - is.close(); - - final List sections = hwpfDocument.getSectionTable() - .getSections(); - assertEquals( sections.size(), 1 ); - - // whole document, including additional text from shape - SEPX sepx = sections.get( 0 ); - assertEquals( sepx.getStart(), 0 ); - assertEquals( sepx.getEnd(), 1428 ); - - // only main range - Range range = hwpfDocument.getRange(); - assertEquals( range.getStartOffset(), 0 ); - assertEquals( range.getEndOffset(), 766 ); - - Paragraph lastInMainRange = range.getParagraph( range.numParagraphs() - 1); - assertTrue( lastInMainRange.getEndOffset() <= 766 ); - - Section section = range.getSection( 0 ); - assertTrue( section.getEndOffset() <= 766 ); - - Paragraph lastInMainSection = section.getParagraph( section - .numParagraphs() - 1); - assertTrue( lastInMainSection.getEndOffset() <= 766 ); - hwpfDocument.close(); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestRangeDelete.java b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestRangeDelete.java deleted file mode 100644 index bf52606d3..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestRangeDelete.java +++ /dev/null @@ -1,239 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.usermodel; - -import org.apache.poi.hwpf.HWPFDocument; -import org.apache.poi.hwpf.HWPFTestDataSamples; -import org.apache.poi.hwpf.model.PAPX; - -import junit.framework.TestCase; - -/** - * Test to see if Range.delete() works even if the Range contains a - * CharacterRun that uses Unicode characters. - */ -public final class TestRangeDelete extends TestCase { - - // u201c and u201d are "smart-quotes" - private final String introText = - "Introduction\r"; - private final String fillerText = - "${delete} This is an MS-Word 97 formatted document created using NeoOffice v. 2.2.4 Patch 0 (OpenOffice.org v. 2.2.1).\r"; - private final String originalText = - "It is used to confirm that text delete works even if Unicode characters (such as \u201c\u2014\u201d (U+2014), \u201c\u2e8e\u201d (U+2E8E), or \u201c\u2714\u201d (U+2714)) are present. Everybody should be thankful to the ${organization} ${delete} and all the POI contributors for their assistance in this matter.\r"; - private final String lastText = - "Thank you, ${organization} ${delete}!\r"; - private final String searchText = "${delete}"; - private final String expectedText1 = " This is an MS-Word 97 formatted document created using NeoOffice v. 2.2.4 Patch 0 (OpenOffice.org v. 2.2.1).\r"; - private final String expectedText2 = - "It is used to confirm that text delete works even if Unicode characters (such as \u201c\u2014\u201d (U+2014), \u201c\u2e8e\u201d (U+2E8E), or \u201c\u2714\u201d (U+2714)) are present. Everybody should be thankful to the ${organization} and all the POI contributors for their assistance in this matter.\r"; - private final String expectedText3 = "Thank you, ${organization} !\r"; - - private String illustrativeDocFile; - - @Override - protected void setUp() { - illustrativeDocFile = "testRangeDelete.doc"; - } - - /** - * Test just opening the files - */ - public void testOpen() { - - HWPFTestDataSamples.openSampleFile(illustrativeDocFile); - } - - /** - * Test (more "confirm" than test) that we have the general structure that we expect to have. - */ - public void testDocStructure() { - - HWPFDocument daDoc = HWPFTestDataSamples.openSampleFile(illustrativeDocFile); - Range range; - Section section; - Paragraph para; - PAPX paraDef; - - // First, check overall - range = daDoc.getOverallRange(); - assertEquals(1, range.numSections()); - assertEquals(5, range.numParagraphs()); - - - // Now, onto just the doc bit - range = daDoc.getRange(); - - assertEquals(1, range.numSections()); - assertEquals(1, daDoc.getSectionTable().getSections().size()); - section = range.getSection(0); - - assertEquals(5, section.numParagraphs()); - - para = section.getParagraph(0); - assertEquals(1, para.numCharacterRuns()); - assertEquals(introText, para.text()); - - para = section.getParagraph(1); - assertEquals(5, para.numCharacterRuns()); - assertEquals(fillerText, para.text()); - - - paraDef = daDoc.getParagraphTable().getParagraphs().get(2); - assertEquals(132, paraDef.getStart()); - assertEquals(400, paraDef.getEnd()); - - para = section.getParagraph(2); - assertEquals(5, para.numCharacterRuns()); - assertEquals(originalText, para.text()); - - - paraDef = daDoc.getParagraphTable().getParagraphs().get(3); - assertEquals(400, paraDef.getStart()); - assertEquals(438, paraDef.getEnd()); - - para = section.getParagraph(3); - assertEquals(1, para.numCharacterRuns()); - assertEquals(lastText, para.text()); - - - // Check things match on text length - assertEquals(439, range.text().length()); - assertEquals(439, section.text().length()); - assertEquals(439, - section.getParagraph(0).text().length() + - section.getParagraph(1).text().length() + - section.getParagraph(2).text().length() + - section.getParagraph(3).text().length() + - section.getParagraph(4).text().length() - ); - } - - /** - * Test that we can delete text (one instance) from our Range with Unicode text. - */ - public void testRangeDeleteOne() { - - HWPFDocument daDoc = HWPFTestDataSamples.openSampleFile(illustrativeDocFile); - - Range range = daDoc.getOverallRange(); - assertEquals(1, range.numSections()); - - Section section = range.getSection(0); - assertEquals(5, section.numParagraphs()); - - Paragraph para = section.getParagraph(2); - - String text = para.text(); - assertEquals(originalText, text); - - int offset = text.indexOf(searchText); - assertEquals(192, offset); - - int absOffset = para.getStartOffset() + offset; - Range subRange = new Range(absOffset, (absOffset + searchText.length()), para.getDocument()); - - assertEquals(searchText, subRange.text()); - - subRange.delete(); - daDoc.getOverallRange().sanityCheck(); - daDoc.getRange().sanityCheck(); - - // we need to let the model re-calculate the Range before we evaluate it - range = daDoc.getRange(); - - assertEquals(1, range.numSections()); - section = range.getSection(0); - - assertEquals(5, section.numParagraphs()); - para = section.getParagraph(2); - - text = para.text(); - assertEquals(expectedText2, text); - - // this can lead to a StringBufferOutOfBoundsException, so we will add it - // even though we don't have an assertion for it - Range daRange = daDoc.getRange(); - daRange.sanityCheck(); - daRange.text(); - } - - /** - * Test that we can delete text (all instances of) from our Range with Unicode text. - */ - public void testRangeDeleteAll() { - - HWPFDocument daDoc = HWPFTestDataSamples.openSampleFile(illustrativeDocFile); - - Range range = daDoc.getRange(); - assertEquals(1, range.numSections()); - - Section section = range.getSection(0); - assertEquals(5, section.numParagraphs()); - - Paragraph para = section.getParagraph(2); - - String text = para.text(); - assertEquals(originalText, text); - - boolean keepLooking = true; - while (keepLooking) { - // Reload the range every time - range = daDoc.getRange(); - int offset = range.text().indexOf(searchText); - if (offset >= 0) { - - int absOffset = range.getStartOffset() + offset; - - Range subRange = new Range( - absOffset, (absOffset + searchText.length()), range.getDocument()); - - assertEquals(searchText, subRange.text()); - - subRange.delete(); - - } else { - keepLooking = false; - } - } - - // we need to let the model re-calculate the Range before we use it - range = daDoc.getRange(); - - assertEquals(1, range.numSections()); - section = range.getSection(0); - - assertEquals(5, section.numParagraphs()); - - para = section.getParagraph(0); - text = para.text(); - assertEquals(introText, text); - - para = section.getParagraph(1); - text = para.text(); - assertEquals(expectedText1, text); - - para = section.getParagraph(2); - text = para.text(); - assertEquals(expectedText2, text); - - para = section.getParagraph(3); - text = para.text(); - assertEquals(expectedText3, text); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestRangeInsertion.java b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestRangeInsertion.java deleted file mode 100644 index 18ae0e7ac..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestRangeInsertion.java +++ /dev/null @@ -1,123 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.usermodel; - -import junit.framework.TestCase; - -import org.apache.poi.hwpf.HWPFDocument; -import org.apache.poi.hwpf.HWPFTestDataSamples; - -/** - * Test to see if Range.insertBefore() works even if the Range contains a - * CharacterRun that uses Unicode characters. - * - * TODO - re-enable me when unicode paragraph stuff is fixed! - */ -public final class TestRangeInsertion extends TestCase { - - // u201c and u201d are "smart-quotes" - private final String originalText = - "It is used to confirm that text insertion works even if Unicode characters (such as \u201c\u2014\u201d (U+2014), \u201c\u2e8e\u201d (U+2E8E), or \u201c\u2714\u201d (U+2714)) are present.\r"; - private final String textToInsert = "Look at me! I'm cool! "; - private final int insertionPoint = 122; - - private String illustrativeDocFile; - - @Override - protected void setUp() { - illustrativeDocFile = "testRangeInsertion.doc"; - } - - /** - * Test just opening the files - */ - public void testOpen() { - - HWPFTestDataSamples.openSampleFile(illustrativeDocFile); - } - - /** - * Test (more "confirm" than test) that we have the general structure that we expect to have. - */ - public void testDocStructure() { - - HWPFDocument daDoc = HWPFTestDataSamples.openSampleFile(illustrativeDocFile); - - Range range = daDoc.getRange(); - - assertEquals(1, range.numSections()); - Section section = range.getSection(0); - - assertEquals(3, section.numParagraphs()); - Paragraph para = section.getParagraph(2); - assertEquals(originalText, para.text()); - - assertEquals(3, para.numCharacterRuns()); - String text = - para.getCharacterRun(0).text() + - para.getCharacterRun(1).text() + - para.getCharacterRun(2).text() - ; - - assertEquals(originalText, text); - - assertEquals(insertionPoint, para.getStartOffset()); - } - - /** - * Test that we can insert text in our CharacterRun with Unicode text. - */ - public void testRangeInsertion() { - - HWPFDocument daDoc = HWPFTestDataSamples.openSampleFile(illustrativeDocFile); - -// if (false) { // TODO - delete or resurrect this code -// Range range = daDoc.getRange(); -// Section section = range.getSection(0); -// Paragraph para = section.getParagraph(2); -// String text = para.getCharacterRun(0).text() + para.getCharacterRun(1).text() + -// para.getCharacterRun(2).text(); -// -// System.out.println(text); -// } - - Range range = new Range(insertionPoint, (insertionPoint + 2), daDoc); - range.insertBefore(textToInsert); - - // we need to let the model re-calculate the Range before we evaluate it - range = daDoc.getRange(); - - assertEquals(1, range.numSections()); - Section section = range.getSection(0); - - assertEquals(3, section.numParagraphs()); - Paragraph para = section.getParagraph(2); - assertEquals((textToInsert + originalText), para.text()); - - assertEquals(3, para.numCharacterRuns()); - String text = - para.getCharacterRun(0).text() + - para.getCharacterRun(1).text() + - para.getCharacterRun(2).text() - ; - - // System.out.println(text); - - assertEquals((textToInsert + originalText), text); - } -} diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestRangeProperties.java b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestRangeProperties.java deleted file mode 100644 index 0865189a2..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestRangeProperties.java +++ /dev/null @@ -1,412 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hwpf.usermodel; - -import java.util.List; - -import junit.framework.TestCase; - -import org.apache.poi.hwpf.HWPFDocument; -import org.apache.poi.hwpf.HWPFTestDataSamples; -import org.apache.poi.hwpf.model.PAPX; -import org.apache.poi.hwpf.model.StyleSheet; - -/** - * Tests to ensure that our ranges end up with - * the right text in them, and the right font/styling - * properties applied to them. - */ -public final class TestRangeProperties extends TestCase { - private static final char page_break = (char)12; - - private static final String u_page_1 = - "This is a fairly simple word document, over two pages, with headers and footers.\r" + - "The trick with this one is that it contains some Unicode based strings in it.\r" + - "Firstly, some currency symbols:\r" + - "\tGBP - \u00a3\r" + - "\tEUR - \u20ac\r" + - "Now, we\u2019ll have some French text, in bold and big:\r" + - "\tMoli\u00e8re\r" + - "And some normal French text:\r" + - "\tL'Avare ou l'\u00c9cole du mensonge\r" + - "That\u2019s it for page one\r" - ; - private static final String u_page_2 = - "This is page two. Les Pr\u00e9cieuses ridicules. The end.\r" - ; - - private static final String a_page_1 = - "I am a test document\r" + - "This is page 1\r" + - "I am Calibri (Body) in font size 11\r" - ; - private static final String a_page_2 = - "This is page two\r" + - "It\u2019s Arial Black in 16 point\r" + - "It\u2019s also in blue\r" - ; - - private HWPFDocument u; - private HWPFDocument a; - - @Override - protected void setUp() { - u = HWPFTestDataSamples.openSampleFile("HeaderFooterUnicode.doc"); - a = HWPFTestDataSamples.openSampleFile("SampleDoc.doc"); - } - - - public void testAsciiTextParagraphs() { - Range r = a.getRange(); - assertEquals( - a_page_1 + - page_break + "\r" + - a_page_2, - r.text() - ); - - assertEquals(1, r.numSections()); - assertEquals(1, a.getSectionTable().getSections().size()); - Section s = r.getSection(0); - assertEquals( - a_page_1 + - page_break + "\r" + - a_page_2, - s.text() - ); - - // no PAP reconstruction - // assertEquals( 7, r.numParagraphs() ); - // with PAP reconstructon - assertEquals( 8, r.numParagraphs() ); - - String[] p1_parts = a_page_1.split("\r"); - String[] p2_parts = a_page_2.split("\r"); - - // Check paragraph contents - assertEquals( - p1_parts[0] + "\r", - r.getParagraph(0).text() - ); - assertEquals( - p1_parts[1] + "\r", - r.getParagraph(1).text() - ); - assertEquals( - p1_parts[2] + "\r", - r.getParagraph(2).text() - ); - - // no PAPX reconstruction - // assertEquals( page_break + "\r", r.getParagraph( 3 ).text() ); - // assertEquals( p2_parts[0] + "\r", r.getParagraph( 4 ).text() ); - // assertEquals( p2_parts[1] + "\r", r.getParagraph( 5 ).text() ); - // assertEquals( p2_parts[2] + "\r", r.getParagraph( 6 ).text() ); - - // with PAPX reconstruction - assertEquals( "" + page_break, r.getParagraph( 3 ).text() ); - assertEquals( "\r", r.getParagraph( 4 ).text() ); - assertEquals( p2_parts[0] + "\r", r.getParagraph( 5 ).text() ); - assertEquals( p2_parts[1] + "\r", r.getParagraph( 6 ).text() ); - assertEquals( p2_parts[2] + "\r", r.getParagraph( 7 ).text() ); - } - - public void testAsciiStyling() { - Range r = a.getRange(); - - Paragraph p1 = r.getParagraph(0); - Paragraph p7 = r.getParagraph(6); - - assertEquals(1, p1.numCharacterRuns()); - assertEquals(1, p7.numCharacterRuns()); - - CharacterRun c1 = p1.getCharacterRun(0); - CharacterRun c7 = p7.getCharacterRun(0); - - assertEquals("Times New Roman", c1.getFontName()); // No Calibri - assertEquals("Arial Black", c7.getFontName()); - assertEquals(22, c1.getFontSize()); - assertEquals(32, c7.getFontSize()); - - // This document has 15 styles - assertEquals(15, a.getStyleSheet().numStyles()); - - // Ensure none of the paragraphs refer to one that isn't there, - // and none of their character runs either - // Also check all use the default style - StyleSheet ss = a.getStyleSheet(); - for(int i=0; i pDefs = r._paragraphs; - // no PAPX reconstruction - // assertEquals(36, pDefs.size()); - // with PAPX reconstruction - assertEquals( 36, pDefs.size() ); - - // Check that the last paragraph ends where it should do - assertEquals(531, u.getOverallRange().text().length()); - PAPX pLast = pDefs.get(34); - // assertEquals(530, pLast.getEnd()); - - // Only care about the first few really though - PAPX p0 = pDefs.get(0); - PAPX p1 = pDefs.get(1); - PAPX p2 = pDefs.get(2); - PAPX p3 = pDefs.get(3); - PAPX p4 = pDefs.get(4); - - // 5 paragraphs should get us to the end of our text - assertTrue(p0.getStart() < 408); - assertTrue(p0.getEnd() < 408); - assertTrue(p1.getStart() < 408); - assertTrue(p1.getEnd() < 408); - assertTrue(p2.getStart() < 408); - assertTrue(p2.getEnd() < 408); - assertTrue(p3.getStart() < 408); - assertTrue(p3.getEnd() < 408); - assertTrue(p4.getStart() < 408); - assertTrue(p4.getEnd() < 408); - - // Paragraphs should match with lines - assertEquals( - 0, - p0.getStart() - ); - assertEquals( - p1_parts[0].length() + 1, - p0.getEnd() - ); - - assertEquals( - p1_parts[0].length() + 1, - p1.getStart() - ); - assertEquals( - p1_parts[0].length() + 1 + - p1_parts[1].length() + 1, - p1.getEnd() - ); - - assertEquals( - p1_parts[0].length() + 1 + - p1_parts[1].length() + 1, - p2.getStart() - ); - assertEquals( - p1_parts[0].length() + 1 + - p1_parts[1].length() + 1 + - p1_parts[2].length() + 1, - p2.getEnd() - ); - } - - /** - * Tests the paragraph text of a unicode document - */ - public void testUnicodeTextParagraphs() { - Range r = u.getRange(); - assertEquals( - u_page_1 + - page_break + "\r" + - u_page_2, - r.text() - ); - - // without PAPX reconstruction - // assertEquals( 12, r.numParagraphs() ); - // with PAPX reconstruction - assertEquals( 13, r.numParagraphs() ); - String[] p1_parts = u_page_1.split("\r"); - String[] p2_parts = u_page_2.split("\r"); - - // Check text all matches up properly - assertEquals(p1_parts[0] + "\r", r.getParagraph(0).text()); - assertEquals(p1_parts[1] + "\r", r.getParagraph(1).text()); - assertEquals(p1_parts[2] + "\r", r.getParagraph(2).text()); - assertEquals(p1_parts[3] + "\r", r.getParagraph(3).text()); - assertEquals(p1_parts[4] + "\r", r.getParagraph(4).text()); - assertEquals(p1_parts[5] + "\r", r.getParagraph(5).text()); - assertEquals(p1_parts[6] + "\r", r.getParagraph(6).text()); - assertEquals(p1_parts[7] + "\r", r.getParagraph(7).text()); - assertEquals(p1_parts[8] + "\r", r.getParagraph(8).text()); - assertEquals(p1_parts[9] + "\r", r.getParagraph(9).text()); - // without PAPX reconstruction - // assertEquals(page_break + "\r", r.getParagraph(10).text()); - // assertEquals(p2_parts[0] + "\r", r.getParagraph(11).text()); - // with PAPX reconstruction - assertEquals( page_break + "", r.getParagraph( 10 ).text() ); - assertEquals( "\r", r.getParagraph( 11 ).text() ); - assertEquals( p2_parts[0] + "\r", r.getParagraph( 12 ).text() ); - } - public void testUnicodeStyling() { - Range r = u.getRange(); - String[] p1_parts = u_page_1.split("\r"); - - Paragraph p1 = r.getParagraph(0); - Paragraph p7 = r.getParagraph(6); - StyleSheet ss = r._doc.getStyleSheet(); - - // Line ending in its own run each time! - assertEquals(2, p1.numCharacterRuns()); - assertEquals(2, p7.numCharacterRuns()); - - CharacterRun c1a = p1.getCharacterRun(0); - CharacterRun c1b = p1.getCharacterRun(1); - CharacterRun c7a = p7.getCharacterRun(0); - CharacterRun c7b = p7.getCharacterRun(1); - - assertEquals("Times New Roman", c1a.getFontName()); // No Calibri - assertEquals(22, c1a.getFontSize()); - - assertEquals("Times New Roman", c1b.getFontName()); // No Calibri - assertEquals(22, c1b.getFontSize()); - - assertEquals("Times New Roman", c7a.getFontName()); - assertEquals(48, c7a.getFontSize()); - - assertEquals("Times New Roman", c7b.getFontName()); - assertEquals(48, c7b.getFontSize()); - - // All use the default base style - assertEquals("Normal", ss.getStyleDescription(c1a.getStyleIndex()).getName()); - assertEquals("Normal", ss.getStyleDescription(c1b.getStyleIndex()).getName()); - assertEquals("Heading 1", ss.getStyleDescription(c7a.getStyleIndex()).getName()); - assertEquals("Heading 1", ss.getStyleDescription(c7b.getStyleIndex()).getName()); - - // Now check where they crop up - assertEquals( - 0, - c1a.getStartOffset() - ); - assertEquals( - p1_parts[0].length(), - c1a.getEndOffset() - ); - - assertEquals( - p1_parts[0].length(), - c1b.getStartOffset() - ); - assertEquals( - p1_parts[0].length()+1, - c1b.getEndOffset() - ); - - assertEquals( - p1_parts[0].length() + 1 + - p1_parts[1].length() + 1 + - p1_parts[2].length() + 1 + - p1_parts[3].length() + 1 + - p1_parts[4].length() + 1 + - p1_parts[5].length() + 1, - c7a.getStartOffset() - ); - assertEquals( - p1_parts[0].length() + 1 + - p1_parts[1].length() + 1 + - p1_parts[2].length() + 1 + - p1_parts[3].length() + 1 + - p1_parts[4].length() + 1 + - p1_parts[5].length() + 1 + - 1, - c7a.getEndOffset() - ); - - assertEquals( - p1_parts[0].length() + 1 + - p1_parts[1].length() + 1 + - p1_parts[2].length() + 1 + - p1_parts[3].length() + 1 + - p1_parts[4].length() + 1 + - p1_parts[5].length() + 1 + - 1, - c7b.getStartOffset() - ); - assertEquals( - p1_parts[0].length() + 1 + - p1_parts[1].length() + 1 + - p1_parts[2].length() + 1 + - p1_parts[3].length() + 1 + - p1_parts[4].length() + 1 + - p1_parts[5].length() + 1 + - p1_parts[6].length() + 1, - c7b.getEndOffset() - ); - - // This document also has 22 styles - assertEquals(22, ss.numStyles()); - - // Ensure none of the paragraphs refer to one that isn't there, - // and none of their character runs either - for(int i=0; i= 2); - CharacterRun chr = range.getCharacterRun(0); - assertEquals(false, chr.isSymbol()); - - chr = range.getCharacterRun(1); - assertEquals(true, chr.isSymbol()); - assertEquals("\u0028", chr.text()); - assertEquals("Wingdings", chr.getSymbolFont().getMainFontName()); - assertEquals(0xf028, chr.getSymbolCharacter()); - } - -} \ No newline at end of file diff --git a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestTableRow.java b/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestTableRow.java deleted file mode 100644 index 9c1127a12..000000000 --- a/src/scratchpad/testcases/org/apache/poi/hwpf/usermodel/TestTableRow.java +++ /dev/null @@ -1,69 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hwpf.usermodel; - -import static org.junit.Assert.assertEquals; - -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hwpf.HWPFDocument; -import org.junit.Test; - -public class TestTableRow { - private static final POIDataSamples SAMPLES = POIDataSamples.getDocumentInstance(); - - @Test - public void testInnerTableCellsDetection() throws IOException { - InputStream is = SAMPLES.openResourceAsStream( "innertable.doc" ); - HWPFDocument hwpfDocument = new HWPFDocument( is ); - is.close(); - hwpfDocument.getRange(); - - Range documentRange = hwpfDocument.getRange(); - Paragraph startOfInnerTable = documentRange.getParagraph( 6 ); - - Table innerTable = documentRange.getTable( startOfInnerTable ); - assertEquals( 2, innerTable.numRows() ); - - TableRow tableRow = innerTable.getRow( 0 ); - assertEquals( 2, tableRow.numCells() ); - hwpfDocument.close(); - } - - @Test - public void testOuterTableCellsDetection() throws IOException { - InputStream is = SAMPLES.openResourceAsStream( "innertable.doc" ); - HWPFDocument hwpfDocument = new HWPFDocument( is ); - is.close(); - hwpfDocument.getRange(); - - Range documentRange = hwpfDocument.getRange(); - Paragraph startOfOuterTable = documentRange.getParagraph( 0 ); - - Table outerTable = documentRange.getTable( startOfOuterTable ); - assertEquals( 3, outerTable.numRows() ); - - assertEquals( 3, outerTable.getRow( 0 ).numCells() ); - assertEquals( 3, outerTable.getRow( 1 ).numCells() ); - assertEquals( 3, outerTable.getRow( 2 ).numCells() ); - - hwpfDocument.close(); - } - -} diff --git a/src/testcases/org/apache/poi/AllPOITests.java b/src/testcases/org/apache/poi/AllPOITests.java deleted file mode 100644 index 0fba8f828..000000000 --- a/src/testcases/org/apache/poi/AllPOITests.java +++ /dev/null @@ -1,40 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi; - -import org.apache.poi.ddf.AllPOIDDFTests; -import org.apache.poi.hpsf.basic.AllPOIHPSFBasicTests; -import org.apache.poi.hssf.HSSFTests; -import org.apache.poi.poifs.AllPOIFSTests; -import org.apache.poi.util.AllPOIUtilTests; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -/** - * Root Test Suite for entire POI project. (Includes all sub-packages of org.apache.poi)
    - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestPOIDocumentMain.class, - AllPOIDDFTests.class, - AllPOIHPSFBasicTests.class, - HSSFTests.class, - AllPOIFSTests.class, - AllPOIUtilTests.class -}) -public final class AllPOITests { -} diff --git a/src/testcases/org/apache/poi/POIDataSamples.java b/src/testcases/org/apache/poi/POIDataSamples.java deleted file mode 100644 index f57d13dae..000000000 --- a/src/testcases/org/apache/poi/POIDataSamples.java +++ /dev/null @@ -1,281 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; - -/** - * Centralises logic for finding/opening sample files - */ -public final class POIDataSamples { - - /** - * Name of the system property that defined path to the test data. - */ - public static final String TEST_PROPERTY = "POI.testdata.path"; - - private static POIDataSamples _instSlideshow; - private static POIDataSamples _instSpreadsheet; - private static POIDataSamples _instDocument; - private static POIDataSamples _instDiagram; - private static POIDataSamples _instOpenxml4j; - private static POIDataSamples _instPOIFS; - private static POIDataSamples _instDDF; - private static POIDataSamples _instHMEF; - private static POIDataSamples _instHPSF; - private static POIDataSamples _instHPBF; - private static POIDataSamples _instHSMF; - private static POIDataSamples _instXmlDSign; - - private File _resolvedDataDir; - /** true if standard system propery is not set, - * but the data is available on the test runtime classpath */ - private boolean _sampleDataIsAvaliableOnClassPath; - private final String _moduleDir; - - /** - * - * @param moduleDir the name of the directory containing the test files - */ - private POIDataSamples(String moduleDir){ - _moduleDir = moduleDir; - initialise(); - } - - public static POIDataSamples getSpreadSheetInstance(){ - if(_instSpreadsheet == null) _instSpreadsheet = new POIDataSamples("spreadsheet"); - return _instSpreadsheet; - } - - public static POIDataSamples getDocumentInstance(){ - if(_instDocument == null) _instDocument = new POIDataSamples("document"); - return _instDocument; - } - - public static POIDataSamples getSlideShowInstance(){ - if(_instSlideshow == null) _instSlideshow = new POIDataSamples("slideshow"); - return _instSlideshow; - } - - public static POIDataSamples getDiagramInstance(){ - if(_instOpenxml4j == null) _instOpenxml4j = new POIDataSamples("diagram"); - return _instOpenxml4j; - } - - public static POIDataSamples getOpenXML4JInstance(){ - if(_instDiagram == null) _instDiagram = new POIDataSamples("openxml4j"); - return _instDiagram; - } - - public static POIDataSamples getPOIFSInstance(){ - if(_instPOIFS == null) _instPOIFS = new POIDataSamples("poifs"); - return _instPOIFS; - } - - public static POIDataSamples getDDFInstance(){ - if(_instDDF == null) _instDDF = new POIDataSamples("ddf"); - return _instDDF; - } - - public static POIDataSamples getHPSFInstance(){ - if(_instHPSF == null) _instHPSF = new POIDataSamples("hpsf"); - return _instHPSF; - } - - public static POIDataSamples getPublisherInstance(){ - if(_instHPBF == null) _instHPBF = new POIDataSamples("publisher"); - return _instHPBF; - } - - public static POIDataSamples getHMEFInstance(){ - if(_instHMEF == null) _instHMEF = new POIDataSamples("hmef"); - return _instHMEF; - } - - public static POIDataSamples getHSMFInstance(){ - if(_instHSMF == null) _instHSMF = new POIDataSamples("hsmf"); - return _instHSMF; - } - - public static POIDataSamples getXmlDSignInstance(){ - if(_instXmlDSign == null) _instXmlDSign = new POIDataSamples("xmldsign"); - return _instXmlDSign; - } - - /** - * Opens a sample file from the test data directory - * - * @param sampleFileName the file to open - * @return an open InputStream for the specified sample file - */ - public InputStream openResourceAsStream(String sampleFileName) { - - if (_sampleDataIsAvaliableOnClassPath) { - InputStream result = sampleFileName == null ? null : - openClasspathResource(sampleFileName); - if(result == null) { - throw new RuntimeException("specified test sample file '" + sampleFileName - + "' not found on the classpath"); - } - // wrap to avoid temp warning method about auto-closing input stream - return new NonSeekableInputStream(result); - } - if (_resolvedDataDir == null) { - throw new RuntimeException("Must set system property '" - + TEST_PROPERTY - + "' properly before running tests"); - } - - File f = getFile(sampleFileName); - try { - return new FileInputStream(f); - } catch (FileNotFoundException e) { - throw new RuntimeException(e); - } - } - - /** - * - * @param sampleFileName the name of the test file - * @return - * @throws RuntimeException if the file was not found - */ - public File getFile(String sampleFileName) { - File f = new File(_resolvedDataDir, sampleFileName); - if (!f.exists()) { - throw new RuntimeException("Sample file '" + sampleFileName - + "' not found in data dir '" + _resolvedDataDir.getAbsolutePath() + "'"); - } - try { - if(sampleFileName.length() > 0) { - String fn = sampleFileName; - if(fn.indexOf('/') > 0) { - fn = fn.substring(fn.indexOf('/')+1); - } - if(!fn.equals(f.getCanonicalFile().getName())){ - throw new RuntimeException("File name is case-sensitive: requested '" + fn - + "' but actual file is '" + f.getCanonicalFile().getName() + "'"); - } - } - } catch (IOException e){ - throw new RuntimeException(e); - } - return f; - } - - private void initialise() { - String dataDirName = System.getProperty(TEST_PROPERTY); - if (dataDirName == null) { - // check to see if we can just get the resources from the classpath - InputStream is = openClasspathResource(""); - if (is != null) { - try { - is.close(); // be nice - } catch (IOException e) { - throw new RuntimeException(e); - } - _sampleDataIsAvaliableOnClassPath = true; - return; - } - - if(new File("test-data").exists()) { - dataDirName = "test-data"; - } else { - throw new RuntimeException("Must set system property '" + - TEST_PROPERTY + "' before running tests"); - } - } - File dataDir = new File(dataDirName, _moduleDir); - if (!dataDir.exists()) { - throw new RuntimeException("Data dir '" + _moduleDir + " does not exist"); - } - // convert to canonical file, to make any subsequent error messages - // clearer. - try { - _resolvedDataDir = dataDir.getCanonicalFile(); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - /** - * Opens a test sample file from the 'data' sub-package of this class's package. - * - * @param sampleFileName the file to open - * @return null if the sample file is not deployed on the classpath. - */ - private InputStream openClasspathResource(String sampleFileName) { - return getClass().getResourceAsStream("/" + _moduleDir + "/" + sampleFileName); - } - - private static final class NonSeekableInputStream extends InputStream { - - private final InputStream _is; - - public NonSeekableInputStream(InputStream is) { - _is = is; - } - - @Override - public int read() throws IOException { - return _is.read(); - } - @Override - public int read(byte[] b, int off, int len) throws IOException { - return _is.read(b, off, len); - } - @Override - public boolean markSupported() { - return false; - } - @Override - public void close() throws IOException { - _is.close(); - } - } - - /** - * @param fileName the file to open - * @return byte array of sample file content from file found in standard test-data directory - */ - public byte[] readFile(String fileName) { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - - try { - InputStream fis = openResourceAsStream(fileName); - - byte[] buf = new byte[512]; - while (true) { - int bytesRead = fis.read(buf); - if (bytesRead < 1) { - break; - } - bos.write(buf, 0, bytesRead); - } - fis.close(); - } catch (IOException e) { - throw new RuntimeException(e); - } - return bos.toByteArray(); - } - -} diff --git a/src/testcases/org/apache/poi/POITestCase.java b/src/testcases/org/apache/poi/POITestCase.java deleted file mode 100644 index 3664da686..000000000 --- a/src/testcases/org/apache/poi/POITestCase.java +++ /dev/null @@ -1,257 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.junit.Assume.assumeTrue; - -import java.lang.reflect.AccessibleObject; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.security.AccessController; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import org.apache.poi.util.SuppressForbidden; -import org.apache.poi.util.Internal; - -/** - * Util class for POI JUnit TestCases, which provide additional features - */ -@Internal -public final class POITestCase { - public static void assertStartsWith(String string, String prefix) { - assertNotNull(string); - assertNotNull(prefix); - - final int len = Math.min(string.length(), prefix.length()); - assertEquals("string does not start with prefix", prefix, string.substring(0, len)); - } - - public static void assertContains(String haystack, String needle) { - assertNotNull(haystack); - assertTrue( - "Unable to find expected text '" + needle + "' in text:\n" + haystack, - haystack.contains(needle) - ); - } - - public static void assertContainsIgnoreCase(String haystack, String needle, Locale locale) { - assertNotNull(haystack); - assertNotNull(needle); - String hay = haystack.toLowerCase(locale); - String n = needle.toLowerCase(locale); - assertTrue("Unable to find expected text '" + needle + "' in text:\n" + haystack, - hay.contains(n) - ); - } - public static void assertContainsIgnoreCase(String haystack, String needle) { - assertContainsIgnoreCase(haystack, needle, Locale.ROOT); - } - - public static void assertNotContained(String haystack, String needle) { - assertNotNull(haystack); - assertFalse( - "Unexpectedly found text '" + needle + "' in text:\n" + haystack, - haystack.contains(needle) - ); - } - - /** - * @param map haystack - * @param key needle - */ - public static void assertContains(Map map, T key) { - if (map.containsKey(key)) { - return; - } - fail("Unable to find " + key + " in " + map); - } - - /** - * Utility method to get the value of a private/protected field. - * Only use this method in test cases!!! - */ - public static R getFieldValue(final Class clazz, final T instance, final Class fieldType, final String fieldName) { - assertTrue("Reflection of private fields is only allowed for POI classes.", clazz.getName().startsWith("org.apache.poi.")); - try { - return AccessController.doPrivileged(new PrivilegedExceptionAction() { - @Override - @SuppressWarnings("unchecked") - @SuppressForbidden("For test usage only") - public R run() throws Exception { - Field f = clazz.getDeclaredField(fieldName); - f.setAccessible(true); - return (R) f.get(instance); - } - }); - } catch (PrivilegedActionException pae) { - throw new RuntimeException("Cannot access field '" + fieldName + "' of class " + clazz, pae.getException()); - } - } - - /** - * Utility method to call a private/protected method. - * Only use this method in test cases!!! - */ - public static R callMethod(final Class clazz, final T instance, final Class returnType, final String methodName, - final Class[] parameterTypes, final Object[] parameters) { - assertTrue("Reflection of private methods is only allowed for POI classes.", clazz.getName().startsWith("org.apache.poi.")); - try { - return AccessController.doPrivileged(new PrivilegedExceptionAction() { - @Override - @SuppressWarnings("unchecked") - @SuppressForbidden("For test usage only") - public R run() throws Exception { - Method m = clazz.getDeclaredMethod(methodName, parameterTypes); - m.setAccessible(true); - return (R) m.invoke(instance, parameters); - } - }); - } catch (PrivilegedActionException pae) { - throw new RuntimeException("Cannot access method '" + methodName + "' of class " + clazz, pae.getException()); - } - } - - /** - * Utility method to shallow compare all fields of the objects - * Only use this method in test cases!!! - */ - public static void assertReflectEquals(final Object expected, Object actual) throws Exception { - final List fields; - try { - fields = AccessController.doPrivileged(new PrivilegedExceptionAction>() { - @Override - @SuppressForbidden("Test only") - public List run() throws Exception { - List flds = new ArrayList(); - for (Class c = expected.getClass(); c != null; c = c.getSuperclass()) { - Field[] fs = c.getDeclaredFields(); - AccessibleObject.setAccessible(fs, true); - for (Field f : fs) { - // JaCoCo Code Coverage adds it's own field, don't look at this one here - if(f.getName().equals("$jacocoData")) { - continue; - } - - flds.add(f); - } - } - return flds; - } - }); - } catch (PrivilegedActionException pae) { - throw pae.getException(); - } - - for (Field f : fields) { - Class t = f.getType(); - if (t.isArray()) { - if (Object[].class.isAssignableFrom(t)) { - assertArrayEquals((Object[])f.get(expected), (Object[])f.get(actual)); - } else if (byte[].class.isAssignableFrom(t)) { - assertArrayEquals((byte[])f.get(expected), (byte[])f.get(actual)); - } else { - fail("Array type is not yet implemented ... add it!"); - } - } else { - assertEquals(f.get(expected), f.get(actual)); - } - } - } - - /** - * Rather than adding {@literal @}Ignore to known-failing tests, - * write the test so that it notifies us if it starts passing. - * This is useful for closing related or forgotten bugs. - * - * An Example: - *
    -     * public static int add(int a, int b) {
    -     *     // a known bug in behavior that has not been fixed yet
    -     *     raise UnsupportedOperationException("add");
    -     * }
    -     * 
    -     * {@literal @}Test
    -     * public void knownFailingUnitTest() {
    -     *     try {
    -     *         assertEquals(2, add(1,1));
    -     *         // this test fails because the assumption that this bug had not been fixed is false
    -     *         testPassesNow(12345);
    -     *     } catch (UnsupportedOperationException e) {
    -     *         // test is skipped because the assumption that this bug had not been fixed is true
    -     *         skipTest(e);
    -     *     }
    -     * }
    -     * 
    -     * Once passing, this unit test can be rewritten as:
    -     * {@literal @}Test
    -     * public void knownPassingUnitTest() {
    -     *     assertEquals(2, add(1,1));
    -     * }
    -     * 
    -     * If you have a better idea how to simplify test code while still notifying
    -     * us when a previous known-failing test now passes, please improve these.
    -     * As a bonus, a known-failing test that fails should not be counted as a
    -     * passing test.
    -     * 
    -     * One possible alternative is to expect the known exception, but without
    -     * a clear message that it is a good thing to no longer get the expected
    -     * exception once the test passes.
    -     * {@literal @}Test(expected=UnsupportedOperationException.class)
    -     * public void knownFailingUnitTest() {
    -     *     assertEquals(2, add(1,1));
    -     * }
    -     *
    -     * @param e  the exception that was caught that will no longer
    -     * be raised when the bug is fixed 
    -     */
    -    public static void skipTest(Throwable e) {
    -        assumeTrue("This test currently fails with " + e, false);
    -    }
    -    /**
    -     * @see #skipTest(Throwable)
    -     *
    -     * @param bug  the bug number corresponding to a known bug in bugzilla
    -     */
    -    public static void testPassesNow(int bug) {
    -        fail("This test passes now. Please update the unit test and bug " + bug + ".");
    -    }
    -    
    -    public static void assertBetween(String message, int value, int min, int max) {
    -        assertTrue(message + ": " + value + " is less than the minimum value of " + min,
    -                min <= value);
    -        assertTrue(message + ": " + value + " is greater than the maximum value of " + max,
    -                value <= max);
    -    }
    -    public static void assertStrictlyBetween(String message, int value, int min, int max) {
    -        assertTrue(message + ": " + value + " is less than or equal to the minimum value of " + min,
    -                min < value);
    -        assertTrue(message + ": " + value + " is greater than or equal to the maximum value of " + max,
    -                value < max);
    -    }
    -}
    diff --git a/src/testcases/org/apache/poi/TestPOIDocumentMain.java b/src/testcases/org/apache/poi/TestPOIDocumentMain.java
    deleted file mode 100644
    index 3c06fd346..000000000
    --- a/src/testcases/org/apache/poi/TestPOIDocumentMain.java
    +++ /dev/null
    @@ -1,199 +0,0 @@
    -/* ====================================================================
    -   Licensed to the Apache Software Foundation (ASF) under one or more
    -   contributor license agreements.  See the NOTICE file distributed with
    -   this work for additional information regarding copyright ownership.
    -   The ASF licenses this file to You under the Apache License, Version 2.0
    -   (the "License"); you may not use this file except in compliance with
    -   the License.  You may obtain a copy of the License at
    -
    -       http://www.apache.org/licenses/LICENSE-2.0
    -
    -   Unless required by applicable law or agreed to in writing, software
    -   distributed under the License is distributed on an "AS IS" BASIS,
    -   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    -   See the License for the specific language governing permissions and
    -   limitations under the License.
    -==================================================================== */
    -
    -package org.apache.poi;
    -
    -import static org.junit.Assert.assertEquals;
    -import static org.junit.Assert.assertNotNull;
    -import static org.junit.Assert.assertNull;
    -
    -import java.io.ByteArrayInputStream;
    -import java.io.ByteArrayOutputStream;
    -import java.io.IOException;
    -
    -import org.apache.poi.hpsf.HPSFPropertiesOnlyDocument;
    -import org.apache.poi.hssf.HSSFTestDataSamples;
    -import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    -import org.apache.poi.poifs.filesystem.NPOIFSFileSystem;
    -import org.apache.poi.poifs.filesystem.OPOIFSFileSystem;
    -import org.junit.Before;
    -import org.junit.Test;
    -
    -/**
    - * Tests that POIDocument correctly loads and saves the common
    - *  (hspf) Document Properties.
    - *
    - * This is part 1 of 2 of the tests - it only does the POIDocuments
    - *  which are part of the Main (not scratchpad)
    - */
    -public final class TestPOIDocumentMain {
    -    // The POI Documents to work on
    -    private POIDocument doc;
    -    private POIDocument doc2;
    -
    -    /**
    -     * Set things up, two spreadsheets for our testing
    -     */
    -    @Before
    -    public void setUp() {
    -        doc = HSSFTestDataSamples.openSampleWorkbook("DateFormats.xls");
    -        doc2 = HSSFTestDataSamples.openSampleWorkbook("StringFormulas.xls");
    -    }
    -
    -    @Test
    -    public void readProperties() {
    -        readPropertiesHelper(doc);
    -    }
    -
    -    private void readPropertiesHelper(POIDocument docWB) {
    -        // We should have both sets
    -        assertNotNull(docWB.getDocumentSummaryInformation());
    -        assertNotNull(docWB.getSummaryInformation());
    -
    -        // Check they are as expected for the test doc
    -        assertEquals("Administrator", docWB.getSummaryInformation().getAuthor());
    -        assertEquals(0, docWB.getDocumentSummaryInformation().getByteCount());
    -    }
    -
    -    @Test
    -    public void readProperties2() {
    -        // Check again on the word one
    -        assertNotNull(doc2.getDocumentSummaryInformation());
    -        assertNotNull(doc2.getSummaryInformation());
    -
    -        assertEquals("Avik Sengupta", doc2.getSummaryInformation().getAuthor());
    -        assertEquals(null, doc2.getSummaryInformation().getKeywords());
    -        assertEquals(0, doc2.getDocumentSummaryInformation().getByteCount());
    -    }
    -
    -    @Test
    -    public void writeProperties() throws IOException {
    -        // Just check we can write them back out into a filesystem
    -        NPOIFSFileSystem outFS = new NPOIFSFileSystem();
    -        doc.readProperties();
    -        doc.writeProperties(outFS);
    -
    -        // Should now hold them
    -        assertNotNull(
    -                outFS.createDocumentInputStream("\005SummaryInformation")
    -        );
    -        assertNotNull(
    -                outFS.createDocumentInputStream("\005DocumentSummaryInformation")
    -        );
    -    }
    -
    -    @Test
    -    public void WriteReadProperties() throws IOException {
    -        ByteArrayOutputStream baos = new ByteArrayOutputStream();
    -
    -        // Write them out
    -        NPOIFSFileSystem outFS = new NPOIFSFileSystem();
    -        doc.readProperties();
    -        doc.writeProperties(outFS);
    -        outFS.writeFilesystem(baos);
    -
    -        // Create a new version
    -        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    -        OPOIFSFileSystem inFS = new OPOIFSFileSystem(bais);
    -
    -        // Check they're still there
    -        POIDocument doc3 = new HPSFPropertiesOnlyDocument(inFS);
    -        doc3.readProperties();
    -        
    -        // Delegate test
    -        readPropertiesHelper(doc3);
    -        doc3.close();
    -    }
    -
    -    @Test
    -    public void createNewProperties() throws IOException {
    -        POIDocument doc = new HSSFWorkbook();
    -
    -        // New document won't have them
    -        assertNull(doc.getSummaryInformation());
    -        assertNull(doc.getDocumentSummaryInformation());
    -
    -        // Add them in
    -        doc.createInformationProperties();
    -        assertNotNull(doc.getSummaryInformation());
    -        assertNotNull(doc.getDocumentSummaryInformation());
    -
    -        // Write out and back in again, no change
    -        ByteArrayOutputStream baos = new ByteArrayOutputStream();
    -        doc.write(baos);
    -        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    -
    -        ((HSSFWorkbook)doc).close();
    -
    -        doc = new HSSFWorkbook(bais);
    -
    -        assertNotNull(doc.getSummaryInformation());
    -        assertNotNull(doc.getDocumentSummaryInformation());
    -        
    -        ((HSSFWorkbook)doc).close();
    -    }
    -
    -    @Test
    -    public void createNewPropertiesOnExistingFile() throws IOException {
    -        POIDocument doc = new HSSFWorkbook();
    -
    -        // New document won't have them
    -        assertNull(doc.getSummaryInformation());
    -        assertNull(doc.getDocumentSummaryInformation());
    -
    -        // Write out and back in again, no change
    -        ByteArrayOutputStream baos = new ByteArrayOutputStream();
    -        doc.write(baos);
    -        
    -        ((HSSFWorkbook)doc).close();
    -        
    -        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    -        doc = new HSSFWorkbook(bais);
    -
    -        assertNull(doc.getSummaryInformation());
    -        assertNull(doc.getDocumentSummaryInformation());
    -
    -        // Create, and change
    -        doc.createInformationProperties();
    -        doc.getSummaryInformation().setAuthor("POI Testing");
    -        doc.getDocumentSummaryInformation().setCompany("ASF");
    -
    -        // Save and re-load
    -        baos = new ByteArrayOutputStream();
    -        doc.write(baos);
    -        
    -        ((HSSFWorkbook)doc).close();
    -
    -        bais = new ByteArrayInputStream(baos.toByteArray());
    -        doc = new HSSFWorkbook(bais);
    -
    -        // Check
    -        assertNotNull(doc.getSummaryInformation());
    -        assertNotNull(doc.getDocumentSummaryInformation());
    -        assertEquals("POI Testing", doc.getSummaryInformation().getAuthor());
    -        assertEquals("ASF", doc.getDocumentSummaryInformation().getCompany());
    -
    -        // Asking to re-create will make no difference now
    -        doc.createInformationProperties();
    -        assertNotNull(doc.getSummaryInformation());
    -        assertNotNull(doc.getDocumentSummaryInformation());
    -        assertEquals("POI Testing", doc.getSummaryInformation().getAuthor());
    -        assertEquals("ASF", doc.getDocumentSummaryInformation().getCompany());
    -
    -        ((HSSFWorkbook)doc).close();
    -    }
    -}
    diff --git a/src/testcases/org/apache/poi/TestPOITestCase.java b/src/testcases/org/apache/poi/TestPOITestCase.java
    deleted file mode 100644
    index 314009604..000000000
    --- a/src/testcases/org/apache/poi/TestPOITestCase.java
    +++ /dev/null
    @@ -1,133 +0,0 @@
    -/* ====================================================================
    -   Licensed to the Apache Software Foundation (ASF) under one or more
    -   contributor license agreements.  See the NOTICE file distributed with
    -   this work for additional information regarding copyright ownership.
    -   The ASF licenses this file to You under the Apache License, Version 2.0
    -   (the "License"); you may not use this file except in compliance with
    -   the License.  You may obtain a copy of the License at
    -
    -       http://www.apache.org/licenses/LICENSE-2.0
    -
    -   Unless required by applicable law or agreed to in writing, software
    -   distributed under the License is distributed on an "AS IS" BASIS,
    -   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    -   See the License for the specific language governing permissions and
    -   limitations under the License.
    -==================================================================== */
    -
    -package org.apache.poi;
    -
    -import static org.junit.Assert.assertEquals;
    -import static org.junit.Assert.assertTrue;
    -import static org.junit.Assert.fail;
    -
    -import java.util.Collections;
    -import java.util.Locale;
    -import java.util.Map;
    -
    -import org.apache.poi.POITestCase;
    -import org.junit.Ignore;
    -import org.junit.Test;
    -
    -/**
    - * A class for testing the POI Junit TestCase utility class
    - */
    -public final class TestPOITestCase {
    -    @Test
    -    public void assertStartsWith() {
    -        POITestCase.assertStartsWith("Apache POI", "");
    -        POITestCase.assertStartsWith("Apache POI", "Apache");
    -        POITestCase.assertStartsWith("Apache POI", "Apache POI");
    -    }
    -    
    -    @Test
    -    public void assertContains() {
    -        POITestCase.assertContains("There is a needle in this haystack", "needle");
    -        /*try {
    -            POITestCase.assertContains("There is gold in this haystack", "needle");
    -            fail("found a needle");
    -        } catch (final junit.framework.AssertionFailedError e) {
    -            // expected
    -        }*/
    -    }
    -
    -    @Test
    -    public void assertContainsIgnoreCase_Locale() {
    -        POITestCase.assertContainsIgnoreCase("There is a Needle in this haystack", "needlE", Locale.ROOT);
    -        // FIXME: test failing case
    -    }
    -
    -    @Test
    -    public void assertContainsIgnoreCase() {
    -        POITestCase.assertContainsIgnoreCase("There is a Needle in this haystack", "needlE");
    -        // FIXME: test failing case
    -    }
    -
    -    @Test
    -    public void assertNotContained() {
    -        POITestCase.assertNotContained("There is a needle in this haystack", "gold");
    -        // FIXME: test failing case
    -    }
    -
    -    @Test
    -    public void assertMapContains() {
    -        Map haystack = Collections.singletonMap("needle", "value");
    -        POITestCase.assertContains(haystack, "needle");
    -        // FIXME: test failing case
    -    }
    -
    -     
    -    /**
    -     * Utility method to get the value of a private/protected field.
    -     * Only use this method in test cases!!!
    -     */
    -    @Ignore
    -    @Test
    -    public void getFieldValue() {
    -        /*
    -        final Class clazz;
    -        final T instance;
    -        final Class fieldType;
    -        final String fieldName;
    -
    -        final R expected;
    -        final R actual = POITestCase.getFieldValue(clazz, instance, fieldType, fieldName);
    -        assertEquals(expected, actual);
    -        */
    -    }
    -     
    -    /**
    -     * Utility method to call a private/protected method.
    -     * Only use this method in test cases!!!
    -     */
    -    @Ignore
    -    @Test
    -    public void callMethod() {
    -        /*
    -        final Class clazz;
    -        final T instance;
    -        final Class returnType;
    -        final String methodName;
    -        final Class[] parameterTypes;
    -        final Object[] parameters;
    -
    -        final R expected;
    -        final R actual = POITestCase.callMethod(clazz, instance, returnType, methodName, parameterTypes, parameters);
    -        assertEquals(expected, actual);
    -        */
    -    }
    -
    -    /**
    -     * Utility method to shallow compare all fields of the objects
    -     * Only use this method in test cases!!!
    -     */
    -    @Ignore
    -    @Test
    -    public void assertReflectEquals() throws Exception {
    -        /*
    -        final Object expected;
    -        final Object actual;
    -        POITestCase.assertReflectEquals(expected, actual);
    -        */
    -    }
    -}
    diff --git a/src/testcases/org/apache/poi/ddf/AllPOIDDFTests.java b/src/testcases/org/apache/poi/ddf/AllPOIDDFTests.java
    deleted file mode 100644
    index 2088e9760..000000000
    --- a/src/testcases/org/apache/poi/ddf/AllPOIDDFTests.java
    +++ /dev/null
    @@ -1,42 +0,0 @@
    -/* ====================================================================
    -   Licensed to the Apache Software Foundation (ASF) under one or more
    -   contributor license agreements.  See the NOTICE file distributed with
    -   this work for additional information regarding copyright ownership.
    -   The ASF licenses this file to You under the Apache License, Version 2.0
    -   (the "License"); you may not use this file except in compliance with
    -   the License.  You may obtain a copy of the License at
    -
    -       http://www.apache.org/licenses/LICENSE-2.0
    -
    -   Unless required by applicable law or agreed to in writing, software
    -   distributed under the License is distributed on an "AS IS" BASIS,
    -   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    -   See the License for the specific language governing permissions and
    -   limitations under the License.
    -==================================================================== */
    -
    -package org.apache.poi.ddf;
    -
    -import org.junit.runner.RunWith;
    -import org.junit.runners.Suite;
    -
    -@RunWith(Suite.class)
    -@Suite.SuiteClasses({
    -    TestEscherBSERecord.class,
    -    TestEscherBlipRecord.class,
    -    TestEscherBoolProperty.class,
    -    TestEscherChildAnchorRecord.class,
    -    TestEscherClientAnchorRecord.class,
    -    TestEscherClientDataRecord.class,
    -    TestEscherContainerRecord.class,
    -    TestEscherDgRecord.class,
    -    TestEscherDggRecord.class,
    -    TestEscherOptRecord.class,
    -    TestEscherPropertyFactory.class,
    -    TestEscherSpRecord.class,
    -    TestEscherSpgrRecord.class,
    -    TestEscherSplitMenuColorsRecord.class,
    -    TestUnknownEscherRecord.class
    -})
    -public final class AllPOIDDFTests {
    -}
    diff --git a/src/testcases/org/apache/poi/ddf/TestEscherBSERecord.java b/src/testcases/org/apache/poi/ddf/TestEscherBSERecord.java
    deleted file mode 100644
    index 6b26799f6..000000000
    --- a/src/testcases/org/apache/poi/ddf/TestEscherBSERecord.java
    +++ /dev/null
    @@ -1,101 +0,0 @@
    -/* ====================================================================
    -   Licensed to the Apache Software Foundation (ASF) under one or more
    -   contributor license agreements.  See the NOTICE file distributed with
    -   this work for additional information regarding copyright ownership.
    -   The ASF licenses this file to You under the Apache License, Version 2.0
    -   (the "License"); you may not use this file except in compliance with
    -   the License.  You may obtain a copy of the License at
    -
    -       http://www.apache.org/licenses/LICENSE-2.0
    -
    -   Unless required by applicable law or agreed to in writing, software
    -   distributed under the License is distributed on an "AS IS" BASIS,
    -   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    -   See the License for the specific language governing permissions and
    -   limitations under the License.
    -==================================================================== */
    -
    -package org.apache.poi.ddf;
    -
    -import junit.framework.TestCase;
    -import org.apache.poi.util.HexDump;
    -import org.apache.poi.util.HexRead;
    -
    -public final class TestEscherBSERecord extends TestCase {
    -    public void testFillFields() {
    -        String data = "01 00 00 00 24 00 00 00 05 05 01 02 03 04 " +
    -                " 05 06 07 08 09 0A 0B 0C 0D 0E 0F 00 01 00 00 00 " +
    -                " 00 00 02 00 00 00 03 00 00 00 04 05 06 07";
    -        EscherBSERecord r = new EscherBSERecord();
    -        int bytesWritten = r.fillFields( HexRead.readFromString( data ), 0, new DefaultEscherRecordFactory() );
    -        assertEquals( 44, bytesWritten );
    -        assertEquals( (short) 0x0001, r.getOptions() );
    -        assertEquals( EscherBSERecord.BT_JPEG, r.getBlipTypeWin32() );
    -        assertEquals( EscherBSERecord.BT_JPEG, r.getBlipTypeMacOS() );
    -        assertEquals( "[01, 02, 03, 04, 05, 06, 07, 08, 09, 0A, 0B, 0C, 0D, 0E, 0F, 00]", HexDump.toHex( r.getUid() ) );
    -        assertEquals( (short) 1, r.getTag() );
    -        assertEquals( 2, r.getRef() );
    -        assertEquals( 3, r.getOffset() );
    -        assertEquals( (byte) 4, r.getUsage() );
    -        assertEquals( (byte) 5, r.getName() );
    -        assertEquals( (byte) 6, r.getUnused2() );
    -        assertEquals( (byte) 7, r.getUnused3() );
    -        assertEquals( 0, r.getRemainingData().length );
    -    }
    -
    -    public void testSerialize() {
    -        EscherBSERecord r = createRecord();
    -
    -        byte[] data = new byte[8 + 36];
    -        int bytesWritten = r.serialize( 0, data, new NullEscherSerializationListener() );
    -        assertEquals( 44, bytesWritten );
    -        assertEquals( "[01, 00, 00, 00, 24, 00, 00, 00, 05, 05, 01, 02, 03, 04, " +
    -                "05, 06, 07, 08, 09, 0A, 0B, 0C, 0D, 0E, 0F, 00, 01, 00, 00, 00, " +
    -                "00, 00, 02, 00, 00, 00, 03, 00, 00, 00, 04, 05, 06, 07]",
    -                HexDump.toHex(data));
    -
    -    }
    -
    -    private EscherBSERecord createRecord() {
    -        EscherBSERecord r = new EscherBSERecord();
    -        r.setOptions( (short) 0x0001 );
    -        r.setBlipTypeWin32( EscherBSERecord.BT_JPEG );
    -        r.setBlipTypeMacOS( EscherBSERecord.BT_JPEG );
    -        r.setUid( HexRead.readFromString( "01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 00" ) );
    -        r.setTag( (short) 1 );
    -        r.setRef( 2 );
    -        r.setOffset( 3 );
    -        r.setUsage( (byte) 4 );
    -        r.setName( (byte) 5 );
    -        r.setUnused2( (byte) 6 );
    -        r.setUnused3( (byte) 7 );
    -        r.setRemainingData( new byte[0] );
    -        return r;
    -
    -    }
    -
    -    public void testToString() {
    -        EscherBSERecord record = createRecord();
    -        String expected = "org.apache.poi.ddf.EscherBSERecord:" + '\n' +
    -                "  RecordId: 0xF007" + '\n' +
    -                "  Version: 0x0001" + '\n' +
    -                "  Instance: 0x0000" + '\n' +
    -                "  BlipTypeWin32: 5" + '\n' +
    -                "  BlipTypeMacOS: 5" + '\n' +
    -                "  SUID: [01, 02, 03, 04, 05, 06, 07, 08, 09, 0A, 0B, 0C, 0D, 0E, 0F, 00]" + '\n' +
    -                "  Tag: 1" + '\n' +
    -                "  Size: 0" + '\n' +
    -                "  Ref: 2" + '\n' +
    -                "  Offset: 3" + '\n' +
    -                "  Usage: 4" + '\n' +
    -                "  Name: 5" + '\n' +
    -                "  Unused2: 6" + '\n' +
    -                "  Unused3: 7" + '\n' +
    -                "  blipRecord: null" + '\n' +
    -                "  Extra Data:" + '\n' +
    -                ": 0";
    -        String actual = record.toString();
    -        assertEquals( expected, actual );
    -    }
    -
    -}
    diff --git a/src/testcases/org/apache/poi/ddf/TestEscherBlipRecord.java b/src/testcases/org/apache/poi/ddf/TestEscherBlipRecord.java
    deleted file mode 100644
    index 899af6e46..000000000
    --- a/src/testcases/org/apache/poi/ddf/TestEscherBlipRecord.java
    +++ /dev/null
    @@ -1,176 +0,0 @@
    -/* ====================================================================
    -   Licensed to the Apache Software Foundation (ASF) under one or more
    -   contributor license agreements.  See the NOTICE file distributed with
    -   this work for additional information regarding copyright ownership.
    -   The ASF licenses this file to You under the Apache License, Version 2.0
    -   (the "License"); you may not use this file except in compliance with
    -   the License.  You may obtain a copy of the License at
    -
    -       http://www.apache.org/licenses/LICENSE-2.0
    -
    -   Unless required by applicable law or agreed to in writing, software
    -   distributed under the License is distributed on an "AS IS" BASIS,
    -   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    -   See the License for the specific language governing permissions and
    -   limitations under the License.
    -==================================================================== */
    -
    -package org.apache.poi.ddf;
    -
    -import static org.junit.Assert.assertArrayEquals;
    -
    -import java.io.File;
    -import java.io.FileInputStream;
    -import java.io.IOException;
    -
    -import junit.framework.TestCase;
    -
    -import org.apache.poi.POIDataSamples;
    -
    -/**
    - * Test read/serialize of escher blip records
    - *
    - * @author Yegor Kozlov
    - */
    -public final class TestEscherBlipRecord extends TestCase {
    -    private static final POIDataSamples _samples = POIDataSamples.getDDFInstance();
    -
    -    //test reading/serializing of a PNG blip
    -    public void testReadPNG() {
    -        //provided in bug-44886
    -        byte[] data = _samples.readFile("Container.dat");
    -
    -        EscherContainerRecord record = new EscherContainerRecord();
    -        record.fillFields(data, 0, new DefaultEscherRecordFactory());
    -        EscherContainerRecord bstore = (EscherContainerRecord)record.getChild(1);
    -        EscherBSERecord bse1 = (EscherBSERecord)bstore.getChild(0);
    -        assertEquals(EscherBSERecord.BT_PNG, bse1.getBlipTypeWin32());
    -        assertEquals(EscherBSERecord.BT_PNG, bse1.getBlipTypeMacOS());
    -        assertArrayEquals(new byte[]{
    -            0x65, 0x07, 0x4A, (byte)0x8D, 0x3E, 0x42, (byte)0x8B, (byte)0xAC,
    -            0x1D, (byte)0x89, 0x35, 0x4F, 0x48, (byte)0xFA, 0x37, (byte)0xC2
    -        }, bse1.getUid());
    -        assertEquals(255, bse1.getTag());
    -        assertEquals(32308, bse1.getSize());
    -
    -        EscherBitmapBlip blip1 = (EscherBitmapBlip)bse1.getBlipRecord();
    -        assertEquals(0x6E00, blip1.getOptions());
    -        assertEquals(EscherBitmapBlip.RECORD_ID_PNG, blip1.getRecordId());
    -        assertArrayEquals(new byte[]{
    -            0x65, 0x07, 0x4A, (byte)0x8D, 0x3E, 0x42, (byte)0x8B, (byte)0xAC,
    -            0x1D, (byte)0x89, 0x35, 0x4F, 0x48, (byte)0xFA, 0x37, (byte)0xC2
    -        }, blip1.getUID());
    -
    -        //serialize and read again
    -        byte[] ser = bse1.serialize();
    -        EscherBSERecord bse2 = new EscherBSERecord();
    -        bse2.fillFields(ser, 0, new DefaultEscherRecordFactory());
    -        assertEquals(bse1.getRecordId(), bse2.getRecordId());
    -        assertEquals(bse1.getBlipTypeWin32(), bse2.getBlipTypeWin32());
    -        assertEquals(bse1.getBlipTypeMacOS(), bse2.getBlipTypeMacOS());
    -        assertArrayEquals(bse1.getUid(), bse2.getUid());
    -        assertEquals(bse1.getTag(), bse2.getTag());
    -        assertEquals(bse1.getSize(), bse2.getSize());
    -
    -        EscherBitmapBlip blip2 = (EscherBitmapBlip)bse1.getBlipRecord();
    -        assertEquals(blip1.getOptions(), blip2.getOptions());
    -        assertEquals(blip1.getRecordId(), blip2.getRecordId());
    -        assertEquals(blip1.getUID(), blip2.getUID());
    -
    -        assertArrayEquals(blip1.getPicturedata(), blip1.getPicturedata());
    -    }
    -
    -    //test reading/serializing of a PICT metafile
    -    public void testReadPICT() {
    -        //provided in bug-44886
    -        byte[] data = _samples.readFile("Container.dat");
    -
    -        EscherContainerRecord record = new EscherContainerRecord();
    -        record.fillFields(data, 0, new DefaultEscherRecordFactory());
    -        EscherContainerRecord bstore = (EscherContainerRecord)record.getChild(1);
    -        EscherBSERecord bse1 = (EscherBSERecord)bstore.getChild(1);
    -        //System.out.println(bse1);
    -        assertEquals(EscherBSERecord.BT_WMF, bse1.getBlipTypeWin32());
    -        assertEquals(EscherBSERecord.BT_PICT, bse1.getBlipTypeMacOS());
    -        assertArrayEquals(new byte[]{
    -            (byte)0xC7, 0x15, 0x69, 0x2D, (byte)0xE5, (byte)0x89, (byte)0xA3, 0x6F,
    -            0x66, 0x03, (byte)0xD6, 0x24, (byte)0xF7, (byte)0xDB, 0x1D, 0x13
    -        }, bse1.getUid());
    -        assertEquals(255, bse1.getTag());
    -        assertEquals(1133, bse1.getSize());
    -
    -        EscherMetafileBlip blip1 = (EscherMetafileBlip)bse1.getBlipRecord();
    -        assertEquals(0x5430, blip1.getOptions());
    -        assertEquals(EscherMetafileBlip.RECORD_ID_PICT, blip1.getRecordId());
    -        assertArrayEquals(new byte[]{
    -            0x57, 0x32, 0x7B, (byte)0x91, 0x23, 0x5D, (byte)0xDB, 0x36,
    -            0x7A, (byte)0xDB, (byte)0xFF, 0x17, (byte)0xFE, (byte)0xF3, (byte)0xA7, 0x05
    -        }, blip1.getUID());
    -        assertArrayEquals(new byte[]{
    -            (byte)0xC7, 0x15, 0x69, 0x2D, (byte)0xE5, (byte)0x89, (byte)0xA3, 0x6F,
    -            0x66, 0x03, (byte)0xD6, 0x24, (byte)0xF7, (byte)0xDB, 0x1D, 0x13
    -        }, blip1.getPrimaryUID());
    -
    -        //serialize and read again
    -        byte[] ser = bse1.serialize();
    -        EscherBSERecord bse2 = new EscherBSERecord();
    -        bse2.fillFields(ser, 0, new DefaultEscherRecordFactory());
    -        assertEquals(bse1.getRecordId(), bse2.getRecordId());
    -        assertEquals(bse1.getOptions(), bse2.getOptions());
    -        assertEquals(bse1.getBlipTypeWin32(), bse2.getBlipTypeWin32());
    -        assertEquals(bse1.getBlipTypeMacOS(), bse2.getBlipTypeMacOS());
    -        assertArrayEquals(bse1.getUid(), bse2.getUid());
    -        assertEquals(bse1.getTag(), bse2.getTag());
    -        assertEquals(bse1.getSize(), bse2.getSize());
    -
    -        EscherMetafileBlip blip2 = (EscherMetafileBlip)bse1.getBlipRecord();
    -        assertEquals(blip1.getOptions(), blip2.getOptions());
    -        assertEquals(blip1.getRecordId(), blip2.getRecordId());
    -        assertEquals(blip1.getUID(), blip2.getUID());
    -        assertEquals(blip1.getPrimaryUID(), blip2.getPrimaryUID());
    -
    -        assertArrayEquals(blip1.getPicturedata(), blip1.getPicturedata());
    -    }
    -
    -    //integral test: check that the read-write-read round trip is consistent
    -    public void testContainer() {
    -        byte[] data = _samples.readFile("Container.dat");
    -
    -        EscherContainerRecord record = new EscherContainerRecord();
    -        record.fillFields(data, 0, new DefaultEscherRecordFactory());
    -
    -        byte[] ser = record.serialize();
    -        assertArrayEquals(data, ser);
    -    }
    -
    -    private byte[] read(File file) {
    -        byte[] data = new byte[(int)file.length()];
    -        try {
    -            FileInputStream is = new FileInputStream(file);
    -            is.read(data);
    -            is.close();
    -        } catch (IOException e) {
    -            throw new RuntimeException(e);
    -        }
    -        return data;
    -    }
    -
    -    /**
    -     * The test data was created from pl031405.xls attached to Bugzilla #47143
    -     */
    -    public void test47143() {
    -        byte[] data = _samples.readFile("47143.dat");
    -        EscherBSERecord bse = new EscherBSERecord();
    -        bse.fillFields(data, 0, new DefaultEscherRecordFactory());
    -        bse.toString(); //assert that toString() works
    -        assertTrue(bse.getBlipRecord() instanceof EscherMetafileBlip);
    -
    -        EscherMetafileBlip blip = (EscherMetafileBlip)bse.getBlipRecord();
    -        blip.toString(); //assert that toString() works
    -        byte[] remaining = blip.getRemainingData();
    -        assertNotNull(remaining);
    -
    -        byte[] ser = bse.serialize();  //serialize and assert against the source data
    -        assertArrayEquals(data, ser);
    -    }
    -}
    diff --git a/src/testcases/org/apache/poi/ddf/TestEscherBoolProperty.java b/src/testcases/org/apache/poi/ddf/TestEscherBoolProperty.java
    deleted file mode 100644
    index f1713533a..000000000
    --- a/src/testcases/org/apache/poi/ddf/TestEscherBoolProperty.java
    +++ /dev/null
    @@ -1,27 +0,0 @@
    -/* ====================================================================
    -   Licensed to the Apache Software Foundation (ASF) under one or more
    -   contributor license agreements.  See the NOTICE file distributed with
    -   this work for additional information regarding copyright ownership.
    -   The ASF licenses this file to You under the Apache License, Version 2.0
    -   (the "License"); you may not use this file except in compliance with
    -   the License.  You may obtain a copy of the License at
    -
    -       http://www.apache.org/licenses/LICENSE-2.0
    -
    -   Unless required by applicable law or agreed to in writing, software
    -   distributed under the License is distributed on an "AS IS" BASIS,
    -   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    -   See the License for the specific language governing permissions and
    -   limitations under the License.
    -==================================================================== */
    -
    -package org.apache.poi.ddf;
    -
    -import junit.framework.TestCase;
    -
    -public final class TestEscherBoolProperty extends TestCase {
    -    public void testToString() {
    -        EscherBoolProperty p = new EscherBoolProperty((short)1, 1);
    -        assertEquals("propNum: 1, RAW: 0x0001, propName: unknown, complex: false, blipId: false, value: 1 (0x00000001)", p.toString());
    -    }
    -}
    diff --git a/src/testcases/org/apache/poi/ddf/TestEscherChildAnchorRecord.java b/src/testcases/org/apache/poi/ddf/TestEscherChildAnchorRecord.java
    deleted file mode 100644
    index 4f8815ade..000000000
    --- a/src/testcases/org/apache/poi/ddf/TestEscherChildAnchorRecord.java
    +++ /dev/null
    @@ -1,86 +0,0 @@
    -/* ====================================================================
    -   Licensed to the Apache Software Foundation (ASF) under one or more
    -   contributor license agreements.  See the NOTICE file distributed with
    -   this work for additional information regarding copyright ownership.
    -   The ASF licenses this file to You under the Apache License, Version 2.0
    -   (the "License"); you may not use this file except in compliance with
    -   the License.  You may obtain a copy of the License at
    -
    -       http://www.apache.org/licenses/LICENSE-2.0
    -
    -   Unless required by applicable law or agreed to in writing, software
    -   distributed under the License is distributed on an "AS IS" BASIS,
    -   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    -   See the License for the specific language governing permissions and
    -   limitations under the License.
    -==================================================================== */
    -
    -package org.apache.poi.ddf;
    -
    -import junit.framework.TestCase;
    -import org.apache.poi.util.HexDump;
    -import org.apache.poi.util.HexRead;
    -
    -public final class TestEscherChildAnchorRecord extends TestCase {
    -    public void testSerialize() {
    -        EscherChildAnchorRecord r = createRecord();
    -
    -        byte[] data = new byte[8 + 16];
    -        int bytesWritten = r.serialize( 0, data, new NullEscherSerializationListener() );
    -        assertEquals( 24, bytesWritten );
    -        assertEquals( "[01, 00, " +
    -                "0F, F0, " +
    -                "10, 00, 00, 00, " +
    -                "01, 00, 00, 00, " +
    -                "02, 00, 00, 00, " +
    -                "03, 00, 00, 00, " +
    -                "04, 00, 00, 00]", HexDump.toHex( data ) );
    -    }
    -
    -    public void testFillFields() {
    -        String hexData = "01 00 " +
    -                "0F F0 " +
    -                "10 00 00 00 " +
    -                "01 00 00 00 " +
    -                "02 00 00 00 " +
    -                "03 00 00 00 " +
    -                "04 00 00 00 ";
    -
    -        byte[] data = HexRead.readFromString( hexData );
    -        EscherChildAnchorRecord r = new EscherChildAnchorRecord();
    -        int bytesWritten = r.fillFields( data, new DefaultEscherRecordFactory() );
    -
    -        assertEquals( 24, bytesWritten );
    -        assertEquals( 1, r.getDx1() );
    -        assertEquals( 2, r.getDy1() );
    -        assertEquals( 3, r.getDx2() );
    -        assertEquals( 4, r.getDy2() );
    -        assertEquals( (short) 0x0001, r.getOptions() );
    -    }
    -
    -    public void testToString(){
    -        String nl = System.getProperty( "line.separator" );
    -
    -        String expected = "org.apache.poi.ddf.EscherChildAnchorRecord:" + nl +
    -                "  RecordId: 0xF00F" + nl +
    -                "  Version: 0x0001" + nl +
    -                "  Instance: 0x0000" + nl +
    -                "  X1: 1" + nl +
    -                "  Y1: 2" + nl +
    -                "  X2: 3" + nl +
    -                "  Y2: 4" + nl;
    -        assertEquals( expected, createRecord().toString() );
    -    }
    -
    -    private static EscherChildAnchorRecord createRecord() {
    -        EscherChildAnchorRecord r = new EscherChildAnchorRecord();
    -        r.setRecordId( EscherChildAnchorRecord.RECORD_ID );
    -        r.setOptions( (short) 0x0001 );
    -        r.setDx1( 1 );
    -        r.setDy1( 2 );
    -        r.setDx2( 3 );
    -        r.setDy2( 4 );
    -        return r;
    -    }
    -}
    -
    diff --git a/src/testcases/org/apache/poi/ddf/TestEscherClientAnchorRecord.java b/src/testcases/org/apache/poi/ddf/TestEscherClientAnchorRecord.java
    deleted file mode 100644
    index a1eb171f4..000000000
    --- a/src/testcases/org/apache/poi/ddf/TestEscherClientAnchorRecord.java
    +++ /dev/null
    @@ -1,106 +0,0 @@
    -/* ====================================================================
    -   Licensed to the Apache Software Foundation (ASF) under one or more
    -   contributor license agreements.  See the NOTICE file distributed with
    -   this work for additional information regarding copyright ownership.
    -   The ASF licenses this file to You under the Apache License, Version 2.0
    -   (the "License"); you may not use this file except in compliance with
    -   the License.  You may obtain a copy of the License at
    -
    -       http://www.apache.org/licenses/LICENSE-2.0
    -
    -   Unless required by applicable law or agreed to in writing, software
    -   distributed under the License is distributed on an "AS IS" BASIS,
    -   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    -   See the License for the specific language governing permissions and
    -   limitations under the License.
    -==================================================================== */
    -
    -package org.apache.poi.ddf;
    -
    -import junit.framework.TestCase;
    -import org.apache.poi.util.HexDump;
    -import org.apache.poi.util.HexRead;
    -
    -public class TestEscherClientAnchorRecord extends TestCase
    -{
    -    public void testSerialize() {
    -        EscherClientAnchorRecord r = createRecord();
    -
    -        byte[] data = new byte[8 + 18 + 2];
    -        int bytesWritten = r.serialize( 0, data, new NullEscherSerializationListener() );
    -        assertEquals( 28, bytesWritten );
    -        assertEquals( "[01, 00, " +
    -                "10, F0, " +
    -                "14, 00, 00, 00, " +
    -                "4D, 00, 37, 00, 21, 00, 58, 00, " +
    -                "0B, 00, 2C, 00, 16, 00, 63, 00, " +
    -                "42, 00, " +
    -                "FF, DD]", HexDump.toHex( data ) );
    -    }
    -
    -    public void testFillFields() {
    -        String hexData = "01 00 " +
    -                "10 F0 " +
    -                "14 00 00 00 " +
    -                "4D 00 37 00 21 00 58 00 " +
    -                "0B 00 2C 00 16 00 63 00 " +
    -                "42 00 " +
    -                "FF DD";
    -        byte[] data = HexRead.readFromString( hexData );
    -        EscherClientAnchorRecord r = new EscherClientAnchorRecord();
    -        int bytesWritten = r.fillFields( data, new DefaultEscherRecordFactory() );
    -
    -        assertEquals( 28, bytesWritten );
    -        assertEquals( (short) 55, r.getCol1() );
    -        assertEquals( (short) 44, r.getCol2() );
    -        assertEquals( (short) 33, r.getDx1() );
    -        assertEquals( (short) 22, r.getDx2() );
    -        assertEquals( (short) 11, r.getDy1() );
    -        assertEquals( (short) 66, r.getDy2() );
    -        assertEquals( (short) 77, r.getFlag() );
    -        assertEquals( (short) 88, r.getRow1() );
    -        assertEquals( (short) 99, r.getRow2() );
    -        assertEquals( (short) 0x0001, r.getOptions() );
    -        assertEquals( (byte) 0xFF, r.getRemainingData()[0] );
    -        assertEquals( (byte) 0xDD, r.getRemainingData()[1] );
    -    }
    -
    -    public void testToString() {
    -        String nl = System.getProperty("line.separator");
    -
    -        String expected = "org.apache.poi.ddf.EscherClientAnchorRecord:" + nl +
    -                "  RecordId: 0xF010" + nl +
    -                "  Version: 0x0001" + nl +
    -                "  Instance: 0x0000" + nl +
    -                "  Flag: 77" + nl +
    -                "  Col1: 55" + nl +
    -                "  DX1: 33" + nl +
    -                "  Row1: 88" + nl +
    -                "  DY1: 11" + nl +
    -                "  Col2: 44" + nl +
    -                "  DX2: 22" + nl +
    -                "  Row2: 99" + nl +
    -                "  DY2: 66" + nl +
    -                "  Extra Data:" + nl +
    -                "00000000 FF DD                                           .." + nl;
    -        assertEquals( expected, createRecord().toString() );
    -    }
    -
    -    private EscherClientAnchorRecord createRecord()
    -    {
    -        EscherClientAnchorRecord r = new EscherClientAnchorRecord();
    -        r.setCol1( (short) 55 );
    -        r.setCol2( (short) 44 );
    -        r.setDx1( (short) 33 );
    -        r.setDx2( (short) 22 );
    -        r.setDy1( (short) 11 );
    -        r.setDy2( (short) 66 );
    -        r.setFlag( (short) 77 );
    -        r.setRow1( (short) 88 );
    -        r.setRow2( (short) 99 );
    -        r.setOptions( (short) 0x0001 );
    -        r.setRemainingData( new byte[]{(byte) 0xFF, (byte) 0xDD} );
    -        return r;
    -    }
    -
    -}
    diff --git a/src/testcases/org/apache/poi/ddf/TestEscherClientDataRecord.java b/src/testcases/org/apache/poi/ddf/TestEscherClientDataRecord.java
    deleted file mode 100644
    index 0282ed091..000000000
    --- a/src/testcases/org/apache/poi/ddf/TestEscherClientDataRecord.java
    +++ /dev/null
    @@ -1,71 +0,0 @@
    -/* ====================================================================
    -   Licensed to the Apache Software Foundation (ASF) under one or more
    -   contributor license agreements.  See the NOTICE file distributed with
    -   this work for additional information regarding copyright ownership.
    -   The ASF licenses this file to You under the Apache License, Version 2.0
    -   (the "License"); you may not use this file except in compliance with
    -   the License.  You may obtain a copy of the License at
    -
    -       http://www.apache.org/licenses/LICENSE-2.0
    -
    -   Unless required by applicable law or agreed to in writing, software
    -   distributed under the License is distributed on an "AS IS" BASIS,
    -   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    -   See the License for the specific language governing permissions and
    -   limitations under the License.
    -==================================================================== */
    - 
    -package org.apache.poi.ddf;
    -
    -import junit.framework.TestCase;
    -import org.apache.poi.util.HexDump;
    -import org.apache.poi.util.HexRead;
    -
    -public class TestEscherClientDataRecord extends TestCase
    -{
    -    public void testSerialize() {
    -        EscherClientDataRecord r = createRecord();
    -
    -        byte[] data = new byte[8];
    -        int bytesWritten = r.serialize( 0, data, new NullEscherSerializationListener() );
    -        assertEquals( 8, bytesWritten );
    -        assertEquals( "[02, 00, " +
    -                "11, F0, " +
    -                "00, 00, 00, 00]",
    -                HexDump.toHex( data ) );
    -    }
    -
    -    public void testFillFields() {
    -        String hexData = "02 00 " +
    -                "11 F0 " +
    -                "00 00 00 00 ";
    -        byte[] data = HexRead.readFromString( hexData );
    -        EscherClientDataRecord r = new EscherClientDataRecord();
    -        int bytesWritten = r.fillFields( data, new DefaultEscherRecordFactory() );
    -
    -        assertEquals( 8, bytesWritten );
    -        assertEquals( (short)0xF011, r.getRecordId() );
    -        assertEquals( "[]", HexDump.toHex(r.getRemainingData()) );
    -    }
    -
    -    public void testToString() {
    -        String nl = System.getProperty("line.separator");
    -
    -        String expected = "org.apache.poi.ddf.EscherClientDataRecord:" + nl +
    -                "  RecordId: 0xF011" + nl +
    -                "  Version: 0x0002" + nl +
    -                "  Instance: 0x0000" + nl +
    -                "  Extra Data:" + nl +
    -                "No Data" + nl ;
    -        assertEquals( expected, createRecord().toString() );
    -    }
    -
    -    private static EscherClientDataRecord createRecord()
    -    {
    -        EscherClientDataRecord r = new EscherClientDataRecord();
    -        r.setOptions( (short) 0x0002 );
    -        r.setRecordId( EscherClientDataRecord.RECORD_ID );
    -        r.setRemainingData( new byte[] {} );
    -        return r;
    -    }
    -}
    diff --git a/src/testcases/org/apache/poi/ddf/TestEscherContainerRecord.java b/src/testcases/org/apache/poi/ddf/TestEscherContainerRecord.java
    deleted file mode 100644
    index 026bc41de..000000000
    --- a/src/testcases/org/apache/poi/ddf/TestEscherContainerRecord.java
    +++ /dev/null
    @@ -1,200 +0,0 @@
    -/* ====================================================================
    -   Licensed to the Apache Software Foundation (ASF) under one or more
    -   contributor license agreements.  See the NOTICE file distributed with
    -   this work for additional information regarding copyright ownership.
    -   The ASF licenses this file to You under the Apache License, Version 2.0
    -   (the "License"); you may not use this file except in compliance with
    -   the License.  You may obtain a copy of the License at
    -
    -       http://www.apache.org/licenses/LICENSE-2.0
    -
    -   Unless required by applicable law or agreed to in writing, software
    -   distributed under the License is distributed on an "AS IS" BASIS,
    -   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    -   See the License for the specific language governing permissions and
    -   limitations under the License.
    -==================================================================== */
    -
    -package org.apache.poi.ddf;
    -
    -import java.util.List;
    -
    -import junit.framework.TestCase;
    -import org.apache.poi.POIDataSamples;
    -import org.apache.poi.util.HexDump;
    -import org.apache.poi.util.HexRead;
    -
    -/**
    - * Tests for {@link EscherContainerRecord}
    - */
    -public final class TestEscherContainerRecord extends TestCase {
    -    private static final POIDataSamples _samples = POIDataSamples.getDDFInstance();
    -
    -	public void testFillFields() {
    -		EscherRecordFactory f = new DefaultEscherRecordFactory();
    -		byte[] data = HexRead.readFromString("0F 02 11 F1 00 00 00 00");
    -		EscherRecord r = f.createRecord(data, 0);
    -		r.fillFields(data, 0, f);
    -		assertTrue(r instanceof EscherContainerRecord);
    -		assertEquals((short) 0x020F, r.getOptions());
    -		assertEquals((short) 0xF111, r.getRecordId());
    -
    -		data = HexRead.readFromString("0F 02 11 F1 08 00 00 00" +
    -				" 02 00 22 F2 00 00 00 00");
    -		r = f.createRecord(data, 0);
    -		r.fillFields(data, 0, f);
    -		EscherRecord c = r.getChild(0);
    -		assertFalse(c instanceof EscherContainerRecord);
    -		assertEquals((short) 0x0002, c.getOptions());
    -		assertEquals((short) 0xF222, c.getRecordId());
    -	}
    -
    -	public void testSerialize() {
    -		UnknownEscherRecord r = new UnknownEscherRecord();
    -		r.setOptions((short) 0x123F);
    -		r.setRecordId((short) 0xF112);
    -		byte[] data = new byte[8];
    -		r.serialize(0, data, new NullEscherSerializationListener());
    -
    -		assertEquals("[3F, 12, 12, F1, 00, 00, 00, 00]", HexDump.toHex(data));
    -
    -		EscherRecord childRecord = new UnknownEscherRecord();
    -		childRecord.setOptions((short) 0x9999);
    -		childRecord.setRecordId((short) 0xFF01);
    -		r.addChildRecord(childRecord);
    -		data = new byte[16];
    -		r.serialize(0, data, new NullEscherSerializationListener());
    -
    -		assertEquals("[3F, 12, 12, F1, 08, 00, 00, 00, 99, 99, 01, FF, 00, 00, 00, 00]", HexDump.toHex(data));
    -
    -	}
    -
    -	public void testToString() {
    -		EscherContainerRecord r = new EscherContainerRecord();
    -		r.setRecordId(EscherContainerRecord.SP_CONTAINER);
    -		r.setOptions((short) 0x000F);
    -		String nl = System.getProperty("line.separator");
    -		assertEquals("org.apache.poi.ddf.EscherContainerRecord (SpContainer):" + nl +
    -				"  isContainer: true" + nl +
    -                "  version: 0x000F" + nl +
    -                "  instance: 0x0000" + nl +
    -				"  recordId: 0xF004" + nl +
    -				"  numchildren: 0" + nl
    -				, r.toString());
    -
    -		EscherOptRecord r2 = new EscherOptRecord();
    -		// don't try to shoot in foot, please -- vlsergey
    -		// r2.setOptions((short) 0x9876);
    -		r2.setRecordId(EscherOptRecord.RECORD_ID);
    -
    -		String expected;
    -		r.addChildRecord(r2);
    -		expected = "org.apache.poi.ddf.EscherContainerRecord (SpContainer):" + nl +
    -				   "  isContainer: true" + nl +
    -                   "  version: 0x000F" + nl +
    -                   "  instance: 0x0000" + nl +
    -				   "  recordId: 0xF004" + nl +
    -				   "  numchildren: 1" + nl +
    -				   "  children: " + nl +
    -				   "   Child 0:" + nl +
    -				   "    org.apache.poi.ddf.EscherOptRecord:" + nl +
    -				   "      isContainer: false" + nl +
    -                   "      version: 0x0003" + nl +
    -                   "      instance: 0x0000" + nl +
    -				   "      recordId: 0xF00B" + nl +
    -				   "      numchildren: 0" + nl +
    -				   "      properties:" + nl +
    -				   "    " + nl;
    -		assertEquals(expected, r.toString());
    -
    -		r.addChildRecord(r2);
    -		expected = "org.apache.poi.ddf.EscherContainerRecord (SpContainer):" + nl +
    -				"  isContainer: true" + nl +
    -                "  version: 0x000F" + nl +
    -                "  instance: 0x0000" + nl +
    -				"  recordId: 0xF004" + nl +
    -				"  numchildren: 2" + nl +
    -				"  children: " + nl +
    -				"   Child 0:" + nl +
    -				"    org.apache.poi.ddf.EscherOptRecord:" + nl +
    -				"      isContainer: false" + nl +
    -                "      version: 0x0003" + nl +
    -                "      instance: 0x0000" + nl +
    -				"      recordId: 0xF00B" + nl +
    -				"      numchildren: 0" + nl +
    -				"      properties:" + nl +
    -				"    " + nl +
    -				"   Child 1:" + nl +
    -				"    org.apache.poi.ddf.EscherOptRecord:" + nl +
    -				"      isContainer: false" + nl +
    -                "      version: 0x0003" + nl +
    -                "      instance: 0x0000" + nl +
    -				"      recordId: 0xF00B" + nl +
    -				"      numchildren: 0" + nl +
    -				"      properties:" + nl +
    -				"    " + nl;
    -		assertEquals(expected, r.toString());
    -	}
    -
    -	private static final class DummyEscherRecord extends EscherRecord {
    -		public DummyEscherRecord() { }
    -		@Override
    -        public int fillFields(byte[] data, int offset, EscherRecordFactory recordFactory) { return 0; }
    -		@Override
    -        public int serialize(int offset, byte[] data, EscherSerializationListener listener) { return 0; }
    -		@Override
    -        public int getRecordSize() { return 10; }
    -		@Override
    -        public String getRecordName() { return ""; }
    -	}
    -
    -	public void testGetRecordSize() {
    -		EscherContainerRecord r = new EscherContainerRecord();
    -		r.addChildRecord(new DummyEscherRecord());
    -		assertEquals(18, r.getRecordSize());
    -	}
    -
    -	/**
    -	 * We were having problems with reading too much data on an UnknownEscherRecord,
    -	 *  but hopefully we now read the correct size.
    -	 */
    -	public void testBug44857() throws Exception {
    -		byte[] data = _samples.readFile("Container.dat");
    -
    -		// This used to fail with an OutOfMemory
    -		EscherContainerRecord record = new EscherContainerRecord();
    -		record.fillFields(data, 0, new DefaultEscherRecordFactory());
    -	}
    -
    -	/**
    -	 * Ensure {@link EscherContainerRecord} doesn't spill its guts everywhere
    -	 */
    -	public void testChildren() {
    -		EscherContainerRecord ecr = new EscherContainerRecord();
    -		List children0 = ecr.getChildRecords();
    -		assertEquals(0, children0.size());
    -
    -		EscherRecord chA = new DummyEscherRecord();
    -		EscherRecord chB = new DummyEscherRecord();
    -		EscherRecord chC = new DummyEscherRecord();
    -
    -		ecr.addChildRecord(chA);
    -		ecr.addChildRecord(chB);
    -		children0.add(chC);
    -
    -		List children1 = ecr.getChildRecords();
    -		assertTrue(children0 !=  children1);
    -		assertEquals(2, children1.size());
    -		assertEquals(chA, children1.get(0));
    -		assertEquals(chB, children1.get(1));
    -
    -		assertEquals(1, children0.size()); // first copy unchanged
    -
    -		ecr.setChildRecords(children0);
    -		ecr.addChildRecord(chA);
    -		List children2 = ecr.getChildRecords();
    -		assertEquals(2, children2.size());
    -		assertEquals(chC, children2.get(0));
    -		assertEquals(chA, children2.get(1));
    -	}
    -}
    diff --git a/src/testcases/org/apache/poi/ddf/TestEscherDgRecord.java b/src/testcases/org/apache/poi/ddf/TestEscherDgRecord.java
    deleted file mode 100644
    index 2e0fd4b10..000000000
    --- a/src/testcases/org/apache/poi/ddf/TestEscherDgRecord.java
    +++ /dev/null
    @@ -1,73 +0,0 @@
    -/* ====================================================================
    -   Licensed to the Apache Software Foundation (ASF) under one or more
    -   contributor license agreements.  See the NOTICE file distributed with
    -   this work for additional information regarding copyright ownership.
    -   The ASF licenses this file to You under the Apache License, Version 2.0
    -   (the "License"); you may not use this file except in compliance with
    -   the License.  You may obtain a copy of the License at
    -
    -       http://www.apache.org/licenses/LICENSE-2.0
    -
    -   Unless required by applicable law or agreed to in writing, software
    -   distributed under the License is distributed on an "AS IS" BASIS,
    -   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    -   See the License for the specific language governing permissions and
    -   limitations under the License.
    -==================================================================== */
    -
    -package org.apache.poi.ddf;
    -
    -import junit.framework.TestCase;
    -import org.apache.poi.util.HexDump;
    -import org.apache.poi.util.HexRead;
    -
    -public final class TestEscherDgRecord extends TestCase {
    -    public void testSerialize() {
    -        EscherDgRecord r = createRecord();
    -
    -        byte[] data = new byte[16];
    -        int bytesWritten = r.serialize( 0, data, new NullEscherSerializationListener() );
    -        assertEquals( 16, bytesWritten );
    -        assertEquals( "[10, 00, " +
    -                "08, F0, " +
    -                "08, 00, 00, 00, " +
    -                "02, 00, 00, 00, " +     // num shapes in drawing
    -                "01, 04, 00, 00]",     // The last MSOSPID given to an SP in this DG
    -                HexDump.toHex( data ) );
    -    }
    -
    -    public void testFillFields() {
    -        String hexData = "10 00 " +
    -                "08 F0 " +
    -                "08 00 00 00 " +
    -                "02 00 00 00 " +
    -                "01 04 00 00 ";
    -        byte[] data = HexRead.readFromString( hexData );
    -        EscherDgRecord r = new EscherDgRecord();
    -        int bytesWritten = r.fillFields( data, new DefaultEscherRecordFactory() );
    -
    -        assertEquals( 16, bytesWritten );
    -        assertEquals( 2, r.getNumShapes() );
    -        assertEquals( 1025, r.getLastMSOSPID() );
    -    }
    -
    -    public void testToString() {
    -        String expected = "org.apache.poi.ddf.EscherDgRecord:" + '\n' +
    -                "  RecordId: 0xF008" + '\n' +
    -                "  Version: 0x0000" + '\n' +
    -                "  Instance: 0x0001" + '\n' +
    -                "  NumShapes: 2" + '\n' +
    -                "  LastMSOSPID: 1025" + '\n';
    -        assertEquals( expected, createRecord().toString() );
    -    }
    -
    -    private static EscherDgRecord createRecord()
    -    {
    -        EscherDgRecord r = new EscherDgRecord();
    -        r.setOptions( (short) 0x0010 );
    -        r.setRecordId( EscherDgRecord.RECORD_ID );
    -        r.setNumShapes(2);
    -        r.setLastMSOSPID(1025);
    -        return r;
    -    }
    -}
    diff --git a/src/testcases/org/apache/poi/ddf/TestEscherDggRecord.java b/src/testcases/org/apache/poi/ddf/TestEscherDggRecord.java
    deleted file mode 100644
    index 2587a3b2d..000000000
    --- a/src/testcases/org/apache/poi/ddf/TestEscherDggRecord.java
    +++ /dev/null
    @@ -1,98 +0,0 @@
    -/* ====================================================================
    -   Licensed to the Apache Software Foundation (ASF) under one or more
    -   contributor license agreements.  See the NOTICE file distributed with
    -   this work for additional information regarding copyright ownership.
    -   The ASF licenses this file to You under the Apache License, Version 2.0
    -   (the "License"); you may not use this file except in compliance with
    -   the License.  You may obtain a copy of the License at
    -
    -       http://www.apache.org/licenses/LICENSE-2.0
    -
    -   Unless required by applicable law or agreed to in writing, software
    -   distributed under the License is distributed on an "AS IS" BASIS,
    -   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    -   See the License for the specific language governing permissions and
    -   limitations under the License.
    -==================================================================== */
    -
    -package org.apache.poi.ddf;
    -
    -import junit.framework.TestCase;
    -import org.apache.poi.util.HexDump;
    -import org.apache.poi.util.HexRead;
    -
    -public final class TestEscherDggRecord extends TestCase {
    -    public void testSerialize() {
    -        EscherDggRecord r = createRecord();
    -
    -        byte[] data = new byte[32];
    -        int bytesWritten = r.serialize( 0, data, new NullEscherSerializationListener() );
    -        assertEquals( 32, bytesWritten );
    -        assertEquals( "[00, 00, " +
    -                "06, F0, " +
    -                "18, 00, 00, 00, " +
    -                "02, 04, 00, 00, " +
    -                "02, 00, 00, 00, " +
    -                "02, 00, 00, 00, " +
    -                "01, 00, 00, 00, " +
    -                "01, 00, 00, 00, 02, 00, 00, 00]",
    -                HexDump.toHex( data ) );
    -    }
    -
    -    public void testFillFields() {
    -        String hexData = "00 00 " +
    -                "06 F0 " +
    -                "18 00 00 00 " +
    -                "02 04 00 00 " +
    -                "02 00 00 00 " +
    -                "02 00 00 00 " +
    -                "01 00 00 00 " +
    -                "01 00 00 00 02 00 00 00";
    -        byte[] data = HexRead.readFromString( hexData );
    -        EscherDggRecord r = new EscherDggRecord();
    -        int bytesWritten = r.fillFields( data, new DefaultEscherRecordFactory() );
    -
    -        assertEquals( 32, bytesWritten );
    -        assertEquals( 0x402, r.getShapeIdMax() );
    -        assertEquals( 0x02, r.getNumIdClusters() );
    -        assertEquals( 0x02, r.getNumShapesSaved() );
    -        assertEquals( 0x01, r.getDrawingsSaved() );
    -        assertEquals( 1, r.getFileIdClusters().length );
    -        assertEquals( 0x01, r.getFileIdClusters()[0].getDrawingGroupId());
    -        assertEquals( 0x02, r.getFileIdClusters()[0].getNumShapeIdsUsed());
    -    }
    -
    -    public void testToString() {
    -        String expected = "org.apache.poi.ddf.EscherDggRecord:" + '\n' +
    -                "  RecordId: 0xF006" + '\n' +
    -                "  Version: 0x0000" + '\n' +
    -                "  Instance: 0x0000" + '\n' +
    -                "  ShapeIdMax: 1026" + '\n' +
    -                "  NumIdClusters: 2" + '\n' +
    -                "  NumShapesSaved: 2" + '\n' +
    -                "  DrawingsSaved: 1" + '\n' +
    -                "  DrawingGroupId1: 1" + '\n' +
    -                "  NumShapeIdsUsed1: 2" + '\n';
    -        assertEquals( expected, createRecord().toString() );
    -    }
    -
    -    private static EscherDggRecord createRecord()
    -    {
    -        EscherDggRecord r = new EscherDggRecord();
    -        r.setOptions( (short) 0x0000 );
    -        r.setRecordId( EscherDggRecord.RECORD_ID );
    -        r.setShapeIdMax( 0x402 );
    -        r.setNumShapesSaved( 0x02 );
    -        r.setDrawingsSaved( 0x01 );
    -        r.setFileIdClusters(new EscherDggRecord.FileIdCluster[] {
    -            new EscherDggRecord.FileIdCluster( 1, 2 )
    -        });
    -        return r;
    -    }
    -
    -    public void testGetRecordSize() {
    -        EscherDggRecord r = new EscherDggRecord();
    -        r.setFileIdClusters(new EscherDggRecord.FileIdCluster[] { new EscherDggRecord.FileIdCluster(0,0) } );
    -        assertEquals(32,r.getRecordSize());
    -    }
    -}
    diff --git a/src/testcases/org/apache/poi/ddf/TestEscherDump.java b/src/testcases/org/apache/poi/ddf/TestEscherDump.java
    deleted file mode 100644
    index 95b074520..000000000
    --- a/src/testcases/org/apache/poi/ddf/TestEscherDump.java
    +++ /dev/null
    @@ -1,87 +0,0 @@
    -/* ====================================================================
    -   Licensed to the Apache Software Foundation (ASF) under one or more
    -   contributor license agreements.  See the NOTICE file distributed with
    -   this work for additional information regarding copyright ownership.
    -   The ASF licenses this file to You under the Apache License, Version 2.0
    -   (the "License"); you may not use this file except in compliance with
    -   the License.  You may obtain a copy of the License at
    -
    -       http://www.apache.org/licenses/LICENSE-2.0
    -
    -   Unless required by applicable law or agreed to in writing, software
    -   distributed under the License is distributed on an "AS IS" BASIS,
    -   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    -   See the License for the specific language governing permissions and
    -   limitations under the License.
    -==================================================================== */
    -
    -package org.apache.poi.ddf;
    -
    -import static org.junit.Assert.assertTrue;
    -
    -import java.io.ByteArrayInputStream;
    -import java.io.InputStream;
    -import java.io.PrintStream;
    -import java.io.UnsupportedEncodingException;
    -
    -import org.apache.poi.POIDataSamples;
    -import org.apache.poi.hssf.HSSFTestDataSamples;
    -import org.apache.poi.util.IOUtils;
    -import org.apache.poi.util.LocaleUtil;
    -import org.apache.poi.util.NullOutputStream;
    -import org.junit.BeforeClass;
    -import org.junit.Test;
    -
    -public class TestEscherDump {
    -    static NullPrinterStream nullPS;
    -    
    -    @BeforeClass
    -    public static void init() throws UnsupportedEncodingException {
    -        nullPS = new NullPrinterStream();
    -    }
    -    
    -    @Test
    -    public void testSimple() throws Exception {
    -        // simple test to at least cover some parts of the class
    -        EscherDump.main(new String[] {}, nullPS);
    -        
    -        new EscherDump().dump(0, new byte[] {}, nullPS);
    -        new EscherDump().dump(new byte[] {}, 0, 0, nullPS);
    -        new EscherDump().dumpOld(0, new ByteArrayInputStream(new byte[] {}), nullPS);
    -    }
    -
    -    @Test
    -    public void testWithData() throws Exception {
    -        new EscherDump().dumpOld(8, new ByteArrayInputStream(new byte[] { 00, 00, 00, 00, 00, 00, 00, 00 }), nullPS);
    -    }
    -
    -    @Test
    -    public  void testWithSamplefile() throws Exception {
    -        //InputStream stream = HSSFTestDataSamples.openSampleFileStream(")
    -        byte[] data = POIDataSamples.getDDFInstance().readFile("Container.dat");
    -        new EscherDump().dump(data.length, data, nullPS);
    -        //new EscherDump().dumpOld(data.length, new ByteArrayInputStream(data), System.out);
    -        
    -        data = new byte[2586114];
    -        InputStream stream = HSSFTestDataSamples.openSampleFileStream("44593.xls");
    -        try {
    -            int bytes = IOUtils.readFully(stream, data);
    -            assertTrue(bytes != -1);
    -            //new EscherDump().dump(bytes, data, System.out);
    -            //new EscherDump().dumpOld(bytes, new ByteArrayInputStream(data), System.out);
    -        } finally {
    -            stream.close();
    -        }
    -    }
    -    
    -    /**
    -     * Implementation of an OutputStream which does nothing, used
    -     * to redirect stdout to avoid spamming the console with output
    -     */
    -    private static class NullPrinterStream extends PrintStream {
    -        @SuppressWarnings("resource")
    -        private NullPrinterStream() throws UnsupportedEncodingException {
    -            super(new NullOutputStream(),true,LocaleUtil.CHARSET_1252.name());
    -        }      
    -    }    
    -}
    diff --git a/src/testcases/org/apache/poi/ddf/TestEscherOptRecord.java b/src/testcases/org/apache/poi/ddf/TestEscherOptRecord.java
    deleted file mode 100644
    index 0b43a0edf..000000000
    --- a/src/testcases/org/apache/poi/ddf/TestEscherOptRecord.java
    +++ /dev/null
    @@ -1,324 +0,0 @@
    -/* ====================================================================
    -   Licensed to the Apache Software Foundation (ASF) under one or more
    -   contributor license agreements.  See the NOTICE file distributed with
    -   this work for additional information regarding copyright ownership.
    -   The ASF licenses this file to You under the Apache License, Version 2.0
    -   (the "License"); you may not use this file except in compliance with
    -   the License.  You may obtain a copy of the License at
    -
    -       http://www.apache.org/licenses/LICENSE-2.0
    -
    -   Unless required by applicable law or agreed to in writing, software
    -   distributed under the License is distributed on an "AS IS" BASIS,
    -   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    -   See the License for the specific language governing permissions and
    -   limitations under the License.
    -==================================================================== */
    -
    -package org.apache.poi.ddf;
    -
    -import static org.junit.Assert.assertArrayEquals;
    -import junit.framework.TestCase;
    -
    -import org.apache.poi.util.HexDump;
    -import org.apache.poi.util.HexRead;
    -
    -public final class TestEscherOptRecord extends TestCase {
    -
    -    public void testFillFields() {
    -        checkFillFieldsSimple();
    -        checkFillFieldsComplex();
    -    }
    -
    -    private void checkFillFieldsComplex() {
    -        String dataStr = "33 00 " +
    -                "0B F0 " +
    -                "14 00 00 00 " +
    -                "BF 00 01 00 00 00 " +
    -                "01 80 02 00 00 00 " +
    -                "BF 00 01 00 00 00 " +
    -                "01 02";
    -
    -        EscherOptRecord r = new EscherOptRecord();
    -        r.fillFields( HexRead.readFromString( dataStr ), new DefaultEscherRecordFactory() );
    -        assertEquals( (short) 0x0033, r.getOptions() );
    -        assertEquals( (short) 0xF00B, r.getRecordId() );
    -        assertEquals( 3, r.getEscherProperties().size() );
    -        EscherBoolProperty prop1 = new EscherBoolProperty( EscherProperties.TEXT__SIZE_TEXT_TO_FIT_SHAPE, 1 );
    -        EscherComplexProperty prop2 = new EscherComplexProperty( (short) 1, false, new byte[] { 0x01, 0x02 } );
    -        EscherBoolProperty prop3 = new EscherBoolProperty( EscherProperties.TEXT__SIZE_TEXT_TO_FIT_SHAPE, 1 );
    -        assertEquals( prop1, r.getEscherProperty( 0 ) );
    -        assertEquals( prop2, r.getEscherProperty( 1 ) );
    -        assertEquals( prop3, r.getEscherProperty( 2 ) );
    -
    -    }
    -
    -    private void checkFillFieldsSimple() {
    -        String dataStr = "33 00 " + // options
    -                        "0B F0 " + // recordid
    -                        "12 00 00 00 " + // remaining bytes
    -                        "BF 00 08 00 08 00 " +
    -                        "81 01 09 00 00 08 " +
    -                        "C0 01 40 00 00 08";
    -
    -        EscherOptRecord r = new EscherOptRecord();
    -        r.fillFields( HexRead.readFromString( dataStr ), new DefaultEscherRecordFactory() );
    -        assertEquals( (short) 0x0033, r.getOptions() );
    -        assertEquals( (short) 0xF00B, r.getRecordId() );
    -        assertEquals( 3, r.getEscherProperties().size() );
    -        EscherBoolProperty prop1 = new EscherBoolProperty( EscherProperties.TEXT__SIZE_TEXT_TO_FIT_SHAPE, 524296 );
    -        EscherRGBProperty prop2 = new EscherRGBProperty( EscherProperties.FILL__FILLCOLOR, 0x08000009 );
    -        EscherRGBProperty prop3 = new EscherRGBProperty( EscherProperties.LINESTYLE__COLOR, 0x08000040 );
    -        assertEquals( prop1, r.getEscherProperty( 0 ) );
    -        assertEquals( prop2, r.getEscherProperty( 1 ) );
    -        assertEquals( prop3, r.getEscherProperty( 2 ) );
    -    }
    -
    -    public void testSerialize() {
    -        checkSerializeSimple();
    -        checkSerializeComplex();
    -    }
    -
    -    private void checkSerializeComplex()
    -    {
    -        //Complex escher record
    -        EscherOptRecord r = new EscherOptRecord();
    -        r.setOptions( (short) 0x0033 );
    -        r.setRecordId( (short) 0xF00B );
    -        EscherBoolProperty prop1 = new EscherBoolProperty( EscherProperties.TEXT__SIZE_TEXT_TO_FIT_SHAPE, 1 );
    -        EscherComplexProperty prop2 = new EscherComplexProperty( (short) 1, false, new byte[] { 0x01, 0x02 } );
    -        EscherBoolProperty prop3 = new EscherBoolProperty( EscherProperties.TEXT__SIZE_TEXT_TO_FIT_SHAPE, 1 );
    -        r.addEscherProperty( prop1 );
    -        r.addEscherProperty( prop2 );
    -        r.addEscherProperty( prop3 );
    -
    -        byte[] data = new byte[28];
    -        int bytesWritten = r.serialize(0, data, new NullEscherSerializationListener() );
    -        assertEquals( 28, bytesWritten );
    -        String dataStr = "[33, 00, " +
    -                "0B, F0, " +
    -                "14, 00, 00, 00, " +
    -                "BF, 00, 01, 00, 00, 00, " +
    -                "01, 80, 02, 00, 00, 00, " +
    -                "BF, 00, 01, 00, 00, 00, " +
    -                "01, 02]";
    -        assertEquals( dataStr, HexDump.toHex(data) );
    -
    -    }
    -
    -    private void checkSerializeSimple()
    -    {
    -        EscherOptRecord r = new EscherOptRecord();
    -        r.setOptions( (short) 0x0033 );
    -        r.setRecordId( (short) 0xF00B );
    -        EscherBoolProperty prop1 = new EscherBoolProperty( EscherProperties.TEXT__SIZE_TEXT_TO_FIT_SHAPE, 1 );
    -        EscherRGBProperty prop2 = new EscherRGBProperty( EscherProperties.FILL__FILLCOLOR, 0x08000009 );
    -        EscherRGBProperty prop3 = new EscherRGBProperty( EscherProperties.LINESTYLE__COLOR, 0x08000040 );
    -        r.addEscherProperty( prop1 );
    -        r.addEscherProperty( prop2 );
    -        r.addEscherProperty( prop3 );
    -
    -        byte[] data = new byte[26];
    -        int bytesWritten = r.serialize(0, data, new NullEscherSerializationListener() );
    -        String dataStr = "[33, 00, " +
    -                "0B, F0, " +
    -                "12, 00, 00, 00, " +
    -                "BF, 00, 01, 00, 00, 00, " +
    -                "81, 01, 09, 00, 00, 08, " +
    -                "C0, 01, 40, 00, 00, 08]";
    -        assertEquals( dataStr, HexDump.toHex(data) );
    -        assertEquals( 26, bytesWritten );
    -    }
    -
    -    public void testToString() {
    -        String nl = System.getProperty("line.separator");
    -        EscherOptRecord r = new EscherOptRecord();
    -        // don't try to shoot in foot, please -- vlsergey
    -        // r.setOptions((short)0x000F);
    -        r.setRecordId(EscherOptRecord.RECORD_ID);
    -        EscherProperty prop1 = new EscherBoolProperty((short)1, 1);
    -        r.addEscherProperty(prop1);
    -        String expected = "org.apache.poi.ddf.EscherOptRecord:" + nl +
    -                "  isContainer: false" + nl +
    -                "  version: 0x0003" + nl +
    -                "  instance: 0x0001" + nl +
    -                "  recordId: 0x" + HexDump.toHex(EscherOptRecord.RECORD_ID) + nl +
    -                "  numchildren: 0" + nl +
    -                "  properties:" + nl +
    -                "    propNum: 1, RAW: 0x0001, propName: unknown, complex: false, blipId: false, value: 1 (0x00000001)" + nl;
    -        assertEquals( expected, r.toString());
    -    }
    -
    -    /**
    -     * Test serialisation of a particually complex example
    -     * This test is currently broken!
    -     */
    -    public void testComplexSerialise() {
    -    	byte[] data = {
    -    		0x53, 0x01, 0x0B, 0xF0-256, 0x9C-256, 0x01, 0x00, 0x00,
    -    		// Simple data follows
    -    		0x42, 0x01,	0x49, 0x00, 0x00, 0x00,          // SP @ 8
    -    		0x43, 0x01, 0x85-256, 0x00, 0x00, 0x00,      // SP @ 14
    -    		0x44, 0x01, 0x04, 0x00, 0x00, 0x00,          // SP @ 20
    -    		0x45, 0xC1-256, 0x88-256, 0x00, 0x00, 0x00,  // SP @ 26
    -    		0x46, 0xC1-256, 0x90-256, 0x00, 0x00, 0x00,  // SP @ 32
    -    		0x7F, 0x01, 0x01, 0x00, 0x01, 0x00,
    -    		0x80-256, 0x01, 0x00, 0x00, 0x00, 0x00,
    -    		0x81-256, 0x01, 0x02, 0x00, 0x00, 0x08,
    -    		0xBF-256, 0x01,	0x10, 0x00, 0x10, 0x00,
    -    		0xC0-256, 0x01, 0x01, 0x00, 0x00, 0x08,      // SP 10
    -    		0xC1-256, 0x01, 0x00, 0x00, 0x01, 0x00,
    -    		0xC4-256, 0x01, 0x00, 0x00, 0x00, 0x00,
    -    		0xCB-256, 0x01, 0x38, 0x63, 0x00, 0x00,
    -    		0xCD-256, 0x01, 0x00, 0x00,	0x00, 0x00,
    -    		0xCE-256, 0x01, 0x00, 0x00, 0x00, 0x00,      // SP 15
    -    		0xD0-256, 0x01, 0x00, 0x00, 0x00, 0x00,
    -    		0xD1-256, 0x01, 0x00, 0x00, 0x00, 0x00,
    -    		0xD7-256, 0x01, 0x00, 0x00, 0x00, 0x00,
    -    		0xFF-256, 0x01, 0x18, 0x00, 0x18, 0x00,
    -    		0x01, 0x02, 0x02, 0x00, 0x00, 0x08,
    -    		0x3F, 0x02, 0x00, 0x00,	0x02, 0x00,          // SP 21
    -
    -    		// Complex data follows
    -
    -    		// Complex data for Array #325
    -    		// Array header
    -    		0x22, 0x00, 0x22, 0x00, 0xF0-256, 0xFF-256,
    -    		// Array data
    -    		0x18, 0x00, 0x28, 0x00, 0x04, 0x00, 0x34,
    -    		0x00, 0x04, 0x00, 0x28, 0x00, 0x04, 0x00,
    -    		0x1C, 0x00, 0x04, 0x00, 0x10, 0x00, 0x04, 0x00, 0x04, 0x00, 0x10,
    -    		0x00, 0x00, 0x00, 0x1C, 0x00,
    -    		0x04, 0x00, 0x28, 0x00, 0x10, 0x00, 0x34, 0x00, 0x18, 0x00, 0x3C,
    -    		0x00, 0x24, 0x00, 0x44, 0x00,
    -    		0x30, 0x00, 0x48, 0x00, 0x3C, 0x00, 0x44, 0x00, 0x48, 0x00, 0x3C,
    -    		0x00, 0x54, 0x00, 0x38, 0x00,
    -    		0x60, 0x00, 0x2C, 0x00, 0x70, 0x00, 0x20, 0x00, 0x78, 0x00,
    -    		0x14, 0x00, 0x80-256, 0x00, 0x08, 0x00,
    -    		0x84-256, 0x00, 0x04, 0x00, 0x78, 0x00, 0x04, 0x00, 0x6C, 0x00,
    -    		0x04, 0x00, 0x60, 0x00, 0x04, 0x00,
    -    		0x54, 0x00, 0x08, 0x00, 0x48, 0x00, 0x0C, 0x00, 0x3C, 0x00, 0x0C,
    -    		0x00, 0x30, 0x00, 0x08, 0x00,
    -    		0x3C, 0x00, 0x08, 0x00, 0x48, 0x00, 0x08, 0x00, 0x54, 0x00, 0x00,
    -    		0x00, 0x48, 0x00, 0x00, 0x00,
    -    		0x3C, 0x00, 0x00, 0x00, 0x30, 0x00, 0x04, 0x00, 0x24, 0x00,
    -    		// Complex data for Array #326
    -    		// Array header
    -    		0x45, 0x00, 0x48, 0x00, 0x02, 0x00,
    -    		// Array data
    -    		0x00, 0x40, 0x00, 0xB0-256, 0x01, 0x00, 0x00, 0xB0-256, 0x01, 0x00,
    -    		0x00, 0xB0-256, 0x01, 0x00, 0x00, 0xB0-256,
    -    		0x01, 0x00, 0x00, 0xB0-256, 0x01, 0x00, 0x00, 0xB0-256, 0x01, 0x00,
    -    		0x00, 0xB0-256, 0x01, 0x00, 0x00, 0xB0-256,
    -    		0x01, 0x00, 0x00, 0xB0-256, 0x01, 0x00, 0x00, 0xB0-256, 0x01, 0x00,
    -    		0x00, 0xB0-256, 0x01, 0x00, 0x00, 0xB0-256,
    -    		0x01, 0x00, 0x00, 0xB0-256, 0x01, 0x00, 0x00, 0xB0-256, 0x01, 0x00,
    -    		0x00, 0xB0-256, 0x01, 0x00, 0x00, 0xB0-256,
    -    		0x01, 0x00, 0x00, 0xB0-256, 0x01, 0x00, 0x00, 0xB0-256, 0x01, 0x00,
    -    		0x00, 0xB0-256, 0x01, 0x00, 0x00, 0xB0-256,
    -    		0x01, 0x00, 0x00, 0xB0-256, 0x01, 0x00, 0x00, 0xB0-256, 0x01, 0x00,
    -    		0x00, 0xB0-256, 0x01, 0x00, 0x00, 0xB0-256,
    -    		0x01, 0x00, 0x00, 0xB0-256, 0x01, 0x00, 0x00, 0xB0-256, 0x01, 0x00,
    -    		0x00, 0xB0-256, 0x01, 0x00, 0x00, 0xB0-256,
    -    		0x01, 0x00, 0x00, 0xB0-256, 0x01, 0x00, 0x00, 0xB0-256, 0x01, 0x00,
    -    		0x00, 0xB0-256, 0x01, 0x00, 0x00, 0xB0-256,
    -    		0x01, 0x00, 0x00, 0xB0-256, 0x01, 0x00, 0x00, 0xB0-256, 0x00, 0x80-256
    -    	};
    -
    -    	// Create the record
    -        EscherOptRecord r = new EscherOptRecord();
    -        int filled = r.fillFields( data, new DefaultEscherRecordFactory() );
    -
    -        // Check it's the right length
    -        assertEquals(data.length, filled);
    -        assertEquals(data.length, r.getRecordSize());
    -
    -        // Serialise it
    -        byte[] dest = new byte[data.length];
    -        int written = r.serialize(0, dest);
    -
    -        // Check it serialised it back to the same data
    -        assertEquals(data.length, written);
    -        for(int i=0; i props = f.createProperties( data, 0, (short)3 );
    -        EscherComplexProperty p1 = (EscherComplexProperty) props.get( 0 );
    -        assertEquals( (short)0xC141, p1.getId() );
    -        assertEquals( "[01, 02, 03]", HexDump.toHex( p1.getComplexData() ) );
    -
    -        EscherComplexProperty p3 = (EscherComplexProperty) props.get( 2 );
    -        assertEquals( (short)0xC141, p3.getId() );
    -        assertEquals( "[01, 02, 03]", HexDump.toHex( p3.getComplexData() ) );
    -    }
    -}
    -
    diff --git a/src/testcases/org/apache/poi/ddf/TestEscherSpRecord.java b/src/testcases/org/apache/poi/ddf/TestEscherSpRecord.java
    deleted file mode 100644
    index f0daf07bd..000000000
    --- a/src/testcases/org/apache/poi/ddf/TestEscherSpRecord.java
    +++ /dev/null
    @@ -1,77 +0,0 @@
    -/* ====================================================================
    -   Licensed to the Apache Software Foundation (ASF) under one or more
    -   contributor license agreements.  See the NOTICE file distributed with
    -   this work for additional information regarding copyright ownership.
    -   The ASF licenses this file to You under the Apache License, Version 2.0
    -   (the "License"); you may not use this file except in compliance with
    -   the License.  You may obtain a copy of the License at
    -
    -       http://www.apache.org/licenses/LICENSE-2.0
    -
    -   Unless required by applicable law or agreed to in writing, software
    -   distributed under the License is distributed on an "AS IS" BASIS,
    -   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    -   See the License for the specific language governing permissions and
    -   limitations under the License.
    -==================================================================== */
    -
    -package org.apache.poi.ddf;
    -
    -import junit.framework.TestCase;
    -import org.apache.poi.util.HexDump;
    -import org.apache.poi.util.HexRead;
    -
    -public class TestEscherSpRecord extends TestCase
    -{
    -    public void testSerialize() {
    -        EscherSpRecord r = createRecord();
    -
    -        byte[] data = new byte[16];
    -        int bytesWritten = r.serialize( 0, data, new NullEscherSerializationListener() );
    -        assertEquals( 16, bytesWritten );
    -        assertEquals( "[02, 00, " +
    -                "0A, F0, " +
    -                "08, 00, 00, 00, " +
    -                "00, 04, 00, 00, " +
    -                "05, 00, 00, 00]",
    -                HexDump.toHex( data ) );
    -    }
    -
    -    public void testFillFields() {
    -        String hexData = "02 00 " +
    -                "0A F0 " +
    -                "08 00 00 00 " +
    -                "00 04 00 00 " +
    -                "05 00 00 00 ";
    -        byte[] data = HexRead.readFromString( hexData );
    -        EscherSpRecord r = new EscherSpRecord();
    -        int bytesWritten = r.fillFields( data, new DefaultEscherRecordFactory() );
    -
    -        assertEquals( 16, bytesWritten );
    -        assertEquals( 0x0400, r.getShapeId() );
    -        assertEquals( 0x05, r.getFlags() );
    -    }
    -
    -    public void testToString() {
    -        String nl = System.getProperty("line.separator");
    -
    -        String expected = "org.apache.poi.ddf.EscherSpRecord:" + nl +
    -                "  RecordId: 0xF00A" + nl +
    -                "  Version: 0x0002" + nl +
    -                "  ShapeType: 0x0000" + nl +
    -                "  ShapeId: 1024" + nl +
    -                "  Flags: GROUP|PATRIARCH (0x00000005)" + nl;
    -        assertEquals( expected, createRecord().toString() );
    -    }
    -
    -    private static EscherSpRecord createRecord()
    -    {
    -        EscherSpRecord r = new EscherSpRecord();
    -        r.setOptions( (short) 0x0002 );
    -        r.setRecordId( EscherSpRecord.RECORD_ID );
    -        r.setShapeId(0x0400);
    -        r.setFlags(0x05);
    -        return r;
    -    }
    -
    -}
    diff --git a/src/testcases/org/apache/poi/ddf/TestEscherSpgrRecord.java b/src/testcases/org/apache/poi/ddf/TestEscherSpgrRecord.java
    deleted file mode 100644
    index e70934ec9..000000000
    --- a/src/testcases/org/apache/poi/ddf/TestEscherSpgrRecord.java
    +++ /dev/null
    @@ -1,84 +0,0 @@
    -/* ====================================================================
    -   Licensed to the Apache Software Foundation (ASF) under one or more
    -   contributor license agreements.  See the NOTICE file distributed with
    -   this work for additional information regarding copyright ownership.
    -   The ASF licenses this file to You under the Apache License, Version 2.0
    -   (the "License"); you may not use this file except in compliance with
    -   the License.  You may obtain a copy of the License at
    -
    -       http://www.apache.org/licenses/LICENSE-2.0
    -
    -   Unless required by applicable law or agreed to in writing, software
    -   distributed under the License is distributed on an "AS IS" BASIS,
    -   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    -   See the License for the specific language governing permissions and
    -   limitations under the License.
    -==================================================================== */
    -
    -package org.apache.poi.ddf;
    -
    -import junit.framework.TestCase;
    -import org.apache.poi.util.HexDump;
    -import org.apache.poi.util.HexRead;
    -
    -public final class TestEscherSpgrRecord extends TestCase {
    -    public void testSerialize() {
    -        EscherSpgrRecord r = createRecord();
    -
    -        byte[] data = new byte[24];
    -        int bytesWritten = r.serialize( 0, data, new NullEscherSerializationListener() );
    -        assertEquals( 24, bytesWritten );
    -        assertEquals( "[10, 00, " +
    -                "09, F0, " +
    -                "10, 00, 00, 00, " +
    -                "01, 00, 00, 00, " +     // x
    -                "02, 00, 00, 00, " +     // y
    -                "03, 00, 00, 00, " +     // width
    -                "04, 00, 00, 00]",     // height
    -                HexDump.toHex( data ) );
    -    }
    -
    -    public void testFillFields() {
    -        String hexData = "10 00 " +
    -                "09 F0 " +
    -                "10 00 00 00 " +
    -                "01 00 00 00 " +
    -                "02 00 00 00 " +
    -                "03 00 00 00 " +
    -                "04 00 00 00 ";
    -        byte[] data = HexRead.readFromString( hexData );
    -        EscherSpgrRecord r = new EscherSpgrRecord();
    -        int bytesWritten = r.fillFields( data, new DefaultEscherRecordFactory() );
    -
    -        assertEquals( 24, bytesWritten );
    -        assertEquals( 1, r.getRectX1() );
    -        assertEquals( 2, r.getRectY1() );
    -        assertEquals( 3, r.getRectX2() );
    -        assertEquals( 4, r.getRectY2() );
    -    }
    -
    -    public void testToString() {
    -
    -        String expected = "org.apache.poi.ddf.EscherSpgrRecord:" + '\n' +
    -                "  RecordId: 0xF009" + '\n' +
    -                "  Version: 0x0000" + '\n' +
    -                "  Instance: 0x0001" + '\n' +
    -                "  RectX: 1" + '\n' +
    -                "  RectY: 2" + '\n' +
    -                "  RectWidth: 3" + '\n' +
    -                "  RectHeight: 4" + '\n';
    -        assertEquals( expected, createRecord().toString() );
    -    }
    -
    -    private static EscherSpgrRecord createRecord()
    -    {
    -        EscherSpgrRecord r = new EscherSpgrRecord();
    -        r.setOptions( (short) 0x0010 );
    -        r.setRecordId( EscherSpgrRecord.RECORD_ID );
    -        r.setRectX1(1);
    -        r.setRectY1(2);
    -        r.setRectX2(3);
    -        r.setRectY2(4);
    -        return r;
    -    }
    -}
    diff --git a/src/testcases/org/apache/poi/ddf/TestEscherSplitMenuColorsRecord.java b/src/testcases/org/apache/poi/ddf/TestEscherSplitMenuColorsRecord.java
    deleted file mode 100644
    index 60facfb33..000000000
    --- a/src/testcases/org/apache/poi/ddf/TestEscherSplitMenuColorsRecord.java
    +++ /dev/null
    @@ -1,84 +0,0 @@
    -/* ====================================================================
    -   Licensed to the Apache Software Foundation (ASF) under one or more
    -   contributor license agreements.  See the NOTICE file distributed with
    -   this work for additional information regarding copyright ownership.
    -   The ASF licenses this file to You under the Apache License, Version 2.0
    -   (the "License"); you may not use this file except in compliance with
    -   the License.  You may obtain a copy of the License at
    -
    -       http://www.apache.org/licenses/LICENSE-2.0
    -
    -   Unless required by applicable law or agreed to in writing, software
    -   distributed under the License is distributed on an "AS IS" BASIS,
    -   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    -   See the License for the specific language governing permissions and
    -   limitations under the License.
    -==================================================================== */
    -
    -package org.apache.poi.ddf;
    -
    -import junit.framework.TestCase;
    -import org.apache.poi.util.HexDump;
    -import org.apache.poi.util.HexRead;
    -
    -public final class TestEscherSplitMenuColorsRecord extends TestCase {
    -    public void testSerialize() {
    -        EscherSplitMenuColorsRecord r = createRecord();
    -
    -        byte[] data = new byte[24];
    -        int bytesWritten = r.serialize( 0, data, new NullEscherSerializationListener() );
    -        assertEquals( 24, bytesWritten );
    -        assertEquals( "[40, 00, " +
    -                "1E, F1, " +
    -                "10, 00, 00, 00, " +
    -                "02, 04, 00, 00, " +
    -                "02, 00, 00, 00, " +
    -                "02, 00, 00, 00, " +
    -                "01, 00, 00, 00]",
    -                HexDump.toHex( data ) );
    -    }
    -
    -    public void testFillFields() {
    -        String hexData = "40 00 " +
    -                "1E F1 " +
    -                "10 00 00 00 " +
    -                "02 04 00 00 " +
    -                "02 00 00 00 " +
    -                "02 00 00 00 " +
    -                "01 00 00 00 ";
    -        byte[] data = HexRead.readFromString( hexData );
    -        EscherSplitMenuColorsRecord r = new EscherSplitMenuColorsRecord();
    -        int bytesWritten = r.fillFields( data, new DefaultEscherRecordFactory() );
    -
    -        assertEquals( 24, bytesWritten );
    -        assertEquals( 0x0402, r.getColor1() );
    -        assertEquals( 0x02, r.getColor2() );
    -        assertEquals( 0x02, r.getColor3() );
    -        assertEquals( 0x01, r.getColor4() );
    -    }
    -
    -    public void testToString() {
    -        String expected = "org.apache.poi.ddf.EscherSplitMenuColorsRecord:" + '\n' +
    -                "  RecordId: 0xF11E" + '\n' +
    -                "  Version: 0x0000" + '\n' +
    -                "  Instance: 0x0004" + '\n' +
    -                "  Color1: 0x00000402" + '\n' +
    -                "  Color2: 0x00000002" + '\n' +
    -                "  Color3: 0x00000002" + '\n' +
    -                "  Color4: 0x00000001" + '\n' +
    -                "";
    -        assertEquals( expected, createRecord().toString() );
    -    }
    -
    -    private static EscherSplitMenuColorsRecord createRecord()
    -    {
    -        EscherSplitMenuColorsRecord r = new EscherSplitMenuColorsRecord();
    -        r.setOptions( (short) 0x0040 );
    -        r.setRecordId( EscherSplitMenuColorsRecord.RECORD_ID );
    -        r.setColor1( 0x402  );
    -        r.setColor2( 0x2 );
    -        r.setColor3( 0x2 );
    -        r.setColor4( 0x1 );
    -        return r;
    -    }
    -}
    diff --git a/src/testcases/org/apache/poi/ddf/TestUnknownEscherRecord.java b/src/testcases/org/apache/poi/ddf/TestUnknownEscherRecord.java
    deleted file mode 100644
    index b42c98c6c..000000000
    --- a/src/testcases/org/apache/poi/ddf/TestUnknownEscherRecord.java
    +++ /dev/null
    @@ -1,156 +0,0 @@
    -/* ====================================================================
    -   Licensed to the Apache Software Foundation (ASF) under one or more
    -   contributor license agreements.  See the NOTICE file distributed with
    -   this work for additional information regarding copyright ownership.
    -   The ASF licenses this file to You under the Apache License, Version 2.0
    -   (the "License"); you may not use this file except in compliance with
    -   the License.  You may obtain a copy of the License at
    -
    -       http://www.apache.org/licenses/LICENSE-2.0
    -
    -   Unless required by applicable law or agreed to in writing, software
    -   distributed under the License is distributed on an "AS IS" BASIS,
    -   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    -   See the License for the specific language governing permissions and
    -   limitations under the License.
    -==================================================================== */
    -
    -package org.apache.poi.ddf;
    -
    -import junit.framework.TestCase;
    -import org.apache.poi.util.HexRead;
    -import org.apache.poi.util.HexDump;
    -
    -public final class TestUnknownEscherRecord extends TestCase {
    -    public void testFillFields() {
    -        String testData =
    -                "0F 02 " + // options
    -                "11 F1 " + // record id
    -                "00 00 00 00";      // remaining bytes
    -
    -        UnknownEscherRecord r = new UnknownEscherRecord();
    -        EscherRecordFactory factory = new DefaultEscherRecordFactory();
    -        r.fillFields( HexRead.readFromString( testData ), factory );
    -
    -        assertEquals( 0x020F, r.getOptions() );
    -        assertEquals( (short) 0xF111, r.getRecordId() );
    -        assertTrue( r.isContainerRecord() );
    -        assertEquals( 8, r.getRecordSize() );
    -        assertEquals( 0, r.getChildRecords().size() );
    -        assertEquals( 0, r.getData().length );
    -
    -        testData =
    -                "00 02 " + // options
    -                "11 F1 " + // record id
    -                "04 00 00 00 " + // remaining bytes
    -                "01 02 03 04";
    -
    -        r = new UnknownEscherRecord();
    -        r.fillFields( HexRead.readFromString( testData ), factory );
    -
    -        assertEquals( 0x0200, r.getOptions() );
    -        assertEquals( (short) 0xF111, r.getRecordId() );
    -        assertEquals( 12, r.getRecordSize() );
    -        assertFalse( r.isContainerRecord() );
    -        assertEquals( 0, r.getChildRecords().size() );
    -        assertEquals( 4, r.getData().length );
    -        assertEquals( 1, r.getData()[0] );
    -        assertEquals( 2, r.getData()[1] );
    -        assertEquals( 3, r.getData()[2] );
    -        assertEquals( 4, r.getData()[3] );
    -
    -        testData =
    -                "0F 02 " + // options
    -                "11 F1 " + // record id
    -                "08 00 00 00 " + // remaining bytes
    -                "00 02 " + // options
    -                "FF FF " + // record id
    -                "00 00 00 00";      // remaining bytes
    -
    -        r = new UnknownEscherRecord();
    -        r.fillFields( HexRead.readFromString( testData ), factory );
    -
    -        assertEquals( 0x020F, r.getOptions() );
    -        assertEquals( (short) 0xF111, r.getRecordId() );
    -        assertEquals( 8, r.getRecordSize() );
    -        assertTrue( r.isContainerRecord() );
    -        assertEquals( 1, r.getChildRecords().size() );
    -        assertEquals( (short) 0xFFFF, r.getChild( 0 ).getRecordId() );
    -        
    -        //Add by Zhang Zhang test error situation when remaining bytes > avalible bytes
    -        testData =
    -            "00 02 " + // options
    -            "11 F1 " + // record id
    -            "05 00 00 00 " + // remaining bytes
    -            "01 02 03 04";
    -
    -	    r = new UnknownEscherRecord();
    -	    r.fillFields( HexRead.readFromString( testData ), factory );
    -	
    -	    assertEquals( 0x0200, r.getOptions() );
    -	    assertEquals( (short) 0xF111, r.getRecordId() );
    -	    assertEquals( 12, r.getRecordSize() );
    -	    assertFalse( r.isContainerRecord() );
    -	    assertEquals( 0, r.getChildRecords().size() );
    -	    assertEquals( 4, r.getData().length );
    -	    assertEquals( 1, r.getData()[0] );
    -	    assertEquals( 2, r.getData()[1] );
    -	    assertEquals( 3, r.getData()[2] );
    -	    assertEquals( 4, r.getData()[3] );
    -	    
    -        testData =
    -            "0F 02 " + // options
    -            "11 F1 " + // record id
    -            "09 00 00 00 " + // remaining bytes
    -            "00 02 " + // options
    -            "FF FF " + // record id
    -            "00 00 00 00";      // remaining bytes
    -
    -	    r = new UnknownEscherRecord();
    -	    r.fillFields( HexRead.readFromString( testData ), factory );
    -	
    -	    assertEquals( 0x020F, r.getOptions() );
    -	    assertEquals( (short) 0xF111, r.getRecordId() );
    -	    assertEquals( 8, r.getRecordSize() );
    -	    assertTrue( r.isContainerRecord() );
    -	    assertEquals( 1, r.getChildRecords().size() );
    -	    assertEquals( (short) 0xFFFF, r.getChild( 0 ).getRecordId() );
    -    }
    -
    -    public void testSerialize() {
    -        UnknownEscherRecord r = new UnknownEscherRecord();
    -        r.setOptions( (short) 0x1234 );
    -        r.setRecordId( (short) 0xF112 );
    -        byte[] data = new byte[8];
    -        r.serialize( 0, data, new NullEscherSerializationListener() );
    -
    -        assertEquals( "[34, 12, 12, F1, 00, 00, 00, 00]", HexDump.toHex( data ) );
    -
    -        EscherRecord childRecord = new UnknownEscherRecord();
    -        childRecord.setOptions( (short) 0x9999 );
    -        childRecord.setRecordId( (short) 0xFF01 );
    -        r.addChildRecord( childRecord );
    -        r.setOptions( (short) 0x123F );
    -        data = new byte[16];
    -        r.serialize( 0, data, new NullEscherSerializationListener() );
    -
    -        assertEquals( "[3F, 12, 12, F1, 08, 00, 00, 00, 99, 99, 01, FF, 00, 00, 00, 00]", HexDump.toHex( data ) );
    -    }
    -
    -    public void testToString() {
    -        UnknownEscherRecord r = new UnknownEscherRecord();
    -        r.setOptions( (short) 0x1234 );
    -        r.setRecordId( (short) 0xF112 );
    -        byte[] data = new byte[8];
    -        r.serialize( 0, data, new NullEscherSerializationListener() );
    -
    -        assertEquals( "org.apache.poi.ddf.UnknownEscherRecord:" + '\n' +
    -                "  isContainer: false" + '\n' +
    -                "  version: 0x0004" + '\n' +
    -                "  instance: 0x0123" + '\n' +
    -                "  recordId: 0xF112" + '\n' +
    -                "  numchildren: 0" + '\n' +
    -                ": 0"
    -                , r.toString() );
    -    }
    -}
    diff --git a/src/testcases/org/apache/poi/hpsf/TestVariantSupport.java b/src/testcases/org/apache/poi/hpsf/TestVariantSupport.java
    deleted file mode 100644
    index 3b6354e4d..000000000
    --- a/src/testcases/org/apache/poi/hpsf/TestVariantSupport.java
    +++ /dev/null
    @@ -1,88 +0,0 @@
    -/*
    - *  ====================================================================
    - *    Licensed to the Apache Software Foundation (ASF) under one or more
    - *    contributor license agreements.  See the NOTICE file distributed with
    - *    this work for additional information regarding copyright ownership.
    - *    The ASF licenses this file to You under the Apache License, Version 2.0
    - *    (the "License"); you may not use this file except in compliance with
    - *    the License.  You may obtain a copy of the License at
    - *
    - *        http://www.apache.org/licenses/LICENSE-2.0
    - *
    - *    Unless required by applicable law or agreed to in writing, software
    - *    distributed under the License is distributed on an "AS IS" BASIS,
    - *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    - *    See the License for the specific language governing permissions and
    - *    limitations under the License.
    - * ====================================================================
    - */
    -package org.apache.poi.hpsf;
    -
    -import junit.framework.TestCase;
    -import org.apache.poi.hpsf.wellknown.PropertyIDMap;
    -import org.apache.poi.util.HexRead;
    -
    -import java.io.ByteArrayInputStream;
    -
    -/**
    - * @author Yegor Kozlov
    - */
    -public class TestVariantSupport extends TestCase {
    -
    -    public void test52337() throws Exception {
    -        // document summary stream   from test1-excel.doc attached to Bugzilla 52337
    -        String hex =
    -                "FE FF 00 00 05 01 02 00 00 00 00 00 00 00 00 00 00 00 00 00" +
    -                "00 00 00 00 02 00 00 00 02 D5 CD D5 9C 2E 1B 10 93 97 08 00" +
    -                "2B 2C F9 AE 44 00 00 00 05 D5 CD D5 9C 2E 1B 10 93 97 08 00" +
    -                "2B 2C F9 AE 58 01 00 00 14 01 00 00 0C 00 00 00 01 00 00 00" +
    -                "68 00 00 00 0F 00 00 00 70 00 00 00 05 00 00 00 98 00 00 00" +
    -                "06 00 00 00 A0 00 00 00 11 00 00 00 A8 00 00 00 17 00 00 00" +
    -                "B0 00 00 00 0B 00 00 00 B8 00 00 00 10 00 00 00 C0 00 00 00" +
    -                "13 00 00 00 C8 00 00 00 16 00 00 00 D0 00 00 00 0D 00 00 00" +
    -                "D8 00 00 00 0C 00 00 00 F3 00 00 00 02 00 00 00 E4 04 00 00" +
    -                "1E 00 00 00 20 00 00 00 44 65 70 61 72 74 6D 65 6E 74 20 6F" +
    -                "66 20 49 6E 74 65 72 6E 61 6C 20 41 66 66 61 69 72 73 00 00" +
    -                "03 00 00 00 05 00 00 00 03 00 00 00 01 00 00 00 03 00 00 00" +
    -                "47 03 00 00 03 00 00 00 0F 27 0B 00 0B 00 00 00 00 00 00 00" +
    -                "0B 00 00 00 00 00 00 00 0B 00 00 00 00 00 00 00 0B 00 00 00" +
    -                "00 00 00 00 1E 10 00 00 01 00 00 00 0F 00 00 00 54 68 69 73" +
    -                "20 69 73 20 61 20 74 65 73 74 00 0C 10 00 00 02 00 00 00 1E" +
    -                "00 00 00 06 00 00 00 54 69 74 6C 65 00 03 00 00 00 01 00 00" +
    -                "00 00 00 00 A8 00 00 00 03 00 00 00 00 00 00 00 20 00 00 00" +
    -                "01 00 00 00 38 00 00 00 02 00 00 00 40 00 00 00 01 00 00 00" +
    -                "02 00 00 00 0C 00 00 00 5F 50 49 44 5F 48 4C 49 4E 4B 53 00" +
    -                "02 00 00 00 E4 04 00 00 41 00 00 00 60 00 00 00 06 00 00 00" +
    -                "03 00 00 00 74 00 74 00 03 00 00 00 09 00 00 00 03 00 00 00" +
    -                "00 00 00 00 03 00 00 00 05 00 00 00 1F 00 00 00 0C 00 00 00" +
    -                "4E 00 6F 00 72 00 6D 00 61 00 6C 00 32 00 2E 00 78 00 6C 00" +
    -                "73 00 00 00 1F 00 00 00 0A 00 00 00 53 00 68 00 65 00 65 00" +
    -                "74 00 31 00 21 00 44 00 32 00 00 00 ";
    -        byte[] bytes = HexRead.readFromString(hex);
    -
    -        PropertySet ps = PropertySetFactory.create(new ByteArrayInputStream(bytes));
    -        DocumentSummaryInformation dsi = (DocumentSummaryInformation) ps;
    -        Section s = dsi.getSections().get(0);
    -
    -        Object hdrs =  s.getProperty(PropertyIDMap.PID_HEADINGPAIR);
    -
    -        assertNotNull("PID_HEADINGPAIR was not found", hdrs);
    -        
    -        assertTrue("PID_HEADINGPAIR: expected byte[] but was "+ hdrs.getClass(), hdrs instanceof byte[]);
    -        // parse the value
    -        Vector v = new Vector((short)Variant.VT_VARIANT);
    -        v.read((byte[])hdrs, 0);
    -
    -        TypedPropertyValue[] items = v.getValues();
    -        assertEquals(2, items.length);
    -
    -        assertNotNull(items[0].getValue());
    -        assertTrue("first item must be CodePageString but was "+ items[0].getValue().getClass(),
    -                items[0].getValue() instanceof CodePageString);
    -        assertNotNull(items[1].getValue());
    -        assertTrue("second item must be Integer but was "+ items[1].getValue().getClass(),
    -                items[1].getValue() instanceof Integer);
    -        assertEquals(1, (int)(Integer)items[1].getValue());
    -
    -    }
    -}
    diff --git a/src/testcases/org/apache/poi/hpsf/basic/AllDataFilesTester.java b/src/testcases/org/apache/poi/hpsf/basic/AllDataFilesTester.java
    deleted file mode 100644
    index a0db23085..000000000
    --- a/src/testcases/org/apache/poi/hpsf/basic/AllDataFilesTester.java
    +++ /dev/null
    @@ -1,74 +0,0 @@
    -/* ====================================================================
    -   Licensed to the Apache Software Foundation (ASF) under one or more
    -   contributor license agreements.  See the NOTICE file distributed with
    -   this work for additional information regarding copyright ownership.
    -   The ASF licenses this file to You under the Apache License, Version 2.0
    -   (the "License"); you may not use this file except in compliance with
    -   the License.  You may obtain a copy of the License at
    -
    -       http://www.apache.org/licenses/LICENSE-2.0
    -
    -   Unless required by applicable law or agreed to in writing, software
    -   distributed under the License is distributed on an "AS IS" BASIS,
    -   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    -   See the License for the specific language governing permissions and
    -   limitations under the License.
    -==================================================================== */
    -
    -package org.apache.poi.hpsf.basic;
    -
    -import org.apache.poi.POIDataSamples;
    -
    -import java.io.File;
    -import java.io.FileFilter;
    -import java.util.logging.Logger;
    -
    -/**
    - * 

    Processes a test method for all OLE2 files in the HPSF test data - * directory. Well, this class does not check whether a file is an OLE2 file but - * rather whether its name begins with "Test".

    - */ -public class AllDataFilesTester { - private static final POIDataSamples _samples = POIDataSamples.getHPSFInstance(); - - /** - *

    Interface specifying how to run a test on a single file.

    - */ - public interface TestTask - { - /** - *

    Executes a test on a single file.

    - * - * @param file the file - * @throws Throwable if the method throws anything. - */ - void runTest(File file) throws Throwable; - } - - /** - *

    Tests the simplified custom properties.

    - * - * @param task the task to execute - * @throws Throwable - */ - public void runTests(final TestTask task) throws Throwable - { - POIDataSamples _samples = POIDataSamples.getHPSFInstance(); - final File dataDir = _samples.getFile(""); - final File[] docs = dataDir.listFiles(new FileFilter() - { - @Override - public boolean accept(final File file) - { - return file.isFile() && file.getName().startsWith("Test"); - }}); - for (final File doc : docs) { - final Logger logger = Logger.getLogger(getClass().getName()); - logger.info("Processing file \" " + doc.toString() + "\"."); - - /* Execute the test task. */ - task.runTest(doc); - } - } - -} diff --git a/src/testcases/org/apache/poi/hpsf/basic/AllPOIHPSFBasicTests.java b/src/testcases/org/apache/poi/hpsf/basic/AllPOIHPSFBasicTests.java deleted file mode 100644 index dbb56451a..000000000 --- a/src/testcases/org/apache/poi/hpsf/basic/AllPOIHPSFBasicTests.java +++ /dev/null @@ -1,37 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hpsf.basic; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -/** - * Test suite for org.apache.poi.hpsf.basic - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestBasic.class, - TestClassID.class, - TestEmptyProperties.class, - TestHPSFBugs.class, - TestMetaDataIPI.class, - TestUnicode.class, - TestWrite.class, - TestWriteWellKnown.class -}) -public class AllPOIHPSFBasicTests { -} diff --git a/src/testcases/org/apache/poi/hpsf/basic/POIFile.java b/src/testcases/org/apache/poi/hpsf/basic/POIFile.java deleted file mode 100644 index 9db2a97a9..000000000 --- a/src/testcases/org/apache/poi/hpsf/basic/POIFile.java +++ /dev/null @@ -1,93 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hpsf.basic; - -import org.apache.poi.poifs.filesystem.POIFSDocumentPath; - -/** - *

    A POI file just for testing.

    - */ -public class POIFile -{ - - private String name; - private POIFSDocumentPath path; - private byte[] bytes; - - - /** - *

    Sets the POI file's name.

    - * - * @param name The POI file's name. - */ - public void setName(final String name) - { - this.name = name; - } - - /** - *

    Returns the POI file's name.

    - * - * @return The POI file's name. - */ - public String getName() - { - return name; - } - - /** - *

    Sets the POI file's path.

    - * - * @param path The POI file's path. - */ - public void setPath(final POIFSDocumentPath path) - { - this.path = path; - } - - /** - *

    Returns the POI file's path.

    - * - * @return The POI file's path. - */ - public POIFSDocumentPath getPath() - { - return path; - } - - /** - *

    Sets the POI file's content bytes.

    - * - * @param bytes The POI file's content bytes. - */ - public void setBytes(final byte[] bytes) - { - this.bytes = bytes; - } - - /** - *

    Returns the POI file's content bytes.

    - * - * @return The POI file's content bytes. - */ - public byte[] getBytes() - { - return bytes; - } - -} diff --git a/src/testcases/org/apache/poi/hpsf/basic/TestBasic.java b/src/testcases/org/apache/poi/hpsf/basic/TestBasic.java deleted file mode 100644 index b40e7a463..000000000 --- a/src/testcases/org/apache/poi/hpsf/basic/TestBasic.java +++ /dev/null @@ -1,201 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hpsf.basic; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.UnsupportedEncodingException; -import java.util.List; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hpsf.DocumentSummaryInformation; -import org.apache.poi.hpsf.HPSFException; -import org.apache.poi.hpsf.MarkUnsupportedException; -import org.apache.poi.hpsf.NoPropertySetStreamException; -import org.apache.poi.hpsf.PropertySet; -import org.apache.poi.hpsf.PropertySetFactory; -import org.apache.poi.hpsf.Section; -import org.apache.poi.hpsf.SummaryInformation; -import org.apache.poi.hpsf.wellknown.SectionIDMap; -import org.junit.Before; -import org.junit.Test; - -/** - *

    Tests the basic HPSF functionality.

    - */ -public final class TestBasic { - - private static final String POI_FS = "TestGermanWord90.doc"; - private static final String[] POI_FILES = new String[] - { - "\005SummaryInformation", - "\005DocumentSummaryInformation", - "WordDocument", - "\001CompObj", - "1Table" - }; - private static final int BYTE_ORDER = 0xfffe; - private static final int FORMAT = 0x0000; - private static final int OS_VERSION = 0x00020A04; - private static final byte[] CLASS_ID = - { - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00 - }; - private static final int[] SECTION_COUNT = - {1, 2}; - private static final boolean[] IS_SUMMARY_INFORMATION = - {true, false}; - private static final boolean[] IS_DOCUMENT_SUMMARY_INFORMATION = - {false, true}; - - private POIFile[] poiFiles; - - - /** - *

    Read a the test file from the "data" directory.

    - * - * @exception FileNotFoundException if the file to be read does not exist. - * @exception IOException if any other I/O exception occurs. - */ - @Before - public void setUp() throws IOException - { - POIDataSamples samples = POIDataSamples.getHPSFInstance(); - final File data = samples.getFile(POI_FS); - poiFiles = Util.readPOIFiles(data); - } - - /** - *

    Checks the names of the files in the POI filesystem. They - * are expected to be in a certain order.

    - */ - @Test - public void testReadFiles() - { - String[] expected = POI_FILES; - for (int i = 0; i < expected.length; i++) - assertEquals(poiFiles[i].getName(), expected[i]); - } - - /** - *

    Tests whether property sets can be created from the POI - * files in the POI file system. This test case expects the first - * file to be a {@link SummaryInformation}, the second file to be - * a {@link DocumentSummaryInformation} and the rest to be no - * property sets. In the latter cases a {@link - * NoPropertySetStreamException} will be thrown when trying to - * create a {@link PropertySet}.

    - * - * @exception IOException if an I/O exception occurs. - * - * @exception UnsupportedEncodingException if a character encoding is not - * supported. - */ - @Test - public void testCreatePropertySets() - throws UnsupportedEncodingException, IOException - { - Class[] expected = new Class[] - { - SummaryInformation.class, - DocumentSummaryInformation.class, - NoPropertySetStreamException.class, - NoPropertySetStreamException.class, - NoPropertySetStreamException.class - }; - for (int i = 0; i < expected.length; i++) - { - InputStream in = new ByteArrayInputStream(poiFiles[i].getBytes()); - Object o; - try - { - o = PropertySetFactory.create(in); - } - catch (NoPropertySetStreamException ex) - { - o = ex; - } - catch (MarkUnsupportedException ex) - { - o = ex; - } - in.close(); - assertEquals(expected[i], o.getClass()); - } - } - - /** - *

    Tests the {@link PropertySet} methods. The test file has two - * property sets: the first one is a {@link SummaryInformation}, - * the second one is a {@link DocumentSummaryInformation}.

    - * - * @exception IOException if an I/O exception occurs - * @exception HPSFException if any HPSF exception occurs - */ - @Test - public void testPropertySetMethods() throws IOException, HPSFException - { - /* Loop over the two property sets. */ - for (int i = 0; i < 2; i++) - { - byte[] b = poiFiles[i].getBytes(); - PropertySet ps = PropertySetFactory.create(new ByteArrayInputStream(b)); - assertEquals(BYTE_ORDER, ps.getByteOrder()); - assertEquals(FORMAT, ps.getFormat()); - assertEquals(OS_VERSION, ps.getOSVersion()); - assertArrayEquals(CLASS_ID, ps.getClassID().getBytes()); - assertEquals(SECTION_COUNT[i], ps.getSectionCount()); - assertEquals(IS_SUMMARY_INFORMATION[i], ps.isSummaryInformation()); - assertEquals(IS_DOCUMENT_SUMMARY_INFORMATION[i], ps.isDocumentSummaryInformation()); - } - } - - /** - *

    Tests the {@link Section} methods. The test file has two - * property sets: the first one is a {@link SummaryInformation}, - * the second one is a {@link DocumentSummaryInformation}.

    - * - * @exception IOException if an I/O exception occurs - * @exception HPSFException if any HPSF exception occurs - */ - @Test - public void testSectionMethods() throws IOException, HPSFException - { - final SummaryInformation si = (SummaryInformation) - PropertySetFactory.create(new ByteArrayInputStream - (poiFiles[0].getBytes())); - final List
    sections = si.getSections(); - final Section s = sections.get(0); - assertArrayEquals(s.getFormatID().getBytes(), SectionIDMap.SUMMARY_INFORMATION_ID); - assertNotNull(s.getProperties()); - assertEquals(17, s.getPropertyCount()); - assertEquals("Titel", s.getProperty(2)); - assertEquals(1764, s.getSize()); - } -} diff --git a/src/testcases/org/apache/poi/hpsf/basic/TestClassID.java b/src/testcases/org/apache/poi/hpsf/basic/TestClassID.java deleted file mode 100644 index ed79510f4..000000000 --- a/src/testcases/org/apache/poi/hpsf/basic/TestClassID.java +++ /dev/null @@ -1,124 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hpsf.basic; - -import java.util.Locale; - -import junit.framework.Assert; -import junit.framework.TestCase; - -import org.apache.poi.hpsf.ClassID; -import org.apache.poi.hpsf.DocumentSummaryInformation; -import org.apache.poi.hpsf.PropertySet; -import org.apache.poi.hpsf.SummaryInformation; - -/** - *

    Tests ClassID structure.

    - * - * @author Michael Zalewski (zalewski@optonline.net) - */ -public final class TestClassID extends TestCase { - - /** - * Various tests of overridden .equals() - */ - public void testEquals() - { - ClassID clsidTest1 = new ClassID( - new byte[] {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, - 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10} - , 0 - ); - ClassID clsidTest2 = new ClassID( - new byte[] {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, - 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10} - , 0 - ); - ClassID clsidTest3 = new ClassID( - new byte[] {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, - 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x11 } - , 0 - ); - Assert.assertEquals(clsidTest1, clsidTest1); - Assert.assertEquals(clsidTest1, clsidTest2); - Assert.assertFalse(clsidTest1.equals(clsidTest3)); - Assert.assertFalse(clsidTest1.equals(null)); - } - /** - * Try to write to a buffer that is too small. This should - * throw an Exception - */ - public void testWriteArrayStoreException() - { - ClassID clsidTest = new ClassID( - new byte[] {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, - 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10} - , 0 - ); - boolean bExceptionOccurred = false; - try - { - clsidTest.write(new byte[15], 0); - } - catch (Exception e) - { - bExceptionOccurred = true; - } - Assert.assertTrue(bExceptionOccurred); - - bExceptionOccurred = false; - try - { - clsidTest.write(new byte[16], 1); - } - catch (Exception e) - { - bExceptionOccurred = true; - } - Assert.assertTrue(bExceptionOccurred); - - // These should work without throwing an Exception - bExceptionOccurred = false; - try - { - clsidTest.write(new byte[16], 0); - clsidTest.write(new byte[17], 1); - } - catch (Exception e) - { - bExceptionOccurred = true; - } - Assert.assertFalse(bExceptionOccurred); - } - /** - *

    Tests the {@link PropertySet} methods. The test file has two - * property set: the first one is a {@link SummaryInformation}, - * the second one is a {@link DocumentSummaryInformation}.

    - */ - public void testClassID() - { - ClassID clsidTest = new ClassID( - new byte[] {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, - 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10} - , 0 - ); - Assert.assertEquals(clsidTest.toString().toUpperCase(Locale.ROOT), - "{04030201-0605-0807-090A-0B0C0D0E0F10}" - ); - } -} diff --git a/src/testcases/org/apache/poi/hpsf/basic/TestEmptyProperties.java b/src/testcases/org/apache/poi/hpsf/basic/TestEmptyProperties.java deleted file mode 100644 index 48103b0c9..000000000 --- a/src/testcases/org/apache/poi/hpsf/basic/TestEmptyProperties.java +++ /dev/null @@ -1,163 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hpsf.basic; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.UnsupportedEncodingException; - -import junit.framework.TestCase; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hpsf.DocumentSummaryInformation; -import org.apache.poi.hpsf.HPSFException; -import org.apache.poi.hpsf.MarkUnsupportedException; -import org.apache.poi.hpsf.NoPropertySetStreamException; -import org.apache.poi.hpsf.PropertySet; -import org.apache.poi.hpsf.PropertySetFactory; -import org.apache.poi.hpsf.SummaryInformation; -import org.apache.poi.hpsf.Variant; - -/** - *

    Test case for OLE2 files with empty properties. An empty property's type - * is {@link Variant#VT_EMPTY}.

    - */ -public final class TestEmptyProperties extends TestCase { - - /** - *

    This test file's summary information stream contains some empty - * properties.

    - */ - private static final String POI_FS = "TestCorel.shw"; - - private static final String[] POI_FILES = new String[] - { - "PerfectOffice_MAIN", - "\005SummaryInformation", - "Main" - }; - - private POIFile[] poiFiles; - - /** - *

    Read a the test file from the "data" directory.

    - * - * @exception FileNotFoundException if the file containing the test data - * does not exist - * @exception IOException if an I/O exception occurs - */ - @Override - public void setUp() throws FileNotFoundException, IOException - { - POIDataSamples samples = POIDataSamples.getHPSFInstance(); - final File data = samples.getFile(POI_FS); - - poiFiles = Util.readPOIFiles(data); - } - - /** - *

    Checks the names of the files in the POI filesystem. They - * are expected to be in a certain order.

    - */ - public void testReadFiles() - { - String[] expected = POI_FILES; - for (int i = 0; i < expected.length; i++) - assertEquals(poiFiles[i].getName(), expected[i]); - } - - /** - *

    Tests whether property sets can be created from the POI - * files in the POI file system. This test case expects the first - * file to be a {@link SummaryInformation}, the second file to be - * a {@link DocumentSummaryInformation} and the rest to be no - * property sets. In the latter cases a {@link - * NoPropertySetStreamException} will be thrown when trying to - * create a {@link PropertySet}.

    - * - * @exception IOException if an I/O exception occurs. - * - * @exception UnsupportedEncodingException if a character encoding is not - * supported. - */ - public void testCreatePropertySets() - throws UnsupportedEncodingException, IOException - { - Class[] expected = new Class[] - { - NoPropertySetStreamException.class, - SummaryInformation.class, - NoPropertySetStreamException.class - }; - for (int i = 0; i < expected.length; i++) - { - InputStream in = new ByteArrayInputStream(poiFiles[i].getBytes()); - Object o; - try - { - o = PropertySetFactory.create(in); - } - catch (NoPropertySetStreamException ex) - { - o = ex; - } - catch (MarkUnsupportedException ex) - { - o = ex; - } - in.close(); - assertEquals(o.getClass(), expected[i]); - } - } - - /** - *

    Tests the {@link PropertySet} methods. The test file has two - * property sets: the first one is a {@link SummaryInformation}, - * the second one is a {@link DocumentSummaryInformation}.

    - * - * @exception IOException if an I/O exception occurs - * @exception HPSFException if an HPSF operation fails - */ - public void testPropertySetMethods() throws IOException, HPSFException - { - byte[] b = poiFiles[1].getBytes(); - PropertySet ps = - PropertySetFactory.create(new ByteArrayInputStream(b)); - SummaryInformation s = (SummaryInformation) ps; - assertNull(s.getTitle()); - assertNull(s.getSubject()); - assertNotNull(s.getAuthor()); - assertNull(s.getKeywords()); - assertNull(s.getComments()); - assertNotNull(s.getTemplate()); - assertNotNull(s.getLastAuthor()); - assertNotNull(s.getRevNumber()); - assertEquals(s.getEditTime(), 0); - assertNull(s.getLastPrinted()); - assertNull(s.getCreateDateTime()); - assertNull(s.getLastSaveDateTime()); - assertEquals(s.getPageCount(), 0); - assertEquals(s.getWordCount(), 0); - assertEquals(s.getCharCount(), 0); - assertNull(s.getThumbnail()); - assertNull(s.getApplicationName()); - } -} diff --git a/src/testcases/org/apache/poi/hpsf/basic/TestHPSFBugs.java b/src/testcases/org/apache/poi/hpsf/basic/TestHPSFBugs.java deleted file mode 100644 index 0600ffea9..000000000 --- a/src/testcases/org/apache/poi/hpsf/basic/TestHPSFBugs.java +++ /dev/null @@ -1,173 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hpsf.basic; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.Date; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.POIDocument; -import org.apache.poi.hpsf.DocumentSummaryInformation; -import org.apache.poi.hpsf.HPSFPropertiesOnlyDocument; -import org.apache.poi.hpsf.MarkUnsupportedException; -import org.apache.poi.hpsf.NoPropertySetStreamException; -import org.apache.poi.hpsf.PropertySetFactory; -import org.apache.poi.hpsf.SummaryInformation; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; -import org.junit.Test; - -/** - * Tests various bugs have been fixed - */ -public final class TestHPSFBugs { - private static final POIDataSamples _samples = POIDataSamples.getHPSFInstance(); - - /** - * Ensure that we can create a new HSSF Workbook, - * then add some properties to it, save + - * reload, and still access & change them. - */ - @Test - public void test48832() throws IOException { - HSSFWorkbook wb1 = new HSSFWorkbook(); - - // Starts empty - assertNull(wb1.getDocumentSummaryInformation()); - assertNull(wb1.getSummaryInformation()); - - // Add new properties - wb1.createInformationProperties(); - - assertNotNull(wb1.getDocumentSummaryInformation()); - assertNotNull(wb1.getSummaryInformation()); - - // Set initial values - wb1.getSummaryInformation().setAuthor("Apache POI"); - wb1.getSummaryInformation().setKeywords("Testing POI"); - wb1.getSummaryInformation().setCreateDateTime(new Date(12345)); - - wb1.getDocumentSummaryInformation().setCompany("Apache"); - - - // Save and reload - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - - - // Ensure changes were taken - assertNotNull(wb2.getDocumentSummaryInformation()); - assertNotNull(wb2.getSummaryInformation()); - - assertEquals("Apache POI", wb2.getSummaryInformation().getAuthor()); - assertEquals("Testing POI", wb2.getSummaryInformation().getKeywords()); - assertEquals(12345, wb2.getSummaryInformation().getCreateDateTime().getTime()); - assertEquals("Apache", wb2.getDocumentSummaryInformation().getCompany()); - - - // Set some more, save + reload - wb2.getSummaryInformation().setComments("Resaved"); - - HSSFWorkbook wb3 = HSSFTestDataSamples.writeOutAndReadBack(wb2); - wb2.close(); - - // Check again - assertNotNull(wb3.getDocumentSummaryInformation()); - assertNotNull(wb3.getSummaryInformation()); - - assertEquals("Apache POI", wb3.getSummaryInformation().getAuthor()); - assertEquals("Testing POI", wb3.getSummaryInformation().getKeywords()); - assertEquals("Resaved", wb3.getSummaryInformation().getComments()); - assertEquals(12345, wb3.getSummaryInformation().getCreateDateTime().getTime()); - assertEquals("Apache", wb3.getDocumentSummaryInformation().getCompany()); - wb3.close(); - } - - /** - * Some files seem to want the length and data to be on a 4-byte boundary, - * and without that you'll hit an ArrayIndexOutOfBoundsException after - * reading junk - */ - @Test - public void test54233() throws IOException, NoPropertySetStreamException, MarkUnsupportedException { - InputStream is = _samples.openResourceAsStream("TestNon4ByteBoundary.doc"); - NPOIFSFileSystem fs = new NPOIFSFileSystem(is); - is.close(); - - SummaryInformation si = (SummaryInformation) - PropertySetFactory.create(fs.getRoot(), SummaryInformation.DEFAULT_STREAM_NAME); - DocumentSummaryInformation dsi = (DocumentSummaryInformation) - PropertySetFactory.create(fs.getRoot(), DocumentSummaryInformation.DEFAULT_STREAM_NAME); - - // Test - assertEquals("Microsoft Word 10.0", si.getApplicationName()); - assertEquals("", si.getTitle()); - assertEquals("", si.getAuthor()); - assertEquals("Cour de Justice", dsi.getCompany()); - - - // Write out and read back, should still be valid - POIDocument doc = new HPSFPropertiesOnlyDocument(fs); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - doc.write(baos); - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - doc = new HPSFPropertiesOnlyDocument(new NPOIFSFileSystem(bais)); - - // Check properties are still there - assertEquals("Microsoft Word 10.0", si.getApplicationName()); - assertEquals("", si.getTitle()); - assertEquals("", si.getAuthor()); - assertEquals("Cour de Justice", dsi.getCompany()); - - doc.close(); - fs.close(); - } - - /** - * CodePage Strings can be zero length - */ - @Test - public void test56138() throws IOException, NoPropertySetStreamException { - InputStream is = _samples.openResourceAsStream("TestZeroLengthCodePage.mpp"); - NPOIFSFileSystem fs = new NPOIFSFileSystem(is); - is.close(); - - SummaryInformation si = (SummaryInformation) - PropertySetFactory.create(fs.getRoot(), SummaryInformation.DEFAULT_STREAM_NAME); - DocumentSummaryInformation dsi = (DocumentSummaryInformation) - PropertySetFactory.create(fs.getRoot(), DocumentSummaryInformation.DEFAULT_STREAM_NAME); - - // Test - assertEquals("MSProject", si.getApplicationName()); - assertEquals("project1", si.getTitle()); - assertEquals("Jon Iles", si.getAuthor()); - - assertEquals("", dsi.getCompany()); - assertEquals(2, dsi.getSectionCount()); - - fs.close(); - } -} diff --git a/src/testcases/org/apache/poi/hpsf/basic/TestMetaDataIPI.java b/src/testcases/org/apache/poi/hpsf/basic/TestMetaDataIPI.java deleted file mode 100644 index 3cb277f5d..000000000 --- a/src/testcases/org/apache/poi/hpsf/basic/TestMetaDataIPI.java +++ /dev/null @@ -1,659 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hpsf.basic; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.util.Date; -import java.util.Random; - -import junit.framework.TestCase; - -import org.apache.poi.hpsf.*; -import org.apache.poi.poifs.filesystem.DirectoryEntry; -import org.apache.poi.poifs.filesystem.DocumentEntry; -import org.apache.poi.poifs.filesystem.DocumentInputStream; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -/** - * Basing on: src/examples/src/org/apache/poi/hpsf/examples/ModifyDocumentSummaryInformation.java - * This class tests reading and writing of meta data. No actual document is created. All information - * is stored in a virtual document in a ByteArrayOutputStream - * @author Matthias G\u00fcnter - */ -public final class TestMetaDataIPI extends TestCase{ - - private ByteArrayOutputStream bout; //our store - private POIFSFileSystem poifs; - private DirectoryEntry dir; - private DocumentSummaryInformation dsi; - private SummaryInformation si; - - - - /** - * Setup is used to get the document ready. Gets the DocumentSummaryInformation and the - * SummaryInformation to reasonable values - */ - @Override - public void setUp() throws Exception { - bout = new ByteArrayOutputStream(); - poifs = new POIFSFileSystem(); - dir = poifs.getRoot(); - dsi = null; - try { - DocumentEntry dsiEntry = (DocumentEntry) dir - .getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME); - DocumentInputStream dis = new DocumentInputStream(dsiEntry); - PropertySet ps = new PropertySet(dis); - dis.close(); - dsi = new DocumentSummaryInformation(ps); - - } catch (FileNotFoundException ex) { - /* - * There is no document summary information yet. We have to create a - * new one. - */ - dsi = PropertySetFactory.newDocumentSummaryInformation(); - assertNotNull(dsi); - } - assertNotNull(dsi); - try { - DocumentEntry dsiEntry = (DocumentEntry) dir - .getEntry(SummaryInformation.DEFAULT_STREAM_NAME); - DocumentInputStream dis = new DocumentInputStream(dsiEntry); - PropertySet ps = new PropertySet(dis); - dis.close(); - si = new SummaryInformation(ps); - - } catch (FileNotFoundException ex) { - /* - * There is no document summary information yet. We have to create a - * new one. - */ - si = PropertySetFactory.newSummaryInformation(); - assertNotNull(si); - } - assertNotNull(dsi); - } - - /** - * Closes the ByteArrayOutputStream and reads it into a ByteArrayInputStream. - * When finished writing information this method is used in the tests to - * start reading from the created document and then the see if the results match. - */ - public void closeAndReOpen() throws IOException, HPSFException { - - dsi.write(dir, DocumentSummaryInformation.DEFAULT_STREAM_NAME); - si.write(dir, SummaryInformation.DEFAULT_STREAM_NAME); - - si = null; - dsi = null; - poifs.writeFilesystem(bout); - bout.flush(); - - InputStream is = new ByteArrayInputStream(bout.toByteArray()); - assertNotNull(is); - POIFSFileSystem poifs = new POIFSFileSystem(is); - is.close(); - - assertNotNull(poifs); - /* Read the document summary information. */ - DirectoryEntry dir = poifs.getRoot(); - - DocumentEntry dsiEntry = (DocumentEntry) dir - .getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME); - DocumentInputStream dis = new DocumentInputStream(dsiEntry); - PropertySet ps = new PropertySet(dis); - dis.close(); - dsi = new DocumentSummaryInformation(ps); - - try { - dsiEntry = (DocumentEntry) dir - .getEntry(SummaryInformation.DEFAULT_STREAM_NAME); - dis = new DocumentInputStream(dsiEntry); - ps = new PropertySet(dis); - dis.close(); - si = new SummaryInformation(ps); - - } catch (FileNotFoundException ex) { - /* - * There is no document summary information yet. We have to create a - * new one. - */ - si = PropertySetFactory.newSummaryInformation(); - assertNotNull(si); - } - } - - /** - * Sets the most important information in DocumentSummaryInformation and Summary Information and rereads it - */ - public void testOne() throws Exception { - - // DocumentSummaryInformation - dsi.setCompany("xxxCompanyxxx"); - dsi.setManager("xxxManagerxxx"); - dsi.setCategory("xxxCategoryxxx"); - - // SummaryInformation - si.setTitle("xxxTitlexxx"); - si.setAuthor("xxxAuthorxxx"); - si.setComments("xxxCommentsxxx"); - si.setKeywords("xxxKeyWordsxxx"); - si.setSubject("xxxSubjectxxx"); - - // Custom Properties (in DocumentSummaryInformation - CustomProperties customProperties = dsi.getCustomProperties(); - if (customProperties == null) { - customProperties = new CustomProperties(); - } - - /* Insert some custom properties into the container. */ - customProperties.put("Key1", "Value1"); - customProperties.put("Schl\u00fcssel2", "Wert2"); - customProperties.put("Sample Integer", new Integer(12345)); - customProperties.put("Sample Boolean", Boolean.TRUE); - Date date = new Date(); - customProperties.put("Sample Date", date); - customProperties.put("Sample Double", new Double(-1.0001)); - customProperties.put("Sample Negative Integer", new Integer(-100000)); - - dsi.setCustomProperties(customProperties); - - // start reading - closeAndReOpen(); - - // testing - assertNotNull(dsi); - assertNotNull(si); - - assertEquals("Category", "xxxCategoryxxx", dsi.getCategory()); - assertEquals("Company", "xxxCompanyxxx", dsi.getCompany()); - assertEquals("Manager", "xxxManagerxxx", dsi.getManager()); - - assertEquals("", "xxxAuthorxxx", si.getAuthor()); - assertEquals("", "xxxTitlexxx", si.getTitle()); - assertEquals("", "xxxCommentsxxx", si.getComments()); - assertEquals("", "xxxKeyWordsxxx", si.getKeywords()); - assertEquals("", "xxxSubjectxxx", si.getSubject()); - - /* - * Read the custom properties. If there are no custom properties yet, - * the application has to create a new CustomProperties object. It will - * serve as a container for custom properties. - */ - customProperties = dsi.getCustomProperties(); - if (customProperties == null) { - fail(); - } - - /* Insert some custom properties into the container. */ - String a1 = (String) customProperties.get("Key1"); - assertEquals("Key1", "Value1", a1); - String a2 = (String) customProperties.get("Schl\u00fcssel2"); - assertEquals("Schl\u00fcssel2", "Wert2", a2); - Integer a3 = (Integer) customProperties.get("Sample Integer"); - assertEquals("Sample Number", new Integer(12345), a3); - Boolean a4 = (Boolean) customProperties.get("Sample Boolean"); - assertEquals("Sample Boolean", Boolean.TRUE, a4); - Date a5 = (Date) customProperties.get("Sample Date"); - assertEquals("Custom Date:", date, a5); - - Double a6 = (Double) customProperties.get("Sample Double"); - assertEquals("Custom Float", new Double(-1.0001), a6); - - Integer a7 = (Integer) customProperties.get("Sample Negative Integer"); - assertEquals("Neg", new Integer(-100000), a7); - } - - /** - * multiplies a string - * @param s Input String - * @return the multiplied String - */ - private static String elongate(String s) { - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < 10000; i++) { - sb.append(s); - sb.append(" "); - } - return sb.toString(); - } - - /** - * Test very long input in each of the fields (approx 30-60KB each) - */ - public void testTwo() throws Exception { - - String company = elongate("company"); - String manager = elongate("manager"); - String category = elongate("category"); - String title = elongate("title"); - String author = elongate("author"); - String comments = elongate("comments"); - String keywords = elongate("keywords"); - String subject = elongate("subject"); - String p1 = elongate("p1"); - String p2 = elongate("p2"); - String k1 = elongate("k1"); - String k2 = elongate("k2"); - - dsi.setCompany(company); - dsi.setManager(manager); - dsi.setCategory(category); - - si.setTitle(title); - si.setAuthor(author); - si.setComments(comments); - si.setKeywords(keywords); - si.setSubject(subject); - CustomProperties customProperties = dsi.getCustomProperties(); - if (customProperties == null) { - customProperties = new CustomProperties(); - } - - /* Insert some custom properties into the container. */ - customProperties.put(k1, p1); - customProperties.put(k2, p2); - customProperties.put("Sample Number", new Integer(12345)); - customProperties.put("Sample Boolean", Boolean.TRUE); - Date date = new Date(); - customProperties.put("Sample Date", date); - - dsi.setCustomProperties(customProperties); - - closeAndReOpen(); - - assertNotNull(dsi); - assertNotNull(si); - /* - * Change the category to "POI example". Any former category value will - * be lost. If there has been no category yet, it will be created. - */ - assertEquals("Category", category, dsi.getCategory()); - assertEquals("Company", company, dsi.getCompany()); - assertEquals("Manager", manager, dsi.getManager()); - - assertEquals("", author, si.getAuthor()); - assertEquals("", title, si.getTitle()); - assertEquals("", comments, si.getComments()); - assertEquals("", keywords, si.getKeywords()); - assertEquals("", subject, si.getSubject()); - - /* - * Read the custom properties. If there are no custom properties yet, - * the application has to create a new CustomProperties object. It will - * serve as a container for custom properties. - */ - customProperties = dsi.getCustomProperties(); - if (customProperties == null) { - fail(); - } - - /* Insert some custom properties into the container. */ - String a1 = (String) customProperties.get(k1); - assertEquals("Key1", p1, a1); - String a2 = (String) customProperties.get(k2); - assertEquals("Schl\u00fcssel2", p2, a2); - Integer a3 = (Integer) customProperties.get("Sample Number"); - assertEquals("Sample Number", new Integer(12345), a3); - Boolean a4 = (Boolean) customProperties.get("Sample Boolean"); - assertEquals("Sample Boolean", Boolean.TRUE, a4); - Date a5 = (Date) customProperties.get("Sample Date"); - assertEquals("Custom Date:", date, a5); - - } - - - /** - * adds strange characters to the string - * @param s Input String - * @return the multiplied String - */ - private static String strangize(String s) { - StringBuilder sb = strangizeInit(s); - - return sb.toString(); - } - - - /** - * Tests with strange characters in keys and data (Umlaute etc.) - */ - public void testThree() throws Exception { - - String company = strangize("company"); - String manager = strangize("manager"); - String category = strangize("category"); - String title = strangize("title"); - String author = strangize("author"); - String comments = strangize("comments"); - String keywords = strangize("keywords"); - String subject = strangize("subject"); - String p1 = strangize("p1"); - String p2 = strangize("p2"); - String k1 = strangize("k1"); - String k2 = strangize("k2"); - - dsi.setCompany(company); - dsi.setManager(manager); - dsi.setCategory(category); - - si.setTitle(title); - si.setAuthor(author); - si.setComments(comments); - si.setKeywords(keywords); - si.setSubject(subject); - CustomProperties customProperties = dsi.getCustomProperties(); - if (customProperties == null) { - customProperties = new CustomProperties(); - } - - /* Insert some custom properties into the container. */ - customProperties.put(k1, p1); - customProperties.put(k2, p2); - customProperties.put("Sample Number", new Integer(12345)); - customProperties.put("Sample Boolean", Boolean.FALSE); - Date date = new Date(0); - customProperties.put("Sample Date", date); - - dsi.setCustomProperties(customProperties); - - closeAndReOpen(); - - assertNotNull(dsi); - assertNotNull(si); - /* - * Change the category to "POI example". Any former category value will - * be lost. If there has been no category yet, it will be created. - */ - assertEquals("Category", category, dsi.getCategory()); - assertEquals("Company", company, dsi.getCompany()); - assertEquals("Manager", manager, dsi.getManager()); - - assertEquals("", author, si.getAuthor()); - assertEquals("", title, si.getTitle()); - assertEquals("", comments, si.getComments()); - assertEquals("", keywords, si.getKeywords()); - assertEquals("", subject, si.getSubject()); - - /* - * Read the custom properties. If there are no custom properties yet, - * the application has to create a new CustomProperties object. It will - * serve as a container for custom properties. - */ - customProperties = dsi.getCustomProperties(); - if (customProperties == null) { - fail(); - } - - /* Insert some custom properties into the container. */ - // System.out.println(k1); - String a1 = (String) customProperties.get(k1); - assertEquals("Key1", p1, a1); - String a2 = (String) customProperties.get(k2); - assertEquals("Schl\u00fcssel2", p2, a2); - Integer a3 = (Integer) customProperties.get("Sample Number"); - assertEquals("Sample Number", new Integer(12345), a3); - Boolean a4 = (Boolean) customProperties.get("Sample Boolean"); - assertEquals("Sample Boolean", Boolean.FALSE, a4); - Date a5 = (Date) customProperties.get("Sample Date"); - assertEquals("Custom Date:", date, a5); - - } - - /** - * Iterative testing: writing, reading etc. - */ - public void testFour() throws Exception { - for (int i = 1; i < 100; i++) { - setUp(); - testThree(); - } - } - - - - /** - * adds strange characters to the string with the adding of unicode characters - * @param s Input String - * @return the multiplied String - */ - private static String strangizeU(String s) { - - StringBuilder sb = strangizeInit(s); - sb.append("\u00e4\u00f6\u00fc\uD840\uDC00"); - return sb.toString(); - } - - private static StringBuilder strangizeInit(String s) { - StringBuilder sb = new StringBuilder(); - String[] umlaute = { "\u00e4", "\u00fc", "\u00f6", "\u00dc", "$", "\u00d6", "\u00dc", - "\u00c9", "\u00d6", "@", "\u00e7", "&" }; - Random rand = new Random(0); // TODO - no Random - tests should be completely deterministic - for (int i = 0; i < 5; i++) { - sb.append(s); - sb.append(" "); - char j = (char) rand.nextInt(220); - j += 33; - // System.out.println(j); - sb.append(">"); - sb.append(Character.valueOf(j)); - sb.append("="); - sb.append(umlaute[rand.nextInt(umlaute.length)]); - sb.append("<"); - } - return sb; - } - - /** - * Unicode test - */ - public void testUnicode() throws Exception { - String company = strangizeU("company"); - String manager = strangizeU("manager"); - String category = strangizeU("category"); - String title = strangizeU("title"); - String author = strangizeU("author"); - String comments = strangizeU("comments"); - String keywords = strangizeU("keywords"); - String subject = strangizeU("subject"); - String p1 = strangizeU("p1"); - String p2 = strangizeU("p2"); - String k1 = strangizeU("k1"); - String k2 = strangizeU("k2"); - - dsi.setCompany(company); - dsi.setManager(manager); - dsi.setCategory(category); - - si.setTitle(title); - si.setAuthor(author); - si.setComments(comments); - si.setKeywords(keywords); - si.setSubject(subject); - CustomProperties customProperties = dsi.getCustomProperties(); - if (customProperties == null) { - customProperties = new CustomProperties(); - } - - /* Insert some custom properties into the container. */ - customProperties.put(k1, p1); - customProperties.put(k2, p2); - customProperties.put("Sample Number", new Integer(12345)); - customProperties.put("Sample Boolean", Boolean.TRUE); - Date date = new Date(); - customProperties.put("Sample Date", date); - - dsi.setCustomProperties(customProperties); - - closeAndReOpen(); - - assertNotNull(dsi); - assertNotNull(si); - /* - * Change the category to "POI example". Any former category value will - * be lost. If there has been no category yet, it will be created. - */ - assertEquals("Category", category, dsi.getCategory()); - assertEquals("Company", company, dsi.getCompany()); - assertEquals("Manager", manager, dsi.getManager()); - - assertEquals("", author, si.getAuthor()); - assertEquals("", title, si.getTitle()); - assertEquals("", comments, si.getComments()); - assertEquals("", keywords, si.getKeywords()); - assertEquals("", subject, si.getSubject()); - - /* - * Read the custom properties. If there are no custom properties yet, - * the application has to create a new CustomProperties object. It will - * serve as a container for custom properties. - */ - customProperties = dsi.getCustomProperties(); - if (customProperties == null) { - fail(); - } - - /* Insert some custom properties into the container. */ - // System.out.println(k1); - String a1 = (String) customProperties.get(k1); - assertEquals("Key1", p1, a1); - String a2 = (String) customProperties.get(k2); - assertEquals("Schl\u00fcssel2", p2, a2); - Integer a3 = (Integer) customProperties.get("Sample Number"); - assertEquals("Sample Number", new Integer(12345), a3); - Boolean a4 = (Boolean) customProperties.get("Sample Boolean"); - assertEquals("Sample Boolean", Boolean.TRUE, a4); - Date a5 = (Date) customProperties.get("Sample Date"); - assertEquals("Custom Date:", date, a5); - } - - - /** - * Iterative testing of the unicode test - * - */ - public void testSix() throws Exception { - for (int i = 1; i < 100; i++) { - setUp(); - testUnicode(); - } - } - - - /** - * Tests conversion in custom fields and errors - */ - public void testConvAndExistence() throws Exception { - - CustomProperties customProperties = dsi.getCustomProperties(); - if (customProperties == null) { - customProperties = new CustomProperties(); - } - - /* Insert some custom properties into the container. */ - customProperties.put("int", new Integer(12345)); - customProperties.put("negint", new Integer(-12345)); - customProperties.put("long", new Long(12345)); - customProperties.put("neglong", new Long(-12345)); - customProperties.put("boolean", Boolean.TRUE); - customProperties.put("string", "a String"); - // customProperties.put("float", new Float(12345.0)); is not valid - // customProperties.put("negfloat", new Float(-12345.1)); is not valid - customProperties.put("double", new Double(12345.2)); - customProperties.put("negdouble", new Double(-12345.3)); - // customProperties.put("char", new Character('a')); is not valid - - Date date = new Date(); - customProperties.put("date", date); - - dsi.setCustomProperties(customProperties); - - closeAndReOpen(); - - assertNotNull(dsi); - assertNotNull(si); - /* - * Change the category to "POI example". Any former category value will - * be lost. If there has been no category yet, it will be created. - */ - assertNull(dsi.getCategory()); - assertNull(dsi.getCompany()); - assertNull(dsi.getManager()); - - assertNull(si.getAuthor()); - assertNull(si.getTitle()); - assertNull(si.getComments()); - assertNull(si.getKeywords()); - assertNull(si.getSubject()); - - /* - * Read the custom properties. If there are no custom properties yet, - * the application has to create a new CustomProperties object. It will - * serve as a container for custom properties. - */ - customProperties = dsi.getCustomProperties(); - if (customProperties == null) { - fail(); - } - - /* Insert some custom properties into the container. */ - - Integer a3 = (Integer) customProperties.get("int"); - assertEquals("int", new Integer(12345), a3); - - a3 = (Integer) customProperties.get("negint"); - assertEquals("negint", new Integer(-12345), a3); - - Long al = (Long) customProperties.get("neglong"); - assertEquals("neglong", new Long(-12345), al); - - al = (Long) customProperties.get("long"); - assertEquals("long", new Long(12345), al); - - Boolean a4 = (Boolean) customProperties.get("boolean"); - assertEquals("boolean", Boolean.TRUE, a4); - - Date a5 = (Date) customProperties.get("date"); - assertEquals("Custom Date:", date, a5); - - Double d = (Double) customProperties.get("double"); - assertEquals("int", new Double(12345.2), d); - - d = (Double) customProperties.get("negdouble"); - assertEquals("string", new Double(-12345.3), d); - - String s = (String) customProperties.get("string"); - assertEquals("sring", "a String", s); - - - assertTrue(customProperties.get("string") instanceof String); - assertTrue(customProperties.get("boolean") instanceof Boolean); - assertTrue(customProperties.get("int") instanceof Integer); - assertTrue(customProperties.get("negint") instanceof Integer); - assertTrue(customProperties.get("long") instanceof Long); - assertTrue(customProperties.get("neglong") instanceof Long); - assertTrue(customProperties.get("double") instanceof Double); - assertTrue(customProperties.get("negdouble") instanceof Double); - assertTrue(customProperties.get("date") instanceof Date); - } -} diff --git a/src/testcases/org/apache/poi/hpsf/basic/TestReadAllFiles.java b/src/testcases/org/apache/poi/hpsf/basic/TestReadAllFiles.java deleted file mode 100644 index b419ad1da..000000000 --- a/src/testcases/org/apache/poi/hpsf/basic/TestReadAllFiles.java +++ /dev/null @@ -1,93 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hpsf.basic; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileFilter; -import java.io.IOException; -import java.io.InputStream; - -import junit.framework.TestCase; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hpsf.HPSFException; -import org.apache.poi.hpsf.PropertySetFactory; - -/** - *

    Tests some HPSF functionality by reading all property sets from all files - * in the "data" directory. If you want to ensure HPSF can deal with a certain - * OLE2 file, just add it to the "data" directory and run this test case.

    - */ -public class TestReadAllFiles extends TestCase { - private static String[] excludes = new String[] {}; - - /** - *

    This test methods reads all property set streams from all POI - * filesystems in the "data" directory.

    - * - * @throws IOException - * @throws HPSFException - */ - public void testReadAllFiles() throws IOException, HPSFException - { - POIDataSamples _samples = POIDataSamples.getHPSFInstance(); - final File dataDir = _samples.getFile(""); - final File[] fileList = dataDir.listFiles(new FileFilter() - { - @Override - public boolean accept(final File f) - { - // exclude files that we know will fail - return f.isFile() && checkExclude(f); - } - }); - - for (final File f : fileList) { - /* Read the POI filesystem's property set streams: */ - final POIFile[] psf1 = Util.readPropertySets(f); - - for (int j = 0; j < psf1.length; j++) - { - final InputStream in = - new ByteArrayInputStream(psf1[j].getBytes()); - try { - PropertySetFactory.create(in); - } catch (Exception e) { - throw new IOException("While handling file: " + f + " at " + j, e); - } - } - } - } - - /** - * Returns true if the file should be checked, false if it should be excluded. - * - * @param f - * @return - */ - public static boolean checkExclude(File f) { - for(String exclude : excludes) { - if(f.getAbsolutePath().endsWith(exclude)) { - return false; - } - } - - return true; - } -} diff --git a/src/testcases/org/apache/poi/hpsf/basic/TestUnicode.java b/src/testcases/org/apache/poi/hpsf/basic/TestUnicode.java deleted file mode 100644 index 6f7e6db1c..000000000 --- a/src/testcases/org/apache/poi/hpsf/basic/TestUnicode.java +++ /dev/null @@ -1,93 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hpsf.basic; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; - -import junit.framework.TestCase; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hpsf.DocumentSummaryInformation; -import org.apache.poi.hpsf.HPSFException; -import org.apache.poi.hpsf.PropertySet; -import org.apache.poi.hpsf.PropertySetFactory; -import org.apache.poi.hpsf.Section; -import org.apache.poi.hpsf.SummaryInformation; -import org.apache.poi.util.CodePageUtil; - -/** - *

    Tests whether Unicode string can be read from a - * DocumentSummaryInformation.

    - */ -public class TestUnicode extends TestCase { - - static final String POI_FS = "TestUnicode.xls"; - static final String[] POI_FILES = new String[] - { - "\005DocumentSummaryInformation", - }; - File data; - POIFile[] poiFiles; - - - /** - *

    Read a the test file from the "data" directory.

    - * - * @exception FileNotFoundException if the file to be read does not exist. - * @exception IOException if any other I/O exception occurs - */ - @Override - protected void setUp() { - POIDataSamples samples = POIDataSamples.getHPSFInstance(); - data = samples.getFile(POI_FS); - } - - - - /** - *

    Tests the {@link PropertySet} methods. The test file has two - * property set: the first one is a {@link SummaryInformation}, - * the second one is a {@link DocumentSummaryInformation}.

    - * - * @exception IOException if an I/O exception occurs - * @exception HPSFException if an HPSF exception occurs - */ - public void testPropertySetMethods() throws IOException, HPSFException - { - POIFile poiFile = Util.readPOIFiles(data, POI_FILES)[0]; - byte[] b = poiFile.getBytes(); - PropertySet ps = - PropertySetFactory.create(new ByteArrayInputStream(b)); - assertTrue(ps.isDocumentSummaryInformation()); - assertEquals(ps.getSectionCount(), 2); - Section s = ps.getSections().get(1); - assertEquals(s.getProperty(1), - Integer.valueOf(CodePageUtil.CP_UTF16)); - assertEquals(s.getProperty(2), - Integer.valueOf(-96070278)); - assertEquals(s.getProperty(3), - "MCon_Info zu Office bei Schreiner"); - assertEquals(s.getProperty(4), - "petrovitsch@schreiner-online.de"); - assertEquals(s.getProperty(5), - "Petrovitsch, Wilhelm"); - } -} diff --git a/src/testcases/org/apache/poi/hpsf/basic/TestWrite.java b/src/testcases/org/apache/poi/hpsf/basic/TestWrite.java deleted file mode 100644 index 20f7d8fae..000000000 --- a/src/testcases/org/apache/poi/hpsf/basic/TestWrite.java +++ /dev/null @@ -1,1102 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hpsf.basic; - -import static org.hamcrest.core.IsEqual.equalTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileFilter; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.UnsupportedEncodingException; -import java.nio.charset.Charset; -import java.util.Date; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hpsf.ClassID; -import org.apache.poi.hpsf.DocumentSummaryInformation; -import org.apache.poi.hpsf.HPSFException; -import org.apache.poi.hpsf.IllegalPropertySetDataException; -import org.apache.poi.hpsf.MutableProperty; -import org.apache.poi.hpsf.MutablePropertySet; -import org.apache.poi.hpsf.MutableSection; -import org.apache.poi.hpsf.NoFormatIDException; -import org.apache.poi.hpsf.NoPropertySetStreamException; -import org.apache.poi.hpsf.PropertySet; -import org.apache.poi.hpsf.PropertySetFactory; -import org.apache.poi.hpsf.ReadingNotSupportedException; -import org.apache.poi.hpsf.Section; -import org.apache.poi.hpsf.SummaryInformation; -import org.apache.poi.hpsf.UnsupportedVariantTypeException; -import org.apache.poi.hpsf.Variant; -import org.apache.poi.hpsf.VariantSupport; -import org.apache.poi.hpsf.WritingNotSupportedException; -import org.apache.poi.hpsf.wellknown.PropertyIDMap; -import org.apache.poi.hpsf.wellknown.SectionIDMap; -import org.apache.poi.poifs.eventfilesystem.POIFSReader; -import org.apache.poi.poifs.eventfilesystem.POIFSReaderEvent; -import org.apache.poi.poifs.eventfilesystem.POIFSReaderListener; -import org.apache.poi.poifs.filesystem.DirectoryEntry; -import org.apache.poi.poifs.filesystem.DocumentNode; -import org.apache.poi.poifs.filesystem.NDocumentInputStream; -import org.apache.poi.poifs.filesystem.NDocumentOutputStream; -import org.apache.poi.poifs.filesystem.NPOIFSDocument; -import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.util.CodePageUtil; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.TempFile; -import org.junit.Before; -import org.junit.Test; - -/** - *

    Tests HPSF's writing functionality.

    - */ -public class TestWrite -{ - private static final POIDataSamples _samples = POIDataSamples.getHPSFInstance(); - - static final String POI_FS = "TestHPSFWritingFunctionality.doc"; - - static final int BYTE_ORDER = 0xfffe; - static final int FORMAT = 0x0000; - static final int OS_VERSION = 0x00020A04; - static final int[] SECTION_COUNT = {1, 2}; - static final boolean[] IS_SUMMARY_INFORMATION = {true, false}; - static final boolean[] IS_DOCUMENT_SUMMARY_INFORMATION = {false, true}; - - final String IMPROPER_DEFAULT_CHARSET_MESSAGE = - "Your default character set is " + getDefaultCharsetName() + - ". However, this testcase must be run in an environment " + - "with a default character set supporting at least " + - "8-bit-characters. You can achieve this by setting the " + - "LANG environment variable to a proper value, e.g. " + - "\"de_DE\"."; - - POIFile[] poiFiles; - - @Before - public void setUp() - { - VariantSupport.setLogUnsupportedTypes(false); - } - - /** - *

    Writes an empty property set to a POIFS and reads it back - * in.

    - * - * @exception IOException if an I/O exception occurs - */ - @Test(expected=NoFormatIDException.class) - public void withoutAFormatID() throws Exception - { - final File filename = TempFile.createTempFile(POI_FS, ".doc"); - - /* Create a mutable property set with a section that does not have the - * formatID set: */ - final OutputStream out = new FileOutputStream(filename); - final POIFSFileSystem poiFs = new POIFSFileSystem(); - final MutablePropertySet ps = new MutablePropertySet(); - ps.clearSections(); - ps.addSection(new MutableSection()); - - /* Write it to a POIFS and the latter to disk: */ - try { - final ByteArrayOutputStream psStream = new ByteArrayOutputStream(); - ps.write(psStream); - psStream.close(); - final byte[] streamData = psStream.toByteArray(); - poiFs.createDocument(new ByteArrayInputStream(streamData), - SummaryInformation.DEFAULT_STREAM_NAME); - poiFs.writeFilesystem(out); - } finally { - poiFs.close(); - out.close(); - } - } - - - - /** - *

    Writes an empty property set to a POIFS and reads it back - * in.

    - * - * @exception IOException if an I/O exception occurs - * @exception UnsupportedVariantTypeException if HPSF does not yet support - * a variant type to be written - */ - @Test - public void writeEmptyPropertySet() - throws IOException, UnsupportedVariantTypeException - { - final File dataDir = _samples.getFile(""); - final File filename = new File(dataDir, POI_FS); - filename.deleteOnExit(); - - /* Create a mutable property set and write it to a POIFS: */ - final OutputStream out = new FileOutputStream(filename); - final POIFSFileSystem poiFs = new POIFSFileSystem(); - final MutablePropertySet ps = new MutablePropertySet(); - final MutableSection s = (MutableSection) ps.getSections().get(0); - s.setFormatID(SectionIDMap.SUMMARY_INFORMATION_ID); - - final ByteArrayOutputStream psStream = new ByteArrayOutputStream(); - ps.write(psStream); - psStream.close(); - final byte[] streamData = psStream.toByteArray(); - poiFs.createDocument(new ByteArrayInputStream(streamData), - SummaryInformation.DEFAULT_STREAM_NAME); - poiFs.writeFilesystem(out); - poiFs.close(); - out.close(); - - /* Read the POIFS: */ - final POIFSReader r = new POIFSReader(); - r.registerListener(new MyPOIFSReaderListener(), - SummaryInformation.DEFAULT_STREAM_NAME); - FileInputStream stream = new FileInputStream(filename); - try { - r.read(stream); - } finally { - stream.close(); - } - } - - - - /** - *

    Writes a simple property set with a SummaryInformation section to a - * POIFS and reads it back in.

    - * - * @exception IOException if an I/O exception occurs - * @exception UnsupportedVariantTypeException if HPSF does not yet support - * a variant type to be written - */ - @Test - public void writeSimplePropertySet() - throws IOException, UnsupportedVariantTypeException - { - final String AUTHOR = "Rainer Klute"; - final String TITLE = "Test Document"; - final File dataDir = _samples.getFile(""); - final File filename = new File(dataDir, POI_FS); - filename.deleteOnExit(); - final OutputStream out = new FileOutputStream(filename); - final POIFSFileSystem poiFs = new POIFSFileSystem(); - - final MutablePropertySet ps = new MutablePropertySet(); - final MutableSection si = new MutableSection(); - si.setFormatID(SectionIDMap.SUMMARY_INFORMATION_ID); - ps.clearSections(); - ps.addSection(si); - - final MutableProperty p = new MutableProperty(); - p.setID(PropertyIDMap.PID_AUTHOR); - p.setType(Variant.VT_LPWSTR); - p.setValue(AUTHOR); - si.setProperty(p); - si.setProperty(PropertyIDMap.PID_TITLE, Variant.VT_LPSTR, TITLE); - - poiFs.createDocument(ps.toInputStream(), - SummaryInformation.DEFAULT_STREAM_NAME); - poiFs.writeFilesystem(out); - poiFs.close(); - out.close(); - - /* Read the POIFS: */ - final PropertySet[] psa = new PropertySet[1]; - final POIFSReader r = new POIFSReader(); - r.registerListener(new POIFSReaderListener() - { - @Override - public void processPOIFSReaderEvent - (final POIFSReaderEvent event) - { - try - { - psa[0] = PropertySetFactory.create(event.getStream()); - } - catch (Exception ex) - { - fail(org.apache.poi.hpsf.Util.toString(ex)); - } - } - - }, - SummaryInformation.DEFAULT_STREAM_NAME); - - InputStream stream = new FileInputStream(filename); - try { - r.read(stream); - } finally { - stream.close(); - } - assertNotNull(psa[0]); - assertTrue(psa[0].isSummaryInformation()); - - final Section s = (psa[0].getSections().get(0)); - Object p1 = s.getProperty(PropertyIDMap.PID_AUTHOR); - Object p2 = s.getProperty(PropertyIDMap.PID_TITLE); - assertEquals(AUTHOR, p1); - assertEquals(TITLE, p2); - } - - - - /** - *

    Writes a simple property set with two sections to a POIFS and reads it - * back in.

    - * - * @exception IOException if an I/O exception occurs - * @exception WritingNotSupportedException if HPSF does not yet support - * a variant type to be written - */ - @Test - public void writeTwoSections() - throws WritingNotSupportedException, IOException - { - final String STREAM_NAME = "PropertySetStream"; - final String SECTION1 = "Section 1"; - final String SECTION2 = "Section 2"; - - final File dataDir = _samples.getFile(""); - final File filename = new File(dataDir, POI_FS); - filename.deleteOnExit(); - final OutputStream out = new FileOutputStream(filename); - - final POIFSFileSystem poiFs = new POIFSFileSystem(); - final MutablePropertySet ps = new MutablePropertySet(); - ps.clearSections(); - - final ClassID formatID = new ClassID(); - formatID.setBytes(new byte[]{0, 1, 2, 3, 4, 5, 6, 7, - 8, 9, 10, 11, 12, 13, 14, 15}); - final MutableSection s1 = new MutableSection(); - s1.setFormatID(formatID); - s1.setProperty(2, SECTION1); - ps.addSection(s1); - - final MutableSection s2 = new MutableSection(); - s2.setFormatID(formatID); - s2.setProperty(2, SECTION2); - ps.addSection(s2); - - poiFs.createDocument(ps.toInputStream(), STREAM_NAME); - poiFs.writeFilesystem(out); - poiFs.close(); - out.close(); - - /* Read the POIFS: */ - final PropertySet[] psa = new PropertySet[1]; - final POIFSReader r = new POIFSReader(); - r.registerListener(new POIFSReaderListener() - { - @Override - public void processPOIFSReaderEvent - (final POIFSReaderEvent event) - { - try - { - psa[0] = PropertySetFactory.create(event.getStream()); - } - catch (Exception ex) - { - throw new RuntimeException(ex); - } - } - }, - STREAM_NAME); - FileInputStream stream = new FileInputStream(filename); - try { - r.read(stream); - } finally { - stream.close(); - } - assertNotNull(psa[0]); - Section s = (psa[0].getSections().get(0)); - assertEquals(s.getFormatID(), formatID); - Object p = s.getProperty(2); - assertEquals(SECTION1, p); - s = (psa[0].getSections().get(1)); - p = s.getProperty(2); - assertEquals(SECTION2, p); - } - - - - static class MyPOIFSReaderListener implements POIFSReaderListener - { - @Override - public void processPOIFSReaderEvent(final POIFSReaderEvent event) - { - try - { - PropertySetFactory.create(event.getStream()); - } - catch (Exception ex) - { - fail(org.apache.poi.hpsf.Util.toString(ex)); - } - } - } - - - - private static final int CODEPAGE_DEFAULT = -1; - private static final int CODEPAGE_1252 = 1252; - private static final int CODEPAGE_UTF8 = CodePageUtil.CP_UTF8; - private static final int CODEPAGE_UTF16 = CodePageUtil.CP_UTF16; - - - - /** - *

    Writes and reads back various variant types and checks whether the - * stuff that has been read back equals the stuff that was written.

    - */ - @Test - public void variantTypes() - { - Throwable t = null; - final int codepage = CODEPAGE_DEFAULT; - if (!hasProperDefaultCharset()) - { - System.err.println(IMPROPER_DEFAULT_CHARSET_MESSAGE + - " This testcase is skipped."); - return; - } - - try - { - check(Variant.VT_EMPTY, null, codepage); - check(Variant.VT_BOOL, Boolean.TRUE, codepage); - check(Variant.VT_BOOL, Boolean.FALSE, codepage); - check( Variant.VT_CF, new byte[] { 8, 0, 0, 0, 1, 0, 0, 0, 1, 2, 3, - 4 }, codepage ); - check(Variant.VT_I4, Integer.valueOf(27), codepage); - check(Variant.VT_I8, Long.valueOf(28), codepage); - check(Variant.VT_R8, new Double(29.0), codepage); - check(Variant.VT_I4, Integer.valueOf(-27), codepage); - check(Variant.VT_I8, Long.valueOf(-28), codepage); - check(Variant.VT_R8, new Double(-29.0), codepage); - check(Variant.VT_FILETIME, new Date(), codepage); - check(Variant.VT_I4, new Integer(Integer.MAX_VALUE), codepage); - check(Variant.VT_I4, new Integer(Integer.MIN_VALUE), codepage); - check(Variant.VT_I8, new Long(Long.MAX_VALUE), codepage); - check(Variant.VT_I8, new Long(Long.MIN_VALUE), codepage); - check(Variant.VT_R8, new Double(Double.MAX_VALUE), codepage); - check(Variant.VT_R8, new Double(Double.MIN_VALUE), codepage); - - check(Variant.VT_LPSTR, - "", codepage); - check(Variant.VT_LPSTR, - "\u00e4", codepage); - check(Variant.VT_LPSTR, - "\u00e4\u00f6", codepage); - check(Variant.VT_LPSTR, - "\u00e4\u00f6\u00fc", codepage); - check(Variant.VT_LPSTR, - "\u00e4\u00f6\u00fc\u00df", codepage); - check(Variant.VT_LPSTR, - "\u00e4\u00f6\u00fc\u00df\u00c4", codepage); - check(Variant.VT_LPSTR, - "\u00e4\u00f6\u00fc\u00df\u00c4\u00d6", codepage); - check(Variant.VT_LPSTR, - "\u00e4\u00f6\u00fc\u00df\u00c4\u00d6\u00dc", codepage); - - check(Variant.VT_LPWSTR, - "", codepage); - check(Variant.VT_LPWSTR, - "\u00e4", codepage); - check(Variant.VT_LPWSTR, - "\u00e4\u00f6", codepage); - check(Variant.VT_LPWSTR, - "\u00e4\u00f6\u00fc", codepage); - check(Variant.VT_LPWSTR, - "\u00e4\u00f6\u00fc\u00df", codepage); - check(Variant.VT_LPWSTR, - "\u00e4\u00f6\u00fc\u00df\u00c4", codepage); - check(Variant.VT_LPWSTR, - "\u00e4\u00f6\u00fc\u00df\u00c4\u00d6", codepage); - check(Variant.VT_LPWSTR, - "\u00e4\u00f6\u00fc\u00df\u00c4\u00d6\u00dc", codepage); - } - catch (Exception ex) - { - t = ex; - } - catch (Error ex) - { - t = ex; - } - if (t != null) - fail(org.apache.poi.hpsf.Util.toString(t)); - } - - - - /** - *

    Writes and reads back strings using several different codepages and - * checks whether the stuff that has been read back equals the stuff that - * was written.

    - */ - @Test - public void codepages() - { - Throwable thr = null; - final int[] validCodepages = new int[] - {CODEPAGE_DEFAULT, CODEPAGE_UTF8, CODEPAGE_UTF16, CODEPAGE_1252}; - for (final int cp : validCodepages) { - if (cp == -1 && !hasProperDefaultCharset()) - { - System.err.println(IMPROPER_DEFAULT_CHARSET_MESSAGE + - " This testcase is skipped for the default codepage."); - continue; - } - - final long t = cp == CODEPAGE_UTF16 ? Variant.VT_LPWSTR - : Variant.VT_LPSTR; - try - { - check(t, "", cp); - check(t, "\u00e4", cp); - check(t, "\u00e4\u00f6", cp); - check(t, "\u00e4\u00f6\u00fc", cp); - check(t, "\u00e4\u00f6\u00fc\u00c4", cp); - check(t, "\u00e4\u00f6\u00fc\u00c4\u00d6", cp); - check(t, "\u00e4\u00f6\u00fc\u00c4\u00d6\u00dc", cp); - check(t, "\u00e4\u00f6\u00fc\u00c4\u00d6\u00dc\u00df", cp); - if (cp == CodePageUtil.CP_UTF16 || cp == CodePageUtil.CP_UTF8) - check(t, "\u79D1\u5B78", cp); - } - catch (Exception ex) - { - thr = ex; - } - catch (Error ex) - { - thr = ex; - } - if (thr != null) - fail(org.apache.poi.hpsf.Util.toString(thr) + - " with codepage " + cp); - } - - final int[] invalidCodepages = new int[] {0, 1, 2, 4711, 815}; - for (int cp : invalidCodepages) { - final long type = cp == CODEPAGE_UTF16 ? Variant.VT_LPWSTR - : Variant.VT_LPSTR; - try - { - check(type, "", cp); - check(type, "\u00e4", cp); - check(type, "\u00e4\u00f6", cp); - check(type, "\u00e4\u00f6\u00fc", cp); - check(type, "\u00e4\u00f6\u00fc\u00c4", cp); - check(type, "\u00e4\u00f6\u00fc\u00c4\u00d6", cp); - check(type, "\u00e4\u00f6\u00fc\u00c4\u00d6\u00dc", cp); - check(type, "\u00e4\u00f6\u00fc\u00c4\u00d6\u00dc\u00df", cp); - fail("UnsupportedEncodingException for codepage " + cp + - " expected."); - } - catch (UnsupportedEncodingException ex) - { - /* This is the expected behaviour. */ - } - catch (Exception ex) - { - thr = ex; - } - catch (Error ex) - { - thr = ex; - } - if (thr != null) - fail(org.apache.poi.hpsf.Util.toString(thr)); - } - - } - - - - /** - *

    Tests whether writing 8-bit characters to a Unicode property - * succeeds.

    - */ - @Test - public void unicodeWrite8Bit() - { - final String TITLE = "This is a sample title"; - final MutablePropertySet mps = new MutablePropertySet(); - final MutableSection ms = (MutableSection) mps.getSections().get(0); - ms.setFormatID(SectionIDMap.SUMMARY_INFORMATION_ID); - final MutableProperty p = new MutableProperty(); - p.setID(PropertyIDMap.PID_TITLE); - p.setType(Variant.VT_LPSTR); - p.setValue(TITLE); - ms.setProperty(p); - - Throwable t = null; - try - { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - mps.write(out); - out.close(); - byte[] bytes = out.toByteArray(); - - PropertySet psr = new PropertySet(bytes); - assertTrue(psr.isSummaryInformation()); - Section sr = psr.getSections().get(0); - String title = (String) sr.getProperty(PropertyIDMap.PID_TITLE); - assertEquals(TITLE, title); - } - catch (WritingNotSupportedException e) - { - t = e; - } - catch (IOException e) - { - t = e; - } - catch (NoPropertySetStreamException e) - { - t = e; - } - if (t != null) - fail(t.getMessage()); - } - - - - /** - *

    Writes a property and reads it back in.

    - * - * @param variantType The property's variant type. - * @param value The property's value. - * @param codepage The codepage to use for writing and reading. - * @throws UnsupportedVariantTypeException if the variant is not supported. - * @throws IOException if an I/O exception occurs. - * @throws ReadingNotSupportedException - * @throws UnsupportedEncodingException - */ - private void check(final long variantType, final Object value, - final int codepage) - throws UnsupportedVariantTypeException, IOException, - ReadingNotSupportedException, UnsupportedEncodingException - { - final ByteArrayOutputStream out = new ByteArrayOutputStream(); - VariantSupport.write(out, variantType, value, codepage); - out.close(); - final byte[] b = out.toByteArray(); - final Object objRead = - VariantSupport.read(b, 0, b.length + LittleEndian.INT_SIZE, - variantType, codepage); - if (objRead instanceof byte[]) - { - byte[] valueB = (byte[])value; - byte[] readB = (byte[])objRead; - if (valueB.length != readB.length) - fail("Byte arrays are different length - expected " + valueB.length + - " but found " + readB.length); - - final int diff = diff(valueB, readB); - if (diff >= 0) - fail("Byte arrays are different. First different byte is at " + - "index " + diff + "."); - } - else - if (value != null && !value.equals(objRead)) - { - fail("Expected: \"" + value + "\" but was: \"" + objRead + - "\". Codepage: " + codepage + - (codepage == -1 ? - " (" + System.getProperty("file.encoding") + ")." : ".")); - } - else - assertEquals(value, objRead); - } - - - - /** - *

    Compares two byte arrays.

    - * - * @param a The first byte array - * @param b The second byte array - * @return The index of the first byte that is different. If the byte arrays - * are equal, -1 is returned. - */ - private int diff(final byte[] a, final byte[] b) - { - final int min = Math.min(a.length, b.length); - for (int i = 0; i < min; i++) - if (a[i] != b[i]) - return i; - if (a.length != b.length) - return min; - return -1; - } - - - - /** - *

    This test method does a write and read back test with all POI - * filesystems in the "data" directory by performing the following - * actions for each file:

    - * - *
      - * - *
    • Read its property set streams.

    • - * - *
    • Create a new POI filesystem containing the origin file's - * property set streams.

    • - * - *
    • Read the property set streams from the POI filesystem just - * created.

    • - * - *
    • Compare each property set stream with the corresponding one from - * the origin file and check whether they are equal.

    • - * - *
    - * @throws IOException - */ - @Test - public void recreate() throws IOException - { - final File dataDir = _samples.getFile(""); - final File[] fileList = dataDir.listFiles(new FileFilter() - { - @Override - public boolean accept(final File f) - { - return f.getName().startsWith("Test") && TestReadAllFiles.checkExclude(f); - } - }); - for (final File file : fileList) { - try { - testRecreate(file); - } catch (Exception e) { - throw new IOException("While handling file " + file, e); - } - } - } - - - - /** - *

    Performs the check described in {@link #recreate()} for a single - * POI filesystem.

    - * - * @param f the POI filesystem to check - * @throws IOException - * @throws HPSFException - */ - private void testRecreate(final File f) throws IOException, HPSFException - { - /* Read the POI filesystem's property set streams: */ - final POIFile[] psf1 = Util.readPropertySets(f); - - /* Create a new POI filesystem containing the origin file's - * property set streams: */ - final File copy = TempFile.createTempFile(f.getName(), ""); - copy.deleteOnExit(); - final OutputStream out = new FileOutputStream(copy); - final POIFSFileSystem poiFs = new POIFSFileSystem(); - for (POIFile file : psf1) { - final InputStream in = - new ByteArrayInputStream(file.getBytes()); - final PropertySet psIn = PropertySetFactory.create(in); - final MutablePropertySet psOut = new MutablePropertySet(psIn); - final ByteArrayOutputStream psStream = - new ByteArrayOutputStream(); - psOut.write(psStream); - psStream.close(); - final byte[] streamData = psStream.toByteArray(); - poiFs.createDocument(new ByteArrayInputStream(streamData), - file.getName()); - poiFs.writeFilesystem(out); - } - poiFs.close(); - out.close(); - - - /* Read the property set streams from the POI filesystem just - * created. */ - final POIFile[] psf2 = Util.readPropertySets(copy); - for (int i = 0; i < psf2.length; i++) - { - final byte[] bytes1 = psf1[i].getBytes(); - final byte[] bytes2 = psf2[i].getBytes(); - final InputStream in1 = new ByteArrayInputStream(bytes1); - final InputStream in2 = new ByteArrayInputStream(bytes2); - final PropertySet ps1 = PropertySetFactory.create(in1); - final PropertySet ps2 = PropertySetFactory.create(in2); - - /* Compare the property set stream with the corresponding one - * from the origin file and check whether they are equal. */ - assertEquals("Equality for file " + f.getName(), ps1, ps2); - } - } - - - - /** - *

    Tests writing and reading back a proper dictionary.

    - * @throws IOException - * @throws HPSFException - */ - @Test - public void dictionary() throws IOException, HPSFException - { - final File copy = TempFile.createTempFile("Test-HPSF", "ole2"); - copy.deleteOnExit(); - - /* Write: */ - final OutputStream out = new FileOutputStream(copy); - final POIFSFileSystem poiFs = new POIFSFileSystem(); - final MutablePropertySet ps1 = new MutablePropertySet(); - final MutableSection s = (MutableSection) ps1.getSections().get(0); - final Map m = new HashMap(3, 1.0f); - m.put(Long.valueOf(1), "String 1"); - m.put(Long.valueOf(2), "String 2"); - m.put(Long.valueOf(3), "String 3"); - s.setDictionary(m); - s.setFormatID(SectionIDMap.DOCUMENT_SUMMARY_INFORMATION_ID[0]); - int codepage = CodePageUtil.CP_UNICODE; - s.setProperty(PropertyIDMap.PID_CODEPAGE, Variant.VT_I2, - Integer.valueOf(codepage)); - poiFs.createDocument(ps1.toInputStream(), "Test"); - poiFs.writeFilesystem(out); - poiFs.close(); - out.close(); - - /* Read back: */ - final POIFile[] psf = Util.readPropertySets(copy); - assertEquals(1, psf.length); - final byte[] bytes = psf[0].getBytes(); - final InputStream in = new ByteArrayInputStream(bytes); - final PropertySet ps2 = PropertySetFactory.create(in); - - /* Check if the result is a DocumentSummaryInformation stream, as - * specified. */ - assertTrue(ps2.isDocumentSummaryInformation()); - - /* Compare the property set stream with the corresponding one - * from the origin file and check whether they are equal. */ - assertEquals(ps1, ps2); - } - - /** - * Tests that when using NPOIFS, we can do an in-place write - * without needing to stream in + out the whole kitchen sink - */ - @Test - public void inPlaceNPOIFSWrite() throws Exception { - NPOIFSFileSystem fs = null; - DirectoryEntry root = null; - DocumentNode sinfDoc = null; - DocumentNode dinfDoc = null; - SummaryInformation sinf = null; - DocumentSummaryInformation dinf = null; - - // We need to work on a File for in-place changes, so create a temp one - final File copy = TempFile.createTempFile("Test-HPSF", "ole2"); - copy.deleteOnExit(); - - // Copy a test file over to our temp location - InputStream inp = _samples.openResourceAsStream("TestShiftJIS.doc"); - FileOutputStream out = new FileOutputStream(copy); - IOUtils.copy(inp, out); - inp.close(); - out.close(); - - - // Open the copy in read/write mode - fs = new NPOIFSFileSystem(copy, false); - root = fs.getRoot(); - - - // Read the properties in there - sinfDoc = (DocumentNode)root.getEntry(SummaryInformation.DEFAULT_STREAM_NAME); - dinfDoc = (DocumentNode)root.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME); - - InputStream sinfStream = new NDocumentInputStream(sinfDoc); - sinf = (SummaryInformation)PropertySetFactory.create(sinfStream); - sinfStream.close(); - assertEquals(131077, sinf.getOSVersion()); - - InputStream dinfStream = new NDocumentInputStream(dinfDoc); - dinf = (DocumentSummaryInformation)PropertySetFactory.create(dinfStream); - dinfStream.close(); - assertEquals(131077, dinf.getOSVersion()); - - - // Check they start as we expect - assertEquals("Reiichiro Hori", sinf.getAuthor()); - assertEquals("Microsoft Word 9.0", sinf.getApplicationName()); - assertEquals("\u7b2c1\u7ae0", sinf.getTitle()); - - assertEquals("", dinf.getCompany()); - assertEquals(null, dinf.getManager()); - - - // Do an in-place replace via an InputStream - new NPOIFSDocument(sinfDoc).replaceContents(sinf.toInputStream()); - new NPOIFSDocument(dinfDoc).replaceContents(dinf.toInputStream()); - - - // Check it didn't get changed - sinfDoc = (DocumentNode)root.getEntry(SummaryInformation.DEFAULT_STREAM_NAME); - dinfDoc = (DocumentNode)root.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME); - - InputStream sinfStream2 = new NDocumentInputStream(sinfDoc); - sinf = (SummaryInformation)PropertySetFactory.create(sinfStream2); - sinfStream2.close(); - assertEquals(131077, sinf.getOSVersion()); - - InputStream dinfStream2 = new NDocumentInputStream(dinfDoc); - dinf = (DocumentSummaryInformation)PropertySetFactory.create(dinfStream2); - dinfStream2.close(); - assertEquals(131077, dinf.getOSVersion()); - - - // Start again! - fs.close(); - inp = _samples.openResourceAsStream("TestShiftJIS.doc"); - out = new FileOutputStream(copy); - IOUtils.copy(inp, out); - inp.close(); - out.close(); - - fs = new NPOIFSFileSystem(copy, false); - root = fs.getRoot(); - - // Read the properties in once more - sinfDoc = (DocumentNode)root.getEntry(SummaryInformation.DEFAULT_STREAM_NAME); - dinfDoc = (DocumentNode)root.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME); - - InputStream sinfStream3 = new NDocumentInputStream(sinfDoc); - sinf = (SummaryInformation)PropertySetFactory.create(sinfStream3); - sinfStream3.close(); - assertEquals(131077, sinf.getOSVersion()); - - InputStream dinfStream3 = new NDocumentInputStream(dinfDoc); - dinf = (DocumentSummaryInformation)PropertySetFactory.create(dinfStream3); - dinfStream3.close(); - assertEquals(131077, dinf.getOSVersion()); - - - // Have them write themselves in-place with no changes, as an OutputStream - OutputStream soufStream = new NDocumentOutputStream(sinfDoc); - sinf.write(soufStream); - soufStream.close(); - OutputStream doufStream = new NDocumentOutputStream(dinfDoc); - dinf.write(doufStream); - doufStream.close(); - - // And also write to some bytes for checking - ByteArrayOutputStream sinfBytes = new ByteArrayOutputStream(); - sinf.write(sinfBytes); - ByteArrayOutputStream dinfBytes = new ByteArrayOutputStream(); - dinf.write(dinfBytes); - - - // Check that the filesystem can give us back the same bytes - sinfDoc = (DocumentNode)root.getEntry(SummaryInformation.DEFAULT_STREAM_NAME); - dinfDoc = (DocumentNode)root.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME); - - InputStream sinfStream4 = new NDocumentInputStream(sinfDoc); - byte[] sinfData = IOUtils.toByteArray(sinfStream4); - sinfStream4.close(); - InputStream dinfStream4 = new NDocumentInputStream(dinfDoc); - byte[] dinfData = IOUtils.toByteArray(dinfStream4); - dinfStream4.close(); - assertThat(sinfBytes.toByteArray(), equalTo(sinfData)); - assertThat(dinfBytes.toByteArray(), equalTo(dinfData)); - - - // Read back in as-is - InputStream sinfStream5 = new NDocumentInputStream(sinfDoc); - sinf = (SummaryInformation)PropertySetFactory.create(sinfStream5); - sinfStream5.close(); - assertEquals(131077, sinf.getOSVersion()); - - InputStream dinfStream5 = new NDocumentInputStream(dinfDoc); - dinf = (DocumentSummaryInformation)PropertySetFactory.create(dinfStream5); - dinfStream5.close(); - assertEquals(131077, dinf.getOSVersion()); - - assertEquals("Reiichiro Hori", sinf.getAuthor()); - assertEquals("Microsoft Word 9.0", sinf.getApplicationName()); - assertEquals("\u7b2c1\u7ae0", sinf.getTitle()); - - assertEquals("", dinf.getCompany()); - assertEquals(null, dinf.getManager()); - - - // Now alter a few of them - sinf.setAuthor("Changed Author"); - sinf.setTitle("Le titre \u00e9tait chang\u00e9"); - dinf.setManager("Changed Manager"); - - - // Save this into the filesystem - OutputStream soufStream2 = new NDocumentOutputStream(sinfDoc); - sinf.write(soufStream2); - soufStream2.close(); - OutputStream doufStream2 = new NDocumentOutputStream(dinfDoc); - dinf.write(doufStream2); - doufStream2.close(); - - - // Read them back in again - sinfDoc = (DocumentNode)root.getEntry(SummaryInformation.DEFAULT_STREAM_NAME); - InputStream sinfStream6 = new NDocumentInputStream(sinfDoc); - sinf = (SummaryInformation)PropertySetFactory.create(sinfStream6); - sinfStream6.close(); - assertEquals(131077, sinf.getOSVersion()); - - dinfDoc = (DocumentNode)root.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME); - InputStream dinfStream6 = new NDocumentInputStream(dinfDoc); - dinf = (DocumentSummaryInformation)PropertySetFactory.create(dinfStream6); - dinfStream6.close(); - assertEquals(131077, dinf.getOSVersion()); - - assertEquals("Changed Author", sinf.getAuthor()); - assertEquals("Microsoft Word 9.0", sinf.getApplicationName()); - assertEquals("Le titre \u00e9tait chang\u00e9", sinf.getTitle()); - - assertEquals("", dinf.getCompany()); - assertEquals("Changed Manager", dinf.getManager()); - - - // Close the whole filesystem, and open it once more - fs.writeFilesystem(); - fs.close(); - - fs = new NPOIFSFileSystem(copy); - root = fs.getRoot(); - - // Re-check on load - sinfDoc = (DocumentNode)root.getEntry(SummaryInformation.DEFAULT_STREAM_NAME); - InputStream sinfStream7 = new NDocumentInputStream(sinfDoc); - sinf = (SummaryInformation)PropertySetFactory.create(sinfStream7); - sinfStream7.close(); - assertEquals(131077, sinf.getOSVersion()); - - dinfDoc = (DocumentNode)root.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME); - InputStream dinfStream7 = new NDocumentInputStream(dinfDoc); - dinf = (DocumentSummaryInformation)PropertySetFactory.create(dinfStream7); - dinfStream7.close(); - assertEquals(131077, dinf.getOSVersion()); - - assertEquals("Changed Author", sinf.getAuthor()); - assertEquals("Microsoft Word 9.0", sinf.getApplicationName()); - assertEquals("Le titre \u00e9tait chang\u00e9", sinf.getTitle()); - - assertEquals("", dinf.getCompany()); - assertEquals("Changed Manager", dinf.getManager()); - - - // Tidy up - fs.close(); - copy.delete(); - } - - - /** - *

    Tests writing and reading back a proper dictionary with an invalid - * codepage. (HPSF writes Unicode dictionaries only.)

    - * @throws IOException - * @throws HPSFException - */ - @Test(expected=IllegalPropertySetDataException.class) - public void dictionaryWithInvalidCodepage() throws IOException, HPSFException - { - final File copy = TempFile.createTempFile("Test-HPSF", "ole2"); - copy.deleteOnExit(); - - /* Write: */ - final OutputStream out = new FileOutputStream(copy); - - final POIFSFileSystem poiFs = new POIFSFileSystem(); - final MutablePropertySet ps1 = new MutablePropertySet(); - final MutableSection s = (MutableSection) ps1.getSections().get(0); - final Map m = new HashMap(3, 1.0f); - m.put(Long.valueOf(1), "String 1"); - m.put(Long.valueOf(2), "String 2"); - m.put(Long.valueOf(3), "String 3"); - - try { - s.setDictionary(m); - s.setFormatID(SectionIDMap.DOCUMENT_SUMMARY_INFORMATION_ID[0]); - int codepage = 12345; - s.setProperty(PropertyIDMap.PID_CODEPAGE, Variant.VT_I2, - Integer.valueOf(codepage)); - poiFs.createDocument(ps1.toInputStream(), "Test"); - poiFs.writeFilesystem(out); - } finally { - poiFs.close(); - out.close(); - } - } - - - - /** - *

    Returns the display name of the default character set.

    - * - * @return the display name of the default character set. - */ - private String getDefaultCharsetName() - { - final String charSetName = System.getProperty("file.encoding"); - final Charset charSet = Charset.forName(charSetName); - return charSet.displayName(Locale.ROOT); - } - - - - /** - *

    In order to execute tests with characters beyond US-ASCII, this - * method checks whether the application is runing in an environment - * where the default character set is 16-bit-capable.

    - * - * @return true if the default character set is 16-bit-capable, - * else false. - */ - private boolean hasProperDefaultCharset() - { - final String charSetName = System.getProperty("file.encoding"); - final Charset charSet = Charset.forName(charSetName); - return charSet.newEncoder().canEncode('\u00e4'); - } -} diff --git a/src/testcases/org/apache/poi/hpsf/basic/TestWriteWellKnown.java b/src/testcases/org/apache/poi/hpsf/basic/TestWriteWellKnown.java deleted file mode 100644 index b47417ec4..000000000 --- a/src/testcases/org/apache/poi/hpsf/basic/TestWriteWellKnown.java +++ /dev/null @@ -1,744 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hpsf.basic; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.io.File; -import java.io.FileFilter; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.util.Calendar; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hpsf.CustomProperties; -import org.apache.poi.hpsf.CustomProperty; -import org.apache.poi.hpsf.DocumentSummaryInformation; -import org.apache.poi.hpsf.MarkUnsupportedException; -import org.apache.poi.hpsf.MutableProperty; -import org.apache.poi.hpsf.MutableSection; -import org.apache.poi.hpsf.NoPropertySetStreamException; -import org.apache.poi.hpsf.PropertySet; -import org.apache.poi.hpsf.PropertySetFactory; -import org.apache.poi.hpsf.SummaryInformation; -import org.apache.poi.hpsf.UnexpectedPropertySetTypeException; -import org.apache.poi.hpsf.Variant; -import org.apache.poi.hpsf.VariantSupport; -import org.apache.poi.hpsf.WritingNotSupportedException; -import org.apache.poi.hpsf.wellknown.SectionIDMap; -import org.apache.poi.poifs.filesystem.DirectoryEntry; -import org.apache.poi.poifs.filesystem.DocumentInputStream; -import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.LocaleUtil; -import org.apache.poi.util.TempFile; -import org.junit.BeforeClass; -import org.junit.Test; - -/** - *

    Tests HPSF's high-level writing functionality for the well-known property - * set "SummaryInformation" and "DocumentSummaryInformation".

    - */ -public class TestWriteWellKnown { - - private static final String POI_FS = "TestWriteWellKnown.doc"; - - @BeforeClass - public static void setUp() { - VariantSupport.setLogUnsupportedTypes(false); - } - - /** - *

    This test method checks whether DocumentSummary information streams - * can be read. This is done by opening all "Test*" files in the 'poifs' directrory - * pointed to by the "POI.testdata.path" system property, trying to extract - * the document summary information stream in the root directory and calling - * its get... methods.

    - */ - @Test - public void testReadDocumentSummaryInformation() - throws FileNotFoundException, IOException, - NoPropertySetStreamException, MarkUnsupportedException, - UnexpectedPropertySetTypeException - { - POIDataSamples _samples = POIDataSamples.getHPSFInstance(); - final File dataDir = _samples.getFile(""); - final File[] docs = dataDir.listFiles(new FileFilter() - { - @Override - public boolean accept(final File file) - { - return file.isFile() && file.getName().startsWith("Test") && TestReadAllFiles.checkExclude(file); - } - }); - - for (final File doc : docs) { - NPOIFSFileSystem poifs = null; - try { - /* Read a test document doc into a POI filesystem. */ - poifs = new NPOIFSFileSystem(doc, true); - final DirectoryEntry dir = poifs.getRoot(); - /* - * If there is a document summry information stream, read it from - * the POI filesystem. - */ - if (dir.hasEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME)) { - final DocumentSummaryInformation dsi = getDocumentSummaryInformation(poifs); - - /* Execute the get... methods. */ - dsi.getByteCount(); - dsi.getByteOrder(); - dsi.getCategory(); - dsi.getCompany(); - dsi.getCustomProperties(); - // FIXME dsi.getDocparts(); - // FIXME dsi.getHeadingPair(); - dsi.getHiddenCount(); - dsi.getLineCount(); - dsi.getLinksDirty(); - dsi.getManager(); - dsi.getMMClipCount(); - dsi.getNoteCount(); - dsi.getParCount(); - dsi.getPresentationFormat(); - dsi.getScale(); - dsi.getSlideCount(); - } - } catch (Exception e) { - throw new IOException("While handling file " + doc, e); - } finally { - if (poifs != null) poifs.close(); - } - } - } - - static final String P_APPLICATION_NAME = "ApplicationName"; - static final String P_AUTHOR = "Author"; - static final int P_CHAR_COUNT = 4712; - static final String P_COMMENTS = "Comments"; - static final Date P_CREATE_DATE_TIME; - static final long P_EDIT_TIME = 4713 * 1000 * 10; - static final String P_KEYWORDS = "Keywords"; - static final String P_LAST_AUTHOR = "LastAuthor"; - static final Date P_LAST_PRINTED; - static final Date P_LAST_SAVE_DATE_TIME; - static final int P_PAGE_COUNT = 4714; - static final String P_REV_NUMBER = "RevNumber"; - static final int P_SECURITY = 1; - static final String P_SUBJECT = "Subject"; - static final String P_TEMPLATE = "Template"; - // FIXME (byte array properties not yet implemented): static final byte[] P_THUMBNAIL = new byte[123]; - static final String P_TITLE = "Title"; - static final int P_WORD_COUNT = 4715; - - static final int P_BYTE_COUNT = 4716; - static final String P_CATEGORY = "Category"; - static final String P_COMPANY = "Company"; - // FIXME (byte array properties not yet implemented): static final byte[] P_DOCPARTS = new byte[123]; - // FIXME (byte array properties not yet implemented): static final byte[] P_HEADING_PAIR = new byte[123]; - static final int P_HIDDEN_COUNT = 4717; - static final int P_LINE_COUNT = 4718; - static final boolean P_LINKS_DIRTY = true; - static final String P_MANAGER = "Manager"; - static final int P_MM_CLIP_COUNT = 4719; - static final int P_NOTE_COUNT = 4720; - static final int P_PAR_COUNT = 4721; - static final String P_PRESENTATION_FORMAT = "PresentationFormat"; - static final boolean P_SCALE = false; - static final int P_SLIDE_COUNT = 4722; - static final Date now = new Date(); - - static final Integer POSITIVE_INTEGER = new Integer(2222); - static final Long POSITIVE_LONG = new Long(3333); - static final Double POSITIVE_DOUBLE = new Double(4444); - static final Integer NEGATIVE_INTEGER = new Integer(2222); - static final Long NEGATIVE_LONG = new Long(3333); - static final Double NEGATIVE_DOUBLE = new Double(4444); - - static final Integer MAX_INTEGER = new Integer(Integer.MAX_VALUE); - static final Integer MIN_INTEGER = new Integer(Integer.MIN_VALUE); - static final Long MAX_LONG = new Long(Long.MAX_VALUE); - static final Long MIN_LONG = new Long(Long.MIN_VALUE); - static final Double MAX_DOUBLE = new Double(Double.MAX_VALUE); - static final Double MIN_DOUBLE = new Double(Double.MIN_VALUE); - - static { - Calendar cal = LocaleUtil.getLocaleCalendar(2000, 6, 6, 6, 6, 6); - P_CREATE_DATE_TIME = cal.getTime(); - cal.set(2001, 7, 7, 7, 7, 7); - P_LAST_PRINTED = cal.getTime(); - cal.set(2002, 8, 8, 8, 8, 8); - P_LAST_SAVE_DATE_TIME = cal.getTime(); - } - - /** - *

    This test method test the writing of properties in the well-known - * property set streams "SummaryInformation" and - * "DocumentSummaryInformation" by performing the following steps:

    - * - *
      - * - *
    1. Read a test document doc1 into a POI filesystem.

    2. - * - *
    3. Read the summary information stream and the document summary - * information stream from the POI filesystem.

    4. - * - *
    5. Write all properties supported by HPSF to the summary - * information (e.g. author, edit date, application name) and to the - * document summary information (e.g. company, manager).

    6. - * - *
    7. Write the summary information stream and the document summary - * information stream to the POI filesystem.

    8. - * - *
    9. Write the POI filesystem to a (temporary) file doc2 - * and close the latter.

    10. - * - *
    11. Open doc2 for reading and check summary information - * and document summary information. All properties written before must be - * found in the property streams of doc2 and have the correct - * values.

    12. - * - *
    13. Remove all properties supported by HPSF from the summary - * information (e.g. author, edit date, application name) and from the - * document summary information (e.g. company, manager).

    14. - * - *
    15. Write the summary information stream and the document summary - * information stream to the POI filesystem.

    16. - * - *
    17. Write the POI filesystem to a (temporary) file doc3 - * and close the latter.

    18. - * - *
    19. Open doc3 for reading and check summary information - * and document summary information. All properties removed before must not - * be found in the property streams of doc3.

    - * - * @throws IOException if some I/O error occurred. - * @throws MarkUnsupportedException - * @throws NoPropertySetStreamException - * @throws UnexpectedPropertySetTypeException - * @throws WritingNotSupportedException - */ - @Test - public void testWriteWellKnown() throws Exception { - POIDataSamples _samples = POIDataSamples.getHPSFInstance(); - - final File doc1 = TempFile.createTempFile("POI_HPSF_Test1.", ".tmp"); - final File doc2 = TempFile.createTempFile("POI_HPSF_Test2.", ".tmp"); - final File doc3 = TempFile.createTempFile("POI_HPSF_Test3.", ".tmp"); - - FileInputStream fis = new FileInputStream(_samples.getFile(POI_FS)); - FileOutputStream fos = new FileOutputStream(doc1); - IOUtils.copy(fis, fos); - fos.close(); - fis.close(); - - CustomProperties cps1 = write1stFile(doc1, doc2); - CustomProperties cps2 = write2ndFile(doc2, doc3); - write3rdFile(doc3, null); - - assertEquals(cps1, cps2); - } - - /* - * Write all properties supported by HPSF to the summary information - * (e.g. author, edit date, application name) and to the document - * summary information (e.g. company, manager). - */ - private static CustomProperties write1stFile(File fileIn, File fileOut) throws Exception { - /* Read a test document doc1 into a POI filesystem. */ - NPOIFSFileSystem poifs = new NPOIFSFileSystem(fileIn, false); - - /* - * Read the summary information stream and the document summary - * information stream from the POI filesystem. - * - * Please note that the result consists of SummaryInformation and - * DocumentSummaryInformation instances which are in memory only. To - * make them permanent they have to be written to a POI filesystem - * explicitly (overwriting the former contents). Then the POI filesystem - * should be saved to a file. - */ - SummaryInformation si = getSummaryInformation(poifs); - DocumentSummaryInformation dsi = getDocumentSummaryInformation(poifs); - - si.setApplicationName(P_APPLICATION_NAME); - si.setAuthor(P_AUTHOR); - si.setCharCount(P_CHAR_COUNT); - si.setComments(P_COMMENTS); - si.setCreateDateTime(P_CREATE_DATE_TIME); - si.setEditTime(P_EDIT_TIME); - si.setKeywords(P_KEYWORDS); - si.setLastAuthor(P_LAST_AUTHOR); - si.setLastPrinted(P_LAST_PRINTED); - si.setLastSaveDateTime(P_LAST_SAVE_DATE_TIME); - si.setPageCount(P_PAGE_COUNT); - si.setRevNumber(P_REV_NUMBER); - si.setSecurity(P_SECURITY); - si.setSubject(P_SUBJECT); - si.setTemplate(P_TEMPLATE); - // FIXME (byte array properties not yet implemented): si.setThumbnail(P_THUMBNAIL); - si.setTitle(P_TITLE); - si.setWordCount(P_WORD_COUNT); - - dsi.setByteCount(P_BYTE_COUNT); - dsi.setCategory(P_CATEGORY); - dsi.setCompany(P_COMPANY); - // FIXME (byte array properties not yet implemented): dsi.setDocparts(P_DOCPARTS); - // FIXME (byte array properties not yet implemented): dsi.setHeadingPair(P_HEADING_PAIR); - dsi.setHiddenCount(P_HIDDEN_COUNT); - dsi.setLineCount(P_LINE_COUNT); - dsi.setLinksDirty(P_LINKS_DIRTY); - dsi.setManager(P_MANAGER); - dsi.setMMClipCount(P_MM_CLIP_COUNT); - dsi.setNoteCount(P_NOTE_COUNT); - dsi.setParCount(P_PAR_COUNT); - dsi.setPresentationFormat(P_PRESENTATION_FORMAT); - dsi.setScale(P_SCALE); - dsi.setSlideCount(P_SLIDE_COUNT); - - CustomProperties cps = dsi.getCustomProperties(); - assertNull(cps); - cps = new CustomProperties(); - cps.put("Schl\u00fcssel \u00e4", "Wert \u00e4"); - cps.put("Schl\u00fcssel \u00e4\u00f6", "Wert \u00e4\u00f6"); - cps.put("Schl\u00fcssel \u00e4\u00f6\u00fc", "Wert \u00e4\u00f6\u00fc"); - cps.put("Schl\u00fcssel \u00e4\u00f6\u00fc\u00d6", "Wert \u00e4\u00f6\u00fc\u00d6"); - cps.put("positive_Integer", POSITIVE_INTEGER); - cps.put("positive_Long", POSITIVE_LONG); - cps.put("positive_Double", POSITIVE_DOUBLE); - cps.put("negative_Integer", NEGATIVE_INTEGER); - cps.put("negative_Long", NEGATIVE_LONG); - cps.put("negative_Double", NEGATIVE_DOUBLE); - cps.put("Boolean", Boolean.TRUE); - cps.put("Date", now); - cps.put("max_Integer", MAX_INTEGER); - cps.put("min_Integer", MIN_INTEGER); - cps.put("max_Long", MAX_LONG); - cps.put("min_Long", MIN_LONG); - cps.put("max_Double", MAX_DOUBLE); - cps.put("min_Double", MIN_DOUBLE); - - // Check the keys went in - assertTrue(cps.containsKey("Schl\u00fcssel \u00e4")); - assertTrue(cps.containsKey("Boolean")); - - // Check the values went in - assertEquals("Wert \u00e4", cps.get("Schl\u00fcssel \u00e4")); - assertEquals(Boolean.TRUE, cps.get("Boolean")); - assertTrue(cps.containsValue(Boolean.TRUE)); - assertTrue(cps.containsValue("Wert \u00e4")); - - // Check that things that aren't in aren't in - assertFalse(cps.containsKey("False Boolean")); - assertFalse(cps.containsValue(Boolean.FALSE)); - - // Save as our custom properties - dsi.setCustomProperties(cps); - - - /* Write the summary information stream and the document summary - * information stream to the POI filesystem. */ - si.write(poifs.getRoot(), SummaryInformation.DEFAULT_STREAM_NAME); - dsi.write(poifs.getRoot(), DocumentSummaryInformation.DEFAULT_STREAM_NAME); - - /* Write the POI filesystem to a (temporary) file doc2 - * and close the latter. */ - OutputStream out = new FileOutputStream(fileOut); - poifs.writeFilesystem(out); - out.close(); - poifs.close(); - - return cps; - } - - /* - * Open doc2 for reading and check summary information and - * document summary information. All properties written before must be - * found in the property streams of doc2 and have the correct - * values. - */ - private static CustomProperties write2ndFile(File fileIn, File fileOut) throws Exception { - NPOIFSFileSystem poifs = new NPOIFSFileSystem(fileIn, false); - SummaryInformation si = getSummaryInformation(poifs); - DocumentSummaryInformation dsi = getDocumentSummaryInformation(poifs); - - assertEquals(P_APPLICATION_NAME, si.getApplicationName()); - assertEquals(P_AUTHOR, si.getAuthor()); - assertEquals(P_CHAR_COUNT, si.getCharCount()); - assertEquals(P_COMMENTS, si.getComments()); - assertEquals(P_CREATE_DATE_TIME, si.getCreateDateTime()); - assertEquals(P_EDIT_TIME, si.getEditTime()); - assertEquals(P_KEYWORDS, si.getKeywords()); - assertEquals(P_LAST_AUTHOR, si.getLastAuthor()); - assertEquals(P_LAST_PRINTED, si.getLastPrinted()); - assertEquals(P_LAST_SAVE_DATE_TIME, si.getLastSaveDateTime()); - assertEquals(P_PAGE_COUNT, si.getPageCount()); - assertEquals(P_REV_NUMBER, si.getRevNumber()); - assertEquals(P_SECURITY, si.getSecurity()); - assertEquals(P_SUBJECT, si.getSubject()); - assertEquals(P_TEMPLATE, si.getTemplate()); - // FIXME (byte array properties not yet implemented): assertEquals(P_THUMBNAIL, si.getThumbnail()); - assertEquals(P_TITLE, si.getTitle()); - assertEquals(P_WORD_COUNT, si.getWordCount()); - - assertEquals(P_BYTE_COUNT, dsi.getByteCount()); - assertEquals(P_CATEGORY, dsi.getCategory()); - assertEquals(P_COMPANY, dsi.getCompany()); - // FIXME (byte array properties not yet implemented): assertEquals(P_, dsi.getDocparts()); - // FIXME (byte array properties not yet implemented): assertEquals(P_, dsi.getHeadingPair()); - assertEquals(P_HIDDEN_COUNT, dsi.getHiddenCount()); - assertEquals(P_LINE_COUNT, dsi.getLineCount()); - assertEquals(P_LINKS_DIRTY, dsi.getLinksDirty()); - assertEquals(P_MANAGER, dsi.getManager()); - assertEquals(P_MM_CLIP_COUNT, dsi.getMMClipCount()); - assertEquals(P_NOTE_COUNT, dsi.getNoteCount()); - assertEquals(P_PAR_COUNT, dsi.getParCount()); - assertEquals(P_PRESENTATION_FORMAT, dsi.getPresentationFormat()); - assertEquals(P_SCALE, dsi.getScale()); - assertEquals(P_SLIDE_COUNT, dsi.getSlideCount()); - - final CustomProperties cps = dsi.getCustomProperties(); - assertNotNull(cps); - assertNull(cps.get("No value available")); - assertEquals("Wert \u00e4", cps.get("Schl\u00fcssel \u00e4")); - assertEquals("Wert \u00e4\u00f6", cps.get("Schl\u00fcssel \u00e4\u00f6")); - assertEquals("Wert \u00e4\u00f6\u00fc", cps.get("Schl\u00fcssel \u00e4\u00f6\u00fc")); - assertEquals("Wert \u00e4\u00f6\u00fc\u00d6", cps.get("Schl\u00fcssel \u00e4\u00f6\u00fc\u00d6")); - assertEquals(POSITIVE_INTEGER, cps.get("positive_Integer")); - assertEquals(POSITIVE_LONG, cps.get("positive_Long")); - assertEquals(POSITIVE_DOUBLE, cps.get("positive_Double")); - assertEquals(NEGATIVE_INTEGER, cps.get("negative_Integer")); - assertEquals(NEGATIVE_LONG, cps.get("negative_Long")); - assertEquals(NEGATIVE_DOUBLE, cps.get("negative_Double")); - assertEquals(Boolean.TRUE, cps.get("Boolean")); - assertEquals(now, cps.get("Date")); - assertEquals(MAX_INTEGER, cps.get("max_Integer")); - assertEquals(MIN_INTEGER, cps.get("min_Integer")); - assertEquals(MAX_LONG, cps.get("max_Long")); - assertEquals(MIN_LONG, cps.get("min_Long")); - assertEquals(MAX_DOUBLE, cps.get("max_Double")); - assertEquals(MIN_DOUBLE, cps.get("min_Double")); - - /* Remove all properties supported by HPSF from the summary - * information (e.g. author, edit date, application name) and from the - * document summary information (e.g. company, manager). */ - si.removeApplicationName(); - si.removeAuthor(); - si.removeCharCount(); - si.removeComments(); - si.removeCreateDateTime(); - si.removeEditTime(); - si.removeKeywords(); - si.removeLastAuthor(); - si.removeLastPrinted(); - si.removeLastSaveDateTime(); - si.removePageCount(); - si.removeRevNumber(); - si.removeSecurity(); - si.removeSubject(); - si.removeTemplate(); - si.removeThumbnail(); - si.removeTitle(); - si.removeWordCount(); - - dsi.removeByteCount(); - dsi.removeCategory(); - dsi.removeCompany(); - dsi.removeCustomProperties(); - dsi.removeDocparts(); - dsi.removeHeadingPair(); - dsi.removeHiddenCount(); - dsi.removeLineCount(); - dsi.removeLinksDirty(); - dsi.removeManager(); - dsi.removeMMClipCount(); - dsi.removeNoteCount(); - dsi.removeParCount(); - dsi.removePresentationFormat(); - dsi.removeScale(); - dsi.removeSlideCount(); - - /* - *
  • Write the summary information stream and the document summary - * information stream to the POI filesystem. */ - si.write(poifs.getRoot(), SummaryInformation.DEFAULT_STREAM_NAME); - dsi.write(poifs.getRoot(), DocumentSummaryInformation.DEFAULT_STREAM_NAME); - - /* - *

  • Write the POI filesystem to a (temporary) file doc3 - * and close the latter. */ - FileOutputStream out = new FileOutputStream(fileOut); - poifs.writeFilesystem(out); - out.close(); - poifs.close(); - - return cps; - } - - /* - * Open doc3 for reading and check summary information - * and document summary information. All properties removed before must not - * be found in the property streams of doc3. - */ - private static CustomProperties write3rdFile(File fileIn, File fileOut) throws Exception { - NPOIFSFileSystem poifs = new NPOIFSFileSystem(fileIn, false); - SummaryInformation si = getSummaryInformation(poifs); - DocumentSummaryInformation dsi = getDocumentSummaryInformation(poifs); - - assertNull(si.getApplicationName()); - assertNull(si.getAuthor()); - assertEquals(0, si.getCharCount()); - assertTrue(si.wasNull()); - assertNull(si.getComments()); - assertNull(si.getCreateDateTime()); - assertEquals(0, si.getEditTime()); - assertTrue(si.wasNull()); - assertNull(si.getKeywords()); - assertNull(si.getLastAuthor()); - assertNull(si.getLastPrinted()); - assertNull(si.getLastSaveDateTime()); - assertEquals(0, si.getPageCount()); - assertTrue(si.wasNull()); - assertNull(si.getRevNumber()); - assertEquals(0, si.getSecurity()); - assertTrue(si.wasNull()); - assertNull(si.getSubject()); - assertNull(si.getTemplate()); - assertNull(si.getThumbnail()); - assertNull(si.getTitle()); - assertEquals(0, si.getWordCount()); - assertTrue(si.wasNull()); - - assertEquals(0, dsi.getByteCount()); - assertTrue(dsi.wasNull()); - assertNull(dsi.getCategory()); - assertNull(dsi.getCustomProperties()); - // FIXME (byte array properties not yet implemented): assertNull(dsi.getDocparts()); - // FIXME (byte array properties not yet implemented): assertNull(dsi.getHeadingPair()); - assertEquals(0, dsi.getHiddenCount()); - assertTrue(dsi.wasNull()); - assertEquals(0, dsi.getLineCount()); - assertTrue(dsi.wasNull()); - assertFalse(dsi.getLinksDirty()); - assertTrue(dsi.wasNull()); - assertNull(dsi.getManager()); - assertEquals(0, dsi.getMMClipCount()); - assertTrue(dsi.wasNull()); - assertEquals(0, dsi.getNoteCount()); - assertTrue(dsi.wasNull()); - assertEquals(0, dsi.getParCount()); - assertTrue(dsi.wasNull()); - assertNull(dsi.getPresentationFormat()); - assertFalse(dsi.getScale()); - assertTrue(dsi.wasNull()); - assertEquals(0, dsi.getSlideCount()); - assertTrue(dsi.wasNull()); - poifs.close(); - - return dsi.getCustomProperties(); - } - - private static SummaryInformation getSummaryInformation(NPOIFSFileSystem poifs) throws Exception { - DocumentInputStream dis = poifs.createDocumentInputStream(SummaryInformation.DEFAULT_STREAM_NAME); - PropertySet ps = new PropertySet(dis); - SummaryInformation si = new SummaryInformation(ps); - dis.close(); - return si; - } - - private static DocumentSummaryInformation getDocumentSummaryInformation(NPOIFSFileSystem poifs) throws Exception { - DocumentInputStream dis = poifs.createDocumentInputStream(DocumentSummaryInformation.DEFAULT_STREAM_NAME); - PropertySet ps = new PropertySet(dis); - DocumentSummaryInformation dsi = new DocumentSummaryInformation(ps); - dis.close(); - return dsi; - } - - - - /** - *

    Tests the simplified custom properties by reading them from the - * available test files.

    - * - * @throws Throwable if anything goes wrong. - */ - @Test - public void testReadCustomPropertiesFromFiles() throws Throwable - { - final AllDataFilesTester.TestTask task = new AllDataFilesTester.TestTask() - { - @Override - public void runTest(final File file) throws FileNotFoundException, - IOException, NoPropertySetStreamException, - MarkUnsupportedException, - UnexpectedPropertySetTypeException - { - /* Read a test document doc into a POI filesystem. */ - NPOIFSFileSystem poifs = null; - try { - poifs = new NPOIFSFileSystem(file); - final DirectoryEntry dir = poifs.getRoot(); - /* - * If there is a document summry information stream, read it from - * the POI filesystem, else create a new one. - */ - DocumentSummaryInformation dsi; - if (dir.hasEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME)) { - final DocumentInputStream dis = poifs.createDocumentInputStream(DocumentSummaryInformation.DEFAULT_STREAM_NAME); - final PropertySet ps = new PropertySet(dis); - dsi = new DocumentSummaryInformation(ps); - dis.close(); - } else { - dsi = PropertySetFactory.newDocumentSummaryInformation(); - } - final CustomProperties cps = dsi.getCustomProperties(); - - if (cps == null) - /* The document does not have custom properties. */ - return; - - for (CustomProperty cp : cps.values()) { - cp.getName(); - cp.getValue(); - } - } finally { - if (poifs != null) poifs.close(); - } - } - }; - - POIDataSamples _samples = POIDataSamples.getHPSFInstance(); - final File dataDir = _samples.getFile(""); - final File[] docs = dataDir.listFiles(new FileFilter() - { - @Override - public boolean accept(final File file) - { - return file.isFile() && file.getName().startsWith("Test") && TestReadAllFiles.checkExclude(file); - } - }); - - for (File doc : docs) { - try { - task.runTest(doc); - } catch (Exception e) { - throw new IOException("While handling file " + doc, e); - } - } - } - - - - /** - *

    Tests basic custom property features.

    - */ - @Test - public void testCustomerProperties() - { - final String KEY = "Schl\u00fcssel \u00e4"; - final String VALUE_1 = "Wert 1"; - final String VALUE_2 = "Wert 2"; - - CustomProperty cp; - CustomProperties cps = new CustomProperties(); - assertEquals(0, cps.size()); - - /* After adding a custom property the size must be 1 and it must be - * possible to extract the custom property from the map. */ - cps.put(KEY, VALUE_1); - assertEquals(1, cps.size()); - Object v1 = cps.get(KEY); - assertEquals(VALUE_1, v1); - - /* After adding a custom property with the same name the size must still - * be one. */ - cps.put(KEY, VALUE_2); - assertEquals(1, cps.size()); - Object v2 = cps.get(KEY); - assertEquals(VALUE_2, v2); - - /* Removing the custom property must return the remove property and - * reduce the size to 0. */ - cp = (CustomProperty) cps.remove(KEY); - assertEquals(KEY, cp.getName()); - assertEquals(VALUE_2, cp.getValue()); - assertEquals(0, cps.size()); - } - - - - /** - *

    Tests reading custom properties from a section including reading - * custom properties which are not pure.

    - */ - @Test - public void testGetCustomerProperties() - { - final int ID_1 = 2; - final int ID_2 = 3; - final String NAME_1 = "Schl\u00fcssel \u00e4"; - final String VALUE_1 = "Wert 1"; - final Map dictionary = new HashMap(); - - DocumentSummaryInformation dsi = PropertySetFactory.newDocumentSummaryInformation(); - CustomProperties cps; - MutableSection s; - - /* A document summary information set stream by default does have custom properties. */ - cps = dsi.getCustomProperties(); - assertNull(cps); - - /* Test an empty custom properties set. */ - s = new MutableSection(); - s.setFormatID(SectionIDMap.DOCUMENT_SUMMARY_INFORMATION_ID[1]); - // s.setCodepage(CodePageUtil.CP_UNICODE); - dsi.addSection(s); - cps = dsi.getCustomProperties(); - assertEquals(0, cps.size()); - - /* Add a custom property. */ - MutableProperty p = new MutableProperty(); - p.setID(ID_1); - p.setType(Variant.VT_LPWSTR); - p.setValue(VALUE_1); - s.setProperty(p); - dictionary.put(Long.valueOf(ID_1), NAME_1); - s.setDictionary(dictionary); - cps = dsi.getCustomProperties(); - assertEquals(1, cps.size()); - assertTrue(cps.isPure()); - - /* Add another custom property. */ - s.setProperty(ID_2, Variant.VT_LPWSTR, VALUE_1); - dictionary.put(Long.valueOf(ID_2), NAME_1); - s.setDictionary(dictionary); - cps = dsi.getCustomProperties(); - assertEquals(1, cps.size()); - assertFalse(cps.isPure()); - } -} diff --git a/src/testcases/org/apache/poi/hpsf/basic/Util.java b/src/testcases/org/apache/poi/hpsf/basic/Util.java deleted file mode 100644 index 668b1858a..000000000 --- a/src/testcases/org/apache/poi/hpsf/basic/Util.java +++ /dev/null @@ -1,264 +0,0 @@ - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hpsf.basic; - -import java.io.ByteArrayOutputStream; -import java.io.EOFException; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; -import java.util.Properties; - -import org.apache.poi.hpsf.PropertySet; -import org.apache.poi.poifs.eventfilesystem.POIFSReader; -import org.apache.poi.poifs.eventfilesystem.POIFSReaderEvent; -import org.apache.poi.poifs.eventfilesystem.POIFSReaderListener; - - - -/** - *

    Static utility methods needed by the HPSF test cases.

    - */ -final class Util { - - /** - *

    Reads bytes from an input stream and writes them to an - * output stream until end of file is encountered.

    - * - * @param in the input stream to read from - * - * @param out the output stream to write to - * - * @exception IOException if an I/O exception occurs - */ - public static void copy(final InputStream in, final OutputStream out) - throws IOException - { - final int BUF_SIZE = 1000; - byte[] b = new byte[BUF_SIZE]; - int read; - boolean eof = false; - while (!eof) - { - try - { - read = in.read(b, 0, BUF_SIZE); - if (read > 0) - out.write(b, 0, read); - else - eof = true; - } - catch (EOFException ex) - { - eof = true; - } - } - } - - - - /** - *

    Reads all files from a POI filesystem and returns them as an - * array of {@link POIFile} instances. This method loads all files - * into memory and thus does not cope well with large POI - * filessystems.

    - * - * @param poiFs The name of the POI filesystem as seen by the - * operating system. (This is the "filename".) - * - * @return The POI files. The elements are ordered in the same way - * as the files in the POI filesystem. - * - * @exception FileNotFoundException if the file containing the POI - * filesystem does not exist - * - * @exception IOException if an I/O exception occurs - */ - public static POIFile[] readPOIFiles(final File poiFs) - throws FileNotFoundException, IOException - { - return readPOIFiles(poiFs, null); - } - - - - /** - *

    Reads a set of files from a POI filesystem and returns them - * as an array of {@link POIFile} instances. This method loads all - * files into memory and thus does not cope well with large POI - * filessystems.

    - * - * @param poiFs The name of the POI filesystem as seen by the - * operating system. (This is the "filename".) - * - * @param poiFiles The names of the POI files to be read. - * - * @return The POI files. The elements are ordered in the same way - * as the files in the POI filesystem. - * - * @exception FileNotFoundException if the file containing the POI - * filesystem does not exist - * - * @exception IOException if an I/O exception occurs - */ - public static POIFile[] readPOIFiles(final File poiFs, - final String[] poiFiles) - throws FileNotFoundException, IOException - { - final List files = new ArrayList(); - POIFSReader r = new POIFSReader(); - POIFSReaderListener pfl = new POIFSReaderListener() - { - @Override - public void processPOIFSReaderEvent(final POIFSReaderEvent event) - { - try - { - final POIFile f = new POIFile(); - f.setName(event.getName()); - f.setPath(event.getPath()); - final InputStream in = event.getStream(); - final ByteArrayOutputStream out = - new ByteArrayOutputStream(); - Util.copy(in, out); - out.close(); - f.setBytes(out.toByteArray()); - files.add(f); - } - catch (IOException ex) - { - throw new RuntimeException(ex); - } - } - }; - if (poiFiles == null) - /* Register the listener for all POI files. */ - r.registerListener(pfl); - else - for (String poiFile : poiFiles) - r.registerListener(pfl, poiFile); - - /* Read the POI filesystem. */ - FileInputStream stream = new FileInputStream(poiFs); - try { - r.read(stream); - } finally { - stream.close(); - } - POIFile[] result = new POIFile[files.size()]; - for (int i = 0; i < result.length; i++) - result[i] = files.get(i); - return result; - } - - - - /** - *

    Read all files from a POI filesystem which are property set streams - * and returns them as an array of {@link org.apache.poi.hpsf.PropertySet} - * instances.

    - * - * @param poiFs The name of the POI filesystem as seen by the - * operating system. (This is the "filename".) - * - * @return The property sets. The elements are ordered in the same way - * as the files in the POI filesystem. - * - * @exception FileNotFoundException if the file containing the POI - * filesystem does not exist - * - * @exception IOException if an I/O exception occurs - */ - public static POIFile[] readPropertySets(final File poiFs) - throws FileNotFoundException, IOException - { - final List files = new ArrayList(7); - final POIFSReader r = new POIFSReader(); - POIFSReaderListener pfl = new POIFSReaderListener() - { - @Override - public void processPOIFSReaderEvent(final POIFSReaderEvent event) - { - try - { - final POIFile f = new POIFile(); - f.setName(event.getName()); - f.setPath(event.getPath()); - final InputStream in = event.getStream(); - if (PropertySet.isPropertySetStream(in)) - { - final ByteArrayOutputStream out = - new ByteArrayOutputStream(); - Util.copy(in, out); - out.close(); - f.setBytes(out.toByteArray()); - files.add(f); - } - } - catch (Exception ex) - { - throw new RuntimeException(ex); - } - } - }; - - /* Register the listener for all POI files. */ - r.registerListener(pfl); - - /* Read the POI filesystem. */ - FileInputStream stream = new FileInputStream(poiFs); - try { - r.read(stream); - } finally { - stream.close(); - } - - POIFile[] result = new POIFile[files.size()]; - for (int i = 0; i < result.length; i++) - result[i] = files.get(i); - return result; - } - - - - /** - *

    Prints the system properties to System.out.

    - */ - public static void printSystemProperties() - { - final Properties p = System.getProperties(); - final List names = new LinkedList(); - for (String name : p.stringPropertyNames()) - names.add(name); - Collections.sort(names); - for (String name : names) { - String value = p.getProperty(name); - System.out.println(name + ": " + value); - } - System.out.println("Current directory: " + - System.getProperty("user.dir")); - } -} diff --git a/src/testcases/org/apache/poi/hpsf/extractor/TestHPSFPropertiesExtractor.java b/src/testcases/org/apache/poi/hpsf/extractor/TestHPSFPropertiesExtractor.java deleted file mode 100644 index 0d7ce885c..000000000 --- a/src/testcases/org/apache/poi/hpsf/extractor/TestHPSFPropertiesExtractor.java +++ /dev/null @@ -1,189 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hpsf.extractor; - -import java.io.IOException; - -import junit.framework.TestCase; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hpsf.Thumbnail; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.extractor.ExcelExtractor; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; - -public final class TestHPSFPropertiesExtractor extends TestCase { - private static final POIDataSamples _samples = POIDataSamples.getHPSFInstance(); - - public void testNormalProperties() throws Exception { - POIFSFileSystem fs = new POIFSFileSystem(_samples.openResourceAsStream("TestMickey.doc")); - HPSFPropertiesExtractor ext = new HPSFPropertiesExtractor(fs); - try { - ext.getText(); - - // Check each bit in turn - String sinfText = ext.getSummaryInformationText(); - String dinfText = ext.getDocumentSummaryInformationText(); - - assertTrue(sinfText.indexOf("TEMPLATE = Normal") > -1); - assertTrue(sinfText.indexOf("SUBJECT = sample subject") > -1); - assertTrue(dinfText.indexOf("MANAGER = sample manager") > -1); - assertTrue(dinfText.indexOf("COMPANY = sample company") > -1); - - // Now overall - String text = ext.getText(); - assertTrue(text.indexOf("TEMPLATE = Normal") > -1); - assertTrue(text.indexOf("SUBJECT = sample subject") > -1); - assertTrue(text.indexOf("MANAGER = sample manager") > -1); - assertTrue(text.indexOf("COMPANY = sample company") > -1); - } finally { - ext.close(); - } - } - - public void testNormalUnicodeProperties() throws Exception { - POIFSFileSystem fs = new POIFSFileSystem(_samples.openResourceAsStream("TestUnicode.xls")); - HPSFPropertiesExtractor ext = new HPSFPropertiesExtractor(fs); - try { - ext.getText(); - - // Check each bit in turn - String sinfText = ext.getSummaryInformationText(); - String dinfText = ext.getDocumentSummaryInformationText(); - - assertTrue(sinfText.indexOf("AUTHOR = marshall") > -1); - assertTrue(sinfText.indexOf("TITLE = Titel: \u00c4h") > -1); - assertTrue(dinfText.indexOf("COMPANY = Schreiner") > -1); - assertTrue(dinfText.indexOf("SCALE = false") > -1); - - // Now overall - String text = ext.getText(); - assertTrue(text.indexOf("AUTHOR = marshall") > -1); - assertTrue(text.indexOf("TITLE = Titel: \u00c4h") > -1); - assertTrue(text.indexOf("COMPANY = Schreiner") > -1); - assertTrue(text.indexOf("SCALE = false") > -1); - } finally { - ext.close(); - } - } - - public void testCustomProperties() throws Exception { - POIFSFileSystem fs = new POIFSFileSystem( - _samples.openResourceAsStream("TestMickey.doc") - ); - HPSFPropertiesExtractor ext = new HPSFPropertiesExtractor(fs); - try { - // Custom properties are part of the document info stream - String dinfText = ext.getDocumentSummaryInformationText(); - assertTrue(dinfText.indexOf("Client = sample client") > -1); - assertTrue(dinfText.indexOf("Division = sample division") > -1); - - String text = ext.getText(); - assertTrue(text.indexOf("Client = sample client") > -1); - assertTrue(text.indexOf("Division = sample division") > -1); - } finally { - ext.close(); - } - } - - public void testConstructors() throws IOException { - POIFSFileSystem fs; - HSSFWorkbook wb; - try { - fs = new POIFSFileSystem(_samples.openResourceAsStream("TestUnicode.xls")); - wb = new HSSFWorkbook(fs); - } catch (IOException e) { - throw new RuntimeException(e); - } - ExcelExtractor excelExt = new ExcelExtractor(wb); - - final String fsText; - HPSFPropertiesExtractor fsExt = new HPSFPropertiesExtractor(fs); - fsExt.setFilesystem(null); // Don't close re-used test resources! - try { - fsText = fsExt.getText(); - } finally { - fsExt.close(); - } - - final String hwText; - HPSFPropertiesExtractor hwExt = new HPSFPropertiesExtractor(wb); - hwExt.setFilesystem(null); // Don't close re-used test resources! - try { - hwText = hwExt.getText(); - } finally { - hwExt.close(); - } - - final String eeText; - HPSFPropertiesExtractor eeExt = new HPSFPropertiesExtractor(excelExt); - eeExt.setFilesystem(null); // Don't close re-used test resources! - try { - eeText = eeExt.getText(); - } finally { - eeExt.close(); - } - - assertEquals(fsText, hwText); - assertEquals(fsText, eeText); - - assertTrue(fsText.indexOf("AUTHOR = marshall") > -1); - assertTrue(fsText.indexOf("TITLE = Titel: \u00c4h") > -1); - - // Finally tidy - wb.close(); - } - - public void test42726() throws IOException { - HPSFPropertiesExtractor ext = new HPSFPropertiesExtractor(HSSFTestDataSamples.openSampleWorkbook("42726.xls")); - try { - String txt = ext.getText(); - assertTrue(txt.indexOf("PID_AUTHOR") != -1); - assertTrue(txt.indexOf("PID_EDITTIME") != -1); - assertTrue(txt.indexOf("PID_REVNUMBER") != -1); - assertTrue(txt.indexOf("PID_THUMBNAIL") != -1); - } finally { - ext.close(); - } - } - - public void testThumbnail() throws Exception { - POIFSFileSystem fs = new POIFSFileSystem(_samples.openResourceAsStream("TestThumbnail.xls")); - HSSFWorkbook wb = new HSSFWorkbook(fs); - Thumbnail thumbnail = new Thumbnail(wb.getSummaryInformation().getThumbnail()); - assertEquals(-1, thumbnail.getClipboardFormatTag()); - assertEquals(3, thumbnail.getClipboardFormat()); - assertNotNull(thumbnail.getThumbnailAsWMF()); - wb.close(); - } - - public void test52258() throws Exception { - POIFSFileSystem fs = new POIFSFileSystem(_samples.openResourceAsStream("TestVisioWithCodepage.vsd")); - HPSFPropertiesExtractor ext = new HPSFPropertiesExtractor(fs); - try { - assertNotNull(ext.getDocSummaryInformation()); - assertNotNull(ext.getDocumentSummaryInformationText()); - assertNotNull(ext.getSummaryInformation()); - assertNotNull(ext.getSummaryInformationText()); - assertNotNull(ext.getText()); - } finally { - ext.close(); - } - } -} diff --git a/src/testcases/org/apache/poi/hssf/HSSFITestDataProvider.java b/src/testcases/org/apache/poi/hssf/HSSFITestDataProvider.java deleted file mode 100644 index 5d80a26d5..000000000 --- a/src/testcases/org/apache/poi/hssf/HSSFITestDataProvider.java +++ /dev/null @@ -1,92 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf; - -import java.io.InputStream; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; - -/** - * @author Yegor Kozlov - */ -public final class HSSFITestDataProvider implements ITestDataProvider { - public static final HSSFITestDataProvider instance = new HSSFITestDataProvider(); - - private HSSFITestDataProvider(){ - // enforce singleton - } - - @Override - public HSSFWorkbook openSampleWorkbook(String sampleFileName) { - return HSSFTestDataSamples.openSampleWorkbook(sampleFileName); - } - - public InputStream openWorkbookStream(String sampleFileName) { - return HSSFTestDataSamples.openSampleFileStream(sampleFileName); - } - - @Override - public HSSFWorkbook writeOutAndReadBack(Workbook original) { - if(!(original instanceof HSSFWorkbook)) { - throw new IllegalArgumentException("Expected an instance of HSSFWorkbook"); - } - return HSSFTestDataSamples.writeOutAndReadBack((HSSFWorkbook)original); - } - - @Override - public HSSFWorkbook createWorkbook(){ - return new HSSFWorkbook(); - } - - //************ SXSSF-specific methods ***************// - @Override - public HSSFWorkbook createWorkbook(int rowAccessWindowSize) { - return createWorkbook(); - } - - @Override - public void trackAllColumnsForAutosizing(Sheet sheet) {} - //************ End SXSSF-specific methods ***************// - - @Override - public FormulaEvaluator createFormulaEvaluator(Workbook wb) { - return new HSSFFormulaEvaluator((HSSFWorkbook) wb); - } - - @Override - public byte[] getTestDataFileContent(String fileName) { - return POIDataSamples.getSpreadSheetInstance().readFile(fileName); - } - - @Override - public SpreadsheetVersion getSpreadsheetVersion(){ - return SpreadsheetVersion.EXCEL97; - } - - @Override - public String getStandardFileNameExtension() { - return "xls"; - } -} diff --git a/src/testcases/org/apache/poi/hssf/HSSFTestDataSamples.java b/src/testcases/org/apache/poi/hssf/HSSFTestDataSamples.java deleted file mode 100644 index fb64e4e23..000000000 --- a/src/testcases/org/apache/poi/hssf/HSSFTestDataSamples.java +++ /dev/null @@ -1,70 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; - -/** - * Centralises logic for finding/opening sample files in the src/testcases/org/apache/poi/hssf/hssf/data folder. - * - * @author Josh Micich - */ -public final class HSSFTestDataSamples { - - private static final POIDataSamples _inst = POIDataSamples.getSpreadSheetInstance(); - - public static InputStream openSampleFileStream(String sampleFileName) { - return _inst.openResourceAsStream(sampleFileName); - } - public static File getSampleFile(String sampleFileName) { - return _inst.getFile(sampleFileName); - } - public static byte[] getTestDataFileContent(String fileName) { - return _inst.readFile(fileName); - } - - public static HSSFWorkbook openSampleWorkbook(String sampleFileName) { - try { - return new HSSFWorkbook(_inst.openResourceAsStream(sampleFileName)); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - /** - * Writes a spreadsheet to a ByteArrayOutputStream and reads it back - * from a ByteArrayInputStream.

    - * Useful for verifying that the serialisation round trip - */ - public static HSSFWorkbook writeOutAndReadBack(HSSFWorkbook original) { - try { - ByteArrayOutputStream baos = new ByteArrayOutputStream(4096); - original.write(baos); - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - return new HSSFWorkbook(bais); - } catch (IOException e) { - throw new RuntimeException(e); - } - } -} diff --git a/src/testcases/org/apache/poi/hssf/HSSFTests.java b/src/testcases/org/apache/poi/hssf/HSSFTests.java deleted file mode 100644 index 28602758e..000000000 --- a/src/testcases/org/apache/poi/hssf/HSSFTests.java +++ /dev/null @@ -1,48 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf; - -import org.apache.poi.hssf.eventmodel.TestEventRecordFactory; -import org.apache.poi.hssf.eventusermodel.AllEventUserModelTests; -import org.apache.poi.hssf.extractor.TestExcelExtractor; -import org.apache.poi.hssf.model.AllModelTests; -import org.apache.poi.hssf.record.AllRecordTests; -import org.apache.poi.hssf.usermodel.AllUserModelTests; -import org.apache.poi.hssf.util.AllHSSFUtilTests; -import org.apache.poi.ss.formula.AllSSFormulaTests; -import org.apache.poi.ss.util.AllSSUtilTests; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -/** - * Test Suite for all sub-packages of org.apache.poi.hssf
    - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - AllEventUserModelTests.class, - AllModelTests.class, - AllUserModelTests.class, - AllRecordTests.class, - AllHSSFUtilTests.class, - TestExcelExtractor.class, - TestEventRecordFactory.class, - AllSSFormulaTests.class, - AllSSUtilTests.class -}) -public final class HSSFTests { -} diff --git a/src/testcases/org/apache/poi/hssf/dev/BaseXLSIteratingTest.java b/src/testcases/org/apache/poi/hssf/dev/BaseXLSIteratingTest.java deleted file mode 100644 index e69c700de..000000000 --- a/src/testcases/org/apache/poi/hssf/dev/BaseXLSIteratingTest.java +++ /dev/null @@ -1,122 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hssf.dev; - -import static org.junit.Assert.assertNotNull; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FilenameFilter; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.util.NullOutputStream; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; - -/** - * Base class for integration-style tests which iterate over all test-files - * and execute the same action to find out if any change breaks these applications. - * - * This test uses {@link Parameterized} to run the test for each file separatedely. - */ -@RunWith(Parameterized.class) -public abstract class BaseXLSIteratingTest { - protected static final OutputStream NULL_OUTPUT_STREAM = new NullOutputStream(); - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - protected static final Map> EXCLUDED = - new HashMap>(); - - @Parameters(name="{index}: {0}") - public static Iterable files() { - String dataDirName = System.getProperty(POIDataSamples.TEST_PROPERTY); - if(dataDirName == null) { - dataDirName = "test-data"; - } - - List files = new ArrayList(); - findFile(files, dataDirName + "/spreadsheet"); - findFile(files, dataDirName + "/hpsf"); - - return files; - } - - private static void findFile(List list, String dir) { - String[] files = new File(dir).list(new FilenameFilter() { - @Override - public boolean accept(File arg0, String arg1) { - return arg1.toLowerCase(Locale.ROOT).endsWith(".xls"); - } - }); - - assertNotNull("Did not find any xls files in directory " + dir, files); - - for(String file : files) { - list.add(new Object[] { new File(dir, file) }); - } - } - - @Parameter - public File file; - - @Test - public void testMain() throws Exception { - // we had intermittent problems when this was set differently somehow, let's try to set it here so it always is set correctly for these tests - Biff8EncryptionKey.setCurrentUserPassword(null); - - String fileName = file.getName(); - if (EXCLUDED.containsKey(fileName)) { - thrown.expect(EXCLUDED.get(fileName)); - } - - try { - runOneFile(file); - } catch (Exception e) { - // try to read it in HSSFWorkbook to quickly fail if we cannot read the file there at all and thus probably should use EXCLUDED instead - FileInputStream stream = new FileInputStream(file); - HSSFWorkbook wb = null; - try { - wb = new HSSFWorkbook(stream); - assertNotNull(wb); - } finally { - if (wb != null) { - wb.close(); - } - stream.close(); - } - - throw e; - } - } - - abstract void runOneFile(File pFile) throws Exception; -} diff --git a/src/testcases/org/apache/poi/hssf/dev/TestBiffDrawingToXml.java b/src/testcases/org/apache/poi/hssf/dev/TestBiffDrawingToXml.java deleted file mode 100644 index ffcb676d5..000000000 --- a/src/testcases/org/apache/poi/hssf/dev/TestBiffDrawingToXml.java +++ /dev/null @@ -1,66 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hssf.dev; - -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStream; -import java.io.PrintStream; - -import org.apache.poi.EncryptedDocumentException; -import org.apache.poi.hssf.OldExcelFormatException; -import org.apache.poi.hssf.record.RecordInputStream; -import org.junit.BeforeClass; - -public class TestBiffDrawingToXml extends BaseXLSIteratingTest { - @BeforeClass - public static void setup() { - EXCLUDED.clear(); - EXCLUDED.put("35897-type4.xls", EncryptedDocumentException.class); // unsupported crypto api header - EXCLUDED.put("51832.xls", EncryptedDocumentException.class); - EXCLUDED.put("xor-encryption-abc.xls", EncryptedDocumentException.class); - EXCLUDED.put("password.xls", EncryptedDocumentException.class); - EXCLUDED.put("46904.xls", OldExcelFormatException.class); - EXCLUDED.put("59074.xls", OldExcelFormatException.class); - EXCLUDED.put("testEXCEL_2.xls", OldExcelFormatException.class); // Biff 2 / Excel 2, pre-OLE2 - EXCLUDED.put("testEXCEL_3.xls", OldExcelFormatException.class); // Biff 3 / Excel 3, pre-OLE2 - EXCLUDED.put("testEXCEL_4.xls", OldExcelFormatException.class); // Biff 4 / Excel 4, pre-OLE2 - EXCLUDED.put("testEXCEL_5.xls", OldExcelFormatException.class); // Biff 5 / Excel 5 - EXCLUDED.put("60284.xls", OldExcelFormatException.class); // Biff 5 / Excel 5 - EXCLUDED.put("testEXCEL_95.xls", OldExcelFormatException.class); // Biff 5 / Excel 95 - EXCLUDED.put("60284.xls", OldExcelFormatException.class); // Biff 5 / Excel 95 - EXCLUDED.put("43493.xls", RecordInputStream.LeftoverDataException.class); // HSSFWorkbook cannot open it as well - EXCLUDED.put("44958_1.xls", RecordInputStream.LeftoverDataException.class); - } - - @Override - void runOneFile(File pFile) throws Exception { - PrintStream save = System.out; - try { - //System.setOut(new PrintStream(TestBiffViewer.NULL_OUTPUT_STREAM)); - // use a NullOutputStream to not write the bytes anywhere for best runtime - InputStream wb = new FileInputStream(pFile); - try { - BiffDrawingToXml.writeToFile(NULL_OUTPUT_STREAM, wb, false, new String[] {}); - } finally { - wb.close(); - } - } finally { - System.setOut(save); - } - } -} diff --git a/src/testcases/org/apache/poi/hssf/dev/TestBiffViewer.java b/src/testcases/org/apache/poi/hssf/dev/TestBiffViewer.java deleted file mode 100644 index 5a36de494..000000000 --- a/src/testcases/org/apache/poi/hssf/dev/TestBiffViewer.java +++ /dev/null @@ -1,81 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hssf.dev; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; - -import org.apache.poi.EncryptedDocumentException; -import org.apache.poi.POIDataSamples; -import org.apache.poi.hssf.OldExcelFormatException; -import org.apache.poi.hssf.record.RecordInputStream; -import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; -import org.apache.poi.util.LocaleUtil; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; - -public class TestBiffViewer extends BaseXLSIteratingTest { - @BeforeClass - public static void setup() { - EXCLUDED.clear(); - EXCLUDED.put("35897-type4.xls", EncryptedDocumentException.class); // unsupported crypto api header - EXCLUDED.put("51832.xls", EncryptedDocumentException.class); - EXCLUDED.put("xor-encryption-abc.xls", EncryptedDocumentException.class); - EXCLUDED.put("password.xls", EncryptedDocumentException.class); - EXCLUDED.put("46904.xls", OldExcelFormatException.class); - EXCLUDED.put("59074.xls", OldExcelFormatException.class); - EXCLUDED.put("testEXCEL_2.xls", OldExcelFormatException.class); // Biff 2 / Excel 2, pre-OLE2 - EXCLUDED.put("testEXCEL_3.xls", OldExcelFormatException.class); // Biff 3 / Excel 3, pre-OLE2 - EXCLUDED.put("testEXCEL_4.xls", OldExcelFormatException.class); // Biff 4 / Excel 4, pre-OLE2 - EXCLUDED.put("testEXCEL_5.xls", OldExcelFormatException.class); // Biff 5 / Excel 5 - EXCLUDED.put("60284.xls", OldExcelFormatException.class); // Biff 5 / Excel 5 - EXCLUDED.put("testEXCEL_95.xls", OldExcelFormatException.class); // Biff 5 / Excel 95 - EXCLUDED.put("60284.xls", OldExcelFormatException.class); // Biff 5 / Excel 95 - EXCLUDED.put("43493.xls", RecordInputStream.LeftoverDataException.class); // HSSFWorkbook cannot open it as well - // EXCLUDED.put("44958_1.xls", RecordInputStream.LeftoverDataException.class); - EXCLUDED.put("50833.xls", IllegalArgumentException.class); // "Name is too long" when setting username - EXCLUDED.put("XRefCalc.xls", RuntimeException.class); // "Buffer overrun" - } - - @Override - void runOneFile(File fileIn) throws IOException { - NPOIFSFileSystem fs = new NPOIFSFileSystem(fileIn, true); - try { - InputStream is = BiffViewer.getPOIFSInputStream(fs); - try { - // use a NullOutputStream to not write the bytes anywhere for best runtime - PrintWriter dummy = new PrintWriter(new OutputStreamWriter(NULL_OUTPUT_STREAM, LocaleUtil.CHARSET_1252)); - BiffViewer.runBiffViewer(dummy, is, true, true, true, false); - } finally { - is.close(); - } - } finally { - fs.close(); - } - } - - @Test - @Ignore("only used for manual tests") - public void testOneFile() throws Exception { - POIDataSamples samples = POIDataSamples.getSpreadSheetInstance(); - runOneFile(samples.getFile("43493.xls")); - } -} diff --git a/src/testcases/org/apache/poi/hssf/dev/TestEFBiffViewer.java b/src/testcases/org/apache/poi/hssf/dev/TestEFBiffViewer.java deleted file mode 100644 index e07b9ff8e..000000000 --- a/src/testcases/org/apache/poi/hssf/dev/TestEFBiffViewer.java +++ /dev/null @@ -1,70 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hssf.dev; - -import java.io.File; -import java.io.IOException; -import java.io.PrintStream; - -import org.apache.poi.EncryptedDocumentException; -import org.apache.poi.hssf.OldExcelFormatException; -import org.apache.poi.hssf.record.RecordInputStream; -import org.apache.poi.util.LocaleUtil; -import org.junit.BeforeClass; - -public class TestEFBiffViewer extends BaseXLSIteratingTest { - @BeforeClass - public static void setup() { - EXCLUDED.clear(); - EXCLUDED.put("35897-type4.xls", EncryptedDocumentException.class); // unsupported crypto api header - EXCLUDED.put("51832.xls", EncryptedDocumentException.class); - EXCLUDED.put("xor-encryption-abc.xls", EncryptedDocumentException.class); - EXCLUDED.put("password.xls", EncryptedDocumentException.class); - EXCLUDED.put("46904.xls", OldExcelFormatException.class); - EXCLUDED.put("59074.xls", OldExcelFormatException.class); - EXCLUDED.put("testEXCEL_2.xls", OldExcelFormatException.class); // Biff 2 / Excel 2, pre-OLE2 - EXCLUDED.put("testEXCEL_3.xls", OldExcelFormatException.class); // Biff 3 / Excel 3, pre-OLE2 - EXCLUDED.put("testEXCEL_4.xls", OldExcelFormatException.class); // Biff 4 / Excel 4, pre-OLE2 - EXCLUDED.put("testEXCEL_5.xls", OldExcelFormatException.class); // Biff 5 / Excel 5 - EXCLUDED.put("60284.xls", OldExcelFormatException.class); // Biff 5 / Excel 5 - EXCLUDED.put("testEXCEL_95.xls", OldExcelFormatException.class); // Biff 5 / Excel 95 - EXCLUDED.put("60284.xls", OldExcelFormatException.class); // Biff 5 / Excel 95 - EXCLUDED.put("43493.xls", RecordInputStream.LeftoverDataException.class); // HSSFWorkbook cannot open it as well - EXCLUDED.put("44958_1.xls", RecordInputStream.LeftoverDataException.class); - EXCLUDED.put("XRefCalc.xls", RuntimeException.class); // "Buffer overrun" - } - - @Override - void runOneFile(File fileIn) throws IOException { - PrintStream save = System.out; - try { - // redirect standard out during the test to avoid spamming the console with output - System.setOut(new PrintStream(NULL_OUTPUT_STREAM,true,LocaleUtil.CHARSET_1252.name())); - - EFBiffViewer.main(new String[] { fileIn.getAbsolutePath() }); - } finally { - System.setOut(save); - } - } - - //@Test - public void testFile() throws IOException { - EFBiffViewer viewer = new EFBiffViewer(); - viewer.setFile(new File("test-data/spreadsheet/59074.xls").getAbsolutePath()); - viewer.run(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/dev/TestFormulaViewer.java b/src/testcases/org/apache/poi/hssf/dev/TestFormulaViewer.java deleted file mode 100644 index 3e575f22b..000000000 --- a/src/testcases/org/apache/poi/hssf/dev/TestFormulaViewer.java +++ /dev/null @@ -1,74 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hssf.dev; - -import static org.junit.Assume.assumeTrue; - -import java.io.File; -import java.io.PrintStream; - -import org.apache.poi.EncryptedDocumentException; -import org.apache.poi.hssf.OldExcelFormatException; -import org.apache.poi.hssf.record.RecordInputStream; -import org.apache.poi.util.LocaleUtil; -import org.junit.BeforeClass; - -public class TestFormulaViewer extends BaseXLSIteratingTest { - @BeforeClass - public static void setup() { - EXCLUDED.clear(); - EXCLUDED.put("35897-type4.xls", EncryptedDocumentException.class); // unsupported crypto api header - EXCLUDED.put("51832.xls", EncryptedDocumentException.class); - EXCLUDED.put("xor-encryption-abc.xls", EncryptedDocumentException.class); - EXCLUDED.put("password.xls", EncryptedDocumentException.class); - EXCLUDED.put("46904.xls", OldExcelFormatException.class); - EXCLUDED.put("59074.xls", OldExcelFormatException.class); - EXCLUDED.put("testEXCEL_2.xls", OldExcelFormatException.class); // Biff 2 / Excel 2, pre-OLE2 - EXCLUDED.put("testEXCEL_3.xls", OldExcelFormatException.class); // Biff 3 / Excel 3, pre-OLE2 - EXCLUDED.put("testEXCEL_4.xls", OldExcelFormatException.class); // Biff 4 / Excel 4, pre-OLE2 - EXCLUDED.put("testEXCEL_5.xls", OldExcelFormatException.class); // Biff 5 / Excel 5 - EXCLUDED.put("60284.xls", OldExcelFormatException.class); // Biff 5 / Excel 5 - EXCLUDED.put("testEXCEL_95.xls", OldExcelFormatException.class); // Biff 5 / Excel 95 - EXCLUDED.put("60284.xls", OldExcelFormatException.class); // Biff 5 / Excel 95 - EXCLUDED.put("43493.xls", RecordInputStream.LeftoverDataException.class); // HSSFWorkbook cannot open it as well - EXCLUDED.put("44958_1.xls", RecordInputStream.LeftoverDataException.class); - } - - @Override - void runOneFile(File fileIn) throws Exception { - PrintStream save = System.out; - try { - // redirect standard out during the test to avoid spamming the console with output - System.setOut(new PrintStream(NULL_OUTPUT_STREAM,true,LocaleUtil.CHARSET_1252.name())); - - FormulaViewer viewer = new FormulaViewer(); - viewer.setFile(fileIn.getAbsolutePath()); - viewer.setList(true); - viewer.run(); - } catch (RuntimeException re) { - String m = re.getMessage(); - if (m.startsWith("toFormulaString") || m.startsWith("3D references")) { - // TODO: fix those cases, but ignore them for now ... - assumeTrue(true); - } else { - throw re; - } - } finally { - System.setOut(save); - } - } -} diff --git a/src/testcases/org/apache/poi/hssf/dev/TestReSave.java b/src/testcases/org/apache/poi/hssf/dev/TestReSave.java deleted file mode 100644 index b1ae03aa9..000000000 --- a/src/testcases/org/apache/poi/hssf/dev/TestReSave.java +++ /dev/null @@ -1,96 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hssf.dev; - -import org.apache.poi.EncryptedDocumentException; -import org.apache.poi.POIDataSamples; -import org.apache.poi.hssf.OldExcelFormatException; -import org.apache.poi.hssf.record.RecordInputStream; -import org.apache.poi.util.LocaleUtil; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; - -import java.io.File; -import java.io.PrintStream; - -import static org.junit.Assert.assertTrue; - -public class TestReSave extends BaseXLSIteratingTest { - @BeforeClass - public static void setup() { - EXCLUDED.clear(); - EXCLUDED.put("35897-type4.xls", EncryptedDocumentException.class); // unsupported crypto api header - EXCLUDED.put("51832.xls", EncryptedDocumentException.class); - EXCLUDED.put("xor-encryption-abc.xls", EncryptedDocumentException.class); - EXCLUDED.put("password.xls", EncryptedDocumentException.class); - EXCLUDED.put("46904.xls", OldExcelFormatException.class); - EXCLUDED.put("59074.xls", OldExcelFormatException.class); - EXCLUDED.put("testEXCEL_2.xls", OldExcelFormatException.class); // Biff 2 / Excel 2, pre-OLE2 - EXCLUDED.put("testEXCEL_3.xls", OldExcelFormatException.class); // Biff 3 / Excel 3, pre-OLE2 - EXCLUDED.put("testEXCEL_4.xls", OldExcelFormatException.class); // Biff 4 / Excel 4, pre-OLE2 - EXCLUDED.put("testEXCEL_5.xls", OldExcelFormatException.class); // Biff 5 / Excel 5 - EXCLUDED.put("60284.xls", OldExcelFormatException.class); // Biff 5 / Excel 5 - EXCLUDED.put("testEXCEL_95.xls", OldExcelFormatException.class); // Biff 5 / Excel 95 - EXCLUDED.put("60284.xls", OldExcelFormatException.class); // Biff 5 / Excel 95 - EXCLUDED.put("43493.xls", RecordInputStream.LeftoverDataException.class); // HSSFWorkbook cannot open it as well - EXCLUDED.put("44958_1.xls", RecordInputStream.LeftoverDataException.class); - EXCLUDED.put("XRefCalc.xls", RuntimeException.class); // "Buffer overrun" - } - - @Override - void runOneFile(File fileIn) throws Exception { - // avoid running on files leftover from previous failed runs - if(fileIn.getName().endsWith("-saved.xls")) { - return; - } - - PrintStream save = System.out; - try { - // redirect standard out during the test to avoid spamming the console with output - System.setOut(new PrintStream(NULL_OUTPUT_STREAM,true,LocaleUtil.CHARSET_1252.name())); - - File reSavedFile = new File(fileIn.getParentFile(), fileIn.getName().replace(".xls", "-saved.xls")); - try { - ReSave.main(new String[] { fileIn.getAbsolutePath() }); - - // also try BiffViewer on the saved file - new TestBiffViewer().runOneFile(reSavedFile); - - // had one case where the re-saved could not be re-saved! - ReSave.main(new String[] { "-bos", reSavedFile.getAbsolutePath() }); - } finally { - // clean up the re-saved file - assertTrue(!reSavedFile.exists() || reSavedFile.delete()); - } - - } finally { - System.setOut(save); - } - } - - @Ignore("Only used for local testing") - @Test - public void testOneFile() throws Exception { - String dataDirName = System.getProperty(POIDataSamples.TEST_PROPERTY); - if(dataDirName == null) { - dataDirName = "test-data"; - } - - runOneFile(new File(dataDirName + "/spreadsheet", "49931.xls")); - } -} diff --git a/src/testcases/org/apache/poi/hssf/dev/TestRecordLister.java b/src/testcases/org/apache/poi/hssf/dev/TestRecordLister.java deleted file mode 100644 index a74846d46..000000000 --- a/src/testcases/org/apache/poi/hssf/dev/TestRecordLister.java +++ /dev/null @@ -1,64 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hssf.dev; - -import java.io.File; -import java.io.IOException; -import java.io.PrintStream; - -import org.apache.poi.hssf.OldExcelFormatException; -import org.apache.poi.util.LocaleUtil; -import org.junit.BeforeClass; - -public class TestRecordLister extends BaseXLSIteratingTest { - @BeforeClass - public static void setup() { - EXCLUDED.clear(); - EXCLUDED.put("46904.xls", OldExcelFormatException.class); - EXCLUDED.put("59074.xls", OldExcelFormatException.class); - EXCLUDED.put("testEXCEL_2.xls", OldExcelFormatException.class); // Biff 2 / Excel 2, pre-OLE2 - EXCLUDED.put("testEXCEL_3.xls", OldExcelFormatException.class); // Biff 3 / Excel 3, pre-OLE2 - EXCLUDED.put("testEXCEL_4.xls", OldExcelFormatException.class); // Biff 4 / Excel 4, pre-OLE2 - EXCLUDED.put("testEXCEL_5.xls", OldExcelFormatException.class); // Biff 5 / Excel 5 - EXCLUDED.put("60284.xls", OldExcelFormatException.class); // Biff 5 / Excel 5 - EXCLUDED.put("testEXCEL_95.xls", OldExcelFormatException.class); // Biff 5 / Excel 95 - EXCLUDED.put("60284.xls", OldExcelFormatException.class); // Biff 5 / Excel 95 - - } - - @Override - void runOneFile(File fileIn) throws IOException { - PrintStream save = System.out; - try { - // redirect standard out during the test to avoid spamming the console with output - System.setOut(new PrintStream(NULL_OUTPUT_STREAM,true,LocaleUtil.CHARSET_1252.name())); - - RecordLister viewer = new RecordLister(); - viewer.setFile(fileIn.getAbsolutePath()); - viewer.run(); - } finally { - System.setOut(save); - } - } - - //@Test - public void testFile() throws IOException { - RecordLister viewer = new RecordLister(); - viewer.setFile(new File("test-data/spreadsheet/testEXCEL_95.xls").getAbsolutePath()); - viewer.run(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/eventmodel/TestAbortableListener.java b/src/testcases/org/apache/poi/hssf/eventmodel/TestAbortableListener.java deleted file mode 100644 index a4618aed4..000000000 --- a/src/testcases/org/apache/poi/hssf/eventmodel/TestAbortableListener.java +++ /dev/null @@ -1,109 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.eventmodel; - -import java.io.ByteArrayInputStream; -import java.io.IOException; - -import junit.framework.TestCase; - -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.hssf.eventusermodel.AbortableHSSFListener; -import org.apache.poi.hssf.eventusermodel.HSSFEventFactory; -import org.apache.poi.hssf.eventusermodel.HSSFRequest; -import org.apache.poi.hssf.record.BOFRecord; -import org.apache.poi.hssf.record.EOFRecord; -import org.apache.poi.hssf.record.Record; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; - -/** - * Tests for {@link AbortableHSSFListener} - */ -public final class TestAbortableListener extends TestCase { - - private POIFSFileSystem openSample() { - ByteArrayInputStream is = new ByteArrayInputStream(HSSFITestDataProvider.instance - .getTestDataFileContent("SimpleWithColours.xls")); - try { - return new POIFSFileSystem(is); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - public void testAbortingBasics() throws Exception { - AbortableCountingListener l = new AbortableCountingListener(1000); - - HSSFRequest req = new HSSFRequest(); - req.addListenerForAllRecords(l); - - HSSFEventFactory f = new HSSFEventFactory(); - - assertEquals(0, l.countSeen); - assertEquals(null, l.lastRecordSeen); - - POIFSFileSystem fs = openSample(); - short res = f.abortableProcessWorkbookEvents(req, fs); - - assertEquals(0, res); - assertEquals(175, l.countSeen); - assertEquals(EOFRecord.sid, l.lastRecordSeen.getSid()); - } - - - public void testAbortStops() throws Exception { - AbortableCountingListener l = new AbortableCountingListener(1); - - HSSFRequest req = new HSSFRequest(); - req.addListenerForAllRecords(l); - - HSSFEventFactory f = new HSSFEventFactory(); - - assertEquals(0, l.countSeen); - assertEquals(null, l.lastRecordSeen); - - POIFSFileSystem fs = openSample(); - short res = f.abortableProcessWorkbookEvents(req, fs); - - assertEquals(1234, res); - assertEquals(1, l.countSeen); - assertEquals(BOFRecord.sid, l.lastRecordSeen.getSid()); - } - - private static final class AbortableCountingListener extends AbortableHSSFListener { - private final int abortAfterIndex; - public int countSeen; - public Record lastRecordSeen; - - public AbortableCountingListener(int abortAfter) { - abortAfterIndex = abortAfter; - countSeen = 0; - lastRecordSeen = null; - } - @Override - public short abortableProcessRecord(Record record) { - countSeen++; - lastRecordSeen = record; - - if(countSeen == abortAfterIndex) { - return 1234; - } - return 0; - } - } -} diff --git a/src/testcases/org/apache/poi/hssf/eventmodel/TestEventRecordFactory.java b/src/testcases/org/apache/poi/hssf/eventmodel/TestEventRecordFactory.java deleted file mode 100644 index b3bf66880..000000000 --- a/src/testcases/org/apache/poi/hssf/eventmodel/TestEventRecordFactory.java +++ /dev/null @@ -1,184 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.eventmodel; - -import java.io.ByteArrayInputStream; - -import junit.framework.TestCase; - -import org.apache.poi.hssf.record.BOFRecord; -import org.apache.poi.hssf.record.ContinueRecord; -import org.apache.poi.hssf.record.EOFRecord; -import org.apache.poi.hssf.record.Record; -import org.apache.poi.hssf.record.RecordFactory; -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.apache.poi.hssf.record.UnknownRecord; -import org.apache.poi.util.NotImplemented; - -/** - * enclosing_type describe the purpose here - * - * @author Andrew C. Oliver acoliver@apache.org - * @author Csaba Nagy (ncsaba at yahoo dot com) - */ -public final class TestEventRecordFactory extends TestCase { - - /** - * tests that the records can be processed and properly return - * values. - */ - public void testProcessRecords() - { - final boolean[] wascalled = { false, }; // hack to pass boolean by ref into inner class - - ERFListener listener = new ERFListener() { - @Override - public boolean processRecord(Record rec) { - wascalled[0] = true; - assertTrue("must be BOFRecord got SID="+rec.getSid(), - (rec.getSid() == BOFRecord.sid)); - return true; - } - }; - EventRecordFactory factory = new EventRecordFactory(listener, new short[] {BOFRecord.sid}); - - BOFRecord bof = new BOFRecord(); - bof.setBuild((short)0); - bof.setBuildYear((short)1999); - bof.setRequiredVersion(123); - bof.setType(BOFRecord.TYPE_WORKBOOK); - bof.setVersion((short)0x06); - bof.setHistoryBitMask(BOFRecord.HISTORY_MASK); - - EOFRecord eof = EOFRecord.instance; - byte[] bytes = new byte[bof.getRecordSize() + eof.getRecordSize()]; - int offset = 0; - offset = bof.serialize(offset,bytes); - offset = eof.serialize(offset,bytes); - - factory.processRecords(new ByteArrayInputStream(bytes)); - assertTrue("The record listener must be called", wascalled[0]); - } - - - /** - * tests that the create record function returns a properly - * constructed record in the simple case. - */ - public void testCreateRecord() { - BOFRecord bof = new BOFRecord(); - bof.setBuild((short)0); - bof.setBuildYear((short)1999); - bof.setRequiredVersion(123); - bof.setType(BOFRecord.TYPE_WORKBOOK); - bof.setVersion((short)0x06); - bof.setHistoryBitMask(BOFRecord.HISTORY_MASK); - - byte[] bytes = bof.serialize(); - - Record[] records = RecordFactory.createRecord(TestcaseRecordInputStream.create(bytes)); - - assertTrue("record.length must be 1, was ="+records.length,records.length == 1); - assertTrue("record is the same", compareRec(bof,records[0])); - - } - - /** - * Compare the serialized bytes of two records are equal - * @param first the first record to compare - * @param second the second record to compare - * @return boolean whether or not the record where equal - */ - private static boolean compareRec(Record first, Record second) { - byte[] rec1 = first.serialize(); - byte[] rec2 = second.serialize(); - - if (rec1.length != rec2.length) { - return false; - } - for (int k=0; k - * OBJECTIVE: Test that the RecordFactory given an InputStream - * constructs the expected records.

    - * SUCCESS: Record factory creates the expected records.

    - * FAILURE: The wrong records are created or contain the wrong values

    - * - */ - public void testContinuedUnknownRecord() { - final byte[] data = { - 0, -1, 0, 0, // an unknown record with 0 length - 0x3C , 0, 3, 0, 1, 2, 3, // a continuation record with 3 bytes of data - 0x3C , 0, 1, 0, 4 // one more continuation record with 1 byte of data - }; - - final int[] recCnt = { 0 }; - final int[] offset = { 0 }; - ERFListener listener = new ERFListener() { - private final String[] expectedRecordTypes = { - UnknownRecord.class.getName(), - ContinueRecord.class.getName(), - ContinueRecord.class.getName() - }; - @Override - public boolean processRecord(Record rec) - { - // System.out.println(rec.toString()); - assertEquals( - "Record type", - expectedRecordTypes[recCnt[0]], - rec.getClass().getName() - ); - compareData(rec, "Record " + recCnt[0] + ": "); - recCnt[0]++; - return true; - } - private void compareData(Record record, String message) { - byte[] recData = record.serialize(); - for (int i = 0; i < recData.length; i++) { - assertEquals(message + " data byte " + i, data[offset[0]++], recData[i]); - } - } - }; - EventRecordFactory factory = new EventRecordFactory(listener, new short[] {-256, 0x3C}); - - factory.processRecords(new ByteArrayInputStream(data)); - assertEquals("nr. of processed records", 3, recCnt[0]); - assertEquals("nr. of processed bytes", data.length, offset[0]); - } -} diff --git a/src/testcases/org/apache/poi/hssf/eventusermodel/AllEventUserModelTests.java b/src/testcases/org/apache/poi/hssf/eventusermodel/AllEventUserModelTests.java deleted file mode 100644 index a5d907375..000000000 --- a/src/testcases/org/apache/poi/hssf/eventusermodel/AllEventUserModelTests.java +++ /dev/null @@ -1,34 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.eventusermodel; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -/** - * Collects all tests for org.apache.poi.hssf.eventusermodel. - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestEventWorkbookBuilder.class, - TestFormatTrackingHSSFListener.class, - TestHSSFEventFactory.class, - TestMissingRecordAwareHSSFListener.class -}) -public class AllEventUserModelTests { -} diff --git a/src/testcases/org/apache/poi/hssf/eventusermodel/TestEventWorkbookBuilder.java b/src/testcases/org/apache/poi/hssf/eventusermodel/TestEventWorkbookBuilder.java deleted file mode 100644 index 609640c6d..000000000 --- a/src/testcases/org/apache/poi/hssf/eventusermodel/TestEventWorkbookBuilder.java +++ /dev/null @@ -1,169 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.eventusermodel; - -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; - -import junit.framework.TestCase; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.eventusermodel.EventWorkbookBuilder.SheetRecordCollectingListener; -import org.apache.poi.hssf.model.HSSFFormulaParser; -import org.apache.poi.hssf.model.InternalWorkbook; -import org.apache.poi.hssf.record.FormulaRecord; -import org.apache.poi.hssf.record.Record; -import org.apache.poi.hssf.usermodel.HSSFEvaluationWorkbook; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.apache.poi.ss.formula.ptg.Ref3DPtg; -/** - * Tests for {@link EventWorkbookBuilder} - */ -public final class TestEventWorkbookBuilder extends TestCase { - private MockHSSFListener mockListen; - private SheetRecordCollectingListener listener; - - @Override - public void setUp() { - HSSFRequest req = new HSSFRequest(); - mockListen = new MockHSSFListener(); - listener = new SheetRecordCollectingListener(mockListen); - req.addListenerForAllRecords(listener); - - HSSFEventFactory factory = new HSSFEventFactory(); - try { - InputStream is = HSSFTestDataSamples.openSampleFileStream("3dFormulas.xls"); - POIFSFileSystem fs = new POIFSFileSystem(is); - factory.processWorkbookEvents(req, fs); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - public void testBasics() { - assertNotNull(listener.getSSTRecord()); - assertNotNull(listener.getBoundSheetRecords()); - assertNotNull(listener.getExternSheetRecords()); - } - - public void testGetStubWorkbooks() { - assertNotNull(listener.getStubWorkbook()); - assertNotNull(listener.getStubHSSFWorkbook()); - } - - public void testContents() { - assertEquals(2, listener.getSSTRecord().getNumStrings()); - assertEquals(3, listener.getBoundSheetRecords().length); - assertEquals(1, listener.getExternSheetRecords().length); - - assertEquals(3, listener.getStubWorkbook().getNumSheets()); - - InternalWorkbook ref = listener.getStubWorkbook(); - assertEquals("Sh3", ref.findSheetFirstNameFromExternSheet(0)); - assertEquals("Sheet1", ref.findSheetFirstNameFromExternSheet(1)); - assertEquals("S2", ref.findSheetFirstNameFromExternSheet(2)); - } - - public void testFormulas() { - - FormulaRecord[] fRecs = mockListen.getFormulaRecords(); - - // Check our formula records - assertEquals(6, fRecs.length); - - InternalWorkbook stubWB = listener.getStubWorkbook(); - assertNotNull(stubWB); - HSSFWorkbook stubHSSF = listener.getStubHSSFWorkbook(); - assertNotNull(stubHSSF); - - // Check these stubs have the right stuff on them - assertEquals("Sheet1", stubWB.getSheetName(0)); - assertEquals("Sheet1", stubHSSF.getSheetName(0)); - assertEquals("S2", stubWB.getSheetName(1)); - assertEquals("S2", stubHSSF.getSheetName(1)); - assertEquals("Sh3", stubWB.getSheetName(2)); - assertEquals("Sh3", stubHSSF.getSheetName(2)); - - // Check we can get the formula without breaking - for (FormulaRecord fRec : fRecs) { - HSSFFormulaParser.toFormulaString(stubHSSF, fRec.getParsedExpression()); - } - - // Peer into just one formula, and check that - // all the ptgs give back the right things - Ptg[] ptgs = fRecs[0].getParsedExpression(); - assertEquals(1, ptgs.length); - assertTrue(ptgs[0] instanceof Ref3DPtg); - - Ref3DPtg ptg = (Ref3DPtg)ptgs[0]; - HSSFEvaluationWorkbook book = HSSFEvaluationWorkbook.create(stubHSSF); - assertEquals("Sheet1!A1", ptg.toFormulaString(book)); - - - // Now check we get the right formula back for - // a few sample ones - FormulaRecord fr; - - // Sheet 1 A2 is on same sheet - fr = fRecs[0]; - assertEquals(1, fr.getRow()); - assertEquals(0, fr.getColumn()); - assertEquals("Sheet1!A1", HSSFFormulaParser.toFormulaString(stubHSSF, fr.getParsedExpression())); - - // Sheet 1 A5 is to another sheet - fr = fRecs[3]; - assertEquals(4, fr.getRow()); - assertEquals(0, fr.getColumn()); - assertEquals("'S2'!A1", HSSFFormulaParser.toFormulaString(stubHSSF, fr.getParsedExpression())); - - // Sheet 1 A7 is to another sheet, range - fr = fRecs[5]; - assertEquals(6, fr.getRow()); - assertEquals(0, fr.getColumn()); - assertEquals("SUM(Sh3!A1:A4)", HSSFFormulaParser.toFormulaString(stubHSSF, fr.getParsedExpression())); - - - // Now, load via Usermodel and re-check - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("3dFormulas.xls"); - assertEquals("Sheet1!A1", wb.getSheetAt(0).getRow(1).getCell(0).getCellFormula()); - assertEquals("SUM(Sh3!A1:A4)", wb.getSheetAt(0).getRow(6).getCell(0).getCellFormula()); - } - - private static final class MockHSSFListener implements HSSFListener { - public MockHSSFListener() {} - private final List _records = new ArrayList(); - private final List _frecs = new ArrayList(); - - @Override - public void processRecord(Record record) { - _records.add(record); - if(record instanceof FormulaRecord) { - _frecs.add(record); - } - } - public FormulaRecord[] getFormulaRecords() { - FormulaRecord[] result = new FormulaRecord[_frecs.size()]; - _frecs.toArray(result); - return result; - } - } -} diff --git a/src/testcases/org/apache/poi/hssf/eventusermodel/TestFormatTrackingHSSFListener.java b/src/testcases/org/apache/poi/hssf/eventusermodel/TestFormatTrackingHSSFListener.java deleted file mode 100644 index ec1e9d0c2..000000000 --- a/src/testcases/org/apache/poi/hssf/eventusermodel/TestFormatTrackingHSSFListener.java +++ /dev/null @@ -1,116 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.eventusermodel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.record.CellValueRecordInterface; -import org.apache.poi.hssf.record.FormulaRecord; -import org.apache.poi.hssf.record.NumberRecord; -import org.apache.poi.hssf.record.Record; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.junit.Test; -/** - * Tests for FormatTrackingHSSFListener - */ -public final class TestFormatTrackingHSSFListener { - private FormatTrackingHSSFListener listener; - private MockHSSFListener mockListen; - - private void processFile(String filename) throws Exception { - HSSFRequest req = new HSSFRequest(); - mockListen = new MockHSSFListener(); - listener = new FormatTrackingHSSFListener(mockListen); - req.addListenerForAllRecords(listener); - - File file = HSSFTestDataSamples.getSampleFile(filename); - HSSFEventFactory factory = new HSSFEventFactory(); - POIFSFileSystem fs = new POIFSFileSystem(file); - factory.processWorkbookEvents(req, fs); - fs.close(); - } - - @Test - public void testFormats() throws Exception { - processFile("MissingBits.xls"); - - assertEquals("_(\"$\"* #,##0_);_(\"$\"* (#,##0);_(\"$\"* \"-\"_);_(@_)", listener.getFormatString(41)); - assertEquals("_(* #,##0_);_(* (#,##0);_(* \"-\"_);_(@_)", listener.getFormatString(42)); - assertEquals("_(* #,##0.00_);_(* (#,##0.00);_(* \"-\"??_);_(@_)", listener.getFormatString(43)); - assertEquals("_(\"$\"* #,##0.00_);_(\"$\"* (#,##0.00);_(\"$\"* \"-\"??_);_(@_)", listener.getFormatString(44)); - } - - /** - * Ensure that all number and formula records can be - * turned into strings without problems. - * For now, we're just looking to get text back, no - * exceptions thrown, but in future we might also - * want to check the exact strings! - */ - @Test - public void testTurnToString() throws Exception { - String[] files = new String[] { - "45365.xls", "45365-2.xls", "MissingBits.xls" - }; - for (String file : files) { - processFile(file); - - // Check we found our formats - assertTrue(listener.getNumberOfCustomFormats() > 5); - assertTrue(listener.getNumberOfExtendedFormats() > 5); - - // Now check we can turn all the numeric - // cells into strings without error - for(Record r : mockListen._records) { - CellValueRecordInterface cvr = null; - - if(r instanceof NumberRecord) { - cvr = (CellValueRecordInterface)r; - } - if(r instanceof FormulaRecord) { - cvr = (CellValueRecordInterface)r; - } - - if(cvr != null) { - // Should always give us a string - String s = listener.formatNumberDateCell(cvr); - assertNotNull(s); - assertTrue(s.length() > 0); - } - } - - // TODO - test some specific format strings - } - } - - private static final class MockHSSFListener implements HSSFListener { - public MockHSSFListener() {} - private final List _records = new ArrayList(); - - @Override - public void processRecord(Record record) { - _records.add(record); - } - } -} \ No newline at end of file diff --git a/src/testcases/org/apache/poi/hssf/eventusermodel/TestHSSFEventFactory.java b/src/testcases/org/apache/poi/hssf/eventusermodel/TestHSSFEventFactory.java deleted file mode 100644 index 040b83cfb..000000000 --- a/src/testcases/org/apache/poi/hssf/eventusermodel/TestHSSFEventFactory.java +++ /dev/null @@ -1,211 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.eventusermodel; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; - -import junit.framework.TestCase; - -import org.apache.poi.EncryptedDocumentException; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.record.BoundSheetRecord; -import org.apache.poi.hssf.record.ContinueRecord; -import org.apache.poi.hssf.record.DVALRecord; -import org.apache.poi.hssf.record.DVRecord; -import org.apache.poi.hssf.record.EOFRecord; -import org.apache.poi.hssf.record.FeatHdrRecord; -import org.apache.poi.hssf.record.NumberRecord; -import org.apache.poi.hssf.record.Record; -import org.apache.poi.hssf.record.SelectionRecord; -import org.apache.poi.hssf.record.WindowTwoRecord; -import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.junit.After; - -/** - * Testing for {@link HSSFEventFactory} - */ -public final class TestHSSFEventFactory extends TestCase { - private static final InputStream openSample(String sampleFileName) { - return HSSFTestDataSamples.openSampleFileStream(sampleFileName); - } - - // to not affect other tests running in the same JVM - @After - public void resetPassword() { - Biff8EncryptionKey.setCurrentUserPassword(null); - } - - public void testWithMissingRecords() throws Exception { - - HSSFRequest req = new HSSFRequest(); - MockHSSFListener mockListen = new MockHSSFListener(); - req.addListenerForAllRecords(mockListen); - - POIFSFileSystem fs = new POIFSFileSystem(openSample("SimpleWithSkip.xls")); - HSSFEventFactory factory = new HSSFEventFactory(); - factory.processWorkbookEvents(req, fs); - - Record[] recs = mockListen.getRecords(); - // Check we got the records - assertTrue( recs.length > 100 ); - - // Check that the last few records are as we expect - // (Makes sure we don't accidently skip the end ones) - int numRec = recs.length; - assertEquals(WindowTwoRecord.class, recs[numRec-3].getClass()); - assertEquals(SelectionRecord.class, recs[numRec-2].getClass()); - assertEquals(EOFRecord.class, recs[numRec-1].getClass()); - } - - public void testWithCrazyContinueRecords() throws Exception { - // Some files have crazy ordering of their continue records - // Check that we don't break on them (bug #42844) - - HSSFRequest req = new HSSFRequest(); - MockHSSFListener mockListen = new MockHSSFListener(); - req.addListenerForAllRecords(mockListen); - - POIFSFileSystem fs = new POIFSFileSystem(openSample("ContinueRecordProblem.xls")); - HSSFEventFactory factory = new HSSFEventFactory(); - factory.processWorkbookEvents(req, fs); - - Record[] recs = mockListen.getRecords(); - // Check we got the records - assertTrue( recs.length > 100 ); - - // And none of them are continue ones - for (Record rec : recs) { - assertFalse( rec instanceof ContinueRecord ); - } - - // Check that the last few records are as we expect - // (Makes sure we don't accidently skip the end ones) - int numRec = recs.length; - assertEquals(DVALRecord.class, recs[numRec-4].getClass()); - assertEquals(DVRecord.class, recs[numRec-3].getClass()); - assertEquals(FeatHdrRecord.class, recs[numRec-2].getClass()); - assertEquals(EOFRecord.class, recs[numRec-1].getClass()); - } - - /** - * Unknown records can be continued. - * Check that HSSFEventFactory doesn't break on them. - * (the test file was provided in a reopen of bug #42844) - */ - public void testUnknownContinueRecords() throws Exception { - - HSSFRequest req = new HSSFRequest(); - MockHSSFListener mockListen = new MockHSSFListener(); - req.addListenerForAllRecords(mockListen); - - POIFSFileSystem fs = new POIFSFileSystem(openSample("42844.xls")); - HSSFEventFactory factory = new HSSFEventFactory(); - factory.processWorkbookEvents(req, fs); - } - - private static class MockHSSFListener implements HSSFListener { - private final List records = new ArrayList(); - - public MockHSSFListener() {} - public Record[] getRecords() { - Record[] result = new Record[records.size()]; - records.toArray(result); - return result; - } - - @Override - public void processRecord(Record record) { - records.add(record); - } - } - - public void testWithDifferentWorkbookName() throws Exception { - HSSFRequest req = new HSSFRequest(); - MockHSSFListener mockListen = new MockHSSFListener(); - req.addListenerForAllRecords(mockListen); - - POIFSFileSystem fs = new POIFSFileSystem(openSample("BOOK_in_capitals.xls")); - HSSFEventFactory factory = new HSSFEventFactory(); - factory.processWorkbookEvents(req, fs); - - fs = new POIFSFileSystem(openSample("WORKBOOK_in_capitals.xls")); - factory = new HSSFEventFactory(); - factory.processWorkbookEvents(req, fs); - } - - public void testWithPasswordProtectedWorkbooks() throws Exception { - HSSFRequest req = new HSSFRequest(); - MockHSSFListener mockListen = new MockHSSFListener(); - req.addListenerForAllRecords(mockListen); - - // Without a password, can't be read - Biff8EncryptionKey.setCurrentUserPassword(null); - POIFSFileSystem fs = new POIFSFileSystem(openSample("xor-encryption-abc.xls")); - - HSSFEventFactory factory = new HSSFEventFactory(); - try { - factory.processWorkbookEvents(req, fs); - fail("Shouldn't be able to process protected workbook without the password"); - } catch (EncryptedDocumentException e) {} - - - // With the password, is properly processed - Biff8EncryptionKey.setCurrentUserPassword("abc"); - - req = new HSSFRequest(); - mockListen = new MockHSSFListener(); - req.addListenerForAllRecords(mockListen); - factory.processWorkbookEvents(req, fs); - - // Check we got the sheet and the contents - Record[] recs = mockListen.getRecords(); - assertTrue( recs.length > 50 ); - - // Has one sheet, with values 1,2,3 in column A rows 1-3 - boolean hasSheet=false, hasA1=false, hasA2=false, hasA3=false; - for (Record r : recs) { - if (r instanceof BoundSheetRecord) { - BoundSheetRecord bsr = (BoundSheetRecord)r; - assertEquals("Sheet1", bsr.getSheetname()); - hasSheet = true; - } - if (r instanceof NumberRecord) { - NumberRecord nr = (NumberRecord)r; - if (nr.getColumn() == 0 && nr.getRow() == 0) { - assertEquals(1, (int)nr.getValue()); - hasA1 = true; - } - if (nr.getColumn() == 0 && nr.getRow() == 1) { - assertEquals(2, (int)nr.getValue()); - hasA2 = true; - } - if (nr.getColumn() == 0 && nr.getRow() == 2) { - assertEquals(3, (int)nr.getValue()); - hasA3 = true; - } - } - } - - assertTrue("Sheet record not found", hasSheet); - assertTrue("Numeric record for A1 not found", hasA1); - assertTrue("Numeric record for A2 not found", hasA2); - assertTrue("Numeric record for A3 not found", hasA3); - } -} diff --git a/src/testcases/org/apache/poi/hssf/eventusermodel/TestMissingRecordAwareHSSFListener.java b/src/testcases/org/apache/poi/hssf/eventusermodel/TestMissingRecordAwareHSSFListener.java deleted file mode 100644 index 0867720f7..000000000 --- a/src/testcases/org/apache/poi/hssf/eventusermodel/TestMissingRecordAwareHSSFListener.java +++ /dev/null @@ -1,895 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.eventusermodel; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.eventusermodel.dummyrecord.LastCellOfRowDummyRecord; -import org.apache.poi.hssf.eventusermodel.dummyrecord.MissingCellDummyRecord; -import org.apache.poi.hssf.eventusermodel.dummyrecord.MissingRowDummyRecord; -import org.apache.poi.hssf.record.BOFRecord; -import org.apache.poi.hssf.record.BlankRecord; -import org.apache.poi.hssf.record.CellValueRecordInterface; -import org.apache.poi.hssf.record.DimensionsRecord; -import org.apache.poi.hssf.record.FormulaRecord; -import org.apache.poi.hssf.record.LabelSSTRecord; -import org.apache.poi.hssf.record.MulBlankRecord; -import org.apache.poi.hssf.record.NumberRecord; -import org.apache.poi.hssf.record.Record; -import org.apache.poi.hssf.record.RowRecord; -import org.apache.poi.hssf.record.SharedFormulaRecord; -import org.apache.poi.hssf.record.StringRecord; -import org.apache.poi.hssf.record.WindowTwoRecord; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -/** - * Tests for MissingRecordAwareHSSFListener - */ -public final class TestMissingRecordAwareHSSFListener extends TestCase { - - private Record[] r; - - private void readRecords(String sampleFileName) { - HSSFRequest req = new HSSFRequest(); - MockHSSFListener mockListen = new MockHSSFListener(); - MissingRecordAwareHSSFListener listener = new MissingRecordAwareHSSFListener(mockListen); - req.addListenerForAllRecords(listener); - - HSSFEventFactory factory = new HSSFEventFactory(); - try { - InputStream is = HSSFTestDataSamples.openSampleFileStream(sampleFileName); - POIFSFileSystem fs = new POIFSFileSystem(is); - factory.processWorkbookEvents(req, fs); - } catch (IOException e) { - throw new RuntimeException(e); - } - - r = mockListen.getRecords(); - assertTrue(r.length > 100); - } - public void openNormal() { - readRecords("MissingBits.xls"); - } - - public void testMissingRowRecords() { - openNormal(); - - // We have rows 0, 1, 2, 20 and 21 - int row0 = -1; - for(int i=0; i -1); - - // Following row 0, we should have 1, 2, then dummy, then 20+21+22 - assertTrue(r[row0] instanceof RowRecord); - assertTrue(r[row0+1] instanceof RowRecord); - assertTrue(r[row0+2] instanceof RowRecord); - assertTrue(r[row0+3] instanceof MissingRowDummyRecord); - assertTrue(r[row0+4] instanceof MissingRowDummyRecord); - assertTrue(r[row0+5] instanceof MissingRowDummyRecord); - assertTrue(r[row0+6] instanceof MissingRowDummyRecord); - // ... - assertTrue(r[row0+18] instanceof MissingRowDummyRecord); - assertTrue(r[row0+19] instanceof MissingRowDummyRecord); - assertTrue(r[row0+20] instanceof RowRecord); - assertTrue(r[row0+21] instanceof RowRecord); - assertTrue(r[row0+22] instanceof RowRecord); - - // Check things had the right row numbers - RowRecord rr; - rr = (RowRecord)r[row0+2]; - assertEquals(2, rr.getRowNumber()); - rr = (RowRecord)r[row0+20]; - assertEquals(20, rr.getRowNumber()); - rr = (RowRecord)r[row0+21]; - assertEquals(21, rr.getRowNumber()); - - MissingRowDummyRecord mr; - mr = (MissingRowDummyRecord)r[row0+3]; - assertEquals(3, mr.getRowNumber()); - mr = (MissingRowDummyRecord)r[row0+4]; - assertEquals(4, mr.getRowNumber()); - mr = (MissingRowDummyRecord)r[row0+5]; - assertEquals(5, mr.getRowNumber()); - mr = (MissingRowDummyRecord)r[row0+18]; - assertEquals(18, mr.getRowNumber()); - mr = (MissingRowDummyRecord)r[row0+19]; - assertEquals(19, mr.getRowNumber()); - } - - public void testEndOfRowRecords() { - openNormal(); - - // Find the cell at 0,0 - int cell00 = -1; - for(int i=0; i -1); - - // We have rows 0, 1, 2, 20 and 21 - // Row 0 has 1 entry - // Row 1 has 4 entries - // Row 2 has 6 entries - // Row 20 has 5 entries - // Row 21 has 7 entries - // Row 22 has 12 entries - - // Row 0 - assertFalse(r[cell00+0] instanceof LastCellOfRowDummyRecord); - assertTrue(r[cell00+1] instanceof LastCellOfRowDummyRecord); - // Row 1 - assertFalse(r[cell00+2] instanceof LastCellOfRowDummyRecord); - assertFalse(r[cell00+3] instanceof LastCellOfRowDummyRecord); - assertFalse(r[cell00+4] instanceof LastCellOfRowDummyRecord); - assertFalse(r[cell00+5] instanceof LastCellOfRowDummyRecord); - assertTrue(r[cell00+6] instanceof LastCellOfRowDummyRecord); - // Row 2 - assertFalse(r[cell00+7] instanceof LastCellOfRowDummyRecord); - assertFalse(r[cell00+8] instanceof LastCellOfRowDummyRecord); - assertFalse(r[cell00+9] instanceof LastCellOfRowDummyRecord); - assertFalse(r[cell00+10] instanceof LastCellOfRowDummyRecord); - assertFalse(r[cell00+11] instanceof LastCellOfRowDummyRecord); - assertFalse(r[cell00+12] instanceof LastCellOfRowDummyRecord); - assertTrue(r[cell00+13] instanceof LastCellOfRowDummyRecord); - // Row 3 -> 19 - assertTrue(r[cell00+14] instanceof LastCellOfRowDummyRecord); - assertTrue(r[cell00+15] instanceof LastCellOfRowDummyRecord); - assertTrue(r[cell00+16] instanceof LastCellOfRowDummyRecord); - assertTrue(r[cell00+17] instanceof LastCellOfRowDummyRecord); - assertTrue(r[cell00+18] instanceof LastCellOfRowDummyRecord); - assertTrue(r[cell00+19] instanceof LastCellOfRowDummyRecord); - assertTrue(r[cell00+20] instanceof LastCellOfRowDummyRecord); - assertTrue(r[cell00+21] instanceof LastCellOfRowDummyRecord); - assertTrue(r[cell00+22] instanceof LastCellOfRowDummyRecord); - assertTrue(r[cell00+23] instanceof LastCellOfRowDummyRecord); - assertTrue(r[cell00+24] instanceof LastCellOfRowDummyRecord); - assertTrue(r[cell00+25] instanceof LastCellOfRowDummyRecord); - assertTrue(r[cell00+26] instanceof LastCellOfRowDummyRecord); - assertTrue(r[cell00+27] instanceof LastCellOfRowDummyRecord); - assertTrue(r[cell00+28] instanceof LastCellOfRowDummyRecord); - assertTrue(r[cell00+29] instanceof LastCellOfRowDummyRecord); - assertTrue(r[cell00+30] instanceof LastCellOfRowDummyRecord); - // Row 20 - assertFalse(r[cell00+31] instanceof LastCellOfRowDummyRecord); - assertFalse(r[cell00+32] instanceof LastCellOfRowDummyRecord); - assertFalse(r[cell00+33] instanceof LastCellOfRowDummyRecord); - assertFalse(r[cell00+34] instanceof LastCellOfRowDummyRecord); - assertFalse(r[cell00+35] instanceof LastCellOfRowDummyRecord); - assertTrue(r[cell00+36] instanceof LastCellOfRowDummyRecord); - // Row 21 - assertFalse(r[cell00+37] instanceof LastCellOfRowDummyRecord); - assertFalse(r[cell00+38] instanceof LastCellOfRowDummyRecord); - assertFalse(r[cell00+39] instanceof LastCellOfRowDummyRecord); - assertFalse(r[cell00+40] instanceof LastCellOfRowDummyRecord); - assertFalse(r[cell00+41] instanceof LastCellOfRowDummyRecord); - assertFalse(r[cell00+42] instanceof LastCellOfRowDummyRecord); - assertFalse(r[cell00+43] instanceof LastCellOfRowDummyRecord); - assertTrue(r[cell00+44] instanceof LastCellOfRowDummyRecord); - // Row 22 - assertFalse(r[cell00+45] instanceof LastCellOfRowDummyRecord); - assertFalse(r[cell00+46] instanceof LastCellOfRowDummyRecord); - assertFalse(r[cell00+47] instanceof LastCellOfRowDummyRecord); - assertFalse(r[cell00+48] instanceof LastCellOfRowDummyRecord); - assertFalse(r[cell00+49] instanceof LastCellOfRowDummyRecord); - assertFalse(r[cell00+50] instanceof LastCellOfRowDummyRecord); - assertFalse(r[cell00+51] instanceof LastCellOfRowDummyRecord); - assertFalse(r[cell00+52] instanceof LastCellOfRowDummyRecord); - assertFalse(r[cell00+53] instanceof LastCellOfRowDummyRecord); - assertFalse(r[cell00+54] instanceof LastCellOfRowDummyRecord); - assertFalse(r[cell00+55] instanceof LastCellOfRowDummyRecord); - assertFalse(r[cell00+56] instanceof LastCellOfRowDummyRecord); - assertTrue(r[cell00+57] instanceof LastCellOfRowDummyRecord); - - // Check the numbers of the last seen columns - LastCellOfRowDummyRecord[] lrs = new LastCellOfRowDummyRecord[24]; - int lrscount = 0; - for (final Record rec : r) { - if(rec instanceof LastCellOfRowDummyRecord) { - lrs[lrscount] = (LastCellOfRowDummyRecord)rec; - lrscount++; - } - } - - assertEquals(0, lrs[0].getLastColumnNumber()); - assertEquals(0, lrs[0].getRow()); - - assertEquals(3, lrs[1].getLastColumnNumber()); - assertEquals(1, lrs[1].getRow()); - - assertEquals(5, lrs[2].getLastColumnNumber()); - assertEquals(2, lrs[2].getRow()); - - for(int i=3; i<=19; i++) { - assertEquals(-1, lrs[i].getLastColumnNumber()); - assertEquals(i, lrs[i].getRow()); - } - - assertEquals(4, lrs[20].getLastColumnNumber()); - assertEquals(20, lrs[20].getRow()); - - assertEquals(6, lrs[21].getLastColumnNumber()); - assertEquals(21, lrs[21].getRow()); - - assertEquals(11, lrs[22].getLastColumnNumber()); - assertEquals(22, lrs[22].getRow()); - } - - - public void testMissingCellRecords() { - openNormal(); - - // Find the cell at 0,0 - int cell00 = -1; - for(int i=0; i -1); - - // We have rows 0, 1, 2, 20 and 21 - // Row 0 has 1 entry, 0 - // Row 1 has 4 entries, 0+3 - // Row 2 has 6 entries, 0+5 - // Row 20 has 5 entries, 0-5 - // Row 21 has 7 entries, 0+1+3+5+6 - // Row 22 has 12 entries, 0+3+4+11 - - // Row 0 - assertFalse(r[cell00+0] instanceof MissingCellDummyRecord); - assertFalse(r[cell00+1] instanceof MissingCellDummyRecord); - - // Row 1 - assertFalse(r[cell00+2] instanceof MissingCellDummyRecord); - assertTrue(r[cell00+3] instanceof MissingCellDummyRecord); - assertTrue(r[cell00+4] instanceof MissingCellDummyRecord); - assertFalse(r[cell00+5] instanceof MissingCellDummyRecord); - assertFalse(r[cell00+6] instanceof MissingCellDummyRecord); - - // Row 2 - assertFalse(r[cell00+7] instanceof MissingCellDummyRecord); - assertTrue(r[cell00+8] instanceof MissingCellDummyRecord); - assertTrue(r[cell00+9] instanceof MissingCellDummyRecord); - assertTrue(r[cell00+10] instanceof MissingCellDummyRecord); - assertTrue(r[cell00+11] instanceof MissingCellDummyRecord); - assertFalse(r[cell00+12] instanceof MissingCellDummyRecord); - assertFalse(r[cell00+13] instanceof MissingCellDummyRecord); - - // Row 3-19 - assertFalse(r[cell00+14] instanceof MissingCellDummyRecord); - assertFalse(r[cell00+15] instanceof MissingCellDummyRecord); - - // Row 20 - assertFalse(r[cell00+31] instanceof MissingCellDummyRecord); - assertFalse(r[cell00+32] instanceof MissingCellDummyRecord); - assertFalse(r[cell00+33] instanceof MissingCellDummyRecord); - assertFalse(r[cell00+34] instanceof MissingCellDummyRecord); - assertFalse(r[cell00+35] instanceof MissingCellDummyRecord); - assertFalse(r[cell00+36] instanceof MissingCellDummyRecord); - - // Row 21 - assertFalse(r[cell00+37] instanceof MissingCellDummyRecord); - assertFalse(r[cell00+38] instanceof MissingCellDummyRecord); - assertTrue(r[cell00+39] instanceof MissingCellDummyRecord); - assertFalse(r[cell00+40] instanceof MissingCellDummyRecord); - assertTrue(r[cell00+41] instanceof MissingCellDummyRecord); - assertFalse(r[cell00+42] instanceof MissingCellDummyRecord); - assertFalse(r[cell00+43] instanceof MissingCellDummyRecord); - assertFalse(r[cell00+44] instanceof MissingCellDummyRecord); - - // Row 22 - assertFalse(r[cell00+45] instanceof MissingCellDummyRecord); - assertTrue(r[cell00+46] instanceof MissingCellDummyRecord); - assertTrue(r[cell00+47] instanceof MissingCellDummyRecord); - assertFalse(r[cell00+48] instanceof MissingCellDummyRecord); - assertFalse(r[cell00+49] instanceof MissingCellDummyRecord); - assertTrue(r[cell00+50] instanceof MissingCellDummyRecord); - assertTrue(r[cell00+51] instanceof MissingCellDummyRecord); - assertTrue(r[cell00+52] instanceof MissingCellDummyRecord); - assertTrue(r[cell00+53] instanceof MissingCellDummyRecord); - assertTrue(r[cell00+54] instanceof MissingCellDummyRecord); - assertTrue(r[cell00+55] instanceof MissingCellDummyRecord); - assertFalse(r[cell00+56] instanceof MissingCellDummyRecord); - assertFalse(r[cell00+57] instanceof MissingCellDummyRecord); - - // Check some numbers - MissingCellDummyRecord mc; - - mc = (MissingCellDummyRecord)r[cell00+3]; - assertEquals(1, mc.getRow()); - assertEquals(1, mc.getColumn()); - mc = (MissingCellDummyRecord)r[cell00+4]; - assertEquals(1, mc.getRow()); - assertEquals(2, mc.getColumn()); - - mc = (MissingCellDummyRecord)r[cell00+8]; - assertEquals(2, mc.getRow()); - assertEquals(1, mc.getColumn()); - mc = (MissingCellDummyRecord)r[cell00+9]; - assertEquals(2, mc.getRow()); - assertEquals(2, mc.getColumn()); - - mc = (MissingCellDummyRecord)r[cell00+55]; - assertEquals(22, mc.getRow()); - assertEquals(10, mc.getColumn()); - } - - // Make sure we don't put in any extra new lines - // that aren't already there - public void testNoExtraNewLines() { - // Load a different file - // This file has has something in lines 1-33 - readRecords("MRExtraLines.xls"); - - int rowCount=0; - for (Record rec : r) { - if(rec instanceof LastCellOfRowDummyRecord) { - LastCellOfRowDummyRecord eor = (LastCellOfRowDummyRecord) rec; - assertEquals(rowCount, eor.getRow()); - rowCount++; - } - } - // Check we got the 33 rows - assertEquals(33, rowCount); - } - - private static final class MockHSSFListener implements HSSFListener { - public MockHSSFListener() {} - private final List _records = new ArrayList(); - private final boolean logToStdOut = false; - - @Override - public void processRecord(Record record) { - _records.add(record); - - if(record instanceof MissingRowDummyRecord) { - MissingRowDummyRecord mr = (MissingRowDummyRecord)record; - log("Got dummy row " + mr.getRowNumber()); - } - if(record instanceof MissingCellDummyRecord) { - MissingCellDummyRecord mc = (MissingCellDummyRecord)record; - log("Got dummy cell " + mc.getRow() + " " + mc.getColumn()); - } - if(record instanceof LastCellOfRowDummyRecord) { - LastCellOfRowDummyRecord lc = (LastCellOfRowDummyRecord)record; - log("Got end-of row, row was " + lc.getRow() + ", last column was " + lc.getLastColumnNumber()); - } - - if(record instanceof BOFRecord) { - BOFRecord r = (BOFRecord)record; - if(r.getType() == BOFRecord.TYPE_WORKSHEET) { - log("On new sheet"); - } - } - if(record instanceof RowRecord) { - RowRecord rr = (RowRecord)record; - log("Starting row #" + rr.getRowNumber()); - } - } - private void log(String msg) { - if(logToStdOut) { - System.out.println(msg); - } - } - public Record[] getRecords() { - Record[] result = new Record[_records.size()]; - _records.toArray(result); - return result; - } - } - - /** - * Make sure that the presence of shared formulas does not cause extra - * end-of-row records. - */ - public void testEndOfRow_bug45672() { - readRecords("ex45672.xls"); - Record[] rr = r; - int eorCount=0; - int sfrCount=0; - for (Record record : rr) { - if (record instanceof SharedFormulaRecord) { - sfrCount++; - } - if (record instanceof LastCellOfRowDummyRecord) { - eorCount++; - } - } - if (eorCount == 2) { - throw new AssertionFailedError("Identified bug 45672"); - } - assertEquals(1, eorCount); - assertEquals(1, sfrCount); - } - - /** - * MulBlank records hold multiple blank cells. Check we - * can handle them correctly. - */ - public void testMulBlankHandling() { - readRecords("45672.xls"); - - // Check that we don't have any MulBlankRecords, but do - // have lots of BlankRecords - Record[] rr = r; - int eorCount=0; - int mbrCount=0; - int brCount=0; - for (Record record : rr) { - if (record instanceof MulBlankRecord) { - mbrCount++; - } - if (record instanceof BlankRecord) { - brCount++; - } - if (record instanceof LastCellOfRowDummyRecord) { - eorCount++; - } - } - if (mbrCount > 0) { - throw new AssertionFailedError("Identified bug 45672"); - } - if (brCount < 20) { - throw new AssertionFailedError("Identified bug 45672"); - } - if (eorCount != 2) { - throw new AssertionFailedError("Identified bug 45672"); - } - assertEquals(2, eorCount); - } - - public void testStringRecordHandling(){ - readRecords("53588.xls"); - Record[] rr = r; - int missingCount=0; - int lastCount=0; - for (Record record : rr) { - if (record instanceof MissingCellDummyRecord) { - missingCount++; - } - if (record instanceof LastCellOfRowDummyRecord) { - lastCount++; - } - } - assertEquals(1, missingCount); - assertEquals(1, lastCount); - } - - public void testFormulasWithStringResultsHandling() { - readRecords("53433.xls"); - - int pos = 95; - - // First three rows are blank - assertEquals(DimensionsRecord.class, r[pos++].getClass()); - - assertEquals(MissingRowDummyRecord.class, r[pos].getClass()); - assertEquals(0, ((MissingRowDummyRecord)r[pos]).getRowNumber()); - pos++; - assertEquals(MissingRowDummyRecord.class, r[pos].getClass()); - assertEquals(1, ((MissingRowDummyRecord)r[pos]).getRowNumber()); - pos++; - assertEquals(MissingRowDummyRecord.class, r[pos].getClass()); - assertEquals(2, ((MissingRowDummyRecord)r[pos]).getRowNumber()); - pos++; - - // Then rows 4-10 are defined - assertEquals(RowRecord.class, r[pos].getClass()); - assertEquals(3, ((RowRecord)r[pos]).getRowNumber()); - pos++; - assertEquals(RowRecord.class, r[pos].getClass()); - assertEquals(4, ((RowRecord)r[pos]).getRowNumber()); - pos++; - assertEquals(RowRecord.class, r[pos].getClass()); - assertEquals(5, ((RowRecord)r[pos]).getRowNumber()); - pos++; - assertEquals(RowRecord.class, r[pos].getClass()); - assertEquals(6, ((RowRecord)r[pos]).getRowNumber()); - pos++; - assertEquals(RowRecord.class, r[pos].getClass()); - assertEquals(7, ((RowRecord)r[pos]).getRowNumber()); - pos++; - assertEquals(RowRecord.class, r[pos].getClass()); - assertEquals(8, ((RowRecord)r[pos]).getRowNumber()); - pos++; - assertEquals(RowRecord.class, r[pos].getClass()); - assertEquals(9, ((RowRecord)r[pos]).getRowNumber()); - pos++; - - // 5 more blank rows - assertEquals(MissingRowDummyRecord.class, r[pos].getClass()); - assertEquals(10, ((MissingRowDummyRecord)r[pos]).getRowNumber()); - pos++; - assertEquals(MissingRowDummyRecord.class, r[pos].getClass()); - assertEquals(11, ((MissingRowDummyRecord)r[pos]).getRowNumber()); - pos++; - assertEquals(MissingRowDummyRecord.class, r[pos].getClass()); - assertEquals(12, ((MissingRowDummyRecord)r[pos]).getRowNumber()); - pos++; - assertEquals(MissingRowDummyRecord.class, r[pos].getClass()); - assertEquals(13, ((MissingRowDummyRecord)r[pos]).getRowNumber()); - pos++; - assertEquals(MissingRowDummyRecord.class, r[pos].getClass()); - assertEquals(14, ((MissingRowDummyRecord)r[pos]).getRowNumber()); - pos++; - - // 2 defined rows - assertEquals(RowRecord.class, r[pos].getClass()); - assertEquals(15, ((RowRecord)r[pos]).getRowNumber()); - pos++; - assertEquals(RowRecord.class, r[pos].getClass()); - assertEquals(16, ((RowRecord)r[pos]).getRowNumber()); - pos++; - - // one blank row - assertEquals(MissingRowDummyRecord.class, r[pos].getClass()); - assertEquals(17, ((MissingRowDummyRecord)r[pos]).getRowNumber()); - pos++; - - // one last real row - assertEquals(RowRecord.class, r[pos].getClass()); - assertEquals(18, ((RowRecord)r[pos]).getRowNumber()); - pos++; - - - - // Now onto the cells - - // Because the 3 first rows are missing, should have last-of-row records first - assertEquals(LastCellOfRowDummyRecord.class, r[pos].getClass()); - assertEquals(0, ((LastCellOfRowDummyRecord)r[pos]).getRow()); - assertEquals(-1, ((LastCellOfRowDummyRecord)r[pos]).getLastColumnNumber()); - pos++; - assertEquals(LastCellOfRowDummyRecord.class, r[pos].getClass()); - assertEquals(1, ((LastCellOfRowDummyRecord)r[pos]).getRow()); - assertEquals(-1, ((LastCellOfRowDummyRecord)r[pos]).getLastColumnNumber()); - pos++; - assertEquals(LastCellOfRowDummyRecord.class, r[pos].getClass()); - assertEquals(2, ((LastCellOfRowDummyRecord)r[pos]).getRow()); - assertEquals(-1, ((LastCellOfRowDummyRecord)r[pos]).getLastColumnNumber()); - pos++; - - - // Onto row 4 (=3) - - // Now we have blank cell A4 - assertEquals(MissingCellDummyRecord.class, r[pos].getClass()); - assertEquals(3, ((MissingCellDummyRecord)r[pos]).getRow()); - assertEquals(0, ((MissingCellDummyRecord)r[pos]).getColumn()); - pos++; - - // Now 4 real cells, all strings - assertEquals(LabelSSTRecord.class, r[pos].getClass()); - assertEquals(3, ((CellValueRecordInterface)r[pos]).getRow()); - assertEquals(1, ((CellValueRecordInterface)r[pos]).getColumn()); - pos++; - assertEquals(LabelSSTRecord.class, r[pos].getClass()); - assertEquals(3, ((CellValueRecordInterface)r[pos]).getRow()); - assertEquals(2, ((CellValueRecordInterface)r[pos]).getColumn()); - pos++; - assertEquals(LabelSSTRecord.class, r[pos].getClass()); - assertEquals(3, ((CellValueRecordInterface)r[pos]).getRow()); - assertEquals(3, ((CellValueRecordInterface)r[pos]).getColumn()); - pos++; - assertEquals(LabelSSTRecord.class, r[pos].getClass()); - assertEquals(3, ((CellValueRecordInterface)r[pos]).getRow()); - assertEquals(4, ((CellValueRecordInterface)r[pos]).getColumn()); - pos++; - - // Final dummy cell for the end-of-row - assertEquals(LastCellOfRowDummyRecord.class, r[pos].getClass()); - assertEquals(3, ((LastCellOfRowDummyRecord)r[pos]).getRow()); - assertEquals(4, ((LastCellOfRowDummyRecord)r[pos]).getLastColumnNumber()); - pos++; - - - // Row 5 has string, formula of string, number, formula of string - assertEquals(MissingCellDummyRecord.class, r[pos].getClass()); - assertEquals(4, ((MissingCellDummyRecord)r[pos]).getRow()); - assertEquals(0, ((MissingCellDummyRecord)r[pos]).getColumn()); - pos++; - - assertEquals(LabelSSTRecord.class, r[pos].getClass()); - assertEquals(4, ((CellValueRecordInterface)r[pos]).getRow()); - assertEquals(1, ((CellValueRecordInterface)r[pos]).getColumn()); - pos++; - assertEquals(FormulaRecord.class, r[pos].getClass()); - assertEquals(4, ((CellValueRecordInterface)r[pos]).getRow()); - assertEquals(2, ((CellValueRecordInterface)r[pos]).getColumn()); - pos++; - assertEquals(StringRecord.class, r[pos].getClass()); - assertEquals("s1", ((StringRecord)r[pos]).getString()); - pos++; - assertEquals(NumberRecord.class, r[pos].getClass()); - assertEquals(4, ((CellValueRecordInterface)r[pos]).getRow()); - assertEquals(3, ((CellValueRecordInterface)r[pos]).getColumn()); - pos++; - assertEquals(FormulaRecord.class, r[pos].getClass()); - assertEquals(4, ((CellValueRecordInterface)r[pos]).getRow()); - assertEquals(4, ((CellValueRecordInterface)r[pos]).getColumn()); - pos++; - assertEquals(StringRecord.class, r[pos].getClass()); - assertEquals("s3845", ((StringRecord)r[pos]).getString()); - pos++; - - // Final dummy cell for the end-of-row - assertEquals(LastCellOfRowDummyRecord.class, r[pos].getClass()); - assertEquals(4, ((LastCellOfRowDummyRecord)r[pos]).getRow()); - assertEquals(4, ((LastCellOfRowDummyRecord)r[pos]).getLastColumnNumber()); - pos++; - - - // Row 6 is blank / string formula / number / number / string formula - assertEquals(MissingCellDummyRecord.class, r[pos].getClass()); - assertEquals(5, ((MissingCellDummyRecord)r[pos]).getRow()); - assertEquals(0, ((MissingCellDummyRecord)r[pos]).getColumn()); - pos++; - - assertEquals(FormulaRecord.class, r[pos].getClass()); - assertEquals(5, ((CellValueRecordInterface)r[pos]).getRow()); - assertEquals(1, ((CellValueRecordInterface)r[pos]).getColumn()); - pos++; - assertEquals(StringRecord.class, r[pos].getClass()); - assertEquals("s4", ((StringRecord)r[pos]).getString()); - pos++; - assertEquals(NumberRecord.class, r[pos].getClass()); - assertEquals(5, ((CellValueRecordInterface)r[pos]).getRow()); - assertEquals(2, ((CellValueRecordInterface)r[pos]).getColumn()); - pos++; - assertEquals(NumberRecord.class, r[pos].getClass()); - assertEquals(5, ((CellValueRecordInterface)r[pos]).getRow()); - assertEquals(3, ((CellValueRecordInterface)r[pos]).getColumn()); - pos++; - assertEquals(FormulaRecord.class, r[pos].getClass()); - assertEquals(5, ((CellValueRecordInterface)r[pos]).getRow()); - assertEquals(4, ((CellValueRecordInterface)r[pos]).getColumn()); - pos++; - assertEquals(StringRecord.class, r[pos].getClass()); - assertEquals("s3845", ((StringRecord)r[pos]).getString()); - pos++; - - assertEquals(LastCellOfRowDummyRecord.class, r[pos].getClass()); - assertEquals(5, ((LastCellOfRowDummyRecord)r[pos]).getRow()); - assertEquals(4, ((LastCellOfRowDummyRecord)r[pos]).getLastColumnNumber()); - pos++; - - - // Row 7 is blank / blank / number / number / number - assertEquals(MissingCellDummyRecord.class, r[pos].getClass()); - assertEquals(6, ((MissingCellDummyRecord)r[pos]).getRow()); - assertEquals(0, ((MissingCellDummyRecord)r[pos]).getColumn()); - pos++; - assertEquals(MissingCellDummyRecord.class, r[pos].getClass()); - assertEquals(6, ((MissingCellDummyRecord)r[pos]).getRow()); - assertEquals(1, ((MissingCellDummyRecord)r[pos]).getColumn()); - pos++; - - assertEquals(NumberRecord.class, r[pos].getClass()); - assertEquals(6, ((CellValueRecordInterface)r[pos]).getRow()); - assertEquals(2, ((CellValueRecordInterface)r[pos]).getColumn()); - pos++; - assertEquals(NumberRecord.class, r[pos].getClass()); - assertEquals(6, ((CellValueRecordInterface)r[pos]).getRow()); - assertEquals(3, ((CellValueRecordInterface)r[pos]).getColumn()); - pos++; - assertEquals(NumberRecord.class, r[pos].getClass()); - assertEquals(6, ((CellValueRecordInterface)r[pos]).getRow()); - assertEquals(4, ((CellValueRecordInterface)r[pos]).getColumn()); - pos++; - - assertEquals(LastCellOfRowDummyRecord.class, r[pos].getClass()); - assertEquals(6, ((LastCellOfRowDummyRecord)r[pos]).getRow()); - assertEquals(4, ((LastCellOfRowDummyRecord)r[pos]).getLastColumnNumber()); - pos++; - - - // Row 8 is blank / string / number formula / string formula / blank - assertEquals(MissingCellDummyRecord.class, r[pos].getClass()); - assertEquals(7, ((MissingCellDummyRecord)r[pos]).getRow()); - assertEquals(0, ((MissingCellDummyRecord)r[pos]).getColumn()); - pos++; - - assertEquals(LabelSSTRecord.class, r[pos].getClass()); - assertEquals(7, ((CellValueRecordInterface)r[pos]).getRow()); - assertEquals(1, ((CellValueRecordInterface)r[pos]).getColumn()); - pos++; - assertEquals(FormulaRecord.class, r[pos].getClass()); - assertEquals(7, ((CellValueRecordInterface)r[pos]).getRow()); - assertEquals(2, ((CellValueRecordInterface)r[pos]).getColumn()); - pos++; - assertEquals(FormulaRecord.class, r[pos].getClass()); - assertEquals(7, ((CellValueRecordInterface)r[pos]).getRow()); - assertEquals(3, ((CellValueRecordInterface)r[pos]).getColumn()); - pos++; - assertEquals(StringRecord.class, r[pos].getClass()); - assertEquals("s4", ((StringRecord)r[pos]).getString()); - pos++; - assertEquals(BlankRecord.class, r[pos].getClass()); - assertEquals(7, ((CellValueRecordInterface)r[pos]).getRow()); - assertEquals(4, ((CellValueRecordInterface)r[pos]).getColumn()); - pos++; - - assertEquals(LastCellOfRowDummyRecord.class, r[pos].getClass()); - assertEquals(7, ((LastCellOfRowDummyRecord)r[pos]).getRow()); - assertEquals(4, ((LastCellOfRowDummyRecord)r[pos]).getLastColumnNumber()); - pos++; - - - // Row 9 is empty, but with a blank at E9 - assertEquals(MissingCellDummyRecord.class, r[pos].getClass()); - assertEquals(8, ((MissingCellDummyRecord)r[pos]).getRow()); - assertEquals(0, ((MissingCellDummyRecord)r[pos]).getColumn()); - pos++; - assertEquals(MissingCellDummyRecord.class, r[pos].getClass()); - assertEquals(8, ((MissingCellDummyRecord)r[pos]).getRow()); - assertEquals(1, ((MissingCellDummyRecord)r[pos]).getColumn()); - pos++; - assertEquals(MissingCellDummyRecord.class, r[pos].getClass()); - assertEquals(8, ((MissingCellDummyRecord)r[pos]).getRow()); - assertEquals(2, ((MissingCellDummyRecord)r[pos]).getColumn()); - pos++; - assertEquals(MissingCellDummyRecord.class, r[pos].getClass()); - assertEquals(8, ((MissingCellDummyRecord)r[pos]).getRow()); - assertEquals(3, ((MissingCellDummyRecord)r[pos]).getColumn()); - pos++; - assertEquals(BlankRecord.class, r[pos].getClass()); - assertEquals(8, ((CellValueRecordInterface)r[pos]).getRow()); - assertEquals(4, ((CellValueRecordInterface)r[pos]).getColumn()); - pos++; - assertEquals(LastCellOfRowDummyRecord.class, r[pos].getClass()); - assertEquals(8, ((LastCellOfRowDummyRecord)r[pos]).getRow()); - assertEquals(4, ((LastCellOfRowDummyRecord)r[pos]).getLastColumnNumber()); - pos++; - - - // Row 10 has a string in D10 - assertEquals(MissingCellDummyRecord.class, r[pos].getClass()); - assertEquals(9, ((MissingCellDummyRecord)r[pos]).getRow()); - assertEquals(0, ((MissingCellDummyRecord)r[pos]).getColumn()); - pos++; - assertEquals(MissingCellDummyRecord.class, r[pos].getClass()); - assertEquals(9, ((MissingCellDummyRecord)r[pos]).getRow()); - assertEquals(1, ((MissingCellDummyRecord)r[pos]).getColumn()); - pos++; - assertEquals(MissingCellDummyRecord.class, r[pos].getClass()); - assertEquals(9, ((MissingCellDummyRecord)r[pos]).getRow()); - assertEquals(2, ((MissingCellDummyRecord)r[pos]).getColumn()); - pos++; - assertEquals(LabelSSTRecord.class, r[pos].getClass()); - assertEquals(9, ((CellValueRecordInterface)r[pos]).getRow()); - assertEquals(3, ((CellValueRecordInterface)r[pos]).getColumn()); - pos++; - assertEquals(LastCellOfRowDummyRecord.class, r[pos].getClass()); - assertEquals(9, ((LastCellOfRowDummyRecord)r[pos]).getRow()); - assertEquals(3, ((LastCellOfRowDummyRecord)r[pos]).getLastColumnNumber()); - pos++; - - - // Now 5 blank rows - assertEquals(LastCellOfRowDummyRecord.class, r[pos].getClass()); - assertEquals(10, ((LastCellOfRowDummyRecord)r[pos]).getRow()); - assertEquals(-1, ((LastCellOfRowDummyRecord)r[pos]).getLastColumnNumber()); - pos++; - assertEquals(LastCellOfRowDummyRecord.class, r[pos].getClass()); - assertEquals(11, ((LastCellOfRowDummyRecord)r[pos]).getRow()); - assertEquals(-1, ((LastCellOfRowDummyRecord)r[pos]).getLastColumnNumber()); - pos++; - assertEquals(LastCellOfRowDummyRecord.class, r[pos].getClass()); - assertEquals(12, ((LastCellOfRowDummyRecord)r[pos]).getRow()); - assertEquals(-1, ((LastCellOfRowDummyRecord)r[pos]).getLastColumnNumber()); - pos++; - assertEquals(LastCellOfRowDummyRecord.class, r[pos].getClass()); - assertEquals(13, ((LastCellOfRowDummyRecord)r[pos]).getRow()); - assertEquals(-1, ((LastCellOfRowDummyRecord)r[pos]).getLastColumnNumber()); - pos++; - assertEquals(LastCellOfRowDummyRecord.class, r[pos].getClass()); - assertEquals(14, ((LastCellOfRowDummyRecord)r[pos]).getRow()); - assertEquals(-1, ((LastCellOfRowDummyRecord)r[pos]).getLastColumnNumber()); - pos++; - - - // Row 16 has a single string in B16 - assertEquals(MissingCellDummyRecord.class, r[pos].getClass()); - assertEquals(15, ((MissingCellDummyRecord)r[pos]).getRow()); - assertEquals(0, ((MissingCellDummyRecord)r[pos]).getColumn()); - pos++; - assertEquals(LabelSSTRecord.class, r[pos].getClass()); - assertEquals(15, ((CellValueRecordInterface)r[pos]).getRow()); - assertEquals(1, ((CellValueRecordInterface)r[pos]).getColumn()); - pos++; - assertEquals(LastCellOfRowDummyRecord.class, r[pos].getClass()); - assertEquals(15, ((LastCellOfRowDummyRecord)r[pos]).getRow()); - assertEquals(1, ((LastCellOfRowDummyRecord)r[pos]).getLastColumnNumber()); - pos++; - - - // Row 17 has a single string in D17 - assertEquals(MissingCellDummyRecord.class, r[pos].getClass()); - assertEquals(16, ((MissingCellDummyRecord)r[pos]).getRow()); - assertEquals(0, ((MissingCellDummyRecord)r[pos]).getColumn()); - pos++; - assertEquals(MissingCellDummyRecord.class, r[pos].getClass()); - assertEquals(16, ((MissingCellDummyRecord)r[pos]).getRow()); - assertEquals(1, ((MissingCellDummyRecord)r[pos]).getColumn()); - pos++; - assertEquals(MissingCellDummyRecord.class, r[pos].getClass()); - assertEquals(16, ((MissingCellDummyRecord)r[pos]).getRow()); - assertEquals(2, ((MissingCellDummyRecord)r[pos]).getColumn()); - pos++; - assertEquals(LabelSSTRecord.class, r[pos].getClass()); - assertEquals(16, ((CellValueRecordInterface)r[pos]).getRow()); - assertEquals(3, ((CellValueRecordInterface)r[pos]).getColumn()); - pos++; - assertEquals(LastCellOfRowDummyRecord.class, r[pos].getClass()); - assertEquals(16, ((LastCellOfRowDummyRecord)r[pos]).getRow()); - assertEquals(3, ((LastCellOfRowDummyRecord)r[pos]).getLastColumnNumber()); - pos++; - - - // Row 18 is blank - assertEquals(LastCellOfRowDummyRecord.class, r[pos].getClass()); - assertEquals(17, ((LastCellOfRowDummyRecord)r[pos]).getRow()); - assertEquals(-1, ((LastCellOfRowDummyRecord)r[pos]).getLastColumnNumber()); - pos++; - - - // Row 19 has a single string in E19 - assertEquals(MissingCellDummyRecord.class, r[pos].getClass()); - assertEquals(18, ((MissingCellDummyRecord)r[pos]).getRow()); - assertEquals(0, ((MissingCellDummyRecord)r[pos]).getColumn()); - pos++; - assertEquals(MissingCellDummyRecord.class, r[pos].getClass()); - assertEquals(18, ((MissingCellDummyRecord)r[pos]).getRow()); - assertEquals(1, ((MissingCellDummyRecord)r[pos]).getColumn()); - pos++; - assertEquals(MissingCellDummyRecord.class, r[pos].getClass()); - assertEquals(18, ((MissingCellDummyRecord)r[pos]).getRow()); - assertEquals(2, ((MissingCellDummyRecord)r[pos]).getColumn()); - pos++; - assertEquals(MissingCellDummyRecord.class, r[pos].getClass()); - assertEquals(18, ((MissingCellDummyRecord)r[pos]).getRow()); - assertEquals(3, ((MissingCellDummyRecord)r[pos]).getColumn()); - pos++; - assertEquals(LabelSSTRecord.class, r[pos].getClass()); - assertEquals(18, ((CellValueRecordInterface)r[pos]).getRow()); - assertEquals(4, ((CellValueRecordInterface)r[pos]).getColumn()); - pos++; - assertEquals(LastCellOfRowDummyRecord.class, r[pos].getClass()); - assertEquals(18, ((LastCellOfRowDummyRecord)r[pos]).getRow()); - assertEquals(4, ((LastCellOfRowDummyRecord)r[pos]).getLastColumnNumber()); - pos++; - - - // And that's it! - assertEquals(WindowTwoRecord.class, r[pos++].getClass()); - } -} diff --git a/src/testcases/org/apache/poi/hssf/extractor/TestExcelExtractor.java b/src/testcases/org/apache/poi/hssf/extractor/TestExcelExtractor.java deleted file mode 100644 index 6156cb1b5..000000000 --- a/src/testcases/org/apache/poi/hssf/extractor/TestExcelExtractor.java +++ /dev/null @@ -1,394 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.extractor; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.File; -import java.io.IOException; -import java.util.Locale; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.poifs.filesystem.DirectoryNode; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.util.LocaleUtil; -import org.junit.After; -import org.junit.Test; - -/** - * - */ -public final class TestExcelExtractor { - // to not affect other tests running in the same JVM - @After - public void resetPassword() { - Biff8EncryptionKey.setCurrentUserPassword(null); - } - - private static ExcelExtractor createExtractor(String sampleFileName) throws IOException { - File file = HSSFTestDataSamples.getSampleFile(sampleFileName); - POIFSFileSystem fs = new POIFSFileSystem(file); - ExcelExtractor extractor = new ExcelExtractor(fs); - extractor.setFilesystem(fs); - return extractor; - } - - @Test - public void testSimple() throws IOException { - ExcelExtractor extractor = createExtractor("Simple.xls"); - - try { - assertEquals("Sheet1\nreplaceMe\nSheet2\nSheet3\n", extractor.getText()); - - // Now turn off sheet names - extractor.setIncludeSheetNames(false); - assertEquals("replaceMe\n", extractor.getText()); - } finally { - extractor.close(); - } - } - - @Test - public void testNumericFormula() throws IOException { - - ExcelExtractor extractor = createExtractor("sumifformula.xls"); - - assertEquals( - "Sheet1\n" + - "1000\t1\t5\n" + - "2000\t2\n" + - "3000\t3\n" + - "4000\t4\n" + - "5000\t5\n" + - "Sheet2\nSheet3\n", - extractor.getText() - ); - - extractor.setFormulasNotResults(true); - - assertEquals( - "Sheet1\n" + - "1000\t1\tSUMIF(A1:A5,\">4000\",B1:B5)\n" + - "2000\t2\n" + - "3000\t3\n" + - "4000\t4\n" + - "5000\t5\n" + - "Sheet2\nSheet3\n", - extractor.getText() - ); - - extractor.close(); - } - - @Test - public void testwithContinueRecords() throws IOException { - - ExcelExtractor extractor = createExtractor("StringContinueRecords.xls"); - - extractor.getText(); - - // Has masses of text - // Until we fixed bug #41064, this would've - // failed by now - assertTrue(extractor.getText().length() > 40960); - - extractor.close(); - } - - @Test - public void testStringConcat() throws IOException { - - ExcelExtractor extractor = createExtractor("SimpleWithFormula.xls"); - - // Comes out as NaN if treated as a number - // And as XYZ if treated as a string - assertEquals("Sheet1\nreplaceme\nreplaceme\nreplacemereplaceme\nSheet2\nSheet3\n", extractor.getText()); - - extractor.setFormulasNotResults(true); - - assertEquals("Sheet1\nreplaceme\nreplaceme\nCONCATENATE(A1,A2)\nSheet2\nSheet3\n", extractor.getText()); - - extractor.close(); - } - - @Test - public void testStringFormula() throws IOException { - - ExcelExtractor extractor = createExtractor("StringFormulas.xls"); - - // Comes out as NaN if treated as a number - // And as XYZ if treated as a string - assertEquals("Sheet1\nXYZ\nSheet2\nSheet3\n", extractor.getText()); - - extractor.setFormulasNotResults(true); - - assertEquals("Sheet1\nUPPER(\"xyz\")\nSheet2\nSheet3\n", extractor.getText()); - - extractor.close(); - } - - - @Test - public void testEventExtractor() throws Exception { - // First up, a simple file with string - // based formulas in it - EventBasedExcelExtractor extractor1 = null; - try { - extractor1 = new EventBasedExcelExtractor( - new POIFSFileSystem( - HSSFTestDataSamples.openSampleFileStream("SimpleWithFormula.xls") - ) - ); - extractor1.setIncludeSheetNames(true); - - String text = extractor1.getText(); - assertEquals("Sheet1\nreplaceme\nreplaceme\nreplacemereplaceme\nSheet2\nSheet3\n", text); - - extractor1.setIncludeSheetNames(false); - extractor1.setFormulasNotResults(true); - - text = extractor1.getText(); - assertEquals("replaceme\nreplaceme\nCONCATENATE(A1,A2)\n", text); - } finally { - if (extractor1 != null) extractor1.close(); - } - - // Now, a slightly longer file with numeric formulas - EventBasedExcelExtractor extractor2 = null; - try { - extractor2 = new EventBasedExcelExtractor( - new POIFSFileSystem( - HSSFTestDataSamples.openSampleFileStream("sumifformula.xls") - ) - ); - - extractor2.setIncludeSheetNames(false); - extractor2.setFormulasNotResults(true); - - String text = extractor2.getText(); - assertEquals( - "1000\t1\tSUMIF(A1:A5,\">4000\",B1:B5)\n" + - "2000\t2\n" + - "3000\t3\n" + - "4000\t4\n" + - "5000\t5\n", - text - ); - } finally { - if (extractor2 != null) extractor2.close(); - } - } - - @Test - public void testWithComments() throws IOException { - ExcelExtractor extractor = createExtractor("SimpleWithComments.xls"); - extractor.setIncludeSheetNames(false); - - // Check without comments - assertEquals( - "1\tone\n" + - "2\ttwo\n" + - "3\tthree\n", - extractor.getText() - ); - - // Now with - extractor.setIncludeCellComments(true); - assertEquals( - "1\tone Comment by Yegor Kozlov: Yegor Kozlov: first cell\n" + - "2\ttwo Comment by Yegor Kozlov: Yegor Kozlov: second cell\n" + - "3\tthree Comment by Yegor Kozlov: Yegor Kozlov: third cell\n", - extractor.getText() - ); - - extractor.close(); - } - - @Test - public void testWithBlank() throws IOException { - ExcelExtractor extractor = createExtractor("MissingBits.xls"); - String def = extractor.getText(); - extractor.setIncludeBlankCells(true); - String padded = extractor.getText(); - - assertTrue(def.startsWith( - "Sheet1\n" + - "&[TAB]\t\n" + - "Hello\n" + - "11\t23\n" - )); - - assertTrue(padded.startsWith( - "Sheet1\n" + - "&[TAB]\t\n" + - "Hello\n" + - "11\t\t\t23\n" - )); - - extractor.close(); - } - - @Test - public void testFormatting() throws Exception { - Locale userLocale = LocaleUtil.getUserLocale(); - LocaleUtil.setUserLocale(Locale.ROOT); - try { - ExcelExtractor extractor = createExtractor("Formatting.xls"); - extractor.setIncludeBlankCells(false); - extractor.setIncludeSheetNames(false); - String text = extractor.getText(); - - // Note - not all the formats in the file - // actually quite match what they claim to - // be, as some are auto-local builtins... - - assertTrue(text.startsWith( - "Dates, all 24th November 2006\n" - )); - assertTrue(text.contains("yyyy/mm/dd\t2006/11/24\n")); - assertTrue(text.contains("yyyy-mm-dd\t2006-11-24\n")); - assertTrue(text.contains("dd-mm-yy\t24-11-06\n")); - - assertTrue("Had: " + text + ", but should contain 'nn.nn\\t10.52\\n'", - text.contains("nn.nn\t10.52\n")); - assertTrue(text.contains("nn.nnn\t10.520\n")); - assertTrue(text.contains("\u00a3nn.nn\t\u00a310.52\n")); - extractor.close(); - } finally { - LocaleUtil.setUserLocale(userLocale); - } - } - - /** - * Embeded in a non-excel file - */ - @Test - public void testWithEmbeded() throws Exception { - POIFSFileSystem fs = null; - - HSSFWorkbook wbA = null, wbB = null; - ExcelExtractor exA = null, exB = null; - - try { - fs = new POIFSFileSystem(POIDataSamples.getDocumentInstance().getFile("word_with_embeded.doc")); - - DirectoryNode objPool = (DirectoryNode) fs.getRoot().getEntry("ObjectPool"); - DirectoryNode dirA = (DirectoryNode) objPool.getEntry("_1269427460"); - DirectoryNode dirB = (DirectoryNode) objPool.getEntry("_1269427461"); - - wbA = new HSSFWorkbook(dirA, fs, true); - exA = new ExcelExtractor(wbA); - wbB = new HSSFWorkbook(dirB, fs, true); - exB = new ExcelExtractor(wbB); - - assertEquals("Sheet1\nTest excel file\nThis is the first file\nSheet2\nSheet3\n", exA.getText()); - assertEquals("Sample Excel", exA.getSummaryInformation().getTitle()); - assertEquals("Sheet1\nAnother excel file\nThis is the second file\nSheet2\nSheet3\n", exB.getText()); - assertEquals("Sample Excel 2", exB.getSummaryInformation().getTitle()); - } finally { - if (exB != null) exB.close(); - if (wbB != null) wbB.close(); - if (exA != null) exA.close(); - if (wbA != null) wbA.close(); - if (fs != null) fs.close(); - } - } - - /** - * Excel embeded in excel - */ - @Test - public void testWithEmbededInOwn() throws Exception { - POIDataSamples ssSamples = POIDataSamples.getSpreadSheetInstance(); - POIFSFileSystem fs = null; - HSSFWorkbook wbA = null, wbB = null; - ExcelExtractor exA = null, exB = null, ex = null; - - try { - fs = new POIFSFileSystem(ssSamples.getFile("excel_with_embeded.xls")); - - DirectoryNode dirA = (DirectoryNode) fs.getRoot().getEntry("MBD0000A3B5"); - DirectoryNode dirB = (DirectoryNode) fs.getRoot().getEntry("MBD0000A3B4"); - - wbA = new HSSFWorkbook(dirA, fs, true); - wbB = new HSSFWorkbook(dirB, fs, true); - - exA = new ExcelExtractor(wbA); - exB = new ExcelExtractor(wbB); - assertEquals("Sheet1\nTest excel file\nThis is the first file\nSheet2\nSheet3\n", exA.getText()); - assertEquals("Sample Excel", exA.getSummaryInformation().getTitle()); - - assertEquals("Sheet1\nAnother excel file\nThis is the second file\nSheet2\nSheet3\n", exB.getText()); - assertEquals("Sample Excel 2", exB.getSummaryInformation().getTitle()); - - // And the base file too - ex = new ExcelExtractor(fs); - assertEquals("Sheet1\nI have lots of embeded files in me\nSheet2\nSheet3\n", ex.getText()); - assertEquals("Excel With Embeded", ex.getSummaryInformation().getTitle()); - } finally { - if (ex != null) ex.close(); - if (exB != null) exB.close(); - if (exA != null) exA.close(); - if (wbB != null) wbB.close(); - if (wbA != null) wbA.close(); - if (fs != null) fs.close(); - } - } - - /** - * Test that we get text from headers and footers - */ - @Test - public void test45538() throws IOException { - String[] files = { - "45538_classic_Footer.xls", "45538_form_Footer.xls", - "45538_classic_Header.xls", "45538_form_Header.xls" - }; - for (String file : files) { - ExcelExtractor extractor = createExtractor(file); - String text = extractor.getText(); - assertTrue("Unable to find expected word in text\n" + text, text.contains("testdoc")); - assertTrue("Unable to find expected word in text\n" + text, text.contains("test phrase")); - extractor.close(); - } - } - - @Test - public void testPassword() throws IOException { - Biff8EncryptionKey.setCurrentUserPassword("password"); - ExcelExtractor extractor = createExtractor("password.xls"); - String text = extractor.getText(); - Biff8EncryptionKey.setCurrentUserPassword(null); - - assertTrue(text.contains("ZIP")); - extractor.close(); - } - - @Test - public void testNullPointerException() throws IOException { - ExcelExtractor extractor = createExtractor("ar.org.apsme.www_Form%20Inscripcion%20Curso%20NO%20Socios.xls"); - assertNotNull(extractor); - assertNotNull(extractor.getText()); - extractor.close(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/extractor/TestOldExcelExtractor.java b/src/testcases/org/apache/poi/hssf/extractor/TestOldExcelExtractor.java deleted file mode 100644 index 659f76902..000000000 --- a/src/testcases/org/apache/poi/hssf/extractor/TestOldExcelExtractor.java +++ /dev/null @@ -1,371 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.extractor; - -import static org.apache.poi.POITestCase.assertContains; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.PrintStream; - -import org.apache.poi.EmptyFileException; -import org.apache.poi.EncryptedDocumentException; -import org.apache.poi.POIDataSamples; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; -import org.apache.poi.poifs.filesystem.OfficeXmlFileException; -import org.apache.poi.util.RecordFormatException; -import org.junit.Ignore; -import org.junit.Test; - -/** - * Unit tests for the Excel 5/95 and Excel 4 (and older) text - * extractor - */ -public final class TestOldExcelExtractor { - private static OldExcelExtractor createExtractor(String sampleFileName) throws IOException { - File file = HSSFTestDataSamples.getSampleFile(sampleFileName); - return new OldExcelExtractor(file); - } - - @Test - public void testSimpleExcel3() throws IOException { - OldExcelExtractor extractor = createExtractor("testEXCEL_3.xls"); - - // Check we can call getText without error - String text = extractor.getText(); - - // Check we find a few words we expect in there - assertContains(text, "Season beginning August"); - assertContains(text, "USDA"); - - // Check we find a few numbers we expect in there - assertContains(text, "347"); - assertContains(text, "228"); - - // Check we find a few string-literal dates in there - assertContains(text, "1981/82"); - - // Check the type - assertEquals(3, extractor.getBiffVersion()); - assertEquals(0x10, extractor.getFileType()); - - extractor.close(); - } - - - @Test - public void testSimpleExcel3NoReading() throws IOException { - OldExcelExtractor extractor = createExtractor("testEXCEL_3.xls"); - assertNotNull(extractor); - - extractor.close(); - } - - @Test - public void testSimpleExcel4() throws IOException { - OldExcelExtractor extractor = createExtractor("testEXCEL_4.xls"); - - // Check we can call getText without error - String text = extractor.getText(); - - // Check we find a few words we expect in there - assertContains(text, "Size"); - assertContains(text, "Returns"); - - // Check we find a few numbers we expect in there - assertContains(text, "11"); - assertContains(text, "784"); - - // Check the type - assertEquals(4, extractor.getBiffVersion()); - assertEquals(0x10, extractor.getFileType()); - - extractor.close(); - } - - @Test - public void testSimpleExcel5() throws IOException { - for (String ver : new String[] {"5", "95"}) { - OldExcelExtractor extractor = createExtractor("testEXCEL_"+ver+".xls"); - - // Check we can call getText without error - String text = extractor.getText(); - - // Check we find a few words we expect in there - assertContains(text, "Sample Excel"); - assertContains(text, "Written and saved"); - - // Check we find a few numbers we expect in there - assertContains(text, "15"); - assertContains(text, "169"); - - // Check we got the sheet names (new formats only) - assertContains(text, "Sheet: Feuil3"); - - // Check the type - assertEquals(5, extractor.getBiffVersion()); - assertEquals(0x05, extractor.getFileType()); - - extractor.close(); - } - } - - @Test - public void testStrings() throws IOException { - OldExcelExtractor extractor = createExtractor("testEXCEL_4.xls"); - String text = extractor.getText(); - - // Simple strings - assertContains(text, "Table 10 -- Examination Coverage:"); - assertContains(text, "Recommended and Average Recommended Additional Tax After"); - assertContains(text, "Individual income tax returns, total"); - - // More complicated strings - assertContains(text, "$100,000 or more"); - assertContains(text, "S corporation returns, Form 1120S [10,15]"); - assertContains(text, "individual income tax return \u201Cshort forms.\u201D"); - - // Formula based strings - // TODO Find some then test - - extractor.close(); - } - - @Test - public void testFormattedNumbersExcel4() throws IOException { - OldExcelExtractor extractor = createExtractor("testEXCEL_4.xls"); - String text = extractor.getText(); - - // Simple numbers - assertContains(text, "151"); - assertContains(text, "784"); - - // Numbers which come from formulas - assertContains(text, "0.398"); // TODO Rounding - assertContains(text, "624"); - - // Formatted numbers - // TODO -// assertContains(text, "55,624"); -// assertContains(text, "11,743,477"); - - extractor.close(); - } - - @Test - public void testFormattedNumbersExcel5() throws IOException { - for (String ver : new String[] {"5", "95"}) { - OldExcelExtractor extractor = createExtractor("testEXCEL_"+ver+".xls"); - String text = extractor.getText(); - - // Simple numbers - assertContains(text, "1"); - - // Numbers which come from formulas - assertContains(text, "13"); - assertContains(text, "169"); - - // Formatted numbers - // TODO -// assertContains(text, "100.00%"); -// assertContains(text, "155.00%"); -// assertContains(text, "1,125"); -// assertContains(text, "189,945"); -// assertContains(text, "1,234,500"); -// assertContains(text, "$169.00"); -// assertContains(text, "$1,253.82"); - - extractor.close(); - } - } - - @Test - public void testFromFile() throws IOException { - for (String ver : new String[] {"4", "5", "95"}) { - String filename = "testEXCEL_"+ver+".xls"; - File f = HSSFTestDataSamples.getSampleFile(filename); - - OldExcelExtractor extractor = new OldExcelExtractor(f); - String text = extractor.getText(); - assertNotNull(text); - assertTrue(text.length() > 100); - - extractor.close(); - } - } - - @Test(expected=OfficeXmlFileException.class) - public void testOpenInvalidFile1() throws IOException { - // a file that exists, but is a different format - createExtractor("WithVariousData.xlsx"); - } - - - @Test(expected=RecordFormatException.class) - public void testOpenInvalidFile2() throws IOException { - // a completely different type of file - createExtractor("48936-strings.txt"); - } - - @Test(expected=FileNotFoundException.class) - public void testOpenInvalidFile3() throws IOException { - // a POIFS file which is not a Workbook - InputStream is = POIDataSamples.getDocumentInstance().openResourceAsStream("47304.doc"); - try { - new OldExcelExtractor(is).close(); - } finally { - is.close(); - } - } - - @Test(expected=EmptyFileException.class) - public void testOpenNonExistingFile() throws IOException { - // a file that exists, but is a different format - OldExcelExtractor extractor = new OldExcelExtractor(new File("notexistingfile.xls")); - extractor.close(); - } - - @Test - public void testInputStream() throws IOException { - File file = HSSFTestDataSamples.getSampleFile("testEXCEL_3.xls"); - InputStream stream = new FileInputStream(file); - try { - OldExcelExtractor extractor = new OldExcelExtractor(stream); - String text = extractor.getText(); - assertNotNull(text); - extractor.close(); - } finally { - stream.close(); - } - } - - @Test - public void testInputStreamNPOIHeader() throws IOException { - File file = HSSFTestDataSamples.getSampleFile("FormulaRefs.xls"); - InputStream stream = new FileInputStream(file); - try { - OldExcelExtractor extractor = new OldExcelExtractor(stream); - extractor.close(); - } finally { - stream.close(); - } - } - - @Test - public void testNPOIFSFileSystem() throws IOException { - File file = HSSFTestDataSamples.getSampleFile("FormulaRefs.xls"); - NPOIFSFileSystem fs = new NPOIFSFileSystem(file); - try { - OldExcelExtractor extractor = new OldExcelExtractor(fs); - extractor.close(); - } finally { - fs.close(); - } - } - - @Test - public void testDirectoryNode() throws IOException { - File file = HSSFTestDataSamples.getSampleFile("FormulaRefs.xls"); - NPOIFSFileSystem fs = new NPOIFSFileSystem(file); - try { - OldExcelExtractor extractor = new OldExcelExtractor(fs.getRoot()); - extractor.close(); - } finally { - fs.close(); - } - } - - @Test - public void testDirectoryNodeInvalidFile() throws IOException { - File file = POIDataSamples.getDocumentInstance().getFile("test.doc"); - NPOIFSFileSystem fs = new NPOIFSFileSystem(file); - try { - OldExcelExtractor extractor = new OldExcelExtractor(fs.getRoot()); - extractor.close(); - fail("Should catch exception here"); - } catch (FileNotFoundException e) { - // expected here - } finally { - fs.close(); - } - } - - @Ignore("Calls System.exit()") - @Test - public void testMainUsage() throws IOException { - PrintStream save = System.err; - try { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - try { - PrintStream str = new PrintStream(out, false, "UTF-8"); - System.setErr(str); - OldExcelExtractor.main(new String[] {}); - } finally { - out.close(); - } - } finally { - System.setErr(save); - } - } - - @Test - public void testMain() throws IOException { - File file = HSSFTestDataSamples.getSampleFile("testEXCEL_3.xls"); - PrintStream save = System.out; - try { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - try { - PrintStream str = new PrintStream(out, false, "UTF-8"); - System.setOut(str); - OldExcelExtractor.main(new String[] {file.getAbsolutePath()}); - } finally { - out.close(); - } - String string = new String(out.toByteArray(), "UTF-8"); - assertTrue("Had: " + string, - string.contains("Table C-13--Lemons")); - } finally { - System.setOut(save); - } - } - - @Test - public void testEncryptionException() throws IOException { - //test file derives from Common Crawl - File file = HSSFTestDataSamples.getSampleFile("60284.xls"); - OldExcelExtractor ex = new OldExcelExtractor(file); - assertEquals(5, ex.getBiffVersion()); - assertEquals(5, ex.getFileType()); - try { - ex.getText(); - fail(); - } catch (EncryptedDocumentException e) { - assertTrue("correct exception thrown", true); - } - ex.close(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/model/AllModelTests.java b/src/testcases/org/apache/poi/hssf/model/AllModelTests.java deleted file mode 100644 index bca29c74f..000000000 --- a/src/testcases/org/apache/poi/hssf/model/AllModelTests.java +++ /dev/null @@ -1,42 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.model; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -/** - * Collects all tests for org.apache.poi.hssf.model. - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestDrawingManager.class, - TestDrawingManager2.class, - //TestFormulaParser.class, //converted to junit4 - TestFormulaParserEval.class, - TestFormulaParserIf.class, - TestLinkTable.class, - TestOperandClassTransformer.class, - TestRowBlocksReader.class, - TestRVA.class, - TestSheet.class, - TestSheetAdditional.class, - TestWorkbook.class -}) -public final class AllModelTests { -} diff --git a/src/testcases/org/apache/poi/hssf/model/TestDrawingAggregate.java b/src/testcases/org/apache/poi/hssf/model/TestDrawingAggregate.java deleted file mode 100644 index ddeacd6fb..000000000 --- a/src/testcases/org/apache/poi/hssf/model/TestDrawingAggregate.java +++ /dev/null @@ -1,946 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hssf.model; - -import static org.apache.poi.poifs.storage.RawDataUtil.decompress; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FilenameFilter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.poi.ddf.DefaultEscherRecordFactory; -import org.apache.poi.ddf.EscherContainerRecord; -import org.apache.poi.ddf.EscherDggRecord; -import org.apache.poi.ddf.EscherRecord; -import org.apache.poi.ddf.EscherRecordFactory; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.record.ContinueRecord; -import org.apache.poi.hssf.record.DrawingRecord; -import org.apache.poi.hssf.record.EOFRecord; -import org.apache.poi.hssf.record.EscherAggregate; -import org.apache.poi.hssf.record.NoteRecord; -import org.apache.poi.hssf.record.ObjRecord; -import org.apache.poi.hssf.record.Record; -import org.apache.poi.hssf.record.RecordBase; -import org.apache.poi.hssf.record.RecordFactory; -import org.apache.poi.hssf.record.TextObjectRecord; -import org.apache.poi.hssf.record.WindowTwoRecord; -import org.apache.poi.hssf.record.aggregates.RowRecordsAggregate; -import org.apache.poi.hssf.usermodel.HSSFPatriarch; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFTestHelper; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.util.HexDump; -import org.junit.Test; - -public class TestDrawingAggregate { - /** - * information about drawing aggregate in a worksheet - */ - private static class DrawingAggregateInfo { - /** - * start and end indices of the aggregate in the worksheet stream - */ - private int startRecordIndex, endRecordIndex; - /** - * the records being aggregated - */ - private List aggRecords; - - /** - * @return aggregate info or null if the sheet does not contain drawing objects - */ - static DrawingAggregateInfo get(HSSFSheet sheet){ - DrawingAggregateInfo info = null; - InternalSheet isheet = HSSFTestHelper.getSheetForTest(sheet); - List records = isheet.getRecords(); - for(int i = 0; i < records.size(); i++){ - RecordBase rb = records.get(i); - if((rb instanceof DrawingRecord) && info == null) { - info = new DrawingAggregateInfo(); - info.startRecordIndex = i; - info.endRecordIndex = i; - } else if (info != null && ( - rb instanceof DrawingRecord - || rb instanceof ObjRecord - || rb instanceof TextObjectRecord - || rb instanceof ContinueRecord - || rb instanceof NoteRecord - )){ - info.endRecordIndex = i; - } else { - if(rb instanceof EscherAggregate) - throw new IllegalStateException("Drawing data already aggregated. " + - "You should cal this method before the first invocation of HSSFSheet#getDrawingPatriarch()"); - if (info != null) break; - } - } - if(info != null){ - info.aggRecords = new ArrayList( - records.subList(info.startRecordIndex, info.endRecordIndex + 1)); - } - return info; - } - - /** - * @return the raw data being aggregated - */ - byte[] getRawBytes(){ - ByteArrayOutputStream out = new ByteArrayOutputStream(); - for (RecordBase rb : aggRecords) { - Record r = (Record) rb; - try { - out.write(r.serialize()); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - return out.toByteArray(); - } - } - - /** - * iterate over all sheets, aggregate drawing records (if there are any) - * and remember information about the aggregated data. - * Then serialize the workbook, read back and assert that the aggregated data is preserved. - * - * The assertion is strict meaning that the drawing data before and after save must be equal. - */ - private static void assertWriteAndReadBack(HSSFWorkbook wb) throws IOException { - // map aggregate info by sheet index - Map aggs = new HashMap(); - for(int i = 0; i < wb.getNumberOfSheets(); i++){ - HSSFSheet sheet = wb.getSheetAt(i); - DrawingAggregateInfo info = DrawingAggregateInfo.get(sheet); - if(info != null) { - aggs.put(i, info); - HSSFPatriarch p = sheet.getDrawingPatriarch(); - - // compare aggregate.serialize() with raw bytes from the record stream - EscherAggregate agg = HSSFTestHelper.getEscherAggregate(p); - - byte[] dgBytes1 = info.getRawBytes(); - byte[] dgBytes2 = agg.serialize(); - - assertEquals("different size of raw data ande aggregate.serialize()", dgBytes1.length, dgBytes2.length); - assertTrue("raw drawing data ("+dgBytes1.length+" bytes) and aggregate.serialize() are different.", - Arrays.equals(dgBytes1, dgBytes2)); - } - } - - if(aggs.size() != 0){ - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb); - for(int i = 0; i < wb2.getNumberOfSheets(); i++){ - DrawingAggregateInfo info1 = aggs.get(i); - if(info1 != null) { - HSSFSheet sheet2 = wb2.getSheetAt(i); - DrawingAggregateInfo info2 = DrawingAggregateInfo.get(sheet2); - byte[] dgBytes1 = info1.getRawBytes(); - byte[] dgBytes2 = info2.getRawBytes(); - assertEquals("different size of drawing data before and after save", dgBytes1.length, dgBytes2.length); - assertTrue("drawing data ("+dgBytes1.length+" bytes) before and after save is different.", - Arrays.equals(dgBytes1, dgBytes2)); - } - } - wb2.close(); - } - } - - /** - * test that we correctly read and write drawing aggregates - * in all .xls files in POI test samples - */ - @Test - public void testAllTestSamples() throws IOException { - File[] xls = new File(System.getProperty("POI.testdata.path"), "spreadsheet").listFiles( - new FilenameFilter() { - @Override - public boolean accept(File dir, String name) { - return name.endsWith(".xls"); - } - } - ); - assertNotNull( - "Need to find files in test-data path, had path: " + new File(System.getProperty("POI.testdata.path"), "spreadsheet"), - xls); - for(File file : xls) { - HSSFWorkbook wb; - try { - wb = HSSFTestDataSamples.openSampleWorkbook(file.getName()); - } catch (Throwable e){ - // don't bother about files we cannot read - they are different bugs - // System.out.println("[WARN] Cannot read " + file.getName()); - continue; - } - try { - assertWriteAndReadBack(wb); - } catch (Exception e) { - String filename = file.getName(); - System.out.println("Drawing Aggregate re-write test failed for " + filename); - e.printStackTrace(System.out); - - fail("Error when writing and re-reading workbook " + filename + "\n" + e); - } - wb.close(); - } - } - - /** - * when reading incomplete data ensure that the serialized bytes match the source - */ - @Test - public void testIncompleteData() throws IOException { - //EscherDgContainer and EscherSpgrContainer length exceeds the actual length of the data - String data = - "H4sIAAAAAAAAAGWOOw7CQAxE32YTsSRIWSgQJSUloqSm5g4ICURBg+iBK3APGi6wBWeh9xGYbEps2WON"+ - "P+OWwpYeIsECMFC8S2jxNvMdlrYQ5xha5N8K6ryHdir6+avwOer5l3hq2NPYWuWN0n1dIsgfbgshuSj1"+ - "+2eqbvLdxQ0ndhy5KJ/lc1ZZK9okY5X/gSbrHZTH1vE/ozagTcwAAAA="; - byte[] dgBytes = decompress(data); - - List records = new ArrayList(); - EscherRecordFactory recordFactory = new DefaultEscherRecordFactory(); - int pos = 0; - while (pos < dgBytes.length) { - EscherRecord r = recordFactory.createRecord(dgBytes, pos); - int bytesRead = r.fillFields(dgBytes, pos, recordFactory); - records.add(r); - pos += bytesRead; - } - assertEquals("data was not fully read", dgBytes.length, pos); - - // serialize to byte array - ByteArrayOutputStream out = new ByteArrayOutputStream(); - for(EscherRecord r : records) { - out.write(r.serialize()); - } - assertEquals(HexDump.toHex(dgBytes, 10), HexDump.toHex(out.toByteArray(), 10)); - } - - /** - * TODO: figure out why it fails with "RecordFormatException: 0 bytes written but getRecordSize() reports 80" - */ - @Test - public void testFailing() throws IOException { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("15573.xls"); - HSSFSheet sh = wb.getSheetAt(0); - sh.getDrawingPatriarch(); - - HSSFTestDataSamples.writeOutAndReadBack(wb).close(); - wb.close(); - } - - private static byte[] toByteArray(List records) { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - for (RecordBase rb : records) { - Record r = (Record) rb; - try { - out.write(r.serialize()); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - return out.toByteArray(); - } - - @Test - public void testSolverContainerMustBeSavedDuringSerialization() throws IOException{ - HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("SolverContainerAfterSPGR.xls"); - HSSFSheet sh = wb1.getSheetAt(0); - InternalSheet ish = HSSFTestHelper.getSheetForTest(sh); - List records = ish.getRecords(); - // records to be aggregated - List dgRecords = records.subList(19, 22); - byte[] dgBytes = toByteArray(dgRecords); - sh.getDrawingPatriarch(); - EscherAggregate agg = (EscherAggregate) ish.findFirstRecordBySid(EscherAggregate.sid); - assertEquals(agg.getEscherRecords().get(0).getChildRecords().size(), 3); - assertEquals(agg.getEscherRecords().get(0).getChild(2).getRecordId(), EscherContainerRecord.SOLVER_CONTAINER); - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sh = wb2.getSheetAt(0); - sh.getDrawingPatriarch(); - ish = HSSFTestHelper.getSheetForTest(sh); - agg = (EscherAggregate) ish.findFirstRecordBySid(EscherAggregate.sid); - assertEquals(agg.getEscherRecords().get(0).getChildRecords().size(), 3); - assertEquals(agg.getEscherRecords().get(0).getChild(2).getRecordId(), EscherContainerRecord.SOLVER_CONTAINER); - - - // collect drawing records into a byte buffer. - agg = (EscherAggregate) ish.findFirstRecordBySid(EscherAggregate.sid); - byte[] dgBytesAfterSave = agg.serialize(); - assertEquals("different size of drawing data before and after save", dgBytes.length, dgBytesAfterSave.length); - assertTrue("drawing data before and after save is different", Arrays.equals(dgBytes, dgBytesAfterSave)); - wb2.close(); - } - - @Test - public void testFileWithTextbox() throws IOException{ - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("text.xls"); - HSSFSheet sh = wb.getSheetAt(0); - InternalSheet ish = HSSFTestHelper.getSheetForTest(sh); - List records = ish.getRecords(); - // records to be aggregated - List dgRecords = records.subList(19, 23); - byte[] dgBytes = toByteArray(dgRecords); - sh.getDrawingPatriarch(); - - // collect drawing records into a byte buffer. - EscherAggregate agg = (EscherAggregate) ish.findFirstRecordBySid(EscherAggregate.sid); - byte[] dgBytesAfterSave = agg.serialize(); - assertEquals("different size of drawing data before and after save", dgBytes.length, dgBytesAfterSave.length); - assertTrue("drawing data before and after save is different", Arrays.equals(dgBytes, dgBytesAfterSave)); - wb.close(); - } - - @Test - public void testFileWithCharts() throws IOException { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("49581.xls"); - HSSFSheet sh = wb.getSheetAt(0); - InternalSheet ish = HSSFTestHelper.getSheetForTest(sh); - List records = ish.getRecords(); - // records to be aggregated - List dgRecords = records.subList(19, 21); - byte[] dgBytes = toByteArray(dgRecords); - sh.getDrawingPatriarch(); - - // collect drawing records into a byte buffer. - EscherAggregate agg = (EscherAggregate) ish.findFirstRecordBySid(EscherAggregate.sid); - byte[] dgBytesAfterSave = agg.serialize(); - assertEquals("different size of drawing data before and after save", dgBytes.length, dgBytesAfterSave.length); - for (int i=0; i< dgBytes.length; i++){ - if (dgBytes[i] != dgBytesAfterSave[i]){ - System.out.println("pos = " + i); - } - } - assertTrue("drawing data before and after save is different", Arrays.equals(dgBytes, dgBytesAfterSave)); - wb.close(); - } - - /** - * test reading drawing aggregate from a test file from Bugzilla 45129 - */ - @Test - public void test45129() throws IOException { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("45129.xls"); - HSSFSheet sh = wb.getSheetAt(0); - - InternalWorkbook iworkbook = HSSFTestHelper.getWorkbookForTest(wb); - InternalSheet isheet = HSSFTestHelper.getSheetForTest(sh); - - List records = isheet.getRecords(); - - // the sheet's drawing is not aggregated - assertEquals("wrong size of sheet records stream", 394, records.size()); - // the last record before the drawing block - assertTrue( - "records.get(18) is expected to be RowRecordsAggregate but was " + records.get(18).getClass().getSimpleName(), - records.get(18) instanceof RowRecordsAggregate); - - // records to be aggregated - List dgRecords = records.subList(19, 389); - // collect drawing records into a byte buffer. - byte[] dgBytes = toByteArray(dgRecords); - - for (RecordBase rb : dgRecords) { - Record r = (Record) rb; - short sid = r.getSid(); - // we expect that drawing block consists of either - // DrawingRecord or ContinueRecord or ObjRecord or TextObjectRecord - assertTrue( - sid == DrawingRecord.sid || - sid == ContinueRecord.sid || - sid == ObjRecord.sid || - sid == TextObjectRecord.sid); - } - - // the first record after the drawing block - assertTrue( - "records.get(389) is expected to be Window2", - records.get(389) instanceof WindowTwoRecord); - - // aggregate drawing records. - // The subrange [19, 388] is expected to be replaced with a EscherAggregate object - DrawingManager2 drawingManager = iworkbook.findDrawingGroup(); - int loc = isheet.aggregateDrawingRecords(drawingManager, false); - EscherAggregate agg = (EscherAggregate) records.get(loc); - - assertEquals("wrong size of the aggregated sheet records stream", 25, records.size()); - assertTrue( - "records.get(18) is expected to be RowRecordsAggregate but was " + records.get(18).getClass().getSimpleName(), - records.get(18) instanceof RowRecordsAggregate); - assertTrue("records.get(19) is expected to be EscherAggregate but was " + records.get(19).getClass().getSimpleName(), - records.get(19) instanceof EscherAggregate); - assertTrue("records.get(20) is expected to be Window2 but was " + records.get(20).getClass().getSimpleName(), - records.get(20) instanceof WindowTwoRecord); - - byte[] dgBytesAfterSave = agg.serialize(); - assertEquals("different size of drawing data before and after save", dgBytes.length, dgBytesAfterSave.length); - assertTrue("drawing data before and after save is different", Arrays.equals(dgBytes, dgBytesAfterSave)); - wb.close(); - } - - /** - * Try to check file with such record sequence - * ... - * DrawingRecord - * ContinueRecord - * ObjRecord | TextObjRecord - * ... - */ - @Test - public void testSerializeDrawingBigger8k() throws IOException { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("DrawingContinue.xls"); - InternalWorkbook iworkbook = HSSFTestHelper.getWorkbookForTest(wb); - HSSFSheet sh = wb.getSheetAt(0); - InternalSheet isheet = HSSFTestHelper.getSheetForTest(sh); - - - List records = isheet.getRecords(); - - // the sheet's drawing is not aggregated - assertEquals("wrong size of sheet records stream", 32, records.size()); - // the last record before the drawing block - assertTrue( - "records.get(18) is expected to be RowRecordsAggregate but was " + records.get(18).getClass().getSimpleName(), - records.get(18) instanceof RowRecordsAggregate); - - // records to be aggregated - List dgRecords = records.subList(19, 26); - for (RecordBase rb : dgRecords) { - Record r = (Record) rb; - short sid = r.getSid(); - // we expect that drawing block consists of either - // DrawingRecord or ContinueRecord or ObjRecord or TextObjectRecord - assertTrue( - sid == DrawingRecord.sid || - sid == ContinueRecord.sid || - sid == ObjRecord.sid || - sid == NoteRecord.sid || - sid == TextObjectRecord.sid); - } - // collect drawing records into a byte buffer. - byte[] dgBytes = toByteArray(dgRecords); - - // the first record after the drawing block - assertTrue( - "records.get(26) is expected to be Window2", - records.get(26) instanceof WindowTwoRecord); - - // aggregate drawing records. - // The subrange [19, 38] is expected to be replaced with a EscherAggregate object - DrawingManager2 drawingManager = iworkbook.findDrawingGroup(); - int loc = isheet.aggregateDrawingRecords(drawingManager, false); - EscherAggregate agg = (EscherAggregate) records.get(loc); - - assertEquals("wrong size of the aggregated sheet records stream", 26, records.size()); - assertTrue( - "records.get(18) is expected to be RowRecordsAggregate but was " + records.get(18).getClass().getSimpleName(), - records.get(18) instanceof RowRecordsAggregate); - assertTrue("records.get(19) is expected to be EscherAggregate but was " + records.get(19).getClass().getSimpleName(), - records.get(19) instanceof EscherAggregate); - assertTrue("records.get(20) is expected to be Window2 but was " + records.get(20).getClass().getSimpleName(), - records.get(20) instanceof WindowTwoRecord); - - byte[] dgBytesAfterSave = agg.serialize(); - assertEquals("different size of drawing data before and after save", dgBytes.length, dgBytesAfterSave.length); - assertTrue("drawing data before and after save is different", Arrays.equals(dgBytes, dgBytesAfterSave)); - wb.close(); - } - - - @Test - public void testSerializeDrawingBigger8k_noAggregation() throws IOException { - HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("DrawingContinue.xls"); - - InternalSheet isheet = HSSFTestHelper.getSheetForTest(wb1.getSheetAt(0)); - List records = isheet.getRecords(); - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - InternalSheet isheet2 = HSSFTestHelper.getSheetForTest(wb2.getSheetAt(0)); - List records2 = isheet2.getRecords(); - - assertEquals(records.size(), records2.size()); - for (int i = 0; i < records.size(); i++) { - RecordBase r1 = records.get(i); - RecordBase r2 = records2.get(i); - assertTrue(r1.getClass() == r2.getClass()); - assertEquals(r1.getRecordSize(), r2.getRecordSize()); - if (r1 instanceof Record) { - assertEquals(((Record) r1).getSid(), ((Record) r2).getSid()); - assertArrayEquals(((Record) r1).serialize(), ((Record) r2).serialize()); - } - } - wb2.close(); - } - - @Test - public void testSerializeDrawingWithComments() throws IOException { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("DrawingAndComments.xls"); - HSSFSheet sh = wb.getSheetAt(0); - InternalWorkbook iworkbook = HSSFTestHelper.getWorkbookForTest(wb); - InternalSheet isheet = HSSFTestHelper.getSheetForTest(sh); - - List records = isheet.getRecords(); - - // the sheet's drawing is not aggregated - assertEquals("wrong size of sheet records stream", 46, records.size()); - // the last record before the drawing block - assertTrue( - "records.get(18) is expected to be RowRecordsAggregate but was " + records.get(18).getClass().getSimpleName(), - records.get(18) instanceof RowRecordsAggregate); - - // records to be aggregated - List dgRecords = records.subList(19, 39); - for (RecordBase rb : dgRecords) { - Record r = (Record) rb; - short sid = r.getSid(); - // we expect that drawing block consists of either - // DrawingRecord or ContinueRecord or ObjRecord or TextObjectRecord - assertTrue( - sid == DrawingRecord.sid || - sid == ContinueRecord.sid || - sid == ObjRecord.sid || - sid == NoteRecord.sid || - sid == TextObjectRecord.sid); - } - // collect drawing records into a byte buffer. - byte[] dgBytes = toByteArray(dgRecords); - - // the first record after the drawing block - assertTrue( - "records.get(39) is expected to be Window2", - records.get(39) instanceof WindowTwoRecord); - - // aggregate drawing records. - // The subrange [19, 38] is expected to be replaced with a EscherAggregate object - DrawingManager2 drawingManager = iworkbook.findDrawingGroup(); - int loc = isheet.aggregateDrawingRecords(drawingManager, false); - EscherAggregate agg = (EscherAggregate) records.get(loc); - - assertEquals("wrong size of the aggregated sheet records stream", 27, records.size()); - assertTrue( - "records.get(18) is expected to be RowRecordsAggregate but was " + records.get(18).getClass().getSimpleName(), - records.get(18) instanceof RowRecordsAggregate); - assertTrue("records.get(19) is expected to be EscherAggregate but was " + records.get(19).getClass().getSimpleName(), - records.get(19) instanceof EscherAggregate); - assertTrue("records.get(20) is expected to be Window2 but was " + records.get(20).getClass().getSimpleName(), - records.get(20) instanceof WindowTwoRecord); - - byte[] dgBytesAfterSave = agg.serialize(); - assertEquals("different size of drawing data before and after save", dgBytes.length, dgBytesAfterSave.length); - assertTrue("drawing data before and after save is different", Arrays.equals(dgBytes, dgBytesAfterSave)); - wb.close(); - } - - - @Test - public void testFileWithPictures() throws IOException { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("ContinueRecordProblem.xls"); - HSSFSheet sh = wb.getSheetAt(0); - - InternalWorkbook iworkbook = HSSFTestHelper.getWorkbookForTest(wb); - InternalSheet isheet = HSSFTestHelper.getSheetForTest(sh); - - List records = isheet.getRecords(); - - // the sheet's drawing is not aggregated - assertEquals("wrong size of sheet records stream", 315, records.size()); - // the last record before the drawing block - assertTrue( - "records.get(21) is expected to be RowRecordsAggregate but was " + records.get(21).getClass().getSimpleName(), - records.get(21) instanceof RowRecordsAggregate); - - // records to be aggregated - List dgRecords = records.subList(22, 300); - for (RecordBase rb : dgRecords) { - Record r = (Record) rb; - short sid = r.getSid(); - // we expect that drawing block consists of either - // DrawingRecord or ContinueRecord or ObjRecord or TextObjectRecord - assertTrue( - sid == DrawingRecord.sid || - sid == ContinueRecord.sid || - sid == ObjRecord.sid || - sid == TextObjectRecord.sid); - } - // collect drawing records into a byte buffer. - byte[] dgBytes = toByteArray(dgRecords); - - // the first record after the drawing block - assertTrue( - "records.get(300) is expected to be Window2", - records.get(300) instanceof WindowTwoRecord); - - // aggregate drawing records. - // The subrange [19, 299] is expected to be replaced with a EscherAggregate object - DrawingManager2 drawingManager = iworkbook.findDrawingGroup(); - int loc = isheet.aggregateDrawingRecords(drawingManager, false); - EscherAggregate agg = (EscherAggregate) records.get(loc); - - assertEquals("wrong size of the aggregated sheet records stream", 38, records.size()); - assertTrue( - "records.get(21) is expected to be RowRecordsAggregate but was " + records.get(21).getClass().getSimpleName(), - records.get(21) instanceof RowRecordsAggregate); - assertTrue("records.get(22) is expected to be EscherAggregate but was " + records.get(22).getClass().getSimpleName(), - records.get(22) instanceof EscherAggregate); - assertTrue("records.get(23) is expected to be Window2 but was " + records.get(23).getClass().getSimpleName(), - records.get(23) instanceof WindowTwoRecord); - - byte[] dgBytesAfterSave = agg.serialize(); - assertEquals("different size of drawing data before and after save", dgBytes.length, dgBytesAfterSave.length); - assertTrue("drawing data before and after save is different", Arrays.equals(dgBytes, dgBytesAfterSave)); - wb.close(); - } - - @Test - public void testUnhandledContinue() throws IOException { - String data = - "H4sIAAAAAAAAAO3adVRU2/4A8EPHAEOnlEooNaSUdCNIg4CUDCEtQ6gwlITSjYiSkoKA0ikg0i1IyCjS"+ - "QwpSEr8B73v3PS6+9+67vz/eH+615pyz9tn71PqevT/rfGcJOIcLBtDXrNgAgBjAXcMFAAAb9SPDBAAw"+ - "gLGmzna8xlxjR9WhAXhrxMAfCzqAf9IPQPXBAn6078IBgAyCH/VgVD2ADwCxAGhNBbXpc9LUF2h8n4we"+ - "iOoNAKEnywaAFmAEGtDQABLgCA0AcAHfZvLjeozjc+gAUMATgAEygBNqzQTwHl8lcH5dGHWmvGY+1FJD"+ - "FQOTHHX1x+dkBta2H9UcoLam0I7bAYCRrJMjDOoIM9W56wx1vcnt6WAfF92t0gIhfrfqv0o8e9khH4fE"+ - "thqnQJHiJqOZUrbDByG8xwYeiEmYJPcUPoP17NH6hTz9cVtyfvnyyUuV3BzE06+vDH/Dlxi+/pYeV32e"+ - "IGIy2p+e90VyZ+i9OlDL+Rp6Dmot/G2tUgYbGW5vpkSep5Fk2eKtJthDdEvKkzrvC4cmWe7kKaliC7ip"+ - "0sMjlMUdN/akSG0ticE4nweeA7LUha1xyjNLXZEJUx80rOZMmgMIveJ5pQ7Hio17qM558+zaZgheNOHN"+ - "tk7hCxKIZgFTs9t1NGhTdj0EIdz0tEcV4KZebLmun1t9qpQ2fF6N29/P3I3j3pYc8kI9zaMjjFNPi/ej"+ - "qfkAaisS9bRAqLXpHai9Kw/38TIr6s3tZghB0GpAXUB/ncuYLE2mulOgiSpODb6R8rVbnQasDoj6bIiB"+ - "gpPYItWexPrqVgUk73GpZwT2sBroUQZ07ovZJ6SXgbdvjH//55ZoggllM0Rdw7K6gHmeIt/exXytDGpq"+ - "VeVUw1D6S2kCKezDar0iZnm3GGAy99/4bWY7VIgeWUlVmOVn8kdFOmIsel1/vx9MX9vNOZHYeqdvYnuy"+ - "PuP2uxHPjCotCFiHoJKzFzI4MTQn1bBVdLQQT0LmrX8os3+t4Nu7F1SC7mDgrFsvKsHS80DFHx3O8SsA"+ - "AJZ3XHlcbcydoagIOY6SWl1Vp3EIQT34gw8x7PqBwdNgkpp5LViiOWHMLE5uaQp1LIusFllOAzxrOusm"+ - "WExAlgdfVmW/LRLc67SnF1MHKe/PT2vXvfZQw1g/fIwStuEpmaxlQa9NEWv40J8h8PmVmRGejXo+EW2v"+ - "HEI0qo7ZNPb5niruyPOdHhnQLRUPGb+y4Wwo0WGygw6NOzBXGDYgzKBYzu+v6872oAZEaXgP4VtOrDV5"+ - "LyQtP9wxoKWMM/buA960eUbfNY0RKG1vKafEuMZMtwJjh5N0+JRy8JYlbS/r6OhsqifipW+Gx4NtrO4B"+ - "znA/UjinjWh9TytvuD/PeHSCSyZI5WEAslSzQZpIoczUQ5XM8tCuQSArrxGN5VGZ1OKFiaOi+zEpKW/o"+ - "vaSMwbfZQYveck70N1ZjZrwdxtKxlzAobG5kMl1LQFazAkJqVsrYDgCNeunmvRhm4c6jbinypsbQpyUr"+ - "wX1UwXJ9mtLhn3qC321JFsoymDATqy98V+hQ3ZBcpxN+W1+6wo6FrlRGKhW2ug7eAH3Dvn0rNWTG6vvr"+ - "qKDGWqAXYu0s8ZmmdMM3xFjWIjXsqtT56ly7tMPY9d40CZ/CQ0b4OLsD9qG5CB5n47N2/2qJMKo1+rUg"+ - "TTpa4D7au2JRC6XrayDXu7ZXGpvcwM5DWoz4HdBBTfQnmzN1K2YG+hpYNVGkX6ZlZGv7OM1XZeaZU1e2"+ - "Rt+QEzSTyLSYPXezW5pSbf62gbi5iHWB7xBAZ2leDdXI7Kat5+Epnor5sC3ZefMh0hUTSQ8VP+BIz2fh"+ - "t3eD2z9TLOhGRLoIErwXi+9yUgMZHhVGhWusRIi4J297mNL4iBUbHaKdFaRyobYMnKg9BWjH4+uPILV0"+ - "8nC8A3U/jlFjjX71Jgi595V1xmS7qScwAiEcrTYLmRbMfuaHL6EOo1NjPeWNa8hlBYLWd64rInOTrmyv"+ - "FPTmG8O5ys73rWL5VnYIcryPaJz1hicCpRGXFTgKhf3IKiBPTEzV5pMWMjt2zJfd24LZxbIx8ecWeVuF"+ - "eCqzynPsivav2VzI2+hbgvBvzjdDA5uZQkqynn+lwzfceOc/l4qsu1hsOTVzy6AnNW9HhaqZ8yHRS87z"+ - "01vZyoyAyGRlaOVkgW6lsSNCaOFlWqgRBJ2ZaR02lhwDHRJ1xN2B1xc64WubpudpxVONMUW7GMG/w61N"+ - "qLmi+xXRMaSqigzr33Iwc3owsLyZl1hUaNChDstgByZaRb2FUik+0vh0uZw72thqliZVKKQydVxsnHk3"+ - "yPj3tx8NnQv4+UTxz+WMaeP0AU6Pnb8XbrR/GklPdzw98vxeLqH/cRw63ft0SPxeejD/ECAaqljYP6Zo"+ - "TOAbas2G/aMp8RrpyQyOBpihYQAbqK0+1BxuiKojWTvefxM1J1MApKiTggESs9MPZ+nkUghPWpajkQKk"+ - "6H/bg/3bDYkDqHuDQT1hXLziJ1WUv+3+2wE6cY650PkPXCD+CRcAqPZf4ALfb1y4csIF3l9c+MWF/44L"+ - "j9ungt3+JRe6HacgxPUvhzyKvXJ2F/yZmvIM81egZfIaDI0XieSQH6KXZeYHV8Oe9jmC77MXmJyzbuVH"+ - "7Dxh7HWqUYgJgJQPP+qfFs2Wy5VJLBvjrb4LP6d2qSSiIEa1EDOTzXzBAf7NYTKe9Uv+BzvZxsBSGlzq"+ - "j2IjVpqWoXU2lXXDhRppha9tKwNMX4WqNEd+qo3WpH0X21ausDawEugMlpZ1XaXro5TpEAOTyMX3q32g"+ - "MJxtF2+idkYSmm3o6N6l7W39svNCNlqfzruLTTpsXDpob1SYnlNqhqsWeUW8X0QLFtb0RgBb4RFZ5sL0"+ - "d0/SQfbKUi5bT3OBzDhhYW67b3Rb0nlESHfbpvodNwNarcSwSY0MT4wUiebd+x+jYc7Y1n2+lUQtURRx"+ - "30MmxUonWXqrOwS88XfYSPvWDKWTxAd15QH75K4YXh20CYiyU3YjQcbGEoJcjplI/AMtEo7r7XINk573"+ - "ttxnL6/9tUHRi1OE6J/j4C+e18b5+n2Sujwc78Z2iVgqPx6w8gr3STZTEnam+x76oWmpHGSLuwkiJvTG"+ - "RlKOOIuBQ9oojJdCS+4ryVHpYg358B7SDCFMC46CEUMqT575UKujkzl/itEcCTxEr8cwQdh5o5lxmTEm"+ - "sBHYgkxtulQL0LCL7vs/j9lrs2FGJpAmZb1khCo2GylQdMmohMWCCNdlSh5UgdKDv7/24CGqTnOKID6P"+ - "zVFodIvClLZo9WhLi4c6eh1EzC5SzyMTLmTnaWpiPnzRRdLGOGLDNc4iUwyxMqmSe6ed0PRpeHenTdnu"+ - "OLWibGodMxRubxi1VyEzLFOFs7LTt8poQuMjWvzk6Ews6D2wxOX6F1iIMr2OwsJbhNo+Ubfgulo5Ravk"+ - "JUteZgv/qaiWkdJy++ryV4WQnU13JuY9z566hsH7oslDpXJGjvbpFH65FOhTlwdfaNChF1Qs3GSMctPh"+ - "Nbz9Fm+pKrB9Z++2XPC1VZ2OCtUKaQm5UWaWKDF9woBGK5HEoXLY2/hUPIeLbibJao0EH3edb2ALE9T4"+ - "ZQV+5Zl+PQUW6ZVIRMQ0pjyc21bn9c6Y4njsNgCvvVmcFDX+RLQKZ9pzmbtT97CkcWN3zy0+hSrChV8h"+ - "jVBJfGUk2+xSWQQden2qE/JJ0wf93E45aJWQUtYEJQ5idRqUycJ3TzENxD4I/XJlTx63k95POuxW6jSb"+ - "NU5wwAcj6djFzYfLB6U7YLpvGT2Swk3LEhF0wpUTMPJESYaj/zktnB54/pwWTsfE76Xr32uB9QwtYKOm"+ - "5GMt4ACzZ2iB+C9qge8/1QLJz7TQ/1e0wP9LC7+08P+hBWVCae5j4tP+VAtqruNMxHUe2Ud+n1fmLyTQ"+ - "2YXx5fEvPB/0XNrBMcMbTT7fB5TM7O+t+C9liWwSe9yRtqHauspQ07lU7sQyCrpFV0itVmSh8uCy2/tc"+ - "rkxkTnA/Icuwi65LXrzZJjtnHVc9/PG3+Paqyx5jxLjp9kTYCh49bnfJR++wGTq+hLGRe9o5GK58GrHP"+ - "7FjDwHSCxrWuXyx9SlJbKsY84b3W1/QO+3VV1NceWUxtBxid1fMEeb7QKAz1A+wk8WG36NZBztBeCYG7"+ - "Ff3BFrRdwldH+yS7B5aW1um8pvWF+8W0tsKaqgWwpTsuZC5YpqhZ0AYqlV/g4gm3iiPF6YRmwpvFhd/D"+ - "33NdS0ps2ALJJj/q52V5VMG0QPbiqOj+HW98bDtnDJerSZ+1+lZo6ggtvZWebZfZBtN9YuxrmAlHTxYf"+ - "cVMDllgfs9JcREuB7CZEfBGQhT07MvJnX2sM/PFxwfU8dYjmBZW53fWD60iNEH3cB9p76dFftdDU0XE0"+ - "eQtfiKn4AVpcWOxftPeb0ZsDA8pLJEO4ut35E4Okqnz7NKwgjs4EOccfF5rfSNDc95WDaY4wHbB9SZU+"+ - "2C3b89lxyHxNsxk8eXENfcuYb3FPwzTNo5HutoMS0IX1onkxJE5oLbCpVoAuDVGtSH07DxyWULrA7qew"+ - "93XSHVJ7S0eaI6tFWGSkkSqG5fXNNIaewY9XxXL904XR5S+itGBOaaoyMuLjYUtuabkPoKtE9IZqZH7D"+ - "f5ZINS+ovLSROlfUeChS3SrjUT9xwJ2ej3XF6+6k/TPFzm+IJyWCBBUe1XwIIS6DA21muvSJqx77Oqur"+ - "DDQNorlG+2d64a68eyEHak/+z7ygeeyFQJQXwMdeEGV970demkTM+/g3L7g4WBuZ7yC5LjyY/yKyDZ/b"+ - "gok76IaXN1V32OAfmGAqzTetqTixv5i0voLHNPd49oWQocYHEM5g+8zbpPDK0QVj+0R4gEyI+wWF9M16"+ - "GvOlR1rss/eySUS7skoe7TItY7t2ujMbvxeOyBB7YfC8OTBGcKqE/O3cVyPNtkqvXWqdV9asDQO7TNfb"+ - "3N/gPR/Rd9gD2kKHUxPpOKhcEgoRegu26aFPXPExpL7aNpRT9D7eaNLCPZAZ7yNnTZcxyqlmD5fnoyra"+ - "wzuIqH+twGznTh7ki6/NuB8Ajx/AYzQmjXV05puyUVLC3CFe7CZZDjaipzsyJ7tzBF55V6FcjB7We32x"+ - "ZTeUreF/TgunB54/p4XTEfF7+Q++LZylBTyA8EQL+IDrGVog+Yta4D9bC104p1MRpD/TgtBfSUUIAL9S"+ - "Eb+08P+gBSMhtMnjl5b+51rQHoecaEE6837xU9bHUW+s2AnqYPixjWDi8hTPy6oMyheJGuqdWNg0iK5G"+ - "EVHdMLHdXq4/6HsLRVwujx8WVJgTF1MVia0W0M0cEfHxqqTvFnE1mVdhz4T2bA+sd04hE0PrS0HpneEl"+ - "BKyvjaSiNsK3P55XNq6KLnS2zo6lzSkrKVzbKUNmlVrgfClUabUVVTW2fp47oaDiQ3bdk8QeY9nwshsF"+ - "U0ZueXZ4zUDu+RqlNpwxbCz7lcVq6py5Qdt74hc0hcut9C0DiJbBMtVR0FinhbSAV2lkYQ3nOyZflfbu"+ - "wsTpcz5lTcx5iT+5Zn3pegbXSIle3PB0Cn8kMr+/oSQy+F7N4orDRGJD+XaCIEWYS7Y8SI/R+ahmYXTa"+ - "jMBDyW+XwWI6cPpNZkWQMeQSpbfDODPeFMYlG/nMz9kGSdVWwBPruVFyNykS/+67tDLkoT7aUXKSberW"+ - "T4+Yu9slePniXDlUGffJxlN7yEheEmPmdDtkDuVhnsONyNKCijToxwBxJioQsvz9ZswLnz8JEfpVDhSl"+ - "FsVD56mJw9Wb9+TswrgB0jvhjcdeuAi7MXKcjIhMY4ZnHjHCx21u4RzyPrvIYsah0+PN+B3kpVibPhKE"+ - "nmaYJvFia3qArN6mS7sA7cIIwjwvfnSmVkftHY3VQuf90Z5H3HO0g1H8yPdlfg3sCcJ3P98Ly6m5tzXv"+ - "ny6SETr94g5cXtcrv4ZddXMiT68thBCEq+NvQp2nGMlRC+FJchk179vxn52zkQlfka3B4coruG/+9muu"+ - "fapi57uGeFsBglGxLM4wNRxbTy6dC2UNJCbn9g4+ipE5KrqHSp4ZpOM9XLvH352LfpaKuHn9RypCUmCk"+ - "5coC9RBwkoqwhBMoe3HZdVKOuJe7EfjU0ctAJD6muK6ILFcN3i24PISLVMm8tHmfhCndtVm17nkx3Ggi"+ - "DBDpFbCO7/dvMhFO6uXmybZv6la3zrixy4XPPKZGHdj0/Z5/SScoPQn52HA+TfkWxQbaGNdswrJMZb7z"+ - "OfkKgxKtYCp8vdDvMtOMBTzyzDNfF7wNuBke719LaLaXS6ZSZ6+rvx0rJmXy+rDW+IpQ+CBso1pdHRRc"+ - "yZIjBbQHH7QmiN/qAakyb4IcZLWTAvEd4udrIZTt1yq/im1+n3kuiH/jFagSzH5Flw3W8ipOfSeCgSgj"+ - "iiKLjELxlsz5xptFVxQ9vGDBuyNXI9okPSQZwiwGqtZ3jXCcJTaWcP7XuHB65PlzXDgdEn+KC2elIkBA"+ - "8gkXCI7/dfAHLpD+RS4InMUFcaDthAtt/8AFsp9wwZf/r3BB8DcuCJxwgfsXF35x4b/jQouTZIA7Kv7O"+ - "/YtUxI9/LojhVueUB4iqhbfJJ2bUENhFCYDT2u5YXEsgUFZLkThQaleuYHC3CTKxTCbd1WT0EahBGslv"+ - "DVS32ii8KogjzQvMo62Dwg72hZO1psRHKPQVVBUiB/prviITb5iO+tuV8Cf4gpbxNSDVG/UcMS0Pn9pX"+ - "1fA9HSo2ohu/A25wf6KTwNh4tyDGJVmddORGO0dF7IBkC70hNsJXKFHlI05Ibn6hbebFsMuvbvjzplET"+ - "SHnmI++kTM7evTcpq/uhfFbDakQz8qsyjX32rhp8Ep/1zTZd2tJVkquZu8KMOVIPhflEnxnPxcax9scj"+ - "lToDBcO0pj5X3t7kifqSPfmyOjC8dKfK1GBAJ0ydvb8WSyv18/6Vwdj9aYKeNLT1q7nMXLlgkoOFNqzE"+ - "2nm7cSKRT4xtUp10hOZfm4YE0Ypt3Z/MaGB/DmqcUQt5RHWUzfTQJS21R/ToZnLorfPzIZocgeD19QPw"+ - "XHTIFdwHg7Mlmota6OqYilolxSmSlx8CKjwsELJHKCrINvmNCxi34NV87Ipn6YNICQjQvqAz/rKMznR+"+ - "xLnkeisDE8nNYUGNo/Yd6z5nn79bwVxU+VrjMw6FYyvsRHjKviTE8i3z9Tag580i9Ern5SnETqo8xEsw"+ - "fIyRKSNIzwJRMUUgiRI8wm5TB8UZvJzFngq0eBhAJRO5vbBiKg5703eOV45AT6Sh6XK9gDG76nyVal0a"+ - "GR0lk4aLl1kWQ6H+WmNtU1jngMZR7RpLTy8JgWWcC6Gelj7Icfervb2pQuc3RKswbdDSUy3K1mwMB09O"+ - "lBZ8Pj1LRWmBn0xd0b0TcWaMvhRwTruEejUL/yMtjCZxXMuKevsgpH2fOmbNcDiBq2jZnuNYC7lyjL3W"+ - "qwueYx20DlUl8XqYe3XExPqBVvFjxAb1PUWkUsOab20KKdiK5yizYzde8dLz1mmLILgnsHdJoYpxUgvG"+ - "/PjoRnHGWuODhPomZGNKi+ICT3xpqjdmSokyIOcwY/Q6GjQGghDxtZ5GXkroNGSRBZXJVzXWn/V8EX8z"+ - "bh2EV1VrM2gkFVGxYum4qEsJHd2DPj6kJnJzVTADlCZWR7ItRI7zEPBUU2RiU8t1G6QOxXMhpekJvVQ4"+ - "IppKQdVys+cLtUY6Un0+hI2Z0wMzAxO8Lr0LbaILk8WtNsxpaFYMrTjC22723OH5GFkUi+ux8An2Hi0F"+ - "fvcr1v8aFU6POn+OCqfj4ffS/e+pcOEMKhABrCdUAAPhwB+pQHYGFcT/BBUEz6LC/wGpc+eRNSkAAA=="; - - byte[] dgBytes = decompress(data); - List dgRecords = RecordFactory.createRecords(new ByteArrayInputStream(dgBytes)); - assertEquals(20, dgRecords.size()); - - short[] expectedSids = { - DrawingRecord.sid, - ObjRecord.sid, - DrawingRecord.sid, - TextObjectRecord.sid, - DrawingRecord.sid, - ObjRecord.sid, - DrawingRecord.sid, - TextObjectRecord.sid, - DrawingRecord.sid, - ObjRecord.sid, - DrawingRecord.sid, - TextObjectRecord.sid, - DrawingRecord.sid, - ObjRecord.sid, - DrawingRecord.sid, - TextObjectRecord.sid, - ContinueRecord.sid, - ObjRecord.sid, - ContinueRecord.sid, - TextObjectRecord.sid - }; - for (int i = 0; i < expectedSids.length; i++) { - assertEquals("unexpected record.sid and index[" + i + "]", expectedSids[i], dgRecords.get(i).getSid()); - } - DrawingManager2 drawingManager = new DrawingManager2(new EscherDggRecord()); - - // create a dummy sheet consisting of our test data - InternalSheet sheet = InternalSheet.createSheet(); - List records = sheet.getRecords(); - records.clear(); - records.addAll(dgRecords); - records.add(EOFRecord.instance); - - - sheet.aggregateDrawingRecords(drawingManager, false); - assertEquals("drawing was not fully aggregated", 2, records.size()); - assertTrue("expected EscherAggregate", records.get(0) instanceof EscherAggregate); - assertTrue("expected EOFRecord", records.get(1) instanceof EOFRecord); - EscherAggregate agg = (EscherAggregate) records.get(0); - - byte[] dgBytesAfterSave = agg.serialize(); - assertEquals("different size of drawing data before and after save", dgBytes.length, dgBytesAfterSave.length); - assertTrue("drawing data before and after save is different", Arrays.equals(dgBytes, dgBytesAfterSave)); - } - - @Test - public void testUnhandledContinue2() throws IOException { - String data = - "H4sIAAAAAAAAAO3bdVRUW9sA8AGGrqFHSlpAhSEcQAkJ6UYQyaFBmiEFpCVEOiREGikJSekGlRJQuiQl"+ - "FQFB4ptBvxvIvd+97/fete4f7rWYc9aZc4aZw7P3/s3zbFYB/FiEANTNeD4AAATA2sQCAADIH0wgAEAI"+ - "QNv04kNugZusiGMoAOxNEODHhgrAObkOgLgGHfDt/GlMAID4+3EUxHEADgDgB8DdVEbsNgDAgPMAHxQl"+ - "nzpAAwoI8XsbUfh1QwCvUPiNAIBjFCzEO/BuoUOeiYZ89fPA60AloCBQGCgO5EE8XgPKA4WA/MCrQDoA"+ - "F+IsRgDDR0VM5JUAwHVAbosYYl9ZDg1ICsA4+Sz0gM3dkJpDxN4s4gwSxFZb3NbG0cTGUf+mm50JXJfD"+ - "1doqJrJbthUC6tjw3QAtsFvnYRJZvMDMlyLTPQ+TzrYehmInaLpMTTqKcMzi0JotHH9kzL01ZkHKc6Ni"+ - "kq2K4yJorozv7TaO8FulNhosxSW8sMlIXxqugsRXD+7W4bYy1NBcBKvi7KqW0pqLcXjSxXM+DifJFmzX"+ - "wxikWpWZvDlUODjJ7JArLYfB6yRHcy9MRtBma/86sYUxiBBz5k0WQBxc2B4jM7/6OjxudljZdFGvxQ/f"+ - "I5br+tFosU4PBbUn555F+hUmPa5ss2Tu+7yRzIRgVsuXDWrkr4Nxp5w01EYk7+l7XHgKn2n3qpbe8no+"+ - "ZuWesRfDsSsy6IG4v8fHaKfuFteEvsEbxF444m7hIrb6DiZWcE4O5GNmRNOdFgje/Q2/Or/+OvtR8XMZ"+ - "irYBenKYNTjaMvJGrzRZrKfqsyGakrbXPlDsC3/c2KmE5CaUuoZhvFXADUk3WXwPm17x0PT0jvLtn2mN"+ - "xBuXgU3VNawp8hrkSnHvM+WppoPBcjJPtB7QsKXyJrO+VegVgOUa0TqKuTf5fM62rrx6bHq9EpaXwRMR"+ - "boP2wUNp6CCQprb70nh8u0Pf+O5kffqdjneu6dWqEMKbeFWXeiED44OL1xt2nh0vxxKReN46EjuQz9/u"+ - "KKC44kwIOOujl5871I5HBQAOMJDdAQAwdoBzws0N7EwQEYKMkgJ1GZsxCOkExRIN1joJfgWxVDFpGcGo"+ - "Qj9YEQ7QSLdKI2WLKLhspp46hiokRtiv0E9vFmE7qKSqOuqo2bojlj1JcezuxZCzqNDWlyirjpMyPT3c"+ - "EfRJfo5Zn+XL/tDzDGxJWZIUEhZ+hc04do8U4Xu81g7nSFIK/SWmffPB3sCismdGvWojIRoSNA8SHYrJ"+ - "xTQkWvJ17lYzUdnpcXF+PiRRGoqK0ilkHaLo8VVb0bZtDeXeaVXlfxqR7pAvX8ybfFfS7/YofnHVpRBH"+ - "0lApA95hPONuVas3kX7dpR2hQkHNJRuE0Jq2/XrGQUM6mQ6/LRQe7XSZ6eMH/Eutk2bCD/ZpYNXv10Zu"+ - "PmSPkomEhfJa817co9K8plVfn7dYGr3pIBT/9DUJtWGrDHrAHZG1yTXhiqmxsYmvO3D3sXtjnuZeZfqj"+ - "RayNk8XdX7z5qNaLaGO3FWazI9RvwT55f9LInEuNb01nVUbDJ38oCeKRHAM+uZ/BM8WnJY3XlPZ6uCO6"+ - "05vVj9B3iZffJ/yhcE6rh5Zc1hO1kkp2Y2pmzTfy2gHGh2IWUkNqjm721ZDu7M9xKoy+H9EDvK3ei/Bz"+ - "KkOwBMpWnQ2XQmXKWC41Mb1ifefDUyitSEO9t7nyiWu1eKTEN7Q03XgVNnoVxTTxeHDBYejjCAM5OtMW"+ - "bO7omPh9p0WvOSPFgd2celfAQRIAQ32ZwcXDM7rqLUQ3PSmHYYpSpmjmPAZ8Sthn67Z+cwbMMHo6NPaK"+ - "pN3m5HhHpikPygTa1vuwBaAln7788kVGO302kID8dL1eAUknroFcleOjaGk34QtRlwBmrePCn9b6Zylt"+ - "nlDxY/umra1wTHlGrXVlAcrjUS4aWHEEsWRLVJA36DOSw6tlvFDPCuKXAuvz1Ii+G4aCHIu/BbGxrYuN"+ - "g4kzMoblI14ptkBAN3alD/yuSFuBnFJYY66qi4qZqEmMlsLMiBfpDa+VKkQfCUXH5U3s9Yzz8Lx7vken"+ - "XUrSDtXi2rxAC0pz0OXNMyyeqJ28cL3gfd50oYZvk57mo5x3t3iELzsWcZdo14RMg0xykkXXdPiyBhfK"+ - "I8YVHS+Q7shaM7mwKtzAbXGn5tCmdJ1Ei61VqUpbeOyae+Po+VFs1Zz4PZtt+KfydJcxYW2bKBYCknYb"+ - "2/ttJKALGC7Q4wFbdD+AdPW4V1J2Z5VTM6SRH0zgJxpCQbgmNl8OfV/Dq0Wc4Y5BH6FTiUm57X5bayYi"+ - "yK9TnFo7R3VJygCERmOfE14cfo3QEWg0Y+wZ2u/a1R68QXP7rhtmyBZfttcvowEK6mXAH08cv29nTCOn"+ - "X+D0WPpr40D53ch6+sLTI9GvjQ31x3Hp9NWnQ+DXtg78ISCU5dAxvk3fQMA2YsuH8e1U0Cbx9/kdhIoG"+ - "6EY824eGB8BHHCHaRB7XBVACyBCzPCpCBkSw0zdnFbCEeVoCqP+gBLh/SuCnBP57ErjpXBiC7H9HfyiB"+ - "7rABCKie8SNB3EbNnkXSZZVoMkd0ilYN3R0U+dkyojCakWwRd7HZkLLwRnE70YNVnkzb1mFFVZhPS4VQ"+ - "Zo+84BTf1Ovh6C0EBUK+UWDwOwWYvuxvb0VznabAyBw3i6A2TjAd8BYXmLh28EWYkJKJnBaRE/udl03a"+ - "WLeJ8IscZuajCuhd22r7dhlPKHCZDUEBPzUq7aK2GO6dQTF+Nfob8xoJMAv+j3iYz8uoYPa3SZchIT3N"+ - "Khs8LCtxho8JHo9cupb0EbPJbvprXa9NScmut9ZnumVhV9vnKs1NX/QbReV2aB1IBZd3vG3Dx2dyKdWZ"+ - "ohmawBYv+gvmbA3WvPc+5KV0xbXmD8mncyttAhgV2VnVtyx277mMediuO59P7O3W3bLeLdnr97CoTwe5"+ - "H0JJ0Catmhskb0KhwXwBBaPE0ZikVQzMmPVM5Dd8oH2G/a5AAaMyhc0vl1Bn8CmIxR1YeY7ovzQFcX+h"+ - "Az9GJ/Kw+iLAsjCgxX7oG+J3m56EtSnKdJSbKT9e9tpTgvShNguDUYXlyxn3ge/hONgjb72KOZQh0gJl"+ - "S86mSzEyZQzfJQC/LKP42G2upWgoY8pgqMQf7zlCAubjWqimKRtwuFa5a0XQDRRDWvzx4ycQgmTnICi8"+ - "KRxTL1ans4EIphwLhQe+uxJsiT/AfHdLfk5bfBn/oAVGO3rBTmxFzpVUvoAkuaS0HStsMknEWvV5rve6"+ - "z559INy3PIkz+3MsvSsrWSc1y2YfKxRrSWwY9RnNAqtqSm8QE7yYx3D9/N668T383V78ZKDo1I5TvsuF"+ - "UqFqUs01p0ZZcBJuejBbZGHbBkVwuYD1mydnBnFQfewychqIOFsCNyMUlE76sPRBYKe0DkhO5K3qy1IL"+ - "ujR7lJJC6qoAFt2LiZmyzaOH7oIYo1V75YfD94QS8POYtS10jXj97EgBkS940/upMNr2P15FmxV851sp"+ - "KYdxbRkGFRJJ2tR5pMc57zzPBww0j4djlO/qKuZetMytokpQvFOg3s6+rjKKTxa3y69TzovjG8M+aT6u"+ - "vKUoPFh6oOPJpvMpbxIH/qROZCA/XZ/j7e3o1nNG8RQtBwRB8X4i0OM3Sr6ieJlaq8JWjHHjbhbnUml4"+ - "A9thSAnoxJeXfK0qlSSyvIthRJdlcU6i+B2n+nymFAN1B8qs5r7cw4HPLLLe6/a2BHZBg4SPD3IGNsm1"+ - "lRA94DmaghKnqL3H3Geqf5sETo9Ef08Cp0Pg/ysBNCAgEfEtvw+ABxg9QwKoZ0rg/YkExn4jAbR/UAI8"+ - "3yUg8xsJCP2UwE8J/GcSKAnuIYz+05yAnM0YBPQ9J+BJPRICYzOnKUtK50peABRIjIixqdLd9ipl77P2"+ - "oU0LXMpeuoDMCdCzVT/8ert1p5m2126hbi/y/QOn7r4oWXXslNkTCOiQkj3J+bIw9DwazJiFzYlFkpzt"+ - "Kk5W30krQlmEmwBK4fSXAPnmA0nZ9MwnmFJyPqEXBl8lw5+HXQ4oCL7f4LBOFlVA59qNgEBgyh0m5gAt"+ - "5TzOx+hm0Aq9YGyT1eAAuzzVkFGZatgIbPUcgWQZAZ1OrIkzbUB/jyHpW9Y29pVByVWndmFKVKJFFJYV"+ - "A7RjsQHDwD7MESl8+pcNdn5hy8J2IILZyUVah/AcypvROiGkRpnLWs9DGlBGImderZiyXzPkjFcLzmNo"+ - "MwPbq4o/GVUacxkLX9vdsflafzg+WT5VcX70/Fr8zkVKmO2iqWEjYr7YIIp9qBDlxLbyrGEOZaJQps2H"+ - "U0bidvqV17cEgzAN/PsxjEVCpeptOyOApeLVAnbkUoupEtUCRA996ZOhQBoyeFmkrEjOLEyrEyhbklld"+ - "Qdr1KeANQV7gEs77EIP7Csv4SATw4JwbafKyM0g1inAw719r78OONpfRDJFJUXuGZqYV4XvVaa4lJ7+j"+ - "p0Wjg5j79cuQkgz7FaxH1kfRSfnqgWZJmnHKrzN8vh5fDEXLEUrv1tl87/OOjOKTLRDsmPVqfGZbfFay"+ - "RT5YT4SsrV35Ln5DcUJgD/Z47z5OvSyLBlvP7SEYkGJjrV7xDpQIIlQssn5HscT5a1tMPRRImIWa0IJB"+ - "S9mG4fMCBA2UChQIiaFQY+jC+xz66J1UvVDCROMKHJdPtJjqa3a+i76xuxNb32iHt3oxNF6CZIBh7MHX"+ - "3qCh6lFjEZSzAlh6X2qcCvHMw7+YD4iKIhZ7nEeXVooSCb00nNDqFjQcZjWQ6dWbmXXHpb4evi648EC0"+ - "wvhiqHWZ4bSSIJ3Y/Avzm210Y7Xjkr/kAxQ1NZniKeC0FC9u5Q4/070BkRh5xPP08YqhrLUebteahItY"+ - "2q07jNXiFuxa4EmjKiuLaTcedreMYvHuax91HhyYHV4s6Qo8eP1Z7fO2pG2psK51OkuyZKiuPv4rKTpF"+ - "vPWbB0oN5Hjr3jH5E5UWITHaF/DQdDDjW9romoIDnXM/aSV91KW8HNwv5AeSfqaNoQY+SQiAx3vt6uvg"+ - "B25YfqClzquedJ4SO6ySyWn3IA+LHcvCrLztMRNTwn1mHdvmCP9tCDg9CP09BJyOgF/bh/8bAdynEICG"+ - "eAPoAFMkAlDwAdlnIADtL6YDgP8gAngBP9MBPxHwX0PA6+aBzkeInnb4lxAgEzbf6ZuV6tRnE9Jul4hW"+ - "TGyCmyXtY3zYlXe9Ev2uP216UvqTZNF6lcBMJr7Dy4buBgM8c7V8tqadXW3ZhuY3stjRlezsPhhJuLF8"+ - "iuIk9tj6MCLjH/nGf9EfW5GkNgtHPzP8vAK0OhS7N06MAatJHe8+kLP8pDIQpSHxOCTRYfOkMqBfvekg"+ - "8xZUazjZuCuVksfMXK2lilAAZg5CAQ/YThSQLRbyspC76c3zYDP+R1lCgAf56dJ+KhBa/7reRwXaIU5X"+ - "HUyfr1q1e5Gj10/VrGJT3Q3PuREeuW60C4Ub8wdJHjfj3/f87N6o4jpJg6LoPk2gOPSUIYEUu1164KEp"+ - "sxeaJYVf0bOVBCuBWp1uJvYtYCACA6JpiUo1LjXh3bsLNrv1e+PjV6aczyee745fuEhpWCRygoGNIiQG"+ - "ZhXo8ysa51DmC6W7fDiDb6ik4vMOu66K94CtDWgkULAQFgCXiieMQEKbucAqps7+iyhBd5xdw0JGTkoD"+ - "9pDLxqgnpYEQ420xC8wh0bJmfi75SrY6k8EImIciPePYHiE5BjsGG+GlFzTnrpoQF2LJQbq4XzpN68hF"+ - "qZkReH4pu/v5QsHVuAgDjZhQmofaco2hW0/GkzUup1w2VPF+JIW2e3wBQQGabxS4xXxCgZtZ3eMzTgqz"+ - "Wi2OwZOCZHtvkRSAJATuYOv0ISiAw/IWu0fzthGQb2NtA5o7cvP6buNBVY1A02g3hdr+KEgwBseYgMTV"+ - "nJQK6EhvhVJEACdl6zWTiBIYPsfVG+7hzt3gs7j4dpzMc+xd4eTjzp0PqrDyopPKQPBJZWB3isgSPpp5"+ - "tgRy7xoJUP1ZZaAbKQH/Delav3JpHZDTG2iT/wt1UbE1dIlRu2lT4kWpVmeTJBZPd+gdFfct192xkZGR"+ - "9FuXR+RWKDME/DMAQYPVbJS69p0VRbt4QVtiFOlXtBz4pTEf7G0PyTMFLDuy71LpE1Gn6zLwD05uEMvq"+ - "6skxj3euZrZrWRQQ02YVmhvcCGxRl+sQBakxUz4kKB/uitdaEEnSD2A5/4GHp3d15eGkie6L0VKWREiP"+ - "re3+PAmI093LRrh/xVccmKlDU2+tltnsZiEAo8YLbIKFUe2uqS6Wl7TUlEkSWV4l4IoYL6NmgSztljq+"+ - "yTA08ObVOPJq5veglrqOOZrESKWoBNHSb7x0t7FHzvWq6Uei7Hj3VP4n9keY/zYJnB6J/p4ETkfAr23j"+ - "76cDEBJAwUB83UZIAJUAAD9DAsAzJCAImD+RwMRvJID+D0rgyncJyP1GAiI/JfBTAv+ZBPoZnjfFIXra"+ - "3l+TQNx81R9KwOF3EqhcNiNyN1LjSXYLR0pg7ywJHO7vdSHzAb3YJMksrnJkwkrnRRKtkGsELgdIRPjm"+ - "g/Gw9e7odqTklDIXBl0luzI/fdm/IOi+0okEIk5JIBkhgcoTCeT+KgG72XMEphZoyMKABRivRXTwa2jX"+ - "iyzNHLMeq7jH3V8OJ61cxsrcL13eP1gWtrXloe/n3zwOOFfGtSsaaJbBAdT5AQG4loGvbt3alq+g1is0"+ - "JY5185VCIiASgYDdmrEFd3jl1z4Pm/VEW4QIwhfktshuDK+0yBN8KV08vJJRWi1Ty2Y8RB4vmFpGxiaw"+ - "yVzCilMmswlgJ8FjCK3oMzcASyIzAmDFQO5hEF5HPwkk/fVqUA+qcufqJjXZ8/I42YZUZEqASbY4M6GC"+ - "tOtD1huCPD/zAHvDR4pqd189pW/6ktwcbPVORBP89FF/a/qYfZoaS39IMTD6UoYOZk85k4CTad8rNoy7"+ - "n4k0aOQ6IRdl28PaC5lhkntKNor55L3kJazXTzICJO0+AwT9Kb9jgFB1y0pia/n9ZeI6xF+vMO0zxpEB"+ - "N+EaSVXyNvPBL3UBm4mkr78wwP07A14iGZCMrAtcgmIj6wJ61G/1UASfEMkswMxaBYU+TXQdUKakUFVh"+ - "+9avrWhsKCIzAsWj8d6xECiFBIkag/aDqSnQHzvgA+7DVErEMyF/5AB9pWYIaduUwgFB95WPbdJ87bAE"+ - "R6ACXr05cMHP1mnlqLVcd/Rle+WiIt3mYMrY12u7KT0UdVadimBty7bG827X/V866uVHib7w9Az11uxQ"+ - "76EqBPrVFRdL29guCPY45bw1rLRnFiUxMepJdXj2kK38NjNTJeMEToBtADTqWkx2ZvUMTeKr+2FCtrLM"+ - "RWSKT10v6rFHHtocMRHsxejn3gurn1oWHy28NfaUwC+o5GvNvT1ga/CkbqLSZ+0eGE6m5pqX/OOi6l+W"+ - "CPhS7XarmsRCW+ogWsQZ1zB46BJswEDIUnh6cfNhtKZQfuMT4HvQ0vWrnnMHm8BZN3RFU7VV6ku9duC9"+ - "SaLsd9dSqzwMHAD/NgacHob+HgNOB8Cvbe3/ZgDvjwxAxURO4oA+NELE9PojA9DPZMDiCQOmfsMAjH+Q"+ - "AdDvDFD4DQNEfzLgJwP+MwY8biPYj/s7CYHwM6oC2j0/JAQyyxAMGMNNSqFfrHPjEe/pWYlKw4/NAwm2"+ - "N+WGE83nduLUh3zczje7QBIawyLIKG9H+Z5G/Yug24G5hhk3g6AuLnJ9ABHYsPbtixBBpSxLLWIndvaX"+ - "TUm4t4nxveZfvmIaEduMckObOu+WFxVjfEcht96ONnl4+O7FhZiSC+TNCQ5sspWy6HI9pikzsLgdwCWO"+ - "LcFzYZLvRYdPHDDMYmQGfdVjeiDKD96/t/Fcymr12vXLdyOMBzE3rKEvp60+cU6nCsHPu1E6X2iEB46l"+ - "5eLEMsUytIMttCw1NvmKnYs94OqXjeVm5k3pVSLbXEOJLjCT5u2VeVUeD3vY2uxuJPV2W29ZH6d9WyBA"+ - "tLNvxIJx8Hz5iFJlZJgpD367Ap2FkNVWBofAQ4bpE/UQFy1eNv1caD9BojU/dg7SAlil4mxWS6GsV641"+ - "20N8J+6nZhhWaKguL96klsdNuM4VxzsUxzBSqzwq6gQqhCjiDVjLboCvMIH1VTs7nY/8AnxCzimcZAPM"+ - "iK2xHnDJqCGzAZZRKr/LBsRRnM4GpPidzgbEo/+QDXj2JMTKjLXuvv6j1+JfgRzmntj6AiRj4JyCpxDf"+ - "pN2FeoU7UIo+IbsHNTUC7b8y4DfZAPRv2QByiSjm79mA0tr7i4sYNr6ptl/zhmpIRvR0cQp2rsDQQ7vR"+ - "+1tjOt/O7rq0jiZDu5TOjOGMJL/0P10oeCodkMhrgeWU5+s/ihtUMdPYzdQTHrT2Eqqwv2OlrQwv7bg2"+ - "tR5mtqVXYcyJrAxAaJEMcOp/GiJa4Vkd7oNgQJM2ggF+xRCloiJTQTZHBAMa7MmaWF6yJIuujXOknawU"+ - "DPusyFoQOyq9rpwYQn7fZVinYnC3Nkh2kjVZeeux67MbR3V7kfxzuveM99mOPLJcblfq2bxnwTNst7Hd"+ - "b2MEXbjrwnXcn+/bRCpdLeiRkK0JX/E38LaHUGP4kfKtjwW8tLQO231jLhO6rnjzmTYGCvW2NnKlINZh"+ - "cCB/3NETFhXebfFUqfFlHsEwRXIMV4KlQNBDcedVzI8JWS1Cyjr1XIfo/zYInB6I/h4ETofA34IA9EcI"+ - "oGECuhEv3od4K2ctFMQ4EwI/VgYw/0EI8AF+VgZ+QuC/BgGe5ra+P68M/HahoMwL61FJBY0+Mh2QttMI"+ - "JiR4QJLf2TgJOkFCfIuJ1idw2vfLiJn0VFDJY2MfdIKxnb4XPDseUx48Rr3/FAQIhdRlZLnLs2/q8xMq"+ - "WlnVkcFfDpPgzshXk2ZpZ/kytyR8rwy8ElTKzmh6ugv2c5ItUWD5lg7wg7kufK3rpS2J3JguW6KPKiac"+ - "HHsd2cRPfYDLb947Lk7gZ+GC4eHSSZOSpyyjymYYGpldboruhWaJ+Zrv1pBYBZOeDTkx2e3QNJ3kGOWn"+ - "CwNHE0dGW3XVEw22wnyV3ZWHgQtSW1l7Ie3DK+EJ4M1elgNLCROj6Kc9JiPkjwRTa5nZ+DeZIzvhNztc"+ - "IdRh9Gahzn1WMyPAGD5jaeBIGikU2NJljiMZk0iTYQ9qthHvU+HSvpj7Gc5OkB0gnwqWS7wjF2mlx7qW"+ - "ejVIA3zh/jI0yyWUkjiUk83Y+NpxU/P1tlAW8okwvMc8wVD/tkeZbPNX7Z5d6XrKE+5xlgU8v6UEuHpF"+ - "f5MSMOX48rHxlS/uHh8qXt4b0/XNFyz2hQYvJN4p3ajgidFr4ZRfSPNEpSir9y9KDrYOVdO4CW7qdt/K"+ - "+WYBiMi6TViJ81ZbTD33t0UCQOQiARRdLO2m/BbqGy+fo0caYztLvt5inEq5VDSzV+2TRLc0Vn9ne12i"+ - "4lY8ar4nviaKEVyUl4u5tPzLIU0JNEfhE8lZUWw72xT81yoD4mVICkRB6fG/U6DsfynQeUIBLWX30o6a"+ - "qfVQileiZT0plgOsMk1JVdN2CfnpkWQBVrsO532MLkWjW8bOkRKMN3JX12sVVynXye/ds7yIGShNwoNT"+ - "Xq4rH9RlyfEo4WmYXEGsLK6pyocQ0sRtfp2yVpeJCKy30uPKz8NE3gkeTx5h6XziEObeJvWsj6opUHpX"+ - "8xQ7myirkq/lAxH1K0x3m6MMPnT0z1rPCPVfsKmaXnpHCiG43wKLSH2fpttVq3G3Nl4LWyr/SHo+Lwvi"+ - "p9IQmzVDjm0LdSLqeHM8ILiJRsdoNYS93WyEhi7IOdKXZLTCvCLifxTMEi+snNzAtfevk8DpkejvSeB0"+ - "BPza/oPKABD5z4SARKQEELP1WQsFMc+QwP8ATkmhK404AAA="; - - byte[] dgBytes = decompress(data); - List dgRecords = RecordFactory.createRecords(new ByteArrayInputStream(dgBytes)); - assertEquals(14, dgRecords.size()); - - short[] expectedSids = { - DrawingRecord.sid, - ObjRecord.sid, - DrawingRecord.sid, - ObjRecord.sid, - DrawingRecord.sid, - ObjRecord.sid, - DrawingRecord.sid, - ObjRecord.sid, - ContinueRecord.sid, - ObjRecord.sid, - ContinueRecord.sid, - ObjRecord.sid, - ContinueRecord.sid, - ObjRecord.sid - }; - - for (int i = 0; i < expectedSids.length; i++) { - assertEquals("unexpected record.sid and index[" + i + "]", expectedSids[i], dgRecords.get(i).getSid()); - } - DrawingManager2 drawingManager = new DrawingManager2(new EscherDggRecord()); - - // create a dummy sheet consisting of our test data - InternalSheet sheet = InternalSheet.createSheet(); - List records = sheet.getRecords(); - records.clear(); - records.addAll(dgRecords); - records.add(EOFRecord.instance); - - sheet.aggregateDrawingRecords(drawingManager, false); - assertEquals("drawing was not fully aggregated", 2, records.size()); - assertTrue("expected EscherAggregate", records.get(0) instanceof EscherAggregate); - assertTrue("expected EOFRecord", records.get(1) instanceof EOFRecord); - - EscherAggregate agg = (EscherAggregate) records.get(0); - - byte[] dgBytesAfterSave = agg.serialize(); - assertEquals("different size of drawing data before and after save", dgBytes.length, dgBytesAfterSave.length); - assertTrue("drawing data brefpore and after save is different", Arrays.equals(dgBytes, dgBytesAfterSave)); - } -} diff --git a/src/testcases/org/apache/poi/hssf/model/TestDrawingManager.java b/src/testcases/org/apache/poi/hssf/model/TestDrawingManager.java deleted file mode 100644 index c15027792..000000000 --- a/src/testcases/org/apache/poi/hssf/model/TestDrawingManager.java +++ /dev/null @@ -1,95 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.model; - -import junit.framework.TestCase; -import org.apache.poi.ddf.EscherDggRecord; -import org.apache.poi.ddf.EscherDgRecord; - -/** - * @deprecated in POI 3.15-beta2, scheduled for removal in 3.17, use DrawingManager2 instead - */ -@Deprecated -public final class TestDrawingManager extends TestCase { - public void testFindFreeSPIDBlock() { - EscherDggRecord dgg = new EscherDggRecord(); - DrawingManager dm = new DrawingManager( dgg ); - dgg.setShapeIdMax( 1024 ); - assertEquals( 2048, dm.findFreeSPIDBlock() ); - dgg.setShapeIdMax( 1025 ); - assertEquals( 2048, dm.findFreeSPIDBlock() ); - dgg.setShapeIdMax( 2047 ); - assertEquals( 2048, dm.findFreeSPIDBlock() ); - } - - public void testFindNewDrawingGroupId() { - EscherDggRecord dgg = new EscherDggRecord(); - dgg.setDrawingsSaved( 1 ); - dgg.setFileIdClusters( new EscherDggRecord.FileIdCluster[]{ - new EscherDggRecord.FileIdCluster( 2, 10 )} ); - DrawingManager dm = new DrawingManager( dgg ); - assertEquals( 1, dm.findNewDrawingGroupId() ); - dgg.setFileIdClusters( new EscherDggRecord.FileIdCluster[]{ - new EscherDggRecord.FileIdCluster( 1, 10 ), - new EscherDggRecord.FileIdCluster( 2, 10 )} ); - assertEquals( 3, dm.findNewDrawingGroupId() ); - } - - public void testDrawingGroupExists() { - EscherDggRecord dgg = new EscherDggRecord(); - dgg.setDrawingsSaved( 1 ); - dgg.setFileIdClusters( new EscherDggRecord.FileIdCluster[]{ - new EscherDggRecord.FileIdCluster( 2, 10 )} ); - DrawingManager dm = new DrawingManager( dgg ); - assertFalse( dm.drawingGroupExists( (short) 1 ) ); - assertTrue( dm.drawingGroupExists( (short) 2 ) ); - assertFalse( dm.drawingGroupExists( (short) 3 ) ); - } - - public void testCreateDgRecord() { - EscherDggRecord dgg = new EscherDggRecord(); - dgg.setDrawingsSaved( 0 ); - dgg.setFileIdClusters( new EscherDggRecord.FileIdCluster[]{} ); - DrawingManager dm = new DrawingManager( dgg ); - - EscherDgRecord dgRecord = dm.createDgRecord(); - assertEquals( -1, dgRecord.getLastMSOSPID() ); - assertEquals( 0, dgRecord.getNumShapes() ); - assertEquals( 1, dm.getDgg().getDrawingsSaved() ); - assertEquals( 1, dm.getDgg().getFileIdClusters().length ); - assertEquals( 1, dm.getDgg().getFileIdClusters()[0].getDrawingGroupId() ); - assertEquals( 0, dm.getDgg().getFileIdClusters()[0].getNumShapeIdsUsed() ); - } - - public void testAllocateShapeId() { - EscherDggRecord dgg = new EscherDggRecord(); - dgg.setDrawingsSaved( 0 ); - dgg.setFileIdClusters( new EscherDggRecord.FileIdCluster[]{} ); - DrawingManager dm = new DrawingManager( dgg ); - - EscherDgRecord dg = dm.createDgRecord(); - int shapeId = dm.allocateShapeId( dg.getDrawingGroupId() ); - assertEquals( 1024, shapeId ); - assertEquals( 1025, dgg.getShapeIdMax() ); - assertEquals( 1, dgg.getDrawingsSaved() ); - assertEquals( 1, dgg.getFileIdClusters()[0].getDrawingGroupId() ); - assertEquals( 1, dgg.getFileIdClusters()[0].getNumShapeIdsUsed() ); - assertEquals( 1024, dg.getLastMSOSPID() ); - assertEquals( 1, dg.getNumShapes() ); - } -} diff --git a/src/testcases/org/apache/poi/hssf/model/TestDrawingManager2.java b/src/testcases/org/apache/poi/hssf/model/TestDrawingManager2.java deleted file mode 100644 index 0a0b78940..000000000 --- a/src/testcases/org/apache/poi/hssf/model/TestDrawingManager2.java +++ /dev/null @@ -1,79 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.model; - -import junit.framework.TestCase; -import org.apache.poi.ddf.EscherDggRecord; -import org.apache.poi.ddf.EscherDgRecord; - -public final class TestDrawingManager2 extends TestCase { - private DrawingManager2 drawingManager2; - private EscherDggRecord dgg; - - @Override - protected void setUp() { - dgg = new EscherDggRecord(); - dgg.setFileIdClusters( new EscherDggRecord.FileIdCluster[0] ); - drawingManager2 = new DrawingManager2( dgg ); - } - - public void testCreateDgRecord() { - EscherDgRecord dgRecord1 = drawingManager2.createDgRecord(); - assertEquals( 1, dgRecord1.getDrawingGroupId() ); - assertEquals( -1, dgRecord1.getLastMSOSPID() ); - - EscherDgRecord dgRecord2 = drawingManager2.createDgRecord(); - assertEquals( 2, dgRecord2.getDrawingGroupId() ); - assertEquals( -1, dgRecord2.getLastMSOSPID() ); - - assertEquals( 2, dgg.getDrawingsSaved( ) ); - assertEquals( 2, dgg.getFileIdClusters().length ); - assertEquals( 3, dgg.getNumIdClusters() ); - assertEquals( 0, dgg.getNumShapesSaved() ); - } - - public void testAllocateShapeId() { - EscherDgRecord dgRecord1 = drawingManager2.createDgRecord(); - EscherDgRecord dgRecord2 = drawingManager2.createDgRecord(); - - assertEquals( 1024, drawingManager2.allocateShapeId( (short)1 ) ); - assertEquals( 1024, dgRecord1.getLastMSOSPID() ); - assertEquals( 1025, dgg.getShapeIdMax() ); - assertEquals( 1025, drawingManager2.allocateShapeId( (short)1 ) ); - assertEquals( 1025, dgRecord1.getLastMSOSPID() ); - assertEquals( 1026, dgg.getShapeIdMax() ); - assertEquals( 1026, drawingManager2.allocateShapeId( (short)1 ) ); - assertEquals( 1026, dgRecord1.getLastMSOSPID() ); - assertEquals( 1027, dgg.getShapeIdMax() ); - assertEquals( 2048, drawingManager2.allocateShapeId( (short)2 ) ); - assertEquals( 2048, dgRecord2.getLastMSOSPID() ); - assertEquals( 2049, dgg.getShapeIdMax() ); - - for (int i = 0; i < 1021; i++) - { - drawingManager2.allocateShapeId( (short)1 ); - assertEquals( 2049, dgg.getShapeIdMax() ); - } - assertEquals( 3072, drawingManager2.allocateShapeId( (short) 1 ) ); - assertEquals( 3073, dgg.getShapeIdMax() ); - - assertEquals( 2, dgg.getDrawingsSaved() ); - assertEquals( 4, dgg.getNumIdClusters() ); - assertEquals( 1026, dgg.getNumShapesSaved() ); - } -} diff --git a/src/testcases/org/apache/poi/hssf/model/TestDrawingShapes.java b/src/testcases/org/apache/poi/hssf/model/TestDrawingShapes.java deleted file mode 100644 index 2c00cbfe0..000000000 --- a/src/testcases/org/apache/poi/hssf/model/TestDrawingShapes.java +++ /dev/null @@ -1,854 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.model; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.util.List; - -import org.apache.poi.ddf.*; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.record.CommonObjectDataSubRecord; -import org.apache.poi.hssf.record.EscherAggregate; -import org.apache.poi.hssf.record.ObjRecord; -import org.apache.poi.hssf.usermodel.HSSFAnchor; -import org.apache.poi.hssf.usermodel.HSSFChildAnchor; -import org.apache.poi.hssf.usermodel.HSSFClientAnchor; -import org.apache.poi.hssf.usermodel.HSSFComment; -import org.apache.poi.hssf.usermodel.HSSFPatriarch; -import org.apache.poi.hssf.usermodel.HSSFPicture; -import org.apache.poi.hssf.usermodel.HSSFPolygon; -import org.apache.poi.hssf.usermodel.HSSFRichTextString; -import org.apache.poi.hssf.usermodel.HSSFShape; -import org.apache.poi.hssf.usermodel.HSSFShapeGroup; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFSimpleShape; -import org.apache.poi.hssf.usermodel.HSSFTestHelper; -import org.apache.poi.hssf.usermodel.HSSFTextbox; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.ClientAnchor.AnchorType; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.util.HexDump; -import org.junit.Test; - - -/** - * Test escher drawing - * - * optionally the system setting "poi.deserialize.escher" can be set to {@code true} - */ -public class TestDrawingShapes { - /** - * HSSFShape tree bust be built correctly - * Check file with such records structure: - * -patriarch - * --shape - * --group - * ---group - * ----shape - * ----shape - * ---shape - * ---group - * ----shape - * ----shape - */ - @Test - public void testDrawingGroups() throws IOException { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("drawings.xls"); - HSSFSheet sheet = wb.getSheet("groups"); - HSSFPatriarch patriarch = sheet.getDrawingPatriarch(); - assertEquals(patriarch.getChildren().size(), 2); - HSSFShapeGroup group = (HSSFShapeGroup) patriarch.getChildren().get(1); - assertEquals(3, group.getChildren().size()); - HSSFShapeGroup group1 = (HSSFShapeGroup) group.getChildren().get(0); - assertEquals(2, group1.getChildren().size()); - group1 = (HSSFShapeGroup) group.getChildren().get(2); - assertEquals(2, group1.getChildren().size()); - wb.close(); - } - - @Test - public void testHSSFShapeCompatibility() { - HSSFSimpleShape shape = new HSSFSimpleShape(null, new HSSFClientAnchor()); - shape.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE); - assertEquals(0x08000040, shape.getLineStyleColor()); - assertEquals(0x08000009, shape.getFillColor()); - assertEquals(HSSFShape.LINEWIDTH_DEFAULT, shape.getLineWidth()); - assertEquals(HSSFShape.LINESTYLE_SOLID, shape.getLineStyle()); - assertFalse(shape.isNoFill()); - - EscherOptRecord opt = shape.getOptRecord(); - - assertEquals(7, opt.getEscherProperties().size()); - assertTrue(((EscherBoolProperty) opt.lookup(EscherProperties.GROUPSHAPE__PRINT)).isTrue()); - assertTrue(((EscherBoolProperty) opt.lookup(EscherProperties.LINESTYLE__NOLINEDRAWDASH)).isTrue()); - assertEquals(0x00000004, ((EscherSimpleProperty) opt.lookup(EscherProperties.GEOMETRY__SHAPEPATH)).getPropertyValue()); - assertNull(opt.lookup(EscherProperties.TEXT__SIZE_TEXT_TO_FIT_SHAPE)); - } - - @Test - public void testDefaultPictureSettings() { - HSSFPicture picture = new HSSFPicture(null, new HSSFClientAnchor()); - assertEquals(picture.getLineWidth(), HSSFShape.LINEWIDTH_DEFAULT); - assertEquals(picture.getFillColor(), HSSFShape.FILL__FILLCOLOR_DEFAULT); - assertEquals(picture.getLineStyle(), HSSFShape.LINESTYLE_NONE); - assertEquals(picture.getLineStyleColor(), HSSFShape.LINESTYLE__COLOR_DEFAULT); - assertFalse(picture.isNoFill()); - assertEquals(picture.getPictureIndex(), -1);//not set yet - } - - /** - * No NullPointerException should appear - */ - @Test - public void testDefaultSettingsWithEmptyContainer() { - EscherContainerRecord container = new EscherContainerRecord(); - EscherOptRecord opt = new EscherOptRecord(); - opt.setRecordId(EscherOptRecord.RECORD_ID); - container.addChildRecord(opt); - ObjRecord obj = new ObjRecord(); - CommonObjectDataSubRecord cod = new CommonObjectDataSubRecord(); - cod.setObjectType(HSSFSimpleShape.OBJECT_TYPE_PICTURE); - obj.addSubRecord(cod); - HSSFPicture picture = new HSSFPicture(container, obj); - - assertEquals(picture.getLineWidth(), HSSFShape.LINEWIDTH_DEFAULT); - assertEquals(picture.getFillColor(), HSSFShape.FILL__FILLCOLOR_DEFAULT); - assertEquals(picture.getLineStyle(), HSSFShape.LINESTYLE_DEFAULT); - assertEquals(picture.getLineStyleColor(), HSSFShape.LINESTYLE__COLOR_DEFAULT); - assertEquals(picture.isNoFill(), HSSFShape.NO_FILL_DEFAULT); - assertEquals(picture.getPictureIndex(), -1);//not set yet - } - - /** - * create a rectangle, save the workbook, read back and verify that all shape properties are there - */ - @Test - public void testReadWriteRectangle() throws IOException { - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet sheet = wb1.createSheet(); - - HSSFPatriarch drawing = sheet.createDrawingPatriarch(); - HSSFClientAnchor anchor = new HSSFClientAnchor(10, 10, 50, 50, (short) 2, 2, (short) 4, 4); - anchor.setAnchorType(AnchorType.MOVE_DONT_RESIZE); - assertEquals(AnchorType.MOVE_DONT_RESIZE, anchor.getAnchorType()); - //noinspection deprecation - anchor.setAnchorType(AnchorType.MOVE_DONT_RESIZE.value); - assertEquals(AnchorType.MOVE_DONT_RESIZE, anchor.getAnchorType()); - - HSSFSimpleShape rectangle = drawing.createSimpleShape(anchor); - rectangle.setShapeType(HSSFSimpleShape.OBJECT_TYPE_RECTANGLE); - rectangle.setLineWidth(10000); - rectangle.setFillColor(777); - assertEquals(rectangle.getFillColor(), 777); - assertEquals(10000, rectangle.getLineWidth()); - rectangle.setLineStyle(10); - assertEquals(10, rectangle.getLineStyle()); - assertEquals(rectangle.getWrapText(), HSSFSimpleShape.WRAP_SQUARE); - rectangle.setLineStyleColor(1111); - rectangle.setNoFill(true); - rectangle.setWrapText(HSSFSimpleShape.WRAP_NONE); - rectangle.setString(new HSSFRichTextString("teeeest")); - assertEquals(rectangle.getLineStyleColor(), 1111); - EscherContainerRecord escherContainer = HSSFTestHelper.getEscherContainer(rectangle); - assertNotNull(escherContainer); - EscherRecord childById = escherContainer.getChildById(EscherOptRecord.RECORD_ID); - assertNotNull(childById); - EscherProperty lookup = ((EscherOptRecord) childById).lookup(EscherProperties.TEXT__TEXTID); - assertNotNull(lookup); - assertEquals(((EscherSimpleProperty) lookup).getPropertyValue(), "teeeest".hashCode()); - assertEquals(rectangle.isNoFill(), true); - assertEquals(rectangle.getWrapText(), HSSFSimpleShape.WRAP_NONE); - assertEquals(rectangle.getString().getString(), "teeeest"); - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sheet = wb2.getSheetAt(0); - drawing = sheet.getDrawingPatriarch(); - assertEquals(1, drawing.getChildren().size()); - - HSSFSimpleShape rectangle2 = - (HSSFSimpleShape) drawing.getChildren().get(0); - assertEquals(HSSFSimpleShape.OBJECT_TYPE_RECTANGLE, - rectangle2.getShapeType()); - assertEquals(10000, rectangle2.getLineWidth()); - assertEquals(10, rectangle2.getLineStyle()); - assertEquals(anchor, rectangle2.getAnchor()); - assertEquals(rectangle2.getLineStyleColor(), 1111); - assertEquals(rectangle2.getFillColor(), 777); - assertEquals(rectangle2.isNoFill(), true); - assertEquals(rectangle2.getString().getString(), "teeeest"); - assertEquals(rectangle.getWrapText(), HSSFSimpleShape.WRAP_NONE); - - rectangle2.setFillColor(3333); - rectangle2.setLineStyle(9); - rectangle2.setLineStyleColor(4444); - rectangle2.setNoFill(false); - rectangle2.setLineWidth(77); - rectangle2.getAnchor().setDx1(2); - rectangle2.getAnchor().setDx2(3); - rectangle2.getAnchor().setDy1(4); - rectangle2.getAnchor().setDy2(5); - rectangle.setWrapText(HSSFSimpleShape.WRAP_BY_POINTS); - rectangle2.setString(new HSSFRichTextString("test22")); - - HSSFWorkbook wb3 = HSSFTestDataSamples.writeOutAndReadBack(wb2); - wb2.close(); - sheet = wb3.getSheetAt(0); - drawing = sheet.getDrawingPatriarch(); - assertEquals(1, drawing.getChildren().size()); - rectangle2 = (HSSFSimpleShape) drawing.getChildren().get(0); - assertEquals(HSSFSimpleShape.OBJECT_TYPE_RECTANGLE, rectangle2.getShapeType()); - assertEquals(rectangle.getWrapText(), HSSFSimpleShape.WRAP_BY_POINTS); - assertEquals(77, rectangle2.getLineWidth()); - assertEquals(9, rectangle2.getLineStyle()); - assertEquals(rectangle2.getLineStyleColor(), 4444); - assertEquals(rectangle2.getFillColor(), 3333); - assertEquals(rectangle2.getAnchor().getDx1(), 2); - assertEquals(rectangle2.getAnchor().getDx2(), 3); - assertEquals(rectangle2.getAnchor().getDy1(), 4); - assertEquals(rectangle2.getAnchor().getDy2(), 5); - assertEquals(rectangle2.isNoFill(), false); - assertEquals(rectangle2.getString().getString(), "test22"); - - HSSFSimpleShape rect3 = drawing.createSimpleShape(new HSSFClientAnchor()); - rect3.setShapeType(HSSFSimpleShape.OBJECT_TYPE_RECTANGLE); - HSSFWorkbook wb4 = HSSFTestDataSamples.writeOutAndReadBack(wb3); - wb3.close(); - - drawing = wb4.getSheetAt(0).getDrawingPatriarch(); - assertEquals(drawing.getChildren().size(), 2); - wb4.close(); - } - - @Test - public void testReadExistingImage() throws IOException { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("drawings.xls"); - HSSFSheet sheet = wb.getSheet("pictures"); - HSSFPatriarch drawing = sheet.getDrawingPatriarch(); - assertEquals(1, drawing.getChildren().size()); - HSSFPicture picture = (HSSFPicture) drawing.getChildren().get(0); - - assertEquals(picture.getPictureIndex(), 2); - assertEquals(picture.getLineStyleColor(), HSSFShape.LINESTYLE__COLOR_DEFAULT); - assertEquals(picture.getFillColor(), 0x5DC943); - assertEquals(picture.getLineWidth(), HSSFShape.LINEWIDTH_DEFAULT); - assertEquals(picture.getLineStyle(), HSSFShape.LINESTYLE_DEFAULT); - assertEquals(picture.isNoFill(), false); - - picture.setPictureIndex(2); - assertEquals(picture.getPictureIndex(), 2); - wb.close(); - } - - - /* assert shape properties when reading shapes from a existing workbook */ - @Test - public void testReadExistingRectangle() throws IOException { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("drawings.xls"); - HSSFSheet sheet = wb.getSheet("rectangles"); - HSSFPatriarch drawing = sheet.getDrawingPatriarch(); - assertEquals(1, drawing.getChildren().size()); - - HSSFSimpleShape shape = (HSSFSimpleShape) drawing.getChildren().get(0); - assertEquals(shape.isNoFill(), false); - assertEquals(shape.getLineStyle(), HSSFShape.LINESTYLE_DASHDOTGEL); - assertEquals(shape.getLineStyleColor(), 0x616161); - assertEquals(HexDump.toHex(shape.getFillColor()), shape.getFillColor(), 0x2CE03D); - assertEquals(shape.getLineWidth(), HSSFShape.LINEWIDTH_ONE_PT * 2); - assertEquals(shape.getString().getString(), "POItest"); - assertEquals(shape.getRotationDegree(), 27); - wb.close(); - } - - @Test - public void testShapeIds() throws IOException { - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet sheet1 = wb1.createSheet(); - HSSFPatriarch patriarch1 = sheet1.createDrawingPatriarch(); - for (int i = 0; i < 2; i++) { - patriarch1.createSimpleShape(new HSSFClientAnchor()); - } - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sheet1 = wb2.getSheetAt(0); - patriarch1 = sheet1.getDrawingPatriarch(); - - EscherAggregate agg1 = HSSFTestHelper.getEscherAggregate(patriarch1); - // last shape ID cached in EscherDgRecord - EscherDgRecord dg1 = - agg1.getEscherContainer().getChildById(EscherDgRecord.RECORD_ID); - assertEquals(1026, dg1.getLastMSOSPID()); - - // iterate over shapes and check shapeId - EscherContainerRecord spgrContainer = - agg1.getEscherContainer().getChildContainers().get(0); - // root spContainer + 2 spContainers for shapes - assertEquals(3, spgrContainer.getChildRecords().size()); - - EscherSpRecord sp0 = - ((EscherContainerRecord) spgrContainer.getChild(0)).getChildById(EscherSpRecord.RECORD_ID); - assertEquals(1024, sp0.getShapeId()); - - EscherSpRecord sp1 = - ((EscherContainerRecord) spgrContainer.getChild(1)).getChildById(EscherSpRecord.RECORD_ID); - assertEquals(1025, sp1.getShapeId()); - - EscherSpRecord sp2 = - ((EscherContainerRecord) spgrContainer.getChild(2)).getChildById(EscherSpRecord.RECORD_ID); - assertEquals(1026, sp2.getShapeId()); - wb2.close(); - } - - /** - * Test get new id for shapes from existing file - * File already have for 1 shape on each sheet, because document must contain EscherDgRecord for each sheet - */ - @Test - public void testAllocateNewIds() throws IOException { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("empty.xls"); - HSSFSheet sheet = wb.getSheetAt(0); - HSSFPatriarch patriarch = sheet.getDrawingPatriarch(); - - /** - * 2048 - main SpContainer id - * 2049 - existing shape id - */ - assertEquals(HSSFTestHelper.allocateNewShapeId(patriarch), 2050); - assertEquals(HSSFTestHelper.allocateNewShapeId(patriarch), 2051); - assertEquals(HSSFTestHelper.allocateNewShapeId(patriarch), 2052); - - sheet = wb.getSheetAt(1); - patriarch = sheet.getDrawingPatriarch(); - - /** - * 3072 - main SpContainer id - * 3073 - existing shape id - */ - assertEquals(HSSFTestHelper.allocateNewShapeId(patriarch), 3074); - assertEquals(HSSFTestHelper.allocateNewShapeId(patriarch), 3075); - assertEquals(HSSFTestHelper.allocateNewShapeId(patriarch), 3076); - - - sheet = wb.getSheetAt(2); - patriarch = sheet.getDrawingPatriarch(); - - assertEquals(HSSFTestHelper.allocateNewShapeId(patriarch), 1026); - assertEquals(HSSFTestHelper.allocateNewShapeId(patriarch), 1027); - assertEquals(HSSFTestHelper.allocateNewShapeId(patriarch), 1028); - wb.close(); - } - - @Test - public void testOpt() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - - // create a sheet with a text box - HSSFSheet sheet = wb.createSheet(); - HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); - - HSSFTextbox textbox = patriarch.createTextbox(new HSSFClientAnchor()); - EscherOptRecord opt1 = HSSFTestHelper.getOptRecord(textbox); - EscherOptRecord opt2 = HSSFTestHelper.getEscherContainer(textbox).getChildById(EscherOptRecord.RECORD_ID); - assertSame(opt1, opt2); - wb.close(); - } - - @Test - public void testCorrectOrderInOptRecord() throws IOException{ - HSSFWorkbook wb = new HSSFWorkbook(); - - HSSFSheet sheet = wb.createSheet(); - HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); - - HSSFTextbox textbox = patriarch.createTextbox(new HSSFClientAnchor()); - EscherOptRecord opt = HSSFTestHelper.getOptRecord(textbox); - - String opt1Str = opt.toXml(); - - textbox.setFillColor(textbox.getFillColor()); - EscherContainerRecord container = HSSFTestHelper.getEscherContainer(textbox); - EscherOptRecord optRecord = container.getChildById(EscherOptRecord.RECORD_ID); - assertEquals(opt1Str, optRecord.toXml()); - textbox.setLineStyle(textbox.getLineStyle()); - assertEquals(opt1Str, optRecord.toXml()); - textbox.setLineWidth(textbox.getLineWidth()); - assertEquals(opt1Str, optRecord.toXml()); - textbox.setLineStyleColor(textbox.getLineStyleColor()); - assertEquals(opt1Str, optRecord.toXml()); - wb.close(); - } - - @Test - public void testDgRecordNumShapes() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet(); - HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); - - EscherAggregate aggregate = HSSFTestHelper.getEscherAggregate(patriarch); - EscherDgRecord dgRecord = (EscherDgRecord) aggregate.getEscherRecord(0).getChild(0); - assertEquals(dgRecord.getNumShapes(), 1); - wb.close(); - } - - @Test - public void testTextForSimpleShape() throws IOException { - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet sheet = wb1.createSheet(); - HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); - - HSSFSimpleShape shape = patriarch.createSimpleShape(new HSSFClientAnchor()); - shape.setShapeType(HSSFSimpleShape.OBJECT_TYPE_RECTANGLE); - - EscherAggregate agg = HSSFTestHelper.getEscherAggregate(patriarch); - assertEquals(agg.getShapeToObjMapping().size(), 2); - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sheet = wb2.getSheetAt(0); - patriarch = sheet.getDrawingPatriarch(); - - shape = (HSSFSimpleShape) patriarch.getChildren().get(0); - - agg = HSSFTestHelper.getEscherAggregate(patriarch); - assertEquals(agg.getShapeToObjMapping().size(), 2); - - shape.setString(new HSSFRichTextString("string1")); - assertEquals(shape.getString().getString(), "string1"); - - assertNotNull(HSSFTestHelper.getEscherContainer(shape).getChildById(EscherTextboxRecord.RECORD_ID)); - assertEquals(agg.getShapeToObjMapping().size(), 2); - - HSSFWorkbook wb3 = HSSFTestDataSamples.writeOutAndReadBack(wb2); - wb2.close(); - - HSSFWorkbook wb4 = HSSFTestDataSamples.writeOutAndReadBack(wb3); - wb3.close(); - sheet = wb4.getSheetAt(0); - patriarch = sheet.getDrawingPatriarch(); - - shape = (HSSFSimpleShape) patriarch.getChildren().get(0); - - assertNotNull(HSSFTestHelper.getTextObjRecord(shape)); - assertEquals(shape.getString().getString(), "string1"); - assertNotNull(HSSFTestHelper.getEscherContainer(shape).getChildById(EscherTextboxRecord.RECORD_ID)); - assertEquals(agg.getShapeToObjMapping().size(), 2); - wb4.close(); - } - - @Test - public void testRemoveShapes() throws IOException { - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet sheet = wb1.createSheet(); - HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); - - HSSFSimpleShape rectangle = patriarch.createSimpleShape(new HSSFClientAnchor()); - rectangle.setShapeType(HSSFSimpleShape.OBJECT_TYPE_RECTANGLE); - - int idx = wb1.addPicture(new byte[]{1,2,3}, Workbook.PICTURE_TYPE_JPEG); - patriarch.createPicture(new HSSFClientAnchor(), idx); - - patriarch.createCellComment(new HSSFClientAnchor()); - - HSSFPolygon polygon = patriarch.createPolygon(new HSSFClientAnchor()); - polygon.setPoints(new int[]{1,2}, new int[]{2,3}); - - patriarch.createTextbox(new HSSFClientAnchor()); - - HSSFShapeGroup group = patriarch.createGroup(new HSSFClientAnchor()); - group.createTextbox(new HSSFChildAnchor()); - group.createPicture(new HSSFChildAnchor(), idx); - - assertEquals(patriarch.getChildren().size(), 6); - assertEquals(group.getChildren().size(), 2); - - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 12); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1); - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sheet = wb2.getSheetAt(0); - patriarch = sheet.getDrawingPatriarch(); - - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 12); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1); - - assertEquals(patriarch.getChildren().size(), 6); - - group = (HSSFShapeGroup) patriarch.getChildren().get(5); - group.removeShape(group.getChildren().get(0)); - - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 10); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1); - - HSSFWorkbook wb3 = HSSFTestDataSamples.writeOutAndReadBack(wb2); - wb2.close(); - sheet = wb3.getSheetAt(0); - patriarch = sheet.getDrawingPatriarch(); - - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 10); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1); - - group = (HSSFShapeGroup) patriarch.getChildren().get(5); - patriarch.removeShape(group); - - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 8); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1); - - HSSFWorkbook wb4 = HSSFTestDataSamples.writeOutAndReadBack(wb3); - wb3.close(); - sheet = wb4.getSheetAt(0); - patriarch = sheet.getDrawingPatriarch(); - - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 8); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1); - assertEquals(patriarch.getChildren().size(), 5); - - HSSFShape shape = patriarch.getChildren().get(0); - patriarch.removeShape(shape); - - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 6); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1); - assertEquals(patriarch.getChildren().size(), 4); - - HSSFWorkbook wb5 = HSSFTestDataSamples.writeOutAndReadBack(wb4); - wb4.close(); - sheet = wb5.getSheetAt(0); - patriarch = sheet.getDrawingPatriarch(); - - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 6); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1); - assertEquals(patriarch.getChildren().size(), 4); - - HSSFPicture picture = (HSSFPicture) patriarch.getChildren().get(0); - patriarch.removeShape(picture); - - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 5); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1); - assertEquals(patriarch.getChildren().size(), 3); - - HSSFWorkbook wb6 = HSSFTestDataSamples.writeOutAndReadBack(wb5); - wb5.close(); - sheet = wb6.getSheetAt(0); - patriarch = sheet.getDrawingPatriarch(); - - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 5); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 1); - assertEquals(patriarch.getChildren().size(), 3); - - HSSFComment comment = (HSSFComment) patriarch.getChildren().get(0); - patriarch.removeShape(comment); - - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 3); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 0); - assertEquals(patriarch.getChildren().size(), 2); - - HSSFWorkbook wb7 = HSSFTestDataSamples.writeOutAndReadBack(wb6); - wb6.close(); - sheet = wb7.getSheetAt(0); - patriarch = sheet.getDrawingPatriarch(); - - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 3); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 0); - assertEquals(patriarch.getChildren().size(), 2); - - polygon = (HSSFPolygon) patriarch.getChildren().get(0); - patriarch.removeShape(polygon); - - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 2); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 0); - assertEquals(patriarch.getChildren().size(), 1); - - HSSFWorkbook wb8 = HSSFTestDataSamples.writeOutAndReadBack(wb7); - wb7.close(); - sheet = wb8.getSheetAt(0); - patriarch = sheet.getDrawingPatriarch(); - - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 2); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 0); - assertEquals(patriarch.getChildren().size(), 1); - - HSSFTextbox textbox = (HSSFTextbox) patriarch.getChildren().get(0); - patriarch.removeShape(textbox); - - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 0); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 0); - assertEquals(patriarch.getChildren().size(), 0); - - HSSFWorkbook wb9 = HSSFTestDataSamples.writeOutAndReadBack(wb8); - wb8.close(); - sheet = wb9.getSheetAt(0); - patriarch = sheet.getDrawingPatriarch(); - - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getShapeToObjMapping().size(), 0); - assertEquals(HSSFTestHelper.getEscherAggregate(patriarch).getTailRecords().size(), 0); - assertEquals(patriarch.getChildren().size(), 0); - wb9.close(); - } - - @Test - public void testShapeFlip() throws IOException { - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet sheet = wb1.createSheet(); - HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); - - HSSFSimpleShape rectangle = patriarch.createSimpleShape(new HSSFClientAnchor()); - rectangle.setShapeType(HSSFSimpleShape.OBJECT_TYPE_RECTANGLE); - - assertEquals(rectangle.isFlipVertical(), false); - assertEquals(rectangle.isFlipHorizontal(), false); - - rectangle.setFlipVertical(true); - assertEquals(rectangle.isFlipVertical(), true); - rectangle.setFlipHorizontal(true); - assertEquals(rectangle.isFlipHorizontal(), true); - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sheet = wb2.getSheetAt(0); - patriarch = sheet.getDrawingPatriarch(); - - rectangle = (HSSFSimpleShape) patriarch.getChildren().get(0); - - assertEquals(rectangle.isFlipHorizontal(), true); - rectangle.setFlipHorizontal(false); - assertEquals(rectangle.isFlipHorizontal(), false); - - assertEquals(rectangle.isFlipVertical(), true); - rectangle.setFlipVertical(false); - assertEquals(rectangle.isFlipVertical(), false); - - HSSFWorkbook wb3 = HSSFTestDataSamples.writeOutAndReadBack(wb2); - wb2.close(); - sheet = wb3.getSheetAt(0); - patriarch = sheet.getDrawingPatriarch(); - - rectangle = (HSSFSimpleShape) patriarch.getChildren().get(0); - - assertEquals(rectangle.isFlipVertical(), false); - assertEquals(rectangle.isFlipHorizontal(), false); - wb3.close(); - } - - @Test - public void testRotation() throws IOException { - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet sheet = wb1.createSheet(); - HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); - - HSSFSimpleShape rectangle = patriarch.createSimpleShape(new HSSFClientAnchor(0,0,100,100, (short) 0,0,(short)5,5)); - rectangle.setShapeType(HSSFSimpleShape.OBJECT_TYPE_RECTANGLE); - - assertEquals(rectangle.getRotationDegree(), 0); - rectangle.setRotationDegree((short) 45); - assertEquals(rectangle.getRotationDegree(), 45); - rectangle.setFlipHorizontal(true); - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sheet = wb2.getSheetAt(0); - patriarch = sheet.getDrawingPatriarch(); - rectangle = (HSSFSimpleShape) patriarch.getChildren().get(0); - assertEquals(rectangle.getRotationDegree(), 45); - rectangle.setRotationDegree((short) 30); - assertEquals(rectangle.getRotationDegree(), 30); - - patriarch.setCoordinates(0, 0, 10, 10); - rectangle.setString(new HSSFRichTextString("1234")); - wb2.close(); - } - - @SuppressWarnings("unused") - @Test - public void testShapeContainerImplementsIterable() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - - HSSFSheet sheet = wb.createSheet(); - HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); - - patriarch.createSimpleShape(new HSSFClientAnchor()); - patriarch.createSimpleShape(new HSSFClientAnchor()); - - int i=2; - - for (HSSFShape shape: patriarch){ - i--; - } - assertEquals(i, 0); - wb.close(); - } - - @Test - public void testClearShapesForPatriarch() throws IOException { - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet sheet = wb1.createSheet(); - HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); - - patriarch.createSimpleShape(new HSSFClientAnchor()); - patriarch.createSimpleShape(new HSSFClientAnchor()); - patriarch.createCellComment(new HSSFClientAnchor()); - - EscherAggregate agg = HSSFTestHelper.getEscherAggregate(patriarch); - - assertEquals(agg.getShapeToObjMapping().size(), 6); - assertEquals(agg.getTailRecords().size(), 1); - assertEquals(patriarch.getChildren().size(), 3); - - patriarch.clear(); - - assertEquals(agg.getShapeToObjMapping().size(), 0); - assertEquals(agg.getTailRecords().size(), 0); - assertEquals(patriarch.getChildren().size(), 0); - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sheet = wb2.getSheetAt(0); - patriarch = sheet.getDrawingPatriarch(); - - assertEquals(agg.getShapeToObjMapping().size(), 0); - assertEquals(agg.getTailRecords().size(), 0); - assertEquals(patriarch.getChildren().size(), 0); - wb2.close(); - } - - @Test - public void testBug45312() throws Exception { - HSSFWorkbook wb = new HSSFWorkbook(); - try { - HSSFSheet sheet = wb.createSheet(); - HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); - - { - HSSFClientAnchor a1 = new HSSFClientAnchor(); - a1.setAnchor( (short)1, 1, 0, 0, (short) 1, 1, 512, 100); - HSSFSimpleShape shape1 = patriarch.createSimpleShape(a1); - shape1.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE); - } - { - HSSFClientAnchor a1 = new HSSFClientAnchor(); - a1.setAnchor( (short)1, 1, 512, 0, (short) 1, 1, 1024, 100); - HSSFSimpleShape shape1 = patriarch.createSimpleShape(a1); - shape1.setFlipVertical(true); - shape1.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE); - } - - { - HSSFClientAnchor a1 = new HSSFClientAnchor(); - a1.setAnchor( (short)2, 2, 0, 0, (short) 2, 2, 512, 100); - HSSFSimpleShape shape1 = patriarch.createSimpleShape(a1); - shape1.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE); - } - { - HSSFClientAnchor a1 = new HSSFClientAnchor(); - a1.setAnchor( (short)2, 2, 0, 100, (short) 2, 2, 512, 200); - HSSFSimpleShape shape1 = patriarch.createSimpleShape(a1); - shape1.setFlipHorizontal(true); - shape1.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE); - } - - /*OutputStream stream = new FileOutputStream("/tmp/45312.xls"); - try { - wb.write(stream); - } finally { - stream.close(); - }*/ - - checkWorkbookBack(wb); - } finally { - wb.close(); - } - } - - private void checkWorkbookBack(HSSFWorkbook wb) throws IOException { - HSSFWorkbook wbBack = HSSFTestDataSamples.writeOutAndReadBack(wb); - assertNotNull(wbBack); - - HSSFSheet sheetBack = wbBack.getSheetAt(0); - assertNotNull(sheetBack); - - HSSFPatriarch patriarchBack = sheetBack.getDrawingPatriarch(); - assertNotNull(patriarchBack); - - List children = patriarchBack.getChildren(); - assertEquals(4, children.size()); - HSSFShape hssfShape = children.get(0); - assertTrue(hssfShape instanceof HSSFSimpleShape); - HSSFAnchor anchor = hssfShape.getAnchor(); - assertTrue(anchor instanceof HSSFClientAnchor); - assertEquals(0, anchor.getDx1()); - assertEquals(512, anchor.getDx2()); - assertEquals(0, anchor.getDy1()); - assertEquals(100, anchor.getDy2()); - HSSFClientAnchor cAnchor = (HSSFClientAnchor) anchor; - assertEquals(1, cAnchor.getCol1()); - assertEquals(1, cAnchor.getCol2()); - assertEquals(1, cAnchor.getRow1()); - assertEquals(1, cAnchor.getRow2()); - - hssfShape = children.get(1); - assertTrue(hssfShape instanceof HSSFSimpleShape); - anchor = hssfShape.getAnchor(); - assertTrue(anchor instanceof HSSFClientAnchor); - assertEquals(512, anchor.getDx1()); - assertEquals(1024, anchor.getDx2()); - assertEquals(0, anchor.getDy1()); - assertEquals(100, anchor.getDy2()); - cAnchor = (HSSFClientAnchor) anchor; - assertEquals(1, cAnchor.getCol1()); - assertEquals(1, cAnchor.getCol2()); - assertEquals(1, cAnchor.getRow1()); - assertEquals(1, cAnchor.getRow2()); - - hssfShape = children.get(2); - assertTrue(hssfShape instanceof HSSFSimpleShape); - anchor = hssfShape.getAnchor(); - assertTrue(anchor instanceof HSSFClientAnchor); - assertEquals(0, anchor.getDx1()); - assertEquals(512, anchor.getDx2()); - assertEquals(0, anchor.getDy1()); - assertEquals(100, anchor.getDy2()); - cAnchor = (HSSFClientAnchor) anchor; - assertEquals(2, cAnchor.getCol1()); - assertEquals(2, cAnchor.getCol2()); - assertEquals(2, cAnchor.getRow1()); - assertEquals(2, cAnchor.getRow2()); - - hssfShape = children.get(3); - assertTrue(hssfShape instanceof HSSFSimpleShape); - anchor = hssfShape.getAnchor(); - assertTrue(anchor instanceof HSSFClientAnchor); - assertEquals(0, anchor.getDx1()); - assertEquals(512, anchor.getDx2()); - assertEquals(100, anchor.getDy1()); - assertEquals(200, anchor.getDy2()); - cAnchor = (HSSFClientAnchor) anchor; - assertEquals(2, cAnchor.getCol1()); - assertEquals(2, cAnchor.getCol2()); - assertEquals(2, cAnchor.getRow1()); - assertEquals(2, cAnchor.getRow2()); - - wbBack.close(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/model/TestEscherRecordFactory.java b/src/testcases/org/apache/poi/hssf/model/TestEscherRecordFactory.java deleted file mode 100644 index 7b1c2078c..000000000 --- a/src/testcases/org/apache/poi/hssf/model/TestEscherRecordFactory.java +++ /dev/null @@ -1,99 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.model; - -import junit.framework.TestCase; -import org.apache.poi.ddf.DefaultEscherRecordFactory; -import org.apache.poi.ddf.EscherContainerRecord; -import org.apache.poi.ddf.EscherTextboxRecord; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.record.EscherAggregate; -import org.apache.poi.hssf.record.Record; -import org.apache.poi.hssf.record.RecordBase; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFTestHelper; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.Arrays; -import java.util.List; -import java.util.Random; - -/** - * @author Evgeniy Berlog - * @date 18.06.12 - */ -public class TestEscherRecordFactory extends TestCase{ - - private static byte[] toByteArray(List records) { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - for (RecordBase rb : records) { - Record r = (Record) rb; - try { - out.write(r.serialize()); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - return out.toByteArray(); - } - - public void testDetectContainer() { - Random rnd = new Random(); - assertEquals(true, DefaultEscherRecordFactory.isContainer((short) 0x0, EscherContainerRecord.DG_CONTAINER)); - assertEquals(true, DefaultEscherRecordFactory.isContainer((short) 0x0, EscherContainerRecord.SOLVER_CONTAINER)); - assertEquals(true, DefaultEscherRecordFactory.isContainer((short) 0x0, EscherContainerRecord.SP_CONTAINER)); - assertEquals(true, DefaultEscherRecordFactory.isContainer((short) 0x0, EscherContainerRecord.DGG_CONTAINER)); - assertEquals(true, DefaultEscherRecordFactory.isContainer((short) 0x0, EscherContainerRecord.BSTORE_CONTAINER)); - assertEquals(true, DefaultEscherRecordFactory.isContainer((short) 0x0, EscherContainerRecord.SPGR_CONTAINER)); - - for (Short i=EscherContainerRecord.DGG_CONTAINER; i<= EscherContainerRecord.SOLVER_CONTAINER; i++){ - assertEquals(true, DefaultEscherRecordFactory.isContainer(Integer.valueOf(rnd.nextInt(Short.MAX_VALUE)).shortValue(), i)); - } - - assertEquals(false, DefaultEscherRecordFactory.isContainer((short) 0x0, Integer.valueOf(EscherContainerRecord.DGG_CONTAINER-1).shortValue())); - assertEquals(false, DefaultEscherRecordFactory.isContainer((short) 0x0, Integer.valueOf(EscherContainerRecord.SOLVER_CONTAINER+1).shortValue())); - - assertEquals(true, DefaultEscherRecordFactory.isContainer((short) 0x000F, Integer.valueOf(EscherContainerRecord.DGG_CONTAINER-1).shortValue())); - assertEquals(true, DefaultEscherRecordFactory.isContainer((short) 0xFFFF, Integer.valueOf(EscherContainerRecord.DGG_CONTAINER-1).shortValue())); - assertEquals(false, DefaultEscherRecordFactory.isContainer((short) 0x000C, Integer.valueOf(EscherContainerRecord.DGG_CONTAINER-1).shortValue())); - assertEquals(false, DefaultEscherRecordFactory.isContainer((short) 0xCCCC, Integer.valueOf(EscherContainerRecord.DGG_CONTAINER-1).shortValue())); - assertEquals(false, DefaultEscherRecordFactory.isContainer((short) 0x000F, EscherTextboxRecord.RECORD_ID)); - assertEquals(false, DefaultEscherRecordFactory.isContainer((short) 0xCCCC, EscherTextboxRecord.RECORD_ID)); - } - - public void testDgContainerMustBeRootOfHSSFSheetEscherRecords() throws IOException { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("47251.xls"); - HSSFSheet sh = wb.getSheetAt(0); - InternalSheet ish = HSSFTestHelper.getSheetForTest(sh); - List records = ish.getRecords(); - // records to be aggregated - List dgRecords = records.subList(19, 23); - byte[] dgBytes = toByteArray(dgRecords); - sh.getDrawingPatriarch(); - EscherAggregate agg = (EscherAggregate) ish.findFirstRecordBySid(EscherAggregate.sid); - assertEquals(true, agg.getEscherRecords().get(0) instanceof EscherContainerRecord); - assertEquals(EscherContainerRecord.DG_CONTAINER, agg.getEscherRecords().get(0).getRecordId()); - assertEquals((short) 0x0, agg.getEscherRecords().get(0).getOptions()); - agg = (EscherAggregate) ish.findFirstRecordBySid(EscherAggregate.sid); - byte[] dgBytesAfterSave = agg.serialize(); - assertEquals("different size of drawing data before and after save", dgBytes.length, dgBytesAfterSave.length); - assertTrue("drawing data before and after save is different", Arrays.equals(dgBytes, dgBytesAfterSave)); - } -} diff --git a/src/testcases/org/apache/poi/hssf/model/TestFormulaParser.java b/src/testcases/org/apache/poi/hssf/model/TestFormulaParser.java deleted file mode 100644 index a6cb27343..000000000 --- a/src/testcases/org/apache/poi/hssf/model/TestFormulaParser.java +++ /dev/null @@ -1,1625 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.model; - -import static org.junit.Assert.*; - -import java.io.IOException; -import java.util.Locale; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.record.NameRecord; -import org.apache.poi.hssf.record.common.UnicodeString; -import org.apache.poi.hssf.usermodel.FormulaExtractor; -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFEvaluationWorkbook; -import org.apache.poi.hssf.usermodel.HSSFName; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.hssf.usermodel.TestHSSFName; -import org.apache.poi.ss.formula.FormulaParseException; -import org.apache.poi.ss.formula.FormulaParser; -import org.apache.poi.ss.formula.FormulaType; -import org.apache.poi.ss.formula.constant.ErrorConstant; -import org.apache.poi.ss.formula.ptg.AbstractFunctionPtg; -import org.apache.poi.ss.formula.ptg.AddPtg; -import org.apache.poi.ss.formula.ptg.Area3DPtg; -import org.apache.poi.ss.formula.ptg.AreaI; -import org.apache.poi.ss.formula.ptg.AreaPtg; -import org.apache.poi.ss.formula.ptg.AreaPtgBase; -import org.apache.poi.ss.formula.ptg.ArrayPtg; -import org.apache.poi.ss.formula.ptg.AttrPtg; -import org.apache.poi.ss.formula.ptg.BoolPtg; -import org.apache.poi.ss.formula.ptg.ConcatPtg; -import org.apache.poi.ss.formula.ptg.DividePtg; -import org.apache.poi.ss.formula.ptg.EqualPtg; -import org.apache.poi.ss.formula.ptg.ErrPtg; -import org.apache.poi.ss.formula.ptg.FuncPtg; -import org.apache.poi.ss.formula.ptg.FuncVarPtg; -import org.apache.poi.ss.formula.ptg.GreaterThanPtg; -import org.apache.poi.ss.formula.ptg.IntPtg; -import org.apache.poi.ss.formula.ptg.IntersectionPtg; -import org.apache.poi.ss.formula.ptg.MemAreaPtg; -import org.apache.poi.ss.formula.ptg.MemFuncPtg; -import org.apache.poi.ss.formula.ptg.MissingArgPtg; -import org.apache.poi.ss.formula.ptg.MultiplyPtg; -import org.apache.poi.ss.formula.ptg.NamePtg; -import org.apache.poi.ss.formula.ptg.NameXPtg; -import org.apache.poi.ss.formula.ptg.NumberPtg; -import org.apache.poi.ss.formula.ptg.ParenthesisPtg; -import org.apache.poi.ss.formula.ptg.PercentPtg; -import org.apache.poi.ss.formula.ptg.PowerPtg; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.apache.poi.ss.formula.ptg.RangePtg; -import org.apache.poi.ss.formula.ptg.Ref3DPtg; -import org.apache.poi.ss.formula.ptg.RefPtg; -import org.apache.poi.ss.formula.ptg.StringPtg; -import org.apache.poi.ss.formula.ptg.SubtractPtg; -import org.apache.poi.ss.formula.ptg.UnaryMinusPtg; -import org.apache.poi.ss.formula.ptg.UnaryPlusPtg; -import org.apache.poi.ss.formula.ptg.UnionPtg; -import org.apache.poi.ss.usermodel.BaseTestBugzillaIssues; -import org.apache.poi.ss.usermodel.FormulaError; -import org.apache.poi.ss.usermodel.Name; -import org.apache.poi.util.HexRead; -import org.apache.poi.util.LittleEndianByteArrayInputStream; -import org.junit.Test; - -/** - * Test the low level formula parser functionality. High level tests are to - * be done via usermodel/HSSFCell.setFormulaValue(). - */ -public final class TestFormulaParser { - - /** - * @return parsed token array already confirmed not null - */ - /* package */ static Ptg[] parseFormula(String formula) { - Ptg[] result = HSSFFormulaParser.parse(formula, (HSSFWorkbook)null); - assertNotNull("Ptg array should not be null", result); - return result; - } - private static String toFormulaString(Ptg[] ptgs) { - return HSSFFormulaParser.toFormulaString((HSSFWorkbook)null, ptgs); - } - - @Test - public void testSimpleFormula() { - confirmTokenClasses("2+2",IntPtg.class, IntPtg.class, AddPtg.class); - } - - @Test - public void testFormulaWithSpace1() { - confirmTokenClasses(" 2 + 2 ",IntPtg.class, IntPtg.class, AddPtg.class); - } - - @Test - public void testFormulaWithSpace2() { - Ptg[] ptgs = parseFormula("2+ sum( 3 , 4) "); - assertEquals(5, ptgs.length); - } - - @Test - public void testFormulaWithSpaceNRef() { - Ptg[] ptgs = parseFormula("sum( A2:A3 )"); - assertEquals(2, ptgs.length); - } - - @Test - public void testFormulaWithString() { - Ptg[] ptgs = parseFormula("\"hello\" & \"world\" "); - assertEquals(3, ptgs.length); - } - - @Test - public void testTRUE() { - Ptg[] ptgs = parseFormula("TRUE"); - assertEquals(1, ptgs.length); - BoolPtg flag = (BoolPtg) ptgs[0]; - assertEquals(true, flag.getValue()); - } - - @Test - public void testSumIf() { - Ptg[] ptgs = parseFormula("SUMIF(A1:A5,\">4000\",B1:B5)"); - assertEquals(4, ptgs.length); - } - - /** - * Bug Reported by xt-jens.riis@nokia.com (Jens Riis) - * Refers to Bug #17582 - * - */ - @Test - public void testNonAlphaFormula() { - Ptg[] ptgs = parseFormula("\"TOTAL[\"&F3&\"]\""); - confirmTokenClasses(ptgs, StringPtg.class, RefPtg.class, ConcatPtg.class, StringPtg.class, ConcatPtg.class); - assertEquals("TOTAL[", ((StringPtg)ptgs[0]).getValue()); - } - - @Test - public void testMacroFunction() throws IOException { - // testNames.xls contains a VB function called 'myFunc' - final String testFile = "testNames.xls"; - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook(testFile); - try { - HSSFEvaluationWorkbook book = HSSFEvaluationWorkbook.create(wb); - - //Expected ptg stack: [NamePtg(myFunc), StringPtg(arg), (additional operands go here...), FunctionPtg(myFunc)] - Ptg[] ptg = FormulaParser.parse("myFunc(\"arg\")", book, FormulaType.CELL, -1); - assertEquals(3, ptg.length); - - // the name gets encoded as the first operand on the stack - NamePtg tname = (NamePtg) ptg[0]; - assertEquals("myFunc", tname.toFormulaString(book)); - - // the function's arguments are pushed onto the stack from left-to-right as OperandPtgs - StringPtg arg = (StringPtg) ptg[1]; - assertEquals("arg", arg.getValue()); - - // The external FunctionPtg is the last Ptg added to the stack - // During formula evaluation, this Ptg pops off the the appropriate number of - // arguments (getNumberOfOperands()) and pushes the result on the stack - AbstractFunctionPtg tfunc = (AbstractFunctionPtg) ptg[2]; //FuncVarPtg - assertTrue(tfunc.isExternalFunction()); - - // confirm formula parsing is case-insensitive - FormulaParser.parse("mYfUnC(\"arg\")", book, FormulaType.CELL, -1); - - // confirm formula parsing doesn't care about argument count or type - // this should only throw an error when evaluating the formula. - FormulaParser.parse("myFunc()", book, FormulaType.CELL, -1); - FormulaParser.parse("myFunc(\"arg\", 0, TRUE)", book, FormulaType.CELL, -1); - - // A completely unknown formula name (not saved in workbook) should still be parseable and renderable - // but will throw an NotImplementedFunctionException or return a #NAME? error value if evaluated. - FormulaParser.parse("yourFunc(\"arg\")", book, FormulaType.CELL, -1); - - // Verify that myFunc and yourFunc were successfully added to Workbook names - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb); - try { - // HSSFWorkbook/EXCEL97-specific side-effects user-defined function names must be added to Workbook's defined names in order to be saved. - assertNotNull(wb2.getName("myFunc")); - assertEqualsIgnoreCase("myFunc", wb2.getName("myFunc").getNameName()); - assertNotNull(wb2.getName("yourFunc")); - assertEqualsIgnoreCase("yourFunc", wb2.getName("yourFunc").getNameName()); - - // Manually check to make sure file isn't corrupted - // TODO: develop a process for occasionally manually reviewing workbooks - // to verify workbooks are not corrupted - /* - final File fileIn = HSSFTestDataSamples.getSampleFile(testFile); - final File reSavedFile = new File(fileIn.getParentFile(), fileIn.getName().replace(".xls", "-saved.xls")); - FileOutputStream fos = new FileOutputStream(reSavedFile); - wb2.write(fos); - fos.close(); - */ - } finally { - wb2.close(); - } - } finally { - wb.close(); - } - } - - private static void assertEqualsIgnoreCase(String expected, String actual) { - assertEquals(expected.toLowerCase(Locale.ROOT), actual.toLowerCase(Locale.ROOT)); - } - - @Test - public void testEmbeddedSlash() { - confirmTokenClasses("HYPERLINK(\"http://www.jakarta.org\",\"Jakarta\")", - StringPtg.class, StringPtg.class, FuncVarPtg.class); - } - - @Test - public void testConcatenate() { - confirmTokenClasses("CONCATENATE(\"first\",\"second\")", - StringPtg.class, StringPtg.class, FuncVarPtg.class); - } - - @Test - public void testWorksheetReferences() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - - wb.createSheet("NoQuotesNeeded"); - wb.createSheet("Quotes Needed Here &#$@"); - - HSSFSheet sheet = wb.createSheet("Test"); - HSSFRow row = sheet.createRow(0); - HSSFCell cell; - - cell = row.createCell(0); - cell.setCellFormula("NoQuotesNeeded!A1"); - - cell = row.createCell(1); - cell.setCellFormula("'Quotes Needed Here &#$@'!A1"); - - wb.close(); - } - - @Test - public void testUnaryMinus() { - confirmTokenClasses("-A1", RefPtg.class, UnaryMinusPtg.class); - } - - @Test - public void testUnaryPlus() { - confirmTokenClasses("+A1", RefPtg.class, UnaryPlusPtg.class); - } - - /** - * There may be multiple ways to encode an expression involving {@link UnaryPlusPtg} - * or {@link UnaryMinusPtg}. These may be perfectly equivalent from a formula - * evaluation perspective, or formula rendering. However, differences in the way - * POI encodes formulas may cause unnecessary confusion. These non-critical tests - * check that POI follows the same encoding rules as Excel. - */ - @Test - public void testExactEncodingOfUnaryPlusAndMinus() { - // as tested in Excel: - confirmUnary("-3", -3, NumberPtg.class); - confirmUnary("--4", -4, NumberPtg.class, UnaryMinusPtg.class); - confirmUnary("+++5", 5, IntPtg.class, UnaryPlusPtg.class, UnaryPlusPtg.class); - confirmUnary("++-6", -6, NumberPtg.class, UnaryPlusPtg.class, UnaryPlusPtg.class); - - // Spaces muck things up a bit. It would be clearer why the following cases are - // reasonable if POI encoded tAttrSpace in the right places. - // Otherwise these differences look capricious. - confirmUnary("+ 12", 12, IntPtg.class, UnaryPlusPtg.class); - confirmUnary("- 13", 13, IntPtg.class, UnaryMinusPtg.class); - } - - private static void confirmUnary(String formulaText, double val, Class...expectedTokenTypes) { - Ptg[] ptgs = parseFormula(formulaText); - confirmTokenClasses(ptgs, expectedTokenTypes); - Ptg ptg0 = ptgs[0]; - if (ptg0 instanceof IntPtg) { - IntPtg intPtg = (IntPtg) ptg0; - assertEquals((int)val, intPtg.getValue()); - } else if (ptg0 instanceof NumberPtg) { - NumberPtg numberPtg = (NumberPtg) ptg0; - assertEquals(val, numberPtg.getValue(), 0.0); - } else { - fail("bad ptg0 " + ptg0); - } - } - - @Test - public void testLeadingSpaceInString() { - String value = " hi "; - Ptg[] ptgs = parseFormula("\"" + value + "\""); - confirmTokenClasses(ptgs, StringPtg.class); - assertTrue("ptg0 contains exact value", ((StringPtg)ptgs[0]).getValue().equals(value)); - } - - @Test - public void testLookupAndMatchFunctionArgs() { - Ptg[] ptgs = parseFormula("lookup(A1, A3:A52, B3:B52)"); - confirmTokenClasses(ptgs, RefPtg.class, AreaPtg.class, AreaPtg.class, FuncVarPtg.class); - assertTrue("ptg0 has Value class", ptgs[0].getPtgClass() == Ptg.CLASS_VALUE); - - ptgs = parseFormula("match(A1, A3:A52)"); - confirmTokenClasses(ptgs, RefPtg.class, AreaPtg.class, FuncVarPtg.class); - assertTrue("ptg0 has Value class", ptgs[0].getPtgClass() == Ptg.CLASS_VALUE); - } - - /** bug 33160*/ - @Test - public void testLargeInt() { - confirmTokenClasses("40", IntPtg.class); - confirmTokenClasses("40000", IntPtg.class); - } - - /** bug 33160 */ - @Test - public void testSimpleLongFormula() { - confirmTokenClasses("40000/2", IntPtg.class, IntPtg.class, DividePtg.class); - } - - /** bug 35027, underscore in sheet name */ - @Test - public void testUnderscore() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - - wb.createSheet("Cash_Flow"); - - HSSFSheet sheet = wb.createSheet("Test"); - HSSFRow row = sheet.createRow(0); - HSSFCell cell; - - cell = row.createCell(0); - cell.setCellFormula("Cash_Flow!A1"); - - wb.close(); - } - - /** bug 49725, defined names with underscore */ - @Test - public void testNamesWithUnderscore() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); //or new XSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("NamesWithUnderscore"); - - HSSFName nm; - - nm = wb.createName(); - nm.setNameName("DA6_LEO_WBS_Number"); - nm.setRefersToFormula("33"); - - nm = wb.createName(); - nm.setNameName("DA6_LEO_WBS_Name"); - nm.setRefersToFormula("33"); - - nm = wb.createName(); - nm.setNameName("A1_"); - nm.setRefersToFormula("22"); - - nm = wb.createName(); - nm.setNameName("_A1"); - nm.setRefersToFormula("11"); - - nm = wb.createName(); - nm.setNameName("A_1"); - nm.setRefersToFormula("44"); - - nm = wb.createName(); - nm.setNameName("A_1_"); - nm.setRefersToFormula("44"); - - HSSFRow row = sheet.createRow(0); - HSSFCell cell = row.createCell(0); - - cell.setCellFormula("DA6_LEO_WBS_Number*2"); - assertEquals("DA6_LEO_WBS_Number*2", cell.getCellFormula()); - - cell.setCellFormula("(A1_*_A1+A_1)/A_1_"); - assertEquals("(A1_*_A1+A_1)/A_1_", cell.getCellFormula()); - - cell.setCellFormula("INDEX(DA6_LEO_WBS_Name,MATCH($A3,DA6_LEO_WBS_Number,0))"); - assertEquals("INDEX(DA6_LEO_WBS_Name,MATCH($A3,DA6_LEO_WBS_Number,0))", cell.getCellFormula()); - - wb.close(); - } - - // bug 38396 : Formula with exponential numbers not parsed correctly. - @Test - public void testExponentialParsing() { - confirmTokenClasses("1.3E21/2", NumberPtg.class, IntPtg.class, DividePtg.class); - confirmTokenClasses("1322E21/2", NumberPtg.class, IntPtg.class, DividePtg.class); - confirmTokenClasses("1.3E1/2", NumberPtg.class, IntPtg.class, DividePtg.class); - } - - @Test - public void testExponentialInSheet() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - - wb.createSheet("Cash_Flow"); - - HSSFSheet sheet = wb.createSheet("Test"); - HSSFRow row = sheet.createRow(0); - HSSFCell cell = row.createCell(0); - String formula; - - cell.setCellFormula("1.3E21/3"); - formula = cell.getCellFormula(); - assertEquals("Exponential formula string", "1.3E+21/3", formula); - - cell.setCellFormula("-1.3E21/3"); - formula = cell.getCellFormula(); - assertEquals("Exponential formula string", "-1.3E+21/3", formula); - - cell.setCellFormula("1322E21/3"); - formula = cell.getCellFormula(); - assertEquals("Exponential formula string", "1.322E+24/3", formula); - - cell.setCellFormula("-1322E21/3"); - formula = cell.getCellFormula(); - assertEquals("Exponential formula string", "-1.322E+24/3", formula); - - cell.setCellFormula("1.3E1/3"); - formula = cell.getCellFormula(); - assertEquals("Exponential formula string", "13/3", formula); - - cell.setCellFormula("-1.3E1/3"); - formula = cell.getCellFormula(); - assertEquals("Exponential formula string", "-13/3", formula); - - cell.setCellFormula("1.3E-4/3"); - formula = cell.getCellFormula(); - assertEquals("Exponential formula string", "0.00013/3", formula); - - cell.setCellFormula("-1.3E-4/3"); - formula = cell.getCellFormula(); - assertEquals("Exponential formula string", "-0.00013/3", formula); - - cell.setCellFormula("13E-15/3"); - formula = cell.getCellFormula(); - assertEquals("Exponential formula string", "0.000000000000013/3", formula); - - cell.setCellFormula("-13E-15/3"); - formula = cell.getCellFormula(); - assertEquals("Exponential formula string", "-0.000000000000013/3", formula); - - cell.setCellFormula("1.3E3/3"); - formula = cell.getCellFormula(); - assertEquals("Exponential formula string", "1300/3", formula); - - cell.setCellFormula("-1.3E3/3"); - formula = cell.getCellFormula(); - assertEquals("Exponential formula string", "-1300/3", formula); - - cell.setCellFormula("1300000000000000/3"); - formula = cell.getCellFormula(); - assertEquals("Exponential formula string", "1300000000000000/3", formula); - - cell.setCellFormula("-1300000000000000/3"); - formula = cell.getCellFormula(); - assertEquals("Exponential formula string", "-1300000000000000/3", formula); - - cell.setCellFormula("-10E-1/3.1E2*4E3/3E4"); - formula = cell.getCellFormula(); - assertEquals("Exponential formula string", "-1/310*4000/30000", formula); - - wb.close(); - } - - @Test - public void testNumbers() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - - wb.createSheet("Cash_Flow"); - - HSSFSheet sheet = wb.createSheet("Test"); - HSSFRow row = sheet.createRow(0); - HSSFCell cell = row.createCell(0); - String formula; - - // starts from decimal point - - cell.setCellFormula(".1"); - formula = cell.getCellFormula(); - assertEquals("0.1", formula); - - cell.setCellFormula("+.1"); - formula = cell.getCellFormula(); - assertEquals("0.1", formula); - - cell.setCellFormula("-.1"); - formula = cell.getCellFormula(); - assertEquals("-0.1", formula); - - // has exponent - - cell.setCellFormula("10E1"); - formula = cell.getCellFormula(); - assertEquals("100", formula); - - cell.setCellFormula("10E+1"); - formula = cell.getCellFormula(); - assertEquals("100", formula); - - cell.setCellFormula("10E-1"); - formula = cell.getCellFormula(); - assertEquals("1", formula); - - wb.close(); - } - - @Test - public void testRanges() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - - wb.createSheet("Cash_Flow"); - - HSSFSheet sheet = wb.createSheet("Test"); - HSSFRow row = sheet.createRow(0); - HSSFCell cell = row.createCell(0); - String formula; - - cell.setCellFormula("A1.A2"); - formula = cell.getCellFormula(); - assertEquals("A1:A2", formula); - - cell.setCellFormula("A1..A2"); - formula = cell.getCellFormula(); - assertEquals("A1:A2", formula); - - cell.setCellFormula("A1...A2"); - formula = cell.getCellFormula(); - assertEquals("A1:A2", formula); - - wb.close(); - } - - @Test - public void testMultiSheetReference() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - - wb.createSheet("Cash_Flow"); - wb.createSheet("Test Sheet"); - - HSSFSheet sheet = wb.createSheet("Test"); - HSSFRow row = sheet.createRow(0); - HSSFCell cell = row.createCell(0); - String formula; - - - // References to a single cell: - - // One sheet - cell.setCellFormula("Cash_Flow!A1"); - formula = cell.getCellFormula(); - assertEquals("Cash_Flow!A1", formula); - - // Then the other - cell.setCellFormula("\'Test Sheet\'!A1"); - formula = cell.getCellFormula(); - assertEquals("\'Test Sheet\'!A1", formula); - - // Now both - cell.setCellFormula("Cash_Flow:\'Test Sheet\'!A1"); - formula = cell.getCellFormula(); - assertEquals("Cash_Flow:\'Test Sheet\'!A1", formula); - - - // References to a range (area) of cells: - - // One sheet - cell.setCellFormula("Cash_Flow!A1:B2"); - formula = cell.getCellFormula(); - assertEquals("Cash_Flow!A1:B2", formula); - - // Then the other - cell.setCellFormula("\'Test Sheet\'!A1:B2"); - formula = cell.getCellFormula(); - assertEquals("\'Test Sheet\'!A1:B2", formula); - - // Now both - cell.setCellFormula("Cash_Flow:\'Test Sheet\'!A1:B2"); - formula = cell.getCellFormula(); - assertEquals("Cash_Flow:\'Test Sheet\'!A1:B2", formula); - - wb.close(); - } - - /** - * Test for bug observable at svn revision 618865 (5-Feb-2008)
    - * a formula consisting of a single no-arg function got rendered without the function braces - */ - @Test - public void testToFormulaStringZeroArgFunction() throws IOException { - HSSFWorkbook book = new HSSFWorkbook(); - - Ptg[] ptgs = { - FuncPtg.create(10), - }; - assertEquals("NA()", HSSFFormulaParser.toFormulaString(book, ptgs)); - - book.close(); - } - - @Test - public void testPercent() { - - confirmTokenClasses("5%", IntPtg.class, PercentPtg.class); - // spaces OK - confirmTokenClasses(" 250 % ", IntPtg.class, PercentPtg.class); - // double percent OK - confirmTokenClasses("12345.678%%", NumberPtg.class, PercentPtg.class, PercentPtg.class); - - // percent of a bracketed expression - confirmTokenClasses("(A1+35)%*B1%", RefPtg.class, IntPtg.class, AddPtg.class, ParenthesisPtg.class, - PercentPtg.class, RefPtg.class, PercentPtg.class, MultiplyPtg.class); - - // percent of a text quantity - confirmTokenClasses("\"8.75\"%", StringPtg.class, PercentPtg.class); - - // percent to the power of - confirmTokenClasses("50%^3", IntPtg.class, PercentPtg.class, IntPtg.class, PowerPtg.class); - - // things that parse OK but would *evaluate* to an error - confirmTokenClasses("\"abc\"%", StringPtg.class, PercentPtg.class); - confirmTokenClasses("#N/A%", ErrPtg.class, PercentPtg.class); - } - - /** - * Tests combinations of various operators in the absence of brackets - */ - @Test - public void testPrecedenceAndAssociativity() { - - // TRUE=TRUE=2=2 evaluates to FALSE - confirmTokenClasses("TRUE=TRUE=2=2", BoolPtg.class, BoolPtg.class, EqualPtg.class, - IntPtg.class, EqualPtg.class, IntPtg.class, EqualPtg.class); - - // 2^3^2 evaluates to 64 not 512 - confirmTokenClasses("2^3^2", IntPtg.class, IntPtg.class, PowerPtg.class, - IntPtg.class, PowerPtg.class); - - // "abc" & 2 + 3 & "def" evaluates to "abc5def" - confirmTokenClasses("\"abc\"&2+3&\"def\"", StringPtg.class, IntPtg.class, IntPtg.class, - AddPtg.class, ConcatPtg.class, StringPtg.class, ConcatPtg.class); - - // (1 / 2) - (3 * 4) - confirmTokenClasses("1/2-3*4", IntPtg.class, IntPtg.class, DividePtg.class, - IntPtg.class, IntPtg.class, MultiplyPtg.class, SubtractPtg.class); - - // 2 * (2^2) - // NOT: (2 *2) ^ 2 -> int int multiply int power - confirmTokenClasses("2*2^2", IntPtg.class, IntPtg.class, IntPtg.class, PowerPtg.class, MultiplyPtg.class); - - // 2^200% -> 2 not 1.6E58 - confirmTokenClasses("2^200%", IntPtg.class, IntPtg.class, PercentPtg.class, PowerPtg.class); - } - - /* package */ static Ptg[] confirmTokenClasses(String formula, Class...expectedClasses) { - Ptg[] ptgs = parseFormula(formula); - confirmTokenClasses(ptgs, expectedClasses); - return ptgs; - } - - private static void confirmTokenClasses(Ptg[] ptgs, Class...expectedClasses) { - assertEquals(expectedClasses.length, ptgs.length); - for (int i = 0; i < expectedClasses.length; i++) { - if(expectedClasses[i] != ptgs[i].getClass()) { - fail("difference at token[" + i + "]: expected (" - + expectedClasses[i].getName() + ") but got (" - + ptgs[i].getClass().getName() + ")"); - } - } - } - - @Test - public void testPower() { - confirmTokenClasses("2^5", IntPtg.class, IntPtg.class, PowerPtg.class); - } - - private static Ptg parseSingleToken(String formula, Class ptgClass) { - Ptg[] ptgs = parseFormula(formula); - assertEquals(1, ptgs.length); - Ptg result = ptgs[0]; - assertEquals(ptgClass, result.getClass()); - return result; - } - - @Test - public void testParseNumber() { - IntPtg ip; - - // bug 33160 - ip = (IntPtg) parseSingleToken("40", IntPtg.class); - assertEquals(40, ip.getValue()); - ip = (IntPtg) parseSingleToken("40000", IntPtg.class); - assertEquals(40000, ip.getValue()); - - // check the upper edge of the IntPtg range: - ip = (IntPtg) parseSingleToken("65535", IntPtg.class); - assertEquals(65535, ip.getValue()); - NumberPtg np = (NumberPtg) parseSingleToken("65536", NumberPtg.class); - assertEquals(65536, np.getValue(), 0); - - np = (NumberPtg) parseSingleToken("65534.6", NumberPtg.class); - assertEquals(65534.6, np.getValue(), 0); - } - - @Test - public void testMissingArgs() { - confirmTokenClasses("if(A1, ,C1)", - RefPtg.class, - AttrPtg.class, // tAttrIf - MissingArgPtg.class, - AttrPtg.class, // tAttrSkip - RefPtg.class, - AttrPtg.class, // tAttrSkip - FuncVarPtg.class - ); - - confirmTokenClasses("counta( , A1:B2, )", MissingArgPtg.class, AreaPtg.class, MissingArgPtg.class, - FuncVarPtg.class); - } - - @Test - public void testParseErrorLiterals() { - - confirmParseErrorLiteral(ErrPtg.NULL_INTERSECTION, "#NULL!"); - confirmParseErrorLiteral(ErrPtg.DIV_ZERO, "#DIV/0!"); - confirmParseErrorLiteral(ErrPtg.VALUE_INVALID, "#VALUE!"); - confirmParseErrorLiteral(ErrPtg.REF_INVALID, "#REF!"); - confirmParseErrorLiteral(ErrPtg.NAME_INVALID, "#NAME?"); - confirmParseErrorLiteral(ErrPtg.NUM_ERROR, "#NUM!"); - confirmParseErrorLiteral(ErrPtg.N_A, "#N/A"); - parseFormula("HLOOKUP(F7,#REF!,G7,#REF!)"); - } - - private static void confirmParseErrorLiteral(ErrPtg expectedToken, String formula) { - assertEquals(expectedToken, parseSingleToken(formula, ErrPtg.class)); - } - - /** - * To aid readability the parameters have been encoded with single quotes instead of double - * quotes. This method converts single quotes to double quotes before performing the parse - * and result check. - */ - private static void confirmStringParse(String singleQuotedValue) { - // formula: internal quotes become double double, surround with double quotes - String formula = '"' + singleQuotedValue.replaceAll("'", "\"\"") + '"'; - String expectedValue = singleQuotedValue.replace('\'', '"'); - - StringPtg sp = (StringPtg) parseSingleToken(formula, StringPtg.class); - assertEquals(expectedValue, sp.getValue()); - } - - @Test - public void testParseStringLiterals_bug28754() throws IOException { - - StringPtg sp; - try { - sp = (StringPtg) parseSingleToken("\"test\"\"ing\"", StringPtg.class); - } catch (RuntimeException e) { - if(e.getMessage().startsWith("Cannot Parse")) { - fail("Identified bug 28754a"); - } - throw e; - } - assertEquals("test\"ing", sp.getValue()); - - HSSFWorkbook wb = new HSSFWorkbook(); - try { - HSSFSheet sheet = wb.createSheet(); - wb.setSheetName(0, "Sheet1"); - - HSSFRow row = sheet.createRow(0); - HSSFCell cell = row.createCell(0); - cell.setCellFormula("right(\"test\"\"ing\", 3)"); - String actualCellFormula = cell.getCellFormula(); - if("RIGHT(\"test\"ing\",3)".equals(actualCellFormula)) { - fail("Identified bug 28754b"); - } - assertEquals("RIGHT(\"test\"\"ing\",3)", actualCellFormula); - } finally { - wb.close(); - } - } - - @Test - public void testParseStringLiterals() { - confirmStringParse("goto considered harmful"); - - confirmStringParse("goto 'considered' harmful"); - - confirmStringParse(""); - confirmStringParse("'"); - confirmStringParse("''"); - confirmStringParse("' '"); - confirmStringParse(" ' "); - } - - @Test - public void testParseSumIfSum() { - String formulaString; - Ptg[] ptgs; - ptgs = parseFormula("sum(5, 2, if(3>2, sum(A1:A2), 6))"); - formulaString = toFormulaString(ptgs); - assertEquals("SUM(5,2,IF(3>2,SUM(A1:A2),6))", formulaString); - - ptgs = parseFormula("if(1<2,sum(5, 2, if(3>2, sum(A1:A2), 6)),4)"); - formulaString = toFormulaString(ptgs); - assertEquals("IF(1<2,SUM(5,2,IF(3>2,SUM(A1:A2),6)),4)", formulaString); - } - - @Test - public void testParserErrors() { - parseExpectedException(" 12 . 345 "); - parseExpectedException("1 .23 "); - - parseExpectedException("sum(#NAME)"); - parseExpectedException("1 + #N / A * 2"); - parseExpectedException("#value?"); - parseExpectedException("#DIV/ 0+2"); - - - parseExpectedException("IF(TRUE)"); - parseExpectedException("countif(A1:B5, C1, D1)"); - - parseExpectedException("("); - parseExpectedException(")"); - parseExpectedException("+"); - parseExpectedException("42+"); - - parseExpectedException("IF("); - } - - private static void parseExpectedException(String formula) { - try { - parseFormula(formula); - fail("Expected FormulaParseException: " + formula); - } catch (FormulaParseException e) { - // expected during successful test - assertNotNull(e.getMessage()); - } - } - - @Test - public void testSetFormulaWithRowBeyond32768_Bug44539() throws IOException { - - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet(); - wb.setSheetName(0, "Sheet1"); - - HSSFRow row = sheet.createRow(0); - HSSFCell cell = row.createCell(0); - cell.setCellFormula("SUM(A32769:A32770)"); - if("SUM(A-32767:A-32766)".equals(cell.getCellFormula())) { - fail("Identified bug 44539"); - } - assertEquals("SUM(A32769:A32770)", cell.getCellFormula()); - - wb.close(); - } - - @Test - public void testSpaceAtStartOfFormula() { - // Simulating cell formula of "= 4" (note space) - // The same Ptg array can be observed if an excel file is saved with that exact formula - - AttrPtg spacePtg = AttrPtg.createSpace(AttrPtg.SpaceType.SPACE_BEFORE, 1); - Ptg[] ptgs = { spacePtg, new IntPtg(4), }; - String formulaString; - try { - formulaString = toFormulaString(ptgs); - } catch (IllegalStateException e) { - if(e.getMessage().equalsIgnoreCase("too much stuff left on the stack")) { - fail("Identified bug 44609"); - } - // else some unexpected error - throw e; - } - // FormulaParser strips spaces anyway - assertEquals("4", formulaString); - - ptgs = new Ptg[] { new IntPtg(3), spacePtg, new IntPtg(4), spacePtg, AddPtg.instance, }; - formulaString = toFormulaString(ptgs); - assertEquals("3+4", formulaString); - } - - /** - * Checks some internal error detecting logic ('stack underflow error' in toFormulaString) - */ - @Test - public void testTooFewOperandArgs() { - // Simulating badly encoded cell formula of "=/1" - // Not sure if Excel could ever produce this - Ptg[] ptgs = { - // Excel would probably have put tMissArg here - new IntPtg(1), - DividePtg.instance, - }; - try { - toFormulaString(ptgs); - fail("Expected exception was not thrown"); - } catch (IllegalStateException e) { - // expected during successful test - assertTrue(e.getMessage().startsWith("Too few arguments supplied to operation")); - } - } - /** - * Make sure that POI uses the right Func Ptg when encoding formulas. Functions with variable - * number of args should get FuncVarPtg, functions with fixed args should get FuncPtg.

    - * - * Prior to the fix for bug 44675 POI would encode FuncVarPtg for all functions. In many cases - * Excel tolerates the wrong Ptg and evaluates the formula OK (e.g. SIN), but in some cases - * (e.g. COUNTIF) Excel fails to evaluate the formula, giving '#VALUE!' instead. - */ - @Test - public void testFuncPtgSelection() { - - Ptg[] ptgs = parseFormula("countif(A1:A2, 1)"); - assertEquals(3, ptgs.length); - if(ptgs[2] instanceof FuncVarPtg) { - fail("Identified bug 44675"); - } - confirmTokenClasses(ptgs, AreaPtg.class, IntPtg.class, FuncPtg.class); - - confirmTokenClasses("sin(1)", IntPtg.class, FuncPtg.class); - } - - @Test - public void testWrongNumberOfFunctionArgs() throws IOException { - confirmArgCountMsg("sin()", "Too few arguments to function 'SIN'. Expected 1 but got 0."); - confirmArgCountMsg("countif(1, 2, 3, 4)", "Too many arguments to function 'COUNTIF'. Expected 2 but got 4."); - confirmArgCountMsg("index(1, 2, 3, 4, 5, 6)", "Too many arguments to function 'INDEX'. At most 4 were expected but got 6."); - confirmArgCountMsg("vlookup(1, 2)", "Too few arguments to function 'VLOOKUP'. At least 3 were expected but got 2."); - } - - private static void confirmArgCountMsg(String formula, String expectedMessage) throws IOException { - HSSFWorkbook book = new HSSFWorkbook(); - try { - HSSFFormulaParser.parse(formula, book); - fail("Didn't get parse exception as expected"); - } catch (FormulaParseException e) { - confirmParseException(e, expectedMessage); - } - book.close(); - } - - @Test - public void testParseErrorExpectedMsg() { - - try { - parseFormula("round(3.14;2)"); - fail("Didn't get parse exception as expected"); - } catch (FormulaParseException e) { - confirmParseException(e, - "Parse error near char 10 ';' in specified formula 'round(3.14;2)'. Expected ',' or ')'"); - } - - try { - parseFormula(" =2+2"); - fail("Didn't get parse exception as expected"); - } catch (FormulaParseException e) { - confirmParseException(e, - "The specified formula ' =2+2' starts with an equals sign which is not allowed."); - } - } - - /** - * this function name has a dot in it. - */ - @Test - public void testParseErrorTypeFunction() { - - Ptg[] ptgs; - try { - ptgs = parseFormula("error.type(A1)"); - } catch (IllegalArgumentException e) { - if (e.getMessage().equals("Invalid Formula cell reference: 'error'")) { - fail("Identified bug 45334"); - } - throw e; - } - confirmTokenClasses(ptgs, RefPtg.class, FuncPtg.class); - assertEquals("ERROR.TYPE", ((FuncPtg) ptgs[1]).getName()); - } - - @Test - public void testNamedRangeThatLooksLikeCell() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("Sheet1"); - HSSFName name = wb.createName(); - name.setRefersToFormula("Sheet1!B1"); - name.setNameName("pfy1"); - - Ptg[] ptgs; - try { - ptgs = HSSFFormulaParser.parse("count(pfy1)", wb); - } catch (IllegalArgumentException e) { - if (e.getMessage().equals("Specified colIx (1012) is out of range")) { - fail("Identified bug 45354"); - } - wb.close(); - throw e; - } - confirmTokenClasses(ptgs, NamePtg.class, FuncVarPtg.class); - - HSSFCell cell = sheet.createRow(0).createCell(0); - cell.setCellFormula("count(pfy1)"); - assertEquals("COUNT(pfy1)", cell.getCellFormula()); - try { - cell.setCellFormula("count(pf1)"); - fail("Expected formula parse execption"); - } catch (FormulaParseException e) { - confirmParseException(e, - "Specified named range 'pf1' does not exist in the current workbook."); - } - cell.setCellFormula("count(fp1)"); // plain cell ref, col is in range - wb.close(); - } - - @Test - public void testParseAreaRefHighRow_bug45358() throws IOException { - Ptg[] ptgs; - AreaI aptg; - - HSSFWorkbook book = new HSSFWorkbook(); - book.createSheet("Sheet1"); - - ptgs = HSSFFormulaParser.parse("Sheet1!A10:A40000", book); - aptg = (AreaI) ptgs[0]; - if (aptg.getLastRow() == -25537) { - fail("Identified bug 45358"); - } - assertEquals(39999, aptg.getLastRow()); - - ptgs = HSSFFormulaParser.parse("Sheet1!A10:A65536", book); - aptg = (AreaI) ptgs[0]; - assertEquals(65535, aptg.getLastRow()); - - // plain area refs should be ok too - ptgs = parseFormula("A10:A65536"); - aptg = (AreaI) ptgs[0]; - assertEquals(65535, aptg.getLastRow()); - - book.close(); - } - - @Test - public void testParseArray() { - Ptg[] ptgs; - ptgs = parseFormula("mode({1,2,2,#REF!;FALSE,3,3,2})"); - confirmTokenClasses(ptgs, ArrayPtg.class, FuncVarPtg.class); - assertEquals("{1,2,2,#REF!;FALSE,3,3,2}", ptgs[0].toFormulaString()); - - ArrayPtg aptg = (ArrayPtg) ptgs[0]; - Object[][] values = aptg.getTokenArrayValues(); - assertEquals(ErrorConstant.valueOf(FormulaError.REF.getCode()), values[0][3]); - assertEquals(Boolean.FALSE, values[1][0]); - } - - @Test - public void testParseStringElementInArray() { - Ptg[] ptgs; - ptgs = parseFormula("MAX({\"5\"},3)"); - confirmTokenClasses(ptgs, ArrayPtg.class, IntPtg.class, FuncVarPtg.class); - Object element = ((ArrayPtg)ptgs[0]).getTokenArrayValues()[0][0]; - if (element instanceof UnicodeString) { - // this would cause ClassCastException below - fail("Wrong encoding of array element value"); - } - assertEquals(String.class, element.getClass()); - - // make sure the formula encodes OK - int encSize = Ptg.getEncodedSize(ptgs); - byte[] data = new byte[encSize]; - Ptg.serializePtgs(ptgs, data, 0); - byte[] expData = HexRead.readFromString( - "20 00 00 00 00 00 00 00 " // tArray - + "1E 03 00 " // tInt(3) - + "42 02 07 00 " // tFuncVar(MAX) 2-arg - + "00 00 00 " // Array data: 1 col, 1 row - + "02 01 00 00 35" // elem (type=string, len=1, "5") - ); - assertArrayEquals(expData, data); - int initSize = Ptg.getEncodedSizeWithoutArrayData(ptgs); - Ptg[] ptgs2 = Ptg.readTokens(initSize, new LittleEndianByteArrayInputStream(data)); - confirmTokenClasses(ptgs2, ArrayPtg.class, IntPtg.class, FuncVarPtg.class); - } - - @Test - public void testParseArrayNegativeElement() { - Ptg[] ptgs; - try { - ptgs = parseFormula("{-42}"); - } catch (FormulaParseException e) { - if (e.getMessage().equals("Parse error near char 1 '-' in specified formula '{-42}'. Expected Integer")) { - fail("Identified bug - failed to parse negative array element."); - } - throw e; - } - confirmTokenClasses(ptgs, ArrayPtg.class); - Object element = ((ArrayPtg)ptgs[0]).getTokenArrayValues()[0][0]; - - assertEquals(-42.0, ((Double)element).doubleValue(), 0.0); - - // Should be able to handle whitespace between unary minus and digits (Excel - // accepts this formula after presenting the user with a confirmation dialog). - ptgs = parseFormula("{- 5}"); - element = ((ArrayPtg)ptgs[0]).getTokenArrayValues()[0][0]; - assertEquals(-5.0, ((Double)element).doubleValue(), 0.0); - } - - @Test - public void testRangeOperator() throws IOException { - - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet(); - HSSFCell cell = sheet.createRow(0).createCell(0); - - wb.setSheetName(0, "Sheet1"); - cell.setCellFormula("Sheet1!B$4:Sheet1!$C1"); // explicit range ':' operator - assertEquals("Sheet1!B$4:Sheet1!$C1", cell.getCellFormula()); - - cell.setCellFormula("Sheet1!B$4:$C1"); // plain area ref - assertEquals("Sheet1!B1:$C$4", cell.getCellFormula()); // note - area ref is normalised - - cell.setCellFormula("Sheet1!$C1...B$4"); // different syntax for plain area ref - assertEquals("Sheet1!B1:$C$4", cell.getCellFormula()); - - // with funny sheet name - wb.setSheetName(0, "A1...A2"); - cell.setCellFormula("A1...A2!B1"); - assertEquals("A1...A2!B1", cell.getCellFormula()); - - wb.close(); - } - - @Test - public void testBooleanNamedSheet() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("true"); - HSSFCell cell = sheet.createRow(0).createCell(0); - cell.setCellFormula("'true'!B2"); - - assertEquals("'true'!B2", cell.getCellFormula()); - - wb.close(); - } - - @Test - public void testParseExternalWorkbookReference() throws IOException { - HSSFWorkbook wbA = HSSFTestDataSamples.openSampleWorkbook("multibookFormulaA.xls"); - HSSFCell cell = wbA.getSheetAt(0).getRow(0).getCell(0); - - // make sure formula in sample is as expected - assertEquals("[multibookFormulaB.xls]BSheet1!B1", cell.getCellFormula()); - Ptg[] expectedPtgs = FormulaExtractor.getPtgs(cell); - confirmSingle3DRef(expectedPtgs, 1); - - // now try (re-)parsing the formula - Ptg[] actualPtgs = HSSFFormulaParser.parse("[multibookFormulaB.xls]BSheet1!B1", wbA); - confirmSingle3DRef(actualPtgs, 1); // externalSheetIndex 1 -> BSheet1 - - // try parsing a formula pointing to a different external sheet - Ptg[] otherPtgs = HSSFFormulaParser.parse("[multibookFormulaB.xls]AnotherSheet!B1", wbA); - confirmSingle3DRef(otherPtgs, 0); // externalSheetIndex 0 -> AnotherSheet - - // try setting the same formula in a cell - cell.setCellFormula("[multibookFormulaB.xls]AnotherSheet!B1"); - assertEquals("[multibookFormulaB.xls]AnotherSheet!B1", cell.getCellFormula()); - - wbA.close(); - } - - private static void confirmSingle3DRef(Ptg[] ptgs, int expectedExternSheetIndex) { - assertEquals(1, ptgs.length); - Ptg ptg0 = ptgs[0]; - assertTrue(ptg0 instanceof Ref3DPtg); - assertEquals(expectedExternSheetIndex, ((Ref3DPtg)ptg0).getExternSheetIndex()); - } - - @Test - public void testUnion() throws IOException { - String formula = "Sheet1!$B$2:$C$3,OFFSET(Sheet1!$E$2:$E$4,1,Sheet1!$A$1),Sheet1!$D$6"; - HSSFWorkbook wb = new HSSFWorkbook(); - wb.createSheet("Sheet1"); - Ptg[] ptgs = FormulaParser.parse(formula, HSSFEvaluationWorkbook.create(wb), FormulaType.CELL, -1); - - confirmTokenClasses(ptgs, - // TODO - AttrPtg.class, // Excel prepends this - MemFuncPtg.class, - Area3DPtg.class, - Area3DPtg.class, - IntPtg.class, - Ref3DPtg.class, - FuncVarPtg.class, - UnionPtg.class, - Ref3DPtg.class, - UnionPtg.class - ); - MemFuncPtg mf = (MemFuncPtg)ptgs[0]; - assertEquals(45, mf.getLenRefSubexpression()); - - // We don't check the type of the operands. - confirmTokenClasses("1,2", MemAreaPtg.class, IntPtg.class, IntPtg.class, UnionPtg.class); - - wb.close(); - } - - @Test - public void testIntersection() throws IOException { - String formula = "Sheet1!$B$2:$C$3 OFFSET(Sheet1!$E$2:$E$4, 1,Sheet1!$A$1) Sheet1!$D$6"; - HSSFWorkbook wb = new HSSFWorkbook(); - wb.createSheet("Sheet1"); - Ptg[] ptgs = FormulaParser.parse(formula, HSSFEvaluationWorkbook.create(wb), FormulaType.CELL, -1); - - confirmTokenClasses(ptgs, - // TODO - AttrPtg.class, // Excel prepends this - MemFuncPtg.class, - Area3DPtg.class, - Area3DPtg.class, - IntPtg.class, - Ref3DPtg.class, - FuncVarPtg.class, - IntersectionPtg.class, - Ref3DPtg.class, - IntersectionPtg.class - ); - MemFuncPtg mf = (MemFuncPtg)ptgs[0]; - assertEquals(45, mf.getLenRefSubexpression()); - - // This used to be an error but now parses. Union has the same behaviour. - confirmTokenClasses("1 2", MemAreaPtg.class, IntPtg.class, IntPtg.class, IntersectionPtg.class); - - wb.close(); - } - - @Test - public void testComparisonInParen() { - confirmTokenClasses("(A1 > B2)", - RefPtg.class, - RefPtg.class, - GreaterThanPtg.class, - ParenthesisPtg.class - ); - } - - @Test - public void testUnionInParen() { - confirmTokenClasses("(A1:B2,B2:C3)", - MemAreaPtg.class, - AreaPtg.class, - AreaPtg.class, - UnionPtg.class, - ParenthesisPtg.class - ); - } - - @Test - public void testIntersectionInParen() { - confirmTokenClasses("(A1:B2 B2:C3)", - MemAreaPtg.class, - AreaPtg.class, - AreaPtg.class, - IntersectionPtg.class, - ParenthesisPtg.class - ); - } - - @Test - public void testRange_bug46643() throws IOException { - String formula = "Sheet1!A1:Sheet1!B3"; - HSSFWorkbook wb = new HSSFWorkbook(); - wb.createSheet("Sheet1"); - Ptg[] ptgs = FormulaParser.parse(formula, HSSFEvaluationWorkbook.create(wb), FormulaType.CELL, -1, -1); - - if (ptgs.length == 3) { - confirmTokenClasses(ptgs, Ref3DPtg.class, Ref3DPtg.class, RangePtg.class); - fail("Identified bug 46643"); - } - - confirmTokenClasses(ptgs, - MemFuncPtg.class, - Ref3DPtg.class, - Ref3DPtg.class, - RangePtg.class - ); - MemFuncPtg mf = (MemFuncPtg)ptgs[0]; - assertEquals(15, mf.getLenRefSubexpression()); - wb.close(); - } - - /** Named ranges with backslashes, e.g. 'POI\\2009' */ - @Test - public void testBackSlashInNames() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - - HSSFName name = wb.createName(); - name.setNameName("POI\\2009"); - name.setRefersToFormula("Sheet1!$A$1"); - - HSSFSheet sheet = wb.createSheet(); - HSSFRow row = sheet.createRow(0); - - HSSFCell cell_C1 = row.createCell(2); - cell_C1.setCellFormula("POI\\2009"); - assertEquals("POI\\2009", cell_C1.getCellFormula()); - - HSSFCell cell_D1 = row.createCell(2); - cell_D1.setCellFormula("NOT(POI\\2009=\"3.5-final\")"); - assertEquals("NOT(POI\\2009=\"3.5-final\")", cell_D1.getCellFormula()); - - wb.close(); - } - - /** - * See the related/similar test: {@link BaseTestBugzillaIssues#bug42448()} - */ - @Test - public void testParseAbnormalSheetNamesAndRanges_bug42448() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - wb.createSheet("A"); - try { - HSSFFormulaParser.parse("SUM(A!C7:A!C67)", wb); - } catch (StringIndexOutOfBoundsException e) { - fail("Identified bug 42448"); - } - // the exact example from the bugzilla description: - HSSFFormulaParser.parse("SUMPRODUCT(A!C7:A!C67, B8:B68) / B69", wb); - - wb.close(); - } - - @Test - public void testRangeFuncOperand_bug46951() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - Ptg[] ptgs; - try { - ptgs = HSSFFormulaParser.parse("SUM(C1:OFFSET(C1,0,B1))", wb); - } catch (RuntimeException e) { - if (e.getMessage().equals("Specified named range 'OFFSET' does not exist in the current workbook.")) { - fail("Identified bug 46951"); - } - wb.close(); - throw e; - } - confirmTokenClasses(ptgs, - MemFuncPtg.class, // [len=23] - RefPtg.class, // [C1] - RefPtg.class, // [C1] - IntPtg.class, // [0] - RefPtg.class, // [B1] - FuncVarPtg.class, // [OFFSET nArgs=3] - RangePtg.class, // - AttrPtg.class // [sum ] - ); - wb.close(); - } - - @Test - public void testUnionOfFullCollFullRowRef() throws IOException { - parseFormula("3:4"); - Ptg[] ptgs = parseFormula("$Z:$AC"); - confirmTokenClasses(ptgs, AreaPtg.class); - parseFormula("B:B"); - - ptgs = parseFormula("$11:$13"); - confirmTokenClasses(ptgs, AreaPtg.class); - - ptgs = parseFormula("$A:$A,$1:$4"); - confirmTokenClasses(ptgs, MemAreaPtg.class, - AreaPtg.class, - AreaPtg.class, - UnionPtg.class - ); - - HSSFWorkbook wb = new HSSFWorkbook(); - wb.createSheet("Sheet1"); - ptgs = HSSFFormulaParser.parse("Sheet1!$A:$A,Sheet1!$1:$4", wb); - confirmTokenClasses(ptgs, MemFuncPtg.class, - Area3DPtg.class, - Area3DPtg.class, - UnionPtg.class - ); - - ptgs = HSSFFormulaParser.parse("'Sheet1'!$A:$A,'Sheet1'!$1:$4", wb); - confirmTokenClasses(ptgs, - MemFuncPtg.class, - Area3DPtg.class, - Area3DPtg.class, - UnionPtg.class - ); - - wb.close(); - } - - @Test - public void testExplicitRangeWithTwoSheetNames() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - wb.createSheet("Sheet1"); - Ptg[] ptgs = HSSFFormulaParser.parse("Sheet1!F1:Sheet1!G2", wb); - confirmTokenClasses(ptgs, - MemFuncPtg.class, - Ref3DPtg.class, - Ref3DPtg.class, - RangePtg.class - ); - MemFuncPtg mf; - mf = (MemFuncPtg)ptgs[0]; - assertEquals(15, mf.getLenRefSubexpression()); - wb.close(); - } - - /** - * Checks that the area-ref and explicit range operators get the right associativity - * and that the {@link MemFuncPtg} / {@link MemAreaPtg} is added correctly - */ - @Test - public void testComplexExplicitRangeEncodings() { - - Ptg[] ptgs; - ptgs = parseFormula("SUM(OFFSET(A1,0,0):B2:C3:D4:E5:OFFSET(F6,1,1):G7)"); - confirmTokenClasses(ptgs, - // AttrPtg.class, // [volatile ] // POI doesn't do this yet (Apr 2009) - MemFuncPtg.class, // len 57 - RefPtg.class, // [A1] - IntPtg.class, // [0] - IntPtg.class, // [0] - FuncVarPtg.class, // [OFFSET nArgs=3] - AreaPtg.class, // [B2:C3] - RangePtg.class, - AreaPtg.class, // [D4:E5] - RangePtg.class, - RefPtg.class, // [F6] - IntPtg.class, // [1] - IntPtg.class, // [1] - FuncVarPtg.class, // [OFFSET nArgs=3] - RangePtg.class, - RefPtg.class, // [G7] - RangePtg.class, - AttrPtg.class // [sum ] - ); - - MemFuncPtg mf = (MemFuncPtg)ptgs[0]; - assertEquals(57, mf.getLenRefSubexpression()); - assertEquals("D4:E5", ((AreaPtgBase)ptgs[7]).toFormulaString()); - assertTrue(((AttrPtg)ptgs[16]).isSum()); - - ptgs = parseFormula("SUM(A1:B2:C3:D4)"); - confirmTokenClasses(ptgs, - // AttrPtg.class, // [volatile ] // POI doesn't do this yet (Apr 2009) - MemAreaPtg.class, // len 19 - AreaPtg.class, // [A1:B2] - AreaPtg.class, // [C3:D4] - RangePtg.class, - AttrPtg.class // [sum ] - ); - MemAreaPtg ma = (MemAreaPtg)ptgs[0]; - assertEquals(19, ma.getLenRefSubexpression()); - } - - - /** - * Mostly confirming that erroneous conditions are detected. Actual error message wording is not critical. - * - */ - @Test - public void testEdgeCaseParserErrors() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - wb.createSheet("Sheet1"); - - confirmParseError(wb, "A1:ROUND(B1,1)", "The RHS of the range operator ':' at position 3 is not a proper reference."); - - confirmParseError(wb, "Sheet1!!!", "Parse error near char 7 '!' in specified formula 'Sheet1!!!'. Expected number, string, defined name, or data table"); - confirmParseError(wb, "Sheet1!.Name", "Parse error near char 7 '.' in specified formula 'Sheet1!.Name'. Expected number, string, defined name, or data table"); - confirmParseError(wb, "Sheet1!Sheet1", "Specified name 'Sheet1' for sheet Sheet1 not found"); - confirmParseError(wb, "Sheet1!F:Sheet1!G", "'Sheet1!F' is not a proper reference."); - confirmParseError(wb, "Sheet1!F..foobar", "Complete area reference expected after sheet name at index 11."); - confirmParseError(wb, "Sheet1!A .. B", "Dotted range (full row or column) expression 'A .. B' must not contain whitespace."); - confirmParseError(wb, "Sheet1!A...B", "Dotted range (full row or column) expression 'A...B' must have exactly 2 dots."); - confirmParseError(wb, "Sheet1!A foobar", "Second part of cell reference expected after sheet name at index 10."); - - confirmParseError(wb, "foobar", "Specified named range 'foobar' does not exist in the current workbook."); - confirmParseError(wb, "A1:1", "The RHS of the range operator ':' at position 3 is not a proper reference."); - wb.close(); - } - - private static void confirmParseError(HSSFWorkbook wb, String formula, String expectedMessage) { - - try { - HSSFFormulaParser.parse(formula, wb); - fail("Expected formula parse execption"); - } catch (FormulaParseException e) { - confirmParseException(e, expectedMessage); - } - } - - /** - * In bug 47078, POI had trouble evaluating a defined name flagged as 'complex'. - * POI should also be able to parse such defined names. - */ - @Test - public void testParseComplexName() throws IOException { - - // Mock up a spreadsheet to match the critical details of the sample - HSSFWorkbook wb = new HSSFWorkbook(); - wb.createSheet("Sheet1"); - HSSFName definedName = wb.createName(); - definedName.setNameName("foo"); - definedName.setRefersToFormula("Sheet1!B2"); - - // Set the complex flag - POI doesn't usually manipulate this flag - NameRecord nameRec = TestHSSFName.getNameRecord(definedName); - nameRec.setOptionFlag((short)0x10); // 0x10 -> complex - - Ptg[] result; - try { - result = HSSFFormulaParser.parse("1+foo", wb); - } catch (FormulaParseException e) { - if (e.getMessage().equals("Specified name 'foo' is not a range as expected.")) { - fail("Identified bug 47078c"); - } - wb.close(); - throw e; - } - confirmTokenClasses(result, IntPtg.class, NamePtg.class, AddPtg.class); - - wb.close(); - } - - /** - * Zero is not a valid row number so cell references like 'A0' are not valid. - * Actually, they should be treated like defined names. - *
    - * In addition, leading zeros (on the row component) should be removed from cell - * references during parsing. - */ - @Test - public void testZeroRowRefs() throws IOException { - String badCellRef = "B0"; // bad because zero is not a valid row number - String leadingZeroCellRef = "B000001"; // this should get parsed as "B1" - HSSFWorkbook wb = new HSSFWorkbook(); - - try { - HSSFFormulaParser.parse(badCellRef, wb); - fail("Identified bug 47312b - Shouldn't be able to parse cell ref '" - + badCellRef + "'."); - } catch (FormulaParseException e) { - // expected during successful test - confirmParseException(e, "Specified named range '" - + badCellRef + "' does not exist in the current workbook."); - } - - Ptg[] ptgs; - try { - ptgs = HSSFFormulaParser.parse(leadingZeroCellRef, wb); - assertEquals("B1", ((RefPtg) ptgs[0]).toFormulaString()); - } catch (FormulaParseException e) { - confirmParseException(e, "Specified named range '" - + leadingZeroCellRef + "' does not exist in the current workbook."); - // close but no cigar - fail("Identified bug 47312c - '" + leadingZeroCellRef + "' should parse as 'B1'."); - } - - // create a defined name called 'B0' and try again - Name n = wb.createName(); - n.setNameName("B0"); - n.setRefersToFormula("1+1"); - ptgs = HSSFFormulaParser.parse("B0", wb); - confirmTokenClasses(ptgs, NamePtg.class); - - wb.close(); - } - - private static void confirmParseException(FormulaParseException e, String expMsg) { - assertEquals(expMsg, e.getMessage()); - } - - @Test - public void test57196_Formula() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - Ptg[] ptgs = HSSFFormulaParser.parse("DEC2HEX(HEX2DEC(O8)-O2+D2)", wb, FormulaType.CELL, -1); - assertNotNull("Ptg array should not be null", ptgs); - - confirmTokenClasses(ptgs, - NameXPtg.class, // ?? - NameXPtg.class, // ?? - RefPtg.class, // O8 - FuncVarPtg.class, // HEX2DEC - RefPtg.class, // O2 - SubtractPtg.class, - RefPtg.class, // D2 - AddPtg.class, - FuncVarPtg.class // DEC2HEX - ); - - RefPtg o8 = (RefPtg) ptgs[2]; - FuncVarPtg hex2Dec = (FuncVarPtg) ptgs[3]; - RefPtg o2 = (RefPtg) ptgs[4]; - RefPtg d2 = (RefPtg) ptgs[6]; - FuncVarPtg dec2Hex = (FuncVarPtg) ptgs[8]; - - assertEquals("O8", o8.toFormulaString()); - assertEquals(255, hex2Dec.getFunctionIndex()); - //assertEquals("", hex2Dec.toString()); - assertEquals("O2", o2.toFormulaString()); - assertEquals("D2", d2.toFormulaString()); - assertEquals(255, dec2Hex.getFunctionIndex()); - - wb.close(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/model/TestFormulaParserEval.java b/src/testcases/org/apache/poi/hssf/model/TestFormulaParserEval.java deleted file mode 100644 index 291b3a500..000000000 --- a/src/testcases/org/apache/poi/hssf/model/TestFormulaParserEval.java +++ /dev/null @@ -1,105 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.model; - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -import org.apache.poi.ss.formula.ptg.AttrPtg; -import org.apache.poi.ss.formula.ptg.NamePtg; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFName; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.FormulaParseException; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; - -/** - * Test the low level formula parser functionality, - * but using parts which need to use - * HSSFFormulaEvaluator. - */ -public final class TestFormulaParserEval extends TestCase { - - public void testWithNamedRange() { - HSSFWorkbook workbook = new HSSFWorkbook(); - - HSSFSheet s = workbook.createSheet("Foo"); - s.createRow(0).createCell(0).setCellValue(1.1); - s.createRow(1).createCell(0).setCellValue(2.3); - s.createRow(2).createCell(2).setCellValue(3.1); - - HSSFName name = workbook.createName(); - name.setNameName("testName"); - name.setRefersToFormula("A1:A2"); - - confirmParseFormula(workbook); - - // Now make it a single cell - name.setRefersToFormula("C3"); - confirmParseFormula(workbook); - - // And make it non-contiguous - // using area unions - name.setRefersToFormula("A1:A2,C3"); - - confirmParseFormula(workbook); - } - - /** - * Makes sure that a formula referring to the named range parses properly - */ - private static void confirmParseFormula(HSSFWorkbook workbook) { - Ptg[] ptgs = HSSFFormulaParser.parse("SUM(testName)", workbook); - assertTrue("two tokens expected, got "+ptgs.length,ptgs.length == 2); - assertEquals(NamePtg.class, ptgs[0].getClass()); - assertEquals(AttrPtg.class, ptgs[1].getClass()); - } - - public void testEvaluateFormulaWithRowBeyond32768_Bug44539() { - - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet(); - wb.setSheetName(0, "Sheet1"); - - HSSFRow row = sheet.createRow(0); - HSSFCell cell = row.createCell(0); - cell.setCellFormula("SUM(A32769:A32770)"); - - // put some values in the cells to make the evaluation more interesting - sheet.createRow(32768).createCell(0).setCellValue(31); - sheet.createRow(32769).createCell(0).setCellValue(11); - - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - CellValue result; - try { - result = fe.evaluate(cell); - } catch (FormulaParseException e) { - if (!e.getMessage().equals("Found reference to named range \"A\", but that named range wasn't defined!")) { - throw new AssertionFailedError("Identifed bug 44539"); - } - throw e; - } - assertEquals(CellType.NUMERIC, result.getCellTypeEnum()); - assertEquals(42.0, result.getNumberValue(), 0.0); - } -} diff --git a/src/testcases/org/apache/poi/hssf/model/TestFormulaParserIf.java b/src/testcases/org/apache/poi/hssf/model/TestFormulaParserIf.java deleted file mode 100644 index a069190f5..000000000 --- a/src/testcases/org/apache/poi/hssf/model/TestFormulaParserIf.java +++ /dev/null @@ -1,238 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.model; - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -import org.apache.poi.ss.formula.ptg.AddPtg; -import org.apache.poi.ss.formula.ptg.AttrPtg; -import org.apache.poi.ss.formula.ptg.BoolPtg; -import org.apache.poi.ss.formula.ptg.FuncPtg; -import org.apache.poi.ss.formula.ptg.FuncVarPtg; -import org.apache.poi.ss.formula.ptg.IntPtg; -import org.apache.poi.ss.formula.ptg.LessEqualPtg; -import org.apache.poi.ss.formula.ptg.LessThanPtg; -import org.apache.poi.ss.formula.ptg.MultiplyPtg; -import org.apache.poi.ss.formula.ptg.NotEqualPtg; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.apache.poi.ss.formula.ptg.RefPtg; -import org.apache.poi.ss.formula.ptg.StringPtg; - -/** - * Tests FormulaParser specifically with respect to IF() functions - */ -public final class TestFormulaParserIf extends TestCase { - private static Ptg[] parseFormula(String formula) { - return TestFormulaParser.parseFormula(formula); - } - - private static Ptg[] confirmTokenClasses(String formula, Class[] expectedClasses) { - return TestFormulaParser.confirmTokenClasses(formula, expectedClasses); - } - - private static void confirmAttrData(Ptg[] ptgs, int i, int expectedData) { - Ptg ptg = ptgs[i]; - if (!(ptg instanceof AttrPtg)) { - throw new AssertionFailedError("Token[" + i + "] was not AttrPtg as expected"); - } - AttrPtg attrPtg = (AttrPtg) ptg; - assertEquals(expectedData, attrPtg.getData()); - } - - public void testSimpleIf() { - - Class[] expClss; - - expClss = new Class[] { - RefPtg.class, - AttrPtg.class, // tAttrIf - IntPtg.class, - AttrPtg.class, // tAttrSkip - IntPtg.class, - AttrPtg.class, // tAttrSkip - FuncVarPtg.class, - }; - - Ptg[] ptgs = confirmTokenClasses("if(A1,1,2)", expClss); - - confirmAttrData(ptgs, 1, 7); - confirmAttrData(ptgs, 3, 10); - confirmAttrData(ptgs, 5, 3); - } - - public void testSimpleIfNoFalseParam() { - - Class[] expClss; - - expClss = new Class[] { - RefPtg.class, - AttrPtg.class, // tAttrIf - RefPtg.class, - AttrPtg.class, // tAttrSkip - FuncVarPtg.class, - }; - - Ptg[] ptgs = confirmTokenClasses("if(A1,B1)", expClss); - - confirmAttrData(ptgs, 1, 9); - confirmAttrData(ptgs, 3, 3); - } - - public void testIfWithLargeParams() { - - Class[] expClss; - - expClss = new Class[] { - RefPtg.class, - AttrPtg.class, // tAttrIf - - RefPtg.class, - IntPtg.class, - MultiplyPtg.class, - RefPtg.class, - IntPtg.class, - AddPtg.class, - FuncPtg.class, - AttrPtg.class, // tAttrSkip - - RefPtg.class, - RefPtg.class, - FuncPtg.class, - - AttrPtg.class, // tAttrSkip - FuncVarPtg.class, - }; - - Ptg[] ptgs = confirmTokenClasses("if(A1,round(B1*100,C1+2),round(B1,C1))", expClss); - - confirmAttrData(ptgs, 1, 25); - confirmAttrData(ptgs, 9, 20); - confirmAttrData(ptgs, 13, 3); - } - - public void testNestedIf() { - - Class[] expClss; - - expClss = new Class[] { - - RefPtg.class, - AttrPtg.class, // A tAttrIf - RefPtg.class, - AttrPtg.class, // B tAttrIf - IntPtg.class, - AttrPtg.class, // B tAttrSkip - IntPtg.class, - AttrPtg.class, // B tAttrSkip - FuncVarPtg.class, - AttrPtg.class, // A tAttrSkip - RefPtg.class, - AttrPtg.class, // C tAttrIf - IntPtg.class, - AttrPtg.class, // C tAttrSkip - IntPtg.class, - AttrPtg.class, // C tAttrSkip - FuncVarPtg.class, - AttrPtg.class, // A tAttrSkip - FuncVarPtg.class, - }; - - Ptg[] ptgs = confirmTokenClasses("if(A1,if(B1,1,2),if(C1,3,4))", expClss); - confirmAttrData(ptgs, 1, 31); - confirmAttrData(ptgs, 3, 7); - confirmAttrData(ptgs, 5, 10); - confirmAttrData(ptgs, 7, 3); - confirmAttrData(ptgs, 9, 34); - confirmAttrData(ptgs, 11, 7); - confirmAttrData(ptgs, 13, 10); - confirmAttrData(ptgs, 15, 3); - confirmAttrData(ptgs, 17, 3); - } - - public void testEmbeddedIf() { - Ptg[] ptgs = parseFormula("IF(3>=1,\"*\",IF(4<>1,\"first\",\"second\"))"); - assertEquals(17, ptgs.length); - - assertEquals("6th Ptg is not a goto (Attr) ptg",AttrPtg.class,ptgs[5].getClass()); - assertEquals("9th Ptg is not a not equal ptg",NotEqualPtg.class,ptgs[8].getClass()); - assertEquals("15th Ptg is not the inner IF variable function ptg",FuncVarPtg.class,ptgs[14].getClass()); - } - - - public void testSimpleLogical() { - Ptg[] ptgs = parseFormula("IF(A1 - * TODO get OOO documentation updated to reflect this (that EXTERNALBOOK is optional). - * - * It's not clear what exact steps need to be taken in Excel to create such a workbook - */ - public void testLinkTableWithoutExternalBookRecord_bug45046() { - HSSFWorkbook wb; - - try { - wb = HSSFTestDataSamples.openSampleWorkbook("ex45046-21984.xls"); - } catch (RuntimeException e) { - if ("DEFINEDNAME is part of LinkTable".equals(e.getMessage())) { - throw new AssertionFailedError("Identified bug 45046 b"); - } - throw e; - } - // some other sanity checks - assertEquals(3, wb.getNumberOfSheets()); - String formula = wb.getSheetAt(0).getRow(4).getCell(13).getCellFormula(); - - if ("ipcSummenproduktIntern($P5,N$6,$A$9,N$5)".equals(formula)) { - // The reported symptom of this bugzilla is an earlier bug (already fixed) - throw new AssertionFailedError("Identified bug 41726"); - // This is observable in version 3.0 - } - - assertEquals("ipcSummenproduktIntern($C5,N$2,$A$9,N$1)", formula); - } - - public void testMultipleExternSheetRecords_bug45698() { - HSSFWorkbook wb; - - try { - wb = HSSFTestDataSamples.openSampleWorkbook("ex45698-22488.xls"); - } catch (RuntimeException e) { - if ("Extern sheet is part of LinkTable".equals(e.getMessage())) { - throw new AssertionFailedError("Identified bug 45698"); - } - throw e; - } - // some other sanity checks - assertEquals(7, wb.getNumberOfSheets()); - } - - public void testExtraSheetRefs_bug45978() { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("ex45978-extraLinkTableSheets.xls"); - /* - ex45978-extraLinkTableSheets.xls is a cut-down version of attachment 22561. - The original file produces the same error. - - This bug was caused by a combination of invalid sheet indexes in the EXTERNSHEET - record, and eager initialisation of the extern sheet references. Note - the workbook - has 2 sheets, but the EXTERNSHEET record refers to sheet indexes 0, 1 and 2. - - Offset 0x3954 (14676) - recordid = 0x17, size = 32 - [EXTERNSHEET] - numOfRefs = 5 - refrec #0: extBook=0 firstSheet=0 lastSheet=0 - refrec #1: extBook=1 firstSheet=2 lastSheet=2 - refrec #2: extBook=2 firstSheet=1 lastSheet=1 - refrec #3: extBook=0 firstSheet=-1 lastSheet=-1 - refrec #4: extBook=0 firstSheet=1 lastSheet=1 - [/EXTERNSHEET] - - As it turns out, the formula in question doesn't even use externSheetIndex #1 - it - uses #4, which resolves to sheetIndex 1 -> 'Data'. - - It is not clear exactly what externSheetIndex #4 would refer to. Excel seems to - display such a formula as "''!$A2", but then complains of broken link errors. - */ - - HSSFCell cell = wb.getSheetAt(0).getRow(1).getCell(1); - String cellFormula; - try { - cellFormula = cell.getCellFormula(); - } catch (IndexOutOfBoundsException e) { - if (e.getMessage().equals("Index: 2, Size: 2")) { - throw new AssertionFailedError("Identified bug 45798"); - } - throw e; - } - assertEquals("Data!$A2", cellFormula); - } - - /** - * This problem was visible in POI svn r763332 - * when reading the workbook of attachment 23468 from bugzilla 47001 - */ - public void testMissingExternSheetRecord_bug47001b() { - - Record[] recs = { - SupBookRecord.createAddInFunctions(), - new SSTRecord(), - }; - List recList = Arrays.asList(recs); - WorkbookRecordList wrl = new WorkbookRecordList(); - - LinkTable lt; - try { - lt = new LinkTable(recList, 0, wrl, Collections.emptyMap()); - } catch (RuntimeException e) { - if (e.getMessage().equals("Expected an EXTERNSHEET record but got (org.apache.poi.hssf.record.SSTRecord)")) { - throw new AssertionFailedError("Identified bug 47001b"); - } - - throw e; - } - assertNotNull(lt); - } - - /** - * - */ - public void testNameCommentRecordBetweenNameRecords() { - - final Record[] recs = { - new NameRecord(), - new NameCommentRecord("name1", "comment1"), - new NameRecord(), - new NameCommentRecord("name2", "comment2"), - - }; - final List recList = Arrays.asList(recs); - final WorkbookRecordList wrl = new WorkbookRecordList(); - final Map commentRecords = new LinkedHashMap(); - - final LinkTable lt = new LinkTable(recList, 0, wrl, commentRecords); - assertNotNull(lt); - - assertEquals(2, commentRecords.size()); - assertTrue(recs[1] == commentRecords.get("name1")); //== is intentionally not .equals()! - assertTrue(recs[3] == commentRecords.get("name2")); //== is intentionally not .equals()! - - assertEquals(2, lt.getNumNames()); - } - - public void testAddNameX(){ - WorkbookRecordList wrl = new WorkbookRecordList(); - wrl.add(0, new BOFRecord()); - wrl.add(1, new CountryRecord()); - wrl.add(2, EOFRecord.instance); - - int numberOfSheets = 3; - LinkTable tbl = new LinkTable(numberOfSheets, wrl); - // creation of a new LinkTable insert two new records: SupBookRecord followed by ExternSheetRecord - // assure they are in place: - // [BOFRecord] - // [CountryRecord] - // [SUPBOOK Internal References nSheets= 3] - // [EXTERNSHEET] - // [EOFRecord] - - assertEquals(5, wrl.getRecords().size()); - assertTrue(wrl.get(2) instanceof SupBookRecord); - SupBookRecord sup1 = (SupBookRecord)wrl.get(2); - assertEquals(numberOfSheets, sup1.getNumberOfSheets()); - assertTrue(wrl.get(3) instanceof ExternSheetRecord); - ExternSheetRecord extSheet = (ExternSheetRecord)wrl.get(3); - assertEquals(0, extSheet.getNumOfRefs()); - - assertNull(tbl.getNameXPtg("ISODD", -1)); - assertEquals(5, wrl.getRecords().size()); //still have five records - - NameXPtg namex1 = tbl.addNameXPtg("ISODD"); // adds two new rercords - assertEquals(0, namex1.getSheetRefIndex()); - assertEquals(0, namex1.getNameIndex()); - assertEquals(namex1.toString(), tbl.getNameXPtg("ISODD", -1).toString()); - - // Can only find on the right sheet ref, if restricting - assertEquals(namex1.toString(), tbl.getNameXPtg("ISODD", 0).toString()); - assertNull(tbl.getNameXPtg("ISODD", 1)); - assertNull(tbl.getNameXPtg("ISODD", 2)); - - // assure they are in place: - // [BOFRecord] - // [CountryRecord] - // [SUPBOOK Internal References nSheets= 3] - // [SUPBOOK Add-In Functions nSheets= 1] - // [EXTERNALNAME .name = ISODD] - // [EXTERNSHEET] - // [EOFRecord] - - assertEquals(7, wrl.getRecords().size()); - assertTrue(wrl.get(3) instanceof SupBookRecord); - SupBookRecord sup2 = (SupBookRecord)wrl.get(3); - assertTrue(sup2.isAddInFunctions()); - assertTrue(wrl.get(4) instanceof ExternalNameRecord); - ExternalNameRecord ext1 = (ExternalNameRecord)wrl.get(4); - assertEquals("ISODD", ext1.getText()); - assertTrue(wrl.get(5) instanceof ExternSheetRecord); - assertEquals(1, extSheet.getNumOfRefs()); - - //check that - assertEquals(0, tbl.resolveNameXIx(namex1.getSheetRefIndex(), namex1.getNameIndex())); - assertEquals("ISODD", tbl.resolveNameXText(namex1.getSheetRefIndex(), namex1.getNameIndex(), null)); - - assertNull(tbl.getNameXPtg("ISEVEN", -1)); - NameXPtg namex2 = tbl.addNameXPtg("ISEVEN"); // adds two new rercords - assertEquals(0, namex2.getSheetRefIndex()); - assertEquals(1, namex2.getNameIndex()); // name index increased by one - assertEquals(namex2.toString(), tbl.getNameXPtg("ISEVEN", -1).toString()); - assertEquals(8, wrl.getRecords().size()); - // assure they are in place: - // [BOFRecord] - // [CountryRecord] - // [SUPBOOK Internal References nSheets= 3] - // [SUPBOOK Add-In Functions nSheets= 1] - // [EXTERNALNAME .name = ISODD] - // [EXTERNALNAME .name = ISEVEN] - // [EXTERNSHEET] - // [EOFRecord] - assertTrue(wrl.get(3) instanceof SupBookRecord); - assertTrue(wrl.get(4) instanceof ExternalNameRecord); - assertTrue(wrl.get(5) instanceof ExternalNameRecord); - assertEquals("ISODD", ((ExternalNameRecord)wrl.get(4)).getText()); - assertEquals("ISEVEN", ((ExternalNameRecord)wrl.get(5)).getText()); - assertTrue(wrl.get(6) instanceof ExternSheetRecord); - assertTrue(wrl.get(7) instanceof EOFRecord); - - assertEquals(0, tbl.resolveNameXIx(namex2.getSheetRefIndex(), namex2.getNameIndex())); - assertEquals("ISEVEN", tbl.resolveNameXText(namex2.getSheetRefIndex(), namex2.getNameIndex(), null)); - - } -} diff --git a/src/testcases/org/apache/poi/hssf/model/TestOperandClassTransformer.java b/src/testcases/org/apache/poi/hssf/model/TestOperandClassTransformer.java deleted file mode 100644 index 467186c29..000000000 --- a/src/testcases/org/apache/poi/hssf/model/TestOperandClassTransformer.java +++ /dev/null @@ -1,145 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.model; - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -import org.apache.poi.ss.formula.ptg.AbstractFunctionPtg; -import org.apache.poi.ss.formula.ptg.FuncVarPtg; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; - -/** - * Tests specific formula examples in OperandClassTransformer. - * - * @author Josh Micich - */ -public final class TestOperandClassTransformer extends TestCase { - - private static Ptg[] parseFormula(String formula) { - Ptg[] result = HSSFFormulaParser.parse(formula, (HSSFWorkbook)null); - assertNotNull("Ptg array should not be null", result); - return result; - } - - public void testMdeterm() { - String formula = "MDETERM(ABS(A1))"; - Ptg[] ptgs = parseFormula(formula); - - confirmTokenClass(ptgs, 0, Ptg.CLASS_ARRAY); - confirmFuncClass(ptgs, 1, "ABS", Ptg.CLASS_ARRAY); - confirmFuncClass(ptgs, 2, "MDETERM", Ptg.CLASS_VALUE); - } - - /** - * In the example: INDEX(PI(),1), Excel encodes PI() as 'array'. It is not clear - * what rule justifies this. POI currently encodes it as 'value' which Excel(2007) seems to - * tolerate. Changing the metadata for INDEX to have first parameter as 'array' class breaks - * other formulas involving INDEX. It seems like a special case needs to be made. Perhaps an - * important observation is that INDEX is one of very few functions that returns 'reference' type. - * - * This test has been added but disabled in order to document this issue. - */ - public void DISABLED_testIndexPi1() { - String formula = "INDEX(PI(),1)"; - Ptg[] ptgs = parseFormula(formula); - - confirmFuncClass(ptgs, 1, "PI", Ptg.CLASS_ARRAY); // fails as of POI 3.1 - confirmFuncClass(ptgs, 2, "INDEX", Ptg.CLASS_VALUE); - } - - /** - * Even though count expects args of type R, because A1 is a direct operand of a - * value operator it must get type V - */ - public void testDirectOperandOfValueOperator() { - String formula = "COUNT(A1*1)"; - Ptg[] ptgs = parseFormula(formula); - if (ptgs[0].getPtgClass() == Ptg.CLASS_REF) { - throw new AssertionFailedError("Identified bug 45348"); - } - - confirmTokenClass(ptgs, 0, Ptg.CLASS_VALUE); - confirmTokenClass(ptgs, 3, Ptg.CLASS_VALUE); - } - - /** - * A cell ref passed to a function expecting type V should be converted to type V - */ - public void testRtoV() { - - String formula = "lookup(A1, A3:A52, B3:B52)"; - Ptg[] ptgs = parseFormula(formula); - confirmTokenClass(ptgs, 0, Ptg.CLASS_VALUE); - } - - public void testComplexIRR_bug45041() { - String formula = "(1+IRR(SUMIF(A:A,ROW(INDIRECT(MIN(A:A)&\":\"&MAX(A:A))),B:B),0))^365-1"; - Ptg[] ptgs = parseFormula(formula); - - FuncVarPtg rowFunc = (FuncVarPtg) ptgs[10]; - FuncVarPtg sumifFunc = (FuncVarPtg) ptgs[12]; - assertEquals("ROW", rowFunc.getName()); - assertEquals("SUMIF", sumifFunc.getName()); - - if (rowFunc.getPtgClass() == Ptg.CLASS_VALUE || sumifFunc.getPtgClass() == Ptg.CLASS_VALUE) { - throw new AssertionFailedError("Identified bug 45041"); - } - confirmTokenClass(ptgs, 1, Ptg.CLASS_REF); - confirmTokenClass(ptgs, 2, Ptg.CLASS_REF); - confirmFuncClass(ptgs, 3, "MIN", Ptg.CLASS_VALUE); - confirmTokenClass(ptgs, 6, Ptg.CLASS_REF); - confirmFuncClass(ptgs, 7, "MAX", Ptg.CLASS_VALUE); - confirmFuncClass(ptgs, 9, "INDIRECT", Ptg.CLASS_REF); - confirmFuncClass(ptgs, 10, "ROW", Ptg.CLASS_ARRAY); - confirmTokenClass(ptgs, 11, Ptg.CLASS_REF); - confirmFuncClass(ptgs, 12, "SUMIF", Ptg.CLASS_ARRAY); - confirmFuncClass(ptgs, 14, "IRR", Ptg.CLASS_VALUE); - } - - private void confirmFuncClass(Ptg[] ptgs, int i, String expectedFunctionName, byte operandClass) { - confirmTokenClass(ptgs, i, operandClass); - AbstractFunctionPtg afp = (AbstractFunctionPtg) ptgs[i]; - assertEquals(expectedFunctionName, afp.getName()); - } - - private void confirmTokenClass(Ptg[] ptgs, int i, byte operandClass) { - Ptg ptg = ptgs[i]; - if (ptg.isBaseToken()) { - throw new AssertionFailedError("ptg[" + i + "] is a base token"); - } - if (operandClass != ptg.getPtgClass()) { - throw new AssertionFailedError("Wrong operand class for ptg (" - + ptg.toString() + "). Expected " + getOperandClassName(operandClass) - + " but got " + getOperandClassName(ptg.getPtgClass())); - } - } - - private static String getOperandClassName(byte ptgClass) { - switch (ptgClass) { - case Ptg.CLASS_REF: - return "R"; - case Ptg.CLASS_VALUE: - return "V"; - case Ptg.CLASS_ARRAY: - return "A"; - } - throw new RuntimeException("Unknown operand class (" + ptgClass + ")"); - } -} diff --git a/src/testcases/org/apache/poi/hssf/model/TestRVA.java b/src/testcases/org/apache/poi/hssf/model/TestRVA.java deleted file mode 100644 index 4869d87d6..000000000 --- a/src/testcases/org/apache/poi/hssf/model/TestRVA.java +++ /dev/null @@ -1,149 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.model; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.fail; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.usermodel.FormulaExtractor; -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; -import org.apache.poi.ss.formula.ptg.AttrPtg; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.apache.poi.ss.usermodel.CellType; -import org.junit.AfterClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; - -/** - * Tests 'operand class' transformation performed by - * OperandClassTransformer by comparing its results with those - * directly produced by Excel (in a sample spreadsheet). - */ -@RunWith(Parameterized.class) -public final class TestRVA { - - private static final String NEW_LINE = System.getProperty("line.separator"); - private static NPOIFSFileSystem poifs; - private static HSSFWorkbook workbook; - private static HSSFSheet sheet; - - - @Parameter(value = 0) - public HSSFCell formulaCell; - @Parameter(value = 1) - public String formula; - - @AfterClass - public static void closeResource() throws Exception { - workbook.close(); - poifs.close(); - } - - @Parameters(name="{1}") - public static Collection data() throws Exception { - poifs = new NPOIFSFileSystem(HSSFTestDataSamples.getSampleFile("testRVA.xls"), true); - workbook = new HSSFWorkbook(poifs); - sheet = workbook.getSheetAt(0); - - List data = new ArrayList(); - - for (int rowIdx = 0; true; rowIdx++) { - HSSFRow row = sheet.getRow(rowIdx); - if (row == null) { - break; - } - HSSFCell cell = row.getCell(0); - if (cell == null || cell.getCellTypeEnum() == CellType.BLANK) { - break; - } - - String formula = cell.getCellFormula(); - data.add(new Object[]{cell,formula}); - } - - return data; - } - - @Test - public void confirmCell() { - Ptg[] excelPtgs = FormulaExtractor.getPtgs(formulaCell); - Ptg[] poiPtgs = HSSFFormulaParser.parse(formula, workbook); - int nExcelTokens = excelPtgs.length; - int nPoiTokens = poiPtgs.length; - if (nExcelTokens != nPoiTokens) { - if (nExcelTokens == nPoiTokens + 1 && excelPtgs[0].getClass() == AttrPtg.class) { - // compensate for missing tAttrVolatile, which belongs in any formula - // involving OFFSET() et al. POI currently does not insert where required - Ptg[] temp = new Ptg[nExcelTokens]; - temp[0] = excelPtgs[0]; - System.arraycopy(poiPtgs, 0, temp, 1, nPoiTokens); - poiPtgs = temp; - } else { - fail("Expected " + nExcelTokens + " tokens but got " + nPoiTokens); - } - } - boolean hasMismatch = false; - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < nExcelTokens; i++) { - Ptg poiPtg = poiPtgs[i]; - Ptg excelPtg = excelPtgs[i]; - if (excelPtg.getClass() != poiPtg.getClass()) { - hasMismatch = true; - sb.append(" mismatch token type[" + i + "] " + getShortClassName(excelPtg) + " " - + excelPtg.getRVAType() + " - " + getShortClassName(poiPtg) + " " - + poiPtg.getRVAType()); - sb.append(NEW_LINE); - continue; - } - if (poiPtg.isBaseToken()) { - continue; - } - sb.append(" token[" + i + "] " + excelPtg.toString() + " " - + excelPtg.getRVAType()); - - if (excelPtg.getPtgClass() != poiPtg.getPtgClass()) { - hasMismatch = true; - sb.append(" - was " + poiPtg.getRVAType()); - } - sb.append(NEW_LINE); - } -// if (false) { // set 'true' to see trace of RVA values -// System.out.println(formulaCell.getRowIndex() + " " + formula); -// System.out.println(sb.toString()); -// } - assertFalse(hasMismatch); - } - - private String getShortClassName(Object o) { - String cn = o.getClass().getName(); - int pos = cn.lastIndexOf('.'); - return cn.substring(pos + 1); - } -} diff --git a/src/testcases/org/apache/poi/hssf/model/TestRowBlocksReader.java b/src/testcases/org/apache/poi/hssf/model/TestRowBlocksReader.java deleted file mode 100644 index bf1fce799..000000000 --- a/src/testcases/org/apache/poi/hssf/model/TestRowBlocksReader.java +++ /dev/null @@ -1,66 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.model; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.util.Arrays; - -import org.apache.poi.hssf.record.NumberRecord; -import org.apache.poi.hssf.record.Record; -import org.apache.poi.hssf.record.RowRecord; -import org.apache.poi.hssf.record.UnknownRecord; -import org.apache.poi.hssf.record.WindowTwoRecord; -import org.apache.poi.hssf.record.pivottable.ViewDefinitionRecord; -import org.apache.poi.util.LocaleUtil; -import org.junit.Test; - -/** - * Tests for {@link RowBlocksReader} - * - * @author Josh Micich - */ -public final class TestRowBlocksReader { - @Test - public void testAbnormalPivotTableRecords_bug46280() { - int SXVIEW_SID = ViewDefinitionRecord.sid; - Record[] inRecs = { - new RowRecord(0), - new NumberRecord(), - // normally MSODRAWING(0x00EC) would come here before SXVIEW - new UnknownRecord(SXVIEW_SID, "dummydata (SXVIEW: View Definition)".getBytes(LocaleUtil.CHARSET_1252)), - new WindowTwoRecord(), - }; - RecordStream rs = new RecordStream(Arrays.asList(inRecs), 0); - RowBlocksReader rbr = new RowBlocksReader(rs); - if (rs.peekNextClass() == WindowTwoRecord.class) { - // Should have stopped at the SXVIEW record - fail("Identified bug 46280b"); - } - RecordStream rbStream = rbr.getPlainRecordStream(); - assertEquals(inRecs[0], rbStream.getNext()); - assertEquals(inRecs[1], rbStream.getNext()); - assertFalse(rbStream.hasNext()); - assertTrue(rs.hasNext()); - assertEquals(inRecs[2], rs.getNext()); - assertEquals(inRecs[3], rs.getNext()); - } -} diff --git a/src/testcases/org/apache/poi/hssf/model/TestSheet.java b/src/testcases/org/apache/poi/hssf/model/TestSheet.java deleted file mode 100644 index 97b3fe0a6..000000000 --- a/src/testcases/org/apache/poi/hssf/model/TestSheet.java +++ /dev/null @@ -1,870 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.model; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.apache.poi.ddf.EscherDggRecord; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.record.BOFRecord; -import org.apache.poi.hssf.record.BlankRecord; -import org.apache.poi.hssf.record.CellValueRecordInterface; -import org.apache.poi.hssf.record.ColumnInfoRecord; -import org.apache.poi.hssf.record.DimensionsRecord; -import org.apache.poi.hssf.record.DrawingRecord; -import org.apache.poi.hssf.record.EOFRecord; -import org.apache.poi.hssf.record.EscherAggregate; -import org.apache.poi.hssf.record.FormulaRecord; -import org.apache.poi.hssf.record.GutsRecord; -import org.apache.poi.hssf.record.IndexRecord; -import org.apache.poi.hssf.record.MergeCellsRecord; -import org.apache.poi.hssf.record.MulBlankRecord; -import org.apache.poi.hssf.record.NoteRecord; -import org.apache.poi.hssf.record.NumberRecord; -import org.apache.poi.hssf.record.ObjRecord; -import org.apache.poi.hssf.record.Record; -import org.apache.poi.hssf.record.RecordBase; -import org.apache.poi.hssf.record.RowRecord; -import org.apache.poi.hssf.record.StringRecord; -import org.apache.poi.hssf.record.TextObjectRecord; -import org.apache.poi.hssf.record.UncalcedRecord; -import org.apache.poi.hssf.record.WindowTwoRecord; -import org.apache.poi.hssf.record.aggregates.ConditionalFormattingTable; -import org.apache.poi.hssf.record.aggregates.PageSettingsBlock; -import org.apache.poi.hssf.record.aggregates.RecordAggregate.RecordVisitor; -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFRichTextString; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.hssf.usermodel.RecordInspector.RecordCollector; -import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.ss.formula.FormulaShifter; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.util.HexRead; -import org.junit.Test; - -import junit.framework.AssertionFailedError; - -/** - * Unit test for the {@link InternalSheet} class. - */ -public final class TestSheet { - private static InternalSheet createSheet(List inRecs) { - return InternalSheet.createSheet(new RecordStream(inRecs, 0)); - } - - private static Record[] getSheetRecords(InternalSheet s, int offset) { - RecordCollector rc = new RecordCollector(); - s.visitContainedRecords(rc, offset); - return rc.getRecords(); - } - - @Test - public void testCreateSheet() { - // Check we're adding row and cell aggregates - List records = new ArrayList(); - records.add(BOFRecord.createSheetBOF()); - records.add( new DimensionsRecord() ); - records.add(createWindow2Record()); - records.add(EOFRecord.instance); - InternalSheet sheet = createSheet(records); - Record[] outRecs = getSheetRecords(sheet, 0); - - int pos = 0; - assertTrue(outRecs[pos++] instanceof BOFRecord ); - assertTrue(outRecs[pos++] instanceof IndexRecord); - assertTrue(outRecs[pos++] instanceof DimensionsRecord); - assertTrue(outRecs[pos++] instanceof WindowTwoRecord ); - assertTrue(outRecs[pos++] instanceof EOFRecord); - } - - private static Record createWindow2Record() { - WindowTwoRecord result = new WindowTwoRecord(); - result.setOptions(( short ) 0x6b6); - result.setTopRow(( short ) 0); - result.setLeftCol(( short ) 0); - result.setHeaderColor(0x40); - result.setPageBreakZoom(( short ) 0); - result.setNormalZoom(( short ) 0); - return result; - } - - private static final class MergedCellListener implements RecordVisitor { - - private int _count; - public MergedCellListener() { - _count = 0; - } - @Override - public void visitRecord(Record r) { - if (r instanceof MergeCellsRecord) { - _count++; - } - } - public int getCount() { - return _count; - } - } - - @Test - public void testAddMergedRegion() { - InternalSheet sheet = InternalSheet.createSheet(); - int regionsToAdd = 4096; - - //simple test that adds a load of regions - for (int n = 0; n < regionsToAdd; n++) - { - int index = sheet.addMergedRegion(0, (short) 0, 1, (short) 1); - assertTrue("Merged region index expected to be " + n + " got " + index, index == n); - } - - //test all the regions were indeed added - assertTrue(sheet.getNumMergedRegions() == regionsToAdd); - - //test that the regions were spread out over the appropriate number of records - MergedCellListener mcListener = new MergedCellListener(); - sheet.visitContainedRecords(mcListener, 0); - int recordsAdded = mcListener.getCount(); - int recordsExpected = regionsToAdd/1027; - if ((regionsToAdd % 1027) != 0) - recordsExpected++; - assertTrue("The " + regionsToAdd + " merged regions should have been spread out over " - + recordsExpected + " records, not " + recordsAdded, recordsAdded == recordsExpected); - // Check we can't add one with invalid date - try { - sheet.addMergedRegion(10, (short)10, 9, (short)12); - fail("Expected an exception to occur"); - } catch(IllegalArgumentException e) { - // occurs during successful test - assertEquals("The 'to' row (9) must not be less than the 'from' row (10)", e.getMessage()); - } - try { - sheet.addMergedRegion(10, (short)10, 12, (short)9); - fail("Expected an exception to occur"); - } catch(IllegalArgumentException e) { - // occurs during successful test - assertEquals("The 'to' col (9) must not be less than the 'from' col (10)", e.getMessage()); - } - } - - @Test - public void testRemoveMergedRegion() { - InternalSheet sheet = InternalSheet.createSheet(); - int regionsToAdd = 4096; - - for (int n = 0; n < regionsToAdd; n++) { - sheet.addMergedRegion(n, 0, n, 1); - } - - int nSheetRecords = sheet.getRecords().size(); - - //remove a third from the beginning - for (int n = 0; n < regionsToAdd/3; n++) - { - sheet.removeMergedRegion(0); - //assert they have been deleted - assertEquals("Num of regions", regionsToAdd - n - 1, sheet.getNumMergedRegions()); - } - - // merge records are removed from within the MergedCellsTable, - // so the sheet record count should not change - assertEquals("Sheet Records", nSheetRecords, sheet.getRecords().size()); - } - - /** - * Bug: 22922 (Reported by Xuemin Guan) - *

    - * Remove mergedregion fails when a sheet loses records after an initial CreateSheet - * fills up the records. - * - */ - @Test - public void testMovingMergedRegion() { - List records = new ArrayList(); - - CellRangeAddress[] cras = { - new CellRangeAddress(0, 1, 0, 2), - }; - MergeCellsRecord merged = new MergeCellsRecord(cras, 0, cras.length); - records.add(BOFRecord.createSheetBOF()); - records.add(new DimensionsRecord()); - records.add(new RowRecord(0)); - records.add(new RowRecord(1)); - records.add(new RowRecord(2)); - records.add(createWindow2Record()); - records.add(EOFRecord.instance); - records.add(merged); - - InternalSheet sheet = createSheet(records); - sheet.getRecords().remove(0); // TODO - what does this line do? - - //stub object to throw off list INDEX operations - sheet.removeMergedRegion(0); - assertEquals("Should be no more merged regions", 0, sheet.getNumMergedRegions()); - } - - @Test - public void testGetMergedRegionAt() { - //TODO - } - - @Test - public void testGetNumMergedRegions() { - //TODO - } - - /** - * Makes sure all rows registered for this sheet are aggregated, they were being skipped - * - */ - @Test - public void testRowAggregation() { - List records = new ArrayList(); - - records.add(InternalSheet.createBOF()); - records.add(new DimensionsRecord()); - records.add(new RowRecord(0)); - records.add(new RowRecord(1)); - FormulaRecord formulaRecord = new FormulaRecord(); - formulaRecord.setCachedResultTypeString(); - records.add(formulaRecord); - records.add(new StringRecord()); - records.add(new RowRecord(2)); - records.add(createWindow2Record()); - records.add(EOFRecord.instance); - - InternalSheet sheet = createSheet(records); - assertNotNull("Row [2] was skipped", sheet.getRow(2)); - } - - /** - * Make sure page break functionality works (in memory) - * - */ - @Test - public void testRowPageBreaks() { - short colFrom = 0; - short colTo = 255; - - InternalSheet worksheet = InternalSheet.createSheet(); - PageSettingsBlock sheet = worksheet.getPageSettings(); - sheet.setRowBreak(0, colFrom, colTo); - - assertTrue("no row break at 0", sheet.isRowBroken(0)); - assertEquals("1 row break available", 1, sheet.getNumRowBreaks()); - - sheet.setRowBreak(0, colFrom, colTo); - sheet.setRowBreak(0, colFrom, colTo); - - assertTrue("no row break at 0", sheet.isRowBroken(0)); - assertEquals("1 row break available", 1, sheet.getNumRowBreaks()); - - sheet.setRowBreak(10, colFrom, colTo); - sheet.setRowBreak(11, colFrom, colTo); - - assertTrue("no row break at 10", sheet.isRowBroken(10)); - assertTrue("no row break at 11", sheet.isRowBroken(11)); - assertEquals("3 row break available", 3, sheet.getNumRowBreaks()); - - - boolean is10 = false; - boolean is0 = false; - boolean is11 = false; - - int[] rowBreaks = sheet.getRowBreaks(); - for (int main : rowBreaks) { - if (main != 0 && main != 10 && main != 11) fail("Invalid page break"); - if (main == 0) is0 = true; - if (main == 10) is10= true; - if (main == 11) is11 = true; - } - - assertTrue("one of the breaks didnt make it", is0 && is10 && is11); - - sheet.removeRowBreak(11); - assertFalse("row should be removed", sheet.isRowBroken(11)); - - sheet.removeRowBreak(0); - assertFalse("row should be removed", sheet.isRowBroken(0)); - - sheet.removeRowBreak(10); - assertFalse("row should be removed", sheet.isRowBroken(10)); - - assertEquals("no more breaks", 0, sheet.getNumRowBreaks()); - } - - /** - * Make sure column pag breaks works properly (in-memory) - * - */ - @Test - public void testColPageBreaks() { - short rowFrom = 0; - short rowTo = (short)65535; - - InternalSheet worksheet = InternalSheet.createSheet(); - PageSettingsBlock sheet = worksheet.getPageSettings(); - sheet.setColumnBreak((short)0, rowFrom, rowTo); - - assertTrue("no col break at 0", sheet.isColumnBroken(0)); - assertEquals("1 col break available", 1, sheet.getNumColumnBreaks()); - - sheet.setColumnBreak((short)0, rowFrom, rowTo); - - assertTrue("no col break at 0", sheet.isColumnBroken(0)); - assertEquals("1 col break available", 1, sheet.getNumColumnBreaks()); - - sheet.setColumnBreak((short)1, rowFrom, rowTo); - sheet.setColumnBreak((short)10, rowFrom, rowTo); - sheet.setColumnBreak((short)15, rowFrom, rowTo); - - assertTrue("no col break at 1", sheet.isColumnBroken(1)); - assertTrue("no col break at 10", sheet.isColumnBroken(10)); - assertTrue("no col break at 15", sheet.isColumnBroken(15)); - assertEquals("4 col break available", 4, sheet.getNumColumnBreaks()); - - boolean is10 = false; - boolean is0 = false; - boolean is1 = false; - boolean is15 = false; - - int[] colBreaks = sheet.getColumnBreaks(); - for (int main : colBreaks) { - if (main != 0 && main != 1 && main != 10 && main != 15) fail("Invalid page break"); - if (main == 0) is0 = true; - if (main == 1) is1 = true; - if (main == 10) is10= true; - if (main == 15) is15 = true; - } - - assertTrue("one of the breaks didnt make it", is0 && is1 && is10 && is15); - - sheet.removeColumnBreak(15); - assertFalse("column break should not be there", sheet.isColumnBroken(15)); - - sheet.removeColumnBreak(0); - assertFalse("column break should not be there", sheet.isColumnBroken(0)); - - sheet.removeColumnBreak(1); - assertFalse("column break should not be there", sheet.isColumnBroken(1)); - - sheet.removeColumnBreak(10); - assertFalse("column break should not be there", sheet.isColumnBroken(10)); - - assertEquals("no more breaks", 0, sheet.getNumColumnBreaks()); - } - - /** - * test newly added method Sheet.getXFIndexForColAt(..) - * works as designed. - */ - @Test - public void testXFIndexForColumn() { - final short TEST_IDX = 10; - final short DEFAULT_IDX = 0xF; // 15 - short xfindex = Short.MIN_VALUE; - InternalSheet sheet = InternalSheet.createSheet(); - - // without ColumnInfoRecord - xfindex = sheet.getXFIndexForColAt((short) 0); - assertEquals(DEFAULT_IDX, xfindex); - xfindex = sheet.getXFIndexForColAt((short) 1); - assertEquals(DEFAULT_IDX, xfindex); - - ColumnInfoRecord nci = new ColumnInfoRecord(); - sheet._columnInfos.insertColumn(nci); - - // single column ColumnInfoRecord - nci.setFirstColumn((short) 2); - nci.setLastColumn((short) 2); - nci.setXFIndex(TEST_IDX); - xfindex = sheet.getXFIndexForColAt((short) 0); - assertEquals(DEFAULT_IDX, xfindex); - xfindex = sheet.getXFIndexForColAt((short) 1); - assertEquals(DEFAULT_IDX, xfindex); - xfindex = sheet.getXFIndexForColAt((short) 2); - assertEquals(TEST_IDX, xfindex); - xfindex = sheet.getXFIndexForColAt((short) 3); - assertEquals(DEFAULT_IDX, xfindex); - - // ten column ColumnInfoRecord - nci.setFirstColumn((short) 2); - nci.setLastColumn((short) 11); - nci.setXFIndex(TEST_IDX); - xfindex = sheet.getXFIndexForColAt((short) 1); - assertEquals(DEFAULT_IDX, xfindex); - xfindex = sheet.getXFIndexForColAt((short) 2); - assertEquals(TEST_IDX, xfindex); - xfindex = sheet.getXFIndexForColAt((short) 6); - assertEquals(TEST_IDX, xfindex); - xfindex = sheet.getXFIndexForColAt((short) 11); - assertEquals(TEST_IDX, xfindex); - xfindex = sheet.getXFIndexForColAt((short) 12); - assertEquals(DEFAULT_IDX, xfindex); - - // single column ColumnInfoRecord starting at index 0 - nci.setFirstColumn((short) 0); - nci.setLastColumn((short) 0); - nci.setXFIndex(TEST_IDX); - xfindex = sheet.getXFIndexForColAt((short) 0); - assertEquals(TEST_IDX, xfindex); - xfindex = sheet.getXFIndexForColAt((short) 1); - assertEquals(DEFAULT_IDX, xfindex); - - // ten column ColumnInfoRecord starting at index 0 - nci.setFirstColumn((short) 0); - nci.setLastColumn((short) 9); - nci.setXFIndex(TEST_IDX); - xfindex = sheet.getXFIndexForColAt((short) 0); - assertEquals(TEST_IDX, xfindex); - xfindex = sheet.getXFIndexForColAt((short) 7); - assertEquals(TEST_IDX, xfindex); - xfindex = sheet.getXFIndexForColAt((short) 9); - assertEquals(TEST_IDX, xfindex); - xfindex = sheet.getXFIndexForColAt((short) 10); - assertEquals(DEFAULT_IDX, xfindex); - } - - private static final class SizeCheckingRecordVisitor implements RecordVisitor { - - private int _totalSize; - public SizeCheckingRecordVisitor() { - _totalSize = 0; - } - @Override - public void visitRecord(Record r) { - - int estimatedSize=r.getRecordSize(); - byte[] buf = new byte[estimatedSize]; - int serializedSize = r.serialize(0, buf); - if (estimatedSize != serializedSize) { - throw new AssertionFailedError("serialized size mismatch for record (" - + r.getClass().getName() + ")"); - } - _totalSize += estimatedSize; - } - public int getTotalSize() { - return _totalSize; - } - } - /** - * Prior to bug 45066, POI would get the estimated sheet size wrong - * when an UncalcedRecord was present.

    - */ - @Test - public void testUncalcSize_bug45066() { - - List records = new ArrayList(); - records.add(BOFRecord.createSheetBOF()); - records.add(new UncalcedRecord()); - records.add(new DimensionsRecord()); - records.add(createWindow2Record()); - records.add(EOFRecord.instance); - InternalSheet sheet = createSheet(records); - - // The original bug was due to different logic for collecting records for sizing and - // serialization. The code has since been refactored into a single method for visiting - // all contained records. Now this test is much less interesting - SizeCheckingRecordVisitor scrv = new SizeCheckingRecordVisitor(); - sheet.visitContainedRecords(scrv, 0); - assertEquals(90, scrv.getTotalSize()); - } - - /** - * Prior to bug 45145 RowRecordsAggregate and ValueRecordsAggregate could - * sometimes occur in reverse order. This test reproduces one of those situations and makes - * sure that RRA comes before VRA.
    - * - * The code here represents a normal POI use case where a spreadsheet is created from scratch. - */ - @Test - public void testRowValueAggregatesOrder_bug45145() { - - InternalSheet sheet = InternalSheet.createSheet(); - - RowRecord rr = new RowRecord(5); - sheet.addRow(rr); - - CellValueRecordInterface cvr = new BlankRecord(); - cvr.setColumn((short)0); - cvr.setRow(5); - sheet.addValueRecord(5, cvr); - - - int dbCellRecordPos = getDbCellRecordPos(sheet); - if (dbCellRecordPos == 252) { - // The overt symptom of the bug - // DBCELL record pos is calculated wrong if VRA comes before RRA - throw new AssertionFailedError("Identified bug 45145"); - } - -// if (false) { -// // make sure that RRA and VRA are in the right place -// // (Aug 2008) since the VRA is now part of the RRA, there is much less chance that -// // they could get out of order. Still, one could write serialize the sheet here, -// // and read back with EventRecordFactory to make sure... -// } - assertEquals(242, dbCellRecordPos); - } - - /** - * @return the value calculated for the position of the first DBCELL record for this sheet. - * That value is found on the IndexRecord. - */ - private static int getDbCellRecordPos(InternalSheet sheet) { - - MyIndexRecordListener myIndexListener = new MyIndexRecordListener(); - sheet.visitContainedRecords(myIndexListener, 0); - IndexRecord indexRecord = myIndexListener.getIndexRecord(); - int dbCellRecordPos = indexRecord.getDbcellAt(0); - return dbCellRecordPos; - } - - private static final class MyIndexRecordListener implements RecordVisitor { - - private IndexRecord _indexRecord; - public MyIndexRecordListener() { - // no-arg constructor - } - public IndexRecord getIndexRecord() { - return _indexRecord; - } - @Override - public void visitRecord(Record r) { - if (r instanceof IndexRecord) { - if (_indexRecord != null) { - throw new RuntimeException("too many index records"); - } - _indexRecord = (IndexRecord)r; - } - } - } - - /** - * Checks for bug introduced around r682282-r683880 that caused a second GUTS records - * which in turn got the dimensions record out of alignment - */ - @Test - public void testGutsRecord_bug45640() { - - InternalSheet sheet = InternalSheet.createSheet(); - sheet.addRow(new RowRecord(0)); - sheet.addRow(new RowRecord(1)); - sheet.groupRowRange( 0, 1, true ); - sheet.toString(); - List recs = sheet.getRecords(); - int count=0; - for(int i=0; i< recs.size(); i++) { - if (recs.get(i) instanceof GutsRecord) { - count++; - } - } - if (count == 2) { - throw new AssertionFailedError("Identified bug 45640"); - } - assertEquals(1, count); - } - - @Test - public void testMisplacedMergedCellsRecords_bug45699() throws Exception { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("ex45698-22488.xls"); - - HSSFSheet sheet = wb.getSheetAt(0); - HSSFRow row = sheet.getRow(3); - HSSFCell cell = row.getCell(4); - if (cell == null) { - fail("Identified bug 45699"); - } - assertEquals("Informations", cell.getRichStringCellValue().getString()); - - wb.close(); - } - /** - * In 3.1, setting margins between creating first row and first cell caused an exception. - */ - @Test - public void testSetMargins_bug45717() throws Exception { - HSSFWorkbook workbook = new HSSFWorkbook(); - HSSFSheet sheet = workbook.createSheet("Vorschauliste"); - HSSFRow row = sheet.createRow(0); - - sheet.setMargin(HSSFSheet.LeftMargin, 0.3); - try { - row.createCell(0); - } catch (IllegalStateException e) { - if (e.getMessage().equals("Cannot create value records before row records exist")) { - fail("Identified bug 45717"); - } - throw e; - } finally { - workbook.close(); - } - } - - /** - * Some apps seem to write files with missing DIMENSION records. - * Excel(2007) tolerates this, so POI should too. - */ - @Test - public void testMissingDims() { - - int rowIx = 5; - int colIx = 6; - NumberRecord nr = new NumberRecord(); - nr.setRow(rowIx); - nr.setColumn((short) colIx); - nr.setValue(3.0); - - List inRecs = new ArrayList(); - inRecs.add(BOFRecord.createSheetBOF()); - inRecs.add(new RowRecord(rowIx)); - inRecs.add(nr); - inRecs.add(createWindow2Record()); - inRecs.add(EOFRecord.instance); - InternalSheet sheet; - try { - sheet = createSheet(inRecs); - } catch (RuntimeException e) { - if ("DimensionsRecord was not found".equals(e.getMessage())) { - throw new AssertionFailedError("Identified bug 46206"); - } - throw e; - } - - RecordCollector rv = new RecordCollector(); - sheet.visitContainedRecords(rv, rowIx); - Record[] outRecs = rv.getRecords(); - assertEquals(8, outRecs.length); - DimensionsRecord dims = (DimensionsRecord) outRecs[5]; - assertEquals(rowIx, dims.getFirstRow()); - assertEquals(rowIx, dims.getLastRow()); - assertEquals(colIx, dims.getFirstCol()); - assertEquals(colIx, dims.getLastCol()); - } - - /** - * Prior to the fix for bug 46547, shifting formulas would have the side-effect - * of creating a {@link ConditionalFormattingTable}. There was no impairment to - * functionality since empty record aggregates are equivalent to missing record - * aggregates. However, since this unnecessary creation helped expose bug 46547b, - * and since there is a slight performance hit the fix was made to avoid it. - */ - @Test - public void testShiftFormulasAddCondFormat_bug46547() { - // Create a sheet with data validity (similar to bugzilla attachment id=23131). - InternalSheet sheet = InternalSheet.createSheet(); - - List sheetRecs = sheet.getRecords(); - assertEquals(23, sheetRecs.size()); - - FormulaShifter shifter = FormulaShifter.createForRowShift(0, "", 0, 0, 1, SpreadsheetVersion.EXCEL97); - sheet.updateFormulasAfterCellShift(shifter, 0); - if (sheetRecs.size() == 24 && sheetRecs.get(22) instanceof ConditionalFormattingTable) { - throw new AssertionFailedError("Identified bug 46547a"); - } - assertEquals(23, sheetRecs.size()); - } - /** - * Bug 46547 happened when attempting to add conditional formatting to a sheet - * which already had data validity constraints. - */ - @Test - public void testAddCondFormatAfterDataValidation_bug46547() { - // Create a sheet with data validity (similar to bugzilla attachment id=23131). - InternalSheet sheet = InternalSheet.createSheet(); - sheet.getOrCreateDataValidityTable(); - - ConditionalFormattingTable cft; - // attempt to add conditional formatting - try { - - cft = sheet.getConditionalFormattingTable(); // lazy getter - } catch (ClassCastException e) { - throw new AssertionFailedError("Identified bug 46547b"); - } - assertNotNull(cft); - } - - @Test - public void testCloneMulBlank_bug46776() { - Record[] recs = { - InternalSheet.createBOF(), - new DimensionsRecord(), - new RowRecord(1), - new MulBlankRecord(1, 3, new short[] { 0x0F, 0x0F, 0x0F, } ), - new RowRecord(2), - createWindow2Record(), - EOFRecord.instance, - }; - - InternalSheet sheet = createSheet(Arrays.asList(recs)); - - InternalSheet sheet2; - try { - sheet2 = sheet.cloneSheet(); - } catch (RuntimeException e) { - if (e.getMessage().equals("The class org.apache.poi.hssf.record.MulBlankRecord needs to define a clone method")) { - throw new AssertionFailedError("Identified bug 46776"); - } - throw e; - } - - RecordCollector rc = new RecordCollector(); - sheet2.visitContainedRecords(rc, 0); - Record[] clonedRecs = rc.getRecords(); - assertEquals(recs.length+2, clonedRecs.length); // +2 for INDEX and DBCELL - } - - @Test - public void testCreateAggregate() { - String msoDrawingRecord1 = - "0F 00 02 F0 20 01 00 00 10 00 08 F0 08 00 00 00 \n" + - "03 00 00 00 02 04 00 00 0F 00 03 F0 08 01 00 00 \n" + - "0F 00 04 F0 28 00 00 00 01 00 09 F0 10 00 00 00 \n" + - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 \n" + - "02 00 0A F0 08 00 00 00 00 04 00 00 05 00 00 00 \n" + - "0F 00 04 F0 64 00 00 00 42 01 0A F0 08 00 00 00 \n" + - "01 04 00 00 00 0A 00 00 73 00 0B F0 2A 00 00 00 \n" + - "BF 00 08 00 08 00 44 01 04 00 00 00 7F 01 00 00 \n" + - "01 00 BF 01 00 00 11 00 C0 01 40 00 00 08 FF 01 \n" + - "10 00 10 00 BF 03 00 00 08 00 00 00 10 F0 12 00 \n" + - "00 00 00 00 01 00 54 00 05 00 45 00 01 00 88 03 \n" + - "05 00 94 00 00 00 11 F0 00 00 00 00"; - - String msoDrawingRecord2 = - "0F 00 04 F0 64 00 00 00 42 01 0A F0 08 00 00 00 " + - "02 04 00 00 80 0A 00 00 73 00 0B F0 2A 00 00 00 " + - "BF 00 08 00 08 00 44 01 04 00 00 00 7F 01 00 00 " + - "01 00 BF 01 00 00 11 00 C0 01 40 00 00 08 FF 01 " + - "10 00 10 00 BF 03 00 00 08 00 00 00 10 F0 12 00 " + - "00 00 00 00 01 00 8D 03 05 00 E4 00 03 00 4D 03 " + - "0B 00 0C 00 00 00 11 F0 00 00 00 00"; - - DrawingRecord d1 = new DrawingRecord(); - d1.setData( HexRead.readFromString( msoDrawingRecord1 ) ); - - ObjRecord r1 = new ObjRecord(); - - DrawingRecord d2 = new DrawingRecord(); - d2.setData( HexRead.readFromString( msoDrawingRecord2 ) ); - - TextObjectRecord r2 = new TextObjectRecord(); - r2.setStr(new HSSFRichTextString("Aggregated")); - NoteRecord n2 = new NoteRecord(); - - List recordStream = new ArrayList(); - recordStream.add(InternalSheet.createBOF()); - recordStream.add( d1 ); - recordStream.add( r1 ); - recordStream.add(createWindow2Record()); - recordStream.add(EOFRecord.instance); - - confirmAggregatedRecords(recordStream); - - - recordStream = new ArrayList(); - recordStream.add(InternalSheet.createBOF()); - recordStream.add( d1 ); - recordStream.add( r1 ); - recordStream.add( d2 ); - recordStream.add( r2 ); - recordStream.add(createWindow2Record()); - recordStream.add(EOFRecord.instance); - - confirmAggregatedRecords(recordStream); - - recordStream = new ArrayList(); - recordStream.add(InternalSheet.createBOF()); - recordStream.add( d1 ); - recordStream.add( r1 ); - recordStream.add( d2 ); - recordStream.add( r2 ); - recordStream.add( n2 ); - recordStream.add(createWindow2Record()); - recordStream.add(EOFRecord.instance); - - confirmAggregatedRecords(recordStream); - } - - private void confirmAggregatedRecords(List recordStream){ - InternalSheet sheet = InternalSheet.createSheet(); - sheet.getRecords().clear(); - sheet.getRecords().addAll(recordStream); - - List sheetRecords = sheet.getRecords(); - - DrawingManager2 drawingManager = new DrawingManager2(new EscherDggRecord() ); - sheet.aggregateDrawingRecords(drawingManager, false); - - assertEquals(4, sheetRecords.size()); - assertEquals(BOFRecord.sid, ((Record)sheetRecords.get(0)).getSid()); - assertEquals(EscherAggregate.sid, ((Record)sheetRecords.get(1)).getSid()); - assertEquals(WindowTwoRecord.sid, ((Record)sheetRecords.get(2)).getSid()); - assertEquals(EOFRecord.sid, ((Record)sheetRecords.get(3)).getSid()); - } - - @Test - public void testSheetDimensions() throws IOException{ - InternalSheet sheet = InternalSheet.createSheet(); - DimensionsRecord dimensions = (DimensionsRecord)sheet.findFirstRecordBySid(DimensionsRecord.sid); - assertEquals(0, dimensions.getFirstCol()); - assertEquals(0, dimensions.getFirstRow()); - assertEquals(1, dimensions.getLastCol()); // plus pne - assertEquals(1, dimensions.getLastRow()); // plus pne - - RowRecord rr = new RowRecord(0); - sheet.addRow(rr); - - assertEquals(0, dimensions.getFirstCol()); - assertEquals(0, dimensions.getFirstRow()); - assertEquals(1, dimensions.getLastCol()); - assertEquals(1, dimensions.getLastRow()); - - CellValueRecordInterface cvr; - - cvr = new BlankRecord(); - cvr.setColumn((short)0); - cvr.setRow(0); - sheet.addValueRecord(0, cvr); - - assertEquals(0, dimensions.getFirstCol()); - assertEquals(0, dimensions.getFirstRow()); - assertEquals(1, dimensions.getLastCol()); - assertEquals(1, dimensions.getLastRow()); - - cvr = new BlankRecord(); - cvr.setColumn((short)1); - cvr.setRow(0); - sheet.addValueRecord(0, cvr); - - assertEquals(0, dimensions.getFirstCol()); - assertEquals(0, dimensions.getFirstRow()); - assertEquals(2, dimensions.getLastCol()); //YK: failed until Bugzilla 53414 was fixed - assertEquals(1, dimensions.getLastRow()); - } -} diff --git a/src/testcases/org/apache/poi/hssf/model/TestSheetAdditional.java b/src/testcases/org/apache/poi/hssf/model/TestSheetAdditional.java deleted file mode 100644 index 8bd521edc..000000000 --- a/src/testcases/org/apache/poi/hssf/model/TestSheetAdditional.java +++ /dev/null @@ -1,68 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.model; - -import junit.framework.TestCase; - -import org.apache.poi.hssf.record.ColumnInfoRecord; - -/** - * @author Tony Poppleton - */ -public final class TestSheetAdditional extends TestCase { - - public void testGetCellWidth() { - InternalSheet sheet = InternalSheet.createSheet(); - ColumnInfoRecord nci = new ColumnInfoRecord(); - - // Prepare test model - nci.setFirstColumn(5); - nci.setLastColumn(10); - nci.setColumnWidth(100); - - - sheet._columnInfos.insertColumn(nci); - - assertEquals(100,sheet.getColumnWidth(5)); - assertEquals(100,sheet.getColumnWidth(6)); - assertEquals(100,sheet.getColumnWidth(7)); - assertEquals(100,sheet.getColumnWidth(8)); - assertEquals(100,sheet.getColumnWidth(9)); - assertEquals(100,sheet.getColumnWidth(10)); - - sheet.setColumnWidth(6,200); - - assertEquals(100,sheet.getColumnWidth(5)); - assertEquals(200,sheet.getColumnWidth(6)); - assertEquals(100,sheet.getColumnWidth(7)); - assertEquals(100,sheet.getColumnWidth(8)); - assertEquals(100,sheet.getColumnWidth(9)); - assertEquals(100,sheet.getColumnWidth(10)); - } - - public void testMaxColumnWidth() { - InternalSheet sheet = InternalSheet.createSheet(); - sheet.setColumnWidth(0, 255*256); //the limit - try { - sheet.setColumnWidth(0, 256*256); //the limit - fail("expected exception"); - } catch (IllegalArgumentException e){ - assertEquals(e.getMessage(), "The maximum column width for an individual cell is 255 characters."); - } - } -} diff --git a/src/testcases/org/apache/poi/hssf/model/TestWorkbook.java b/src/testcases/org/apache/poi/hssf/model/TestWorkbook.java deleted file mode 100644 index 558a5ec0f..000000000 --- a/src/testcases/org/apache/poi/hssf/model/TestWorkbook.java +++ /dev/null @@ -1,161 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.model; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; - -import org.apache.poi.hssf.record.CountryRecord; -import org.apache.poi.hssf.record.FontRecord; -import org.apache.poi.hssf.record.RecalcIdRecord; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.hssf.usermodel.TestHSSFWorkbook; -import org.apache.poi.ss.formula.OperationEvaluationContext; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.ss.formula.functions.FreeRefFunction; -import org.apache.poi.ss.formula.udf.AggregatingUDFFinder; -import org.apache.poi.ss.formula.udf.DefaultUDFFinder; -import org.apache.poi.ss.formula.udf.UDFFinder; -import org.junit.Test; - -/** - * Unit test for the Workbook class. - */ -public final class TestWorkbook { - @Test - public void testFontStuff() throws IOException { - HSSFWorkbook hwb = new HSSFWorkbook(); - InternalWorkbook wb = TestHSSFWorkbook.getInternalWorkbook(hwb); - - assertEquals(4, wb.getNumberOfFontRecords()); - assertEquals(68, wb.getRecords().size()); - - FontRecord f1 = wb.getFontRecordAt(0); - FontRecord f4 = wb.getFontRecordAt(3); - - assertEquals(0, wb.getFontIndex(f1)); - assertEquals(3, wb.getFontIndex(f4)); - - assertEquals(f1, wb.getFontRecordAt(0)); - assertEquals(f4, wb.getFontRecordAt(3)); - - // There is no 4! new ones go in at 5 - - FontRecord n = wb.createNewFont(); - assertEquals(69, wb.getRecords().size()); - assertEquals(5, wb.getNumberOfFontRecords()); - assertEquals(5, wb.getFontIndex(n)); - assertEquals(n, wb.getFontRecordAt(5)); - - // And another - FontRecord n6 = wb.createNewFont(); - assertEquals(70, wb.getRecords().size()); - assertEquals(6, wb.getNumberOfFontRecords()); - assertEquals(6, wb.getFontIndex(n6)); - assertEquals(n6, wb.getFontRecordAt(6)); - - - // Now remove the one formerly at 5 - assertEquals(70, wb.getRecords().size()); - wb.removeFontRecord(n); - - // Check that 6 has gone to 5 - assertEquals(69, wb.getRecords().size()); - assertEquals(5, wb.getNumberOfFontRecords()); - assertEquals(5, wb.getFontIndex(n6)); - assertEquals(n6, wb.getFontRecordAt(5)); - - // Check that the earlier ones are unchanged - assertEquals(0, wb.getFontIndex(f1)); - assertEquals(3, wb.getFontIndex(f4)); - assertEquals(f1, wb.getFontRecordAt(0)); - assertEquals(f4, wb.getFontRecordAt(3)); - - // Finally, add another one - FontRecord n7 = wb.createNewFont(); - assertEquals(70, wb.getRecords().size()); - assertEquals(6, wb.getNumberOfFontRecords()); - assertEquals(6, wb.getFontIndex(n7)); - assertEquals(n7, wb.getFontRecordAt(6)); - - hwb.close(); - } - - @Test - public void testAddNameX() throws IOException { - HSSFWorkbook hwb = new HSSFWorkbook(); - InternalWorkbook wb = TestHSSFWorkbook.getInternalWorkbook(hwb); - assertNotNull(wb.getNameXPtg("ISODD", AggregatingUDFFinder.DEFAULT)); - - FreeRefFunction NotImplemented = new FreeRefFunction() { - @Override - public ValueEval evaluate(ValueEval[] args, OperationEvaluationContext ec) { - throw new RuntimeException("not implemented"); - } - }; - - /* - * register the two test UDFs in a UDF finder, to be passed to the evaluator - */ - UDFFinder udff1 = new DefaultUDFFinder(new String[] { "myFunc", }, - new FreeRefFunction[] { NotImplemented }); - UDFFinder udff2 = new DefaultUDFFinder(new String[] { "myFunc2", }, - new FreeRefFunction[] { NotImplemented }); - UDFFinder udff = new AggregatingUDFFinder(udff1, udff2); - assertNotNull(wb.getNameXPtg("myFunc", udff)); - assertNotNull(wb.getNameXPtg("myFunc2", udff)); - - assertNull(wb.getNameXPtg("myFunc3", udff)); // myFunc3 is unknown - - hwb.close(); - } - - @Test - public void testRecalcId() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - assertFalse(wb.getForceFormulaRecalculation()); - - InternalWorkbook iwb = TestHSSFWorkbook.getInternalWorkbook(wb); - int countryPos = iwb.findFirstRecordLocBySid(CountryRecord.sid); - assertTrue(countryPos != -1); - // RecalcIdRecord is not present in new workbooks - assertEquals(null, iwb.findFirstRecordBySid(RecalcIdRecord.sid)); - RecalcIdRecord record = iwb.getRecalcId(); - assertNotNull(record); - assertSame(record, iwb.getRecalcId()); - - assertSame(record, iwb.findFirstRecordBySid(RecalcIdRecord.sid)); - assertEquals(countryPos + 1, iwb.findFirstRecordLocBySid(RecalcIdRecord.sid)); - - record.setEngineId(100); - assertEquals(100, record.getEngineId()); - assertTrue(wb.getForceFormulaRecalculation()); - - wb.setForceFormulaRecalculation(true); // resets the EngineId flag to zero - assertEquals(0, record.getEngineId()); - assertFalse(wb.getForceFormulaRecalculation()); - - wb.close(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/AllRecordTests.java b/src/testcases/org/apache/poi/hssf/record/AllRecordTests.java deleted file mode 100644 index e32816756..000000000 --- a/src/testcases/org/apache/poi/hssf/record/AllRecordTests.java +++ /dev/null @@ -1,96 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record; - -import org.apache.poi.hssf.record.aggregates.AllRecordAggregateTests; -import org.apache.poi.hssf.record.cf.TestCellRange; -import org.apache.poi.hssf.record.chart.AllChartRecordTests; -import org.apache.poi.hssf.record.common.TestUnicodeString; -import org.apache.poi.hssf.record.pivot.AllPivotRecordTests; -import org.apache.poi.poifs.crypt.AllEncryptionTests; -import org.apache.poi.ss.formula.constant.TestConstantValueParser; -import org.apache.poi.ss.formula.ptg.AllFormulaTests; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -/** - * Collects all tests for package org.apache.poi.hssf.record and sub-packages. - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - AllChartRecordTests.class, - AllEncryptionTests.class, - AllFormulaTests.class, - AllPivotRecordTests.class, - AllRecordAggregateTests.class, - TestArrayRecord.class, - TestBOFRecord.class, - TestBoolErrRecord.class, - TestBoundSheetRecord.class, - TestCellRange.class, - TestCFHeaderRecord.class, - TestCFRuleRecord.class, - TestColumnInfoRecord.class, - TestCommonObjectDataSubRecord.class, - TestConstantValueParser.class, - TestDVALRecord.class, - TestDrawingGroupRecord.class, - TestDrawingRecord.class, - TestEmbeddedObjectRefSubRecord.class, - TestEndSubRecord.class, - TestEscherAggregate.class, - TestExtendedFormatRecord.class, - TestExternalNameRecord.class, - TestFeatRecord.class, - TestFontRecord.class, - TestFormulaRecord.class, - TestHyperlinkRecord.class, - TestInterfaceEndRecord.class, - TestLabelRecord.class, - TestLbsDataSubRecord.class, - TestMergeCellsRecord.class, - TestNameRecord.class, - TestNoteRecord.class, - TestNoteStructureSubRecord.class, - TestObjRecord.class, - //TestPaletteRecord.class, //converted to junit4 - TestPaneRecord.class, - TestPLVRecord.class, - TestRecalcIdRecord.class, - TestRecordFactory.class, - TestRecordFactoryInputStream.class, - TestRecordInputStream.class, - TestSCLRecord.class, - TestSSTDeserializer.class, - TestSSTRecord.class, - TestSSTRecordSizeCalculator.class, - TestSharedFormulaRecord.class, - TestStringRecord.class, - TestStyleRecord.class, - TestSubRecord.class, - TestSupBookRecord.class, - TestTableRecord.class, - TestTextObjectBaseRecord.class, - TestTextObjectRecord.class, - TestUnicodeNameRecord.class, - TestUnicodeString.class, - TestWriteAccessRecord.class, - TestDConRefRecord.class -}) -public final class AllRecordTests { -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestArrayRecord.java b/src/testcases/org/apache/poi/hssf/record/TestArrayRecord.java deleted file mode 100644 index ff5fe0ad9..000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestArrayRecord.java +++ /dev/null @@ -1,77 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record; - -import junit.framework.TestCase; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.hssf.util.CellRangeAddress8Bit; -import org.apache.poi.ss.formula.Formula; -import org.apache.poi.ss.formula.FormulaParser; -import org.apache.poi.ss.formula.FormulaRenderer; -import org.apache.poi.ss.formula.FormulaType; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.apache.poi.util.HexDump; -import org.apache.poi.util.HexRead; - -public final class TestArrayRecord extends TestCase { - - public void testRead() { - String hex = - "21 02 25 00 01 00 01 00 01 01 00 00 00 00 00 00 " + - "17 00 65 00 00 01 00 02 C0 02 C0 65 00 00 01 00 " + - "03 C0 03 C0 04 62 01 07 00"; - byte[] data = HexRead.readFromString(hex); - RecordInputStream in = TestcaseRecordInputStream.create(data); - ArrayRecord r1 = new ArrayRecord(in); - CellRangeAddress8Bit range = r1.getRange(); - assertEquals(1, range.getFirstColumn()); - assertEquals(1, range.getLastColumn()); - assertEquals(1, range.getFirstRow()); - assertEquals(1, range.getLastRow()); - - Ptg[] ptg = r1.getFormulaTokens(); - assertEquals("MAX(C1:C2-D1:D2)", FormulaRenderer.toFormulaString(null, ptg)); - - //construct a new ArrayRecord with the same contents as r1 - Ptg[] fmlaPtg = FormulaParser.parse("MAX(C1:C2-D1:D2)", null, FormulaType.ARRAY, 0); - ArrayRecord r2 = new ArrayRecord(Formula.create(fmlaPtg), new CellRangeAddress8Bit(1, 1, 1, 1)); - byte[] ser = r2.serialize(); - //serialize and check that the data is the same as in r1 - assertEquals(HexDump.toHex(data), HexDump.toHex(ser)); - } - - public void testBug57231() { - HSSFWorkbook wb = HSSFTestDataSamples - .openSampleWorkbook("57231_MixedGasReport.xls"); - HSSFSheet sheet = wb.getSheet("master"); - - HSSFSheet newSheet = wb.cloneSheet(wb.getSheetIndex(sheet)); - int idx = wb.getSheetIndex(newSheet); - wb.setSheetName(idx, "newName"); - - // Write the output to a file - HSSFWorkbook wbBack = HSSFTestDataSamples.writeOutAndReadBack(wb); - assertNotNull(wbBack); - - assertNotNull(wbBack.getSheet("master")); - assertNotNull(wbBack.getSheet("newName")); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestAutoFilterInfoRecord.java b/src/testcases/org/apache/poi/hssf/record/TestAutoFilterInfoRecord.java deleted file mode 100644 index 45819504f..000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestAutoFilterInfoRecord.java +++ /dev/null @@ -1,67 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record; - -import static org.junit.Assert.assertArrayEquals; -import junit.framework.TestCase; - -/** - * Tests the AutoFilterInfoRecord class. - * - * @author Yegor Kozlov - */ -public final class TestAutoFilterInfoRecord extends TestCase { - private final byte[] data = new byte[] { - 0x05, 0x00 - }; - - public void testRead() { - - AutoFilterInfoRecord record = new AutoFilterInfoRecord(TestcaseRecordInputStream.create(AutoFilterInfoRecord.sid, data)); - - assertEquals(AutoFilterInfoRecord.sid, record.getSid()); - assertEquals(data.length, record.getDataSize()); - assertEquals(5, record.getNumEntries()); - record.setNumEntries((short)3); - assertEquals(3, record.getNumEntries()); - } - - public void testWrite() { - AutoFilterInfoRecord record = new AutoFilterInfoRecord(); - record.setNumEntries((short)3); - - byte [] ser = record.serialize(); - assertEquals(ser.length - 4, data.length); - record = new AutoFilterInfoRecord(TestcaseRecordInputStream.create(ser)); - assertEquals(3, record.getNumEntries()); - } - - public void testClone() - { - AutoFilterInfoRecord record = new AutoFilterInfoRecord(); - record.setNumEntries((short)3); - byte[] src = record.serialize(); - - AutoFilterInfoRecord cloned = record.clone(); - assertEquals(3, record.getNumEntries()); - byte[] cln = cloned.serialize(); - - assertEquals(record.getDataSize(), cloned.getDataSize()); - assertArrayEquals(src, cln); - } -} \ No newline at end of file diff --git a/src/testcases/org/apache/poi/hssf/record/TestBOFRecord.java b/src/testcases/org/apache/poi/hssf/record/TestBOFRecord.java deleted file mode 100644 index 612fbcb65..000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestBOFRecord.java +++ /dev/null @@ -1,33 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record; - -import java.io.IOException; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.junit.Test; -/** - * - */ -public final class TestBOFRecord { - @Test - public void testBOFRecord() throws IOException { - // This used to throw an error before - #42794 - HSSFTestDataSamples.openSampleWorkbook("bug_42794.xls").close(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestBoolErrRecord.java b/src/testcases/org/apache/poi/hssf/record/TestBoolErrRecord.java deleted file mode 100644 index 67b151c66..000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestBoolErrRecord.java +++ /dev/null @@ -1,84 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record; - -import static org.junit.Assert.assertArrayEquals; -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -import org.apache.poi.hssf.record.RecordInputStream.LeftoverDataException; -import org.apache.poi.util.HexRead; -/** - * Tests for {@link BoolErrRecord} - */ -public final class TestBoolErrRecord extends TestCase { - - public void testError() { - byte[] data = HexRead.readFromString( - "00 00 00 00 0F 00 " + // row, col, xfIndex - "07 01 " // #DIV/0!, isError - ); - - RecordInputStream in = TestcaseRecordInputStream.create(BoolErrRecord.sid, data); - BoolErrRecord ber = new BoolErrRecord(in); - assertTrue(ber.isError()); - assertEquals(7, ber.getErrorValue()); - - TestcaseRecordInputStream.confirmRecordEncoding(BoolErrRecord.sid, data, ber.serialize()); - } - - /** - * Bugzilla 47479 was due to an apparent error in OOO which (as of version 3.0.1) - * writes the value field of BOOLERR records as 2 bytes instead of 1.
    - * Coincidentally, the extra byte written is zero, which is exactly the value - * required by the isError field. This probably why Excel seems to have - * no problem. OOO does not have the same bug for error values (which wouldn't - * work by the same coincidence). - */ - public void testOooBadFormat_bug47479() { - byte[] data = HexRead.readFromString( - "05 02 09 00 " + // sid, size - "00 00 00 00 0F 00 " + // row, col, xfIndex - "01 00 00 " // extra 00 byte here - ); - - RecordInputStream in = TestcaseRecordInputStream.create(data); - BoolErrRecord ber = new BoolErrRecord(in); - boolean hasMore; - try { - hasMore = in.hasNextRecord(); - } catch (LeftoverDataException e) { - if ("Initialisation of record 0x205 left 1 bytes remaining still to be read.".equals(e.getMessage())) { - throw new AssertionFailedError("Identified bug 47479"); - } - throw e; - } - assertFalse(hasMore); - assertTrue(ber.isBoolean()); - assertEquals(true, ber.getBooleanValue()); - - // Check that the record re-serializes correctly - byte[] outData = ber.serialize(); - byte[] expData = HexRead.readFromString( - "05 02 08 00 " + - "00 00 00 00 0F 00 " + - "01 00 " // normal number of data bytes - ); - assertArrayEquals(expData, outData); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestBoundSheetRecord.java b/src/testcases/org/apache/poi/hssf/record/TestBoundSheetRecord.java deleted file mode 100644 index d50ae9e73..000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestBoundSheetRecord.java +++ /dev/null @@ -1,131 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record; - -import static org.junit.Assert.assertArrayEquals; - -import java.util.ArrayList; -import java.util.List; - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -import org.apache.poi.util.HexRead; - -/** - * Tests BoundSheetRecord. - * - * @see BoundSheetRecord - * - * @author Glen Stampoultzis (glens at apache.org) - */ -public final class TestBoundSheetRecord extends TestCase { - - - public void testRecordLength() { - BoundSheetRecord record = new BoundSheetRecord("Sheet1"); - assertEquals(18, record.getRecordSize()); - } - - public void testWideRecordLength() { - BoundSheetRecord record = new BoundSheetRecord("Sheet\u20ac"); - assertEquals(24, record.getRecordSize()); - } - - public void testName() { - BoundSheetRecord record = new BoundSheetRecord("1234567890223456789032345678904"); - - try { - record.setSheetname("s//*s"); - throw new AssertionFailedError("Should have thrown IllegalArgumentException, but didnt"); - } catch (IllegalArgumentException e) { - // expected - } - } - - public void testDeserializeUnicode() { - - byte[] data = HexRead.readFromString("" - + "85 00 1A 00" // sid, length - + "3C 09 00 00" // bof - + "00 00"// flags - + "09 01" // str-len. unicode flag - // string data - + "21 04 42 04 40 04" - + "30 04 3D 04 38 04" - + "47 04 3A 04 30 04" - ); - - RecordInputStream in = TestcaseRecordInputStream.create(data); - BoundSheetRecord bsr = new BoundSheetRecord(in); - // sheet name is unicode Russian for 'minor page' - assertEquals("\u0421\u0442\u0440\u0430\u043D\u0438\u0447\u043A\u0430", bsr.getSheetname()); - - byte[] data2 = bsr.serialize(); - assertArrayEquals(data, data2); - } - - public void testOrdering() { - BoundSheetRecord bs1 = new BoundSheetRecord("SheetB"); - BoundSheetRecord bs2 = new BoundSheetRecord("SheetC"); - BoundSheetRecord bs3 = new BoundSheetRecord("SheetA"); - bs1.setPositionOfBof(11); - bs2.setPositionOfBof(33); - bs3.setPositionOfBof(22); - - List l = new ArrayList(); - l.add(bs1); - l.add(bs2); - l.add(bs3); - - BoundSheetRecord[] r = BoundSheetRecord.orderByBofPosition(l); - assertEquals(3, r.length); - assertEquals(bs1, r[0]); - assertEquals(bs3, r[1]); - assertEquals(bs2, r[2]); - } - - public void testValidNames() { - confirmValid("Sheet1", true); - confirmValid("O'Brien's sales", true); - confirmValid(" data # ", true); - confirmValid("data $1.00", true); - - confirmValid("data?", false); - confirmValid("abc/def", false); - confirmValid("data[0]", false); - confirmValid("data*", false); - confirmValid("abc\\def", false); - confirmValid("'data", false); - confirmValid("data'", false); - } - - private static void confirmValid(String sheetName, boolean expectedResult) { - - try { - new BoundSheetRecord(sheetName); - if (!expectedResult) { - throw new AssertionFailedError("Expected sheet name '" + sheetName + "' to be invalid"); - } - } catch (IllegalArgumentException e) { - if (expectedResult) { - throw new AssertionFailedError("Expected sheet name '" + sheetName + "' to be valid"); - } - } - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestCFHeaderRecord.java b/src/testcases/org/apache/poi/hssf/record/TestCFHeaderRecord.java deleted file mode 100644 index 9c9b5486c..000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestCFHeaderRecord.java +++ /dev/null @@ -1,213 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record; - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -import org.apache.poi.ss.util.CellRangeAddress; - -/** - * Tests the serialization and deserialization of the {@link CFHeaderRecord} - * and {@link CFHeader12Record} classes works correctly. - */ -public final class TestCFHeaderRecord extends TestCase { - public void testCreateCFHeaderRecord () { - CFHeaderRecord record = new CFHeaderRecord(); - CellRangeAddress[] ranges = { - new CellRangeAddress(0,0xFFFF,5,5), - new CellRangeAddress(0,0xFFFF,6,6), - new CellRangeAddress(0,1,0,1), - new CellRangeAddress(0,1,2,3), - new CellRangeAddress(2,3,0,1), - new CellRangeAddress(2,3,2,3), - }; - record.setCellRanges(ranges); - ranges = record.getCellRanges(); - assertEquals(6,ranges.length); - CellRangeAddress enclosingCellRange = record.getEnclosingCellRange(); - assertEquals(0, enclosingCellRange.getFirstRow()); - assertEquals(65535, enclosingCellRange.getLastRow()); - assertEquals(0, enclosingCellRange.getFirstColumn()); - assertEquals(6, enclosingCellRange.getLastColumn()); - - assertEquals(false, record.getNeedRecalculation()); - assertEquals(0, record.getID()); - - record.setNeedRecalculation(true); - assertEquals(true, record.getNeedRecalculation()); - assertEquals(0, record.getID()); - - record.setID(7); - record.setNeedRecalculation(false); - assertEquals(false, record.getNeedRecalculation()); - assertEquals(7, record.getID()); - } - - public void testCreateCFHeader12Record () { - CFHeader12Record record = new CFHeader12Record(); - CellRangeAddress[] ranges = { - new CellRangeAddress(0,0xFFFF,5,5), - new CellRangeAddress(0,0xFFFF,6,6), - new CellRangeAddress(0,1,0,1), - new CellRangeAddress(0,1,2,3), - new CellRangeAddress(2,3,0,1), - new CellRangeAddress(2,3,2,3), - }; - record.setCellRanges(ranges); - ranges = record.getCellRanges(); - assertEquals(6,ranges.length); - CellRangeAddress enclosingCellRange = record.getEnclosingCellRange(); - assertEquals(0, enclosingCellRange.getFirstRow()); - assertEquals(65535, enclosingCellRange.getLastRow()); - assertEquals(0, enclosingCellRange.getFirstColumn()); - assertEquals(6, enclosingCellRange.getLastColumn()); - - assertEquals(false, record.getNeedRecalculation()); - assertEquals(0, record.getID()); - - record.setNeedRecalculation(true); - assertEquals(true, record.getNeedRecalculation()); - assertEquals(0, record.getID()); - - record.setID(7); - record.setNeedRecalculation(false); - assertEquals(false, record.getNeedRecalculation()); - assertEquals(7, record.getID()); - } - - public void testSerialization() { - byte[] recordData = - { - (byte)0x03, (byte)0x00, - (byte)0x01, (byte)0x00, - - (byte)0x00, (byte)0x00, - (byte)0x03, (byte)0x00, - (byte)0x00, (byte)0x00, - (byte)0x03, (byte)0x00, - - (byte)0x04, (byte)0x00, // nRegions - - (byte)0x00, (byte)0x00, - (byte)0x01, (byte)0x00, - (byte)0x00, (byte)0x00, - (byte)0x01, (byte)0x00, - - (byte)0x00, (byte)0x00, - (byte)0x01, (byte)0x00, - (byte)0x02, (byte)0x00, - (byte)0x03, (byte)0x00, - - (byte)0x02, (byte)0x00, - (byte)0x03, (byte)0x00, - (byte)0x00, (byte)0x00, - (byte)0x01, (byte)0x00, - - (byte)0x02, (byte)0x00, - (byte)0x03, (byte)0x00, - (byte)0x02, (byte)0x00, - (byte)0x03, (byte)0x00, - }; - - CFHeaderRecord record = new CFHeaderRecord(TestcaseRecordInputStream.create(CFHeaderRecord.sid, recordData)); - - assertEquals("#CFRULES", 3, record.getNumberOfConditionalFormats()); - assertTrue(record.getNeedRecalculation()); - confirm(record.getEnclosingCellRange(), 0, 3, 0, 3); - CellRangeAddress[] ranges = record.getCellRanges(); - assertEquals(4, ranges.length); - confirm(ranges[0], 0, 1, 0, 1); - confirm(ranges[1], 0, 1, 2, 3); - confirm(ranges[2], 2, 3, 0, 1); - confirm(ranges[3], 2, 3, 2, 3); - assertEquals(recordData.length+4, record.getRecordSize()); - - byte[] output = record.serialize(); - - assertEquals("Output size", recordData.length+4, output.length); //includes sid+recordlength - - for (int i = 0; i < recordData.length; i++) - { - assertEquals("CFHeaderRecord doesn't match", recordData[i], output[i+4]); - } - } - - public void testExtremeRows() { - byte[] recordData = { - (byte)0x13, (byte)0x00, // nFormats - (byte)0x00, (byte)0x00, - - (byte)0x00, (byte)0x00, - (byte)0xFF, (byte)0xFF, - (byte)0x00, (byte)0x00, - (byte)0xFF, (byte)0x00, - - (byte)0x03, (byte)0x00, // nRegions - - (byte)0x40, (byte)0x9C, - (byte)0x50, (byte)0xC3, - (byte)0x02, (byte)0x00, - (byte)0x02, (byte)0x00, - - (byte)0x00, (byte)0x00, - (byte)0xFF, (byte)0xFF, - (byte)0x05, (byte)0x00, - (byte)0x05, (byte)0x00, - - (byte)0x07, (byte)0x00, - (byte)0x07, (byte)0x00, - (byte)0x00, (byte)0x00, - (byte)0xFF, (byte)0x00, - }; - - CFHeaderRecord record; - try { - record = new CFHeaderRecord(TestcaseRecordInputStream.create(CFHeaderRecord.sid, recordData)); - } catch (IllegalArgumentException e) { - if(e.getMessage().equals("invalid cell range (-25536, 2, -15536, 2)")) { - throw new AssertionFailedError("Identified bug 44739b"); - } - throw e; - } - - assertEquals("#CFRULES", 19, record.getNumberOfConditionalFormats()); - assertFalse(record.getNeedRecalculation()); - confirm(record.getEnclosingCellRange(), 0, 65535, 0, 255); - CellRangeAddress[] ranges = record.getCellRanges(); - assertEquals(3, ranges.length); - confirm(ranges[0], 40000, 50000, 2, 2); - confirm(ranges[1], 0, 65535, 5, 5); - confirm(ranges[2], 7, 7, 0, 255); - - byte[] output = record.serialize(); - - assertEquals("Output size", recordData.length+4, output.length); //includes sid+recordlength - - for (int i = 0; i < recordData.length;i++) { - assertEquals("CFHeaderRecord doesn't match", recordData[i], output[i+4]); - } - } - - private static void confirm(CellRangeAddress cr, int expFirstRow, int expLastRow, int expFirstCol, int expLastColumn) { - assertEquals("first row", expFirstRow, cr.getFirstRow()); - assertEquals("last row", expLastRow, cr.getLastRow()); - assertEquals("first column", expFirstCol, cr.getFirstColumn()); - assertEquals("last column", expLastColumn, cr.getLastColumn()); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestCFRuleRecord.java b/src/testcases/org/apache/poi/hssf/record/TestCFRuleRecord.java deleted file mode 100644 index acaddd0f6..000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestCFRuleRecord.java +++ /dev/null @@ -1,473 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; - -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.hssf.record.CFRuleBase.ComparisonOperator; -import org.apache.poi.hssf.record.cf.BorderFormatting; -import org.apache.poi.hssf.record.cf.FontFormatting; -import org.apache.poi.hssf.record.cf.PatternFormatting; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.hssf.util.HSSFColor.HSSFColorPredefined; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.apache.poi.ss.formula.ptg.RefNPtg; -import org.apache.poi.ss.formula.ptg.RefPtg; -import org.apache.poi.ss.usermodel.ConditionalFormattingThreshold.RangeType; -import org.apache.poi.ss.usermodel.IconMultiStateFormatting.IconSet; -import org.apache.poi.util.LittleEndian; -import org.junit.Test; - -import junit.framework.AssertionFailedError; - -/** - * Tests the serialization and deserialization of the TestCFRuleRecord - * class works correctly. - */ -public final class TestCFRuleRecord { - @Test - public void testConstructors () throws IOException { - HSSFWorkbook workbook = new HSSFWorkbook(); - HSSFSheet sheet = workbook.createSheet(); - - CFRuleRecord rule1 = CFRuleRecord.create(sheet, "7"); - assertEquals(CFRuleBase.CONDITION_TYPE_FORMULA, rule1.getConditionType()); - assertEquals(ComparisonOperator.NO_COMPARISON, rule1.getComparisonOperation()); - assertNotNull(rule1.getParsedExpression1()); - assertSame(Ptg.EMPTY_PTG_ARRAY, rule1.getParsedExpression2()); - - CFRuleRecord rule2 = CFRuleRecord.create(sheet, ComparisonOperator.BETWEEN, "2", "5"); - assertEquals(CFRuleBase.CONDITION_TYPE_CELL_VALUE_IS, rule2.getConditionType()); - assertEquals(ComparisonOperator.BETWEEN, rule2.getComparisonOperation()); - assertNotNull(rule2.getParsedExpression1()); - assertNotNull(rule2.getParsedExpression2()); - - CFRuleRecord rule3 = CFRuleRecord.create(sheet, ComparisonOperator.EQUAL, null, null); - assertEquals(CFRuleBase.CONDITION_TYPE_CELL_VALUE_IS, rule3.getConditionType()); - assertEquals(ComparisonOperator.EQUAL, rule3.getComparisonOperation()); - assertSame(Ptg.EMPTY_PTG_ARRAY, rule3.getParsedExpression2()); - assertSame(Ptg.EMPTY_PTG_ARRAY, rule3.getParsedExpression2()); - workbook.close(); - } - - @Test - public void testCreateCFRuleRecord() throws IOException { - HSSFWorkbook workbook = new HSSFWorkbook(); - HSSFSheet sheet = workbook.createSheet(); - CFRuleRecord record = CFRuleRecord.create(sheet, "7"); - testCFRuleRecord(record); - - // Serialize - byte [] serializedRecord = record.serialize(); - - // Strip header - byte [] recordData = new byte[serializedRecord.length-4]; - System.arraycopy(serializedRecord, 4, recordData, 0, recordData.length); - - // Deserialize - record = new CFRuleRecord(TestcaseRecordInputStream.create(CFRuleRecord.sid, recordData)); - - // Serialize again - byte[] output = record.serialize(); - - // Compare - assertEquals("Output size", recordData.length+4, output.length); //includes sid+recordlength - - for (int i = 0; i < recordData.length;i++) { - assertEquals("CFRuleRecord doesn't match", recordData[i], output[i+4]); - } - workbook.close(); - } - - @Test - public void testCreateCFRule12Record() throws IOException { - HSSFWorkbook workbook = new HSSFWorkbook(); - HSSFSheet sheet = workbook.createSheet(); - CFRule12Record record = CFRule12Record.create(sheet, "7"); - testCFRule12Record(record); - - // Serialize - byte [] serializedRecord = record.serialize(); - - // Strip header - byte [] recordData = new byte[serializedRecord.length-4]; - System.arraycopy(serializedRecord, 4, recordData, 0, recordData.length); - - // Deserialize - record = new CFRule12Record(TestcaseRecordInputStream.create(CFRule12Record.sid, recordData)); - - // Serialize again - byte[] output = record.serialize(); - - // Compare - assertEquals("Output size", recordData.length+4, output.length); //includes sid+recordlength - - for (int i = 0; i < recordData.length;i++) { - assertEquals("CFRule12Record doesn't match", recordData[i], output[i+4]); - } - workbook.close(); - } - - @Test - public void testCreateIconCFRule12Record() throws IOException { - HSSFWorkbook workbook = new HSSFWorkbook(); - HSSFSheet sheet = workbook.createSheet(); - CFRule12Record record = CFRule12Record.create(sheet, IconSet.GREY_5_ARROWS); - record.getMultiStateFormatting().getThresholds()[1].setType(RangeType.PERCENT.id); - record.getMultiStateFormatting().getThresholds()[1].setValue(10d); - record.getMultiStateFormatting().getThresholds()[2].setType(RangeType.NUMBER.id); - record.getMultiStateFormatting().getThresholds()[2].setValue(-4d); - - // Check it - testCFRule12Record(record); - assertEquals(IconSet.GREY_5_ARROWS, record.getMultiStateFormatting().getIconSet()); - assertEquals(5, record.getMultiStateFormatting().getThresholds().length); - - // Serialize - byte [] serializedRecord = record.serialize(); - - // Strip header - byte [] recordData = new byte[serializedRecord.length-4]; - System.arraycopy(serializedRecord, 4, recordData, 0, recordData.length); - - // Deserialize - record = new CFRule12Record(TestcaseRecordInputStream.create(CFRule12Record.sid, recordData)); - - // Check it has the icon, and the right number of thresholds - assertEquals(IconSet.GREY_5_ARROWS, record.getMultiStateFormatting().getIconSet()); - assertEquals(5, record.getMultiStateFormatting().getThresholds().length); - - // Serialize again - byte[] output = record.serialize(); - - // Compare - assertEquals("Output size", recordData.length+4, output.length); //includes sid+recordlength - - for (int i = 0; i < recordData.length;i++) { - assertEquals("CFRule12Record doesn't match", recordData[i], output[i+4]); - } - workbook.close(); - } - - private void testCFRuleRecord(CFRuleRecord record) { - testCFRuleBase(record); - - assertFalse(record.isLeftBorderModified()); - record.setLeftBorderModified(true); - assertTrue(record.isLeftBorderModified()); - - assertFalse(record.isRightBorderModified()); - record.setRightBorderModified(true); - assertTrue(record.isRightBorderModified()); - - assertFalse(record.isTopBorderModified()); - record.setTopBorderModified(true); - assertTrue(record.isTopBorderModified()); - - assertFalse(record.isBottomBorderModified()); - record.setBottomBorderModified(true); - assertTrue(record.isBottomBorderModified()); - - assertFalse(record.isTopLeftBottomRightBorderModified()); - record.setTopLeftBottomRightBorderModified(true); - assertTrue(record.isTopLeftBottomRightBorderModified()); - - assertFalse(record.isBottomLeftTopRightBorderModified()); - record.setBottomLeftTopRightBorderModified(true); - assertTrue(record.isBottomLeftTopRightBorderModified()); - - - assertFalse(record.isPatternBackgroundColorModified()); - record.setPatternBackgroundColorModified(true); - assertTrue(record.isPatternBackgroundColorModified()); - - assertFalse(record.isPatternColorModified()); - record.setPatternColorModified(true); - assertTrue(record.isPatternColorModified()); - - assertFalse(record.isPatternStyleModified()); - record.setPatternStyleModified(true); - assertTrue(record.isPatternStyleModified()); - } - private void testCFRule12Record(CFRule12Record record) { - assertEquals(CFRule12Record.sid, record.getFutureRecordType()); - assertEquals("A1", record.getAssociatedRange().formatAsString()); - testCFRuleBase(record); - } - private void testCFRuleBase(CFRuleBase record) { - FontFormatting fontFormatting = new FontFormatting(); - testFontFormattingAccessors(fontFormatting); - assertFalse(record.containsFontFormattingBlock()); - record.setFontFormatting(fontFormatting); - assertTrue(record.containsFontFormattingBlock()); - - BorderFormatting borderFormatting = new BorderFormatting(); - testBorderFormattingAccessors(borderFormatting); - assertFalse(record.containsBorderFormattingBlock()); - record.setBorderFormatting(borderFormatting); - assertTrue(record.containsBorderFormattingBlock()); - - PatternFormatting patternFormatting = new PatternFormatting(); - testPatternFormattingAccessors(patternFormatting); - assertFalse(record.containsPatternFormattingBlock()); - record.setPatternFormatting(patternFormatting); - assertTrue(record.containsPatternFormattingBlock()); - } - - private void testPatternFormattingAccessors(PatternFormatting patternFormatting) { - patternFormatting.setFillBackgroundColor(HSSFColorPredefined.GREEN.getIndex()); - assertEquals(HSSFColorPredefined.GREEN.getIndex(),patternFormatting.getFillBackgroundColor()); - - patternFormatting.setFillForegroundColor(HSSFColorPredefined.INDIGO.getIndex()); - assertEquals(HSSFColorPredefined.INDIGO.getIndex(),patternFormatting.getFillForegroundColor()); - - patternFormatting.setFillPattern(PatternFormatting.DIAMONDS); - assertEquals(PatternFormatting.DIAMONDS,patternFormatting.getFillPattern()); - } - - private void testBorderFormattingAccessors(BorderFormatting borderFormatting) { - borderFormatting.setBackwardDiagonalOn(false); - assertFalse(borderFormatting.isBackwardDiagonalOn()); - borderFormatting.setBackwardDiagonalOn(true); - assertTrue(borderFormatting.isBackwardDiagonalOn()); - - borderFormatting.setBorderBottom(BorderFormatting.BORDER_DOTTED); - assertEquals(BorderFormatting.BORDER_DOTTED, borderFormatting.getBorderBottom()); - - borderFormatting.setBorderDiagonal(BorderFormatting.BORDER_MEDIUM); - assertEquals(BorderFormatting.BORDER_MEDIUM, borderFormatting.getBorderDiagonal()); - - borderFormatting.setBorderLeft(BorderFormatting.BORDER_MEDIUM_DASH_DOT_DOT); - assertEquals(BorderFormatting.BORDER_MEDIUM_DASH_DOT_DOT, borderFormatting.getBorderLeft()); - - borderFormatting.setBorderRight(BorderFormatting.BORDER_MEDIUM_DASHED); - assertEquals(BorderFormatting.BORDER_MEDIUM_DASHED, borderFormatting.getBorderRight()); - - borderFormatting.setBorderTop(BorderFormatting.BORDER_HAIR); - assertEquals(BorderFormatting.BORDER_HAIR, borderFormatting.getBorderTop()); - - borderFormatting.setBottomBorderColor(HSSFColorPredefined.AQUA.getIndex()); - assertEquals(HSSFColorPredefined.AQUA.getIndex(), borderFormatting.getBottomBorderColor()); - - borderFormatting.setDiagonalBorderColor(HSSFColorPredefined.RED.getIndex()); - assertEquals(HSSFColorPredefined.RED.getIndex(), borderFormatting.getDiagonalBorderColor()); - - assertFalse(borderFormatting.isForwardDiagonalOn()); - borderFormatting.setForwardDiagonalOn(true); - assertTrue(borderFormatting.isForwardDiagonalOn()); - - borderFormatting.setLeftBorderColor(HSSFColorPredefined.BLACK.getIndex()); - assertEquals(HSSFColorPredefined.BLACK.getIndex(), borderFormatting.getLeftBorderColor()); - - borderFormatting.setRightBorderColor(HSSFColorPredefined.BLUE.getIndex()); - assertEquals(HSSFColorPredefined.BLUE.getIndex(), borderFormatting.getRightBorderColor()); - - borderFormatting.setTopBorderColor(HSSFColorPredefined.GOLD.getIndex()); - assertEquals(HSSFColorPredefined.GOLD.getIndex(), borderFormatting.getTopBorderColor()); - } - - - private void testFontFormattingAccessors(FontFormatting fontFormatting) { - // Check for defaults - assertFalse(fontFormatting.isEscapementTypeModified()); - assertFalse(fontFormatting.isFontCancellationModified()); - assertFalse(fontFormatting.isFontOutlineModified()); - assertFalse(fontFormatting.isFontShadowModified()); - assertFalse(fontFormatting.isFontStyleModified()); - assertFalse(fontFormatting.isUnderlineTypeModified()); - assertFalse(fontFormatting.isFontWeightModified()); - - assertFalse(fontFormatting.isBold()); - assertFalse(fontFormatting.isItalic()); - assertFalse(fontFormatting.isOutlineOn()); - assertFalse(fontFormatting.isShadowOn()); - assertFalse(fontFormatting.isStruckout()); - - assertEquals(0, fontFormatting.getEscapementType()); - assertEquals(-1, fontFormatting.getFontColorIndex()); - assertEquals(-1, fontFormatting.getFontHeight()); - assertEquals(0, fontFormatting.getFontWeight()); - assertEquals(0, fontFormatting.getUnderlineType()); - - fontFormatting.setBold(true); - assertTrue(fontFormatting.isBold()); - fontFormatting.setBold(false); - assertFalse(fontFormatting.isBold()); - - fontFormatting.setEscapementType(FontFormatting.SS_SUB); - assertEquals(FontFormatting.SS_SUB, fontFormatting.getEscapementType()); - fontFormatting.setEscapementType(FontFormatting.SS_SUPER); - assertEquals(FontFormatting.SS_SUPER, fontFormatting.getEscapementType()); - fontFormatting.setEscapementType(FontFormatting.SS_NONE); - assertEquals(FontFormatting.SS_NONE, fontFormatting.getEscapementType()); - - fontFormatting.setEscapementTypeModified(false); - assertFalse(fontFormatting.isEscapementTypeModified()); - fontFormatting.setEscapementTypeModified(true); - assertTrue(fontFormatting.isEscapementTypeModified()); - - fontFormatting.setFontWieghtModified(false); - assertFalse(fontFormatting.isFontWeightModified()); - fontFormatting.setFontWieghtModified(true); - assertTrue(fontFormatting.isFontWeightModified()); - - fontFormatting.setFontCancellationModified(false); - assertFalse(fontFormatting.isFontCancellationModified()); - fontFormatting.setFontCancellationModified(true); - assertTrue(fontFormatting.isFontCancellationModified()); - - fontFormatting.setFontColorIndex((short)10); - assertEquals(10,fontFormatting.getFontColorIndex()); - - fontFormatting.setFontHeight(100); - assertEquals(100,fontFormatting.getFontHeight()); - - fontFormatting.setFontOutlineModified(false); - assertFalse(fontFormatting.isFontOutlineModified()); - fontFormatting.setFontOutlineModified(true); - assertTrue(fontFormatting.isFontOutlineModified()); - - fontFormatting.setFontShadowModified(false); - assertFalse(fontFormatting.isFontShadowModified()); - fontFormatting.setFontShadowModified(true); - assertTrue(fontFormatting.isFontShadowModified()); - - fontFormatting.setFontStyleModified(false); - assertFalse(fontFormatting.isFontStyleModified()); - fontFormatting.setFontStyleModified(true); - assertTrue(fontFormatting.isFontStyleModified()); - - fontFormatting.setItalic(false); - assertFalse(fontFormatting.isItalic()); - fontFormatting.setItalic(true); - assertTrue(fontFormatting.isItalic()); - - fontFormatting.setOutline(false); - assertFalse(fontFormatting.isOutlineOn()); - fontFormatting.setOutline(true); - assertTrue(fontFormatting.isOutlineOn()); - - fontFormatting.setShadow(false); - assertFalse(fontFormatting.isShadowOn()); - fontFormatting.setShadow(true); - assertTrue(fontFormatting.isShadowOn()); - - fontFormatting.setStrikeout(false); - assertFalse(fontFormatting.isStruckout()); - fontFormatting.setStrikeout(true); - assertTrue(fontFormatting.isStruckout()); - - fontFormatting.setUnderlineType(FontFormatting.U_DOUBLE_ACCOUNTING); - assertEquals(FontFormatting.U_DOUBLE_ACCOUNTING, fontFormatting.getUnderlineType()); - - fontFormatting.setUnderlineTypeModified(false); - assertFalse(fontFormatting.isUnderlineTypeModified()); - fontFormatting.setUnderlineTypeModified(true); - assertTrue(fontFormatting.isUnderlineTypeModified()); - } - - @Test - public void testWrite() throws IOException { - HSSFWorkbook workbook = new HSSFWorkbook(); - HSSFSheet sheet = workbook.createSheet(); - CFRuleRecord rr = CFRuleRecord.create(sheet, ComparisonOperator.BETWEEN, "5", "10"); - - PatternFormatting patternFormatting = new PatternFormatting(); - patternFormatting.setFillPattern(PatternFormatting.BRICKS); - rr.setPatternFormatting(patternFormatting); - - byte[] data = rr.serialize(); - assertEquals(26, data.length); - assertEquals(3, LittleEndian.getShort(data, 6)); - assertEquals(3, LittleEndian.getShort(data, 8)); - - int flags = LittleEndian.getInt(data, 10); - assertEquals("unused flags should be 111", 0x00380000, flags & 0x00380000); - assertEquals("undocumented flags should be 0000", 0, flags & 0x03C00000); // Otherwise Excel gets unhappy - // check all remaining flag bits (some are not well understood yet) - assertEquals(0x203FFFFF, flags); - workbook.close(); - } - - private static final byte[] DATA_REFN = { - // formula extracted from bugzilla 45234 att 22141 - 1, 3, - 9, // formula 1 length - 0, 0, 0, -1, -1, 63, 32, 2, -128, 0, 0, 0, 5, - // formula 1: "=B3=1" (formula is relative to B4) - 76, -1, -1, 0, -64, // tRefN(B1) - 30, 1, 0, - 11, - }; - - /** - * tRefN and tAreaN tokens must be preserved when re-serializing conditional format formulas - */ - @Test - public void testReserializeRefNTokens() { - - RecordInputStream is = TestcaseRecordInputStream.create(CFRuleRecord.sid, DATA_REFN); - CFRuleRecord rr = new CFRuleRecord(is); - Ptg[] ptgs = rr.getParsedExpression1(); - assertEquals(3, ptgs.length); - if (ptgs[0] instanceof RefPtg) { - throw new AssertionFailedError("Identified bug 45234"); - } - assertEquals(RefNPtg.class, ptgs[0].getClass()); - RefNPtg refNPtg = (RefNPtg) ptgs[0]; - assertTrue(refNPtg.isColRelative()); - assertTrue(refNPtg.isRowRelative()); - - byte[] data = rr.serialize(); - TestcaseRecordInputStream.confirmRecordEncoding(CFRuleRecord.sid, DATA_REFN, data); - } - - @Test - public void testBug53691() throws IOException { - HSSFWorkbook workbook = new HSSFWorkbook(); - HSSFSheet sheet = workbook.createSheet(); - - CFRuleRecord record = CFRuleRecord.create(sheet, ComparisonOperator.BETWEEN, "2", "5"); - - CFRuleRecord clone = record.clone(); - - byte [] serializedRecord = record.serialize(); - byte [] serializedClone = clone.serialize(); - assertArrayEquals(serializedRecord, serializedClone); - workbook.close(); - } - - @Test - public void testBug57231_rewrite() throws IOException { - HSSFWorkbook wb1 = HSSFITestDataProvider.instance.openSampleWorkbook("57231_MixedGasReport.xls"); - assertEquals(7, wb1.getNumberOfSheets()); - HSSFWorkbook wb2 = HSSFITestDataProvider.instance.writeOutAndReadBack(wb1); - assertEquals(7, wb2.getNumberOfSheets()); - wb2.close(); - wb1.close(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestColumnInfoRecord.java b/src/testcases/org/apache/poi/hssf/record/TestColumnInfoRecord.java deleted file mode 100644 index 8e5b48276..000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestColumnInfoRecord.java +++ /dev/null @@ -1,87 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record; - -import static org.junit.Assert.assertArrayEquals; -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -import org.apache.poi.util.HexRead; - -/** - * Tests for {@link ColumnInfoRecord} - * - * @author Josh Micich - */ -public final class TestColumnInfoRecord extends TestCase { - - public void testBasic() { - byte[] data = HexRead.readFromString("7D 00 0C 00 14 00 9B 00 C7 19 0F 00 01 13 00 00"); - - RecordInputStream in = TestcaseRecordInputStream.create(data); - ColumnInfoRecord cir = new ColumnInfoRecord(in); - assertEquals(0, in.remaining()); - - assertEquals(20, cir.getFirstColumn()); - assertEquals(155, cir.getLastColumn()); - assertEquals(6599, cir.getColumnWidth()); - assertEquals(15, cir.getXFIndex()); - assertEquals(true, cir.getHidden()); - assertEquals(3, cir.getOutlineLevel()); - assertEquals(true, cir.getCollapsed()); - assertArrayEquals(data, cir.serialize()); - } - - /** - * Some applications skip the last reserved field when writing {@link ColumnInfoRecord}s - * The attached file was apparently created by "SoftArtisans OfficeWriter for Excel". - * Excel reads that file OK and assumes zero for the value of the reserved field. - */ - public void testZeroResevedBytes_bug48332() { - // Taken from bugzilla attachment 24661 (offset 0x1E73) - byte[] inpData = HexRead.readFromString("7D 00 0A 00 00 00 00 00 D5 19 0F 00 02 00"); - byte[] outData = HexRead.readFromString("7D 00 0C 00 00 00 00 00 D5 19 0F 00 02 00 00 00"); - - RecordInputStream in = TestcaseRecordInputStream.create(inpData); - ColumnInfoRecord cir; - try { - cir = new ColumnInfoRecord(in); - } catch (RuntimeException e) { - if (e.getMessage().equals("Unusual record size remaining=(0)")) { - throw new AssertionFailedError("Identified bug 48332"); - } - throw e; - } - assertEquals(0, in.remaining()); - assertArrayEquals(outData, cir.serialize()); - } - - /** - * Some sample files have just one reserved byte (field 6): - * OddStyleRecord.xls, NoGutsRecords.xls, WORKBOOK_in_capitals.xls - * but this seems to cause no problem to Excel - */ - public void testOneReservedByte() { - byte[] inpData = HexRead.readFromString("7D 00 0B 00 00 00 00 00 24 02 0F 00 00 00 01"); - byte[] outData = HexRead.readFromString("7D 00 0C 00 00 00 00 00 24 02 0F 00 00 00 01 00"); - RecordInputStream in = TestcaseRecordInputStream.create(inpData); - ColumnInfoRecord cir = new ColumnInfoRecord(in); - assertEquals(0, in.remaining()); - assertArrayEquals(outData, cir.serialize()); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestCommonObjectDataSubRecord.java b/src/testcases/org/apache/poi/hssf/record/TestCommonObjectDataSubRecord.java deleted file mode 100644 index 7ff862385..000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestCommonObjectDataSubRecord.java +++ /dev/null @@ -1,74 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record; - - -import junit.framework.TestCase; - -/** - * Tests the serialization and deserialization of the {@link CommonObjectDataSubRecord} - * class works correctly. Test data taken directly from a real - * Excel file. - * - * @author Glen Stampoultzis (glens at apache.org) - */ -public final class TestCommonObjectDataSubRecord extends TestCase { - byte[] data = new byte[] { - (byte)0x12,(byte)0x00,(byte)0x01,(byte)0x00, - (byte)0x01,(byte)0x00,(byte)0x11,(byte)0x60, - (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00, - (byte)0x00,(byte)0x0D,(byte)0x26,(byte)0x01, - (byte)0x00,(byte)0x00, - }; - - public void testLoad() { - CommonObjectDataSubRecord record = new CommonObjectDataSubRecord(TestcaseRecordInputStream.createLittleEndian(data), data.length); - - assertEquals( CommonObjectDataSubRecord.OBJECT_TYPE_LIST_BOX, record.getObjectType()); - assertEquals((short) 1, record.getObjectId()); - assertEquals((short) 1, record.getOption()); - assertEquals(true, record.isLocked()); - assertEquals(false, record.isPrintable()); - assertEquals(false, record.isAutofill()); - assertEquals(false, record.isAutoline()); - assertEquals(24593, record.getReserved1()); - assertEquals(218103808, record.getReserved2()); - assertEquals(294, record.getReserved3()); - assertEquals(18, record.getDataSize()); - } - - public void testStore() { - CommonObjectDataSubRecord record = new CommonObjectDataSubRecord(); - - record.setObjectType(CommonObjectDataSubRecord.OBJECT_TYPE_LIST_BOX); - record.setObjectId( 1); - record.setOption((short) 1); - record.setLocked(true); - record.setPrintable(false); - record.setAutofill(false); - record.setAutoline(false); - record.setReserved1(24593); - record.setReserved2(218103808); - record.setReserved3(294); - - byte [] recordBytes = record.serialize(); - assertEquals(recordBytes.length - 4, data.length); - for (int i = 0; i < data.length; i++) - assertEquals("At offset " + i, data[i], recordBytes[i+4]); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestDConRefRecord.java b/src/testcases/org/apache/poi/hssf/record/TestDConRefRecord.java deleted file mode 100644 index b101a4ee2..000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestDConRefRecord.java +++ /dev/null @@ -1,305 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.hssf.record; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.Arrays; -import junit.framework.TestCase; -import org.apache.poi.util.LittleEndianOutputStream; - -/** - * Unit tests for DConRefRecord class. - * - * @author Niklas Rehfeld - */ -public class TestDConRefRecord extends TestCase -{ - /** - * record of a proper single-byte external 'volume'-style path with multiple parts and a sheet - * name. - */ - final byte[] volumeString = new byte[] - { - 0, 0, 0, 0, 0, 0, //ref (6 bytes) not used... - 17, 0,//cchFile (2 bytes) - 0, //char type - 1, 1, 'c', '[', 'f', 'o', 'o', 0x3, - 'b', 'a', 'r', ']', 's', 'h', 'e', 'e', - 't' - }; - /** - * record of a proper single-byte external 'unc-volume'-style path with multiple parts and a - * sheet name. - */ - final byte[] uncVolumeString = new byte[] - { - 0, 0, 0, 0, 0, 0, //ref (6 bytes) not used... - 34, 0,//cchFile (2 bytes) - 0, //char type - 1, 1, '@', '[', 'c', 'o', 'm', 'p', - 0x3, 's', 'h', 'a', 'r', 'e', 'd', 0x3, - 'r', 'e', 'l', 'a', 't', 'i', 'v', 'e', - 0x3, 'f', 'o', 'o', ']', 's', 'h', 'e', - 'e', 't' - }; - /** - * record of a proper single-byte external 'simple-file-path-dcon' style path with a sheet name. - */ - final byte[] simpleFilePathDconString = new byte[] - { - 0, 0, 0, 0, 0, 0, //ref (6 bytes) not used... - 16, 0,//cchFile (2 bytes) - 0, //char type - 1, 'c', '[', 'f', 'o', 'o', 0x3, 'b', - 'a', 'r', ']', 's', 'h', 'e', 'e', 't' - }; - /** - * record of a proper 'transfer-protocol'-style path. This one has a sheet name at the end, and - * another one inside the file path. The spec doesn't seem to care about what they are. - */ - final byte[] transferProtocolString = new byte[] - { - 0, 0, 0, 0, 0, 0, //ref (6 bytes) not used... - 33, 0,//cchFile (2 bytes) - 0, //char type - 0x1, 0x5, 30, //count = 30 - '[', 'h', 't', 't', 'p', ':', '/', '/', - '[', 'f', 'o', 'o', 0x3, 'b', 'a', 'r', - ']', 's', 'h', 'e', 'e', 't', '1', ']', - 's', 'h', 'e', 'e', 't', 'x' - }; - /** - * startup-type path. - */ - final byte[] relVolumeString = new byte[] - { - 0, 0, 0, 0, 0, 0, //ref (6 bytes) not used... - 16, 0,//cchFile (2 bytes) - 0, //char type - 0x1, 0x2, '[', 'f', 'o', 'o', 0x3, 'b', - 'a', 'r', ']', 's', 'h', 'e', 'e', 't' - }; - /** - * startup-type path. - */ - final byte[] startupString = new byte[] - { - 0, 0, 0, 0, 0, 0, //ref (6 bytes) not used... - 16, 0,//cchFile (2 bytes) - 0, //char type - 0x1, 0x6, '[', 'f', 'o', 'o', 0x3, 'b', - 'a', 'r', ']', 's', 'h', 'e', 'e', 't' - }; - /** - * alt-startup-type path. - */ - final byte[] altStartupString = new byte[] - { - 0, 0, 0, 0, 0, 0, //ref (6 bytes) not used... - 16, 0,//cchFile (2 bytes) - 0, //char type - 0x1, 0x7, '[', 'f', 'o', 'o', 0x3, 'b', - 'a', 'r', ']', 's', 'h', 'e', 'e', 't' - }; - /** - * library-style path. - */ - final byte[] libraryString = new byte[] - { - 0, 0, 0, 0, 0, 0, //ref (6 bytes) not used... - 16, 0,//cchFile (2 bytes) - 0, //char type - 0x1, 0x8, '[', 'f', 'o', 'o', 0x3, 'b', - 'a', 'r', ']', 's', 'h', 'e', 'e', 't' - }; - /** - * record of single-byte string, external, volume path. - */ - final byte[] data1 = new byte[] - { - 0, 0, 0, 0, 0, 0, //ref (6 bytes) not used... - 10, 0,//cchFile (2 bytes) - 0, //char type - 1, 1, (byte) 'b', (byte) 'l', (byte) 'a', (byte) ' ', (byte) 't', - (byte) 'e', (byte) 's', (byte) 't' - //unused doesn't exist as stFile[1] != 2 - }; - /** - * record of double-byte string, self-reference. - */ - final byte[] data2 = new byte[] - { - 0, 0, 0, 0, 0, 0, //ref (6 bytes) not used... - 9, 0,//cchFile (2 bytes) - 1, //char type = unicode - 2, 0, (byte) 'b', 0, (byte) 'l', 0, (byte) 'a', 0, (byte) ' ', 0, (byte) 't', 0, - (byte) 'e', 0, (byte) 's', (byte) 't', 0,//stFile - 0, 0 //unused (2 bytes as we're using double-byte chars) - }; - /** - * record of single-byte string, self-reference. - */ - final byte[] data3 = new byte[] - { - 0, 0, 0, 0, 0, 0, //ref (6 bytes) not used... - 9, 0,//cchFile (2 bytes) - 0, //char type = ansi - 2, (byte) 'b', (byte) 'l', (byte) 'a', (byte) ' ', (byte) 't', (byte) 'e', (byte) 's', - (byte) 't',//stFile - 0 //unused (1 byte as we're using single byes) - }; - /** - * double-byte string, external reference, unc-volume. - */ - final byte[] data4 = new byte[] - { - 0, 0, 0, 0, 0, 0, //ref (6 bytes) not used... - 16, 0,//cchFile (2 bytes) - //stFile starts here: - 1, //char type = unicode - 1, 0, 1, 0, 0x40, 0, (byte) 'c', 0, (byte) 'o', 0, (byte) 'm', 0, (byte) 'p', 0, 0x03, 0, - (byte) 'b', 0, (byte) 'l', 0, (byte) 'a', 0, 0x03, 0, (byte) 't', 0, (byte) 'e', 0, - (byte) 's', 0, (byte) 't', 0, - //unused doesn't exist as stFile[1] != 2 - }; - - /** - * test read-constructor-then-serialize for a single-byte external reference strings of - * various flavours. This uses the RecordInputStream constructor. - * @throws IOException - */ - public void testReadWriteSBExtRef() throws IOException - { - testReadWrite(data1, "read-write single-byte external reference, volume type path"); - testReadWrite(volumeString, - "read-write properly formed single-byte external reference, volume type path"); - testReadWrite(uncVolumeString, - "read-write properly formed single-byte external reference, UNC volume type path"); - testReadWrite(relVolumeString, - "read-write properly formed single-byte external reference, rel-volume type path"); - testReadWrite(simpleFilePathDconString, - "read-write properly formed single-byte external reference, simple-file-path-dcon type path"); - testReadWrite(transferProtocolString, - "read-write properly formed single-byte external reference, transfer-protocol type path"); - testReadWrite(startupString, - "read-write properly formed single-byte external reference, startup type path"); - testReadWrite(altStartupString, - "read-write properly formed single-byte external reference, alt-startup type path"); - testReadWrite(libraryString, - "read-write properly formed single-byte external reference, library type path"); - } - - /** - * test read-constructor-then-serialize for a double-byte external reference 'UNC-Volume' style - * string - *

    - * @throws IOException - */ - public void testReadWriteDBExtRefUncVol() throws IOException - { - testReadWrite(data4, "read-write double-byte external reference, UNC volume type path"); - } - - private void testReadWrite(byte[] data, String message) throws IOException - { - RecordInputStream is = TestcaseRecordInputStream.create(81, data); - DConRefRecord d = new DConRefRecord(is); - ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length); - LittleEndianOutputStream o = new LittleEndianOutputStream(bos); - d.serialize(o); - o.flush(); - - assertTrue(message, Arrays.equals(data, - bos.toByteArray())); - } - - /** - * test read-constructor-then-serialize for a double-byte self-reference style string - *

    - * @throws IOException - */ - public void testReadWriteDBSelfRef() throws IOException - { - testReadWrite(data2, "read-write double-byte self reference"); - } - - /** - * test read-constructor-then-serialize for a single-byte self-reference style string - *

    - * @throws IOException - */ - public void testReadWriteSBSelfRef() throws IOException - { - testReadWrite(data3, "read-write single byte self reference"); - } - - /** - * Test of getDataSize method, of class DConRefRecord. - */ - public void testGetDataSize() - { - DConRefRecord instance = new DConRefRecord(TestcaseRecordInputStream.create(81, data1)); - int expResult = data1.length; - int result = instance.getDataSize(); - assertEquals("single byte external reference, volume type path data size", expResult, result); - instance = new DConRefRecord(TestcaseRecordInputStream.create(81, data2)); - assertEquals("double byte self reference data size", data2.length, instance.getDataSize()); - instance = new DConRefRecord(TestcaseRecordInputStream.create(81, data3)); - assertEquals("single byte self reference data size", data3.length, instance.getDataSize()); - instance = new DConRefRecord(TestcaseRecordInputStream.create(81, data4)); - assertEquals("double byte external reference, UNC volume type path data size", data4.length, - instance.getDataSize()); - } - - /** - * Test of getSid method, of class DConRefRecord. - */ - public void testGetSid() - { - DConRefRecord instance = new DConRefRecord(TestcaseRecordInputStream.create(81, data1)); - short expResult = 81; - short result = instance.getSid(); - assertEquals("SID", expResult, result); - } - - /** - * Test of getPath method, of class DConRefRecord. - * @todo different types of paths. - */ - public void testGetPath() - { - DConRefRecord instance = new DConRefRecord(TestcaseRecordInputStream.create(81, data1)); - byte[] expResult = Arrays.copyOfRange(data1, 9, data1.length); - byte[] result = instance.getPath(); - assertTrue("get path", Arrays.equals(expResult, result)); - } - - /** - * Test of isExternalRef method, of class DConRefRecord. - */ - public void testIsExternalRef() - { - DConRefRecord instance = new DConRefRecord(TestcaseRecordInputStream.create(81, data1)); - assertTrue("external reference", instance.isExternalRef()); - instance = new DConRefRecord(TestcaseRecordInputStream.create(81, data2)); - assertFalse("internal reference", instance.isExternalRef()); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestDVALRecord.java b/src/testcases/org/apache/poi/hssf/record/TestDVALRecord.java deleted file mode 100644 index bcfb76645..000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestDVALRecord.java +++ /dev/null @@ -1,55 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record; - -import java.io.ByteArrayInputStream; - -import org.apache.poi.util.LittleEndian; - -import junit.framework.TestCase; - -/** - * - * @author Josh Micich - */ -public final class TestDVALRecord extends TestCase { - public void testRead() { - - byte[] data = new byte[22]; - LittleEndian.putShort(data, 0, DVALRecord.sid); - LittleEndian.putShort(data, 2, (short)18); - LittleEndian.putShort(data, 4, (short)55); - LittleEndian.putInt(data, 6, 56); - LittleEndian.putInt(data, 10, 57); - LittleEndian.putInt(data, 14, 58); - LittleEndian.putInt(data, 18, 59); - - RecordInputStream in = new RecordInputStream(new ByteArrayInputStream(data)); - in.nextRecord(); - DVALRecord dv = new DVALRecord(in); - - assertEquals(55, dv.getOptions()); - assertEquals(56, dv.getHorizontalPos()); - assertEquals(57, dv.getVerticalPos()); - assertEquals(58, dv.getObjectID()); - if(dv.getDVRecNo() == 0) { - fail("Identified bug 44510"); - } - assertEquals(59, dv.getDVRecNo()); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestDrawingGroupRecord.java b/src/testcases/org/apache/poi/hssf/record/TestDrawingGroupRecord.java deleted file mode 100644 index 17d6475e8..000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestDrawingGroupRecord.java +++ /dev/null @@ -1,137 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record; - -import junit.framework.TestCase; -import org.apache.poi.ddf.EscherContainerRecord; -import org.apache.poi.ddf.EscherSpRecord; -import org.apache.poi.util.HexDump; - -public final class TestDrawingGroupRecord extends TestCase { - private static final int MAX_RECORD_SIZE = 8228; - private static final int MAX_DATA_SIZE = MAX_RECORD_SIZE - 4; - - public void testGetRecordSize() { - DrawingGroupRecord r = new DrawingGroupRecord(); - assertEquals(4, r.getRecordSize()); - - EscherSpRecord sp = new EscherSpRecord(); - sp.setRecordId(EscherSpRecord.RECORD_ID); - sp.setOptions((short) 0x1111); - sp.setFlags(-1); - sp.setShapeId(-1); - EscherContainerRecord dggContainer = new EscherContainerRecord(); - dggContainer.setOptions((short) 0x000F); - dggContainer.setRecordId((short) 0xF000); - dggContainer.addChildRecord(sp); - - r.addEscherRecord(dggContainer); - assertEquals(28, r.getRecordSize()); - - byte[] data = new byte[28]; - int size = r.serialize(0, data); - assertEquals("[EB, 00, 18, 00, 0F, 00, 00, F0, 10, 00, 00, 00, 11, 11, 0A, F0, 08, 00, 00, 00, FF, FF, FF, FF, FF, FF, FF, FF]", HexDump.toHex(data)); - assertEquals(28, size); - - assertEquals(24, dggContainer.getRecordSize()); - - - r = new DrawingGroupRecord( ); - r.setRawData( new byte[MAX_DATA_SIZE] ); - assertEquals( MAX_RECORD_SIZE, r.getRecordSize() ); - r.setRawData( new byte[MAX_DATA_SIZE+1] ); - assertEquals( MAX_RECORD_SIZE + 5, r.getRecordSize() ); - r.setRawData( new byte[MAX_DATA_SIZE*2] ); - assertEquals( MAX_RECORD_SIZE * 2, r.getRecordSize() ); - r.setRawData( new byte[MAX_DATA_SIZE*2 + 1] ); - assertEquals( MAX_RECORD_SIZE * 2 + 5, r.getRecordSize() ); - } - - public void testSerialize() { - // Check under max record size - DrawingGroupRecord r = new DrawingGroupRecord(); - byte[] rawData = new byte[100]; - rawData[0] = 100; - rawData[99] = (byte) 200; - r.setRawData( rawData ); - byte[] buffer = new byte[r.getRecordSize()]; - int size = r.serialize( 0, buffer ); - assertEquals( 104, size ); - assertEquals("[EB, 00, 64, 00, 64, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, C8]", HexDump.toHex(buffer)); - - // check at max record size - rawData = new byte[MAX_DATA_SIZE]; - r.setRawData( rawData ); - buffer = new byte[r.getRecordSize()]; - size = r.serialize( 0, buffer ); - assertEquals( MAX_RECORD_SIZE, size ); - - // check over max record size - rawData = new byte[MAX_DATA_SIZE+1]; - rawData[rawData.length-1] = (byte) 255; - r.setRawData( rawData ); - buffer = new byte[r.getRecordSize()]; - size = r.serialize( 0, buffer ); - assertEquals( MAX_RECORD_SIZE + 5, size ); - assertEquals( "[EB, 00, 20, 20]", HexDump.toHex(cut(buffer, 0, 4) )); - assertEquals( "[00, EB, 00, 01, 00, FF]", HexDump.toHex(cut(buffer, MAX_RECORD_SIZE - 1, MAX_RECORD_SIZE + 5) )); - - // check continue record - rawData = new byte[MAX_DATA_SIZE * 2 + 1]; - rawData[rawData.length-1] = (byte) 255; - r.setRawData( rawData ); - buffer = new byte[r.getRecordSize()]; - size = r.serialize( 0, buffer ); - assertEquals( MAX_RECORD_SIZE * 2 + 5, size ); - assertEquals( MAX_RECORD_SIZE * 2 + 5, r.getRecordSize() ); - assertEquals( "[EB, 00, 20, 20]", HexDump.toHex(cut(buffer, 0, 4) )); - assertEquals( "[EB, 00, 20, 20]", HexDump.toHex(cut(buffer, MAX_RECORD_SIZE, MAX_RECORD_SIZE + 4) )); - assertEquals( "[3C, 00, 01, 00, FF]", HexDump.toHex(cut(buffer, MAX_RECORD_SIZE * 2, MAX_RECORD_SIZE * 2 + 5) )); - - // check continue record - rawData = new byte[664532]; - r.setRawData( rawData ); - buffer = new byte[r.getRecordSize()]; - size = r.serialize( 0, buffer ); - assertEquals( 664856, size ); - assertEquals( 664856, r.getRecordSize() ); - } - - private static byte[] cut( byte[] data, int fromInclusive, int toExclusive ) - { - int length = toExclusive - fromInclusive; - byte[] result = new byte[length]; - System.arraycopy( data, fromInclusive, result, 0, length); - return result; - } - - public void testGrossSizeFromDataSize() { - for (int i = 0; i < MAX_RECORD_SIZE * 4; i += 11) - { - //System.out.print( "data size = " + i + ", gross size = " + DrawingGroupRecord.grossSizeFromDataSize( i ) ); - //System.out.println( " Diff: " + (DrawingGroupRecord.grossSizeFromDataSize( i ) - i) ); - } - - assertEquals( 4, DrawingGroupRecord.grossSizeFromDataSize( 0 ) ); - assertEquals( 5, DrawingGroupRecord.grossSizeFromDataSize( 1 ) ); - assertEquals( MAX_RECORD_SIZE, DrawingGroupRecord.grossSizeFromDataSize( MAX_DATA_SIZE ) ); - assertEquals( MAX_RECORD_SIZE + 5, DrawingGroupRecord.grossSizeFromDataSize( MAX_DATA_SIZE + 1 ) ); - assertEquals( MAX_RECORD_SIZE * 2, DrawingGroupRecord.grossSizeFromDataSize( MAX_DATA_SIZE * 2 ) ); - assertEquals( MAX_RECORD_SIZE * 2 + 5, DrawingGroupRecord.grossSizeFromDataSize( MAX_DATA_SIZE * 2 + 1 ) ); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestDrawingRecord.java b/src/testcases/org/apache/poi/hssf/record/TestDrawingRecord.java deleted file mode 100644 index e6a316791..000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestDrawingRecord.java +++ /dev/null @@ -1,63 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record; - -import static org.junit.Assert.assertArrayEquals; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.Arrays; -import java.util.List; - -import junit.framework.TestCase; - -public final class TestDrawingRecord extends TestCase { - - /** - * Check that RecordFactoryInputStream properly handles continued DrawingRecords - * See Bugzilla #47548 - */ - public void testReadContinued() throws IOException { - - //simulate a continues drawing record - ByteArrayOutputStream out = new ByteArrayOutputStream(); - //main part - DrawingRecord dg = new DrawingRecord(); - byte[] data1 = new byte[8224]; - Arrays.fill(data1, (byte)1); - dg.setData(data1); - out.write(dg.serialize()); - - //continued part - byte[] data2 = new byte[4048]; - Arrays.fill(data2, (byte)2); - ContinueRecord cn = new ContinueRecord(data2); - out.write(cn.serialize()); - - List rec = RecordFactory.createRecords(new ByteArrayInputStream(out.toByteArray())); - assertEquals(2, rec.size()); - assertTrue(rec.get(0) instanceof DrawingRecord); - assertTrue(rec.get(1) instanceof ContinueRecord); - - assertArrayEquals(data1, ((DrawingRecord)rec.get(0)).getRecordData()); - assertArrayEquals(data2, ((ContinueRecord)rec.get(1)).getData()); - - } - -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestEmbeddedObjectRefSubRecord.java b/src/testcases/org/apache/poi/hssf/record/TestEmbeddedObjectRefSubRecord.java deleted file mode 100644 index 3f7dd8643..000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestEmbeddedObjectRefSubRecord.java +++ /dev/null @@ -1,170 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record; - -import static org.junit.Assert.assertArrayEquals; -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -import org.apache.poi.util.HexRead; - -/** - * Tests the serialization and deserialization of the TestEmbeddedObjectRefSubRecord - * class works correctly. Test data taken directly from a real - * Excel file. - * - * @author Yegor Kozlov - */ -public final class TestEmbeddedObjectRefSubRecord extends TestCase { - - private static final short EORSR_SID = EmbeddedObjectRefSubRecord.sid; - - public void testStore() { - String data1 - = "20 00 05 00 FC 10 76 01 02 24 14 DF 00 03 10 00 " - + "00 46 6F 72 6D 73 2E 43 68 65 63 6B 42 6F 78 2E " - + "31 00 00 00 00 00 70 00 00 00 00 00 00 00 00 00 " - + "00 00"; - - byte[] src = hr(data1); - - RecordInputStream in = TestcaseRecordInputStream.create(EORSR_SID, src); - - EmbeddedObjectRefSubRecord record1 = new EmbeddedObjectRefSubRecord(in, src.length); - - byte[] ser = record1.serialize(); - - RecordInputStream in2 = TestcaseRecordInputStream.create(ser); - EmbeddedObjectRefSubRecord record2 = new EmbeddedObjectRefSubRecord(in2, ser.length-4); - - confirmData(src, ser); - assertEquals(record1.getOLEClassName(), record2.getOLEClassName()); - - byte[] ser2 = record1.serialize(); - assertArrayEquals(ser, ser2); - } - - /** - * @param expectedData does not include sid & size - * @param actualFullRecordData includes sid & size - */ - private static void confirmData(byte[] expectedData, byte[] actualFullRecordData) { - assertEquals(expectedData.length, actualFullRecordData.length-4); - for (int i = 0; i < expectedData.length; i++) { - if(expectedData[i] != actualFullRecordData[i+4]) { - throw new AssertionFailedError("Difference at offset (" + i + ")"); - } - } - } - - public void testCreate() { - - EmbeddedObjectRefSubRecord record1 = new EmbeddedObjectRefSubRecord(); - - byte[] ser = record1.serialize(); - RecordInputStream in2 = TestcaseRecordInputStream.create(ser); - EmbeddedObjectRefSubRecord record2 = new EmbeddedObjectRefSubRecord(in2, ser.length-4); - - assertEquals(record1.getOLEClassName(), record2.getOLEClassName()); - assertEquals(record1.getStreamId(), record2.getStreamId()); - - byte[] ser2 = record1.serialize(); - assertArrayEquals(ser, ser2); - } - - public void testCameraTool_bug45912() { - /** - * taken from ftPictFmla sub-record in attachment 22645 (offset 0x40AB). - */ - byte[] data45912 = hr( - "12 00 0B 00 F8 02 88 04 3B 00 " + - "00 00 00 01 00 00 00 01 " + - "00 00"); - RecordInputStream in = TestcaseRecordInputStream.create(EORSR_SID, data45912); - - EmbeddedObjectRefSubRecord rec = new EmbeddedObjectRefSubRecord(in, data45912.length); - byte[] ser2 = rec.serialize(); - confirmData(data45912, ser2); - } - - private static byte[] hr(String string) { - return HexRead.readFromString(string); - } - - /** - * tests various examples of OLE controls - */ - public void testVarious() { - String[] rawData = { - "12 00 0B 00 70 95 0B 05 3B 01 00 36 00 40 00 18 00 19 00 18", - "12 00 0B 00 B0 4D 3E 03 3B 00 00 00 00 01 00 00 80 01 C0 00", - "0C 00 05 00 60 AF 3B 03 24 FD FF FE C0 FE", - "24 00 05 00 40 42 3E 03 02 80 CD B4 04 03 15 00 00 46 6F 72 6D 73 2E 43 6F 6D 6D 61 6E 64 42 75 74 74 6F 6E 2E 31 00 00 00 00 54 00 00 00 00 00 00 00 00 00 00 00", - "22 00 05 00 10 4E 3E 03 02 00 4C CC 04 03 12 00 00 46 6F 72 6D 73 2E 53 70 69 6E 42 75 74 74 6F 6E 2E 31 00 54 00 00 00 20 00 00 00 00 00 00 00 00 00 00 00", - "20 00 05 00 E0 41 3E 03 02 00 FC 0B 05 03 10 00 00 46 6F 72 6D 73 2E 43 6F 6D 62 6F 42 6F 78 2E 31 00 74 00 00 00 4C 00 00 00 00 00 00 00 00 00 00 00", - "24 00 05 00 00 4C AF 03 02 80 E1 93 05 03 14 00 00 46 6F 72 6D 73 2E 4F 70 74 69 6F 6E 42 75 74 74 6F 6E 2E 31 00 C0 00 00 00 70 00 00 00 00 00 00 00 00 00 00 00", - "20 00 05 00 E0 A4 28 04 02 80 EA 93 05 03 10 00 00 46 6F 72 6D 73 2E 43 68 65 63 6B 42 6F 78 2E 31 00 30 01 00 00 6C 00 00 00 00 00 00 00 00 00 00 00", - "1C 00 05 00 30 40 3E 03 02 00 CC B4 04 03 0D 00 00 46 6F 72 6D 73 2E 4C 61 62 65 6C 2E 31 9C 01 00 00 54 00 00 00 00 00 00 00 00 00 00 00", - "1E 00 05 00 B0 A4 28 04 02 00 D0 0A 05 03 0F 00 00 46 6F 72 6D 73 2E 4C 69 73 74 42 6F 78 2E 31 F0 01 00 00 48 00 00 00 00 00 00 00 00 00 00 00", - "24 00 05 00 C0 AF 3B 03 02 80 D1 0A 05 03 14 00 00 46 6F 72 6D 73 2E 54 6F 67 67 6C 65 42 75 74 74 6F 6E 2E 31 00 38 02 00 00 6C 00 00 00 00 00 00 00 00 00 00 00", - "1E 00 05 00 90 AF 3B 03 02 80 D4 0A 05 03 0F 00 00 46 6F 72 6D 73 2E 54 65 78 74 42 6F 78 2E 31 A4 02 00 00 48 00 00 00 00 00 00 00 00 00 00 00", - "24 00 05 00 60 40 3E 03 02 00 D6 0A 05 03 14 00 00 46 6F 72 6D 73 2E 54 6F 67 67 6C 65 42 75 74 74 6F 6E 2E 31 00 EC 02 00 00 6C 00 00 00 00 00 00 00 00 00 00 00", - "20 00 05 00 20 4D 3E 03 02 00 D9 0A 05 03 11 00 00 46 6F 72 6D 73 2E 53 63 72 6F 6C 6C 42 61 72 2E 31 58 03 00 00 20 00 00 00 00 00 00 00 00 00 00 00", - "20 00 05 00 00 AF 28 04 02 80 31 AC 04 03 10 00 00 53 68 65 6C 6C 2E 45 78 70 6C 6F 72 65 72 2E 32 00 78 03 00 00 AC 00 00 00 00 00 00 00 00 00 00 00", - }; - - for (int i = 0; i < rawData.length; i++) { - confirmRead(hr(rawData[i]), i); - } - } - - private static void confirmRead(byte[] data, int i) { - RecordInputStream in = TestcaseRecordInputStream.create(EORSR_SID, data); - - EmbeddedObjectRefSubRecord rec = new EmbeddedObjectRefSubRecord(in, data.length); - byte[] ser2 = rec.serialize(); - TestcaseRecordInputStream.confirmRecordEncoding("Test record " + i, EORSR_SID, data, ser2); - } - - public void testVisioDrawing_bug46199() { - /** - * taken from ftPictFmla sub-record in attachment 22860 (stream offset 0x768F).
    - * Note that the since the string length is zero, there is no unicode flag byte - */ - byte[] data46199 = hr( - "0E 00 " - + "05 00 " - + "28 25 A3 01 " - + "02 6C D1 34 02 " - + "03 00 00 " - + "0F CB E8 00"); - RecordInputStream in = TestcaseRecordInputStream.create(EORSR_SID, data46199); - - EmbeddedObjectRefSubRecord rec; - try { - rec = new EmbeddedObjectRefSubRecord(in, data46199.length); - } catch (RecordFormatException e) { - if (e.getMessage().equals("Not enough data (3) to read requested (4) bytes")) { - throw new AssertionFailedError("Identified bug 22860"); - } - throw e; - } - byte[] ser2 = rec.serialize(); - TestcaseRecordInputStream.confirmRecordEncoding(EORSR_SID, data46199, ser2); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestEndSubRecord.java b/src/testcases/org/apache/poi/hssf/record/TestEndSubRecord.java deleted file mode 100644 index ab4a80120..000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestEndSubRecord.java +++ /dev/null @@ -1,47 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record; - - -import junit.framework.TestCase; - -/** - * Tests the serialization and deserialization of the EndSubRecord - * class works correctly. Test data taken directly from a real - * Excel file. - * - * @author Glen Stampoultzis (glens at apache.org) - */ -public final class TestEndSubRecord extends TestCase { - private static final byte[] data = { }; - - public void testLoad() { - EndSubRecord record = new EndSubRecord(TestcaseRecordInputStream.create(0x00, data), 0); - assertEquals(0, record.getDataSize()); - } - - public void testStore() - { - EndSubRecord record = new EndSubRecord(); - - byte [] recordBytes = record.serialize(); - assertEquals(recordBytes.length - 4, data.length); - for (int i = 0; i < data.length; i++) - assertEquals("At offset " + i, data[i], recordBytes[i+4]); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestEscherAggregate.java b/src/testcases/org/apache/poi/hssf/record/TestEscherAggregate.java deleted file mode 100644 index 0df5d44f4..000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestEscherAggregate.java +++ /dev/null @@ -1,131 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record; - -import junit.framework.TestCase; -import org.apache.poi.ddf.EscherClientDataRecord; -import org.apache.poi.ddf.EscherContainerRecord; -import org.apache.poi.ddf.EscherSpRecord; -import org.apache.poi.util.HexDump; -import org.apache.poi.util.HexRead; - -import java.util.ArrayList; -import java.util.List; - -/** - * Tests the EscherAggregate class. - * - * @author Glen Stampoultzis (glens at apache.org) - */ -public final class TestEscherAggregate extends TestCase { - /** - * Tests that the create aggregate method correctly rejoins escher records together. - */ - public void testCreateAggregate() { - String msoDrawingRecord1 = - "0F 00 02 F0 20 01 00 00 10 00 08 F0 08 00 00 00 \n" + - "03 00 00 00 02 04 00 00 0F 00 03 F0 08 01 00 00 \n" + - "0F 00 04 F0 28 00 00 00 01 00 09 F0 10 00 00 00 \n" + - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 \n" + - "02 00 0A F0 08 00 00 00 00 04 00 00 05 00 00 00 \n" + - "0F 00 04 F0 64 00 00 00 42 01 0A F0 08 00 00 00 \n" + - "01 04 00 00 00 0A 00 00 73 00 0B F0 2A 00 00 00 \n" + - "BF 00 08 00 08 00 44 01 04 00 00 00 7F 01 00 00 \n" + - "01 00 BF 01 00 00 11 00 C0 01 40 00 00 08 FF 01 \n" + - "10 00 10 00 BF 03 00 00 08 00 00 00 10 F0 12 00 \n" + - "00 00 00 00 01 00 54 00 05 00 45 00 01 00 88 03 \n" + - "05 00 94 00 00 00 11 F0 00 00 00 00"; - - String msoDrawingRecord2 = - "0F 00 04 F0 64 00 00 00 42 01 0A F0 08 00 00 00 " + - "02 04 00 00 80 0A 00 00 73 00 0B F0 2A 00 00 00 " + - "BF 00 08 00 08 00 44 01 04 00 00 00 7F 01 00 00 " + - "01 00 BF 01 00 00 11 00 C0 01 40 00 00 08 FF 01 " + - "10 00 10 00 BF 03 00 00 08 00 00 00 10 F0 12 00 " + - "00 00 00 00 01 00 8D 03 05 00 E4 00 03 00 4D 03 " + - "0B 00 0C 00 00 00 11 F0 00 00 00 00"; - - DrawingRecord d1 = new DrawingRecord(); - d1.setData( HexRead.readFromString( msoDrawingRecord1 ) ); - - ObjRecord r1 = new ObjRecord(); - - DrawingRecord d2 = new DrawingRecord(); - d2.setData( HexRead.readFromString( msoDrawingRecord2 ) ); - - ObjRecord r2 = new ObjRecord(); - - List records = new ArrayList(); - records.add( d1 ); - records.add( r1 ); - records.add( d2 ); - records.add( r2 ); - - EscherAggregate aggregate = EscherAggregate.createAggregate(records, 0); - - assertEquals( 1, aggregate.getEscherRecords().size() ); - assertEquals( (short) 0xF002, aggregate.getEscherRecord( 0 ).getRecordId() ); - assertEquals( 2, aggregate.getEscherRecord( 0 ).getChildRecords().size() ); - -// System.out.println( "aggregate = " + aggregate ); - } - - public void testSerialize() { - - EscherContainerRecord container1 = new EscherContainerRecord(); - EscherContainerRecord spContainer1 = new EscherContainerRecord(); - EscherContainerRecord spContainer2 = new EscherContainerRecord(); - EscherContainerRecord spContainer3 = new EscherContainerRecord(); - EscherSpRecord sp1 = new EscherSpRecord(); - EscherSpRecord sp2 = new EscherSpRecord(); - EscherSpRecord sp3 = new EscherSpRecord(); - EscherClientDataRecord d2 = new EscherClientDataRecord(); - EscherClientDataRecord d3 = new EscherClientDataRecord(); - - container1.setOptions( (short) 0x000F ); - spContainer1.setOptions( (short) 0x000F ); - spContainer1.setRecordId( EscherContainerRecord.SP_CONTAINER ); - spContainer2.setOptions( (short) 0x000F ); - spContainer2.setRecordId( EscherContainerRecord.SP_CONTAINER ); - spContainer3.setOptions( (short) 0x000F ); - spContainer3.setRecordId( EscherContainerRecord.SP_CONTAINER ); - d2.setRecordId( EscherClientDataRecord.RECORD_ID ); - d2.setRemainingData( new byte[0] ); - d3.setRecordId( EscherClientDataRecord.RECORD_ID ); - d3.setRemainingData( new byte[0] ); - container1.addChildRecord( spContainer1 ); - container1.addChildRecord( spContainer2 ); - container1.addChildRecord( spContainer3 ); - spContainer1.addChildRecord( sp1 ); - spContainer2.addChildRecord( sp2 ); - spContainer3.addChildRecord( sp3 ); - spContainer2.addChildRecord( d2 ); - spContainer3.addChildRecord( d3 ); - - EscherAggregate aggregate = new EscherAggregate(false); - aggregate.addEscherRecord( container1 ); - aggregate.associateShapeToObjRecord( d2, new ObjRecord() ); - aggregate.associateShapeToObjRecord( d3, new ObjRecord() ); - - byte[] data = new byte[112]; - int bytesWritten = aggregate.serialize( 0, data ); - assertEquals( 112, bytesWritten ); - assertEquals( "[EC, 00, 40, 00, 0F, 00, 00, 00, 58, 00, 00, 00, 0F, 00, 04, F0, 10, 00, 00, 00, 00, 00, 0A, F0, 08, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 0F, 00, 04, F0, 18, 00, 00, 00, 00, 00, 0A, F0, 08, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 11, F0, 00, 00, 00, 00, 5D, 00, 00, 00, EC, 00, 20, 00, 0F, 00, 04, F0, 18, 00, 00, 00, 00, 00, 0A, F0, 08, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 11, F0, 00, 00, 00, 00, 5D, 00, 00, 00]", - HexDump.toHex( data ) ); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestExtSSTRecord.java b/src/testcases/org/apache/poi/hssf/record/TestExtSSTRecord.java deleted file mode 100644 index 7a126c57a..000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestExtSSTRecord.java +++ /dev/null @@ -1,865 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.hssf.record; - -import junit.framework.TestCase; -import org.apache.poi.hssf.record.common.UnicodeString; -import org.apache.poi.util.HexRead; - -/** - * @author Yegor Kozlov - */ -public final class TestExtSSTRecord extends TestCase { - - - /** - * hex dump from ISBN_UPD_PL_20100104_1525.xls atatched to Bugzilla 50867 - */ - private static final String data_50967 = - // "Offset=0x0008BB19(572185) recno=159 sid=0x00FF size=0x201A(8218)\n" + - " FF 00 1A 20 08 00 1A" + - "09 00 00 0C 00 00 00 6D 09 00 00 5F 00 00 00 B8" + - "09 00 00 AA 00 00 00 BC 0A 00 00 AE 01 00 00 FA" + - "0B 00 00 EC 02 00 00 C6 0D 00 00 B8 04 00 00 2E" + - "0F 00 00 20 06 00 00 5C 11 00 00 4E 08 00 00 B0" + - "12 00 00 A2 09 00 00 A4 13 00 00 96 0A 00 00 92" + - "15 00 00 84 0C 00 00 0A 17 00 00 FC 0D 00 00 32" + - "18 00 00 24 0F 00 00 84 19 00 00 76 10 00 00 9A" + - "1A 00 00 8C 11 00 00 5E 1C 00 00 50 13 00 00 24" + - "1D 00 00 16 14 00 00 56 1E 00 00 48 15 00 00 1C" + - "1F 00 00 0E 16 00 00 DA 1F 00 00 CC 16 00 00 76" + - "21 00 00 68 18 00 00 2E 23 00 00 20 1A 00 00 A0" + - "24 00 00 92 1B 00 00 FA 25 00 00 EC 1C 00 00 BA" + - "27 00 00 AC 1E 00 00 12 29 00 00 04 00 00 00 4E" + - "2A 00 00 40 01 00 00 A0 2B 00 00 92 02 00 00 C8" + - "2C 00 00 BA 03 00 00 62 2E 00 00 54 05 00 00 58" + - "2F 00 00 4A 06 00 00 9A 30 00 00 8C 07 00 00 02" + - "32 00 00 F4 08 00 00 36 33 00 00 28 0A 00 00 30" + - "34 00 00 22 0B 00 00 FC 34 00 00 EE 0B 00 00 FE" + - "35 00 00 F0 0C 00 00 26 37 00 00 18 0E 00 00 C6" + - "38 00 00 B8 0F 00 00 FA 39 00 00 EC 10 00 00 8E" + - "3B 00 00 80 12 00 00 2C 3D 00 00 1E 14 00 00 3C" + - "3E 00 00 2E 15 00 00 80 3F 00 00 72 16 00 00 74" + - "40 00 00 66 17 00 00 8A 41 00 00 7C 18 00 00 64" + - "42 00 00 56 19 00 00 96 43 00 00 88 1A 00 00 82" + - "44 00 00 74 1B 00 00 76 45 00 00 68 1C 00 00 80" + - "46 00 00 72 1D 00 00 88 47 00 00 7A 1E 00 00 80" + - "48 00 00 72 1F 00 00 66 49 00 00 34 00 00 00 76" + - "4A 00 00 44 01 00 00 D0 4B 00 00 9E 02 00 00 F2" + - "4C 00 00 C0 03 00 00 DA 4D 00 00 A8 04 00 00 B4" + - "4F 00 00 82 06 00 00 12 51 00 00 E0 07 00 00 2A" + - "52 00 00 F8 08 00 00 3C 53 00 00 0A 0A 00 00 6E" + - "54 00 00 3C 0B 00 00 BC 55 00 00 8A 0C 00 00 14" + - "57 00 00 E2 0D 00 00 3C 58 00 00 0A 0F 00 00 36" + - "59 00 00 04 10 00 00 4A 5A 00 00 18 11 00 00 4A" + - "5B 00 00 18 12 00 00 AC 5C 00 00 7A 13 00 00 C2" + - "5D 00 00 90 14 00 00 2C 5F 00 00 FA 15 00 00 74" + - "60 00 00 42 17 00 00 56 62 00 00 24 19 00 00 12" + - "64 00 00 E0 1A 00 00 E8 65 00 00 B6 1C 00 00 CA" + - "66 00 00 98 1D 00 00 14 68 00 00 E2 1E 00 00 56" + - "69 00 00 04 00 00 00 EC 6A 00 00 9A 01 00 00 DC" + - "6B 00 00 8A 02 00 00 EE 6C 00 00 9C 03 00 00 66" + - "6E 00 00 14 05 00 00 A6 6F 00 00 54 06 00 00 92" + - "70 00 00 40 07 00 00 E6 71 00 00 94 08 00 00 48" + - "73 00 00 F6 09 00 00 AC 74 00 00 5A 0B 00 00 A2" + - "75 00 00 50 0C 00 00 C4 76 00 00 72 0D 00 00 4E" + - "78 00 00 FC 0E 00 00 14 7A 00 00 C2 10 00 00 0C" + - "7B 00 00 BA 11 00 00 4E 7C 00 00 FC 12 00 00 5A" + - "7D 00 00 08 14 00 00 C4 7E 00 00 72 15 00 00 BA" + - "80 00 00 68 17 00 00 1C 82 00 00 CA 18 00 00 5E" + - "83 00 00 0C 1A 00 00 BA 84 00 00 68 1B 00 00 E6" + - "85 00 00 94 1C 00 00 46 87 00 00 F4 1D 00 00 94" + - "88 00 00 42 1F 00 00 24 8A 00 00 10 01 00 00 80" + - "8B 00 00 6C 02 00 00 8E 8C 00 00 7A 03 00 00 82" + - "8D 00 00 6E 04 00 00 54 8E 00 00 40 05 00 00 60" + - "8F 00 00 4C 06 00 00 68 90 00 00 54 07 00 00 92" + - "91 00 00 7E 08 00 00 C8 92 00 00 B4 09 00 00 2C" + - "94 00 00 18 0B 00 00 8E 95 00 00 7A 0C 00 00 AA" + - "96 00 00 96 0D 00 00 FA 97 00 00 E6 0E 00 00 3E" + - "99 00 00 2A 10 00 00 54 9A 00 00 40 11 00 00 D4" + - "9B 00 00 C0 12 00 00 C2 9C 00 00 AE 13 00 00 1E" + - "9E 00 00 0A 15 00 00 F4 9E 00 00 E0 15 00 00 E0" + - "9F 00 00 CC 16 00 00 08 A1 00 00 F4 17 00 00 0E" + - "A2 00 00 FA 18 00 00 8A A3 00 00 76 1A 00 00 78" + - "A5 00 00 64 1C 00 00 4E A6 00 00 3A 1D 00 00 42" + - "A7 00 00 2E 1E 00 00 08 A9 00 00 F4 1F 00 00 BE" + - "AA 00 00 8D 01 00 00 34 AC 00 00 03 03 00 00 62" + - "AD 00 00 31 04 00 00 68 AE 00 00 37 05 00 00 52" + - "AF 00 00 21 06 00 00 DE B0 00 00 AD 07 00 00 A8" + - "B1 00 00 77 08 00 00 B6 B2 00 00 85 09 00 00 DA" + - "B3 00 00 A9 0A 00 00 EC B4 00 00 BB 0B 00 00 EA" + - "B5 00 00 B9 0C 00 00 0A B7 00 00 D9 0D 00 00 0A" + - "B8 00 00 D9 0E 00 00 26 B9 00 00 F5 0F 00 00 72" + - "BA 00 00 41 11 00 00 D8 BB 00 00 A7 12 00 00 3A" + - "BD 00 00 09 14 00 00 6C BE 00 00 3B 15 00 00 88" + - "BF 00 00 57 16 00 00 D8 C0 00 00 A7 17 00 00 60" + - "C2 00 00 2F 19 00 00 84 C3 00 00 53 1A 00 00 A8" + - "C4 00 00 77 1B 00 00 CE C5 00 00 9D 1C 00 00 02" + - "C7 00 00 D1 1D 00 00 58 C8 00 00 27 1F 00 00 56" + - "C9 00 00 04 00 00 00 D0 CA 00 00 7E 01 00 00 D4" + - "CB 00 00 82 02 00 00 38 CD 00 00 E6 03 00 00 E4" + - "CF 00 00 92 06 00 00 76 D1 00 00 24 08 00 00 10" + - "D3 00 00 BE 09 00 00 50 D4 00 00 FE 0A 00 00 94" + - "D5 00 00 42 0C 00 00 14 D7 00 00 C2 0D 00 00 92" + - "D8 00 00 40 0F 00 00 EC D9 00 00 9A 10 00 00 20" + - "DC 00 00 CE 12 00 00 7E DD 00 00 2C 14 00 00 5C" + - "DF 00 00 0A 16 00 00 B8 E0 00 00 66 17 00 00 9C" + - "E1 00 00 4A 18 00 00 44 E3 00 00 F2 19 00 00 A6" + - "E4 00 00 54 1B 00 00 F8 E5 00 00 A6 1C 00 00 D4" + - "E7 00 00 82 1E 00 00 2E E9 00 00 DC 1F 00 00 C8" + - "EA 00 00 75 01 00 00 3C EC 00 00 E9 02 00 00 6A" + - "ED 00 00 17 04 00 00 BC EE 00 00 69 05 00 00 18" + - "F0 00 00 C5 06 00 00 D0 F1 00 00 7D 08 00 00 66" + - "F3 00 00 13 0A 00 00 8C F4 00 00 39 0B 00 00 EC" + - "F5 00 00 99 0C 00 00 2A F7 00 00 D7 0D 00 00 84" + - "F8 00 00 31 0F 00 00 A0 F9 00 00 4D 10 00 00 06" + - "FB 00 00 B3 11 00 00 E6 FB 00 00 93 12 00 00 08" + - "FD 00 00 B5 13 00 00 66 FE 00 00 13 15 00 00 DA" + - "FF 00 00 87 16 00 00 52 01 01 00 FF 17 00 00 74" + - "02 01 00 21 19 00 00 96 03 01 00 43 1A 00 00 BC" + - "04 01 00 69 1B 00 00 72 06 01 00 1F 1D 00 00 D4" + - "07 01 00 81 1E 00 00 56 09 01 00 04 00 00 00 FC" + - "0A 01 00 AA 01 00 00 5E 0C 01 00 0C 03 00 00 B6" + - "0D 01 00 64 04 00 00 F4 0E 01 00 A2 05 00 00 74" + - "10 01 00 22 07 00 00 00 12 01 00 AE 08 00 00 4A" + - "13 01 00 F8 09 00 00 40 14 01 00 EE 0A 00 00 66" + - "15 01 00 14 0C 00 00 B8 16 01 00 66 0D 00 00 3E" + - "18 01 00 EC 0E 00 00 58 19 01 00 06 10 00 00 72" + - "1A 01 00 20 11 00 00 4A 1C 01 00 F8 12 00 00 8E" + - "1D 01 00 3C 14 00 00 E8 1E 01 00 96 15 00 00 A8" + - "20 01 00 56 17 00 00 88 23 01 00 36 1A 00 00 00" + - "25 01 00 AE 1B 00 00 AE 26 01 00 5C 1D 00 00 88" + - "28 01 00 36 1F 00 00 96 29 01 00 25 00 00 00 E6" + - "2A 01 00 75 01 00 00 A2 2C 01 00 31 03 00 00 40" + - "2E 01 00 CF 04 00 00 B8 2F 01 00 47 06 00 00 64" + - "31 01 00 F3 07 00 00 C0 32 01 00 4F 09 00 00 1C" + - "34 01 00 AB 0A 00 00 A4 35 01 00 33 0C 00 00 2A" + - "37 01 00 B9 0D 00 00 9A 38 01 00 29 0F 00 00 94" + - "3A 01 00 23 11 00 00 86 3B 01 00 15 12 00 00 44" + - "3D 01 00 D3 13 00 00 6E 3E 01 00 FD 14 00 00 8C" + - "40 01 00 1B 17 00 00 44 42 01 00 D3 18 00 00 0E" + - "44 01 00 9D 1A 00 00 06 45 01 00 95 1B 00 00 BA" + - "46 01 00 49 1D 00 00 24 49 01 00 B3 1F 00 00 A2" + - "4A 01 00 12 01 00 00 2C 4C 01 00 9C 02 00 00 D4" + - "4D 01 00 44 04 00 00 5E 50 01 00 CE 06 00 00 82" + - "51 01 00 F2 07 00 00 9C 52 01 00 0C 09 00 00 9E" + - "54 01 00 0E 0B 00 00 6C 56 01 00 DC 0C 00 00 42" + - "57 01 00 B2 0D 00 00 70 58 01 00 E0 0E 00 00 6E" + - "5A 01 00 DE 10 00 00 86 5C 01 00 F6 12 00 00 F2" + - "5D 01 00 62 14 00 00 A0 5F 01 00 10 16 00 00 6C" + - "61 01 00 DC 17 00 00 6C 64 01 00 DC 1A 00 00 F0" + - "66 01 00 60 1D 00 00 4E 69 01 00 BE 1F 00 00 68" + - "6A 01 00 EA 00 00 00 6E 6C 01 00 F0 02 00 00 B8" + - "6D 01 00 3A 04 00 00 52 6F 01 00 D4 05 00 00 C6" + - "70 01 00 48 07 00 00 80 72 01 00 02 09 00 00 DC" + - "73 01 00 5E 0A 00 00 F2 75 01 00 74 0C 00 00 6C" + - "77 01 00 EE 0D 00 00 46 79 01 00 C8 0F 00 00 CC" + - "7A 01 00 4E 11 00 00 80 7C 01 00 02 13 00 00 08" + - "7E 01 00 8A 14 00 00 80 7F 01 00 02 16 00 00 46" + - "81 01 00 C8 17 00 00 26 83 01 00 A8 19 00 00 A4" + - "84 01 00 26 1B 00 00 02 86 01 00 84 1C 00 00 F4" + - "87 01 00 76 1E 00 00 68 89 01 00 04 00 00 00 4E" + - "8B 01 00 EA 01 00 00 04 8D 01 00 A0 03 00 00 FE" + - "8E 01 00 9A 05 00 00 A2 90 01 00 3E 07 00 00 A6" + - "91 01 00 42 08 00 00 76 93 01 00 12 0A 00 00 72" + - "95 01 00 0E 0C 00 00 36 97 01 00 D2 0D 00 00 50" + - "99 01 00 EC 0F 00 00 E2 9B 01 00 7E 12 00 00 6A" + - "9D 01 00 06 14 00 00 28 9F 01 00 C4 15 00 00 F0" + - "A1 01 00 8C 18 00 00 B8 A3 01 00 54 1A 00 00 14" + - "A6 01 00 B0 1C 00 00 7C A7 01 00 18 1E 00 00 E2" + - "A8 01 00 7E 1F 00 00 8C AA 01 00 2A 01 00 00 8C" + - "AC 01 00 2A 03 00 00 A6 AE 01 00 44 05 00 00 76" + - "B0 01 00 14 07 00 00 A0 B2 01 00 3E 09 00 00 12" + - "B4 01 00 B0 0A 00 00 78 B5 01 00 16 0C 00 00 A4" + - "B6 01 00 42 0D 00 00 5C B7 01 00 FA 0D 00 00 08" + - "B8 01 00 A6 0E 00 00 D0 B9 01 00 6E 10 00 00 D2" + - "BB 01 00 70 12 00 00 6C BD 01 00 0A 14 00 00 78" + - "BF 01 00 16 16 00 00 AE C0 01 00 4C 17 00 00 BA" + - "C1 01 00 58 18 00 00 02 C3 01 00 A0 19 00 00 BA" + - "C3 01 00 58 1A 00 00 F6 C4 01 00 94 1B 00 00 70" + - "C7 01 00 0E 1E 00 00 E8 C8 01 00 86 1F 00 00 AC" + - "CA 01 00 88 01 00 00 88 CC 01 00 64 03 00 00 90" + - "CE 01 00 6C 05 00 00 5C D0 01 00 38 07 00 00 66" + - "D2 01 00 42 09 00 00 F6 D3 01 00 D2 0A 00 00 4E" + - "D5 01 00 2A 0C 00 00 A2 D7 01 00 7E 0E 00 00 BE" + - "D8 01 00 9A 0F 00 00 AE DA 01 00 8A 11 00 00 7E" + - "DC 01 00 5A 13 00 00 F4 DD 01 00 D0 14 00 00 98" + - "DF 01 00 74 16 00 00 AA E1 01 00 86 18 00 00 24" + - "E3 01 00 00 1A 00 00 84 E4 01 00 60 1B 00 00 58" + - "E6 01 00 34 1D 00 00 DA E8 01 00 B6 1F 00 00 A6" + - "EA 01 00 5F 01 00 00 44 EC 01 00 FD 02 00 00 B8" + - "ED 01 00 71 04 00 00 18 EF 01 00 D1 05 00 00 3A" + - "F1 01 00 F3 07 00 00 3E F3 01 00 F7 09 00 00 9C" + - "F4 01 00 55 0B 00 00 74 F7 01 00 2D 0E 00 00 36" + - "F9 01 00 EF 0F 00 00 AA FB 01 00 63 12 00 00 60" + - "FD 01 00 19 14 00 00 60 FF 01 00 19 16 00 00 B2" + - "01 02 00 6B 18 00 00 84 03 02 00 3D 1A 00 00 42" + - "06 02 00 FB 1C 00 00 DE 08 02 00 97 1F 00 00 42" + - "0B 02 00 11 02 00 00 A0 0D 02 00 6F 04 00 00 28" + - "10 02 00 F7 06 00 00 FE 11 02 00 CD 08 00 00 64" + - "13 02 00 33 0A 00 00 4C 14 02 00 1B 0B 00 00 D8" + - "15 02 00 A7 0C 00 00 C6 16 02 00 95 0D 00 00 F8" + - "17 02 00 C7 0E 00 00 C4 19 02 00 93 10 00 00 02" + - "1B 02 00 D1 11 00 00 A4 1C 02 00 73 13 00 00 7A" + - "1D 02 00 49 14 00 00 B2 1E 02 00 81 15 00 00 66" + - "20 02 00 35 17 00 00 B2 21 02 00 81 18 00 00 52" + - "23 02 00 21 1A 00 00 B4 24 02 00 83 1B 00 00 EC" + - "25 02 00 BB 1C 00 00 36 27 02 00 05 1E 00 00 5E" + - "28 02 00 2D 1F 00 00 A8 29 02 00 62 00 00 00 4A" + - "2B 02 00 04 02 00 00 CA 2C 02 00 84 03 00 00 20" + - "2E 02 00 DA 04 00 00 C6 2F 02 00 80 06 00 00 26" + - "31 02 00 E0 07 00 00 3A 32 02 00 F4 08 00 00 6E" + - "33 02 00 28 0A 00 00 F4 34 02 00 AE 0B 00 00 DA" + - "35 02 00 94 0C 00 00 E4 36 02 00 9E 0D 00 00 08" + - "38 02 00 C2 0E 00 00 52 39 02 00 0C 10 00 00 96" + - "3A 02 00 50 11 00 00 3C 3C 02 00 F6 12 00 00 D2" + - "3D 02 00 8C 14 00 00 30 3F 02 00 EA 15 00 00 7A" + - "40 02 00 34 17 00 00 74 41 02 00 2E 18 00 00 F4" + - "42 02 00 AE 19 00 00 64 44 02 00 1E 1B 00 00 B4" + - "45 02 00 6E 1C 00 00 FA 46 02 00 B4 1D 00 00 4A" + - "48 02 00 04 1F 00 00 4C 49 02 00 04 00 00 00 58" + - "4A 02 00 10 01 00 00 98 4B 02 00 50 02 00 00 E0" + - "4C 02 00 98 03 00 00 48 4E 02 00 00 05 00 00 2E" + - "4F 02 00 E6 05 00 00 BE 50 02 00 76 07 00 00 18" + - "52 02 00 D0 08 00 00 66 53 02 00 1E 0A 00 00 BA" + - "54 02 00 72 0B 00 00 F2 55 02 00 AA 0C 00 00 3C" + - "57 02 00 F4 0D 00 00 6A 58 02 00 22 0F 00 00 D4" + - "59 02 00 8C 10 00 00 20 5B 02 00 D8 11 00 00 4C" + - "5C 02 00 04 13 00 00 FC 5C 02 00 B4 13 00 00 7A" + - "5E 02 00 32 15 00 00 B4 5F 02 00 6C 16 00 00 FA" + - "60 02 00 B2 17 00 00 7E 62 02 00 36 19 00 00 3C" + - "63 02 00 F4 19 00 00 CE 64 02 00 86 1B 00 00 F6" + - "65 02 00 AE 1C 00 00 18 67 02 00 D0 1D 00 00 82" + - "68 02 00 3A 1F 00 00 A0 69 02 00 3B 00 00 00 CE" + - "6A 02 00 69 01 00 00 CC 6B 02 00 67 02 00 00 D6" + - "6C 02 00 71 03 00 00 0E 6E 02 00 A9 04 00 00 24" + - "6F 02 00 BF 05 00 00 4A 70 02 00 E5 06 00 00 7A" + - "71 02 00 15 08 00 00 5A 72 02 00 F5 08 00 00 A0" + - "73 02 00 3B 0A 00 00 B6 74 02 00 51 0B 00 00 DA" + - "75 02 00 75 0C 00 00 E4 76 02 00 7F 0D 00 00 20" + - "78 02 00 BB 0E 00 00 00 79 02 00 9B 0F 00 00 F8" + - "79 02 00 93 10 00 00 16 7B 02 00 B1 11 00 00 06" + - "7C 02 00 A1 12 00 00 FA 7C 02 00 95 13 00 00 2A" + - "7E 02 00 C5 14 00 00 5C 7F 02 00 F7 15 00 00 46" + - "80 02 00 E1 16 00 00 54 81 02 00 EF 17 00 00 70" + - "82 02 00 0B 19 00 00 68 83 02 00 03 1A 00 00 40" + - "84 02 00 DB 1A 00 00 16 85 02 00 B1 1B 00 00 28" + - "86 02 00 C3 1C 00 00 DE 86 02 00 79 1D 00 00 08" + - "88 02 00 A3 1E 00 00 CE 88 02 00 69 1F 00 00 F2" + - "89 02 00 7A 00 00 00 C6 8A 02 00 4E 01 00 00 D8" + - "8B 02 00 60 02 00 00 B4 8C 02 00 3C 03 00 00 A2" + - "8D 02 00 2A 04 00 00 EE 8E 02 00 76 05 00 00 06" + - "90 02 00 8E 06 00 00 12 91 02 00 9A 07 00 00 F8" + - "91 02 00 80 08 00 00 20 93 02 00 A8 09 00 00 0A" + - "95 02 00 92 0B 00 00 FE 95 02 00 86 0C 00 00 C6" + - "96 02 00 4E 0D 00 00 92 97 02 00 1A 0E 00 00 36" + - "98 02 00 BE 0E 00 00 02 99 02 00 8A 0F 00 00 28" + - "9A 02 00 B0 10 00 00 5A 9B 02 00 E2 11 00 00 74" + - "9C 02 00 FC 12 00 00 6C 9D 02 00 F4 13 00 00 42" + - "9E 02 00 CA 14 00 00 90 9F 02 00 18 16 00 00 34" + - "A1 02 00 BC 17 00 00 1E A2 02 00 A6 18 00 00 42" + - "A3 02 00 CA 19 00 00 62 A4 02 00 EA 1A 00 00 74" + - "A5 02 00 FC 1B 00 00 B0 A6 02 00 38 1D 00 00 5A" + - "A8 02 00 E2 1E 00 00 86 A9 02 00 04 00 00 00 30" + - "AB 02 00 AE 01 00 00 DA AC 02 00 58 03 00 00 C4" + - "AD 02 00 42 04 00 00 8C AE 02 00 0A 05 00 00 C4" + - "AF 02 00 42 06 00 00 86 B1 02 00 04 08 00 00 54" + - "B2 02 00 D2 08 00 00 8A B3 02 00 08 0A 00 00 54" + - "B4 02 00 D2 0A 00 00 52 B5 02 00 D0 0B 00 00 58" + - "B6 02 00 D6 0C 00 00 68 B7 02 00 E6 0D 00 00 3E" + - "B8 02 00 BC 0E 00 00 2C B9 02 00 AA 0F 00 00 78" + - "BA 02 00 F6 10 00 00 AA BB 02 00 28 12 00 00 D6" + - "BC 02 00 54 13 00 00 CC BD 02 00 4A 14 00 00 F8" + - "BE 02 00 76 15 00 00 42 C0 02 00 C0 16 00 00 5C" + - "C1 02 00 DA 17 00 00 42 C2 02 00 C0 18 00 00 36" + - "C3 02 00 B4 19 00 00 78 C4 02 00 F6 1A 00 00 90" + - "C5 02 00 0E 1C 00 00 BA C6 02 00 38 1D 00 00 1A" + - "C8 02 00 98 1E 00 00 62 C9 02 00 E0 1F 00 00 0E" + - "CA 02 00 77 00 00 00 24 CB 02 00 8D 01 00 00 38" + - "CC 02 00 A1 02 00 00 A6 CD 02 00 0F 04 00 00 84" + - "CE 02 00 ED 04 00 00 50 CF 02 00 B9 05 00 00 2C" + - "D0 02 00 95 06 00 00 3A D1 02 00 A3 07 00 00 22" + - "D3 02 00 8B 09 00 00 14 D4 02 00 7D 0A 00 00 3E" + - "D5 02 00 A7 0B 00 00 68 D6 02 00 D1 0C 00 00 62" + - "D7 02 00 CB 0D 00 00 4C D8 02 00 B5 0E 00 00 6A" + - "D9 02 00 D3 0F 00 00 92 DA 02 00 FB 10 00 00 CC" + - "DB 02 00 35 12 00 00 FC DC 02 00 65 13 00 00 A6" + - "DE 02 00 0F 15 00 00 B2 DF 02 00 1B 16 00 00 9E" + - "E0 02 00 07 17 00 00 A6 E1 02 00 0F 18 00 00 AA" + - "E2 02 00 13 19 00 00 86 E3 02 00 EF 19 00 00 C8" + - "E4 02 00 31 1B 00 00 F0 E5 02 00 59 1C 00 00 C6" + - "E6 02 00 2F 1D 00 00 BA E7 02 00 23 1E 00 00 EC" + - "E8 02 00 55 1F 00 00 02 EA 02 00 6C 00 00 00 64" + - "EB 02 00 CE 01 00 00 F4 EC 02 00 5E 03 00 00 FE" + - "ED 02 00 68 04 00 00 00 EF 02 00 6A 05 00 00 F6" + - "EF 02 00 60 06 00 00 FA F0 02 00 64 07 00 00 CE" + - "F1 02 00 38 08 00 00 2E F3 02 00 98 09 00 00 36" + - "F4 02 00 A0 0A 00 00 46 F5 02 00 B0 0B 00 00 50" + - "F6 02 00 BA 0C 00 00 60 F7 02 00 CA 0D 00 00 7C" + - "F8 02 00 E6 0E 00 00 CC F9 02 00 36 10 00 00 DE" + - "FA 02 00 48 11 00 00 AA FB 02 00 14 12 00 00 2E" + - "FD 02 00 98 13 00 00 54 FE 02 00 BE 14 00 00 6E" + - "FF 02 00 D8 15 00 00 88 00 03 00 F2 16 00 00 D6" + - "01 03 00 40 18 00 00 4A 03 03 00 B4 19 00 00 80" + - "04 03 00 EA 1A 00 00 90 05 03 00 FA 1B 00 00 96" + - "06 03 00 00 1D 00 00 A4 07 03 00 0E 1E 00 00 12" + - "09 03 00 7C 1F 00 00 20 0A 03 00 8B 00 00 00 8E" + - "0B 03 00 F9 01 00 00 B6 0C 03 00 21 03 00 00 D6" + - "0D 03 00 41 04 00 00 D6 0E 03 00 41 05 00 00 28" + - "10 03 00 93 06 00 00 36 11 03 00 A1 07 00 00 84" + - "12 03 00 EF 08 00 00 F2 13 03 00 5D 0A 00 00 44" + - "15 03 00 AF 0B 00 00 F6 16 03 00 61 0D 00 00 26" + - "18 03 00 91 0E 00 00 B8 19 03 00 23 10 00 00 0A" + - "1B 03 00 75 11 00 00 5E 1C 03 00 C9 12 00 00 A4" + - "1D 03 00 0F 14 00 00 CA 1E 03 00 35 15 00 00 3A" + - "20 03 00 A5 16 00 00 C2 21 03 00 2D 18 00 00 A8" + - "22 03 00 13 19 00 00 DA 23 03 00 45 1A 00 00 3A" + - "25 03 00 A5 1B 00 00 2C 26 03 00 97 1C 00 00 96" + - "27 03 00 01 1E 00 00 A2 28 03 00 0D 1F 00 00 B0" + - "29 03 00 04 00 00 00 78 2B 03 00 CC 01 00 00 44" + - "2C 03 00 98 02 00 00 74 2D 03 00 C8 03 00 00 00" + - "2F 03 00 54 05 00 00 18 30 03 00 6C 06 00 00 6C" + - "31 03 00 C0 07 00 00 E8 32 03 00 3C 09 00 00 E6" + - "33 03 00 3A 0A 00 00 5E 35 03 00 B2 0B 00 00 02" + - "37 03 00 56 0D 00 00 56 38 03 00 AA 0E 00 00 82" + - "39 03 00 D6 0F 00 00 C8 3A 03 00 1C 11 00 00 08" + - "3C 03 00 5C 12 00 00 72 3D 03 00 C6 13 00 00 C2" + - "3E 03 00 16 15 00 00 28 40 03 00 7C 16 00 00 AE" + - "41 03 00 02 18 00 00 38 43 03 00 8C 19 00 00 7A" + - "44 03 00 CE 1A 00 00 C4 45 03 00 18 1C 00 00 1E" + - "47 03 00 72 1D 00 00 A2 48 03 00 F6 1E 00 00 1E" + - "4A 03 00 51 00 00 00 7A 4B 03 00 AD 01 00 00 F8" + - "4C 03 00 2B 03 00 00 7C 4E 03 00 AF 04 00 00 6C" + - "50 03 00 9F 06 00 00 B8 51 03 00 EB 07 00 00 30" + - "53 03 00 63 09 00 00 2A 54 03 00 5D 0A 00 00 5C" + - "55 03 00 8F 0B 00 00 D4 56 03 00 07 0D 00 00 DE" + - "57 03 00 11 0E 00 00 E8 58 03 00 1B 0F 00 00 B0" + - "59 03 00 E3 0F 00 00 F4 5A 03 00 27 11 00 00 68" + - "5C 03 00 9B 12 00 00 F6 5D 03 00 29 14 00 00 F4" + - "5E 03 00 27 15 00 00 64 60 03 00 97 16 00 00 9E" + - "61 03 00 D1 17 00 00 CA 62 03 00 FD 18 00 00 3C" + - "64 03 00 6F 1A 00 00 96 65 03 00 C9 1B 00 00 FC" + - "66 03 00 2F 1D 00 00 40 68 03 00 73 1E 00 00 AE" + - "69 03 00 E1 1F 00 00 3E 6B 03 00 73 01 00 00 66" + - "6C 03 00 9B 02 00 00 52 6D 03 00 87 03 00 00 24" + - "6F 03 00 59 05 00 00 AA 70 03 00 DF 06 00 00 E6" + - "71 03 00 1B 08 00 00 82 73 03 00 B7 09 00 00 00" + - "75 03 00 35 0B 00 00 9E 76 03 00 D3 0C 00 00 20" + - "78 03 00 55 0E 00 00 0E 79 03 00 43 0F 00 00 10" + - "7A 03 00 45 10 00 00 02 7B 03 00 37 11 00 00 3C" + - "7C 03 00 71 12 00 00 8E 7D 03 00 C3 13 00 00 F4" + - "7E 03 00 29 15 00 00 96 80 03 00 CB 16 00 00 44" + - "82 03 00 79 18 00 00 76 84 03 00 AB 1A 00 00 92" + - "86 03 00 C7 1C 00 00 2D 88 03 00 62 1E 00 00 19" + - "8A 03 00 88 00 00 00 11 8B 03 00 80 01 00 00 BB" + - "8C 03 00 2A 03 00 00 CB 8D 03 00 3A 04 00 00 CB" + - "8E 03 00 3A 05 00 00 CF 8F 03 00 3E 06 00 00 C5" + - "90 03 00 34 07 00 00 A7 91 03 00 16 08 00 00 C9" + - "92 03 00 38 09 00 00 C5 93 03 00 34 0A 00 00 CD" + - "94 03 00 3C 0B 00 00 C5 96 03 00 34 0D 00 00 BB" + - "98 03 00 2A 0F 00 00 A9 99 03 00 18 10 00 00 C3" + - "9A 03 00 32 11 00 00 53 9C 03 00 C2 12 00 00 51" + - "9D 03 00 C0 13 00 00 AF 9E 03 00 1E 15 00 00 ED" + - "9F 03 00 5C 16 00 00 53 A1 03 00 C2 17 00 00 17" + - "A3 03 00 86 19 00 00 55 A4 03 00 C4 1A 00 00 6B" + - "A5 03 00 DA 1B 00 00 5F A6 03 00 CE 1C 00 00 5F" + - "A7 03 00 CE 1D 00 00 9F A8 03 00 0E 1F 00 00 51" + - "AA 03 00 9E 00 00 00 1F AC 03 00 6C 02 00 00 17" + - "AE 03 00 64 04 00 00 B7 B0 03 00 04 07 00 00 05" + - "B3 03 00 52 09 00 00 97 B4 03 00 E4 0A 00 00 03" + - "B6 03 00 50 0C 00 00 7F B7 03 00 CC 0D 00 00 0B" + - "B9 03 00 58 0F 00 00 41 BB 03 00 8E 11 00 00 23" + - "BD 03 00 70 13 00 00 1D BF 03 00 6A 15 00 00 47" + - "C0 03 00 94 16 00 00 FB C1 03 00 48 18 00 00 45" + - "C3 03 00 92 19 00 00 7F C4 03 00 CC 1A 00 00 19" + - "C6 03 00 66 1C 00 00 55 C7 03 00 A2 1D 00 00 9D" + - "C8 03 00 EA 1E 00 00 FB C9 03 00 58 00 00 00 89" + - "CB 03 00 E6 01 00 00 2B CD 03 00 88 03 00 00 8D" + - "CE 03 00 EA 04 00 00 F9 CF 03 00 56 06 00 00 6D" + - "D1 03 00 CA 07 00 00 EF D3 03 00 4C 0A 00 00 1D" + - "D5 03 00 7A 0B 00 00 C9 D6 03 00 26 0D 00 00 C3" + - "D8 03 00 20 0F 00 00 1D DA 03 00 7A 10 00 00 07" + - "DC 03 00 64 12 00 00 61 DD 03 00 BE 13 00 00 E3" + - "DE 03 00 40 15 00 00 29 E0 03 00 86 16 00 00 5B" + - "E2 03 00 B8 18 00 00 B7 E4 03 00 14 1B 00 00 A7" + - "E6 03 00 04 1D 00 00 E5 E8 03 00 42 1F 00 00 AF" + - "EA 03 00 3D 01 00 00 AD EC 03 00 3B 03 00 00 C1" + - "EE 03 00 4F 05 00 00 C7 F0 03 00 55 07 00 00 0B" + - "F3 03 00 99 09 00 00 E9 F4 03 00 77 0B 00 00 ED" + - "F6 03 00 7B 0D 00 00 53 F9 03 00 E1 0F 00 00 5B" + - "FB 03 00 E9 11 00 00 5F FD 03 00 ED 13 00 00 EF" + - "FF 03 00 7D 16 00 00 AF 01 04 00 3D 18 00 00 B9" + - "02 04 00 47 19 00 00 AD 04 04 00 3B 1B 00 00 51" + - "06 04 00 DF 1C 00 00 6F 07 04 00 FD 1D 00 00 69" + - "08 04 00 F7 1E 00 00 E1 09 04 00 52 00 00 00 81" + - "0B 04 00 F2 01 00 00 51 0C 04 00 C2 02 00 00 39" + - "0D 04 00 AA 03 00 00 5D 0E 04 00 CE 04 00 00 BB" + - "0F 04 00 2C 06 00 00 91 10 04 00 02 07 00 00 1D" + - "12 04 00 8E 08 00 00 2D 13 04 00 9E 09 00 00 7B" + - "14 04 00 EC 0A 00 00 1D 16 04 00 8E 0C 00 00 8B" + - "17 04 00 FC 0D 00 00 B5 18 04 00 26 0F 00 00 6D" + - "1A 04 00 DE 10 00 00 8B 1B 04 00 FC 11 00 00 AB" + - "1C 04 00 1C 13 00 00 E7 1D 04 00 58 14 00 00 37" + - "1F 04 00 A8 15 00 00 69 20 04 00 DA 16 00 00 83" + - "21 04 00 F4 17 00 00 8D 22 04 00 FE 18 00 00 E7" + - "23 04 00 58 1A 00 00 B7 25 04 00 28 1C 00 00 29" + - "28 04 00 9A 1E 00 00 97 29 04 00 04 00 00 00 DB" + - "2A 04 00 48 01 00 00 EF 2B 04 00 5C 02 00 00 5B" + - "2D 04 00 C8 03 00 00 71 2E 04 00 DE 04 00 00 BF" + - "2F 04 00 2C 06 00 00 9D 31 04 00 0A 08 00 00 DD" + - "32 04 00 4A 09 00 00 FB 33 04 00 68 0A 00 00 11" + - "36 04 00 7E 0C 00 00 4D 37 04 00 BA 0D 00 00 01" + - "39 04 00 6E 0F 00 00 67 3A 04 00 D4 10 00 00 0D" + - "3C 04 00 7A 12 00 00 A1 3D 04 00 0E 14 00 00 F3" + - "3E 04 00 60 15 00 00 87 40 04 00 F4 16 00 00 83" + - "42 04 00 F0 18 00 00 F7 43 04 00 64 1A 00 00 F7" + - "45 04 00 64 1C 00 00 FB 47 04 00 68 1E 00 00 3D" + - "49 04 00 AA 1F 00 00 39 4B 04 00 92 01 00 00 8B" + - "4C 04 00 E4 02 00 00 97 4E 04 00 F0 04 00 00 5D" + - "50 04 00 B6 06 00 00 19 52 04 00 72 08 00 00 43" + - "53 04 00 9C 09 00 00 FD 54 04 00 56 0B 00 00 FD" + - "55 04 00 56 0C 00 00 4B 57 04 00 A4 0D 00 00 83" + - "58 04 00 DC 0E 00 00 E9 59 04 00 42 10 00 00 47" + - "5B 04 00 A0 11 00 00 B9 5C 04 00 12 13 00 00 5D" + - "5E 04 00 B6 14 00 00 DB 5F 04 00 34 16 00 00 F1" + - "61 04 00 4A 18 00 00 35 64 04 00 8E 1A 00 00 87" + - "66 04 00 E0 1C 00 00 B9 68 04 00 12 1F 00 00 AD" + - "6A 04 00 FA 00 00 00 EB 6C 04 00 38 03 00 00 0B" + - "6F 04 00 58 05 00 00 49 71 04 00 96 07 00 00 11" + - "73 04 00 5E 09 00 00 A5 75 04 00 F2 0B 00 00 89" + - "77 04 00 D6 0D 00 00 C9 79 04 00 16 10 00 00 C5" + - "7A 04 00 12 11 00 00 15 7C 04 00 62 12 00 00 7F" + - "7D 04 00 CC 13 00 00 83 7F 04 00 D0 15 00 00 AB" + - "81 04 00 F8 17 00 00 2D 83 04 00 7A 19 00 00 7B" + - "84 04 00 C8 1A 00 00 CD 85 04 00 1A 1C 00 00 DF" + - "87 04 00 2C 1E 00 00 65 89 04 00 B2 1F 00 00 BF" + - "8B 04 00 0B 02 00 00 25 8E 04 00 71 04 00 00 F5" + - "8F 04 00 41 06 00 00 79 91 04 00 C5 07 00 00 19" + - "93 04 00 65 09 00 00 5D 94 04 00 A9 0A 00 00 4B" + - "96 04 00 97 0C 00 00 B7 97 04 00 03 0E 00 00 37" + - "99 04 00 83 0F 00 00 EB 9A 04 00 37 11 00 00 E3" + - "9B 04 00 2F 12 00 00 BD 9D 04 00 09 14 00 00 C1" + - "9F 04 00 0D 16 00 00 AB A1 04 00 F7 17 00 00 EB" + - "A2 04 00 37 19 00 00 DF A3 04 00 2B 1A 00 00 CB" + - "A4 04 00 17 1B 00 00 93 A5 04 00 DF 1B 00 00 6F" + - "A6 04 00 BB 1C 00 00 59 A7 04 00 A5 1D 00 00 5B" + - "A8 04 00 A7 1E 00 00 47 A9 04 00 93 1F 00 00 4B" + - "AA 04 00 AE 00 00 00 49 AB 04 00 AC 01 00 00 53" + - "AC 04 00 B6 02 00 00 7B AD 04 00 DE 03 00 00 67" + - "AE 04 00 CA 04 00 00 73 AF 04 00 D6 05 00 00 B3" + - "B0 04 00 16 07 00 00 A7 B1 04 00 0A 08 00 00 7B" + - "B2 04 00 DE 08 00 00 C7 B3 04 00 2A 0A 00 00 B3" + - "B4 04 00 16 0B 00 00 EB B5 04 00 4E 0C 00 00 09" + - "B7 04 00 6C 0D 00 00 11 B8 04 00 74 0E 00 00 37" + - "B9 04 00 9A 0F 00 00 41 BA 04 00 A4 10 00 00 A7" + - "BB 04 00 0A 12 00 00 87 BC 04 00 EA 12 00 00 9D" + - "BD 04 00 00 14 00 00 DF BE 04 00 42 15 00 00 C5" + - "BF 04 00 28 16 00 00 A9 C0 04 00 0C 17 00 00 A1" + - "C1 04 00 04 18 00 00 9B C2 04 00 FE 18 00 00 DD" + - "C3 04 00 40 1A 00 00 AF C4 04 00 12 1B 00 00 D1" + - "C5 04 00 34 1C 00 00 F5 C6 04 00 58 1D 00 00 E5" + - "C7 04 00 48 1E 00 00 2F C9 04 00 92 1F 00 00 11" + - "CA 04 00 63 00 00 00 E5 CA 04 00 37 01 00 00 C3" + - "CB 04 00 15 02 00 00 A9 CC 04 00 FB 02 00 00 B1" + - "CD 04 00 03 04 00 00 A1 CE 04 00 F3 04 00 00 8B" + - "CF 04 00 DD 05 00 00 5D D0 04 00 AF 06 00 00 33" + - "D1 04 00 85 07 00 00 39 D2 04 00 8B 08 00 00 27" + - "D3 04 00 79 09 00 00 21 D4 04 00 73 0A 00 00 EF" + - "D4 04 00 41 0B 00 00 C3 D5 04 00 15 0C 00 00 7D" + - "D6 04 00 CF 0C 00 00 3F D7 04 00 91 0D 00 00 5F" + - "D8 04 00 B1 0E 00 00 3D D9 04 00 8F 0F 00 00 0D" + - "DA 04 00 5F 10 00 00 F7 DA 04 00 49 11 00 00 31" + - "DC 04 00 83 12 00 00 B7 DD 04 00 09 14 00 00 ED" + - "DE 04 00 3F 15 00 00 EF DF 04 00 41 16 00 00 D5" + - "E0 04 00 27 17 00 00 AF E1 04 00 01 18 00 00 C7" + - "E2 04 00 19 19 00 00 B7 E3 04 00 09 1A 00 00 A9" + - "E4 04 00 FB 1A 00 00 B7 E5 04 00 09 1C 00 00 C1" + - "E6 04 00 13 1D 00 00 A9 E7 04 00 FB 1D 00 00 AB" + - "E8 04 00 FD 1E 00 00 93 E9 04 00 E5 1F 00 00 75" + - "EA 04 00 CF 00 00 00 3F EB 04 00 99 01 00 00 63" + - "EC 04 00 BD 02 00 00 67 ED 04 00 C1 03 00 00 83" + - "EE 04 00 DD 04 00 00 8F EF 04 00 E9 05 00 00 79" + - "F0 04 00 D3 06 00 00 4F F1 04 00 A9 07 00 00 3F" + - "F2 04 00 99 08 00 00 41 F3 04 00 9B 09 00 00 11" + - "F4 04 00 6B 0A 00 00 27 F5 04 00 81 0B 00 00 21" + - "F6 04 00 7B 0C 00 00 23 F7 04 00 7D 0D 00 00 5F" + - "F8 04 00 B9 0E 00 00 2D F9 04 00 87 0F 00 00 2F" + - "FA 04 00 89 10 00 00 2B FB 04 00 85 11 00 00 4D" + - "FC 04 00 A7 12 00 00 2B FD 04 00 85 13 00 00 2F" + - "FE 04 00 89 14 00 00 4D FF 04 00 A7 15 00 00 59" + - "00 05 00 B3 16 00 00 7D 01 05 00 D7 17 00 00 AD" + - "02 05 00 07 19 00 00 B7 03 05 00 11 1A 00 00 47" + - "05 05 00 A1 1B 00 00 7D 06 05 00 D7 1C 00 00 0F" + - "08 05 00 69 1E 00 00 5D 09 05 00 B7 1F 00 00 9B" + - "0A 05 00 DE 00 00 00 A1 0B 05 00 E4 01 00 00 91" + - "0C 05 00 D4 02 00 00 09 0E 05 00 4C 04 00 00 A7" + - "0F 05 00 EA 05 00 00 FD 10 05 00 40 07 00 00 93" + - "12 05 00 D6 08 00 00 35 14 05 00 78 0A 00 00 63" + - "15 05 00 A6 0B 00 00 97 17 05 00 DA 0D 00 00 B1" + - "19 05 00 F4 0F 00 00 2B 1C 05 00 6E 12 00 00 69" + - "1D 05 00 AC 13 00 00 8D 1E 05 00 D0 14 00 00 D1" + - "1F 05 00 14 16 00 00 FF 20 05 00 42 17 00 00 93" + - "22 05 00 D6 18 00 00 F1 23 05 00 34 1A 00 00 55" + - "25 05 00 98 1B 00 00 83 26 05 00 C6 1C 00 00 BF" + - "27 05 00 02 1E 00 00 13 29 05 00 56 1F 00 00 7D" + - "2A 05 00 B5 00 00 00 F3 2B 05 00 2B 02 00 00 79" + - "2D 05 00 B1 03 00 00 D7 2E 05 00 0F 05 00 00 11" + - "30 05 00 49 06 00 00 19 32 05 00 51 08 00 00 2B" + - "33 05 00 63 09 00 00 33 34 05 00 6B 0A 00 00 AF" + - "35 05 00 E7 0B 00 00 8F 36 05 00 C7 0C 00 00 01" + - "38 05 00 39 0E 00 00 49 39 05 00 81 0F 00 00 AD" + - "3A 05 00 E5 10 00 00 29 3C 05 00 61 12 00 00 0F" + - "3E 05 00 47 14 00 00 99 3F 05 00 D1 15 00 00 79" + - "41 05 00 B1 17 00 00 E7 43 05 00 1F 1A 00 00 D1" + - "46 05 00 09 1D 00 00 29 49 05 00 61 1F 00 00 CF" + - "4B 05 00 EE 01 00 00 F9 4D 05 00 18 04 00 00 E5" + - "50 05 00 04 07 00 00 51 53 05 00 70 09 00 00 C1" + - "55 05 00 E0 0B 00 00 5F 58 05 00 7E 0E 00 00 9D" + - "59 05 00 BC 0F 00 00 8F 5A 05 00 AE 10 00 00 9D" + - "5C 05 00 BC 12 00 00 CB 5D 05 00 EA 13 00 00 8F" + - "5F 05 00 AE 15 00 00 B1 60 05 00 D0 16 00 00 FB" + - "61 05 00 1A 18 00 00 29 63 05 00 48 19 00 00 BD" + - "64 05 00 DC 1A 00 00 67 66 05 00 86 1C 00 00 21" + - "68 05 00 40 1E 00 00 83 69 05 00 A2 1F 00 00 F9" + - "6A 05 00 0B 01 00 00 EB 6C 05 00 FD 02 00 00 B5" + - "6E 05 00 C7 04 00 00 19 70 05 00 2B 06 00 00 11" + - "72 05 00 23 08 00 00 53 73 05 00 65 09 00 00 99" + - "74 05 00 AB 0A 00 00 23 76 05 00 35 0C 00 00 13" + - "78 05 00 25 0E 00 00 91 79 05 00 A3 0F 00 00 E3" + - "7A 05 00 F5 10 00 00 B7 7B 05 00 C9 11 00 00 B7" + - "7C 05 00 C9 12 00 00 B7 7D 05 00 C9 13 00 00 81" + - "7F 05 00 93 15 00 00 E7 80 05 00 F9 16 00 00 67" + - "82 05 00 79 18 00 00 6B 83 05 00 7D 19 00 00 8B" + - "84 05 00 9D 1A 00 00 71 86 05 00 83 1C 00 00 F5" + - "87 05 00 07 1E 00 00 " + - - //Offset=0x0008DB37(580407) recno=160 sid=0x003C size=0x1048(4168) - " 3C 00 48 10 47 8A 05 00 4E" + - "00 00 00 45 8B 05 00 4C 01 00 00 59 8C 05 00 60" + - "02 00 00 91 8D 05 00 98 03 00 00 77 8F 05 00 7E" + - "05 00 00 B9 90 05 00 C0 06 00 00 D3 91 05 00 DA" + - "07 00 00 75 93 05 00 7C 09 00 00 2F 95 05 00 36" + - "0B 00 00 F1 96 05 00 F8 0C 00 00 DB 98 05 00 E2" + - "0E 00 00 3D 9A 05 00 44 10 00 00 41 9C 05 00 48" + - "12 00 00 A1 9D 05 00 A8 13 00 00 F7 9E 05 00 FE" + - "14 00 00 71 A0 05 00 78 16 00 00 11 A2 05 00 18" + - "18 00 00 0F A3 05 00 16 19 00 00 69 A4 05 00 70" + - "1A 00 00 89 A6 05 00 90 1C 00 00 65 A8 05 00 6C" + - "1E 00 00 E3 AA 05 00 CF 00 00 00 AF AC 05 00 9B" + - "02 00 00 91 AE 05 00 7D 04 00 00 B7 B0 05 00 A3" + - "06 00 00 85 B2 05 00 71 08 00 00 D9 B3 05 00 C5" + - "09 00 00 4F B5 05 00 3B 0B 00 00 BD B6 05 00 A9" + - "0C 00 00 AF B8 05 00 9B 0E 00 00 63 BA 05 00 4F" + - "10 00 00 35 BC 05 00 21 12 00 00 5B BD 05 00 47" + - "13 00 00 53 BE 05 00 3F 14 00 00 9F BF 05 00 8B" + - "15 00 00 17 C2 05 00 03 18 00 00 CB C3 05 00 B7" + - "19 00 00 FB C4 05 00 E7 1A 00 00 89 C6 05 00 75" + - "1C 00 00 67 C7 05 00 53 1D 00 00 D7 C8 05 00 C3" + - "1E 00 00 0B CA 05 00 F7 1F 00 00 0D CB 05 00 EB" + - "00 00 00 F7 CB 05 00 D5 01 00 00 03 CD 05 00 E1" + - "02 00 00 13 CE 05 00 F1 03 00 00 33 CF 05 00 11" + - "05 00 00 51 D0 05 00 2F 06 00 00 49 D1 05 00 27" + - "07 00 00 43 D2 05 00 21 08 00 00 63 D4 05 00 41" + - "0A 00 00 93 D5 05 00 71 0B 00 00 C9 D6 05 00 A7" + - "0C 00 00 FF D7 05 00 DD 0D 00 00 73 D9 05 00 51" + - "0F 00 00 27 DB 05 00 05 11 00 00 8B DC 05 00 69" + - "12 00 00 C3 DD 05 00 A1 13 00 00 3F DF 05 00 1D" + - "15 00 00 E5 E0 05 00 C3 16 00 00 FF E1 05 00 DD" + - "17 00 00 29 E3 05 00 07 19 00 00 3F E4 05 00 1D" + - "1A 00 00 15 E5 05 00 F3 1A 00 00 F9 E5 05 00 D7" + - "1B 00 00 C5 E6 05 00 A3 1C 00 00 C9 E7 05 00 A7" + - "1D 00 00 27 E9 05 00 05 1F 00 00 A1 EA 05 00 73" + - "00 00 00 6B EC 05 00 3D 02 00 00 A3 ED 05 00 75" + - "03 00 00 B5 EE 05 00 87 04 00 00 E9 EF 05 00 BB" + - "05 00 00 77 F1 05 00 49 07 00 00 B9 F2 05 00 8B" + - "08 00 00 C5 F4 05 00 97 0A 00 00 0D F6 05 00 DF" + - "0B 00 00 C3 F7 05 00 95 0D 00 00 E5 F9 05 00 B7" + - "0F 00 00 B5 FB 05 00 87 11 00 00 6B FE 05 00 3D" + - "14 00 00 DD 00 06 00 AF 16 00 00 0B 03 06 00 DD" + - "18 00 00 9F 05 06 00 71 1B 00 00 7B 08 06 00 4D" + - "1E 00 00 A7 0A 06 00 62 00 00 00 59 0D 06 00 14" + - "03 00 00 3D 0F 06 00 F8 04 00 00 9B 10 06 00 56" + - "06 00 00 17 12 06 00 D2 07 00 00 6F 13 06 00 2A" + - "09 00 00 59 14 06 00 14 0A 00 00 1F 16 06 00 DA" + - "0B 00 00 49 17 06 00 04 0D 00 00 D1 18 06 00 8C" + - "0E 00 00 C1 1A 06 00 7C 10 00 00 2B 1C 06 00 E6" + - "11 00 00 9F 1D 06 00 5A 13 00 00 77 1F 06 00 32" + - "15 00 00 CD 20 06 00 88 16 00 00 B7 21 06 00 72" + - "17 00 00 9D 22 06 00 58 18 00 00 61 23 06 00 1C" + - "19 00 00 33 24 06 00 EE 19 00 00 67 25 06 00 22" + - "1B 00 00 4F 26 06 00 0A 1C 00 00 3F 27 06 00 FA" + - "1C 00 00 17 28 06 00 D2 1D 00 00 25 29 06 00 E0" + - "1E 00 00 19 2A 06 00 D4 1F 00 00 DF 2A 06 00 96" + - "00 00 00 CF 2B 06 00 86 01 00 00 9D 2C 06 00 54" + - "02 00 00 CD 2D 06 00 84 03 00 00 9F 2E 06 00 56" + - "04 00 00 7F 2F 06 00 36 05 00 00 49 30 06 00 00" + - "06 00 00 21 31 06 00 D8 06 00 00 17 32 06 00 CE" + - "07 00 00 05 33 06 00 BC 08 00 00 FF 33 06 00 B6" + - "09 00 00 DD 34 06 00 94 0A 00 00 B1 35 06 00 68" + - "0B 00 00 99 36 06 00 50 0C 00 00 73 37 06 00 2A" + - "0D 00 00 95 38 06 00 4C 0E 00 00 8D 39 06 00 44" + - "0F 00 00 A9 3A 06 00 60 10 00 00 F3 3B 06 00 AA" + - "11 00 00 19 3D 06 00 D0 12 00 00 2D 3E 06 00 E4" + - "13 00 00 49 3F 06 00 00 15 00 00 FF 40 06 00 B6" + - "16 00 00 9D 42 06 00 54 18 00 00 4D 44 06 00 04" + - "1A 00 00 9B 46 06 00 52 1C 00 00 BF 48 06 00 76" + - "1E 00 00 19 4B 06 00 D9 00 00 00 DB 4D 06 00 9B" + - "03 00 00 53 4F 06 00 13 05 00 00 EB 50 06 00 AB" + - "06 00 00 25 52 06 00 E5 07 00 00 9B 53 06 00 5B" + - "09 00 00 03 55 06 00 C3 0A 00 00 85 56 06 00 45" + - "0C 00 00 E9 58 06 00 A9 0E 00 00 EF 59 06 00 AF" + - "0F 00 00 61 5B 06 00 21 11 00 00 2B 5D 06 00 EB" + - "12 00 00 57 5F 06 00 17 15 00 00 D1 60 06 00 91" + - "16 00 00 15 63 06 00 D5 18 00 00 97 65 06 00 57" + - "1B 00 00 D3 67 06 00 93 1D 00 00 31 69 06 00 F1" + - "1E 00 00 47 6A 06 00 07 20 00 00 FB 6B 06 00 97" + - "01 00 00 43 6D 06 00 DF 02 00 00 7B 6E 06 00 17" + - "04 00 00 39 70 06 00 D5 05 00 00 BD 71 06 00 59" + - "07 00 00 6B 73 06 00 07 09 00 00 95 74 06 00 31" + - "0A 00 00 59 76 06 00 F5 0B 00 00 C7 77 06 00 63" + - "0D 00 00 BF 79 06 00 5B 0F 00 00 AD 7B 06 00 49" + - "11 00 00 9B 7D 06 00 37 13 00 00 FB 7E 06 00 97" + - "14 00 00 2D 81 06 00 C9 16 00 00 5B 82 06 00 F7" + - "17 00 00 D5 83 06 00 71 19 00 00 B1 85 06 00 4D" + - "1B 00 00 73 87 06 00 0F 1D 00 00 29 89 06 00 C5" + - "1E 00 00 AF 8A 06 00 34 00 00 00 C9 8B 06 00 4E" + - "01 00 00 39 8D 06 00 BE 02 00 00 B1 8E 06 00 36" + - "04 00 00 01 90 06 00 86 05 00 00 6D 91 06 00 F2" + - "06 00 00 C7 92 06 00 4C 08 00 00 21 94 06 00 A6" + - "09 00 00 51 95 06 00 D6 0A 00 00 61 96 06 00 E6" + - "0B 00 00 F1 97 06 00 76 0D 00 00 F5 98 06 00 7A" + - "0E 00 00 37 9A 06 00 BC 0F 00 00 79 9B 06 00 FE" + - "10 00 00 09 9D 06 00 8E 12 00 00 DD 9D 06 00 62" + - "13 00 00 1F 9F 06 00 A4 14 00 00 29 A0 06 00 AE" + - "15 00 00 3B A1 06 00 C0 16 00 00 AF A2 06 00 34" + - "18 00 00 E3 A3 06 00 68 19 00 00 3D A5 06 00 C2" + - "1A 00 00 91 A6 06 00 16 1C 00 00 3F A8 06 00 C4" + - "1D 00 00 1B AA 06 00 A0 1F 00 00 1B AB 06 00 8A" + - "00 00 00 63 AC 06 00 D2 01 00 00 75 AD 06 00 E4" + - "02 00 00 91 AE 06 00 00 04 00 00 E7 AF 06 00 56" + - "05 00 00 41 B1 06 00 B0 06 00 00 85 B2 06 00 F4" + - "07 00 00 83 B3 06 00 F2 08 00 00 CD B4 06 00 3C" + - "0A 00 00 B7 B5 06 00 26 0B 00 00 ED B6 06 00 5C" + - "0C 00 00 D9 B7 06 00 48 0D 00 00 B3 B9 06 00 22" + - "0F 00 00 63 BB 06 00 D2 10 00 00 E3 BC 06 00 52" + - "12 00 00 53 BE 06 00 C2 13 00 00 83 BF 06 00 F2" + - "14 00 00 AF C0 06 00 1E 16 00 00 8F C2 06 00 FE" + - "17 00 00 0F C4 06 00 7E 19 00 00 DF C5 06 00 4E" + - "1B 00 00 77 C7 06 00 E6 1C 00 00 D9 C8 06 00 48" + - "1E 00 00 C5 CA 06 00 35 00 00 00 D9 CB 06 00 49" + - "01 00 00 29 CD 06 00 99 02 00 00 F3 CE 06 00 63" + - "04 00 00 0B D1 06 00 7B 06 00 00 45 D2 06 00 B5" + - "07 00 00 59 D4 06 00 C9 09 00 00 87 D6 06 00 F7" + - "0B 00 00 DD D7 06 00 4D 0D 00 00 2D DA 06 00 9D" + - "0F 00 00 2D DC 06 00 9D 11 00 00 B7 DD 06 00 27" + - "13 00 00 09 DF 06 00 79 14 00 00 FB E0 06 00 6B" + - "16 00 00 E9 E2 06 00 59 18 00 00 47 E4 06 00 B7" + - "19 00 00 21 E6 06 00 91 1B 00 00 03 E8 06 00 73" + - "1D 00 00 D1 E9 06 00 41 1F 00 00 45 EC 06 00 95" + - "01 00 00 63 EE 06 00 B3 03 00 00 C9 F1 06 00 19" + - "07 00 00 BD F4 06 00 0D 0A 00 00 57 F7 06 00 A7" + - "0C 00 00 9B FA 06 00 EB 0F 00 00 37 FD 06 00 87" + - "12 00 00 55 FF 06 00 A5 14 00 00 57 01 07 00 A7" + - "16 00 00 D3 03 07 00 23 19 00 00 BF 05 07 00 0F" + - "1B 00 00 1D 07 07 00 6D 1C 00 00 15 08 07 00 65" + - "1D 00 00 1F 09 07 00 6F 1E 00 00 39 0B 07 00 8E" + - "00 00 00 D5 0C 07 00 2A 02 00 00 21 0E 07 00 76" + - "03 00 00 59 10 07 00 AE 05 00 00 43 12 07 00 98" + - "07 00 00 A1 13 07 00 F6 08 00 00 9B 16 07 00 F0" + - "0B 00 00 99 18 07 00 EE 0D 00 00 43 1A 07 00 98" + - "0F 00 00 D3 1C 07 00 28 12 00 00 4B 1E 07 00 A0" + - "13 00 00 E9 1F 07 00 3E 15 00 00 13 21 07 00 68" + - "16 00 00 65 22 07 00 BA 17 00 00 BF 23 07 00 14" + - "19 00 00 77 25 07 00 CC 1A 00 00 11 27 07 00 66" + - "1C 00 00 1B 28 07 00 70 1D 00 00 89 2A 07 00 DE" + - "1F 00 00 07 2C 07 00 61 01 00 00 4D 2E 07 00 A7" + - "03 00 00 41 31 07 00 9B 06 00 00 F1 33 07 00 4B" + - "09 00 00 8B 36 07 00 E5 0B 00 00 15 39 07 00 6F" + - "0E 00 00 17 3B 07 00 71 10 00 00 2B 3E 07 00 85" + - "13 00 00 61 40 07 00 BB 15 00 00 1D 42 07 00 77" + - "17 00 00 29 43 07 00 83 18 00 00 0D 45 07 00 67" + - "1A 00 00 2D 46 07 00 87 1B 00 00 DF 47 07 00 39" + - "1D 00 00 C7 4A 07 00 04 00 00 00 AB 4D 07 00 E8" + - "02 00 00 55 50 07 00 92 05 00 00 C9 52 07 00 06" + - "08 00 00 91 55 07 00 CE 0A 00 00 9F 57 07 00 DC" + - "0C 00 00 8B 59 07 00 C8 0E 00 00 83 5A 07 00 C0" + - "0F 00 00 03 5C 07 00 40 11 00 00 3F 5D 07 00 7C" + - "12 00 00 7B 5E 07 00 B8 13 00 00 EF 5F 07 00 2C" + - "15 00 00 85 61 07 00 C2 16 00 00 2F 63 07 00 6C" + - "18 00 00 BB 65 07 00 F8 1A 00 00 D9 66 07 00 16" + - "1C 00 00 21 68 07 00 5E 1D 00 00 4D 69 07 00 8A" + - "1E 00 00 E3 6A 07 00 04 00 00 00 CF 6B 07 00 F0" + - "00 00 00 6B 6D 07 00 8C 02 00 00 F1 6E 07 00 12" + - "04 00 00 6D 70 07 00 8E 05 00 00 6F 71 07 00 90" + - "06 00 00 9F 72 07 00 C0 07 00 00 55 74 07 00 76" + - "09 00 00 49 76 07 00 6A 0B 00 00 D3 78 07 00 F4" + - "0D 00 00 5F 7A 07 00 80 0F 00 00 A9 7B 07 00 CA" + - "10 00 00 8F 7D 07 00 B0 12 00 00 B5 7F 07 00 D6" + - "14 00 00 F9 81 07 00 1A 17 00 00 57 83 07 00 78" + - "18 00 00 A5 84 07 00 C6 19 00 00 C3 85 07 00 E4" + - "1A 00 00 FB 86 07 00 1C 1C 00 00 01 89 07 00 22" + - "1E 00 00 2B 8A 07 00 4C 1F 00 00 77 8B 07 00 85" + - "00 00 00 AD 8C 07 00 BB 01 00 00 4F 8E 07 00 5D" + - "03 00 00 99 90 07 00 A7 05 00 00 F9 92 07 00 07" + - "08 00 00 AB 94 07 00 B9 09 00 00 33 96 07 00 41" + - "0B 00 00 CF 97 07 00 DD 0C 00 00 19 9A 07 00 27" + - "0F 00 00 31 9B 07 00 3F 10 00 00 BF 9C 07 00 CD" + - "11 00 00 A1 9E 07 00 AF 13 00 00 BF A0 07 00 CD" + - "15 00 00 A3 A2 07 00 B1 17 00 00 95 A4 07 00 A3" + - "19 00 00 95 A6 07 00 A3 1B 00 00 B7 A8 07 00 C5" + - "1D 00 00 9F AA 07 00 AD 1F 00 00 F5 AC 07 00 F2" + - "01 00 00 8F AE 07 00 8C 03 00 00 DB B0 07 00 D8" + - "05 00 00 8D B2 07 00 8A 07 00 00 11 B4 07 00 0E" + - "09 00 00 95 B5 07 00 92 0A 00 00 D3 B7 07 00 D0" + - "0C 00 00 5D B9 07 00 5A 0E 00 00 63 BB 07 00 60" + - "10 00 00 21 BE 07 00 1E 13 00 00 EB BF 07 00 E8" + - "14 00 00 A3 C2 07 00 A0 17 00 00 25 C4 07 00 22" + - "19 00 00 F7 C4 07 00 F4 19 00 00 29 C6 07 00 26" + - "1B 00 00 BD C7 07 00 BA 1C 00 00 61 C9 07 00 5E" + - "1E 00 00 3B CB 07 00 6D 00 00 00 C7 CC 07 00 F9" + - "01 00 00 4D CE 07 00 7F 03 00 00 93 D0 07 00 C5" + - "05 00 00 53 D2 07 00 85 07 00 00 BF D3 07 00 F1" + - "08 00 00 EF D4 07 00 21 0A 00 00 F7 D6 07 00 29" + - "0C 00 00 8F D8 07 00 C1 0D 00 00 DB D9 07 00 0D" + - "0F 00 00 21 DB 07 00 53 10 00 00 59 DC 07 00 8B" + - "11 00 00 25 DE 07 00 57 13 00 00 AB DF 07 00 DD" + - "14 00 00 5B E1 07 00 8D 16 00 00 91 E3 07 00 C3" + - "18 00 00 03 E5 07 00 35 1A 00 00 29 E6 07 00 5B" + - "1B 00 00 41 E7 07 00 73 1C 00 00 87 E8 07 00 B9" + - "1D 00 00 F1 E9 07 00 23 1F 00 00 33 EB 07 00 5E" + - "00 00 00 37 ED 07 00 62 02 00 00 13 EF 07 00 3E" + - "04 00 00 15 F0 07 00 40 05 00 00 13 F1 07 00 3E" + - "06 00 00 39 F2 07 00 64 07 00 00 41 F3 07 00 6C" + - "08 00 00 25 F4 07 00 50 09 00 00 75 F5 07 00 A0" + - "0A 00 00 83 F7 07 00 AE 0C 00 00 AF F9 07 00 DA" + - "0E 00 00 E1 FB 07 00 0C 11 00 00 3B FE 07 00 66" + - "13 00 00 8B FF 07 00 B6 14 00 00 21 01 08 00 4C" + - "16 00 00 89 03 08 00 B4 18 00 00 7D 04 08 00 A8" + - "19 00 00 0F 06 08 00 3A 1B 00 00 9F 07 08 00 CA" + - "1C 00 00 F3 08 08 00 1E 1E 00 00 19 0A 08 00 44" + - "1F 00 00 3D 0C 08 00 59 01 00 00 61 0D 08 00 7D" + - "02 00 00 11 0F 08 00 2D 04 00 00 45 10 08 00 61" + - "05 00 00 9F 11 08 00 BB 06 00 00 65 13 08 00 81" + - "08 00 00 83 15 08 00 9F 0A 00 00 39 17 08 00 55" + - "0C 00 00 0D 1A 08 00 29 0F 00 00 71 1C 08 00 8D" + - "11 00 00 95 1D 08 00 B1 12 00 00 D9 1E 08 00 F5" + - "13 00 00 35 20 08 00 51 15 00 00 99 21 08 00 B5" + - "16 00 00 09 24 08 00 25 19 00 00 3F 25 08 00 5B" + - "1A 00 00 57 26 08 00 73 1B 00 00 49 27 08 00 65" + - "1C 00 00 69 28 08 00 85 1D 00 00 C3 29 08 00 DF" + - "1E 00 00 9D 2B 08 00 D9 00 00 00 09 2D 08 00 45" + - "02 00 00 29 2E 08 00 65 03 00 00 2F 31 08 00 6B" + - "06 00 00 9D 32 08 00 D9 07 00 00 B1 33 08 00 ED" + - "08 00 00 0D 36 08 00 49 0B 00 00 BB 37 08 00 F7" + - "0C 00 00 19 3A 08 00 55 0F 00 00 79 3C 08 00 B5" + - "11 00 00 E1 3D 08 00 1D 13 00 00 6F 3F 08 00 AB" + - "14 00 00 5F 40 08 00 9B 15 00 00 8D 41 08 00 C9" + - "16 00 00 FF 42 08 00 3B 18 00 00 07 44 08 00 43" + - "19 00 00 27 46 08 00 63 1B 00 00 53 47 08 00 8F" + - "1C 00 00 47 48 08 00 83 1D 00 00 53 49 08 00 8F" + - "1E 00 00 61 4A 08 00 9D 1F 00 00 D7 4B 08 00 1E" + - "01 00 00 57 4D 08 00 9E 02 00 00 CB 4E 08 00 12" + - "04 00 00 7D 50 08 00 C4 05 00 00 A9 51 08 00 F0" + - "06 00 00 41 53 08 00 88 08 00 00 ED 54 08 00 34" + - "0A 00 00 17 57 08 00 5E 0C 00 00 91 58 08 00 D8" + - "0D 00 00 B7 59 08 00 FE 0E 00 00 0F 5B 08 00 56" + - "10 00 00 33 5C 08 00 7A 11 00 00 A7 5D 08 00 EE" + - "12 00 00 25 5F 08 00 6C 14 00 00 D5 61 08 00 1C" + - "17 00 00 EB 63 08 00 32 19 00 00 A5 65 08 00 EC" + - "1A 00 00 E1 67 08 00 28 1D 00 00 9F 69 08 00 E6" + - "1E 00 00 DD 6A 08 00 04 00 00 00 6F 6C 08 00 96" + - "01 00 00 B7 6D 08 00 DE 02 00 00 6D 6F 08 00 94" + - "04 00 00 ED 70 08 00 14 06 00 00 5B 72 08 00 82" + - "07 00 00 09 74 08 00 30 09 00 00 43 75 08 00 6A" + - "0A 00 00 77 76 08 00 9E 0B 00 00 7D 77 08 00 A4" + - "0C 00 00 E3 78 08 00 0A 0E 00 00 87 7B 08 00 AE" + - "10 00 00 DF 7C 08 00 06 12 00 00 DF 7D 08 00 06" + - "13 00 00 3F 7F 08 00 66 14 00 00 71 80 08 00 98" + - "15 00 00 8F 81 08 00 B6 16 00 00 EF 82 08 00 16" + - "18 00 00 AB 84 08 00 D2 19 00 00 8D 86 08 00 B4" + - "1B 00 00 B9 87 08 00 E0 1C 00 00 47 89 08 00 6E" + - "1E 00 00 F7 8A 08 00 04 00 00 00 FB 8B 08 00 08" + - "01 00 00 9B 8D 08 00 A8 02 00 00 DF 8E 08 00 EC" + - "03 00 00 DB 8F 08 00 E8 04 00 00 BB 90 08 00 C8" + - "05 00 00 F3 91 08 00 00 07 00 00 43 93 08 00 50" + - "08 00 00 71 94 08 00 7E 09 00 00 5B 96 08 00 68" + - "0B 00 00 A9 97 08 00 B6 0C 00 00 0F 99 08 00 1C" + - "0E 00 00 C5 9A 08 00 D2 0F 00 00 11 9C 08 00 1E" + - "11 00 00 D1 9C 08 00 DE 11 00 00 DD 9D 08 00 EA" + - "12 00 00 73 9F 08 00 80 14 00 00 05 A1 08 00 12" + - "16 00 00 1D A2 08 00 2A 17 00 00 EB A3 08 00 F8" + - "18 00 00 33 A5 08 00 40 1A 00 00 F5 A6 08 00 02" + - "1C 00 00 6B A8 08 00 78 1D 00 00 77 A9 08 00 84" + - "1E 00 00 A5 AB 08 00 CE 00 00 00 99 AD 08 00 C2" + - "02 00 00 ED AF 08 00 16 05 00 00 CB B1 08 00 F4" + - "06 00 00 B9 B3 08 00 E2 08 00 00 4F B5 08 00 78" + - "0A 00 00 67 B6 08 00 90 0B 00 00 DD B7 08 00 06" + - "0D 00 00 67 B9 08 00 90 0E 00 00 C7 BA 08 00 F0" + - "0F 00 00 "; - - - /** - * deep comparison of two SST records - */ - public static void assertEquals(SSTRecord expected, SSTRecord actual){ - assertEquals("number of strings", expected.getNumStrings(), actual.getNumStrings()); - assertEquals("number of unique strings", expected.getNumUniqueStrings(), actual.getNumUniqueStrings()); - assertEquals("count of strings", expected.countStrings(), actual.countStrings()); - for ( int k = 0; k < expected.countStrings(); k++ ) { - UnicodeString us1 = expected.getString(k); - UnicodeString us2 = actual.getString(k); - - assertTrue("String at idx=" + k, us1.equals(us2)); - } - } - - /** - * ExtSSTRecord can be continued. Ensure we properly read the continue remainder. - */ - public void test50967() { - byte[] bytes = HexRead.readFromString(data_50967); - - RecordInputStream in = TestcaseRecordInputStream.create(bytes); - assertEquals(ExtSSTRecord.sid, in.getSid()); - ExtSSTRecord src = new ExtSSTRecord(in); - assertEquals(12386, src.getDataSize()); - ExtSSTRecord.InfoSubRecord[] sub1 = src.getInfoSubRecords(); - - byte[] serialized = src.serialize(); - - in = TestcaseRecordInputStream.create(serialized); - assertEquals(ExtSSTRecord.sid, in.getSid()); - ExtSSTRecord dst = new ExtSSTRecord(in); - assertEquals(12386, dst.getDataSize()); - ExtSSTRecord.InfoSubRecord[] sub2 = src.getInfoSubRecords(); - assertEquals(sub1.length, sub2.length); - - for(int i = 0; i < sub1.length; i++){ - ExtSSTRecord.InfoSubRecord s1 = sub1[i]; - ExtSSTRecord.InfoSubRecord s2 = sub2[i]; - - assertEquals(s1.getBucketSSTOffset(), s2.getBucketSSTOffset()); - assertEquals(s1.getStreamPos(), s2.getStreamPos()); - - } - } - - -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestExtendedFormatRecord.java b/src/testcases/org/apache/poi/hssf/record/TestExtendedFormatRecord.java deleted file mode 100644 index 5ed16ad0f..000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestExtendedFormatRecord.java +++ /dev/null @@ -1,156 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record; - -import junit.framework.TestCase; -/** - */ -public final class TestExtendedFormatRecord extends TestCase { - - private static final byte[] data = new byte[] { - 00, 00, // Font 0 - 00, 00, // Format 0 - 0xF5 - 256, 0xFF - 256, // Cell opts ... - 0x20, 00, // Alignment 20 - 00, 00, // Ident 0 - 00, 00, // Border 0 - 00, 00, // Palette 0 - 00, 00, 00, 00, // ADTL Palette 0 - 0xC0 - 256, 0x20 // Fill Palette 20c0 - }; - - private static ExtendedFormatRecord createEFR() { - return new ExtendedFormatRecord(TestcaseRecordInputStream.create(0x00E0, data)); - } - - public void testLoad() { - ExtendedFormatRecord record = createEFR(); - assertEquals(0, record.getFontIndex()); - assertEquals(0, record.getFormatIndex()); - assertEquals(0xF5 - 256, record.getCellOptions()); - assertEquals(0x20, record.getAlignmentOptions()); - assertEquals(0, record.getIndentionOptions()); - assertEquals(0, record.getBorderOptions()); - assertEquals(0, record.getPaletteOptions()); - assertEquals(0, record.getAdtlPaletteOptions()); - assertEquals(0x20c0, record.getFillPaletteOptions()); - - assertEquals(20 + 4, record.getRecordSize()); - } - - - public void testStore() { -// .fontindex = 0 -// .formatindex = 0 -// .celloptions = fffffff5 -// .islocked = true -// .ishidden = false -// .recordtype= 1 -// .parentidx = fff -// .alignmentoptions= 20 -// .alignment = 0 -// .wraptext = false -// .valignment= 2 -// .justlast = 0 -// .rotation = 0 -// .indentionoptions= 0 -// .indent = 0 -// .shrinktoft= false -// .mergecells= false -// .readngordr= 0 -// .formatflag= false -// .fontflag = false -// .prntalgnmt= false -// .borderflag= false -// .paternflag= false -// .celloption= false -// .borderoptns = 0 -// .lftln = 0 -// .rgtln = 0 -// .topln = 0 -// .btmln = 0 -// .paleteoptns = 0 -// .leftborder= 0 -// .rghtborder= 0 -// .diag = 0 -// .paleteoptn2 = 0 -// .topborder = 0 -// .botmborder= 0 -// .adtldiag = 0 -// .diaglnstyl= 0 -// .fillpattrn= 0 -// .fillpaloptn = 20c0 -// .foreground= 40 -// .background= 41 - - ExtendedFormatRecord record = new ExtendedFormatRecord(); - record.setFontIndex((short) 0); - record.setFormatIndex((short) 0); - - record.setLocked(true); - record.setHidden(false); - record.setXFType((short) 1); - record.setParentIndex((short) 0xfff); - - record.setVerticalAlignment((short) 2); - - record.setFillForeground((short) 0x40); - record.setFillBackground((short) 0x41); - - byte[] recordBytes = record.serialize(); - assertEquals(recordBytes.length - 4, data.length); - for (int i = 0; i < data.length; i++) - assertEquals("At offset " + i, data[i], recordBytes[i + 4]); - } - - public void testCloneOnto() { - ExtendedFormatRecord base = createEFR(); - - ExtendedFormatRecord other = new ExtendedFormatRecord(); - other.cloneStyleFrom(base); - - byte[] recordBytes = other.serialize(); - assertEquals(recordBytes.length - 4, data.length); - for (int i = 0; i < data.length; i++) - assertEquals("At offset " + i, data[i], recordBytes[i + 4]); - } - - public void testRotation() { - ExtendedFormatRecord record = createEFR(); - assertEquals(0, record.getRotation()); - - record.setRotation((short)1); - assertEquals(1, record.getRotation()); - - record.setRotation((short)89); - assertEquals(89, record.getRotation()); - - record.setRotation((short)90); - assertEquals(90, record.getRotation()); - - // internally values below zero are stored differently - record.setRotation((short)-1); - assertEquals(255, record.getRotation()); - - record.setRotation((short)-89); - assertEquals(-77, 90-record.getRotation()); - - record.setRotation((short)-90); - assertEquals(-76, 90-record.getRotation()); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestExternalNameRecord.java b/src/testcases/org/apache/poi/hssf/record/TestExternalNameRecord.java deleted file mode 100644 index 54042ba00..000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestExternalNameRecord.java +++ /dev/null @@ -1,191 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record; - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -import org.apache.poi.util.HexDump; -import org.apache.poi.util.HexRead; -/** - * - * @author Josh Micich - */ -public final class TestExternalNameRecord extends TestCase { - - private static final byte[] dataFDS = { - 0, 0, 0, 0, 0, 0, 3, 0, 70, 68, 83, 0, 0, - }; - - // data taken from bugzilla 44774 att 21790 - private static final byte[] dataAutoDocName = { - -22, 127, 0, 0, 0, 0, 29, 0, 39, 49, 57, 49, 50, 49, 57, 65, 87, 52, 32, 67, 111, 114, - 112, 44, 91, 87, 79, 82, 75, 79, 85, 84, 95, 80, 88, 93, 39, - }; - - // data taken from bugzilla 44774 att 21790 - private static final byte[] dataPlainName = { - 0, 0, 0, 0, 0, 0, 9, 0, 82, 97, 116, 101, 95, 68, 97, 116, 101, 9, 0, 58, 0, 0, 0, 0, 4, 0, 8, 0 - // TODO - the last 2 bytes of formula data (8,0) seem weird. They encode to ConcatPtg, UnknownPtg - // UnknownPtg is otherwise not created by any other test cases - }; - - private static ExternalNameRecord createSimpleENR(byte[] data) { - return new ExternalNameRecord(TestcaseRecordInputStream.create(0x0023, data)); - } - public void testBasicDeserializeReserialize() { - - ExternalNameRecord enr = createSimpleENR(dataFDS); - assertEquals("FDS", enr.getText()); - - try { - TestcaseRecordInputStream.confirmRecordEncoding(0x0023, dataFDS, enr.serialize()); - } catch (ArrayIndexOutOfBoundsException e) { - if(e.getMessage().equals("15")) { - throw new AssertionFailedError("Identified bug 44695"); - } - } - } - - public void testBasicSize() { - ExternalNameRecord enr = createSimpleENR(dataFDS); - if(enr.getRecordSize() == 13) { - throw new AssertionFailedError("Identified bug 44695"); - } - assertEquals(17, enr.getRecordSize()); - - assertNotNull(enr.serialize()); - } - - public void testAutoStdDocName() { - - ExternalNameRecord enr; - try { - enr = createSimpleENR(dataAutoDocName); - } catch (ArrayIndexOutOfBoundsException e) { - if(e.getMessage() == null) { - throw new AssertionFailedError("Identified bug XXXX"); - } - throw e; - } - assertEquals("'191219AW4 Corp,[WORKOUT_PX]'", enr.getText()); - assertTrue(enr.isAutomaticLink()); - assertFalse(enr.isBuiltInName()); - assertFalse(enr.isIconifiedPictureLink()); - assertFalse(enr.isOLELink()); - assertFalse(enr.isPicureLink()); - assertTrue(enr.isStdDocumentNameIdentifier()); - - TestcaseRecordInputStream.confirmRecordEncoding(0x0023, dataAutoDocName, enr.serialize()); - } - - public void testPlainName() { - - ExternalNameRecord enr = createSimpleENR(dataPlainName); - assertEquals("Rate_Date", enr.getText()); - assertFalse(enr.isAutomaticLink()); - assertFalse(enr.isBuiltInName()); - assertFalse(enr.isIconifiedPictureLink()); - assertFalse(enr.isOLELink()); - assertFalse(enr.isPicureLink()); - assertFalse(enr.isStdDocumentNameIdentifier()); - - TestcaseRecordInputStream.confirmRecordEncoding(0x0023, dataPlainName, enr.serialize()); - } - - public void testDDELink_bug47229() { - /** - * Hex dump read directly from text of bugzilla 47229 - */ - final byte[] dataDDE = HexRead.readFromString( - "E2 7F 00 00 00 00 " + - "37 00 " + // text len - // 010672AT0 MUNI,[RTG_MOODY_UNDERLYING,RTG_SP_UNDERLYING] - "30 31 30 36 37 32 41 54 30 20 4D 55 4E 49 2C " + - "5B 52 54 47 5F 4D 4F 4F 44 59 5F 55 4E 44 45 52 4C 59 49 4E 47 2C " + - "52 54 47 5F 53 50 5F 55 4E 44 45 52 4C 59 49 4E 47 5D " + - // constant array { { "#N/A N.A.", "#N/A N.A.", }, } - " 01 00 00 " + - "02 09 00 00 23 4E 2F 41 20 4E 2E 41 2E " + - "02 09 00 00 23 4E 2F 41 20 4E 2E 41 2E"); - ExternalNameRecord enr; - try { - enr = createSimpleENR(dataDDE); - } catch (RecordFormatException e) { - // actual msg reported in bugzilla 47229 is different - // because that seems to be using a version from before svn r646666 - if (e.getMessage().startsWith("Some unread data (is formula present?)")) { - throw new AssertionFailedError("Identified bug 47229 - failed to read ENR with OLE/DDE result data"); - } - throw e; - } - assertEquals("010672AT0 MUNI,[RTG_MOODY_UNDERLYING,RTG_SP_UNDERLYING]", enr.getText()); - - TestcaseRecordInputStream.confirmRecordEncoding(0x0023, dataDDE, enr.serialize()); - } - - public void testUnicodeName_bug47384() { - // data taken from bugzilla 47384 att 23830 at offset 0x13A0 - byte[] dataUN = HexRead.readFromString( - "23 00 22 00" + - "00 00 00 00 00 00 " + - "0C 01 " + - "59 01 61 00 7A 00 65 00 6E 00 ED 00 5F 00 42 00 69 00 6C 00 6C 00 61 00" + - "00 00"); - - RecordInputStream in = TestcaseRecordInputStream.create(dataUN); - ExternalNameRecord enr; - try { - enr = new ExternalNameRecord(in); - } catch (RecordFormatException e) { - if (e.getMessage().startsWith("Expected to find a ContinueRecord in order to read remaining 242 of 268 chars")) { - throw new AssertionFailedError("Identified bug 47384 - failed to read ENR with unicode name"); - } - throw e; - } - assertEquals("\u0159azen\u00ED_Billa", enr.getText()); - byte[] ser = enr.serialize(); - assertEquals(HexDump.toHex(dataUN), HexDump.toHex(ser)); - } - - public void test48339() { - // data taken from bugzilla 48339 - byte[] data = HexRead.readFromString( - "23 00 09 00" + - "F4, FF, 14, 2D, 61, 01, 01, 00, 27"); - - RecordInputStream in = TestcaseRecordInputStream.create(data); - ExternalNameRecord enr = new ExternalNameRecord(in); - byte[] ser = enr.serialize(); - assertEquals(HexDump.toHex(data), HexDump.toHex(ser)); - } - - public void testNPEWithFileFrom49219() { - // the file at test-data/spreadsheet/49219.xls has ExternalNameRecords without actual data, - // we did handle this during reading, but failed during serializing this out, ensure it works now - byte[] data = new byte[] { - 2, 127, 0, 0, 0, 0, - 9, 0, 82, 97, 116, 101, 95, 68, 97, 116, 101}; - - ExternalNameRecord enr = createSimpleENR(data); - - byte[] ser = enr.serialize(); - assertEquals("[23, 00, 11, 00, 02, 7F, 00, 00, 00, 00, 09, 00, 52, 61, 74, 65, 5F, 44, 61, 74, 65]", - HexDump.toHex(ser)); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestFeatRecord.java b/src/testcases/org/apache/poi/hssf/record/TestFeatRecord.java deleted file mode 100644 index dc884000b..000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestFeatRecord.java +++ /dev/null @@ -1,182 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.model.InternalSheet; -import org.apache.poi.hssf.model.InternalWorkbook; -import org.apache.poi.hssf.record.common.FeatFormulaErr2; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFTestHelper; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; - -import junit.framework.TestCase; -/** - * Tests for FeatRecord - * - * @author Josh Micich - */ -public final class TestFeatRecord extends TestCase { - public void testWithoutFeatRecord() throws Exception { - HSSFWorkbook hssf = - HSSFTestDataSamples.openSampleWorkbook("46136-WithWarnings.xls"); - InternalWorkbook wb = HSSFTestHelper.getWorkbookForTest(hssf); - - assertEquals(1, hssf.getNumberOfSheets()); - - int countFR = 0; - int countFRH = 0; - - // Check on the workbook, but shouldn't be there! - for(Record r : wb.getRecords()) { - if(r instanceof FeatRecord) { - countFR++; - } else if (r.getSid() == FeatRecord.sid) { - countFR++; - } - if(r instanceof FeatHdrRecord) { - countFRH++; - } else if (r.getSid() == FeatHdrRecord.sid) { - countFRH++; - } - } - - assertEquals(0, countFR); - assertEquals(0, countFRH); - - // Now check on the sheet - HSSFSheet s = hssf.getSheetAt(0); - InternalSheet sheet = HSSFTestHelper.getSheetForTest(s); - - for(RecordBase rb : sheet.getRecords()) { - if(rb instanceof Record) { - Record r = (Record)rb; - if(r instanceof FeatRecord) { - countFR++; - } else if (r.getSid() == FeatRecord.sid) { - countFR++; - } - if(r instanceof FeatHdrRecord) { - countFRH++; - } else if (r.getSid() == FeatHdrRecord.sid) { - countFRH++; - } - } - } - - assertEquals(0, countFR); - assertEquals(0, countFRH); - } - - public void testReadFeatRecord() throws Exception { - HSSFWorkbook hssf = - HSSFTestDataSamples.openSampleWorkbook("46136-NoWarnings.xls"); - InternalWorkbook wb = HSSFTestHelper.getWorkbookForTest(hssf); - - FeatRecord fr = null; - FeatHdrRecord fhr = null; - - assertEquals(1, hssf.getNumberOfSheets()); - - // First check it isn't on the Workbook - int countFR = 0; - int countFRH = 0; - for(Record r : wb.getRecords()) { - if(r instanceof FeatRecord) { - fr = (FeatRecord)r; - countFR++; - } else if (r.getSid() == FeatRecord.sid) { - fail("FeatRecord SID found but not created correctly!"); - } - if(r instanceof FeatHdrRecord) { - countFRH++; - } else if (r.getSid() == FeatHdrRecord.sid) { - fail("FeatHdrRecord SID found but not created correctly!"); - } - } - - assertEquals(0, countFR); - assertEquals(0, countFRH); - - // Now find it on our sheet - HSSFSheet s = hssf.getSheetAt(0); - InternalSheet sheet = HSSFTestHelper.getSheetForTest(s); - - for(RecordBase rb : sheet.getRecords()) { - if(rb instanceof Record) { - Record r = (Record)rb; - if(r instanceof FeatRecord) { - fr = (FeatRecord)r; - countFR++; - } else if (r.getSid() == FeatRecord.sid) { - countFR++; - } - if(r instanceof FeatHdrRecord) { - fhr = (FeatHdrRecord)r; - countFRH++; - } else if (r.getSid() == FeatHdrRecord.sid) { - countFRH++; - } - } - } - - assertEquals(1, countFR); - assertEquals(1, countFRH); - assertNotNull(fr); - assertNotNull(fhr); - - // Now check the contents are as expected - assertEquals( - FeatHdrRecord.SHAREDFEATURES_ISFFEC2, - fr.getIsf_sharedFeatureType() - ); - - // Applies to one cell only - assertEquals(1, fr.getCellRefs().length); - assertEquals(0, fr.getCellRefs()[0].getFirstRow()); - assertEquals(0, fr.getCellRefs()[0].getLastRow()); - assertEquals(0, fr.getCellRefs()[0].getFirstColumn()); - assertEquals(0, fr.getCellRefs()[0].getLastColumn()); - - // More checking of shared features stuff - assertEquals(4, fr.getCbFeatData()); - assertEquals(4, fr.getSharedFeature().getDataSize()); - assertEquals(FeatFormulaErr2.class, fr.getSharedFeature().getClass()); - - FeatFormulaErr2 fferr2 = (FeatFormulaErr2)fr.getSharedFeature(); - assertEquals(0x04, fferr2._getRawErrorCheckValue()); - - assertFalse(fferr2.getCheckCalculationErrors()); - assertFalse(fferr2.getCheckDateTimeFormats()); - assertFalse(fferr2.getCheckEmptyCellRef()); - assertFalse(fferr2.getCheckInconsistentFormulas()); - assertFalse(fferr2.getCheckInconsistentRanges()); - assertTrue(fferr2.getCheckNumbersAsText()); - assertFalse(fferr2.getCheckUnprotectedFormulas()); - assertFalse(fferr2.getPerformDataValidation()); - } - - /** - * cloning sheets with feat records - */ - public void testCloneSheetWithFeatRecord() throws Exception { - HSSFWorkbook wb = - HSSFTestDataSamples.openSampleWorkbook("46136-WithWarnings.xls"); - wb.cloneSheet(0); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestFontRecord.java b/src/testcases/org/apache/poi/hssf/record/TestFontRecord.java deleted file mode 100644 index 7791df3aa..000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestFontRecord.java +++ /dev/null @@ -1,149 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record; - - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -import org.apache.poi.util.HexRead; - -/** - * Tests the serialization and deserialization of the {@link FontRecord} - * class works correctly. Test data taken directly from a real Excel file. - */ -public final class TestFontRecord extends TestCase { - - private static final int SID = 0x31; - private static final byte[] data = { - 0xC8-256, 00, // font height = xc8 - 00, 00, // attrs = 0 - 0xFF-256, 0x7F, // colour palette = x7fff - 0x90-256, 0x01, // bold weight = x190 - 00, 00, // supersubscript - 00, 00, // underline, family - 00, 00, // charset, padding - 05, 00, // name length, unicode flag - 0x41, 0x72, 0x69, 0x61, 0x6C, // Arial, as unicode - - }; - - public void testLoad() { - - FontRecord record = new FontRecord(TestcaseRecordInputStream.create(0x31, data)); - assertEquals(0xc8, record.getFontHeight()); - assertEquals(0x00, record.getAttributes()); - assertFalse(record.isItalic()); - assertFalse(record.isStruckout()); - assertFalse(record.isMacoutlined()); - assertFalse(record.isMacshadowed()); - assertEquals(0x7fff, record.getColorPaletteIndex()); - assertEquals(0x190, record.getBoldWeight()); - assertEquals(0x00, record.getSuperSubScript()); - assertEquals(0x00, record.getUnderline()); - assertEquals(0x00, record.getFamily()); - assertEquals(0x00, record.getCharset()); - assertEquals("Arial", record.getFontName()); - - assertEquals(21 + 4, record.getRecordSize()); - } - - public void testStore() { -// .fontheight = c8 -// .attributes = 0 -// .italic = false -// .strikout = false -// .macoutlined= false -// .macshadowed= false -// .colorpalette = 7fff -// .boldweight = 190 -// .supersubscript = 0 -// .underline = 0 -// .family = 0 -// .charset = 0 -// .namelength = 5 -// .fontname = Arial - - FontRecord record = new FontRecord(); - record.setFontHeight((short)0xc8); - record.setAttributes((short)0); - record.setColorPaletteIndex((short)0x7fff); - record.setBoldWeight((short)0x190); - record.setSuperSubScript((short)0); - record.setUnderline((byte)0); - record.setFamily((byte)0); - record.setCharset((byte)0); - record.setFontName("Arial"); - - byte [] recordBytes = record.serialize(); - TestcaseRecordInputStream.confirmRecordEncoding(0x31, data, recordBytes); - } - - public void testCloneOnto() { - FontRecord base = new FontRecord(TestcaseRecordInputStream.create(0x31, data)); - - FontRecord other = new FontRecord(); - other.cloneStyleFrom(base); - - byte [] recordBytes = other.serialize(); - assertEquals(recordBytes.length - 4, data.length); - for (int i = 0; i < data.length; i++) - assertEquals("At offset " + i, data[i], recordBytes[i+4]); - } - - public void testSameProperties() { - FontRecord f1 = new FontRecord(TestcaseRecordInputStream.create(0x31, data)); - FontRecord f2 = new FontRecord(TestcaseRecordInputStream.create(0x31, data)); - - assertTrue(f1.sameProperties(f2)); - - f2.setFontName("Arial2"); - assertFalse(f1.sameProperties(f2)); - f2.setFontName("Arial"); - assertTrue(f1.sameProperties(f2)); - - f2.setFontHeight((short)11); - assertFalse(f1.sameProperties(f2)); - f2.setFontHeight((short)0xc8); - assertTrue(f1.sameProperties(f2)); - } - - /** - * Bugzilla 47250 suggests that the unicode options byte should be present even when the name - * length is zero. The OOO documentation seems to agree with this and POI had no test data - * samples to say otherwise. - */ - public void testEmptyName_bug47250() { - byte[] emptyNameData = HexRead.readFromString( - "C8 00 00 00 FF 7F 90 01 00 00 00 00 00 00 " - + "00" // zero length - + "00" // unicode options byte - ); - - RecordInputStream in = TestcaseRecordInputStream.create(SID, emptyNameData); - FontRecord fr = new FontRecord(in); - if (in.available() == 1) { - throw new AssertionFailedError("Identified bug 47250"); - } - assertEquals(0, in.available()); - - assertEquals(0, fr.getFontName().length()); - byte[] recordBytes = fr.serialize(); - TestcaseRecordInputStream.confirmRecordEncoding(SID, emptyNameData, recordBytes); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestFormulaRecord.java b/src/testcases/org/apache/poi/hssf/record/TestFormulaRecord.java deleted file mode 100644 index 2f6a14b76..000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestFormulaRecord.java +++ /dev/null @@ -1,193 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record; - -import org.apache.poi.ss.formula.ptg.AttrPtg; -import org.apache.poi.ss.formula.ptg.FuncVarPtg; -import org.apache.poi.ss.formula.ptg.IntPtg; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.apache.poi.ss.formula.ptg.RefPtg; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.FormulaError; - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -/** - * Tests for {@link FormulaRecord} - * - * @author Andrew C. Oliver - */ -public final class TestFormulaRecord extends TestCase { - - public void testCreateFormulaRecord () { - FormulaRecord record = new FormulaRecord(); - record.setColumn((short)0); - record.setRow(1); - record.setXFIndex((short)4); - - assertEquals(record.getColumn(),0); - assertEquals(record.getRow(), 1); - assertEquals(record.getXFIndex(),4); - } - - /** - * Make sure a NAN value is preserved - * This formula record is a representation of =1/0 at row 0, column 0 - */ - public void testCheckNanPreserve() { - byte[] formulaByte = { - 0, 0, 0, 0, - 0x0F, 0x00, - - // 8 bytes cached number is a 'special value' in this case - 0x02, // special cached value type 'error' - 0x00, - FormulaError.DIV0.getCode(), - 0x00, - 0x00, - 0x00, - (byte)0xFF, - (byte)0xFF, - - 0x00, - 0x00, - 0x00, - 0x00, - - (byte)0xE0, //18 - (byte)0xFC, - // Ptgs - 0x07, 0x00, // encoded length - 0x1E, 0x01, 0x00, // IntPtg(1) - 0x1E, 0x00, 0x00, // IntPtg(0) - 0x06, // DividePtg - - }; - - FormulaRecord record = new FormulaRecord(TestcaseRecordInputStream.create(FormulaRecord.sid, formulaByte)); - assertEquals("Row", 0, record.getRow()); - assertEquals("Column", 0, record.getColumn()); - assertEquals(CellType.ERROR.getCode(), record.getCachedResultType()); - - byte[] output = record.serialize(); - assertEquals("Output size", 33, output.length); //includes sid+recordlength - - for (int i = 5; i < 13;i++) { - assertEquals("FormulaByte NaN doesn't match", formulaByte[i], output[i+4]); - } - } - - /** - * Tests to see if the shared formula cells properly reserialize the expPtg - * - */ - public void testExpFormula() { - byte[] formulaByte = new byte[27]; - - formulaByte[4] =(byte)0x0F; - formulaByte[14]=(byte)0x08; - formulaByte[18]=(byte)0xE0; - formulaByte[19]=(byte)0xFD; - formulaByte[20]=(byte)0x05; - formulaByte[22]=(byte)0x01; - FormulaRecord record = new FormulaRecord(TestcaseRecordInputStream.create(FormulaRecord.sid, formulaByte)); - assertEquals("Row", 0, record.getRow()); - assertEquals("Column", 0, record.getColumn()); - byte[] output = record.serialize(); - assertEquals("Output size", 31, output.length); //includes sid+recordlength - assertEquals("Offset 22", 1, output[26]); - } - - public void testWithConcat() { - // =CHOOSE(2,A2,A3,A4) - byte[] data = { - 1, 0, 1, 0, 15, 0, 0, 0, 0, 0, 0, 0, 57, - 64, 0, 0, 12, 0, 12, -4, 46, 0, - 30, 2, 0, // Int - 2 - 25, 4, 3, 0, // Attr - 8, 0, 17, 0, 26, 0, // jumpTable - 35, 0, // chooseOffset - 36, 1, 0, 0, -64, // Ref - A2 - 25, 8, 21, 0, // Attr - 36, 2, 0, 0, -64, // Ref - A3 - 25, 8, 12, 0, // Attr - 36, 3, 0, 0, -64, // Ref - A4 - 25, 8, 3, 0, // Attr - 66, 4, 100, 0 // CHOOSE - }; - RecordInputStream inp = TestcaseRecordInputStream.create(FormatRecord.sid, data); - - FormulaRecord fr = new FormulaRecord(inp); - - Ptg[] ptgs = fr.getParsedExpression(); - assertEquals(9, ptgs.length); - assertEquals(IntPtg.class, ptgs[0].getClass()); - assertEquals(AttrPtg.class, ptgs[1].getClass()); - assertEquals(RefPtg.class, ptgs[2].getClass()); - assertEquals(AttrPtg.class, ptgs[3].getClass()); - assertEquals(RefPtg.class, ptgs[4].getClass()); - assertEquals(AttrPtg.class, ptgs[5].getClass()); - assertEquals(RefPtg.class, ptgs[6].getClass()); - assertEquals(AttrPtg.class, ptgs[7].getClass()); - assertEquals(FuncVarPtg.class, ptgs[8].getClass()); - - FuncVarPtg choose = (FuncVarPtg)ptgs[8]; - assertEquals("CHOOSE", choose.getName()); - } - - public void testReserialize() { - FormulaRecord formulaRecord = new FormulaRecord(); - formulaRecord.setRow(1); - formulaRecord.setColumn((short) 1); - formulaRecord.setParsedExpression(new Ptg[] { new RefPtg("B$5"), }); - formulaRecord.setValue(3.3); - byte[] ser = formulaRecord.serialize(); - assertEquals(31, ser.length); - - RecordInputStream in = TestcaseRecordInputStream.create(ser); - FormulaRecord fr2 = new FormulaRecord(in); - assertEquals(3.3, fr2.getValue(), 0.0); - Ptg[] ptgs = fr2.getParsedExpression(); - assertEquals(1, ptgs.length); - RefPtg rp = (RefPtg) ptgs[0]; - assertEquals("B$5", rp.toFormulaString()); - } - - /** - * Bug noticed while fixing 46479. Operands of conditional operator ( ? : ) were swapped - * inside {@link FormulaRecord} - */ - public void testCachedValue_bug46479() { - FormulaRecord fr0 = new FormulaRecord(); - FormulaRecord fr1 = new FormulaRecord(); - // test some other cached value types - fr0.setValue(3.5); - assertEquals(3.5, fr0.getValue(), 0.0); - fr0.setCachedResultErrorCode(FormulaError.REF.getCode()); - assertEquals(FormulaError.REF.getCode(), fr0.getCachedErrorValue()); - - fr0.setCachedResultBoolean(false); - fr1.setCachedResultBoolean(true); - if (fr0.getCachedBooleanValue() == true && fr1.getCachedBooleanValue() == false) { - throw new AssertionFailedError("Identified bug 46479c"); - } - assertEquals(false, fr0.getCachedBooleanValue()); - assertEquals(true, fr1.getCachedBooleanValue()); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestFtCblsSubRecord.java b/src/testcases/org/apache/poi/hssf/record/TestFtCblsSubRecord.java deleted file mode 100644 index 382307234..000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestFtCblsSubRecord.java +++ /dev/null @@ -1,65 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record; - - -import static org.junit.Assert.assertArrayEquals; -import junit.framework.TestCase; - -/** - * Tests the serialization and deserialization of the FtCblsSubRecord - * class works correctly. - * - * @author Yegor Kozlov - */ -public final class TestFtCblsSubRecord extends TestCase { - private final byte[] data = new byte[] { - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x64, 0x00, - 0x01, 0x00, 0x0A, 0x00, 0x00, 0x00, 0x10, 0x00, 0x01, 0x00 - }; - - public void testRead() { - - FtCblsSubRecord record = new FtCblsSubRecord(TestcaseRecordInputStream.create(FtCblsSubRecord.sid, data), data.length); - - assertEquals(FtCblsSubRecord.sid, record.getSid()); - assertEquals(data.length, record.getDataSize()); - } - - public void testWrite() { - FtCblsSubRecord record = new FtCblsSubRecord(); - assertEquals(FtCblsSubRecord.sid, record.getSid()); - assertEquals(data.length, record.getDataSize()); - - byte [] ser = record.serialize(); - assertEquals(ser.length - 4, data.length); - - } - - public void testClone() - { - FtCblsSubRecord record = new FtCblsSubRecord(); - byte[] src = record.serialize(); - - FtCblsSubRecord cloned = record.clone(); - byte[] cln = cloned.serialize(); - - assertEquals(record.getDataSize(), cloned.getDataSize()); - assertArrayEquals(src, cln); - } -} \ No newline at end of file diff --git a/src/testcases/org/apache/poi/hssf/record/TestHyperlinkRecord.java b/src/testcases/org/apache/poi/hssf/record/TestHyperlinkRecord.java deleted file mode 100644 index 2379a29db..000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestHyperlinkRecord.java +++ /dev/null @@ -1,543 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hssf.record; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.fail; - -import org.apache.poi.hssf.record.HyperlinkRecord.GUID; -import org.apache.poi.util.HexDump; -import org.apache.poi.util.HexRead; -import org.apache.poi.util.LittleEndianByteArrayInputStream; -import org.apache.poi.util.LittleEndianByteArrayOutputStream; -import org.junit.Test; - -/** - * Test HyperlinkRecord - */ -public final class TestHyperlinkRecord { - - //link to http://www.lakings.com/ - private static final byte[] data1 = { - 0x02, 0x00, //First row of the hyperlink - 0x02, 0x00, //Last row of the hyperlink - 0x00, 0x00, //First column of the hyperlink - 0x00, 0x00, //Last column of the hyperlink - - //16-byte GUID. Seems to be always the same. Does not depend on the hyperlink type - (byte)0xD0, (byte)0xC9, (byte)0xEA, 0x79, (byte)0xF9, (byte)0xBA, (byte)0xCE, 0x11, - (byte)0x8C, (byte)0x82, 0x00, (byte)0xAA, 0x00, 0x4B, (byte)0xA9, 0x0B, - - 0x02, 0x00, 0x00, 0x00, //integer, always 2 - - // flags. Define the type of the hyperlink: - // HyperlinkRecord.HLINK_URL | HyperlinkRecord.HLINK_ABS | HyperlinkRecord.HLINK_LABEL - 0x17, 0x00, 0x00, 0x00, - - 0x08, 0x00, 0x00, 0x00, //length of the label including the trailing '\0' - - //label: - 0x4D, 0x00, 0x79, 0x00, 0x20, 0x00, 0x4C, 0x00, 0x69, 0x00, 0x6E, 0x00, 0x6B, 0x00, 0x00, 0x00, - - //16-byte link moniker: HyperlinkRecord.URL_MONIKER - (byte)0xE0, (byte)0xC9, (byte)0xEA, 0x79, (byte)0xF9, (byte)0xBA, (byte)0xCE, 0x11, - (byte)0x8C, (byte)0x82, 0x00, (byte)0xAA, 0x00, 0x4B, (byte)0xA9, 0x0B, - - //count of bytes in the address including the tail - 0x48, 0x00, 0x00, 0x00, //integer - - //the actual link, terminated by '\u0000' - 0x68, 0x00, 0x74, 0x00, 0x74, 0x00, 0x70, 0x00, 0x3A, 0x00, 0x2F, 0x00, - 0x2F, 0x00, 0x77, 0x00, 0x77, 0x00, 0x77, 0x00, 0x2E, 0x00, 0x6C, 0x00, - 0x61, 0x00, 0x6B, 0x00, 0x69, 0x00, 0x6E, 0x00, 0x67, 0x00, 0x73, 0x00, - 0x2E, 0x00, 0x63, 0x00, 0x6F, 0x00, 0x6D, 0x00, 0x2F, 0x00, 0x00, 0x00, - - //standard 24-byte tail of a URL link. Seems to always be the same for all URL HLINKs - 0x79, 0x58, (byte)0x81, (byte)0xF4, 0x3B, 0x1D, 0x7F, 0x48, (byte)0xAF, 0x2C, - (byte)0x82, 0x5D, (byte)0xC4, (byte)0x85, 0x27, 0x63, 0x00, 0x00, 0x00, - 0x00, (byte)0xA5, (byte)0xAB, 0x00, 0x00 - }; - - //link to a file in the current directory: link1.xls - private static final byte[] data2 = { - 0x00, 0x00, - 0x00, 0x00, - 0x00, 0x00, - 0x00, 0x00, - //16-bit GUID. Seems to be always the same. Does not depend on the hyperlink type - (byte)0xD0, (byte)0xC9, (byte)0xEA, 0x79, (byte)0xF9, (byte)0xBA, (byte)0xCE, 0x11, - (byte)0x8C, (byte)0x82, 0x00, (byte)0xAA, 0x00, 0x4B, (byte)0xA9, 0x0B, - - 0x02, 0x00, 0x00, 0x00, //integer, always 2 - - 0x15, 0x00, 0x00, 0x00, //options: HyperlinkRecord.HLINK_URL | HyperlinkRecord.HLINK_LABEL - - 0x05, 0x00, 0x00, 0x00, //length of the label - //label - 0x66, 0x00, 0x69, 0x00, 0x6C, 0x00, 0x65, 0x00, 0x00, 0x00, - - //16-byte link moniker: HyperlinkRecord.FILE_MONIKER - 0x03, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, (byte)0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46, - - 0x00, 0x00, //level - 0x0A, 0x00, 0x00, 0x00, //length of the path ) - - //path to the file (plain ISO-8859 bytes, NOT UTF-16LE!) - 0x6C, 0x69, 0x6E, 0x6B, 0x31, 0x2E, 0x78, 0x6C, 0x73, 0x00, - - //standard 24-byte tail of a file link - (byte)0xFF, (byte)0xFF, (byte)0xAD, (byte)0xDE, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, - - 0x00, 0x00, 0x00, 0x00, // length of address link field - }; - - // mailto:ebgans@mail.ru?subject=Hello,%20Ebgans! - private static final byte[] data3 = { - 0x01, 0x00, - 0x01, 0x00, - 0x00, 0x00, - 0x00, 0x00, - - //16-bit GUID. Seems to be always the same. Does not depend on the hyperlink type - (byte)0xD0, (byte)0xC9, (byte)0xEA, 0x79, (byte)0xF9, (byte)0xBA, (byte)0xCE, 0x11, - (byte)0x8C, (byte)0x82, 0x00, (byte)0xAA, 0x00, 0x4B, (byte)0xA9, 0x0B, - - 0x02, 0x00, 0x00, 0x00, //integer, always 2 - - 0x17, 0x00, 0x00, 0x00, //options: HyperlinkRecord.HLINK_URL | HyperlinkRecord.HLINK_ABS | HyperlinkRecord.HLINK_LABEL - - 0x06, 0x00, 0x00, 0x00, //length of the label - 0x65, 0x00, 0x6D, 0x00, 0x61, 0x00, 0x69, 0x00, 0x6C, 0x00, 0x00, 0x00, //label - - //16-byte link moniker: HyperlinkRecord.URL_MONIKER - (byte)0xE0, (byte)0xC9, (byte)0xEA, 0x79, (byte)0xF9, (byte)0xBA, (byte)0xCE, 0x11, - (byte)0x8C, (byte)0x82, 0x00, (byte)0xAA, 0x00, 0x4B, (byte)0xA9, 0x0B, - - //length of the address including the tail. - 0x76, 0x00, 0x00, 0x00, - - //the address is terminated by '\u0000' - 0x6D, 0x00, 0x61, 0x00, 0x69, 0x00, 0x6C, 0x00, 0x74, 0x00, 0x6F, 0x00, - 0x3A, 0x00, 0x65, 0x00, 0x62, 0x00, 0x67, 0x00, 0x61, 0x00, 0x6E, 0x00, - 0x73, 0x00, 0x40, 0x00, 0x6D, 0x00, 0x61, 0x00, 0x69, 0x00, 0x6C, 0x00, - 0x2E, 0x00, 0x72, 0x00, 0x75, 0x00, 0x3F, 0x00, 0x73, 0x00, 0x75, 0x00, - 0x62, 0x00, 0x6A, 0x00, 0x65, 0x00, 0x63, 0x00, 0x74, 0x00, 0x3D, 0x00, - 0x48, 0x00, 0x65, 0x00, 0x6C, 0x00, 0x6C, 0x00, 0x6F, 0x00, 0x2C, 0x00, - 0x25, 0x00, 0x32, 0x00, 0x30, 0x00, 0x45, 0x00, 0x62, 0x00, 0x67, 0x00, - 0x61, 0x00, 0x6E, 0x00, 0x73, 0x00, 0x21, 0x00, 0x00, 0x00, - - //standard 24-byte tail of a URL link - 0x79, 0x58, (byte)0x81, (byte)0xF4, 0x3B, 0x1D, 0x7F, 0x48, (byte)0xAF, (byte)0x2C, - (byte)0x82, 0x5D, (byte)0xC4, (byte)0x85, 0x27, 0x63, 0x00, 0x00, 0x00, - 0x00, (byte)0xA5, (byte)0xAB, 0x00, 0x00 - }; - - //link to a place in worksheet: Sheet1!A1 - private static final byte[] data4 = { - 0x03, 0x00, - 0x03, 0x00, - 0x00, 0x00, - 0x00, 0x00, - - //16-bit GUID. Seems to be always the same. Does not depend on the hyperlink type - (byte)0xD0, (byte)0xC9, (byte)0xEA, 0x79, (byte)0xF9, (byte)0xBA, (byte)0xCE, 0x11, - (byte)0x8C, (byte)0x82, 0x00, (byte)0xAA, 0x00, 0x4B, (byte)0xA9, 0x0B, - - 0x02, 0x00, 0x00, 0x00, //integer, always 2 - - 0x1C, 0x00, 0x00, 0x00, //flags: HyperlinkRecord.HLINK_LABEL | HyperlinkRecord.HLINK_PLACE - - 0x06, 0x00, 0x00, 0x00, //length of the label - - 0x70, 0x00, 0x6C, 0x00, 0x61, 0x00, 0x63, 0x00, 0x65, 0x00, 0x00, 0x00, //label - - 0x0A, 0x00, 0x00, 0x00, //length of the document link including trailing zero - - //link: Sheet1!A1 - 0x53, 0x00, 0x68, 0x00, 0x65, 0x00, 0x65, 0x00, 0x74, 0x00, 0x31, 0x00, 0x21, - 0x00, 0x41, 0x00, 0x31, 0x00, 0x00, 0x00 - }; - - private static final byte[] dataLinkToWorkbook = HexRead.readFromString( - "01 00 01 00 01 00 01 00 " + - "D0 C9 EA 79 F9 BA CE 11 8C 82 00 AA 00 4B A9 0B " + - "02 00 00 00 " + - "1D 00 00 00 " + // options: LABEL | PLACE | FILE_OR_URL - // label: "My Label" - "09 00 00 00 " + - "4D 00 79 00 20 00 4C 00 61 00 62 00 65 00 6C 00 00 00 " + - "03 03 00 00 00 00 00 00 C0 00 00 00 00 00 00 46 " + // file GUID - "00 00 " + // file options - // shortFileName: "YEARFR~1.XLS" - "0D 00 00 00 " + - "59 45 41 52 46 52 7E 31 2E 58 4C 53 00 " + - // FILE_TAIL - unknown byte sequence - "FF FF AD DE 00 00 00 00 " + - "00 00 00 00 00 00 00 00 " + - "00 00 00 00 00 00 00 00 " + - // field len, char data len - "2E 00 00 00 " + - "28 00 00 00 " + - "03 00 " + // unknown ushort - // _address: "yearfracExamples.xls" - "79 00 65 00 61 00 72 00 66 00 72 00 61 00 63 00 " + - "45 00 78 00 61 00 6D 00 70 00 6C 00 65 00 73 00 " + - "2E 00 78 00 6C 00 73 00 " + - // textMark: "Sheet1!B6" - "0A 00 00 00 " + - "53 00 68 00 65 00 65 00 74 00 31 00 21 00 42 00 " + - "36 00 00 00" - ); - - private static final byte[] dataTargetFrame = HexRead.readFromString( - "0E 00 0E 00 00 00 00 00 " + - "D0 C9 EA 79 F9 BA CE 11 8C 82 00 AA 00 4B A9 0B " + - "02 00 00 00 " + - "83 00 00 00 " + // options: TARGET_FRAME | ABS | FILE_OR_URL - // targetFrame: "_blank" - "07 00 00 00 " + - "5F 00 62 00 6C 00 61 00 6E 00 6B 00 00 00 " + - // url GUID - "E0 C9 EA 79 F9 BA CE 11 8C 82 00 AA 00 4B A9 0B " + - // address: "http://www.regnow.com/softsell/nph-softsell.cgi?currency=USD&item=7924-37" - "94 00 00 00 " + - "68 00 74 00 74 00 70 00 3A 00 2F 00 2F 00 77 00 " + - "77 00 77 00 2E 00 72 00 65 00 67 00 6E 00 6F 00 " + - "77 00 2E 00 63 00 6F 00 6D 00 2F 00 73 00 6F 00 " + - "66 00 74 00 73 00 65 00 6C 00 6C 00 2F 00 6E 00 " + - "70 00 68 00 2D 00 73 00 6F 00 66 00 74 00 73 00 " + - "65 00 6C 00 6C 00 2E 00 63 00 67 00 69 00 3F 00 " + - "63 00 75 00 72 00 72 00 65 00 6E 00 63 00 79 00 " + - "3D 00 55 00 53 00 44 00 26 00 69 00 74 00 65 00 " + - "6D 00 3D 00 37 00 39 00 32 00 34 00 2D 00 33 00 " + - "37 00 00 00" - ); - - - private static final byte[] dataUNC = HexRead.readFromString( - "01 00 01 00 01 00 01 00 " + - "D0 C9 EA 79 F9 BA CE 11 8C 82 00 AA 00 4B A9 0B " + - "02 00 00 00 " + - "1F 01 00 00 " + // options: UNC_PATH | LABEL | TEXT_MARK | ABS | FILE_OR_URL - "09 00 00 00 " + // label: "My Label" - "4D 00 79 00 20 00 6C 00 61 00 62 00 65 00 6C 00 00 00 " + - // note - no moniker GUID - "27 00 00 00 " + // "\\\\MyServer\\my-share\\myDir\\PRODNAME.xls" - "5C 00 5C 00 4D 00 79 00 53 00 65 00 72 00 76 00 " + - "65 00 72 00 5C 00 6D 00 79 00 2D 00 73 00 68 00 " + - "61 00 72 00 65 00 5C 00 6D 00 79 00 44 00 69 00 " + - "72 00 5C 00 50 00 52 00 4F 00 44 00 4E 00 41 00 " + - "4D 00 45 00 2E 00 78 00 6C 00 73 00 00 00 " + - - "0C 00 00 00 " + // textMark: PRODNAME!C2 - "50 00 52 00 4F 00 44 00 4E 00 41 00 4D 00 45 00 21 00 " + - "43 00 32 00 00 00" - ); - - - /** - * From Bugzilla 47498 - */ - private static byte[] data_47498 = { - 0x02, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, (byte)0xD0, (byte)0xC9, - (byte)0xEA, 0x79, (byte)0xF9, (byte)0xBA, (byte)0xCE, 0x11, (byte)0x8C, - (byte)0x82, 0x00, (byte)0xAA, 0x00, 0x4B, (byte)0xA9, 0x0B, 0x02, 0x00, - 0x00, 0x00, 0x15, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x50, 0x00, - 0x44, 0x00, 0x46, 0x00, 0x00, 0x00, (byte)0xE0, (byte)0xC9, (byte)0xEA, - 0x79, (byte)0xF9, (byte)0xBA, (byte)0xCE, (byte)0x11, (byte)0x8C, (byte)0x82, - 0x00, (byte)0xAA, 0x00, 0x4B, (byte)0xA9, 0x0B, 0x28, 0x00, 0x00, 0x00, - 0x74, 0x00, 0x65, 0x00, 0x73, 0x00, 0x74, 0x00, 0x66, 0x00, 0x6F, 0x00, - 0x6C, 0x00, 0x64, 0x00, 0x65, 0x00, 0x72, 0x00, 0x2F, 0x00, 0x74, 0x00, - 0x65, 0x00, 0x73, 0x00, 0x74, 0x00, 0x2E, 0x00, 0x50, 0x00, 0x44, 0x00, - 0x46, 0x00, 0x00, 0x00 - }; - - - private void confirmGUID(GUID expectedGuid, GUID actualGuid) { - assertEquals(expectedGuid, actualGuid); - } - - @Test - public void testReadURLLink(){ - RecordInputStream is = TestcaseRecordInputStream.create(HyperlinkRecord.sid, data1); - HyperlinkRecord link = new HyperlinkRecord(is); - assertEquals(2, link.getFirstRow()); - assertEquals(2, link.getLastRow()); - assertEquals(0, link.getFirstColumn()); - assertEquals(0, link.getLastColumn()); - confirmGUID(HyperlinkRecord.STD_MONIKER, link.getGuid()); - confirmGUID(HyperlinkRecord.URL_MONIKER, link.getMoniker()); - assertEquals(2, link.getLabelOptions()); - int opts = HyperlinkRecord.HLINK_URL | HyperlinkRecord.HLINK_ABS | HyperlinkRecord.HLINK_LABEL; - assertEquals(0x17, opts); - assertEquals(opts, link.getLinkOptions()); - assertEquals(0, link.getFileOptions()); - - assertEquals("My Link", link.getLabel()); - assertEquals("http://www.lakings.com/", link.getAddress()); - } - - @Test - public void testReadFileLink(){ - RecordInputStream is = TestcaseRecordInputStream.create(HyperlinkRecord.sid, data2); - HyperlinkRecord link = new HyperlinkRecord(is); - assertEquals(0, link.getFirstRow()); - assertEquals(0, link.getLastRow()); - assertEquals(0, link.getFirstColumn()); - assertEquals(0, link.getLastColumn()); - confirmGUID(HyperlinkRecord.STD_MONIKER, link.getGuid()); - confirmGUID(HyperlinkRecord.FILE_MONIKER, link.getMoniker()); - assertEquals(2, link.getLabelOptions()); - int opts = HyperlinkRecord.HLINK_URL | HyperlinkRecord.HLINK_LABEL; - assertEquals(0x15, opts); - assertEquals(opts, link.getLinkOptions()); - - assertEquals("file", link.getLabel()); - assertEquals("link1.xls", link.getShortFilename()); - assertEquals("link1.xls", link.getAddress()); - } - - @Test - public void testReadEmailLink(){ - RecordInputStream is = TestcaseRecordInputStream.create(HyperlinkRecord.sid, data3); - HyperlinkRecord link = new HyperlinkRecord(is); - assertEquals(1, link.getFirstRow()); - assertEquals(1, link.getLastRow()); - assertEquals(0, link.getFirstColumn()); - assertEquals(0, link.getLastColumn()); - confirmGUID(HyperlinkRecord.STD_MONIKER, link.getGuid()); - confirmGUID(HyperlinkRecord.URL_MONIKER, link.getMoniker()); - assertEquals(2, link.getLabelOptions()); - int opts = HyperlinkRecord.HLINK_URL | HyperlinkRecord.HLINK_ABS | HyperlinkRecord.HLINK_LABEL; - assertEquals(0x17, opts); - assertEquals(opts, link.getLinkOptions()); - - assertEquals("email", link.getLabel()); - assertEquals("mailto:ebgans@mail.ru?subject=Hello,%20Ebgans!", link.getAddress()); - } - - @Test - public void testReadDocumentLink(){ - RecordInputStream is = TestcaseRecordInputStream.create(HyperlinkRecord.sid, data4); - HyperlinkRecord link = new HyperlinkRecord(is); - assertEquals(3, link.getFirstRow()); - assertEquals(3, link.getLastRow()); - assertEquals(0, link.getFirstColumn()); - assertEquals(0, link.getLastColumn()); - confirmGUID(HyperlinkRecord.STD_MONIKER, link.getGuid()); - assertEquals(2, link.getLabelOptions()); - int opts = HyperlinkRecord.HLINK_LABEL | HyperlinkRecord.HLINK_PLACE; - assertEquals(0x1C, opts); - assertEquals(opts, link.getLinkOptions()); - - assertEquals("place", link.getLabel()); - assertEquals("Sheet1!A1", link.getTextMark()); - assertEquals("Sheet1!A1", link.getAddress()); - } - - private void serialize(byte[] data){ - RecordInputStream is = TestcaseRecordInputStream.create(HyperlinkRecord.sid, data); - HyperlinkRecord link = new HyperlinkRecord(is); - byte[] bytes1 = link.serialize(); - is = TestcaseRecordInputStream.create(bytes1); - link = new HyperlinkRecord(is); - byte[] bytes2 = link.serialize(); - assertEquals(bytes1.length, bytes2.length); - assertArrayEquals(bytes1, bytes2); - } - - @Test - public void testSerialize(){ - serialize(data1); - serialize(data2); - serialize(data3); - serialize(data4); - } - - @Test - public void testCreateURLRecord() { - HyperlinkRecord link = new HyperlinkRecord(); - link.newUrlLink(); - link.setFirstRow((short)2); - link.setLastRow((short)2); - link.setLabel("My Link"); - link.setAddress("http://www.lakings.com/"); - - byte[] tmp = link.serialize(); - byte[] ser = new byte[tmp.length-4]; - System.arraycopy(tmp, 4, ser, 0, ser.length); - assertEquals(data1.length, ser.length); - assertArrayEquals(data1, ser); - } - - @Test - public void testCreateFileRecord() { - HyperlinkRecord link = new HyperlinkRecord(); - link.newFileLink(); - link.setFirstRow((short)0); - link.setLastRow((short)0); - link.setLabel("file"); - link.setShortFilename("link1.xls"); - - byte[] tmp = link.serialize(); - byte[] ser = new byte[tmp.length-4]; - System.arraycopy(tmp, 4, ser, 0, ser.length); - assertEquals(data2.length, ser.length); - assertArrayEquals(data2, ser); - } - - @Test - public void testCreateDocumentRecord() { - HyperlinkRecord link = new HyperlinkRecord(); - link.newDocumentLink(); - link.setFirstRow((short)3); - link.setLastRow((short)3); - link.setLabel("place"); - link.setTextMark("Sheet1!A1"); - - byte[] tmp = link.serialize(); - byte[] ser = new byte[tmp.length-4]; - System.arraycopy(tmp, 4, ser, 0, ser.length); - assertEquals(data4.length, ser.length); - assertArrayEquals(data4, ser); - } - - @Test - public void testCreateEmailtRecord() { - HyperlinkRecord link = new HyperlinkRecord(); - link.newUrlLink(); - link.setFirstRow((short)1); - link.setLastRow((short)1); - link.setLabel("email"); - link.setAddress("mailto:ebgans@mail.ru?subject=Hello,%20Ebgans!"); - - byte[] tmp = link.serialize(); - byte[] ser = new byte[tmp.length-4]; - System.arraycopy(tmp, 4, ser, 0, ser.length); - assertEquals(data3.length, ser.length); - assertArrayEquals(data3, ser); - } - - @Test - public void testClone() { - byte[][] data = {data1, data2, data3, data4}; - for (final byte[] d : data) { - RecordInputStream is = TestcaseRecordInputStream.create(HyperlinkRecord.sid, d); - HyperlinkRecord link = new HyperlinkRecord(is); - HyperlinkRecord clone = link.clone(); - assertArrayEquals(link.serialize(), clone.serialize()); - } - - } - - @Test - public void testReserializeTargetFrame() { - RecordInputStream in = TestcaseRecordInputStream.create(HyperlinkRecord.sid, dataTargetFrame); - HyperlinkRecord hr = new HyperlinkRecord(in); - byte[] ser = hr.serialize(); - TestcaseRecordInputStream.confirmRecordEncoding(HyperlinkRecord.sid, dataTargetFrame, ser); - } - - @Test - public void testReserializeLinkToWorkbook() { - - RecordInputStream in = TestcaseRecordInputStream.create(HyperlinkRecord.sid, dataLinkToWorkbook); - HyperlinkRecord hr = new HyperlinkRecord(in); - byte[] ser = hr.serialize(); - TestcaseRecordInputStream.confirmRecordEncoding(HyperlinkRecord.sid, dataLinkToWorkbook, ser); - assertNotEquals("Identified bug in reading workbook link", "YEARFR~1.XLS", hr.getAddress()); - assertEquals("yearfracExamples.xls", hr.getAddress()); - } - - @Test - public void testReserializeUNC() { - - RecordInputStream in = TestcaseRecordInputStream.create(HyperlinkRecord.sid, dataUNC); - HyperlinkRecord hr = new HyperlinkRecord(in); - byte[] ser = hr.serialize(); - TestcaseRecordInputStream.confirmRecordEncoding(HyperlinkRecord.sid, dataUNC, ser); - try { - hr.toString(); - } catch (NullPointerException e) { - fail("Identified bug with option URL and UNC set at same time"); - } - } - - @Test - public void testGUID() { - GUID g; - g = GUID.parse("3F2504E0-4F89-11D3-9A0C-0305E82C3301"); - confirmGUID(g, 0x3F2504E0, 0x4F89, 0x11D3, 0x9A0C0305E82C3301L); - assertEquals("3F2504E0-4F89-11D3-9A0C-0305E82C3301", g.formatAsString()); - - g = GUID.parse("13579BDF-0246-8ACE-0123-456789ABCDEF"); - confirmGUID(g, 0x13579BDF, 0x0246, 0x8ACE, 0x0123456789ABCDEFL); - assertEquals("13579BDF-0246-8ACE-0123-456789ABCDEF", g.formatAsString()); - - byte[] buf = new byte[16]; - g.serialize(new LittleEndianByteArrayOutputStream(buf, 0)); - String expectedDump = "[DF, 9B, 57, 13, 46, 02, CE, 8A, 01, 23, 45, 67, 89, AB, CD, EF]"; - assertEquals(expectedDump, HexDump.toHex(buf)); - - // STD Moniker - g = createFromStreamDump("[D0, C9, EA, 79, F9, BA, CE, 11, 8C, 82, 00, AA, 00, 4B, A9, 0B]"); - assertEquals("79EAC9D0-BAF9-11CE-8C82-00AA004BA90B", g.formatAsString()); - // URL Moniker - g = createFromStreamDump("[E0, C9, EA, 79, F9, BA, CE, 11, 8C, 82, 00, AA, 00, 4B, A9, 0B]"); - assertEquals("79EAC9E0-BAF9-11CE-8C82-00AA004BA90B", g.formatAsString()); - // File Moniker - g = createFromStreamDump("[03, 03, 00, 00, 00, 00, 00, 00, C0, 00, 00, 00, 00, 00, 00, 46]"); - assertEquals("00000303-0000-0000-C000-000000000046", g.formatAsString()); - } - - private static GUID createFromStreamDump(String s) { - return new GUID(new LittleEndianByteArrayInputStream(HexRead.readFromString(s))); - } - - private void confirmGUID(GUID g, int d1, int d2, int d3, long d4) { - assertEquals(HexDump.intToHex(d1), HexDump.intToHex(g.getD1())); - assertEquals(HexDump.shortToHex(d2), HexDump.shortToHex(g.getD2())); - assertEquals(HexDump.shortToHex(d3), HexDump.shortToHex(g.getD3())); - assertEquals(HexDump.longToHex(d4), HexDump.longToHex(g.getD4())); - } - - @Test - public void test47498(){ - RecordInputStream is = TestcaseRecordInputStream.create(HyperlinkRecord.sid, data_47498); - HyperlinkRecord link = new HyperlinkRecord(is); - assertEquals(2, link.getFirstRow()); - assertEquals(2, link.getLastRow()); - assertEquals(0, link.getFirstColumn()); - assertEquals(0, link.getLastColumn()); - confirmGUID(HyperlinkRecord.STD_MONIKER, link.getGuid()); - confirmGUID(HyperlinkRecord.URL_MONIKER, link.getMoniker()); - assertEquals(2, link.getLabelOptions()); - int opts = HyperlinkRecord.HLINK_URL | HyperlinkRecord.HLINK_LABEL; - assertEquals(opts, link.getLinkOptions()); - assertEquals(0, link.getFileOptions()); - - assertEquals("PDF", link.getLabel()); - assertEquals("testfolder/test.PDF", link.getAddress()); - - byte[] ser = link.serialize(); - TestcaseRecordInputStream.confirmRecordEncoding(HyperlinkRecord.sid, data_47498, ser); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestInterfaceEndRecord.java b/src/testcases/org/apache/poi/hssf/record/TestInterfaceEndRecord.java deleted file mode 100644 index 528f8e364..000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestInterfaceEndRecord.java +++ /dev/null @@ -1,59 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record; - - -import junit.framework.TestCase; -import org.apache.poi.util.HexRead; -import org.apache.poi.util.HexDump; -import java.util.List; -import java.io.ByteArrayInputStream; - -/** - * Tests the serialization and deserialization of the EndSubRecord - * class works correctly. Test data taken directly from a real - * Excel file. - * - * @author Yegor Kozlov - */ -public final class TestInterfaceEndRecord extends TestCase { - - public void testCreate() { - InterfaceEndRecord record = InterfaceEndRecord.instance; - assertEquals(0, record.getDataSize()); - } - - /** - * Silently swallow unexpected contents in InterfaceEndRecord. - * Although it violates the spec, Excel silently converts this - * data to an {@link InterfaceHdrRecord}. - */ - public void testUnexpectedBytes_bug47251(){ - String hex = "" + - "09 08 10 00 00 06 05 00 EC 15 CD 07 C1 C0 00 00 06 03 00 00 " + //BOF - "E2 00 02 00 B0 04 " + //INTERFACEEND with extra two bytes - "0A 00 00 00"; // EOF - byte[] data = HexRead.readFromString(hex); - List records = RecordFactory.createRecords(new ByteArrayInputStream(data)); - assertEquals(3, records.size()); - Record rec1 = records.get(1); - assertEquals(InterfaceHdrRecord.class, rec1.getClass()); - InterfaceHdrRecord r = (InterfaceHdrRecord)rec1; - assertEquals("[E1, 00, 02, 00, B0, 04]", HexDump.toHex(r.serialize())); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestLabelRecord.java b/src/testcases/org/apache/poi/hssf/record/TestLabelRecord.java deleted file mode 100644 index 10f363652..000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestLabelRecord.java +++ /dev/null @@ -1,41 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; -/** - * Tests for LabelRecord - * - * @author Josh Micich - */ -public final class TestLabelRecord extends TestCase { - - public void testEmptyString() { - HSSFWorkbook wb; - try { - wb = HSSFTestDataSamples.openSampleWorkbook("ex42570-20305.xls"); - } catch (NullPointerException e) { - throw new AssertionFailedError("Identified bug 42570"); - } - HSSFTestDataSamples.writeOutAndReadBack(wb); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestLbsDataSubRecord.java b/src/testcases/org/apache/poi/hssf/record/TestLbsDataSubRecord.java deleted file mode 100644 index 0f5354840..000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestLbsDataSubRecord.java +++ /dev/null @@ -1,178 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record; - - -import static org.junit.Assert.assertArrayEquals; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -import junit.framework.TestCase; - -import org.apache.poi.ss.formula.ptg.AreaPtg; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.util.HexRead; -import org.apache.poi.util.LittleEndianInputStream; -import org.apache.poi.util.LittleEndianOutputStream; - -/** - * Tests the serialization and deserialization of the LbsDataSubRecord class works correctly. - * - * @author Yegor Kozlov - */ -public final class TestLbsDataSubRecord extends TestCase { - - /** - * test read-write round trip - * test data was taken from 47701.xls - */ - public void test_47701(){ - byte[] data = HexRead.readFromString( - "15, 00, 12, 00, 12, 00, 02, 00, 11, 20, " + - "00, 00, 00, 00, 80, 3D, 03, 05, 00, 00, " + - "00, 00, 0C, 00, 14, 00, 00, 00, 00, 00, " + - "00, 00, 00, 00, 00, 00, 01, 00, 0A, 00, " + - "00, 00, 10, 00, 01, 00, 13, 00, EE, 1F, " + - "10, 00, 09, 00, 40, 9F, 74, 01, 25, 09, " + - "00, 0C, 00, 07, 00, 07, 00, 07, 04, 00, " + - "00, 00, 08, 00, 00, 00"); - RecordInputStream in = TestcaseRecordInputStream.create(ObjRecord.sid, data); - // check read OK - ObjRecord record = new ObjRecord(in); - assertEquals(3, record.getSubRecords().size()); - SubRecord sr = record.getSubRecords().get(2); - assertTrue(sr instanceof LbsDataSubRecord); - LbsDataSubRecord lbs = (LbsDataSubRecord)sr; - assertEquals(4, lbs.getNumberOfItems()); - - assertTrue(lbs.getFormula() instanceof AreaPtg); - AreaPtg ptg = (AreaPtg)lbs.getFormula(); - CellRangeAddress range = new CellRangeAddress( - ptg.getFirstRow(), ptg.getLastRow(), ptg.getFirstColumn(), ptg.getLastColumn()); - assertEquals("H10:H13", range.formatAsString()); - - // check that it re-serializes to the same data - byte[] ser = record.serialize(); - TestcaseRecordInputStream.confirmRecordEncoding(ObjRecord.sid, data, ser); - } - - /** - * test data was taken from the file attached to Bugzilla 45778 - */ - public void test_45778(){ - byte[] data = HexRead.readFromString( - "15, 00, 12, 00, 14, 00, 01, 00, 01, 00, " + - "01, 21, 00, 00, 3C, 13, F4, 03, 00, 00, " + - "00, 00, 0C, 00, 14, 00, 00, 00, 00, 00, " + - "00, 00, 00, 00, 00, 00, 01, 00, 08, 00, 00, " + - "00, 10, 00, 00, 00, " + - "13, 00, EE, 1F, " + - "00, 00, " + - "08, 00, " + //number of items - "08, 00, " + //selected item - "01, 03, " + //flags - "00, 00, " + //objId - //LbsDropData - "0A, 00, " + //flags - "14, 00, " + //the number of lines to be displayed in the dropdown - "6C, 00, " + //the smallest width in pixels allowed for the dropdown window - "00, 00, " + //num chars - "00, 00"); - RecordInputStream in = TestcaseRecordInputStream.create(ObjRecord.sid, data); - // check read OK - ObjRecord record = new ObjRecord(in); - - SubRecord sr = record.getSubRecords().get(2); - assertTrue(sr instanceof LbsDataSubRecord); - LbsDataSubRecord lbs = (LbsDataSubRecord)sr; - assertEquals(8, lbs.getNumberOfItems()); - assertNull(lbs.getFormula()); - - // check that it re-serializes to the same data - byte[] ser = record.serialize(); - TestcaseRecordInputStream.confirmRecordEncoding(ObjRecord.sid, data, ser); - - } - - /** - * Test data produced by OpenOffice 3.1 by opening and saving 47701.xls - * There are 5 padding bytes that are removed by POI - */ - public void test_remove_padding(){ - byte[] data = HexRead.readFromString( - "5D, 00, 4C, 00, " + - "15, 00, 12, 00, 12, 00, 01, 00, 11, 00, " + - "00, 00, 00, 00, 00, 00, 00, 00, 00, 00, " + - "00, 00, 0C, 00, 14, 00, 00, 00, 00, 00, " + - "00, 00, 00, 00, 00, 00, 01, 00, 09, 00, " + - "00, 00, 0F, 00, 01, 00, " + - "13, 00, 1B, 00, " + - "10, 00, " + //next 16 bytes is a ptg aray - "09, 00, 00, 00, 00, 00, 25, 09, 00, 0C, 00, 07, 00, 07, 00, 00, " + - "01, 00, " + //num lines - "00, 00, " + //selected - "08, 00, " + - "00, 00, " + - "00, 00, 00, 00, 00"); //padding bytes - - RecordInputStream in = TestcaseRecordInputStream.create(data); - // check read OK - ObjRecord record = new ObjRecord(in); - // check that it re-serializes to the same data - byte[] ser = record.serialize(); - - assertEquals(data.length-5, ser.length); - for(int i=0; i < ser.length; i++) assertEquals(data[i],ser[i]); - - //check we can read the trimmed record - RecordInputStream in2 = TestcaseRecordInputStream.create(ser); - ObjRecord record2 = new ObjRecord(in2); - byte[] ser2 = record2.serialize(); - assertArrayEquals(ser, ser2); - } - - public void test_LbsDropData() throws IOException{ - byte[] data = HexRead.readFromString( - //LbsDropData - "0A, 00, " + //flags - "14, 00, " + //the number of lines to be displayed in the dropdown - "6C, 00, " + //the smallest width in pixels allowed for the dropdown window - "00, 00, " + //num chars - "00, " + //compression flag - "00"); //padding byte - - LittleEndianInputStream in = new LittleEndianInputStream(new ByteArrayInputStream(data)); - try { - LbsDataSubRecord.LbsDropData lbs = new LbsDataSubRecord.LbsDropData(in); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - LittleEndianOutputStream out = new LittleEndianOutputStream(baos); - try { - lbs.serialize(out); - - assertArrayEquals(data, baos.toByteArray()); - } finally { - out.close(); - } - } finally { - in.close(); - } - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestMergeCellsRecord.java b/src/testcases/org/apache/poi/hssf/record/TestMergeCellsRecord.java deleted file mode 100644 index d7d05ab45..000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestMergeCellsRecord.java +++ /dev/null @@ -1,81 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record; - -import java.util.ArrayList; -import java.util.List; - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -import org.apache.poi.hssf.model.RecordStream; -import org.apache.poi.hssf.record.aggregates.MergedCellsTable; -import org.apache.poi.hssf.record.aggregates.RecordAggregate.RecordVisitor; -import org.apache.poi.ss.util.CellRangeAddress; - - -/** - * Make sure the merge cells record behaves - * @author Danny Mui (dmui at apache dot org) - * - */ -public final class TestMergeCellsRecord extends TestCase { - - /** - * Make sure when a clone is called, we actually clone it. - */ - public void testCloneReferences() { - CellRangeAddress[] cras = { new CellRangeAddress(0, 1, 0, 2), }; - MergeCellsRecord merge = new MergeCellsRecord(cras, 0, cras.length); - MergeCellsRecord clone = merge.clone(); - - assertNotSame("Merged and cloned objects are the same", merge, clone); - - CellRangeAddress mergeRegion = merge.getAreaAt(0); - CellRangeAddress cloneRegion = clone.getAreaAt(0); - assertNotSame("Should not point to same objects when cloning", mergeRegion, cloneRegion); - assertEquals("New Clone Row From doesnt match", mergeRegion.getFirstRow(), cloneRegion.getFirstRow()); - assertEquals("New Clone Row To doesnt match", mergeRegion.getLastRow(), cloneRegion.getLastRow()); - assertEquals("New Clone Col From doesnt match", mergeRegion.getFirstColumn(), cloneRegion.getFirstColumn()); - assertEquals("New Clone Col To doesnt match", mergeRegion.getLastColumn(), cloneRegion.getLastColumn()); - - assertFalse(merge.getAreaAt(0) == clone.getAreaAt(0)); - } - - private static final RecordVisitor dummyRecordVisitor = new RecordVisitor() { - @Override - public void visitRecord(Record r) { - // do nothing - } - }; - public void testMCTable_bug46009() { - MergedCellsTable mct = new MergedCellsTable(); - List recList = new ArrayList(); - CellRangeAddress[] cras = new CellRangeAddress[] { - new CellRangeAddress(0, 0, 0, 3), - }; - recList.add(new MergeCellsRecord(cras, 0, 1)); - RecordStream rs = new RecordStream(recList, 0); - mct.read(rs); - try { - mct.visitContainedRecords(dummyRecordVisitor); - } catch (ArrayStoreException e) { - throw new AssertionFailedError("Identified bug 46009"); - } - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestNameCommentRecord.java b/src/testcases/org/apache/poi/hssf/record/TestNameCommentRecord.java deleted file mode 100644 index f7a29eb46..000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestNameCommentRecord.java +++ /dev/null @@ -1,42 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record; - -import junit.framework.TestCase; - -import org.apache.poi.util.HexRead; - -/** - * Tests the NameCommentRecord serializes/deserializes correctly - * - * @author Andrew Shirley (aks at corefiling.co.uk) - */ -public final class TestNameCommentRecord extends TestCase { - public void testReserialize() { - final byte[] data = HexRead - .readFromString("" - + "94 08 00 00 00 00 00 00 00 00 00 00 04 00 07 00 00 6E 61 6D 65 00 63 6F 6D 6D 65 6E 74]"); - final RecordInputStream in = TestcaseRecordInputStream.create(NameCommentRecord.sid, data); - final NameCommentRecord ncr = new NameCommentRecord(in); - assertEquals(0x0894, ncr.getRecordType()); - assertEquals("name", ncr.getNameText()); - assertEquals("comment", ncr.getCommentText()); - final byte[] data2 = ncr.serialize(); - TestcaseRecordInputStream.confirmRecordEncoding(NameCommentRecord.sid, data, data2); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestNameRecord.java b/src/testcases/org/apache/poi/hssf/record/TestNameRecord.java deleted file mode 100644 index 231b6c92c..000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestNameRecord.java +++ /dev/null @@ -1,717 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record; - -import java.io.IOException; - -import junit.framework.TestCase; - -import org.apache.poi.hssf.usermodel.HSSFName; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.ptg.Area3DPtg; -import org.apache.poi.ss.formula.ptg.ArrayPtg; -import org.apache.poi.ss.formula.ptg.NamePtg; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.apache.poi.ss.formula.ptg.Ref3DPtg; -import org.apache.poi.util.HexRead; - -/** - * Tests the NameRecord serializes/deserializes correctly - * - * @author Danny Mui (dmui at apache dot org) - */ -public final class TestNameRecord extends TestCase { - - /** - * Makes sure that additional name information is parsed properly such as menu/description - */ - public void testFillExtras() { - - byte[] examples = HexRead.readFromString("" - + "88 03 67 06 07 00 00 00 00 00 00 23 00 00 00 4D " - + "61 63 72 6F 31 3A 01 00 00 00 11 00 00 4D 61 63 " - + "72 6F 20 72 65 63 6F 72 64 65 64 20 32 37 2D 53 " - + "65 70 2D 39 33 20 62 79 20 41 4C 4C 57 4F 52"); - - NameRecord name = new NameRecord(TestcaseRecordInputStream.create(NameRecord.sid, examples)); - String description = name.getDescriptionText(); - assertNotNull(description); - assertTrue(description.endsWith("Macro recorded 27-Sep-93 by ALLWOR")); - } - - public void testReserialize() { - byte[] data = HexRead - .readFromString("" - + "20 00 00 01 0B 00 00 00 01 00 00 00 00 00 00 06 3B 00 00 00 00 02 00 00 00 09 00]"); - RecordInputStream in = TestcaseRecordInputStream.create(NameRecord.sid, data); - NameRecord nr = new NameRecord(in); - assertEquals(0x0020, nr.getOptionFlag()); - byte[] data2 = nr.serialize(); - TestcaseRecordInputStream.confirmRecordEncoding(NameRecord.sid, data, data2); - } - - public void testFormulaRelAbs_bug46174() throws IOException { - // perhaps this testcase belongs on TestHSSFName - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFName name = wb.createName(); - wb.createSheet("Sheet1"); - name.setNameName("test"); - name.setRefersToFormula("Sheet1!$B$3"); - if (name.getRefersToFormula().equals("Sheet1!B3")) { - fail("Identified bug 46174"); - } - assertEquals("Sheet1!$B$3", name.getRefersToFormula()); - wb.close(); - } - - public void testFormulaGeneral() throws IOException { - // perhaps this testcase belongs on TestHSSFName - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFName name = wb.createName(); - wb.createSheet("Sheet1"); - name.setNameName("test"); - name.setRefersToFormula("Sheet1!A1+Sheet1!A2"); - assertEquals("Sheet1!A1+Sheet1!A2", name.getRefersToFormula()); - name.setRefersToFormula("5*6"); - assertEquals("5*6", name.getRefersToFormula()); - - wb.close(); - } - - /** - * A NameRecord followed by a ContinueRecord. See Bugzilla 50244 - */ - public void test50244(){ - String record_0x0018 = - " 18 00 " + - "21 1E 00 00 00 11 08 00 00 00 03 00 00 00 00 00 " + - "00 77 44 61 74 61 47 72 75 70 70 65 53 65 72 69 " + - "65 2E 60 00 B7 02 0C 00 57 03 00 B7 02 02 09 00 " + - "00 31 2E 54 32 30 2E 30 30 31 02 09 00 00 31 2E " + - "54 32 30 2E 30 30 31 02 09 00 00 31 2E 54 32 30 " + - "2E 30 30 31 02 09 00 00 31 2E 54 32 30 2E 30 30 " + - "32 02 09 00 00 31 2E 54 32 30 2E 30 30 32 02 09 " + - "00 00 31 2E 54 32 30 2E 30 30 32 02 09 00 00 31 " + - "2E 54 32 30 2E 30 30 33 02 09 00 00 31 2E 54 32 " + - "30 2E 30 30 33 02 09 00 00 31 2E 54 32 30 2E 30 " + - "30 33 02 09 00 00 31 2E 54 32 30 2E 30 31 33 02 " + - "09 00 00 31 2E 54 32 30 2E 30 31 33 02 09 00 00 " + - "31 2E 54 32 30 2E 30 31 33 02 09 00 00 31 2E 54 " + - "32 30 2E 30 31 34 02 09 00 00 31 2E 54 32 30 2E " + - "30 31 34 02 09 00 00 31 2E 54 32 30 2E 30 31 34 " + - "02 09 00 00 31 2E 54 32 30 2E 30 31 35 02 09 00 " + - "00 31 2E 54 32 30 2E 30 31 35 02 09 00 00 31 2E " + - "54 32 30 2E 30 31 35 02 09 00 00 31 2E 54 32 30 " + - "2E 30 32 35 02 09 00 00 31 2E 54 32 30 2E 30 32 " + - "35 02 09 00 00 31 2E 54 32 30 2E 30 32 35 02 09 " + - "00 00 31 2E 54 32 30 2E 30 32 36 02 09 00 00 31 " + - "2E 54 32 30 2E 30 32 36 02 09 00 00 31 2E 54 32 " + - "30 2E 30 32 36 02 09 00 00 31 2E 54 32 30 2E 30 " + - "32 37 02 09 00 00 31 2E 54 32 30 2E 30 32 37 02 " + - "09 00 00 31 2E 54 32 30 2E 30 32 37 02 09 00 00 " + - "31 2E 54 32 30 2E 30 33 37 02 09 00 00 31 2E 54 " + - "32 30 2E 30 33 37 02 09 00 00 31 2E 54 32 30 2E " + - "30 33 37 02 09 00 00 31 2E 54 32 30 2E 30 33 38 " + - "02 09 00 00 31 2E 54 32 30 2E 30 33 38 02 09 00 " + - "00 31 2E 54 32 30 2E 30 33 38 02 09 00 00 31 2E " + - "54 32 30 2E 30 33 39 02 09 00 00 31 2E 54 32 30 " + - "2E 30 33 39 02 09 00 00 31 2E 54 32 30 2E 30 33 " + - "39 02 09 00 00 31 2E 54 32 30 2E 30 34 39 02 09 " + - "00 00 31 2E 54 32 30 2E 30 34 39 02 09 00 00 31 " + - "2E 54 32 30 2E 30 34 39 02 09 00 00 31 2E 54 32 " + - "30 2E 30 35 30 02 09 00 00 31 2E 54 32 30 2E 30 " + - "35 30 02 09 00 00 31 2E 54 32 30 2E 30 35 30 02 " + - "09 00 00 31 2E 54 32 30 2E 30 35 31 02 09 00 00 " + - "31 2E 54 32 30 2E 30 35 31 02 09 00 00 31 2E 54 " + - "32 30 2E 30 35 31 02 09 00 00 31 2E 54 32 30 2E " + - "30 36 31 02 09 00 00 31 2E 54 32 30 2E 30 36 31 " + - "02 09 00 00 31 2E 54 32 30 2E 30 36 31 02 09 00 " + - "00 31 2E 54 32 30 2E 30 36 32 02 09 00 00 31 2E " + - "54 32 30 2E 30 36 32 02 09 00 00 31 2E 54 32 30 " + - "2E 30 36 32 02 09 00 00 31 2E 54 32 30 2E 30 36 " + - "33 02 09 00 00 31 2E 54 32 30 2E 30 36 33 02 09 " + - "00 00 31 2E 54 32 30 2E 30 36 33 02 09 00 00 31 " + - "2E 54 32 30 2E 30 37 33 02 09 00 00 31 2E 54 32 " + - "30 2E 30 37 33 02 09 00 00 31 2E 54 32 30 2E 30 " + - "37 33 02 09 00 00 31 2E 54 32 30 2E 30 37 34 02 " + - "09 00 00 31 2E 54 32 30 2E 30 37 34 02 09 00 00 " + - "31 2E 54 32 30 2E 30 37 34 02 09 00 00 31 2E 54 " + - "32 30 2E 30 37 35 02 09 00 00 31 2E 54 32 30 2E " + - "30 37 35 02 09 00 00 31 2E 54 32 30 2E 30 37 35 " + - "02 09 00 00 31 2E 54 32 30 2E 30 38 35 02 09 00 " + - "00 31 2E 54 32 30 2E 30 38 35 02 09 00 00 31 2E " + - "54 32 30 2E 30 38 35 02 09 00 00 31 2E 54 32 30 " + - "2E 30 38 36 02 09 00 00 31 2E 54 32 30 2E 30 38 " + - "36 02 09 00 00 31 2E 54 32 30 2E 30 38 36 02 09 " + - "00 00 31 2E 54 32 30 2E 30 38 37 02 09 00 00 31 " + - "2E 54 32 30 2E 30 38 37 02 09 00 00 31 2E 54 32 " + - "30 2E 30 38 37 02 09 00 00 31 2E 54 32 30 2E 30 " + - "39 37 02 09 00 00 31 2E 54 32 30 2E 30 39 37 02 " + - "09 00 00 31 2E 54 32 30 2E 30 39 37 02 09 00 00 " + - "31 2E 54 32 30 2E 30 39 38 02 09 00 00 31 2E 54 " + - "32 30 2E 30 39 38 02 09 00 00 31 2E 54 32 30 2E " + - "30 39 38 02 09 00 00 31 2E 54 32 30 2E 30 39 39 " + - "02 09 00 00 31 2E 54 32 30 2E 30 39 39 02 09 00 " + - "00 31 2E 54 32 30 2E 30 39 39 02 09 00 00 31 2E " + - "54 32 30 2E 31 30 39 02 09 00 00 31 2E 54 32 30 " + - "2E 31 30 39 02 09 00 00 31 2E 54 32 30 2E 31 30 " + - "39 02 09 00 00 31 2E 54 32 30 2E 31 31 30 02 09 " + - "00 00 31 2E 54 32 30 2E 31 31 30 02 09 00 00 31 " + - "2E 54 32 30 2E 31 31 30 02 09 00 00 31 2E 54 32 " + - "30 2E 31 31 31 02 09 00 00 31 2E 54 32 30 2E 31 " + - "31 31 02 09 00 00 31 2E 54 32 30 2E 31 31 31 02 " + - "09 00 00 31 2E 54 32 30 2E 31 32 31 02 09 00 00 " + - "31 2E 54 32 30 2E 31 32 31 02 09 00 00 31 2E 54 " + - "32 30 2E 31 32 31 02 09 00 00 31 2E 54 32 30 2E " + - "31 32 32 02 09 00 00 31 2E 54 32 30 2E 31 32 32 " + - "02 09 00 00 31 2E 54 32 30 2E 31 32 32 02 09 00 " + - "00 31 2E 54 32 30 2E 31 32 33 02 09 00 00 31 2E " + - "54 32 30 2E 31 32 33 02 09 00 00 31 2E 54 32 30 " + - "2E 31 32 33 02 09 00 00 31 2E 54 32 30 2E 31 33 " + - "33 02 09 00 00 31 2E 54 32 30 2E 31 33 33 02 09 " + - "00 00 31 2E 54 32 30 2E 31 33 33 02 09 00 00 31 " + - "2E 54 32 30 2E 31 33 34 02 09 00 00 31 2E 54 32 " + - "30 2E 31 33 34 02 09 00 00 31 2E 54 32 30 2E 31 " + - "33 34 02 09 00 00 31 2E 54 32 30 2E 31 33 35 02 " + - "09 00 00 31 2E 54 32 30 2E 31 33 35 02 09 00 00 " + - "31 2E 54 32 30 2E 31 33 35 02 09 00 00 31 2E 54 " + - "32 30 2E 31 34 35 02 09 00 00 31 2E 54 32 30 2E " + - "31 34 35 02 09 00 00 31 2E 54 32 30 2E 31 34 35 " + - "02 09 00 00 31 2E 54 32 30 2E 31 34 36 02 09 00 " + - "00 31 2E 54 32 30 2E 31 34 36 02 09 00 00 31 2E " + - "54 32 30 2E 31 34 36 02 09 00 00 31 2E 54 32 30 " + - "2E 31 34 37 02 09 00 00 31 2E 54 32 30 2E 31 34 " + - "37 02 09 00 00 31 2E 54 32 30 2E 31 34 37 02 09 " + - "00 00 31 2E 54 32 30 2E 31 35 37 02 09 00 00 31 " + - "2E 54 32 30 2E 31 35 37 02 09 00 00 31 2E 54 32 " + - "30 2E 31 35 37 02 09 00 00 31 2E 54 32 30 2E 31 " + - "35 38 02 09 00 00 31 2E 54 32 30 2E 31 35 38 02 " + - "09 00 00 31 2E 54 32 30 2E 31 35 38 02 09 00 00 " + - "31 2E 54 32 30 2E 31 35 39 02 09 00 00 31 2E 54 " + - "32 30 2E 31 35 39 02 09 00 00 31 2E 54 32 30 2E " + - "31 35 39 02 09 00 00 31 2E 54 32 30 2E 31 36 39 " + - "02 09 00 00 31 2E 54 32 30 2E 31 36 39 02 09 00 " + - "00 31 2E 54 32 30 2E 31 36 39 02 09 00 00 31 2E " + - "54 32 30 2E 31 37 30 02 09 00 00 31 2E 54 32 30 " + - "2E 31 37 30 02 09 00 00 31 2E 54 32 30 2E 31 37 " + - "30 02 09 00 00 31 2E 54 32 30 2E 31 37 31 02 09 " + - "00 00 31 2E 54 32 30 2E 31 37 31 02 09 00 00 31 " + - "2E 54 32 30 2E 31 37 31 02 09 00 00 31 2E 54 36 " + - "30 2E 30 30 39 02 09 00 00 31 2E 54 36 30 2E 30 " + - "30 39 02 09 00 00 31 2E 54 36 30 2E 30 30 39 02 " + - "09 00 00 31 2E 54 36 30 2E 30 31 30 02 09 00 00 " + - "31 2E 54 36 30 2E 30 31 30 02 09 00 00 31 2E 54 " + - "36 30 2E 30 31 30 02 09 00 00 31 2E 54 36 30 2E " + - "30 31 31 02 09 00 00 31 2E 54 36 30 2E 30 31 31 " + - "02 09 00 00 31 2E 54 36 30 2E 30 31 31 02 09 00 " + - "00 31 2E 54 36 30 2E 30 32 31 02 09 00 00 31 2E " + - "54 36 30 2E 30 32 31 02 09 00 00 31 2E 54 36 30 " + - "2E 30 32 31 02 09 00 00 31 2E 54 36 30 2E 30 32 " + - "32 02 09 00 00 31 2E 54 36 30 2E 30 32 32 02 09 " + - "00 00 31 2E 54 36 30 2E 30 32 32 02 09 00 00 31 " + - "2E 54 36 30 2E 30 32 33 02 09 00 00 31 2E 54 36 " + - "30 2E 30 32 33 02 09 00 00 31 2E 54 36 30 2E 30 " + - "32 33 02 09 00 00 31 2E 54 36 30 2E 30 33 33 02 " + - "09 00 00 31 2E 54 36 30 2E 30 33 33 02 09 00 00 " + - "31 2E 54 36 30 2E 30 33 33 02 09 00 00 31 2E 54 " + - "36 30 2E 30 33 34 02 09 00 00 31 2E 54 36 30 2E " + - "30 33 34 02 09 00 00 31 2E 54 36 30 2E 30 33 34 " + - "02 09 00 00 31 2E 54 36 30 2E 30 33 35 02 09 00 " + - "00 31 2E 54 36 30 2E 30 33 35 02 09 00 00 31 2E " + - "54 36 30 2E 30 33 35 02 09 00 00 31 2E 54 36 30 " + - "2E 30 34 35 02 09 00 00 31 2E 54 36 30 2E 30 34 " + - "35 02 09 00 00 31 2E 54 36 30 2E 30 34 35 02 09 " + - "00 00 31 2E 54 36 30 2E 30 34 36 02 09 00 00 31 " + - "2E 54 36 30 2E 30 34 36 02 09 00 00 31 2E 54 36 " + - "30 2E 30 34 36 02 09 00 00 31 2E 54 36 30 2E 30 " + - "34 37 02 09 00 00 31 2E 54 36 30 2E 30 34 37 02 " + - "09 00 00 31 2E 54 36 30 2E 30 34 37 02 09 00 00 " + - "31 2E 54 36 30 2E 30 35 37 02 09 00 00 31 2E 54 " + - "36 30 2E 30 35 37 02 09 00 00 31 2E 54 36 30 2E " + - "30 35 37 02 09 00 00 31 2E 54 36 30 2E 30 35 38 " + - "02 09 00 00 31 2E 54 36 30 2E 30 35 38 02 09 00 " + - "00 31 2E 54 36 30 2E 30 35 38 02 09 00 00 31 2E " + - "54 36 30 2E 30 35 39 02 09 00 00 31 2E 54 36 30 " + - "2E 30 35 39 02 09 00 00 31 2E 54 36 30 2E 30 35 " + - "39 02 09 00 00 31 2E 54 36 30 2E 30 36 30 02 09 " + - "00 00 31 2E 54 36 30 2E 30 36 30 02 09 00 00 31 " + - "2E 54 36 30 2E 30 36 30 02 09 00 00 31 2E 54 36 " + - "30 2E 30 35 30 02 09 00 00 31 2E 54 36 30 2E 30 " + - "35 30 02 09 00 00 31 2E 54 36 30 2E 30 35 30 02 " + - "09 00 00 31 2E 54 36 30 2E 30 34 39 02 09 00 00 " + - "31 2E 54 36 30 2E 30 34 39 02 09 00 00 31 2E 54 " + - "36 30 2E 30 34 39 02 09 00 00 31 2E 54 36 30 2E " + - "30 34 38 02 09 00 00 31 2E 54 36 30 2E 30 34 38 " + - "02 09 00 00 31 2E 54 36 30 2E 30 34 38 02 09 00 " + - "00 31 2E 54 36 30 2E 30 33 38 02 09 00 00 31 2E " + - "54 36 30 2E 30 33 38 02 09 00 00 31 2E 54 36 30 " + - "2E 30 33 38 02 09 00 00 31 2E 54 36 30 2E 30 33 " + - "37 02 09 00 00 31 2E 54 36 30 2E 30 33 37 02 09 " + - "00 00 31 2E 54 36 30 2E 30 33 37 02 09 00 00 31 " + - "2E 54 36 30 2E 30 33 36 02 09 00 00 31 2E 54 36 " + - "30 2E 30 33 36 02 09 00 00 31 2E 54 36 30 2E 30 " + - "33 36 02 09 00 00 31 2E 54 36 30 2E 30 32 36 02 " + - "09 00 00 31 2E 54 36 30 2E 30 32 36 02 09 00 00 " + - "31 2E 54 36 30 2E 30 32 36 02 09 00 00 31 2E 54 " + - "36 30 2E 30 32 35 02 09 00 00 31 2E 54 36 30 2E " + - "30 32 35 02 09 00 00 31 2E 54 36 30 2E 30 32 35 " + - "02 09 00 00 31 2E 54 36 30 2E 30 32 34 02 09 00 " + - "00 31 2E 54 36 30 2E 30 32 34 02 09 00 00 31 2E " + - "54 36 30 2E 30 32 34 02 09 00 00 31 2E 54 36 30 " + - "2E 30 31 34 02 09 00 00 31 2E 54 36 30 2E 30 31 " + - "34 02 09 00 00 31 2E 54 36 30 2E 30 31 34 02 09 " + - "00 00 31 2E 54 36 30 2E 30 31 33 02 09 00 00 31 " + - "2E 54 36 30 2E 30 31 33 02 09 00 00 31 2E 54 36 " + - "30 2E 30 31 33 02 09 00 00 31 2E 54 36 30 2E 30 " + - "31 32 02 09 00 00 31 2E 54 36 30 2E 30 31 32 02 " + - "09 00 00 31 2E 54 36 30 2E 30 31 32 02 09 00 00 " + - "31 2E 54 36 30 2E 30 30 32 02 09 00 00 31 2E 54 " + - "36 30 2E 30 30 32 02 09 00 00 31 2E 54 36 30 2E " + - "30 30 32 02 09 00 00 31 2E 54 36 30 2E 30 30 31 " + - "02 09 00 00 31 2E 54 36 30 2E 30 30 31 02 09 00 " + - "00 31 2E 54 36 30 2E 30 30 31 02 09 00 00 31 2E " + - "54 32 30 2E 31 37 32 02 09 00 00 31 2E 54 32 30 " + - "2E 31 37 32 02 09 00 00 31 2E 54 32 30 2E 31 37 " + - "32 02 09 00 00 31 2E 54 32 30 2E 31 36 32 02 09 " + - "00 00 31 2E 54 32 30 2E 31 36 32 02 09 00 00 31 " + - "2E 54 32 30 2E 31 36 32 02 09 00 00 31 2E 54 32 " + - "30 2E 31 36 31 02 09 00 00 31 2E 54 32 30 2E 31 " + - "36 31 02 09 00 00 31 2E 54 32 30 2E 31 36 31 02 " + - "09 00 00 31 2E 54 32 30 2E 31 36 30 02 09 00 00 " + - "31 2E 54 32 30 2E 31 36 30 02 09 00 00 31 2E 54 " + - "32 30 2E 31 36 30 02 09 00 00 31 2E 54 32 30 2E " + - "31 35 30 02 09 00 00 31 2E 54 32 30 2E 31 35 30 " + - "02 09 00 00 31 2E 54 32 30 2E 31 35 30 02 09 00 " + - "00 31 2E 54 32 30 2E 31 34 39 02 09 00 00 31 2E " + - "54 32 30 2E 31 34 39 02 09 00 00 31 2E 54 32 30 " + - "2E 31 34 39 02 09 00 00 31 2E 54 32 30 2E 31 34 " + - "38 02 09 00 00 31 2E 54 32 30 2E 31 34 38 02 09 " + - "00 00 31 2E 54 32 30 2E 31 34 38 02 09 00 00 31 " + - "2E 54 32 30 2E 31 33 38 02 09 00 00 31 2E 54 32 " + - "30 2E 31 33 38 02 09 00 00 31 2E 54 32 30 2E 31 " + - "33 38 02 09 00 00 31 2E 54 32 30 2E 31 33 37 02 " + - "09 00 00 31 2E 54 32 30 2E 31 33 37 02 09 00 00 " + - "31 2E 54 32 30 2E 31 33 37 02 09 00 00 31 2E 54 " + - "32 30 2E 31 33 36 02 09 00 00 31 2E 54 32 30 2E " + - "31 33 36 02 09 00 00 31 2E 54 32 30 2E 31 33 36 " + - "02 09 00 00 31 2E 54 32 30 2E 31 32 36 02 09 00 " + - "00 31 2E 54 32 30 2E 31 32 36 02 09 00 00 31 2E " + - "54 32 30 2E 31 32 36 02 09 00 00 31 2E 54 32 30 " + - "2E 31 32 35 02 09 00 00 31 2E 54 32 30 2E 31 32 " + - "35 02 09 00 00 31 2E 54 32 30 2E 31 32 35 02 09 " + - "00 00 31 2E 54 32 30 2E 31 32 34 02 09 00 00 31 " + - "2E 54 32 30 2E 31 32 34 02 09 00 00 31 2E 54 32 " + - "30 2E 31 32 34 02 09 00 00 31 2E 54 32 30 2E 31 " + - "31 34 02 09 00 00 31 2E 54 32 30 2E 31 31 34 02 " + - "09 00 00 31 2E 54 32 30 2E 31 31 34 02 09 00 00 " + - "31 2E 54 32 30 2E 31 31 33 02 09 00 00 31 2E 54 " + - "32 30 2E 31 31 33 02 09 00 00 31 2E 54 32 30 2E " + - "31 31 33 02 09 00 00 31 2E 54 32 30 2E 31 31 32 " + - "02 09 00 00 31 2E 54 32 30 2E 31 31 32 02 09 00 " + - "00 31 2E 54 32 30 2E 31 31 32 02 09 00 00 31 2E " + - "54 32 30 2E 31 30 32 02 09 00 00 31 2E 54 32 30 " + - "2E 31 30 32 02 09 00 00 31 2E 54 32 30 2E 31 30 " + - "32 02 09 00 00 31 2E 54 32 30 2E 31 30 31 02 09 " + - "00 00 31 2E 54 32 30 2E 31 30 31 02 09 00 00 31 " + - "2E 54 32 30 2E 31 30 31 02 09 00 00 31 2E 54 32 " + - "30 2E 31 30 30 02 09 00 00 31 2E 54 32 30 2E 31 " + - "30 30 02 09 00 00 31 2E 54 32 30 2E 31 30 30 02 " + - "09 00 00 31 2E 54 32 30 2E 30 39 30 02 09 00 00 " + - "31 2E 54 32 30 2E 30 39 30 02 09 00 00 31 2E 54 " + - "32 30 2E 30 39 30 02 09 00 00 31 2E 54 32 30 2E " + - "30 38 39 02 09 00 00 31 2E 54 32 30 2E 30 38 39 " + - "02 09 00 00 31 2E 54 32 30 2E 30 38 39 02 09 00 " + - "00 31 2E 54 32 30 2E 30 38 38 02 09 00 00 31 2E " + - "54 32 30 2E 30 38 38 02 09 00 00 31 2E 54 32 30 " + - "2E 30 38 38 02 09 00 00 31 2E 54 32 30 2E 30 37 " + - "38 02 09 00 00 31 2E 54 32 30 2E 30 37 38 02 09 " + - "00 00 31 2E 54 32 30 2E 30 37 38 02 09 00 00 31 " + - "2E 54 32 30 2E 30 37 37 02 09 00 00 31 2E 54 32 " + - "30 2E 30 37 37 02 09 00 00 31 2E 54 32 30 2E 30 " + - "37 37 02 09 00 00 31 2E 54 32 30 2E 30 37 36 02 " + - "09 00 00 31 2E 54 32 30 2E 30 37 36 02 09 00 00 " + - "31 2E 54 32 30 2E 30 37 36 02 09 00 00 31 2E 54 " + - "32 30 2E 30 36 36 02 09 00 00 31 2E 54 32 30 2E " + - "30 36 36 02 09 00 00 31 2E 54 32 30 2E 30 36 36 " + - "02 09 00 00 31 2E 54 32 30 2E 30 36 35 02 09 00 " + - "00 31 2E 54 32 30 2E 30 36 35 02 09 00 00 31 2E " + - "54 32 30 2E 30 36 35 02 09 00 00 31 2E 54 32 30 " + - "2E 30 36 34 02 09 00 00 31 2E 54 32 30 2E 30 36 " + - "34 02 09 00 00 31 2E 54 32 30 2E 30 36 34 02 09 " + - "00 00 31 2E 54 32 30 2E 30 35 34 02 09 00 00 31 " + - "2E 54 32 30 2E 30 35 34 02 09 00 00 31 2E 54 32 " + - "30 2E 30 35 34 02 09 00 00 31 2E 54 32 30 2E 30 " + - "35 33 02 09 00 00 31 2E 54 32 30 2E 30 35 33 02 " + - "09 00 00 31 2E 54 32 30 2E 30 35 33 02 09 00 00 " + - "31 2E 54 32 30 2E 30 35 32 02 09 00 00 31 2E 54 " + - "32 30 2E 30 35 32 02 09 00 00 31 2E 54 32 30 2E " + - "30 35 32 02 09 00 00 31 2E 54 32 30 2E 30 34 32 " + - "02 09 00 00 31 2E 54 32 30 2E 30 34 32 02 09 00 " + - "00 31 2E 54 32 30 2E 30 34 32 02 09 00 00 31 2E " + - "54 32 30 2E 30 34 31 02 09 00 00 31 2E 54 32 30 " + - "2E 30 34 31 02 09 00 00 31 2E 54 32 30 2E 30 34 " + - "31 02 09 00 00 31 2E 54 32 30 2E 30 34 30 02 09 " + - "00 00 31 2E 54 32 30 2E 30 34 30 02 09 00 00 31 " + - "2E 54 32 30 2E 30 34 30 02 09 00 00 31 2E 54 32 " + - "30 2E 30 33 30 02 09 00 00 31 2E 54 32 30 2E 30 " + - "33 30 02 09 00 00 31 2E 54 32 30 2E 30 33 30 02 " + - "09 00 00 31 2E 54 32 30 2E 30 32 39 02 09 00 00 " + - "31 2E 54 32 30 2E 30 32 39 02 09 00 00 31 2E 54 " + - "32 30 2E 30 32 39 02 09 00 00 31 2E 54 32 30 2E " + - "30 32 38 02 09 00 00 31 2E 54 32 30 2E 30 32 38 " + - "02 09 00 00 31 2E 54 32 30 2E 30 32 38 02 09 00 " + - "00 31 2E 54 32 30 2E 30 31 38 02 09 00 00 31 2E " + - "54 32 30 2E 30 31 38 02 09 00 00 31 2E 54 32 30 " + - "2E 30 31 38 02 09 00 00 31 2E 54 32 30 2E 30 31 " + - "37 02 09 00 00 31 2E 54 32 30 2E 30 31 37 02 09 " + - "00 00 31 2E 54 32 30 2E 30 31 37 02 09 00 00 31 " + - "2E 54 32 30 2E 30 31 36 02 09 00 00 31 2E 54 32 " + - "30 2E 30 31 36 02 09 00 00 31 2E 54 32 30 2E 30 " + - "31 36 02 09 00 00 31 2E 54 32 30 2E 30 30 36 02 " + - "09 00 00 31 2E 54 32 30 2E 30 30 36 02 09 00 00 " + - "31 2E 54 32 30 2E 30 30 36 02 09 00 00 31 2E 54 " + - "32 30 2E 30 30 35 02 09 00 00 31 2E 54 32 30 2E " + - "30 30 35 02 09 00 00 31 2E 54 32 30 2E 30 30 35 " + - "02 09 00 00 31 2E 54 32 30 2E 30 30 34 02 09 00 " + - "00 31 2E 54 32 30 2E 30 30 34 02 09 00 00 31 2E " + - "54 32 30 2E 30 30 34 02 09 00 00 31 2E 54 32 30 " + - "2E 30 30 37 02 09 00 00 31 2E 54 32 30 2E 30 30 " + - "37 02 09 00 00 31 2E 54 32 30 2E 30 30 37 02 09 " + - "00 00 31 2E 54 32 30 2E 30 30 38 02 09 00 00 31 " + - "2E 54 32 30 2E 30 30 38 02 09 00 00 31 2E 54 32 " + - "30 2E 30 30 38 02 09 00 00 31 2E 54 32 30 2E 30 " + - "30 39 02 09 00 00 31 2E 54 32 30 2E 30 30 39 02 " + - "09 00 00 31 2E 54 32 30 2E 30 30 39 02 09 00 00 " + - "31 2E 54 32 30 2E 30 31 39 02 09 00 00 31 2E 54 " + - "32 30 2E 30 31 39 02 09 00 00 31 2E 54 32 30 2E " + - "30 31 39 02 09 00 00 31 2E 54 32 30 2E 30 32 30 " + - "02 09 00 00 31 2E 54 32 30 2E 30 32 30 02 09 00 " + - "00 31 2E 54 32 30 2E 30 32 30 02 09 00 00 31 2E " + - "54 32 30 2E 30 32 31 02 09 00 00 31 2E 54 32 30 " + - "2E 30 32 31 02 09 00 00 31 2E 54 32 30 2E 30 32 " + - "31 02 09 00 00 31 2E 54 32 30 2E 30 33 31 02 09 " + - "00 00 31 2E 54 32 30 2E 30 33 31 02 09 00 00 31 " + - "2E 54 32 30 2E 30 33 31 02 09 00 00 31 2E 54 32 " + - "30 2E 30 33 32 02 09 00 00 31 2E 54 32 30 2E 30 " + - "33 32 02 09 00 00 31 2E 54 32 30 2E 30 33 32 02 " + - "09 00 00 31 2E 54 32 30 2E 30 33 33 02 09 00 00 " + - "31 2E 54 32 30 2E 30 33 33 02 09 00 00 31 2E 54 " + - "32 30 2E 30 33 33 02 09 00 00 31 2E 54 32 30 2E " + - "30 34 33 02 09 00 00 31 2E 54 32 30 2E 30 34 33 " + - "02 09 00 00 31 2E 54 32 30 2E 30 34 33 02 09 00 " + - "00 31 2E 54 32 30 2E 30 34 34 02 09 00 00 31 2E " + - "54 32 30 2E 30 34 34 02 09 00 00 31 2E 54 32 30 " + - "2E 30 34 34 02 09 00 00 31 2E 54 32 30 2E 30 34 " + - "35 02 09 00 00 31 2E 54 32 30 2E 30 34 35 02 09 " + - "00 00 31 2E 54 32 30 2E 30 34 35 02 09 00 00 31 " + - "2E 54 32 30 2E 30 35 35 02 09 00 00 31 2E 54 32 " + - "30 2E 30 35 35 02 09 00 00 31 2E 54 32 30 2E 30 " + - "35 35 02 09 00 00 31 2E 54 32 30 2E 30 35 36 02 " + - "09 00 00 31 2E 54 32 30 2E 30 35 36 02 09 00 00 " + - "31 2E 54 32 30 2E 30 35 36 02 09 00 00 31 2E 54 " + - "32 30 2E 30 35 37 02 09 00 00 31 2E 54 32 30 2E " + - "30 35 37 02 09 00 00 31 2E 54 32 30 2E 30 35 37 " + - "02 09 00 00 31 2E 54 32 30 2E 30 36 37 02 09 00 " + - "00 31 2E 54 32 30 2E 30 36 37 02 09 00 00 31 2E " + - "54 32 30 2E 30 36 37 02 09 00 00 31 2E 54 32 30 " + - "2E 30 36 38 02 09 00 00 31 2E 54 32 30 2E 30 36 " + - "38 02 09 00 00 31 2E 54 32 30 2E 30 36 38 02 09 " + - "00 00 31 2E 54 32 30 2E 30 36 39 02 09 00 00 31 " + - "2E 54 32 30 2E 30 36 39 02 09 00 00 31 2E 54 32 " + - "30 2E 30 36 39 02 09 00 00 31 2E 54 32 30 2E 30 " + - "37 39 02 09 00 00 31 2E 54 32 30 2E 30 37 39 02 " + - "09 00 00 31 2E 54 32 30 2E 30 37 39 02 09 00 00 " + - "31 2E 54 32 30 2E 30 38 30 02 09 00 00 31 2E 54 " + - "32 30 2E 30 38 30 02 09 00 00 31 2E 54 32 30 2E " + - "30 38 30 02 09 00 00 31 2E 54 32 30 2E 30 38 31 " + - "02 09 00 00 31 2E 54 32 30 2E 30 38 31 02 09 00 " + - "00 31 2E 54 32 30 2E 30 38 31 02 09 00 00 31 2E " + - "54 32 30 2E 30 39 31 02 09 00 00 31 2E 54 32 30 " + - "2E 30 39 31 02 09 00 00 31 2E 54 32 30 2E 30 39 " + - "31 02 09 00 00 31 2E 54 32 30 2E 30 39 32 02 09 " + - "00 00 31 2E 54 32 30 2E 30 39 32 02 09 00 00 31 " + - "2E 54 32 30 2E 30 39 32 02 09 00 00 31 2E 54 32 " + - "30 2E 30 39 33 02 09 00 00 31 2E 54 32 30 2E 30 " + - "39 33 02 09 00 00 31 2E 54 32 30 2E 30 39 33 02 " + - "09 00 00 31 2E 54 32 30 2E 31 30 33 02 09 00 00 " + - "31 2E 54 32 30 2E 31 30 33 02 09 00 00 31 2E 54 " + - "32 30 2E 31 30 33 02 09 00 00 31 2E 54 32 30 2E " + - "31 30 34 02 09 00 00 31 2E 54 32 30 2E 31 30 34 " + - "02 09 00 00 31 2E 54 32 30 2E 31 30 34 02 09 00 " + - "00 31 2E 54 32 30 2E 31 30 35 02 09 00 00 31 2E " + - "54 32 30 2E 31 30 35 02 09 00 00 31 2E 54 32 30 " + - "2E 31 30 35 02 09 00 00 31 2E 54 32 30 2E 31 31 " + - "35 02 09 00 00 31 2E 54 32 30 2E 31 31 35 02 09 " + - "00 00 31 2E 54 32 30 2E 31 31 35 02 09 00 00 31 " + - "2E 54 32 30 2E 31 31 36 02 09 00 00 31 2E 54 32 " + - "30 2E 31 31 36 02 09 00 00 31 2E 54 32 30 2E 31 " + - "31 36 02 09 00 00 31 2E 54 32 30 2E 31 31 37 02 " + - "09 00 00 31 2E 54 32 30 2E 31 31 37 02 09 00 00 " + - "31 2E 54 32 30 2E 31 31 37 02 09 00 00 31 2E 54 " + - "32 30 2E 31 32 37 02 09 00 00 31 2E 54 32 30 2E " + - "31 32 37 02 09 00 00 31 2E 54 32 30 2E 31 32 37 " + - "02 09 00 00 31 2E 54 32 30 2E 31 32 38 02 09 00 " + - "00 31 2E 54 32 30 2E 31 32 38 02 09 00 00 31 2E " + - "54 32 30 2E 31 32 38 02 09 00 00 31 2E 54 32 30 " + - "2E 31 32 39 02 09 00 00 31 2E 54 32 30 2E 31 32 " + - "39 02 09 00 00 31 2E 54 32 30 2E 31 32 39 02 09 " + - "00 00 31 2E 54 32 30 2E 31 33 39 02 09 00 00 31 " + - "2E 54 32 30 2E 31 33 39 02 09 00 00 31 2E 54 32 " + - "30 2E 31 33 39 02 09 00 00 31 2E 54 32 30 2E 31 " + - "34 30 02 09 00 00 31 2E 54 32 30 2E 31 34 30 02 " + - "09 00 00 31 2E 54 32 30 2E 31 34 30 02 09 00 00 " + - "31 2E 54 32 30 2E 31 34 31 02 09 00 00 31 2E 54 " + - "32 30 2E 31 34 31 02 09 00 00 31 2E 54 32 30 2E " + - "31 34 31 02 09 00 00 31 2E 54 32 30 2E 31 35 31 " + - "02 09 00 00 31 2E 54 32 30 2E 31 35 31 02 09 00 " + - "00 31 2E 54 32 30 2E 31 35 31 02 09 00 00 31 2E " + - "54 32 30 2E 31 35 32 02 09 00 00 31 2E 54 32 30 " + - "2E 31 35 32 02 09 00 00 31 2E 54 32 30 2E 31 35 " + - "32 02 09 00 00 31 2E 54 32 30 2E 31 35 33 02 09 " + - "00 00 31 2E 54 32 30 2E 31 35 33 02 09 00 00 31 " + - "2E 54 32 30 2E 31 35 33 02 09 00 00 31 2E 54 32 " + - "30 2E 31 36 33 02 09 00 00 31 2E 54 32 30 2E 31 " + - "36 33 02 09 00 00 31 2E 54 32 30 2E 31 36 33 02 " + - "09 00 00 31 2E 54 32 30 2E 31 36 34 02 09 00 00 " + - "31 2E 54 32 30 2E 31 36 34 02 09 00 00 31 2E 54 " + - "32 30 2E 31 36 34 02 09 00 00 31 2E 54 32 30 2E " + - "31 36 35 02 09 00 00 31 2E 54 32 30 2E 31 36 35 " + - "02 09 00 00 31 2E 54 32 30 2E 31 36 35 02 09 00 " + - "00 31 2E 54 36 30 2E 30 30 33 02 09 00 00 31 2E " + - "54 36 30 2E 30 30 33 02 09 00 00 31 2E 54 36 30 " + - "2E 30 30 33 02 09 00 00 31 2E 54 36 30 2E 30 30 " + - "34 02 09 00 00 31 2E 54 36 30 2E 30 30 34 02 09 " + - "00 00 31 2E 54 36 30 2E 30 30 34 02 09 00 00 31 " + - "2E 54 36 30 2E 30 30 35 02 09 00 00 31 2E 54 36 " + - "30 2E 30 30 35 02 09 00 00 31 2E 54 36 30 2E 30 " + - "30 35 02 09 00 00 31 2E 54 36 30 2E 30 31 35 02 " + - "09 00 00 31 2E 54 36 30 2E 30 31 35 02 09 00 00 " + - "31 2E 54 36 30 2E 30 31 35 02 09 00 00 31 2E 54 " + - "36 30 2E 30 31 36 02 09 00 00 31 2E 54 36 30 2E " + - "30 31 36 02 09 00 00 31 2E 54 36 30 2E 30 31 36 " + - "02 09 00 00 31 2E 54 36 30 2E 30 31 37 02 09 00 " + - "00 31 2E 54 36 30 2E 30 31 37 02 09 00 00 31 2E " + - "54 36 30 2E 30 31 37 02 09 00 00 31 2E 54 36 30 " + - "2E 30 32 37 02 09 00 00 31 2E 54 36 30 2E 30 32 " + - "37 02 09 00 00 31 2E 54 36 30 2E 30 32 37 02 09 " + - "00 00 31 2E 54 36 30 2E 30 32 38 02 09 00 00 31 " + - "2E 54 36 30 2E 30 32 38 02 09 00 00 31 2E 54 36 " + - "30 2E 30 32 38 02 09 00 00 31 2E 54 36 30 2E 30 " + - "32 39 02 09 00 00 31 2E 54 36 30 2E 30 32 39 02 " + - "09 00 00 31 2E 54 36 30 2E 30 32 39 02 09 00 00 " + - "31 2E 54 36 30 2E 30 33 39 02 09 00 00 31 2E 54 " + - "36 30 2E 30 33 39 02 09 00 00 31 2E 54 36 30 2E " + - "30 33 39 02 09 00 00 31 2E 54 36 30 2E 30 34 30 " + - "02 09 00 00 31 2E 54 36 30 2E 30 34 30 02 09 00 " + - "00 31 2E 54 36 30 2E 30 34 30 02 09 00 00 31 2E " + - "54 36 30 2E 30 34 31 02 09 00 00 31 2E 54 36 30 " + - "2E 30 34 31 02 09 00 00 31 2E 54 36 30 2E 30 34 " + - "31 02 09 00 00 31 2E 54 36 30 2E 30 35 31 02 09 " + - "00 00 31 2E 54 36 30 2E 30 35 31 02 09 00 00 31 " + - "2E 54 36 30 2E 30 35 31 02 09 00 00 31 2E 54 36 " + - "30 2E 30 35 32 02 09 00 00 31 2E 54 36 30 2E 30 " + - "35 32 02 09 00 00 31 2E 54 36 30 2E 30 35 32 02 " + - "09 00 00 31 2E 54 36 30 2E 30 35 33 02 09 00 00 " + - "31 2E 54 36 30 2E 30 35 33 02 09 00 00 31 2E 54 " + - "36 30 2E 30 35 33 02 09 00 00 31 2E 54 36 30 2E " + - "30 35 36 02 09 00 00 31 2E 54 36 30 2E 30 35 36 " + - "02 09 00 00 31 2E 54 36 30 2E 30 35 36 02 09 00 " + - "00 31 2E 54 36 30 2E 30 35 35 02 09 00 00 31 2E " + - "54 36 30 2E 30 35 35 02 09 00 00 31 2E 54 36 30 " + - "2E 30 35 35 02 09 00 00 31 2E 54 36 30 2E 30 35 " + - "34 02 09 00 00 31 2E 54 36 30 2E 30 35 34 02 09 " + - "00 00 31 2E 54 36 30 2E 30 35 34 02 09 00 00 31 " + - "2E 54 36 30 2E 30 34 34 02 09 00 00 31 2E 54 36 " + - "30 2E 30 34 34 02 09 00 00 31 2E 54 36 30 2E 30 " + - "34 34 02 09 00 00 31 2E 54 36 30 2E 30 34 33 02 " + - "09 00 00 31 2E 54 36 30 2E 30 34 33 02 09 00 00 " + - "31 2E 54 36 30 2E 30 34 33 02 09 00 00 31 2E 54 " + - "36 30 2E 30 34 32 02 09 00 00 31 2E 54 36 30 2E " + - "30 34 32 02 09 00 00 31 2E 54 36 30 2E 30 34 32 " + - "02 09 00 00 31 2E 54 36 30 2E 30 33 32 02 09 00 " + - "00 31 2E 54 36 30 2E 30 33 32 02 09 00 00 31 2E " + - "54 36 30 2E 30 33 32 02 09 00 00 31 2E 54 36 30 " + - "2E 30 33 31 02 09 00 00 31 2E 54 36 30 2E 30 33 " + - "31 02 09 00 00 31 2E 54 36 30 2E 30 33 31 02 09 " + - "00 00 31 2E 54 36 30 2E 30 33 30 02 09 00 00 31 " + - "2E 54 36 30 2E 30 33 30 02 09 00 00 31 2E 54 36 " + - "30 2E 30 33 30 02 09 00 00 31 2E 54 36 30 2E 30 " + - "32 30 02 09 00 00 31 2E 54 36 30 2E 30 32 30 02 " + - "09 00 00 31 2E 54 36 30 2E 30 32 30 02 09 00 00 " + - "31 2E 54 36 30 2E 30 31 39 02 09 00 00 31 2E 54 " + - "36 30 2E 30 31 39 02 09 00 00 31 2E 54 36 30 2E " + - "30 31 39 02 09 00 00 31 2E 54 36 30 2E 30 31 38 " + - "02 09 00 00 31 2E 54 36 30 2E 30 31 38 02 09 00 " + - "00 31 2E 54 36 30 2E 30 31 38 02 09 00 00 31 2E " + - "54 36 30 2E 30 30 38 02 09 00 00 31 2E 54 36 30 " + - "2E 30 30 38 02 09 00 00 31 2E 54 36 30 2E 30 30 " + - "38 02 09 00 00 31 2E 54 36 30 2E 30 30 37 02 09 " + - "00 00 31 2E 54 36 30 2E 30 30 37 02 09 00 00 31 " + - "2E 54 36 30 2E 30 30 37 02 09 00 00 31 2E 54 36 " + - "30 2E 30 30 36 02 09 00 00 31 2E 54 36 30 2E 30 " + - "30 36 02 09 00 00 31 2E 54 36 30 2E 30 30 36 02 " + - "09 00 00 31 2E 54 32 30 2E 31 36 38 02 09 00 00 " + - "31 2E 54 32 30 2E 31 36 38 02 09 00 00 31 2E 54 " + - "32 30 2E 31 36 38 02 09 00 00 31 2E 54 32 30 2E " + - "31 36 37 02 09 00 00 31 2E 54 32 30 2E 31 36 37 " + - "02 09 00 00 31 2E 54 32 30 2E 31 36 37 02 09 00 " + - "00 31 2E 54 32 30 2E 31 36 36 02 09 00 00 31 2E " + - "54 32 30 2E 31 36 36 02 09 00 00 31 2E 54 32 30 " + - "2E 31 36 36 02 09 00 00 31 2E 54 32 30 2E 31 35 " + - "36 02 09 00 00 31 2E 54 32 30 2E 31 35 36 02 09 " + - "00 00 31 2E 54 32 30 2E 31 35 36 02 09 00 00 31 " + - "2E 54 32 30 2E 31 35 35 02 09 00 00 31 2E 54 32 " + - "30 2E 31 35 35 02 09 00 00 31 2E 54 32 30 2E 31 " + - "35 35 02 09 00 00 31 2E 54 32 30 2E 31 35 34 02 " + - "09 00 00 31 2E 54 32 30 2E 31 35 34 02 09 00 00 " + - "31 2E 54 32 30 2E 31 35 34 02 09 00 00 31 2E 54 " + - "32 30 2E 31 34 34 02 09 00 00 31 2E 54 32 30 2E " + - "31 34 34 "; - - String record_0x03C = - " 3C 00 62 05 02 09 00 00 31 2E 54 32 30 " + - "2E 31 34 34 02 09 00 00 31 2E 54 32 30 2E 31 34 " + - "33 02 09 00 00 31 2E 54 32 30 2E 31 34 33 02 09 " + - "00 00 31 2E 54 32 30 2E 31 34 33 02 09 00 00 31 " + - "2E 54 32 30 2E 31 34 32 02 09 00 00 31 2E 54 32 " + - "30 2E 31 34 32 02 09 00 00 31 2E 54 32 30 2E 31 " + - "34 32 02 09 00 00 31 2E 54 32 30 2E 31 33 32 02 " + - "09 00 00 31 2E 54 32 30 2E 31 33 32 02 09 00 00 " + - "31 2E 54 32 30 2E 31 33 32 02 09 00 00 31 2E 54 " + - "32 30 2E 31 33 31 02 09 00 00 31 2E 54 32 30 2E " + - "31 33 31 02 09 00 00 31 2E 54 32 30 2E 31 33 31 " + - "02 09 00 00 31 2E 54 32 30 2E 31 33 30 02 09 00 " + - "00 31 2E 54 32 30 2E 31 33 30 02 09 00 00 31 2E " + - "54 32 30 2E 31 33 30 02 09 00 00 31 2E 54 32 30 " + - "2E 31 32 30 02 09 00 00 31 2E 54 32 30 2E 31 32 " + - "30 02 09 00 00 31 2E 54 32 30 2E 31 32 30 02 09 " + - "00 00 31 2E 54 32 30 2E 31 31 39 02 09 00 00 31 " + - "2E 54 32 30 2E 31 31 39 02 09 00 00 31 2E 54 32 " + - "30 2E 31 31 39 02 09 00 00 31 2E 54 32 30 2E 31 " + - "31 38 02 09 00 00 31 2E 54 32 30 2E 31 31 38 02 " + - "09 00 00 31 2E 54 32 30 2E 31 31 38 02 09 00 00 " + - "31 2E 54 32 30 2E 31 30 38 02 09 00 00 31 2E 54 " + - "32 30 2E 31 30 38 02 09 00 00 31 2E 54 32 30 2E " + - "31 30 38 02 09 00 00 31 2E 54 32 30 2E 31 30 37 " + - "02 09 00 00 31 2E 54 32 30 2E 31 30 37 02 09 00 " + - "00 31 2E 54 32 30 2E 31 30 37 02 09 00 00 31 2E " + - "54 32 30 2E 31 30 36 02 09 00 00 31 2E 54 32 30 " + - "2E 31 30 36 02 09 00 00 31 2E 54 32 30 2E 31 30 " + - "36 02 09 00 00 31 2E 54 32 30 2E 30 39 36 02 09 " + - "00 00 31 2E 54 32 30 2E 30 39 36 02 09 00 00 31 " + - "2E 54 32 30 2E 30 39 36 02 09 00 00 31 2E 54 32 " + - "30 2E 30 39 35 02 09 00 00 31 2E 54 32 30 2E 30 " + - "39 35 02 09 00 00 31 2E 54 32 30 2E 30 39 35 02 " + - "09 00 00 31 2E 54 32 30 2E 30 39 34 02 09 00 00 " + - "31 2E 54 32 30 2E 30 39 34 02 09 00 00 31 2E 54 " + - "32 30 2E 30 39 34 02 09 00 00 31 2E 54 32 30 2E " + - "30 38 34 02 09 00 00 31 2E 54 32 30 2E 30 38 34 " + - "02 09 00 00 31 2E 54 32 30 2E 30 38 34 02 09 00 " + - "00 31 2E 54 32 30 2E 30 38 33 02 09 00 00 31 2E " + - "54 32 30 2E 30 38 33 02 09 00 00 31 2E 54 32 30 " + - "2E 30 38 33 02 09 00 00 31 2E 54 32 30 2E 30 38 " + - "32 02 09 00 00 31 2E 54 32 30 2E 30 38 32 02 09 " + - "00 00 31 2E 54 32 30 2E 30 38 32 02 09 00 00 31 " + - "2E 54 32 30 2E 30 37 32 02 09 00 00 31 2E 54 32 " + - "30 2E 30 37 32 02 09 00 00 31 2E 54 32 30 2E 30 " + - "37 32 02 09 00 00 31 2E 54 32 30 2E 30 37 31 02 " + - "09 00 00 31 2E 54 32 30 2E 30 37 31 02 09 00 00 " + - "31 2E 54 32 30 2E 30 37 31 02 09 00 00 31 2E 54 " + - "32 30 2E 30 37 30 02 09 00 00 31 2E 54 32 30 2E " + - "30 37 30 02 09 00 00 31 2E 54 32 30 2E 30 37 30 " + - "02 09 00 00 31 2E 54 32 30 2E 30 36 30 02 09 00 " + - "00 31 2E 54 32 30 2E 30 36 30 02 09 00 00 31 2E " + - "54 32 30 2E 30 36 30 02 09 00 00 31 2E 54 32 30 " + - "2E 30 35 39 02 09 00 00 31 2E 54 32 30 2E 30 35 " + - "39 02 09 00 00 31 2E 54 32 30 2E 30 35 39 02 09 " + - "00 00 31 2E 54 32 30 2E 30 35 38 02 09 00 00 31 " + - "2E 54 32 30 2E 30 35 38 02 09 00 00 31 2E 54 32 " + - "30 2E 30 35 38 02 09 00 00 31 2E 54 32 30 2E 30 " + - "34 38 02 09 00 00 31 2E 54 32 30 2E 30 34 38 02 " + - "09 00 00 31 2E 54 32 30 2E 30 34 38 02 09 00 00 " + - "31 2E 54 32 30 2E 30 34 37 02 09 00 00 31 2E 54 " + - "32 30 2E 30 34 37 02 09 00 00 31 2E 54 32 30 2E " + - "30 34 37 02 09 00 00 31 2E 54 32 30 2E 30 34 36 " + - "02 09 00 00 31 2E 54 32 30 2E 30 34 36 02 09 00 " + - "00 31 2E 54 32 30 2E 30 34 36 02 09 00 00 31 2E " + - "54 32 30 2E 30 33 36 02 09 00 00 31 2E 54 32 30 " + - "2E 30 33 36 02 09 00 00 31 2E 54 32 30 2E 30 33 " + - "36 02 09 00 00 31 2E 54 32 30 2E 30 33 35 02 09 " + - "00 00 31 2E 54 32 30 2E 30 33 35 02 09 00 00 31 " + - "2E 54 32 30 2E 30 33 35 02 09 00 00 31 2E 54 32 " + - "30 2E 30 33 34 02 09 00 00 31 2E 54 32 30 2E 30 " + - "33 34 02 09 00 00 31 2E 54 32 30 2E 30 33 34 02 " + - "09 00 00 31 2E 54 32 30 2E 30 32 34 02 09 00 00 " + - "31 2E 54 32 30 2E 30 32 34 02 09 00 00 31 2E 54 " + - "32 30 2E 30 32 34 02 09 00 00 31 2E 54 32 30 2E " + - "30 32 33 02 09 00 00 31 2E 54 32 30 2E 30 32 33 " + - "02 09 00 00 31 2E 54 32 30 2E 30 32 33 02 09 00 " + - "00 31 2E 54 32 30 2E 30 32 32 02 09 00 00 31 2E " + - "54 32 30 2E 30 32 32 02 09 00 00 31 2E 54 32 30 " + - "2E 30 32 32 02 09 00 00 31 2E 54 32 30 2E 30 31 " + - "32 02 09 00 00 31 2E 54 32 30 2E 30 31 32 02 09 " + - "00 00 31 2E 54 32 30 2E 30 31 32 02 09 00 00 31 " + - "2E 54 32 30 2E 30 31 31 02 09 00 00 31 2E 54 32 " + - "30 2E 30 31 31 02 09 00 00 31 2E 54 32 30 2E 30 " + - "31 31 02 09 00 00 31 2E 54 32 30 2E 30 31 30 02 " + - "09 00 00 31 2E 54 32 30 2E 30 31 30 02 09 00 00 " + - "31 2E 54 32 30 2E 30 31 30 "; - - byte[] data1 = HexRead.readFromString(record_0x0018 + record_0x03C); - RecordInputStream in1 = TestcaseRecordInputStream.create(data1); - NameRecord nr1 = new NameRecord(in1); - assert_bug50244(nr1); - - byte[] data2 = nr1.serialize(); - - assertEquals(data1.length, data2.length); - RecordInputStream in2 = TestcaseRecordInputStream.create(data2); - NameRecord nr2 = new NameRecord(in2); - assert_bug50244(nr2); - } - - private void assert_bug50244(NameRecord nr){ - assertEquals("wDataGruppeSerie.", nr.getNameText()); - Ptg[] ptg = nr.getNameDefinition(); - assertEquals(1, ptg.length); - ArrayPtg arr = (ArrayPtg)ptg[0]; - assertEquals(696, arr.getRowCount()); - assertEquals(1, arr.getColumnCount()); - Object[][] vals = arr.getTokenArrayValues(); - assertEquals("1.T20.001", vals[0][0]); - assertEquals("1.T20.010", vals[vals.length - 1][0]); - } - - public void testBug57923() { - NameRecord record = new NameRecord(); - assertEquals(0, record.getExternSheetNumber()); - - record.setNameDefinition(new Ptg[] {}); - assertEquals(0, record.getExternSheetNumber()); - - record.setNameDefinition(new Ptg[] {new NamePtg(1)}); - assertEquals(0, record.getExternSheetNumber()); - - record.setNameDefinition(new Ptg[] {new Area3DPtg("area", 1)}); - assertEquals(1, record.getExternSheetNumber()); - - record.setNameDefinition(new Ptg[] {new Ref3DPtg("A1", 1)}); - assertEquals(1, record.getExternSheetNumber()); - } - -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestNoteRecord.java b/src/testcases/org/apache/poi/hssf/record/TestNoteRecord.java deleted file mode 100644 index 5f238f80c..000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestNoteRecord.java +++ /dev/null @@ -1,134 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record; - -import static org.junit.Assert.assertArrayEquals; -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -import org.apache.poi.util.HexRead; - -/** - * Tests the serialization and deserialization of the NoteRecord - * class works correctly. Test data taken directly from a real - * Excel file. - * - * @author Yegor Kozlov - */ -public final class TestNoteRecord extends TestCase { - private final byte[] testData = HexRead.readFromString( - "06 00 01 00 02 00 02 04 " + - "1A 00 00 " + - "41 70 61 63 68 65 20 53 6F 66 74 77 61 72 65 20 46 6F 75 6E 64 61 74 69 6F 6E " + - "00" // padding byte - ); - - public void testRead() { - - NoteRecord record = new NoteRecord(TestcaseRecordInputStream.create(NoteRecord.sid, testData)); - - assertEquals(NoteRecord.sid, record.getSid()); - assertEquals(6, record.getRow()); - assertEquals(1, record.getColumn()); - assertEquals(NoteRecord.NOTE_VISIBLE, record.getFlags()); - assertEquals(1026, record.getShapeId()); - assertEquals("Apache Software Foundation", record.getAuthor()); - } - - public void testWrite() { - NoteRecord record = new NoteRecord(); - assertEquals(NoteRecord.sid, record.getSid()); - - record.setRow((short)6); - record.setColumn((short)1); - record.setFlags(NoteRecord.NOTE_VISIBLE); - record.setShapeId((short)1026); - record.setAuthor("Apache Software Foundation"); - - byte[] ser = record.serialize(); - TestcaseRecordInputStream.confirmRecordEncoding(NoteRecord.sid, testData, ser); - } - - public void testClone() { - NoteRecord record = new NoteRecord(); - - record.setRow((short)1); - record.setColumn((short)2); - record.setFlags(NoteRecord.NOTE_VISIBLE); - record.setShapeId((short)1026); - record.setAuthor("Apache Software Foundation"); - - NoteRecord cloned = record.clone(); - assertEquals(record.getRow(), cloned.getRow()); - assertEquals(record.getColumn(), cloned.getColumn()); - assertEquals(record.getFlags(), cloned.getFlags()); - assertEquals(record.getShapeId(), cloned.getShapeId()); - assertEquals(record.getAuthor(), cloned.getAuthor()); - - //finally check that the serialized data is the same - byte[] src = record.serialize(); - byte[] cln = cloned.serialize(); - assertArrayEquals(src, cln); - } - - public void testUnicodeAuthor() { - // This sample data was created by setting the 'user name' field in the 'Personalize' - // section of Excel's options to \u30A2\u30D1\u30C3\u30C1\u65CF, and then - // creating a cell comment. - byte[] data = HexRead.readFromString("01 00 01 00 00 00 03 00 " + - "05 00 01 " + // len=5, 16bit - "A2 30 D1 30 C3 30 C1 30 CF 65 " + // character data - "00 " // padding byte - ); - RecordInputStream in = TestcaseRecordInputStream.create(NoteRecord.sid, data); - NoteRecord nr = new NoteRecord(in); - if ("\u00A2\u0030\u00D1\u0030\u00C3".equals(nr.getAuthor())) { - throw new AssertionFailedError("Identified bug in reading note with unicode author"); - } - assertEquals("\u30A2\u30D1\u30C3\u30C1\u65CF", nr.getAuthor()); - assertTrue(nr.authorIsMultibyte()); - - byte[] ser = nr.serialize(); - TestcaseRecordInputStream.confirmRecordEncoding(NoteRecord.sid, data, ser); - - // Re-check - in = TestcaseRecordInputStream.create(ser); - nr = new NoteRecord(in); - assertEquals("\u30A2\u30D1\u30C3\u30C1\u65CF", nr.getAuthor()); - assertTrue(nr.authorIsMultibyte()); - - - // Change to a non unicode author, will stop being unicode - nr.setAuthor("Simple"); - ser = nr.serialize(); - in = TestcaseRecordInputStream.create(ser); - nr = new NoteRecord(in); - - assertEquals("Simple", nr.getAuthor()); - assertFalse(nr.authorIsMultibyte()); - - // Now set it back again - nr.setAuthor("Unicode\u1234"); - ser = nr.serialize(); - in = TestcaseRecordInputStream.create(ser); - nr = new NoteRecord(in); - - assertEquals("Unicode\u1234", nr.getAuthor()); - assertTrue(nr.authorIsMultibyte()); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestNoteStructureSubRecord.java b/src/testcases/org/apache/poi/hssf/record/TestNoteStructureSubRecord.java deleted file mode 100644 index 5a4d5c887..000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestNoteStructureSubRecord.java +++ /dev/null @@ -1,67 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record; - - -import static org.junit.Assert.assertArrayEquals; -import junit.framework.TestCase; - -/** - * Tests the serialization and deserialization of the NoteRecord - * class works correctly. Test data taken directly from a real - * Excel file. - * - * @author Yegor Kozlov - */ -public final class TestNoteStructureSubRecord extends TestCase { - private final byte[] data = new byte[] { - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, (byte)0x80, 0x00, 0x00, 0x00, - 0x00, 0x00, (byte)0xBF, 0x00, 0x00, 0x00, 0x00, 0x00, (byte)0x81, 0x01, - (byte)0xCC, (byte)0xEC - }; - - public void testRead() { - - NoteStructureSubRecord record = new NoteStructureSubRecord(TestcaseRecordInputStream.create(NoteStructureSubRecord.sid, data), data.length); - - assertEquals(NoteStructureSubRecord.sid, record.getSid()); - assertEquals(data.length, record.getDataSize()); - } - - public void testWrite() { - NoteStructureSubRecord record = new NoteStructureSubRecord(); - assertEquals(NoteStructureSubRecord.sid, record.getSid()); - assertEquals(data.length, record.getDataSize()); - - byte [] ser = record.serialize(); - assertEquals(ser.length - 4, data.length); - - } - - public void testClone() - { - NoteStructureSubRecord record = new NoteStructureSubRecord(); - byte[] src = record.serialize(); - - NoteStructureSubRecord cloned = record.clone(); - byte[] cln = cloned.serialize(); - - assertEquals(record.getDataSize(), cloned.getDataSize()); - assertArrayEquals(src, cln); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestObjRecord.java b/src/testcases/org/apache/poi/hssf/record/TestObjRecord.java deleted file mode 100644 index b20dc35bf..000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestObjRecord.java +++ /dev/null @@ -1,147 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.util.List; - -import org.apache.poi.util.HexRead; -import org.junit.Test; - -/** - * Tests the serialization and deserialization of the ObjRecord class works correctly. - * Test data taken directly from a real Excel file. - */ -public final class TestObjRecord { - /** - * OBJ record data containing two sub-records. - * The data taken directly from a real Excel file. - * - * [OBJ] - * [ftCmo] - * [ftEnd] - */ - private static final byte[] recdata = HexRead.readFromString("" - + "15 00 12 00 06 00 01 00 11 60 " - + "F4 02 41 01 14 10 1F 02 00 00 " - +"00 00 00 00 00 00" - // TODO - this data seems to require two extra bytes padding. not sure where original file is. - // it's not bug 38607 attachment 17639 - ); - - /** - * Hex dump from - * offset 0x2072 in att 22076 of bug 45133 - */ - private static final byte[] recdataNeedingPadding = HexRead.readFromString("" - + "5D 00 20 00" - + "15 00 12 00 00 00 01 00 11 60 00 00 00 00 38 6F CC 03 00 00 00 00 06 00 02 00 00 00 00 00 00 00" - ); - - @Test - public void testLoad() { - ObjRecord record = new ObjRecord(TestcaseRecordInputStream.create(ObjRecord.sid, recdata)); - - assertEquals(26, record.getRecordSize() - 4); - - List subrecords = record.getSubRecords(); - assertEquals(2, subrecords.size() ); - assertTrue(subrecords.get(0) instanceof CommonObjectDataSubRecord); - assertTrue(subrecords.get(1) instanceof EndSubRecord ); - - } - - @Test - public void testStore() { - ObjRecord record = new ObjRecord(TestcaseRecordInputStream.create(ObjRecord.sid, recdata)); - - byte [] recordBytes = record.serialize(); - assertEquals(26, recordBytes.length - 4); - byte[] subData = new byte[recdata.length]; - System.arraycopy(recordBytes, 4, subData, 0, subData.length); - assertArrayEquals(recdata, subData); - } - - @Test - public void testConstruct() { - ObjRecord record = new ObjRecord(); - CommonObjectDataSubRecord ftCmo = new CommonObjectDataSubRecord(); - ftCmo.setObjectType( CommonObjectDataSubRecord.OBJECT_TYPE_COMMENT); - ftCmo.setObjectId( 1024 ); - ftCmo.setLocked( true ); - ftCmo.setPrintable( true ); - ftCmo.setAutofill( true ); - ftCmo.setAutoline( true ); - record.addSubRecord(ftCmo); - EndSubRecord ftEnd = new EndSubRecord(); - record.addSubRecord(ftEnd); - - //serialize and read again - byte [] recordBytes = record.serialize(); - //cut off the record header - byte [] bytes = new byte[recordBytes.length-4]; - System.arraycopy(recordBytes, 4, bytes, 0, bytes.length); - - record = new ObjRecord(TestcaseRecordInputStream.create(ObjRecord.sid, bytes)); - List subrecords = record.getSubRecords(); - assertEquals( 2, subrecords.size() ); - assertTrue( subrecords.get(0) instanceof CommonObjectDataSubRecord); - assertTrue( subrecords.get(1) instanceof EndSubRecord ); - } - - @Test - public void testReadWriteWithPadding_bug45133() { - ObjRecord record = new ObjRecord(TestcaseRecordInputStream.create(recdataNeedingPadding)); - - if (record.getRecordSize() == 34) { - fail("Identified bug 45133"); - } - - assertEquals(36, record.getRecordSize()); - - List subrecords = record.getSubRecords(); - assertEquals(3, subrecords.size() ); - assertEquals(CommonObjectDataSubRecord.class, subrecords.get(0).getClass()); - assertEquals(GroupMarkerSubRecord.class, subrecords.get(1).getClass()); - assertEquals(EndSubRecord.class, subrecords.get(2).getClass()); - } - - /** - * Check that ObjRecord tolerates and preserves padding to a 4-byte boundary - * (normally padding is to a 2-byte boundary). - */ - @Test - public void test4BytePadding() { - // actual data from file saved by Excel 2007 - byte[] data = HexRead.readFromString("" - + "15 00 12 00 1E 00 01 00 11 60 B4 6D 3C 01 C4 06 " - + "49 06 00 00 00 00 00 00 00 00 00 00"); - // this data seems to have 2 extra bytes of padding more than usual - // the total may have been padded to the nearest quad-byte length - RecordInputStream in = TestcaseRecordInputStream.create(ObjRecord.sid, data); - // check read OK - ObjRecord record = new ObjRecord(in); - // check that it re-serializes to the same data - byte[] ser = record.serialize(); - TestcaseRecordInputStream.confirmRecordEncoding(ObjRecord.sid, data, ser); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestPLVRecord.java b/src/testcases/org/apache/poi/hssf/record/TestPLVRecord.java deleted file mode 100644 index fce575b1c..000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestPLVRecord.java +++ /dev/null @@ -1,59 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record; - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.usermodel.DVConstraint; -import org.apache.poi.hssf.usermodel.HSSFDataValidation; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.DataValidationConstraint; -import org.apache.poi.ss.util.CellRangeAddressList; - -import java.io.InputStream; - -/** - * Verify that presence of PLV record doesn't break data - * validation, bug #53972: - * https://issues.apache.org/bugzilla/show_bug.cgi?id=53972 - * - * @author Andrew Novikov - */ - -public final class TestPLVRecord extends TestCase { - private final static String DV_DEFINITION = "$A$1:$A$5"; - private final static String XLS_FILENAME = "53972.xls"; - private final static String SHEET_NAME = "S2"; - - public void testPLVRecord() throws Exception { - InputStream is = HSSFTestDataSamples.openSampleFileStream(XLS_FILENAME); - HSSFWorkbook workbook = new HSSFWorkbook(is); - - CellRangeAddressList cellRange = new CellRangeAddressList(0, 0, 1, 1); - DataValidationConstraint constraint = DVConstraint.createFormulaListConstraint(DV_DEFINITION); - HSSFDataValidation dataValidation = new HSSFDataValidation(cellRange, constraint); - - // This used to throw an error before - try { - workbook.getSheet(SHEET_NAME).addValidationData(dataValidation); - } catch (IllegalStateException ex) { - throw new AssertionFailedError("Identified bug 53972, PLV record breaks addDataValidation()"); - } - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestPaletteRecord.java b/src/testcases/org/apache/poi/hssf/record/TestPaletteRecord.java deleted file mode 100644 index 321b6e312..000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestPaletteRecord.java +++ /dev/null @@ -1,54 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record; - -import static org.junit.Assert.assertEquals; - -import java.util.Map; -import java.util.Map.Entry; - -import org.apache.poi.hssf.util.HSSFColor; -import org.junit.Test; - -/** - * Verifies that custom palette editing works correctly - */ -public final class TestPaletteRecord { - - /** - * Tests that the default palette matches the constants of HSSFColor - */ - @Test - public void testDefaultPalette() { - PaletteRecord palette = new PaletteRecord(); - - //make sure all the HSSFColor constants match - Map colors = HSSFColor.getIndexHash(); - for (Entry entry : colors.entrySet()) { - int index = entry.getKey(); - HSSFColor c = entry.getValue(); - short[] rgbTriplet = c.getTriplet(); - byte[] paletteTriplet = palette.getColor((short) index); - String msg = "Expected HSSFColor constant to match PaletteRecord at index" + (index == c.getIndex2() ? "2" : "") + " 0x" - + Integer.toHexString(index); - assertEquals(msg, rgbTriplet[0], paletteTriplet[0] & 0xff); - assertEquals(msg, rgbTriplet[1], paletteTriplet[1] & 0xff); - assertEquals(msg, rgbTriplet[2], paletteTriplet[2] & 0xff); - } - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestPaneRecord.java b/src/testcases/org/apache/poi/hssf/record/TestPaneRecord.java deleted file mode 100644 index 93d1a1f98..000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestPaneRecord.java +++ /dev/null @@ -1,66 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record; - - -import junit.framework.TestCase; - -/** - * Tests the serialization and deserialization of the PaneRecord - * class works correctly. Test data taken directly from a real - * Excel file. - * - * @author Glen Stampoultzis (glens at apache.org) - */ -public final class TestPaneRecord extends TestCase { - byte[] data = new byte[] { - (byte)0x01, (byte)0x00, - (byte)0x02, (byte)0x00, - (byte)0x03, (byte)0x00, - (byte)0x04, (byte)0x00, - (byte)0x02, (byte)0x00, - }; - - public void testLoad() { - PaneRecord record = new PaneRecord(TestcaseRecordInputStream.create(0x41, data)); - - assertEquals( (short)1, record.getX()); - assertEquals( (short)2, record.getY()); - assertEquals( (short)3, record.getTopRow()); - assertEquals( (short)4, record.getLeftColumn()); - assertEquals( PaneRecord.ACTIVE_PANE_LOWER_LEFT, record.getActivePane()); - - assertEquals( 14, record.getRecordSize() ); - } - - public void testStore() - { - PaneRecord record = new PaneRecord(); - - record.setX( (short) 1); - record.setY( (short) 2); - record.setTopRow( (short) 3); - record.setLeftColumn( (short) 4); - record.setActivePane( PaneRecord.ACTIVE_PANE_LOWER_LEFT); - - byte [] recordBytes = record.serialize(); - assertEquals(recordBytes.length - 4, data.length); - for (int i = 0; i < data.length; i++) - assertEquals("At offset " + i, data[i], recordBytes[i+4]); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestRecalcIdRecord.java b/src/testcases/org/apache/poi/hssf/record/TestRecalcIdRecord.java deleted file mode 100644 index 868cf8e00..000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestRecalcIdRecord.java +++ /dev/null @@ -1,71 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record; - -import static org.junit.Assert.assertArrayEquals; -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -import org.apache.poi.util.HexRead; -/** - * - * @author Josh Micich - */ -public final class TestRecalcIdRecord extends TestCase { - - private static RecalcIdRecord create(byte[] data) { - RecordInputStream in = TestcaseRecordInputStream.create(RecalcIdRecord.sid, data); - RecalcIdRecord result = new RecalcIdRecord(in); - assertEquals(0, in.remaining()); - return result; - } - public void testBasicDeserializeReserialize() { - - byte[] data = HexRead.readFromString( - "C1 01" + // rt - "00 00" + // reserved - "1D EB 01 00"); // engine id - - RecalcIdRecord r = create(data); - TestcaseRecordInputStream.confirmRecordEncoding(RecalcIdRecord.sid, data, r.serialize()); - } - - public void testBadFirstField_bug48096() { - /** - * Data taken from the sample file referenced in Bugzilla 48096, file offset 0x0D45. - * The apparent problem is that the first data short field has been written with the - * wrong endianness. Excel seems to ignore whatever value is present in this - * field, and always rewrites it as (C1, 01). POI now does the same. - */ - byte[] badData = HexRead.readFromString("C1 01 08 00 01 C1 00 00 00 01 69 61"); - byte[] goodData = HexRead.readFromString("C1 01 08 00 C1 01 00 00 00 01 69 61"); - - RecordInputStream in = TestcaseRecordInputStream.create(badData); - RecalcIdRecord r; - try { - r = new RecalcIdRecord(in); - } catch (RecordFormatException e) { - if (e.getMessage().equals("expected 449 but got 49409")) { - throw new AssertionFailedError("Identified bug 48096"); - } - throw e; - } - assertEquals(0, in.remaining()); - assertArrayEquals(r.serialize(), goodData); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestRecordFactory.java b/src/testcases/org/apache/poi/hssf/record/TestRecordFactory.java deleted file mode 100644 index 5b46346bd..000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestRecordFactory.java +++ /dev/null @@ -1,240 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record; - -import static org.junit.Assert.*; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.List; - -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.util.HexRead; -import org.junit.Test; - -/** - * Tests the record factory - */ -public final class TestRecordFactory { - - - /** - * TEST NAME: Test Basic Record Construction

    - * OBJECTIVE: Test that the RecordFactory given the required parameters for know - * record types can construct the proper record w/values.

    - * SUCCESS: Record factory creates the records with the expected values.

    - * FAILURE: The wrong records are creates or contain the wrong values

    - * - */ - @Test - public void testBasicRecordConstruction() { - short recType = BOFRecord.sid; - byte[] data = { - 0, 6, 5, 0, -2, 28, -51, 7, -55, 64, 0, 0, 6, 1, 0, 0 - }; - Record[] record = RecordFactory.createRecord(TestcaseRecordInputStream.create(recType, data)); - - assertEquals(BOFRecord.class.getName(), - record[ 0 ].getClass().getName()); - BOFRecord bofRecord = ( BOFRecord ) record[ 0 ]; - - assertEquals(7422, bofRecord.getBuild()); - assertEquals(1997, bofRecord.getBuildYear()); - assertEquals(16585, bofRecord.getHistoryBitMask()); - assertEquals(20, bofRecord.getRecordSize()); - assertEquals(262, bofRecord.getRequiredVersion()); - assertEquals(2057, bofRecord.getSid()); - assertEquals(5, bofRecord.getType()); - assertEquals(1536, bofRecord.getVersion()); - recType = MMSRecord.sid; - data = new byte[] { - 0, 0 - }; - record = RecordFactory.createRecord(TestcaseRecordInputStream.create(recType, data)); - assertEquals(MMSRecord.class.getName(), - record[ 0 ].getClass().getName()); - MMSRecord mmsRecord = ( MMSRecord ) record[ 0 ]; - - assertEquals(0, mmsRecord.getAddMenuCount()); - assertEquals(0, mmsRecord.getDelMenuCount()); - assertEquals(6, mmsRecord.getRecordSize()); - assertEquals(193, mmsRecord.getSid()); - } - - /** - * TEST NAME: Test Special Record Construction

    - * OBJECTIVE: Test that the RecordFactory given the required parameters for - * constructing a RKRecord will return a NumberRecord.

    - * SUCCESS: Record factory creates the Number record with the expected values.

    - * FAILURE: The wrong records are created or contain the wrong values

    - * - */ - @Test - public void testSpecial() { - short recType = RKRecord.sid; - byte[] data = { - 0, 0, 0, 0, 21, 0, 0, 0, 0, 0 - }; - Record[] record = RecordFactory.createRecord(TestcaseRecordInputStream.create(recType, data)); - - assertEquals(NumberRecord.class.getName(), - record[ 0 ].getClass().getName()); - NumberRecord numberRecord = ( NumberRecord ) record[ 0 ]; - - assertEquals(0, numberRecord.getColumn()); - assertEquals(18, numberRecord.getRecordSize()); - assertEquals(0, numberRecord.getRow()); - assertEquals(515, numberRecord.getSid()); - assertEquals(0.0, numberRecord.getValue(), 0.001); - assertEquals(21, numberRecord.getXFIndex()); - } - - /** - * TEST NAME: Test Creating ContinueRecords After Unknown Records From An InputStream

    - * OBJECTIVE: Test that the RecordFactory given an InputStream - * constructs the expected array of records.

    - * SUCCESS: Record factory creates the expected records.

    - * FAILURE: The wrong records are created or contain the wrong values

    - */ - @Test - public void testContinuedUnknownRecord() { - byte[] data = { - 0, -1, 0, 0, // an unknown record with 0 length - 0x3C , 0, 3, 0, 1, 2, 3, // a continuation record with 3 bytes of data - 0x3C , 0, 1, 0, 4 // one more continuation record with 1 byte of data - }; - - ByteArrayInputStream bois = new ByteArrayInputStream(data); - Record[] records = RecordFactory.createRecords(bois).toArray(new Record[0]); - assertEquals("Created record count", 3, records.length); - assertEquals("1st record's type", - UnknownRecord.class.getName(), - records[ 0 ].getClass().getName()); - assertEquals("1st record's sid", (short)-256, records[0].getSid()); - assertEquals("2nd record's type", - ContinueRecord.class.getName(), - records[ 1 ].getClass().getName()); - ContinueRecord record = (ContinueRecord) records[1]; - assertEquals("2nd record's sid", 0x3C, record.getSid()); - assertEquals("1st data byte", 1, record.getData()[ 0 ]); - assertEquals("2nd data byte", 2, record.getData()[ 1 ]); - assertEquals("3rd data byte", 3, record.getData()[ 2 ]); - assertEquals("3rd record's type", - ContinueRecord.class.getName(), - records[ 2 ].getClass().getName()); - record = (ContinueRecord) records[2]; - assertEquals("3nd record's sid", 0x3C, record.getSid()); - assertEquals("4th data byte", 4, record.getData()[ 0 ]); - } - - /** - * Drawing records have a very strange continue behaviour. - * There can actually be OBJ records mixed between the continues. - * Record factory must preserve this structure when reading records. - */ - @Test - public void testMixedContinue() throws IOException { - /** - * Adapted from a real test sample file 39512.xls (Offset 0x4854). - * See Bug 39512 for details. - */ - String dump = - //OBJ - "5D 00 48 00 15 00 12 00 0C 00 3C 00 11 00 A0 2E 03 01 CC 42 " + - "CF 00 00 00 00 00 0A 00 0C 00 00 00 00 00 00 00 00 00 00 00 " + - "03 00 0B 00 06 00 28 01 03 01 00 00 12 00 08 00 00 00 00 00 " + - "00 00 03 00 11 00 04 00 3D 00 00 00 00 00 00 00 " + - //MSODRAWING - "EC 00 08 00 00 00 0D F0 00 00 00 00 " + - //TXO (and 2 trailing CONTINUE records) - "B6 01 12 00 22 02 00 00 00 00 00 00 00 00 10 00 10 00 00 00 00 00 " + - "3C 00 11 00 00 4F 70 74 69 6F 6E 20 42 75 74 74 6F 6E 20 33 39 " + - "3C 00 10 00 00 00 05 00 00 00 00 00 10 00 00 00 00 00 00 00 " + - // another CONTINUE - "3C 00 7E 00 0F 00 04 F0 7E 00 00 00 92 0C 0A F0 08 00 00 00 " + - "3D 04 00 00 00 0A 00 00 A3 00 0B F0 3C 00 00 00 7F 00 00 01 " + - "00 01 80 00 8C 01 03 01 85 00 01 00 00 00 8B 00 02 00 00 00 " + - "BF 00 08 00 1A 00 7F 01 29 00 29 00 81 01 41 00 00 08 BF 01 " + - "00 00 10 00 C0 01 40 00 00 08 FF 01 00 00 08 00 00 00 10 F0 " + - "12 00 00 00 02 00 02 00 A0 03 18 00 B5 00 04 00 30 02 1A 00 " + - "00 00 00 00 11 F0 00 00 00 00 " + - //OBJ - "5D 00 48 00 15 00 12 00 0C 00 3D 00 11 00 8C 01 03 01 C8 59 CF 00 00 " + - "00 00 00 0A 00 0C 00 00 00 00 00 00 00 00 00 00 00 03 00 0B 00 06 00 " + - "7C 16 03 01 00 00 12 00 08 00 00 00 00 00 00 00 03 00 11 00 04 00 01 " + - "00 00 00 00 00 00 00"; - byte[] data = HexRead.readFromString(dump); - - List records = RecordFactory.createRecords(new ByteArrayInputStream(data)); - assertEquals(5, records.size()); - assertTrue(records.get(0) instanceof ObjRecord); - assertTrue(records.get(1) instanceof DrawingRecord); - assertTrue(records.get(2) instanceof TextObjectRecord); - assertTrue(records.get(3) instanceof ContinueRecord); - assertTrue(records.get(4) instanceof ObjRecord); - - //serialize and verify that the serialized data is the same as the original - ByteArrayOutputStream out = new ByteArrayOutputStream(); - for(Record rec : records){ - out.write(rec.serialize()); - } - - byte[] ser = out.toByteArray(); - assertEquals(data.length, ser.length); - assertArrayEquals(data, ser); - } - - @Test - public void testNonZeroPadding_bug46987() throws IOException { - Record[] recs = { - new BOFRecord(), - new WriteAccessRecord(), // need *something* between BOF and EOF - EOFRecord.instance, - BOFRecord.createSheetBOF(), - EOFRecord.instance, - }; - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - for (Record rec : recs) { - try { - baos.write(rec.serialize()); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - //simulate the bad padding at the end of the workbook stream in attachment 23483 of bug 46987 - baos.write(0x00); - baos.write(0x11); - baos.write(0x00); - baos.write(0x02); - for (int i = 0; i < 192; i++) { - baos.write(0x00); - } - - - POIFSFileSystem fs = new POIFSFileSystem(); - fs.createDocument(new ByteArrayInputStream(baos.toByteArray()), "dummy"); - InputStream is = fs.getRoot().createDocumentInputStream("dummy"); - - List outRecs = RecordFactory.createRecords(is); - // Buffer underrun - requested 512 bytes but 192 was available - assertEquals(5, outRecs.size()); - fs.close(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestRecordFactoryInputStream.java b/src/testcases/org/apache/poi/hssf/record/TestRecordFactoryInputStream.java deleted file mode 100644 index 4cfdfcf24..000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestRecordFactoryInputStream.java +++ /dev/null @@ -1,167 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; - -import java.io.ByteArrayInputStream; - -import org.apache.poi.EncryptedDocumentException; -import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey; -import org.apache.poi.util.HexRead; -import org.junit.After; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; - -/** - * Tests for {@link RecordFactoryInputStream} - * - * @author Josh Micich - */ -public final class TestRecordFactoryInputStream { - // to not affect other tests running in the same JVM - @After - public void resetPassword() { - Biff8EncryptionKey.setCurrentUserPassword(null); - } - - /** - * Hex dump of a BOF record and most of a FILEPASS record. - * A 16 byte saltHash should be added to complete the second record - */ - private static final String COMMON_HEX_DATA = "" - // BOF - + "09 08 10 00" - + "00 06 05 00 D3 10 CC 07 01 00 00 00 00 06 00 00" - // FILEPASS - + "2F 00 36 00" - + "01 00 01 00 01 00" - + "BAADF00D BAADF00D BAADF00D BAADF00D" // docId - + "DEADBEEF DEADBEEF DEADBEEF DEADBEEF" // saltData - ; - - /** - * Hex dump of a sample WINDOW1 record - */ - private static final String SAMPLE_WINDOW1 = "3D 00 12 00" - + "00 00 00 00 40 38 55 23 38 00 00 00 00 00 01 00 58 02"; - - @Rule - public ExpectedException expectedEx = ExpectedException.none(); - - - /** - * Makes sure that a default password mismatch condition is represented with {@link EncryptedDocumentException} - */ - @Test - public void defaultPasswordWrong() { - // This encodng depends on docId, password and stream position - final String SAMPLE_WINDOW1_ENCR1 = "3D 00 12 00" - + "C4, 9B, 02, 50, 86, E0, DF, 34, FB, 57, 0E, 8C, CE, 25, 45, E3, 80, 01"; - - byte[] dataWrongDefault = HexRead.readFromString("" - + COMMON_HEX_DATA - + "00000000 00000000 00000000 00000001" - + SAMPLE_WINDOW1_ENCR1 - ); - - Biff8EncryptionKey.setCurrentUserPassword(null); - expectedEx.expect(EncryptedDocumentException.class); - expectedEx.expectMessage("Default password is invalid for salt/verifier/verifierHash"); - createRFIS(dataWrongDefault); - } - - @Test - public void defaultPasswordOK() { - // This encodng depends on docId, password and stream position - final String SAMPLE_WINDOW1_ENCR1 = "3D 00 12 00" - + "C4, 9B, 02, 50, 86, E0, DF, 34, FB, 57, 0E, 8C, CE, 25, 45, E3, 80, 01"; - - byte[] dataCorrectDefault = HexRead.readFromString("" - + COMMON_HEX_DATA - + "137BEF04 969A200B 306329DE 52254005" // correct saltHash for default password (and docId/saltHash) - + SAMPLE_WINDOW1_ENCR1 - ); - - Biff8EncryptionKey.setCurrentUserPassword(null); - RecordFactoryInputStream rfis = createRFIS(dataCorrectDefault); - confirmReadInitialRecords(rfis); - } - - - /** - * Makes sure that an incorrect user supplied password condition is represented with {@link EncryptedDocumentException} - */ - @Test - public void suppliedPasswordWrong() { - // This encoding depends on docId, password and stream position - final String SAMPLE_WINDOW1_ENCR2 = "3D 00 12 00" - + "45, B9, 90, FE, B6, C6, EC, 73, EE, 3F, 52, 45, 97, DB, E3, C1, D6, FE"; - - byte[] dataWrongDefault = HexRead.readFromString("" - + COMMON_HEX_DATA - + "00000000 00000000 00000000 00000000" - + SAMPLE_WINDOW1_ENCR2 - ); - - - Biff8EncryptionKey.setCurrentUserPassword("passw0rd"); - - expectedEx.expect(EncryptedDocumentException.class); - expectedEx.expectMessage("Supplied password is invalid for salt/verifier/verifierHash"); - createRFIS(dataWrongDefault); - } - - @Test - public void suppliedPasswordOK() { - // This encoding depends on docId, password and stream position - final String SAMPLE_WINDOW1_ENCR2 = "3D 00 12 00" - + "45, B9, 90, FE, B6, C6, EC, 73, EE, 3F, 52, 45, 97, DB, E3, C1, D6, FE"; - - Biff8EncryptionKey.setCurrentUserPassword("passw0rd"); - - byte[] dataCorrectDefault = HexRead.readFromString("" - + COMMON_HEX_DATA - + "C728659A C38E35E0 568A338F C3FC9D70" // correct saltHash for supplied password (and docId/saltHash) - + SAMPLE_WINDOW1_ENCR2 - ); - - RecordFactoryInputStream rfis = createRFIS(dataCorrectDefault); - Biff8EncryptionKey.setCurrentUserPassword(null); - - confirmReadInitialRecords(rfis); - } - - - /** - * makes sure the record stream starts with {@link BOFRecord}, {@link FilePassRecord} and then {@link WindowOneRecord} - * The third record is decrypted so this method also checks its content. - */ - private void confirmReadInitialRecords(RecordFactoryInputStream rfis) { - assertEquals(BOFRecord.class, rfis.nextRecord().getClass()); - FilePassRecord recFP = (FilePassRecord) rfis.nextRecord(); - WindowOneRecord rec1 = (WindowOneRecord) rfis.nextRecord(); - assertArrayEquals(HexRead.readFromString(SAMPLE_WINDOW1),rec1.serialize()); - } - - private static RecordFactoryInputStream createRFIS(byte[] data) { - return new RecordFactoryInputStream(new ByteArrayInputStream(data), true); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestRecordInputStream.java b/src/testcases/org/apache/poi/hssf/record/TestRecordInputStream.java deleted file mode 100644 index 518c5f047..000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestRecordInputStream.java +++ /dev/null @@ -1,105 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record; - -import org.apache.poi.util.HexRead; - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -/** - * Tests for {@link RecordInputStream} - * - * @author Josh Micich - */ -public final class TestRecordInputStream extends TestCase { - - /** - * Data inspired by attachment 22626 of bug 45866
    - * A unicode string of 18 chars, with a continue record where the compression flag changes - */ - private static final String HED_DUMP1 = "" - + "1A 59 00 8A 9E 8A " // 3 uncompressed unicode chars - + "3C 00 " // Continue sid - + "10 00 " // rec size 16 (1+15) - + "00" // next chunk is compressed - + "20 2D 20 4D 75 6C 74 69 6C 69 6E 67 75 61 6C " // 15 chars - ; - /** - * same string re-arranged - */ - private static final String HED_DUMP2 = "" - // 15 chars at end of current record - + "4D 75 6C 74 69 6C 69 6E 67 75 61 6C 20 2D 20" - + "3C 00 " // Continue sid - + "07 00 " // rec size 7 (1+6) - + "01" // this bit uncompressed - + "1A 59 00 8A 9E 8A " // 3 uncompressed unicode chars - ; - public void testChangeOfCompressionFlag_bug25866() { - byte[] changingFlagSimpleData = HexRead.readFromString("" - + "AA AA " // fake SID - + "06 00 " // first rec len 6 - + HED_DUMP1 - ); - RecordInputStream in = TestcaseRecordInputStream.create(changingFlagSimpleData); - String actual; - try { - actual = in.readUnicodeLEString(18); - } catch (IllegalArgumentException e) { - if ("compressByte in continue records must be 1 while reading unicode LE string".equals(e.getMessage())) { - throw new AssertionFailedError("Identified bug 45866"); - } - - throw e; - } - assertEquals("\u591A\u8A00\u8A9E - Multilingual", actual); - } - - public void testChangeFromUnCompressedToCompressed() { - byte[] changingFlagSimpleData = HexRead.readFromString("" - + "AA AA " // fake SID - + "0F 00 " // first rec len 15 - + HED_DUMP2 - ); - RecordInputStream in = TestcaseRecordInputStream.create(changingFlagSimpleData); - String actual = in.readCompressedUnicode(18); - assertEquals("Multilingual - \u591A\u8A00\u8A9E", actual); - } - - public void testReadString() { - byte[] changingFlagFullData = HexRead.readFromString("" - + "AA AA " // fake SID - + "12 00 " // first rec len 18 (15 + next 3 bytes) - + "12 00 " // total chars 18 - + "00 " // this bit compressed - + HED_DUMP2 - ); - RecordInputStream in = TestcaseRecordInputStream.create(changingFlagFullData); - String actual = in.readString(); - assertEquals("Multilingual - \u591A\u8A00\u8A9E", actual); - } - - public void testLeftoverDataException() { - // just ensure that the exception is created correctly, even with unknown sids - new RecordInputStream.LeftoverDataException(1, 200); - new RecordInputStream.LeftoverDataException(0, 200); - new RecordInputStream.LeftoverDataException(999999999, 200); - new RecordInputStream.LeftoverDataException(HeaderRecord.sid, 200); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestSCLRecord.java b/src/testcases/org/apache/poi/hssf/record/TestSCLRecord.java deleted file mode 100644 index 335b6605d..000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestSCLRecord.java +++ /dev/null @@ -1,56 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record; - - -import junit.framework.TestCase; - -/** - * Tests the serialization and deserialization of the SCLRecord - * class works correctly. Test data taken directly from a real - * Excel file. - * - - * @author Andrew C. Oliver (acoliver at apache.org) - */ -public final class TestSCLRecord extends TestCase { - byte[] data = new byte[] { - (byte)0x3,(byte)0x0,(byte)0x4,(byte)0x0 - }; - - public void testLoad() { - SCLRecord record = new SCLRecord(TestcaseRecordInputStream.create(0xa0, data)); - assertEquals( 3, record.getNumerator()); - assertEquals( 4, record.getDenominator()); - - assertEquals( 8, record.getRecordSize() ); - } - - public void testStore() - { - SCLRecord record = new SCLRecord(); - record.setNumerator( (short)3 ); - record.setDenominator( (short)4 ); - - - byte [] recordBytes = record.serialize(); - assertEquals(recordBytes.length - 4, data.length); - for (int i = 0; i < data.length; i++) - assertEquals("At offset " + i, data[i], recordBytes[i+4]); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestSSTDeserializer.java b/src/testcases/org/apache/poi/hssf/record/TestSSTDeserializer.java deleted file mode 100644 index c7797115a..000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestSSTDeserializer.java +++ /dev/null @@ -1,125 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record; - -import static org.junit.Assert.assertEquals; - -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.record.common.UnicodeString; -import org.apache.poi.util.HexRead; -import org.apache.poi.util.IntMapper; -import org.junit.Test; - -/** - * Exercise the SSTDeserializer class. - * - * @author Glen Stampoultzis (glens at apache.org) - */ -public final class TestSSTDeserializer { - private static final int FAKE_SID = -5555; - - private static byte[] concat(byte[] a, byte[] b) { - byte[] result = new byte[a.length + b.length]; - System.arraycopy(a, 0, result, 0, a.length); - System.arraycopy(b, 0, result, a.length, b.length); - return result; - } - - private static byte[] readSampleHexData(String sampleFileName, String sectionName, int recSid) - throws IOException { - InputStream is = HSSFTestDataSamples.openSampleFileStream(sampleFileName); - byte[] data = HexRead.readData(is, sectionName); - byte[] result = TestcaseRecordInputStream.mergeDataAndSid(recSid, data.length, data); - is.close(); - return result; - } - - @Test - public void testSpanRichTextToPlainText() throws IOException { - byte[] header = readSampleHexData("richtextdata.txt", "header", FAKE_SID); - byte[] continueBytes = readSampleHexData("richtextdata.txt", "continue1", ContinueRecord.sid); - RecordInputStream in = TestcaseRecordInputStream.create(concat(header, continueBytes)); - - - IntMapper strings = new IntMapper(); - SSTDeserializer deserializer = new SSTDeserializer( strings ); - deserializer.manufactureStrings(1, in ); - - assertEquals( "At a dinner party orAt At At ", strings.get( 0 ) + "" ); - } - - @Test - public void testContinuationWithNoOverlap() throws IOException { - byte[] header = readSampleHexData("evencontinuation.txt", "header", FAKE_SID); - byte[] continueBytes = readSampleHexData("evencontinuation.txt", "continue1", ContinueRecord.sid); - RecordInputStream in = TestcaseRecordInputStream.create(concat(header, continueBytes)); - - IntMapper strings = new IntMapper(); - SSTDeserializer deserializer = new SSTDeserializer( strings ); - deserializer.manufactureStrings( 2, in); - - assertEquals( "At a dinner party or", strings.get( 0 ) + "" ); - assertEquals( "At a dinner party", strings.get( 1 ) + "" ); - } - - /** - * Strings can actually span across more than one continuation. - */ - @Test - public void testStringAcross2Continuations() throws IOException { - byte[] header = readSampleHexData("stringacross2continuations.txt", "header", FAKE_SID); - byte[] continue1 = readSampleHexData("stringacross2continuations.txt", "continue1", ContinueRecord.sid); - byte[] continue2 = readSampleHexData("stringacross2continuations.txt", "continue2", ContinueRecord.sid); - - RecordInputStream in = TestcaseRecordInputStream.create(concat(header, concat(continue1, continue2))); - - IntMapper strings = new IntMapper(); - SSTDeserializer deserializer = new SSTDeserializer( strings ); - deserializer.manufactureStrings( 2, in); - - assertEquals( "At a dinner party or", strings.get( 0 ) + "" ); - assertEquals( "At a dinner partyAt a dinner party", strings.get( 1 ) + "" ); - } - - @Test - public void testExtendedStrings() throws IOException { - byte[] header = readSampleHexData("extendedtextstrings.txt", "rich-header", FAKE_SID); - byte[] continueBytes = readSampleHexData("extendedtextstrings.txt", "rich-continue1", ContinueRecord.sid); - RecordInputStream in = TestcaseRecordInputStream.create(concat(header, continueBytes)); - - IntMapper strings = new IntMapper(); - SSTDeserializer deserializer = new SSTDeserializer( strings ); - deserializer.manufactureStrings( 1, in); - - assertEquals( "At a dinner party orAt At At ", strings.get( 0 ) + "" ); - - - header = readSampleHexData("extendedtextstrings.txt", "norich-header", FAKE_SID); - continueBytes = readSampleHexData("extendedtextstrings.txt", "norich-continue1", ContinueRecord.sid); - in = TestcaseRecordInputStream.create(concat(header, continueBytes)); - - strings = new IntMapper(); - deserializer = new SSTDeserializer( strings ); - deserializer.manufactureStrings( 1, in); - - assertEquals( "At a dinner party orAt At At ", strings.get( 0 ) + "" ); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestSSTRecord.java b/src/testcases/org/apache/poi/hssf/record/TestSSTRecord.java deleted file mode 100644 index cd98ee084..000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestSSTRecord.java +++ /dev/null @@ -1,1523 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.Arrays; -import java.util.Iterator; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.record.common.UnicodeString; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.util.HexRead; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.LocaleUtil; -import org.junit.Test; - -import junit.framework.AssertionFailedError; - -/** - * @author Marc Johnson (mjohnson at apache dot org) - * @author Glen Stampoultzis (glens at apache.org) - */ -public final class TestSSTRecord { - - /** - * decodes hexdump files and concatenates the results - * @param hexDumpFileNames names of sample files in the hssf test data directory - * @throws IOException - */ - private static byte[] concatHexDumps(String... hexDumpFileNames) throws IOException { - int nFiles = hexDumpFileNames.length; - ByteArrayOutputStream baos = new ByteArrayOutputStream(nFiles * 8228); - for (int i = 0; i < nFiles; i++) { - String sampleFileName = hexDumpFileNames[i]; - InputStream is = HSSFTestDataSamples.openSampleFileStream(sampleFileName); - BufferedReader br = new BufferedReader(new InputStreamReader(is, LocaleUtil.CHARSET_1252)); - - while (true) { - String line = br.readLine(); - if (line == null) { - break; - } - baos.write(HexRead.readFromString(line)); - } - is.close(); - } - - return baos.toByteArray(); - } - - /** - * @param rawData serialization of one {@link SSTRecord} and zero or more {@link ContinueRecord}s - */ - private static SSTRecord createSSTFromRawData(byte[] rawData) { - RecordInputStream in = new RecordInputStream(new ByteArrayInputStream(rawData)); - in.nextRecord(); - SSTRecord result = new SSTRecord(in); - assertEquals(0, in.remaining()); - assertTrue(!in.hasNextRecord()); - return result; - } - - /** - * SST is often split over several {@link ContinueRecord}s - * @throws IOException - */ - @Test - public void testContinuedRecord() throws IOException { - byte[] origData; - SSTRecord record; - byte[] ser_output; - - origData = concatHexDumps("BigSSTRecord", "BigSSTRecordCR"); - record = createSSTFromRawData(origData); - assertEquals( 1464, record.getNumStrings() ); - assertEquals( 688, record.getNumUniqueStrings() ); - assertEquals( 688, record.countStrings() ); - ser_output = record.serialize(); - assertArrayEquals(origData, ser_output); - - // testing based on new bug report - origData = concatHexDumps("BigSSTRecord2", "BigSSTRecord2CR1", "BigSSTRecord2CR2", "BigSSTRecord2CR3", - "BigSSTRecord2CR4", "BigSSTRecord2CR5", "BigSSTRecord2CR6", "BigSSTRecord2CR7"); - record = createSSTFromRawData(origData); - - - assertEquals( 158642, record.getNumStrings() ); - assertEquals( 5249, record.getNumUniqueStrings() ); - assertEquals( 5249, record.countStrings() ); - ser_output = record.serialize(); -// if (false) { // set true to observe make sure areSameSSTs() is working -// ser_output[11000] = 'X'; -// } - - SSTRecord rec2 = createSSTFromRawData(ser_output); - if (!areSameSSTs(record, rec2)) { - throw new AssertionFailedError("large SST re-serialized incorrectly"); - } -// if (false) { -// // TODO - trivial differences in ContinueRecord break locations -// // Sample data should be checked against what most recent Excel version produces. -// // maybe tweaks are required in ContinuableRecordOutput -// assertArrayEquals(origData, ser_output); -// } - } - - private boolean areSameSSTs(SSTRecord a, SSTRecord b) { - - if (a.getNumStrings() != b.getNumStrings()) { - return false; - } - int nElems = a.getNumUniqueStrings(); - if (nElems != b.getNumUniqueStrings()) { - return false; - } - for(int i=0; i iter = record.getStrings(); - - while ( iter.hasNext() ) { - UnicodeString ucs = iter.next(); - - if ( ucs.equals( s1 ) ) - { - assertEquals( (byte) 0, ucs.getOptionFlags() ); - } - else if ( ucs.equals( s2 ) ) - { - assertEquals( (byte) 1, ucs.getOptionFlags() ); - } - else - { - fail( "cannot match string: " + ucs.getString() ); - } - } - } - - /** - * test simple constructor - */ - @Test - public void testSimpleConstructor() { - SSTRecord record = new SSTRecord(); - - assertEquals( 0, record.getNumStrings() ); - assertEquals( 0, record.getNumUniqueStrings() ); - assertEquals( 0, record.countStrings() ); - byte[] output = record.serialize(); - byte[] expected = - { - (byte) record.getSid(), (byte) ( record.getSid() >> 8 ), - (byte) 8, (byte) 0, (byte) 0, (byte) 0, (byte) 0, - (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0 - }; - - assertEquals( expected.length, output.length ); - for ( int k = 0; k < expected.length; k++ ) - { - assertEquals( String.valueOf( k ), expected[k], output[k] ); - } - } - - /** - * Tests that workbooks with rich text that duplicates a non rich text cell can be read and written. - */ - @Test - public void testReadWriteDuplicatedRichText1() throws Exception { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("duprich1.xls"); - HSSFSheet sheet = wb.getSheetAt( 1 ); - assertEquals( "01/05 (Wed)", sheet.getRow( 0 ).getCell(8 ).getStringCellValue() ); - assertEquals( "01/05 (Wed)", sheet.getRow( 1 ).getCell(8 ).getStringCellValue() ); - - HSSFTestDataSamples.writeOutAndReadBack(wb).close(); - - wb.close(); - - // test the second file. - wb = HSSFTestDataSamples.openSampleWorkbook("duprich2.xls"); - sheet = wb.getSheetAt( 0 ); - int row = 0; - assertEquals( "Testing", sheet.getRow( row++ ).getCell(0 ).getStringCellValue() ); - assertEquals( "rich", sheet.getRow( row++ ).getCell(0 ).getStringCellValue() ); - assertEquals( "text", sheet.getRow( row++ ).getCell(0 ).getStringCellValue() ); - assertEquals( "strings", sheet.getRow( row++ ).getCell(0 ).getStringCellValue() ); - assertEquals( "Testing", sheet.getRow( row++ ).getCell(0 ).getStringCellValue() ); - assertEquals( "Testing", sheet.getRow( row++ ).getCell(0 ).getStringCellValue() ); - - HSSFTestDataSamples.writeOutAndReadBack(wb).close(); - - wb.close(); - } - - /** - * hex dump from UnicodeStringFailCase1.xls atatched to Bugzilla 50779 - */ - private static final String data_50779_1 = - //Offset=0x00000612(1554) recno=71 sid=0x00FC size=0x2020(8224) - " FC 00 20 20 51 00 00 00 51 00 00 00 32 00" + - "05 10 00 00 00 42 30 44 30 46 30 48 30 4A 30 4B" + - "30 4D 30 4F 30 51 30 53 30 55 30 57 30 59 30 5B" + - "30 5D 30 5F 30 61 30 64 30 66 30 68 30 6A 30 6B" + - "30 6C 30 6D 30 6E 30 6F 30 72 30 75 30 78 30 7B" + - "30 7E 30 7F 30 80 30 81 30 82 30 84 30 86 30 88" + - "30 89 30 8A 30 8B 30 8C 30 8D 30 8F 30 92 30 93" + - "30 30 00 30 00 30 00 31 00 01 00 0C 00 05 00 35" + - "00 00 00 00 00 00 00 4B 30 32 00 01 42 30 44 30" + - "46 30 48 30 4A 30 4B 30 4D 30 4F 30 51 30 53 30" + - "55 30 57 30 59 30 5B 30 5D 30 5F 30 61 30 64 30" + - "66 30 68 30 6A 30 6B 30 6C 30 6D 30 6E 30 6F 30" + - "72 30 75 30 78 30 7B 30 7E 30 7F 30 80 30 81 30" + - "82 30 84 30 86 30 88 30 89 30 8A 30 8B 30 8C 30" + - "8D 30 8F 30 92 30 93 30 30 00 30 00 30 00 32 00" + - "32 00 01 42 30 44 30 46 30 48 30 4A 30 4B 30 4D" + - "30 4F 30 51 30 53 30 55 30 57 30 59 30 5B 30 5D" + - "30 5F 30 61 30 64 30 66 30 68 30 6A 30 6B 30 6C" + - "30 6D 30 6E 30 6F 30 72 30 75 30 78 30 7B 30 7E" + - "30 7F 30 80 30 81 30 82 30 84 30 86 30 88 30 89" + - "30 8A 30 8B 30 8C 30 8D 30 8F 30 92 30 93 30 30" + - "00 30 00 30 00 33 00 32 00 01 42 30 44 30 46 30" + - "48 30 4A 30 4B 30 4D 30 4F 30 51 30 53 30 55 30" + - "57 30 59 30 5B 30 5D 30 5F 30 61 30 64 30 66 30" + - "68 30 6A 30 6B 30 6C 30 6D 30 6E 30 6F 30 72 30" + - "75 30 78 30 7B 30 7E 30 7F 30 80 30 81 30 82 30" + - "84 30 86 30 88 30 89 30 8A 30 8B 30 8C 30 8D 30" + - "8F 30 92 30 93 30 30 00 30 00 30 00 34 00 32 00" + - "01 42 30 44 30 46 30 48 30 4A 30 4B 30 4D 30 4F" + - "30 51 30 53 30 55 30 57 30 59 30 5B 30 5D 30 5F" + - "30 61 30 64 30 66 30 68 30 6A 30 6B 30 6C 30 6D" + - "30 6E 30 6F 30 72 30 75 30 78 30 7B 30 7E 30 7F" + - "30 80 30 81 30 82 30 84 30 86 30 88 30 89 30 8A" + - "30 8B 30 8C 30 8D 30 8F 30 92 30 93 30 30 00 30" + - "00 30 00 35 00 32 00 01 42 30 44 30 46 30 48 30" + - "4A 30 4B 30 4D 30 4F 30 51 30 53 30 55 30 57 30" + - "59 30 5B 30 5D 30 5F 30 61 30 64 30 66 30 68 30" + - "6A 30 6B 30 6C 30 6D 30 6E 30 6F 30 72 30 75 30" + - "78 30 7B 30 7E 30 7F 30 80 30 81 30 82 30 84 30" + - "86 30 88 30 89 30 8A 30 8B 30 8C 30 8D 30 8F 30" + - "92 30 93 30 30 00 30 00 30 00 36 00 32 00 01 42" + - "30 44 30 46 30 48 30 4A 30 4B 30 4D 30 4F 30 51" + - "30 53 30 55 30 57 30 59 30 5B 30 5D 30 5F 30 61" + - "30 64 30 66 30 68 30 6A 30 6B 30 6C 30 6D 30 6E" + - "30 6F 30 72 30 75 30 78 30 7B 30 7E 30 7F 30 80" + - "30 81 30 82 30 84 30 86 30 88 30 89 30 8A 30 8B" + - "30 8C 30 8D 30 8F 30 92 30 93 30 30 00 30 00 30" + - "00 37 00 32 00 01 42 30 44 30 46 30 48 30 4A 30" + - "4B 30 4D 30 4F 30 51 30 53 30 55 30 57 30 59 30" + - "5B 30 5D 30 5F 30 61 30 64 30 66 30 68 30 6A 30" + - "6B 30 6C 30 6D 30 6E 30 6F 30 72 30 75 30 78 30" + - "7B 30 7E 30 7F 30 80 30 81 30 82 30 84 30 86 30" + - "88 30 89 30 8A 30 8B 30 8C 30 8D 30 8F 30 92 30" + - "93 30 30 00 30 00 30 00 38 00 32 00 01 42 30 44" + - "30 46 30 48 30 4A 30 4B 30 4D 30 4F 30 51 30 53" + - "30 55 30 57 30 59 30 5B 30 5D 30 5F 30 61 30 64" + - "30 66 30 68 30 6A 30 6B 30 6C 30 6D 30 6E 30 6F" + - "30 72 30 75 30 78 30 7B 30 7E 30 7F 30 80 30 81" + - "30 82 30 84 30 86 30 88 30 89 30 8A 30 8B 30 8C" + - "30 8D 30 8F 30 92 30 93 30 30 00 30 00 30 00 39" + - "00 32 00 01 42 30 44 30 46 30 48 30 4A 30 4B 30" + - "4D 30 4F 30 51 30 53 30 55 30 57 30 59 30 5B 30" + - "5D 30 5F 30 61 30 64 30 66 30 68 30 6A 30 6B 30" + - "6C 30 6D 30 6E 30 6F 30 72 30 75 30 78 30 7B 30" + - "7E 30 7F 30 80 30 81 30 82 30 84 30 86 30 88 30" + - "89 30 8A 30 8B 30 8C 30 8D 30 8F 30 92 30 93 30" + - "30 00 30 00 31 00 30 00 32 00 01 42 30 44 30 46" + - "30 48 30 4A 30 4B 30 4D 30 4F 30 51 30 53 30 55" + - "30 57 30 59 30 5B 30 5D 30 5F 30 61 30 64 30 66" + - "30 68 30 6A 30 6B 30 6C 30 6D 30 6E 30 6F 30 72" + - "30 75 30 78 30 7B 30 7E 30 7F 30 80 30 81 30 82" + - "30 84 30 86 30 88 30 89 30 8A 30 8B 30 8C 30 8D" + - "30 8F 30 92 30 93 30 30 00 30 00 31 00 31 00 32" + - "00 01 42 30 44 30 46 30 48 30 4A 30 4B 30 4D 30" + - "4F 30 51 30 53 30 55 30 57 30 59 30 5B 30 5D 30" + - "5F 30 61 30 64 30 66 30 68 30 6A 30 6B 30 6C 30" + - "6D 30 6E 30 6F 30 72 30 75 30 78 30 7B 30 7E 30" + - "7F 30 80 30 81 30 82 30 84 30 86 30 88 30 89 30" + - "8A 30 8B 30 8C 30 8D 30 8F 30 92 30 93 30 30 00" + - "30 00 31 00 32 00 32 00 01 42 30 44 30 46 30 48" + - "30 4A 30 4B 30 4D 30 4F 30 51 30 53 30 55 30 57" + - "30 59 30 5B 30 5D 30 5F 30 61 30 64 30 66 30 68" + - "30 6A 30 6B 30 6C 30 6D 30 6E 30 6F 30 72 30 75" + - "30 78 30 7B 30 7E 30 7F 30 80 30 81 30 82 30 84" + - "30 86 30 88 30 89 30 8A 30 8B 30 8C 30 8D 30 8F" + - "30 92 30 93 30 30 00 30 00 31 00 33 00 32 00 01" + - "42 30 44 30 46 30 48 30 4A 30 4B 30 4D 30 4F 30" + - "51 30 53 30 55 30 57 30 59 30 5B 30 5D 30 5F 30" + - "61 30 64 30 66 30 68 30 6A 30 6B 30 6C 30 6D 30" + - "6E 30 6F 30 72 30 75 30 78 30 7B 30 7E 30 7F 30" + - "80 30 81 30 82 30 84 30 86 30 88 30 89 30 8A 30" + - "8B 30 8C 30 8D 30 8F 30 92 30 93 30 30 00 30 00" + - "31 00 34 00 32 00 01 42 30 44 30 46 30 48 30 4A" + - "30 4B 30 4D 30 4F 30 51 30 53 30 55 30 57 30 59" + - "30 5B 30 5D 30 5F 30 61 30 64 30 66 30 68 30 6A" + - "30 6B 30 6C 30 6D 30 6E 30 6F 30 72 30 75 30 78" + - "30 7B 30 7E 30 7F 30 80 30 81 30 82 30 84 30 86" + - "30 88 30 89 30 8A 30 8B 30 8C 30 8D 30 8F 30 92" + - "30 93 30 30 00 30 00 31 00 35 00 32 00 01 42 30" + - "44 30 46 30 48 30 4A 30 4B 30 4D 30 4F 30 51 30" + - "53 30 55 30 57 30 59 30 5B 30 5D 30 5F 30 61 30" + - "64 30 66 30 68 30 6A 30 6B 30 6C 30 6D 30 6E 30" + - "6F 30 72 30 75 30 78 30 7B 30 7E 30 7F 30 80 30" + - "81 30 82 30 84 30 86 30 88 30 89 30 8A 30 8B 30" + - "8C 30 8D 30 8F 30 92 30 93 30 30 00 30 00 31 00" + - "36 00 32 00 01 42 30 44 30 46 30 48 30 4A 30 4B" + - "30 4D 30 4F 30 51 30 53 30 55 30 57 30 59 30 5B" + - "30 5D 30 5F 30 61 30 64 30 66 30 68 30 6A 30 6B" + - "30 6C 30 6D 30 6E 30 6F 30 72 30 75 30 78 30 7B" + - "30 7E 30 7F 30 80 30 81 30 82 30 84 30 86 30 88" + - "30 89 30 8A 30 8B 30 8C 30 8D 30 8F 30 92 30 93" + - "30 30 00 30 00 31 00 37 00 32 00 01 42 30 44 30" + - "46 30 48 30 4A 30 4B 30 4D 30 4F 30 51 30 53 30" + - "55 30 57 30 59 30 5B 30 5D 30 5F 30 61 30 64 30" + - "66 30 68 30 6A 30 6B 30 6C 30 6D 30 6E 30 6F 30" + - "72 30 75 30 78 30 7B 30 7E 30 7F 30 80 30 81 30" + - "82 30 84 30 86 30 88 30 89 30 8A 30 8B 30 8C 30" + - "8D 30 8F 30 92 30 93 30 30 00 30 00 31 00 38 00" + - "32 00 01 42 30 44 30 46 30 48 30 4A 30 4B 30 4D" + - "30 4F 30 51 30 53 30 55 30 57 30 59 30 5B 30 5D" + - "30 5F 30 61 30 64 30 66 30 68 30 6A 30 6B 30 6C" + - "30 6D 30 6E 30 6F 30 72 30 75 30 78 30 7B 30 7E" + - "30 7F 30 80 30 81 30 82 30 84 30 86 30 88 30 89" + - "30 8A 30 8B 30 8C 30 8D 30 8F 30 92 30 93 30 30" + - "00 30 00 31 00 39 00 32 00 01 42 30 44 30 46 30" + - "48 30 4A 30 4B 30 4D 30 4F 30 51 30 53 30 55 30" + - "57 30 59 30 5B 30 5D 30 5F 30 61 30 64 30 66 30" + - "68 30 6A 30 6B 30 6C 30 6D 30 6E 30 6F 30 72 30" + - "75 30 78 30 7B 30 7E 30 7F 30 80 30 81 30 82 30" + - "84 30 86 30 88 30 89 30 8A 30 8B 30 8C 30 8D 30" + - "8F 30 92 30 93 30 30 00 30 00 32 00 30 00 32 00" + - "01 42 30 44 30 46 30 48 30 4A 30 4B 30 4D 30 4F" + - "30 51 30 53 30 55 30 57 30 59 30 5B 30 5D 30 5F" + - "30 61 30 64 30 66 30 68 30 6A 30 6B 30 6C 30 6D" + - "30 6E 30 6F 30 72 30 75 30 78 30 7B 30 7E 30 7F" + - "30 80 30 81 30 82 30 84 30 86 30 88 30 89 30 8A" + - "30 8B 30 8C 30 8D 30 8F 30 92 30 93 30 30 00 30" + - "00 32 00 31 00 32 00 01 42 30 44 30 46 30 48 30" + - "4A 30 4B 30 4D 30 4F 30 51 30 53 30 55 30 57 30" + - "59 30 5B 30 5D 30 5F 30 61 30 64 30 66 30 68 30" + - "6A 30 6B 30 6C 30 6D 30 6E 30 6F 30 72 30 75 30" + - "78 30 7B 30 7E 30 7F 30 80 30 81 30 82 30 84 30" + - "86 30 88 30 89 30 8A 30 8B 30 8C 30 8D 30 8F 30" + - "92 30 93 30 30 00 30 00 32 00 32 00 32 00 01 42" + - "30 44 30 46 30 48 30 4A 30 4B 30 4D 30 4F 30 51" + - "30 53 30 55 30 57 30 59 30 5B 30 5D 30 5F 30 61" + - "30 64 30 66 30 68 30 6A 30 6B 30 6C 30 6D 30 6E" + - "30 6F 30 72 30 75 30 78 30 7B 30 7E 30 7F 30 80" + - "30 81 30 82 30 84 30 86 30 88 30 89 30 8A 30 8B" + - "30 8C 30 8D 30 8F 30 92 30 93 30 30 00 30 00 32" + - "00 33 00 32 00 01 42 30 44 30 46 30 48 30 4A 30" + - "4B 30 4D 30 4F 30 51 30 53 30 55 30 57 30 59 30" + - "5B 30 5D 30 5F 30 61 30 64 30 66 30 68 30 6A 30" + - "6B 30 6C 30 6D 30 6E 30 6F 30 72 30 75 30 78 30" + - "7B 30 7E 30 7F 30 80 30 81 30 82 30 84 30 86 30" + - "88 30 89 30 8A 30 8B 30 8C 30 8D 30 8F 30 92 30" + - "93 30 30 00 30 00 32 00 34 00 32 00 01 42 30 44" + - "30 46 30 48 30 4A 30 4B 30 4D 30 4F 30 51 30 53" + - "30 55 30 57 30 59 30 5B 30 5D 30 5F 30 61 30 64" + - "30 66 30 68 30 6A 30 6B 30 6C 30 6D 30 6E 30 6F" + - "30 72 30 75 30 78 30 7B 30 7E 30 7F 30 80 30 81" + - "30 82 30 84 30 86 30 88 30 89 30 8A 30 8B 30 8C" + - "30 8D 30 8F 30 92 30 93 30 30 00 30 00 32 00 35" + - "00 32 00 01 42 30 44 30 46 30 48 30 4A 30 4B 30" + - "4D 30 4F 30 51 30 53 30 55 30 57 30 59 30 5B 30" + - "5D 30 5F 30 61 30 64 30 66 30 68 30 6A 30 6B 30" + - "6C 30 6D 30 6E 30 6F 30 72 30 75 30 78 30 7B 30" + - "7E 30 7F 30 80 30 81 30 82 30 84 30 86 30 88 30" + - "89 30 8A 30 8B 30 8C 30 8D 30 8F 30 92 30 93 30" + - "30 00 30 00 32 00 36 00 32 00 01 42 30 44 30 46" + - "30 48 30 4A 30 4B 30 4D 30 4F 30 51 30 53 30 55" + - "30 57 30 59 30 5B 30 5D 30 5F 30 61 30 64 30 66" + - "30 68 30 6A 30 6B 30 6C 30 6D 30 6E 30 6F 30 72" + - "30 75 30 78 30 7B 30 7E 30 7F 30 80 30 81 30 82" + - "30 84 30 86 30 88 30 89 30 8A 30 8B 30 8C 30 8D" + - "30 8F 30 92 30 93 30 30 00 30 00 32 00 37 00 32" + - "00 01 42 30 44 30 46 30 48 30 4A 30 4B 30 4D 30" + - "4F 30 51 30 53 30 55 30 57 30 59 30 5B 30 5D 30" + - "5F 30 61 30 64 30 66 30 68 30 6A 30 6B 30 6C 30" + - "6D 30 6E 30 6F 30 72 30 75 30 78 30 7B 30 7E 30" + - "7F 30 80 30 81 30 82 30 84 30 86 30 88 30 89 30" + - "8A 30 8B 30 8C 30 8D 30 8F 30 92 30 93 30 30 00" + - "30 00 32 00 38 00 32 00 01 42 30 44 30 46 30 48" + - "30 4A 30 4B 30 4D 30 4F 30 51 30 53 30 55 30 57" + - "30 59 30 5B 30 5D 30 5F 30 61 30 64 30 66 30 68" + - "30 6A 30 6B 30 6C 30 6D 30 6E 30 6F 30 72 30 75" + - "30 78 30 7B 30 7E 30 7F 30 80 30 81 30 82 30 84" + - "30 86 30 88 30 89 30 8A 30 8B 30 8C 30 8D 30 8F" + - "30 92 30 93 30 30 00 30 00 32 00 39 00 32 00 01" + - "42 30 44 30 46 30 48 30 4A 30 4B 30 4D 30 4F 30" + - "51 30 53 30 55 30 57 30 59 30 5B 30 5D 30 5F 30" + - "61 30 64 30 66 30 68 30 6A 30 6B 30 6C 30 6D 30" + - "6E 30 6F 30 72 30 75 30 78 30 7B 30 7E 30 7F 30" + - "80 30 81 30 82 30 84 30 86 30 88 30 89 30 8A 30" + - "8B 30 8C 30 8D 30 8F 30 92 30 93 30 30 00 30 00" + - "33 00 30 00 32 00 01 42 30 44 30 46 30 48 30 4A" + - "30 4B 30 4D 30 4F 30 51 30 53 30 55 30 57 30 59" + - "30 5B 30 5D 30 5F 30 61 30 64 30 66 30 68 30 6A" + - "30 6B 30 6C 30 6D 30 6E 30 6F 30 72 30 75 30 78" + - "30 7B 30 7E 30 7F 30 80 30 81 30 82 30 84 30 86" + - "30 88 30 89 30 8A 30 8B 30 8C 30 8D 30 8F 30 92" + - "30 93 30 30 00 30 00 33 00 31 00 32 00 01 42 30" + - "44 30 46 30 48 30 4A 30 4B 30 4D 30 4F 30 51 30" + - "53 30 55 30 57 30 59 30 5B 30 5D 30 5F 30 61 30" + - "64 30 66 30 68 30 6A 30 6B 30 6C 30 6D 30 6E 30" + - "6F 30 72 30 75 30 78 30 7B 30 7E 30 7F 30 80 30" + - "81 30 82 30 84 30 86 30 88 30 89 30 8A 30 8B 30" + - "8C 30 8D 30 8F 30 92 30 93 30 30 00 30 00 33 00" + - "32 00 32 00 01 42 30 44 30 46 30 48 30 4A 30 4B" + - "30 4D 30 4F 30 51 30 53 30 55 30 57 30 59 30 5B" + - "30 5D 30 5F 30 61 30 64 30 66 30 68 30 6A 30 6B" + - "30 6C 30 6D 30 6E 30 6F 30 72 30 75 30 78 30 7B" + - "30 7E 30 7F 30 80 30 81 30 82 30 84 30 86 30 88" + - "30 89 30 8A 30 8B 30 8C 30 8D 30 8F 30 92 30 93" + - "30 30 00 30 00 33 00 33 00 32 00 01 42 30 44 30" + - "46 30 48 30 4A 30 4B 30 4D 30 4F 30 51 30 53 30" + - "55 30 57 30 59 30 5B 30 5D 30 5F 30 61 30 64 30" + - "66 30 68 30 6A 30 6B 30 6C 30 6D 30 6E 30 6F 30" + - "72 30 75 30 78 30 7B 30 7E 30 7F 30 80 30 81 30" + - "82 30 84 30 86 30 88 30 89 30 8A 30 8B 30 8C 30" + - "8D 30 8F 30 92 30 93 30 30 00 30 00 33 00 34 00" + - "32 00 01 42 30 44 30 46 30 48 30 4A 30 4B 30 4D" + - "30 4F 30 51 30 53 30 55 30 57 30 59 30 5B 30 5D" + - "30 5F 30 61 30 64 30 66 30 68 30 6A 30 6B 30 6C" + - "30 6D 30 6E 30 6F 30 72 30 75 30 78 30 7B 30 7E" + - "30 7F 30 80 30 81 30 82 30 84 30 86 30 88 30 89" + - "30 8A 30 8B 30 8C 30 8D 30 8F 30 92 30 93 30 30" + - "00 30 00 33 00 35 00 32 00 01 42 30 44 30 46 30" + - "48 30 4A 30 4B 30 4D 30 4F 30 51 30 53 30 55 30" + - "57 30 59 30 5B 30 5D 30 5F 30 61 30 64 30 66 30" + - "68 30 6A 30 6B 30 6C 30 6D 30 6E 30 6F 30 72 30" + - "75 30 78 30 7B 30 7E 30 7F 30 80 30 81 30 82 30" + - "84 30 86 30 88 30 89 30 8A 30 8B 30 8C 30 8D 30" + - "8F 30 92 30 93 30 30 00 30 00 33 00 36 00 32 00" + - "01 42 30 44 30 46 30 48 30 4A 30 4B 30 4D 30 4F" + - "30 51 30 53 30 55 30 57 30 59 30 5B 30 5D 30 5F" + - "30 61 30 64 30 66 30 68 30 6A 30 6B 30 6C 30 6D" + - "30 6E 30 6F 30 72 30 75 30 78 30 7B 30 7E 30 7F" + - "30 80 30 81 30 82 30 84 30 86 30 88 30 89 30 8A" + - "30 8B 30 8C 30 8D 30 8F 30 92 30 93 30 30 00 30" + - "00 33 00 37 00 32 00 01 42 30 44 30 46 30 48 30" + - "4A 30 4B 30 4D 30 4F 30 51 30 53 30 55 30 57 30" + - "59 30 5B 30 5D 30 5F 30 61 30 64 30 66 30 68 30" + - "6A 30 6B 30 6C 30 6D 30 6E 30 6F 30 72 30 75 30" + - "78 30 7B 30 7E 30 7F 30 80 30 81 30 82 30 84 30" + - "86 30 88 30 89 30 8A 30 8B 30 8C 30 8D 30 8F 30" + - "92 30 93 30 30 00 30 00 33 00 38 00 32 00 01 42" + - "30 44 30 46 30 48 30 4A 30 4B 30 4D 30 4F 30 51" + - "30 53 30 55 30 57 30 59 30 5B 30 5D 30 5F 30 61" + - "30 64 30 66 30 68 30 6A 30 6B 30 6C 30 6D 30 6E" + - "30 6F 30 72 30 75 30 78 30 7B 30 7E 30 7F 30 80" + - "30 81 30 82 30 84 30 86 30 88 30 89 30 8A 30 8B" + - "30 8C 30 8D 30 8F 30 92 30 93 30 30 00 30 00 33" + - "00 39 00 32 00 01 42 30 44 30 46 30 48 30 4A 30" + - "4B 30 4D 30 4F 30 51 30 53 30 55 30 57 30 59 30" + - "5B 30 5D 30 5F 30 61 30 64 30 66 30 68 30 6A 30" + - "6B 30 6C 30 6D 30 6E 30 6F 30 72 30 75 30 78 30" + - "7B 30 7E 30 7F 30 80 30 81 30 82 30 84 30 86 30" + - "88 30 89 30 8A 30 8B 30 8C 30 8D 30 8F 30 92 30" + - "93 30 30 00 30 00 34 00 30 00 32 00 01 42 30 44" + - "30 46 30 48 30 4A 30 4B 30 4D 30 4F 30 51 30 53" + - "30 55 30 57 30 59 30 5B 30 5D 30 5F 30 61 30 64" + - "30 66 30 68 30 6A 30 6B 30 6C 30 6D 30 6E 30 6F" + - "30 72 30 75 30 78 30 7B 30 7E 30 7F 30 80 30 81" + - "30 82 30 84 30 86 30 88 30 89 30 8A 30 8B 30 8C" + - "30 8D 30 8F 30 92 30 93 30 30 00 30 00 34 00 31" + - "00 32 00 01 42 30 44 30 46 30 48 30 4A 30 4B 30" + - "4D 30 4F 30 51 30 53 30 55 30 57 30 59 30 5B 30" + - "5D 30 5F 30 61 30 64 30 66 30 68 30 6A 30 6B 30" + - "6C 30 6D 30 6E 30 6F 30 72 30 75 30 78 30 7B 30" + - "7E 30 7F 30 80 30 81 30 82 30 84 30 86 30 88 30" + - "89 30 8A 30 8B 30 8C 30 8D 30 8F 30 92 30 93 30" + - "30 00 30 00 34 00 32 00 32 00 01 42 30 44 30 46" + - "30 48 30 4A 30 4B 30 4D 30 4F 30 51 30 53 30 55" + - "30 57 30 59 30 5B 30 5D 30 5F 30 61 30 64 30 66" + - "30 68 30 6A 30 6B 30 6C 30 6D 30 6E 30 6F 30 72" + - "30 75 30 78 30 7B 30 7E 30 7F 30 80 30 81 30 82" + - "30 84 30 86 30 88 30 89 30 8A 30 8B 30 8C 30 8D" + - "30 8F 30 92 30 93 30 30 00 30 00 34 00 33 00 32" + - "00 01 42 30 44 30 46 30 48 30 4A 30 4B 30 4D 30" + - "4F 30 51 30 53 30 55 30 57 30 59 30 5B 30 5D 30" + - "5F 30 61 30 64 30 66 30 68 30 6A 30 6B 30 6C 30" + - "6D 30 6E 30 6F 30 72 30 75 30 78 30 7B 30 7E 30" + - "7F 30 80 30 81 30 82 30 84 30 86 30 88 30 89 30" + - "8A 30 8B 30 8C 30 8D 30 8F 30 92 30 93 30 30 00" + - "30 00 34 00 34 00 32 00 01 42 30 44 30 46 30 48" + - "30 4A 30 4B 30 4D 30 4F 30 51 30 53 30 55 30 57" + - "30 59 30 5B 30 5D 30 5F 30 61 30 64 30 66 30 68" + - "30 6A 30 6B 30 6C 30 6D 30 6E 30 6F 30 72 30 75" + - "30 78 30 7B 30 7E 30 7F 30 80 30 81 30 82 30 84" + - "30 86 30 88 30 89 30 8A 30 8B 30 8C 30 8D 30 8F" + - "30 92 30 93 30 30 00 30 00 34 00 35 00 32 00 01" + - "42 30 44 30 46 30 48 30 4A 30 4B 30 4D 30 4F 30" + - "51 30 53 30 55 30 57 30 59 30 5B 30 5D 30 5F 30" + - "61 30 64 30 66 30 68 30 6A 30 6B 30 6C 30 6D 30" + - "6E 30 6F 30 72 30 75 30 78 30 7B 30 7E 30 7F 30" + - "80 30 81 30 82 30 84 30 86 30 88 30 89 30 8A 30" + - "8B 30 8C 30 8D 30 8F 30 92 30 93 30 30 00 30 00" + - "34 00 36 00 32 00 01 42 30 44 30 46 30 48 30 4A" + - "30 4B 30 4D 30 4F 30 51 30 53 30 55 30 57 30 59" + - "30 5B 30 5D 30 5F 30 61 30 64 30 66 30 68 30 6A" + - "30 6B 30 6C 30 6D 30 6E 30 6F 30 72 30 75 30 78" + - "30 7B 30 7E 30 7F 30 80 30 81 30 82 30 84 30 86" + - "30 88 30 89 30 8A 30 8B 30 8C 30 8D 30 8F 30 92" + - "30 93 30 30 00 30 00 34 00 37 00 32 00 01 42 30" + - "44 30 46 30 48 30 4A 30 4B 30 4D 30 4F 30 51 30" + - "53 30 55 30 57 30 59 30 5B 30 5D 30 5F 30 61 30" + - "64 30 66 30 68 30 6A 30 6B 30 6C 30 6D 30 6E 30" + - "6F 30 72 30 75 30 78 30 7B 30 7E 30 7F 30 80 30" + - "81 30 82 30 84 30 86 30 88 30 89 30 8A 30 8B 30" + - "8C 30 8D 30 8F 30 92 30 93 30 30 00 30 00 34 00" + - "38 00 32 00 01 42 30 44 30 46 30 48 30 4A 30 4B" + - "30 4D 30 4F 30 51 30 53 30 55 30 57 30 59 30 5B" + - "30 5D 30 5F 30 61 30 64 30 66 30 68 30 6A 30 6B" + - "30 6C 30 6D 30 6E 30 6F 30 72 30 75 30 78 30 7B" + - "30 7E 30 7F 30 80 30 81 30 82 30 84 30 86 30 88" + - "30 89 30 8A 30 8B 30 8C 30 8D 30 8F 30 92 30 93" + - "30 30 00 30 00 34 00 39 00 32 00 01 42 30 44 30" + - "46 30 48 30 4A 30 4B 30 4D 30 4F 30 51 30 53 30" + - "55 30 57 30 59 30 5B 30 5D 30 5F 30 61 30 64 30" + - "66 30 68 30 6A 30 6B 30 6C 30 6D 30 6E 30 6F 30" + - "72 30 75 30 78 30 7B 30 7E 30 7F 30 80 30 81 30" + - "82 30 84 30 86 30 88 30 89 30 8A 30 8B 30 8C 30" + - "8D 30 8F 30 92 30 93 30 30 00 30 00 35 00 30 00" + - "32 00 01 42 30 44 30 46 30 48 30 4A 30 4B 30 4D" + - "30 4F 30 51 30 53 30 55 30 57 30 59 30 5B 30 5D" + - "30 5F 30 61 30 64 30 66 30 68 30 6A 30 6B 30 6C" + - "30 6D 30 6E 30 6F 30 72 30 75 30 78 30 7B 30 7E" + - "30 7F 30 80 30 81 30 82 30 84 30 86 30 88 30 89" + - "30 8A 30 8B 30 8C 30 8D 30 8F 30 92 30 93 30 30" + - "00 30 00 35 00 31 00 32 00 01 42 30 44 30 46 30" + - "48 30 4A 30 4B 30 4D 30 4F 30 51 30 53 30 55 30" + - "57 30 59 30 5B 30 5D 30 5F 30 61 30 64 30 66 30" + - "68 30 6A 30 6B 30 6C 30 6D 30 6E 30 6F 30 72 30" + - "75 30 78 30 7B 30 7E 30 7F 30 80 30 81 30 82 30" + - "84 30 86 30 88 30 89 30 8A 30 8B 30 8C 30 8D 30" + - "8F 30 92 30 93 30 30 00 30 00 35 00 32 00 32 00" + - "01 42 30 44 30 46 30 48 30 4A 30 4B 30 4D 30 4F" + - "30 51 30 53 30 55 30 57 30 59 30 5B 30 5D 30 5F" + - "30 61 30 64 30 66 30 68 30 6A 30 6B 30 6C 30 6D" + - "30 6E 30 6F 30 72 30 75 30 78 30 7B 30 7E 30 7F" + - "30 80 30 81 30 82 30 84 30 86 30 88 30 89 30 8A" + - "30 8B 30 8C 30 8D 30 8F 30 92 30 93 30 30 00 30" + - "00 35 00 33 00 32 00 01 42 30 44 30 46 30 48 30" + - "4A 30 4B 30 4D 30 4F 30 51 30 53 30 55 30 57 30" + - "59 30 5B 30 5D 30 5F 30 61 30 64 30 66 30 68 30" + - "6A 30 6B 30 6C 30 6D 30 6E 30 6F 30 72 30 75 30" + - "78 30 7B 30 7E 30 7F 30 80 30 81 30 82 30 84 30" + - "86 30 88 30 89 30 8A 30 8B 30 8C 30 8D 30 8F 30" + - "92 30 93 30 30 00 30 00 35 00 34 00 32 00 01 42" + - "30 44 30 46 30 48 30 4A 30 4B 30 4D 30 4F 30 51" + - "30 53 30 55 30 57 30 59 30 5B 30 5D 30 5F 30 61" + - "30 64 30 66 30 68 30 6A 30 6B 30 6C 30 6D 30 6E" + - "30 6F 30 72 30 75 30 78 30 7B 30 7E 30 7F 30 80" + - "30 81 30 82 30 84 30 86 30 88 30 89 30 8A 30 8B" + - "30 8C 30 8D 30 8F 30 92 30 93 30 30 00 30 00 35" + - "00 35 00 32 00 01 42 30 44 30 46 30 48 30 4A 30" + - "4B 30 4D 30 4F 30 51 30 53 30 55 30 57 30 59 30" + - "5B 30 5D 30 5F 30 61 30 64 30 66 30 68 30 6A 30" + - "6B 30 6C 30 6D 30 6E 30 6F 30 72 30 75 30 78 30" + - "7B 30 7E 30 7F 30 80 30 81 30 82 30 84 30 86 30" + - "88 30 89 30 8A 30 8B 30 8C 30 8D 30 8F 30 92 30" + - "93 30 30 00 30 00 35 00 36 00 32 00 01 42 30 44" + - "30 46 30 48 30 4A 30 4B 30 4D 30 4F 30 51 30 53" + - "30 55 30 57 30 59 30 5B 30 5D 30 5F 30 61 30 64" + - "30 66 30 68 30 6A 30 6B 30 6C 30 6D 30 6E 30 6F" + - "30 72 30 75 30 78 30 7B 30 7E 30 7F 30 80 30 81" + - "30 82 30 84 30 86 30 88 30 89 30 8A 30 8B 30 8C" + - "30 8D 30 8F 30 92 30 93 30 30 00 30 00 35 00 37" + - "00 32 00 01 42 30 44 30 46 30 48 30 4A 30 4B 30" + - "4D 30 4F 30 51 30 53 30 55 30 57 30 59 30 5B 30" + - "5D 30 5F 30 61 30 64 30 66 30 68 30 6A 30 6B 30" + - "6C 30 6D 30 6E 30 6F 30 72 30 75 30 78 30 7B 30" + - "7E 30 7F 30 80 30 81 30 82 30 84 30 86 30 88 30" + - "89 30 8A 30 8B 30 8C 30 8D 30 8F 30 92 30 93 30" + - "30 00 30 00 35 00 38 00 32 00 01 42 30 44 30 46" + - "30 48 30 4A 30 4B 30 4D 30 4F 30 51 30 53 30 55" + - "30 57 30 59 30 5B 30 5D 30 5F 30 61 30 64 30 66" + - "30 68 30 6A 30 6B 30 6C 30 6D 30 6E 30 6F 30 72" + - "30 75 30 78 30 7B 30 7E 30 7F 30 80 30 81 30 82" + - "30 84 30 86 30 88 30 89 30 8A 30 8B 30 8C 30 8D" + - "30 8F 30 92 30 93 30 30 00 30 00 35 00 39 00 32" + - "00 01 42 30 44 30 46 30 48 30 4A 30 4B 30 4D 30" + - "4F 30 51 30 53 30 55 30 57 30 59 30 5B 30 5D 30" + - "5F 30 61 30 64 30 66 30 68 30 6A 30 6B 30 6C 30" + - "6D 30 6E 30 6F 30 72 30 75 30 78 30 7B 30 7E 30" + - "7F 30 80 30 81 30 82 30 84 30 86 30 88 30 89 30" + - "8A 30 8B 30 8C 30 8D 30 8F 30 92 30 93 30 30 00" + - "30 00 36 00 30 00 32 00 01 42 30 44 30 46 30 48" + - "30 4A 30 4B 30 4D 30 4F 30 51 30 53 30 55 30 57" + - "30 59 30 5B 30 5D 30 5F 30 61 30 64 30 66 30 68" + - "30 6A 30 6B 30 6C 30 6D 30 6E 30 6F 30 72 30 75" + - "30 78 30 7B 30 7E 30 7F 30 80 30 81 30 82 30 84" + - "30 86 30 88 30 89 30 8A 30 8B 30 8C 30 8D 30 8F" + - "30 92 30 93 30 30 00 30 00 36 00 31 00 32 00 01" + - "42 30 44 30 46 30 48 30 4A 30 4B 30 4D 30 4F 30" + - "51 30 53 30 55 30 57 30 59 30 5B 30 5D 30 5F 30" + - "61 30 64 30 66 30 68 30 6A 30 6B 30 6C 30 6D 30" + - "6E 30 6F 30 72 30 75 30 78 30 7B 30 7E 30 7F 30" + - "80 30 81 30 82 30 84 30 86 30 88 30 89 30 8A 30" + - "8B 30 8C 30 8D 30 8F 30 92 30 93 30 30 00 30 00" + - "36 00 32 00 32 00 01 42 30 44 30 46 30 48 30 4A" + - "30 4B 30 4D 30 4F 30 51 30 53 30 55 30 57 30 59" + - "30 5B 30 5D 30 5F 30 61 30 64 30 66 30 68 30 6A" + - "30 6B 30 6C 30 6D 30 6E 30 6F 30 72 30 75 30 78" + - "30 7B 30 7E 30 7F 30 80 30 81 30 82 30 84 30 86" + - "30 88 30 89 30 8A 30 8B 30 8C 30 8D 30 8F 30 92" + - "30 93 30 30 00 30 00 36 00 33 00 32 00 01 42 30" + - "44 30 46 30 48 30 4A 30 4B 30 4D 30 4F 30 51 30" + - "53 30 55 30 57 30 59 30 5B 30 5D 30 5F 30 61 30" + - "64 30 66 30 68 30 6A 30 6B 30 6C 30 6D 30 6E 30" + - "6F 30 72 30 75 30 78 30 7B 30 7E 30 7F 30 80 30" + - "81 30 82 30 84 30 86 30 88 30 89 30 8A 30 8B 30" + - "8C 30 8D 30 8F 30 92 30 93 30 30 00 30 00 36 00" + - "34 00 32 00 01 42 30 44 30 46 30 48 30 4A 30 4B" + - "30 4D 30 4F 30 51 30 53 30 55 30 57 30 59 30 5B" + - "30 5D 30 5F 30 61 30 64 30 66 30 68 30 6A 30 6B" + - "30 6C 30 6D 30 6E 30 6F 30 72 30 75 30 78 30 7B" + - "30 7E 30 7F 30 80 30 81 30 82 30 84 30 86 30 88" + - "30 89 30 8A 30 8B 30 8C 30 8D 30 8F 30 92 30 93" + - "30 30 00 30 00 36 00 35 00 32 00 01 42 30 44 30" + - "46 30 48 30 4A 30 4B 30 4D 30 4F 30 51 30 53 30" + - "55 30 57 30 59 30 5B 30 5D 30 5F 30 61 30 64 30" + - "66 30 68 30 6A 30 6B 30 6C 30 6D 30 6E 30 6F 30" + - "72 30 75 30 78 30 7B 30 7E 30 7F 30 80 30 81 30" + - "82 30 84 30 86 30 88 30 89 30 8A 30 8B 30 8C 30" + - "8D 30 8F 30 92 30 93 30 30 00 30 00 36 00 36 00" + - "32 00 01 42 30 44 30 46 30 48 30 4A 30 4B 30 4D" + - "30 4F 30 51 30 53 30 55 30 57 30 59 30 5B 30 5D" + - "30 5F 30 61 30 64 30 66 30 68 30 6A 30 6B 30 6C" + - "30 6D 30 6E 30 6F 30 72 30 75 30 78 30 7B 30 7E" + - "30 7F 30 80 30 81 30 82 30 84 30 86 30 88 30 89" + - "30 8A 30 8B 30 8C 30 8D 30 8F 30 92 30 93 30 30" + - "00 30 00 36 00 37 00 32 00 01 42 30 44 30 46 30" + - "48 30 4A 30 4B 30 4D 30 4F 30 51 30 53 30 55 30" + - "57 30 59 30 5B 30 5D 30 5F 30 61 30 64 30 66 30" + - "68 30 6A 30 6B 30 6C 30 6D 30 6E 30 6F 30 72 30" + - "75 30 78 30 7B 30 7E 30 7F 30 80 30 81 30 82 30" + - "84 30 86 30 88 30 89 30 8A 30 8B 30 8C 30 8D 30" + - "8F 30 92 30 93 30 30 00 30 00 36 00 38 00 32 00" + - "01 42 30 44 30 46 30 48 30 4A 30 4B 30 4D 30 4F" + - "30 51 30 53 30 55 30 57 30 59 30 5B 30 5D 30 5F" + - "30 61 30 64 30 66 30 68 30 6A 30 6B 30 6C 30 6D" + - "30 6E 30 6F 30 72 30 75 30 78 30 7B 30 7E 30 7F" + - "30 80 30 81 30 82 30 84 30 86 30 88 30 89 30 8A" + - "30 8B 30 8C 30 8D 30 8F 30 92 30 93 30 30 00 30" + - "00 36 00 39 00 32 00 01 42 30 44 30 46 30 48 30" + - "4A 30 4B 30 4D 30 4F 30 51 30 53 30 55 30 57 30" + - "59 30 5B 30 5D 30 5F 30 61 30 64 30 66 30 68 30" + - "6A 30 6B 30 6C 30 6D 30 6E 30 6F 30 72 30 75 30" + - "78 30 7B 30 7E 30 7F 30 80 30 81 30 82 30 84 30" + - "86 30 88 30 89 30 8A 30 8B 30 8C 30 8D 30 8F 30" + - "92 30 93 30 30 00 30 00 37 00 30 00 32 00 01 42" + - "30 44 30 46 30 48 30 4A 30 4B 30 4D 30 4F 30 51" + - "30 53 30 55 30 57 30 59 30 5B 30 5D 30 5F 30 61" + - "30 64 30 66 30 68 30 6A 30 6B 30 6C 30 6D 30 6E" + - "30 6F 30 72 30 75 30 78 30 7B 30 7E 30 7F 30 80" + - "30 81 30 82 30 84 30 86 30 88 30 89 30 8A 30 8B" + - "30 8C 30 8D 30 8F 30 92 30 93 30 30 00 30 00 37" + - "00 31 00 32 00 01 42 30 44 30 46 30 48 30 4A 30" + - "4B 30 4D 30 4F 30 51 30 53 30 55 30 57 30 59 30" + - "5B 30 5D 30 5F 30 61 30 64 30 66 30 68 30 6A 30" + - "6B 30 6C 30 6D 30 6E 30 6F 30 72 30 75 30 78 30" + - "7B 30 7E 30 7F 30 80 30 81 30 82 30 84 30 86 30" + - "88 30 89 30 8A 30 8B 30 8C 30 8D 30 8F 30 92 30" + - "93 30 30 00 30 00 37 00 32 00 32 00 01 42 30 44" + - "30 46 30 48 30 4A 30 4B 30 4D 30 4F 30 51 30 53" + - "30 55 30 57 30 59 30 5B 30 5D 30 5F 30 61 30 64" + - "30 66 30 68 30 6A 30 6B 30 6C 30 6D 30 6E 30 6F" + - "30 72 30 75 30 78 30 7B 30 7E 30 7F 30 80 30 81" + - "30 82 30 84 30 86 30 88 30 89 30 8A 30 8B 30 8C" + - "30 8D 30 8F 30 92 30 93 30 30 00 30 00 37 00 33" + - "00 32 00 01 42 30 44 30 46 30 48 30 4A 30 4B 30" + - "4D 30 4F 30 51 30 53 30 55 30 57 30 59 30 5B 30" + - "5D 30 5F 30 61 30 64 30 66 30 68 30 6A 30 6B 30" + - "6C 30 6D 30 6E 30 6F 30 72 30 75 30 78 30 7B 30" + - "7E 30 7F 30 80 30 81 30 82 30 84 30 86 30 88 30" + - "89 30 8A 30 8B 30 8C 30 8D 30 8F 30 92 30 93 30" + - "30 00 30 00 37 00 34 00 32 00 01 42 30 44 30 46" + - "30 48 30 4A 30 4B 30 4D 30 4F 30 51 30 53 30 55" + - "30 57 30 59 30 5B 30 5D 30 5F 30 61 30 64 30 66" + - "30 68 30 6A 30 6B 30 6C 30 6D 30 6E 30 6F 30 72" + - "30 75 30 78 30 7B 30 7E 30 7F 30 80 30 81 30 82" + - "30 84 30 86 30 88 30 89 30 8A 30 8B 30 8C 30 8D" + - "30 8F 30 92 30 93 30 30 00 30 00 37 00 35 00 32" + - "00 01 42 30 44 30 46 30 48 30 4A 30 4B 30 4D 30" + - "4F 30 51 30 53 30 55 30 57 30 59 30 5B 30 5D 30" + - "5F 30 61 30 64 30 66 30 68 30 6A 30 6B 30 6C 30" + - "6D 30 6E 30 6F 30 72 30 75 30 78 30 7B 30 7E 30" + - "7F 30 80 30 81 30 82 30 84 30 86 30 88 30 89 30" + - "8A 30 8B 30 8C 30 8D 30 8F 30 92 30 93 30 30 00" + - "30 00 37 00 36 00 32 00 01 42 30 44 30 46 30 48" + - "30 4A 30 4B 30 4D 30 4F 30 51 30 53 30 55 30 57" + - "30 59 30 5B 30 5D 30 5F 30 61 30 64 30 66 30 68" + - "30 6A 30 6B 30 6C 30 6D 30 6E 30 6F 30 72 30 75" + - "30 78 30 7B 30 7E 30 7F 30 80 30 81 30 82 30 84" + - "30 86 30 88 30 89 30 8A 30 8B 30 8C 30 8D 30 8F" + - "30 92 30 93 30 30 00 30 00 37 00 37 00 32 00 01" + - "42 30 44 30 46 30 48 30 4A 30 4B 30 4D 30 4F 30" + - "51 30 53 30 55 30 57 30 59 30 5B 30 5D 30 5F 30" + - "61 30 64 30 66 30 68 30 6A 30 6B 30 6C 30 6D 30" + - "6E 30 6F 30 72 30 75 30 78 30 7B 30 7E 30 7F 30" + - "80 30 81 30 82 30 84 30 86 30 88 30 89 30 8A 30" + - "8B 30 8C 30 8D 30 8F 30 92 30 93 30 30 00 30 00" + - "37 00 38 00 1F 00 05 B8 00 00 00 17 53 77 6D 53" + - "90 52 97 EE 68 0C 77 A9 5C 4B 62 0C 77 8F 79 F6" + - "5C 0C 77 03 68 28 67 0C 77 FC 57 89 73 0C 77 71" + - "67 AC 4E FD 90 43 53 49 84 0C 77 5E 79 48 59 DD" + - "5D 0C 77 77 95 CE 91 0C 77 01 00 B4 00 05 00 35" + - "00 0A 00 37 00 37 00 DB 30 C3 30 AB 30 A4 30 C9" + - "30 A6 30 A2 30 AA 30 E2 30 EA 30 B1 30 F3 30 A4" + - "30 EF 30 C6 30 B1 30 F3 30 D5 30 AF 30 B7 30 DE" + - "30 B1 30 F3 30 C8 30 C1 30 AE 30 B1 30 F3 30 B5" + - "30 A4 30 BF 30 DE 30 B1 30 F3 30 C8 30 A6 30 AD" + - "30 E7 30 A6 30 C8 " + - - // Offset=0x00002636(9782) recno=72 sid=0x003C size=0x0151(337) - " 3C 00 51 01 30 C1 30 D0 30 B1" + - "30 F3 30 AB 30 CA 30 AC 30 EF 30 B1 30 F3 30 CA" + - "30 AC 30 CE 30 B1 30 F3 30 00 00 00 00 03 00 06" + - "00 03 00 03 00 0C 00 06 00 03 00 11 00 09 00 03" + - "00 17 00 0C 00 03 00 1C 00 0F 00 03 00 22 00 12" + - "00 03 00 28 00 15 00 03 00 2C 00 18 00 04 00 32" + - "00 1C 00 03 00 32 00 05 10 00 00 00 42 30 44 30" + - "46 30 48 30 4A 30 4B 30 4D 30 4F 30 51 30 53 30" + - "55 30 57 30 59 30 5B 30 5D 30 5F 30 61 30 64 30" + - "66 30 68 30 6A 30 6B 30 6C 30 6D 30 6E 30 6F 30" + - "72 30 75 30 78 30 7B 30 7E 30 7F 30 80 30 81 30" + - "82 30 84 30 86 30 88 30 89 30 8A 30 8B 30 8C 30" + - "8D 30 8F 30 92 30 93 30 30 00 30 00 37 00 39 00" + - "01 00 0C 00 05 00 35 00 00 00 00 00 00 00 00 00" + - "32 00 05 10 00 00 00 42 30 44 30 46 30 48 30 4A" + - "30 4B 30 4D 30 4F 30 51 30 53 30 55 30 57 30 59" + - "30 5B 30 5D 30 5F 30 61 30 64 30 66 30 68 30 6A" + - "30 6B 30 6C 30 6D 30 6E 30 6F 30 72 30 75 30 78" + - "30 7B 30 7E 30 7F 30 80 30 81 30 82 30 84 30 86" + - "30 88 30 89 30 8A 30 8B 30 8C 30 8D 30 8F 30 92" + - "30 93 30 30 00 30 00 38 00 30 00 01 00 0C 00 05" + - "00 35 00 00 00 00 00 00 00 4B 30 "; - - - /** - * hex dump from UnicodeStringFailCase2.xls atatched to Bugzilla 50779 - */ - private static final String data_50779_2 = - //"Offset=0x00000612(1554) recno=71 sid=0x00FC size=0x2020(8224)\n" + - " FC 00 20 20 51 00 00 00 51 00 00 00 32 00" + - "01 42 30 44 30 46 30 48 30 4A 30 4B 30 4D 30 4F" + - "30 51 30 53 30 55 30 57 30 59 30 5B 30 5D 30 5F" + - "30 61 30 64 30 66 30 68 30 6A 30 6B 30 6C 30 6D" + - "30 6E 30 6F 30 72 30 75 30 78 30 7B 30 7E 30 7F" + - "30 80 30 81 30 82 30 84 30 86 30 88 30 89 30 8A" + - "30 8B 30 8C 30 8D 30 8F 30 92 30 93 30 30 00 30" + - "00 30 00 31 00 32 00 01 42 30 44 30 46 30 48 30" + - "4A 30 4B 30 4D 30 4F 30 51 30 53 30 55 30 57 30" + - "59 30 5B 30 5D 30 5F 30 61 30 64 30 66 30 68 30" + - "6A 30 6B 30 6C 30 6D 30 6E 30 6F 30 72 30 75 30" + - "78 30 7B 30 7E 30 7F 30 80 30 81 30 82 30 84 30" + - "86 30 88 30 89 30 8A 30 8B 30 8C 30 8D 30 8F 30" + - "92 30 93 30 30 00 30 00 30 00 32 00 32 00 01 42" + - "30 44 30 46 30 48 30 4A 30 4B 30 4D 30 4F 30 51" + - "30 53 30 55 30 57 30 59 30 5B 30 5D 30 5F 30 61" + - "30 64 30 66 30 68 30 6A 30 6B 30 6C 30 6D 30 6E" + - "30 6F 30 72 30 75 30 78 30 7B 30 7E 30 7F 30 80" + - "30 81 30 82 30 84 30 86 30 88 30 89 30 8A 30 8B" + - "30 8C 30 8D 30 8F 30 92 30 93 30 30 00 30 00 30" + - "00 33 00 32 00 01 42 30 44 30 46 30 48 30 4A 30" + - "4B 30 4D 30 4F 30 51 30 53 30 55 30 57 30 59 30" + - "5B 30 5D 30 5F 30 61 30 64 30 66 30 68 30 6A 30" + - "6B 30 6C 30 6D 30 6E 30 6F 30 72 30 75 30 78 30" + - "7B 30 7E 30 7F 30 80 30 81 30 82 30 84 30 86 30" + - "88 30 89 30 8A 30 8B 30 8C 30 8D 30 8F 30 92 30" + - "93 30 30 00 30 00 30 00 34 00 32 00 01 42 30 44" + - "30 46 30 48 30 4A 30 4B 30 4D 30 4F 30 51 30 53" + - "30 55 30 57 30 59 30 5B 30 5D 30 5F 30 61 30 64" + - "30 66 30 68 30 6A 30 6B 30 6C 30 6D 30 6E 30 6F" + - "30 72 30 75 30 78 30 7B 30 7E 30 7F 30 80 30 81" + - "30 82 30 84 30 86 30 88 30 89 30 8A 30 8B 30 8C" + - "30 8D 30 8F 30 92 30 93 30 30 00 30 00 30 00 35" + - "00 32 00 01 42 30 44 30 46 30 48 30 4A 30 4B 30" + - "4D 30 4F 30 51 30 53 30 55 30 57 30 59 30 5B 30" + - "5D 30 5F 30 61 30 64 30 66 30 68 30 6A 30 6B 30" + - "6C 30 6D 30 6E 30 6F 30 72 30 75 30 78 30 7B 30" + - "7E 30 7F 30 80 30 81 30 82 30 84 30 86 30 88 30" + - "89 30 8A 30 8B 30 8C 30 8D 30 8F 30 92 30 93 30" + - "30 00 30 00 30 00 36 00 32 00 01 42 30 44 30 46" + - "30 48 30 4A 30 4B 30 4D 30 4F 30 51 30 53 30 55" + - "30 57 30 59 30 5B 30 5D 30 5F 30 61 30 64 30 66" + - "30 68 30 6A 30 6B 30 6C 30 6D 30 6E 30 6F 30 72" + - "30 75 30 78 30 7B 30 7E 30 7F 30 80 30 81 30 82" + - "30 84 30 86 30 88 30 89 30 8A 30 8B 30 8C 30 8D" + - "30 8F 30 92 30 93 30 30 00 30 00 30 00 37 00 32" + - "00 01 42 30 44 30 46 30 48 30 4A 30 4B 30 4D 30" + - "4F 30 51 30 53 30 55 30 57 30 59 30 5B 30 5D 30" + - "5F 30 61 30 64 30 66 30 68 30 6A 30 6B 30 6C 30" + - "6D 30 6E 30 6F 30 72 30 75 30 78 30 7B 30 7E 30" + - "7F 30 80 30 81 30 82 30 84 30 86 30 88 30 89 30" + - "8A 30 8B 30 8C 30 8D 30 8F 30 92 30 93 30 30 00" + - "30 00 30 00 38 00 32 00 01 42 30 44 30 46 30 48" + - "30 4A 30 4B 30 4D 30 4F 30 51 30 53 30 55 30 57" + - "30 59 30 5B 30 5D 30 5F 30 61 30 64 30 66 30 68" + - "30 6A 30 6B 30 6C 30 6D 30 6E 30 6F 30 72 30 75" + - "30 78 30 7B 30 7E 30 7F 30 80 30 81 30 82 30 84" + - "30 86 30 88 30 89 30 8A 30 8B 30 8C 30 8D 30 8F" + - "30 92 30 93 30 30 00 30 00 30 00 39 00 32 00 01" + - "42 30 44 30 46 30 48 30 4A 30 4B 30 4D 30 4F 30" + - "51 30 53 30 55 30 57 30 59 30 5B 30 5D 30 5F 30" + - "61 30 64 30 66 30 68 30 6A 30 6B 30 6C 30 6D 30" + - "6E 30 6F 30 72 30 75 30 78 30 7B 30 7E 30 7F 30" + - "80 30 81 30 82 30 84 30 86 30 88 30 89 30 8A 30" + - "8B 30 8C 30 8D 30 8F 30 92 30 93 30 30 00 30 00" + - "31 00 30 00 32 00 01 42 30 44 30 46 30 48 30 4A" + - "30 4B 30 4D 30 4F 30 51 30 53 30 55 30 57 30 59" + - "30 5B 30 5D 30 5F 30 61 30 64 30 66 30 68 30 6A" + - "30 6B 30 6C 30 6D 30 6E 30 6F 30 72 30 75 30 78" + - "30 7B 30 7E 30 7F 30 80 30 81 30 82 30 84 30 86" + - "30 88 30 89 30 8A 30 8B 30 8C 30 8D 30 8F 30 92" + - "30 93 30 30 00 30 00 31 00 31 00 32 00 01 42 30" + - "44 30 46 30 48 30 4A 30 4B 30 4D 30 4F 30 51 30" + - "53 30 55 30 57 30 59 30 5B 30 5D 30 5F 30 61 30" + - "64 30 66 30 68 30 6A 30 6B 30 6C 30 6D 30 6E 30" + - "6F 30 72 30 75 30 78 30 7B 30 7E 30 7F 30 80 30" + - "81 30 82 30 84 30 86 30 88 30 89 30 8A 30 8B 30" + - "8C 30 8D 30 8F 30 92 30 93 30 30 00 30 00 31 00" + - "32 00 32 00 01 42 30 44 30 46 30 48 30 4A 30 4B" + - "30 4D 30 4F 30 51 30 53 30 55 30 57 30 59 30 5B" + - "30 5D 30 5F 30 61 30 64 30 66 30 68 30 6A 30 6B" + - "30 6C 30 6D 30 6E 30 6F 30 72 30 75 30 78 30 7B" + - "30 7E 30 7F 30 80 30 81 30 82 30 84 30 86 30 88" + - "30 89 30 8A 30 8B 30 8C 30 8D 30 8F 30 92 30 93" + - "30 30 00 30 00 31 00 33 00 32 00 01 42 30 44 30" + - "46 30 48 30 4A 30 4B 30 4D 30 4F 30 51 30 53 30" + - "55 30 57 30 59 30 5B 30 5D 30 5F 30 61 30 64 30" + - "66 30 68 30 6A 30 6B 30 6C 30 6D 30 6E 30 6F 30" + - "72 30 75 30 78 30 7B 30 7E 30 7F 30 80 30 81 30" + - "82 30 84 30 86 30 88 30 89 30 8A 30 8B 30 8C 30" + - "8D 30 8F 30 92 30 93 30 30 00 30 00 31 00 34 00" + - "32 00 01 42 30 44 30 46 30 48 30 4A 30 4B 30 4D" + - "30 4F 30 51 30 53 30 55 30 57 30 59 30 5B 30 5D" + - "30 5F 30 61 30 64 30 66 30 68 30 6A 30 6B 30 6C" + - "30 6D 30 6E 30 6F 30 72 30 75 30 78 30 7B 30 7E" + - "30 7F 30 80 30 81 30 82 30 84 30 86 30 88 30 89" + - "30 8A 30 8B 30 8C 30 8D 30 8F 30 92 30 93 30 30" + - "00 30 00 31 00 35 00 32 00 01 42 30 44 30 46 30" + - "48 30 4A 30 4B 30 4D 30 4F 30 51 30 53 30 55 30" + - "57 30 59 30 5B 30 5D 30 5F 30 61 30 64 30 66 30" + - "68 30 6A 30 6B 30 6C 30 6D 30 6E 30 6F 30 72 30" + - "75 30 78 30 7B 30 7E 30 7F 30 80 30 81 30 82 30" + - "84 30 86 30 88 30 89 30 8A 30 8B 30 8C 30 8D 30" + - "8F 30 92 30 93 30 30 00 30 00 31 00 36 00 32 00" + - "01 42 30 44 30 46 30 48 30 4A 30 4B 30 4D 30 4F" + - "30 51 30 53 30 55 30 57 30 59 30 5B 30 5D 30 5F" + - "30 61 30 64 30 66 30 68 30 6A 30 6B 30 6C 30 6D" + - "30 6E 30 6F 30 72 30 75 30 78 30 7B 30 7E 30 7F" + - "30 80 30 81 30 82 30 84 30 86 30 88 30 89 30 8A" + - "30 8B 30 8C 30 8D 30 8F 30 92 30 93 30 30 00 30" + - "00 31 00 37 00 32 00 01 42 30 44 30 46 30 48 30" + - "4A 30 4B 30 4D 30 4F 30 51 30 53 30 55 30 57 30" + - "59 30 5B 30 5D 30 5F 30 61 30 64 30 66 30 68 30" + - "6A 30 6B 30 6C 30 6D 30 6E 30 6F 30 72 30 75 30" + - "78 30 7B 30 7E 30 7F 30 80 30 81 30 82 30 84 30" + - "86 30 88 30 89 30 8A 30 8B 30 8C 30 8D 30 8F 30" + - "92 30 93 30 30 00 30 00 31 00 38 00 32 00 01 42" + - "30 44 30 46 30 48 30 4A 30 4B 30 4D 30 4F 30 51" + - "30 53 30 55 30 57 30 59 30 5B 30 5D 30 5F 30 61" + - "30 64 30 66 30 68 30 6A 30 6B 30 6C 30 6D 30 6E" + - "30 6F 30 72 30 75 30 78 30 7B 30 7E 30 7F 30 80" + - "30 81 30 82 30 84 30 86 30 88 30 89 30 8A 30 8B" + - "30 8C 30 8D 30 8F 30 92 30 93 30 30 00 30 00 31" + - "00 39 00 32 00 01 42 30 44 30 46 30 48 30 4A 30" + - "4B 30 4D 30 4F 30 51 30 53 30 55 30 57 30 59 30" + - "5B 30 5D 30 5F 30 61 30 64 30 66 30 68 30 6A 30" + - "6B 30 6C 30 6D 30 6E 30 6F 30 72 30 75 30 78 30" + - "7B 30 7E 30 7F 30 80 30 81 30 82 30 84 30 86 30" + - "88 30 89 30 8A 30 8B 30 8C 30 8D 30 8F 30 92 30" + - "93 30 30 00 30 00 32 00 30 00 32 00 01 42 30 44" + - "30 46 30 48 30 4A 30 4B 30 4D 30 4F 30 51 30 53" + - "30 55 30 57 30 59 30 5B 30 5D 30 5F 30 61 30 64" + - "30 66 30 68 30 6A 30 6B 30 6C 30 6D 30 6E 30 6F" + - "30 72 30 75 30 78 30 7B 30 7E 30 7F 30 80 30 81" + - "30 82 30 84 30 86 30 88 30 89 30 8A 30 8B 30 8C" + - "30 8D 30 8F 30 92 30 93 30 30 00 30 00 32 00 31" + - "00 32 00 01 42 30 44 30 46 30 48 30 4A 30 4B 30" + - "4D 30 4F 30 51 30 53 30 55 30 57 30 59 30 5B 30" + - "5D 30 5F 30 61 30 64 30 66 30 68 30 6A 30 6B 30" + - "6C 30 6D 30 6E 30 6F 30 72 30 75 30 78 30 7B 30" + - "7E 30 7F 30 80 30 81 30 82 30 84 30 86 30 88 30" + - "89 30 8A 30 8B 30 8C 30 8D 30 8F 30 92 30 93 30" + - "30 00 30 00 32 00 32 00 32 00 01 42 30 44 30 46" + - "30 48 30 4A 30 4B 30 4D 30 4F 30 51 30 53 30 55" + - "30 57 30 59 30 5B 30 5D 30 5F 30 61 30 64 30 66" + - "30 68 30 6A 30 6B 30 6C 30 6D 30 6E 30 6F 30 72" + - "30 75 30 78 30 7B 30 7E 30 7F 30 80 30 81 30 82" + - "30 84 30 86 30 88 30 89 30 8A 30 8B 30 8C 30 8D" + - "30 8F 30 92 30 93 30 30 00 30 00 32 00 33 00 32" + - "00 01 42 30 44 30 46 30 48 30 4A 30 4B 30 4D 30" + - "4F 30 51 30 53 30 55 30 57 30 59 30 5B 30 5D 30" + - "5F 30 61 30 64 30 66 30 68 30 6A 30 6B 30 6C 30" + - "6D 30 6E 30 6F 30 72 30 75 30 78 30 7B 30 7E 30" + - "7F 30 80 30 81 30 82 30 84 30 86 30 88 30 89 30" + - "8A 30 8B 30 8C 30 8D 30 8F 30 92 30 93 30 30 00" + - "30 00 32 00 34 00 32 00 01 42 30 44 30 46 30 48" + - "30 4A 30 4B 30 4D 30 4F 30 51 30 53 30 55 30 57" + - "30 59 30 5B 30 5D 30 5F 30 61 30 64 30 66 30 68" + - "30 6A 30 6B 30 6C 30 6D 30 6E 30 6F 30 72 30 75" + - "30 78 30 7B 30 7E 30 7F 30 80 30 81 30 82 30 84" + - "30 86 30 88 30 89 30 8A 30 8B 30 8C 30 8D 30 8F" + - "30 92 30 93 30 30 00 30 00 32 00 35 00 32 00 01" + - "42 30 44 30 46 30 48 30 4A 30 4B 30 4D 30 4F 30" + - "51 30 53 30 55 30 57 30 59 30 5B 30 5D 30 5F 30" + - "61 30 64 30 66 30 68 30 6A 30 6B 30 6C 30 6D 30" + - "6E 30 6F 30 72 30 75 30 78 30 7B 30 7E 30 7F 30" + - "80 30 81 30 82 30 84 30 86 30 88 30 89 30 8A 30" + - "8B 30 8C 30 8D 30 8F 30 92 30 93 30 30 00 30 00" + - "32 00 36 00 32 00 01 42 30 44 30 46 30 48 30 4A" + - "30 4B 30 4D 30 4F 30 51 30 53 30 55 30 57 30 59" + - "30 5B 30 5D 30 5F 30 61 30 64 30 66 30 68 30 6A" + - "30 6B 30 6C 30 6D 30 6E 30 6F 30 72 30 75 30 78" + - "30 7B 30 7E 30 7F 30 80 30 81 30 82 30 84 30 86" + - "30 88 30 89 30 8A 30 8B 30 8C 30 8D 30 8F 30 92" + - "30 93 30 30 00 30 00 32 00 37 00 32 00 01 42 30" + - "44 30 46 30 48 30 4A 30 4B 30 4D 30 4F 30 51 30" + - "53 30 55 30 57 30 59 30 5B 30 5D 30 5F 30 61 30" + - "64 30 66 30 68 30 6A 30 6B 30 6C 30 6D 30 6E 30" + - "6F 30 72 30 75 30 78 30 7B 30 7E 30 7F 30 80 30" + - "81 30 82 30 84 30 86 30 88 30 89 30 8A 30 8B 30" + - "8C 30 8D 30 8F 30 92 30 93 30 30 00 30 00 32 00" + - "38 00 32 00 01 42 30 44 30 46 30 48 30 4A 30 4B" + - "30 4D 30 4F 30 51 30 53 30 55 30 57 30 59 30 5B" + - "30 5D 30 5F 30 61 30 64 30 66 30 68 30 6A 30 6B" + - "30 6C 30 6D 30 6E 30 6F 30 72 30 75 30 78 30 7B" + - "30 7E 30 7F 30 80 30 81 30 82 30 84 30 86 30 88" + - "30 89 30 8A 30 8B 30 8C 30 8D 30 8F 30 92 30 93" + - "30 30 00 30 00 32 00 39 00 32 00 01 42 30 44 30" + - "46 30 48 30 4A 30 4B 30 4D 30 4F 30 51 30 53 30" + - "55 30 57 30 59 30 5B 30 5D 30 5F 30 61 30 64 30" + - "66 30 68 30 6A 30 6B 30 6C 30 6D 30 6E 30 6F 30" + - "72 30 75 30 78 30 7B 30 7E 30 7F 30 80 30 81 30" + - "82 30 84 30 86 30 88 30 89 30 8A 30 8B 30 8C 30" + - "8D 30 8F 30 92 30 93 30 30 00 30 00 33 00 30 00" + - "32 00 01 42 30 44 30 46 30 48 30 4A 30 4B 30 4D" + - "30 4F 30 51 30 53 30 55 30 57 30 59 30 5B 30 5D" + - "30 5F 30 61 30 64 30 66 30 68 30 6A 30 6B 30 6C" + - "30 6D 30 6E 30 6F 30 72 30 75 30 78 30 7B 30 7E" + - "30 7F 30 80 30 81 30 82 30 84 30 86 30 88 30 89" + - "30 8A 30 8B 30 8C 30 8D 30 8F 30 92 30 93 30 30" + - "00 30 00 33 00 31 00 32 00 01 42 30 44 30 46 30" + - "48 30 4A 30 4B 30 4D 30 4F 30 51 30 53 30 55 30" + - "57 30 59 30 5B 30 5D 30 5F 30 61 30 64 30 66 30" + - "68 30 6A 30 6B 30 6C 30 6D 30 6E 30 6F 30 72 30" + - "75 30 78 30 7B 30 7E 30 7F 30 80 30 81 30 82 30" + - "84 30 86 30 88 30 89 30 8A 30 8B 30 8C 30 8D 30" + - "8F 30 92 30 93 30 30 00 30 00 33 00 32 00 32 00" + - "01 42 30 44 30 46 30 48 30 4A 30 4B 30 4D 30 4F" + - "30 51 30 53 30 55 30 57 30 59 30 5B 30 5D 30 5F" + - "30 61 30 64 30 66 30 68 30 6A 30 6B 30 6C 30 6D" + - "30 6E 30 6F 30 72 30 75 30 78 30 7B 30 7E 30 7F" + - "30 80 30 81 30 82 30 84 30 86 30 88 30 89 30 8A" + - "30 8B 30 8C 30 8D 30 8F 30 92 30 93 30 30 00 30" + - "00 33 00 33 00 32 00 01 42 30 44 30 46 30 48 30" + - "4A 30 4B 30 4D 30 4F 30 51 30 53 30 55 30 57 30" + - "59 30 5B 30 5D 30 5F 30 61 30 64 30 66 30 68 30" + - "6A 30 6B 30 6C 30 6D 30 6E 30 6F 30 72 30 75 30" + - "78 30 7B 30 7E 30 7F 30 80 30 81 30 82 30 84 30" + - "86 30 88 30 89 30 8A 30 8B 30 8C 30 8D 30 8F 30" + - "92 30 93 30 30 00 30 00 33 00 34 00 32 00 01 42" + - "30 44 30 46 30 48 30 4A 30 4B 30 4D 30 4F 30 51" + - "30 53 30 55 30 57 30 59 30 5B 30 5D 30 5F 30 61" + - "30 64 30 66 30 68 30 6A 30 6B 30 6C 30 6D 30 6E" + - "30 6F 30 72 30 75 30 78 30 7B 30 7E 30 7F 30 80" + - "30 81 30 82 30 84 30 86 30 88 30 89 30 8A 30 8B" + - "30 8C 30 8D 30 8F 30 92 30 93 30 30 00 30 00 33" + - "00 35 00 32 00 01 42 30 44 30 46 30 48 30 4A 30" + - "4B 30 4D 30 4F 30 51 30 53 30 55 30 57 30 59 30" + - "5B 30 5D 30 5F 30 61 30 64 30 66 30 68 30 6A 30" + - "6B 30 6C 30 6D 30 6E 30 6F 30 72 30 75 30 78 30" + - "7B 30 7E 30 7F 30 80 30 81 30 82 30 84 30 86 30" + - "88 30 89 30 8A 30 8B 30 8C 30 8D 30 8F 30 92 30" + - "93 30 30 00 30 00 33 00 36 00 32 00 01 42 30 44" + - "30 46 30 48 30 4A 30 4B 30 4D 30 4F 30 51 30 53" + - "30 55 30 57 30 59 30 5B 30 5D 30 5F 30 61 30 64" + - "30 66 30 68 30 6A 30 6B 30 6C 30 6D 30 6E 30 6F" + - "30 72 30 75 30 78 30 7B 30 7E 30 7F 30 80 30 81" + - "30 82 30 84 30 86 30 88 30 89 30 8A 30 8B 30 8C" + - "30 8D 30 8F 30 92 30 93 30 30 00 30 00 33 00 37" + - "00 32 00 01 42 30 44 30 46 30 48 30 4A 30 4B 30" + - "4D 30 4F 30 51 30 53 30 55 30 57 30 59 30 5B 30" + - "5D 30 5F 30 61 30 64 30 66 30 68 30 6A 30 6B 30" + - "6C 30 6D 30 6E 30 6F 30 72 30 75 30 78 30 7B 30" + - "7E 30 7F 30 80 30 81 30 82 30 84 30 86 30 88 30" + - "89 30 8A 30 8B 30 8C 30 8D 30 8F 30 92 30 93 30" + - "30 00 30 00 33 00 38 00 32 00 01 42 30 44 30 46" + - "30 48 30 4A 30 4B 30 4D 30 4F 30 51 30 53 30 55" + - "30 57 30 59 30 5B 30 5D 30 5F 30 61 30 64 30 66" + - "30 68 30 6A 30 6B 30 6C 30 6D 30 6E 30 6F 30 72" + - "30 75 30 78 30 7B 30 7E 30 7F 30 80 30 81 30 82" + - "30 84 30 86 30 88 30 89 30 8A 30 8B 30 8C 30 8D" + - "30 8F 30 92 30 93 30 30 00 30 00 33 00 39 00 32" + - "00 01 42 30 44 30 46 30 48 30 4A 30 4B 30 4D 30" + - "4F 30 51 30 53 30 55 30 57 30 59 30 5B 30 5D 30" + - "5F 30 61 30 64 30 66 30 68 30 6A 30 6B 30 6C 30" + - "6D 30 6E 30 6F 30 72 30 75 30 78 30 7B 30 7E 30" + - "7F 30 80 30 81 30 82 30 84 30 86 30 88 30 89 30" + - "8A 30 8B 30 8C 30 8D 30 8F 30 92 30 93 30 30 00" + - "30 00 34 00 30 00 32 00 01 42 30 44 30 46 30 48" + - "30 4A 30 4B 30 4D 30 4F 30 51 30 53 30 55 30 57" + - "30 59 30 5B 30 5D 30 5F 30 61 30 64 30 66 30 68" + - "30 6A 30 6B 30 6C 30 6D 30 6E 30 6F 30 72 30 75" + - "30 78 30 7B 30 7E 30 7F 30 80 30 81 30 82 30 84" + - "30 86 30 88 30 89 30 8A 30 8B 30 8C 30 8D 30 8F" + - "30 92 30 93 30 30 00 30 00 34 00 31 00 32 00 01" + - "42 30 44 30 46 30 48 30 4A 30 4B 30 4D 30 4F 30" + - "51 30 53 30 55 30 57 30 59 30 5B 30 5D 30 5F 30" + - "61 30 64 30 66 30 68 30 6A 30 6B 30 6C 30 6D 30" + - "6E 30 6F 30 72 30 75 30 78 30 7B 30 7E 30 7F 30" + - "80 30 81 30 82 30 84 30 86 30 88 30 89 30 8A 30" + - "8B 30 8C 30 8D 30 8F 30 92 30 93 30 30 00 30 00" + - "34 00 32 00 32 00 01 42 30 44 30 46 30 48 30 4A" + - "30 4B 30 4D 30 4F 30 51 30 53 30 55 30 57 30 59" + - "30 5B 30 5D 30 5F 30 61 30 64 30 66 30 68 30 6A" + - "30 6B 30 6C 30 6D 30 6E 30 6F 30 72 30 75 30 78" + - "30 7B 30 7E 30 7F 30 80 30 81 30 82 30 84 30 86" + - "30 88 30 89 30 8A 30 8B 30 8C 30 8D 30 8F 30 92" + - "30 93 30 30 00 30 00 34 00 33 00 32 00 01 42 30" + - "44 30 46 30 48 30 4A 30 4B 30 4D 30 4F 30 51 30" + - "53 30 55 30 57 30 59 30 5B 30 5D 30 5F 30 61 30" + - "64 30 66 30 68 30 6A 30 6B 30 6C 30 6D 30 6E 30" + - "6F 30 72 30 75 30 78 30 7B 30 7E 30 7F 30 80 30" + - "81 30 82 30 84 30 86 30 88 30 89 30 8A 30 8B 30" + - "8C 30 8D 30 8F 30 92 30 93 30 30 00 30 00 34 00" + - "34 00 32 00 01 42 30 44 30 46 30 48 30 4A 30 4B" + - "30 4D 30 4F 30 51 30 53 30 55 30 57 30 59 30 5B" + - "30 5D 30 5F 30 61 30 64 30 66 30 68 30 6A 30 6B" + - "30 6C 30 6D 30 6E 30 6F 30 72 30 75 30 78 30 7B" + - "30 7E 30 7F 30 80 30 81 30 82 30 84 30 86 30 88" + - "30 89 30 8A 30 8B 30 8C 30 8D 30 8F 30 92 30 93" + - "30 30 00 30 00 34 00 35 00 32 00 01 42 30 44 30" + - "46 30 48 30 4A 30 4B 30 4D 30 4F 30 51 30 53 30" + - "55 30 57 30 59 30 5B 30 5D 30 5F 30 61 30 64 30" + - "66 30 68 30 6A 30 6B 30 6C 30 6D 30 6E 30 6F 30" + - "72 30 75 30 78 30 7B 30 7E 30 7F 30 80 30 81 30" + - "82 30 84 30 86 30 88 30 89 30 8A 30 8B 30 8C 30" + - "8D 30 8F 30 92 30 93 30 30 00 30 00 34 00 36 00" + - "32 00 01 42 30 44 30 46 30 48 30 4A 30 4B 30 4D" + - "30 4F 30 51 30 53 30 55 30 57 30 59 30 5B 30 5D" + - "30 5F 30 61 30 64 30 66 30 68 30 6A 30 6B 30 6C" + - "30 6D 30 6E 30 6F 30 72 30 75 30 78 30 7B 30 7E" + - "30 7F 30 80 30 81 30 82 30 84 30 86 30 88 30 89" + - "30 8A 30 8B 30 8C 30 8D 30 8F 30 92 30 93 30 30" + - "00 30 00 34 00 37 00 32 00 01 42 30 44 30 46 30" + - "48 30 4A 30 4B 30 4D 30 4F 30 51 30 53 30 55 30" + - "57 30 59 30 5B 30 5D 30 5F 30 61 30 64 30 66 30" + - "68 30 6A 30 6B 30 6C 30 6D 30 6E 30 6F 30 72 30" + - "75 30 78 30 7B 30 7E 30 7F 30 80 30 81 30 82 30" + - "84 30 86 30 88 30 89 30 8A 30 8B 30 8C 30 8D 30" + - "8F 30 92 30 93 30 30 00 30 00 34 00 38 00 32 00" + - "01 42 30 44 30 46 30 48 30 4A 30 4B 30 4D 30 4F" + - "30 51 30 53 30 55 30 57 30 59 30 5B 30 5D 30 5F" + - "30 61 30 64 30 66 30 68 30 6A 30 6B 30 6C 30 6D" + - "30 6E 30 6F 30 72 30 75 30 78 30 7B 30 7E 30 7F" + - "30 80 30 81 30 82 30 84 30 86 30 88 30 89 30 8A" + - "30 8B 30 8C 30 8D 30 8F 30 92 30 93 30 30 00 30" + - "00 34 00 39 00 32 00 01 42 30 44 30 46 30 48 30" + - "4A 30 4B 30 4D 30 4F 30 51 30 53 30 55 30 57 30" + - "59 30 5B 30 5D 30 5F 30 61 30 64 30 66 30 68 30" + - "6A 30 6B 30 6C 30 6D 30 6E 30 6F 30 72 30 75 30" + - "78 30 7B 30 7E 30 7F 30 80 30 81 30 82 30 84 30" + - "86 30 88 30 89 30 8A 30 8B 30 8C 30 8D 30 8F 30" + - "92 30 93 30 30 00 30 00 35 00 30 00 32 00 01 42" + - "30 44 30 46 30 48 30 4A 30 4B 30 4D 30 4F 30 51" + - "30 53 30 55 30 57 30 59 30 5B 30 5D 30 5F 30 61" + - "30 64 30 66 30 68 30 6A 30 6B 30 6C 30 6D 30 6E" + - "30 6F 30 72 30 75 30 78 30 7B 30 7E 30 7F 30 80" + - "30 81 30 82 30 84 30 86 30 88 30 89 30 8A 30 8B" + - "30 8C 30 8D 30 8F 30 92 30 93 30 30 00 30 00 35" + - "00 31 00 32 00 01 42 30 44 30 46 30 48 30 4A 30" + - "4B 30 4D 30 4F 30 51 30 53 30 55 30 57 30 59 30" + - "5B 30 5D 30 5F 30 61 30 64 30 66 30 68 30 6A 30" + - "6B 30 6C 30 6D 30 6E 30 6F 30 72 30 75 30 78 30" + - "7B 30 7E 30 7F 30 80 30 81 30 82 30 84 30 86 30" + - "88 30 89 30 8A 30 8B 30 8C 30 8D 30 8F 30 92 30" + - "93 30 30 00 30 00 35 00 32 00 32 00 01 42 30 44" + - "30 46 30 48 30 4A 30 4B 30 4D 30 4F 30 51 30 53" + - "30 55 30 57 30 59 30 5B 30 5D 30 5F 30 61 30 64" + - "30 66 30 68 30 6A 30 6B 30 6C 30 6D 30 6E 30 6F" + - "30 72 30 75 30 78 30 7B 30 7E 30 7F 30 80 30 81" + - "30 82 30 84 30 86 30 88 30 89 30 8A 30 8B 30 8C" + - "30 8D 30 8F 30 92 30 93 30 30 00 30 00 35 00 33" + - "00 32 00 01 42 30 44 30 46 30 48 30 4A 30 4B 30" + - "4D 30 4F 30 51 30 53 30 55 30 57 30 59 30 5B 30" + - "5D 30 5F 30 61 30 64 30 66 30 68 30 6A 30 6B 30" + - "6C 30 6D 30 6E 30 6F 30 72 30 75 30 78 30 7B 30" + - "7E 30 7F 30 80 30 81 30 82 30 84 30 86 30 88 30" + - "89 30 8A 30 8B 30 8C 30 8D 30 8F 30 92 30 93 30" + - "30 00 30 00 35 00 34 00 32 00 01 42 30 44 30 46" + - "30 48 30 4A 30 4B 30 4D 30 4F 30 51 30 53 30 55" + - "30 57 30 59 30 5B 30 5D 30 5F 30 61 30 64 30 66" + - "30 68 30 6A 30 6B 30 6C 30 6D 30 6E 30 6F 30 72" + - "30 75 30 78 30 7B 30 7E 30 7F 30 80 30 81 30 82" + - "30 84 30 86 30 88 30 89 30 8A 30 8B 30 8C 30 8D" + - "30 8F 30 92 30 93 30 30 00 30 00 35 00 35 00 32" + - "00 01 42 30 44 30 46 30 48 30 4A 30 4B 30 4D 30" + - "4F 30 51 30 53 30 55 30 57 30 59 30 5B 30 5D 30" + - "5F 30 61 30 64 30 66 30 68 30 6A 30 6B 30 6C 30" + - "6D 30 6E 30 6F 30 72 30 75 30 78 30 7B 30 7E 30" + - "7F 30 80 30 81 30 82 30 84 30 86 30 88 30 89 30" + - "8A 30 8B 30 8C 30 8D 30 8F 30 92 30 93 30 30 00" + - "30 00 35 00 36 00 32 00 01 42 30 44 30 46 30 48" + - "30 4A 30 4B 30 4D 30 4F 30 51 30 53 30 55 30 57" + - "30 59 30 5B 30 5D 30 5F 30 61 30 64 30 66 30 68" + - "30 6A 30 6B 30 6C 30 6D 30 6E 30 6F 30 72 30 75" + - "30 78 30 7B 30 7E 30 7F 30 80 30 81 30 82 30 84" + - "30 86 30 88 30 89 30 8A 30 8B 30 8C 30 8D 30 8F" + - "30 92 30 93 30 30 00 30 00 35 00 37 00 32 00 01" + - "42 30 44 30 46 30 48 30 4A 30 4B 30 4D 30 4F 30" + - "51 30 53 30 55 30 57 30 59 30 5B 30 5D 30 5F 30" + - "61 30 64 30 66 30 68 30 6A 30 6B 30 6C 30 6D 30" + - "6E 30 6F 30 72 30 75 30 78 30 7B 30 7E 30 7F 30" + - "80 30 81 30 82 30 84 30 86 30 88 30 89 30 8A 30" + - "8B 30 8C 30 8D 30 8F 30 92 30 93 30 30 00 30 00" + - "35 00 38 00 32 00 01 42 30 44 30 46 30 48 30 4A" + - "30 4B 30 4D 30 4F 30 51 30 53 30 55 30 57 30 59" + - "30 5B 30 5D 30 5F 30 61 30 64 30 66 30 68 30 6A" + - "30 6B 30 6C 30 6D 30 6E 30 6F 30 72 30 75 30 78" + - "30 7B 30 7E 30 7F 30 80 30 81 30 82 30 84 30 86" + - "30 88 30 89 30 8A 30 8B 30 8C 30 8D 30 8F 30 92" + - "30 93 30 30 00 30 00 35 00 39 00 32 00 01 42 30" + - "44 30 46 30 48 30 4A 30 4B 30 4D 30 4F 30 51 30" + - "53 30 55 30 57 30 59 30 5B 30 5D 30 5F 30 61 30" + - "64 30 66 30 68 30 6A 30 6B 30 6C 30 6D 30 6E 30" + - "6F 30 72 30 75 30 78 30 7B 30 7E 30 7F 30 80 30" + - "81 30 82 30 84 30 86 30 88 30 89 30 8A 30 8B 30" + - "8C 30 8D 30 8F 30 92 30 93 30 30 00 30 00 36 00" + - "30 00 32 00 01 42 30 44 30 46 30 48 30 4A 30 4B" + - "30 4D 30 4F 30 51 30 53 30 55 30 57 30 59 30 5B" + - "30 5D 30 5F 30 61 30 64 30 66 30 68 30 6A 30 6B" + - "30 6C 30 6D 30 6E 30 6F 30 72 30 75 30 78 30 7B" + - "30 7E 30 7F 30 80 30 81 30 82 30 84 30 86 30 88" + - "30 89 30 8A 30 8B 30 8C 30 8D 30 8F 30 92 30 93" + - "30 30 00 30 00 36 00 31 00 32 00 01 42 30 44 30" + - "46 30 48 30 4A 30 4B 30 4D 30 4F 30 51 30 53 30" + - "55 30 57 30 59 30 5B 30 5D 30 5F 30 61 30 64 30" + - "66 30 68 30 6A 30 6B 30 6C 30 6D 30 6E 30 6F 30" + - "72 30 75 30 78 30 7B 30 7E 30 7F 30 80 30 81 30" + - "82 30 84 30 86 30 88 30 89 30 8A 30 8B 30 8C 30" + - "8D 30 8F 30 92 30 93 30 30 00 30 00 36 00 32 00" + - "32 00 01 42 30 44 30 46 30 48 30 4A 30 4B 30 4D" + - "30 4F 30 51 30 53 30 55 30 57 30 59 30 5B 30 5D" + - "30 5F 30 61 30 64 30 66 30 68 30 6A 30 6B 30 6C" + - "30 6D 30 6E 30 6F 30 72 30 75 30 78 30 7B 30 7E" + - "30 7F 30 80 30 81 30 82 30 84 30 86 30 88 30 89" + - "30 8A 30 8B 30 8C 30 8D 30 8F 30 92 30 93 30 30" + - "00 30 00 36 00 33 00 32 00 01 42 30 44 30 46 30" + - "48 30 4A 30 4B 30 4D 30 4F 30 51 30 53 30 55 30" + - "57 30 59 30 5B 30 5D 30 5F 30 61 30 64 30 66 30" + - "68 30 6A 30 6B 30 6C 30 6D 30 6E 30 6F 30 72 30" + - "75 30 78 30 7B 30 7E 30 7F 30 80 30 81 30 82 30" + - "84 30 86 30 88 30 89 30 8A 30 8B 30 8C 30 8D 30" + - "8F 30 92 30 93 30 30 00 30 00 36 00 34 00 32 00" + - "01 42 30 44 30 46 30 48 30 4A 30 4B 30 4D 30 4F" + - "30 51 30 53 30 55 30 57 30 59 30 5B 30 5D 30 5F" + - "30 61 30 64 30 66 30 68 30 6A 30 6B 30 6C 30 6D" + - "30 6E 30 6F 30 72 30 75 30 78 30 7B 30 7E 30 7F" + - "30 80 30 81 30 82 30 84 30 86 30 88 30 89 30 8A" + - "30 8B 30 8C 30 8D 30 8F 30 92 30 93 30 30 00 30" + - "00 36 00 35 00 32 00 01 42 30 44 30 46 30 48 30" + - "4A 30 4B 30 4D 30 4F 30 51 30 53 30 55 30 57 30" + - "59 30 5B 30 5D 30 5F 30 61 30 64 30 66 30 68 30" + - "6A 30 6B 30 6C 30 6D 30 6E 30 6F 30 72 30 75 30" + - "78 30 7B 30 7E 30 7F 30 80 30 81 30 82 30 84 30" + - "86 30 88 30 89 30 8A 30 8B 30 8C 30 8D 30 8F 30" + - "92 30 93 30 30 00 30 00 36 00 36 00 32 00 01 42" + - "30 44 30 46 30 48 30 4A 30 4B 30 4D 30 4F 30 51" + - "30 53 30 55 30 57 30 59 30 5B 30 5D 30 5F 30 61" + - "30 64 30 66 30 68 30 6A 30 6B 30 6C 30 6D 30 6E" + - "30 6F 30 72 30 75 30 78 30 7B 30 7E 30 7F 30 80" + - "30 81 30 82 30 84 30 86 30 88 30 89 30 8A 30 8B" + - "30 8C 30 8D 30 8F 30 92 30 93 30 30 00 30 00 36" + - "00 37 00 32 00 01 42 30 44 30 46 30 48 30 4A 30" + - "4B 30 4D 30 4F 30 51 30 53 30 55 30 57 30 59 30" + - "5B 30 5D 30 5F 30 61 30 64 30 66 30 68 30 6A 30" + - "6B 30 6C 30 6D 30 6E 30 6F 30 72 30 75 30 78 30" + - "7B 30 7E 30 7F 30 80 30 81 30 82 30 84 30 86 30" + - "88 30 89 30 8A 30 8B 30 8C 30 8D 30 8F 30 92 30" + - "93 30 30 00 30 00 36 00 38 00 32 00 01 42 30 44" + - "30 46 30 48 30 4A 30 4B 30 4D 30 4F 30 51 30 53" + - "30 55 30 57 30 59 30 5B 30 5D 30 5F 30 61 30 64" + - "30 66 30 68 30 6A 30 6B 30 6C 30 6D 30 6E 30 6F" + - "30 72 30 75 30 78 30 7B 30 7E 30 7F 30 80 30 81" + - "30 82 30 84 30 86 30 88 30 89 30 8A 30 8B 30 8C" + - "30 8D 30 8F 30 92 30 93 30 30 00 30 00 36 00 39" + - "00 32 00 01 42 30 44 30 46 30 48 30 4A 30 4B 30" + - "4D 30 4F 30 51 30 53 30 55 30 57 30 59 30 5B 30" + - "5D 30 5F 30 61 30 64 30 66 30 68 30 6A 30 6B 30" + - "6C 30 6D 30 6E 30 6F 30 72 30 75 30 78 30 7B 30" + - "7E 30 7F 30 80 30 81 30 82 30 84 30 86 30 88 30" + - "89 30 8A 30 8B 30 8C 30 8D 30 8F 30 92 30 93 30" + - "30 00 30 00 37 00 30 00 32 00 01 42 30 44 30 46" + - "30 48 30 4A 30 4B 30 4D 30 4F 30 51 30 53 30 55" + - "30 57 30 59 30 5B 30 5D 30 5F 30 61 30 64 30 66" + - "30 68 30 6A 30 6B 30 6C 30 6D 30 6E 30 6F 30 72" + - "30 75 30 78 30 7B 30 7E 30 7F 30 80 30 81 30 82" + - "30 84 30 86 30 88 30 89 30 8A 30 8B 30 8C 30 8D" + - "30 8F 30 92 30 93 30 30 00 30 00 37 00 31 00 32" + - "00 01 42 30 44 30 46 30 48 30 4A 30 4B 30 4D 30" + - "4F 30 51 30 53 30 55 30 57 30 59 30 5B 30 5D 30" + - "5F 30 61 30 64 30 66 30 68 30 6A 30 6B 30 6C 30" + - "6D 30 6E 30 6F 30 72 30 75 30 78 30 7B 30 7E 30" + - "7F 30 80 30 81 30 82 30 84 30 86 30 88 30 89 30" + - "8A 30 8B 30 8C 30 8D 30 8F 30 92 30 93 30 30 00" + - "30 00 37 00 32 00 32 00 01 42 30 44 30 46 30 48" + - "30 4A 30 4B 30 4D 30 4F 30 51 30 53 30 55 30 57" + - "30 59 30 5B 30 5D 30 5F 30 61 30 64 30 66 30 68" + - "30 6A 30 6B 30 6C 30 6D 30 6E 30 6F 30 72 30 75" + - "30 78 30 7B 30 7E 30 7F 30 80 30 81 30 82 30 84" + - "30 86 30 88 30 89 30 8A 30 8B 30 8C 30 8D 30 8F" + - "30 92 30 93 30 30 00 30 00 37 00 33 00 32 00 01" + - "42 30 44 30 46 30 48 30 4A 30 4B 30 4D 30 4F 30" + - "51 30 53 30 55 30 57 30 59 30 5B 30 5D 30 5F 30" + - "61 30 64 30 66 30 68 30 6A 30 6B 30 6C 30 6D 30" + - "6E 30 6F 30 72 30 75 30 78 30 7B 30 7E 30 7F 30" + - "80 30 81 30 82 30 84 30 86 30 88 30 89 30 8A 30" + - "8B 30 8C 30 8D 30 8F 30 92 30 93 30 30 00 30 00" + - "37 00 34 00 32 00 01 42 30 44 30 46 30 48 30 4A" + - "30 4B 30 4D 30 4F 30 51 30 53 30 55 30 57 30 59" + - "30 5B 30 5D 30 5F 30 61 30 64 30 66 30 68 30 6A" + - "30 6B 30 6C 30 6D 30 6E 30 6F 30 72 30 75 30 78" + - "30 7B 30 7E 30 7F 30 80 30 81 30 82 30 84 30 86" + - "30 88 30 89 30 8A 30 8B 30 8C 30 8D 30 8F 30 92" + - "30 93 30 30 00 30 00 37 00 35 00 32 00 01 42 30" + - "44 30 46 30 48 30 4A 30 4B 30 4D 30 4F 30 51 30" + - "53 30 55 30 57 30 59 30 5B 30 5D 30 5F 30 61 30" + - "64 30 66 30 68 30 6A 30 6B 30 6C 30 6D 30 6E 30" + - "6F 30 72 30 75 30 78 30 7B 30 7E 30 7F 30 80 30" + - "81 30 82 30 84 30 86 30 88 30 89 30 8A 30 8B 30" + - "8C 30 8D 30 8F 30 92 30 93 30 30 00 30 00 37 00" + - "36 00 32 00 01 42 30 44 30 46 30 48 30 4A 30 4B" + - "30 4D 30 4F 30 51 30 53 30 55 30 57 30 59 30 5B" + - "30 5D 30 5F 30 61 30 64 30 66 30 68 30 6A 30 6B" + - "30 6C 30 6D 30 6E 30 6F 30 72 30 75 30 78 30 7B" + - "30 7E 30 7F 30 80 30 81 30 82 30 84 30 86 30 88" + - "30 89 30 8A 30 8B 30 8C 30 8D 30 8F 30 92 30 93" + - "30 30 00 30 00 37 00 37 00 32 00 01 42 30 44 30" + - "46 30 48 30 4A 30 4B 30 4D 30 4F 30 51 30 53 30" + - "55 30 57 30 59 30 5B 30 5D 30 5F 30 61 30 64 30" + - "66 30 68 30 6A 30 6B 30 6C 30 6D 30 6E 30 6F 30" + - "72 30 75 30 78 30 7B 30 7E 30 7F 30 80 30 81 30" + - "82 30 84 30 86 30 88 30 89 30 8A 30 8B 30 8C 30" + - "8D 30 8F 30 92 30 93 30 30 00 30 00 37 00 38 00" + - "18 00 05 96 00 00 00 17 53 77 6D 53 90 52 97 EE" + - "68 0C 77 A9 5C 4B 62 0C 77 8F 79 F6 5C 0C 77 03" + - "68 28 67 0C 77 FC 57 89 73 0C 77 71 67 AC 4E FD" + - "90 43 53 49 84 0C 77 01 00 92 00 05 00 35 00 08" + - "00 2C 00 2C 00 DB 30 C3 30 AB 30 A4 30 C9 30 A6" + - "30 A2 30 AA 30 E2 30 EA 30 B1 30 F3 30 A4 30 EF" + - "30 C6 30 B1 30 F3 30 D5 30 AF 30 B7 30 DE 30 B1" + - "30 F3 30 C8 30 C1 30 AE 30 B1 30 F3 30 B5 30 A4" + - "30 BF 30 DE 30 B1 30 F3 30 C8 30 A6 30 AD 30 E7" + - "30 A6 30 C8 30 C1 30 D0 30 B1 30 F3 30 00 00 00" + - "00 03 00 06 00 03 00 03 00 0C 00 06 00 03 00 11" + - "00 09 00 03 00 17 " + - - //Offset=0x00002636(9782) recno=72 sid=0x003C size=0x010D(269) - " 3C 00 0D 01 00 0C 00 03 00 1C" + - "00 0F 00 03 00 22 00 12 00 03 00 28 00 15 00 03" + - "00 32 00 05 10 00 00 00 42 30 44 30 46 30 48 30" + - "4A 30 4B 30 4D 30 4F 30 51 30 53 30 55 30 57 30" + - "59 30 5B 30 5D 30 5F 30 61 30 64 30 66 30 68 30" + - "6A 30 6B 30 6C 30 6D 30 6E 30 6F 30 72 30 75 30" + - "78 30 7B 30 7E 30 7F 30 80 30 81 30 82 30 84 30" + - "86 30 88 30 89 30 8A 30 8B 30 8C 30 8D 30 8F 30" + - "92 30 93 30 30 00 30 00 37 00 39 00 01 00 0C 00" + - "05 00 35 00 00 00 00 00 00 00 00 00 32 00 05 10" + - "00 00 00 42 30 44 30 46 30 48 30 4A 30 4B 30 4D" + - "30 4F 30 51 30 53 30 55 30 57 30 59 30 5B 30 5D" + - "30 5F 30 61 30 64 30 66 30 68 30 6A 30 6B 30 6C" + - "30 6D 30 6E 30 6F 30 72 30 75 30 78 30 7B 30 7E" + - "30 7F 30 80 30 81 30 82 30 84 30 86 30 88 30 89" + - "30 8A 30 8B 30 8C 30 8D 30 8F 30 92 30 93 30 30" + - "00 30 00 38 00 30 00 01 00 0C 00 05 00 35 00 00" + - "00 00 00 00 00 4B 30 "; - - - /** - * deep comparison of two SST records - */ - private static void assertRecordEquals(SSTRecord expected, SSTRecord actual){ - assertEquals("number of strings", expected.getNumStrings(), actual.getNumStrings()); - assertEquals("number of unique strings", expected.getNumUniqueStrings(), actual.getNumUniqueStrings()); - assertEquals("count of strings", expected.countStrings(), actual.countStrings()); - for ( int k = 0; k < expected.countStrings(); k++ ) { - org.apache.poi.hssf.record.common.UnicodeString us1 = expected.getString(k); - org.apache.poi.hssf.record.common.UnicodeString us2 = actual.getString(k); - - assertTrue("String at idx=" + k, us1.equals(us2)); - } - } - - @Test - public void test50779_1(){ - byte[] bytes = HexRead.readFromString(data_50779_1); - - RecordInputStream in = TestcaseRecordInputStream.create(bytes); - assertEquals(SSTRecord.sid, in.getSid()); - SSTRecord src = new SSTRecord(in); - assertEquals(81, src.getNumStrings()); - - byte[] serialized = src.serialize(); - - in = TestcaseRecordInputStream.create(serialized); - assertEquals(SSTRecord.sid, in.getSid()); - SSTRecord dst = new SSTRecord(in); - assertEquals(81, dst.getNumStrings()); - - assertRecordEquals(src, dst); - } - - @Test - public void test50779_2() { - byte[] bytes = HexRead.readFromString(data_50779_2); - - RecordInputStream in = TestcaseRecordInputStream.create(bytes); - assertEquals(SSTRecord.sid, in.getSid()); - SSTRecord src = new SSTRecord(in); - assertEquals(81, src.getNumStrings()); - - byte[] serialized = src.serialize(); - - in = TestcaseRecordInputStream.create(serialized); - assertEquals(SSTRecord.sid, in.getSid()); - SSTRecord dst = new SSTRecord(in); - assertEquals(81, dst.getNumStrings()); - - assertRecordEquals(src, dst); - } - - @Test - public void test57456() { - byte[] bytes = HexRead.readFromString("FC, 00, 08, 00, 00, 00, 00, 00, E1, 06, 00, 00"); - RecordInputStream in = TestcaseRecordInputStream.create(bytes); - assertEquals(SSTRecord.sid, in.getSid()); - SSTRecord src = new SSTRecord(in); - assertEquals(0, src.getNumStrings()); - assertEquals(0, src.getNumUniqueStrings()); - - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestSSTRecordSizeCalculator.java b/src/testcases/org/apache/poi/hssf/record/TestSSTRecordSizeCalculator.java deleted file mode 100644 index 80380ac5e..000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestSSTRecordSizeCalculator.java +++ /dev/null @@ -1,119 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record; - -import junit.framework.TestCase; - -import org.apache.poi.hssf.record.common.UnicodeString; -import org.apache.poi.hssf.record.cont.ContinuableRecordOutput; -import org.apache.poi.util.IntMapper; - -/** - * Tests that records size calculates correctly. - * - * @author Glen Stampoultzis (glens at apache.org) - */ -public final class TestSSTRecordSizeCalculator extends TestCase { - private static final String SMALL_STRING = "Small string"; - private static final int COMPRESSED_PLAIN_STRING_OVERHEAD = 3; - private static final int OPTION_FIELD_SIZE = 1; - - private final IntMapper strings = new IntMapper(); - - private void confirmSize(int expectedSize) { - ContinuableRecordOutput cro = ContinuableRecordOutput.createForCountingOnly(); - SSTSerializer ss = new SSTSerializer(strings, 0, 0); - ss.serialize(cro); - assertEquals(expectedSize, cro.getTotalSize()); - } - - public void testBasic() { - strings.add(makeUnicodeString(SMALL_STRING)); - confirmSize(SSTRecord.SST_RECORD_OVERHEAD - + COMPRESSED_PLAIN_STRING_OVERHEAD - + SMALL_STRING.length()); - } - - public void testBigStringAcrossUnicode() { - int bigString = SSTRecord.MAX_DATA_SPACE + 100; - strings.add(makeUnicodeString(bigString)); - confirmSize(SSTRecord.SST_RECORD_OVERHEAD - + COMPRESSED_PLAIN_STRING_OVERHEAD - + SSTRecord.MAX_DATA_SPACE - + SSTRecord.STD_RECORD_OVERHEAD - + OPTION_FIELD_SIZE - + 100); - } - - public void testPerfectFit() { - int perfectFit = SSTRecord.MAX_DATA_SPACE - COMPRESSED_PLAIN_STRING_OVERHEAD; - strings.add(makeUnicodeString(perfectFit)); - confirmSize(SSTRecord.SST_RECORD_OVERHEAD - + COMPRESSED_PLAIN_STRING_OVERHEAD - + perfectFit); - } - - public void testJustOversized() { - int tooBig = SSTRecord.MAX_DATA_SPACE - COMPRESSED_PLAIN_STRING_OVERHEAD + 1; - strings.add(makeUnicodeString(tooBig)); - confirmSize(SSTRecord.SST_RECORD_OVERHEAD - + COMPRESSED_PLAIN_STRING_OVERHEAD - + tooBig - 1 - // continue record - + SSTRecord.STD_RECORD_OVERHEAD - + OPTION_FIELD_SIZE + 1); - - } - - public void testSecondStringStartsOnNewContinuation() { - int perfectFit = SSTRecord.MAX_DATA_SPACE - COMPRESSED_PLAIN_STRING_OVERHEAD; - strings.add(makeUnicodeString(perfectFit)); - strings.add(makeUnicodeString(SMALL_STRING)); - confirmSize(SSTRecord.SST_RECORD_OVERHEAD - + SSTRecord.MAX_DATA_SPACE - // second string - + SSTRecord.STD_RECORD_OVERHEAD - + COMPRESSED_PLAIN_STRING_OVERHEAD - + SMALL_STRING.length()); - } - - public void testHeaderCrossesNormalContinuePoint() { - int almostPerfectFit = SSTRecord.MAX_DATA_SPACE - COMPRESSED_PLAIN_STRING_OVERHEAD - 2; - strings.add(makeUnicodeString(almostPerfectFit)); - String oneCharString = new String(new char[1]); - strings.add(makeUnicodeString(oneCharString)); - confirmSize(SSTRecord.SST_RECORD_OVERHEAD - + COMPRESSED_PLAIN_STRING_OVERHEAD - + almostPerfectFit - // second string - + SSTRecord.STD_RECORD_OVERHEAD - + COMPRESSED_PLAIN_STRING_OVERHEAD - + oneCharString.length()); - - } - private static UnicodeString makeUnicodeString(int size) { - String s = new String(new char[size]); - return makeUnicodeString(s); - } - - private static UnicodeString makeUnicodeString(String s) { - UnicodeString st = new UnicodeString(s); - st.setOptionFlags((byte) 0); - return st; - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestSharedFormulaRecord.java b/src/testcases/org/apache/poi/hssf/record/TestSharedFormulaRecord.java deleted file mode 100644 index 98f1e855c..000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestSharedFormulaRecord.java +++ /dev/null @@ -1,248 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record; - -import junit.framework.AssertionFailedError; -import junit.framework.ComparisonFailure; -import junit.framework.TestCase; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.apache.poi.ss.formula.ptg.RefPtg; -import org.apache.poi.ss.formula.SharedFormula; -import org.apache.poi.hssf.usermodel.*; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; -import org.apache.poi.ss.formula.FormulaParser; -import org.apache.poi.ss.formula.FormulaRenderer; -import org.apache.poi.ss.formula.FormulaType; -import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.util.LittleEndianInput; - -/** - * @author Josh Micich - */ -public final class TestSharedFormulaRecord extends TestCase { - - /** - * A sample spreadsheet known to have one sheet with 4 shared formula ranges - */ - private static final String SHARED_FORMULA_TEST_XLS = "SharedFormulaTest.xls"; - /** - * Binary data for an encoded formula. Taken from attachment 22062 (bugzilla 45123/45421). - * The shared formula is in Sheet1!C6:C21, with text "SUMPRODUCT(--(End_Acct=$C6),--(End_Bal))" - * This data is found at offset 0x1A4A (within the shared formula record). - * The critical thing about this formula is that it contains shared formula tokens (tRefN*, - * tAreaN*) with operand class 'array'. - */ - private static final byte[] SHARED_FORMULA_WITH_REF_ARRAYS_DATA = { - 0x1A, 0x00, - 0x63, 0x02, 0x00, 0x00, 0x00, - 0x6C, 0x00, 0x00, 0x02, (byte)0x80, // tRefNA - 0x0B, - 0x15, - 0x13, - 0x13, - 0x63, 0x03, 0x00, 0x00, 0x00, - 0x15, - 0x13, - 0x13, - 0x42, 0x02, (byte)0xE4, 0x00, - }; - - /** - * The method SharedFormulaRecord.convertSharedFormulas() converts formulas from - * 'shared formula' to 'single cell formula' format. It is important that token operand - * classes are preserved during this transformation, because Excel may not tolerate the - * incorrect encoding. The formula here is one such example (Excel displays #VALUE!). - */ - public void testConvertSharedFormulasOperandClasses_bug45123() { - - LittleEndianInput in = TestcaseRecordInputStream.createLittleEndian(SHARED_FORMULA_WITH_REF_ARRAYS_DATA); - int encodedLen = in.readUShort(); - Ptg[] sharedFormula = Ptg.readTokens(encodedLen, in); - - SharedFormula sf = new SharedFormula(SpreadsheetVersion.EXCEL97); - Ptg[] convertedFormula = sf.convertSharedFormulas(sharedFormula, 100, 200); - - RefPtg refPtg = (RefPtg) convertedFormula[1]; - assertEquals("$C101", refPtg.toFormulaString()); - if (refPtg.getPtgClass() == Ptg.CLASS_REF) { - throw new AssertionFailedError("Identified bug 45123"); - } - - confirmOperandClasses(sharedFormula, convertedFormula); - } - - private static void confirmOperandClasses(Ptg[] originalPtgs, Ptg[] convertedPtgs) { - assertEquals(originalPtgs.length, convertedPtgs.length); - for (int i = 0; i < convertedPtgs.length; i++) { - Ptg originalPtg = originalPtgs[i]; - Ptg convertedPtg = convertedPtgs[i]; - if (originalPtg.getPtgClass() != convertedPtg.getPtgClass()) { - throw new ComparisonFailure("Different operand class for token[" + i + "]", - String.valueOf(originalPtg.getPtgClass()), String.valueOf(convertedPtg.getPtgClass())); - } - } - } - - public void testConvertSharedFormulas() { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFEvaluationWorkbook fpb = HSSFEvaluationWorkbook.create(wb); - Ptg[] sharedFormula, convertedFormula; - - SharedFormula sf = new SharedFormula(SpreadsheetVersion.EXCEL97); - - sharedFormula = FormulaParser.parse("A2", fpb, FormulaType.CELL, -1); - convertedFormula = sf.convertSharedFormulas(sharedFormula, 0, 0); - confirmOperandClasses(sharedFormula, convertedFormula); - //conversion relative to [0,0] should return the original formula - assertEquals("A2", FormulaRenderer.toFormulaString(fpb, convertedFormula)); - - convertedFormula = sf.convertSharedFormulas(sharedFormula, 1, 0); - confirmOperandClasses(sharedFormula, convertedFormula); - //one row down - assertEquals("A3", FormulaRenderer.toFormulaString(fpb, convertedFormula)); - - convertedFormula = sf.convertSharedFormulas(sharedFormula, 1, 1); - confirmOperandClasses(sharedFormula, convertedFormula); - //one row down and one cell right - assertEquals("B3", FormulaRenderer.toFormulaString(fpb, convertedFormula)); - - sharedFormula = FormulaParser.parse("SUM(A1:C1)", fpb, FormulaType.CELL, -1); - convertedFormula = sf.convertSharedFormulas(sharedFormula, 0, 0); - confirmOperandClasses(sharedFormula, convertedFormula); - assertEquals("SUM(A1:C1)", FormulaRenderer.toFormulaString(fpb, convertedFormula)); - - convertedFormula = sf.convertSharedFormulas(sharedFormula, 1, 0); - confirmOperandClasses(sharedFormula, convertedFormula); - assertEquals("SUM(A2:C2)", FormulaRenderer.toFormulaString(fpb, convertedFormula)); - - convertedFormula = sf.convertSharedFormulas(sharedFormula, 1, 1); - confirmOperandClasses(sharedFormula, convertedFormula); - assertEquals("SUM(B2:D2)", FormulaRenderer.toFormulaString(fpb, convertedFormula)); - } - - /** - * Make sure that POI preserves {@link SharedFormulaRecord}s - */ - public void testPreserveOnReserialize() { - HSSFWorkbook wb; - HSSFSheet sheet; - HSSFCell cellB32769; - HSSFCell cellC32769; - - // Reading directly from XLS file - wb = HSSFTestDataSamples.openSampleWorkbook(SHARED_FORMULA_TEST_XLS); - sheet = wb.getSheetAt(0); - cellB32769 = sheet.getRow(32768).getCell(1); - cellC32769 = sheet.getRow(32768).getCell(2); - // check reading of formulas which are shared (two cells from a 1R x 8C range) - assertEquals("B32770*2", cellB32769.getCellFormula()); - assertEquals("C32770*2", cellC32769.getCellFormula()); - confirmCellEvaluation(wb, cellB32769, 4); - confirmCellEvaluation(wb, cellC32769, 6); - // Confirm this example really does have SharedFormulas. - // there are 3 others besides the one at A32769:H32769 - assertEquals(4, countSharedFormulas(sheet)); - - - // Re-serialize and check again - wb = HSSFTestDataSamples.writeOutAndReadBack(wb); - sheet = wb.getSheetAt(0); - cellB32769 = sheet.getRow(32768).getCell(1); - cellC32769 = sheet.getRow(32768).getCell(2); - assertEquals("B32770*2", cellB32769.getCellFormula()); - confirmCellEvaluation(wb, cellB32769, 4); - assertEquals(4, countSharedFormulas(sheet)); - } - - public void testUnshareFormulaDueToChangeFormula() { - HSSFWorkbook wb; - HSSFSheet sheet; - HSSFCell cellB32769; - HSSFCell cellC32769; - - wb = HSSFTestDataSamples.openSampleWorkbook(SHARED_FORMULA_TEST_XLS); - sheet = wb.getSheetAt(0); - cellB32769 = sheet.getRow(32768).getCell(1); - cellC32769 = sheet.getRow(32768).getCell(2); - - // Updating cell formula, causing it to become unshared - cellB32769.setCellFormula("1+1"); - confirmCellEvaluation(wb, cellB32769, 2); - // currently (Oct 2008) POI handles this by exploding the whole shared formula group - assertEquals(3, countSharedFormulas(sheet)); // one less now - // check that nearby cell of the same group still has the same formula - assertEquals("C32770*2", cellC32769.getCellFormula()); - confirmCellEvaluation(wb, cellC32769, 6); - } - public void testUnshareFormulaDueToDelete() { - HSSFWorkbook wb; - HSSFSheet sheet; - HSSFCell cell; - final int ROW_IX = 2; - - // changing shared formula cell to blank - wb = HSSFTestDataSamples.openSampleWorkbook(SHARED_FORMULA_TEST_XLS); - sheet = wb.getSheetAt(0); - - assertEquals("A$1*2", sheet.getRow(ROW_IX).getCell(1).getCellFormula()); - cell = sheet.getRow(ROW_IX).getCell(1); - cell.setCellType(CellType.BLANK); - assertEquals(3, countSharedFormulas(sheet)); - - wb = HSSFTestDataSamples.writeOutAndReadBack(wb); - sheet = wb.getSheetAt(0); - assertEquals("A$1*2", sheet.getRow(ROW_IX+1).getCell(1).getCellFormula()); - - // deleting shared formula cell - wb = HSSFTestDataSamples.openSampleWorkbook(SHARED_FORMULA_TEST_XLS); - sheet = wb.getSheetAt(0); - - assertEquals("A$1*2", sheet.getRow(ROW_IX).getCell(1).getCellFormula()); - cell = sheet.getRow(ROW_IX).getCell(1); - sheet.getRow(ROW_IX).removeCell(cell); - assertEquals(3, countSharedFormulas(sheet)); - - wb = HSSFTestDataSamples.writeOutAndReadBack(wb); - sheet = wb.getSheetAt(0); - assertEquals("A$1*2", sheet.getRow(ROW_IX+1).getCell(1).getCellFormula()); - } - - private static void confirmCellEvaluation(HSSFWorkbook wb, HSSFCell cell, double expectedValue) { - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - CellValue cv = fe.evaluate(cell); - assertEquals(CellType.NUMERIC, cv.getCellTypeEnum()); - assertEquals(expectedValue, cv.getNumberValue(), 0.0); - } - - /** - * @return the number of {@link SharedFormulaRecord}s encoded for the specified sheet - */ - private static int countSharedFormulas(HSSFSheet sheet) { - Record[] records = RecordInspector.getRecords(sheet, 0); - int count = 0; - for (Record rec : records) { - if(rec instanceof SharedFormulaRecord) { - count++; - } - } - return count; - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestStringRecord.java b/src/testcases/org/apache/poi/hssf/record/TestStringRecord.java deleted file mode 100644 index c73493cb3..000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestStringRecord.java +++ /dev/null @@ -1,103 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record; - - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -import java.io.IOException; - -import org.apache.poi.util.HexRead; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.LittleEndianByteArrayInputStream; -import org.junit.Test; - -/** - * Tests the serialization and deserialization of the StringRecord - * class works correctly. Test data taken directly from a real - * Excel file. - */ -public final class TestStringRecord { - private static final byte[] data = HexRead.readFromString( - "0B 00 " + // length - "00 " + // option - // string - "46 61 68 72 7A 65 75 67 74 79 70" - ); - - @Test - public void testLoad() { - - StringRecord record = new StringRecord(TestcaseRecordInputStream.create(0x207, data)); - assertEquals( "Fahrzeugtyp", record.getString()); - - assertEquals( 18, record.getRecordSize() ); - } - - @Test - public void testStore() { - StringRecord record = new StringRecord(); - record.setString("Fahrzeugtyp"); - - byte [] recordBytes = record.serialize(); - assertEquals(recordBytes.length - 4, data.length); - for (int i = 0; i < data.length; i++) { - assertEquals("At offset " + i, data[i], recordBytes[i+4]); - } - } - - @Test - public void testContinue() throws IOException { - int MAX_BIFF_DATA = RecordInputStream.MAX_RECORD_DATA_SIZE; - int TEXT_LEN = MAX_BIFF_DATA + 1000; // deliberately over-size - String textChunk = "ABCDEGGHIJKLMNOP"; // 16 chars - StringBuffer sb = new StringBuffer(16384); - while (sb.length() < TEXT_LEN) { - sb.append(textChunk); - } - sb.setLength(TEXT_LEN); - - StringRecord sr = new StringRecord(); - sr.setString(sb.toString()); - byte[] ser = sr.serialize(); - assertEquals(StringRecord.sid, LittleEndian.getUShort(ser, 0)); - if (LittleEndian.getUShort(ser, 2) > MAX_BIFF_DATA) { - fail("StringRecord should have been split with a continue record"); - } - // Confirm expected size of first record, and ushort strLen. - assertEquals(MAX_BIFF_DATA, LittleEndian.getUShort(ser, 2)); - assertEquals(TEXT_LEN, LittleEndian.getUShort(ser, 4)); - - // Confirm first few bytes of ContinueRecord - LittleEndianByteArrayInputStream crIn = new LittleEndianByteArrayInputStream(ser, (MAX_BIFF_DATA + 4)); - int nCharsInFirstRec = MAX_BIFF_DATA - (2 + 1); // strLen, optionFlags - int nCharsInSecondRec = TEXT_LEN - nCharsInFirstRec; - assertEquals(ContinueRecord.sid, crIn.readUShort()); - assertEquals(1 + nCharsInSecondRec, crIn.readUShort()); - assertEquals(0, crIn.readUByte()); - assertEquals('N', crIn.readUByte()); - assertEquals('O', crIn.readUByte()); - - // re-read and make sure string value is the same - RecordInputStream in = TestcaseRecordInputStream.create(ser); - StringRecord sr2 = new StringRecord(in); - assertEquals(sb.toString(), sr2.getString()); - crIn.close(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestStyleRecord.java b/src/testcases/org/apache/poi/hssf/record/TestStyleRecord.java deleted file mode 100644 index 890546c94..000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestStyleRecord.java +++ /dev/null @@ -1,46 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record; - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -import org.apache.poi.util.HexRead; - -/** - * Tests for {@link StyleRecord} - */ -public final class TestStyleRecord extends TestCase { - public void testUnicodeReadName() { - byte[] data = HexRead.readFromString( - "11 00 09 00 01 38 5E C4 89 5F 00 53 00 68 00 65 00 65 00 74 00 31 00"); - RecordInputStream in = TestcaseRecordInputStream.create(StyleRecord.sid, data); - StyleRecord sr = new StyleRecord(in); - assertEquals("\u5E38\u89C4_Sheet1", sr.getName()); // "_Sheet1" - byte[] ser; - try { - ser = sr.serialize(); - } catch (IllegalStateException e) { - if (e.getMessage().equals("Incorrect number of bytes written - expected 27 but got 18")) { - throw new AssertionFailedError("Identified bug 46385"); - } - throw e; - } - TestcaseRecordInputStream.confirmRecordEncoding(StyleRecord.sid, data, ser); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestSubRecord.java b/src/testcases/org/apache/poi/hssf/record/TestSubRecord.java deleted file mode 100644 index 56bc99f26..000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestSubRecord.java +++ /dev/null @@ -1,160 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - - -package org.apache.poi.hssf.record; - - -import static org.junit.Assert.assertArrayEquals; -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -import org.apache.poi.util.HexRead; -import org.apache.poi.util.LittleEndian; - -/** - * Tests Subrecord components of an OBJ record. Test data taken directly - * from a real Excel file. - * - * @author Michael Zalewski (zalewski@optonline.net) - */ -public final class TestSubRecord extends TestCase { - /* - The following is a dump of the OBJ record corresponding to an auto-filter - drop-down list. The 3rd subrecord beginning at offset 0x002e (type=0x0013) - does not conform to the documentation, because the length field is 0x1fee, - which is longer than the entire OBJ record. - - 00000000 15 00 12 00 14 00 01 00 01 21 00 00 00 00 3C 13 .........!....<. Type=0x15 Len=0x0012 ftCmo - 00000010 F4 03 00 00 00 00 - 0C 00 14 00 00 00 00 00 00 00 ................ Type=0x0c Len=0x0014 ftSbs - 00000020 00 00 00 00 01 00 08 00 00 00 10 00 00 00 - 13 00 ................ Type=0x13 Len=0x1FEE ftLbsData - 00000030 EE 1F 00 00 08 00 08 00 01 03 00 00 0A 00 14 00 ................ - 00000040 6C 00 - 00 00 00 00 l..... Type=0x00 Len=0x0000 ftEnd - */ - - private static final byte[] dataAutoFilter - = HexRead.readFromString("" - + "5D 00 46 00 " // ObjRecord.sid, size=70 - // ftCmo - + "15 00 12 00 " - + "14 00 01 00 01 00 01 21 00 00 3C 13 F4 03 00 00 00 00 " - // ftSbs (currently UnknownSubrecord) - + "0C 00 14 00 " - + "00 00 00 00 00 00 00 00 00 00 01 00 08 00 00 00 10 00 00 00 " - // ftLbsData (currently UnknownSubrecord) - + "13 00 EE 1F 00 00 " - + "08 00 08 00 01 03 00 00 0A 00 14 00 6C 00 " - // ftEnd - + "00 00 00 00" - ); - - - /** - * Make sure that ftLbsData (which has abnormal size info) is parsed correctly. - * If the size field is interpreted incorrectly, the resulting ObjRecord becomes way too big. - * At the time of fixing (Oct-2008 svn r707447) {@link RecordInputStream} allowed buffer - * read overruns, so the bug was mostly silent. - */ - public void testReadAll_bug45778() { - RecordInputStream in = TestcaseRecordInputStream.create(dataAutoFilter); - ObjRecord or = new ObjRecord(in); - byte[] data2 = or.serialize(); - if (data2.length == 8228) { - throw new AssertionFailedError("Identified bug 45778"); - } - assertEquals(74, data2.length); - assertArrayEquals(dataAutoFilter, data2); - } - - public void testReadManualComboWithFormula() { - byte[] data = HexRead.readFromString("" - + "5D 00 66 00 " - + "15 00 12 00 14 00 02 00 11 20 00 00 00 00 " - + "20 44 C6 04 00 00 00 00 0C 00 14 00 04 F0 C6 04 " - + "00 00 00 00 00 00 01 00 06 00 00 00 10 00 00 00 " - + "0E 00 0C 00 05 00 80 44 C6 04 24 09 00 02 00 02 " - + "13 00 DE 1F 10 00 09 00 80 44 C6 04 25 0A 00 0F " - + "00 02 00 02 00 02 06 00 03 00 08 00 00 00 00 00 " - + "08 00 00 00 00 00 00 00 " // TODO sometimes last byte is non-zero - ); - - RecordInputStream in = TestcaseRecordInputStream.create(data); - ObjRecord or = new ObjRecord(in); - byte[] data2 = or.serialize(); - if (data2.length == 8228) { - throw new AssertionFailedError("Identified bug 45778"); - } - assertEquals("Encoded length", data.length, data2.length); - for (int i = 0; i < data.length; i++) { - if (data[i] != data2[i]) { - throw new AssertionFailedError("Encoded data differs at index " + i); - } - } - assertArrayEquals(data, data2); - } - - /** - * Some versions of POI (e.g. 3.1 - prior to svn r707450 / bug 45778) interpreted the ftLbs - * subrecord second short (0x1FEE) as a length, and hence read lots of extra padding. This - * buffer-overrun in {@link RecordInputStream} happened silently due to problems later fixed - * in svn 707778. When the ObjRecord is written, the extra padding is written too, making the - * record 8224 bytes long instead of 70. - * (An aside: It seems more than a coincidence that this problem creates a record of exactly - * {@link RecordInputStream#MAX_RECORD_DATA_SIZE} but not enough is understood about - * subrecords to explain this.)
    - * - * Excel reads files with this excessive padding OK. It also truncates the over-sized - * ObjRecord back to the proper size. POI should do the same. - */ - public void testWayTooMuchPadding_bug46545() { - byte[] data = HexRead.readFromString("" - + "15 00 12 00 14 00 13 00 01 21 00 00 00" - + "00 98 0B 5B 09 00 00 00 00 0C 00 14 00 00 00 00 00 00 00 00" - + "00 00 00 01 00 01 00 00 00 10 00 00 00 " - // ftLbs - + "13 00 EE 1F 00 00 " - + "01 00 00 00 01 06 00 00 02 00 08 00 75 00 " - // ftEnd - + "00 00 00 00" - ); - final int LBS_START_POS = 0x002E; - final int WRONG_LBS_SIZE = 0x1FEE; - assertEquals(0x0013, LittleEndian.getShort(data, LBS_START_POS+0)); - assertEquals(WRONG_LBS_SIZE, LittleEndian.getShort(data, LBS_START_POS+2)); - int wrongTotalSize = LBS_START_POS + 4 + WRONG_LBS_SIZE; - byte[] wrongData = new byte[wrongTotalSize]; - System.arraycopy(data, 0, wrongData, 0, data.length); - // wrongData has the ObjRecord data as would have been written by v3.1 - - RecordInputStream in = TestcaseRecordInputStream.create(ObjRecord.sid, wrongData); - ObjRecord or; - try { - or = new ObjRecord(in); - } catch (RecordFormatException e) { - if (e.getMessage().startsWith("Leftover 8154 bytes in subrecord data")) { - throw new AssertionFailedError("Identified bug 46545"); - } - throw e; - } - // make sure POI properly truncates the ObjRecord data - byte[] data2 = or.serialize(); - TestcaseRecordInputStream.confirmRecordEncoding(ObjRecord.sid, data, data2); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestSupBookRecord.java b/src/testcases/org/apache/poi/hssf/record/TestSupBookRecord.java deleted file mode 100644 index 47926cfe0..000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestSupBookRecord.java +++ /dev/null @@ -1,157 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record; - - -import junit.framework.TestCase; - -import static org.apache.poi.hssf.record.SupBookRecord.*; - -/** - * Tests the serialization and deserialization of the SupBook record - * class works correctly. - * - * @author Andrew C. Oliver (acoliver at apache dot org) - */ -public final class TestSupBookRecord extends TestCase { - /** - * This contains a fake data section of a SubBookRecord - */ - byte[] dataIR = new byte[] { - (byte)0x04,(byte)0x00,(byte)0x01,(byte)0x04, - }; - byte[] dataAIF = new byte[] { - (byte)0x01,(byte)0x00,(byte)0x01,(byte)0x3A, - }; - byte[] dataER = new byte[] { - (byte)0x02,(byte)0x00, - (byte)0x07,(byte)0x00, (byte)0x00, - (byte)'t', (byte)'e', (byte)'s', (byte)'t', (byte)'U', (byte)'R', (byte)'L', - (byte)0x06,(byte)0x00, (byte)0x00, - (byte)'S', (byte)'h', (byte)'e', (byte)'e', (byte)'t', (byte)'1', - (byte)0x06,(byte)0x00, (byte)0x00, - (byte)'S', (byte)'h', (byte)'e', (byte)'e', (byte)'t', (byte)'2', - }; - - /** - * tests that we can load the record - */ - public void testLoadIR() { - - SupBookRecord record = new SupBookRecord(TestcaseRecordInputStream.create(0x01AE, dataIR)); - assertTrue( record.isInternalReferences() ); //expected flag - assertEquals( 0x4, record.getNumberOfSheets() ); //expected # of sheets - - assertEquals( 8, record.getRecordSize() ); //sid+size+data - } - /** - * tests that we can load the record - */ - public void testLoadER() { - - SupBookRecord record = new SupBookRecord(TestcaseRecordInputStream.create(0x01AE, dataER)); - assertTrue( record.isExternalReferences() ); //expected flag - assertEquals( 0x2, record.getNumberOfSheets() ); //expected # of sheets - - assertEquals( 34, record.getRecordSize() ); //sid+size+data - - assertEquals("testURL", record.getURL()); - String[] sheetNames = record.getSheetNames(); - assertEquals(2, sheetNames.length); - assertEquals("Sheet1", sheetNames[0]); - assertEquals("Sheet2", sheetNames[1]); - } - - /** - * tests that we can load the record - */ - public void testLoadAIF() { - - SupBookRecord record = new SupBookRecord(TestcaseRecordInputStream.create(0x01AE, dataAIF)); - assertTrue( record.isAddInFunctions() ); //expected flag - assertEquals( 0x1, record.getNumberOfSheets() ); //expected # of sheets - assertEquals( 8, record.getRecordSize() ); //sid+size+data - } - - /** - * Tests that we can store the record - * - */ - public void testStoreIR() { - SupBookRecord record = SupBookRecord.createInternalReferences((short)4); - - TestcaseRecordInputStream.confirmRecordEncoding(0x01AE, dataIR, record.serialize()); - } - - public void testStoreER() { - String url = "testURL"; - String[] sheetNames = { "Sheet1", "Sheet2", }; - SupBookRecord record = SupBookRecord.createExternalReferences(url, sheetNames); - - TestcaseRecordInputStream.confirmRecordEncoding(0x01AE, dataER, record.serialize()); - } - - public void testStoreAIF() { - SupBookRecord record = SupBookRecord.createAddInFunctions(); - assertEquals(1, record.getNumberOfSheets()); - assertTrue(record.isAddInFunctions()); - TestcaseRecordInputStream.confirmRecordEncoding(0x01AE, dataAIF, record.serialize()); - } - - public void testExternalReferenceUrl() { - String[] sheetNames = new String[]{"SampleSheet"}; - final char startMarker = (char)1; - - SupBookRecord record; - - record = new SupBookRecord(startMarker + "test.xls", sheetNames); - assertEquals("test.xls", record.getURL()); - - //UNC path notation - record = new SupBookRecord(startMarker + "" + CH_VOLUME + "@servername" + CH_DOWN_DIR + "test.xls", sheetNames); - assertEquals("\\\\servername" + PATH_SEPERATOR + "test.xls", record.getURL()); - - //Absolute path notation - different device - record = new SupBookRecord(startMarker + "" + CH_VOLUME + "D" + CH_DOWN_DIR + "test.xls", sheetNames); - assertEquals("D:" + PATH_SEPERATOR + "test.xls", record.getURL()); - - //Absolute path notation - same device - record = new SupBookRecord(startMarker + "" + CH_SAME_VOLUME + "folder" + CH_DOWN_DIR + "test.xls", sheetNames); - assertEquals(PATH_SEPERATOR + "folder" + PATH_SEPERATOR + "test.xls", record.getURL()); - - //Relative path notation - down - record = new SupBookRecord(startMarker + "folder" + CH_DOWN_DIR + "test.xls", sheetNames); - assertEquals("folder" + PATH_SEPERATOR + "test.xls", record.getURL()); - - //Relative path notation - up - record = new SupBookRecord(startMarker +""+ CH_UP_DIR + "test.xls", sheetNames); - assertEquals(".." + PATH_SEPERATOR + "test.xls", record.getURL()); - - //Relative path notation - for EXCEL.exe - fallback - record = new SupBookRecord(startMarker +""+ CH_STARTUP_DIR + "test.xls", sheetNames); - assertEquals("." + PATH_SEPERATOR + "test.xls", record.getURL()); - - //Relative path notation - for EXCEL lib folder - fallback - record = new SupBookRecord(startMarker +""+ CH_LIB_DIR + "test.xls", sheetNames); - assertEquals("." + PATH_SEPERATOR + "test.xls", record.getURL()); - - //Relative path notation - for alternative EXCEL.exe - fallback - record = new SupBookRecord(startMarker +""+ CH_ALT_STARTUP_DIR+ "test.xls", sheetNames); - assertEquals("." + PATH_SEPERATOR + "test.xls", record.getURL()); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestTableRecord.java b/src/testcases/org/apache/poi/hssf/record/TestTableRecord.java deleted file mode 100644 index 3a2ada6e7..000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestTableRecord.java +++ /dev/null @@ -1,94 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record; - -import org.apache.poi.hssf.util.CellRangeAddress8Bit; - -import junit.framework.TestCase; - -/** - * Tests the serialization and deserialization of the TableRecord - * class works correctly. Test data taken directly from a real - * Excel file. - */ -public final class TestTableRecord extends TestCase { - byte[] header = new byte[] { - 0x36, 02, 0x10, 00, // sid=x236, 16 bytes long - }; - byte[] data = new byte[] { - 03, 00, // from row 3 - 8, 00, // to row 8 - 04, // from col 4 - 06, // to col 6 - 00, 00, // no flags set - 04, 00, // row inp row 4 - 01, 00, // col inp row 1 - 0x76, 0x40, // row inp col 0x4076 (!) - 00, 00 // col inp col 0 - }; - - public void testLoad() { - - TableRecord record = new TableRecord(TestcaseRecordInputStream.create(0x236, data)); - - CellRangeAddress8Bit range = record.getRange(); - assertEquals(3, range.getFirstRow()); - assertEquals(8, range.getLastRow()); - assertEquals(4, range.getFirstColumn()); - assertEquals(6, range.getLastColumn()); - assertEquals(0, record.getFlags()); - assertEquals(4, record.getRowInputRow()); - assertEquals(1, record.getColInputRow()); - assertEquals(0x4076, record.getRowInputCol()); - assertEquals(0, record.getColInputCol()); - - assertEquals( 16 + 4, record.getRecordSize() ); - } - - public void testStore() - { -// Offset 0x3bd9 (15321) -// recordid = 0x236, size = 16 -// [TABLE] -// .row from = 3 -// .row to = 8 -// .column from = 4 -// .column to = 6 -// .flags = 0 -// .always calc =false -// .reserved = 0 -// .row input row = 4 -// .col input row = 1 -// .row input col = 4076 -// .col input col = 0 -// [/TABLE] - - CellRangeAddress8Bit crab = new CellRangeAddress8Bit(3, 8, 4, 6); - TableRecord record = new TableRecord(crab); - record.setFlags((byte)0); - record.setRowInputRow(4); - record.setColInputRow(1); - record.setRowInputCol(0x4076); - record.setColInputCol(0); - - byte [] recordBytes = record.serialize(); - assertEquals(recordBytes.length - 4, data.length); - for (int i = 0; i < data.length; i++) - assertEquals("At offset " + i, data[i], recordBytes[i+4]); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestTextObjectBaseRecord.java b/src/testcases/org/apache/poi/hssf/record/TestTextObjectBaseRecord.java deleted file mode 100644 index b14fd762c..000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestTextObjectBaseRecord.java +++ /dev/null @@ -1,87 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record; - - -import org.apache.poi.hssf.usermodel.HSSFRichTextString; -import org.apache.poi.util.HexRead; - -import junit.framework.TestCase; - -/** - * Tests the serialization and deserialization of the TextObjectBaseRecord - * class works correctly. Test data taken directly from a real - * Excel file. - * - * @author Glen Stampoultzis (glens at apache.org) - */ -public final class TestTextObjectBaseRecord extends TestCase { - /** data for one TXO rec and two continue recs */ - private static final byte[] data = HexRead.readFromString( - "B6 01 " + // TextObjectRecord.sid - "12 00 " + // size 18 - "44 02 02 00 00 00 00 00" + - "00 00 " + - "02 00 " + // strLen 2 - "10 00 " + // 16 bytes for 2 format runs - "00 00" + - "00 00 " + - "3C 00 " + // ContinueRecord.sid - "03 00 " + // size 3 - "00 " + // unicode compressed - "41 42 " + // 'AB' - "3C 00 " + // ContinueRecord.sid - "10 00 " + // size 16 - "00 00 18 00 00 00 00 00 " + - "02 00 00 00 00 00 00 00 " - ); - - - public void testLoad() { - RecordInputStream in = TestcaseRecordInputStream.create(data); - TextObjectRecord record = new TextObjectRecord(in); - - assertEquals(TextObjectRecord.HORIZONTAL_TEXT_ALIGNMENT_CENTERED, record.getHorizontalTextAlignment()); - assertEquals(TextObjectRecord.VERTICAL_TEXT_ALIGNMENT_JUSTIFY, record.getVerticalTextAlignment()); - assertEquals(true, record.isTextLocked()); - assertEquals(TextObjectRecord.TEXT_ORIENTATION_ROT_RIGHT, record.getTextOrientation()); - - assertEquals(49, record.getRecordSize() ); - } - - public void testStore() - { - TextObjectRecord record = new TextObjectRecord(); - - - HSSFRichTextString str = new HSSFRichTextString("AB"); - str.applyFont(0, 2, (short)0x0018); - str.applyFont(2, 2, (short)0x0320); - - record.setHorizontalTextAlignment(TextObjectRecord.HORIZONTAL_TEXT_ALIGNMENT_CENTERED); - record.setVerticalTextAlignment(TextObjectRecord.VERTICAL_TEXT_ALIGNMENT_JUSTIFY); - record.setTextLocked(true); - record.setTextOrientation(TextObjectRecord.TEXT_ORIENTATION_ROT_RIGHT); - record.setStr(str); - - byte [] recordBytes = record.serialize(); - assertEquals(recordBytes.length, data.length); - for (int i = 0; i < data.length; i++) - assertEquals("At offset " + i, data[i], recordBytes[i]); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestTextObjectRecord.java b/src/testcases/org/apache/poi/hssf/record/TestTextObjectRecord.java deleted file mode 100644 index 330e93df9..000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestTextObjectRecord.java +++ /dev/null @@ -1,195 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record; - -import static org.junit.Assert.assertArrayEquals; - -import java.io.ByteArrayInputStream; - -import junit.framework.TestCase; - -import org.apache.poi.hssf.usermodel.HSSFRichTextString; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.apache.poi.ss.formula.ptg.RefPtg; -import org.apache.poi.util.HexRead; -import org.apache.poi.util.LittleEndian; - -/** - * Tests that serialization and deserialization of the TextObjectRecord . - * Test data taken directly from a real Excel file. - * - * @author Yegor Kozlov - */ -public final class TestTextObjectRecord extends TestCase { - - private static final byte[] simpleData = HexRead.readFromString( - "B6 01 12 00 " + - "12 02 00 00 00 00 00 00" + - "00 00 0D 00 08 00 00 00" + - "00 00 " + - "3C 00 0E 00 " + - "00 48 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21 " + - "3C 00 08 " + - "00 0D 00 00 00 00 00 00 00" - ); - - - public void testRead() { - - RecordInputStream is =TestcaseRecordInputStream.create(simpleData); - TextObjectRecord record = new TextObjectRecord(is); - - assertEquals(TextObjectRecord.sid, record.getSid()); - assertEquals(TextObjectRecord.HORIZONTAL_TEXT_ALIGNMENT_LEFT_ALIGNED, record.getHorizontalTextAlignment()); - assertEquals(TextObjectRecord.VERTICAL_TEXT_ALIGNMENT_TOP, record.getVerticalTextAlignment()); - assertEquals(TextObjectRecord.TEXT_ORIENTATION_NONE, record.getTextOrientation()); - assertEquals("Hello, World!", record.getStr().getString()); - } - - public void testWrite() { - HSSFRichTextString str = new HSSFRichTextString("Hello, World!"); - - TextObjectRecord record = new TextObjectRecord(); - record.setStr(str); - record.setHorizontalTextAlignment( TextObjectRecord.HORIZONTAL_TEXT_ALIGNMENT_LEFT_ALIGNED ); - record.setVerticalTextAlignment( TextObjectRecord.VERTICAL_TEXT_ALIGNMENT_TOP ); - record.setTextLocked( true ); - record.setTextOrientation( TextObjectRecord.TEXT_ORIENTATION_NONE ); - - byte [] ser = record.serialize(); - assertEquals(ser.length , simpleData.length); - - assertArrayEquals(simpleData, ser); - - //read again - RecordInputStream is = TestcaseRecordInputStream.create(simpleData); - record = new TextObjectRecord(is); - } - - /** - * Zero {@link ContinueRecord}s follow a {@link TextObjectRecord} if the text is empty - */ - public void testWriteEmpty() { - HSSFRichTextString str = new HSSFRichTextString(""); - - TextObjectRecord record = new TextObjectRecord(); - record.setStr(str); - - byte [] ser = record.serialize(); - - int formatDataLen = LittleEndian.getUShort(ser, 16); - assertEquals("formatDataLength", 0, formatDataLen); - - assertEquals(22, ser.length); // just the TXO record - - //read again - RecordInputStream is = TestcaseRecordInputStream.create(ser); - record = new TextObjectRecord(is); - assertEquals(0, record.getStr().length()); - } - - /** - * Test that TextObjectRecord serializes logs records properly. - */ - public void testLongRecords() { - int[] lengths = {1024, 2048, 4096, 8192, 16384}; //test against strings of different length - for (int length : lengths) { - StringBuffer buff = new StringBuffer(length); - for (int j = 0; j < length; j++) { - buff.append("x"); - } - HSSFRichTextString str = new HSSFRichTextString(buff.toString()); - - TextObjectRecord obj = new TextObjectRecord(); - obj.setStr(str); - - byte [] data = obj.serialize(); - RecordInputStream is = new RecordInputStream(new ByteArrayInputStream(data)); - is.nextRecord(); - TextObjectRecord record = new TextObjectRecord(is); - str = record.getStr(); - - assertEquals(buff.length(), str.length()); - assertEquals(buff.toString(), str.getString()); - } - } - - /** - * Test cloning - */ - public void testClone() { - String text = "Hello, World"; - HSSFRichTextString str = new HSSFRichTextString(text); - - TextObjectRecord obj = new TextObjectRecord(); - obj.setStr( str ); - - - TextObjectRecord cloned = (TextObjectRecord)obj.clone(); - assertEquals(obj.getRecordSize(), cloned.getRecordSize()); - assertEquals(obj.getHorizontalTextAlignment(), cloned.getHorizontalTextAlignment()); - assertEquals(obj.getStr().getString(), cloned.getStr().getString()); - - //finally check that the serialized data is the same - byte[] src = obj.serialize(); - byte[] cln = cloned.serialize(); - assertArrayEquals(src, cln); - } - - /** similar to {@link #simpleData} but with link formula at end of TXO rec*/ - private static final byte[] linkData = HexRead.readFromString( - "B6 01 " + // TextObjectRecord.sid - "1E 00 " + // size 18 - "44 02 02 00 00 00 00 00" + - "00 00 " + - "02 00 " + // strLen 2 - "10 00 " + // 16 bytes for 2 format runs - "00 00 00 00 " + - - "05 00 " + // formula size - "D4 F0 8A 03 " + // unknownInt - "24 01 00 13 C0 " + //tRef(T2) - "13 " + // ?? - - "3C 00 " + // ContinueRecord.sid - "03 00 " + // size 3 - "00 " + // unicode compressed - "41 42 " + // 'AB' - "3C 00 " + // ContinueRecord.sid - "10 00 " + // size 16 - "00 00 18 00 00 00 00 00 " + - "02 00 00 00 00 00 00 00 " - ); - - - public void testLinkFormula() { - RecordInputStream is = new RecordInputStream(new ByteArrayInputStream(linkData)); - is.nextRecord(); - TextObjectRecord rec = new TextObjectRecord(is); - - Ptg ptg = rec.getLinkRefPtg(); - assertNotNull(ptg); - assertEquals(RefPtg.class, ptg.getClass()); - RefPtg rptg = (RefPtg) ptg; - assertEquals("T2", rptg.toFormulaString()); - - byte [] data2 = rec.serialize(); - assertEquals(linkData.length, data2.length); - assertArrayEquals(linkData, data2); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestUnicodeNameRecord.java b/src/testcases/org/apache/poi/hssf/record/TestUnicodeNameRecord.java deleted file mode 100644 index 6ec080384..000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestUnicodeNameRecord.java +++ /dev/null @@ -1,36 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record; - - -import junit.framework.TestCase; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -/** - * - */ -public final class TestUnicodeNameRecord extends TestCase { - - public void testReadBook() { - - // This bit used to crash - HSSFWorkbook book = HSSFTestDataSamples.openSampleWorkbook("unicodeNameRecord.xls"); - book.getSheetAt(0); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestWriteAccessRecord.java b/src/testcases/org/apache/poi/hssf/record/TestWriteAccessRecord.java deleted file mode 100644 index fa0700c4a..000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestWriteAccessRecord.java +++ /dev/null @@ -1,103 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record; - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -import org.apache.poi.util.HexRead; - -/** - * Tests for {@link WriteAccessRecord} - * - * @author Josh Micich - */ -public final class TestWriteAccessRecord extends TestCase { - - private static final String HEX_SIXTYFOUR_SPACES = "" - + "20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 " - + "20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 " - + "20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 " - + "20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20"; - - - public void testMissingStringHeader_bug47001a() { - /* - * Data taken from offset 0x0224 in - * attachment 23468 from bugzilla 47001 - */ - byte[] data = HexRead.readFromString("" - + "5C 00 70 00 " - + "4A 61 76 61 20 45 78 63 65 6C 20 41 50 49 20 76 " - + "32 2E 36 2E 34" - + "20 20 20 20 20 20 20 20 20 20 20 " - + "20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 " - + HEX_SIXTYFOUR_SPACES); - - RecordInputStream in = TestcaseRecordInputStream.create(data); - - WriteAccessRecord rec; - try { - rec = new WriteAccessRecord(in); - } catch (RecordFormatException e) { - if (e.getMessage().equals("Not enough data (0) to read requested (1) bytes")) { - throw new AssertionFailedError("Identified bug 47001a"); - } - throw e; - } - assertEquals("Java Excel API v2.6.4", rec.getUsername()); - - - byte[] expectedEncoding = HexRead.readFromString("" - + "15 00 00 4A 61 76 61 20 45 78 63 65 6C 20 41 50 " - + "49 20 76 32 2E 36 2E 34" - + "20 20 20 20 20 20 20 20 " - + "20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 " - + HEX_SIXTYFOUR_SPACES); - - TestcaseRecordInputStream.confirmRecordEncoding(WriteAccessRecord.sid, expectedEncoding, rec.serialize()); - } - - public void testShortRecordWrittenByMSAccess() { - /* - * Data taken from two example files - * ex42564-21435.xls - * bug_42794.xls (from bug 42794 attachment 20429) - * In both cases, this data is found at offset 0x0C1C. - */ - byte[] data = HexRead.readFromString("" - + "5C 00 39 00 " - + "36 00 00 41 20 73 61 74 69 73 66 69 65 64 20 4D " - + "69 63 72 6F 73 6F 66 74 20 4F 66 66 69 63 65 39 " - + "20 55 73 65 72" - + "20 20 20 20 20 20 20 20 20 20 20 " - + "20 20 20 20 20 20 20 20 20"); - - RecordInputStream in = TestcaseRecordInputStream.create(data); - WriteAccessRecord rec = new WriteAccessRecord(in); - assertEquals("A satisfied Microsoft Office9 User", rec.getUsername()); - byte[] expectedEncoding = HexRead.readFromString("" - + "22 00 00 41 20 73 61 74 69 73 66 69 65 64 20 4D " - + "69 63 72 6F 73 6F 66 74 20 4F 66 66 69 63 65 39 " - + "20 55 73 65 72" - + "20 20 20 20 20 20 20 20 20 20 20 " - + HEX_SIXTYFOUR_SPACES); - - TestcaseRecordInputStream.confirmRecordEncoding(WriteAccessRecord.sid, expectedEncoding, rec.serialize()); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/TestcaseRecordInputStream.java b/src/testcases/org/apache/poi/hssf/record/TestcaseRecordInputStream.java deleted file mode 100644 index 3fc80407e..000000000 --- a/src/testcases/org/apache/poi/hssf/record/TestcaseRecordInputStream.java +++ /dev/null @@ -1,105 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record; - -import java.io.ByteArrayInputStream; -import java.io.InputStream; - -import junit.framework.Assert; -import junit.framework.AssertionFailedError; - -import org.apache.poi.util.HexDump; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.LittleEndianByteArrayInputStream; -import org.apache.poi.util.LittleEndianInput; - -/** - * A Record Input Stream derivative that makes access to byte arrays used in the - * test cases work a bit easier. - *

    Creates the stream and moves to the first record. - * - * @author Jason Height (jheight at apache.org) - */ -public final class TestcaseRecordInputStream { - - private TestcaseRecordInputStream() { - // no instances of this class - } - - /** - * Prepends a mock record identifier to the supplied data and opens a record input stream - */ - public static LittleEndianInput createLittleEndian(byte[] data) { - return new LittleEndianByteArrayInputStream(data); - - } - public static RecordInputStream create(int sid, byte[] data) { - return create(mergeDataAndSid(sid, data.length, data)); - } - /** - * First 4 bytes of data are assumed to be record identifier and length. The supplied - * data can contain multiple records (sequentially encoded in the same way) - */ - public static RecordInputStream create(byte[] data) { - InputStream is = new ByteArrayInputStream(data); - RecordInputStream result = new RecordInputStream(is); - result.nextRecord(); - return result; - } - - public static byte[] mergeDataAndSid(int sid, int length, byte[] data) { - byte[] result = new byte[data.length + 4]; - LittleEndian.putUShort(result, 0, sid); - LittleEndian.putUShort(result, 2, length); - System.arraycopy(data, 0, result, 4, data.length); - return result; - } - /** - * Confirms data sections are equal - * @param expectedData - just raw data (without sid or size short ints) - * @param actualRecordBytes this includes 4 prefix bytes (sid & size) - */ - public static void confirmRecordEncoding(int expectedSid, byte[] expectedData, byte[] actualRecordBytes) - throws AssertionFailedError { - confirmRecordEncoding(null, expectedSid, expectedData, actualRecordBytes); - } - /** - * Confirms data sections are equal - * @param msgPrefix message prefix to be displayed in case of failure - * @param expectedData - just raw data (without ushort sid, ushort size) - * @param actualRecordBytes this includes 4 prefix bytes (sid & size) - */ - public static void confirmRecordEncoding(String msgPrefix, int expectedSid, byte[] expectedData, byte[] actualRecordBytes) - throws AssertionFailedError { - int expectedDataSize = expectedData.length; - Assert.assertEquals("Size of encode data mismatch", actualRecordBytes.length - 4, expectedDataSize); - Assert.assertEquals(expectedSid, LittleEndian.getShort(actualRecordBytes, 0)); - Assert.assertEquals(expectedDataSize, LittleEndian.getShort(actualRecordBytes, 2)); - for (int i = 0; i < expectedDataSize; i++) - if (expectedData[i] != actualRecordBytes[i+4]) { - StringBuilder sb = new StringBuilder(64); - if (msgPrefix != null) { - sb.append(msgPrefix).append(": "); - } - sb.append("At offset ").append(i); - sb.append(": expected ").append(HexDump.byteToHex(expectedData[i])); - sb.append(" but found ").append(HexDump.byteToHex(actualRecordBytes[i+4])); - throw new AssertionFailedError(sb.toString()); - } - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/aggregates/AllRecordAggregateTests.java b/src/testcases/org/apache/poi/hssf/record/aggregates/AllRecordAggregateTests.java deleted file mode 100644 index 4edf3eb9c..000000000 --- a/src/testcases/org/apache/poi/hssf/record/aggregates/AllRecordAggregateTests.java +++ /dev/null @@ -1,37 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record.aggregates; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -/** - * Collects all tests for package org.apache.poi.hssf.record.aggregates. - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestCFRecordsAggregate.class, - TestColumnInfoRecordsAggregate.class, - TestFormulaRecordAggregate.class, - TestRowRecordsAggregate.class, - TestSharedValueManager.class, - TestValueRecordsAggregate.class, - TestPageSettingsBlock.class -}) -public final class AllRecordAggregateTests { -} diff --git a/src/testcases/org/apache/poi/hssf/record/aggregates/TestCFRecordsAggregate.java b/src/testcases/org/apache/poi/hssf/record/aggregates/TestCFRecordsAggregate.java deleted file mode 100644 index ee04ed01a..000000000 --- a/src/testcases/org/apache/poi/hssf/record/aggregates/TestCFRecordsAggregate.java +++ /dev/null @@ -1,170 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record.aggregates; - -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -import org.apache.poi.hssf.model.RecordStream; -import org.apache.poi.hssf.record.CFHeaderBase; -import org.apache.poi.hssf.record.CFHeaderRecord; -import org.apache.poi.hssf.record.CFRule12Record; -import org.apache.poi.hssf.record.CFRuleBase; -import org.apache.poi.hssf.record.CFRuleBase.ComparisonOperator; -import org.apache.poi.hssf.record.CFRuleRecord; -import org.apache.poi.hssf.record.Record; -import org.apache.poi.hssf.record.RecordFactory; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.util.LittleEndian; - -/** - * Tests the serialization and deserialization of the CFRecordsAggregate - * class works correctly. - */ -@SuppressWarnings("resource") -public final class TestCFRecordsAggregate extends TestCase { - public void testCFRecordsAggregate() { - HSSFWorkbook workbook = new HSSFWorkbook(); - HSSFSheet sheet = workbook.createSheet(); - - List recs = new ArrayList(); - CFHeaderBase header = new CFHeaderRecord(); - CFRuleBase rule1 = CFRuleRecord.create(sheet, "7"); - CFRuleBase rule2 = CFRuleRecord.create(sheet, ComparisonOperator.BETWEEN, "2", "5"); - CFRuleBase rule3 = CFRuleRecord.create(sheet, ComparisonOperator.GE, "100", null); - header.setNumberOfConditionalFormats(3); - CellRangeAddress[] cellRanges = { - new CellRangeAddress(0,1,0,0), - new CellRangeAddress(0,1,2,2), - }; - header.setCellRanges(cellRanges); - recs.add(header); - recs.add(rule1); - recs.add(rule2); - recs.add(rule3); - CFRecordsAggregate record = CFRecordsAggregate.createCFAggregate(new RecordStream(recs, 0)); - - // Serialize - byte [] serializedRecord = new byte[record.getRecordSize()]; - record.serialize(0, serializedRecord); - InputStream in = new ByteArrayInputStream(serializedRecord); - - //Parse - recs = RecordFactory.createRecords(in); - - // Verify - assertNotNull(recs); - assertEquals(4, recs.size()); - - header = (CFHeaderRecord)recs.get(0); - rule1 = (CFRuleRecord)recs.get(1); - assertNotNull(rule1); - rule2 = (CFRuleRecord)recs.get(2); - assertNotNull(rule2); - rule3 = (CFRuleRecord)recs.get(3); - assertNotNull(rule3); - cellRanges = header.getCellRanges(); - - assertEquals(2, cellRanges.length); - assertEquals(3, header.getNumberOfConditionalFormats()); - assertFalse(header.getNeedRecalculation()); - - record = CFRecordsAggregate.createCFAggregate(new RecordStream(recs, 0)); - - record = record.cloneCFAggregate(); - - assertNotNull(record.getHeader()); - assertEquals(3,record.getNumberOfRules()); - - header = record.getHeader(); - rule1 = record.getRule(0); - assertNotNull(rule1); - rule2 = record.getRule(1); - assertNotNull(rule2); - rule3 = record.getRule(2); - assertNotNull(rule3); - cellRanges = header.getCellRanges(); - - assertEquals(2, cellRanges.length); - assertEquals(3, header.getNumberOfConditionalFormats()); - assertFalse(header.getNeedRecalculation()); - } - - /** - * Make sure that the CF Header record is properly updated with the number of rules - */ - public void testNRules() { - HSSFWorkbook workbook = new HSSFWorkbook(); - HSSFSheet sheet = workbook.createSheet(); - CellRangeAddress[] cellRanges = { - new CellRangeAddress(0,1,0,0), - new CellRangeAddress(0,1,2,2), - }; - CFRuleRecord[] rules = { - CFRuleRecord.create(sheet, "7"), - CFRuleRecord.create(sheet, ComparisonOperator.BETWEEN, "2", "5"), - }; - CFRecordsAggregate agg = new CFRecordsAggregate(cellRanges, rules); - byte[] serializedRecord = new byte[agg.getRecordSize()]; - agg.serialize(0, serializedRecord); - - int nRules = LittleEndian.getUShort(serializedRecord, 4); - if (nRules == 0) { - throw new AssertionFailedError("Identified bug 45682 b"); - } - assertEquals(rules.length, nRules); - } - - public void testCantMixTypes() { - HSSFWorkbook workbook = new HSSFWorkbook(); - HSSFSheet sheet = workbook.createSheet(); - CellRangeAddress[] cellRanges = { - new CellRangeAddress(0,1,0,0), - new CellRangeAddress(0,1,2,2), - }; - CFRuleBase[] rules = { - CFRuleRecord.create(sheet, "7"), - CFRule12Record.create(sheet, ComparisonOperator.BETWEEN, "2", "5"), - }; - try { - new CFRecordsAggregate(cellRanges, rules); - fail("Shouldn't be able to mix between types"); - } catch (IllegalArgumentException e) { - // expected here - } - - - rules = new CFRuleBase[] { CFRuleRecord.create(sheet, "7") }; - CFRecordsAggregate agg = new CFRecordsAggregate(cellRanges, rules); - assertTrue(agg.getHeader().getNeedRecalculation()); - - try { - agg.addRule(CFRule12Record.create(sheet, "7")); - fail("Shouldn't be able to mix between types"); - } catch (IllegalArgumentException e) { - // expected here - } - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/aggregates/TestColumnInfoRecordsAggregate.java b/src/testcases/org/apache/poi/hssf/record/aggregates/TestColumnInfoRecordsAggregate.java deleted file mode 100644 index 28299b8ca..000000000 --- a/src/testcases/org/apache/poi/hssf/record/aggregates/TestColumnInfoRecordsAggregate.java +++ /dev/null @@ -1,147 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record.aggregates; - -import static org.junit.Assert.assertEquals; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.hssf.record.ColumnInfoRecord; -import org.apache.poi.hssf.record.Record; -import org.apache.poi.hssf.record.RecordBase; -import org.apache.poi.hssf.record.aggregates.RecordAggregate.RecordVisitor; -import org.junit.Test; - -import junit.framework.AssertionFailedError; - -public final class TestColumnInfoRecordsAggregate { - - @Test - public void testGetRecordSize() { - ColumnInfoRecordsAggregate agg = new ColumnInfoRecordsAggregate(); - agg.insertColumn(createColInfo(1, 3)); - agg.insertColumn(createColInfo(4, 7)); - agg.insertColumn(createColInfo(8, 8)); - agg.groupColumnRange((short) 2, (short) 5, true); - assertEquals(4, agg.getNumColumns()); - - confirmSerializedSize(agg); - - agg = new ColumnInfoRecordsAggregate(); - agg.groupColumnRange((short) 3, (short) 6, true); - confirmSerializedSize(agg); - } - - private static void confirmSerializedSize(RecordBase cirAgg) { - int estimatedSize = cirAgg.getRecordSize(); - byte[] buf = new byte[estimatedSize]; - int serializedSize = cirAgg.serialize(0, buf); - assertEquals(estimatedSize, serializedSize); - } - - private static ColumnInfoRecord createColInfo(int firstCol, int lastCol) { - ColumnInfoRecord columnInfoRecord = new ColumnInfoRecord(); - columnInfoRecord.setFirstColumn((short) firstCol); - columnInfoRecord.setLastColumn((short) lastCol); - return columnInfoRecord; - } - - private static final class CIRCollector implements RecordVisitor { - - private final List _list = new ArrayList(); - - @Override - public void visitRecord(Record r) { - _list.add(r); - } - - public static ColumnInfoRecord[] getRecords(ColumnInfoRecordsAggregate agg) { - CIRCollector circ = new CIRCollector(); - agg.visitContainedRecords(circ); - ColumnInfoRecord[] result = - circ._list.toArray(new ColumnInfoRecord[circ._list.size()]); - return result; - } - } - - @Test - public void testGroupColumns_bug45639() { - ColumnInfoRecordsAggregate agg = new ColumnInfoRecordsAggregate(); - agg.groupColumnRange( 7, 9, true); - agg.groupColumnRange( 4, 12, true); - try { - agg.groupColumnRange( 1, 15, true); - } catch (ArrayIndexOutOfBoundsException e) { - throw new AssertionFailedError("Identified bug 45639"); - } - ColumnInfoRecord[] cirs = CIRCollector.getRecords(agg); - assertEquals(5, cirs.length); - confirmCIR(cirs, 0, 1, 3, 1, false, false); - confirmCIR(cirs, 1, 4, 6, 2, false, false); - confirmCIR(cirs, 2, 7, 9, 3, false, false); - confirmCIR(cirs, 3, 10, 12, 2, false, false); - confirmCIR(cirs, 4, 13, 15, 1, false, false); - } - - /** - * Check that an inner group remains hidden - */ - @Test - public void testHiddenAfterExpanding() { - ColumnInfoRecordsAggregate agg = new ColumnInfoRecordsAggregate(); - agg.groupColumnRange(1, 15, true); - agg.groupColumnRange(4, 12, true); - - ColumnInfoRecord[] cirs; - - // collapse both inner and outer groups - agg.collapseColumn(6); - agg.collapseColumn(3); - - cirs = CIRCollector.getRecords(agg); - assertEquals(5, cirs.length); - confirmCIR(cirs, 0, 1, 3, 1, true, false); - confirmCIR(cirs, 1, 4, 12, 2, true, false); - confirmCIR(cirs, 2, 13, 13, 1, true, true); - confirmCIR(cirs, 3, 14, 15, 1, true, false); - confirmCIR(cirs, 4, 16, 16, 0, false, true); - - // just expand the inner group - agg.expandColumn(6); - - cirs = CIRCollector.getRecords(agg); - assertEquals(4, cirs.length); - if (!cirs[1].getHidden()) { - throw new AssertionFailedError("Inner group should still be hidden"); - } - confirmCIR(cirs, 0, 1, 3, 1, true, false); - confirmCIR(cirs, 1, 4, 12, 2, true, false); - confirmCIR(cirs, 2, 13, 15, 1, true, false); - confirmCIR(cirs, 3, 16, 16, 0, false, true); - } - - private static void confirmCIR(ColumnInfoRecord[] cirs, int ix, int startColIx, int endColIx, int level, boolean isHidden, boolean isCollapsed) { - ColumnInfoRecord cir = cirs[ix]; - assertEquals("startColIx", startColIx, cir.getFirstColumn()); - assertEquals("endColIx", endColIx, cir.getLastColumn()); - assertEquals("level", level, cir.getOutlineLevel()); - assertEquals("hidden", isHidden, cir.getHidden()); - assertEquals("collapsed", isCollapsed, cir.getCollapsed()); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/aggregates/TestFormulaRecordAggregate.java b/src/testcases/org/apache/poi/hssf/record/aggregates/TestFormulaRecordAggregate.java deleted file mode 100644 index 677134e9b..000000000 --- a/src/testcases/org/apache/poi/hssf/record/aggregates/TestFormulaRecordAggregate.java +++ /dev/null @@ -1,107 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record.aggregates; - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -import org.apache.poi.hssf.record.FormulaRecord; -import org.apache.poi.hssf.record.Record; -import org.apache.poi.hssf.record.RecordFormatException; -import org.apache.poi.hssf.record.StringRecord; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.apache.poi.ss.formula.ptg.ExpPtg; -import org.apache.poi.hssf.usermodel.RecordInspector.RecordCollector; -import org.apache.poi.hssf.model.HSSFFormulaParser; -import org.apache.poi.ss.formula.FormulaType; -import org.apache.poi.ss.formula.FormulaRenderer; -import org.apache.poi.ss.util.CellRangeAddress; - -/** - * - * @author avik - */ -public final class TestFormulaRecordAggregate extends TestCase { - - public void testBasic() { - FormulaRecord f = new FormulaRecord(); - f.setCachedResultTypeString(); - StringRecord s = new StringRecord(); - s.setString("abc"); - FormulaRecordAggregate fagg = new FormulaRecordAggregate(f, s, SharedValueManager.createEmpty()); - assertEquals("abc", fagg.getStringValue()); - assertFalse(fagg.isPartOfArrayFormula()); - } - - /** - * Sometimes a {@link StringRecord} appears after a {@link FormulaRecord} even though the - * formula has evaluated to a text value. This might be more likely to occur when the formula - * can evaluate to a text value.
    - * Bug 46213 attachment 22874 has such an extra {@link StringRecord} at stream offset 0x5765. - * This file seems to open in Excel (2007) with no trouble. When it is re-saved, Excel omits - * the extra record. POI should do the same. - */ - public void testExtraStringRecord_bug46213() { - FormulaRecord fr = new FormulaRecord(); - fr.setValue(2.0); - StringRecord sr = new StringRecord(); - sr.setString("NA"); - SharedValueManager svm = SharedValueManager.createEmpty(); - FormulaRecordAggregate fra; - - try { - fra = new FormulaRecordAggregate(fr, sr, svm); - } catch (RecordFormatException e) { - if ("String record was supplied but formula record flag is not set".equals(e.getMessage())) { - throw new AssertionFailedError("Identified bug 46213"); - } - throw e; - } - RecordCollector rc = new RecordCollector(); - fra.visitContainedRecords(rc); - Record[] vraRecs = rc.getRecords(); - assertEquals(1, vraRecs.length); - assertEquals(fr, vraRecs[0]); - } - - public void testArrayFormulas() { - int rownum = 4; - int colnum = 4; - - FormulaRecord fr = new FormulaRecord(); - fr.setRow(rownum); - fr.setColumn((short)colnum); - - FormulaRecordAggregate agg = new FormulaRecordAggregate(fr, null, SharedValueManager.createEmpty()); - Ptg[] ptgsForCell = {new ExpPtg(rownum, colnum)}; - agg.setParsedExpression(ptgsForCell); - - String formula = "SUM(A1:A3*B1:B3)"; - Ptg[] ptgs = HSSFFormulaParser.parse(formula, null, FormulaType.ARRAY, 0); - agg.setArrayFormula(new CellRangeAddress(rownum, rownum, colnum, colnum), ptgs); - - assertTrue(agg.isPartOfArrayFormula()); - assertEquals("E5", agg.getArrayFormulaRange().formatAsString()); - Ptg[] ptg = agg.getFormulaTokens(); - String fmlaSer = FormulaRenderer.toFormulaString(null, ptg); - assertEquals(formula, fmlaSer); - - agg.removeArrayFormula(rownum, colnum); - assertFalse(agg.isPartOfArrayFormula()); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/aggregates/TestPageSettingsBlock.java b/src/testcases/org/apache/poi/hssf/record/aggregates/TestPageSettingsBlock.java deleted file mode 100644 index 0f6caa758..000000000 --- a/src/testcases/org/apache/poi/hssf/record/aggregates/TestPageSettingsBlock.java +++ /dev/null @@ -1,458 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record.aggregates; - -import static org.junit.Assert.assertArrayEquals; - -import java.util.Arrays; - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.model.InternalSheet; -import org.apache.poi.hssf.model.RecordStream; -import org.apache.poi.hssf.record.*; -import org.apache.poi.hssf.usermodel.HSSFPrintSetup; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.hssf.usermodel.RecordInspector.RecordCollector; -import org.apache.poi.util.HexRead; - -/** - * Tess for {@link PageSettingsBlock} - * - * @author Dmitriy Kumshayev - */ -public final class TestPageSettingsBlock extends TestCase { - - public void testPrintSetup_bug46548() { - - // PageSettingBlock in this file contains PLS (sid=x004D) record - // followed by ContinueRecord (sid=x003C) - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("ex46548-23133.xls"); - HSSFSheet sheet = wb.getSheetAt(0); - HSSFPrintSetup ps = sheet.getPrintSetup(); - - try { - ps.getCopies(); - } catch (NullPointerException e) { - e.printStackTrace(); - throw new AssertionFailedError("Identified bug 46548: PageSettingBlock missing PrintSetupRecord record"); - } - } - - /** - * Bug 46840 occurred because POI failed to recognise HEADERFOOTER as part of the - * {@link PageSettingsBlock}. - */ - public void testHeaderFooter_bug46840() { - - int rowIx = 5; - int colIx = 6; - NumberRecord nr = new NumberRecord(); - nr.setRow(rowIx); - nr.setColumn((short) colIx); - nr.setValue(3.0); - - Record[] recs = { - BOFRecord.createSheetBOF(), - new HeaderRecord("&LSales Figures"), - new FooterRecord("&LJanuary"), - new HeaderFooterRecord(HexRead.readFromString("9C 08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 C4 60 00 00 00 00 00 00 00 00")), - new DimensionsRecord(), - new WindowTwoRecord(), - new UserSViewBegin(HexRead.readFromString("ED 77 3B 86 BC 3F 37 4C A9 58 60 23 43 68 54 4B 01 00 00 00 64 00 00 00 40 00 00 00 02 00 00 00 3D 80 04 00 00 00 00 00 00 00 0C 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 F0 3F FF FF 01 00")), - new HeaderRecord("&LSales Figures"), - new FooterRecord("&LJanuary"), - new HeaderFooterRecord(HexRead.readFromString("9C 08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 C4 60 00 00 00 00 00 00 00 00")), - new UserSViewEnd(HexRead.readFromString("01, 00")), - - EOFRecord.instance, - }; - RecordStream rs = new RecordStream(Arrays.asList(recs), 0); - InternalSheet sheet; - try { - sheet = InternalSheet.createSheet(rs); - } catch (RuntimeException e) { - if (e.getMessage().equals("two Page Settings Blocks found in the same sheet")) { - throw new AssertionFailedError("Identified bug 46480"); - } - throw e; - } - - RecordCollector rv = new RecordCollector(); - sheet.visitContainedRecords(rv, rowIx); - Record[] outRecs = rv.getRecords(); - assertEquals(13, outRecs.length); - } - - /** - * Bug 46953 occurred because POI didn't handle late PSB records properly. - */ - public void testLateHeaderFooter_bug46953() { - - int rowIx = 5; - int colIx = 6; - NumberRecord nr = new NumberRecord(); - nr.setRow(rowIx); - nr.setColumn((short) colIx); - nr.setValue(3.0); - - Record[] recs = { - BOFRecord.createSheetBOF(), - new HeaderRecord("&LSales Figures"), - new FooterRecord("&LJanuary"), - new DimensionsRecord(), - new WindowTwoRecord(), - new HeaderFooterRecord(HexRead.readFromString("9C 08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 C4 60 00 00 00 00 00 00 00 00")), - EOFRecord.instance, - }; - RecordStream rs = new RecordStream(Arrays.asList(recs), 0); - InternalSheet sheet = InternalSheet.createSheet(rs); - - RecordCollector rv = new RecordCollector(); - sheet.visitContainedRecords(rv, 0); - Record[] outRecs = rv.getRecords(); - if (outRecs[4] == EOFRecord.instance) { - throw new AssertionFailedError("Identified bug 46953 - EOF incorrectly appended to PSB"); - } - assertEquals(recs.length+1, outRecs.length); // +1 for index record - - assertEquals(BOFRecord.class, outRecs[0].getClass()); - assertEquals(IndexRecord.class, outRecs[1].getClass()); - assertEquals(HeaderRecord.class, outRecs[2].getClass()); - assertEquals(FooterRecord.class, outRecs[3].getClass()); - assertEquals(HeaderFooterRecord.class, outRecs[4].getClass()); - assertEquals(DimensionsRecord.class, outRecs[5].getClass()); - assertEquals(WindowTwoRecord.class, outRecs[6].getClass()); - assertEquals(EOFRecord.instance, outRecs[7]); - } - /** - * Bug 47199 was due to the margin records being located well after the initial PSB records. - * The example file supplied (attachment 23710) had three non-PSB record types - * between the PRINTSETUP record and first MARGIN record: - *

      - *
    • PRINTSETUP(0x00A1)
    • - *
    • DEFAULTCOLWIDTH(0x0055)
    • - *
    • COLINFO(0x007D)
    • - *
    • DIMENSIONS(0x0200)
    • - *
    • BottomMargin(0x0029)
    • - *
    - */ - public void testLateMargins_bug47199() { - - Record[] recs = { - BOFRecord.createSheetBOF(), - new HeaderRecord("&LSales Figures"), - new FooterRecord("&LJanuary"), - new DimensionsRecord(), - createBottomMargin(0.787F), - new WindowTwoRecord(), - EOFRecord.instance, - }; - RecordStream rs = new RecordStream(Arrays.asList(recs), 0); - - InternalSheet sheet; - try { - sheet = InternalSheet.createSheet(rs); - } catch (RuntimeException e) { - if (e.getMessage().equals("two Page Settings Blocks found in the same sheet")) { - throw new AssertionFailedError("Identified bug 47199a - failed to process late margings records"); - } - throw e; - } - - RecordCollector rv = new RecordCollector(); - sheet.visitContainedRecords(rv, 0); - Record[] outRecs = rv.getRecords(); - assertEquals(recs.length+1, outRecs.length); // +1 for index record - - assertEquals(BOFRecord.class, outRecs[0].getClass()); - assertEquals(IndexRecord.class, outRecs[1].getClass()); - assertEquals(HeaderRecord.class, outRecs[2].getClass()); - assertEquals(FooterRecord.class, outRecs[3].getClass()); - assertEquals(DimensionsRecord.class, outRecs[5].getClass()); - assertEquals(WindowTwoRecord.class, outRecs[6].getClass()); - assertEquals(EOFRecord.instance, outRecs[7]); - } - - private Record createBottomMargin(float value) { - BottomMarginRecord result = new BottomMarginRecord(); - result.setMargin(value); - return result; - } - - /** - * The PageSettingsBlock should not allow multiple copies of the same record. This extra assertion - * was added while fixing bug 47199. All existing POI test samples comply with this requirement. - */ - public void testDuplicatePSBRecord_bug47199() { - // Hypothetical setup of PSB records which should cause POI to crash - Record[] recs = { - new HeaderRecord("&LSales Figures"), - new HeaderRecord("&LInventory"), - }; - RecordStream rs = new RecordStream(Arrays.asList(recs), 0); - - try { - new PageSettingsBlock(rs); - throw new AssertionFailedError("Identified bug 47199b - duplicate PSB records should not be allowed"); - } catch (org.apache.poi.util.RecordFormatException e) { - if (!e.getMessage().equals("Duplicate PageSettingsBlock record (sid=0x14)")) { - throw new AssertionFailedError("Expected RecordFormatException due to duplicate PSB record"); - } - } - } - - private static UnknownRecord ur(int sid, String hexData) { - return new UnknownRecord(sid, HexRead.readFromString(hexData)); - } - - /** - * Excel tolerates missing header / footer records, but adds them (empty) in when re-saving. - * This is not critical functionality but it has been decided to keep POI consistent with - * Excel in this regard. - */ - public void testMissingHeaderFooter() { - // initialise PSB with some records, but not the header / footer - Record[] recs = { - new HCenterRecord(), - new VCenterRecord(), - }; - RecordStream rs = new RecordStream(Arrays.asList(recs), 0); - PageSettingsBlock psb = new PageSettingsBlock(rs); - - // serialize the PSB to see what records come out - RecordCollector rc = new RecordCollector(); - psb.visitContainedRecords(rc); - Record[] outRecs = rc.getRecords(); - - if (outRecs.length == 2) { - throw new AssertionFailedError("PageSettingsBlock didn't add missing header/footer records"); - } - assertEquals(4, outRecs.length); - assertEquals(HeaderRecord.class, outRecs[0].getClass()); - assertEquals(FooterRecord.class, outRecs[1].getClass()); - assertEquals(HCenterRecord.class, outRecs[2].getClass()); - assertEquals(VCenterRecord.class, outRecs[3].getClass()); - - // make sure the added header / footer records are empty - HeaderRecord hr = (HeaderRecord) outRecs[0]; - assertEquals("", hr.getText()); - FooterRecord fr = (FooterRecord) outRecs[1]; - assertEquals("", fr.getText()); - } - - /** - * Apparently it's OK to have more than one PLS record. - * Attachment 23866 from bug 47415 had a PageSettingsBlock with two PLS records. This file - * seems to open OK in Excel(2007) but both PLS records are removed (perhaps because the - * specified printers were not available on the testing machine). Since the example file does - * not upset Excel, POI will preserve multiple PLS records.

    - * - * As of June 2009, PLS is still uninterpreted by POI - */ - public void testDuplicatePLS_bug47415() { - Record plsA = ur(UnknownRecord.PLS_004D, "BA AD F0 0D"); - Record plsB = ur(UnknownRecord.PLS_004D, "DE AD BE EF"); - Record contB1 = new ContinueRecord(HexRead.readFromString("FE ED")); - Record contB2 = new ContinueRecord(HexRead.readFromString("FA CE")); - Record[] recs = { - new HeaderRecord("&LSales Figures"), - new FooterRecord("&LInventory"), - new HCenterRecord(), - new VCenterRecord(), - plsA, - plsB, contB1, contB2, // make sure continuing PLS is still OK - }; - RecordStream rs = new RecordStream(Arrays.asList(recs), 0); - PageSettingsBlock psb; - try { - psb = new PageSettingsBlock(rs); - } catch (org.apache.poi.util.RecordFormatException e) { - if ("Duplicate PageSettingsBlock record (sid=0x4d)".equals(e.getMessage())) { - throw new AssertionFailedError("Identified bug 47415"); - } - throw e; - } - - // serialize the PSB to see what records come out - RecordCollector rc = new RecordCollector(); - psb.visitContainedRecords(rc); - Record[] outRecs = rc.getRecords(); - - // records were assembled in standard order, so this simple check is OK - assertArrayEquals(recs, outRecs); - } - - public void testDuplicateHeaderFooter_bug48026() { - - Record[] recs = { - BOFRecord.createSheetBOF(), - new IndexRecord(), - - //PageSettingsBlock - new HeaderRecord("&LDecember"), - new FooterRecord("&LJanuary"), - new DimensionsRecord(), - - new WindowTwoRecord(), - - //CustomViewSettingsRecordAggregate - new UserSViewBegin(HexRead.readFromString("53 CE BD CC DE 38 44 45 97 C1 5C 89 F9 37 32 1B 01 00 00 00 64 00 00 00 40 00 00 00 03 00 00 00 7D 00 00 20 00 00 34 00 00 00 18 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 FF FF FF FF")), - new SelectionRecord(0, 0), - new UserSViewEnd(HexRead.readFromString("01 00")), - - // two HeaderFooterRecord records, the first one has zero GUID (16 bytes at offset 12) and belongs to the PSB, - // the other is matched with a CustomViewSettingsRecordAggregate having UserSViewBegin with the same GUID - new HeaderFooterRecord(HexRead.readFromString("9C 08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 34 33 00 00 00 00 00 00 00 00")), - new HeaderFooterRecord(HexRead.readFromString("9C 08 00 00 00 00 00 00 00 00 00 00 53 CE BD CC DE 38 44 45 97 C1 5C 89 F9 37 32 1B 34 33 00 00 00 00 00 00 00 00")), - - EOFRecord.instance, - }; - RecordStream rs = new RecordStream(Arrays.asList(recs), 0); - InternalSheet sheet; - try { - sheet = InternalSheet.createSheet(rs); - } catch (RuntimeException e) { - if (e.getMessage().equals("Duplicate PageSettingsBlock record (sid=0x89c)")) { - throw new AssertionFailedError("Identified bug 48026"); - } - throw e; - } - - RecordCollector rv = new RecordCollector(); - sheet.visitContainedRecords(rv, 0); - Record[] outRecs = rv.getRecords(); - - assertEquals(recs.length, outRecs.length); - //expected order of records: - Record[] expectedRecs = { - recs[0], //BOFRecord - recs[1], //IndexRecord - - //PageSettingsBlock - recs[2], //HeaderRecord - recs[3], //FooterRecord - recs[9], //HeaderFooterRecord - recs[4], // DimensionsRecord - recs[5], // WindowTwoRecord - - //CustomViewSettingsRecordAggregate - recs[6], // UserSViewBegin - recs[7], // SelectionRecord - recs[10], // HeaderFooterRecord - recs[8], // UserSViewEnd - - recs[11], //EOFRecord - }; - for(int i=0; i < expectedRecs.length; i++){ - assertEquals("Record mismatch at index " + i, expectedRecs[i].getClass(), outRecs[i].getClass()); - } - HeaderFooterRecord hd1 = (HeaderFooterRecord)expectedRecs[4]; - //GUID is zero - assertArrayEquals(new byte[16], hd1.getGuid()); - assertTrue(hd1.isCurrentSheet()); - - UserSViewBegin svb = (UserSViewBegin)expectedRecs[7]; - HeaderFooterRecord hd2 = (HeaderFooterRecord)expectedRecs[9]; - assertFalse(hd2.isCurrentSheet()); - //GUIDs of HeaderFooterRecord and UserSViewBegin must be the same - assertArrayEquals(svb.getGuid(), hd2.getGuid()); - } - - public void testDuplicateHeaderFooterInside_bug48026() { - - Record[] recs = { - BOFRecord.createSheetBOF(), - new IndexRecord(), - - //PageSettingsBlock - new HeaderRecord("&LDecember"), - new FooterRecord("&LJanuary"), - new DimensionsRecord(), - - new WindowTwoRecord(), - - //CustomViewSettingsRecordAggregate - new UserSViewBegin(HexRead.readFromString("53 CE BD CC DE 38 44 45 97 C1 5C 89 F9 37 32 1B 01 00 00 00 64 00 00 00 40 00 00 00 03 00 00 00 7D 00 00 20 00 00 34 00 00 00 18 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 FF FF FF FF")), - new SelectionRecord(0, 0), - - // two HeaderFooterRecord records, the first one has zero GUID (16 bytes at offset 12) and belongs to the PSB, - // the other is matched with a CustomViewSettingsRecordAggregate having UserSViewBegin with the same GUID - new HeaderFooterRecord(HexRead.readFromString("9C 08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 34 33 00 00 00 00 00 00 00 00")), - new HeaderFooterRecord(HexRead.readFromString("9C 08 00 00 00 00 00 00 00 00 00 00 53 CE BD CC DE 38 44 45 97 C1 5C 89 F9 37 32 1B 34 33 00 00 00 00 00 00 00 00")), - - new UserSViewEnd(HexRead.readFromString("01 00")), - - EOFRecord.instance, - }; - RecordStream rs = new RecordStream(Arrays.asList(recs), 0); - InternalSheet sheet; - try { - sheet = InternalSheet.createSheet(rs); - } catch (RuntimeException e) { - if (e.getMessage().equals("Duplicate PageSettingsBlock record (sid=0x89c)")) { - throw new AssertionFailedError("Identified bug 48026"); - } - throw e; - } - - RecordCollector rv = new RecordCollector(); - sheet.visitContainedRecords(rv, 0); - Record[] outRecs = rv.getRecords(); - - assertEquals(recs.length+1, outRecs.length); - //expected order of records: - Record[] expectedRecs = { - recs[0], //BOFRecord - recs[1], //IndexRecord - - //PageSettingsBlock - recs[2], //HeaderRecord - recs[3], //FooterRecord - recs[4], // DimensionsRecord - recs[5], // WindowTwoRecord - - //CustomViewSettingsRecordAggregate - recs[6], // UserSViewBegin - recs[7], // SelectionRecord - recs[2], //HeaderRecord - recs[3], //FooterRecord - recs[8], // HeaderFooterRecord -// recs[9], //HeaderFooterRecord - recs[10], // UserSViewEnd - - recs[11], //EOFRecord - }; - for(int i=0; i < expectedRecs.length; i++){ - assertEquals("Record mismatch at index " + i, expectedRecs[i].getClass(), outRecs[i].getClass()); - } - HeaderFooterRecord hd1 = (HeaderFooterRecord)expectedRecs[10]; - //GUID is zero - assertArrayEquals(new byte[16], hd1.getGuid()); - assertTrue(hd1.isCurrentSheet()); - - UserSViewBegin svb = (UserSViewBegin)expectedRecs[6]; - HeaderFooterRecord hd2 = (HeaderFooterRecord)recs[9]; - assertFalse(hd2.isCurrentSheet()); - //GUIDs of HeaderFooterRecord and UserSViewBegin must be the same - assertArrayEquals(svb.getGuid(), hd2.getGuid()); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/aggregates/TestRowRecordsAggregate.java b/src/testcases/org/apache/poi/hssf/record/aggregates/TestRowRecordsAggregate.java deleted file mode 100644 index 1d8b508c7..000000000 --- a/src/testcases/org/apache/poi/hssf/record/aggregates/TestRowRecordsAggregate.java +++ /dev/null @@ -1,160 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record.aggregates; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.util.Arrays; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.model.RecordStream; -import org.apache.poi.hssf.record.ArrayRecord; -import org.apache.poi.hssf.record.ContinueRecord; -import org.apache.poi.hssf.record.FormulaRecord; -import org.apache.poi.hssf.record.NumberRecord; -import org.apache.poi.hssf.record.Record; -import org.apache.poi.hssf.record.RowRecord; -import org.apache.poi.hssf.record.SharedFormulaRecord; -import org.apache.poi.hssf.record.SharedValueRecordBase; -import org.apache.poi.hssf.record.TableRecord; -import org.apache.poi.hssf.record.UnknownRecord; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.hssf.usermodel.RecordInspector; -import org.apache.poi.hssf.usermodel.RecordInspector.RecordCollector; -import org.apache.poi.hssf.util.CellRangeAddress8Bit; -import org.apache.poi.util.LocaleUtil; -import org.junit.Test; - -/** - * Tests for {@link RowRecordsAggregate} - */ -public final class TestRowRecordsAggregate { - - @Test - public void testRowGet() { - RowRecordsAggregate rra = new RowRecordsAggregate(); - RowRecord rr = new RowRecord(4); - rra.insertRow(rr); - rra.insertRow(new RowRecord(1)); - - RowRecord rr1 = rra.getRow(4); - - assertNotNull(rr1); - assertEquals("Row number is 1", 4, rr1.getRowNumber()); - assertTrue("Row record retrieved is identical ", rr1 == rr); - } - - /** - * Prior to Aug 2008, POI would re-serialize spreadsheets with {@link ArrayRecord}s or - * {@link TableRecord}s with those records out of order. Similar to - * {@link SharedFormulaRecord}s, these records should appear immediately after the first - * {@link FormulaRecord}s that they apply to (and only once).
    - */ - @Test - public void testArraysAndTables() throws Exception { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("testArraysAndTables.xls"); - Record[] sheetRecs = RecordInspector.getRecords(wb.getSheetAt(0), 0); - - int countArrayFormulas = verifySharedValues(sheetRecs, ArrayRecord.class); - assertEquals(5, countArrayFormulas); - int countTableFormulas = verifySharedValues(sheetRecs, TableRecord.class); - assertEquals(3, countTableFormulas); - - // Note - SharedFormulaRecords are currently not re-serialized by POI (each is extracted - // into many non-shared formulas), but if they ever were, the same rules would apply. - int countSharedFormulas = verifySharedValues(sheetRecs, SharedFormulaRecord.class); - assertEquals(0, countSharedFormulas); - - -// if (false) { // set true to observe re-serialized file -// File f = new File(System.getProperty("java.io.tmpdir") + "/testArraysAndTables-out.xls"); -// try { -// OutputStream os = new FileOutputStream(f); -// wb.write(os); -// os.close(); -// } catch (IOException e) { -// throw new RuntimeException(e); -// } -// System.out.println("Output file to " + f.getAbsolutePath()); -// } - - wb.close(); - } - - private static int verifySharedValues(Record[] recs, Class shfClass) { - - int result =0; - for(int i=0; i - * The functionality change being tested here is actually not critical to the overall fix - * for bug 46280, since the fix involved making sure the that offending PivotTable - * records do not get into {@link RowRecordsAggregate}.
    - * This fix in {@link RowRecordsAggregate} was implemented anyway since any {@link - * UnknownRecord} has the potential of being 'continued'. - */ - @Test - public void testUnknownContinue_bug46280() { - Record[] inRecs = { - new RowRecord(0), - new NumberRecord(), - new UnknownRecord(0x5555, "dummydata".getBytes(LocaleUtil.CHARSET_1252)), - new ContinueRecord("moredummydata".getBytes(LocaleUtil.CHARSET_1252)), - }; - RecordStream rs = new RecordStream(Arrays.asList(inRecs), 0); - RowRecordsAggregate rra; - try { - rra = new RowRecordsAggregate(rs, SharedValueManager.createEmpty()); - } catch (RuntimeException e) { - if (e.getMessage().startsWith("Unexpected record type")) { - fail("Identified bug 46280a"); - } - throw e; - } - RecordCollector rv = new RecordCollector(); - rra.visitContainedRecords(rv); - Record[] outRecs = rv.getRecords(); - assertEquals(5, outRecs.length); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/aggregates/TestSharedValueManager.java b/src/testcases/org/apache/poi/hssf/record/aggregates/TestSharedValueManager.java deleted file mode 100644 index 66f8e89e8..000000000 --- a/src/testcases/org/apache/poi/hssf/record/aggregates/TestSharedValueManager.java +++ /dev/null @@ -1,201 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record.aggregates; - -import java.util.Collection; -import java.util.HashMap; - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -import org.apache.poi.POITestCase; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.record.Record; -import org.apache.poi.hssf.record.SharedFormulaRecord; -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.hssf.usermodel.RecordInspector; - -/** - * Tests for {@link SharedValueManager} - * - * @author Josh Micich - */ -public final class TestSharedValueManager extends TestCase { - - /** - * This Excel workbook contains two sheets that each have a pair of overlapping shared formula - * ranges. The first sheet has one row and one column shared formula ranges which intersect. - * The second sheet has two column shared formula ranges - one contained within the other. - * These shared formula ranges were created by fill-dragging a single cell formula across the - * desired region. The larger shared formula ranges were placed first.
    - * - * There are probably many ways to produce similar effects, but it should be noted that Excel - * is quite temperamental in this regard. Slight variations in technique can cause the shared - * formulas to spill out into plain formula records (which would make these tests pointless). - * - */ - private static final String SAMPLE_FILE_NAME = "overlapSharedFormula.xls"; - /** - * Some of these bugs are intermittent, and the test author couldn't think of a way to write - * test code to hit them bug deterministically. The reason for the unpredictability is that - * the bugs depended on the {@link SharedFormulaRecord}s being searched in a particular order. - * At the time of writing of the test, the order was being determined by the call to {@link - * Collection#toArray(Object[])} on {@link HashMap#values()} where the items in the map were - * using default {@link Object#hashCode()}
    - */ - private static final int MAX_ATTEMPTS=5; - - /** - * This bug happened when there were two or more shared formula ranges that overlapped. POI - * would sometimes associate formulas in the overlapping region with the wrong shared formula - */ - public void testPartiallyOverlappingRanges() { - Record[] records; - - int attempt=1; - do { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook(SAMPLE_FILE_NAME); - - HSSFSheet sheet = wb.getSheetAt(0); - RecordInspector.getRecords(sheet, 0); - assertEquals("1+1", sheet.getRow(2).getCell(0).getCellFormula()); - if ("1+1".equals(sheet.getRow(3).getCell(0).getCellFormula())) { - throw new AssertionFailedError("Identified bug - wrong shared formula record chosen" - + " (attempt " + attempt + ")"); - } - assertEquals("2+2", sheet.getRow(3).getCell(0).getCellFormula()); - records = RecordInspector.getRecords(sheet, 0); - } while (attempt++ < MAX_ATTEMPTS); - - int count=0; - for (Record record : records) { - if (record instanceof SharedFormulaRecord) { - count++; - } - } - assertEquals(2, count); - } - - /** - * This bug occurs for similar reasons to the bug in {@link #testPartiallyOverlappingRanges()} - * but the symptoms are much uglier - serialization fails with {@link NullPointerException}.
    - */ - public void testCompletelyOverlappedRanges() { - Record[] records; - - int attempt=1; - do { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook(SAMPLE_FILE_NAME); - - HSSFSheet sheet = wb.getSheetAt(1); - try { - records = RecordInspector.getRecords(sheet, 0); - } catch (NullPointerException e) { - throw new AssertionFailedError("Identified bug " + - "- cannot reserialize completely overlapped shared formula" - + " (attempt " + attempt + ")"); - } - } while (attempt++ < MAX_ATTEMPTS); - - int count=0; - for (Record record : records) { - if (record instanceof SharedFormulaRecord) { - count++; - } - } - assertEquals(2, count); - } - - /** - * Tests fix for a bug in the way shared formula cells are associated with shared formula - * records. Prior to this fix, POI would attempt to use the upper left corner of the - * shared formula range as the locator cell. The correct cell to use is the 'first cell' - * in the shared formula group which is not always the top left cell. This is possible - * because shared formula groups may be sparse and may overlap.
    - * - * Two existing sample files (15228.xls and ex45046-21984.xls) had similar issues. - * These were not explored fully, but seem to be fixed now. - */ - public void testRecalculateFormulas47747() { - - /* - * ex47747-sharedFormula.xls is a heavily cut-down version of the spreadsheet from - * the attachment (id=24176) in Bugzilla 47747. This was done to make the sample - * file smaller, which hopefully allows the special data encoding condition to be - * seen more easily. Care must be taken when modifying this file since the - * special conditions are easily destroyed (which would make this test useless). - * It seems that removing the worksheet protection has made this more so - if the - * current file is re-saved in Excel(2007) the bug condition disappears. - * - * - * Using BiffViewer, one can see that there are two shared formula groups representing - * the essentially same formula over ~20 cells. The shared group ranges overlap and - * are A12:Q20 and A20:Q27. The locator cell ('first cell') for the second group is - * Q20 which is not the top left cell of the enclosing range. It is this specific - * condition which caused the bug to occur - */ - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("ex47747-sharedFormula.xls"); - - // pick out a cell from within the second shared formula group - HSSFCell cell = wb.getSheetAt(0).getRow(23).getCell(0); - String formulaText; - try { - formulaText = cell.getCellFormula(); - // succeeds if the formula record has been associated - // with the second shared formula group - } catch (RuntimeException e) { - // bug occurs if the formula record has been associated - // with the first shared formula group - if ("Shared Formula Conversion: Coding Error".equals(e.getMessage())) { - throw new AssertionFailedError("Identified bug 47747"); - } - throw e; - } - assertEquals("$AF24*A$7", formulaText); - } - - /** - * Convenience test method for digging the {@link SharedValueManager} out of a - * {@link RowRecordsAggregate}. - */ - public static SharedValueManager extractFromRRA(RowRecordsAggregate rra) { - return POITestCase.getFieldValue(RowRecordsAggregate.class, rra, SharedValueManager.class, "_sharedValueManager"); - } - - public void testBug52527() { - HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("52527.xls"); - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - - assertEquals("IF(H3,LINEST(N9:N14,K9:M14,FALSE),LINEST(N8:N14,K8:M14,FALSE))", - wb1.getSheetAt(0).getRow(4).getCell(11).getCellFormula()); - assertEquals("IF(H3,LINEST(N9:N14,K9:M14,FALSE),LINEST(N8:N14,K8:M14,FALSE))", - wb2.getSheetAt(0).getRow(4).getCell(11).getCellFormula()); - - assertEquals("1/SQRT(J9)", - wb1.getSheetAt(0).getRow(8).getCell(10).getCellFormula()); - assertEquals("1/SQRT(J9)", - wb2.getSheetAt(0).getRow(8).getCell(10).getCellFormula()); - - assertEquals("1/SQRT(J26)", - wb1.getSheetAt(0).getRow(25).getCell(10).getCellFormula()); - assertEquals("1/SQRT(J26)", - wb2.getSheetAt(0).getRow(25).getCell(10).getCellFormula()); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/aggregates/TestValueRecordsAggregate.java b/src/testcases/org/apache/poi/hssf/record/aggregates/TestValueRecordsAggregate.java deleted file mode 100644 index f31c49d44..000000000 --- a/src/testcases/org/apache/poi/hssf/record/aggregates/TestValueRecordsAggregate.java +++ /dev/null @@ -1,422 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record.aggregates; - -import static org.junit.Assert.*; - -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.zip.CRC32; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.model.RecordStream; -import org.apache.poi.hssf.model.RowBlocksReader; -import org.apache.poi.hssf.record.BlankRecord; -import org.apache.poi.hssf.record.CellValueRecordInterface; -import org.apache.poi.hssf.record.FormulaRecord; -import org.apache.poi.hssf.record.MulBlankRecord; -import org.apache.poi.hssf.record.Record; -import org.apache.poi.hssf.record.SharedFormulaRecord; -import org.apache.poi.hssf.record.WindowTwoRecord; -import org.apache.poi.hssf.record.aggregates.RecordAggregate.RecordVisitor; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.util.HexRead; -import org.junit.Test; - -import junit.framework.AssertionFailedError; - -/** - * Tests for {@link ValueRecordsAggregate} - */ -public final class TestValueRecordsAggregate { - private static final String ABNORMAL_SHARED_FORMULA_FLAG_TEST_FILE = "AbnormalSharedFormulaFlag.xls"; - private final ValueRecordsAggregate valueRecord = new ValueRecordsAggregate(); - - private List getValueRecords() { - List list = new ArrayList(); - for ( CellValueRecordInterface rec : valueRecord ) { - list.add(rec); - } - return Collections.unmodifiableList(list); - } - - /** - * Make sure the shared formula DOESNT makes it to the FormulaRecordAggregate when being parsed - * as part of the value records - */ - @Test - public void testSharedFormula() { - List records = new ArrayList(); - records.add(new FormulaRecord()); - records.add(new SharedFormulaRecord()); - records.add(new WindowTwoRecord()); - - constructValueRecord(records); - List cvrs = getValueRecords(); - //Ensure that the SharedFormulaRecord has been converted - assertEquals(1, cvrs.size()); - - CellValueRecordInterface record = cvrs.get(0); - assertNotNull( "Row contains a value", record ); - assertTrue( "First record is a FormulaRecordsAggregate", ( record instanceof FormulaRecordAggregate ) ); - } - - private void constructValueRecord(List records) { - RowBlocksReader rbr = new RowBlocksReader(new RecordStream(records, 0)); - SharedValueManager sfrh = rbr.getSharedFormulaManager(); - RecordStream rs = rbr.getPlainRecordStream(); - while(rs.hasNext()) { - Record rec = rs.getNext(); - valueRecord.construct((CellValueRecordInterface)rec, rs, sfrh); - } - } - - private static List testData() { - List records = new ArrayList(); - FormulaRecord formulaRecord = new FormulaRecord(); - BlankRecord blankRecord = new BlankRecord(); - formulaRecord.setRow(1); - formulaRecord.setColumn((short) 1); - blankRecord.setRow(2); - blankRecord.setColumn((short) 2); - records.add(formulaRecord); - records.add(blankRecord); - records.add(new WindowTwoRecord()); - return records; - } - - @Test - public void testInsertCell() { - assertEquals(0, getValueRecords().size()); - - BlankRecord blankRecord = newBlankRecord(); - valueRecord.insertCell( blankRecord ); - assertEquals(1, getValueRecords().size()); - } - - @Test - public void testRemoveCell() { - BlankRecord blankRecord1 = newBlankRecord(); - valueRecord.insertCell( blankRecord1 ); - BlankRecord blankRecord2 = newBlankRecord(); - valueRecord.removeCell( blankRecord2 ); - assertEquals(0, getValueRecords().size()); - - // removing an already empty cell just falls through - valueRecord.removeCell( blankRecord2 ); - } - - @Test - public void testGetPhysicalNumberOfCells() { - assertEquals(0, valueRecord.getPhysicalNumberOfCells()); - BlankRecord blankRecord1 = newBlankRecord(); - valueRecord.insertCell( blankRecord1 ); - assertEquals(1, valueRecord.getPhysicalNumberOfCells()); - valueRecord.removeCell( blankRecord1 ); - assertEquals(0, valueRecord.getPhysicalNumberOfCells()); - } - - @Test - public void testGetFirstCellNum() { - assertEquals( -1, valueRecord.getFirstCellNum() ); - valueRecord.insertCell( newBlankRecord( 2, 2 ) ); - assertEquals( 2, valueRecord.getFirstCellNum() ); - valueRecord.insertCell( newBlankRecord( 3, 3 ) ); - assertEquals( 2, valueRecord.getFirstCellNum() ); - - // Note: Removal doesn't currently reset the first column. It probably should but it doesn't. - valueRecord.removeCell( newBlankRecord( 2, 2 ) ); - assertEquals( 2, valueRecord.getFirstCellNum() ); - } - - @Test - public void testGetLastCellNum() { - assertEquals( -1, valueRecord.getLastCellNum() ); - valueRecord.insertCell( newBlankRecord( 2, 2 ) ); - assertEquals( 2, valueRecord.getLastCellNum() ); - valueRecord.insertCell( newBlankRecord( 3, 3 ) ); - assertEquals( 3, valueRecord.getLastCellNum() ); - - // Note: Removal doesn't currently reset the last column. It probably should but it doesn't. - valueRecord.removeCell( newBlankRecord( 3, 3 ) ); - assertEquals( 3, valueRecord.getLastCellNum() ); - - } - - - private static final class SerializerVisitor implements RecordVisitor { - private final byte[] _buf; - private int _writeIndex; - public SerializerVisitor(byte[] buf) { - _buf = buf; - _writeIndex = 0; - - } - @Override - public void visitRecord(Record r) { - r.serialize(_writeIndex, _buf); - _writeIndex += r.getRecordSize(); - } - public int getWriteIndex() { - return _writeIndex; - } - } - - @Test - public void testSerialize() { - byte[] expectedArray = HexRead.readFromString("" - + "06 00 16 00 " // Formula - + "01 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 " - + "01 02 06 00 " // Blank - + "02 00 02 00 00 00"); - byte[] actualArray = new byte[expectedArray.length]; - List records = testData(); - constructValueRecord(records); - - SerializerVisitor sv = new SerializerVisitor(actualArray); - valueRecord.visitCellsForRow(1, sv); - valueRecord.visitCellsForRow(2, sv); - assertEquals(actualArray.length, sv.getWriteIndex()); - assertArrayEquals(expectedArray, actualArray); - } - - private static BlankRecord newBlankRecord() { - return newBlankRecord( 2, 2 ); - } - - private static BlankRecord newBlankRecord(int col, int row) { - BlankRecord blankRecord = new BlankRecord(); - blankRecord.setRow( row ); - blankRecord.setColumn( (short) col ); - return blankRecord; - } - - /** - * Sometimes the 'shared formula' flag (FormulaRecord.isSharedFormula()) is set when - * there is no corresponding SharedFormulaRecord available. SharedFormulaRecord definitions do - * not span multiple sheets. They are are only defined within a sheet, and thus they do not - * have a sheet index field (only row and column range fields).
    - * So it is important that the code which locates the SharedFormulaRecord for each - * FormulaRecord does not allow matches across sheets.
    - * - * Prior to bugzilla 44449 (Feb 2008), POI ValueRecordsAggregate.construct(int, List) - * allowed SharedFormulaRecords to be erroneously used across sheets. That incorrect - * behaviour is shown by this test.

    - * - * Notes on how to produce the test spreadsheet:

    - * The setup for this test (AbnormalSharedFormulaFlag.xls) is rather fragile, insomuchas - * re-saving the file (either with Excel or POI) clears the flag.
    - *
      - *
    1. A new spreadsheet was created in Excel (File | New | Blank Workbook).
    2. - *
    3. Sheet3 was deleted.
    4. - *
    5. Sheet2!A1 formula was set to '="second formula"', and fill-dragged through A1:A8.
    6. - *
    7. Sheet1!A1 formula was set to '="first formula"', and also fill-dragged through A1:A8.
    8. - *
    9. Four rows on Sheet1 "5" through "8" were deleted ('delete rows' alt-E D, not 'clear' Del).
    10. - *
    11. The spreadsheet was saved as AbnormalSharedFormulaFlag.xls.
    12. - *
    - * Prior to the row delete action the spreadsheet has two SharedFormulaRecords. One - * for each sheet. To expose the bug, the shared formulas have been made to overlap.
    - * The row delete action (as described here) seems to to delete the - * SharedFormulaRecord from Sheet1 (but not clear the 'shared formula' flags.
    - * There are other variations on this theme to create the same effect. - * - */ - @Test - public void testSpuriousSharedFormulaFlag() throws Exception { - - long actualCRC = getFileCRC(HSSFTestDataSamples.openSampleFileStream(ABNORMAL_SHARED_FORMULA_FLAG_TEST_FILE)); - long expectedCRC = 2277445406L; - if(actualCRC != expectedCRC) { - System.err.println("Expected crc " + expectedCRC + " but got " + actualCRC); - throw failUnexpectedTestFileChange(); - } - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook(ABNORMAL_SHARED_FORMULA_FLAG_TEST_FILE); - - HSSFSheet s = wb.getSheetAt(0); // Sheet1 - - String cellFormula; - cellFormula = getFormulaFromFirstCell(s, 0); // row "1" - // the problem is not observable in the first row of the shared formula - assertEquals("Something else wrong with this test case", "\"first formula\"", cellFormula); - - // but the problem is observable in rows 2,3,4 - cellFormula = getFormulaFromFirstCell(s, 1); // row "2" - assertNotEquals("found bug 44449 (Wrong SharedFormulaRecord was used).", "\"second formula\"", cellFormula); - - assertEquals("Something else wrong with this test case", "\"first formula\"", cellFormula); - - wb.close(); - } - private static String getFormulaFromFirstCell(HSSFSheet s, int rowIx) { - return s.getRow(rowIx).getCell(0).getCellFormula(); - } - - /** - * If someone opened this particular test file in Excel and saved it, the peculiar condition - * which causes the target bug would probably disappear. This test would then just succeed - * regardless of whether the fix was present. So a CRC check is performed to make it less easy - * for that to occur. - */ - private static RuntimeException failUnexpectedTestFileChange() { - String msg = "Test file '" + ABNORMAL_SHARED_FORMULA_FLAG_TEST_FILE + "' has changed. " - + "This junit may not be properly testing for the target bug. " - + "Either revert the test file or ensure that the new version " - + "has the right characteristics to test the target bug."; - // A breakpoint in ValueRecordsAggregate.handleMissingSharedFormulaRecord(FormulaRecord) - // should get hit during parsing of Sheet1. - // If the test spreadsheet is created as directed, this condition should occur. - // It is easy to upset the test spreadsheet (for example re-saving will destroy the - // peculiar condition we are testing for). - throw new RuntimeException(msg); - } - - /** - * gets a CRC checksum for the content of a file - */ - private static long getFileCRC(InputStream is) { - CRC32 crc = new CRC32(); - byte[] buf = new byte[2048]; - try { - while(true) { - int bytesRead = is.read(buf); - if(bytesRead < 1) { - break; - } - crc.update(buf, 0, bytesRead); - } - is.close(); - } catch (IOException e) { - throw new RuntimeException(e); - } - - return crc.getValue(); - } - - @Test - public void testRemoveNewRow_bug46312() { - // To make bug occur, rowIndex needs to be >= ValueRecordsAggregate.records.length - int rowIndex = 30; - - ValueRecordsAggregate vra = new ValueRecordsAggregate(); - try { - vra.removeAllCellsValuesForRow(rowIndex); - } catch (IllegalArgumentException e) { - if (e.getMessage().equals("Specified rowIndex 30 is outside the allowable range (0..30)")) { - throw new AssertionFailedError("Identified bug 46312"); - } - throw e; - } - -// if (false) { // same bug as demonstrated through usermodel API -// -// HSSFWorkbook wb = new HSSFWorkbook(); -// HSSFSheet sheet = wb.createSheet(); -// HSSFRow row = sheet.createRow(rowIndex); -// if (false) { // must not add any cells to the new row if we want to see the bug -// row.createCell(0); // this causes ValueRecordsAggregate.records to auto-extend -// } -// try { -// sheet.createRow(rowIndex); -// } catch (IllegalArgumentException e) { -// throw new AssertionFailedError("Identified bug 46312"); -// } -// } - } - - /** - * Tests various manipulations of blank cells, to make sure that {@link MulBlankRecord}s - * are use appropriately - */ - @Test - public void testMultipleBlanks() { - BlankRecord brA2 = newBlankRecord(0, 1); - BlankRecord brB2 = newBlankRecord(1, 1); - BlankRecord brC2 = newBlankRecord(2, 1); - BlankRecord brD2 = newBlankRecord(3, 1); - BlankRecord brE2 = newBlankRecord(4, 1); - BlankRecord brB3 = newBlankRecord(1, 2); - BlankRecord brC3 = newBlankRecord(2, 2); - - valueRecord.insertCell(brA2); - valueRecord.insertCell(brB2); - valueRecord.insertCell(brD2); - confirmMulBlank(3, 1, 1); - - valueRecord.insertCell(brC3); - confirmMulBlank(4, 1, 2); - - valueRecord.insertCell(brB3); - valueRecord.insertCell(brE2); - confirmMulBlank(6, 3, 0); - - valueRecord.insertCell(brC2); - confirmMulBlank(7, 2, 0); - - valueRecord.removeCell(brA2); - confirmMulBlank(6, 2, 0); - - valueRecord.removeCell(brC2); - confirmMulBlank(5, 2, 1); - - valueRecord.removeCell(brC3); - confirmMulBlank(4, 1, 2); - } - - private void confirmMulBlank(int expectedTotalBlankCells, - int expectedNumberOfMulBlankRecords, int expectedNumberOfSingleBlankRecords) { - // assumed row ranges set-up by caller: - final int firstRow = 1; - final int lastRow = 2; - - - final class BlankStats { - public int countBlankCells; - public int countMulBlankRecords; - public int countSingleBlankRecords; - } - - final BlankStats bs = new BlankStats(); - RecordVisitor rv = new RecordVisitor() { - - @Override - public void visitRecord(Record r) { - if (r instanceof MulBlankRecord) { - MulBlankRecord mbr = (MulBlankRecord) r; - bs.countMulBlankRecords++; - bs.countBlankCells += mbr.getNumColumns(); - } else if (r instanceof BlankRecord) { - bs.countSingleBlankRecords++; - bs.countBlankCells++; - } - } - }; - - for (int rowIx = firstRow; rowIx <=lastRow; rowIx++) { - if (valueRecord.rowHasCells(rowIx)) { - valueRecord.visitCellsForRow(rowIx, rv); - } - } - assertEquals(expectedTotalBlankCells, bs.countBlankCells); - assertEquals(expectedNumberOfMulBlankRecords, bs.countMulBlankRecords); - assertEquals(expectedNumberOfSingleBlankRecords, bs.countSingleBlankRecords); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/cf/TestCellRange.java b/src/testcases/org/apache/poi/hssf/record/cf/TestCellRange.java deleted file mode 100644 index 54f1702e2..000000000 --- a/src/testcases/org/apache/poi/hssf/record/cf/TestCellRange.java +++ /dev/null @@ -1,274 +0,0 @@ -/* ==================================================================== -Licensed to the Apache Software Foundation (ASF) under one or more -contributor license agreements. See the NOTICE file distributed with -this work for additional information regarding copyright ownership. -The ASF licenses this file to You under the Apache License, Version 2.0 -(the "License"); you may not use this file except in compliance with -the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record.cf; - -import java.util.Arrays; - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.CellRangeUtil; - -/** - * Tests CellRange operations. - */ -public final class TestCellRange extends TestCase -{ - private static final CellRangeAddress biggest = createCR( 0, -1, 0,-1); - private static final CellRangeAddress tenthColumn = createCR( 0, -1,10,10); - private static final CellRangeAddress tenthRow = createCR(10, 10, 0,-1); - private static final CellRangeAddress box10x10 = createCR( 0, 10, 0,10); - private static final CellRangeAddress box9x9 = createCR( 0, 9, 0, 9); - private static final CellRangeAddress box10to20c = createCR( 0, 10,10,20); - private static final CellRangeAddress oneCell = createCR(10, 10,10,10); - - private static final CellRangeAddress[] sampleRanges = { - biggest, tenthColumn, tenthRow, box10x10, box9x9, box10to20c, oneCell, - }; - - /** cross-reference of contains() operations for sampleRanges against itself */ - private static final boolean [][] containsExpectedResults = - { - // biggest, tenthColumn, tenthRow, box10x10, box9x9, box10to20c, oneCell - /*biggest */ {true, true , true , true , true , true , true}, - /*tenthColumn*/ {false, true , false, false, false, false, true}, - /*tenthRow */ {false, false, true , false, false, false, true}, - /*box10x10 */ {false, false, false, true , true , false, true}, - /*box9x9 */ {false, false, false, false, true , false, false}, - /*box10to20c */ {false, false, false, false, false, true , true}, - /*oneCell */ {false, false, false, false, false, false, true}, - } ; - - /** - * @param lastRow pass -1 for max row index - * @param lastCol pass -1 for max col index - */ - private static CellRangeAddress createCR(int firstRow, int lastRow, int firstCol, int lastCol) { - // max row & max col limit as per BIFF8 - return new CellRangeAddress( - firstRow, - lastRow == -1 ? 0xFFFF : lastRow, - firstCol, - lastCol == -1 ? 0x00FF : lastCol); - } - - public void testContainsMethod() - { - CellRangeAddress [] ranges = sampleRanges; - for(int i=0; i!=ranges.length;i++) - { - for(int j=0; j!=ranges.length;j++) - { - boolean expectedResult = containsExpectedResults[i][j]; - assertEquals("("+i+","+j+"): ", expectedResult, CellRangeUtil.contains(ranges[i], ranges[j])); - } - } - } - - private static final CellRangeAddress col1 = createCR( 0, -1, 1,1); - private static final CellRangeAddress col2 = createCR( 0, -1, 2,2); - private static final CellRangeAddress row1 = createCR( 1, 1, 0,-1); - private static final CellRangeAddress row2 = createCR( 2, 2, 0,-1); - - private static final CellRangeAddress box0 = createCR( 0, 2, 0,2); - private static final CellRangeAddress box1 = createCR( 0, 1, 0,1); - private static final CellRangeAddress box2 = createCR( 0, 1, 2,3); - private static final CellRangeAddress box3 = createCR( 2, 3, 0,1); - private static final CellRangeAddress box4 = createCR( 2, 3, 2,3); - private static final CellRangeAddress box5 = createCR( 1, 3, 1,3); - - public void testHasSharedBorderMethod() - { - assertFalse(CellRangeUtil.hasExactSharedBorder(col1, col1)); - assertFalse(CellRangeUtil.hasExactSharedBorder(col2, col2)); - assertTrue(CellRangeUtil.hasExactSharedBorder(col1, col2)); - assertTrue(CellRangeUtil.hasExactSharedBorder(col2, col1)); - - assertFalse(CellRangeUtil.hasExactSharedBorder(row1, row1)); - assertFalse(CellRangeUtil.hasExactSharedBorder(row2, row2)); - assertTrue(CellRangeUtil.hasExactSharedBorder(row1, row2)); - assertTrue(CellRangeUtil.hasExactSharedBorder(row2, row1)); - - assertFalse(CellRangeUtil.hasExactSharedBorder(row1, col1)); - assertFalse(CellRangeUtil.hasExactSharedBorder(row1, col2)); - assertFalse(CellRangeUtil.hasExactSharedBorder(col1, row1)); - assertFalse(CellRangeUtil.hasExactSharedBorder(col2, row1)); - assertFalse(CellRangeUtil.hasExactSharedBorder(row2, col1)); - assertFalse(CellRangeUtil.hasExactSharedBorder(row2, col2)); - assertFalse(CellRangeUtil.hasExactSharedBorder(col1, row2)); - assertFalse(CellRangeUtil.hasExactSharedBorder(col2, row2)); - assertTrue(CellRangeUtil.hasExactSharedBorder(col2, col1)); - - assertFalse(CellRangeUtil.hasExactSharedBorder(box1, box1)); - assertTrue(CellRangeUtil.hasExactSharedBorder(box1, box2)); - assertTrue(CellRangeUtil.hasExactSharedBorder(box1, box3)); - assertFalse(CellRangeUtil.hasExactSharedBorder(box1, box4)); - - assertTrue(CellRangeUtil.hasExactSharedBorder(box2, box1)); - assertFalse(CellRangeUtil.hasExactSharedBorder(box2, box2)); - assertFalse(CellRangeUtil.hasExactSharedBorder(box2, box3)); - assertTrue(CellRangeUtil.hasExactSharedBorder(box2, box4)); - - assertTrue(CellRangeUtil.hasExactSharedBorder(box3, box1)); - assertFalse(CellRangeUtil.hasExactSharedBorder(box3, box2)); - assertFalse(CellRangeUtil.hasExactSharedBorder(box3, box3)); - assertTrue(CellRangeUtil.hasExactSharedBorder(box3, box4)); - - assertFalse(CellRangeUtil.hasExactSharedBorder(box4, box1)); - assertTrue(CellRangeUtil.hasExactSharedBorder(box4, box2)); - assertTrue(CellRangeUtil.hasExactSharedBorder(box4, box3)); - assertFalse(CellRangeUtil.hasExactSharedBorder(box4, box4)); - } - - public void testIntersectMethod() - { - assertEquals(CellRangeUtil.OVERLAP, CellRangeUtil.intersect(box0, box5)); - assertEquals(CellRangeUtil.OVERLAP, CellRangeUtil.intersect(box5, box0)); - assertEquals(CellRangeUtil.NO_INTERSECTION, CellRangeUtil.intersect(box1, box4)); - assertEquals(CellRangeUtil.NO_INTERSECTION, CellRangeUtil.intersect(box4, box1)); - assertEquals(CellRangeUtil.NO_INTERSECTION, CellRangeUtil.intersect(box2, box3)); - assertEquals(CellRangeUtil.NO_INTERSECTION, CellRangeUtil.intersect(box3, box2)); - assertEquals(CellRangeUtil.INSIDE, CellRangeUtil.intersect(box0, box1)); - assertEquals(CellRangeUtil.INSIDE, CellRangeUtil.intersect(box0, box0)); - assertEquals(CellRangeUtil.ENCLOSES, CellRangeUtil.intersect(box1, box0)); - assertEquals(CellRangeUtil.INSIDE, CellRangeUtil.intersect(tenthColumn, oneCell)); - assertEquals(CellRangeUtil.ENCLOSES, CellRangeUtil.intersect(oneCell, tenthColumn)); - assertEquals(CellRangeUtil.OVERLAP, CellRangeUtil.intersect(tenthColumn, tenthRow)); - assertEquals(CellRangeUtil.OVERLAP, CellRangeUtil.intersect(tenthRow, tenthColumn)); - assertEquals(CellRangeUtil.INSIDE, CellRangeUtil.intersect(tenthColumn, tenthColumn)); - assertEquals(CellRangeUtil.INSIDE, CellRangeUtil.intersect(tenthRow, tenthRow)); - - // Bug 55380 - assertEquals(CellRangeUtil.OVERLAP, CellRangeUtil.intersect( - CellRangeAddress.valueOf("C1:D2"), CellRangeAddress.valueOf("C2:C3"))); - } - - /** - * Cell ranges like the following are valid - * =$C:$IV,$B$1:$B$8,$B$10:$B$65536,$A:$A - */ - public void testCreate() { - CellRangeAddress cr; - - cr = createCR(0, -1, 2, 255); // $C:$IV - confirmRange(cr, false, true); - cr = createCR(0, 7, 1, 1); // $B$1:$B$8 - - try { - cr = createCR(9, -1, 1, 1); // $B$65536 - } catch (IllegalArgumentException e) { - if(e.getMessage().startsWith("invalid cell range")) { - throw new AssertionFailedError("Identified bug 44739"); - } - throw e; - } - cr = createCR(0, -1, 0, 0); // $A:$A - } - - private static void confirmRange(CellRangeAddress cr, boolean isFullRow, boolean isFullColumn) { - assertEquals("isFullRowRange", isFullRow, cr.isFullRowRange()); - assertEquals("isFullColumnRange", isFullColumn, cr.isFullColumnRange()); - } - - public void testNumberOfCells() { - assertEquals(1, oneCell.getNumberOfCells()); - assertEquals(100, box9x9.getNumberOfCells()); - assertEquals(121, box10to20c.getNumberOfCells()); - } - - public void testMergeCellRanges() { - // no result on empty - cellRangeTest(new String[]{ }); - - // various cases with two ranges - cellRangeTest(new String[]{"A1:B1", "A2:B2"}, "A1:B2"); - cellRangeTest(new String[]{"A1:B1" }, "A1:B1"); - cellRangeTest(new String[]{"A1:B2", "A2:B2"}, "A1:B2"); - cellRangeTest(new String[]{"A1:B3", "A2:B2"}, "A1:B3"); - cellRangeTest(new String[]{"A1:C1", "A2:B2"}, new String[] {"A1:C1", "A2:B2"}); - - // cases with three ranges - cellRangeTest(new String[]{"A1:A1", "A2:B2", "A1:C1"}, new String[] {"A1:C1", "A2:B2"}); - cellRangeTest(new String[]{"A1:C1", "A2:B2", "A1:A1"}, new String[] {"A1:C1", "A2:B2"}); - - // "standard" cases - // enclose - cellRangeTest(new String[]{"A1:D4", "B2:C3"}, new String[] {"A1:D4"}); - // inside - cellRangeTest(new String[]{"B2:C3", "A1:D4"}, new String[] {"A1:D4"}); - cellRangeTest(new String[]{"B2:C3", "A1:D4"}, new String[] {"A1:D4"}); - // disjunct - cellRangeTest(new String[]{"A1:B2", "C3:D4"}, new String[] {"A1:B2", "C3:D4"}); - cellRangeTest(new String[]{"A1:B2", "A3:D4"}, new String[] {"A1:B2", "A3:D4"}); - // overlap that cannot be merged - cellRangeTest(new String[]{"C1:D2", "C2:C3"}, new String[] {"C1:D2", "C2:C3"}); - // overlap which could theoretically be merged, but isn't because the implementation was buggy and therefore was removed - cellRangeTest(new String[]{"A1:C3", "B1:D3"}, new String[] {"A1:C3", "B1:D3"}); // could be one region "A1:D3" - cellRangeTest(new String[]{"A1:C3", "B1:D1"}, new String[] {"A1:C3", "B1:D1"}); // could be one region "A1:D3" - } - - public void testMergeCellRanges55380() { - cellRangeTest(new String[]{"C1:D2", "C2:C3"}, new String[] {"C1:D2", "C2:C3"}); - cellRangeTest(new String[]{"A1:C3", "B2:D2"}, new String[] {"A1:C3", "B2:D2"}); - cellRangeTest(new String[]{"C9:D30", "C7:C31"}, new String[] {"C9:D30", "C7:C31"}); - } - -// public void testResolveRangeOverlap() { -// resolveRangeOverlapTest("C1:D2", "C2:C3"); -// } - - private void cellRangeTest(String[] input, String... expectedOutput) { - CellRangeAddress[] inputArr = new CellRangeAddress[input.length]; - for(int i = 0;i < input.length;i++) { - inputArr[i] = CellRangeAddress.valueOf(input[i]); - } - CellRangeAddress[] result = CellRangeUtil.mergeCellRanges(inputArr); - verifyExpectedResult(result, expectedOutput); - } - -// private void resolveRangeOverlapTest(String a, String b, String...expectedOutput) { -// CellRangeAddress rangeA = CellRangeAddress.valueOf(a); -// CellRangeAddress rangeB = CellRangeAddress.valueOf(b); -// CellRangeAddress[] result = CellRangeUtil.resolveRangeOverlap(rangeA, rangeB); -// verifyExpectedResult(result, expectedOutput); -// } - - private void verifyExpectedResult(CellRangeAddress[] result, String... expectedOutput) { - assertEquals("\nExpected: " + Arrays.toString(expectedOutput) + "\nHad: " + Arrays.toString(result), - expectedOutput.length, result.length); - for(int i = 0;i < expectedOutput.length;i++) { - assertEquals("\nExpected: " + Arrays.toString(expectedOutput) + "\nHad: " + Arrays.toString(result), - expectedOutput[i], result[i].formatAsString()); - } - } - - public void testValueOf() { - CellRangeAddress cr1 = CellRangeAddress.valueOf("A1:B1"); - assertEquals(0, cr1.getFirstColumn()); - assertEquals(0, cr1.getFirstRow()); - assertEquals(1, cr1.getLastColumn()); - assertEquals(0, cr1.getLastRow()); - - CellRangeAddress cr2 = CellRangeAddress.valueOf("B1"); - assertEquals(1, cr2.getFirstColumn()); - assertEquals(0, cr2.getFirstRow()); - assertEquals(1, cr2.getLastColumn()); - assertEquals(0, cr2.getLastRow()); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/AllChartRecordTests.java b/src/testcases/org/apache/poi/hssf/record/chart/AllChartRecordTests.java deleted file mode 100644 index 84b07e9d7..000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/AllChartRecordTests.java +++ /dev/null @@ -1,67 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record.chart; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -/** - * Collects all tests for package org.apache.poi.hssf.record.class. - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestAreaFormatRecord.class, - TestAreaRecord.class, - TestAxisLineFormatRecord.class, - TestAxisOptionsRecord.class, - TestAxisParentRecord.class, - TestAxisRecord.class, - TestAxisUsedRecord.class, - TestBarRecord.class, - TestCategorySeriesAxisRecord.class, - TestChartFormatRecord.class, - TestChartRecord.class, - TestChartTitleFormatRecord.class, - TestDatRecord.class, - TestDataFormatRecord.class, - TestDefaultDataLabelTextPropertiesRecord.class, - TestFontBasisRecord.class, - TestFontIndexRecord.class, - TestFrameRecord.class, - TestLegendRecord.class, - TestLineFormatRecord.class, - TestLinkedDataRecord.class, - TestNumberFormatIndexRecord.class, - TestObjectLinkRecord.class, - TestPlotAreaRecord.class, - TestPlotGrowthRecord.class, - TestSeriesChartGroupIndexRecord.class, - TestSeriesIndexRecord.class, - TestSeriesLabelsRecord.class, - TestSeriesListRecord.class, - TestSeriesRecord.class, - TestSeriesTextRecord.class, - TestSeriesToChartGroupRecord.class, - TestSheetPropertiesRecord.class, - TestTextRecord.class, - TestTickRecord.class, - TestUnitsRecord.class, - TestValueRangeRecord.class -}) -public class AllChartRecordTests { -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestAreaFormatRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestAreaFormatRecord.java deleted file mode 100644 index c47a8b4f7..000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestAreaFormatRecord.java +++ /dev/null @@ -1,77 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record.chart; - - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; - -import junit.framework.TestCase; - -/** - * Tests the serialization and deserialization of the AreaFormatRecord - * class works correctly. Test data taken directly from a real - * Excel file. - * - - * @author Glen Stampoultzis (glens at apache.org) - */ -public final class TestAreaFormatRecord extends TestCase { - byte[] data = new byte[] { - (byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0x00, // forecolor - (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00, // backcolor - (byte)0x01,(byte)0x00, // pattern - (byte)0x01,(byte)0x00, // format - (byte)0x4E,(byte)0x00, // forecolor index - (byte)0x4D,(byte)0x00 // backcolor index - - }; - - public void testLoad() { - - AreaFormatRecord record = new AreaFormatRecord(TestcaseRecordInputStream.create(0x100a, data)); - assertEquals( 0xFFFFFF, record.getForegroundColor()); - assertEquals( 0x000000, record.getBackgroundColor()); - assertEquals( 1, record.getPattern()); - assertEquals( 1, record.getFormatFlags()); - assertEquals( true, record.isAutomatic() ); - assertEquals( false, record.isInvert() ); - assertEquals( 0x4e, record.getForecolorIndex()); - assertEquals( 0x4d, record.getBackcolorIndex()); - - - assertEquals( 20, record.getRecordSize() ); - } - - public void testStore() - { - AreaFormatRecord record = new AreaFormatRecord(); - record.setForegroundColor( 0xFFFFFF ); - record.setBackgroundColor( 0x000000 ); - record.setPattern( (short)1 ); - record.setAutomatic( true ); - record.setInvert( false ); - record.setForecolorIndex( (short)0x4e ); - record.setBackcolorIndex( (short)0x4d ); - - - byte [] recordBytes = record.serialize(); - assertEquals(recordBytes.length - 4, data.length); - for (int i = 0; i < data.length; i++) - assertEquals("At offset " + i, data[i], recordBytes[i+4]); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestAreaRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestAreaRecord.java deleted file mode 100644 index 2570d2e1c..000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestAreaRecord.java +++ /dev/null @@ -1,63 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record.chart; - - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; - -import junit.framework.TestCase; - -/** - * Tests the serialization and deserialization of the AreaRecord - * class works correctly. Test data taken directly from a real - * Excel file. - * - * - * @author Glen Stampoultzis (glens at apache.org) - */ -public final class TestAreaRecord extends TestCase { - byte[] data = new byte[] { - (byte)0x02,(byte)0x00 // format flags - }; - - public void testLoad() { - - AreaRecord record = new AreaRecord(TestcaseRecordInputStream.create(0x101A, data)); - assertEquals( 2, record.getFormatFlags()); - assertEquals( false, record.isStacked() ); - assertEquals( true, record.isDisplayAsPercentage() ); - assertEquals( false, record.isShadow() ); - - - assertEquals( 6, record.getRecordSize() ); - } - - public void testStore() - { - AreaRecord record = new AreaRecord(); - record.setStacked( false ); - record.setDisplayAsPercentage( true ); - record.setShadow( false ); - - - byte [] recordBytes = record.serialize(); - assertEquals(recordBytes.length - 4, data.length); - for (int i = 0; i < data.length; i++) - assertEquals("At offset " + i, data[i], recordBytes[i+4]); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestAxisLineFormatRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestAxisLineFormatRecord.java deleted file mode 100644 index ae80fe2b3..000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestAxisLineFormatRecord.java +++ /dev/null @@ -1,56 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record.chart; - - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; - -import junit.framework.TestCase; - -/** - * Tests the serialization and deserialization of the AxisLineFormatRecord - * class works correctly. Test data taken directly from a real - * Excel file. - * - - * @author Glen Stampoultzis (glens at apache.org) - */ -public final class TestAxisLineFormatRecord extends TestCase { - byte[] data = new byte[] { - (byte)0x01,(byte)0x00 - }; - - public void testLoad() { - AxisLineFormatRecord record = new AxisLineFormatRecord(TestcaseRecordInputStream.create(0x1021, data)); - assertEquals( AxisLineFormatRecord.AXIS_TYPE_MAJOR_GRID_LINE, record.getAxisType()); - - assertEquals( 6, record.getRecordSize() ); - } - - public void testStore() - { - AxisLineFormatRecord record = new AxisLineFormatRecord(); - record.setAxisType( AxisLineFormatRecord.AXIS_TYPE_MAJOR_GRID_LINE ); - - - byte [] recordBytes = record.serialize(); - assertEquals(recordBytes.length - 4, data.length); - for (int i = 0; i < data.length; i++) - assertEquals("At offset " + i, data[i], recordBytes[i+4]); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestAxisOptionsRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestAxisOptionsRecord.java deleted file mode 100644 index 344bdee5d..000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestAxisOptionsRecord.java +++ /dev/null @@ -1,91 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record.chart; - - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; - -import junit.framework.TestCase; - -/** - * Tests the serialization and deserialization of the AxisOptionsRecord - * class works correctly. Test data taken directly from a real - * Excel file. - * - - * @author Andrew C. Oliver(acoliver at apache.org) - */ -public final class TestAxisOptionsRecord extends TestCase { - private static final byte[] data = { - (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x01, - (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x01,(byte)0x00, - (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00, - (byte)0x00,(byte)0xEF,(byte)0x00 - }; - - public void testLoad() { - AxisOptionsRecord record = new AxisOptionsRecord(TestcaseRecordInputStream.create(0x1062, data)); - assertEquals( 0, record.getMinimumCategory()); - assertEquals( 0, record.getMaximumCategory()); - assertEquals( 1, record.getMajorUnitValue()); - assertEquals( 0, record.getMajorUnit()); - assertEquals( 1, record.getMinorUnitValue()); - assertEquals( 0, record.getMinorUnit()); - assertEquals( 0, record.getBaseUnit()); - assertEquals( 0, record.getCrossingPoint()); - assertEquals( 239, record.getOptions()); - assertEquals( true, record.isDefaultMinimum() ); - assertEquals( true, record.isDefaultMaximum() ); - assertEquals( true, record.isDefaultMajor() ); - assertEquals( true, record.isDefaultMinorUnit() ); - assertEquals( false, record.isIsDate() ); - assertEquals( true, record.isDefaultBase() ); - assertEquals( true, record.isDefaultCross() ); - assertEquals( true, record.isDefaultDateSettings() ); - - assertEquals( 22, record.getRecordSize() ); - } - - public void testStore() - { - AxisOptionsRecord record = new AxisOptionsRecord(); - record.setMinimumCategory( (short)0 ); - record.setMaximumCategory( (short)0 ); - record.setMajorUnitValue( (short)1 ); - record.setMajorUnit( (short)0 ); - record.setMinorUnitValue( (short)1 ); - record.setMinorUnit( (short)0 ); - record.setBaseUnit( (short)0 ); - record.setCrossingPoint( (short)0 ); - record.setOptions( (short)239 ); - record.setDefaultMinimum( true ); - record.setDefaultMaximum( true ); - record.setDefaultMajor( true ); - record.setDefaultMinorUnit( true ); - record.setIsDate( false ); - record.setDefaultBase( true ); - record.setDefaultCross( true ); - record.setDefaultDateSettings( true ); - - - byte [] recordBytes = record.serialize(); - assertEquals(recordBytes.length - 4, data.length); - for (int i = 0; i < data.length; i++) - assertEquals("At offset " + i, data[i], recordBytes[i+4]); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestAxisParentRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestAxisParentRecord.java deleted file mode 100644 index 323f7f3c0..000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestAxisParentRecord.java +++ /dev/null @@ -1,67 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record.chart; - - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; - -import junit.framework.TestCase; - -/** - * Tests the serialization and deserialization of the AxisParentRecord - * class works correctly. Test data taken directly from a real - * Excel file. - * - * @author Glen Stampoultzis (glens at apache.org) - */ -public final class TestAxisParentRecord extends TestCase { - byte[] data = new byte[] { - (byte)0x00,(byte)0x00, // axis type - (byte)0x1D,(byte)0x02,(byte)0x00,(byte)0x00, // x - (byte)0xDD,(byte)0x00,(byte)0x00,(byte)0x00, // y - (byte)0x31,(byte)0x0B,(byte)0x00,(byte)0x00, // width - (byte)0x56,(byte)0x0B,(byte)0x00,(byte)0x00 // height - }; - - public void testLoad() { - AxisParentRecord record = new AxisParentRecord(TestcaseRecordInputStream.create(0x1041, data)); - assertEquals( AxisParentRecord.AXIS_TYPE_MAIN, record.getAxisType()); - assertEquals( 0x021d, record.getX()); - assertEquals( 0xdd, record.getY()); - assertEquals( 0x0b31, record.getWidth()); - assertEquals( 0x0b56, record.getHeight()); - - assertEquals( 22, record.getRecordSize() ); - } - - public void testStore() - { - AxisParentRecord record = new AxisParentRecord(); - record.setAxisType( AxisParentRecord.AXIS_TYPE_MAIN ); - record.setX( 0x021d ); - record.setY( 0xdd ); - record.setWidth( 0x0b31 ); - record.setHeight( 0x0b56 ); - - - byte [] recordBytes = record.serialize(); - assertEquals(recordBytes.length - 4, data.length); - for (int i = 0; i < data.length; i++) - assertEquals("At offset " + i, data[i], recordBytes[i+4]); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestAxisRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestAxisRecord.java deleted file mode 100644 index e8ebf322f..000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestAxisRecord.java +++ /dev/null @@ -1,69 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record.chart; - - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; - -import junit.framework.TestCase; - -/** - * Tests the serialization and deserialization of the AxisRecord - * class works correctly. Test data taken directly from a real - * Excel file. - * - - * @author Glen Stampoultzis (glens at apache.org) - */ -public final class TestAxisRecord extends TestCase { - byte[] data = new byte[] { - (byte)0x00,(byte)0x00, // type - (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00, - (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00, - (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00, - (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00 - }; - - public void testLoad() { - - AxisRecord record = new AxisRecord(TestcaseRecordInputStream.create(0x101d, data)); - assertEquals( AxisRecord.AXIS_TYPE_CATEGORY_OR_X_AXIS, record.getAxisType()); - assertEquals( 0, record.getReserved1()); - assertEquals( 0, record.getReserved2()); - assertEquals( 0, record.getReserved3()); - assertEquals( 0, record.getReserved4()); - - assertEquals( 4 + 18, record.getRecordSize() ); - } - - public void testStore() - { - AxisRecord record = new AxisRecord(); - record.setAxisType( AxisRecord.AXIS_TYPE_CATEGORY_OR_X_AXIS ); - record.setReserved1( 0 ); - record.setReserved2( 0 ); - record.setReserved3( 0 ); - record.setReserved4( 0 ); - - - byte [] recordBytes = record.serialize(); - assertEquals(recordBytes.length - 4, data.length); - for (int i = 0; i < data.length; i++) - assertEquals("At offset " + i, data[i], recordBytes[i+4]); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestAxisUsedRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestAxisUsedRecord.java deleted file mode 100644 index f421b4ffc..000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestAxisUsedRecord.java +++ /dev/null @@ -1,56 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record.chart; - - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; - -import junit.framework.TestCase; - -/** - * Tests the serialization and deserialization of the AxisUsedRecord - * class works correctly. Test data taken directly from a real - * Excel file. - * - - * @author Glen Stampoultzis (glens at apache.org) - */ -public final class TestAxisUsedRecord extends TestCase { - byte[] data = new byte[] { - (byte)0x01,(byte)0x00, - }; - - public void testLoad() { - AxisUsedRecord record = new AxisUsedRecord(TestcaseRecordInputStream.create(0x1046, data)); - assertEquals( 1, record.getNumAxis()); - - assertEquals( 6, record.getRecordSize() ); - } - - public void testStore() - { - AxisUsedRecord record = new AxisUsedRecord(); - record.setNumAxis( (short)1 ); - - - byte [] recordBytes = record.serialize(); - assertEquals(recordBytes.length - 4, data.length); - for (int i = 0; i < data.length; i++) - assertEquals("At offset " + i, data[i], recordBytes[i+4]); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestBarRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestBarRecord.java deleted file mode 100644 index 4781fe941..000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestBarRecord.java +++ /dev/null @@ -1,70 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record.chart; - - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; - -import junit.framework.TestCase; - -/** - * Tests the serialization and deserialization of the BarRecord - * class works correctly. Test data taken directly from a real - * Excel file. - * - - * @author Glen Stampoultzis (glens at apache.org) - */ -public final class TestBarRecord extends TestCase { - byte[] data = new byte[] { - (byte)0x00,(byte)0x00, // bar space - (byte)0x96,(byte)0x00, // category space - (byte)0x00,(byte)0x00 // format flags - }; - - public void testLoad() { - - BarRecord record = new BarRecord(TestcaseRecordInputStream.create(0x1017, data)); - assertEquals( 0, record.getBarSpace()); - assertEquals( 0x96, record.getCategorySpace()); - assertEquals( 0, record.getFormatFlags()); - assertEquals( false, record.isHorizontal() ); - assertEquals( false, record.isStacked() ); - assertEquals( false, record.isDisplayAsPercentage() ); - assertEquals( false, record.isShadow() ); - - assertEquals( 10, record.getRecordSize() ); - } - - public void testStore() - { - BarRecord record = new BarRecord(); - record.setBarSpace( (short)0 ); - record.setCategorySpace( (short)0x96 ); - record.setHorizontal( false ); - record.setStacked( false ); - record.setDisplayAsPercentage( false ); - record.setShadow( false ); - - - byte [] recordBytes = record.serialize(); - assertEquals(recordBytes.length - 4, data.length); - for (int i = 0; i < data.length; i++) - assertEquals("At offset " + i, data[i], recordBytes[i+4]); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestCategorySeriesAxisRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestCategorySeriesAxisRecord.java deleted file mode 100644 index 948241dbb..000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestCategorySeriesAxisRecord.java +++ /dev/null @@ -1,71 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record.chart; - - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; - -import junit.framework.TestCase; - -/** - * Tests the serialization and deserialization of the CategorySeriesAxisRecord - * class works correctly. Test data taken directly from a real - * Excel file. - * - - * @author Glen Stampoultzis (glens at apache.org) - */ -public final class TestCategorySeriesAxisRecord extends TestCase { - byte[] data = new byte[] { - (byte)0x01,(byte)0x00, // crossing point - (byte)0x01,(byte)0x00, // label frequency - (byte)0x01,(byte)0x00, // tick mark frequency - (byte)0x01,(byte)0x00 // options - }; - - public void testLoad() { - - CategorySeriesAxisRecord record = new CategorySeriesAxisRecord(TestcaseRecordInputStream.create(0x1020, data)); - assertEquals( 1, record.getCrossingPoint()); - assertEquals( 1, record.getLabelFrequency()); - assertEquals( 1, record.getTickMarkFrequency()); - assertEquals( 1, record.getOptions()); - assertEquals( true, record.isValueAxisCrossing() ); - assertEquals( false, record.isCrossesFarRight() ); - assertEquals( false, record.isReversed() ); - - assertEquals( 4 + 8, record.getRecordSize() ); - } - - public void testStore() - { - CategorySeriesAxisRecord record = new CategorySeriesAxisRecord(); - record.setCrossingPoint( (short)1 ); - record.setLabelFrequency( (short)1 ); - record.setTickMarkFrequency( (short)1 ); - record.setValueAxisCrossing( true ); - record.setCrossesFarRight( false ); - record.setReversed( false ); - - - byte [] recordBytes = record.serialize(); - assertEquals(recordBytes.length - 4, data.length); - for (int i = 0; i < data.length; i++) - assertEquals("At offset " + i, data[i], recordBytes[i+4]); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestChartFormatRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestChartFormatRecord.java deleted file mode 100644 index 15c209088..000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestChartFormatRecord.java +++ /dev/null @@ -1,60 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record.chart; - -import static org.junit.Assert.assertArrayEquals; -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -import org.apache.poi.hssf.record.RecordInputStream; -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.apache.poi.util.HexRead; - -/** - * Tests for {@link ChartFormatRecord} Test data taken directly from a real - * Excel file. - * - * @author Josh Micich - */ -public final class TestChartFormatRecord extends TestCase { - /** - * This rather uninteresting data came from attachment 23347 of bug 46693 at - * offsets 0x6BB2 and 0x7BAF - */ - private static final byte[] data = HexRead.readFromString( - "14 10 14 00 " // BIFF header - + "00 00 00 00 00 00 00 00 " - + "00 00 00 00 00 00 00 00 " - + "00 00 00 00"); - - /** - * The correct size of a {@link ChartFormatRecord} is 20 bytes (not including header). - */ - public void testLoad() { - RecordInputStream in = TestcaseRecordInputStream.create(data); - ChartFormatRecord record = new ChartFormatRecord(in); - if (in.remaining() == 2) { - throw new AssertionFailedError("Identified bug 44693d"); - } - assertEquals(0, in.remaining()); - assertEquals(24, record.getRecordSize()); - - byte[] data2 = record.serialize(); - assertArrayEquals(data, data2); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestChartRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestChartRecord.java deleted file mode 100644 index c423d1b9a..000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestChartRecord.java +++ /dev/null @@ -1,66 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record.chart; - - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; - -import junit.framework.TestCase; - -/** - * Tests the serialization and deserialization of the ChartRecord - * class works correctly. Test data taken directly from a real - * Excel file. - * - - * @author Glen Stampoultzis (glens at apache.org) - */ -public final class TestChartRecord extends TestCase { - byte[] data = new byte[] { - (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00, - (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00, - (byte)0xE8,(byte)0xFF,(byte)0xD0,(byte)0x01, - (byte)0xC8,(byte)0xCC,(byte)0xE5,(byte)0x00 - }; - - public void testLoad() { - - ChartRecord record = new ChartRecord(TestcaseRecordInputStream.create(0x1002, data)); - assertEquals( 0, record.getX()); - assertEquals( 0, record.getY()); - assertEquals( 30474216, record.getWidth()); - assertEquals( 15060168, record.getHeight()); - - assertEquals( 20, record.getRecordSize() ); - } - - public void testStore() - { - ChartRecord record = new ChartRecord(); - record.setX( 0 ); - record.setY( 0 ); - record.setWidth( 30474216 ); - record.setHeight( 15060168 ); - - - byte [] recordBytes = record.serialize(); - assertEquals(recordBytes.length - 4, data.length); - for (int i = 0; i < data.length; i++) - assertEquals("At offset " + i, data[i], recordBytes[i+4]); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestChartTitleFormatRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestChartTitleFormatRecord.java deleted file mode 100644 index d65c37e70..000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestChartTitleFormatRecord.java +++ /dev/null @@ -1,81 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record.chart; - -import static org.junit.Assert.assertEquals; - -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.eventusermodel.HSSFEventFactory; -import org.apache.poi.hssf.eventusermodel.HSSFListener; -import org.apache.poi.hssf.eventusermodel.HSSFRequest; -import org.apache.poi.hssf.record.Record; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; -import org.junit.Test; - -public final class TestChartTitleFormatRecord { - - @Test - public void testRecord() throws Exception { - NPOIFSFileSystem fs = new NPOIFSFileSystem( - HSSFTestDataSamples.getSampleFile("WithFormattedGraphTitle.xls")); - - // Check we can open the file via usermodel - HSSFWorkbook hssf = new HSSFWorkbook(fs); - - // Now process it through eventusermodel, and - // look out for the title records - ChartTitleFormatRecordGrabber grabber = new ChartTitleFormatRecordGrabber(); - InputStream din = fs.createDocumentInputStream("Workbook"); - HSSFRequest req = new HSSFRequest(); - req.addListenerForAllRecords(grabber); - HSSFEventFactory factory = new HSSFEventFactory(); - factory.processEvents(req, din); - din.close(); - - // Should've found one - assertEquals(1, grabber.chartTitleFormatRecords.size()); - // And it should be of something interesting - ChartTitleFormatRecord r = grabber.chartTitleFormatRecords.get(0); - assertEquals(3, r.getFormatCount()); - - hssf.close(); - fs.close(); - - } - - private static final class ChartTitleFormatRecordGrabber implements HSSFListener { - private final List chartTitleFormatRecords; - - public ChartTitleFormatRecordGrabber() { - chartTitleFormatRecords = new ArrayList(); - } - - @Override - public void processRecord(Record record) { - if(record instanceof ChartTitleFormatRecord) { - chartTitleFormatRecords.add((ChartTitleFormatRecord)record); - } - } - - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestDatRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestDatRecord.java deleted file mode 100644 index 93b25ed95..000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestDatRecord.java +++ /dev/null @@ -1,64 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record.chart; - - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; - -import junit.framework.TestCase; - -/** - * Tests the serialization and deserialization of the DatRecord - * class works correctly. Test data taken directly from a real - * Excel file. - * - - * @author Glen Stampoultzis (glens at apache.org) - */ -public final class TestDatRecord extends TestCase { - byte[] data = new byte[] { - (byte)0x0D,(byte)0x00 // options - }; - - public void testLoad() { - - DatRecord record = new DatRecord(TestcaseRecordInputStream.create(0x1063, data)); - assertEquals( 0xD, record.getOptions()); - assertEquals( true, record.isHorizontalBorder() ); - assertEquals( false, record.isVerticalBorder() ); - assertEquals( true, record.isBorder() ); - assertEquals( true, record.isShowSeriesKey() ); - - assertEquals( 6, record.getRecordSize() ); - } - - public void testStore() - { - DatRecord record = new DatRecord(); - record.setHorizontalBorder( true ); - record.setVerticalBorder( false ); - record.setBorder( true ); - record.setShowSeriesKey( true ); - - - byte [] recordBytes = record.serialize(); - assertEquals(recordBytes.length - 4, data.length); - for (int i = 0; i < data.length; i++) - assertEquals("At offset " + i, data[i], recordBytes[i+4]); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestDataFormatRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestDataFormatRecord.java deleted file mode 100644 index c9958f507..000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestDataFormatRecord.java +++ /dev/null @@ -1,68 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record.chart; - - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; - -import junit.framework.TestCase; - -/** - * Tests the serialization and deserialization of the DataFormatRecord - * class works correctly. Test data taken directly from a real - * Excel file. - * - - * @author Glen Stampoultzis (glens at apache.org) - */ -public final class TestDataFormatRecord extends TestCase { - byte[] data = new byte[] { - (byte)0xFF,(byte)0xFF, // point number - (byte)0x00,(byte)0x00, // series index - (byte)0x00,(byte)0x00, // series number - (byte)0x00,(byte)0x00 // format flags - }; - - public void testLoad() { - - DataFormatRecord record = new DataFormatRecord(TestcaseRecordInputStream.create(0x1006, data)); - assertEquals( (short)0xFFFF, record.getPointNumber()); - assertEquals( 0, record.getSeriesIndex()); - assertEquals( 0, record.getSeriesNumber()); - assertEquals( 0, record.getFormatFlags()); - assertEquals( false, record.isUseExcel4Colors() ); - - assertEquals( 12, record.getRecordSize() ); - } - - public void testStore() - { - DataFormatRecord record = new DataFormatRecord(); - record.setPointNumber( (short)0xFFFF ); - record.setSeriesIndex( (short)0 ); - record.setSeriesNumber( (short)0 ); - record.setFormatFlags( (short)0 ); - record.setUseExcel4Colors( false ); - - - byte [] recordBytes = record.serialize(); - assertEquals(recordBytes.length - 4, data.length); - for (int i = 0; i < data.length; i++) - assertEquals("At offset " + i, data[i], recordBytes[i+4]); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestDefaultDataLabelTextPropertiesRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestDefaultDataLabelTextPropertiesRecord.java deleted file mode 100644 index 32bddd81a..000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestDefaultDataLabelTextPropertiesRecord.java +++ /dev/null @@ -1,57 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record.chart; - - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; - -import junit.framework.TestCase; - -/** - * Tests the serialization and deserialization of the DefaultDataLabelTextPropertiesRecord - * class works correctly. Test data taken directly from a real - * Excel file. - * - - * @author Glen Stampoultzis (glens at apache.org) - */ -public final class TestDefaultDataLabelTextPropertiesRecord extends TestCase { - byte[] data = new byte[] { - (byte)0x02,(byte)0x00 - }; - - public void testLoad() { - - DefaultDataLabelTextPropertiesRecord record = new DefaultDataLabelTextPropertiesRecord(TestcaseRecordInputStream.create(0x1024, data)); - assertEquals( 2, record.getCategoryDataType()); - - assertEquals( 6, record.getRecordSize() ); - } - - public void testStore() - { - DefaultDataLabelTextPropertiesRecord record = new DefaultDataLabelTextPropertiesRecord(); - record.setCategoryDataType( (short)2 ); - - - byte [] recordBytes = record.serialize(); - assertEquals(recordBytes.length - 4, data.length); - for (int i = 0; i < data.length; i++) - assertEquals("At offset " + i, data[i], recordBytes[i+4]); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestFontBasisRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestFontBasisRecord.java deleted file mode 100644 index c783a34e6..000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestFontBasisRecord.java +++ /dev/null @@ -1,68 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record.chart; - - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; - -import junit.framework.TestCase; - -/** - * Tests the serialization and deserialization of the FontBasisRecord - * class works correctly. Test data taken directly from a real - * Excel file. - * - - * @author Glen Stampoultzis (glens at apache.org) - */ -public final class TestFontBasisRecord extends TestCase { - byte[] data = new byte[] { - (byte)0x28,(byte)0x1A, // x basis - (byte)0x9C,(byte)0x0F, // y basis - (byte)0xC8,(byte)0x00, // height basis - (byte)0x00,(byte)0x00, // scale - (byte)0x05,(byte)0x00 // index to font table - }; - - public void testLoad() { - - FontBasisRecord record = new FontBasisRecord(TestcaseRecordInputStream.create(0x1060, data)); - assertEquals( 0x1a28, record.getXBasis()); - assertEquals( 0x0f9c, record.getYBasis()); - assertEquals( 0xc8, record.getHeightBasis()); - assertEquals( 0x00, record.getScale()); - assertEquals( 0x05, record.getIndexToFontTable()); - - assertEquals( 14, record.getRecordSize() ); - } - - public void testStore() - { - FontBasisRecord record = new FontBasisRecord(); - record.setXBasis( (short)0x1a28 ); - record.setYBasis( (short)0x0f9c ); - record.setHeightBasis( (short)0xc8 ); - record.setScale( (short)0x00 ); - record.setIndexToFontTable( (short)0x05 ); - - byte [] recordBytes = record.serialize(); - assertEquals(recordBytes.length - 4, data.length); - for (int i = 0; i < data.length; i++) - assertEquals("At offset " + i, data[i], recordBytes[i+4]); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestFontIndexRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestFontIndexRecord.java deleted file mode 100644 index fb09d30dc..000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestFontIndexRecord.java +++ /dev/null @@ -1,57 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record.chart; - - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; - -import junit.framework.TestCase; - -/** - * Tests the serialization and deserialization of the FontIndexRecord - * class works correctly. Test data taken directly from a real - * Excel file. - * - - * @author Glen Stampoultzis (glens at apache.org) - */ -public final class TestFontIndexRecord extends TestCase { - byte[] data = new byte[] { - (byte)0x05,(byte)0x00 - }; - - public void testLoad() { - - FontIndexRecord record = new FontIndexRecord(TestcaseRecordInputStream.create(0x1026, data)); - assertEquals( 5, record.getFontIndex()); - - assertEquals( 6, record.getRecordSize() ); - } - - public void testStore() - { - FontIndexRecord record = new FontIndexRecord(); - record.setFontIndex( (short)5 ); - - - byte [] recordBytes = record.serialize(); - assertEquals(recordBytes.length - 4, data.length); - for (int i = 0; i < data.length; i++) - assertEquals("At offset " + i, data[i], recordBytes[i+4]); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestFrameRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestFrameRecord.java deleted file mode 100644 index da2a8a318..000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestFrameRecord.java +++ /dev/null @@ -1,64 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record.chart; - - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; - -import junit.framework.TestCase; - -/** - * Tests the serialization and deserialization of the FrameRecord - * class works correctly. Test data taken directly from a real - * Excel file. - * - - * @author Glen Stampoultzis (glens at apache.org) - */ -public final class TestFrameRecord extends TestCase { - byte[] data = new byte[] { - (byte)0x00,(byte)0x00, // border type - (byte)0x02,(byte)0x00 // options - }; - - public void testLoad() { - - FrameRecord record = new FrameRecord(TestcaseRecordInputStream.create(0x1032, data)); - assertEquals( FrameRecord.BORDER_TYPE_REGULAR, record.getBorderType()); - assertEquals( 2, record.getOptions()); - assertEquals( false, record.isAutoSize() ); - assertEquals( true, record.isAutoPosition() ); - - assertEquals( 8, record.getRecordSize() ); - } - - public void testStore() - { - FrameRecord record = new FrameRecord(); - record.setBorderType( FrameRecord.BORDER_TYPE_REGULAR ); - record.setOptions( (short)2 ); - record.setAutoSize( false ); - record.setAutoPosition( true ); - - - byte [] recordBytes = record.serialize(); - assertEquals(recordBytes.length - 4, data.length); - for (int i = 0; i < data.length; i++) - assertEquals("At offset " + i, data[i], recordBytes[i+4]); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestLegendRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestLegendRecord.java deleted file mode 100644 index a23d6741b..000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestLegendRecord.java +++ /dev/null @@ -1,91 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record.chart; - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; - -import junit.framework.TestCase; - -/** - * Tests the serialization and deserialization of the LegendRecord class works - * correctly. Test data taken directly from a real Excel file. - * - * - * @author Andrew C. Oliver (acoliver at apache.org) - */ -public final class TestLegendRecord extends TestCase { - byte[] data = new byte[] { (byte) 0x76, (byte) 0x0E, (byte) 0x00, (byte) 0x00, (byte) 0x86, - (byte) 0x07, (byte) 0x00, (byte) 0x00, (byte) 0x19, (byte) 0x01, (byte) 0x00, - (byte) 0x00, (byte) 0x8B, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x03, - (byte) 0x01, (byte) 0x1F, (byte) 0x00 }; - - public void testLoad() { - LegendRecord record = new LegendRecord(TestcaseRecordInputStream.create(0x1015, data)); - - assertEquals(0xe76, record.getXAxisUpperLeft()); - - assertEquals(0x786, record.getYAxisUpperLeft()); - - assertEquals(0x119, record.getXSize()); - - assertEquals(0x8b, record.getYSize()); - - assertEquals((byte) 0x3, record.getType()); - - assertEquals((byte) 0x1, record.getSpacing()); - - assertEquals((short) 0x1f, record.getOptions()); - assertEquals(true, record.isAutoPosition()); - assertEquals(true, record.isAutoSeries()); - assertEquals(true, record.isAutoXPositioning()); - assertEquals(true, record.isAutoYPositioning()); - assertEquals(true, record.isVertical()); - assertEquals(false, record.isDataTable()); - - assertEquals(24, record.getRecordSize()); - } - - public void testStore() { - LegendRecord record = new LegendRecord(); - - record.setXAxisUpperLeft(0xe76); - - record.setYAxisUpperLeft(0x786); - - record.setXSize(0x119); - - record.setYSize(0x8b); - - record.setType((byte) 0x3); - - record.setSpacing((byte) 0x1); - - record.setOptions((short) 0x1f); - record.setAutoPosition(true); - record.setAutoSeries(true); - record.setAutoXPositioning(true); - record.setAutoYPositioning(true); - record.setVertical(true); - record.setDataTable(false); - - byte[] recordBytes = record.serialize(); - assertEquals(recordBytes.length - 4, data.length); - for (int i = 0; i < data.length; i++) - assertEquals("At offset " + i, data[i], recordBytes[i + 4]); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestLineFormatRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestLineFormatRecord.java deleted file mode 100644 index 5b58b2256..000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestLineFormatRecord.java +++ /dev/null @@ -1,71 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record.chart; - - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; - -import junit.framework.TestCase; - -/** - * Tests the serialization and deserialization of the LineFormatRecord - * class works correctly. Test data taken directly from a real - * Excel file. - * - - * @author Glen Stampoultzis (glens at apache.org) - */ -public final class TestLineFormatRecord extends TestCase { - byte[] data = new byte[] { - (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00, // colour - (byte)0x00,(byte)0x00, // pattern - (byte)0x00,(byte)0x00, // weight - (byte)0x01,(byte)0x00, // format - (byte)0x4D,(byte)0x00 // index - }; - - public void testLoad() { - LineFormatRecord record = new LineFormatRecord(TestcaseRecordInputStream.create(0x1007, data)); - assertEquals( 0, record.getLineColor()); - assertEquals( 0, record.getLinePattern()); - assertEquals( 0, record.getWeight()); - assertEquals( 1, record.getFormat()); - assertEquals( true, record.isAuto() ); - assertEquals( false, record.isDrawTicks() ); - assertEquals( 0x4d, record.getColourPaletteIndex()); - - assertEquals( 16, record.getRecordSize() ); - } - - public void testStore() - { - LineFormatRecord record = new LineFormatRecord(); - record.setLineColor( 0 ); - record.setLinePattern( (short)0 ); - record.setWeight( (short)0 ); - record.setAuto( true ); - record.setDrawTicks( false ); - record.setColourPaletteIndex( (short)0x4d ); - - - byte [] recordBytes = record.serialize(); - assertEquals(recordBytes.length - 4, data.length); - for (int i = 0; i < data.length; i++) - assertEquals("At offset " + i, data[i], recordBytes[i+4]); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestLinkedDataRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestLinkedDataRecord.java deleted file mode 100644 index 3fa87dcc8..000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestLinkedDataRecord.java +++ /dev/null @@ -1,193 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record.chart; - - -import junit.framework.TestCase; - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.apache.poi.ss.formula.ptg.Area3DPtg; -import org.apache.poi.ss.formula.ptg.Ptg; - -/** - * Tests the serialization and deserialization of the LinkedDataRecord - * class works correctly. Test data taken directly from a real - * Excel file. - * - * @author Glen Stampoultzis (glens at apache.org) - */ -public final class TestLinkedDataRecord extends TestCase { - -/* - The records below are records that would appear in a simple bar chart - - The first record links to the series title (linkType = 0). It's - reference type is 1 which means that it links directly to data entered - into the forumula bar. There seems to be no reference to any data - however. The formulaOfLink field contains two 0 bytes. This probably - means that there is no particular heading set. - - -============================================ -Offset 0xf9c (3996) -rectype = 0x1051, recsize = 0x8 --BEGIN DUMP--------------------------------- -00000000 00 01 00 00 00 00 00 00 ........ --END DUMP----------------------------------- -recordid = 0x1051, size =8 -[AI] -.linkType = 0x00 (0 ) -.referenceType = 0x01 (1 ) -.options = 0x0000 (0 ) - .customNumberFormat = false -.indexNumberFmtRecord = 0x0000 (0 ) -.formulaOfLink = (org.apache.poi.hssf.record.LinkedDataFormulaField@95fd19 ) -[/AI] - - - The second record links to the series data (linkType=1). The - referenceType = 2 which means it's linked to the worksheet. - It links using a formula. The formula value is - 0B 00 3B 00 00 00 00 1E 00 01 00 01 00. - - 0B 00 11 bytes length - 3B (tArea3d) Rectangular area - 00 00 index to REF entry in extern sheet - 00 00 index to first row - 1E 00 index to last row - 01 00 index to first column and relative flags - 01 00 index to last column and relative flags - -============================================ -Offset 0xfa8 (4008) -rectype = 0x1051, recsize = 0x13 --BEGIN DUMP--------------------------------- -00000000 01 02 00 00 00 00 0B 00 3B 00 00 00 00 1E 00 01 ........;....... -00000010 00 01 00 ... --END DUMP----------------------------------- -recordid = 0x1051, size =19 -[AI] -.linkType = 0x01 (1 ) -.referenceType = 0x02 (2 ) -.options = 0x0000 (0 ) - .customNumberFormat = false -.indexNumberFmtRecord = 0x0000 (0 ) -.formulaOfLink = (org.apache.poi.hssf.record.LinkedDataFormulaField@11b9fb1 ) -[/AI] - - The third record links to the series categories (linkType=2). The - reference type of 2 means that it's linked to the worksheet. - It links using a formula. The formula value is - 0B 00 3B 00 00 00 00 1E 00 01 00 01 00 - - 0B 00 11 bytes in length - 3B (tArea3d) Rectangular area - 00 00 index to REF entry in extern sheet - 00 00 index to first row - 00 1F index to last row - 00 00 index to first column and relative flags - 00 00 index to last column and relative flags - - -============================================ -Offset 0xfbf (4031) -rectype = 0x1051, recsize = 0x13 --BEGIN DUMP--------------------------------- -00000000 02 02 00 00 69 01 0B 00 3B 00 00 00 00 1F 00 00 ....i...;....... -00000010 00 00 00 ... --END DUMP----------------------------------- -recordid = 0x1051, size =19 -[AI] -.linkType = 0x02 (2 ) -.referenceType = 0x02 (2 ) -.options = 0x0000 (0 ) - .customNumberFormat = false -.indexNumberFmtRecord = 0x0169 (361 ) -.formulaOfLink = (org.apache.poi.hssf.record.LinkedDataFormulaField@913fe2 ) -[/AI] - -This third link type does not seem to be documented and does not appear to -contain any useful information anyway. - -============================================ -Offset 0xfd6 (4054) -rectype = 0x1051, recsize = 0x8 --BEGIN DUMP--------------------------------- -00000000 03 01 00 00 00 00 00 00 ........ --END DUMP----------------------------------- -recordid = 0x1051, size =8 -[AI] -.linkType = 0x03 (3 ) -.referenceType = 0x01 (1 ) -.options = 0x0000 (0 ) - .customNumberFormat = false -.indexNumberFmtRecord = 0x0000 (0 ) -.formulaOfLink = (org.apache.poi.hssf.record.LinkedDataFormulaField@1f934ad ) -[/AI] - -*/ - - byte[] data = new byte[]{ - (byte)0x01, // link type - (byte)0x02, // reference type - (byte)0x00,(byte)0x00, // options - (byte)0x00,(byte)0x00, // index number format record - (byte)0x0B,(byte)0x00, // 11 bytes length - (byte)0x3B, // formula of link - (byte)0x00,(byte)0x00, // index to ref entry in extern sheet - (byte)0x00,(byte)0x00, // index to first row - (byte)0x00,(byte)0x1F, // index to last row - (byte)0x00,(byte)0x00, // index to first column and relative flags - (byte)0x00,(byte)0x00, // index to last column and relative flags - }; - - public void testLoad() { - - LinkedDataRecord record = new LinkedDataRecord(TestcaseRecordInputStream.create(0x1051, data)); - assertEquals( LinkedDataRecord.LINK_TYPE_VALUES, record.getLinkType()); - assertEquals( LinkedDataRecord.REFERENCE_TYPE_WORKSHEET, record.getReferenceType()); - assertEquals( 0, record.getOptions()); - assertEquals( false, record.isCustomNumberFormat() ); - assertEquals( 0, record.getIndexNumberFmtRecord()); - - Area3DPtg ptgExpected = new Area3DPtg(0, 7936, 0, 0, - false, false, false, false, 0); - - Ptg ptgActual = record.getFormulaOfLink()[0]; - assertEquals(ptgExpected.toString(), ptgActual.toString()); - - assertEquals( data.length + 4, record.getRecordSize() ); - } - - public void testStore() { - LinkedDataRecord record = new LinkedDataRecord(); - record.setLinkType( LinkedDataRecord.LINK_TYPE_VALUES ); - record.setReferenceType( LinkedDataRecord.REFERENCE_TYPE_WORKSHEET ); - record.setOptions( (short)0 ); - record.setCustomNumberFormat( false ); - record.setIndexNumberFmtRecord( (short)0 ); - Area3DPtg ptg = new Area3DPtg(0, 7936, 0, 0, - false, false, false, false, 0); - record.setFormulaOfLink(new Ptg[] { ptg, } ); - - byte [] recordBytes = record.serialize(); - assertEquals(recordBytes.length - 4, data.length); - for (int i = 0; i < data.length; i++) - assertEquals("At offset " + i, data[i], recordBytes[i+4]); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestNumberFormatIndexRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestNumberFormatIndexRecord.java deleted file mode 100644 index d06f646c5..000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestNumberFormatIndexRecord.java +++ /dev/null @@ -1,57 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record.chart; - - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; - -import junit.framework.TestCase; - -/** - * Tests the serialization and deserialization of the NumberFormatIndexRecord - * class works correctly. Test data taken directly from a real - * Excel file. - * - - * @author Glen Stampoultzis (glens at apache.org) - */ -public final class TestNumberFormatIndexRecord extends TestCase { - byte[] data = new byte[] { - 0x05,0x00 - }; - - public void testLoad() { - - NumberFormatIndexRecord record = new NumberFormatIndexRecord(TestcaseRecordInputStream.create(0x104e, data)); - assertEquals( 5, record.getFormatIndex()); - - assertEquals( 6, record.getRecordSize() ); - } - - public void testStore() - { - NumberFormatIndexRecord record = new NumberFormatIndexRecord(); - record.setFormatIndex( (short)5 ); - - - byte [] recordBytes = record.serialize(); - assertEquals(recordBytes.length - 4, data.length); - for (int i = 0; i < data.length; i++) - assertEquals("At offset " + i, data[i], recordBytes[i+4]); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestObjectLinkRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestObjectLinkRecord.java deleted file mode 100644 index f12babe13..000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestObjectLinkRecord.java +++ /dev/null @@ -1,61 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record.chart; - - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; - -import junit.framework.TestCase; - -/** - * Tests the serialization and deserialization of the ObjectLinkRecord - * class works correctly. Test data taken directly from a real - * Excel file. - * - - * @author Andrew C. Oliver (acoliver at apache.org) - */ -public final class TestObjectLinkRecord extends TestCase { - byte[] data = new byte[] { - (byte)0x03,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00 - }; - - public void testLoad() { - ObjectLinkRecord record = new ObjectLinkRecord(TestcaseRecordInputStream.create(0x1027, data)); - - assertEquals( (short)3, record.getAnchorId()); - assertEquals( (short)0x00, record.getLink1()); - assertEquals( (short)0x00, record.getLink2()); - - assertEquals( 10, record.getRecordSize() ); - } - - public void testStore() { - ObjectLinkRecord record = new ObjectLinkRecord(); - - record.setAnchorId( (short)3 ); - record.setLink1( (short)0x00 ); - record.setLink2( (short)0x00 ); - - - byte [] recordBytes = record.serialize(); - assertEquals(recordBytes.length - 4, data.length); - for (int i = 0; i < data.length; i++) - assertEquals("At offset " + i, data[i], recordBytes[i+4]); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestPlotAreaRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestPlotAreaRecord.java deleted file mode 100644 index bfd678b30..000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestPlotAreaRecord.java +++ /dev/null @@ -1,52 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record.chart; - - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; - -import junit.framework.TestCase; - -/** - * Tests the serialization and deserialization of the PlotAreaRecord - * class works correctly. Test data taken directly from a real - * Excel file. - * - - * @author Andrew C. Oliver (acoliver at apache.org) - */ -public final class TestPlotAreaRecord extends TestCase { - byte[] data = new byte[] { - - }; - - public void testLoad() { - PlotAreaRecord record = new PlotAreaRecord(TestcaseRecordInputStream.create(0x1035, data)); - - assertEquals( 4, record.getRecordSize() ); - } - - public void testStore() { - PlotAreaRecord record = new PlotAreaRecord(); - - byte [] recordBytes = record.serialize(); - assertEquals(recordBytes.length - 4, data.length); - for (int i = 0; i < data.length; i++) - assertEquals("At offset " + i, data[i], recordBytes[i+4]); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestPlotGrowthRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestPlotGrowthRecord.java deleted file mode 100644 index cb7de70b0..000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestPlotGrowthRecord.java +++ /dev/null @@ -1,59 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record.chart; - - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; - -import junit.framework.TestCase; - -/** - * Tests the serialization and deserialization of the PlotGrowthRecord - * class works correctly. Test data taken directly from a real - * Excel file. - * - * @author Glen Stampoultzis (glens at apache.org) - */ -public final class TestPlotGrowthRecord extends TestCase { - byte[] data = new byte[] { - (byte)0x00,(byte)0x00,(byte)0x01,(byte)0x00, // horizontal - (byte)0x00,(byte)0x00,(byte)0x01,(byte)0x00 // vertical - }; - - public void testLoad() { - - PlotGrowthRecord record = new PlotGrowthRecord(TestcaseRecordInputStream.create(0x1064, data)); - assertEquals( 65536, record.getHorizontalScale()); - assertEquals( 65536, record.getVerticalScale()); - - assertEquals( 12, record.getRecordSize() ); - } - - public void testStore() - { - PlotGrowthRecord record = new PlotGrowthRecord(); - record.setHorizontalScale( 65536 ); - record.setVerticalScale( 65536 ); - - - byte [] recordBytes = record.serialize(); - assertEquals(recordBytes.length - 4, data.length); - for (int i = 0; i < data.length; i++) - assertEquals("At offset " + i, data[i], recordBytes[i+4]); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesChartGroupIndexRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesChartGroupIndexRecord.java deleted file mode 100644 index d216cc2f2..000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesChartGroupIndexRecord.java +++ /dev/null @@ -1,55 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record.chart; - - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; - -import junit.framework.TestCase; - -/** - * Tests the serialization and deserialization of the SeriesChartGroupIndexRecord - * class works correctly. Test data taken directly from a real - * Excel file. - * - * @author Glen Stampoultzis (glens at apache.org) - */ -public final class TestSeriesChartGroupIndexRecord extends TestCase { - byte[] data = new byte[] { - (byte)0x00,(byte)0x00 - }; - - public void testLoad() { - SeriesChartGroupIndexRecord record = new SeriesChartGroupIndexRecord(TestcaseRecordInputStream.create(0x1045, data)); - assertEquals( 0, record.getChartGroupIndex()); - - assertEquals( 6, record.getRecordSize() ); - } - - public void testStore() - { - SeriesChartGroupIndexRecord record = new SeriesChartGroupIndexRecord(); - record.setChartGroupIndex( (short)0 ); - - - byte [] recordBytes = record.serialize(); - assertEquals(recordBytes.length - 4, data.length); - for (int i = 0; i < data.length; i++) - assertEquals("At offset " + i, data[i], recordBytes[i+4]); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesIndexRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesIndexRecord.java deleted file mode 100644 index 86f24a38b..000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesIndexRecord.java +++ /dev/null @@ -1,59 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record.chart; - - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; - -import junit.framework.TestCase; - -/** - * Tests the serialization and deserialization of the SeriesIndexRecord - * class works correctly. Test data taken directly from a real - * Excel file. - * - - * @author Andrew C. Oliver (acoliver at apache.org) - */ -public final class TestSeriesIndexRecord extends TestCase { - byte[] data = new byte[] { - (byte)0x03,(byte)0x00 - }; - - public void testLoad() { - SeriesIndexRecord record = new SeriesIndexRecord(TestcaseRecordInputStream.create(0x1065, data)); - - assertEquals( (short)3, record.getIndex()); - assertEquals( 6, record.getRecordSize() ); - } - - public void testStore() - { - SeriesIndexRecord record = new SeriesIndexRecord(); - - - - record.setIndex( (short)3 ); - - - byte [] recordBytes = record.serialize(); - assertEquals(recordBytes.length - 4, data.length); - for (int i = 0; i < data.length; i++) - assertEquals("At offset " + i, data[i], recordBytes[i+4]); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesLabelsRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesLabelsRecord.java deleted file mode 100644 index 9f0f1f1ea..000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesLabelsRecord.java +++ /dev/null @@ -1,68 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record.chart; - - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; - -import junit.framework.TestCase; - -/** - * Tests the serialization and deserialization of the SeriesLabelsRecord - * class works correctly. Test data taken directly from a real - * Excel file. - * - - * @author Glen Stampoultzis (glens at apache.org) - */ -public final class TestSeriesLabelsRecord extends TestCase { - byte[] data = new byte[] { - (byte)0x03,(byte)0x00 - }; - - public void testLoad() { - SeriesLabelsRecord record = new SeriesLabelsRecord(TestcaseRecordInputStream.create(0x100c, data)); - assertEquals( 3, record.getFormatFlags()); - assertEquals( true, record.isShowActual() ); - assertEquals( true, record.isShowPercent() ); - assertEquals( false, record.isLabelAsPercentage() ); - assertEquals( false, record.isSmoothedLine() ); - assertEquals( false, record.isShowLabel() ); - assertEquals( false, record.isShowBubbleSizes() ); - - - assertEquals( 2+4, record.getRecordSize() ); - } - - public void testStore() - { - SeriesLabelsRecord record = new SeriesLabelsRecord(); - record.setShowActual( true ); - record.setShowPercent( true ); - record.setLabelAsPercentage( false ); - record.setSmoothedLine( false ); - record.setShowLabel( false ); - record.setShowBubbleSizes( false ); - - - byte [] recordBytes = record.serialize(); - assertEquals(recordBytes.length - 4, data.length); - for (int i = 0; i < data.length; i++) - assertEquals("At offset " + i, data[i], recordBytes[i+4]); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesListRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesListRecord.java deleted file mode 100644 index c049de4f3..000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesListRecord.java +++ /dev/null @@ -1,56 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record.chart; - - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; - -import junit.framework.TestCase; - -/** - * Tests the serialization and deserialization of the SeriesListRecord - * class works correctly. Test data taken directly from a real - * Excel file. - * - - * @author Glen Stampoultzis (glens at apache.org) - */ -public final class TestSeriesListRecord extends TestCase { - private static final byte[] data = { - (byte)0x02,(byte)0x00,(byte)0x01,(byte)0x20,(byte)0xff,(byte)0xf0 - }; - - public void testLoad() { - - SeriesListRecord record = new SeriesListRecord(TestcaseRecordInputStream.create(0x1016, data)); - assertEquals( (short)0x2001, record.getSeriesNumbers()[0]); - assertEquals( (short)0xf0ff, record.getSeriesNumbers()[1]); - assertEquals( 2, record.getSeriesNumbers().length); - - assertEquals( 4 + 6, record.getRecordSize() ); - } - - public void testStore() { - SeriesListRecord record = new SeriesListRecord(new short[] { (short)0x2001, (short)0xf0ff } ); - - byte [] recordBytes = record.serialize(); - assertEquals(recordBytes.length - 4, data.length); - for (int i = 0; i < data.length; i++) - assertEquals("At offset " + i, data[i], recordBytes[i+4]); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesRecord.java deleted file mode 100644 index dacaae10d..000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesRecord.java +++ /dev/null @@ -1,71 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record.chart; - - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; - -import junit.framework.TestCase; - -/** - * Tests the serialization and deserialization of the SeriesRecord - * class works correctly. Test data taken directly from a real - * Excel file. - * - * @author Glen Stampoultzis (glens at apache.org) - */ -public final class TestSeriesRecord extends TestCase { - byte[] data = new byte[] { - (byte)0x01,(byte)0x00, // category data type - (byte)0x01,(byte)0x00, // values data type - (byte)0x1B,(byte)0x00, // num categories - (byte)0x1B,(byte)0x00, // num values - (byte)0x01,(byte)0x00, // bubble series type - (byte)0x00,(byte)0x00 // num bubble values - }; - - public void testLoad() { - - SeriesRecord record = new SeriesRecord(TestcaseRecordInputStream.create(0x1003, data)); - assertEquals( SeriesRecord.CATEGORY_DATA_TYPE_NUMERIC, record.getCategoryDataType()); - assertEquals( SeriesRecord.VALUES_DATA_TYPE_NUMERIC, record.getValuesDataType()); - assertEquals( 27, record.getNumCategories()); - assertEquals( 27, record.getNumValues()); - assertEquals( SeriesRecord.BUBBLE_SERIES_TYPE_NUMERIC, record.getBubbleSeriesType()); - assertEquals( 0, record.getNumBubbleValues()); - - - assertEquals( 16, record.getRecordSize() ); - } - - public void testStore() - { - SeriesRecord record = new SeriesRecord(); - record.setCategoryDataType( SeriesRecord.CATEGORY_DATA_TYPE_NUMERIC ); - record.setValuesDataType( SeriesRecord.VALUES_DATA_TYPE_NUMERIC ); - record.setNumCategories( (short)27 ); - record.setNumValues( (short)27 ); - record.setBubbleSeriesType( SeriesRecord.BUBBLE_SERIES_TYPE_NUMERIC ); - record.setNumBubbleValues( (short)0 ); - - byte [] recordBytes = record.serialize(); - assertEquals(recordBytes.length - 4, data.length); - for (int i = 0; i < data.length; i++) - assertEquals("At offset " + i, data[i], recordBytes[i+4]); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesTextRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesTextRecord.java deleted file mode 100644 index 2d11999be..000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesTextRecord.java +++ /dev/null @@ -1,108 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record.chart; - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -import org.apache.poi.hssf.record.RecordFormatException; -import org.apache.poi.hssf.record.RecordInputStream; -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.apache.poi.util.HexRead; - -/** - * Tests the serialization and deserialization of the SeriesTextRecord class - * works correctly. Test data taken directly from a real Excel file. - * - * - * @author Andrew C. Oliver (acoliver at apache.org) - */ -public final class TestSeriesTextRecord extends TestCase { - private static final byte[] SIMPLE_DATA = HexRead - .readFromString("00 00 0C 00 56 61 6C 75 65 20 4E 75 6D 62 65 72"); - - public void testLoad() { - SeriesTextRecord record = new SeriesTextRecord(TestcaseRecordInputStream.create(0x100d, SIMPLE_DATA)); - - assertEquals((short) 0, record.getId()); - assertEquals("Value Number", record.getText()); - - assertEquals(SIMPLE_DATA.length + 4, record.getRecordSize()); - } - - public void testStore() { - SeriesTextRecord record = new SeriesTextRecord(); - - record.setId(0); - record.setText("Value Number"); - - byte[] recordBytes = record.serialize(); - TestcaseRecordInputStream.confirmRecordEncoding(SeriesTextRecord.sid, SIMPLE_DATA, - recordBytes); - } - - public void testReserializeLongTitle() { - // Hex dump from bug 45784 attachment 22560 streamOffset=0x0CD1 - byte[] data = HexRead.readFromString( - "00 00, " - + "82 " - + "01 " - + "50 00 6C 00 61 00 73 00 6D 00 61 00 20 00 4C 00 " - + "65 00 76 00 65 00 6C 00 73 00 20 00 6F 00 66 00 " - + "20 00 4C 00 2D 00 30 00 30 00 30 00 31 00 31 00 " - + "31 00 32 00 32 00 32 00 2D 00 33 00 33 00 33 00 " - + "58 00 34 00 34 00 34 00 20 00 69 00 6E 00 20 00 " - + "53 00 44 00 20 00 72 00 61 00 74 00 0A 00 50 00 " - + "4F 00 20 00 33 00 2E 00 30 00 20 00 6D 00 67 00 " - + "2F 00 6B 00 67 00 20 00 28 00 35 00 2E 00 30 00 " - + "20 00 6D 00 4C 00 2F 00 6B 00 67 00 29 00 20 00 " - + "69 00 6E 00 20 00 4D 00 65 00 74 00 68 00 6F 00 " - + "63 00 65 00 6C 00 0A 00 49 00 56 00 20 00 30 00 " - + "2E 00 35 00 20 00 6D 00 67 00 2F 00 6B 00 67 00 " - + "20 00 28 00 31 00 2E 00 30 00 20 00 6D 00 4C 00 " - + "2F 00 6B 00 67 00 29 00 20 00 69 00 6E 00 20 00 " - + "36 00 30 00 25 00 20 00 50 00 45 00 47 00 20 00 " - + "32 00 30 00 30 00 0A 00 46 00 20 00 3D 00 61 00 " - + "62 00 63 00"); - - RecordInputStream in = TestcaseRecordInputStream.create(SeriesTextRecord.sid, data); - SeriesTextRecord str; - try { - str = new SeriesTextRecord(in); - } catch (RecordFormatException e) { - if (e.getCause() instanceof IllegalArgumentException) { - // 'would be' error msg changed at svn r703620 - // "Illegal length - asked for -126 but only 130 left!" - // "Bad requested string length (-126)" - throw new AssertionFailedError("Identified bug 45784a"); - } - throw e; - } - - if (str.getRecordSize() < 0) { - throw new AssertionFailedError("Identified bug 45784b"); - } - byte[] ser; - try { - ser = str.serialize(); - } catch (Exception e) { - throw new RuntimeException(e); - } - TestcaseRecordInputStream.confirmRecordEncoding(SeriesTextRecord.sid, data, ser); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesToChartGroupRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesToChartGroupRecord.java deleted file mode 100644 index 22ad685c2..000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestSeriesToChartGroupRecord.java +++ /dev/null @@ -1,56 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record.chart; - - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; - -import junit.framework.TestCase; - -/** - * Tests the serialization and deserialization of the SeriesToChartGroupRecord - * class works correctly. Test data taken directly from a real - * Excel file. - * - - * @author Andrew C. Oliver (acoliver at apache.org) - */ -public final class TestSeriesToChartGroupRecord extends TestCase { - byte[] data = new byte[] { - (byte)0x0, (byte)0x0 - }; - - public void testLoad() { - SeriesToChartGroupRecord record = new SeriesToChartGroupRecord(TestcaseRecordInputStream.create(0x1045, data)); - assertEquals( 0x0, record.getChartGroupIndex()); - - assertEquals( 0x6, record.getRecordSize() ); - } - - public void testStore() - { - SeriesToChartGroupRecord record = new SeriesToChartGroupRecord(); - record.setChartGroupIndex( (short)0x0 ); - - - byte [] recordBytes = record.serialize(); - assertEquals(recordBytes.length - 4, data.length); - for (int i = 0; i < data.length; i++) - assertEquals("At offset " + i, data[i], recordBytes[i+4]); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestSheetPropertiesRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestSheetPropertiesRecord.java deleted file mode 100644 index ba1415e4d..000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestSheetPropertiesRecord.java +++ /dev/null @@ -1,71 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record.chart; - - -import org.apache.poi.hssf.record.RecordInputStream; -import org.apache.poi.hssf.record.TestcaseRecordInputStream; - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -/** - * Tests for {@link SheetPropertiesRecord} - * Test data taken directly from a real Excel file. - * - * @author Glen Stampoultzis (glens at apache.org) - */ -public final class TestSheetPropertiesRecord extends TestCase { - private static final byte[] data = { - (byte)0x0A,(byte)0x00, - (byte)0x00, - (byte)0x00, // not sure where that last byte comes from - }; - - public void testLoad() { - RecordInputStream in = TestcaseRecordInputStream.create(0x1044, data); - SheetPropertiesRecord record = new SheetPropertiesRecord(in); - if (in.remaining() == 1) { - throw new AssertionFailedError("Identified bug 44693c"); - } - assertEquals(0, in.remaining()); - assertEquals( 10, record.getFlags()); - assertEquals( false, record.isChartTypeManuallyFormatted() ); - assertEquals( true, record.isPlotVisibleOnly() ); - assertEquals( false, record.isDoNotSizeWithWindow() ); - assertEquals( true, record.isDefaultPlotDimensions() ); - assertEquals( false, record.isAutoPlotArea() ); - assertEquals( 0, record.getEmpty()); - - assertEquals( 8, record.getRecordSize() ); - } - - public void testStore() { - SheetPropertiesRecord record = new SheetPropertiesRecord(); - record.setChartTypeManuallyFormatted( false ); - record.setPlotVisibleOnly( true ); - record.setDoNotSizeWithWindow( false ); - record.setDefaultPlotDimensions( true ); - record.setAutoPlotArea( false ); - record.setEmpty( (byte)0 ); - - - byte [] recordBytes = record.serialize(); - TestcaseRecordInputStream.confirmRecordEncoding(SheetPropertiesRecord.sid, data, recordBytes); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestTextRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestTextRecord.java deleted file mode 100644 index 4214b0a37..000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestTextRecord.java +++ /dev/null @@ -1,117 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record.chart; - - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; - -import junit.framework.TestCase; - -/** - * Tests the serialization and deserialization of the TextRecord - * class works correctly. Test data taken directly from a real - * Excel file. - * - * @author Glen Stampoultzis (glens at apache.org) - */ -public final class TestTextRecord extends TestCase { - byte[] data = new byte[] { - (byte)0x02, // horiz align - (byte)0x02, // vert align - (byte)0x01,(byte)0x00, // display mode - (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00, // rgb color - (byte)0xD6,(byte)0xFF,(byte)0xFF,(byte)0xFF, // x - (byte)0xC4,(byte)0xFF,(byte)0xFF,(byte)0xFF, // y - (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00, // width - (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00, // height - (byte)0xB1,(byte)0x00, // options 1 - (byte)0x4D,(byte)0x00, // index of color value - (byte)0x50,(byte)0x2B, // options 2 -- strange upper bits supposed to be 0'd - (byte)0x00,(byte)0x00 // text rotation - }; - - public void testLoad() { - - TextRecord record = new TextRecord(TestcaseRecordInputStream.create(0x1025, data)); - assertEquals( TextRecord.HORIZONTAL_ALIGNMENT_CENTER, record.getHorizontalAlignment()); - assertEquals( TextRecord.VERTICAL_ALIGNMENT_CENTER, record.getVerticalAlignment()); - assertEquals( TextRecord.DISPLAY_MODE_TRANSPARENT, record.getDisplayMode()); - assertEquals( 0, record.getRgbColor()); - assertEquals( -42, record.getX()); - assertEquals( -60, record.getY()); - assertEquals( 0, record.getWidth()); - assertEquals( 0, record.getHeight()); - assertEquals( 177, record.getOptions1()); - assertEquals( true, record.isAutoColor() ); - assertEquals( false, record.isShowKey() ); - assertEquals( false, record.isShowValue() ); - assertEquals( false, record.isVertical() ); - assertEquals( true, record.isAutoGeneratedText() ); - assertEquals( true, record.isGenerated() ); - assertEquals( false, record.isAutoLabelDeleted() ); - assertEquals( true, record.isAutoBackground() ); - assertEquals( TextRecord.ROTATION_NONE, record.getRotation() ); - assertEquals( false, record.isShowCategoryLabelAsPercentage() ); - assertEquals( false, record.isShowValueAsPercentage() ); - assertEquals( false, record.isShowBubbleSizes() ); - assertEquals( false, record.isShowLabel() ); - assertEquals( 77, record.getIndexOfColorValue()); - assertEquals( 11088, record.getOptions2()); - assertEquals( 0, record.getDataLabelPlacement() ); - assertEquals( 0, record.getTextRotation()); - - - assertEquals( 36, record.getRecordSize() ); - } - - public void testStore() - { - TextRecord record = new TextRecord(); - record.setHorizontalAlignment( TextRecord.HORIZONTAL_ALIGNMENT_CENTER ); - record.setVerticalAlignment( TextRecord.VERTICAL_ALIGNMENT_CENTER ); - record.setDisplayMode( TextRecord.DISPLAY_MODE_TRANSPARENT ); - record.setRgbColor( 0 ); - record.setX( -42 ); - record.setY( -60 ); - record.setWidth( 0 ); - record.setHeight( 0 ); - record.setAutoColor( true ); - record.setShowKey( false ); - record.setShowValue( false ); - record.setVertical( false ); - record.setAutoGeneratedText( true ); - record.setGenerated( true ); - record.setAutoLabelDeleted( false ); - record.setAutoBackground( true ); - record.setRotation( TextRecord.ROTATION_NONE ); - record.setShowCategoryLabelAsPercentage( false ); - record.setShowValueAsPercentage( false ); - record.setShowBubbleSizes( false ); - record.setShowLabel( false ); - record.setIndexOfColorValue( (short)77 ); - record.setOptions2( (short)0x2b50 ); -// record.setDataLabelPlacement( (short)0x2b50 ); - record.setTextRotation( (short)0 ); - - - byte [] recordBytes = record.serialize(); - assertEquals(recordBytes.length - 4, data.length); - for (int i = 0; i < data.length; i++) - assertEquals("At offset " + i, data[i], recordBytes[i+4]); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestTickRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestTickRecord.java deleted file mode 100644 index 28d13178f..000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestTickRecord.java +++ /dev/null @@ -1,87 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record.chart; - - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; - -import junit.framework.TestCase; - -/** - * Tests the serialization and deserialization of the TickRecord - * class works correctly. Test data taken directly from a real - * Excel file. - * - * @author Andrew C. Oliver(acoliver at apache.org) - */ -public final class TestTickRecord extends TestCase { - private static final byte[] data = { - (byte)0x02, (byte)0x00, (byte)0x03, (byte)0x01, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, - (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x23, (byte)0x00, - (byte)0x4D, (byte)0x00, (byte)0x00, (byte)0x00 - }; - - public void testLoad() { - TickRecord record = new TickRecord(TestcaseRecordInputStream.create(0x101e, data)); - assertEquals( (byte)2, record.getMajorTickType()); - assertEquals( (byte)0, record.getMinorTickType()); - assertEquals( (byte)3, record.getLabelPosition()); - assertEquals( (short)1, record.getBackground()); - assertEquals( 0, record.getLabelColorRgb()); - assertEquals( (short)0, record.getZero1()); - assertEquals( (short)0, record.getZero2()); - assertEquals( (short)35, record.getOptions()); - assertEquals( true, record.isAutoTextColor() ); - assertEquals( true, record.isAutoTextBackground() ); - assertEquals( (short)0x0, record.getRotation() ); - assertEquals( true, record.isAutorotate() ); - assertEquals( (short)77, record.getTickColor()); - assertEquals( (short)0x0, record.getZero3()); - - - assertEquals( 34, record.getRecordSize() ); - } - - public void testStore() { - TickRecord record = new TickRecord(); - record.setMajorTickType( (byte)2 ); - record.setMinorTickType( (byte)0 ); - record.setLabelPosition( (byte)3 ); - record.setBackground( (byte)1 ); - record.setLabelColorRgb( 0 ); - record.setZero1( (short)0 ); - record.setZero2( (short)0 ); - record.setOptions( (short)35 ); - record.setAutoTextColor( true ); - record.setAutoTextBackground( true ); - record.setRotation( (short)0 ); - record.setAutorotate( true ); - record.setTickColor( (short)77 ); - record.setZero3( (short)0 ); - - - byte [] recordBytes = record.serialize(); - assertEquals(recordBytes.length - 4, data.length); - for (int i = 0; i < data.length; i++) - assertEquals("At offset " + i, data[i], recordBytes[i+4]); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestUnitsRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestUnitsRecord.java deleted file mode 100644 index 4c142bdb0..000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestUnitsRecord.java +++ /dev/null @@ -1,57 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record.chart; - - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; - -import junit.framework.TestCase; - -/** - * Tests the serialization and deserialization of the UnitsRecord - * class works correctly. Test data taken directly from a real - * Excel file. - * - - * @author Glen Stampoultzis (glens at apache.org) - */ -public final class TestUnitsRecord extends TestCase { - byte[] data = new byte[] { - (byte)0x00, (byte)0x00 - }; - - public void testLoad() { - - UnitsRecord record = new UnitsRecord(TestcaseRecordInputStream.create(0x1001, data)); - assertEquals( 0, record.getUnits()); - - assertEquals( 6, record.getRecordSize() ); - } - - public void testStore() - { - UnitsRecord record = new UnitsRecord(); - record.setUnits( (short)0 ); - - - byte [] recordBytes = record.serialize(); - assertEquals(recordBytes.length - 4, data.length); - for (int i = 0; i < data.length; i++) - assertEquals("At offset " + i, data[i], recordBytes[i+4]); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/chart/TestValueRangeRecord.java b/src/testcases/org/apache/poi/hssf/record/chart/TestValueRangeRecord.java deleted file mode 100644 index d2a08df4a..000000000 --- a/src/testcases/org/apache/poi/hssf/record/chart/TestValueRangeRecord.java +++ /dev/null @@ -1,88 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record.chart; - - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; - -import junit.framework.TestCase; - -/** - * Tests the serialization and deserialization of the ValueRangeRecord - * class works correctly. Test data taken directly from a real - * Excel file. - * - * - * @author Glen Stampoultzis (glens at apache.org) - */ -public final class TestValueRangeRecord extends TestCase { - byte[] data = new byte[] { - (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00, // min axis value - (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00, // max axis value - (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00, // major increment - (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00, // minor increment - (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00, // cross over - (byte)0x1F,(byte)0x01 // options - }; - - public void testLoad() { - - ValueRangeRecord record = new ValueRangeRecord(TestcaseRecordInputStream.create(0x101f, data)); - assertEquals( 0.0, record.getMinimumAxisValue(), 0.001); - assertEquals( 0.0, record.getMaximumAxisValue(), 0.001); - assertEquals( 0.0, record.getMajorIncrement(), 0.001); - assertEquals( 0.0, record.getMinorIncrement(), 0.001); - assertEquals( 0.0, record.getCategoryAxisCross(), 0.001); - assertEquals( 0x011f, record.getOptions()); - assertEquals( true, record.isAutomaticMinimum() ); - assertEquals( true, record.isAutomaticMaximum() ); - assertEquals( true, record.isAutomaticMajor() ); - assertEquals( true, record.isAutomaticMinor() ); - assertEquals( true, record.isAutomaticCategoryCrossing() ); - assertEquals( false, record.isLogarithmicScale() ); - assertEquals( false, record.isValuesInReverse() ); - assertEquals( false, record.isCrossCategoryAxisAtMaximum() ); - assertEquals( true, record.isReserved() ); - - assertEquals( 42+4, record.getRecordSize() ); - } - - public void testStore() - { - ValueRangeRecord record = new ValueRangeRecord(); - record.setMinimumAxisValue( 0 ); - record.setMaximumAxisValue( 0 ); - record.setMajorIncrement( 0 ); - record.setMinorIncrement( 0 ); - record.setCategoryAxisCross( 0 ); - record.setAutomaticMinimum( true ); - record.setAutomaticMaximum( true ); - record.setAutomaticMajor( true ); - record.setAutomaticMinor( true ); - record.setAutomaticCategoryCrossing( true ); - record.setLogarithmicScale( false ); - record.setValuesInReverse( false ); - record.setCrossCategoryAxisAtMaximum( false ); - record.setReserved( true ); - - byte [] recordBytes = record.serialize(); - assertEquals(recordBytes.length - 4, data.length); - for (int i = 0; i < data.length; i++) - assertEquals("At offset " + i, data[i], recordBytes[i+4]); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/common/TestUnicodeString.java b/src/testcases/org/apache/poi/hssf/record/common/TestUnicodeString.java deleted file mode 100644 index c1c585db4..000000000 --- a/src/testcases/org/apache/poi/hssf/record/common/TestUnicodeString.java +++ /dev/null @@ -1,369 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record.common; - -import static org.junit.Assert.assertEquals; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; - -import org.apache.poi.hssf.record.ContinueRecord; -import org.apache.poi.hssf.record.RecordInputStream; -import org.apache.poi.hssf.record.SSTRecord; -import org.apache.poi.hssf.record.common.UnicodeString.ExtRst; -import org.apache.poi.hssf.record.common.UnicodeString.FormatRun; -import org.apache.poi.hssf.record.cont.ContinuableRecordOutput; -import org.apache.poi.util.LittleEndianByteArrayInputStream; -import org.apache.poi.util.LittleEndianByteArrayOutputStream; -import org.apache.poi.util.LittleEndianConsts; -import org.apache.poi.util.LittleEndianInput; -import org.apache.poi.util.LittleEndianInputStream; -import org.apache.poi.util.LittleEndianOutputStream; -import org.apache.poi.util.StringUtil; -import org.junit.Test; - -/** - * Tests that {@link UnicodeString} record size calculates correctly. The record size - * is used when serializing {@link SSTRecord}s. - * - * @author Jason Height (jheight at apache.org) - */ -public final class TestUnicodeString { - private static final int MAX_DATA_SIZE = RecordInputStream.MAX_RECORD_DATA_SIZE; - - /** a 4 character string requiring 16 bit encoding */ - private static final String STR_16_BIT = "A\u591A\u8A00\u8A9E"; - - private static void confirmSize(int expectedSize, UnicodeString s) { - confirmSize(expectedSize, s, 0); - } - /** - * Note - a value of zero for amountUsedInCurrentRecord would only ever occur just - * after a {@link ContinueRecord} had been started. In the initial {@link SSTRecord} this - * value starts at 8 (for the first {@link UnicodeString} written). In general, it can be - * any value between 0 and {@link #MAX_DATA_SIZE} - */ - private static void confirmSize(int expectedSize, UnicodeString s, int amountUsedInCurrentRecord) { - ContinuableRecordOutput out = ContinuableRecordOutput.createForCountingOnly(); - out.writeContinue(); - for(int i=amountUsedInCurrentRecord; i>0; i--) { - out.writeByte(0); - } - int size0 = out.getTotalSize(); - s.serialize(out); - int size1 = out.getTotalSize(); - int actualSize = size1-size0; - assertEquals(expectedSize, actualSize); - } - - @Test - public void smallStringSize() { - //Test a basic string - UnicodeString s = makeUnicodeString("Test"); - confirmSize(7, s); - - //Test a small string that is uncompressed - s = makeUnicodeString(STR_16_BIT); - s.setOptionFlags((byte)0x01); - confirmSize(11, s); - - //Test a compressed small string that has rich text formatting - s.setString("Test"); - s.setOptionFlags((byte)0x8); - UnicodeString.FormatRun r = new UnicodeString.FormatRun((short)0,(short)1); - s.addFormatRun(r); - UnicodeString.FormatRun r2 = new UnicodeString.FormatRun((short)2,(short)2); - s.addFormatRun(r2); - confirmSize(17, s); - - //Test a uncompressed small string that has rich text formatting - s.setString(STR_16_BIT); - s.setOptionFlags((byte)0x9); - confirmSize(21, s); - - //Test a compressed small string that has rich text and extended text - s.setString("Test"); - s.setOptionFlags((byte)0xC); - confirmSize(17, s); - - // Extended phonetics data - // Minimum size is 14 - // Also adds 4 bytes to hold the length - s.setExtendedRst( - new ExtRst() - ); - confirmSize(35, s); - - //Test a uncompressed small string that has rich text and extended text - s.setString(STR_16_BIT); - s.setOptionFlags((byte)0xD); - confirmSize(39, s); - - s.setExtendedRst(null); - confirmSize(21, s); - } - - @Test - public void perfectStringSize() { - //Test a basic string - UnicodeString s = makeUnicodeString(MAX_DATA_SIZE-2-1); - confirmSize(MAX_DATA_SIZE, s); - - //Test an uncompressed string - //Note that we can only ever get to a maximim size of 8227 since an uncompressed - //string is writing double bytes. - s = makeUnicodeString((MAX_DATA_SIZE-2-1)/2, true); - s.setOptionFlags((byte)0x1); - confirmSize(MAX_DATA_SIZE-1, s); - } - - @Test - public void perfectRichStringSize() { - //Test a rich text string - UnicodeString s = makeUnicodeString(MAX_DATA_SIZE-2-1-8-2); - s.addFormatRun(new UnicodeString.FormatRun((short)1,(short)0)); - s.addFormatRun(new UnicodeString.FormatRun((short)2,(short)1)); - s.setOptionFlags((byte)0x8); - confirmSize(MAX_DATA_SIZE, s); - - //Test an uncompressed rich text string - //Note that we can only ever get to a maximum size of 8227 since an uncompressed - //string is writing double bytes. - s = makeUnicodeString((MAX_DATA_SIZE-2-1-8-2)/2, true); - s.addFormatRun(new UnicodeString.FormatRun((short)1,(short)0)); - s.addFormatRun(new UnicodeString.FormatRun((short)2,(short)1)); - s.setOptionFlags((byte)0x9); - confirmSize(MAX_DATA_SIZE-1, s); - } - - @Test - public void continuedStringSize() { - //Test a basic string - UnicodeString s = makeUnicodeString(MAX_DATA_SIZE-2-1+20); - confirmSize(MAX_DATA_SIZE+4+1+20, s); - } - - /** Tests that a string size calculation that fits neatly in two records, the second being a continue*/ - @Test - public void perfectContinuedStringSize() { - //Test a basic string - int strSize = MAX_DATA_SIZE*2; - //String overhead - strSize -= 3; - //Continue Record overhead - strSize -= 4; - //Continue Record additional byte overhead - strSize -= 1; - UnicodeString s = makeUnicodeString(strSize); - confirmSize(MAX_DATA_SIZE*2, s); - } - - @Test - public void formatRun() throws Exception { - FormatRun fr = new FormatRun((short)4, (short)0x15c); - assertEquals(4, fr.getCharacterPos()); - assertEquals(0x15c, fr.getFontIndex()); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - LittleEndianOutputStream out = new LittleEndianOutputStream(baos); - - fr.serialize(out); - - byte[] b = baos.toByteArray(); - assertEquals(4, b.length); - assertEquals(4, b[0]); - assertEquals(0, b[1]); - assertEquals(0x5c, b[2]); - assertEquals(0x01, b[3]); - - LittleEndianInputStream inp = new LittleEndianInputStream( - new ByteArrayInputStream(b) - ); - fr = new FormatRun(inp); - assertEquals(4, fr.getCharacterPos()); - assertEquals(0x15c, fr.getFontIndex()); - } - - @Test - public void extRstFromEmpty() throws Exception { - ExtRst ext = new ExtRst(); - - assertEquals(0, ext.getNumberOfRuns()); - assertEquals(0, ext.getFormattingFontIndex()); - assertEquals(0, ext.getFormattingOptions()); - assertEquals("", ext.getPhoneticText()); - assertEquals(0, ext.getPhRuns().length); - assertEquals(10, ext.getDataSize()); // Excludes 4 byte header - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - LittleEndianOutputStream out = new LittleEndianOutputStream(baos); - ContinuableRecordOutput cout = new ContinuableRecordOutput(out, 0xffff); - - ext.serialize(cout); - cout.writeContinue(); - - byte[] b = baos.toByteArray(); - assertEquals(20, b.length); - - // First 4 bytes from the outputstream - assertEquals(-1, b[0]); - assertEquals(-1, b[1]); - assertEquals(14, b[2]); - assertEquals(00, b[3]); - - // Reserved - assertEquals(1, b[4]); - assertEquals(0, b[5]); - // Data size - assertEquals(10, b[6]); - assertEquals(00, b[7]); - // Font*2 - assertEquals(0, b[8]); - assertEquals(0, b[9]); - assertEquals(0, b[10]); - assertEquals(0, b[11]); - // 0 Runs - assertEquals(0, b[12]); - assertEquals(0, b[13]); - // Size=0, *2 - assertEquals(0, b[14]); - assertEquals(0, b[15]); - assertEquals(0, b[16]); - assertEquals(0, b[17]); - - // Last 2 bytes from the outputstream - assertEquals(ContinueRecord.sid, b[18]); - assertEquals(0, b[19]); - - - // Load in again and re-test - byte[] data = new byte[14]; - System.arraycopy(b, 4, data, 0, data.length); - LittleEndianInputStream inp = new LittleEndianInputStream( - new ByteArrayInputStream(data) - ); - ext = new ExtRst(inp, data.length); - - assertEquals(0, ext.getNumberOfRuns()); - assertEquals(0, ext.getFormattingFontIndex()); - assertEquals(0, ext.getFormattingOptions()); - assertEquals("", ext.getPhoneticText()); - assertEquals(0, ext.getPhRuns().length); - } - - @Test - public void extRstFromData() throws Exception { - byte[] data = new byte[] { - 01, 00, 0x0C, 00, - 00, 00, 0x37, 00, - 00, 00, - 00, 00, 00, 00, - 00, 00 // Cruft at the end, as found from real files - }; - assertEquals(16, data.length); - - LittleEndianInputStream inp = new LittleEndianInputStream( - new ByteArrayInputStream(data) - ); - ExtRst ext = new ExtRst(inp, data.length); - assertEquals(0x0c, ext.getDataSize()); // Excludes 4 byte header - - assertEquals(0, ext.getNumberOfRuns()); - assertEquals(0x37, ext.getFormattingOptions()); - assertEquals(0, ext.getFormattingFontIndex()); - assertEquals("", ext.getPhoneticText()); - assertEquals(0, ext.getPhRuns().length); - } - - @Test - public void corruptExtRstDetection() throws Exception { - byte[] data = new byte[] { - 0x79, 0x79, 0x11, 0x11, - 0x22, 0x22, 0x33, 0x33, - }; - assertEquals(8, data.length); - - LittleEndianInputStream inp = new LittleEndianInputStream( - new ByteArrayInputStream(data) - ); - ExtRst ext = new ExtRst(inp, data.length); - - // Will be empty - assertEquals(ext, new ExtRst()); - - // If written, will be the usual size - assertEquals(10, ext.getDataSize()); // Excludes 4 byte header - - // Is empty - assertEquals(0, ext.getNumberOfRuns()); - assertEquals(0, ext.getFormattingOptions()); - assertEquals(0, ext.getFormattingFontIndex()); - assertEquals("", ext.getPhoneticText()); - assertEquals(0, ext.getPhRuns().length); - } - - @Test - public void extRstEqualsAndHashCode() { - byte buf[] = new byte[200]; - LittleEndianByteArrayOutputStream bos = new LittleEndianByteArrayOutputStream(buf, 0); - String str = "\u1d02\u1d12\u1d22"; - bos.writeShort(1); - bos.writeShort(5*LittleEndianConsts.SHORT_SIZE+str.length()*2+3*LittleEndianConsts.SHORT_SIZE+2); // data size - bos.writeShort(0x4711); - bos.writeShort(0x0815); - bos.writeShort(1); - bos.writeShort(str.length()); - bos.writeShort(str.length()); - StringUtil.putUnicodeLE(str, bos); - bos.writeShort(1); - bos.writeShort(1); - bos.writeShort(3); - bos.writeShort(42); - - LittleEndianInput in = new LittleEndianByteArrayInputStream(buf, 0, bos.getWriteIndex()); - UnicodeString.ExtRst extRst1 = new UnicodeString.ExtRst(in, bos.getWriteIndex()); - in = new LittleEndianByteArrayInputStream(buf, 0, bos.getWriteIndex()); - UnicodeString.ExtRst extRst2 = new UnicodeString.ExtRst(in, bos.getWriteIndex()); - - assertEquals(extRst1, extRst2); - assertEquals(extRst1.hashCode(), extRst2.hashCode()); - } - - private static UnicodeString makeUnicodeString(String s) { - UnicodeString st = new UnicodeString(s); - st.setOptionFlags((byte)0); - return st; - } - - private static UnicodeString makeUnicodeString(int numChars) { - return makeUnicodeString(numChars, false); - } - /** - * @param is16Bit if true the created string will have characters > 0x00FF - * @return a string of the specified number of characters - */ - private static UnicodeString makeUnicodeString(int numChars, boolean is16Bit) { - StringBuffer b = new StringBuffer(numChars); - int charBase = is16Bit ? 0x8A00 : 'A'; - for (int i=0;iorg.apache.poi.hssf.record.pivot. - * - * @author Josh Micich - */ -public final class AllPivotRecordTests { - - public static Test suite() { - TestSuite result = new TestSuite(AllPivotRecordTests.class.getName()); - - result.addTestSuite(TestExtendedPivotTableViewFieldsRecord.class); - result.addTestSuite(TestPageItemRecord.class); - result.addTestSuite(TestViewFieldsRecord.class); - return result; - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/pivot/TestExtendedPivotTableViewFieldsRecord.java b/src/testcases/org/apache/poi/hssf/record/pivot/TestExtendedPivotTableViewFieldsRecord.java deleted file mode 100644 index 945528dd2..000000000 --- a/src/testcases/org/apache/poi/hssf/record/pivot/TestExtendedPivotTableViewFieldsRecord.java +++ /dev/null @@ -1,76 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record.pivot; - -import org.apache.poi.hssf.record.RecordFormatException; -import org.apache.poi.hssf.record.RecordInputStream; -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.apache.poi.hssf.record.pivottable.ExtendedPivotTableViewFieldsRecord; -import org.apache.poi.util.HexRead; - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -/** - * Tests for {@link ExtendedPivotTableViewFieldsRecord} - * - * @author Josh Micich - */ -public final class TestExtendedPivotTableViewFieldsRecord extends TestCase { - - public void testSubNameNotPresent_bug46693() { - // This data came from attachment 23347 of bug 46693 at offset 0xAA43 - byte[] data = HexRead.readFromString( - "00 01 14 00" + // BIFF header - "1E 14 00 0A FF FF FF FF 00 00 FF FF 00 00 00 00 00 00 00 00"); - RecordInputStream in = TestcaseRecordInputStream.create(data); - ExtendedPivotTableViewFieldsRecord rec; - try { - rec = new ExtendedPivotTableViewFieldsRecord(in); - } catch (RecordFormatException e) { - if (e.getMessage().equals("Expected to find a ContinueRecord in order to read remaining 65535 of 65535 chars")) { - throw new AssertionFailedError("Identified bug 46693a"); - } - throw e; - } - - assertEquals(data.length, rec.getRecordSize()); - } - - public void testOlderFormat_bug46918() { - // There are 10 SXVDEX records in the file (not uploaded) that originated bugzilla 46918 - // They all had the following hex encoding: - byte data[] = HexRead.readFromString("00 01 0A 00 1E 14 00 0A FF FF FF FF 00 00"); - - RecordInputStream in = TestcaseRecordInputStream.create(data); - ExtendedPivotTableViewFieldsRecord rec; - try { - rec = new ExtendedPivotTableViewFieldsRecord(in); - } catch (RecordFormatException e) { - if (e.getMessage().equals("Not enough data (0) to read requested (2) bytes")) { - throw new AssertionFailedError("Identified bug 46918"); - } - throw e; - } - - byte expReserData[] = HexRead.readFromString("1E 14 00 0A FF FF FF FF 00 00" + - "FF FF 00 00 00 00 00 00 00 00"); - - TestcaseRecordInputStream.confirmRecordEncoding(ExtendedPivotTableViewFieldsRecord.sid, expReserData, rec.serialize()); - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/pivot/TestPageItemRecord.java b/src/testcases/org/apache/poi/hssf/record/pivot/TestPageItemRecord.java deleted file mode 100644 index 7cf3b4929..000000000 --- a/src/testcases/org/apache/poi/hssf/record/pivot/TestPageItemRecord.java +++ /dev/null @@ -1,63 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record.pivot; - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -import org.apache.poi.hssf.record.RecordInputStream; -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.apache.poi.hssf.record.pivottable.PageItemRecord; -import org.apache.poi.util.HexRead; - -/** - * Tests for {@link PageItemRecord} - * - * @author Josh Micich - */ -public final class TestPageItemRecord extends TestCase { - - public void testMoreThanOneInfoItem_bug46917() { - byte[] data = HexRead.readFromString("01 02 03 04 05 06 07 08 09 0A 0B 0C"); - RecordInputStream in = TestcaseRecordInputStream.create(PageItemRecord.sid, data); - PageItemRecord rec = new PageItemRecord(in); - if (in.remaining() == 6) { - throw new AssertionFailedError("Identified bug 46917"); - } - assertEquals(0, in.remaining()); - - assertEquals(4+data.length, rec.getRecordSize()); - } - - public void testSerialize() { - confirmSerialize("01 02 03 04 05 06"); - confirmSerialize("01 02 03 04 05 06 07 08 09 0A 0B 0C"); - confirmSerialize("01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 11 12"); - } - - private static PageItemRecord confirmSerialize(String hexDump) { - byte[] data = HexRead.readFromString(hexDump); - RecordInputStream in = TestcaseRecordInputStream.create(PageItemRecord.sid, data); - PageItemRecord rec = new PageItemRecord(in); - assertEquals(0, in.remaining()); - assertEquals(4+data.length, rec.getRecordSize()); - byte[] data2 = rec.serialize(); - TestcaseRecordInputStream.confirmRecordEncoding(PageItemRecord.sid, data, data2); - return rec; - } -} diff --git a/src/testcases/org/apache/poi/hssf/record/pivot/TestViewFieldsRecord.java b/src/testcases/org/apache/poi/hssf/record/pivot/TestViewFieldsRecord.java deleted file mode 100644 index 448a2acb3..000000000 --- a/src/testcases/org/apache/poi/hssf/record/pivot/TestViewFieldsRecord.java +++ /dev/null @@ -1,64 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.record.pivot; - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -import org.apache.poi.hssf.record.RecordInputStream; -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.apache.poi.hssf.record.pivottable.ViewFieldsRecord; -import org.apache.poi.util.HexRead; - -/** - * Tests for {@link ViewFieldsRecord} - * - * @author Josh Micich - */ -public final class TestViewFieldsRecord extends TestCase { - - public void testUnicodeFlag_bug46693() { - byte[] data = HexRead.readFromString("01 00 01 00 01 00 04 00 05 00 00 6D 61 72 63 6F"); - RecordInputStream in = TestcaseRecordInputStream.create(ViewFieldsRecord.sid, data); - ViewFieldsRecord rec = new ViewFieldsRecord(in); - if (in.remaining() == 1) { - throw new AssertionFailedError("Identified bug 46693b"); - } - assertEquals(0, in.remaining()); - assertEquals(4+data.length, rec.getRecordSize()); - } - - public void testSerialize() { - // This hex data was produced by changing the 'Custom Name' property, - // available under 'Field Settings' from the 'PivotTable Field List' (Excel 2007) - confirmSerialize("00 00 01 00 01 00 00 00 FF FF"); - confirmSerialize("01 00 01 00 01 00 04 00 05 00 00 6D 61 72 63 6F"); - confirmSerialize("01 00 01 00 01 00 04 00 0A 00 01 48 00 69 00 73 00 74 00 6F 00 72 00 79 00 2D 00 82 69 81 89"); - } - - private static ViewFieldsRecord confirmSerialize(String hexDump) { - byte[] data = HexRead.readFromString(hexDump); - RecordInputStream in = TestcaseRecordInputStream.create(ViewFieldsRecord.sid, data); - ViewFieldsRecord rec = new ViewFieldsRecord(in); - assertEquals(0, in.remaining()); - assertEquals(4+data.length, rec.getRecordSize()); - byte[] data2 = rec.serialize(); - TestcaseRecordInputStream.confirmRecordEncoding(ViewFieldsRecord.sid, data, data2); - return rec; - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/AllUserModelTests.java b/src/testcases/org/apache/poi/hssf/usermodel/AllUserModelTests.java deleted file mode 100644 index bcbddf055..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/AllUserModelTests.java +++ /dev/null @@ -1,76 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -/** - * Collects all tests for the org.apache.poi.hssf.usermodel package. - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestBug42464.class, - TestBugs.class, - TestCellStyle.class, - TestCloneSheet.class, - TestDataValidation.class, - TestEscherGraphics.class, - TestEscherGraphics2d.class, - TestFontDetails.class, - TestFormulaEvaluatorBugs.class, - TestFormulaEvaluatorDocs.class, - TestFormulas.class, - TestHSSFCell.class, - TestHSSFClientAnchor.class, - //TestHSSFComment.class, //converted to junit4 - TestHSSFConditionalFormatting.class, - TestHSSFDataFormat.class, - TestHSSFDataFormatter.class, - TestHSSFDateUtil.class, - TestHSSFFont.class, - TestHSSFFormulaEvaluator.class, - TestHSSFHeaderFooter.class, - TestHSSFHyperlink.class, - TestHSSFName.class, - TestHSSFOptimiser.class, - TestHSSFPalette.class, - TestHSSFPatriarch.class, - TestHSSFPicture.class, - TestHSSFPictureData.class, - TestHSSFRichTextString.class, - TestHSSFRow.class, - TestHSSFSheet.class, - TestHSSFSheetShiftRows.class, - TestHSSFSheetUpdateArrayFormulas.class, - TestHSSFTextbox.class, - TestHSSFWorkbook.class, - TestOLE2Embeding.class, - TestPOIFSProperties.class, - TestReadWriteChart.class, - TestRowStyle.class, - TestSanityChecker.class, - TestSheetHiding.class, - /* deliberately avoiding this one - TestUnfixedBugs.class,*/ - TestUnicodeWorkbook.class, - TestNonStandardWorkbookStreamNames.class, - TestWorkbook.class -}) -public class AllUserModelTests { -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/FormulaExtractor.java b/src/testcases/org/apache/poi/hssf/usermodel/FormulaExtractor.java deleted file mode 100644 index c44b3c0c7..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/FormulaExtractor.java +++ /dev/null @@ -1,43 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import org.apache.poi.hssf.record.CellValueRecordInterface; -import org.apache.poi.hssf.record.aggregates.FormulaRecordAggregate; -import org.apache.poi.ss.formula.ptg.Ptg; - -/** - * Test utility class to get Ptg arrays out of formula cells - * - * @author Josh Micich - */ -public final class FormulaExtractor { - - private FormulaExtractor() { - // no instances of this class - } - - public static Ptg[] getPtgs(HSSFCell cell) { - CellValueRecordInterface vr = cell.getCellValueRecord(); - if (!(vr instanceof FormulaRecordAggregate)) { - throw new IllegalArgumentException("Not a formula cell"); - } - FormulaRecordAggregate fra = (FormulaRecordAggregate) vr; - return fra.getFormulaRecord().getParsedExpression(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/HSSFEvaluationTestHelper.java b/src/testcases/org/apache/poi/hssf/usermodel/HSSFEvaluationTestHelper.java deleted file mode 100644 index 96196c146..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/HSSFEvaluationTestHelper.java +++ /dev/null @@ -1,33 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import org.apache.poi.ss.formula.EvaluationCell; - -/** - * Raises visibility of some internal functionality for test purposes - * - * @author Josh Micich - */ -public final class HSSFEvaluationTestHelper { - - public static EvaluationCell wrapCell(HSSFCell cell) { - return new HSSFEvaluationCell(cell); - } - -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/HSSFTestHelper.java b/src/testcases/org/apache/poi/hssf/usermodel/HSSFTestHelper.java deleted file mode 100644 index 1016f6d25..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/HSSFTestHelper.java +++ /dev/null @@ -1,106 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; -import org.apache.poi.ddf.*; -import org.apache.poi.hssf.model.DrawingManager2; -import org.apache.poi.hssf.model.InternalSheet; -import org.apache.poi.hssf.model.InternalWorkbook; -import org.apache.poi.hssf.record.EscherAggregate; -import org.apache.poi.hssf.record.ObjRecord; -import org.apache.poi.hssf.record.TextObjectRecord; - -/** - * Helper class for HSSF tests that aren't within the - * HSSF UserModel package, but need to do internal - * UserModel things. - */ -public class HSSFTestHelper { - - public static class MockDrawingManager extends DrawingManager2 { - - public MockDrawingManager (){ - super(null); - } - - @Override - public int allocateShapeId(short drawingGroupId) { - return 1025; //Mock value - } - - @Override - public int allocateShapeId(short drawingGroupId, EscherDgRecord dg) { - return 1025; - } - - @Override - public EscherDgRecord createDgRecord() - { - EscherDgRecord dg = new EscherDgRecord(); - dg.setRecordId( EscherDgRecord.RECORD_ID ); - dg.setOptions( (short) (16) ); - dg.setNumShapes( 1 ); - dg.setLastMSOSPID( 1024 ); - return dg; - } - } - /** - * Lets non UserModel tests at the low level Workbook - */ - public static InternalWorkbook getWorkbookForTest(HSSFWorkbook wb) { - return wb.getWorkbook(); - } - public static InternalSheet getSheetForTest(HSSFSheet sheet) { - return sheet.getSheet(); - } - - public static HSSFPatriarch createTestPatriarch(HSSFSheet sheet, EscherAggregate agg){ - return new HSSFPatriarch(sheet, agg); - } - - public static EscherAggregate getEscherAggregate(HSSFPatriarch patriarch){ - return patriarch.getBoundAggregate(); - } - - public static int allocateNewShapeId(HSSFPatriarch patriarch){ - return patriarch.newShapeId(); - } - - public static EscherOptRecord getOptRecord(HSSFShape shape){ - return shape.getOptRecord(); - } - - public static void setShapeId(HSSFShape shape, int id){ - shape.setShapeId(id); - } - - public static EscherContainerRecord getEscherContainer(HSSFShape shape){ - return shape.getEscherContainer(); - } - - public static TextObjectRecord getTextObjRecord(HSSFSimpleShape shape){ - return shape.getTextObjectRecord(); - } - - public static ObjRecord getObjRecord(HSSFShape shape){ - return shape.getObjRecord(); - } - - public static EscherRecord getEscherAnchor(HSSFAnchor anchor){ - return anchor.getEscherAnchor(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/RecordInspector.java b/src/testcases/org/apache/poi/hssf/usermodel/RecordInspector.java deleted file mode 100644 index 1784d95aa..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/RecordInspector.java +++ /dev/null @@ -1,68 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.hssf.record.Record; -import org.apache.poi.hssf.record.aggregates.RecordAggregate.RecordVisitor; - -/** - * Test utility class to get {@link Record}s out of HSSF objects - * - * @author Josh Micich - */ -public final class RecordInspector { - - private RecordInspector() { - // no instances of this class - } - - public static final class RecordCollector implements RecordVisitor { - - private final List _list; - - public RecordCollector() { - _list = new ArrayList(128); - } - - @Override - public void visitRecord(Record r) { - _list.add(r); - } - - public Record[] getRecords() { - Record[] result = new Record[_list.size()]; - _list.toArray(result); - return result; - } - } - - /** - * @param streamOffset start position for serialization. This affects values in some - * records such as INDEX, but most callers will be OK to pass zero. - * @return the {@link Record}s (in order) which will be output when the - * specified sheet is serialized - */ - public static Record[] getRecords(HSSFSheet hSheet, int streamOffset) { - RecordCollector rc = new RecordCollector(); - hSheet.getSheet().visitContainedRecords(rc, streamOffset); - return rc.getRecords(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/SanityChecker.java b/src/testcases/org/apache/poi/hssf/usermodel/SanityChecker.java deleted file mode 100644 index 5f90b7285..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/SanityChecker.java +++ /dev/null @@ -1,375 +0,0 @@ - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - - -package org.apache.poi.hssf.usermodel; - -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.util.List; - -import org.apache.poi.hssf.model.InternalSheet; -import org.apache.poi.hssf.model.InternalWorkbook; -import org.apache.poi.hssf.record.BOFRecord; -import org.apache.poi.hssf.record.BackupRecord; -import org.apache.poi.hssf.record.BookBoolRecord; -import org.apache.poi.hssf.record.BoundSheetRecord; -import org.apache.poi.hssf.record.CalcModeRecord; -import org.apache.poi.hssf.record.CodepageRecord; -import org.apache.poi.hssf.record.CountryRecord; -import org.apache.poi.hssf.record.DSFRecord; -import org.apache.poi.hssf.record.DateWindow1904Record; -import org.apache.poi.hssf.record.DefaultColWidthRecord; -import org.apache.poi.hssf.record.DefaultRowHeightRecord; -import org.apache.poi.hssf.record.DeltaRecord; -import org.apache.poi.hssf.record.DimensionsRecord; -import org.apache.poi.hssf.record.EOFRecord; -import org.apache.poi.hssf.record.ExtSSTRecord; -import org.apache.poi.hssf.record.ExtendedFormatRecord; -import org.apache.poi.hssf.record.ExternSheetRecord; -import org.apache.poi.hssf.record.FnGroupCountRecord; -import org.apache.poi.hssf.record.FontRecord; -import org.apache.poi.hssf.record.FormatRecord; -import org.apache.poi.hssf.record.GridsetRecord; -import org.apache.poi.hssf.record.GutsRecord; -import org.apache.poi.hssf.record.HideObjRecord; -import org.apache.poi.hssf.record.InterfaceEndRecord; -import org.apache.poi.hssf.record.InterfaceHdrRecord; -import org.apache.poi.hssf.record.IterationRecord; -import org.apache.poi.hssf.record.MMSRecord; -import org.apache.poi.hssf.record.NameRecord; -import org.apache.poi.hssf.record.PasswordRev4Record; -import org.apache.poi.hssf.record.PrecisionRecord; -import org.apache.poi.hssf.record.PrintGridlinesRecord; -import org.apache.poi.hssf.record.PrintHeadersRecord; -import org.apache.poi.hssf.record.ProtectRecord; -import org.apache.poi.hssf.record.Record; -import org.apache.poi.hssf.record.RecordBase; -import org.apache.poi.hssf.record.RefModeRecord; -import org.apache.poi.hssf.record.RefreshAllRecord; -import org.apache.poi.hssf.record.SSTRecord; -import org.apache.poi.hssf.record.SaveRecalcRecord; -import org.apache.poi.hssf.record.SelectionRecord; -import org.apache.poi.hssf.record.StyleRecord; -import org.apache.poi.hssf.record.SupBookRecord; -import org.apache.poi.hssf.record.TabIdRecord; -import org.apache.poi.hssf.record.UseSelFSRecord; -import org.apache.poi.hssf.record.WSBoolRecord; -import org.apache.poi.hssf.record.WindowOneRecord; -import org.apache.poi.hssf.record.WindowProtectRecord; -import org.apache.poi.hssf.record.WindowTwoRecord; -import org.apache.poi.hssf.record.WriteAccessRecord; -import org.apache.poi.hssf.record.aggregates.PageSettingsBlock; - -/** - * Designed to check wither the records written actually make sense. - */ -public class SanityChecker { - static class CheckRecord - { - Class record; - char occurance; // 1 = one time, M = 1..many times, * = 0..many, 0 = optional - private final boolean together; - - public CheckRecord( Class record, char occurance ) - { - this(record, occurance, true); - } - - /** - * @param record The record type to check - * @param occurance The occurance 1 = occurs once, M = occurs many times - * @param together - */ - public CheckRecord(Class record, char occurance, boolean together) - { - this.record = record; - this.occurance = occurance; - this.together = together; - } - - public Class getRecord() - { - return record; - } - - public char getOccurance() - { - return occurance; - } - - public boolean isRequired() - { - return occurance == '1' || occurance == 'M'; - } - - public boolean isOptional() - { - return occurance == '0' || occurance == '*'; - } - - public boolean isTogether() - { - return together; - } - - public boolean isMany() - { - return occurance == '*' || occurance == 'M'; - } - - public int match( List records, int recordIdx ) - { - int firstRecord = findFirstRecord(records, getRecord(), recordIdx); - if (isRequired()) - { - return matchRequired( firstRecord, records, recordIdx ); - } - return matchOptional( firstRecord, records, recordIdx ); - } - - private int matchOptional( int firstRecord, List records, int recordIdx ) - { - if (firstRecord == -1) - { - return recordIdx; - } - - return matchOneOrMany( records, firstRecord ); - } - - private int matchRequired( int firstRecord, List records, int recordIdx ) - { - if (firstRecord == -1) - { - fail("Manditory record missing or out of order: " + record); - } - - return matchOneOrMany( records, firstRecord ); - } - - private int matchOneOrMany( List records, int recordIdx ) - { - if (isZeroOrOne()) - { - // check no other records - if (findFirstRecord(records, getRecord(), recordIdx+1) != -1) - fail("More than one record matched for " + getRecord().getName()); - } - else if (isZeroToMany()) - { - if (together) - { - int nextIdx = findFirstRecord(records, record, recordIdx+1); - while (nextIdx != -1) - { - if (nextIdx - 1 != recordIdx) - fail("Records are not together " + record.getName()); - recordIdx = nextIdx; - nextIdx = findFirstRecord(records, record, recordIdx+1); - } - } - } - return recordIdx+1; - } - - private boolean isZeroToMany() - { - return occurance == '*' || occurance == 'M'; - } - - private boolean isZeroOrOne() - { - return occurance == '0' || occurance == '1'; - } - } - - CheckRecord[] workbookRecords = new CheckRecord[] { - new CheckRecord(BOFRecord.class, '1'), - new CheckRecord(InterfaceHdrRecord.class, '1'), - new CheckRecord(MMSRecord.class, '1'), - new CheckRecord(InterfaceEndRecord.class, '1'), - new CheckRecord(WriteAccessRecord.class, '1'), - new CheckRecord(CodepageRecord.class, '1'), - new CheckRecord(DSFRecord.class, '1'), - new CheckRecord(TabIdRecord.class, '1'), - new CheckRecord(FnGroupCountRecord.class, '1'), - new CheckRecord(WindowProtectRecord.class, '1'), - new CheckRecord(ProtectRecord.class, '1'), - new CheckRecord(PasswordRev4Record.class, '1'), - new CheckRecord(WindowOneRecord.class, '1'), - new CheckRecord(BackupRecord.class, '1'), - new CheckRecord(HideObjRecord.class, '1'), - new CheckRecord(DateWindow1904Record.class, '1'), - new CheckRecord(PrecisionRecord.class, '1'), - new CheckRecord(RefreshAllRecord.class, '1'), - new CheckRecord(BookBoolRecord.class, '1'), - new CheckRecord(FontRecord.class, 'M'), - new CheckRecord(FormatRecord.class, 'M'), - new CheckRecord(ExtendedFormatRecord.class, 'M'), - new CheckRecord(StyleRecord.class, 'M'), - new CheckRecord(UseSelFSRecord.class, '1'), - new CheckRecord(BoundSheetRecord.class, 'M'), - new CheckRecord(CountryRecord.class, '1'), - new CheckRecord(SupBookRecord.class, '0'), - new CheckRecord(ExternSheetRecord.class, '0'), - new CheckRecord(NameRecord.class, '*'), - new CheckRecord(SSTRecord.class, '1'), - new CheckRecord(ExtSSTRecord.class, '1'), - new CheckRecord(EOFRecord.class, '1'), - }; - - CheckRecord[] sheetRecords = new CheckRecord[] { - new CheckRecord(BOFRecord.class, '1'), - new CheckRecord(CalcModeRecord.class, '1'), - new CheckRecord(RefModeRecord.class, '1'), - new CheckRecord(IterationRecord.class, '1'), - new CheckRecord(DeltaRecord.class, '1'), - new CheckRecord(SaveRecalcRecord.class, '1'), - new CheckRecord(PrintHeadersRecord.class, '1'), - new CheckRecord(PrintGridlinesRecord.class, '1'), - new CheckRecord(GridsetRecord.class, '1'), - new CheckRecord(GutsRecord.class, '1'), - new CheckRecord(DefaultRowHeightRecord.class, '1'), - new CheckRecord(WSBoolRecord.class, '1'), - new CheckRecord(PageSettingsBlock.class, '1'), - new CheckRecord(DefaultColWidthRecord.class, '1'), - new CheckRecord(DimensionsRecord.class, '1'), - new CheckRecord(WindowTwoRecord.class, '1'), - new CheckRecord(SelectionRecord.class, '1'), - new CheckRecord(EOFRecord.class, '1') - }; - - private void checkWorkbookRecords(InternalWorkbook workbook) - { - List records = workbook.getRecords(); - assertTrue(records.get(0) instanceof BOFRecord); - assertTrue(records.get(records.size() - 1) instanceof EOFRecord); - - checkRecordOrder(records, workbookRecords); -// checkRecordsTogether(records, workbookRecords); - } - - private void checkSheetRecords(InternalSheet sheet) { - List records = sheet.getRecords(); - assertTrue(records.get(0) instanceof BOFRecord); - assertTrue(records.get(records.size() - 1) instanceof EOFRecord); - - checkRecordOrder(records, sheetRecords); -// checkRecordsTogether(records, sheetRecords); - } - - public void checkHSSFWorkbook(HSSFWorkbook wb) - { - checkWorkbookRecords(wb.getWorkbook()); - for (int i = 0; i < wb.getNumberOfSheets(); i++) - checkSheetRecords(wb.getSheetAt(i).getSheet()); - - } - - /* - private void checkRecordsTogether(List records, CheckRecord[] check) - { - for ( int checkIdx = 0; checkIdx < check.length; checkIdx++ ) - { - int recordIdx = findFirstRecord(records, check[checkIdx].getRecord()); - boolean notFoundAndRecordRequired = (recordIdx == -1 && check[checkIdx].isRequired()); - if (notFoundAndRecordRequired) - { - fail("Expected to find record of class " + check.getClass() + " but did not"); - } - else if (recordIdx >= 0) - { - if (check[checkIdx].isMany()) - { - // Skip records that are together - while (recordIdx < records.size() && check[checkIdx].getRecord().isInstance(records.get(recordIdx))) - recordIdx++; - } - - // Make sure record does not occur in remaining records (after the next) - recordIdx++; - for (int recordIdx2 = recordIdx; recordIdx2 < records.size(); recordIdx2++) - { - if (check[checkIdx].getRecord().isInstance(records.get(recordIdx2))) - fail("Record occurs scattered throughout record chain:\n" + records.get(recordIdx2)); - } - } - } - } */ - - /* package */ static int findFirstRecord( List records, Class record, int startIndex ) - { - for (int i = startIndex; i < records.size(); i++) - { - if (record.getName().equals(records.get(i).getClass().getName())) - return i; - } - return -1; - } - - void checkRecordOrder(List records, CheckRecord[] check) - { - int recordIdx = 0; - for (CheckRecord element : check) { - recordIdx = element.match(records, recordIdx); - } - } - - /* - void checkRecordOrder(List records, CheckRecord[] check) - { - int checkIndex = 0; - for (int recordIndex = 0; recordIndex < records.size(); recordIndex++) - { - Record record = (Record) records.get(recordIndex); - if (check[checkIndex].getRecord().isInstance(record)) - { - if (check[checkIndex].getOccurance() == 'M') - { - // skip over duplicate records if multiples are allowed - while (recordIndex+1 < records.size() && check[checkIndex].getRecord().isInstance(records.get(recordIndex+1))) - recordIndex++; -// lastGoodMatch = recordIndex; - } - else if (check[checkIndex].getOccurance() == '1') - { - // Check next record to make sure there's not more than one - if (recordIndex != records.size() - 1) - { - if (check[checkIndex].getRecord().isInstance(records.get(recordIndex+1))) - { - fail("More than one occurance of record found:\n" + records.get(recordIndex).toString()); - } - } -// lastGoodMatch = recordIndex; - } -// else if (check[checkIndex].getOccurance() == '0') -// { -// -// } - checkIndex++; - } - if (checkIndex >= check.length) - return; - } - fail("Could not find required record: " + check[checkIndex]); - } */ - -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/StreamUtility.java b/src/testcases/org/apache/poi/hssf/usermodel/StreamUtility.java deleted file mode 100644 index 06aa0b84b..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/StreamUtility.java +++ /dev/null @@ -1,131 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; - -/** - * Utility class to help test code verify that generated files do not differ from proof copies in - * any significant detail. Normally this task would be simple except for the presence of artifacts - * in the file that change every time it is generated. Usually these volatile artifacts are - * time-stamps, user names, or other machine dependent parameters. - * - * @author Josh Micich - */ -public final class StreamUtility { - - /** - * Compares two streams with expected differences in specified regions. The streams are - * expected to be of equal length and comparison is always byte for byte. That is - - * differences can only involve exchanging each individual byte for another single byte.
    - * Both input streams are closed. - * - * @param allowableDifferenceRegions array of integer pairs: (offset, length). - * Any differences encountered in these regions of the streams will be ignored - * @return null if streams are identical, else the - * byte indexes of differing data. If streams were different lengths, - * the returned indexes will be -1 and the length of the shorter stream - */ - public static int[] diffStreams(InputStream isA, InputStream isB, int[] allowableDifferenceRegions) { - - if((allowableDifferenceRegions.length % 2) != 0) { - throw new RuntimeException("allowableDifferenceRegions length is odd"); - } - boolean success = false; - int[] result; - try { - result = diffInternal(isA, isB, allowableDifferenceRegions); - success = true; - } catch (IOException e) { - throw new RuntimeException(e); - } finally { - close(isA, success); - close(isB, success); - } - return result; - } - - /** - * @param success false if the outer method is throwing an exception. - */ - private static void close(InputStream is, boolean success) { - try { - is.close(); - } catch (IOException e) { - if(success) { - // this is a new error. ok to throw - throw new RuntimeException(e); - } - // else don't subvert original exception. just print stack trace for this one - e.printStackTrace(); - } - } - - private static int[] diffInternal(InputStream isA, InputStream isB, int[] allowableDifferenceRegions) - throws IOException { - int offset = 0; - List temp = new ArrayList(); - while (true) { - int b = isA.read(); - int b2 = isB.read(); - if (b == -1) { - // EOF - if (b2 == -1) { - return toPrimitiveIntArray(temp); - } - return new int[] { -1, offset, }; - } - if (b2 == -1) { - return new int[] { -1, offset, }; - } - if (b != b2 && !isIgnoredRegion(allowableDifferenceRegions, offset)) { - temp.add(Integer.valueOf(offset)); - } - offset++; - } - } - - private static boolean isIgnoredRegion(int[] allowableDifferenceRegions, int offset) { - for (int i = 0; i < allowableDifferenceRegions.length; i+=2) { - int start = allowableDifferenceRegions[i]; - int end = start + allowableDifferenceRegions[i+1]; - if(start <= offset && offset < end) { - return true; - } - } - return false; - } - - private static int[] toPrimitiveIntArray(List temp) { - int nItems = temp.size(); - if(nItems < 1) { - return null; - } - Integer[] boxInts = new Integer[nItems]; - temp.toArray(boxInts); - - int[] result = new int[nItems]; - for (int i = 0; i < result.length; i++) { - result[i] = boxInts[i].intValue(); - } - return result; - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestBug42464.java b/src/testcases/org/apache/poi/hssf/usermodel/TestBug42464.java deleted file mode 100644 index cbfc6d9b8..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestBug42464.java +++ /dev/null @@ -1,93 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.Assert.assertNotNull; - -import java.util.Iterator; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.record.FormulaRecord; -import org.apache.poi.hssf.record.aggregates.FormulaRecordAggregate; -import org.apache.poi.hssf.util.CellReference; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; -import org.apache.poi.ss.usermodel.Row; -import org.junit.Test; - -/** - * - */ -public final class TestBug42464 { - - @Test - public void testOKFile() throws Exception { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("42464-ExpPtg-ok.xls"); - process(wb); - wb.close(); - } - - @Test - public void testExpSharedBadFile() throws Exception { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("42464-ExpPtg-bad.xls"); - process(wb); - wb.close(); - } - - private static void process(HSSFWorkbook wb) { - HSSFFormulaEvaluator eval = new HSSFFormulaEvaluator(wb); - for(int i=0; i it = s.rowIterator(); - while(it.hasNext()) { - HSSFRow r = (HSSFRow)it.next(); - process(r, eval); - } - } - } - - private static void process(HSSFRow row, HSSFFormulaEvaluator eval) { - Iterator it = row.cellIterator(); - while(it.hasNext()) { - HSSFCell cell = (HSSFCell)it.next(); - if(cell.getCellTypeEnum() != CellType.FORMULA) { - continue; - } - FormulaRecordAggregate record = (FormulaRecordAggregate) cell.getCellValueRecord(); - FormulaRecord r = record.getFormulaRecord(); - Ptg[] ptgs = r.getParsedExpression(); - - String cellRef = new CellReference(row.getRowNum(), cell.getColumnIndex(), false, false).formatAsString(); -// if(false && cellRef.equals("BP24")) { // TODO - replace System.out.println()s with asserts -// System.out.print(cellRef); -// System.out.println(" - has " + ptgs.length + " ptgs:"); -// for(int i=0; i " + cell.getCellFormula()); -// } - - CellValue evalResult = eval.evaluate(cell); - assertNotNull(evalResult); - } - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestBugs.java b/src/testcases/org/apache/poi/hssf/usermodel/TestBugs.java deleted file mode 100644 index b84c953cf..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestBugs.java +++ /dev/null @@ -1,3097 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.awt.image.BufferedImage; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Calendar; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; -import java.util.TimeZone; - -import javax.imageio.ImageIO; - -import org.apache.poi.EncryptedDocumentException; -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.OldExcelFormatException; -import org.apache.poi.hssf.extractor.ExcelExtractor; -import org.apache.poi.hssf.model.InternalSheet; -import org.apache.poi.hssf.model.InternalWorkbook; -import org.apache.poi.hssf.record.CellValueRecordInterface; -import org.apache.poi.hssf.record.CommonObjectDataSubRecord; -import org.apache.poi.hssf.record.EmbeddedObjectRefSubRecord; -import org.apache.poi.hssf.record.NameRecord; -import org.apache.poi.hssf.record.Record; -import org.apache.poi.hssf.record.TabIdRecord; -import org.apache.poi.hssf.record.UnknownRecord; -import org.apache.poi.hssf.record.aggregates.FormulaRecordAggregate; -import org.apache.poi.hssf.record.aggregates.PageSettingsBlock; -import org.apache.poi.hssf.record.aggregates.RecordAggregate; -import org.apache.poi.hssf.record.common.UnicodeString; -import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey; -import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; -import org.apache.poi.poifs.filesystem.OPOIFSFileSystem; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.ss.formula.ptg.Area3DPtg; -import org.apache.poi.ss.formula.ptg.DeletedArea3DPtg; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.apache.poi.ss.usermodel.BaseTestBugzillaIssues; -import org.apache.poi.ss.usermodel.BorderStyle; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.ClientAnchor.AnchorType; -import org.apache.poi.ss.usermodel.ComparisonOperator; -import org.apache.poi.ss.usermodel.DataFormatter; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Name; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.SheetVisibility; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.util.LocaleUtil; -import org.junit.After; -import org.junit.Assume; -import org.junit.Ignore; -import org.junit.Test; - -/** - * Testcases for bugs entered in bugzilla - * the Test name contains the bugzilla bug id - * - * YK: If a bug can be tested in terms of common ss interfaces, - * define the test in the base class {@link BaseTestBugzillaIssues} - */ -@SuppressWarnings("deprecation") -public final class TestBugs extends BaseTestBugzillaIssues { - // to not affect other tests running in the same JVM - @After - public void resetPassword() { - Biff8EncryptionKey.setCurrentUserPassword(null); - } - - public TestBugs() { - super(HSSFITestDataProvider.instance); - } - - private static HSSFWorkbook openSample(String sampleFileName) { - return HSSFITestDataProvider.instance.openSampleWorkbook(sampleFileName); - } - - private static HSSFWorkbook writeOutAndReadBack(HSSFWorkbook original) { - return HSSFITestDataProvider.instance.writeOutAndReadBack(original); - } - - /** Test reading AND writing a complicated workbook - *Test opening resulting sheet in excel*/ - @Test - public void bug15228() throws Exception { - HSSFWorkbook wb = openSample("15228.xls"); - HSSFSheet s = wb.getSheetAt(0); - HSSFRow r = s.createRow(0); - HSSFCell c = r.createCell(0); - c.setCellValue(10); - writeOutAndReadBack(wb).close(); - wb.close(); - } - - @Test - public void bug13796() throws Exception { - HSSFWorkbook wb = openSample("13796.xls"); - HSSFSheet s = wb.getSheetAt(0); - HSSFRow r = s.createRow(0); - HSSFCell c = r.createCell(0); - c.setCellValue(10); - writeOutAndReadBack(wb).close(); - wb.close(); - } - - /** test reading of a formula with a name and a cell ref in one - **/ - @Test - public void bug14460() throws Exception { - HSSFWorkbook wb = openSample("14460.xls"); - wb.getSheetAt(0); - wb.close(); - } - - @Test - public void bug14330() throws Exception { - HSSFWorkbook wb1 = openSample("14330-1.xls"); - wb1.getSheetAt(0); - wb1.close(); - - HSSFWorkbook wb2 = openSample("14330-2.xls"); - wb2.getSheetAt(0); - wb2.close(); - } - - private static void setCellText(HSSFCell cell, String text) { - cell.setCellValue(new HSSFRichTextString(text)); - } - - /** test rewriting a file with large number of unique strings - *open resulting file in Excel to check results!*/ - @Test - public void bug15375() throws Exception { - HSSFWorkbook wb = openSample("15375.xls"); - HSSFSheet sheet = wb.getSheetAt(0); - - HSSFRow row = sheet.getRow(5); - HSSFCell cell = row.getCell(3); - if (cell == null) - cell = row.createCell(3); - - // Write test - cell.setCellType(CellType.STRING); - setCellText(cell, "a test"); - - // change existing numeric cell value - - HSSFRow oRow = sheet.getRow(14); - HSSFCell oCell = oRow.getCell(4); - oCell.setCellValue(75); - oCell = oRow.getCell(5); - setCellText(oCell, "0.3"); - - writeOutAndReadBack(wb).close(); - wb.close(); - } - /** - * test writing a file with large number of unique strings, - * open resulting file in Excel to check results! - */ - @Test - public void bug15375_2() throws Exception { - bug15375(6000); - } - - /**Double byte strings*/ - @Test - public void bug15556() throws Exception { - HSSFWorkbook wb = openSample("15556.xls"); - HSSFSheet sheet = wb.getSheetAt(0); - HSSFRow row = sheet.getRow(45); - assertNotNull("Read row fine!" , row); - wb.close(); - } - - /**Double byte strings */ - @Test - public void bug22742() { - openSample("22742.xls"); - } - - /**Double byte strings */ - @Test - public void bug12561_1() { - openSample("12561-1.xls"); - } - - /** Double byte strings */ - @Test - public void bug12561_2() { - openSample("12561-2.xls"); - } - - /** Double byte strings - File supplied by jubeson*/ - @Test - public void bug12843_1() { - openSample("12843-1.xls"); - } - - /** Double byte strings - File supplied by Paul Chung*/ - @Test - public void bug12843_2() { - openSample("12843-2.xls"); - } - - /** Reference to Name*/ - @Test - public void bug13224() { - openSample("13224.xls"); - } - - /** Illegal argument exception - cannot store duplicate value in Map*/ - @Test - public void bug19599() { - openSample("19599-1.xls"); - openSample("19599-2.xls"); - } - - @Test - public void bug24215() throws Exception { - HSSFWorkbook wb = openSample("24215.xls"); - - for (int sheetIndex = 0; sheetIndex < wb.getNumberOfSheets();sheetIndex++) { - HSSFSheet sheet = wb.getSheetAt(sheetIndex); - int rows = sheet.getLastRowNum(); - - for (int rowIndex = 0; rowIndex < rows; rowIndex++) { - HSSFRow row = sheet.getRow(rowIndex); - int cells = row.getLastCellNum(); - - for (int cellIndex = 0; cellIndex < cells; cellIndex++) { - row.getCell(cellIndex); - } - } - } - wb.close(); - } - - /**Tests read and write of Unicode strings in formula results - * bug and testcase submitted by Sompop Kumnoonsate - * The file contains THAI unicode characters. - */ - @Test - public void bugUnicodeStringFormulaRead() throws Exception { - - HSSFWorkbook w = openSample("25695.xls"); - - HSSFCell a1 = w.getSheetAt(0).getRow(0).getCell(0); - HSSFCell a2 = w.getSheetAt(0).getRow(0).getCell(1); - HSSFCell b1 = w.getSheetAt(0).getRow(1).getCell(0); - HSSFCell b2 = w.getSheetAt(0).getRow(1).getCell(1); - HSSFCell c1 = w.getSheetAt(0).getRow(2).getCell(0); - HSSFCell c2 = w.getSheetAt(0).getRow(2).getCell(1); - HSSFCell d1 = w.getSheetAt(0).getRow(3).getCell(0); - HSSFCell d2 = w.getSheetAt(0).getRow(3).getCell(1); - - /* - // THAI code page - System.out.println("a1="+unicodeString(a1)); - System.out.println("a2="+unicodeString(a2)); - // US code page - System.out.println("b1="+unicodeString(b1)); - System.out.println("b2="+unicodeString(b2)); - // THAI+US - System.out.println("c1="+unicodeString(c1)); - System.out.println("c2="+unicodeString(c2)); - // US+THAI - System.out.println("d1="+unicodeString(d1)); - System.out.println("d2="+unicodeString(d2)); - */ - - confirmSameCellText(a1, a2); - confirmSameCellText(b1, b2); - confirmSameCellText(c1, c2); - confirmSameCellText(d1, d2); - - HSSFWorkbook rw = writeOutAndReadBack(w); - w.close(); - - HSSFCell ra1 = rw.getSheetAt(0).getRow(0).getCell(0); - HSSFCell ra2 = rw.getSheetAt(0).getRow(0).getCell(1); - HSSFCell rb1 = rw.getSheetAt(0).getRow(1).getCell(0); - HSSFCell rb2 = rw.getSheetAt(0).getRow(1).getCell(1); - HSSFCell rc1 = rw.getSheetAt(0).getRow(2).getCell(0); - HSSFCell rc2 = rw.getSheetAt(0).getRow(2).getCell(1); - HSSFCell rd1 = rw.getSheetAt(0).getRow(3).getCell(0); - HSSFCell rd2 = rw.getSheetAt(0).getRow(3).getCell(1); - - confirmSameCellText(a1, ra1); - confirmSameCellText(b1, rb1); - confirmSameCellText(c1, rc1); - confirmSameCellText(d1, rd1); - - confirmSameCellText(a1, ra2); - confirmSameCellText(b1, rb2); - confirmSameCellText(c1, rc2); - confirmSameCellText(d1, rd2); - - rw.close(); - } - - private static void confirmSameCellText(HSSFCell a, HSSFCell b) { - assertEquals(a.getRichStringCellValue().getString(), b.getRichStringCellValue().getString()); - } - - /*private static String unicodeString(HSSFCell cell) { - String ss = cell.getRichStringCellValue().getString(); - char s[] = ss.toCharArray(); - StringBuffer sb = new StringBuffer(); - for (int x=0;x it = sheet.rowIterator(); it.hasNext(); rownum++) { - Row row = it.next(); - assertEquals(rownum, row.getRowNum()); - int cellNum = 0; - for (Iterator it2 = row.cellIterator(); it2.hasNext(); cellNum++) { - Cell cell = it2.next(); - assertEquals(cellNum, cell.getColumnIndex()); - } - } - wb.close(); - } - - /** - * Test bug 38266: NPE when adding a row break - * - * User's diagnosis: - * 1. Manually (i.e., not using POI) create an Excel Workbook, making sure it - * contains a sheet that doesn't have any row breaks - * 2. Using POI, create a new HSSFWorkbook from the template in step #1 - * 3. Try adding a row break (via sheet.setRowBreak()) to the sheet mentioned in step #1 - * 4. Get a NullPointerException - */ - @Test - public void bug38266() throws Exception { - String[] files = {"Simple.xls", "SimpleMultiCell.xls", "duprich1.xls"}; - for (String file : files) { - HSSFWorkbook wb = openSample(file); - - HSSFSheet sheet = wb.getSheetAt( 0 ); - int[] breaks = sheet.getRowBreaks(); - assertEquals(0, breaks.length); - - //add 3 row breaks - for (int j = 1; j <= 3; j++) { - sheet.setRowBreak(j*20); - } - wb.close(); - } - } - - @Test - public void bug40738() throws Exception { - HSSFWorkbook wb = openSample("SimpleWithAutofilter.xls"); - writeOutAndReadBack(wb).close(); - wb.close(); - } - - /** - * Bug 44200: Sheet not cloneable when Note added to excel cell - */ - @Test - public void bug44200() throws Exception { - HSSFWorkbook wb = openSample("44200.xls"); - wb.cloneSheet(0); - writeOutAndReadBack(wb).close(); - wb.close(); - } - - /** - * Bug 44201: Sheet not cloneable when validation added to excel cell - */ - @Test - public void bug44201() throws Exception { - HSSFWorkbook wb = openSample("44201.xls"); - writeOutAndReadBack(wb).close(); - wb.close(); - } - - /** - * Bug 37684 : Unhandled Continue Record Error - */ - @Test - public void bug37684() throws Exception { - HSSFWorkbook wb1 = openSample("37684-1.xls"); - writeOutAndReadBack(wb1).close(); - wb1.close(); - HSSFWorkbook wb2 = openSample("37684-2.xls"); - writeOutAndReadBack(wb2).close(); - wb2.close(); - } - - /** - * Bug 41139: Constructing HSSFWorkbook is failed,threw threw ArrayIndexOutOfBoundsException for creating UnknownRecord - */ - @Test - public void bug41139() throws Exception { - HSSFWorkbook wb = openSample("41139.xls"); - writeOutAndReadBack(wb).close(); - wb.close(); - } - - /** - * Bug 41546: Constructing HSSFWorkbook is failed, - * Unknown Ptg in Formula: 0x1a (26) - */ - @Test - public void bug41546() throws Exception { - HSSFWorkbook wb1 = openSample("41546.xls"); - assertEquals(1, wb1.getNumberOfSheets()); - HSSFWorkbook wb2 = writeOutAndReadBack(wb1); - assertEquals(1, wb2.getNumberOfSheets()); - wb2.close(); - wb1.close(); - } - - /** - * Bug 42564: Some files from Access were giving a RecordFormatException - * when reading the BOFRecord - */ - @Test - public void bug42564() throws Exception { - HSSFWorkbook wb = openSample("ex42564-21435.xls"); - writeOutAndReadBack(wb).close(); - wb.close(); - } - - /** - * Bug 42564: Some files from Access also have issues - * with the NameRecord, once you get past the BOFRecord - * issue. - */ - @Test - public void bug42564Alt() throws Exception { - HSSFWorkbook wb = openSample("ex42564-21503.xls"); - writeOutAndReadBack(wb).close(); - wb.close(); - } - - /** - * Bug 42618: RecordFormatException reading a file containing - * =CHOOSE(2,A2,A3,A4) - */ - @Test - public void bug42618() throws Exception { - HSSFWorkbook wb1 = openSample("SimpleWithChoose.xls"); - HSSFWorkbook wb2 = writeOutAndReadBack(wb1); - wb1.close(); - // Check we detect the string properly too - HSSFSheet s = wb2.getSheetAt(0); - - // Textual value - HSSFRow r1 = s.getRow(0); - HSSFCell c1 = r1.getCell(1); - assertEquals("=CHOOSE(2,A2,A3,A4)", c1.getRichStringCellValue().toString()); - - // Formula Value - HSSFRow r2 = s.getRow(1); - HSSFCell c2 = r2.getCell(1); - assertEquals(25, (int)c2.getNumericCellValue()); - - try { - assertEquals("CHOOSE(2,A2,A3,A4)", c2.getCellFormula()); - } catch (IllegalStateException e) { - if (e.getMessage().startsWith("Too few arguments") - && e.getMessage().indexOf("ConcatPtg") > 0) { - fail("identified bug 44306"); - } - } - wb2.close(); - } - - /** - * Something up with the FileSharingRecord - */ - @Test - public void bug43251() throws Exception { - // Used to blow up with an IllegalArgumentException - // when creating a FileSharingRecord - HSSFWorkbook wb = openSample("43251.xls"); - assertEquals(1, wb.getNumberOfSheets()); - wb.close(); - } - - /** - * Crystal reports generates files with short - * StyleRecords, which is against the spec - */ - @Test - public void bug44471() throws Exception { - // Used to blow up with an ArrayIndexOutOfBounds - // when creating a StyleRecord - HSSFWorkbook wb = openSample("OddStyleRecord.xls"); - assertEquals(1, wb.getNumberOfSheets()); - wb.close(); - } - - /** - * Files with "read only recommended" were giving - * grief on the FileSharingRecord - */ - @Test - public void bug44536() throws Exception { - // Used to blow up with an IllegalArgumentException - // when creating a FileSharingRecord - HSSFWorkbook wb1 = openSample("ReadOnlyRecommended.xls"); - - // Check read only advised - assertEquals(3, wb1.getNumberOfSheets()); - assertTrue(wb1.isWriteProtected()); - wb1.close(); - - // But also check that another wb isn't - HSSFWorkbook wb2 = openSample("SimpleWithChoose.xls"); - assertFalse(wb2.isWriteProtected()); - wb2.close(); - } - - /** - * Some files were having problems with the DVRecord, - * probably due to dropdowns - */ - @Test - public void bug44593() throws Exception { - // Used to blow up with an IllegalArgumentException - // when creating a DVRecord - // Now won't, but no idea if this means we have - // rubbish in the DVRecord or not... - HSSFWorkbook wb = openSample("44593.xls"); - assertEquals(2, wb.getNumberOfSheets()); - wb.close(); - } - - /** - * Used to give problems due to trying to read a zero - * length string, but that's now properly handled - */ - @Test - public void bug44643() throws Exception { - // Used to blow up with an IllegalArgumentException - HSSFWorkbook wb = openSample("44643.xls"); - assertEquals(1, wb.getNumberOfSheets()); - wb.close(); - } - - /** - * User reported the wrong number of rows from the - * iterator, but we can't replicate that - */ - @Test - public void bug44693() throws Exception { - HSSFWorkbook wb = openSample("44693.xls"); - HSSFSheet s = wb.getSheetAt(0); - - // Rows are 1 to 713 - assertEquals(0, s.getFirstRowNum()); - assertEquals(712, s.getLastRowNum()); - assertEquals(713, s.getPhysicalNumberOfRows()); - - // Now check the iterator - int rowsSeen = 0; - for(Iterator i = s.rowIterator(); i.hasNext(); ) { - Row r = i.next(); - assertNotNull(r); - rowsSeen++; - } - assertEquals(713, rowsSeen); - wb.close(); - } - - /** - * Bug 28774: Excel will crash when opening xls-files with images. - */ - @Test - public void bug28774() throws Exception { - HSSFWorkbook wb = openSample("28774.xls"); - assertTrue("no errors reading sample xls", true); - writeOutAndReadBack(wb).close(); - assertTrue("no errors writing sample xls", true); - wb.close(); - } - - /** - * Had a problem apparently, not sure what as it - * works just fine... - */ - @Test - public void bug44891() throws Exception { - HSSFWorkbook wb = openSample("44891.xls"); - assertTrue("no errors reading sample xls", true); - writeOutAndReadBack(wb).close(); - assertTrue("no errors writing sample xls", true); - wb.close(); - } - - /** - * Bug 44235: Ms Excel can't open save as excel file - * - * Works fine with poi-3.1-beta1. - */ - @Test - public void bug44235() throws Exception { - HSSFWorkbook wb = openSample("44235.xls"); - assertTrue("no errors reading sample xls", true); - writeOutAndReadBack(wb).close(); - assertTrue("no errors writing sample xls", true); - wb.close(); - } - - @Test - public void bug36947() throws Exception { - HSSFWorkbook wb = openSample("36947.xls"); - assertTrue("no errors reading sample xls", true); - writeOutAndReadBack(wb).close(); - assertTrue("no errors writing sample xls", true); - wb.close(); - } - - @Test - public void bug39634() throws Exception { - HSSFWorkbook wb = openSample("39634.xls"); - assertTrue("no errors reading sample xls", true); - writeOutAndReadBack(wb).close(); - assertTrue("no errors writing sample xls", true); - wb.close(); - } - - /** - * Problems with extracting check boxes from - * HSSFObjectData - */ - @Test(expected=FileNotFoundException.class) - public void bug44840() throws Exception { - HSSFWorkbook wb = openSample("WithCheckBoxes.xls"); - - // Take a look at the embedded objects - List objects = wb.getAllEmbeddedObjects(); - assertEquals(1, objects.size()); - - HSSFObjectData obj = objects.get(0); - assertNotNull(obj); - - // Peek inside the underlying record - EmbeddedObjectRefSubRecord rec = obj.findObjectRecord(); - assertNotNull(rec); - -// assertEquals(32, rec.field_1_stream_id_offset); - assertEquals(0, rec.getStreamId().intValue()); // WRONG! - assertEquals("Forms.CheckBox.1", rec.getOLEClassName()); - assertEquals(12, rec.getObjectData().length); - - // Doesn't have a directory - assertFalse(obj.hasDirectoryEntry()); - assertNotNull(obj.getObjectData()); - assertEquals(12, obj.getObjectData().length); - assertEquals("Forms.CheckBox.1", obj.getOLE2ClassName()); - - try { - obj.getDirectory(); - } finally { - wb.close(); - } - } - - /** - * Test that we can delete sheets without - * breaking the build in named ranges - * used for printing stuff. - */ - @Test - public void bug30978() throws Exception { - HSSFWorkbook wb1 = openSample("30978-alt.xls"); - assertEquals(1, wb1.getNumberOfNames()); - assertEquals(3, wb1.getNumberOfSheets()); - - // Check all names fit within range, and use - // DeletedArea3DPtg - InternalWorkbook w = wb1.getWorkbook(); - assertNames(wb1, w); - - // Delete the 2nd sheet - wb1.removeSheetAt(1); - - // Re-check - assertEquals(1, wb1.getNumberOfNames()); - assertEquals(2, wb1.getNumberOfSheets()); - assertNames(wb1, w); - - // Save and re-load - HSSFWorkbook wb2 = writeOutAndReadBack(wb1); - wb1.close(); - w = wb2.getWorkbook(); - - assertEquals(1, wb2.getNumberOfNames()); - assertEquals(2, wb2.getNumberOfSheets()); - - assertNames(wb2, w); - wb2.close(); - } - - private void assertNames(HSSFWorkbook wb1, InternalWorkbook w) { - for(int i=0; i it = ns.getSheet().getCellValueIterator(); it.hasNext(); i++) { - CellValueRecordInterface cvr = it.next(); - if(cvr instanceof FormulaRecordAggregate) { - FormulaRecordAggregate fr = (FormulaRecordAggregate)cvr; - - if(i == 0) { - assertEquals(70164.0, fr.getFormulaRecord().getValue(), 0.0001); - assertNull(fr.getStringRecord()); - } else if (i == 1) { - assertEquals(0.0, fr.getFormulaRecord().getValue(), 0.0001); - assertNotNull(fr.getStringRecord()); - assertEquals("70164", fr.getStringRecord().getString()); - } else { - assertEquals(0.0, fr.getFormulaRecord().getValue(), 0.0001); - assertNotNull(fr.getStringRecord()); - assertEquals("90210", fr.getStringRecord().getString()); - } - } - } - assertEquals(3, i); - wb2.close(); - } - - private static void confirmCachedValue(double expectedValue, HSSFCell cell) { - assertEquals(CellType.FORMULA, cell.getCellTypeEnum()); - assertEquals(CellType.NUMERIC, cell.getCachedFormulaResultTypeEnum()); - assertEquals(expectedValue, cell.getNumericCellValue(), 0.0); - } - private static void confirmCachedValue(String expectedValue, HSSFCell cell) { - assertEquals(CellType.FORMULA, cell.getCellTypeEnum()); - assertEquals(CellType.STRING, cell.getCachedFormulaResultTypeEnum()); - assertEquals(expectedValue, cell.getRichStringCellValue().getString()); - } - - /** - * Problem with "Vector Rows", eg a whole - * column which is set to the result of - * {=sin(B1:B9)}(9,1), so that each cell is - * shown to have the contents - * {=sin(B1:B9){9,1)[rownum][0] - * In this sample file, the vector column - * is C, and the data column is B. - * - * Expected ExpPtg to be converted from Shared to Non-Shared... - */ - @Ignore("For now, blows up with an exception from ExtPtg") - @Test - public void test43623() throws Exception { - HSSFWorkbook wb1 = openSample("43623.xls"); - assertEquals(1, wb1.getNumberOfSheets()); - - HSSFSheet s1 = wb1.getSheetAt(0); - - HSSFCell c1 = s1.getRow(0).getCell(2); - HSSFCell c2 = s1.getRow(1).getCell(2); - HSSFCell c3 = s1.getRow(2).getCell(2); - - // These formula contents are a guess... - assertEquals("{=sin(B1:B9){9,1)[0][0]", c1.getCellFormula()); - assertEquals("{=sin(B1:B9){9,1)[1][0]", c2.getCellFormula()); - assertEquals("{=sin(B1:B9){9,1)[2][0]", c3.getCellFormula()); - - // Save and re-open, ensure it still works - HSSFWorkbook wb2 = writeOutAndReadBack(wb1); - wb1.close(); - HSSFSheet ns1 = wb2.getSheetAt(0); - HSSFCell nc1 = ns1.getRow(0).getCell(2); - HSSFCell nc2 = ns1.getRow(1).getCell(2); - HSSFCell nc3 = ns1.getRow(2).getCell(2); - - assertEquals("{=sin(B1:B9){9,1)[0][0]", nc1.getCellFormula()); - assertEquals("{=sin(B1:B9){9,1)[1][0]", nc2.getCellFormula()); - assertEquals("{=sin(B1:B9){9,1)[2][0]", nc3.getCellFormula()); - wb2.close(); - } - - /** - * People are all getting confused about the last - * row and cell number - */ - @Test - public void bug30635() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet s = wb.createSheet(); - - // No rows, everything is 0 - assertEquals(0, s.getFirstRowNum()); - assertEquals(0, s.getLastRowNum()); - assertEquals(0, s.getPhysicalNumberOfRows()); - - // One row, most things are 0, physical is 1 - s.createRow(0); - assertEquals(0, s.getFirstRowNum()); - assertEquals(0, s.getLastRowNum()); - assertEquals(1, s.getPhysicalNumberOfRows()); - - // And another, things change - s.createRow(4); - assertEquals(0, s.getFirstRowNum()); - assertEquals(4, s.getLastRowNum()); - assertEquals(2, s.getPhysicalNumberOfRows()); - - - // Now start on cells - HSSFRow r = s.getRow(0); - assertEquals(-1, r.getFirstCellNum()); - assertEquals(-1, r.getLastCellNum()); - assertEquals(0, r.getPhysicalNumberOfCells()); - - // Add a cell, things move off -1 - r.createCell(0); - assertEquals(0, r.getFirstCellNum()); - assertEquals(1, r.getLastCellNum()); // last cell # + 1 - assertEquals(1, r.getPhysicalNumberOfCells()); - - r.createCell(1); - assertEquals(0, r.getFirstCellNum()); - assertEquals(2, r.getLastCellNum()); // last cell # + 1 - assertEquals(2, r.getPhysicalNumberOfCells()); - - r.createCell(4); - assertEquals(0, r.getFirstCellNum()); - assertEquals(5, r.getLastCellNum()); // last cell # + 1 - assertEquals(3, r.getPhysicalNumberOfCells()); - - wb.close(); - } - - /** - * Data Tables - ptg 0x2 - */ - @Test - public void bug44958() throws Exception { - HSSFWorkbook wb = openSample("44958.xls"); - HSSFSheet s; - HSSFRow r; - HSSFCell c; - - // Check the contents of the formulas - - // E4 to G9 of sheet 4 make up the table - s = wb.getSheet("OneVariable Table Completed"); - r = s.getRow(3); - c = r.getCell(4); - assertEquals(CellType.FORMULA, c.getCellTypeEnum()); - - // TODO - check the formula once tables and - // arrays are properly supported - - - // E4 to H9 of sheet 5 make up the table - s = wb.getSheet("TwoVariable Table Example"); - r = s.getRow(3); - c = r.getCell(4); - assertEquals(CellType.FORMULA, c.getCellTypeEnum()); - - // TODO - check the formula once tables and - // arrays are properly supported - wb.close(); - } - - /** - * 45322: HSSFSheet.autoSizeColumn fails when style.getDataFormat() returns -1 - */ - @Test - public void bug45322() throws Exception { - HSSFWorkbook wb = openSample("44958.xls"); - HSSFSheet sh = wb.getSheetAt(0); - for(short i=0; i < 30; i++) sh.autoSizeColumn(i); - wb.close(); - } - - /** - * We used to add too many UncalcRecords to sheets - * with diagrams on. Don't any more - */ - @Test - public void bug45414() throws Exception { - HSSFWorkbook wb1 = openSample("WithThreeCharts.xls"); - wb1.getSheetAt(0).setForceFormulaRecalculation(true); - wb1.getSheetAt(1).setForceFormulaRecalculation(false); - wb1.getSheetAt(2).setForceFormulaRecalculation(true); - - // Write out and back in again - // This used to break - HSSFWorkbook wb2 = writeOutAndReadBack(wb1); - wb1.close(); - - // Check now set as it should be - assertTrue(wb2.getSheetAt(0).getForceFormulaRecalculation()); - assertFalse(wb2.getSheetAt(1).getForceFormulaRecalculation()); - assertTrue(wb2.getSheetAt(2).getForceFormulaRecalculation()); - wb2.close(); - } - - /** - * Very hidden sheets not displaying as such - */ - @Test - public void bug45761() throws Exception { - HSSFWorkbook wb1 = openSample("45761.xls"); - assertEquals(3, wb1.getNumberOfSheets()); - - assertFalse(wb1.isSheetHidden(0)); - assertFalse(wb1.isSheetVeryHidden(0)); - assertTrue(wb1.isSheetHidden(1)); - assertFalse(wb1.isSheetVeryHidden(1)); - assertFalse(wb1.isSheetHidden(2)); - assertTrue(wb1.isSheetVeryHidden(2)); - - // Change sheet 0 to be very hidden, and re-load - wb1.setSheetVisibility(0, SheetVisibility.VERY_HIDDEN); - - HSSFWorkbook wb2 = writeOutAndReadBack(wb1); - wb1.close(); - - assertFalse(wb2.isSheetHidden(0)); - assertTrue(wb2.isSheetVeryHidden(0)); - assertTrue(wb2.isSheetHidden(1)); - assertFalse(wb2.isSheetVeryHidden(1)); - assertFalse(wb2.isSheetHidden(2)); - assertTrue(wb2.isSheetVeryHidden(2)); - wb2.close(); - } - - /** - * The resolution for bug 45777 assumed that the maximum text length in a header / footer - * record was 256 bytes. This assumption appears to be wrong. Since the fix for bug 47244, - * POI now supports header / footer text lengths beyond 256 bytes. - */ - @Test - public void bug45777() throws Exception { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet s = wb.createSheet(); - - char[] cc248 = new char[248]; - Arrays.fill(cc248, 'x'); - String s248 = new String(cc248); - - String s249 = s248 + "1"; - String s250 = s248 + "12"; - String s251 = s248 + "123"; - assertEquals(248, s248.length()); - assertEquals(249, s249.length()); - assertEquals(250, s250.length()); - assertEquals(251, s251.length()); - - - // Try on headers - s.getHeader().setCenter(s248); - assertEquals(254, s.getHeader().getRawText().length()); - writeOutAndReadBack(wb).close(); - - s.getHeader().setCenter(s251); - assertEquals(257, s.getHeader().getRawText().length()); - writeOutAndReadBack(wb).close(); - - // header can be more than 256 bytes - s.getHeader().setCenter(s250); // 256 bytes required - s.getHeader().setCenter(s251); // 257 bytes required - - // Now try on footers - s.getFooter().setCenter(s248); - assertEquals(254, s.getFooter().getRawText().length()); - writeOutAndReadBack(wb).close(); - - s.getFooter().setCenter(s251); - assertEquals(257, s.getFooter().getRawText().length()); - writeOutAndReadBack(wb).close(); - - // footer can be more than 256 bytes - s.getFooter().setCenter(s250); // 256 bytes required - s.getFooter().setCenter(s251); // 257 bytes required - - wb.close(); - } - - /** - * Charts with long titles - */ - @Test - public void bug45784() throws Exception { - // This used to break - HSSFWorkbook wb = openSample("45784.xls"); - assertEquals(1, wb.getNumberOfSheets()); - writeOutAndReadBack(wb).close(); - wb.close(); - } - - /** - * Cell background colours - */ - @Test - public void bug45492() throws Exception { - HSSFWorkbook wb = openSample("45492.xls"); - HSSFSheet s = wb.getSheetAt(0); - HSSFRow r = s.getRow(0); - HSSFPalette p = wb.getCustomPalette(); - - HSSFCell auto = r.getCell(0); - HSSFCell grey = r.getCell(1); - HSSFCell red = r.getCell(2); - HSSFCell blue = r.getCell(3); - HSSFCell green = r.getCell(4); - - assertEquals(64, auto.getCellStyle().getFillForegroundColor()); - assertEquals(64, auto.getCellStyle().getFillBackgroundColor()); - assertEquals("0:0:0", p.getColor(64).getHexString()); - - assertEquals(22, grey.getCellStyle().getFillForegroundColor()); - assertEquals(64, grey.getCellStyle().getFillBackgroundColor()); - assertEquals("C0C0:C0C0:C0C0", p.getColor(22).getHexString()); - - assertEquals(10, red.getCellStyle().getFillForegroundColor()); - assertEquals(64, red.getCellStyle().getFillBackgroundColor()); - assertEquals("FFFF:0:0", p.getColor(10).getHexString()); - - assertEquals(12, blue.getCellStyle().getFillForegroundColor()); - assertEquals(64, blue.getCellStyle().getFillBackgroundColor()); - assertEquals("0:0:FFFF", p.getColor(12).getHexString()); - - assertEquals(11, green.getCellStyle().getFillForegroundColor()); - assertEquals(64, green.getCellStyle().getFillBackgroundColor()); - assertEquals("0:FFFF:0", p.getColor(11).getHexString()); - wb.close(); - } - - /** - * ContinueRecord after EOF - */ - @Test - public void bug46137() throws Exception { - // This used to break - HSSFWorkbook wb = openSample("46137.xls"); - assertEquals(7, wb.getNumberOfSheets()); - writeOutAndReadBack(wb).close(); - wb.close(); - } - - /** - * Odd POIFS blocks issue: - * block[ 44 ] already removed from org.apache.poi.poifs.storage.BlockListImpl.remove - */ - @Test - public void bug45290() throws Exception { - HSSFWorkbook wb = openSample("45290.xls"); - assertEquals(1, wb.getNumberOfSheets()); - wb.close(); - } - - /** - * In POI-2.5 user reported exception when parsing a name with a custom VBA function: - * =MY_VBA_FUNCTION("lskdjflsk") - */ - @Test - public void bug30070() throws Exception { - HSSFWorkbook wb = openSample("30070.xls"); //contains custom VBA function 'Commission' - HSSFSheet sh = wb.getSheetAt(0); - HSSFCell cell = sh.getRow(0).getCell(1); - - //B1 uses VBA in the formula - assertEquals("Commission(A1)", cell.getCellFormula()); - - //name sales_1 refers to Commission(Sheet0!$A$1) - int idx = wb.getNameIndex("sales_1"); - assertTrue(idx != -1); - - HSSFName name = wb.getNameAt(idx); - assertEquals("Commission(Sheet0!$A$1)", name.getRefersToFormula()); - wb.close(); - } - - /** - * The link formulas which is referring to other books cannot be taken (the bug existed prior to POI-3.2) - * Expected: - * - * [link_sub.xls]Sheet1!$A$1 - * [link_sub.xls]Sheet1!$A$2 - * [link_sub.xls]Sheet1!$A$3 - * - * POI-3.1 output: - * - * Sheet1!$A$1 - * Sheet1!$A$2 - * Sheet1!$A$3 - * - */ - @Test - public void bug27364() throws Exception { - HSSFWorkbook wb = openSample("27364.xls"); - HSSFSheet sheet = wb.getSheetAt(0); - - assertEquals("[link_sub.xls]Sheet1!$A$1", sheet.getRow(0).getCell(0).getCellFormula()); - assertEquals("[link_sub.xls]Sheet1!$A$2", sheet.getRow(1).getCell(0).getCellFormula()); - assertEquals("[link_sub.xls]Sheet1!$A$3", sheet.getRow(2).getCell(0).getCellFormula()); - wb.close(); - } - - /** - * Similar to bug#27364: - * HSSFCell.getCellFormula() fails with references to external workbooks - */ - @Test - public void bug31661() throws Exception { - HSSFWorkbook wb = openSample("31661.xls"); - HSSFSheet sheet = wb.getSheetAt(0); - HSSFCell cell = sheet.getRow(11).getCell(10); //K11 - assertEquals("+'[GM Budget.xls]8085.4450'!$B$2", cell.getCellFormula()); - wb.close(); - } - - /** - * Incorrect handling of non-ISO 8859-1 characters in Windows ANSII Code Page 1252 - */ - @Test - public void bug27394() throws Exception { - HSSFWorkbook wb = openSample("27394.xls"); - assertEquals("\u0161\u017E", wb.getSheetName(0)); - assertEquals("\u0161\u017E\u010D\u0148\u0159", wb.getSheetName(1)); - HSSFSheet sheet = wb.getSheetAt(0); - - assertEquals("\u0161\u017E", sheet.getRow(0).getCell(0).getStringCellValue()); - assertEquals("\u0161\u017E\u010D\u0148\u0159", sheet.getRow(1).getCell(0).getStringCellValue()); - wb.close(); - } - - /** - * Multiple calls of HSSFWorkbook.write result in corrupted xls - */ - @Test - public void bug32191() throws IOException { - HSSFWorkbook wb = openSample("27394.xls"); - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - wb.write(out); - out.close(); - int size1 = out.size(); - - out = new ByteArrayOutputStream(); - wb.write(out); - out.close(); - int size2 = out.size(); - - assertEquals(size1, size2); - out = new ByteArrayOutputStream(); - wb.write(out); - out.close(); - int size3 = out.size(); - assertEquals(size2, size3); - wb.close(); - } - - /** - * java.io.IOException: block[ 0 ] already removed - * (is an excel 95 file though) - */ - @Test - public void bug46904() throws Exception { - try { - OPOIFSFileSystem fs = new OPOIFSFileSystem( - HSSFITestDataProvider.instance.openWorkbookStream("46904.xls")); - new HSSFWorkbook(fs.getRoot(), false).close(); - fail("Should catch exception here"); - } catch(OldExcelFormatException e) { - assertTrue(e.getMessage().startsWith( - "The supplied spreadsheet seems to be Excel" - )); - } - try { - NPOIFSFileSystem fs = new NPOIFSFileSystem( - HSSFITestDataProvider.instance.openWorkbookStream("46904.xls")); - try { - new HSSFWorkbook(fs.getRoot(), false).close(); - fail("Should catch exception here"); - } finally { - fs.close(); - } - } catch(OldExcelFormatException e) { - assertTrue(e.getMessage().startsWith( - "The supplied spreadsheet seems to be Excel" - )); - } - } - - /** - * java.lang.NegativeArraySizeException reading long - * non-unicode data for a name record - */ - @Test - public void bug47034() throws Exception { - HSSFWorkbook wb = openSample("47034.xls"); - assertEquals(893, wb.getNumberOfNames()); - assertEquals("Matthew\\Matthew11_1\\Matthew2331_1\\Matthew2351_1\\Matthew2361_1___lab", wb.getNameName(300)); - wb.close(); - } - - /** - * HSSFRichTextString.length() returns negative for really long strings. - * The test file was created in OpenOffice 3.0 as Excel does not allow cell text longer than 32,767 characters - */ - @Test - public void bug46368() throws Exception { - HSSFWorkbook wb = openSample("46368.xls"); - HSSFSheet s = wb.getSheetAt(0); - HSSFCell cell1 = s.getRow(0).getCell(0); - assertEquals(32770, cell1.getStringCellValue().length()); - - HSSFCell cell2 = s.getRow(2).getCell(0); - assertEquals(32766, cell2.getStringCellValue().length()); - wb.close(); - } - - /** - * Short records on certain sheets with charts in them - */ - @Test - public void bug48180() throws Exception { - HSSFWorkbook wb = openSample("48180.xls"); - - HSSFSheet s = wb.getSheetAt(0); - HSSFCell cell1 = s.getRow(0).getCell(0); - assertEquals("test ", cell1.getStringCellValue()); - - HSSFCell cell2 = s.getRow(0).getCell(1); - assertEquals(1.0, cell2.getNumericCellValue(), 0.0); - wb.close(); - } - - /** - * POI 3.5 beta 7 can not read excel file contain list box (Form Control) - */ - @Test - public void bug47701() { - openSample("47701.xls"); - } - - @Test - public void bug48026() { - openSample("48026.xls"); - } - - @Test - public void bug47251() { - // Firstly, try with one that triggers on InterfaceHdrRecord - openSample("47251.xls"); - - // Now with one that triggers on NoteRecord - openSample("47251_1.xls"); - } - - /** - * Round trip a file with an unusual UnicodeString/ExtRst record parts - */ - @Test - public void bug47847() throws Exception { - HSSFWorkbook wb1 = openSample("47847.xls"); - assertEquals(3, wb1.getNumberOfSheets()); - - // Find the SST record - UnicodeString withExt = wb1.getWorkbook().getSSTString(0); - UnicodeString withoutExt = wb1.getWorkbook().getSSTString(31); - - assertEquals("O:Alloc:Qty", withExt.getString()); - assertTrue((withExt.getOptionFlags() & 0x0004) == 0x0004); - - assertEquals("RT", withoutExt.getString()); - assertTrue((withoutExt.getOptionFlags() & 0x0004) == 0x0000); - - // Something about continues... - - - // Write out and re-read - HSSFWorkbook wb2 = writeOutAndReadBack(wb1); - wb1.close(); - assertEquals(3, wb2.getNumberOfSheets()); - - // Check it's the same now - withExt = wb2.getWorkbook().getSSTString(0); - withoutExt = wb2.getWorkbook().getSSTString(31); - - assertEquals("O:Alloc:Qty", withExt.getString()); - assertTrue((withExt.getOptionFlags() & 0x0004) == 0x0004); - - assertEquals("RT", withoutExt.getString()); - assertTrue((withoutExt.getOptionFlags() & 0x0004) == 0x0000); - wb2.close(); - } - - /** - * Problem with cloning a sheet with a chart - * contained in it. - */ - @Test - public void bug49096() throws Exception { - HSSFWorkbook wb1 = openSample("49096.xls"); - assertEquals(1, wb1.getNumberOfSheets()); - - assertNotNull(wb1.getSheetAt(0)); - wb1.cloneSheet(0); - assertEquals(2, wb1.getNumberOfSheets()); - - HSSFWorkbook wb2 = writeOutAndReadBack(wb1); - wb1.close(); - assertEquals(2, wb2.getNumberOfSheets()); - wb2.close(); - } - - /** - * Newly created sheets need to get a - * proper TabID, otherwise print setup - * gets confused on them. - * Also ensure that print setup refs are - * by reference not value - */ - @Test - public void bug46664() throws Exception { - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet sheet = wb1.createSheet("new_sheet"); - HSSFRow row = sheet.createRow((short)0); - row.createCell(0).setCellValue(new HSSFRichTextString("Column A")); - row.createCell(1).setCellValue(new HSSFRichTextString("Column B")); - row.createCell(2).setCellValue(new HSSFRichTextString("Column C")); - row.createCell(3).setCellValue(new HSSFRichTextString("Column D")); - row.createCell(4).setCellValue(new HSSFRichTextString("Column E")); - row.createCell(5).setCellValue(new HSSFRichTextString("Column F")); - - //set print area from column a to column c (on first row) - wb1.setPrintArea( - 0, //sheet index - 0, //start column - 2, //end column - 0, //start row - 0 //end row - ); - - HSSFWorkbook wb2 = writeOutAndReadBack(wb1); - wb1.close(); - - // Ensure the tab index - TabIdRecord tr = null; - for(Record r : wb2.getWorkbook().getRecords()) { - if(r instanceof TabIdRecord) { - tr = (TabIdRecord)r; - } - } - assertNotNull(tr); - assertEquals(1, tr._tabids.length); - assertEquals(0, tr._tabids[0]); - - // Ensure the print setup - assertEquals("new_sheet!$A$1:$C$1", wb2.getPrintArea(0)); - HSSFName printArea = wb2.getName("Print_Area"); - assertNotNull(printArea); - assertEquals("new_sheet!$A$1:$C$1", printArea.getRefersToFormula()); - - // Needs reference not value - NameRecord nr = wb2.getWorkbook().getNameRecord( - wb2.getNameIndex("Print_Area") - ); - assertEquals("Print_Area", nr.getNameText()); - assertEquals(1, nr.getNameDefinition().length); - assertEquals( - "new_sheet!$A$1:$C$1", - ((Area3DPtg)nr.getNameDefinition()[0]).toFormulaString(HSSFEvaluationWorkbook.create(wb2)) - ); - assertEquals('R', nr.getNameDefinition()[0].getRVAType()); - wb2.close(); - } - - /** - * Problems with formula references to - * sheets via URLs - */ - @Test - public void bug45970() throws Exception { - HSSFWorkbook wb1 = openSample("FormulaRefs.xls"); - assertEquals(3, wb1.getNumberOfSheets()); - - HSSFSheet s = wb1.getSheetAt(0); - HSSFRow row; - - row = s.getRow(0); - assertEquals(CellType.NUMERIC, row.getCell(1).getCellTypeEnum()); - assertEquals(112.0, row.getCell(1).getNumericCellValue(), 0); - - row = s.getRow(1); - assertEquals(CellType.FORMULA, row.getCell(1).getCellTypeEnum()); - assertEquals("B1", row.getCell(1).getCellFormula()); - assertEquals(112.0, row.getCell(1).getNumericCellValue(), 0); - - row = s.getRow(2); - assertEquals(CellType.FORMULA, row.getCell(1).getCellTypeEnum()); - assertEquals("Sheet1!B1", row.getCell(1).getCellFormula()); - assertEquals(112.0, row.getCell(1).getNumericCellValue(), 0); - - row = s.getRow(3); - assertEquals(CellType.FORMULA, row.getCell(1).getCellTypeEnum()); - assertEquals("[Formulas2.xls]Sheet1!B2", row.getCell(1).getCellFormula()); - assertEquals(112.0, row.getCell(1).getNumericCellValue(), 0); - - row = s.getRow(4); - assertEquals(CellType.FORMULA, row.getCell(1).getCellTypeEnum()); - assertEquals("'[$http://gagravarr.org/FormulaRefs.xls]Sheet1'!B1", row.getCell(1).getCellFormula()); - assertEquals(112.0, row.getCell(1).getNumericCellValue(), 0); - - // Link our new workbook - Workbook externalWb1 = new HSSFWorkbook(); - externalWb1.createSheet("Sheet1"); - wb1.linkExternalWorkbook("$http://gagravarr.org/FormulaRefs2.xls", externalWb1); - - // Change 4 - row.getCell(1).setCellFormula("'[$http://gagravarr.org/FormulaRefs2.xls]Sheet1'!B2"); - row.getCell(1).setCellValue(123.0); - - // Link our new workbook - Workbook externalWb2 = new HSSFWorkbook(); - externalWb2.createSheet("Sheet1"); - wb1.linkExternalWorkbook("$http://example.com/FormulaRefs.xls", externalWb2); - - // Add 5 - row = s.createRow(5); - row.createCell(1, CellType.FORMULA); - row.getCell(1).setCellFormula("'[$http://example.com/FormulaRefs.xls]Sheet1'!B1"); - row.getCell(1).setCellValue(234.0); - - // Re-test - HSSFWorkbook wb2 = writeOutAndReadBack(wb1); - wb1.close(); - s = wb2.getSheetAt(0); - - row = s.getRow(0); - assertEquals(CellType.NUMERIC, row.getCell(1).getCellTypeEnum()); - assertEquals(112.0, row.getCell(1).getNumericCellValue(),0); - - row = s.getRow(1); - assertEquals(CellType.FORMULA, row.getCell(1).getCellTypeEnum()); - assertEquals("B1", row.getCell(1).getCellFormula()); - assertEquals(112.0, row.getCell(1).getNumericCellValue(), 0); - - row = s.getRow(2); - assertEquals(CellType.FORMULA, row.getCell(1).getCellTypeEnum()); - assertEquals("Sheet1!B1", row.getCell(1).getCellFormula()); - assertEquals(112.0, row.getCell(1).getNumericCellValue(), 0); - - row = s.getRow(3); - assertEquals(CellType.FORMULA, row.getCell(1).getCellTypeEnum()); - assertEquals("[Formulas2.xls]Sheet1!B2", row.getCell(1).getCellFormula()); - assertEquals(112.0, row.getCell(1).getNumericCellValue(), 0); - - row = s.getRow(4); - assertEquals(CellType.FORMULA, row.getCell(1).getCellTypeEnum()); - assertEquals("'[$http://gagravarr.org/FormulaRefs2.xls]Sheet1'!B2", row.getCell(1).getCellFormula()); - assertEquals(123.0, row.getCell(1).getNumericCellValue(), 0); - - row = s.getRow(5); - assertEquals(CellType.FORMULA, row.getCell(1).getCellTypeEnum()); - assertEquals("'[$http://example.com/FormulaRefs.xls]Sheet1'!B1", row.getCell(1).getCellFormula()); - assertEquals(234.0, row.getCell(1).getNumericCellValue(), 0); - - wb2.close(); - } - - /** - * Test for a file with NameRecord with NameCommentRecord comments - */ - @Test - public void bug49185() throws Exception { - HSSFWorkbook wb1 = openSample("49185.xls"); - Name name = wb1.getName("foobarName"); - assertNotNull(name); - assertEquals("This is a comment", name.getComment()); - - // Rename the name, comment comes with it - name.setNameName("ChangedName"); - assertEquals("This is a comment", name.getComment()); - - // Save and re-check - HSSFWorkbook wb2 = writeOutAndReadBack(wb1); - wb1.close(); - name = wb2.getName("ChangedName"); - assertNotNull(name); - assertEquals("This is a comment", name.getComment()); - - // Now try to change it - name.setComment("Changed Comment"); - assertEquals("Changed Comment", name.getComment()); - - // Save and re-check - HSSFWorkbook wb3 = writeOutAndReadBack(wb2); - wb2.close(); - name = wb3.getName("ChangedName"); - assertNotNull(name); - assertEquals("Changed Comment", name.getComment()); - wb3.close(); - } - - /** - * Vertically aligned text - */ - @Test - public void bug49524() throws Exception { - HSSFWorkbook wb1 = openSample("49524.xls"); - Sheet s = wb1.getSheetAt(0); - Row r = s.getRow(0); - Cell rotated = r.getCell(0); - Cell normal = r.getCell(1); - - // Check the current ones - assertEquals(0, normal.getCellStyle().getRotation()); - assertEquals(0xff, rotated.getCellStyle().getRotation()); - - // Add a new style, also rotated - CellStyle cs = wb1.createCellStyle(); - cs.setRotation((short)0xff); - Cell nc = r.createCell(2); - nc.setCellValue("New Rotated Text"); - nc.setCellStyle(cs); - assertEquals(0xff, nc.getCellStyle().getRotation()); - - // Write out and read back - HSSFWorkbook wb2 = writeOutAndReadBack(wb1); - wb1.close(); - - // Re-check - s = wb2.getSheetAt(0); - r = s.getRow(0); - rotated = r.getCell(0); - normal = r.getCell(1); - nc = r.getCell(2); - - assertEquals(0, normal.getCellStyle().getRotation()); - assertEquals(0xff, rotated.getCellStyle().getRotation()); - assertEquals(0xff, nc.getCellStyle().getRotation()); - wb2.close(); - } - - /** - * Setting the user style name on custom styles - */ - @Test - public void bug49689() throws Exception { - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet s = wb1.createSheet("Test"); - HSSFRow r = s.createRow(0); - HSSFCell c = r.createCell(0); - - HSSFCellStyle cs1 = wb1.createCellStyle(); - HSSFCellStyle cs2 = wb1.createCellStyle(); - HSSFCellStyle cs3 = wb1.createCellStyle(); - - assertEquals(21, cs1.getIndex()); - cs1.setUserStyleName("Testing"); - - assertEquals(22, cs2.getIndex()); - cs2.setUserStyleName("Testing 2"); - - assertEquals(23, cs3.getIndex()); - cs3.setUserStyleName("Testing 3"); - - // Set one - c.setCellStyle(cs1); - - // Write out and read back - HSSFWorkbook wb2 = writeOutAndReadBack(wb1); - wb1.close(); - - // Re-check - assertEquals("Testing", wb2.getCellStyleAt((short)21).getUserStyleName()); - assertEquals("Testing 2", wb2.getCellStyleAt((short)22).getUserStyleName()); - assertEquals("Testing 3", wb2.getCellStyleAt((short)23).getUserStyleName()); - - wb2.close(); - } - - @Test - public void bug49751() throws Exception { - HSSFWorkbook wb = openSample("49751.xls"); - int numCellStyles = wb.getNumCellStyles(); - List namedStyles = Arrays.asList( - "20% - Accent1", "20% - Accent2", "20% - Accent3", "20% - Accent4", "20% - Accent5", - "20% - Accent6", "40% - Accent1", "40% - Accent2", "40% - Accent3", "40% - Accent4", - "40% - Accent5", "40% - Accent6", "60% - Accent1", "60% - Accent2", "60% - Accent3", - "60% - Accent4", "60% - Accent5", "60% - Accent6", "Accent1", "Accent2", "Accent3", - "Accent4", "Accent5", "Accent6", "Bad", "Calculation", "Check Cell", "Explanatory Text", - "Good", "Heading 1", "Heading 2", "Heading 3", "Heading 4", "Input", "Linked Cell", - "Neutral", "Note", "Output", "Title", "Total", "Warning Text"); - - List collecteddStyles = new ArrayList(); - for (int i = 0; i < numCellStyles; i++) { - HSSFCellStyle cellStyle = wb.getCellStyleAt(i); - String styleName = cellStyle.getUserStyleName(); - if (styleName != null) { - collecteddStyles.add(styleName); - } - } - assertTrue(namedStyles.containsAll(collecteddStyles)); - wb.close(); - } - - /** - * Regression with the PageSettingsBlock - */ - @Test - public void bug49931() throws Exception { - HSSFWorkbook wb = openSample("49931.xls"); - assertEquals(1, wb.getNumberOfSheets()); - assertEquals("Foo", wb.getSheetAt(0).getRow(0).getCell(0).getRichStringCellValue().toString()); - wb.close(); - } - - /** - * Missing left/right/centre options on a footer - */ - @Test - public void bug48325() throws Exception { - HSSFWorkbook wb = openSample("48325.xls"); - HSSFSheet sh = wb.getSheetAt(0); - HSSFFooter f = sh.getFooter(); - - // Will show as the center, as that is what excel does - // with an invalid footer lacking left/right/center details - assertEquals("Left text should be empty", "", f.getLeft()); - assertEquals("Right text should be empty", "", f.getRight()); - assertEquals( - "Center text should contain the illegal value", - "BlahBlah blah blah ", f.getCenter() - ); - wb.close(); - } - - /** - * IllegalStateException received when creating Data validation in sheet with macro - */ - @Test - public void bug50020() throws Exception { - HSSFWorkbook wb = openSample("50020.xls"); - writeOutAndReadBack(wb).close(); - wb.close(); - } - - @Test - public void bug50426() throws Exception { - HSSFWorkbook wb = openSample("50426.xls"); - writeOutAndReadBack(wb).close(); - wb.close(); - } - - /** - * Last row number when shifting rows - */ - @Test - public void bug50416LastRowNumber() throws IOException { - // Create the workbook with 1 sheet which contains 3 rows - HSSFWorkbook workbook = new HSSFWorkbook(); - Sheet sheet = workbook.createSheet("Bug50416"); - Row row1 = sheet.createRow(0); - Cell cellA_1 = row1.createCell(0,CellType.STRING); - cellA_1.setCellValue("Cell A,1"); - Row row2 = sheet.createRow(1); - Cell cellA_2 = row2.createCell(0,CellType.STRING); - cellA_2.setCellValue("Cell A,2"); - Row row3 = sheet.createRow(2); - Cell cellA_3 = row3.createCell(0,CellType.STRING); - cellA_3.setCellValue("Cell A,3"); - - // Test the last Row number it currently correct - assertEquals(2, sheet.getLastRowNum()); - - // Shift the first row to the end - sheet.shiftRows(0, 0, 3); - assertEquals(3, sheet.getLastRowNum()); - assertEquals(-1, sheet.getRow(0).getLastCellNum()); - assertEquals("Cell A,2", sheet.getRow(1).getCell(0).getStringCellValue()); - assertEquals("Cell A,3", sheet.getRow(2).getCell(0).getStringCellValue()); - assertEquals("Cell A,1", sheet.getRow(3).getCell(0).getStringCellValue()); - - // Shift the 2nd row up to the first one - sheet.shiftRows(1, 1, -1); - assertEquals(3, sheet.getLastRowNum()); - assertEquals("Cell A,2", sheet.getRow(0).getCell(0).getStringCellValue()); - assertEquals(-1, sheet.getRow(1).getLastCellNum()); - assertEquals("Cell A,3", sheet.getRow(2).getCell(0).getStringCellValue()); - assertEquals("Cell A,1", sheet.getRow(3).getCell(0).getStringCellValue()); - - // Shift the 4th row up into the gap in the 3rd row - sheet.shiftRows(3, 3, -2); - assertEquals(2, sheet.getLastRowNum()); - assertEquals("Cell A,2", sheet.getRow(0).getCell(0).getStringCellValue()); - assertEquals("Cell A,1", sheet.getRow(1).getCell(0).getStringCellValue()); - assertEquals("Cell A,3", sheet.getRow(2).getCell(0).getStringCellValue()); - assertEquals(-1, sheet.getRow(3).getLastCellNum()); - - // Now zap the empty 4th row - won't do anything - sheet.removeRow(sheet.getRow(3)); - - // Test again the last row number which should be 2 - assertEquals(2, sheet.getLastRowNum()); - assertEquals("Cell A,2", sheet.getRow(0).getCell(0).getStringCellValue()); - assertEquals("Cell A,1", sheet.getRow(1).getCell(0).getStringCellValue()); - assertEquals("Cell A,3", sheet.getRow(2).getCell(0).getStringCellValue()); - - workbook.close(); - } - - /** - * If you send a file between Excel and OpenOffice enough, something - * will turn the "General" format into "GENERAL" - */ - @Test - public void bug50756() throws Exception { - HSSFWorkbook wb = openSample("50756.xls"); - HSSFSheet s = wb.getSheetAt(0); - HSSFRow r17 = s.getRow(16); - HSSFRow r18 = s.getRow(17); - HSSFDataFormatter df = new HSSFDataFormatter(); - - assertEquals(10.0, r17.getCell(1).getNumericCellValue(), 0); - assertEquals(20.0, r17.getCell(2).getNumericCellValue(), 0); - assertEquals(20.0, r17.getCell(3).getNumericCellValue(), 0); - assertEquals("GENERAL", r17.getCell(1).getCellStyle().getDataFormatString()); - assertEquals("GENERAL", r17.getCell(2).getCellStyle().getDataFormatString()); - assertEquals("GENERAL", r17.getCell(3).getCellStyle().getDataFormatString()); - assertEquals("10", df.formatCellValue(r17.getCell(1))); - assertEquals("20", df.formatCellValue(r17.getCell(2))); - assertEquals("20", df.formatCellValue(r17.getCell(3))); - - assertEquals(16.0, r18.getCell(1).getNumericCellValue(), 0); - assertEquals(35.0, r18.getCell(2).getNumericCellValue(), 0); - assertEquals(123.0, r18.getCell(3).getNumericCellValue(), 0); - assertEquals("GENERAL", r18.getCell(1).getCellStyle().getDataFormatString()); - assertEquals("GENERAL", r18.getCell(2).getCellStyle().getDataFormatString()); - assertEquals("GENERAL", r18.getCell(3).getCellStyle().getDataFormatString()); - assertEquals("16", df.formatCellValue(r18.getCell(1))); - assertEquals("35", df.formatCellValue(r18.getCell(2))); - assertEquals("123", df.formatCellValue(r18.getCell(3))); - wb.close(); - } - - /** - * A protected sheet with comments, when written out by - * POI, ends up upsetting excel. - * TODO Identify the cause and add extra asserts for - * the bit excel cares about - */ - @Test - public void bug50833() throws Exception { - Biff8EncryptionKey.setCurrentUserPassword(null); - - HSSFWorkbook wb1 = openSample("50833.xls"); - HSSFSheet s = wb1.getSheetAt(0); - assertEquals("Sheet1", s.getSheetName()); - assertEquals(false, s.getProtect()); - - HSSFCell c = s.getRow(0).getCell(0); - assertEquals("test cell value", c.getRichStringCellValue().getString()); - - HSSFComment cmt = c.getCellComment(); - assertNotNull(cmt); - assertEquals("Robert Lawrence", cmt.getAuthor()); - assertEquals("Robert Lawrence:\ntest comment", cmt.getString().getString()); - - // Reload - HSSFWorkbook wb2 = writeOutAndReadBack(wb1); - wb1.close(); - s = wb2.getSheetAt(0); - c = s.getRow(0).getCell(0); - - // Re-check the comment - cmt = c.getCellComment(); - assertNotNull(cmt); - assertEquals("Robert Lawrence", cmt.getAuthor()); - assertEquals("Robert Lawrence:\ntest comment", cmt.getString().getString()); - - // TODO Identify what excel doesn't like, and check for that - wb2.close(); - } - - @Test - public void bug50779() throws Exception { - HSSFWorkbook wb1 = openSample("50779_1.xls"); - writeOutAndReadBack(wb1).close(); - wb1.close(); - - HSSFWorkbook wb2 = openSample("50779_2.xls"); - writeOutAndReadBack(wb2).close(); - wb2.close(); - } - - /** - * The spec says that ChartEndObjectRecord has 6 reserved - * bytes on the end, but we sometimes find files without... - */ - @Test - public void bug50939() throws Exception { - HSSFWorkbook wb = openSample("50939.xls"); - assertEquals(2, wb.getNumberOfSheets()); - wb.close(); - } - - @Test - public void bug49219() throws Exception { - HSSFWorkbook wb = openSample("49219.xls"); - assertEquals(1, wb.getNumberOfSheets()); - assertEquals("DGATE", wb.getSheetAt(0).getRow(1).getCell(0).getStringCellValue()); - wb.close(); - } - - @Test - public void bug48968() throws Exception { - TimeZone userTimeZone = LocaleUtil.getUserTimeZone(); - LocaleUtil.setUserTimeZone(TimeZone.getTimeZone("CET")); - try { - HSSFWorkbook wb = openSample("48968.xls"); - assertEquals(1, wb.getNumberOfSheets()); - - DataFormatter fmt = new DataFormatter(); - - // Check the dates - HSSFSheet s = wb.getSheetAt(0); - Cell cell_d20110325 = s.getRow(0).getCell(0); - Cell cell_d19000102 = s.getRow(11).getCell(0); - Cell cell_d19000100 = s.getRow(21).getCell(0); - assertEquals(s.getRow(0).getCell(3).getStringCellValue(), fmt.formatCellValue(cell_d20110325)); - assertEquals(s.getRow(11).getCell(3).getStringCellValue(), fmt.formatCellValue(cell_d19000102)); - // There is no such thing as 00/01/1900... - assertEquals("00/01/1900 06:14:24", s.getRow(21).getCell(3).getStringCellValue()); - assertEquals("31/12/1899 06:14:24", fmt.formatCellValue(cell_d19000100)); - - // Check the cached values - assertEquals("HOUR(A1)", s.getRow(5).getCell(0).getCellFormula()); - assertEquals(11.0, s.getRow(5).getCell(0).getNumericCellValue(), 0); - assertEquals("MINUTE(A1)", s.getRow(6).getCell(0).getCellFormula()); - assertEquals(39.0, s.getRow(6).getCell(0).getNumericCellValue(), 0); - assertEquals("SECOND(A1)", s.getRow(7).getCell(0).getCellFormula()); - assertEquals(54.0, s.getRow(7).getCell(0).getNumericCellValue(), 0); - - // Re-evaluate and check - HSSFFormulaEvaluator.evaluateAllFormulaCells(wb); - assertEquals("HOUR(A1)", s.getRow(5).getCell(0).getCellFormula()); - assertEquals(11.0, s.getRow(5).getCell(0).getNumericCellValue(), 0); - assertEquals("MINUTE(A1)", s.getRow(6).getCell(0).getCellFormula()); - assertEquals(39.0, s.getRow(6).getCell(0).getNumericCellValue(), 0); - assertEquals("SECOND(A1)", s.getRow(7).getCell(0).getCellFormula()); - assertEquals(54.0, s.getRow(7).getCell(0).getNumericCellValue(), 0); - - // Push the time forward a bit and check - double date = s.getRow(0).getCell(0).getNumericCellValue(); - s.getRow(0).getCell(0).setCellValue(date + 1.26); - - HSSFFormulaEvaluator.evaluateAllFormulaCells(wb); - assertEquals("HOUR(A1)", s.getRow(5).getCell(0).getCellFormula()); - assertEquals(11.0+6.0, s.getRow(5).getCell(0).getNumericCellValue(), 0); - assertEquals("MINUTE(A1)", s.getRow(6).getCell(0).getCellFormula()); - assertEquals(39.0+14.0+1, s.getRow(6).getCell(0).getNumericCellValue(), 0); - assertEquals("SECOND(A1)", s.getRow(7).getCell(0).getCellFormula()); - assertEquals(54.0+24.0-60, s.getRow(7).getCell(0).getNumericCellValue(), 0); - - wb.close(); - } finally { - LocaleUtil.setUserTimeZone(userTimeZone); - } - } - - - /** - * Mixture of Ascii and Unicode strings in a - * NameComment record - */ - @Test - public void bug51143() throws Exception { - HSSFWorkbook wb1 = openSample("51143.xls"); - assertEquals(1, wb1.getNumberOfSheets()); - HSSFWorkbook wb2 = writeOutAndReadBack(wb1); - wb1.close(); - assertEquals(1, wb2.getNumberOfSheets()); - wb2.close(); - } - - /** - * File with exactly 256 data blocks (+header block) - * shouldn't break on POIFS loading - */ - @SuppressWarnings("resource") - @Test - public void bug51461() throws Exception { - byte[] data = HSSFITestDataProvider.instance.getTestDataFileContent("51461.xls"); - - HSSFWorkbook wbPOIFS = new HSSFWorkbook(new POIFSFileSystem( - new ByteArrayInputStream(data)).getRoot(), false); - HSSFWorkbook wbNPOIFS = new HSSFWorkbook(new NPOIFSFileSystem( - new ByteArrayInputStream(data)).getRoot(), false); - - assertEquals(2, wbPOIFS.getNumberOfSheets()); - assertEquals(2, wbNPOIFS.getNumberOfSheets()); - } - - /** - * Large row numbers and NPOIFS vs POIFS - */ - @SuppressWarnings("resource") - @Test - public void bug51535() throws Exception { - byte[] data = HSSFITestDataProvider.instance.getTestDataFileContent("51535.xls"); - - HSSFWorkbook wbPOIFS = new HSSFWorkbook(new POIFSFileSystem( - new ByteArrayInputStream(data)).getRoot(), false); - HSSFWorkbook wbNPOIFS = new HSSFWorkbook(new NPOIFSFileSystem( - new ByteArrayInputStream(data)).getRoot(), false); - - for(HSSFWorkbook wb : new HSSFWorkbook[] {wbPOIFS, wbNPOIFS}) { - assertEquals(3, wb.getNumberOfSheets()); - - // Check directly - HSSFSheet s = wb.getSheetAt(0); - assertEquals("Top Left Cell", s.getRow(0).getCell(0).getStringCellValue()); - assertEquals("Top Right Cell", s.getRow(0).getCell(255).getStringCellValue()); - assertEquals("Bottom Left Cell", s.getRow(65535).getCell(0).getStringCellValue()); - assertEquals("Bottom Right Cell", s.getRow(65535).getCell(255).getStringCellValue()); - - // Extract and check - ExcelExtractor ex = new ExcelExtractor(wb); - String text = ex.getText(); - assertTrue(text.contains("Top Left Cell")); - assertTrue(text.contains("Top Right Cell")); - assertTrue(text.contains("Bottom Left Cell")); - assertTrue(text.contains("Bottom Right Cell")); - ex.close(); - } - } - - @Test - public void bug51670() throws Exception { - HSSFWorkbook wb = openSample("51670.xls"); - writeOutAndReadBack(wb).close(); - wb.close(); - } - - /** - * Sum across multiple workbooks - * eg =SUM($Sheet2.A1:$Sheet3.A1) - */ - @Test - public void test48703() throws Exception { - HSSFWorkbook wb = openSample("48703.xls"); - assertEquals(3, wb.getNumberOfSheets()); - - // Check reading the formula - Sheet sheet = wb.getSheetAt(0); - Row r = sheet.getRow(0); - Cell c = r.getCell(0); - - assertEquals("SUM(Sheet2:Sheet3!A1)", c.getCellFormula()); - assertEquals(4.0, c.getNumericCellValue(), 0); - - // Check the evaluated result - HSSFFormulaEvaluator eval = new HSSFFormulaEvaluator(wb); - eval.evaluateFormulaCellEnum(c); - assertEquals(4.0, c.getNumericCellValue(), 0); - wb.close(); - } - - /** - * Normally encrypted files have BOF then FILEPASS, but - * some may squeeze a WRITEPROTECT in the middle - */ - @Test(expected=EncryptedDocumentException.class) - public void bug51832() { - openSample("51832.xls"); - } - - @Test - public void bug49896() throws Exception { - HSSFWorkbook wb = openSample("49896.xls"); - HSSFCell cell = wb.getSheetAt(0).getRow(1).getCell(1); - String PATH_SEPARATOR = System.getProperty("file.separator"); - assertEquals("VLOOKUP(A2,'[C:Documents and Settings" + PATH_SEPARATOR+"Yegor"+PATH_SEPARATOR - +"My Documents"+PATH_SEPARATOR+"csco.xls]Sheet1'!$A$2:$B$3,2,FALSE)", - cell.getCellFormula()); - wb.close(); - } - - @Test - public void bug49529() throws Exception { - // user code reported in Bugzilla #49529 - HSSFWorkbook wb = openSample("49529.xls"); - wb.getSheetAt(0).createDrawingPatriarch(); - // prior to the fix the line below failed with - // java.lang.IllegalStateException: EOF - next record not available - wb.cloneSheet(0); - - // make sure we are still readable - writeOutAndReadBack(wb).close(); - - wb.close(); - } - - /** - * Note - part of this test is still failing, see - * {@link TestUnfixedBugs#test49612()} - */ - @Test - public void bug49612_part() throws IOException { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("49612.xls"); - HSSFSheet sh = wb.getSheetAt(0); - HSSFRow row = sh.getRow(0); - HSSFCell c1 = row.getCell(2); - HSSFCell d1 = row.getCell(3); - HSSFCell e1 = row.getCell(2); - - assertEquals("SUM(BOB+JIM)", c1.getCellFormula()); - - // Problem 1: See TestUnfixedBugs#test49612() - // Problem 2: TestUnfixedBugs#test49612() - - // Problem 3: These used to fail, now pass - HSSFFormulaEvaluator eval = new HSSFFormulaEvaluator(wb); - assertEquals("evaluating c1", 30.0, eval.evaluate(c1).getNumberValue(), 0.001); - assertEquals("evaluating d1", 30.0, eval.evaluate(d1).getNumberValue(), 0.001); - assertEquals("evaluating e1", 30.0, eval.evaluate(e1).getNumberValue(), 0.001); - wb.close(); - } - - @Test - public void bug51675() throws Exception { - final List list = new ArrayList(); - HSSFWorkbook wb = openSample("51675.xls"); - HSSFSheet sh = wb.getSheetAt(0); - InternalSheet ish = HSSFTestHelper.getSheetForTest(sh); - PageSettingsBlock psb = (PageSettingsBlock) ish.getRecords().get(13); - psb.visitContainedRecords(new RecordAggregate.RecordVisitor() { - @Override - public void visitRecord(Record r) { - list.add(r.getSid()); - } - }); - assertTrue(list.get(list.size()-1).intValue() == UnknownRecord.BITMAP_00E9); - assertTrue(list.get(list.size()-2).intValue() == UnknownRecord.HEADER_FOOTER_089C); - wb.close(); - } - - @Test - public void bug52272() throws IOException{ - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sh = wb.createSheet(); - HSSFPatriarch p = sh.createDrawingPatriarch(); - - HSSFSimpleShape s = p.createSimpleShape(new HSSFClientAnchor()); - s.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE); - - HSSFSheet sh2 = wb.cloneSheet(0); - assertNotNull(sh2.getDrawingPatriarch()); - - wb.close(); - } - - @Test - public void bug53432() throws IOException{ - Workbook wb1 = new HSSFWorkbook(); //or new HSSFWorkbook(); - wb1.addPicture(new byte[]{123,22}, Workbook.PICTURE_TYPE_JPEG); - assertEquals(wb1.getAllPictures().size(), 1); - wb1.close(); - - wb1.close(); - wb1 = new HSSFWorkbook(); - - Workbook wb2 = writeOutAndReadBack((HSSFWorkbook) wb1); - wb1.close(); - assertEquals(wb2.getAllPictures().size(), 0); - wb2.addPicture(new byte[]{123,22}, Workbook.PICTURE_TYPE_JPEG); - assertEquals(wb2.getAllPictures().size(), 1); - - Workbook wb3 = writeOutAndReadBack((HSSFWorkbook) wb2); - wb2.close(); - assertEquals(wb3.getAllPictures().size(), 1); - - wb3.close(); - } - - @Test - public void bug46250() throws Exception { - HSSFWorkbook wb = openSample("46250.xls"); - Sheet sh = wb.getSheet("Template"); - Sheet cSh = wb.cloneSheet(wb.getSheetIndex(sh)); - - HSSFPatriarch patriarch = (HSSFPatriarch) cSh.createDrawingPatriarch(); - HSSFTextbox tb = (HSSFTextbox) patriarch.getChildren().get(2); - - tb.setString(new HSSFRichTextString("POI test")); - tb.setAnchor(new HSSFClientAnchor(0,0,0,0,(short)0,0,(short)10,10)); - - writeOutAndReadBack(wb).close(); - - wb.close(); - } - - @Test - public void bug53404() throws Exception { - HSSFWorkbook wb = openSample("53404.xls"); - Sheet sheet = wb.getSheet("test-sheet"); - int rowCount = sheet.getLastRowNum() + 1; - int newRows = 5; - Calendar cal = LocaleUtil.getLocaleCalendar(); - for (int r = rowCount; r < rowCount + newRows; r++) { - Row row = sheet.createRow((short) r); - row.createCell(0).setCellValue(1.03 * (r + 7)); - row.createCell(1).setCellValue(cal.getTime()); - row.createCell(2).setCellValue(cal); - row.createCell(3).setCellValue(String.format(Locale.ROOT, "row:%d/col:%d", r, 3)); - row.createCell(4).setCellValue(true); - row.createCell(5).setCellType(CellType.ERROR); - row.createCell(6).setCellValue("added cells."); - } - - writeOutAndReadBack(wb).close(); - - wb.close(); - } - - @Test - public void bug54016() throws Exception { - // This used to break - HSSFWorkbook wb = openSample("54016.xls"); - writeOutAndReadBack(wb).close(); - wb.close(); - } - - /** Row style information is 12 not 16 bits */ - @Test - public void bug49237() throws Exception { - Workbook wb = openSample("49237.xls"); - Sheet sheet = wb.getSheetAt(0); - Row row = sheet.getRow(0); - CellStyle rstyle = row.getRowStyle(); - assertNotNull(rstyle); - assertEquals(BorderStyle.DOUBLE, rstyle.getBorderBottomEnum()); - wb.close(); - } - - /** POI doesn't currently support the RC4 CryptoAPI encryption header structure */ - @Test(expected=EncryptedDocumentException.class) - public void bug35897() throws Exception { - // password is abc - try { - Biff8EncryptionKey.setCurrentUserPassword("abc"); - openSample("xor-encryption-abc.xls").close(); - } finally { - Biff8EncryptionKey.setCurrentUserPassword(null); - } - - // One using the only-recently-documented encryption header type 4, - // and the RC4 CryptoAPI encryption header structure - openSample("35897-type4.xls").close(); - } - - @Test - public void bug56450() throws Exception { - HSSFWorkbook wb = openSample("56450.xls"); - HSSFSheet sheet = wb.getSheetAt(0); - int comments = 0; - for (Row r : sheet) { - for (Cell c : r) { - if (c.getCellComment() != null) { - assertNotNull(c.getCellComment().getString().getString()); - comments++; - } - } - } - assertEquals(0, comments); - wb.close(); - } - - /** - * Files initially created with Excel 2010 can have >3 CF rules - */ - @Test - public void bug56482() throws Exception { - HSSFWorkbook wb = openSample("56482.xls"); - assertEquals(1, wb.getNumberOfSheets()); - - HSSFSheet sheet = wb.getSheetAt(0); - HSSFSheetConditionalFormatting cf = sheet.getSheetConditionalFormatting(); - - assertEquals(5, cf.getNumConditionalFormattings()); - wb.close(); - } - - @Test - public void bug56325() throws IOException { - HSSFWorkbook wb1; - POIFSFileSystem fs; - - File file = HSSFTestDataSamples.getSampleFile("56325.xls"); - InputStream stream = new FileInputStream(file); - try { - fs = new POIFSFileSystem(stream); - wb1 = new HSSFWorkbook(fs); - } finally { - stream.close(); - } - - assertEquals(3, wb1.getNumberOfSheets()); - wb1.removeSheetAt(0); - assertEquals(2, wb1.getNumberOfSheets()); - - HSSFWorkbook wb2 = writeOutAndReadBack(wb1); - wb1.close(); - fs.close(); - assertEquals(2, wb2.getNumberOfSheets()); - wb2.removeSheetAt(0); - assertEquals(1, wb2.getNumberOfSheets()); - wb2.removeSheetAt(0); - assertEquals(0, wb2.getNumberOfSheets()); - - HSSFWorkbook wb3 = writeOutAndReadBack(wb2); - wb2.close(); - - assertEquals(0, wb3.getNumberOfSheets()); - wb3.close(); - } - - @Test - public void bug56325a() throws IOException { - HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("56325a.xls"); - - HSSFSheet sheet = wb1.cloneSheet(2); - wb1.setSheetName(3, "Clone 1"); - sheet.setRepeatingRows(CellRangeAddress.valueOf("2:3")); - wb1.setPrintArea(3, "$A$4:$C$10"); - - sheet = wb1.cloneSheet(2); - wb1.setSheetName(4, "Clone 2"); - sheet.setRepeatingRows(CellRangeAddress.valueOf("2:3")); - wb1.setPrintArea(4, "$A$4:$C$10"); - - wb1.removeSheetAt(2); - - Workbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - assertEquals(4, wb2.getNumberOfSheets()); - wb2.close(); - wb1.close(); - } - - /** - * Formulas which reference named ranges, either in other - * sheets, or workbook scoped but in other workbooks. - * Used to fail with - * java.lang.RuntimeException: Unexpected eval class (org.apache.poi.ss.formula.eval.NameXEval) - */ - @Test - public void bug56737() throws IOException { - Workbook wb = openSample("56737.xls"); - - // Check the named range definitions - Name nSheetScope = wb.getName("NR_To_A1"); - Name nWBScope = wb.getName("NR_Global_B2"); - - assertNotNull(nSheetScope); - assertNotNull(nWBScope); - - assertEquals("Defines!$A$1", nSheetScope.getRefersToFormula()); - assertEquals("Defines!$B$2", nWBScope.getRefersToFormula()); - - // Check the different kinds of formulas - Sheet s = wb.getSheetAt(0); - Cell cRefSName = s.getRow(1).getCell(3); - Cell cRefWName = s.getRow(2).getCell(3); - - assertEquals("Defines!NR_To_A1", cRefSName.getCellFormula()); - - // TODO Correct this, so that the filename is shown too, see bug #56742 - // This is what Excel itself shows - //assertEquals("'56737.xls'!NR_Global_B2", cRefWName.getCellFormula()); - // TODO This isn't right, but it's what we currently generate.... - assertEquals("NR_Global_B2", cRefWName.getCellFormula()); - - // Try to evaluate them - FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator(); - assertEquals("Test A1", eval.evaluate(cRefSName).getStringValue()); - assertEquals(142, (int)eval.evaluate(cRefWName).getNumberValue()); - - // Try to evaluate everything - eval.evaluateAll(); - wb.close(); - } - - /** - * ClassCastException in HSSFOptimiser - StyleRecord cannot be cast to - * ExtendedFormatRecord when removing un-used styles - */ - @Test - public void bug54443() throws Exception { - HSSFWorkbook workbook = new HSSFWorkbook( ); - HSSFCellStyle style = workbook.createCellStyle(); - HSSFCellStyle newStyle = workbook.createCellStyle(); - - HSSFSheet mySheet = workbook.createSheet(); - HSSFRow row = mySheet.createRow(0); - HSSFCell cell = row.createCell(0); - - // Use style - cell.setCellStyle(style); - // Switch to newStyle, style is now un-used - cell.setCellStyle(newStyle); - - // Optimize - HSSFOptimiser.optimiseCellStyles(workbook); - workbook.close(); - } - - /** - * Intersection formula ranges, eg =(C2:D3 D3:E4) - */ - @Test - public void bug52111() throws Exception { - Workbook wb = openSample("Intersection-52111.xls"); - Sheet s = wb.getSheetAt(0); - assertFormula(wb, s.getRow(2).getCell(0), "(C2:D3 D3:E4)", "4.0"); - assertFormula(wb, s.getRow(6).getCell(0), "Tabelle2!E:E Tabelle2!$A11:$IV11", "5.0"); - assertFormula(wb, s.getRow(8).getCell(0), "Tabelle2!E:F Tabelle2!$A11:$IV12", null); - wb.close(); - } - - private void assertFormula(Workbook wb, Cell intF, String expectedFormula, String expectedResultOrNull) { - assertEquals(CellType.FORMULA, intF.getCellTypeEnum()); - if (null == expectedResultOrNull) { - assertEquals(CellType.ERROR, intF.getCachedFormulaResultTypeEnum()); - expectedResultOrNull = "#VALUE!"; - } - else { - assertEquals(CellType.NUMERIC, intF.getCachedFormulaResultTypeEnum()); - } - - assertEquals(expectedFormula, intF.getCellFormula()); - - // Check we can evaluate it correctly - FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator(); - assertEquals(expectedResultOrNull, eval.evaluate(intF).formatAsString()); - } - - @Test - public void bug42016() throws Exception { - Workbook wb = openSample("42016.xls"); - Sheet s = wb.getSheetAt(0); - for(int row = 0;row < 7;row++) { - assertEquals("A$1+B$1", s.getRow(row).getCell(2).getCellFormula()); - } - wb.close(); - } - - /** - * Unexpected record type (org.apache.poi.hssf.record.ColumnInfoRecord) - */ - @Test - public void bug53984() throws Exception { - Workbook wb = openSample("53984.xls"); - Sheet s = wb.getSheetAt(0); - assertEquals("International Communication Services SA", s.getRow(2).getCell(0).getStringCellValue()); - assertEquals("Saudi Arabia-Riyadh", s.getRow(210).getCell(0).getStringCellValue()); - wb.close(); - } - - /** - * Read, write, read for formulas point to cells in other files. - * See {@link #bug46670()} for the main test, this just - * covers reading an existing file and checking it. - * TODO Fix this so that it works - formulas are ending up as - * #REF when being changed - */ - @Test - @Ignore - public void bug46670_existing() throws Exception { - Sheet s; - Cell c; - - // Expected values - String refLocal = "'[refs/airport.xls]Sheet1'!$A$2"; - String refHttp = "'[9http://www.principlesofeconometrics.com/excel/airline.xls]Sheet1'!$A$2"; - - // Check we can read them correctly - HSSFWorkbook wb1 = openSample("46670_local.xls"); - s = wb1.getSheetAt(0); - assertEquals(refLocal, s.getRow(0).getCell(0).getCellFormula()); - wb1.close(); - - HSSFWorkbook wb2 = openSample("46670_http.xls"); - s = wb2.getSheetAt(0); - assertEquals(refHttp, s.getRow(0).getCell(0).getCellFormula()); - wb2.close(); - - // Now try to set them to the same values, and ensure that - // they end up as they did before, even with a save and re-load - HSSFWorkbook wb3 = openSample("46670_local.xls"); - s = wb3.getSheetAt(0); - c = s.getRow(0).getCell(0); - c.setCellFormula(refLocal); - assertEquals(refLocal, c.getCellFormula()); - - HSSFWorkbook wb4 = HSSFTestDataSamples.writeOutAndReadBack(wb3); - wb3.close(); - s = wb4.getSheetAt(0); - assertEquals(refLocal, s.getRow(0).getCell(0).getCellFormula()); - wb4.close(); - - HSSFWorkbook wb5 = openSample("46670_http.xls"); - s = wb5.getSheetAt(0); - c = s.getRow(0).getCell(0); - c.setCellFormula(refHttp); - assertEquals(refHttp, c.getCellFormula()); - - HSSFWorkbook wb6 = HSSFTestDataSamples.writeOutAndReadBack(wb5); - wb5.close(); - s = wb6.getSheetAt(0); - assertEquals(refHttp, s.getRow(0).getCell(0).getCellFormula()); - wb6.close(); - } - - @Test - public void test57456() throws IOException { - Workbook wb = openSample("57456.xls"); - wb.close(); - } - - @Test - public void test57163() throws IOException { - Workbook wb = openSample("57163.xls"); - - while (wb.getNumberOfSheets() > 1) { - wb.removeSheetAt(1); - } - wb.close(); - } - - @Test - public void test53109() throws IOException { - HSSFWorkbook wb1 = openSample("53109.xls"); - - HSSFWorkbook wb2 = writeOutAndReadBack(wb1); - assertNotNull(wb2); - wb2.close(); - - wb1.close(); - } - - @Test - public void test53109a() throws IOException { - HSSFWorkbook wb1 = openSample("com.aida-tour.www_SPO_files_maldives%20august%20october.xls"); - - Workbook wb2 = writeOutAndReadBack(wb1); - assertNotNull(wb2); - wb2.close(); - - wb1.close(); - } - - @Test - public void test48043() throws IOException { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("56325a.xls"); - - wb.removeSheetAt(2); - wb.removeSheetAt(1); - - //Sheet s = wb.createSheet("sheetname"); - Sheet s = wb.getSheetAt(0); - Row row = s.createRow(0); - Cell cell = row.createCell(0); - - cell.setCellFormula( - "IF(AND(ISBLANK(A10)," + - "ISBLANK(B10)),\"\"," + - "CONCATENATE(A10,\"-\",B10))"); - - FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator(); - - eval.evaluateAll(); - - /*OutputStream out = new FileOutputStream("C:\\temp\\48043.xls"); - try { - wb.write(out); - } finally { - out.close(); - }*/ - - Workbook wbBack = HSSFTestDataSamples.writeOutAndReadBack(wb); - assertNotNull(wbBack); - wbBack.close(); - - wb.close(); - } - - @Test - public void test57925() throws IOException { - Workbook wb = HSSFTestDataSamples.openSampleWorkbook("57925.xls"); - - wb.getCreationHelper().createFormulaEvaluator().evaluateAll(); - - for(int i = 0;i < wb.getNumberOfSheets();i++) { - Sheet sheet = wb.getSheetAt(i); - for(Row row : sheet) { - for(Cell cell : row) { - new DataFormatter().formatCellValue(cell); - } - } - } - - wb.close(); - } - - @Test - public void test46515() throws IOException { - Workbook wb = HSSFTestDataSamples.openSampleWorkbook("46515.xls"); - - // Get structure from webservice - String urlString = "http://poi.apache.org/resources/images/project-logo.jpg"; - URL structURL = new URL(urlString); - BufferedImage bimage; - try { - bimage = ImageIO.read(structURL); - } catch (IOException e) { - Assume.assumeNoException("Downloading a jpg from poi.apache.org should work", e); - return; - } finally { - wb.close(); - } - - // Convert BufferedImage to byte[] - ByteArrayOutputStream imageBAOS = new ByteArrayOutputStream(); - ImageIO.write(bimage, "jpeg", imageBAOS); - imageBAOS.flush(); - byte[]imageBytes = imageBAOS.toByteArray(); - imageBAOS.close(); - - // Pop structure into Structure HSSFSheet - int pict = wb.addPicture(imageBytes, HSSFWorkbook.PICTURE_TYPE_JPEG); - Sheet sheet = wb.getSheet("Structure"); - assertNotNull("Did not find sheet", sheet); - HSSFPatriarch patriarch = (HSSFPatriarch) sheet.createDrawingPatriarch(); - HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0, (short) 1, 1, (short) 10, 22); - anchor.setAnchorType(AnchorType.MOVE_DONT_RESIZE); - patriarch.createPicture(anchor, pict); - - // Write out destination file -// FileOutputStream fileOut = new FileOutputStream("/tmp/46515.xls"); -// wb.write(fileOut); -// fileOut.close(); - - wb.close(); - } - - @Test - public void test55668() throws IOException { - Workbook wb = HSSFTestDataSamples.openSampleWorkbook("55668.xls"); - - Sheet sheet = wb.getSheetAt(0); - Row row = sheet.getRow(0); - Cell cell = row.getCell(0); - assertEquals(CellType.FORMULA, cell.getCellTypeEnum()); - assertEquals("IF(TRUE,\"\",\"\")", cell.getCellFormula()); - assertEquals("", cell.getStringCellValue()); - cell.setCellType(CellType.STRING); - - assertEquals(CellType.BLANK, cell.getCellTypeEnum()); - try { - assertNull(cell.getCellFormula()); - fail("Should throw an exception here"); - } catch (IllegalStateException e) { - // expected here - } - assertEquals("", cell.getStringCellValue()); - - wb.close(); - } - - @Test - public void test55982() throws IOException { - Workbook wb = HSSFTestDataSamples.openSampleWorkbook("55982.xls"); - Sheet newSheet = wb.cloneSheet(1); - assertNotNull(newSheet); - wb.close(); - } - - /** - * Test generator of ids for the CommonObjectDataSubRecord record. - */ - @Test - public void test51332() { - HSSFClientAnchor anchor = new HSSFClientAnchor(); - HSSFSimpleShape shape; - CommonObjectDataSubRecord cmo; - - shape = new HSSFTextbox(null, anchor); - shape.setShapeId(1025); - cmo = (CommonObjectDataSubRecord)shape.getObjRecord().getSubRecords().get(0); - assertEquals(1, cmo.getObjectId()); - - shape = new HSSFPicture(null, anchor); - shape.setShapeId(1026); - cmo = (CommonObjectDataSubRecord)shape.getObjRecord().getSubRecords().get(0); - assertEquals(2, cmo.getObjectId()); - - shape = new HSSFComment(null, anchor); - shape.setShapeId(1027); - cmo = (CommonObjectDataSubRecord)shape.getObjRecord().getSubRecords().get(0); - assertEquals(1027, cmo.getObjectId()); - } - - // As of POI 3.15 beta 2, LibreOffice does not display the diagonal border while it does display the bottom border - // I have not checked Excel to know if this is a LibreOffice or a POI problem. - @Test - public void test53564() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("Page 1"); - final short BLUE = 30; - - HSSFSheetConditionalFormatting scf = sheet.getSheetConditionalFormatting(); - HSSFConditionalFormattingRule rule = scf.createConditionalFormattingRule(ComparisonOperator.GT, "10"); - - HSSFBorderFormatting bord = rule.createBorderFormatting(); - bord.setBorderDiagonal(BorderStyle.THICK); - assertEquals(BorderStyle.THICK, bord.getBorderDiagonalEnum()); - - bord.setBackwardDiagonalOn(true); - assertTrue(bord.isBackwardDiagonalOn()); - - bord.setForwardDiagonalOn(true); - assertTrue(bord.isForwardDiagonalOn()); - - bord.setDiagonalBorderColor(BLUE); - assertEquals(BLUE, bord.getDiagonalBorderColor()); - - // Create the bottom border style so we know what a border is supposed to look like - bord.setBorderBottom(BorderStyle.THICK); - assertEquals(BorderStyle.THICK, bord.getBorderBottomEnum()); - bord.setBottomBorderColor(BLUE); - assertEquals(BLUE, bord.getBottomBorderColor()); - - CellRangeAddress[] A2_D4 = {new CellRangeAddress(1, 3, 0, 3)}; - scf.addConditionalFormatting(A2_D4, rule); - - // Set a cell value within the conditional formatting range whose rule would resolve to True. - Cell C3 = sheet.createRow(2).createCell(2); - C3.setCellValue(30.0); - - // Manually check the output file with Excel to see if the diagonal border is present - //OutputStream fos = new FileOutputStream("/tmp/53564.xls"); - //wb.write(fos); - //fos.close(); - wb.close(); - } - - @Test - public void test45353a() throws IOException { - final Workbook wb = HSSFTestDataSamples.openSampleWorkbook("named-cell-in-formula-test.xls"); - wb.getCreationHelper().createFormulaEvaluator().evaluateAll(); - wb.close(); - } - - @Test - public void test45353b() throws IOException { - final Workbook wb = HSSFTestDataSamples.openSampleWorkbook("named-cell-test.xls"); - wb.getCreationHelper().createFormulaEvaluator().evaluateAll(); - wb.close(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestCellStyle.java b/src/testcases/org/apache/poi/hssf/usermodel/TestCellStyle.java deleted file mode 100644 index f02b950f8..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestCellStyle.java +++ /dev/null @@ -1,549 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Calendar; -import java.util.Date; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.ss.usermodel.BorderStyle; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.Font; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.util.LocaleUtil; -import org.apache.poi.util.TempFile; -import org.junit.Test; - -import junit.framework.TestCase; - -/** - * Class to test cell styling functionality - */ - -public final class TestCellStyle extends TestCase { - - private static HSSFWorkbook openSample(String sampleFileName) { - return HSSFTestDataSamples.openSampleWorkbook(sampleFileName); - } - - - /** - * TEST NAME: Test Write Sheet Font

    - * OBJECTIVE: Test that HSSF can create a simple spreadsheet with numeric and string values and styled with fonts.

    - * SUCCESS: HSSF creates a sheet. Filesize matches a known good. HSSFSheet objects - * Last row, first row is tested against the correct values (99,0).

    - * FAILURE: HSSF does not create a sheet or excepts. Filesize does not match the known good. - * HSSFSheet last row or first row is incorrect.

    - * - */ - public void testWriteSheetFont() throws IOException{ - File file = TempFile.createTempFile("testWriteSheetFont", - ".xls"); - FileOutputStream out = new FileOutputStream(file); - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet s = wb.createSheet(); - HSSFRow r = null; - HSSFCell c = null; - HSSFFont fnt = wb.createFont(); - HSSFCellStyle cs = wb.createCellStyle(); - - fnt.setColor(HSSFFont.COLOR_RED); - fnt.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); - cs.setFont(fnt); - for (int rownum = 0; rownum < 100; rownum++) { - r = s.createRow(rownum); - - for (int cellnum = 0; cellnum < 50; cellnum += 2) { - c = r.createCell(cellnum); - c.setCellValue(rownum * 10000 + cellnum - + ((( double ) rownum / 1000) - + (( double ) cellnum / 10000))); - c = r.createCell(cellnum + 1); - c.setCellValue("TEST"); - c.setCellStyle(cs); - } - } - wb.write(out); - out.close(); - SanityChecker sanityChecker = new SanityChecker(); - sanityChecker.checkHSSFWorkbook(wb); - assertEquals("LAST ROW == 99", 99, s.getLastRowNum()); - assertEquals("FIRST ROW == 0", 0, s.getFirstRowNum()); - - // assert((s.getLastRowNum() == 99)); - } - - /** - * Tests that is creating a file with a date or an calendar works correctly. - */ - public void testDataStyle() throws IOException { - File file = TempFile.createTempFile("testWriteSheetStyleDate", - ".xls"); - FileOutputStream out = new FileOutputStream(file); - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet s = wb.createSheet(); - HSSFCellStyle cs = wb.createCellStyle(); - HSSFRow row = s.createRow(0); - - // with Date: - HSSFCell cell = row.createCell(1); - cs.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy")); - cell.setCellStyle(cs); - cell.setCellValue(new Date()); - - // with Calendar: - cell = row.createCell(2); - cs.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy")); - cell.setCellStyle(cs); - Calendar cal = LocaleUtil.getLocaleCalendar(); - cell.setCellValue(cal); - - wb.write(out); - out.close(); - SanityChecker sanityChecker = new SanityChecker(); - sanityChecker.checkHSSFWorkbook(wb); - - assertEquals("LAST ROW ", 0, s.getLastRowNum()); - assertEquals("FIRST ROW ", 0, s.getFirstRowNum()); - } - - public void testHashEquals() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet s = wb.createSheet(); - HSSFCellStyle cs1 = wb.createCellStyle(); - HSSFCellStyle cs2 = wb.createCellStyle(); - HSSFRow row = s.createRow(0); - HSSFCell cell1 = row.createCell(1); - HSSFCell cell2 = row.createCell(2); - - cs1.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy")); - cs2.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/dd/yy")); - - cell1.setCellStyle(cs1); - cell1.setCellValue(new Date()); - - cell2.setCellStyle(cs2); - cell2.setCellValue(new Date()); - - assertEquals(cs1.hashCode(), cs1.hashCode()); - assertEquals(cs2.hashCode(), cs2.hashCode()); - assertTrue(cs1.equals(cs1)); - assertTrue(cs2.equals(cs2)); - - // Change cs1, hash will alter - int hash1 = cs1.hashCode(); - cs1.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/dd/yy")); - assertFalse(hash1 == cs1.hashCode()); - - wb.close(); - } - - /** - * TEST NAME: Test Write Sheet Style

    - * OBJECTIVE: Test that HSSF can create a simple spreadsheet with numeric and string values and styled with colors - * and borders.

    - * SUCCESS: HSSF creates a sheet. Filesize matches a known good. HSSFSheet objects - * Last row, first row is tested against the correct values (99,0).

    - * FAILURE: HSSF does not create a sheet or excepts. Filesize does not match the known good. - * HSSFSheet last row or first row is incorrect.

    - * - */ - public void testWriteSheetStyle() throws IOException { - File file = TempFile.createTempFile("testWriteSheetStyle", - ".xls"); - FileOutputStream out = new FileOutputStream(file); - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet s = wb.createSheet(); - HSSFRow r = null; - HSSFCell c = null; - HSSFFont fnt = wb.createFont(); - HSSFCellStyle cs = wb.createCellStyle(); - HSSFCellStyle cs2 = wb.createCellStyle(); - - cs.setBorderBottom(BorderStyle.THIN); - cs.setBorderLeft(BorderStyle.THIN); - cs.setBorderRight(BorderStyle.THIN); - cs.setBorderTop(BorderStyle.THIN); - cs.setFillForegroundColor(( short ) 0xA); - cs.setFillPattern(( short ) 1); - fnt.setColor(( short ) 0xf); - fnt.setItalic(true); - cs2.setFillForegroundColor(( short ) 0x0); - cs2.setFillPattern(( short ) 1); - cs2.setFont(fnt); - for (int rownum = 0; rownum < 100; rownum++) { - r = s.createRow(rownum); - - for (int cellnum = 0; cellnum < 50; cellnum += 2) { - c = r.createCell(cellnum); - c.setCellValue(rownum * 10000 + cellnum - + ((( double ) rownum / 1000) - + (( double ) cellnum / 10000))); - c.setCellStyle(cs); - c = r.createCell(cellnum + 1); - c.setCellValue("TEST"); - c.setCellStyle(cs2); - } - } - wb.write(out); - out.close(); - SanityChecker sanityChecker = new SanityChecker(); - sanityChecker.checkHSSFWorkbook(wb); - assertEquals("LAST ROW == 99", 99, s.getLastRowNum()); - assertEquals("FIRST ROW == 0", 0, s.getFirstRowNum()); - } - - /** - * Cloning one HSSFCellStyle onto Another, same - * HSSFWorkbook - */ - public void testCloneStyleSameWB() { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFFont fnt = wb.createFont(); - fnt.setFontName("TestingFont"); - assertEquals(5, wb.getNumberOfFonts()); - - HSSFCellStyle orig = wb.createCellStyle(); - orig.setAlignment(HSSFCellStyle.ALIGN_RIGHT); - orig.setFont(fnt); - orig.setDataFormat((short)18); - - assertTrue(HSSFCellStyle.ALIGN_RIGHT == orig.getAlignment()); - assertTrue(fnt == orig.getFont(wb)); - assertTrue(18 == orig.getDataFormat()); - - HSSFCellStyle clone = wb.createCellStyle(); - assertFalse(HSSFCellStyle.ALIGN_RIGHT == clone.getAlignment()); - assertFalse(fnt == clone.getFont(wb)); - assertFalse(18 == clone.getDataFormat()); - - clone.cloneStyleFrom(orig); - assertTrue(HSSFCellStyle.ALIGN_RIGHT == clone.getAlignment()); - assertTrue(fnt == clone.getFont(wb)); - assertTrue(18 == clone.getDataFormat()); - assertEquals(5, wb.getNumberOfFonts()); - } - - /** - * Cloning one HSSFCellStyle onto Another, across - * two different HSSFWorkbooks - */ - public void testCloneStyleDiffWB() { - HSSFWorkbook wbOrig = new HSSFWorkbook(); - - HSSFFont fnt = wbOrig.createFont(); - fnt.setFontName("TestingFont"); - assertEquals(5, wbOrig.getNumberOfFonts()); - - HSSFDataFormat fmt = wbOrig.createDataFormat(); - fmt.getFormat("MadeUpOne"); - fmt.getFormat("MadeUpTwo"); - - HSSFCellStyle orig = wbOrig.createCellStyle(); - orig.setAlignment(HSSFCellStyle.ALIGN_RIGHT); - orig.setFont(fnt); - orig.setDataFormat(fmt.getFormat("Test##")); - - assertTrue(HSSFCellStyle.ALIGN_RIGHT == orig.getAlignment()); - assertTrue(fnt == orig.getFont(wbOrig)); - assertTrue(fmt.getFormat("Test##") == orig.getDataFormat()); - - // Now a style on another workbook - HSSFWorkbook wbClone = new HSSFWorkbook(); - assertEquals(4, wbClone.getNumberOfFonts()); - HSSFDataFormat fmtClone = wbClone.createDataFormat(); - - HSSFCellStyle clone = wbClone.createCellStyle(); - assertEquals(4, wbClone.getNumberOfFonts()); - - assertFalse(HSSFCellStyle.ALIGN_RIGHT == clone.getAlignment()); - assertFalse("TestingFont" == clone.getFont(wbClone).getFontName()); - - clone.cloneStyleFrom(orig); - assertTrue(HSSFCellStyle.ALIGN_RIGHT == clone.getAlignment()); - assertTrue("TestingFont" == clone.getFont(wbClone).getFontName()); - assertTrue(fmtClone.getFormat("Test##") == clone.getDataFormat()); - assertFalse(fmtClone.getFormat("Test##") == fmt.getFormat("Test##")); - assertEquals(5, wbClone.getNumberOfFonts()); - } - - public void testStyleNames() { - HSSFWorkbook wb = openSample("WithExtendedStyles.xls"); - HSSFSheet s = wb.getSheetAt(0); - HSSFCell c1 = s.getRow(0).getCell(0); - HSSFCell c2 = s.getRow(1).getCell(0); - HSSFCell c3 = s.getRow(2).getCell(0); - - HSSFCellStyle cs1 = c1.getCellStyle(); - HSSFCellStyle cs2 = c2.getCellStyle(); - HSSFCellStyle cs3 = c3.getCellStyle(); - - assertNotNull(cs1); - assertNotNull(cs2); - assertNotNull(cs3); - - // Check we got the styles we'd expect - assertEquals(10, cs1.getFont(wb).getFontHeightInPoints()); - assertEquals(9, cs2.getFont(wb).getFontHeightInPoints()); - assertEquals(12, cs3.getFont(wb).getFontHeightInPoints()); - - assertEquals(15, cs1.getIndex()); - assertEquals(23, cs2.getIndex()); - assertEquals(24, cs3.getIndex()); - - assertNull(cs1.getParentStyle()); - assertNotNull(cs2.getParentStyle()); - assertNotNull(cs3.getParentStyle()); - - assertEquals(21, cs2.getParentStyle().getIndex()); - assertEquals(22, cs3.getParentStyle().getIndex()); - - // Now check we can get style records for - // the parent ones - assertNull(wb.getWorkbook().getStyleRecord(15)); - assertNull(wb.getWorkbook().getStyleRecord(23)); - assertNull(wb.getWorkbook().getStyleRecord(24)); - - assertNotNull(wb.getWorkbook().getStyleRecord(21)); - assertNotNull(wb.getWorkbook().getStyleRecord(22)); - - // Now check the style names - assertEquals(null, cs1.getUserStyleName()); - assertEquals(null, cs2.getUserStyleName()); - assertEquals(null, cs3.getUserStyleName()); - assertEquals("style1", cs2.getParentStyle().getUserStyleName()); - assertEquals("style2", cs3.getParentStyle().getUserStyleName()); - - // now apply a named style to a new cell - HSSFCell c4 = s.getRow(0).createCell(1); - c4.setCellStyle(cs2); - assertEquals("style1", c4.getCellStyle().getParentStyle().getUserStyleName()); - } - - public void testGetSetBorderHair() { - HSSFWorkbook wb = openSample("55341_CellStyleBorder.xls"); - HSSFSheet s = wb.getSheetAt(0); - HSSFCellStyle cs; - - cs = s.getRow(0).getCell(0).getCellStyle(); - assertEquals(BorderStyle.HAIR, cs.getBorderRightEnum()); - - cs = s.getRow(1).getCell(1).getCellStyle(); - assertEquals(BorderStyle.DOTTED, cs.getBorderRightEnum()); - - cs = s.getRow(2).getCell(2).getCellStyle(); - assertEquals(BorderStyle.DASH_DOT_DOT, cs.getBorderRightEnum()); - - cs = s.getRow(3).getCell(3).getCellStyle(); - assertEquals(BorderStyle.DASHED, cs.getBorderRightEnum()); - - cs = s.getRow(4).getCell(4).getCellStyle(); - assertEquals(BorderStyle.THIN, cs.getBorderRightEnum()); - - cs = s.getRow(5).getCell(5).getCellStyle(); - assertEquals(BorderStyle.MEDIUM_DASH_DOT_DOT, cs.getBorderRightEnum()); - - cs = s.getRow(6).getCell(6).getCellStyle(); - assertEquals(BorderStyle.SLANTED_DASH_DOT, cs.getBorderRightEnum()); - - cs = s.getRow(7).getCell(7).getCellStyle(); - assertEquals(BorderStyle.MEDIUM_DASH_DOT, cs.getBorderRightEnum()); - - cs = s.getRow(8).getCell(8).getCellStyle(); - assertEquals(BorderStyle.MEDIUM_DASHED, cs.getBorderRightEnum()); - - cs = s.getRow(9).getCell(9).getCellStyle(); - assertEquals(BorderStyle.MEDIUM, cs.getBorderRightEnum()); - - cs = s.getRow(10).getCell(10).getCellStyle(); - assertEquals(BorderStyle.THICK, cs.getBorderRightEnum()); - - cs = s.getRow(11).getCell(11).getCellStyle(); - assertEquals(BorderStyle.DOUBLE, cs.getBorderRightEnum()); - } - - public void testShrinkToFit() { - // Existing file - HSSFWorkbook wb = openSample("ShrinkToFit.xls"); - HSSFSheet s = wb.getSheetAt(0); - HSSFRow r = s.getRow(0); - HSSFCellStyle cs = r.getCell(0).getCellStyle(); - - assertEquals(true, cs.getShrinkToFit()); - - // New file - HSSFWorkbook wbOrig = new HSSFWorkbook(); - s = wbOrig.createSheet(); - r = s.createRow(0); - - cs = wbOrig.createCellStyle(); - cs.setShrinkToFit(false); - r.createCell(0).setCellStyle(cs); - - cs = wbOrig.createCellStyle(); - cs.setShrinkToFit(true); - r.createCell(1).setCellStyle(cs); - - // Write out, read, and check - wb = HSSFTestDataSamples.writeOutAndReadBack(wbOrig); - s = wb.getSheetAt(0); - r = s.getRow(0); - assertEquals(false, r.getCell(0).getCellStyle().getShrinkToFit()); - assertEquals(true, r.getCell(1).getCellStyle().getShrinkToFit()); - } - - - - private static class CellFormatBugExample extends Thread { - private final String fileName; - private Throwable exception = null; - - public CellFormatBugExample(String fileName) { - this.fileName = fileName; - } - - @Override - public void run() { - try { - for(int i = 0;i< 10;i++) { - Workbook wb = HSSFTestDataSamples.openSampleWorkbook(fileName); - Sheet sheet = wb.getSheetAt(0); - - for (Row row : sheet) { - for (Integer idxCell = 0; idxCell < row.getLastCellNum(); idxCell++) { - - Cell cell = row.getCell(idxCell); - cell.getCellStyle().getDataFormatString(); - if (cell.getCellTypeEnum() == CellType.NUMERIC) { - boolean isDate = HSSFDateUtil.isCellDateFormatted(cell); - if (idxCell > 0 && isDate) { - fail("cell " + idxCell + " is not a date: " + idxCell.toString()); - } - } - } - } - } - } catch (Throwable e) { - exception = e; - } - } - - public Throwable getException() { - return exception; - } - } - - public void test56563() throws Throwable { - CellFormatBugExample threadA = new CellFormatBugExample("56563a.xls"); - threadA.start(); - CellFormatBugExample threadB = new CellFormatBugExample("56563b.xls"); - threadB.start(); - - threadA.join(); - threadB.join(); - - if(threadA.getException() != null) { - throw threadA.getException(); - } - if(threadB.getException() != null) { - throw threadB.getException(); - } - } - - public void test56959() throws IOException { - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet("somesheet"); - - Row row = sheet.createRow(0); - - // Create a new font and alter it. - Font font = wb.createFont(); - font.setFontHeightInPoints((short)24); - font.setFontName("Courier New"); - font.setItalic(true); - font.setStrikeout(true); - font.setColor(Font.COLOR_RED); - - CellStyle style = wb.createCellStyle(); - style.setBorderBottom(BorderStyle.DOTTED); - style.setFont(font); - - Cell cell = row.createCell(0); - cell.setCellStyle(style); - cell.setCellValue("testtext"); - - Cell newCell = row.createCell(1); - - newCell.setCellStyle(style); - newCell.setCellValue("2testtext2"); - - CellStyle newStyle = newCell.getCellStyle(); - assertEquals(BorderStyle.DOTTED, newStyle.getBorderBottomEnum()); - assertEquals(Font.COLOR_RED, ((HSSFCellStyle)newStyle).getFont(wb).getColor()); - -// OutputStream out = new FileOutputStream("/tmp/56959.xls"); -// try { -// wb.write(out); -// } finally { -// out.close(); -// } - } - - - @Test - public void test58043() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFCellStyle cellStyle = wb.createCellStyle(); - - assertEquals(0, cellStyle.getRotation()); - - cellStyle.setRotation((short)89); - assertEquals(89, cellStyle.getRotation()); - - cellStyle.setRotation((short)90); - assertEquals(90, cellStyle.getRotation()); - - cellStyle.setRotation((short)-1); - assertEquals(-1, cellStyle.getRotation()); - - cellStyle.setRotation((short)-89); - assertEquals(-89, cellStyle.getRotation()); - - cellStyle.setRotation((short)-90); - assertEquals(-90, cellStyle.getRotation()); - - cellStyle.setRotation((short)-89); - assertEquals(-89, cellStyle.getRotation()); - - // values above 90 are mapped to the correct values for compatibility between HSSF and XSSF - cellStyle.setRotation((short)179); - assertEquals(-89, cellStyle.getRotation()); - - cellStyle.setRotation((short)180); - assertEquals(-90, cellStyle.getRotation()); - - wb.close(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestCloneSheet.java b/src/testcases/org/apache/poi/hssf/usermodel/TestCloneSheet.java deleted file mode 100644 index 5bdfe6227..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestCloneSheet.java +++ /dev/null @@ -1,132 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import org.apache.poi.ddf.EscherDgRecord; -import org.apache.poi.ddf.EscherSpRecord; -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.hssf.record.CommonObjectDataSubRecord; -import org.apache.poi.hssf.record.EscherAggregate; -import org.apache.poi.ss.usermodel.BaseTestCloneSheet; -import org.junit.Test; - -import java.io.IOException; -import java.util.Arrays; - -import static org.junit.Assert.*; - -/** - * Test the ability to clone a sheet. - * If adding new records that belong to a sheet (as opposed to a book) - * add that record to the sheet in the testCloneSheetBasic method. - * @author avik - */ -public final class TestCloneSheet extends BaseTestCloneSheet { - public TestCloneSheet() { - super(HSSFITestDataProvider.instance); - } - - @Test - public void testCloneSheetWithoutDrawings(){ - HSSFWorkbook b = new HSSFWorkbook(); - HSSFSheet s = b.createSheet("Test"); - HSSFSheet s2 = s.cloneSheet(b); - - assertNull(s.getDrawingPatriarch()); - assertNull(s2.getDrawingPatriarch()); - assertEquals(HSSFTestHelper.getSheetForTest(s).getRecords().size(), HSSFTestHelper.getSheetForTest(s2).getRecords().size()); - } - - @Test - public void testCloneSheetWithEmptyDrawingAggregate(){ - HSSFWorkbook b = new HSSFWorkbook(); - HSSFSheet s = b.createSheet("Test"); - HSSFPatriarch patriarch = s.createDrawingPatriarch(); - - EscherAggregate agg1 = patriarch.getBoundAggregate(); - - HSSFSheet s2 = s.cloneSheet(b); - - patriarch = s2.getDrawingPatriarch(); - - EscherAggregate agg2 = patriarch.getBoundAggregate(); - - EscherSpRecord sp1 = (EscherSpRecord) agg1.getEscherContainer().getChild(1).getChild(0).getChild(1); - EscherSpRecord sp2 = (EscherSpRecord) agg2.getEscherContainer().getChild(1).getChild(0).getChild(1); - - assertEquals(sp1.getShapeId(), 1024); - assertEquals(sp2.getShapeId(), 2048); - - EscherDgRecord dg = (EscherDgRecord) agg2.getEscherContainer().getChild(0); - - assertEquals(dg.getLastMSOSPID(), 2048); - assertEquals(dg.getInstance(), 0x2); - - //everything except id and DgRecord.lastMSOSPID and DgRecord.Instance must be the same - - sp2.setShapeId(1024); - dg.setLastMSOSPID(1024); - dg.setInstance((short) 0x1); - - assertEquals(agg1.serialize().length, agg2.serialize().length); - assertEquals(agg1.toXml(""), agg2.toXml("")); - assertArrayEquals(agg1.serialize(), agg2.serialize()); - } - - @Test - public void testCloneComment() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sh = wb.createSheet(); - HSSFPatriarch p = sh.createDrawingPatriarch(); - HSSFComment c = p.createComment(new HSSFClientAnchor(0,0,100,100, (short) 0,0,(short)5,5)); - c.setColumn(1); - c.setRow(2); - c.setString(new HSSFRichTextString("qwertyuio")); - - HSSFSheet sh2 = wb.cloneSheet(0); - HSSFPatriarch p2 = sh2.getDrawingPatriarch(); - HSSFComment c2 = (HSSFComment) p2.getChildren().get(0); - - assertEquals(c.getString(), c2.getString()); - assertEquals(c.getRow(), c2.getRow()); - assertEquals(c.getColumn(), c2.getColumn()); - - // The ShapeId is not equal? - // assertEquals(c.getNoteRecord().getShapeId(), c2.getNoteRecord().getShapeId()); - - assertArrayEquals(c2.getTextObjectRecord().serialize(), c.getTextObjectRecord().serialize()); - - // ShapeId is different - CommonObjectDataSubRecord subRecord = (CommonObjectDataSubRecord) c2.getObjRecord().getSubRecords().get(0); - subRecord.setObjectId(1025); - - assertArrayEquals(c2.getObjRecord().serialize(), c.getObjRecord().serialize()); - - // ShapeId is different - c2.getNoteRecord().setShapeId(1025); - assertArrayEquals(c2.getNoteRecord().serialize(), c.getNoteRecord().serialize()); - - //everything except spRecord.shapeId must be the same - assertFalse(Arrays.equals(c2.getEscherContainer().serialize(), c.getEscherContainer().serialize())); - EscherSpRecord sp = (EscherSpRecord) c2.getEscherContainer().getChild(0); - sp.setShapeId(1025); - assertArrayEquals(c2.getEscherContainer().serialize(), c.getEscherContainer().serialize()); - - wb.close(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestCryptoAPI.java b/src/testcases/org/apache/poi/hssf/usermodel/TestCryptoAPI.java deleted file mode 100644 index 3baafa8b3..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestCryptoAPI.java +++ /dev/null @@ -1,70 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.apache.poi.POITestCase.assertContains; - -import java.io.IOException; - -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.hssf.extractor.ExcelExtractor; -import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey; -import org.junit.AfterClass; -import org.junit.Test; - -public class TestCryptoAPI { - final HSSFITestDataProvider ssTests = HSSFITestDataProvider.instance; - - @AfterClass - public static void resetPW() { - Biff8EncryptionKey.setCurrentUserPassword(null); - } - - @Test - public void bug59857() throws IOException { - // XOR-Obfuscation - // TODO: XOR-Obfuscation is currently flawed - although the de-/obfuscation initially works, - // it suddenly differs from the result of encrypted files via Office ... - // and only very small files can be opened without file validation errors - validateContent("xor-encryption-abc.xls", "abc", "Sheet1\n1\n2\n3\n"); - - // BinaryRC4 - validateContent("password.xls", "password", "A ZIP bomb is a variant of mail-bombing. After most commercial mail servers began checking mail with anti-virus software and filtering certain malicious file types, trojan horse viruses tried to send themselves compressed into archives, such as ZIP, RAR or 7-Zip. Mail server software was then configured to unpack archives and check their contents as well. That gave black hats the idea to compose a \"bomb\" consisting of an enormous text file, containing, for example, only the letter z repeated millions of times. Such a file compresses into a relatively small archive, but its unpacking (especially by early versions of mail servers) would use a high amount of processing power, RAM and swap space, which could result in denial of service. Modern mail server computers usually have sufficient intelligence to recognize such attacks as well as sufficient processing power and memory space to process malicious attachments without interruption of service, though some are still susceptible to this technique if the ZIP bomb is mass-mailed."); - - // CryptoAPI - validateContent("35897-type4.xls", "freedom", "Sheet1\nhello there!\n"); - } - - private void validateContent(String wbFile, String password, String textExpected) throws IOException { - Biff8EncryptionKey.setCurrentUserPassword(password); - HSSFWorkbook wb = ssTests.openSampleWorkbook(wbFile); - ExcelExtractor ee1 = new ExcelExtractor(wb); - String textActual = ee1.getText(); - assertContains(textActual, textExpected); - - Biff8EncryptionKey.setCurrentUserPassword("bla"); - HSSFWorkbook wbBla = ssTests.writeOutAndReadBack(wb); - ExcelExtractor ee2 = new ExcelExtractor(wbBla); - textActual = ee2.getText(); - assertContains(textActual, textExpected); - ee2.close(); - ee1.close(); - wbBla.close(); - wb.close(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestDataValidation.java b/src/testcases/org/apache/poi/hssf/usermodel/TestDataValidation.java deleted file mode 100644 index a440a39de..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestDataValidation.java +++ /dev/null @@ -1,475 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.PrintStream; -import java.util.List; - -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.record.DVRecord; -import org.apache.poi.ss.usermodel.BaseTestDataValidation; -import org.apache.poi.ss.usermodel.DataValidation; -import org.apache.poi.ss.usermodel.DataValidation.ErrorStyle; -import org.apache.poi.ss.usermodel.DataValidationConstraint; -import org.apache.poi.ss.usermodel.DataValidationConstraint.OperatorType; -import org.apache.poi.ss.usermodel.DataValidationConstraint.ValidationType; -import org.apache.poi.ss.usermodel.DataValidationHelper; -import org.apache.poi.ss.usermodel.DateUtil; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.CellRangeAddressList; -import org.junit.Test; - -/** - * Class for testing Excel's data validation mechanism - * - * @author Dragos Buleandra ( dragos.buleandra@trade2b.ro ) - */ -public final class TestDataValidation extends BaseTestDataValidation { - - public TestDataValidation(){ - super(HSSFITestDataProvider.instance); - } - - - public void assertDataValidation(Workbook wb) { - - ByteArrayOutputStream baos = new ByteArrayOutputStream(22000); - try { - wb.write(baos); - baos.close(); - } catch (IOException e) { - throw new RuntimeException(e); - } - byte[] generatedContent = baos.toByteArray(); - boolean isSame; -// if (false) { -// // TODO - add proof spreadsheet and compare -// InputStream proofStream = HSSFTestDataSamples.openSampleFileStream("TestDataValidation.xls"); -// isSame = compareStreams(proofStream, generatedContent); -// } - isSame = true; - - if (isSame) { - return; - } - File tempDir = new File(System.getProperty("java.io.tmpdir")); - File generatedFile = new File(tempDir, "GeneratedTestDataValidation.xls"); - try { - FileOutputStream fileOut = new FileOutputStream(generatedFile); - fileOut.write(generatedContent); - fileOut.close(); - } catch (IOException e) { - throw new RuntimeException(e); - } - - PrintStream ps = System.out; - - ps.println("This test case has failed because the generated file differs from proof copy '" - ); // TODO+ proofFile.getAbsolutePath() + "'."); - ps.println("The cause is usually a change to this test, or some common spreadsheet generation code. " - + "The developer has to decide whether the changes were wanted or unwanted."); - ps.println("If the changes to the generated version were unwanted, " - + "make the fix elsewhere (do not modify this test or the proof spreadsheet to get the test working)."); - ps.println("If the changes were wanted, make sure to open the newly generated file in Excel " - + "and verify it manually. The new proof file should be submitted after it is verified to be correct."); - ps.println(""); - ps.println("One other possible (but less likely) cause of a failed test is a problem in the " - + "comparison logic used here. Perhaps some extra file regions need to be ignored."); - ps.println("The generated file has been saved to '" + generatedFile.getAbsolutePath() + "' for manual inspection."); - - fail("Generated file differs from proof copy. See sysout comments for details on how to fix."); - - } - -// private static boolean compareStreams(InputStream isA, byte[] generatedContent) { -// -// InputStream isB = new ByteArrayInputStream(generatedContent); -// -// // The allowable regions where the generated file can differ from the -// // proof should be small (i.e. much less than 1K) -// int[] allowableDifferenceRegions = { -// 0x0228, 16, // a region of the file containing the OS username -// 0x506C, 8, // See RootProperty (super fields _seconds_2 and _days_2) -// }; -// int[] diffs = StreamUtility.diffStreams(isA, isB, allowableDifferenceRegions); -// if (diffs == null) { -// return true; -// } -// System.err.println("Diff from proof: "); -// for (int i = 0; i < diffs.length; i++) { -// System.err.println("diff at offset: 0x" + Integer.toHexString(diffs[i])); -// } -// return false; -// } - - - - - - /* package */ static void setCellValue(HSSFCell cell, String text) { - cell.setCellValue(new HSSFRichTextString(text)); - - } - - @Test - public void testAddToExistingSheet() throws Exception { - - // dvEmpty.xls is a simple one sheet workbook. With a DataValidations header record but no - // DataValidations. It's important that the example has one SHEETPROTECTION record. - // Such a workbook can be created in Excel (2007) by adding datavalidation for one cell - // and then deleting the row that contains the cell. - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("dvEmpty.xls"); - int dvRow = 0; - Sheet sheet = wb.getSheetAt(0); - DataValidationHelper dataValidationHelper = sheet.getDataValidationHelper(); - DataValidationConstraint dc = dataValidationHelper.createIntegerConstraint(OperatorType.EQUAL, "42", null); - DataValidation dv = dataValidationHelper.createValidation(dc,new CellRangeAddressList(dvRow, dvRow, 0, 0)); - - dv.setEmptyCellAllowed(false); - dv.setErrorStyle(ErrorStyle.STOP); - dv.setShowPromptBox(true); - dv.createErrorBox("Xxx", "Yyy"); - dv.setSuppressDropDownArrow(true); - - sheet.addValidationData(dv); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - wb.write(baos); - - byte[] wbData = baos.toByteArray(); - -// if (false) { // TODO (Jul 2008) fix EventRecordFactory to process unknown records, (and DV records for that matter) -// -// ERFListener erfListener = null; // new MyERFListener(); -// EventRecordFactory erf = new EventRecordFactory(erfListener, null); -// try { -// POIFSFileSystem fs = new POIFSFileSystem(new ByteArrayInputStream(baos.toByteArray())); -// erf.processRecords(fs.createDocumentInputStream("Workbook")); -// } catch (RecordFormatException e) { -// throw new RuntimeException(e); -// } catch (IOException e) { -// throw new RuntimeException(e); -// } -// } - // else verify record ordering by navigating the raw bytes - - byte[] dvHeaderRecStart= { (byte)0xB2, 0x01, 0x12, 0x00, }; - int dvHeaderOffset = findIndex(wbData, dvHeaderRecStart); - assertTrue(dvHeaderOffset > 0); - int nextRecIndex = dvHeaderOffset + 22; - int nextSid - = ((wbData[nextRecIndex + 0] << 0) & 0x00FF) - + ((wbData[nextRecIndex + 1] << 8) & 0xFF00) - ; - // nextSid should be for a DVRecord. If anything comes between the DV header record - // and the DV records, Excel will not be able to open the workbook without error. - - if (nextSid == 0x0867) { - fail("Identified bug 45519"); - } - assertEquals(DVRecord.sid, nextSid); - - wb.close(); - } - - private int findIndex(byte[] largeData, byte[] searchPattern) { - byte firstByte = searchPattern[0]; - for (int i = 0; i < largeData.length; i++) { - if(largeData[i] != firstByte) { - continue; - } - boolean match = true; - for (int j = 1; j < searchPattern.length; j++) { - if(searchPattern[j] != largeData[i+j]) { - match = false; - break; - } - } - if (match) { - return i; - } - } - return -1; - } - - @Test - public void testGetDataValidationsAny() throws Exception { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet(); - List list = sheet.getDataValidations(); - assertEquals(0, list.size()); - - DataValidationHelper dataValidationHelper = sheet.getDataValidationHelper(); - DataValidationConstraint constraint = dataValidationHelper.createNumericConstraint(ValidationType.ANY, - OperatorType.IGNORED, null, null); - CellRangeAddressList addressList = new CellRangeAddressList(1, 2, 3, 4); - DataValidation validation = dataValidationHelper.createValidation(constraint, addressList); - validation.setEmptyCellAllowed(true); - validation.createErrorBox("error-title", "error-text"); - validation.createPromptBox("prompt-title", "prompt-text"); - sheet.addValidationData(validation); - - list = sheet.getDataValidations(); // <-- works - assertEquals(1, list.size()); - - HSSFDataValidation dv = list.get(0); - { - CellRangeAddressList regions = dv.getRegions(); - assertEquals(1, regions.countRanges()); - - CellRangeAddress address = regions.getCellRangeAddress(0); - assertEquals(1, address.getFirstRow()); - assertEquals(2, address.getLastRow()); - assertEquals(3, address.getFirstColumn()); - assertEquals(4, address.getLastColumn()); - } - assertEquals(true, dv.getEmptyCellAllowed()); - assertEquals(false, dv.getSuppressDropDownArrow()); - assertEquals(true, dv.getShowErrorBox()); - assertEquals("error-title", dv.getErrorBoxTitle()); - assertEquals("error-text", dv.getErrorBoxText()); - assertEquals(true, dv.getShowPromptBox()); - assertEquals("prompt-title", dv.getPromptBoxTitle()); - assertEquals("prompt-text", dv.getPromptBoxText()); - - DataValidationConstraint c = dv.getValidationConstraint(); - assertEquals(ValidationType.ANY, c.getValidationType()); - assertEquals(OperatorType.IGNORED, c.getOperator()); - - wb.close(); - } - - @Test - public void testGetDataValidationsIntegerFormula() throws Exception { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet(); - List list = sheet.getDataValidations(); - assertEquals(0, list.size()); - - DataValidationHelper dataValidationHelper = sheet.getDataValidationHelper(); - DataValidationConstraint constraint = dataValidationHelper.createIntegerConstraint(OperatorType.BETWEEN, "=A2", - "=A3"); - CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0); - DataValidation validation = dataValidationHelper.createValidation(constraint, addressList); - sheet.addValidationData(validation); - - list = sheet.getDataValidations(); // <-- works - assertEquals(1, list.size()); - - HSSFDataValidation dv = list.get(0); - DVConstraint c = dv.getConstraint(); - assertEquals(ValidationType.INTEGER, c.getValidationType()); - assertEquals(OperatorType.BETWEEN, c.getOperator()); - assertEquals("A2", c.getFormula1()); - assertEquals("A3", c.getFormula2()); - assertEquals(null, c.getValue1()); - assertEquals(null, c.getValue2()); - - wb.close(); - } - - @Test - public void testGetDataValidationsIntegerValue() throws Exception { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet(); - List list = sheet.getDataValidations(); - assertEquals(0, list.size()); - - DataValidationHelper dataValidationHelper = sheet.getDataValidationHelper(); - DataValidationConstraint constraint = dataValidationHelper.createIntegerConstraint(OperatorType.BETWEEN, "100", - "200"); - CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0); - DataValidation validation = dataValidationHelper.createValidation(constraint, addressList); - sheet.addValidationData(validation); - - list = sheet.getDataValidations(); // <-- works - assertEquals(1, list.size()); - - HSSFDataValidation dv = list.get(0); - DVConstraint c = dv.getConstraint(); - assertEquals(ValidationType.INTEGER, c.getValidationType()); - assertEquals(OperatorType.BETWEEN, c.getOperator()); - assertEquals(null, c.getFormula1()); - assertEquals(null, c.getFormula2()); - assertEquals(new Double("100"), c.getValue1()); - assertEquals(new Double("200"), c.getValue2()); - - wb.close(); - } - - @Test - public void testGetDataValidationsDecimal() throws Exception { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet(); - List list = sheet.getDataValidations(); - assertEquals(0, list.size()); - - DataValidationHelper dataValidationHelper = sheet.getDataValidationHelper(); - DataValidationConstraint constraint = dataValidationHelper.createDecimalConstraint(OperatorType.BETWEEN, "=A2", - "200"); - CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0); - DataValidation validation = dataValidationHelper.createValidation(constraint, addressList); - sheet.addValidationData(validation); - - list = sheet.getDataValidations(); // <-- works - assertEquals(1, list.size()); - - HSSFDataValidation dv = list.get(0); - DVConstraint c = dv.getConstraint(); - assertEquals(ValidationType.DECIMAL, c.getValidationType()); - assertEquals(OperatorType.BETWEEN, c.getOperator()); - assertEquals("A2", c.getFormula1()); - assertEquals(null, c.getFormula2()); - assertEquals(null, c.getValue1()); - assertEquals(new Double("200"), c.getValue2()); - - wb.close(); - } - - @Test - public void testGetDataValidationsDate() throws Exception { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet(); - List list = sheet.getDataValidations(); - assertEquals(0, list.size()); - - DataValidationHelper dataValidationHelper = sheet.getDataValidationHelper(); - DataValidationConstraint constraint = dataValidationHelper.createDateConstraint(OperatorType.EQUAL, - "2014/10/25", null, null); - CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0); - DataValidation validation = dataValidationHelper.createValidation(constraint, addressList); - sheet.addValidationData(validation); - - list = sheet.getDataValidations(); // <-- works - assertEquals(1, list.size()); - - HSSFDataValidation dv = list.get(0); - DVConstraint c = dv.getConstraint(); - assertEquals(ValidationType.DATE, c.getValidationType()); - assertEquals(OperatorType.EQUAL, c.getOperator()); - assertEquals(null, c.getFormula1()); - assertEquals(null, c.getFormula2()); - assertEquals(DateUtil.getExcelDate(DateUtil.parseYYYYMMDDDate("2014/10/25")), c.getValue1(), 0); - assertEquals(null, c.getValue2()); - - wb.close(); - } - - @Test - public void testGetDataValidationsListExplicit() throws Exception { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet(); - List list = sheet.getDataValidations(); - assertEquals(0, list.size()); - - DataValidationHelper dataValidationHelper = sheet.getDataValidationHelper(); - DataValidationConstraint constraint = dataValidationHelper.createExplicitListConstraint(new String[] { "aaa", - "bbb", "ccc" }); - CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0); - DataValidation validation = dataValidationHelper.createValidation(constraint, addressList); - validation.setSuppressDropDownArrow(true); - sheet.addValidationData(validation); - - list = sheet.getDataValidations(); // <-- works - assertEquals(1, list.size()); - - HSSFDataValidation dv = list.get(0); - assertEquals(true, dv.getSuppressDropDownArrow()); - - DVConstraint c = dv.getConstraint(); - assertEquals(ValidationType.LIST, c.getValidationType()); - assertEquals(null, c.getFormula1()); - assertEquals(null, c.getFormula2()); - assertEquals(null, c.getValue1()); - assertEquals(null, c.getValue2()); - String[] values = c.getExplicitListValues(); - assertEquals(3, values.length); - assertEquals("aaa", values[0]); - assertEquals("bbb", values[1]); - assertEquals("ccc", values[2]); - - wb.close(); - } - - @Test - public void testGetDataValidationsListFormula() throws Exception { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet(); - List list = sheet.getDataValidations(); - assertEquals(0, list.size()); - - DataValidationHelper dataValidationHelper = sheet.getDataValidationHelper(); - DataValidationConstraint constraint = dataValidationHelper.createFormulaListConstraint("A2"); - CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0); - DataValidation validation = dataValidationHelper.createValidation(constraint, addressList); - validation.setSuppressDropDownArrow(true); - sheet.addValidationData(validation); - - list = sheet.getDataValidations(); // <-- works - assertEquals(1, list.size()); - - HSSFDataValidation dv = list.get(0); - assertEquals(true, dv.getSuppressDropDownArrow()); - - DVConstraint c = dv.getConstraint(); - assertEquals(ValidationType.LIST, c.getValidationType()); - assertEquals("A2", c.getFormula1()); - assertEquals(null, c.getFormula2()); - assertEquals(null, c.getValue1()); - assertEquals(null, c.getValue2()); - - wb.close(); - } - - @Test - public void testGetDataValidationsFormula() throws Exception { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet(); - List list = sheet.getDataValidations(); - assertEquals(0, list.size()); - - DataValidationHelper dataValidationHelper = sheet.getDataValidationHelper(); - DataValidationConstraint constraint = dataValidationHelper.createCustomConstraint("A2:A3"); - CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0); - DataValidation validation = dataValidationHelper.createValidation(constraint, addressList); - sheet.addValidationData(validation); - - list = sheet.getDataValidations(); // <-- works - assertEquals(1, list.size()); - - HSSFDataValidation dv = list.get(0); - DVConstraint c = dv.getConstraint(); - assertEquals(ValidationType.FORMULA, c.getValidationType()); - assertEquals("A2:A3", c.getFormula1()); - assertEquals(null, c.getFormula2()); - assertEquals(null, c.getValue1()); - assertEquals(null, c.getValue2()); - wb.close(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestEmbeddedObjects.java b/src/testcases/org/apache/poi/hssf/usermodel/TestEmbeddedObjects.java deleted file mode 100644 index 7d9fadaa8..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestEmbeddedObjects.java +++ /dev/null @@ -1,62 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import junit.framework.TestCase; -import org.apache.poi.hssf.HSSFTestDataSamples; - -import java.io.IOException; -import java.util.List; - -/** - * Tests for the embedded object fetching support in HSSF - */ -public class TestEmbeddedObjects extends TestCase{ - public void testReadExistingObject() throws IOException { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("drawings.xls"); - List list = wb.getAllEmbeddedObjects(); - assertEquals(list.size(), 1); - HSSFObjectData obj = list.get(0); - assertNotNull(obj.getObjectData()); - assertNotNull(obj.getDirectory()); - assertNotNull(obj.getOLE2ClassName()); - } - - /** - * Need to recurse into the shapes to find this one - * See https://github.com/apache/poi/pull/2 - */ - public void testReadNestedObject() throws IOException { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("WithCheckBoxes.xls"); - List list = wb.getAllEmbeddedObjects(); - assertEquals(list.size(), 1); - HSSFObjectData obj = list.get(0); - assertNotNull(obj.getObjectData()); - assertNotNull(obj.getOLE2ClassName()); - } - - /** - * One with large numbers of recursivly embedded resources - * See https://github.com/apache/poi/pull/2 - */ - public void testReadManyNestedObjects() throws IOException { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("45538_form_Header.xls"); - List list = wb.getAllEmbeddedObjects(); - assertEquals(list.size(), 40); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestEscherGraphics.java b/src/testcases/org/apache/poi/hssf/usermodel/TestEscherGraphics.java deleted file mode 100644 index e6d569384..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestEscherGraphics.java +++ /dev/null @@ -1,307 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.awt.Color; -import java.awt.Font; -import java.awt.FontMetrics; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -/** - * Tests the capabilities of the EscherGraphics class. - * - * All tests have two escher groups available to them, - * one anchored at 0,0,1022,255 and another anchored - * at 20,30,500,200 - */ -public final class TestEscherGraphics { - private HSSFWorkbook workbook; - private HSSFPatriarch patriarch; - private HSSFShapeGroup escherGroupA; - private EscherGraphics graphics; - - @Before - public void setUp() throws IOException { - workbook = new HSSFWorkbook(); - - HSSFSheet sheet = workbook.createSheet("test"); - patriarch = sheet.createDrawingPatriarch(); - escherGroupA = patriarch.createGroup(new HSSFClientAnchor(0,0,1022,255,(short)0,0,(short) 0,0)); - patriarch.createGroup(new HSSFClientAnchor(20,30,500,200,(short)0,0,(short) 0,0)); - graphics = new EscherGraphics(escherGroupA, workbook, Color.black, 1.0f); - } - - @After - public void closeResources() throws IOException { - workbook.close(); - } - - @Test - public void testGetFont() { - Font f = graphics.getFont(); - if (f.toString().indexOf("dialog") == -1 && f.toString().indexOf("Dialog") == -1) { - assertEquals("java.awt.Font[family=Arial,name=Arial,style=plain,size=10]", f.toString()); - } - } - - @Test - public void testGetFontMetrics() { - Font f = graphics.getFont(); - if (f.toString().indexOf("dialog") != -1 || f.toString().indexOf("Dialog") != -1) { - return; - } - FontMetrics fontMetrics = graphics.getFontMetrics(graphics.getFont()); - assertEquals(7, fontMetrics.charWidth('X')); - assertEquals("java.awt.Font[family=Arial,name=Arial,style=plain,size=10]", fontMetrics.getFont().toString()); - } - - @Test - public void testSetFont() { - Font f = new Font("Helvetica", 0, 12); - graphics.setFont(f); - assertEquals(f, graphics.getFont()); - } - - @Test - public void testSetColor() { - graphics.setColor(Color.red); - assertEquals(Color.red, graphics.getColor()); - } - - @Test - public void testFillRect() { - graphics.fillRect( 10, 10, 20, 20 ); - HSSFSimpleShape s = (HSSFSimpleShape) escherGroupA.getChildren().get(0); - assertEquals(HSSFSimpleShape.OBJECT_TYPE_RECTANGLE, s.getShapeType()); - assertEquals(10, s.getAnchor().getDx1()); - assertEquals(10, s.getAnchor().getDy1()); - assertEquals(30, s.getAnchor().getDy2()); - assertEquals(30, s.getAnchor().getDx2()); - } - - @Test - public void testDrawString() { - graphics.drawString("This is a test", 10, 10); - HSSFTextbox t = (HSSFTextbox) escherGroupA.getChildren().get(0); - assertEquals("This is a test", t.getString().getString()); - } - - @Test - public void testGetDataBackAgain() throws Exception { - HSSFSheet s; - HSSFShapeGroup s1; - HSSFShapeGroup s2; - - patriarch.setCoordinates(10, 20, 30, 40); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - workbook.write(baos); - workbook = new HSSFWorkbook(new ByteArrayInputStream(baos.toByteArray())); - s = workbook.getSheetAt(0); - - patriarch = s.getDrawingPatriarch(); - - assertNotNull(patriarch); - assertEquals(10, patriarch.getX1()); - assertEquals(20, patriarch.getY1()); - assertEquals(30, patriarch.getX2()); - assertEquals(40, patriarch.getY2()); - - // Check the two groups too - assertEquals(2, patriarch.countOfAllChildren()); - assertTrue(patriarch.getChildren().get(0) instanceof HSSFShapeGroup); - assertTrue(patriarch.getChildren().get(1) instanceof HSSFShapeGroup); - - s1 = (HSSFShapeGroup)patriarch.getChildren().get(0); - s2 = (HSSFShapeGroup)patriarch.getChildren().get(1); - - assertEquals(0, s1.getX1()); - assertEquals(0, s1.getY1()); - assertEquals(1023, s1.getX2()); - assertEquals(255, s1.getY2()); - assertEquals(0, s2.getX1()); - assertEquals(0, s2.getY1()); - assertEquals(1023, s2.getX2()); - assertEquals(255, s2.getY2()); - - assertEquals(0, s1.getAnchor().getDx1()); - assertEquals(0, s1.getAnchor().getDy1()); - assertEquals(1022, s1.getAnchor().getDx2()); - assertEquals(255, s1.getAnchor().getDy2()); - assertEquals(20, s2.getAnchor().getDx1()); - assertEquals(30, s2.getAnchor().getDy1()); - assertEquals(500, s2.getAnchor().getDx2()); - assertEquals(200, s2.getAnchor().getDy2()); - - - // Write and re-load once more, to check that's ok - baos = new ByteArrayOutputStream(); - workbook.write(baos); - workbook = new HSSFWorkbook(new ByteArrayInputStream(baos.toByteArray())); - s = workbook.getSheetAt(0); - patriarch = s.getDrawingPatriarch(); - - assertNotNull(patriarch); - assertEquals(10, patriarch.getX1()); - assertEquals(20, patriarch.getY1()); - assertEquals(30, patriarch.getX2()); - assertEquals(40, patriarch.getY2()); - - // Check the two groups too - assertEquals(2, patriarch.countOfAllChildren()); - assertTrue(patriarch.getChildren().get(0) instanceof HSSFShapeGroup); - assertTrue(patriarch.getChildren().get(1) instanceof HSSFShapeGroup); - - s1 = (HSSFShapeGroup)patriarch.getChildren().get(0); - s2 = (HSSFShapeGroup)patriarch.getChildren().get(1); - - assertEquals(0, s1.getX1()); - assertEquals(0, s1.getY1()); - assertEquals(1023, s1.getX2()); - assertEquals(255, s1.getY2()); - assertEquals(0, s2.getX1()); - assertEquals(0, s2.getY1()); - assertEquals(1023, s2.getX2()); - assertEquals(255, s2.getY2()); - - assertEquals(0, s1.getAnchor().getDx1()); - assertEquals(0, s1.getAnchor().getDy1()); - assertEquals(1022, s1.getAnchor().getDx2()); - assertEquals(255, s1.getAnchor().getDy2()); - assertEquals(20, s2.getAnchor().getDx1()); - assertEquals(30, s2.getAnchor().getDy1()); - assertEquals(500, s2.getAnchor().getDx2()); - assertEquals(200, s2.getAnchor().getDy2()); - - // Change the positions of the first groups, - // but not of their anchors - s1.setCoordinates(2, 3, 1021, 242); - - baos = new ByteArrayOutputStream(); - workbook.write(baos); - workbook = new HSSFWorkbook(new ByteArrayInputStream(baos.toByteArray())); - s = workbook.getSheetAt(0); - patriarch = s.getDrawingPatriarch(); - - assertNotNull(patriarch); - assertEquals(10, patriarch.getX1()); - assertEquals(20, patriarch.getY1()); - assertEquals(30, patriarch.getX2()); - assertEquals(40, patriarch.getY2()); - - // Check the two groups too - assertEquals(2, patriarch.countOfAllChildren()); - assertEquals(2, patriarch.getChildren().size()); - assertTrue(patriarch.getChildren().get(0) instanceof HSSFShapeGroup); - assertTrue(patriarch.getChildren().get(1) instanceof HSSFShapeGroup); - - s1 = (HSSFShapeGroup)patriarch.getChildren().get(0); - s2 = (HSSFShapeGroup)patriarch.getChildren().get(1); - - assertEquals(2, s1.getX1()); - assertEquals(3, s1.getY1()); - assertEquals(1021, s1.getX2()); - assertEquals(242, s1.getY2()); - assertEquals(0, s2.getX1()); - assertEquals(0, s2.getY1()); - assertEquals(1023, s2.getX2()); - assertEquals(255, s2.getY2()); - - assertEquals(0, s1.getAnchor().getDx1()); - assertEquals(0, s1.getAnchor().getDy1()); - assertEquals(1022, s1.getAnchor().getDx2()); - assertEquals(255, s1.getAnchor().getDy2()); - assertEquals(20, s2.getAnchor().getDx1()); - assertEquals(30, s2.getAnchor().getDy1()); - assertEquals(500, s2.getAnchor().getDx2()); - assertEquals(200, s2.getAnchor().getDy2()); - - - // Now add some text to one group, and some more - // to the base, and check we can get it back again - HSSFTextbox tbox1 = - patriarch.createTextbox(new HSSFClientAnchor(1,2,3,4, (short)0,0,(short)0,0)); - tbox1.setString(new HSSFRichTextString("I am text box 1")); - HSSFTextbox tbox2 = - s2.createTextbox(new HSSFChildAnchor(41,42,43,44)); - tbox2.setString(new HSSFRichTextString("This is text box 2")); - - assertEquals(3, patriarch.getChildren().size()); - - - baos = new ByteArrayOutputStream(); - workbook.write(baos); - workbook = new HSSFWorkbook(new ByteArrayInputStream(baos.toByteArray())); - s = workbook.getSheetAt(0); - - patriarch = s.getDrawingPatriarch(); - - assertNotNull(patriarch); - assertEquals(10, patriarch.getX1()); - assertEquals(20, patriarch.getY1()); - assertEquals(30, patriarch.getX2()); - assertEquals(40, patriarch.getY2()); - - // Check the two groups and the text - // Result of patriarch.countOfAllChildren() makes no sense: - // Returns 4 for 2 empty groups + 1 TextBox. - //assertEquals(3, patriarch.countOfAllChildren()); - assertEquals(3, patriarch.getChildren().size()); - - // Should be two groups and a text - assertTrue(patriarch.getChildren().get(0) instanceof HSSFShapeGroup); - assertTrue(patriarch.getChildren().get(1) instanceof HSSFShapeGroup); - assertTrue(patriarch.getChildren().get(2) instanceof HSSFTextbox); - - s1 = (HSSFShapeGroup)patriarch.getChildren().get(0); - tbox1 = (HSSFTextbox)patriarch.getChildren().get(2); - - s2 = (HSSFShapeGroup)patriarch.getChildren().get(1); - - assertEquals(2, s1.getX1()); - assertEquals(3, s1.getY1()); - assertEquals(1021, s1.getX2()); - assertEquals(242, s1.getY2()); - assertEquals(0, s2.getX1()); - assertEquals(0, s2.getY1()); - assertEquals(1023, s2.getX2()); - assertEquals(255, s2.getY2()); - - assertEquals(0, s1.getAnchor().getDx1()); - assertEquals(0, s1.getAnchor().getDy1()); - assertEquals(1022, s1.getAnchor().getDx2()); - assertEquals(255, s1.getAnchor().getDy2()); - assertEquals(20, s2.getAnchor().getDx1()); - assertEquals(30, s2.getAnchor().getDy1()); - assertEquals(500, s2.getAnchor().getDx2()); - assertEquals(200, s2.getAnchor().getDy2()); - - // Not working just yet - assertEquals("I am text box 1", tbox1.getString().getString()); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestEscherGraphics2d.java b/src/testcases/org/apache/poi/hssf/usermodel/TestEscherGraphics2d.java deleted file mode 100644 index b0b4293a7..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestEscherGraphics2d.java +++ /dev/null @@ -1,149 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.awt.Color; -import java.awt.Font; -import java.awt.FontMetrics; -import java.awt.geom.Line2D; -import java.io.IOException; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -/** - * Tests the Graphics2d drawing capability. - */ -public final class TestEscherGraphics2d { - private HSSFWorkbook workbook; - private HSSFShapeGroup escherGroup; - private EscherGraphics2d graphics; - - @Before - public void setUp() { - workbook = new HSSFWorkbook(); - HSSFSheet sheet = workbook.createSheet("test"); - escherGroup = sheet.createDrawingPatriarch().createGroup(new HSSFClientAnchor(0,0,1023,255,(short)0,0,(short) 0,0)); - escherGroup = new HSSFShapeGroup(null, new HSSFChildAnchor()); - EscherGraphics g = new EscherGraphics(escherGroup, workbook, Color.black, 1.0f); - graphics = new EscherGraphics2d(g); - } - - @After - public void closeResources() throws IOException { - workbook.close(); - } - - @Test - public void testDrawString() { - graphics.drawString("This is a test", 10, 10); - HSSFTextbox t = (HSSFTextbox) escherGroup.getChildren().get(0); - assertEquals("This is a test", t.getString().getString()); - - // Check that with a valid font, it's still ok - Font font = new Font("Forte", Font.PLAIN, 12); - graphics.setFont(font); - graphics.drawString("This is another test", 10, 10); - - // And test with ones that need the style appending - font = new Font("dialog", Font.PLAIN, 12); - graphics.setFont(font); - graphics.drawString("This is another test", 10, 10); - - font = new Font("dialog", Font.BOLD, 12); - graphics.setFont(font); - graphics.drawString("This is another test", 10, 10); - - // But with an invalid font, we get an exception - font = new Font("IamAmadeUPfont", Font.PLAIN, 22); - graphics.setFont(font); - try { - graphics.drawString("This is another test", 10, 10); - fail(); - } catch(IllegalArgumentException e) { - // expected - } - } - - @Test - public void testFillRect() { - graphics.fillRect( 10, 10, 20, 20 ); - HSSFSimpleShape s = (HSSFSimpleShape) escherGroup.getChildren().get(0); - assertEquals(HSSFSimpleShape.OBJECT_TYPE_RECTANGLE, s.getShapeType()); - assertEquals(10, s.getAnchor().getDx1()); - assertEquals(10, s.getAnchor().getDy1()); - assertEquals(30, s.getAnchor().getDy2()); - assertEquals(30, s.getAnchor().getDx2()); - } - - @Test - public void testGetFontMetrics() { - FontMetrics fontMetrics = graphics.getFontMetrics(graphics.getFont()); - if (isDialogPresent()) { - // if dialog is returned we can't run the test properly. - return; - } - assertEquals(7, fontMetrics.charWidth('X')); - assertEquals("java.awt.Font[family=Arial,name=Arial,style=plain,size=10]", fontMetrics.getFont().toString()); - } - - @Test - public void testSetFont() { - Font f = new Font("Helvetica", 0, 12); - graphics.setFont(f); - assertEquals(f, graphics.getFont()); - } - - @Test - public void testSetColor() { - graphics.setColor(Color.red); - assertEquals(Color.red, graphics.getColor()); - } - - @Test - public void testGetFont() { - Font f = graphics.getFont(); - if (isDialogPresent()) { - // if dialog is returned we can't run the test properly. - return; - } - - assertEquals("java.awt.Font[family=Arial,name=Arial,style=plain,size=10]", f.toString()); - } - - private boolean isDialogPresent() { - String fontDebugStr = graphics.getFont().toString(); - return fontDebugStr.indexOf("dialog") != -1 || fontDebugStr.indexOf("Dialog") != -1; - } - - @Test - public void testDraw() { - graphics.draw(new Line2D.Double(10,10,20,20)); - HSSFSimpleShape s = (HSSFSimpleShape) escherGroup.getChildren().get(0); - assertTrue(s.getShapeType() == HSSFSimpleShape.OBJECT_TYPE_LINE); - assertEquals(10, s.getAnchor().getDx1()); - assertEquals(10, s.getAnchor().getDy1()); - assertEquals(20, s.getAnchor().getDx2()); - assertEquals(20, s.getAnchor().getDy2()); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestExternalReferenceChange.java b/src/testcases/org/apache/poi/hssf/usermodel/TestExternalReferenceChange.java deleted file mode 100644 index a059f1f56..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestExternalReferenceChange.java +++ /dev/null @@ -1,68 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hssf.usermodel; - -import java.io.IOException; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.ss.usermodel.CellType; - -import junit.framework.TestCase; - -public class TestExternalReferenceChange extends TestCase { - - private static final String MAIN_WORKBOOK_FILENAME = "52575_main.xls"; - private static final String SOURCE_DUMMY_WORKBOOK_FILENAME = "source_dummy.xls"; - private static final String SOURCE_WORKBOOK_FILENAME = "52575_source.xls"; - - private HSSFWorkbook mainWorkbook; - private HSSFWorkbook sourceWorkbook; - - @Override - protected void setUp() throws Exception { - mainWorkbook = HSSFTestDataSamples.openSampleWorkbook(MAIN_WORKBOOK_FILENAME); - sourceWorkbook = HSSFTestDataSamples.openSampleWorkbook(SOURCE_WORKBOOK_FILENAME); - - assertNotNull(mainWorkbook); - assertNotNull(sourceWorkbook); - } - - public void testDummyToSource() throws IOException { - boolean changed = mainWorkbook.changeExternalReference("DOESNOTEXIST", SOURCE_WORKBOOK_FILENAME); - assertFalse(changed); - - changed = mainWorkbook.changeExternalReference(SOURCE_DUMMY_WORKBOOK_FILENAME, SOURCE_WORKBOOK_FILENAME); - assertTrue(changed); - - HSSFSheet lSheet = mainWorkbook.getSheetAt(0); - HSSFCell lA1Cell = lSheet.getRow(0).getCell(0); - - assertEquals(CellType.FORMULA, lA1Cell.getCellTypeEnum()); - - HSSFFormulaEvaluator lMainWorkbookEvaluator = new HSSFFormulaEvaluator(mainWorkbook); - HSSFFormulaEvaluator lSourceEvaluator = new HSSFFormulaEvaluator(sourceWorkbook); - HSSFFormulaEvaluator.setupEnvironment( - new String[]{MAIN_WORKBOOK_FILENAME, SOURCE_WORKBOOK_FILENAME}, - new HSSFFormulaEvaluator[] {lMainWorkbookEvaluator, lSourceEvaluator}); - - assertEquals(CellType.NUMERIC, lMainWorkbookEvaluator.evaluateFormulaCellEnum(lA1Cell)); - - assertEquals(20.0d, lA1Cell.getNumericCellValue(), 0.00001d); - - } - -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestFontDetails.java b/src/testcases/org/apache/poi/hssf/usermodel/TestFontDetails.java deleted file mode 100644 index 724d26432..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestFontDetails.java +++ /dev/null @@ -1,56 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import junit.framework.TestCase; - -import java.util.Properties; - -/** - * Tests the implementation of the FontDetails class. - * - * @author Glen Stampoultzis (glens at apache.org) - */ -public final class TestFontDetails extends TestCase { - private Properties properties; - private FontDetails fontDetails; - - @Override - protected void setUp() { - properties = new Properties(); - properties.setProperty("font.Arial.height", "13"); - properties.setProperty("font.Arial.characters", "a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "); - properties.setProperty("font.Arial.widths", "6, 6, 6, 6, 6, 3, 6, 6, 3, 4, 6, 3, 9, 6, 6, 6, 6, 4, 6, 3, 6, 7, 9, 6, 5, 5, 7, 7, 7, 7, 7, 6, 8, 7, 3, 6, 7, 6, 9, 7, 8, 7, 8, 7, 7, 5, 7, 7, 9, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, "); - fontDetails = FontDetails.create("Arial", properties); - } - - public void testCreate() { - assertEquals(13, fontDetails.getHeight()); - assertEquals(6, fontDetails.getCharWidth('a')); - assertEquals(3, fontDetails.getCharWidth('f')); - } - - public void testGetStringWidth() { - assertEquals(9, fontDetails.getStringWidth("af")); - } - - public void testGetCharWidth() { - assertEquals(6, fontDetails.getCharWidth('a')); - assertEquals(9, fontDetails.getCharWidth('=')); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestFormulaEvaluatorBugs.java b/src/testcases/org/apache/poi/hssf/usermodel/TestFormulaEvaluatorBugs.java deleted file mode 100644 index 9e8c4a3ef..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestFormulaEvaluatorBugs.java +++ /dev/null @@ -1,584 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -import java.io.File; -import java.io.FileOutputStream; -import java.util.Calendar; -import java.util.Iterator; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.record.FormulaRecord; -import org.apache.poi.hssf.record.aggregates.FormulaRecordAggregate; -import org.apache.poi.ss.formula.EvaluationCell; -import org.apache.poi.ss.formula.EvaluationListener; -import org.apache.poi.ss.formula.WorkbookEvaluator; -import org.apache.poi.ss.formula.WorkbookEvaluatorTestHelper; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.ss.formula.ptg.AreaPtg; -import org.apache.poi.ss.formula.ptg.FuncPtg; -import org.apache.poi.ss.formula.ptg.FuncVarPtg; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.apache.poi.ss.formula.ptg.RefPtg; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.util.LocaleUtil; -import org.junit.BeforeClass; -import org.junit.Test; - -/** - * - */ -public final class TestFormulaEvaluatorBugs { - private static boolean OUTPUT_TEST_FILES = false; - private static String tmpDirName; - - @BeforeClass - public static void setUp() { - tmpDirName = System.getProperty("java.io.tmpdir"); - OUTPUT_TEST_FILES = Boolean.parseBoolean( - System.getProperty("org.apache.poi.test.output_test_files", "False")); - } - - /** - * An odd problem with evaluateFormulaCell giving the - * right values when file is opened, but changes - * to the source data in some versions of excel - * doesn't cause them to be updated. However, other - * versions of excel, and gnumeric, work just fine - * WARNING - tedious bug where you actually have to - * open up excel - */ - @Test - public void test44636() throws Exception { - // Open the existing file, tweak one value and - // re-calculate - - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("44636.xls"); - HSSFSheet sheet = wb.getSheetAt(0); - HSSFRow row = sheet.getRow(0); - - row.getCell(0).setCellValue(4.2); - row.getCell(2).setCellValue(25); - - HSSFFormulaEvaluator.evaluateAllFormulaCells(wb); - assertEquals(4.2 * 25, row.getCell(3).getNumericCellValue(), 0.0001); - - if (OUTPUT_TEST_FILES) { - // Save - File existing = new File(tmpDirName, "44636-existing.xls"); - FileOutputStream out = new FileOutputStream(existing); - wb.write(out); - out.close(); - System.err.println("Existing file for bug #44636 written to " + existing.toString()); - } - wb.close(); - - // Now, do a new file from scratch - wb = new HSSFWorkbook(); - sheet = wb.createSheet(); - - row = sheet.createRow(0); - row.createCell(0).setCellValue(1.2); - row.createCell(1).setCellValue(4.2); - - row = sheet.createRow(1); - row.createCell(0).setCellFormula("SUM(A1:B1)"); - - HSSFFormulaEvaluator.evaluateAllFormulaCells(wb); - assertEquals(5.4, row.getCell(0).getNumericCellValue(), 0.0001); - - if (OUTPUT_TEST_FILES) { - // Save - File scratch = new File(tmpDirName, "44636-scratch.xls"); - FileOutputStream out = new FileOutputStream(scratch); - wb.write(out); - out.close(); - System.err.println("New file for bug #44636 written to " + scratch.toString()); - } - wb.close(); - } - - /** - * Bug 44297: 32767+32768 is evaluated to -1 - * Fix: IntPtg must operate with unsigned short. Reading signed short results in incorrect formula calculation - * if a formula has values in the interval [Short.MAX_VALUE, (Short.MAX_VALUE+1)*2] - */ - @Test - public void test44297() throws Exception { - - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("44297.xls"); - - HSSFRow row; - HSSFCell cell; - - HSSFSheet sheet = wb.getSheetAt(0); - - HSSFFormulaEvaluator eva = new HSSFFormulaEvaluator(wb); - - row = sheet.getRow(0); - cell = row.getCell(0); - assertEquals("31+46", cell.getCellFormula()); - assertEquals(77, eva.evaluate(cell).getNumberValue(), 0); - - row = sheet.getRow(1); - cell = row.getCell(0); - assertEquals("30+53", cell.getCellFormula()); - assertEquals(83, eva.evaluate(cell).getNumberValue(), 0); - - row = sheet.getRow(2); - cell = row.getCell(0); - assertEquals("SUM(A1:A2)", cell.getCellFormula()); - assertEquals(160, eva.evaluate(cell).getNumberValue(), 0); - - row = sheet.getRow(4); - cell = row.getCell(0); - assertEquals("32767+32768", cell.getCellFormula()); - assertEquals(65535, eva.evaluate(cell).getNumberValue(), 0); - - row = sheet.getRow(7); - cell = row.getCell(0); - assertEquals("32744+42333", cell.getCellFormula()); - assertEquals(75077, eva.evaluate(cell).getNumberValue(), 0); - - row = sheet.getRow(8); - cell = row.getCell(0); - assertEquals("327680/32768", cell.getCellFormula()); - assertEquals(10, eva.evaluate(cell).getNumberValue(), 0); - - row = sheet.getRow(9); - cell = row.getCell(0); - assertEquals("32767+32769", cell.getCellFormula()); - assertEquals(65536, eva.evaluate(cell).getNumberValue(), 0); - - row = sheet.getRow(10); - cell = row.getCell(0); - assertEquals("35000+36000", cell.getCellFormula()); - assertEquals(71000, eva.evaluate(cell).getNumberValue(), 0); - - row = sheet.getRow(11); - cell = row.getCell(0); - assertEquals("-1000000-3000000", cell.getCellFormula()); - assertEquals(-4000000, eva.evaluate(cell).getNumberValue(), 0); - - wb.close(); - } - - /** - * Bug 44410: SUM(C:C) is valid in excel, and means a sum - * of all the rows in Column C - */ - @Test - public void test44410() throws Exception { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("SingleLetterRanges.xls"); - - HSSFSheet sheet = wb.getSheetAt(0); - - HSSFFormulaEvaluator eva = new HSSFFormulaEvaluator(wb); - - // =index(C:C,2,1) -> 2 - HSSFRow rowIDX = sheet.getRow(3); - // =sum(C:C) -> 6 - HSSFRow rowSUM = sheet.getRow(4); - // =sum(C:D) -> 66 - HSSFRow rowSUM2D = sheet.getRow(5); - - // Test the sum - HSSFCell cellSUM = rowSUM.getCell(0); - - FormulaRecordAggregate frec = (FormulaRecordAggregate) cellSUM.getCellValueRecord(); - Ptg[] ops = frec.getFormulaRecord().getParsedExpression(); - assertEquals(2, ops.length); - assertEquals(AreaPtg.class, ops[0].getClass()); - assertEquals(FuncVarPtg.class, ops[1].getClass()); - - // Actually stored as C1 to C65536 - // (last row is -1 === 65535) - AreaPtg ptg = (AreaPtg) ops[0]; - assertEquals(2, ptg.getFirstColumn()); - assertEquals(2, ptg.getLastColumn()); - assertEquals(0, ptg.getFirstRow()); - assertEquals(65535, ptg.getLastRow()); - assertEquals("C:C", ptg.toFormulaString()); - - // Will show as C:C, but won't know how many - // rows it covers as we don't have the sheet - // to hand when turning the Ptgs into a string - assertEquals("SUM(C:C)", cellSUM.getCellFormula()); - - // But the evaluator knows the sheet, so it - // can do it properly - assertEquals(6, eva.evaluate(cellSUM).getNumberValue(), 0); - - // Test the index - // Again, the formula string will be right but - // lacking row count, evaluated will be right - HSSFCell cellIDX = rowIDX.getCell(0); - assertEquals("INDEX(C:C,2,1)", cellIDX.getCellFormula()); - assertEquals(2, eva.evaluate(cellIDX).getNumberValue(), 0); - - // Across two colums - HSSFCell cellSUM2D = rowSUM2D.getCell(0); - assertEquals("SUM(C:D)", cellSUM2D.getCellFormula()); - assertEquals(66, eva.evaluate(cellSUM2D).getNumberValue(), 0); - - wb.close(); - } - - /** - * Tests that we can evaluate boolean cells properly - */ - @Test - public void testEvaluateBooleanInCell_bug44508() throws Exception { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet(); - wb.setSheetName(0, "Sheet1"); - HSSFRow row = sheet.createRow(0); - HSSFCell cell = row.createCell(0); - - cell.setCellFormula("1=1"); - - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - try { - fe.evaluateInCell(cell); - } catch (NumberFormatException e) { - fail("Identified bug 44508"); - } - assertEquals(true, cell.getBooleanCellValue()); - - wb.close(); - } - - @Test - public void testClassCast_bug44861() throws Exception { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("44861.xls"); - - // Check direct - HSSFFormulaEvaluator.evaluateAllFormulaCells(wb); - - // And via calls - int numSheets = wb.getNumberOfSheets(); - for (int i = 0; i < numSheets; i++) { - HSSFSheet s = wb.getSheetAt(i); - HSSFFormulaEvaluator eval = new HSSFFormulaEvaluator(wb); - - for (Iterator rows = s.rowIterator(); rows.hasNext();) { - HSSFRow r = (HSSFRow)rows.next(); - for (Iterator cells = r.cellIterator(); cells.hasNext();) { - HSSFCell c = (HSSFCell)cells.next(); - eval.evaluateFormulaCellEnum(c); - } - } - } - - wb.close(); - } - - @Test - public void testEvaluateInCellWithErrorCode_bug44950() throws Exception { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("Sheet1"); - HSSFRow row = sheet.createRow(1); - HSSFCell cell = row.createCell(0); - cell.setCellFormula("na()"); // this formula evaluates to an Excel error code '#N/A' - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - try { - fe.evaluateInCell(cell); - } catch (NumberFormatException e) { - if (e.getMessage().equals("You cannot get an error value from a non-error cell")) { - fail("Identified bug 44950 b"); - } - throw e; - } finally { - wb.close(); - } - } - - @Test - public void testDateWithNegativeParts_bug48528() throws Exception { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("Sheet1"); - HSSFRow row = sheet.createRow(1); - HSSFCell cell = row.createCell(0); - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - - // 5th Feb 2012 = 40944 - // 1st Feb 2012 = 40940 - // 5th Jan 2012 = 40913 - // 5th Dec 2011 = 40882 - // 5th Feb 2011 = 40579 - - cell.setCellFormula("DATE(2012,2,1)"); - fe.notifyUpdateCell(cell); - assertEquals(40940.0, fe.evaluate(cell).getNumberValue(), 0); - - cell.setCellFormula("DATE(2012,2,1+4)"); - fe.notifyUpdateCell(cell); - assertEquals(40944.0, fe.evaluate(cell).getNumberValue(), 0); - - cell.setCellFormula("DATE(2012,2-1,1+4)"); - fe.notifyUpdateCell(cell); - assertEquals(40913.0, fe.evaluate(cell).getNumberValue(), 0); - - cell.setCellFormula("DATE(2012,2,1-27)"); - fe.notifyUpdateCell(cell); - assertEquals(40913.0, fe.evaluate(cell).getNumberValue(), 0); - - cell.setCellFormula("DATE(2012,2-2,1+4)"); - fe.notifyUpdateCell(cell); - assertEquals(40882.0, fe.evaluate(cell).getNumberValue(), 0); - - cell.setCellFormula("DATE(2012,2,1-58)"); - fe.notifyUpdateCell(cell); - assertEquals(40882.0, fe.evaluate(cell).getNumberValue(), 0); - - cell.setCellFormula("DATE(2012,2-12,1+4)"); - fe.notifyUpdateCell(cell); - assertEquals(40579.0, fe.evaluate(cell).getNumberValue(), 0); - - wb.close(); - } - - private static final class EvalListener extends EvaluationListener { - private int _countCacheHits; - private int _countCacheMisses; - - public EvalListener() { - _countCacheHits = 0; - _countCacheMisses = 0; - } - public int getCountCacheHits() { - return _countCacheHits; - } - public int getCountCacheMisses() { - return _countCacheMisses; - } - - @Override - public void onCacheHit(int sheetIndex, int srcRowNum, int srcColNum, ValueEval result) { - _countCacheHits++; - } - @Override - public void onStartEvaluate(EvaluationCell cell, ICacheEntry entry) { - _countCacheMisses++; - } - } - - /** - * The HSSFFormula evaluator performance benefits greatly from caching of intermediate cell values - */ - @Test - public void testSlowEvaluate45376() throws Exception { - /* - * Note - to observe behaviour without caching, disable the call to - * updateValue() from FormulaCellCacheEntry.updateFormulaResult(). - */ - - // Firstly set up a sequence of formula cells where each depends on the previous multiple - // times. Without caching, each subsequent cell take about 4 times longer to evaluate. - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("Sheet1"); - HSSFRow row = sheet.createRow(0); - for(int i=1; i<10; i++) { - HSSFCell cell = row.createCell(i); - char prevCol = (char) ('A' + i-1); - String prevCell = prevCol + "1"; - // this formula is inspired by the offending formula of the attachment for bug 45376 - // IF(DATE(YEAR(A1),MONTH(A1)+1,1)<=$D$3,DATE(YEAR(A1),MONTH(A1)+1,1),NA()) etc - String formula = "IF(DATE(YEAR(" + prevCell + "),MONTH(" + prevCell + ")+1,1)<=$D$3," + - "DATE(YEAR(" + prevCell + "),MONTH(" + prevCell + ")+1,1),NA())"; - cell.setCellFormula(formula); - } - Calendar cal = LocaleUtil.getLocaleCalendar(2000, 0, 1, 0, 0, 0); - row.createCell(0).setCellValue(cal); - - // Choose cell A9 instead of A10, so that the failing test case doesn't take too long to execute. - HSSFCell cell = row.getCell(8); - EvalListener evalListener = new EvalListener(); - WorkbookEvaluator evaluator = WorkbookEvaluatorTestHelper.createEvaluator(wb, evalListener); - ValueEval ve = evaluator.evaluate(HSSFEvaluationTestHelper.wrapCell(cell)); - int evalCount = evalListener.getCountCacheMisses(); - if (evalCount > 10) { - // Without caching, evaluating cell 'A9' takes 21845 evaluations which consumes - // much time (~3 sec on Core 2 Duo 2.2GHz) - // short-circuit-if optimisation cuts this down to 255 evaluations which is still too high - // System.err.println("Cell A9 took " + evalCount + " intermediate evaluations"); - fail("Identifed bug 45376 - Formula evaluator should cache values"); - } - // With caching, the evaluationCount is 8 which is exactly the - // number of formula cells that needed to be evaluated. - assertEquals(8, evalCount); - - // The cache hits would be 24 if fully evaluating all arguments of the - // "IF()" functions (Each of the 8 formulas has 4 refs to formula cells - // which result in 1 cache miss and 3 cache hits). However with the - // short-circuit-if optimisation, 2 of the cell refs get skipped - // reducing this metric 8. - assertEquals(8, evalListener.getCountCacheHits()); - - // confirm the evaluation result too - assertEquals(ErrorEval.NA, ve); - - wb.close(); - } - - @SuppressWarnings("resource") - @Test - public void test55747_55324() throws Exception { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFFormulaEvaluator ev = wb.getCreationHelper().createFormulaEvaluator(); - HSSFSheet ws = wb.createSheet(); - HSSFRow row = ws.createRow(0); - HSSFCell cell; - - // Our test value - cell = row.createCell(0); - cell.setCellValue("abc"); - - // Lots of IF cases - - cell = row.createCell(1); - cell.setCellFormula("IF(A1<>\"\",MID(A1,1,2),\"X\")");//if(expr,func,val) - - cell = row.createCell(2); - cell.setCellFormula("IF(A1<>\"\",\"A\",\"B\")");// if(expr,val,val) - - cell = row.createCell(3); - cell.setCellFormula("IF(A1=\"\",\"X\",MID(A1,1,2))");//if(expr,val,func), - - cell = row.createCell(4); - cell.setCellFormula("IF(A1<>\"\",\"X\",MID(A1,1,2))");//if(expr,val,func), - - cell = row.createCell(5); - cell.setCellFormula("IF(A1=\"\",MID(A1,1,2),MID(A1,2,2))");//if(exp,func,func) - cell = row.createCell(6); - cell.setCellFormula("IF(A1<>\"\",MID(A1,1,2),MID(A1,2,2))");//if(exp,func,func) - - cell = row.createCell(7); - cell.setCellFormula("IF(MID(A1,1,2)<>\"\",\"A\",\"B\")");//if(func_expr,val,val) - - // And some MID ones just to check - row = ws.createRow(1); - cell = row.createCell(1); - cell.setCellFormula("MID(A1,1,2)"); - cell = row.createCell(2); - cell.setCellFormula("MID(A1,2,2)"); - cell = row.createCell(3); - cell.setCellFormula("MID(A1,2,1)"); - cell = row.createCell(4); - cell.setCellFormula("MID(A1,3,1)"); - - // Evaluate - ev.evaluateAll(); - - // Save and re-load - wb = HSSFTestDataSamples.writeOutAndReadBack(wb); - ws = wb.getSheetAt(0); - - // Check the MID Ptgs in Row 2 have V RefPtgs for A1 - row = ws.getRow(1); - for (int i=1; i<=4; i++) { - cell = row.getCell(i); - Ptg[] ptgs = getPtgs(cell); - assertEquals(4, ptgs.length); - assertEquals(FuncPtg.class, ptgs[3].getClass()); - assertEquals("MID", ((FuncPtg)ptgs[3]).getName()); - assertRefPtgA1('V', ptgs, 0); - } - - // Now check the IF formulas - row = ws.getRow(0); - - // H1, MID is used in the expression IF checks, so A1 should be V - cell = row.getCell(CellReference.convertColStringToIndex("H")); - assertRefPtgA1('V', getPtgs(cell), 0); - - // E1, MID is used in the FALSE route, so: - // A1 should be V in the IF check - // A1 should be R in the FALSE route - cell = row.getCell(CellReference.convertColStringToIndex("E")); - assertRefPtgA1('V', getPtgs(cell), 0); - assertRefPtgA1('R', getPtgs(cell), 6); - - // Check that, for B1, D1, F1 and G1, the references to A1 - // from all of IF check, True and False are V - cell = row.getCell(CellReference.convertColStringToIndex("B")); - assertRefPtgA1('V', getPtgs(cell), 0); -// assertRefPtgA1('V', getPtgs(cell), 4); // FIXME! - - cell = row.getCell(CellReference.convertColStringToIndex("D")); - assertRefPtgA1('V', getPtgs(cell), 0); -// assertRefPtgA1('V', getPtgs(cell), 6); // FIXME! - - cell = row.getCell(CellReference.convertColStringToIndex("F")); - assertRefPtgA1('V', getPtgs(cell), 0); -// assertRefPtgA1('V', getPtgs(cell), 4); // FIXME! -// assertRefPtgA1('V', getPtgs(cell), 9); // FIXME! - - cell = row.getCell(CellReference.convertColStringToIndex("G")); - assertRefPtgA1('V', getPtgs(cell), 0); -// assertRefPtgA1('V', getPtgs(cell), 4); // FIXME! -// assertRefPtgA1('V', getPtgs(cell), 9); // FIXME! - - - // Check our cached values were correctly evaluated - cell = row.getCell(CellReference.convertColStringToIndex("A")); - assertEquals("abc", cell.getStringCellValue()); - cell = row.getCell(CellReference.convertColStringToIndex("B")); - assertEquals("ab", cell.getStringCellValue()); - cell = row.getCell(CellReference.convertColStringToIndex("C")); - assertEquals("A", cell.getStringCellValue()); - cell = row.getCell(CellReference.convertColStringToIndex("D")); - assertEquals("ab", cell.getStringCellValue()); - cell = row.getCell(CellReference.convertColStringToIndex("E")); - assertEquals("X", cell.getStringCellValue()); - cell = row.getCell(CellReference.convertColStringToIndex("F")); - assertEquals("bc", cell.getStringCellValue()); - cell = row.getCell(CellReference.convertColStringToIndex("G")); - assertEquals("ab", cell.getStringCellValue()); - cell = row.getCell(CellReference.convertColStringToIndex("H")); - assertEquals("A", cell.getStringCellValue()); - - // Enable this to write out + check in Excel - if (OUTPUT_TEST_FILES) { - FileOutputStream out = new FileOutputStream("/tmp/test.xls"); - wb.write(out); - out.close(); - } - } - private Ptg[] getPtgs(HSSFCell cell) { - assertEquals(CellType.FORMULA, cell.getCellTypeEnum()); - assertEquals(FormulaRecordAggregate.class, cell.getCellValueRecord().getClass()); - FormulaRecordAggregate agg = (FormulaRecordAggregate)cell.getCellValueRecord(); - FormulaRecord rec = agg.getFormulaRecord(); - return rec.getParsedExpression(); - } - private void assertRefPtgA1(char rv, Ptg[] ptgs, int at) { - Ptg ptg = ptgs[at]; - assertEquals(RefPtg.class, ptg.getClass()); - assertEquals(0, ((RefPtg)ptg).getRow()); - assertEquals(0, ((RefPtg)ptg).getColumn()); - assertEquals(rv, ((RefPtg)ptg).getRVAType()); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestFormulaEvaluatorDocs.java b/src/testcases/org/apache/poi/hssf/usermodel/TestFormulaEvaluatorDocs.java deleted file mode 100644 index 5e52a0c14..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestFormulaEvaluatorDocs.java +++ /dev/null @@ -1,123 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; - -import junit.framework.TestCase; - -/** - * Tests to show that our documentation at - * http://poi.apache.org/hssf/eval.html - * all actually works as we'd expect them to - */ -public final class TestFormulaEvaluatorDocs extends TestCase { - - /** - * http://poi.apache.org/hssf/eval.html#EvaluateAll - */ - public void testEvaluateAll() { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet s1 = wb.createSheet(); - HSSFSheet s2 = wb.createSheet(); - wb.setSheetName(0, "S1"); - wb.setSheetName(1, "S2"); - - HSSFRow s1r1 = s1.createRow(0); - HSSFRow s1r2 = s1.createRow(1); - HSSFRow s2r1 = s2.createRow(0); - - HSSFCell s1r1c1 = s1r1.createCell(0); - HSSFCell s1r1c2 = s1r1.createCell(1); - HSSFCell s1r1c3 = s1r1.createCell(2); - s1r1c1.setCellValue(22.3); - s1r1c2.setCellValue(33.4); - s1r1c3.setCellFormula("SUM(A1:B1)"); - - HSSFCell s1r2c1 = s1r2.createCell(0); - HSSFCell s1r2c2 = s1r2.createCell(1); - HSSFCell s1r2c3 = s1r2.createCell(2); - s1r2c1.setCellValue(-1.2); - s1r2c2.setCellValue(-3.4); - s1r2c3.setCellFormula("SUM(A2:B2)"); - - HSSFCell s2r1c1 = s2r1.createCell(0); - s2r1c1.setCellFormula("S1!A1"); - - // Not evaluated yet - assertEquals(0.0, s1r1c3.getNumericCellValue(), 0); - assertEquals(0.0, s1r2c3.getNumericCellValue(), 0); - assertEquals(0.0, s2r1c1.getNumericCellValue(), 0); - - // Do a full evaluate, as per our docs - // uses evaluateFormulaCell() - for(Sheet sheet : wb) { - HSSFFormulaEvaluator evaluator = new HSSFFormulaEvaluator(wb); - for(Row r : sheet) { - for(Cell c : r) { - if(c.getCellTypeEnum() == CellType.FORMULA) { - evaluator.evaluateFormulaCellEnum(c); - - // For testing - all should be numeric - assertEquals(CellType.NUMERIC, evaluator.evaluateFormulaCellEnum(c)); - } - } - } - } - - // Check now as expected - assertEquals(55.7, wb.getSheetAt(0).getRow(0).getCell(2).getNumericCellValue(), 0); - assertEquals("SUM(A1:B1)", wb.getSheetAt(0).getRow(0).getCell(2).getCellFormula()); - assertEquals(CellType.FORMULA, wb.getSheetAt(0).getRow(0).getCell(2).getCellTypeEnum()); - - assertEquals(-4.6, wb.getSheetAt(0).getRow(1).getCell(2).getNumericCellValue(), 0); - assertEquals("SUM(A2:B2)", wb.getSheetAt(0).getRow(1).getCell(2).getCellFormula()); - assertEquals(CellType.FORMULA, wb.getSheetAt(0).getRow(1).getCell(2).getCellTypeEnum()); - - assertEquals(22.3, wb.getSheetAt(1).getRow(0).getCell(0).getNumericCellValue(), 0); - assertEquals("'S1'!A1", wb.getSheetAt(1).getRow(0).getCell(0).getCellFormula()); - assertEquals(CellType.FORMULA, wb.getSheetAt(1).getRow(0).getCell(0).getCellTypeEnum()); - - - // Now do the alternate call, which zaps the formulas - // uses evaluateInCell() - for(Sheet sheet : wb) { - HSSFFormulaEvaluator evaluator = new HSSFFormulaEvaluator(wb); - - for(Row r : sheet) { - for(Cell c : r) { - if(c.getCellTypeEnum() == CellType.FORMULA) { - evaluator.evaluateInCell(c); - } - } - } - } - - assertEquals(55.7, wb.getSheetAt(0).getRow(0).getCell(2).getNumericCellValue(), 0); - assertEquals(CellType.NUMERIC, wb.getSheetAt(0).getRow(0).getCell(2).getCellTypeEnum()); - - assertEquals(-4.6, wb.getSheetAt(0).getRow(1).getCell(2).getNumericCellValue(), 0); - assertEquals(CellType.NUMERIC, wb.getSheetAt(0).getRow(1).getCell(2).getCellTypeEnum()); - - assertEquals(22.3, wb.getSheetAt(1).getRow(0).getCell(0).getNumericCellValue(), 0); - assertEquals(CellType.NUMERIC, wb.getSheetAt(1).getRow(0).getCell(0).getCellTypeEnum()); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestFormulas.java b/src/testcases/org/apache/poi/hssf/usermodel/TestFormulas.java deleted file mode 100644 index 73d0de582..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestFormulas.java +++ /dev/null @@ -1,1053 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Date; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.model.HSSFFormulaParser; -import org.apache.poi.hssf.util.CellReference; -import org.apache.poi.ss.formula.FormulaType; -import org.apache.poi.ss.formula.ptg.NamePtg; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Name; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.util.TempFile; -import org.junit.Test; - -public final class TestFormulas { - - private static HSSFWorkbook openSample(String sampleFileName) { - return HSSFTestDataSamples.openSampleWorkbook(sampleFileName); - } - - /** - * Add 1+1 -- WHoohoo! - */ - @Test - public void testBasicAddIntegers() throws IOException { - - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet s = wb1.createSheet(); - HSSFRow r = null; - HSSFCell c = null; - - //get our minimum values - r = s.createRow(1); - c = r.createCell(1); - c.setCellFormula(1 + "+" + 1); - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - s = wb2.getSheetAt(0); - r = s.getRow(1); - c = r.getCell(1); - - assertTrue("Formula is as expected",("1+1".equals(c.getCellFormula()))); - wb2.close(); - } - - /** - * Add various integers - */ - @Test - public void testAddIntegers() throws IOException { - binomialOperator("+"); - } - - /** - * Multiply various integers - */ - @Test - public void testMultplyIntegers() throws IOException { - binomialOperator("*"); - } - - /** - * Subtract various integers - */ - @Test - public void testSubtractIntegers() throws IOException { - binomialOperator("-"); - } - - /** - * Subtract various integers - */ - @Test - public void testDivideIntegers() throws IOException { - binomialOperator("/"); - } - - /** - * Exponentialize various integers; - */ - @Test - public void testPowerIntegers() throws IOException { - binomialOperator("^"); - } - - /** - * Concatenate two numbers 1&2 = 12 - */ - @Test - public void testConcatIntegers() throws IOException { - binomialOperator("&"); - } - - /** - * tests 1*2+3*4 - */ - @Test - public void testOrderOfOperationsMultiply() throws IOException { - orderTest("1*2+3*4"); - } - - /** - * tests 1*2+3^4 - */ - @Test - public void testOrderOfOperationsPower() throws IOException { - orderTest("1*2+3^4"); - } - - /** - * Tests that parenthesis are obeyed - */ - @Test - public void testParenthesis() throws IOException { - orderTest("(1*3)+2+(1+2)*(3^4)^5"); - } - - @Test - public void testReferencesOpr() throws IOException { - String[] operation = new String[] { - "+", "-", "*", "/", "^", "&" - }; - for (final String op : operation) { - operationRefTest(op); - } - } - - /** - * Tests creating a file with floating point in a formula. - * - */ - @Test - public void testFloat() throws IOException { - floatTest("*"); - floatTest("/"); - } - - private static void floatTest(String operator) throws IOException { - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet s = wb1.createSheet(); - HSSFRow r = null; - HSSFCell c = null; - - //get our minimum values - - r = s.createRow(0); - c = r.createCell(1); - c.setCellFormula(""+Float.MIN_VALUE + operator + Float.MIN_VALUE); - - for (int x = 1; x < Short.MAX_VALUE && x > 0; x=(short)(x*2) ) { - r = s.createRow(x); - - for (int y = 1; y < 256 && y > 0; y= (short) (y +2)) { - - c = r.createCell(y); - c.setCellFormula("" + x+"."+y + operator + y +"."+x); - - - } - } - if (s.getLastRowNum() < Short.MAX_VALUE) { - r = s.createRow(0); - c = r.createCell(0); - c.setCellFormula("" + Float.MAX_VALUE + operator + Float.MAX_VALUE); - } - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - - floatVerify(operator, wb2); - wb2.close(); - } - - private static void floatVerify(String operator, HSSFWorkbook wb) { - - HSSFSheet s = wb.getSheetAt(0); - - // don't know how to check correct result .. for the moment, we just verify that the file can be read. - - for (int x = 1; x < Short.MAX_VALUE && x > 0; x=(short)(x*2)) { - HSSFRow r = s.getRow(x); - - for (int y = 1; y < 256 && y > 0; y=(short)(y+2)) { - - HSSFCell c = r.getCell(y); - assertTrue("got a formula",c.getCellFormula()!=null); - - assertTrue("loop Formula is as expected "+x+"."+y+operator+y+"."+x+"!="+c.getCellFormula(),( - (""+x+"."+y+operator+y+"."+x).equals(c.getCellFormula()) )); - } - } - } - - @Test - public void testAreaSum() throws IOException { - areaFunctionTest("SUM"); - } - - @Test - public void testAreaAverage() throws IOException { - areaFunctionTest("AVERAGE"); - } - - @Test - public void testRefArraySum() throws IOException { - refArrayFunctionTest("SUM"); - } - - @Test - public void testAreaArraySum() throws IOException { - refAreaArrayFunctionTest("SUM"); - } - - private static void operationRefTest(String operator) throws IOException { - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet s = wb1.createSheet(); - HSSFRow r = null; - HSSFCell c = null; - - //get our minimum values - r = s.createRow(0); - c = r.createCell(1); - c.setCellFormula("A2" + operator + "A3"); - - for (int x = 1; x < Short.MAX_VALUE && x > 0; x=(short)(x*2)) { - r = s.createRow(x); - - for (int y = 1; y < 256 && y > 0; y++) { - - String ref=null; - String ref2=null; - short refx1=0; - short refy1=0; - short refx2=0; - short refy2=0; - if (x +50 < Short.MAX_VALUE) { - refx1=(short)(x+50); - refx2=(short)(x+46); - } else { - refx1=(short)(x-4); - refx2=(short)(x-3); - } - - if (y+50 < 255) { - refy1=(short)(y+50); - refy2=(short)(y+49); - } else { - refy1=(short)(y-4); - refy2=(short)(y-3); - } - - c = r.getCell(y); - CellReference cr= new CellReference(refx1,refy1, false, false); - ref=cr.formatAsString(); - cr=new CellReference(refx2,refy2, false, false); - ref2=cr.formatAsString(); - - c = r.createCell(y); - c.setCellFormula("" + ref + operator + ref2); - - - - } - } - - //make sure we do the maximum value of the Int operator - if (s.getLastRowNum() < Short.MAX_VALUE) { - r = s.getRow(0); - c = r.createCell(0); - c.setCellFormula("" + "B1" + operator + "IV255"); - } - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - operationalRefVerify(operator, wb2); - wb2.close(); - } - - /** - * Opens the sheet we wrote out by binomialOperator and makes sure the formulas - * all match what we expect (x operator y) - */ - private static void operationalRefVerify(String operator, HSSFWorkbook wb) { - - HSSFSheet s = wb.getSheetAt(0); - HSSFRow r = null; - HSSFCell c = null; - - //get our minimum values - r = s.getRow(0); - c = r.getCell(1); - //get our minimum values - assertTrue("minval Formula is as expected A2"+operator+"A3 != "+c.getCellFormula(), - ( ("A2"+operator+"A3").equals(c.getCellFormula()) - )); - - - for (int x = 1; x < Short.MAX_VALUE && x > 0; x=(short)(x*2)) { - r = s.getRow(x); - - for (int y = 1; y < 256 && y > 0; y++) { - - int refx1; - int refy1; - int refx2; - int refy2; - if (x +50 < Short.MAX_VALUE) { - refx1=x+50; - refx2=x+46; - } else { - refx1=x-4; - refx2=x-3; - } - - if (y+50 < 255) { - refy1=y+50; - refy2=y+49; - } else { - refy1=y-4; - refy2=y-3; - } - - c = r.getCell(y); - CellReference cr= new CellReference(refx1, refy1, false, false); - String ref=cr.formatAsString(); - ref=cr.formatAsString(); - cr=new CellReference(refx2,refy2, false, false); - String ref2=cr.formatAsString(); - - - assertTrue("loop Formula is as expected "+ref+operator+ref2+"!="+c.getCellFormula(),( - (""+ref+operator+ref2).equals(c.getCellFormula()) - ) - ); - } - } - - //test our maximum values - r = s.getRow(0); - c = r.getCell(0); - - assertEquals("B1"+operator+"IV255", c.getCellFormula()); - } - - - - /** - * tests order wrting out == order writing in for a given formula - */ - private static void orderTest(String formula) throws IOException { - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet s = wb1.createSheet(); - HSSFRow r = null; - HSSFCell c = null; - - //get our minimum values - r = s.createRow(0); - c = r.createCell(1); - c.setCellFormula(formula); - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - s = wb2.getSheetAt(0); - - //get our minimum values - r = s.getRow(0); - c = r.getCell(1); - assertTrue("minval Formula is as expected", formula.equals(c.getCellFormula())); - wb2.close(); - } - - /** - * All multi-binomial operator tests use this to create a worksheet with a - * huge set of x operator y formulas. Next we call binomialVerify and verify - * that they are all how we expect. - */ - private static void binomialOperator(String operator) throws IOException { - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet s = wb1.createSheet(); - HSSFRow r = null; - HSSFCell c = null; - - //get our minimum values - r = s.createRow(0); - c = r.createCell(1); - c.setCellFormula(1 + operator + 1); - - for (int x = 1; x < Short.MAX_VALUE && x > 0; x=(short)(x*2)) { - r = s.createRow(x); - - for (int y = 1; y < 256 && y > 0; y++) { - - c = r.createCell(y); - c.setCellFormula("" + x + operator + y); - - } - } - - //make sure we do the maximum value of the Int operator - if (s.getLastRowNum() < Short.MAX_VALUE) { - r = s.getRow(0); - c = r.createCell(0); - c.setCellFormula("" + Short.MAX_VALUE + operator + Short.MAX_VALUE); - } - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - binomialVerify(operator, wb2); - wb2.close(); - } - - /** - * Opens the sheet we wrote out by binomialOperator and makes sure the formulas - * all match what we expect (x operator y) - */ - private static void binomialVerify(String operator, HSSFWorkbook wb) { - HSSFSheet s = wb.getSheetAt(0); - HSSFRow r = null; - HSSFCell c = null; - - //get our minimum values - r = s.getRow(0); - c = r.getCell(1); - assertTrue("minval Formula is as expected 1"+operator+"1 != "+c.getCellFormula(), - ( ("1"+operator+"1").equals(c.getCellFormula()) - )); - - for (int x = 1; x < Short.MAX_VALUE && x > 0; x=(short)(x*2)) { - r = s.getRow(x); - - for (int y = 1; y < 256 && y > 0; y++) { - - c = r.getCell(y); - - assertTrue("loop Formula is as expected "+x+operator+y+"!="+c.getCellFormula(),( - (""+x+operator+y).equals(c.getCellFormula()) - ) - ); - } - } - - //test our maximum values - r = s.getRow(0); - c = r.getCell(0); - - assertTrue("maxval Formula is as expected",( - (""+Short.MAX_VALUE+operator+Short.MAX_VALUE).equals(c.getCellFormula()) - ) - ); - } - - /** - * Writes a function then tests to see if its correct - */ - public static void areaFunctionTest(String function) throws IOException { - - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet s = wb1.createSheet(); - HSSFRow r = null; - HSSFCell c = null; - - - r = s.createRow(0); - - c = r.createCell(0); - c.setCellFormula(function+"(A2:A3)"); - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - s = wb2.getSheetAt(0); - r = s.getRow(0); - c = r.getCell(0); - - assertTrue("function ="+function+"(A2:A3)", - ( (function+"(A2:A3)").equals((function+"(A2:A3)")) ) - ); - wb2.close(); - } - - /** - * Writes a function then tests to see if its correct - */ - public void refArrayFunctionTest(String function) throws IOException { - - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet s = wb1.createSheet(); - HSSFRow r = null; - HSSFCell c = null; - - - r = s.createRow(0); - - c = r.createCell(0); - c.setCellFormula(function+"(A2,A3)"); - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - s = wb2.getSheetAt(0); - r = s.getRow(0); - c = r.getCell(0); - - assertTrue("function ="+function+"(A2,A3)", - ( (function+"(A2,A3)").equals(c.getCellFormula()) ) - ); - wb2.close(); - } - - - /** - * Writes a function then tests to see if its correct - * - */ - public void refAreaArrayFunctionTest(String function) throws IOException { - - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet s = wb1.createSheet(); - HSSFRow r = null; - HSSFCell c = null; - - - r = s.createRow(0); - - c = r.createCell(0); - c.setCellFormula(function+"(A2:A4,B2:B4)"); - c=r.createCell(1); - c.setCellFormula(function+"($A$2:$A4,B$2:B4)"); - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - s = wb2.getSheetAt(0); - r = s.getRow(0); - c = r.getCell(0); - - assertTrue("function ="+function+"(A2:A4,B2:B4)", - ( (function+"(A2:A4,B2:B4)").equals(c.getCellFormula()) ) - ); - - c=r.getCell(1); - assertTrue("function ="+function+"($A$2:$A4,B$2:B4)", - ( (function+"($A$2:$A4,B$2:B4)").equals(c.getCellFormula()) ) - ); - wb2.close(); - } - - - @Test - public void testAbsRefs() throws IOException { - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet s = wb1.createSheet(); - HSSFRow r; - HSSFCell c; - - r = s.createRow(0); - c = r.createCell(0); - c.setCellFormula("A3+A2"); - c=r.createCell(1); - c.setCellFormula("$A3+$A2"); - c=r.createCell(2); - c.setCellFormula("A$3+A$2"); - c=r.createCell(3); - c.setCellFormula("$A$3+$A$2"); - c=r.createCell(4); - c.setCellFormula("SUM($A$3,$A$2)"); - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - s = wb2.getSheetAt(0); - r = s.getRow(0); - c = r.getCell(0); - assertTrue("A3+A2", ("A3+A2").equals(c.getCellFormula())); - c = r.getCell(1); - assertTrue("$A3+$A2", ("$A3+$A2").equals(c.getCellFormula())); - c = r.getCell(2); - assertTrue("A$3+A$2", ("A$3+A$2").equals(c.getCellFormula())); - c = r.getCell(3); - assertTrue("$A$3+$A$2", ("$A$3+$A$2").equals(c.getCellFormula())); - c = r.getCell(4); - assertTrue("SUM($A$3,$A$2)", ("SUM($A$3,$A$2)").equals(c.getCellFormula())); - wb2.close(); - } - - @Test - public void testSheetFunctions() throws IOException { - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet s = wb1.createSheet("A"); - HSSFRow r = null; - HSSFCell c = null; - r = s.createRow(0); - c = r.createCell(0);c.setCellValue(1); - c = r.createCell(1);c.setCellValue(2); - - s = wb1.createSheet("B"); - r = s.createRow(0); - c=r.createCell(0); c.setCellFormula("AVERAGE(A!A1:B1)"); - c=r.createCell(1); c.setCellFormula("A!A1+A!B1"); - c=r.createCell(2); c.setCellFormula("A!$A$1+A!$B1"); - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - - s = wb2.getSheet("B"); - r = s.getRow(0); - c = r.getCell(0); - assertTrue("expected: AVERAGE(A!A1:B1) got: "+c.getCellFormula(), ("AVERAGE(A!A1:B1)").equals(c.getCellFormula())); - c = r.getCell(1); - assertTrue("expected: A!A1+A!B1 got: "+c.getCellFormula(), ("A!A1+A!B1").equals(c.getCellFormula())); - wb2.close(); - } - - @Test - public void testRVAoperands() throws IOException { - File file = TempFile.createTempFile("testFormulaRVA",".xls"); - FileOutputStream out = new FileOutputStream(file); - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet s = wb.createSheet(); - HSSFRow r = null; - HSSFCell c = null; - - - r = s.createRow(0); - - c = r.createCell(0); - c.setCellFormula("A3+A2"); - c=r.createCell(1); - c.setCellFormula("AVERAGE(A3,A2)"); - c=r.createCell(2); - c.setCellFormula("ROW(A3)"); - c=r.createCell(3); - c.setCellFormula("AVERAGE(A2:A3)"); - c=r.createCell(4); - c.setCellFormula("POWER(A2,A3)"); - c=r.createCell(5); - c.setCellFormula("SIN(A2)"); - - c=r.createCell(6); - c.setCellFormula("SUM(A2:A3)"); - - c=r.createCell(7); - c.setCellFormula("SUM(A2,A3)"); - - r = s.createRow(1);c=r.createCell(0); c.setCellValue(2.0); - r = s.createRow(2);c=r.createCell(0); c.setCellValue(3.0); - - wb.write(out); - out.close(); - assertTrue("file exists",file.exists()); - wb.close(); - } - - @Test - public void testStringFormulas() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet s = wb.createSheet("A"); - HSSFRow r = null; - HSSFCell c = null; - r = s.createRow(0); - c=r.createCell(1); c.setCellFormula("UPPER(\"abc\")"); - c=r.createCell(2); c.setCellFormula("LOWER(\"ABC\")"); - c=r.createCell(3); c.setCellFormula("CONCATENATE(\" my \",\" name \")"); - - HSSFTestDataSamples.writeOutAndReadBack(wb).close(); - wb.close(); - - wb = openSample("StringFormulas.xls"); - s = wb.getSheetAt(0); - r = s.getRow(0); - c = r.getCell(0); - assertEquals("UPPER(\"xyz\")", c.getCellFormula()); - wb.close(); - } - - @Test - public void testLogicalFormulas() throws IOException { - - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet s = wb1.createSheet("A"); - HSSFRow r = null; - HSSFCell c = null; - r = s.createRow(0); - c=r.createCell(1); c.setCellFormula("IF(A14000\",B1:B5)"; - - HSSFWorkbook wb = openSample("sumifformula.xls"); - - HSSFSheet s = wb.getSheetAt(0); - HSSFRow r = s.getRow(0); - HSSFCell c = r.getCell(2); - assertEquals(function, c.getCellFormula()); - - - wb = new HSSFWorkbook(); - s = wb.createSheet(); - - r = s.createRow(0); - c=r.createCell(0); c.setCellValue(1000); - c=r.createCell(1); c.setCellValue(1); - - - r = s.createRow(1); - c=r.createCell(0); c.setCellValue(2000); - c=r.createCell(1); c.setCellValue(2); - - r = s.createRow(2); - c=r.createCell(0); c.setCellValue(3000); - c=r.createCell(1); c.setCellValue(3); - - r = s.createRow(3); - c=r.createCell(0); c.setCellValue(4000); - c=r.createCell(1); c.setCellValue(4); - - r = s.createRow(4); - c=r.createCell(0); c.setCellValue(5000); - c=r.createCell(1); c.setCellValue(5); - - r = s.getRow(0); - c=r.createCell(2); c.setCellFormula(function); - - HSSFTestDataSamples.writeOutAndReadBack(wb).close(); - wb.close(); - } - - @Test - public void testSquareMacro() throws IOException { - HSSFWorkbook w = openSample("SquareMacro.xls"); - - HSSFSheet s0 = w.getSheetAt(0); - HSSFRow[] r = {s0.getRow(0), s0.getRow(1)}; - - HSSFCell a1 = r[0].getCell(0); - assertEquals("square(1)", a1.getCellFormula()); - assertEquals(1d, a1.getNumericCellValue(), 1e-9); - - HSSFCell a2 = r[1].getCell(0); - assertEquals("square(2)", a2.getCellFormula()); - assertEquals(4d, a2.getNumericCellValue(), 1e-9); - - HSSFCell b1 = r[0].getCell(1); - assertEquals("IF(TRUE,square(1))", b1.getCellFormula()); - assertEquals(1d, b1.getNumericCellValue(), 1e-9); - - HSSFCell b2 = r[1].getCell(1); - assertEquals("IF(TRUE,square(2))", b2.getCellFormula()); - assertEquals(4d, b2.getNumericCellValue(), 1e-9); - - HSSFCell c1 = r[0].getCell(2); - assertEquals("square(square(1))", c1.getCellFormula()); - assertEquals(1d, c1.getNumericCellValue(), 1e-9); - - HSSFCell c2 = r[1].getCell(2); - assertEquals("square(square(2))", c2.getCellFormula()); - assertEquals(16d, c2.getNumericCellValue(), 1e-9); - - HSSFCell d1 = r[0].getCell(3); - assertEquals("square(one())", d1.getCellFormula()); - assertEquals(1d, d1.getNumericCellValue(), 1e-9); - - HSSFCell d2 = r[1].getCell(3); - assertEquals("square(two())", d2.getCellFormula()); - assertEquals(4d, d2.getNumericCellValue(), 1e-9); - - w.close(); - } - - @Test - public void testStringFormulaRead() throws IOException { - HSSFWorkbook w = openSample("StringFormulas.xls"); - HSSFCell c = w.getSheetAt(0).getRow(0).getCell(0); - assertEquals("String Cell value","XYZ",c.getRichStringCellValue().getString()); - w.close(); - } - - /** test for bug 34021*/ - @Test - public void testComplexSheetRefs () throws IOException { - HSSFWorkbook sb = new HSSFWorkbook(); - try { - HSSFSheet s1 = sb.createSheet("Sheet a.1"); - HSSFSheet s2 = sb.createSheet("Sheet.A"); - s2.createRow(1).createCell(2).setCellFormula("'Sheet a.1'!A1"); - s1.createRow(1).createCell(2).setCellFormula("'Sheet.A'!A1"); - File file = TempFile.createTempFile("testComplexSheetRefs",".xls"); - FileOutputStream stream = new FileOutputStream(file); - try { - sb.write(stream); - } finally { - stream.close(); - } - } finally { - sb.close(); - } - } - - /** Unknown Ptg 3C*/ - @Test - public void test27272_1() throws IOException { - HSSFWorkbook wb = openSample("27272_1.xls"); - wb.getSheetAt(0); - assertEquals("Reference for named range ", "Compliance!#REF!",wb.getNameAt(0).getRefersToFormula()); - File outF = TempFile.createTempFile("bug27272_1",".xls"); - FileOutputStream stream = new FileOutputStream(outF); - try { - wb.write(stream); - } finally { - stream.close(); - } - wb.close(); - } - /** Unknown Ptg 3D*/ - @Test - public void test27272_2() throws IOException { - HSSFWorkbook wb = openSample("27272_2.xls"); - assertEquals("Reference for named range ", "LOAD.POD_HISTORIES!#REF!",wb.getNameAt(0).getRefersToFormula()); - File outF = TempFile.createTempFile("bug27272_2",".xls"); - FileOutputStream stream = new FileOutputStream(outF); - try { - wb.write(stream); - } finally { - stream.close(); - } - wb.close(); - } - - /** MissingArgPtg */ - @Test - public void testMissingArgPtg() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - try { - HSSFCell cell = wb.createSheet("Sheet1").createRow(4).createCell(0); - cell.setCellFormula("IF(A1=\"A\",1,)"); - } finally { - wb.close(); - } - } - - @Test - public void testSharedFormula() throws IOException { - HSSFWorkbook wb = openSample("SharedFormulaTest.xls"); - - assertEquals("A$1*2", wb.getSheetAt(0).getRow(1).getCell(1).toString()); - assertEquals("$A11*2", wb.getSheetAt(0).getRow(11).getCell(1).toString()); - assertEquals("DZ2*2", wb.getSheetAt(0).getRow(1).getCell(128).toString()); - assertEquals("B32770*2", wb.getSheetAt(0).getRow(32768).getCell(1).toString()); - wb.close(); - } - - /** - * Test creation / evaluation of formulas with sheet-level names - */ - @Test - public void testSheetLevelFormulas() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - - HSSFRow row; - HSSFSheet sh1 = wb.createSheet("Sheet1"); - HSSFName nm1 = wb.createName(); - nm1.setNameName("sales_1"); - nm1.setSheetIndex(0); - nm1.setRefersToFormula("Sheet1!$A$1"); - row = sh1.createRow(0); - row.createCell(0).setCellValue(3); - row.createCell(1).setCellFormula("sales_1"); - row.createCell(2).setCellFormula("sales_1*2"); - - - HSSFSheet sh2 = wb.createSheet("Sheet2"); - HSSFName nm2 = wb.createName(); - nm2.setNameName("sales_1"); - nm2.setSheetIndex(1); - nm2.setRefersToFormula("Sheet2!$A$1"); - - row = sh2.createRow(0); - row.createCell(0).setCellValue(5); - row.createCell(1).setCellFormula("sales_1"); - row.createCell(2).setCellFormula("sales_1*3"); - - //check that NamePtg refers to the correct NameRecord - Ptg[] ptgs1 = HSSFFormulaParser.parse("sales_1", wb, FormulaType.CELL, 0); - NamePtg nPtg1 = (NamePtg)ptgs1[0]; - assertSame(nm1, wb.getNameAt(nPtg1.getIndex())); - - Ptg[] ptgs2 = HSSFFormulaParser.parse("sales_1", wb, FormulaType.CELL, 1); - NamePtg nPtg2 = (NamePtg)ptgs2[0]; - assertSame(nm2, wb.getNameAt(nPtg2.getIndex())); - - //check that the formula evaluator returns the correct result - HSSFFormulaEvaluator evaluator = new HSSFFormulaEvaluator(wb); - assertEquals(3.0, evaluator.evaluate(sh1.getRow(0).getCell(1)).getNumberValue(), 0.0); - assertEquals(6.0, evaluator.evaluate(sh1.getRow(0).getCell(2)).getNumberValue(), 0.0); - - assertEquals(5.0, evaluator.evaluate(sh2.getRow(0).getCell(1)).getNumberValue(), 0.0); - assertEquals(15.0, evaluator.evaluate(sh2.getRow(0).getCell(2)).getNumberValue(), 0.0); - wb.close(); - } - - /** - * Verify that FormulaParser handles defined names beginning with underscores, - * see Bug #49640 - */ - @Test - public void testFormulasWithUnderscore() throws IOException{ - HSSFWorkbook wb = new HSSFWorkbook(); - try { - Name nm1 = wb.createName(); - nm1.setNameName("_score1"); - nm1.setRefersToFormula("A1"); - - Name nm2 = wb.createName(); - nm2.setNameName("_score2"); - nm2.setRefersToFormula("A2"); - - Sheet sheet = wb.createSheet(); - Cell cell = sheet.createRow(0).createCell(2); - cell.setCellFormula("_score1*SUM(_score1+_score2)"); - assertEquals("_score1*SUM(_score1+_score2)", cell.getCellFormula()); - } finally { - wb.close(); - } - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFCell.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFCell.java deleted file mode 100644 index fd3b1a66d..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFCell.java +++ /dev/null @@ -1,473 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; - -import java.io.IOException; -import java.util.Calendar; -import java.util.Date; - -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.model.InternalSheet; -import org.apache.poi.hssf.record.DBCellRecord; -import org.apache.poi.hssf.record.FormulaRecord; -import org.apache.poi.hssf.record.Record; -import org.apache.poi.hssf.record.StringRecord; -import org.apache.poi.ss.usermodel.BaseTestCell; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.FormulaError; -import org.apache.poi.ss.usermodel.RichTextString; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.util.LocaleUtil; -import org.junit.Test; - -import junit.framework.AssertionFailedError; - -/** - * Tests various functionality having to do with {@link HSSFCell}. For instance support for - * particular datatypes, etc. - */ -public final class TestHSSFCell extends BaseTestCell { - - public TestHSSFCell() { - super(HSSFITestDataProvider.instance); - } - - /** - * Checks that the recognition of files using 1904 date windowing - * is working properly. Conversion of the date is also an issue, - * but there's a separate unit test for that. - */ - @Test - public void testDateWindowingRead() throws IOException { - Calendar cal = LocaleUtil.getLocaleCalendar(2000, 0, 1, 0, 0, 0);// Jan. 1, 2000 - Date date = cal.getTime(); - - // first check a file with 1900 Date Windowing - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("1900DateWindowing.xls"); - HSSFSheet sheet = wb.getSheetAt(0); - - assertEquals("Date from file using 1900 Date Windowing", - date.getTime(), - sheet.getRow(0).getCell(0).getDateCellValue().getTime()); - wb.close(); - - // now check a file with 1904 Date Windowing - wb = HSSFTestDataSamples.openSampleWorkbook("1904DateWindowing.xls"); - sheet = wb.getSheetAt(0); - - assertEquals("Date from file using 1904 Date Windowing", - date.getTime(), - sheet.getRow(0).getCell(0).getDateCellValue().getTime()); - wb.close(); - } - - - - /** - * Checks that dates are properly written to both types of files: - * those with 1900 and 1904 date windowing. Note that if the - * previous test ({@link #testDateWindowingRead}) fails, the - * results of this test are meaningless. - */ - @Test - public void testDateWindowingWrite() throws IOException { - Calendar cal = LocaleUtil.getLocaleCalendar(2000,0,1,0,0,0); // Jan. 1, 2000 - Date date = cal.getTime(); - - // first check a file with 1900 Date Windowing - HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("1900DateWindowing.xls"); - - setCell(wb1, 0, 1, date); - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - - assertEquals("Date from file using 1900 Date Windowing", - date.getTime(), - readCell(wb2, 0, 1).getTime()); - wb1.close(); - wb2.close(); - - // now check a file with 1904 Date Windowing - wb1 = HSSFTestDataSamples.openSampleWorkbook("1904DateWindowing.xls"); - setCell(wb1, 0, 1, date); - wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - assertEquals("Date from file using 1900 Date Windowing", - date.getTime(), - readCell(wb2, 0, 1).getTime()); - wb1.close(); - wb2.close(); - } - - private static void setCell(HSSFWorkbook workbook, int rowIdx, int colIdx, Date date) { - HSSFSheet sheet = workbook.getSheetAt(0); - HSSFRow row = sheet.getRow(rowIdx); - HSSFCell cell = row.getCell(colIdx); - - if (cell == null) { - cell = row.createCell(colIdx); - } - cell.setCellValue(date); - } - - private static Date readCell(HSSFWorkbook workbook, int rowIdx, int colIdx) { - HSSFSheet sheet = workbook.getSheetAt(0); - HSSFRow row = sheet.getRow(rowIdx); - HSSFCell cell = row.getCell(colIdx); - return cell.getDateCellValue(); - } - - /** - * Tests that the active cell can be correctly read and set - */ - @Test - public void testActiveCell() throws IOException { - //read in sample - HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("Simple.xls"); - - //check initial position - HSSFSheet umSheet = wb1.getSheetAt(0); - InternalSheet s = umSheet.getSheet(); - assertEquals("Initial active cell should be in col 0", - (short) 0, s.getActiveCellCol()); - assertEquals("Initial active cell should be on row 1", - 1, s.getActiveCellRow()); - - //modify position through HSSFCell - HSSFCell cell = umSheet.createRow(3).createCell(2); - cell.setAsActiveCell(); - assertEquals("After modify, active cell should be in col 2", - (short) 2, s.getActiveCellCol()); - assertEquals("After modify, active cell should be on row 3", - 3, s.getActiveCellRow()); - - //write book to temp file; read and verify that position is serialized - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - - umSheet = wb2.getSheetAt(0); - s = umSheet.getSheet(); - - assertEquals("After serialize, active cell should be in col 2", - (short) 2, s.getActiveCellCol()); - assertEquals("After serialize, active cell should be on row 3", - 3, s.getActiveCellRow()); - - wb2.close(); - } - - - @Test - public void testActiveCellBug56114() throws IOException { - Workbook wb = new HSSFWorkbook(); - Sheet sh = wb.createSheet(); - - sh.createRow(0); - sh.createRow(1); - sh.createRow(2); - sh.createRow(3); - - Cell cell = sh.getRow(1).createCell(3); - sh.getRow(3).createCell(3); - - assertEquals(0, ((HSSFSheet)wb.getSheetAt(0)).getSheet().getActiveCellRow()); - assertEquals(0, ((HSSFSheet)wb.getSheetAt(0)).getSheet().getActiveCellCol()); - - cell.setAsActiveCell(); - - assertEquals(1, ((HSSFSheet)wb.getSheetAt(0)).getSheet().getActiveCellRow()); - assertEquals(3, ((HSSFSheet)wb.getSheetAt(0)).getSheet().getActiveCellCol()); - -// FileOutputStream fos = new FileOutputStream("/tmp/56114.xls"); -// -// wb.write(fos); -// -// fos.close(); - - Workbook wbBack = _testDataProvider.writeOutAndReadBack(wb); - wb.close(); - - assertEquals(1, ((HSSFSheet)wbBack.getSheetAt(0)).getSheet().getActiveCellRow()); - assertEquals(3, ((HSSFSheet)wbBack.getSheetAt(0)).getSheet().getActiveCellCol()); - - wbBack.getSheetAt(0).getRow(3).getCell(3).setAsActiveCell(); - - assertEquals(3, ((HSSFSheet)wbBack.getSheetAt(0)).getSheet().getActiveCellRow()); - assertEquals(3, ((HSSFSheet)wbBack.getSheetAt(0)).getSheet().getActiveCellCol()); - -// fos = new FileOutputStream("/tmp/56114a.xls"); -// -// wbBack.write(fos); -// -// fos.close(); - - Workbook wbBack2 = _testDataProvider.writeOutAndReadBack(wbBack); - wbBack.close(); - - assertEquals(3, ((HSSFSheet)wbBack2.getSheetAt(0)).getSheet().getActiveCellRow()); - assertEquals(3, ((HSSFSheet)wbBack2.getSheetAt(0)).getSheet().getActiveCellCol()); - wbBack2.close(); - } - - /** - * Test reading hyperlinks - */ - @Test - public void testWithHyperlink() throws IOException { - - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("WithHyperlink.xls"); - - HSSFSheet sheet = wb.getSheetAt(0); - HSSFCell cell = sheet.getRow(4).getCell(0); - HSSFHyperlink link = cell.getHyperlink(); - assertNotNull(link); - - assertEquals("Foo", link.getLabel()); - assertEquals("http://poi.apache.org/", link.getAddress()); - assertEquals(4, link.getFirstRow()); - assertEquals(0, link.getFirstColumn()); - - wb.close(); - } - - /** - * Test reading hyperlinks - */ - @Test - public void testWithTwoHyperlinks() throws IOException { - - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("WithTwoHyperLinks.xls"); - - HSSFSheet sheet = wb.getSheetAt(0); - - HSSFCell cell1 = sheet.getRow(4).getCell(0); - HSSFHyperlink link1 = cell1.getHyperlink(); - assertNotNull(link1); - assertEquals("Foo", link1.getLabel()); - assertEquals("http://poi.apache.org/", link1.getAddress()); - assertEquals(4, link1.getFirstRow()); - assertEquals(0, link1.getFirstColumn()); - - HSSFCell cell2 = sheet.getRow(8).getCell(1); - HSSFHyperlink link2 = cell2.getHyperlink(); - assertNotNull(link2); - assertEquals("Bar", link2.getLabel()); - assertEquals("http://poi.apache.org/hssf/", link2.getAddress()); - assertEquals(8, link2.getFirstRow()); - assertEquals(1, link2.getFirstColumn()); - - wb.close(); - } - - /** - * Test to ensure we can only assign cell styles that belong - * to our workbook, and not those from other workbooks. - */ - @Test - public void testCellStyleWorkbookMatch() throws IOException { - HSSFWorkbook wbA = new HSSFWorkbook(); - HSSFWorkbook wbB = new HSSFWorkbook(); - - HSSFCellStyle styA = wbA.createCellStyle(); - HSSFCellStyle styB = wbB.createCellStyle(); - - styA.verifyBelongsToWorkbook(wbA); - styB.verifyBelongsToWorkbook(wbB); - try { - styA.verifyBelongsToWorkbook(wbB); - fail(); - } catch (IllegalArgumentException e) { - // expected during successful test - } - try { - styB.verifyBelongsToWorkbook(wbA); - fail(); - } catch (IllegalArgumentException e) { - // expected during successful test - } - - Cell cellA = wbA.createSheet().createRow(0).createCell(0); - Cell cellB = wbB.createSheet().createRow(0).createCell(0); - - cellA.setCellStyle(styA); - cellB.setCellStyle(styB); - try { - cellA.setCellStyle(styB); - fail(); - } catch (IllegalArgumentException e) { - // expected during successful test - } - try { - cellB.setCellStyle(styA); - fail(); - } catch (IllegalArgumentException e) { - // expected during successful test - } - - wbB.close(); - wbA.close(); - } - - /** - * Test for small bug observable around r736460 (prior to version 3.5). POI fails to remove - * the {@link StringRecord} following the {@link FormulaRecord} after the result type had been - * changed to number/boolean/error. Excel silently ignores the extra record, but some POI - * versions (prior to bug 46213 / r717883) crash instead. - * @throws IOException - */ - @Test - public void testCachedTypeChange() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("Sheet1"); - Cell cell = sheet.createRow(0).createCell(0); - cell.setCellFormula("A1"); - cell.setCellValue("abc"); - confirmStringRecord(sheet, true); - cell.setCellValue(123); - Record[] recs = RecordInspector.getRecords(sheet, 0); - if (recs.length == 28 && recs[23] instanceof StringRecord) { - wb.close(); - throw new AssertionFailedError("Identified bug - leftover StringRecord"); - } - confirmStringRecord(sheet, false); - - // string to error code - cell.setCellValue("abc"); - confirmStringRecord(sheet, true); - cell.setCellErrorValue(FormulaError.REF.getCode()); - confirmStringRecord(sheet, false); - - // string to boolean - cell.setCellValue("abc"); - confirmStringRecord(sheet, true); - cell.setCellValue(false); - confirmStringRecord(sheet, false); - wb.close(); - } - - private static void confirmStringRecord(HSSFSheet sheet, boolean isPresent) { - Record[] recs = RecordInspector.getRecords(sheet, 0); - assertEquals(isPresent ? 28 : 27, recs.length); - int index = 22; - Record fr = recs[index++]; - assertEquals(FormulaRecord.class, fr.getClass()); - if (isPresent) { - assertEquals(StringRecord.class, recs[index++].getClass()); - } else { - assertFalse(StringRecord.class == recs[index].getClass()); - } - Record dbcr = recs[index]; - assertEquals(DBCellRecord.class, dbcr.getClass()); - } - - /** - * HSSF prior to version 3.7 had a bug: it could write a NaN but could not read such a file back. - */ - @Test - public void testReadNaN() throws IOException { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("49761.xls"); - assertNotNull(wb); - wb.close(); - } - - @Test - public void testHSSFCell() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet(); - HSSFRow row = sheet.createRow(0); - row.createCell(0); - HSSFCell cell = new HSSFCell(wb, sheet, 0, (short)0); - assertNotNull(cell); - wb.close(); - } - - @Test - public void testDeprecatedMethods() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet(); - HSSFRow row = sheet.createRow(0); - HSSFCell cell = row.createCell(0); - - // cover some deprecated methods and other smaller stuff... - assertEquals(wb.getWorkbook(), cell.getBoundWorkbook()); - - try { - cell.getCachedFormulaResultTypeEnum(); - fail("Should catch exception"); - } catch (IllegalStateException e) { - // expected here - } - - cell.removeCellComment(); - cell.removeCellComment(); - - wb.close(); - } - - @Test - public void testCellType() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - - cell.setCellType(CellType.BLANK); - assertNull(null, cell.getDateCellValue()); - assertFalse(cell.getBooleanCellValue()); - assertEquals("", cell.toString()); - - cell.setCellType(CellType.STRING); - assertEquals("", cell.toString()); - cell.setCellType(CellType.STRING); - cell.setCellValue(1.2); - cell.setCellType(CellType.NUMERIC); - assertEquals("1.2", cell.toString()); - cell.setCellType(CellType.BOOLEAN); - assertEquals("TRUE", cell.toString()); - cell.setCellType(CellType.BOOLEAN); - cell.setCellValue("" + FormulaError.VALUE.name()); - cell.setCellType(CellType.ERROR); - assertEquals("#VALUE!", cell.toString()); - cell.setCellType(CellType.ERROR); - cell.setCellType(CellType.BOOLEAN); - assertEquals("FALSE", cell.toString()); - cell.setCellValue(1.2); - cell.setCellType(CellType.NUMERIC); - assertEquals("1.2", cell.toString()); - cell.setCellType(CellType.BOOLEAN); - cell.setCellType(CellType.STRING); - cell.setCellType(CellType.ERROR); - cell.setCellType(CellType.STRING); - cell.setCellValue(1.2); - cell.setCellType(CellType.NUMERIC); - cell.setCellType(CellType.STRING); - assertEquals("1.2", cell.toString()); - - cell.setCellValue((String)null); - cell.setCellValue((RichTextString)null); - wb.close(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFClientAnchor.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFClientAnchor.java deleted file mode 100644 index 96c2d9220..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFClientAnchor.java +++ /dev/null @@ -1,161 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import junit.framework.TestCase; -import org.apache.poi.ddf.EscherClientAnchorRecord; -import org.apache.poi.hssf.model.ConvertAnchor; - -/** - * Various tests for HSSFClientAnchor. - * - * @author Glen Stampoultzis (glens at apache.org) - * @author Yegor Kozlov (yegor at apache.org) - */ -public final class TestHSSFClientAnchor extends TestCase { - public void testGetAnchorHeightInPoints() { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("test"); - HSSFClientAnchor a = new HSSFClientAnchor(0,0,1023,255,(short)0,0,(short)0,0); - float p = a.getAnchorHeightInPoints(sheet); - assertEquals(12.7,p,0.001); - - sheet.createRow(0).setHeightInPoints(14); - a = new HSSFClientAnchor(0,0,1023,255,(short)0,0,(short)0,0); - p = a.getAnchorHeightInPoints(sheet); - assertEquals(13.945,p,0.001); - - a = new HSSFClientAnchor(0,0,1023,127,(short)0,0,(short)0,0); - p = a.getAnchorHeightInPoints(sheet); - assertEquals(6.945,p,0.001); - - a = new HSSFClientAnchor(0,126,1023,127,(short)0,0,(short)0,0); - p = a.getAnchorHeightInPoints(sheet); - assertEquals(0.054,p,0.001); - - a = new HSSFClientAnchor(0,0,1023,0,(short)0,0,(short)0,1); - p = a.getAnchorHeightInPoints(sheet); - assertEquals(14.0,p,0.001); - - sheet.createRow(0).setHeightInPoints(12); - a = new HSSFClientAnchor(0,127,1023,127,(short)0,0,(short)0,1); - p = a.getAnchorHeightInPoints(sheet); - assertEquals(12.372,p,0.001); - - } - - /** - * When HSSFClientAnchor is converted into EscherClientAnchorRecord - * check that dx1, dx2, dy1 and dy2 are written "as is". - * (Bug 42999 reported that dx1 and dx2 are swapped if dx1>dx2. It doesn't make sense for client anchors.) - */ - public void testConvertAnchor() { - HSSFClientAnchor[] anchors = { - new HSSFClientAnchor( 0 , 0 , 0 , 0 ,(short)0, 1,(short)1,3), - new HSSFClientAnchor( 100 , 0 , 900 , 255 ,(short)0, 1,(short)1,3), - new HSSFClientAnchor( 900 , 0 , 100 , 255 ,(short)0, 1,(short)1,3) - }; - for (HSSFClientAnchor anchor : anchors) { - EscherClientAnchorRecord record = (EscherClientAnchorRecord)ConvertAnchor.createAnchor(anchor); - assertEquals(anchor.getDx1(), record.getDx1()); - assertEquals(anchor.getDx2(), record.getDx2()); - assertEquals(anchor.getDy1(), record.getDy1()); - assertEquals(anchor.getDy2(), record.getDy2()); - assertEquals(anchor.getCol1(), record.getCol1()); - assertEquals(anchor.getCol2(), record.getCol2()); - assertEquals(anchor.getRow1(), record.getRow1()); - assertEquals(anchor.getRow2(), record.getRow2()); - } - } - - public void testAnchorHeightInPoints(){ - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet(); - - HSSFClientAnchor[] anchor = { - new HSSFClientAnchor( 0 , 0, 0 , 0 ,(short)0, 1,(short)1, 3), - new HSSFClientAnchor( 0 , 254 , 0 , 126 ,(short)0, 1,(short)1, 3), - new HSSFClientAnchor( 0 , 128 , 0 , 128 ,(short)0, 1,(short)1, 3), - new HSSFClientAnchor( 0 , 0 , 0 , 128 ,(short)0, 1,(short)1, 3), - }; - float[] ref = {25.5f, 19.125f, 25.5f, 31.875f}; - for (int i = 0; i < anchor.length; i++) { - float height = anchor[i].getAnchorHeightInPoints(sheet); - assertEquals(ref[i], height, 0); - } - } - - /** - * Check {@link HSSFClientAnchor} constructor does not treat 32768 as -32768. - */ - public void testCanHaveRowGreaterThan32767() { - // Maximum permitted row number should be 65535. - HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0, (short) 0, 32768, (short) 0, 32768); - - assertEquals(32768, anchor.getRow1()); - assertEquals(32768, anchor.getRow2()); - } - - /** - * Check the maximum is not set at 255*256 instead of 256*256 - 1. - */ - public void testCanHaveRowUpTo65535() { - HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0, (short) 0, 65535, (short) 0, 65535); - - assertEquals(65535, anchor.getRow1()); - assertEquals(65535, anchor.getRow2()); - } - - public void testCannotHaveRowGreaterThan65535() { - try { - new HSSFClientAnchor(0, 0, 0, 0, (short) 0, 65536, (short) 0, 65536); - fail("Expected IllegalArgumentException to be thrown"); - } catch (IllegalArgumentException ex) { - // pass - } - } - - /** - * Check the same maximum value enforced when using {@link HSSFClientAnchor#setRow1}. - */ - public void testCanSetRowUpTo65535() { - HSSFClientAnchor anchor = new HSSFClientAnchor(); - anchor.setRow1(65535); - anchor.setRow2(65535); - - assertEquals(65535, anchor.getRow1()); - assertEquals(65535, anchor.getRow2()); - } - - public void testCannotSetRow1GreaterThan65535() { - try { - new HSSFClientAnchor().setRow1(65536); - fail("Expected IllegalArgumentException to be thrown"); - } catch (IllegalArgumentException ex) { - // pass - } - } - public void testCannotSetRow2GreaterThan65535() { - try { - new HSSFClientAnchor().setRow2(65536); - fail("Expected IllegalArgumentException to be thrown"); - } catch (IllegalArgumentException ex) { - // pass - } - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFComment.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFComment.java deleted file mode 100644 index f8162fcf2..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFComment.java +++ /dev/null @@ -1,453 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hssf.usermodel; - -import static org.apache.poi.poifs.storage.RawDataUtil.decompress; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - -import java.io.IOException; - -import org.apache.poi.ddf.EscherSpRecord; -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.record.CommonObjectDataSubRecord; -import org.apache.poi.hssf.record.EscherAggregate; -import org.apache.poi.hssf.record.NoteRecord; -import org.apache.poi.hssf.record.ObjRecord; -import org.apache.poi.hssf.record.TextObjectRecord; -import org.apache.poi.ss.usermodel.BaseTestCellComment; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.ClientAnchor; -import org.apache.poi.ss.usermodel.Comment; -import org.apache.poi.ss.usermodel.CreationHelper; -import org.apache.poi.ss.usermodel.Drawing; -import org.apache.poi.ss.usermodel.RichTextString; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.junit.Test; - -/** - * Tests TestHSSFCellComment. - * - * @author Yegor Kozlov - */ -public final class TestHSSFComment extends BaseTestCellComment { - - public TestHSSFComment() { - super(HSSFITestDataProvider.instance); - } - - @Test - public void defaultShapeType() { - HSSFComment comment = new HSSFComment((HSSFShape)null, new HSSFClientAnchor()); - assertEquals(HSSFSimpleShape.OBJECT_TYPE_COMMENT, comment.getShapeType()); - } - - /** - * HSSFCell#findCellComment should NOT rely on the order of records - * when matching cells and their cell comments. The correct algorithm is to map - */ - @Test - public void bug47924() throws IOException { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("47924.xls"); - HSSFSheet sheet = wb.getSheetAt(0); - HSSFCell cell; - HSSFComment comment; - - cell = sheet.getRow(0).getCell(0); - comment = cell.getCellComment(); - assertEquals("a1", comment.getString().getString()); - - cell = sheet.getRow(1).getCell(0); - comment = cell.getCellComment(); - assertEquals("a2", comment.getString().getString()); - - cell = sheet.getRow(2).getCell(0); - comment = cell.getCellComment(); - assertEquals("a3", comment.getString().getString()); - - cell = sheet.getRow(2).getCell(2); - comment = cell.getCellComment(); - assertEquals("c3", comment.getString().getString()); - - cell = sheet.getRow(4).getCell(1); - comment = cell.getCellComment(); - assertEquals("b5", comment.getString().getString()); - - cell = sheet.getRow(5).getCell(2); - comment = cell.getCellComment(); - assertEquals("c6", comment.getString().getString()); - - wb.close(); - } - - @Test - public void testBug56380InsertComments() throws Exception { - HSSFWorkbook workbook = new HSSFWorkbook(); - Sheet sheet = workbook.createSheet(); - Drawing drawing = sheet.createDrawingPatriarch(); - int noOfRows = 1025; - String comment = "c"; - - for(int i = 0; i < noOfRows; i++) { - Row row = sheet.createRow(i); - Cell cell = row.createCell(0); - insertComment(drawing, cell, comment + i); - } - - // assert that the comments are created properly before writing - checkComments(sheet, noOfRows, comment); - - /*// store in temp-file - OutputStream fs = new FileOutputStream("/tmp/56380.xls"); - try { - sheet.getWorkbook().write(fs); - } finally { - fs.close(); - }*/ - - // save and recreate the workbook from the saved file - HSSFWorkbook workbookBack = HSSFTestDataSamples.writeOutAndReadBack(workbook); - sheet = workbookBack.getSheetAt(0); - - // assert that the comments are created properly after reading back in - checkComments(sheet, noOfRows, comment); - - workbook.close(); - workbookBack.close(); - } - - @Test - public void testBug56380InsertTooManyComments() throws Exception { - HSSFWorkbook workbook = new HSSFWorkbook(); - try { - Sheet sheet = workbook.createSheet(); - Drawing drawing = sheet.createDrawingPatriarch(); - String comment = "c"; - - for(int rowNum = 0;rowNum < 258;rowNum++) { - sheet.createRow(rowNum); - } - - // should still work, for some reason DrawingManager2.allocateShapeId() skips the first 1024... - for(int count = 1025;count < 65535;count++) { - int rowNum = count / 255; - int cellNum = count % 255; - Cell cell = sheet.getRow(rowNum).createCell(cellNum); - try { - Comment commentObj = insertComment(drawing, cell, comment + cellNum); - - assertEquals(count, ((HSSFComment)commentObj).getNoteRecord().getShapeId()); - } catch (IllegalArgumentException e) { - throw new IllegalArgumentException("While adding shape number " + count, e); - } - } - - // this should now fail to insert - Row row = sheet.createRow(257); - Cell cell = row.createCell(0); - insertComment(drawing, cell, comment + 0); - } finally { - workbook.close(); - } - } - - private void checkComments(Sheet sheet, int noOfRows, String comment) { - for(int i = 0; i < noOfRows; i++) { - assertNotNull(sheet.getRow(i)); - assertNotNull(sheet.getRow(i).getCell(0)); - assertNotNull("Did not get a Cell Comment for row " + i, sheet.getRow(i).getCell(0).getCellComment()); - assertNotNull(sheet.getRow(i).getCell(0).getCellComment().getString()); - assertEquals(comment + i, sheet.getRow(i).getCell(0).getCellComment().getString().getString()); - } - } - - private Comment insertComment(Drawing drawing, Cell cell, String message) { - CreationHelper factory = cell.getSheet().getWorkbook().getCreationHelper(); - - ClientAnchor anchor = factory.createClientAnchor(); - anchor.setCol1(cell.getColumnIndex()); - anchor.setCol2(cell.getColumnIndex() + 1); - anchor.setRow1(cell.getRowIndex()); - anchor.setRow2(cell.getRowIndex() + 1); - anchor.setDx1(100); - anchor.setDx2(100); - anchor.setDy1(100); - anchor.setDy2(100); - - Comment comment = drawing.createCellComment(anchor); - - RichTextString str = factory.createRichTextString(message); - comment.setString(str); - comment.setAuthor("fanfy"); - cell.setCellComment(comment); - - return comment; - } - - @Test - public void resultEqualsToNonExistingAbstractShape() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sh = wb.createSheet(); - HSSFPatriarch patriarch = sh.createDrawingPatriarch(); - - HSSFComment comment = patriarch.createCellComment(new HSSFClientAnchor()); - HSSFRow row = sh.createRow(0); - HSSFCell cell = row.createCell(0); - cell.setCellComment(comment); - - assertEquals(comment.getEscherContainer().getChildRecords().size(), 5); - - //sp record - byte[] expected = decompress("H4sIAAAAAAAAAFvEw/WBg4GBgZEFSHAxMAAA9gX7nhAAAAA="); - byte[] actual = comment.getEscherContainer().getChild(0).serialize(); - - assertEquals(expected.length, actual.length); - assertArrayEquals(expected, actual); - - expected = decompress("H4sIAAAAAAAAAGNgEPggxIANAABK4+laGgAAAA=="); - actual = comment.getEscherContainer().getChild(2).serialize(); - - assertEquals(expected.length, actual.length); - assertArrayEquals(expected, actual); - - expected = decompress("H4sIAAAAAAAAAGNgEPzAAAQACl6c5QgAAAA="); - actual = comment.getEscherContainer().getChild(3).serialize(); - - assertEquals(expected.length, actual.length); - assertArrayEquals(expected, actual); - - expected = decompress("H4sIAAAAAAAAAGNg4P3AAAQA6pyIkQgAAAA="); - actual = comment.getEscherContainer().getChild(4).serialize(); - - assertEquals(expected.length, actual.length); - assertArrayEquals(expected, actual); - - ObjRecord obj = comment.getObjRecord(); - - expected = decompress("H4sIAAAAAAAAAItlMGEQZRBikGRgZBF0YEACvAxiDLgBAJZsuoU4AAAA"); - actual = obj.serialize(); - - assertEquals(expected.length, actual.length); - //assertArrayEquals(expected, actual); - - TextObjectRecord tor = comment.getTextObjectRecord(); - - expected = decompress("H4sIAAAAAAAAANvGKMQgxMSABgBGi8T+FgAAAA=="); - actual = tor.serialize(); - - assertEquals(expected.length, actual.length); - assertArrayEquals(expected, actual); - - NoteRecord note = comment.getNoteRecord(); - - expected = decompress("H4sIAAAAAAAAAJNh4GGAAEYWEAkAS0KXuRAAAAA="); - actual = note.serialize(); - - assertEquals(expected.length, actual.length); - assertArrayEquals(expected, actual); - - wb.close(); - } - - @Test - public void addToExistingFile() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sh = wb.createSheet(); - HSSFPatriarch patriarch = sh.createDrawingPatriarch(); - int idx = wb.addPicture(new byte[]{1,2,3}, Workbook.PICTURE_TYPE_PNG); - - HSSFComment comment = patriarch.createCellComment(new HSSFClientAnchor()); - comment.setColumn(5); - comment.setString(new HSSFRichTextString("comment1")); - comment = patriarch.createCellComment(new HSSFClientAnchor(0,0,100,100,(short)0,0,(short)10,10)); - comment.setRow(5); - comment.setString(new HSSFRichTextString("comment2")); - comment.setBackgroundImage(idx); - assertEquals(comment.getBackgroundImageId(), idx); - - assertEquals(patriarch.getChildren().size(), 2); - - HSSFWorkbook wbBack = HSSFTestDataSamples.writeOutAndReadBack(wb); - sh = wbBack.getSheetAt(0); - patriarch = sh.getDrawingPatriarch(); - - comment = (HSSFComment) patriarch.getChildren().get(1); - assertEquals(comment.getBackgroundImageId(), idx); - comment.resetBackgroundImage(); - assertEquals(comment.getBackgroundImageId(), 0); - - assertEquals(patriarch.getChildren().size(), 2); - comment = patriarch.createCellComment(new HSSFClientAnchor()); - comment.setString(new HSSFRichTextString("comment3")); - - assertEquals(patriarch.getChildren().size(), 3); - HSSFWorkbook wbBack2 = HSSFTestDataSamples.writeOutAndReadBack(wbBack); - sh = wbBack2.getSheetAt(0); - patriarch = sh.getDrawingPatriarch(); - comment = (HSSFComment) patriarch.getChildren().get(1); - assertEquals(comment.getBackgroundImageId(), 0); - assertEquals(patriarch.getChildren().size(), 3); - assertEquals(((HSSFComment) patriarch.getChildren().get(0)).getString().getString(), "comment1"); - assertEquals(((HSSFComment) patriarch.getChildren().get(1)).getString().getString(), "comment2"); - assertEquals(((HSSFComment) patriarch.getChildren().get(2)).getString().getString(), "comment3"); - - wb.close(); - wbBack.close(); - wbBack2.close(); - } - - @Test - public void setGetProperties() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sh = wb.createSheet(); - HSSFPatriarch patriarch = sh.createDrawingPatriarch(); - - HSSFComment comment = patriarch.createCellComment(new HSSFClientAnchor()); - comment.setString(new HSSFRichTextString("comment1")); - assertEquals(comment.getString().getString(), "comment1"); - - comment.setAuthor("poi"); - assertEquals(comment.getAuthor(), "poi"); - - comment.setColumn(3); - assertEquals(comment.getColumn(), 3); - - comment.setRow(4); - assertEquals(comment.getRow(), 4); - - comment.setVisible(false); - assertEquals(comment.isVisible(), false); - - HSSFWorkbook wbBack = HSSFTestDataSamples.writeOutAndReadBack(wb); - sh = wbBack.getSheetAt(0); - patriarch = sh.getDrawingPatriarch(); - - comment = (HSSFComment) patriarch.getChildren().get(0); - - assertEquals(comment.getString().getString(), "comment1"); - assertEquals("poi", comment.getAuthor()); - assertEquals(comment.getColumn(), 3); - assertEquals(comment.getRow(), 4); - assertEquals(comment.isVisible(), false); - - comment.setString(new HSSFRichTextString("comment12")); - comment.setAuthor("poi2"); - comment.setColumn(32); - comment.setRow(42); - comment.setVisible(true); - - HSSFWorkbook wbBack2 = HSSFTestDataSamples.writeOutAndReadBack(wbBack); - sh = wbBack2.getSheetAt(0); - patriarch = sh.getDrawingPatriarch(); - comment = (HSSFComment) patriarch.getChildren().get(0); - - assertEquals(comment.getString().getString(), "comment12"); - assertEquals("poi2", comment.getAuthor()); - assertEquals(comment.getColumn(), 32); - assertEquals(comment.getRow(), 42); - assertEquals(comment.isVisible(), true); - - wb.close(); - wbBack.close(); - wbBack2.close(); - } - - @Test - public void existingFileWithComment() throws IOException { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("drawings.xls"); - HSSFSheet sheet = wb.getSheet("comments"); - HSSFPatriarch drawing = sheet.getDrawingPatriarch(); - assertEquals(1, drawing.getChildren().size()); - HSSFComment comment = (HSSFComment) drawing.getChildren().get(0); - assertEquals(comment.getAuthor(), "evgeniy"); - assertEquals(comment.getString().getString(), "evgeniy:\npoi test"); - assertEquals(comment.getColumn(), 1); - assertEquals(comment.getRow(), 2); - wb.close(); - } - - @Test - public void findComments() throws IOException{ - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sh = wb.createSheet(); - HSSFPatriarch patriarch = sh.createDrawingPatriarch(); - - HSSFComment comment = patriarch.createCellComment(new HSSFClientAnchor()); - HSSFRow row = sh.createRow(5); - HSSFCell cell = row.createCell(4); - cell.setCellComment(comment); - - assertNotNull(sh.findCellComment(5, 4)); - assertNull(sh.findCellComment(5, 5)); - - HSSFWorkbook wbBack = HSSFTestDataSamples.writeOutAndReadBack(wb); - sh = wbBack.getSheetAt(0); - - assertNotNull(sh.findCellComment(5, 4)); - assertNull(sh.findCellComment(5, 5)); - - wb.close(); - wbBack.close(); - } - - @Test - public void initState() throws IOException{ - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sh = wb.createSheet(); - HSSFPatriarch patriarch = sh.createDrawingPatriarch(); - - EscherAggregate agg = HSSFTestHelper.getEscherAggregate(patriarch); - assertEquals(agg.getTailRecords().size(), 0); - - HSSFComment comment = patriarch.createCellComment(new HSSFClientAnchor()); - assertEquals(agg.getTailRecords().size(), 1); - - HSSFSimpleShape shape = patriarch.createSimpleShape(new HSSFClientAnchor()); - assertNotNull(shape); - - assertEquals(comment.getOptRecord().getEscherProperties().size(), 10); - - wb.close(); - } - - @Test - public void shapeId() throws IOException{ - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sh = wb.createSheet(); - HSSFPatriarch patriarch = sh.createDrawingPatriarch(); - - HSSFComment comment = patriarch.createCellComment(new HSSFClientAnchor()); - - comment.setShapeId(2024); - - assertEquals(comment.getShapeId(), 2024); - - CommonObjectDataSubRecord cod = (CommonObjectDataSubRecord) comment.getObjRecord().getSubRecords().get(0); - assertEquals(2024, cod.getObjectId()); - EscherSpRecord spRecord = (EscherSpRecord) comment.getEscherContainer().getChild(0); - assertEquals(2024, spRecord.getShapeId(), 2024); - assertEquals(2024, comment.getShapeId(), 2024); - assertEquals(2024, comment.getNoteRecord().getShapeId()); - - wb.close(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFConditionalFormatting.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFConditionalFormatting.java deleted file mode 100644 index 63ba22c93..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFConditionalFormatting.java +++ /dev/null @@ -1,122 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - - -import static org.junit.Assert.*; - -import java.io.IOException; - -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.hssf.util.HSSFColor; -import org.apache.poi.ss.usermodel.*; -import org.junit.Test; - -/** - * HSSF-specific Conditional Formatting tests - */ -public final class TestHSSFConditionalFormatting extends BaseTestConditionalFormatting { - public TestHSSFConditionalFormatting(){ - super(HSSFITestDataProvider.instance); - } - @Override - protected void assertColour(String hexExpected, Color actual) { - assertNotNull("Colour must be given", actual); - if (actual instanceof HSSFColor) { - HSSFColor colour = (HSSFColor)actual; - assertEquals(hexExpected, colour.getHexString()); - } else { - HSSFExtendedColor colour = (HSSFExtendedColor)actual; - if (hexExpected.length() == 8) { - assertEquals(hexExpected, colour.getARGBHex()); - } else { - assertEquals(hexExpected, colour.getARGBHex().substring(2)); - } - } - } - - @Test - public void testRead() throws IOException { - testRead("WithConditionalFormatting.xls"); - } - - @Test - public void testReadOffice2007() throws IOException { - testReadOffice2007("NewStyleConditionalFormattings.xls"); - } - - @Test - public void test53691() throws IOException { - SheetConditionalFormatting cf; - final Workbook wb = HSSFITestDataProvider.instance.openSampleWorkbook("53691.xls"); - /* - FileInputStream s = new FileInputStream("C:\\temp\\53691bbadfixed.xls"); - try { - wb = new HSSFWorkbook(s); - } finally { - s.close(); - } - - wb.removeSheetAt(1);*/ - - // initially it is good - writeTemp53691(wb, "agood"); - - // clone sheet corrupts it - Sheet sheet = wb.cloneSheet(0); - writeTemp53691(wb, "bbad"); - - // removing the sheet makes it good again - wb.removeSheetAt(wb.getSheetIndex(sheet)); - writeTemp53691(wb, "cgood"); - - // cloning again and removing the conditional formatting makes it good again - sheet = wb.cloneSheet(0); - removeConditionalFormatting(sheet); - writeTemp53691(wb, "dgood"); - - // cloning the conditional formatting manually makes it bad again - cf = sheet.getSheetConditionalFormatting(); - SheetConditionalFormatting scf = wb.getSheetAt(0).getSheetConditionalFormatting(); - for (int j = 0; j < scf.getNumConditionalFormattings(); j++) { - cf.addConditionalFormatting(scf.getConditionalFormattingAt(j)); - } - writeTemp53691(wb, "ebad"); - - // remove all conditional formatting for comparing BIFF output - removeConditionalFormatting(sheet); - removeConditionalFormatting(wb.getSheetAt(0)); - writeTemp53691(wb, "fgood"); - - wb.close(); - } - - private void removeConditionalFormatting(Sheet sheet) { - SheetConditionalFormatting cf = sheet.getSheetConditionalFormatting(); - for (int j = 0; j < cf.getNumConditionalFormattings(); j++) { - cf.removeConditionalFormatting(j); - } - } - - private void writeTemp53691(Workbook wb, @SuppressWarnings("UnusedParameters") String suffix) throws IOException { - // assert that we can write/read it in memory - Workbook wbBack = HSSFITestDataProvider.instance.writeOutAndReadBack(wb); - assertNotNull(wbBack); - wbBack.close(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFDataFormat.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFDataFormat.java deleted file mode 100644 index dd334b018..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFDataFormat.java +++ /dev/null @@ -1,102 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; - -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.ss.usermodel.BaseTestDataFormat; -import org.apache.poi.ss.usermodel.BuiltinFormats; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.DataFormat; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.junit.Test; - -/** - * Tests for {@link HSSFDataFormat} - */ -public final class TestHSSFDataFormat extends BaseTestDataFormat { - private static POILogger _logger = POILogFactory.getLogger(TestHSSFDataFormat.class); - - public TestHSSFDataFormat() { - super(HSSFITestDataProvider.instance); - } - - /** - * [Bug 49928] formatCellValue returns incorrect value for \u00a3 formatted cells - */ - @Override - @Test - public void test49928() throws IOException { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("49928.xls"); - doTest49928Core(wb); - - // an attempt to register an existing format returns its index - int poundFmtIdx = wb.getSheetAt(0).getRow(0).getCell(0).getCellStyle().getDataFormat(); - assertEquals(poundFmtIdx, wb.createDataFormat().getFormat(poundFmt)); - - // now create a custom format with Pound (\u00a3) - DataFormat dataFormat = wb.createDataFormat(); - short customFmtIdx = dataFormat.getFormat("\u00a3##.00[Yellow]"); - assertTrue(customFmtIdx >= BuiltinFormats.FIRST_USER_DEFINED_FORMAT_INDEX ); - assertEquals("\u00a3##.00[Yellow]", dataFormat.getFormat(customFmtIdx)); - - wb.close(); - } - - /** - * [Bug 58532] Handle formats that go numnum, numK, numM etc - */ - @Override - @Test - public void test58532() throws IOException { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("FormatKM.xls"); - doTest58532Core(wb); - wb.close(); - } - - /** - * Bug 51378: getDataFormatString method call crashes when reading the test file - */ - @Test - public void test51378() throws IOException { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("12561-1.xls"); - for (int i = 0; i < wb.getNumberOfSheets(); i++) { - HSSFSheet sheet = wb.getSheetAt(i); - for (Row row : sheet) { - for (Cell cell : row) { - CellStyle style = cell.getCellStyle(); - - String fmt = style.getDataFormatString(); - if(fmt == null) { - _logger.log(POILogger.WARN, cell + ": " + fmt); - } - } - } - } - wb.close(); - } - -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFDataFormatter.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFDataFormatter.java deleted file mode 100644 index 35c307ba4..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFDataFormatter.java +++ /dev/null @@ -1,459 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.text.DecimalFormat; -import java.text.DecimalFormatSymbols; -import java.text.Format; -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.Iterator; -import java.util.Locale; -import java.util.TimeZone; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.DateUtil; -import org.apache.poi.util.LocaleUtil; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; - -/** - * Unit tests for HSSFDataFormatter.java - */ -public final class TestHSSFDataFormatter { - private static TimeZone userTimeZone; - - @BeforeClass - public static void setTimeZone() { - userTimeZone = LocaleUtil.getUserTimeZone(); - LocaleUtil.setUserTimeZone(TimeZone.getTimeZone("CET")); - LocaleUtil.setUserLocale(Locale.US); - } - - @AfterClass - public static void resetTimeZone() { - LocaleUtil.setUserTimeZone(userTimeZone); - LocaleUtil.setUserLocale(Locale.ROOT); - } - - - private final HSSFDataFormatter formatter; - private final HSSFWorkbook wb; - - public TestHSSFDataFormatter() { - // create the formatter to test - formatter = new HSSFDataFormatter(); - - // create a workbook to test with - wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet(); - HSSFDataFormat format = wb.createDataFormat(); - - // create a row and put some cells in it - HSSFRow row = sheet.createRow(0); - - // date value for July 8 1901 1:19 PM - double dateNum = 555.555; - // date value for July 8 1901 11:23 AM - double timeNum = 555.47431; - - //valid date formats -- all should have "Jul" in output - String[] goodDatePatterns = { - "[$-F800]dddd\\,\\ mmmm\\ dd\\,\\ yyyy", - "mmm/d/yy\\ h:mm PM;@", - "mmmm/d/yy\\ h:mm;@", - "mmmm/d;@", - "mmmm/d/yy;@", - "mmm/dd/yy;@", - "[$-409]d\\-mmm;@", - "[$-409]d\\-mmm\\-yy;@", - "[$-409]dd\\-mmm\\-yy;@", - "[$-409]mmm\\-yy;@", - "[$-409]mmmm\\-yy;@", - "[$-409]mmmm\\ d\\,\\ yyyy;@", - "[$-409]mmm/d/yy\\ h:mm:ss;@", - "[$-409]mmmm/d/yy\\ h:mm:ss am;@", - "[$-409]mmmmm;@", - "[$-409]mmmmm\\-yy;@", - "mmmm/d/yyyy;@", - "[$-409]d\\-mmm\\-yyyy;@", - "[$-409]d\\-mmm;[$-3]d\\-mmm;@", // international three-part - "[$-41f]d\\-mmm;[$-41f]d\\-mmm;@", // turkish international three-part - "[$-F40f]d\\-mmm;[$-F40f]d\\-mmm;@", // custom international three-part - "[$-F40f]d\\-mmm;[$-F40f]d\\-mmm;0;@" // custom international four-part - }; - - //valid time formats - all should have 11:23 in output - String[] goodTimePatterns = { - "HH:MM", - "HH:MM:SS", - "HH:MM;HH:MM;HH:MM", - // This is fun - blue if positive time, - // red if negative time or green for zero! - "[BLUE]HH:MM;[RED]HH:MM;[GREEN]HH:MM", - "yyyy-mm-dd hh:mm", - "yyyy-mm-dd hh:mm:ss", - }; - - // valid number formats - String[] goodNumPatterns = { - "#,##0.0000", - "#,##0;[Red]#,##0", - "(#,##0.00_);(#,##0.00)", - "($#,##0.00_);[Red]($#,##0.00)", - "$#,##0.00", - "[$-809]#,##0.00", // international format - "[$-2]#,##0.00", // international format - "[$-041f]#,##0.00", // international format - "0000.00000%", - "0.000E+00", - "0.00E+00", - "[BLACK]0.00;[COLOR 5]##.##", - "[>999999]#,,\"M\";[>999]#,\"K\";#", // num/K/M - "[>999999]#.000,,\"M\";[>999]#.000,\"K\";#.000", // with decimals - "[$-809]#,##0.00;[$-809]#,##0.00", // two-part international format - "[$-809]#,##0.00;[$-809]#,##0.00;0", // three-part international format - "[$-809]#,##0.00;[$-809]#,##0.00;0;@", // four-part international format - }; - - // invalid date formats -- will throw exception in DecimalFormat ctor - String[] badNumPatterns = { - "#,#$'#0.0000", - "'#','#ABC#0;##,##0", - "000 '123 4'5'6 000", - "#''0#0'1#10L16EE" - }; - - // create cells with good date patterns - for (int i = 0; i < goodDatePatterns.length; i++) { - HSSFCell cell = row.createCell(i); - cell.setCellValue(dateNum); - HSSFCellStyle cellStyle = wb.createCellStyle(); - cellStyle.setDataFormat(format.getFormat(goodDatePatterns[i])); - cell.setCellStyle(cellStyle); - } - row = sheet.createRow(1); - - // create cells with time patterns - for (int i = 0; i < goodTimePatterns.length; i++) { - HSSFCell cell = row.createCell(i); - cell.setCellValue(timeNum); - HSSFCellStyle cellStyle = wb.createCellStyle(); - cellStyle.setDataFormat(format.getFormat(goodTimePatterns[i])); - cell.setCellStyle(cellStyle); - } - row = sheet.createRow(2); - - // create cells with num patterns - for (int i = 0; i < goodNumPatterns.length; i++) { - HSSFCell cell = row.createCell(i); - cell.setCellValue(-1234567890.12345); - HSSFCellStyle cellStyle = wb.createCellStyle(); - cellStyle.setDataFormat(format.getFormat(goodNumPatterns[i])); - cell.setCellStyle(cellStyle); - } - row = sheet.createRow(3); - - // create cells with bad num patterns - for (int i = 0; i < badNumPatterns.length; i++) { - HSSFCell cell = row.createCell(i); - // If the '.' is any later, ExcelGeneralNumberFormat will render an integer, as Excel does. - cell.setCellValue(12345678.9012345); - HSSFCellStyle cellStyle = wb.createCellStyle(); - cellStyle.setDataFormat(format.getFormat(badNumPatterns[i])); - cell.setCellStyle(cellStyle); - } - - // Built in formats - - { // Zip + 4 format - row = sheet.createRow(4); - HSSFCell cell = row.createCell(0); - cell.setCellValue(123456789); - HSSFCellStyle cellStyle = wb.createCellStyle(); - cellStyle.setDataFormat(format.getFormat("00000-0000")); - cell.setCellStyle(cellStyle); - } - - { // Phone number format - row = sheet.createRow(5); - HSSFCell cell = row.createCell(0); - cell.setCellValue(5551234567D); - HSSFCellStyle cellStyle = wb.createCellStyle(); - cellStyle.setDataFormat(format.getFormat("[<=9999999]###-####;(###) ###-####")); - cell.setCellStyle(cellStyle); - } - - { // SSN format - row = sheet.createRow(6); - HSSFCell cell = row.createCell(0); - cell.setCellValue(444551234); - HSSFCellStyle cellStyle = wb.createCellStyle(); - cellStyle.setDataFormat(format.getFormat("000-00-0000")); - cell.setCellStyle(cellStyle); - } - - { // formula cell - row = sheet.createRow(7); - HSSFCell cell = row.createCell(0); - cell.setCellType(CellType.FORMULA); - cell.setCellFormula("SUM(12.25,12.25)/100"); - HSSFCellStyle cellStyle = wb.createCellStyle(); - cellStyle.setDataFormat(format.getFormat("##.00%;")); - cell.setCellStyle(cellStyle); - } - } - - /** - * Test getting formatted values from numeric and date cells. - */ - @Test - public void testGetFormattedCellValueHSSFCell() { - // Valid date formats -- cell values should be date formatted & not "555.555" - HSSFRow row = wb.getSheetAt(0).getRow(0); - Iterator it = row.cellIterator(); - log("==== VALID DATE FORMATS ===="); - while (it.hasNext()) { - Cell cell = it.next(); - String fmtval = formatter.formatCellValue(cell); - log(fmtval); - - // should not be equal to "555.555" - assertTrue( DateUtil.isCellDateFormatted(cell) ); - assertTrue( ! "555.555".equals(fmtval)); - - String fmt = cell.getCellStyle().getDataFormatString(); - - //assert the correct month form, as in the original Excel format - String monthPtrn = fmt.contains("mmmm") ? "MMMM" : "MMM"; - // this line is intended to compute how "July" would look like in the current locale - SimpleDateFormat sdf = new SimpleDateFormat(monthPtrn, LocaleUtil.getUserLocale()); - sdf.setTimeZone(LocaleUtil.getUserTimeZone()); - Calendar calDef = LocaleUtil.getLocaleCalendar(2010, 6, 15, 0, 0, 0); - String jul = sdf.format(calDef.getTime()); - // special case for MMMMM = 1st letter of month name - if(fmt.contains("mmmmm")) { - jul = jul.substring(0,1); - } - // check we found july properly - assertTrue("Format came out incorrect - " + fmt, fmtval.contains(jul)); - } - - row = wb.getSheetAt(0).getRow(1); - it = row.cellIterator(); - log("==== VALID TIME FORMATS ===="); - while (it.hasNext()) { - Cell cell = it.next(); - String fmt = cell.getCellStyle().getDataFormatString(); - String fmtval = formatter.formatCellValue(cell); - log(fmtval); - - // should not be equal to "555.47431" - assertTrue( DateUtil.isCellDateFormatted(cell) ); - assertTrue( ! "555.47431".equals(fmtval)); - - // check we found the time properly - assertTrue("Format came out incorrect - " + fmt + " - found " + fmtval + - ", but expected to find '11:23'", fmtval.contains("11:23")); - } - - // test number formats - row = wb.getSheetAt(0).getRow(1); - it = row.cellIterator(); - log("\n==== VALID NUMBER FORMATS ===="); - while (it.hasNext()) { - HSSFCell cell = (HSSFCell) it.next(); - final String formatted = formatter.formatCellValue(cell); - log(formatted); - - // should not include "12345678" - note that the input value was negative - assertTrue(formatted != null && ! formatted.contains("12345678")); - } - - // test bad number formats - row = wb.getSheetAt(0).getRow(3); - it = row.cellIterator(); - log("\n==== INVALID NUMBER FORMATS ===="); - while (it.hasNext()) { - HSSFCell cell = (HSSFCell) it.next(); - log(formatter.formatCellValue(cell)); - // in some locales the the decimal delimiter is a comma, not a dot - char decimalSeparator = DecimalFormatSymbols.getInstance(LocaleUtil.getUserLocale()).getDecimalSeparator(); - assertEquals("12345678" + decimalSeparator + "9", formatter.formatCellValue(cell)); - } - - // test Zip+4 format - row = wb.getSheetAt(0).getRow(4); - HSSFCell cell = row.getCell(0); - log("\n==== ZIP FORMAT ===="); - log(formatter.formatCellValue(cell)); - assertEquals("12345-6789", formatter.formatCellValue(cell)); - - // test phone number format - row = wb.getSheetAt(0).getRow(5); - cell = row.getCell(0); - log("\n==== PHONE FORMAT ===="); - log(formatter.formatCellValue(cell)); - assertEquals("(555) 123-4567", formatter.formatCellValue(cell)); - - // test SSN format - row = wb.getSheetAt(0).getRow(6); - cell = row.getCell(0); - log("\n==== SSN FORMAT ===="); - log(formatter.formatCellValue(cell)); - assertEquals("444-55-1234", formatter.formatCellValue(cell)); - - // null test-- null cell should result in empty String - assertEquals(formatter.formatCellValue(null), ""); - - // null test-- null cell should result in empty String - assertEquals(formatter.formatCellValue(null), ""); - } - - @Test - public void testGetFormattedCellValueHSSFCellHSSFFormulaEvaluator() { - // test formula format - HSSFRow row = wb.getSheetAt(0).getRow(7); - HSSFCell cell = row.getCell(0); - log("\n==== FORMULA CELL ===="); - - // first without a formula evaluator - log(formatter.formatCellValue(cell) + "\t (without evaluator)"); - assertEquals("SUM(12.25,12.25)/100", formatter.formatCellValue(cell)); - - // now with a formula evaluator - HSSFFormulaEvaluator evaluator = new HSSFFormulaEvaluator(wb); - log(formatter.formatCellValue(cell, evaluator) + "\t\t\t (with evaluator)"); - char decimalSeparator = DecimalFormatSymbols.getInstance(LocaleUtil.getUserLocale()).getDecimalSeparator(); - assertEquals("24" + decimalSeparator + "50%", formatter.formatCellValue(cell,evaluator)); - - } - - /** - * Test using a default number format. The format should be used when a - * format pattern cannot be parsed by DecimalFormat. - */ - @Test - public void testSetDefaultNumberFormat() { - HSSFRow row = wb.getSheetAt(0).getRow(3); - Iterator it = row.cellIterator(); - DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(LocaleUtil.getUserLocale()); - Format defaultFormat = new DecimalFormat("Balance $#,#00.00 USD;Balance -$#,#00.00 USD", dfs); - formatter.setDefaultNumberFormat(defaultFormat); - - log("\n==== DEFAULT NUMBER FORMAT ===="); - while (it.hasNext()) { - Cell cell = it.next(); - cell.setCellValue(cell.getNumericCellValue() * Math.random() / 1000000 - 1000); - log(formatter.formatCellValue(cell)); - - String formatted = formatter.formatCellValue(cell); - assertTrue("Doesn't start with Balance: " + formatted, formatted.startsWith("Balance ")); - assertTrue("Doesn't end with USD: " + formatted, formatted.endsWith(" USD")); - } - } - - /** - * A format of "@" means use the general format - */ - @Test - public void testGeneralAtFormat() { - HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook("47154.xls"); - HSSFSheet sheet = workbook.getSheetAt(0); - HSSFRow row = sheet.getRow(0); - HSSFCell cellA1 = row.getCell(0); - - assertEquals(CellType.NUMERIC, cellA1.getCellTypeEnum()); - assertEquals(2345.0, cellA1.getNumericCellValue(), 0.0001); - assertEquals("@", cellA1.getCellStyle().getDataFormatString()); - - HSSFDataFormatter f = new HSSFDataFormatter(); - - assertEquals("2345", f.formatCellValue(cellA1)); - } - - /** - * Tests various formattings of dates and numbers - */ - @Test - public void testFromFile() { - HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook("Formatting.xls"); - HSSFSheet sheet = workbook.getSheetAt(0); - - HSSFDataFormatter f = new HSSFDataFormatter(); - - // This one is one of the nasty auto-locale changing ones... - assertEquals("dd/mm/yyyy", sheet.getRow(1).getCell(0).getStringCellValue()); - assertEquals("m/d/yy", sheet.getRow(1).getCell(1).getCellStyle().getDataFormatString()); - assertEquals("11/24/06", f.formatCellValue(sheet.getRow(1).getCell(1))); - - assertEquals("yyyy/mm/dd", sheet.getRow(2).getCell(0).getStringCellValue()); - assertEquals("yyyy/mm/dd", sheet.getRow(2).getCell(1).getCellStyle().getDataFormatString()); - assertEquals("2006/11/24", f.formatCellValue(sheet.getRow(2).getCell(1))); - - assertEquals("yyyy-mm-dd", sheet.getRow(3).getCell(0).getStringCellValue()); - assertEquals("yyyy\\-mm\\-dd", sheet.getRow(3).getCell(1).getCellStyle().getDataFormatString()); - assertEquals("2006-11-24", f.formatCellValue(sheet.getRow(3).getCell(1))); - - assertEquals("yy/mm/dd", sheet.getRow(4).getCell(0).getStringCellValue()); - assertEquals("yy/mm/dd", sheet.getRow(4).getCell(1).getCellStyle().getDataFormatString()); - assertEquals("06/11/24", f.formatCellValue(sheet.getRow(4).getCell(1))); - - // Another builtin fun one - assertEquals("dd/mm/yy", sheet.getRow(5).getCell(0).getStringCellValue()); - assertEquals("d/m/yy;@", sheet.getRow(5).getCell(1).getCellStyle().getDataFormatString()); - assertEquals("24/11/06", f.formatCellValue(sheet.getRow(5).getCell(1))); - - assertEquals("dd-mm-yy", sheet.getRow(6).getCell(0).getStringCellValue()); - assertEquals("dd\\-mm\\-yy", sheet.getRow(6).getCell(1).getCellStyle().getDataFormatString()); - assertEquals("24-11-06", f.formatCellValue(sheet.getRow(6).getCell(1))); - - - // Another builtin fun one - assertEquals("nn.nn", sheet.getRow(9).getCell(0).getStringCellValue()); - assertEquals("General", sheet.getRow(9).getCell(1).getCellStyle().getDataFormatString()); - assertEquals("10.52", f.formatCellValue(sheet.getRow(9).getCell(1))); - - // text isn't quite the format rule... - assertEquals("nn.nnn", sheet.getRow(10).getCell(0).getStringCellValue()); - assertEquals("0.000", sheet.getRow(10).getCell(1).getCellStyle().getDataFormatString()); - assertEquals("10.520", f.formatCellValue(sheet.getRow(10).getCell(1))); - - // text isn't quite the format rule... - assertEquals("nn.n", sheet.getRow(11).getCell(0).getStringCellValue()); - assertEquals("0.0", sheet.getRow(11).getCell(1).getCellStyle().getDataFormatString()); - assertEquals("10.5", f.formatCellValue(sheet.getRow(11).getCell(1))); - - // text isn't quite the format rule... - assertEquals("\u00a3nn.nn", sheet.getRow(12).getCell(0).getStringCellValue()); - assertEquals("\"\u00a3\"#,##0.00", sheet.getRow(12).getCell(1).getCellStyle().getDataFormatString()); - assertEquals("\u00a310.52", f.formatCellValue(sheet.getRow(12).getCell(1))); - } - - private static void log(@SuppressWarnings("UnusedParameters") String msg) { -// if (false) { // successful tests should be silent -// System.out.println(msg); -// } - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFDateUtil.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFDateUtil.java deleted file mode 100644 index 3cbd90498..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFDateUtil.java +++ /dev/null @@ -1,590 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static java.util.Calendar.AUGUST; -import static java.util.Calendar.FEBRUARY; -import static java.util.Calendar.JANUARY; -import static java.util.Calendar.JULY; -import static java.util.Calendar.MARCH; -import static java.util.Calendar.MAY; -import static java.util.Calendar.OCTOBER; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.IOException; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.Date; -import java.util.Locale; -import java.util.TimeZone; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.model.InternalWorkbook; -import org.apache.poi.ss.usermodel.DateUtil; -import org.apache.poi.util.LocaleUtil; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; - -/** - * Class TestHSSFDateUtil - */ -public class TestHSSFDateUtil { - - static TimeZone userTimeZone; - - @BeforeClass - public static void setCEST() { - userTimeZone = LocaleUtil.getUserTimeZone(); - LocaleUtil.setUserTimeZone(TimeZone.getTimeZone("CEST")); - } - - @AfterClass - public static void resetTimeZone() { - LocaleUtil.setUserTimeZone(userTimeZone); - } - - /** - * Checks the date conversion functions in the HSSFDateUtil class. - */ - @Test - public void dateConversion() { - - // Iteratating over the hours exposes any rounding issues. - Calendar cal = LocaleUtil.getLocaleCalendar(2002,JANUARY,1,0,1,1); - for (int hour = 0; hour < 23; hour++) { - double excelDate = HSSFDateUtil.getExcelDate(cal.getTime(), false); - - assertEquals("Checking hour = " + hour, cal.getTime().getTime(), - HSSFDateUtil.getJavaDate(excelDate, false).getTime()); - - cal.add(Calendar.HOUR_OF_DAY, 1); - } - - // check 1900 and 1904 date windowing conversions - double excelDate = 36526.0; - // with 1900 windowing, excelDate is Jan. 1, 2000 - // with 1904 windowing, excelDate is Jan. 2, 2004 - cal.set(2000,JANUARY,1,0,0,0); // Jan. 1, 2000 - Date dateIf1900 = cal.getTime(); - cal.add(Calendar.YEAR,4); // now Jan. 1, 2004 - cal.add(Calendar.DATE,1); // now Jan. 2, 2004 - Date dateIf1904 = cal.getTime(); - // 1900 windowing - assertEquals("Checking 1900 Date Windowing", - dateIf1900.getTime(), - HSSFDateUtil.getJavaDate(excelDate,false).getTime()); - // 1904 windowing - assertEquals("Checking 1904 Date Windowing", - dateIf1904.getTime(), - HSSFDateUtil.getJavaDate(excelDate,true).getTime()); - } - - /** - * Checks the conversion of a java.util.date to Excel on a day when - * Daylight Saving Time starts. - */ - @Test - public void excelConversionOnDSTStart() { - Calendar cal = LocaleUtil.getLocaleCalendar(2004,MARCH,28,0,0,0); - for (int hour = 0; hour < 24; hour++) { - - // Skip 02:00 CET as that is the Daylight change time - // and Java converts it automatically to 03:00 CEST - if (hour == 2) { - continue; - } - - cal.set(Calendar.HOUR_OF_DAY, hour); - Date javaDate = cal.getTime(); - - - double excelDate = HSSFDateUtil.getExcelDate(javaDate, false); - double difference = excelDate - Math.floor(excelDate); - int differenceInHours = (int) (difference * 24 * 60 + 0.5) / 60; - assertEquals("Checking " + hour + " hour on Daylight Saving Time start date", - hour, - differenceInHours); - assertEquals("Checking " + hour + " hour on Daylight Saving Time start date", - javaDate.getTime(), - HSSFDateUtil.getJavaDate(excelDate, false).getTime()); - } - } - - /** - * Checks the conversion of an Excel date to a java.util.date on a day when - * Daylight Saving Time starts. - */ - @Test - public void javaConversionOnDSTStart() { - Calendar cal = LocaleUtil.getLocaleCalendar(2004,MARCH,28,0,0,0); - double excelDate = HSSFDateUtil.getExcelDate(cal.getTime(), false); - double oneHour = 1.0 / 24; - double oneMinute = oneHour / 60; - for (int hour = 0; hour < 24; hour++, excelDate += oneHour) { - - // Skip 02:00 CET as that is the Daylight change time - // and Java converts it automatically to 03:00 CEST - if (hour == 2) { - continue; - } - - cal.set(Calendar.HOUR_OF_DAY, hour); - Date javaDate = HSSFDateUtil.getJavaDate(excelDate, false); - double actDate = HSSFDateUtil.getExcelDate(javaDate, false); - assertEquals("Checking " + hour + " hours on Daylight Saving Time start date", - excelDate, actDate, oneMinute); - } - } - - /** - * Checks the conversion of a java.util.Date to Excel on a day when - * Daylight Saving Time ends. - */ - @Test - public void excelConversionOnDSTEnd() { - Calendar cal = LocaleUtil.getLocaleCalendar(2004,OCTOBER,31,0,0,0); - for (int hour = 0; hour < 24; hour++) { - cal.set(Calendar.HOUR_OF_DAY, hour); - Date javaDate = cal.getTime(); - double excelDate = HSSFDateUtil.getExcelDate(javaDate, false); - double difference = excelDate - Math.floor(excelDate); - int differenceInHours = (int) (difference * 24 * 60 + 0.5) / 60; - assertEquals("Checking " + hour + " hour on Daylight Saving Time end date", - hour, - differenceInHours); - assertEquals("Checking " + hour + " hour on Daylight Saving Time start date", - javaDate.getTime(), - HSSFDateUtil.getJavaDate(excelDate, false).getTime()); - } - } - - /** - * Checks the conversion of an Excel date to java.util.Date on a day when - * Daylight Saving Time ends. - */ - @Test - public void javaConversionOnDSTEnd() { - Calendar cal = LocaleUtil.getLocaleCalendar(2004,OCTOBER,31,0,0,0); - double excelDate = HSSFDateUtil.getExcelDate(cal.getTime(), false); - double oneHour = 1.0 / 24; - double oneMinute = oneHour / 60; - for (int hour = 0; hour < 24; hour++, excelDate += oneHour) { - cal.set(Calendar.HOUR_OF_DAY, hour); - Date javaDate = HSSFDateUtil.getJavaDate(excelDate, false); - assertEquals("Checking " + hour + " hours on Daylight Saving Time start date", - excelDate, - HSSFDateUtil.getExcelDate(javaDate, false), oneMinute); - } - } - - /** - * Tests that we deal with time-zones properly - */ - @Test - public void calendarConversion() { - TimeZone userTZ = LocaleUtil.getUserTimeZone(); - LocaleUtil.setUserTimeZone(TimeZone.getTimeZone("CET")); - try { - Calendar cal = LocaleUtil.getLocaleCalendar(2002,JANUARY,1,12,1,1); - Date expected = cal.getTime(); - - // Iterating over the hours exposes any rounding issues. - for (int hour = -12; hour <= 12; hour++) - { - String id = "GMT" + (hour < 0 ? "" : "+") + hour + ":00"; - cal.setTimeZone(TimeZone.getTimeZone(id)); - cal.set(Calendar.HOUR_OF_DAY, 12); - double excelDate = HSSFDateUtil.getExcelDate(cal, false); - Date javaDate = HSSFDateUtil.getJavaDate(excelDate); - - // Should match despite time-zone - assertEquals("Checking timezone " + id, expected.getTime(), javaDate.getTime()); - } - - // Check that the timezone aware getter works correctly - TimeZone cet = TimeZone.getTimeZone("Europe/Copenhagen"); - TimeZone ldn = TimeZone.getTimeZone("Europe/London"); - - // 12:45 on 27th April 2012 - double excelDate = 41026.53125; - - // Same, no change - assertEquals( - HSSFDateUtil.getJavaDate(excelDate, false).getTime(), - HSSFDateUtil.getJavaDate(excelDate, false, cet).getTime() - ); - - // London vs Copenhagen, should differ by an hour - Date cetDate = HSSFDateUtil.getJavaDate(excelDate, false); - Date ldnDate = HSSFDateUtil.getJavaDate(excelDate, false, ldn); - assertEquals(ldnDate.getTime() - cetDate.getTime(), 60*60*1000); - } finally { - LocaleUtil.setUserTimeZone(userTZ); - } - } - - /** - * Tests that we correctly detect date formats as such - */ - @Test - public void identifyDateFormats() { - // First up, try with a few built in date formats - short[] builtins = new short[] { 0x0e, 0x0f, 0x10, 0x16, 0x2d, 0x2e }; - for (short builtin : builtins) { - String formatStr = HSSFDataFormat.getBuiltinFormat(builtin); - assertTrue( HSSFDateUtil.isInternalDateFormat(builtin) ); - assertTrue( HSSFDateUtil.isADateFormat(builtin,formatStr) ); - } - - // Now try a few built-in non date formats - builtins = new short[] { 0x01, 0x02, 0x17, 0x1f, 0x30 }; - for (short builtin : builtins) { - String formatStr = HSSFDataFormat.getBuiltinFormat(builtin); - assertFalse( HSSFDateUtil.isInternalDateFormat(builtin) ); - assertFalse( HSSFDateUtil.isADateFormat(builtin,formatStr) ); - } - - // Now for some non-internal ones - // These come after the real ones - int numBuiltins = HSSFDataFormat.getNumberOfBuiltinBuiltinFormats(); - assertTrue(numBuiltins < 60); - short formatId = 60; - assertFalse( HSSFDateUtil.isInternalDateFormat(formatId) ); - - // Valid ones first - String[] formats = new String[] { - "yyyy-mm-dd", "yyyy/mm/dd", "yy/mm/dd", "yy/mmm/dd", - "dd/mm/yy", "dd/mm/yyyy", "dd/mmm/yy", - "dd-mm-yy", "dd-mm-yyyy", - "DD-MM-YY", "DD-mm-YYYY", - "dd\\-mm\\-yy", // Sometimes escaped - "dd.mm.yyyy", "dd\\.mm\\.yyyy", - "dd\\ mm\\.yyyy AM", "dd\\ mm\\.yyyy pm", - "dd\\ mm\\.yyyy\\-dd", "[h]:mm:ss", - "mm/dd/yy", "\"mm\"/\"dd\"/\"yy\"", - "m\\/d\\/yyyy", - - // These crazy ones are valid - "yyyy-mm-dd;@", "yyyy/mm/dd;@", - "dd-mm-yy;@", "dd-mm-yyyy;@", - // These even crazier ones are also valid - // (who knows what they mean though...) - "[$-F800]dddd\\,\\ mmm\\ dd\\,\\ yyyy", - "[$-F900]ddd/mm/yyy", - // These ones specify colours, who knew that was allowed? - "[BLACK]dddd/mm/yy", - "[yeLLow]yyyy-mm-dd" - }; - for (String format : formats) { - assertTrue( - format + " is a date format", - HSSFDateUtil.isADateFormat(formatId, format) - ); - } - - // Then time based ones too - formats = new String[] { - "yyyy-mm-dd hh:mm:ss", "yyyy/mm/dd HH:MM:SS", - "mm/dd HH:MM", "yy/mmm/dd SS", - "mm/dd HH:MM AM", "mm/dd HH:MM am", - "mm/dd HH:MM PM", "mm/dd HH:MM pm", - "m/d/yy h:mm AM/PM", - "hh:mm:ss", "hh:mm:ss.0", "mm:ss.0", - //support elapsed time [h],[m],[s] - "[hh]", "[mm]", "[ss]", "[SS]", "[red][hh]" - }; - for (String format : formats) { - assertTrue( - format + " is a datetime format", - HSSFDateUtil.isADateFormat(formatId, format) - ); - } - - // Then invalid ones - formats = new String[] { - "yyyy*mm*dd", - "0.0", "0.000", - "0%", "0.0%", - "[]Foo", "[BLACK]0.00%", - "[ms]", "[Mh]", - "", null - }; - for (String format : formats) { - assertFalse( - format + " is not a date or datetime format", - HSSFDateUtil.isADateFormat(formatId, format) - ); - } - - // And these are ones we probably shouldn't allow, - // but would need a better regexp - formats = new String[] { - "yyyy:mm:dd", - }; - for (String format : formats) { - // assertFalse( HSSFDateUtil.isADateFormat(formatId, formats[i]) ); - } - } - - /** - * Test that against a real, test file, we still do everything - * correctly - * @throws IOException - */ - @Test - public void onARealFile() throws IOException { - - HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook("DateFormats.xls"); - HSSFSheet sheet = workbook.getSheetAt(0); - InternalWorkbook wb = workbook.getWorkbook(); - assertNotNull(wb); - - HSSFRow row; - HSSFCell cell; - HSSFCellStyle style; - - double aug_10_2007 = 39304.0; - - // Should have dates in 2nd column - // All of them are the 10th of August - // 2 US dates, 3 UK dates - row = sheet.getRow(0); - cell = row.getCell(1); - style = cell.getCellStyle(); - assertEquals(aug_10_2007, cell.getNumericCellValue(), 0.0001); - assertEquals("d-mmm-yy", style.getDataFormatString()); - assertTrue(HSSFDateUtil.isInternalDateFormat(style.getDataFormat())); - assertTrue(HSSFDateUtil.isADateFormat(style.getDataFormat(), style.getDataFormatString())); - assertTrue(HSSFDateUtil.isCellDateFormatted(cell)); - - row = sheet.getRow(1); - cell = row.getCell(1); - style = cell.getCellStyle(); - assertEquals(aug_10_2007, cell.getNumericCellValue(), 0.0001); - assertFalse(HSSFDateUtil.isInternalDateFormat(cell.getCellStyle().getDataFormat())); - assertTrue(HSSFDateUtil.isADateFormat(style.getDataFormat(), style.getDataFormatString())); - assertTrue(HSSFDateUtil.isCellDateFormatted(cell)); - - row = sheet.getRow(2); - cell = row.getCell(1); - style = cell.getCellStyle(); - assertEquals(aug_10_2007, cell.getNumericCellValue(), 0.0001); - assertTrue(HSSFDateUtil.isInternalDateFormat(cell.getCellStyle().getDataFormat())); - assertTrue(HSSFDateUtil.isADateFormat(style.getDataFormat(), style.getDataFormatString())); - assertTrue(HSSFDateUtil.isCellDateFormatted(cell)); - - row = sheet.getRow(3); - cell = row.getCell(1); - style = cell.getCellStyle(); - assertEquals(aug_10_2007, cell.getNumericCellValue(), 0.0001); - assertFalse(HSSFDateUtil.isInternalDateFormat(cell.getCellStyle().getDataFormat())); - assertTrue(HSSFDateUtil.isADateFormat(style.getDataFormat(), style.getDataFormatString())); - assertTrue(HSSFDateUtil.isCellDateFormatted(cell)); - - row = sheet.getRow(4); - cell = row.getCell(1); - style = cell.getCellStyle(); - assertEquals(aug_10_2007, cell.getNumericCellValue(), 0.0001); - assertFalse(HSSFDateUtil.isInternalDateFormat(cell.getCellStyle().getDataFormat())); - assertTrue(HSSFDateUtil.isADateFormat(style.getDataFormat(), style.getDataFormatString())); - assertTrue(HSSFDateUtil.isCellDateFormatted(cell)); - - workbook.close(); - } - - @Test - public void excelDateBorderCases() throws ParseException { - SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.ROOT); - df.setTimeZone(LocaleUtil.getUserTimeZone()); - - assertEquals(1.0, DateUtil.getExcelDate(df.parse("1900-01-01")), 0.00001); - assertEquals(31.0, DateUtil.getExcelDate(df.parse("1900-01-31")), 0.00001); - assertEquals(32.0, DateUtil.getExcelDate(df.parse("1900-02-01")), 0.00001); - assertEquals(/* BAD_DATE! */ -1.0, DateUtil.getExcelDate(df.parse("1899-12-31")), 0.00001); - } - - @Test - public void dateBug_2Excel() { - assertEquals(59.0, HSSFDateUtil.getExcelDate(createDate(1900, FEBRUARY, 28), false), 0.00001); - assertEquals(61.0, HSSFDateUtil.getExcelDate(createDate(1900, MARCH, 1), false), 0.00001); - - assertEquals(37315.00, HSSFDateUtil.getExcelDate(createDate(2002, FEBRUARY, 28), false), 0.00001); - assertEquals(37316.00, HSSFDateUtil.getExcelDate(createDate(2002, MARCH, 1), false), 0.00001); - assertEquals(37257.00, HSSFDateUtil.getExcelDate(createDate(2002, JANUARY, 1), false), 0.00001); - assertEquals(38074.00, HSSFDateUtil.getExcelDate(createDate(2004, MARCH, 28), false), 0.00001); - } - - @Test - public void dateBug_2Java() { - assertEquals(createDate(1900, FEBRUARY, 28), HSSFDateUtil.getJavaDate(59.0, false)); - assertEquals(createDate(1900, MARCH, 1), HSSFDateUtil.getJavaDate(61.0, false)); - - assertEquals(createDate(2002, FEBRUARY, 28), HSSFDateUtil.getJavaDate(37315.00, false)); - assertEquals(createDate(2002, MARCH, 1), HSSFDateUtil.getJavaDate(37316.00, false)); - assertEquals(createDate(2002, JANUARY, 1), HSSFDateUtil.getJavaDate(37257.00, false)); - assertEquals(createDate(2004, MARCH, 28), HSSFDateUtil.getJavaDate(38074.00, false)); - } - - @Test - public void date1904() { - assertEquals(createDate(1904, JANUARY, 2), HSSFDateUtil.getJavaDate(1.0, true)); - assertEquals(createDate(1904, JANUARY, 1), HSSFDateUtil.getJavaDate(0.0, true)); - assertEquals(0.0, HSSFDateUtil.getExcelDate(createDate(1904, JANUARY, 1), true), 0.00001); - assertEquals(1.0, HSSFDateUtil.getExcelDate(createDate(1904, JANUARY, 2), true), 0.00001); - - assertEquals(createDate(1998, JULY, 5), HSSFDateUtil.getJavaDate(35981, false)); - assertEquals(createDate(1998, JULY, 5), HSSFDateUtil.getJavaDate(34519, true)); - - assertEquals(35981.0, HSSFDateUtil.getExcelDate(createDate(1998, JULY, 5), false), 0.00001); - assertEquals(34519.0, HSSFDateUtil.getExcelDate(createDate(1998, JULY, 5), true), 0.00001); - } - - /** - * @param month zero based - * @param day one based - */ - private static Date createDate(int year, int month, int day) { - return createDate(year, month, day, 0, 0, 0); - } - - /** - * @param month zero based - * @param day one based - */ - private static Date createDate(int year, int month, int day, int hour, int minute, int second) { - Calendar c = LocaleUtil.getLocaleCalendar(year, month, day, hour, minute, second); - return c.getTime(); - } - - /** - * Check if HSSFDateUtil.getAbsoluteDay works as advertised. - */ - @Test - public void absoluteDay() { - // 1 Jan 1900 is 1 day after 31 Dec 1899 - Calendar cal = LocaleUtil.getLocaleCalendar(1900,JANUARY,1,0,0,0); - assertEquals("Checking absolute day (1 Jan 1900)", 1, HSSFDateUtil.absoluteDay(cal, false)); - // 1 Jan 1901 is 366 days after 31 Dec 1899 - cal.set(1901,JANUARY,1,0,0,0); - assertEquals("Checking absolute day (1 Jan 1901)", 366, HSSFDateUtil.absoluteDay(cal, false)); - } - - @Test - public void absoluteDayYearTooLow() { - Calendar cal = LocaleUtil.getLocaleCalendar(1899,JANUARY,1,0,0,0); - try { - HSSFDateUtil.absoluteDay(cal, false); - fail("Should fail here"); - } catch (IllegalArgumentException e) { - // expected here - } - - try { - cal.set(1903,JANUARY,1,0,0,0); - HSSFDateUtil.absoluteDay(cal, true); - fail("Should fail here"); - } catch (IllegalArgumentException e) { - // expected here - } - } - - @Test - public void convertTime() { - - final double delta = 1E-7; // a couple of digits more accuracy than strictly required - assertEquals(0.5, HSSFDateUtil.convertTime("12:00"), delta); - assertEquals(2.0/3, HSSFDateUtil.convertTime("16:00"), delta); - assertEquals(0.0000116, HSSFDateUtil.convertTime("0:00:01"), delta); - assertEquals(0.7330440, HSSFDateUtil.convertTime("17:35:35"), delta); - } - - @Test - public void parseDate() { - assertEquals(createDate(2008, AUGUST, 3), HSSFDateUtil.parseYYYYMMDDDate("2008/08/03")); - assertEquals(createDate(1994, MAY, 1), HSSFDateUtil.parseYYYYMMDDDate("1994/05/01")); - } - - /** - * Ensure that date values *with* a fractional portion get the right time of day - */ - @Test - public void convertDateTime() { - // Excel day 30000 is date 18-Feb-1982 - // 0.7 corresponds to time 16:48:00 - Date actual = HSSFDateUtil.getJavaDate(30000.7); - Date expected = createDate(1982, 1, 18, 16, 48, 0); - assertEquals(expected, actual); - } - - /** - * User reported a datetime issue in POI-2.5: - * Setting Cell's value to Jan 1, 1900 without a time doesn't return the same value set to - * @throws IOException - */ - @Test - public void bug19172() throws IOException - { - HSSFWorkbook workbook = new HSSFWorkbook(); - HSSFSheet sheet = workbook.createSheet(); - HSSFCell cell = sheet.createRow(0).createCell(0); - - // A pseudo special Excel dates - Calendar cal = LocaleUtil.getLocaleCalendar(1900, JANUARY, 1); - - Date valueToTest = cal.getTime(); - - cell.setCellValue(valueToTest); - - Date returnedValue = cell.getDateCellValue(); - - assertEquals(valueToTest.getTime(), returnedValue.getTime()); - - workbook.close(); - } - - /** - * DateUtil.isCellFormatted(Cell) should not true for a numeric cell - * that's formatted as ".0000" - */ - @Test - public void bug54557() throws Exception { - final String format = ".0000"; - boolean isDateFormat = HSSFDateUtil.isADateFormat(165, format); - - assertEquals(false, isDateFormat); - } - - @Test - public void bug56269() throws Exception { - double excelFraction = 41642.45833321759d; - Calendar calNoRound = HSSFDateUtil.getJavaCalendar(excelFraction, false); - assertEquals(10, calNoRound.get(Calendar.HOUR)); - assertEquals(59, calNoRound.get(Calendar.MINUTE)); - assertEquals(59, calNoRound.get(Calendar.SECOND)); - Calendar calRound = HSSFDateUtil.getJavaCalendar(excelFraction, false, null, true); - assertEquals(11, calRound.get(Calendar.HOUR)); - assertEquals(0, calRound.get(Calendar.MINUTE)); - assertEquals(0, calRound.get(Calendar.SECOND)); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFExternalFunctions.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFExternalFunctions.java deleted file mode 100644 index cb897c6c2..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFExternalFunctions.java +++ /dev/null @@ -1,30 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.ss.formula.BaseTestExternalFunctions; - -/** - * Tests setting and evaluating user-defined functions in HSSF - */ -public final class TestHSSFExternalFunctions extends BaseTestExternalFunctions { - public TestHSSFExternalFunctions() { - super(HSSFITestDataProvider.instance, "atp.xls"); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFFont.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFFont.java deleted file mode 100644 index 81f28d81f..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFFont.java +++ /dev/null @@ -1,42 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import java.io.IOException; - -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.ss.usermodel.BaseTestFont; -import org.apache.poi.ss.usermodel.Font; -import org.junit.Test; - -/** - * Tests various functionality having to do with {@link org.apache.poi.ss.usermodel.Name}. - * - * @author Yegor Kozlov - */ -public final class TestHSSFFont extends BaseTestFont { - - public TestHSSFFont() { - super(HSSFITestDataProvider.instance); - } - - @Test - public void testDefaultFont() throws IOException { - baseTestDefaultFont(HSSFFont.FONT_ARIAL, (short)200, Font.COLOR_NORMAL); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFFormulaEvaluator.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFFormulaEvaluator.java deleted file mode 100644 index d8987496f..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFFormulaEvaluator.java +++ /dev/null @@ -1,333 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -import java.io.IOException; - -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.record.NameRecord; -import org.apache.poi.ss.formula.EvaluationCell; -import org.apache.poi.ss.formula.EvaluationListener; -import org.apache.poi.ss.formula.WorkbookEvaluator; -import org.apache.poi.ss.formula.WorkbookEvaluatorTestHelper; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.ss.usermodel.BaseTestFormulaEvaluator; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; -import org.apache.poi.ss.usermodel.FormulaError; -import org.junit.Test; - -public final class TestHSSFFormulaEvaluator extends BaseTestFormulaEvaluator { - - public TestHSSFFormulaEvaluator() { - super(HSSFITestDataProvider.instance); - } - - /** - * Test that the HSSFFormulaEvaluator can evaluate simple named ranges - * (single cells and rectangular areas) - */ - @Test - public void testEvaluateSimple() throws IOException { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("testNames.xls"); - HSSFSheet sheet = wb.getSheetAt(0); - HSSFCell cell = sheet.getRow(8).getCell(0); - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - CellValue cv = fe.evaluate(cell); - assertEquals(CellType.NUMERIC, cv.getCellTypeEnum()); - assertEquals(3.72, cv.getNumberValue(), 0.0); - wb.close(); - } - - /** - * Test for bug due to attempt to convert a cached formula error result to a boolean - */ - @Test - @Override - public void testUpdateCachedFormulaResultFromErrorToNumber_bug46479() throws IOException { - - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("Sheet1"); - HSSFRow row = sheet.createRow(0); - HSSFCell cellA1 = row.createCell(0); - HSSFCell cellB1 = row.createCell(1); - cellB1.setCellFormula("A1+1"); - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - - cellA1.setCellErrorValue(FormulaError.NAME.getCode()); - fe.evaluateFormulaCellEnum(cellB1); - - cellA1.setCellValue(2.5); - fe.notifyUpdateCell(cellA1); - try { - fe.evaluateInCell(cellB1); - } catch (IllegalStateException e) { - if (e.getMessage().equals("Cannot get a numeric value from a error formula cell")) { - fail("Identified bug 46479a"); - } - } - assertEquals(3.5, cellB1.getNumericCellValue(), 0.0); - - wb.close(); - } - - /** - * When evaluating defined names, POI has to decide whether it is capable. Currently - * (May2009) POI only supports simple cell and area refs.
    - * The sample spreadsheet (bugzilla attachment 23508) had a name flagged as 'complex' - * which contained a simple area ref. It is not clear what the 'complex' flag is used - * for but POI should look elsewhere to decide whether it can evaluate the name. - */ - @Test - public void testDefinedNameWithComplexFlag_bug47048() throws IOException { - // Mock up a spreadsheet to match the critical details of the sample - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("Input"); - HSSFName definedName = wb.createName(); - definedName.setNameName("Is_Multicar_Vehicle"); - definedName.setRefersToFormula("Input!$B$17:$G$17"); - - // Set up some data and the formula - HSSFRow row17 = sheet.createRow(16); - row17.createCell(0).setCellValue(25.0); - row17.createCell(1).setCellValue(1.33); - row17.createCell(2).setCellValue(4.0); - - HSSFRow row = sheet.createRow(0); - HSSFCell cellA1 = row.createCell(0); - cellA1.setCellFormula("SUM(Is_Multicar_Vehicle)"); - - // Set the complex flag - POI doesn't usually manipulate this flag - NameRecord nameRec = TestHSSFName.getNameRecord(definedName); - nameRec.setOptionFlag((short)0x10); // 0x10 -> complex - - HSSFFormulaEvaluator hsf = new HSSFFormulaEvaluator(wb); - CellValue value; - try { - value = hsf.evaluate(cellA1); - - assertEquals(CellType.NUMERIC, value.getCellTypeEnum()); - assertEquals(5.33, value.getNumberValue(), 0.0); - - } catch (RuntimeException e) { - if (e.getMessage().equals("Don't now how to evalate name 'Is_Multicar_Vehicle'")) { - fail("Identified bug 47048a"); - } - throw e; - } finally { - wb.close(); - } - } - - private static final class EvalCountListener extends EvaluationListener { - private int _evalCount; - public EvalCountListener() { - _evalCount = 0; - } - @Override - public void onStartEvaluate(EvaluationCell cell, ICacheEntry entry) { - _evalCount++; - } - public int getEvalCount() { - return _evalCount; - } - } - - /** - * The HSSFFormula evaluator performance benefits greatly from caching of intermediate cell values - */ - @Test - public void testShortCircuitIfEvaluation() throws IOException { - - // Set up a simple IF() formula that has measurable evaluation cost for its operands. - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("Sheet1"); - HSSFRow row = sheet.createRow(0); - HSSFCell cellA1 = row.createCell(0); - cellA1.setCellFormula("if(B1,C1,D1+E1+F1)"); - // populate cells B1..F1 with simple formulas instead of plain values so we can use - // EvaluationListener to check which parts of the first formula get evaluated - for (int i=1; i<6; i++) { - // formulas are just literal constants "1".."5" - row.createCell(i).setCellFormula(String.valueOf(i)); - } - - EvalCountListener evalListener = new EvalCountListener(); - WorkbookEvaluator evaluator = WorkbookEvaluatorTestHelper.createEvaluator(wb, evalListener); - ValueEval ve = evaluator.evaluate(HSSFEvaluationTestHelper.wrapCell(cellA1)); - int evalCount = evalListener.getEvalCount(); - if (evalCount == 6) { - // Without short-circuit-if evaluation, evaluating cell 'A1' takes 3 extra evaluations (for D1,E1,F1) - fail("Identifed bug 48195 - Formula evaluator should short-circuit IF() calculations."); - } - assertEquals(3, evalCount); - assertEquals(2.0, ((NumberEval)ve).getNumberValue(), 0D); - - wb.close(); - } - - /** - * Ensures that we can handle NameXPtgs in the formulas - * we parse. - */ - @Test - public void testXRefs() throws IOException { - HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("XRefCalc.xls"); - HSSFWorkbook wb2 = HSSFTestDataSamples.openSampleWorkbook("XRefCalcData.xls"); - Cell cell; - - // VLookup on a name in another file - cell = wb1.getSheetAt(0).getRow(1).getCell(2); - assertEquals(CellType.FORMULA, cell.getCellTypeEnum()); - assertEquals(CellType.NUMERIC, cell.getCachedFormulaResultTypeEnum()); - assertEquals(12.30, cell.getNumericCellValue(), 0.0001); - // WARNING - this is wrong! - // The file name should be showing, but bug #45970 is fixed - // we seem to loose it - assertEquals("VLOOKUP(PART,COSTS,2,FALSE)", cell.getCellFormula()); - - - // Simple reference to a name in another file - cell = wb1.getSheetAt(0).getRow(1).getCell(4); - assertEquals(CellType.FORMULA, cell.getCellTypeEnum()); - assertEquals(CellType.NUMERIC, cell.getCachedFormulaResultTypeEnum()); - assertEquals(36.90, cell.getNumericCellValue(), 0.0001); - // TODO Correct this! - // The file name should be shown too, see bug #56742 - assertEquals("Cost*Markup_Cost", cell.getCellFormula()); - - - // Evaluate the cells - HSSFFormulaEvaluator eval = new HSSFFormulaEvaluator(wb1); - HSSFFormulaEvaluator.setupEnvironment( - new String[] { "XRefCalc.xls", "XRefCalcData.xls" }, - new HSSFFormulaEvaluator[] { - eval, - new HSSFFormulaEvaluator(wb2) - } - ); - eval.evaluateFormulaCellEnum( - wb1.getSheetAt(0).getRow(1).getCell(2) - ); - eval.evaluateFormulaCellEnum( - wb1.getSheetAt(0).getRow(1).getCell(4) - ); - - - // Re-check VLOOKUP one - cell = wb1.getSheetAt(0).getRow(1).getCell(2); - assertEquals(CellType.FORMULA, cell.getCellTypeEnum()); - assertEquals(CellType.NUMERIC, cell.getCachedFormulaResultTypeEnum()); - assertEquals(12.30, cell.getNumericCellValue(), 0.0001); - - // Re-check ref one - cell = wb1.getSheetAt(0).getRow(1).getCell(4); - assertEquals(CellType.FORMULA, cell.getCellTypeEnum()); - assertEquals(CellType.NUMERIC, cell.getCachedFormulaResultTypeEnum()); - assertEquals(36.90, cell.getNumericCellValue(), 0.0001); - - - // Add a formula that refers to one of the existing external workbooks - cell = wb1.getSheetAt(0).getRow(1).createCell(40); - cell.setCellFormula("Cost*[XRefCalcData.xls]MarkupSheet!$B$1"); - - // Check is was stored correctly - assertEquals("Cost*[XRefCalcData.xls]MarkupSheet!$B$1", cell.getCellFormula()); - - // Check it evaluates correctly - eval.evaluateFormulaCellEnum(cell); - assertEquals(24.60*1.8, cell.getNumericCellValue(), 0); - - - // Try to add a formula for a new external workbook, won't be allowed to start - try { - cell = wb1.getSheetAt(0).getRow(1).createCell(42); - cell.setCellFormula("[alt.xls]Sheet0!$A$1"); - fail("New workbook not linked, shouldn't be able to add"); - } catch(Exception e) {} - - // Link our new workbook - HSSFWorkbook wb3 = new HSSFWorkbook(); - wb3.createSheet().createRow(0).createCell(0).setCellValue("In another workbook"); - wb1.linkExternalWorkbook("alt.xls", wb3); - - // Now add a formula that refers to our new workbook - cell.setCellFormula("[alt.xls]Sheet0!$A$1"); - assertEquals("[alt.xls]Sheet0!$A$1", cell.getCellFormula()); - - // Evaluate it, without a link to that workbook - try { - eval.evaluate(cell); - fail("No cached value and no link to workbook, shouldn't evaluate"); - } catch(Exception e) {} - - // Add a link, check it does - HSSFFormulaEvaluator.setupEnvironment( - new String[] { "XRefCalc.xls", "XRefCalcData.xls", "alt.xls" }, - new HSSFFormulaEvaluator[] { - eval, - new HSSFFormulaEvaluator(wb2), - new HSSFFormulaEvaluator(wb3) - } - ); - eval.evaluateFormulaCellEnum(cell); - assertEquals("In another workbook", cell.getStringCellValue()); - - - // Save and re-load - HSSFWorkbook wb4 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - eval = new HSSFFormulaEvaluator(wb4); - HSSFFormulaEvaluator.setupEnvironment( - new String[] { "XRefCalc.xls", "XRefCalcData.xls", "alt.xls" }, - new HSSFFormulaEvaluator[] { - eval, - new HSSFFormulaEvaluator(wb2), - new HSSFFormulaEvaluator(wb3) - } - ); - - // Check the one referring to the previously existing workbook behaves - cell = wb4.getSheetAt(0).getRow(1).getCell(40); - assertEquals("Cost*[XRefCalcData.xls]MarkupSheet!$B$1", cell.getCellFormula()); - eval.evaluateFormulaCellEnum(cell); - assertEquals(24.60*1.8, cell.getNumericCellValue(), 0); - - // Now check the newly added reference - cell = wb4.getSheetAt(0).getRow(1).getCell(42); - assertEquals("[alt.xls]Sheet0!$A$1", cell.getCellFormula()); - eval.evaluateFormulaCellEnum(cell); - assertEquals("In another workbook", cell.getStringCellValue()); - - wb4.close(); - wb3.close(); - wb2.close(); - wb1.close(); - } - - @Test - public void testSharedFormulas() throws IOException { - baseTestSharedFormulas("shared_formulas.xls"); - } - -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFHeaderFooter.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFHeaderFooter.java deleted file mode 100644 index d2e820013..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFHeaderFooter.java +++ /dev/null @@ -1,186 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -import org.apache.poi.hssf.HSSFTestDataSamples; - -/** - * Tests for {@link HSSFHeader} / {@link HSSFFooter} - * - * @author Shawn Laubach (slaubach at apache dot com) - */ -public final class TestHSSFHeaderFooter extends TestCase { - - /** - * Tests that get header retrieves the proper values. - * - * @author Shawn Laubach (slaubach at apache dot org) - */ - public void testRetrieveCorrectHeader() { - - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("EmbeddedChartHeaderTest.xls"); - HSSFSheet s = wb.getSheetAt( 0 ); - HSSFHeader head = s.getHeader(); - - assertEquals("Top Left", head.getLeft()); - assertEquals("Top Center", head.getCenter()); - assertEquals("Top Right", head.getRight()); - } - - public void testSpecialChars() { - assertEquals("&U", HSSFHeader.startUnderline()); - assertEquals("&U", HSSFHeader.endUnderline()); - assertEquals("&P", HSSFHeader.page()); - - assertEquals("&22", HSSFFooter.fontSize((short)22)); - assertEquals("&\"Arial,bold\"", HSSFFooter.font("Arial", "bold")); - } - - public void testStripFields() { - String simple = "I am a test header"; - String withPage = "I am a&P test header"; - String withLots = "I&A am&N a&P test&T header&U"; - String withFont = "I&22 am a&\"Arial,bold\" test header"; - String withOtherAnds = "I am a&P test header&&"; - String withOtherAnds2 = "I am a&P test header&a&b"; - - assertEquals(simple, HSSFHeader.stripFields(simple)); - assertEquals(simple, HSSFHeader.stripFields(withPage)); - assertEquals(simple, HSSFHeader.stripFields(withLots)); - assertEquals(simple, HSSFHeader.stripFields(withFont)); - assertEquals(simple + "&&", HSSFHeader.stripFields(withOtherAnds)); - assertEquals(simple + "&a&b", HSSFHeader.stripFields(withOtherAnds2)); - - // Now test the default strip flag - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("EmbeddedChartHeaderTest.xls"); - HSSFSheet s = wb.getSheetAt( 0 ); - HSSFHeader head = s.getHeader(); - - assertEquals("Top Left", head.getLeft()); - assertEquals("Top Center", head.getCenter()); - assertEquals("Top Right", head.getRight()); - - head.setLeft("Top &P&F&D Left"); - assertEquals("Top &P&F&D Left", head.getLeft()); - - assertEquals("Top Left", HeaderFooter.stripFields(head.getLeft())); - - // Now even more complex - head.setCenter("HEADER TEXT &P&N&D&T&Z&F&F&A&G&X END"); - assertEquals("HEADER TEXT END", HeaderFooter.stripFields(head.getCenter())); - } - - /** - * Tests that get header retrieves the proper values. - * - * @author Shawn Laubach (slaubach at apache dot org) - */ - public void testRetrieveCorrectFooter() { - - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("EmbeddedChartHeaderTest.xls"); - HSSFSheet s = wb.getSheetAt(0); - HSSFFooter foot = s.getFooter(); - - assertEquals("Bottom Left", foot.getLeft()); - assertEquals("Bottom Center", foot.getCenter()); - assertEquals("Bottom Right", foot.getRight()); - } - - /** - * Testcase for Bug 17039 HSSFHeader does not support DBCS - */ - public void testHeaderHas16bitCharacter() { - HSSFWorkbook b = new HSSFWorkbook(); - HSSFSheet s = b.createSheet("Test"); - HSSFHeader h = s.getHeader(); - h.setLeft("\u0391"); - h.setCenter("\u0392"); - h.setRight("\u0393"); - - HSSFWorkbook b2 = HSSFTestDataSamples.writeOutAndReadBack(b); - HSSFHeader h2 = b2.getSheet("Test").getHeader(); - - assertEquals(h2.getLeft(),"\u0391"); - assertEquals(h2.getCenter(),"\u0392"); - assertEquals(h2.getRight(),"\u0393"); - } - - /** - * Testcase for Bug 17039 HSSFFooter does not support DBCS - */ - public void testFooterHas16bitCharacter() { - HSSFWorkbook b = new HSSFWorkbook(); - HSSFSheet s = b.createSheet("Test"); - HSSFFooter f = s.getFooter(); - f.setLeft("\u0391"); - f.setCenter("\u0392"); - f.setRight("\u0393"); - - HSSFWorkbook b2 = HSSFTestDataSamples.writeOutAndReadBack(b); - HSSFFooter f2 = b2.getSheet("Test").getFooter(); - - assertEquals(f2.getLeft(),"\u0391"); - assertEquals(f2.getCenter(),"\u0392"); - assertEquals(f2.getRight(),"\u0393"); - } - - public void testReadDBCSHeaderFooter() { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("DBCSHeader.xls"); - HSSFSheet s = wb.getSheetAt(0); - HSSFHeader h = s.getHeader(); - assertEquals("Header Left " ,h.getLeft(),"\u090f\u0915"); - assertEquals("Header Center " ,h.getCenter(),"\u0939\u094b\u0917\u093e"); - assertEquals("Header Right " ,h.getRight(),"\u091c\u093e"); - - HSSFFooter f = s.getFooter(); - assertEquals("Footer Left " ,f.getLeft(),"\u091c\u093e"); - assertEquals("Footer Center " ,f.getCenter(),"\u091c\u093e"); - assertEquals("Footer Right " ,f.getRight(),"\u091c\u093e"); - } - - /** - * Excel tolerates files with missing HEADER/FOOTER records. POI should do the same. - */ - public void testMissingHeaderFooterRecord_bug47244() { - // noHeaderFooter47244.xls was created by a slightly modified POI - // which omitted the HEADER/FOOTER records - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("noHeaderFooter47244.xls"); - HSSFSheet sheet = wb.getSheetAt(0); - HSSFFooter footer; - try { - footer = sheet.getFooter(); - } catch (NullPointerException e) { - throw new AssertionFailedError("Identified bug 47244a"); - } - assertEquals("", footer.getRawText()); - HSSFHeader header = sheet.getHeader(); - assertEquals("", header.getRawText()); - - // make sure header / footer is properly linked to underlying data - HSSFHeader header2 = sheet.getHeader(); - header.setCenter("foo"); - assertEquals("foo", header2.getCenter()); - - HSSFFooter footer2 = sheet.getFooter(); - footer.setCenter("bar"); - assertEquals("bar", footer2.getCenter()); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFHyperlink.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFHyperlink.java deleted file mode 100644 index a54d8f1e7..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFHyperlink.java +++ /dev/null @@ -1,293 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - -import java.io.IOException; - -import org.apache.poi.common.usermodel.HyperlinkType; -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.ss.usermodel.BaseTestHyperlink; -import org.apache.poi.ss.usermodel.Hyperlink; -/* -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.xssf.usermodel.XSSFCreationHelper; -import org.apache.poi.xssf.usermodel.XSSFHyperlink; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -*/ -import org.junit.Test; - -/** - * Tests HSSFHyperlink. - * - * @author Yegor Kozlov - */ -public final class TestHSSFHyperlink extends BaseTestHyperlink { - - public TestHSSFHyperlink() { - super(HSSFITestDataProvider.instance); - } - /** - * Test that we can read hyperlinks. - */ - @Test - public void testRead() { - - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("HyperlinksOnManySheets.xls"); - - HSSFSheet sheet; - HSSFCell cell; - HSSFHyperlink link; - - sheet = wb.getSheet("WebLinks"); - cell = sheet.getRow(4).getCell(0); - link = cell.getHyperlink(); - assertNotNull(link); - assertEquals("POI", link.getLabel()); - assertEquals("POI", cell.getRichStringCellValue().getString()); - assertEquals("http://poi.apache.org/", link.getAddress()); - assertEquals(HyperlinkType.URL, link.getTypeEnum()); - - cell = sheet.getRow(8).getCell(0); - link = cell.getHyperlink(); - assertNotNull(link); - assertEquals("HSSF", link.getLabel()); - assertEquals("HSSF", cell.getRichStringCellValue().getString()); - assertEquals("http://poi.apache.org/hssf/", link.getAddress()); - assertEquals(HyperlinkType.URL, link.getTypeEnum()); - - sheet = wb.getSheet("Emails"); - cell = sheet.getRow(4).getCell(0); - link = cell.getHyperlink(); - assertNotNull(link); - assertEquals("dev", link.getLabel()); - assertEquals("dev", cell.getRichStringCellValue().getString()); - assertEquals("mailto:dev@poi.apache.org", link.getAddress()); - assertEquals(HyperlinkType.EMAIL, link.getTypeEnum()); - - sheet = wb.getSheet("Internal"); - cell = sheet.getRow(4).getCell(0); - link = cell.getHyperlink(); - assertNotNull(link); - assertEquals("Link To First Sheet", link.getLabel()); - assertEquals("Link To First Sheet", cell.getRichStringCellValue().getString()); - assertEquals("WebLinks!A1", link.getTextMark()); - assertEquals("WebLinks!A1", link.getAddress()); - assertEquals(HyperlinkType.DOCUMENT, link.getTypeEnum()); - } - - @Test - public void testModify() { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("HyperlinksOnManySheets.xls"); - - HSSFSheet sheet; - HSSFCell cell; - HSSFHyperlink link; - - sheet = wb.getSheet("WebLinks"); - cell = sheet.getRow(4).getCell(0); - link = cell.getHyperlink(); - //modify the link - link.setAddress("www.apache.org"); - - wb = HSSFTestDataSamples.writeOutAndReadBack(wb); - sheet = wb.getSheet("WebLinks"); - cell = sheet.getRow(4).getCell(0); - link = cell.getHyperlink(); - assertNotNull(link); - assertEquals("www.apache.org", link.getAddress()); - - } - - /** - * HSSF-specific ways of creating links to a place in workbook. - * You can set the target in two ways: - * link.setTextMark("'Target Sheet-1'!A1"); //HSSF-specific - * or - * link.setAddress("'Target Sheet-1'!A1"); //common between XSSF and HSSF - * @throws IOException - */ - @Test - public void testCreateDocumentLink() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - - //link to a place in this workbook - HSSFHyperlink link; - HSSFCell cell; - HSSFSheet sheet = wb.createSheet("Hyperlinks"); - - //create a target sheet and cell - HSSFSheet sheet2 = wb.createSheet("Target Sheet"); - sheet2.createRow(0).createCell(0).setCellValue("Target Cell"); - - //cell A1 has a link to 'Target Sheet-1'!A1 - cell = sheet.createRow(0).createCell(0); - cell.setCellValue("Worksheet Link"); - link = new HSSFHyperlink(HyperlinkType.DOCUMENT); - link.setTextMark("'Target Sheet'!A1"); - cell.setHyperlink(link); - - //cell B1 has a link to cell A1 on the same sheet - cell = sheet.createRow(1).createCell(0); - cell.setCellValue("Worksheet Link"); - link = new HSSFHyperlink(HyperlinkType.DOCUMENT); - link.setAddress("'Hyperlinks'!A1"); - cell.setHyperlink(link); - - HSSFWorkbook wbBack = HSSFTestDataSamples.writeOutAndReadBack(wb); - wb.close(); - - sheet = wbBack.getSheet("Hyperlinks"); - - cell = sheet.getRow(0).getCell(0); - link = cell.getHyperlink(); - assertNotNull(link); - assertEquals("'Target Sheet'!A1", link.getTextMark()); - assertEquals("'Target Sheet'!A1", link.getAddress()); - - cell = sheet.getRow(1).getCell(0); - link = cell.getHyperlink(); - assertNotNull(link); - assertEquals("'Hyperlinks'!A1", link.getTextMark()); - assertEquals("'Hyperlinks'!A1", link.getAddress()); - - wbBack.close(); - } - - @Test - public void testCloneSheet() { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("HyperlinksOnManySheets.xls"); - - HSSFCell cell; - HSSFHyperlink link; - - HSSFSheet sheet = wb.cloneSheet(0); - - cell = sheet.getRow(4).getCell(0); - link = cell.getHyperlink(); - assertNotNull(link); - assertEquals("http://poi.apache.org/", link.getAddress()); - - cell = sheet.getRow(8).getCell(0); - link = cell.getHyperlink(); - assertNotNull(link); - assertEquals("http://poi.apache.org/hssf/", link.getAddress()); - } - - @Test - public void testCreate() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - - HSSFHyperlink link; - HSSFCell cell; - HSSFSheet sheet = wb.createSheet("Hyperlinks"); - - cell = sheet.createRow(1).createCell(0); - cell.setCellValue("File Link"); - link = new HSSFHyperlink(HyperlinkType.FILE); - link.setAddress("testfolder\\test.PDF"); - cell.setHyperlink(link); - - HSSFWorkbook wbBack = HSSFTestDataSamples.writeOutAndReadBack(wb); - - wb.close(); - - sheet = wbBack.getSheet("Hyperlinks"); - - cell = sheet.getRow(1).getCell(0); - link = cell.getHyperlink(); - assertNotNull(link); - assertEquals("testfolder\\test.PDF", link.getAddress()); - - wbBack.close(); - } - - /** - * Test that HSSFSheet#shiftRows moves hyperlinks, - * see bugs #46445 and #29957 - */ - @Test - public void testShiftRows(){ - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("46445.xls"); - - - HSSFSheet sheet = wb.getSheetAt(0); - - //verify existing hyperlink in A3 - HSSFCell cell1 = sheet.getRow(2).getCell(0); - HSSFHyperlink link1 = cell1.getHyperlink(); - assertNotNull(link1); - assertEquals(2, link1.getFirstRow()); - assertEquals(2, link1.getLastRow()); - - //assign a hyperlink to A4 - HSSFHyperlink link2 = new HSSFHyperlink(HyperlinkType.DOCUMENT); - link2.setAddress("Sheet2!A2"); - HSSFCell cell2 = sheet.getRow(3).getCell(0); - cell2.setHyperlink(link2); - assertEquals(3, link2.getFirstRow()); - assertEquals(3, link2.getLastRow()); - - //move the 3rd row two rows down - sheet.shiftRows(sheet.getFirstRowNum(), sheet.getLastRowNum(), 2); - - //cells A3 and A4 don't contain hyperlinks anymore - assertNull(sheet.getRow(2).getCell(0).getHyperlink()); - assertNull(sheet.getRow(3).getCell(0).getHyperlink()); - - //the first hyperlink now belongs to A5 - HSSFHyperlink link1_shifted = sheet.getRow(2+2).getCell(0).getHyperlink(); - assertNotNull(link1_shifted); - assertEquals(4, link1_shifted.getFirstRow()); - assertEquals(4, link1_shifted.getLastRow()); - - //the second hyperlink now belongs to A6 - HSSFHyperlink link2_shifted = sheet.getRow(3+2).getCell(0).getHyperlink(); - assertNotNull(link2_shifted); - assertEquals(5, link2_shifted.getFirstRow()); - assertEquals(5, link2_shifted.getLastRow()); - } - - @Override - public HSSFHyperlink copyHyperlink(Hyperlink link) { - return new HSSFHyperlink(link); - } - - /* - @Test - public void testCopyXSSFHyperlink() throws IOException { - XSSFWorkbook wb = new XSSFWorkbook(); - XSSFCreationHelper helper = wb.getCreationHelper(); - XSSFHyperlink xlink = helper.createHyperlink(Hyperlink.LINK_URL); - xlink.setAddress("http://poi.apache.org/"); - xlink.setCellReference("D3"); - xlink.setTooltip("tooltip"); - HSSFHyperlink hlink = new HSSFHyperlink(xlink); - - assertEquals("http://poi.apache.org/", hlink.getAddress()); - assertEquals("D3", new CellReference(hlink.getFirstRow(), hlink.getFirstColumn()).formatAsString()); - // Are HSSFHyperlink.label and XSSFHyperlink.tooltip the same? If so, perhaps one of these needs renamed for a consistent Hyperlink interface - // assertEquals("tooltip", hlink.getLabel()); - - wb.close(); - }*/ -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFName.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFName.java deleted file mode 100644 index 16333fc67..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFName.java +++ /dev/null @@ -1,241 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import org.apache.poi.POITestCase; -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.model.HSSFFormulaParser; -import org.apache.poi.hssf.record.NameRecord; -import org.apache.poi.ss.formula.FormulaType; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.apache.poi.ss.usermodel.BaseTestNamedRange; -import org.apache.poi.ss.util.AreaReference; -import org.apache.poi.ss.util.CellRangeAddress; -import org.junit.Test; - -import static org.junit.Assert.*; - -/** - * Tests various functionality having to do with {@link org.apache.poi.ss.usermodel.Name}. - */ -public final class TestHSSFName extends BaseTestNamedRange { - - /** - * For manipulating the internals of {@link HSSFName} during testing.
    - * Some tests need a {@link NameRecord} with unusual state, not normally producible by POI. - * This method achieves the aims at low cost without augmenting the POI usermodel api. - * @return a reference to the wrapped {@link NameRecord} - */ - public static NameRecord getNameRecord(HSSFName definedName) { - return POITestCase.getFieldValue(HSSFName.class, definedName, NameRecord.class, "_definedNameRec"); - } - - public TestHSSFName() { - super(HSSFITestDataProvider.instance); - } - - @Test - public void testRepeatingRowsAndColumsNames() throws Exception { - // First test that setting RR&C for same sheet more than once only creates a - // single Print_Titles built-in record - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("FirstSheet"); - - // set repeating rows and columns twice for the first sheet - CellRangeAddress cra = CellRangeAddress.valueOf("A1:A3"); - for (int i = 0; i < 2; i++) { - sheet.setRepeatingColumns(cra); - sheet.setRepeatingRows(cra); - sheet.createFreezePane(0, 3); - } - assertEquals(1, wb.getNumberOfNames()); - HSSFName nr1 = wb.getNameAt(0); - - assertEquals("Print_Titles", nr1.getNameName()); - // TODO - full column references not rendering properly, absolute markers not present either - // assertEquals("FirstSheet!$A:$A,FirstSheet!$1:$3", nr1.getRefersToFormula()); - assertEquals("FirstSheet!A:A,FirstSheet!$A$1:$IV$3", nr1.getRefersToFormula()); - - // Save and re-open - HSSFWorkbook nwb = HSSFTestDataSamples.writeOutAndReadBack(wb); - wb.close(); - - assertEquals(1, nwb.getNumberOfNames()); - nr1 = nwb.getNameAt(0); - - assertEquals("Print_Titles", nr1.getNameName()); - assertEquals("FirstSheet!A:A,FirstSheet!$A$1:$IV$3", nr1.getRefersToFormula()); - - // check that setting RR&C on a second sheet causes a new Print_Titles built-in - // name to be created - sheet = nwb.createSheet("SecondSheet"); - cra = CellRangeAddress.valueOf("B1:C1"); - sheet.setRepeatingColumns(cra); - sheet.setRepeatingRows(cra); - - assertEquals(2, nwb.getNumberOfNames()); - HSSFName nr2 = nwb.getNameAt(1); - - assertEquals("Print_Titles", nr2.getNameName()); - assertEquals("SecondSheet!B:C,SecondSheet!$A$1:$IV$1", nr2.getRefersToFormula()); - - nwb.close(); - } - - @Test - public void testNamedRange() throws Exception { - HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("Simple.xls"); - - //Creating new Named Range - HSSFName newNamedRange = wb1.createName(); - - //Getting Sheet Name for the reference - String sheetName = wb1.getSheetName(0); - - //Setting its name - newNamedRange.setNameName("RangeTest"); - //Setting its reference - newNamedRange.setRefersToFormula(sheetName + "!$D$4:$E$8"); - - //Getting NAmed Range - HSSFName namedRange1 = wb1.getNameAt(0); - //Getting it sheet name - sheetName = namedRange1.getSheetName(); - assertNotNull(sheetName); - - // sanity check - SanityChecker c = new SanityChecker(); - c.checkHSSFWorkbook(wb1); - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - HSSFName nm = wb2.getNameAt(wb2.getNameIndex("RangeTest")); - assertTrue("Name is "+nm.getNameName(),"RangeTest".equals(nm.getNameName())); - assertEquals(wb2.getSheetName(0)+"!$D$4:$E$8", nm.getRefersToFormula()); - wb2.close(); - wb1.close(); - } - - /** - * Reads an excel file already containing a named range. - *

    - * Addresses Bug #9632 - */ - @Test - public void testNamedRead() throws Exception { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("namedinput.xls"); - - //Get index of the named range with the name = "NamedRangeName" , which was defined in input.xls as A1:D10 - int NamedRangeIndex = wb.getNameIndex("NamedRangeName"); - - //Getting NAmed Range - HSSFName namedRange1 = wb.getNameAt(NamedRangeIndex); - String sheetName = wb.getSheetName(0); - - //Getting its reference - String reference = namedRange1.getRefersToFormula(); - - assertEquals(sheetName+"!$A$1:$D$10", reference); - - HSSFName namedRange2 = wb.getNameAt(1); - - assertEquals(sheetName+"!$D$17:$G$27", namedRange2.getRefersToFormula()); - assertEquals("SecondNamedRange", namedRange2.getNameName()); - - wb.close(); - } - - /** - * Reads an excel file already containing a named range and updates it - *

    - * OBJECTIVE: Test that HSSF can create a simple spreadsheet with numeric and string values and styled with fonts.

    - * SUCCESS: HSSF creates a sheet. Filesize matches a known good. HSSFSheet objects - * Last row, first row is tested against the correct values (99,0).

    - * FAILURE: HSSF does not create a sheet or excepts. Filesize does not match the known good. - * HSSFSheet last row or first row is incorrect.

    - * - */ - public void testWriteSheetFont() { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet s = wb.createSheet(); - HSSFRow r = null; - HSSFFont fnt = wb.createFont(); - HSSFCellStyle cs = wb.createCellStyle(); - - fnt.setColor(HSSFFont.COLOR_RED); - fnt.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); - cs.setFont(fnt); - for (int rownum = 0; rownum < 100; rownum++) - { - r = s.createRow(rownum); - r.setRowStyle(cs); - r.createCell(0); - } - wb = HSSFTestDataSamples.writeOutAndReadBack(wb); - - SanityChecker sanityChecker = new SanityChecker(); - sanityChecker.checkHSSFWorkbook(wb); - assertEquals("LAST ROW == 99", 99, s.getLastRowNum()); - assertEquals("FIRST ROW == 0", 0, s.getFirstRowNum()); - } - - /** - * Tests that is creating a file with a date or an calendar works correctly. - */ - public void testDataStyle() { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet s = wb.createSheet(); - HSSFCellStyle cs = wb.createCellStyle(); - HSSFRow row = s.createRow(0); - - // with Date: - cs.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy")); - row.setRowStyle(cs); - row.createCell(0); - - - // with Calendar: - row = s.createRow(1); - cs.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy")); - row.setRowStyle(cs); - row.createCell(0); - - wb = HSSFTestDataSamples.writeOutAndReadBack(wb); - - SanityChecker sanityChecker = new SanityChecker(); - sanityChecker.checkHSSFWorkbook(wb); - - assertEquals("LAST ROW ", 1, s.getLastRowNum()); - assertEquals("FIRST ROW ", 0, s.getFirstRowNum()); - - } - - /** - * TEST NAME: Test Write Sheet Style

    - * OBJECTIVE: Test that HSSF can create a simple spreadsheet with numeric and string values and styled with colors - * and borders.

    - * SUCCESS: HSSF creates a sheet. Filesize matches a known good. HSSFSheet objects - * Last row, first row is tested against the correct values (99,0).

    - * FAILURE: HSSF does not create a sheet or excepts. Filesize does not match the known good. - * HSSFSheet last row or first row is incorrect.

    - * - */ - public void testWriteSheetStyle() { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet s = wb.createSheet(); - HSSFRow r = null; - HSSFFont fnt = wb.createFont(); - HSSFCellStyle cs = wb.createCellStyle(); - HSSFCellStyle cs2 = wb.createCellStyle(); - - cs.setBorderBottom(BorderStyle.THIN); - cs.setBorderLeft(BorderStyle.THIN); - cs.setBorderRight(BorderStyle.THIN); - cs.setBorderTop(BorderStyle.THIN); - cs.setFillForegroundColor(( short ) 0xA); - cs.setFillPattern(( short ) 1); - fnt.setColor(( short ) 0xf); - fnt.setItalic(true); - cs2.setFillForegroundColor(( short ) 0x0); - cs2.setFillPattern(( short ) 1); - cs2.setFont(fnt); - for (int rownum = 0; rownum < 100; rownum++) - { - r = s.createRow(rownum); - r.setRowStyle(cs); - r.createCell(0); - - rownum++; - if (rownum >= 100) break; // I feel too lazy to check if this isreqd :-/ - - r = s.createRow(rownum); - r.setRowStyle(cs2); - r.createCell(0); - } - wb = HSSFTestDataSamples.writeOutAndReadBack(wb); - - SanityChecker sanityChecker = new SanityChecker(); - sanityChecker.checkHSSFWorkbook(wb); - assertEquals("LAST ROW == 99", 99, s.getLastRowNum()); - assertEquals("FIRST ROW == 0", 0, s.getFirstRowNum()); - - s = wb.getSheetAt(0); - assertNotNull("Sheet is not null", s); - - for (int rownum = 0; rownum < 100; rownum++) - { - r = s.getRow(rownum); - assertNotNull("Row is not null", r); - - cs = r.getRowStyle(); - assertEquals("Bottom Border Style for row:", BorderStyle.THIN, cs.getBorderBottomEnum()); - assertEquals("Left Border Style for row:", BorderStyle.THIN, cs.getBorderLeftEnum()); - assertEquals("Right Border Style for row:", BorderStyle.THIN, cs.getBorderRightEnum()); - assertEquals("Top Border Style for row:", BorderStyle.THIN, cs.getBorderTopEnum()); - assertEquals("FillForegroundColor for row:", 0xA, cs.getFillForegroundColor()); - assertEquals("FillPattern for row:", 0x1, cs.getFillPattern()); - - rownum++; - if (rownum >= 100) break; // I feel too lazy to check if this isreqd :-/ - - r = s.getRow(rownum); - assertNotNull("Row is not null", r); - cs2 = r.getRowStyle(); - assertEquals("FillForegroundColor for row: ", cs2.getFillForegroundColor(), (short) 0x0); - assertEquals("FillPattern for row: ", cs2.getFillPattern(), (short) 0x1); - } - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestSanityChecker.java b/src/testcases/org/apache/poi/hssf/usermodel/TestSanityChecker.java deleted file mode 100644 index 340187214..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestSanityChecker.java +++ /dev/null @@ -1,138 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.Assert.fail; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.apache.poi.hssf.record.BOFRecord; -import org.apache.poi.hssf.record.BoundSheetRecord; -import org.apache.poi.hssf.record.EOFRecord; -import org.apache.poi.hssf.record.InterfaceHdrRecord; -import org.apache.poi.hssf.record.NameRecord; -import org.apache.poi.hssf.record.Record; -import org.apache.poi.hssf.usermodel.SanityChecker.CheckRecord; -import org.junit.Test; - -/** - * A Test case for a test utility class.
    - * Okay, this may seem strange but I need to test my test logic. - * - * @author Glen Stampoultzis (glens at apache.org) - */ -public final class TestSanityChecker { - private static final Record INTERFACEHDR = new InterfaceHdrRecord(InterfaceHdrRecord.CODEPAGE); - private static BoundSheetRecord createBoundSheetRec() { - return new BoundSheetRecord("Sheet1"); - } - - @Test - public void testCheckRecordOrder() { - final SanityChecker c = new SanityChecker(); - List records = new ArrayList(); - records.add(new BOFRecord()); - records.add(INTERFACEHDR); - records.add(createBoundSheetRec()); - records.add(EOFRecord.instance); - CheckRecord[] check = { - new CheckRecord(BOFRecord.class, '1'), - new CheckRecord(InterfaceHdrRecord.class, '0'), - new CheckRecord(BoundSheetRecord.class, 'M'), - new CheckRecord(NameRecord.class, '*'), - new CheckRecord(EOFRecord.class, '1'), - }; - // check pass - c.checkRecordOrder(records, check); - records.add(2, createBoundSheetRec()); - c.checkRecordOrder(records, check); - records.remove(1); // optional record missing - c.checkRecordOrder(records, check); - records.add(3, new NameRecord()); - records.add(3, new NameRecord()); // optional multiple record occurs more than one time - c.checkRecordOrder(records, check); - - // check fail - confirmBadRecordOrder(check, new Record[] { - new BOFRecord(), - createBoundSheetRec(), - INTERFACEHDR, - EOFRecord.instance, - }); - - confirmBadRecordOrder(check, new Record[] { - new BOFRecord(), - INTERFACEHDR, - createBoundSheetRec(), - INTERFACEHDR, - EOFRecord.instance, - }); - - confirmBadRecordOrder(check, new Record[] { - new BOFRecord(), - createBoundSheetRec(), - new NameRecord(), - EOFRecord.instance, - new NameRecord(), - }); - - confirmBadRecordOrder(check, new Record[] { - INTERFACEHDR, - createBoundSheetRec(), - EOFRecord.instance, - }); - - confirmBadRecordOrder(check, new Record[] { - new BOFRecord(), - INTERFACEHDR, - EOFRecord.instance, - }); - - confirmBadRecordOrder(check, new Record[] { - INTERFACEHDR, - createBoundSheetRec(), - new BOFRecord(), - EOFRecord.instance, - }); - - confirmBadRecordOrder(check, new Record[] { - new BOFRecord(), - createBoundSheetRec(), - INTERFACEHDR, - EOFRecord.instance, - }); - } - private static void confirmBadRecordOrder(final SanityChecker.CheckRecord[] check, Record[] recs) { - final SanityChecker c = new SanityChecker(); - final List records = Arrays.asList(recs); - try { - new Runnable() { - @Override - public void run() { - c.checkRecordOrder(records, check); - } - }.run(); - } catch (AssertionError pass) { - // expected during normal test - return; - } - fail("Did not get failure exception as expected"); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestShapeGroup.java b/src/testcases/org/apache/poi/hssf/usermodel/TestShapeGroup.java deleted file mode 100644 index bbe81c381..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestShapeGroup.java +++ /dev/null @@ -1,265 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import org.apache.poi.POITestCase; -import org.apache.poi.ddf.EscherContainerRecord; -import org.apache.poi.ddf.EscherSpgrRecord; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.record.EscherAggregate; - -import junit.framework.TestCase; - -/** - * @author Evgeniy Berlog - * @date 29.06.12 - */ -public class TestShapeGroup extends TestCase{ - - public void testSetGetCoordinates(){ - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sh = wb.createSheet(); - HSSFPatriarch patriarch = sh.createDrawingPatriarch(); - HSSFShapeGroup group = patriarch.createGroup(new HSSFClientAnchor()); - assertEquals(group.getX1(), 0); - assertEquals(group.getY1(), 0); - assertEquals(group.getX2(), 1023); - assertEquals(group.getY2(), 255); - - group.setCoordinates(1,2,3,4); - - assertEquals(group.getX1(), 1); - assertEquals(group.getY1(), 2); - assertEquals(group.getX2(), 3); - assertEquals(group.getY2(), 4); - - wb = HSSFTestDataSamples.writeOutAndReadBack(wb); - sh = wb.getSheetAt(0); - patriarch = sh.getDrawingPatriarch(); - - group = (HSSFShapeGroup) patriarch.getChildren().get(0); - assertEquals(group.getX1(), 1); - assertEquals(group.getY1(), 2); - assertEquals(group.getX2(), 3); - assertEquals(group.getY2(), 4); - } - - public void testAddToExistingFile(){ - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sh = wb.createSheet(); - HSSFPatriarch patriarch = sh.createDrawingPatriarch(); - HSSFShapeGroup group1 = patriarch.createGroup(new HSSFClientAnchor()); - HSSFShapeGroup group2 = patriarch.createGroup(new HSSFClientAnchor()); - - group1.setCoordinates(1,2,3,4); - group2.setCoordinates(5,6,7,8); - - wb = HSSFTestDataSamples.writeOutAndReadBack(wb); - sh = wb.getSheetAt(0); - patriarch = sh.getDrawingPatriarch(); - - assertEquals(patriarch.getChildren().size(), 2); - - HSSFShapeGroup group3 = patriarch.createGroup(new HSSFClientAnchor()); - group3.setCoordinates(9,10,11,12); - - wb = HSSFTestDataSamples.writeOutAndReadBack(wb); - sh = wb.getSheetAt(0); - patriarch = sh.getDrawingPatriarch(); - - assertEquals(patriarch.getChildren().size(), 3); - } - - public void testModify() throws Exception { - HSSFWorkbook wb = new HSSFWorkbook(); - - // create a sheet with a text box - HSSFSheet sheet = wb.createSheet(); - HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); - - HSSFShapeGroup group1 = patriarch.createGroup(new - HSSFClientAnchor(0,0,0,0, - (short)0, 0, (short)15, 25)); - group1.setCoordinates(0, 0, 792, 612); - - HSSFTextbox textbox1 = group1.createTextbox(new - HSSFChildAnchor(100, 100, 300, 300)); - HSSFRichTextString rt1 = new HSSFRichTextString("Hello, World!"); - textbox1.setString(rt1); - - // write, read back and check that our text box is there - wb = HSSFTestDataSamples.writeOutAndReadBack(wb); - sheet = wb.getSheetAt(0); - patriarch = sheet.getDrawingPatriarch(); - assertEquals(1, patriarch.getChildren().size()); - - group1 = (HSSFShapeGroup)patriarch.getChildren().get(0); - assertEquals(1, group1.getChildren().size()); - textbox1 = (HSSFTextbox)group1.getChildren().get(0); - assertEquals("Hello, World!", textbox1.getString().getString()); - - // modify anchor - assertEquals(new HSSFChildAnchor(100, 100, 300, 300), - textbox1.getAnchor()); - HSSFChildAnchor newAnchor = new HSSFChildAnchor(200,200, 400, 400); - textbox1.setAnchor(newAnchor); - // modify text - textbox1.setString(new HSSFRichTextString("Hello, World! (modified)")); - - // add a new text box - HSSFTextbox textbox2 = group1.createTextbox(new - HSSFChildAnchor(400, 400, 600, 600)); - HSSFRichTextString rt2 = new HSSFRichTextString("Hello, World-2"); - textbox2.setString(rt2); - assertEquals(2, group1.getChildren().size()); - - wb = HSSFTestDataSamples.writeOutAndReadBack(wb); - sheet = wb.getSheetAt(0); - patriarch = sheet.getDrawingPatriarch(); - assertEquals(1, patriarch.getChildren().size()); - - group1 = (HSSFShapeGroup)patriarch.getChildren().get(0); - assertEquals(2, group1.getChildren().size()); - textbox1 = (HSSFTextbox)group1.getChildren().get(0); - assertEquals("Hello, World! (modified)", - textbox1.getString().getString()); - assertEquals(new HSSFChildAnchor(200,200, 400, 400), - textbox1.getAnchor()); - - textbox2 = (HSSFTextbox)group1.getChildren().get(1); - assertEquals("Hello, World-2", textbox2.getString().getString()); - assertEquals(new HSSFChildAnchor(400, 400, 600, 600), - textbox2.getAnchor()); - - wb = HSSFTestDataSamples.writeOutAndReadBack(wb); - sheet = wb.getSheetAt(0); - patriarch = sheet.getDrawingPatriarch(); - group1 = (HSSFShapeGroup)patriarch.getChildren().get(0); - textbox1 = (HSSFTextbox)group1.getChildren().get(0); - textbox2 = (HSSFTextbox)group1.getChildren().get(1); - HSSFTextbox textbox3 = group1.createTextbox(new - HSSFChildAnchor(400,200, 600, 400)); - HSSFRichTextString rt3 = new HSSFRichTextString("Hello, World-3"); - textbox3.setString(rt3); - } - - public void testAddShapesToGroup(){ - HSSFWorkbook wb = new HSSFWorkbook(); - - // create a sheet with a text box - HSSFSheet sheet = wb.createSheet(); - HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); - - HSSFShapeGroup group = patriarch.createGroup(new HSSFClientAnchor()); - int index = wb.addPicture(new byte[]{1,2,3}, HSSFWorkbook.PICTURE_TYPE_JPEG); - group.createPicture(new HSSFChildAnchor(), index); - HSSFPolygon polygon = group.createPolygon(new HSSFChildAnchor()); - polygon.setPoints(new int[]{1,100, 1}, new int[]{1, 50, 100}); - group.createTextbox(new HSSFChildAnchor()); - group.createShape(new HSSFChildAnchor()); - - wb = HSSFTestDataSamples.writeOutAndReadBack(wb); - sheet = wb.getSheetAt(0); - patriarch = sheet.getDrawingPatriarch(); - assertEquals(1, patriarch.getChildren().size()); - - assertTrue(patriarch.getChildren().get(0) instanceof HSSFShapeGroup); - group = (HSSFShapeGroup) patriarch.getChildren().get(0); - - assertEquals(group.getChildren().size(), 4); - - assertTrue(group.getChildren().get(0) instanceof HSSFPicture); - assertTrue(group.getChildren().get(1) instanceof HSSFPolygon); - assertTrue(group.getChildren().get(2) instanceof HSSFTextbox); - assertTrue(group.getChildren().get(3) instanceof HSSFSimpleShape); - - HSSFShapeGroup group2 = patriarch.createGroup(new HSSFClientAnchor()); - - index = wb.addPicture(new byte[]{2,2,2}, HSSFWorkbook.PICTURE_TYPE_JPEG); - group2.createPicture(new HSSFChildAnchor(), index); - polygon = group2.createPolygon(new HSSFChildAnchor()); - polygon.setPoints(new int[]{1,100, 1}, new int[]{1, 50, 100}); - group2.createTextbox(new HSSFChildAnchor()); - group2.createShape(new HSSFChildAnchor()); - group2.createShape(new HSSFChildAnchor()); - - wb = HSSFTestDataSamples.writeOutAndReadBack(wb); - sheet = wb.getSheetAt(0); - patriarch = sheet.getDrawingPatriarch(); - assertEquals(2, patriarch.getChildren().size()); - - group = (HSSFShapeGroup) patriarch.getChildren().get(1); - - assertEquals(group.getChildren().size(), 5); - - assertTrue(group.getChildren().get(0) instanceof HSSFPicture); - assertTrue(group.getChildren().get(1) instanceof HSSFPolygon); - assertTrue(group.getChildren().get(2) instanceof HSSFTextbox); - assertTrue(group.getChildren().get(3) instanceof HSSFSimpleShape); - assertTrue(group.getChildren().get(4) instanceof HSSFSimpleShape); - - group.getShapeId(); - } - - public void testSpgrRecord(){ - HSSFWorkbook wb = new HSSFWorkbook(); - - // create a sheet with a text box - HSSFSheet sheet = wb.createSheet(); - HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); - - HSSFShapeGroup group = patriarch.createGroup(new HSSFClientAnchor()); - assertSame(((EscherContainerRecord)group.getEscherContainer().getChild(0)).getChildById(EscherSpgrRecord.RECORD_ID), getSpgrRecord(group)); - } - - private static EscherSpgrRecord getSpgrRecord(HSSFShapeGroup group) { - return POITestCase.getFieldValue(HSSFShapeGroup.class, group, EscherSpgrRecord.class, "_spgrRecord"); - } - - public void testClearShapes(){ - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet(); - HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); - HSSFShapeGroup group = patriarch.createGroup(new HSSFClientAnchor()); - - group.createShape(new HSSFChildAnchor()); - group.createShape(new HSSFChildAnchor()); - - EscherAggregate agg = HSSFTestHelper.getEscherAggregate(patriarch); - - assertEquals(agg.getShapeToObjMapping().size(), 5); - assertEquals(agg.getTailRecords().size(), 0); - assertEquals(group.getChildren().size(), 2); - - group.clear(); - - assertEquals(agg.getShapeToObjMapping().size(), 1); - assertEquals(agg.getTailRecords().size(), 0); - assertEquals(group.getChildren().size(), 0); - - wb = HSSFTestDataSamples.writeOutAndReadBack(wb); - sheet = wb.getSheetAt(0); - patriarch = sheet.getDrawingPatriarch(); - - group = (HSSFShapeGroup) patriarch.getChildren().get(0); - - assertEquals(agg.getShapeToObjMapping().size(), 1); - assertEquals(agg.getTailRecords().size(), 0); - assertEquals(group.getChildren().size(), 0); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestSheetHiding.java b/src/testcases/org/apache/poi/hssf/usermodel/TestSheetHiding.java deleted file mode 100644 index ef70b1325..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestSheetHiding.java +++ /dev/null @@ -1,28 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.ss.usermodel.BaseTestSheetHiding; - -public final class TestSheetHiding extends BaseTestSheetHiding { - public TestSheetHiding() { - super(HSSFITestDataProvider.instance, - "TwoSheetsOneHidden.xls", "TwoSheetsNoneHidden.xls"); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestText.java b/src/testcases/org/apache/poi/hssf/usermodel/TestText.java deleted file mode 100644 index bb16cf987..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestText.java +++ /dev/null @@ -1,214 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.apache.poi.poifs.storage.RawDataUtil.decompress; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; - -import java.io.IOException; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.record.ObjRecord; -import org.apache.poi.hssf.record.TextObjectRecord; -import org.junit.Test; - -/** - * @author Evgeniy Berlog - * @date 25.06.12 - */ -public class TestText { - - @Test - public void testResultEqualsToNonExistingAbstractShape() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sh = wb.createSheet(); - HSSFPatriarch patriarch = sh.createDrawingPatriarch(); - HSSFTextbox textbox = patriarch.createTextbox(new HSSFClientAnchor()); - - assertEquals(textbox.getEscherContainer().getChildRecords().size(), 5); - - //sp record - byte[] expected = decompress("H4sIAAAAAAAAAFvEw/WBg4GBgZEFSHAxMAAA9gX7nhAAAAA="); - byte[] actual = textbox.getEscherContainer().getChild(0).serialize(); - - assertEquals(expected.length, actual.length); - assertArrayEquals(expected, actual); - - expected = decompress("H4sIAAAAAAAAAGNgEPggxIANAABK4+laGgAAAA=="); - actual = textbox.getEscherContainer().getChild(2).serialize(); - - assertEquals(expected.length, actual.length); - assertArrayEquals(expected, actual); - - expected = decompress("H4sIAAAAAAAAAGNgEPzAAAQACl6c5QgAAAA="); - actual = textbox.getEscherContainer().getChild(3).serialize(); - - assertEquals(expected.length, actual.length); - assertArrayEquals(expected, actual); - - expected = decompress("H4sIAAAAAAAAAGNg4P3AAAQA6pyIkQgAAAA="); - actual = textbox.getEscherContainer().getChild(4).serialize(); - - assertEquals(expected.length, actual.length); - assertArrayEquals(expected, actual); - - ObjRecord obj = textbox.getObjRecord(); - - expected = decompress("H4sIAAAAAAAAAItlkGIQZRBiYGNgZBBMYEADAOdCLuweAAAA"); - actual = obj.serialize(); - - assertEquals(expected.length, actual.length); - assertArrayEquals(expected, actual); - - TextObjectRecord tor = textbox.getTextObjectRecord(); - - expected = decompress("H4sIAAAAAAAAANvGKMQgxMSABgBGi8T+FgAAAA=="); - actual = tor.serialize(); - - assertEquals(expected.length, actual.length); - assertArrayEquals(expected, actual); - - wb.close(); - } - - @Test - public void testAddTextToExistingFile() throws Exception { - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet sh = wb1.createSheet(); - HSSFPatriarch patriarch = sh.createDrawingPatriarch(); - HSSFTextbox textbox = patriarch.createTextbox(new HSSFClientAnchor()); - textbox.setString(new HSSFRichTextString("just for test")); - HSSFTextbox textbox2 = patriarch.createTextbox(new HSSFClientAnchor()); - textbox2.setString(new HSSFRichTextString("just for test2")); - - assertEquals(patriarch.getChildren().size(), 2); - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sh = wb2.getSheetAt(0); - patriarch = sh.getDrawingPatriarch(); - - assertEquals(patriarch.getChildren().size(), 2); - HSSFTextbox text3 = patriarch.createTextbox(new HSSFClientAnchor()); - text3.setString(new HSSFRichTextString("text3")); - assertEquals(patriarch.getChildren().size(), 3); - - HSSFWorkbook wb3 = HSSFTestDataSamples.writeOutAndReadBack(wb2); - wb2.close(); - sh = wb3.getSheetAt(0); - patriarch = sh.getDrawingPatriarch(); - - assertEquals(patriarch.getChildren().size(), 3); - assertEquals(((HSSFTextbox) patriarch.getChildren().get(0)).getString().getString(), "just for test"); - assertEquals(((HSSFTextbox) patriarch.getChildren().get(1)).getString().getString(), "just for test2"); - assertEquals(((HSSFTextbox) patriarch.getChildren().get(2)).getString().getString(), "text3"); - - wb3.close(); - } - - @Test - public void testSetGetProperties() throws Exception { - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet sh = wb1.createSheet(); - HSSFPatriarch patriarch = sh.createDrawingPatriarch(); - HSSFTextbox textbox = patriarch.createTextbox(new HSSFClientAnchor()); - textbox.setString(new HSSFRichTextString("test")); - assertEquals(textbox.getString().getString(), "test"); - - textbox.setHorizontalAlignment((short) 5); - assertEquals(textbox.getHorizontalAlignment(), 5); - - textbox.setVerticalAlignment((short) 6); - assertEquals(textbox.getVerticalAlignment(), (short) 6); - - textbox.setMarginBottom(7); - assertEquals(textbox.getMarginBottom(), 7); - - textbox.setMarginLeft(8); - assertEquals(textbox.getMarginLeft(), 8); - - textbox.setMarginRight(9); - assertEquals(textbox.getMarginRight(), 9); - - textbox.setMarginTop(10); - assertEquals(textbox.getMarginTop(), 10); - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sh = wb2.getSheetAt(0); - patriarch = sh.getDrawingPatriarch(); - textbox = (HSSFTextbox) patriarch.getChildren().get(0); - assertEquals(textbox.getString().getString(), "test"); - assertEquals(textbox.getHorizontalAlignment(), 5); - assertEquals(textbox.getVerticalAlignment(), (short) 6); - assertEquals(textbox.getMarginBottom(), 7); - assertEquals(textbox.getMarginLeft(), 8); - assertEquals(textbox.getMarginRight(), 9); - assertEquals(textbox.getMarginTop(), 10); - - textbox.setString(new HSSFRichTextString("test1")); - textbox.setHorizontalAlignment(HSSFTextbox.HORIZONTAL_ALIGNMENT_CENTERED); - textbox.setVerticalAlignment(HSSFTextbox.VERTICAL_ALIGNMENT_TOP); - textbox.setMarginBottom(71); - textbox.setMarginLeft(81); - textbox.setMarginRight(91); - textbox.setMarginTop(101); - - assertEquals(textbox.getString().getString(), "test1"); - assertEquals(textbox.getHorizontalAlignment(), HSSFTextbox.HORIZONTAL_ALIGNMENT_CENTERED); - assertEquals(textbox.getVerticalAlignment(), HSSFTextbox.VERTICAL_ALIGNMENT_TOP); - assertEquals(textbox.getMarginBottom(), 71); - assertEquals(textbox.getMarginLeft(), 81); - assertEquals(textbox.getMarginRight(), 91); - assertEquals(textbox.getMarginTop(), 101); - - HSSFWorkbook wb3 = HSSFTestDataSamples.writeOutAndReadBack(wb2); - wb2.close(); - sh = wb3.getSheetAt(0); - patriarch = sh.getDrawingPatriarch(); - textbox = (HSSFTextbox) patriarch.getChildren().get(0); - - assertEquals(textbox.getString().getString(), "test1"); - assertEquals(textbox.getHorizontalAlignment(), HSSFTextbox.HORIZONTAL_ALIGNMENT_CENTERED); - assertEquals(textbox.getVerticalAlignment(), HSSFTextbox.VERTICAL_ALIGNMENT_TOP); - assertEquals(textbox.getMarginBottom(), 71); - assertEquals(textbox.getMarginLeft(), 81); - assertEquals(textbox.getMarginRight(), 91); - assertEquals(textbox.getMarginTop(), 101); - - wb3.close(); - } - - @Test - public void testExistingFileWithText() throws Exception { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("drawings.xls"); - HSSFSheet sheet = wb.getSheet("text"); - HSSFPatriarch drawing = sheet.getDrawingPatriarch(); - assertEquals(1, drawing.getChildren().size()); - HSSFTextbox textbox = (HSSFTextbox) drawing.getChildren().get(0); - assertEquals(textbox.getHorizontalAlignment(), HSSFTextbox.HORIZONTAL_ALIGNMENT_LEFT); - assertEquals(textbox.getVerticalAlignment(), HSSFTextbox.VERTICAL_ALIGNMENT_TOP); - assertEquals(textbox.getMarginTop(), 0); - assertEquals(textbox.getMarginBottom(), 3600000); - assertEquals(textbox.getMarginLeft(), 3600000); - assertEquals(textbox.getMarginRight(), 0); - assertEquals(textbox.getString().getString(), "teeeeesssstttt"); - wb.close(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestUnfixedBugs.java b/src/testcases/org/apache/poi/hssf/usermodel/TestUnfixedBugs.java deleted file mode 100644 index a059a025f..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestUnfixedBugs.java +++ /dev/null @@ -1,161 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import java.io.IOException; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.record.RecordFormatException; -import org.apache.poi.hssf.util.HSSFColor; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.junit.Test; - -import junit.framework.AssertionFailedError; - -/** - * @author aviks - * - * This testcase contains tests for bugs that are yet to be fixed. Therefore, - * the standard ant test target does not run these tests. Run this testcase with - * the single-test target. The names of the tests usually correspond to the - * Bugzilla id's PLEASE MOVE tests from this class to TestBugs once the bugs are - * fixed, so that they are then run automatically. - */ -public final class TestUnfixedBugs { - - @Test - public void test43493() { - // Has crazy corrupt sub-records on - // a EmbeddedObjectRefSubRecord - try { - HSSFTestDataSamples.openSampleWorkbook("43493.xls"); - } catch (RecordFormatException e) { - if (e.getCause().getCause() instanceof ArrayIndexOutOfBoundsException) { - throw new AssertionFailedError("Identified bug 43493"); - } - throw e; - } - } - - /** - * Note - some parts of this bug have been fixed, and have been - * transfered over to {@link TestBugs#bug49612_part()} - */ - @Test - public void test49612() throws IOException { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("49612.xls"); - HSSFSheet sh = wb.getSheetAt(0); - HSSFRow row = sh.getRow(0); - HSSFCell c1 = row.getCell(2); - HSSFCell d1 = row.getCell(3); - HSSFCell e1 = row.getCell(2); - - assertEquals("SUM(BOB+JIM)", c1.getCellFormula()); - - // Problem 1: Filename missing, see bug #56742 - assertEquals("SUM('49612.xls'!BOB+'49612.xls'!JIM)", d1.getCellFormula()); - - //Problem 2: Filename missing, see bug #56742 - //junit.framework.ComparisonFailure: - //Expected :SUM('49612.xls'!BOB+'49612.xls'!JIM) - //Actual :SUM(BOB+JIM) - assertEquals("SUM('49612.xls'!BOB+'49612.xls'!JIM)", e1.getCellFormula()); - - // Problem 3 - fixed and transfered - wb.close(); - } - - @Test - public void testFormulaRecordAggregate_1() throws Exception { - // fails at formula "=MEHRFACH.OPERATIONEN(E$3;$B$5;$D4)" - Workbook wb = HSSFTestDataSamples.openSampleWorkbook("44958_1.xls"); - try { - for(int i = 0;i < wb.getNumberOfSheets();i++) { - Sheet sheet = wb.getSheetAt(i); - assertNotNull(wb.getSheet(sheet.getSheetName())); - sheet.groupColumn((short) 4, (short) 5); - sheet.setColumnGroupCollapsed(4, true); - sheet.setColumnGroupCollapsed(4, false); - - for(Row row : sheet) { - for(Cell cell : row) { - try { - cell.toString(); - } catch (Exception e) { - throw new Exception("While handling: " + sheet.getSheetName() + "/" + row.getRowNum() + "/" + cell.getColumnIndex(), e); - } - } - } - } - } finally { - wb.close(); - } - } - - @Test - public void testFormulaRecordAggregate() throws Exception { - // fails at formula "=MEHRFACH.OPERATIONEN(E$3;$B$5;$D4)" - Workbook wb = HSSFTestDataSamples.openSampleWorkbook("44958.xls"); - try { - for(int i = 0;i < wb.getNumberOfSheets();i++) { - Sheet sheet = wb.getSheetAt(i); - assertNotNull(wb.getSheet(sheet.getSheetName())); - sheet.groupColumn((short) 4, (short) 5); - sheet.setColumnGroupCollapsed(4, true); - sheet.setColumnGroupCollapsed(4, false); - - for(Row row : sheet) { - for(Cell cell : row) { - try { - cell.toString(); - } catch (Exception e) { - throw new Exception("While handling: " + sheet.getSheetName() + "/" + row.getRowNum() + "/" + cell.getColumnIndex(), e); - } - } - } - } - } finally { - wb.close(); - } - } - - @Test - public void testBug57074() throws IOException { - Workbook wb = HSSFTestDataSamples.openSampleWorkbook("57074.xls"); - Sheet sheet = wb.getSheet("Sheet1"); - Row row = sheet.getRow(0); - Cell cell = row.getCell(0); - - HSSFColor bgColor = (HSSFColor) cell.getCellStyle().getFillBackgroundColorColor(); - String bgColorStr = bgColor.getTriplet()[0]+", "+bgColor.getTriplet()[1]+", "+bgColor.getTriplet()[2]; - //System.out.println(bgColorStr); - assertEquals("215, 228, 188", bgColorStr); - - HSSFColor fontColor = (HSSFColor) cell.getCellStyle().getFillForegroundColorColor(); - String fontColorStr = fontColor.getTriplet()[0]+", "+fontColor.getTriplet()[1]+", "+fontColor.getTriplet()[2]; - //System.out.println(fontColorStr); - assertEquals("0, 128, 128", fontColorStr); - wb.close(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestUnicodeWorkbook.java b/src/testcases/org/apache/poi/hssf/usermodel/TestUnicodeWorkbook.java deleted file mode 100644 index b0efff9c6..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestUnicodeWorkbook.java +++ /dev/null @@ -1,52 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import junit.framework.TestCase; -import org.apache.poi.hssf.HSSFTestDataSamples; - -public final class TestUnicodeWorkbook extends TestCase { - - /** - * Tests Bug38230 - * That a Umlat is written and then read back. - * It should have been written as a compressed unicode. - */ - public void testUmlatReadWrite() { - HSSFWorkbook wb = new HSSFWorkbook(); - - //Create a unicode sheet name (euro symbol) - HSSFSheet s = wb.createSheet("test"); - - HSSFRow r = s.createRow(0); - HSSFCell c = r.createCell(1); - c.setCellValue(new HSSFRichTextString("\u00e4")); - - //Confirm that the sring will be compressed - assertEquals(c.getRichStringCellValue().getUnicodeString().getOptionFlags(), 0); - - wb = HSSFTestDataSamples.writeOutAndReadBack(wb); - - //Test the sheetname - s = wb.getSheet("test"); - assertNotNull(s); - - c = r.getCell(1); - assertEquals(c.getRichStringCellValue().getString(), "\u00e4"); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestWorkbook.java b/src/testcases/org/apache/poi/hssf/usermodel/TestWorkbook.java deleted file mode 100644 index 347fb219f..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestWorkbook.java +++ /dev/null @@ -1,682 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.IOException; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.model.InternalWorkbook; -import org.apache.poi.hssf.record.BackupRecord; -import org.apache.poi.hssf.record.LabelSSTRecord; -import org.apache.poi.hssf.record.Record; -import org.apache.poi.hssf.record.aggregates.RecordAggregate.RecordVisitor; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.Name; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.CellRangeAddress; -import org.junit.Test; - -/** - * Class to test Workbook functionality - */ -public final class TestWorkbook { - private static final String LAST_NAME_KEY = "lastName"; - private static final String FIRST_NAME_KEY = "firstName"; - private static final String SSN_KEY = "ssn"; - private static final String REPLACE_ME = "replaceMe"; - private static final String REPLACED = "replaced"; - private static final String DO_NOT_REPLACE = "doNotReplace"; - private static final String EMPLOYEE_INFORMATION = "Employee Info"; - private static final String LAST_NAME_VALUE = "Bush"; - private static final String FIRST_NAME_VALUE = "George"; - private static final String SSN_VALUE = "555555555"; - private final SanityChecker sanityChecker = new SanityChecker(); - - - private static HSSFWorkbook openSample(String sampleFileName) { - return HSSFTestDataSamples.openSampleWorkbook(sampleFileName); - } - - /** - * TEST NAME: Test Write Sheet Simple

    - * OBJECTIVE: Test that HSSF can create a simple spreadsheet with numeric and string values.

    - * SUCCESS: HSSF creates a sheet. Filesize matches a known good. HSSFSheet objects - * Last row, first row is tested against the correct values (99,0).

    - * FAILURE: HSSF does not create a sheet or excepts. Filesize does not match the known good. - * HSSFSheet last row or first row is incorrect.

    - */ - @Test - public void testWriteSheetSimple() throws IOException { - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet s = wb1.createSheet(); - - for (int rownum = 0; rownum < 100; rownum++) { - HSSFRow r = s.createRow(rownum); - - for (int cellnum = 0; cellnum < 50; cellnum += 2) { - HSSFCell c = r.createCell(cellnum); - c.setCellValue(rownum * 10000 + cellnum - + ((( double ) rownum / 1000) - + (( double ) cellnum / 10000))); - c = r.createCell(cellnum + 1); - c.setCellValue(new HSSFRichTextString("TEST")); - } - } - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - - sanityChecker.checkHSSFWorkbook(wb1); - assertEquals("LAST ROW == 99", 99, s.getLastRowNum()); - assertEquals("FIRST ROW == 0", 0, s.getFirstRowNum()); - - sanityChecker.checkHSSFWorkbook(wb2); - s = wb2.getSheetAt(0); - assertEquals("LAST ROW == 99", 99, s.getLastRowNum()); - assertEquals("FIRST ROW == 0", 0, s.getFirstRowNum()); - wb2.close(); - wb1.close(); - } - - /** - * TEST NAME: Test Write/Modify Sheet Simple

    - * OBJECTIVE: Test that HSSF can create a simple spreadsheet with numeric and string values, - * remove some rows, yet still have a valid file/data.

    - * SUCCESS: HSSF creates a sheet. Filesize matches a known good. HSSFSheet objects - * Last row, first row is tested against the correct values (74,25).

    - * FAILURE: HSSF does not create a sheet or excepts. Filesize does not match the known good. - * HSSFSheet last row or first row is incorrect.

    - */ - @Test - public void testWriteModifySheetSimple() throws IOException { - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet s = wb1.createSheet(); - - for (int rownum = 0; rownum < 100; rownum++) { - HSSFRow r = s.createRow(rownum); - - for (int cellnum = 0; cellnum < 50; cellnum += 2) { - HSSFCell c = r.createCell(cellnum); - c.setCellValue(rownum * 10000 + cellnum - + ((( double ) rownum / 1000) - + (( double ) cellnum / 10000))); - c = r.createCell(cellnum + 1); - c.setCellValue(new HSSFRichTextString("TEST")); - } - } - for (int rownum = 0; rownum < 25; rownum++) { - HSSFRow r = s.getRow(rownum); - s.removeRow(r); - } - for (int rownum = 75; rownum < 100; rownum++) { - HSSFRow r = s.getRow(rownum); - s.removeRow(r); - } - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - - sanityChecker.checkHSSFWorkbook(wb1); - assertEquals("LAST ROW == 74", 74, s.getLastRowNum()); - assertEquals("FIRST ROW == 25", 25, s.getFirstRowNum()); - - sanityChecker.checkHSSFWorkbook(wb2); - s = wb2.getSheetAt(0); - assertEquals("LAST ROW == 74", 74, s.getLastRowNum()); - assertEquals("FIRST ROW == 25", 25, s.getFirstRowNum()); - - wb2.close(); - wb1.close(); - } - - /** - * TEST NAME: Test Read Simple

    - * OBJECTIVE: Test that HSSF can read a simple spreadsheet (Simple.xls).

    - * SUCCESS: HSSF reads the sheet. Matches values in their particular positions.

    - * FAILURE: HSSF does not read a sheet or excepts. HSSF cannot identify values - * in the sheet in their known positions.

    - */ - @Test - public void testReadSimple() throws IOException { - HSSFWorkbook wb = openSample("Simple.xls"); - HSSFSheet sheet = wb.getSheetAt(0); - - HSSFCell cell = sheet.getRow(0).getCell(0); - assertEquals(REPLACE_ME, cell .getRichStringCellValue().getString()); - wb.close(); - } - - /** - * TEST NAME: Test Read Simple w/ Data Format

    - * OBJECTIVE: Test that HSSF can read a simple spreadsheet (SimpleWithDataFormat.xls).

    - * SUCCESS: HSSF reads the sheet. Matches values in their particular positions and format is correct

    - * FAILURE: HSSF does not read a sheet or excepts. HSSF cannot identify values - * in the sheet in their known positions.

    - */ - @Test - public void testReadSimpleWithDataFormat() throws IOException { - HSSFWorkbook wb = openSample("SimpleWithDataFormat.xls"); - HSSFSheet sheet = wb.getSheetAt(0); - HSSFDataFormat format = wb.createDataFormat(); - HSSFCell cell = sheet.getRow(0).getCell(0); - - assertEquals(1.25,cell.getNumericCellValue(), 1e-10); - - assertEquals(format.getFormat(cell.getCellStyle().getDataFormat()), "0.0"); - - wb.close(); - } - -/** - * TEST NAME: Test Read/Write Simple w/ Data Format

    - * OBJECTIVE: Test that HSSF can write a sheet with custom data formats and then read it and get the proper formats.

    - * SUCCESS: HSSF reads the sheet. Matches values in their particular positions and format is correct

    - * FAILURE: HSSF does not read a sheet or excepts. HSSF cannot identify values - * in the sheet in their known positions.

    - */ - @Test - public void testWriteDataFormat() throws IOException { - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet s1 = wb1.createSheet(); - HSSFDataFormat format = wb1.createDataFormat(); - HSSFCellStyle cs = wb1.createCellStyle(); - - short df = format.getFormat("0.0"); - cs.setDataFormat(df); - - HSSFCell c1 = s1.createRow(0).createCell(0); - c1.setCellStyle(cs); - c1.setCellValue(1.25); - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - - HSSFSheet s2 = wb2.getSheetAt(0); - HSSFCell c2 = s2.getRow(0).getCell(0); - format = wb2.createDataFormat(); - - assertEquals(1.25, c2.getNumericCellValue(), 1e-10); - - assertEquals(format.getFormat(df), "0.0"); - - assertEquals(format, wb2.createDataFormat()); - - wb2.close(); - wb1.close(); - } - - /** - * TEST NAME: Test Read Employee Simple

    - * OBJECTIVE: Test that HSSF can read a simple spreadsheet (Employee.xls).

    - * SUCCESS: HSSF reads the sheet. Matches values in their particular positions.

    - * FAILURE: HSSF does not read a sheet or excepts. HSSF cannot identify values - * in the sheet in their known positions.

    - * - */ - @Test - public void testReadEmployeeSimple() throws IOException { - HSSFWorkbook wb = openSample("Employee.xls"); - HSSFSheet sheet = wb.getSheetAt(0); - - assertEquals(EMPLOYEE_INFORMATION, sheet.getRow(1).getCell(1).getRichStringCellValue().getString()); - assertEquals(LAST_NAME_KEY, sheet.getRow(3).getCell(2).getRichStringCellValue().getString()); - assertEquals(FIRST_NAME_KEY, sheet.getRow(4).getCell(2).getRichStringCellValue().getString()); - assertEquals(SSN_KEY, sheet.getRow(5).getCell(2).getRichStringCellValue().getString()); - - wb.close(); - } - - /** - * TEST NAME: Test Modify Sheet Simple

    - * OBJECTIVE: Test that HSSF can read a simple spreadsheet with a string value and replace - * it with another string value.

    - * SUCCESS: HSSF reads a sheet. HSSF replaces the cell value with another cell value. HSSF - * writes the sheet out to another file. HSSF reads the result and ensures the value - * has been properly replaced.

    - * FAILURE: HSSF does not read a sheet or excepts. HSSF does not write the sheet or excepts. - * HSSF does not re-read the sheet or excepts. Upon re-reading the sheet the value - * is incorrect or has not been replaced.

    - */ - @Test - public void testModifySimple() throws IOException { - HSSFWorkbook wb1 = openSample("Simple.xls"); - HSSFSheet sheet = wb1.getSheetAt(0); - HSSFCell cell = sheet.getRow(0).getCell(0); - - cell.setCellValue(new HSSFRichTextString(REPLACED)); - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - sheet = wb2.getSheetAt(0); - cell = sheet.getRow(0).getCell(0); - assertEquals(REPLACED, cell.getRichStringCellValue().getString()); - - wb2.close(); - wb1.close(); - } - - /** - * TEST NAME: Test Modify Sheet Simple With Skipped cells

    - * OBJECTIVE: Test that HSSF can read a simple spreadsheet with string values and replace - * them with other string values while not replacing other cells.

    - * SUCCESS: HSSF reads a sheet. HSSF replaces the cell value with another cell value. HSSF - * writes the sheet out to another file. HSSF reads the result and ensures the value - * has been properly replaced and unreplaced values are still unreplaced.

    - * FAILURE: HSSF does not read a sheet or excepts. HSSF does not write the sheet or excepts. - * HSSF does not re-read the sheet or excepts. Upon re-reading the sheet the value - * is incorrect or has not been replaced or the incorrect cell has its value replaced - * or is incorrect.

    - */ - @Test - public void testModifySimpleWithSkip() throws IOException { - HSSFWorkbook wb1 = openSample("SimpleWithSkip.xls"); - HSSFSheet sheet = wb1.getSheetAt(0); - HSSFCell cell = sheet.getRow(0).getCell(1); - - cell.setCellValue(new HSSFRichTextString(REPLACED)); - cell = sheet.getRow(1).getCell(0); - cell.setCellValue(new HSSFRichTextString(REPLACED)); - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - - sheet = wb2.getSheetAt(0); - cell = sheet.getRow(0).getCell(1); - assertEquals(REPLACED, cell.getRichStringCellValue().getString()); - cell = sheet.getRow(0).getCell(0); - assertEquals(DO_NOT_REPLACE, cell.getRichStringCellValue().getString()); - cell = sheet.getRow(1).getCell(0); - assertEquals(REPLACED, cell.getRichStringCellValue().getString()); - cell = sheet.getRow(1).getCell(1); - assertEquals(DO_NOT_REPLACE, cell.getRichStringCellValue().getString()); - - wb2.close(); - wb1.close(); - } - - /** - * TEST NAME: Test Modify Sheet With Styling

    - * OBJECTIVE: Test that HSSF can read a simple spreadsheet with string values and replace - * them with other string values despite any styling. In this release of HSSF styling will - * probably be lost and is NOT tested.

    - * SUCCESS: HSSF reads a sheet. HSSF replaces the cell values with other cell values. HSSF - * writes the sheet out to another file. HSSF reads the result and ensures the value - * has been properly replaced.

    - * FAILURE: HSSF does not read a sheet or excepts. HSSF does not write the sheet or excepts. - * HSSF does not re-read the sheet or excepts. Upon re-reading the sheet the value - * is incorrect or has not been replaced.

    - */ - @Test - public void testModifySimpleWithStyling() throws IOException { - HSSFWorkbook wb1 = openSample("SimpleWithStyling.xls"); - HSSFSheet sheet = wb1.getSheetAt(0); - - for (int k = 0; k < 4; k++) { - HSSFCell cell = sheet.getRow(k).getCell(0); - cell.setCellValue(new HSSFRichTextString(REPLACED)); - } - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - sheet = wb2.getSheetAt(0); - for (int k = 0; k < 4; k++) { - HSSFCell cell = sheet.getRow(k).getCell(0); - assertEquals(REPLACED, cell.getRichStringCellValue().getString()); - } - - wb2.close(); - wb1.close(); - } - - /** - * TEST NAME: Test Modify Employee Sheet

    - * OBJECTIVE: Test that HSSF can read a simple spreadsheet with string values and replace - * them with other string values despite any styling. In this release of HSSF styling will - * probably be lost and is NOT tested.

    - * SUCCESS: HSSF reads a sheet. HSSF replaces the cell values with other cell values. HSSF - * writes the sheet out to another file. HSSF reads the result and ensures the value - * has been properly replaced.

    - * FAILURE: HSSF does not read a sheet or excepts. HSSF does not write the sheet or excepts. - * HSSF does not re-read the sheet or excepts. Upon re-reading the sheet the value - * is incorrect or has not been replaced.

    - */ - @Test - public void testModifyEmployee() throws IOException { - HSSFWorkbook wb1 = openSample("Employee.xls"); - HSSFSheet sheet = wb1.getSheetAt(0); - HSSFCell cell = sheet.getRow(3).getCell(2); - - cell.setCellValue(new HSSFRichTextString(LAST_NAME_VALUE)); - cell = sheet.getRow(4).getCell(2); - cell.setCellValue(new HSSFRichTextString(FIRST_NAME_VALUE)); - cell = sheet.getRow(5).getCell(2); - cell.setCellValue(new HSSFRichTextString(SSN_VALUE)); - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - sheet = wb2.getSheetAt(0); - assertEquals(EMPLOYEE_INFORMATION, sheet.getRow(1).getCell(1).getRichStringCellValue().getString()); - assertEquals(LAST_NAME_VALUE, sheet.getRow(3).getCell(2).getRichStringCellValue().getString()); - assertEquals(FIRST_NAME_VALUE, sheet.getRow(4).getCell(2).getRichStringCellValue().getString()); - assertEquals(SSN_VALUE, sheet.getRow(5).getCell(2).getRichStringCellValue().getString()); - - wb2.close(); - wb1.close(); - } - - /** - * TEST NAME: Test Read Sheet with an RK number

    - * OBJECTIVE: Test that HSSF can read a simple spreadsheet with and RKRecord and correctly - * identify the cell as numeric and convert it to a NumberRecord.

    - * SUCCESS: HSSF reads a sheet. HSSF returns that the cell is a numeric type cell.

    - * FAILURE: HSSF does not read a sheet or excepts. HSSF incorrectly identifies the cell

    - */ - @Test - public void testReadSheetWithRK() throws IOException { - HSSFWorkbook wb = openSample("rk.xls"); - HSSFSheet s = wb.getSheetAt(0); - HSSFCell c = s.getRow(0).getCell(0); - - assertEquals(CellType.NUMERIC, c.getCellTypeEnum()); - - wb.close(); - } - - /** - * TEST NAME: Test Write/Modify Sheet Simple

    - * OBJECTIVE: Test that HSSF can create a simple spreadsheet with numeric and string values, - * remove some rows, yet still have a valid file/data.

    - * SUCCESS: HSSF creates a sheet. Filesize matches a known good. HSSFSheet objects - * Last row, first row is tested against the correct values (74,25).

    - * FAILURE: HSSF does not create a sheet or excepts. Filesize does not match the known good. - * HSSFSheet last row or first row is incorrect.

    - */ - @Test - public void testWriteModifySheetMerged() throws IOException { - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet s = wb1.createSheet(); - - for (int rownum = 0; rownum < 100; rownum++) { - HSSFRow r = s.createRow(rownum); - - for (int cellnum = 0; cellnum < 50; cellnum += 2) { - HSSFCell c = r.createCell(cellnum); - c.setCellValue(rownum * 10000 + cellnum - + ((( double ) rownum / 1000) - + (( double ) cellnum / 10000))); - c = r.createCell(cellnum + 1); - c.setCellValue(new HSSFRichTextString("TEST")); - } - } - s.addMergedRegion(new CellRangeAddress(0, 10, 0, 10)); - s.addMergedRegion(new CellRangeAddress(30, 40, 5, 15)); - sanityChecker.checkHSSFWorkbook(wb1); - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - - s = wb2.getSheetAt(0); - CellRangeAddress r1 = s.getMergedRegion(0); - CellRangeAddress r2 = s.getMergedRegion(1); - - confirmRegion(new CellRangeAddress(0, 10, 0, 10), r1); - confirmRegion(new CellRangeAddress(30, 40,5, 15), r2); - - wb2.close(); - wb1.close(); - } - - private static void confirmRegion(CellRangeAddress ra, CellRangeAddress rb) { - assertEquals(ra.getFirstRow(), rb.getFirstRow()); - assertEquals(ra.getLastRow(), rb.getLastRow()); - assertEquals(ra.getFirstColumn(), rb.getFirstColumn()); - assertEquals(ra.getLastColumn(), rb.getLastColumn()); - } - - /** - * Test the backup field gets set as expected. - * @throws IOException - */ - @Test - public void testBackupRecord() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - wb.createSheet(); - InternalWorkbook workbook = wb.getWorkbook(); - BackupRecord record = workbook.getBackupRecord(); - - assertEquals(0, record.getBackup()); - assertFalse(wb.getBackupFlag()); - wb.setBackupFlag(true); - assertEquals(1, record.getBackup()); - assertTrue(wb.getBackupFlag()); - wb.setBackupFlag(false); - assertEquals(0, record.getBackup()); - assertFalse(wb.getBackupFlag()); - - wb.close(); - } - - private static final class RecordCounter implements RecordVisitor { - private int _count; - - public RecordCounter() { - _count=0; - } - public int getCount() { - return _count; - } - @Override - public void visitRecord(Record r) { - if (r instanceof LabelSSTRecord) { - _count++; - } - } - } - - /** - * This tests is for bug [ #506658 ] Repeating output. - * - * We need to make sure only one LabelSSTRecord is produced. - * @throws IOException - */ - @Test - public void testRepeatingBug() throws IOException { - HSSFWorkbook workbook = new HSSFWorkbook(); - HSSFSheet sheet = workbook.createSheet("Design Variants"); - HSSFRow row = sheet.createRow(2); - HSSFCell cell = row.createCell(1); - - cell.setCellValue(new HSSFRichTextString("Class")); - cell = row.createCell(2); - - RecordCounter rc = new RecordCounter(); - sheet.getSheet().visitContainedRecords(rc, 0); - assertEquals(1, rc.getCount()); - - workbook.close(); - } - - - /** - * Test for row indexes beyond {@link Short#MAX_VALUE}. - * This bug was first fixed in svn r352609. - */ - @Test - public void testRowIndexesBeyond32768() throws IOException { - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet sheet = wb1.createSheet(); - HSSFRow row; - HSSFCell cell; - for (int i = 32700; i < 32771; i++) { - row = sheet.createRow(i); - cell = row.createCell(0); - cell.setCellValue(i); - } - sanityChecker.checkHSSFWorkbook(wb1); - assertEquals("LAST ROW == 32770", 32770, sheet.getLastRowNum()); - cell = sheet.getRow(32770).getCell(0); - double lastVal = cell.getNumericCellValue(); - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - HSSFSheet s = wb2.getSheetAt(0); - row = s.getRow(32770); - cell = row.getCell(0); - assertEquals("Value from last row == 32770", lastVal, cell.getNumericCellValue(), 0); - assertEquals("LAST ROW == 32770", 32770, s.getLastRowNum()); - - wb2.close(); - wb1.close(); - } - - /** - * Generate a file to verify repeating rows and cols made it - */ - @Test - public void testRepeatingColsRows() throws IOException { - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet sheet = wb1.createSheet("Test Print Titles"); - - HSSFRow row = sheet.createRow(0); - - HSSFCell cell = row.createCell(1); - cell.setCellValue(new HSSFRichTextString("hi")); - - CellRangeAddress cra = CellRangeAddress.valueOf("A1:B1"); - sheet.setRepeatingColumns(cra); - sheet.setRepeatingRows(cra); - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - sheet = wb2.getSheetAt(0); - assertEquals("A:B", sheet.getRepeatingColumns().formatAsString()); - assertEquals("1:1", sheet.getRepeatingRows().formatAsString()); - - wb2.close(); - wb1.close(); - } - - /** - * Test setRepeatingRowsAndColumns when startRow and startColumn are -1. - */ - @Test - public void testRepeatingColsRowsMinusOne() throws IOException - { - HSSFWorkbook workbook = new HSSFWorkbook(); - HSSFSheet sheet = workbook.createSheet("Test Print Titles"); - - HSSFRow row = sheet.createRow(0); - - HSSFCell cell = row.createCell(1); - cell.setCellValue(new HSSFRichTextString("hi")); - CellRangeAddress cra = new CellRangeAddress(-1, 1, -1, 1); - try { - sheet.setRepeatingColumns(cra); - fail("invalid start index is ignored"); - } catch (IllegalArgumentException e) {} - - try { - sheet.setRepeatingRows(cra); - fail("invalid start index is ignored"); - } catch (IllegalArgumentException e) {} - - sheet.setRepeatingColumns(null); - sheet.setRepeatingRows(null); - - HSSFTestDataSamples.writeOutAndReadBack(workbook).close(); - - workbook.close(); - } - - @Test - public void testAddMergedRegionWithRegion() throws IOException { - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet s = wb1.createSheet(); - - for (int rownum = 0; rownum < 100; rownum++) { - HSSFRow r = s.createRow(rownum); - - for (int cellnum = 0; cellnum < 50; cellnum += 2) { - HSSFCell c = r.createCell(cellnum); - c.setCellValue(rownum * 10000 + cellnum - + ((( double ) rownum / 1000) - + (( double ) cellnum / 10000))); - c = r.createCell(cellnum + 1); - c.setCellValue(new HSSFRichTextString("TEST")); - } - } - s.addMergedRegion(new CellRangeAddress(0, 10, 0, 10)); - s.addMergedRegion(new CellRangeAddress(30, 40, 5, 15)); - sanityChecker.checkHSSFWorkbook(wb1); - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - - s = wb2.getSheetAt(0); - CellRangeAddress r1 = s.getMergedRegion(0); - CellRangeAddress r2 = s.getMergedRegion(1); - - confirmRegion(new CellRangeAddress(0, 10, 0, 10), r1); - confirmRegion(new CellRangeAddress(30, 40,5, 15), r2); - - wb2.close(); - wb1.close(); - } - - @Test - public void testBug58085RemoveSheetWithNames() throws Exception { - HSSFWorkbook wb1 = new HSSFWorkbook(); - Sheet sheet1 = wb1.createSheet("sheet1"); - Sheet sheet2 = wb1.createSheet("sheet2"); - Sheet sheet3 = wb1.createSheet("sheet3"); - - sheet1.createRow(0).createCell((short) 0).setCellValue("val1"); - sheet2.createRow(0).createCell((short) 0).setCellValue("val2"); - sheet3.createRow(0).createCell((short) 0).setCellValue("val3"); - - Name namedCell1 = wb1.createName(); - namedCell1.setNameName("name1"); - String reference1 = "sheet1!$A$1"; - namedCell1.setRefersToFormula(reference1); - - Name namedCell2= wb1.createName(); - namedCell2.setNameName("name2"); - String reference2 = "sheet2!$A$1"; - namedCell2.setRefersToFormula(reference2); - - Name namedCell3 = wb1.createName(); - namedCell3.setNameName("name3"); - String reference3 = "sheet3!$A$1"; - namedCell3.setRefersToFormula(reference3); - - Workbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - - Name nameCell = wb2.getName("name1"); - assertEquals("sheet1!$A$1", nameCell.getRefersToFormula()); - nameCell = wb2.getName("name2"); - assertEquals("sheet2!$A$1", nameCell.getRefersToFormula()); - nameCell = wb2.getName("name3"); - assertEquals("sheet3!$A$1", nameCell.getRefersToFormula()); - - wb2.removeSheetAt(wb2.getSheetIndex("sheet1")); - - nameCell = wb2.getName("name1"); - assertEquals("#REF!$A$1", nameCell.getRefersToFormula()); - nameCell = wb2.getName("name2"); - assertEquals("sheet2!$A$1", nameCell.getRefersToFormula()); - nameCell = wb2.getName("name3"); - assertEquals("sheet3!$A$1", nameCell.getRefersToFormula()); - - wb2.close(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/util/AllHSSFUtilTests.java b/src/testcases/org/apache/poi/hssf/util/AllHSSFUtilTests.java deleted file mode 100644 index 7e71fb2de..000000000 --- a/src/testcases/org/apache/poi/hssf/util/AllHSSFUtilTests.java +++ /dev/null @@ -1,34 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.util; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -/** - * Collects all tests for org.apache.poi.hssf.util. - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestAreaReference.class, - TestCellReference.class, - TestHSSFColor.class, - TestRKUtil.class -}) -public class AllHSSFUtilTests { -} diff --git a/src/testcases/org/apache/poi/hssf/util/TestAreaReference.java b/src/testcases/org/apache/poi/hssf/util/TestAreaReference.java deleted file mode 100644 index 4bc3d0741..000000000 --- a/src/testcases/org/apache/poi/hssf/util/TestAreaReference.java +++ /dev/null @@ -1,291 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.util; - -import java.io.InputStream; - -import junit.framework.TestCase; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.model.HSSFFormulaParser; -import org.apache.poi.hssf.model.InternalWorkbook; -import org.apache.poi.hssf.record.NameRecord; -import org.apache.poi.ss.formula.ptg.Area3DPtg; -import org.apache.poi.ss.formula.ptg.MemFuncPtg; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.apache.poi.ss.formula.ptg.UnionPtg; -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFEvaluationWorkbook; -import org.apache.poi.hssf.usermodel.HSSFName; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.hssf.usermodel.TestHSSFWorkbook; -import org.apache.poi.ss.util.AreaReference; -import org.apache.poi.ss.util.CellReference; -/** - * - */ -public final class TestAreaReference extends TestCase { - - public void testAreaRef1() { - AreaReference ar = new AreaReference("$A$1:$B$2"); - assertFalse("Two cells expected", ar.isSingleCell()); - CellReference cf = ar.getFirstCell(); - assertTrue("row is 4",cf.getRow()==0); - assertTrue("col is 1",cf.getCol()==0); - assertTrue("row is abs",cf.isRowAbsolute()); - assertTrue("col is abs",cf.isColAbsolute()); - assertTrue("string is $A$1",cf.formatAsString().equals("$A$1")); - - cf = ar.getLastCell(); - assertTrue("row is 4",cf.getRow()==1); - assertTrue("col is 1",cf.getCol()==1); - assertTrue("row is abs",cf.isRowAbsolute()); - assertTrue("col is abs",cf.isColAbsolute()); - assertTrue("string is $B$2",cf.formatAsString().equals("$B$2")); - - CellReference[] refs = ar.getAllReferencedCells(); - assertEquals(4, refs.length); - - assertEquals(0, refs[0].getRow()); - assertEquals(0, refs[0].getCol()); - assertNull(refs[0].getSheetName()); - - assertEquals(0, refs[1].getRow()); - assertEquals(1, refs[1].getCol()); - assertNull(refs[1].getSheetName()); - - assertEquals(1, refs[2].getRow()); - assertEquals(0, refs[2].getCol()); - assertNull(refs[2].getSheetName()); - - assertEquals(1, refs[3].getRow()); - assertEquals(1, refs[3].getCol()); - assertNull(refs[3].getSheetName()); - } - - /** - * References failed when sheet names were being used - * Reported by Arne.Clauss@gedas.de - */ - public void testReferenceWithSheet() { - AreaReference ar; - - ar = new AreaReference("Tabelle1!B5:B5"); - assertTrue(ar.isSingleCell()); - TestCellReference.confirmCell(ar.getFirstCell(), "Tabelle1", 4, 1, false, false, "Tabelle1!B5"); - - assertEquals(1, ar.getAllReferencedCells().length); - - - ar = new AreaReference("Tabelle1!$B$5:$B$7"); - assertFalse(ar.isSingleCell()); - - TestCellReference.confirmCell(ar.getFirstCell(), "Tabelle1", 4, 1, true, true, "Tabelle1!$B$5"); - TestCellReference.confirmCell(ar.getLastCell(), "Tabelle1", 6, 1, true, true, "Tabelle1!$B$7"); - - // And all that make it up - CellReference[] allCells = ar.getAllReferencedCells(); - assertEquals(3, allCells.length); - TestCellReference.confirmCell(allCells[0], "Tabelle1", 4, 1, true, true, "Tabelle1!$B$5"); - TestCellReference.confirmCell(allCells[1], "Tabelle1", 5, 1, true, true, "Tabelle1!$B$6"); - TestCellReference.confirmCell(allCells[2], "Tabelle1", 6, 1, true, true, "Tabelle1!$B$7"); - } - - public void testContiguousReferences() { - String refSimple = "$C$10:$C$10"; - String ref2D = "$C$10:$D$11"; - String refDCSimple = "$C$10:$C$10,$D$12:$D$12,$E$14:$E$14"; - String refDC2D = "$C$10:$C$11,$D$12:$D$12,$E$14:$E$20"; - String refDC3D = "Tabelle1!$C$10:$C$14,Tabelle1!$D$10:$D$12"; - - // Check that we detect as contiguous properly - assertTrue(AreaReference.isContiguous(refSimple)); - assertTrue(AreaReference.isContiguous(ref2D)); - assertFalse(AreaReference.isContiguous(refDCSimple)); - assertFalse(AreaReference.isContiguous(refDC2D)); - assertFalse(AreaReference.isContiguous(refDC3D)); - - // Check we can only create contiguous entries - new AreaReference(refSimple); - new AreaReference(ref2D); - try { - new AreaReference(refDCSimple); - fail(); - } catch(IllegalArgumentException e) { - // expected during successful test - } - try { - new AreaReference(refDC2D); - fail(); - } catch(IllegalArgumentException e) { - // expected during successful test - } - try { - new AreaReference(refDC3D); - fail(); - } catch(IllegalArgumentException e) { - // expected during successful test - } - - // Test that we split as expected - AreaReference[] refs; - - refs = AreaReference.generateContiguous(refSimple); - assertEquals(1, refs.length); - assertTrue(refs[0].isSingleCell()); - assertEquals("$C$10", refs[0].formatAsString()); - - refs = AreaReference.generateContiguous(ref2D); - assertEquals(1, refs.length); - assertFalse(refs[0].isSingleCell()); - assertEquals("$C$10:$D$11", refs[0].formatAsString()); - - refs = AreaReference.generateContiguous(refDCSimple); - assertEquals(3, refs.length); - assertTrue(refs[0].isSingleCell()); - assertTrue(refs[1].isSingleCell()); - assertTrue(refs[2].isSingleCell()); - assertEquals("$C$10", refs[0].formatAsString()); - assertEquals("$D$12", refs[1].formatAsString()); - assertEquals("$E$14", refs[2].formatAsString()); - - refs = AreaReference.generateContiguous(refDC2D); - assertEquals(3, refs.length); - assertFalse(refs[0].isSingleCell()); - assertTrue(refs[1].isSingleCell()); - assertFalse(refs[2].isSingleCell()); - assertEquals("$C$10:$C$11", refs[0].formatAsString()); - assertEquals("$D$12", refs[1].formatAsString()); - assertEquals("$E$14:$E$20", refs[2].formatAsString()); - - refs = AreaReference.generateContiguous(refDC3D); - assertEquals(2, refs.length); - assertFalse(refs[0].isSingleCell()); - assertFalse(refs[0].isSingleCell()); - assertEquals("Tabelle1!$C$10:$C$14", refs[0].formatAsString()); - assertEquals("Tabelle1!$D$10:$D$12", refs[1].formatAsString()); - assertEquals("Tabelle1", refs[0].getFirstCell().getSheetName()); - assertEquals("Tabelle1", refs[0].getLastCell().getSheetName()); - assertEquals("Tabelle1", refs[1].getFirstCell().getSheetName()); - assertEquals("Tabelle1", refs[1].getLastCell().getSheetName()); - } - - public void testDiscontinousReference() throws Exception { - InputStream is = HSSFTestDataSamples.openSampleFileStream("44167.xls"); - HSSFWorkbook wb = new HSSFWorkbook(is); - InternalWorkbook workbook = TestHSSFWorkbook.getInternalWorkbook(wb); - HSSFEvaluationWorkbook eb = HSSFEvaluationWorkbook.create(wb); - - assertEquals(1, wb.getNumberOfNames()); - String sheetName = "Tabelle1"; - String rawRefA = "$C$10:$C$14"; - String rawRefB = "$C$16:$C$18"; - String refA = sheetName + "!" + rawRefA; - String refB = sheetName + "!" + rawRefB; - String ref = refA + "," + refB; - - // Check the low level record - NameRecord nr = workbook.getNameRecord(0); - assertNotNull(nr); - assertEquals("test", nr.getNameText()); - - Ptg[] def =nr.getNameDefinition(); - assertEquals(4, def.length); - - MemFuncPtg ptgA = (MemFuncPtg)def[0]; - Area3DPtg ptgB = (Area3DPtg)def[1]; - Area3DPtg ptgC = (Area3DPtg)def[2]; - UnionPtg ptgD = (UnionPtg)def[3]; - assertEquals("", ptgA.toFormulaString()); - assertEquals(refA, ptgB.toFormulaString(eb)); - assertEquals(refB, ptgC.toFormulaString(eb)); - assertEquals(",", ptgD.toFormulaString()); - - assertEquals(ref, HSSFFormulaParser.toFormulaString(wb, nr.getNameDefinition())); - - // Check the high level definition - int idx = wb.getNameIndex("test"); - assertEquals(0, idx); - HSSFName aNamedCell = wb.getNameAt(idx); - - // Should have 2 references - assertEquals(ref, aNamedCell.getRefersToFormula()); - - // Check the parsing of the reference into cells - assertFalse(AreaReference.isContiguous(aNamedCell.getRefersToFormula())); - AreaReference[] arefs = AreaReference.generateContiguous(aNamedCell.getRefersToFormula()); - assertEquals(2, arefs.length); - assertEquals(refA, arefs[0].formatAsString()); - assertEquals(refB, arefs[1].formatAsString()); - - for (AreaReference ar : arefs) { - confirmResolveCellRef(wb, ar.getFirstCell()); - confirmResolveCellRef(wb, ar.getLastCell()); - } - } - - private static void confirmResolveCellRef(HSSFWorkbook wb, CellReference cref) { - HSSFSheet s = wb.getSheet(cref.getSheetName()); - HSSFRow r = s.getRow(cref.getRow()); - HSSFCell c = r.getCell((int)cref.getCol()); - assertNotNull(c); - } - - public void testSpecialSheetNames() { - AreaReference ar; - ar = new AreaReference("'Sheet A'!A1:A1"); - confirmAreaSheetName(ar, "Sheet A", "'Sheet A'!A1"); - - ar = new AreaReference("'Hey! Look Here!'!A1:A1"); - confirmAreaSheetName(ar, "Hey! Look Here!", "'Hey! Look Here!'!A1"); - - ar = new AreaReference("'O''Toole'!A1:B2"); - confirmAreaSheetName(ar, "O'Toole", "'O''Toole'!A1:B2"); - - ar = new AreaReference("'one:many'!A1:B2"); - confirmAreaSheetName(ar, "one:many", "'one:many'!A1:B2"); - } - - private static void confirmAreaSheetName(AreaReference ar, String sheetName, String expectedFullText) { - CellReference[] cells = ar.getAllReferencedCells(); - assertEquals(sheetName, cells[0].getSheetName()); - assertEquals(expectedFullText, ar.formatAsString()); - } - - public void testWholeColumnRefs() { - confirmWholeColumnRef("A:A", 0, 0, false, false); - confirmWholeColumnRef("$C:D", 2, 3, true, false); - confirmWholeColumnRef("AD:$AE", 29, 30, false, true); - } - - private static void confirmWholeColumnRef(String ref, int firstCol, int lastCol, boolean firstIsAbs, boolean lastIsAbs) { - AreaReference ar = new AreaReference(ref); - confirmCell(ar.getFirstCell(), 0, firstCol, true, firstIsAbs); - confirmCell(ar.getLastCell(), 0xFFFF, lastCol, true, lastIsAbs); - } - - private static void confirmCell(CellReference cell, int row, int col, boolean isRowAbs, - boolean isColAbs) { - assertEquals(row, cell.getRow()); - assertEquals(col, cell.getCol()); - assertEquals(isRowAbs, cell.isRowAbsolute()); - assertEquals(isColAbs, cell.isColAbsolute()); - } -} diff --git a/src/testcases/org/apache/poi/hssf/util/TestCellReference.java b/src/testcases/org/apache/poi/hssf/util/TestCellReference.java deleted file mode 100644 index ee08781e8..000000000 --- a/src/testcases/org/apache/poi/hssf/util/TestCellReference.java +++ /dev/null @@ -1,167 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.util; - -import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.ss.util.CellReference.NameType; -import org.apache.poi.ss.SpreadsheetVersion; - -/** - * Tests for the HSSF and SS versions of CellReference. - * See also {@link org.apache.poi.ss.util.TestCellReference} - */ -public final class TestCellReference { - @Test - public void testColNumConversion() { - assertEquals(0, CellReference.convertColStringToIndex("A")); - assertEquals(1, CellReference.convertColStringToIndex("B")); - assertEquals(25, CellReference.convertColStringToIndex("Z")); - assertEquals(26, CellReference.convertColStringToIndex("AA")); - assertEquals(27, CellReference.convertColStringToIndex("AB")); - assertEquals(51, CellReference.convertColStringToIndex("AZ")); - assertEquals(701, CellReference.convertColStringToIndex("ZZ")); - assertEquals(702, CellReference.convertColStringToIndex("AAA")); - assertEquals(18277, CellReference.convertColStringToIndex("ZZZ")); - - assertEquals("A", CellReference.convertNumToColString(0)); - assertEquals("B", CellReference.convertNumToColString(1)); - assertEquals("Z", CellReference.convertNumToColString(25)); - assertEquals("AA", CellReference.convertNumToColString(26)); - assertEquals("ZZ", CellReference.convertNumToColString(701)); - assertEquals("AAA", CellReference.convertNumToColString(702)); - assertEquals("ZZZ", CellReference.convertNumToColString(18277)); - - // Absolute references are allowed for the string ones - assertEquals(0, CellReference.convertColStringToIndex("$A")); - assertEquals(25, CellReference.convertColStringToIndex("$Z")); - assertEquals(26, CellReference.convertColStringToIndex("$AA")); - - // $ sign isn't allowed elsewhere though - try { - CellReference.convertColStringToIndex("A$B$"); - fail("Column reference is invalid and shouldn't be accepted"); - } catch (IllegalArgumentException e) {} - } - - @Test - public void testAbsRef1(){ - CellReference cf = new CellReference("$B$5"); - confirmCell(cf, null, 4, 1, true, true, "$B$5"); - } - - @Test - public void testAbsRef2(){ - CellReference cf = new CellReference(4,1,true,true); - confirmCell(cf, null, 4, 1, true, true, "$B$5"); - } - - @Test - public void testAbsRef3(){ - CellReference cf = new CellReference("B$5"); - confirmCell(cf, null, 4, 1, true, false, "B$5"); - } - - @Test - public void testAbsRef4(){ - CellReference cf = new CellReference(4,1,true,false); - confirmCell(cf, null, 4, 1, true, false, "B$5"); - } - - @Test - public void testAbsRef5(){ - CellReference cf = new CellReference("$B5"); - confirmCell(cf, null, 4, 1, false, true, "$B5"); - } - - @Test - public void testAbsRef6(){ - CellReference cf = new CellReference(4,1,false,true); - confirmCell(cf, null, 4, 1, false, true, "$B5"); - } - - @Test - public void testAbsRef7(){ - CellReference cf = new CellReference("B5"); - confirmCell(cf, null, 4, 1, false, false, "B5"); - } - - @Test - public void testAbsRef8(){ - CellReference cf = new CellReference(4,1,false,false); - confirmCell(cf, null, 4, 1, false, false, "B5"); - } - - @Test - public void testSpecialSheetNames() { - CellReference cf; - cf = new CellReference("'profit + loss'!A1"); - confirmCell(cf, "profit + loss", 0, 0, false, false, "'profit + loss'!A1"); - - cf = new CellReference("'O''Brien''s Sales'!A1"); - confirmCell(cf, "O'Brien's Sales", 0, 0, false, false, "'O''Brien''s Sales'!A1"); - - cf = new CellReference("'Amazing!'!A1"); - confirmCell(cf, "Amazing!", 0, 0, false, false, "'Amazing!'!A1"); - } - - /* package */ static void confirmCell(CellReference cf, String expSheetName, int expRow, - int expCol, boolean expIsRowAbs, boolean expIsColAbs, String expText) { - - assertEquals(expSheetName, cf.getSheetName()); - assertEquals("row index is wrong", expRow, cf.getRow()); - assertEquals("col index is wrong", expCol, cf.getCol()); - assertEquals("isRowAbsolute is wrong", expIsRowAbs, cf.isRowAbsolute()); - assertEquals("isColAbsolute is wrong", expIsColAbs, cf.isColAbsolute()); - assertEquals("text is wrong", expText, cf.formatAsString()); - } - - @Test - public void testClassifyCellReference() { - confirmNameType("a1", NameType.CELL); - confirmNameType("pfy1", NameType.NAMED_RANGE); - confirmNameType("pf1", NameType.NAMED_RANGE); // (col) out of cell range - confirmNameType("fp1", NameType.CELL); - confirmNameType("pf$1", NameType.BAD_CELL_OR_NAMED_RANGE); - confirmNameType("_A1", NameType.NAMED_RANGE); - confirmNameType("A_1", NameType.NAMED_RANGE); - confirmNameType("A1_", NameType.NAMED_RANGE); - confirmNameType(".A1", NameType.BAD_CELL_OR_NAMED_RANGE); - confirmNameType("A.1", NameType.NAMED_RANGE); - confirmNameType("A1.", NameType.NAMED_RANGE); - } - - @Test - public void testClassificationOfRowReferences(){ - confirmNameType("10", NameType.ROW); - confirmNameType("$10", NameType.ROW); - confirmNameType("65536", NameType.ROW); - - confirmNameType("65537", NameType.BAD_CELL_OR_NAMED_RANGE); - confirmNameType("$100000", NameType.BAD_CELL_OR_NAMED_RANGE); - confirmNameType("$1$1", NameType.BAD_CELL_OR_NAMED_RANGE); - } - - private void confirmNameType(String ref, NameType expectedResult) { - NameType actualResult = CellReference.classifyCellReference(ref, SpreadsheetVersion.EXCEL97); - assertEquals(expectedResult, actualResult); - } -} diff --git a/src/testcases/org/apache/poi/hssf/util/TestHSSFColor.java b/src/testcases/org/apache/poi/hssf/util/TestHSSFColor.java deleted file mode 100644 index be35ee268..000000000 --- a/src/testcases/org/apache/poi/hssf/util/TestHSSFColor.java +++ /dev/null @@ -1,61 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.util; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.util.Map; - -import org.apache.poi.hssf.util.HSSFColor.HSSFColorPredefined; -import org.junit.Test; - -public final class TestHSSFColor { - @Test - public void testBasics() { - assertNotNull(HSSFColor.YELLOW.class); - assertTrue(HSSFColorPredefined.YELLOW.getIndex() > 0); - assertTrue(HSSFColorPredefined.YELLOW.getIndex2() > 0); - } - - @Test - public void testContents() { - short[] triplet = HSSFColorPredefined.YELLOW.getTriplet(); - assertEquals(3, triplet.length); - assertEquals(255, triplet[0]); - assertEquals(255, triplet[1]); - assertEquals(0, triplet[2]); - - assertEquals("FFFF:FFFF:0", HSSFColorPredefined.YELLOW.getHexString()); - } - - @Test - public void testTrippletHash() { - Map tripplets = HSSFColor.getTripletHash(); - - assertEquals( - HSSFColor.MAROON.class, - tripplets.get(HSSFColorPredefined.MAROON.getHexString()).getClass() - ); - assertEquals( - HSSFColor.YELLOW.class, - tripplets.get(HSSFColorPredefined.YELLOW.getHexString()).getClass() - ); - } -} diff --git a/src/testcases/org/apache/poi/hssf/util/TestRKUtil.java b/src/testcases/org/apache/poi/hssf/util/TestRKUtil.java deleted file mode 100644 index 5b845775f..000000000 --- a/src/testcases/org/apache/poi/hssf/util/TestRKUtil.java +++ /dev/null @@ -1,51 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.util; - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -/** - * Tests the {@link RKUtil} class. - */ -public final class TestRKUtil extends TestCase { - - /** - * Check we can decode correctly. - */ - public void testDecode() { - - int[] values = { 1074266112, 1081384961, 1081397249, - 0x3FF00000, 0x405EC001, 0x02F1853A, 0x02F1853B, 0xFCDD699A, - }; - double[] rvalues = { 3.0, 3.3, 3.33, - 1, 1.23, 12345678, 123456.78, -13149594, - }; - - for (int j = 0; j < values.length; j++) { - - int intBits = values[j]; - double expectedValue = rvalues[j]; - double actualValue = RKUtil.decodeNumber(intBits); - if (expectedValue != actualValue) { - throw new AssertionFailedError("0x" + Integer.toHexString(intBits) - + " should decode to " + expectedValue + " but got " + actualValue); - } - } - } -} diff --git a/src/testcases/org/apache/poi/poifs/AllPOIFSTests.java b/src/testcases/org/apache/poi/poifs/AllPOIFSTests.java deleted file mode 100644 index a50bfe6f4..000000000 --- a/src/testcases/org/apache/poi/poifs/AllPOIFSTests.java +++ /dev/null @@ -1,42 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs; - -import org.apache.poi.poifs.eventfilesystem.TestPOIFSReaderRegistry; -import org.apache.poi.poifs.filesystem.AllPOIFSFileSystemTests; -import org.apache.poi.poifs.macros.TestVBAMacroReader; -import org.apache.poi.poifs.nio.TestDataSource; -import org.apache.poi.poifs.property.AllPOIFSPropertyTests; -import org.apache.poi.poifs.storage.AllPOIFSStorageTests; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -/** - * Test suite for all sub-packages of org.apache.poi.poifs - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestPOIFSReaderRegistry.class - , TestDataSource.class - , TestVBAMacroReader.class - , AllPOIFSFileSystemTests.class - , AllPOIFSPropertyTests.class - , AllPOIFSStorageTests.class -}) -public final class AllPOIFSTests { -} diff --git a/src/testcases/org/apache/poi/poifs/crypt/AllEncryptionTests.java b/src/testcases/org/apache/poi/poifs/crypt/AllEncryptionTests.java deleted file mode 100644 index 8bd67db91..000000000 --- a/src/testcases/org/apache/poi/poifs/crypt/AllEncryptionTests.java +++ /dev/null @@ -1,33 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.crypt; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -/** - * Collects all tests for package org.apache.poi.poifs.crypt. - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestBiff8DecryptingStream.class, - TestCipherAlgorithm.class, - TestXorEncryption.class -}) -public final class AllEncryptionTests { -} diff --git a/src/testcases/org/apache/poi/poifs/crypt/TestBiff8DecryptingStream.java b/src/testcases/org/apache/poi/poifs/crypt/TestBiff8DecryptingStream.java deleted file mode 100644 index d8a78582f..000000000 --- a/src/testcases/org/apache/poi/poifs/crypt/TestBiff8DecryptingStream.java +++ /dev/null @@ -1,249 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.crypt; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; - -import java.io.InputStream; -import java.util.Arrays; - -import javax.crypto.spec.SecretKeySpec; - -import org.apache.poi.hssf.record.crypto.Biff8DecryptingStream; -import org.apache.poi.util.HexDump; -import org.apache.poi.util.HexRead; -import org.junit.Test; - -import junit.framework.AssertionFailedError; -import junit.framework.ComparisonFailure; - -/** - * Tests for {@link Biff8DecryptingStream} - */ -public final class TestBiff8DecryptingStream { - - /** - * A mock {@link InputStream} that keeps track of position and also produces - * slightly interesting data. Each successive data byte value is one greater - * than the previous. - */ - private static final class MockStream extends InputStream { - private final int _initialValue; - private int _position; - - public MockStream(int initialValue) { - _initialValue = initialValue; - } - - @Override - public int read() { - return (_initialValue+_position++) & 0xFF; - } - } - - private static final class StreamTester { - private static final boolean ONLY_LOG_ERRORS = true; - - private final MockStream _ms; - private final Biff8DecryptingStream _bds; - private boolean _errorsOccurred; - - /** - * @param expectedFirstInt expected value of the first int read from the decrypted stream - */ - public StreamTester(MockStream ms, String keyDigestHex, int expectedFirstInt) { - _ms = ms; - byte[] keyDigest = HexRead.readFromString(keyDigestHex); - EncryptionInfo ei = new EncryptionInfo(EncryptionMode.binaryRC4); - Decryptor dec = ei.getDecryptor(); - dec.setSecretKey(new SecretKeySpec(keyDigest, "RC4")); - - _bds = new Biff8DecryptingStream(_ms, 0, ei); - assertEquals(expectedFirstInt, _bds.readInt()); - _errorsOccurred = false; - } - - public Biff8DecryptingStream getBDS() { - return _bds; - } - - /** - * Used to 'skip over' the uninteresting middle bits of the key blocks. - * Also confirms that read position of the underlying stream is aligned. - */ - public void rollForward(int fromPosition, int toPosition) { - assertEquals(fromPosition, _bds.getPosition()); - for (int i = fromPosition; i < toPosition; i++) { - _bds.readByte(); - } - assertEquals(toPosition, _bds.getPosition()); - } - - public void confirmByte(int expVal) { - assertEquals(HexDump.byteToHex(expVal), HexDump.byteToHex(_bds.readUByte())); - } - - public void confirmShort(int expVal) { - assertEquals(HexDump.shortToHex(expVal), HexDump.shortToHex(_bds.readShort())); - } - - public void confirmUShort(int expVal) { - assertEquals(HexDump.shortToHex(expVal), HexDump.shortToHex(_bds.readUShort())); - } - - public short readShort() { - return _bds.readShort(); - } - - public int readUShort() { - return _bds.readUShort(); - } - - public void confirmInt(int expVal) { - assertEquals(HexDump.intToHex(expVal), HexDump.intToHex(_bds.readInt())); - } - - public void confirmLong(long expVal) { - assertEquals(HexDump.longToHex(expVal), HexDump.longToHex(_bds.readLong())); - } - - public void confirmData(String expHexData) { - - byte[] expData = HexRead.readFromString(expHexData); - byte[] actData = new byte[expData.length]; - _bds.readFully(actData); - if (Arrays.equals(expData, actData)) { - return; - } - _errorsOccurred = true; - if (ONLY_LOG_ERRORS) { - logErr(2, "Data mismatch " + HexDump.toHex(expData) + " - " - + HexDump.toHex(actData)); - return; - } - throw new ComparisonFailure("Data mismatch", HexDump.toHex(expData), HexDump.toHex(actData)); - } - - private static void logErr(int stackFrameCount, String msg) { - StackTraceElement ste = new Exception().getStackTrace()[stackFrameCount]; - System.err.print("(" + ste.getFileName() + ":" + ste.getLineNumber() + ") "); - System.err.println(msg); - } - - public void assertNoErrors() { - assertFalse("Some values decrypted incorrectly", _errorsOccurred); - } - } - - /** - * Tests reading of 64,32,16 and 8 bit integers aligned with key changing boundaries - */ - @Test - public void readsAlignedWithBoundary() { - StreamTester st = createStreamTester(0x50, "BA AD F0 0D 00", 0x96C66829); - - st.rollForward(0x0004, 0x03FF); - st.confirmByte(0x3E); - st.confirmByte(0x28); - st.rollForward(0x0401, 0x07FE); - st.confirmShort(0x76CC); - st.confirmShort(0xD83E); - st.rollForward(0x0802, 0x0BFC); - st.confirmInt(0x25F280EB); - st.confirmInt(0xB549E99B); - st.rollForward(0x0C04, 0x0FF8); - st.confirmLong(0x6AA2D5F6B975D10CL); - st.confirmLong(0x34248ADF7ED4F029L); - // check for signed/unsigned shorts #58069 - st.rollForward(0x1008, 0x7213); - st.confirmUShort(0xFFFF); - st.rollForward(0x7215, 0x1B9AD); - st.confirmShort(-1); - st.rollForward(0x1B9AF, 0x37D99); - assertEquals(0xFFFF, st.readUShort()); - st.rollForward(0x37D9B, 0x4A6F2); - assertEquals(-1, st.readShort()); - st.assertNoErrors(); - } - - /** - * Tests reading of 64,32 and 16 bit integers across key changing boundaries - */ - @Test - public void readsSpanningBoundary() { - StreamTester st = createStreamTester(0x50, "BA AD F0 0D 00", 0x96C66829); - - st.rollForward(0x0004, 0x03FC); - st.confirmLong(0x885243283E2A5EEFL); - st.rollForward(0x0404, 0x07FE); - st.confirmInt(0xD83E76CC); - st.rollForward(0x0802, 0x0BFF); - st.confirmShort(0x9B25); - st.assertNoErrors(); - } - - /** - * Checks that the BIFF header fields (sid, size) get read without applying decryption, - * and that the RC4 stream stays aligned during these calls - */ - @Test - public void readHeaderUShort() { - StreamTester st = createStreamTester(0x50, "BA AD F0 0D 00", 0x96C66829); - - st.rollForward(0x0004, 0x03FF); - - Biff8DecryptingStream bds = st.getBDS(); - int hval = bds.readDataSize(); // unencrypted - int nextInt = bds.readInt(); - if (nextInt == 0x8F534029) { - throw new AssertionFailedError( - "Indentified bug in key alignment after call to readHeaderUShort()"); - } - assertEquals(0x16885243, nextInt); - if (hval == 0x283E) { - throw new AssertionFailedError("readHeaderUShort() incorrectly decrypted result"); - } - assertEquals(0x504F, hval); - - // confirm next key change - st.rollForward(0x0405, 0x07FC); - st.confirmInt(0x76CC1223); - st.confirmInt(0x4842D83E); - st.assertNoErrors(); - } - - /** - * Tests reading of byte sequences across and aligned with key changing boundaries - */ - @Test - public void readByteArrays() { - StreamTester st = createStreamTester(0x50, "BA AD F0 0D 00", 0x96C66829); - - st.rollForward(0x0004, 0x2FFC); - st.confirmData("66 A1 20 B1 04 A3 35 F5"); // 4 bytes on either side of boundary - st.rollForward(0x3004, 0x33F8); - st.confirmData("F8 97 59 36"); // last 4 bytes in block - st.confirmData("01 C2 4E 55"); // first 4 bytes in next block - st.assertNoErrors(); - } - - private static StreamTester createStreamTester(int mockStreamStartVal, String keyDigestHex, int expectedFirstInt) { - return new StreamTester(new MockStream(mockStreamStartVal), keyDigestHex, expectedFirstInt); - } -} diff --git a/src/testcases/org/apache/poi/poifs/crypt/TestCipherAlgorithm.java b/src/testcases/org/apache/poi/poifs/crypt/TestCipherAlgorithm.java deleted file mode 100644 index 68d6ab290..000000000 --- a/src/testcases/org/apache/poi/poifs/crypt/TestCipherAlgorithm.java +++ /dev/null @@ -1,52 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.crypt; - -import static org.junit.Assert.assertEquals; - -import org.apache.poi.EncryptedDocumentException; -import org.junit.Test; - -public class TestCipherAlgorithm { - @Test - public void validInputs() { - assertEquals(128, CipherAlgorithm.aes128.defaultKeySize); - - for(CipherAlgorithm alg : CipherAlgorithm.values()) { - assertEquals(alg, CipherAlgorithm.valueOf(alg.toString())); - } - - assertEquals(CipherAlgorithm.aes128, CipherAlgorithm.fromEcmaId(0x660E)); - assertEquals(CipherAlgorithm.aes192, CipherAlgorithm.fromXmlId("AES", 192)); - } - - @Test(expected=EncryptedDocumentException.class) - public void invalidEcmaId() { - CipherAlgorithm.fromEcmaId(0); - } - - @Test(expected=EncryptedDocumentException.class) - public void invalidXmlId1() { - CipherAlgorithm.fromXmlId("AES", 1); - } - - @Test(expected=EncryptedDocumentException.class) - public void invalidXmlId2() { - CipherAlgorithm.fromXmlId("RC1", 0x40); - } -} diff --git a/src/testcases/org/apache/poi/poifs/crypt/TestXorEncryption.java b/src/testcases/org/apache/poi/poifs/crypt/TestXorEncryption.java deleted file mode 100644 index 20dec4552..000000000 --- a/src/testcases/org/apache/poi/poifs/crypt/TestXorEncryption.java +++ /dev/null @@ -1,75 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.crypt; - -import static org.hamcrest.core.IsEqual.equalTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; - -import java.io.IOException; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; -import org.apache.poi.util.HexRead; -import org.junit.After; -import org.junit.Test; - -public class TestXorEncryption { - - private static final HSSFTestDataSamples samples = new HSSFTestDataSamples(); - - // to not affect other tests running in the same JVM - @After - public void resetPassword() { - Biff8EncryptionKey.setCurrentUserPassword(null); - } - - @Test - public void testXorEncryption() throws IOException { - // Xor-Password: abc - // 2.5.343 XORObfuscation - // key = 20810 - // verifier = 52250 - int verifier = CryptoFunctions.createXorVerifier1("abc"); - int key = CryptoFunctions.createXorKey1("abc"); - assertEquals(20810, key); - assertEquals(52250, verifier); - - byte xorArrAct[] = CryptoFunctions.createXorArray1("abc"); - byte xorArrExp[] = HexRead.readFromString("AC-CC-A4-AB-D6-BA-C3-BA-D6-A3-2B-45-D3-79-29-BB"); - assertThat(xorArrExp, equalTo(xorArrAct)); - } - - @SuppressWarnings("static-access") - @Test - public void testUserFile() throws IOException { - Biff8EncryptionKey.setCurrentUserPassword("abc"); - NPOIFSFileSystem fs = new NPOIFSFileSystem(samples.getSampleFile("xor-encryption-abc.xls"), true); - HSSFWorkbook hwb = new HSSFWorkbook(fs.getRoot(), true); - - HSSFSheet sh = hwb.getSheetAt(0); - assertEquals(1.0, sh.getRow(0).getCell(0).getNumericCellValue(), 0.0); - assertEquals(2.0, sh.getRow(1).getCell(0).getNumericCellValue(), 0.0); - assertEquals(3.0, sh.getRow(2).getCell(0).getNumericCellValue(), 0.0); - hwb.close(); - fs.close(); - } -} diff --git a/src/testcases/org/apache/poi/poifs/crypt/binaryrc4/TestBinaryRC4.java b/src/testcases/org/apache/poi/poifs/crypt/binaryrc4/TestBinaryRC4.java deleted file mode 100644 index b1155c3f5..000000000 --- a/src/testcases/org/apache/poi/poifs/crypt/binaryrc4/TestBinaryRC4.java +++ /dev/null @@ -1,106 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.crypt.binaryrc4; - -import static org.apache.poi.util.HexRead.readFromString; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.security.GeneralSecurityException; - -import javax.crypto.SecretKey; - -import org.apache.poi.poifs.crypt.Decryptor; -import org.apache.poi.poifs.crypt.EncryptionInfo; -import org.apache.poi.poifs.crypt.EncryptionMode; -import org.junit.Test; - -public class TestBinaryRC4 { - @Test - public void createKeyDigest() throws GeneralSecurityException { - byte[] docIdData = readFromString("17 F6 D1 6B 09 B1 5F 7B 4C 9D 03 B4 81 B5 B4 4A"); - byte[] expResult = readFromString("C2 D9 56 B2 6B"); - - EncryptionInfo ei = new EncryptionInfo(EncryptionMode.binaryRC4); - BinaryRC4EncryptionVerifier ver = (BinaryRC4EncryptionVerifier)ei.getVerifier(); - ver.setSalt(docIdData); - SecretKey sk = BinaryRC4Decryptor.generateSecretKey("MoneyForNothing", ver); - - assertArrayEquals("keyDigest mismatch", expResult, sk.getEncoded()); - } - - @Test - public void testValidateWithDefaultPassword() throws GeneralSecurityException { - - String docIdSuffixA = "F 35 52 38 0D 75 4A E6 85 C2 FD 78 CE 3D D1 B6"; // valid prefix is 'D' - String saltHashA = "30 38 BE 5E 93 C5 7E B4 5F 52 CD A1 C6 8F B6 2A"; - String saltDataA = "D4 04 43 EC B7 A7 6F 6A D2 68 C7 DF CF A8 80 68"; - - String docIdB = "39 D7 80 41 DA E4 74 2C 8C 84 F9 4D 39 9A 19 2D"; - String saltDataSuffixB = "3 EA 8D 52 11 11 37 D2 BD 55 4C 01 0A 47 6E EB"; // valid prefix is 'C' - String saltHashB = "96 19 F5 D0 F1 63 08 F1 3E 09 40 1E 87 F0 4E 16"; - - confirmValid(true, "D" + docIdSuffixA, saltDataA, saltHashA); - confirmValid(true, docIdB, "C" + saltDataSuffixB, saltHashB); - confirmValid(false, "E" + docIdSuffixA, saltDataA, saltHashA); - confirmValid(false, docIdB, "B" + saltDataSuffixB, saltHashB); - } - - @Test - public void testValidateWithSuppliedPassword() throws GeneralSecurityException { - - String docId = "DF 35 52 38 0D 75 4A E6 85 C2 FD 78 CE 3D D1 B6"; - String saltData = "D4 04 43 EC B7 A7 6F 6A D2 68 C7 DF CF A8 80 68"; - String saltHashA = "8D C2 63 CC E1 1D E0 05 20 16 96 AF 48 59 94 64"; // for password '5ecret' - String saltHashB = "31 0B 0D A4 69 55 8E 27 A1 03 AD C9 AE F8 09 04"; // for password '5ecret' - - confirmValid(true, docId, saltData, saltHashA, "5ecret"); - confirmValid(false, docId, saltData, saltHashA, "Secret"); - confirmValid(true, docId, saltData, saltHashB, "Secret"); - confirmValid(false, docId, saltData, saltHashB, "secret"); - } - - - private static void confirmValid(boolean expectedResult, - String docIdHex, String saltDataHex, String saltHashHex) throws GeneralSecurityException { - confirmValid(expectedResult, docIdHex, saltDataHex, saltHashHex, null); - } - - private static void confirmValid(boolean expectedResult, String docIdHex, - String saltDataHex, String saltHashHex, String password) throws GeneralSecurityException { - byte[] docId = readFromString(docIdHex); - byte[] saltData = readFromString(saltDataHex); - byte[] saltHash = readFromString(saltHashHex); - - EncryptionInfo ei = new EncryptionInfo(EncryptionMode.binaryRC4); - BinaryRC4EncryptionVerifier ver = (BinaryRC4EncryptionVerifier)ei.getVerifier(); - ver.setSalt(docId); - ver.setEncryptedVerifier(saltData); - ver.setEncryptedVerifierHash(saltHash); - - String pass = password == null ? Decryptor.DEFAULT_PASSWORD : password; - boolean actResult = ei.getDecryptor().verifyPassword(pass); - if (expectedResult) { - assertTrue("validate failed", actResult); - } else { - assertFalse("validate succeeded unexpectedly", actResult); - } - } - -} diff --git a/src/testcases/org/apache/poi/poifs/dev/TestPOIFSDump.java b/src/testcases/org/apache/poi/poifs/dev/TestPOIFSDump.java deleted file mode 100644 index 3c50507d1..000000000 --- a/src/testcases/org/apache/poi/poifs/dev/TestPOIFSDump.java +++ /dev/null @@ -1,193 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.poifs.dev; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; -import org.apache.poi.poifs.filesystem.NotOLE2FileException; -import org.apache.poi.poifs.filesystem.OfficeXmlFileException; -import org.apache.poi.poifs.property.NPropertyTable; -import org.apache.poi.util.TempFile; -import org.junit.After; -import org.junit.Ignore; -import org.junit.Test; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; - -import static org.junit.Assert.*; - -public class TestPOIFSDump { - - private static final String TEST_FILE = HSSFTestDataSamples.getSampleFile("46515.xls").getAbsolutePath(); - private static final String INVALID_FILE = HSSFTestDataSamples.getSampleFile("48936-strings.txt").getAbsolutePath(); - private static final String INVALID_XLSX_FILE = HSSFTestDataSamples.getSampleFile("47668.xlsx").getAbsolutePath(); - - private static final String[] DUMP_OPTIONS = { - "-dumprops", - "-dump-props", - "-dump-properties", - "-dumpmini", - "-dump-mini", - "-dump-ministream", - "-dump-mini-stream", - }; - - @After - public void tearDown() throws IOException { - // clean up the directory that POIFSDump writes to - deleteDirectory(new File(new File(TEST_FILE+"_dump").getName())); - } - - public static void deleteDirectory(File directory) throws IOException { - if (!directory.exists()) { - return; - } - - cleanDirectory(directory); - - if (!directory.delete()) { - String message = - "Unable to delete directory " + directory + "."; - throw new IOException(message); - } - } - - public static void cleanDirectory(File directory) throws IOException { - if (!directory.isDirectory()) { - String message = directory + " is not a directory"; - throw new IllegalArgumentException(message); - } - - File[] files = directory.listFiles(); - if (files == null) { // null if security restricted - throw new IOException("Failed to list contents of " + directory); - } - - IOException exception = null; - for (File file : files) { - try { - forceDelete(file); - } catch (IOException ioe) { - exception = ioe; - } - } - - if (null != exception) { - throw exception; - } - } - - public static void forceDelete(File file) throws IOException { - if (file.isDirectory()) { - deleteDirectory(file); - } else { - boolean filePresent = file.exists(); - if (!file.delete()) { - if (!filePresent){ - throw new FileNotFoundException("File does not exist: " + file); - } - String message = - "Unable to delete file: " + file; - throw new IOException(message); - } - } - } - - @Test - public void testMain() throws Exception { - POIFSDump.main(new String[] { - TEST_FILE - }); - - for(String option : DUMP_OPTIONS) { - POIFSDump.main(new String[]{ - option, - TEST_FILE - }); - } - } - @Test - public void testInvalidFile() throws Exception { - try { - POIFSDump.main(new String[]{ - INVALID_FILE - }); - fail("Should fail with an exception"); - } catch (NotOLE2FileException e) { - // expected here - } - - try { - POIFSDump.main(new String[]{ - INVALID_XLSX_FILE - }); - fail("Should fail with an exception"); - } catch (OfficeXmlFileException e) { - // expected here - } - - for(String option : DUMP_OPTIONS) { - try { - POIFSDump.main(new String[]{ - option, - INVALID_FILE - }); - fail("Should fail with an exception"); - } catch (NotOLE2FileException e) { - // expected here - } - - try { - POIFSDump.main(new String[]{ - option, - INVALID_XLSX_FILE - }); - fail("Should fail with an exception"); - } catch (OfficeXmlFileException e) { - // expected here - } - } - } - - @Ignore("Calls System.exit()") - @Test - public void testMainNoArgs() throws Exception { - POIFSDump.main(new String[] {}); - } - - @Test(expected=IndexOutOfBoundsException.class) - public void testFailToWrite() throws IOException { - File dir = TempFile.createTempFile("TestPOIFSDump", ".tst"); - assertTrue("Had: " + dir, dir.exists()); - assertTrue("Had: " + dir, dir.delete()); - assertTrue("Had: " + dir, dir.mkdirs()); - - FileInputStream is = new FileInputStream(TEST_FILE); - NPOIFSFileSystem fs = new NPOIFSFileSystem(is); - is.close(); - - NPropertyTable props = fs.getPropertyTable(); - assertNotNull(props); - - // try with an invalid startBlock to trigger an exception - // to validate that file-handles are closed properly - POIFSDump.dump(fs, 999999999, "mini-stream", dir); - } -} \ No newline at end of file diff --git a/src/testcases/org/apache/poi/poifs/eventfilesystem/Listener.java b/src/testcases/org/apache/poi/poifs/eventfilesystem/Listener.java deleted file mode 100644 index 4b597c171..000000000 --- a/src/testcases/org/apache/poi/poifs/eventfilesystem/Listener.java +++ /dev/null @@ -1,45 +0,0 @@ - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - - -package org.apache.poi.poifs.eventfilesystem; - -/** - * Class Listener - * - * @author Marc Johnson (mjohnson at apache dot org) - * @version %I%, %G% - */ - -class Listener - implements POIFSReaderListener -{ - - /** - * Process a POIFSReaderEvent that this listener had registered - * for - * - * @param event the POIFSReaderEvent - */ - - @Override - public void processPOIFSReaderEvent(POIFSReaderEvent event) - { - } -} // end class Listener - diff --git a/src/testcases/org/apache/poi/poifs/eventfilesystem/TestPOIFSReaderRegistry.java b/src/testcases/org/apache/poi/poifs/eventfilesystem/TestPOIFSReaderRegistry.java deleted file mode 100644 index 7a0e3d6d0..000000000 --- a/src/testcases/org/apache/poi/poifs/eventfilesystem/TestPOIFSReaderRegistry.java +++ /dev/null @@ -1,153 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.eventfilesystem; - -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; - -import junit.framework.TestCase; - -import org.apache.poi.poifs.filesystem.POIFSDocumentPath; - -/** - * Class to test POIFSReaderRegistry functionality - * - * @author Marc Johnson - */ -public final class TestPOIFSReaderRegistry extends TestCase { - private final POIFSReaderListener[] listeners = - { - new Listener(), new Listener(), new Listener(), new Listener() - }; - private final POIFSDocumentPath[] paths = - { - new POIFSDocumentPath(), new POIFSDocumentPath(new String[] - { - "a" - }), new POIFSDocumentPath(new String[] - { - "b" - }), new POIFSDocumentPath(new String[] - { - "c" - }) - }; - private final String[] names = - { - "a0", "a1", "a2", "a3" - }; - - /** - * Test empty registry - */ - public void testEmptyRegistry() { - POIFSReaderRegistry registry = new POIFSReaderRegistry(); - - for (POIFSDocumentPath path : paths) { - for (String name : names) { - Iterator listeners = - registry.getListeners(path, name); - - assertTrue(!listeners.hasNext()); - } - } - } - - /** - * Test mixed registration operations - */ - public void testMixedRegistrationOperations() { - POIFSReaderRegistry registry = new POIFSReaderRegistry(); - - for (int j = 0; j < listeners.length; j++) - { - for (int k = 0; k < paths.length; k++) - { - for (int n = 0; n < names.length; n++) - { - if ((j != k) && (k != n)) - { - registry.registerListener( - listeners[ j ], paths[ k ], names[ n ]); - } - } - } - } - for (int k = 0; k < paths.length; k++) - { - for (int n = 0; n < names.length; n++) - { - Iterator listeners = - registry.getListeners(paths[ k ], names[ n ]); - - if (k == n) - { - assertTrue(!listeners.hasNext()); - } - else - { - Set registeredListeners = - new HashSet(); - - while (listeners.hasNext()) - { - registeredListeners.add(listeners.next()); - } - assertEquals(this.listeners.length - 1, - registeredListeners.size()); - for (int j = 0; j < this.listeners.length; j++) - { - if (j == k) - { - assertTrue(!registeredListeners - .contains(this.listeners[ j ])); - } - else - { - assertTrue(registeredListeners - .contains(this.listeners[ j ])); - } - } - } - } - } - for (POIFSReaderListener listener : listeners) { - registry.registerListener(listener); - } - for (POIFSDocumentPath path : paths) { - for (String name : names) { - Iterator listeners = - registry.getListeners(path, name); - Set registeredListeners = - new HashSet(); - - while (listeners.hasNext()) - { - registeredListeners.add(listeners.next()); - } - assertEquals(this.listeners.length, - registeredListeners.size()); - for (POIFSReaderListener listener : this.listeners) { - assertTrue(registeredListeners - .contains(listener)); - } - } - } - } -} diff --git a/src/testcases/org/apache/poi/poifs/filesystem/AllPOIFSFileSystemTests.java b/src/testcases/org/apache/poi/poifs/filesystem/AllPOIFSFileSystemTests.java deleted file mode 100644 index 999f2de1b..000000000 --- a/src/testcases/org/apache/poi/poifs/filesystem/AllPOIFSFileSystemTests.java +++ /dev/null @@ -1,43 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.filesystem; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -/** - * Tests for org.apache.poi.poifs.filesystem
    - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestDirectoryNode.class - , TestDocument.class - , TestDocumentDescriptor.class - , TestDocumentInputStream.class - , TestDocumentNode.class - , TestDocumentOutputStream.class - , TestEmptyDocument.class - , TestOfficeXMLException.class - , TestPOIFSDocumentPath.class - , TestPOIFSFileSystem.class - , TestNPOIFSFileSystem.class - , TestPropertySorter.class - , TestOle10Native.class -}) -public final class AllPOIFSFileSystemTests { -} diff --git a/src/testcases/org/apache/poi/poifs/filesystem/ReaderWriter.java b/src/testcases/org/apache/poi/poifs/filesystem/ReaderWriter.java deleted file mode 100644 index 2aae3729d..000000000 --- a/src/testcases/org/apache/poi/poifs/filesystem/ReaderWriter.java +++ /dev/null @@ -1,195 +0,0 @@ - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - - -package org.apache.poi.poifs.filesystem; - -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -import org.apache.poi.poifs.eventfilesystem.POIFSReader; -import org.apache.poi.poifs.eventfilesystem.POIFSReaderEvent; -import org.apache.poi.poifs.eventfilesystem.POIFSReaderListener; - -/** - * Test (Proof of concept) program that employs the - * POIFSReaderListener and POIFSWriterListener interfaces - * - * @author Marc Johnson (mjohnson at apache dot org) - */ - -public class ReaderWriter - implements POIFSReaderListener, POIFSWriterListener -{ - private final POIFSFileSystem filesystem; - private final DirectoryEntry root; - - // keys are DocumentDescriptors, values are byte[]s - private final Map dataMap; - - /** - * Constructor ReaderWriter - * - * - * @param filesystem - * - */ - - ReaderWriter(final POIFSFileSystem filesystem) - { - this.filesystem = filesystem; - root = this.filesystem.getRoot(); - dataMap = new HashMap(); - } - - /** - * Method main - * - * - * @param args - * - * @exception IOException - * - */ - - public static void main(String [] args) - throws IOException - { - if (args.length != 2) - { - System.err.println( - "two arguments required: one input file name and one output file name"); - } - else - { - POIFSReader reader = new POIFSReader(); - POIFSFileSystem filesystem = new POIFSFileSystem(); - - reader.registerListener(new ReaderWriter(filesystem)); - FileInputStream istream = new FileInputStream(args[ 0 ]); - - reader.read(istream); - istream.close(); - FileOutputStream ostream = new FileOutputStream(args[ 1 ]); - - filesystem.writeFilesystem(ostream); - ostream.close(); - - filesystem.close(); - } - } - - /* ********** START implementation of POIFSReaderListener ********** */ - - /** - * Process a POIFSReaderEvent that this listener had registered - * for - * - * @param event the POIFSReaderEvent - */ - - @Override - public void processPOIFSReaderEvent(final POIFSReaderEvent event) - { - DocumentInputStream istream = event.getStream(); - POIFSDocumentPath path = event.getPath(); - String name = event.getName(); - - try - { - int size = istream.available(); - byte[] data = new byte[ istream.available() ]; - - istream.read(data); - DocumentDescriptor descriptor = new DocumentDescriptor(path, - name); - - System.out.println("adding document: " + descriptor + " (" + size - + " bytes)"); - dataMap.put(descriptor, data); - //int pathLength = path.length(); - DirectoryEntry entry = root; - - for (int k = 0; k < path.length(); k++) - { - String componentName = path.getComponent(k); - Entry nextEntry = null; - - try - { - nextEntry = entry.getEntry(componentName); - } - catch (FileNotFoundException ignored) - { - try - { - nextEntry = entry.createDirectory(componentName); - } - catch (IOException e) - { - System.out.println("Unable to create directory"); - e.printStackTrace(); - System.exit(1); - } - } - entry = ( DirectoryEntry ) nextEntry; - } - entry.createDocument(name, size, this); - } - catch (IOException ignored) - { - } - } - - /* ********** END implementation of POIFSReaderListener ********** */ - /* ********** START implementation of POIFSWriterListener ********** */ - - /** - * Process a POIFSWriterEvent that this listener had registered - * for - * - * @param event the POIFSWriterEvent - */ - - @Override - public void processPOIFSWriterEvent(final POIFSWriterEvent event) - { - try - { - DocumentDescriptor descriptor = - new DocumentDescriptor(event.getPath(), event.getName()); - - System.out.println("looking up document: " + descriptor + " (" - + event.getLimit() + " bytes)"); - event.getStream().write(dataMap.get(descriptor)); - } - catch (IOException e) - { - System.out.println("Unable to write document"); - e.printStackTrace(); - System.exit(1); - } - } - - /* ********** END implementation of POIFSWriterListener ********** */ -} // end public class ReaderWriter - diff --git a/src/testcases/org/apache/poi/poifs/filesystem/SlowInputStream.java b/src/testcases/org/apache/poi/poifs/filesystem/SlowInputStream.java deleted file mode 100644 index f818d2197..000000000 --- a/src/testcases/org/apache/poi/poifs/filesystem/SlowInputStream.java +++ /dev/null @@ -1,41 +0,0 @@ - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - - -package org.apache.poi.poifs.filesystem; - -import java.io.*; -import java.util.Random; - -/** - * Returns a random amount of requested data. Used to check conformance with - * InputStream API contracts. - */ -public class SlowInputStream extends FilterInputStream -{ - private final Random r = new Random(0); - - public SlowInputStream(InputStream in) { - super(in); - } - - @Override - public int read(byte[] b, int off, int len) throws IOException { - return super.read(b, off, r.nextInt(len) + 1); - } -} diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestDirectoryNode.java b/src/testcases/org/apache/poi/poifs/filesystem/TestDirectoryNode.java deleted file mode 100644 index 41d1a340f..000000000 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestDirectoryNode.java +++ /dev/null @@ -1,220 +0,0 @@ - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.filesystem; - -import java.io.ByteArrayInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.Iterator; - -import org.apache.poi.poifs.property.DirectoryProperty; -import org.apache.poi.poifs.property.DocumentProperty; - -import junit.framework.TestCase; - -/** - * Class to test DirectoryNode functionality - * - * @author Marc Johnson - */ -public final class TestDirectoryNode extends TestCase { - - /** - * test trivial constructor (a DirectoryNode with no children) - */ - public void testEmptyConstructor() { - POIFSFileSystem fs = new POIFSFileSystem(); - DirectoryProperty property1 = new DirectoryProperty("parent"); - DirectoryProperty property2 = new DirectoryProperty("child"); - DirectoryNode parent = new DirectoryNode(property1, fs, null); - DirectoryNode node = new DirectoryNode(property2, fs, - parent); - - assertEquals(0, parent.getPath().length()); - assertEquals(1, node.getPath().length()); - assertEquals("child", node.getPath().getComponent(0)); - - // verify that getEntries behaves correctly - int count = 0; - Iterator iter = node.getEntries(); - - while (iter.hasNext()) - { - count++; - iter.next(); - } - assertEquals(0, count); - - // verify behavior of isEmpty - assertTrue(node.isEmpty()); - - // verify behavior of getEntryCount - assertEquals(0, node.getEntryCount()); - - // verify behavior of getEntry - try - { - node.getEntry("foo"); - fail("should have caught FileNotFoundException"); - } - catch (FileNotFoundException ignored) - { - - // as expected - } - - // verify behavior of isDirectoryEntry - assertTrue(node.isDirectoryEntry()); - - // verify behavior of getName - assertEquals(property2.getName(), node.getName()); - - // verify behavior of isDocumentEntry - assertTrue(!node.isDocumentEntry()); - - // verify behavior of getParent - assertEquals(parent, node.getParent()); - } - - /** - * test non-trivial constructor (a DirectoryNode with children) - */ - public void testNonEmptyConstructor() throws IOException { - DirectoryProperty property1 = new DirectoryProperty("parent"); - DirectoryProperty property2 = new DirectoryProperty("child1"); - - property1.addChild(property2); - property1.addChild(new DocumentProperty("child2", 2000)); - property2.addChild(new DocumentProperty("child3", 30000)); - DirectoryNode node = new DirectoryNode(property1, - new POIFSFileSystem(), null); - - // verify that getEntries behaves correctly - int count = 0; - Iterator iter = node.getEntries(); - - while (iter.hasNext()) - { - count++; - iter.next(); - } - assertEquals(2, count); - - // verify behavior of isEmpty - assertTrue(!node.isEmpty()); - - // verify behavior of getEntryCount - assertEquals(2, node.getEntryCount()); - - // verify behavior of getEntry - DirectoryNode child1 = ( DirectoryNode ) node.getEntry("child1"); - - child1.getEntry("child3"); - node.getEntry("child2"); - try - { - node.getEntry("child3"); - fail("should have caught FileNotFoundException"); - } - catch (FileNotFoundException ignored) - { - - // as expected - } - - // verify behavior of isDirectoryEntry - assertTrue(node.isDirectoryEntry()); - - // verify behavior of getName - assertEquals(property1.getName(), node.getName()); - - // verify behavior of isDocumentEntry - assertTrue(!node.isDocumentEntry()); - - // verify behavior of getParent - assertNull(node.getParent()); - } - - /** - * test deletion methods - */ - public void testDeletion() throws IOException { - POIFSFileSystem fs = new POIFSFileSystem(); - DirectoryEntry root = fs.getRoot(); - - // verify cannot delete the root directory - assertFalse(root.delete()); - assertTrue(root.isEmpty()); - - DirectoryEntry dir = fs.createDirectory("myDir"); - - assertFalse(root.isEmpty()); - assertTrue(dir.isEmpty()); - - // verify can delete empty directory - assertFalse(root.delete()); - assertTrue(dir.delete()); - - // Now look at a non-empty one - dir = fs.createDirectory("NextDir"); - DocumentEntry doc = - dir.createDocument("foo", - new ByteArrayInputStream(new byte[ 1 ])); - - assertFalse(root.isEmpty()); - assertFalse(dir.isEmpty()); - - // verify cannot delete non-empty directory - assertFalse(dir.delete()); - - // but we can delete it if we remove the document - assertTrue(doc.delete()); - assertTrue(dir.isEmpty()); - assertTrue(dir.delete()); - - // It's really gone! - assertTrue(root.isEmpty()); - - fs.close(); - } - - /** - * test change name methods - */ - public void testRename() throws IOException { - POIFSFileSystem fs = new POIFSFileSystem(); - DirectoryEntry root = fs.getRoot(); - - // verify cannot rename the root directory - assertTrue(!root.renameTo("foo")); - DirectoryEntry dir = fs.createDirectory("myDir"); - - assertTrue(dir.renameTo("foo")); - assertEquals("foo", dir.getName()); - DirectoryEntry dir2 = fs.createDirectory("myDir"); - - assertTrue(!dir2.renameTo("foo")); - assertEquals("myDir", dir2.getName()); - assertTrue(dir.renameTo("FirstDir")); - assertTrue(dir2.renameTo("foo")); - assertEquals("foo", dir2.getName()); - - fs.close(); - } -} diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestDocument.java b/src/testcases/org/apache/poi/poifs/filesystem/TestDocument.java deleted file mode 100644 index f670b9a66..000000000 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestDocument.java +++ /dev/null @@ -1,234 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.filesystem; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -import org.apache.poi.poifs.property.DocumentProperty; -import org.apache.poi.poifs.storage.RawDataBlock; - -import junit.framework.TestCase; - -/** - * Class to test OPOIFSDocument functionality - */ -public final class TestDocument extends TestCase { - - /** - * Integration test -- really about all we can do - */ - public void testOPOIFSDocument() throws IOException { - - // verify correct number of blocks get created for document - // that is exact multituple of block size - OPOIFSDocument document; - byte[] array = new byte[ 4096 ]; - - for (int j = 0; j < array.length; j++) - { - array[ j ] = ( byte ) j; - } - document = new OPOIFSDocument("foo", new SlowInputStream(new ByteArrayInputStream(array))); - checkDocument(document, array); - - // verify correct number of blocks get created for document - // that is not an exact multiple of block size - array = new byte[ 4097 ]; - for (int j = 0; j < array.length; j++) - { - array[ j ] = ( byte ) j; - } - document = new OPOIFSDocument("bar", new ByteArrayInputStream(array)); - checkDocument(document, array); - - // verify correct number of blocks get created for document - // that is small - array = new byte[ 4095 ]; - for (int j = 0; j < array.length; j++) - { - array[ j ] = ( byte ) j; - } - document = new OPOIFSDocument("_bar", new ByteArrayInputStream(array)); - checkDocument(document, array); - - // verify correct number of blocks get created for document - // that is rather small - array = new byte[ 199 ]; - for (int j = 0; j < array.length; j++) - { - array[ j ] = ( byte ) j; - } - document = new OPOIFSDocument("_bar2", - new ByteArrayInputStream(array)); - checkDocument(document, array); - - // verify that output is correct - array = new byte[ 4097 ]; - for (int j = 0; j < array.length; j++) - { - array[ j ] = ( byte ) j; - } - document = new OPOIFSDocument("foobar", - new ByteArrayInputStream(array)); - checkDocument(document, array); - document.setStartBlock(0x12345678); // what a big file!! - DocumentProperty property = document.getDocumentProperty(); - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - - property.writeData(stream); - byte[] output = stream.toByteArray(); - byte[] array2 = - { - ( byte ) 'f', ( byte ) 0, ( byte ) 'o', ( byte ) 0, ( byte ) 'o', - ( byte ) 0, ( byte ) 'b', ( byte ) 0, ( byte ) 'a', ( byte ) 0, - ( byte ) 'r', ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, - ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, - ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, - ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, - ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, - ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, - ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, - ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, - ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, - ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, - ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 14, - ( byte ) 0, ( byte ) 2, ( byte ) 1, ( byte ) -1, ( byte ) -1, - ( byte ) -1, ( byte ) -1, ( byte ) -1, ( byte ) -1, ( byte ) -1, - ( byte ) -1, ( byte ) -1, ( byte ) -1, ( byte ) -1, ( byte ) -1, - ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, - ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, - ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, - ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, - ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, - ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, - ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, - ( byte ) 0, ( byte ) 0x78, ( byte ) 0x56, ( byte ) 0x34, - ( byte ) 0x12, ( byte ) 1, ( byte ) 16, ( byte ) 0, ( byte ) 0, - ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0 - }; - - assertEquals(array2.length, output.length); - for (int j = 0; j < output.length; j++) - { - assertEquals("Checking property offset " + j, array2[ j ], - output[ j ]); - } - } - - private static OPOIFSDocument makeCopy(OPOIFSDocument document, byte[] input, byte[] data) - throws IOException { - OPOIFSDocument copy = null; - - if (input.length >= 4096) - { - RawDataBlock[] blocks = - new RawDataBlock[ (input.length + 511) / 512 ]; - ByteArrayInputStream stream = new ByteArrayInputStream(data); - int index = 0; - - while (true) - { - RawDataBlock block = new RawDataBlock(stream); - - if (block.eof()) - { - break; - } - blocks[ index++ ] = block; - } - copy = new OPOIFSDocument("test" + input.length, blocks, - input.length); - } - else - { - copy = new OPOIFSDocument("test"+input.length, document.getSmallBlocks(), input.length); - } - return copy; - } - - private static void checkDocument(final OPOIFSDocument document, final byte[] input) - throws IOException { - int big_blocks = 0; - int small_blocks = 0; - int total_output = 0; - - if (input.length >= 4096) - { - big_blocks = (input.length + 511) / 512; - total_output = big_blocks * 512; - } - else - { - small_blocks = (input.length + 63) / 64; - total_output = 0; - } - checkValues( - big_blocks, small_blocks, total_output, - makeCopy( - document, input, - checkValues( - big_blocks, small_blocks, total_output, document, - input)), input); - } - - private static byte[] checkValues(int big_blocks, int small_blocks, int total_output, - OPOIFSDocument document, byte[] input) throws IOException { - assertEquals(document, document.getDocumentProperty().getDocument()); - int increment = ( int ) Math.sqrt(input.length); - - for (int j = 1; j <= input.length; j += increment) - { - byte[] buffer = new byte[ j ]; - int offset = 0; - - for (int k = 0; k < (input.length / j); k++) - { - document.read(buffer, offset); - for (int n = 0; n < buffer.length; n++) - { - assertEquals("checking byte " + (k * j) + n, - input[ (k * j) + n ], buffer[ n ]); - } - offset += j; - } - } - assertEquals(big_blocks, document.countBlocks()); - assertEquals(small_blocks, document.getSmallBlocks().length); - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - - document.writeBlocks(stream); - byte[] output = stream.toByteArray(); - - assertEquals(total_output, output.length); - int limit = Math.min(total_output, input.length); - - for (int j = 0; j < limit; j++) - { - assertEquals("Checking document offset " + j, input[ j ], - output[ j ]); - } - for (int j = limit; j < output.length; j++) - { - assertEquals("Checking document offset " + j, ( byte ) -1, - output[ j ]); - } - return output; - } -} diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestDocumentDescriptor.java b/src/testcases/org/apache/poi/poifs/filesystem/TestDocumentDescriptor.java deleted file mode 100644 index 9b69b1a2c..000000000 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestDocumentDescriptor.java +++ /dev/null @@ -1,175 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.filesystem; - -import junit.framework.TestCase; - -/** - * Class to test DocumentDescriptor functionality - * - * @author Marc Johnson - */ -public final class TestDocumentDescriptor extends TestCase { - - /** - * test equality - */ - public void testEquality() { - String[] names = { "c1", "c2", "c3", "c4", "c5" }; - POIFSDocumentPath a1 = new POIFSDocumentPath(); - POIFSDocumentPath a2 = new POIFSDocumentPath(null); - POIFSDocumentPath a3 = new POIFSDocumentPath(new String[ 0 ]); - POIFSDocumentPath a4 = new POIFSDocumentPath(a1, null); - POIFSDocumentPath a5 = new POIFSDocumentPath(a1, - new String[ 0 ]); - POIFSDocumentPath[] paths = { a1, a2, a3, a4, a5 }; - - for (int j = 0; j < paths.length; j++) - { - for (int k = 0; k < paths.length; k++) - { - for (int m = 0; m < names.length; m++) - { - DocumentDescriptor d1 = new DocumentDescriptor(paths[ j ], - names[ m ]); - - for (int n = 0; n < names.length; n++) - { - DocumentDescriptor d2 = - new DocumentDescriptor(paths[ k ], names[ n ]); - - if (m == n) - { - assertEquals("" + j + "," + k + "," + m + "," - + n, d1, d2); - } - else - { - assertTrue("" + j + "," + k + "," + m + "," + n, - !d1.equals(d2)); - } - } - } - } - } - a2 = new POIFSDocumentPath(a1, new String[] - { - "foo" - }); - a3 = new POIFSDocumentPath(a2, new String[] - { - "bar" - }); - a4 = new POIFSDocumentPath(a3, new String[] - { - "fubar" - }); - a5 = new POIFSDocumentPath(a4, new String[] - { - "foobar" - }); - POIFSDocumentPath[] builtUpPaths = - { - a1, a2, a3, a4, a5 - }; - POIFSDocumentPath[] fullPaths = - { - new POIFSDocumentPath(), new POIFSDocumentPath(new String[] - { - "foo" - }), new POIFSDocumentPath(new String[] - { - "foo", "bar" - }), new POIFSDocumentPath(new String[] - { - "foo", "bar", "fubar" - }), new POIFSDocumentPath(new String[] - { - "foo", "bar", "fubar", "foobar" - }) - }; - - for (int k = 0; k < builtUpPaths.length; k++) - { - for (int j = 0; j < fullPaths.length; j++) - { - for (int m = 0; m < names.length; m++) - { - DocumentDescriptor d1 = - new DocumentDescriptor(fullPaths[ j ], names[ m ]); - - for (int n = 0; n < names.length; n++) - { - DocumentDescriptor d2 = - new DocumentDescriptor(builtUpPaths[ k ], - names[ n ]); - - if ((k == j) && (m == n)) - { - assertEquals("" + j + "," + k + "," + m + "," - + n, d1, d2); - } - else - { - assertTrue("" + j + "," + k + "," + m + "," + n, - !(d1.equals(d2))); - } - } - } - } - } - POIFSDocumentPath[] badPaths = - { - new POIFSDocumentPath(new String[] - { - "_foo" - }), new POIFSDocumentPath(new String[] - { - "foo", "_bar" - }), new POIFSDocumentPath(new String[] - { - "foo", "bar", "_fubar" - }), new POIFSDocumentPath(new String[] - { - "foo", "bar", "fubar", "_foobar" - }) - }; - - for (int k = 0; k < builtUpPaths.length; k++) - { - for (int j = 0; j < badPaths.length; j++) - { - for (int m = 0; m < names.length; m++) - { - DocumentDescriptor d1 = - new DocumentDescriptor(badPaths[ j ], names[ m ]); - - for (int n = 0; n < names.length; n++) - { - DocumentDescriptor d2 = - new DocumentDescriptor(builtUpPaths[ k ], - names[ n ]); - - assertTrue("" + j + "," + k + "," + m + "," + n, - !(d1.equals(d2))); - } - } - } - } - } -} diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestDocumentInputStream.java b/src/testcases/org/apache/poi/poifs/filesystem/TestDocumentInputStream.java deleted file mode 100644 index bbe1e39f6..000000000 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestDocumentInputStream.java +++ /dev/null @@ -1,554 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.filesystem; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.util.Arrays; - -import junit.framework.TestCase; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.poifs.property.DirectoryProperty; -import org.apache.poi.poifs.storage.RawDataBlock; - -/** - * Class to test DocumentInputStream functionality - */ -public final class TestDocumentInputStream extends TestCase { - private DocumentNode _workbook_n; - private DocumentNode _workbook_o; - private byte[] _workbook_data; - private static final int _workbook_size = 5000; - - // non-even division of _workbook_size, also non-even division of - // any block size - private static final int _buffer_size = 6; - - @Override - protected void setUp() throws Exception { - int blocks = (_workbook_size + 511) / 512; - - _workbook_data = new byte[ 512 * blocks ]; - Arrays.fill(_workbook_data, ( byte ) -1); - for (int j = 0; j < _workbook_size; j++) - { - _workbook_data[ j ] = ( byte ) (j * j); - } - - // Create the Old POIFS Version - RawDataBlock[] rawBlocks = new RawDataBlock[ blocks ]; - ByteArrayInputStream stream = - new ByteArrayInputStream(_workbook_data); - - for (int j = 0; j < blocks; j++) - { - rawBlocks[ j ] = new RawDataBlock(stream); - } - OPOIFSDocument document = new OPOIFSDocument("Workbook", rawBlocks, - _workbook_size); - - _workbook_o = new DocumentNode( - document.getDocumentProperty(), - new DirectoryNode( - new DirectoryProperty("Root Entry"), (POIFSFileSystem)null, null)); - - // Now create the NPOIFS Version - byte[] _workbook_data_only = new byte[_workbook_size]; - System.arraycopy(_workbook_data, 0, _workbook_data_only, 0, _workbook_size); - - NPOIFSFileSystem npoifs = new NPOIFSFileSystem(); - // Make it easy when debugging to see what isn't the doc - byte[] minus1 = new byte[512]; - Arrays.fill(minus1, (byte)-1); - npoifs.getBlockAt(-1).put(minus1); - npoifs.getBlockAt(0).put(minus1); - npoifs.getBlockAt(1).put(minus1); - - // Create the NPOIFS document - _workbook_n = (DocumentNode)npoifs.createDocument( - new ByteArrayInputStream(_workbook_data_only), - "Workbook" - ); - } - - /** - * test constructor - */ - public void testConstructor() throws IOException { - DocumentInputStream ostream = new ODocumentInputStream(_workbook_o); - DocumentInputStream nstream = new NDocumentInputStream(_workbook_n); - - assertEquals(_workbook_size, _workbook_o.getSize()); - assertEquals(_workbook_size, _workbook_n.getSize()); - - assertEquals(_workbook_size, ostream.available()); - assertEquals(_workbook_size, nstream.available()); - - ostream.close(); - nstream.close(); - } - - /** - * test available() behavior - */ - public void testAvailable() throws IOException { - DocumentInputStream ostream = new DocumentInputStream(_workbook_o); - DocumentInputStream nstream = new NDocumentInputStream(_workbook_n); - - assertEquals(_workbook_size, ostream.available()); - assertEquals(_workbook_size, nstream.available()); - ostream.close(); - nstream.close(); - - try { - ostream.available(); - fail("Should have caught IOException"); - } catch (IllegalStateException ignored) { - // as expected - } - try { - nstream.available(); - fail("Should have caught IOException"); - } catch (IllegalStateException ignored) { - // as expected - } - } - - /** - * test mark/reset/markSupported. - */ - public void testMarkFunctions() throws IOException { - byte[] buffer = new byte[ _workbook_size / 5 ]; - byte[] small_buffer = new byte[212]; - - DocumentInputStream[] streams = new DocumentInputStream[] { - new DocumentInputStream(_workbook_o), - new NDocumentInputStream(_workbook_n) - }; - for(DocumentInputStream stream : streams) { - // Read a fifth of it, and check all's correct - stream.read(buffer); - for (int j = 0; j < buffer.length; j++) { - assertEquals( - "checking byte " + j, - _workbook_data[ j ], buffer[ j ] - ); - } - assertEquals(_workbook_size - buffer.length, stream.available()); - - // Reset, and check the available goes back to being the - // whole of the stream - stream.reset(); - assertEquals(_workbook_size, stream.available()); - - - // Read part of a block - stream.read(small_buffer); - for (int j = 0; j < small_buffer.length; j++) { - assertEquals( - "checking byte " + j, - _workbook_data[ j ], small_buffer[ j ] - ); - } - assertEquals(_workbook_size - small_buffer.length, stream.available()); - stream.mark(0); - - // Read the next part - stream.read(small_buffer); - for (int j = 0; j < small_buffer.length; j++) { - assertEquals( - "checking byte " + j, - _workbook_data[ j+small_buffer.length ], small_buffer[ j ] - ); - } - assertEquals(_workbook_size - 2*small_buffer.length, stream.available()); - - // Reset, check it goes back to where it was - stream.reset(); - assertEquals(_workbook_size - small_buffer.length, stream.available()); - - // Read - stream.read(small_buffer); - for (int j = 0; j < small_buffer.length; j++) { - assertEquals( - "checking byte " + j, - _workbook_data[ j+small_buffer.length ], small_buffer[ j ] - ); - } - assertEquals(_workbook_size - 2*small_buffer.length, stream.available()); - - - // Now read at various points - Arrays.fill(small_buffer, ( byte ) 0); - stream.read(small_buffer, 6, 8); - stream.read(small_buffer, 100, 10); - stream.read(small_buffer, 150, 12); - int pos = small_buffer.length * 2; - for (int j = 0; j < small_buffer.length; j++) { - byte exp = 0; - if(j>= 6 && j<6+8) { - exp = _workbook_data[pos]; - pos++; - } - if(j>= 100 && j<100+10) { - exp = _workbook_data[pos]; - pos++; - } - if(j>= 150 && j<150+12) { - exp = _workbook_data[pos]; - pos++; - } - - assertEquals("checking byte " + j, exp, small_buffer[j]); - } - } - - // Now repeat it with spanning multiple blocks - streams = new DocumentInputStream[] { - new DocumentInputStream(_workbook_o), - new NDocumentInputStream(_workbook_n) - }; - for(DocumentInputStream stream : streams) { - // Read several blocks work - buffer = new byte[ _workbook_size / 5 ]; - stream.read(buffer); - for (int j = 0; j < buffer.length; j++) { - assertEquals( - "checking byte " + j, - _workbook_data[ j ], buffer[ j ] - ); - } - assertEquals(_workbook_size - buffer.length, stream.available()); - - // Read all of it again, check it began at the start again - stream.reset(); - assertEquals(_workbook_size, stream.available()); - - stream.read(buffer); - for (int j = 0; j < buffer.length; j++) { - assertEquals( - "checking byte " + j, - _workbook_data[ j ], buffer[ j ] - ); - } - - // Mark our position, and read another whole buffer - stream.mark(12); - stream.read(buffer); - assertEquals(_workbook_size - (2 * buffer.length), - stream.available()); - for (int j = buffer.length; j < (2 * buffer.length); j++) - { - assertEquals("checking byte " + j, _workbook_data[ j ], - buffer[ j - buffer.length ]); - } - - // Reset, should go back to only one buffer full read - stream.reset(); - assertEquals(_workbook_size - buffer.length, stream.available()); - - // Read the buffer again - stream.read(buffer); - assertEquals(_workbook_size - (2 * buffer.length), - stream.available()); - for (int j = buffer.length; j < (2 * buffer.length); j++) - { - assertEquals("checking byte " + j, _workbook_data[ j ], - buffer[ j - buffer.length ]); - } - assertTrue(stream.markSupported()); - } - } - - /** - * test simple read method - */ - public void testReadSingleByte() throws IOException { - DocumentInputStream[] streams = new DocumentInputStream[] { - new DocumentInputStream(_workbook_o), - new NDocumentInputStream(_workbook_n) - }; - for(DocumentInputStream stream : streams) { - int remaining = _workbook_size; - - // Try and read each byte in turn - for (int j = 0; j < _workbook_size; j++) { - int b = stream.read(); - assertTrue("checking sign of " + j, b >= 0); - assertEquals("validating byte " + j, _workbook_data[ j ], - ( byte ) b); - remaining--; - assertEquals("checking remaining after reading byte " + j, - remaining, stream.available()); - } - - // Ensure we fell off the end - assertEquals(-1, stream.read()); - - // Check that after close we can no longer read - stream.close(); - try { - stream.read(); - fail("Should have caught IOException"); - } catch (IOException ignored) { - // as expected - } - } - } - - /** - * Test buffered read - */ - public void testBufferRead() throws IOException { - DocumentInputStream[] streams = new DocumentInputStream[] { - new DocumentInputStream(_workbook_o), - new NDocumentInputStream(_workbook_n) - }; - for(DocumentInputStream stream : streams) { - // Need to give a byte array to read - try { - stream.read(null); - fail("Should have caught NullPointerException"); - } catch (NullPointerException ignored) { - // as expected - } - - // test reading zero length buffer - assertEquals(0, stream.read(new byte[ 0 ])); - assertEquals(_workbook_size, stream.available()); - byte[] buffer = new byte[ _buffer_size ]; - int offset = 0; - - while (stream.available() >= buffer.length) - { - assertEquals(_buffer_size, stream.read(buffer)); - for (byte data : buffer) { - assertEquals("in main loop, byte " + offset, - _workbook_data[ offset ], data); - offset++; - } - assertEquals("offset " + offset, _workbook_size - offset, - stream.available()); - } - assertEquals(_workbook_size % _buffer_size, stream.available()); - Arrays.fill(buffer, ( byte ) 0); - int count = stream.read(buffer); - - assertEquals(_workbook_size % _buffer_size, count); - for (int j = 0; j < count; j++) - { - assertEquals("past main loop, byte " + offset, - _workbook_data[ offset ], buffer[ j ]); - offset++; - } - assertEquals(_workbook_size, offset); - for (int j = count; j < buffer.length; j++) - { - assertEquals("checking remainder, byte " + j, 0, buffer[ j ]); - } - assertEquals(-1, stream.read(buffer)); - stream.close(); - try { - stream.read(buffer); - fail("Should have caught IOException"); - } catch (IOException ignored) { - // as expected - } - } - } - - /** - * Test complex buffered read - */ - public void testComplexBufferRead() throws IOException { - DocumentInputStream[] streams = new DocumentInputStream[] { - new DocumentInputStream(_workbook_o), - new NDocumentInputStream(_workbook_n) - }; - for(DocumentInputStream stream : streams) { - try { - stream.read(null, 0, 1); - fail("Should have caught NullPointerException"); - } catch (IllegalArgumentException ignored) { - // as expected - } - - // test illegal offsets and lengths - try { - stream.read(new byte[ 5 ], -4, 0); - fail("Should have caught IndexOutOfBoundsException"); - } catch (IndexOutOfBoundsException ignored) { - // as expected - } - try { - stream.read(new byte[ 5 ], 0, -4); - fail("Should have caught IndexOutOfBoundsException"); - } catch (IndexOutOfBoundsException ignored) { - // as expected - } - try { - stream.read(new byte[ 5 ], 0, 6); - fail("Should have caught IndexOutOfBoundsException"); - } catch (IndexOutOfBoundsException ignored) { - // as expected - } - - // test reading zero - assertEquals(0, stream.read(new byte[ 5 ], 0, 0)); - assertEquals(_workbook_size, stream.available()); - byte[] buffer = new byte[ _workbook_size ]; - int offset = 0; - - while (stream.available() >= _buffer_size) - { - Arrays.fill(buffer, ( byte ) 0); - assertEquals(_buffer_size, - stream.read(buffer, offset, _buffer_size)); - for (int j = 0; j < offset; j++) - { - assertEquals("checking byte " + j, 0, buffer[ j ]); - } - for (int j = offset; j < (offset + _buffer_size); j++) - { - assertEquals("checking byte " + j, _workbook_data[ j ], - buffer[ j ]); - } - for (int j = offset + _buffer_size; j < buffer.length; j++) - { - assertEquals("checking byte " + j, 0, buffer[ j ]); - } - offset += _buffer_size; - assertEquals("offset " + offset, _workbook_size - offset, - stream.available()); - } - assertEquals(_workbook_size % _buffer_size, stream.available()); - Arrays.fill(buffer, ( byte ) 0); - int count = stream.read(buffer, offset, - _workbook_size % _buffer_size); - - assertEquals(_workbook_size % _buffer_size, count); - for (int j = 0; j < offset; j++) - { - assertEquals("checking byte " + j, 0, buffer[ j ]); - } - for (int j = offset; j < buffer.length; j++) - { - assertEquals("checking byte " + j, _workbook_data[ j ], - buffer[ j ]); - } - assertEquals(_workbook_size, offset + count); - for (int j = count; j < offset; j++) - { - assertEquals("byte " + j, 0, buffer[ j ]); - } - - assertEquals(-1, stream.read(buffer, 0, 1)); - stream.close(); - try { - stream.read(buffer, 0, 1); - fail("Should have caught IOException"); - } catch (IOException ignored) { - // as expected - } - } - } - - /** - * Tests that we can skip within the stream - */ - public void testSkip() throws IOException { - DocumentInputStream[] streams = new DocumentInputStream[] { - new DocumentInputStream(_workbook_o), - new NDocumentInputStream(_workbook_n) - }; - for(DocumentInputStream stream : streams) { - assertEquals(_workbook_size, stream.available()); - int count = stream.available(); - - while (stream.available() >= _buffer_size) { - assertEquals(_buffer_size, stream.skip(_buffer_size)); - count -= _buffer_size; - assertEquals(count, stream.available()); - } - assertEquals(_workbook_size % _buffer_size, - stream.skip(_buffer_size)); - assertEquals(0, stream.available()); - stream.reset(); - assertEquals(_workbook_size, stream.available()); - assertEquals(_workbook_size, stream.skip(_workbook_size * 2)); - assertEquals(0, stream.available()); - stream.reset(); - assertEquals(_workbook_size, stream.available()); - assertEquals(_workbook_size, - stream.skip(2 + ( long ) Integer.MAX_VALUE)); - assertEquals(0, stream.available()); - } - } - - /** - * Test that we can read files at multiple levels down the tree - */ - public void testReadMultipleTreeLevels() throws Exception { - final POIDataSamples _samples = POIDataSamples.getPublisherInstance(); - File sample = _samples.getFile("Sample.pub"); - - DocumentInputStream stream; - - NPOIFSFileSystem npoifs = new NPOIFSFileSystem(sample); - try { - OPOIFSFileSystem opoifs = new OPOIFSFileSystem(new FileInputStream(sample)); - - // Ensure we have what we expect on the root - assertEquals(npoifs, npoifs.getRoot().getNFileSystem()); - assertEquals(npoifs, npoifs.getRoot().getFileSystem()); - assertEquals(null, npoifs.getRoot().getOFileSystem()); - assertEquals(null, opoifs.getRoot().getFileSystem()); - assertEquals(opoifs, opoifs.getRoot().getOFileSystem()); - assertEquals(null, opoifs.getRoot().getNFileSystem()); - - // Check inside - for(DirectoryNode root : new DirectoryNode[] { opoifs.getRoot(), npoifs.getRoot() }) { - // Top Level - Entry top = root.getEntry("Contents"); - assertEquals(true, top.isDocumentEntry()); - stream = root.createDocumentInputStream(top); - stream.read(); - - // One Level Down - DirectoryNode escher = (DirectoryNode)root.getEntry("Escher"); - Entry one = escher.getEntry("EscherStm"); - assertEquals(true, one.isDocumentEntry()); - stream = escher.createDocumentInputStream(one); - stream.read(); - - // Two Levels Down - DirectoryNode quill = (DirectoryNode)root.getEntry("Quill"); - DirectoryNode quillSub = (DirectoryNode)quill.getEntry("QuillSub"); - Entry two = quillSub.getEntry("CONTENTS"); - assertEquals(true, two.isDocumentEntry()); - stream = quillSub.createDocumentInputStream(two); - stream.read(); - } - } finally { - npoifs.close(); - } - } -} diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestDocumentNode.java b/src/testcases/org/apache/poi/poifs/filesystem/TestDocumentNode.java deleted file mode 100644 index 69d167793..000000000 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestDocumentNode.java +++ /dev/null @@ -1,73 +0,0 @@ - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.filesystem; - -import java.io.*; - -import junit.framework.*; - -import org.apache.poi.poifs.property.DirectoryProperty; -import org.apache.poi.poifs.property.DocumentProperty; -import org.apache.poi.poifs.storage.RawDataBlock; - -/** - * Class to test DocumentNode functionality - * - * @author Marc Johnson - */ -public final class TestDocumentNode extends TestCase { - - /** - * test constructor - */ - public void testConstructor() throws IOException { - DirectoryProperty property1 = new DirectoryProperty("directory"); - RawDataBlock[] rawBlocks = new RawDataBlock[ 4 ]; - ByteArrayInputStream stream = - new ByteArrayInputStream(new byte[ 2048 ]); - - for (int j = 0; j < 4; j++) - { - rawBlocks[ j ] = new RawDataBlock(stream); - } - OPOIFSDocument document = new OPOIFSDocument("document", rawBlocks, - 2000); - DocumentProperty property2 = document.getDocumentProperty(); - DirectoryNode parent = new DirectoryNode(property1, (POIFSFileSystem)null, null); - DocumentNode node = new DocumentNode(property2, parent); - - // verify we can retrieve the document - assertEquals(property2.getDocument(), node.getDocument()); - - // verify we can get the size - assertEquals(property2.getSize(), node.getSize()); - - // verify isDocumentEntry returns true - assertTrue(node.isDocumentEntry()); - - // verify isDirectoryEntry returns false - assertTrue(!node.isDirectoryEntry()); - - // verify getName behaves correctly - assertEquals(property2.getName(), node.getName()); - - // verify getParent behaves correctly - assertEquals(parent, node.getParent()); - } -} diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestDocumentOutputStream.java b/src/testcases/org/apache/poi/poifs/filesystem/TestDocumentOutputStream.java deleted file mode 100644 index 7404b240e..000000000 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestDocumentOutputStream.java +++ /dev/null @@ -1,175 +0,0 @@ - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.filesystem; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.Arrays; - -import org.junit.Test; - -/** - * Class to test DocumentOutputStream functionality - */ -public final class TestDocumentOutputStream { - - /** - * test write(int) behavior - */ - @Test - public void testWrite1() throws IOException { - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - DocumentOutputStream dstream = new DocumentOutputStream(stream, 25); - - for (int j = 0; j < 25; j++) - { - dstream.write(j); - } - try - { - dstream.write(0); - fail("Should have caught IOException"); - } - catch (IOException ignored) - { - } - byte[] output = stream.toByteArray(); - - assertEquals(25, output.length); - for (int j = 0; j < 25; j++) - { - assertEquals(( byte ) j, output[ j ]); - } - dstream.close(); - stream.close(); - } - - /** - * test write(byte[]) behavior - */ - @Test - public void testWrite2() throws IOException { - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - DocumentOutputStream dstream = new DocumentOutputStream(stream, 25); - - for (int j = 0; j < 6; j++) - { - byte[] array = new byte[ 4 ]; - - Arrays.fill(array, ( byte ) j); - dstream.write(array); - } - try - { - byte[] array = new byte[ 4 ]; - - Arrays.fill(array, ( byte ) 7); - dstream.write(array); - fail("Should have caught IOException"); - } - catch (IOException ignored) - { - } - byte[] output = stream.toByteArray(); - - assertEquals(24, output.length); - for (int j = 0; j < 6; j++) - { - for (int k = 0; k < 4; k++) - { - assertEquals(String.valueOf((j * 4) + k), ( byte ) j, - output[ (j * 4) + k ]); - } - } - dstream.close(); - stream.close(); - } - - /** - * test write(byte[], int, int) behavior - */ - @Test - public void testWrite3() throws IOException { - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - DocumentOutputStream dstream = new DocumentOutputStream(stream, 25); - byte[] array = new byte[ 50 ]; - - for (int j = 0; j < 50; j++) - { - array[ j ] = ( byte ) j; - } - dstream.write(array, 1, 25); - try - { - dstream.write(array, 0, 1); - fail("Should have caught IOException"); - } - catch (IOException ignored) - { - } - byte[] output = stream.toByteArray(); - - assertEquals(25, output.length); - for (int j = 0; j < 25; j++) - { - assertEquals(( byte ) (j + 1), output[ j ]); - } - dstream.close(); - stream.close(); - } - - /** - * test writeFiller() - */ - @Test - public void testWriteFiller() throws IOException { - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - DocumentOutputStream dstream = new DocumentOutputStream(stream, 25); - - for (int j = 0; j < 25; j++) - { - dstream.write(j); - } - try - { - dstream.write(0); - fail("Should have caught IOException"); - } - catch (IOException ignored) - { - } - dstream.writeFiller(100, ( byte ) 0xff); - byte[] output = stream.toByteArray(); - - assertEquals(100, output.length); - for (int j = 0; j < 25; j++) - { - assertEquals(( byte ) j, output[ j ]); - } - for (int j = 25; j < 100; j++) - { - assertEquals(String.valueOf(j), ( byte ) 0xff, output[ j ]); - } - dstream.close(); - stream.close(); - } -} diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestEmptyDocument.java b/src/testcases/org/apache/poi/poifs/filesystem/TestEmptyDocument.java deleted file mode 100644 index 9c7b688b5..000000000 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestEmptyDocument.java +++ /dev/null @@ -1,130 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.filesystem; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.junit.Test; - -public final class TestEmptyDocument { - private static final POILogger LOG = POILogFactory.getLogger(TestEmptyDocument.class); - - @Test - public void testSingleEmptyDocument() throws IOException { - POIFSFileSystem fs = new POIFSFileSystem(); - DirectoryEntry dir = fs.getRoot(); - dir.createDocument("Foo", new ByteArrayInputStream(new byte[] {})); - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - fs.writeFilesystem(out); - new POIFSFileSystem(new ByteArrayInputStream(out.toByteArray())).close(); - fs.close(); - } - - @Test - public void testSingleEmptyDocumentEvent() throws IOException { - POIFSFileSystem fs = new POIFSFileSystem(); - DirectoryEntry dir = fs.getRoot(); - dir.createDocument("Foo", 0, new POIFSWriterListener() { - @Override - public void processPOIFSWriterEvent(POIFSWriterEvent event) { - LOG.log(POILogger.WARN, "written"); - } - }); - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - fs.writeFilesystem(out); - new POIFSFileSystem(new ByteArrayInputStream(out.toByteArray())).close(); - fs.close(); - } - - @Test - public void testEmptyDocumentWithFriend() throws IOException { - POIFSFileSystem fs = new POIFSFileSystem(); - DirectoryEntry dir = fs.getRoot(); - dir.createDocument("Bar", new ByteArrayInputStream(new byte[] { 0 })); - dir.createDocument("Foo", new ByteArrayInputStream(new byte[] {})); - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - fs.writeFilesystem(out); - new POIFSFileSystem(new ByteArrayInputStream(out.toByteArray())).close(); - fs.close(); - } - - @Test - public void testEmptyDocumentEventWithFriend() throws IOException { - POIFSFileSystem fs = new POIFSFileSystem(); - DirectoryEntry dir = fs.getRoot(); - dir.createDocument("Bar", 1, new POIFSWriterListener() { - @Override - public void processPOIFSWriterEvent(POIFSWriterEvent event) { - try { - event.getStream().write(0); - } catch (IOException exception) { - throw new RuntimeException("exception on write: " + exception); - } - } - }); - dir.createDocument("Foo", 0, new POIFSWriterListener() { - @Override - public void processPOIFSWriterEvent(POIFSWriterEvent event) { - } - }); - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - fs.writeFilesystem(out); - new POIFSFileSystem(new ByteArrayInputStream(out.toByteArray())).close(); - fs.close(); - } - - @Test - public void testEmptyDocumentBug11744() throws Exception { - byte[] testData = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; - - POIFSFileSystem fs = new POIFSFileSystem(); - fs.createDocument(new ByteArrayInputStream(new byte[0]), "Empty"); - fs.createDocument(new ByteArrayInputStream(testData), "NotEmpty"); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - fs.writeFilesystem(out); - out.toByteArray(); - fs.close(); - - // This line caused the error. - fs = new POIFSFileSystem(new ByteArrayInputStream(out.toByteArray())); - - DocumentEntry entry = (DocumentEntry) fs.getRoot().getEntry("Empty"); - assertEquals("Expected zero size", 0, entry.getSize()); - byte[] actualReadbackData; - actualReadbackData = IOUtils.toByteArray(new DocumentInputStream(entry)); - assertEquals("Expected zero read from stream", 0, actualReadbackData.length); - - entry = (DocumentEntry) fs.getRoot().getEntry("NotEmpty"); - actualReadbackData = IOUtils.toByteArray(new DocumentInputStream(entry)); - assertEquals("Expected size was wrong", testData.length, entry.getSize()); - assertArrayEquals("Expected same data read from stream", testData, actualReadbackData); - fs.close(); - } -} diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestEntryUtils.java b/src/testcases/org/apache/poi/poifs/filesystem/TestEntryUtils.java deleted file mode 100644 index da3e38392..000000000 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestEntryUtils.java +++ /dev/null @@ -1,208 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.filesystem; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.junit.Test; - -public class TestEntryUtils { - private static final byte[] dataSmallA = new byte[] { 12, 42, 11, -12, -121 }; - private static final byte[] dataSmallB = new byte[] { 11, 73, 21, -92, -103 }; - - @Test - public void testCopyRecursively() throws IOException { - POIFSFileSystem fsD = new POIFSFileSystem(); - POIFSFileSystem fs = new POIFSFileSystem(); - DirectoryEntry dirA = fs.createDirectory("DirA"); - DirectoryEntry dirB = fs.createDirectory("DirB"); - - DocumentEntry entryR = fs.createDocument(new ByteArrayInputStream(dataSmallA), "EntryRoot"); - DocumentEntry entryA1 = dirA.createDocument("EntryA1", new ByteArrayInputStream(dataSmallA)); - DocumentEntry entryA2 = dirA.createDocument("EntryA2", new ByteArrayInputStream(dataSmallB)); - - // Copy docs - assertEquals(0, fsD.getRoot().getEntryCount()); - EntryUtils.copyNodeRecursively(entryR, fsD.getRoot()); - - assertEquals(1, fsD.getRoot().getEntryCount()); - assertNotNull(fsD.getRoot().getEntry("EntryRoot")); - - EntryUtils.copyNodeRecursively(entryA1, fsD.getRoot()); - assertEquals(2, fsD.getRoot().getEntryCount()); - assertNotNull(fsD.getRoot().getEntry("EntryRoot")); - assertNotNull(fsD.getRoot().getEntry("EntryA1")); - - EntryUtils.copyNodeRecursively(entryA2, fsD.getRoot()); - assertEquals(3, fsD.getRoot().getEntryCount()); - assertNotNull(fsD.getRoot().getEntry("EntryRoot")); - assertNotNull(fsD.getRoot().getEntry("EntryA1")); - assertNotNull(fsD.getRoot().getEntry("EntryA2")); - - fsD.close(); - - // Copy directories - fsD = new POIFSFileSystem(); - assertEquals(0, fsD.getRoot().getEntryCount()); - - EntryUtils.copyNodeRecursively(dirB, fsD.getRoot()); - assertEquals(1, fsD.getRoot().getEntryCount()); - assertNotNull(fsD.getRoot().getEntry("DirB")); - assertEquals(0, ((DirectoryEntry)fsD.getRoot().getEntry("DirB")).getEntryCount()); - - EntryUtils.copyNodeRecursively(dirA, fsD.getRoot()); - assertEquals(2, fsD.getRoot().getEntryCount()); - assertNotNull(fsD.getRoot().getEntry("DirB")); - assertEquals(0, ((DirectoryEntry)fsD.getRoot().getEntry("DirB")).getEntryCount()); - assertNotNull(fsD.getRoot().getEntry("DirA")); - assertEquals(2, ((DirectoryEntry)fsD.getRoot().getEntry("DirA")).getEntryCount()); - fsD.close(); - - // Copy the whole lot - fsD = new POIFSFileSystem(); - assertEquals(0, fsD.getRoot().getEntryCount()); - - EntryUtils.copyNodes(fs, fsD, new ArrayList()); - assertEquals(3, fsD.getRoot().getEntryCount()); - assertNotNull(fsD.getRoot().getEntry(dirA.getName())); - assertNotNull(fsD.getRoot().getEntry(dirB.getName())); - assertNotNull(fsD.getRoot().getEntry(entryR.getName())); - assertEquals(0, ((DirectoryEntry)fsD.getRoot().getEntry("DirB")).getEntryCount()); - assertEquals(2, ((DirectoryEntry)fsD.getRoot().getEntry("DirA")).getEntryCount()); - fsD.close(); - fs.close(); - } - - @Test - public void testAreDocumentsIdentical() throws IOException { - POIFSFileSystem fs = new POIFSFileSystem(); - DirectoryEntry dirA = fs.createDirectory("DirA"); - DirectoryEntry dirB = fs.createDirectory("DirB"); - - DocumentEntry entryA1 = dirA.createDocument("Entry1", new ByteArrayInputStream(dataSmallA)); - DocumentEntry entryA1b = dirA.createDocument("Entry1b", new ByteArrayInputStream(dataSmallA)); - DocumentEntry entryA2 = dirA.createDocument("Entry2", new ByteArrayInputStream(dataSmallB)); - DocumentEntry entryB1 = dirB.createDocument("Entry1", new ByteArrayInputStream(dataSmallA)); - - - // Names must match - assertEquals(false, entryA1.getName().equals(entryA1b.getName())); - assertEquals(false, EntryUtils.areDocumentsIdentical(entryA1, entryA1b)); - - // Contents must match - assertEquals(false, EntryUtils.areDocumentsIdentical(entryA1, entryA2)); - - // Parents don't matter if contents + names are the same - assertEquals(false, entryA1.getParent().equals(entryB1.getParent())); - assertEquals(true, EntryUtils.areDocumentsIdentical(entryA1, entryB1)); - - - // Can work with NPOIFS + POIFS - ByteArrayOutputStream tmpO = new ByteArrayOutputStream(); - fs.writeFilesystem(tmpO); - - ByteArrayInputStream tmpI = new ByteArrayInputStream(tmpO.toByteArray()); - NPOIFSFileSystem nfs = new NPOIFSFileSystem(tmpI); - - DirectoryEntry dN1 = (DirectoryEntry)nfs.getRoot().getEntry("DirA"); - DirectoryEntry dN2 = (DirectoryEntry)nfs.getRoot().getEntry("DirB"); - DocumentEntry eNA1 = (DocumentEntry)dN1.getEntry(entryA1.getName()); - DocumentEntry eNA2 = (DocumentEntry)dN1.getEntry(entryA2.getName()); - DocumentEntry eNB1 = (DocumentEntry)dN2.getEntry(entryB1.getName()); - - assertEquals(false, EntryUtils.areDocumentsIdentical(eNA1, eNA2)); - assertEquals(true, EntryUtils.areDocumentsIdentical(eNA1, eNB1)); - - assertEquals(false, EntryUtils.areDocumentsIdentical(eNA1, entryA1b)); - assertEquals(false, EntryUtils.areDocumentsIdentical(eNA1, entryA2)); - - assertEquals(true, EntryUtils.areDocumentsIdentical(eNA1, entryA1)); - assertEquals(true, EntryUtils.areDocumentsIdentical(eNA1, entryB1)); - nfs.close(); - fs.close(); - } - - @Test - public void testAreDirectoriesIdentical() throws IOException { - POIFSFileSystem fs = new POIFSFileSystem(); - DirectoryEntry dirA = fs.createDirectory("DirA"); - DirectoryEntry dirB = fs.createDirectory("DirB"); - - // Names must match - assertEquals(false, EntryUtils.areDirectoriesIdentical(dirA, dirB)); - - // Empty dirs are fine - DirectoryEntry dirA1 = dirA.createDirectory("TheDir"); - DirectoryEntry dirB1 = dirB.createDirectory("TheDir"); - assertEquals(0, dirA1.getEntryCount()); - assertEquals(0, dirB1.getEntryCount()); - assertEquals(true, EntryUtils.areDirectoriesIdentical(dirA1, dirB1)); - - // Otherwise children must match - dirA1.createDocument("Entry1", new ByteArrayInputStream(dataSmallA)); - assertEquals(false, EntryUtils.areDirectoriesIdentical(dirA1, dirB1)); - - dirB1.createDocument("Entry1", new ByteArrayInputStream(dataSmallA)); - assertEquals(true, EntryUtils.areDirectoriesIdentical(dirA1, dirB1)); - - dirA1.createDirectory("DD"); - assertEquals(false, EntryUtils.areDirectoriesIdentical(dirA1, dirB1)); - dirB1.createDirectory("DD"); - assertEquals(true, EntryUtils.areDirectoriesIdentical(dirA1, dirB1)); - - - // Excludes support - List excl = Arrays.asList(new String[] {"Ignore1", "IgnDir/Ign2"}); - FilteringDirectoryNode fdA = new FilteringDirectoryNode(dirA1, excl); - FilteringDirectoryNode fdB = new FilteringDirectoryNode(dirB1, excl); - - assertEquals(true, EntryUtils.areDirectoriesIdentical(fdA, fdB)); - - // Add an ignored doc, no notice is taken - fdA.createDocument("Ignore1", new ByteArrayInputStream(dataSmallA)); - assertEquals(true, EntryUtils.areDirectoriesIdentical(fdA, fdB)); - - // Add a directory with filtered contents, not the same - DirectoryEntry dirAI = dirA1.createDirectory("IgnDir"); - assertEquals(false, EntryUtils.areDirectoriesIdentical(fdA, fdB)); - - DirectoryEntry dirBI = dirB1.createDirectory("IgnDir"); - assertEquals(true, EntryUtils.areDirectoriesIdentical(fdA, fdB)); - - // Add something to the filtered subdir that gets ignored - dirAI.createDocument("Ign2", new ByteArrayInputStream(dataSmallA)); - assertEquals(true, EntryUtils.areDirectoriesIdentical(fdA, fdB)); - - // And something that doesn't - dirAI.createDocument("IgnZZ", new ByteArrayInputStream(dataSmallA)); - assertEquals(false, EntryUtils.areDirectoriesIdentical(fdA, fdB)); - - dirBI.createDocument("IgnZZ", new ByteArrayInputStream(dataSmallA)); - assertEquals(true, EntryUtils.areDirectoriesIdentical(fdA, fdB)); - - fs.close(); - } -} diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestFileSystemBugs.java b/src/testcases/org/apache/poi/poifs/filesystem/TestFileSystemBugs.java deleted file mode 100644 index 2bdcb0052..000000000 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestFileSystemBugs.java +++ /dev/null @@ -1,187 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.filesystem; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import junit.framework.TestCase; - -import org.apache.poi.POIDataSamples; - -/** - * Tests bugs across both POIFSFileSystem and NPOIFSFileSystem - */ -public final class TestFileSystemBugs extends TestCase { - protected static POIDataSamples _samples = POIDataSamples.getPOIFSInstance(); - protected static POIDataSamples _ssSamples = POIDataSamples.getSpreadSheetInstance(); - - protected List openedFSs; - @Override - protected void tearDown() throws Exception { - if (openedFSs != null && !openedFSs.isEmpty()) { - for (NPOIFSFileSystem fs : openedFSs) { - try { - fs.close(); - } catch (Exception e) { - System.err.println("Error closing FS: " + e); - } - } - } - openedFSs = null; - } - protected DirectoryNode[] openSample(String name, boolean oldFails) throws Exception { - return openSamples(new InputStream[] { - _samples.openResourceAsStream(name), - _samples.openResourceAsStream(name) - }, oldFails); - } - protected DirectoryNode[] openSSSample(String name, boolean oldFails) throws Exception { - return openSamples(new InputStream[] { - _ssSamples.openResourceAsStream(name), - _ssSamples.openResourceAsStream(name) - }, oldFails); - } - protected DirectoryNode[] openSamples(InputStream[] inps, boolean oldFails) throws Exception { - NPOIFSFileSystem nfs = new NPOIFSFileSystem(inps[0]); - if (openedFSs == null) openedFSs = new ArrayList(); - openedFSs.add(nfs); - - OPOIFSFileSystem ofs = null; - try { - ofs = new OPOIFSFileSystem(inps[1]); - if (oldFails) fail("POIFSFileSystem should have failed but didn't"); - } catch (Exception e) { - if (!oldFails) throw e; - } - - if (ofs == null) return new DirectoryNode[] { nfs.getRoot() }; - return new DirectoryNode[] { ofs.getRoot(), nfs.getRoot() }; - } - - /** - * Test that we can open files that come via Lotus notes. - * These have a top level directory without a name.... - */ - public void testNotesOLE2Files() throws Exception { - // Check the contents - for (DirectoryNode root : openSample("Notes.ole2", false)) { - assertEquals(1, root.getEntryCount()); - - Entry entry = root.getEntries().next(); - assertTrue(entry.isDirectoryEntry()); - assertTrue(entry instanceof DirectoryEntry); - - // The directory lacks a name! - DirectoryEntry dir = (DirectoryEntry)entry; - assertEquals("", dir.getName()); - - // Has two children - assertEquals(2, dir.getEntryCount()); - - // Check them - Iterator it = dir.getEntries(); - entry = it.next(); - assertEquals(true, entry.isDocumentEntry()); - assertEquals("\u0001Ole10Native", entry.getName()); - - entry = it.next(); - assertEquals(true, entry.isDocumentEntry()); - assertEquals("\u0001CompObj", entry.getName()); - } - } - - /** - * Ensure that a file with a corrupted property in the - * properties table can still be loaded, and the remaining - * properties used - * Note - only works for NPOIFSFileSystem, POIFSFileSystem - * can't cope with this level of corruption - */ - public void testCorruptedProperties() throws Exception { - for (DirectoryNode root : openSample("unknown_properties.msg", true)) { - assertEquals(42, root.getEntryCount()); - } - } - - /** - * With heavily nested documents, ensure we still re-write the same - */ - public void testHeavilyNestedReWrite() throws Exception { - for (DirectoryNode root : openSSSample("ex42570-20305.xls", false)) { - // Record the structure - Map entries = new HashMap(); - fetchSizes("/", root, entries); - - // Prepare to copy - DirectoryNode dest; - if (root.getNFileSystem() != null) { - dest = (new NPOIFSFileSystem()).getRoot(); - } else { - dest = (new OPOIFSFileSystem()).getRoot(); - } - - // Copy over - EntryUtils.copyNodes(root, dest); - - // Re-load, always as NPOIFS - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - if (root.getNFileSystem() != null) { - root.getNFileSystem().writeFilesystem(baos); - } else { - root.getOFileSystem().writeFilesystem(baos); - } - NPOIFSFileSystem read = new NPOIFSFileSystem( - new ByteArrayInputStream(baos.toByteArray())); - - // Check the structure matches - checkSizes("/", read.getRoot(), entries); - } - } - private void fetchSizes(String path, DirectoryNode dir, Map entries) { - for (Entry entry : dir) { - if (entry instanceof DirectoryNode) { - String ourPath = path + entry.getName() + "/"; - entries.put(ourPath, -1); - fetchSizes(ourPath, (DirectoryNode)entry, entries); - } else { - DocumentNode doc = (DocumentNode)entry; - entries.put(path+entry.getName(), doc.getSize()); - } - } - } - private void checkSizes(String path, DirectoryNode dir, Map entries) { - for (Entry entry : dir) { - if (entry instanceof DirectoryNode) { - String ourPath = path + entry.getName() + "/"; - assertTrue(entries.containsKey(ourPath)); - assertEquals(-1, entries.get(ourPath).intValue()); - checkSizes(ourPath, (DirectoryNode)entry, entries); - } else { - DocumentNode doc = (DocumentNode)entry; - assertEquals(entries.get(path+entry.getName()).intValue(), doc.getSize()); - } - } - } -} diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestFilteringDirectoryNode.java b/src/testcases/org/apache/poi/poifs/filesystem/TestFilteringDirectoryNode.java deleted file mode 100644 index bef0281f2..000000000 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestFilteringDirectoryNode.java +++ /dev/null @@ -1,172 +0,0 @@ - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.filesystem; - -import java.io.ByteArrayInputStream; -import java.io.FileNotFoundException; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; - -import junit.framework.TestCase; - -/** - * Class to test FilteringDirectoryNode functionality - */ -public final class TestFilteringDirectoryNode extends TestCase { - private POIFSFileSystem fs; - private DirectoryEntry dirA; - private DirectoryEntry dirAA; - private DirectoryEntry dirB; - private DocumentEntry eRoot; - private DocumentEntry eA; - private DocumentEntry eAA; - - @Override - protected void setUp() throws Exception { - fs = new POIFSFileSystem(); - dirA = fs.createDirectory("DirA"); - dirB = fs.createDirectory("DirB"); - dirAA = dirA.createDirectory("DirAA"); - eRoot = fs.getRoot().createDocument("Root", new ByteArrayInputStream(new byte[] {})); - eA = dirA.createDocument("NA", new ByteArrayInputStream(new byte[] {})); - eAA = dirAA.createDocument("NAA", new ByteArrayInputStream(new byte[] {})); - } - - public void testNoFiltering() throws Exception { - FilteringDirectoryNode d = new FilteringDirectoryNode(fs.getRoot(), new HashSet()); - assertEquals(3, d.getEntryCount()); - assertEquals(dirA.getName(), d.getEntry(dirA.getName()).getName()); - - assertEquals(true, d.getEntry(dirA.getName()).isDirectoryEntry()); - assertEquals(false, d.getEntry(dirA.getName()).isDocumentEntry()); - - assertEquals(true, d.getEntry(dirB.getName()).isDirectoryEntry()); - assertEquals(false, d.getEntry(dirB.getName()).isDocumentEntry()); - - assertEquals(false, d.getEntry(eRoot.getName()).isDirectoryEntry()); - assertEquals(true, d.getEntry(eRoot.getName()).isDocumentEntry()); - - Iterator i = d.getEntries(); - assertEquals(dirA, i.next()); - assertEquals(dirB, i.next()); - assertEquals(eRoot, i.next()); - assertEquals(null, i.next()); - } - - public void testChildFiltering() throws Exception { - List excl = Arrays.asList(new String[] {"NotThere","AlsoNotThere", eRoot.getName()}); - FilteringDirectoryNode d = new FilteringDirectoryNode(fs.getRoot(), excl); - - assertEquals(2, d.getEntryCount()); - assertEquals(true, d.hasEntry(dirA.getName())); - assertEquals(true, d.hasEntry(dirB.getName())); - assertEquals(false, d.hasEntry(eRoot.getName())); - - assertEquals(dirA, d.getEntry(dirA.getName())); - assertEquals(dirB, d.getEntry(dirB.getName())); - try { - d.getEntry(eRoot.getName()); - fail("Should be filtered"); - } catch(FileNotFoundException e) {} - - Iterator i = d.getEntries(); - assertEquals(dirA, i.next()); - assertEquals(dirB, i.next()); - assertEquals(null, i.next()); - - - // Filter more - excl = Arrays.asList(new String[] {"NotThere","AlsoNotThere", eRoot.getName(), dirA.getName()}); - d = new FilteringDirectoryNode(fs.getRoot(), excl); - - assertEquals(1, d.getEntryCount()); - assertEquals(false, d.hasEntry(dirA.getName())); - assertEquals(true, d.hasEntry(dirB.getName())); - assertEquals(false, d.hasEntry(eRoot.getName())); - - try { - d.getEntry(dirA.getName()); - fail("Should be filtered"); - } catch(FileNotFoundException e) {} - assertEquals(dirB, d.getEntry(dirB.getName())); - try { - d.getEntry(eRoot.getName()); - fail("Should be filtered"); - } catch(FileNotFoundException e) {} - - i = d.getEntries(); - assertEquals(dirB, i.next()); - assertEquals(null, i.next()); - - - // Filter everything - excl = Arrays.asList(new String[] {"NotThere", eRoot.getName(), dirA.getName(), dirB.getName()}); - d = new FilteringDirectoryNode(fs.getRoot(), excl); - - assertEquals(0, d.getEntryCount()); - assertEquals(false, d.hasEntry(dirA.getName())); - assertEquals(false, d.hasEntry(dirB.getName())); - assertEquals(false, d.hasEntry(eRoot.getName())); - - try { - d.getEntry(dirA.getName()); - fail("Should be filtered"); - } catch(FileNotFoundException e) {} - try { - d.getEntry(dirB.getName()); - fail("Should be filtered"); - } catch(FileNotFoundException e) {} - try { - d.getEntry(eRoot.getName()); - fail("Should be filtered"); - } catch(FileNotFoundException e) {} - - i = d.getEntries(); - assertEquals(null, i.next()); - } - - public void testNestedFiltering() throws Exception { - List excl = Arrays.asList(new String[] { - dirA.getName()+"/"+"MadeUp", - dirA.getName()+"/"+eA.getName(), - dirA.getName()+"/"+dirAA.getName()+"/Test", - eRoot.getName() - }); - FilteringDirectoryNode d = new FilteringDirectoryNode(fs.getRoot(), excl); - - // Check main - assertEquals(2, d.getEntryCount()); - assertEquals(true, d.hasEntry(dirA.getName())); - assertEquals(true, d.hasEntry(dirB.getName())); - assertEquals(false, d.hasEntry(eRoot.getName())); - - // Check filtering down - assertEquals(true, d.getEntry(dirA.getName()) instanceof FilteringDirectoryNode); - assertEquals(false, d.getEntry(dirB.getName()) instanceof FilteringDirectoryNode); - - DirectoryEntry fdA = (DirectoryEntry)d.getEntry(dirA.getName()); - assertEquals(false, fdA.hasEntry(eA.getName())); - assertEquals(true, fdA.hasEntry(dirAA.getName())); - - DirectoryEntry fdAA = (DirectoryEntry)fdA.getEntry(dirAA.getName()); - assertEquals(true, fdAA.hasEntry(eAA.getName())); - } -} diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestNPOIFSFileSystem.java b/src/testcases/org/apache/poi/poifs/filesystem/TestNPOIFSFileSystem.java deleted file mode 100644 index 24973f977..000000000 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestNPOIFSFileSystem.java +++ /dev/null @@ -1,1696 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.filesystem; - -import static org.hamcrest.core.IsCollectionContaining.hasItem; -import static org.hamcrest.core.IsEqual.equalTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.ByteBuffer; -import java.util.Iterator; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hpsf.DocumentSummaryInformation; -import org.apache.poi.hpsf.PropertySet; -import org.apache.poi.hpsf.PropertySetFactory; -import org.apache.poi.hpsf.SummaryInformation; -import org.apache.poi.poifs.common.POIFSConstants; -import org.apache.poi.poifs.property.DirectoryProperty; -import org.apache.poi.poifs.property.NPropertyTable; -import org.apache.poi.poifs.property.Property; -import org.apache.poi.poifs.property.RootProperty; -import org.apache.poi.poifs.storage.HeaderBlock; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.TempFile; -import org.junit.Assume; -import org.junit.Ignore; -import org.junit.Test; - -/** - * Tests for the new NIO POIFSFileSystem implementation - */ -public final class TestNPOIFSFileSystem { - private static final POIDataSamples _inst = POIDataSamples.getPOIFSInstance(); - - /** - * Returns test files with 512 byte and 4k block sizes, loaded - * both from InputStreams and Files - */ - protected NPOIFSFileSystem[] get512and4kFileAndInput() throws IOException { - NPOIFSFileSystem fsA = new NPOIFSFileSystem(_inst.getFile("BlockSize512.zvi")); - NPOIFSFileSystem fsB = new NPOIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi")); - NPOIFSFileSystem fsC = new NPOIFSFileSystem(_inst.getFile("BlockSize4096.zvi")); - NPOIFSFileSystem fsD = new NPOIFSFileSystem(_inst.openResourceAsStream("BlockSize4096.zvi")); - return new NPOIFSFileSystem[] {fsA,fsB,fsC,fsD}; - } - - protected static void assertBATCount(NPOIFSFileSystem fs, int expectedBAT, int expectedXBAT) throws IOException { - int foundBAT = 0; - int foundXBAT = 0; - int sz = (int)(fs.size() / fs.getBigBlockSize()); - for (int i=0; i 98 -> END - assertEquals(98, fs.getNextBlock(97)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(98)); - - - // Check the properties - NPropertyTable props = fs._get_property_table(); - assertEquals(90, props.getStartBlock()); - assertEquals(7, props.countBlocks()); - - // Root property tells us about the Mini Stream - RootProperty root = props.getRoot(); - assertEquals("Root Entry", root.getName()); - assertEquals(11564, root.getSize()); - assertEquals(0, root.getStartBlock()); - - // Check its children too - Property prop; - Iterator pi = root.getChildren(); - prop = pi.next(); - assertEquals("Thumbnail", prop.getName()); - prop = pi.next(); - assertEquals("\u0005DocumentSummaryInformation", prop.getName()); - prop = pi.next(); - assertEquals("\u0005SummaryInformation", prop.getName()); - prop = pi.next(); - assertEquals("Image", prop.getName()); - prop = pi.next(); - assertEquals("Tags", prop.getName()); - assertEquals(false, pi.hasNext()); - - - // Check the SBAT (Small Blocks FAT) was properly processed - NPOIFSMiniStore ministore = fs.getMiniStore(); - - // Verify we only got two SBAT blocks - ministore.getBATBlockAndIndex(0); - ministore.getBATBlockAndIndex(128); - try { - ministore.getBATBlockAndIndex(256); - fail("Should only be two SBATs, but a 3rd was found"); - } catch(IndexOutOfBoundsException e) {} - - // Verify a few offsets: 0->50 is a stream - for(int i=0; i<50; i++) { - assertEquals(i+1, ministore.getNextBlock(i)); - } - assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(50)); - - fs.close(); - } - - // Now with a simple 4096 block file - fsA = new NPOIFSFileSystem(_inst.getFile("BlockSize4096.zvi")); - fsB = new NPOIFSFileSystem(_inst.openResourceAsStream("BlockSize4096.zvi")); - for(NPOIFSFileSystem fs : new NPOIFSFileSystem[] {fsA,fsB}) { - // Check the FAT was properly processed - // Verify we only got one block - fs.getBATBlockAndIndex(0); - fs.getBATBlockAndIndex(1); - try { - fs.getBATBlockAndIndex(1040); - fail("Should only be one BAT, but a 2nd was found"); - } catch(IndexOutOfBoundsException e) {} - - // Verify a few next offsets - // 0 -> 1 -> 2 -> END - assertEquals(1, fs.getNextBlock(0)); - assertEquals(2, fs.getNextBlock(1)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(2)); - - - // Check the properties - NPropertyTable props = fs._get_property_table(); - assertEquals(12, props.getStartBlock()); - assertEquals(1, props.countBlocks()); - - // Root property tells us about the Mini Stream - RootProperty root = props.getRoot(); - assertEquals("Root Entry", root.getName()); - assertEquals(11564, root.getSize()); - assertEquals(0, root.getStartBlock()); - - // Check its children too - Property prop; - Iterator pi = root.getChildren(); - prop = pi.next(); - assertEquals("Thumbnail", prop.getName()); - prop = pi.next(); - assertEquals("\u0005DocumentSummaryInformation", prop.getName()); - prop = pi.next(); - assertEquals("\u0005SummaryInformation", prop.getName()); - prop = pi.next(); - assertEquals("Image", prop.getName()); - prop = pi.next(); - assertEquals("Tags", prop.getName()); - assertEquals(false, pi.hasNext()); - - - // Check the SBAT (Small Blocks FAT) was properly processed - NPOIFSMiniStore ministore = fs.getMiniStore(); - - // Verify we only got one SBAT block - ministore.getBATBlockAndIndex(0); - ministore.getBATBlockAndIndex(128); - ministore.getBATBlockAndIndex(1023); - try { - ministore.getBATBlockAndIndex(1024); - fail("Should only be one SBAT, but a 2nd was found"); - } catch(IndexOutOfBoundsException e) {} - - // Verify a few offsets: 0->50 is a stream - for(int i=0; i<50; i++) { - assertEquals(i+1, ministore.getNextBlock(i)); - } - assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(50)); - - fs.close(); - } - } - - /** - * Check that for a given block, we can correctly figure - * out what the next one is - */ - @Test - public void nextBlock() throws IOException { - NPOIFSFileSystem fsA = new NPOIFSFileSystem(_inst.getFile("BlockSize512.zvi")); - NPOIFSFileSystem fsB = new NPOIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi")); - for(NPOIFSFileSystem fs : new NPOIFSFileSystem[] {fsA,fsB}) { - // 0 -> 21 are simple - for(int i=0; i<21; i++) { - assertEquals(i+1, fs.getNextBlock(i)); - } - // 21 jumps to 89, then ends - assertEquals(89, fs.getNextBlock(21)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(89)); - - // 22 -> 88 simple sequential stream - for(int i=22; i<88; i++) { - assertEquals(i+1, fs.getNextBlock(i)); - } - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(88)); - - // 90 -> 96 is another stream - for(int i=90; i<96; i++) { - assertEquals(i+1, fs.getNextBlock(i)); - } - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(96)); - - // 97+98 is another - assertEquals(98, fs.getNextBlock(97)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(98)); - - // 99 is our FAT block - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(99)); - - // 100 onwards is free - for(int i=100; i 1 -> 2 -> end - assertEquals(1, fs.getNextBlock(0)); - assertEquals(2, fs.getNextBlock(1)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(2)); - - // 4 -> 11 then end - for(int i=4; i<11; i++) { - assertEquals(i+1, fs.getNextBlock(i)); - } - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(11)); - - fs.close(); - } - } - - /** - * Check we get the right data back for each block - */ - @Test - public void getBlock() throws IOException { - NPOIFSFileSystem fsA = new NPOIFSFileSystem(_inst.getFile("BlockSize512.zvi")); - NPOIFSFileSystem fsB = new NPOIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi")); - for(NPOIFSFileSystem fs : new NPOIFSFileSystem[] {fsA,fsB}) { - ByteBuffer b; - - // The 0th block is the first data block - b = fs.getBlockAt(0); - assertEquals((byte)0x9e, b.get()); - assertEquals((byte)0x75, b.get()); - assertEquals((byte)0x97, b.get()); - assertEquals((byte)0xf6, b.get()); - - // And the next block - b = fs.getBlockAt(1); - assertEquals((byte)0x86, b.get()); - assertEquals((byte)0x09, b.get()); - assertEquals((byte)0x22, b.get()); - assertEquals((byte)0xfb, b.get()); - - // Check the final block too - b = fs.getBlockAt(99); - assertEquals((byte)0x01, b.get()); - assertEquals((byte)0x00, b.get()); - assertEquals((byte)0x00, b.get()); - assertEquals((byte)0x00, b.get()); - assertEquals((byte)0x02, b.get()); - assertEquals((byte)0x00, b.get()); - assertEquals((byte)0x00, b.get()); - assertEquals((byte)0x00, b.get()); - - fs.close(); - } - - // Quick check on 4096 byte blocks too - fsA = new NPOIFSFileSystem(_inst.getFile("BlockSize4096.zvi")); - fsB = new NPOIFSFileSystem(_inst.openResourceAsStream("BlockSize4096.zvi")); - for(NPOIFSFileSystem fs : new NPOIFSFileSystem[] {fsA,fsB}) { - ByteBuffer b; - - // The 0th block is the first data block - b = fs.getBlockAt(0); - assertEquals((byte)0x9e, b.get()); - assertEquals((byte)0x75, b.get()); - assertEquals((byte)0x97, b.get()); - assertEquals((byte)0xf6, b.get()); - - // And the next block - b = fs.getBlockAt(1); - assertEquals((byte)0x00, b.get()); - assertEquals((byte)0x00, b.get()); - assertEquals((byte)0x03, b.get()); - assertEquals((byte)0x00, b.get()); - - // The 14th block is the FAT - b = fs.getBlockAt(14); - assertEquals((byte)0x01, b.get()); - assertEquals((byte)0x00, b.get()); - assertEquals((byte)0x00, b.get()); - assertEquals((byte)0x00, b.get()); - assertEquals((byte)0x02, b.get()); - assertEquals((byte)0x00, b.get()); - assertEquals((byte)0x00, b.get()); - assertEquals((byte)0x00, b.get()); - - fs.close(); - } - } - - /** - * Ask for free blocks where there are some already - * to be had from the FAT - */ - @Test - public void getFreeBlockWithSpare() throws IOException { - NPOIFSFileSystem fs = new NPOIFSFileSystem(_inst.getFile("BlockSize512.zvi")); - - // Our first BAT block has spares - assertEquals(true, fs.getBATBlockAndIndex(0).getBlock().hasFreeSectors()); - - // First free one is 100 - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(100)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(101)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(102)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(103)); - - // Ask, will get 100 - assertEquals(100, fs.getFreeBlock()); - - // Ask again, will still get 100 as not written to - assertEquals(100, fs.getFreeBlock()); - - // Allocate it, then ask again - fs.setNextBlock(100, POIFSConstants.END_OF_CHAIN); - assertEquals(101, fs.getFreeBlock()); - - // All done - fs.close(); - } - - /** - * Ask for free blocks where no free ones exist, and so the - * file needs to be extended and another BAT/XBAT added - */ - @Test - public void getFreeBlockWithNoneSpare() throws IOException { - NPOIFSFileSystem fs1 = new NPOIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi")); - int free; - - // We have one BAT at block 99 - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs1.getNextBlock(99)); - assertBATCount(fs1, 1, 0); - - // We've spare ones from 100 to 128 - for(int i=100; i<128; i++) { - assertEquals(POIFSConstants.UNUSED_BLOCK, fs1.getNextBlock(i)); - } - - // Check our BAT knows it's free - assertEquals(true, fs1.getBATBlockAndIndex(0).getBlock().hasFreeSectors()); - - // Allocate all the spare ones - for(int i=100; i<128; i++) { - fs1.setNextBlock(i, POIFSConstants.END_OF_CHAIN); - } - - // BAT is now full, but there's only the one - assertEquals(false, fs1.getBATBlockAndIndex(0).getBlock().hasFreeSectors()); - try { - assertEquals(false, fs1.getBATBlockAndIndex(128).getBlock().hasFreeSectors()); - fail("Should only be one BAT"); - } catch(IndexOutOfBoundsException e) {} - assertBATCount(fs1, 1, 0); - - - // Now ask for a free one, will need to extend the file - assertEquals(129, fs1.getFreeBlock()); - - assertEquals(false, fs1.getBATBlockAndIndex(0).getBlock().hasFreeSectors()); - assertEquals(true, fs1.getBATBlockAndIndex(128).getBlock().hasFreeSectors()); - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs1.getNextBlock(128)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs1.getNextBlock(129)); - - // We now have 2 BATs, but no XBATs - assertBATCount(fs1, 2, 0); - - - // Fill up to hold 109 BAT blocks - for(int i=0; i<109; i++) { - fs1.getFreeBlock(); - int startOffset = i*128; - while( fs1.getBATBlockAndIndex(startOffset).getBlock().hasFreeSectors() ) { - free = fs1.getFreeBlock(); - fs1.setNextBlock(free, POIFSConstants.END_OF_CHAIN); - } - } - - assertEquals(false, fs1.getBATBlockAndIndex(109*128-1).getBlock().hasFreeSectors()); - try { - assertEquals(false, fs1.getBATBlockAndIndex(109*128).getBlock().hasFreeSectors()); - fail("Should only be 109 BATs"); - } catch(IndexOutOfBoundsException e) {} - - // We now have 109 BATs, but no XBATs - assertBATCount(fs1, 109, 0); - - - // Ask for it to be written out, and check the header - HeaderBlock header = writeOutAndReadHeader(fs1); - assertEquals(109, header.getBATCount()); - assertEquals(0, header.getXBATCount()); - - - // Ask for another, will get our first XBAT - free = fs1.getFreeBlock(); - assertEquals(false, fs1.getBATBlockAndIndex(109*128-1).getBlock().hasFreeSectors()); - assertEquals(true, fs1.getBATBlockAndIndex(110*128-1).getBlock().hasFreeSectors()); - try { - assertEquals(false, fs1.getBATBlockAndIndex(110*128).getBlock().hasFreeSectors()); - fail("Should only be 110 BATs"); - } catch(IndexOutOfBoundsException e) {} - assertBATCount(fs1, 110, 1); - - header = writeOutAndReadHeader(fs1); - assertEquals(110, header.getBATCount()); - assertEquals(1, header.getXBATCount()); - - - // Fill the XBAT, which means filling 127 BATs - for(int i=109; i<109+127; i++) { - fs1.getFreeBlock(); - int startOffset = i*128; - while( fs1.getBATBlockAndIndex(startOffset).getBlock().hasFreeSectors() ) { - free = fs1.getFreeBlock(); - fs1.setNextBlock(free, POIFSConstants.END_OF_CHAIN); - } - assertBATCount(fs1, i+1, 1); - } - - // Should now have 109+127 = 236 BATs - assertEquals(false, fs1.getBATBlockAndIndex(236*128-1).getBlock().hasFreeSectors()); - try { - assertEquals(false, fs1.getBATBlockAndIndex(236*128).getBlock().hasFreeSectors()); - fail("Should only be 236 BATs"); - } catch(IndexOutOfBoundsException e) {} - assertBATCount(fs1, 236, 1); - - - // Ask for another, will get our 2nd XBAT - free = fs1.getFreeBlock(); - assertEquals(false, fs1.getBATBlockAndIndex(236*128-1).getBlock().hasFreeSectors()); - assertEquals(true, fs1.getBATBlockAndIndex(237*128-1).getBlock().hasFreeSectors()); - try { - assertEquals(false, fs1.getBATBlockAndIndex(237*128).getBlock().hasFreeSectors()); - fail("Should only be 237 BATs"); - } catch(IndexOutOfBoundsException e) {} - - - // Check the counts now - assertBATCount(fs1, 237, 2); - - // Check the header - header = writeOutAndReadHeader(fs1); - - - // Now, write it out, and read it back in again fully - NPOIFSFileSystem fs2 = writeOutAndReadBack(fs1); - fs1.close(); - - // Check that it is seen correctly - assertBATCount(fs2, 237, 2); - - assertEquals(false, fs2.getBATBlockAndIndex(236*128-1).getBlock().hasFreeSectors()); - assertEquals(true, fs2.getBATBlockAndIndex(237*128-1).getBlock().hasFreeSectors()); - try { - assertEquals(false, fs2.getBATBlockAndIndex(237*128).getBlock().hasFreeSectors()); - fail("Should only be 237 BATs"); - } catch(IndexOutOfBoundsException e) {} - - - // All done - fs2.close(); - } - - /** - * Test that we can correctly get the list of directory - * entries, and the details on the files in them - */ - @Test - public void listEntries() throws IOException { - for(NPOIFSFileSystem fs : get512and4kFileAndInput()) { - DirectoryEntry root = fs.getRoot(); - assertEquals(5, root.getEntryCount()); - - // Check by the names - Entry thumbnail = root.getEntry("Thumbnail"); - Entry dsi = root.getEntry("\u0005DocumentSummaryInformation"); - Entry si = root.getEntry("\u0005SummaryInformation"); - Entry image = root.getEntry("Image"); - Entry tags = root.getEntry("Tags"); - - assertEquals(false, thumbnail.isDirectoryEntry()); - assertEquals(false, dsi.isDirectoryEntry()); - assertEquals(false, si.isDirectoryEntry()); - assertEquals(true, image.isDirectoryEntry()); - assertEquals(false, tags.isDirectoryEntry()); - - // Check via the iterator - Iterator it = root.getEntries(); - assertEquals(thumbnail.getName(), it.next().getName()); - assertEquals(dsi.getName(), it.next().getName()); - assertEquals(si.getName(), it.next().getName()); - assertEquals(image.getName(), it.next().getName()); - assertEquals(tags.getName(), it.next().getName()); - - // Look inside another - DirectoryEntry imageD = (DirectoryEntry)image; - assertEquals(7, imageD.getEntryCount()); - - fs.close(); - } - } - - /** - * Tests that we can get the correct contents for - * a document in the filesystem - */ - @Test - public void getDocumentEntry() throws Exception { - for(NPOIFSFileSystem fs : get512and4kFileAndInput()) { - DirectoryEntry root = fs.getRoot(); - Entry si = root.getEntry("\u0005SummaryInformation"); - - assertEquals(true, si.isDocumentEntry()); - DocumentNode doc = (DocumentNode)si; - - // Check we can read it - assertContentsMatches(null, doc); - - // Now try to build the property set - DocumentInputStream inp = new NDocumentInputStream(doc); - PropertySet ps = PropertySetFactory.create(inp); - SummaryInformation inf = (SummaryInformation)ps; - - // Check some bits in it - assertEquals(null, inf.getApplicationName()); - assertEquals(null, inf.getAuthor()); - assertEquals(null, inf.getSubject()); - assertEquals(131333, inf.getOSVersion()); - - // Finish with this one - inp.close(); - - - // Try the other summary information - si = root.getEntry("\u0005DocumentSummaryInformation"); - assertEquals(true, si.isDocumentEntry()); - doc = (DocumentNode)si; - assertContentsMatches(null, doc); - - inp = new NDocumentInputStream(doc); - ps = PropertySetFactory.create(inp); - DocumentSummaryInformation dinf = (DocumentSummaryInformation)ps; - assertEquals(131333, dinf.getOSVersion()); - - fs.close(); - } - } - - /** - * Read a file, write it and read it again. - * Then, alter+add some streams, write and read - */ - @Test - public void readWriteRead() throws Exception { - SummaryInformation sinf = null; - DocumentSummaryInformation dinf = null; - DirectoryEntry root = null, testDir = null; - - for(NPOIFSFileSystem fs1 : get512and4kFileAndInput()) { - // Check we can find the entries we expect - root = fs1.getRoot(); - assertEquals(5, root.getEntryCount()); - assertThat(root.getEntryNames(), hasItem("Thumbnail")); - assertThat(root.getEntryNames(), hasItem("Image")); - assertThat(root.getEntryNames(), hasItem("Tags")); - assertThat(root.getEntryNames(), hasItem("\u0005DocumentSummaryInformation")); - assertThat(root.getEntryNames(), hasItem("\u0005SummaryInformation")); - - - // Write out, re-load - NPOIFSFileSystem fs2 = writeOutAndReadBack(fs1); - fs1.close(); - - // Check they're still there - root = fs2.getRoot(); - assertEquals(5, root.getEntryCount()); - assertThat(root.getEntryNames(), hasItem("Thumbnail")); - assertThat(root.getEntryNames(), hasItem("Image")); - assertThat(root.getEntryNames(), hasItem("Tags")); - assertThat(root.getEntryNames(), hasItem("\u0005DocumentSummaryInformation")); - assertThat(root.getEntryNames(), hasItem("\u0005SummaryInformation")); - - - // Check the contents of them - parse the summary block and check - sinf = (SummaryInformation)PropertySetFactory.create(new NDocumentInputStream( - (DocumentEntry)root.getEntry(SummaryInformation.DEFAULT_STREAM_NAME))); - assertEquals(131333, sinf.getOSVersion()); - - dinf = (DocumentSummaryInformation)PropertySetFactory.create(new NDocumentInputStream( - (DocumentEntry)root.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME))); - assertEquals(131333, dinf.getOSVersion()); - - - // Add a test mini stream - testDir = root.createDirectory("Testing 123"); - testDir.createDirectory("Testing 456"); - testDir.createDirectory("Testing 789"); - byte[] mini = new byte[] { 42, 0, 1, 2, 3, 4, 42 }; - testDir.createDocument("Mini", new ByteArrayInputStream(mini)); - - - // Write out, re-load - NPOIFSFileSystem fs3 = writeOutAndReadBack(fs2); - fs2.close(); - - root = fs3.getRoot(); - testDir = (DirectoryEntry)root.getEntry("Testing 123"); - assertEquals(6, root.getEntryCount()); - assertThat(root.getEntryNames(), hasItem("Thumbnail")); - assertThat(root.getEntryNames(), hasItem("Image")); - assertThat(root.getEntryNames(), hasItem("Tags")); - assertThat(root.getEntryNames(), hasItem("Testing 123")); - assertThat(root.getEntryNames(), hasItem("\u0005DocumentSummaryInformation")); - assertThat(root.getEntryNames(), hasItem("\u0005SummaryInformation")); - - - // Check old and new are there - sinf = (SummaryInformation)PropertySetFactory.create(new NDocumentInputStream( - (DocumentEntry)root.getEntry(SummaryInformation.DEFAULT_STREAM_NAME))); - assertEquals(131333, sinf.getOSVersion()); - - dinf = (DocumentSummaryInformation)PropertySetFactory.create(new NDocumentInputStream( - (DocumentEntry)root.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME))); - assertEquals(131333, dinf.getOSVersion()); - - assertContentsMatches(mini, (DocumentEntry)testDir.getEntry("Mini")); - - - // Write out and read once more, just to be sure - NPOIFSFileSystem fs4 = writeOutAndReadBack(fs3); - fs3.close(); - - root = fs4.getRoot(); - testDir = (DirectoryEntry)root.getEntry("Testing 123"); - assertEquals(6, root.getEntryCount()); - assertThat(root.getEntryNames(), hasItem("Thumbnail")); - assertThat(root.getEntryNames(), hasItem("Image")); - assertThat(root.getEntryNames(), hasItem("Tags")); - assertThat(root.getEntryNames(), hasItem("Testing 123")); - assertThat(root.getEntryNames(), hasItem("\u0005DocumentSummaryInformation")); - assertThat(root.getEntryNames(), hasItem("\u0005SummaryInformation")); - - sinf = (SummaryInformation)PropertySetFactory.create(new NDocumentInputStream( - (DocumentEntry)root.getEntry(SummaryInformation.DEFAULT_STREAM_NAME))); - assertEquals(131333, sinf.getOSVersion()); - - dinf = (DocumentSummaryInformation)PropertySetFactory.create(new NDocumentInputStream( - (DocumentEntry)root.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME))); - assertEquals(131333, dinf.getOSVersion()); - - assertContentsMatches(mini, (DocumentEntry)testDir.getEntry("Mini")); - - - // Add a full stream, delete a full stream - byte[] main4096 = new byte[4096]; - main4096[0] = -10; - main4096[4095] = -11; - testDir.createDocument("Normal4096", new ByteArrayInputStream(main4096)); - - root.getEntry("Tags").delete(); - - - // Write out, re-load - NPOIFSFileSystem fs5 = writeOutAndReadBack(fs4); - fs4.close(); - - // Check it's all there - root = fs5.getRoot(); - testDir = (DirectoryEntry)root.getEntry("Testing 123"); - assertEquals(5, root.getEntryCount()); - assertThat(root.getEntryNames(), hasItem("Thumbnail")); - assertThat(root.getEntryNames(), hasItem("Image")); - assertThat(root.getEntryNames(), hasItem("Testing 123")); - assertThat(root.getEntryNames(), hasItem("\u0005DocumentSummaryInformation")); - assertThat(root.getEntryNames(), hasItem("\u0005SummaryInformation")); - - - // Check old and new are there - sinf = (SummaryInformation)PropertySetFactory.create(new NDocumentInputStream( - (DocumentEntry)root.getEntry(SummaryInformation.DEFAULT_STREAM_NAME))); - assertEquals(131333, sinf.getOSVersion()); - - dinf = (DocumentSummaryInformation)PropertySetFactory.create(new NDocumentInputStream( - (DocumentEntry)root.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME))); - assertEquals(131333, dinf.getOSVersion()); - - assertContentsMatches(mini, (DocumentEntry)testDir.getEntry("Mini")); - assertContentsMatches(main4096, (DocumentEntry)testDir.getEntry("Normal4096")); - - - // Delete a directory, and add one more - testDir.getEntry("Testing 456").delete(); - testDir.createDirectory("Testing ABC"); - - - // Save - NPOIFSFileSystem fs6 = writeOutAndReadBack(fs5); - fs5.close(); - - // Check - root = fs6.getRoot(); - testDir = (DirectoryEntry)root.getEntry("Testing 123"); - - assertEquals(5, root.getEntryCount()); - assertThat(root.getEntryNames(), hasItem("Thumbnail")); - assertThat(root.getEntryNames(), hasItem("Image")); - assertThat(root.getEntryNames(), hasItem("Testing 123")); - assertThat(root.getEntryNames(), hasItem("\u0005DocumentSummaryInformation")); - assertThat(root.getEntryNames(), hasItem("\u0005SummaryInformation")); - - assertEquals(4, testDir.getEntryCount()); - assertThat(testDir.getEntryNames(), hasItem("Mini")); - assertThat(testDir.getEntryNames(), hasItem("Normal4096")); - assertThat(testDir.getEntryNames(), hasItem("Testing 789")); - assertThat(testDir.getEntryNames(), hasItem("Testing ABC")); - - - // Add another mini stream - byte[] mini2 = new byte[] { -42, 0, -1, -2, -3, -4, -42 }; - testDir.createDocument("Mini2", new ByteArrayInputStream(mini2)); - - // Save, load, check - NPOIFSFileSystem fs7 = writeOutAndReadBack(fs6); - fs6.close(); - - root = fs7.getRoot(); - testDir = (DirectoryEntry)root.getEntry("Testing 123"); - - assertEquals(5, root.getEntryCount()); - assertThat(root.getEntryNames(), hasItem("Thumbnail")); - assertThat(root.getEntryNames(), hasItem("Image")); - assertThat(root.getEntryNames(), hasItem("Testing 123")); - assertThat(root.getEntryNames(), hasItem("\u0005DocumentSummaryInformation")); - assertThat(root.getEntryNames(), hasItem("\u0005SummaryInformation")); - - assertEquals(5, testDir.getEntryCount()); - assertThat(testDir.getEntryNames(), hasItem("Mini")); - assertThat(testDir.getEntryNames(), hasItem("Mini2")); - assertThat(testDir.getEntryNames(), hasItem("Normal4096")); - assertThat(testDir.getEntryNames(), hasItem("Testing 789")); - assertThat(testDir.getEntryNames(), hasItem("Testing ABC")); - - assertContentsMatches(mini, (DocumentEntry)testDir.getEntry("Mini")); - assertContentsMatches(mini2, (DocumentEntry)testDir.getEntry("Mini2")); - assertContentsMatches(main4096, (DocumentEntry)testDir.getEntry("Normal4096")); - - - // Delete a mini stream, add one more - testDir.getEntry("Mini").delete(); - - byte[] mini3 = new byte[] { 42, 0, 42, 0, 42, 0, 42 }; - testDir.createDocument("Mini3", new ByteArrayInputStream(mini3)); - - - // Save, load, check - NPOIFSFileSystem fs8 = writeOutAndReadBack(fs7); - fs7.close(); - - root = fs8.getRoot(); - testDir = (DirectoryEntry)root.getEntry("Testing 123"); - - assertEquals(5, root.getEntryCount()); - assertThat(root.getEntryNames(), hasItem("Thumbnail")); - assertThat(root.getEntryNames(), hasItem("Image")); - assertThat(root.getEntryNames(), hasItem("Testing 123")); - assertThat(root.getEntryNames(), hasItem("\u0005DocumentSummaryInformation")); - assertThat(root.getEntryNames(), hasItem("\u0005SummaryInformation")); - - assertEquals(5, testDir.getEntryCount()); - assertThat(testDir.getEntryNames(), hasItem("Mini2")); - assertThat(testDir.getEntryNames(), hasItem("Mini3")); - assertThat(testDir.getEntryNames(), hasItem("Normal4096")); - assertThat(testDir.getEntryNames(), hasItem("Testing 789")); - assertThat(testDir.getEntryNames(), hasItem("Testing ABC")); - - assertContentsMatches(mini2, (DocumentEntry)testDir.getEntry("Mini2")); - assertContentsMatches(mini3, (DocumentEntry)testDir.getEntry("Mini3")); - assertContentsMatches(main4096, (DocumentEntry)testDir.getEntry("Normal4096")); - - - // Change some existing streams - NPOIFSDocument mini2Doc = new NPOIFSDocument((DocumentNode)testDir.getEntry("Mini2")); - mini2Doc.replaceContents(new ByteArrayInputStream(mini)); - - byte[] main4106 = new byte[4106]; - main4106[0] = 41; - main4106[4105] = 42; - NPOIFSDocument mainDoc = new NPOIFSDocument((DocumentNode)testDir.getEntry("Normal4096")); - mainDoc.replaceContents(new ByteArrayInputStream(main4106)); - - - // Re-check - NPOIFSFileSystem fs9 = writeOutAndReadBack(fs8); - fs8.close(); - - root = fs9.getRoot(); - testDir = (DirectoryEntry)root.getEntry("Testing 123"); - - assertEquals(5, root.getEntryCount()); - assertThat(root.getEntryNames(), hasItem("Thumbnail")); - assertThat(root.getEntryNames(), hasItem("Image")); - assertThat(root.getEntryNames(), hasItem("Testing 123")); - assertThat(root.getEntryNames(), hasItem("\u0005DocumentSummaryInformation")); - assertThat(root.getEntryNames(), hasItem("\u0005SummaryInformation")); - - assertEquals(5, testDir.getEntryCount()); - assertThat(testDir.getEntryNames(), hasItem("Mini2")); - assertThat(testDir.getEntryNames(), hasItem("Mini3")); - assertThat(testDir.getEntryNames(), hasItem("Normal4096")); - assertThat(testDir.getEntryNames(), hasItem("Testing 789")); - assertThat(testDir.getEntryNames(), hasItem("Testing ABC")); - - assertContentsMatches(mini, (DocumentEntry)testDir.getEntry("Mini2")); - assertContentsMatches(mini3, (DocumentEntry)testDir.getEntry("Mini3")); - assertContentsMatches(main4106, (DocumentEntry)testDir.getEntry("Normal4096")); - - - // All done - fs9.close(); - } - } - - /** - * Create a new file, write it and read it again - * Then, add some streams, write and read - */ - @Test - public void createWriteRead() throws IOException { - NPOIFSFileSystem fs1 = new NPOIFSFileSystem(); - DocumentEntry miniDoc; - DocumentEntry normDoc; - - // Initially has Properties + BAT but not SBAT - assertEquals(POIFSConstants.END_OF_CHAIN, fs1.getNextBlock(0)); - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs1.getNextBlock(1)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs1.getNextBlock(2)); - - // Check that the SBAT is empty - assertEquals(POIFSConstants.END_OF_CHAIN, fs1.getRoot().getProperty().getStartBlock()); - - // Check that properties table was given block 0 - assertEquals(0, fs1._get_property_table().getStartBlock()); - - // Write and read it - NPOIFSFileSystem fs2 = writeOutAndReadBack(fs1); - fs1.close(); - - // No change, SBAT remains empty - assertEquals(POIFSConstants.END_OF_CHAIN, fs2.getNextBlock(0)); - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs2.getNextBlock(1)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs2.getNextBlock(2)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs2.getNextBlock(3)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs2.getRoot().getProperty().getStartBlock()); - assertEquals(0, fs2._get_property_table().getStartBlock()); - fs2.close(); - - // Check the same but with saving to a file - NPOIFSFileSystem fs3 = new NPOIFSFileSystem(); - NPOIFSFileSystem fs4 = writeOutFileAndReadBack(fs3); - fs3.close(); - - // Same, no change, SBAT remains empty - assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(0)); - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs4.getNextBlock(1)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs4.getNextBlock(2)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs4.getNextBlock(3)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getRoot().getProperty().getStartBlock()); - assertEquals(0, fs4._get_property_table().getStartBlock()); - - - - // Put everything within a new directory - DirectoryEntry testDir = fs4.createDirectory("Test Directory"); - - // Add a new Normal Stream (Normal Streams minimum 4096 bytes) - byte[] main4096 = new byte[4096]; - main4096[0] = -10; - main4096[4095] = -11; - testDir.createDocument("Normal4096", new ByteArrayInputStream(main4096)); - - assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(0)); - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs4.getNextBlock(1)); - assertEquals(3, fs4.getNextBlock(2)); - assertEquals(4, fs4.getNextBlock(3)); - assertEquals(5, fs4.getNextBlock(4)); - assertEquals(6, fs4.getNextBlock(5)); - assertEquals(7, fs4.getNextBlock(6)); - assertEquals(8, fs4.getNextBlock(7)); - assertEquals(9, fs4.getNextBlock(8)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(9)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs4.getNextBlock(10)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs4.getNextBlock(11)); - // SBAT still unused - assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getRoot().getProperty().getStartBlock()); - - - // Add a bigger Normal Stream - byte[] main5124 = new byte[5124]; - main5124[0] = -22; - main5124[5123] = -33; - testDir.createDocument("Normal5124", new ByteArrayInputStream(main5124)); - - assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(0)); - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs4.getNextBlock(1)); - assertEquals(3, fs4.getNextBlock(2)); - assertEquals(4, fs4.getNextBlock(3)); - assertEquals(5, fs4.getNextBlock(4)); - assertEquals(6, fs4.getNextBlock(5)); - assertEquals(7, fs4.getNextBlock(6)); - assertEquals(8, fs4.getNextBlock(7)); - assertEquals(9, fs4.getNextBlock(8)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(9)); - - assertEquals(11, fs4.getNextBlock(10)); - assertEquals(12, fs4.getNextBlock(11)); - assertEquals(13, fs4.getNextBlock(12)); - assertEquals(14, fs4.getNextBlock(13)); - assertEquals(15, fs4.getNextBlock(14)); - assertEquals(16, fs4.getNextBlock(15)); - assertEquals(17, fs4.getNextBlock(16)); - assertEquals(18, fs4.getNextBlock(17)); - assertEquals(19, fs4.getNextBlock(18)); - assertEquals(20, fs4.getNextBlock(19)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(20)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs4.getNextBlock(21)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs4.getNextBlock(22)); - - assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getRoot().getProperty().getStartBlock()); - - - // Now Add a mini stream - byte[] mini = new byte[] { 42, 0, 1, 2, 3, 4, 42 }; - testDir.createDocument("Mini", new ByteArrayInputStream(mini)); - - // Mini stream will get one block for fat + one block for data - assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(0)); - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs4.getNextBlock(1)); - assertEquals(3, fs4.getNextBlock(2)); - assertEquals(4, fs4.getNextBlock(3)); - assertEquals(5, fs4.getNextBlock(4)); - assertEquals(6, fs4.getNextBlock(5)); - assertEquals(7, fs4.getNextBlock(6)); - assertEquals(8, fs4.getNextBlock(7)); - assertEquals(9, fs4.getNextBlock(8)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(9)); - - assertEquals(11, fs4.getNextBlock(10)); - assertEquals(12, fs4.getNextBlock(11)); - assertEquals(13, fs4.getNextBlock(12)); - assertEquals(14, fs4.getNextBlock(13)); - assertEquals(15, fs4.getNextBlock(14)); - assertEquals(16, fs4.getNextBlock(15)); - assertEquals(17, fs4.getNextBlock(16)); - assertEquals(18, fs4.getNextBlock(17)); - assertEquals(19, fs4.getNextBlock(18)); - assertEquals(20, fs4.getNextBlock(19)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(20)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(21)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs4.getNextBlock(22)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs4.getNextBlock(23)); - - // Check the mini stream location was set - // (21 is mini fat, 22 is first mini stream block) - assertEquals(22, fs4.getRoot().getProperty().getStartBlock()); - - - // Write and read back - NPOIFSFileSystem fs5 = writeOutAndReadBack(fs4); - fs4.close(); - HeaderBlock header = writeOutAndReadHeader(fs5); - - // Check the header has the right points in it - assertEquals(1, header.getBATCount()); - assertEquals(1, header.getBATArray()[0]); - assertEquals(0, header.getPropertyStart()); - assertEquals(1, header.getSBATCount()); - assertEquals(21, header.getSBATStart()); - assertEquals(22, fs5._get_property_table().getRoot().getStartBlock()); - - // Block use should be almost the same, except the properties - // stream will have grown out to cover 2 blocks - // Check the block use is all unchanged - assertEquals(23, fs5.getNextBlock(0)); // Properties now extends over 2 blocks - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs5.getNextBlock(1)); - - assertEquals(3, fs5.getNextBlock(2)); - assertEquals(4, fs5.getNextBlock(3)); - assertEquals(5, fs5.getNextBlock(4)); - assertEquals(6, fs5.getNextBlock(5)); - assertEquals(7, fs5.getNextBlock(6)); - assertEquals(8, fs5.getNextBlock(7)); - assertEquals(9, fs5.getNextBlock(8)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs5.getNextBlock(9)); // End of normal4096 - - assertEquals(11, fs5.getNextBlock(10)); - assertEquals(12, fs5.getNextBlock(11)); - assertEquals(13, fs5.getNextBlock(12)); - assertEquals(14, fs5.getNextBlock(13)); - assertEquals(15, fs5.getNextBlock(14)); - assertEquals(16, fs5.getNextBlock(15)); - assertEquals(17, fs5.getNextBlock(16)); - assertEquals(18, fs5.getNextBlock(17)); - assertEquals(19, fs5.getNextBlock(18)); - assertEquals(20, fs5.getNextBlock(19)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs5.getNextBlock(20)); // End of normal5124 - - assertEquals(POIFSConstants.END_OF_CHAIN, fs5.getNextBlock(21)); // Mini Stream FAT - assertEquals(POIFSConstants.END_OF_CHAIN, fs5.getNextBlock(22)); // Mini Stream data - assertEquals(POIFSConstants.END_OF_CHAIN, fs5.getNextBlock(23)); // Properties #2 - assertEquals(POIFSConstants.UNUSED_BLOCK, fs5.getNextBlock(24)); - - - // Check some data - assertEquals(1, fs5.getRoot().getEntryCount()); - testDir = (DirectoryEntry)fs5.getRoot().getEntry("Test Directory"); - assertEquals(3, testDir.getEntryCount()); - - miniDoc = (DocumentEntry)testDir.getEntry("Mini"); - assertContentsMatches(mini, miniDoc); - - normDoc = (DocumentEntry)testDir.getEntry("Normal4096"); - assertContentsMatches(main4096, normDoc); - - normDoc = (DocumentEntry)testDir.getEntry("Normal5124"); - assertContentsMatches(main5124, normDoc); - - - // Delete a couple of streams - miniDoc.delete(); - normDoc.delete(); - - - // Check - will have un-used sectors now - NPOIFSFileSystem fs6 = writeOutAndReadBack(fs5); - fs5.close(); - - assertEquals(POIFSConstants.END_OF_CHAIN, fs6.getNextBlock(0)); // Props back in 1 block - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs6.getNextBlock(1)); - - assertEquals(3, fs6.getNextBlock(2)); - assertEquals(4, fs6.getNextBlock(3)); - assertEquals(5, fs6.getNextBlock(4)); - assertEquals(6, fs6.getNextBlock(5)); - assertEquals(7, fs6.getNextBlock(6)); - assertEquals(8, fs6.getNextBlock(7)); - assertEquals(9, fs6.getNextBlock(8)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs6.getNextBlock(9)); // End of normal4096 - - assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(10)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(11)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(12)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(13)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(14)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(15)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(16)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(17)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(18)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(19)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(20)); - - assertEquals(POIFSConstants.END_OF_CHAIN, fs6.getNextBlock(21)); // Mini Stream FAT - assertEquals(POIFSConstants.END_OF_CHAIN, fs6.getNextBlock(22)); // Mini Stream data - assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(23)); // Properties gone - assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(24)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs6.getNextBlock(25)); - - // All done - fs6.close(); - } - - @Test - public void addBeforeWrite() throws IOException { - NPOIFSFileSystem fs1 = new NPOIFSFileSystem(); - DocumentEntry miniDoc; - DocumentEntry normDoc; - HeaderBlock hdr; - - // Initially has Properties + BAT but nothing else - assertEquals(POIFSConstants.END_OF_CHAIN, fs1.getNextBlock(0)); - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs1.getNextBlock(1)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs1.getNextBlock(2)); - - hdr = writeOutAndReadHeader(fs1); - // No mini stream, and no xbats - // Will have fat then properties stream - assertEquals(1, hdr.getBATCount()); - assertEquals(1, hdr.getBATArray()[0]); - assertEquals(0, hdr.getPropertyStart()); - assertEquals(POIFSConstants.END_OF_CHAIN, hdr.getSBATStart()); - assertEquals(POIFSConstants.END_OF_CHAIN, hdr.getXBATIndex()); - assertEquals(POIFSConstants.SMALLER_BIG_BLOCK_SIZE*3, fs1.size()); - fs1.close(); - - // Get a clean filesystem to start with - fs1 = new NPOIFSFileSystem(); - - // Put our test files in a non-standard place - DirectoryEntry parentDir = fs1.createDirectory("Parent Directory"); - DirectoryEntry testDir = parentDir.createDirectory("Test Directory"); - - - // Add to the mini stream - byte[] mini = new byte[] { 42, 0, 1, 2, 3, 4, 42 }; - testDir.createDocument("Mini", new ByteArrayInputStream(mini)); - - // Add to the main stream - byte[] main4096 = new byte[4096]; - main4096[0] = -10; - main4096[4095] = -11; - testDir.createDocument("Normal4096", new ByteArrayInputStream(main4096)); - - - // Check the mini stream was added, then the main stream - assertEquals(POIFSConstants.END_OF_CHAIN, fs1.getNextBlock(0)); - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs1.getNextBlock(1)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs1.getNextBlock(2)); // Mini Fat - assertEquals(POIFSConstants.END_OF_CHAIN, fs1.getNextBlock(3)); // Mini Stream - assertEquals(5, fs1.getNextBlock(4)); // Main Stream - assertEquals(6, fs1.getNextBlock(5)); - assertEquals(7, fs1.getNextBlock(6)); - assertEquals(8, fs1.getNextBlock(7)); - assertEquals(9, fs1.getNextBlock(8)); - assertEquals(10, fs1.getNextBlock(9)); - assertEquals(11, fs1.getNextBlock(10)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs1.getNextBlock(11)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs1.getNextBlock(12)); - assertEquals(POIFSConstants.SMALLER_BIG_BLOCK_SIZE*13, fs1.size()); - - - // Check that we can read the right data pre-write - miniDoc = (DocumentEntry)testDir.getEntry("Mini"); - assertContentsMatches(mini, miniDoc); - - normDoc = (DocumentEntry)testDir.getEntry("Normal4096"); - assertContentsMatches(main4096, normDoc); - - - // Write, read, check - hdr = writeOutAndReadHeader(fs1); - NPOIFSFileSystem fs2 = writeOutAndReadBack(fs1); - fs1.close(); - - // Check the header details - will have the sbat near the start, - // then the properties at the end - assertEquals(1, hdr.getBATCount()); - assertEquals(1, hdr.getBATArray()[0]); - assertEquals(2, hdr.getSBATStart()); - assertEquals(0, hdr.getPropertyStart()); - assertEquals(POIFSConstants.END_OF_CHAIN, hdr.getXBATIndex()); - - // Check the block allocation is unchanged, other than - // the properties stream going in at the end - assertEquals(12, fs2.getNextBlock(0)); // Properties - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs2.getNextBlock(1)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs2.getNextBlock(2)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs2.getNextBlock(3)); - assertEquals(5, fs2.getNextBlock(4)); - assertEquals(6, fs2.getNextBlock(5)); - assertEquals(7, fs2.getNextBlock(6)); - assertEquals(8, fs2.getNextBlock(7)); - assertEquals(9, fs2.getNextBlock(8)); - assertEquals(10, fs2.getNextBlock(9)); - assertEquals(11, fs2.getNextBlock(10)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs2.getNextBlock(11)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs2.getNextBlock(12)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs2.getNextBlock(13)); - assertEquals(POIFSConstants.SMALLER_BIG_BLOCK_SIZE*14, fs2.size()); - - - // Check the data - DirectoryEntry fsRoot = fs2.getRoot(); - assertEquals(1, fsRoot.getEntryCount()); - - parentDir = (DirectoryEntry)fsRoot.getEntry("Parent Directory"); - assertEquals(1, parentDir.getEntryCount()); - - testDir = (DirectoryEntry)parentDir.getEntry("Test Directory"); - assertEquals(2, testDir.getEntryCount()); - - miniDoc = (DocumentEntry)testDir.getEntry("Mini"); - assertContentsMatches(mini, miniDoc); - - normDoc = (DocumentEntry)testDir.getEntry("Normal4096"); - assertContentsMatches(main4096, normDoc); - - - // Add one more stream to each, then save and re-load - byte[] mini2 = new byte[] { -42, 0, -1, -2, -3, -4, -42 }; - testDir.createDocument("Mini2", new ByteArrayInputStream(mini2)); - - // Add to the main stream - byte[] main4106 = new byte[4106]; - main4106[0] = 41; - main4106[4105] = 42; - testDir.createDocument("Normal4106", new ByteArrayInputStream(main4106)); - - - // Recheck the data in all 4 streams - NPOIFSFileSystem fs3 = writeOutAndReadBack(fs2); - fs2.close(); - - fsRoot = fs3.getRoot(); - assertEquals(1, fsRoot.getEntryCount()); - - parentDir = (DirectoryEntry)fsRoot.getEntry("Parent Directory"); - assertEquals(1, parentDir.getEntryCount()); - - testDir = (DirectoryEntry)parentDir.getEntry("Test Directory"); - assertEquals(4, testDir.getEntryCount()); - - miniDoc = (DocumentEntry)testDir.getEntry("Mini"); - assertContentsMatches(mini, miniDoc); - - miniDoc = (DocumentEntry)testDir.getEntry("Mini2"); - assertContentsMatches(mini2, miniDoc); - - normDoc = (DocumentEntry)testDir.getEntry("Normal4106"); - assertContentsMatches(main4106, normDoc); - - // All done - fs3.close(); - } - - @Test - public void readZeroLengthEntries() throws IOException { - NPOIFSFileSystem fs = new NPOIFSFileSystem(_inst.getFile("only-zero-byte-streams.ole2")); - DirectoryNode testDir = fs.getRoot(); - assertEquals(3, testDir.getEntryCount()); - DocumentEntry entry; - - entry = (DocumentEntry)testDir.getEntry("test-zero-1"); - assertNotNull(entry); - assertEquals(0, entry.getSize()); - - entry = (DocumentEntry)testDir.getEntry("test-zero-2"); - assertNotNull(entry); - assertEquals(0, entry.getSize()); - - entry = (DocumentEntry)testDir.getEntry("test-zero-3"); - assertNotNull(entry); - assertEquals(0, entry.getSize()); - - // Check properties, all have zero length, no blocks - NPropertyTable props = fs._get_property_table(); - assertEquals(POIFSConstants.END_OF_CHAIN, props.getRoot().getStartBlock()); - for (Property prop : props.getRoot()) { - assertEquals("test-zero-", prop.getName().substring(0, 10)); - assertEquals(POIFSConstants.END_OF_CHAIN, prop.getStartBlock()); - } - - // All done - fs.close(); - } - - @Test - public void writeZeroLengthEntries() throws IOException { - NPOIFSFileSystem fs1 = new NPOIFSFileSystem(); - DirectoryNode testDir = fs1.getRoot(); - DocumentEntry miniDoc; - DocumentEntry normDoc; - DocumentEntry emptyDoc; - - // Add mini and normal sized entries to start - byte[] mini2 = new byte[] { -42, 0, -1, -2, -3, -4, -42 }; - testDir.createDocument("Mini2", new ByteArrayInputStream(mini2)); - - // Add to the main stream - byte[] main4106 = new byte[4106]; - main4106[0] = 41; - main4106[4105] = 42; - testDir.createDocument("Normal4106", new ByteArrayInputStream(main4106)); - - // Now add some empty ones - byte[] empty = new byte[0]; - testDir.createDocument("empty-1", new ByteArrayInputStream(empty)); - testDir.createDocument("empty-2", new ByteArrayInputStream(empty)); - testDir.createDocument("empty-3", new ByteArrayInputStream(empty)); - - // Check - miniDoc = (DocumentEntry)testDir.getEntry("Mini2"); - assertContentsMatches(mini2, miniDoc); - - normDoc = (DocumentEntry)testDir.getEntry("Normal4106"); - assertContentsMatches(main4106, normDoc); - - emptyDoc = (DocumentEntry)testDir.getEntry("empty-1"); - assertContentsMatches(empty, emptyDoc); - - emptyDoc = (DocumentEntry)testDir.getEntry("empty-2"); - assertContentsMatches(empty, emptyDoc); - - emptyDoc = (DocumentEntry)testDir.getEntry("empty-3"); - assertContentsMatches(empty, emptyDoc); - - // Look at the properties entry, and check the empty ones - // have zero size and no start block - NPropertyTable props = fs1._get_property_table(); - Iterator propsIt = props.getRoot().getChildren(); - - Property prop = propsIt.next(); - assertEquals("Mini2", prop.getName()); - assertEquals(0, prop.getStartBlock()); - assertEquals(7, prop.getSize()); - - prop = propsIt.next(); - assertEquals("Normal4106", prop.getName()); - assertEquals(4, prop.getStartBlock()); // BAT, Props, SBAT, MIni - assertEquals(4106, prop.getSize()); - - prop = propsIt.next(); - assertEquals("empty-1", prop.getName()); - assertEquals(POIFSConstants.END_OF_CHAIN, prop.getStartBlock()); - assertEquals(0, prop.getSize()); - - prop = propsIt.next(); - assertEquals("empty-2", prop.getName()); - assertEquals(POIFSConstants.END_OF_CHAIN, prop.getStartBlock()); - assertEquals(0, prop.getSize()); - - prop = propsIt.next(); - assertEquals("empty-3", prop.getName()); - assertEquals(POIFSConstants.END_OF_CHAIN, prop.getStartBlock()); - assertEquals(0, prop.getSize()); - - - // Save and re-check - NPOIFSFileSystem fs2 = writeOutAndReadBack(fs1); - fs1.close(); - testDir = fs2.getRoot(); - - miniDoc = (DocumentEntry)testDir.getEntry("Mini2"); - assertContentsMatches(mini2, miniDoc); - - normDoc = (DocumentEntry)testDir.getEntry("Normal4106"); - assertContentsMatches(main4106, normDoc); - - emptyDoc = (DocumentEntry)testDir.getEntry("empty-1"); - assertContentsMatches(empty, emptyDoc); - - emptyDoc = (DocumentEntry)testDir.getEntry("empty-2"); - assertContentsMatches(empty, emptyDoc); - - emptyDoc = (DocumentEntry)testDir.getEntry("empty-3"); - assertContentsMatches(empty, emptyDoc); - - // Check that a mini-stream was assigned, with one block used - assertEquals(3, testDir.getProperty().getStartBlock()); - assertEquals(64, testDir.getProperty().getSize()); - - // All done - fs2.close(); - } - - /** - * Test that we can read a file with NPOIFS, create a new NPOIFS instance, - * write it out, read it with POIFS, and see the original data - */ - @Test - public void NPOIFSReadCopyWritePOIFSRead() throws IOException { - File testFile = POIDataSamples.getSpreadSheetInstance().getFile("Simple.xls"); - NPOIFSFileSystem src = new NPOIFSFileSystem(testFile); - byte wbDataExp[] = IOUtils.toByteArray(src.createDocumentInputStream("Workbook")); - - NPOIFSFileSystem nfs = new NPOIFSFileSystem(); - EntryUtils.copyNodes(src.getRoot(), nfs.getRoot()); - src.close(); - - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - nfs.writeFilesystem(bos); - nfs.close(); - - POIFSFileSystem pfs = new POIFSFileSystem(new ByteArrayInputStream(bos.toByteArray())); - byte wbDataAct[] = IOUtils.toByteArray(pfs.createDocumentInputStream("Workbook")); - - assertThat(wbDataExp, equalTo(wbDataAct)); - pfs.close(); - } - - /** - * Ensure that you can recursively delete directories and their - * contents - */ - @Test - public void RecursiveDelete() throws IOException { - File testFile = POIDataSamples.getSpreadSheetInstance().getFile("SimpleMacro.xls"); - NPOIFSFileSystem src = new NPOIFSFileSystem(testFile); - - // Starts out with 5 entries: - // _VBA_PROJECT_CUR - // SummaryInformation <(0x05)SummaryInformation> - // DocumentSummaryInformation <(0x05)DocumentSummaryInformation> - // Workbook - // CompObj <(0x01)CompObj> - assertEquals(5, _countChildren(src._get_property_table().getRoot())); - assertEquals(5, src.getRoot().getEntryCount()); - - // Grab the VBA project root - DirectoryEntry vbaProj = (DirectoryEntry)src.getRoot().getEntry("_VBA_PROJECT_CUR"); - assertEquals(3, vbaProj.getEntryCount()); - // Can't delete yet, has stuff - assertEquals(false, vbaProj.delete()); - // Recursively delete - _recursiveDeletee(vbaProj); - - // Entries gone - assertEquals(4, _countChildren(src._get_property_table().getRoot())); - assertEquals(4, src.getRoot().getEntryCount()); - - // Done - src.close(); - } - private void _recursiveDeletee(Entry entry) throws IOException { - if (entry.isDocumentEntry()) { - assertEquals(true, entry.delete()); - return; - } - - DirectoryEntry dir = (DirectoryEntry)entry; - String[] names = dir.getEntryNames().toArray(new String[dir.getEntryCount()]); - for (String name : names) { - Entry ce = dir.getEntry(name); - _recursiveDeletee(ce); - } - assertEquals(true, dir.delete()); - } - @SuppressWarnings("unused") - private int _countChildren(DirectoryProperty p) { - int count = 0; - for (Property cp : p) { count++; } - return count; - } - - /** - * To ensure we can create a file >2gb in size, as well as to - * extend existing files past the 2gb boundary. - * - * Note that to run this test, you will require 2.5+gb of free - * space on your TMP/TEMP partition/disk - * - * Note that to run this test, you need to be able to mmap 2.5+gb - * files, which may need bigger kernel.shmmax and vm.max_map_count - * settings on Linux. - * - * TODO Fix this to work... - */ - @Test - @Ignore("Work in progress test for #60670") - public void CreationAndExtensionPast2GB() throws Exception { - File big = TempFile.createTempFile("poi-test-", ".ole2"); - Assume.assumeTrue("2.5gb of free space is required on your tmp/temp " + - "partition/disk to run large file tests", - big.getFreeSpace() > 2.5*1024*1024*1024); - System.out.println("Slow, memory heavy test in progress...."); - - int s100mb = 100*1024*1024; - int s512mb = 512*1024*1024; - long s2gb = 2l*1024*1024*1024; - DocumentEntry entry; - NPOIFSFileSystem fs; - - // Create a just-sub 2gb file - fs = POIFSFileSystem.create(big); - for (int i=0; i<19; i++) { - fs.createDocument(new DummyDataInputStream(s100mb), "Entry"+i); - } - fs.writeFilesystem(); - fs.close(); - - // Extend it past the 2gb mark - fs = new NPOIFSFileSystem(big, false); - for (int i=0; i<19; i++) { - entry = (DocumentEntry)fs.getRoot().getEntry("Entry"+i); - assertNotNull(entry); - assertEquals(s100mb, entry.getSize()); - } - - fs.createDocument(new DummyDataInputStream(s512mb), "Bigger"); - fs.writeFilesystem(); - fs.close(); - - // Check it still works - fs = new NPOIFSFileSystem(big, false); - for (int i=0; i<19; i++) { - entry = (DocumentEntry)fs.getRoot().getEntry("Entry"+i); - assertNotNull(entry); - assertEquals(s100mb, entry.getSize()); - } - entry = (DocumentEntry)fs.getRoot().getEntry("Bigger"); - assertNotNull(entry); - assertEquals(s512mb, entry.getSize()); - - // Tidy - fs.close(); - big.delete(); - - - // Create a >2gb file - fs = POIFSFileSystem.create(big); - for (int i=0; i<4; i++) { - fs.createDocument(new DummyDataInputStream(s512mb), "Entry"+i); - } - fs.writeFilesystem(); - fs.close(); - - // Read it - fs = new NPOIFSFileSystem(big, false); - for (int i=0; i<4; i++) { - entry = (DocumentEntry)fs.getRoot().getEntry("Entry"+i); - assertNotNull(entry); - assertEquals(s512mb, entry.getSize()); - } - - // Extend it - fs.createDocument(new DummyDataInputStream(s512mb), "Entry4"); - fs.writeFilesystem(); - fs.close(); - - // Check it worked - fs = new NPOIFSFileSystem(big, false); - for (int i=0; i<5; i++) { - entry = (DocumentEntry)fs.getRoot().getEntry("Entry"+i); - assertNotNull(entry); - assertEquals(s512mb, entry.getSize()); - } - - // Tidy - fs.close(); - big.delete(); - - // Create a file with a 2gb entry - fs = POIFSFileSystem.create(big); - fs.createDocument(new DummyDataInputStream(s100mb), "Small"); - // TODO Check we get a helpful error about the max size - fs.createDocument(new DummyDataInputStream(s2gb), "Big"); - } - - protected static class DummyDataInputStream extends InputStream { - protected final long maxSize; - protected long size; - public DummyDataInputStream(long maxSize) { - this.maxSize = maxSize; - this.size = 0; - } - - public int read() throws IOException { - if (size >= maxSize) return -1; - size++; - return (int)(size % 128); - } - - public int read(byte[] b) throws IOException { - return read(b, 0, b.length); - } - public int read(byte[] b, int offset, int len) throws IOException { - if (size >= maxSize) return -1; - int sz = (int)Math.min(len, maxSize-size); - for (int i=0; i 51 is one stream - for(int i=0; i<50; i++) { - assertEquals(i+1, ministore.getNextBlock(i)); - } - assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(50)); - - // 51 -> 103 is the next - for(int i=51; i<103; i++) { - assertEquals(i+1, ministore.getNextBlock(i)); - } - assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(103)); - - // Then there are 3 one block ones - assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(104)); - assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(105)); - assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(106)); - - // 107 -> 154 is the next - for(int i=107; i<154; i++) { - assertEquals(i+1, ministore.getNextBlock(i)); - } - assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(154)); - - // 155 -> 160 is the next - for(int i=155; i<160; i++) { - assertEquals(i+1, ministore.getNextBlock(i)); - } - assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(160)); - - // 161 -> 166 is the next - for(int i=161; i<166; i++) { - assertEquals(i+1, ministore.getNextBlock(i)); - } - assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(166)); - - // 167 -> 172 is the next - for(int i=167; i<172; i++) { - assertEquals(i+1, ministore.getNextBlock(i)); - } - assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(172)); - - // Now some short ones - assertEquals(174 , ministore.getNextBlock(173)); - assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(174)); - - assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(175)); - - assertEquals(177 , ministore.getNextBlock(176)); - assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(177)); - - assertEquals(179 , ministore.getNextBlock(178)); - assertEquals(180 , ministore.getNextBlock(179)); - assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(180)); - - // 181 onwards is free - for(int i=181; i 179 -> 180, 181+ is free - assertEquals(179 , ministore.getNextBlock(178)); - assertEquals(180 , ministore.getNextBlock(179)); - assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(180)); - for(int i=181; i<256; i++) { - assertEquals(POIFSConstants.UNUSED_BLOCK, ministore.getNextBlock(i)); - } - - // However, the ministore data only covers blocks to 183 - for(int i=0; i<=183; i++) { - ministore.getBlockAt(i); - } - try { - ministore.getBlockAt(184); - fail("No block at 184"); - } catch(IndexOutOfBoundsException e) {} - - // The ministore itself is made up of 23 big blocks - Iterator it = new NPOIFSStream(fs, fs.getRoot().getProperty().getStartBlock()).getBlockIterator(); - int count = 0; - while(it.hasNext()) { - count++; - it.next(); - } - assertEquals(23, count); - - // Ask it to get block 184 with creating, it will do - ministore.createBlockIfNeeded(184); - - // The ministore should be one big block bigger now - it = new NPOIFSStream(fs, fs.getRoot().getProperty().getStartBlock()).getBlockIterator(); - count = 0; - while(it.hasNext()) { - count++; - it.next(); - } - assertEquals(24, count); - - // The mini block block counts now run to 191 - for(int i=0; i<=191; i++) { - ministore.getBlockAt(i); - } - try { - ministore.getBlockAt(192); - fail("No block at 192"); - } catch(IndexOutOfBoundsException e) {} - - - // Now try writing through to 192, check that the SBAT and blocks are there - byte[] data = new byte[15*64]; - NPOIFSStream stream = new NPOIFSStream(ministore, 178); - stream.updateContents(data); - - // Check now - assertEquals(179 , ministore.getNextBlock(178)); - assertEquals(180 , ministore.getNextBlock(179)); - assertEquals(181 , ministore.getNextBlock(180)); - assertEquals(182 , ministore.getNextBlock(181)); - assertEquals(183 , ministore.getNextBlock(182)); - assertEquals(184 , ministore.getNextBlock(183)); - assertEquals(185 , ministore.getNextBlock(184)); - assertEquals(186 , ministore.getNextBlock(185)); - assertEquals(187 , ministore.getNextBlock(186)); - assertEquals(188 , ministore.getNextBlock(187)); - assertEquals(189 , ministore.getNextBlock(188)); - assertEquals(190 , ministore.getNextBlock(189)); - assertEquals(191 , ministore.getNextBlock(190)); - assertEquals(192 , ministore.getNextBlock(191)); - assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(192)); - for(int i=193; i<256; i++) { - assertEquals(POIFSConstants.UNUSED_BLOCK, ministore.getNextBlock(i)); - } - - fs.close(); - } - - @Test - public void testCreateMiniStoreFirst() throws Exception { - NPOIFSFileSystem fs = new NPOIFSFileSystem(); - NPOIFSMiniStore ministore = fs.getMiniStore(); - DocumentInputStream dis; - DocumentEntry entry; - - // Initially has Properties + BAT but nothing else - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(0)); - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(1)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(2)); - // Ministore has no blocks, so can't iterate until used - try { - ministore.getNextBlock(0); - } catch (IndexOutOfBoundsException e) {} - - // Write a very small new document, will populate the ministore for us - byte[] data = new byte[8]; - for (int i=0; i i = stream.getBlockIterator(); - assertEquals(true, i.hasNext()); - assertEquals(true, i.hasNext()); - assertEquals(true, i.hasNext()); - ByteBuffer b = i.next(); - assertEquals(false, i.hasNext()); - assertEquals(false, i.hasNext()); - assertEquals(false, i.hasNext()); - - // Check the contents - assertEquals((byte)0x81, b.get()); - assertEquals((byte)0x00, b.get()); - assertEquals((byte)0x00, b.get()); - assertEquals((byte)0x00, b.get()); - assertEquals((byte)0x82, b.get()); - assertEquals((byte)0x00, b.get()); - assertEquals((byte)0x00, b.get()); - assertEquals((byte)0x00, b.get()); - - fs.close(); - } - - /** - * Read a stream with only two blocks in it - */ - public void testReadShortStream() throws Exception { - NPOIFSFileSystem fs = new NPOIFSFileSystem(_inst.getFile("BlockSize512.zvi")); - - // 97 -> 98 -> end - NPOIFSStream stream = new NPOIFSStream(fs, 97); - Iterator i = stream.getBlockIterator(); - assertEquals(true, i.hasNext()); - assertEquals(true, i.hasNext()); - assertEquals(true, i.hasNext()); - ByteBuffer b97 = i.next(); - assertEquals(true, i.hasNext()); - assertEquals(true, i.hasNext()); - ByteBuffer b98 = i.next(); - assertEquals(false, i.hasNext()); - assertEquals(false, i.hasNext()); - assertEquals(false, i.hasNext()); - - // Check the contents of the 1st block - assertEquals((byte)0x01, b97.get()); - assertEquals((byte)0x00, b97.get()); - assertEquals((byte)0x00, b97.get()); - assertEquals((byte)0x00, b97.get()); - assertEquals((byte)0x02, b97.get()); - assertEquals((byte)0x00, b97.get()); - assertEquals((byte)0x00, b97.get()); - assertEquals((byte)0x00, b97.get()); - - // Check the contents of the 2nd block - assertEquals((byte)0x81, b98.get()); - assertEquals((byte)0x00, b98.get()); - assertEquals((byte)0x00, b98.get()); - assertEquals((byte)0x00, b98.get()); - assertEquals((byte)0x82, b98.get()); - assertEquals((byte)0x00, b98.get()); - assertEquals((byte)0x00, b98.get()); - assertEquals((byte)0x00, b98.get()); - - fs.close(); - } - - /** - * Read a stream with many blocks - */ - public void testReadLongerStream() throws Exception { - NPOIFSFileSystem fs = new NPOIFSFileSystem(_inst.getFile("BlockSize512.zvi")); - - ByteBuffer b0 = null; - ByteBuffer b1 = null; - ByteBuffer b22 = null; - - // The stream at 0 has 23 blocks in it - NPOIFSStream stream = new NPOIFSStream(fs, 0); - Iterator i = stream.getBlockIterator(); - int count = 0; - while(i.hasNext()) { - ByteBuffer b = i.next(); - if(count == 0) { - b0 = b; - } - if(count == 1) { - b1 = b; - } - if(count == 22) { - b22 = b; - } - - count++; - } - assertEquals(23, count); - - // Check the contents - // 1st block is at 0 - assertEquals((byte)0x9e, b0.get()); - assertEquals((byte)0x75, b0.get()); - assertEquals((byte)0x97, b0.get()); - assertEquals((byte)0xf6, b0.get()); - - // 2nd block is at 1 - assertEquals((byte)0x86, b1.get()); - assertEquals((byte)0x09, b1.get()); - assertEquals((byte)0x22, b1.get()); - assertEquals((byte)0xfb, b1.get()); - - // last block is at 89 - assertEquals((byte)0xfe, b22.get()); - assertEquals((byte)0xff, b22.get()); - assertEquals((byte)0x00, b22.get()); - assertEquals((byte)0x00, b22.get()); - assertEquals((byte)0x05, b22.get()); - assertEquals((byte)0x01, b22.get()); - assertEquals((byte)0x02, b22.get()); - assertEquals((byte)0x00, b22.get()); - - fs.close(); - } - - /** - * Read a stream with several blocks in a 4096 byte block file - */ - public void testReadStream4096() throws Exception { - NPOIFSFileSystem fs = new NPOIFSFileSystem(_inst.getFile("BlockSize4096.zvi")); - - // 0 -> 1 -> 2 -> end - NPOIFSStream stream = new NPOIFSStream(fs, 0); - Iterator i = stream.getBlockIterator(); - assertEquals(true, i.hasNext()); - assertEquals(true, i.hasNext()); - assertEquals(true, i.hasNext()); - ByteBuffer b0 = i.next(); - assertEquals(true, i.hasNext()); - assertEquals(true, i.hasNext()); - ByteBuffer b1 = i.next(); - assertEquals(true, i.hasNext()); - assertEquals(true, i.hasNext()); - ByteBuffer b2 = i.next(); - assertEquals(false, i.hasNext()); - assertEquals(false, i.hasNext()); - assertEquals(false, i.hasNext()); - - // Check the contents of the 1st block - assertEquals((byte)0x9E, b0.get()); - assertEquals((byte)0x75, b0.get()); - assertEquals((byte)0x97, b0.get()); - assertEquals((byte)0xF6, b0.get()); - assertEquals((byte)0xFF, b0.get()); - assertEquals((byte)0x21, b0.get()); - assertEquals((byte)0xD2, b0.get()); - assertEquals((byte)0x11, b0.get()); - - // Check the contents of the 2nd block - assertEquals((byte)0x00, b1.get()); - assertEquals((byte)0x00, b1.get()); - assertEquals((byte)0x03, b1.get()); - assertEquals((byte)0x00, b1.get()); - assertEquals((byte)0x00, b1.get()); - assertEquals((byte)0x00, b1.get()); - assertEquals((byte)0x00, b1.get()); - assertEquals((byte)0x00, b1.get()); - - // Check the contents of the 3rd block - assertEquals((byte)0x6D, b2.get()); - assertEquals((byte)0x00, b2.get()); - assertEquals((byte)0x00, b2.get()); - assertEquals((byte)0x00, b2.get()); - assertEquals((byte)0x03, b2.get()); - assertEquals((byte)0x00, b2.get()); - assertEquals((byte)0x46, b2.get()); - assertEquals((byte)0x00, b2.get()); - - fs.close(); - } - - /** - * Craft a nasty file with a loop, and ensure we don't get stuck - */ - public void testReadFailsOnLoop() throws Exception { - NPOIFSFileSystem fs = new NPOIFSFileSystem(_inst.getFile("BlockSize512.zvi")); - - // Hack the FAT so that it goes 0->1->2->0 - fs.setNextBlock(0, 1); - fs.setNextBlock(1, 2); - fs.setNextBlock(2, 0); - - // Now try to read - NPOIFSStream stream = new NPOIFSStream(fs, 0); - Iterator i = stream.getBlockIterator(); - assertEquals(true, i.hasNext()); - - // 1st read works - i.next(); - assertEquals(true, i.hasNext()); - - // 2nd read works - i.next(); - assertEquals(true, i.hasNext()); - - // 3rd read works - i.next(); - assertEquals(true, i.hasNext()); - - // 4th read blows up as it loops back to 0 - try { - i.next(); - fail("Loop should have been detected but wasn't!"); - } catch(RuntimeException e) { - // Good, it was detected - } - assertEquals(true, i.hasNext()); - - fs.close(); - } - - /** - * Tests that we can load some streams that are - * stored in the mini stream. - */ - public void testReadMiniStreams() throws Exception { - NPOIFSFileSystem fs = new NPOIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi")); - NPOIFSMiniStore ministore = fs.getMiniStore(); - - // 178 -> 179 -> 180 -> end - NPOIFSStream stream = new NPOIFSStream(ministore, 178); - Iterator i = stream.getBlockIterator(); - assertEquals(true, i.hasNext()); - assertEquals(true, i.hasNext()); - assertEquals(true, i.hasNext()); - ByteBuffer b178 = i.next(); - assertEquals(true, i.hasNext()); - assertEquals(true, i.hasNext()); - ByteBuffer b179 = i.next(); - assertEquals(true, i.hasNext()); - ByteBuffer b180 = i.next(); - assertEquals(false, i.hasNext()); - assertEquals(false, i.hasNext()); - assertEquals(false, i.hasNext()); - - // Check the contents of the 1st block - assertEquals((byte)0xfe, b178.get()); - assertEquals((byte)0xff, b178.get()); - assertEquals((byte)0x00, b178.get()); - assertEquals((byte)0x00, b178.get()); - assertEquals((byte)0x05, b178.get()); - assertEquals((byte)0x01, b178.get()); - assertEquals((byte)0x02, b178.get()); - assertEquals((byte)0x00, b178.get()); - - // And the 2nd - assertEquals((byte)0x6c, b179.get()); - assertEquals((byte)0x00, b179.get()); - assertEquals((byte)0x00, b179.get()); - assertEquals((byte)0x00, b179.get()); - assertEquals((byte)0x28, b179.get()); - assertEquals((byte)0x00, b179.get()); - assertEquals((byte)0x00, b179.get()); - assertEquals((byte)0x00, b179.get()); - - // And the 3rd - assertEquals((byte)0x30, b180.get()); - assertEquals((byte)0x00, b180.get()); - assertEquals((byte)0x00, b180.get()); - assertEquals((byte)0x00, b180.get()); - assertEquals((byte)0x00, b180.get()); - assertEquals((byte)0x00, b180.get()); - assertEquals((byte)0x00, b180.get()); - assertEquals((byte)0x80, b180.get()); - - fs.close(); - } - - /** - * Writing the same amount of data as before - */ - public void testReplaceStream() throws Exception { - NPOIFSFileSystem fs = new NPOIFSFileSystem(_inst.openResourceAsStream("BlockSize512.zvi")); - - byte[] data = new byte[512]; - for(int i=0; i it = stream.getBlockIterator(); - assertEquals(true, it.hasNext()); - ByteBuffer b = it.next(); - assertEquals(false, it.hasNext()); - - // Now check the contents - data = new byte[512]; - b.get(data); - for(int i=0; i 98 -> end - assertEquals(98, fs.getNextBlock(97)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(98)); - - // Create a 2 block stream, will become a 1 block one - NPOIFSStream stream = new NPOIFSStream(fs, 97); - stream.updateContents(data); - - // 97 should now be the end, and 98 free - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(97)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(98)); - - // Check the reading of blocks - Iterator it = stream.getBlockIterator(); - assertEquals(true, it.hasNext()); - ByteBuffer b = it.next(); - assertEquals(false, it.hasNext()); - - // Now check the contents - data = new byte[512]; - b.get(data); - for(int i=0; i 98 -> end - assertEquals(98, fs.getNextBlock(97)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(98)); - - // 100 is our first free one - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(99)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(100)); - - // Create a 2 block stream, will become a 3 block one - NPOIFSStream stream = new NPOIFSStream(fs, 97); - stream.updateContents(data); - - // 97 -> 98 -> 100 -> end - assertEquals(98, fs.getNextBlock(97)); - assertEquals(100, fs.getNextBlock(98)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(100)); - - // Check the reading of blocks - Iterator it = stream.getBlockIterator(); - int count = 0; - while(it.hasNext()) { - ByteBuffer b = it.next(); - data = new byte[512]; - b.get(data); - for(int i=0; i it = stream.getBlockIterator(); - int count = 0; - while(it.hasNext()) { - ByteBuffer b = it.next(); - data = new byte[512]; - b.get(data); - for(int i=0; i 1 -> 2 -> end - assertEquals(1, fs.getNextBlock(0)); - assertEquals(2, fs.getNextBlock(1)); - assertEquals(POIFSConstants.END_OF_CHAIN, fs.getNextBlock(2)); - assertEquals(4, fs.getNextBlock(3)); - - // First free one is at 15 - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK, fs.getNextBlock(14)); - assertEquals(POIFSConstants.UNUSED_BLOCK, fs.getNextBlock(15)); - - - // Write a 5 block file - byte[] data = new byte[4096*5]; - for(int i=0; i it = stream.getBlockIterator(); - int count = 0; - while(it.hasNext()) { - ByteBuffer b = it.next(); - data = new byte[512]; - b.get(data); - for(int i=0; i 179 -> 180 -> end - assertEquals(179, ministore.getNextBlock(178)); - assertEquals(180, ministore.getNextBlock(179)); - assertEquals(POIFSConstants.END_OF_CHAIN, ministore.getNextBlock(180)); - - - // Try writing 3 full blocks worth - byte[] data = new byte[64*3]; - for(int i=0; i it = stream.getBlockIterator(); - ByteBuffer b178 = it.next(); - ByteBuffer b179 = it.next(); - ByteBuffer b180 = it.next(); - assertEquals(false, it.hasNext()); - - assertEquals((byte)0x00, b178.get()); - assertEquals((byte)0x01, b178.get()); - assertEquals((byte)0x40, b179.get()); - assertEquals((byte)0x41, b179.get()); - assertEquals((byte)0x80, b180.get()); - assertEquals((byte)0x81, b180.get()); - - - // Try writing just into 3 blocks worth - data = new byte[64*2 + 12]; - for(int i=0; i1->2->0 - fs.setNextBlock(0, 1); - fs.setNextBlock(1, 2); - fs.setNextBlock(2, 0); - - // Try to write a large amount, should fail on the write - byte[] data = new byte[512*4]; - NPOIFSStream stream = new NPOIFSStream(fs, 0); - try { - stream.updateContents(data); - fail("Loop should have been detected but wasn't!"); - } catch(IllegalStateException e) {} - - // Now reset, and try on a small bit - // Should fail during the freeing set - fs.setNextBlock(0, 1); - fs.setNextBlock(1, 2); - fs.setNextBlock(2, 0); - - data = new byte[512]; - stream = new NPOIFSStream(fs, 0); - try { - stream.updateContents(data); - fail("Loop should have been detected but wasn't!"); - } catch(IllegalStateException e) {} - - fs.close(); - } - - /** - * Tests adding a new stream, writing and reading it. - */ - public void testReadWriteNewStream() throws Exception { - NPOIFSFileSystem fs = new NPOIFSFileSystem(); - NPOIFSStream stream = new NPOIFSStream(fs); - - // Check our filesystem has Properties then BAT - assertEquals(2, fs.getFreeBlock()); - BATBlock bat = fs.getBATBlockAndIndex(0).getBlock(); - assertEquals(POIFSConstants.END_OF_CHAIN, bat.getValueAt(0)); - assertEquals(POIFSConstants.FAT_SECTOR_BLOCK,bat.getValueAt(1)); - assertEquals(POIFSConstants.UNUSED_BLOCK, bat.getValueAt(2)); - - // Check the stream as-is - assertEquals(POIFSConstants.END_OF_CHAIN, stream.getStartBlock()); - try { - stream.getBlockIterator(); - fail("Shouldn't be able to get an iterator before writing"); - } catch(IllegalStateException e) {} - - // Write in two blocks - byte[] data = new byte[512+20]; - for(int i=0; i<512; i++) { - data[i] = (byte)(i%256); - } - for(int i=512; i it = stream.getBlockIterator(); - assertEquals(true, it.hasNext()); - ByteBuffer b = it.next(); - - byte[] read = new byte[512]; - b.get(read); - for(int i=0; i -1); - assertTrue(e.getMessage().indexOf("You are calling the part of POI that deals with OLE2 Office Documents") > -1); - } - } - public void test2003XMLException() throws IOException - { - InputStream in = openSampleStream("SampleSS.xml"); - - try { - new POIFSFileSystem(in).close(); - fail("expected exception was not thrown"); - } catch(NotOLE2FileException e) { - // expected during successful test - assertTrue(e.getMessage().indexOf("The supplied data appears to be a raw XML file") > -1); - assertTrue(e.getMessage().indexOf("Formats such as Office 2003 XML") > -1); - } - } - - public void testDetectAsPOIFS() throws IOException { - // ooxml file isn't - confirmIsPOIFS("SampleSS.xlsx", false); - - // 2003 xml file isn't - confirmIsPOIFS("SampleSS.xml", false); - - // xls file is - confirmIsPOIFS("SampleSS.xls", true); - - // text file isn't - confirmIsPOIFS("SampleSS.txt", false); - } - private void confirmIsPOIFS(String sampleFileName, boolean expectedResult) throws IOException { - InputStream in = new PushbackInputStream(openSampleStream(sampleFileName), 10); - try { - boolean actualResult; - try { - actualResult = POIFSFileSystem.hasPOIFSHeader(in); - } catch (IOException e) { - throw new RuntimeException(e); - } - assertEquals(expectedResult, actualResult); - } finally { - in.close(); - } - } - - public void testFileCorruption() throws Exception { - - // create test InputStream - byte[] testData = { (byte)1, (byte)2, (byte)3 }; - InputStream testInput = new ByteArrayInputStream(testData); - - // detect header - InputStream in = new PushbackInputStream(testInput, 10); - assertFalse(POIFSFileSystem.hasPOIFSHeader(in)); - - // check if InputStream is still intact - byte[] test = new byte[3]; - in.read(test); - assertTrue(Arrays.equals(testData, test)); - assertEquals(-1, in.read()); - } - - - public void testFileCorruptionOPOIFS() throws Exception { - - // create test InputStream - byte[] testData = { (byte)1, (byte)2, (byte)3 }; - InputStream testInput = new ByteArrayInputStream(testData); - - // detect header - InputStream in = new PushbackInputStream(testInput, 10); - assertFalse(OPOIFSFileSystem.hasPOIFSHeader(in)); - - // check if InputStream is still intact - byte[] test = new byte[3]; - in.read(test); - assertTrue(Arrays.equals(testData, test)); - assertEquals(-1, in.read()); - } -} diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestOle10Native.java b/src/testcases/org/apache/poi/poifs/filesystem/TestOle10Native.java deleted file mode 100644 index 0abdf8489..000000000 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestOle10Native.java +++ /dev/null @@ -1,125 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.filesystem; - -import static org.hamcrest.core.IsEqual.equalTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.util.IOUtils; -import org.junit.Ignore; -import org.junit.Test; - -public class TestOle10Native { - private static final POIDataSamples dataSamples = POIDataSamples.getPOIFSInstance(); - - @Test - public void testOleNative() throws IOException, Ole10NativeException { - POIFSFileSystem fs = new POIFSFileSystem(dataSamples.openResourceAsStream("oleObject1.bin")); - - Ole10Native ole = Ole10Native.createFromEmbeddedOleObject(fs); - - assertEquals("File1.svg", ole.getLabel()); - assertEquals("D:\\Documents and Settings\\rsc\\My Documents\\file1.svg", ole.getCommand()); - } - - @Test - public void testFiles() throws IOException, Ole10NativeException { - File files[] = { - // bug 51891 - POIDataSamples.getPOIFSInstance().getFile("multimedia.doc"), - // tika bug 1072 - POIDataSamples.getPOIFSInstance().getFile("20-Force-on-a-current-S00.doc"), - // other files containing ole10native records ... - POIDataSamples.getDocumentInstance().getFile("Bug53380_3.doc"), - POIDataSamples.getDocumentInstance().getFile("Bug47731.doc") - }; - - for (File f : files) { - NPOIFSFileSystem fs = new NPOIFSFileSystem(f, true); - List entries = new ArrayList(); - findOle10(entries, fs.getRoot(), "/", ""); - - for (Entry e : entries) { - ByteArrayOutputStream bosExp = new ByteArrayOutputStream(); - InputStream is = ((DirectoryNode)e.getParent()).createDocumentInputStream(e); - IOUtils.copy(is,bosExp); - is.close(); - - Ole10Native ole = Ole10Native.createFromEmbeddedOleObject((DirectoryNode)e.getParent()); - - ByteArrayOutputStream bosAct = new ByteArrayOutputStream(); - ole.writeOut(bosAct); - - assertThat(bosExp.toByteArray(), equalTo(bosAct.toByteArray())); - } - - fs.close(); - } - } - - /* - void searchOle10Files() throws Exception { - File dir = new File("test-data/document"); - for (File file : dir.listFiles(new FileFilter(){ - public boolean accept(File pathname) { - return pathname.getName().endsWith("doc"); - } - })) { - NPOIFSFileSystem fs = new NPOIFSFileSystem(file, true); - findOle10(null, fs.getRoot(), "/", file.getName()); - fs.close(); - } - }*/ - - void findOle10(List entries, DirectoryNode dn, String path, String filename) { - Iterator iter = dn.getEntries(); - while (iter.hasNext()) { - Entry e = iter.next(); - if (Ole10Native.OLE10_NATIVE.equals(e.getName())) { - if (entries != null) entries.add(e); - // System.out.println(filename+" : "+path); - } else if (e.isDirectoryEntry()) { - findOle10(entries, (DirectoryNode)e, path+e.getName()+"/", filename); - } - } - } - - @Test - public void testOleNativeOOM() throws IOException, Ole10NativeException { - POIFSFileSystem fs = new POIFSFileSystem(dataSamples.openResourceAsStream("60256.bin")); - try { - Ole10Native.createFromEmbeddedOleObject(fs); - fail("Should have thrown exception because OLENative lacks a length parameter"); - } catch (Ole10NativeException e) { - assertTrue(e.getMessage().indexOf("declared data length") > -1); - } - } - -} diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSDocumentPath.java b/src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSDocumentPath.java deleted file mode 100644 index 0ca030438..000000000 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSDocumentPath.java +++ /dev/null @@ -1,314 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.filesystem; - -import junit.framework.TestCase; - -/** - * Class to test POIFSDocumentPath functionality - * - * @author Marc Johnson - */ -public final class TestPOIFSDocumentPath extends TestCase { - - - /** - * Test default constructor - */ - public void testDefaultConstructor() { - POIFSDocumentPath path = new POIFSDocumentPath(); - - assertEquals(0, path.length()); - } - - /** - * Test full path constructor - */ - public void testFullPathConstructor() { - String[] components = - { - "foo", "bar", "foobar", "fubar" - }; - - for (int j = 0; j < components.length; j++) - { - String[] params = new String[ j ]; - - for (int k = 0; k < j; k++) - { - params[ k ] = components[ k ]; - } - POIFSDocumentPath path = new POIFSDocumentPath(params); - - assertEquals(j, path.length()); - for (int k = 0; k < j; k++) - { - assertEquals(components[ k ], path.getComponent(k)); - } - if (j == 0) - { - assertNull(path.getParent()); - } - else - { - POIFSDocumentPath parent = path.getParent(); - - assertNotNull(parent); - assertEquals(j - 1, parent.length()); - for (int k = 0; k < j - 1; k++) - { - assertEquals(components[ k ], parent.getComponent(k)); - } - } - } - - // test weird variants - assertEquals(0, new POIFSDocumentPath(null).length()); - try - { - new POIFSDocumentPath(new String[] - { - "fu", "" - }); - fail("should have caught IllegalArgumentException"); - } - catch (IllegalArgumentException ignored) - { - } - try - { - new POIFSDocumentPath(new String[] - { - "fu", null - }); - fail("should have caught IllegalArgumentException"); - } - catch (IllegalArgumentException ignored) - { - } - } - - /** - * Test relative path constructor - */ - public void testRelativePathConstructor() { - String[] initialComponents = - { - "a", "b", "c" - }; - - for (int n = 0; n < initialComponents.length; n++) - { - String[] initialParams = new String[ n ]; - - for (int k = 0; k < n; k++) - { - initialParams[ k ] = initialComponents[ k ]; - } - POIFSDocumentPath base = - new POIFSDocumentPath(initialParams); - String[] components = - { - "foo", "bar", "foobar", "fubar" - }; - - for (int j = 0; j < components.length; j++) - { - String[] params = new String[ j ]; - - for (int k = 0; k < j; k++) - { - params[ k ] = components[ k ]; - } - POIFSDocumentPath path = new POIFSDocumentPath(base, params); - - assertEquals(j + n, path.length()); - for (int k = 0; k < n; k++) - { - assertEquals(initialComponents[ k ], - path.getComponent(k)); - } - for (int k = 0; k < j; k++) - { - assertEquals(components[ k ], path.getComponent(k + n)); - } - if ((j + n) == 0) - { - assertNull(path.getParent()); - } - else - { - POIFSDocumentPath parent = path.getParent(); - - assertNotNull(parent); - assertEquals(j + n - 1, parent.length()); - for (int k = 0; k < (j + n - 1); k++) - { - assertEquals(path.getComponent(k), - parent.getComponent(k)); - } - } - } - - // Test weird variants - - // This one is allowed, even if it's really odd - assertEquals(n, new POIFSDocumentPath(base, null).length()); - new POIFSDocumentPath(base, new String[] - { - "fu", "" - }); - - // This one is allowed too - new POIFSDocumentPath(base, new String[] - { - "", "fu" - }); - - // This one shouldn't be allowed - try - { - new POIFSDocumentPath(base, new String[] - { - "fu", null - }); - fail("should have caught IllegalArgumentException"); - } - catch (IllegalArgumentException ignored) - { - } - - // Ditto - try - { - new POIFSDocumentPath(base, new String[] - { - null, "fu" - }); - fail("should have caught IllegalArgumentException"); - } - catch (IllegalArgumentException ignored) - { - } - } - } - - /** - * test equality - */ - public void testEquality() { - POIFSDocumentPath a1 = new POIFSDocumentPath(); - POIFSDocumentPath a2 = new POIFSDocumentPath(null); - POIFSDocumentPath a3 = new POIFSDocumentPath(new String[ 0 ]); - POIFSDocumentPath a4 = new POIFSDocumentPath(a1, null); - POIFSDocumentPath a5 = new POIFSDocumentPath(a1, - new String[ 0 ]); - POIFSDocumentPath[] paths = - { - a1, a2, a3, a4, a5 - }; - - for (int j = 0; j < paths.length; j++) - { - for (int k = 0; k < paths.length; k++) - { - assertEquals(j + "<>" + k, - paths[ j ], paths[ k ]); - } - } - a2 = new POIFSDocumentPath(a1, new String[] - { - "foo" - }); - a3 = new POIFSDocumentPath(a2, new String[] - { - "bar" - }); - a4 = new POIFSDocumentPath(a3, new String[] - { - "fubar" - }); - a5 = new POIFSDocumentPath(a4, new String[] - { - "foobar" - }); - POIFSDocumentPath[] builtUpPaths = - { - a1, a2, a3, a4, a5 - }; - POIFSDocumentPath[] fullPaths = - { - new POIFSDocumentPath(), new POIFSDocumentPath(new String[] - { - "foo" - }), new POIFSDocumentPath(new String[] - { - "foo", "bar" - }), new POIFSDocumentPath(new String[] - { - "foo", "bar", "fubar" - }), new POIFSDocumentPath(new String[] - { - "foo", "bar", "fubar", "foobar" - }) - }; - - for (int k = 0; k < builtUpPaths.length; k++) - { - for (int j = 0; j < fullPaths.length; j++) - { - if (k == j) - { - assertEquals(j + "<>" - + k, fullPaths[ j ], - builtUpPaths[ k ]); - } - else - { - assertTrue(j + "<>" + k, - !(fullPaths[ j ].equals(builtUpPaths[ k ]))); - } - } - } - POIFSDocumentPath[] badPaths = - { - new POIFSDocumentPath(new String[] - { - "_foo" - }), new POIFSDocumentPath(new String[] - { - "foo", "_bar" - }), new POIFSDocumentPath(new String[] - { - "foo", "bar", "_fubar" - }), new POIFSDocumentPath(new String[] - { - "foo", "bar", "fubar", "_foobar" - }) - }; - - for (int k = 0; k < builtUpPaths.length; k++) - { - for (int j = 0; j < badPaths.length; j++) - { - assertTrue(j + "<>" + k, - !(fullPaths[ k ].equals(badPaths[ j ]))); - } - } - } -} diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSFileSystem.java b/src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSFileSystem.java deleted file mode 100644 index 9aac65ab4..000000000 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSFileSystem.java +++ /dev/null @@ -1,303 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.filesystem; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.nio.ByteBuffer; - -import junit.framework.TestCase; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.poifs.common.POIFSBigBlockSize; -import org.apache.poi.poifs.common.POIFSConstants; -import org.apache.poi.poifs.storage.BATBlock; -import org.apache.poi.poifs.storage.BlockAllocationTableReader; -import org.apache.poi.poifs.storage.HeaderBlock; -import org.apache.poi.poifs.storage.RawDataBlockList; - -/** - * Tests for the older OPOIFS-based POIFSFileSystem - */ -public final class TestPOIFSFileSystem extends TestCase { - private final POIDataSamples _samples = POIDataSamples.getPOIFSInstance(); - - /** - * Mock exception used to ensure correct error handling - */ - private static final class MyEx extends RuntimeException { - public MyEx() { - // no fields to initialise - } - } - /** - * Helps facilitate testing. Keeps track of whether close() was called. - * Also can throw an exception at a specific point in the stream. - */ - private static final class TestIS extends InputStream { - - private final InputStream _is; - private final int _failIndex; - private int _currentIx; - private boolean _isClosed; - - public TestIS(InputStream is, int failIndex) { - _is = is; - _failIndex = failIndex; - _currentIx = 0; - _isClosed = false; - } - - @Override - public int read() throws IOException { - int result = _is.read(); - if(result >=0) { - checkRead(1); - } - return result; - } - @Override - public int read(byte[] b, int off, int len) throws IOException { - int result = _is.read(b, off, len); - checkRead(result); - return result; - } - - private void checkRead(int nBytes) { - _currentIx += nBytes; - if(_failIndex > 0 && _currentIx > _failIndex) { - throw new MyEx(); - } - } - @Override - public void close() throws IOException { - _isClosed = true; - _is.close(); - } - public boolean isClosed() { - return _isClosed; - } - } - - /** - * Test for undesired behaviour observable as of svn revision 618865 (5-Feb-2008). - * POIFSFileSystem was not closing the input stream. - */ - public void testAlwaysClose() { - TestIS testIS; - - // Normal case - read until EOF and close - testIS = new TestIS(openSampleStream("13224.xls"), -1); - try { - new OPOIFSFileSystem(testIS); - } catch (IOException e) { - throw new RuntimeException(e); - } - assertTrue("input stream was not closed", testIS.isClosed()); - - // intended to crash after reading 10000 bytes - testIS = new TestIS(openSampleStream("13224.xls"), 10000); - try { - new OPOIFSFileSystem(testIS); - fail("ex should have been thrown"); - } catch (IOException e) { - throw new RuntimeException(e); - } catch (MyEx e) { - // expected - } - assertTrue("input stream was not closed", testIS.isClosed()); // but still should close - } - - /** - * Test for bug # 48898 - problem opening an OLE2 - * file where the last block is short (i.e. not a full - * multiple of 512 bytes) - * - * As yet, this problem remains. One school of thought is - * not not issue an EOF when we discover the last block - * is short, but this seems a bit wrong. - * The other is to fix the handling of the last block in - * POIFS, since it seems to be slight wrong - */ - public void testShortLastBlock() throws Exception { - String[] files = new String[] { - "ShortLastBlock.qwp", "ShortLastBlock.wps" - }; - - for (String file : files) { - // Open the file up - OPOIFSFileSystem fs = new OPOIFSFileSystem( - _samples.openResourceAsStream(file) - ); - - // Write it into a temp output array - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - fs.writeFilesystem(baos); - - // Check sizes - } - } - - /** - * Check that we do the right thing when the list of which - * sectors are BAT blocks points off the list of - * sectors that exist in the file. - */ - public void testFATandDIFATsectors() throws Exception { - // Open the file up - try { - InputStream stream = _samples.openResourceAsStream("ReferencesInvalidSectors.mpp"); - try { - new OPOIFSFileSystem(stream); - fail("File is corrupt and shouldn't have been opened"); - } finally { - stream.close(); - } - } catch (IOException e) { - String msg = e.getMessage(); - assertTrue(msg.startsWith("Your file contains 695 sectors")); - } - } - - /** - * Tests that we can write and read a file that contains XBATs - * as well as regular BATs. - * However, because a file needs to be at least 6.875mb big - * to have an XBAT in it, we don't have a test one. So, generate it. - */ - public void testBATandXBAT() throws Exception { - byte[] hugeStream = new byte[8*1024*1024]; - OPOIFSFileSystem fs = new OPOIFSFileSystem(); - fs.getRoot().createDocument( - "BIG", new ByteArrayInputStream(hugeStream) - ); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - fs.writeFilesystem(baos); - byte[] fsData = baos.toByteArray(); - - - // Check the header was written properly - InputStream inp = new ByteArrayInputStream(fsData); - HeaderBlock header = new HeaderBlock(inp); - assertEquals(109+21, header.getBATCount()); - assertEquals(1, header.getXBATCount()); - - - // We should have 21 BATs in the XBAT - ByteBuffer xbatData = ByteBuffer.allocate(512); - xbatData.put(fsData, (1+header.getXBATIndex())*512, 512); - xbatData.position(0); - BATBlock xbat = BATBlock.createBATBlock(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, xbatData); - for(int i=0; i<21; i++) { - assertTrue(xbat.getValueAt(i) != POIFSConstants.UNUSED_BLOCK); - } - for(int i=21; i<127; i++) { - assertEquals(POIFSConstants.UNUSED_BLOCK, xbat.getValueAt(i)); - } - assertEquals(POIFSConstants.END_OF_CHAIN, xbat.getValueAt(127)); - - - // Load the blocks and check with that - RawDataBlockList blockList = new RawDataBlockList(inp, POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS); - assertEquals(fsData.length / 512, blockList.blockCount() + 1); // Header not counted - new BlockAllocationTableReader(header.getBigBlockSize(), - header.getBATCount(), - header.getBATArray(), - header.getXBATCount(), - header.getXBATIndex(), - blockList); - assertEquals(fsData.length / 512, blockList.blockCount() + 1); // Header not counted - - // Now load it and check - fs = null; - fs = new OPOIFSFileSystem( - new ByteArrayInputStream(fsData) - ); - - DirectoryNode root = fs.getRoot(); - assertEquals(1, root.getEntryCount()); - DocumentNode big = (DocumentNode)root.getEntry("BIG"); - assertEquals(hugeStream.length, big.getSize()); - } - - /** - * Most OLE2 files use 512byte blocks. However, a small number - * use 4k blocks. Check that we can open these. - */ - public void test4KBlocks() throws Exception { - POIDataSamples _samples = POIDataSamples.getPOIFSInstance(); - InputStream inp = _samples.openResourceAsStream("BlockSize4096.zvi"); - try { - // First up, check that we can process the header properly - HeaderBlock header_block = new HeaderBlock(inp); - POIFSBigBlockSize bigBlockSize = header_block.getBigBlockSize(); - assertEquals(4096, bigBlockSize.getBigBlockSize()); - - // Check the fat info looks sane - assertEquals(1, header_block.getBATArray().length); - assertEquals(1, header_block.getBATCount()); - assertEquals(0, header_block.getXBATCount()); - - // Now check we can get the basic fat - RawDataBlockList data_blocks = new RawDataBlockList(inp, - bigBlockSize); - assertEquals(15, data_blocks.blockCount()); - - // Now try and open properly - OPOIFSFileSystem fs = new OPOIFSFileSystem( - _samples.openResourceAsStream("BlockSize4096.zvi")); - assertTrue(fs.getRoot().getEntryCount() > 3); - - // Check we can get at all the contents - checkAllDirectoryContents(fs.getRoot()); - - // Finally, check we can do a similar 512byte one too - fs = new OPOIFSFileSystem( - _samples.openResourceAsStream("BlockSize512.zvi")); - assertTrue(fs.getRoot().getEntryCount() > 3); - checkAllDirectoryContents(fs.getRoot()); - } finally { - inp.close(); - } - } - private void checkAllDirectoryContents(DirectoryEntry dir) throws IOException { - for(Entry entry : dir) { - if(entry instanceof DirectoryEntry) { - checkAllDirectoryContents((DirectoryEntry)entry); - } else { - DocumentNode doc = (DocumentNode) entry; - DocumentInputStream dis = new DocumentInputStream(doc); - try { - int numBytes = dis.available(); - byte[] data = new byte [numBytes]; - dis.read(data); - } finally { - dis.close(); - } - } - } - } - - private static InputStream openSampleStream(String sampleFileName) { - return HSSFTestDataSamples.openSampleFileStream(sampleFileName); - } -} diff --git a/src/testcases/org/apache/poi/poifs/filesystem/TestPropertySorter.java b/src/testcases/org/apache/poi/poifs/filesystem/TestPropertySorter.java deleted file mode 100644 index 09388c233..000000000 --- a/src/testcases/org/apache/poi/poifs/filesystem/TestPropertySorter.java +++ /dev/null @@ -1,151 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.filesystem; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Comparator; -import java.util.Iterator; -import java.util.List; - -import junit.framework.ComparisonFailure; -import junit.framework.TestCase; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.poifs.property.DirectoryProperty; -import org.apache.poi.poifs.property.Property; - -/** - * Verify the order of entries DirectoryProperty . - *

    - * In particular it is important to serialize ROOT._VBA_PROJECT_CUR.VBA node. - * See bug 39234 in bugzilla. Thanks to Bill Seddon for providing the solution. - *

    - * - * @author Yegor Kozlov - */ -public final class TestPropertySorter extends TestCase { - - //the correct order of entries in the test file - private static final String[] _entries = { - "dir", "JML", "UTIL", "Loader", "Sheet1", "Sheet2", "Sheet3", - "__SRP_0", "__SRP_1", "__SRP_2", "__SRP_3", "__SRP_4", "__SRP_5", - "ThisWorkbook", "_VBA_PROJECT", - }; - - private static POIFSFileSystem openSampleFS() { - InputStream is = HSSFTestDataSamples.openSampleFileStream("39234.xls"); - try { - return new POIFSFileSystem(is); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - /** - * Test sorting of properties in DirectoryProperty - */ - public void testSortProperties() throws IOException { - POIFSFileSystem fs = openSampleFS(); - Property[] props = getVBAProperties(fs); - - assertEquals(_entries.length, props.length); - - // (1). See that there is a problem with the old case-sensitive property comparator - Arrays.sort(props, OldCaseSensitivePropertyComparator); - try { - for (int i = 0; i < props.length; i++) { - assertEquals(_entries[i], props[i].getName()); - } - fail("expected old case-sensitive property comparator to return properties in wrong order"); - } catch (ComparisonFailure e){ - // expected during successful test - assertNotNull(e.getMessage()); - } - - // (2) Verify that the fixed property comparator works right - Arrays.sort(props, new DirectoryProperty.PropertyComparator()); - for (int i = 0; i < props.length; i++) { - assertEquals(_entries[i], props[i].getName()); - } - } - - /** - * Serialize file system and verify that the order of properties is the same as in the original file. - */ - public void testSerialization() throws IOException { - POIFSFileSystem fs = openSampleFS(); - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - fs.writeFilesystem(out); - out.close(); - InputStream is = new ByteArrayInputStream(out.toByteArray()); - fs = new POIFSFileSystem(is); - is.close(); - Property[] props = getVBAProperties(fs); - Arrays.sort(props, new DirectoryProperty.PropertyComparator()); - - assertEquals(_entries.length, props.length); - for (int i = 0; i < props.length; i++) { - assertEquals(_entries[i], props[i].getName()); - } - } - - /** - * @return array of properties read from ROOT._VBA_PROJECT_CUR.VBA node - */ - protected Property[] getVBAProperties(POIFSFileSystem fs) throws IOException { - String _VBA_PROJECT_CUR = "_VBA_PROJECT_CUR"; - String VBA = "VBA"; - - DirectoryEntry root = fs.getRoot(); - DirectoryEntry vba_project = (DirectoryEntry)root.getEntry(_VBA_PROJECT_CUR); - - DirectoryNode vba = (DirectoryNode)vba_project.getEntry(VBA); - DirectoryProperty p = (DirectoryProperty)vba.getProperty(); - - List lst = new ArrayList(); - for (Iterator it = p.getChildren(); it.hasNext();){ - Property ch = it.next(); - lst.add(ch); - } - return lst.toArray(new Property[ 0 ]); - } - - /** - * Old version of case-sensitive PropertyComparator to demonstrate the problem - */ - private static final Comparator OldCaseSensitivePropertyComparator = new Comparator() { - - @Override - public int compare(Property o1, Property o2) { - String name1 = o1.getName(); - String name2 = o2.getName(); - int result = name1.length() - name2.length(); - - if (result == 0) { - result = name1.compareTo(name2); - } - return result; - } - }; -} diff --git a/src/testcases/org/apache/poi/poifs/macros/TestVBAMacroReader.java b/src/testcases/org/apache/poi/poifs/macros/TestVBAMacroReader.java deleted file mode 100644 index eeb43b4d2..000000000 --- a/src/testcases/org/apache/poi/poifs/macros/TestVBAMacroReader.java +++ /dev/null @@ -1,289 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.macros; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.StringUtil; -import org.junit.Ignore; -import org.junit.Test; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -import static org.apache.poi.POITestCase.assertContains; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; - -public class TestVBAMacroReader { - private static final Map expectedMacroContents; - - protected static String readVBA(POIDataSamples poiDataSamples) { - File macro = poiDataSamples.getFile("SimpleMacro.vba"); - final byte[] bytes; - try { - FileInputStream stream = new FileInputStream(macro); - try { - bytes = IOUtils.toByteArray(stream); - } finally { - stream.close(); - } - } catch (IOException e) { - throw new RuntimeException(e); - } - - String testMacroContents = new String(bytes, StringUtil.UTF8); - - if (! testMacroContents.startsWith("Sub ")) { - throw new IllegalArgumentException("Not a macro"); - } - - return testMacroContents.substring(testMacroContents.indexOf("()")+3); - } - - static { - final Map _expectedMacroContents = new HashMap(); - final POIDataSamples[] dataSamples = { - POIDataSamples.getSpreadSheetInstance(), - POIDataSamples.getSlideShowInstance(), - POIDataSamples.getDocumentInstance(), - POIDataSamples.getDiagramInstance() - }; - for (POIDataSamples sample : dataSamples) { - _expectedMacroContents.put(sample, readVBA(sample)); - } - expectedMacroContents = Collections.unmodifiableMap(_expectedMacroContents); - } - - //////////////////////////////// From Stream ///////////////////////////// - @Test - public void HSSFfromStream() throws Exception { - fromStream(POIDataSamples.getSpreadSheetInstance(), "SimpleMacro.xls"); - } - @Test - public void XSSFfromStream() throws Exception { - fromStream(POIDataSamples.getSpreadSheetInstance(), "SimpleMacro.xlsm"); - } - @Ignore("bug 59302: Found 0 macros; See org.apache.poi.hslf.usermodel.TestBugs.getMacrosFromHSLF()" + - "for an example of how to get macros out of ppt. TODO: make integration across file formats more elegant") - @Test - public void HSLFfromStream() throws Exception { - fromStream(POIDataSamples.getSlideShowInstance(), "SimpleMacro.ppt"); - } - @Test - public void XSLFfromStream() throws Exception { - fromStream(POIDataSamples.getSlideShowInstance(), "SimpleMacro.pptm"); - } - @Test - public void HWPFfromStream() throws Exception { - fromStream(POIDataSamples.getDocumentInstance(), "SimpleMacro.doc"); - } - @Test - public void XWPFfromStream() throws Exception { - fromStream(POIDataSamples.getDocumentInstance(), "SimpleMacro.docm"); - } - @Ignore("Found 0 macros") - @Test - public void HDGFfromStream() throws Exception { - fromStream(POIDataSamples.getDiagramInstance(), "SimpleMacro.vsd"); - } - @Test - public void XDGFfromStream() throws Exception { - fromStream(POIDataSamples.getDiagramInstance(), "SimpleMacro.vsdm"); - } - - //////////////////////////////// From File ///////////////////////////// - @Test - public void HSSFfromFile() throws Exception { - fromFile(POIDataSamples.getSpreadSheetInstance(), "SimpleMacro.xls"); - } - @Test - public void XSSFfromFile() throws Exception { - fromFile(POIDataSamples.getSpreadSheetInstance(), "SimpleMacro.xlsm"); - } - @Ignore("bug 59302: Found 0 macros; See org.apache.poi.hslf.usermodel.TestBugs.getMacrosFromHSLF()" + - "for an example of how to get macros out of ppt. TODO: make integration across file formats more elegant") - @Test - public void HSLFfromFile() throws Exception { - fromFile(POIDataSamples.getSlideShowInstance(), "SimpleMacro.ppt"); - } - @Test - public void XSLFfromFile() throws Exception { - fromFile(POIDataSamples.getSlideShowInstance(), "SimpleMacro.pptm"); - } - @Test - public void HWPFfromFile() throws Exception { - fromFile(POIDataSamples.getDocumentInstance(), "SimpleMacro.doc"); - } - @Test - public void XWPFfromFile() throws Exception { - fromFile(POIDataSamples.getDocumentInstance(), "SimpleMacro.docm"); - } - @Ignore("Found 0 macros") - @Test - public void HDGFfromFile() throws Exception { - fromFile(POIDataSamples.getDiagramInstance(), "SimpleMacro.vsd"); - } - @Test - public void XDGFfromFile() throws Exception { - fromFile(POIDataSamples.getDiagramInstance(), "SimpleMacro.vsdm"); - } - - //////////////////////////////// From NPOIFS ///////////////////////////// - @Test - public void HSSFfromNPOIFS() throws Exception { - fromNPOIFS(POIDataSamples.getSpreadSheetInstance(), "SimpleMacro.xls"); - } - @Ignore("bug 59302: Found 0 macros") - @Test - public void HSLFfromNPOIFS() throws Exception { - fromNPOIFS(POIDataSamples.getSlideShowInstance(), "SimpleMacro.ppt"); - } - @Test - public void HWPFfromNPOIFS() throws Exception { - fromNPOIFS(POIDataSamples.getDocumentInstance(), "SimpleMacro.doc"); - } - @Ignore("Found 0 macros") - @Test - public void HDGFfromNPOIFS() throws Exception { - fromNPOIFS(POIDataSamples.getDiagramInstance(), "SimpleMacro.vsd"); - } - - protected void fromFile(POIDataSamples dataSamples, String filename) throws IOException { - File f = dataSamples.getFile(filename); - VBAMacroReader r = new VBAMacroReader(f); - try { - assertMacroContents(dataSamples, r); - } finally { - r.close(); - } - } - - protected void fromStream(POIDataSamples dataSamples, String filename) throws IOException { - InputStream fis = dataSamples.openResourceAsStream(filename); - try { - VBAMacroReader r = new VBAMacroReader(fis); - try { - assertMacroContents(dataSamples, r); - } finally { - r.close(); - } - } finally { - fis.close(); - } - } - - protected void fromNPOIFS(POIDataSamples dataSamples, String filename) throws IOException { - File f = dataSamples.getFile(filename); - NPOIFSFileSystem fs = new NPOIFSFileSystem(f); - try { - VBAMacroReader r = new VBAMacroReader(fs); - try { - assertMacroContents(dataSamples, r); - } finally { - r.close(); - } - } finally { - fs.close(); - } - } - - protected void assertMacroContents(POIDataSamples samples, VBAMacroReader r) throws IOException { - assertNotNull(r); - Map contents = r.readMacros(); - assertNotNull(contents); - assertFalse("Found 0 macros", contents.isEmpty()); - /* - assertEquals(5, contents.size()); - - // Check the ones without scripts - String[] noScripts = new String[] { "ThisWorkbook", - "Sheet1", "Sheet2", "Sheet3" }; - for (String entry : noScripts) { - assertTrue(entry, contents.containsKey(entry)); - - String content = contents.get(entry); - assertContains(content, "Attribute VB_Exposed = True"); - assertContains(content, "Attribute VB_Customizable = True"); - assertContains(content, "Attribute VB_TemplateDerived = False"); - assertContains(content, "Attribute VB_GlobalNameSpace = False"); - assertContains(content, "Attribute VB_Exposed = True"); - } - */ - - // Check the script one - assertContains(contents, "Module1"); - String content = contents.get("Module1"); - assertNotNull(content); - assertContains(content, "Attribute VB_Name = \"Module1\""); - //assertContains(content, "Attribute TestMacro.VB_Description = \"This is a test macro\""); - - // And the macro itself - String testMacroNoSub = expectedMacroContents.get(samples); - assertContains(content, testMacroNoSub); - } - - - @Test - public void bug59830() throws IOException { - //test file is "609751.xls" in govdocs1 - File f = POIDataSamples.getSpreadSheetInstance().getFile("59830.xls"); - VBAMacroReader r = new VBAMacroReader(f); - Map macros = r.readMacros(); - assertNotNull(macros.get("Module20")); - assertContains(macros.get("Module20"), "here start of superscripting"); - r.close(); - } - - @Test - public void bug59858() throws IOException { - File f = POIDataSamples.getSpreadSheetInstance().getFile("59858.xls"); - VBAMacroReader r = new VBAMacroReader(f); - Map macros = r.readMacros(); - assertNotNull(macros.get("Sheet4")); - assertContains(macros.get("Sheet4"), "intentional constituent"); - r.close(); - } - - @Test - public void bug60158() throws IOException { - File f = POIDataSamples.getDocumentInstance().getFile("60158.docm"); - VBAMacroReader r = new VBAMacroReader(f); - Map macros = r.readMacros(); - assertNotNull(macros.get("NewMacros")); - assertContains(macros.get("NewMacros"), "' dirty"); - r.close(); - } - - @Test - public void bug60273() throws IOException { - //test file derives from govdocs1 147240.xls - File f = POIDataSamples.getSpreadSheetInstance().getFile("60273.xls"); - VBAMacroReader r = new VBAMacroReader(f); - Map macros = r.readMacros(); - assertNotNull(macros.get("Module1")); - assertContains(macros.get("Module1"), "9/8/2004"); - r.close(); - } -} diff --git a/src/testcases/org/apache/poi/poifs/nio/TestDataSource.java b/src/testcases/org/apache/poi/poifs/nio/TestDataSource.java deleted file mode 100644 index 1bc3f4532..000000000 --- a/src/testcases/org/apache/poi/poifs/nio/TestDataSource.java +++ /dev/null @@ -1,274 +0,0 @@ - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - - -package org.apache.poi.poifs.nio; - -import junit.framework.TestCase; -import org.apache.poi.POIDataSamples; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.TempFile; - -import java.io.*; -import java.nio.BufferUnderflowException; -import java.nio.ByteBuffer; - -/** - * Tests for the datasource implementations - */ -public class TestDataSource extends TestCase -{ - private static POIDataSamples data = POIDataSamples.getPOIFSInstance(); - - public void testFile() throws Exception { - File f = data.getFile("Notes.ole2"); - - FileBackedDataSource ds = new FileBackedDataSource(f); - try { - checkDataSource(ds, false); - } finally { - ds.close(); - } - - // try a second time - ds = new FileBackedDataSource(f); - try { - checkDataSource(ds, false); - } finally { - ds.close(); - } - } - - public void testFileWritable() throws Exception { - File temp = TempFile.createTempFile("TestDataSource", ".test"); - try { - writeDataToFile(temp); - - FileBackedDataSource ds = new FileBackedDataSource(temp, false); - try { - checkDataSource(ds, true); - } finally { - ds.close(); - } - - // try a second time - ds = new FileBackedDataSource(temp, false); - try { - checkDataSource(ds, true); - } finally { - ds.close(); - } - - writeDataToFile(temp); - } finally { - assertTrue(temp.exists()); - assertTrue("Could not delete file " + temp, temp.delete()); - } - } - - - public void testRewritableFile() throws Exception { - File temp = TempFile.createTempFile("TestDataSource", ".test"); - try { - writeDataToFile(temp); - - FileBackedDataSource ds = new FileBackedDataSource(temp, true); - try { - ByteBuffer buf = ds.read(0, 10); - assertNotNull(buf); - buf = ds.read(8, 0x400); - assertNotNull(buf); - } finally { - ds.close(); - } - - // try a second time - ds = new FileBackedDataSource(temp, true); - try { - ByteBuffer buf = ds.read(0, 10); - assertNotNull(buf); - buf = ds.read(8, 0x400); - assertNotNull(buf); - } finally { - ds.close(); - } - - writeDataToFile(temp); - } finally { - assertTrue(temp.exists()); - assertTrue(temp.delete()); - } - } - - private void writeDataToFile(File temp) throws IOException { - OutputStream str = new FileOutputStream(temp); - try { - InputStream in = data.openResourceAsStream("Notes.ole2"); - try { - IOUtils.copy(in, str); - } finally { - in.close(); - } - } finally { - str.close(); - } - } - - private void checkDataSource(FileBackedDataSource ds, boolean writeable) throws IOException { - assertEquals(writeable, ds.isWriteable()); - assertNotNull(ds.getChannel()); - - // rewriting changes the size - if(writeable) { - assertTrue("Had: " + ds.size(), ds.size() == 8192 || ds.size() == 8198); - } else { - assertEquals(8192, ds.size()); - } - - // Start of file - ByteBuffer bs; - bs = ds.read(4, 0); - assertEquals(4, bs.capacity()); - assertEquals(0, bs.position()); - assertEquals(0xd0 - 256, bs.get(0)); - assertEquals(0xcf - 256, bs.get(1)); - assertEquals(0x11, bs.get(2)); - assertEquals(0xe0 - 256, bs.get(3)); - assertEquals(0xd0 - 256, bs.get()); - assertEquals(0xcf - 256, bs.get()); - assertEquals(0x11, bs.get()); - assertEquals(0xe0 - 256, bs.get()); - - // Mid way through - bs = ds.read(8, 0x400); - assertEquals(8, bs.capacity()); - assertEquals(0, bs.position()); - assertEquals((byte) 'R', bs.get(0)); - assertEquals(0, bs.get(1)); - assertEquals((byte) 'o', bs.get(2)); - assertEquals(0, bs.get(3)); - assertEquals((byte) 'o', bs.get(4)); - assertEquals(0, bs.get(5)); - assertEquals((byte) 't', bs.get(6)); - assertEquals(0, bs.get(7)); - - // Can go to the end, but not past it - bs = ds.read(8, 8190); - assertEquals(0, bs.position()); // TODO How best to warn of a short read? - - // Can't go off the end - try { - ds.read(4, 8192); - if(!writeable) { - fail("Shouldn't be able to read off the end of the file"); - } - } catch (IndexOutOfBoundsException e) { - // expected here - } - } - - public void testByteArray() throws Exception { - byte[] data = new byte[256]; - byte b; - for(int i=0; i - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestDirectoryProperty.class, - TestDocumentProperty.class, - TestPropertyFactory.class, - TestPropertyTable.class, - TestRootProperty.class -}) -public final class AllPOIFSPropertyTests { -} diff --git a/src/testcases/org/apache/poi/poifs/property/LocalProperty.java b/src/testcases/org/apache/poi/poifs/property/LocalProperty.java deleted file mode 100644 index f578129b6..000000000 --- a/src/testcases/org/apache/poi/poifs/property/LocalProperty.java +++ /dev/null @@ -1,60 +0,0 @@ - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - - -package org.apache.poi.poifs.property; - -class LocalProperty - extends Property -{ - - /** - * Constructor LocalProperty - * - * @param index - */ - - LocalProperty(int index) - { - super(); - setName("foo" + index); - setIndex(index); - } - - /** - * Method preWrite - */ - - @Override - protected void preWrite() - { - } - - /** - * Method isDirectory - * - * @return false - */ - - @Override - public boolean isDirectory() - { - return false; - } -} // end package-scope class LocalProperty - diff --git a/src/testcases/org/apache/poi/poifs/property/TestDirectoryProperty.java b/src/testcases/org/apache/poi/poifs/property/TestDirectoryProperty.java deleted file mode 100644 index 8db101c25..000000000 --- a/src/testcases/org/apache/poi/poifs/property/TestDirectoryProperty.java +++ /dev/null @@ -1,304 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.property; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; - -import org.apache.poi.poifs.storage.RawDataUtil; -import org.apache.poi.util.LocaleUtil; -import org.junit.Test; - -/** - * Class to test DirectoryProperty functionality - */ -public final class TestDirectoryProperty { - private DirectoryProperty _property; - private byte[] _testblock; - - /** - * Test constructing DirectoryProperty - */ - @Test - public void testConstructor() throws IOException { - createBasicDirectoryProperty(); - verifyProperty(); - } - - /** - * Test pre-write functionality - */ - @Test - public void testPreWrite() throws IOException { - createBasicDirectoryProperty(); - _property.preWrite(); - - // shouldn't change anything at all - verifyProperty(); - verifyChildren(0); - - // now try adding 1 property - createBasicDirectoryProperty(); - _property.addChild(new LocalProperty(1)); - _property.preWrite(); - - // update children index - _testblock[ 0x4C ] = 1; - _testblock[ 0x4D ] = 0; - _testblock[ 0x4E ] = 0; - _testblock[ 0x4F ] = 0; - verifyProperty(); - verifyChildren(1); - - // now try adding 2 properties - createBasicDirectoryProperty(); - _property.addChild(new LocalProperty(1)); - _property.addChild(new LocalProperty(2)); - _property.preWrite(); - - // update children index - _testblock[ 0x4C ] = 2; - _testblock[ 0x4D ] = 0; - _testblock[ 0x4E ] = 0; - _testblock[ 0x4F ] = 0; - verifyProperty(); - verifyChildren(2); - - // beat on the children allocation code - for (int count = 1; count < 100; count++) - { - createBasicDirectoryProperty(); - for (int j = 1; j < (count + 1); j++) - { - _property.addChild(new LocalProperty(j)); - } - _property.preWrite(); - verifyChildren(count); - } - } - - private void verifyChildren(int count) { - Iterator iter = _property.getChildren(); - List children = new ArrayList(); - - while (iter.hasNext()) - { - children.add(iter.next()); - } - assertEquals(count, children.size()); - if (count != 0) - { - boolean[] found = new boolean[ count ]; - - found[ _property.getChildIndex() - 1 ] = true; - int total_found = 1; - - Arrays.fill(found, false); - iter = children.iterator(); - while (iter.hasNext()) - { - Property child = iter.next(); - Child next = child.getNextChild(); - - if (next != null) - { - int index = (( Property ) next).getIndex(); - - if (index != -1) - { - assertTrue("found index " + index + " twice", - !found[ index - 1 ]); - found[ index - 1 ] = true; - total_found++; - } - } - Child previous = child.getPreviousChild(); - - if (previous != null) - { - int index = (( Property ) previous).getIndex(); - - if (index != -1) - { - assertTrue("found index " + index + " twice", - !found[ index - 1 ]); - found[ index - 1 ] = true; - total_found++; - } - } - } - assertEquals(count, total_found); - } - } - - private void createBasicDirectoryProperty() { - String name = "MyDirectory"; - - _property = new DirectoryProperty(name); - _testblock = new byte[ 128 ]; - int index = 0; - - for (; index < 0x40; index++) - { - _testblock[ index ] = ( byte ) 0; - } - int limit = Math.min(31, name.length()); - - _testblock[ index++ ] = ( byte ) (2 * (limit + 1)); - _testblock[ index++ ] = ( byte ) 0; - _testblock[ index++ ] = ( byte ) 1; - _testblock[ index++ ] = ( byte ) 1; - for (; index < 0x50; index++) - { - _testblock[ index ] = ( byte ) 0xff; - } - for (; index < 0x80; index++) - { - _testblock[ index ] = ( byte ) 0; - } - byte[] name_bytes = name.getBytes(LocaleUtil.CHARSET_1252); - - for (index = 0; index < limit; index++) - { - _testblock[ index * 2 ] = name_bytes[ index ]; - } - } - - private void verifyProperty() throws IOException { - ByteArrayOutputStream stream = new ByteArrayOutputStream(512); - - _property.writeData(stream); - byte[] output = stream.toByteArray(); - - assertEquals(_testblock.length, output.length); - for (int j = 0; j < _testblock.length; j++) - { - assertEquals("mismatch at offset " + j, _testblock[ j ], - output[ j ]); - } - } - - @Test - public void testAddChild() throws IOException { - createBasicDirectoryProperty(); - _property.addChild(new LocalProperty(1)); - _property.addChild(new LocalProperty(2)); - try - { - _property.addChild(new LocalProperty(1)); - fail("should have caught IOException"); - } - catch (IOException ignored) - { - - // as expected - } - try - { - _property.addChild(new LocalProperty(2)); - fail("should have caught IOException"); - } - catch (IOException ignored) - { - - // as expected - } - _property.addChild(new LocalProperty(3)); - } - - @Test - public void testDeleteChild() throws IOException { - createBasicDirectoryProperty(); - Property p1 = new LocalProperty(1); - - _property.addChild(p1); - try - { - _property.addChild(new LocalProperty(1)); - fail("should have caught IOException"); - } - catch (IOException ignored) - { - - // as expected - } - assertTrue(_property.deleteChild(p1)); - assertTrue(!_property.deleteChild(p1)); - _property.addChild(new LocalProperty(1)); - } - - @Test - public void testChangeName() throws IOException { - createBasicDirectoryProperty(); - Property p1 = new LocalProperty(1); - String originalName = p1.getName(); - - _property.addChild(p1); - assertTrue(_property.changeName(p1, "foobar")); - assertEquals("foobar", p1.getName()); - assertTrue(!_property.changeName(p1, "foobar")); - assertEquals("foobar", p1.getName()); - Property p2 = new LocalProperty(1); - - _property.addChild(p2); - assertTrue(!_property.changeName(p1, originalName)); - assertTrue(_property.changeName(p2, "foo")); - assertTrue(_property.changeName(p1, originalName)); - } - - @Test - public void testReadingConstructor() { - String[] input = { - "42 00 6F 00 6F 00 74 00 20 00 45 00 6E 00 74 00 72 00 79 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "16 00 01 01 FF FF FF FF FF FF FF FF 02 00 00 00 20 08 02 00 00 00 00 00 C0 00 00 00 00 00 00 46", - "00 00 00 00 00 00 00 00 00 00 00 00 C0 5C E8 23 9E 6B C1 01 FE FF FF FF 00 00 00 00 00 00 00 00", - }; - verifyReadingProperty(0, RawDataUtil.decode(input), 0, "Boot Entry"); - } - - private static void verifyReadingProperty(int index, byte[] input, int offset, String name) { - DirectoryProperty property = new DirectoryProperty(index, input, offset); - ByteArrayOutputStream stream = new ByteArrayOutputStream(128); - byte[] expected = new byte[128]; - - System.arraycopy(input, offset, expected, 0, 128); - try { - property.writeData(stream); - } catch (IOException e) { - throw new RuntimeException(e); - } - byte[] output = stream.toByteArray(); - - assertEquals(128, output.length); - for (int j = 0; j < 128; j++) { - assertEquals("mismatch at offset " + j, expected[j], output[j]); - } - assertEquals(index, property.getIndex()); - assertEquals(name, property.getName()); - assertTrue(!property.getChildren().hasNext()); - } -} diff --git a/src/testcases/org/apache/poi/poifs/property/TestDocumentProperty.java b/src/testcases/org/apache/poi/poifs/property/TestDocumentProperty.java deleted file mode 100644 index bd0b30edd..000000000 --- a/src/testcases/org/apache/poi/poifs/property/TestDocumentProperty.java +++ /dev/null @@ -1,159 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.property; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -import org.apache.poi.poifs.storage.RawDataUtil; -import org.apache.poi.util.LocaleUtil; - -import junit.framework.TestCase; - -/** - * Class to test DocumentProperty functionality - * - * @author Marc Johnson - */ -public final class TestDocumentProperty extends TestCase { - - public void testConstructor() throws IOException { - // test with short name, small file - verifyProperty("foo", 1234); - - // test with just long enough name, small file - verifyProperty("A.really.long.long.long.name123", 2345); - - // test with longer name, just small enough file - verifyProperty("A.really.long.long.long.name1234", 4095); - - // test with just long enough file - verifyProperty("A.really.long.long.long.name123", 4096); - } - - public void testReadingConstructor() throws IOException { - String[] hexData = { - "52 00 6F 00 6F 00 74 00 20 00 45 00 6E 00 74 00 72 00 79 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "16 00 05 01 FF FF FF FF FF FF FF FF 02 00 00 00 20 08 02 00 00 00 00 00 C0 00 00 00 00 00 00 46", - "00 00 00 00 00 00 00 00 00 00 00 00 C0 5C E8 23 9E 6B C1 01 FE FF FF FF 00 00 00 00 00 00 00 00", - "57 00 6F 00 72 00 6B 00 62 00 6F 00 6F 00 6B 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "12 00 02 01 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 10 00 00 00 00 00 00", - "05 00 53 00 75 00 6D 00 6D 00 61 00 72 00 79 00 49 00 6E 00 66 00 6F 00 72 00 6D 00 61 00 74 00", - "69 00 6F 00 6E 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "28 00 02 01 01 00 00 00 03 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 08 00 00 00 00 10 00 00 00 00 00 00", - "05 00 44 00 6F 00 63 00 75 00 6D 00 65 00 6E 00 74 00 53 00 75 00 6D 00 6D 00 61 00 72 00 79 00", - "49 00 6E 00 66 00 6F 00 72 00 6D 00 61 00 74 00 69 00 6F 00 6E 00 00 00 00 00 00 00 00 00 00 00", - "38 00 02 01 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 10 00 00 00 00 10 00 00 00 00 00 00", - }; - byte[] input = RawDataUtil.decode(hexData); - - verifyReadingProperty(1, input, 128, "Workbook"); - verifyReadingProperty(2, input, 256, "\005SummaryInformation"); - verifyReadingProperty(3, input, 384, "\005DocumentSummaryInformation"); - } - - private void verifyReadingProperty(int index, byte[] input, int offset, String name) - throws IOException { - DocumentProperty property = new DocumentProperty(index, input, - offset); - ByteArrayOutputStream stream = new ByteArrayOutputStream(128); - byte[] expected = new byte[ 128 ]; - - System.arraycopy(input, offset, expected, 0, 128); - property.writeData(stream); - byte[] output = stream.toByteArray(); - - assertEquals(128, output.length); - for (int j = 0; j < 128; j++) - { - assertEquals("mismatch at offset " + j, expected[ j ], - output[ j ]); - } - assertEquals(index, property.getIndex()); - assertEquals(name, property.getName()); - } - - private void verifyProperty(String name, int size) throws IOException { - DocumentProperty property = new DocumentProperty(name, size); - - if (size >= 4096) - { - assertTrue(!property.shouldUseSmallBlocks()); - } - else - { - assertTrue(property.shouldUseSmallBlocks()); - } - byte[] testblock = new byte[ 128 ]; - int index = 0; - - for (; index < 0x40; index++) - { - testblock[ index ] = ( byte ) 0; - } - int limit = Math.min(31, name.length()); - - testblock[ index++ ] = ( byte ) (2 * (limit + 1)); - testblock[ index++ ] = ( byte ) 0; - testblock[ index++ ] = ( byte ) 2; - testblock[ index++ ] = ( byte ) 1; - for (; index < 0x50; index++) - { - testblock[ index ] = ( byte ) 0xFF; - } - for (; index < 0x78; index++) - { - testblock[ index ] = ( byte ) 0; - } - int sz = size; - - testblock[ index++ ] = ( byte ) sz; - sz /= 256; - testblock[ index++ ] = ( byte ) sz; - sz /= 256; - testblock[ index++ ] = ( byte ) sz; - sz /= 256; - testblock[ index++ ] = ( byte ) sz; - for (; index < 0x80; index++) - { - testblock[ index ] = ( byte ) 0x0; - } - byte[] name_bytes = name.getBytes(LocaleUtil.CHARSET_1252); - - for (index = 0; index < limit; index++) - { - testblock[ index * 2 ] = name_bytes[ index ]; - } - ByteArrayOutputStream stream = new ByteArrayOutputStream(512); - - property.writeData(stream); - byte[] output = stream.toByteArray(); - - assertEquals(testblock.length, output.length); - for (int j = 0; j < testblock.length; j++) - { - assertEquals("mismatch at offset " + j, testblock[ j ], - output[ j ]); - } - } -} diff --git a/src/testcases/org/apache/poi/poifs/property/TestPropertyFactory.java b/src/testcases/org/apache/poi/poifs/property/TestPropertyFactory.java deleted file mode 100644 index 362871298..000000000 --- a/src/testcases/org/apache/poi/poifs/property/TestPropertyFactory.java +++ /dev/null @@ -1,398 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.property; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.util.List; - -import org.apache.poi.poifs.storage.RawDataBlock; -import org.apache.poi.poifs.storage.RawDataUtil; -import org.junit.Test; - -/** - * Class to test PropertyFactory functionality - */ -public final class TestPropertyFactory { - - @Test - public void testConvertToProperties() throws IOException { - - // real data from a real file! - String[] hexData = { - "52 00 6F 00 6F 00 74 00 20 00 45 00 6E 00 74 00 72 00 79 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "16 00 05 00 FF FF FF FF FF FF FF FF 0D 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 C0 47 A4 DE EC 65 C1 01 03 00 00 00 40 0C 00 00 00 00 00 00", - "44 00 6F 00 63 00 75 00 6D 00 65 00 6E 00 74 00 20 00 44 00 65 00 74 00 61 00 69 00 6C 00 73 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "22 00 00 01 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 A0 7F 29 08 59 56 C1 01 C0 20 31 08 59 56 C1 01 00 00 00 00 00 00 00 00 00 00 00 00", - "43 00 72 00 65 00 61 00 74 00 69 00 6F 00 6E 00 20 00 4E 00 61 00 6D 00 65 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "1C 00 00 01 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 FE FF FF FF 2C 00 00 00 00 00 00 00", - "43 00 72 00 65 00 61 00 74 00 69 00 6F 00 6E 00 20 00 44 00 61 00 74 00 65 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "1C 00 00 01 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 FE FF FF FF 0A 00 00 00 00 00 00 00", - "4C 00 61 00 73 00 74 00 20 00 53 00 61 00 76 00 65 00 64 00 20 00 44 00 61 00 74 00 65 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "20 00 00 01 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 FE FF FF FF 0A 00 00 00 00 00 00 00", - "44 00 61 00 74 00 65 00 20 00 46 00 69 00 6C 00 65 00 64 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "16 00 00 01 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 FE FF FF FF 0A 00 00 00 00 00 00 00", - "44 00 6F 00 63 00 75 00 6D 00 65 00 6E 00 74 00 20 00 56 00 65 00 72 00 73 00 69 00 6F 00 6E 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "22 00 00 01 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 FE FF FF FF 04 00 00 00 00 00 00 00", - "42 00 61 00 63 00 63 00 68 00 75 00 73 00 20 00 44 00 65 00 61 00 6C 00 20 00 4E 00 75 00 6D 00", - "62 00 65 00 72 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "28 00 00 01 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 FE FF FF FF 04 00 00 00 00 00 00 00", - "44 00 6F 00 63 00 75 00 6D 00 65 00 6E 00 74 00 20 00 4C 00 6F 00 63 00 6B 00 65 00 64 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "20 00 00 01 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 FE FF FF FF 04 00 00 00 00 00 00 00", - "44 00 6F 00 63 00 75 00 6D 00 65 00 6E 00 74 00 20 00 44 00 65 00 61 00 6C 00 20 00 54 00 79 00", - "70 00 65 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "26 00 00 01 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 FE FF FF FF 06 00 00 00 00 00 00 00", - "44 00 6F 00 63 00 75 00 6D 00 65 00 6E 00 74 00 20 00 41 00 75 00 64 00 69 00 74 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "1E 00 00 01 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 C0 20 31 08 59 56 C1 01 80 48 3A 08 59 56 C1 01 00 00 00 00 00 00 00 00 00 00 00 00", - "55 00 73 00 65 00 72 00 20 00 41 00 75 00 64 00 69 00 74 00 20 00 54 00 72 00 61 00 69 00 6C 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "22 00 00 01 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 FE FF FF FF 42 00 00 00 00 00 00 00", - "43 00 6F 00 6E 00 74 00 72 00 61 00 63 00 74 00 20 00 47 00 65 00 6E 00 65 00 72 00 61 00 74 00", - "69 00 6F 00 6E 00 20 00 49 00 6E 00 66 00 6F 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "32 00 00 01 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 80 48 3A 08 59 56 C1 01 80 48 3A 08 59 56 C1 01 00 00 00 00 00 00 00 00 00 00 00 00", - "44 00 65 00 61 00 6C 00 20 00 49 00 6E 00 66 00 6F 00 72 00 6D 00 61 00 74 00 69 00 6F 00 6E 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "22 00 01 01 FF FF FF FF FF FF FF FF 19 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 80 48 3A 08 59 56 C1 01 80 B2 52 08 59 56 C1 01 00 00 00 00 00 00 00 00 00 00 00 00", - "44 00 65 00 61 00 6C 00 20 00 44 00 65 00 73 00 63 00 72 00 69 00 70 00 74 00 69 00 6F 00 6E 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "22 00 02 00 16 00 00 00 26 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0A 00 00 00 09 00 00 00 00 00 00 00", - "53 00 61 00 6C 00 65 00 73 00 20 00 41 00 72 00 65 00 61 00 20 00 43 00 6F 00 64 00 65 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "20 00 02 01 12 00 00 00 2A 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0B 00 00 00 04 00 00 00 00 00 00 00", - "44 00 65 00 61 00 6C 00 20 00 43 00 75 00 72 00 72 00 65 00 6E 00 63 00 79 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "1C 00 02 01 1B 00 00 00 20 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0C 00 00 00 07 00 00 00 00 00 00 00", - "4F 00 75 00 74 00 62 00 6F 00 75 00 6E 00 64 00 20 00 54 00 72 00 61 00 76 00 65 00 6C 00 20 00", - "44 00 61 00 74 00 65 00 73 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "2C 00 02 01 25 00 00 00 27 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0D 00 00 00 21 00 00 00 00 00 00 00", - "4D 00 61 00 78 00 69 00 6D 00 75 00 6D 00 20 00 53 00 74 00 61 00 79 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "1A 00 02 01 14 00 00 00 10 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0E 00 00 00 05 00 00 00 00 00 00 00", - "4D 00 61 00 78 00 69 00 6D 00 75 00 6D 00 20 00 53 00 74 00 61 00 79 00 20 00 50 00 65 00 72 00", - "69 00 6F 00 64 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "28 00 02 00 18 00 00 00 23 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0F 00 00 00 04 00 00 00 00 00 00 00", - "44 00 65 00 61 00 6C 00 20 00 54 00 79 00 70 00 65 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "14 00 02 00 15 00 00 00 28 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 10 00 00 00 04 00 00 00 00 00 00 00", - "53 00 75 00 62 00 20 00 44 00 65 00 61 00 6C 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "12 00 02 01 2E 00 00 00 1F 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 11 00 00 00 04 00 00 00 00 00 00 00", - "43 00 6F 00 6D 00 6D 00 69 00 73 00 73 00 69 00 6F 00 6E 00 20 00 56 00 61 00 6C 00 75 00 65 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "22 00 02 01 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 12 00 00 00 04 00 00 00 00 00 00 00", - "46 00 61 00 72 00 65 00 20 00 54 00 79 00 70 00 65 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "14 00 02 00 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 13 00 00 00 04 00 00 00 00 00 00 00", - "46 00 55 00 44 00 20 00 47 00 72 00 69 00 64 00 20 00 44 00 69 00 6D 00 65 00 6E 00 73 00 69 00", - "6F 00 6E 00 73 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "28 00 02 01 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 14 00 00 00 04 00 00 00 00 00 00 00", - "46 00 55 00 44 00 20 00 47 00 72 00 69 00 64 00 20 00 49 00 6E 00 66 00 6F 00 72 00 6D 00 61 00", - "74 00 69 00 6F 00 6E 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "2A 00 02 01 0F 00 00 00 1A 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 FE FF FF FF 00 00 00 00 00 00 00 00", - "44 00 6F 00 75 00 62 00 6C 00 65 00 20 00 44 00 65 00 61 00 6C 00 69 00 6E 00 67 00 20 00 49 00", - "6E 00 64 00 69 00 63 00 61 00 74 00 6F 00 72 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "32 00 02 01 11 00 00 00 21 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 15 00 00 00 04 00 00 00 00 00 00 00", - "42 00 75 00 73 00 69 00 6E 00 65 00 73 00 73 00 20 00 54 00 79 00 70 00 65 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "1C 00 02 00 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 16 00 00 00 04 00 00 00 00 00 00 00", - "55 00 6D 00 62 00 72 00 65 00 6C 00 6C 00 61 00 20 00 4C 00 69 00 6E 00 6B 00 73 00 20 00 61 00", - "6E 00 64 00 20 00 50 00 61 00 73 00 73 00 65 00 6E 00 67 00 65 00 72 00 73 00 00 00 00 00 00 00", - "3C 00 02 00 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 FE FF FF FF 00 00 00 00 00 00 00 00", - "41 00 67 00 65 00 6E 00 74 00 73 00 20 00 4E 00 61 00 6D 00 65 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "18 00 02 00 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 17 00 00 00 04 00 00 00 00 00 00 00", - "4E 00 75 00 6D 00 62 00 65 00 72 00 20 00 6F 00 66 00 20 00 50 00 61 00 73 00 73 00 65 00 6E 00", - "67 00 65 00 72 00 73 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "2A 00 02 00 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 18 00 00 00 04 00 00 00 00 00 00 00", - "41 00 4C 00 43 00 20 00 43 00 6F 00 64 00 65 00 73 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "14 00 02 00 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 FE FF FF FF 00 00 00 00 00 00 00 00", - "43 00 6F 00 6E 00 73 00 6F 00 72 00 74 00 69 00 61 00 20 00 43 00 6F 00 64 00 65 00 73 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "20 00 02 00 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 FE FF FF FF 00 00 00 00 00 00 00 00", - "43 00 68 00 69 00 6C 00 64 00 20 00 50 00 65 00 72 00 63 00 65 00 6E 00 74 00 61 00 67 00 65 00", - "20 00 50 00 65 00 72 00 6D 00 69 00 74 00 74 00 65 00 64 00 00 00 00 00 00 00 00 00 00 00 00 00", - "36 00 02 01 24 00 00 00 2C 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 19 00 00 00 04 00 00 00 00 00 00 00", - "50 00 65 00 72 00 63 00 65 00 6E 00 74 00 61 00 67 00 65 00 20 00 6F 00 66 00 20 00 59 00 69 00", - "65 00 6C 00 64 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "28 00 02 00 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 1A 00 00 00 04 00 00 00 00 00 00 00", - "4E 00 65 00 74 00 20 00 52 00 65 00 6D 00 69 00 74 00 20 00 50 00 65 00 72 00 6D 00 69 00 74 00", - "74 00 65 00 64 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "28 00 02 01 29 00 00 00 22 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 1B 00 00 00 04 00 00 00 00 00 00 00", - "49 00 6E 00 66 00 61 00 6E 00 74 00 20 00 44 00 69 00 73 00 63 00 6F 00 75 00 6E 00 74 00 20 00", - "50 00 65 00 72 00 6D 00 69 00 74 00 74 00 65 00 64 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "34 00 02 01 2D 00 00 00 FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 1C 00 00 00 04 00 00 00 00 00 00 00", - "49 00 6E 00 66 00 61 00 6E 00 74 00 20 00 44 00 69 00 73 00 63 00 6F 00 75 00 6E 00 74 00 20 00", - "56 00 61 00 6C 00 75 00 65 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "2C 00 02 01 1E 00 00 00 2F 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 1D 00 00 00 04 00 00 00 00 00 00 00", - "54 00 52 00 56 00 41 00 20 00 49 00 6E 00 66 00 6F 00 72 00 6D 00 61 00 74 00 69 00 6F 00 6E 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "22 00 02 01 30 00 00 00 FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 1E 00 00 00 04 00 00 00 00 00 00 00", - "42 00 75 00 73 00 69 00 6E 00 65 00 73 00 73 00 20 00 4A 00 75 00 73 00 74 00 69 00 66 00 69 00", - "63 00 61 00 74 00 69 00 6F 00 6E 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "2E 00 02 01 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 1F 00 00 00 04 00 00 00 00 00 00 00", - "53 00 75 00 72 00 63 00 68 00 61 00 72 00 67 00 65 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "14 00 02 01 17 00 00 00 1D 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 20 00 00 00 04 00 00 00 00 00 00 00", - "4E 00 61 00 74 00 75 00 72 00 65 00 20 00 6F 00 66 00 20 00 56 00 61 00 72 00 69 00 61 00 74 00", - "69 00 6F 00 6E 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "28 00 02 00 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 21 00 00 00 50 00 00 00 00 00 00 00", - "4F 00 74 00 68 00 65 00 72 00 20 00 52 00 65 00 66 00 75 00 6E 00 64 00 20 00 54 00 65 00 78 00", - "74 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "24 00 02 01 0E 00 00 00 13 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 23 00 00 00 04 00 00 00 00 00 00 00", - "43 00 61 00 6E 00 63 00 65 00 6C 00 6C 00 61 00 74 00 69 00 6F 00 6E 00 20 00 46 00 65 00 65 00", - "20 00 50 00 65 00 72 00 63 00 65 00 6E 00 74 00 61 00 67 00 65 00 00 00 00 00 00 00 00 00 00 00", - "38 00 02 00 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 24 00 00 00 04 00 00 00 00 00 00 00", - "43 00 61 00 6E 00 63 00 65 00 6C 00 6C 00 61 00 74 00 69 00 6F 00 6E 00 20 00 46 00 65 00 65 00", - "20 00 46 00 69 00 78 00 65 00 64 00 20 00 56 00 61 00 6C 00 75 00 65 00 00 00 00 00 00 00 00 00", - "3A 00 02 01 2B 00 00 00 1C 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 25 00 00 00 04 00 00 00 00 00 00 00", - "43 00 61 00 6E 00 63 00 65 00 6C 00 6C 00 61 00 74 00 69 00 6F 00 6E 00 20 00 46 00 65 00 65 00", - "20 00 43 00 75 00 72 00 72 00 65 00 6E 00 63 00 79 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "34 00 02 00 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 26 00 00 00 07 00 00 00 00 00 00 00", - "52 00 65 00 6D 00 61 00 72 00 6B 00 73 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "10 00 02 00 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 FE FF FF FF 00 00 00 00 00 00 00 00", - "4F 00 74 00 68 00 65 00 72 00 20 00 43 00 61 00 72 00 72 00 69 00 65 00 72 00 20 00 53 00 65 00", - "63 00 74 00 6F 00 72 00 73 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "2C 00 02 00 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 27 00 00 00 04 00 00 00 00 00 00 00", - "50 00 72 00 6F 00 72 00 61 00 74 00 65 00 20 00 43 00 6F 00 6D 00 6D 00 65 00 6E 00 74 00 73 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "22 00 02 00 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 FE FF FF FF 00 00 00 00 00 00 00 00", - "4E 00 65 00 67 00 6F 00 74 00 69 00 61 00 74 00 69 00 6F 00 6E 00 20 00 49 00 6E 00 66 00 6F 00", - "72 00 6D 00 61 00 74 00 69 00 6F 00 6E 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "30 00 00 01 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 80 B2 52 08 59 56 C1 01 80 B2 52 08 59 56 C1 01 00 00 00 00 00 00 00 00 00 00 00 00", - "52 00 65 00 73 00 74 00 72 00 69 00 63 00 74 00 65 00 64 00 20 00 43 00 61 00 72 00 72 00 69 00", - "65 00 72 00 73 00 20 00 26 00 20 00 53 00 74 00 6E 00 73 00 00 00 00 00 00 00 00 00 00 00 00 00", - "36 00 00 01 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 FE FF FF FF 04 00 00 00 00 00 00 00", - "41 00 64 00 64 00 69 00 74 00 69 00 6F 00 6E 00 61 00 6C 00 20 00 43 00 6F 00 6D 00 6D 00 65 00", - "6E 00 74 00 73 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "28 00 00 01 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 FE FF FF FF 04 00 00 00 00 00 00 00", - "52 00 65 00 76 00 65 00 6E 00 75 00 65 00 20 00 4D 00 61 00 6E 00 61 00 67 00 65 00 6D 00 65 00", - "6E 00 74 00 20 00 43 00 6F 00 6D 00 6D 00 65 00 6E 00 74 00 73 00 00 00 00 00 00 00 00 00 00 00", - "38 00 00 01 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 FE FF FF FF 04 00 00 00 00 00 00 00", - "52 00 65 00 76 00 65 00 6E 00 75 00 65 00 20 00 4D 00 61 00 6E 00 61 00 67 00 65 00 6D 00 65 00", - "6E 00 74 00 20 00 52 00 65 00 66 00 65 00 72 00 65 00 6E 00 63 00 65 00 00 00 00 00 00 00 00 00", - "3A 00 00 01 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 FE FF FF FF 04 00 00 00 00 00 00 00", - "4D 00 69 00 6E 00 69 00 6D 00 75 00 6D 00 20 00 53 00 74 00 61 00 79 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "1A 00 00 01 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 FE FF FF FF 04 00 00 00 00 00 00 00", - "43 00 72 00 65 00 61 00 74 00 65 00 64 00 20 00 42 00 79 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "16 00 00 01 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 FE FF FF FF 1B 00 00 00 00 00 00 00", - "4F 00 6E 00 20 00 42 00 65 00 68 00 61 00 6C 00 66 00 20 00 4F 00 66 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "1A 00 00 01 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 FE FF FF FF 04 00 00 00 00 00 00 00", - "44 00 65 00 61 00 6C 00 20 00 50 00 61 00 67 00 65 00 20 00 41 00 75 00 74 00 68 00 20 00 4C 00", - "6F 00 63 00 6B 00 73 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "2A 00 00 01 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 FE FF FF FF 10 00 00 00 00 00 00 00", - "47 00 72 00 6F 00 75 00 70 00 20 00 41 00 75 00 74 00 68 00 6F 00 72 00 69 00 73 00 61 00 74 00", - "69 00 6F 00 6E 00 20 00 49 00 6E 00 66 00 6F 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "32 00 00 01 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 80 B2 52 08 59 56 C1 01 40 DA 5B 08 59 56 C1 01 00 00 00 00 00 00 00 00 00 00 00 00", - "4C 00 61 00 73 00 74 00 20 00 49 00 73 00 73 00 75 00 65 00 64 00 20 00 47 00 72 00 6F 00 75 00", - "70 00 20 00 4E 00 75 00 6D 00 62 00 65 00 72 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "32 00 00 01 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 FE FF FF FF 06 00 00 00 00 00 00 00", - "47 00 72 00 6F 00 75 00 70 00 20 00 4E 00 75 00 6D 00 62 00 65 00 72 00 73 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "1C 00 00 01 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 FE FF FF FF 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - }; - - byte[] testdata = RawDataUtil.decode(hexData); - ByteArrayInputStream stream = new ByteArrayInputStream(testdata); - RawDataBlock[] raw_data = new RawDataBlock[testdata.length / 512]; - - for (int j = 0; j < raw_data.length; j++) { - raw_data[j] = new RawDataBlock(stream); - } - List properties = PropertyFactory.convertToProperties(raw_data); - - assertEquals(64, properties.size()); - String[] names = { - "Root Entry", null, null, null, null, null, null, null, null, - null, null, null, null, "Deal Information", "Deal Description", - "Sales Area Code", "Deal Currency", "Outbound Travel Dates", - "Maximum Stay", "Maximum Stay Period", "Deal Type", "Sub Deal", - "Commission Value", "Fare Type", "FUD Grid Dimensions", - "FUD Grid Information", "Double Dealing Indicator", - "Business Type", "Umbrella Links and Passengers", "Agents Name", - "Number of Passengers", "ALC Codes", "Consortia Codes", - "Child Percentage Permitted", "Percentage of Yield", - "Net Remit Permitted", "Infant Discount Permitted", - "Infant Discount Value", "TRVA Information", - "Business Justification", "Surcharge", "Nature of Variation", - "Other Refund Text", "Cancellation Fee Percentage", - "Cancellation Fee Fixed Value", "Cancellation Fee Currency", - "Remarks", "Other Carrier Sectors", "Prorate Comments", null, - null, null, null, null, null, null, null, null, null, null, null, - null, null, null - }; - assertEquals(64, names.length); - - boolean[] isRoot = { - true, false, false, false, false, false, false, false, false, - false, false, false, false, false, false, false, false, false, - false, false, false, false, false, false, false, false, false, - false, false, false, false, false, false, false, false, false, - false, false, false, false, false, false, false, false, false, - false, false, false, false, false, false, false, false, false, - false, false, false, false, false, false, false, false, false, - false - }; - assertEquals(64, isRoot.length); - - boolean[] isDocument = { - false, false, false, false, false, false, false, false, false, - false, false, false, false, false, true, true, true, true, true, - true, true, true, true, true, true, true, true, true, true, true, - true, true, true, true, true, true, true, true, true, true, true, - true, true, true, true, true, true, true, true, false, false, - false, false, false, false, false, false, false, false, false, - false, false, false, false - }; - assertEquals(64, isDocument.length); - - boolean[] isDirectory = { - false, false, false, false, false, false, false, false, false, - false, false, false, false, true, false, false, false, false, - false, false, false, false, false, false, false, false, false, - false, false, false, false, false, false, false, false, false, - false, false, false, false, false, false, false, false, false, - false, false, false, false, false, false, false, false, false, - false, false, false, false, false, false, false, false, false, - false - }; - assertEquals(64, isDirectory.length); - - boolean[] isNull = { - false, true, true, true, true, true, true, true, true, true, true, - true, true, false, false, false, false, false, false, false, - false, false, false, false, false, false, false, false, false, - false, false, false, false, false, false, false, false, false, - false, false, false, false, false, false, false, false, false, - false, false, true, true, true, true, true, true, true, true, - true, true, true, true, true, true, true - }; - assertEquals(64, isNull.length); - - for (int j = 0; j < 64; j++) { - if (isNull[j]) { - assertNull("Checking property " + j, properties.get(j)); - } else { - assertNotNull("Checking property " + j, properties.get(j)); - if (isRoot[j]) { - assertTrue("Checking property " + j, properties.get(j) instanceof RootProperty); - } - if (isDirectory[j]) { - assertTrue("Checking property " + j, - properties.get(j) instanceof DirectoryProperty); - } - if (isDocument[j]) { - assertTrue("Checking property " + j, - properties.get(j) instanceof DocumentProperty); - } - assertEquals("Checking property " + j, names[j], properties.get(j).getName()); - } - } - } -} diff --git a/src/testcases/org/apache/poi/poifs/property/TestPropertyTable.java b/src/testcases/org/apache/poi/poifs/property/TestPropertyTable.java deleted file mode 100644 index 3950ce07e..000000000 --- a/src/testcases/org/apache/poi/poifs/property/TestPropertyTable.java +++ /dev/null @@ -1,468 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.property; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -import org.apache.poi.poifs.common.POIFSConstants; -import org.apache.poi.poifs.storage.BlockAllocationTableReader; -import org.apache.poi.poifs.storage.HeaderBlock; -import org.apache.poi.poifs.storage.RawDataBlockList; -import org.apache.poi.poifs.storage.RawDataUtil; -import org.junit.Test; - -/** - * Class to test PropertyTable functionality - */ -public final class TestPropertyTable { - - private static void confirmBlockEncoding(String[] expectedDataHexDumpLines, PropertyTable table) { - byte[] expectedData = RawDataUtil.decode(expectedDataHexDumpLines); - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - try { - table.writeBlocks(stream); - } catch (IOException e) { - throw new RuntimeException(e); - } - byte[] output = stream.toByteArray(); - - assertEquals("length check #1", expectedData.length, output.length); - for (int j = 0; j < expectedData.length; j++) { - assertEquals("content check #1: mismatch at offset " + j, expectedData[j], output[j]); - } - } - - /** - * Test PropertyTable - *

    - * Running individual tests of the PropertyTable methods, which is the - * traditional way to write unit tests (at least for me), seems somewhat - * useless in this case. Of greater relevance: if one follows the normal - * steps of creating a PropertyTable, and then checking the output, does it - * make sense? In other words, more of an integration test. - *

    - * So, the test consists of creating a PropertyTable instance, adding three - * DocumentProperty instances to it, and then getting the output (including - * the preWrite phase first), and comparing it against a real property table - * extracted from a file known to be acceptable to Excel. - */ - @Test - public void testWriterPropertyTable() throws IOException { - - // create the PropertyTable - HeaderBlock headerBlock = new HeaderBlock(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS); - PropertyTable table = new PropertyTable(headerBlock); - - // create three DocumentProperty instances and add them to the - // PropertyTable - DocumentProperty workbook = new DocumentProperty("Workbook", 0x00046777); - - workbook.setStartBlock(0); - DocumentProperty summary1 = new DocumentProperty("\005SummaryInformation", 0x00001000); - - summary1.setStartBlock(0x00000234); - DocumentProperty summary2 = new DocumentProperty("\005DocumentSummaryInformation", - 0x00001000); - - summary2.setStartBlock(0x0000023C); - table.addProperty(workbook); - RootProperty root = table.getRoot(); - - root.addChild(workbook); - table.addProperty(summary1); - root = table.getRoot(); - root.addChild(summary1); - table.addProperty(summary2); - root = table.getRoot(); - root.addChild(summary2); - table.preWrite(); - - String[] testblock = { - "52 00 6F 00 6F 00 74 00 20 00 45 00 6E 00 74 00 72 00 79 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "16 00 05 01 FF FF FF FF FF FF FF FF 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 FE FF FF FF 00 00 00 00 00 00 00 00", - "57 00 6F 00 72 00 6B 00 62 00 6F 00 6F 00 6B 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "12 00 02 01 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 77 67 04 00 00 00 00 00", - "05 00 53 00 75 00 6D 00 6D 00 61 00 72 00 79 00 49 00 6E 00 66 00 6F 00 72 00 6D 00 61 00 74 00", - "69 00 6F 00 6E 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "28 00 02 01 01 00 00 00 03 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 34 02 00 00 00 10 00 00 00 00 00 00", - "05 00 44 00 6F 00 63 00 75 00 6D 00 65 00 6E 00 74 00 53 00 75 00 6D 00 6D 00 61 00 72 00 79 00", - "49 00 6E 00 66 00 6F 00 72 00 6D 00 61 00 74 00 69 00 6F 00 6E 00 00 00 00 00 00 00 00 00 00 00", - "38 00 02 01 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3C 02 00 00 00 10 00 00 00 00 00 00", - }; - confirmBlockEncoding(testblock, table); - - table.removeProperty(summary1); - root = table.getRoot(); - root.deleteChild(summary1); - table.preWrite(); - - String[] testblock2 = { - "52 00 6F 00 6F 00 74 00 20 00 45 00 6E 00 74 00 72 00 79 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "16 00 05 01 FF FF FF FF FF FF FF FF 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 FE FF FF FF 00 00 00 00 00 00 00 00", - "57 00 6F 00 72 00 6B 00 62 00 6F 00 6F 00 6B 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "12 00 02 01 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 77 67 04 00 00 00 00 00", - "05 00 44 00 6F 00 63 00 75 00 6D 00 65 00 6E 00 74 00 53 00 75 00 6D 00 6D 00 61 00 72 00 79 00", - "49 00 6E 00 66 00 6F 00 72 00 6D 00 61 00 74 00 69 00 6F 00 6E 00 00 00 00 00 00 00 00 00 00 00", - "38 00 02 01 01 00 00 00 FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3C 02 00 00 00 10 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "02 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - }; - confirmBlockEncoding(testblock2, table); - - table.addProperty(summary1); - root = table.getRoot(); - root.addChild(summary1); - table.preWrite(); - - String[] testblock3 = { - "52 00 6F 00 6F 00 74 00 20 00 45 00 6E 00 74 00 72 00 79 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "16 00 05 01 FF FF FF FF FF FF FF FF 03 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 FE FF FF FF 00 00 00 00 00 00 00 00", - "57 00 6F 00 72 00 6B 00 62 00 6F 00 6F 00 6B 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "12 00 02 01 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 77 67 04 00 00 00 00 00", - "05 00 44 00 6F 00 63 00 75 00 6D 00 65 00 6E 00 74 00 53 00 75 00 6D 00 6D 00 61 00 72 00 79 00", - "49 00 6E 00 66 00 6F 00 72 00 6D 00 61 00 74 00 69 00 6F 00 6E 00 00 00 00 00 00 00 00 00 00 00", - "38 00 02 01 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3C 02 00 00 00 10 00 00 00 00 00 00", - "05 00 53 00 75 00 6D 00 6D 00 61 00 72 00 79 00 49 00 6E 00 66 00 6F 00 72 00 6D 00 61 00 74 00", - "69 00 6F 00 6E 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "28 00 02 01 01 00 00 00 02 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 34 02 00 00 00 10 00 00 00 00 00 00", - }; - confirmBlockEncoding(testblock3, table); - } - - public void testReadingConstructor() throws IOException { - - // first, we need the raw data blocks - String[] raw_data_array = { - "52 00 6F 00 6F 00 74 00 20 00 45 00 6E 00 74 00 72 00 79 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "16 00 05 01 FF FF FF FF FF FF FF FF 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0A 00 00 00 80 07 00 00 00 00 00 00", - "44 00 65 00 61 00 6C 00 20 00 49 00 6E 00 66 00 6F 00 72 00 6D 00 61 00 74 00 69 00 6F 00 6E 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "22 00 01 01 FF FF FF FF FF FF FF FF 15 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "46 00 55 00 44 00 20 00 47 00 72 00 69 00 64 00 20 00 49 00 6E 00 66 00 6F 00 72 00 6D 00 61 00", - "74 00 69 00 6F 00 6E 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "2A 00 02 01 FF FF FF FF 0E 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "44 00 6F 00 75 00 62 00 6C 00 65 00 20 00 44 00 65 00 61 00 6C 00 69 00 6E 00 67 00 20 00 49 00", - "6E 00 64 00 69 00 63 00 61 00 74 00 6F 00 72 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "32 00 02 01 FF FF FF FF 09 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00", - "43 00 68 00 69 00 6C 00 64 00 20 00 50 00 65 00 72 00 63 00 65 00 6E 00 74 00 61 00 67 00 65 00", - "20 00 50 00 65 00 72 00 6D 00 69 00 74 00 74 00 65 00 64 00 00 00 00 00 00 00 00 00 00 00 00 00", - "36 00 02 01 FF FF FF FF 07 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 04 00 00 00 00 00 00 00", - "43 00 61 00 6E 00 63 00 65 00 6C 00 6C 00 61 00 74 00 69 00 6F 00 6E 00 20 00 46 00 65 00 65 00", - "20 00 46 00 69 00 78 00 65 00 64 00 20 00 56 00 61 00 6C 00 75 00 65 00 00 00 00 00 00 00 00 00", - "3A 00 02 01 FF FF FF FF 06 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 04 00 00 00 00 00 00 00", - "55 00 6D 00 62 00 72 00 65 00 6C 00 6C 00 61 00 20 00 4C 00 69 00 6E 00 6B 00 73 00 20 00 61 00", - "6E 00 64 00 20 00 50 00 61 00 73 00 73 00 65 00 6E 00 67 00 65 00 72 00 73 00 00 00 00 00 00 00", - "3C 00 02 01 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "43 00 61 00 6E 00 63 00 65 00 6C 00 6C 00 61 00 74 00 69 00 6F 00 6E 00 20 00 46 00 65 00 65 00", - "20 00 50 00 65 00 72 00 63 00 65 00 6E 00 74 00 61 00 67 00 65 00 00 00 00 00 00 00 00 00 00 00", - "38 00 02 01 FF FF FF FF 05 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 03 00 00 00 04 00 00 00 00 00 00 00", - "49 00 6E 00 66 00 61 00 6E 00 74 00 20 00 44 00 69 00 73 00 63 00 6F 00 75 00 6E 00 74 00 20 00", - "50 00 65 00 72 00 6D 00 69 00 74 00 74 00 65 00 64 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "34 00 02 01 FF FF FF FF 04 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 04 00 00 00 00 00 00 00", - "43 00 61 00 6E 00 63 00 65 00 6C 00 6C 00 61 00 74 00 69 00 6F 00 6E 00 20 00 46 00 65 00 65 00", - "20 00 43 00 75 00 72 00 72 00 65 00 6E 00 63 00 79 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "34 00 02 01 FF FF FF FF 08 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 05 00 00 00 07 00 00 00 00 00 00 00", - "4F 00 75 00 74 00 62 00 6F 00 75 00 6E 00 64 00 20 00 54 00 72 00 61 00 76 00 65 00 6C 00 20 00", - "44 00 61 00 74 00 65 00 73 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "2C 00 02 01 FF FF FF FF 0B 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 06 00 00 00 21 00 00 00 00 00 00 00", - "42 00 75 00 73 00 69 00 6E 00 65 00 73 00 73 00 20 00 4A 00 75 00 73 00 74 00 69 00 66 00 69 00", - "63 00 61 00 74 00 69 00 6F 00 6E 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "2E 00 02 01 FF FF FF FF 03 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00 04 00 00 00 00 00 00 00", - "49 00 6E 00 66 00 61 00 6E 00 74 00 20 00 44 00 69 00 73 00 63 00 6F 00 75 00 6E 00 74 00 20 00", - "56 00 61 00 6C 00 75 00 65 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "2C 00 02 01 FF FF FF FF 0D 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 08 00 00 00 04 00 00 00 00 00 00 00", - "4F 00 74 00 68 00 65 00 72 00 20 00 43 00 61 00 72 00 72 00 69 00 65 00 72 00 20 00 53 00 65 00", - "63 00 74 00 6F 00 72 00 73 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "2C 00 02 01 FF FF FF FF 0A 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 09 00 00 00 04 00 00 00 00 00 00 00", - "4E 00 75 00 6D 00 62 00 65 00 72 00 20 00 6F 00 66 00 20 00 50 00 61 00 73 00 73 00 65 00 6E 00", - "67 00 65 00 72 00 73 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "2A 00 02 01 FF FF FF FF 0C 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0A 00 00 00 04 00 00 00 00 00 00 00", - "53 00 61 00 6C 00 65 00 73 00 20 00 41 00 72 00 65 00 61 00 20 00 43 00 6F 00 64 00 65 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "20 00 02 01 1C 00 00 00 FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0B 00 00 00 04 00 00 00 00 00 00 00", - "4F 00 74 00 68 00 65 00 72 00 20 00 52 00 65 00 66 00 75 00 6E 00 64 00 20 00 54 00 65 00 78 00", - "74 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "24 00 02 01 17 00 00 00 FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0C 00 00 00 04 00 00 00 00 00 00 00", - "4D 00 61 00 78 00 69 00 6D 00 75 00 6D 00 20 00 53 00 74 00 61 00 79 00 20 00 50 00 65 00 72 00", - "69 00 6F 00 64 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "28 00 02 01 FF FF FF FF 14 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0D 00 00 00 04 00 00 00 00 00 00 00", - "4E 00 65 00 74 00 20 00 52 00 65 00 6D 00 69 00 74 00 20 00 50 00 65 00 72 00 6D 00 69 00 74 00", - "74 00 65 00 64 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "28 00 02 01 FF FF FF FF 13 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0E 00 00 00 04 00 00 00 00 00 00 00", - "50 00 65 00 72 00 63 00 65 00 6E 00 74 00 61 00 67 00 65 00 20 00 6F 00 66 00 20 00 59 00 69 00", - "65 00 6C 00 64 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "28 00 02 01 FF FF FF FF 02 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0F 00 00 00 04 00 00 00 00 00 00 00", - "4E 00 61 00 74 00 75 00 72 00 65 00 20 00 6F 00 66 00 20 00 56 00 61 00 72 00 69 00 61 00 74 00", - "69 00 6F 00 6E 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "28 00 02 01 FF FF FF FF 12 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 10 00 00 00 50 00 00 00 00 00 00 00", - "46 00 55 00 44 00 20 00 47 00 72 00 69 00 64 00 20 00 44 00 69 00 6D 00 65 00 6E 00 73 00 69 00", - "6F 00 6E 00 73 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "28 00 02 01 10 00 00 00 11 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 12 00 00 00 04 00 00 00 00 00 00 00", - "44 00 65 00 61 00 6C 00 20 00 44 00 65 00 73 00 63 00 72 00 69 00 70 00 74 00 69 00 6F 00 6E 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "22 00 02 01 19 00 00 00 FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 13 00 00 00 09 00 00 00 00 00 00 00", - "54 00 52 00 56 00 41 00 20 00 49 00 6E 00 66 00 6F 00 72 00 6D 00 61 00 74 00 69 00 6F 00 6E 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "22 00 02 01 18 00 00 00 FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 14 00 00 00 04 00 00 00 00 00 00 00", - "50 00 72 00 6F 00 72 00 61 00 74 00 65 00 20 00 43 00 6F 00 6D 00 6D 00 65 00 6E 00 74 00 73 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "22 00 02 01 16 00 00 00 FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "43 00 6F 00 6D 00 6D 00 69 00 73 00 73 00 69 00 6F 00 6E 00 20 00 56 00 61 00 6C 00 75 00 65 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "22 00 02 01 0F 00 00 00 FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 15 00 00 00 04 00 00 00 00 00 00 00", - "4D 00 61 00 78 00 69 00 6D 00 75 00 6D 00 20 00 53 00 74 00 61 00 79 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "1A 00 02 01 20 00 00 00 FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 16 00 00 00 05 00 00 00 00 00 00 00", - "44 00 65 00 61 00 6C 00 20 00 43 00 75 00 72 00 72 00 65 00 6E 00 63 00 79 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "1C 00 02 01 1D 00 00 00 FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 17 00 00 00 07 00 00 00 00 00 00 00", - "43 00 6F 00 6E 00 73 00 6F 00 72 00 74 00 69 00 61 00 20 00 43 00 6F 00 64 00 65 00 73 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "20 00 02 01 1B 00 00 00 FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "42 00 75 00 73 00 69 00 6E 00 65 00 73 00 73 00 20 00 54 00 79 00 70 00 65 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "1C 00 02 01 1A 00 00 00 FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 18 00 00 00 04 00 00 00 00 00 00 00", - "44 00 65 00 61 00 6C 00 20 00 54 00 79 00 70 00 65 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "14 00 02 01 23 00 00 00 FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 19 00 00 00 04 00 00 00 00 00 00 00", - "53 00 75 00 72 00 63 00 68 00 61 00 72 00 67 00 65 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "14 00 02 01 21 00 00 00 FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 1A 00 00 00 04 00 00 00 00 00 00 00", - "41 00 67 00 65 00 6E 00 74 00 73 00 20 00 4E 00 61 00 6D 00 65 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "18 00 02 01 1F 00 00 00 FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 1B 00 00 00 04 00 00 00 00 00 00 00", - "46 00 61 00 72 00 65 00 20 00 54 00 79 00 70 00 65 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "14 00 02 01 1E 00 00 00 FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 1C 00 00 00 04 00 00 00 00 00 00 00", - "53 00 75 00 62 00 20 00 44 00 65 00 61 00 6C 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "12 00 02 01 24 00 00 00 FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 1D 00 00 00 04 00 00 00 00 00 00 00", - "41 00 4C 00 43 00 20 00 43 00 6F 00 64 00 65 00 73 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "14 00 02 01 22 00 00 00 FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "52 00 65 00 6D 00 61 00 72 00 6B 00 73 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "10 00 02 01 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "02 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "02 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "02 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "02 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "02 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "08 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "08 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "02 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "08 00 03 00 47 42 50 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "08 00 1D 00 28 41 29 31 36 2D 4F 63 74 2D 32 30 30 31 20 74 6F 20 31 36 2D 4F 63 74 2D 32 30 30", - "31 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "08 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "08 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "02 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "08 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "08 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "08 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "02 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "02 00 01 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "08 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "02 00 00 00 08 00 00 00 02 00 00 00 08 00 00 00 02 00 00 00 08 00 00 00 02 00 00 00 08 00 00 00", - "02 00 00 00 08 00 00 00 02 00 00 00 08 00 00 00 02 00 00 00 08 00 00 00 02 00 00 00 08 00 00 00", - "02 00 00 00 08 00 00 00 02 00 00 00 08 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "02 00 18 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "08 00 05 00 6A 61 6D 65 73 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "02 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "08 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "08 00 01 00 31 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "08 00 03 00 47 42 50 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "08 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "02 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "08 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "08 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "08 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "02 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FE FF FF FF FE FF FF FF FE FF FF FF FE FF FF FF FE FF FF FF FE FF FF FF FE FF FF FF FE FF FF FF", - "FE FF FF FF FE FF FF FF FE FF FF FF FE FF FF FF FE FF FF FF FE FF FF FF FE FF FF FF FE FF FF FF", - "11 00 00 00 FE FF FF FF FE FF FF FF FE FF FF FF FE FF FF FF FE FF FF FF FE FF FF FF FE FF FF FF", - "FE FF FF FF FE FF FF FF FE FF FF FF FE FF FF FF FE FF FF FF FE FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "01 00 00 00 02 00 00 00 03 00 00 00 04 00 00 00 05 00 00 00 06 00 00 00 07 00 00 00 08 00 00 00", - "09 00 00 00 FE FF FF FF 0B 00 00 00 0C 00 00 00 0D 00 00 00 FE FF FF FF FE FF FF FF FE FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - }; - - RawDataBlockList data_blocks = new RawDataBlockList(new ByteArrayInputStream(RawDataUtil - .decode(raw_data_array)), POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS); - int[] bat_array = { 15 }; - - // need to initialize the block list with a block allocation - // table - new BlockAllocationTableReader( - POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, 1, bat_array, 0, -2, data_blocks); - - // Fake up a header - HeaderBlock header_block = new HeaderBlock(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS); - header_block.setPropertyStart(0); - - // get property table from the document - PropertyTable table = new PropertyTable(header_block, data_blocks); - - assertEquals(30 * 64, table.getRoot().getSize()); - int count = 0; - Property child = null; - for (Property p : table.getRoot()) { - child = p; - ++count; - } - - assertNotNull("no children found", child); - assertEquals(1, count); - assertTrue(child.isDirectory()); - count = 0; - for (Property p : (DirectoryProperty) child) { - child = p; - ++count; - } - assertEquals(35, count); - } -} diff --git a/src/testcases/org/apache/poi/poifs/property/TestRootProperty.java b/src/testcases/org/apache/poi/poifs/property/TestRootProperty.java deleted file mode 100644 index 27708a4b6..000000000 --- a/src/testcases/org/apache/poi/poifs/property/TestRootProperty.java +++ /dev/null @@ -1,137 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.property; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -import org.apache.poi.poifs.common.POIFSConstants; -import org.apache.poi.poifs.storage.RawDataUtil; -import org.apache.poi.util.LocaleUtil; -import org.junit.Test; - -/** - * Class to test RootProperty functionality - * - * @author Marc Johnson - */ -public final class TestRootProperty { - private RootProperty _property; - private byte[] _testblock; - - @Test - public void testConstructor() throws IOException { - createBasicRootProperty(); - verifyProperty(); - } - - private void createBasicRootProperty() { - _property = new RootProperty(); - _testblock = new byte[128]; - int index = 0; - - for (; index < 0x40; index++) { - _testblock[index] = (byte) 0; - } - String name = "Root Entry"; - int limit = Math.min(31, name.length()); - - _testblock[index++] = (byte) (2 * (limit + 1)); - _testblock[index++] = (byte) 0; - _testblock[index++] = (byte) 5; - _testblock[index++] = (byte) 1; - for (; index < 0x50; index++) { - _testblock[index] = (byte) 0xff; - } - for (; index < 0x74; index++) { - _testblock[index] = (byte) 0; - } - _testblock[index++] = (byte) POIFSConstants.END_OF_CHAIN; - for (; index < 0x78; index++) { - _testblock[index] = (byte) 0xff; - } - for (; index < 0x80; index++) { - _testblock[index] = (byte) 0; - } - byte[] name_bytes = name.getBytes(LocaleUtil.CHARSET_1252); - - for (index = 0; index < limit; index++) { - _testblock[index * 2] = name_bytes[index]; - } - } - - private void verifyProperty() throws IOException { - ByteArrayOutputStream stream = new ByteArrayOutputStream(512); - - _property.writeData(stream); - byte[] output = stream.toByteArray(); - - assertEquals(_testblock.length, output.length); - for (int j = 0; j < _testblock.length; j++) { - assertEquals("mismatch at offset " + j, _testblock[j], output[j]); - } - } - - @Test - public void testSetSize() { - for (int j = 0; j < 10; j++) { - createBasicRootProperty(); - _property.setSize(j); - assertEquals("trying block count of " + j, j * 64, _property.getSize()); - } - } - - @Test - public void testReadingConstructor() { - String[] input = { - "52 00 6F 00 6F 00 74 00 20 00 45 00 6E 00 74 00 72 00 79 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "16 00 05 01 FF FF FF FF FF FF FF FF 02 00 00 00 20 08 02 00 00 00 00 00 C0 00 00 00 00 00 00 46", - "00 00 00 00 00 00 00 00 00 00 00 00 C0 5C E8 23 9E 6B C1 01 FE FF FF FF 00 00 00 00 00 00 00 00", - }; - verifyReadingProperty(0, RawDataUtil.decode(input), 0, "Root Entry", - "{00020820-0000-0000-C000-000000000046}"); - } - - private void verifyReadingProperty(int index, byte[] input, int offset, String name, - String sClsId) { - RootProperty property = new RootProperty(index, input, offset); - ByteArrayOutputStream stream = new ByteArrayOutputStream(128); - byte[] expected = new byte[128]; - - System.arraycopy(input, offset, expected, 0, 128); - try { - property.writeData(stream); - } catch (IOException e) { - throw new RuntimeException(e); - } - byte[] output = stream.toByteArray(); - - assertEquals(128, output.length); - for (int j = 0; j < 128; j++) { - assertEquals("mismatch at offset " + j, expected[j], output[j]); - } - assertEquals(index, property.getIndex()); - assertEquals(name, property.getName()); - assertTrue(!property.getChildren().hasNext()); - assertEquals(property.getStorageClsid().toString(), sClsId); - } -} diff --git a/src/testcases/org/apache/poi/poifs/storage/AllPOIFSStorageTests.java b/src/testcases/org/apache/poi/poifs/storage/AllPOIFSStorageTests.java deleted file mode 100644 index 806154599..000000000 --- a/src/testcases/org/apache/poi/poifs/storage/AllPOIFSStorageTests.java +++ /dev/null @@ -1,43 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.storage; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -/** - * Tests for org.apache.poi.poifs.storage
    - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestBATBlock.class, - TestBlockAllocationTableReader.class, - TestBlockAllocationTableWriter.class, - TestBlockListImpl.class, - TestDocumentBlock.class, - TestHeaderBlockReading.class, - TestHeaderBlockWriting.class, - TestPropertyBlock.class, - TestRawDataBlock.class, - TestRawDataBlockList.class, - TestSmallBlockTableReader.class, - TestSmallBlockTableWriter.class, - TestSmallDocumentBlock.class, - TestSmallDocumentBlockList.class -}) -public class AllPOIFSStorageTests { -} diff --git a/src/testcases/org/apache/poi/poifs/storage/LocalProperty.java b/src/testcases/org/apache/poi/poifs/storage/LocalProperty.java deleted file mode 100644 index 13a1c5230..000000000 --- a/src/testcases/org/apache/poi/poifs/storage/LocalProperty.java +++ /dev/null @@ -1,59 +0,0 @@ - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - - -package org.apache.poi.poifs.storage; - -import org.apache.poi.poifs.property.Property; - -class LocalProperty - extends Property -{ - - /** - * Constructor TestProperty - * - * @param name name of the property - */ - - LocalProperty(String name) - { - super(); - setName(name); - } - - /** - * do nothing - */ - - @Override - protected void preWrite() - { - } - - /** - * @return false - */ - - @Override - public boolean isDirectory() - { - return false; - } -} // end package scope class LocalProperty - diff --git a/src/testcases/org/apache/poi/poifs/storage/LocalRawDataBlockList.java b/src/testcases/org/apache/poi/poifs/storage/LocalRawDataBlockList.java deleted file mode 100644 index 7358f0024..000000000 --- a/src/testcases/org/apache/poi/poifs/storage/LocalRawDataBlockList.java +++ /dev/null @@ -1,191 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.storage; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.poifs.common.POIFSConstants; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.LittleEndianConsts; - -/** - * Class LocalRawDataBlockList - * - * @author Marc Johnson(mjohnson at apache dot org) - */ -public final class LocalRawDataBlockList extends RawDataBlockList { - private final List _list; - private RawDataBlock[] _array; - - public LocalRawDataBlockList() - throws IOException - { - super(new ByteArrayInputStream(new byte[ 0 ]), POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS); - _list = new ArrayList(); - _array = null; - } - - /** - * create and a new XBAT block - * - * @param start index of first BAT block - * @param end index of last BAT block - * @param chain index of next XBAT block - */ - public void createNewXBATBlock(final int start, final int end, - final int chain) - throws IOException - { - byte[] data = new byte[ 512 ]; - int offset = 0; - - for (int k = start; k <= end; k++) - { - LittleEndian.putInt(data, offset, k); - offset += LittleEndianConsts.INT_SIZE; - } - while (offset != 508) - { - LittleEndian.putInt(data, offset, -1); - offset += LittleEndianConsts.INT_SIZE; - } - LittleEndian.putInt(data, offset, chain); - add(new RawDataBlock(new ByteArrayInputStream(data))); - } - - /** - * create a BAT block and add it to the list - * - * @param start_index initial index for the block list - */ - public void createNewBATBlock(final int start_index) - throws IOException - { - byte[] data = new byte[ 512 ]; - int offset = 0; - - for (int j = 0; j < 128; j++) - { - int index = start_index + j; - - if (index % 256 == 0) - { - LittleEndian.putInt(data, offset, -1); - } - else if (index % 256 == 255) - { - LittleEndian.putInt(data, offset, -2); - } - else - { - LittleEndian.putInt(data, offset, index + 1); - } - offset += LittleEndianConsts.INT_SIZE; - } - add(new RawDataBlock(new ByteArrayInputStream(data))); - } - - /** - * fill the list with dummy blocks - * - * @param count of blocks - */ - public void fill(final int count) - throws IOException - { - int limit = 128 * count; - - for (int j = _list.size(); j < limit; j++) - { - add(new RawDataBlock(new ByteArrayInputStream(new byte[ 0 ]))); - } - } - - /** - * add a new block - * - * @param block new block to add - */ - public void add(RawDataBlock block) - { - _list.add(block); - } - - /** - * override of remove method - * - * @param index of block to be removed - * - * @return desired block - */ - @Override - public ListManagedBlock remove(final int index) - throws IOException - { - ensureArrayExists(); - RawDataBlock rvalue = null; - - try - { - rvalue = _array[ index ]; - if (rvalue == null) - { - throw new IOException("index " + index + " is null"); - } - _array[ index ] = null; - } - catch (ArrayIndexOutOfBoundsException ignored) - { - throw new IOException("Cannot remove block[ " + index - + " ]; out of range"); - } - return rvalue; - } - - /** - * remove the specified block from the list - * - * @param index the index of the specified block; if the index is - * out of range, that's ok - */ - @Override - public void zap(final int index) - { - ensureArrayExists(); - if ((index >= 0) && (index < _array.length)) - { - _array[ index ] = null; - } - } - - private void ensureArrayExists() - { - if (_array == null) - { - _array = _list.toArray(new RawDataBlock[ 0 ]); - } - } - - @Override - public int blockCount() { - return _list.size(); - } -} diff --git a/src/testcases/org/apache/poi/poifs/storage/RawDataUtil.java b/src/testcases/org/apache/poi/poifs/storage/RawDataUtil.java deleted file mode 100644 index f3ae3b087..000000000 --- a/src/testcases/org/apache/poi/poifs/storage/RawDataUtil.java +++ /dev/null @@ -1,117 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.poifs.storage; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.Arrays; -import java.util.zip.GZIPInputStream; - -import javax.xml.bind.DatatypeConverter; - -import org.apache.poi.util.HexDump; -import org.apache.poi.util.HexRead; -import org.apache.poi.util.IOUtils; - -/** - * Test utility class.
    - * - * Creates raw byte[] data from hex-dump String arrays. - * - * @author Josh Micich - */ -public final class RawDataUtil { - - public static byte[] decode(String[] hexDataLines) { - ByteArrayOutputStream baos = new ByteArrayOutputStream(hexDataLines.length * 32 + 32); - - for (String hexDataLine : hexDataLines) { - byte[] lineData = HexRead.readFromString(hexDataLine); - baos.write(lineData, 0, lineData.length); - } - return baos.toByteArray(); - } - - /** - * Development time utility method.
    - * Transforms a byte array into hex-dump String lines in java source code format. - */ - public static void dumpData(byte[] data) { - int i=0; - System.out.println("String[] hexDataLines = {"); - System.out.print("\t\""); - while(true) { - System.out.print(HexDump.byteToHex(data[i]).substring(2)); - i++; - if (i>=data.length) { - break; - } - if (i % 32 == 0) { - System.out.println("\","); - System.out.print("\t\""); - } else { - System.out.print(" "); - } - } - System.out.println("\","); - System.out.println("};"); - } - - /** - * Development time utility method.
    - * Confirms that the specified byte array is equivalent to the hex-dump String lines. - */ - public static void confirmEqual(byte[] expected, String[] hexDataLines) { - ByteArrayOutputStream baos = new ByteArrayOutputStream(hexDataLines.length * 32 + 32); - - for (String hexDataLine : hexDataLines) { - byte[] lineData = HexRead.readFromString(hexDataLine); - baos.write(lineData, 0, lineData.length); - } - if (!Arrays.equals(expected, baos.toByteArray())) { - throw new RuntimeException("different"); - } - } - - /** - * Decompress previously gziped/base64ed data - * - * @param data the gziped/base64ed data - * @return the raw bytes - * @throws IOException if you copy and pasted the data wrong - */ - public static byte[] decompress(String data) throws IOException { - byte[] base64Bytes = DatatypeConverter.parseBase64Binary(data); - return IOUtils.toByteArray(new GZIPInputStream(new ByteArrayInputStream(base64Bytes))); - } - - /** - * Compress raw data for test runs - usually called while debugging :) - * - * @param data the raw data - * @return the gziped/base64ed data as String - * @throws IOException usually not ... - */ - public static String compress(byte[] data) throws IOException { - java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream(); - java.util.zip.GZIPOutputStream gz = new java.util.zip.GZIPOutputStream(bos); - gz.write(data); - gz.finish(); - return DatatypeConverter.printBase64Binary(bos.toByteArray()); - } -} diff --git a/src/testcases/org/apache/poi/poifs/storage/TestBATBlock.java b/src/testcases/org/apache/poi/poifs/storage/TestBATBlock.java deleted file mode 100644 index 5ee530926..000000000 --- a/src/testcases/org/apache/poi/poifs/storage/TestBATBlock.java +++ /dev/null @@ -1,448 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.storage; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import junit.framework.TestCase; - -import org.apache.poi.poifs.common.POIFSBigBlockSize; -import org.apache.poi.poifs.common.POIFSConstants; - -/** - * Class to test BATBlock functionality - * - * @author Marc Johnson - */ -public final class TestBATBlock extends TestCase { - - /** - * Test the createBATBlocks method. The test involves setting up - * various arrays of int's and ensuring that the correct number of - * BATBlocks is created for each array, and that the data from - * each array is correctly written to the BATBlocks. - */ - public void testCreateBATBlocks() throws IOException { - - // test 0 length array (basic sanity) - BATBlock[] rvalue = BATBlock.createBATBlocks(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, createTestArray(0)); - - assertEquals(0, rvalue.length); - - // test array of length 1 - rvalue = BATBlock.createBATBlocks(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, createTestArray(1)); - assertEquals(1, rvalue.length); - verifyContents(rvalue, 1); - - // test array of length 127 - rvalue = BATBlock.createBATBlocks(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, createTestArray(127)); - assertEquals(1, rvalue.length); - verifyContents(rvalue, 127); - - // test array of length 128 - rvalue = BATBlock.createBATBlocks(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, createTestArray(128)); - assertEquals(1, rvalue.length); - verifyContents(rvalue, 128); - - // test array of length 129 - rvalue = BATBlock.createBATBlocks(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, createTestArray(129)); - assertEquals(2, rvalue.length); - verifyContents(rvalue, 129); - } - - private static int[] createTestArray(int count) { - int[] rvalue = new int[ count ]; - - for (int j = 0; j < count; j++) - { - rvalue[ j ] = j; - } - return rvalue; - } - - private static void verifyContents(BATBlock[] blocks, int entries) throws IOException { - byte[] expected = new byte[ 512 * blocks.length ]; - - Arrays.fill(expected, ( byte ) 0xFF); - int offset = 0; - - for (int j = 0; j < entries; j++) - { - expected[ offset++ ] = ( byte ) j; - expected[ offset++ ] = 0; - expected[ offset++ ] = 0; - expected[ offset++ ] = 0; - } - ByteArrayOutputStream stream = new ByteArrayOutputStream(512 - * blocks.length); - - for (BATBlock block : blocks) { - block.writeBlocks(stream); - } - byte[] actual = stream.toByteArray(); - - assertEquals(expected.length, actual.length); - for (int j = 0; j < expected.length; j++) - { - assertEquals(expected[ j ], actual[ j ]); - } - } - - public void testCreateXBATBlocks() throws IOException { - // test 0 length array (basic sanity) - BATBlock[] rvalue = BATBlock.createXBATBlocks(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, createTestArray(0), 1); - - assertEquals(0, rvalue.length); - - // test array of length 1 - rvalue = BATBlock.createXBATBlocks(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, createTestArray(1), 1); - assertEquals(1, rvalue.length); - verifyXBATContents(rvalue, 1, 1); - - // test array of length 127 - rvalue = BATBlock.createXBATBlocks(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, createTestArray(127), 1); - assertEquals(1, rvalue.length); - verifyXBATContents(rvalue, 127, 1); - - // test array of length 128 - rvalue = BATBlock.createXBATBlocks(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, createTestArray(128), 1); - assertEquals(2, rvalue.length); - verifyXBATContents(rvalue, 128, 1); - - // test array of length 254 - rvalue = BATBlock.createXBATBlocks(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, createTestArray(254), 1); - assertEquals(2, rvalue.length); - verifyXBATContents(rvalue, 254, 1); - - // test array of length 255 - rvalue = BATBlock.createXBATBlocks(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, createTestArray(255), 1); - assertEquals(3, rvalue.length); - verifyXBATContents(rvalue, 255, 1); - } - - private static void verifyXBATContents(BATBlock[] blocks, int entries, int start_block) - throws IOException { - byte[] expected = new byte[ 512 * blocks.length ]; - - Arrays.fill(expected, ( byte ) 0xFF); - int offset = 0; - - for (int j = 0; j < entries; j++) - { - if ((j % 127) == 0) - { - if (j != 0) - { - offset += 4; - } - } - expected[ offset++ ] = ( byte ) j; - expected[ offset++ ] = 0; - expected[ offset++ ] = 0; - expected[ offset++ ] = 0; - } - for (int j = 0; j < (blocks.length - 1); j++) - { - offset = 508 + (j * 512); - expected[ offset++ ] = ( byte ) (start_block + j + 1); - expected[ offset++ ] = 0; - expected[ offset++ ] = 0; - expected[ offset++ ] = 0; - } - offset = (blocks.length * 512) - 4; - expected[ offset++ ] = ( byte ) -2; - expected[ offset++ ] = ( byte ) -1; - expected[ offset++ ] = ( byte ) -1; - expected[ offset++ ] = ( byte ) -1; - ByteArrayOutputStream stream = new ByteArrayOutputStream(512 - * blocks.length); - - for (BATBlock block : blocks) { - block.writeBlocks(stream); - } - byte[] actual = stream.toByteArray(); - - assertEquals(expected.length, actual.length); - for (int j = 0; j < expected.length; j++) - { - assertEquals("offset " + j, expected[ j ], actual[ j ]); - } - } - - public void testCalculateXBATStorageRequirements() { - int[] blockCounts = { 0, 1, 127, 128 }; - int[] requirements = { 0, 1, 1, 2 }; - - for (int j = 0; j < blockCounts.length; j++) - { - assertEquals( - "requirement for " + blockCounts[ j ], requirements[ j ], - BATBlock.calculateXBATStorageRequirements(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, blockCounts[ j ])); - } - } - - public void testEntriesPerBlock() { - assertEquals(128, POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS.getBATEntriesPerBlock()); - } - public void testEntriesPerXBATBlock() { - assertEquals(127, POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS.getXBATEntriesPerBlock()); - } - public void testGetXBATChainOffset() { - assertEquals(508, POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS.getNextXBATChainOffset()); - } - - public void testCalculateMaximumSize() throws Exception { - // Zero fat blocks isn't technically valid, but it'd be header only - assertEquals( - 512, - BATBlock.calculateMaximumSize(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, 0) - ); - assertEquals( - 4096, - BATBlock.calculateMaximumSize(POIFSConstants.LARGER_BIG_BLOCK_SIZE_DETAILS, 0) - ); - - // A single FAT block can address 128/1024 blocks - assertEquals( - 512 + 512*128, - BATBlock.calculateMaximumSize(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, 1) - ); - assertEquals( - 4096 + 4096*1024, - BATBlock.calculateMaximumSize(POIFSConstants.LARGER_BIG_BLOCK_SIZE_DETAILS, 1) - ); - - assertEquals( - 512 + 4*512*128, - BATBlock.calculateMaximumSize(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, 4) - ); - assertEquals( - 4096 + 4*4096*1024, - BATBlock.calculateMaximumSize(POIFSConstants.LARGER_BIG_BLOCK_SIZE_DETAILS, 4) - ); - - // One XBAT block holds 127/1023 individual BAT blocks, so they can address - // a fairly hefty amount of space themselves - // However, the BATs continue as before - assertEquals( - 512 + 109*512*128, - BATBlock.calculateMaximumSize(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, 109) - ); - assertEquals( - 4096 + 109*4096*1024, - BATBlock.calculateMaximumSize(POIFSConstants.LARGER_BIG_BLOCK_SIZE_DETAILS, 109) - ); - - assertEquals( - 512 + 110*512*128, - BATBlock.calculateMaximumSize(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, 110) - ); - assertEquals( - 4096 + 110*4096*1024, - BATBlock.calculateMaximumSize(POIFSConstants.LARGER_BIG_BLOCK_SIZE_DETAILS, 110) - ); - - assertEquals( - 512 + 112*512*128, - BATBlock.calculateMaximumSize(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, 112) - ); - assertEquals( - 4096 + 112*4096*1024, - BATBlock.calculateMaximumSize(POIFSConstants.LARGER_BIG_BLOCK_SIZE_DETAILS, 112) - ); - - // Check for >2gb, which we only support via a File - assertEquals( - 512 + 8030l*512*128, - BATBlock.calculateMaximumSize(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, 8030) - ); - assertEquals( - 4096 + 8030l*4096*1024, - BATBlock.calculateMaximumSize(POIFSConstants.LARGER_BIG_BLOCK_SIZE_DETAILS, 8030) - ); - } - - public void testUsedSectors() throws Exception { - POIFSBigBlockSize b512 = POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS; - POIFSBigBlockSize b4096 = POIFSConstants.LARGER_BIG_BLOCK_SIZE_DETAILS; - - // Try first with 512 block sizes, which can hold 128 entries - BATBlock block512 = BATBlock.createEmptyBATBlock(b512, false); - assertEquals(true, block512.hasFreeSectors()); - assertEquals(0, block512.getUsedSectors(false)); - - // Allocate a few - block512.setValueAt(0, 42); - block512.setValueAt(10, 42); - block512.setValueAt(20, 42); - assertEquals(true, block512.hasFreeSectors()); - assertEquals(3, block512.getUsedSectors(false)); - - // Allocate all - for (int i=0; i blocks = new ArrayList(); - int offset; - - - // First, try a one BAT block file - header.setBATCount(1); - blocks.add( - BATBlock.createBATBlock(header.getBigBlockSize(), ByteBuffer.allocate(512)) - ); - - offset = 0; - assertEquals(0, BATBlock.getBATBlockAndIndex(offset, header, blocks).getIndex()); - assertEquals(0, blocks.indexOf( BATBlock.getBATBlockAndIndex(offset, header, blocks).getBlock() )); - - offset = 1; - assertEquals(1, BATBlock.getBATBlockAndIndex(offset, header, blocks).getIndex()); - assertEquals(0, blocks.indexOf( BATBlock.getBATBlockAndIndex(offset, header, blocks).getBlock() )); - - offset = 127; - assertEquals(127, BATBlock.getBATBlockAndIndex(offset, header, blocks).getIndex()); - assertEquals(0, blocks.indexOf( BATBlock.getBATBlockAndIndex(offset, header, blocks).getBlock() )); - - - // Now go for one with multiple BAT blocks - header.setBATCount(2); - blocks.add( - BATBlock.createBATBlock(header.getBigBlockSize(), ByteBuffer.allocate(512)) - ); - - offset = 0; - assertEquals(0, BATBlock.getBATBlockAndIndex(offset, header, blocks).getIndex()); - assertEquals(0, blocks.indexOf( BATBlock.getBATBlockAndIndex(offset, header, blocks).getBlock() )); - - offset = 127; - assertEquals(127, BATBlock.getBATBlockAndIndex(offset, header, blocks).getIndex()); - assertEquals(0, blocks.indexOf( BATBlock.getBATBlockAndIndex(offset, header, blocks).getBlock() )); - - offset = 128; - assertEquals(0, BATBlock.getBATBlockAndIndex(offset, header, blocks).getIndex()); - assertEquals(1, blocks.indexOf( BATBlock.getBATBlockAndIndex(offset, header, blocks).getBlock() )); - - offset = 129; - assertEquals(1, BATBlock.getBATBlockAndIndex(offset, header, blocks).getIndex()); - assertEquals(1, blocks.indexOf( BATBlock.getBATBlockAndIndex(offset, header, blocks).getBlock() )); - - - // The XBAT count makes no difference, as we flatten in memory - header.setBATCount(1); - header.setXBATCount(1); - offset = 0; - assertEquals(0, BATBlock.getBATBlockAndIndex(offset, header, blocks).getIndex()); - assertEquals(0, blocks.indexOf( BATBlock.getBATBlockAndIndex(offset, header, blocks).getBlock() )); - - offset = 126; - assertEquals(126, BATBlock.getBATBlockAndIndex(offset, header, blocks).getIndex()); - assertEquals(0, blocks.indexOf( BATBlock.getBATBlockAndIndex(offset, header, blocks).getBlock() )); - - offset = 127; - assertEquals(127, BATBlock.getBATBlockAndIndex(offset, header, blocks).getIndex()); - assertEquals(0, blocks.indexOf( BATBlock.getBATBlockAndIndex(offset, header, blocks).getBlock() )); - - offset = 128; - assertEquals(0, BATBlock.getBATBlockAndIndex(offset, header, blocks).getIndex()); - assertEquals(1, blocks.indexOf( BATBlock.getBATBlockAndIndex(offset, header, blocks).getBlock() )); - - offset = 129; - assertEquals(1, BATBlock.getBATBlockAndIndex(offset, header, blocks).getIndex()); - assertEquals(1, blocks.indexOf( BATBlock.getBATBlockAndIndex(offset, header, blocks).getBlock() )); - - - // Check with the bigger block size too - header = new HeaderBlock(POIFSConstants.LARGER_BIG_BLOCK_SIZE_DETAILS); - - offset = 0; - assertEquals(0, BATBlock.getBATBlockAndIndex(offset, header, blocks).getIndex()); - assertEquals(0, blocks.indexOf( BATBlock.getBATBlockAndIndex(offset, header, blocks).getBlock() )); - - offset = 1022; - assertEquals(1022, BATBlock.getBATBlockAndIndex(offset, header, blocks).getIndex()); - assertEquals(0, blocks.indexOf( BATBlock.getBATBlockAndIndex(offset, header, blocks).getBlock() )); - - offset = 1023; - assertEquals(1023, BATBlock.getBATBlockAndIndex(offset, header, blocks).getIndex()); - assertEquals(0, blocks.indexOf( BATBlock.getBATBlockAndIndex(offset, header, blocks).getBlock() )); - - offset = 1024; - assertEquals(0, BATBlock.getBATBlockAndIndex(offset, header, blocks).getIndex()); - assertEquals(1, blocks.indexOf( BATBlock.getBATBlockAndIndex(offset, header, blocks).getBlock() )); - - // Biggr block size, back to real BATs - header.setBATCount(2); - - offset = 0; - assertEquals(0, BATBlock.getBATBlockAndIndex(offset, header, blocks).getIndex()); - assertEquals(0, blocks.indexOf( BATBlock.getBATBlockAndIndex(offset, header, blocks).getBlock() )); - - offset = 1022; - assertEquals(1022, BATBlock.getBATBlockAndIndex(offset, header, blocks).getIndex()); - assertEquals(0, blocks.indexOf( BATBlock.getBATBlockAndIndex(offset, header, blocks).getBlock() )); - - offset = 1023; - assertEquals(1023, BATBlock.getBATBlockAndIndex(offset, header, blocks).getIndex()); - assertEquals(0, blocks.indexOf( BATBlock.getBATBlockAndIndex(offset, header, blocks).getBlock() )); - - offset = 1024; - assertEquals(0, BATBlock.getBATBlockAndIndex(offset, header, blocks).getIndex()); - assertEquals(1, blocks.indexOf( BATBlock.getBATBlockAndIndex(offset, header, blocks).getBlock() )); - } -} diff --git a/src/testcases/org/apache/poi/poifs/storage/TestBlockAllocationTableReader.java b/src/testcases/org/apache/poi/poifs/storage/TestBlockAllocationTableReader.java deleted file mode 100644 index 6a249afc1..000000000 --- a/src/testcases/org/apache/poi/poifs/storage/TestBlockAllocationTableReader.java +++ /dev/null @@ -1,429 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.storage; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.Arrays; - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -import org.apache.poi.poifs.common.POIFSBigBlockSize; -import org.apache.poi.poifs.common.POIFSConstants; -import org.apache.poi.util.HexRead; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.LittleEndianConsts; - -/** - * Class to test BlockAllocationTableReader functionality - * - * @author Marc Johnson - */ -public final class TestBlockAllocationTableReader extends TestCase { - - /** - * Test small block allocation table constructor - */ - public void testSmallBATConstructor() throws IOException { - - // need to create an array of raw blocks containing the SBAT, - // and a small document block list - String[] sbat_data = { - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FE FF FF FF FE FF FF FF FE FF FF FF FE FF FF FF FE FF FF FF FE FF FF FF", - "FE FF FF FF FE FF FF FF FE FF FF FF FE FF FF FF FE FF FF FF FE FF FF FF FE FF FF FF FE FF FF FF", - "FE FF FF FF FE FF FF FF FE FF FF FF FE FF FF FF FE FF FF FF FE FF FF FF FE FF FF FF FE FF FF FF", - "FE FF FF FF 22 00 00 00 FE FF FF FF FE FF FF FF FE FF FF FF FE FF FF FF FE FF FF FF FE FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - }; - - RawDataBlock[] sbats = { new RawDataBlock(makeDataStream(sbat_data)) }; - - String[] sbt_data = { - "08 00 28 00 6A 61 6D 65 73 2D 55 37 37 32 37 39 32 2D 28 31 36 2D 4F 63 74 2D 32 30 30 31 40 31", - "36 2D 34 31 2D 33 33 29 2E 5A 44 46 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "07 00 00 00 00 00 80 27 E2 40 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "07 00 00 00 00 00 80 27 E2 40 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "07 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "02 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "0B 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "03 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "08 00 02 00 20 31 08 00 05 00 53 61 76 65 64 08 00 17 00 53 2E 48 55 53 53 41 49 4E 20 41 20 44", - "45 56 20 4F 46 46 52 20 55 4B 08 00 0B 00 31 36 2D 4F 63 74 2D 32 30 30 31 08 00 05 00 35 2E 33", - "2E 32 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "08 00 05 00 6A 61 6D 65 73 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "08 00 03 00 47 42 50 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "08 00 1D 00 28 41 29 31 36 2D 4F 63 74 2D 32 30 30 31 20 74 6F 20 31 36 2D 4F 63 74 2D 32 30 30", - "31 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "08 00 01 00 31 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "02 00 18 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "02 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "02 00 00 00 08 00 00 00 02 00 00 00 08 00 00 00 02 00 00 00 08 00 00 00 02 00 00 00 08 00 00 00", - "02 00 00 00 08 00 00 00 02 00 00 00 08 00 00 00 02 00 00 00 08 00 00 00 02 00 00 00 08 00 00 00", - "02 00 00 00 08 00 00 00 02 00 00 00 08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "08 00 03 00 47 42 50 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "08 00 17 00 53 2E 48 55 53 53 41 49 4E 20 41 20 44 45 56 20 4F 46 46 52 20 55 4B 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "02 00 00 00 02 00 00 00 02 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "03 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - }; - - RawDataBlock[] sbts = new RawDataBlock[7]; - InputStream sbt_input = makeDataStream(sbt_data); - - for (int j = 0; j < 7; j++) { - sbts[j] = new RawDataBlock(sbt_input); - } - SmallDocumentBlockList small_blocks = new SmallDocumentBlockList(SmallDocumentBlock - .extract(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, sbts)); - BlockAllocationTableReader sbat = new BlockAllocationTableReader( - POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, sbats, small_blocks); - boolean[] isUsed = { - false, false, false, false, false, false, false, false, false, - false, true, true, true, true, true, true, true, true, true, true, - true, true, true, true, true, true, true, true, true, true, true, - true, true, true, true, true, true, true, true, true, false, - false, false, false, false, false, false, false, false, false, - false, false, false, false, false, false, false, false, false, - false, false, false, false, false, false, false, false, false, - false, false, false, false, false, false, false, false, false, - false, false, false, false, false, false, false, false, false, - false, false, false, false, false, false, false, false, false, - false, false, false, false, false, false, false, false, false, - false, false, false, false, false, false, false, false, false, - false, false, false, false, false, false, false, false, false, - false, false, false, false, false, false - }; - int[] nextIndex = { - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -2, -2, -2, -2, -2, -2, - -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, - -2, 34, -2, -2, -2, -2, -2, -2, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 - }; - - for (int j = 0; j < 128; j++) { - if (isUsed[j]) { - assertTrue("checking usage of block " + j, sbat.isUsed(j)); - assertEquals("checking usage of block " + j, nextIndex[j], sbat - .getNextBlockIndex(j)); - small_blocks.remove(j); - } else { - assertTrue("checking usage of block " + j, !sbat.isUsed(j)); - try { - small_blocks.remove(j); - fail("removing block " + j + " should have failed"); - } catch (IOException ignored) { - // expected during successful test - } - } - } - } - - private static InputStream makeDataStream(String[] hexDataLines) { - return new ByteArrayInputStream(RawDataUtil.decode(hexDataLines)); - } - - public void testReadingConstructor() throws IOException { - - // create a document, minus the header block, and use that to - // create a RawDataBlockList. The document will exist entire - // of BATBlocks and XBATBlocks - // - // we will create two XBAT blocks, which will encompass 128 - // BAT blocks between them, and two extra BAT blocks which - // will be in the block array passed to the constructor. This - // makes a total of 130 BAT blocks, which will encompass - // 16,640 blocks, for a file size of some 8.5 megabytes. - // - // Naturally, we'll fake that out ... - // - // map of blocks: - // block 0: xbat block 0 - // block 1: xbat block 1 - // block 2: bat block 0 - // block 3: bat block 1 - // blocks 4-130: bat blocks 2-128, contained in xbat block 0 - // block 131: bat block 129, contained in xbat block 1 - // blocks 132-16639: fictitious blocks, faked out. All blocks - // whose index is evenly divisible by 256 - // will be unused - LocalRawDataBlockList list = new LocalRawDataBlockList(); - - list.createNewXBATBlock(4, 130, 1); - list.createNewXBATBlock(131, 131, -2); - for (int j = 0; j < 130; j++) { - list.createNewBATBlock(j * 128); - } - list.fill(132); - int[] blocks = { 2, 3 }; - BlockAllocationTableReader table = new BlockAllocationTableReader( - POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, 130, blocks, 2, 0, list); - - for (int i = 0; i < (130 * 128); i++) { - if (i % 256 == 0) { - assertTrue("verifying block " + i + " is unused", !table.isUsed(i)); - } else if (i % 256 == 255) { - assertEquals("Verify end of chain for block " + i, POIFSConstants.END_OF_CHAIN, - table.getNextBlockIndex(i)); - } else { - assertEquals("Verify next index for block " + i, i + 1, table.getNextBlockIndex(i)); - } - } - } - - public void testFetchBlocks() throws IOException { - - // strategy: - // - // 1. set up a single BAT block from which to construct a - // BAT. create nonsense blocks in the raw data block list - // corresponding to the indices in the BAT block. - // 2. The indices will include very short documents (0 and 1 - // block in length), longer documents, and some screwed up - // documents (one with a loop, one that will peek into - // another document's data, one that includes an unused - // document, one that includes a reserved (BAT) block, one - // that includes a reserved (XBAT) block, and one that - // points off into space somewhere - LocalRawDataBlockList list = new LocalRawDataBlockList(); - byte[] data = new byte[512]; - int offset = 0; - - LittleEndian.putInt(data, offset, -3); // for the BAT block itself - offset += LittleEndianConsts.INT_SIZE; - - // document 1: is at end of file already; start block = -2 - // document 2: has only one block; start block = 1 - LittleEndian.putInt(data, offset, -2); - offset += LittleEndianConsts.INT_SIZE; - - // document 3: has a loop in it; start block = 2 - LittleEndian.putInt(data, offset, 2); - offset += LittleEndianConsts.INT_SIZE; - - // document 4: peeks into document 2's data; start block = 3 - LittleEndian.putInt(data, offset, 4); - offset += LittleEndianConsts.INT_SIZE; - LittleEndian.putInt(data, offset, 1); - offset += LittleEndianConsts.INT_SIZE; - - // document 5: includes an unused block; start block = 5 - LittleEndian.putInt(data, offset, 6); - offset += LittleEndianConsts.INT_SIZE; - LittleEndian.putInt(data, offset, -1); - offset += LittleEndianConsts.INT_SIZE; - - // document 6: includes a BAT block; start block = 7 - LittleEndian.putInt(data, offset, 8); - offset += LittleEndianConsts.INT_SIZE; - LittleEndian.putInt(data, offset, 0); - offset += LittleEndianConsts.INT_SIZE; - - // document 7: includes an XBAT block; start block = 9 - LittleEndian.putInt(data, offset, 10); - offset += LittleEndianConsts.INT_SIZE; - LittleEndian.putInt(data, offset, -4); - offset += LittleEndianConsts.INT_SIZE; - - // document 8: goes off into space; start block = 11; - LittleEndian.putInt(data, offset, 1000); - offset += LittleEndianConsts.INT_SIZE; - - // document 9: no screw ups; start block = 12; - int index = 13; - - for (; offset < 508; offset += LittleEndianConsts.INT_SIZE) { - LittleEndian.putInt(data, offset, index++); - } - LittleEndian.putInt(data, offset, -2); - list.add(new RawDataBlock(new ByteArrayInputStream(data))); - list.fill(1); - int[] blocks = { 0 }; - BlockAllocationTableReader table = new BlockAllocationTableReader( - POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, 1, blocks, 0, -2, list); - int[] start_blocks = { -2, 1, 2, 3, 5, 7, 9, 11, 12 }; - int[] expected_length = { 0, 1, -1, -1, -1, -1, -1, -1, 116 }; - - for (int j = 0; j < start_blocks.length; j++) { - try { - ListManagedBlock[] dataBlocks = table.fetchBlocks(start_blocks[j], -1, list); - - if (expected_length[j] == -1) { - fail("document " + j + " should have failed, but found a length of " - + dataBlocks.length); - } else { - assertEquals(expected_length[j], dataBlocks.length); - } - } catch (IOException e) { - if (expected_length[j] == -1) { - - // no problem, we expected a failure here - } else { - throw e; - } - } - } - } - - /** - * Bugzilla 48085 describes an error where a corrupted Excel file causes POI to throw an - * {@link OutOfMemoryError}. - */ - public void testBadSectorAllocationTableSize_bug48085() { - int BLOCK_SIZE = 512; - POIFSBigBlockSize bigBlockSize = POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS; - assertEquals(BLOCK_SIZE, bigBlockSize.getBigBlockSize()); - - // 512 bytes take from the start of bugzilla attachment 24444 - byte[] initData = HexRead.readFromString( - - "D0 CF 11 E0 A1 B1 1A E1 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 3E 20 03 20 FE FF 09 20" + - "06 20 20 20 20 20 20 20 20 20 20 20 01 20 20 20 01 20 20 20 20 20 20 20 20 10 20 20 02 20 20 20" + - "02 20 20 20 FE FF FF FF 20 20 20 20 20 20 20 20 " - ); - // the rest of the block is 'FF' - byte[] data = new byte[BLOCK_SIZE]; - Arrays.fill(data, (byte)0xFF); - System.arraycopy(initData, 0, data, 0, initData.length); - - // similar code to POIFSFileSystem.: - InputStream stream = new ByteArrayInputStream(data); - HeaderBlock hb; - RawDataBlockList dataBlocks; - try { - hb = new HeaderBlock(stream); - dataBlocks = new RawDataBlockList(stream, bigBlockSize); - } catch (IOException e) { - throw new RuntimeException(e); - } - try { - new BlockAllocationTableReader(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, - hb.getBATCount(), hb.getBATArray(), hb.getXBATCount(), - hb.getXBATIndex(), dataBlocks); - } catch (IOException e) { - // expected during successful test - assertEquals("Block count 538976257 is too high. POI maximum is 65535.", e.getMessage()); - } catch (OutOfMemoryError e) { - if (e.getStackTrace()[1].getMethodName().equals("testBadSectorAllocationTableSize")) { - throw new AssertionFailedError("Identified bug 48085"); - } - } - } -} diff --git a/src/testcases/org/apache/poi/poifs/storage/TestBlockAllocationTableWriter.java b/src/testcases/org/apache/poi/poifs/storage/TestBlockAllocationTableWriter.java deleted file mode 100644 index 023dc6f19..000000000 --- a/src/testcases/org/apache/poi/poifs/storage/TestBlockAllocationTableWriter.java +++ /dev/null @@ -1,148 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.storage; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.Arrays; - -import junit.framework.TestCase; - -import org.apache.poi.poifs.common.POIFSConstants; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.LittleEndianConsts; - -/** - * Class to test BlockAllocationTableWriter functionality - * - * @author Marc Johnson - */ -public final class TestBlockAllocationTableWriter extends TestCase { - - public void testAllocateSpace() { - BlockAllocationTableWriter table = - new BlockAllocationTableWriter(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS); - int[] blockSizes = - { - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 - }; - int expectedIndex = 0; - - for (int blockSize : blockSizes) { - assertEquals(expectedIndex, table.allocateSpace(blockSize)); - expectedIndex += blockSize; - } - } - - public void testCreateBlocks() { - BlockAllocationTableWriter table = new BlockAllocationTableWriter(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS); - - table.allocateSpace(127); - table.createBlocks(); - verifyBlocksCreated(table, 1); - table = new BlockAllocationTableWriter(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS); - table.allocateSpace(128); - table.createBlocks(); - verifyBlocksCreated(table, 2); - table = new BlockAllocationTableWriter(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS); - table.allocateSpace(254); - table.createBlocks(); - verifyBlocksCreated(table, 2); - table = new BlockAllocationTableWriter(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS); - table.allocateSpace(255); - table.createBlocks(); - verifyBlocksCreated(table, 3); - table = new BlockAllocationTableWriter(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS); - table.allocateSpace(13843); - table.createBlocks(); - verifyBlocksCreated(table, 109); - table = new BlockAllocationTableWriter(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS); - table.allocateSpace(13844); - table.createBlocks(); - verifyBlocksCreated(table, 110); - table = new BlockAllocationTableWriter(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS); - table.allocateSpace(13969); - table.createBlocks(); - verifyBlocksCreated(table, 110); - table = new BlockAllocationTableWriter(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS); - table.allocateSpace(13970); - table.createBlocks(); - verifyBlocksCreated(table, 111); - } - - /** - * Test content produced by BlockAllocationTableWriter - */ - public void testProduct() throws IOException { - BlockAllocationTableWriter table = new BlockAllocationTableWriter(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS); - - for (int k = 1; k <= 22; k++) - { - table.allocateSpace(k); - } - table.createBlocks(); - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - - table.writeBlocks(stream); - byte[] output = stream.toByteArray(); - - assertEquals(1024, output.length); - byte[] expected = new byte[ 1024 ]; - - Arrays.fill(expected, ( byte ) 0xFF); - int offset = 0; - int block_index = 1; - - for (int k = 1; k <= 22; k++) - { - int limit = k - 1; - - for (int j = 0; j < limit; j++) - { - LittleEndian.putInt(expected, offset, block_index++); - offset += LittleEndianConsts.INT_SIZE; - } - LittleEndian.putInt(expected, offset, - POIFSConstants.END_OF_CHAIN); - offset += 4; - block_index++; - } - - // add BAT block indices - LittleEndian.putInt(expected, offset, block_index++); - offset += LittleEndianConsts.INT_SIZE; - LittleEndian.putInt(expected, offset, POIFSConstants.END_OF_CHAIN); - for (int k = 0; k < expected.length; k++) - { - assertEquals("At offset " + k, expected[ k ], output[ k ]); - } - } - - private static void verifyBlocksCreated(BlockAllocationTableWriter table, int count){ - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - - try { - table.writeBlocks(stream); - } catch (IOException e) { - throw new RuntimeException(e); - } - byte[] output = stream.toByteArray(); - - assertEquals(count * 512, output.length); - } -} diff --git a/src/testcases/org/apache/poi/poifs/storage/TestBlockListImpl.java b/src/testcases/org/apache/poi/poifs/storage/TestBlockListImpl.java deleted file mode 100644 index 344b51485..000000000 --- a/src/testcases/org/apache/poi/poifs/storage/TestBlockListImpl.java +++ /dev/null @@ -1,281 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.storage; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.apache.poi.poifs.common.POIFSConstants; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.LittleEndianConsts; -import org.junit.Test; - -/** - * Class to test BlockListImpl functionality - * - * @author Marc Johnson - */ -public final class TestBlockListImpl { - private static final class BlockListTestImpl extends BlockListImpl { - public BlockListTestImpl() { - // no extra initialisation - } - } - private static BlockListImpl create() { - return new BlockListTestImpl(); - } - - @Test - public void testZap() throws IOException { - BlockListImpl list = create(); - - // verify that you can zap anything - for (int j = -2; j < 10; j++) - { - list.zap(j); - } - RawDataBlock[] blocks = new RawDataBlock[ 5 ]; - - for (int j = 0; j < 5; j++) - { - blocks[ j ] = - new RawDataBlock(new ByteArrayInputStream(new byte[ 512 ])); - } - list.setBlocks(blocks); - for (int j = -2; j < 10; j++) - { - list.zap(j); - } - - // verify that all blocks are gone - for (int j = 0; j < 5; j++) - { - try - { - list.remove(j); - fail("removing item " + j + " should not have succeeded"); - } - catch (IOException ignored) - { - } - } - } - - @Test - public void testRemove() throws IOException { - BlockListImpl list = create(); - RawDataBlock[] blocks = new RawDataBlock[ 5 ]; - byte[] data = new byte[ 512 * 5 ]; - - for (int j = 0; j < 5; j++) - { - Arrays.fill(data, j * 512, (j * 512) + 512, ( byte ) j); - } - ByteArrayInputStream stream = new ByteArrayInputStream(data); - - for (int j = 0; j < 5; j++) - { - blocks[ j ] = new RawDataBlock(stream); - } - list.setBlocks(blocks); - - // verify that you can't remove illegal indices - for (int j = -2; j < 10; j++) - { - if ((j < 0) || (j >= 5)) - { - try - { - list.remove(j); - fail("removing item " + j + " should have failed"); - } - catch (IOException ignored) - { - } - } - } - - // verify we can safely and correctly remove all blocks - for (int j = 0; j < 5; j++) - { - byte[] output = list.remove(j).getData(); - - for (int k = 0; k < 512; k++) - { - assertEquals("testing block " + j + ", index " + k, - data[ (j * 512) + k ], output[ k ]); - } - } - - // verify that all blocks are gone - for (int j = 0; j < 5; j++) - { - try - { - list.remove(j); - fail("removing item " + j + " should not have succeeded"); - } - catch (IOException ignored) - { - } - } - } - - @Test - public void testSetBAT() throws IOException { - BlockListImpl list = create(); - - list.setBAT(null); - list.setBAT(new BlockAllocationTableReader(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS)); - try - { - list.setBAT(new BlockAllocationTableReader(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS)); - fail("second attempt should have failed"); - } - catch (IOException ignored) - { - } - } - - @Test - public void testFetchBlocks() throws IOException { - - // strategy: - // - // 1. set up a single BAT block from which to construct a - // BAT. create nonsense blocks in the raw data block list - // corresponding to the indices in the BAT block. - // 2. The indices will include very short documents (0 and 1 - // block in length), longer documents, and some screwed up - // documents (one with a loop, one that will peek into - // another document's data, one that includes an unused - // document, one that includes a reserved (BAT) block, one - // that includes a reserved (XBAT) block, and one that - // points off into space somewhere - BlockListImpl list = create(); - List raw_blocks = new ArrayList(); - byte[] data = new byte[ 512 ]; - int offset = 0; - - LittleEndian.putInt(data, offset, -3); // for the BAT block itself - offset += LittleEndianConsts.INT_SIZE; - - // document 1: is at end of file already; start block = -2 - // document 2: has only one block; start block = 1 - LittleEndian.putInt(data, offset, -2); - offset += LittleEndianConsts.INT_SIZE; - - // document 3: has a loop in it; start block = 2 - LittleEndian.putInt(data, offset, 2); - offset += LittleEndianConsts.INT_SIZE; - - // document 4: peeks into document 2's data; start block = 3 - LittleEndian.putInt(data, offset, 4); - offset += LittleEndianConsts.INT_SIZE; - LittleEndian.putInt(data, offset, 1); - offset += LittleEndianConsts.INT_SIZE; - - // document 5: includes an unused block; start block = 5 - LittleEndian.putInt(data, offset, 6); - offset += LittleEndianConsts.INT_SIZE; - LittleEndian.putInt(data, offset, -1); - offset += LittleEndianConsts.INT_SIZE; - - // document 6: includes a BAT block; start block = 7 - LittleEndian.putInt(data, offset, 8); - offset += LittleEndianConsts.INT_SIZE; - LittleEndian.putInt(data, offset, 0); - offset += LittleEndianConsts.INT_SIZE; - - // document 7: includes an XBAT block; start block = 9 - LittleEndian.putInt(data, offset, 10); - offset += LittleEndianConsts.INT_SIZE; - LittleEndian.putInt(data, offset, -4); - offset += LittleEndianConsts.INT_SIZE; - - // document 8: goes off into space; start block = 11; - LittleEndian.putInt(data, offset, 1000); - offset += LittleEndianConsts.INT_SIZE; - - // document 9: no screw ups; start block = 12; - int index = 13; - - for (; offset < 508; offset += LittleEndianConsts.INT_SIZE) - { - LittleEndian.putInt(data, offset, index++); - } - LittleEndian.putInt(data, offset, -2); - raw_blocks.add(new RawDataBlock(new ByteArrayInputStream(data))); - for (int j = raw_blocks.size(); j < 128; j++) - { - raw_blocks.add( - new RawDataBlock(new ByteArrayInputStream(new byte[ 0 ]))); - } - list.setBlocks(raw_blocks.toArray(new RawDataBlock[raw_blocks.size()])); - int[] blocks = - { - 0 - }; - BlockAllocationTableReader table = - new BlockAllocationTableReader(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, 1, blocks, 0, -2, list); - int[] start_blocks = - { - -2, 1, 2, 3, 5, 7, 9, 11, 12 - }; - int[] expected_length = - { - 0, 1, -1, -1, -1, -1, -1, -1, 116 - }; - - for (int j = 0; j < start_blocks.length; j++) - { - try - { - ListManagedBlock[] dataBlocks = - list.fetchBlocks(start_blocks[ j ], -1); - - if (expected_length[ j ] == -1) - { - fail("document " + j + " should have failed"); - } - else - { - assertEquals(expected_length[ j ], dataBlocks.length); - } - } - catch (IOException e) - { - if (expected_length[ j ] == -1) - { - - // no problem, we expected a failure here - } - else - { - throw e; - } - } - } - } -} diff --git a/src/testcases/org/apache/poi/poifs/storage/TestDocumentBlock.java b/src/testcases/org/apache/poi/poifs/storage/TestDocumentBlock.java deleted file mode 100644 index 313d92cb4..000000000 --- a/src/testcases/org/apache/poi/poifs/storage/TestDocumentBlock.java +++ /dev/null @@ -1,113 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.storage; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -import org.apache.poi.poifs.common.POIFSConstants; - -import junit.framework.TestCase; - -/** - * Class to test DocumentBlock functionality - * - * @author Marc Johnson - */ -public final class TestDocumentBlock extends TestCase { - static final private byte[] _testdata; - - static - { - _testdata = new byte[ 2000 ]; - for (int j = 0; j < _testdata.length; j++) - { - _testdata[ j ] = ( byte ) j; - } - } - - /** - * Test the writing DocumentBlock constructor. - */ - public void testConstructor() - throws IOException - { - ByteArrayInputStream input = new ByteArrayInputStream(_testdata); - int index = 0; - int size = 0; - - while (true) - { - byte[] data = new byte[ Math.min(_testdata.length - index, 512) ]; - - System.arraycopy(_testdata, index, data, 0, data.length); - DocumentBlock block = new DocumentBlock(input, POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS); - - verifyOutput(block, data); - size += block.size(); - if (block.partiallyRead()) - { - break; - } - index += 512; - } - assertEquals(_testdata.length, size); - } - - - /** - * Test 'reading' constructor - */ - public void testReadingConstructor() - throws IOException - { - RawDataBlock input = - new RawDataBlock(new ByteArrayInputStream(_testdata)); - - verifyOutput(new DocumentBlock(input), input.getData()); - } - - private void verifyOutput(DocumentBlock block, byte [] input) - throws IOException - { - assertEquals(input.length, block.size()); - if (input.length < 512) - { - assertTrue(block.partiallyRead()); - } - else - { - assertTrue(!block.partiallyRead()); - } - ByteArrayOutputStream output = new ByteArrayOutputStream(512); - - block.writeBlocks(output); - byte[] copy = output.toByteArray(); - int j = 0; - - for (; j < input.length; j++) - { - assertEquals(input[ j ], copy[ j ]); - } - for (; j < 512; j++) - { - assertEquals(( byte ) 0xFF, copy[ j ]); - } - } -} diff --git a/src/testcases/org/apache/poi/poifs/storage/TestHeaderBlockReading.java b/src/testcases/org/apache/poi/poifs/storage/TestHeaderBlockReading.java deleted file mode 100644 index 15077c4fb..000000000 --- a/src/testcases/org/apache/poi/poifs/storage/TestHeaderBlockReading.java +++ /dev/null @@ -1,83 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.storage; - -import java.io.ByteArrayInputStream; -import java.io.IOException; - -import junit.framework.TestCase; - -/** - * Class to test HeaderBlockReader functionality - * - * @author Marc Johnson - */ -public final class TestHeaderBlockReading extends TestCase { - - public void testConstructors() throws IOException { - String[] hexData = { - "D0 CF 11 E0 A1 B1 1A E1 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3B 00 03 00 FE FF 09 00", - "06 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 FE FF FF FF 00 00 00 00 00 10 00 00 FE FF FF FF", - "01 00 00 00 FE FF FF FF 00 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - }; - byte[] content = RawDataUtil.decode(hexData); - HeaderBlock block = new HeaderBlock(new ByteArrayInputStream(content)); - - assertEquals(-2, block.getPropertyStart()); - - // verify we can't read a short block - byte[] shortblock = new byte[511]; - - System.arraycopy(content, 0, shortblock, 0, 511); - try { - block = new HeaderBlock(new ByteArrayInputStream(shortblock)); - fail("Should have caught IOException reading a short block"); - } catch (IOException ignored) { - - // as expected - } - - // try various forms of corruption - for (int index = 0; index < 8; index++) { - content[index] = (byte) (content[index] - 1); - try { - block = new HeaderBlock(new ByteArrayInputStream(content)); - fail("Should have caught IOException corrupting byte " + index); - } catch (IOException ignored) { - - // as expected - } - - // restore byte value - content[index] = (byte) (content[index] + 1); - } - } -} diff --git a/src/testcases/org/apache/poi/poifs/storage/TestHeaderBlockWriting.java b/src/testcases/org/apache/poi/poifs/storage/TestHeaderBlockWriting.java deleted file mode 100644 index e01c7885b..000000000 --- a/src/testcases/org/apache/poi/poifs/storage/TestHeaderBlockWriting.java +++ /dev/null @@ -1,270 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.storage; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -import junit.framework.TestCase; - -import org.apache.poi.poifs.common.POIFSConstants; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.LittleEndianConsts; - -/** - * Class to test HeaderBlockWriter functionality - * - * @author Marc Johnson - */ -public final class TestHeaderBlockWriting extends TestCase { - - private static void confirmEqual(String[] expectedDataHexDumpLines, byte[] actual) { - byte[] expected = RawDataUtil.decode(expectedDataHexDumpLines); - - assertEquals(expected.length, actual.length); - for (int j = 0; j < expected.length; j++) { - assertEquals("testing byte " + j, expected[j], actual[j]); - } - } - - /** - * Test creating a HeaderBlockWriter - */ - public void testConstructors() throws IOException { - HeaderBlockWriter block = new HeaderBlockWriter(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS); - ByteArrayOutputStream output = new ByteArrayOutputStream(512); - - block.writeBlocks(output); - byte[] copy = output.toByteArray(); - String[] expected = { - "D0 CF 11 E0 A1 B1 1A E1 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3B 00 03 00 FE FF 09 00", - "06 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 FE FF FF FF 00 00 00 00 00 10 00 00 FE FF FF FF", - "00 00 00 00 FE FF FF FF 00 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - }; - - confirmEqual(expected, copy); - - // verify we can read a 'good' HeaderBlockWriter (also test - // getPropertyStart) - block.setPropertyStart(0x87654321); - output = new ByteArrayOutputStream(512); - block.writeBlocks(output); - assertEquals(0x87654321, new HeaderBlock( - new ByteArrayInputStream(output.toByteArray())).getPropertyStart()); - } - - /** - * Test setting the SBAT start block - */ - public void testSetSBATStart() throws IOException { - HeaderBlockWriter block = new HeaderBlockWriter(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS); - - block.setSBATStart(0x01234567); - ByteArrayOutputStream output = new ByteArrayOutputStream(512); - - block.writeBlocks(output); - byte[] copy = output.toByteArray(); - String[] expected = { - "D0 CF 11 E0 A1 B1 1A E1 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3B 00 03 00 FE FF 09 00", - "06 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 FE FF FF FF 00 00 00 00 00 10 00 00 67 45 23 01", - "00 00 00 00 FE FF FF FF 00 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - }; - confirmEqual(expected, copy); - } - - /** - * test setPropertyStart and getPropertyStart - */ - public void testSetPropertyStart() throws IOException { - HeaderBlockWriter block = new HeaderBlockWriter(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS); - - block.setPropertyStart(0x01234567); - ByteArrayOutputStream output = new ByteArrayOutputStream(512); - - block.writeBlocks(output); - byte[] copy = output.toByteArray(); - String[] expected = { - "D0 CF 11 E0 A1 B1 1A E1 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3B 00 03 00 FE FF 09 00", - "06 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 67 45 23 01 00 00 00 00 00 10 00 00 FE FF FF FF", - "00 00 00 00 FE FF FF FF 00 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - }; - confirmEqual(expected, copy); - } - - /** - * test setting the BAT blocks; also tests getBATCount, getBATArray, - * getXBATCount - */ - public void testSetBATBlocks() throws IOException { - - // first, a small set of blocks - HeaderBlockWriter block = new HeaderBlockWriter(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS); - BATBlock[] xbats = block.setBATBlocks(5, 0x01234567); - - assertEquals(0, xbats.length); - assertEquals(0, HeaderBlockWriter.calculateXBATStorageRequirements(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS,5)); - ByteArrayOutputStream output = new ByteArrayOutputStream(512); - - block.writeBlocks(output); - byte[] copy = output.toByteArray(); - String[] expected = { - "D0 CF 11 E0 A1 B1 1A E1 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3B 00 03 00 FE FF 09 00", - "06 00 00 00 00 00 00 00 00 00 00 00 05 00 00 00 FE FF FF FF 00 00 00 00 00 10 00 00 FE FF FF FF", - "00 00 00 00 FE FF FF FF 00 00 00 00 67 45 23 01 68 45 23 01 69 45 23 01 6A 45 23 01 6B 45 23 01", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - }; - - confirmEqual(expected, copy); - - // second, a full set of blocks (109 blocks) - block = new HeaderBlockWriter(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS); - xbats = block.setBATBlocks(109, 0x01234567); - assertEquals(0, xbats.length); - assertEquals(0, HeaderBlockWriter.calculateXBATStorageRequirements(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS,109)); - output = new ByteArrayOutputStream(512); - block.writeBlocks(output); - copy = output.toByteArray(); - String[] expected2 = { - "D0 CF 11 E0 A1 B1 1A E1 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3B 00 03 00 FE FF 09 00", - "06 00 00 00 00 00 00 00 00 00 00 00 6D 00 00 00 FE FF FF FF 00 00 00 00 00 10 00 00 FE FF FF FF", - "00 00 00 00 FE FF FF FF 00 00 00 00 67 45 23 01 68 45 23 01 69 45 23 01 6A 45 23 01 6B 45 23 01", - "6C 45 23 01 6D 45 23 01 6E 45 23 01 6F 45 23 01 70 45 23 01 71 45 23 01 72 45 23 01 73 45 23 01", - "74 45 23 01 75 45 23 01 76 45 23 01 77 45 23 01 78 45 23 01 79 45 23 01 7A 45 23 01 7B 45 23 01", - "7C 45 23 01 7D 45 23 01 7E 45 23 01 7F 45 23 01 80 45 23 01 81 45 23 01 82 45 23 01 83 45 23 01", - "84 45 23 01 85 45 23 01 86 45 23 01 87 45 23 01 88 45 23 01 89 45 23 01 8A 45 23 01 8B 45 23 01", - "8C 45 23 01 8D 45 23 01 8E 45 23 01 8F 45 23 01 90 45 23 01 91 45 23 01 92 45 23 01 93 45 23 01", - "94 45 23 01 95 45 23 01 96 45 23 01 97 45 23 01 98 45 23 01 99 45 23 01 9A 45 23 01 9B 45 23 01", - "9C 45 23 01 9D 45 23 01 9E 45 23 01 9F 45 23 01 A0 45 23 01 A1 45 23 01 A2 45 23 01 A3 45 23 01", - "A4 45 23 01 A5 45 23 01 A6 45 23 01 A7 45 23 01 A8 45 23 01 A9 45 23 01 AA 45 23 01 AB 45 23 01", - "AC 45 23 01 AD 45 23 01 AE 45 23 01 AF 45 23 01 B0 45 23 01 B1 45 23 01 B2 45 23 01 B3 45 23 01", - "B4 45 23 01 B5 45 23 01 B6 45 23 01 B7 45 23 01 B8 45 23 01 B9 45 23 01 BA 45 23 01 BB 45 23 01", - "BC 45 23 01 BD 45 23 01 BE 45 23 01 BF 45 23 01 C0 45 23 01 C1 45 23 01 C2 45 23 01 C3 45 23 01", - "C4 45 23 01 C5 45 23 01 C6 45 23 01 C7 45 23 01 C8 45 23 01 C9 45 23 01 CA 45 23 01 CB 45 23 01", - "CC 45 23 01 CD 45 23 01 CE 45 23 01 CF 45 23 01 D0 45 23 01 D1 45 23 01 D2 45 23 01 D3 45 23 01", - }; - confirmEqual(expected2, copy); - - // finally, a really large set of blocks (256 blocks) - block = new HeaderBlockWriter(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS); - xbats = block.setBATBlocks(256, 0x01234567); - assertEquals(2, xbats.length); - assertEquals(2, HeaderBlockWriter.calculateXBATStorageRequirements(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS,256)); - output = new ByteArrayOutputStream(512); - block.writeBlocks(output); - copy = output.toByteArray(); - String[] expected3 = { - "D0 CF 11 E0 A1 B1 1A E1 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3B 00 03 00 FE FF 09 00", - "06 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 FE FF FF FF 00 00 00 00 00 10 00 00 FE FF FF FF", - "00 00 00 00 67 46 23 01 02 00 00 00 67 45 23 01 68 45 23 01 69 45 23 01 6A 45 23 01 6B 45 23 01", - "6C 45 23 01 6D 45 23 01 6E 45 23 01 6F 45 23 01 70 45 23 01 71 45 23 01 72 45 23 01 73 45 23 01", - "74 45 23 01 75 45 23 01 76 45 23 01 77 45 23 01 78 45 23 01 79 45 23 01 7A 45 23 01 7B 45 23 01", - "7C 45 23 01 7D 45 23 01 7E 45 23 01 7F 45 23 01 80 45 23 01 81 45 23 01 82 45 23 01 83 45 23 01", - "84 45 23 01 85 45 23 01 86 45 23 01 87 45 23 01 88 45 23 01 89 45 23 01 8A 45 23 01 8B 45 23 01", - "8C 45 23 01 8D 45 23 01 8E 45 23 01 8F 45 23 01 90 45 23 01 91 45 23 01 92 45 23 01 93 45 23 01", - "94 45 23 01 95 45 23 01 96 45 23 01 97 45 23 01 98 45 23 01 99 45 23 01 9A 45 23 01 9B 45 23 01", - "9C 45 23 01 9D 45 23 01 9E 45 23 01 9F 45 23 01 A0 45 23 01 A1 45 23 01 A2 45 23 01 A3 45 23 01", - "A4 45 23 01 A5 45 23 01 A6 45 23 01 A7 45 23 01 A8 45 23 01 A9 45 23 01 AA 45 23 01 AB 45 23 01", - "AC 45 23 01 AD 45 23 01 AE 45 23 01 AF 45 23 01 B0 45 23 01 B1 45 23 01 B2 45 23 01 B3 45 23 01", - "B4 45 23 01 B5 45 23 01 B6 45 23 01 B7 45 23 01 B8 45 23 01 B9 45 23 01 BA 45 23 01 BB 45 23 01", - "BC 45 23 01 BD 45 23 01 BE 45 23 01 BF 45 23 01 C0 45 23 01 C1 45 23 01 C2 45 23 01 C3 45 23 01", - "C4 45 23 01 C5 45 23 01 C6 45 23 01 C7 45 23 01 C8 45 23 01 C9 45 23 01 CA 45 23 01 CB 45 23 01", - "CC 45 23 01 CD 45 23 01 CE 45 23 01 CF 45 23 01 D0 45 23 01 D1 45 23 01 D2 45 23 01 D3 45 23 01", - }; - - confirmEqual(expected3, copy); - - output = new ByteArrayOutputStream(1028); - xbats[0].writeBlocks(output); - xbats[1].writeBlocks(output); - copy = output.toByteArray(); - int correct = 0x012345D4; - int offset = 0; - int k = 0; - - for (; k < 127; k++) { - assertEquals("XBAT entry " + k, correct, LittleEndian.getInt(copy, offset)); - correct++; - offset += LittleEndianConsts.INT_SIZE; - } - assertEquals("XBAT Chain", 0x01234567 + 257, LittleEndian.getInt(copy, offset)); - offset += LittleEndianConsts.INT_SIZE; - k++; - for (; k < 148; k++) { - assertEquals("XBAT entry " + k, correct, LittleEndian.getInt(copy, offset)); - correct++; - offset += LittleEndianConsts.INT_SIZE; - } - for (; k < 255; k++) { - assertEquals("XBAT entry " + k, -1, LittleEndian.getInt(copy, offset)); - offset += LittleEndianConsts.INT_SIZE; - } - assertEquals("XBAT End of chain", -2, LittleEndian.getInt(copy, offset)); - } -} diff --git a/src/testcases/org/apache/poi/poifs/storage/TestPropertyBlock.java b/src/testcases/org/apache/poi/poifs/storage/TestPropertyBlock.java deleted file mode 100644 index e4af23a99..000000000 --- a/src/testcases/org/apache/poi/poifs/storage/TestPropertyBlock.java +++ /dev/null @@ -1,201 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.storage; - -import static org.junit.Assert.assertEquals; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.poifs.common.POIFSConstants; -import org.apache.poi.poifs.property.Property; -import org.junit.Test; - -/** - * Class to test PropertyBlock functionality - */ -public final class TestPropertyBlock { - - @Test - public void testCreatePropertyBlocks() throws Exception { - - // test with 0 properties - List properties = new ArrayList(); - BlockWritable[] blocks = - PropertyBlock.createPropertyBlockArray(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS,properties); - - assertEquals(0, blocks.length); - - // test with 1 property - properties.add(new LocalProperty("Root Entry")); - blocks = PropertyBlock.createPropertyBlockArray(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS,properties); - assertEquals(1, blocks.length); - byte[] testblock = new byte[ 512 ]; - - for (int j = 0; j < 4; j++) - { - setDefaultBlock(testblock, j); - } - testblock[ 0x0000 ] = ( byte ) 'R'; - testblock[ 0x0002 ] = ( byte ) 'o'; - testblock[ 0x0004 ] = ( byte ) 'o'; - testblock[ 0x0006 ] = ( byte ) 't'; - testblock[ 0x0008 ] = ( byte ) ' '; - testblock[ 0x000A ] = ( byte ) 'E'; - testblock[ 0x000C ] = ( byte ) 'n'; - testblock[ 0x000E ] = ( byte ) 't'; - testblock[ 0x0010 ] = ( byte ) 'r'; - testblock[ 0x0012 ] = ( byte ) 'y'; - testblock[ 0x0040 ] = ( byte ) 22; - verifyCorrect(blocks, testblock); - - // test with 3 properties - properties.add(new LocalProperty("workbook")); - properties.add(new LocalProperty("summary")); - blocks = PropertyBlock.createPropertyBlockArray(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS,properties); - assertEquals(1, blocks.length); - testblock[ 0x0080 ] = ( byte ) 'w'; - testblock[ 0x0082 ] = ( byte ) 'o'; - testblock[ 0x0084 ] = ( byte ) 'r'; - testblock[ 0x0086 ] = ( byte ) 'k'; - testblock[ 0x0088 ] = ( byte ) 'b'; - testblock[ 0x008A ] = ( byte ) 'o'; - testblock[ 0x008C ] = ( byte ) 'o'; - testblock[ 0x008E ] = ( byte ) 'k'; - testblock[ 0x00C0 ] = ( byte ) 18; - testblock[ 0x0100 ] = ( byte ) 's'; - testblock[ 0x0102 ] = ( byte ) 'u'; - testblock[ 0x0104 ] = ( byte ) 'm'; - testblock[ 0x0106 ] = ( byte ) 'm'; - testblock[ 0x0108 ] = ( byte ) 'a'; - testblock[ 0x010A ] = ( byte ) 'r'; - testblock[ 0x010C ] = ( byte ) 'y'; - testblock[ 0x0140 ] = ( byte ) 16; - verifyCorrect(blocks, testblock); - - // test with 4 properties - properties.add(new LocalProperty("wintery")); - blocks = PropertyBlock.createPropertyBlockArray(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS,properties); - assertEquals(1, blocks.length); - testblock[ 0x0180 ] = ( byte ) 'w'; - testblock[ 0x0182 ] = ( byte ) 'i'; - testblock[ 0x0184 ] = ( byte ) 'n'; - testblock[ 0x0186 ] = ( byte ) 't'; - testblock[ 0x0188 ] = ( byte ) 'e'; - testblock[ 0x018A ] = ( byte ) 'r'; - testblock[ 0x018C ] = ( byte ) 'y'; - testblock[ 0x01C0 ] = ( byte ) 16; - verifyCorrect(blocks, testblock); - - // test with 5 properties - properties.add(new LocalProperty("foo")); - blocks = PropertyBlock.createPropertyBlockArray(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS,properties); - assertEquals(2, blocks.length); - testblock = new byte[ 1024 ]; - for (int j = 0; j < 8; j++) - { - setDefaultBlock(testblock, j); - } - testblock[ 0x0000 ] = ( byte ) 'R'; - testblock[ 0x0002 ] = ( byte ) 'o'; - testblock[ 0x0004 ] = ( byte ) 'o'; - testblock[ 0x0006 ] = ( byte ) 't'; - testblock[ 0x0008 ] = ( byte ) ' '; - testblock[ 0x000A ] = ( byte ) 'E'; - testblock[ 0x000C ] = ( byte ) 'n'; - testblock[ 0x000E ] = ( byte ) 't'; - testblock[ 0x0010 ] = ( byte ) 'r'; - testblock[ 0x0012 ] = ( byte ) 'y'; - testblock[ 0x0040 ] = ( byte ) 22; - testblock[ 0x0080 ] = ( byte ) 'w'; - testblock[ 0x0082 ] = ( byte ) 'o'; - testblock[ 0x0084 ] = ( byte ) 'r'; - testblock[ 0x0086 ] = ( byte ) 'k'; - testblock[ 0x0088 ] = ( byte ) 'b'; - testblock[ 0x008A ] = ( byte ) 'o'; - testblock[ 0x008C ] = ( byte ) 'o'; - testblock[ 0x008E ] = ( byte ) 'k'; - testblock[ 0x00C0 ] = ( byte ) 18; - testblock[ 0x0100 ] = ( byte ) 's'; - testblock[ 0x0102 ] = ( byte ) 'u'; - testblock[ 0x0104 ] = ( byte ) 'm'; - testblock[ 0x0106 ] = ( byte ) 'm'; - testblock[ 0x0108 ] = ( byte ) 'a'; - testblock[ 0x010A ] = ( byte ) 'r'; - testblock[ 0x010C ] = ( byte ) 'y'; - testblock[ 0x0140 ] = ( byte ) 16; - testblock[ 0x0180 ] = ( byte ) 'w'; - testblock[ 0x0182 ] = ( byte ) 'i'; - testblock[ 0x0184 ] = ( byte ) 'n'; - testblock[ 0x0186 ] = ( byte ) 't'; - testblock[ 0x0188 ] = ( byte ) 'e'; - testblock[ 0x018A ] = ( byte ) 'r'; - testblock[ 0x018C ] = ( byte ) 'y'; - testblock[ 0x01C0 ] = ( byte ) 16; - testblock[ 0x0200 ] = ( byte ) 'f'; - testblock[ 0x0202 ] = ( byte ) 'o'; - testblock[ 0x0204 ] = ( byte ) 'o'; - testblock[ 0x0240 ] = ( byte ) 8; - verifyCorrect(blocks, testblock); - } - - private static void setDefaultBlock(byte [] testblock, int j) - { - int base = j * 128; - int index = 0; - - for (; index < 0x40; index++) - { - testblock[ base++ ] = ( byte ) 0; - } - testblock[ base++ ] = ( byte ) 2; - testblock[ base++ ] = ( byte ) 0; - index += 2; - for (; index < 0x44; index++) - { - testblock[ base++ ] = ( byte ) 0; - } - for (; index < 0x50; index++) - { - testblock[ base++ ] = ( byte ) 0xff; - } - for (; index < 0x80; index++) - { - testblock[ base++ ] = ( byte ) 0; - } - } - - private static void verifyCorrect(BlockWritable[] blocks, byte[] testblock) - throws IOException { - ByteArrayOutputStream stream = new ByteArrayOutputStream(512 - * blocks.length); - - for (BlockWritable b : blocks) { - b.writeBlocks(stream); - } - byte[] output = stream.toByteArray(); - - assertEquals(testblock.length, output.length); - for (int j = 0; j < testblock.length; j++) { - assertEquals("mismatch at offset " + j, testblock[ j ], - output[ j ]); - } - } -} diff --git a/src/testcases/org/apache/poi/poifs/storage/TestRawDataBlock.java b/src/testcases/org/apache/poi/poifs/storage/TestRawDataBlock.java deleted file mode 100644 index ea995c11f..000000000 --- a/src/testcases/org/apache/poi/poifs/storage/TestRawDataBlock.java +++ /dev/null @@ -1,262 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.storage; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.Random; - -import junit.framework.TestCase; - -import org.apache.poi.util.DummyPOILogger; -import org.apache.poi.util.POILogger; - -/** - * Class to test RawDataBlock functionality - * - * @author Marc Johnson - */ -public final class TestRawDataBlock extends TestCase { - /** - * Test creating a normal RawDataBlock - */ - public void testNormalConstructor() throws IOException { - byte[] data = new byte[ 512 ]; - - for (int j = 0; j < 512; j++) - { - data[ j ] = ( byte ) j; - } - RawDataBlock block = new RawDataBlock(new ByteArrayInputStream(data)); - - assertTrue("Should not be at EOF", !block.eof()); - byte[] out_data = block.getData(); - - assertEquals("Should be same length", data.length, out_data.length); - for (int j = 0; j < 512; j++) - { - assertEquals("Should be same value at offset " + j, data[ j ], - out_data[ j ]); - } - } - - /** - * Test creating an empty RawDataBlock - */ - public void testEmptyConstructor() throws IOException { - byte[] data = new byte[ 0 ]; - RawDataBlock block = new RawDataBlock(new ByteArrayInputStream(data)); - - assertTrue("Should be at EOF", block.eof()); - try - { - block.getData(); - } - catch (IOException ignored) - { - - // as expected - } - } - - /** - * Test creating a short RawDataBlock - * Will trigger a warning, but no longer an IOException, - * as people seem to have "valid" truncated files - */ - public void testShortConstructor() throws Exception { - // Get the logger to be used - POILogger oldLogger = RawDataBlock.log; - DummyPOILogger logger = new DummyPOILogger(); - try { - RawDataBlock.log = logger; - assertEquals(0, logger.logged.size()); - - // Test for various data sizes - for (int k = 1; k <= 512; k++) - { - byte[] data = new byte[ k ]; - - for (int j = 0; j < k; j++) - { - data[ j ] = ( byte ) j; - } - RawDataBlock block = null; - - logger.reset(); - assertEquals(0, logger.logged.size()); - - // Have it created - block = new RawDataBlock(new ByteArrayInputStream(data)); - assertNotNull(block); - - // Check for the warning is there for <512 - if(k < 512) { - assertEquals( - "Warning on " + k + " byte short block", - 1, logger.logged.size() - ); - - // Build the expected warning message, and check - String bts = k + " byte"; - if(k > 1) { - bts += "s"; - } - - assertEquals( - "7 - Unable to read entire block; "+bts+" read before EOF; expected 512 bytes. Your document was either written by software that ignores the spec, or has been truncated!", - logger.logged.get(0) - ); - } else { - assertEquals(0, logger.logged.size()); - } - } - } finally { - RawDataBlock.log = oldLogger; - } - } - - /** - * Tests that when using a slow input stream, which - * won't return a full block at a time, we don't - * incorrectly think that there's not enough data - */ - public void testSlowInputStream() throws Exception { - // Get the logger to be used - POILogger oldLogger = RawDataBlock.log; - DummyPOILogger logger = new DummyPOILogger(); - try { - RawDataBlock.log = logger; - assertEquals(0, logger.logged.size()); - - // Test for various ok data sizes - for (int k = 1; k < 512; k++) { - byte[] data = new byte[ 512 ]; - for (int j = 0; j < data.length; j++) { - data[j] = (byte) j; - } - - // Shouldn't complain, as there is enough data, - // even if it dribbles through - RawDataBlock block = - new RawDataBlock(new SlowInputStream(data, k)); - assertFalse(block.eof()); - } - - // But if there wasn't enough data available, will - // complain - for (int k = 1; k < 512; k++) { - byte[] data = new byte[ 511 ]; - for (int j = 0; j < data.length; j++) { - data[j] = (byte) j; - } - - logger.reset(); - assertEquals(0, logger.logged.size()); - - // Should complain, as there isn't enough data - RawDataBlock block = - new RawDataBlock(new SlowInputStream(data, k)); - assertNotNull(block); - assertEquals( - "Warning on " + k + " byte short block", - 1, logger.logged.size() - ); - } - } finally { - RawDataBlock.log = oldLogger; - } - } - - /** - * An input stream which will return a maximum of - * a given number of bytes to read, and often claims - * not to have any data - */ - public static class SlowInputStream extends InputStream { - private final Random rnd = new Random(); - private final byte[] data; - private final int chunkSize; - private int pos = 0; - - public SlowInputStream(byte[] data, int chunkSize) { - this.chunkSize = chunkSize; - this.data = data; - } - - /** - * 75% of the time, claim there's no data available - */ - private boolean claimNoData() { - if(rnd.nextFloat() < 0.25f) { - return false; - } - return true; - } - - @Override - public int read() { - if(pos >= data.length) { - return -1; - } - int ret = data[pos]; - pos++; - - if(ret < 0) ret += 256; - return ret; - } - - /** - * Reads the requested number of bytes, or the chunk - * size, whichever is lower. - * Quite often will simply claim to have no data - */ - @Override - public int read(byte[] b, int off, int len) { - // Keep the length within the chunk size - if(len > chunkSize) { - len = chunkSize; - } - // Don't read off the end of the data - if(pos + len > data.length) { - len = data.length - pos; - - // Spot when we're out of data - if(len == 0) { - return -1; - } - } - - // 75% of the time, claim there's no data - if(claimNoData()) { - return 0; - } - - // Copy, and return what we read - System.arraycopy(data, pos, b, off, len); - pos += len; - return len; - } - - @Override - public int read(byte[] b) { - return read(b, 0, b.length); - } - } -} diff --git a/src/testcases/org/apache/poi/poifs/storage/TestRawDataBlockList.java b/src/testcases/org/apache/poi/poifs/storage/TestRawDataBlockList.java deleted file mode 100644 index cc38bbc51..000000000 --- a/src/testcases/org/apache/poi/poifs/storage/TestRawDataBlockList.java +++ /dev/null @@ -1,84 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.storage; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import junit.framework.TestCase; - -import org.apache.poi.poifs.common.POIFSConstants; -import org.apache.poi.util.DummyPOILogger; -import org.apache.poi.util.POILogger; - -/** - * Class to test RawDataBlockList functionality - * - * @author Marc Johnson - */ -public final class TestRawDataBlockList extends TestCase { - /** - * Test creating a normal RawDataBlockList - */ - public void testNormalConstructor() throws IOException { - byte[] data = new byte[ 2560 ]; - - for (int j = 0; j < 2560; j++) - { - data[ j ] = ( byte ) j; - } - new RawDataBlockList(new ByteArrayInputStream(data), POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS); - } - - /** - * Test creating an empty RawDataBlockList - */ - public void testEmptyConstructor() throws IOException { - new RawDataBlockList(new ByteArrayInputStream(new byte[ 0 ]), POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS); - } - - /** - * Test creating a short RawDataBlockList - */ - public void testShortConstructor() throws Exception { - // Get the logger to be used - POILogger oldLogger = RawDataBlock.log; - DummyPOILogger logger = new DummyPOILogger(); - try { - RawDataBlock.log = logger; - assertEquals(0, logger.logged.size()); - - // Test for various short sizes - for (int k = 2049; k < 2560; k++) - { - byte[] data = new byte[ k ]; - - for (int j = 0; j < k; j++) - { - data[ j ] = ( byte ) j; - } - - // Check we logged the error - logger.reset(); - new RawDataBlockList(new ByteArrayInputStream(data), POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS); - assertEquals(1, logger.logged.size()); - } - } finally { - RawDataBlock.log = oldLogger; - } - } -} diff --git a/src/testcases/org/apache/poi/poifs/storage/TestSmallBlockTableReader.java b/src/testcases/org/apache/poi/poifs/storage/TestSmallBlockTableReader.java deleted file mode 100644 index ee8ac39d5..000000000 --- a/src/testcases/org/apache/poi/poifs/storage/TestSmallBlockTableReader.java +++ /dev/null @@ -1,317 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.storage; - -import java.io.ByteArrayInputStream; -import java.io.IOException; - -import junit.framework.TestCase; - -import org.apache.poi.poifs.common.POIFSConstants; -import org.apache.poi.poifs.property.PropertyTable; -import org.apache.poi.poifs.property.RootProperty; - -/** - * Class to test SmallBlockTableReader functionality - * - * @author Marc Johnson - */ -public final class TestSmallBlockTableReader extends TestCase { - - public void testReadingConstructor() throws IOException { - - // first, we need the raw data blocks - String[] raw_data_array = { - "52 00 6F 00 6F 00 74 00 20 00 45 00 6E 00 74 00 72 00 79 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "16 00 05 01 FF FF FF FF FF FF FF FF 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0A 00 00 00 80 07 00 00 00 00 00 00", - "44 00 65 00 61 00 6C 00 20 00 49 00 6E 00 66 00 6F 00 72 00 6D 00 61 00 74 00 69 00 6F 00 6E 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "22 00 01 01 FF FF FF FF FF FF FF FF 15 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "46 00 55 00 44 00 20 00 47 00 72 00 69 00 64 00 20 00 49 00 6E 00 66 00 6F 00 72 00 6D 00 61 00", - "74 00 69 00 6F 00 6E 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "2A 00 02 01 FF FF FF FF 0E 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "44 00 6F 00 75 00 62 00 6C 00 65 00 20 00 44 00 65 00 61 00 6C 00 69 00 6E 00 67 00 20 00 49 00", - "6E 00 64 00 69 00 63 00 61 00 74 00 6F 00 72 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "32 00 02 01 FF FF FF FF 09 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00", - "43 00 68 00 69 00 6C 00 64 00 20 00 50 00 65 00 72 00 63 00 65 00 6E 00 74 00 61 00 67 00 65 00", - "20 00 50 00 65 00 72 00 6D 00 69 00 74 00 74 00 65 00 64 00 00 00 00 00 00 00 00 00 00 00 00 00", - "36 00 02 01 FF FF FF FF 07 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 04 00 00 00 00 00 00 00", - "43 00 61 00 6E 00 63 00 65 00 6C 00 6C 00 61 00 74 00 69 00 6F 00 6E 00 20 00 46 00 65 00 65 00", - "20 00 46 00 69 00 78 00 65 00 64 00 20 00 56 00 61 00 6C 00 75 00 65 00 00 00 00 00 00 00 00 00", - "3A 00 02 01 FF FF FF FF 06 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 04 00 00 00 00 00 00 00", - "55 00 6D 00 62 00 72 00 65 00 6C 00 6C 00 61 00 20 00 4C 00 69 00 6E 00 6B 00 73 00 20 00 61 00", - "6E 00 64 00 20 00 50 00 61 00 73 00 73 00 65 00 6E 00 67 00 65 00 72 00 73 00 00 00 00 00 00 00", - "3C 00 02 01 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "43 00 61 00 6E 00 63 00 65 00 6C 00 6C 00 61 00 74 00 69 00 6F 00 6E 00 20 00 46 00 65 00 65 00", - "20 00 50 00 65 00 72 00 63 00 65 00 6E 00 74 00 61 00 67 00 65 00 00 00 00 00 00 00 00 00 00 00", - "38 00 02 01 FF FF FF FF 05 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 03 00 00 00 04 00 00 00 00 00 00 00", - "49 00 6E 00 66 00 61 00 6E 00 74 00 20 00 44 00 69 00 73 00 63 00 6F 00 75 00 6E 00 74 00 20 00", - "50 00 65 00 72 00 6D 00 69 00 74 00 74 00 65 00 64 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "34 00 02 01 FF FF FF FF 04 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 04 00 00 00 00 00 00 00", - "43 00 61 00 6E 00 63 00 65 00 6C 00 6C 00 61 00 74 00 69 00 6F 00 6E 00 20 00 46 00 65 00 65 00", - "20 00 43 00 75 00 72 00 72 00 65 00 6E 00 63 00 79 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "34 00 02 01 FF FF FF FF 08 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 05 00 00 00 07 00 00 00 00 00 00 00", - "4F 00 75 00 74 00 62 00 6F 00 75 00 6E 00 64 00 20 00 54 00 72 00 61 00 76 00 65 00 6C 00 20 00", - "44 00 61 00 74 00 65 00 73 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "2C 00 02 01 FF FF FF FF 0B 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 06 00 00 00 21 00 00 00 00 00 00 00", - "42 00 75 00 73 00 69 00 6E 00 65 00 73 00 73 00 20 00 4A 00 75 00 73 00 74 00 69 00 66 00 69 00", - "63 00 61 00 74 00 69 00 6F 00 6E 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "2E 00 02 01 FF FF FF FF 03 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00 04 00 00 00 00 00 00 00", - "49 00 6E 00 66 00 61 00 6E 00 74 00 20 00 44 00 69 00 73 00 63 00 6F 00 75 00 6E 00 74 00 20 00", - "56 00 61 00 6C 00 75 00 65 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "2C 00 02 01 FF FF FF FF 0D 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 08 00 00 00 04 00 00 00 00 00 00 00", - "4F 00 74 00 68 00 65 00 72 00 20 00 43 00 61 00 72 00 72 00 69 00 65 00 72 00 20 00 53 00 65 00", - "63 00 74 00 6F 00 72 00 73 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "2C 00 02 01 FF FF FF FF 0A 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 09 00 00 00 04 00 00 00 00 00 00 00", - "4E 00 75 00 6D 00 62 00 65 00 72 00 20 00 6F 00 66 00 20 00 50 00 61 00 73 00 73 00 65 00 6E 00", - "67 00 65 00 72 00 73 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "2A 00 02 01 FF FF FF FF 0C 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0A 00 00 00 04 00 00 00 00 00 00 00", - "53 00 61 00 6C 00 65 00 73 00 20 00 41 00 72 00 65 00 61 00 20 00 43 00 6F 00 64 00 65 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "20 00 02 01 1C 00 00 00 FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0B 00 00 00 04 00 00 00 00 00 00 00", - "4F 00 74 00 68 00 65 00 72 00 20 00 52 00 65 00 66 00 75 00 6E 00 64 00 20 00 54 00 65 00 78 00", - "74 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "24 00 02 01 17 00 00 00 FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0C 00 00 00 04 00 00 00 00 00 00 00", - "4D 00 61 00 78 00 69 00 6D 00 75 00 6D 00 20 00 53 00 74 00 61 00 79 00 20 00 50 00 65 00 72 00", - "69 00 6F 00 64 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "28 00 02 01 FF FF FF FF 14 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0D 00 00 00 04 00 00 00 00 00 00 00", - "4E 00 65 00 74 00 20 00 52 00 65 00 6D 00 69 00 74 00 20 00 50 00 65 00 72 00 6D 00 69 00 74 00", - "74 00 65 00 64 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "28 00 02 01 FF FF FF FF 13 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0E 00 00 00 04 00 00 00 00 00 00 00", - "50 00 65 00 72 00 63 00 65 00 6E 00 74 00 61 00 67 00 65 00 20 00 6F 00 66 00 20 00 59 00 69 00", - "65 00 6C 00 64 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "28 00 02 01 FF FF FF FF 02 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0F 00 00 00 04 00 00 00 00 00 00 00", - "4E 00 61 00 74 00 75 00 72 00 65 00 20 00 6F 00 66 00 20 00 56 00 61 00 72 00 69 00 61 00 74 00", - "69 00 6F 00 6E 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "28 00 02 01 FF FF FF FF 12 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 10 00 00 00 50 00 00 00 00 00 00 00", - "46 00 55 00 44 00 20 00 47 00 72 00 69 00 64 00 20 00 44 00 69 00 6D 00 65 00 6E 00 73 00 69 00", - "6F 00 6E 00 73 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "28 00 02 01 10 00 00 00 11 00 00 00 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 12 00 00 00 04 00 00 00 00 00 00 00", - "44 00 65 00 61 00 6C 00 20 00 44 00 65 00 73 00 63 00 72 00 69 00 70 00 74 00 69 00 6F 00 6E 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "22 00 02 01 19 00 00 00 FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 13 00 00 00 09 00 00 00 00 00 00 00", - "54 00 52 00 56 00 41 00 20 00 49 00 6E 00 66 00 6F 00 72 00 6D 00 61 00 74 00 69 00 6F 00 6E 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "22 00 02 01 18 00 00 00 FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 14 00 00 00 04 00 00 00 00 00 00 00", - "50 00 72 00 6F 00 72 00 61 00 74 00 65 00 20 00 43 00 6F 00 6D 00 6D 00 65 00 6E 00 74 00 73 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "22 00 02 01 16 00 00 00 FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "43 00 6F 00 6D 00 6D 00 69 00 73 00 73 00 69 00 6F 00 6E 00 20 00 56 00 61 00 6C 00 75 00 65 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "22 00 02 01 0F 00 00 00 FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 15 00 00 00 04 00 00 00 00 00 00 00", - "4D 00 61 00 78 00 69 00 6D 00 75 00 6D 00 20 00 53 00 74 00 61 00 79 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "1A 00 02 01 20 00 00 00 FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 16 00 00 00 05 00 00 00 00 00 00 00", - "44 00 65 00 61 00 6C 00 20 00 43 00 75 00 72 00 72 00 65 00 6E 00 63 00 79 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "1C 00 02 01 1D 00 00 00 FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 17 00 00 00 07 00 00 00 00 00 00 00", - "43 00 6F 00 6E 00 73 00 6F 00 72 00 74 00 69 00 61 00 20 00 43 00 6F 00 64 00 65 00 73 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "20 00 02 01 1B 00 00 00 FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "42 00 75 00 73 00 69 00 6E 00 65 00 73 00 73 00 20 00 54 00 79 00 70 00 65 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "1C 00 02 01 1A 00 00 00 FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 18 00 00 00 04 00 00 00 00 00 00 00", - "44 00 65 00 61 00 6C 00 20 00 54 00 79 00 70 00 65 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "14 00 02 01 23 00 00 00 FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 19 00 00 00 04 00 00 00 00 00 00 00", - "53 00 75 00 72 00 63 00 68 00 61 00 72 00 67 00 65 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "14 00 02 01 21 00 00 00 FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 1A 00 00 00 04 00 00 00 00 00 00 00", - "41 00 67 00 65 00 6E 00 74 00 73 00 20 00 4E 00 61 00 6D 00 65 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "18 00 02 01 1F 00 00 00 FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 1B 00 00 00 04 00 00 00 00 00 00 00", - "46 00 61 00 72 00 65 00 20 00 54 00 79 00 70 00 65 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "14 00 02 01 1E 00 00 00 FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 1C 00 00 00 04 00 00 00 00 00 00 00", - "53 00 75 00 62 00 20 00 44 00 65 00 61 00 6C 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "12 00 02 01 24 00 00 00 FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 1D 00 00 00 04 00 00 00 00 00 00 00", - "41 00 4C 00 43 00 20 00 43 00 6F 00 64 00 65 00 73 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "14 00 02 01 22 00 00 00 FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "52 00 65 00 6D 00 61 00 72 00 6B 00 73 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "10 00 02 01 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "02 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "02 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "02 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00", - "02 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "02 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "08 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "08 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "02 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "08 00 03 00 47 42 50 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "08 00 1D 00 28 41 29 31 36 2D 4F 63 74 2D 32 30 30 31 20 74 6F 20 31 36 2D 4F 63 74 2D 32 30 30", - "31 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "08 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "08 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "02 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "08 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "08 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "08 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "02 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "02 00 01 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "08 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "02 00 00 00 08 00 00 00 02 00 00 00 08 00 00 00 02 00 00 00 08 00 00 00 02 00 00 00 08 00 00 00", - "02 00 00 00 08 00 00 00 02 00 00 00 08 00 00 00 02 00 00 00 08 00 00 00 02 00 00 00 08 00 00 00", - "02 00 00 00 08 00 00 00 02 00 00 00 08 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "02 00 18 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "08 00 05 00 6A 61 6D 65 73 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "02 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "08 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "08 00 01 00 31 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "08 00 03 00 47 42 50 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "08 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "02 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "08 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "08 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "08 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "02 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FE FF FF FF FE FF FF FF FE FF FF FF FE FF FF FF FE FF FF FF FE FF FF FF FE FF FF FF FE FF FF FF", - "FE FF FF FF FE FF FF FF FE FF FF FF FE FF FF FF FE FF FF FF FE FF FF FF FE FF FF FF FE FF FF FF", - "11 00 00 00 FE FF FF FF FE FF FF FF FE FF FF FF FE FF FF FF FE FF FF FF FE FF FF FF FE FF FF FF", - "FE FF FF FF FE FF FF FF FE FF FF FF FE FF FF FF FE FF FF FF FE FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "01 00 00 00 02 00 00 00 03 00 00 00 04 00 00 00 05 00 00 00 06 00 00 00 07 00 00 00 08 00 00 00", - "09 00 00 00 FE FF FF FF 0B 00 00 00 0C 00 00 00 0D 00 00 00 FE FF FF FF FE FF FF FF FE FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - "FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF", - }; - - RawDataBlockList data_blocks = new RawDataBlockList(new ByteArrayInputStream(RawDataUtil - .decode(raw_data_array)), POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS); - int[] bat_array = { 15 }; - - // need to initialize the block list with a block allocation - // table - new BlockAllocationTableReader(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, 1, bat_array, 0, -2, data_blocks); - - // Fake up a header - HeaderBlock header_block = new HeaderBlock(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS); - header_block.setPropertyStart(0); - - // get property table from the document - PropertyTable properties = new PropertyTable(header_block, data_blocks); - RootProperty root = properties.getRoot(); - BlockList bl = SmallBlockTableReader.getSmallDocumentBlocks( - POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, data_blocks, root, 14); - assertNotNull(bl); - } -} diff --git a/src/testcases/org/apache/poi/poifs/storage/TestSmallBlockTableWriter.java b/src/testcases/org/apache/poi/poifs/storage/TestSmallBlockTableWriter.java deleted file mode 100644 index 9bb4f6a16..000000000 --- a/src/testcases/org/apache/poi/poifs/storage/TestSmallBlockTableWriter.java +++ /dev/null @@ -1,96 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.storage; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import junit.framework.TestCase; - -import org.apache.poi.poifs.common.POIFSConstants; -import org.apache.poi.poifs.filesystem.OPOIFSDocument; -import org.apache.poi.poifs.property.PropertyTable; -import org.apache.poi.poifs.property.RootProperty; - -/** - * Class to test SmallBlockTableWriter functionality - * - * @author Marc Johnson - */ -public final class TestSmallBlockTableWriter extends TestCase { - - public void testWritingConstructor() throws IOException { - List documents = new ArrayList(); - - documents.add( - new OPOIFSDocument( - "doc340", new ByteArrayInputStream(new byte[ 340 ]))); - documents.add( - new OPOIFSDocument( - "doc5000", new ByteArrayInputStream(new byte[ 5000 ]))); - documents - .add(new OPOIFSDocument("doc0", - new ByteArrayInputStream(new byte[ 0 ]))); - documents - .add(new OPOIFSDocument("doc1", - new ByteArrayInputStream(new byte[ 1 ]))); - documents - .add(new OPOIFSDocument("doc2", - new ByteArrayInputStream(new byte[ 2 ]))); - documents - .add(new OPOIFSDocument("doc3", - new ByteArrayInputStream(new byte[ 3 ]))); - documents - .add(new OPOIFSDocument("doc4", - new ByteArrayInputStream(new byte[ 4 ]))); - documents - .add(new OPOIFSDocument("doc5", - new ByteArrayInputStream(new byte[ 5 ]))); - documents - .add(new OPOIFSDocument("doc6", - new ByteArrayInputStream(new byte[ 6 ]))); - documents - .add(new OPOIFSDocument("doc7", - new ByteArrayInputStream(new byte[ 7 ]))); - documents - .add(new OPOIFSDocument("doc8", - new ByteArrayInputStream(new byte[ 8 ]))); - documents - .add(new OPOIFSDocument("doc9", - new ByteArrayInputStream(new byte[ 9 ]))); - - HeaderBlock header = new HeaderBlock(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS); - RootProperty root = new PropertyTable(header).getRoot(); - SmallBlockTableWriter sbtw = new SmallBlockTableWriter( - POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, documents,root); - BlockAllocationTableWriter bat = sbtw.getSBAT(); - - // 15 small blocks: 6 for doc340, 0 for doc5000 (too big), 0 - // for doc0 (no storage needed), 1 each for doc1 through doc9 - assertEquals(15 * 64, root.getSize()); - - // 15 small blocks rounds up to 2 big blocks - assertEquals(2, sbtw.countBlocks()); - int start_block = 1000 + root.getStartBlock(); - - sbtw.setStartBlock(start_block); - assertEquals(start_block, root.getStartBlock()); - } -} diff --git a/src/testcases/org/apache/poi/poifs/storage/TestSmallDocumentBlock.java b/src/testcases/org/apache/poi/poifs/storage/TestSmallDocumentBlock.java deleted file mode 100644 index 2d6ef1845..000000000 --- a/src/testcases/org/apache/poi/poifs/storage/TestSmallDocumentBlock.java +++ /dev/null @@ -1,223 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.storage; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import junit.framework.TestCase; - -import org.apache.poi.poifs.common.POIFSConstants; - -/** - * Class to test SmallDocumentBlock functionality - * - * @author Marc Johnson - */ -public final class TestSmallDocumentBlock extends TestCase { - static final private byte[] _testdata; - static final private int _testdata_size = 2999; - - static - { - _testdata = new byte[ _testdata_size ]; - for (int j = 0; j < _testdata.length; j++) - { - _testdata[ j ] = ( byte ) j; - } - } - - /** - * Test conversion from DocumentBlocks - */ - public void testConvert1() - throws IOException - { - ByteArrayInputStream stream = new ByteArrayInputStream(_testdata); - List documents = new ArrayList(); - - while (true) - { - DocumentBlock block = new DocumentBlock(stream,POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS); - - documents.add(block); - if (block.partiallyRead()) - { - break; - } - } - SmallDocumentBlock[] results = - SmallDocumentBlock.convert(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, - documents.toArray(new DocumentBlock[ 0 ]), _testdata_size); - - assertEquals("checking correct result size: ", - (_testdata_size + 63) / 64, results.length); - ByteArrayOutputStream output = new ByteArrayOutputStream(); - - for (SmallDocumentBlock result : results) { - result.writeBlocks(output); - } - byte[] output_array = output.toByteArray(); - - assertEquals("checking correct output size: ", 64 * results.length, - output_array.length); - int index = 0; - - for (; index < _testdata_size; index++) - { - assertEquals("checking output " + index, _testdata[ index ], - output_array[ index ]); - } - for (; index < output_array.length; index++) - { - assertEquals("checking output " + index, ( byte ) 0xff, - output_array[ index ]); - } - } - - /** - * Test conversion from byte array - */ - public void testConvert2() - throws IOException - { - for (int j = 0; j < 320; j++) - { - byte[] array = new byte[ j ]; - - for (int k = 0; k < j; k++) - { - array[ k ] = ( byte ) k; - } - SmallDocumentBlock[] blocks = SmallDocumentBlock.convert( - POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, array, 319); - - assertEquals(5, blocks.length); - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - - for (SmallDocumentBlock block : blocks) { - block.writeBlocks(stream); - } - stream.close(); - byte[] output = stream.toByteArray(); - - for (int k = 0; k < array.length; k++) - { - assertEquals(String.valueOf(k), array[ k ], output[ k ]); - } - for (int k = array.length; k < 320; k++) - { - assertEquals(String.valueOf(k), ( byte ) 0xFF, output[ k ]); - } - } - } - - /** - * test fill - */ - public void testFill() - throws IOException - { - for (int j = 0; j <= 8; j++) - { - List blocks = new ArrayList(); - - for (int k = 0; k < j; k++) - { - blocks.add(new SmallDocumentBlock(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS)); - } - int result = SmallDocumentBlock.fill(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, blocks); - - assertEquals("correct big block count: ", (j + 7) / 8, result); - assertEquals("correct small block count: ", 8 * result, - blocks.size()); - for (int m = j; m < blocks.size(); m++) - { - BlockWritable block = blocks.get(m); - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - - block.writeBlocks(stream); - byte[] output = stream.toByteArray(); - - assertEquals("correct output size (block[ " + m + " ]): ", - 64, output.length); - for (int n = 0; n < 64; n++) - { - assertEquals("correct value (block[ " + m + " ][ " + n - + " ]): ", ( byte ) 0xff, output[ n ]); - } - } - } - } - - /** - * test calcSize - */ - - public void testCalcSize() - { - for (int j = 0; j < 10; j++) - { - assertEquals("testing " + j, j * 64, - SmallDocumentBlock.calcSize(j)); - } - } - - /** - * test extract method - * - * @exception IOException - */ - - public void testExtract() - throws IOException - { - byte[] data = new byte[ 512 ]; - int offset = 0; - - for (int j = 0; j < 8; j++) - { - for (int k = 0; k < 64; k++) - { - data[ offset++ ] = ( byte ) (k + j); - } - } - RawDataBlock[] blocks = - { - new RawDataBlock(new ByteArrayInputStream(data)) - }; - List output = SmallDocumentBlock.extract(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS,blocks); - - offset = 0; - for (SmallDocumentBlock block : output) - { - byte[] out_data = block.getData(); - - assertEquals("testing block at offset " + offset, 64, - out_data.length); - for (byte b : out_data) { - assertEquals("testing byte at offset " + offset, - data[ offset ], b); - offset++; - } - } - } -} diff --git a/src/testcases/org/apache/poi/poifs/storage/TestSmallDocumentBlockList.java b/src/testcases/org/apache/poi/poifs/storage/TestSmallDocumentBlockList.java deleted file mode 100644 index 5301214e9..000000000 --- a/src/testcases/org/apache/poi/poifs/storage/TestSmallDocumentBlockList.java +++ /dev/null @@ -1,67 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.poifs.storage; - -import java.io.ByteArrayInputStream; -import java.io.IOException; - -import org.apache.poi.poifs.common.POIFSConstants; - -import junit.framework.TestCase; - -/** - * Class to test SmallDocumentBlockList functionality - * - * @author Marc Johnson - */ -public final class TestSmallDocumentBlockList extends TestCase { - - public void testConstructor() throws IOException { - byte[] data = new byte[ 2560 ]; - - for (int j = 0; j < 2560; j++) - { - data[ j ] = ( byte ) j; - } - ByteArrayInputStream stream = new ByteArrayInputStream(data); - RawDataBlock[] blocks = new RawDataBlock[ 5 ]; - - for (int j = 0; j < 5; j++) - { - blocks[ j ] = new RawDataBlock(stream); - } - SmallDocumentBlockList sdbl = - new SmallDocumentBlockList(SmallDocumentBlock.extract(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS,blocks)); - - // proof we added the blocks - for (int j = 0; j < 40; j++) - { - sdbl.remove(j); - } - try - { - sdbl.remove(41); - fail("there should have been an Earth-shattering ka-boom!"); - } - catch (IOException ignored) - { - - // it better have thrown one!! - } - } -} diff --git a/src/testcases/org/apache/poi/sl/TestCommonSL.java b/src/testcases/org/apache/poi/sl/TestCommonSL.java deleted file mode 100644 index bb04ad71c..000000000 --- a/src/testcases/org/apache/poi/sl/TestCommonSL.java +++ /dev/null @@ -1,38 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.sl; - -import java.awt.Color; - -import org.apache.poi.sl.draw.DrawPaint; -import org.apache.poi.sl.usermodel.PaintStyle; -import org.apache.poi.sl.usermodel.PaintStyle.SolidPaint; -import org.junit.Ignore; - -/** - * Currently only contains helper methods - */ -@Ignore -public class TestCommonSL { - - public static boolean sameColor(Color colorExpected, PaintStyle paintActual) { - if (!(paintActual instanceof SolidPaint)) return false; - Color thisC = DrawPaint.applyColorTransform(((SolidPaint)paintActual).getSolidColor()); - return thisC.equals(colorExpected); - } - -} diff --git a/src/testcases/org/apache/poi/sl/draw/geom/TestPresetGeometries.java b/src/testcases/org/apache/poi/sl/draw/geom/TestPresetGeometries.java deleted file mode 100644 index 43a408383..000000000 --- a/src/testcases/org/apache/poi/sl/draw/geom/TestPresetGeometries.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ -package org.apache.poi.sl.draw.geom; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.awt.geom.Path2D; -import java.awt.geom.Rectangle2D; -import java.net.URL; -import java.util.Enumeration; -import java.util.Map; - -import org.junit.Test; - -public class TestPresetGeometries { - @Test - public void testRead(){ - Map shapes = PresetGeometries.getInstance(); - assertEquals(187, shapes.size()); - - for(String name : shapes.keySet()) { - CustomGeometry geom = shapes.get(name); - Context ctx = new Context(geom, new Rectangle2D.Double(0, 0, 100, 100), new IAdjustableShape() { - @Override - public Guide getAdjustValue(String presetName) { - return null; - } - }); - for(Path p : geom){ - Path2D path = p.getPath(ctx); - assertNotNull(path); - } - } - - // we get the same instance on further calls - assertTrue(shapes == PresetGeometries.getInstance()); - } - - // helper methods to adjust list of presets for other tests - public static void clearPreset() { - // ensure that we are initialized - assertNotNull(PresetGeometries.getInstance()); - - // test handling if some presets are not found - PresetGeometries._inst.clear(); - } - - public static void resetPreset() { - PresetGeometries._inst = null; - } - - @Test - public void testCheckXMLParser() throws Exception{ - // Gump reports a strange error because of an unavailable XML Parser, let's try to find out where - // this comes from - // - Enumeration resources = this.getClass().getClassLoader().getResources("META-INF/services/javax.xml.stream.XMLEventFactory"); - printURLs(resources); - resources = ClassLoader.getSystemResources("META-INF/services/javax.xml.stream.XMLEventFactory"); - printURLs(resources); - resources = ClassLoader.getSystemResources("org/apache/poi/sl/draw/geom/presetShapeDefinitions.xml"); - printURLs(resources); - } - - private void printURLs(Enumeration resources) { - while(resources.hasMoreElements()) { - URL url = resources.nextElement(); - System.out.println("URL: " + url); - } - } -} diff --git a/src/testcases/org/apache/poi/sl/usermodel/BaseTestSlideShow.java b/src/testcases/org/apache/poi/sl/usermodel/BaseTestSlideShow.java deleted file mode 100644 index e02260844..000000000 --- a/src/testcases/org/apache/poi/sl/usermodel/BaseTestSlideShow.java +++ /dev/null @@ -1,95 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.sl.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.sl.usermodel.PictureData.PictureType; -import org.junit.Test; - -public abstract class BaseTestSlideShow { - protected static final POIDataSamples slTests = POIDataSamples.getSlideShowInstance(); - - public abstract SlideShow createSlideShow(); - - @Test - public void addPicture_File() throws IOException { - SlideShow show = createSlideShow(); - File f = slTests.getFile("clock.jpg"); - - assertEquals(0, show.getPictureData().size()); - PictureData picture = show.addPicture(f, PictureType.JPEG); - assertEquals(1, show.getPictureData().size()); - assertSame(picture, show.getPictureData().get(0)); - - show.close(); - } - - @Test - public void addPicture_Stream() throws IOException { - SlideShow show = createSlideShow(); - try { - InputStream stream = slTests.openResourceAsStream("clock.jpg"); - try { - assertEquals(0, show.getPictureData().size()); - PictureData picture = show.addPicture(stream, PictureType.JPEG); - assertEquals(1, show.getPictureData().size()); - assertSame(picture, show.getPictureData().get(0)); - - } finally { - stream.close(); - } - } finally { - show.close(); - } - } - - @Test - public void addPicture_ByteArray() throws IOException { - SlideShow show = createSlideShow(); - byte[] data = slTests.readFile("clock.jpg"); - - assertEquals(0, show.getPictureData().size()); - PictureData picture = show.addPicture(data, PictureType.JPEG); - assertEquals(1, show.getPictureData().size()); - assertSame(picture, show.getPictureData().get(0)); - - show.close(); - } - - @Test - public void findPicture() throws IOException { - SlideShow show = createSlideShow(); - byte[] data = slTests.readFile("clock.jpg"); - - assertNull(show.findPictureData(data)); - PictureData picture = show.addPicture(data, PictureType.JPEG); - PictureData found = show.findPictureData(data); - assertNotNull(found); - assertEquals(picture, found); - - show.close(); - } -} diff --git a/src/testcases/org/apache/poi/sl/usermodel/BaseTestSlideShowFactory.java b/src/testcases/org/apache/poi/sl/usermodel/BaseTestSlideShowFactory.java deleted file mode 100644 index 168679025..000000000 --- a/src/testcases/org/apache/poi/sl/usermodel/BaseTestSlideShowFactory.java +++ /dev/null @@ -1,204 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.sl.usermodel; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; - -public class BaseTestSlideShowFactory { - private static final POIDataSamples _slTests = POIDataSamples.getSlideShowInstance(); - - @SuppressWarnings("resource") - protected static void testFactoryFromFile(String file) throws Exception { - SlideShow ss; - // from file - ss = SlideShowFactory.create(fromFile(file)); - assertNotNull(ss); - assertCloseDoesNotModifyFile(file, ss); - } - - @SuppressWarnings("resource") - protected static void testFactoryFromStream(String file) throws Exception { - SlideShow ss; - // from stream - ss = SlideShowFactory.create(fromStream(file)); - assertNotNull(ss); - assertCloseDoesNotModifyFile(file, ss); - } - - @SuppressWarnings("resource") - protected static void testFactoryFromNative(String file) throws Exception { - SlideShow ss; - // from NPOIFS - if (file.endsWith(".ppt")) { - NPOIFSFileSystem npoifs = new NPOIFSFileSystem(fromFile(file)); - ss = SlideShowFactory.create(npoifs); - assertNotNull(ss); - npoifs.close(); - assertCloseDoesNotModifyFile(file, ss); - } - // from OPCPackage - else if (file.endsWith(".pptx")) { - // not implemented - throw new UnsupportedOperationException("Test not implemented"); - } - else { - fail("Unexpected file extension: " + file); - } - } - - @SuppressWarnings("resource") - protected static void testFactoryFromProtectedFile(String protectedFile, String password) throws Exception { - SlideShow ss; - // from protected file - ss = SlideShowFactory.create(fromFile(protectedFile), password); - assertNotNull(ss); - assertCloseDoesNotModifyFile(protectedFile, ss); - } - - @SuppressWarnings("resource") - protected static void testFactoryFromProtectedStream(String protectedFile, String password) throws Exception { - SlideShow ss; - // from protected stream - ss = SlideShowFactory.create(fromStream(protectedFile), password); - assertNotNull(ss); - assertCloseDoesNotModifyFile(protectedFile, ss); - } - - @SuppressWarnings("resource") - protected static void testFactoryFromProtectedNative(String protectedFile, String password) throws Exception { - SlideShow ss; - // Encryption layer is a BIFF8 binary format that can be read by NPOIFSFileSystem, - // used for both HSLF and XSLF - - // from protected NPOIFS - if (protectedFile.endsWith(".ppt") || protectedFile.endsWith(".pptx")) { - NPOIFSFileSystem npoifs = new NPOIFSFileSystem(fromFile(protectedFile)); - ss = SlideShowFactory.create(npoifs, password); - assertNotNull(ss); - npoifs.close(); - assertCloseDoesNotModifyFile(protectedFile, ss); - } - else { - fail("Unrecognized file extension: " + protectedFile); - } - } - - public static void testFactory(String file, String protectedFile, String password) - throws Exception { - testFactoryFromFile(file); - testFactoryFromStream(file); - testFactoryFromNative(file); - - testFactoryFromProtectedFile(protectedFile, password); - testFactoryFromProtectedStream(protectedFile, password); - testFactoryFromProtectedNative(protectedFile, password); - } - - /** - * reads either a test-data file (filename) or a file outside the test-data folder (full path) - */ - private static byte[] readFile(String filename) { - byte[] bytes; - try { - bytes = _slTests.readFile(filename); - } catch (final RuntimeException e) { - if (!e.getMessage().startsWith("Sample file '" + filename + "' not found in data dir")) { - throw e; - } - bytes = readExternalFile(filename); - } - return bytes; - } - - private static byte[] readExternalFile(String path) { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - - try { - InputStream fis = new FileInputStream(path); - byte[] buf = new byte[512]; - while (true) { - int bytesRead = fis.read(buf); - if (bytesRead < 1) { - break; - } - baos.write(buf, 0, bytesRead); - } - fis.close(); - } catch (final IOException e) { - throw new RuntimeException(e); - } - final byte[] bytes = baos.toByteArray(); - return bytes; - } - - /** - * FIXME: - * bug 58779: Closing an XMLSlideShow that was created with {@link SlideShowFactory#create(File)} modifies the file - * - * @param filename the sample filename or full path of the slideshow to check before and after closing - * @param ss the slideshow to close or revert - * @throws IOException - */ - private static void assertCloseDoesNotModifyFile(String filename, SlideShow ss) throws IOException { - final byte[] before = readFile(filename); - ss.close(); - final byte[] after = readFile(filename); - - try { - assertArrayEquals(filename + " sample file was modified as a result of closing the slideshow", - before, after); - } catch (AssertionError e) { - // if the file after closing is different, then re-set - // the file to the state before in order to not have a dirty SCM - // working tree when running this test - FileOutputStream str = new FileOutputStream(_slTests.getFile(filename)); - try { - str.write(before); - } finally { - str.close(); - } - - throw e; - } - } - - private static File fromFile(String file) { - return (file.contains("/") || file.contains("\\")) - ? new File(file) - : _slTests.getFile(file); - } - - private static InputStream fromStream(String file) throws IOException { - return (file.contains("/") || file.contains("\\")) - ? new FileInputStream(file) - : _slTests.openResourceAsStream(file); - } - -} diff --git a/src/testcases/org/apache/poi/ss/ITestDataProvider.java b/src/testcases/org/apache/poi/ss/ITestDataProvider.java deleted file mode 100644 index e258e1a4a..000000000 --- a/src/testcases/org/apache/poi/ss/ITestDataProvider.java +++ /dev/null @@ -1,88 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss; - -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; - -/** - * Encapsulates a provider of test data for common HSSF / XSSF tests. - */ -public interface ITestDataProvider { - /** - * Provides HSSF / XSSF specific way for re-serialising a workbook - * - * @param wb the workbook to re-serialize - * @return the re-serialized workbook - */ - Workbook writeOutAndReadBack(Workbook wb); - - /** - * Provides way of loading HSSF / XSSF sample workbooks - * - * @param sampleFileName the file name to load - * @return an instance of Workbook loaded from the supplied file name - */ - Workbook openSampleWorkbook(String sampleFileName); - - /** - * Provides way of creating HSSF / XSSF workbooks - * @return an instance of Workbook - */ - Workbook createWorkbook(); - - - //************ SXSSF-specific methods ***************// - /** - * Provides way of creating a SXSSFWorkbook with a specific row access window size. - * Equivalent to createWorkbook on others. - * @return an instance of Workbook - */ - Workbook createWorkbook(int rowAccessWindowSize); - - /** - * Only matters for SXSSF - enables tracking of the column - * widths so that autosizing can work. No-op on others. - */ - void trackAllColumnsForAutosizing(Sheet sheet); - //************ End SXSSF-specific methods ***************// - - /** - * Creates the corresponding {@link FormulaEvaluator} for the - * type of Workbook handled by this Provider. - * - * @param wb The workbook to base the formula evaluator on. - * @return A new instance of a matching type of formula evaluator. - */ - FormulaEvaluator createFormulaEvaluator(Workbook wb); - - /** - * Opens a sample file from the standard HSSF test data directory - * - * @return an open InputStream for the specified sample file - */ - byte[] getTestDataFileContent(String fileName); - - SpreadsheetVersion getSpreadsheetVersion(); - - /** - * @return "xls" or "xlsx" - */ - String getStandardFileNameExtension(); -} diff --git a/src/testcases/org/apache/poi/ss/TestSpreadsheetVersion.java b/src/testcases/org/apache/poi/ss/TestSpreadsheetVersion.java deleted file mode 100644 index 93b549eee..000000000 --- a/src/testcases/org/apache/poi/ss/TestSpreadsheetVersion.java +++ /dev/null @@ -1,50 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss; - -import junit.framework.TestCase; - -/** - * Check that all enum values are properly set - * - * @author Yegor Kozlov - */ -public final class TestSpreadsheetVersion extends TestCase { - - public void testExcel97(){ - SpreadsheetVersion v = SpreadsheetVersion.EXCEL97; - assertEquals(1 << 8, v.getMaxColumns()); - assertEquals(v.getMaxColumns() - 1, v.getLastColumnIndex()); - assertEquals(1 << 16, v.getMaxRows()); - assertEquals(v.getMaxRows() - 1, v.getLastRowIndex()); - assertEquals(30, v.getMaxFunctionArgs()); - assertEquals(3, v.getMaxConditionalFormats()); - assertEquals("IV", v.getLastColumnName()); - } - - public void testExcel2007(){ - SpreadsheetVersion v = SpreadsheetVersion.EXCEL2007; - assertEquals(1 << 14, v.getMaxColumns()); - assertEquals(v.getMaxColumns() - 1, v.getLastColumnIndex()); - assertEquals(1 << 20, v.getMaxRows()); - assertEquals(v.getMaxRows() - 1, v.getLastRowIndex()); - assertEquals(255, v.getMaxFunctionArgs()); - assertEquals(Integer.MAX_VALUE, v.getMaxConditionalFormats()); - assertEquals("XFD", v.getLastColumnName()); - } -} diff --git a/src/testcases/org/apache/poi/ss/format/CellFormatTestBase.java b/src/testcases/org/apache/poi/ss/format/CellFormatTestBase.java deleted file mode 100644 index d28ac8892..000000000 --- a/src/testcases/org/apache/poi/ss/format/CellFormatTestBase.java +++ /dev/null @@ -1,311 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.format; - -import static java.awt.Color.BLACK; -import static java.awt.Color.BLUE; -import static java.awt.Color.CYAN; -import static java.awt.Color.GREEN; -import static java.awt.Color.MAGENTA; -import static java.awt.Color.ORANGE; -import static java.awt.Color.RED; -import static java.awt.Color.WHITE; -import static java.awt.Color.YELLOW; -import static org.junit.Assert.assertEquals; - -import java.awt.Color; -import java.io.IOException; -import java.util.Arrays; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; -import java.util.TreeSet; - -import javax.swing.JLabel; - -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Row.MissingCellPolicy; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.util.LocaleUtil; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; - -/** - * This class is a base class for spreadsheet-based tests, such as are used for - * cell formatting. This reads tests from the spreadsheet, as well as reading - * flags that can be used to paramterize these tests. - *

    - * Each test has four parts: The expected result (column A), the format string - * (column B), the value to format (column C), and a comma-separated list of - * categores that this test falls in. Normally all tests are run, but if the - * flag "Categories" is not empty, only tests that have at least one category - * listed in "Categories" are run. - */ -public class CellFormatTestBase { - private static final POILogger logger = POILogFactory.getLogger(CellFormatTestBase.class); - - private final ITestDataProvider _testDataProvider; - - protected Workbook workbook; - - private String testFile; - private Map testFlags; - private boolean tryAllColors; - private JLabel label; - - private static final String[] COLOR_NAMES = - {"Black", "Red", "Green", "Blue", "Yellow", "Cyan", "Magenta", - "White"}; - private static final Color[] COLORS = - {BLACK, RED, GREEN, BLUE, YELLOW, CYAN, MAGENTA, WHITE}; - - public static final Color TEST_COLOR = ORANGE.darker(); - - protected CellFormatTestBase(ITestDataProvider testDataProvider) { - _testDataProvider = testDataProvider; - } - - abstract static class CellValue { - abstract Object getValue(Cell cell); - - Color getColor(Cell cell) { - return TEST_COLOR; - } - - void equivalent(String expected, String actual, CellFormatPart format) { - assertEquals("format \"" + format + "\"", '"' + expected + '"', - '"' + actual + '"'); - } - } - - protected void runFormatTests(String workbookName, CellValue valueGetter) - throws IOException { - - openWorkbook(workbookName); - - readFlags(workbook); - - Set runCategories = new TreeSet( - String.CASE_INSENSITIVE_ORDER); - String runCategoryList = flagString("Categories", ""); - if (runCategoryList != null) { - runCategories.addAll(Arrays.asList(runCategoryList.split( - "\\s*,\\s*"))); - runCategories.remove(""); // this can be found and means nothing - } - - Sheet sheet = workbook.getSheet("Tests"); - Iterator rowIter = sheet.rowIterator(); - // Skip the header row - rowIter.next(); - while (rowIter.hasNext()) { - Row row = rowIter.next(); - if (row == null) continue; - String expectedText = row.getCell(0).getStringCellValue(); - String format = row.getCell(1).getStringCellValue(); - Cell value = row.getCell(2); - String testCategoryList = row.getCell(3).getStringCellValue(); - boolean byCategory = runByCategory(runCategories, testCategoryList); - if ((expectedText.length() > 0 || format.length() > 0) && byCategory) { - tryFormat(row.getRowNum(), expectedText, format, valueGetter, value); - } - } - } - - /** - * Open a given workbook. - * - * @param workbookName The workbook name. This is presumed to live in the - * "spreadsheets" directory under the directory named in - * the Java property "POI.testdata.path". - * - * @throws IOException - */ - protected void openWorkbook(String workbookName) - throws IOException { - workbook = _testDataProvider.openSampleWorkbook(workbookName); - workbook.setMissingCellPolicy(MissingCellPolicy.CREATE_NULL_AS_BLANK); - testFile = workbookName; - } - - /** - * Read the flags from the workbook. Flags are on the sheet named "Flags", - * and consist of names in column A and values in column B. These are put - * into a map that can be queried later. - * - * @param wb The workbook to look in. - */ - private void readFlags(Workbook wb) { - Sheet flagSheet = wb.getSheet("Flags"); - testFlags = new TreeMap(String.CASE_INSENSITIVE_ORDER); - if (flagSheet != null) { - int end = flagSheet.getLastRowNum(); - // Skip the header row, therefore "+ 1" - for (int r = flagSheet.getFirstRowNum() + 1; r <= end; r++) { - Row row = flagSheet.getRow(r); - if (row == null) - continue; - String flagName = row.getCell(0).getStringCellValue(); - String flagValue = row.getCell(1).getStringCellValue(); - if (flagName.length() > 0) { - testFlags.put(flagName, flagValue); - } - } - } - - tryAllColors = flagBoolean("AllColors", true); - } - - /** - * Returns true if any of the categories for this run are contained - * in the test's listed categories. - * - * @param categories The categories of tests to be run. If this is - * empty, then all tests will be run. - * @param testCategories The categories that this test is in. This is a - * comma-separated list. If any tests in - * this list are in categories, the test will - * be run. - * - * @return true if the test should be run. - */ - private boolean runByCategory(Set categories, - String testCategories) { - - if (categories.isEmpty()) - return true; - // If there are specified categories, find out if this has one of them - for (String category : testCategories.split("\\s*,\\s*")) { - if (categories.contains(category)) { - return true; - } - } - return false; - } - - private void tryFormat(int row, String expectedText, String desc, - CellValue getter, Cell cell) { - - Object value = getter.getValue(cell); - Color testColor = getter.getColor(cell); - if (testColor == null) - testColor = TEST_COLOR; - - if (label == null) - label = new JLabel(); - label.setForeground(testColor); - label.setText("xyzzy"); - - logger.log(POILogger.INFO, String.format(LocaleUtil.getUserLocale(), - "Row %d: \"%s\" -> \"%s\": expected \"%s\"", - row + 1, String.valueOf(value), desc, expectedText)); - String actualText = tryColor(desc, null, getter, value, expectedText, - testColor); - logger.log(POILogger.INFO, String.format(LocaleUtil.getUserLocale(), - ", actual \"%s\")%n", actualText)); - - if (tryAllColors && testColor != TEST_COLOR) { - for (int i = 0; i < COLOR_NAMES.length; i++) { - tryColor(desc, COLOR_NAMES[i], getter, value, expectedText, COLORS[i]); - } - } - } - - private String tryColor(String desc, String cname, CellValue getter, - Object value, String expectedText, Color expectedColor) { - - if (cname != null) - desc = "[" + cname + "]" + desc; - Color origColor = label.getForeground(); - CellFormatPart format = new CellFormatPart(desc); - if (!format.apply(label, value).applies) { - // If this doesn't apply, no color change is expected - expectedColor = origColor; - } - - String actualText = label.getText(); - Color actualColor = label.getForeground(); - getter.equivalent(expectedText, actualText, format); - assertEquals(cname == null ? "no color" : "color " + cname, - expectedColor, actualColor); - return actualText; - } - - /** - * Returns the value for the given flag. The flag has the value of - * true if the text value is "true", "yes", or - * "on" (ignoring case). - * - * @param flagName The name of the flag to fetch. - * @param expected The value for the flag that is expected when the tests - * are run for a full test. If the current value is not the - * expected one, you will get a warning in the test output. - * This is so that you do not accidentally leave a flag set - * to a value that prevents running some tests, thereby - * letting you accidentally release code that is not fully - * tested. - * - * @return The value for the flag. - */ - protected boolean flagBoolean(String flagName, boolean expected) { - String value = testFlags.get(flagName); - boolean isSet; - if (value == null) - isSet = false; - else { - isSet = value.equalsIgnoreCase("true") || value.equalsIgnoreCase( - "yes") || value.equalsIgnoreCase("on"); - } - warnIfUnexpected(flagName, expected, isSet); - return isSet; - } - - /** - * Returns the value for the given flag. - * - * @param flagName The name of the flag to fetch. - * @param expected The value for the flag that is expected when the tests - * are run for a full test. If the current value is not the - * expected one, you will get a warning in the test output. - * This is so that you do not accidentally leave a flag set - * to a value that prevents running some tests, thereby - * letting you accidentally release code that is not fully - * tested. - * - * @return The value for the flag. - */ - protected String flagString(String flagName, String expected) { - String value = testFlags.get(flagName); - if (value == null) - value = ""; - warnIfUnexpected(flagName, expected, value); - return value; - } - - private void warnIfUnexpected(String flagName, Object expected, - Object actual) { - if (!actual.equals(expected)) { - System.err.println( - "WARNING: " + testFile + ": " + "Flag " + flagName + - " = \"" + actual + "\" [not \"" + expected + "\"]"); - } - } -} diff --git a/src/testcases/org/apache/poi/ss/format/TestCellFormat.java b/src/testcases/org/apache/poi/ss/format/TestCellFormat.java deleted file mode 100644 index 5d19c633f..000000000 --- a/src/testcases/org/apache/poi/ss/format/TestCellFormat.java +++ /dev/null @@ -1,1014 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.format; - -import static org.junit.Assert.*; - -import java.io.IOException; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Locale; -import java.util.TimeZone; - -import javax.swing.JLabel; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.DateUtil; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.util.LocaleUtil; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; - -public class TestCellFormat { - - private static TimeZone userTimeZone; - - @BeforeClass - public static void setTimeZone() { - userTimeZone = LocaleUtil.getUserTimeZone(); - LocaleUtil.setUserTimeZone(TimeZone.getTimeZone("CET")); - LocaleUtil.setUserLocale(Locale.US); - } - - @AfterClass - public static void resetTimeZone() { - LocaleUtil.setUserTimeZone(userTimeZone); - LocaleUtil.setUserLocale(Locale.ROOT); - } - - - private static final String _255_POUND_SIGNS; - static { - StringBuilder sb = new StringBuilder(); - for (int i = 1; i <= 255; i++) { - sb.append('#'); - } - _255_POUND_SIGNS = sb.toString(); - } - - @Test - public void testSome() { - JLabel l = new JLabel(); - CellFormat fmt = CellFormat.getInstance( - "\"$\"#,##0.00_);[Red]\\(\"$\"#,##0.00\\)"); - fmt.apply(l, 1.1); - } - - @Test - public void testPositiveFormatHasOnePart() { - CellFormat fmt = CellFormat.getInstance("0.00"); - CellFormatResult result = fmt.apply(12.345); - assertEquals("12.35", result.text); - } - - @Test - public void testNegativeFormatHasOnePart() { - CellFormat fmt = CellFormat.getInstance("0.00"); - CellFormatResult result = fmt.apply(-12.345); - assertEquals("-12.35", result.text); - } - - @Test - public void testZeroFormatHasOnePart() { - CellFormat fmt = CellFormat.getInstance("0.00"); - CellFormatResult result = fmt.apply(0.0); - assertEquals("0.00", result.text); - } - - @Test - public void testPositiveFormatHasPosAndNegParts() { - CellFormat fmt = CellFormat.getInstance("0.00;-0.00"); - CellFormatResult result = fmt.apply(12.345); - assertEquals("12.35", result.text); - } - - @Test - public void testNegativeFormatHasPosAndNegParts() { - CellFormat fmt = CellFormat.getInstance("0.00;-0.00"); - CellFormatResult result = fmt.apply(-12.345); - assertEquals("-12.35", result.text); - } - - @Test - public void testNegativeFormatHasPosAndNegParts2() { - CellFormat fmt = CellFormat.getInstance("0.00;(0.00)"); - CellFormatResult result = fmt.apply(-12.345); - assertEquals("(12.35)", result.text); - } - - @Test - public void testZeroFormatHasPosAndNegParts() { - CellFormat fmt = CellFormat.getInstance("0.00;-0.00"); - CellFormatResult result = fmt.apply(0.0); - assertEquals("0.00", result.text); - } - - @Test - public void testFormatWithThreeSections() { - CellFormat fmt = CellFormat.getInstance("0.00;-0.00;-"); - - assertEquals("12.35", fmt.apply(12.345).text); - assertEquals("-12.35", fmt.apply(-12.345).text); - assertEquals("-", fmt.apply(0.0).text); - assertEquals("abc", fmt.apply("abc").text); - } - - @Test - public void testFormatWithFourSections() { - CellFormat fmt = CellFormat.getInstance("0.00;-0.00;-; @ "); - - assertEquals("12.35", fmt.apply(12.345).text); - assertEquals("-12.35", fmt.apply(-12.345).text); - assertEquals("-", fmt.apply(0.0).text); - assertEquals(" abc ", fmt.apply("abc").text); - } - - @Test - public void testApplyCellForGeneralFormat() throws Exception { - - // Create a workbook, row and cell to test with - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell0 = row.createCell(0); - Cell cell1 = row.createCell(1); - Cell cell2 = row.createCell(2); - Cell cell3 = row.createCell(3); - Cell cell4 = row.createCell(4); - - CellFormat cf = CellFormat.getInstance("General"); - - // case CellType.BLANK - CellFormatResult result0 = cf.apply(cell0); - assertEquals("", result0.text); - - // case CellType.BOOLEAN - cell1.setCellValue(true); - CellFormatResult result1 = cf.apply(cell1); - assertEquals("TRUE", result1.text); - - // case CellType.NUMERIC - cell2.setCellValue(1.23); - CellFormatResult result2 = cf.apply(cell2); - assertEquals("1.23", result2.text); - - cell3.setCellValue(123.0); - CellFormatResult result3 = cf.apply(cell3); - assertEquals("123", result3.text); - - // case CellType.STRING - cell4.setCellValue("abc"); - CellFormatResult result4 = cf.apply(cell4); - assertEquals("abc", result4.text); - - wb.close(); - } - - @Test - public void testApplyCellForAtFormat() throws Exception { - - // Create a workbook, row and cell to test with - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell0 = row.createCell(0); - Cell cell1 = row.createCell(1); - Cell cell2 = row.createCell(2); - Cell cell3 = row.createCell(3); - Cell cell4 = row.createCell(4); - - CellFormat cf = CellFormat.getInstance("@"); - - // case CellType.BLANK - CellFormatResult result0 = cf.apply(cell0); - assertEquals("", result0.text); - - // case CellType.BOOLEAN - cell1.setCellValue(true); - CellFormatResult result1 = cf.apply(cell1); - assertEquals("TRUE", result1.text); - - // case CellType.NUMERIC - cell2.setCellValue(1.23); - CellFormatResult result2 = cf.apply(cell2); - assertEquals("1.23", result2.text); - - cell3.setCellValue(123.0); - CellFormatResult result3 = cf.apply(cell3); - assertEquals("123", result3.text); - - // case CellType.STRING - cell4.setCellValue("abc"); - CellFormatResult result4 = cf.apply(cell4); - assertEquals("abc", result4.text); - - wb.close(); - } - - @Test - public void testApplyCellForDateFormat() throws Exception { - - // Create a workbook, row and cell to test with - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell0 = row.createCell(0); - Cell cell1 = row.createCell(1); - - CellFormat cf = CellFormat.getInstance("dd/mm/yyyy"); - - cell0.setCellValue(10); - CellFormatResult result0 = cf.apply(cell0); - assertEquals("10/01/1900", result0.text); - - cell1.setCellValue(-1); - CellFormatResult result1 = cf.apply(cell1); - assertEquals(_255_POUND_SIGNS, result1.text); - - wb.close(); - } - - @Test - public void testApplyCellForTimeFormat() throws Exception { - - // Create a workbook, row and cell to test with - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - - CellFormat cf = CellFormat.getInstance("hh:mm"); - - cell.setCellValue(DateUtil.convertTime("03:04:05")); - CellFormatResult result = cf.apply(cell); - assertEquals("03:04", result.text); - - wb.close(); - } - - @Test - public void testApplyCellForDateFormatAndNegativeFormat() throws Exception { - - // Create a workbook, row and cell to test with - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell0 = row.createCell(0); - Cell cell1 = row.createCell(1); - - CellFormat cf = CellFormat.getInstance("dd/mm/yyyy;(0)"); - - cell0.setCellValue(10); - CellFormatResult result0 = cf.apply(cell0); - assertEquals("10/01/1900", result0.text); - - cell1.setCellValue(-1); - CellFormatResult result1 = cf.apply(cell1); - assertEquals("(1)", result1.text); - - wb.close(); - } - - @Test - public void testApplyJLabelCellForGeneralFormat() throws Exception { - - // Create a workbook, row and cell to test with - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell0 = row.createCell(0); - Cell cell1 = row.createCell(1); - Cell cell2 = row.createCell(2); - Cell cell3 = row.createCell(3); - Cell cell4 = row.createCell(4); - - CellFormat cf = CellFormat.getInstance("General"); - - JLabel label0 = new JLabel(); - JLabel label1 = new JLabel(); - JLabel label2 = new JLabel(); - JLabel label3 = new JLabel(); - JLabel label4 = new JLabel(); - - // case CellType.BLANK - CellFormatResult result0 = cf.apply(label0, cell0); - assertEquals("", result0.text); - assertEquals("", label0.getText()); - - // case CellType.BOOLEAN - cell1.setCellValue(true); - CellFormatResult result1 = cf.apply(label1, cell1); - assertEquals("TRUE", result1.text); - assertEquals("TRUE", label1.getText()); - - // case CellType.NUMERIC - cell2.setCellValue(1.23); - CellFormatResult result2 = cf.apply(label2, cell2); - assertEquals("1.23", result2.text); - assertEquals("1.23", label2.getText()); - - cell3.setCellValue(123.0); - CellFormatResult result3 = cf.apply(label3, cell3); - assertEquals("123", result3.text); - assertEquals("123", label3.getText()); - - // case CellType.STRING - cell4.setCellValue("abc"); - CellFormatResult result4 = cf.apply(label4, cell4); - assertEquals("abc", result4.text); - assertEquals("abc", label4.getText()); - - wb.close(); - } - - @Test - public void testApplyJLabelCellForAtFormat() throws Exception { - - // Create a workbook, row and cell to test with - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell0 = row.createCell(0); - Cell cell1 = row.createCell(1); - Cell cell2 = row.createCell(2); - Cell cell3 = row.createCell(3); - Cell cell4 = row.createCell(4); - - CellFormat cf = CellFormat.getInstance("@"); - - JLabel label0 = new JLabel(); - JLabel label1 = new JLabel(); - JLabel label2 = new JLabel(); - JLabel label3 = new JLabel(); - JLabel label4 = new JLabel(); - - // case CellType.BLANK - CellFormatResult result0 = cf.apply(label0, cell0); - assertEquals("", result0.text); - assertEquals("", label0.getText()); - - // case CellType.BOOLEAN - cell1.setCellValue(true); - CellFormatResult result1 = cf.apply(label1, cell1); - assertEquals("TRUE", result1.text); - assertEquals("TRUE", label1.getText()); - - // case CellType.NUMERIC - cell2.setCellValue(1.23); - CellFormatResult result2 = cf.apply(label2, cell2); - assertEquals("1.23", result2.text); - assertEquals("1.23", label2.getText()); - - cell3.setCellValue(123.0); - CellFormatResult result3 = cf.apply(label3, cell3); - assertEquals("123", result3.text); - assertEquals("123", label3.getText()); - - // case CellType.STRING - cell4.setCellValue("abc"); - CellFormatResult result4 = cf.apply(label4, cell4); - assertEquals("abc", result4.text); - assertEquals("abc", label4.getText()); - - wb.close(); - } - - @Test - public void testApplyJLabelCellForDateFormat() throws Exception { - - // Create a workbook, row and cell to test with - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell0 = row.createCell(0); - Cell cell1 = row.createCell(1); - - CellFormat cf = CellFormat.getInstance("dd/mm/yyyy"); - - JLabel label0 = new JLabel(); - JLabel label1 = new JLabel(); - - cell0.setCellValue(10); - CellFormatResult result0 = cf.apply(label0, cell0); - assertEquals("10/01/1900", result0.text); - assertEquals("10/01/1900", label0.getText()); - - cell1.setCellValue(-1); - CellFormatResult result1 = cf.apply(label1, cell1); - assertEquals(_255_POUND_SIGNS, result1.text); - assertEquals(_255_POUND_SIGNS, label1.getText()); - - wb.close(); - } - - @Test - public void testApplyJLabelCellForTimeFormat() throws Exception { - - // Create a workbook, row and cell to test with - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - - CellFormat cf = CellFormat.getInstance("hh:mm"); - - JLabel label = new JLabel(); - - cell.setCellValue(DateUtil.convertTime("03:04:05")); - CellFormatResult result = cf.apply(label, cell); - assertEquals("03:04", result.text); - assertEquals("03:04", label.getText()); - - wb.close(); - } - - @Test - public void testApplyJLabelCellForDateFormatAndNegativeFormat() throws Exception { - - // Create a workbook, row and cell to test with - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell0 = row.createCell(0); - Cell cell1 = row.createCell(1); - - CellFormat cf = CellFormat.getInstance("dd/mm/yyyy;(0)"); - - JLabel label0 = new JLabel(); - JLabel label1 = new JLabel(); - - cell0.setCellValue(10); - CellFormatResult result0 = cf.apply(label0, cell0); - assertEquals("10/01/1900", result0.text); - assertEquals("10/01/1900", label0.getText()); - - cell1.setCellValue(-1); - CellFormatResult result1 = cf.apply(label1, cell1); - assertEquals("(1)", result1.text); - assertEquals("(1)", label1.getText()); - - wb.close(); - } - - @Test - public void testApplyFormatHasOnePartAndPartHasCondition() throws Exception { - - // Create a workbook, row and cell to test with - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - - CellFormat cf = CellFormat.getInstance("[>=100]0.00"); - - cell.setCellValue(100); - assertEquals("100.00", cf.apply(cell).text); - - cell.setCellValue(10); - assertEquals("10", cf.apply(cell).text); - - cell.setCellValue(0.123456789012345); - assertEquals("0.123456789", cf.apply(cell).text); - - cell.setCellValue(0); - assertEquals("0", cf.apply(cell).text); - - cell.setCellValue("abc"); - assertEquals("abc", cf.apply(cell).text); - - wb.close(); - } - - @Test - public void testApplyFormatHasTwoPartsFirstHasCondition() throws Exception { - - // Create a workbook, row and cell to test with - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - - CellFormat cf = CellFormat.getInstance("[>=100]0.00;0.000"); - - cell.setCellValue(100); - assertEquals("100.00", cf.apply(cell).text); - - cell.setCellValue(10); - assertEquals("10.000", cf.apply(cell).text); - - cell.setCellValue(0.123456789012345); - assertEquals("0.123", cf.apply(cell).text); - - cell.setCellValue(0); - assertEquals("0.000", cf.apply(cell).text); - - cell.setCellValue(-10); - assertEquals("-10.000", cf.apply(cell).text); - - cell.setCellValue("abc"); - assertEquals("abc", cf.apply(cell).text); - - cell.setCellValue("TRUE"); - assertEquals("TRUE", cf.apply(cell).text); - - wb.close(); - } - - @Test - public void testApplyFormatHasTwoPartsBothHaveCondition() throws Exception { - - // Create a workbook, row and cell to test with - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - - CellFormat cf = CellFormat.getInstance("[>=100]0.00;[>=10]0.000"); - - cell.setCellValue(100); - assertEquals("100.00", cf.apply(cell).text); - - cell.setCellValue(10); - assertEquals("10.000", cf.apply(cell).text); - - cell.setCellValue(0); - assertEquals(_255_POUND_SIGNS, cf.apply(cell).text); - - cell.setCellValue(-0.123456789012345); - assertEquals(_255_POUND_SIGNS, cf.apply(cell).text); - - cell.setCellValue(-10); - assertEquals(_255_POUND_SIGNS, cf.apply(cell).text); - - cell.setCellValue("abc"); - assertEquals("abc", cf.apply(cell).text); - - wb.close(); - } - - @Test - public void testApplyFormatHasThreePartsFirstHasCondition() throws Exception { - - // Create a workbook, row and cell to test with - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - - CellFormat cf = CellFormat.getInstance("[>=100]0.00;0.000;0.0000"); - - cell.setCellValue(100); - assertEquals("100.00", cf.apply(cell).text); - - cell.setCellValue(10); - assertEquals("10.0000", cf.apply(cell).text); - - cell.setCellValue(0.123456789012345); - assertEquals("0.1235", cf.apply(cell).text); - - cell.setCellValue(0); - assertEquals("0.0000", cf.apply(cell).text); - - // Second format part ('0.000') is used for negative numbers - // so result does not have a minus sign - cell.setCellValue(-10); - assertEquals("10.000", cf.apply(cell).text); - - cell.setCellValue("abc"); - assertEquals("abc", cf.apply(cell).text); - - wb.close(); - } - - @Test - public void testApplyFormatHasThreePartsFirstTwoHaveCondition() throws Exception { - - // Create a workbook, row and cell to test with - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - - CellFormat cf = CellFormat.getInstance("[>=100]0.00;[>=10]0.000;0.0000"); - - cell.setCellValue(100); - assertEquals("100.00", cf.apply(cell).text); - - cell.setCellValue(10); - assertEquals("10.000", cf.apply(cell).text); - - cell.setCellValue(0); - assertEquals("0.0000", cf.apply(cell).text); - - cell.setCellValue(-10); - assertEquals("-10.0000", cf.apply(cell).text); - - cell.setCellValue("abc"); - assertEquals("abc", cf.apply(cell).text); - - wb.close(); - } - - @Test - public void testApplyFormatHasThreePartsFirstIsDateFirstTwoHaveCondition() throws Exception { - - // Create a workbook, row and cell to test with - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - - CellFormat cf = CellFormat.getInstance("[>=100]0.00;[>=10]dd/mm/yyyy;0.0"); - - cell.setCellValue(100); - assertEquals("100.00", cf.apply(cell).text); - - cell.setCellValue(10); - assertEquals("10/01/1900", cf.apply(cell).text); - - cell.setCellValue(0); - assertEquals("0.0", cf.apply(cell).text); - - cell.setCellValue(-10); - assertEquals("-10.0", cf.apply(cell).text); - - cell.setCellValue("abc"); - assertEquals("abc", cf.apply(cell).text); - - wb.close(); - } - - @Test - public void testApplyFormatHasTwoPartsFirstHasConditionSecondIsGeneral() throws Exception { - - // Create a workbook, row and cell to test with - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - - CellFormat cf = CellFormat.getInstance("[>=100]0.00;General"); - - cell.setCellValue(100); - assertEquals("100.00", cf.apply(cell).text); - - cell.setCellValue(10); - assertEquals("10", cf.apply(cell).text); - - cell.setCellValue(0); - assertEquals("0", cf.apply(cell).text); - - cell.setCellValue(-10); - assertEquals("-10", cf.apply(cell).text); - - cell.setCellValue("abc"); - assertEquals("abc", cf.apply(cell).text); - - wb.close(); - } - - @Test - public void testApplyFormatHasThreePartsFirstTwoHaveConditionThirdIsGeneral() throws Exception { - - // Create a workbook, row and cell to test with - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - - CellFormat cf = CellFormat.getInstance("[>=100]0.00;[>=10]0.000;General"); - - cell.setCellValue(100); - assertEquals("100.00", cf.apply(cell).text); - - cell.setCellValue(10); - assertEquals("10.000", cf.apply(cell).text); - - cell.setCellValue(0); - assertEquals("0", cf.apply(cell).text); - - cell.setCellValue(-10); - assertEquals("-10", cf.apply(cell).text); - - cell.setCellValue("abc"); - assertEquals("abc", cf.apply(cell).text); - - wb.close(); - } - - @Test - public void testApplyFormatHasFourPartsFirstHasCondition() throws Exception { - - // Create a workbook, row and cell to test with - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - - CellFormat cf = CellFormat.getInstance("[>=100]0.00;0.000;0.0000;~~@~~"); - - cell.setCellValue(100); - assertEquals("100.00", cf.apply(cell).text); - - cell.setCellValue(10); - assertEquals("10.0000", cf.apply(cell).text); - - cell.setCellValue(0.123456789012345); - assertEquals("0.1235", cf.apply(cell).text); - - cell.setCellValue(0); - assertEquals("0.0000", cf.apply(cell).text); - - // Second format part ('0.000') is used for negative numbers - // so result does not have a minus sign - cell.setCellValue(-10); - assertEquals("10.000", cf.apply(cell).text); - - cell.setCellValue("abc"); - assertEquals("~~abc~~", cf.apply(cell).text); - - wb.close(); - } - - @Test - public void testApplyFormatHasFourPartsSecondHasCondition() throws Exception { - - // Create a workbook, row and cell to test with - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - - CellFormat cf = CellFormat.getInstance("0.00;[>=100]0.000;0.0000;~~@~~"); - - cell.setCellValue(100); - assertEquals("100.00", cf.apply(cell).text); - - cell.setCellValue(10); - assertEquals("10.00", cf.apply(cell).text); - - cell.setCellValue(0.123456789012345); - assertEquals("0.12", cf.apply(cell).text); - - cell.setCellValue(0); - assertEquals("0.0000", cf.apply(cell).text); - - cell.setCellValue(-10); - assertEquals("-10.0000", cf.apply(cell).text); - - cell.setCellValue("abc"); - assertEquals("~~abc~~", cf.apply(cell).text); - - cell.setCellValue(true); - assertEquals("~~TRUE~~", cf.apply(cell).text); - - wb.close(); - } - - @Test - public void testApplyFormatHasFourPartsFirstTwoHaveCondition() throws Exception { - - // Create a workbook, row and cell to test with - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - - CellFormat cf = CellFormat.getInstance("[>=100]0.00;[>=10]0.000;0.0000;~~@~~"); - - cell.setCellValue(100); - assertEquals("100.00", cf.apply(cell).text); - - cell.setCellValue(10); - assertEquals("10.000", cf.apply(cell).text); - - cell.setCellValue(0); - assertEquals("0.0000", cf.apply(cell).text); - - cell.setCellValue(-10); - assertEquals("-10.0000", cf.apply(cell).text); - - cell.setCellValue("abc"); - assertEquals("~~abc~~", cf.apply(cell).text); - - cell.setCellValue(true); - assertEquals("~~TRUE~~", cf.apply(cell).text); - - wb.close(); - } - - /* - * Test apply(Object value) with a number as parameter - */ - @Test - public void testApplyObjectNumber() { - - CellFormat cf1 = CellFormat.getInstance("0.000"); - - assertEquals("1.235", cf1.apply(1.2345).text); - assertEquals("-1.235", cf1.apply(-1.2345).text); - - CellFormat cf2 = CellFormat.getInstance("0.000;(0.000)"); - - assertEquals("1.235", cf2.apply(1.2345).text); - assertEquals("(1.235)", cf2.apply(-1.2345).text); - - CellFormat cf3 = CellFormat.getInstance("[>1]0.000;0.0000"); - - assertEquals("1.235", cf3.apply(1.2345).text); - assertEquals("-1.2345", cf3.apply(-1.2345).text); - - CellFormat cf4 = CellFormat.getInstance("0.000;[>1]0.0000"); - - assertEquals("1.235", cf4.apply(1.2345).text); - assertEquals(_255_POUND_SIGNS, cf4.apply(-1.2345).text); - - } - - /* - * Test apply(Object value) with a Date as parameter - */ - @Test - public void testApplyObjectDate() throws ParseException { - - CellFormat cf1 = CellFormat.getInstance("m/d/yyyy"); - Date date1 = new SimpleDateFormat("M/d/y", Locale.ROOT).parse("01/11/2012"); - assertEquals("1/11/2012", cf1.apply(date1).text); - - } - - @Test - public void testApplyCellForDateFormatWithConditions() throws Exception { - - // Create a workbook, row and cell to test with - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - - CellFormat cf = CellFormat.getInstance("[<1]hh:mm:ss AM/PM;[>=1]dd/mm/yyyy hh:mm:ss AM/PM;General"); - - cell.setCellValue(0.5); - assertEquals("12:00:00 PM", cf.apply(cell).text); - - cell.setCellValue(1.5); - assertEquals("01/01/1900 12:00:00 PM", cf.apply(cell).text); - - cell.setCellValue(-1); - assertEquals(_255_POUND_SIGNS, cf.apply(cell).text); - - wb.close(); - } - - /* - * Test apply(Object value) with a String as parameter - */ - @Test - public void testApplyObjectString() { - - CellFormat cf = CellFormat.getInstance("0.00"); - - assertEquals("abc", cf.apply("abc").text); - - } - - /* - * Test apply(Object value) with a Boolean as parameter - */ - @Test - public void testApplyObjectBoolean() { - - CellFormat cf1 = CellFormat.getInstance("0"); - CellFormat cf2 = CellFormat.getInstance("General"); - CellFormat cf3 = CellFormat.getInstance("@"); - - assertEquals("TRUE", cf1.apply(true).text); - assertEquals("FALSE", cf2.apply(false).text); - assertEquals("TRUE", cf3.apply(true).text); - - } - - @Test - public void testSimpleFractionFormat() throws IOException { - CellFormat cf1 = CellFormat.getInstance("# ?/?"); - // Create a workbook, row and cell to test with - Workbook wb = new HSSFWorkbook(); - try { - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - cell.setCellValue(123456.6); - //System.out.println(cf1.apply(cell).text); - assertEquals("123456 3/5", cf1.apply(cell).text); - } finally { - wb.close(); - } - } - - @Test - public void testAccountingFormats() throws IOException { - char pound = '\u00A3'; - char euro = '\u20AC'; - - // Accounting -> 0 decimal places, default currency symbol - String formatDft = "_-\"$\"* #,##0_-;\\-\"$\"* #,##0_-;_-\"$\"* \"-\"_-;_-@_-"; - // Accounting -> 0 decimal places, US currency symbol - String formatUS = "_-[$$-409]* #,##0_ ;_-[$$-409]* -#,##0 ;_-[$$-409]* \"-\"_-;_-@_-"; - // Accounting -> 0 decimal places, UK currency symbol - String formatUK = "_-[$"+pound+"-809]* #,##0_-;\\-[$"+pound+"-809]* #,##0_-;_-[$"+pound+"-809]* \"-\"??_-;_-@_-"; - // French style accounting, euro sign comes after not before - String formatFR = "_-#,##0* [$"+euro+"-40C]_-;\\-#,##0* [$"+euro+"-40C]_-;_-\"-\"??* [$"+euro+"-40C] _-;_-@_-"; - - // Has +ve, -ve and zero rules - CellFormat cfDft = CellFormat.getInstance(formatDft); - CellFormat cfUS = CellFormat.getInstance(formatUS); - CellFormat cfUK = CellFormat.getInstance(formatUK); - CellFormat cfFR = CellFormat.getInstance(formatFR); - - // For +ve numbers, should be Space + currency symbol + spaces + whole number with commas + space - // (Except French, which is mostly reversed...) - assertEquals(" $ 12 ", cfDft.apply(Double.valueOf(12.33)).text); - assertEquals(" $ 12 ", cfUS.apply(Double.valueOf(12.33)).text); - assertEquals(" "+pound+" 12 ", cfUK.apply(Double.valueOf(12.33)).text); - assertEquals(" 12 "+euro+" ", cfFR.apply(Double.valueOf(12.33)).text); - - assertEquals(" $ 16,789 ", cfDft.apply(Double.valueOf(16789.2)).text); - assertEquals(" $ 16,789 ", cfUS.apply(Double.valueOf(16789.2)).text); - assertEquals(" "+pound+" 16,789 ", cfUK.apply(Double.valueOf(16789.2)).text); - assertEquals(" 16,789 "+euro+" ", cfFR.apply(Double.valueOf(16789.2)).text); - - // For -ve numbers, gets a bit more complicated... - assertEquals("-$ 12 ", cfDft.apply(Double.valueOf(-12.33)).text); - assertEquals(" $ -12 ", cfUS.apply(Double.valueOf(-12.33)).text); - assertEquals("-"+pound+" 12 ", cfUK.apply(Double.valueOf(-12.33)).text); - assertEquals("-12 "+euro+" ", cfFR.apply(Double.valueOf(-12.33)).text); - - assertEquals("-$ 16,789 ", cfDft.apply(Double.valueOf(-16789.2)).text); - assertEquals(" $ -16,789 ", cfUS.apply(Double.valueOf(-16789.2)).text); - assertEquals("-"+pound+" 16,789 ", cfUK.apply(Double.valueOf(-16789.2)).text); - assertEquals("-16,789 "+euro+" ", cfFR.apply(Double.valueOf(-16789.2)).text); - - // For zero, should be Space + currency symbol + spaces + Minus + spaces - assertEquals(" $ - ", cfDft.apply(Double.valueOf(0)).text); - // TODO Fix the exception this incorrectly triggers - //assertEquals(" $ - ", cfUS.apply(Double.valueOf(0)).text); - // TODO Fix these to not have an incorrect bonus 0 on the end - //assertEquals(" "+pound+" - ", cfUK.apply(Double.valueOf(0)).text); - //assertEquals(" - "+euro+" ", cfFR.apply(Double.valueOf(0)).text); - } - - @Test - public void testThreePartComplexFormat1() { - // verify a rather complex format found e.g. in http://wahl.land-oberoesterreich.gv.at/Downloads/bp10.xls - CellFormatPart posPart = new CellFormatPart("[$-F400]h:mm:ss\\ AM/PM"); - assertNotNull(posPart); - assertEquals("1:00:12 AM", posPart.apply(new Date(12345)).text); - - CellFormatPart negPart = new CellFormatPart("[$-F40]h:mm:ss\\ AM/PM"); - assertNotNull(negPart); - assertEquals("1:00:12 AM", posPart.apply(new Date(12345)).text); - - //assertNotNull(new CellFormatPart("_-* \"\"??_-;_-@_-")); - - CellFormat instance = CellFormat.getInstance("[$-F400]h:mm:ss\\ AM/PM;[$-F40]h:mm:ss\\ AM/PM;_-* \"\"??_-;_-@_-"); - assertNotNull(instance); - assertEquals("1:00:12 AM", instance.apply(new Date(12345)).text); - } - - @Test - public void testThreePartComplexFormat2() { - // verify a rather complex format found e.g. in http://wahl.land-oberoesterreich.gv.at/Downloads/bp10.xls - CellFormatPart posPart = new CellFormatPart("dd/mm/yyyy"); - assertNotNull(posPart); - assertEquals("01/01/1970", posPart.apply(new Date(12345)).text); - - CellFormatPart negPart = new CellFormatPart("dd/mm/yyyy"); - assertNotNull(negPart); - assertEquals("01/01/1970", posPart.apply(new Date(12345)).text); - - //assertNotNull(new CellFormatPart("_-* \"\"??_-;_-@_-")); - - CellFormat instance = CellFormat.getInstance("dd/mm/yyyy;dd/mm/yyyy;_-* \"\"??_-;_-@_-"); - assertNotNull(instance); - assertEquals("01/01/1970", instance.apply(new Date(12345)).text); - } -} \ No newline at end of file diff --git a/src/testcases/org/apache/poi/ss/format/TestCellFormatCondition.java b/src/testcases/org/apache/poi/ss/format/TestCellFormatCondition.java deleted file mode 100644 index 1a56b824a..000000000 --- a/src/testcases/org/apache/poi/ss/format/TestCellFormatCondition.java +++ /dev/null @@ -1,63 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.format; - -import junit.framework.TestCase; - -public class TestCellFormatCondition extends TestCase { - public void testSVConditions() { - CellFormatCondition lt = CellFormatCondition.getInstance("<", "1.5"); - assertTrue(lt.pass(1.4)); - assertFalse(lt.pass(1.5)); - assertFalse(lt.pass(1.6)); - - CellFormatCondition le = CellFormatCondition.getInstance("<=", "1.5"); - assertTrue(le.pass(1.4)); - assertTrue(le.pass(1.5)); - assertFalse(le.pass(1.6)); - - CellFormatCondition gt = CellFormatCondition.getInstance(">", "1.5"); - assertFalse(gt.pass(1.4)); - assertFalse(gt.pass(1.5)); - assertTrue(gt.pass(1.6)); - - CellFormatCondition ge = CellFormatCondition.getInstance(">=", "1.5"); - assertFalse(ge.pass(1.4)); - assertTrue(ge.pass(1.5)); - assertTrue(ge.pass(1.6)); - - CellFormatCondition eqs = CellFormatCondition.getInstance("=", "1.5"); - assertFalse(eqs.pass(1.4)); - assertTrue(eqs.pass(1.5)); - assertFalse(eqs.pass(1.6)); - - CellFormatCondition eql = CellFormatCondition.getInstance("==", "1.5"); - assertFalse(eql.pass(1.4)); - assertTrue(eql.pass(1.5)); - assertFalse(eql.pass(1.6)); - - CellFormatCondition neo = CellFormatCondition.getInstance("<>", "1.5"); - assertTrue(neo.pass(1.4)); - assertFalse(neo.pass(1.5)); - assertTrue(neo.pass(1.6)); - - CellFormatCondition nen = CellFormatCondition.getInstance("!=", "1.5"); - assertTrue(nen.pass(1.4)); - assertFalse(nen.pass(1.5)); - assertTrue(nen.pass(1.6)); - } -} \ No newline at end of file diff --git a/src/testcases/org/apache/poi/ss/format/TestCellFormatResult.java b/src/testcases/org/apache/poi/ss/format/TestCellFormatResult.java deleted file mode 100644 index 6e77df248..000000000 --- a/src/testcases/org/apache/poi/ss/format/TestCellFormatResult.java +++ /dev/null @@ -1,37 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.format; - -import java.awt.Color; - -import junit.framework.TestCase; - -public class TestCellFormatResult extends TestCase { - - public void testNullTextRaisesException() { - try { - final boolean applies = true; - final String text = null; - final Color textColor = Color.BLACK; - final CellFormatResult result = new CellFormatResult(applies, text, textColor); - fail("Cannot initialize CellFormatResult with null text parameter"); - } - catch (IllegalArgumentException e) { - //Expected - } - } -} \ No newline at end of file diff --git a/src/testcases/org/apache/poi/ss/formula/AllSSFormulaTests.java b/src/testcases/org/apache/poi/ss/formula/AllSSFormulaTests.java deleted file mode 100644 index 59631017d..000000000 --- a/src/testcases/org/apache/poi/ss/formula/AllSSFormulaTests.java +++ /dev/null @@ -1,35 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula; - -import org.apache.poi.ss.formula.eval.forked.TestForkedEvaluator; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -/** - * Test suite for org.apache.poi.ss.formula - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestCellCacheEntry.class, - TestEvaluationCache.class, - TestWorkbookEvaluator.class, - TestForkedEvaluator.class -}) -public class AllSSFormulaTests { -} diff --git a/src/testcases/org/apache/poi/ss/formula/BaseTestExternalFunctions.java b/src/testcases/org/apache/poi/ss/formula/BaseTestExternalFunctions.java deleted file mode 100644 index 764201594..000000000 --- a/src/testcases/org/apache/poi/ss/formula/BaseTestExternalFunctions.java +++ /dev/null @@ -1,164 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.formula; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.IOException; - -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NotImplementedException; -import org.apache.poi.ss.formula.eval.NotImplementedFunctionException; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.ss.formula.functions.FreeRefFunction; -import org.apache.poi.ss.formula.udf.DefaultUDFFinder; -import org.apache.poi.ss.formula.udf.UDFFinder; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.junit.Test; - -/** - * Test setting / evaluating of Analysis Toolpack and user-defined functions - */ -public abstract class BaseTestExternalFunctions { - // define two custom user-defined functions - private static class MyFunc implements FreeRefFunction { - public MyFunc() { - // - } - - @Override - public ValueEval evaluate(ValueEval[] args, OperationEvaluationContext ec) { - if (args.length != 1 || !(args[0] instanceof StringEval)) { - return ErrorEval.VALUE_INVALID; - } - StringEval input = (StringEval) args[0]; - return new StringEval(input.getStringValue() + "abc"); - } - } - - private static class MyFunc2 implements FreeRefFunction { - public MyFunc2() { - // - } - - @Override - public ValueEval evaluate(ValueEval[] args, OperationEvaluationContext ec) { - if (args.length != 1 || !(args[0] instanceof StringEval)) { - return ErrorEval.VALUE_INVALID; - } - StringEval input = (StringEval) args[0]; - return new StringEval(input.getStringValue() + "abc2"); - } - } - - /** - * register the two test UDFs in a UDF finder, to be passed to the workbook - */ - private static UDFFinder customToolpack = new DefaultUDFFinder( - new String[] { "myFunc", "myFunc2"}, - new FreeRefFunction[] { new MyFunc(), new MyFunc2()} - ); - - - private final ITestDataProvider _testDataProvider; - private final String atpFile; - - /** - * @param testDataProvider an object that provides test data in HSSF / XSSF specific way - */ - protected BaseTestExternalFunctions(ITestDataProvider testDataProvider, String atpFile) { - _testDataProvider = testDataProvider; - this.atpFile = atpFile; - } - - @Test - public void testExternalFunctions() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - - Sheet sh = wb.createSheet(); - - Cell cell1 = sh.createRow(0).createCell(0); - // functions from the Excel Analysis Toolpack - cell1.setCellFormula("ISODD(1)+ISEVEN(2)"); - assertEquals("ISODD(1)+ISEVEN(2)", cell1.getCellFormula()); - - Cell cell2 = sh.createRow(1).createCell(0); - // unregistered functions are parseable and renderable, but may not be evaluateable - cell2.setCellFormula("MYFUNC(\"B1\")"); - try { - evaluator.evaluate(cell2); - fail("Expected NotImplementedFunctionException/NotImplementedException"); - } catch (final NotImplementedException e) { - assertTrue(e.getCause() instanceof NotImplementedFunctionException); - // Alternatively, a future implementation of evaluate could return #NAME? error to align behavior with Excel - // assertEquals(ErrorEval.NAME_INVALID, ErrorEval.valueOf(evaluator.evaluate(cell2).getErrorValue())); - } - - wb.addToolPack(customToolpack); - - cell2.setCellFormula("MYFUNC(\"B1\")"); - assertEquals("MYFUNC(\"B1\")", cell2.getCellFormula()); - - Cell cell3 = sh.createRow(2).createCell(0); - cell3.setCellFormula("MYFUNC2(\"C1\")&\"-\"&A2"); //where A2 is defined above - assertEquals("MYFUNC2(\"C1\")&\"-\"&A2", cell3.getCellFormula()); - - assertEquals(2.0, evaluator.evaluate(cell1).getNumberValue(), 0); - assertEquals("B1abc", evaluator.evaluate(cell2).getStringValue()); - assertEquals("C1abc2-B1abc", evaluator.evaluate(cell3).getStringValue()); - - wb.close(); - } - - /** - * test invoking saved ATP functions - * - * @param testFile either atp.xls or atp.xlsx - */ - @Test - public void baseTestInvokeATP() throws IOException { - Workbook wb = _testDataProvider.openSampleWorkbook(atpFile); - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - - Sheet sh = wb.getSheetAt(0); - // these two are not implemented in r - assertEquals("DELTA(1.3,1.5)", sh.getRow(0).getCell(1).getCellFormula()); - assertEquals("COMPLEX(2,4)", sh.getRow(1).getCell(1).getCellFormula()); - - Cell cell2 = sh.getRow(2).getCell(1); - assertEquals("ISODD(2)", cell2.getCellFormula()); - assertEquals(false, evaluator.evaluate(cell2).getBooleanValue()); - assertEquals(CellType.BOOLEAN, evaluator.evaluateFormulaCellEnum(cell2)); - - Cell cell3 = sh.getRow(3).getCell(1); - assertEquals("ISEVEN(2)", cell3.getCellFormula()); - assertEquals(true, evaluator.evaluate(cell3).getBooleanValue()); - assertEquals(CellType.BOOLEAN, evaluator.evaluateFormulaCellEnum(cell3)); - - wb.close(); - } - -} diff --git a/src/testcases/org/apache/poi/ss/formula/EvaluationListener.java b/src/testcases/org/apache/poi/ss/formula/EvaluationListener.java deleted file mode 100644 index babbbf62c..000000000 --- a/src/testcases/org/apache/poi/ss/formula/EvaluationListener.java +++ /dev/null @@ -1,67 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula; - -import org.apache.poi.ss.formula.eval.ValueEval; - -/** - * Tests should extend this class if they need to track the internal working of the {@link WorkbookEvaluator}.
    - * - * Default method implementations all do nothing - * - * @author Josh Micich - */ -public abstract class EvaluationListener implements IEvaluationListener { - @Override - public void onCacheHit(int sheetIndex, int rowIndex, int columnIndex, ValueEval result) { - // do nothing - } - @Override - public void onReadPlainValue(int sheetIndex, int rowIndex, int columnIndex, ICacheEntry entry) { - // do nothing - } - @Override - public void onStartEvaluate(EvaluationCell cell, ICacheEntry entry) { - // do nothing - } - @Override - public void onEndEvaluate(ICacheEntry entry, ValueEval result) { - // do nothing - } - @Override - public void onClearWholeCache() { - // do nothing - } - @Override - public void onClearCachedValue(ICacheEntry entry) { - // do nothing - } - @Override - public void onChangeFromBlankValue(int sheetIndex, int rowIndex, int columnIndex, - EvaluationCell cell, ICacheEntry entry) { - // do nothing - } - @Override - public void sortDependentCachedValues(ICacheEntry[] entries) { - // do nothing - } - @Override - public void onClearDependentCachedValue(ICacheEntry entry, int depth) { - // do nothing - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/TestCellCacheEntry.java b/src/testcases/org/apache/poi/ss/formula/TestCellCacheEntry.java deleted file mode 100644 index 128a767f5..000000000 --- a/src/testcases/org/apache/poi/ss/formula/TestCellCacheEntry.java +++ /dev/null @@ -1,43 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula; - -import junit.framework.TestCase; - -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.ValueEval; - -/** - * Tests {@link org.apache.poi.ss.formula.CellCacheEntry}. - * - * @author Josh Micich - */ -public class TestCellCacheEntry extends TestCase { - - public void testBasic() { - CellCacheEntry pcce = new PlainValueCellCacheEntry(new NumberEval(42.0)); - ValueEval ve = pcce.getValue(); - assertEquals(42, ((NumberEval)ve).getNumberValue(), 0.0); - - FormulaCellCacheEntry fcce = new FormulaCellCacheEntry(); - fcce.updateFormulaResult(new NumberEval(10.0), CellCacheEntry.EMPTY_ARRAY, null); - - ve = fcce.getValue(); - assertEquals(10, ((NumberEval)ve).getNumberValue(), 0.0); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/TestEvaluationCache.java b/src/testcases/org/apache/poi/ss/formula/TestEvaluationCache.java deleted file mode 100644 index 4641c4fdc..000000000 --- a/src/testcases/org/apache/poi/ss/formula/TestEvaluationCache.java +++ /dev/null @@ -1,786 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula; - -import java.io.PrintStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -import org.apache.poi.hssf.model.HSSFFormulaParser; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.apache.poi.ss.formula.eval.BlankEval; -import org.apache.poi.ss.formula.eval.BoolEval; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.hssf.usermodel.FormulaExtractor; -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFEvaluationTestHelper; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.hssf.util.CellReference; -import org.apache.poi.ss.formula.IEvaluationListener.ICacheEntry; -import org.apache.poi.ss.formula.PlainCellCache.Loc; -import org.apache.poi.ss.usermodel.*; - -/** - * Tests {@link org.apache.poi.ss.formula.EvaluationCache}. Makes sure that where possible (previously calculated) cached - * values are used. Also checks that changing cell values causes the correct (minimal) set of - * dependent cached values to be cleared. - * - * @author Josh Micich - */ -public class TestEvaluationCache extends TestCase { - - private static final class FormulaCellCacheEntryComparer implements Comparator { - - private final Map _formulaCellsByCacheEntry; - - public FormulaCellCacheEntryComparer(Map formulaCellsByCacheEntry) { - _formulaCellsByCacheEntry = formulaCellsByCacheEntry; - } - private EvaluationCell getCell(ICacheEntry a) { - return _formulaCellsByCacheEntry.get(a); - } - @Override - public int compare(ICacheEntry oa, ICacheEntry ob) { - EvaluationCell a = getCell(oa); - EvaluationCell b = getCell(ob); - int cmp; - cmp = a.getRowIndex() - b.getRowIndex(); - if (cmp != 0) { - return cmp; - } - cmp = a.getColumnIndex() - b.getColumnIndex(); - if (cmp != 0) { - return cmp; - } - if (a.getSheet() == b.getSheet()) { - return 0; - } - throw new RuntimeException("Incomplete code - don't know how to order sheets"); - } - } - - private static final class EvalListener extends EvaluationListener { - - private final List _logList; - private final HSSFWorkbook _book; - private final Map _formulaCellsByCacheEntry; - private final Map _plainCellLocsByCacheEntry; - - public EvalListener(HSSFWorkbook wb) { - _book = wb; - _logList = new ArrayList(); - _formulaCellsByCacheEntry = new HashMap(); - _plainCellLocsByCacheEntry = new HashMap(); - } - @Override - public void onCacheHit(int sheetIndex, int rowIndex, int columnIndex, ValueEval result) { - log("hit", rowIndex, columnIndex, result); - } - @Override - public void onReadPlainValue(int sheetIndex, int rowIndex, int columnIndex, ICacheEntry entry) { - Loc loc = new Loc(0, sheetIndex, rowIndex, columnIndex); - _plainCellLocsByCacheEntry.put(entry, loc); - log("value", rowIndex, columnIndex, entry.getValue()); - } - @Override - public void onStartEvaluate(EvaluationCell cell, ICacheEntry entry) { - _formulaCellsByCacheEntry.put(entry, cell); - HSSFCell hc = _book.getSheetAt(0).getRow(cell.getRowIndex()).getCell(cell.getColumnIndex()); - log("start", cell.getRowIndex(), cell.getColumnIndex(), FormulaExtractor.getPtgs(hc)); - } - @Override - public void onEndEvaluate(ICacheEntry entry, ValueEval result) { - EvaluationCell cell = _formulaCellsByCacheEntry.get(entry); - log("end", cell.getRowIndex(), cell.getColumnIndex(), result); - } - @Override - public void onClearCachedValue(ICacheEntry entry) { - int rowIndex; - int columnIndex; - EvaluationCell cell = _formulaCellsByCacheEntry.get(entry); - if (cell == null) { - Loc loc = _plainCellLocsByCacheEntry.get(entry); - if (loc == null) { - throw new IllegalStateException("can't find cell or location"); - } - rowIndex = loc.getRowIndex(); - columnIndex = loc.getColumnIndex(); - } else { - rowIndex = cell.getRowIndex(); - columnIndex = cell.getColumnIndex(); - } - log("clear", rowIndex, columnIndex, entry.getValue()); - } - @Override - public void sortDependentCachedValues(ICacheEntry[] entries) { - Arrays.sort(entries, new FormulaCellCacheEntryComparer(_formulaCellsByCacheEntry)); - } - @Override - public void onClearDependentCachedValue(ICacheEntry entry, int depth) { - EvaluationCell cell = _formulaCellsByCacheEntry.get(entry); - log("clear" + depth, cell.getRowIndex(), cell.getColumnIndex(), entry.getValue()); - } - - @Override - public void onChangeFromBlankValue(int sheetIndex, int rowIndex, int columnIndex, - EvaluationCell cell, ICacheEntry entry) { - log("changeFromBlank", rowIndex, columnIndex, entry.getValue()); - if (entry.getValue() == null) { // hack to tell the difference between formula and plain value - // perhaps the API could be improved: onChangeFromBlankToValue, onChangeFromBlankToFormula - _formulaCellsByCacheEntry.put(entry, cell); - } else { - Loc loc = new Loc(0, sheetIndex, rowIndex, columnIndex); - _plainCellLocsByCacheEntry.put(entry, loc); - } - } - private void log(String tag, int rowIndex, int columnIndex, Object value) { - StringBuffer sb = new StringBuffer(64); - sb.append(tag).append(' '); - sb.append(new CellReference(rowIndex, columnIndex, false, false).formatAsString()); - if (value != null) { - sb.append(' ').append(formatValue(value)); - } - _logList.add(sb.toString()); - } - private String formatValue(Object value) { - if (value instanceof Ptg[]) { - Ptg[] ptgs = (Ptg[]) value; - return HSSFFormulaParser.toFormulaString(_book, ptgs); - } - if (value instanceof NumberEval) { - NumberEval ne = (NumberEval) value; - return ne.getStringValue(); - } - if (value instanceof StringEval) { - StringEval se = (StringEval) value; - return "'" + se.getStringValue() + "'"; - } - if (value instanceof BoolEval) { - BoolEval be = (BoolEval) value; - return be.getStringValue(); - } - if (value == BlankEval.instance) { - return "#BLANK#"; - } - if (value instanceof ErrorEval) { - ErrorEval ee = (ErrorEval) value; - return ErrorEval.getText(ee.getErrorCode()); - } - throw new IllegalArgumentException("Unexpected value class (" - + value.getClass().getName() + ")"); - } - public String[] getAndClearLog() { - String[] result = new String[_logList.size()]; - _logList.toArray(result); - _logList.clear(); - return result; - } - } - /** - * Wrapper class to manage repetitive tasks from this test, - * - * Note - this class does a little bit more than just plain set-up of data. The method - * {@link WorkbookEvaluator#clearCachedResultValue(HSSFSheet, int, int)} is called whenever a - * cell value is changed. - * - */ - private static final class MySheet { - - private final HSSFSheet _sheet; - private final WorkbookEvaluator _evaluator; - private final HSSFWorkbook _wb; - private final EvalListener _evalListener; - - public MySheet() { - _wb = new HSSFWorkbook(); - _evalListener = new EvalListener(_wb); - _evaluator = WorkbookEvaluatorTestHelper.createEvaluator(_wb, _evalListener); - _sheet = _wb.createSheet("Sheet1"); - } - - private static EvaluationCell wrapCell(HSSFCell cell) { - return HSSFEvaluationTestHelper.wrapCell(cell); - } - - public void setCellValue(String cellRefText, double value) { - HSSFCell cell = getOrCreateCell(cellRefText); - // be sure to blank cell, in case it is currently a formula - cell.setCellType(CellType.BLANK); - // otherwise this line will only set the formula cached result; - cell.setCellValue(value); - _evaluator.notifyUpdateCell(wrapCell(cell)); - } - public void clearCell(String cellRefText) { - HSSFCell cell = getOrCreateCell(cellRefText); - cell.setCellType(CellType.BLANK); - _evaluator.notifyUpdateCell(wrapCell(cell)); - } - - public void setCellFormula(String cellRefText, String formulaText) { - HSSFCell cell = getOrCreateCell(cellRefText); - cell.setCellFormula(formulaText); - _evaluator.notifyUpdateCell(wrapCell(cell)); - } - - private HSSFCell getOrCreateCell(String cellRefText) { - CellReference cr = new CellReference(cellRefText); - int rowIndex = cr.getRow(); - HSSFRow row = _sheet.getRow(rowIndex); - if (row == null) { - row = _sheet.createRow(rowIndex); - } - int cellIndex = cr.getCol(); - HSSFCell cell = row.getCell(cellIndex); - if (cell == null) { - cell = row.createCell(cellIndex); - } - return cell; - } - - public ValueEval evaluateCell(String cellRefText) { - return _evaluator.evaluate(wrapCell(getOrCreateCell(cellRefText))); - } - - public String[] getAndClearLog() { - return _evalListener.getAndClearLog(); - } - - public void clearAllCachedResultValues() { - _evaluator.clearAllCachedResultValues(); - } - } - - private static MySheet createMediumComplex() { - MySheet ms = new MySheet(); - - // plain data in D1:F3 - ms.setCellValue("D1", 12); - ms.setCellValue("E1", 13); - ms.setCellValue("D2", 14); - ms.setCellValue("E2", 15); - ms.setCellValue("D3", 16); - ms.setCellValue("E3", 17); - - - ms.setCellFormula("C1", "SUM(D1:E2)"); - ms.setCellFormula("C2", "SUM(D2:E3)"); - ms.setCellFormula("C3", "SUM(D3:E4)"); - - ms.setCellFormula("B1", "C2-C1"); - ms.setCellFormula("B2", "B3*C1-C2"); - ms.setCellValue("B3", 2); - - ms.setCellFormula("A1", "MAX(B1:B2)"); - ms.setCellFormula("A2", "MIN(B3,D2:F2)"); - ms.setCellFormula("A3", "B3*C3"); - - // clear all the logging from the above initialisation - ms.getAndClearLog(); - ms.clearAllCachedResultValues(); - return ms; - } - - public void testMediumComplex() { - - MySheet ms = createMediumComplex(); - // completely fresh evaluation - confirmEvaluate(ms, "A1", 46); - confirmLog(ms, new String[] { - "start A1 MAX(B1:B2)", - "start B1 C2-C1", - "start C2 SUM(D2:E3)", - "value D2 14", "value E2 15", "value D3 16", "value E3 17", - "end C2 62", - "start C1 SUM(D1:E2)", - "value D1 12", "value E1 13", "hit D2 14", "hit E2 15", - "end C1 54", - "end B1 8", - "start B2 B3*C1-C2", - "value B3 2", - "hit C1 54", - "hit C2 62", - "end B2 46", - "end A1 46", - }); - - - // simple cache hit - immediate re-evaluation with no changes - confirmEvaluate(ms, "A1", 46); - confirmLog(ms, new String[] { "hit A1 46", }); - - // change a low level cell - ms.setCellValue("D1", 10); - confirmLog(ms, new String[] { - "clear D1 10", - "clear1 C1 54", - "clear2 B1 8", - "clear3 A1 46", - "clear2 B2 46", - }); - confirmEvaluate(ms, "A1", 42); - confirmLog(ms, new String[] { - "start A1 MAX(B1:B2)", - "start B1 C2-C1", - "hit C2 62", - "start C1 SUM(D1:E2)", - "hit D1 10", "hit E1 13", "hit D2 14", "hit E2 15", - "end C1 52", - "end B1 10", - "start B2 B3*C1-C2", - "hit B3 2", - "hit C1 52", - "hit C2 62", - "end B2 42", - "end A1 42", - }); - - // Reset and try changing an intermediate value - ms = createMediumComplex(); - confirmEvaluate(ms, "A1", 46); - ms.getAndClearLog(); - - ms.setCellValue("B3", 3); // B3 is in the middle of the dependency tree - confirmLog(ms, new String[] { - "clear B3 3", - "clear1 B2 46", - "clear2 A1 46", - }); - confirmEvaluate(ms, "A1", 100); - confirmLog(ms, new String[] { - "start A1 MAX(B1:B2)", - "hit B1 8", - "start B2 B3*C1-C2", - "hit B3 3", - "hit C1 54", - "hit C2 62", - "end B2 100", - "end A1 100", - }); - } - - public void testMediumComplexWithDependencyChange() { - - // Changing an intermediate formula - MySheet ms = createMediumComplex(); - confirmEvaluate(ms, "A1", 46); - ms.getAndClearLog(); - ms.setCellFormula("B2", "B3*C2-C3"); // used to be "B3*C1-C2" - confirmLog(ms, new String[] { - "clear B2 46", - "clear1 A1 46", - }); - - confirmEvaluate(ms, "A1", 91); - confirmLog(ms, new String[] { - "start A1 MAX(B1:B2)", - "hit B1 8", - "start B2 B3*C2-C3", - "hit B3 2", - "hit C2 62", - "start C3 SUM(D3:E4)", - "hit D3 16", "hit E3 17", -// "value D4 #BLANK#", "value E4 #BLANK#", - "end C3 33", - "end B2 91", - "end A1 91", - }); - - //---------------- - // Note - From now on the demonstrated POI behaviour is not optimal - //---------------- - - // Now change a value that should no longer affect B2 - ms.setCellValue("D1", 11); - confirmLog(ms, new String[] { - "clear D1 11", - "clear1 C1 54", - // note there is no "clear2 B2 91" here because B2 doesn't depend on C1 anymore - "clear2 B1 8", - "clear3 A1 91", - }); - - confirmEvaluate(ms, "B2", 91); - confirmLog(ms, new String[] { - "hit B2 91", // further confirmation that B2 was not cleared due to changing D1 above - }); - - // things should be back to normal now - ms.setCellValue("D1", 11); - confirmLog(ms, new String[] { }); - confirmEvaluate(ms, "B2", 91); - confirmLog(ms, new String[] { - "hit B2 91", - }); - } - - /** - * verifies that when updating a plain cell, depending (formula) cell cached values are cleared - * only when the plain cell's value actually changes - */ - public void testRedundantUpdate() { - MySheet ms = new MySheet(); - - ms.setCellValue("B1", 12); - ms.setCellValue("C1", 13); - ms.setCellFormula("A1", "B1+C1"); - - // evaluate twice to confirm caching looks OK - ms.evaluateCell("A1"); - ms.getAndClearLog(); - confirmEvaluate(ms, "A1", 25); - confirmLog(ms, new String[] { - "hit A1 25", - }); - - // Make redundant update, and check re-evaluation - ms.setCellValue("B1", 12); // value didn't change - confirmLog(ms, new String[] {}); - confirmEvaluate(ms, "A1", 25); - confirmLog(ms, new String[] { - "hit A1 25", - }); - - ms.setCellValue("B1", 11); // value changing - confirmLog(ms, new String[] { - "clear B1 11", - "clear1 A1 25", // expect consuming formula cached result to get cleared - }); - confirmEvaluate(ms, "A1", 24); - confirmLog(ms, new String[] { - "start A1 B1+C1", - "hit B1 11", - "hit C1 13", - "end A1 24", - }); - } - - /** - * Changing any input to a formula may cause the formula to 'use' a different set of cells. - * Functions like INDEX and OFFSET make this effect obvious, with functions like MATCH - * and VLOOKUP the effect can be subtle. The presence of error values can also produce this - * effect in almost every function and operator. - */ - public void testSimpleWithDependencyChange() { - - MySheet ms = new MySheet(); - - ms.setCellFormula("A1", "INDEX(C1:E1,1,B1)"); - ms.setCellValue("B1", 1); - ms.setCellValue("C1", 17); - ms.setCellValue("D1", 18); - ms.setCellValue("E1", 19); - ms.clearAllCachedResultValues(); - ms.getAndClearLog(); - - confirmEvaluate(ms, "A1", 17); - confirmLog(ms, new String[] { - "start A1 INDEX(C1:E1,1,B1)", - "value B1 1", - "value C1 17", - "end A1 17", - }); - ms.setCellValue("B1", 2); - ms.getAndClearLog(); - - confirmEvaluate(ms, "A1", 18); - confirmLog(ms, new String[] { - "start A1 INDEX(C1:E1,1,B1)", - "hit B1 2", - "value D1 18", - "end A1 18", - }); - - // change C1. Note - last time A1 evaluated C1 was not used - ms.setCellValue("C1", 15); - ms.getAndClearLog(); - confirmEvaluate(ms, "A1", 18); - confirmLog(ms, new String[] { - "hit A1 18", - }); - - // but A1 still uses D1, so if it changes... - ms.setCellValue("D1", 25); - ms.getAndClearLog(); - confirmEvaluate(ms, "A1", 25); - confirmLog(ms, new String[] { - "start A1 INDEX(C1:E1,1,B1)", - "hit B1 2", - "hit D1 25", - "end A1 25", - }); - } - - public void testBlankCells() { - - - MySheet ms = new MySheet(); - - ms.setCellFormula("A1", "sum(B1:D4,B5:E6)"); - ms.setCellValue("B1", 12); - ms.clearAllCachedResultValues(); - ms.getAndClearLog(); - - confirmEvaluate(ms, "A1", 12); - confirmLog(ms, new String[] { - "start A1 SUM(B1:D4,B5:E6)", - "value B1 12", - "end A1 12", - }); - ms.setCellValue("B6", 2); - ms.getAndClearLog(); - - confirmEvaluate(ms, "A1", 14); - confirmLog(ms, new String[] { - "start A1 SUM(B1:D4,B5:E6)", - "hit B1 12", - "hit B6 2", - "end A1 14", - }); - ms.setCellValue("E4", 2); - ms.getAndClearLog(); - - confirmEvaluate(ms, "A1", 14); - confirmLog(ms, new String[] { - "hit A1 14", - }); - - ms.setCellValue("D1", 1); - ms.getAndClearLog(); - - confirmEvaluate(ms, "A1", 15); - confirmLog(ms, new String[] { - "start A1 SUM(B1:D4,B5:E6)", - "hit B1 12", - "hit D1 1", - "hit B6 2", - "end A1 15", - }); - } - - /** - * Make sure that when blank cells are changed to value/formula cells, any dependent formulas - * have their cached results cleared. - */ - public void testBlankCellChangedToValueCell_bug46053() { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("Sheet1"); - HSSFRow row = sheet.createRow(0); - HSSFCell cellA1 = row.createCell(0); - HSSFCell cellB1 = row.createCell(1); - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - - cellA1.setCellFormula("B1+2.2"); - cellB1.setCellValue(1.5); - - fe.notifyUpdateCell(cellA1); - fe.notifyUpdateCell(cellB1); - - CellValue cv; - cv = fe.evaluate(cellA1); - assertEquals(3.7, cv.getNumberValue(), 0.0); - - cellB1.setCellType(CellType.BLANK); - fe.notifyUpdateCell(cellB1); - cv = fe.evaluate(cellA1); // B1 was used to evaluate A1 - assertEquals(2.2, cv.getNumberValue(), 0.0); - - cellB1.setCellValue(0.4); // changing B1, so A1 cached result should be cleared - fe.notifyUpdateCell(cellB1); - cv = fe.evaluate(cellA1); - if (cv.getNumberValue() == 2.2) { - // looks like left-over cached result from before change to B1 - throw new AssertionFailedError("Identified bug 46053"); - } - assertEquals(2.6, cv.getNumberValue(), 0.0); - } - - /** - * same use-case as the test for bug 46053, but checking trace values too - */ - public void testBlankCellChangedToValueCell() { - - MySheet ms = new MySheet(); - - ms.setCellFormula("A1", "B1+2.2"); - ms.setCellValue("B1", 1.5); - ms.clearAllCachedResultValues(); - ms.clearCell("B1"); - ms.getAndClearLog(); - - confirmEvaluate(ms, "A1", 2.2); - confirmLog(ms, new String[] { - "start A1 B1+2.2", - "end A1 2.2", - }); - ms.setCellValue("B1", 0.4); - confirmLog(ms, new String[] { - "changeFromBlank B1 0.4", - "clear A1", - }); - - confirmEvaluate(ms, "A1", 2.6); - confirmLog(ms, new String[] { - "start A1 B1+2.2", - "hit B1 0.4", - "end A1 2.6", - }); - } - - private static void confirmEvaluate(MySheet ms, String cellRefText, double expectedValue) { - ValueEval v = ms.evaluateCell(cellRefText); - assertEquals(NumberEval.class, v.getClass()); - assertEquals(expectedValue, ((NumberEval)v).getNumberValue(), 0.0); - } - - private static void confirmLog(MySheet ms, String[] expectedLog) { - String[] actualLog = ms.getAndClearLog(); - int endIx = actualLog.length; - PrintStream ps = System.err; - if (endIx != expectedLog.length) { - ps.println("Log lengths mismatch"); - dumpCompare(ps, expectedLog, actualLog); - throw new AssertionFailedError("Log lengths mismatch"); - } - for (int i=0; i< endIx; i++) { - if (!actualLog[i].equals(expectedLog[i])) { - String msg = "Log entry mismatch at index " + i; - ps.println(msg); - dumpCompare(ps, expectedLog, actualLog); - throw new AssertionFailedError(msg); - } - } - - } - - private static void dumpCompare(PrintStream ps, String[] expectedLog, String[] actualLog) { - int max = Math.max(actualLog.length, expectedLog.length); - ps.println("Index\tExpected\tActual"); - for(int i=0; i workbooks = new HashMap(); - workbooks.put(MAIN_WORKBOOK_FILENAME, lMainWorkbookEvaluator); - workbooks.put(SOURCE_DUMMY_WORKBOOK_FILENAME, lSourceEvaluator); - lMainWorkbookEvaluator.setupReferencedWorkbooks(workbooks); - - assertEquals(CellType.NUMERIC, lMainWorkbookEvaluator.evaluateFormulaCellEnum(lA1Cell)); - assertEquals(CellType.STRING, lMainWorkbookEvaluator.evaluateFormulaCellEnum(lB1Cell)); - assertEquals(CellType.BOOLEAN, lMainWorkbookEvaluator.evaluateFormulaCellEnum(lC1Cell)); - - assertEquals(20.0d, lA1Cell.getNumericCellValue(), 0.00001d); - assertEquals("Apache rocks!", lB1Cell.getStringCellValue()); - assertEquals(false, lC1Cell.getBooleanCellValue()); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/TestPlainCellCache.java b/src/testcases/org/apache/poi/ss/formula/TestPlainCellCache.java deleted file mode 100644 index e40100d5b..000000000 --- a/src/testcases/org/apache/poi/ss/formula/TestPlainCellCache.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.ss.formula; - -import junit.framework.TestCase; -import org.apache.poi.ss.formula.PlainCellCache.Loc; -import org.apache.poi.ss.formula.eval.*; - -/** - * @author Yegor Kozlov - */ -public class TestPlainCellCache extends TestCase { - - /** - * - */ - public void testLoc(){ - PlainCellCache cache = new PlainCellCache(); - for (int bookIndex = 0; bookIndex < 0x1000; bookIndex += 0x100) { - for (int sheetIndex = 0; sheetIndex < 0x1000; sheetIndex += 0x100) { - for (int rowIndex = 0; rowIndex < 0x100000; rowIndex += 0x1000) { - for (int columnIndex = 0; columnIndex < 0x4000; columnIndex += 0x100) { - Loc loc = new Loc(bookIndex, sheetIndex, rowIndex, columnIndex); - assertEquals(bookIndex, loc.getBookIndex()); - assertEquals(sheetIndex, loc.getSheetIndex()); - assertEquals(rowIndex, loc.getRowIndex()); - assertEquals(columnIndex, loc.getColumnIndex()); - - Loc sameLoc = new Loc(bookIndex, sheetIndex, rowIndex, columnIndex); - assertEquals(loc.hashCode(), sameLoc.hashCode()); - assertTrue(loc.equals(sameLoc)); - - assertNull(cache.get(loc)); - PlainValueCellCacheEntry entry = new PlainValueCellCacheEntry(new NumberEval(0)); - cache.put(loc, entry); - assertSame(entry, cache.get(loc)); - cache.remove(loc); - assertNull(cache.get(loc)); - - cache.put(loc, entry); - } - cache.clear(); - } - } - - } - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/TestSheetNameFormatter.java b/src/testcases/org/apache/poi/ss/formula/TestSheetNameFormatter.java deleted file mode 100644 index 69b0c9b4f..000000000 --- a/src/testcases/org/apache/poi/ss/formula/TestSheetNameFormatter.java +++ /dev/null @@ -1,108 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula; - -import junit.framework.TestCase; -import org.apache.poi.ss.formula.SheetNameFormatter; - -/** - * Tests for {@link SheetNameFormatter} - * - * @author Josh Micich - */ -public final class TestSheetNameFormatter extends TestCase { - - private static void confirmFormat(String rawSheetName, String expectedSheetNameEncoding) { - assertEquals(expectedSheetNameEncoding, SheetNameFormatter.format(rawSheetName)); - } - - /** - * Tests main public method 'format' - */ - public void testFormat() { - - confirmFormat("abc", "abc"); - confirmFormat("123", "'123'"); - - confirmFormat("my sheet", "'my sheet'"); // space - confirmFormat("A:MEM", "'A:MEM'"); // colon - - confirmFormat("O'Brian", "'O''Brian'"); // single quote gets doubled - - - confirmFormat("3rdTimeLucky", "'3rdTimeLucky'"); // digit in first pos - confirmFormat("_", "_"); // plain underscore OK - confirmFormat("my_3rd_sheet", "my_3rd_sheet"); // underscores and digits OK - confirmFormat("A12220", "'A12220'"); - confirmFormat("TAXRETURN19980415", "TAXRETURN19980415"); - } - - public void testBooleanLiterals() { - confirmFormat("TRUE", "'TRUE'"); - confirmFormat("FALSE", "'FALSE'"); - confirmFormat("True", "'True'"); - confirmFormat("fAlse", "'fAlse'"); - - confirmFormat("Yes", "Yes"); - confirmFormat("No", "No"); - } - - private static void confirmCellNameMatch(String rawSheetName, boolean expected) { - assertEquals(expected, SheetNameFormatter.nameLooksLikePlainCellReference(rawSheetName)); - } - - /** - * Tests functionality to determine whether a sheet name containing only letters and digits - * would look (to Excel) like a cell name. - */ - public void testLooksLikePlainCellReference() { - - confirmCellNameMatch("A1", true); - confirmCellNameMatch("a111", true); - confirmCellNameMatch("AA", false); - confirmCellNameMatch("aa1", true); - confirmCellNameMatch("A1A", false); - confirmCellNameMatch("A1A1", false); - confirmCellNameMatch("Sh3", false); - confirmCellNameMatch("SALES20080101", false); // out of range - } - - private static void confirmCellRange(String text, int numberOfPrefixLetters, boolean expected) { - String prefix = text.substring(0, numberOfPrefixLetters); - String suffix = text.substring(numberOfPrefixLetters); - assertEquals(expected, SheetNameFormatter.cellReferenceIsWithinRange(prefix, suffix)); - } - - /** - * Tests exact boundaries for names that look very close to cell names (i.e. contain 1 or more - * letters followed by one or more digits). - */ - public void testCellRange() { - confirmCellRange("A1", 1, true); - confirmCellRange("a111", 1, true); - confirmCellRange("A65536", 1, true); - confirmCellRange("A65537", 1, false); - confirmCellRange("iv1", 2, true); - confirmCellRange("IW1", 2, false); - confirmCellRange("AAA1", 3, false); - confirmCellRange("a111", 1, true); - confirmCellRange("Sheet1", 6, false); - confirmCellRange("iV65536", 2, true); // max cell in Excel 97-2003 - confirmCellRange("IW65537", 2, false); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/TestWorkbookEvaluator.java b/src/testcases/org/apache/poi/ss/formula/TestWorkbookEvaluator.java deleted file mode 100644 index 7c8936362..000000000 --- a/src/testcases/org/apache/poi/ss/formula/TestWorkbookEvaluator.java +++ /dev/null @@ -1,609 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.IOException; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.eval.BlankEval; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.MissingArgEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.ss.formula.ptg.AreaErrPtg; -import org.apache.poi.ss.formula.ptg.AttrPtg; -import org.apache.poi.ss.formula.ptg.DeletedArea3DPtg; -import org.apache.poi.ss.formula.ptg.DeletedRef3DPtg; -import org.apache.poi.ss.formula.ptg.IntPtg; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.apache.poi.ss.formula.ptg.RefErrorPtg; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Name; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.junit.Ignore; -import org.junit.Test; - -/** - * Tests {@link WorkbookEvaluator}. - * - * @author Josh Micich - */ -public class TestWorkbookEvaluator { - - private static final double EPSILON = 0.0000001; - - private static ValueEval evaluateFormula(Ptg[] ptgs) { - OperationEvaluationContext ec = new OperationEvaluationContext(null, null, 0, 0, 0, null); - return new WorkbookEvaluator(null, null, null).evaluateFormula(ec, ptgs); - } - - /** - * Make sure that the evaluator can directly handle tAttrSum (instead of relying on re-parsing - * the whole formula which converts tAttrSum to tFuncVar("SUM") ) - */ - @Test - public void testAttrSum() { - - Ptg[] ptgs = { - new IntPtg(42), - AttrPtg.SUM, - }; - - ValueEval result = evaluateFormula(ptgs); - assertEquals(42, ((NumberEval)result).getNumberValue(), 0.0); - } - - /** - * Make sure that the evaluator can directly handle (deleted) ref error tokens - * (instead of relying on re-parsing the whole formula which converts these - * to the error constant #REF! ) - */ - @Test - public void testRefErr() { - - confirmRefErr(new RefErrorPtg()); - confirmRefErr(new AreaErrPtg()); - confirmRefErr(new DeletedRef3DPtg(0)); - confirmRefErr(new DeletedArea3DPtg(0)); - } - private static void confirmRefErr(Ptg ptg) { - Ptg[] ptgs = { - ptg, - }; - - ValueEval result = evaluateFormula(ptgs); - assertEquals(ErrorEval.REF_INVALID, result); - } - - /** - * Make sure that the evaluator can directly handle tAttrSum (instead of relying on re-parsing - * the whole formula which converts tAttrSum to tFuncVar("SUM") ) - */ - @Test - public void testMemFunc() { - - Ptg[] ptgs = { - new IntPtg(42), - AttrPtg.SUM, - }; - - ValueEval result = evaluateFormula(ptgs); - assertEquals(42, ((NumberEval)result).getNumberValue(), 0.0); - } - - - @Test - public void testEvaluateMultipleWorkbooks() { - HSSFWorkbook wbA = HSSFTestDataSamples.openSampleWorkbook("multibookFormulaA.xls"); - HSSFWorkbook wbB = HSSFTestDataSamples.openSampleWorkbook("multibookFormulaB.xls"); - - HSSFFormulaEvaluator evaluatorA = new HSSFFormulaEvaluator(wbA); - HSSFFormulaEvaluator evaluatorB = new HSSFFormulaEvaluator(wbB); - - // Hook up the workbook evaluators to enable evaluation of formulas across books - String[] bookNames = { "multibookFormulaA.xls", "multibookFormulaB.xls", }; - HSSFFormulaEvaluator[] evaluators = { evaluatorA, evaluatorB, }; - HSSFFormulaEvaluator.setupEnvironment(bookNames, evaluators); - - HSSFCell cell; - - HSSFSheet aSheet1 = wbA.getSheetAt(0); - HSSFSheet bSheet1 = wbB.getSheetAt(0); - - // Simple case - single link from wbA to wbB - confirmFormula(wbA, 0, 0, 0, "[multibookFormulaB.xls]BSheet1!B1"); - cell = aSheet1.getRow(0).getCell(0); - confirmEvaluation(35, evaluatorA, cell); - - - // more complex case - back link into wbA - // [wbA]ASheet1!A2 references (among other things) [wbB]BSheet1!B2 - confirmFormula(wbA, 0, 1, 0, "[multibookFormulaB.xls]BSheet1!$B$2+2*A3"); - // [wbB]BSheet1!B2 references (among other things) [wbA]AnotherSheet!A1:B2 - confirmFormula(wbB, 0, 1, 1, "SUM([multibookFormulaA.xls]AnotherSheet!$A$1:$B$2)+B3"); - - cell = aSheet1.getRow(1).getCell(0); - confirmEvaluation(264, evaluatorA, cell); - - // change [wbB]BSheet1!B3 (from 50 to 60) - HSSFCell cellB3 = bSheet1.getRow(2).getCell(1); - cellB3.setCellValue(60); - evaluatorB.notifyUpdateCell(cellB3); - confirmEvaluation(274, evaluatorA, cell); - - // change [wbA]ASheet1!A3 (from 100 to 80) - HSSFCell cellA3 = aSheet1.getRow(2).getCell(0); - cellA3.setCellValue(80); - evaluatorA.notifyUpdateCell(cellA3); - confirmEvaluation(234, evaluatorA, cell); - - // change [wbA]AnotherSheet!A1 (from 2 to 3) - HSSFCell cellA1 = wbA.getSheetAt(1).getRow(0).getCell(0); - cellA1.setCellValue(3); - evaluatorA.notifyUpdateCell(cellA1); - confirmEvaluation(235, evaluatorA, cell); - } - - private static void confirmEvaluation(double expectedValue, HSSFFormulaEvaluator fe, HSSFCell cell) { - assertEquals(expectedValue, fe.evaluate(cell).getNumberValue(), 0.0); - } - - private static void confirmFormula(HSSFWorkbook wb, int sheetIndex, int rowIndex, int columnIndex, - String expectedFormula) { - HSSFCell cell = wb.getSheetAt(sheetIndex).getRow(rowIndex).getCell(columnIndex); - assertEquals(expectedFormula, cell.getCellFormula()); - } - - /** - * This test makes sure that any {@link MissingArgEval} that propagates to - * the result of a function gets translated to {@link BlankEval}. - */ - @Test - public void testMissingArg() { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("Sheet1"); - HSSFRow row = sheet.createRow(0); - HSSFCell cell = row.createCell(0); - cell.setCellFormula("1+IF(1,,)"); - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - CellValue cv = null; - try { - cv = fe.evaluate(cell); - } catch (RuntimeException e) { - fail("Missing arg result not being handled correctly."); - } - assertEquals(CellType.NUMERIC, cv.getCellTypeEnum()); - // adding blank to 1.0 gives 1.0 - assertEquals(1.0, cv.getNumberValue(), 0.0); - - // check with string operand - cell.setCellFormula("\"abc\"&IF(1,,)"); - fe.notifySetFormula(cell); - cv = fe.evaluate(cell); - assertEquals(CellType.STRING, cv.getCellTypeEnum()); - // adding blank to "abc" gives "abc" - assertEquals("abc", cv.getStringValue()); - - // check CHOOSE() - cell.setCellFormula("\"abc\"&CHOOSE(2,5,,9)"); - fe.notifySetFormula(cell); - cv = fe.evaluate(cell); - assertEquals(CellType.STRING, cv.getCellTypeEnum()); - // adding blank to "abc" gives "abc" - assertEquals("abc", cv.getStringValue()); - } - - /** - * Functions like IF, INDIRECT, INDEX, OFFSET etc can return AreaEvals which - * should be dereferenced by the evaluator - * @throws IOException - */ - @Test - public void testResultOutsideRange() throws IOException { - Workbook wb = new HSSFWorkbook(); - try { - Cell cell = wb.createSheet("Sheet1").createRow(0).createCell(0); - cell.setCellFormula("D2:D5"); // IF(TRUE,D2:D5,D2) or OFFSET(D2:D5,0,0) would work too - FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); - CellValue cv; - try { - cv = fe.evaluate(cell); - } catch (IllegalArgumentException e) { - if ("Specified row index (0) is outside the allowed range (1..4)".equals(e.getMessage())) { - fail("Identified bug in result dereferencing"); - } - throw new RuntimeException(e); - } - assertEquals(CellType.ERROR, cv.getCellTypeEnum()); - assertEquals(ErrorEval.VALUE_INVALID.getErrorCode(), cv.getErrorValue()); - - // verify circular refs are still detected properly - fe.clearAllCachedResultValues(); - cell.setCellFormula("OFFSET(A1,0,0)"); - cv = fe.evaluate(cell); - assertEquals(CellType.ERROR, cv.getCellTypeEnum()); - assertEquals(ErrorEval.CIRCULAR_REF_ERROR.getErrorCode(), cv.getErrorValue()); - } finally { - wb.close(); - } - } - - - /** - * formulas with defined names. - * @throws IOException - */ - @Test - public void testNamesInFormulas() throws IOException { - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet("Sheet1"); - - Name name1 = wb.createName(); - name1.setNameName("aConstant"); - name1.setRefersToFormula("3.14"); - - Name name2 = wb.createName(); - name2.setNameName("aFormula"); - name2.setRefersToFormula("SUM(Sheet1!$A$1:$A$3)"); - - Name name3 = wb.createName(); - name3.setNameName("aSet"); - name3.setRefersToFormula("Sheet1!$A$2:$A$4"); - - - Row row0 = sheet.createRow(0); - Row row1 = sheet.createRow(1); - Row row2 = sheet.createRow(2); - Row row3 = sheet.createRow(3); - row0.createCell(0).setCellValue(2); - row1.createCell(0).setCellValue(5); - row2.createCell(0).setCellValue(3); - row3.createCell(0).setCellValue(7); - - row0.createCell(2).setCellFormula("aConstant"); - row1.createCell(2).setCellFormula("aFormula"); - row2.createCell(2).setCellFormula("SUM(aSet)"); - row3.createCell(2).setCellFormula("aConstant+aFormula+SUM(aSet)"); - - FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); - assertEquals(3.14, fe.evaluate(row0.getCell(2)).getNumberValue(), EPSILON); - assertEquals(10.0, fe.evaluate(row1.getCell(2)).getNumberValue(), EPSILON); - assertEquals(15.0, fe.evaluate(row2.getCell(2)).getNumberValue(), EPSILON); - assertEquals(28.14, fe.evaluate(row3.getCell(2)).getNumberValue(), EPSILON); - - wb.close(); - } - - @Test - public void testIgnoreMissingWorkbooks() { - // TODO: update this test for meaningful functional behavior - WorkbookEvaluator evaluator = new WorkbookEvaluator(null, null, null); - assertFalse(evaluator.isIgnoreMissingWorkbooks()); - - evaluator.setIgnoreMissingWorkbooks(true); - assertTrue(evaluator.isIgnoreMissingWorkbooks()); - - evaluator.setIgnoreMissingWorkbooks(false); - assertFalse(evaluator.isIgnoreMissingWorkbooks()); - } - - @Test - public void testDebugEvaluationOutputForNextEval() { - // TODO: update this test for meaningful functional behavior - WorkbookEvaluator evaluator = new WorkbookEvaluator(null, null, null); - assertFalse(evaluator.isDebugEvaluationOutputForNextEval()); - - evaluator.setDebugEvaluationOutputForNextEval(true); - assertTrue(evaluator.isDebugEvaluationOutputForNextEval()); - - evaluator.setDebugEvaluationOutputForNextEval(false); - assertFalse(evaluator.isDebugEvaluationOutputForNextEval()); - } - -// Test IF-Equals Formula Evaluation (bug 58591) - - private Workbook testIFEqualsFormulaEvaluation_setup(String formula, CellType a1CellType) { - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet("IFEquals"); - Row row = sheet.createRow(0); - Cell A1 = row.createCell(0); - Cell B1 = row.createCell(1); - Cell C1 = row.createCell(2); - Cell D1 = row.createCell(3); - - switch (a1CellType) { - case NUMERIC: - A1.setCellValue(1.0); - // "A1=1" should return true - break; - case STRING: - A1.setCellValue("1"); - // "A1=1" should return false - // "A1=\"1\"" should return true - break; - case BOOLEAN: - A1.setCellValue(true); - // "A1=1" should return true - break; - case FORMULA: - A1.setCellFormula("1"); - // "A1=1" should return true - break; - case BLANK: - A1.setCellValue((String) null); - // "A1=1" should return false - break; - default: - throw new IllegalArgumentException("unexpected cell type: " + a1CellType); - } - B1.setCellValue(2.0); - C1.setCellValue(3.0); - D1.setCellFormula(formula); - - return wb; - } - - private void testIFEqualsFormulaEvaluation_teardown(Workbook wb) { - try { - wb.close(); - } catch (final IOException e) { - fail("Unable to close workbook"); - } - } - - - - private void testIFEqualsFormulaEvaluation_evaluate( - String formula, CellType cellType, String expectedFormula, double expectedResult) { - Workbook wb = testIFEqualsFormulaEvaluation_setup(formula, cellType); - Cell D1 = wb.getSheet("IFEquals").getRow(0).getCell(3); - - FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator(); - CellValue result = eval.evaluate(D1); - - // Call should not modify the contents - assertEquals(CellType.FORMULA, D1.getCellTypeEnum()); - assertEquals(expectedFormula, D1.getCellFormula()); - - assertEquals(CellType.NUMERIC, result.getCellTypeEnum()); - assertEquals(expectedResult, result.getNumberValue(), EPSILON); - - testIFEqualsFormulaEvaluation_teardown(wb); - } - - private void testIFEqualsFormulaEvaluation_eval( - final String formula, final CellType cellType, final String expectedFormula, final double expectedValue) { - testIFEqualsFormulaEvaluation_evaluate(formula, cellType, expectedFormula, expectedValue); - testIFEqualsFormulaEvaluation_evaluateFormulaCell(formula, cellType, expectedFormula, expectedValue); - testIFEqualsFormulaEvaluation_evaluateInCell(formula, cellType, expectedFormula, expectedValue); - testIFEqualsFormulaEvaluation_evaluateAll(formula, cellType, expectedFormula, expectedValue); - testIFEqualsFormulaEvaluation_evaluateAllFormulaCells(formula, cellType, expectedFormula, expectedValue); - } - - @Test - public void testIFEqualsFormulaEvaluation_NumericLiteral() { - final String formula = "IF(A1=1, 2, 3)"; - final CellType cellType = CellType.NUMERIC; - final String expectedFormula = "IF(A1=1,2,3)"; - final double expectedValue = 2.0; - testIFEqualsFormulaEvaluation_eval(formula, cellType, expectedFormula, expectedValue); - } - - @Test - public void testIFEqualsFormulaEvaluation_Numeric() { - final String formula = "IF(A1=1, B1, C1)"; - final CellType cellType = CellType.NUMERIC; - final String expectedFormula = "IF(A1=1,B1,C1)"; - final double expectedValue = 2.0; - testIFEqualsFormulaEvaluation_eval(formula, cellType, expectedFormula, expectedValue); - } - - @Test - public void testIFEqualsFormulaEvaluation_NumericCoerceToString() { - final String formula = "IF(A1&\"\"=\"1\", B1, C1)"; - final CellType cellType = CellType.NUMERIC; - final String expectedFormula = "IF(A1&\"\"=\"1\",B1,C1)"; - final double expectedValue = 2.0; - testIFEqualsFormulaEvaluation_eval(formula, cellType, expectedFormula, expectedValue); - } - - @Test - public void testIFEqualsFormulaEvaluation_String() { - final String formula = "IF(A1=1, B1, C1)"; - final CellType cellType = CellType.STRING; - final String expectedFormula = "IF(A1=1,B1,C1)"; - final double expectedValue = 3.0; - testIFEqualsFormulaEvaluation_eval(formula, cellType, expectedFormula, expectedValue); - } - - @Test - public void testIFEqualsFormulaEvaluation_StringCompareToString() { - final String formula = "IF(A1=\"1\", B1, C1)"; - final CellType cellType = CellType.STRING; - final String expectedFormula = "IF(A1=\"1\",B1,C1)"; - final double expectedValue = 2.0; - testIFEqualsFormulaEvaluation_eval(formula, cellType, expectedFormula, expectedValue); - } - - @Test - public void testIFEqualsFormulaEvaluation_StringCoerceToNumeric() { - final String formula = "IF(A1+0=1, B1, C1)"; - final CellType cellType = CellType.STRING; - final String expectedFormula = "IF(A1+0=1,B1,C1)"; - final double expectedValue = 2.0; - testIFEqualsFormulaEvaluation_eval(formula, cellType, expectedFormula, expectedValue); - } - - @Ignore("Bug 58591: this test currently fails") - @Test - public void testIFEqualsFormulaEvaluation_Boolean() { - final String formula = "IF(A1=1, B1, C1)"; - final CellType cellType = CellType.BOOLEAN; - final String expectedFormula = "IF(A1=1,B1,C1)"; - final double expectedValue = 2.0; - testIFEqualsFormulaEvaluation_eval(formula, cellType, expectedFormula, expectedValue); - } - - @Ignore("Bug 58591: this test currently fails") - @Test - public void testIFEqualsFormulaEvaluation_BooleanSimple() { - final String formula = "3-(A1=1)"; - final CellType cellType = CellType.BOOLEAN; - final String expectedFormula = "3-(A1=1)"; - final double expectedValue = 2.0; - testIFEqualsFormulaEvaluation_eval(formula, cellType, expectedFormula, expectedValue); - } - - @Test - public void testIFEqualsFormulaEvaluation_Formula() { - final String formula = "IF(A1=1, B1, C1)"; - final CellType cellType = CellType.FORMULA; - final String expectedFormula = "IF(A1=1,B1,C1)"; - final double expectedValue = 2.0; - testIFEqualsFormulaEvaluation_eval(formula, cellType, expectedFormula, expectedValue); - } - - @Test - public void testIFEqualsFormulaEvaluation_Blank() { - final String formula = "IF(A1=1, B1, C1)"; - final CellType cellType = CellType.BLANK; - final String expectedFormula = "IF(A1=1,B1,C1)"; - final double expectedValue = 3.0; - testIFEqualsFormulaEvaluation_eval(formula, cellType, expectedFormula, expectedValue); - } - - @Test - public void testIFEqualsFormulaEvaluation_BlankCompareToZero() { - final String formula = "IF(A1=0, B1, C1)"; - final CellType cellType = CellType.BLANK; - final String expectedFormula = "IF(A1=0,B1,C1)"; - final double expectedValue = 2.0; - testIFEqualsFormulaEvaluation_eval(formula, cellType, expectedFormula, expectedValue); - } - - @Ignore("Bug 58591: this test currently fails") - @Test - public void testIFEqualsFormulaEvaluation_BlankInverted() { - final String formula = "IF(NOT(A1)=1, B1, C1)"; - final CellType cellType = CellType.BLANK; - final String expectedFormula = "IF(NOT(A1)=1,B1,C1)"; - final double expectedValue = 2.0; - testIFEqualsFormulaEvaluation_eval(formula, cellType, expectedFormula, expectedValue); - } - - @Ignore("Bug 58591: this test currently fails") - @Test - public void testIFEqualsFormulaEvaluation_BlankInvertedSimple() { - final String formula = "3-(NOT(A1)=1)"; - final CellType cellType = CellType.BLANK; - final String expectedFormula = "3-(NOT(A1)=1)"; - final double expectedValue = 2.0; - testIFEqualsFormulaEvaluation_eval(formula, cellType, expectedFormula, expectedValue); - } - - - private void testIFEqualsFormulaEvaluation_evaluateFormulaCell( - String formula, CellType cellType, String expectedFormula, double expectedResult) { - Workbook wb = testIFEqualsFormulaEvaluation_setup(formula, cellType); - Cell D1 = wb.getSheet("IFEquals").getRow(0).getCell(3); - - FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator(); - CellType resultCellType = eval.evaluateFormulaCellEnum(D1); - - // Call should modify the contents, but leave the formula intact - assertEquals(CellType.FORMULA, D1.getCellTypeEnum()); - assertEquals(expectedFormula, D1.getCellFormula()); - assertEquals(CellType.NUMERIC, resultCellType); - assertEquals(CellType.NUMERIC, D1.getCachedFormulaResultTypeEnum()); - assertEquals(expectedResult, D1.getNumericCellValue(), EPSILON); - - testIFEqualsFormulaEvaluation_teardown(wb); - } - - private void testIFEqualsFormulaEvaluation_evaluateInCell( - String formula, CellType cellType, String expectedFormula, double expectedResult) { - Workbook wb = testIFEqualsFormulaEvaluation_setup(formula, cellType); - Cell D1 = wb.getSheet("IFEquals").getRow(0).getCell(3); - - FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator(); - Cell result = eval.evaluateInCell(D1); - - // Call should modify the contents and replace the formula with the result - assertSame(D1, result); // returns the same cell that was provided as an argument so that calls can be chained. - try { - D1.getCellFormula(); - fail("cell formula should be overwritten with formula result"); - } catch (final IllegalStateException expected) { } - assertEquals(CellType.NUMERIC, D1.getCellTypeEnum()); - assertEquals(expectedResult, D1.getNumericCellValue(), EPSILON); - - testIFEqualsFormulaEvaluation_teardown(wb); - } - - private void testIFEqualsFormulaEvaluation_evaluateAll( - String formula, CellType cellType, String expectedFormula, double expectedResult) { - Workbook wb = testIFEqualsFormulaEvaluation_setup(formula, cellType); - Cell D1 = wb.getSheet("IFEquals").getRow(0).getCell(3); - - FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator(); - eval.evaluateAll(); - - // Call should modify the contents - assertEquals(CellType.FORMULA, D1.getCellTypeEnum()); - assertEquals(expectedFormula, D1.getCellFormula()); - - assertEquals(CellType.NUMERIC, D1.getCachedFormulaResultTypeEnum()); - assertEquals(expectedResult, D1.getNumericCellValue(), EPSILON); - - testIFEqualsFormulaEvaluation_teardown(wb); - } - - private void testIFEqualsFormulaEvaluation_evaluateAllFormulaCells( - String formula, CellType cellType, String expectedFormula, double expectedResult) { - Workbook wb = testIFEqualsFormulaEvaluation_setup(formula, cellType); - Cell D1 = wb.getSheet("IFEquals").getRow(0).getCell(3); - - HSSFFormulaEvaluator.evaluateAllFormulaCells(wb); - - // Call should modify the contents - assertEquals(CellType.FORMULA, D1.getCellTypeEnum()); - // whitespace gets deleted because formula is parsed and re-rendered - assertEquals(expectedFormula, D1.getCellFormula()); - - assertEquals(CellType.NUMERIC, D1.getCachedFormulaResultTypeEnum()); - assertEquals(expectedResult, D1.getNumericCellValue(), EPSILON); - - testIFEqualsFormulaEvaluation_teardown(wb); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/WorkbookEvaluatorTestHelper.java b/src/testcases/org/apache/poi/ss/formula/WorkbookEvaluatorTestHelper.java deleted file mode 100644 index 673cb9500..000000000 --- a/src/testcases/org/apache/poi/ss/formula/WorkbookEvaluatorTestHelper.java +++ /dev/null @@ -1,37 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula; - -import org.apache.poi.hssf.usermodel.HSSFEvaluationWorkbook; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; - -/** - * Allows tests to execute {@link WorkbookEvaluator}s and track the internal workings. - * - * @author Josh Micich - */ -public final class WorkbookEvaluatorTestHelper { - - private WorkbookEvaluatorTestHelper() { - // no instances of this class - } - - public static WorkbookEvaluator createEvaluator(HSSFWorkbook wb, EvaluationListener listener) { - return new WorkbookEvaluator(HSSFEvaluationWorkbook.create(wb), listener, null, null); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/atp/TestDateParser.java b/src/testcases/org/apache/poi/ss/formula/atp/TestDateParser.java deleted file mode 100644 index 95f5ea09e..000000000 --- a/src/testcases/org/apache/poi/ss/formula/atp/TestDateParser.java +++ /dev/null @@ -1,79 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.atp; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -import java.util.Calendar; - -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.EvaluationException; -import org.apache.poi.util.LocaleUtil; -import org.junit.Test; - -public class TestDateParser { - @Test - public void testFailWhenNoDate() { - try { - DateParser.parseDate("potato"); - fail("Shouldn't parse potato!"); - } catch (EvaluationException e) { - assertEquals(ErrorEval.VALUE_INVALID, e.getErrorEval()); - } - } - - @Test - public void testFailWhenLooksLikeDateButItIsnt() { - try { - DateParser.parseDate("potato/cucumber/banana"); - fail("Shouldn't parse this thing!"); - } catch (EvaluationException e) { - assertEquals(ErrorEval.VALUE_INVALID, e.getErrorEval()); - } - } - - @Test - public void testFailWhenIsInvalidDate() { - try { - DateParser.parseDate("13/13/13"); - fail("Shouldn't parse this thing!"); - } catch (EvaluationException e) { - assertEquals(ErrorEval.VALUE_INVALID, e.getErrorEval()); - } - } - - @Test - public void testShouldParseValidDate() throws EvaluationException { - Calendar expDate = LocaleUtil.getLocaleCalendar(1984, Calendar.OCTOBER, 20); - Calendar actDate = DateParser.parseDate("1984/10/20"); - assertEquals("Had: " + expDate.getTime() + " and " + actDate.getTime() + "/" + - expDate.getTimeInMillis() + "ms and " + actDate.getTimeInMillis() + "ms", - expDate, actDate); - } - - @Test - public void testShouldIgnoreTimestamp() throws EvaluationException { - Calendar expDate = LocaleUtil.getLocaleCalendar(1984, Calendar.OCTOBER, 20); - Calendar actDate = DateParser.parseDate("1984/10/20 12:34:56"); - assertEquals("Had: " + expDate.getTime() + " and " + actDate.getTime() + "/" + - expDate.getTimeInMillis() + "ms and " + actDate.getTimeInMillis() + "ms", - expDate, actDate); - } - -} diff --git a/src/testcases/org/apache/poi/ss/formula/atp/TestIfError.java b/src/testcases/org/apache/poi/ss/formula/atp/TestIfError.java deleted file mode 100644 index 3a0a5b9b7..000000000 --- a/src/testcases/org/apache/poi/ss/formula/atp/TestIfError.java +++ /dev/null @@ -1,96 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.formula.atp; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.CellReference; - -import junit.framework.TestCase; - -/** - * Testcase for 'Analysis Toolpak' function IFERROR() - * - * @author Johan Karlsteen - */ -public class TestIfError extends TestCase { - - /** - * =IFERROR(210/35,\"Error in calculation\")" Divides 210 by 35 and returns 6.0 - * =IFERROR(55/0,\"Error in calculation\")" Divides 55 by 0 and returns the error text - * =IFERROR(C1,\"Error in calculation\")" References the result of dividing 55 by 0 and returns the error text - */ - public static void testEvaluate(){ - Workbook wb = new HSSFWorkbook(); - Sheet sh = wb.createSheet(); - Row row1 = sh.createRow(0); - Row row2 = sh.createRow(1); - - // Create cells - row1.createCell(0, CellType.NUMERIC); - row1.createCell(1, CellType.NUMERIC); - row1.createCell(2, CellType.NUMERIC); - row2.createCell(0, CellType.NUMERIC); - row2.createCell(1, CellType.NUMERIC); - - // Create references - CellReference a1 = new CellReference("A1"); - CellReference a2 = new CellReference("A2"); - CellReference b1 = new CellReference("B1"); - CellReference b2 = new CellReference("B2"); - CellReference c1 = new CellReference("C1"); - - // Set values - sh.getRow(a1.getRow()).getCell(a1.getCol()).setCellValue(210); - sh.getRow(a2.getRow()).getCell(a2.getCol()).setCellValue(55); - sh.getRow(b1.getRow()).getCell(b1.getCol()).setCellValue(35); - sh.getRow(b2.getRow()).getCell(b2.getCol()).setCellValue(0); - sh.getRow(c1.getRow()).getCell(c1.getCol()).setCellFormula("A1/B2"); - - Cell cell1 = sh.createRow(3).createCell(0); - cell1.setCellFormula("IFERROR(A1/B1,\"Error in calculation\")"); - Cell cell2 = sh.createRow(3).createCell(0); - cell2.setCellFormula("IFERROR(A2/B2,\"Error in calculation\")"); - Cell cell3 = sh.createRow(3).createCell(0); - cell3.setCellFormula("IFERROR(C1,\"error\")"); - - double accuracy = 1E-9; - - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - - assertEquals("Checks that the cell is numeric", - CellType.NUMERIC, evaluator.evaluate(cell1).getCellTypeEnum()); - assertEquals("Divides 210 by 35 and returns 6.0", - 6.0, evaluator.evaluate(cell1).getNumberValue(), accuracy); - - - assertEquals("Checks that the cell is numeric", - CellType.STRING, evaluator.evaluate(cell2).getCellTypeEnum()); - assertEquals("Rounds -10 to a nearest multiple of -3 (-9)", - "Error in calculation", evaluator.evaluate(cell2).getStringValue()); - - assertEquals("Check that C1 returns string", - CellType.STRING, evaluator.evaluate(cell3).getCellTypeEnum()); - assertEquals("Check that C1 returns string \"error\"", - "error", evaluator.evaluate(cell3).getStringValue()); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/atp/TestMRound.java b/src/testcases/org/apache/poi/ss/formula/atp/TestMRound.java deleted file mode 100644 index 2338fbbe6..000000000 --- a/src/testcases/org/apache/poi/ss/formula/atp/TestMRound.java +++ /dev/null @@ -1,70 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.formula.atp; - -import junit.framework.TestCase; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.usermodel.*; - -/** - * Testcase for 'Analysis Toolpak' function MROUND() - * - * @author Yegor Kozlov - */ -public class TestMRound extends TestCase { - - /** -=MROUND(10, 3) Rounds 10 to a nearest multiple of 3 (9) -=MROUND(-10, -3) Rounds -10 to a nearest multiple of -3 (-9) -=MROUND(1.3, 0.2) Rounds 1.3 to a nearest multiple of 0.2 (1.4) -=MROUND(5, -2) Returns an error, because -2 and 5 have different signs (#NUM!) * - */ - public static void testEvaluate(){ - Workbook wb = new HSSFWorkbook(); - Sheet sh = wb.createSheet(); - Cell cell1 = sh.createRow(0).createCell(0); - cell1.setCellFormula("MROUND(10, 3)"); - Cell cell2 = sh.createRow(0).createCell(0); - cell2.setCellFormula("MROUND(-10, -3)"); - Cell cell3 = sh.createRow(0).createCell(0); - cell3.setCellFormula("MROUND(1.3, 0.2)"); - Cell cell4 = sh.createRow(0).createCell(0); - cell4.setCellFormula("MROUND(5, -2)"); - Cell cell5 = sh.createRow(0).createCell(0); - cell5.setCellFormula("MROUND(5, 0)"); - - double accuracy = 1E-9; - - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - - assertEquals("Rounds 10 to a nearest multiple of 3 (9)", - 9.0, evaluator.evaluate(cell1).getNumberValue(), accuracy); - - assertEquals("Rounds -10 to a nearest multiple of -3 (-9)", - -9.0, evaluator.evaluate(cell2).getNumberValue(), accuracy); - - assertEquals("Rounds 1.3 to a nearest multiple of 0.2 (1.4)", - 1.4, evaluator.evaluate(cell3).getNumberValue(), accuracy); - - assertEquals("Returns an error, because -2 and 5 have different signs (#NUM!)", - ErrorEval.NUM_ERROR.getErrorCode(), evaluator.evaluate(cell4).getErrorValue()); - - assertEquals("Returns 0 because the multiple is 0", - 0.0, evaluator.evaluate(cell5).getNumberValue()); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/atp/TestNetworkdaysFunction.java b/src/testcases/org/apache/poi/ss/formula/atp/TestNetworkdaysFunction.java deleted file mode 100644 index f92204d87..000000000 --- a/src/testcases/org/apache/poi/ss/formula/atp/TestNetworkdaysFunction.java +++ /dev/null @@ -1,126 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.atp; - -import static org.apache.poi.ss.formula.eval.ErrorEval.NAME_INVALID; -import static org.apache.poi.ss.formula.eval.ErrorEval.VALUE_INVALID; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.ss.formula.OperationEvaluationContext; -import org.apache.poi.ss.formula.TwoDEval; -import org.apache.poi.ss.formula.eval.AreaEval; -import org.apache.poi.ss.formula.eval.AreaEvalBase; -import org.apache.poi.ss.formula.eval.NumericValueEval; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; - -import junit.framework.TestCase; - -public class TestNetworkdaysFunction extends TestCase { - - private static final String STARTING_DATE = "2008/10/01"; - private static final String END_DATE = "2009/03/01"; - private static final String FIRST_HOLIDAY = "2008/11/26"; - private static final String SECOND_HOLIDAY = "2008/12/04"; - private static final String THIRD_HOLIDAY = "2009/01/21"; - - private static final OperationEvaluationContext EC = new OperationEvaluationContext(null, null, 1, 1, 1, null); - - public void testFailWhenNoArguments() { - assertEquals(VALUE_INVALID, NetworkdaysFunction.instance.evaluate(new ValueEval[0], null)); - } - - public void testFailWhenLessThan2Arguments() { - assertEquals(VALUE_INVALID, NetworkdaysFunction.instance.evaluate(new ValueEval[1], null)); - } - - public void testFailWhenMoreThan3Arguments() { - assertEquals(VALUE_INVALID, NetworkdaysFunction.instance.evaluate(new ValueEval[4], null)); - } - - public void testFailWhenArgumentsAreNotDates() { - assertEquals(VALUE_INVALID, NetworkdaysFunction.instance.evaluate(new ValueEval[]{ new StringEval("Potato"), - new StringEval("Cucumber") }, EC)); - } - - public void testFailWhenStartDateAfterEndDate() { - assertEquals(NAME_INVALID, NetworkdaysFunction.instance.evaluate(new ValueEval[]{ new StringEval(END_DATE), - new StringEval(STARTING_DATE) }, EC)); - } - - public void testReturnNetworkdays() { - assertEquals(108, (int) ((NumericValueEval) NetworkdaysFunction.instance.evaluate(new ValueEval[]{ - new StringEval(STARTING_DATE), new StringEval(END_DATE) }, EC)).getNumberValue()); - } - - public void testReturnNetworkdaysWithAHoliday() { - assertEquals(107, (int) ((NumericValueEval) NetworkdaysFunction.instance.evaluate(new ValueEval[]{ - new StringEval(STARTING_DATE), new StringEval(END_DATE), new StringEval(FIRST_HOLIDAY) }, - EC)).getNumberValue()); - } - - public void testReturnNetworkdaysWithManyHolidays() { - assertEquals(105, (int) ((NumericValueEval) NetworkdaysFunction.instance.evaluate(new ValueEval[]{ - new StringEval(STARTING_DATE), new StringEval(END_DATE), - new MockAreaEval(FIRST_HOLIDAY, SECOND_HOLIDAY, THIRD_HOLIDAY) }, EC)).getNumberValue()); - } - - private class MockAreaEval extends AreaEvalBase { - - private List holidays; - - public MockAreaEval(String... holidays) { - this(0, 0, 0, holidays.length - 1); - this.holidays = new ArrayList(); - for (String holiday : holidays) { - this.holidays.add(new StringEval(holiday)); - } - } - - protected MockAreaEval(int firstRow, int firstColumn, int lastRow, int lastColumn) { - super(firstRow, firstColumn, lastRow, lastColumn); - } - - @Override - public ValueEval getRelativeValue(int sheetIndex, int relativeRowIndex, int relativeColumnIndex) { - return this.holidays.get(relativeColumnIndex); - } - @Override - public ValueEval getRelativeValue(int relativeRowIndex, int relativeColumnIndex) { - return getRelativeValue(-1, relativeRowIndex, relativeColumnIndex); - } - - @Override - public AreaEval offset(int relFirstRowIx, int relLastRowIx, int relFirstColIx, int relLastColIx) { - return null; - } - - @Override - public TwoDEval getColumn(int columnIndex) { - return null; - } - - @Override - public TwoDEval getRow(int rowIndex) { - return null; - } - - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/atp/TestPercentile.java b/src/testcases/org/apache/poi/ss/formula/atp/TestPercentile.java deleted file mode 100644 index 8107d97e7..000000000 --- a/src/testcases/org/apache/poi/ss/formula/atp/TestPercentile.java +++ /dev/null @@ -1,112 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.formula.atp; - -import org.apache.poi.ss.formula.eval.AreaEval; -import org.apache.poi.ss.formula.eval.BlankEval; -import org.apache.poi.ss.formula.eval.BoolEval; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.ss.formula.functions.AggregateFunction; -import org.apache.poi.ss.formula.functions.EvalFactory; - -import junit.framework.TestCase; - -/** - * Testcase for Excel function PERCENTILE() - * - * @author T. Gordon - */ -public class TestPercentile extends TestCase { - - public void testPercentile() { - testBasic(); - testUnusualArgs(); - testUnusualArgs2(); - testUnusualArgs3(); - testErrors(); - testErrors2(); - } - - private static ValueEval invokePercentile(ValueEval[] args, ValueEval percentile) { - AreaEval aeA = EvalFactory.createAreaEval("A1:A" + args.length, args); - ValueEval[] args2 = { aeA, percentile }; - return AggregateFunction.PERCENTILE.evaluate(args2, -1, -1); - } - - private void confirmPercentile(ValueEval percentile, ValueEval[] args, double expected) { - ValueEval result = invokePercentile(args, percentile); - assertEquals(NumberEval.class, result.getClass()); - double delta = 0.00000001; - assertEquals(expected, ((NumberEval) result).getNumberValue(), delta); - } - - private void confirmPercentile(ValueEval percentile, ValueEval[] args, ErrorEval expectedError) { - ValueEval result = invokePercentile(args, percentile); - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(expectedError.getErrorCode(), ((ErrorEval) result).getErrorCode()); - } - - public void testBasic() { - ValueEval[] values = { new NumberEval(210.128), new NumberEval(65.2182), new NumberEval(32.231), - new NumberEval(12.123), new NumberEval(45.32) }; - ValueEval percentile = new NumberEval(0.95); - confirmPercentile(percentile, values, 181.14604); - } - - public void testBlanks() { - ValueEval[] values = { new NumberEval(210.128), new NumberEval(65.2182), new NumberEval(32.231), - BlankEval.instance, new NumberEval(45.32) }; - ValueEval percentile = new NumberEval(0.95); - confirmPercentile(percentile, values, 188.39153); - } - - public void testUnusualArgs() { - ValueEval[] values = { new NumberEval(1), new NumberEval(2), BoolEval.TRUE, BoolEval.FALSE }; - ValueEval percentile = new NumberEval(0.95); - confirmPercentile(percentile, values, 1.95); - } - - //percentile has to be between 0 and 1 - here we test less than zero - public void testUnusualArgs2() { - ValueEval[] values = { new NumberEval(1), new NumberEval(2), }; - ValueEval percentile = new NumberEval(-0.1); - confirmPercentile(percentile, values, ErrorEval.NUM_ERROR); - } - - //percentile has to be between 0 and 1 - here we test more than 1 - public void testUnusualArgs3() { - ValueEval[] values = { new NumberEval(1), new NumberEval(2) }; - ValueEval percentile = new NumberEval(1.1); - confirmPercentile(percentile, values, ErrorEval.NUM_ERROR); - } - - //here we test where there are errors as part of inputs - public void testErrors() { - ValueEval[] values = { new NumberEval(1), ErrorEval.NAME_INVALID, new NumberEval(3), ErrorEval.DIV_ZERO, }; - ValueEval percentile = new NumberEval(0.95); - confirmPercentile(percentile, values, ErrorEval.NAME_INVALID); - } - - //here we test where there are errors as part of inputs - public void testErrors2() { - ValueEval[] values = { new NumberEval(1), new NumberEval(2), new NumberEval(3), ErrorEval.DIV_ZERO, }; - ValueEval percentile = new NumberEval(0.95); - confirmPercentile(percentile, values, ErrorEval.DIV_ZERO); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/atp/TestRandBetween.java b/src/testcases/org/apache/poi/ss/formula/atp/TestRandBetween.java deleted file mode 100644 index 51bbdf098..000000000 --- a/src/testcases/org/apache/poi/ss/formula/atp/TestRandBetween.java +++ /dev/null @@ -1,194 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.formula.atp; - -import junit.framework.TestCase; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; - -/** - * Testcase for 'Analysis Toolpak' function RANDBETWEEN() - * - * @author Brendan Nolan - */ -public class TestRandBetween extends TestCase { - - private Workbook wb; - private FormulaEvaluator evaluator; - private Cell bottomValueCell; - private Cell topValueCell; - private Cell formulaCell; - - @Override - protected void setUp() throws Exception { - super.setUp(); - wb = HSSFTestDataSamples.openSampleWorkbook("TestRandBetween.xls"); - evaluator = wb.getCreationHelper().createFormulaEvaluator(); - - Sheet sheet = wb.createSheet("RandBetweenSheet"); - Row row = sheet.createRow(0); - bottomValueCell = row.createCell(0); - topValueCell = row.createCell(1); - formulaCell = row.createCell(2, CellType.FORMULA); - } - - @Override - protected void tearDown() throws Exception { - // TODO Auto-generated method stub - super.tearDown(); - } - - /** - * Check where values are the same - */ - public void testRandBetweenSameValues() { - - evaluator.clearAllCachedResultValues(); - formulaCell.setCellFormula("RANDBETWEEN(1,1)"); - evaluator.evaluateFormulaCellEnum(formulaCell); - assertEquals(1, formulaCell.getNumericCellValue(), 0); - evaluator.clearAllCachedResultValues(); - formulaCell.setCellFormula("RANDBETWEEN(-1,-1)"); - evaluator.evaluateFormulaCellEnum(formulaCell); - assertEquals(-1, formulaCell.getNumericCellValue(), 0); - - } - - /** - * Check special case where rounded up bottom value is greater than - * top value. - */ - public void testRandBetweenSpecialCase() { - - - bottomValueCell.setCellValue(0.05); - topValueCell.setCellValue(0.1); - formulaCell.setCellFormula("RANDBETWEEN($A$1,$B$1)"); - evaluator.clearAllCachedResultValues(); - evaluator.evaluateFormulaCellEnum(formulaCell); - assertEquals(1, formulaCell.getNumericCellValue(), 0); - bottomValueCell.setCellValue(-0.1); - topValueCell.setCellValue(-0.05); - formulaCell.setCellFormula("RANDBETWEEN($A$1,$B$1)"); - evaluator.clearAllCachedResultValues(); - evaluator.evaluateFormulaCellEnum(formulaCell); - assertEquals(0, formulaCell.getNumericCellValue(), 0); - bottomValueCell.setCellValue(-1.1); - topValueCell.setCellValue(-1.05); - formulaCell.setCellFormula("RANDBETWEEN($A$1,$B$1)"); - evaluator.clearAllCachedResultValues(); - evaluator.evaluateFormulaCellEnum(formulaCell); - assertEquals(-1, formulaCell.getNumericCellValue(), 0); - bottomValueCell.setCellValue(-1.1); - topValueCell.setCellValue(-1.1); - formulaCell.setCellFormula("RANDBETWEEN($A$1,$B$1)"); - evaluator.clearAllCachedResultValues(); - evaluator.evaluateFormulaCellEnum(formulaCell); - assertEquals(-1, formulaCell.getNumericCellValue(), 0); - } - - /** - * Check top value of BLANK which Excel will evaluate as 0 - */ - public void testRandBetweenTopBlank() { - - bottomValueCell.setCellValue(-1); - topValueCell.setCellType(CellType.BLANK); - formulaCell.setCellFormula("RANDBETWEEN($A$1,$B$1)"); - evaluator.clearAllCachedResultValues(); - evaluator.evaluateFormulaCellEnum(formulaCell); - assertTrue(formulaCell.getNumericCellValue() == 0 || formulaCell.getNumericCellValue() == -1); - - } - /** - * Check where input values are of wrong type - */ - public void testRandBetweenWrongInputTypes() { - // Check case where bottom input is of the wrong type - bottomValueCell.setCellValue("STRING"); - topValueCell.setCellValue(1); - formulaCell.setCellFormula("RANDBETWEEN($A$1,$B$1)"); - evaluator.clearAllCachedResultValues(); - evaluator.evaluateFormulaCellEnum(formulaCell); - assertEquals(CellType.ERROR, formulaCell.getCachedFormulaResultTypeEnum()); - assertEquals(ErrorEval.VALUE_INVALID.getErrorCode(), formulaCell.getErrorCellValue()); - - - // Check case where top input is of the wrong type - bottomValueCell.setCellValue(1); - topValueCell.setCellValue("STRING"); - formulaCell.setCellFormula("RANDBETWEEN($A$1,$B$1)"); - evaluator.clearAllCachedResultValues(); - evaluator.evaluateFormulaCellEnum(formulaCell); - assertEquals(CellType.ERROR, formulaCell.getCachedFormulaResultTypeEnum()); - assertEquals(ErrorEval.VALUE_INVALID.getErrorCode(), formulaCell.getErrorCellValue()); - - // Check case where both inputs are of wrong type - bottomValueCell.setCellValue("STRING"); - topValueCell.setCellValue("STRING"); - formulaCell.setCellFormula("RANDBETWEEN($A$1,$B$1)"); - evaluator.clearAllCachedResultValues(); - evaluator.evaluateFormulaCellEnum(formulaCell); - assertEquals(CellType.ERROR, formulaCell.getCachedFormulaResultTypeEnum()); - assertEquals(ErrorEval.VALUE_INVALID.getErrorCode(), formulaCell.getErrorCellValue()); - - } - - /** - * Check case where bottom is greater than top - */ - public void testRandBetweenBottomGreaterThanTop() { - - // Check case where bottom is greater than top - bottomValueCell.setCellValue(1); - topValueCell.setCellValue(0); - formulaCell.setCellFormula("RANDBETWEEN($A$1,$B$1)"); - evaluator.clearAllCachedResultValues(); - evaluator.evaluateFormulaCellEnum(formulaCell); - assertEquals(CellType.ERROR, formulaCell.getCachedFormulaResultTypeEnum()); - assertEquals(ErrorEval.NUM_ERROR.getErrorCode(), formulaCell.getErrorCellValue()); - bottomValueCell.setCellValue(1); - topValueCell.setCellType(CellType.BLANK); - formulaCell.setCellFormula("RANDBETWEEN($A$1,$B$1)"); - evaluator.clearAllCachedResultValues(); - evaluator.evaluateFormulaCellEnum(formulaCell); - assertEquals(CellType.ERROR, formulaCell.getCachedFormulaResultTypeEnum()); - assertEquals(ErrorEval.NUM_ERROR.getErrorCode(), formulaCell.getErrorCellValue()); - } - - /** - * Boundary check of Double MIN and MAX values - */ - public void testRandBetweenBoundaryCheck() { - - bottomValueCell.setCellValue(Double.MIN_VALUE); - topValueCell.setCellValue(Double.MAX_VALUE); - formulaCell.setCellFormula("RANDBETWEEN($A$1,$B$1)"); - evaluator.clearAllCachedResultValues(); - evaluator.evaluateFormulaCellEnum(formulaCell); - assertTrue(formulaCell.getNumericCellValue() >= Double.MIN_VALUE && formulaCell.getNumericCellValue() <= Double.MAX_VALUE); - - } - -} diff --git a/src/testcases/org/apache/poi/ss/formula/atp/TestWorkdayCalculator.java b/src/testcases/org/apache/poi/ss/formula/atp/TestWorkdayCalculator.java deleted file mode 100644 index 80adae743..000000000 --- a/src/testcases/org/apache/poi/ss/formula/atp/TestWorkdayCalculator.java +++ /dev/null @@ -1,167 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.atp; - -import static java.util.Calendar.SATURDAY; -import static org.junit.Assert.assertEquals; - -import java.util.Calendar; -import java.util.Date; - -import org.apache.poi.ss.usermodel.DateUtil; -import org.apache.poi.util.LocaleUtil; -import org.junit.Test; - -public class TestWorkdayCalculator { - - @Test - public void testCalculateWorkdaysShouldReturnJustWeekdaysWhenNoWeekend() { - final double A_MONDAY = DateUtil.getExcelDate(d(2011, 12, 12)); - final double A_FRIDAY = DateUtil.getExcelDate(d(2011, 12, 16)); - assertEquals(5, WorkdayCalculator.instance.calculateWorkdays(A_MONDAY, A_FRIDAY, new double[0])); - } - - @Test - public void testCalculateWorkdaysShouldReturnAllDaysButNoSaturdays() { - final double A_WEDNESDAY = DateUtil.getExcelDate(d(2011, 12, 14)); - final double A_SATURDAY = DateUtil.getExcelDate(d(2011, 12, 18)); - assertEquals(3, WorkdayCalculator.instance.calculateWorkdays(A_WEDNESDAY, A_SATURDAY, new double[0])); - } - - @Test - public void testCalculateWorkdaysShouldReturnAllDaysButNoSundays() { - final double A_SUNDAY = DateUtil.getExcelDate(d(2011, 12, 11)); - final double A_THURSDAY = DateUtil.getExcelDate(d(2011, 12, 15)); - assertEquals(4, WorkdayCalculator.instance.calculateWorkdays(A_SUNDAY, A_THURSDAY, new double[0])); - } - - @Test - public void testCalculateWorkdaysShouldReturnAllDaysButNoHolidays() { - final double A_MONDAY = DateUtil.getExcelDate(d(2011, 12, 12)); - final double A_FRIDAY = DateUtil.getExcelDate(d(2011, 12, 16)); - final double A_WEDNESDAY = DateUtil.getExcelDate(d(2011, 12, 14)); - assertEquals(4, WorkdayCalculator.instance.calculateWorkdays(A_MONDAY, A_FRIDAY, new double[]{ A_WEDNESDAY })); - } - - @Test - public void testCalculateWorkdaysShouldIgnoreWeekendHolidays() { - final double A_FRIDAY = DateUtil.getExcelDate(d(2011, 12, 16)); - final double A_SATURDAY = DateUtil.getExcelDate(d(2011, 12, 17)); - final double A_SUNDAY = DateUtil.getExcelDate(d(2011, 12, 18)); - final double A_WEDNESDAY = DateUtil.getExcelDate(d(2011, 12, 21)); - assertEquals(4, WorkdayCalculator.instance.calculateWorkdays(A_FRIDAY, A_WEDNESDAY, new double[]{ A_SATURDAY, A_SUNDAY })); - } - - @Test - public void testCalculateWorkdaysOnSameDayShouldReturn1ForWeekdays() { - final double A_MONDAY = DateUtil.getExcelDate(d(2017, 1, 2)); - assertEquals(1, WorkdayCalculator.instance.calculateWorkdays(A_MONDAY, A_MONDAY, new double[0])); - } - - @Test - public void testCalculateWorkdaysOnSameDayShouldReturn0ForHolidays() { - final double A_MONDAY = DateUtil.getExcelDate(d(2017, 1, 2)); - assertEquals(0, WorkdayCalculator.instance.calculateWorkdays(A_MONDAY, A_MONDAY, new double[]{ A_MONDAY })); - } - - @Test - public void testCalculateWorkdaysOnSameDayShouldReturn0ForWeekends() { - final double A_SUNDAY = DateUtil.getExcelDate(d(2017, 1, 1)); - assertEquals(0, WorkdayCalculator.instance.calculateWorkdays(A_SUNDAY, A_SUNDAY, new double[0])); - } - - @Test - public void testCalculateWorkdaysNumberOfDays() { - double start = 41553.0; - int days = 1; - assertEquals(d(2013, 10, 7), WorkdayCalculator.instance.calculateWorkdays(start, days, new double[0])); - } - - @Test - public void testPastDaysOfWeekShouldReturn0Past0Saturdays() { - final double A_WEDNESDAY = DateUtil.getExcelDate(d(2011, 12, 7)); - final double A_FRIDAY = DateUtil.getExcelDate(d(2011, 12, 9)); - assertEquals(0, WorkdayCalculator.instance.pastDaysOfWeek(A_WEDNESDAY, A_FRIDAY, SATURDAY)); - } - - @Test - public void testPastDaysOfWeekShouldReturn1Past1Saturdays() { - final double A_WEDNESDAY = DateUtil.getExcelDate(d(2011, 12, 7)); - final double A_SUNDAY = DateUtil.getExcelDate(d(2011, 12, 11)); - assertEquals(1, WorkdayCalculator.instance.pastDaysOfWeek(A_WEDNESDAY, A_SUNDAY, SATURDAY)); - } - - @Test - public void testPastDaysOfWeekShouldReturn2Past2Saturdays() { - final double A_THURSDAY = DateUtil.getExcelDate(d(2011, 12, 8)); - final double A_MONDAY = DateUtil.getExcelDate(d(2011, 12, 19)); - assertEquals(2, WorkdayCalculator.instance.pastDaysOfWeek(A_THURSDAY, A_MONDAY, SATURDAY)); - } - - @Test - public void testPastDaysOfWeekShouldReturn1BeginningFromASaturday() { - final double A_SATURDAY = DateUtil.getExcelDate(d(2011, 12, 10)); - final double A_SUNDAY = DateUtil.getExcelDate(d(2011, 12, 11)); - assertEquals(1, WorkdayCalculator.instance.pastDaysOfWeek(A_SATURDAY, A_SUNDAY, SATURDAY)); - } - - @Test - public void testPastDaysOfWeekShouldReturn1EndingAtASaturday() { - final double A_THURSDAY = DateUtil.getExcelDate(d(2011, 12, 8)); - final double A_SATURDAY = DateUtil.getExcelDate(d(2011, 12, 10)); - assertEquals(1, WorkdayCalculator.instance.pastDaysOfWeek(A_THURSDAY, A_SATURDAY, SATURDAY)); - } - - private static Date d(int year, int month, int day) { - Calendar cal = LocaleUtil.getLocaleCalendar(year, month-1, day, 0, 0, 0); - return cal.getTime(); - } - - @Test - public void testCalculateNonWeekendHolidays() { - final double start = DateUtil.getExcelDate(d(2016, 12, 24)); - final double end = DateUtil.getExcelDate(d(2016, 12, 31)); - final double holiday1 = DateUtil.getExcelDate(d(2016, 12, 25)); - final double holiday2 = DateUtil.getExcelDate(d(2016, 12, 26)); - int count = WorkdayCalculator.instance.calculateNonWeekendHolidays(start, end, new double[]{holiday1, holiday2}); - assertEquals("Expected 1 non-weekend-holiday for " + start + " to " + end + " and " + holiday1 + " and " + holiday2, - 1, count); - } - - @Test - public void testCalculateNonWeekendHolidaysOneDay() { - final double start = DateUtil.getExcelDate(d(2016, 12, 26)); - final double end = DateUtil.getExcelDate(d(2016, 12, 26)); - final double holiday1 = DateUtil.getExcelDate(d(2016, 12, 25)); - final double holiday2 = DateUtil.getExcelDate(d(2016, 12, 26)); - int count = WorkdayCalculator.instance.calculateNonWeekendHolidays(start, end, new double[]{holiday1, holiday2}); - assertEquals("Expected 1 non-weekend-holiday for " + start + " to " + end + " and " + holiday1 + " and " + holiday2, - 1, count); - } - - @SuppressWarnings("deprecation") - @Test - public void testIsNonWorkday() throws Exception { - final double weekend = DateUtil.getExcelDate(d(2016, 12, 25)); - final double holiday = DateUtil.getExcelDate(d(2016, 12, 26)); - final double workday = DateUtil.getExcelDate(d(2016, 12, 27)); - assertEquals(1, WorkdayCalculator.instance.isNonWorkday(weekend, new double[]{holiday})); - assertEquals(1, WorkdayCalculator.instance.isNonWorkday(holiday, new double[]{holiday})); - assertEquals(0, WorkdayCalculator.instance.isNonWorkday(workday, new double[]{holiday})); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/atp/TestWorkdayFunction.java b/src/testcases/org/apache/poi/ss/formula/atp/TestWorkdayFunction.java deleted file mode 100644 index bbd6e56aa..000000000 --- a/src/testcases/org/apache/poi/ss/formula/atp/TestWorkdayFunction.java +++ /dev/null @@ -1,215 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - - -package org.apache.poi.ss.formula.atp; - - -import static org.apache.poi.ss.formula.eval.ErrorEval.VALUE_INVALID; -import static org.junit.Assert.assertEquals; - -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Date; -import java.util.List; - -import org.apache.poi.ss.formula.OperationEvaluationContext; -import org.apache.poi.ss.formula.TwoDEval; -import org.apache.poi.ss.formula.eval.AreaEval; -import org.apache.poi.ss.formula.eval.AreaEvalBase; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.ss.usermodel.DateUtil; -import org.apache.poi.util.LocaleUtil; -import org.junit.Test; - -public class TestWorkdayFunction { - - private static final String STARTING_DATE = "2008/10/01"; - private static final String FIRST_HOLIDAY = "2008/11/26"; - private static final String SECOND_HOLIDAY = "2008/12/04"; - private static final String THIRD_HOLIDAY = "2009/01/21"; - private static final String RETROATIVE_HOLIDAY = "2008/09/29"; - - private static final OperationEvaluationContext EC = new OperationEvaluationContext(null, null, 1, 1, 1, null); - - @Test - public void testFailWhenNoArguments() { - ValueEval ve[] = new ValueEval[0]; - assertEquals(VALUE_INVALID, WorkdayFunction.instance.evaluate(ve, null)); - } - - @Test - public void testFailWhenLessThan2Arguments() { - ValueEval ve[] = new ValueEval[1]; - assertEquals(VALUE_INVALID, WorkdayFunction.instance.evaluate(ve, null)); - } - - @Test - public void testFailWhenMoreThan3Arguments() { - ValueEval ve[] = new ValueEval[4]; - assertEquals(VALUE_INVALID, WorkdayFunction.instance.evaluate(ve, null)); - } - - @Test - public void testFailWhenArgumentsAreNotDatesNorNumbers() { - ValueEval ve[] = { new StringEval("Potato"), new StringEval("Cucumber") }; - assertEquals(VALUE_INVALID, WorkdayFunction.instance.evaluate(ve, EC)); - } - - @Test - public void testReturnWorkdays() { - Calendar expCal = LocaleUtil.getLocaleCalendar(2009, 3, 30); - Date expDate = expCal.getTime(); - ValueEval ve[] = { new StringEval(STARTING_DATE), new NumberEval(151) }; - Date actDate = DateUtil.getJavaDate(((NumberEval) WorkdayFunction.instance.evaluate(ve, EC)).getNumberValue()); - assertEquals(expDate, actDate); - } - - @Test - public void testReturnWorkdaysSpanningAWeekendSubtractingDays() { - Calendar expCal = LocaleUtil.getLocaleCalendar(2013, 8, 27); - Date expDate = expCal.getTime(); - - ValueEval ve[] = { new StringEval("2013/09/30"), new NumberEval(-1) }; - double numberValue = ((NumberEval) WorkdayFunction.instance.evaluate(ve, EC)).getNumberValue(); - assertEquals(41544.0, numberValue, 0); - - Date actDate = DateUtil.getJavaDate(numberValue); - assertEquals(expDate, actDate); - } - - @Test - public void testReturnWorkdaysSpanningAWeekendAddingDays() { - Calendar expCal = LocaleUtil.getLocaleCalendar(2013, 8, 30); - Date expDate = expCal.getTime(); - - ValueEval ve[] = { new StringEval("2013/09/27"), new NumberEval(1) }; - double numberValue = ((NumberEval) WorkdayFunction.instance.evaluate(ve, EC)).getNumberValue(); - assertEquals(41547.0, numberValue, 0); - - Date actDate = DateUtil.getJavaDate(numberValue); - assertEquals(expDate, actDate); - } - - @Test - public void testReturnWorkdaysWhenStartIsWeekendAddingDays() { - Calendar expCal = LocaleUtil.getLocaleCalendar(2013, 9, 7); - Date expDate = expCal.getTime(); - - ValueEval ve[] = { new StringEval("2013/10/06"), new NumberEval(1) }; - double numberValue = ((NumberEval) WorkdayFunction.instance.evaluate(ve, EC)).getNumberValue(); - assertEquals(41554.0, numberValue, 0); - - Date actDate = DateUtil.getJavaDate(numberValue); - assertEquals(expDate, actDate); - } - - @Test - public void testReturnWorkdaysWhenStartIsWeekendSubtractingDays() { - Calendar expCal = LocaleUtil.getLocaleCalendar(2013, 9, 4); - Date expDate = expCal.getTime(); - - ValueEval ve[] = { new StringEval("2013/10/06"), new NumberEval(-1) }; - double numberValue = ((NumberEval) WorkdayFunction.instance.evaluate(ve, EC)).getNumberValue(); - assertEquals(41551.0, numberValue, 0); - - Date actDate = DateUtil.getJavaDate(numberValue); - assertEquals(expDate, actDate); - } - - @Test - public void testReturnWorkdaysWithDaysTruncated() { - Calendar expCal = LocaleUtil.getLocaleCalendar(2009, 3, 30); - Date expDate = expCal.getTime(); - - ValueEval ve[] = { new StringEval(STARTING_DATE), new NumberEval(151.99999) }; - double numberValue = ((NumberEval) WorkdayFunction.instance.evaluate(ve, EC)).getNumberValue(); - - Date actDate = DateUtil.getJavaDate(numberValue); - assertEquals(expDate, actDate); - } - - @Test - public void testReturnRetroativeWorkday() { - Calendar expCal = LocaleUtil.getLocaleCalendar(2008, 8, 23); - Date expDate = expCal.getTime(); - - ValueEval ve[] = { new StringEval(STARTING_DATE), new NumberEval(-5), new StringEval(RETROATIVE_HOLIDAY) }; - double numberValue = ((NumberEval) WorkdayFunction.instance.evaluate(ve, EC)).getNumberValue(); - - Date actDate = DateUtil.getJavaDate(numberValue); - assertEquals(expDate, actDate); - } - - @Test - public void testReturnNetworkdaysWithManyHolidays() { - Calendar expCal = LocaleUtil.getLocaleCalendar(2009, 4, 5); - Date expDate = expCal.getTime(); - - ValueEval ve[] = { - new StringEval(STARTING_DATE), new NumberEval(151), - new MockAreaEval(FIRST_HOLIDAY, SECOND_HOLIDAY, THIRD_HOLIDAY) }; - double numberValue = ((NumberEval) WorkdayFunction.instance.evaluate(ve, EC)).getNumberValue(); - - Date actDate = DateUtil.getJavaDate(numberValue); - assertEquals(expDate, actDate); - } - - private class MockAreaEval extends AreaEvalBase { - - private List holidays; - - public MockAreaEval(String... holidays) { - this(0, 0, 0, holidays.length - 1); - this.holidays = new ArrayList(); - for (String holiday : holidays) { - this.holidays.add(new StringEval(holiday)); - } - } - - protected MockAreaEval(int firstRow, int firstColumn, int lastRow, int lastColumn) { - super(firstRow, firstColumn, lastRow, lastColumn); - } - - @Override - public ValueEval getRelativeValue(int sheetIndex, int relativeRowIndex, int relativeColumnIndex) { - return this.holidays.get(relativeColumnIndex); - } - @Override - public ValueEval getRelativeValue(int relativeRowIndex, int relativeColumnIndex) { - return getRelativeValue(-1, relativeRowIndex, relativeColumnIndex); - } - - @Override - public AreaEval offset(int relFirstRowIx, int relLastRowIx, int relFirstColIx, int relLastColIx) { - return null; - } - - @Override - public TwoDEval getColumn(int columnIndex) { - return null; - } - - @Override - public TwoDEval getRow(int rowIndex) { - return null; - } - - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/atp/TestYearFracCalculator.java b/src/testcases/org/apache/poi/ss/formula/atp/TestYearFracCalculator.java deleted file mode 100644 index 6094d1860..000000000 --- a/src/testcases/org/apache/poi/ss/formula/atp/TestYearFracCalculator.java +++ /dev/null @@ -1,66 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.atp; - -import static org.junit.Assert.assertEquals; - -import java.util.Calendar; - -import org.apache.poi.ss.formula.eval.EvaluationException; -import org.apache.poi.ss.usermodel.DateUtil; -import org.apache.poi.util.LocaleUtil; -import org.junit.Test; - -/** - * Specific test cases for YearFracCalculator - */ -public final class TestYearFracCalculator { - - @Test - public void testBasis1() { - confirm(md(1999, 1, 1), md(1999, 4, 5), 1, 0.257534247); - confirm(md(1999, 4, 1), md(1999, 4, 5), 1, 0.010958904); - confirm(md(1999, 4, 1), md(1999, 4, 4), 1, 0.008219178); - confirm(md(1999, 4, 2), md(1999, 4, 5), 1, 0.008219178); - confirm(md(1999, 3, 31), md(1999, 4, 3), 1, 0.008219178); - confirm(md(1999, 4, 5), md(1999, 4, 8), 1, 0.008219178); - confirm(md(1999, 4, 4), md(1999, 4, 7), 1, 0.008219178); - confirm(md(2000, 2, 5), md(2000, 6, 1), 0, 0.322222222); - } - - private void confirm(double startDate, double endDate, int basis, double expectedValue) { - double actualValue; - try { - actualValue = YearFracCalculator.calculate(startDate, endDate, basis); - } catch (EvaluationException e) { - throw new RuntimeException(e); - } - double diff = actualValue - expectedValue; - if (Math.abs(diff) > 0.000000001) { - double hours = diff * 365 * 24; - System.out.println(startDate + " " + endDate + " off by " + hours + " hours"); - assertEquals(expectedValue, actualValue, 0.000000001); - } - - } - - private static double md(int year, int month, int day) { - Calendar c = LocaleUtil.getLocaleCalendar(year, month-1, day); - return DateUtil.getExcelDate(c.getTime()); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/atp/TestYearFracCalculatorFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/atp/TestYearFracCalculatorFromSpreadsheet.java deleted file mode 100644 index f683e5dbf..000000000 --- a/src/testcases/org/apache/poi/ss/formula/atp/TestYearFracCalculatorFromSpreadsheet.java +++ /dev/null @@ -1,116 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.atp; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.util.Calendar; -import java.util.Iterator; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFDateUtil; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.eval.EvaluationException; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.util.LocaleUtil; -import org.junit.Test; - -/** - * Tests YearFracCalculator using test-cases listed in a sample spreadsheet - */ -public final class TestYearFracCalculatorFromSpreadsheet { - - private static final class SS { - - public static final int BASIS_COLUMN = 1; // "B" - public static final int START_YEAR_COLUMN = 2; // "C" - public static final int END_YEAR_COLUMN = 5; // "F" - public static final int YEARFRAC_FORMULA_COLUMN = 11; // "L" - public static final int EXPECTED_RESULT_COLUMN = 13; // "N" - } - - @Test - public void testAll() throws Exception { - - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("yearfracExamples.xls"); - HSSFSheet sheet = wb.getSheetAt(0); - HSSFFormulaEvaluator formulaEvaluator = new HSSFFormulaEvaluator(wb); - int nSuccess = 0; - Iterator rowIterator = sheet.rowIterator(); - while(rowIterator.hasNext()) { - HSSFRow row = (HSSFRow) rowIterator.next(); - - HSSFCell cell = row.getCell(SS.YEARFRAC_FORMULA_COLUMN); - if (cell == null || cell.getCellTypeEnum() != CellType.FORMULA) { - continue; - } - processRow(row, cell, formulaEvaluator); - nSuccess++; - } - - assertTrue("No test sample cases found", nSuccess > 0); - wb.close(); - } - - private void processRow(HSSFRow row, HSSFCell cell, HSSFFormulaEvaluator formulaEvaluator) - throws EvaluationException { - - double startDate = makeDate(row, SS.START_YEAR_COLUMN); - double endDate = makeDate(row, SS.END_YEAR_COLUMN); - - int basis = getIntCell(row, SS.BASIS_COLUMN); - - double expectedValue = getDoubleCell(row, SS.EXPECTED_RESULT_COLUMN); - - double actualValue = YearFracCalculator.calculate(startDate, endDate, basis); - - String loc = " - row " + (row.getRowNum()+1); - assertEquals("Direct calculate failed"+loc, expectedValue, actualValue, 0); - actualValue = formulaEvaluator.evaluate(cell).getNumberValue(); - assertEquals("Formula evaluate failed"+loc, expectedValue, actualValue, 0); - } - - private static double makeDate(HSSFRow row, int yearColumn) { - int year = getIntCell(row, yearColumn + 0); - int month = getIntCell(row, yearColumn + 1); - int day = getIntCell(row, yearColumn + 2); - Calendar c = LocaleUtil.getLocaleCalendar(year, month-1, day); - return HSSFDateUtil.getExcelDate(c.getTime()); - } - - private static int getIntCell(HSSFRow row, int colIx) { - double dVal = getDoubleCell(row, colIx); - String msg = "Non integer value (" + dVal + ") cell found at column " + (char)('A' + colIx); - assertEquals(msg, Math.floor(dVal), dVal, 0); - return (int)dVal; - } - - private static double getDoubleCell(HSSFRow row, int colIx) { - HSSFCell cell = row.getCell(colIx); - assertNotNull("No cell found at column " + colIx, cell); - double dVal = cell.getNumericCellValue(); - return dVal; - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/constant/TestConstantValueParser.java b/src/testcases/org/apache/poi/ss/formula/constant/TestConstantValueParser.java deleted file mode 100644 index 08ce2d96e..000000000 --- a/src/testcases/org/apache/poi/ss/formula/constant/TestConstantValueParser.java +++ /dev/null @@ -1,83 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.constant; - - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -import java.util.Arrays; - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.apache.poi.ss.usermodel.FormulaError; -import org.apache.poi.util.HexRead; -import org.apache.poi.util.LittleEndianByteArrayOutputStream; -import org.apache.poi.util.LittleEndianInput; -import org.junit.Test; - -public final class TestConstantValueParser { - private static final Object[] SAMPLE_VALUES = { - Boolean.TRUE, - null, - new Double(1.1), - "Sample text", - ErrorConstant.valueOf(FormulaError.DIV0.getCode()), - }; - private static final byte[] SAMPLE_ENCODING = HexRead.readFromString( - "04 01 00 00 00 00 00 00 00 " + - "00 00 00 00 00 00 00 00 00 " + - "01 9A 99 99 99 99 99 F1 3F " + - "02 0B 00 00 53 61 6D 70 6C 65 20 74 65 78 74 " + - "10 07 00 00 00 00 00 00 00"); - - @Test - public void testGetEncodedSize() { - int actual = ConstantValueParser.getEncodedSize(SAMPLE_VALUES); - assertEquals(51, actual); - } - - @Test - public void testEncode() { - int size = ConstantValueParser.getEncodedSize(SAMPLE_VALUES); - byte[] data = new byte[size]; - - ConstantValueParser.encode(new LittleEndianByteArrayOutputStream(data, 0), SAMPLE_VALUES); - - if (!Arrays.equals(data, SAMPLE_ENCODING)) { - fail("Encoding differs"); - } - } - - @Test - public void testDecode() { - LittleEndianInput in = TestcaseRecordInputStream.createLittleEndian(SAMPLE_ENCODING); - - Object[] values = ConstantValueParser.parse(in, 4); - for (int i = 0; i < values.length; i++) { - if(!isEqual(SAMPLE_VALUES[i], values[i])) { - fail("Decoded result differs"); - } - } - } - private static boolean isEqual(Object a, Object b) { - if (a == null) { - return b == null; - } - return a.equals(b); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/eval/AllFormulaEvalTests.java b/src/testcases/org/apache/poi/ss/formula/eval/AllFormulaEvalTests.java deleted file mode 100644 index d30e5e585..000000000 --- a/src/testcases/org/apache/poi/ss/formula/eval/AllFormulaEvalTests.java +++ /dev/null @@ -1,42 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.eval; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -/** - * Collects all tests the package org.apache.poi.hssf.record.formula.eval. - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestAreaEval.class, - TestHSSFCircularReferences.class, - TestDivideEval.class, - TestEqualEval.class, - TestExternalFunction.class, - TestFormulaBugs.class, - TestFormulasFromSpreadsheet.class, - TestMinusZeroResult.class, - TestMissingArgEval.class, - TestPercentEval.class, - TestRangeEval.class, - TestUnaryPlusEval.class -}) -public class AllFormulaEvalTests { -} diff --git a/src/testcases/org/apache/poi/ss/formula/eval/BaseTestCircularReferences.java b/src/testcases/org/apache/poi/ss/formula/eval/BaseTestCircularReferences.java deleted file mode 100644 index ec3aa9107..000000000 --- a/src/testcases/org/apache/poi/ss/formula/eval/BaseTestCircularReferences.java +++ /dev/null @@ -1,191 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.formula.eval; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; - -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.junit.Test; - -import junit.framework.AssertionFailedError; - -/** - * Common superclass for testing cases of circular references - * both for HSSF and XSSF - */ -public abstract class BaseTestCircularReferences { - - protected final ITestDataProvider _testDataProvider; - - /** - * @param testDataProvider an object that provides test data in HSSF / XSSF specific way - */ - protected BaseTestCircularReferences(ITestDataProvider testDataProvider) { - _testDataProvider = testDataProvider; - } - - - /** - * Translates StackOverflowError into AssertionFailedError - */ - private CellValue evaluateWithCycles(Workbook wb, Cell testCell) - throws AssertionFailedError { - FormulaEvaluator evaluator = _testDataProvider.createFormulaEvaluator(wb); - try { - return evaluator.evaluate(testCell); - } catch (StackOverflowError e) { - throw new AssertionFailedError( "circular reference caused stack overflow error"); - } - } - /** - * Makes sure that the specified evaluated cell value represents a circular reference error. - */ - private static void confirmCycleErrorCode(CellValue cellValue) { - assertTrue(cellValue.getCellTypeEnum() == CellType.ERROR); - assertEquals(ErrorEval.CIRCULAR_REF_ERROR.getErrorCode(), cellValue.getErrorValue()); - } - - - /** - * ASF Bugzilla Bug 44413 - * "INDEX() formula cannot contain its own location in the data array range" - */ - @Test - public void testIndexFormula() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet("Sheet1"); - - int colB = 1; - sheet.createRow(0).createCell(colB).setCellValue(1); - sheet.createRow(1).createCell(colB).setCellValue(2); - sheet.createRow(2).createCell(colB).setCellValue(3); - Row row4 = sheet.createRow(3); - Cell testCell = row4.createCell(0); - // This formula should evaluate to the contents of B2, - testCell.setCellFormula("INDEX(A1:B4,2,2)"); - // However the range A1:B4 also includes the current cell A4. If the other parameters - // were 4 and 1, this would represent a circular reference. Prior to v3.2 POI would - // 'fully' evaluate ref arguments before invoking operators, which raised the possibility of - // cycles / StackOverflowErrors. - - - CellValue cellValue = evaluateWithCycles(wb, testCell); - - assertTrue(cellValue.getCellTypeEnum() == CellType.NUMERIC); - assertEquals(2, cellValue.getNumberValue(), 0); - wb.close(); - } - - /** - * Cell A1 has formula "=A1" - */ - @Test - public void testSimpleCircularReference() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet("Sheet1"); - - Row row = sheet.createRow(0); - Cell testCell = row.createCell(0); - testCell.setCellFormula("A1"); - - CellValue cellValue = evaluateWithCycles(wb, testCell); - - confirmCycleErrorCode(cellValue); - - wb.close(); - } - - /** - * A1=B1, B1=C1, C1=D1, D1=A1 - */ - @Test - public void testMultiLevelCircularReference() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet("Sheet1"); - - Row row = sheet.createRow(0); - row.createCell(0).setCellFormula("B1"); - row.createCell(1).setCellFormula("C1"); - row.createCell(2).setCellFormula("D1"); - Cell testCell = row.createCell(3); - testCell.setCellFormula("A1"); - - CellValue cellValue = evaluateWithCycles(wb, testCell); - - confirmCycleErrorCode(cellValue); - - wb.close(); - } - - @Test - public void testIntermediateCircularReferenceResults_bug46898() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet("Sheet1"); - - Row row = sheet.createRow(0); - - Cell cellA1 = row.createCell(0); - Cell cellB1 = row.createCell(1); - Cell cellC1 = row.createCell(2); - Cell cellD1 = row.createCell(3); - Cell cellE1 = row.createCell(4); - - cellA1.setCellFormula("IF(FALSE, 1+B1, 42)"); - cellB1.setCellFormula("1+C1"); - cellC1.setCellFormula("1+D1"); - cellD1.setCellFormula("1+E1"); - cellE1.setCellFormula("1+A1"); - - FormulaEvaluator fe = _testDataProvider.createFormulaEvaluator(wb); - CellValue cv; - - // Happy day flow - evaluate A1 first - cv = fe.evaluate(cellA1); - assertEquals(CellType.NUMERIC, cv.getCellTypeEnum()); - assertEquals(42.0, cv.getNumberValue(), 0.0); - cv = fe.evaluate(cellB1); // no circ-ref-error because A1 result is cached - assertEquals(CellType.NUMERIC, cv.getCellTypeEnum()); - assertEquals(46.0, cv.getNumberValue(), 0.0); - - // Show the bug - evaluate another cell from the loop first - fe.clearAllCachedResultValues(); - cv = fe.evaluate(cellB1); - // Identified bug 46898 - assertNotEquals(cv.getCellTypeEnum(), ErrorEval.CIRCULAR_REF_ERROR.getErrorCode()); - assertEquals(CellType.NUMERIC, cv.getCellTypeEnum()); - assertEquals(46.0, cv.getNumberValue(), 0.0); - - // start evaluation on another cell - fe.clearAllCachedResultValues(); - cv = fe.evaluate(cellE1); - assertEquals(CellType.NUMERIC, cv.getCellTypeEnum()); - assertEquals(43.0, cv.getNumberValue(), 0.0); - - wb.close(); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/eval/EvalInstances.java b/src/testcases/org/apache/poi/ss/formula/eval/EvalInstances.java deleted file mode 100644 index 4a1544477..000000000 --- a/src/testcases/org/apache/poi/ss/formula/eval/EvalInstances.java +++ /dev/null @@ -1,53 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.eval; - -import org.apache.poi.ss.formula.functions.Function; - -/** - * Collects eval instances for easy access by tests in this package - * - * @author Josh Micich - */ -final class EvalInstances { - private EvalInstances() { - // no instances of this class - } - - public static final Function Add = TwoOperandNumericOperation.AddEval; - public static final Function Subtract = TwoOperandNumericOperation.SubtractEval; - public static final Function Multiply = TwoOperandNumericOperation.MultiplyEval; - public static final Function Divide = TwoOperandNumericOperation.DivideEval; - - public static final Function Power = TwoOperandNumericOperation.PowerEval; - - public static final Function Percent = PercentEval.instance; - - public static final Function UnaryMinus = UnaryMinusEval.instance; - public static final Function UnaryPlus = UnaryPlusEval.instance; - - public static final Function Equal = RelationalOperationEval.EqualEval; - public static final Function LessThan = RelationalOperationEval.LessThanEval; - public static final Function LessEqual = RelationalOperationEval.LessEqualEval; - public static final Function GreaterThan = RelationalOperationEval.GreaterThanEval; - public static final Function GreaterEqual = RelationalOperationEval.GreaterEqualEval; - public static final Function NotEqual = RelationalOperationEval.NotEqualEval; - - public static final Function Range = RangeEval.instance; - public static final Function Concat = ConcatEval.instance; -} diff --git a/src/testcases/org/apache/poi/ss/formula/eval/TestAreaEval.java b/src/testcases/org/apache/poi/ss/formula/eval/TestAreaEval.java deleted file mode 100644 index a3ace443d..000000000 --- a/src/testcases/org/apache/poi/ss/formula/eval/TestAreaEval.java +++ /dev/null @@ -1,62 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.eval; - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -import org.apache.poi.ss.formula.ptg.AreaPtg; -import org.apache.poi.ss.formula.functions.EvalFactory; - -/** - * Tests for AreaEval - * - * @author Josh Micich - */ -public final class TestAreaEval extends TestCase { - - public void testGetValue_bug44950() { - // TODO - this test probably isn't testing much anymore - AreaPtg ptg = new AreaPtg("B2:D3"); - NumberEval one = new NumberEval(1); - ValueEval[] values = { - one, - new NumberEval(2), - new NumberEval(3), - new NumberEval(4), - new NumberEval(5), - new NumberEval(6), - }; - AreaEval ae = EvalFactory.createAreaEval(ptg, values); - if (one == ae.getAbsoluteValue(1, 2)) { - throw new AssertionFailedError("Identified bug 44950 a"); - } - confirm(1, ae, 1, 1); - confirm(2, ae, 1, 2); - confirm(3, ae, 1, 3); - confirm(4, ae, 2, 1); - confirm(5, ae, 2, 2); - confirm(6, ae, 2, 3); - - } - - private static void confirm(int expectedValue, AreaEval ae, int row, int col) { - NumberEval v = (NumberEval) ae.getAbsoluteValue(row, col); - assertEquals(expectedValue, v.getNumberValue(), 0.0); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/eval/TestDivideEval.java b/src/testcases/org/apache/poi/ss/formula/eval/TestDivideEval.java deleted file mode 100644 index 11c661d9f..000000000 --- a/src/testcases/org/apache/poi/ss/formula/eval/TestDivideEval.java +++ /dev/null @@ -1,62 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.eval; - -import junit.framework.TestCase; - -import org.apache.poi.ss.formula.functions.EvalFactory; -import org.apache.poi.ss.formula.functions.NumericFunctionInvoker; - -/** - * Test for divide operator evaluator. - * - * @author Josh Micich - */ -public final class TestDivideEval extends TestCase { - - private static void confirm(ValueEval arg0, ValueEval arg1, double expectedResult) { - ValueEval[] args = { - arg0, arg1, - }; - - double result = NumericFunctionInvoker.invoke(EvalInstances.Divide, args, 0, 0); - - assertEquals(expectedResult, result, 0); - } - - public void testBasic() { - confirm(new NumberEval(5), new NumberEval(2), 2.5); - confirm(new NumberEval(3), new NumberEval(16), 0.1875); - confirm(new NumberEval(-150), new NumberEval(-15), 10.0); - confirm(new StringEval("0.2"), new NumberEval(0.05), 4.0); - confirm(BoolEval.TRUE, new StringEval("-0.2"), -5.0); - } - - public void test1x1Area() { - AreaEval ae0 = EvalFactory.createAreaEval("B2:B2", new ValueEval[] { new NumberEval(50), }); - AreaEval ae1 = EvalFactory.createAreaEval("C2:C2", new ValueEval[] { new NumberEval(10), }); - confirm(ae0, ae1, 5); - } - public void testDivZero() { - ValueEval[] args = { - new NumberEval(5), NumberEval.ZERO, - }; - ValueEval result = EvalInstances.Divide.evaluate(args, 0, (short) 0); - assertEquals(ErrorEval.DIV_ZERO, result); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/eval/TestEqualEval.java b/src/testcases/org/apache/poi/ss/formula/eval/TestEqualEval.java deleted file mode 100644 index e10de014c..000000000 --- a/src/testcases/org/apache/poi/ss/formula/eval/TestEqualEval.java +++ /dev/null @@ -1,169 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.eval; - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -import org.apache.poi.ss.formula.functions.EvalFactory; -import org.apache.poi.ss.formula.functions.Function; - -/** - * Test for {@link EqualEval} - * - * @author Josh Micich - */ -public final class TestEqualEval extends TestCase { - // convenient access to namepace - private static final EvalInstances EI = null; - - /** - * Test for bug observable at svn revision 692218 (Sep 2008)
    - * The value from a 1x1 area should be taken immediately, regardless of srcRow and srcCol - */ - public void test1x1AreaOperand() { - - ValueEval[] values = { BoolEval.FALSE, }; - ValueEval[] args = { - EvalFactory.createAreaEval("B1:B1", values), - BoolEval.FALSE, - }; - ValueEval result = evaluate(EvalInstances.Equal, args, 10, 10); - if (result instanceof ErrorEval) { - if (result == ErrorEval.VALUE_INVALID) { - throw new AssertionFailedError("Identified bug in evaluation of 1x1 area"); - } - } - assertEquals(BoolEval.class, result.getClass()); - assertTrue(((BoolEval)result).getBooleanValue()); - } - /** - * Empty string is equal to blank - */ - public void testBlankEqualToEmptyString() { - - ValueEval[] args = { - new StringEval(""), - BlankEval.instance, - }; - ValueEval result = evaluate(EvalInstances.Equal, args, 10, 10); - assertEquals(BoolEval.class, result.getClass()); - BoolEval be = (BoolEval) result; - if (!be.getBooleanValue()) { - throw new AssertionFailedError("Identified bug blank/empty string equality"); - } - assertTrue(be.getBooleanValue()); - } - - /** - * Test for bug 46613 (observable at svn r737248) - */ - public void testStringInsensitive_bug46613() { - if (!evalStringCmp("abc", "aBc", EvalInstances.Equal)) { - throw new AssertionFailedError("Identified bug 46613"); - } - assertTrue(evalStringCmp("abc", "aBc", EvalInstances.Equal)); - assertTrue(evalStringCmp("ABC", "azz", EvalInstances.LessThan)); - assertTrue(evalStringCmp("abc", "AZZ", EvalInstances.LessThan)); - assertTrue(evalStringCmp("ABC", "aaa", EvalInstances.GreaterThan)); - assertTrue(evalStringCmp("abc", "AAA", EvalInstances.GreaterThan)); - } - - private static boolean evalStringCmp(String a, String b, Function cmpOp) { - ValueEval[] args = { - new StringEval(a), - new StringEval(b), - }; - ValueEval result = evaluate(cmpOp, args, 10, 20); - assertEquals(BoolEval.class, result.getClass()); - BoolEval be = (BoolEval) result; - return be.getBooleanValue(); - } - - public void testBooleanCompares() { - confirmCompares(BoolEval.TRUE, new StringEval("TRUE"), +1); - confirmCompares(BoolEval.TRUE, new NumberEval(1.0), +1); - confirmCompares(BoolEval.TRUE, BoolEval.TRUE, 0); - confirmCompares(BoolEval.TRUE, BoolEval.FALSE, +1); - - confirmCompares(BoolEval.FALSE, new StringEval("TRUE"), +1); - confirmCompares(BoolEval.FALSE, new StringEval("FALSE"), +1); - confirmCompares(BoolEval.FALSE, new NumberEval(0.0), +1); - confirmCompares(BoolEval.FALSE, BoolEval.FALSE, 0); - } - private static void confirmCompares(ValueEval a, ValueEval b, int expRes) { - confirm(a, b, expRes>0, EvalInstances.GreaterThan); - confirm(a, b, expRes>=0, EvalInstances.GreaterEqual); - confirm(a, b, expRes==0, EvalInstances.Equal); - confirm(a, b, expRes<=0, EvalInstances.LessEqual); - confirm(a, b, expRes<0, EvalInstances.LessThan); - - confirm(b, a, expRes<0, EvalInstances.GreaterThan); - confirm(b, a, expRes<=0, EvalInstances.GreaterEqual); - confirm(b, a, expRes==0, EvalInstances.Equal); - confirm(b, a, expRes>=0, EvalInstances.LessEqual); - confirm(b, a, expRes>0, EvalInstances.LessThan); - } - private static void confirm(ValueEval a, ValueEval b, boolean expectedResult, Function cmpOp) { - ValueEval[] args = { a, b, }; - ValueEval result = evaluate(cmpOp, args, 10, 20); - assertEquals(BoolEval.class, result.getClass()); - assertEquals(expectedResult, ((BoolEval) result).getBooleanValue()); - } - - /** - * Bug 47198 involved a formula "-A1=0" where cell A1 was 0.0. - * Excel evaluates "-A1=0" to TRUE, not because it thinks -0.0==0.0 - * but because "-A1" evaluated to +0.0 - *

    - * Note - the original diagnosis of bug 47198 was that - * "Excel considers -0.0 to be equal to 0.0" which is NQR - * See {@link TestMinusZeroResult} for more specific tests regarding -0.0. - */ - public void testZeroEquality_bug47198() { - NumberEval zero = new NumberEval(0.0); - NumberEval mZero = (NumberEval) evaluate(UnaryMinusEval.instance, new ValueEval[] { zero, }, 0, 0); - if (Double.doubleToLongBits(mZero.getNumberValue()) == 0x8000000000000000L) { - throw new AssertionFailedError("Identified bug 47198: unary minus should convert -0.0 to 0.0"); - } - ValueEval[] args = { zero, mZero, }; - BoolEval result = (BoolEval) evaluate(EvalInstances.Equal, args, 0, 0); - if (!result.getBooleanValue()) { - throw new AssertionFailedError("Identified bug 47198: -0.0 != 0.0"); - } - } - - public void testRounding_bug47598() { - double x = 1+1.0028-0.9973; // should be 1.0055, but has IEEE rounding - assertFalse(x == 1.0055); - - NumberEval a = new NumberEval(x); - NumberEval b = new NumberEval(1.0055); - assertEquals("1.0055", b.getStringValue()); - - ValueEval[] args = { a, b, }; - BoolEval result = (BoolEval) evaluate(EvalInstances.Equal, args, 0, 0); - if (!result.getBooleanValue()) { - throw new AssertionFailedError("Identified bug 47598: 1+1.0028-0.9973 != 1.0055"); - } - } - - private static ValueEval evaluate(Function oper, ValueEval[] args, int srcRowIx, int srcColIx) { - return oper.evaluate(args, srcRowIx, (short) srcColIx); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/eval/TestExternalFunction.java b/src/testcases/org/apache/poi/ss/formula/eval/TestExternalFunction.java deleted file mode 100644 index 7a153e597..000000000 --- a/src/testcases/org/apache/poi/ss/formula/eval/TestExternalFunction.java +++ /dev/null @@ -1,97 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.eval; - -import junit.framework.TestCase; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.ss.formula.functions.FreeRefFunction; -import org.apache.poi.ss.formula.udf.DefaultUDFFinder; -import org.apache.poi.ss.formula.udf.AggregatingUDFFinder; -import org.apache.poi.ss.formula.udf.UDFFinder; -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.OperationEvaluationContext; - -/** - * @author Josh Micich - * @author Petr Udalau - registering UDFs in workbook and using ToolPacks. - */ -public final class TestExternalFunction extends TestCase { - - private static class MyFunc implements FreeRefFunction { - public MyFunc() { - // - } - - @Override - public ValueEval evaluate(ValueEval[] args, OperationEvaluationContext ec) { - if (args.length != 1 || !(args[0] instanceof StringEval)) { - return ErrorEval.VALUE_INVALID; - } - StringEval input = (StringEval) args[0]; - return new StringEval(input.getStringValue() + "abc"); - } - } - - private static class MyFunc2 implements FreeRefFunction { - public MyFunc2() { - // - } - - @Override - public ValueEval evaluate(ValueEval[] args, OperationEvaluationContext ec) { - if (args.length != 1 || !(args[0] instanceof StringEval)) { - return ErrorEval.VALUE_INVALID; - } - StringEval input = (StringEval) args[0]; - return new StringEval(input.getStringValue() + "abc2"); - } - } - - /** - * Checks that an external function can get invoked from the formula - * evaluator. - */ - public void testInvoke() { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("testNames.xls"); - HSSFSheet sheet = wb.getSheetAt(0); - - /** - * register the two test UDFs in a UDF finder, to be passed to the evaluator - */ - UDFFinder udff1 = new DefaultUDFFinder(new String[] { "myFunc", }, - new FreeRefFunction[] { new MyFunc(), }); - UDFFinder udff2 = new DefaultUDFFinder(new String[] { "myFunc2", }, - new FreeRefFunction[] { new MyFunc2(), }); - UDFFinder udff = new AggregatingUDFFinder(udff1, udff2); - - - HSSFRow row = sheet.getRow(0); - HSSFCell myFuncCell = row.getCell(1); // =myFunc("_") - - HSSFCell myFunc2Cell = row.getCell(2); // =myFunc2("_") - - HSSFFormulaEvaluator fe = HSSFFormulaEvaluator.create(wb, null, udff); - assertEquals("_abc", fe.evaluate(myFuncCell).getStringValue()); - assertEquals("_abc2", fe.evaluate(myFunc2Cell).getStringValue()); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/eval/TestFormulaBugs.java b/src/testcases/org/apache/poi/ss/formula/eval/TestFormulaBugs.java deleted file mode 100644 index 7147db528..000000000 --- a/src/testcases/org/apache/poi/ss/formula/eval/TestFormulaBugs.java +++ /dev/null @@ -1,201 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.eval; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.usermodel.*; -import org.apache.poi.ss.usermodel.*; -import org.junit.Test; - -import java.io.IOException; -import java.io.InputStream; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -/** - * Miscellaneous tests for bugzilla entries.

    The test name contains the - * bugzilla bug id. - */ -public final class TestFormulaBugs { - - /** - * Bug 27349 - VLOOKUP with reference to another sheet.

    This test was - * added long after the relevant functionality was fixed. - */ - @Test - public void test27349() throws Exception { - // 27349-vlookupAcrossSheets.xls is bugzilla/attachment.cgi?id=10622 - InputStream is = HSSFTestDataSamples.openSampleFileStream("27349-vlookupAcrossSheets.xls"); - // original bug may have thrown exception here, - // or output warning to stderr - Workbook wb = new HSSFWorkbook(is); - - Sheet sheet = wb.getSheetAt(0); - Row row = sheet.getRow(1); - Cell cell = row.getCell(0); - - // this definitely would have failed due to 27349 - assertEquals("VLOOKUP(1,'DATA TABLE'!$A$8:'DATA TABLE'!$B$10,2)", cell - .getCellFormula()); - - // We might as well evaluate the formula - FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); - CellValue cv = fe.evaluate(cell); - - assertEquals(CellType.NUMERIC, cv.getCellTypeEnum()); - assertEquals(3.0, cv.getNumberValue(), 0.0); - - wb.close(); - is.close(); - } - - /** - * Bug 27405 - isnumber() formula always evaluates to false in if statement

    - * - * seems to be a duplicate of 24925 - */ - @Test - public void test27405() throws Exception { - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet("input"); - // input row 0 - Row row = sheet.createRow(0); - /*Cell cell =*/ row.createCell(0); - Cell cell = row.createCell(1); - cell.setCellValue(1); // B1 - // input row 1 - row = sheet.createRow(1); - cell = row.createCell(1); - cell.setCellValue(999); // B2 - - int rno = 4; - row = sheet.createRow(rno); - cell = row.createCell(1); // B5 - cell.setCellFormula("isnumber(b1)"); - cell = row.createCell(3); // D5 - cell.setCellFormula("IF(ISNUMBER(b1),b1,b2)"); - -// if (false) { // set true to check excel file manually -// // bug report mentions 'Editing the formula in excel "fixes" the problem.' -// try { -// FileOutputStream fileOut = new FileOutputStream("27405output.xls"); -// wb.write(fileOut); -// fileOut.close(); -// } catch (IOException e) { -// throw new RuntimeException(e); -// } -// } - - // use POI's evaluator as an extra sanity check - FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); - CellValue cv; - cv = fe.evaluate(cell); - assertEquals(CellType.NUMERIC, cv.getCellTypeEnum()); - assertEquals(1.0, cv.getNumberValue(), 0.0); - - cv = fe.evaluate(row.getCell(1)); - assertEquals(CellType.BOOLEAN, cv.getCellTypeEnum()); - assertEquals(true, cv.getBooleanValue()); - - wb.close(); - } - - /** - * Bug 42448 - Can't parse SUMPRODUCT(A!C7:A!C67, B8:B68) / B69

    - */ - @Test - public void test42448() throws IOException { - Workbook wb = new HSSFWorkbook(); - Sheet sheet1 = wb.createSheet("Sheet1"); - - Row row = sheet1.createRow(0); - Cell cell = row.createCell(0); - - // it's important to create the referenced sheet first - Sheet sheet2 = wb.createSheet("A"); // note name 'A' - // TODO - POI crashes if the formula is added before this sheet - // RuntimeException("Zero length string is an invalid sheet name") - // Excel doesn't crash but the formula doesn't work until it is - // re-entered - - String inputFormula = "SUMPRODUCT(A!C7:A!C67, B8:B68) / B69"; // as per bug report - try { - cell.setCellFormula(inputFormula); - } catch (StringIndexOutOfBoundsException e) { - fail("Identified bug 42448"); - } - - assertEquals("SUMPRODUCT(A!C7:A!C67,B8:B68)/B69", cell.getCellFormula()); - - // might as well evaluate the sucker... - - addCell(sheet2, 5, 2, 3.0); // A!C6 - addCell(sheet2, 6, 2, 4.0); // A!C7 - addCell(sheet2, 66, 2, 5.0); // A!C67 - addCell(sheet2, 67, 2, 6.0); // A!C68 - - addCell(sheet1, 6, 1, 7.0); // B7 - addCell(sheet1, 7, 1, 8.0); // B8 - addCell(sheet1, 67, 1, 9.0); // B68 - addCell(sheet1, 68, 1, 10.0); // B69 - - double expectedResult = (4.0 * 8.0 + 5.0 * 9.0) / 10.0; - - FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); - CellValue cv = fe.evaluate(cell); - - assertEquals(CellType.NUMERIC, cv.getCellTypeEnum()); - assertEquals(expectedResult, cv.getNumberValue(), 0.0); - - wb.close(); - } - - private static void addCell(Sheet sheet, int rowIx, int colIx, - double value) { - sheet.createRow(rowIx).createCell(colIx).setCellValue(value); - } - - @Test - public void test55032() throws IOException { - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet("input"); - - Row row = sheet.createRow(0); - Cell cell = row.createCell(1); - - checkFormulaValue(wb, cell, "PV(0.08/12, 20*12, 500, ,0)", -59777.14585); - checkFormulaValue(wb, cell, "PV(0.08/12, 20*12, 500, ,)", -59777.14585); - checkFormulaValue(wb, cell, "PV(0.08/12, 20*12, 500, 500,)", -59878.6315455); - - checkFormulaValue(wb, cell, "FV(0.08/12, 20*12, 500, ,)", -294510.2078107270); - checkFormulaValue(wb, cell, "PMT(0.08/12, 20*12, 500, ,)", -4.1822003450); - checkFormulaValue(wb, cell, "NPER(0.08/12, 20*12, 500, ,)", -2.0758873434); - - wb.close(); - } - - private void checkFormulaValue(Workbook wb, Cell cell, String formula, double expectedValue) { - cell.setCellFormula(formula); - - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - CellValue value = evaluator.evaluate(cell); - - assertEquals(expectedValue, value.getNumberValue(), 0.0001); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/eval/TestFormulasFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/eval/TestFormulasFromSpreadsheet.java deleted file mode 100644 index 9ce0488f9..000000000 --- a/src/testcases/org/apache/poi/ss/formula/eval/TestFormulasFromSpreadsheet.java +++ /dev/null @@ -1,241 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.eval; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Locale; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.functions.TestMathX; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.util.LocaleUtil; -import org.junit.AfterClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; - -import junit.framework.AssertionFailedError; - -/** - * Tests formulas and operators as loaded from a test data spreadsheet.

    - * This class does not test implementors of Function and OperationEval in - * isolation. Much of the evaluation engine (i.e. HSSFFormulaEvaluator, ...) gets - * exercised as well. Tests for bug fixes and specific/tricky behaviour can be found in the - * corresponding test class (TestXxxx) of the target (Xxxx) implementor, - * where execution can be observed more easily. - */ -@RunWith(Parameterized.class) -public final class TestFormulasFromSpreadsheet { - - private static HSSFWorkbook workbook; - private static Sheet sheet; - private static HSSFFormulaEvaluator evaluator; - private static Locale userLocale; - - /** - * This class defines constants for navigating around the test data spreadsheet used for these tests. - */ - private static interface SS { - - /** - * Name of the test spreadsheet (found in the standard test data folder) - */ - String FILENAME = "FormulaEvalTestData.xls"; - /** - * Row (zero-based) in the test spreadsheet where the operator examples start. - */ - int START_OPERATORS_ROW_INDEX = 22; // Row '23' - /** - * Row (zero-based) in the test spreadsheet where the function examples start. - */ - int START_FUNCTIONS_ROW_INDEX = 95; // Row '96' - /** - * Index of the column that contains the function names - */ - int COLUMN_INDEX_FUNCTION_NAME = 1; // Column 'B' - - /** - * Used to indicate when there are no more functions left - */ - String FUNCTION_NAMES_END_SENTINEL = ""; - - /** - * Index of the column where the test values start (for each function) - */ - short COLUMN_INDEX_FIRST_TEST_VALUE = 3; // Column 'D' - - /** - * Each function takes 4 rows in the test spreadsheet - */ - int NUMBER_OF_ROWS_PER_FUNCTION = 4; - } - - @Parameter(value = 0) - public String targetFunctionName; - @Parameter(value = 1) - public int formulasRowIdx; - @Parameter(value = 2) - public int expectedValuesRowIdx; - - @AfterClass - public static void closeResource() throws Exception { - LocaleUtil.setUserLocale(userLocale); - workbook.close(); - } - - @Parameters(name="{0}") - public static Collection data() throws Exception { - // Function "Text" uses custom-formats which are locale specific - // can't set the locale on a per-testrun execution, as some settings have been - // already set, when we would try to change the locale by then - userLocale = LocaleUtil.getUserLocale(); - LocaleUtil.setUserLocale(Locale.ROOT); - - workbook = HSSFTestDataSamples.openSampleWorkbook(SS.FILENAME); - sheet = workbook.getSheetAt( 0 ); - evaluator = new HSSFFormulaEvaluator(workbook); - - List data = new ArrayList(); - - processFunctionGroup(data, SS.START_OPERATORS_ROW_INDEX, null); - processFunctionGroup(data, SS.START_FUNCTIONS_ROW_INDEX, null); - // example for debugging individual functions/operators: - // processFunctionGroup(data, SS.START_OPERATORS_ROW_INDEX, "ConcatEval"); - // processFunctionGroup(data, SS.START_FUNCTIONS_ROW_INDEX, "Text"); - - return data; - } - - /** - * @param startRowIndex row index in the spreadsheet where the first function/operator is found - * @param testFocusFunctionName name of a single function/operator to test alone. - * Typically pass null to test all functions - */ - private static void processFunctionGroup(List data, int startRowIndex, String testFocusFunctionName) { - for (int rowIndex = startRowIndex; true; rowIndex += SS.NUMBER_OF_ROWS_PER_FUNCTION) { - Row r = sheet.getRow(rowIndex); - String targetFunctionName = getTargetFunctionName(r); - assertNotNull("Test spreadsheet cell empty on row (" - + (rowIndex+1) + "). Expected function name or '" - + SS.FUNCTION_NAMES_END_SENTINEL + "'", targetFunctionName); - if(targetFunctionName.equals(SS.FUNCTION_NAMES_END_SENTINEL)) { - // found end of functions list - break; - } - if(testFocusFunctionName == null || targetFunctionName.equalsIgnoreCase(testFocusFunctionName)) { - - // expected results are on the row below - Row expectedValuesRow = sheet.getRow(rowIndex + 1); - int missingRowNum = rowIndex + 2; //+1 for 1-based, +1 for next row - assertNotNull("Missing expected values row for function '" - + targetFunctionName + " (row " + missingRowNum + ")", expectedValuesRow); - - data.add(new Object[]{targetFunctionName, rowIndex, rowIndex + 1}); - } - } - } - - @Test - public void processFunctionRow() { - Row formulasRow = sheet.getRow(formulasRowIdx); - Row expectedValuesRow = sheet.getRow(expectedValuesRowIdx); - - short endcolnum = formulasRow.getLastCellNum(); - - // iterate across the row for all the evaluation cases - for (int colnum=SS.COLUMN_INDEX_FIRST_TEST_VALUE; colnum < endcolnum; colnum++) { - Cell c = formulasRow.getCell(colnum); - if (c == null || c.getCellTypeEnum() != CellType.FORMULA) { - continue; - } - - CellValue actValue = evaluator.evaluate(c); - Cell expValue = (expectedValuesRow == null) ? null : expectedValuesRow.getCell(colnum); - - String msg = String.format(Locale.ROOT, "Function '%s': Formula: %s @ %d:%d" - , targetFunctionName, c.getCellFormula(), formulasRow.getRowNum(), colnum); - - assertNotNull(msg + " - Bad setup data expected value is null", expValue); - assertNotNull(msg + " - actual value was null", actValue); - - final CellType cellType = expValue.getCellTypeEnum(); - switch (cellType) { - case BLANK: - assertEquals(msg, CellType.BLANK, actValue.getCellTypeEnum()); - break; - case BOOLEAN: - assertEquals(msg, CellType.BOOLEAN, actValue.getCellTypeEnum()); - assertEquals(msg, expValue.getBooleanCellValue(), actValue.getBooleanValue()); - break; - case ERROR: - assertEquals(msg, CellType.ERROR, actValue.getCellTypeEnum()); - assertEquals(msg, ErrorEval.getText(expValue.getErrorCellValue()), ErrorEval.getText(actValue.getErrorValue())); - break; - case FORMULA: // will never be used, since we will call method after formula evaluation - fail("Cannot expect formula as result of formula evaluation: " + msg); - case NUMERIC: - assertEquals(msg, CellType.NUMERIC, actValue.getCellTypeEnum()); - TestMathX.assertEquals(msg, expValue.getNumericCellValue(), actValue.getNumberValue(), TestMathX.POS_ZERO, TestMathX.DIFF_TOLERANCE_FACTOR); - break; - case STRING: - assertEquals(msg, CellType.STRING, actValue.getCellTypeEnum()); - assertEquals(msg, expValue.getRichStringCellValue().getString(), actValue.getStringValue()); - break; - default: - fail("Unexpected cell type: " + cellType); - } - } - } - /** - * @return null if cell is missing, empty or blank - */ - private static String getTargetFunctionName(Row r) { - if(r == null) { - System.err.println("Warning - given null row, can't figure out function name"); - return null; - } - Cell cell = r.getCell(SS.COLUMN_INDEX_FUNCTION_NAME); - if(cell == null) { - System.err.println("Warning - Row " + r.getRowNum() + " has no cell " + SS.COLUMN_INDEX_FUNCTION_NAME + ", can't figure out function name"); - return null; - } - if(cell.getCellTypeEnum() == CellType.BLANK) { - return null; - } - if(cell.getCellTypeEnum() == CellType.STRING) { - return cell.getRichStringCellValue().getString(); - } - - throw new AssertionFailedError("Bad cell type for 'function name' column: (" - + cell.getCellTypeEnum() + ") row (" + (r.getRowNum() +1) + ")"); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/eval/TestHSSFCircularReferences.java b/src/testcases/org/apache/poi/ss/formula/eval/TestHSSFCircularReferences.java deleted file mode 100644 index f1e21b42d..000000000 --- a/src/testcases/org/apache/poi/ss/formula/eval/TestHSSFCircularReferences.java +++ /dev/null @@ -1,31 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.eval; - -import org.apache.poi.hssf.HSSFITestDataProvider; - -/** - * Tests HSSFFormulaEvaluator for its handling of cell formula circular references. - * - * @author Josh Micich - */ -public final class TestHSSFCircularReferences extends BaseTestCircularReferences { - public TestHSSFCircularReferences() { - super(HSSFITestDataProvider.instance); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/eval/TestMinusZeroResult.java b/src/testcases/org/apache/poi/ss/formula/eval/TestMinusZeroResult.java deleted file mode 100644 index 7500be57e..000000000 --- a/src/testcases/org/apache/poi/ss/formula/eval/TestMinusZeroResult.java +++ /dev/null @@ -1,148 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.eval; - -import junit.framework.ComparisonFailure; -import junit.framework.TestCase; - -import org.apache.poi.ss.formula.functions.Function; -import org.apache.poi.util.HexDump; - -/** - * IEEE 754 defines a quantity '-0.0' which is distinct from '0.0'. - * Negative zero is not easy to observe in Excel, since it is usually converted to 0.0. - * (Note - the results of XLL add-in functions don't seem to be converted, so they are one - * reliable avenue to observe Excel's treatment of '-0.0' as an operand.) - *

    - * POI attempts to emulate Excel faithfully, so this class tests - * two aspects of '-0.0' in formula evaluation: - *

      - *
    1. For most operation results '-0.0' is converted to '0.0'.
    2. - *
    3. Comparison operators have slightly different rules regarding '-0.0'.
    4. - *
    - * @author Josh Micich - */ -public final class TestMinusZeroResult extends TestCase { - private static final double MINUS_ZERO = -0.0; - - public void testSimpleOperators() { - - // unary plus is a no-op - checkEval(MINUS_ZERO, UnaryPlusEval.instance, MINUS_ZERO); - - // most simple operators convert -0.0 to +0.0 - checkEval(0.0, EvalInstances.UnaryMinus, 0.0); - checkEval(0.0, EvalInstances.Percent, MINUS_ZERO); - checkEval(0.0, EvalInstances.Multiply, MINUS_ZERO, 1.0); - checkEval(0.0, EvalInstances.Divide, MINUS_ZERO, 1.0); - checkEval(0.0, EvalInstances.Power, MINUS_ZERO, 1.0); - - // but SubtractEval does not convert -0.0, so '-' and '+' work like java - checkEval(MINUS_ZERO, EvalInstances.Subtract, MINUS_ZERO, 0.0); // this is the main point of bug 47198 - checkEval(0.0, EvalInstances.Add, MINUS_ZERO, 0.0); - } - - /** - * These results are hard to see in Excel (since -0.0 is usually converted to +0.0 before it - * gets to the comparison operator) - */ - public void testComparisonOperators() { - checkEval(false, EvalInstances.Equal, 0.0, MINUS_ZERO); - checkEval(true, EvalInstances.GreaterThan, 0.0, MINUS_ZERO); - checkEval(true, EvalInstances.LessThan, MINUS_ZERO, 0.0); - } - - public void testTextRendering() { - confirmTextRendering("-0", MINUS_ZERO); - // sub-normal negative numbers also display as '-0' - confirmTextRendering("-0", Double.longBitsToDouble(0x8000100020003000L)); - } - - /** - * Uses {@link ConcatEval} to force number-to-text conversion - */ - private static void confirmTextRendering(String expRendering, double d) { - ValueEval[] args = { StringEval.EMPTY_INSTANCE, new NumberEval(d), }; - StringEval se = (StringEval) EvalInstances.Concat.evaluate(args, -1, (short)-1); - String result = se.getStringValue(); - assertEquals(expRendering, result); - } - - private static void checkEval(double expectedResult, Function instance, double... dArgs) { - NumberEval result = (NumberEval) evaluate(instance, dArgs); - assertDouble(expectedResult, result.getNumberValue()); - } - private static void checkEval(boolean expectedResult, Function instance, double... dArgs) { - BoolEval result = (BoolEval) evaluate(instance, dArgs); - assertEquals(expectedResult, result.getBooleanValue()); - } - private static ValueEval evaluate(Function instance, double... dArgs) { - ValueEval[] evalArgs; - evalArgs = new ValueEval[dArgs.length]; - for (int i = 0; i < evalArgs.length; i++) { - evalArgs[i] = new NumberEval(dArgs[i]); - } - ValueEval r = instance.evaluate(evalArgs, -1, (short)-1); - return r; - } - - /** - * Not really a POI test - just shows similar behaviour of '-0.0' in Java. - */ - public void testJava() { - - assertEquals(0x8000000000000000L, Double.doubleToLongBits(MINUS_ZERO)); - - // The simple operators consider all zeros to be the same - assertTrue(MINUS_ZERO == MINUS_ZERO); - assertTrue(MINUS_ZERO == +0.0); - assertFalse(MINUS_ZERO < +0.0); - - // Double.compare() considers them different - assertTrue(Double.compare(MINUS_ZERO, +0.0) < 0); - - // multiplying zero by any negative quantity yields minus zero - assertDouble(MINUS_ZERO, 0.0*-1); - assertDouble(MINUS_ZERO, 0.0*-1e300); - assertDouble(MINUS_ZERO, 0.0*-1e-300); - - // minus zero can be produced as a result of underflow - assertDouble(MINUS_ZERO, -1e-300 / 1e100); - - // multiplying or dividing minus zero by a positive quantity yields minus zero - assertDouble(MINUS_ZERO, MINUS_ZERO * 1.0); - assertDouble(MINUS_ZERO, MINUS_ZERO / 1.0); - - // subtracting positive zero gives minus zero - assertDouble(MINUS_ZERO, MINUS_ZERO - 0.0); - // BUT adding positive zero gives positive zero - assertDouble(0.0, MINUS_ZERO + 0.0); // <<---- - } - - /** - * Just so there is no ambiguity. The two double values have to be exactly equal - */ - private static void assertDouble(double a, double b) { - long bitsA = Double.doubleToLongBits(a); - long bitsB = Double.doubleToLongBits(b); - if (bitsA != bitsB) { - throw new ComparisonFailure("value different to expected", - HexDump.longToHex(bitsA), HexDump.longToHex(bitsB)); - } - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/eval/TestMissingArgEval.java b/src/testcases/org/apache/poi/ss/formula/eval/TestMissingArgEval.java deleted file mode 100644 index 2bef73c81..000000000 --- a/src/testcases/org/apache/poi/ss/formula/eval/TestMissingArgEval.java +++ /dev/null @@ -1,74 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.eval; - -import java.util.EmptyStackException; - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.CellValue; - -/** - * Tests for {@link MissingArgEval} - * - * @author Josh Micich - */ -public final class TestMissingArgEval extends TestCase { - - public void testEvaluateMissingArgs() { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - HSSFSheet sheet = wb.createSheet("Sheet1"); - HSSFCell cell = sheet.createRow(0).createCell(0); - - cell.setCellFormula("if(true,)"); - fe.clearAllCachedResultValues(); - CellValue cv; - try { - cv = fe.evaluate(cell); - } catch (EmptyStackException e) { - throw new AssertionFailedError("Missing args evaluation not implemented (bug 43354"); - } - // MissingArg -> BlankEval -> zero (as formula result) - assertEquals(0.0, cv.getNumberValue(), 0.0); - - // MissingArg -> BlankEval -> empty string (in concatenation) - cell.setCellFormula("\"abc\"&if(true,)"); - fe.clearAllCachedResultValues(); - assertEquals("abc", fe.evaluate(cell).getStringValue()); - } - - public void testCountFuncs() { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - HSSFSheet sheet = wb.createSheet("Sheet1"); - HSSFCell cell = sheet.createRow(0).createCell(0); - - cell.setCellFormula("COUNT(C5,,,,)"); // 4 missing args, C5 is blank - assertEquals(4.0, fe.evaluate(cell).getNumberValue(), 0.0); - - cell.setCellFormula("COUNTA(C5,,)"); // 2 missing args, C5 is blank - fe.clearAllCachedResultValues(); - assertEquals(2.0, fe.evaluate(cell).getNumberValue(), 0.0); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/eval/TestMultiSheetEval.java b/src/testcases/org/apache/poi/ss/formula/eval/TestMultiSheetEval.java deleted file mode 100644 index 9db99b1e5..000000000 --- a/src/testcases/org/apache/poi/ss/formula/eval/TestMultiSheetEval.java +++ /dev/null @@ -1,338 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.eval; - -import java.io.PrintStream; -import java.util.Collection; -import java.util.Locale; - -import junit.framework.Assert; -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.functions.TestMathX; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; - -/** - * Tests formulas for multi sheet reference (i.e. SUM(Sheet1:Sheet5!A1)) - */ -public final class TestMultiSheetEval extends TestCase { - private static final POILogger logger = POILogFactory.getLogger(TestFormulasFromSpreadsheet.class); - - private static final class Result { - public static final int SOME_EVALUATIONS_FAILED = -1; - public static final int ALL_EVALUATIONS_SUCCEEDED = +1; - public static final int NO_EVALUATIONS_FOUND = 0; - } - - /** - * This class defines constants for navigating around the test data spreadsheet used for these tests. - */ - private static final class SS { - - /** - * Name of the test spreadsheet (found in the standard test data folder) - */ - public final static String FILENAME = "FormulaSheetRange.xls"; - /** - * Row (zero-based) in the test spreadsheet where the function examples start. - */ - public static final int START_FUNCTIONS_ROW_INDEX = 10; // Row '11' - /** - * Index of the column that contains the function names - */ - public static final int COLUMN_INDEX_FUNCTION_NAME = 0; // Column 'A' - /** - * Index of the column that contains the test names - */ - public static final int COLUMN_INDEX_TEST_NAME = 1; // Column 'B' - /** - * Used to indicate when there are no more functions left - */ - public static final String FUNCTION_NAMES_END_SENTINEL = ""; - - /** - * Index of the column where the test expected value is present - */ - public static final short COLUMN_INDEX_EXPECTED_VALUE = 2; // Column 'C' - /** - * Index of the column where the test actual value is present - */ - public static final short COLUMN_INDEX_ACTUAL_VALUE = 3; // Column 'D' - /** - * Test sheet name (sheet with all test formulae) - */ - public static final String TEST_SHEET_NAME = "test"; - } - - private HSSFWorkbook workbook; - private Sheet sheet; - // Note - multiple failures are aggregated before ending. - // If one or more functions fail, a single AssertionFailedError is thrown at the end - private int _functionFailureCount; - private int _functionSuccessCount; - private int _evaluationFailureCount; - private int _evaluationSuccessCount; - - private static void confirmExpectedResult(String msg, Cell expected, CellValue actual) { - if (expected == null) { - throw new AssertionFailedError(msg + " - Bad setup data expected value is null"); - } - if(actual == null) { - throw new AssertionFailedError(msg + " - actual value was null"); - } - - final CellType cellType = expected.getCellTypeEnum(); - - switch (cellType) { - case BLANK: - assertEquals(msg, CellType.BLANK, actual.getCellTypeEnum()); - break; - case BOOLEAN: - assertEquals(msg, CellType.BOOLEAN, actual.getCellTypeEnum()); - assertEquals(msg, expected.getBooleanCellValue(), actual.getBooleanValue()); - break; - case ERROR: - assertEquals(msg, CellType.ERROR, actual.getCellTypeEnum()); - assertEquals(msg, ErrorEval.getText(expected.getErrorCellValue()), ErrorEval.getText(actual.getErrorValue())); - break; - case FORMULA: // will never be used, since we will call method after formula evaluation - throw new AssertionFailedError("Cannot expect formula as result of formula evaluation: " + msg); - case NUMERIC: - assertEquals(msg, CellType.NUMERIC, actual.getCellTypeEnum()); - TestMathX.assertEquals(msg, expected.getNumericCellValue(), actual.getNumberValue(), TestMathX.POS_ZERO, TestMathX.DIFF_TOLERANCE_FACTOR); - break; - case STRING: - assertEquals(msg, CellType.STRING, actual.getCellTypeEnum()); - assertEquals(msg, expected.getRichStringCellValue().getString(), actual.getStringValue()); - break; - default: - throw new AssertionFailedError("Unexpected cell type: " + cellType); - } - } - - - @Override - protected void setUp() { - if (workbook == null) { - workbook = HSSFTestDataSamples.openSampleWorkbook(SS.FILENAME); - sheet = workbook.getSheet( SS.TEST_SHEET_NAME ); - } - _functionFailureCount = 0; - _functionSuccessCount = 0; - _evaluationFailureCount = 0; - _evaluationSuccessCount = 0; - } - - public void testFunctionsFromTestSpreadsheet() { - - processFunctionGroup(SS.START_FUNCTIONS_ROW_INDEX, null); - - // confirm results - String successMsg = "There were " - + _evaluationSuccessCount + " successful evaluation(s) and " - + _functionSuccessCount + " function(s) without error"; - if(_functionFailureCount > 0) { - String msg = _functionFailureCount + " function(s) failed in " - + _evaluationFailureCount + " evaluation(s). " + successMsg; - throw new AssertionFailedError(msg); - } - logger.log(POILogger.INFO, getClass().getName() + ": " + successMsg); - } - - /** - * @param startRowIndex row index in the spreadsheet where the first function/operator is found - * @param testFocusFunctionName name of a single function/operator to test alone. - * Typically pass null to test all functions - */ - private void processFunctionGroup(int startRowIndex, String testFocusFunctionName) { - HSSFFormulaEvaluator evaluator = new HSSFFormulaEvaluator(workbook); - Collection funcs = FunctionEval.getSupportedFunctionNames(); - - int rowIndex = startRowIndex; - while (true) { - Row r = sheet.getRow(rowIndex); - - // only evaluate non empty row - if( r != null ) - { - String targetFunctionName = getTargetFunctionName(r); - String targetTestName = getTargetTestName(r); - if(targetFunctionName == null) { - throw new AssertionFailedError("Test spreadsheet cell empty on row (" - + (rowIndex+1) + "). Expected function name or '" - + SS.FUNCTION_NAMES_END_SENTINEL + "'"); - } - if(targetFunctionName.equals(SS.FUNCTION_NAMES_END_SENTINEL)) { - // found end of functions list - break; - } - if(testFocusFunctionName == null || targetFunctionName.equalsIgnoreCase(testFocusFunctionName)) { - - // expected results are on the row below - Cell expectedValueCell = r.getCell(SS.COLUMN_INDEX_EXPECTED_VALUE); - if(expectedValueCell == null) { - int missingRowNum = rowIndex + 1; - throw new AssertionFailedError("Missing expected values cell for function '" - + targetFunctionName + ", test" + targetTestName + " (row " + - missingRowNum + ")"); - } - - switch(processFunctionRow(evaluator, targetFunctionName, targetTestName, r, expectedValueCell)) { - case Result.ALL_EVALUATIONS_SUCCEEDED: _functionSuccessCount++; break; - case Result.SOME_EVALUATIONS_FAILED: _functionFailureCount++; break; - default: - throw new RuntimeException("unexpected result"); - case Result.NO_EVALUATIONS_FOUND: // do nothing - String uname = targetFunctionName.toUpperCase(Locale.ROOT); - if(startRowIndex >= SS.START_FUNCTIONS_ROW_INDEX && - funcs.contains(uname)) { - logger.log(POILogger.WARN, uname + ": function is supported but missing test data"); - } - break; - } - } - } - rowIndex ++; - } - } - - /** - * - * @return a constant from the local Result class denoting whether there were any evaluation - * cases, and whether they all succeeded. - */ - private int processFunctionRow(HSSFFormulaEvaluator evaluator, String targetFunctionName, - String targetTestName, Row formulasRow, Cell expectedValueCell) { - - int result = Result.NO_EVALUATIONS_FOUND; // so far - - Cell c = formulasRow.getCell(SS.COLUMN_INDEX_ACTUAL_VALUE); - if (c == null || c.getCellTypeEnum() != CellType.FORMULA) { - return result; - } - - CellValue actualValue = evaluator.evaluate(c); - - try { - confirmExpectedResult("Function '" + targetFunctionName + "': Test: '" + targetTestName + "' Formula: " + c.getCellFormula() - + " @ " + formulasRow.getRowNum() + ":" + SS.COLUMN_INDEX_ACTUAL_VALUE, - expectedValueCell, actualValue); - _evaluationSuccessCount ++; - if(result != Result.SOME_EVALUATIONS_FAILED) { - result = Result.ALL_EVALUATIONS_SUCCEEDED; - } - } catch (AssertionFailedError e) { - _evaluationFailureCount ++; - printShortStackTrace(System.err, e); - result = Result.SOME_EVALUATIONS_FAILED; - } - - return result; - } - - /** - * Useful to keep output concise when expecting many failures to be reported by this test case - */ - private static void printShortStackTrace(PrintStream ps, AssertionFailedError e) { - StackTraceElement[] stes = e.getStackTrace(); - - int startIx = 0; - // skip any top frames inside junit.framework.Assert - while(startIx= endIx) { - // something went wrong. just print the whole stack trace - e.printStackTrace(ps); - } - endIx -= 4; // skip 4 frames of reflection invocation - ps.println(e.toString()); - for(int i=startIx; inull if cell is missing, empty or blank - */ - private static String getTargetFunctionName(Row r) { - if(r == null) { - System.err.println("Warning - given null row, can't figure out function name"); - return null; - } - Cell cell = r.getCell(SS.COLUMN_INDEX_FUNCTION_NAME); - if(cell == null) { - System.err.println("Warning - Row " + r.getRowNum() + " has no cell " + SS.COLUMN_INDEX_FUNCTION_NAME + ", can't figure out function name"); - return null; - } - if(cell.getCellTypeEnum() == CellType.BLANK) { - return null; - } - if(cell.getCellTypeEnum() == CellType.STRING) { - return cell.getRichStringCellValue().getString(); - } - - throw new AssertionFailedError("Bad cell type for 'function name' column: (" - + cell.getCellTypeEnum() + ") row (" + (r.getRowNum() +1) + ")"); - } - /** - * @return null if cell is missing, empty or blank - */ - private static String getTargetTestName(Row r) { - if(r == null) { - System.err.println("Warning - given null row, can't figure out test name"); - return null; - } - Cell cell = r.getCell(SS.COLUMN_INDEX_TEST_NAME); - if(cell == null) { - System.err.println("Warning - Row " + r.getRowNum() + " has no cell " + SS.COLUMN_INDEX_TEST_NAME + ", can't figure out test name"); - return null; - } - if(cell.getCellTypeEnum() == CellType.BLANK) { - return null; - } - if(cell.getCellTypeEnum() == CellType.STRING) { - return cell.getRichStringCellValue().getString(); - } - - throw new AssertionFailedError("Bad cell type for 'test name' column: (" - + cell.getCellTypeEnum() + ") row (" + (r.getRowNum() +1) + ")"); - } - -} diff --git a/src/testcases/org/apache/poi/ss/formula/eval/TestOperandResolver.java b/src/testcases/org/apache/poi/ss/formula/eval/TestOperandResolver.java deleted file mode 100644 index 4e24f84e7..000000000 --- a/src/testcases/org/apache/poi/ss/formula/eval/TestOperandResolver.java +++ /dev/null @@ -1,89 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.eval; - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -/** - * Tests for OperandResolver - * - * @author Brendan Nolan - */ -public final class TestOperandResolver extends TestCase { - - public void testParseDouble_bug48472() { - - String value = "-"; - - Double resolvedValue = null; - - try { - resolvedValue = OperandResolver.parseDouble(value); - } catch (StringIndexOutOfBoundsException e) { - throw new AssertionFailedError("Identified bug 48472"); - } - - assertEquals(null, resolvedValue); - - } - - public void testParseDouble_bug49723() { - - String value = ".1"; - - Double resolvedValue = null; - - resolvedValue = OperandResolver.parseDouble(value); - - assertNotNull("Identified bug 49723", resolvedValue); - - } - - /** - * - * Tests that a list of valid strings all return a non null value from {@link OperandResolver#parseDouble(String)} - * - */ - public void testParseDoubleValidStrings() { - - String[] values = new String[]{".19", "0.19", "1.9", "1E4", "-.19", "-0.19", "8.5","-1E4", ".5E6","+1.5","+1E5", " +1E5 "}; - - for (String value : values) { - assertTrue(OperandResolver.parseDouble(value) != null); - assertEquals(OperandResolver.parseDouble(value), Double.parseDouble(value)); - } - - } - - /** - * - * Tests that a list of invalid strings all return null from {@link OperandResolver#parseDouble(String)} - * - */ - public void testParseDoubleInvalidStrings() { - - String[] values = new String[]{"-", "ABC", "-X", "1E5a", "Infinity", "NaN", ".5F", "1,000"}; - - for (String value : values) { - assertEquals(null, OperandResolver.parseDouble(value)); - } - - } - -} diff --git a/src/testcases/org/apache/poi/ss/formula/eval/TestPercentEval.java b/src/testcases/org/apache/poi/ss/formula/eval/TestPercentEval.java deleted file mode 100644 index 71cf649dd..000000000 --- a/src/testcases/org/apache/poi/ss/formula/eval/TestPercentEval.java +++ /dev/null @@ -1,84 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.eval; - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -import org.apache.poi.ss.formula.functions.EvalFactory; -import org.apache.poi.ss.formula.functions.NumericFunctionInvoker; -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; - -/** - * Test for percent operator evaluator. - * - * @author Josh Micich - */ -public final class TestPercentEval extends TestCase { - - private static void confirm(ValueEval arg, double expectedResult) { - ValueEval[] args = { - arg, - }; - - double result = NumericFunctionInvoker.invoke(PercentEval.instance, args, 0, 0); - - assertEquals(expectedResult, result, 0); - } - - public void testBasic() { - confirm(new NumberEval(5), 0.05); - confirm(new NumberEval(3000), 30.0); - confirm(new NumberEval(-150), -1.5); - confirm(new StringEval("0.2"), 0.002); - confirm(BoolEval.TRUE, 0.01); - } - - public void test1x1Area() { - AreaEval ae = EvalFactory.createAreaEval("B2:B2", new ValueEval[] { new NumberEval(50), }); - confirm(ae, 0.5); - } - public void testInSpreadSheet() { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("Sheet1"); - HSSFRow row = sheet.createRow(0); - HSSFCell cell = row.createCell(0); - cell.setCellFormula("B1%"); - row.createCell(1).setCellValue(50.0); - - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - CellValue cv; - try { - cv = fe.evaluate(cell); - } catch (RuntimeException e) { - if(e.getCause() instanceof NullPointerException) { - throw new AssertionFailedError("Identified bug 44608"); - } - // else some other unexpected error - throw e; - } - assertEquals(CellType.NUMERIC, cv.getCellTypeEnum()); - assertEquals(0.5, cv.getNumberValue(), 0.0); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/eval/TestRangeEval.java b/src/testcases/org/apache/poi/ss/formula/eval/TestRangeEval.java deleted file mode 100644 index 6a6443660..000000000 --- a/src/testcases/org/apache/poi/ss/formula/eval/TestRangeEval.java +++ /dev/null @@ -1,170 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.eval; - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.TwoDEval; -import org.apache.poi.ss.formula.ptg.AreaI; -import org.apache.poi.ss.formula.ptg.AreaI.OffsetArea; -import org.apache.poi.ss.usermodel.CellValue; -import org.apache.poi.ss.util.AreaReference; -import org.apache.poi.ss.util.CellReference; - -/** - * Test for unary plus operator evaluator. - * - * @author Josh Micich - */ -public final class TestRangeEval extends TestCase { - - public void testPermutations() { - - confirm("B3", "D7", "B3:D7"); - confirm("B1", "B1", "B1:B1"); - - confirm("B7", "D3", "B3:D7"); - confirm("D3", "B7", "B3:D7"); - confirm("D7", "B3", "B3:D7"); - } - - private static void confirm(String refA, String refB, String expectedAreaRef) { - - ValueEval[] args = { - createRefEval(refA), - createRefEval(refB), - }; - @SuppressWarnings("deprecation") - AreaReference ar = new AreaReference(expectedAreaRef); - ValueEval result = EvalInstances.Range.evaluate(args, 0, (short)0); - assertTrue(result instanceof AreaEval); - AreaEval ae = (AreaEval) result; - assertEquals(ar.getFirstCell().getRow(), ae.getFirstRow()); - assertEquals(ar.getLastCell().getRow(), ae.getLastRow()); - assertEquals(ar.getFirstCell().getCol(), ae.getFirstColumn()); - assertEquals(ar.getLastCell().getCol(), ae.getLastColumn()); - } - - private static ValueEval createRefEval(String refStr) { - CellReference cr = new CellReference(refStr); - return new MockRefEval(cr.getRow(), cr.getCol()); - - } - - private static final class MockRefEval extends RefEvalBase { - public MockRefEval(int rowIndex, int columnIndex) { - super(-1, -1, rowIndex, columnIndex); - } - @Override - public ValueEval getInnerValueEval(int sheetIndex) { - throw new RuntimeException("not expected to be called during this test"); - } - @Override - public AreaEval offset(int relFirstRowIx, int relLastRowIx, int relFirstColIx, - int relLastColIx) { - AreaI area = new OffsetArea(getRow(), getColumn(), - relFirstRowIx, relLastRowIx, relFirstColIx, relLastColIx); - return new MockAreaEval(area); - } - } - - private static final class MockAreaEval extends AreaEvalBase { - - public MockAreaEval(AreaI ptg) { - super(ptg); - } - private MockAreaEval(int firstRow, int firstColumn, int lastRow, int lastColumn) { - super(firstRow, firstColumn, lastRow, lastColumn); - } - @Override - public ValueEval getRelativeValue(int relativeRowIndex, int relativeColumnIndex) { - throw new RuntimeException("not expected to be called during this test"); - } - @Override - public ValueEval getRelativeValue(int sheetIndex, int relativeRowIndex, int relativeColumnIndex) { - throw new RuntimeException("not expected to be called during this test"); - } - @Override - public AreaEval offset(int relFirstRowIx, int relLastRowIx, int relFirstColIx, - int relLastColIx) { - AreaI area = new OffsetArea(getFirstRow(), getFirstColumn(), - relFirstRowIx, relLastRowIx, relFirstColIx, relLastColIx); - - return new MockAreaEval(area); - } - @Override - public TwoDEval getRow(int rowIndex) { - if (rowIndex >= getHeight()) { - throw new IllegalArgumentException("Invalid rowIndex " + rowIndex - + ". Allowable range is (0.." + getHeight() + ")."); - } - return new MockAreaEval(rowIndex, getFirstColumn(), rowIndex, getLastColumn()); - } - @Override - public TwoDEval getColumn(int columnIndex) { - if (columnIndex >= getWidth()) { - throw new IllegalArgumentException("Invalid columnIndex " + columnIndex - + ". Allowable range is (0.." + getWidth() + ")."); - } - return new MockAreaEval(getFirstRow(), columnIndex, getLastRow(), columnIndex); - } - } - - public void testRangeUsingOffsetFunc_bug46948() { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFRow row = wb.createSheet("Sheet1").createRow(0); - HSSFCell cellA1 = row.createCell(0); - HSSFCell cellB1 = row.createCell(1); - row.createCell(2).setCellValue(5.0); // C1 - row.createCell(3).setCellValue(7.0); // D1 - row.createCell(4).setCellValue(9.0); // E1 - - - cellA1.setCellFormula("SUM(C1:OFFSET(C1,0,B1))"); - - cellB1.setCellValue(1.0); // range will be C1:D1 - - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - CellValue cv; - try { - cv = fe.evaluate(cellA1); - } catch (IllegalArgumentException e) { - if (e.getMessage().equals("Unexpected ref arg class (org.apache.poi.ss.formula.LazyAreaEval)")) { - throw new AssertionFailedError("Identified bug 46948"); - } - throw e; - } - - assertEquals(12.0, cv.getNumberValue(), 0.0); - - cellB1.setCellValue(2.0); // range will be C1:E1 - fe.notifyUpdateCell(cellB1); - cv = fe.evaluate(cellA1); - assertEquals(21.0, cv.getNumberValue(), 0.0); - - cellB1.setCellValue(0.0); // range will be C1:C1 - fe.notifyUpdateCell(cellB1); - cv = fe.evaluate(cellA1); - assertEquals(5.0, cv.getNumberValue(), 0.0); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/eval/TestUnaryPlusEval.java b/src/testcases/org/apache/poi/ss/formula/eval/TestUnaryPlusEval.java deleted file mode 100644 index c4a39fc14..000000000 --- a/src/testcases/org/apache/poi/ss/formula/eval/TestUnaryPlusEval.java +++ /dev/null @@ -1,58 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.eval; - -import junit.framework.TestCase; - -import org.apache.poi.ss.formula.ptg.AreaPtg; -import org.apache.poi.ss.formula.functions.EvalFactory; -import org.apache.poi.ss.formula.functions.NumericFunctionInvoker; - -/** - * Test for unary plus operator evaluator. - * - * @author Josh Micich - */ -public final class TestUnaryPlusEval extends TestCase { - - /** - * Test for bug observable at svn revision 618865 (5-Feb-2008)
    - * The code for handling column operands had been copy-pasted from the row handling code. - */ - public void testColumnOperand() { - - short firstRow = (short)8; - short lastRow = (short)12; - short colNum = (short)5; - AreaPtg areaPtg = new AreaPtg(firstRow, lastRow, colNum, colNum, false, false, false, false); - ValueEval[] values = { - new NumberEval(27), - new NumberEval(29), - new NumberEval(35), // value in row 10 - new NumberEval(37), - new NumberEval(38), - }; - ValueEval[] args = { - EvalFactory.createAreaEval(areaPtg, values), - }; - - double result = NumericFunctionInvoker.invoke(EvalInstances.UnaryPlus, args, 10, (short)20); - - assertEquals(35, result, 0); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/eval/forked/TestForkedEvaluator.java b/src/testcases/org/apache/poi/ss/formula/eval/forked/TestForkedEvaluator.java deleted file mode 100644 index e00dbafd3..000000000 --- a/src/testcases/org/apache/poi/ss/formula/eval/forked/TestForkedEvaluator.java +++ /dev/null @@ -1,122 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.eval.forked; - -import static org.junit.Assert.assertEquals; - -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.IStabilityClassifier; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; - -public class TestForkedEvaluator { - - @Rule - public ExpectedException expectedEx = ExpectedException.none(); - - protected Workbook newWorkbook() { - return new HSSFWorkbook(); - } - - /** - * set up a calculation workbook with input cells nicely segregated on a - * sheet called "Inputs" - */ - protected Workbook createWorkbook() { - Workbook wb = newWorkbook(); - Sheet sheet1 = wb.createSheet("Inputs"); - Sheet sheet2 = wb.createSheet("Calculations"); - Row row; - row = sheet2.createRow(0); - row.createCell(0).setCellFormula("B1*Inputs!A1-Inputs!B1"); - row.createCell(1).setCellValue(5.0); // Calculations!B1 - - // some default input values - row = sheet1.createRow(0); - row.createCell(0).setCellValue(2.0); // Inputs!A1 - row.createCell(1).setCellValue(3.0); // Inputs!B1 - return wb; - } - - /** - * Shows a basic use-case for {@link ForkedEvaluator} - */ - @Test - public void testBasic() throws IOException { - Workbook wb = createWorkbook(); - - // The stability classifier is useful to reduce memory consumption of caching logic - IStabilityClassifier stabilityClassifier = new IStabilityClassifier() { - @Override - public boolean isCellFinal(int sheetIndex, int rowIndex, int columnIndex) { - return sheetIndex == 1; - } - }; - - ForkedEvaluator fe1 = ForkedEvaluator.create(wb, stabilityClassifier, null); - ForkedEvaluator fe2 = ForkedEvaluator.create(wb, stabilityClassifier, null); - - // fe1 and fe2 can be used concurrently on separate threads - - fe1.updateCell("Inputs", 0, 0, new NumberEval(4.0)); - fe1.updateCell("Inputs", 0, 1, new NumberEval(1.1)); - - fe2.updateCell("Inputs", 0, 0, new NumberEval(1.2)); - fe2.updateCell("Inputs", 0, 1, new NumberEval(2.0)); - - assertEquals(18.9, ((NumberEval) fe1.evaluate("Calculations", 0, 0)).getNumberValue(), 0.0); - assertEquals(4.0, ((NumberEval) fe2.evaluate("Calculations", 0, 0)).getNumberValue(), 0.0); - fe1.updateCell("Inputs", 0, 0, new NumberEval(3.0)); - assertEquals(13.9, ((NumberEval) fe1.evaluate("Calculations", 0, 0)).getNumberValue(), 0.0); - - wb.close(); - } - - /** - * As of Sep 2009, the Forked evaluator can update values from existing cells (this is because - * the underlying 'master' cell is used as a key into the calculation cache. Prior to the fix - * for this bug, an attempt to update a missing cell would result in NPE. This junit tests for - * a more meaningful error message.
    - * - * An alternate solution might involve allowing empty cells to be created as necessary. That - * was considered less desirable because so far, the underlying 'master' workbook is strictly - * read-only with respect to the ForkedEvaluator. - */ - @Test - public void testMissingInputCellH() throws IOException { - expectedEx.expect(UnsupportedOperationException.class); - expectedEx.expectMessage("Underlying cell 'A2' is missing in master sheet."); - - Workbook wb = createWorkbook(); - - try { - ForkedEvaluator fe = ForkedEvaluator.create(wb, null, null); - // attempt update input at cell A2 (which is missing) - fe.updateCell("Inputs", 1, 0, new NumberEval(4.0)); - } finally { - wb.close(); - } - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/function/AllFormulaFunctionTests.java b/src/testcases/org/apache/poi/ss/formula/function/AllFormulaFunctionTests.java deleted file mode 100644 index 1931bdbcd..000000000 --- a/src/testcases/org/apache/poi/ss/formula/function/AllFormulaFunctionTests.java +++ /dev/null @@ -1,33 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.function; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -/** - * Collects all tests for this org.apache.poi.hssf.record.formula.function. - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestFunctionMetadataRegistry.class, - TestParseMissingBuiltInFuncs.class, - TestReadMissingBuiltInFuncs.class -}) -public class AllFormulaFunctionTests { -} diff --git a/src/testcases/org/apache/poi/ss/formula/function/ExcelFileFormatDocFunctionExtractor.java b/src/testcases/org/apache/poi/ss/formula/function/ExcelFileFormatDocFunctionExtractor.java deleted file mode 100644 index 2dab84ca7..000000000 --- a/src/testcases/org/apache/poi/ss/formula/function/ExcelFileFormatDocFunctionExtractor.java +++ /dev/null @@ -1,635 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.function; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.PrintStream; -import java.io.UnsupportedEncodingException; -import java.math.BigInteger; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLConnection; -import java.security.MessageDigest; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Stack; -import java.util.zip.ZipException; -import java.util.zip.ZipFile; - -import org.apache.poi.poifs.crypt.CryptoFunctions; -import org.apache.poi.poifs.crypt.HashAlgorithm; -import org.apache.poi.util.TempFile; -import org.xml.sax.Attributes; -import org.xml.sax.ContentHandler; -import org.xml.sax.InputSource; -import org.xml.sax.Locator; -import org.xml.sax.SAXException; -import org.xml.sax.XMLReader; -import org.xml.sax.helpers.XMLReaderFactory; - -/** - * This class is not used during normal POI run-time but is used at development time to generate - * the file 'functionMetadata.txt'. There are more than 300 built-in functions in Excel and the - * intention of this class is to make it easier to maintain the metadata, by extracting it from - * a reliable source. - */ -public final class ExcelFileFormatDocFunctionExtractor { - - private static final String SOURCE_DOC_FILE_NAME = "excelfileformat.odt"; - - /** - * For simplicity, the output file is strictly simple ASCII. - * This method detects any unexpected characters. - */ - /* package */ static boolean isSimpleAscii(char c) { - - if (c>=0x21 && c<=0x7E) { - // everything from '!' to '~' (includes letters, digits, punctuation - return true; - } - // some specific whitespace chars below 0x21: - switch(c) { - case ' ': - case '\t': - case '\r': - case '\n': - return true; - } - return false; - } - - - private static final class FunctionData { - // special characters from the ooo document - private static final int CHAR_ELLIPSIS_8230 = 8230; - private static final int CHAR_NDASH_8211 = 8211; - - private final int _index; - private final boolean _hasFootnote; - private final String _name; - private final int _minParams; - private final int _maxParams; - private final String _returnClass; - private final String _paramClasses; - private final boolean _isVolatile; - - public FunctionData(int funcIx, boolean hasFootnote, String funcName, int minParams, int maxParams, - String returnClass, String paramClasses, boolean isVolatile) { - _index = funcIx; - _hasFootnote = hasFootnote; - _name = funcName; - _minParams = minParams; - _maxParams = maxParams; - _returnClass = convertSpecialChars(returnClass); - _paramClasses = convertSpecialChars(paramClasses); - _isVolatile = isVolatile; - } - private static String convertSpecialChars(String ss) { - StringBuffer sb = new StringBuffer(ss.length() + 4); - for(int i=0; i _allFunctionsByIndex; - private final Map _allFunctionsByName; - private final Set _groupFunctionIndexes; - private final Set _groupFunctionNames; - private final PrintStream _ps; - - public FunctionDataCollector(PrintStream ps) { - _ps = ps; - _allFunctionsByIndex = new HashMap(); - _allFunctionsByName = new HashMap(); - _groupFunctionIndexes = new HashSet(); - _groupFunctionNames = new HashSet(); - } - - public void addFuntion(int funcIx, boolean hasFootnote, String funcName, int minParams, int maxParams, - String returnClass, String paramClasses, String volatileFlagStr) { - boolean isVolatile = volatileFlagStr.length() > 0; - - Integer funcIxKey = Integer.valueOf(funcIx); - if(!_groupFunctionIndexes.add(funcIxKey)) { - throw new RuntimeException("Duplicate function index (" + funcIx + ")"); - } - if(!_groupFunctionNames.add(funcName)) { - throw new RuntimeException("Duplicate function name '" + funcName + "'"); - } - - checkRedefinedFunction(hasFootnote, funcName, funcIxKey); - FunctionData fd = new FunctionData(funcIx, hasFootnote, funcName, - minParams, maxParams, returnClass, paramClasses, isVolatile); - - _allFunctionsByIndex.put(funcIxKey, fd); - _allFunctionsByName.put(funcName, fd); - } - - /** - * Some extra validation here. - * Any function which changes definition will have a footnote in the source document - */ - private void checkRedefinedFunction(boolean hasNote, String funcName, Integer funcIxKey) { - FunctionData fdPrev; - // check by index - fdPrev = _allFunctionsByIndex.get(funcIxKey); - if(fdPrev != null) { - if(!fdPrev.hasFootnote() || !hasNote) { - throw new RuntimeException("changing function [" - + funcIxKey + "] definition without foot-note"); - } - _allFunctionsByName.remove(fdPrev.getName()); - } - // check by name - fdPrev = _allFunctionsByName.get(funcName); - if(fdPrev != null) { - if(!fdPrev.hasFootnote() || !hasNote) { - throw new RuntimeException("changing function '" - + funcName + "' definition without foot-note"); - } - _allFunctionsByIndex.remove(Integer.valueOf(fdPrev.getIndex())); - } - } - - public void endTableGroup(String headingText) { - Integer[] keys = new Integer[_groupFunctionIndexes.size()]; - _groupFunctionIndexes.toArray(keys); - _groupFunctionIndexes.clear(); - _groupFunctionNames.clear(); - Arrays.sort(keys); - - _ps.println("# " + headingText); - for (Integer key : keys) { - FunctionData fd = _allFunctionsByIndex.get(key); - _ps.println(fd.formatAsDataLine()); - } - } - } - - /** - * To avoid drag-in - parse XML using only JDK. - */ - private static class EFFDocHandler implements ContentHandler { - private static final String[] HEADING_PATH_NAMES = { - "office:document-content", "office:body", "office:text", "text:h", - }; - private static final String[] TABLE_BASE_PATH_NAMES = { - "office:document-content", "office:body", "office:text", "table:table", - }; - private static final String[] TABLE_ROW_RELPATH_NAMES = { - "table:table-row", - }; - private static final String[] TABLE_CELL_RELPATH_NAMES = { - "table:table-row", "table:table-cell", "text:p", - }; - // after May 2008 there was one more style applied to the footnotes - private static final String[] NOTE_REF_RELPATH_NAMES_OLD = { - "table:table-row", "table:table-cell", "text:p", "text:span", "text:note-ref", - }; - private static final String[] NOTE_REF_RELPATH_NAMES = { - "table:table-row", "table:table-cell", "text:p", "text:span", "text:span", "text:note-ref", - }; - - - private final Stack _elemNameStack; - /** true only when parsing the target tables */ - private boolean _isInsideTable; - - private final List _rowData; - private final StringBuffer _textNodeBuffer; - private final List _rowNoteFlags; - private boolean _cellHasNote; - - private final FunctionDataCollector _fdc; - private String _lastHeadingText; - - public EFFDocHandler(FunctionDataCollector fdc) { - _fdc = fdc; - _elemNameStack = new Stack(); - _isInsideTable = false; - _rowData = new ArrayList(); - _textNodeBuffer = new StringBuffer(); - _rowNoteFlags = new ArrayList(); - } - - private boolean matchesTargetPath() { - return matchesPath(0, TABLE_BASE_PATH_NAMES); - } - - private boolean matchesRelPath(String[] pathNames) { - return matchesPath(TABLE_BASE_PATH_NAMES.length, pathNames); - } - - private boolean matchesPath(int baseStackIndex, String[] pathNames) { - if(_elemNameStack.size() != baseStackIndex + pathNames.length) { - return false; - } - for (int i = 0; i < pathNames.length; i++) { - if(!_elemNameStack.get(baseStackIndex + i).equals(pathNames[i])) { - return false; - } - } - return true; - } - - @Override - public void characters(char[] ch, int start, int length) { - // only 2 text nodes where text is collected: - if(matchesRelPath(TABLE_CELL_RELPATH_NAMES) || matchesPath(0, HEADING_PATH_NAMES)) { - _textNodeBuffer.append(ch, start, length); - } - } - - @Override - public void endElement(String namespaceURI, String localName, String name) { - String expectedName = _elemNameStack.peek(); - if(expectedName != name) { - throw new RuntimeException("close tag mismatch"); - } - if(matchesPath(0, HEADING_PATH_NAMES)) { - _lastHeadingText = _textNodeBuffer.toString().trim(); - _textNodeBuffer.setLength(0); - } - if(_isInsideTable) { - if(matchesTargetPath()) { - _fdc.endTableGroup(_lastHeadingText); - _isInsideTable = false; - } else if(matchesRelPath(TABLE_ROW_RELPATH_NAMES)) { - String[] cellData = new String[_rowData.size()]; - _rowData.toArray(cellData); - _rowData.clear(); - Boolean[] noteFlags = new Boolean[_rowNoteFlags.size()]; - _rowNoteFlags.toArray(noteFlags); - _rowNoteFlags.clear(); - processTableRow(cellData, noteFlags); - } else if(matchesRelPath(TABLE_CELL_RELPATH_NAMES)) { - _rowData.add(_textNodeBuffer.toString().trim()); - _rowNoteFlags.add(Boolean.valueOf(_cellHasNote)); - _textNodeBuffer.setLength(0); - } - } - _elemNameStack.pop(); - } - - private void processTableRow(String[] cellData, Boolean[] noteFlags) { - // each table row of the document contains data for two functions - if(cellData.length != 15) { - throw new RuntimeException("Bad table row size"); - } - processFunction(cellData, noteFlags, 0); - processFunction(cellData, noteFlags, 8); - } - - public void processFunction(String[] cellData, Boolean[] noteFlags, int i) { - String funcIxStr = cellData[i + 0]; - if (funcIxStr.length() < 1) { - // empty (happens on the right hand side when there is an odd number of functions) - return; - } - int funcIx = parseInt(funcIxStr); - - boolean hasFootnote = noteFlags[i + 1].booleanValue(); - String funcName = cellData[i + 1]; - int minParams = parseInt(cellData[i + 2]); - int maxParams = parseInt(cellData[i + 3]); - - String returnClass = cellData[i + 4]; - String paramClasses = cellData[i + 5]; - String volatileFlagStr = cellData[i + 6]; - - _fdc.addFuntion(funcIx, hasFootnote, funcName, minParams, maxParams, returnClass, paramClasses, volatileFlagStr); - } - - private static int parseInt(String valStr) { - try { - return Integer.parseInt(valStr); - } catch (NumberFormatException e) { - throw new RuntimeException("Value '" + valStr + "' could not be parsed as an integer"); - } - } - - @Override - public void startElement(String namespaceURI, String localName, String name, Attributes atts) { - _elemNameStack.add(name); - if(matchesTargetPath()) { - String tableName = atts.getValue("table:name"); - if(tableName.startsWith("tab_fml_func") && !tableName.equals("tab_fml_func0")) { - _isInsideTable = true; - } - return; - } - if(matchesPath(0, HEADING_PATH_NAMES)) { - _textNodeBuffer.setLength(0); - } else if(matchesRelPath(TABLE_ROW_RELPATH_NAMES)) { - _rowData.clear(); - _rowNoteFlags.clear(); - } else if(matchesRelPath(TABLE_CELL_RELPATH_NAMES)) { - _textNodeBuffer.setLength(0); - _cellHasNote = false; - } else if(matchesRelPath(NOTE_REF_RELPATH_NAMES_OLD)) { - _cellHasNote = true; - } else if(matchesRelPath(NOTE_REF_RELPATH_NAMES)) { - _cellHasNote = true; - } - } - - @Override - public void endDocument() { - // do nothing - } - @Override - public void endPrefixMapping(String prefix) { - // do nothing - } - @Override - public void ignorableWhitespace(char[] ch, int start, int length) { - // do nothing - } - @Override - public void processingInstruction(String target, String data) { - // do nothing - } - @Override - public void setDocumentLocator(Locator locator) { - // do nothing - } - @Override - public void skippedEntity(String name) { - // do nothing - } - @Override - public void startDocument() { - // do nothing - } - @Override - public void startPrefixMapping(String prefix, String uri) { - // do nothing - } - } - - private static void extractFunctionData(FunctionDataCollector fdc, InputStream is) { - XMLReader xr; - - try { - // First up, try the default one - xr = XMLReaderFactory.createXMLReader(); - } catch (SAXException e) { - // Try one for java 1.4 - System.setProperty("org.xml.sax.driver", "org.apache.crimson.parser.XMLReaderImpl"); - try { - xr = XMLReaderFactory.createXMLReader(); - } catch (SAXException e2) { - throw new RuntimeException(e2); - } - } - xr.setContentHandler(new EFFDocHandler(fdc)); - - InputSource inSrc = new InputSource(is); - - try { - xr.parse(inSrc); - is.close(); - } catch (IOException e) { - throw new RuntimeException(e); - } catch (SAXException e) { - throw new RuntimeException(e); - } - } - /** - * To be sure that no tricky unicode chars make it through to the output file. - */ - private static final class SimpleAsciiOutputStream extends OutputStream { - - private final OutputStream _os; - - public SimpleAsciiOutputStream(OutputStream os) { - _os = os; - } - - @Override - public void write(int b) throws IOException { - checkByte(b); - _os.write(b); - } - - private static void checkByte(int b) { - if (!isSimpleAscii((char)b)) { - throw new RuntimeException("Encountered char (" + b + ") which was not simple ascii as expected"); - } - } - - @Override - public void write(byte[] b, int off, int len) throws IOException { - for (int i = 0; i < len; i++) { - checkByte(b[i + off]); - - } - _os.write(b, off, len); - } - } - - private static void processFile(File effDocFile, File outFile) { - if(!effDocFile.exists()) { - throw new RuntimeException("file '" + effDocFile.getAbsolutePath() + "' does not exist"); - } - OutputStream os; - try { - os = new FileOutputStream(outFile); - } catch (FileNotFoundException e) { - throw new RuntimeException(e); - } - os = new SimpleAsciiOutputStream(os); - PrintStream ps; - try { - ps = new PrintStream(os, true, "UTF-8"); - } catch(UnsupportedEncodingException e) { - throw new RuntimeException(e); - } - - outputLicenseHeader(ps); - Class genClass = ExcelFileFormatDocFunctionExtractor.class; - ps.println("# Created by (" + genClass.getName() + ")"); - // identify the source file - ps.print("# from source file '" + SOURCE_DOC_FILE_NAME + "'"); - ps.println(" (size=" + effDocFile.length() + ", md5=" + getFileMD5(effDocFile) + ")"); - ps.println("#"); - ps.println("#Columns: (index, name, minParams, maxParams, returnClass, paramClasses, isVolatile, hasFootnote )"); - ps.println(""); - try { - // can't use ZipHelper here, because its in a different module - ZipFile zf = new ZipFile(effDocFile); - InputStream is = zf.getInputStream(zf.getEntry("content.xml")); - extractFunctionData(new FunctionDataCollector(ps), is); - zf.close(); - } catch (ZipException e) { - throw new RuntimeException(e); - } catch (IOException e) { - throw new RuntimeException(e); - } - ps.close(); - - String canonicalOutputFileName; - try { - canonicalOutputFileName = outFile.getCanonicalPath(); - } catch (IOException e) { - throw new RuntimeException(e); - } - System.out.println("Successfully output to '" + canonicalOutputFileName + "'"); - } - - private static void outputLicenseHeader(PrintStream ps) { - String[] lines= { - "Licensed to the Apache Software Foundation (ASF) under one or more", - "contributor license agreements. See the NOTICE file distributed with", - "this work for additional information regarding copyright ownership.", - "The ASF licenses this file to You under the Apache License, Version 2.0", - "(the \"License\"); you may not use this file except in compliance with", - "the License. You may obtain a copy of the License at", - "", - " http://www.apache.org/licenses/LICENSE-2.0", - "", - "Unless required by applicable law or agreed to in writing, software", - "distributed under the License is distributed on an \"AS IS\" BASIS,", - "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", - "See the License for the specific language governing permissions and", - "limitations under the License.", - }; - for (String line : lines) { - ps.print("# "); - ps.println(line); - } - ps.println(); - } - - /** - * Helps identify the source file - */ - private static String getFileMD5(File f) { - MessageDigest m = CryptoFunctions.getMessageDigest(HashAlgorithm.md5); - - byte[]buf = new byte[2048]; - try { - InputStream is = new FileInputStream(f); - while(true) { - int bytesRead = is.read(buf); - if(bytesRead<1) { - break; - } - m.update(buf, 0, bytesRead); - } - is.close(); - } catch (IOException e) { - throw new RuntimeException(e); - } - - return "0x" + new BigInteger(1, m.digest()).toString(16); - } - - private static File downloadSourceFile() { - URL url; - try { - url = new URL("http://sc.openoffice.org/" + SOURCE_DOC_FILE_NAME); - } catch (MalformedURLException e) { - throw new RuntimeException(e); - } - - File result; - byte[]buf = new byte[2048]; - try { - URLConnection conn = url.openConnection(); - InputStream is = conn.getInputStream(); - System.out.println("downloading " + url.toExternalForm()); - result = TempFile.createTempFile("excelfileformat", ".odt"); - OutputStream os = new FileOutputStream(result); - while(true) { - int bytesRead = is.read(buf); - if(bytesRead<1) { - break; - } - os.write(buf, 0, bytesRead); - } - is.close(); - os.close(); - } catch (IOException e) { - throw new RuntimeException(e); - } - System.out.println("file downloaded ok"); - return result; - } - - public static void main(String[] args) { - - File outFile = new File("functionMetadata-asGenerated.txt"); - -// if (false) { // set true to use local file -// File dir = new File("c:/temp"); -// File effDocFile = new File(dir, SOURCE_DOC_FILE_NAME); -// processFile(effDocFile, outFile); -// return; -// } - - File tempEFFDocFile = downloadSourceFile(); - processFile(tempEFFDocFile, outFile); - tempEFFDocFile.delete(); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/function/TestFunctionMetadataRegistry.java b/src/testcases/org/apache/poi/ss/formula/function/TestFunctionMetadataRegistry.java deleted file mode 100644 index b050401d9..000000000 --- a/src/testcases/org/apache/poi/ss/formula/function/TestFunctionMetadataRegistry.java +++ /dev/null @@ -1,44 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.function; - -import junit.framework.TestCase; - -/** - * - * @author Josh Micich - */ -public final class TestFunctionMetadataRegistry extends TestCase { - - public void testWellKnownFunctions() { - confirmFunction(0, "COUNT"); - confirmFunction(1, "IF"); - - } - - private static void confirmFunction(int index, String funcName) { - FunctionMetadata fm; - fm = FunctionMetadataRegistry.getFunctionByIndex(index); - assertNotNull(fm); - assertEquals(funcName, fm.getName()); - - fm = FunctionMetadataRegistry.getFunctionByName(funcName); - assertNotNull(fm); - assertEquals(index, fm.getIndex()); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/function/TestParseMissingBuiltInFuncs.java b/src/testcases/org/apache/poi/ss/formula/function/TestParseMissingBuiltInFuncs.java deleted file mode 100644 index 38afaaa9c..000000000 --- a/src/testcases/org/apache/poi/ss/formula/function/TestParseMissingBuiltInFuncs.java +++ /dev/null @@ -1,107 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.function; - -import static org.junit.Assert.assertEquals; - -import java.io.IOException; - -import org.apache.poi.hssf.model.HSSFFormulaParser; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.ptg.AbstractFunctionPtg; -import org.apache.poi.ss.formula.ptg.FuncPtg; -import org.apache.poi.ss.formula.ptg.FuncVarPtg; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.junit.Test; - -import junit.framework.AssertionFailedError; -/** - * Tests parsing of some built-in functions that were not properly - * registered in POI as of bug #44675, #44733 (March/April 2008). - */ -public final class TestParseMissingBuiltInFuncs { - - private static Ptg[] parse(String formula) throws IOException { - HSSFWorkbook book = new HSSFWorkbook(); - Ptg[] ptgs = HSSFFormulaParser.parse(formula, book); - book.close(); - return ptgs; - } - - private static void confirmFunc(String formula, int expPtgArraySize, boolean isVarArgFunc, int funcIx) - throws IOException { - Ptg[] ptgs = parse(formula); - Ptg ptgF = ptgs[ptgs.length-1]; // func is last RPN token in all these formulas - - // Check critical things in the Ptg array encoding. - if(!(ptgF instanceof AbstractFunctionPtg)) { - throw new RuntimeException("function token missing"); - } - AbstractFunctionPtg func = (AbstractFunctionPtg) ptgF; - if(func.getFunctionIndex() == 255) { - throw new AssertionFailedError("Failed to recognise built-in function in formula '" - + formula + "'"); - } - assertEquals(expPtgArraySize, ptgs.length); - assertEquals(funcIx, func.getFunctionIndex()); - Class expCls = isVarArgFunc ? FuncVarPtg.class : FuncPtg.class; - assertEquals(expCls, ptgF.getClass()); - - // check that parsed Ptg array converts back to formula text OK - HSSFWorkbook book = new HSSFWorkbook(); - String reRenderedFormula = HSSFFormulaParser.toFormulaString(book, ptgs); - assertEquals(formula, reRenderedFormula); - book.close(); - } - - @Test - public void testDatedif() throws IOException { - int expSize = 4; // NB would be 5 if POI added tAttrVolatile properly - confirmFunc("DATEDIF(NOW(),NOW(),\"d\")", expSize, false, 351); - } - - @Test - public void testDdb() throws IOException { - confirmFunc("DDB(1,1,1,1,1)", 6, true, 144); - } - - @Test - public void testAtan() throws IOException { - confirmFunc("ATAN(1)", 2, false, 18); - } - - @Test - public void testUsdollar() throws IOException { - confirmFunc("USDOLLAR(1)", 2, true, 204); - } - - @Test - public void testDBCS() throws IOException { - confirmFunc("DBCS(\"abc\")", 2, false, 215); - } - - @Test - public void testIsnontext() throws IOException { - confirmFunc("ISNONTEXT(\"abc\")", 2, false, 190); - } - - @Test - public void testDproduct() throws IOException { - confirmFunc("DPRODUCT(C1:E5,\"HarvestYield\",G1:H2)", 4, false, 189); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/function/TestReadMissingBuiltInFuncs.java b/src/testcases/org/apache/poi/ss/formula/function/TestReadMissingBuiltInFuncs.java deleted file mode 100644 index d28653743..000000000 --- a/src/testcases/org/apache/poi/ss/formula/function/TestReadMissingBuiltInFuncs.java +++ /dev/null @@ -1,168 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.function; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -import java.lang.reflect.InvocationTargetException; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.record.RecordFormatException; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; - -/** - * Tests reading from a sample spreadsheet some built-in functions that were not properly - * registered in POI as of bug #44675, #44733 (March/April 2008). - */ -public final class TestReadMissingBuiltInFuncs { - - /** - * This spreadsheet has examples of calls to the interesting built-in functions in cells A1:A7 - */ - private static final String SAMPLE_SPREADSHEET_FILE_NAME = "missingFuncs44675.xls"; - - private static HSSFWorkbook wb; - private static HSSFSheet _sheet; - - @BeforeClass - public static void initSheet() { - wb = HSSFTestDataSamples.openSampleWorkbook(SAMPLE_SPREADSHEET_FILE_NAME); - try { - _sheet = wb.getSheetAt(0); - } catch (RecordFormatException e) { - if(e.getCause() instanceof InvocationTargetException) { - InvocationTargetException ite = (InvocationTargetException) e.getCause(); - if(ite.getTargetException() instanceof RuntimeException) { - RuntimeException re = (RuntimeException) ite.getTargetException(); - if(re.getMessage().equals("Invalid built-in function index (189)")) { - fail("DPRODUCT() registered with wrong index"); - } - } - } - // some other unexpected error - throw e; - } - } - - @AfterClass - public static void closeResources() throws Exception { - wb.close(); - } - - @Test - public void testDatedif() { - String formula; - try { - formula = getCellFormula(0); - } catch (IllegalStateException e) { - if(e.getMessage().startsWith("Too few arguments")) { - if(e.getMessage().indexOf("AttrPtg") > 0) { - fail("tAttrVolatile not supported in FormulaParser.toFormulaString"); - } - fail("NOW() registered with 1 arg instead of 0"); - } - if(e.getMessage().startsWith("too much stuff")) { - fail("DATEDIF() not registered"); - } - // some other unexpected error - throw e; - } - assertEquals("DATEDIF(NOW(),NOW(),\"d\")", formula); - } - - @Test - public void testDdb() { - String formula = getCellFormula(1); - if("externalflag(1,1,1,1,1)".equals(formula)) { - fail("DDB() not registered"); - } - assertEquals("DDB(1,1,1,1,1)", formula); - } - - @Test - public void testAtan() { - String formula = getCellFormula(2); - if("ARCTAN(1)".equals(formula)) { - fail("func ix 18 registered as ARCTAN() instead of ATAN()"); - } - assertEquals("ATAN(1)", formula); - } - - @Test - public void testUsdollar() { - String formula = getCellFormula(3); - if("YEN(1)".equals(formula)) { - fail("func ix 204 registered as YEN() instead of USDOLLAR()"); - } - assertEquals("USDOLLAR(1)", formula); - } - - @Test - public void testDBCS() { - String formula = ""; - try { - formula = getCellFormula(4); - } catch (IllegalStateException e) { - if(e.getMessage().startsWith("too much stuff")) { - fail("DBCS() not registered"); - } - // some other unexpected error - throw e; - } catch (NegativeArraySizeException e) { - fail("found err- DBCS() registered with -1 args"); - } - if("JIS(\"abc\")".equals(formula)) { - fail("func ix 215 registered as JIS() instead of DBCS()"); - } - assertEquals("DBCS(\"abc\")", formula); - } - - @Test - public void testIsnontext() { - String formula; - try { - formula = getCellFormula(5); - } catch (IllegalStateException e) { - if(e.getMessage().startsWith("too much stuff")) { - fail("ISNONTEXT() registered with wrong index"); - } - // some other unexpected error - throw e; - } - assertEquals("ISNONTEXT(\"abc\")", formula); - } - - @Test - public void testDproduct() { - String formula = getCellFormula(6); - assertEquals("DPRODUCT(C1:E5,\"HarvestYield\",G1:H2)", formula); - } - - private String getCellFormula(int rowIx) { - String result = _sheet.getRow(rowIx).getCell(0).getCellFormula(); -// if (false) { -// System.err.println(result); -// } - return result; - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/AbstractNumericTestCase.java b/src/testcases/org/apache/poi/ss/formula/functions/AbstractNumericTestCase.java deleted file mode 100644 index cc8b5c52d..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/AbstractNumericTestCase.java +++ /dev/null @@ -1,75 +0,0 @@ -/* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -/* - * Created on May 29, 2005 - * - */ -package org.apache.poi.ss.formula.functions; - -import junit.framework.TestCase; - -/** - * @author Amol S. Deshmukh < amolweb at ya hoo dot com > - * - */ -public abstract class AbstractNumericTestCase extends TestCase { - - public static final double POS_ZERO = 1E-4; - public static final double DIFF_TOLERANCE_FACTOR = 1E-8; - - @Override - public void setUp() { - } - - @Override - public void tearDown() { - } - - /** - * Why doesnt JUnit have a method like this for doubles? - * The current impl (3.8.1) of Junit has a retar*** method - * for comparing doubles. DO NOT use that. - * TODO: This class should really be in an abstract super class - * to avoid code duplication across this project. - * @param message - * @param baseval - * @param checkval - */ - public static void assertEquals(String message, double baseval, double checkval, double almostZero, double diffToleranceFactor) { - double posZero = Math.abs(almostZero); - double negZero = -1 * posZero; - if (Double.isNaN(baseval)) { - assertTrue(message+": Expected " + baseval + " but was " + checkval - , Double.isNaN(baseval)); - } - else if (Double.isInfinite(baseval)) { - assertTrue(message+": Expected " + baseval + " but was " + checkval - , Double.isInfinite(baseval) && ((baseval<0) == (checkval<0))); - } - else { - assertTrue(message+": Expected " + baseval + " but was " + checkval - ,baseval != 0 - ? Math.abs(baseval - checkval) <= Math.abs(diffToleranceFactor * baseval) - : checkval < posZero && checkval > negZero); - } - } - - public static void assertEquals(String msg, double baseval, double checkval) { - assertEquals(msg, baseval, checkval, POS_ZERO, DIFF_TOLERANCE_FACTOR); - } - -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/AllIndividualFunctionEvaluationTests.java b/src/testcases/org/apache/poi/ss/formula/functions/AllIndividualFunctionEvaluationTests.java deleted file mode 100644 index 272c51a39..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/AllIndividualFunctionEvaluationTests.java +++ /dev/null @@ -1,63 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -/** - * Direct tests for all implementors of Function. - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestAverage.class, - TestCountFuncs.class, - TestDate.class, - TestDays360.class, - TestFinanceLib.class, - TestFind.class, - TestIndex.class, - TestIndexFunctionFromSpreadsheet.class, - TestIndirect.class, - TestIsBlank.class, - TestLen.class, - TestLookupFunctionsFromSpreadsheet.class, - TestMatch.class, - TestMathX.class, - TestMid.class, - TestNper.class, - TestOffset.class, - TestPmt.class, - TestRoundFuncs.class, - TestRowCol.class, - TestStatsLib.class, - TestSubtotal.class, - TestSumif.class, - TestSumproduct.class, - TestText.class, - TestTFunc.class, - TestTime.class, - TestTrim.class, - TestTrunc.class, - TestValue.class, - TestXYNumericFunction.class, - TestAddress.class, - TestClean.class -}) -public class AllIndividualFunctionEvaluationTests { -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/AllSpreadsheetBasedTests.java b/src/testcases/org/apache/poi/ss/formula/functions/AllSpreadsheetBasedTests.java deleted file mode 100644 index 2b34dcf8a..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/AllSpreadsheetBasedTests.java +++ /dev/null @@ -1,48 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -/** - * Direct tests for all implementors of Function. - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestCodeFunctionsFromSpreadsheet.class, - TestComplexFunctionsFromSpreadsheet.class, - TestDeltaFunctionsFromSpreadsheet.class, - TestDGetFunctionsFromSpreadsheet.class, - TestDStarFunctionsFromSpreadsheet.class, - TestFactDoubleFunctionsFromSpreadsheet.class, - TestFixedFunctionsFromSpreadsheet.class, - TestImaginaryFunctionsFromSpreadsheet.class, - TestImRealFunctionsFromSpreadsheet.class, - TestIndexFunctionFromSpreadsheet.class, - TestIndirectFunctionFromSpreadsheet.class, - TestLookupFunctionsFromSpreadsheet.class, - TestMatchFunctionsFromSpreadsheet.class, - TestQuotientFunctionsFromSpreadsheet.class, - TestReptFunctionsFromSpreadsheet.class, - TestRomanFunctionsFromSpreadsheet.class, - TestWeekNumFunctionsFromSpreadsheet.class, - TestWeekNumFunctionsFromSpreadsheet2013.class -}) -public class AllSpreadsheetBasedTests { -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/BaseTestFunctionsFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/functions/BaseTestFunctionsFromSpreadsheet.java deleted file mode 100644 index 2d589217e..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/BaseTestFunctionsFromSpreadsheet.java +++ /dev/null @@ -1,239 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Locale; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.hssf.util.CellReference; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; - -@RunWith(Parameterized.class) -public abstract class BaseTestFunctionsFromSpreadsheet { - - /** - * This class defines constants for navigating around the test data spreadsheet used for these tests. - */ - interface SS { - /** Name of the test spreadsheet (found in the standard test data folder) */ - - /** Name of the first sheet in the spreadsheet (contains comments) */ - String README_SHEET_NAME = "Read Me"; - - /** Row (zero-based) in each sheet where the evaluation cases start. */ - int START_TEST_CASES_ROW_INDEX = 4; // Row '5' - /** Index of the column that contains the function names */ - int COLUMN_INDEX_MARKER = 0; // Column 'A' - int COLUMN_INDEX_EVALUATION = 1; // Column 'B' - int COLUMN_INDEX_EXPECTED_RESULT = 2; // Column 'C' - int COLUMN_ROW_COMMENT = 3; // Column 'D' - - /** Used to indicate when there are no more test cases on the current sheet */ - String TEST_CASES_END_MARKER = ""; - /** Used to indicate that the test on the current row should be ignored */ - String SKIP_CURRENT_TEST_CASE_MARKER = ""; - - } - - @Parameter(value = 0) - public String testName; - @Parameter(value = 1) - public String filename; - @Parameter(value = 2) - public HSSFSheet sheet; - @Parameter(value = 3) - public int formulasRowIdx; - @Parameter(value = 4) - public HSSFFormulaEvaluator evaluator; - - - - protected static Collection data(Class clazz, String filename) throws Exception { - HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook(filename); - confirmReadMeSheet(workbook, clazz); - - List data = new ArrayList(); - - int nSheets = workbook.getNumberOfSheets(); - for(int sheetIdx=1; sheetIdx< nSheets; sheetIdx++) { - HSSFSheet sheet = workbook.getSheetAt(sheetIdx); - processFunctionGroup(data, sheet, SS.START_TEST_CASES_ROW_INDEX, null, filename); - } - - workbook.close(); - - return data; - } - - private static void processFunctionGroup(List data, HSSFSheet sheet, final int startRowIndex, String testFocusFunctionName, String filename) { - HSSFFormulaEvaluator evaluator = new HSSFFormulaEvaluator(sheet.getWorkbook()); - - String currentGroupComment = ""; - final int maxRows = sheet.getLastRowNum()+1; - for(int rowIndex=startRowIndex; rowIndex clazz) { - String firstSheetName = workbook.getSheetName(0); - assertTrue("First sheet's name was '" + firstSheetName + "' but expected '" + SS.README_SHEET_NAME + "'", - firstSheetName.equalsIgnoreCase(SS.README_SHEET_NAME)); - HSSFSheet sheet = workbook.getSheetAt(0); - String specifiedClassName = sheet.getRow(2).getCell(0).getRichStringCellValue().getString(); - assertEquals("Test class name in spreadsheet comment", clazz.getName(), specifiedClassName); - } - - /** - * @return null if cell is missing, empty or blank - */ - private static String getCellTextValue(HSSFRow r, int colIndex, String columnName) { - if(r == null) { - return null; - } - HSSFCell cell = r.getCell(colIndex); - if(cell == null) { - return null; - } - if(cell.getCellTypeEnum() == CellType.BLANK) { - return null; - } - if(cell.getCellTypeEnum() == CellType.STRING) { - return cell.getRichStringCellValue().getString(); - } - - fail("Bad cell type for '" + columnName + "' column: (" - + cell.getCellTypeEnum() + ") row (" + (r.getRowNum() +1) + ")"); - return ""; - } - - private static String formatValue(HSSFCell expecedCell) { - switch (expecedCell.getCellTypeEnum()) { - case BLANK: return ""; - case BOOLEAN: return Boolean.toString(expecedCell.getBooleanCellValue()); - case NUMERIC: return Double.toString(expecedCell.getNumericCellValue()); - case STRING: return expecedCell.getRichStringCellValue().getString(); - default: fail("Unexpected cell type of expected value (" + expecedCell.getCellTypeEnum() + ")"); - } - return ""; - } - - -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/EvalFactory.java b/src/testcases/org/apache/poi/ss/formula/functions/EvalFactory.java deleted file mode 100644 index dfe8e53e9..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/EvalFactory.java +++ /dev/null @@ -1,184 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import org.apache.poi.ss.formula.TwoDEval; -import org.apache.poi.ss.formula.eval.AreaEval; -import org.apache.poi.ss.formula.eval.AreaEvalBase; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.RefEval; -import org.apache.poi.ss.formula.eval.RefEvalBase; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.ss.formula.ptg.AreaI; -import org.apache.poi.ss.formula.ptg.AreaPtg; -import org.apache.poi.ss.formula.ptg.Ref3DPtg; -import org.apache.poi.ss.formula.ptg.RefPtg; - -/** - * Test helper class for creating mock Eval objects - * - * @author Josh Micich - */ -public final class EvalFactory { - - private EvalFactory() { - // no instances of this class - } - - /** - * Creates a dummy AreaEval - * @param values empty (null) entries in this array will be converted to NumberEval.ZERO - */ - public static AreaEval createAreaEval(String areaRefStr, ValueEval[] values) { - AreaPtg areaPtg = new AreaPtg(areaRefStr); - return createAreaEval(areaPtg, values); - } - - /** - * Creates a dummy AreaEval - * @param values empty (null) entries in this array will be converted to NumberEval.ZERO - */ - public static AreaEval createAreaEval(AreaPtg areaPtg, ValueEval[] values) { - int nCols = areaPtg.getLastColumn() - areaPtg.getFirstColumn() + 1; - int nRows = areaPtg.getLastRow() - areaPtg.getFirstRow() + 1; - int nExpected = nRows * nCols; - if (values.length != nExpected) { - throw new RuntimeException("Expected " + nExpected + " values but got " + values.length); - } - for (int i = 0; i < nExpected; i++) { - if (values[i] == null) { - values[i] = NumberEval.ZERO; - } - } - return new MockAreaEval(areaPtg, values); - } - - /** - * Creates a single RefEval (with value zero) - */ - public static RefEval createRefEval(String refStr) { - return createRefEval(refStr, NumberEval.ZERO); - } - public static RefEval createRefEval(String refStr, ValueEval value) { - return new MockRefEval(new RefPtg(refStr), value); - } - - private static final class MockAreaEval extends AreaEvalBase { - private final ValueEval[] _values; - public MockAreaEval(AreaI areaPtg, ValueEval[] values) { - super(areaPtg); - _values = values; - } - private MockAreaEval(int firstRow, int firstColumn, int lastRow, int lastColumn, ValueEval[] values) { - super(firstRow, firstColumn, lastRow, lastColumn); - _values = values; - } - @Override - public ValueEval getRelativeValue(int relativeRowIndex, int relativeColumnIndex) { - return getRelativeValue(-1, relativeRowIndex, relativeColumnIndex); - } - @Override - public ValueEval getRelativeValue(int sheetIndex, int relativeRowIndex, int relativeColumnIndex) { - if (relativeRowIndex < 0 || relativeRowIndex >=getHeight()) { - throw new IllegalArgumentException("row index out of range"); - } - int width = getWidth(); - if (relativeColumnIndex < 0 || relativeColumnIndex >=width) { - throw new IllegalArgumentException("column index out of range"); - } - int oneDimensionalIndex = relativeRowIndex * width + relativeColumnIndex; - return _values[oneDimensionalIndex]; - } - @Override - public AreaEval offset(int relFirstRowIx, int relLastRowIx, int relFirstColIx, int relLastColIx) { - if (relFirstRowIx < 0 || relFirstColIx < 0 - || relLastRowIx >= getHeight() || relLastColIx >= getWidth()) { - throw new RuntimeException("Operation not implemented on this mock object"); - } - - if (relFirstRowIx == 0 && relFirstColIx == 0 - && relLastRowIx == getHeight()-1 && relLastColIx == getWidth()-1) { - return this; - } - ValueEval[] values = transpose(_values, getWidth(), relFirstRowIx, relLastRowIx, relFirstColIx, relLastColIx); - return new MockAreaEval(getFirstRow() + relFirstRowIx, getFirstColumn() + relFirstColIx, - getFirstRow() + relLastRowIx, getFirstColumn() + relLastColIx, values); - } - private static ValueEval[] transpose(ValueEval[] srcValues, int srcWidth, - int relFirstRowIx, int relLastRowIx, - int relFirstColIx, int relLastColIx) { - int height = relLastRowIx - relFirstRowIx + 1; - int width = relLastColIx - relFirstColIx + 1; - ValueEval[] result = new ValueEval[height * width]; - for (int r=0; r= getHeight()) { - throw new IllegalArgumentException("Invalid rowIndex " + rowIndex - + ". Allowable range is (0.." + getHeight() + ")."); - } - ValueEval[] values = new ValueEval[getWidth()]; - for (int i = 0; i < values.length; i++) { - values[i] = getRelativeValue(rowIndex, i); - } - return new MockAreaEval(rowIndex, getFirstColumn(), rowIndex, getLastColumn(), values); - } - @Override - public TwoDEval getColumn(int columnIndex) { - if (columnIndex >= getWidth()) { - throw new IllegalArgumentException("Invalid columnIndex " + columnIndex - + ". Allowable range is (0.." + getWidth() + ")."); - } - ValueEval[] values = new ValueEval[getHeight()]; - for (int i = 0; i < values.length; i++) { - values[i] = getRelativeValue(i, columnIndex); - } - return new MockAreaEval(getFirstRow(), columnIndex, getLastRow(), columnIndex, values); - } - } - - private static final class MockRefEval extends RefEvalBase { - private final ValueEval _value; - public MockRefEval(RefPtg ptg, ValueEval value) { - super(-1, -1, ptg.getRow(), ptg.getColumn()); - _value = value; - } - public MockRefEval(Ref3DPtg ptg, ValueEval value) { - super(-1, -1, ptg.getRow(), ptg.getColumn()); - _value = value; - } - @Override - public ValueEval getInnerValueEval(int sheetIndex) { - return _value; - } - @Override - public AreaEval offset(int relFirstRowIx, int relLastRowIx, int relFirstColIx, int relLastColIx) { - throw new RuntimeException("Operation not implemented on this mock object"); - } - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/NumericFunctionInvoker.java b/src/testcases/org/apache/poi/ss/formula/functions/NumericFunctionInvoker.java deleted file mode 100644 index f51e8a22f..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/NumericFunctionInvoker.java +++ /dev/null @@ -1,111 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import junit.framework.AssertionFailedError; - -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumericValueEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.ss.formula.eval.NotImplementedException; - -/** - * Test helper class for invoking functions with numeric results. - * - * @author Josh Micich - */ -public final class NumericFunctionInvoker { - - private NumericFunctionInvoker() { - // no instances of this class - } - - private static final class NumericEvalEx extends Exception { - public NumericEvalEx(String msg) { - super(msg); - } - } - - /** - * Invokes the specified function with the arguments. - *

    - * Assumes that the cell coordinate parameters of - * Function.evaluate(args, srcCellRow, srcCellCol) - * are not required. - *

    - * This method cannot be used for confirming error return codes. Any non-numeric evaluation - * result causes the current junit test to fail. - */ - public static double invoke(Function f, ValueEval[] args) { - return invoke(f, args, -1, -1); - } - /** - * Invokes the specified operator with the arguments. - *

    - * This method cannot be used for confirming error return codes. Any non-numeric evaluation - * result causes the current junit test to fail. - */ - public static double invoke(Function f, ValueEval[] args, int srcCellRow, int srcCellCol) { - try { - return invokeInternal(f, args, srcCellRow, srcCellCol); - } catch (NumericEvalEx e) { - throw new AssertionFailedError("Evaluation of function (" + f.getClass().getName() - + ") failed: " + e.getMessage()); - } - } - /** - * Formats nicer error messages for the junit output - */ - private static double invokeInternal(Function target, ValueEval[] args, int srcCellRow, int srcCellCol) - throws NumericEvalEx { - ValueEval evalResult; - try { - evalResult = target.evaluate(args, srcCellRow, (short)srcCellCol); - } catch (NotImplementedException e) { - throw new NumericEvalEx("Not implemented:" + e.getMessage()); - } - - if(evalResult == null) { - throw new NumericEvalEx("Result object was null"); - } - if(evalResult instanceof ErrorEval) { - ErrorEval ee = (ErrorEval) evalResult; - throw new NumericEvalEx(formatErrorMessage(ee)); - } - if(!(evalResult instanceof NumericValueEval)) { - throw new NumericEvalEx("Result object type (" + evalResult.getClass().getName() - + ") is invalid. Expected implementor of (" - + NumericValueEval.class.getName() + ")"); - } - - NumericValueEval result = (NumericValueEval) evalResult; - return result.getNumberValue(); - } - private static String formatErrorMessage(ErrorEval ee) { - if(errorCodesAreEqual(ee, ErrorEval.VALUE_INVALID)) { - return "Error code: #VALUE! (invalid value)"; - } - return "Error code=" + ee.getErrorCode(); - } - private static boolean errorCodesAreEqual(ErrorEval a, ErrorEval b) { - if(a==b) { - return true; - } - return a.getErrorCode() == b.getErrorCode(); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/RefEvalImplementation.java b/src/testcases/org/apache/poi/ss/formula/functions/RefEvalImplementation.java deleted file mode 100644 index 05cfdfc8a..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/RefEvalImplementation.java +++ /dev/null @@ -1,68 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import org.apache.poi.ss.formula.eval.AreaEval; -import org.apache.poi.ss.formula.eval.RefEval; -import org.apache.poi.ss.formula.eval.ValueEval; - -final class RefEvalImplementation implements RefEval { - - private final ValueEval value; - - public RefEvalImplementation(ValueEval value) { - this.value = value; - } - - @Override - public AreaEval offset(int relFirstRowIx, int relLastRowIx, - int relFirstColIx, int relLastColIx) { - throw new UnsupportedOperationException(); - } - - @Override - public ValueEval getInnerValueEval(int sheetIndex) { - return value; - } - - @Override - public int getNumberOfSheets() { - return 1; - } - - @Override - public int getFirstSheetIndex() { - return 0; - } - - @Override - public int getLastSheetIndex() { - return 0; - } - - @Override - public int getRow() { - throw new UnsupportedOperationException(); - } - - @Override - public int getColumn() { - throw new UnsupportedOperationException(); - } - -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestAddress.java b/src/testcases/org/apache/poi/ss/formula/functions/TestAddress.java deleted file mode 100644 index 527477bbc..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestAddress.java +++ /dev/null @@ -1,79 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.formula.functions; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; - -import junit.framework.TestCase; - -public final class TestAddress extends TestCase { - - public void testAddress() { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFCell cell = wb.createSheet().createRow(0).createCell(0); - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - - String formulaText = "ADDRESS(1,2)"; - confirmResult(fe, cell, formulaText, "$B$1"); - - formulaText = "ADDRESS(1,2,)"; // with explicitly empty third parameter - confirmResult(fe, cell, formulaText, "$B$1"); - - formulaText = "ADDRESS(22,44)"; - confirmResult(fe, cell, formulaText, "$AR$22"); - - formulaText = "ADDRESS(1,1)"; - confirmResult(fe, cell, formulaText, "$A$1"); - - formulaText = "ADDRESS(1,128)"; - confirmResult(fe, cell, formulaText, "$DX$1"); - - formulaText = "ADDRESS(1,512)"; - confirmResult(fe, cell, formulaText, "$SR$1"); - - formulaText = "ADDRESS(1,1000)"; - confirmResult(fe, cell, formulaText, "$ALL$1"); - - formulaText = "ADDRESS(1,10000)"; - confirmResult(fe, cell, formulaText, "$NTP$1"); - - formulaText = "ADDRESS(2,3)"; - confirmResult(fe, cell, formulaText, "$C$2"); - - formulaText = "ADDRESS(2,3,2)"; - confirmResult(fe, cell, formulaText, "C$2"); - - formulaText = "ADDRESS(2,3,2,,\"EXCEL SHEET\")"; - confirmResult(fe, cell, formulaText, "'EXCEL SHEET'!C$2"); - - formulaText = "ADDRESS(2,3,3,TRUE,\"[Book1]Sheet1\")"; - confirmResult(fe, cell, formulaText, "'[Book1]Sheet1'!$C2"); - } - - private static void confirmResult(HSSFFormulaEvaluator fe, HSSFCell cell, String formulaText, - String expectedResult) { - cell.setCellFormula(formulaText); - fe.notifyUpdateCell(cell); - CellValue result = fe.evaluate(cell); - assertEquals(result.getCellTypeEnum(), CellType.STRING); - assertEquals(expectedResult, result.getStringValue()); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestAverage.java b/src/testcases/org/apache/poi/ss/formula/functions/TestAverage.java deleted file mode 100644 index 1dcba00c5..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestAverage.java +++ /dev/null @@ -1,98 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import junit.framework.TestCase; - -import org.apache.poi.ss.formula.eval.BlankEval; -import org.apache.poi.ss.formula.eval.BoolEval; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.ValueEval; -/** - * Tests for Excel function AVERAGE() - * - * @author Josh Micich - */ -public final class TestAverage extends TestCase { - - private static ValueEval invokeAverage(ValueEval[] args) { - return AggregateFunction.AVERAGE.evaluate(args, -1, (short)-1); - } - - private void confirmAverage(ValueEval[] args, double expected) { - ValueEval result = invokeAverage(args); - assertEquals(NumberEval.class, result.getClass()); - assertEquals(expected, ((NumberEval)result).getNumberValue(), 0); - } - - private void confirmAverage(ValueEval[] args, ErrorEval expectedError) { - ValueEval result = invokeAverage(args); - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(expectedError.getErrorCode(), ((ErrorEval)result).getErrorCode()); - } - - public void testBasic() { - - ValueEval[] values = { - new NumberEval(1), - new NumberEval(2), - new NumberEval(3), - new NumberEval(4), - }; - - confirmAverage(values, 2.5); - - values = new ValueEval[] { - new NumberEval(1), - new NumberEval(2), - BlankEval.instance, - new NumberEval(3), - BlankEval.instance, - new NumberEval(4), - BlankEval.instance, - }; - - confirmAverage(values, 2.5); - } - - /** - * Valid cases where values are not pure numbers - */ - public void testUnusualArgs() { - ValueEval[] values = { - new NumberEval(1), - new NumberEval(2), - BoolEval.TRUE, - BoolEval.FALSE, - }; - - confirmAverage(values, 1.0); - - } - - public void testErrors() { - ValueEval[] values = { - new NumberEval(1), - ErrorEval.NAME_INVALID, - new NumberEval(3), - ErrorEval.DIV_ZERO, - }; - confirmAverage(values, ErrorEval.NAME_INVALID); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestBin2Dec.java b/src/testcases/org/apache/poi/ss/formula/functions/TestBin2Dec.java deleted file mode 100644 index 134975e20..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestBin2Dec.java +++ /dev/null @@ -1,114 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import junit.framework.TestCase; - -import org.apache.poi.hssf.usermodel.HSSFEvaluationWorkbook; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.IStabilityClassifier; -import org.apache.poi.ss.formula.OperationEvaluationContext; -import org.apache.poi.ss.formula.WorkbookEvaluator; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; - -/** - * Tests for {@link Bin2Dec} - * - * @author cedric dot walter @ gmail dot com - */ -public final class TestBin2Dec extends TestCase { - - private static ValueEval invokeValue(String number1) { - ValueEval[] args = new ValueEval[] { new StringEval(number1) }; - return new Bin2Dec().evaluate(args, -1, -1); - } - - private static void confirmValue(String msg, String number1, String expected) { - ValueEval result = invokeValue(number1); - assertEquals("Had: " + result.toString(), NumberEval.class, result.getClass()); - assertEquals(msg, expected, ((NumberEval) result).getStringValue()); - } - - private static void confirmValueError(String msg, String number1, ErrorEval numError) { - ValueEval result = invokeValue(number1); - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(msg, numError, result); - } - - public void testBasic() { - confirmValue("Converts binary '00101' to decimal (5)", "00101", "5"); - confirmValue("Converts binary '1111111111' to decimal (-1)", "1111111111", "-1"); - confirmValue("Converts binary '1111111110' to decimal (-2)", "1111111110", "-2"); - confirmValue("Converts binary '0111111111' to decimal (511)", "0111111111", "511"); - } - - public void testErrors() { - confirmValueError("does not support more than 10 digits","01010101010", ErrorEval.NUM_ERROR); - confirmValueError("not a valid binary number","GGGGGGG", ErrorEval.NUM_ERROR); - confirmValueError("not a valid binary number","3.14159", ErrorEval.NUM_ERROR); - } - - public void testEvalOperationEvaluationContext() { - OperationEvaluationContext ctx = createContext(); - - ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0) }; - ValueEval result = new Bin2Dec().evaluate(args, ctx); - - assertEquals(NumberEval.class, result.getClass()); - assertEquals("0", ((NumberEval) result).getStringValue()); - } - - public void testEvalOperationEvaluationContextFails() { - OperationEvaluationContext ctx = createContext(); - - ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0), ctx.getRefEval(0, 0) }; - ValueEval result = new Bin2Dec().evaluate(args, ctx); - - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(ErrorEval.VALUE_INVALID, result); - } - - private OperationEvaluationContext createContext() { - HSSFWorkbook wb = new HSSFWorkbook(); - wb.createSheet(); - HSSFEvaluationWorkbook workbook = HSSFEvaluationWorkbook.create(wb); - WorkbookEvaluator workbookEvaluator = new WorkbookEvaluator(workbook, new IStabilityClassifier() { - - @Override - public boolean isCellFinal(int sheetIndex, int rowIndex, int columnIndex) { - return true; - } - }, null); - OperationEvaluationContext ctx = new OperationEvaluationContext(workbookEvaluator, - workbook, 0, 0, 0, null); - return ctx; - } - - public void testRefs() { - OperationEvaluationContext ctx = createContext(); - - ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0) }; - ValueEval result = new Bin2Dec().evaluate(args, -1, -1); - - assertEquals(NumberEval.class, result.getClass()); - assertEquals("0", ((NumberEval) result).getStringValue()); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestCalendarFieldFunction.java b/src/testcases/org/apache/poi/ss/formula/functions/TestCalendarFieldFunction.java deleted file mode 100644 index c7c33ad9b..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestCalendarFieldFunction.java +++ /dev/null @@ -1,113 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -/** - * Test for YEAR / MONTH / DAY / HOUR / MINUTE / SECOND - */ -public final class TestCalendarFieldFunction extends TestCase { - - private HSSFCell cell11; - private HSSFFormulaEvaluator evaluator; - - @Override - public void setUp() { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("new sheet"); - cell11 = sheet.createRow(0).createCell(0); - cell11.setCellType(CellType.FORMULA); - evaluator = new HSSFFormulaEvaluator(wb); - } - - public void testValid() { - confirm("YEAR(2.26)", 1900); - confirm("MONTH(2.26)", 1); - confirm("DAY(2.26)", 2); - confirm("HOUR(2.26)", 6); - confirm("MINUTE(2.26)", 14); - confirm("SECOND(2.26)", 24); - - confirm("YEAR(40627.4860417)", 2011); - confirm("MONTH(40627.4860417)", 3); - confirm("DAY(40627.4860417)", 25); - confirm("HOUR(40627.4860417)", 11); - confirm("MINUTE(40627.4860417)", 39); - confirm("SECOND(40627.4860417)", 54); - } - - public void testRounding() { - // 41484.999994200 = 23:59:59,499 - // 41484.9999942129 = 23:59:59,500 (but sub-milliseconds are below 0.5 (0.49999453965575), XLS-second results in 59) - // 41484.9999942130 = 23:59:59,500 (sub-milliseconds are 0.50000334065408, XLS-second results in 00) - - confirm("DAY(41484.999994200)", 29); - confirm("SECOND(41484.999994200)", 59); - - confirm("DAY(41484.9999942129)", 29); - confirm("HOUR(41484.9999942129)", 23); - confirm("MINUTE(41484.9999942129)", 59); - confirm("SECOND(41484.9999942129)", 59); - - confirm("DAY(41484.9999942130)", 30); - confirm("HOUR(41484.9999942130)", 0); - confirm("MINUTE(41484.9999942130)", 0); - confirm("SECOND(41484.9999942130)", 0); - } - - public void testDaylightSaving() { - confirm("HOUR(41364.08263888890000)", 1); // 31.03.2013 01:59:00,000 - confirm("HOUR(41364.08333333330000)", 2); // 31.03.2013 02:00:00,000 (this time does not exist in TZ CET, but EXCEL does not care) - confirm("HOUR(41364.08402777780000)", 2); // 31.03.2013 02:01:00,000 - confirm("HOUR(41364.12430555560000)", 2); // 31.03.2013 02:59:00,000 - confirm("HOUR(41364.12500000000000)", 3); // 31.03.2013 03:00:00,000 - } - - public void testBugDate() { - confirm("YEAR(0.0)", 1900); - confirm("MONTH(0.0)", 1); - confirm("DAY(0.0)", 0); - - confirm("YEAR(0.26)", 1900); - confirm("MONTH(0.26)", 1); - confirm("DAY(0.26)", 0); - confirm("HOUR(0.26)", 6); - confirm("MINUTE(0.26)", 14); - confirm("SECOND(0.26)", 24); - } - - private void confirm(String formulaText, double expectedResult) { - cell11.setCellFormula(formulaText); - evaluator.clearAllCachedResultValues(); - CellValue cv = evaluator.evaluate(cell11); - if (cv.getCellTypeEnum() != CellType.NUMERIC) { - throw new AssertionFailedError("Wrong result type: " + cv.formatAsString()); - } - double actualValue = cv.getNumberValue(); - assertEquals(expectedResult, actualValue, 0); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestClean.java b/src/testcases/org/apache/poi/ss/formula/functions/TestClean.java deleted file mode 100644 index 39bb4d085..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestClean.java +++ /dev/null @@ -1,66 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.formula.functions; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; - -import junit.framework.TestCase; - -public final class TestClean extends TestCase { - - public void testClean() { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFCell cell = wb.createSheet().createRow(0).createCell(0); - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - - String[] asserts = { - "aniket\u0007\u0017\u0019", "aniket", - "\u0011aniket\u0007\u0017\u0010", "aniket", - "\u0011aniket\u0007\u0017\u007F", "aniket\u007F", - "\u2116aniket\u2211\uFB5E\u2039", "\u2116aniket\u2211\uFB5E\u2039", - }; - - for(int i = 0; i < asserts.length; i+= 2){ - String formulaText = "CLEAN(\"" + asserts[i] + "\")"; - confirmResult(fe, cell, formulaText, asserts[i + 1]); - } - - asserts = new String[] { - "CHAR(7)&\"text\"&CHAR(7)", "text", - "CHAR(7)&\"text\"&CHAR(17)", "text", - "CHAR(181)&\"text\"&CHAR(190)", "\u00B5text\u00BE", - "\"text\"&CHAR(160)&\"'\"", "text\u00A0'", - }; - for(int i = 0; i < asserts.length; i+= 2){ - String formulaText = "CLEAN(" + asserts[i] + ")"; - confirmResult(fe, cell, formulaText, asserts[i + 1]); - } - } - - private static void confirmResult(HSSFFormulaEvaluator fe, HSSFCell cell, String formulaText, - String expectedResult) { - cell.setCellFormula(formulaText); - fe.notifyUpdateCell(cell); - CellValue result = fe.evaluate(cell); - assertEquals(result.getCellTypeEnum(), CellType.STRING); - assertEquals(expectedResult, result.getStringValue()); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestCode.java b/src/testcases/org/apache/poi/ss/formula/functions/TestCode.java deleted file mode 100644 index 6069f4094..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestCode.java +++ /dev/null @@ -1,59 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.formula.functions; - -import junit.framework.TestCase; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; - -/** - * Tests for {@link Code} - * - * @author cedric dot walter @ gmail dot com - */ -public class TestCode extends TestCase -{ - private static ValueEval invokeValue(String number1) { - ValueEval[] args = new ValueEval[]{new StringEval(number1),}; - return new Code().evaluate(args, -1, -1); - } - - private static void confirmValue(String msg, String number1, String expected) { - ValueEval result = invokeValue(number1); - assertEquals(StringEval.class, result.getClass()); - assertEquals(msg, expected, ((StringEval) result).getStringValue()); - } - - private static void confirmValueError(String msg, String number1, ErrorEval numError) { - ValueEval result = invokeValue(number1); - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(msg, numError, result); - } - - - public void testBasic() { - confirmValue("Displays the numeric code for A (65)", "A", "65"); - confirmValue("Displays the numeric code for the first character in text ABCDEFGHI (65)", "ABCDEFGHI", "65"); - - confirmValue("Displays the numeric code for ! (33)", "!", "33"); - } - - public void testErrors() { - confirmValueError("Empty text", "", ErrorEval.VALUE_INVALID); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestCodeFunctionsFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/functions/TestCodeFunctionsFromSpreadsheet.java deleted file mode 100644 index 8cc6ea3b1..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestCodeFunctionsFromSpreadsheet.java +++ /dev/null @@ -1,32 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import java.util.Collection; - -import org.junit.runners.Parameterized.Parameters; - -/** - * Tests CODE() as loaded from a test data spreadsheet.

    - */ -public class TestCodeFunctionsFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - @Parameters(name="{0}") - public static Collection data() throws Exception { - return data(TestCodeFunctionsFromSpreadsheet.class, "CodeFunctionTestCaseData.xls"); - } -} \ No newline at end of file diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestComplex.java b/src/testcases/org/apache/poi/ss/formula/functions/TestComplex.java deleted file mode 100644 index ce1cce91e..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestComplex.java +++ /dev/null @@ -1,69 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.formula.functions; - -import junit.framework.TestCase; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; - -/** - * Tests for {@link Complex} - * - * @author cedric dot walter @ gmail dot com - */ -public class TestComplex extends TestCase -{ - private static ValueEval invokeValue(String real_num, String i_num, String suffix) { - ValueEval[] args = new ValueEval[]{new StringEval(real_num), new StringEval(i_num), new StringEval(suffix)}; - return new Complex().evaluate(args, -1, -1); - } - - private static void confirmValue(String msg, String real_num, String i_num, String suffix, String expected) { - ValueEval result = invokeValue(real_num, i_num, suffix); - assertEquals(StringEval.class, result.getClass()); - assertEquals(msg, expected, ((StringEval) result).getStringValue()); - } - - private static void confirmValueError(String msg, String real_num, String i_num, String suffix, ErrorEval numError) { - ValueEval result = invokeValue(real_num, i_num, suffix); - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(msg, numError, result); - } - - public void testBasic() { - confirmValue("Complex number with 3 and 4 as the real and imaginary coefficients (3 + 4i)", "3","4", "", "3+4i"); - confirmValue("Complex number with 3 and 4 as the real and imaginary coefficients, and j as the suffix (3 + 4j)", "3","4", "j", "3+4j"); - - confirmValue("Complex number with 0 and 1 as the real and imaginary coefficients (i)", "0","1", "", "i"); - confirmValue("Complex number with 1 and 0 as the real and imaginary coefficients (1)", "1","0", "", "1"); - - confirmValue("Complex number with 2 and 3 as the real and imaginary coefficients (2 + 3i)", "2","3", "", "2+3i"); - confirmValue("Complex number with -2 and -3 as the real and imaginary coefficients (-2-3i)", "-2","-3", "", "-2-3i"); - - confirmValue("Complex number with -2 and -3 as the real and imaginary coefficients (-0.5-3.2i)", "-0.5","-3.2", "", "-0.5-3.2i"); - } - - public void testErrors() { - confirmValueError("argument is nonnumeric", "ABCD", "","", ErrorEval.VALUE_INVALID); - confirmValueError("argument is nonnumeric", "1", "ABCD","", ErrorEval.VALUE_INVALID); - confirmValueError("f suffix is neither \"i\" nor \"j\"", "1", "1","k", ErrorEval.VALUE_INVALID); - - confirmValueError("never use \"I\" ", "1", "1","I", ErrorEval.VALUE_INVALID); - confirmValueError("never use \"J\" ", "1", "1","J", ErrorEval.VALUE_INVALID); - } -} \ No newline at end of file diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestComplexFunctionsFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/functions/TestComplexFunctionsFromSpreadsheet.java deleted file mode 100644 index 760974c28..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestComplexFunctionsFromSpreadsheet.java +++ /dev/null @@ -1,32 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import java.util.Collection; - -import org.junit.runners.Parameterized.Parameters; - -/** - * Tests COMPLEX() as loaded from a test data spreadsheet.

    - */ -public class TestComplexFunctionsFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - @Parameters(name="{0}") - public static Collection data() throws Exception { - return data(TestComplexFunctionsFromSpreadsheet.class, "ComplexFunctionTestCaseData.xls"); - } -} \ No newline at end of file diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestCountFuncs.java b/src/testcases/org/apache/poi/ss/formula/functions/TestCountFuncs.java deleted file mode 100644 index 39b1f28ac..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestCountFuncs.java +++ /dev/null @@ -1,575 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.eval.AreaEval; -import org.apache.poi.ss.formula.eval.BlankEval; -import org.apache.poi.ss.formula.eval.BoolEval; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.OperandResolver; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.ss.formula.functions.CountUtils.I_MatchPredicate; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.util.CellReference; - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -/** - * Test cases for COUNT(), COUNTA() COUNTIF(), COUNTBLANK() - */ -public final class TestCountFuncs extends TestCase { - - private static final String NULL = null; - - public void testCountBlank() { - AreaEval range; - ValueEval[] values; - - values = new ValueEval[] { - new NumberEval(0), - new StringEval(""), // note - does match blank - BoolEval.TRUE, - BoolEval.FALSE, - ErrorEval.DIV_ZERO, - BlankEval.instance, - }; - range = EvalFactory.createAreaEval("A1:B3", values); - confirmCountBlank(2, range); - - values = new ValueEval[] { - new NumberEval(0), - new StringEval(""), // does match blank - BlankEval.instance, - BoolEval.FALSE, - BoolEval.TRUE, - BlankEval.instance, - }; - range = EvalFactory.createAreaEval("A1:B3", values); - confirmCountBlank(3, range); - } - - public void testCountA() { - ValueEval[] args; - - args = new ValueEval[] { - new NumberEval(0), - }; - confirmCountA(1, args); - - args = new ValueEval[] { - new NumberEval(0), - new NumberEval(0), - new StringEval(""), - }; - confirmCountA(3, args); - - args = new ValueEval[] { - EvalFactory.createAreaEval("D2:F5", new ValueEval[12]), - }; - confirmCountA(12, args); - - args = new ValueEval[] { - EvalFactory.createAreaEval("D1:F5", new ValueEval[15]), - EvalFactory.createRefEval("A1"), - EvalFactory.createAreaEval("A1:G6", new ValueEval[42]), - new NumberEval(0), - }; - confirmCountA(59, args); - } - - public void testCountIf() { - AreaEval range; - ValueEval[] values; - - // when criteria is a boolean value - values = new ValueEval[] { - new NumberEval(0), - new StringEval("TRUE"), // note - does not match boolean TRUE - BoolEval.TRUE, - BoolEval.FALSE, - BoolEval.TRUE, - BlankEval.instance, - }; - range = EvalFactory.createAreaEval("A1:B3", values); - confirmCountIf(2, range, BoolEval.TRUE); - - // when criteria is numeric - values = new ValueEval[] { - new NumberEval(0), - new StringEval("2"), - new StringEval("2.001"), - new NumberEval(2), - new NumberEval(2), - BoolEval.TRUE, - }; - range = EvalFactory.createAreaEval("A1:B3", values); - confirmCountIf(3, range, new NumberEval(2)); - // note - same results when criteria is a string that parses as the number with the same value - confirmCountIf(3, range, new StringEval("2.00")); - - // when criteria is an expression (starting with a comparison operator) - confirmCountIf(2, range, new StringEval(">1")); - // when criteria is an expression (starting with a comparison operator) - confirmCountIf(2, range, new StringEval(">0.5")); - } - - public void testCriteriaPredicateNe_Bug46647() { - I_MatchPredicate mp = Countif.createCriteriaPredicate(new StringEval("<>aa"), 0, 0); - assertNotNull(mp); - StringEval seA = new StringEval("aa"); // this should not match the criteria '<>aa' - StringEval seB = new StringEval("bb"); // this should match - if (mp.matches(seA) && !mp.matches(seB)) { - throw new AssertionFailedError("Identified bug 46647"); - } - assertFalse(mp.matches(seA)); - assertTrue(mp.matches(seB)); - - // general tests for not-equal (<>) operator - AreaEval range; - ValueEval[] values; - - values = new ValueEval[] { - new StringEval("aa"), - new StringEval("def"), - new StringEval("aa"), - new StringEval("ghi"), - new StringEval("aa"), - new StringEval("aa"), - }; - - range = EvalFactory.createAreaEval("A1:A6", values); - confirmCountIf(2, range, new StringEval("<>aa")); - - values = new ValueEval[] { - new StringEval("ab"), - new StringEval("aabb"), - new StringEval("aa"), // match - new StringEval("abb"), - new StringEval("aab"), - new StringEval("ba"), // match - }; - - range = EvalFactory.createAreaEval("A1:A6", values); - confirmCountIf(2, range, new StringEval("<>a*b")); - - - values = new ValueEval[] { - new NumberEval(222), - new NumberEval(222), - new NumberEval(111), - new StringEval("aa"), - new StringEval("111"), - }; - - range = EvalFactory.createAreaEval("A1:A5", values); - confirmCountIf(4, range, new StringEval("<>111")); - } - - /** - * String criteria in COUNTIF are case insensitive; - * for example, the string "apples" and the string "APPLES" will match the same cells. - */ - public void testCaseInsensitiveStringComparison() { - AreaEval range; - ValueEval[] values; - - values = new ValueEval[] { - new StringEval("no"), - new StringEval("NO"), - new StringEval("No"), - new StringEval("Yes") - }; - - range = EvalFactory.createAreaEval("A1:A4", values); - confirmCountIf(3, range, new StringEval("no")); - confirmCountIf(3, range, new StringEval("NO")); - confirmCountIf(3, range, new StringEval("No")); - } - - /** - * special case where the criteria argument is a cell reference - */ - public void testCountIfWithCriteriaReference() { - - ValueEval[] values = { - new NumberEval(22), - new NumberEval(25), - new NumberEval(21), - new NumberEval(25), - new NumberEval(25), - new NumberEval(25), - }; - AreaEval arg0 = EvalFactory.createAreaEval("C1:C6", values); - - ValueEval criteriaArg = EvalFactory.createRefEval("A1", new NumberEval(25)); - ValueEval[] args= { arg0, criteriaArg, }; - - double actual = NumericFunctionInvoker.invoke(new Countif(), args); - assertEquals(4, actual, 0D); - } - - private static void confirmCountA(int expected, ValueEval[] args) { - double result = NumericFunctionInvoker.invoke(new Counta(), args); - assertEquals(expected, result, 0); - } - private static void confirmCountIf(int expected, AreaEval range, ValueEval criteria) { - - ValueEval[] args = { range, criteria, }; - double result = NumericFunctionInvoker.invoke(new Countif(), args); - assertEquals(expected, result, 0); - } - private static void confirmCountBlank(int expected, AreaEval range) { - - ValueEval[] args = { range }; - double result = NumericFunctionInvoker.invoke(new Countblank(), args); - assertEquals(expected, result, 0); - } - - private static I_MatchPredicate createCriteriaPredicate(ValueEval ev) { - return Countif.createCriteriaPredicate(ev, 0, 0); - } - - /** - * the criteria arg is mostly handled by {@link OperandResolver#getSingleValue(org.apache.poi.ss.formula.eval.ValueEval, int, int)}} - */ - public void testCountifAreaCriteria() { - int srcColIx = 2; // anything but column A - - ValueEval v0 = new NumberEval(2.0); - ValueEval v1 = new StringEval("abc"); - ValueEval v2 = ErrorEval.DIV_ZERO; - - AreaEval ev = EvalFactory.createAreaEval("A10:A12", new ValueEval[] { v0, v1, v2, }); - - I_MatchPredicate mp; - mp = Countif.createCriteriaPredicate(ev, 9, srcColIx); - confirmPredicate(true, mp, srcColIx); - confirmPredicate(false, mp, "abc"); - confirmPredicate(false, mp, ErrorEval.DIV_ZERO); - - mp = Countif.createCriteriaPredicate(ev, 10, srcColIx); - confirmPredicate(false, mp, srcColIx); - confirmPredicate(true, mp, "abc"); - confirmPredicate(false, mp, ErrorEval.DIV_ZERO); - - mp = Countif.createCriteriaPredicate(ev, 11, srcColIx); - confirmPredicate(false, mp, srcColIx); - confirmPredicate(false, mp, "abc"); - confirmPredicate(true, mp, ErrorEval.DIV_ZERO); - confirmPredicate(false, mp, ErrorEval.VALUE_INVALID); - - // tricky: indexing outside of A10:A12 - // even this #VALUE! error gets used by COUNTIF as valid criteria - mp = Countif.createCriteriaPredicate(ev, 12, srcColIx); - confirmPredicate(false, mp, srcColIx); - confirmPredicate(false, mp, "abc"); - confirmPredicate(false, mp, ErrorEval.DIV_ZERO); - confirmPredicate(true, mp, ErrorEval.VALUE_INVALID); - } - - public void testCountifEmptyStringCriteria() { - I_MatchPredicate mp; - - // pred '=' matches blank cell but not empty string - mp = createCriteriaPredicate(new StringEval("=")); - confirmPredicate(false, mp, ""); - confirmPredicate(true, mp, NULL); - - // pred '' matches both blank cell but not empty string - mp = createCriteriaPredicate(new StringEval("")); - confirmPredicate(true, mp, ""); - confirmPredicate(true, mp, NULL); - - // pred '<>' matches empty string but not blank cell - mp = createCriteriaPredicate(new StringEval("<>")); - confirmPredicate(false, mp, NULL); - confirmPredicate(true, mp, ""); - } - - public void testCountifComparisons() { - I_MatchPredicate mp; - - mp = createCriteriaPredicate(new StringEval(">5")); - confirmPredicate(false, mp, 4); - confirmPredicate(false, mp, 5); - confirmPredicate(true, mp, 6); - - mp = createCriteriaPredicate(new StringEval("<=5")); - confirmPredicate(true, mp, 4); - confirmPredicate(true, mp, 5); - confirmPredicate(false, mp, 6); - confirmPredicate(false, mp, "4.9"); - confirmPredicate(false, mp, "4.9t"); - confirmPredicate(false, mp, "5.1"); - confirmPredicate(false, mp, NULL); - - mp = createCriteriaPredicate(new StringEval("=abc")); - confirmPredicate(true, mp, "abc"); - - mp = createCriteriaPredicate(new StringEval("=42")); - confirmPredicate(false, mp, 41); - confirmPredicate(true, mp, 42); - confirmPredicate(true, mp, "42"); - - mp = createCriteriaPredicate(new StringEval(">abc")); - confirmPredicate(false, mp, 4); - confirmPredicate(false, mp, "abc"); - confirmPredicate(true, mp, "abd"); - - mp = createCriteriaPredicate(new StringEval(">4t3")); - confirmPredicate(false, mp, 4); - confirmPredicate(false, mp, 500); - confirmPredicate(true, mp, "500"); - confirmPredicate(true, mp, "4t4"); - } - - /** - * the criteria arg value can be an error code (the error does not - * propagate to the COUNTIF result). - */ - public void testCountifErrorCriteria() { - I_MatchPredicate mp; - - mp = createCriteriaPredicate(new StringEval("#REF!")); - confirmPredicate(false, mp, 4); - confirmPredicate(false, mp, "#REF!"); - confirmPredicate(true, mp, ErrorEval.REF_INVALID); - - mp = createCriteriaPredicate(new StringEval("<#VALUE!")); - confirmPredicate(false, mp, 4); - confirmPredicate(false, mp, "#DIV/0!"); - confirmPredicate(false, mp, "#REF!"); - confirmPredicate(true, mp, ErrorEval.DIV_ZERO); - confirmPredicate(false, mp, ErrorEval.REF_INVALID); - - // not quite an error literal, should be treated as plain text - mp = createCriteriaPredicate(new StringEval("<=#REF!a")); - confirmPredicate(false, mp, 4); - confirmPredicate(true, mp, "#DIV/0!"); - confirmPredicate(true, mp, "#REF!"); - confirmPredicate(false, mp, ErrorEval.DIV_ZERO); - confirmPredicate(false, mp, ErrorEval.REF_INVALID); - } - - /** - * Bug #51498 - Check that CountIf behaves correctly for GTE, LTE - * and NEQ cases - */ - public void testCountifBug51498() throws Exception { - final int REF_COL = 4; - final int EVAL_COL = 3; - - HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook("51498.xls"); - FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator(); - HSSFSheet sheet = workbook.getSheetAt(0); - - // numeric criteria - for (int i = 0; i < 8; i++) { - CellValue expected = evaluator.evaluate(sheet.getRow(i).getCell(REF_COL)); - CellValue actual = evaluator.evaluate(sheet.getRow(i).getCell(EVAL_COL)); - assertEquals(expected.formatAsString(), actual.formatAsString()); - } - - // boolean criteria - for (int i = 0; i < 8; i++) { - HSSFCell cellFmla = sheet.getRow(i).getCell(8); - HSSFCell cellRef = sheet.getRow(i).getCell(9); - - double expectedValue = cellRef.getNumericCellValue(); - double actualValue = evaluator.evaluate(cellFmla).getNumberValue(); - - assertEquals( - "Problem with a formula at " + - new CellReference(cellFmla).formatAsString() + "[" + cellFmla.getCellFormula()+"] ", - expectedValue, actualValue, 0.0001); - } - - // string criteria - for (int i = 1; i < 9; i++) { - HSSFCell cellFmla = sheet.getRow(i).getCell(13); - HSSFCell cellRef = sheet.getRow(i).getCell(14); - - double expectedValue = cellRef.getNumericCellValue(); - double actualValue = evaluator.evaluate(cellFmla).getNumberValue(); - - assertEquals( - "Problem with a formula at " + - new CellReference(cellFmla).formatAsString() + "[" + cellFmla.getCellFormula()+"] ", - expectedValue, actualValue, 0.0001); - } - } - - public void testWildCards() { - I_MatchPredicate mp; - - mp = createCriteriaPredicate(new StringEval("a*b")); - confirmPredicate(false, mp, "abc"); - confirmPredicate(true, mp, "ab"); - confirmPredicate(true, mp, "axxb"); - confirmPredicate(false, mp, "xab"); - - mp = createCriteriaPredicate(new StringEval("a?b")); - confirmPredicate(false, mp, "abc"); - confirmPredicate(false, mp, "ab"); - confirmPredicate(false, mp, "axxb"); - confirmPredicate(false, mp, "xab"); - confirmPredicate(true, mp, "axb"); - - mp = createCriteriaPredicate(new StringEval("a~?")); - confirmPredicate(false, mp, "a~a"); - confirmPredicate(false, mp, "a~?"); - confirmPredicate(true, mp, "a?"); - - mp = createCriteriaPredicate(new StringEval("~*a")); - confirmPredicate(false, mp, "~aa"); - confirmPredicate(false, mp, "~*a"); - confirmPredicate(true, mp, "*a"); - - mp = createCriteriaPredicate(new StringEval("12?12")); - confirmPredicate(false, mp, 12812); - confirmPredicate(true, mp, "12812"); - confirmPredicate(false, mp, "128812"); - } - public void testNotQuiteWildCards() { - I_MatchPredicate mp; - - // make sure special reg-ex chars are treated like normal chars - mp = createCriteriaPredicate(new StringEval("a.b")); - confirmPredicate(false, mp, "aab"); - confirmPredicate(true, mp, "a.b"); - - - mp = createCriteriaPredicate(new StringEval("a~b")); - confirmPredicate(false, mp, "ab"); - confirmPredicate(false, mp, "axb"); - confirmPredicate(false, mp, "a~~b"); - confirmPredicate(true, mp, "a~b"); - - mp = createCriteriaPredicate(new StringEval(">a*b")); - confirmPredicate(false, mp, "a(b"); - confirmPredicate(true, mp, "aab"); - confirmPredicate(false, mp, "a*a"); - confirmPredicate(true, mp, "a*c"); - } - - private static void confirmPredicate(boolean expectedResult, I_MatchPredicate matchPredicate, int value) { - assertEquals(expectedResult, matchPredicate.matches(new NumberEval(value))); - } - private static void confirmPredicate(boolean expectedResult, I_MatchPredicate matchPredicate, String value) { - ValueEval ev = value == null ? BlankEval.instance : new StringEval(value); - assertEquals(expectedResult, matchPredicate.matches(ev)); - } - private static void confirmPredicate(boolean expectedResult, I_MatchPredicate matchPredicate, ErrorEval value) { - assertEquals(expectedResult, matchPredicate.matches(value)); - } - - public void testCountifFromSpreadsheet() { - testCountFunctionFromSpreadsheet("countifExamples.xls", 1, 2, 3, "countif"); - } - - /** - * Two COUNTIF examples taken from - * http://office.microsoft.com/en-us/excel-help/countif-function-HP010069840.aspx?CTT=5&origin=HA010277524 - */ - public void testCountifExamples() { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("countifExamples.xls"); - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - - HSSFSheet sheet1 = wb.getSheet("MSDN Example 1"); - for (int rowIx=7; rowIx<=12; rowIx++) { - HSSFRow row = sheet1.getRow(rowIx-1); - HSSFCell cellA = row.getCell(0); // cell containing a formula with COUNTIF - assertEquals(CellType.FORMULA, cellA.getCellTypeEnum()); - HSSFCell cellC = row.getCell(2); // cell with a reference value - assertEquals(CellType.NUMERIC, cellC.getCellTypeEnum()); - - CellValue cv = fe.evaluate(cellA); - double actualValue = cv.getNumberValue(); - double expectedValue = cellC.getNumericCellValue(); - assertEquals( - "Problem with a formula at " + new CellReference(cellA).formatAsString() - + ": " + cellA.getCellFormula() + " :" - + "Expected = (" + expectedValue + ") Actual=(" + actualValue + ") ", - expectedValue, actualValue, 0.0001); - } - - HSSFSheet sheet2 = wb.getSheet("MSDN Example 2"); - for (int rowIx=9; rowIx<=14; rowIx++) { - HSSFRow row = sheet2.getRow(rowIx-1); - HSSFCell cellA = row.getCell(0); // cell containing a formula with COUNTIF - assertEquals(CellType.FORMULA, cellA.getCellTypeEnum()); - HSSFCell cellC = row.getCell(2); // cell with a reference value - assertEquals(CellType.NUMERIC, cellC.getCellTypeEnum()); - - CellValue cv = fe.evaluate(cellA); - double actualValue = cv.getNumberValue(); - double expectedValue = cellC.getNumericCellValue(); - - assertEquals( - "Problem with a formula at " + - new CellReference(cellA).formatAsString() + "[" + cellA.getCellFormula()+"]: " - + "Expected = (" + expectedValue + ") Actual=(" + actualValue + ") ", - expectedValue, actualValue, 0.0001); - - } - } - - public void testCountBlankFromSpreadsheet() { - testCountFunctionFromSpreadsheet("countblankExamples.xls", 1, 3, 4, "countblank"); - } - - private static void testCountFunctionFromSpreadsheet(String FILE_NAME, int START_ROW_IX, int COL_IX_ACTUAL, int COL_IX_EXPECTED, String functionName) { - - int failureCount = 0; - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook(FILE_NAME); - HSSFSheet sheet = wb.getSheetAt(0); - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - int maxRow = sheet.getLastRowNum(); - for (int rowIx=START_ROW_IX; rowIx 0) { - throw new AssertionFailedError(failureCount + " " + functionName - + " evaluations failed. See stderr for more details"); - } - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestDGetFunctionsFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/functions/TestDGetFunctionsFromSpreadsheet.java deleted file mode 100644 index 4ac7b9861..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestDGetFunctionsFromSpreadsheet.java +++ /dev/null @@ -1,31 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.formula.functions; - -import java.util.Collection; - -import org.junit.runners.Parameterized.Parameters; - -/** -* Tests DGET() as loaded from a test data spreadsheet. -*/ -public class TestDGetFunctionsFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - @Parameters(name="{0}") - public static Collection data() throws Exception { - return data(TestDGetFunctionsFromSpreadsheet.class, "DGet.xls"); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestDStarFunctionsFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/functions/TestDStarFunctionsFromSpreadsheet.java deleted file mode 100644 index 0d20d98d5..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestDStarFunctionsFromSpreadsheet.java +++ /dev/null @@ -1,31 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.formula.functions; - -import java.util.Collection; - -import org.junit.runners.Parameterized.Parameters; - -/** -* Tests D*() functions as loaded from a test data spreadsheet. -*/ -public class TestDStarFunctionsFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - @Parameters(name="{0}") - public static Collection data() throws Exception { - return data(TestDStarFunctionsFromSpreadsheet.class, "DStar.xls"); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestDate.java b/src/testcases/org/apache/poi/ss/formula/functions/TestDate.java deleted file mode 100644 index 45241f6af..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestDate.java +++ /dev/null @@ -1,91 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -/** - * @author Pavel Krupets (pkrupets at palmtreebusiness dot com) - */ -public final class TestDate extends TestCase { - - private HSSFCell cell11; - private HSSFFormulaEvaluator evaluator; - - @Override - public void setUp() { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("new sheet"); - cell11 = sheet.createRow(0).createCell(0); - cell11.setCellType(CellType.FORMULA); - evaluator = new HSSFFormulaEvaluator(wb); - } - - /** - * Test disabled pending a fix in the formula evaluator - * TODO - create MissingArgEval and modify the formula evaluator to handle this - */ - public void DISABLEDtestSomeArgumentsMissing() { - confirm("DATE(, 1, 0)", 0.0); - confirm("DATE(, 1, 1)", 1.0); - } - - public void testValid() { - - confirm("DATE(1900, 1, 1)", 1); - confirm("DATE(1900, 1, 32)", 32); - confirm("DATE(1900, 222, 1)", 6727); - confirm("DATE(1900, 2, 0)", 31); - confirm("DATE(2000, 1, 222)", 36747.00); - confirm("DATE(2007, 1, 1)", 39083); - } - - public void testBugDate() { - confirm("DATE(1900, 2, 29)", 60); - confirm("DATE(1900, 2, 30)", 61); - confirm("DATE(1900, 1, 222)", 222); - confirm("DATE(1900, 1, 2222)", 2222); - confirm("DATE(1900, 1, 22222)", 22222); - } - - public void testPartYears() { - confirm("DATE(4, 1, 1)", 1462.00); - confirm("DATE(14, 1, 1)", 5115.00); - confirm("DATE(104, 1, 1)", 37987.00); - confirm("DATE(1004, 1, 1)", 366705.00); - } - - private void confirm(String formulaText, double expectedResult) { - cell11.setCellFormula(formulaText); - evaluator.clearAllCachedResultValues(); - CellValue cv = evaluator.evaluate(cell11); - if (cv.getCellTypeEnum() != CellType.NUMERIC) { - throw new AssertionFailedError("Wrong result type: " + cv.formatAsString()); - } - double actualValue = cv.getNumberValue(); - assertEquals(expectedResult, actualValue, 0); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestDays360.java b/src/testcases/org/apache/poi/ss/formula/functions/TestDays360.java deleted file mode 100644 index 159477057..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestDays360.java +++ /dev/null @@ -1,165 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.util.Calendar; -import java.util.Date; -import java.util.Locale; - -import org.apache.poi.hssf.usermodel.HSSFDateUtil; -import org.apache.poi.ss.formula.eval.BoolEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.util.LocaleUtil; -import org.junit.Test; - -public final class TestDays360 { - - /** - * @param month 1-based - */ - private static Date makeDate(int year, int month, int day) { - Calendar cal = LocaleUtil.getLocaleCalendar(year, month-1, day); - return cal.getTime(); - } - - private static Date decrementDay(Date d) { - Calendar c = LocaleUtil.getLocaleCalendar(); - c.setTime(d); - c.add(Calendar.DAY_OF_MONTH, -1); - return c.getTime(); - } - - @Test - public void testBasic() { - confirm(120, 2009, 1, 15, 2009, 5, 15); - confirm(158, 2009, 1, 26, 2009, 7, 4); - - // same results in leap years - confirm(120, 2008, 1, 15, 2008, 5, 15); - confirm(158, 2008, 1, 26, 2008, 7, 4); - - // longer time spans - confirm(562, 2008, 8, 11, 2010, 3, 3); - confirm(916, 2007, 2, 23, 2009, 9, 9); - - // other tests - confirm(1, makeDate(1993, 2, 28), makeDate(1993, 3, 1), false); - confirm(1, makeDate(1996, 2, 29), makeDate(1996, 3, 1), false); - confirm(-2, makeDate(1993, 2, 28), makeDate(1993, 2, 28), false); - confirm(3, makeDate(1993, 2, 28), makeDate(1993, 3, 1), true); - confirm(2, makeDate(1996, 2, 29), makeDate(1996, 3, 1), true); - - // from https://support.office.com/en-us/article/DAYS360-function-B9A509FD-49EF-407E-94DF-0CBDA5718C2A - confirm(1, makeDate(2011, 1, 30), makeDate(2011, 2, 1), false); - confirm(360, makeDate(2011, 1, 1), makeDate(2011, 12, 31), false); - confirm(30, makeDate(2011, 1, 1), makeDate(2011, 2, 1), false); - } - - private static void confirm(int expResult, int y1, int m1, int d1, int y2, int m2, int d2) { - confirm(expResult, makeDate(y1, m1, d1), makeDate(y2, m2, d2), false); - confirm(-expResult, makeDate(y2, m2, d2), makeDate(y1, m1, d1), false); - } - - /** - * The method parameter only makes a difference when the second parameter - * is the last day of the month that does not have 30 days. - */ - @Test - public void testMonthBoundaries() { - // jan - confirmMonthBoundary(false, 2001, 1, 0, 0, 2, 3, 4); - confirmMonthBoundary(true, 2001, 1, 0, 0, 1, 2, 3); - // feb - confirmMonthBoundary(false, 2001, 2,-2, 1, 2, 3, 4); - confirmMonthBoundary(true, 2001, 2, 0, 1, 2, 3, 4); - // mar - confirmMonthBoundary(false, 2001, 3, 0, 0, 2, 3, 4); - confirmMonthBoundary(true, 2001, 3, 0, 0, 1, 2, 3); - // apr - confirmMonthBoundary(false, 2001, 4, 0, 1, 2, 3, 4); - confirmMonthBoundary(true, 2001, 4, 0, 1, 2, 3, 4); - // may - confirmMonthBoundary(false, 2001, 5, 0, 0, 2, 3, 4); - confirmMonthBoundary(true, 2001, 5, 0, 0, 1, 2, 3); - // jun - confirmMonthBoundary(false, 2001, 6, 0, 1, 2, 3, 4); - confirmMonthBoundary(true, 2001, 6, 0, 1, 2, 3, 4); - // leap year - confirmMonthBoundary(false, 2012, 2, -1, 1, 2, 3, 4); - confirmMonthBoundary(true, 2012, 2, 0, 1, 2, 3, 4); - - // bug 60029 - Date start = makeDate(2018, 2, 28); - Date end = makeDate(2018, 3, 31); - confirm(30, start, end, false); - - // examples from https://support.office.com/en-us/article/DAYS360-function-B9A509FD-49EF-407E-94DF-0CBDA5718C2A - start = makeDate(2011, 1, 30); - end = makeDate(2011, 2, 1); - confirm(1, start, end, false); - - start = makeDate(2011, 1, 1); - end = makeDate(2011, 12, 31); - confirm(360, start, end, false); - - start = makeDate(2011, 1, 1); - end = makeDate(2011, 2, 1); - confirm(30, start, end, false); - } - - - /** - * @param monthNo 1-based - */ - private static void confirmMonthBoundary(boolean method, int year, int monthNo, int...diffs) { - Date firstDayOfNextMonth = makeDate(year, monthNo+1, 1); - Date secondArg = decrementDay(firstDayOfNextMonth); - Date firstArg = secondArg; - - for (int expResult : diffs) { - confirm(expResult, firstArg, secondArg, method); - firstArg = decrementDay(firstArg); - } - - } - private static void confirm(int expResult, Date firstArg, Date secondArg, boolean method) { - ValueEval ve; - if (method) { - ve = invokeDays360(convert(firstArg), convert(secondArg), BoolEval.TRUE); - } else { - ve = invokeDays360(convert(firstArg), convert(secondArg)); - } - assertTrue("wrong return type (" + ve.getClass().getName() + ")", ve instanceof NumberEval); - - NumberEval numberEval = (NumberEval) ve; - String err = String.format(Locale.ROOT, "days360(%tF,%tF,%b) wrong result", firstArg, secondArg, method); - assertEquals(err, expResult, numberEval.getNumberValue(), 0); - } - - private static ValueEval invokeDays360(ValueEval...args) { - return new Days360().evaluate(args, -1, -1); - } - - private static NumberEval convert(Date d) { - return new NumberEval(HSSFDateUtil.getExcelDate(d)); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestDec2Bin.java b/src/testcases/org/apache/poi/ss/formula/functions/TestDec2Bin.java deleted file mode 100644 index c12dbe9e0..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestDec2Bin.java +++ /dev/null @@ -1,241 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import junit.framework.TestCase; - -import org.apache.poi.hssf.usermodel.HSSFEvaluationWorkbook; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.IStabilityClassifier; -import org.apache.poi.ss.formula.OperationEvaluationContext; -import org.apache.poi.ss.formula.WorkbookEvaluator; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; - -/** - * Tests for {@link Dec2Bin} - * - * @author cedric dot walter @ gmail dot com - */ -public final class TestDec2Bin extends TestCase { - - private static ValueEval invokeValue(String number1) { - ValueEval[] args = new ValueEval[] { new StringEval(number1) }; - return new Dec2Bin().evaluate(args, -1, -1); - } - - private static ValueEval invokeBack(String number1) { - ValueEval[] args = new ValueEval[] { new StringEval(number1) }; - return new Bin2Dec().evaluate(args, -1, -1); - } - - private static void confirmValue(String msg, String number1, String expected) { - ValueEval result = invokeValue(number1); - assertEquals("Had: " + result.toString(), StringEval.class, result.getClass()); - assertEquals(msg, expected, ((StringEval) result).getStringValue()); - } - - private static void confirmValueError(String msg, String number1, ErrorEval numError) { - ValueEval result = invokeValue(number1); - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(msg, numError, result); - } - - public void testBasic() { - confirmValue("Converts binary '00101' from binary (5)", "5", "101"); - confirmValue("Converts binary '1111111111' from binary (-1)", "-1", "1111111111"); - confirmValue("Converts binary '1111111110' from binary (-2)", "-2", "1111111110"); - confirmValue("Converts binary '0111111111' from binary (511)", "511", "111111111"); - confirmValue("Converts binary '1000000000' from binary (511)", "-512", "1000000000"); - } - - public void testErrors() { - confirmValueError("fails for >= 512 or < -512","512", ErrorEval.NUM_ERROR); - confirmValueError("fails for >= 512 or < -512","-513", ErrorEval.NUM_ERROR); - confirmValueError("not a valid decimal number","GGGGGGG", ErrorEval.VALUE_INVALID); - confirmValueError("not a valid decimal number","3.14159a", ErrorEval.VALUE_INVALID); - } - - public void testEvalOperationEvaluationContext() { - OperationEvaluationContext ctx = createContext(); - - ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0) }; - ValueEval result = new Dec2Bin().evaluate(args, ctx); - - assertEquals(StringEval.class, result.getClass()); - assertEquals("1101", ((StringEval) result).getStringValue()); - } - - public void testEvalOperationEvaluationContextFails() { - OperationEvaluationContext ctx = createContext(); - - ValueEval[] args = new ValueEval[] { ErrorEval.VALUE_INVALID }; - ValueEval result = new Dec2Bin().evaluate(args, ctx); - - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(ErrorEval.VALUE_INVALID, result); - } - - private OperationEvaluationContext createContext() { - HSSFWorkbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - cell.setCellValue("13.43"); - cell = row.createCell(1); - cell.setCellValue("8"); - cell = row.createCell(2); - cell.setCellValue("-8"); - cell = row.createCell(3); - cell.setCellValue("1"); - - HSSFEvaluationWorkbook workbook = HSSFEvaluationWorkbook.create(wb); - WorkbookEvaluator workbookEvaluator = new WorkbookEvaluator(workbook, new IStabilityClassifier() { - - @Override - public boolean isCellFinal(int sheetIndex, int rowIndex, int columnIndex) { - return true; - } - }, null); - OperationEvaluationContext ctx = new OperationEvaluationContext(workbookEvaluator, - workbook, 0, 0, 0, null); - return ctx; - } - - public void testRefs() { - OperationEvaluationContext ctx = createContext(); - - ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0) }; - ValueEval result = new Dec2Bin().evaluate(args, -1, -1); - - assertEquals("Had: " + result.toString(), StringEval.class, result.getClass()); - assertEquals("1101", ((StringEval) result).getStringValue()); - } - - public void testWithPlacesIntInt() { - OperationEvaluationContext ctx = createContext(); - - ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0), ctx.getRefEval(0, 1) }; - ValueEval result = new Dec2Bin().evaluate(args, -1, -1); - - assertEquals("Had: " + result.toString(), StringEval.class, result.getClass()); - // TODO: documentation and behavior do not match here! - assertEquals("1101", ((StringEval) result).getStringValue()); - } - - public void testWithPlaces() { - OperationEvaluationContext ctx = createContext(); - - ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0), ctx.getRefEval(0, 1) }; - ValueEval result = new Dec2Bin().evaluate(args, ctx); - - assertEquals("Had: " + result.toString(), StringEval.class, result.getClass()); - // TODO: documentation and behavior do not match here! - assertEquals("1101", ((StringEval) result).getStringValue()); - } - - public void testWithToShortPlaces() { - OperationEvaluationContext ctx = createContext(); - - ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0), ctx.getRefEval(0, 3) }; - ValueEval result = new Dec2Bin().evaluate(args, -1, -1); - - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(ErrorEval.NUM_ERROR, result); - } - - public void testWithTooManyParamsIntInt() { - OperationEvaluationContext ctx = createContext(); - - ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0), ctx.getRefEval(0, 1), ctx.getRefEval(0, 1) }; - ValueEval result = new Dec2Bin().evaluate(args, -1, -1); - - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(ErrorEval.VALUE_INVALID, result); - } - - public void testWithTooManyParams() { - OperationEvaluationContext ctx = createContext(); - - ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0), ctx.getRefEval(0, 1), ctx.getRefEval(0, 1) }; - ValueEval result = new Dec2Bin().evaluate(args, ctx); - - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(ErrorEval.VALUE_INVALID, result); - } - - public void testWithErrorPlaces() { - OperationEvaluationContext ctx = createContext(); - - ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0), ErrorEval.NULL_INTERSECTION }; - ValueEval result = new Dec2Bin().evaluate(args, -1, -1); - - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(ErrorEval.NULL_INTERSECTION, result); - } - - public void testWithNegativePlaces() { - OperationEvaluationContext ctx = createContext(); - - ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0), ctx.getRefEval(0, 2) }; - ValueEval result = new Dec2Bin().evaluate(args, -1, -1); - - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(ErrorEval.NUM_ERROR, result); - } - - public void testWithZeroPlaces() { - OperationEvaluationContext ctx = createContext(); - - ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0), new NumberEval(0.0) }; - ValueEval result = new Dec2Bin().evaluate(args, -1, -1); - - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(ErrorEval.NUM_ERROR, result); - } - - public void testWithEmptyPlaces() { - OperationEvaluationContext ctx = createContext(); - - ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0), ctx.getRefEval(1, 0) }; - ValueEval result = new Dec2Bin().evaluate(args, -1, -1); - - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(ErrorEval.VALUE_INVALID, result); - } - - public void testBackAndForth() { - for (int i = -512; i < 512; i++) { - ValueEval result = invokeValue(Integer.toString(i)); - assertEquals("Had: " + result.toString(), StringEval.class, - result.getClass()); - - ValueEval back = invokeBack(((StringEval) result).getStringValue()); - assertEquals("Had: " + back.toString(), NumberEval.class, - back.getClass()); - - assertEquals(Integer.toString(i), - ((NumberEval) back).getStringValue()); - } - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestDec2Hex.java b/src/testcases/org/apache/poi/ss/formula/functions/TestDec2Hex.java deleted file mode 100644 index 6084d652d..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestDec2Hex.java +++ /dev/null @@ -1,244 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import junit.framework.TestCase; - -import org.apache.poi.hssf.usermodel.HSSFEvaluationWorkbook; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.IStabilityClassifier; -import org.apache.poi.ss.formula.OperationEvaluationContext; -import org.apache.poi.ss.formula.WorkbookEvaluator; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; - -/** - * Tests for {@link Dec2Hex} - * - * @author cedric dot walter @ gmail dot com - */ -public final class TestDec2Hex extends TestCase { - - private static ValueEval invokeValue(String number1, String number2) { - ValueEval[] args = new ValueEval[] { new StringEval(number1), new StringEval(number2), }; - return new Dec2Hex().evaluate(args, -1, -1); - } - - private static ValueEval invokeBack(String number1) { - ValueEval[] args = new ValueEval[] { new StringEval(number1) }; - return new Hex2Dec().evaluate(args, -1, -1); - } - - private static ValueEval invokeValue(String number1) { - ValueEval[] args = new ValueEval[] { new StringEval(number1), }; - return new Dec2Hex().evaluate(args, -1, -1); - } - - private static void confirmValue(String msg, String number1, String number2, String expected) { - ValueEval result = invokeValue(number1, number2); - assertEquals(StringEval.class, result.getClass()); - assertEquals(msg, expected, ((StringEval) result).getStringValue()); - } - - private static void confirmValue(String msg, String number1, String expected) { - ValueEval result = invokeValue(number1); - assertEquals(StringEval.class, result.getClass()); - assertEquals(msg, expected, ((StringEval) result).getStringValue()); - } - - private static void confirmValueError(String msg, String number1, String number2, ErrorEval numError) { - ValueEval result = invokeValue(number1, number2); - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(msg, numError, result); - } - - public void testBasic() { - confirmValue("Converts decimal 100 to hexadecimal with 0 characters (64)", "100","0", "64"); - confirmValue("Converts decimal 100 to hexadecimal with 4 characters (0064)", "100","4", "0064"); - confirmValue("Converts decimal 100 to hexadecimal with 5 characters (0064)", "100","5", "00064"); - confirmValue("Converts decimal 100 to hexadecimal with 10 (default) characters", "100","10", "0000000064"); - confirmValue("If argument places contains a decimal value, dec2hex ignores the numbers to the right side of the decimal point.", "100","10.0", "0000000064"); - - confirmValue("Converts decimal -54 to hexadecimal, 2 is ignored","-54", "2", "FFFFFFFFCA"); - confirmValue("places is optionnal","-54", "FFFFFFFFCA"); - - confirmValue("Converts normal decimal number to hexadecimal", "100", "64"); - - String maxInt = Integer.toString(Integer.MAX_VALUE); - assertEquals("2147483647", maxInt); - confirmValue("Converts INT_MAX to hexadecimal", maxInt, "7FFFFFFF"); - - String minInt = Integer.toString(Integer.MIN_VALUE); - assertEquals("-2147483648", minInt); - confirmValue("Converts INT_MIN to hexadecimal", minInt, "FF80000000"); - - String maxIntPlusOne = Long.toString(((long)Integer.MAX_VALUE)+1); - assertEquals("2147483648", maxIntPlusOne); - confirmValue("Converts INT_MAX + 1 to hexadecimal", maxIntPlusOne, "80000000"); - - String maxLong = Long.toString(549755813887l); - assertEquals("549755813887", maxLong); - confirmValue("Converts the max supported value to hexadecimal", maxLong, "7FFFFFFFFF"); - - String minLong = Long.toString(-549755813888l); - assertEquals("-549755813888", minLong); - confirmValue("Converts the min supported value to hexadecimal", minLong, "FF80000000"); - } - - public void testErrors() { - confirmValueError("Out of range min number","-549755813889","0", ErrorEval.NUM_ERROR); - confirmValueError("Out of range max number","549755813888","0", ErrorEval.NUM_ERROR); - - confirmValueError("negative places not allowed","549755813888","-10", ErrorEval.NUM_ERROR); - confirmValueError("non number places not allowed","ABCDEF","0", ErrorEval.VALUE_INVALID); - } - - public void testEvalOperationEvaluationContextFails() { - OperationEvaluationContext ctx = createContext(); - - ValueEval[] args = new ValueEval[] { ErrorEval.VALUE_INVALID }; - ValueEval result = new Dec2Hex().evaluate(args, ctx); - - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(ErrorEval.VALUE_INVALID, result); - } - - private OperationEvaluationContext createContext() { - HSSFWorkbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - cell.setCellValue("123.43"); - cell = row.createCell(1); - cell.setCellValue("8"); - cell = row.createCell(2); - cell.setCellValue("-8"); - - HSSFEvaluationWorkbook workbook = HSSFEvaluationWorkbook.create(wb); - WorkbookEvaluator workbookEvaluator = new WorkbookEvaluator(workbook, new IStabilityClassifier() { - - @Override - public boolean isCellFinal(int sheetIndex, int rowIndex, int columnIndex) { - return true; - } - }, null); - OperationEvaluationContext ctx = new OperationEvaluationContext(workbookEvaluator, - workbook, 0, 0, 0, null); - return ctx; - } - - public void testRefs() { - OperationEvaluationContext ctx = createContext(); - - ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0) }; - ValueEval result = new Dec2Hex().evaluate(args, -1, -1); - - assertEquals("Had: " + result.toString(), StringEval.class, result.getClass()); - assertEquals("7B", ((StringEval) result).getStringValue()); - } - - public void testWithPlacesIntInt() { - OperationEvaluationContext ctx = createContext(); - - ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0), ctx.getRefEval(0, 1) }; - ValueEval result = new Dec2Hex().evaluate(args, -1, -1); - - assertEquals("Had: " + result.toString(), StringEval.class, result.getClass()); - assertEquals("0000007B", ((StringEval) result).getStringValue()); - } - - public void testWithPlaces() { - OperationEvaluationContext ctx = createContext(); - - ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0), ctx.getRefEval(0, 1) }; - ValueEval result = new Dec2Hex().evaluate(args, ctx); - - assertEquals("Had: " + result.toString(), StringEval.class, result.getClass()); - assertEquals("0000007B", ((StringEval) result).getStringValue()); - } - - public void testWithTooManyParamsIntInt() { - OperationEvaluationContext ctx = createContext(); - - ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0), ctx.getRefEval(0, 1), ctx.getRefEval(0, 1) }; - ValueEval result = new Dec2Hex().evaluate(args, -1, -1); - - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(ErrorEval.VALUE_INVALID, result); - } - - public void testWithTooManyParams() { - OperationEvaluationContext ctx = createContext(); - - ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0), ctx.getRefEval(0, 1), ctx.getRefEval(0, 1) }; - ValueEval result = new Dec2Hex().evaluate(args, ctx); - - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(ErrorEval.VALUE_INVALID, result); - } - - public void testWithErrorPlaces() { - OperationEvaluationContext ctx = createContext(); - - ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0), ErrorEval.NULL_INTERSECTION }; - ValueEval result = new Dec2Hex().evaluate(args, -1, -1); - - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(ErrorEval.NULL_INTERSECTION, result); - } - - public void testWithNegativePlaces() { - OperationEvaluationContext ctx = createContext(); - - ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0), ctx.getRefEval(0, 2) }; - ValueEval result = new Dec2Hex().evaluate(args, -1, -1); - - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(ErrorEval.NUM_ERROR, result); - } - - public void testWithEmptyPlaces() { - OperationEvaluationContext ctx = createContext(); - - ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0), ctx.getRefEval(1, 0) }; - ValueEval result = new Dec2Hex().evaluate(args, -1, -1); - - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(ErrorEval.VALUE_INVALID, result); - } - - public void testBackAndForth() { - for (int i = -512; i < 512; i++) { - ValueEval result = invokeValue(Integer.toString(i)); - assertEquals("Had: " + result.toString(), StringEval.class, - result.getClass()); - - ValueEval back = invokeBack(((StringEval) result).getStringValue()); - assertEquals("Had: " + back.toString(), NumberEval.class, - back.getClass()); - - assertEquals(Integer.toString(i), - ((NumberEval) back).getStringValue()); - } - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestDelta.java b/src/testcases/org/apache/poi/ss/formula/functions/TestDelta.java deleted file mode 100644 index 30ce14021..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestDelta.java +++ /dev/null @@ -1,63 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import junit.framework.TestCase; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; - -/** - * Tests for {@link org.apache.poi.ss.formula.functions.Delta} - * - * @author cedric dot walter @ gmail dot com - */ -public final class TestDelta extends TestCase { - - private static ValueEval invokeValue(String number1, String number2) { - ValueEval[] args = new ValueEval[] { new StringEval(number1), new StringEval(number2), }; - return new Delta().evaluate(args, -1, -1); - } - - private static void confirmValue(String number1, String number2, double expected) { - ValueEval result = invokeValue(number1, number2); - assertEquals(NumberEval.class, result.getClass()); - assertEquals(expected, ((NumberEval) result).getNumberValue(), 0.0); - } - - private static void confirmValueError(String number1, String number2) { - ValueEval result = invokeValue(number1, number2); - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(ErrorEval.VALUE_INVALID, result); - } - - public void testBasic() { - confirmValue("5","4", 0); // Checks whether 5 equals 4 (0) - confirmValue("5","5", 1); // Checks whether 5 equals 5 (1) - - confirmValue("0.5","0", 0); // Checks whether 0.5 equals 0 (0) - confirmValue("0.50","0.5", 1); - confirmValue("0.5000000000","0.5", 1); - } - - public void testErrors() { - confirmValueError("A1","B2"); - confirmValueError("AAAA","BBBB"); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestDeltaFunctionsFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/functions/TestDeltaFunctionsFromSpreadsheet.java deleted file mode 100644 index d469f930a..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestDeltaFunctionsFromSpreadsheet.java +++ /dev/null @@ -1,31 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.formula.functions; - -import java.util.Collection; - -import org.junit.runners.Parameterized.Parameters; - -/** - * Tests DELTA() as loaded from a test data spreadsheet.

    - */ -public class TestDeltaFunctionsFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - @Parameters(name="{0}") - public static Collection data() throws Exception { - return data(TestDeltaFunctionsFromSpreadsheet.class, "DeltaFunctionTestCaseData.xls"); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestEDate.java b/src/testcases/org/apache/poi/ss/formula/functions/TestEDate.java deleted file mode 100644 index 1b134483d..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestEDate.java +++ /dev/null @@ -1,129 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.util.Calendar; -import java.util.Date; - -import org.apache.poi.ss.formula.eval.BlankEval; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.ss.usermodel.DateUtil; -import org.apache.poi.ss.usermodel.FormulaError; -import org.apache.poi.util.LocaleUtil; -import org.junit.Test; - -public class TestEDate { - - @Test - public void testEDateProperValues() { - // verify some border-case combinations of startDate and month-increase - checkValue(1000, 0, 1000d); - checkValue(1, 0, 1d); - checkValue(0, 1, 31d); - checkValue(1, 1, 32d); - checkValue(0, 0, /* BAD_DATE! */ -1.0d); - checkValue(0, -2, /* BAD_DATE! */ -1.0d); - checkValue(0, -3, /* BAD_DATE! */ -1.0d); - checkValue(49104, 0, 49104d); - checkValue(49104, 1, 49134d); - } - - private void checkValue(int startDate, int monthInc, double expectedResult) { - EDate eDate = new EDate(); - NumberEval result = (NumberEval) eDate.evaluate(new ValueEval[]{new NumberEval(startDate), new NumberEval(monthInc)}, null); - assertEquals(expectedResult, result.getNumberValue(), 0); - } - - @Test - public void testEDateInvalidValues() { - EDate eDate = new EDate(); - ErrorEval result = (ErrorEval) eDate.evaluate(new ValueEval[]{new NumberEval(1000)}, null); - assertEquals(FormulaError.VALUE.getCode(), result.getErrorCode(), 0); - } - - @Test - public void testEDateIncrease() { - EDate eDate = new EDate(); - Date startDate = new Date(); - int offset = 2; - NumberEval result = (NumberEval) eDate.evaluate(new ValueEval[]{new NumberEval(DateUtil.getExcelDate(startDate)), new NumberEval(offset)}, null); - Date resultDate = DateUtil.getJavaDate(result.getNumberValue()); - Calendar instance = LocaleUtil.getLocaleCalendar(); - instance.setTime(startDate); - instance.add(Calendar.MONTH, offset); - assertEquals(resultDate, instance.getTime()); - - } - - @Test - public void testEDateDecrease() { - EDate eDate = new EDate(); - Date startDate = new Date(); - int offset = -2; - NumberEval result = (NumberEval) eDate.evaluate(new ValueEval[]{new NumberEval(DateUtil.getExcelDate(startDate)), new NumberEval(offset)}, null); - Date resultDate = DateUtil.getJavaDate(result.getNumberValue()); - Calendar instance = LocaleUtil.getLocaleCalendar(); - instance.setTime(startDate); - instance.add(Calendar.MONTH, offset); - assertEquals(resultDate, instance.getTime()); - } - - @Test - public void testBug56688() { - EDate eDate = new EDate(); - NumberEval result = (NumberEval) eDate.evaluate(new ValueEval[]{new NumberEval(1000), new RefEvalImplementation(new NumberEval(0))}, null); - assertEquals(1000d, result.getNumberValue(), 0); - } - - @Test - public void testRefEvalStartDate() { - EDate eDate = new EDate(); - NumberEval result = (NumberEval) eDate.evaluate(new ValueEval[]{new RefEvalImplementation(new NumberEval(1000)), new NumberEval(0)}, null); - assertEquals(1000d, result.getNumberValue(), 0); - } - - @Test - public void testEDateInvalidValueEval() { - ValueEval evaluate = new EDate().evaluate(new ValueEval[]{new ValueEval() {}, new NumberEval(0)}, null); - assertTrue(evaluate instanceof ErrorEval); - assertEquals(ErrorEval.VALUE_INVALID, evaluate); - } - - @Test - public void testEDateBlankValueEval() { - NumberEval evaluate = (NumberEval) new EDate().evaluate(new ValueEval[]{BlankEval.instance, new NumberEval(0)}, null); - assertEquals(-1.0d, evaluate.getNumberValue(), 0); - } - - @Test - public void testEDateBlankRefValueEval() { - EDate eDate = new EDate(); - NumberEval result = (NumberEval) eDate.evaluate(new ValueEval[]{new RefEvalImplementation(BlankEval.instance), new NumberEval(0)}, null); - assertEquals("0 startDate triggers BAD_DATE currently, thus -1.0!", - -1.0d, result.getNumberValue(), 0); - - result = (NumberEval) eDate.evaluate(new ValueEval[]{new NumberEval(1), new RefEvalImplementation(BlankEval.instance)}, null); - assertEquals("Blank is handled as 0 otherwise", - 1.0d, result.getNumberValue(), 0); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestEOMonth.java b/src/testcases/org/apache/poi/ss/formula/functions/TestEOMonth.java deleted file mode 100644 index 71c49cf75..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestEOMonth.java +++ /dev/null @@ -1,152 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.util.Calendar; -import java.util.Date; - -import org.apache.poi.ss.formula.OperationEvaluationContext; -import org.apache.poi.ss.formula.eval.BlankEval; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.ss.usermodel.DateUtil; -import org.apache.poi.ss.usermodel.FormulaError; -import org.apache.poi.util.LocaleUtil; -import org.junit.Test; - -public class TestEOMonth { - - private static final double BAD_DATE = -1.0; - - private static final double DATE_1900_01_01 = 1.0; - private static final double DATE_1900_01_31 = 31.0; - private static final double DATE_1900_02_28 = 59.0; - private static final double DATE_1902_09_26 = 1000.0; - private static final double DATE_1902_09_30 = 1004.0; - private static final double DATE_2034_06_09 = 49104.0; - private static final double DATE_2034_06_30 = 49125.0; - private static final double DATE_2034_07_31 = 49156.0; - - private final FreeRefFunction eOMonth = EOMonth.instance; - private final OperationEvaluationContext ec = new OperationEvaluationContext(null, null, 0, 0, 0, null); - - @Test - public void testEOMonthProperValues() { - // verify some border-case combinations of startDate and month-increase - checkValue(DATE_1900_01_01, 0, DATE_1900_01_31); - checkValue(DATE_1900_01_01, 1, DATE_1900_02_28); - checkValue(DATE_1902_09_26, 0, DATE_1902_09_30); - checkValue(DATE_2034_06_09, 0, DATE_2034_06_30); - checkValue(DATE_2034_06_09, 1, DATE_2034_07_31); - } - - @Test - public void testEOMonthBadDateValues() { - checkValue(0.0, -2, BAD_DATE); - checkValue(0.0, -3, BAD_DATE); - checkValue(DATE_1900_01_31, -1, BAD_DATE); - } - - private void checkValue(double startDate, int monthInc, double expectedResult) { - ValueEval ve[] = {new NumberEval(startDate), new NumberEval(monthInc)}; - NumberEval result = (NumberEval) eOMonth.evaluate(ve, ec); - assertEquals(expectedResult, result.getNumberValue(), 0); - } - - @Test - public void testEOMonthZeroDate() { - NumberEval result = (NumberEval) eOMonth.evaluate(new ValueEval[] {new NumberEval(0), new NumberEval(0)}, ec); - assertEquals("0 startDate is 1900-01-00", DATE_1900_01_31, result.getNumberValue(), 0); - - result = (NumberEval) eOMonth.evaluate(new ValueEval[] {new NumberEval(0), new NumberEval(1)}, ec); - assertEquals("0 startDate is 1900-01-00", DATE_1900_02_28, result.getNumberValue(), 0); - } - - @Test - public void testEOMonthInvalidArguments() { - ValueEval result = eOMonth.evaluate(new ValueEval[] {new NumberEval(DATE_1902_09_26)}, ec); - assertTrue(result instanceof ErrorEval); - assertEquals(FormulaError.VALUE.getCode(), ((ErrorEval) result).getErrorCode(), 0); - - result = eOMonth.evaluate(new ValueEval[] {new StringEval("a"), new StringEval("b")}, ec); - assertTrue(result instanceof ErrorEval); - assertEquals(FormulaError.VALUE.getCode(), ((ErrorEval) result).getErrorCode(), 0); - } - - @Test - public void checkOffset() { - for (int offset=-12; offset<=12; offset++) { - Calendar cal = LocaleUtil.getLocaleCalendar(); - Date startDate = cal.getTime(); - - cal.add(Calendar.MONTH, offset); - cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH)); - cal.clear(Calendar.HOUR); - cal.set(Calendar.HOUR_OF_DAY, 0); - cal.clear(Calendar.MINUTE); - cal.clear(Calendar.SECOND); - cal.clear(Calendar.MILLISECOND); - Date expDate = cal.getTime(); - - ValueEval ve[] = { - new NumberEval(DateUtil.getExcelDate(startDate)), - new NumberEval(offset) - }; - NumberEval result = (NumberEval) eOMonth.evaluate(ve, ec); - Date actDate = DateUtil.getJavaDate(result.getNumberValue()); - - assertEquals(expDate, actDate); - } - } - - @Test - public void testBug56688() { - ValueEval ve[] = {new NumberEval(DATE_1902_09_26), new RefEvalImplementation(new NumberEval(0))}; - NumberEval result = (NumberEval) eOMonth.evaluate(ve, ec); - assertEquals(DATE_1902_09_30, result.getNumberValue(), 0); - } - - @Test - public void testRefEvalStartDate() { - ValueEval ve[] = {new RefEvalImplementation(new NumberEval(DATE_1902_09_26)), new NumberEval(0)}; - NumberEval result = (NumberEval) eOMonth.evaluate(ve, ec); - assertEquals(DATE_1902_09_30, result.getNumberValue(), 0); - } - - @Test - public void testEOMonthBlankValueEval() { - NumberEval evaluate = (NumberEval) eOMonth.evaluate(new ValueEval[] {BlankEval.instance, new NumberEval(0)}, ec); - assertEquals("Blank is handled as 0", DATE_1900_01_31, evaluate.getNumberValue(), 0); - } - - @Test - public void testEOMonthBlankRefValueEval() { - ValueEval[] ve1 = {new RefEvalImplementation(BlankEval.instance), new NumberEval(1)}; - NumberEval result = (NumberEval) eOMonth.evaluate(ve1, ec); - assertEquals("Blank is handled as 0", DATE_1900_02_28, result.getNumberValue(), 0); - - ValueEval[] ve2 = {new NumberEval(1), new RefEvalImplementation(BlankEval.instance)}; - result = (NumberEval) eOMonth.evaluate(ve2, ec); - assertEquals("Blank is handled as 0", DATE_1900_01_31, result.getNumberValue(), 0); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestFactDoubleFunctionsFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/functions/TestFactDoubleFunctionsFromSpreadsheet.java deleted file mode 100644 index df3001e89..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestFactDoubleFunctionsFromSpreadsheet.java +++ /dev/null @@ -1,32 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import java.util.Collection; - -import org.junit.runners.Parameterized.Parameters; - -/** - * Tests FactDouble() as loaded from a test data spreadsheet.

    - */ -public class TestFactDoubleFunctionsFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - @Parameters(name="{0}") - public static Collection data() throws Exception { - return data(TestFactDoubleFunctionsFromSpreadsheet.class, "FactDoubleFunctionTestCaseData.xls"); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestFinanceLib.java b/src/testcases/org/apache/poi/ss/formula/functions/TestFinanceLib.java deleted file mode 100644 index 90300bf24..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestFinanceLib.java +++ /dev/null @@ -1,202 +0,0 @@ -/* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -/* - * Created on May 23, 2005 - * - */ -package org.apache.poi.ss.formula.functions; - - -/** - * @author Amol S. Deshmukh < amolweb at ya hoo dot com > - * - */ -public class TestFinanceLib extends AbstractNumericTestCase { - - public void testFv() { - double f, r, y, p, x; - int n; - boolean t = false; - - r = 0; n = 3; y = 2; p = 7; t = true; - f = FinanceLib.fv(r, n, y, p, t); - x = -13; - assertEquals("fv ", x, f); - - r = 1; n = 10; y = 100; p = 10000; t = false; - f = FinanceLib.fv(r, n, y, p, t); - x = -10342300; - assertEquals("fv ", x, f); - - r = 1; n = 10; y = 100; p = 10000; t = true; - f = FinanceLib.fv(r, n, y, p, t); - x = -10444600; - assertEquals("fv ", x, f); - - r = 2; n = 12; y = 120; p = 12000; t = false; - f = FinanceLib.fv(r, n, y, p, t); - x = -6409178400d; - assertEquals("fv ", x, f); - - r = 2; n = 12; y = 120; p = 12000; t = true; - f = FinanceLib.fv(r, n, y, p, t); - x = -6472951200d; - assertEquals("fv ", x, f); - - // cross tests with pv - r = 2.95; n = 13; y = 13000; p = -4406.78544294496; t = false; - f = FinanceLib.fv(r, n, y, p, t); - x = 333891.230010986; // as returned by excel - assertEquals("fv ", x, f); - - r = 2.95; n = 13; y = 13000; p = -17406.7852148156; t = true; - f = FinanceLib.fv(r, n, y, p, t); - x = 333891.230102539; // as returned by excel - assertEquals("fv ", x, f); - - } - public void testNpv() { - double r, v[], npv, x; - - r = 1; v = new double[]{100, 200, 300, 400}; - npv = FinanceLib.npv(r, v); - x = 162.5; - assertEquals("npv ", x, npv); - - r = 2.5; v = new double[]{1000, 666.66666, 333.33, 12.2768416}; - npv = FinanceLib.npv(r, v); - x = 347.99232604144827; - assertEquals("npv ", x, npv); - - r = 12.33333; v = new double[]{1000, 0, -900, -7777.5765}; - npv = FinanceLib.npv(r, v); - x = 74.3742433377061; - assertEquals("npv ", x, npv); - - r = 0.05; v = new double[]{200000, 300000.55, 400000, 1000000, 6000000, 7000000, -300000}; - npv = FinanceLib.npv(r, v); - x = 11342283.4233124; - assertEquals("npv ", x, npv); - } - public void testPmt() { - double f, r, y, p, x; - int n; - boolean t = false; - - r = 0; n = 3; p = 2; f = 7; t = true; - y = FinanceLib.pmt(r, n, p, f, t); - x = -3; - assertEquals("pmt ", x, y); - - // cross check with pv - r = 1; n = 10; p = -109.66796875; f = 10000; t = false; - y = FinanceLib.pmt(r, n, p, f, t); - x = 100; - assertEquals("pmt ", x, y); - - r = 1; n = 10; p = -209.5703125; f = 10000; t = true; - y = FinanceLib.pmt(r, n, p, f, t); - x = 100; - assertEquals("pmt ", x, y); - - // cross check with fv - r = 2; n = 12; f = -6409178400d; p = 12000; t = false; - y = FinanceLib.pmt(r, n, p, f, t); - x = 120; - assertEquals("pmt ", x, y); - - r = 2; n = 12; f = -6472951200d; p = 12000; t = true; - y = FinanceLib.pmt(r, n, p, f, t); - x = 120; - assertEquals("pmt ", x, y); - } - - public void testPv() { - double f, r, y, p, x; - int n; - boolean t = false; - - r = 0; n = 3; y = 2; f = 7; t = true; - f = FinanceLib.pv(r, n, y, f, t); - x = -13; - assertEquals("pv ", x, f); - - r = 1; n = 10; y = 100; f = 10000; t = false; - p = FinanceLib.pv(r, n, y, f, t); - x = -109.66796875; - assertEquals("pv ", x, p); - - r = 1; n = 10; y = 100; f = 10000; t = true; - p = FinanceLib.pv(r, n, y, f, t); - x = -209.5703125; - assertEquals("pv ", x, p); - - r = 2.95; n = 13; y = 13000; f = 333891.23; t = false; - p = FinanceLib.pv(r, n, y, f, t); - x = -4406.78544294496; - assertEquals("pv ", x, p); - - r = 2.95; n = 13; y = 13000; f = 333891.23; t = true; - p = FinanceLib.pv(r, n, y, f, t); - x = -17406.7852148156; - assertEquals("pv ", x, p); - - // cross tests with fv - r = 2; n = 12; y = 120; f = -6409178400d; t = false; - p = FinanceLib.pv(r, n, y, f, t); - x = 12000; - assertEquals("pv ", x, p); - - r = 2; n = 12; y = 120; f = -6472951200d; t = true; - p = FinanceLib.pv(r, n, y, f, t); - x = 12000; - assertEquals("pv ", x, p); - - } - - public void testNper() { - double f, r, y, p, x, n; - boolean t = false; - - r = 0; y = 7; p = 2; f = 3; t = false; - n = FinanceLib.nper(r, y, p, f, t); - x = -0.71428571429; // can you believe it? excel returns nper as a fraction!?? - assertEquals("nper ", x, n); - - // cross check with pv - r = 1; y = 100; p = -109.66796875; f = 10000; t = false; - n = FinanceLib.nper(r, y, p, f, t); - x = 10; - assertEquals("nper ", x, n); - - r = 1; y = 100; p = -209.5703125; f = 10000; t = true; - n = FinanceLib.nper(r, y, p, f, t); - x = 10; - assertEquals("nper ", x, n); - - // cross check with fv - r = 2; y = 120; f = -6409178400d; p = 12000; t = false; - n = FinanceLib.nper(r, y, p, f, t); - x = 12; - assertEquals("nper ", x, n); - - r = 2; y = 120; f = -6472951200d; p = 12000; t = true; - n = FinanceLib.nper(r, y, p, f, t); - x = 12; - assertEquals("nper ", x, n); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestFind.java b/src/testcases/org/apache/poi/ss/formula/functions/TestFind.java deleted file mode 100644 index 5ac75d62a..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestFind.java +++ /dev/null @@ -1,81 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.Assert.assertEquals; - -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; -import org.apache.poi.ss.usermodel.FormulaError; -import org.junit.Test; - -/** - * Tests for {@link Financed} - */ -public final class TestFind { - - @Test - public void testFind() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFCell cell = wb.createSheet().createRow(0).createCell(0); - - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - - confirmResult(fe, cell, "find(\"h\", \"haystack\")", 1); - confirmResult(fe, cell, "find(\"a\", \"haystack\",2)", 2); - confirmResult(fe, cell, "find(\"a\", \"haystack\",3)", 6); - - // number args converted to text - confirmResult(fe, cell, "find(7, 32768)", 3); - confirmResult(fe, cell, "find(\"34\", 1341235233412, 3)", 10); - confirmResult(fe, cell, "find(5, 87654)", 4); - - // Errors - confirmError(fe, cell, "find(\"n\", \"haystack\")", FormulaError.VALUE); - confirmError(fe, cell, "find(\"k\", \"haystack\",9)", FormulaError.VALUE); - confirmError(fe, cell, "find(\"k\", \"haystack\",#REF!)", FormulaError.REF); - confirmError(fe, cell, "find(\"k\", \"haystack\",0)", FormulaError.VALUE); - confirmError(fe, cell, "find(#DIV/0!, #N/A, #REF!)", FormulaError.DIV0); - confirmError(fe, cell, "find(2, #N/A, #REF!)", FormulaError.NA); - - wb.close(); - } - - private static void confirmResult(HSSFFormulaEvaluator fe, HSSFCell cell, String formulaText, - int expectedResult) { - cell.setCellFormula(formulaText); - fe.notifyUpdateCell(cell); - CellValue result = fe.evaluate(cell); - assertEquals(result.getCellTypeEnum(), CellType.NUMERIC); - assertEquals(expectedResult, result.getNumberValue(), 0.0); - } - - private static void confirmError(HSSFFormulaEvaluator fe, HSSFCell cell, String formulaText, - FormulaError expectedErrorCode) { - cell.setCellFormula(formulaText); - fe.notifyUpdateCell(cell); - CellValue result = fe.evaluate(cell); - assertEquals(result.getCellTypeEnum(), CellType.ERROR); - assertEquals(expectedErrorCode.getCode(), result.getErrorValue()); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestFixed.java b/src/testcases/org/apache/poi/ss/formula/functions/TestFixed.java deleted file mode 100644 index f6e1f3809..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestFixed.java +++ /dev/null @@ -1,133 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.eval.BoolEval; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; -import org.apache.poi.ss.usermodel.FormulaError; -import org.junit.Before; -import org.junit.Test; - -public final class TestFixed { - - private HSSFCell cell11; - private HSSFFormulaEvaluator evaluator; - - @Before - public void setUp() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - try { - HSSFSheet sheet = wb.createSheet("new sheet"); - cell11 = sheet.createRow(0).createCell(0); - cell11.setCellType(CellType.FORMULA); - evaluator = new HSSFFormulaEvaluator(wb); - } finally { - wb.close(); - } - } - - @Test - public void testValid() { - // thousands separator - confirm("FIXED(1234.56789,2,TRUE)", "1234.57"); - confirm("FIXED(1234.56789,2,FALSE)", "1,234.57"); - // rounding - confirm("FIXED(1.8,0,TRUE)", "2"); - confirm("FIXED(1.2,0,TRUE)", "1"); - confirm("FIXED(1.5,0,TRUE)", "2"); - confirm("FIXED(1,0,TRUE)", "1"); - // fractional digits - confirm("FIXED(1234.56789,7,TRUE)", "1234.5678900"); - confirm("FIXED(1234.56789,0,TRUE)", "1235"); - confirm("FIXED(1234.56789,-1,TRUE)", "1230"); - // less than three arguments - confirm("FIXED(1234.56789)", "1,234.57"); - confirm("FIXED(1234.56789,3)", "1,234.568"); - // invalid arguments - confirmValueError("FIXED(\"invalid\")"); - confirmValueError("FIXED(1,\"invalid\")"); - confirmValueError("FIXED(1,2,\"invalid\")"); - // strange arguments - confirm("FIXED(1000,2,8)", "1000.00"); - confirm("FIXED(1000,2,0)", "1,000.00"); - // corner cases - confirm("FIXED(1.23456789012345,15,TRUE)", "1.234567890123450"); - // Seems POI accepts longer numbers than Excel does, excel trims the - // number to 15 digits and removes the "9" in the formula itself. - // Not the fault of FIXED though. - // confirm("FIXED(1.234567890123459,15,TRUE)", "1.234567890123450"); - confirm("FIXED(60,-2,TRUE)", "100"); - confirm("FIXED(10,-2,TRUE)", "0"); - // rounding propagation - confirm("FIXED(99.9,0,TRUE)", "100"); - } - - @Test - public void testOptionalParams() { - Fixed fixed = new Fixed(); - ValueEval evaluate = fixed.evaluate(0, 0, new NumberEval(1234.56789)); - assertTrue(evaluate instanceof StringEval); - assertEquals("1,234.57", ((StringEval)evaluate).getStringValue()); - - evaluate = fixed.evaluate(0, 0, new NumberEval(1234.56789), new NumberEval(1)); - assertTrue(evaluate instanceof StringEval); - assertEquals("1,234.6", ((StringEval)evaluate).getStringValue()); - - evaluate = fixed.evaluate(0, 0, new NumberEval(1234.56789), new NumberEval(1), BoolEval.TRUE); - assertTrue(evaluate instanceof StringEval); - assertEquals("1234.6", ((StringEval)evaluate).getStringValue()); - - evaluate = fixed.evaluate(new ValueEval[] {}, 1, 1); - assertTrue(evaluate instanceof ErrorEval); - - evaluate = fixed.evaluate(new ValueEval[] { new NumberEval(1), new NumberEval(1), new NumberEval(1), new NumberEval(1) }, 1, 1); - assertTrue(evaluate instanceof ErrorEval); - } - - private void confirm(String formulaText, String expectedResult) { - cell11.setCellFormula(formulaText); - evaluator.clearAllCachedResultValues(); - CellValue cv = evaluator.evaluate(cell11); - assertEquals("Wrong result type: " + cv.formatAsString(), CellType.STRING, cv.getCellTypeEnum()); - String actualValue = cv.getStringValue(); - assertEquals(expectedResult, actualValue); - } - - private void confirmValueError(String formulaText) { - cell11.setCellFormula(formulaText); - evaluator.clearAllCachedResultValues(); - CellValue cv = evaluator.evaluate(cell11); - assertTrue("Wrong result type: " + cv.formatAsString(), - cv.getCellTypeEnum() == CellType.ERROR - && cv.getErrorValue() == FormulaError.VALUE.getCode()); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestFixedFunctionsFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/functions/TestFixedFunctionsFromSpreadsheet.java deleted file mode 100644 index a5efd75e2..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestFixedFunctionsFromSpreadsheet.java +++ /dev/null @@ -1,32 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import java.util.Collection; - -import org.junit.runners.Parameterized.Parameters; - -/** - * Tests FIXED() as loaded from a test data spreadsheet. - */ -public class TestFixedFunctionsFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - @Parameters(name="{0}") - public static Collection data() throws Exception { - return data(TestFixedFunctionsFromSpreadsheet.class, "57003-FixedFunctionTestCaseData.xls"); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestHex2Dec.java b/src/testcases/org/apache/poi/ss/formula/functions/TestHex2Dec.java deleted file mode 100644 index b1bcb2f85..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestHex2Dec.java +++ /dev/null @@ -1,112 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import junit.framework.TestCase; - -import org.apache.poi.hssf.usermodel.HSSFEvaluationWorkbook; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.IStabilityClassifier; -import org.apache.poi.ss.formula.OperationEvaluationContext; -import org.apache.poi.ss.formula.WorkbookEvaluator; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; - -/** - * Tests for {@link Hex2Dec} - * - * @author cedric dot walter @ gmail dot com - */ -public final class TestHex2Dec extends TestCase { - - private static ValueEval invokeValue(String number1) { - ValueEval[] args = new ValueEval[] { new StringEval(number1) }; - return new Hex2Dec().evaluate(args, -1, -1); - } - - private static void confirmValue(String msg, String number1, String expected) { - ValueEval result = invokeValue(number1); - assertEquals(NumberEval.class, result.getClass()); - assertEquals(msg, expected, ((NumberEval) result).getStringValue()); - } - - private static void confirmValueError(String msg, String number1, ErrorEval numError) { - ValueEval result = invokeValue(number1); - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(msg, numError, result); - } - - public void testBasic() { - confirmValue("Converts hex 'A5' to decimal (165)", "A5", "165"); - confirmValue("Converts hex FFFFFFFF5B to decimal (-165)", "FFFFFFFF5B", "-165"); - confirmValue("Converts hex 3DA408B9 to decimal (-165)", "3DA408B9", "1034160313"); - } - - public void testErrors() { - confirmValueError("not a valid hex number","GGGGGGG", ErrorEval.NUM_ERROR); - confirmValueError("not a valid hex number","3.14159", ErrorEval.NUM_ERROR); - } - - public void testEvalOperationEvaluationContext() { - OperationEvaluationContext ctx = createContext(); - - ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0) }; - ValueEval result = new Hex2Dec().evaluate(args, ctx); - - assertEquals(NumberEval.class, result.getClass()); - assertEquals("0", ((NumberEval) result).getStringValue()); - } - - public void testEvalOperationEvaluationContextFails() { - OperationEvaluationContext ctx = createContext(); - - ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0), ctx.getRefEval(0, 0) }; - ValueEval result = new Hex2Dec().evaluate(args, ctx); - - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(ErrorEval.VALUE_INVALID, result); - } - - private OperationEvaluationContext createContext() { - HSSFWorkbook wb = new HSSFWorkbook(); - wb.createSheet(); - HSSFEvaluationWorkbook workbook = HSSFEvaluationWorkbook.create(wb); - WorkbookEvaluator workbookEvaluator = new WorkbookEvaluator(workbook, new IStabilityClassifier() { - - @Override - public boolean isCellFinal(int sheetIndex, int rowIndex, int columnIndex) { - return true; - } - }, null); - OperationEvaluationContext ctx = new OperationEvaluationContext(workbookEvaluator, - workbook, 0, 0, 0, null); - return ctx; - } - - public void testRefs() { - OperationEvaluationContext ctx = createContext(); - - ValueEval[] args = new ValueEval[] { ctx.getRefEval(0, 0) }; - ValueEval result = new Hex2Dec().evaluate(args, -1, -1); - - assertEquals(NumberEval.class, result.getClass()); - assertEquals("0", ((NumberEval) result).getStringValue()); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestIPMT.java b/src/testcases/org/apache/poi/ss/formula/functions/TestIPMT.java deleted file mode 100644 index 8ec8fbce6..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestIPMT.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.ss.formula.functions; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; - -import junit.framework.TestCase; - -/** - * Test cases for IPMT() - * - */ -public final class TestIPMT extends TestCase { - - - /** - * from http://office.microsoft.com/en-001/excel-help/ipmt-HP005209145.aspx - */ - public void testFromFile() { - - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("finance.xls"); - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - - HSSFSheet example1 = wb.getSheet("IPMT"); - HSSFCell ex1cell1 = example1.getRow(6).getCell(0); - fe.evaluate(ex1cell1); - assertEquals(-22.41, ex1cell1.getNumericCellValue(), 0.1); - - HSSFCell ex1cell2 = example1.getRow(7).getCell(0); - fe.evaluate(ex1cell2); - assertEquals(-292.45, ex1cell2.getNumericCellValue(), 0.1); - - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestImRealFunctionsFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/functions/TestImRealFunctionsFromSpreadsheet.java deleted file mode 100644 index 88f27a19e..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestImRealFunctionsFromSpreadsheet.java +++ /dev/null @@ -1,32 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import java.util.Collection; - -import org.junit.runners.Parameterized.Parameters; - -/** - * Tests ImReal() as loaded from a test data spreadsheet.

    - */ -public class TestImRealFunctionsFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - @Parameters(name="{0}") - public static Collection data() throws Exception { - return data(TestImRealFunctionsFromSpreadsheet.class, "ImRealFunctionTestCaseData.xls"); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestImaginaryFunctionsFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/functions/TestImaginaryFunctionsFromSpreadsheet.java deleted file mode 100644 index 7fe71ce62..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestImaginaryFunctionsFromSpreadsheet.java +++ /dev/null @@ -1,32 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import java.util.Collection; - -import org.junit.runners.Parameterized.Parameters; - -/** - * Tests Imaginary() as loaded from a test data spreadsheet.

    - */ -public class TestImaginaryFunctionsFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - @Parameters(name="{0}") - public static Collection data() throws Exception { - return data(TestImaginaryFunctionsFromSpreadsheet.class, "ImaginaryFunctionTestCaseData.xls"); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestIndex.java b/src/testcases/org/apache/poi/ss/formula/functions/TestIndex.java deleted file mode 100644 index ce0325285..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestIndex.java +++ /dev/null @@ -1,157 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import java.util.Arrays; - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -import org.apache.poi.ss.formula.eval.AreaEval; -import org.apache.poi.ss.formula.eval.MissingArgEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.ss.formula.WorkbookEvaluator; -import org.apache.poi.ss.util.CellRangeAddress; - -/** - * Tests for the INDEX() function.

    - * - * This class contains just a few specific cases that directly invoke {@link Index}, - * with minimum overhead.
    - * Another test: {@link TestIndexFunctionFromSpreadsheet} operates from a higher level - * and has far greater coverage of input permutations.
    - * - * @author Josh Micich - */ -public final class TestIndex extends TestCase { - - private static final Index FUNC_INST = new Index(); - private static final double[] TEST_VALUES0 = { - 1, 2, - 3, 4, - 5, 6, - 7, 8, - 9, 10, - 11, 12, - }; - - /** - * For the case when the first argument to INDEX() is an area reference - */ - public void testEvaluateAreaReference() { - - double[] values = TEST_VALUES0; - confirmAreaEval("C1:D6", values, 4, 1, 7); - confirmAreaEval("C1:D6", values, 6, 2, 12); - confirmAreaEval("C1:D6", values, 3, 1, 5); - - // now treat same data as 3 columns, 4 rows - confirmAreaEval("C10:E13", values, 2, 2, 5); - confirmAreaEval("C10:E13", values, 4, 1, 10); - } - - /** - * @param areaRefString in Excel notation e.g. 'D2:E97' - * @param dValues array of evaluated values for the area reference - * @param rowNum 1-based - * @param colNum 1-based, pass -1 to signify argument not present - */ - private static void confirmAreaEval(String areaRefString, double[] dValues, - int rowNum, int colNum, double expectedResult) { - ValueEval[] values = new ValueEval[dValues.length]; - for (int i = 0; i < values.length; i++) { - values[i] = new NumberEval(dValues[i]); - } - AreaEval arg0 = EvalFactory.createAreaEval(areaRefString, values); - - ValueEval[] args; - if (colNum > 0) { - args = new ValueEval[] { arg0, new NumberEval(rowNum), new NumberEval(colNum), }; - } else { - args = new ValueEval[] { arg0, new NumberEval(rowNum), }; - } - - double actual = invokeAndDereference(args); - assertEquals(expectedResult, actual, 0D); - } - - private static double invokeAndDereference(ValueEval[] args) { - ValueEval ve = FUNC_INST.evaluate(args, -1, -1); - ve = WorkbookEvaluator.dereferenceResult(ve, -1, -1); - assertEquals(NumberEval.class, ve.getClass()); - return ((NumberEval)ve).getNumberValue(); - } - - /** - * Tests expressions like "INDEX(A1:C1,,2)".
    - * This problem was found while fixing bug 47048 and is observable up to svn r773441. - */ - public void testMissingArg() { - ValueEval[] values = { - new NumberEval(25.0), - new NumberEval(26.0), - new NumberEval(28.0), - }; - AreaEval arg0 = EvalFactory.createAreaEval("A10:C10", values); - ValueEval[] args = new ValueEval[] { arg0, MissingArgEval.instance, new NumberEval(2), }; - ValueEval actualResult; - try { - actualResult = FUNC_INST.evaluate(args, -1, -1); - } catch (RuntimeException e) { - if (e.getMessage().equals("Unexpected arg eval type (org.apache.poi.hssf.record.formula.eval.MissingArgEval")) { - throw new AssertionFailedError("Identified bug 47048b - INDEX() should support missing-arg"); - } - throw e; - } - // result should be an area eval "B10:B10" - AreaEval ae = confirmAreaEval("B10:B10", actualResult); - actualResult = ae.getValue(0, 0); - assertEquals(NumberEval.class, actualResult.getClass()); - assertEquals(26.0, ((NumberEval)actualResult).getNumberValue(), 0.0); - } - - /** - * When the argument to INDEX is a reference, the result should be a reference - * A formula like "OFFSET(INDEX(A1:B2,2,1),1,1,1,1)" should return the value of cell B3. - * This works because the INDEX() function returns a reference to A2 (not the value of A2) - */ - public void testReferenceResult() { - ValueEval[] values = new ValueEval[4]; - Arrays.fill(values, NumberEval.ZERO); - AreaEval arg0 = EvalFactory.createAreaEval("A1:B2", values); - ValueEval[] args = new ValueEval[] { arg0, new NumberEval(2), new NumberEval(1), }; - ValueEval ve = FUNC_INST.evaluate(args, -1, -1); - confirmAreaEval("A2:A2", ve); - } - - /** - * Confirms that the result is an area ref with the specified coordinates - * @return ve cast to {@link AreaEval} if it is valid - */ - private static AreaEval confirmAreaEval(String refText, ValueEval ve) { - CellRangeAddress cra = CellRangeAddress.valueOf(refText); - assertTrue(ve instanceof AreaEval); - AreaEval ae = (AreaEval) ve; - assertEquals(cra.getFirstRow(), ae.getFirstRow()); - assertEquals(cra.getFirstColumn(), ae.getFirstColumn()); - assertEquals(cra.getLastRow(), ae.getLastRow()); - assertEquals(cra.getLastColumn(), ae.getLastColumn()); - return ae; - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestIndexFunctionFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/functions/TestIndexFunctionFromSpreadsheet.java deleted file mode 100644 index 0370b627d..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestIndexFunctionFromSpreadsheet.java +++ /dev/null @@ -1,32 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import java.util.Collection; - -import org.junit.runners.Parameterized.Parameters; - -/** - * Tests INDEX() as loaded from a test data spreadsheet.

    - */ -public final class TestIndexFunctionFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - @Parameters(name="{0}") - public static Collection data() throws Exception { - return data(TestIndexFunctionFromSpreadsheet.class, "IndexFunctionTestCaseData.xls"); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestIndirect.java b/src/testcases/org/apache/poi/ss/formula/functions/TestIndirect.java deleted file mode 100644 index 99d370bd6..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestIndirect.java +++ /dev/null @@ -1,213 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFName; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.junit.Test; - -/** - * Tests for the INDIRECT() function.

    - */ -public final class TestIndirect { - // convenient access to namespace - // private static final ErrorEval EE = null; - - private static void createDataRow(HSSFSheet sheet, int rowIndex, double... vals) { - HSSFRow row = sheet.createRow(rowIndex); - for (int i = 0; i < vals.length; i++) { - row.createCell(i).setCellValue(vals[i]); - } - } - - private static HSSFWorkbook createWBA() { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet1 = wb.createSheet("Sheet1"); - HSSFSheet sheet2 = wb.createSheet("Sheet2"); - HSSFSheet sheet3 = wb.createSheet("John's sales"); - - createDataRow(sheet1, 0, 11, 12, 13, 14); - createDataRow(sheet1, 1, 21, 22, 23, 24); - createDataRow(sheet1, 2, 31, 32, 33, 34); - - createDataRow(sheet2, 0, 50, 55, 60, 65); - createDataRow(sheet2, 1, 51, 56, 61, 66); - createDataRow(sheet2, 2, 52, 57, 62, 67); - - createDataRow(sheet3, 0, 30, 31, 32); - createDataRow(sheet3, 1, 33, 34, 35); - - HSSFName name1 = wb.createName(); - name1.setNameName("sales1"); - name1.setRefersToFormula("Sheet1!A1:D1"); - - HSSFName name2 = wb.createName(); - name2.setNameName("sales2"); - name2.setRefersToFormula("Sheet2!B1:C3"); - - HSSFRow row = sheet1.createRow(3); - row.createCell(0).setCellValue("sales1"); //A4 - row.createCell(1).setCellValue("sales2"); //B4 - - return wb; - } - - private static HSSFWorkbook createWBB() { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet1 = wb.createSheet("Sheet1"); - HSSFSheet sheet2 = wb.createSheet("Sheet2"); - HSSFSheet sheet3 = wb.createSheet("## Look here!"); - - createDataRow(sheet1, 0, 400, 440, 480, 520); - createDataRow(sheet1, 1, 420, 460, 500, 540); - - createDataRow(sheet2, 0, 50, 55, 60, 65); - createDataRow(sheet2, 1, 51, 56, 61, 66); - - createDataRow(sheet3, 0, 42); - - return wb; - } - - @Test - public void testBasic() throws Exception { - - HSSFWorkbook wbA = createWBA(); - HSSFCell c = wbA.getSheetAt(0).createRow(5).createCell(2); - HSSFFormulaEvaluator feA = new HSSFFormulaEvaluator(wbA); - - // non-error cases - confirm(feA, c, "INDIRECT(\"C2\")", 23); - confirm(feA, c, "INDIRECT(\"C2\", TRUE)", 23); - confirm(feA, c, "INDIRECT(\"$C2\")", 23); - confirm(feA, c, "INDIRECT(\"C$2\")", 23); - confirm(feA, c, "SUM(INDIRECT(\"Sheet2!B1:C3\"))", 351); // area ref - confirm(feA, c, "SUM(INDIRECT(\"Sheet2! B1 : C3 \"))", 351); // spaces in area ref - confirm(feA, c, "SUM(INDIRECT(\"'John''s sales'!A1:C1\"))", 93); // special chars in sheet name - confirm(feA, c, "INDIRECT(\"'Sheet1'!B3\")", 32); // redundant sheet name quotes - confirm(feA, c, "INDIRECT(\"sHeet1!B3\")", 32); // case-insensitive sheet name - confirm(feA, c, "INDIRECT(\" D3 \")", 34); // spaces around cell ref - confirm(feA, c, "INDIRECT(\"Sheet1! D3 \")", 34); // spaces around cell ref - confirm(feA, c, "INDIRECT(\"A1\", TRUE)", 11); // explicit arg1. only TRUE supported so far - - confirm(feA, c, "INDIRECT(\"A1:G1\")", 13); // de-reference area ref (note formula is in C4) - - confirm(feA, c, "SUM(INDIRECT(A4))", 50); // indirect defined name - confirm(feA, c, "SUM(INDIRECT(B4))", 351); // indirect defined name pointinh to other sheet - - // simple error propagation: - - // arg0 is evaluated to text first - confirm(feA, c, "INDIRECT(#DIV/0!)", ErrorEval.DIV_ZERO); - confirm(feA, c, "INDIRECT(#DIV/0!)", ErrorEval.DIV_ZERO); - confirm(feA, c, "INDIRECT(#NAME?, \"x\")", ErrorEval.NAME_INVALID); - confirm(feA, c, "INDIRECT(#NUM!, #N/A)", ErrorEval.NUM_ERROR); - - // arg1 is evaluated to boolean before arg0 is decoded - confirm(feA, c, "INDIRECT(\"garbage\", #N/A)", ErrorEval.NA); - confirm(feA, c, "INDIRECT(\"garbage\", \"\")", ErrorEval.VALUE_INVALID); // empty string is not valid boolean - confirm(feA, c, "INDIRECT(\"garbage\", \"flase\")", ErrorEval.VALUE_INVALID); // must be "TRUE" or "FALSE" - - - // spaces around sheet name (with or without quotes makes no difference) - confirm(feA, c, "INDIRECT(\"'Sheet1 '!D3\")", ErrorEval.REF_INVALID); - confirm(feA, c, "INDIRECT(\" Sheet1!D3\")", ErrorEval.REF_INVALID); - confirm(feA, c, "INDIRECT(\"'Sheet1' !D3\")", ErrorEval.REF_INVALID); - - - confirm(feA, c, "SUM(INDIRECT(\"'John's sales'!A1:C1\"))", ErrorEval.REF_INVALID); // bad quote escaping - confirm(feA, c, "INDIRECT(\"[Book1]Sheet1!A1\")", ErrorEval.REF_INVALID); // unknown external workbook - confirm(feA, c, "INDIRECT(\"Sheet3!A1\")", ErrorEval.REF_INVALID); // unknown sheet -// if (false) { // TODO - support evaluation of defined names -// confirm(feA, c, "INDIRECT(\"Sheet1!IW1\")", ErrorEval.REF_INVALID); // bad column -// confirm(feA, c, "INDIRECT(\"Sheet1!A65537\")", ErrorEval.REF_INVALID); // bad row -// } - confirm(feA, c, "INDIRECT(\"Sheet1!A 1\")", ErrorEval.REF_INVALID); // space in cell ref - - wbA.close(); - } - - @Test - public void testMultipleWorkbooks() throws Exception { - HSSFWorkbook wbA = createWBA(); - HSSFCell cellA = wbA.getSheetAt(0).createRow(10).createCell(0); - HSSFFormulaEvaluator feA = new HSSFFormulaEvaluator(wbA); - - HSSFWorkbook wbB = createWBB(); - HSSFCell cellB = wbB.getSheetAt(0).createRow(10).createCell(0); - HSSFFormulaEvaluator feB = new HSSFFormulaEvaluator(wbB); - - String[] workbookNames = { "MyBook", "Figures for January", }; - HSSFFormulaEvaluator[] evaluators = { feA, feB, }; - HSSFFormulaEvaluator.setupEnvironment(workbookNames, evaluators); - - confirm(feB, cellB, "INDIRECT(\"'[Figures for January]## Look here!'!A1\")", 42); // same wb - confirm(feA, cellA, "INDIRECT(\"'[Figures for January]## Look here!'!A1\")", 42); // across workbooks - - // 2 level recursion - confirm(feB, cellB, "INDIRECT(\"[MyBook]Sheet2!A1\")", 50); // set up (and check) first level - confirm(feA, cellA, "INDIRECT(\"'[Figures for January]Sheet1'!A11\")", 50); // points to cellB - - wbB.close(); - wbA.close(); - } - - private static void confirm(FormulaEvaluator fe, Cell cell, String formula, - double expectedResult) { - fe.clearAllCachedResultValues(); - cell.setCellFormula(formula); - CellValue cv = fe.evaluate(cell); - if (cv.getCellTypeEnum() != CellType.NUMERIC) { - fail("expected numeric cell type but got " + cv.formatAsString()); - } - assertEquals(expectedResult, cv.getNumberValue(), 0.0); - } - - private static void confirm(FormulaEvaluator fe, Cell cell, String formula, - ErrorEval expectedResult) { - fe.clearAllCachedResultValues(); - cell.setCellFormula(formula); - CellValue cv = fe.evaluate(cell); - if (cv.getCellTypeEnum() != CellType.ERROR) { - fail("expected error cell type but got " + cv.formatAsString()); - } - int expCode = expectedResult.getErrorCode(); - if (cv.getErrorValue() != expCode) { - fail("Expected error '" + ErrorEval.getText(expCode) - + "' but got '" + cv.formatAsString() + "'."); - } - } - - @Test - public void testInvalidInput() { - assertEquals(ErrorEval.VALUE_INVALID, Indirect.instance.evaluate(new ValueEval[] {}, null)); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestIndirectFunctionFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/functions/TestIndirectFunctionFromSpreadsheet.java deleted file mode 100644 index a78b5fd5e..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestIndirectFunctionFromSpreadsheet.java +++ /dev/null @@ -1,36 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import java.util.Collection; - -import org.junit.runners.Parameterized.Parameters; - -/** - * Tests INDIRECT() as loaded from a test data spreadsheet.

    - * - * Tests for bug fixes and specific/tricky behaviour can be found in the corresponding test class - * (TestXxxx) of the target (Xxxx) implementor, where execution can be observed - * more easily. - */ -public final class TestIndirectFunctionFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - @Parameters(name="{0}") - public static Collection data() throws Exception { - return data(TestIndirectFunctionFromSpreadsheet.class, "IndirectFunctionTestCaseData.xls"); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestIntercept.java b/src/testcases/org/apache/poi/ss/formula/functions/TestIntercept.java deleted file mode 100644 index 34b6d8579..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestIntercept.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.ss.formula.functions; - -import junit.framework.TestCase; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.ValueEval; -/** - * Test for Excel function INTERCEPT() - * - * @author Johan Karlsteen - */ -public final class TestIntercept extends TestCase { - private static final Function INTERCEPT = new Intercept(); - - private static ValueEval invoke(Function function, ValueEval xArray, ValueEval yArray) { - ValueEval[] args = new ValueEval[] { xArray, yArray, }; - return function.evaluate(args, -1, (short)-1); - } - - private void confirm(Function function, ValueEval xArray, ValueEval yArray, double expected) { - ValueEval result = invoke(function, xArray, yArray); - assertEquals(NumberEval.class, result.getClass()); - assertEquals(expected, ((NumberEval)result).getNumberValue(), 0); - } - private void confirmError(Function function, ValueEval xArray, ValueEval yArray, ErrorEval expectedError) { - ValueEval result = invoke(function, xArray, yArray); - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(expectedError.getErrorCode(), ((ErrorEval)result).getErrorCode()); - } - - private void confirmError(ValueEval xArray, ValueEval yArray, ErrorEval expectedError) { - confirmError(INTERCEPT, xArray, yArray, expectedError); - } - - public void testBasic() { - Double exp = Math.pow(10, 7.5); - ValueEval[] yValues = { - new NumberEval(3+exp), - new NumberEval(4+exp), - new NumberEval(2+exp), - new NumberEval(5+exp), - new NumberEval(4+exp), - new NumberEval(7+exp), - }; - ValueEval areaEvalY = createAreaEval(yValues); - - ValueEval[] xValues = { - new NumberEval(1), - new NumberEval(2), - new NumberEval(3), - new NumberEval(4), - new NumberEval(5), - new NumberEval(6), - }; - ValueEval areaEvalX = createAreaEval(xValues); - confirm(INTERCEPT, areaEvalX, areaEvalY, -24516534.39905822); - // Excel 2010 gives -24516534.3990583 - } - - /** - * number of items in array is not limited to 30 - */ - public void testLargeArrays() { - ValueEval[] yValues = createMockNumberArray(100, 3); // [1,2,0,1,2,0,...,0,1] - yValues[0] = new NumberEval(2.0); // Changes first element to 2 - ValueEval[] xValues = createMockNumberArray(100, 101); // [1,2,3,4,...,99,100] - - confirm(INTERCEPT, createAreaEval(xValues), createAreaEval(yValues), 51.74384236453202); - // Excel 2010 gives 51.74384236453200 - } - - private ValueEval[] createMockNumberArray(int size, double value) { - ValueEval[] result = new ValueEval[size]; - for (int i = 0; i < result.length; i++) { - result[i] = new NumberEval((i+1)%value); - } - return result; - } - - private static ValueEval createAreaEval(ValueEval[] values) { - String refStr = "A1:A" + values.length; - return EvalFactory.createAreaEval(refStr, values); - } - - public void testErrors() { - ValueEval[] xValues = { - ErrorEval.REF_INVALID, - new NumberEval(2), - }; - ValueEval areaEvalX = createAreaEval(xValues); - ValueEval[] yValues = { - new NumberEval(2), - ErrorEval.NULL_INTERSECTION, - }; - ValueEval areaEvalY = createAreaEval(yValues); - ValueEval[] zValues = { // wrong size - new NumberEval(2), - }; - ValueEval areaEvalZ = createAreaEval(zValues); - - // if either arg is an error, that error propagates - confirmError(ErrorEval.REF_INVALID, ErrorEval.NAME_INVALID, ErrorEval.REF_INVALID); - confirmError(areaEvalX, ErrorEval.NAME_INVALID, ErrorEval.NAME_INVALID); - confirmError(ErrorEval.NAME_INVALID, areaEvalX, ErrorEval.NAME_INVALID); - - // array sizes must match - confirmError(areaEvalX, areaEvalZ, ErrorEval.NA); - confirmError(areaEvalZ, areaEvalY, ErrorEval.NA); - - // any error in an array item propagates up - confirmError(areaEvalX, areaEvalX, ErrorEval.REF_INVALID); - - // search for errors array by array, not pair by pair - confirmError(areaEvalX, areaEvalY, ErrorEval.NULL_INTERSECTION); - confirmError(areaEvalY, areaEvalX, ErrorEval.REF_INVALID); - } - - /** - * Example from - * http://office.microsoft.com/en-us/excel-help/intercept-function-HP010062512.aspx?CTT=5&origin=HA010277524 - */ - public void testFromFile() { - - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("intercept.xls"); - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - - HSSFSheet example1 = wb.getSheet("Example 1"); - HSSFCell a8 = example1.getRow(7).getCell(0); - assertEquals("INTERCEPT(A2:A6,B2:B6)", a8.getCellFormula()); - fe.evaluate(a8); - assertEquals(0.048387097, a8.getNumericCellValue(), 0.000000001); - - } -} \ No newline at end of file diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestIrr.java b/src/testcases/org/apache/poi/ss/formula/functions/TestIrr.java deleted file mode 100644 index 40fac0dea..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestIrr.java +++ /dev/null @@ -1,134 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -/** - * Tests for {@link Irr} - * - * @author Marcel May - */ -public final class TestIrr extends TestCase { - - public void testIrr() { - // http://en.wikipedia.org/wiki/Internal_rate_of_return#Example - double[] incomes = {-4000d, 1200d, 1410d, 1875d, 1050d}; - double irr = Irr.irr(incomes); - double irrRounded = Math.round(irr * 1000d) / 1000d; - assertEquals("irr", 0.143d, irrRounded); - - // http://www.techonthenet.com/excel/formulas/irr.php - incomes = new double[]{-7500d, 3000d, 5000d, 1200d, 4000d}; - irr = Irr.irr(incomes); - irrRounded = Math.round(irr * 100d) / 100d; - assertEquals("irr", 0.28d, irrRounded); - - incomes = new double[]{-10000d, 3400d, 6500d, 1000d}; - irr = Irr.irr(incomes); - irrRounded = Math.round(irr * 100d) / 100d; - assertEquals("irr", 0.05, irrRounded); - - incomes = new double[]{100d, -10d, -110d}; - irr = Irr.irr(incomes); - irrRounded = Math.round(irr * 100d) / 100d; - assertEquals("irr", 0.1, irrRounded); - - incomes = new double[]{-70000d, 12000, 15000}; - irr = Irr.irr(incomes, -0.1); - irrRounded = Math.round(irr * 100d) / 100d; - assertEquals("irr", -0.44, irrRounded); - } - - public void testEvaluateInSheet() { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("Sheet1"); - HSSFRow row = sheet.createRow(0); - - row.createCell(0).setCellValue(-4000d); - row.createCell(1).setCellValue(1200d); - row.createCell(2).setCellValue(1410d); - row.createCell(3).setCellValue(1875d); - row.createCell(4).setCellValue(1050d); - - HSSFCell cell = row.createCell(5); - cell.setCellFormula("IRR(A1:E1)"); - - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - fe.clearAllCachedResultValues(); - fe.evaluateFormulaCellEnum(cell); - double res = cell.getNumericCellValue(); - assertEquals(0.143d, Math.round(res * 1000d) / 1000d); - } - - public void testIrrFromSpreadsheet(){ - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("IrrNpvTestCaseData.xls"); - HSSFSheet sheet = wb.getSheet("IRR-NPV"); - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - StringBuffer failures = new StringBuffer(); - int failureCount = 0; - // TODO YK: Formulas in rows 16 and 17 operate with ArrayPtg which isn't yet supported - // FormulaEvaluator as of r1041407 throws "Unexpected ptg class (org.apache.poi.ss.formula.ptg.ArrayPtg)" - for(int rownum = 9; rownum <= 15; rownum++){ - HSSFRow row = sheet.getRow(rownum); - HSSFCell cellA = row.getCell(0); - try { - CellValue cv = fe.evaluate(cellA); - assertFormulaResult(cv, cellA); - } catch (Throwable e){ - if(failures.length() > 0) failures.append('\n'); - failures.append("Row[" + (cellA.getRowIndex() + 1)+ "]: " + cellA.getCellFormula() + " "); - failures.append(e.getMessage()); - failureCount++; - } - - HSSFCell cellC = row.getCell(2); //IRR-NPV relationship: NPV(IRR(values), values) = 0 - try { - CellValue cv = fe.evaluate(cellC); - assertEquals(0, cv.getNumberValue(), 0.0001); // should agree within 0.01% - } catch (Throwable e){ - if(failures.length() > 0) failures.append('\n'); - failures.append("Row[" + (cellC.getRowIndex() + 1)+ "]: " + cellC.getCellFormula() + " "); - failures.append(e.getMessage()); - failureCount++; - } - } - - if(failures.length() > 0) { - throw new AssertionFailedError(failureCount + " IRR assertions failed:\n" + failures.toString()); - } - - } - - private static void assertFormulaResult(CellValue cv, HSSFCell cell){ - double actualValue = cv.getNumberValue(); - double expectedValue = cell.getNumericCellValue(); // cached formula result calculated by Excel - assertEquals("Invalid formula result: " + cv.toString(), CellType.NUMERIC, cv.getCellTypeEnum()); - assertEquals(expectedValue, actualValue, 1E-4); // should agree within 0.01% - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestIsBlank.java b/src/testcases/org/apache/poi/ss/formula/functions/TestIsBlank.java deleted file mode 100644 index e723711cc..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestIsBlank.java +++ /dev/null @@ -1,59 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; - -import junit.framework.TestCase; -/** - * Tests for Excel function ISBLANK() - * - * @author Josh Micich - */ -public final class TestIsBlank extends TestCase { - - public void test3DArea() { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet1 = wb.createSheet(); - wb.setSheetName(0, "Sheet1"); - wb.createSheet(); - wb.setSheetName(1, "Sheet2"); - HSSFRow row = sheet1.createRow(0); - HSSFCell cell = row.createCell(0); - - - cell.setCellFormula("isblank(Sheet2!A1:A1)"); - - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - CellValue result = fe.evaluate(cell); - assertEquals(CellType.BOOLEAN, result.getCellTypeEnum()); - assertEquals(true, result.getBooleanValue()); - - cell.setCellFormula("isblank(D7:D7)"); - - result = fe.evaluate(cell); - assertEquals(CellType.BOOLEAN, result.getCellTypeEnum()); - assertEquals(true, result.getBooleanValue()); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestLeftRight.java b/src/testcases/org/apache/poi/ss/formula/functions/TestLeftRight.java deleted file mode 100644 index 58160bdfe..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestLeftRight.java +++ /dev/null @@ -1,73 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; - -import junit.framework.TestCase; - -/** - * - * Test cases for {@link TextFunction#LEFT} and {@link TextFunction#RIGHT} - * - * @author Brendan Nolan - * - */ -public class TestLeftRight extends TestCase { - - private static final NumberEval NEGATIVE_OPERAND = new NumberEval(-1.0); - private static final StringEval ANY_STRING_VALUE = new StringEval("ANYSTRINGVALUE"); - - - private static ValueEval invokeLeft(ValueEval text, ValueEval operand) { - ValueEval[] args = new ValueEval[] { text, operand }; - return TextFunction.LEFT.evaluate(args, -1, (short)-1); - } - - private static ValueEval invokeRight(ValueEval text, ValueEval operand) { - ValueEval[] args = new ValueEval[] { text, operand }; - return TextFunction.RIGHT.evaluate(args, -1, (short)-1); - } - - public void testLeftRight_bug49841() { - - try { - invokeLeft(ANY_STRING_VALUE, NEGATIVE_OPERAND); - invokeRight(ANY_STRING_VALUE, NEGATIVE_OPERAND); - } catch (StringIndexOutOfBoundsException e) { - fail("Identified bug 49841"); - } - - } - - public void testLeftRightNegativeOperand() { - - assertEquals(ErrorEval.VALUE_INVALID, invokeRight(ANY_STRING_VALUE, NEGATIVE_OPERAND)); - assertEquals(ErrorEval.VALUE_INVALID, invokeLeft(ANY_STRING_VALUE, NEGATIVE_OPERAND)); - - } - - - - - - -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestLen.java b/src/testcases/org/apache/poi/ss/formula/functions/TestLen.java deleted file mode 100644 index a9a3d4cff..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestLen.java +++ /dev/null @@ -1,72 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import junit.framework.TestCase; - -import org.apache.poi.ss.formula.eval.BlankEval; -import org.apache.poi.ss.formula.eval.BoolEval; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; -/** - * Tests for Excel function LEN() - * - * @author Josh Micich - */ -public final class TestLen extends TestCase { - - private static ValueEval invokeLen(ValueEval text) { - ValueEval[] args = new ValueEval[] { text, }; - return TextFunction.LEN.evaluate(args, -1, (short)-1); - } - - private void confirmLen(ValueEval text, int expected) { - ValueEval result = invokeLen(text); - assertEquals(NumberEval.class, result.getClass()); - assertEquals(expected, ((NumberEval)result).getNumberValue(), 0); - } - - private void confirmLen(ValueEval text, ErrorEval expectedError) { - ValueEval result = invokeLen(text); - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(expectedError.getErrorCode(), ((ErrorEval)result).getErrorCode()); - } - - public void testBasic() { - - confirmLen(new StringEval("galactic"), 8); - } - - /** - * Valid cases where text arg is not exactly a string - */ - public void testUnusualArgs() { - - // text (first) arg type is number, other args are strings with fractional digits - confirmLen(new NumberEval(123456), 6); - confirmLen(BoolEval.FALSE, 5); - confirmLen(BoolEval.TRUE, 4); - confirmLen(BlankEval.instance, 0); - } - - public void testErrors() { - confirmLen(ErrorEval.NAME_INVALID, ErrorEval.NAME_INVALID); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestLogicalFunction.java b/src/testcases/org/apache/poi/ss/formula/functions/TestLogicalFunction.java deleted file mode 100644 index 1e48ced66..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestLogicalFunction.java +++ /dev/null @@ -1,107 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; -import org.apache.poi.ss.usermodel.FormulaEvaluator; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.CellReference; - -import junit.framework.TestCase; - -/** - * LogicalFunction unit tests. - */ -public class TestLogicalFunction extends TestCase { - - private FormulaEvaluator evaluator; - private Row row3; - private Cell cell1; - private Cell cell2; - - @Override - public void setUp() throws IOException { - Workbook wb = new HSSFWorkbook(); - try { - buildWorkbook(wb); - } finally { - wb.close(); - } - } - - private void buildWorkbook(Workbook wb) { - Sheet sh = wb.createSheet(); - Row row1 = sh.createRow(0); - Row row2 = sh.createRow(1); - row3 = sh.createRow(2); - - row1.createCell(0, CellType.NUMERIC); - row1.createCell(1, CellType.NUMERIC); - - row2.createCell(0, CellType.NUMERIC); - row2.createCell(1, CellType.NUMERIC); - - row3.createCell(0); - row3.createCell(1); - - CellReference a1 = new CellReference("A1"); - CellReference a2 = new CellReference("A2"); - CellReference b1 = new CellReference("B1"); - CellReference b2 = new CellReference("B2"); - - sh.getRow(a1.getRow()).getCell(a1.getCol()).setCellValue(35); - sh.getRow(a2.getRow()).getCell(a2.getCol()).setCellValue(0); - sh.getRow(b1.getRow()).getCell(b1.getCol()).setCellFormula("A1/A2"); - sh.getRow(b2.getRow()).getCell(b2.getCol()).setCellFormula("NA()"); - - evaluator = wb.getCreationHelper().createFormulaEvaluator(); - } - - public void testIsErr() { - cell1 = row3.createCell(0); - cell1.setCellFormula("ISERR(B1)"); // produces #DIV/0! - cell2 = row3.createCell(1); - cell2.setCellFormula("ISERR(B2)"); // produces #N/A - - CellValue cell1Value = evaluator.evaluate(cell1); - CellValue cell2Value = evaluator.evaluate(cell2); - - assertEquals(true, cell1Value.getBooleanValue()); - assertEquals(false, cell2Value.getBooleanValue()); - } - - public void testIsError() { - cell1 = row3.createCell(0); - cell1.setCellFormula("ISERROR(B1)"); // produces #DIV/0! - cell2 = row3.createCell(1); - cell2.setCellFormula("ISERROR(B2)"); // produces #N/A - - CellValue cell1Value = evaluator.evaluate(cell1); - CellValue cell2Value = evaluator.evaluate(cell2); - - assertEquals(true, cell1Value.getBooleanValue()); - assertEquals(true, cell2Value.getBooleanValue()); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestLookupFunctionsFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/functions/TestLookupFunctionsFromSpreadsheet.java deleted file mode 100644 index 6d95561d5..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestLookupFunctionsFromSpreadsheet.java +++ /dev/null @@ -1,38 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import java.util.Collection; - -import org.junit.runners.Parameterized.Parameters; - -/** - * Tests lookup functions (VLOOKUP, HLOOKUP, LOOKUP, MATCH) as loaded from a test data spreadsheet.

    - * These tests have been separated from the common function and operator tests because the lookup - * functions have more complex test cases and test data setup. - * - * Tests for bug fixes and specific/tricky behaviour can be found in the corresponding test class - * (TestXxxx) of the target (Xxxx) implementor, where execution can be observed - * more easily. - */ -public final class TestLookupFunctionsFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - @Parameters(name="{0}") - public static Collection data() throws Exception { - return data(TestLookupFunctionsFromSpreadsheet.class, "LookupFunctionsTestCaseData.xls"); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestMatch.java b/src/testcases/org/apache/poi/ss/formula/functions/TestMatch.java deleted file mode 100644 index 40731e21a..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestMatch.java +++ /dev/null @@ -1,278 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import org.apache.poi.ss.formula.eval.AreaEval; -import org.apache.poi.ss.formula.eval.BoolEval; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.NumericValueEval; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; - -import junit.framework.TestCase; - -/** - * Test cases for MATCH() - */ -public final class TestMatch extends TestCase { - /** less than or equal to */ - private static final NumberEval MATCH_LARGEST_LTE = new NumberEval(1); - private static final NumberEval MATCH_EXACT = new NumberEval(0); - /** greater than or equal to */ - private static final NumberEval MATCH_SMALLEST_GTE = new NumberEval(-1); - - private static final StringEval MATCH_INVALID = new StringEval("blabla"); - - private static ValueEval invokeMatch(ValueEval lookup_value, ValueEval lookup_array, ValueEval match_type) { - ValueEval[] args = { lookup_value, lookup_array, match_type, }; - return new Match().evaluate(args, -1, (short)-1); - } - - private static ValueEval invokeMatch(ValueEval lookup_value, ValueEval lookup_array) { - ValueEval[] args = { lookup_value, lookup_array, }; - return new Match().evaluate(args, -1, (short)-1); - } - - private static void confirmInt(int expected, ValueEval actualEval) { - if(!(actualEval instanceof NumericValueEval)) { - fail("Expected numeric result but had " + actualEval); - } - NumericValueEval nve = (NumericValueEval)actualEval; - assertEquals(expected, nve.getNumberValue(), 0); - } - - public void testSimpleNumber() { - - ValueEval[] values = { - new NumberEval(4), - new NumberEval(5), - new NumberEval(10), - new NumberEval(10), - new NumberEval(25), - }; - - AreaEval ae = EvalFactory.createAreaEval("A1:A5", values); - - confirmInt(2, invokeMatch(new NumberEval(5), ae, MATCH_LARGEST_LTE)); - confirmInt(2, invokeMatch(new NumberEval(5), ae)); - confirmInt(2, invokeMatch(new NumberEval(5), ae, MATCH_EXACT)); - confirmInt(4, invokeMatch(new NumberEval(10), ae, MATCH_LARGEST_LTE)); - confirmInt(3, invokeMatch(new NumberEval(10), ae, MATCH_EXACT)); - confirmInt(4, invokeMatch(new NumberEval(20), ae, MATCH_LARGEST_LTE)); - assertEquals(ErrorEval.NA, invokeMatch(new NumberEval(20), ae, MATCH_EXACT)); - } - - public void testReversedNumber() { - - ValueEval[] values = { - new NumberEval(25), - new NumberEval(10), - new NumberEval(10), - new NumberEval(10), - new NumberEval(4), - }; - - AreaEval ae = EvalFactory.createAreaEval("A1:A5", values); - - confirmInt(2, invokeMatch(new NumberEval(10), ae, MATCH_SMALLEST_GTE)); - confirmInt(2, invokeMatch(new NumberEval(10), ae, MATCH_EXACT)); - confirmInt(4, invokeMatch(new NumberEval(9), ae, MATCH_SMALLEST_GTE)); - confirmInt(1, invokeMatch(new NumberEval(20), ae, MATCH_SMALLEST_GTE)); - confirmInt(5, invokeMatch(new NumberEval(3), ae, MATCH_SMALLEST_GTE)); - assertEquals(ErrorEval.NA, invokeMatch(new NumberEval(20), ae, MATCH_EXACT)); - assertEquals(ErrorEval.NA, invokeMatch(new NumberEval(26), ae, MATCH_SMALLEST_GTE)); - } - - public void testSimpleString() { - // Arrange - ValueEval[] values = { - new StringEval("Albert"), - new StringEval("Charles"), - new StringEval("Ed"), - new StringEval("Greg"), - new StringEval("Ian"), - }; - - AreaEval ae = EvalFactory.createAreaEval("A1:A5", values); - - // Note String comparisons are case insensitive - confirmInt(3, invokeMatch(new StringEval("Ed"), ae, MATCH_LARGEST_LTE)); - confirmInt(3, invokeMatch(new StringEval("eD"), ae, MATCH_LARGEST_LTE)); - confirmInt(3, invokeMatch(new StringEval("Ed"), ae, MATCH_EXACT)); - confirmInt(3, invokeMatch(new StringEval("ed"), ae, MATCH_EXACT)); - - assertEquals(ErrorEval.NA, invokeMatch(new StringEval("Hugh"), ae, MATCH_EXACT)); - } - - public void testSimpleWildcardValuesString() { - // Arrange - ValueEval[] values = { - new StringEval("Albert"), - new StringEval("Charles"), - new StringEval("Ed"), - new StringEval("Greg"), - new StringEval("Ian"), - }; - - AreaEval ae = EvalFactory.createAreaEval("A1:A5", values); - - // Note String comparisons are case insensitive - confirmInt(3, invokeMatch(new StringEval("e*"), ae, MATCH_EXACT)); - confirmInt(3, invokeMatch(new StringEval("*d"), ae, MATCH_EXACT)); - - confirmInt(1, invokeMatch(new StringEval("Al*"), ae, MATCH_EXACT)); - confirmInt(2, invokeMatch(new StringEval("Char*"), ae, MATCH_EXACT)); - - confirmInt(4, invokeMatch(new StringEval("*eg"), ae, MATCH_EXACT)); - confirmInt(4, invokeMatch(new StringEval("G?eg"), ae, MATCH_EXACT)); - confirmInt(4, invokeMatch(new StringEval("??eg"), ae, MATCH_EXACT)); - confirmInt(4, invokeMatch(new StringEval("G*?eg"), ae, MATCH_EXACT)); - confirmInt(4, invokeMatch(new StringEval("Hugh"), ae, MATCH_LARGEST_LTE)); - - confirmInt(5, invokeMatch(new StringEval("*Ian*"), ae, MATCH_EXACT)); - confirmInt(5, invokeMatch(new StringEval("*Ian*"), ae, MATCH_LARGEST_LTE)); - } - - public void testTildeString() { - - ValueEval[] values = { - new StringEval("what?"), - new StringEval("all*") - }; - - AreaEval ae = EvalFactory.createAreaEval("A1:A2", values); - - confirmInt(1, invokeMatch(new StringEval("what~?"), ae, MATCH_EXACT)); - confirmInt(2, invokeMatch(new StringEval("all~*"), ae, MATCH_EXACT)); - } - - public void testSimpleBoolean() { - - ValueEval[] values = { - BoolEval.FALSE, - BoolEval.FALSE, - BoolEval.TRUE, - BoolEval.TRUE, - }; - - AreaEval ae = EvalFactory.createAreaEval("A1:A4", values); - - // Note String comparisons are case insensitive - confirmInt(2, invokeMatch(BoolEval.FALSE, ae, MATCH_LARGEST_LTE)); - confirmInt(1, invokeMatch(BoolEval.FALSE, ae, MATCH_EXACT)); - confirmInt(4, invokeMatch(BoolEval.TRUE, ae, MATCH_LARGEST_LTE)); - confirmInt(3, invokeMatch(BoolEval.TRUE, ae, MATCH_EXACT)); - } - - public void testHeterogeneous() { - - ValueEval[] values = { - new NumberEval(4), - BoolEval.FALSE, - new NumberEval(5), - new StringEval("Albert"), - BoolEval.FALSE, - BoolEval.TRUE, - new NumberEval(10), - new StringEval("Charles"), - new StringEval("Ed"), - new NumberEval(10), - new NumberEval(25), - BoolEval.TRUE, - new StringEval("Ed"), - }; - - AreaEval ae = EvalFactory.createAreaEval("A1:A13", values); - - assertEquals(ErrorEval.NA, invokeMatch(new StringEval("Aaron"), ae, MATCH_LARGEST_LTE)); - - confirmInt(5, invokeMatch(BoolEval.FALSE, ae, MATCH_LARGEST_LTE)); - confirmInt(2, invokeMatch(BoolEval.FALSE, ae, MATCH_EXACT)); - confirmInt(3, invokeMatch(new NumberEval(5), ae, MATCH_LARGEST_LTE)); - confirmInt(3, invokeMatch(new NumberEval(5), ae, MATCH_EXACT)); - - confirmInt(8, invokeMatch(new StringEval("CHARLES"), ae, MATCH_EXACT)); - //wildcard values - confirmInt(8, invokeMatch(new StringEval("CHAR*"), ae, MATCH_EXACT)); - confirmInt(8, invokeMatch(new StringEval("*CHARLES"), ae, MATCH_EXACT)); - - confirmInt(4, invokeMatch(new StringEval("Ben"), ae, MATCH_LARGEST_LTE)); - - confirmInt(13, invokeMatch(new StringEval("ED"), ae, MATCH_LARGEST_LTE)); - confirmInt(13, invokeMatch(new StringEval("ED*"), ae, MATCH_LARGEST_LTE)); - confirmInt(13, invokeMatch(new StringEval("*ED"), ae, MATCH_LARGEST_LTE)); - confirmInt(9, invokeMatch(new StringEval("ED"), ae, MATCH_EXACT)); - confirmInt(9, invokeMatch(new StringEval("ED*"), ae, MATCH_EXACT)); - - confirmInt(13, invokeMatch(new StringEval("Hugh"), ae, MATCH_LARGEST_LTE)); - assertEquals(ErrorEval.NA, invokeMatch(new StringEval("Hugh"), ae, MATCH_EXACT)); - - confirmInt(11, invokeMatch(new NumberEval(30), ae, MATCH_LARGEST_LTE)); - confirmInt(12, invokeMatch(BoolEval.TRUE, ae, MATCH_LARGEST_LTE)); - } - - - /** - * Ensures that the match_type argument can be an AreaEval.
    - * Bugzilla 44421 - */ - public void testMatchArgTypeArea() { - - ValueEval[] values = { - new NumberEval(4), - new NumberEval(5), - new NumberEval(10), - new NumberEval(10), - new NumberEval(25), - }; - - AreaEval ae = EvalFactory.createAreaEval("A1:A5", values); - - AreaEval matchAE = EvalFactory.createAreaEval("C1:C1", new ValueEval[] { MATCH_LARGEST_LTE, }); - - try { - confirmInt(4, invokeMatch(new NumberEval(10), ae, matchAE)); - } catch (RuntimeException e) { - if(e.getMessage().startsWith("Unexpected match_type type")) { - // identified bug 44421 - fail(e.getMessage()); - } - // some other error ?? - throw e; - } - } - - public void testInvalidMatchType() { - - ValueEval[] values = { - new NumberEval(4), - new NumberEval(5), - new NumberEval(10), - new NumberEval(10), - new NumberEval(25), - }; - - AreaEval ae = EvalFactory.createAreaEval("A1:A5", values); - - confirmInt(2, invokeMatch(new NumberEval(5), ae, MATCH_LARGEST_LTE)); - - assertEquals("Should return #REF! for invalid match type", - ErrorEval.REF_INVALID, invokeMatch(new StringEval("Ben"), ae, MATCH_INVALID)); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestMatchFunctionsFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/functions/TestMatchFunctionsFromSpreadsheet.java deleted file mode 100644 index df3b52595..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestMatchFunctionsFromSpreadsheet.java +++ /dev/null @@ -1,36 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import java.util.Collection; - -import org.junit.runners.Parameterized.Parameters; - -/** - * Tests Match functions as loaded from a test data spreadsheet.

    - * - * Tests for bug fixes and specific/tricky behaviour can be found in the corresponding test class - * (TestXxxx) of the target (Xxxx) implementor, where execution can be observed - * more easily. - */ -public final class TestMatchFunctionsFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - @Parameters(name="{0}") - public static Collection data() throws Exception { - return data(TestMatchFunctionsFromSpreadsheet.class, "MatchFunctionTestCaseData.xls"); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestMathX.java b/src/testcases/org/apache/poi/ss/formula/functions/TestMathX.java deleted file mode 100644 index 18268068f..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestMathX.java +++ /dev/null @@ -1,948 +0,0 @@ -/* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -/* - * Created on May 23, 2005 - * - */ -package org.apache.poi.ss.formula.functions; - -import org.apache.poi.ss.formula.functions.XYNumericFunction.Accumulator; - - -/** - * @author Amol S. Deshmukh < amolweb at ya hoo dot com > - * - */ -public class TestMathX extends AbstractNumericTestCase { - - public void testAcosh() { - double d = 0; - - d = MathX.acosh(0); - assertTrue("Acosh 0 is NaN", Double.isNaN(d)); - - d = MathX.acosh(1); - assertEquals("Acosh 1 ", 0, d); - - d = MathX.acosh(-1); - assertTrue("Acosh -1 is NaN", Double.isNaN(d)); - - d = MathX.acosh(100); - assertEquals("Acosh 100 ", 5.298292366d, d); - - d = MathX.acosh(101.001); - assertEquals("Acosh 101.001 ", 5.308253091d, d); - - d = MathX.acosh(200000); - assertEquals("Acosh 200000 ", 12.89921983d, d); - - } - - public void testAsinh() { - double d = 0; - - d = MathX.asinh(0); - assertEquals("asinh 0", d, 0); - - d = MathX.asinh(1); - assertEquals("asinh 1 ", 0.881373587, d); - - d = MathX.asinh(-1); - assertEquals("asinh -1 ", -0.881373587, d); - - d = MathX.asinh(-100); - assertEquals("asinh -100 ", -5.298342366, d); - - d = MathX.asinh(100); - assertEquals("asinh 100 ", 5.298342366, d); - - d = MathX.asinh(200000); - assertEquals("asinh 200000", 12.899219826096400, d); - - d = MathX.asinh(-200000); - assertEquals("asinh -200000 ", -12.899223853137, d); - - } - - public void testAtanh() { - double d = 0; - d = MathX.atanh(0); - assertEquals("atanh 0", d, 0); - - d = MathX.atanh(1); - assertEquals("atanh 1 ", Double.POSITIVE_INFINITY, d); - - d = MathX.atanh(-1); - assertEquals("atanh -1 ", Double.NEGATIVE_INFINITY, d); - - d = MathX.atanh(-100); - assertEquals("atanh -100 ", Double.NaN, d); - - d = MathX.atanh(100); - assertEquals("atanh 100 ", Double.NaN, d); - - d = MathX.atanh(200000); - assertEquals("atanh 200000", Double.NaN, d); - - d = MathX.atanh(-200000); - assertEquals("atanh -200000 ", Double.NaN, d); - - d = MathX.atanh(0.1); - assertEquals("atanh 0.1", 0.100335348, d); - - d = MathX.atanh(-0.1); - assertEquals("atanh -0.1 ", -0.100335348, d); - - } - - public void testCosh() { - double d = 0; - d = MathX.cosh(0); - assertEquals("cosh 0", 1, d); - - d = MathX.cosh(1); - assertEquals("cosh 1 ", 1.543080635, d); - - d = MathX.cosh(-1); - assertEquals("cosh -1 ", 1.543080635, d); - - d = MathX.cosh(-100); - assertEquals("cosh -100 ", 1.344058570908070E+43, d); - - d = MathX.cosh(100); - assertEquals("cosh 100 ", 1.344058570908070E+43, d); - - d = MathX.cosh(15); - assertEquals("cosh 15", 1634508.686, d); - - d = MathX.cosh(-15); - assertEquals("cosh -15 ", 1634508.686, d); - - d = MathX.cosh(0.1); - assertEquals("cosh 0.1", 1.005004168, d); - - d = MathX.cosh(-0.1); - assertEquals("cosh -0.1 ", 1.005004168, d); - - } - - public void testTanh() { - double d = 0; - d = MathX.tanh(0); - assertEquals("tanh 0", 0, d); - - d = MathX.tanh(1); - assertEquals("tanh 1 ", 0.761594156, d); - - d = MathX.tanh(-1); - assertEquals("tanh -1 ", -0.761594156, d); - - d = MathX.tanh(-100); - assertEquals("tanh -100 ", -1, d); - - d = MathX.tanh(100); - assertEquals("tanh 100 ", 1, d); - - d = MathX.tanh(15); - assertEquals("tanh 15", 1, d); - - d = MathX.tanh(-15); - assertEquals("tanh -15 ", -1, d); - - d = MathX.tanh(0.1); - assertEquals("tanh 0.1", 0.099667995, d); - - d = MathX.tanh(-0.1); - assertEquals("tanh -0.1 ", -0.099667995, d); - - } - - public void testMax() { - double[] d = new double[100]; - d[0] = 1.1; d[1] = 2.1; d[2] = 3.1; d[3] = 4.1; - d[4] = 5.1; d[5] = 6.1; d[6] = 7.1; d[7] = 8.1; - d[8] = 9.1; d[9] = 10.1; d[10] = 11.1; d[11] = 12.1; - d[12] = 13.1; d[13] = 14.1; d[14] = 15.1; d[15] = 16.1; - d[16] = 17.1; d[17] = 18.1; d[18] = 19.1; d[19] = 20.1; - - double m = MathX.max(d); - assertEquals("Max ", 20.1, m); - - d = new double[1000]; - m = MathX.max(d); - assertEquals("Max ", 0, m); - - d[0] = -1.1; d[1] = 2.1; d[2] = -3.1; d[3] = 4.1; - d[4] = -5.1; d[5] = 6.1; d[6] = -7.1; d[7] = 8.1; - d[8] = -9.1; d[9] = 10.1; d[10] = -11.1; d[11] = 12.1; - d[12] = -13.1; d[13] = 14.1; d[14] = -15.1; d[15] = 16.1; - d[16] = -17.1; d[17] = 18.1; d[18] = -19.1; d[19] = 20.1; - m = MathX.max(d); - assertEquals("Max ", 20.1, m); - - d = new double[20]; - d[0] = -1.1; d[1] = -2.1; d[2] = -3.1; d[3] = -4.1; - d[4] = -5.1; d[5] = -6.1; d[6] = -7.1; d[7] = -8.1; - d[8] = -9.1; d[9] = -10.1; d[10] = -11.1; d[11] = -12.1; - d[12] = -13.1; d[13] = -14.1; d[14] = -15.1; d[15] = -16.1; - d[16] = -17.1; d[17] = -18.1; d[18] = -19.1; d[19] = -20.1; - m = MathX.max(d); - assertEquals("Max ", -1.1, m); - - } - - public void testMin() { - double[] d = new double[100]; - d[0] = 1.1; d[1] = 2.1; d[2] = 3.1; d[3] = 4.1; - d[4] = 5.1; d[5] = 6.1; d[6] = 7.1; d[7] = 8.1; - d[8] = 9.1; d[9] = 10.1; d[10] = 11.1; d[11] = 12.1; - d[12] = 13.1; d[13] = 14.1; d[14] = 15.1; d[15] = 16.1; - d[16] = 17.1; d[17] = 18.1; d[18] = 19.1; d[19] = 20.1; - - double m = MathX.min(d); - assertEquals("Min ", 0, m); - - d = new double[20]; - d[0] = 1.1; d[1] = 2.1; d[2] = 3.1; d[3] = 4.1; - d[4] = 5.1; d[5] = 6.1; d[6] = 7.1; d[7] = 8.1; - d[8] = 9.1; d[9] = 10.1; d[10] = 11.1; d[11] = 12.1; - d[12] = 13.1; d[13] = 14.1; d[14] = 15.1; d[15] = 16.1; - d[16] = 17.1; d[17] = 18.1; d[18] = 19.1; d[19] = 20.1; - - m = MathX.min(d); - assertEquals("Min ", 1.1, m); - - d = new double[1000]; - m = MathX.min(d); - assertEquals("Min ", 0, m); - - d[0] = -1.1; d[1] = 2.1; d[2] = -3.1; d[3] = 4.1; - d[4] = -5.1; d[5] = 6.1; d[6] = -7.1; d[7] = 8.1; - d[8] = -9.1; d[9] = 10.1; d[10] = -11.1; d[11] = 12.1; - d[12] = -13.1; d[13] = 14.1; d[14] = -15.1; d[15] = 16.1; - d[16] = -17.1; d[17] = 18.1; d[18] = -19.1; d[19] = 20.1; - m = MathX.min(d); - assertEquals("Min ", -19.1, m); - - d = new double[20]; - d[0] = -1.1; d[1] = -2.1; d[2] = -3.1; d[3] = -4.1; - d[4] = -5.1; d[5] = -6.1; d[6] = -7.1; d[7] = -8.1; - d[8] = -9.1; d[9] = -10.1; d[10] = -11.1; d[11] = -12.1; - d[12] = -13.1; d[13] = -14.1; d[14] = -15.1; d[15] = -16.1; - d[16] = -17.1; d[17] = -18.1; d[18] = -19.1; d[19] = -20.1; - m = MathX.min(d); - assertEquals("Min ", -20.1, m); - } - - public void testProduct() { - assertEquals("Product ", 0, MathX.product(null)); - assertEquals("Product ", 0, MathX.product(new double[] {})); - assertEquals("Product ", 0, MathX.product(new double[] {1, 0})); - - assertEquals("Product ", 1, MathX.product(new double[] { 1 })); - assertEquals("Product ", 1, MathX.product(new double[] { 1, 1 })); - assertEquals("Product ", 10, MathX.product(new double[] { 10, 1 })); - assertEquals("Product ", -2, MathX.product(new double[] { 2, -1 })); - assertEquals("Product ", 99988000209999d, MathX.product(new double[] { 99999, 99999, 9999 })); - - double[] d = new double[100]; - d[0] = 1.1; d[1] = 2.1; d[2] = 3.1; d[3] = 4.1; - d[4] = 5.1; d[5] = 6.1; d[6] = 7.1; d[7] = 8.1; - d[8] = 9.1; d[9] = 10.1; d[10] = 11.1; d[11] = 12.1; - d[12] = 13.1; d[13] = 14.1; d[14] = 15.1; d[15] = 16.1; - d[16] = 17.1; d[17] = 18.1; d[18] = 19.1; d[19] = 20.1; - - double m = MathX.product(d); - assertEquals("Product ", 0, m); - - d = new double[20]; - d[0] = 1.1; d[1] = 2.1; d[2] = 3.1; d[3] = 4.1; - d[4] = 5.1; d[5] = 6.1; d[6] = 7.1; d[7] = 8.1; - d[8] = 9.1; d[9] = 10.1; d[10] = 11.1; d[11] = 12.1; - d[12] = 13.1; d[13] = 14.1; d[14] = 15.1; d[15] = 16.1; - d[16] = 17.1; d[17] = 18.1; d[18] = 19.1; d[19] = 20.1; - - m = MathX.product(d); - assertEquals("Product ", 3459946360003355534d, m); - - d = new double[1000]; - m = MathX.product(d); - assertEquals("Product ", 0, m); - - d = new double[20]; - d[0] = -1.1; d[1] = -2.1; d[2] = -3.1; d[3] = -4.1; - d[4] = -5.1; d[5] = -6.1; d[6] = -7.1; d[7] = -8.1; - d[8] = -9.1; d[9] = -10.1; d[10] = -11.1; d[11] = -12.1; - d[12] = -13.1; d[13] = -14.1; d[14] = -15.1; d[15] = -16.1; - d[16] = -17.1; d[17] = -18.1; d[18] = -19.1; d[19] = -20.1; - m = MathX.product(d); - assertEquals("Product ", 3459946360003355534d, m); - } - - public void testMod() { - - //example from Excel help - assertEquals(1.0, MathX.mod(3, 2)); - assertEquals(1.0, MathX.mod(-3, 2)); - assertEquals(-1.0, MathX.mod(3, -2)); - assertEquals(-1.0, MathX.mod(-3, -2)); - - assertEquals(0.0, MathX.mod(0, 2)); - assertEquals(Double.NaN, MathX.mod(3, 0)); - assertEquals(1.4, MathX.mod(3.4, 2)); - assertEquals(-1.4, MathX.mod(-3.4, -2)); - assertEquals(0.6000000000000001, MathX.mod(-3.4, 2.0));// should actually be 0.6 - assertEquals(-0.6000000000000001, MathX.mod(3.4, -2.0));// should actually be -0.6 - assertEquals(3.0, MathX.mod(3, Double.MAX_VALUE)); - assertEquals(2.0, MathX.mod(Double.MAX_VALUE, 3)); - - // Bugzilla 50033 - assertEquals(1.0, MathX.mod(13, 12)); - } - - public void testNChooseK() { - int n=100; - int k=50; - double d = MathX.nChooseK(n, k); - assertEquals("NChooseK ", 1.00891344545564E29, d); - - n = -1; k = 1; - d = MathX.nChooseK(n, k); - assertEquals("NChooseK ", Double.NaN, d); - - n = 1; k = -1; - d = MathX.nChooseK(n, k); - assertEquals("NChooseK ", Double.NaN, d); - - n = 0; k = 1; - d = MathX.nChooseK(n, k); - assertEquals("NChooseK ", Double.NaN, d); - - n = 1; k = 0; - d = MathX.nChooseK(n, k); - assertEquals("NChooseK ", 1, d); - - n = 10; k = 9; - d = MathX.nChooseK(n, k); - assertEquals("NChooseK ", 10, d); - - n = 10; k = 10; - d = MathX.nChooseK(n, k); - assertEquals("NChooseK ", 1, d); - - n = 10; k = 1; - d = MathX.nChooseK(n, k); - assertEquals("NChooseK ", 10, d); - - n = 1000; k = 1; - d = MathX.nChooseK(n, k); - assertEquals("NChooseK ", 1000, d); // awesome ;) - - n = 1000; k = 2; - d = MathX.nChooseK(n, k); - assertEquals("NChooseK ", 499500, d); // awesome ;) - - n = 13; k = 7; - d = MathX.nChooseK(n, k); - assertEquals("NChooseK ", 1716, d); - - } - - public void testSign() { - final short minus = -1; - final short zero = 0; - final short plus = 1; - double d = 0; - - - assertEquals("Sign ", minus, MathX.sign(minus)); - assertEquals("Sign ", plus, MathX.sign(plus)); - assertEquals("Sign ", zero, MathX.sign(zero)); - - d = 0; - assertEquals("Sign ", zero, MathX.sign(d)); - - d = -1.000001; - assertEquals("Sign ", minus, MathX.sign(d)); - - d = -.000001; - assertEquals("Sign ", minus, MathX.sign(d)); - - d = -1E-200; - assertEquals("Sign ", minus, MathX.sign(d)); - - d = Double.NEGATIVE_INFINITY; - assertEquals("Sign ", minus, MathX.sign(d)); - - d = -200.11; - assertEquals("Sign ", minus, MathX.sign(d)); - - d = -2000000000000.11; - assertEquals("Sign ", minus, MathX.sign(d)); - - d = 1.000001; - assertEquals("Sign ", plus, MathX.sign(d)); - - d = .000001; - assertEquals("Sign ", plus, MathX.sign(d)); - - d = 1E-200; - assertEquals("Sign ", plus, MathX.sign(d)); - - d = Double.POSITIVE_INFINITY; - assertEquals("Sign ", plus, MathX.sign(d)); - - d = 200.11; - assertEquals("Sign ", plus, MathX.sign(d)); - - d = 2000000000000.11; - assertEquals("Sign ", plus, MathX.sign(d)); - - } - - public void testSinh() { - double d = 0; - d = MathX.sinh(0); - assertEquals("sinh 0", 0, d); - - d = MathX.sinh(1); - assertEquals("sinh 1 ", 1.175201194, d); - - d = MathX.sinh(-1); - assertEquals("sinh -1 ", -1.175201194, d); - - d = MathX.sinh(-100); - assertEquals("sinh -100 ", -1.344058570908070E+43, d); - - d = MathX.sinh(100); - assertEquals("sinh 100 ", 1.344058570908070E+43, d); - - d = MathX.sinh(15); - assertEquals("sinh 15", 1634508.686, d); - - d = MathX.sinh(-15); - assertEquals("sinh -15 ", -1634508.686, d); - - d = MathX.sinh(0.1); - assertEquals("sinh 0.1", 0.10016675, d); - - d = MathX.sinh(-0.1); - assertEquals("sinh -0.1 ", -0.10016675, d); - - } - - public void testSum() { - double[] d = new double[100]; - d[0] = 1.1; d[1] = 2.1; d[2] = 3.1; d[3] = 4.1; - d[4] = 5.1; d[5] = 6.1; d[6] = 7.1; d[7] = 8.1; - d[8] = 9.1; d[9] = 10.1; d[10] = 11.1; d[11] = 12.1; - d[12] = 13.1; d[13] = 14.1; d[14] = 15.1; d[15] = 16.1; - d[16] = 17.1; d[17] = 18.1; d[18] = 19.1; d[19] = 20.1; - - double s = MathX.sum(d); - assertEquals("Sum ", 212, s); - - d = new double[1000]; - s = MathX.sum(d); - assertEquals("Sum ", 0, s); - - d[0] = -1.1; d[1] = 2.1; d[2] = -3.1; d[3] = 4.1; - d[4] = -5.1; d[5] = 6.1; d[6] = -7.1; d[7] = 8.1; - d[8] = -9.1; d[9] = 10.1; d[10] = -11.1; d[11] = 12.1; - d[12] = -13.1; d[13] = 14.1; d[14] = -15.1; d[15] = 16.1; - d[16] = -17.1; d[17] = 18.1; d[18] = -19.1; d[19] = 20.1; - s = MathX.sum(d); - assertEquals("Sum ", 10, s); - - d[0] = -1.1; d[1] = -2.1; d[2] = -3.1; d[3] = -4.1; - d[4] = -5.1; d[5] = -6.1; d[6] = -7.1; d[7] = -8.1; - d[8] = -9.1; d[9] = -10.1; d[10] = -11.1; d[11] = -12.1; - d[12] = -13.1; d[13] = -14.1; d[14] = -15.1; d[15] = -16.1; - d[16] = -17.1; d[17] = -18.1; d[18] = -19.1; d[19] = -20.1; - s = MathX.sum(d); - assertEquals("Sum ", -212, s); - - } - - public void testSumsq() { - double[] d = new double[100]; - d[0] = 1.1; d[1] = 2.1; d[2] = 3.1; d[3] = 4.1; - d[4] = 5.1; d[5] = 6.1; d[6] = 7.1; d[7] = 8.1; - d[8] = 9.1; d[9] = 10.1; d[10] = 11.1; d[11] = 12.1; - d[12] = 13.1; d[13] = 14.1; d[14] = 15.1; d[15] = 16.1; - d[16] = 17.1; d[17] = 18.1; d[18] = 19.1; d[19] = 20.1; - - double s = MathX.sumsq(d); - assertEquals("Sumsq ", 2912.2, s); - - d = new double[1000]; - s = MathX.sumsq(d); - assertEquals("Sumsq ", 0, s); - - d[0] = -1.1; d[1] = 2.1; d[2] = -3.1; d[3] = 4.1; - d[4] = -5.1; d[5] = 6.1; d[6] = -7.1; d[7] = 8.1; - d[8] = -9.1; d[9] = 10.1; d[10] = -11.1; d[11] = 12.1; - d[12] = -13.1; d[13] = 14.1; d[14] = -15.1; d[15] = 16.1; - d[16] = -17.1; d[17] = 18.1; d[18] = -19.1; d[19] = 20.1; - s = MathX.sumsq(d); - assertEquals("Sumsq ", 2912.2, s); - - d[0] = -1.1; d[1] = -2.1; d[2] = -3.1; d[3] = -4.1; - d[4] = -5.1; d[5] = -6.1; d[6] = -7.1; d[7] = -8.1; - d[8] = -9.1; d[9] = -10.1; d[10] = -11.1; d[11] = -12.1; - d[12] = -13.1; d[13] = -14.1; d[14] = -15.1; d[15] = -16.1; - d[16] = -17.1; d[17] = -18.1; d[18] = -19.1; d[19] = -20.1; - s = MathX.sumsq(d); - assertEquals("Sumsq ", 2912.2, s); - } - - public void testFactorial() { - int n = 0; - double s = 0; - - n = 0; - s = MathX.factorial(n); - assertEquals("Factorial ", 1, s); - - n = 1; - s = MathX.factorial(n); - assertEquals("Factorial ", 1, s); - - n = 10; - s = MathX.factorial(n); - assertEquals("Factorial ", 3628800, s); - - n = 99; - s = MathX.factorial(n); - assertEquals("Factorial ", 9.33262154439E+155, s); - - n = -1; - s = MathX.factorial(n); - assertEquals("Factorial ", Double.NaN, s); - - n = Integer.MAX_VALUE; - s = MathX.factorial(n); - assertEquals("Factorial ", Double.POSITIVE_INFINITY, s); - } - - public void testSumx2my2() { - double[] xarr = null; - double[] yarr = null; - - xarr = new double[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - yarr = new double[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; - confirmSumx2my2(xarr, yarr, 100); - - xarr = new double[]{-1, -2, -3, -4, -5, -6, -7, -8, -9, -10}; - yarr = new double[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; - confirmSumx2my2(xarr, yarr, 100); - - xarr = new double[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; - yarr = new double[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - confirmSumx2my2(xarr, yarr, -100); - - xarr = new double[]{10}; - yarr = new double[]{9}; - confirmSumx2my2(xarr, yarr, 19); - - xarr = new double[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - yarr = new double[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - confirmSumx2my2(xarr, yarr, 0); - } - - public void testSumx2py2() { - double[] xarr = null; - double[] yarr = null; - - xarr = new double[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - yarr = new double[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; - confirmSumx2py2(xarr, yarr, 670); - - xarr = new double[]{-1, -2, -3, -4, -5, -6, -7, -8, -9, -10}; - yarr = new double[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; - confirmSumx2py2(xarr, yarr, 670); - - xarr = new double[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; - yarr = new double[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - confirmSumx2py2(xarr, yarr, 670); - - xarr = new double[]{10}; - yarr = new double[]{9}; - confirmSumx2py2(xarr, yarr, 181); - - xarr = new double[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - yarr = new double[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - confirmSumx2py2(xarr, yarr, 770); - } - - public void testSumxmy2() { - double[] xarr = null; - double[] yarr = null; - - xarr = new double[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - yarr = new double[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; - confirmSumxmy2(xarr, yarr, 10); - - xarr = new double[]{-1, -2, -3, -4, -5, -6, -7, -8, -9, -10}; - yarr = new double[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; - confirmSumxmy2(xarr, yarr, 1330); - - xarr = new double[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; - yarr = new double[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - confirmSumxmy2(xarr, yarr, 10); - - xarr = new double[]{10}; - yarr = new double[]{9}; - confirmSumxmy2(xarr, yarr, 1); - - xarr = new double[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - yarr = new double[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - confirmSumxmy2(xarr, yarr, 0); - } - - private static void confirmSumx2my2(double[] xarr, double[] yarr, double expectedResult) { - confirmXY(new Sumx2my2().createAccumulator(), xarr, yarr, expectedResult); - } - private static void confirmSumx2py2(double[] xarr, double[] yarr, double expectedResult) { - confirmXY(new Sumx2py2().createAccumulator(), xarr, yarr, expectedResult); - } - private static void confirmSumxmy2(double[] xarr, double[] yarr, double expectedResult) { - confirmXY(new Sumxmy2().createAccumulator(), xarr, yarr, expectedResult); - } - - private static void confirmXY(Accumulator acc, double[] xarr, double[] yarr, - double expectedResult) { - double result = 0.0; - for (int i = 0; i < xarr.length; i++) { - result += acc.accumulate(xarr[i], yarr[i]); - } - assertEquals(expectedResult, result, 0.0); - } - - public void testRound() { - double d = 0; - int p = 0; - - d = 0; p = 0; - assertEquals("round ", 0, MathX.round(d, p)); - - d = 10; p = 0; - assertEquals("round ", 10, MathX.round(d, p)); - - d = 123.23; p = 0; - assertEquals("round ", 123, MathX.round(d, p)); - - d = -123.23; p = 0; - assertEquals("round ", -123, MathX.round(d, p)); - - d = 123.12; p = 2; - assertEquals("round ", 123.12, MathX.round(d, p)); - - d = 88.123459; p = 5; - assertEquals("round ", 88.12346, MathX.round(d, p)); - - d = 0; p = 2; - assertEquals("round ", 0, MathX.round(d, p)); - - d = 0; p = -1; - assertEquals("round ", 0, MathX.round(d, p)); - - d = 0.01; p = -1; - assertEquals("round ", 0, MathX.round(d, p)); - - d = 123.12; p = -2; - assertEquals("round ", 100, MathX.round(d, p)); - - d = 88.123459; p = -3; - assertEquals("round ", 0, MathX.round(d, p)); - - d = 49.00000001; p = -1; - assertEquals("round ", 50, MathX.round(d, p)); - - d = 149.999999; p = -2; - assertEquals("round ", 100, MathX.round(d, p)); - - d = 150.0; p = -2; - assertEquals("round ", 200, MathX.round(d, p)); - - d = 2162.615d; p = 2; - assertEquals("round ", 2162.62d, MathX.round(d, p)); - - d = 0.049999999999999975d; p = 2; - assertEquals("round ", 0.05d, MathX.round(d, p)); - - d = 0.049999999999999975d; p = 1; - assertEquals("round ", 0.1d, MathX.round(d, p)); - - d = Double.NaN; p = 1; - assertEquals("round ", Double.NaN, MathX.round(d, p)); - - d = Double.POSITIVE_INFINITY; p = 1; - assertEquals("round ", Double.NaN, MathX.round(d, p)); - - d = Double.NEGATIVE_INFINITY; p = 1; - assertEquals("round ", Double.NaN, MathX.round(d, p)); - - d = Double.MAX_VALUE; p = 1; - assertEquals("round ", Double.MAX_VALUE, MathX.round(d, p)); - - d = Double.MIN_VALUE; p = 1; - assertEquals("round ", 0.0d, MathX.round(d, p)); - } - - public void testRoundDown() { - double d = 0; - int p = 0; - - d = 0; p = 0; - assertEquals("roundDown ", 0, MathX.roundDown(d, p)); - - d = 10; p = 0; - assertEquals("roundDown ", 10, MathX.roundDown(d, p)); - - d = 123.99; p = 0; - assertEquals("roundDown ", 123, MathX.roundDown(d, p)); - - d = -123.99; p = 0; - assertEquals("roundDown ", -123, MathX.roundDown(d, p)); - - d = 123.99; p = 2; - assertEquals("roundDown ", 123.99, MathX.roundDown(d, p)); - - d = 88.123459; p = 5; - assertEquals("roundDown ", 88.12345, MathX.roundDown(d, p)); - - d = 0; p = 2; - assertEquals("roundDown ", 0, MathX.roundDown(d, p)); - - d = 0; p = -1; - assertEquals("roundDown ", 0, MathX.roundDown(d, p)); - - d = 0.01; p = -1; - assertEquals("roundDown ", 0, MathX.roundDown(d, p)); - - d = 199.12; p = -2; - assertEquals("roundDown ", 100, MathX.roundDown(d, p)); - - d = 88.123459; p = -3; - assertEquals("roundDown ", 0, MathX.roundDown(d, p)); - - d = 99.00000001; p = -1; - assertEquals("roundDown ", 90, MathX.roundDown(d, p)); - - d = 100.00001; p = -2; - assertEquals("roundDown ", 100, MathX.roundDown(d, p)); - - d = 150.0; p = -2; - assertEquals("roundDown ", 100, MathX.roundDown(d, p)); - - d = 0.049999999999999975d; p = 2; - assertEquals("round ", 0.04d, MathX.roundDown(d, p)); - - d = 0.049999999999999975d; p = 1; - assertEquals("round ", 0.0d, MathX.roundDown(d, p)); - - d = Double.NaN; p = 1; - assertEquals("round ", Double.NaN, MathX.roundDown(d, p)); - - d = Double.POSITIVE_INFINITY; p = 1; - assertEquals("round ", Double.NaN, MathX.roundDown(d, p)); - - d = Double.NEGATIVE_INFINITY; p = 1; - assertEquals("round ", Double.NaN, MathX.roundDown(d, p)); - - d = Double.MAX_VALUE; p = 1; - assertEquals("round ", Double.MAX_VALUE, MathX.roundDown(d, p)); - - d = Double.MIN_VALUE; p = 1; - assertEquals("round ", 0.0d, MathX.roundDown(d, p)); - } - - public void testRoundUp() { - double d = 0; - int p = 0; - - d = 0; p = 0; - assertEquals("roundUp ", 0, MathX.roundUp(d, p)); - - d = 10; p = 0; - assertEquals("roundUp ", 10, MathX.roundUp(d, p)); - - d = 123.23; p = 0; - assertEquals("roundUp ", 124, MathX.roundUp(d, p)); - - d = -123.23; p = 0; - assertEquals("roundUp ", -124, MathX.roundUp(d, p)); - - d = 123.12; p = 2; - assertEquals("roundUp ", 123.12, MathX.roundUp(d, p)); - - d = 88.123459; p = 5; - assertEquals("roundUp ", 88.12346, MathX.roundUp(d, p)); - - d = 0; p = 2; - assertEquals("roundUp ", 0, MathX.roundUp(d, p)); - - d = 0; p = -1; - assertEquals("roundUp ", 0, MathX.roundUp(d, p)); - - d = 0.01; p = -1; - assertEquals("roundUp ", 10, MathX.roundUp(d, p)); - - d = 123.12; p = -2; - assertEquals("roundUp ", 200, MathX.roundUp(d, p)); - - d = 88.123459; p = -3; - assertEquals("roundUp ", 1000, MathX.roundUp(d, p)); - - d = 49.00000001; p = -1; - assertEquals("roundUp ", 50, MathX.roundUp(d, p)); - - d = 149.999999; p = -2; - assertEquals("roundUp ", 200, MathX.roundUp(d, p)); - - d = 150.0; p = -2; - assertEquals("roundUp ", 200, MathX.roundUp(d, p)); - - d = 0.049999999999999975d; p = 2; - assertEquals("round ", 0.05d, MathX.roundUp(d, p)); - - d = 0.049999999999999975d; p = 1; - assertEquals("round ", 0.1d, MathX.roundUp(d, p)); - - d = Double.NaN; p = 1; - assertEquals("round ", Double.NaN, MathX.roundUp(d, p)); - - d = Double.POSITIVE_INFINITY; p = 1; - assertEquals("round ", Double.NaN, MathX.roundUp(d, p)); - - d = Double.NEGATIVE_INFINITY; p = 1; - assertEquals("round ", Double.NaN, MathX.roundUp(d, p)); - - d = Double.MAX_VALUE; p = 1; - assertEquals("round ", Double.MAX_VALUE, MathX.roundUp(d, p)); - - d = Double.MIN_VALUE; p = 1; - assertEquals("round ", 0.1d, MathX.roundUp(d, p)); - } - - public void testCeiling() { - double d = 0; - double s = 0; - - d = 0; s = 0; - assertEquals("ceiling ", 0, MathX.ceiling(d, s)); - - d = 1; s = 0; - assertEquals("ceiling ", 0, MathX.ceiling(d, s)); - - d = 0; s = 1; - assertEquals("ceiling ", 0, MathX.ceiling(d, s)); - - d = -1; s = 0; - assertEquals("ceiling ", 0, MathX.ceiling(d, s)); - - d = 0; s = -1; - assertEquals("ceiling ", 0, MathX.ceiling(d, s)); - - d = 10; s = 1.11; - assertEquals("ceiling ", 11.1, MathX.ceiling(d, s)); - - d = 11.12333; s = 0.03499; - assertEquals("ceiling ", 11.12682, MathX.ceiling(d, s)); - - d = -11.12333; s = 0.03499; - assertEquals("ceiling ", Double.NaN, MathX.ceiling(d, s)); - - d = 11.12333; s = -0.03499; - assertEquals("ceiling ", Double.NaN, MathX.ceiling(d, s)); - - d = -11.12333; s = -0.03499; - assertEquals("ceiling ", -11.12682, MathX.ceiling(d, s)); - - d = 100; s = 0.001; - assertEquals("ceiling ", 100, MathX.ceiling(d, s)); - - d = -0.001; s = -9.99; - assertEquals("ceiling ", -9.99, MathX.ceiling(d, s)); - - d = 4.42; s = 0.05; - assertEquals("ceiling ", 4.45, MathX.ceiling(d, s)); - - d = 0.05; s = 4.42; - assertEquals("ceiling ", 4.42, MathX.ceiling(d, s)); - - d = 0.6666; s = 3.33; - assertEquals("ceiling ", 3.33, MathX.ceiling(d, s)); - - d = 2d/3; s = 3.33; - assertEquals("ceiling ", 3.33, MathX.ceiling(d, s)); - } - - public void testFloor() { - double d = 0; - double s = 0; - - d = 0; s = 0; - assertEquals("floor ", 0, MathX.floor(d, s)); - - d = 1; s = 0; - assertEquals("floor ", Double.NaN, MathX.floor(d, s)); - - d = 0; s = 1; - assertEquals("floor ", 0, MathX.floor(d, s)); - - d = -1; s = 0; - assertEquals("floor ", Double.NaN, MathX.floor(d, s)); - - d = 0; s = -1; - assertEquals("floor ", 0, MathX.floor(d, s)); - - d = 10; s = 1.11; - assertEquals("floor ", 9.99, MathX.floor(d, s)); - - d = 11.12333; s = 0.03499; - assertEquals("floor ", 11.09183, MathX.floor(d, s)); - - d = -11.12333; s = 0.03499; - assertEquals("floor ", Double.NaN, MathX.floor(d, s)); - - d = 11.12333; s = -0.03499; - assertEquals("floor ", Double.NaN, MathX.floor(d, s)); - - d = -11.12333; s = -0.03499; - assertEquals("floor ", -11.09183, MathX.floor(d, s)); - - d = 100; s = 0.001; - assertEquals("floor ", 100, MathX.floor(d, s)); - - d = -0.001; s = -9.99; - assertEquals("floor ", 0, MathX.floor(d, s)); - - d = 4.42; s = 0.05; - assertEquals("floor ", 4.4, MathX.floor(d, s)); - - d = 0.05; s = 4.42; - assertEquals("floor ", 0, MathX.floor(d, s)); - - d = 0.6666; s = 3.33; - assertEquals("floor ", 0, MathX.floor(d, s)); - - d = 2d/3; s = 3.33; - assertEquals("floor ", 0, MathX.floor(d, s)); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestMid.java b/src/testcases/org/apache/poi/ss/formula/functions/TestMid.java deleted file mode 100644 index 7c19d44a6..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestMid.java +++ /dev/null @@ -1,110 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import junit.framework.TestCase; - -import org.apache.poi.ss.formula.eval.AreaEval; -import org.apache.poi.ss.formula.eval.BlankEval; -import org.apache.poi.ss.formula.eval.BoolEval; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.RefEval; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; -/** - * Tests for Excel function MID() - * - * @author Josh Micich - */ -public final class TestMid extends TestCase { - - - private static ValueEval invokeMid(ValueEval text, ValueEval startPos, ValueEval numChars) { - ValueEval[] args = new ValueEval[] { text, startPos, numChars, }; - return TextFunction.MID.evaluate(args, -1, (short)-1); - } - - private void confirmMid(ValueEval text, ValueEval startPos, ValueEval numChars, String expected) { - ValueEval result = invokeMid(text, startPos, numChars); - assertEquals(StringEval.class, result.getClass()); - assertEquals(expected, ((StringEval)result).getStringValue()); - } - - private void confirmMid(ValueEval text, ValueEval startPos, ValueEval numChars, ErrorEval expectedError) { - ValueEval result = invokeMid(text, startPos, numChars); - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(expectedError.getErrorCode(), ((ErrorEval)result).getErrorCode()); - } - - public void testBasic() { - - confirmMid(new StringEval("galactic"), new NumberEval(3), new NumberEval(4), "lact"); - } - - /** - * Valid cases where args are not precisely (string, int, int) but can be resolved OK. - */ - public void testUnusualArgs() { - // startPos with fractional digits - confirmMid(new StringEval("galactic"), new NumberEval(3.1), new NumberEval(4), "lact"); - - // string startPos - confirmMid(new StringEval("galactic"), new StringEval("3"), new NumberEval(4), "lact"); - - // text (first) arg type is number, other args are strings with fractional digits - confirmMid(new NumberEval(123456), new StringEval("3.1"), new StringEval("2.9"), "34"); - - // startPos is 1x1 area ref, numChars is cell ref - AreaEval aeStart = EvalFactory.createAreaEval("A1:A1", new ValueEval[] { new NumberEval(2), } ); - RefEval reNumChars = EvalFactory.createRefEval("B1", new NumberEval(3)); - confirmMid(new StringEval("galactic"), aeStart, reNumChars, "ala"); - - confirmMid(new StringEval("galactic"), new NumberEval(3.1), BlankEval.instance, ""); - - confirmMid(new StringEval("galactic"), new NumberEval(3), BoolEval.FALSE, ""); - confirmMid(new StringEval("galactic"), new NumberEval(3), BoolEval.TRUE, "l"); - confirmMid(BlankEval.instance, new NumberEval(3), BoolEval.TRUE, ""); - - } - - /** - * Extreme values for startPos and numChars - */ - public void testExtremes() { - confirmMid(new StringEval("galactic"), new NumberEval(4), new NumberEval(400), "actic"); - - confirmMid(new StringEval("galactic"), new NumberEval(30), new NumberEval(4), ""); - confirmMid(new StringEval("galactic"), new NumberEval(3), new NumberEval(0), ""); - } - - /** - * All sorts of ways to make MID return defined errors. - */ - public void testErrors() { - confirmMid(ErrorEval.NAME_INVALID, new NumberEval(3), new NumberEval(4), ErrorEval.NAME_INVALID); - confirmMid(new StringEval("galactic"), ErrorEval.NAME_INVALID, new NumberEval(4), ErrorEval.NAME_INVALID); - confirmMid(new StringEval("galactic"), new NumberEval(3), ErrorEval.NAME_INVALID, ErrorEval.NAME_INVALID); - confirmMid(new StringEval("galactic"), ErrorEval.DIV_ZERO, ErrorEval.NAME_INVALID, ErrorEval.DIV_ZERO); - - confirmMid(new StringEval("galactic"), BlankEval.instance, new NumberEval(3.1), ErrorEval.VALUE_INVALID); - - confirmMid(new StringEval("galactic"), new NumberEval(0), new NumberEval(4), ErrorEval.VALUE_INVALID); - confirmMid(new StringEval("galactic"), new NumberEval(1), new NumberEval(-1), ErrorEval.VALUE_INVALID); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestMirr.java b/src/testcases/org/apache/poi/ss/formula/functions/TestMirr.java deleted file mode 100644 index f38bff7fc..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestMirr.java +++ /dev/null @@ -1,168 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.EvaluationException; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.CellValue; - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -/** - * Tests for {@link org.apache.poi.ss.formula.functions.Mirr} - * - * @author Carlos Delgado (carlos dot del dot est at gmail dot com) - * @author Cedric Walter (cedric dot walter at gmail dot com) - * @see {@link org.apache.poi.ss.formula.functions.TestIrr} - */ -public final class TestMirr extends TestCase { - - public void testMirr() { - Mirr mirr = new Mirr(); - double mirrValue; - - double financeRate = 0.12; - double reinvestRate = 0.1; - double[] values = {-120000d, 39000d, 30000d, 21000d, 37000d, 46000d, reinvestRate, financeRate}; - try { - mirrValue = mirr.evaluate(values); - } catch (EvaluationException e) { - throw new AssertionFailedError("MIRR should not failed with these parameters" + e); - } - assertEquals("mirr", 0.126094130366, mirrValue, 0.0000000001); - - reinvestRate = 0.05; - financeRate = 0.08; - values = new double[]{-7500d, 3000d, 5000d, 1200d, 4000d, reinvestRate, financeRate}; - try { - mirrValue = mirr.evaluate(values); - } catch (EvaluationException e) { - throw new AssertionFailedError("MIRR should not failed with these parameters" + e); - } - assertEquals("mirr", 0.18736225093, mirrValue, 0.0000000001); - - reinvestRate = 0.065; - financeRate = 0.1; - values = new double[]{-10000, 3400d, 6500d, 1000d, reinvestRate, financeRate}; - try { - mirrValue = mirr.evaluate(values); - } catch (EvaluationException e) { - throw new AssertionFailedError("MIRR should not failed with these parameters" + e); - } - assertEquals("mirr", 0.07039493966, mirrValue, 0.0000000001); - - reinvestRate = 0.07; - financeRate = 0.01; - values = new double[]{-10000d, -3400d, -6500d, -1000d, reinvestRate, financeRate}; - try { - mirrValue = mirr.evaluate(values); - } catch (EvaluationException e) { - throw new AssertionFailedError("MIRR should not failed with these parameters" + e); - } - assertEquals("mirr", -1, mirrValue, 0.0); - - } - - public void testMirrErrors_expectDIV0() { - Mirr mirr = new Mirr(); - - double reinvestRate = 0.05; - double financeRate = 0.08; - double[] incomes = {120000d, 39000d, 30000d, 21000d, 37000d, 46000d, reinvestRate, financeRate}; - try { - mirr.evaluate(incomes); - } catch (EvaluationException e) { - assertEquals(ErrorEval.DIV_ZERO, e.getErrorEval()); - return; - } - throw new AssertionFailedError("MIRR should failed with all these positives values"); - } - - - public void testEvaluateInSheet() { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("Sheet1"); - HSSFRow row = sheet.createRow(0); - - row.createCell(0).setCellValue(-7500d); - row.createCell(1).setCellValue(3000d); - row.createCell(2).setCellValue(5000d); - row.createCell(3).setCellValue(1200d); - row.createCell(4).setCellValue(4000d); - - row.createCell(5).setCellValue(0.05d); - row.createCell(6).setCellValue(0.08d); - - HSSFCell cell = row.createCell(7); - cell.setCellFormula("MIRR(A1:E1, F1, G1)"); - - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - fe.clearAllCachedResultValues(); - fe.evaluateFormulaCellEnum(cell); - double res = cell.getNumericCellValue(); - assertEquals(0.18736225093, res, 0.00000001); - } - - public void testMirrFromSpreadsheet() { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("mirrTest.xls"); - HSSFSheet sheet = wb.getSheet("Mirr"); - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - StringBuilder failures = new StringBuilder(); - int failureCount = 0; - int[] resultRows = {9, 19, 29, 45}; - - for (int rowNum : resultRows) { - HSSFRow row = sheet.getRow(rowNum); - HSSFCell cellA = row.getCell(0); - try { - CellValue cv = fe.evaluate(cellA); - assertFormulaResult(cv, cellA); - } catch (Throwable e) { - if (failures.length() > 0) failures.append('\n'); - failures.append("Row[").append(cellA.getRowIndex() + 1).append("]: ").append(cellA.getCellFormula()).append(" "); - failures.append(e.getMessage()); - failureCount++; - } - } - - HSSFRow row = sheet.getRow(37); - HSSFCell cellA = row.getCell(0); - CellValue cv = fe.evaluate(cellA); - assertEquals(ErrorEval.DIV_ZERO.getErrorCode(), cv.getErrorValue()); - - if (failures.length() > 0) { - throw new AssertionFailedError(failureCount + " IRR assertions failed:\n" + failures.toString()); - } - - } - - private static void assertFormulaResult(CellValue cv, HSSFCell cell) { - double actualValue = cv.getNumberValue(); - double expectedValue = cell.getNumericCellValue(); // cached formula result calculated by Excel - assertEquals("Invalid formula result: " + cv.toString(), CellType.NUMERIC, cv.getCellTypeEnum()); - assertEquals(expectedValue, actualValue, 1E-8); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestNper.java b/src/testcases/org/apache/poi/ss/formula/functions/TestNper.java deleted file mode 100644 index 7952b5c6a..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestNper.java +++ /dev/null @@ -1,70 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.Assert.assertEquals; - -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.FormulaError; -import org.junit.Test; - -/** - * Tests for {@link FinanceFunction#NPER} - */ -public final class TestNper { - - @Test - public void testSimpleEvaluate() { - ValueEval[] args = { - new NumberEval(0.05), - new NumberEval(250), - new NumberEval(-1000), - }; - ValueEval result = FinanceFunction.NPER.evaluate(args, 0, (short)0); - - assertEquals(NumberEval.class, result.getClass()); - assertEquals(4.57353557, ((NumberEval)result).getNumberValue(), 0.00000001); - } - - @Test - public void testEvaluate_bug_45732() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("Sheet1"); - HSSFCell cell = sheet.createRow(0).createCell(0); - - cell.setCellFormula("NPER(12,4500,100000,100000)"); - cell.setCellValue(15.0); - assertEquals("NPER(12,4500,100000,100000)", cell.getCellFormula()); - assertEquals(CellType.NUMERIC, cell.getCachedFormulaResultTypeEnum()); - assertEquals(15.0, cell.getNumericCellValue(), 0.0); - - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - fe.evaluateFormulaCellEnum(cell); - assertEquals(CellType.ERROR, cell.getCachedFormulaResultTypeEnum()); - assertEquals(FormulaError.NUM.getCode(), cell.getErrorCellValue()); - wb.close(); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestNpv.java b/src/testcases/org/apache/poi/ss/formula/functions/TestNpv.java deleted file mode 100644 index f26b70f16..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestNpv.java +++ /dev/null @@ -1,102 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import junit.framework.TestCase; -import junit.framework.AssertionFailedError; -import org.apache.poi.hssf.usermodel.*; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.ss.usermodel.CellValue; - -/** - * Tests for {@link Npv} - * - * @author Marcel May - * @see Excel Help - */ -public final class TestNpv extends TestCase { - - public void testEvaluateInSheetExample2() { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("Sheet1"); - HSSFRow row = sheet.createRow(0); - - sheet.createRow(1).createCell(0).setCellValue(0.08d); - sheet.createRow(2).createCell(0).setCellValue(-40000d); - sheet.createRow(3).createCell(0).setCellValue(8000d); - sheet.createRow(4).createCell(0).setCellValue(9200d); - sheet.createRow(5).createCell(0).setCellValue(10000d); - sheet.createRow(6).createCell(0).setCellValue(12000d); - sheet.createRow(7).createCell(0).setCellValue(14500d); - - HSSFCell cell = row.createCell(8); - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - - // Enumeration - cell.setCellFormula("NPV(A2, A4,A5,A6,A7,A8)+A3"); - fe.clearAllCachedResultValues(); - fe.evaluateFormulaCellEnum(cell); - double res = cell.getNumericCellValue(); - assertEquals(1922.06d, Math.round(res * 100d) / 100d); - - // Range - cell.setCellFormula("NPV(A2, A4:A8)+A3"); - - fe.clearAllCachedResultValues(); - fe.evaluateFormulaCellEnum(cell); - res = cell.getNumericCellValue(); - assertEquals(1922.06d, Math.round(res * 100d) / 100d); - } - - /** - * evaluate formulas with NPV and compare the result with - * the cached formula result pre-calculated by Excel - */ - public void testNpvFromSpreadsheet(){ - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("IrrNpvTestCaseData.xls"); - HSSFSheet sheet = wb.getSheet("IRR-NPV"); - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - StringBuffer failures = new StringBuffer(); - int failureCount = 0; - // TODO YK: Formulas in rows 16 and 17 operate with ArrayPtg which isn't yet supported - // FormulaEvaluator as of r1041407 throws "Unexpected ptg class (org.apache.poi.ss.formula.ptg.ArrayPtg)" - for(int rownum = 9; rownum <= 15; rownum++){ - HSSFRow row = sheet.getRow(rownum); - HSSFCell cellB = row.getCell(1); - try { - CellValue cv = fe.evaluate(cellB); - assertFormulaResult(cv, cellB); - } catch (Throwable e){ - if(failures.length() > 0) failures.append('\n'); - failures.append("Row[" + (cellB.getRowIndex() + 1)+ "]: " + cellB.getCellFormula() + " "); - failures.append(e.getMessage()); - failureCount++; - } - } - - if(failures.length() > 0) { - throw new AssertionFailedError(failureCount + " IRR evaluations failed:\n" + failures.toString()); - } - } - - private static void assertFormulaResult(CellValue cv, HSSFCell cell){ - double actualValue = cv.getNumberValue(); - double expectedValue = cell.getNumericCellValue(); // cached formula result calculated by Excel - assertEquals(expectedValue, actualValue, 1E-4); // should agree within 0.01% - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestOct2Dec.java b/src/testcases/org/apache/poi/ss/formula/functions/TestOct2Dec.java deleted file mode 100644 index 7599ec93f..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestOct2Dec.java +++ /dev/null @@ -1,63 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import junit.framework.TestCase; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; - -/** - * Tests for {@link org.apache.poi.ss.formula.functions.Oct2Dec} - * - * @author cedric dot walter @ gmail dot com - */ -public final class TestOct2Dec extends TestCase { - - private static ValueEval invokeValue(String number1) { - ValueEval[] args = new ValueEval[] { new StringEval(number1) }; - return new Oct2Dec().evaluate(args, -1, -1); - } - - private static void confirmValue(String msg, String number1, String expected) { - ValueEval result = invokeValue(number1); - assertEquals(NumberEval.class, result.getClass()); - assertEquals(msg, expected, ((NumberEval) result).getStringValue()); - } - - private static void confirmValueError(String msg, String number1, ErrorEval numError) { - ValueEval result = invokeValue(number1); - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(msg, numError, result); - } - - public void testBasic() { - confirmValue("Converts octal '' to decimal (0)", "", "0"); - confirmValue("Converts octal 54 to decimal (44)", "54", "44"); - confirmValue("Converts octal 7777777533 to decimal (-165)", "7777777533", "-165"); - confirmValue("Converts octal 7000000000 to decimal (-134217728)", "7000000000", "-134217728"); - confirmValue("Converts octal 7776667533 to decimal (-299173)", "7776667533", "-299173"); - } - - public void testErrors() { - confirmValueError("not a valid octal number","ABCDEFGH", ErrorEval.NUM_ERROR); - confirmValueError("not a valid octal number","99999999", ErrorEval.NUM_ERROR); - confirmValueError("not a valid octal number","3.14159", ErrorEval.NUM_ERROR); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestOffset.java b/src/testcases/org/apache/poi/ss/formula/functions/TestOffset.java deleted file mode 100644 index 24d347270..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestOffset.java +++ /dev/null @@ -1,99 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -import org.apache.poi.ss.formula.eval.EvaluationException; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.functions.Offset.LinearOffsetRange; - -/** - * Tests for OFFSET function implementation - * - * @author Josh Micich - */ -public final class TestOffset extends TestCase { - - private static void confirmDoubleConvert(double doubleVal, int expected) { - try { - assertEquals(expected, Offset.evaluateIntArg(new NumberEval(doubleVal), -1, -1)); - } catch (EvaluationException e) { - throw new AssertionFailedError("Unexpected error '" + e.getErrorEval().toString() + "'."); - } - } - /** - * Excel's double to int conversion (for function 'OFFSET()') behaves more like Math.floor(). - * Note - negative values are not symmetrical - * Fractional values are silently truncated. - * Truncation is toward negative infinity. - */ - public void testDoubleConversion() { - - confirmDoubleConvert(100.09, 100); - confirmDoubleConvert(100.01, 100); - confirmDoubleConvert(100.00, 100); - confirmDoubleConvert(99.99, 99); - - confirmDoubleConvert(+2.01, +2); - confirmDoubleConvert(+2.00, +2); - confirmDoubleConvert(+1.99, +1); - confirmDoubleConvert(+1.01, +1); - confirmDoubleConvert(+1.00, +1); - confirmDoubleConvert(+0.99, 0); - confirmDoubleConvert(+0.01, 0); - confirmDoubleConvert( 0.00, 0); - confirmDoubleConvert(-0.01, -1); - confirmDoubleConvert(-0.99, -1); - confirmDoubleConvert(-1.00, -1); - confirmDoubleConvert(-1.01, -2); - confirmDoubleConvert(-1.99, -2); - confirmDoubleConvert(-2.00, -2); - confirmDoubleConvert(-2.01, -3); - } - - public void testLinearOffsetRange() { - LinearOffsetRange lor; - - lor = new LinearOffsetRange(3, 2); - assertEquals(3, lor.getFirstIndex()); - assertEquals(4, lor.getLastIndex()); - lor = lor.normaliseAndTranslate(0); // expected no change - assertEquals(3, lor.getFirstIndex()); - assertEquals(4, lor.getLastIndex()); - - lor = lor.normaliseAndTranslate(5); - assertEquals(8, lor.getFirstIndex()); - assertEquals(9, lor.getLastIndex()); - - // negative length - - lor = new LinearOffsetRange(6, -4).normaliseAndTranslate(0); - assertEquals(3, lor.getFirstIndex()); - assertEquals(6, lor.getLastIndex()); - - - // bounds checking - lor = new LinearOffsetRange(0, 100); - assertFalse(lor.isOutOfBounds(0, 16383)); - lor = lor.normaliseAndTranslate(16300); - assertTrue(lor.isOutOfBounds(0, 16383)); - assertFalse(lor.isOutOfBounds(0, 65535)); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestPPMT.java b/src/testcases/org/apache/poi/ss/formula/functions/TestPPMT.java deleted file mode 100644 index 45472f6dc..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestPPMT.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.ss.formula.functions; - -import junit.framework.TestCase; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; - -/** - * Test cases for PPMT() - * - */ -public final class TestPPMT extends TestCase { - - - /** - * http://office.microsoft.com/en-001/excel-help/ppmt-function-HP010342774.aspx - */ - public void testFromFile() { - - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("finance.xls"); - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - - HSSFSheet example1 = wb.getSheet("PPMT"); - HSSFCell ex1cell1 = example1.getRow(5).getCell(0); - fe.evaluate(ex1cell1); - assertEquals(-75.62, ex1cell1.getNumericCellValue(), 0.1); - - HSSFCell ex1cell2 = example1.getRow(16).getCell(0); - fe.evaluate(ex1cell2); - assertEquals(-27598.05, ex1cell2.getNumericCellValue(), 0.1); - - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestPmt.java b/src/testcases/org/apache/poi/ss/formula/functions/TestPmt.java deleted file mode 100644 index f408a42ed..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestPmt.java +++ /dev/null @@ -1,84 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.ss.usermodel.FormulaError; -import org.junit.Test; - -public final class TestPmt { - - private static void confirm(double expected, NumberEval ne) { - // only asserting accuracy to 4 fractional digits - assertEquals(expected, ne.getNumberValue(), 0.00005); - } - private static ValueEval invoke(ValueEval[] args) { - return FinanceFunction.PMT.evaluate(args, -1, (short)-1); - } - /** - * Invocation when not expecting an error result - */ - private static NumberEval invokeNormal(ValueEval[] args) { - ValueEval ev = invoke(args); - if(ev instanceof ErrorEval) { - fail("Normal evaluation failed with error code: " + ev.toString()); - } - return (NumberEval) ev; - } - - private static void confirm(double expected, double rate, double nper, double pv, double fv, boolean isBeginning) { - ValueEval[] args = { - new NumberEval(rate), - new NumberEval(nper), - new NumberEval(pv), - new NumberEval(fv), - new NumberEval(isBeginning ? 1 : 0), - }; - confirm(expected, invokeNormal(args)); - } - - @Test - public void testBasic() { - confirm(-1037.0321, (0.08/12), 10, 10000, 0, false); - confirm(-1030.1643, (0.08/12), 10, 10000, 0, true); - } - - @Test - public void test3args() { - - ValueEval[] args = { - new NumberEval(0.005), - new NumberEval(24), - new NumberEval(1000), - }; - ValueEval ev = invoke(args); - if(ev instanceof ErrorEval) { - ErrorEval err = (ErrorEval) ev; - if(err.getErrorCode() == FormulaError.VALUE.getCode()) { - fail("Identified bug 44691"); - } - } - - confirm(-44.3206, invokeNormal(args)); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestPoisson.java b/src/testcases/org/apache/poi/ss/formula/functions/TestPoisson.java deleted file mode 100644 index e18d66ec6..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestPoisson.java +++ /dev/null @@ -1,111 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import junit.framework.TestCase; - -import org.apache.poi.ss.formula.eval.BoolEval; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.ValueEval; - -/** - * Tests for Excel function POISSON(x,mean,cumulative) - * @author Kalpesh Parmar - */ -public class TestPoisson extends TestCase { - - private static final double DELTA = 1E-15; - - private static ValueEval invokePoisson(double x, double mean, boolean cumulative) - { - - ValueEval[] valueEvals = new ValueEval[3]; - valueEvals[0] = new NumberEval(x); - valueEvals[1] = new NumberEval(mean); - valueEvals[2] = BoolEval.valueOf(cumulative); - - return NumericFunction.POISSON.evaluate(valueEvals,-1,-1); - } - - public void testCumulativeProbability() - { - double x = 1; - double mean = 0.2; - double result = 0.9824769036935787; // known result - - NumberEval myResult = (NumberEval)invokePoisson(x,mean,true); - - assertEquals(myResult.getNumberValue(), result, DELTA); - } - - public void testNonCumulativeProbability() - { - double x = 0; - double mean = 0.2; - double result = 0.8187307530779818; // known result - - NumberEval myResult = (NumberEval)invokePoisson(x,mean,false); - - assertEquals(myResult.getNumberValue(), result, DELTA); - } - - public void testNegativeMean() - { - double x = 0; - double mean = -0.2; - - ErrorEval myResult = (ErrorEval)invokePoisson(x,mean,false); - - assertEquals(ErrorEval.NUM_ERROR.getErrorCode(), myResult.getErrorCode()); - } - - public void testNegativeX() - { - double x = -1; - double mean = 0.2; - - ErrorEval myResult = (ErrorEval)invokePoisson(x,mean,false); - - assertEquals(ErrorEval.NUM_ERROR.getErrorCode(), myResult.getErrorCode()); - } - - - - public void testXAsDecimalNumber() - { - double x = 1.1; - double mean = 0.2; - double result = 0.9824769036935787; // known result - - NumberEval myResult = (NumberEval)invokePoisson(x,mean,true); - - assertEquals(myResult.getNumberValue(), result, DELTA); - } - - public void testXZeroMeanZero() - { - double x = 0; - double mean = 0; - double result = 1; // known result in excel - - NumberEval myResult = (NumberEval)invokePoisson(x,mean,true); - - assertEquals(myResult.getNumberValue(), result, DELTA); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestQuotient.java b/src/testcases/org/apache/poi/ss/formula/functions/TestQuotient.java deleted file mode 100644 index dd6c30e1a..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestQuotient.java +++ /dev/null @@ -1,64 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.formula.functions; - -import junit.framework.TestCase; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; - -/** - * Tests for {@link Quotient} - * - * @author cedric dot walter @ gmail dot com - */ -public class TestQuotient extends TestCase { - private static ValueEval invokeValue(String numerator, String denominator) { - ValueEval[] args = new ValueEval[]{new StringEval(numerator), new StringEval(denominator)}; - return new Quotient().evaluate(args, -1, -1); - } - - private static void confirmValue(String msg, String numerator, String denominator, String expected) { - ValueEval result = invokeValue(numerator, denominator); - assertEquals(NumberEval.class, result.getClass()); - assertEquals(msg, expected, ((NumberEval) result).getStringValue()); - } - - private static void confirmValueError(String msg, String numerator, String denominator, ErrorEval numError) { - ValueEval result = invokeValue(numerator, denominator); - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(msg, numError, result); - } - - public void testBasic() { - confirmValue("Integer portion of 5/2 (2)", "5", "2", "2"); - confirmValue("Integer portion of 4.5/3.1 (1)", "4.5", "3.1", "1"); - - confirmValue("Integer portion of -10/3 (-3)", "-10", "3", "-3"); - confirmValue("Integer portion of -5.5/2 (-2)", "-5.5", "2", "-2"); - - confirmValue("Integer portion of Pi/Avogadro (0)", "3.14159", "6.02214179E+23", "0"); - } - - public void testErrors() { - confirmValueError("numerator is nonnumeric", "ABCD", "", ErrorEval.VALUE_INVALID); - confirmValueError("denominator is nonnumeric", "", "ABCD", ErrorEval.VALUE_INVALID); - - confirmValueError("dividing by zero", "3.14159", "0", ErrorEval.DIV_ZERO); - } -} \ No newline at end of file diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestQuotientFunctionsFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/functions/TestQuotientFunctionsFromSpreadsheet.java deleted file mode 100644 index 146e0cf90..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestQuotientFunctionsFromSpreadsheet.java +++ /dev/null @@ -1,32 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import java.util.Collection; - -import org.junit.runners.Parameterized.Parameters; - -/** - * Tests QUOTIENT() as loaded from a test data spreadsheet.

    - */ -public class TestQuotientFunctionsFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - @Parameters(name="{0}") - public static Collection data() throws Exception { - return data(TestQuotientFunctionsFromSpreadsheet.class, "QuotientFunctionTestCaseData.xls"); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestRank.java b/src/testcases/org/apache/poi/ss/formula/functions/TestRank.java deleted file mode 100644 index b62dffa09..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestRank.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.ss.formula.functions; - -import junit.framework.TestCase; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.util.CellReference; - -/** - * Test cases for RANK() - */ -public final class TestRank extends TestCase { - - public void testFromFile() { - - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("rank.xls"); - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - - HSSFSheet example1 = wb.getSheet("Example 1"); - HSSFCell ex1cell1 = example1.getRow(7).getCell(0); - assertEquals(3.0, fe.evaluate(ex1cell1).getNumberValue()); - HSSFCell ex1cell2 = example1.getRow(8).getCell(0); - assertEquals(5.0, fe.evaluate(ex1cell2).getNumberValue()); - - HSSFSheet example2 = wb.getSheet("Example 2"); - for(int rownum = 1; rownum<= 10; rownum ++){ - HSSFCell cell = example2.getRow(rownum).getCell(2); - double cachedResult = cell.getNumericCellValue(); //cached formula result - assertEquals(cachedResult, fe.evaluate(cell).getNumberValue()); - } - - HSSFSheet example3 = wb.getSheet("Example 3"); - for(int rownum = 1; rownum<= 10; rownum ++){ - HSSFCell cellD = example3.getRow(rownum).getCell(3); - double cachedResultD = cellD.getNumericCellValue(); //cached formula result - assertEquals(new CellReference(cellD).formatAsString(), cachedResultD, fe.evaluate(cellD).getNumberValue()); - - HSSFCell cellE = example3.getRow(rownum).getCell(4); - double cachedResultE = cellE.getNumericCellValue(); //cached formula result - assertEquals(new CellReference(cellE).formatAsString(), cachedResultE, fe.evaluate(cellE).getNumberValue()); - - HSSFCell cellF = example3.getRow(rownum).getCell(5); - double cachedResultF = cellF.getNumericCellValue(); //cached formula result - assertEquals(new CellReference(cellF).formatAsString(), cachedResultF, fe.evaluate(cellF).getNumberValue()); - } - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestReptFunctionsFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/functions/TestReptFunctionsFromSpreadsheet.java deleted file mode 100644 index e1d26ff63..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestReptFunctionsFromSpreadsheet.java +++ /dev/null @@ -1,32 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import java.util.Collection; - -import org.junit.runners.Parameterized.Parameters; - -/** - * Tests REPT() as loaded from a test data spreadsheet.

    - */ -public class TestReptFunctionsFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - @Parameters(name="{0}") - public static Collection data() throws Exception { - return data(TestReptFunctionsFromSpreadsheet.class, "ReptFunctionTestCaseData.xls"); - } -} \ No newline at end of file diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestRomanFunctionsFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/functions/TestRomanFunctionsFromSpreadsheet.java deleted file mode 100644 index 7f6ca4ea6..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestRomanFunctionsFromSpreadsheet.java +++ /dev/null @@ -1,32 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import java.util.Collection; - -import org.junit.runners.Parameterized.Parameters; - -/** - * Tests Roman() as loaded from a test data spreadsheet.

    - */ -public class TestRomanFunctionsFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - @Parameters(name="{0}") - public static Collection data() throws Exception { - return data(TestRomanFunctionsFromSpreadsheet.class, "RomanFunctionTestCaseData.xls"); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestRoundFuncs.java b/src/testcases/org/apache/poi/ss/formula/functions/TestRoundFuncs.java deleted file mode 100644 index 5d2398d2b..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestRoundFuncs.java +++ /dev/null @@ -1,50 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import junit.framework.TestCase; - -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.StringEval; - -/** - * Test cases for ROUND(), ROUNDUP(), ROUNDDOWN() - * - * @author Josh Micich - */ -public final class TestRoundFuncs extends TestCase { - private static final NumericFunction F = null; - public void testRounddownWithStringArg() { - - ValueEval strArg = new StringEval("abc"); - ValueEval[] args = { strArg, new NumberEval(2), }; - ValueEval result = NumericFunction.ROUNDDOWN.evaluate(args, -1, (short)-1); - assertEquals(ErrorEval.VALUE_INVALID, result); - } - - public void testRoundupWithStringArg() { - - ValueEval strArg = new StringEval("abc"); - ValueEval[] args = { strArg, new NumberEval(2), }; - ValueEval result = NumericFunction.ROUNDUP.evaluate(args, -1, (short)-1); - assertEquals(ErrorEval.VALUE_INVALID, result); - } - -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestRowCol.java b/src/testcases/org/apache/poi/ss/formula/functions/TestRowCol.java deleted file mode 100644 index a27a63ee9..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestRowCol.java +++ /dev/null @@ -1,97 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import junit.framework.TestCase; - -import org.apache.poi.ss.formula.eval.ValueEval; - -/** - * Tests for ROW(), ROWS(), COLUMN(), COLUMNS() - * - * @author Josh Micich - */ -public final class TestRowCol extends TestCase { - - public void testCol() { - Function target = new Column(); - { - ValueEval[] args = { EvalFactory.createRefEval("C5"), }; - double actual = NumericFunctionInvoker.invoke(target, args); - assertEquals(3, actual, 0D); - } - { - ValueEval[] args = { EvalFactory.createAreaEval("E2:H12", new ValueEval[44]), }; - double actual = NumericFunctionInvoker.invoke(target, args); - assertEquals(5, actual, 0D); - } - } - - public void testRow() { - Function target = new RowFunc(); - { - ValueEval[] args = { EvalFactory.createRefEval("C5"), }; - double actual = NumericFunctionInvoker.invoke(target, args); - assertEquals(5, actual, 0D); - } - { - ValueEval[] args = { EvalFactory.createAreaEval("E2:H12", new ValueEval[44]), }; - double actual = NumericFunctionInvoker.invoke(target, args); - assertEquals(2, actual, 0D); - } - } - - public void testColumns() { - - confirmColumnsFunc("A1:F1", 6, 1); - confirmColumnsFunc("A1:C2", 3, 2); - confirmColumnsFunc("A1:B3", 2, 3); - confirmColumnsFunc("A1:A6", 1, 6); - - ValueEval[] args = { EvalFactory.createRefEval("C5"), }; - double actual = NumericFunctionInvoker.invoke(new Columns(), args); - assertEquals(1, actual, 0D); - } - - public void testRows() { - - confirmRowsFunc("A1:F1", 6, 1); - confirmRowsFunc("A1:C2", 3, 2); - confirmRowsFunc("A1:B3", 2, 3); - confirmRowsFunc("A1:A6", 1, 6); - - ValueEval[] args = { EvalFactory.createRefEval("C5"), }; - double actual = NumericFunctionInvoker.invoke(new Rows(), args); - assertEquals(1, actual, 0D); - } - - private static void confirmRowsFunc(String areaRefStr, int nCols, int nRows) { - ValueEval[] args = { EvalFactory.createAreaEval(areaRefStr, new ValueEval[nCols * nRows]), }; - - double actual = NumericFunctionInvoker.invoke(new Rows(), args); - assertEquals(nRows, actual, 0D); - } - - - private static void confirmColumnsFunc(String areaRefStr, int nCols, int nRows) { - ValueEval[] args = { EvalFactory.createAreaEval(areaRefStr, new ValueEval[nCols * nRows]), }; - - double actual = NumericFunctionInvoker.invoke(new Columns(), args); - assertEquals(nCols, actual, 0D); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestSlope.java b/src/testcases/org/apache/poi/ss/formula/functions/TestSlope.java deleted file mode 100644 index db5fee109..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestSlope.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.ss.formula.functions; - -import junit.framework.TestCase; - -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.ValueEval; -/** - * Test for Excel function SLOPE() - * - * @author Johan Karlsteen - */ -public final class TestSlope extends TestCase { - private static final Function SLOPE = new Slope(); - - private static ValueEval invoke(Function function, ValueEval xArray, ValueEval yArray) { - ValueEval[] args = new ValueEval[] { xArray, yArray, }; - return function.evaluate(args, -1, (short)-1); - } - - private void confirm(Function function, ValueEval xArray, ValueEval yArray, double expected) { - ValueEval result = invoke(function, xArray, yArray); - assertEquals(NumberEval.class, result.getClass()); - assertEquals(expected, ((NumberEval)result).getNumberValue(), 0); - } - private void confirmError(Function function, ValueEval xArray, ValueEval yArray, ErrorEval expectedError) { - ValueEval result = invoke(function, xArray, yArray); - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(expectedError.getErrorCode(), ((ErrorEval)result).getErrorCode()); - } - - private void confirmError(ValueEval xArray, ValueEval yArray, ErrorEval expectedError) { - confirmError(SLOPE, xArray, yArray, expectedError); - } - - public void testBasic() { - Double exp = Math.pow(10, 7.5); - ValueEval[] yValues = { - new NumberEval(3+exp), - new NumberEval(4+exp), - new NumberEval(2+exp), - new NumberEval(5+exp), - new NumberEval(4+exp), - new NumberEval(7+exp), - }; - ValueEval areaEvalY = createAreaEval(yValues); - - ValueEval[] xValues = { - new NumberEval(1), - new NumberEval(2), - new NumberEval(3), - new NumberEval(4), - new NumberEval(5), - new NumberEval(6), - }; - ValueEval areaEvalX = createAreaEval(xValues); - confirm(SLOPE, areaEvalX, areaEvalY, 0.7752808988764045); - // Excel 2010 gives 0.775280898876405 - } - - /** - * number of items in array is not limited to 30 - */ - public void testLargeArrays() { - ValueEval[] yValues = createMockNumberArray(100, 3); // [1,2,0,1,2,0,...,0,1] - yValues[0] = new NumberEval(2.0); // Changes first element to 2 - ValueEval[] xValues = createMockNumberArray(100, 101); // [1,2,3,4,...,99,100] - - confirm(SLOPE, createAreaEval(xValues), createAreaEval(yValues), -1.231527093596059); - // Excel 2010 gives -1.23152709359606 - } - - private ValueEval[] createMockNumberArray(int size, double value) { - ValueEval[] result = new ValueEval[size]; - for (int i = 0; i < result.length; i++) { - result[i] = new NumberEval((i+1)%value); - } - return result; - } - - private static ValueEval createAreaEval(ValueEval[] values) { - String refStr = "A1:A" + values.length; - return EvalFactory.createAreaEval(refStr, values); - } - - public void testErrors() { - ValueEval[] xValues = { - ErrorEval.REF_INVALID, - new NumberEval(2), - }; - ValueEval areaEvalX = createAreaEval(xValues); - ValueEval[] yValues = { - new NumberEval(2), - ErrorEval.NULL_INTERSECTION, - }; - ValueEval areaEvalY = createAreaEval(yValues); - ValueEval[] zValues = { // wrong size - new NumberEval(2), - }; - ValueEval areaEvalZ = createAreaEval(zValues); - - // if either arg is an error, that error propagates - confirmError(ErrorEval.REF_INVALID, ErrorEval.NAME_INVALID, ErrorEval.REF_INVALID); - confirmError(areaEvalX, ErrorEval.NAME_INVALID, ErrorEval.NAME_INVALID); - confirmError(ErrorEval.NAME_INVALID, areaEvalX, ErrorEval.NAME_INVALID); - - // array sizes must match - confirmError(areaEvalX, areaEvalZ, ErrorEval.NA); - confirmError(areaEvalZ, areaEvalY, ErrorEval.NA); - - // any error in an array item propagates up - confirmError(areaEvalX, areaEvalX, ErrorEval.REF_INVALID); - - // search for errors array by array, not pair by pair - confirmError(areaEvalX, areaEvalY, ErrorEval.NULL_INTERSECTION); - confirmError(areaEvalY, areaEvalX, ErrorEval.REF_INVALID); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestStatsLib.java b/src/testcases/org/apache/poi/ss/formula/functions/TestStatsLib.java deleted file mode 100644 index cd0176f22..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestStatsLib.java +++ /dev/null @@ -1,321 +0,0 @@ -/* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -/* - * Created on May 30, 2005 - * - */ -package org.apache.poi.ss.formula.functions; - -import junit.framework.AssertionFailedError; - -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.EvaluationException; - - -/** - * @author Amol S. Deshmukh < amolweb at ya hoo dot com > - * - */ -public class TestStatsLib extends AbstractNumericTestCase { - - public void testDevsq() { - double[] v = null; - double d, x = 0; - - v = new double[] {1,2,3,4,5,6,7,8,9,10}; - d = StatsLib.devsq(v); - x = 82.5; - assertEquals("devsq ", x, d); - - v = new double[] {1,1,1,1,1,1,1,1,1,1}; - d = StatsLib.devsq(v); - x = 0; - assertEquals("devsq ", x, d); - - v = new double[] {0,0,0,0,0,0,0,0,0,0}; - d = StatsLib.devsq(v); - x = 0; - assertEquals("devsq ", x, d); - - v = new double[] {1,2,1,2,1,2,1,2,1,2}; - d = StatsLib.devsq(v); - x = 2.5; - assertEquals("devsq ", x, d); - - v = new double[] {123.12,33.3333,2d/3d,5.37828,0.999}; - d = StatsLib.devsq(v); - x = 10953.7416965767; - assertEquals("devsq ", x, d); - - v = new double[] {-1,-2,-3,-4,-5,-6,-7,-8,-9,-10}; - d = StatsLib.devsq(v); - x = 82.5; - assertEquals("devsq ", x, d); - } - - public void testKthLargest() { - double[] v = null; - double d, x = 0; - - v = new double[] {1,2,3,4,5,6,7,8,9,10}; - d = StatsLib.kthLargest(v, 3); - x = 8; - assertEquals("kthLargest ", x, d); - - v = new double[] {1,1,1,1,1,1,1,1,1,1}; - d = StatsLib.kthLargest(v, 3); - x = 1; - assertEquals("kthLargest ", x, d); - - v = new double[] {0,0,0,0,0,0,0,0,0,0}; - d = StatsLib.kthLargest(v, 3); - x = 0; - assertEquals("kthLargest ", x, d); - - v = new double[] {1,2,1,2,1,2,1,2,1,2}; - d = StatsLib.kthLargest(v, 3); - x = 2; - assertEquals("kthLargest ", x, d); - - v = new double[] {123.12,33.3333,2d/3d,5.37828,0.999}; - d = StatsLib.kthLargest(v, 3); - x = 5.37828; - assertEquals("kthLargest ", x, d); - - v = new double[] {-1,-2,-3,-4,-5,-6,-7,-8,-9,-10}; - d = StatsLib.kthLargest(v, 3); - x = -3; - assertEquals("kthLargest ", x, d); - } - - public void testKthSmallest() { - } - - public void testAvedev() { - double[] v = null; - double d, x = 0; - - v = new double[] {1,2,3,4,5,6,7,8,9,10}; - d = StatsLib.avedev(v); - x = 2.5; - assertEquals("avedev ", x, d); - - v = new double[] {1,1,1,1,1,1,1,1,1,1}; - d = StatsLib.avedev(v); - x = 0; - assertEquals("avedev ", x, d); - - v = new double[] {0,0,0,0,0,0,0,0,0,0}; - d = StatsLib.avedev(v); - x = 0; - assertEquals("avedev ", x, d); - - v = new double[] {1,2,1,2,1,2,1,2,1,2}; - d = StatsLib.avedev(v); - x = 0.5; - assertEquals("avedev ", x, d); - - v = new double[] {123.12,33.3333,2d/3d,5.37828,0.999}; - d = StatsLib.avedev(v); - x = 36.42176053333; - assertEquals("avedev ", x, d); - - v = new double[] {-1,-2,-3,-4,-5,-6,-7,-8,-9,-10}; - d = StatsLib.avedev(v); - x = 2.5; - assertEquals("avedev ", x, d); - } - - public void testMedian() { - double[] v = null; - double d, x = 0; - - v = new double[] {1,2,3,4,5,6,7,8,9,10}; - d = StatsLib.median(v); - x = 5.5; - assertEquals("median ", x, d); - - v = new double[] {1,1,1,1,1,1,1,1,1,1}; - d = StatsLib.median(v); - x = 1; - assertEquals("median ", x, d); - - v = new double[] {0,0,0,0,0,0,0,0,0,0}; - d = StatsLib.median(v); - x = 0; - assertEquals("median ", x, d); - - v = new double[] {1,2,1,2,1,2,1,2,1,2}; - d = StatsLib.median(v); - x = 1.5; - assertEquals("median ", x, d); - - v = new double[] {123.12,33.3333,2d/3d,5.37828,0.999}; - d = StatsLib.median(v); - x = 5.37828; - assertEquals("median ", x, d); - - v = new double[] {-1,-2,-3,-4,-5,-6,-7,-8,-9,-10}; - d = StatsLib.median(v); - x = -5.5; - assertEquals("median ", x, d); - - v = new double[] {-2,-3,-4,-5,-6,-7,-8,-9,-10}; - d = StatsLib.median(v); - x = -6; - assertEquals("median ", x, d); - - v = new double[] {1,2,3,4,5,6,7,8,9}; - d = StatsLib.median(v); - x = 5; - assertEquals("median ", x, d); - } - - public void testMode() { - double[] v; - double d, x = 0; - - v = new double[] {1,2,3,4,5,6,7,8,9,10}; - confirmMode(v, null); - - v = new double[] {1,1,1,1,1,1,1,1,1,1}; - confirmMode(v, 1.0); - - v = new double[] {0,0,0,0,0,0,0,0,0,0}; - confirmMode(v, 0.0); - - v = new double[] {1,2,1,2,1,2,1,2,1,2}; - confirmMode(v, 1.0); - - v = new double[] {123.12,33.3333,2d/3d,5.37828,0.999}; - confirmMode(v, null); - - v = new double[] {-1,-2,-3,-4,-5,-6,-7,-8,-9,-10}; - confirmMode(v, null); - - v = new double[] {1,2,3,4,1,1,1,1,0,0,0,0,0}; - confirmMode(v, 1.0); - - v = new double[] {0,1,2,3,4,1,1,1,0,0,0,0,1}; - confirmMode(v, 0.0); - } - private static void confirmMode(double[] v, double expectedResult) { - confirmMode(v, new Double(expectedResult)); - } - private static void confirmMode(double[] v, Double expectedResult) { - double actual; - try { - actual = Mode.evaluate(v); - if (expectedResult == null) { - throw new AssertionFailedError("Expected N/A exception was not thrown"); - } - } catch (EvaluationException e) { - if (expectedResult == null) { - assertEquals(ErrorEval.NA, e.getErrorEval()); - return; - } - throw new RuntimeException(e); - } - assertEquals("mode", expectedResult.doubleValue(), actual); - } - - - public void testStddev() { - double[] v = null; - double d, x = 0; - - v = new double[] {1,2,3,4,5,6,7,8,9,10}; - d = StatsLib.stdev(v); - x = 3.02765035410; - assertEquals("stdev ", x, d); - - v = new double[] {1,1,1,1,1,1,1,1,1,1}; - d = StatsLib.stdev(v); - x = 0; - assertEquals("stdev ", x, d); - - v = new double[] {0,0,0,0,0,0,0,0,0,0}; - d = StatsLib.stdev(v); - x = 0; - assertEquals("stdev ", x, d); - - v = new double[] {1,2,1,2,1,2,1,2,1,2}; - d = StatsLib.stdev(v); - x = 0.52704627669; - assertEquals("stdev ", x, d); - - v = new double[] {123.12,33.3333,2d/3d,5.37828,0.999}; - d = StatsLib.stdev(v); - x = 52.33006233652; - assertEquals("stdev ", x, d); - - v = new double[] {-1,-2,-3,-4,-5,-6,-7,-8,-9,-10}; - d = StatsLib.stdev(v); - x = 3.02765035410; - assertEquals("stdev ", x, d); - } - - public void testVar() { - double[] v = null; - double d, x = 0; - - v = new double[] {3.50, 5.00, 7.23, 2.99}; - d = StatsLib.var(v); - x = 3.6178; - assertEquals("var ", x, d); - - v = new double[] {34.5, 2.0, 8.9, -4.0}; - d = StatsLib.var(v); - x = 286.99; - assertEquals("var ", x, d); - - v = new double[] {7.0, 25.0, 21.69}; - d = StatsLib.var(v); - x = 91.79203333; - assertEquals("var ", x, d); - - v = new double[] {1345,1301,1368,1322,1310,1370,1318,1350,1303,1299}; - d = StatsLib.var(v); - x = 754.2666667; - assertEquals("var ", x, d); - } - - public void testVarp() { - double[] v = null; - double d, x = 0; - - v = new double[] {3.50, 5.00, 7.23, 2.99}; - d = StatsLib.varp(v); - x = 2.71335; - assertEquals("varp ", x, d); - - v = new double[] {34.5, 2.0, 8.9, -4.0}; - d = StatsLib.varp(v); - x = 215.2425; - assertEquals("varp ", x, d); - - v = new double[] {7.0, 25.0, 21.69}; - d = StatsLib.varp(v); - x = 61.19468889; - assertEquals("varp ", x, d); - - v = new double[] {1345,1301,1368,1322,1310,1370,1318,1350,1303,1299}; - d = StatsLib.varp(v); - x = 678.84; - assertEquals("varp ", x, d); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestSubtotal.java b/src/testcases/org/apache/poi/ss/formula/functions/TestSubtotal.java deleted file mode 100644 index f2750b591..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestSubtotal.java +++ /dev/null @@ -1,414 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.formula.FormulaParseException; -import org.apache.poi.ss.formula.eval.*; - -import junit.framework.TestCase; -import org.apache.poi.ss.usermodel.*; - -/** - * Tests for {@link Subtotal} - * - * @author Paul Tomlin - */ -public final class TestSubtotal extends TestCase { - private static final int FUNCTION_AVERAGE = 1; - private static final int FUNCTION_COUNT = 2; - private static final int FUNCTION_MAX = 4; - private static final int FUNCTION_MIN = 5; - private static final int FUNCTION_PRODUCT = 6; - private static final int FUNCTION_STDEV = 7; - private static final int FUNCTION_SUM = 9; - - private static final double[] TEST_VALUES0 = { - 1, 2, - 3, 4, - 5, 6, - 7, 8, - 9, 10 - }; - - private static void confirmSubtotal(int function, double expected) { - ValueEval[] values = new ValueEval[TEST_VALUES0.length]; - for (int i = 0; i < TEST_VALUES0.length; i++) { - values[i] = new NumberEval(TEST_VALUES0[i]); - } - - AreaEval arg1 = EvalFactory.createAreaEval("C1:D5", values); - ValueEval args[] = { new NumberEval(function), arg1 }; - - ValueEval result = new Subtotal().evaluate(args, 0, 0); - - assertEquals(NumberEval.class, result.getClass()); - assertEquals(expected, ((NumberEval) result).getNumberValue(), 0.0); - } - - public void testBasics() { - confirmSubtotal(FUNCTION_SUM, 55.0); - confirmSubtotal(FUNCTION_AVERAGE, 5.5); - confirmSubtotal(FUNCTION_COUNT, 10.0); - confirmSubtotal(FUNCTION_MAX, 10.0); - confirmSubtotal(FUNCTION_MIN, 1.0); - confirmSubtotal(FUNCTION_PRODUCT, 3628800.0); - confirmSubtotal(FUNCTION_STDEV, 3.0276503540974917); - } - - public void testAvg(){ - Workbook wb = new HSSFWorkbook(); - - FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); - - Sheet sh = wb.createSheet(); - Cell a1 = sh.createRow(1).createCell(1); - a1.setCellValue(1); - Cell a2 = sh.createRow(2).createCell(1); - a2.setCellValue(3); - Cell a3 = sh.createRow(3).createCell(1); - a3.setCellFormula("SUBTOTAL(1,B2:B3)"); - Cell a4 = sh.createRow(4).createCell(1); - a4.setCellValue(1); - Cell a5 = sh.createRow(5).createCell(1); - a5.setCellValue(7); - Cell a6 = sh.createRow(6).createCell(1); - a6.setCellFormula("SUBTOTAL(1,B2:B6)*2 + 2"); - Cell a7 = sh.createRow(7).createCell(1); - a7.setCellFormula("SUBTOTAL(1,B2:B7)"); - Cell a8 = sh.createRow(8).createCell(1); - a8.setCellFormula("SUBTOTAL(1,B2,B3,B4,B5,B6,B7,B8)"); - - fe.evaluateAll(); - - assertEquals(2.0, a3.getNumericCellValue()); - assertEquals(8.0, a6.getNumericCellValue()); - assertEquals(3.0, a7.getNumericCellValue()); - assertEquals(3.0, a8.getNumericCellValue()); - } - - public void testSum(){ - Workbook wb = new HSSFWorkbook(); - - FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); - - Sheet sh = wb.createSheet(); - Cell a1 = sh.createRow(1).createCell(1); - a1.setCellValue(1); - Cell a2 = sh.createRow(2).createCell(1); - a2.setCellValue(3); - Cell a3 = sh.createRow(3).createCell(1); - a3.setCellFormula("SUBTOTAL(9,B2:B3)"); - Cell a4 = sh.createRow(4).createCell(1); - a4.setCellValue(1); - Cell a5 = sh.createRow(5).createCell(1); - a5.setCellValue(7); - Cell a6 = sh.createRow(6).createCell(1); - a6.setCellFormula("SUBTOTAL(9,B2:B6)*2 + 2"); - Cell a7 = sh.createRow(7).createCell(1); - a7.setCellFormula("SUBTOTAL(9,B2:B7)"); - Cell a8 = sh.createRow(8).createCell(1); - a8.setCellFormula("SUBTOTAL(9,B2,B3,B4,B5,B6,B7,B8)"); - - fe.evaluateAll(); - - assertEquals(4.0, a3.getNumericCellValue()); - assertEquals(26.0, a6.getNumericCellValue()); - assertEquals(12.0, a7.getNumericCellValue()); - assertEquals(12.0, a8.getNumericCellValue()); - } - - public void testCount(){ - - Workbook wb = new HSSFWorkbook(); - - FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); - - Sheet sh = wb.createSheet(); - Cell a1 = sh.createRow(1).createCell(1); - a1.setCellValue(1); - Cell a2 = sh.createRow(2).createCell(1); - a2.setCellValue(3); - Cell a3 = sh.createRow(3).createCell(1); - a3.setCellFormula("SUBTOTAL(2,B2:B3)"); - Cell a4 = sh.createRow(4).createCell(1); - a4.setCellValue("POI"); // A4 is string and not counted - /*Cell a5 =*/ sh.createRow(5).createCell(1); // A5 is blank and not counted - - Cell a6 = sh.createRow(6).createCell(1); - a6.setCellFormula("SUBTOTAL(2,B2:B6)*2 + 2"); - Cell a7 = sh.createRow(7).createCell(1); - a7.setCellFormula("SUBTOTAL(2,B2:B7)"); - Cell a8 = sh.createRow(8).createCell(1); - a8.setCellFormula("SUBTOTAL(2,B2,B3,B4,B5,B6,B7,B8)"); - - fe.evaluateAll(); - - assertEquals(2.0, a3.getNumericCellValue()); - assertEquals(6.0, a6.getNumericCellValue()); - assertEquals(2.0, a7.getNumericCellValue()); - assertEquals(2.0, a8.getNumericCellValue()); - } - - public void testCounta(){ - - Workbook wb = new HSSFWorkbook(); - - FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); - - Sheet sh = wb.createSheet(); - Cell a1 = sh.createRow(1).createCell(1); - a1.setCellValue(1); - Cell a2 = sh.createRow(2).createCell(1); - a2.setCellValue(3); - Cell a3 = sh.createRow(3).createCell(1); - a3.setCellFormula("SUBTOTAL(3,B2:B3)"); - Cell a4 = sh.createRow(4).createCell(1); - a4.setCellValue("POI"); // A4 is string and not counted - /*Cell a5 =*/ sh.createRow(5).createCell(1); // A5 is blank and not counted - - Cell a6 = sh.createRow(6).createCell(1); - a6.setCellFormula("SUBTOTAL(3,B2:B6)*2 + 2"); - Cell a7 = sh.createRow(7).createCell(1); - a7.setCellFormula("SUBTOTAL(3,B2:B7)"); - Cell a8 = sh.createRow(8).createCell(1); - a8.setCellFormula("SUBTOTAL(3,B2,B3,B4,B5,B6,B7,B8)"); - - fe.evaluateAll(); - - assertEquals(2.0, a3.getNumericCellValue()); - assertEquals(8.0, a6.getNumericCellValue()); - assertEquals(3.0, a7.getNumericCellValue()); - assertEquals(3.0, a8.getNumericCellValue()); - } - - public void testMax(){ - - Workbook wb = new HSSFWorkbook(); - - FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); - - Sheet sh = wb.createSheet(); - Cell a1 = sh.createRow(1).createCell(1); - a1.setCellValue(1); - Cell a2 = sh.createRow(2).createCell(1); - a2.setCellValue(3); - Cell a3 = sh.createRow(3).createCell(1); - a3.setCellFormula("SUBTOTAL(4,B2:B3)"); - Cell a4 = sh.createRow(4).createCell(1); - a4.setCellValue(1); - Cell a5 = sh.createRow(5).createCell(1); - a5.setCellValue(7); - Cell a6 = sh.createRow(6).createCell(1); - a6.setCellFormula("SUBTOTAL(4,B2:B6)*2 + 2"); - Cell a7 = sh.createRow(7).createCell(1); - a7.setCellFormula("SUBTOTAL(4,B2:B7)"); - Cell a8 = sh.createRow(8).createCell(1); - a8.setCellFormula("SUBTOTAL(4,B2,B3,B4,B5,B6,B7,B8)"); - - fe.evaluateAll(); - - assertEquals(3.0, a3.getNumericCellValue()); - assertEquals(16.0, a6.getNumericCellValue()); - assertEquals(7.0, a7.getNumericCellValue()); - assertEquals(7.0, a8.getNumericCellValue()); - } - - public void testMin(){ - - Workbook wb = new HSSFWorkbook(); - - FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); - - Sheet sh = wb.createSheet(); - Cell a1 = sh.createRow(1).createCell(1); - a1.setCellValue(1); - Cell a2 = sh.createRow(2).createCell(1); - a2.setCellValue(3); - Cell a3 = sh.createRow(3).createCell(1); - a3.setCellFormula("SUBTOTAL(5,B2:B3)"); - Cell a4 = sh.createRow(4).createCell(1); - a4.setCellValue(1); - Cell a5 = sh.createRow(5).createCell(1); - a5.setCellValue(7); - Cell a6 = sh.createRow(6).createCell(1); - a6.setCellFormula("SUBTOTAL(5,B2:B6)*2 + 2"); - Cell a7 = sh.createRow(7).createCell(1); - a7.setCellFormula("SUBTOTAL(5,B2:B7)"); - Cell a8 = sh.createRow(8).createCell(1); - a8.setCellFormula("SUBTOTAL(5,B2,B3,B4,B5,B6,B7,B8)"); - - fe.evaluateAll(); - - assertEquals(1.0, a3.getNumericCellValue()); - assertEquals(4.0, a6.getNumericCellValue()); - assertEquals(1.0, a7.getNumericCellValue()); - assertEquals(1.0, a8.getNumericCellValue()); - } - - public void testStdev(){ - - Workbook wb = new HSSFWorkbook(); - - FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); - - Sheet sh = wb.createSheet(); - Cell a1 = sh.createRow(1).createCell(1); - a1.setCellValue(1); - Cell a2 = sh.createRow(2).createCell(1); - a2.setCellValue(3); - Cell a3 = sh.createRow(3).createCell(1); - a3.setCellFormula("SUBTOTAL(7,B2:B3)"); - Cell a4 = sh.createRow(4).createCell(1); - a4.setCellValue(1); - Cell a5 = sh.createRow(5).createCell(1); - a5.setCellValue(7); - Cell a6 = sh.createRow(6).createCell(1); - a6.setCellFormula("SUBTOTAL(7,B2:B6)*2 + 2"); - Cell a7 = sh.createRow(7).createCell(1); - a7.setCellFormula("SUBTOTAL(7,B2:B7)"); - Cell a8 = sh.createRow(8).createCell(1); - a8.setCellFormula("SUBTOTAL(7,B2,B3,B4,B5,B6,B7,B8)"); - - fe.evaluateAll(); - - assertEquals(1.41421, a3.getNumericCellValue(), 0.0001); - assertEquals(7.65685, a6.getNumericCellValue(), 0.0001); - assertEquals(2.82842, a7.getNumericCellValue(), 0.0001); - assertEquals(2.82842, a8.getNumericCellValue(), 0.0001); - } - - public void test50209(){ - Workbook wb = new HSSFWorkbook(); - Sheet sh = wb.createSheet(); - Cell a1 = sh.createRow(1).createCell(1); - a1.setCellValue(1); - Cell a2 = sh.createRow(2).createCell(1); - a2.setCellFormula("SUBTOTAL(9,B2)"); - Cell a3 = sh.createRow(3).createCell(1); - a3.setCellFormula("SUBTOTAL(9,B2:B3)"); - - FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); - fe.evaluateAll(); - assertEquals(1.0, a2.getNumericCellValue()); - assertEquals(1.0, a3.getNumericCellValue()); - } - - private static void confirmExpectedResult(FormulaEvaluator evaluator, String msg, Cell cell, double expected) { - - CellValue value = evaluator.evaluate(cell); - if (value.getErrorValue() != 0) - throw new RuntimeException(msg + ": " + value.formatAsString()); - assertEquals(msg, expected, value.getNumberValue()); - } - - public void testFunctionsFromTestSpreadsheet() { - HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook("SubtotalsNested.xls"); - HSSFSheet sheet = workbook.getSheetAt(0); - FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator(); - - assertEquals("B2", 10.0, sheet.getRow(1).getCell(1).getNumericCellValue()); - assertEquals("B3", 20.0, sheet.getRow(2).getCell(1).getNumericCellValue()); - - //Test simple subtotal over one area - Cell cellA3 = sheet.getRow(3).getCell(1); - confirmExpectedResult(evaluator, "B4", cellA3, 30.0); - - //Test existence of the second area - assertNotNull("C2 must not be null", sheet.getRow(1).getCell(2)); - assertEquals("C2", 7.0, sheet.getRow(1).getCell(2).getNumericCellValue()); - - Cell cellC1 = sheet.getRow(1).getCell(3); - Cell cellC2 = sheet.getRow(2).getCell(3); - Cell cellC3 = sheet.getRow(3).getCell(3); - - //Test Functions SUM, COUNT and COUNTA calculation of SUBTOTAL - //a) areas A and B are used - //b) first 2 subtotals don't consider the value of nested subtotal in A3 - confirmExpectedResult(evaluator, "SUBTOTAL(SUM;B2:B8;C2:C8)", cellC1, 37.0); - confirmExpectedResult(evaluator, "SUBTOTAL(COUNT;B2:B8,C2:C8)", cellC2, 3.0); - confirmExpectedResult(evaluator, "SUBTOTAL(COUNTA;B2:B8,C2:C8)", cellC3, 5.0); - } - - public void testUnimplemented(){ - Workbook wb = new HSSFWorkbook(); - - FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); - - Sheet sh = wb.createSheet(); - Cell a3 = sh.createRow(3).createCell(1); - a3.setCellFormula("SUBTOTAL(8,B2:B3)"); - - try { - fe.evaluateAll(); - fail("Should catch an NotImplementedFunctionException here, adjust these tests if it was actually implemented"); - } catch (NotImplementedException e) { - // expected here - } - - a3.setCellFormula("SUBTOTAL(10,B2:B3)"); - - try { - fe.evaluateAll(); - fail("Should catch an NotImplementedFunctionException here, adjust these tests if it was actually implemented"); - } catch (NotImplementedException e) { - // expected here - } - - a3.setCellFormula("SUBTOTAL(11,B2:B3)"); - - try { - fe.evaluateAll(); - fail("Should catch an NotImplementedFunctionException here, adjust these tests if it was actually implemented"); - } catch (NotImplementedException e) { - // expected here - } - - a3.setCellFormula("SUBTOTAL(107,B2:B3)"); - - try { - fe.evaluateAll(); - fail("Should catch an NotImplementedFunctionException here, adjust these tests if it was actually implemented"); - } catch (NotImplementedException e) { - // expected here - } - - a3.setCellFormula("SUBTOTAL(0,B2:B3)"); - fe.evaluateAll(); - assertEquals(FormulaError.VALUE.getCode(), a3.getErrorCellValue()); - - try { - a3.setCellFormula("SUBTOTAL(9)"); - fail("Should catch an exception here"); - } catch (FormulaParseException e) { - // expected here - } - - try { - a3.setCellFormula("SUBTOTAL()"); - fail("Should catch an exception here"); - } catch (FormulaParseException e) { - // expected here - } - - Subtotal subtotal = new Subtotal(); - assertEquals(ErrorEval.VALUE_INVALID, subtotal.evaluate(new ValueEval[] {}, 0, 0)); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestSumif.java b/src/testcases/org/apache/poi/ss/formula/functions/TestSumif.java deleted file mode 100644 index c761d22f1..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestSumif.java +++ /dev/null @@ -1,119 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -import org.apache.poi.ss.formula.eval.AreaEval; -import org.apache.poi.ss.formula.eval.BlankEval; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.NumericValueEval; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; - -/** - * Test cases for SUMPRODUCT() - * - * @author Josh Micich - */ -public final class TestSumif extends TestCase { - private static final NumberEval _30 = new NumberEval(30); - private static final NumberEval _40 = new NumberEval(40); - private static final NumberEval _50 = new NumberEval(50); - private static final NumberEval _60 = new NumberEval(60); - - private static ValueEval invokeSumif(int rowIx, int colIx, ValueEval...args) { - return new Sumif().evaluate(args, rowIx, colIx); - } - private static void confirmDouble(double expected, ValueEval actualEval) { - if(!(actualEval instanceof NumericValueEval)) { - throw new AssertionFailedError("Expected numeric result"); - } - NumericValueEval nve = (NumericValueEval)actualEval; - assertEquals(expected, nve.getNumberValue(), 0); - } - - public void testBasic() { - ValueEval[] arg0values = new ValueEval[] { _30, _30, _40, _40, _50, _50 }; - ValueEval[] arg2values = new ValueEval[] { _30, _40, _50, _60, _60, _60 }; - - AreaEval arg0; - AreaEval arg2; - - arg0 = EvalFactory.createAreaEval("A3:B5", arg0values); - arg2 = EvalFactory.createAreaEval("D1:E3", arg2values); - - confirm(60.0, arg0, new NumberEval(30.0)); - confirm(70.0, arg0, new NumberEval(30.0), arg2); - confirm(100.0, arg0, new StringEval(">45")); - confirm(100.0, arg0, new StringEval(">=45")); - confirm(100.0, arg0, new StringEval(">=50.0")); - confirm(140.0, arg0, new StringEval("<45")); - confirm(140.0, arg0, new StringEval("<=45")); - confirm(140.0, arg0, new StringEval("<=40.0")); - confirm(160.0, arg0, new StringEval("<>40.0")); - confirm(80.0, arg0, new StringEval("=40.0")); - - - } - private static void confirm(double expectedResult, ValueEval...args) { - confirmDouble(expectedResult, invokeSumif(-1, -1, args)); - } - - - /** - * test for bug observed near svn r882931 - */ - public void testCriteriaArgRange() { - ValueEval[] arg0values = new ValueEval[] { _50, _60, _50, _50, _50, _30, }; - ValueEval[] arg1values = new ValueEval[] { _30, _40, _50, _60, }; - - AreaEval arg0; - AreaEval arg1; - ValueEval ve; - - arg0 = EvalFactory.createAreaEval("A3:B5", arg0values); - arg1 = EvalFactory.createAreaEval("A2:D2", arg1values); // single row range - - ve = invokeSumif(0, 2, arg0, arg1); // invoking from cell C1 - if (ve instanceof NumberEval) { - NumberEval ne = (NumberEval) ve; - if (ne.getNumberValue() == 30.0) { - throw new AssertionFailedError("identified error in SUMIF - criteria arg not evaluated properly"); - } - } - - confirmDouble(200, ve); - - arg0 = EvalFactory.createAreaEval("C1:D3", arg0values); - arg1 = EvalFactory.createAreaEval("B1:B4", arg1values); // single column range - - ve = invokeSumif(3, 0, arg0, arg1); // invoking from cell A4 - - confirmDouble(60, ve); - } - - public void testEvaluateException() { - assertEquals(ErrorEval.VALUE_INVALID, invokeSumif(-1, -1, BlankEval.instance, new NumberEval(30.0))); - assertEquals(ErrorEval.VALUE_INVALID, invokeSumif(-1, -1, BlankEval.instance, new NumberEval(30.0), new NumberEval(30.0))); - assertEquals(ErrorEval.VALUE_INVALID, invokeSumif(-1, -1, new NumberEval(30.0), BlankEval.instance, new NumberEval(30.0))); - assertEquals(ErrorEval.VALUE_INVALID, invokeSumif(-1, -1, new NumberEval(30.0), new NumberEval(30.0), BlankEval.instance)); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestSumifs.java b/src/testcases/org/apache/poi/ss/formula/functions/TestSumifs.java deleted file mode 100644 index 3f611cb50..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestSumifs.java +++ /dev/null @@ -1,348 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.ss.formula.functions; - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.usermodel.*; -import org.apache.poi.ss.formula.OperationEvaluationContext; -import org.apache.poi.ss.formula.eval.*; - -/** - * Test cases for SUMIFS() - * - * @author Yegor Kozlov - */ -public final class TestSumifs extends TestCase { - - private static final OperationEvaluationContext EC = new OperationEvaluationContext(null, null, 0, 1, 0, null); - - private static ValueEval invokeSumifs(ValueEval[] args, OperationEvaluationContext ec) { - return new Sumifs().evaluate(args, EC); - } - private static void confirmDouble(double expected, ValueEval actualEval) { - if(!(actualEval instanceof NumericValueEval)) { - throw new AssertionFailedError("Expected numeric result"); - } - NumericValueEval nve = (NumericValueEval)actualEval; - assertEquals(expected, nve.getNumberValue(), 0); - } - - private static void confirm(double expectedResult, ValueEval[] args) { - confirmDouble(expectedResult, invokeSumifs(args, EC)); - } - - /** - * Example 1 from - * http://office.microsoft.com/en-us/excel-help/sumifs-function-HA010047504.aspx - */ - public void testExample1() { - // mimic test sample from http://office.microsoft.com/en-us/excel-help/sumifs-function-HA010047504.aspx - ValueEval[] a2a9 = new ValueEval[] { - new NumberEval(5), - new NumberEval(4), - new NumberEval(15), - new NumberEval(3), - new NumberEval(22), - new NumberEval(12), - new NumberEval(10), - new NumberEval(33) - }; - - ValueEval[] b2b9 = new ValueEval[] { - new StringEval("Apples"), - new StringEval("Apples"), - new StringEval("Artichokes"), - new StringEval("Artichokes"), - new StringEval("Bananas"), - new StringEval("Bananas"), - new StringEval("Carrots"), - new StringEval("Carrots"), - }; - - ValueEval[] c2c9 = new ValueEval[] { - new NumberEval(1), - new NumberEval(2), - new NumberEval(1), - new NumberEval(2), - new NumberEval(1), - new NumberEval(2), - new NumberEval(1), - new NumberEval(2) - }; - - ValueEval[] args; - // "=SUMIFS(A2:A9, B2:B9, "=A*", C2:C9, 1)" - args = new ValueEval[]{ - EvalFactory.createAreaEval("A2:A9", a2a9), - EvalFactory.createAreaEval("B2:B9", b2b9), - new StringEval("A*"), - EvalFactory.createAreaEval("C2:C9", c2c9), - new NumberEval(1), - }; - confirm(20.0, args); - - // "=SUMIFS(A2:A9, B2:B9, "<>Bananas", C2:C9, 1)" - args = new ValueEval[]{ - EvalFactory.createAreaEval("A2:A9", a2a9), - EvalFactory.createAreaEval("B2:B9", b2b9), - new StringEval("<>Bananas"), - EvalFactory.createAreaEval("C2:C9", c2c9), - new NumberEval(1), - }; - confirm(30.0, args); - - // a test case that returns ErrorEval.VALUE_INVALID : - // the dimensions of the first and second criteria ranges are different - // "=SUMIFS(A2:A9, B2:B8, "<>Bananas", C2:C9, 1)" - args = new ValueEval[]{ - EvalFactory.createAreaEval("A2:A9", a2a9), - EvalFactory.createAreaEval("B2:B8", new ValueEval[] { - new StringEval("Apples"), - new StringEval("Apples"), - new StringEval("Artichokes"), - new StringEval("Artichokes"), - new StringEval("Bananas"), - new StringEval("Bananas"), - new StringEval("Carrots"), - }), - new StringEval("<>Bananas"), - EvalFactory.createAreaEval("C2:C9", c2c9), - new NumberEval(1), - }; - assertEquals(ErrorEval.VALUE_INVALID, invokeSumifs(args, EC)); - - } - - /** - * Example 2 from - * http://office.microsoft.com/en-us/excel-help/sumifs-function-HA010047504.aspx - */ - public void testExample2() { - ValueEval[] b2e2 = new ValueEval[] { - new NumberEval(100), - new NumberEval(390), - new NumberEval(8321), - new NumberEval(500) - }; - // 1% 0.5% 3% 4% - ValueEval[] b3e3 = new ValueEval[] { - new NumberEval(0.01), - new NumberEval(0.005), - new NumberEval(0.03), - new NumberEval(0.04) - }; - - // 1% 1.3% 2.1% 2% - ValueEval[] b4e4 = new ValueEval[] { - new NumberEval(0.01), - new NumberEval(0.013), - new NumberEval(0.021), - new NumberEval(0.02) - }; - - // 0.5% 3% 1% 4% - ValueEval[] b5e5 = new ValueEval[] { - new NumberEval(0.005), - new NumberEval(0.03), - new NumberEval(0.01), - new NumberEval(0.04) - }; - - ValueEval[] args; - - // "=SUMIFS(B2:E2, B3:E3, ">3%", B4:E4, ">=2%")" - args = new ValueEval[]{ - EvalFactory.createAreaEval("B2:E2", b2e2), - EvalFactory.createAreaEval("B3:E3", b3e3), - new StringEval(">0.03"), // 3% in the MSFT example - EvalFactory.createAreaEval("B4:E4", b4e4), - new StringEval(">=0.02"), // 2% in the MSFT example - }; - confirm(500.0, args); - } - - /** - * Example 3 from - * http://office.microsoft.com/en-us/excel-help/sumifs-function-HA010047504.aspx - */ - public void testExample3() { - //3.3 0.8 5.5 5.5 - ValueEval[] b2e2 = new ValueEval[] { - new NumberEval(3.3), - new NumberEval(0.8), - new NumberEval(5.5), - new NumberEval(5.5) - }; - // 55 39 39 57.5 - ValueEval[] b3e3 = new ValueEval[] { - new NumberEval(55), - new NumberEval(39), - new NumberEval(39), - new NumberEval(57.5) - }; - - // 6.5 19.5 6 6.5 - ValueEval[] b4e4 = new ValueEval[] { - new NumberEval(6.5), - new NumberEval(19.5), - new NumberEval(6), - new NumberEval(6.5) - }; - - ValueEval[] args; - - // "=SUMIFS(B2:E2, B3:E3, ">=40", B4:E4, "<10")" - args = new ValueEval[]{ - EvalFactory.createAreaEval("B2:E2", b2e2), - EvalFactory.createAreaEval("B3:E3", b3e3), - new StringEval(">=40"), - EvalFactory.createAreaEval("B4:E4", b4e4), - new StringEval("<10"), - }; - confirm(8.8, args); - } - - /** - * Example 5 from - * http://office.microsoft.com/en-us/excel-help/sumifs-function-HA010047504.aspx - * - * Criteria entered as reference and by using wildcard characters - */ - public void testFromFile() { - - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("sumifs.xls"); - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - - HSSFSheet example1 = wb.getSheet("Example 1"); - HSSFCell ex1cell1 = example1.getRow(10).getCell(2); - fe.evaluate(ex1cell1); - assertEquals(20.0, ex1cell1.getNumericCellValue()); - HSSFCell ex1cell2 = example1.getRow(11).getCell(2); - fe.evaluate(ex1cell2); - assertEquals(30.0, ex1cell2.getNumericCellValue()); - - HSSFSheet example2 = wb.getSheet("Example 2"); - HSSFCell ex2cell1 = example2.getRow(6).getCell(2); - fe.evaluate(ex2cell1); - assertEquals(500.0, ex2cell1.getNumericCellValue()); - HSSFCell ex2cell2 = example2.getRow(7).getCell(2); - fe.evaluate(ex2cell2); - assertEquals(8711.0, ex2cell2.getNumericCellValue()); - - HSSFSheet example3 = wb.getSheet("Example 3"); - HSSFCell ex3cell = example3.getRow(5).getCell(2); - fe.evaluate(ex3cell); - assertEquals(8,8, ex3cell.getNumericCellValue()); - - HSSFSheet example4 = wb.getSheet("Example 4"); - HSSFCell ex4cell = example4.getRow(8).getCell(2); - fe.evaluate(ex4cell); - assertEquals(3.5, ex4cell.getNumericCellValue()); - - HSSFSheet example5 = wb.getSheet("Example 5"); - HSSFCell ex5cell = example5.getRow(8).getCell(2); - fe.evaluate(ex5cell); - assertEquals(625000., ex5cell.getNumericCellValue()); - - } - - public void testBug56655() { - ValueEval[] a2a9 = new ValueEval[] { - new NumberEval(5), - new NumberEval(4), - new NumberEval(15), - new NumberEval(3), - new NumberEval(22), - new NumberEval(12), - new NumberEval(10), - new NumberEval(33) - }; - - ValueEval[] args = new ValueEval[]{ - EvalFactory.createAreaEval("A2:A9", a2a9), - ErrorEval.VALUE_INVALID, - new StringEval("A*"), - }; - - ValueEval result = invokeSumifs(args, EC); - assertTrue("Expect to have an error when an input is an invalid value, but had: " + result.getClass(), result instanceof ErrorEval); - - args = new ValueEval[]{ - EvalFactory.createAreaEval("A2:A9", a2a9), - EvalFactory.createAreaEval("A2:A9", a2a9), - ErrorEval.VALUE_INVALID, - }; - - result = invokeSumifs(args, EC); - assertTrue("Expect to have an error when an input is an invalid value, but had: " + result.getClass(), result instanceof ErrorEval); - } - - public void testBug56655b() { -/* - setCellFormula(sheet, 0, 0, "B1*C1"); - sheet.getRow(0).createCell(1).setCellValue("A"); - setCellFormula(sheet, 1, 0, "B1*C1"); - sheet.getRow(1).createCell(1).setCellValue("A"); - setCellFormula(sheet, 0, 3, "SUMIFS(A:A,A:A,A2)"); - */ - ValueEval[] a0a1 = new ValueEval[] { - NumberEval.ZERO, - NumberEval.ZERO - }; - - ValueEval[] args = new ValueEval[]{ - EvalFactory.createAreaEval("A0:A1", a0a1), - EvalFactory.createAreaEval("A0:A1", a0a1), - ErrorEval.VALUE_INVALID - }; - - ValueEval result = invokeSumifs(args, EC); - assertTrue("Expect to have an error when an input is an invalid value, but had: " + result.getClass(), result instanceof ErrorEval); - assertEquals(ErrorEval.VALUE_INVALID, result); - } - - - public void testBug56655c() { -/* - setCellFormula(sheet, 0, 0, "B1*C1"); - sheet.getRow(0).createCell(1).setCellValue("A"); - setCellFormula(sheet, 1, 0, "B1*C1"); - sheet.getRow(1).createCell(1).setCellValue("A"); - setCellFormula(sheet, 0, 3, "SUMIFS(A:A,A:A,A2)"); - */ - ValueEval[] a0a1 = new ValueEval[] { - NumberEval.ZERO, - NumberEval.ZERO - }; - - ValueEval[] args = new ValueEval[]{ - EvalFactory.createAreaEval("A0:A1", a0a1), - EvalFactory.createAreaEval("A0:A1", a0a1), - ErrorEval.NAME_INVALID - }; - - ValueEval result = invokeSumifs(args, EC); - assertTrue("Expect to have an error when an input is an invalid value, but had: " + result.getClass(), result instanceof ErrorEval); - assertEquals(ErrorEval.NAME_INVALID, result); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestSumproduct.java b/src/testcases/org/apache/poi/ss/formula/functions/TestSumproduct.java deleted file mode 100644 index a8ccf4789..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestSumproduct.java +++ /dev/null @@ -1,117 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import junit.framework.TestCase; - -import org.apache.poi.ss.formula.eval.AreaEval; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.NumericValueEval; -import org.apache.poi.ss.formula.eval.RefEval; -import org.apache.poi.ss.formula.eval.ValueEval; - -/** - * Test cases for SUMPRODUCT() - * - * @author Josh Micich - */ -public final class TestSumproduct extends TestCase { - - private static ValueEval invokeSumproduct(ValueEval[] args) { - // srcCellRow and srcCellColumn are ignored by SUMPRODUCT - return new Sumproduct().evaluate(args, -1, (short)-1); - } - private static void confirmDouble(double expected, ValueEval actualEval) { - if(!(actualEval instanceof NumericValueEval)) { - fail("Expected numeric result"); - } - NumericValueEval nve = (NumericValueEval)actualEval; - assertEquals(expected, nve.getNumberValue(), 0); - } - - public void testScalarSimple() { - - RefEval refEval = EvalFactory.createRefEval("A1", new NumberEval(3)); - ValueEval[] args = { - refEval, - new NumberEval(2), - }; - ValueEval result = invokeSumproduct(args); - confirmDouble(6D, result); - } - - public void testAreaSimple() { - ValueEval[] aValues = { - new NumberEval(2), - new NumberEval(4), - new NumberEval(5), - }; - ValueEval[] bValues = { - new NumberEval(3), - new NumberEval(6), - new NumberEval(7), - }; - AreaEval aeA = EvalFactory.createAreaEval("A1:A3", aValues); - AreaEval aeB = EvalFactory.createAreaEval("B1:B3", bValues); - - ValueEval[] args = { aeA, aeB, }; - ValueEval result = invokeSumproduct(args); - confirmDouble(65D, result); - } - - /** - * For scalar products, the terms may be 1x1 area refs - */ - public void testOneByOneArea() { - - AreaEval ae = EvalFactory.createAreaEval("A1:A1", new ValueEval[] { new NumberEval(7), }); - - ValueEval[] args = { - ae, - new NumberEval(2), - }; - ValueEval result = invokeSumproduct(args); - confirmDouble(14D, result); - } - - public void testMismatchAreaDimensions() { - - AreaEval aeA = EvalFactory.createAreaEval("A1:A3", new ValueEval[3]); - AreaEval aeB = EvalFactory.createAreaEval("B1:D1", new ValueEval[3]); - - ValueEval[] args; - args = new ValueEval[] { aeA, aeB, }; - assertEquals(ErrorEval.VALUE_INVALID, invokeSumproduct(args)); - - args = new ValueEval[] { aeA, new NumberEval(5), }; - assertEquals(ErrorEval.VALUE_INVALID, invokeSumproduct(args)); - } - - public void testAreaWithErrorCell() { - ValueEval[] aValues = { - ErrorEval.REF_INVALID, - null, - }; - AreaEval aeA = EvalFactory.createAreaEval("A1:A2", aValues); - AreaEval aeB = EvalFactory.createAreaEval("B1:B2", new ValueEval[2]); - - ValueEval[] args = { aeA, aeB, }; - assertEquals(ErrorEval.REF_INVALID, invokeSumproduct(args)); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestTFunc.java b/src/testcases/org/apache/poi/ss/formula/functions/TestTFunc.java deleted file mode 100644 index 4e1209bfa..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestTFunc.java +++ /dev/null @@ -1,132 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import junit.framework.TestCase; - -import org.apache.poi.ss.formula.eval.AreaEval; -import org.apache.poi.ss.formula.eval.BlankEval; -import org.apache.poi.ss.formula.eval.BoolEval; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; - -/** - * Test cases for Excel function T() - * - * @author Josh Micich - */ -public final class TestTFunc extends TestCase { - - /** - * @return the result of calling function T() with the specified argument - */ - private static ValueEval invokeT(ValueEval arg) { - ValueEval[] args = { arg, }; - ValueEval result = new T().evaluate(args, -1, (short)-1); - assertNotNull("result may never be null", result); - return result; - } - /** - * Simulates call: T(A1) - * where cell A1 has the specified innerValue - */ - private ValueEval invokeTWithReference(ValueEval innerValue) { - ValueEval arg = EvalFactory.createRefEval("$B$2", innerValue); - return invokeT(arg); - } - - private static void confirmText(String text) { - ValueEval arg = new StringEval(text); - ValueEval eval = invokeT(arg); - StringEval se = (StringEval) eval; - assertEquals(text, se.getStringValue()); - } - - public void testTextValues() { - - confirmText("abc"); - confirmText(""); - confirmText(" "); - confirmText("~"); - confirmText("123"); - confirmText("TRUE"); - } - - private static void confirmError(ValueEval arg) { - ValueEval eval = invokeT(arg); - assertTrue(arg == eval); - } - - public void testErrorValues() { - - confirmError(ErrorEval.VALUE_INVALID); - confirmError(ErrorEval.NA); - confirmError(ErrorEval.REF_INVALID); - } - - private static void confirmString(ValueEval eval, String expected) { - assertTrue(eval instanceof StringEval); - assertEquals(expected, ((StringEval)eval).getStringValue()); - } - - private static void confirmOther(ValueEval arg) { - ValueEval eval = invokeT(arg); - confirmString(eval, ""); - } - - public void testOtherValues() { - confirmOther(new NumberEval(2)); - confirmOther(BoolEval.FALSE); - confirmOther(BlankEval.instance); // can this particular case be verified? - } - - public void testRefValues() { - ValueEval eval; - - eval = invokeTWithReference(new StringEval("def")); - confirmString(eval, "def"); - eval = invokeTWithReference(new StringEval(" ")); - confirmString(eval, " "); - - eval = invokeTWithReference(new NumberEval(2)); - confirmString(eval, ""); - eval = invokeTWithReference(BoolEval.TRUE); - confirmString(eval, ""); - - eval = invokeTWithReference(ErrorEval.NAME_INVALID); - assertTrue(eval == ErrorEval.NAME_INVALID); - } - - public void testAreaArg() { - ValueEval[] areaValues = new ValueEval[] { - new StringEval("abc"), new StringEval("def"), - new StringEval("ghi"), new StringEval("jkl"), - }; - AreaEval ae = EvalFactory.createAreaEval("C10:D11", areaValues); - - ValueEval ve; - ve = invokeT(ae); - confirmString(ve, "abc"); - - areaValues[0] = new NumberEval(5.0); - ve = invokeT(ae); - confirmString(ve, ""); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestText.java b/src/testcases/org/apache/poi/ss/formula/functions/TestText.java deleted file mode 100644 index 0e6521ef2..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestText.java +++ /dev/null @@ -1,139 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.Assert.assertEquals; - -import java.text.DateFormatSymbols; -import java.text.DecimalFormatSymbols; -import java.text.SimpleDateFormat; -import java.util.TimeZone; - -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.util.LocaleUtil; -import org.junit.Test; - -/** - * Test case for TEXT() - */ -public final class TestText { - @Test - public void testTextWithStringFirstArg() { - ValueEval strArg = new StringEval("abc"); - ValueEval formatArg = new StringEval("abc"); - ValueEval[] args = { strArg, formatArg }; - ValueEval result = TextFunction.TEXT.evaluate(args, -1, (short)-1); - assertEquals(ErrorEval.VALUE_INVALID, result); - } - - @Test - public void testTextWithDeciamlFormatSecondArg() { - ValueEval numArg = new NumberEval(321321.321); - ValueEval formatArg = new StringEval("#,###.00000"); - ValueEval[] args = { numArg, formatArg }; - ValueEval result = TextFunction.TEXT.evaluate(args, -1, (short)-1); - DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(LocaleUtil.getUserLocale()); - char groupSeparator = dfs.getGroupingSeparator(); - char decimalSeparator = dfs.getDecimalSeparator(); - ValueEval testResult = new StringEval("321" + groupSeparator + "321" + decimalSeparator + "32100"); - assertEquals(testResult.toString(), result.toString()); - numArg = new NumberEval(321.321); - formatArg = new StringEval("00000.00000"); - args[0] = numArg; - args[1] = formatArg; - result = TextFunction.TEXT.evaluate(args, -1, (short)-1); - testResult = new StringEval("00321" + decimalSeparator + "32100"); - assertEquals(testResult.toString(), result.toString()); - - formatArg = new StringEval("$#.#"); - args[1] = formatArg; - result = TextFunction.TEXT.evaluate(args, -1, (short)-1); - testResult = new StringEval("$321" + decimalSeparator + "3"); - assertEquals(testResult.toString(), result.toString()); - } - - @Test - public void testTextWithFractionFormatSecondArg() { - ValueEval numArg = new NumberEval(321.321); - ValueEval formatArg = new StringEval("# #/#"); - ValueEval[] args = { numArg, formatArg }; - ValueEval result = TextFunction.TEXT.evaluate(args, -1, (short)-1); - ValueEval testResult = new StringEval("321 1/3"); - assertEquals(testResult.toString(), result.toString()); - - formatArg = new StringEval("# #/##"); - args[1] = formatArg; - result = TextFunction.TEXT.evaluate(args, -1, (short)-1); - testResult = new StringEval("321 26/81"); - assertEquals(testResult.toString(), result.toString()); - - formatArg = new StringEval("#/##"); - args[1] = formatArg; - result = TextFunction.TEXT.evaluate(args, -1, (short)-1); - testResult = new StringEval("26027/81"); - assertEquals(testResult.toString(), result.toString()); - } - - @Test - public void testTextWithDateFormatSecondArg() { - TimeZone userTZ = LocaleUtil.getUserTimeZone(); - LocaleUtil.setUserTimeZone(TimeZone.getTimeZone("CET")); - try { - // Test with Java style M=Month - ValueEval numArg = new NumberEval(321.321); - ValueEval formatArg = new StringEval("dd:MM:yyyy hh:mm:ss"); - ValueEval[] args = { numArg, formatArg }; - ValueEval result = TextFunction.TEXT.evaluate(args, -1, (short)-1); - ValueEval testResult = new StringEval("16:11:1900 07:42:14"); - assertEquals(testResult.toString(), result.toString()); - - // Excel also supports "m before h is month" - formatArg = new StringEval("dd:mm:yyyy hh:mm:ss"); - args[1] = formatArg; - result = TextFunction.TEXT.evaluate(args, -1, (short)-1); - testResult = new StringEval("16:11:1900 07:42:14"); - assertEquals(testResult.toString(), result.toString()); - - // this line is intended to compute how "November" would look like in the current locale - // update: now the locale will be (if not set otherwise) always Locale.getDefault() (see LocaleUtil) - DateFormatSymbols dfs = DateFormatSymbols.getInstance(LocaleUtil.getUserLocale()); - SimpleDateFormat sdf = new SimpleDateFormat("MMMM", dfs); - sdf.setTimeZone(LocaleUtil.getUserTimeZone()); - String november = sdf.format(LocaleUtil.getLocaleCalendar(2015,10,1).getTime()); - - // Again with Java style - formatArg = new StringEval("MMMM dd, yyyy"); - args[1] = formatArg; - result = TextFunction.TEXT.evaluate(args, -1, (short)-1); - testResult = new StringEval(november + " 16, 1900"); - assertEquals(testResult.toString(), result.toString()); - - // And Excel style - formatArg = new StringEval("mmmm dd, yyyy"); - args[1] = formatArg; - result = TextFunction.TEXT.evaluate(args, -1, (short)-1); - testResult = new StringEval(november + " 16, 1900"); - assertEquals(testResult.toString(), result.toString()); - } finally { - LocaleUtil.setUserTimeZone(userTZ); - } - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestTime.java b/src/testcases/org/apache/poi/ss/formula/functions/TestTime.java deleted file mode 100644 index 7f12c136a..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestTime.java +++ /dev/null @@ -1,124 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import static org.junit.Assert.assertEquals; - -import java.util.regex.Pattern; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFCellStyle; -import org.apache.poi.hssf.usermodel.HSSFDataFormat; -import org.apache.poi.hssf.usermodel.HSSFDataFormatter; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.junit.Before; -import org.junit.Test; - -/** - * Tests for {@link TimeFunc} - */ -public final class TestTime { - - private static final int SECONDS_PER_MINUTE = 60; - private static final int SECONDS_PER_HOUR = 60 * SECONDS_PER_MINUTE; - private static final double SECONDS_PER_DAY = 24 * SECONDS_PER_HOUR; - private HSSFCell cell11; - private HSSFFormulaEvaluator evaluator; - private HSSFWorkbook wb; - private HSSFDataFormatter form; - private HSSFCellStyle style; - - @Before - public void setUp() { - wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet("new sheet"); - style = wb.createCellStyle(); - HSSFDataFormat fmt = wb.createDataFormat(); - style.setDataFormat(fmt.getFormat("hh:mm:ss")); - - cell11 = sheet.createRow(0).createCell(0); - form = new HSSFDataFormatter(); - - evaluator = new HSSFFormulaEvaluator(wb); - } - - @Test - public void testSomeArgumentsMissing() { - confirm("00:00:00", "TIME(, 0, 0)"); - confirm("12:00:00", "TIME(12, , )"); - } - - @Test - public void testValid() { - confirm("00:00:01", 0, 0, 1); - confirm("00:01:00", 0, 1, 0); - - confirm("00:00:00", 0, 0, 0); - - confirm("01:00:00", 1, 0, 0); - confirm("12:00:00", 12, 0, 0); - confirm("23:00:00", 23, 0, 0); - confirm("00:00:00", 24, 0, 0); - confirm("01:00:00", 25, 0, 0); - confirm("00:00:00", 48, 0, 0); - confirm("06:00:00", 6, 0, 0); - confirm("06:01:00", 6, 1, 0); - confirm("06:30:00", 6, 30, 0); - - confirm("06:59:00", 6, 59, 0); - confirm("07:00:00", 6, 60, 0); - confirm("07:01:00", 6, 61, 0); - confirm("08:00:00", 6, 120, 0); - confirm("06:00:00", 6, 1440, 0); - confirm("18:49:00", 18, 49, 0); - confirm("18:49:01", 18, 49, 1); - confirm("18:49:30", 18, 49, 30); - confirm("18:49:59", 18, 49, 59); - confirm("18:50:00", 18, 49, 60); - confirm("18:50:01", 18, 49, 61); - confirm("18:50:59", 18, 49, 119); - confirm("18:51:00", 18, 49, 120); - confirm("03:55:07", 18, 49, 32767); - confirm("12:08:01", 18, 32767, 61); - confirm("07:50:01", 32767, 49, 61); - } - private void confirm(String expectedTimeStr, int inH, int inM, int inS) { - confirm(expectedTimeStr, "TIME(" + inH + "," + inM + "," + inS + ")"); - } - - private void confirm(String expectedTimeStr, String formulaText) { - String[] parts = Pattern.compile(":").split(expectedTimeStr); - int expH = Integer.parseInt(parts[0]); - int expM = Integer.parseInt(parts[1]); - int expS = Integer.parseInt(parts[2]); - - double expectedValue = (expH*SECONDS_PER_HOUR + expM*SECONDS_PER_MINUTE + expS)/SECONDS_PER_DAY; - - cell11.setCellFormula(formulaText); - cell11.setCellStyle(style); - evaluator.clearAllCachedResultValues(); - - double actualValue = evaluator.evaluate(cell11).getNumberValue(); - assertEquals(expectedValue, actualValue, 0.0); - - String actualText = form.formatCellValue(cell11, evaluator); - assertEquals(expectedTimeStr, actualText); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestTrim.java b/src/testcases/org/apache/poi/ss/formula/functions/TestTrim.java deleted file mode 100644 index bb5efa728..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestTrim.java +++ /dev/null @@ -1,78 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import junit.framework.TestCase; - -import org.apache.poi.ss.formula.eval.BlankEval; -import org.apache.poi.ss.formula.eval.BoolEval; -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; -/** - * Tests for Excel function TRIM() - * - * @author Josh Micich - */ -public final class TestTrim extends TestCase { - - - private static ValueEval invokeTrim(ValueEval text) { - ValueEval[] args = new ValueEval[] { text, }; - return TextFunction.TRIM.evaluate(args, -1, (short)-1); - } - - private void confirmTrim(ValueEval text, String expected) { - ValueEval result = invokeTrim(text); - assertEquals(StringEval.class, result.getClass()); - assertEquals(expected, ((StringEval)result).getStringValue()); - } - - private void confirmTrim(ValueEval text, ErrorEval expectedError) { - ValueEval result = invokeTrim(text); - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(expectedError.getErrorCode(), ((ErrorEval)result).getErrorCode()); - } - - public void testBasic() { - - confirmTrim(new StringEval(" hi "), "hi"); - confirmTrim(new StringEval("hi "), "hi"); - confirmTrim(new StringEval(" hi"), "hi"); - confirmTrim(new StringEval(" hi there "), "hi there"); - confirmTrim(new StringEval(""), ""); - confirmTrim(new StringEval(" "), ""); - } - - /** - * Valid cases where text arg is not exactly a string - */ - public void testUnusualArgs() { - - // text (first) arg type is number, other args are strings with fractional digits - confirmTrim(new NumberEval(123456), "123456"); - confirmTrim(BoolEval.FALSE, "FALSE"); - confirmTrim(BoolEval.TRUE, "TRUE"); - confirmTrim(BlankEval.instance, ""); - } - - public void testErrors() { - confirmTrim(ErrorEval.NAME_INVALID, ErrorEval.NAME_INVALID); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestTrunc.java b/src/testcases/org/apache/poi/ss/formula/functions/TestTrunc.java deleted file mode 100644 index 91bb8e7d7..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestTrunc.java +++ /dev/null @@ -1,66 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.StringEval; - -/** - * Test case for TRUNC() - * - * @author Stephen Wolke (smwolke at geistig.com) - */ -public final class TestTrunc extends AbstractNumericTestCase { - private static final NumericFunction F = null; - public void testTruncWithStringArg() { - - ValueEval strArg = new StringEval("abc"); - ValueEval[] args = { strArg, new NumberEval(2) }; - ValueEval result = NumericFunction.TRUNC.evaluate(args, -1, (short)-1); - assertEquals(ErrorEval.VALUE_INVALID, result); - } - - public void testTruncWithWholeNumber() { - ValueEval[] args = { new NumberEval(200), new NumberEval(2) }; - @SuppressWarnings("static-access") - ValueEval result = F.TRUNC.evaluate(args, -1, (short)-1); - assertEquals("TRUNC", (new NumberEval(200d)).getNumberValue(), ((NumberEval)result).getNumberValue()); - } - - public void testTruncWithDecimalNumber() { - ValueEval[] args = { new NumberEval(2.612777), new NumberEval(3) }; - @SuppressWarnings("static-access") - ValueEval result = F.TRUNC.evaluate(args, -1, (short)-1); - assertEquals("TRUNC", (new NumberEval(2.612d)).getNumberValue(), ((NumberEval)result).getNumberValue()); - } - - public void testTruncWithDecimalNumberOneArg() { - ValueEval[] args = { new NumberEval(2.612777) }; - ValueEval result = NumericFunction.TRUNC.evaluate(args, -1, (short)-1); - assertEquals("TRUNC", (new NumberEval(2d)).getNumberValue(), ((NumberEval)result).getNumberValue()); - } - - public void testNegative() { - ValueEval[] args = { new NumberEval(-8.9), new NumberEval(0) }; - @SuppressWarnings("static-access") - ValueEval result = F.TRUNC.evaluate(args, -1, (short)-1); - assertEquals("TRUNC", (new NumberEval(-8)).getNumberValue(), ((NumberEval)result).getNumberValue()); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestValue.java b/src/testcases/org/apache/poi/ss/formula/functions/TestValue.java deleted file mode 100644 index fb18a95a6..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestValue.java +++ /dev/null @@ -1,94 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import junit.framework.TestCase; - -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.StringEval; -import org.apache.poi.ss.formula.eval.ValueEval; - -/** - * Tests for {@link Value} - */ -public final class TestValue extends TestCase { - - private static ValueEval invokeValue(String strText) { - ValueEval[] args = new ValueEval[] { new StringEval(strText), }; - return new Value().evaluate(args, -1, (short) -1); - } - - private static void confirmValue(String strText, double expected) { - ValueEval result = invokeValue(strText); - assertEquals(NumberEval.class, result.getClass()); - assertEquals(expected, ((NumberEval) result).getNumberValue(), 0.0); - } - - private static void confirmValueError(String strText) { - ValueEval result = invokeValue(strText); - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(ErrorEval.VALUE_INVALID, result); - } - - public void testBasic() { - - confirmValue("100", 100); - confirmValue("-2.3", -2.3); - confirmValue(".5", 0.5); - confirmValue(".5e2", 50); - confirmValue(".5e-2", 0.005); - confirmValue(".5e+2", 50); - confirmValue("+5", 5); - confirmValue("$1,000", 1000); - confirmValue("100.5e1", 1005); - confirmValue("1,0000", 10000); - confirmValue("1,000,0000", 10000000); - confirmValue("1,000,0000,00000", 1000000000000.0); - confirmValue(" 100 ", 100); - confirmValue(" + 100", 100); - confirmValue("10000", 10000); - confirmValue("$-5", -5); - confirmValue("$.5", 0.5); - confirmValue("123e+5", 12300000); - confirmValue("1,000e2", 100000); - confirmValue("$10e2", 1000); - confirmValue("$1,000e2", 100000); - confirmValue("30%", 0.3); - confirmValue("30 %", 0.3); - } - - public void testErrors() { - confirmValueError("1+1"); - confirmValueError("1 1"); - confirmValueError("1,00.0"); - confirmValueError("1,00"); - confirmValueError("$1,00.5e1"); - confirmValueError("1,00.5e1"); - confirmValueError("1,0,000"); - confirmValueError("1,00,000"); - confirmValueError("++100"); - confirmValueError("$$5"); - confirmValueError("-"); - confirmValueError("+"); - confirmValueError("$"); - confirmValueError(",300"); - confirmValueError("0.233,4"); - confirmValueError("1e2.5"); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestWeekNumFunctionsFromSpreadsheet.java b/src/testcases/org/apache/poi/ss/formula/functions/TestWeekNumFunctionsFromSpreadsheet.java deleted file mode 100644 index cf70a993d..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestWeekNumFunctionsFromSpreadsheet.java +++ /dev/null @@ -1,32 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import java.util.Collection; - -import org.junit.runners.Parameterized.Parameters; - -/** - * Tests WeekNum() as loaded from a test data spreadsheet.

    - */ -public class TestWeekNumFunctionsFromSpreadsheet extends BaseTestFunctionsFromSpreadsheet { - @Parameters(name="{0}") - public static Collection data() throws Exception { - return data(TestWeekNumFunctionsFromSpreadsheet.class, "WeekNumFunctionTestCaseData.xls"); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestWeekNumFunctionsFromSpreadsheet2013.java b/src/testcases/org/apache/poi/ss/formula/functions/TestWeekNumFunctionsFromSpreadsheet2013.java deleted file mode 100644 index 6d104efca..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestWeekNumFunctionsFromSpreadsheet2013.java +++ /dev/null @@ -1,33 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import java.util.Collection; - -import org.junit.runners.Parameterized.Parameters; - -/** - * Tests WeekNum() as loaded from a test data 2013 excel spreadsheet.

    - */ -public class TestWeekNumFunctionsFromSpreadsheet2013 extends BaseTestFunctionsFromSpreadsheet { - @Parameters(name="{0}") - public static Collection data() throws Exception { - //Only open this file with Excel 2013 to keep binary specific to that version - return data(TestWeekNumFunctionsFromSpreadsheet2013.class, "WeekNumFunctionTestCaseData2013.xls"); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestWeekdayFunc.java b/src/testcases/org/apache/poi/ss/formula/functions/TestWeekdayFunc.java deleted file mode 100644 index a3d9511d1..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestWeekdayFunc.java +++ /dev/null @@ -1,93 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import org.apache.poi.ss.formula.eval.*; -import org.apache.poi.util.StringUtil; -import org.junit.Test; - -import static org.junit.Assert.*; - -/** - * Tests WEEKDAY(serial_number[, return_type]) excep function - * https://support.office.com/en-us/article/WEEKDAY-function-60E44483-2ED1-439F-8BD0-E404C190949A - */ -public class TestWeekdayFunc { - private static final double TOLERANCE = 0.001; - - private void assertEvaluateEquals(double expected, double serial_number) { - String formula = "WEEKDAY(" + serial_number + ")"; - ValueEval[] args = new ValueEval[] { new NumberEval(serial_number) }; - NumberEval result = (NumberEval) WeekdayFunc.instance.evaluate(args, 0, 0); - assertEquals(formula, expected, result.getNumberValue(), TOLERANCE); - } - private void assertEvaluateEquals(double expected, double serial_number, double return_type) { - String formula = "WEEKDAY(" + serial_number + ", " + return_type + ")"; - ValueEval[] args = new ValueEval[] { new NumberEval(serial_number), new NumberEval(return_type) }; - NumberEval result = (NumberEval) WeekdayFunc.instance.evaluate(args, 0, 0); - assertEquals(formula, expected, result.getNumberValue(), TOLERANCE); - } - - - @Test - public void testEvaluate() throws Exception { - assertEvaluateEquals(2.0, 1.0); - assertEvaluateEquals(2.0, 1.0, 1.0); - assertEvaluateEquals(1.0, 1.0, 2.0); - assertEvaluateEquals(0.0, 1.0, 3.0); - assertEvaluateEquals(1.0, 1.0, 11.0); - assertEvaluateEquals(7.0, 1.0, 12.0); - assertEvaluateEquals(6.0, 1.0, 13.0); - assertEvaluateEquals(5.0, 1.0, 14.0); - assertEvaluateEquals(4.0, 1.0, 15.0); - assertEvaluateEquals(3.0, 1.0, 16.0); - assertEvaluateEquals(2.0, 1.0, 17.0); - - - assertEvaluateEquals(3.0, 39448.0); - assertEvaluateEquals(3.0, 39448.0, 1.0); - assertEvaluateEquals(2.0, 39448.0, 2.0); - assertEvaluateEquals(1.0, 39448.0, 3.0); - assertEvaluateEquals(2.0, 39448.0, 11.0); - assertEvaluateEquals(1.0, 39448.0, 12.0); - assertEvaluateEquals(7.0, 39448.0, 13.0); - assertEvaluateEquals(6.0, 39448.0, 14.0); - assertEvaluateEquals(5.0, 39448.0, 15.0); - assertEvaluateEquals(4.0, 39448.0, 16.0); - assertEvaluateEquals(3.0, 39448.0, 17.0); - } - - // for testing invalid invocations - private void assertEvaluateEquals(String message, ErrorEval expected, ValueEval... args) { - String formula = "WEEKDAY(" + StringUtil.join(args, ", ") + ")"; - ValueEval result = WeekdayFunc.instance.evaluate(args, 0, 0); - assertEquals(formula + ": " + message, expected, result); - } - - @Test - public void testEvaluateInvalid() throws Exception { - assertEvaluateEquals("no args", ErrorEval.VALUE_INVALID); - assertEvaluateEquals("too many args", ErrorEval.VALUE_INVALID, new NumberEval(1.0), new NumberEval(1.0), new NumberEval(1.0)); - assertEvaluateEquals("negative date", ErrorEval.NUM_ERROR, new NumberEval(-1.0)); - assertEvaluateEquals("cannot coerce serial_number to number", ErrorEval.VALUE_INVALID, new StringEval("")); - assertEvaluateEquals("cannot coerce return_type to number", ErrorEval.VALUE_INVALID, new StringEval("1"), new StringEval("")); - assertEvaluateEquals("return_type is blank", ErrorEval.NUM_ERROR, new StringEval("2"), BlankEval.instance); - assertEvaluateEquals("return_type is missing", ErrorEval.NUM_ERROR, new StringEval("3"), MissingArgEval.instance); - assertEvaluateEquals("invalid return_type", ErrorEval.NUM_ERROR, new NumberEval(1.0), new NumberEval(18.0)); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/functions/TestXYNumericFunction.java b/src/testcases/org/apache/poi/ss/formula/functions/TestXYNumericFunction.java deleted file mode 100644 index cc7f91a99..000000000 --- a/src/testcases/org/apache/poi/ss/formula/functions/TestXYNumericFunction.java +++ /dev/null @@ -1,135 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.functions; - -import junit.framework.TestCase; - -import org.apache.poi.ss.formula.eval.ErrorEval; -import org.apache.poi.ss.formula.eval.NumberEval; -import org.apache.poi.ss.formula.eval.ValueEval; -/** - * Tests for Excel functions SUMX2MY2(), SUMX2PY2(), SUMXMY2() - * - * @author Josh Micich - */ -public final class TestXYNumericFunction extends TestCase { - private static final Function SUM_SQUARES = new Sumx2py2(); - private static final Function DIFF_SQUARES = new Sumx2my2(); - private static final Function SUM_SQUARES_OF_DIFFS = new Sumxmy2(); - - private static ValueEval invoke(Function function, ValueEval xArray, ValueEval yArray) { - ValueEval[] args = new ValueEval[] { xArray, yArray, }; - return function.evaluate(args, -1, (short)-1); - } - - private void confirm(Function function, ValueEval xArray, ValueEval yArray, double expected) { - ValueEval result = invoke(function, xArray, yArray); - assertEquals(NumberEval.class, result.getClass()); - assertEquals(expected, ((NumberEval)result).getNumberValue(), 0); - } - private void confirmError(Function function, ValueEval xArray, ValueEval yArray, ErrorEval expectedError) { - ValueEval result = invoke(function, xArray, yArray); - assertEquals(ErrorEval.class, result.getClass()); - assertEquals(expectedError.getErrorCode(), ((ErrorEval)result).getErrorCode()); - } - - private void confirmError(ValueEval xArray, ValueEval yArray, ErrorEval expectedError) { - confirmError(SUM_SQUARES, xArray, yArray, expectedError); - confirmError(DIFF_SQUARES, xArray, yArray, expectedError); - confirmError(SUM_SQUARES_OF_DIFFS, xArray, yArray, expectedError); - } - - public void testBasic() { - ValueEval[] xValues = { - new NumberEval(1), - new NumberEval(2), - }; - ValueEval areaEvalX = createAreaEval(xValues); - confirm(SUM_SQUARES, areaEvalX, areaEvalX, 10.0); - confirm(DIFF_SQUARES, areaEvalX, areaEvalX, 0.0); - confirm(SUM_SQUARES_OF_DIFFS, areaEvalX, areaEvalX, 0.0); - - ValueEval[] yValues = { - new NumberEval(3), - new NumberEval(4), - }; - ValueEval areaEvalY = createAreaEval(yValues); - confirm(SUM_SQUARES, areaEvalX, areaEvalY, 30.0); - confirm(DIFF_SQUARES, areaEvalX, areaEvalY, -20.0); - confirm(SUM_SQUARES_OF_DIFFS, areaEvalX, areaEvalY, 8.0); - } - - /** - * number of items in array is not limited to 30 - */ - public void testLargeArrays() { - ValueEval[] xValues = createMockNumberArray(100, 3); - ValueEval[] yValues = createMockNumberArray(100, 2); - - confirm(SUM_SQUARES, createAreaEval(xValues), createAreaEval(yValues), 1300.0); - confirm(DIFF_SQUARES, createAreaEval(xValues), createAreaEval(yValues), 500.0); - confirm(SUM_SQUARES_OF_DIFFS, createAreaEval(xValues), createAreaEval(yValues), 100.0); - } - - - private ValueEval[] createMockNumberArray(int size, double value) { - ValueEval[] result = new ValueEval[size]; - for (int i = 0; i < result.length; i++) { - result[i] = new NumberEval(value); - } - return result; - } - - private static ValueEval createAreaEval(ValueEval[] values) { - String refStr = "A1:A" + values.length; - return EvalFactory.createAreaEval(refStr, values); - } - - public void testErrors() { - ValueEval[] xValues = { - ErrorEval.REF_INVALID, - new NumberEval(2), - }; - ValueEval areaEvalX = createAreaEval(xValues); - ValueEval[] yValues = { - new NumberEval(2), - ErrorEval.NULL_INTERSECTION, - }; - ValueEval areaEvalY = createAreaEval(yValues); - ValueEval[] zValues = { // wrong size - new NumberEval(2), - }; - ValueEval areaEvalZ = createAreaEval(zValues); - - // if either arg is an error, that error propagates - confirmError(ErrorEval.REF_INVALID, ErrorEval.NAME_INVALID, ErrorEval.REF_INVALID); - confirmError(areaEvalX, ErrorEval.NAME_INVALID, ErrorEval.NAME_INVALID); - confirmError(ErrorEval.NAME_INVALID, areaEvalX, ErrorEval.NAME_INVALID); - - // array sizes must match - confirmError(areaEvalX, areaEvalZ, ErrorEval.NA); - confirmError(areaEvalZ, areaEvalY, ErrorEval.NA); - - // any error in an array item propagates up - confirmError(areaEvalX, areaEvalX, ErrorEval.REF_INVALID); - - // search for errors array by array, not pair by pair - confirmError(areaEvalX, areaEvalY, ErrorEval.REF_INVALID); - confirmError(areaEvalY, areaEvalX, ErrorEval.NULL_INTERSECTION); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/ptg/AbstractPtgTestCase.java b/src/testcases/org/apache/poi/ss/formula/ptg/AbstractPtgTestCase.java deleted file mode 100644 index 202a9e06c..000000000 --- a/src/testcases/org/apache/poi/ss/formula/ptg/AbstractPtgTestCase.java +++ /dev/null @@ -1,51 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.ptg; - -import junit.framework.TestCase; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; - -/** - * Convenient abstract class to reduce the amount of boilerplate code needed - * in ptg-related unit tests. - * - * @author Daniel Noll (daniel at nuix dot com dot au) - */ -public abstract class AbstractPtgTestCase extends TestCase { - - /** - * Loads a workbook from the given filename in the test data dir. - * - * @param sampleFileName the filename. - * @return the loaded workbook. - */ - protected static final HSSFWorkbook loadWorkbook(String sampleFileName) { - return HSSFTestDataSamples.openSampleWorkbook(sampleFileName); - } - - /** - * Creates a new Workbook and adds one sheet with the specified name - */ - protected static final HSSFWorkbook createWorkbookWithSheet(String sheetName) { - HSSFWorkbook book = new HSSFWorkbook(); - book.createSheet(sheetName); - return book; - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/ptg/AllFormulaTests.java b/src/testcases/org/apache/poi/ss/formula/ptg/AllFormulaTests.java deleted file mode 100644 index 93797a74f..000000000 --- a/src/testcases/org/apache/poi/ss/formula/ptg/AllFormulaTests.java +++ /dev/null @@ -1,54 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.ptg; - -import org.apache.poi.ss.formula.TestSheetNameFormatter; -import org.apache.poi.ss.formula.eval.AllFormulaEvalTests; -import org.apache.poi.ss.formula.function.AllFormulaFunctionTests; -import org.apache.poi.ss.formula.functions.AllIndividualFunctionEvaluationTests; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -/** - * Collects all tests for org.apache.poi.hssf.record.formula. - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - AllFormulaEvalTests.class, - AllFormulaFunctionTests.class, - AllIndividualFunctionEvaluationTests.class, - TestArea3DPtg.class, - TestAreaErrPtg.class, - TestAreaPtg.class, - TestArrayPtg.class, - TestAttrPtg.class, - TestErrPtg.class, - TestExternalFunctionFormulas.class, - //TestFormulaShifter.class, //converted to junit4 - TestFuncPtg.class, - TestFuncVarPtg.class, - TestIntersectionPtg.class, - TestPercentPtg.class, - TestRangePtg.class, - TestRef3DPtg.class, - TestReferencePtg.class, - TestSheetNameFormatter.class, - TestUnionPtg.class -}) -public class AllFormulaTests { -} diff --git a/src/testcases/org/apache/poi/ss/formula/ptg/TestArea3DPtg.java b/src/testcases/org/apache/poi/ss/formula/ptg/TestArea3DPtg.java deleted file mode 100644 index bb11807e5..000000000 --- a/src/testcases/org/apache/poi/ss/formula/ptg/TestArea3DPtg.java +++ /dev/null @@ -1,48 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.ptg; - -import org.apache.poi.hssf.usermodel.HSSFEvaluationWorkbook; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; - -/** - * Tests for Area3DPtg - * - * @author Josh Micich - */ -public final class TestArea3DPtg extends AbstractPtgTestCase { - - /** - * confirms that sheet names get properly escaped - */ - public void testToFormulaString() { - - Area3DPtg target = new Area3DPtg("A1:B1", (short)0); - - String sheetName = "my sheet"; - HSSFWorkbook wb = createWorkbookWithSheet(sheetName); - HSSFEvaluationWorkbook book = HSSFEvaluationWorkbook.create(wb); - assertEquals("'my sheet'!A1:B1", target.toFormulaString(book)); - - wb.setSheetName(0, "Sheet1"); - assertEquals("Sheet1!A1:B1", target.toFormulaString(book)); - - wb.setSheetName(0, "C64"); - assertEquals("'C64'!A1:B1", target.toFormulaString(book)); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/ptg/TestAreaErrPtg.java b/src/testcases/org/apache/poi/ss/formula/ptg/TestAreaErrPtg.java deleted file mode 100644 index e8032cb23..000000000 --- a/src/testcases/org/apache/poi/ss/formula/ptg/TestAreaErrPtg.java +++ /dev/null @@ -1,36 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.ptg; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; - -/** - * Tests for {@link AreaErrPtg}. - * - * @author Daniel Noll (daniel at nuix dot com dot au) - */ -public final class TestAreaErrPtg extends AbstractPtgTestCase { - /** - * Tests reading a file containing this ptg. - */ - public void testReading() { - HSSFWorkbook workbook = loadWorkbook("AreaErrPtg.xls"); - assertEquals("Wrong formula string for area error", "SUM(#REF!)", - workbook.getSheetAt(0).getRow(0).getCell(2).getCellFormula()); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/ptg/TestAreaPtg.java b/src/testcases/org/apache/poi/ss/formula/ptg/TestAreaPtg.java deleted file mode 100644 index 559dd8c72..000000000 --- a/src/testcases/org/apache/poi/ss/formula/ptg/TestAreaPtg.java +++ /dev/null @@ -1,143 +0,0 @@ - -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.ptg; - -import junit.framework.TestCase; - -import org.apache.poi.hssf.model.HSSFFormulaParser; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; - -/** - * Tests for {@link AreaPtg}. - * - * @author Dmitriy Kumshayev - */ -public final class TestAreaPtg extends TestCase { - - AreaPtg relative; - AreaPtg absolute; - - @Override - protected void setUp() { - short firstRow=5; - short lastRow=13; - short firstCol=7; - short lastCol=17; - relative = new AreaPtg(firstRow,lastRow,firstCol,lastCol,true,true,true,true); - absolute = new AreaPtg(firstRow,lastRow,firstCol,lastCol,false,false,false,false); - } - - public static void testSortTopLeftToBottomRight() { - AreaPtg ptg = new AreaPtg("A$1:$B5"); - assertEquals("A$1:$B5", ptg.toFormulaString()); - ptg.setFirstColumn(3); - assertEquals("Area Ptg should not implicitly re-sort itself (except during construction)", - "D$1:$B5", ptg.toFormulaString()); - ptg.sortTopLeftToBottomRight(); - assertEquals("Area Ptg should restore itself to top-left to lower-right order when explicitly asked", - "$B$1:D5", ptg.toFormulaString()); - } - - public void testSetColumnsAbsolute() - { - resetColumns(absolute); - validateReference(true, absolute); - } - public void testSetColumnsRelative() - { - resetColumns(relative); - validateReference(false, relative); - } - - private void validateReference(boolean abs, AreaPtg ref) - { - assertEquals("First column reference is not "+(abs?"absolute":"relative"),abs,!ref.isFirstColRelative()); - assertEquals("Last column reference is not "+(abs?"absolute":"relative"),abs,!ref.isLastColRelative()); - assertEquals("First row reference is not "+(abs?"absolute":"relative"),abs,!ref.isFirstRowRelative()); - assertEquals("Last row reference is not "+(abs?"absolute":"relative"),abs,!ref.isLastRowRelative()); - } - - - private static void resetColumns(AreaPtg aptg) { - int fc = aptg.getFirstColumn(); - int lc = aptg.getLastColumn(); - aptg.setFirstColumn(fc); - aptg.setLastColumn(lc); - assertEquals(fc , aptg.getFirstColumn() ); - assertEquals(lc , aptg.getLastColumn() ); - } - - public void testAbsoluteRelativeRefs() { - AreaPtg sca1 = new AreaPtg(4, 5, 6, 7, true, false, true, false); - AreaPtg sca2 = new AreaPtg(4, 5, 6, 7, false, true, false, true); - AreaPtg sca3 = new AreaPtg(5, 5, 7, 7, true, false, true, false); - AreaPtg sca4 = new AreaPtg(5, 5, 7, 7, false, true, false, true); - - assertEquals("first rel., last abs.", "G5:$H$6", sca1.toFormulaString()); - assertEquals("first abs., last rel.", "$G$5:H6", sca2.toFormulaString()); - assertEquals("first rel., last abs.", "H6:$H$6", sca3.toFormulaString()); - assertEquals("first abs., last rel.", "$H$6:H6", sca4.toFormulaString()); - - AreaPtg cla1 = cloneArea(sca1); - AreaPtg cla2 = cloneArea(sca2); - AreaPtg cla3 = cloneArea(sca3); - AreaPtg cla4 = cloneArea(sca4); - - assertEquals("first rel., last abs.", "G5:$H$6", cla1.toFormulaString()); - assertEquals("first abs., last rel.", "$G$5:H6", cla2.toFormulaString()); - assertEquals("first rel., last abs.", "H6:$H$6", cla3.toFormulaString()); - assertEquals("first abs., last rel.", "$H$6:H6", cla4.toFormulaString()); - } - private AreaPtg cloneArea(AreaPtg a) - { - return new AreaPtg( - a.getFirstRow(), a.getLastRow(), a.getFirstColumn(), a.getLastColumn(), - a.isFirstRowRelative(), a.isLastRowRelative(), a.isFirstColRelative(), a.isLastColRelative() - ); - } - - public void testFormulaParser() - { - String formula1="SUM($E$5:$E$6)"; - String expectedFormula1="SUM($F$5:$F$6)"; - String newFormula1 = shiftAllColumnsBy1(formula1); - assertEquals("Absolute references changed", expectedFormula1, newFormula1); - - String formula2="SUM(E5:E6)"; - String expectedFormula2="SUM(F5:F6)"; - String newFormula2 = shiftAllColumnsBy1(formula2); - assertEquals("Relative references changed", expectedFormula2, newFormula2); - } - - private static String shiftAllColumnsBy1(String formula) { - int letUsShiftColumn1By1Column=1; - HSSFWorkbook wb = null; - Ptg[] ptgs = HSSFFormulaParser.parse(formula, wb); - for (Ptg ptg : ptgs) { - if (ptg instanceof AreaPtg ) - { - AreaPtg aptg = (AreaPtg)ptg; - aptg.setFirstColumn((short)(aptg.getFirstColumn()+letUsShiftColumn1By1Column)); - aptg.setLastColumn((short)(aptg.getLastColumn()+letUsShiftColumn1By1Column)); - } - } - String newFormula = HSSFFormulaParser.toFormulaString(wb, ptgs); - return newFormula; - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/ptg/TestArrayPtg.java b/src/testcases/org/apache/poi/ss/formula/ptg/TestArrayPtg.java deleted file mode 100644 index 36783a4c5..000000000 --- a/src/testcases/org/apache/poi/ss/formula/ptg/TestArrayPtg.java +++ /dev/null @@ -1,158 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.ptg; - -import static org.junit.Assert.assertArrayEquals; -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.util.LittleEndianByteArrayOutputStream; -import org.apache.poi.util.LittleEndianInput; -/** - * Tests for ArrayPtg - * - * @author Josh Micich - */ -public final class TestArrayPtg extends TestCase { - - private static final byte[] ENCODED_PTG_DATA = { - 0x40, - 0, 0, 0, 0, 0, 0, 0, - }; - private static final byte[] ENCODED_CONSTANT_DATA = { - 2, // 3 columns - 1, 0, // 2 rows - 4, 1, 0, 0, 0, 0, 0, 0, 0, // TRUE - 2, 4, 0, 0, 65, 66, 67, 68, // "ABCD" - 2, 1, 0, 0, 69, // "E" - 1, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 4, 0, 0, 0, 0, 0, 0, 0, 0, // FALSE - 2, 2, 0, 0, 70, 71, // "FG" - }; - - private static ArrayPtg create(byte[] initialData, byte[] constantData) { - ArrayPtg.Initial ptgInit = new ArrayPtg.Initial(TestcaseRecordInputStream.createLittleEndian(initialData)); - return ptgInit.finishReading(TestcaseRecordInputStream.createLittleEndian(constantData)); - } - - /** - * Lots of problems with ArrayPtg's decoding and encoding of the element value data - */ - public void testReadWriteTokenValueBytes() { - ArrayPtg ptg = create(ENCODED_PTG_DATA, ENCODED_CONSTANT_DATA); - assertEquals(3, ptg.getColumnCount()); - assertEquals(2, ptg.getRowCount()); - Object[][] values = ptg.getTokenArrayValues(); - assertEquals(2, values.length); - - - assertEquals(Boolean.TRUE, values[0][0]); - assertEquals("ABCD", values[0][1]); - assertEquals(new Double(0), values[1][0]); - assertEquals(Boolean.FALSE, values[1][1]); - assertEquals("FG", values[1][2]); - - byte[] outBuf = new byte[ENCODED_CONSTANT_DATA.length]; - ptg.writeTokenValueBytes(new LittleEndianByteArrayOutputStream(outBuf, 0)); - - if(outBuf[0] == 4) { - throw new AssertionFailedError("Identified bug 42564b"); - } - assertArrayEquals(ENCODED_CONSTANT_DATA, outBuf); - } - - - /** - * Excel stores array elements column by column. This test makes sure POI does the same. - */ - public void testElementOrdering() { - ArrayPtg ptg = create(ENCODED_PTG_DATA, ENCODED_CONSTANT_DATA); - assertEquals(3, ptg.getColumnCount()); - assertEquals(2, ptg.getRowCount()); - - assertEquals(0, ptg.getValueIndex(0, 0)); - assertEquals(1, ptg.getValueIndex(1, 0)); - assertEquals(2, ptg.getValueIndex(2, 0)); - assertEquals(3, ptg.getValueIndex(0, 1)); - assertEquals(4, ptg.getValueIndex(1, 1)); - assertEquals(5, ptg.getValueIndex(2, 1)); - } - - /** - * Test for a bug which was temporarily introduced by the fix for bug 42564. - * A spreadsheet was added to make the ordering clearer. - */ - public void testElementOrderingInSpreadsheet() { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("ex42564-elementOrder.xls"); - - // The formula has an array with 3 rows and 5 columns - String formula = wb.getSheetAt(0).getRow(0).getCell(0).getCellFormula(); - - if (formula.equals("SUM({1,6,11;2,7,12;3,8,13;4,9,14;5,10,15})")) { - throw new AssertionFailedError("Identified bug 42564 b"); - } - assertEquals("SUM({1,2,3,4,5;6,7,8,9,10;11,12,13,14,15})", formula); - } - - public void testToFormulaString() { - ArrayPtg ptg = create(ENCODED_PTG_DATA, ENCODED_CONSTANT_DATA); - String actualFormula; - try { - actualFormula = ptg.toFormulaString(); - } catch (IllegalArgumentException e) { - if (e.getMessage().equals("Unexpected constant class (java.lang.Boolean)")) { - throw new AssertionFailedError("Identified bug 45380"); - } - throw e; - } - assertEquals("{TRUE,\"ABCD\",\"E\";0,FALSE,\"FG\"}", actualFormula); - } - - /** - * worth checking since AttrPtg.sid=0x20 and Ptg.CLASS_* = (0x00, 0x20, and 0x40) - */ - public void testOperandClassDecoding() { - confirmOperandClassDecoding(Ptg.CLASS_REF); - confirmOperandClassDecoding(Ptg.CLASS_VALUE); - confirmOperandClassDecoding(Ptg.CLASS_ARRAY); - } - - private static void confirmOperandClassDecoding(byte operandClass) { - byte[] fullData = concat(ENCODED_PTG_DATA, ENCODED_CONSTANT_DATA); - - // Force encoded operand class for tArray - fullData[0] = (byte) (ArrayPtg.sid + operandClass); - - LittleEndianInput in = TestcaseRecordInputStream.createLittleEndian(fullData); - - Ptg[] ptgs = Ptg.readTokens(ENCODED_PTG_DATA.length, in); - assertEquals(1, ptgs.length); - ArrayPtg aPtg = (ArrayPtg) ptgs[0]; - assertEquals(operandClass, aPtg.getPtgClass()); - } - - private static byte[] concat(byte[] a, byte[] b) { - byte[] result = new byte[a.length + b.length]; - System.arraycopy(a, 0, result, 0, a.length); - System.arraycopy(b, 0, result, a.length, b.length); - return result; - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/ptg/TestAttrPtg.java b/src/testcases/org/apache/poi/ss/formula/ptg/TestAttrPtg.java deleted file mode 100644 index 6146449fc..000000000 --- a/src/testcases/org/apache/poi/ss/formula/ptg/TestAttrPtg.java +++ /dev/null @@ -1,49 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.ptg; - -import static org.junit.Assert.assertArrayEquals; -import junit.framework.AssertionFailedError; - -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.apache.poi.util.HexRead; -import org.apache.poi.util.LittleEndianInput; - -/** - * Tests for {@link AttrPtg}. - * - * @author Josh Micich - */ -public final class TestAttrPtg extends AbstractPtgTestCase { - - /** - * Fix for bug visible around svn r706772. - */ - public void testReserializeAttrChoose() { - byte[] data = HexRead.readFromString("19, 04, 03, 00, 08, 00, 11, 00, 1A, 00, 23, 00"); - LittleEndianInput in = TestcaseRecordInputStream.createLittleEndian(data); - Ptg[] ptgs = Ptg.readTokens(data.length, in); - byte[] data2 = new byte[data.length]; - try { - Ptg.serializePtgs(ptgs, data2, 0); - } catch (ArrayIndexOutOfBoundsException e) { - throw new AssertionFailedError("incorrect re-serialization of tAttrChoose"); - } - assertArrayEquals(data, data2); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/ptg/TestErrPtg.java b/src/testcases/org/apache/poi/ss/formula/ptg/TestErrPtg.java deleted file mode 100644 index 735ba393e..000000000 --- a/src/testcases/org/apache/poi/ss/formula/ptg/TestErrPtg.java +++ /dev/null @@ -1,38 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.ptg; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; - -/** - * Tests for {@link ErrPtg}. - * - * @author Daniel Noll (daniel at nuix dot com dot au) - */ -public final class TestErrPtg extends AbstractPtgTestCase { - /** - * Tests reading a file containing this ptg. - */ - public void testReading() { - HSSFWorkbook workbook = loadWorkbook("ErrPtg.xls"); - HSSFCell cell = workbook.getSheetAt(0).getRow(3).getCell(0); - assertEquals("Wrong cell value", 4.0, cell.getNumericCellValue(), 0.0); - assertEquals("Wrong cell formula", "ERROR.TYPE(#REF!)", cell.getCellFormula()); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/ptg/TestExternalFunctionFormulas.java b/src/testcases/org/apache/poi/ss/formula/ptg/TestExternalFunctionFormulas.java deleted file mode 100644 index bb3220743..000000000 --- a/src/testcases/org/apache/poi/ss/formula/ptg/TestExternalFunctionFormulas.java +++ /dev/null @@ -1,94 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.ptg; - -import static org.junit.Assert.assertEquals; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.model.HSSFFormulaParser; -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.CellValue; -import org.junit.Test; - -/** - * Tests for functions from external workbooks (e.g. YEARFRAC). - */ -public final class TestExternalFunctionFormulas { - - /** - * tests NameXPtg.toFormulaString(Workbook) and logic in Workbook below that - */ - @Test - public void testReadFormulaContainingExternalFunction() throws Exception { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("externalFunctionExample.xls"); - - String expectedFormula = "YEARFRAC(B1,C1)"; - HSSFSheet sht = wb.getSheetAt(0); - String cellFormula = sht.getRow(0).getCell(0).getCellFormula(); - assertEquals(expectedFormula, cellFormula); - - wb.close(); - } - - @Test - public void testParse() throws Exception { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("externalFunctionExample.xls"); - Ptg[] ptgs = HSSFFormulaParser.parse("YEARFRAC(B1,C1)", wb); - assertEquals(4, ptgs.length); - assertEquals(NameXPtg.class, ptgs[0].getClass()); - - wb.getSheetAt(0).getRow(0).createCell(6).setCellFormula("YEARFRAC(C1,B1)"); -// if (false) { -// // In case you fancy checking in excel -// try { -// File tempFile = TempFile.createTempFile("testExtFunc", ".xls"); -// FileOutputStream fout = new FileOutputStream(tempFile); -// wb.write(fout); -// fout.close(); -// System.out.println("check out " + tempFile.getAbsolutePath()); -// } catch (IOException e) { -// throw new RuntimeException(e); -// } -// } - wb.close(); - } - - @Test - public void testEvaluate() throws Exception { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("externalFunctionExample.xls"); - HSSFSheet sheet = wb.getSheetAt(0); - HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb); - confirmCellEval(sheet, 0, 0, fe, "YEARFRAC(B1,C1)", 29.0/90.0); - confirmCellEval(sheet, 1, 0, fe, "YEARFRAC(B2,C2)", 0.0); - confirmCellEval(sheet, 2, 0, fe, "YEARFRAC(B3,C3,D3)", 0.0); - confirmCellEval(sheet, 3, 0, fe, "IF(ISEVEN(3),1.2,1.6)", 1.6); - confirmCellEval(sheet, 4, 0, fe, "IF(ISODD(3),1.2,1.6)", 1.2); - wb.close(); - } - - private static void confirmCellEval(HSSFSheet sheet, int rowIx, int colIx, - HSSFFormulaEvaluator fe, String expectedFormula, double expectedResult) { - HSSFCell cell = sheet.getRow(rowIx).getCell(colIx); - assertEquals(expectedFormula, cell.getCellFormula()); - CellValue cv = fe.evaluate(cell); - assertEquals(expectedResult, cv.getNumberValue(), 0.0); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/ptg/TestExternalNameReference.java b/src/testcases/org/apache/poi/ss/formula/ptg/TestExternalNameReference.java deleted file mode 100644 index 6fa94dfaf..000000000 --- a/src/testcases/org/apache/poi/ss/formula/ptg/TestExternalNameReference.java +++ /dev/null @@ -1,106 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.ptg; - - -import junit.framework.TestCase; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.hssf.util.CellReference; -/** - * Tests for proper calculation of named ranges from external workbooks. - * - * - * @author Stephen Wolke (smwolke at geistig.com) - */ -public final class TestExternalNameReference extends TestCase { - double MARKUP_COST = 1.9d; - double MARKUP_COST_1 = 1.8d; - double MARKUP_COST_2 = 1.5d; - double PART_COST = 12.3d; - double NEW_QUANT = 7.0d; - double NEW_PART_COST = 15.3d; - /** - * tests NameXPtg for external cell reference by name and logic in Workbook below that - */ - public void testReadCalcSheet() { - try{ - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("XRefCalc.xls"); - assertEquals("Sheet1!$A$2", wb.getName("QUANT").getRefersToFormula()); - assertEquals("Sheet1!$B$2", wb.getName("PART").getRefersToFormula()); - assertEquals("x123",wb.getSheet("Sheet1").getRow(1).getCell(1).getStringCellValue()); - assertEquals("Sheet1!$C$2", wb.getName("UNITCOST").getRefersToFormula()); - CellReference cellRef = new CellReference(wb.getName("UNITCOST").getRefersToFormula()); - HSSFCell cell = wb.getSheet(cellRef.getSheetName()).getRow(cellRef.getRow()).getCell((int)cellRef.getCol()); - assertEquals("VLOOKUP(PART,COSTS,2,FALSE)",cell.getCellFormula()); - assertEquals("Sheet1!$D$2", wb.getName("COST").getRefersToFormula()); - cellRef = new CellReference(wb.getName("COST").getRefersToFormula()); - cell = wb.getSheet(cellRef.getSheetName()).getRow(cellRef.getRow()).getCell((int)cellRef.getCol()); - assertEquals("UNITCOST*Quant",cell.getCellFormula()); - assertEquals("Sheet1!$E$2", wb.getName("TOTALCOST").getRefersToFormula()); - cellRef = new CellReference(wb.getName("TOTALCOST").getRefersToFormula()); - cell = wb.getSheet(cellRef.getSheetName()).getRow(cellRef.getRow()).getCell((int)cellRef.getCol()); - assertEquals("Cost*Markup_Cost",cell.getCellFormula()); - }catch(Exception e){ - fail(); - } - } - - public void testReadReferencedSheet() { - try{ - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("XRefCalcData.xls"); - assertEquals("CostSheet!$A$2:$B$3", wb.getName("COSTS").getRefersToFormula()); - assertEquals("x123",wb.getSheet("CostSheet").getRow(1).getCell(0).getStringCellValue()); - assertEquals(PART_COST,wb.getSheet("CostSheet").getRow(1).getCell(1).getNumericCellValue()); - assertEquals("MarkupSheet!$B$1", wb.getName("Markup_Cost").getRefersToFormula()); - assertEquals(MARKUP_COST_1,wb.getSheet("MarkupSheet").getRow(0).getCell(1).getNumericCellValue()); - }catch(Exception e){ - fail(); - } - } - - public void testEvaluate() throws Exception { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("XRefCalc.xls"); - HSSFWorkbook wb2 = HSSFTestDataSamples.openSampleWorkbook("XRefCalcData.xls"); - CellReference cellRef = new CellReference(wb.getName("QUANT").getRefersToFormula()); - HSSFCell cell = wb.getSheet(cellRef.getSheetName()).getRow(cellRef.getRow()).getCell((int)cellRef.getCol()); - cell.setCellValue(NEW_QUANT); - cell = wb2.getSheet("CostSheet").getRow(1).getCell(1); - cell.setCellValue(NEW_PART_COST); - HSSFFormulaEvaluator evaluator = new HSSFFormulaEvaluator(wb); - HSSFFormulaEvaluator evaluatorCost = new HSSFFormulaEvaluator(wb2); - String[] bookNames = { "XRefCalc.xls", "XRefCalcData.xls" }; - HSSFFormulaEvaluator[] evaluators = { evaluator, evaluatorCost, }; - HSSFFormulaEvaluator.setupEnvironment(bookNames, evaluators); - cellRef = new CellReference(wb.getName("UNITCOST").getRefersToFormula()); - HSSFCell uccell = wb.getSheet(cellRef.getSheetName()).getRow(cellRef.getRow()).getCell((int)cellRef.getCol()); - cellRef = new CellReference(wb.getName("COST").getRefersToFormula()); - HSSFCell ccell = wb.getSheet(cellRef.getSheetName()).getRow(cellRef.getRow()).getCell((int)cellRef.getCol()); - cellRef = new CellReference(wb.getName("TOTALCOST").getRefersToFormula()); - HSSFCell tccell = wb.getSheet(cellRef.getSheetName()).getRow(cellRef.getRow()).getCell((int)cellRef.getCol()); - evaluator.evaluateFormulaCellEnum(uccell); - evaluator.evaluateFormulaCellEnum(ccell); - evaluator.evaluateFormulaCellEnum(tccell); - assertEquals(NEW_PART_COST, uccell.getNumericCellValue()); - assertEquals(NEW_PART_COST*NEW_QUANT, ccell.getNumericCellValue()); - assertEquals(NEW_PART_COST*NEW_QUANT*MARKUP_COST_2, tccell.getNumericCellValue()); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/ptg/TestFuncPtg.java b/src/testcases/org/apache/poi/ss/formula/ptg/TestFuncPtg.java deleted file mode 100644 index fd1af26dd..000000000 --- a/src/testcases/org/apache/poi/ss/formula/ptg/TestFuncPtg.java +++ /dev/null @@ -1,46 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.ptg; - -import junit.framework.TestCase; -import org.apache.poi.hssf.record.TestcaseRecordInputStream; - -/** - * Make sure the FuncPtg performs as expected - * - * @author Danny Mui (dmui at apache dot org) - */ -public final class TestFuncPtg extends TestCase { - - public void testRead() { - // This function index represents the LEN() function - byte[] fakeData = { 0x20, 0x00,}; - - FuncPtg ptg = FuncPtg.create(TestcaseRecordInputStream.createLittleEndian(fakeData) ); - assertEquals( "Len formula index is not 32(20H)", 0x20, ptg.getFunctionIndex() ); - assertEquals( "Number of operands in the len formula", 1, ptg.getNumberOfOperands() ); - assertEquals( "Function Name", "LEN", ptg.getName() ); - assertEquals( "Ptg Size", 3, ptg.getSize() ); - } - - public void testNumberOfOperands() { - FuncPtg funcPtg = FuncPtg.create(27); // ROUND() - takes 2 args - assertEquals(2, funcPtg.getNumberOfOperands()); - assertEquals("ROUND", funcPtg.getName()); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/ptg/TestFuncVarPtg.java b/src/testcases/org/apache/poi/ss/formula/ptg/TestFuncVarPtg.java deleted file mode 100644 index ecc07aac4..000000000 --- a/src/testcases/org/apache/poi/ss/formula/ptg/TestFuncVarPtg.java +++ /dev/null @@ -1,53 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.ptg; - -import org.apache.poi.hssf.model.HSSFFormulaParser; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; -/** - * @author Josh Micich - */ -public final class TestFuncVarPtg extends TestCase { - - /** - * The first fix for bugzilla 44675 broke the encoding of SUM formulas (and probably others). - * The operand classes of the parameters to SUM() should be coerced to 'reference' not 'value'. - * In the case of SUM, Excel evaluates the formula to '#VALUE!' if a parameter operand class is - * wrong. In other cases Excel seems to tolerate bad operand classes.

    - * This functionality is related to the setParameterRVA() methods of FormulaParser - */ - public void testOperandClass() { - HSSFWorkbook book = new HSSFWorkbook(); - Ptg[] ptgs = HSSFFormulaParser.parse("sum(A1:A2)", book); - assertEquals(2, ptgs.length); - assertEquals(AreaPtg.class, ptgs[0].getClass()); - - switch(ptgs[0].getPtgClass()) { - case Ptg.CLASS_REF: - // correct behaviour - break; - case Ptg.CLASS_VALUE: - throw new AssertionFailedError("Identified bug 44675b"); - default: - throw new RuntimeException("Unexpected operand class"); - } - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/ptg/TestIntersectionPtg.java b/src/testcases/org/apache/poi/ss/formula/ptg/TestIntersectionPtg.java deleted file mode 100644 index c06b80e38..000000000 --- a/src/testcases/org/apache/poi/ss/formula/ptg/TestIntersectionPtg.java +++ /dev/null @@ -1,38 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.ptg; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; - -/** - * Tests for {@link IntersectionPtg}. - * - * @author Daniel Noll (daniel at nuix dot com dot au) - */ -public final class TestIntersectionPtg extends AbstractPtgTestCase { - /** - * Tests reading a file containing this ptg. - */ - public void testReading() { - HSSFWorkbook workbook = loadWorkbook("IntersectionPtg.xls"); - HSSFCell cell = workbook.getSheetAt(0).getRow(4).getCell(2); - assertEquals("Wrong cell value", 5.0, cell.getNumericCellValue(), 0.0); - assertEquals("Wrong cell formula", "SUM(A1:B2 B2:C3)", cell.getCellFormula()); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/ptg/TestPercentPtg.java b/src/testcases/org/apache/poi/ss/formula/ptg/TestPercentPtg.java deleted file mode 100644 index 79d34530a..000000000 --- a/src/testcases/org/apache/poi/ss/formula/ptg/TestPercentPtg.java +++ /dev/null @@ -1,43 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.ptg; - -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; - -/** - * Tests for {@link PercentPtg}. - * - * @author Daniel Noll (daniel at nuix dot com dot au) - */ -public final class TestPercentPtg extends AbstractPtgTestCase { - /** - * Tests reading a file containing this ptg. - */ - public void testReading() { - HSSFWorkbook workbook = loadWorkbook("PercentPtg.xls"); - HSSFSheet sheet = workbook.getSheetAt(0); - - assertEquals("Wrong numeric value for original number", 53000.0, - sheet.getRow(0).getCell(0).getNumericCellValue(), 0.0); - assertEquals("Wrong numeric value for percent formula result", 5300.0, - sheet.getRow(1).getCell(0).getNumericCellValue(), 0.0); - assertEquals("Wrong formula string for percent formula", "A1*10%", - sheet.getRow(1).getCell(0).getCellFormula()); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/ptg/TestRangePtg.java b/src/testcases/org/apache/poi/ss/formula/ptg/TestRangePtg.java deleted file mode 100644 index 3b02684bb..000000000 --- a/src/testcases/org/apache/poi/ss/formula/ptg/TestRangePtg.java +++ /dev/null @@ -1,38 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.ptg; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; - -/** - * Tests for {@link RangePtg}. - * - * @author Daniel Noll (daniel at nuix dot com dot au) - */ -public final class TestRangePtg extends AbstractPtgTestCase { - /** - * Tests reading a file containing this ptg. - */ - public void testReading() { - HSSFWorkbook workbook = loadWorkbook("RangePtg.xls"); - HSSFCell cell = workbook.getSheetAt(0).getRow(3).getCell(1); - assertEquals("Wrong cell value", 10.0, cell.getNumericCellValue(), 0.0); - assertEquals("Wrong cell formula", "SUM(pineapple:B2)", cell.getCellFormula()); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/ptg/TestRef3DPtg.java b/src/testcases/org/apache/poi/ss/formula/ptg/TestRef3DPtg.java deleted file mode 100644 index 3aca4c4e0..000000000 --- a/src/testcases/org/apache/poi/ss/formula/ptg/TestRef3DPtg.java +++ /dev/null @@ -1,44 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.ptg; - -import org.apache.poi.hssf.usermodel.HSSFEvaluationWorkbook; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; - -/** - * Tests for Ref3DPtg - * - * @author Josh Micich - */ -public final class TestRef3DPtg extends AbstractPtgTestCase { - - public void testToFormulaString() { - - Ref3DPtg target = new Ref3DPtg("A1", (short)0); - - HSSFWorkbook wb = createWorkbookWithSheet("my sheet"); - HSSFEvaluationWorkbook book = HSSFEvaluationWorkbook.create(wb); - assertEquals("'my sheet'!A1", target.toFormulaString(book)); - - wb.setSheetName(0, "ProfitAndLoss"); - assertEquals("ProfitAndLoss!A1", target.toFormulaString(book)); - - wb.setSheetName(0, "profit+loss"); - assertEquals("'profit+loss'!A1", target.toFormulaString(book)); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/ptg/TestReferencePtg.java b/src/testcases/org/apache/poi/ss/formula/ptg/TestReferencePtg.java deleted file mode 100644 index 7167c2ec0..000000000 --- a/src/testcases/org/apache/poi/ss/formula/ptg/TestReferencePtg.java +++ /dev/null @@ -1,121 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.ptg; - -import static org.junit.Assert.assertArrayEquals; -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.record.TestcaseRecordInputStream; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.util.LittleEndianInput; - -/** - * Tests for {@link RefPtg}. - */ -public final class TestReferencePtg extends TestCase { - /** - * Tests reading a file containing this ptg. - */ - public void testReading() { - HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook("ReferencePtg.xls"); - HSSFSheet sheet = workbook.getSheetAt(0); - - // First row - assertEquals("Wrong numeric value for original number", 55.0, - sheet.getRow(0).getCell(0).getNumericCellValue(), 0.0); - assertEquals("Wrong numeric value for referemce", 55.0, - sheet.getRow(0).getCell(1).getNumericCellValue(), 0.0); - assertEquals("Wrong formula string for reference", "A1", - sheet.getRow(0).getCell(1).getCellFormula()); - - // Now moving over the 2**15 boundary - // (Remember that excel row (n) is poi row (n-1) - assertEquals("Wrong numeric value for original number", 32767.0, - sheet.getRow(32766).getCell(0).getNumericCellValue(), 0.0); - assertEquals("Wrong numeric value for referemce", 32767.0, - sheet.getRow(32766).getCell(1).getNumericCellValue(), 0.0); - assertEquals("Wrong formula string for reference", "A32767", - sheet.getRow(32766).getCell(1).getCellFormula()); - - assertEquals("Wrong numeric value for original number", 32768.0, - sheet.getRow(32767).getCell(0).getNumericCellValue(), 0.0); - assertEquals("Wrong numeric value for referemce", 32768.0, - sheet.getRow(32767).getCell(1).getNumericCellValue(), 0.0); - assertEquals("Wrong formula string for reference", "A32768", - sheet.getRow(32767).getCell(1).getCellFormula()); - - assertEquals("Wrong numeric value for original number", 32769.0, - sheet.getRow(32768).getCell(0).getNumericCellValue(), 0.0); - assertEquals("Wrong numeric value for referemce", 32769.0, - sheet.getRow(32768).getCell(1).getNumericCellValue(), 0.0); - assertEquals("Wrong formula string for reference", "A32769", - sheet.getRow(32768).getCell(1).getCellFormula()); - - assertEquals("Wrong numeric value for original number", 32770.0, - sheet.getRow(32769).getCell(0).getNumericCellValue(), 0.0); - assertEquals("Wrong numeric value for referemce", 32770.0, - sheet.getRow(32769).getCell(1).getNumericCellValue(), 0.0); - assertEquals("Wrong formula string for reference", "A32770", - sheet.getRow(32769).getCell(1).getCellFormula()); - } - - public void testBug44921() { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("ex44921-21902.xls"); - - try { - HSSFTestDataSamples.writeOutAndReadBack(wb); - } catch (RuntimeException e) { - if(e.getMessage().equals("Coding Error: This method should never be called. This ptg should be converted")) { - throw new AssertionFailedError("Identified bug 44921"); - } - throw e; - } - } - private static final byte[] tRefN_data = { - 0x2C, 33, 44, 55, 66, - }; - public void testReadWrite_tRefN_bug45091() { - LittleEndianInput in = TestcaseRecordInputStream.createLittleEndian(tRefN_data); - Ptg[] ptgs = Ptg.readTokens(tRefN_data.length, in); - byte[] outData = new byte[5]; - Ptg.serializePtgs(ptgs, outData, 0); - if (outData[0] == 0x24) { - throw new AssertionFailedError("Identified bug 45091"); - } - assertArrayEquals(tRefN_data, outData); - } - - /** - * test that RefPtgBase can handle references with column index greater than 255, - * see Bugzilla 50096 - */ - public void testColumnGreater255() { - RefPtgBase ptg; - ptg = new RefPtg("IW1"); - assertEquals(256, ptg.getColumn()); - assertEquals("IW1", ptg.formatReferenceAsString()); - - ptg = new RefPtg("JA1"); - assertEquals(260, ptg.getColumn()); - assertEquals("JA1", ptg.formatReferenceAsString()); - } -} - diff --git a/src/testcases/org/apache/poi/ss/formula/ptg/TestUnionPtg.java b/src/testcases/org/apache/poi/ss/formula/ptg/TestUnionPtg.java deleted file mode 100644 index 9ea756061..000000000 --- a/src/testcases/org/apache/poi/ss/formula/ptg/TestUnionPtg.java +++ /dev/null @@ -1,38 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.formula.ptg; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; - -/** - * Tests for {@link UnionPtg}. - * - * @author Daniel Noll (daniel at nuix dot com dot au) - */ -public final class TestUnionPtg extends AbstractPtgTestCase { - /** - * Tests reading a file containing this ptg. - */ - public void testReading() { - HSSFWorkbook workbook = loadWorkbook("UnionPtg.xls"); - HSSFCell cell = workbook.getSheetAt(0).getRow(4).getCell(2); - assertEquals("Wrong cell value", 24.0, cell.getNumericCellValue(), 0.0); - assertEquals("Wrong cell formula", "SUM(A1:B2,B2:C3)", cell.getCellFormula()); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/udf/BaseTestUDFFinder.java b/src/testcases/org/apache/poi/ss/formula/udf/BaseTestUDFFinder.java deleted file mode 100644 index ab3aa987c..000000000 --- a/src/testcases/org/apache/poi/ss/formula/udf/BaseTestUDFFinder.java +++ /dev/null @@ -1,40 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.formula.udf; - -import static org.junit.Assert.assertNotNull; - -import org.apache.poi.ss.formula.functions.FreeRefFunction; -import org.apache.poi.ss.formula.eval.ValueEval; -import org.apache.poi.ss.formula.OperationEvaluationContext; - -public class BaseTestUDFFinder { - - protected UDFFinder _instance; - protected static final FreeRefFunction NotImplemented = new FreeRefFunction() { - @Override - public ValueEval evaluate(ValueEval[] args, OperationEvaluationContext ec) { - throw new RuntimeException("not implemented"); - } - }; - - protected void confirmFindFunction(String name) { - FreeRefFunction func = _instance.findFunction(name); - assertNotNull(func); - } - -} diff --git a/src/testcases/org/apache/poi/ss/formula/udf/TestAggregatingUDFFinder.java b/src/testcases/org/apache/poi/ss/formula/udf/TestAggregatingUDFFinder.java deleted file mode 100644 index 88d7e84ff..000000000 --- a/src/testcases/org/apache/poi/ss/formula/udf/TestAggregatingUDFFinder.java +++ /dev/null @@ -1,37 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.formula.udf; - -import org.apache.poi.ss.formula.atp.AnalysisToolPak; -import org.junit.Test; - -public class TestAggregatingUDFFinder extends BaseTestUDFFinder { - - public TestAggregatingUDFFinder() { - _instance = new AggregatingUDFFinder(AnalysisToolPak.instance); - } - - @Test - public void findFunction() { - confirmFindFunction("BESSELJ"); - } - - @Test - public void add() { - ((AggregatingUDFFinder)_instance).add(AnalysisToolPak.instance); - } -} diff --git a/src/testcases/org/apache/poi/ss/formula/udf/TestDefaultUDFFinder.java b/src/testcases/org/apache/poi/ss/formula/udf/TestDefaultUDFFinder.java deleted file mode 100644 index 010b19d4e..000000000 --- a/src/testcases/org/apache/poi/ss/formula/udf/TestDefaultUDFFinder.java +++ /dev/null @@ -1,35 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.formula.udf; - -import org.apache.poi.ss.formula.functions.FreeRefFunction; -import org.junit.Test; - -public class TestDefaultUDFFinder extends BaseTestUDFFinder { - - public TestDefaultUDFFinder() { - _instance = new DefaultUDFFinder( - new String[] { "NotImplemented" }, - new FreeRefFunction[] { NotImplemented } - ); - } - - @Test - public void findFunction() { - confirmFindFunction("NotImplemented"); - } -} diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestBorderStyle.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestBorderStyle.java deleted file mode 100644 index 2fd2c37bf..000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestBorderStyle.java +++ /dev/null @@ -1,82 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - - 2012 - Alfresco Software, Ltd. - Alfresco Software has modified source of this file - The details of changes as svn diff can be found in svn at location root/projects/3rd-party/src -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import static org.junit.Assert.assertEquals; - -import java.io.IOException; - -import org.apache.poi.ss.ITestDataProvider; -import org.junit.Test; - -/** - * Tests of {@link BorderStyle} - */ -public class BaseTestBorderStyle { - - private final ITestDataProvider _testDataProvider; - - protected BaseTestBorderStyle(ITestDataProvider testDataProvider) { - _testDataProvider = testDataProvider; - } - - /** - * Test that we use the specified locale when deciding - * how to format normal numbers - */ - @Test - public void testBorderStyle() throws IOException { - String ext = _testDataProvider.getStandardFileNameExtension(); - Workbook wb = _testDataProvider.openSampleWorkbook("59264."+ext); - Sheet sh = wb.getSheetAt(0); - - assertBorderStyleEquals(BorderStyle.NONE, getDiagonalCell(sh, 0)); - assertBorderStyleEquals(BorderStyle.THIN, getDiagonalCell(sh, 1)); - assertBorderStyleEquals(BorderStyle.MEDIUM, getDiagonalCell(sh, 2)); - assertBorderStyleEquals(BorderStyle.DASHED, getDiagonalCell(sh, 3)); - assertBorderStyleEquals(BorderStyle.DOTTED, getDiagonalCell(sh, 4)); - assertBorderStyleEquals(BorderStyle.THICK, getDiagonalCell(sh, 5)); - assertBorderStyleEquals(BorderStyle.DOUBLE, getDiagonalCell(sh, 6)); - assertBorderStyleEquals(BorderStyle.HAIR, getDiagonalCell(sh, 7)); - assertBorderStyleEquals(BorderStyle.MEDIUM_DASHED, getDiagonalCell(sh, 8)); - assertBorderStyleEquals(BorderStyle.DASH_DOT, getDiagonalCell(sh, 9)); - assertBorderStyleEquals(BorderStyle.MEDIUM_DASH_DOT, getDiagonalCell(sh, 10)); - assertBorderStyleEquals(BorderStyle.DASH_DOT_DOT, getDiagonalCell(sh, 11)); - assertBorderStyleEquals(BorderStyle.MEDIUM_DASH_DOT_DOT, getDiagonalCell(sh, 12)); - assertBorderStyleEquals(BorderStyle.SLANTED_DASH_DOT, getDiagonalCell(sh, 13)); - - wb.close(); - } - - private Cell getDiagonalCell(Sheet sheet, int n) { - return sheet.getRow(n).getCell(n); - } - - protected void assertBorderStyleEquals(BorderStyle expected, Cell cell) { - CellStyle style = cell.getCellStyle(); - assertEquals(expected, style.getBorderTopEnum()); - assertEquals(expected, style.getBorderBottomEnum()); - assertEquals(expected, style.getBorderLeftEnum()); - assertEquals(expected, style.getBorderRightEnum()); - } - -} diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestBugzillaIssues.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestBugzillaIssues.java deleted file mode 100644 index 52f8b72b2..000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestBugzillaIssues.java +++ /dev/null @@ -1,1907 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.awt.font.FontRenderContext; -import java.awt.font.TextAttribute; -import java.awt.font.TextLayout; -import java.awt.geom.Rectangle2D; -import java.io.IOException; -import java.text.AttributedString; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.CellRangeAddressList; -import org.apache.poi.ss.util.PaneInformation; -import org.apache.poi.ss.util.SheetUtil; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.junit.Assume; -import org.junit.Ignore; -import org.junit.Test; - -/** - * A base class for bugzilla issues that can be described in terms of common ss interfaces. - * - * @author Yegor Kozlov - */ -public abstract class BaseTestBugzillaIssues { - private static final POILogger logger = POILogFactory.getLogger(BaseTestBugzillaIssues.class); - - private static final String TEST_32 = "Some text with 32 characters to "; - private static final String TEST_255 = "Some very long text that is exactly 255 characters, which are allowed here, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla....."; - private static final String TEST_256 = "Some very long text that is longer than the 255 characters allowed in HSSF here, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla bla, bla1"; - private static final String TEST_SPECIAL_TITLE = "special \n\t\r\u0002characters"; - private static final String TEST_SPECIAL = "Some text with special \n\t\r\u0002characters to s"; - - private final ITestDataProvider _testDataProvider; - - protected BaseTestBugzillaIssues(ITestDataProvider testDataProvider) { - _testDataProvider = testDataProvider; - } - - /** - * Unlike org.junit.Assert.assertEquals(double expected, double actual, double delta), - * where delta is an absolute error value, this function's factor is a relative error, - * so it's easier to express "actual is within 5% of expected". - */ - public static void assertAlmostEquals(double expected, double actual, float factor) { - double diff = Math.abs(expected - actual); - double fuzz = expected * factor; - if (diff > fuzz) { - fail(actual + " not within " + fuzz + " of " + expected); - } - } - - /** - * Test writing a hyperlink - * Open resulting sheet in Excel and check that A1 contains a hyperlink - * - * Also tests bug 15353 (problems with hyperlinks to Google) - */ - @Test - public final void bug23094() throws IOException { - Workbook wb1 = _testDataProvider.createWorkbook(); - Sheet s = wb1.createSheet(); - Row r = s.createRow(0); - r.createCell(0).setCellFormula("HYPERLINK(\"http://jakarta.apache.org\",\"Jakarta\")"); - r.createCell(1).setCellFormula("HYPERLINK(\"http://google.com\",\"Google\")"); - - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - wb1.close(); - r = wb2.getSheetAt(0).getRow(0); - - Cell cell_0 = r.getCell(0); - assertEquals("HYPERLINK(\"http://jakarta.apache.org\",\"Jakarta\")", cell_0.getCellFormula()); - Cell cell_1 = r.getCell(1); - assertEquals("HYPERLINK(\"http://google.com\",\"Google\")", cell_1.getCellFormula()); - - wb2.close(); - } - - /** - * test writing a file with large number of unique strings, - * open resulting file in Excel to check results! - * @param num the number of strings to generate - */ - public final void bug15375(int num) throws IOException { - Workbook wb1 = _testDataProvider.createWorkbook(); - Sheet sheet = wb1.createSheet(); - CreationHelper factory = wb1.getCreationHelper(); - - for (int i = 0; i < num; i++) { - String tmp1 = "Test1" + i; - String tmp2 = "Test2" + i; - String tmp3 = "Test3" + i; - - Row row = sheet.createRow(i); - - Cell cell = row.createCell(0); - cell.setCellValue(factory.createRichTextString(tmp1)); - cell = row.createCell(1); - cell.setCellValue(factory.createRichTextString(tmp2)); - cell = row.createCell(2); - cell.setCellValue(factory.createRichTextString(tmp3)); - } - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - wb1.close(); - - sheet = wb2.getSheetAt(0); - for (int i = 0; i < num; i++) { - String tmp1 = "Test1" + i; - String tmp2 = "Test2" + i; - String tmp3 = "Test3" + i; - - Row row = sheet.getRow(i); - - assertEquals(tmp1, row.getCell(0).getStringCellValue()); - assertEquals(tmp2, row.getCell(1).getStringCellValue()); - assertEquals(tmp3, row.getCell(2).getStringCellValue()); - } - wb2.close(); - } - - /** - * Merged regions were being removed from the parent in cloned sheets - */ - @Test - public void bug22720() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - wb.createSheet("TEST"); - Sheet template = wb.getSheetAt(0); - - template.addMergedRegion(new CellRangeAddress(0, 1, 0, 2)); - template.addMergedRegion(new CellRangeAddress(2, 3, 0, 2)); - - Sheet clone = wb.cloneSheet(0); - int originalMerged = template.getNumMergedRegions(); - assertEquals("2 merged regions", 2, originalMerged); - - //remove merged regions from clone - for (int i=template.getNumMergedRegions()-1; i>=0; i--) { - clone.removeMergedRegion(i); - } - - assertEquals("Original Sheet's Merged Regions were removed", originalMerged, template.getNumMergedRegions()); - //check if template's merged regions are OK - if (template.getNumMergedRegions()>0) { - // fetch the first merged region...EXCEPTION OCCURS HERE - template.getMergedRegion(0); - } - - wb.close(); - } - - @Test - public final void bug28031() throws IOException { - Workbook wb1 = _testDataProvider.createWorkbook(); - Sheet sheet = wb1.createSheet(); - wb1.setSheetName(0, "Sheet1"); - - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - String formulaText = - "IF(ROUND(A2*B2*C2,2)>ROUND(B2*D2,2),ROUND(A2*B2*C2,2),ROUND(B2*D2,2))"; - cell.setCellFormula(formulaText); - - assertEquals(formulaText, cell.getCellFormula()); - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - wb1.close(); - - cell = wb2.getSheetAt(0).getRow(0).getCell(0); - assertEquals("IF(ROUND(A2*B2*C2,2)>ROUND(B2*D2,2),ROUND(A2*B2*C2,2),ROUND(B2*D2,2))", cell.getCellFormula()); - wb2.close(); - } - - /** - * Bug 21334: "File error: data may have been lost" with a file - * that contains macros and this formula: - * {=SUM(IF(FREQUENCY(IF(LEN(V4:V220)>0,MATCH(V4:V220,V4:V220,0),""),IF(LEN(V4:V220)>0,MATCH(V4:V220,V4:V220,0),""))>0,1))} - */ - @Test - public final void bug21334() throws IOException { - Workbook wb1 = _testDataProvider.createWorkbook(); - Sheet sh = wb1.createSheet(); - Cell cell = sh.createRow(0).createCell(0); - String formula = "SUM(IF(FREQUENCY(IF(LEN(V4:V220)>0,MATCH(V4:V220,V4:V220,0),\"\"),IF(LEN(V4:V220)>0,MATCH(V4:V220,V4:V220,0),\"\"))>0,1))"; - cell.setCellFormula(formula); - - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - wb1.close(); - Cell cell_sv = wb2.getSheetAt(0).getRow(0).getCell(0); - assertEquals(formula, cell_sv.getCellFormula()); - wb2.close(); - } - - /** another test for the number of unique strings issue - *test opening the resulting file in Excel*/ - @Test - public final void bug22568() throws IOException { - Workbook wb1 = _testDataProvider.createWorkbook(); - Sheet sheet = wb1.createSheet("ExcelTest") ; - - int col_cnt = 3; - int rw_cnt = 2000; - - Row rw ; - rw = sheet.createRow(0) ; - //Header row - for(int j=0; j 0) { - fmla.append(','); - } - fmla.append("A1"); - } - fmla.append(")"); - return fmla.toString(); - } - - @Test - public final void bug50681_testAutoSize() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - BaseTestSheetAutosizeColumn.fixFonts(wb); - Sheet sheet = wb.createSheet("Sheet1"); - _testDataProvider.trackAllColumnsForAutosizing(sheet); - Row row = sheet.createRow(0); - Cell cell0 = row.createCell(0); - - String longValue = "www.hostname.com, www.hostname.com, " + - "www.hostname.com, www.hostname.com, www.hostname.com, " + - "www.hostname.com, www.hostname.com, www.hostname.com, " + - "www.hostname.com, www.hostname.com, www.hostname.com, " + - "www.hostname.com, www.hostname.com, www.hostname.com, " + - "www.hostname.com, www.hostname.com, www.hostname.com, www.hostname.com"; - - cell0.setCellValue(longValue); - - // autoSize will fail if required fonts are not installed, skip this test then - Font font = wb.getFontAt(cell0.getCellStyle().getFontIndex()); - Assume.assumeTrue("Cannot verify autoSizeColumn() because the necessary Fonts are not installed on this machine: " + font, - SheetUtil.canComputeColumnWidth(font)); - - assertEquals("Expecting no indentation in this test", - 0, cell0.getCellStyle().getIndention()); - assertEquals("Expecting no rotation in this test", - 0, cell0.getCellStyle().getRotation()); - - // check computing size up to a large size -// StringBuilder b = new StringBuilder(); -// for(int i = 0;i < longValue.length()*5;i++) { -// b.append("w"); -// assertTrue("Had zero length starting at length " + i, computeCellWidthFixed(font, b.toString()) > 0); -// } - double widthManual = computeCellWidthManually(cell0, font); - double widthBeforeCell = SheetUtil.getCellWidth(cell0, 8, null, false); - double widthBeforeCol = SheetUtil.getColumnWidth(sheet, 0, false); - - String info = widthManual + "/" + widthBeforeCell + "/" + widthBeforeCol + "/" + - SheetUtil.canComputeColumnWidth(font) + "/" + computeCellWidthFixed(font, "1") + "/" + computeCellWidthFixed(font, "w") + "/" + - computeCellWidthFixed(font, "1w") + "/" + computeCellWidthFixed(font, "0000") + "/" + computeCellWidthFixed(font, longValue); - assertTrue("Expected to have cell width > 0 when computing manually, but had " + info, widthManual > 0); - assertTrue("Expected to have cell width > 0 BEFORE auto-size, but had " + info, widthBeforeCell > 0); - assertTrue("Expected to have column width > 0 BEFORE auto-size, but had " + info, widthBeforeCol > 0); - - sheet.autoSizeColumn(0); - - double width = SheetUtil.getColumnWidth(sheet, 0, false); - assertTrue("Expected to have column width > 0 AFTER auto-size, but had " + width, width > 0); - width = SheetUtil.getCellWidth(cell0, 8, null, false); - assertTrue("Expected to have cell width > 0 AFTER auto-size, but had " + width, width > 0); - - assertEquals(255*256, sheet.getColumnWidth(0)); // maximum column width is 255 characters - sheet.setColumnWidth(0, sheet.getColumnWidth(0)); // Bug 50681 reports exception at this point - wb.close(); - } - - @Test - public final void bug51622_testAutoSizeShouldRecognizeLeadingSpaces() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - BaseTestSheetAutosizeColumn.fixFonts(wb); - Sheet sheet = wb.createSheet(); - _testDataProvider.trackAllColumnsForAutosizing(sheet); - Row row = sheet.createRow(0); - Cell cell0 = row.createCell(0); - Cell cell1 = row.createCell(1); - Cell cell2 = row.createCell(2); - - cell0.setCellValue("Test Column AutoSize"); - cell1.setCellValue(" Test Column AutoSize"); - cell2.setCellValue("Test Column AutoSize "); - - sheet.autoSizeColumn(0); - sheet.autoSizeColumn(1); - sheet.autoSizeColumn(2); - - int noWhitespaceColWidth = sheet.getColumnWidth(0); - int leadingWhitespaceColWidth = sheet.getColumnWidth(1); - int trailingWhitespaceColWidth = sheet.getColumnWidth(2); - - // Based on the amount of text and whitespace used, and the default font - // assume that the cell with whitespace should be at least 20% wider than - // the cell without whitespace. This number is arbitrary, but should be large - // enough to guarantee that the whitespace cell isn't wider due to chance. - // Experimentally, I calculated the ratio as 1.2478181, though this ratio may change - // if the default font or margins change. - final double expectedRatioThreshold = 1.2f; - double leadingWhitespaceRatio = ((double) leadingWhitespaceColWidth)/noWhitespaceColWidth; - double trailingWhitespaceRatio = ((double) leadingWhitespaceColWidth)/noWhitespaceColWidth; - - assertGreaterThan("leading whitespace is longer than no whitespace", leadingWhitespaceRatio, expectedRatioThreshold); - assertGreaterThan("trailing whitespace is longer than no whitespace", trailingWhitespaceRatio, expectedRatioThreshold); - assertEquals("cells with equal leading and trailing whitespace have equal width", - leadingWhitespaceColWidth, trailingWhitespaceColWidth); - - wb.close(); - } - - /** - * Test if a > b. Fails if false. - */ - private void assertGreaterThan(String message, double a, double b) { - if (a <= b) { - String msg = "Expected: " + a + " > " + b; - fail(message + ": " + msg); - } - } - - // FIXME: this function is a self-fulfilling prophecy: this test will always pass as long - // as the code-under-test and the testcase code are written the same way (have the same bugs). - private double computeCellWidthManually(Cell cell0, Font font) { - final FontRenderContext fontRenderContext = new FontRenderContext(null, true, true); - RichTextString rt = cell0.getRichStringCellValue(); - String[] lines = rt.getString().split("\\n"); - assertEquals(1, lines.length); - String txt = lines[0] + "0"; - - AttributedString str = new AttributedString(txt); - copyAttributes(font, str, txt.length()); - - // TODO: support rich text fragments - /*if (rt.numFormattingRuns() > 0) { - }*/ - - TextLayout layout = new TextLayout(str.getIterator(), fontRenderContext); - double frameWidth = getFrameWidth(layout); - return ((frameWidth / 1) / 8); - } - - private double getFrameWidth(TextLayout layout) { - Rectangle2D bounds = layout.getBounds(); - return bounds.getX() + bounds.getWidth(); - } - - private double computeCellWidthFixed(Font font, String txt) { - final FontRenderContext fontRenderContext = new FontRenderContext(null, true, true); - AttributedString str = new AttributedString(txt); - copyAttributes(font, str, txt.length()); - - TextLayout layout = new TextLayout(str.getIterator(), fontRenderContext); - return getFrameWidth(layout); - } - - private static void copyAttributes(Font font, AttributedString str, int endIdx) { - str.addAttribute(TextAttribute.FAMILY, font.getFontName(), 0, endIdx); - str.addAttribute(TextAttribute.SIZE, (float)font.getFontHeightInPoints()); - if (font.getBold()) { - str.addAttribute(TextAttribute.WEIGHT, TextAttribute.WEIGHT_BOLD, 0, endIdx); - } - if (font.getItalic() ) { - str.addAttribute(TextAttribute.POSTURE, TextAttribute.POSTURE_OBLIQUE, 0, endIdx); - } - if (font.getUnderline() == Font.U_SINGLE ) { - str.addAttribute(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON, 0, endIdx); - } - } - - /** - * CreateFreezePane column/row order check - */ - @Test - public void bug49381() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - int colSplit = 1; - int rowSplit = 2; - int leftmostColumn = 3; - int topRow = 4; - - Sheet s = wb.createSheet(); - - // Populate - for(int rn=0; rn<= topRow; rn++) { - Row r = s.createRow(rn); - for(int cn=0; cn evaluators = new HashMap(); - evaluators.put(refLocal, wb3.getCreationHelper().createFormulaEvaluator()); - evaluators.put(refHttp, wb3.getCreationHelper().createFormulaEvaluator()); - - FormulaEvaluator evaluator = wb2.getCreationHelper().createFormulaEvaluator(); - evaluator.setupReferencedWorkbooks(evaluators); - - - // Try to evaluate, with the other file - evaluator.evaluateFormulaCellEnum(c1); - evaluator.evaluateFormulaCellEnum(c2); - - assertEquals(otherCellText, c1.getStringCellValue()); - assertEquals(otherCellText, c2.getStringCellValue()); - - wb3.close(); - wb2.close(); - } - - @Test - public void test56574OverwriteExistingRow() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet(); - - { // create the Formula-Cell - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - cell.setCellFormula("A2"); - } - - { // check that it is there now - Row row = sheet.getRow(0); - - /* CTCell[] cArray = ((XSSFRow)row).getCTRow().getCArray(); - assertEquals(1, cArray.length);*/ - - Cell cell = row.getCell(0); - assertEquals(CellType.FORMULA, cell.getCellTypeEnum()); - } - - { // overwrite the row - Row row = sheet.createRow(0); - assertNotNull(row); - } - - { // creating a row in place of another should remove the existing data, - // check that the cell is gone now - Row row = sheet.getRow(0); - - /*CTCell[] cArray = ((XSSFRow)row).getCTRow().getCArray(); - assertEquals(0, cArray.length);*/ - - Cell cell = row.getCell(0); - assertNull(cell); - } - - // the calculation chain in XSSF is empty in a newly created workbook, so we cannot check if it is correctly updated - /*assertNull(((XSSFWorkbook)wb).getCalculationChain()); - assertNotNull(((XSSFWorkbook)wb).getCalculationChain().getCTCalcChain()); - assertNotNull(((XSSFWorkbook)wb).getCalculationChain().getCTCalcChain().getCArray()); - assertEquals(0, ((XSSFWorkbook)wb).getCalculationChain().getCTCalcChain().getCArray().length);*/ - - wb.close(); - } - - /** - * With HSSF, if you create a font, don't change it, and - * create a 2nd, you really do get two fonts that you - * can alter as and when you want. - * With XSSF, that wasn't the case, but this verifies - * that it now is again - */ - @Test - public void bug48718() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - int startingFonts = wb instanceof HSSFWorkbook ? 4 : 1; - - assertEquals(startingFonts, wb.getNumberOfFonts()); - - // Get a font, and slightly change it - Font a = wb.createFont(); - assertEquals(startingFonts+1, wb.getNumberOfFonts()); - a.setFontHeightInPoints((short)23); - assertEquals(startingFonts+1, wb.getNumberOfFonts()); - - // Get two more, unchanged - /*Font b =*/ wb.createFont(); - assertEquals(startingFonts+2, wb.getNumberOfFonts()); - /*Font c =*/ wb.createFont(); - assertEquals(startingFonts+3, wb.getNumberOfFonts()); - - wb.close(); - } - - @Test - public void bug57430() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - wb.createSheet("Sheet1"); - - Name name1 = wb.createName(); - name1.setNameName("FMLA"); - name1.setRefersToFormula("Sheet1!$B$3"); - wb.close(); - } - - @SuppressWarnings("deprecation") - @Test - public void bug56981() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - CellStyle vertTop = wb.createCellStyle(); - vertTop.setVerticalAlignment(CellStyle.VERTICAL_TOP); - CellStyle vertBottom = wb.createCellStyle(); - vertBottom.setVerticalAlignment(CellStyle.VERTICAL_BOTTOM); - Sheet sheet = wb.createSheet("Sheet 1"); - Row row = sheet.createRow(0); - Cell top = row.createCell(0); - Cell bottom = row.createCell(1); - top.setCellValue("Top"); - top.setCellStyle(vertTop); // comment this out to get all bottom-aligned - // cells - bottom.setCellValue("Bottom"); - bottom.setCellStyle(vertBottom); - row.setHeightInPoints(85.75f); // make it obvious - - /*FileOutputStream out = new FileOutputStream("c:\\temp\\56981.xlsx"); - try { - wb.write(out); - } finally { - out.close(); - }*/ - - wb.close(); - } - - @Test - public void test57973() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - - CreationHelper factory = wb.getCreationHelper(); - - Sheet sheet = wb.createSheet(); - Drawing drawing = sheet.createDrawingPatriarch(); - ClientAnchor anchor = factory.createClientAnchor(); - - Cell cell0 = sheet.createRow(0).createCell(0); - cell0.setCellValue("Cell0"); - - Comment comment0 = drawing.createCellComment(anchor); - RichTextString str0 = factory.createRichTextString("Hello, World1!"); - comment0.setString(str0); - comment0.setAuthor("Apache POI"); - cell0.setCellComment(comment0); - - anchor = factory.createClientAnchor(); - anchor.setCol1(1); - anchor.setCol2(1); - anchor.setRow1(1); - anchor.setRow2(1); - Cell cell1 = sheet.createRow(3).createCell(5); - cell1.setCellValue("F4"); - Comment comment1 = drawing.createCellComment(anchor); - RichTextString str1 = factory.createRichTextString("Hello, World2!"); - comment1.setString(str1); - comment1.setAuthor("Apache POI"); - cell1.setCellComment(comment1); - - Cell cell2 = sheet.createRow(2).createCell(2); - cell2.setCellValue("C3"); - - anchor = factory.createClientAnchor(); - anchor.setCol1(2); - anchor.setCol2(2); - anchor.setRow1(2); - anchor.setRow2(2); - - Comment comment2 = drawing.createCellComment(anchor); - RichTextString str2 = factory.createRichTextString("XSSF can set cell comments"); - //apply custom font to the text in the comment - Font font = wb.createFont(); - font.setFontName("Arial"); - font.setFontHeightInPoints((short)14); - font.setBold(true); - font.setColor(IndexedColors.RED.getIndex()); - str2.applyFont(font); - - comment2.setString(str2); - comment2.setAuthor("Apache POI"); - comment2.setColumn(2); - comment2.setRow(2); - - wb.close(); - } - - /** - * Ensures that XSSF and HSSF agree with each other, - * and with the docs on when fetching the wrong - * kind of value from a Formula cell - */ - @Test - public void bug47815() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet s = wb.createSheet(); - Row r = s.createRow(0); - - // Setup - Cell cn = r.createCell(0, CellType.NUMERIC); - cn.setCellValue(1.2); - Cell cs = r.createCell(1, CellType.STRING); - cs.setCellValue("Testing"); - - Cell cfn = r.createCell(2, CellType.FORMULA); - cfn.setCellFormula("A1"); - Cell cfs = r.createCell(3, CellType.FORMULA); - cfs.setCellFormula("B1"); - - FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); - assertEquals(CellType.NUMERIC, fe.evaluate(cfn).getCellTypeEnum()); - assertEquals(CellType.STRING, fe.evaluate(cfs).getCellTypeEnum()); - fe.evaluateFormulaCellEnum(cfn); - fe.evaluateFormulaCellEnum(cfs); - - // Now test - assertEquals(CellType.NUMERIC, cn.getCellTypeEnum()); - assertEquals(CellType.STRING, cs.getCellTypeEnum()); - assertEquals(CellType.FORMULA, cfn.getCellTypeEnum()); - assertEquals(CellType.NUMERIC, cfn.getCachedFormulaResultTypeEnum()); - assertEquals(CellType.FORMULA, cfs.getCellTypeEnum()); - assertEquals(CellType.STRING, cfs.getCachedFormulaResultTypeEnum()); - - // Different ways of retrieving - assertEquals(1.2, cn.getNumericCellValue(), 0); - try { - cn.getRichStringCellValue(); - fail(); - } catch(IllegalStateException e) { - // expected here - } - - assertEquals("Testing", cs.getStringCellValue()); - try { - cs.getNumericCellValue(); - fail(); - } catch(IllegalStateException e) { - // expected here - } - - assertEquals(1.2, cfn.getNumericCellValue(), 0); - try { - cfn.getRichStringCellValue(); - fail(); - } catch(IllegalStateException e) { - // expected here - } - - assertEquals("Testing", cfs.getStringCellValue()); - try { - cfs.getNumericCellValue(); - fail(); - } catch(IllegalStateException e) { - // expected here - } - - wb.close(); - } - - @Test - public void test58113() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet( "Test" ); - - Row row = sheet.createRow(0); - - Cell cell = row.createCell(0); - // verify that null-values can be set, this was possible up to 3.11, but broken in 3.12 - cell.setCellValue((String)null); - String value = cell.getStringCellValue(); - assertTrue("HSSF will currently return empty string, XSSF/SXSSF will return null, but had: " + value, - value == null || value.length() == 0); - - cell = row.createCell(1); - // also verify that setting formulas to null works - cell.setCellType(CellType.FORMULA); - cell.setCellValue((String)null); - - wb.getCreationHelper().createFormulaEvaluator().evaluateAll(); - - value = cell.getStringCellValue(); - assertTrue("HSSF will currently return empty string, XSSF/SXSSF will return null, but had: " + value, - value == null || value.length() == 0); - - // set some value - cell.setCellType(CellType.STRING); - cell.setCellValue("somevalue"); - - value = cell.getStringCellValue(); - assertTrue("can set value afterwards: " + value, - value.equals("somevalue")); - - // verify that the null-value is actually set even if there was some value in the cell before - cell.setCellValue((String)null); - value = cell.getStringCellValue(); - assertTrue("HSSF will currently return empty string, XSSF/SXSSF will return null, but had: " + value, - value == null || value.length() == 0); - - wb.close(); - } - - /** - * Formulas with Nested Ifs, or If with text functions like - * Mid in it, can give #VALUE in Excel - */ - @Test - public void bug55747() throws IOException { - Workbook wb1 = _testDataProvider.createWorkbook(); - FormulaEvaluator ev = wb1.getCreationHelper().createFormulaEvaluator(); - Sheet s = wb1.createSheet(); - - Row row = s.createRow(0); - row.createCell(0).setCellValue("abc"); - row.createCell(1).setCellValue(""); - row.createCell(2).setCellValue(3); - - Cell cell = row.createCell(5); - cell.setCellFormula("IF(A1<>\"\",MID(A1,1,2),\" \")"); - ev.evaluateAll(); - assertEquals("ab", cell.getStringCellValue()); - - cell = row.createCell(6); - cell.setCellFormula("IF(B1<>\"\",MID(A1,1,2),\"empty\")"); - ev.evaluateAll(); - assertEquals("empty", cell.getStringCellValue()); - - cell = row.createCell(7); - cell.setCellFormula("IF(A1<>\"\",IF(C1<>\"\",MID(A1,1,2),\"c1\"),\"c2\")"); - ev.evaluateAll(); - assertEquals("ab", cell.getStringCellValue()); - - // Write it back out, and re-read - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - wb1.close(); - ev = wb2.getCreationHelper().createFormulaEvaluator(); - s = wb2.getSheetAt(0); - row = s.getRow(0); - - // Check read ok, and re-evaluate fine - cell = row.getCell(5); - assertEquals("ab", cell.getStringCellValue()); - ev.evaluateFormulaCellEnum(cell); - assertEquals("ab", cell.getStringCellValue()); - - cell = row.getCell(6); - assertEquals("empty", cell.getStringCellValue()); - ev.evaluateFormulaCellEnum(cell); - assertEquals("empty", cell.getStringCellValue()); - - cell = row.getCell(7); - assertEquals("ab", cell.getStringCellValue()); - ev.evaluateFormulaCellEnum(cell); - assertEquals("ab", cell.getStringCellValue()); - wb2.close(); - } - - @SuppressWarnings("deprecation") - @Test - public void bug58260() throws IOException { - //Create workbook and worksheet - Workbook wb = _testDataProvider.createWorkbook(); - //Sheet worksheet = wb.createSheet("sample"); - - //Loop through and add all values from array list - // use a fixed seed to always produce the same file which makes comparing stuff easier - //Random rnd = new Random(4352345); - int maxStyles = (wb instanceof HSSFWorkbook) ? 4009 : 64000; - for(int i = 0;i < maxStyles;i++) { - //Create new row - //Row row = worksheet.createRow(i); - - //Create cell style - CellStyle style = null; - try { - style = wb.createCellStyle(); - } catch (IllegalStateException e) { - fail("Failed for row " + i); - } - style.setAlignment(CellStyle.ALIGN_RIGHT); - if((wb instanceof HSSFWorkbook)) { - // there are some predefined styles - assertEquals(i+21, style.getIndex()); - } else { - // getIndex() returns short, which is not sufficient for > 32767 - // we should really change the API to be "int" for getIndex() but - // that needs API changes - assertEquals(i+1, style.getIndex() & 0xffff); - } - - //Create cell - //Cell cell = row.createCell(0); - - //Set cell style - //cell.setCellStyle(style); - - //Set cell value - //cell.setCellValue("r" + rnd.nextInt()); - } - - // should fail if we try to add more now - try { - wb.createCellStyle(); - fail("Should fail after " + maxStyles + " styles, but did not fail"); - } catch (IllegalStateException e) { - // expected here - } - - /*//add column width for appearance sake - worksheet.setColumnWidth(0, 5000); - - // Write the output to a file - System.out.println("Writing..."); - OutputStream fileOut = new FileOutputStream("C:\\temp\\58260." + _testDataProvider.getStandardFileNameExtension()); - - // the resulting file can be compressed nicely, so we need to disable the zip bomb detection here - double before = ZipSecureFile.getMinInflateRatio(); - try { - ZipSecureFile.setMinInflateRatio(0.00001); - wb.write(fileOut); - } finally { - fileOut.close(); - ZipSecureFile.setMinInflateRatio(before); - }*/ - - wb.close(); - } - - @Test - public void test50319() throws IOException { - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet("Test"); - sheet.createRow(0); - sheet.groupRow(0, 0); - sheet.setRowGroupCollapsed(0, true); - - sheet.groupColumn(0, 0); - sheet.setColumnGroupCollapsed(0, true); - - wb.close(); - } - - // Bug 58648: FormulaParser throws exception in parseSimpleFactor() when getCellFormula() - // is called on a cell and the formula contains spaces between closing parentheses ") )" - // https://bz.apache.org/bugzilla/show_bug.cgi?id=58648 - @Test - public void test58648() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Cell cell = wb.createSheet().createRow(0).createCell(0); - cell.setCellFormula("((1 + 1) )"); - // fails with - // org.apache.poi.ss.formula.FormulaParseException: Parse error near char ... ')' - // in specified formula '((1 + 1) )'. Expected cell ref or constant literal - - wb.close(); - } - - /** - * If someone sets a null string as a cell value, treat - * it as an empty cell, and avoid a NPE on auto-sizing - */ - @Test - public void test57034() throws Exception { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet s = wb.createSheet(); - Cell cell = s.createRow(0).createCell(0); - cell.setCellValue((String)null); - assertEquals(CellType.BLANK, cell.getCellTypeEnum()); - - _testDataProvider.trackAllColumnsForAutosizing(s); - - s.autoSizeColumn(0); - assertEquals(2048, s.getColumnWidth(0)); - - s.autoSizeColumn(0, true); - assertEquals(2048, s.getColumnWidth(0)); - - wb.close(); - } - - @Test - public void test52684() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - - Sheet sheet = wb.createSheet("test"); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - - cell.setCellValue(12312345123L); - - DataFormat format = wb.createDataFormat(); - CellStyle style = wb.createCellStyle(); - style.setDataFormat(format.getFormat("000-00000-000")); - cell.setCellStyle(style); - - assertEquals("000-00000-000", - cell.getCellStyle().getDataFormatString()); - assertEquals(164, cell.getCellStyle().getDataFormat()); - - DataFormatter formatter = new DataFormatter(); - - assertEquals("12-312-345-123", formatter.formatCellValue(cell)); - - wb.close(); - } - - @Test - public void test58896() throws IOException { - final int nrows = 160; - final int ncols = 139; - - // Create a workbook - final Workbook wb = _testDataProvider.createWorkbook(nrows+1); - final Sheet sh = wb.createSheet(); - if (logger.check(POILogger.DEBUG)) { - logger.log(POILogger.DEBUG, wb.getClass().getName() + " column autosizing timing..."); - } - - final long t0 = time(); - _testDataProvider.trackAllColumnsForAutosizing(sh); - for (int r=0; r 50000) { - // fail("Best fit width time per cell exceeded 50000 ns: " + bestFitWidthTimePerCell_ns + " ns"); - //} - - //if (totalTime_s > 10) { - // fail("Total time exceeded 10 seconds: " + totalTime_s + " s"); - //} - } - - protected long time() { - return System.currentTimeMillis(); - } - - protected double delta(long startTimeMillis) { - return time() - startTimeMillis; - } - - @Ignore("bug 59393") - @Test - public void bug59393_commentsCanHaveSameAnchor() throws IOException - { - Workbook wb = _testDataProvider.createWorkbook(); - - Sheet sheet = wb.createSheet(); - - CreationHelper helper = wb.getCreationHelper(); - ClientAnchor anchor = helper.createClientAnchor(); - Drawing drawing = sheet.createDrawingPatriarch(); - - Row row = sheet.createRow(0); - - Cell cell1 = row.createCell(0); - Cell cell2 = row.createCell(1); - Cell cell3 = row.createCell(2); - - Comment comment1 = drawing.createCellComment(anchor); - RichTextString richTextString1 = helper.createRichTextString("comment1"); - comment1.setString(richTextString1); - cell1.setCellComment(comment1); - - // fails with IllegalArgumentException("Multiple cell comments in one cell are not allowed, cell: A1") - // because createCellComment tries to create a cell at A1 - // (from CellAddress(anchor.getRow1(), anchor.getCell1())), - // but cell A1 already has a comment (comment1). - // Need to atomically create a comment and attach it to a cell. - // Current workaround: change anchor between each usage - // anchor.setCol1(1); - Comment comment2 = drawing.createCellComment(anchor); - RichTextString richTextString2 = helper.createRichTextString("comment2"); - comment2.setString(richTextString2); - cell2.setCellComment(comment2); - - // anchor.setCol1(2); - Comment comment3 = drawing.createCellComment(anchor); - RichTextString richTextString3 = helper.createRichTextString("comment3"); - comment3.setString(richTextString3); - cell3.setCellComment(comment3); - - wb.close(); - } - - - @Test - public void bug57798() throws Exception { - String fileName = "57798." + _testDataProvider.getStandardFileNameExtension(); - Workbook workbook = _testDataProvider.openSampleWorkbook(fileName); - - Sheet sheet = workbook.getSheet("Sheet1"); - - // ******************************* - // First cell of array formula, OK - int rowId = 0; - int cellId = 1; - System.out.println("Reading row " + rowId + ", col " + cellId); - - Row row = sheet.getRow(rowId); - Cell cell = row.getCell(cellId); - - System.out.println("Formula:" + cell.getCellFormula()); - if (CellType.FORMULA == cell.getCellTypeEnum()) { - CellType formulaResultType = cell.getCachedFormulaResultTypeEnum(); - System.out.println("Formula Result Type:" + formulaResultType); - } - - // ******************************* - // Second cell of array formula, NOT OK for xlsx files - rowId = 1; - cellId = 1; - System.out.println("Reading row " + rowId + ", col " + cellId); - - row = sheet.getRow(rowId); - cell = row.getCell(cellId); - System.out.println("Formula:" + cell.getCellFormula()); - - if (CellType.FORMULA == cell.getCellTypeEnum()) { - CellType formulaResultType = cell.getCachedFormulaResultTypeEnum(); - System.out.println("Formula Result Type:" + formulaResultType); - } - - workbook.close(); - } - - @Ignore - @Test - public void test57929() throws IOException { - // Create a workbook with print areas on 2 sheets - Workbook wb = _testDataProvider.createWorkbook(); - wb.createSheet("Sheet0"); - wb.createSheet("Sheet1"); - wb.setPrintArea(0, "$A$1:$C$6"); - wb.setPrintArea(1, "$B$1:$C$5"); - - // Verify the print areas were set correctly - assertEquals("Sheet0!$A$1:$C$6", wb.getPrintArea(0)); - assertEquals("Sheet1!$B$1:$C$5", wb.getPrintArea(1)); - - // Remove the print area on Sheet0 and change the print area on Sheet1 - wb.removePrintArea(0); - wb.setPrintArea(1, "$A$1:$A$1"); - - // Verify that the changes were made - assertNull("Sheet0 before write", wb.getPrintArea(0)); - assertEquals("Sheet1 before write", "Sheet1!$A$1:$A$1", wb.getPrintArea(1)); - - // Verify that the changes are non-volatile - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb); - wb.close(); - - assertNull("Sheet0 after write", wb2.getPrintArea(0)); // CURRENTLY FAILS with "Sheet0!$A$1:$C$6" - assertEquals("Sheet1 after write", "Sheet1!$A$1:$A$1", wb2.getPrintArea(1)); - } - - - @Test - public void test55384() throws Exception { - Workbook wb = _testDataProvider.createWorkbook(); - try { - Sheet sh = wb.createSheet(); - for (int rownum = 0; rownum < 10; rownum++) { - org.apache.poi.ss.usermodel.Row row = sh.createRow(rownum); - for (int cellnum = 0; cellnum < 3; cellnum++) { - Cell cell = row.createCell(cellnum); - cell.setCellValue(rownum + cellnum); - } - } - Row row = sh.createRow(10); - // setting no precalculated value works just fine. - Cell cell1 = row.createCell(0); - cell1.setCellFormula("SUM(A1:A10)"); - - // but setting a precalculated STRING value fails totally in SXSSF - Cell cell2 = row.createCell(1); - cell2.setCellFormula("SUM(B1:B10)"); - cell2.setCellValue("55"); - - // setting a precalculated int value works as expected - Cell cell3 = row.createCell(2); - cell3.setCellFormula("SUM(C1:C10)"); - cell3.setCellValue(65); - - assertEquals(CellType.FORMULA, cell1.getCellTypeEnum()); - assertEquals(CellType.FORMULA, cell2.getCellTypeEnum()); - assertEquals(CellType.FORMULA, cell3.getCellTypeEnum()); - - assertEquals("SUM(A1:A10)", cell1.getCellFormula()); - assertEquals("SUM(B1:B10)", cell2.getCellFormula()); - assertEquals("SUM(C1:C10)", cell3.getCellFormula()); - - /*String name = wb.getClass().getCanonicalName(); - String ext = (wb instanceof HSSFWorkbook) ? ".xls" : ".xlsx"; - OutputStream output = new FileOutputStream("/tmp" + name + ext); - try { - wb.write(output); - } finally { - output.close(); - }*/ - - Workbook wbBack = _testDataProvider.writeOutAndReadBack(wb); - checkFormulaPreevaluatedString(wbBack); - wbBack.close(); - } finally { - wb.close(); - } - } - - private void checkFormulaPreevaluatedString(Workbook readFile) { - Sheet sheet = readFile.getSheetAt(0); - Row row = sheet.getRow(sheet.getLastRowNum()); - assertEquals(10, row.getRowNum()); - - for (Cell cell : row) { - String cellValue; - switch (cell.getCellTypeEnum()) { - case STRING: - cellValue = cell.getRichStringCellValue().getString(); - break; - case FORMULA: - cellValue = cell.getCellFormula(); - break; - default: - fail("unexpected cell type"); - return; - } - assertNotNull(cellValue); - cellValue = cellValue.isEmpty() ? null : cellValue; - assertNotNull(cellValue); - } - } - - // bug 60197: setSheetOrder should update sheet-scoped named ranges to maintain references to the sheets before the re-order - @Test - public void bug60197_NamedRangesReferToCorrectSheetWhenSheetOrderIsChanged() throws Exception { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet1 = wb.createSheet("Sheet1"); - Sheet sheet2 = wb.createSheet("Sheet2"); - Sheet sheet3 = wb.createSheet("Sheet3"); - - Name nameOnSheet1 = wb.createName(); - nameOnSheet1.setSheetIndex(wb.getSheetIndex(sheet1)); - nameOnSheet1.setNameName("NameOnSheet1"); - nameOnSheet1.setRefersToFormula("Sheet1!A1"); - - Name nameOnSheet2 = wb.createName(); - nameOnSheet2.setSheetIndex(wb.getSheetIndex(sheet2)); - nameOnSheet2.setNameName("NameOnSheet2"); - nameOnSheet2.setRefersToFormula("Sheet2!A1"); - - Name nameOnSheet3 = wb.createName(); - nameOnSheet3.setSheetIndex(wb.getSheetIndex(sheet3)); - nameOnSheet3.setNameName("NameOnSheet3"); - nameOnSheet3.setRefersToFormula("Sheet3!A1"); - - // workbook-scoped name - Name name = wb.createName(); - name.setNameName("WorkbookScopedName"); - name.setRefersToFormula("Sheet2!A1"); - - assertEquals("Sheet1", nameOnSheet1.getSheetName()); - assertEquals("Sheet2", nameOnSheet2.getSheetName()); - assertEquals("Sheet3", nameOnSheet3.getSheetName()); - assertEquals(-1, name.getSheetIndex()); - assertEquals("Sheet2!A1", name.getRefersToFormula()); - - // rearrange the sheets several times to make sure the names always refer to the right sheet - for (int i=0; i<=9; i++) { - wb.setSheetOrder("Sheet3", i % 3); - - // Current bug in XSSF: - // Call stack: - // XSSFWorkbook.write(OutputStream) - // XSSFWorkbook.commit() - // XSSFWorkbook.saveNamedRanges() - // This dumps the current namedRanges to CTDefinedName and writes these to the CTWorkbook - // Then the XSSFName namedRanges list is cleared and rebuilt - // Thus, any XSSFName object becomes invalid after a write - // This re-assignment to the XSSFNames is not necessary if wb.write is not called. - nameOnSheet1 = wb.getName("NameOnSheet1"); - nameOnSheet2 = wb.getName("NameOnSheet2"); - nameOnSheet3 = wb.getName("NameOnSheet3"); - name = wb.getName("WorkbookScopedName"); - - // The name should still refer to the same sheet after the sheets are re-ordered - assertEquals(i % 3, wb.getSheetIndex("Sheet3")); - assertEquals(nameOnSheet1.getNameName(), "Sheet1", nameOnSheet1.getSheetName()); - assertEquals(nameOnSheet2.getNameName(), "Sheet2", nameOnSheet2.getSheetName()); - assertEquals(nameOnSheet3.getNameName(), "Sheet3", nameOnSheet3.getSheetName()); - assertEquals(name.getNameName(), -1, name.getSheetIndex()); - assertEquals(name.getNameName(), "Sheet2!A1", name.getRefersToFormula()); - - // make sure the changes to the names stick after writing out the workbook - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb); - - // See note above. XSSFNames become invalid after workbook write - // Without reassignment here, an XmlValueDisconnectedException may occur - nameOnSheet1 = wb.getName("NameOnSheet1"); - nameOnSheet2 = wb.getName("NameOnSheet2"); - nameOnSheet3 = wb.getName("NameOnSheet3"); - name = wb.getName("WorkbookScopedName"); - - // Saving the workbook should not change the sheet names - assertEquals(i % 3, wb.getSheetIndex("Sheet3")); - assertEquals(nameOnSheet1.getNameName(), "Sheet1", nameOnSheet1.getSheetName()); - assertEquals(nameOnSheet2.getNameName(), "Sheet2", nameOnSheet2.getSheetName()); - assertEquals(nameOnSheet3.getNameName(), "Sheet3", nameOnSheet3.getSheetName()); - assertEquals(name.getNameName(), -1, name.getSheetIndex()); - assertEquals(name.getNameName(), "Sheet2!A1", name.getRefersToFormula()); - - // Verify names in wb2 - nameOnSheet1 = wb2.getName("NameOnSheet1"); - nameOnSheet2 = wb2.getName("NameOnSheet2"); - nameOnSheet3 = wb2.getName("NameOnSheet3"); - name = wb2.getName("WorkbookScopedName"); - - assertEquals(i % 3, wb2.getSheetIndex("Sheet3")); - assertEquals(nameOnSheet1.getNameName(), "Sheet1", nameOnSheet1.getSheetName()); - assertEquals(nameOnSheet2.getNameName(), "Sheet2", nameOnSheet2.getSheetName()); - assertEquals(nameOnSheet3.getNameName(), "Sheet3", nameOnSheet3.getSheetName()); - assertEquals(name.getNameName(), -1, name.getSheetIndex()); - assertEquals(name.getNameName(), "Sheet2!A1", name.getRefersToFormula()); - - wb2.close(); - } - - wb.close(); - } - - @Test - public void test59200() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - final Sheet sheet = wb.createSheet(); - - DataValidation dataValidation; - CellRangeAddressList headerCell = new CellRangeAddressList(0, 1, 0, 1); - DataValidationConstraint constraint = sheet.getDataValidationHelper().createCustomConstraint("A1<>\"\""); - - dataValidation = sheet.getDataValidationHelper().createValidation(constraint, headerCell); - - // HSSF has 32/255 limits as part of the Spec, XSSF has no limit in the spec, but Excel applies a 255 length limit! - // more than 255 fail for all - checkFailures(dataValidation, TEST_256, TEST_32, true); - checkFailures(dataValidation, TEST_32, TEST_256, true); - - // null does work - checkFailures(dataValidation, null, null, false); - - // more than 32 title fail for HSSFWorkbook - checkFailures(dataValidation, TEST_255, TEST_32, wb instanceof HSSFWorkbook); - - // special characters work - checkFailures(dataValidation, TEST_SPECIAL_TITLE, TEST_SPECIAL, false); - - // 32 length title and 255 length text work for both - checkFailures(dataValidation, TEST_32, TEST_255, false); - - dataValidation.setShowErrorBox(false); - sheet.addValidationData(dataValidation); - - // write out and read back in to trigger some more validation - final Workbook wbBack = _testDataProvider.writeOutAndReadBack(wb); - - final Sheet sheetBack = wbBack.getSheetAt(0); - final List dataValidations = sheetBack.getDataValidations(); - assertEquals(1, dataValidations.size()); - - /*String ext = (wb instanceof HSSFWorkbook) ? ".xls" : ".xlsx"; - OutputStream str = new FileOutputStream("C:\\temp\\59200" + ext); - try { - wb.write(str); - } finally { - str.close(); - }*/ - - wb.close(); - } - - private void checkFailures(DataValidation dataValidation, String title, String text, boolean shouldFail) { - try { - dataValidation.createPromptBox(title, text); - assertFalse("Should fail in a length-check, had " + (title == null ? null : title.length()) + " and " + (text == null ? null : text.length()), shouldFail); - } catch (IllegalStateException e) { - assertTrue("Should not fail in a length-check, had " + (title == null ? null : title.length()) + " and " + (text == null ? null : text.length()), shouldFail); - // expected here - } - try { - dataValidation.createErrorBox(title, text); - assertFalse("Should fail in a length-check, had " + (title == null ? null : title.length()) + " and " + (text == null ? null : text.length()), shouldFail); - } catch (IllegalStateException e) { - assertTrue("Should not fail in a length-check, had " + (title == null ? null : title.length()) + " and " + (text == null ? null : text.length()), shouldFail); - } - } - - @Test - public void test60370() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - final Sheet sheet = wb.createSheet(); - - DataValidation dataValidation; - CellRangeAddressList headerCell = new CellRangeAddressList(0, 1, 0, 1); - DataValidationConstraint constraint = sheet.getDataValidationHelper().createCustomConstraint("A1<>\"\""); - - dataValidation = sheet.getDataValidationHelper().createValidation(constraint, headerCell); - checkFailures(dataValidation, TEST_SPECIAL_TITLE, TEST_SPECIAL, false); - - dataValidation.setShowErrorBox(true); - dataValidation.setShowPromptBox(true); - sheet.addValidationData(dataValidation); - - // write out and read back in to trigger some more validation - final Workbook wbBack = _testDataProvider.writeOutAndReadBack(wb); - - final Sheet sheetBack = wbBack.getSheetAt(0); - final List dataValidations = sheetBack.getDataValidations(); - assertEquals(1, dataValidations.size()); - - /*String ext = (wb instanceof HSSFWorkbook) ? ".xls" : ".xlsx"; - OutputStream str = new FileOutputStream("/tmp/60370" + ext); - try { - wb.write(str); - } finally { - str.close(); - }*/ - - wb.close(); - } -} \ No newline at end of file diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestCell.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestCell.java deleted file mode 100644 index 0bec60ded..000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestCell.java +++ /dev/null @@ -1,1052 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import static org.apache.poi.ss.usermodel.FormulaError.forInt; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.IOException; -import java.util.Calendar; - -import org.apache.poi.common.usermodel.HyperlinkType; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.util.LocaleUtil; -import org.junit.Test; - -/** - * Common superclass for testing implementations of - * {@link org.apache.poi.ss.usermodel.Cell} - */ -public abstract class BaseTestCell { - - protected final ITestDataProvider _testDataProvider; - - /** - * @param testDataProvider an object that provides test data in HSSF / XSSF specific way - */ - protected BaseTestCell(ITestDataProvider testDataProvider) { - _testDataProvider = testDataProvider; - } - - @Test - public void testSetValues() throws Exception { - Workbook book = _testDataProvider.createWorkbook(); - Sheet sheet = book.createSheet("test"); - Row row = sheet.createRow(0); - - CreationHelper factory = book.getCreationHelper(); - Cell cell = row.createCell(0); - - cell.setCellValue(1.2); - assertEquals(1.2, cell.getNumericCellValue(), 0.0001); - assertEquals(CellType.NUMERIC, cell.getCellTypeEnum()); - assertProhibitedValueAccess(cell, CellType.BOOLEAN, CellType.STRING, - CellType.FORMULA, CellType.ERROR); - - cell.setCellValue(false); - assertEquals(false, cell.getBooleanCellValue()); - assertEquals(CellType.BOOLEAN, cell.getCellTypeEnum()); - cell.setCellValue(true); - assertEquals(true, cell.getBooleanCellValue()); - assertProhibitedValueAccess(cell, CellType.NUMERIC, CellType.STRING, - CellType.FORMULA, CellType.ERROR); - - cell.setCellValue(factory.createRichTextString("Foo")); - assertEquals("Foo", cell.getRichStringCellValue().getString()); - assertEquals("Foo", cell.getStringCellValue()); - assertEquals(CellType.STRING, cell.getCellTypeEnum()); - assertProhibitedValueAccess(cell, CellType.NUMERIC, CellType.BOOLEAN, - CellType.FORMULA, CellType.ERROR); - - cell.setCellValue("345"); - assertEquals("345", cell.getRichStringCellValue().getString()); - assertEquals("345", cell.getStringCellValue()); - assertEquals(CellType.STRING, cell.getCellTypeEnum()); - assertProhibitedValueAccess(cell, CellType.NUMERIC, CellType.BOOLEAN, - CellType.FORMULA, CellType.ERROR); - - Calendar c = LocaleUtil.getLocaleCalendar(); - c.setTimeInMillis(123456789); - cell.setCellValue(c.getTime()); - assertEquals(c.getTime().getTime(), cell.getDateCellValue().getTime()); - assertEquals(CellType.NUMERIC, cell.getCellTypeEnum()); - assertProhibitedValueAccess(cell, CellType.BOOLEAN, CellType.STRING, - CellType.FORMULA, CellType.ERROR); - - cell.setCellValue(c); - assertEquals(c.getTime().getTime(), cell.getDateCellValue().getTime()); - assertEquals(CellType.NUMERIC, cell.getCellTypeEnum()); - assertProhibitedValueAccess(cell, CellType.BOOLEAN, CellType.STRING, - CellType.FORMULA, CellType.ERROR); - - cell.setCellErrorValue(FormulaError.NA.getCode()); - assertEquals(FormulaError.NA.getCode(), cell.getErrorCellValue()); - assertEquals(CellType.ERROR, cell.getCellTypeEnum()); - assertProhibitedValueAccess(cell, CellType.NUMERIC, CellType.BOOLEAN, - CellType.FORMULA, CellType.STRING); - - book.close(); - } - - private static void assertProhibitedValueAccess(Cell cell, CellType ... types) { - for(CellType type : types){ - try { - switch (type) { - case NUMERIC: - cell.getNumericCellValue(); - break; - case STRING: - cell.getStringCellValue(); - break; - case BOOLEAN: - cell.getBooleanCellValue(); - break; - case FORMULA: - cell.getCellFormula(); - break; - case ERROR: - cell.getErrorCellValue(); - break; - default: - fail("Should get exception when reading cell type (" + type + ")."); - } - - } catch (IllegalStateException e){ - // expected during successful test - assertTrue(e.getMessage().startsWith("Cannot get a")); - } - } - } - - /** - * test that Boolean (BoolErrRecord) are supported properly. - * @see testErr - */ - @Test - public void testBool() throws IOException { - - Workbook wb1 = _testDataProvider.createWorkbook(); - Sheet s = wb1.createSheet("testSheet1"); - Row r; - Cell c; - // B1 - r = s.createRow(0); - c=r.createCell(1); - assertEquals(0, c.getRowIndex()); - assertEquals(1, c.getColumnIndex()); - c.setCellValue(true); - assertEquals("B1 value", true, c.getBooleanCellValue()); - - // C1 - c=r.createCell(2); - assertEquals(0, c.getRowIndex()); - assertEquals(2, c.getColumnIndex()); - c.setCellValue(false); - assertEquals("C1 value", false, c.getBooleanCellValue()); - - // Make sure values are saved and re-read correctly. - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - wb1.close(); - - s = wb2.getSheet("testSheet1"); - r = s.getRow(0); - assertEquals("Row 1 should have 2 cells", 2, r.getPhysicalNumberOfCells()); - - c = r.getCell(1); - assertEquals(0, c.getRowIndex()); - assertEquals(1, c.getColumnIndex()); - assertEquals(CellType.BOOLEAN, c.getCellTypeEnum()); - assertEquals("B1 value", true, c.getBooleanCellValue()); - - c = r.getCell(2); - assertEquals(0, c.getRowIndex()); - assertEquals(2, c.getColumnIndex()); - assertEquals(CellType.BOOLEAN, c.getCellTypeEnum()); - assertEquals("C1 value", false, c.getBooleanCellValue()); - - wb2.close(); - } - - /** - * test that Error types (BoolErrRecord) are supported properly. - * @see testBool - */ - @Test - public void testErr() throws IOException { - - Workbook wb1 = _testDataProvider.createWorkbook(); - Sheet s = wb1.createSheet("testSheet1"); - Row r; - Cell c; - - // B1 - r = s.createRow(0); - c=r.createCell(1); - assertEquals(0, c.getRowIndex()); - assertEquals(1, c.getColumnIndex()); - c.setCellErrorValue(FormulaError.NULL.getCode()); - assertEquals("B1 value == #NULL!", FormulaError.NULL.getCode(), c.getErrorCellValue()); - - // C1 - c=r.createCell(2); - assertEquals(0, c.getRowIndex()); - assertEquals(2, c.getColumnIndex()); - c.setCellErrorValue(FormulaError.DIV0.getCode()); - assertEquals("C1 value == #DIV/0!", FormulaError.DIV0.getCode(), c.getErrorCellValue()); - - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - wb1.close(); - - s = wb2.getSheet("testSheet1"); - - r = s.getRow(0); - assertEquals("Row 1 should have 2 cells", 2, r.getPhysicalNumberOfCells()); - - c = r.getCell(1); - assertEquals(0, c.getRowIndex()); - assertEquals(1, c.getColumnIndex()); - assertEquals(CellType.ERROR, c.getCellTypeEnum()); - assertEquals("B1 value == #NULL!", FormulaError.NULL.getCode(), c.getErrorCellValue()); - - c = r.getCell(2); - assertEquals(0, c.getRowIndex()); - assertEquals(2, c.getColumnIndex()); - assertEquals(CellType.ERROR, c.getCellTypeEnum()); - assertEquals("C1 value == #DIV/0!", FormulaError.DIV0.getCode(), c.getErrorCellValue()); - - wb2.close(); - } - - /** - * test that Cell Styles being applied to formulas remain intact - */ - @Test - public void testFormulaStyle() throws Exception { - - Workbook wb1 = _testDataProvider.createWorkbook(); - Sheet s = wb1.createSheet("testSheet1"); - Row r = null; - Cell c = null; - CellStyle cs = wb1.createCellStyle(); - Font f = wb1.createFont(); - f.setFontHeightInPoints((short) 20); - f.setColor(IndexedColors.RED.getIndex()); - f.setBold(true); - f.setFontName("Arial Unicode MS"); - cs.setFillBackgroundColor((short)3); - cs.setFont(f); - cs.setBorderTop(BorderStyle.THIN); - cs.setBorderRight(BorderStyle.THIN); - cs.setBorderLeft(BorderStyle.THIN); - cs.setBorderBottom(BorderStyle.THIN); - - r = s.createRow(0); - c=r.createCell(0); - c.setCellStyle(cs); - c.setCellFormula("2*3"); - - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - wb1.close(); - s = wb2.getSheetAt(0); - r = s.getRow(0); - c = r.getCell(0); - - assertEquals("Formula Cell at 0,0", CellType.FORMULA, c.getCellTypeEnum()); - cs = c.getCellStyle(); - - assertNotNull("Formula Cell Style", cs); - assertEquals("Font Index Matches", f.getIndex(), cs.getFontIndex()); - assertEquals("Top Border", BorderStyle.THIN, cs.getBorderTopEnum()); - assertEquals("Left Border", BorderStyle.THIN, cs.getBorderLeftEnum()); - assertEquals("Right Border", BorderStyle.THIN, cs.getBorderRightEnum()); - assertEquals("Bottom Border", BorderStyle.THIN, cs.getBorderBottomEnum()); - wb2.close(); - } - - /**tests the toString() method of HSSFCell*/ - @Test - public void testToString() throws Exception { - Workbook wb1 = _testDataProvider.createWorkbook(); - Row r = wb1.createSheet("Sheet1").createRow(0); - CreationHelper factory = wb1.getCreationHelper(); - - r.createCell(0).setCellValue(false); - r.createCell(1).setCellValue(true); - r.createCell(2).setCellValue(1.5); - r.createCell(3).setCellValue(factory.createRichTextString("Astring")); - r.createCell(4).setCellErrorValue(FormulaError.DIV0.getCode()); - r.createCell(5).setCellFormula("A1+B1"); - r.createCell(6); // blank - - // create date-formatted cell - Calendar c = LocaleUtil.getLocaleCalendar(); - c.set(2010, 01, 02, 00, 00, 00); - r.createCell(7).setCellValue(c); - CellStyle dateStyle = wb1.createCellStyle(); - short formatId = wb1.getCreationHelper().createDataFormat().getFormat("m/d/yy h:mm"); // any date format will do - dateStyle.setDataFormat(formatId); - r.getCell(7).setCellStyle(dateStyle); - - assertEquals("Boolean", "FALSE", r.getCell(0).toString()); - assertEquals("Boolean", "TRUE", r.getCell(1).toString()); - assertEquals("Numeric", "1.5", r.getCell(2).toString()); - assertEquals("String", "Astring", r.getCell(3).toString()); - assertEquals("Error", "#DIV/0!", r.getCell(4).toString()); - assertEquals("Formula", "A1+B1", r.getCell(5).toString()); - assertEquals("Blank", "", r.getCell(6).toString()); - // toString on a date-formatted cell displays dates as dd-MMM-yyyy, which has locale problems with the month - String dateCell1 = r.getCell(7).toString(); - assertTrue("Date (Day)", dateCell1.startsWith("02-")); - assertTrue("Date (Year)", dateCell1.endsWith("-2010")); - - - //Write out the file, read it in, and then check cell values - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - wb1.close(); - - r = wb2.getSheetAt(0).getRow(0); - assertEquals("Boolean", "FALSE", r.getCell(0).toString()); - assertEquals("Boolean", "TRUE", r.getCell(1).toString()); - assertEquals("Numeric", "1.5", r.getCell(2).toString()); - assertEquals("String", "Astring", r.getCell(3).toString()); - assertEquals("Error", "#DIV/0!", r.getCell(4).toString()); - assertEquals("Formula", "A1+B1", r.getCell(5).toString()); - assertEquals("Blank", "", r.getCell(6).toString()); - String dateCell2 = r.getCell(7).toString(); - assertEquals("Date", dateCell1, dateCell2); - wb2.close(); - } - - /** - * Test that setting cached formula result keeps the cell type - */ - @Test - public void testSetFormulaValue() throws Exception { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet s = wb.createSheet(); - Row r = s.createRow(0); - - Cell c1 = r.createCell(0); - c1.setCellFormula("NA()"); - assertEquals(0.0, c1.getNumericCellValue(), 0.0); - assertEquals(CellType.NUMERIC, c1.getCachedFormulaResultTypeEnum()); - c1.setCellValue(10); - assertEquals(10.0, c1.getNumericCellValue(), 0.0); - assertEquals(CellType.FORMULA, c1.getCellTypeEnum()); - assertEquals(CellType.NUMERIC, c1.getCachedFormulaResultTypeEnum()); - - Cell c2 = r.createCell(1); - c2.setCellFormula("NA()"); - assertEquals(0.0, c2.getNumericCellValue(), 0.0); - assertEquals(CellType.NUMERIC, c2.getCachedFormulaResultTypeEnum()); - c2.setCellValue("I changed!"); - assertEquals("I changed!", c2.getStringCellValue()); - assertEquals(CellType.FORMULA, c2.getCellTypeEnum()); - assertEquals(CellType.STRING, c2.getCachedFormulaResultTypeEnum()); - - //calglin Cell.setCellFormula(null) for a non-formula cell - Cell c3 = r.createCell(2); - c3.setCellFormula(null); - assertEquals(CellType.BLANK, c3.getCellTypeEnum()); - wb.close(); - - } - - private Cell createACell(Workbook wb) { - return wb.createSheet("Sheet1").createRow(0).createCell(0); - } - - /** - * bug 58452: Copy cell formulas containing unregistered function names - * Make sure that formulas with unknown/unregistered UDFs can be written to and read back from a file. - * - * @throws IOException - */ - @Test - public void testFormulaWithUnknownUDF() throws IOException { - final Workbook wb1 = _testDataProvider.createWorkbook(); - final FormulaEvaluator evaluator1 = wb1.getCreationHelper().createFormulaEvaluator(); - try { - final Cell cell1 = wb1.createSheet().createRow(0).createCell(0); - final String formula = "myFunc(\"arg\")"; - cell1.setCellFormula(formula); - confirmFormulaWithUnknownUDF(formula, cell1, evaluator1); - - final Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - final FormulaEvaluator evaluator2 = wb2.getCreationHelper().createFormulaEvaluator(); - try { - final Cell cell2 = wb2.getSheetAt(0).getRow(0).getCell(0); - confirmFormulaWithUnknownUDF(formula, cell2, evaluator2); - } finally { - wb2.close(); - } - } finally { - wb1.close(); - } - } - - private static void confirmFormulaWithUnknownUDF(String expectedFormula, Cell cell, FormulaEvaluator evaluator) { - assertEquals(expectedFormula, cell.getCellFormula()); - try { - evaluator.evaluate(cell); - fail("Expected NotImplementedFunctionException/NotImplementedException"); - } catch (final org.apache.poi.ss.formula.eval.NotImplementedException e) { - // expected - } - } - - @Test - public void testChangeTypeStringToBool() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - - Cell cell = createACell(wb); - - cell.setCellValue("TRUE"); - assertEquals(CellType.STRING, cell.getCellTypeEnum()); - // test conversion of cell from text to boolean - cell.setCellType(CellType.BOOLEAN); - - assertEquals(CellType.BOOLEAN, cell.getCellTypeEnum()); - assertEquals(true, cell.getBooleanCellValue()); - cell.setCellType(CellType.STRING); - assertEquals("TRUE", cell.getRichStringCellValue().getString()); - - // 'false' text to bool and back - cell.setCellValue("FALSE"); - cell.setCellType(CellType.BOOLEAN); - assertEquals(CellType.BOOLEAN, cell.getCellTypeEnum()); - assertEquals(false, cell.getBooleanCellValue()); - cell.setCellType(CellType.STRING); - assertEquals("FALSE", cell.getRichStringCellValue().getString()); - - wb.close(); - } - - @Test - public void testChangeTypeBoolToString() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - - Cell cell = createACell(wb); - - cell.setCellValue(true); - // test conversion of cell from boolean to text - cell.setCellType(CellType.STRING); - assertEquals("TRUE", cell.getRichStringCellValue().getString()); - - wb.close(); - } - - @Test - public void testChangeTypeErrorToNumber() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - - Cell cell = createACell(wb); - cell.setCellErrorValue(FormulaError.NAME.getCode()); - try { - cell.setCellValue(2.5); - } catch (ClassCastException e) { - fail("Identified bug 46479b"); - } - assertEquals(2.5, cell.getNumericCellValue(), 0.0); - - wb.close(); - } - - @Test - public void testChangeTypeErrorToBoolean() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - - Cell cell = createACell(wb); - cell.setCellErrorValue(FormulaError.NAME.getCode()); - cell.setCellValue(true); - // Identify bug 46479c - assertEquals(true, cell.getBooleanCellValue()); - - wb.close(); - } - - /** - * Test for a bug observed around svn r886733 when using - * {@link FormulaEvaluator#evaluateInCell(Cell)} with a - * string result type. - */ - @Test - public void testConvertStringFormulaCell() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - - Cell cellA1 = createACell(wb); - cellA1.setCellFormula("\"abc\""); - - // default cached formula result is numeric zero - assertEquals(0.0, cellA1.getNumericCellValue(), 0.0); - - FormulaEvaluator fe = cellA1.getSheet().getWorkbook().getCreationHelper().createFormulaEvaluator(); - - fe.evaluateFormulaCellEnum(cellA1); - assertEquals("abc", cellA1.getStringCellValue()); - - fe.evaluateInCell(cellA1); - assertFalse("Identified bug with writing back formula result of type string", cellA1.getStringCellValue().equals("")); - assertEquals("abc", cellA1.getStringCellValue()); - - wb.close(); - } - - /** - * similar to {@link #testConvertStringFormulaCell()} but checks at a - * lower level that {#link {@link Cell#setCellType(int)} works properly - */ - @Test - public void testSetTypeStringOnFormulaCell() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - - Cell cellA1 = createACell(wb); - FormulaEvaluator fe = cellA1.getSheet().getWorkbook().getCreationHelper().createFormulaEvaluator(); - - cellA1.setCellFormula("\"DEF\""); - fe.clearAllCachedResultValues(); - fe.evaluateFormulaCellEnum(cellA1); - assertEquals("DEF", cellA1.getStringCellValue()); - cellA1.setCellType(CellType.STRING); - assertEquals("DEF", cellA1.getStringCellValue()); - - cellA1.setCellFormula("25.061"); - fe.clearAllCachedResultValues(); - fe.evaluateFormulaCellEnum(cellA1); - confirmCannotReadString(cellA1); - assertEquals(25.061, cellA1.getNumericCellValue(), 0.0); - cellA1.setCellType(CellType.STRING); - assertEquals("25.061", cellA1.getStringCellValue()); - - cellA1.setCellFormula("TRUE"); - fe.clearAllCachedResultValues(); - fe.evaluateFormulaCellEnum(cellA1); - confirmCannotReadString(cellA1); - assertEquals(true, cellA1.getBooleanCellValue()); - cellA1.setCellType(CellType.STRING); - assertEquals("TRUE", cellA1.getStringCellValue()); - - cellA1.setCellFormula("#NAME?"); - fe.clearAllCachedResultValues(); - fe.evaluateFormulaCellEnum(cellA1); - confirmCannotReadString(cellA1); - assertEquals(FormulaError.NAME, forInt(cellA1.getErrorCellValue())); - cellA1.setCellType(CellType.STRING); - assertEquals("#NAME?", cellA1.getStringCellValue()); - - wb.close(); - } - - private static void confirmCannotReadString(Cell cell) { - assertProhibitedValueAccess(cell, CellType.STRING); - } - - /** - * Test for bug in convertCellValueToBoolean to make sure that formula results get converted - */ - @Test - public void testChangeTypeFormulaToBoolean() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - - Cell cell = createACell(wb); - cell.setCellFormula("1=1"); - cell.setCellValue(true); - cell.setCellType(CellType.BOOLEAN); - assertTrue("Identified bug 46479d", cell.getBooleanCellValue()); - assertEquals(true, cell.getBooleanCellValue()); - - wb.close(); - } - - /** - * Bug 40296: HSSFCell.setCellFormula throws - * ClassCastException if cell is created using HSSFRow.createCell(short column, int type) - */ - @Test - public void test40296() throws Exception { - Workbook wb1 = _testDataProvider.createWorkbook(); - Sheet workSheet = wb1.createSheet("Sheet1"); - Cell cell; - Row row = workSheet.createRow(0); - - cell = row.createCell(0, CellType.NUMERIC); - cell.setCellValue(1.0); - assertEquals(CellType.NUMERIC, cell.getCellTypeEnum()); - assertEquals(1.0, cell.getNumericCellValue(), 0.0); - - cell = row.createCell(1, CellType.NUMERIC); - cell.setCellValue(2.0); - assertEquals(CellType.NUMERIC, cell.getCellTypeEnum()); - assertEquals(2.0, cell.getNumericCellValue(), 0.0); - - cell = row.createCell(2, CellType.FORMULA); - cell.setCellFormula("SUM(A1:B1)"); - assertEquals(CellType.FORMULA, cell.getCellTypeEnum()); - assertEquals("SUM(A1:B1)", cell.getCellFormula()); - - //serialize and check again - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - wb1.close(); - row = wb2.getSheetAt(0).getRow(0); - cell = row.getCell(0); - assertEquals(CellType.NUMERIC, cell.getCellTypeEnum()); - assertEquals(1.0, cell.getNumericCellValue(), 0.0); - - cell = row.getCell(1); - assertEquals(CellType.NUMERIC, cell.getCellTypeEnum()); - assertEquals(2.0, cell.getNumericCellValue(), 0.0); - - cell = row.getCell(2); - assertEquals(CellType.FORMULA, cell.getCellTypeEnum()); - assertEquals("SUM(A1:B1)", cell.getCellFormula()); - wb2.close(); - } - - @Test - public void testSetStringInFormulaCell_bug44606() throws Exception { - Workbook wb = _testDataProvider.createWorkbook(); - Cell cell = wb.createSheet("Sheet1").createRow(0).createCell(0); - cell.setCellFormula("B1&C1"); - cell.setCellValue(wb.getCreationHelper().createRichTextString("hello")); - wb.close(); - } - - /** - * Make sure that cell.setCellType(CellType.BLANK) preserves the cell style - */ - @Test - public void testSetBlank_bug47028() throws Exception { - Workbook wb = _testDataProvider.createWorkbook(); - CellStyle style = wb.createCellStyle(); - Cell cell = wb.createSheet("Sheet1").createRow(0).createCell(0); - cell.setCellStyle(style); - int i1 = cell.getCellStyle().getIndex(); - cell.setCellType(CellType.BLANK); - int i2 = cell.getCellStyle().getIndex(); - assertEquals(i1, i2); - wb.close(); - } - - /** - * Excel's implementation of floating number arithmetic does not fully adhere to IEEE 754: - * - * From http://support.microsoft.com/kb/78113: - * - *
      - *
    • Positive/Negative Infinities: - * Infinities occur when you divide by 0. Excel does not support infinities, rather, - * it gives a #DIV/0! error in these cases. - *
    • - *
    • - * Not-a-Number (NaN): - * NaN is used to represent invalid operations (such as infinity/infinity, - * infinity-infinity, or the square root of -1). NaNs allow a program to - * continue past an invalid operation. Excel instead immediately generates - * an error such as #NUM! or #DIV/0!. - *
    • - *
    - */ - @Test - public void testNanAndInfinity() throws Exception { - Workbook wb1 = _testDataProvider.createWorkbook(); - Sheet workSheet = wb1.createSheet("Sheet1"); - Row row = workSheet.createRow(0); - - Cell cell0 = row.createCell(0); - cell0.setCellValue(Double.NaN); - assertEquals("Double.NaN should change cell type to CellType#ERROR", CellType.ERROR, cell0.getCellTypeEnum()); - assertEquals("Double.NaN should change cell value to #NUM!", FormulaError.NUM, forInt(cell0.getErrorCellValue())); - - Cell cell1 = row.createCell(1); - cell1.setCellValue(Double.POSITIVE_INFINITY); - assertEquals("Double.POSITIVE_INFINITY should change cell type to CellType#ERROR", CellType.ERROR, cell1.getCellTypeEnum()); - assertEquals("Double.POSITIVE_INFINITY should change cell value to #DIV/0!", FormulaError.DIV0, forInt(cell1.getErrorCellValue())); - - Cell cell2 = row.createCell(2); - cell2.setCellValue(Double.NEGATIVE_INFINITY); - assertEquals("Double.NEGATIVE_INFINITY should change cell type to CellType#ERROR", CellType.ERROR, cell2.getCellTypeEnum()); - assertEquals("Double.NEGATIVE_INFINITY should change cell value to #DIV/0!", FormulaError.DIV0, forInt(cell2.getErrorCellValue())); - - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - wb1.close(); - row = wb2.getSheetAt(0).getRow(0); - - cell0 = row.getCell(0); - assertEquals(CellType.ERROR, cell0.getCellTypeEnum()); - assertEquals(FormulaError.NUM, forInt(cell0.getErrorCellValue())); - - cell1 = row.getCell(1); - assertEquals(CellType.ERROR, cell1.getCellTypeEnum()); - assertEquals(FormulaError.DIV0, forInt(cell1.getErrorCellValue())); - - cell2 = row.getCell(2); - assertEquals(CellType.ERROR, cell2.getCellTypeEnum()); - assertEquals(FormulaError.DIV0, forInt(cell2.getErrorCellValue())); - wb2.close(); - } - - @Test - public void testDefaultStyleProperties() throws Exception { - Workbook wb1 = _testDataProvider.createWorkbook(); - - Cell cell = wb1.createSheet("Sheet1").createRow(0).createCell(0); - CellStyle style = cell.getCellStyle(); - - assertTrue(style.getLocked()); - assertFalse(style.getHidden()); - assertEquals(0, style.getIndention()); - assertEquals(0, style.getFontIndex()); - assertEquals(HorizontalAlignment.GENERAL, style.getAlignmentEnum()); - assertEquals(0, style.getDataFormat()); - assertEquals(false, style.getWrapText()); - - CellStyle style2 = wb1.createCellStyle(); - assertTrue(style2.getLocked()); - assertFalse(style2.getHidden()); - style2.setLocked(false); - style2.setHidden(true); - assertFalse(style2.getLocked()); - assertTrue(style2.getHidden()); - - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - wb1.close(); - cell = wb2.getSheetAt(0).getRow(0).getCell(0); - style = cell.getCellStyle(); - assertFalse(style2.getLocked()); - assertTrue(style2.getHidden()); - - style2.setLocked(true); - style2.setHidden(false); - assertTrue(style2.getLocked()); - assertFalse(style2.getHidden()); - wb2.close(); - } - - @Test - public void testBug55658SetNumericValue() throws Exception { - Workbook wb1 = _testDataProvider.createWorkbook(); - Sheet sh = wb1.createSheet(); - Row row = sh.createRow(0); - Cell cell = row.createCell(0); - cell.setCellValue(Integer.valueOf(23)); - - cell.setCellValue("some"); - - cell = row.createCell(1); - cell.setCellValue(Integer.valueOf(23)); - - cell.setCellValue("24"); - - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - wb1.close(); - - assertEquals("some", wb2.getSheetAt(0).getRow(0).getCell(0).getStringCellValue()); - assertEquals("24", wb2.getSheetAt(0).getRow(0).getCell(1).getStringCellValue()); - wb2.close(); - } - - @Test - public void testRemoveHyperlink() throws Exception { - Workbook wb1 = _testDataProvider.createWorkbook(); - Sheet sh = wb1.createSheet("test"); - Row row = sh.createRow(0); - CreationHelper helper = wb1.getCreationHelper(); - - Cell cell1 = row.createCell(1); - Hyperlink link1 = helper.createHyperlink(HyperlinkType.URL); - cell1.setHyperlink(link1); - assertNotNull(cell1.getHyperlink()); - cell1.removeHyperlink(); - assertNull(cell1.getHyperlink()); - - Cell cell2 = row.createCell(0); - Hyperlink link2 = helper.createHyperlink(HyperlinkType.URL); - cell2.setHyperlink(link2); - assertNotNull(cell2.getHyperlink()); - cell2.setHyperlink(null); - assertNull(cell2.getHyperlink()); - - Cell cell3 = row.createCell(2); - Hyperlink link3 = helper.createHyperlink(HyperlinkType.URL); - link3.setAddress("http://poi.apache.org/"); - cell3.setHyperlink(link3); - assertNotNull(cell3.getHyperlink()); - - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - wb1.close(); - assertNotNull(wb2); - - cell1 = wb2.getSheet("test").getRow(0).getCell(1); - assertNull(cell1.getHyperlink()); - cell2 = wb2.getSheet("test").getRow(0).getCell(0); - assertNull(cell2.getHyperlink()); - cell3 = wb2.getSheet("test").getRow(0).getCell(2); - assertNotNull(cell3.getHyperlink()); - wb2.close(); - } - - /** - * Cell with the formula that returns error must return error code(There was - * an problem that cell could not return error value form formula cell). - * @throws IOException - */ - @Test - public void testGetErrorCellValueFromFormulaCell() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - try { - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - cell.setCellFormula("SQRT(-1)"); - wb.getCreationHelper().createFormulaEvaluator().evaluateFormulaCellEnum(cell); - assertEquals(36, cell.getErrorCellValue()); - } finally { - wb.close(); - } - } - - @Test - public void testSetRemoveStyle() throws Exception { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - - // different default style indexes for HSSF and XSSF/SXSSF - CellStyle defaultStyle = wb.getCellStyleAt(wb instanceof HSSFWorkbook ? (short)15 : (short)0); - - // Starts out with the default style - assertEquals(defaultStyle, cell.getCellStyle()); - - // Create some styles, no change - CellStyle style1 = wb.createCellStyle(); - CellStyle style2 = wb.createCellStyle(); - style1.setDataFormat((short)2); - style2.setDataFormat((short)3); - - assertEquals(defaultStyle, cell.getCellStyle()); - - // Apply one, changes - cell.setCellStyle(style1); - assertEquals(style1, cell.getCellStyle()); - - // Apply the other, changes - cell.setCellStyle(style2); - assertEquals(style2, cell.getCellStyle()); - - // Remove, goes back to default - cell.setCellStyle(null); - assertEquals(defaultStyle, cell.getCellStyle()); - - // Add back, returns - cell.setCellStyle(style2); - assertEquals(style2, cell.getCellStyle()); - - wb.close(); - } - - @Test - public void test57008() throws IOException { - Workbook wb1 = _testDataProvider.createWorkbook(); - Sheet sheet = wb1.createSheet(); - - Row row0 = sheet.createRow(0); - Cell cell0 = row0.createCell(0); - cell0.setCellValue("row 0, cell 0 _x0046_ without changes"); - - Cell cell1 = row0.createCell(1); - cell1.setCellValue("row 0, cell 1 _x005fx0046_ with changes"); - - Cell cell2 = row0.createCell(2); - cell2.setCellValue("hgh_x0041_**_x0100_*_x0101_*_x0190_*_x0200_*_x0300_*_x0427_*"); - - checkUnicodeValues(wb1); - - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - checkUnicodeValues(wb2); - wb2.close(); - wb1.close(); - } - - /** - * Setting a cell value of a null RichTextString should set - * the cell to Blank, test case for 58558 - */ - @Test - public void testSetCellValueNullRichTextString() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet(); - Cell cell = sheet.createRow(0).createCell(0); - - RichTextString nullStr = null; - cell.setCellValue(nullStr); - assertEquals("", cell.getStringCellValue()); - assertEquals(CellType.BLANK, cell.getCellTypeEnum()); - - cell = sheet.createRow(0).createCell(1); - cell.setCellValue(1.2d); - assertEquals(CellType.NUMERIC, cell.getCellTypeEnum()); - cell.setCellValue(nullStr); - assertEquals("", cell.getStringCellValue()); - assertEquals(CellType.BLANK, cell.getCellTypeEnum()); - - cell = sheet.createRow(0).createCell(1); - cell.setCellValue(wb.getCreationHelper().createRichTextString("Test")); - assertEquals(CellType.STRING, cell.getCellTypeEnum()); - cell.setCellValue(nullStr); - assertEquals("", cell.getStringCellValue()); - assertEquals(CellType.BLANK, cell.getCellTypeEnum()); - - wb.close(); - } - - private void checkUnicodeValues(Workbook wb) { - assertEquals((wb instanceof HSSFWorkbook ? "row 0, cell 0 _x0046_ without changes" : "row 0, cell 0 F without changes"), - wb.getSheetAt(0).getRow(0).getCell(0).toString()); - assertEquals((wb instanceof HSSFWorkbook ? "row 0, cell 1 _x005fx0046_ with changes" : "row 0, cell 1 _x005fx0046_ with changes"), - wb.getSheetAt(0).getRow(0).getCell(1).toString()); - assertEquals((wb instanceof HSSFWorkbook ? "hgh_x0041_**_x0100_*_x0101_*_x0190_*_x0200_*_x0300_*_x0427_*" : "hghA**\u0100*\u0101*\u0190*\u0200*\u0300*\u0427*"), - wb.getSheetAt(0).getRow(0).getCell(2).toString()); - } - - /** - * The maximum length of cell contents (text) is 32,767 characters. - * @throws IOException - */ - @Test - public void testMaxTextLength() throws IOException{ - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet(); - Cell cell = sheet.createRow(0).createCell(0); - - int maxlen = wb instanceof HSSFWorkbook ? - SpreadsheetVersion.EXCEL97.getMaxTextLength() - : SpreadsheetVersion.EXCEL2007.getMaxTextLength(); - assertEquals(32767, maxlen); - - StringBuffer b = new StringBuffer() ; - - // 32767 is okay - for( int i = 0 ; i < maxlen ; i++ ) - { - b.append( "X" ) ; - } - cell.setCellValue(b.toString()); - - b.append("X"); - // 32768 produces an invalid XLS file - try { - cell.setCellValue(b.toString()); - fail("Expected exception"); - } catch (IllegalArgumentException e){ - assertEquals("The maximum length of cell contents (text) is 32,767 characters", e.getMessage()); - } - wb.close(); - } - - /** - * Tests that the setAsActiveCell and getActiveCell function pairs work together - */ - @Test - public void setAsActiveCell() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell A1 = row.createCell(0); - Cell B1 = row.createCell(1); - - A1.setAsActiveCell(); - assertEquals(A1.getAddress(), sheet.getActiveCell()); - - B1.setAsActiveCell(); - assertEquals(B1.getAddress(), sheet.getActiveCell()); - - wb.close(); - } - - @Test - public void getCellComment() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet(); - CreationHelper factory = wb.getCreationHelper(); - Row row = sheet.createRow(0); - Cell cell = row.createCell(1); - - // cell does not have a comment - assertNull(cell.getCellComment()); - - // add a cell comment - ClientAnchor anchor = factory.createClientAnchor(); - anchor.setCol1(cell.getColumnIndex()); - anchor.setCol2(cell.getColumnIndex()+1); - anchor.setRow1(row.getRowNum()); - anchor.setRow2(row.getRowNum()+3); - - Drawing drawing = sheet.createDrawingPatriarch(); - Comment comment = drawing.createCellComment(anchor); - RichTextString str = factory.createRichTextString("Hello, World!"); - comment.setString(str); - comment.setAuthor("Apache POI"); - cell.setCellComment(comment); - // ideally assertSame, but XSSFCell creates a new XSSFCellComment wrapping the same bean for every call to getCellComment. - assertEquals(comment, cell.getCellComment()); - - wb.close(); - } - - @Test - public void primitiveToEnumReplacementDoesNotBreakBackwardsCompatibility() throws IOException { - // bug 59836 - // until we have changes POI from working on primitives (int) to enums, - // we should make sure we minimize backwards compatibility breakages. - // This method tests the old way of working with cell types, alignment, etc. - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - - // Cell.CELL_TYPE_* -> CellType.* - cell.setCellValue(5.0); - assertEquals(Cell.CELL_TYPE_NUMERIC, cell.getCellType()); - assertEquals(0, cell.getCellType()); //make sure that hard-coded int literals still work, even though users should be using the named constants - assertEquals(CellType.NUMERIC, cell.getCellTypeEnum()); // make sure old way and new way are compatible - - // make sure switch(int|Enum) still works. Cases must be statically resolvable in Java 6 ("constant expression required") - switch(cell.getCellType()) { - case Cell.CELL_TYPE_NUMERIC: - // expected - break; - case Cell.CELL_TYPE_STRING: - case Cell.CELL_TYPE_BOOLEAN: - case Cell.CELL_TYPE_ERROR: - case Cell.CELL_TYPE_FORMULA: - case Cell.CELL_TYPE_BLANK: - default: - fail("unexpected cell type: " + cell.getCellType()); - } - - wb.close(); - } -} diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestCellComment.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestCellComment.java deleted file mode 100644 index 535094ff0..000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestCellComment.java +++ /dev/null @@ -1,419 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import static org.apache.poi.util.Units.EMU_PER_PIXEL; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.ss.util.CellAddress; -import org.apache.poi.util.Units; -import org.junit.Test; - -/** - * Common superclass for testing implementations of - * {@link Comment} - */ -public abstract class BaseTestCellComment { - - private final ITestDataProvider _testDataProvider; - - protected BaseTestCellComment(ITestDataProvider testDataProvider) { - _testDataProvider = testDataProvider; - } - - @Test - public final void find() throws IOException { - Workbook book = _testDataProvider.createWorkbook(); - Sheet sheet = book.createSheet(); - assertNull(sheet.getCellComment(new CellAddress(0, 0))); - - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - assertNull(sheet.getCellComment(new CellAddress(0, 0))); - assertNull(cell.getCellComment()); - book.close(); - } - - @Test - public final void create() throws IOException { - String cellText = "Hello, World"; - String commentText = "We can set comments in POI"; - String commentAuthor = "Apache Software Foundation"; - int cellRow = 3; - int cellColumn = 1; - - Workbook wb1 = _testDataProvider.createWorkbook(); - CreationHelper factory = wb1.getCreationHelper(); - - Sheet sheet = wb1.createSheet(); - assertNull(sheet.getCellComment(new CellAddress(cellRow, cellColumn))); - - Cell cell = sheet.createRow(cellRow).createCell(cellColumn); - cell.setCellValue(factory.createRichTextString(cellText)); - assertNull(cell.getCellComment()); - assertNull(sheet.getCellComment(new CellAddress(cellRow, cellColumn))); - - Drawing patr = sheet.createDrawingPatriarch(); - ClientAnchor anchor = factory.createClientAnchor(); - anchor.setCol1(2); - anchor.setCol2(5); - anchor.setRow1(1); - anchor.setRow2(2); - Comment comment = patr.createCellComment(anchor); - assertFalse(comment.isVisible()); - comment.setVisible(true); - assertTrue(comment.isVisible()); - RichTextString string1 = factory.createRichTextString(commentText); - comment.setString(string1); - comment.setAuthor(commentAuthor); - cell.setCellComment(comment); - assertNotNull(cell.getCellComment()); - assertNotNull(sheet.getCellComment(new CellAddress(cellRow, cellColumn))); - - //verify our settings - assertEquals(commentAuthor, comment.getAuthor()); - assertEquals(commentText, comment.getString().getString()); - assertEquals(cellRow, comment.getRow()); - assertEquals(cellColumn, comment.getColumn()); - - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - wb1.close(); - - sheet = wb2.getSheetAt(0); - cell = sheet.getRow(cellRow).getCell(cellColumn); - comment = cell.getCellComment(); - - assertNotNull(comment); - assertEquals(commentAuthor, comment.getAuthor()); - assertEquals(commentText, comment.getString().getString()); - assertEquals(cellRow, comment.getRow()); - assertEquals(cellColumn, comment.getColumn()); - assertTrue(comment.isVisible()); - - // Change slightly, and re-test - comment.setString(factory.createRichTextString("New Comment Text")); - comment.setVisible(false); - - Workbook wb3 = _testDataProvider.writeOutAndReadBack(wb2); - wb2.close(); - - sheet = wb3.getSheetAt(0); - cell = sheet.getRow(cellRow).getCell(cellColumn); - comment = cell.getCellComment(); - - assertNotNull(comment); - assertEquals(commentAuthor, comment.getAuthor()); - assertEquals("New Comment Text", comment.getString().getString()); - assertEquals(cellRow, comment.getRow()); - assertEquals(cellColumn, comment.getColumn()); - assertFalse(comment.isVisible()); - - // Test Comment.equals and Comment.hashCode - assertEquals(comment, cell.getCellComment()); - assertEquals(comment.hashCode(), cell.getCellComment().hashCode()); - - wb3.close(); - } - - /** - * test that we can read cell comments from an existing workbook. - */ - @Test - public final void readComments() throws IOException { - - Workbook wb = _testDataProvider.openSampleWorkbook("SimpleWithComments." + _testDataProvider.getStandardFileNameExtension()); - - Sheet sheet = wb.getSheetAt(0); - - Cell cell; - Row row; - Comment comment; - - for (int rownum = 0; rownum < 3; rownum++) { - row = sheet.getRow(rownum); - cell = row.getCell(0); - comment = cell.getCellComment(); - assertNull("Cells in the first column are not commented", comment); - assertNull(sheet.getCellComment(new CellAddress(rownum, 0))); - } - - for (int rownum = 0; rownum < 3; rownum++) { - row = sheet.getRow(rownum); - cell = row.getCell(1); - comment = cell.getCellComment(); - assertNotNull("Cells in the second column have comments", comment); - assertNotNull("Cells in the second column have comments", sheet.getCellComment(new CellAddress(rownum, 1))); - - assertEquals("Yegor Kozlov", comment.getAuthor()); - assertFalse("cells in the second column have not empyy notes", - "".equals(comment.getString().getString())); - assertEquals(rownum, comment.getRow()); - assertEquals(cell.getColumnIndex(), comment.getColumn()); - } - - wb.close(); - } - - /** - * test that we can modify existing cell comments - */ - @Test - public final void modifyComments() throws IOException { - - Workbook wb1 = _testDataProvider.openSampleWorkbook("SimpleWithComments." + _testDataProvider.getStandardFileNameExtension()); - CreationHelper factory = wb1.getCreationHelper(); - - Sheet sheet = wb1.getSheetAt(0); - - Cell cell; - Row row; - Comment comment; - - for (int rownum = 0; rownum < 3; rownum++) { - row = sheet.getRow(rownum); - cell = row.getCell(1); - comment = cell.getCellComment(); - comment.setAuthor("Mofified[" + rownum + "] by Yegor"); - comment.setString(factory.createRichTextString("Modified comment at row " + rownum)); - } - - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - wb1.close(); - sheet = wb2.getSheetAt(0); - - for (int rownum = 0; rownum < 3; rownum++) { - row = sheet.getRow(rownum); - cell = row.getCell(1); - comment = cell.getCellComment(); - - assertEquals("Mofified[" + rownum + "] by Yegor", comment.getAuthor()); - assertEquals("Modified comment at row " + rownum, comment.getString().getString()); - } - - wb2.close(); - } - - @Test - public final void deleteComments() throws IOException { - Workbook wb1 = _testDataProvider.openSampleWorkbook("SimpleWithComments." + _testDataProvider.getStandardFileNameExtension()); - Sheet sheet = wb1.getSheetAt(0); - - // Zap from rows 1 and 3 - assertNotNull(sheet.getRow(0).getCell(1).getCellComment()); - assertNotNull(sheet.getRow(1).getCell(1).getCellComment()); - assertNotNull(sheet.getRow(2).getCell(1).getCellComment()); - - sheet.getRow(0).getCell(1).removeCellComment(); - sheet.getRow(2).getCell(1).setCellComment(null); - - // Check gone so far - assertNull(sheet.getRow(0).getCell(1).getCellComment()); - assertNotNull(sheet.getRow(1).getCell(1).getCellComment()); - assertNull(sheet.getRow(2).getCell(1).getCellComment()); - - // Save and re-load - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - wb1.close(); - sheet = wb2.getSheetAt(0); - // Check - assertNull(sheet.getRow(0).getCell(1).getCellComment()); - assertNotNull(sheet.getRow(1).getCell(1).getCellComment()); - assertNull(sheet.getRow(2).getCell(1).getCellComment()); - - wb2.close(); - } - - /** - * code from the quick guide - */ - @Test - public void quickGuide() throws IOException { - Workbook wb1 = _testDataProvider.createWorkbook(); - - CreationHelper factory = wb1.getCreationHelper(); - - Sheet sheet = wb1.createSheet(); - - Cell cell = sheet.createRow(3).createCell(5); - cell.setCellValue("F4"); - - Drawing drawing = sheet.createDrawingPatriarch(); - - ClientAnchor anchor = factory.createClientAnchor(); - Comment comment = drawing.createCellComment(anchor); - RichTextString str = factory.createRichTextString("Hello, World!"); - comment.setString(str); - comment.setAuthor("Apache POI"); - //assign the comment to the cell - cell.setCellComment(comment); - - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - wb1.close(); - sheet = wb2.getSheetAt(0); - cell = sheet.getRow(3).getCell(5); - comment = cell.getCellComment(); - assertNotNull(comment); - assertEquals("Hello, World!", comment.getString().getString()); - assertEquals("Apache POI", comment.getAuthor()); - assertEquals(3, comment.getRow()); - assertEquals(5, comment.getColumn()); - - wb2.close(); - } - - @Test - public void getClientAnchor() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(10); - Cell cell = row.createCell(5); - CreationHelper factory = wb.getCreationHelper(); - - Drawing drawing = sheet.createDrawingPatriarch(); - - double r_mul, c_mul; - if (sheet instanceof HSSFSheet) { - double rowheight = Units.toEMU(row.getHeightInPoints())/EMU_PER_PIXEL; - r_mul = 256.0/rowheight; - double colwidth = sheet.getColumnWidthInPixels(2); - c_mul = 1024.0/colwidth; - } else { - r_mul = c_mul = EMU_PER_PIXEL; - } - - int dx1 = (int)Math.round(10*c_mul); - int dy1 = (int)Math.round(10*r_mul); - int dx2 = (int)Math.round(3*c_mul); - int dy2 = (int)Math.round(4*r_mul); - int col1 = cell.getColumnIndex()+1; - int row1 = row.getRowNum(); - int col2 = cell.getColumnIndex()+2; - int row2 = row.getRowNum()+1; - - ClientAnchor anchor = drawing.createAnchor(dx1, dy1, dx2, dy2, col1, row1, col2, row2); - Comment comment = drawing.createCellComment(anchor); - comment.setVisible(true); - cell.setCellComment(comment); - - anchor = comment.getClientAnchor(); - assertEquals(dx1, anchor.getDx1()); - assertEquals(dy1, anchor.getDy1()); - assertEquals(dx2, anchor.getDx2()); - assertEquals(dy2, anchor.getDy2()); - assertEquals(col1, anchor.getCol1()); - assertEquals(row1, anchor.getRow1()); - assertEquals(col2, anchor.getCol2()); - assertEquals(row2, anchor.getRow2()); - - anchor = factory.createClientAnchor(); - comment = drawing.createCellComment(anchor); - cell.setCellComment(comment); - anchor = comment.getClientAnchor(); - - if (sheet instanceof HSSFSheet) { - assertEquals(0, anchor.getCol1()); - assertEquals(0, anchor.getDx1()); - assertEquals(0, anchor.getRow1()); - assertEquals(0, anchor.getDy1()); - assertEquals(0, anchor.getCol2()); - assertEquals(0, anchor.getDx2()); - assertEquals(0, anchor.getRow2()); - assertEquals(0, anchor.getDy2()); - } else { - // when anchor is initialized without parameters, the comment anchor attributes default to - // "1, 15, 0, 2, 3, 15, 3, 16" ... see XSSFVMLDrawing.newCommentShape() - assertEquals( 1, anchor.getCol1()); - assertEquals(15*EMU_PER_PIXEL, anchor.getDx1()); - assertEquals( 0, anchor.getRow1()); - assertEquals( 2*EMU_PER_PIXEL, anchor.getDy1()); - assertEquals( 3, anchor.getCol2()); - assertEquals(15*EMU_PER_PIXEL, anchor.getDx2()); - assertEquals( 3, anchor.getRow2()); - assertEquals(16*EMU_PER_PIXEL, anchor.getDy2()); - } - - wb.close(); - } - - @Test - public void attemptToSave2CommentsWithSameCoordinates() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sh = wb.createSheet(); - CreationHelper factory = wb.getCreationHelper(); - Drawing patriarch = sh.createDrawingPatriarch(); - patriarch.createCellComment(factory.createClientAnchor()); - - try { - patriarch.createCellComment(factory.createClientAnchor()); - _testDataProvider.writeOutAndReadBack(wb); - fail("Should not be able to create a corrupted workbook with multiple cell comments in one cell"); - } catch (IllegalStateException e) { - // HSSFWorkbooks fail when writing out workbook - assertEquals("found multiple cell comments for cell $A$1", e.getMessage()); - } catch (IllegalArgumentException e) { - // XSSFWorkbooks fail when creating and setting the cell address of the comment - assertEquals("Multiple cell comments in one cell are not allowed, cell: A1", e.getMessage()); - } finally { - wb.close(); - } - } - - @Test - public void getAddress() { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sh = wb.createSheet(); - CreationHelper factory = wb.getCreationHelper(); - Drawing patriarch = sh.createDrawingPatriarch(); - Comment comment = patriarch.createCellComment(factory.createClientAnchor()); - - assertEquals(CellAddress.A1, comment.getAddress()); - Cell C2 = sh.createRow(1).createCell(2); - C2.setCellComment(comment); - assertEquals(new CellAddress("C2"), comment.getAddress()); - } - - @Test - public void setAddress() { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sh = wb.createSheet(); - CreationHelper factory = wb.getCreationHelper(); - Drawing patriarch = sh.createDrawingPatriarch(); - Comment comment = patriarch.createCellComment(factory.createClientAnchor()); - - assertEquals(CellAddress.A1, comment.getAddress()); - CellAddress C2 = new CellAddress("C2"); - assertEquals("C2", C2.formatAsString()); - comment.setAddress(C2); - assertEquals(C2, comment.getAddress()); - - CellAddress E10 = new CellAddress(9, 4); - assertEquals("E10", E10.formatAsString()); - comment.setAddress(9, 4); - assertEquals(E10, comment.getAddress()); - } -} diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestCloneSheet.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestCloneSheet.java deleted file mode 100644 index f6c47af84..000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestCloneSheet.java +++ /dev/null @@ -1,100 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.ss.util.CellRangeAddress; -import org.junit.Test; - -import java.io.IOException; - -import static org.junit.Assert.*; - -/** - * Common superclass for testing implementations of - * Workbook.cloneSheet() - */ -public abstract class BaseTestCloneSheet { - - private final ITestDataProvider _testDataProvider; - - protected BaseTestCloneSheet(ITestDataProvider testDataProvider) { - _testDataProvider = testDataProvider; - } - - @Test - public void testCloneSheetBasic() throws IOException{ - Workbook b = _testDataProvider.createWorkbook(); - Sheet s = b.createSheet("Test"); - s.addMergedRegion(new CellRangeAddress(0, 1, 0, 1)); - Sheet clonedSheet = b.cloneSheet(0); - - assertEquals("One merged area", 1, clonedSheet.getNumMergedRegions()); - - b.close(); - } - - /** - * Ensures that pagebreak cloning works properly - * @throws IOException - */ - @Test - public void testPageBreakClones() throws IOException { - Workbook b = _testDataProvider.createWorkbook(); - Sheet s = b.createSheet("Test"); - s.setRowBreak(3); - s.setColumnBreak((short) 6); - - Sheet clone = b.cloneSheet(0); - assertTrue("Row 3 not broken", clone.isRowBroken(3)); - assertTrue("Column 6 not broken", clone.isColumnBroken((short) 6)); - - s.removeRowBreak(3); - - assertTrue("Row 3 still should be broken", clone.isRowBroken(3)); - - b.close(); - } - - @Test - public void testCloneSheetIntValid() { - Workbook wb = _testDataProvider.createWorkbook(); - wb.createSheet("Sheet01"); - wb.cloneSheet(0); - assertEquals(2, wb.getNumberOfSheets()); - try { - wb.cloneSheet(2); - fail("ShouldFail"); - } catch (IllegalArgumentException e) { - // expected here - } - } - - @Test - public void testCloneSheetIntInvalid() { - Workbook wb = _testDataProvider.createWorkbook(); - wb.createSheet("Sheet01"); - try { - wb.cloneSheet(1); - fail("Should Fail"); - } catch (IllegalArgumentException e) { - // expected here - } - assertEquals(1, wb.getNumberOfSheets()); - } -} diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestConditionalFormatting.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestConditionalFormatting.java deleted file mode 100644 index d1b429010..000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestConditionalFormatting.java +++ /dev/null @@ -1,1436 +0,0 @@ -/* - * ==================================================================== - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ==================================================================== - */ - -package org.apache.poi.ss.usermodel; - -import org.apache.poi.hssf.usermodel.HSSFConditionalFormatting; -import org.apache.poi.hssf.usermodel.HSSFConditionalFormattingRule; -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.ss.usermodel.ConditionalFormattingThreshold.RangeType; -import org.apache.poi.ss.usermodel.IconMultiStateFormatting.IconSet; -import org.apache.poi.ss.util.CellRangeAddress; -import org.junit.Test; - -import java.io.IOException; - -import static org.junit.Assert.*; - -/** - * Base tests for Conditional Formatting, for both HSSF and XSSF - */ -public abstract class BaseTestConditionalFormatting { - private final ITestDataProvider _testDataProvider; - - public BaseTestConditionalFormatting(ITestDataProvider testDataProvider){ - _testDataProvider = testDataProvider; - } - - protected abstract void assertColour(String hexExpected, Color actual); - - @Test - public void testBasic() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sh = wb.createSheet(); - SheetConditionalFormatting sheetCF = sh.getSheetConditionalFormatting(); - - assertEquals(0, sheetCF.getNumConditionalFormattings()); - try { - assertNull(sheetCF.getConditionalFormattingAt(0)); - fail("expected exception"); - } catch (IllegalArgumentException e) { - assertTrue(e.getMessage().startsWith("Specified CF index 0 is outside the allowable range")); - } - - try { - sheetCF.removeConditionalFormatting(0); - fail("expected exception"); - } catch (IllegalArgumentException e) { - assertTrue(e.getMessage().startsWith("Specified CF index 0 is outside the allowable range")); - } - - ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("1"); - ConditionalFormattingRule rule2 = sheetCF.createConditionalFormattingRule("2"); - ConditionalFormattingRule rule3 = sheetCF.createConditionalFormattingRule("3"); - ConditionalFormattingRule rule4 = sheetCF.createConditionalFormattingRule("4"); - try { - sheetCF.addConditionalFormatting(null, rule1); - fail("expected exception"); - } catch (IllegalArgumentException e) { - assertTrue(e.getMessage().startsWith("regions must not be null")); - } - try { - sheetCF.addConditionalFormatting( - new CellRangeAddress[]{ CellRangeAddress.valueOf("A1:A3") }, - (ConditionalFormattingRule)null); - fail("expected exception"); - } catch (IllegalArgumentException e) { - assertTrue(e.getMessage().startsWith("cfRules must not be null")); - } - - try { - sheetCF.addConditionalFormatting( - new CellRangeAddress[]{ CellRangeAddress.valueOf("A1:A3") }, - new ConditionalFormattingRule[0]); - fail("expected exception"); - } catch (IllegalArgumentException e) { - assertTrue(e.getMessage().startsWith("cfRules must not be empty")); - } - - try { - sheetCF.addConditionalFormatting( - new CellRangeAddress[]{ CellRangeAddress.valueOf("A1:A3") }, - new ConditionalFormattingRule[]{rule1, rule2, rule3, rule4}); - fail("expected exception"); - } catch (IllegalArgumentException e) { - assertTrue(e.getMessage().startsWith("Number of rules must not exceed 3")); - } - wb.close(); - } - - /** - * Test format conditions based on a boolean formula - */ - @Test - public void testBooleanFormulaConditions() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sh = wb.createSheet(); - SheetConditionalFormatting sheetCF = sh.getSheetConditionalFormatting(); - - ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("SUM(A1:A5)>10"); - assertEquals(ConditionType.FORMULA, rule1.getConditionType()); - assertEquals("SUM(A1:A5)>10", rule1.getFormula1()); - int formatIndex1 = sheetCF.addConditionalFormatting( - new CellRangeAddress[]{ - CellRangeAddress.valueOf("B1"), - CellRangeAddress.valueOf("C3"), - }, rule1); - assertEquals(0, formatIndex1); - assertEquals(1, sheetCF.getNumConditionalFormattings()); - CellRangeAddress[] ranges1 = sheetCF.getConditionalFormattingAt(formatIndex1).getFormattingRanges(); - assertEquals(2, ranges1.length); - assertEquals("B1", ranges1[0].formatAsString()); - assertEquals("C3", ranges1[1].formatAsString()); - - // adjacent address are merged - int formatIndex2 = sheetCF.addConditionalFormatting( - new CellRangeAddress[]{ - CellRangeAddress.valueOf("B1"), - CellRangeAddress.valueOf("B2"), - CellRangeAddress.valueOf("B3"), - }, rule1); - assertEquals(1, formatIndex2); - assertEquals(2, sheetCF.getNumConditionalFormattings()); - CellRangeAddress[] ranges2 = sheetCF.getConditionalFormattingAt(formatIndex2).getFormattingRanges(); - assertEquals(1, ranges2.length); - assertEquals("B1:B3", ranges2[0].formatAsString()); - wb.close(); - } - - @Test - public void testSingleFormulaConditions() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sh = wb.createSheet(); - SheetConditionalFormatting sheetCF = sh.getSheetConditionalFormatting(); - - ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule( - ComparisonOperator.EQUAL, "SUM(A1:A5)+10"); - assertEquals(ConditionType.CELL_VALUE_IS, rule1.getConditionType()); - assertEquals("SUM(A1:A5)+10", rule1.getFormula1()); - assertEquals(ComparisonOperator.EQUAL, rule1.getComparisonOperation()); - - ConditionalFormattingRule rule2 = sheetCF.createConditionalFormattingRule( - ComparisonOperator.NOT_EQUAL, "15"); - assertEquals(ConditionType.CELL_VALUE_IS, rule2.getConditionType()); - assertEquals("15", rule2.getFormula1()); - assertEquals(ComparisonOperator.NOT_EQUAL, rule2.getComparisonOperation()); - - ConditionalFormattingRule rule3 = sheetCF.createConditionalFormattingRule( - ComparisonOperator.NOT_EQUAL, "15"); - assertEquals(ConditionType.CELL_VALUE_IS, rule3.getConditionType()); - assertEquals("15", rule3.getFormula1()); - assertEquals(ComparisonOperator.NOT_EQUAL, rule3.getComparisonOperation()); - - ConditionalFormattingRule rule4 = sheetCF.createConditionalFormattingRule( - ComparisonOperator.GT, "0"); - assertEquals(ConditionType.CELL_VALUE_IS, rule4.getConditionType()); - assertEquals("0", rule4.getFormula1()); - assertEquals(ComparisonOperator.GT, rule4.getComparisonOperation()); - - ConditionalFormattingRule rule5 = sheetCF.createConditionalFormattingRule( - ComparisonOperator.LT, "0"); - assertEquals(ConditionType.CELL_VALUE_IS, rule5.getConditionType()); - assertEquals("0", rule5.getFormula1()); - assertEquals(ComparisonOperator.LT, rule5.getComparisonOperation()); - - ConditionalFormattingRule rule6 = sheetCF.createConditionalFormattingRule( - ComparisonOperator.GE, "0"); - assertEquals(ConditionType.CELL_VALUE_IS, rule6.getConditionType()); - assertEquals("0", rule6.getFormula1()); - assertEquals(ComparisonOperator.GE, rule6.getComparisonOperation()); - - ConditionalFormattingRule rule7 = sheetCF.createConditionalFormattingRule( - ComparisonOperator.LE, "0"); - assertEquals(ConditionType.CELL_VALUE_IS, rule7.getConditionType()); - assertEquals("0", rule7.getFormula1()); - assertEquals(ComparisonOperator.LE, rule7.getComparisonOperation()); - - ConditionalFormattingRule rule8 = sheetCF.createConditionalFormattingRule( - ComparisonOperator.BETWEEN, "0", "5"); - assertEquals(ConditionType.CELL_VALUE_IS, rule8.getConditionType()); - assertEquals("0", rule8.getFormula1()); - assertEquals("5", rule8.getFormula2()); - assertEquals(ComparisonOperator.BETWEEN, rule8.getComparisonOperation()); - - ConditionalFormattingRule rule9 = sheetCF.createConditionalFormattingRule( - ComparisonOperator.NOT_BETWEEN, "0", "5"); - assertEquals(ConditionType.CELL_VALUE_IS, rule9.getConditionType()); - assertEquals("0", rule9.getFormula1()); - assertEquals("5", rule9.getFormula2()); - assertEquals(ComparisonOperator.NOT_BETWEEN, rule9.getComparisonOperation()); - - wb.close(); - } - - @Test - public void testCopy() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet1 = wb.createSheet(); - Sheet sheet2 = wb.createSheet(); - SheetConditionalFormatting sheet1CF = sheet1.getSheetConditionalFormatting(); - SheetConditionalFormatting sheet2CF = sheet2.getSheetConditionalFormatting(); - assertEquals(0, sheet1CF.getNumConditionalFormattings()); - assertEquals(0, sheet2CF.getNumConditionalFormattings()); - - ConditionalFormattingRule rule1 = sheet1CF.createConditionalFormattingRule( - ComparisonOperator.EQUAL, "SUM(A1:A5)+10"); - - ConditionalFormattingRule rule2 = sheet1CF.createConditionalFormattingRule( - ComparisonOperator.NOT_EQUAL, "15"); - - // adjacent address are merged - int formatIndex = sheet1CF.addConditionalFormatting( - new CellRangeAddress[]{ - CellRangeAddress.valueOf("A1:A5"), - CellRangeAddress.valueOf("C1:C5") - }, rule1, rule2); - assertEquals(0, formatIndex); - assertEquals(1, sheet1CF.getNumConditionalFormattings()); - - assertEquals(0, sheet2CF.getNumConditionalFormattings()); - sheet2CF.addConditionalFormatting(sheet1CF.getConditionalFormattingAt(formatIndex)); - assertEquals(1, sheet2CF.getNumConditionalFormattings()); - - ConditionalFormatting sheet2cf = sheet2CF.getConditionalFormattingAt(0); - assertEquals(2, sheet2cf.getNumberOfRules()); - assertEquals("SUM(A1:A5)+10", sheet2cf.getRule(0).getFormula1()); - assertEquals(ComparisonOperator.EQUAL, sheet2cf.getRule(0).getComparisonOperation()); - assertEquals(ConditionType.CELL_VALUE_IS, sheet2cf.getRule(0).getConditionType()); - assertEquals("15", sheet2cf.getRule(1).getFormula1()); - assertEquals(ComparisonOperator.NOT_EQUAL, sheet2cf.getRule(1).getComparisonOperation()); - assertEquals(ConditionType.CELL_VALUE_IS, sheet2cf.getRule(1).getConditionType()); - - wb.close(); - } - - @Test - public void testRemove() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet1 = wb.createSheet(); - SheetConditionalFormatting sheetCF = sheet1.getSheetConditionalFormatting(); - assertEquals(0, sheetCF.getNumConditionalFormattings()); - - ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule( - ComparisonOperator.EQUAL, "SUM(A1:A5)"); - - // adjacent address are merged - int formatIndex = sheetCF.addConditionalFormatting( - new CellRangeAddress[]{ - CellRangeAddress.valueOf("A1:A5") - }, rule1); - assertEquals(0, formatIndex); - assertEquals(1, sheetCF.getNumConditionalFormattings()); - sheetCF.removeConditionalFormatting(0); - assertEquals(0, sheetCF.getNumConditionalFormattings()); - try { - assertNull(sheetCF.getConditionalFormattingAt(0)); - fail("expected exception"); - } catch (IllegalArgumentException e) { - assertTrue(e.getMessage().startsWith("Specified CF index 0 is outside the allowable range")); - } - - formatIndex = sheetCF.addConditionalFormatting( - new CellRangeAddress[]{ - CellRangeAddress.valueOf("A1:A5") - }, rule1); - assertEquals(0, formatIndex); - assertEquals(1, sheetCF.getNumConditionalFormattings()); - sheetCF.removeConditionalFormatting(0); - assertEquals(0, sheetCF.getNumConditionalFormattings()); - try { - assertNull(sheetCF.getConditionalFormattingAt(0)); - fail("expected exception"); - } catch (IllegalArgumentException e) { - assertTrue(e.getMessage().startsWith("Specified CF index 0 is outside the allowable range")); - } - - wb.close(); - } - - @Test - public void testCreateCF() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet(); - String formula = "7"; - - SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting(); - - ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule(formula); - FontFormatting fontFmt = rule1.createFontFormatting(); - fontFmt.setFontStyle(true, false); - - BorderFormatting bordFmt = rule1.createBorderFormatting(); - bordFmt.setBorderBottom(BorderStyle.THIN); - bordFmt.setBorderTop(BorderStyle.THICK); - bordFmt.setBorderLeft(BorderStyle.DASHED); - bordFmt.setBorderRight(BorderStyle.DOTTED); - - PatternFormatting patternFmt = rule1.createPatternFormatting(); - patternFmt.setFillBackgroundColor(IndexedColors.YELLOW.index); - - - ConditionalFormattingRule rule2 = sheetCF.createConditionalFormattingRule(ComparisonOperator.BETWEEN, "1", "2"); - ConditionalFormattingRule [] cfRules = - { - rule1, rule2 - }; - - short col = 1; - CellRangeAddress [] regions = { - new CellRangeAddress(0, 65535, col, col) - }; - - sheetCF.addConditionalFormatting(regions, cfRules); - sheetCF.addConditionalFormatting(regions, cfRules); - - // Verification - assertEquals(2, sheetCF.getNumConditionalFormattings()); - sheetCF.removeConditionalFormatting(1); - assertEquals(1, sheetCF.getNumConditionalFormattings()); - ConditionalFormatting cf = sheetCF.getConditionalFormattingAt(0); - assertNotNull(cf); - - regions = cf.getFormattingRanges(); - assertNotNull(regions); - assertEquals(1, regions.length); - CellRangeAddress r = regions[0]; - assertEquals(1, r.getFirstColumn()); - assertEquals(1, r.getLastColumn()); - assertEquals(0, r.getFirstRow()); - assertEquals(65535, r.getLastRow()); - - assertEquals(2, cf.getNumberOfRules()); - - rule1 = cf.getRule(0); - assertEquals("7",rule1.getFormula1()); - assertNull(rule1.getFormula2()); - - FontFormatting r1fp = rule1.getFontFormatting(); - assertNotNull(r1fp); - - assertTrue(r1fp.isItalic()); - assertFalse(r1fp.isBold()); - - BorderFormatting r1bf = rule1.getBorderFormatting(); - assertNotNull(r1bf); - assertEquals(BorderStyle.THIN, r1bf.getBorderBottomEnum()); - assertEquals(BorderStyle.THICK,r1bf.getBorderTopEnum()); - assertEquals(BorderStyle.DASHED,r1bf.getBorderLeftEnum()); - assertEquals(BorderStyle.DOTTED,r1bf.getBorderRightEnum()); - - PatternFormatting r1pf = rule1.getPatternFormatting(); - assertNotNull(r1pf); -// assertEquals(IndexedColors.YELLOW.index,r1pf.getFillBackgroundColor()); - - rule2 = cf.getRule(1); - assertEquals("2",rule2.getFormula2()); - assertEquals("1",rule2.getFormula1()); - - workbook.close(); - } - - @Test - public void testClone() throws IOException { - - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet(); - String formula = "7"; - - SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting(); - - ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule(formula); - FontFormatting fontFmt = rule1.createFontFormatting(); - fontFmt.setFontStyle(true, false); - - PatternFormatting patternFmt = rule1.createPatternFormatting(); - patternFmt.setFillBackgroundColor(IndexedColors.YELLOW.index); - - - ConditionalFormattingRule rule2 = sheetCF.createConditionalFormattingRule(ComparisonOperator.BETWEEN, "1", "2"); - ConditionalFormattingRule [] cfRules = - { - rule1, rule2 - }; - - short col = 1; - CellRangeAddress [] regions = { - new CellRangeAddress(0, 65535, col, col) - }; - - sheetCF.addConditionalFormatting(regions, cfRules); - - try { - wb.cloneSheet(0); - assertEquals(2, wb.getNumberOfSheets()); - } catch (RuntimeException e) { - if (e.getMessage().indexOf("needs to define a clone method") > 0) { - fail("Identified bug 45682"); - } - throw e; - } finally { - wb.close(); - } - } - - @Test - public void testShiftRows() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet(); - - SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting(); - - ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule( - ComparisonOperator.BETWEEN, "SUM(A10:A15)", "1+SUM(B16:B30)"); - FontFormatting fontFmt = rule1.createFontFormatting(); - fontFmt.setFontStyle(true, false); - - PatternFormatting patternFmt = rule1.createPatternFormatting(); - patternFmt.setFillBackgroundColor(IndexedColors.YELLOW.index); - - ConditionalFormattingRule rule2 = sheetCF.createConditionalFormattingRule( - ComparisonOperator.BETWEEN, "SUM(A10:A15)", "1+SUM(B16:B30)"); - BorderFormatting borderFmt = rule2.createBorderFormatting(); - borderFmt.setBorderDiagonal(BorderStyle.MEDIUM); - - CellRangeAddress [] regions = { - new CellRangeAddress(2, 4, 0, 0), // A3:A5 - }; - sheetCF.addConditionalFormatting(regions, rule1); - sheetCF.addConditionalFormatting(regions, rule2); - - // This row-shift should destroy the CF region - sheet.shiftRows(10, 20, -9); - assertEquals(0, sheetCF.getNumConditionalFormattings()); - - // re-add the CF - sheetCF.addConditionalFormatting(regions, rule1); - sheetCF.addConditionalFormatting(regions, rule2); - - // This row shift should only affect the formulas - sheet.shiftRows(14, 17, 8); - ConditionalFormatting cf1 = sheetCF.getConditionalFormattingAt(0); - assertEquals("SUM(A10:A23)", cf1.getRule(0).getFormula1()); - assertEquals("1+SUM(B24:B30)", cf1.getRule(0).getFormula2()); - ConditionalFormatting cf2 = sheetCF.getConditionalFormattingAt(1); - assertEquals("SUM(A10:A23)", cf2.getRule(0).getFormula1()); - assertEquals("1+SUM(B24:B30)", cf2.getRule(0).getFormula2()); - - sheet.shiftRows(0, 8, 21); - cf1 = sheetCF.getConditionalFormattingAt(0); - assertEquals("SUM(A10:A21)", cf1.getRule(0).getFormula1()); - assertEquals("1+SUM(#REF!)", cf1.getRule(0).getFormula2()); - cf2 = sheetCF.getConditionalFormattingAt(1); - assertEquals("SUM(A10:A21)", cf2.getRule(0).getFormula1()); - assertEquals("1+SUM(#REF!)", cf2.getRule(0).getFormula2()); - - wb.close(); - } - - protected void testRead(String filename) throws IOException { - Workbook wb = _testDataProvider.openSampleWorkbook(filename); - Sheet sh = wb.getSheet("CF"); - SheetConditionalFormatting sheetCF = sh.getSheetConditionalFormatting(); - assertEquals(3, sheetCF.getNumConditionalFormattings()); - - ConditionalFormatting cf1 = sheetCF.getConditionalFormattingAt(0); - assertEquals(2, cf1.getNumberOfRules()); - - CellRangeAddress[] regions1 = cf1.getFormattingRanges(); - assertEquals(1, regions1.length); - assertEquals("A1:A8", regions1[0].formatAsString()); - - // CF1 has two rules: values less than -3 are bold-italic red, values greater than 3 are green - ConditionalFormattingRule rule1 = cf1.getRule(0); - assertEquals(ConditionType.CELL_VALUE_IS, rule1.getConditionType()); - assertEquals(ComparisonOperator.GT, rule1.getComparisonOperation()); - assertEquals("3", rule1.getFormula1()); - assertNull(rule1.getFormula2()); - // fills and borders are not set - assertNull(rule1.getPatternFormatting()); - assertNull(rule1.getBorderFormatting()); - - FontFormatting fmt1 = rule1.getFontFormatting(); -// assertEquals(IndexedColors.GREEN.index, fmt1.getFontColorIndex()); - assertTrue(fmt1.isBold()); - assertFalse(fmt1.isItalic()); - - ConditionalFormattingRule rule2 = cf1.getRule(1); - assertEquals(ConditionType.CELL_VALUE_IS, rule2.getConditionType()); - assertEquals(ComparisonOperator.LT, rule2.getComparisonOperation()); - assertEquals("-3", rule2.getFormula1()); - assertNull(rule2.getFormula2()); - assertNull(rule2.getPatternFormatting()); - assertNull(rule2.getBorderFormatting()); - - FontFormatting fmt2 = rule2.getFontFormatting(); -// assertEquals(IndexedColors.RED.index, fmt2.getFontColorIndex()); - assertTrue(fmt2.isBold()); - assertTrue(fmt2.isItalic()); - - - ConditionalFormatting cf2 = sheetCF.getConditionalFormattingAt(1); - assertEquals(1, cf2.getNumberOfRules()); - CellRangeAddress[] regions2 = cf2.getFormattingRanges(); - assertEquals(1, regions2.length); - assertEquals("B9", regions2[0].formatAsString()); - - ConditionalFormattingRule rule3 = cf2.getRule(0); - assertEquals(ConditionType.FORMULA, rule3.getConditionType()); - assertEquals(ComparisonOperator.NO_COMPARISON, rule3.getComparisonOperation()); - assertEquals("$A$8>5", rule3.getFormula1()); - assertNull(rule3.getFormula2()); - - FontFormatting fmt3 = rule3.getFontFormatting(); -// assertEquals(IndexedColors.RED.index, fmt3.getFontColorIndex()); - assertTrue(fmt3.isBold()); - assertTrue(fmt3.isItalic()); - - PatternFormatting fmt4 = rule3.getPatternFormatting(); -// assertEquals(IndexedColors.LIGHT_CORNFLOWER_BLUE.index, fmt4.getFillBackgroundColor()); -// assertEquals(IndexedColors.AUTOMATIC.index, fmt4.getFillForegroundColor()); - assertEquals(PatternFormatting.NO_FILL, fmt4.getFillPattern()); - // borders are not set - assertNull(rule3.getBorderFormatting()); - - ConditionalFormatting cf3 = sheetCF.getConditionalFormattingAt(2); - CellRangeAddress[] regions3 = cf3.getFormattingRanges(); - assertEquals(1, regions3.length); - assertEquals("B1:B7", regions3[0].formatAsString()); - assertEquals(2, cf3.getNumberOfRules()); - - ConditionalFormattingRule rule4 = cf3.getRule(0); - assertEquals(ConditionType.CELL_VALUE_IS, rule4.getConditionType()); - assertEquals(ComparisonOperator.LE, rule4.getComparisonOperation()); - assertEquals("\"AAA\"", rule4.getFormula1()); - assertNull(rule4.getFormula2()); - - ConditionalFormattingRule rule5 = cf3.getRule(1); - assertEquals(ConditionType.CELL_VALUE_IS, rule5.getConditionType()); - assertEquals(ComparisonOperator.BETWEEN, rule5.getComparisonOperation()); - assertEquals("\"A\"", rule5.getFormula1()); - assertEquals("\"AAA\"", rule5.getFormula2()); - - wb.close(); - } - - public void testReadOffice2007(String filename) throws IOException { - Workbook wb = _testDataProvider.openSampleWorkbook(filename); - Sheet s = wb.getSheet("CF"); - - // Sanity check data - assertEquals("Values", s.getRow(0).getCell(0).toString()); - assertEquals("10.0", s.getRow(2).getCell(0).toString()); - - // Check we found all the conditional formatting rules we should have - SheetConditionalFormatting sheetCF = s.getSheetConditionalFormatting(); - int numCF = 3; - int numCF12 = 15; - int numCFEX = 0; // TODO This should be 2, but we don't support CFEX formattings yet, see #58149 - assertEquals(numCF+numCF12+numCFEX, sheetCF.getNumConditionalFormattings()); - - int fCF = 0, fCF12 = 0, fCFEX = 0; - for (int i=0; iYellow->Green - Column F - cf = sheetCF.getConditionalFormattingAt(3); - assertEquals(1, cf.getFormattingRanges().length); - assertEquals("F2:F17", cf.getFormattingRanges()[0].formatAsString()); - assertColorScale(cf, "F8696B", "FFEB84", "63BE7B"); - - - // Colours Blue->White->Red - Column G - cf = sheetCF.getConditionalFormattingAt(4); - assertEquals(1, cf.getFormattingRanges().length); - assertEquals("G2:G17", cf.getFormattingRanges()[0].formatAsString()); - assertColorScale(cf, "5A8AC6", "FCFCFF", "F8696B"); - - - // Icons : Default - Column H, percentage thresholds - cf = sheetCF.getConditionalFormattingAt(5); - assertEquals(1, cf.getFormattingRanges().length); - assertEquals("H2:H17", cf.getFormattingRanges()[0].formatAsString()); - assertIconSetPercentages(cf, IconSet.GYR_3_TRAFFIC_LIGHTS, 0d, 33d, 67d); - - - // Icons : 3 signs - Column I - cf = sheetCF.getConditionalFormattingAt(6); - assertEquals(1, cf.getFormattingRanges().length); - assertEquals("I2:I17", cf.getFormattingRanges()[0].formatAsString()); - assertIconSetPercentages(cf, IconSet.GYR_3_SHAPES, 0d, 33d, 67d); - - - // Icons : 3 traffic lights 2 - Column J - cf = sheetCF.getConditionalFormattingAt(7); - assertEquals(1, cf.getFormattingRanges().length); - assertEquals("J2:J17", cf.getFormattingRanges()[0].formatAsString()); - assertIconSetPercentages(cf, IconSet.GYR_3_TRAFFIC_LIGHTS_BOX, 0d, 33d, 67d); - - - // Icons : 4 traffic lights - Column K - cf = sheetCF.getConditionalFormattingAt(8); - assertEquals(1, cf.getFormattingRanges().length); - assertEquals("K2:K17", cf.getFormattingRanges()[0].formatAsString()); - assertIconSetPercentages(cf, IconSet.GYRB_4_TRAFFIC_LIGHTS, 0d, 25d, 50d, 75d); - - - // Icons : 3 symbols with backgrounds - Column L - cf = sheetCF.getConditionalFormattingAt(9); - assertEquals(1, cf.getFormattingRanges().length); - assertEquals("L2:L17", cf.getFormattingRanges()[0].formatAsString()); - assertIconSetPercentages(cf, IconSet.GYR_3_SYMBOLS_CIRCLE, 0d, 33d, 67d); - - - // Icons : 3 flags - Column M2 Only - cf = sheetCF.getConditionalFormattingAt(10); - assertEquals(1, cf.getFormattingRanges().length); - assertEquals("M2", cf.getFormattingRanges()[0].formatAsString()); - assertIconSetPercentages(cf, IconSet.GYR_3_FLAGS, 0d, 33d, 67d); - - // Icons : 3 flags - Column M (all) - cf = sheetCF.getConditionalFormattingAt(11); - assertEquals(1, cf.getFormattingRanges().length); - assertEquals("M2:M17", cf.getFormattingRanges()[0].formatAsString()); - assertIconSetPercentages(cf, IconSet.GYR_3_FLAGS, 0d, 33d, 67d); - - - // Icons : 3 symbols 2 (no background) - Column N - cf = sheetCF.getConditionalFormattingAt(12); - assertEquals(1, cf.getFormattingRanges().length); - assertEquals("N2:N17", cf.getFormattingRanges()[0].formatAsString()); - assertIconSetPercentages(cf, IconSet.GYR_3_SYMBOLS, 0d, 33d, 67d); - - - // Icons : 3 arrows - Column O - cf = sheetCF.getConditionalFormattingAt(13); - assertEquals(1, cf.getFormattingRanges().length); - assertEquals("O2:O17", cf.getFormattingRanges()[0].formatAsString()); - assertIconSetPercentages(cf, IconSet.GYR_3_ARROW, 0d, 33d, 67d); - - - // Icons : 5 arrows grey - Column P - cf = sheetCF.getConditionalFormattingAt(14); - assertEquals(1, cf.getFormattingRanges().length); - assertEquals("P2:P17", cf.getFormattingRanges()[0].formatAsString()); - assertIconSetPercentages(cf, IconSet.GREY_5_ARROWS, 0d, 20d, 40d, 60d, 80d); - - - // Icons : 3 stars (ext) - Column Q - // TODO Support EXT formattings - - - // Icons : 4 ratings - Column R - cf = sheetCF.getConditionalFormattingAt(15); - assertEquals(1, cf.getFormattingRanges().length); - assertEquals("R2:R17", cf.getFormattingRanges()[0].formatAsString()); - assertIconSetPercentages(cf, IconSet.RATINGS_4, 0d, 25d, 50d, 75d); - - - // Icons : 5 ratings - Column S - cf = sheetCF.getConditionalFormattingAt(16); - assertEquals(1, cf.getFormattingRanges().length); - assertEquals("S2:S17", cf.getFormattingRanges()[0].formatAsString()); - assertIconSetPercentages(cf, IconSet.RATINGS_5, 0d, 20d, 40d, 60d, 80d); - - - // Custom Icon+Format - Column T - cf = sheetCF.getConditionalFormattingAt(17); - assertEquals(1, cf.getFormattingRanges().length); - assertEquals("T2:T17", cf.getFormattingRanges()[0].formatAsString()); - - // TODO Support IconSet + Other CFs with 2 rules -// assertEquals(2, cf.getNumberOfRules()); -// cr = cf.getRule(0); -// assertIconSetPercentages(cr, IconSet.GYR_3_TRAFFIC_LIGHTS_BOX, 0d, 33d, 67d); -// cr = cf.getRule(1); -// assertEquals(ConditionType.FORMULA, cr.getConditionType()); -// assertEquals(ComparisonOperator.NO_COMPARISON, cr.getComparisonOperation()); -// // TODO Why aren't these two the same between formats? -// if (cr instanceof HSSFConditionalFormattingRule) { -// assertEquals("MOD(ROW($T1),2)=1", cr.getFormula1()); -// } else { -// assertEquals("MOD(ROW($T2),2)=1", cr.getFormula1()); -// } -// assertEquals(null, cr.getFormula2()); - - - // Mixed icons - Column U - // TODO Support EXT formattings - - wb.close(); - } - - private void assertDataBar(ConditionalFormatting cf, String color) { - assertEquals(1, cf.getNumberOfRules()); - ConditionalFormattingRule cr = cf.getRule(0); - assertDataBar(cr, color); - } - private void assertDataBar(ConditionalFormattingRule cr, String color) { - assertEquals(ConditionType.DATA_BAR, cr.getConditionType()); - assertEquals(ComparisonOperator.NO_COMPARISON, cr.getComparisonOperation()); - assertEquals(null, cr.getFormula1()); - assertEquals(null, cr.getFormula2()); - - DataBarFormatting databar = cr.getDataBarFormatting(); - assertNotNull(databar); - assertEquals(false, databar.isIconOnly()); - assertEquals(true, databar.isLeftToRight()); - assertEquals(0, databar.getWidthMin()); - assertEquals(100, databar.getWidthMax()); - - assertColour(color, databar.getColor()); - - ConditionalFormattingThreshold th; - th = databar.getMinThreshold(); - assertEquals(RangeType.MIN, th.getRangeType()); - assertEquals(null, th.getValue()); - assertEquals(null, th.getFormula()); - th = databar.getMaxThreshold(); - assertEquals(RangeType.MAX, th.getRangeType()); - assertEquals(null, th.getValue()); - assertEquals(null, th.getFormula()); - } - - private void assertIconSetPercentages(ConditionalFormatting cf, IconSet iconset, Double...vals) { - assertEquals(1, cf.getNumberOfRules()); - ConditionalFormattingRule cr = cf.getRule(0); - assertIconSetPercentages(cr, iconset, vals); - } - private void assertIconSetPercentages(ConditionalFormattingRule cr, IconSet iconset, Double...vals) { - assertEquals(ConditionType.ICON_SET, cr.getConditionType()); - assertEquals(ComparisonOperator.NO_COMPARISON, cr.getComparisonOperation()); - assertEquals(null, cr.getFormula1()); - assertEquals(null, cr.getFormula2()); - - IconMultiStateFormatting icon = cr.getMultiStateFormatting(); - assertNotNull(icon); - assertEquals(iconset, icon.getIconSet()); - assertEquals(false, icon.isIconOnly()); - assertEquals(false, icon.isReversed()); - - assertNotNull(icon.getThresholds()); - assertEquals(vals.length, icon.getThresholds().length); - for (int i=0; i0"); - sheet.getSheetConditionalFormatting().addConditionalFormatting(ranges, rule); - wb.close(); - } - - @Test - public void testSetCellRangeAddresswithSingleRange() throws Exception { - Workbook wb = _testDataProvider.createWorkbook(); - final Sheet sheet = wb.createSheet("S1"); - final SheetConditionalFormatting cf = sheet.getSheetConditionalFormatting(); - assertEquals(0, cf.getNumConditionalFormattings()); - ConditionalFormattingRule rule1 = cf.createConditionalFormattingRule("$A$1>0"); - cf.addConditionalFormatting(new CellRangeAddress[] { - CellRangeAddress.valueOf("A1:A5") - }, rule1); - - assertEquals(1, cf.getNumConditionalFormattings()); - ConditionalFormatting readCf = cf.getConditionalFormattingAt(0); - CellRangeAddress[] formattingRanges = readCf.getFormattingRanges(); - assertEquals(1, formattingRanges.length); - CellRangeAddress formattingRange = formattingRanges[0]; - assertEquals("A1:A5", formattingRange.formatAsString()); - - readCf.setFormattingRanges(new CellRangeAddress[] { - CellRangeAddress.valueOf("A1:A6") - }); - - readCf = cf.getConditionalFormattingAt(0); - formattingRanges = readCf.getFormattingRanges(); - assertEquals(1, formattingRanges.length); - formattingRange = formattingRanges[0]; - assertEquals("A1:A6", formattingRange.formatAsString()); - } - - @Test - public void testSetCellRangeAddressWithMultipleRanges() throws Exception { - Workbook wb = _testDataProvider.createWorkbook(); - final Sheet sheet = wb.createSheet("S1"); - final SheetConditionalFormatting cf = sheet.getSheetConditionalFormatting(); - assertEquals(0, cf.getNumConditionalFormattings()); - ConditionalFormattingRule rule1 = cf.createConditionalFormattingRule("$A$1>0"); - cf.addConditionalFormatting(new CellRangeAddress[] { - CellRangeAddress.valueOf("A1:A5") - }, rule1); - - assertEquals(1, cf.getNumConditionalFormattings()); - ConditionalFormatting readCf = cf.getConditionalFormattingAt(0); - CellRangeAddress[] formattingRanges = readCf.getFormattingRanges(); - assertEquals(1, formattingRanges.length); - CellRangeAddress formattingRange = formattingRanges[0]; - assertEquals("A1:A5", formattingRange.formatAsString()); - - readCf.setFormattingRanges(new CellRangeAddress[] { - CellRangeAddress.valueOf("A1:A6"), - CellRangeAddress.valueOf("B1:B6") - }); - - readCf = cf.getConditionalFormattingAt(0); - formattingRanges = readCf.getFormattingRanges(); - assertEquals(2, formattingRanges.length); - formattingRange = formattingRanges[0]; - assertEquals("A1:A6", formattingRange.formatAsString()); - formattingRange = formattingRanges[1]; - assertEquals("B1:B6", formattingRange.formatAsString()); - } - - @Test(expected = IllegalArgumentException.class) - public void testSetCellRangeAddressWithNullRanges() throws Exception { - Workbook wb = _testDataProvider.createWorkbook(); - final Sheet sheet = wb.createSheet("S1"); - final SheetConditionalFormatting cf = sheet.getSheetConditionalFormatting(); - assertEquals(0, cf.getNumConditionalFormattings()); - ConditionalFormattingRule rule1 = cf.createConditionalFormattingRule("$A$1>0"); - cf.addConditionalFormatting(new CellRangeAddress[] { - CellRangeAddress.valueOf("A1:A5") - }, rule1); - - assertEquals(1, cf.getNumConditionalFormattings()); - ConditionalFormatting readCf = cf.getConditionalFormattingAt(0); - readCf.setFormattingRanges(null); - } - - - @SuppressWarnings("deprecation") - @Test - public void test52122() throws Exception { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet("Conditional Formatting Test"); - sheet.setColumnWidth(0, 256 * 10); - sheet.setColumnWidth(1, 256 * 10); - sheet.setColumnWidth(2, 256 * 10); - - // Create some content. - // row 0 - Row row = sheet.createRow(0); - - Cell cell0 = row.createCell(0); - cell0.setCellType(CellType.NUMERIC); - cell0.setCellValue(100); - - Cell cell1 = row.createCell(1); - cell1.setCellType(CellType.NUMERIC); - cell1.setCellValue(120); - - Cell cell2 = row.createCell(2); - cell2.setCellType(CellType.NUMERIC); - cell2.setCellValue(130); - - // row 1 - row = sheet.createRow(1); - - cell0 = row.createCell(0); - cell0.setCellType(CellType.NUMERIC); - cell0.setCellValue(200); - - cell1 = row.createCell(1); - cell1.setCellType(CellType.NUMERIC); - cell1.setCellValue(220); - - cell2 = row.createCell(2); - cell2.setCellType(CellType.NUMERIC); - cell2.setCellValue(230); - - // row 2 - row = sheet.createRow(2); - - cell0 = row.createCell(0); - cell0.setCellType(CellType.NUMERIC); - cell0.setCellValue(300); - - cell1 = row.createCell(1); - cell1.setCellType(CellType.NUMERIC); - cell1.setCellValue(320); - - cell2 = row.createCell(2); - cell2.setCellType(CellType.NUMERIC); - cell2.setCellValue(330); - - // Create conditional formatting, CELL1 should be yellow if CELL0 is not blank. - SheetConditionalFormatting formatting = sheet.getSheetConditionalFormatting(); - - ConditionalFormattingRule rule = formatting.createConditionalFormattingRule("$A$1>75"); - - PatternFormatting pattern = rule.createPatternFormatting(); - pattern.setFillBackgroundColor(IndexedColors.BLUE.index); - pattern.setFillPattern(PatternFormatting.SOLID_FOREGROUND); - - CellRangeAddress[] range = {CellRangeAddress.valueOf("B2:C2")}; - CellRangeAddress[] range2 = {CellRangeAddress.valueOf("B1:C1")}; - - formatting.addConditionalFormatting(range, rule); - formatting.addConditionalFormatting(range2, rule); - - // Write file. - /*FileOutputStream fos = new FileOutputStream("c:\\temp\\52122_conditional-sheet.xls"); - try { - workbook.write(fos); - } finally { - fos.close(); - }*/ - - Workbook wbBack = _testDataProvider.writeOutAndReadBack(workbook); - Sheet sheetBack = wbBack.getSheetAt(0); - final SheetConditionalFormatting sheetConditionalFormattingBack = sheetBack.getSheetConditionalFormatting(); - assertNotNull(sheetConditionalFormattingBack); - final ConditionalFormatting formattingBack = sheetConditionalFormattingBack.getConditionalFormattingAt(0); - assertNotNull(formattingBack); - final ConditionalFormattingRule ruleBack = formattingBack.getRule(0); - assertNotNull(ruleBack); - final PatternFormatting patternFormattingBack1 = ruleBack.getPatternFormatting(); - assertNotNull(patternFormattingBack1); - assertEquals(IndexedColors.BLUE.index, patternFormattingBack1.getFillBackgroundColor()); - assertEquals(PatternFormatting.SOLID_FOREGROUND, patternFormattingBack1.getFillPattern()); - } -} \ No newline at end of file diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestDataFormat.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestDataFormat.java deleted file mode 100644 index 70ba300b7..000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestDataFormat.java +++ /dev/null @@ -1,245 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; - -import org.apache.poi.ss.ITestDataProvider; -import org.junit.Test; - -/** - * Tests of implementation of {@link DataFormat} - * - */ -public abstract class BaseTestDataFormat { - - private final ITestDataProvider _testDataProvider; - - protected BaseTestDataFormat(ITestDataProvider testDataProvider) { - _testDataProvider = testDataProvider; - } - - public void assertNotBuiltInFormat(String customFmt) { - //check it is not in built-in formats - assertEquals(-1, BuiltinFormats.getBuiltinFormat(customFmt)); - } - - @Test - public final void testBuiltinFormats() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - - DataFormat df = wb.createDataFormat(); - - String[] formats = BuiltinFormats.getAll(); - for (int idx = 0; idx < formats.length; idx++) { - String fmt = formats[idx]; - assertEquals(idx, df.getFormat(fmt)); - } - - //default format for new cells is General - Sheet sheet = wb.createSheet(); - Cell cell = sheet.createRow(0).createCell(0); - assertEquals(0, cell.getCellStyle().getDataFormat()); - assertEquals("General", cell.getCellStyle().getDataFormatString()); - - //create a custom data format - String customFmt = "#0.00 AM/PM"; - //check it is not in built-in formats - assertNotBuiltInFormat(customFmt); - int customIdx = df.getFormat(customFmt); - //The first user-defined format starts at 164. - assertTrue(customIdx >= BuiltinFormats.FIRST_USER_DEFINED_FORMAT_INDEX); - //read and verify the string representation - assertEquals(customFmt, df.getFormat((short)customIdx)); - - wb.close(); - } - - /** - * [Bug 49928] formatCellValue returns incorrect value for \u00a3 formatted cells - */ - @Test - public abstract void test49928() throws IOException; - protected final static String poundFmt = "\"\u00a3\"#,##0;[Red]\\-\"\u00a3\"#,##0"; - public void doTest49928Core(Workbook wb){ - DataFormatter df = new DataFormatter(); - - Sheet sheet = wb.getSheetAt(0); - Cell cell = sheet.getRow(0).getCell(0); - CellStyle style = cell.getCellStyle(); - - // not expected normally, id of a custom format should be greater - // than BuiltinFormats.FIRST_USER_DEFINED_FORMAT_INDEX - short poundFmtIdx = 6; - - assertEquals(poundFmt, style.getDataFormatString()); - assertEquals(poundFmtIdx, style.getDataFormat()); - assertEquals("\u00a31", df.formatCellValue(cell)); - - - DataFormat dataFormat = wb.createDataFormat(); - assertEquals(poundFmtIdx, dataFormat.getFormat(poundFmt)); - assertEquals(poundFmt, dataFormat.getFormat(poundFmtIdx)); - } - - @Test - public void testReadbackFormat() throws IOException { - readbackFormat("built-in format", "0.00"); - readbackFormat("overridden built-in format", poundFmt); - - String customFormat = "#0.00 AM/PM"; - assertNotBuiltInFormat(customFormat); - readbackFormat("custom format", customFormat); - } - - private void readbackFormat(String msg, String fmt) throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - try { - DataFormat dataFormat = wb.createDataFormat(); - short fmtIdx = dataFormat.getFormat(fmt); - String readbackFmt = dataFormat.getFormat(fmtIdx); - assertEquals(msg, fmt, readbackFmt); - } finally { - wb.close(); - } - } - - @Test - public abstract void test58532() throws IOException; - public void doTest58532Core(Workbook wb) { - Sheet s = wb.getSheetAt(0); - DataFormatter fmt = new DataFormatter(); - FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator(); - - // Column A is the raw values - // Column B is the ##/#K/#M values - // Column C is strings of what they should look like - // Column D is the #.##/#.#K/#.#M values - // Column E is strings of what they should look like - - String formatKMWhole = "[>999999]#,,\"M\";[>999]#,\"K\";#"; - String formatKM3dp = "[>999999]#.000,,\"M\";[>999]#.000,\"K\";#.000"; - - // Check the formats are as expected - Row headers = s.getRow(0); - assertNotNull(headers); - assertEquals(formatKMWhole, headers.getCell(1).getStringCellValue()); - assertEquals(formatKM3dp, headers.getCell(3).getStringCellValue()); - - Row r2 = s.getRow(1); - assertNotNull(r2); - assertEquals(formatKMWhole, r2.getCell(1).getCellStyle().getDataFormatString()); - assertEquals(formatKM3dp, r2.getCell(3).getCellStyle().getDataFormatString()); - - // For all of the contents rows, check that DataFormatter is able - // to format the cells to the same value as the one next to it - for (int rn=1; rn 1'000 - */ - @Test - public final void test55265() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - DataFormatter formatter = new DataFormatter(); - DataFormat fmt = wb.createDataFormat(); - Sheet sheet = wb.createSheet(); - Row r = sheet.createRow(0); - - CellStyle cs = wb.createCellStyle(); - cs.setDataFormat(fmt.getFormat("#'##0")); - - Cell zero = r.createCell(0); - zero.setCellValue(0); - zero.setCellStyle(cs); - - Cell sml = r.createCell(1); - sml.setCellValue(12); - sml.setCellStyle(cs); - - Cell med = r.createCell(2); - med.setCellValue(1234); - med.setCellStyle(cs); - - Cell lge = r.createCell(3); - lge.setCellValue(12345678); - lge.setCellStyle(cs); - - assertEquals("0", formatter.formatCellValue(zero)); - assertEquals("12", formatter.formatCellValue(sml)); - assertEquals("1'234", formatter.formatCellValue(med)); - assertEquals("12'345'678", formatter.formatCellValue(lge)); - wb.close(); - } -} diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestDataValidation.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestDataValidation.java deleted file mode 100644 index 5b8bdc84c..000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestDataValidation.java +++ /dev/null @@ -1,506 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.ss.usermodel.DataValidation.ErrorStyle; -import org.apache.poi.ss.usermodel.DataValidationConstraint.OperatorType; -import org.apache.poi.ss.usermodel.DataValidationConstraint.ValidationType; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.CellRangeAddressList; -import org.apache.poi.util.POILogFactory; -import org.apache.poi.util.POILogger; -import org.junit.Test; - -/** - * Class for testing Excel's data validation mechanism - * - * @author Dragos Buleandra ( dragos.buleandra@trade2b.ro ) - */ -public abstract class BaseTestDataValidation { - private final ITestDataProvider _testDataProvider; - - private static final POILogger log = POILogFactory.getLogger(BaseTestDataValidation.class); - - protected BaseTestDataValidation(ITestDataProvider testDataProvider) { - _testDataProvider = testDataProvider; - } - - /** Convenient access to ERROR_STYLE constants */ - protected static final DataValidation.ErrorStyle ES = null; - /** Convenient access to OPERATOR constants */ - protected static final DataValidationConstraint.ValidationType VT = null; - /** Convenient access to OPERATOR constants */ - protected static final DataValidationConstraint.OperatorType OP = null; - - private static final class ValidationAdder { - - private final CellStyle _style_1; - private final CellStyle _style_2; - private final int _validationType; - private final Sheet _sheet; - private int _currentRowIndex; - private final CellStyle _cellStyle; - - public ValidationAdder(Sheet fSheet, CellStyle style_1, CellStyle style_2, - CellStyle cellStyle, int validationType) { - _sheet = fSheet; - _style_1 = style_1; - _style_2 = style_2; - _cellStyle = cellStyle; - _validationType = validationType; - _currentRowIndex = fSheet.getPhysicalNumberOfRows(); - } - public void addValidation(int operatorType, String firstFormula, String secondFormula, - int errorStyle, String ruleDescr, String promptDescr, - boolean allowEmpty, boolean inputBox, boolean errorBox) { - String[] explicitListValues = null; - - addValidationInternal(operatorType, firstFormula, secondFormula, errorStyle, ruleDescr, - promptDescr, allowEmpty, inputBox, errorBox, true, - explicitListValues); - } - - private void addValidationInternal(int operatorType, String firstFormula, - String secondFormula, int errorStyle, String ruleDescr, String promptDescr, - boolean allowEmpty, boolean inputBox, boolean errorBox, boolean suppressDropDown, - String[] explicitListValues) { - int rowNum = _currentRowIndex++; - - DataValidationHelper dataValidationHelper = _sheet.getDataValidationHelper(); - DataValidationConstraint dc = createConstraint(dataValidationHelper,operatorType, firstFormula, secondFormula, explicitListValues); - - DataValidation dv = dataValidationHelper.createValidation(dc,new CellRangeAddressList(rowNum, rowNum, 0, 0)); - - dv.setEmptyCellAllowed(allowEmpty); - dv.setErrorStyle(errorStyle); - dv.createErrorBox("Invalid Input", "Something is wrong - check condition!"); - dv.createPromptBox("Validated Cell", "Allowable values have been restricted"); - - dv.setShowPromptBox(inputBox); - dv.setShowErrorBox(errorBox); - dv.setSuppressDropDownArrow(suppressDropDown); - - - _sheet.addValidationData(dv); - writeDataValidationSettings(_sheet, _style_1, _style_2, ruleDescr, allowEmpty, - inputBox, errorBox); - if (_cellStyle != null) { - Row row = _sheet.getRow(_sheet.getPhysicalNumberOfRows() - 1); - Cell cell = row.createCell(0); - cell.setCellStyle(_cellStyle); - } - writeOtherSettings(_sheet, _style_1, promptDescr); - } - private DataValidationConstraint createConstraint(DataValidationHelper dataValidationHelper,int operatorType, String firstFormula, - String secondFormula, String[] explicitListValues) { - if (_validationType == ValidationType.LIST) { - if (explicitListValues != null) { - return dataValidationHelper.createExplicitListConstraint(explicitListValues); - } - return dataValidationHelper.createFormulaListConstraint(firstFormula); - } - if (_validationType == ValidationType.TIME) { - return dataValidationHelper.createTimeConstraint(operatorType, firstFormula, secondFormula); - } - if (_validationType == ValidationType.DATE) { - return dataValidationHelper.createDateConstraint(operatorType, firstFormula, secondFormula, null); - } - if (_validationType == ValidationType.FORMULA) { - return dataValidationHelper.createCustomConstraint(firstFormula); - } - - if( _validationType == ValidationType.INTEGER) { - return dataValidationHelper.createIntegerConstraint(operatorType, firstFormula, secondFormula); - } - if( _validationType == ValidationType.DECIMAL) { - return dataValidationHelper.createDecimalConstraint(operatorType, firstFormula, secondFormula); - } - if( _validationType == ValidationType.TEXT_LENGTH) { - return dataValidationHelper.createTextLengthConstraint(operatorType, firstFormula, secondFormula); - } - return null; - } - /** - * writes plain text values into cells in a tabular format to form comments readable from within - * the spreadsheet. - */ - private static void writeDataValidationSettings(Sheet sheet, CellStyle style_1, - CellStyle style_2, String strCondition, boolean allowEmpty, boolean inputBox, - boolean errorBox) { - Row row = sheet.createRow(sheet.getPhysicalNumberOfRows()); - // condition's string - Cell cell = row.createCell(1); - cell.setCellStyle(style_1); - setCellValue(cell, strCondition); - // allow empty cells - cell = row.createCell(2); - cell.setCellStyle(style_2); - setCellValue(cell, ((allowEmpty) ? "yes" : "no")); - // show input box - cell = row.createCell(3); - cell.setCellStyle(style_2); - setCellValue(cell, ((inputBox) ? "yes" : "no")); - // show error box - cell = row.createCell(4); - cell.setCellStyle(style_2); - setCellValue(cell, ((errorBox) ? "yes" : "no")); - } - private static void writeOtherSettings(Sheet sheet, CellStyle style, - String strStettings) { - Row row = sheet.getRow(sheet.getPhysicalNumberOfRows() - 1); - Cell cell = row.createCell(5); - cell.setCellStyle(style); - setCellValue(cell, strStettings); - } - public void addListValidation(String[] explicitListValues, String listFormula, String listValsDescr, - boolean allowEmpty, boolean suppressDropDown) { - String promptDescr = (allowEmpty ? "empty ok" : "not empty") - + ", " + (suppressDropDown ? "no drop-down" : "drop-down"); - addValidationInternal(ValidationType.LIST, listFormula, null, ErrorStyle.STOP, listValsDescr, promptDescr, - allowEmpty, false, true, suppressDropDown, explicitListValues); - } - } - - private static void log(String msg) { - log.log(POILogger.INFO, msg); - } - - /** - * Manages the cell styles used for formatting the output spreadsheet - */ - private static final class WorkbookFormatter { - - private final Workbook _wb; - private final CellStyle _style_1; - private final CellStyle _style_2; - private final CellStyle _style_3; - private final CellStyle _style_4; - private Sheet _currentSheet; - - public WorkbookFormatter(Workbook wb) { - _wb = wb; - _style_1 = createStyle( wb, HorizontalAlignment.LEFT ); - _style_2 = createStyle( wb, HorizontalAlignment.CENTER ); - _style_3 = createStyle( wb, HorizontalAlignment.CENTER, IndexedColors.GREY_25_PERCENT.getIndex(), true ); - _style_4 = createHeaderStyle(wb); - } - - private static CellStyle createStyle(Workbook wb, HorizontalAlignment h_align, short color, - boolean bold) { - Font font = wb.createFont(); - if (bold) { - font.setBold(true); - } - - CellStyle cellStyle = wb.createCellStyle(); - cellStyle.setFont(font); - cellStyle.setFillForegroundColor(color); - cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); - cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); - cellStyle.setAlignment(h_align); - cellStyle.setBorderLeft(BorderStyle.THIN); - cellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex()); - cellStyle.setBorderTop(BorderStyle.THIN); - cellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex()); - cellStyle.setBorderRight(BorderStyle.THIN); - cellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex()); - cellStyle.setBorderBottom(BorderStyle.THIN); - cellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex()); - - return cellStyle; - } - - private static CellStyle createStyle(Workbook wb, HorizontalAlignment h_align) { - return createStyle(wb, h_align, IndexedColors.WHITE.getIndex(), false); - } - private static CellStyle createHeaderStyle(Workbook wb) { - Font font = wb.createFont(); - font.setColor( IndexedColors.WHITE.getIndex() ); - font.setBold(true); - - CellStyle cellStyle = wb.createCellStyle(); - cellStyle.setFillForegroundColor(IndexedColors.BLUE_GREY.getIndex()); - cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); - cellStyle.setAlignment(HorizontalAlignment.CENTER); - cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); - cellStyle.setBorderLeft(BorderStyle.THIN); - cellStyle.setLeftBorderColor(IndexedColors.WHITE.getIndex()); - cellStyle.setBorderTop(BorderStyle.THIN); - cellStyle.setTopBorderColor(IndexedColors.WHITE.getIndex()); - cellStyle.setBorderRight(BorderStyle.THIN); - cellStyle.setRightBorderColor(IndexedColors.WHITE.getIndex()); - cellStyle.setBorderBottom(BorderStyle.THIN); - cellStyle.setBottomBorderColor(IndexedColors.WHITE.getIndex()); - cellStyle.setFont(font); - return cellStyle; - } - - - public Sheet createSheet(String sheetName) { - _currentSheet = _wb.createSheet(sheetName); - return _currentSheet; - } - public void createDVTypeRow(String strTypeDescription) { - Sheet sheet = _currentSheet; - Row row = sheet.createRow(sheet.getPhysicalNumberOfRows()); - sheet.addMergedRegion(new CellRangeAddress(sheet.getPhysicalNumberOfRows()-1, sheet.getPhysicalNumberOfRows()-1, 0, 5)); - Cell cell = row.createCell(0); - setCellValue(cell, strTypeDescription); - cell.setCellStyle(_style_3); - row = sheet.createRow(sheet.getPhysicalNumberOfRows()); - } - - public void createHeaderRow() { - Sheet sheet = _currentSheet; - Row row = sheet.createRow(sheet.getPhysicalNumberOfRows()); - row.setHeight((short) 400); - for (int i = 0; i < 6; i++) { - row.createCell(i).setCellStyle(_style_4); - if (i == 2 || i == 3 || i == 4) { - sheet.setColumnWidth(i, 3500); - } else if (i == 5) { - sheet.setColumnWidth(i, 10000); - } else { - sheet.setColumnWidth(i, 8000); - } - } - Cell cell = row.getCell(0); - setCellValue(cell, "Data validation cells"); - cell = row.getCell(1); - setCellValue(cell, "Condition"); - cell = row.getCell(2); - setCellValue(cell, "Allow blank"); - cell = row.getCell(3); - setCellValue(cell, "Prompt box"); - cell = row.getCell(4); - setCellValue(cell, "Error box"); - cell = row.getCell(5); - setCellValue(cell, "Other settings"); - } - - public ValidationAdder createValidationAdder(CellStyle cellStyle, int dataValidationType) { - return new ValidationAdder(_currentSheet, _style_1, _style_2, cellStyle, dataValidationType); - } - - public void createDVDescriptionRow(String strTypeDescription) { - Sheet sheet = _currentSheet; - Row row = sheet.getRow(sheet.getPhysicalNumberOfRows()-1); - sheet.addMergedRegion(new CellRangeAddress(sheet.getPhysicalNumberOfRows()-1, sheet.getPhysicalNumberOfRows()-1, 0, 5)); - Cell cell = row.createCell(0); - setCellValue(cell, strTypeDescription); - cell.setCellStyle(_style_3); - row = sheet.createRow(sheet.getPhysicalNumberOfRows()); - } - } - - - private void addCustomValidations(WorkbookFormatter wf) { - wf.createSheet("Custom"); - wf.createHeaderRow(); - - ValidationAdder va = wf.createValidationAdder(null, ValidationType.FORMULA); - va.addValidation(OperatorType.BETWEEN, "ISNUMBER($A2)", null, ErrorStyle.STOP, "ISNUMBER(A2)", "Error box type = STOP", true, true, true); - va.addValidation(OperatorType.BETWEEN, "IF(SUM(A2:A3)=5,TRUE,FALSE)", null, ErrorStyle.WARNING, "IF(SUM(A2:A3)=5,TRUE,FALSE)", "Error box type = WARNING", false, false, true); - } - - private static void addSimpleNumericValidations(WorkbookFormatter wf) { - // data validation's number types - wf.createSheet("Numbers"); - - // "Whole number" validation type - wf.createDVTypeRow("Whole number"); - wf.createHeaderRow(); - - ValidationAdder va = wf.createValidationAdder(null, ValidationType.INTEGER); - va.addValidation(OperatorType.BETWEEN, "2", "6", ErrorStyle.STOP, "Between 2 and 6 ", "Error box type = STOP", true, true, true); - va.addValidation(OperatorType.NOT_BETWEEN, "2", "6", ErrorStyle.INFO, "Not between 2 and 6 ", "Error box type = INFO", false, true, true); - va.addValidation(OperatorType.EQUAL, "=3+2", null, ErrorStyle.WARNING, "Equal to (3+2)", "Error box type = WARNING", false, false, true); - va.addValidation(OperatorType.NOT_EQUAL, "3", null, ErrorStyle.WARNING, "Not equal to 3", "-", false, false, false); - va.addValidation(OperatorType.GREATER_THAN, "3", null, ErrorStyle.WARNING, "Greater than 3", "-", true, false, false); - va.addValidation(OperatorType.LESS_THAN, "3", null, ErrorStyle.WARNING, "Less than 3", "-", true, true, false); - va.addValidation(OperatorType.GREATER_OR_EQUAL, "4", null, ErrorStyle.STOP, "Greater than or equal to 4", "Error box type = STOP", true, false, true); - va.addValidation(OperatorType.LESS_OR_EQUAL, "4", null, ErrorStyle.STOP, "Less than or equal to 4", "-", false, true, false); - - // "Decimal" validation type - wf.createDVTypeRow("Decimal"); - wf.createHeaderRow(); - - va = wf.createValidationAdder(null, ValidationType.DECIMAL); - va.addValidation(OperatorType.BETWEEN, "2", "6", ErrorStyle.STOP, "Between 2 and 6 ", "Error box type = STOP", true, true, true); - va.addValidation(OperatorType.NOT_BETWEEN, "2", "6", ErrorStyle.INFO, "Not between 2 and 6 ", "Error box type = INFO", false, true, true); - va.addValidation(OperatorType.EQUAL, "3", null, ErrorStyle.WARNING, "Equal to 3", "Error box type = WARNING", false, false, true); - va.addValidation(OperatorType.NOT_EQUAL, "3", null, ErrorStyle.WARNING, "Not equal to 3", "-", false, false, false); - va.addValidation(OperatorType.GREATER_THAN, "=12/6", null, ErrorStyle.WARNING, "Greater than (12/6)", "-", true, false, false); - va.addValidation(OperatorType.LESS_THAN, "3", null, ErrorStyle.WARNING, "Less than 3", "-", true, true, false); - va.addValidation(OperatorType.GREATER_OR_EQUAL, "4", null, ErrorStyle.STOP, "Greater than or equal to 4", "Error box type = STOP", true, false, true); - va.addValidation(OperatorType.LESS_OR_EQUAL, "4", null, ErrorStyle.STOP, "Less than or equal to 4", "-", false, true, false); - } - - private static void addListValidations(WorkbookFormatter wf, Workbook wb) { - final String cellStrValue - = "a b c d e f g h i j k l m n o p r s t u v x y z w 0 1 2 3 4 " - + "a b c d e f g h i j k l m n o p r s t u v x y z w 0 1 2 3 4 " - + "a b c d e f g h i j k l m n o p r s t u v x y z w 0 1 2 3 4 " - + "a b c d e f g h i j k l m n o p r s t u v x y z w 0 1 2 3 4 "; - final String dataSheetName = "list_data"; - // "List" Data Validation type - Sheet fSheet = wf.createSheet("Lists"); - Sheet dataSheet = wb.createSheet(dataSheetName); - - - wf.createDVTypeRow("Explicit lists - list items are explicitly provided"); - wf.createDVDescriptionRow("Disadvantage - sum of item's length should be less than 255 characters"); - wf.createHeaderRow(); - - ValidationAdder va = wf.createValidationAdder(null, ValidationType.LIST); - String listValsDescr = "POIFS,HSSF,HWPF,HPSF"; - String[] listVals = listValsDescr.split(","); - va.addListValidation(listVals, null, listValsDescr, false, false); - va.addListValidation(listVals, null, listValsDescr, false, true); - va.addListValidation(listVals, null, listValsDescr, true, false); - va.addListValidation(listVals, null, listValsDescr, true, true); - - - - wf.createDVTypeRow("Reference lists - list items are taken from others cells"); - wf.createDVDescriptionRow("Advantage - no restriction regarding the sum of item's length"); - wf.createHeaderRow(); - va = wf.createValidationAdder(null, ValidationType.LIST); - String strFormula = "$A$30:$A$39"; - va.addListValidation(null, strFormula, strFormula, false, false); - - strFormula = dataSheetName + "!$A$1:$A$10"; - va.addListValidation(null, strFormula, strFormula, false, false); - Name namedRange = wb.createName(); - namedRange.setNameName("myName"); - namedRange.setRefersToFormula(dataSheetName + "!$A$2:$A$7"); - strFormula = "myName"; - va.addListValidation(null, strFormula, strFormula, false, false); - strFormula = "offset(myName, 2, 1, 4, 2)"; // Note about last param '2': - // - Excel expects single row or single column when entered in UI, but process this OK otherwise - va.addListValidation(null, strFormula, strFormula, false, false); - - // add list data on same sheet - for (int i = 0; i < 10; i++) { - Row currRow = fSheet.createRow(i + 29); - setCellValue(currRow.createCell(0), cellStrValue); - } - // add list data on another sheet - for (int i = 0; i < 10; i++) { - Row currRow = dataSheet.createRow(i + 0); - setCellValue(currRow.createCell(0), "Data a" + i); - setCellValue(currRow.createCell(1), "Data b" + i); - setCellValue(currRow.createCell(2), "Data c" + i); - } - } - - private static void addDateTimeValidations(WorkbookFormatter wf, Workbook wb) { - wf.createSheet("Dates and Times"); - - DataFormat dataFormat = wb.createDataFormat(); - short fmtDate = dataFormat.getFormat("m/d/yyyy"); - short fmtTime = dataFormat.getFormat("h:mm"); - CellStyle cellStyle_date = wb.createCellStyle(); - cellStyle_date.setDataFormat(fmtDate); - CellStyle cellStyle_time = wb.createCellStyle(); - cellStyle_time.setDataFormat(fmtTime); - - wf.createDVTypeRow("Date ( cells are already formated as date - m/d/yyyy)"); - wf.createHeaderRow(); - - ValidationAdder va = wf.createValidationAdder(cellStyle_date, ValidationType.DATE); - va.addValidation(OperatorType.BETWEEN, "2004/01/02", "2004/01/06", ErrorStyle.STOP, "Between 1/2/2004 and 1/6/2004 ", "Error box type = STOP", true, true, true); - va.addValidation(OperatorType.NOT_BETWEEN, "2004/01/01", "2004/01/06", ErrorStyle.INFO, "Not between 1/2/2004 and 1/6/2004 ", "Error box type = INFO", false, true, true); - va.addValidation(OperatorType.EQUAL, "2004/03/02", null, ErrorStyle.WARNING, "Equal to 3/2/2004", "Error box type = WARNING", false, false, true); - va.addValidation(OperatorType.NOT_EQUAL, "2004/03/02", null, ErrorStyle.WARNING, "Not equal to 3/2/2004", "-", false, false, false); - va.addValidation(OperatorType.GREATER_THAN,"=DATEVALUE(\"4-Jul-2001\")", null, ErrorStyle.WARNING, "Greater than DATEVALUE('4-Jul-2001')", "-", true, false, false); - va.addValidation(OperatorType.LESS_THAN, "2004/03/02", null, ErrorStyle.WARNING, "Less than 3/2/2004", "-", true, true, false); - va.addValidation(OperatorType.GREATER_OR_EQUAL, "2004/03/02", null, ErrorStyle.STOP, "Greater than or equal to 3/2/2004", "Error box type = STOP", true, false, true); - va.addValidation(OperatorType.LESS_OR_EQUAL, "2004/03/04", null, ErrorStyle.STOP, "Less than or equal to 3/4/2004", "-", false, true, false); - - // "Time" validation type - wf.createDVTypeRow("Time ( cells are already formated as time - h:mm)"); - wf.createHeaderRow(); - - va = wf.createValidationAdder(cellStyle_time, ValidationType.TIME); - va.addValidation(OperatorType.BETWEEN, "12:00", "16:00", ErrorStyle.STOP, "Between 12:00 and 16:00 ", "Error box type = STOP", true, true, true); - va.addValidation(OperatorType.NOT_BETWEEN, "12:00", "16:00", ErrorStyle.INFO, "Not between 12:00 and 16:00 ", "Error box type = INFO", false, true, true); - va.addValidation(OperatorType.EQUAL, "13:35", null, ErrorStyle.WARNING, "Equal to 13:35", "Error box type = WARNING", false, false, true); - va.addValidation(OperatorType.NOT_EQUAL, "13:35", null, ErrorStyle.WARNING, "Not equal to 13:35", "-", false, false, false); - va.addValidation(OperatorType.GREATER_THAN,"12:00", null, ErrorStyle.WARNING, "Greater than 12:00", "-", true, false, false); - va.addValidation(OperatorType.LESS_THAN, "=1/2", null, ErrorStyle.WARNING, "Less than (1/2) -> 12:00", "-", true, true, false); - va.addValidation(OperatorType.GREATER_OR_EQUAL, "14:00", null, ErrorStyle.STOP, "Greater than or equal to 14:00", "Error box type = STOP", true, false, true); - va.addValidation(OperatorType.LESS_OR_EQUAL,"14:00", null, ErrorStyle.STOP, "Less than or equal to 14:00", "-", false, true, false); - } - - private static void addTextLengthValidations(WorkbookFormatter wf) { - wf.createSheet("Text lengths"); - wf.createHeaderRow(); - - ValidationAdder va = wf.createValidationAdder(null, ValidationType.TEXT_LENGTH); - va.addValidation(OperatorType.BETWEEN, "2", "6", ErrorStyle.STOP, "Between 2 and 6 ", "Error box type = STOP", true, true, true); - va.addValidation(OperatorType.NOT_BETWEEN, "2", "6", ErrorStyle.INFO, "Not between 2 and 6 ", "Error box type = INFO", false, true, true); - va.addValidation(OperatorType.EQUAL, "3", null, ErrorStyle.WARNING, "Equal to 3", "Error box type = WARNING", false, false, true); - va.addValidation(OperatorType.NOT_EQUAL, "3", null, ErrorStyle.WARNING, "Not equal to 3", "-", false, false, false); - va.addValidation(OperatorType.GREATER_THAN, "3", null, ErrorStyle.WARNING, "Greater than 3", "-", true, false, false); - va.addValidation(OperatorType.LESS_THAN, "3", null, ErrorStyle.WARNING, "Less than 3", "-", true, true, false); - va.addValidation(OperatorType.GREATER_OR_EQUAL, "4", null, ErrorStyle.STOP, "Greater than or equal to 4", "Error box type = STOP", true, false, true); - va.addValidation(OperatorType.LESS_OR_EQUAL, "4", null, ErrorStyle.STOP, "Less than or equal to 4", "-", false, true, false); - } - - @Test - public void testDataValidation() throws Exception { - log("\nTest no. 2 - Test Excel's Data validation mechanism"); - Workbook wb = _testDataProvider.createWorkbook(); - WorkbookFormatter wf = new WorkbookFormatter(wb); - - log(" Create sheet for Data Validation's number types ... "); - addSimpleNumericValidations(wf); - log("done !"); - - log(" Create sheet for 'List' Data Validation type ... "); - addListValidations(wf, wb); - log("done !"); - - log(" Create sheet for 'Date' and 'Time' Data Validation types ... "); - addDateTimeValidations(wf, wb); - log("done !"); - - log(" Create sheet for 'Text length' Data Validation type... "); - addTextLengthValidations(wf); - log("done !"); - - // Custom Validation type - log(" Create sheet for 'Custom' Data Validation type ... "); - addCustomValidations(wf); - log("done !"); - - _testDataProvider.writeOutAndReadBack(wb).close(); - - wb.close(); - } - - - - /* package */ static void setCellValue(Cell cell, String text) { - cell.setCellValue(text); - - } - -} \ No newline at end of file diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestFont.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestFont.java deleted file mode 100644 index cc4a90376..000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestFont.java +++ /dev/null @@ -1,216 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import static org.junit.Assert.*; - -import java.io.IOException; - -import org.apache.poi.ss.ITestDataProvider; -import org.junit.Test; - -/** - * @author Yegor Kozlov - */ -public abstract class BaseTestFont { - - private final ITestDataProvider _testDataProvider; - - protected BaseTestFont(ITestDataProvider testDataProvider) { - _testDataProvider = testDataProvider; - } - - protected final void baseTestDefaultFont(String defaultName, short defaultSize, short defaultColor) throws IOException { - //get default font and check against default value - Workbook workbook = _testDataProvider.createWorkbook(); - Font fontFind=workbook.findFont(Font.BOLDWEIGHT_NORMAL, defaultColor, defaultSize, defaultName, false, false, Font.SS_NONE, Font.U_NONE); - assertNotNull(fontFind); - - //get default font, then change 2 values and check against different values (height changes) - Font font=workbook.createFont(); - font.setBoldweight(Font.BOLDWEIGHT_BOLD); - assertEquals(Font.BOLDWEIGHT_BOLD, font.getBoldweight()); - font.setUnderline(Font.U_DOUBLE); - assertEquals(Font.U_DOUBLE, font.getUnderline()); - font.setFontHeightInPoints((short)15); - assertEquals(15*20, font.getFontHeight()); - assertEquals(15, font.getFontHeightInPoints()); - fontFind=workbook.findFont(Font.BOLDWEIGHT_BOLD, defaultColor, (short)(15*20), defaultName, false, false, Font.SS_NONE, Font.U_DOUBLE); - assertNotNull(fontFind); - workbook.close(); - } - - @Test - public final void testGetNumberOfFonts() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - int num0 = wb.getNumberOfFonts(); - - Font f1=wb.createFont(); - f1.setBoldweight(Font.BOLDWEIGHT_BOLD); - short idx1 = f1.getIndex(); - wb.createCellStyle().setFont(f1); - - Font f2=wb.createFont(); - f2.setUnderline(Font.U_DOUBLE); - short idx2 = f2.getIndex(); - wb.createCellStyle().setFont(f2); - - Font f3=wb.createFont(); - f3.setFontHeightInPoints((short)23); - short idx3 = f3.getIndex(); - wb.createCellStyle().setFont(f3); - - assertEquals(num0 + 3,wb.getNumberOfFonts()); - assertEquals(Font.BOLDWEIGHT_BOLD,wb.getFontAt(idx1).getBoldweight()); - assertEquals(Font.U_DOUBLE,wb.getFontAt(idx2).getUnderline()); - assertEquals(23,wb.getFontAt(idx3).getFontHeightInPoints()); - wb.close(); - } - - /** - * Tests that we can define fonts to a new - * file, save, load, and still see them - */ - @Test - public final void testCreateSave() throws IOException { - Workbook wb1 = _testDataProvider.createWorkbook(); - Sheet s1 = wb1.createSheet(); - Row r1 = s1.createRow(0); - Cell r1c1 = r1.createCell(0); - r1c1.setCellValue(2.2); - - int num0 = wb1.getNumberOfFonts(); - - Font font=wb1.createFont(); - font.setBoldweight(Font.BOLDWEIGHT_BOLD); - font.setStrikeout(true); - font.setColor(IndexedColors.YELLOW.getIndex()); - font.setFontName("Courier"); - short font1Idx = font.getIndex(); - wb1.createCellStyle().setFont(font); - assertEquals(num0 + 1, wb1.getNumberOfFonts()); - - CellStyle cellStyleTitle=wb1.createCellStyle(); - cellStyleTitle.setFont(font); - r1c1.setCellStyle(cellStyleTitle); - - // Save and re-load - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - wb1.close(); - s1 = wb2.getSheetAt(0); - - assertEquals(num0 + 1, wb2.getNumberOfFonts()); - short idx = s1.getRow(0).getCell(0).getCellStyle().getFontIndex(); - Font fnt = wb2.getFontAt(idx); - assertNotNull(fnt); - assertEquals(IndexedColors.YELLOW.getIndex(), fnt.getColor()); - assertEquals("Courier", fnt.getFontName()); - - // Now add an orphaned one - Font font2 = wb2.createFont(); - font2.setItalic(true); - font2.setFontHeightInPoints((short)15); - short font2Idx = font2.getIndex(); - wb2.createCellStyle().setFont(font2); - assertEquals(num0 + 2, wb2.getNumberOfFonts()); - - // Save and re-load - Workbook wb3 = _testDataProvider.writeOutAndReadBack(wb2); - wb2.close(); - s1 = wb3.getSheetAt(0); - - assertEquals(num0 + 2, wb3.getNumberOfFonts()); - assertNotNull(wb3.getFontAt(font1Idx)); - assertNotNull(wb3.getFontAt(font2Idx)); - - assertEquals(15, wb3.getFontAt(font2Idx).getFontHeightInPoints()); - assertEquals(true, wb3.getFontAt(font2Idx).getItalic()); - wb3.close(); - } - - /** - * Test that fonts get added properly - * - * @see org.apache.poi.hssf.usermodel.TestBugs#test45338() - */ - @Test - public final void test45338() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - int num0 = wb.getNumberOfFonts(); - - Sheet s = wb.createSheet(); - s.createRow(0); - s.createRow(1); - s.getRow(0).createCell(0); - s.getRow(1).createCell(0); - - //default font - Font f1 = wb.getFontAt((short)0); - assertEquals(Font.BOLDWEIGHT_NORMAL, f1.getBoldweight()); - - // Check that asking for the same font - // multiple times gives you the same thing. - // Otherwise, our tests wouldn't work! - assertSame(wb.getFontAt((short)0), wb.getFontAt((short)0)); - - // Look for a new font we have - // yet to add - assertNull( - wb.findFont( - Font.BOLDWEIGHT_BOLD, (short)123, (short)(22*20), - "Thingy", false, true, (short)2, (byte)2 - ) - ); - - Font nf = wb.createFont(); - short nfIdx = nf.getIndex(); - assertEquals(num0 + 1, wb.getNumberOfFonts()); - - assertSame(nf, wb.getFontAt(nfIdx)); - - nf.setBoldweight(Font.BOLDWEIGHT_BOLD); - nf.setColor((short)123); - nf.setFontHeightInPoints((short)22); - nf.setFontName("Thingy"); - nf.setItalic(false); - nf.setStrikeout(true); - nf.setTypeOffset((short)2); - nf.setUnderline((byte)2); - - assertEquals(num0 + 1, wb.getNumberOfFonts()); - assertEquals(nf, wb.getFontAt(nfIdx)); - - assertEquals(wb.getFontAt(nfIdx), wb.getFontAt(nfIdx)); - assertTrue(wb.getFontAt((short)0) != wb.getFontAt(nfIdx)); - - // Find it now - assertNotNull( - wb.findFont( - Font.BOLDWEIGHT_BOLD, (short)123, (short)(22*20), - "Thingy", false, true, (short)2, (byte)2 - ) - ); - assertSame(nf, - wb.findFont( - Font.BOLDWEIGHT_BOLD, (short)123, (short)(22*20), - "Thingy", false, true, (short)2, (byte)2 - ) - ); - wb.close(); - } -} diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestFormulaEvaluator.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestFormulaEvaluator.java deleted file mode 100644 index c4922a7c8..000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestFormulaEvaluator.java +++ /dev/null @@ -1,341 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.fail; - -import java.io.IOException; - -import org.apache.poi.ss.ITestDataProvider; -import org.junit.Test; - -/** - * Common superclass for testing implementation of {@link FormulaEvaluator} - */ -public abstract class BaseTestFormulaEvaluator { - - protected final ITestDataProvider _testDataProvider; - - /** - * @param testDataProvider an object that provides test data in / specific way - */ - protected BaseTestFormulaEvaluator(ITestDataProvider testDataProvider) { - _testDataProvider = testDataProvider; - } - - @Test - public void testSimpleArithmetic() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet s = wb.createSheet(); - Row r = s.createRow(0); - - Cell c1 = r.createCell(0); - c1.setCellFormula("1+5"); - assertEquals(0.0, c1.getNumericCellValue(), 0.0); - - Cell c2 = r.createCell(1); - c2.setCellFormula("10/2"); - assertEquals(0.0, c2.getNumericCellValue(), 0.0); - - FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); - - fe.evaluateFormulaCellEnum(c1); - fe.evaluateFormulaCellEnum(c2); - - assertEquals(6.0, c1.getNumericCellValue(), 0.0001); - assertEquals(5.0, c2.getNumericCellValue(), 0.0001); - - wb.close(); - } - - @Test - public void testSumCount() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet s = wb.createSheet(); - Row r = s.createRow(0); - r.createCell(0).setCellValue(2.5); - r.createCell(1).setCellValue(1.1); - r.createCell(2).setCellValue(3.2); - r.createCell(4).setCellValue(10.7); - - r = s.createRow(1); - - Cell c1 = r.createCell(0); - c1.setCellFormula("SUM(A1:B1)"); - assertEquals(0.0, c1.getNumericCellValue(), 0.0); - - Cell c2 = r.createCell(1); - c2.setCellFormula("SUM(A1:E1)"); - assertEquals(0.0, c2.getNumericCellValue(), 0.0); - - Cell c3 = r.createCell(2); - c3.setCellFormula("COUNT(A1:A1)"); - assertEquals(0.0, c3.getNumericCellValue(), 0.0); - - Cell c4 = r.createCell(3); - c4.setCellFormula("COUNTA(A1:E1)"); - assertEquals(0.0, c4.getNumericCellValue(), 0.0); - - - // Evaluate and test - FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); - - fe.evaluateFormulaCellEnum(c1); - fe.evaluateFormulaCellEnum(c2); - fe.evaluateFormulaCellEnum(c3); - fe.evaluateFormulaCellEnum(c4); - - assertEquals(3.6, c1.getNumericCellValue(), 0.0001); - assertEquals(17.5, c2.getNumericCellValue(), 0.0001); - assertEquals(1, c3.getNumericCellValue(), 0.0001); - assertEquals(4, c4.getNumericCellValue(), 0.0001); - - wb.close(); - } - - public void baseTestSharedFormulas(String sampleFile) throws IOException { - Workbook wb = _testDataProvider.openSampleWorkbook(sampleFile); - - Sheet sheet = wb.getSheetAt(0); - - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - Cell cell; - - cell = sheet.getRow(1).getCell(0); - assertEquals("B2", cell.getCellFormula()); - assertEquals("ProductionOrderConfirmation", evaluator.evaluate(cell).getStringValue()); - - cell = sheet.getRow(2).getCell(0); - assertEquals("B3", cell.getCellFormula()); - assertEquals("RequiredAcceptanceDate", evaluator.evaluate(cell).getStringValue()); - - cell = sheet.getRow(3).getCell(0); - assertEquals("B4", cell.getCellFormula()); - assertEquals("Header", evaluator.evaluate(cell).getStringValue()); - - cell = sheet.getRow(4).getCell(0); - assertEquals("B5", cell.getCellFormula()); - assertEquals("UniqueDocumentNumberID", evaluator.evaluate(cell).getStringValue()); - - wb.close(); - } - - /** - * Test creation / evaluation of formulas with sheet-level names - */ - @Test - public void testSheetLevelFormulas() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - - Row row; - Sheet sh1 = wb.createSheet("Sheet1"); - Name nm1 = wb.createName(); - nm1.setNameName("sales_1"); - nm1.setSheetIndex(0); - nm1.setRefersToFormula("Sheet1!$A$1"); - row = sh1.createRow(0); - row.createCell(0).setCellValue(3); - row.createCell(1).setCellFormula("sales_1"); - row.createCell(2).setCellFormula("sales_1*2"); - - Sheet sh2 = wb.createSheet("Sheet2"); - Name nm2 = wb.createName(); - nm2.setNameName("sales_1"); - nm2.setSheetIndex(1); - nm2.setRefersToFormula("Sheet2!$A$1"); - - row = sh2.createRow(0); - row.createCell(0).setCellValue(5); - row.createCell(1).setCellFormula("sales_1"); - row.createCell(2).setCellFormula("sales_1*3"); - - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - assertEquals(3.0, evaluator.evaluate(sh1.getRow(0).getCell(1)).getNumberValue(), 0.0); - assertEquals(6.0, evaluator.evaluate(sh1.getRow(0).getCell(2)).getNumberValue(), 0.0); - - assertEquals(5.0, evaluator.evaluate(sh2.getRow(0).getCell(1)).getNumberValue(), 0.0); - assertEquals(15.0, evaluator.evaluate(sh2.getRow(0).getCell(2)).getNumberValue(), 0.0); - - wb.close(); - } - - @Test - public void testFullColumnRefs() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet("Sheet1"); - Row row = sheet.createRow(0); - Cell cell0 = row.createCell(0); - cell0.setCellFormula("sum(D:D)"); - Cell cell1 = row.createCell(1); - cell1.setCellFormula("sum(D:E)"); - - // some values in column D - setValue(sheet, 1, 3, 5.0); - setValue(sheet, 2, 3, 6.0); - setValue(sheet, 5, 3, 7.0); - setValue(sheet, 50, 3, 8.0); - - // some values in column E - setValue(sheet, 1, 4, 9.0); - setValue(sheet, 2, 4, 10.0); - setValue(sheet, 30000, 4, 11.0); - - // some other values - setValue(sheet, 1, 2, 100.0); - setValue(sheet, 2, 5, 100.0); - setValue(sheet, 3, 6, 100.0); - - - FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); - assertEquals(26.0, fe.evaluate(cell0).getNumberValue(), 0.0); - assertEquals(56.0, fe.evaluate(cell1).getNumberValue(), 0.0); - - wb.close(); - } - - @Test - public void testRepeatedEvaluation() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); - Sheet sheet = wb.createSheet("Sheet1"); - Row r = sheet.createRow(0); - Cell c = r.createCell(0, CellType.FORMULA); - - // Create a value and check it - c.setCellFormula("Date(2011,10,6)"); - CellValue cellValue = fe.evaluate(c); - assertEquals(40822.0, cellValue.getNumberValue(), 0.0); - cellValue = fe.evaluate(c); - assertEquals(40822.0, cellValue.getNumberValue(), 0.0); - - // Change it - c.setCellFormula("Date(2011,10,4)"); - - // Evaluate it, no change as the formula evaluator - // won't know to clear the cache - cellValue = fe.evaluate(c); - assertEquals(40822.0, cellValue.getNumberValue(), 0.0); - - // Manually flush for this cell, and check - fe.notifySetFormula(c); - cellValue = fe.evaluate(c); - assertEquals(40820.0, cellValue.getNumberValue(), 0.0); - - // Change again, without notifying - c.setCellFormula("Date(2010,10,4)"); - cellValue = fe.evaluate(c); - assertEquals(40820.0, cellValue.getNumberValue(), 0.0); - - // Now manually clear all, will see the new value - fe.clearAllCachedResultValues(); - cellValue = fe.evaluate(c); - assertEquals(40455.0, cellValue.getNumberValue(), 0.0); - - wb.close(); - } - - private static void setValue(Sheet sheet, int rowIndex, int colIndex, double value) { - Row row = sheet.getRow(rowIndex); - if (row == null) { - row = sheet.createRow(rowIndex); - } - row.createCell(colIndex).setCellValue(value); - } - - /** - * {@link FormulaEvaluator#evaluate(org.apache.poi.ss.usermodel.Cell)} should behave the same whether the cell - * is null or blank. - */ - @Test - public void testEvaluateBlank() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); - assertNull(fe.evaluate(null)); - Sheet sheet = wb.createSheet("Sheet1"); - Cell cell = sheet.createRow(0).createCell(0); - assertNull(fe.evaluate(cell)); - wb.close(); - } - - /** - * Test for bug due to attempt to convert a cached formula error result to a boolean - */ - @Test - public void testUpdateCachedFormulaResultFromErrorToNumber_bug46479() throws IOException { - - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet("Sheet1"); - Row row = sheet.createRow(0); - Cell cellA1 = row.createCell(0); - Cell cellB1 = row.createCell(1); - cellB1.setCellFormula("A1+1"); - FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); - - cellA1.setCellErrorValue(FormulaError.NAME.getCode()); - fe.evaluateFormulaCellEnum(cellB1); - - cellA1.setCellValue(2.5); - fe.notifyUpdateCell(cellA1); - try { - fe.evaluateInCell(cellB1); - } catch (IllegalStateException e) { - if (e.getMessage().equals("Cannot get a numeric value from a error formula cell")) { - fail("Identified bug 46479a"); - } - } - assertEquals(3.5, cellB1.getNumericCellValue(), 0.0); - - wb.close(); - } - - @Test - public void testRounding_bug51339() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet("Sheet1"); - Row row = sheet.createRow(0); - Cell cellA1 = row.createCell(0); - cellA1.setCellValue(2162.615d); - Cell cellB1 = row.createCell(1); - cellB1.setCellFormula("round(a1,2)"); - Cell cellC1 = row.createCell(2); - cellC1.setCellFormula("roundup(a1,2)"); - Cell cellD1 = row.createCell(3); - cellD1.setCellFormula("rounddown(a1,2)"); - FormulaEvaluator fe = wb.getCreationHelper().createFormulaEvaluator(); - - assertEquals(2162.62, fe.evaluateInCell(cellB1).getNumericCellValue(), 0.0); - assertEquals(2162.62, fe.evaluateInCell(cellC1).getNumericCellValue(), 0.0); - assertEquals(2162.61, fe.evaluateInCell(cellD1).getNumericCellValue(), 0.0); - - wb.close(); - } - - @Test - public void evaluateInCellReturnsSameCell() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - wb.createSheet().createRow(0).createCell(0); - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - Cell cell = wb.getSheetAt(0).getRow(0).getCell(0); - Cell same = evaluator.evaluateInCell(cell); - assertSame(cell, same); - wb.close(); - } -} \ No newline at end of file diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestHyperlink.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestHyperlink.java deleted file mode 100644 index d5b71758c..000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestHyperlink.java +++ /dev/null @@ -1,148 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotSame; - -import java.io.IOException; -import java.util.List; - -import org.junit.Test; -import org.apache.poi.common.usermodel.HyperlinkType; -import org.apache.poi.ss.ITestDataProvider; - -/** - * Test diffrent types of Excel hyperlinks - * - * @author Yegor Kozlov - */ -public abstract class BaseTestHyperlink { - - private final ITestDataProvider _testDataProvider; - - protected BaseTestHyperlink(ITestDataProvider testDataProvider) { - _testDataProvider = testDataProvider; - } - - @Test - public final void testBasicTypes() throws IOException { - Workbook wb1 = _testDataProvider.createWorkbook(); - CreationHelper createHelper = wb1.getCreationHelper(); - - Cell cell; - Hyperlink link; - Sheet sheet = wb1.createSheet("Hyperlinks"); - - //URL - cell = sheet.createRow(0).createCell((short) 0); - cell.setCellValue("URL Link"); - link = createHelper.createHyperlink(HyperlinkType.URL); - link.setAddress("http://poi.apache.org/"); - cell.setHyperlink(link); - - //link to a file in the current directory - cell = sheet.createRow(1).createCell((short) 0); - cell.setCellValue("File Link"); - link = createHelper.createHyperlink(HyperlinkType.FILE); - link.setAddress("hyperinks-beta4-dump.txt"); - cell.setHyperlink(link); - - //e-mail link - cell = sheet.createRow(2).createCell((short) 0); - cell.setCellValue("Email Link"); - link = createHelper.createHyperlink(HyperlinkType.EMAIL); - //note, if subject contains white spaces, make sure they are url-encoded - link.setAddress("mailto:poi@apache.org?subject=Hyperlinks"); - cell.setHyperlink(link); - - //link to a place in this workbook - - //create a target sheet and cell - Sheet sheet2 = wb1.createSheet("Target Sheet"); - sheet2.createRow(0).createCell((short) 0).setCellValue("Target Cell"); - - cell = sheet.createRow(3).createCell((short) 0); - cell.setCellValue("Worksheet Link"); - link = createHelper.createHyperlink(HyperlinkType.DOCUMENT); - link.setAddress("'Target Sheet'!A1"); - cell.setHyperlink(link); - - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - wb1.close(); - - sheet = wb2.getSheetAt(0); - link = sheet.getRow(0).getCell(0).getHyperlink(); - - assertEquals("http://poi.apache.org/", link.getAddress()); - link = sheet.getRow(1).getCell(0).getHyperlink(); - assertEquals("hyperinks-beta4-dump.txt", link.getAddress()); - link = sheet.getRow(2).getCell(0).getHyperlink(); - assertEquals("mailto:poi@apache.org?subject=Hyperlinks", link.getAddress()); - link = sheet.getRow(3).getCell(0).getHyperlink(); - assertEquals("'Target Sheet'!A1", link.getAddress()); - - wb2.close(); - } - - // copy a hyperlink via the copy constructor - @Test - public void testCopyHyperlink() throws IOException { - final Workbook wb = _testDataProvider.createWorkbook(); - final CreationHelper createHelper = wb.getCreationHelper(); - - final Sheet sheet = wb.createSheet("Hyperlinks"); - final Row row = sheet.createRow(0); - final Cell cell1, cell2; - final Hyperlink link1, link2; - - //URL - cell1 = row.createCell(0); - cell2 = row.createCell(1); - cell1.setCellValue("URL Link"); - link1 = createHelper.createHyperlink(HyperlinkType.URL); - link1.setAddress("http://poi.apache.org/"); - cell1.setHyperlink(link1); - - link2 = copyHyperlink(link1); - - // Change address (type is not changeable) - link2.setAddress("http://apache.org/"); - cell2.setHyperlink(link2); - - // Make sure hyperlinks were deep-copied, and modifying one does not modify the other. - assertNotSame(link1, link2); - assertNotEquals(link1, link2); - assertEquals("http://poi.apache.org/", link1.getAddress()); - assertEquals("http://apache.org/", link2.getAddress()); - assertEquals(link1, cell1.getHyperlink()); - assertEquals(link2, cell2.getHyperlink()); - - // Make sure both hyperlinks were added to the sheet - @SuppressWarnings("unchecked") - final List actualHyperlinks = (List) sheet.getHyperlinkList(); - assertEquals(2, actualHyperlinks.size()); - assertEquals(link1, actualHyperlinks.get(0)); - assertEquals(link2, actualHyperlinks.get(1)); - - wb.close(); - } - - public abstract Hyperlink copyHyperlink(Hyperlink link); -} diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestNamedRange.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestNamedRange.java deleted file mode 100644 index 74b5a5fac..000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestNamedRange.java +++ /dev/null @@ -1,755 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.IOException; -import java.util.Arrays; -import java.util.List; - -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.ss.util.AreaReference; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.util.IOUtils; -import org.junit.Test; - -/** - * Tests of implementations of {@link org.apache.poi.ss.usermodel.Name}. - * - * @author Yegor Kozlov - */ -public abstract class BaseTestNamedRange { - - private final ITestDataProvider _testDataProvider; - - protected BaseTestNamedRange(ITestDataProvider testDataProvider) { - _testDataProvider = testDataProvider; - } - - @Test - public final void testCreate() throws Exception { - // Create a new workbook - Workbook wb = _testDataProvider.createWorkbook(); - wb.createSheet("Test1"); - wb.createSheet("Testing Named Ranges"); - - Name name1 = wb.createName(); - name1.setNameName("testOne"); - - //setting a duplicate name should throw IllegalArgumentException - Name name2 = wb.createName(); - try { - name2.setNameName("testOne"); - fail("expected exception"); - } catch (IllegalArgumentException e){ - assertEquals("The workbook already contains this name: testOne", e.getMessage()); - } - //the check for duplicates is case-insensitive - try { - name2.setNameName("TESTone"); - fail("expected exception"); - } catch (IllegalArgumentException e){ - assertEquals("The workbook already contains this name: TESTone", e.getMessage()); - } - - name2.setNameName("testTwo"); - - String ref1 = "Test1!$A$1:$B$1"; - name1.setRefersToFormula(ref1); - assertEquals(ref1, name1.getRefersToFormula()); - assertEquals("Test1", name1.getSheetName()); - - String ref2 = "'Testing Named Ranges'!$A$1:$B$1"; - name1.setRefersToFormula(ref2); - assertEquals("'Testing Named Ranges'!$A$1:$B$1", name1.getRefersToFormula()); - assertEquals("Testing Named Ranges", name1.getSheetName()); - - assertEquals(-1, name1.getSheetIndex()); - name1.setSheetIndex(-1); - assertEquals(-1, name1.getSheetIndex()); - try { - name1.setSheetIndex(2); - fail("should throw IllegalArgumentException"); - } catch(IllegalArgumentException e){ - assertEquals("Sheet index (2) is out of range (0..1)", e.getMessage()); - } - - name1.setSheetIndex(1); - assertEquals(1, name1.getSheetIndex()); - - //-1 means the name applies to the entire workbook - name1.setSheetIndex(-1); - assertEquals(-1, name1.getSheetIndex()); - - //names cannot be blank and must begin with a letter or underscore and not contain spaces - String[] invalidNames = {"", "123", "1Name", "Named Range"}; - for (String name : invalidNames) { - try { - name1.setNameName(name); - fail("should have thrown exceptiuon due to invalid name: " + name); - } catch (IllegalArgumentException e) { - // expected during successful test - } - } - - wb.close(); - } - - @Test - public final void testUnicodeNamedRange() throws Exception { - Workbook wb1 = _testDataProvider.createWorkbook(); - wb1.createSheet("Test"); - Name name = wb1.createName(); - name.setNameName("\u03B1"); - name.setRefersToFormula("Test!$D$3:$E$8"); - - - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - Name name2 = wb2.getNameAt(0); - - assertEquals("\u03B1", name2.getNameName()); - assertEquals("Test!$D$3:$E$8", name2.getRefersToFormula()); - - wb2.close(); - wb1.close(); - } - - @Test - public final void testAddRemove() throws Exception { - Workbook wb = _testDataProvider.createWorkbook(); - assertEquals(0, wb.getNumberOfNames()); - Name name1 = wb.createName(); - name1.setNameName("name1"); - assertEquals(1, wb.getNumberOfNames()); - - Name name2 = wb.createName(); - name2.setNameName("name2"); - assertEquals(2, wb.getNumberOfNames()); - - Name name3 = wb.createName(); - name3.setNameName("name3"); - assertEquals(3, wb.getNumberOfNames()); - - wb.removeName("name2"); - assertEquals(2, wb.getNumberOfNames()); - - wb.removeName(0); - assertEquals(1, wb.getNumberOfNames()); - - wb.close(); - } - - @Test - public final void testScope() throws Exception { - Workbook wb = _testDataProvider.createWorkbook(); - wb.createSheet(); - wb.createSheet(); - - Name name; - - name = wb.createName(); - name.setNameName("aaa"); - name = wb.createName(); - try { - name.setNameName("aaa"); - fail("Expected exception"); - } catch(Exception e){ - assertEquals("The workbook already contains this name: aaa", e.getMessage()); - } - - name = wb.createName(); - name.setSheetIndex(0); - name.setNameName("aaa"); - name = wb.createName(); - name.setSheetIndex(0); - try { - name.setNameName("aaa"); - fail("Expected exception"); - } catch(Exception e){ - assertEquals("The sheet already contains this name: aaa", e.getMessage()); - } - - name = wb.createName(); - name.setSheetIndex(1); - name.setNameName("aaa"); - name = wb.createName(); - name.setSheetIndex(1); - try { - name.setNameName("aaa"); - fail("Expected exception"); - } catch(Exception e){ - assertEquals("The sheet already contains this name: aaa", e.getMessage()); - } - - assertEquals(3, wb.getNames("aaa").size()); - - wb.close(); - } - - /** - * Test case provided by czhang@cambian.com (Chun Zhang) - *

    - * Addresses Bug #13775 - */ - @Test - public final void testMultiNamedRange() throws Exception { - - // Create a new workbook - Workbook wb1 = _testDataProvider.createWorkbook(); - - // Create a worksheet 'sheet1' in the new workbook - wb1.createSheet (); - wb1.setSheetName (0, "sheet1"); - - // Create another worksheet 'sheet2' in the new workbook - wb1.createSheet (); - wb1.setSheetName (1, "sheet2"); - - // Create a new named range for worksheet 'sheet1' - Name namedRange1 = wb1.createName(); - - // Set the name for the named range for worksheet 'sheet1' - namedRange1.setNameName("RangeTest1"); - - // Set the reference for the named range for worksheet 'sheet1' - namedRange1.setRefersToFormula("sheet1" + "!$A$1:$L$41"); - - // Create a new named range for worksheet 'sheet2' - Name namedRange2 = wb1.createName(); - - // Set the name for the named range for worksheet 'sheet2' - namedRange2.setNameName("RangeTest2"); - - // Set the reference for the named range for worksheet 'sheet2' - namedRange2.setRefersToFormula("sheet2" + "!$A$1:$O$21"); - - // Write the workbook to a file - // Read the Excel file and verify its content - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - Name nm1 = wb2.getName("RangeTest1"); - assertTrue("Name is "+nm1.getNameName(),"RangeTest1".equals(nm1.getNameName())); - assertTrue("Reference is "+nm1.getRefersToFormula(),(wb2.getSheetName(0)+"!$A$1:$L$41").equals(nm1.getRefersToFormula())); - - Name nm2 = wb2.getName("RangeTest2"); - assertTrue("Name is "+nm2.getNameName(),"RangeTest2".equals(nm2.getNameName())); - assertTrue("Reference is "+nm2.getRefersToFormula(),(wb2.getSheetName(1)+"!$A$1:$O$21").equals(nm2.getRefersToFormula())); - - wb2.close(); - wb1.close(); - } - - /** - * Test to see if the print areas can be retrieved/created in memory - */ - @Test - public final void testSinglePrintArea() throws Exception { - Workbook workbook = _testDataProvider.createWorkbook(); - workbook.createSheet("Test Print Area"); - String sheetName = workbook.getSheetName(0); - - String reference = "$A$1:$B$1"; - workbook.setPrintArea(0, reference); - - String retrievedPrintArea = workbook.getPrintArea(0); - - assertNotNull("Print Area not defined for first sheet", retrievedPrintArea); - assertEquals("'" + sheetName + "'!$A$1:$B$1", retrievedPrintArea); - - workbook.close(); - } - - /** - * For Convenience, don't force sheet names to be used - */ - @Test - public final void testSinglePrintAreaWOSheet() throws Exception - { - Workbook workbook = _testDataProvider.createWorkbook(); - workbook.createSheet("Test Print Area"); - String sheetName = workbook.getSheetName(0); - - String reference = "$A$1:$B$1"; - workbook.setPrintArea(0, reference); - - String retrievedPrintArea = workbook.getPrintArea(0); - - assertNotNull("Print Area not defined for first sheet", retrievedPrintArea); - assertEquals("'" + sheetName + "'!" + reference, retrievedPrintArea); - - workbook.close(); - } - - /** - * Test to see if the print area made it to the file - */ - @Test - public final void testPrintAreaFile() throws Exception { - Workbook wb1 = _testDataProvider.createWorkbook(); - wb1.createSheet("Test Print Area"); - String sheetName = wb1.getSheetName(0); - - - String reference = "$A$1:$B$1"; - wb1.setPrintArea(0, reference); - - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - - String retrievedPrintArea = wb2.getPrintArea(0); - assertNotNull("Print Area not defined for first sheet", retrievedPrintArea); - assertEquals("References Match", "'" + sheetName + "'!$A$1:$B$1", retrievedPrintArea); - - wb2.close(); - wb1.close(); - } - - /** - * Test to see if multiple print areas made it to the file - */ - @Test - public final void testMultiplePrintAreaFile() throws Exception { - Workbook wb1 = _testDataProvider.createWorkbook(); - - wb1.createSheet("Sheet1"); - wb1.createSheet("Sheet2"); - wb1.createSheet("Sheet3"); - String reference1 = "$A$1:$B$1"; - String reference2 = "$B$2:$D$5"; - String reference3 = "$D$2:$F$5"; - - wb1.setPrintArea(0, reference1); - wb1.setPrintArea(1, reference2); - wb1.setPrintArea(2, reference3); - - //Check created print areas - String retrievedPrintArea; - - retrievedPrintArea = wb1.getPrintArea(0); - assertNotNull("Print Area Not Found (Sheet 1)", retrievedPrintArea); - assertEquals("Sheet1!" + reference1, retrievedPrintArea); - - retrievedPrintArea = wb1.getPrintArea(1); - assertNotNull("Print Area Not Found (Sheet 2)", retrievedPrintArea); - assertEquals("Sheet2!" + reference2, retrievedPrintArea); - - retrievedPrintArea = wb1.getPrintArea(2); - assertNotNull("Print Area Not Found (Sheet 3)", retrievedPrintArea); - assertEquals("Sheet3!" + reference3, retrievedPrintArea); - - // Check print areas after re-reading workbook - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - - retrievedPrintArea = wb2.getPrintArea(0); - assertNotNull("Print Area Not Found (Sheet 1)", retrievedPrintArea); - assertEquals("Sheet1!" + reference1, retrievedPrintArea); - - retrievedPrintArea = wb2.getPrintArea(1); - assertNotNull("Print Area Not Found (Sheet 2)", retrievedPrintArea); - assertEquals("Sheet2!" + reference2, retrievedPrintArea); - - retrievedPrintArea = wb2.getPrintArea(2); - assertNotNull("Print Area Not Found (Sheet 3)", retrievedPrintArea); - assertEquals("Sheet3!" + reference3, retrievedPrintArea); - - wb2.close(); - wb1.close(); - } - - /** - * Tests the setting of print areas with coordinates (Row/Column designations) - * - */ - @Test - public final void testPrintAreaCoords() throws Exception { - Workbook workbook = _testDataProvider.createWorkbook(); - workbook.createSheet("Test Print Area"); - String sheetName = workbook.getSheetName(0); - - workbook.setPrintArea(0, 0, 1, 0, 0); - - String retrievedPrintArea = workbook.getPrintArea(0); - - assertNotNull("Print Area not defined for first sheet", retrievedPrintArea); - assertEquals("'" + sheetName + "'!$A$1:$B$1", retrievedPrintArea); - - workbook.close(); - } - - - /** - * Tests the parsing of union area expressions, and re-display in the presence of sheet names - * with special characters. - */ - @Test - public final void testPrintAreaUnion() throws Exception { - Workbook workbook = _testDataProvider.createWorkbook(); - workbook.createSheet("Test Print Area"); - - String reference = "$A$1:$B$1,$D$1:$F$2"; - workbook.setPrintArea(0, reference); - String retrievedPrintArea = workbook.getPrintArea(0); - assertNotNull("Print Area not defined for first sheet", retrievedPrintArea); - assertEquals("'Test Print Area'!$A$1:$B$1,'Test Print Area'!$D$1:$F$2", retrievedPrintArea); - - workbook.close(); - } - - /** - * Verifies an existing print area is deleted - * - */ - @Test - public final void testPrintAreaRemove() throws Exception { - Workbook workbook = _testDataProvider.createWorkbook(); - workbook.createSheet("Test Print Area"); - workbook.getSheetName(0); - - workbook.setPrintArea(0, 0, 1, 0, 0); - - String retrievedPrintArea = workbook.getPrintArea(0); - - assertNotNull("Print Area not defined for first sheet", retrievedPrintArea); - - workbook.removePrintArea(0); - assertNull("PrintArea was not removed", workbook.getPrintArea(0)); - workbook.close(); - } - - /** - * Test that multiple named ranges can be added written and read - */ - @Test - public final void testMultipleNamedWrite() throws Exception { - Workbook wb1 = _testDataProvider.createWorkbook(); - - - wb1.createSheet("testSheet1"); - String sheetName = wb1.getSheetName(0); - - assertEquals("testSheet1", sheetName); - - //Creating new Named Range - Name newNamedRange = wb1.createName(); - - newNamedRange.setNameName("RangeTest"); - newNamedRange.setRefersToFormula(sheetName + "!$D$4:$E$8"); - - //Creating another new Named Range - Name newNamedRange2 = wb1.createName(); - - newNamedRange2.setNameName("AnotherTest"); - newNamedRange2.setRefersToFormula(sheetName + "!$F$1:$G$6"); - - wb1.getNameAt(0); - - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - Name nm =wb2.getName("RangeTest"); - assertTrue("Name is "+nm.getNameName(),"RangeTest".equals(nm.getNameName())); - assertTrue("Reference is "+nm.getRefersToFormula(),(wb2.getSheetName(0)+"!$D$4:$E$8").equals(nm.getRefersToFormula())); - - nm = wb2.getName("AnotherTest"); - assertTrue("Name is "+nm.getNameName(),"AnotherTest".equals(nm.getNameName())); - assertTrue("Reference is "+nm.getRefersToFormula(),newNamedRange2.getRefersToFormula().equals(nm.getRefersToFormula())); - - wb2.close(); - wb1.close(); - } - /** - * Verifies correct functioning for "single cell named range" (aka "named cell") - */ - @Test - public final void testNamedCell_1() throws Exception { - - // setup for this testcase - String sheetName = "Test Named Cell"; - String cellName = "named_cell"; - String cellValue = "TEST Value"; - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet(sheetName); - CreationHelper factory = wb.getCreationHelper(); - sheet.createRow(0).createCell(0).setCellValue(factory.createRichTextString(cellValue)); - - // create named range for a single cell using areareference - Name namedCell = wb.createName(); - namedCell.setNameName(cellName); - String reference = "'" + sheetName + "'" + "!A1:A1"; - namedCell.setRefersToFormula(reference); - - // retrieve the newly created named range - Name aNamedCell = wb.getName(cellName); - assertNotNull(aNamedCell); - - // retrieve the cell at the named range and test its contents - @SuppressWarnings("deprecation") - AreaReference aref = new AreaReference(aNamedCell.getRefersToFormula()); - assertTrue("Should be exactly 1 cell in the named cell :'" +cellName+"'", aref.isSingleCell()); - - CellReference cref = aref.getFirstCell(); - assertNotNull(cref); - Sheet s = wb.getSheet(cref.getSheetName()); - assertNotNull(s); - Row r = sheet.getRow(cref.getRow()); - Cell c = r.getCell(cref.getCol()); - String contents = c.getRichStringCellValue().getString(); - assertEquals("Contents of cell retrieved by its named reference", contents, cellValue); - - wb.close(); - } - - /** - * Verifies correct functioning for "single cell named range" (aka "named cell") - */ - @Test - public final void testNamedCell_2() throws Exception { - - // setup for this testcase - String sname = "TestSheet", cname = "TestName", cvalue = "TestVal"; - Workbook wb = _testDataProvider.createWorkbook(); - CreationHelper factory = wb.getCreationHelper(); - Sheet sheet = wb.createSheet(sname); - sheet.createRow(0).createCell(0).setCellValue(factory.createRichTextString(cvalue)); - - // create named range for a single cell using cellreference - Name namedCell = wb.createName(); - namedCell.setNameName(cname); - String reference = sname+"!A1"; - namedCell.setRefersToFormula(reference); - - // retrieve the newly created named range - Name aNamedCell = wb.getName(cname); - assertNotNull(aNamedCell); - - // retrieve the cell at the named range and test its contents - CellReference cref = new CellReference(aNamedCell.getRefersToFormula()); - assertNotNull(cref); - Sheet s = wb.getSheet(cref.getSheetName()); - assertNotNull(s); - Row r = sheet.getRow(cref.getRow()); - Cell c = r.getCell(cref.getCol()); - String contents = c.getRichStringCellValue().getString(); - assertEquals("Contents of cell retrieved by its named reference", contents, cvalue); - - wb.close(); - } - - - /** - * Bugzilla attachment 23444 (from bug 46973) has a NAME record with the following encoding: - *

    -     * 00000000 | 18 00 17 00 00 00 00 08 00 00 00 00 00 00 00 00 | ................
    -     * 00000010 | 00 00 00 55 50 53 53 74 61 74 65                | ...UPSState
    -     * 
    - * - * This caused trouble for anything that requires {@link Name#getRefersToFormula()} - * It is easy enough to re-create the the same data (by not setting the formula). Excel - * seems to gracefully remove this uninitialized name record. It would be nice if POI - * could do the same, but that would involve adjusting subsequent name indexes across - * all formulas.

    - * - * For the moment, POI has been made to behave more sensibly with uninitialized name - * records. - */ - @Test - public final void testUninitialisedNameGetRefersToFormula_bug46973() throws Exception { - Workbook wb = _testDataProvider.createWorkbook(); - Name n = wb.createName(); - n.setNameName("UPSState"); - String formula = n.getRefersToFormula(); - - // bug 46973: fails here with IllegalArgumentException - // ptgs must not be null - - assertNull(formula); - // according to exact definition of isDeleted() - assertFalse(n.isDeleted()); - wb.close(); - } - - @Test - public final void testDeletedCell() throws Exception { - Workbook wb = _testDataProvider.createWorkbook(); - Name n = wb.createName(); - n.setNameName("MyName"); - // contrived example to expose bug: - n.setRefersToFormula("if(A1,\"#REF!\", \"\")"); - - assertFalse("Identified bug in recoginising formulas referring to deleted cells", n.isDeleted()); - - wb.close(); - } - - @Test - public final void testFunctionNames() throws Exception { - Workbook wb = _testDataProvider.createWorkbook(); - Name n = wb.createName(); - assertFalse(n.isFunctionName()); - - n.setFunction(false); - assertFalse(n.isFunctionName()); - - n.setFunction(true); - assertTrue(n.isFunctionName()); - - n.setFunction(false); - assertFalse(n.isFunctionName()); - - wb.close(); - } - - @Test - public final void testDefferedSetting() throws Exception { - Workbook wb = _testDataProvider.createWorkbook(); - Name n1 = wb.createName(); - assertNull(n1.getRefersToFormula()); - assertEquals("", n1.getNameName()); - - Name n2 = wb.createName(); - assertNull(n2.getRefersToFormula()); - assertEquals("", n2.getNameName()); - - n1.setNameName("sale_1"); - n1.setRefersToFormula("10"); - - n2.setNameName("sale_2"); - n2.setRefersToFormula("20"); - - try { - n2.setNameName("sale_1"); - fail("Expected exception"); - } catch(Exception e){ - assertEquals("The workbook already contains this name: sale_1", e.getMessage()); - } - - wb.close(); - } - - @Test - public void testBug56930() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - - // x1 on sheet1 defines "x=1" - wb.createSheet("sheet1"); - Name x1 = wb.createName(); - - x1.setNameName("x"); - x1.setRefersToFormula("1"); - x1.setSheetIndex(wb.getSheetIndex("sheet1")); - - // x2 on sheet2 defines "x=2" - wb.createSheet("sheet2"); - Name x2 = wb.createName(); - x2.setNameName("x"); - x2.setRefersToFormula("2"); - x2.setSheetIndex(wb.getSheetIndex("sheet2")); - - List names = wb.getNames("x"); - assertEquals("Had: " + names, 2, names.size()); - assertEquals("1", names.get(0).getRefersToFormula()); - assertEquals("2", names.get(1).getRefersToFormula()); - - assertEquals("1", wb.getName("x").getRefersToFormula()); - wb.removeName("x"); - assertEquals("2", wb.getName("x").getRefersToFormula()); - - wb.close(); - } - - // bug 56781: name validation only checks for first character's validity and presence of spaces - // bug 60246: validate name does not allow DOT in named ranges - @Test - public void testValid() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - - Name name = wb.createName(); - for (String valid : Arrays.asList( - "Hello", - "number1", - "_underscore", - "underscore_", - "p.e.r.o.i.d.s", - "\\Backslash", - "Backslash\\" - )) { - name.setNameName(valid); - } - - wb.close(); - } - - @Test - public void testInvalid() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - - Name name = wb.createName(); - try { - name.setNameName(""); - fail("expected exception: (blank)"); - } catch (final IllegalArgumentException e) { - assertEquals("Name cannot be blank", e.getMessage()); - } - - for (String invalid : Arrays.asList( - "1number", - "Sheet1!A1", - "Exclamation!", - "Has Space", - "Colon:", - "A-Minus", - "A+Plus", - "Dollar$", - ".periodAtBeginning", - "R", //special shorthand - "C", //special shorthand - "A1", // A1-style cell reference - "R1C1", // R1C1-style cell reference - "NameThatIsLongerThan255Characters.NameThatIsLongerThan255Characters.NameThatIsLongerThan255Characters..."+ - "NameThatIsLongerThan255Characters.NameThatIsLongerThan255Characters.NameThatIsLongerThan255Characters..."+ - "NameThatIsLongerThan255Characters.NameThatIsLongerThan255Characters.NameThatIsLongerThan255Characters..."+ - "NameThatIsLongerThan255Characters.NameThatIsLongerThan255Characters.NameThatIsLongerThan255Characters..."+ - "NameThatIsLongerThan255Characters.NameThatIsLongerThan255Characters.NameThatIsLongerThan255Characters" - )) { - try { - name.setNameName(invalid); - fail("expected exception: " + invalid); - } catch (final IllegalArgumentException e) { - assertTrue(invalid, - e.getMessage().startsWith("Invalid name: '"+invalid+"'")); - } - } - - } - - // bug 60260: renaming a sheet with a named range referring to a unicode (non-ASCII) sheet name - @Test - public void renameSheetWithNamedRangeReferringToUnicodeSheetName() { - Workbook wb = _testDataProvider.createWorkbook(); - wb.createSheet("Sheet\u30FB1"); - - Name name = wb.createName(); - name.setNameName("test_named_range"); - name.setRefersToFormula("'Sheet\u30FB201'!A1:A6"); - - wb.setSheetName(0, "Sheet 1"); - IOUtils.closeQuietly(wb); - } -} diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestPicture.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestPicture.java deleted file mode 100644 index d7c68940c..000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestPicture.java +++ /dev/null @@ -1,137 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import java.awt.Dimension; -import java.awt.Point; -import java.awt.image.BufferedImage; -import java.io.ByteArrayInputStream; -import java.io.IOException; - -import javax.imageio.ImageIO; - -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.ss.util.ImageUtils; -import org.apache.poi.util.Units; -import org.junit.Test; - -/** - * @author Yegor Kozlov - */ -public abstract class BaseTestPicture { - - private final ITestDataProvider _testDataProvider; - - protected BaseTestPicture(ITestDataProvider testDataProvider) { - _testDataProvider = testDataProvider; - } - - public void baseTestResize(Picture input, Picture compare, double scaleX, double scaleY) { - input.resize(scaleX, scaleY); - - ClientAnchor inpCA = input.getClientAnchor(); - ClientAnchor cmpCA = compare.getClientAnchor(); - - Dimension inpDim = ImageUtils.getDimensionFromAnchor(input); - Dimension cmpDim = ImageUtils.getDimensionFromAnchor(compare); - - double emuPX = Units.EMU_PER_PIXEL; - - assertEquals("the image height differs", inpDim.getHeight(), cmpDim.getHeight(), emuPX*6); - assertEquals("the image width differs", inpDim.getWidth(), cmpDim.getWidth(), emuPX*6); - assertEquals("the starting column differs", inpCA.getCol1(), cmpCA.getCol1()); - assertEquals("the column x-offset differs", inpCA.getDx1(), cmpCA.getDx1(), 1); - assertEquals("the column y-offset differs", inpCA.getDy1(), cmpCA.getDy1(), 1); - assertEquals("the ending columns differs", inpCA.getCol2(), cmpCA.getCol2()); - // can't compare row heights because of variable test heights - - input.resize(); - inpDim = ImageUtils.getDimensionFromAnchor(input); - - Dimension imgDim = input.getImageDimension(); - - assertEquals("the image height differs", imgDim.getHeight(), inpDim.getHeight()/emuPX, 1); - assertEquals("the image width differs", imgDim.getWidth(), inpDim.getWidth()/emuPX, 1); - } - - - @Test - public void testResizeNoColumns() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - try { - Sheet sheet = wb.createSheet(); - - Row row = sheet.createRow(0); - - handleResize(wb, sheet, row); - } finally { - wb.close(); - } - } - - @Test - public void testResizeWithColumns() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - try { - Sheet sheet = wb.createSheet(); - - Row row = sheet.createRow(0); - row.createCell(0); - - handleResize(wb, sheet, row); - } finally { - wb.close(); - } - } - - - private void handleResize(Workbook wb, Sheet sheet, Row row) throws IOException { - Drawing drawing = sheet.createDrawingPatriarch(); - CreationHelper createHelper = wb.getCreationHelper(); - - final byte[] bytes = HSSFITestDataProvider.instance.getTestDataFileContent("logoKarmokar4.png"); - - row.setHeightInPoints(getImageSize(bytes).y); - - int pictureIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_PNG); - - //add a picture shape - ClientAnchor anchor = createHelper.createClientAnchor(); - //set top-left corner of the picture, - //subsequent call of Picture#resize() will operate relative to it - anchor.setCol1(0); - anchor.setRow1(0); - - Picture pict = drawing.createPicture(anchor, pictureIdx); - - //auto-size picture relative to its top-left corner - pict.resize(); - } - - private static Point getImageSize( byte [] image) throws IOException { - BufferedImage img = ImageIO.read(new ByteArrayInputStream(image)); - - assertNotNull(img); - - return new Point(img.getWidth(), img.getHeight()); - } -} diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestRow.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestRow.java deleted file mode 100644 index 2492c20a8..000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestRow.java +++ /dev/null @@ -1,469 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.IOException; -import java.util.Iterator; - -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.ss.usermodel.Row.MissingCellPolicy; -import org.junit.Test; - -/** - * A base class for testing implementations of - * {@link org.apache.poi.ss.usermodel.Row} - */ -public abstract class BaseTestRow { - - protected final ITestDataProvider _testDataProvider; - - protected BaseTestRow(ITestDataProvider testDataProvider) { - _testDataProvider = testDataProvider; - } - - @Test - public void testLastAndFirstColumns() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet(); - Row row = sheet.createRow(0); - assertEquals(-1, row.getFirstCellNum()); - assertEquals(-1, row.getLastCellNum()); - - //getting cells from an empty row should returns null - for(int i=0; i < 10; i++) assertNull(row.getCell(i)); - - row.createCell(2); - assertEquals(2, row.getFirstCellNum()); - assertEquals(3, row.getLastCellNum()); - - row.createCell(1); - assertEquals(1, row.getFirstCellNum()); - assertEquals(3, row.getLastCellNum()); - - // check the exact case reported in 'bug' 43901 - notice that the cellNum is '0' based - row.createCell(3); - assertEquals(1, row.getFirstCellNum()); - assertEquals(4, row.getLastCellNum()); - workbook.close(); - } - - /** - * Make sure that there is no cross-talk between rows especially with getFirstCellNum and getLastCellNum - * This test was added in response to bug report 44987. - */ - @Test - public void testBoundsInMultipleRows() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet(); - Row rowA = sheet.createRow(0); - - rowA.createCell(10); - rowA.createCell(5); - assertEquals(5, rowA.getFirstCellNum()); - assertEquals(11, rowA.getLastCellNum()); - - Row rowB = sheet.createRow(1); - rowB.createCell(15); - rowB.createCell(30); - assertEquals(15, rowB.getFirstCellNum()); - assertEquals(31, rowB.getLastCellNum()); - - assertEquals(5, rowA.getFirstCellNum()); - assertEquals(11, rowA.getLastCellNum()); - rowA.createCell(50); - assertEquals(51, rowA.getLastCellNum()); - - assertEquals(31, rowB.getLastCellNum()); - workbook.close(); - } - - @Test - public void testRemoveCell() throws IOException { - Workbook wb1 = _testDataProvider.createWorkbook(); - { - Sheet sheet = wb1.createSheet(); - Row row = sheet.createRow(0); - - assertEquals(0, row.getPhysicalNumberOfCells()); - assertEquals(-1, row.getLastCellNum()); - assertEquals(-1, row.getFirstCellNum()); - - row.createCell(1); - assertEquals(2, row.getLastCellNum()); - assertEquals(1, row.getFirstCellNum()); - assertEquals(1, row.getPhysicalNumberOfCells()); - row.createCell(3); - assertEquals(4, row.getLastCellNum()); - assertEquals(1, row.getFirstCellNum()); - assertEquals(2, row.getPhysicalNumberOfCells()); - row.removeCell(row.getCell(3)); - assertEquals(2, row.getLastCellNum()); - assertEquals(1, row.getFirstCellNum()); - assertEquals(1, row.getPhysicalNumberOfCells()); - row.removeCell(row.getCell(1)); - assertEquals(-1, row.getLastCellNum()); - assertEquals(-1, row.getFirstCellNum()); - assertEquals(0, row.getPhysicalNumberOfCells()); - } - - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - wb1.close(); - - { - Sheet sheet = wb2.getSheetAt(0); - Row row = sheet.getRow(0); - assertEquals(-1, row.getLastCellNum()); - assertEquals(-1, row.getFirstCellNum()); - assertEquals(0, row.getPhysicalNumberOfCells()); - } - - wb2.close(); - } - - protected void baseTestRowBounds(int maxRowNum) throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet(); - //Test low row bound - sheet.createRow(0); - //Test low row bound exception - try { - sheet.createRow(-1); - fail("expected exception"); - } catch (IllegalArgumentException e) { - // expected during successful test - assertTrue("Did not find expected error message, had: " + e, - e.getMessage().startsWith("Invalid row number (-1)")); - } - - //Test high row bound - sheet.createRow(maxRowNum); - //Test high row bound exception - try { - sheet.createRow(maxRowNum + 1); - fail("expected exception"); - } catch (IllegalArgumentException e) { - // expected during successful test - assertEquals("Invalid row number ("+(maxRowNum + 1)+") outside allowable range (0.."+maxRowNum+")", e.getMessage()); - } - - workbook.close(); - } - - protected void baseTestCellBounds(int maxCellNum) throws IOException { - Workbook wb1 = _testDataProvider.createWorkbook(); - Sheet sheet = wb1.createSheet(); - - Row row = sheet.createRow(0); - //Test low cell bound - try { - row.createCell(-1); - fail("expected exception"); - } catch (IllegalArgumentException e) { - // expected during successful test - assertTrue(e.getMessage().startsWith("Invalid column index (-1)")); - } - - //Test high cell bound - try { - row.createCell(maxCellNum + 1); - fail("expected exception"); - } catch (IllegalArgumentException e) { - // expected during successful test - assertTrue(e.getMessage().startsWith("Invalid column index ("+(maxCellNum+1)+")")); - } - for(int i=0; i < maxCellNum; i++){ - row.createCell(i); - } - assertEquals(maxCellNum, row.getPhysicalNumberOfCells()); - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - wb1.close(); - - sheet = wb2.getSheetAt(0); - row = sheet.getRow(0); - assertEquals(maxCellNum, row.getPhysicalNumberOfCells()); - for(int i=0; i < maxCellNum; i++){ - Cell cell = row.getCell(i); - assertEquals(i, cell.getColumnIndex()); - } - wb2.close(); - } - - /** - * Prior to patch 43901, POI was producing files with the wrong last-column - * number on the row - */ - @Test - public void testLastCellNumIsCorrectAfterAddCell_bug43901() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet("test"); - Row row = sheet.createRow(0); - - // New row has last col -1 - assertEquals(-1, row.getLastCellNum()); - if(row.getLastCellNum() == 0) { - fail("Identified bug 43901"); - } - - // Create two cells, will return one higher - // than that for the last number - row.createCell(0); - assertEquals(1, row.getLastCellNum()); - row.createCell(255); - assertEquals(256, row.getLastCellNum()); - workbook.close(); - } - - /** - * Tests for the missing/blank cell policy stuff - */ - @Test - public void testGetCellPolicy() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet("test"); - Row row = sheet.createRow(0); - - // 0 -> string - // 1 -> num - // 2 missing - // 3 missing - // 4 -> blank - // 5 -> num - row.createCell(0).setCellValue("test"); - row.createCell(1).setCellValue(3.2); - row.createCell(4, CellType.BLANK); - row.createCell(5).setCellValue(4); - - // First up, no policy given, uses default - assertEquals(CellType.STRING, row.getCell(0).getCellTypeEnum()); - assertEquals(CellType.NUMERIC, row.getCell(1).getCellTypeEnum()); - assertEquals(null, row.getCell(2)); - assertEquals(null, row.getCell(3)); - assertEquals(CellType.BLANK, row.getCell(4).getCellTypeEnum()); - assertEquals(CellType.NUMERIC, row.getCell(5).getCellTypeEnum()); - - // RETURN_NULL_AND_BLANK - same as default - assertEquals(CellType.STRING, row.getCell(0, MissingCellPolicy.RETURN_NULL_AND_BLANK).getCellTypeEnum()); - assertEquals(CellType.NUMERIC, row.getCell(1, MissingCellPolicy.RETURN_NULL_AND_BLANK).getCellTypeEnum()); - assertEquals(null, row.getCell(2, MissingCellPolicy.RETURN_NULL_AND_BLANK)); - assertEquals(null, row.getCell(3, MissingCellPolicy.RETURN_NULL_AND_BLANK)); - assertEquals(CellType.BLANK, row.getCell(4, MissingCellPolicy.RETURN_NULL_AND_BLANK).getCellTypeEnum()); - assertEquals(CellType.NUMERIC, row.getCell(5, MissingCellPolicy.RETURN_NULL_AND_BLANK).getCellTypeEnum()); - - // RETURN_BLANK_AS_NULL - nearly the same - assertEquals(CellType.STRING, row.getCell(0, MissingCellPolicy.RETURN_BLANK_AS_NULL).getCellTypeEnum()); - assertEquals(CellType.NUMERIC, row.getCell(1, MissingCellPolicy.RETURN_BLANK_AS_NULL).getCellTypeEnum()); - assertEquals(null, row.getCell(2, MissingCellPolicy.RETURN_BLANK_AS_NULL)); - assertEquals(null, row.getCell(3, MissingCellPolicy.RETURN_BLANK_AS_NULL)); - assertEquals(null, row.getCell(4, MissingCellPolicy.RETURN_BLANK_AS_NULL)); - assertEquals(CellType.NUMERIC, row.getCell(5, MissingCellPolicy.RETURN_BLANK_AS_NULL).getCellTypeEnum()); - - // CREATE_NULL_AS_BLANK - creates as needed - assertEquals(CellType.STRING, row.getCell(0, MissingCellPolicy.CREATE_NULL_AS_BLANK).getCellTypeEnum()); - assertEquals(CellType.NUMERIC, row.getCell(1, MissingCellPolicy.CREATE_NULL_AS_BLANK).getCellTypeEnum()); - assertEquals(CellType.BLANK, row.getCell(2, MissingCellPolicy.CREATE_NULL_AS_BLANK).getCellTypeEnum()); - assertEquals(CellType.BLANK, row.getCell(3, MissingCellPolicy.CREATE_NULL_AS_BLANK).getCellTypeEnum()); - assertEquals(CellType.BLANK, row.getCell(4, MissingCellPolicy.CREATE_NULL_AS_BLANK).getCellTypeEnum()); - assertEquals(CellType.NUMERIC, row.getCell(5, MissingCellPolicy.CREATE_NULL_AS_BLANK).getCellTypeEnum()); - - // Check created ones get the right column - assertEquals(0, row.getCell(0, MissingCellPolicy.CREATE_NULL_AS_BLANK).getColumnIndex()); - assertEquals(1, row.getCell(1, MissingCellPolicy.CREATE_NULL_AS_BLANK).getColumnIndex()); - assertEquals(2, row.getCell(2, MissingCellPolicy.CREATE_NULL_AS_BLANK).getColumnIndex()); - assertEquals(3, row.getCell(3, MissingCellPolicy.CREATE_NULL_AS_BLANK).getColumnIndex()); - assertEquals(4, row.getCell(4, MissingCellPolicy.CREATE_NULL_AS_BLANK).getColumnIndex()); - assertEquals(5, row.getCell(5, MissingCellPolicy.CREATE_NULL_AS_BLANK).getColumnIndex()); - - - // Now change the cell policy on the workbook, check - // that that is now used if no policy given - workbook.setMissingCellPolicy(MissingCellPolicy.RETURN_BLANK_AS_NULL); - - assertEquals(CellType.STRING, row.getCell(0).getCellTypeEnum()); - assertEquals(CellType.NUMERIC, row.getCell(1).getCellTypeEnum()); - assertEquals(null, row.getCell(2)); - assertEquals(null, row.getCell(3)); - assertEquals(null, row.getCell(4)); - assertEquals(CellType.NUMERIC, row.getCell(5).getCellTypeEnum()); - - workbook.close(); - } - - @Test - public void testRowHeight() throws IOException { - Workbook wb1 = _testDataProvider.createWorkbook(); - Sheet sheet = wb1.createSheet(); - Row row1 = sheet.createRow(0); - - assertEquals(sheet.getDefaultRowHeight(), row1.getHeight()); - - sheet.setDefaultRowHeightInPoints(20); - row1.setHeight((short)-1); //reset the row height - assertEquals(20.0f, row1.getHeightInPoints(), 0F); - assertEquals(20*20, row1.getHeight()); - - Row row2 = sheet.createRow(1); - assertEquals(sheet.getDefaultRowHeight(), row2.getHeight()); - row2.setHeight((short)310); - assertEquals(310, row2.getHeight()); - assertEquals(310F/20, row2.getHeightInPoints(), 0F); - - Row row3 = sheet.createRow(2); - row3.setHeightInPoints(25.5f); - assertEquals((short)(25.5f*20), row3.getHeight()); - assertEquals(25.5f, row3.getHeightInPoints(), 0F); - - Row row4 = sheet.createRow(3); - assertFalse(row4.getZeroHeight()); - row4.setZeroHeight(true); - assertTrue(row4.getZeroHeight()); - - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - wb1.close(); - sheet = wb2.getSheetAt(0); - - row1 = sheet.getRow(0); - row2 = sheet.getRow(1); - row3 = sheet.getRow(2); - row4 = sheet.getRow(3); - assertEquals(20.0f, row1.getHeightInPoints(), 0F); - assertEquals(20*20, row1.getHeight()); - - assertEquals(310, row2.getHeight()); - assertEquals(310F/20, row2.getHeightInPoints(), 0F); - - assertEquals((short)(25.5f*20), row3.getHeight()); - assertEquals(25.5f, row3.getHeightInPoints(), 0F); - - assertFalse(row1.getZeroHeight()); - assertFalse(row2.getZeroHeight()); - assertFalse(row3.getZeroHeight()); - assertTrue(row4.getZeroHeight()); - wb2.close(); - } - - /** - * Test adding cells to a row in various places and see if we can find them again. - */ - @Test - public void testCellIterator() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - - // One cell at the beginning - Cell cell1 = row.createCell(1); - Iterator it = row.cellIterator(); - assertTrue(it.hasNext()); - assertTrue(cell1 == it.next()); - assertFalse(it.hasNext()); - - // Add another cell at the end - Cell cell2 = row.createCell(99); - it = row.cellIterator(); - assertTrue(it.hasNext()); - assertTrue(cell1 == it.next()); - assertTrue(it.hasNext()); - assertTrue(cell2 == it.next()); - - // Add another cell at the beginning - Cell cell3 = row.createCell(0); - it = row.cellIterator(); - assertTrue(it.hasNext()); - assertTrue(cell3 == it.next()); - assertTrue(it.hasNext()); - assertTrue(cell1 == it.next()); - assertTrue(it.hasNext()); - assertTrue(cell2 == it.next()); - - // Replace cell1 - Cell cell4 = row.createCell(1); - it = row.cellIterator(); - assertTrue(it.hasNext()); - assertTrue(cell3 == it.next()); - assertTrue(it.hasNext()); - assertTrue(cell4 == it.next()); - assertTrue(it.hasNext()); - assertTrue(cell2 == it.next()); - assertFalse(it.hasNext()); - - // Add another cell, specifying the cellType - Cell cell5 = row.createCell(2, CellType.STRING); - it = row.cellIterator(); - assertNotNull(cell5); - assertTrue(it.hasNext()); - assertTrue(cell3 == it.next()); - assertTrue(it.hasNext()); - assertTrue(cell4 == it.next()); - assertTrue(it.hasNext()); - assertTrue(cell5 == it.next()); - assertTrue(it.hasNext()); - assertTrue(cell2 == it.next()); - assertEquals(CellType.STRING, cell5.getCellTypeEnum()); - wb.close(); - } - - @Test - public void testRowStyle() throws IOException { - Workbook wb1 = _testDataProvider.createWorkbook(); - Sheet sheet = wb1.createSheet("test"); - Row row1 = sheet.createRow(0); - Row row2 = sheet.createRow(1); - - // Won't be styled currently - assertEquals(false, row1.isFormatted()); - assertEquals(false, row2.isFormatted()); - assertEquals(null, row1.getRowStyle()); - assertEquals(null, row2.getRowStyle()); - - // Style one - CellStyle style = wb1.createCellStyle(); - style.setDataFormat((short)4); - row2.setRowStyle(style); - - // Check - assertEquals(false, row1.isFormatted()); - assertEquals(true, row2.isFormatted()); - assertEquals(null, row1.getRowStyle()); - assertEquals(style, row2.getRowStyle()); - - // Save, load and re-check - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - wb1.close(); - - sheet = wb2.getSheetAt(0); - - row1 = sheet.getRow(0); - row2 = sheet.getRow(1); - style = wb2.getCellStyleAt(style.getIndex()); - - assertEquals(false, row1.isFormatted()); - assertEquals(true, row2.isFormatted()); - assertEquals(null, row1.getRowStyle()); - assertEquals(style, row2.getRowStyle()); - assertEquals(4, style.getDataFormat()); - - wb2.close(); - } -} diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheet.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheet.java deleted file mode 100644 index a0a82eeb9..000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheet.java +++ /dev/null @@ -1,1386 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import org.apache.poi.common.usermodel.HyperlinkType; -import org.apache.poi.hssf.usermodel.*; -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.ss.util.CellAddress; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.PaneInformation; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; - -import java.io.IOException; -import java.util.*; -import java.util.Map.Entry; - -import static org.apache.poi.POITestCase.assertBetween; -import static org.junit.Assert.*; -import static org.junit.Assume.assumeTrue; - -/** - * Common superclass for testing {@link org.apache.poi.xssf.usermodel.XSSFCell} and - * {@link org.apache.poi.hssf.usermodel.HSSFCell} - */ -public abstract class BaseTestSheet { - private static final int ROW_COUNT = 40000; - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - protected final ITestDataProvider _testDataProvider; - - protected BaseTestSheet(ITestDataProvider testDataProvider) { - _testDataProvider = testDataProvider; - } - - protected void trackColumnsForAutoSizingIfSXSSF(Sheet sheet) { - // do nothing for Sheet base class. This will be overridden for SXSSFSheets. - } - - @Test - public void createRow() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet(); - assertEquals(0, sheet.getPhysicalNumberOfRows()); - - //Test that we get null for undefined rownumber - assertNull(sheet.getRow(1)); - - // Test row creation with consecutive indexes - Row row1 = sheet.createRow(0); - Row row2 = sheet.createRow(1); - assertEquals(0, row1.getRowNum()); - assertEquals(1, row2.getRowNum()); - Iterator it = sheet.rowIterator(); - assertTrue(it.hasNext()); - assertSame(row1, it.next()); - assertTrue(it.hasNext()); - assertSame(row2, it.next()); - assertEquals(1, sheet.getLastRowNum()); - - // Test row creation with non consecutive index - Row row101 = sheet.createRow(100); - assertNotNull(row101); - assertEquals(100, sheet.getLastRowNum()); - assertEquals(3, sheet.getPhysicalNumberOfRows()); - - // Test overwriting an existing row - Row row2_ovrewritten = sheet.createRow(1); - Cell cell = row2_ovrewritten.createCell(0); - cell.setCellValue(100); - Iterator it2 = sheet.rowIterator(); - assertTrue(it2.hasNext()); - assertSame(row1, it2.next()); - assertTrue(it2.hasNext()); - Row row2_ovrewritten_ref = it2.next(); - assertSame(row2_ovrewritten, row2_ovrewritten_ref); - assertEquals(100.0, row2_ovrewritten_ref.getCell(0).getNumericCellValue(), 0.0); - - workbook.close(); - } - - @Test(expected=IllegalArgumentException.class) - public void createRowBeforeFirstRow() throws IOException { - final Workbook workbook = _testDataProvider.createWorkbook(); - final Sheet sh = workbook.createSheet(); - sh.createRow(0); - try { - // Negative rows not allowed - sh.createRow(-1); - } finally { - workbook.close(); - } - } - - @Test(expected=IllegalArgumentException.class) - public void createRowAfterLastRow() throws IOException { - final SpreadsheetVersion version = _testDataProvider.getSpreadsheetVersion(); - final Workbook workbook = _testDataProvider.createWorkbook(); - final Sheet sh = workbook.createSheet(); - sh.createRow(version.getLastRowIndex()); - try { - // Row number must be between 0 and last row - sh.createRow(version.getLastRowIndex() + 1); - } finally { - workbook.close(); - } - } - - @Test - public void removeRow() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet1 = workbook.createSheet(); - assertEquals(0, sheet1.getPhysicalNumberOfRows()); - assertEquals(0, sheet1.getFirstRowNum()); - assertEquals(0, sheet1.getLastRowNum()); - - Row row0 = sheet1.createRow(0); - assertEquals(1, sheet1.getPhysicalNumberOfRows()); - assertEquals(0, sheet1.getFirstRowNum()); - assertEquals(0, sheet1.getLastRowNum()); - sheet1.removeRow(row0); - assertEquals(0, sheet1.getPhysicalNumberOfRows()); - assertEquals(0, sheet1.getFirstRowNum()); - assertEquals(0, sheet1.getLastRowNum()); - - sheet1.createRow(1); - Row row2 = sheet1.createRow(2); - assertEquals(2, sheet1.getPhysicalNumberOfRows()); - assertEquals(1, sheet1.getFirstRowNum()); - assertEquals(2, sheet1.getLastRowNum()); - - assertNotNull(sheet1.getRow(1)); - assertNotNull(sheet1.getRow(2)); - sheet1.removeRow(row2); - assertNotNull(sheet1.getRow(1)); - assertNull(sheet1.getRow(2)); - assertEquals(1, sheet1.getPhysicalNumberOfRows()); - assertEquals(1, sheet1.getFirstRowNum()); - assertEquals(1, sheet1.getLastRowNum()); - - Row row3 = sheet1.createRow(3); - Sheet sheet2 = workbook.createSheet(); - - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Specified row does not belong to this sheet"); - sheet2.removeRow(row3); - - workbook.close(); - } - - @Test - public void cloneSheet() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - CreationHelper factory = workbook.getCreationHelper(); - Sheet sheet = workbook.createSheet("Test Clone"); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - Cell cell2 = row.createCell(1); - cell.setCellValue(factory.createRichTextString("clone_test")); - cell2.setCellFormula("SIN(1)"); - - Sheet clonedSheet = workbook.cloneSheet(0); - Row clonedRow = clonedSheet.getRow(0); - - //Check for a good clone - assertEquals(clonedRow.getCell(0).getRichStringCellValue().getString(), "clone_test"); - - //Check that the cells are not somehow linked - cell.setCellValue(factory.createRichTextString("Difference Check")); - cell2.setCellFormula("cos(2)"); - if ("Difference Check".equals(clonedRow.getCell(0).getRichStringCellValue().getString())) { - fail("string cell not properly cloned"); - } - if ("COS(2)".equals(clonedRow.getCell(1).getCellFormula())) { - fail("formula cell not properly cloned"); - } - assertEquals(clonedRow.getCell(0).getRichStringCellValue().getString(), "clone_test"); - assertEquals(clonedRow.getCell(1).getCellFormula(), "SIN(1)"); - - workbook.close(); - } - - /** tests that the sheet name for multiple clones of the same sheet is unique - * BUG 37416 - */ - @Test - public void cloneSheetMultipleTimes() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - CreationHelper factory = workbook.getCreationHelper(); - Sheet sheet = workbook.createSheet("Test Clone"); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - cell.setCellValue(factory.createRichTextString("clone_test")); - //Clone the sheet multiple times - workbook.cloneSheet(0); - workbook.cloneSheet(0); - - assertNotNull(workbook.getSheet("Test Clone")); - assertNotNull(workbook.getSheet("Test Clone (2)")); - assertEquals("Test Clone (3)", workbook.getSheetName(2)); - assertNotNull(workbook.getSheet("Test Clone (3)")); - - workbook.removeSheetAt(0); - workbook.removeSheetAt(0); - workbook.removeSheetAt(0); - workbook.createSheet("abc ( 123)"); - workbook.cloneSheet(0); - assertEquals("abc (124)", workbook.getSheetName(1)); - - workbook.close(); - } - - /** - * Setting landscape and portrait stuff on new sheets - */ - @Test - public void printSetupLandscapeNew() throws IOException { - Workbook wb1 = _testDataProvider.createWorkbook(); - Sheet sheetL = wb1.createSheet("LandscapeS"); - Sheet sheetP = wb1.createSheet("LandscapeP"); - - // Check two aspects of the print setup - assertFalse(sheetL.getPrintSetup().getLandscape()); - assertFalse(sheetP.getPrintSetup().getLandscape()); - assertEquals(1, sheetL.getPrintSetup().getCopies()); - assertEquals(1, sheetP.getPrintSetup().getCopies()); - - // Change one on each - sheetL.getPrintSetup().setLandscape(true); - sheetP.getPrintSetup().setCopies((short)3); - - // Check taken - assertTrue(sheetL.getPrintSetup().getLandscape()); - assertFalse(sheetP.getPrintSetup().getLandscape()); - assertEquals(1, sheetL.getPrintSetup().getCopies()); - assertEquals(3, sheetP.getPrintSetup().getCopies()); - - // Save and re-load, and check still there - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - wb1.close(); - sheetL = wb2.getSheet("LandscapeS"); - sheetP = wb2.getSheet("LandscapeP"); - - assertTrue(sheetL.getPrintSetup().getLandscape()); - assertFalse(sheetP.getPrintSetup().getLandscape()); - assertEquals(1, sheetL.getPrintSetup().getCopies()); - assertEquals(3, sheetP.getPrintSetup().getCopies()); - wb2.close(); - } - - /** - * Disallow creating wholly or partially overlapping merged regions - * as this results in a corrupted workbook - */ - @Test - public void addOverlappingMergedRegions() throws IOException { - final Workbook wb = _testDataProvider.createWorkbook(); - final Sheet sheet = wb.createSheet(); - - final CellRangeAddress baseRegion = new CellRangeAddress(0, 1, 0, 1); //A1:B2 - sheet.addMergedRegion(baseRegion); - - try { - final CellRangeAddress duplicateRegion = new CellRangeAddress(0, 1, 0, 1); //A1:B2 - sheet.addMergedRegion(duplicateRegion); - fail("Should not be able to add a merged region (" + duplicateRegion.formatAsString() + ") " + - "if sheet already contains the same merged region (" + baseRegion.formatAsString() + ")"); - } catch (final IllegalStateException e) { - // expected here - } - - try { - final CellRangeAddress partiallyOverlappingRegion = new CellRangeAddress(1, 2, 1, 2); //B2:C3 - sheet.addMergedRegion(partiallyOverlappingRegion); - fail("Should not be able to add a merged region (" + partiallyOverlappingRegion.formatAsString() + ") " + - "if it partially overlaps with an existing merged region (" + baseRegion.formatAsString() + ")"); - } catch (final IllegalStateException e) { - // expected here - } - - try { - final CellRangeAddress subsetRegion = new CellRangeAddress(0, 1, 0, 0); //A1:A2 - sheet.addMergedRegion(subsetRegion); - fail("Should not be able to add a merged region (" + subsetRegion.formatAsString() + ") " + - "if it is a formal subset of an existing merged region (" + baseRegion.formatAsString() + ")"); - } catch (final IllegalStateException e) { - // expected here - } - - try { - final CellRangeAddress supersetRegion = new CellRangeAddress(0, 2, 0, 2); //A1:C3 - sheet.addMergedRegion(supersetRegion); - fail("Should not be able to add a merged region (" + supersetRegion.formatAsString() + ") " + - "if it is a formal superset of an existing merged region (" + baseRegion.formatAsString() + ")"); - } catch (final IllegalStateException e) { - // expected here - } - - final CellRangeAddress disjointRegion = new CellRangeAddress(10, 11, 10, 11); - sheet.addMergedRegion(disjointRegion); - - wb.close(); - } - - /* - * Bug 56345: Reject single-cell merged regions - */ - @Test - public void addMergedRegionWithSingleCellShouldFail() throws IOException { - final Workbook wb = _testDataProvider.createWorkbook(); - - final Sheet sheet = wb.createSheet(); - final CellRangeAddress region = CellRangeAddress.valueOf("A1:A1"); - try { - sheet.addMergedRegion(region); - fail("Should not be able to add a single-cell merged region (" + region.formatAsString() + ")"); - } catch (final IllegalArgumentException e) { - // expected - } - wb.close(); - } - - /** - * Test adding merged regions. If the region's bounds are outside of the allowed range - * then an IllegalArgumentException should be thrown - * - */ - @Test - public void addMerged() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet(); - assertEquals(0, sheet.getNumMergedRegions()); - SpreadsheetVersion ssVersion = _testDataProvider.getSpreadsheetVersion(); - - CellRangeAddress region = new CellRangeAddress(0, 1, 0, 1); - sheet.addMergedRegion(region); - assertEquals(1, sheet.getNumMergedRegions()); - - try { - region = new CellRangeAddress(-1, -1, -1, -1); - sheet.addMergedRegion(region); - fail("Expected exception"); - } catch (IllegalArgumentException e){ - // TODO: assertEquals("Minimum row number is 0.", e.getMessage()); - } - try { - region = new CellRangeAddress(0, 0, 0, ssVersion.getLastColumnIndex() + 1); - sheet.addMergedRegion(region); - fail("Expected exception"); - } catch (IllegalArgumentException e){ - assertEquals("Maximum column number is " + ssVersion.getLastColumnIndex(), e.getMessage()); - } - try { - region = new CellRangeAddress(0, ssVersion.getLastRowIndex() + 1, 0, 1); - sheet.addMergedRegion(region); - fail("Expected exception"); - } catch (IllegalArgumentException e){ - assertEquals("Maximum row number is " + ssVersion.getLastRowIndex(), e.getMessage()); - } - assertEquals(1, sheet.getNumMergedRegions()); - - wb.close(); - } - - /** - * When removing one merged region, it would break - * - */ - @Test - public void removeMerged() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet(); - CellRangeAddress region = new CellRangeAddress(0, 1, 0, 1); - sheet.addMergedRegion(region); - region = new CellRangeAddress(2, 3, 0, 1); - sheet.addMergedRegion(region); - - sheet.removeMergedRegion(0); - - region = sheet.getMergedRegion(0); - assertEquals("Left over region should be starting at row 2", 2, region.getFirstRow()); - - sheet.removeMergedRegion(0); - - assertEquals("there should be no merged regions left!", 0, sheet.getNumMergedRegions()); - - //an, add, remove, get(0) would null pointer - sheet.addMergedRegion(region); - assertEquals("there should now be one merged region!", 1, sheet.getNumMergedRegions()); - sheet.removeMergedRegion(0); - assertEquals("there should now be zero merged regions!", 0, sheet.getNumMergedRegions()); - //add it again! - region.setLastRow(4); - - sheet.addMergedRegion(region); - assertEquals("there should now be one merged region!", 1, sheet.getNumMergedRegions()); - - //should exist now! - assertTrue("there isn't more than one merged region in there", 1 <= sheet.getNumMergedRegions()); - region = sheet.getMergedRegion(0); - assertEquals("the merged row to doesnt match the one we put in ", 4, region.getLastRow()); - - wb.close(); - } - - /** - * Remove multiple merged regions - */ - @Test - public void removeMergedRegions() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet(); - - Map mergedRegions = new HashMap(); - for (int r=0; r<10; r++) { - CellRangeAddress region = new CellRangeAddress(r, r, 0, 1); - mergedRegions.put(r, region); - sheet.addMergedRegion(region); - } - assertCollectionEquals(mergedRegions.values(), sheet.getMergedRegions()); - - Collection removed = Arrays.asList(0, 2, 3, 6, 8); - mergedRegions.keySet().removeAll(removed); - sheet.removeMergedRegions(removed); - assertCollectionEquals(mergedRegions.values(), sheet.getMergedRegions()); - - wb.close(); - } - - private static void assertCollectionEquals(Collection expected, Collection actual) { - Set e = new HashSet(expected); - Set a = new HashSet(actual); - assertEquals(e, a); - } - - @Test - public void shiftMerged() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - CreationHelper factory = wb.getCreationHelper(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - cell.setCellValue(factory.createRichTextString("first row, first cell")); - - row = sheet.createRow(1); - cell = row.createCell(1); - cell.setCellValue(factory.createRichTextString("second row, second cell")); - - CellRangeAddress region = CellRangeAddress.valueOf("A2:B2"); - sheet.addMergedRegion(region); - - sheet.shiftRows(1, 1, 1); - - region = sheet.getMergedRegion(0); - - CellRangeAddress expectedRegion = CellRangeAddress.valueOf("A3:B3"); - assertEquals("Merged region should shift down a row", expectedRegion, region); - - wb.close(); - } - - /** - * bug 58885: checking for overlapping merged regions when - * adding a merged region is safe, but runs in O(n). - * the check for merged regions when adding a merged region - * can be skipped (unsafe) and run in O(1). - */ - @Test - public void addMergedRegionUnsafe() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sh = wb.createSheet(); - CellRangeAddress region1 = CellRangeAddress.valueOf("A1:B2"); - CellRangeAddress region2 = CellRangeAddress.valueOf("B2:C3"); - CellRangeAddress region3 = CellRangeAddress.valueOf("C3:D4"); - CellRangeAddress region4 = CellRangeAddress.valueOf("J10:K11"); - assumeTrue(region1.intersects(region2)); - assumeTrue(region2.intersects(region3)); - - sh.addMergedRegionUnsafe(region1); - assertTrue(sh.getMergedRegions().contains(region1)); - - // adding a duplicate or overlapping merged region should not - // raise an exception with the unsafe version of addMergedRegion. - - sh.addMergedRegionUnsafe(region2); - - // the safe version of addMergedRegion should throw when trying to add a merged region that overlaps an existing region - assertTrue(sh.getMergedRegions().contains(region2)); - try { - sh.addMergedRegion(region3); - fail("Expected IllegalStateException. region3 overlaps already added merged region2."); - } catch (final IllegalStateException e) { - // expected - assertFalse(sh.getMergedRegions().contains(region3)); - } - // addMergedRegion should not re-validate previously-added merged regions - sh.addMergedRegion(region4); - - // validation methods should detect a problem with previously added merged regions (runs in O(n^2) time) - try { - sh.validateMergedRegions(); - fail("Expected validation to fail. Sheet contains merged regions A1:B2 and B2:C3, which overlap at B2."); - } catch (final IllegalStateException e) { - // expected - } - - wb.close(); - } - - /** - * Tests the display of gridlines, formulas, and rowcolheadings. - */ - @Test - public void displayOptions() throws IOException { - Workbook wb1 = _testDataProvider.createWorkbook(); - Sheet sheet = wb1.createSheet(); - - assertEquals(sheet.isDisplayGridlines(), true); - assertEquals(sheet.isDisplayRowColHeadings(), true); - assertEquals(sheet.isDisplayFormulas(), false); - assertEquals(sheet.isDisplayZeros(), true); - - sheet.setDisplayGridlines(false); - sheet.setDisplayRowColHeadings(false); - sheet.setDisplayFormulas(true); - sheet.setDisplayZeros(false); - - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - wb1.close(); - sheet = wb2.getSheetAt(0); - - assertEquals(sheet.isDisplayGridlines(), false); - assertEquals(sheet.isDisplayRowColHeadings(), false); - assertEquals(sheet.isDisplayFormulas(), true); - assertEquals(sheet.isDisplayZeros(), false); - - wb2.close(); - } - - @Test - public void columnWidth() throws IOException { - Workbook wb1 = _testDataProvider.createWorkbook(); - Sheet sheet = wb1.createSheet(); - - //default column width measured in characters - sheet.setDefaultColumnWidth(10); - assertEquals(10, sheet.getDefaultColumnWidth()); - //columns A-C have default width - assertEquals(256*10, sheet.getColumnWidth(0)); - assertEquals(256*10, sheet.getColumnWidth(1)); - assertEquals(256*10, sheet.getColumnWidth(2)); - - //set custom width for D-F - for (char i = 'D'; i <= 'F'; i++) { - //Sheet#setColumnWidth accepts the width in units of 1/256th of a character width - int w = 256*12; - sheet.setColumnWidth(i, w); - assertEquals(w, sheet.getColumnWidth(i)); - } - //reset the default column width, columns A-C change, D-F still have custom width - sheet.setDefaultColumnWidth(20); - assertEquals(20, sheet.getDefaultColumnWidth()); - assertEquals(256*20, sheet.getColumnWidth(0)); - assertEquals(256*20, sheet.getColumnWidth(1)); - assertEquals(256*20, sheet.getColumnWidth(2)); - for (char i = 'D'; i <= 'F'; i++) { - int w = 256*12; - assertEquals(w, sheet.getColumnWidth(i)); - } - - // check for 16-bit signed/unsigned error: - sheet.setColumnWidth(10, 40000); - assertEquals(40000, sheet.getColumnWidth(10)); - - //The maximum column width for an individual cell is 255 characters - try { - sheet.setColumnWidth(9, 256*256); - fail("expected exception"); - } catch(IllegalArgumentException e){ - assertEquals("The maximum column width for an individual cell is 255 characters.", e.getMessage()); - } - - //serialize and read again - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - wb1.close(); - - sheet = wb2.getSheetAt(0); - assertEquals(20, sheet.getDefaultColumnWidth()); - //columns A-C have default width - assertEquals(256*20, sheet.getColumnWidth(0)); - assertEquals(256*20, sheet.getColumnWidth(1)); - assertEquals(256*20, sheet.getColumnWidth(2)); - //columns D-F have custom width - for (char i = 'D'; i <= 'F'; i++) { - short w = (256*12); - assertEquals(w, sheet.getColumnWidth(i)); - } - assertEquals(40000, sheet.getColumnWidth(10)); - - wb2.close(); - } - - - @Test - public void defaultRowHeight() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet(); - sheet.setDefaultRowHeightInPoints(15); - assertEquals((short) 300, sheet.getDefaultRowHeight()); - assertEquals(15.0F, sheet.getDefaultRowHeightInPoints(), 0F); - - Row row = sheet.createRow(1); - // new row inherits default height from the sheet - assertEquals(sheet.getDefaultRowHeight(), row.getHeight()); - - // Set a new default row height in twips and test getting the value in points - sheet.setDefaultRowHeight((short) 360); - assertEquals(18.0f, sheet.getDefaultRowHeightInPoints(), 0F); - assertEquals((short) 360, sheet.getDefaultRowHeight()); - - // Test that defaultRowHeight is a truncated short: E.G. 360inPoints -> 18; 361inPoints -> 18 - sheet.setDefaultRowHeight((short) 361); - assertEquals((float)361/20, sheet.getDefaultRowHeightInPoints(), 0F); - assertEquals((short) 361, sheet.getDefaultRowHeight()); - - // Set a new default row height in points and test getting the value in twips - sheet.setDefaultRowHeightInPoints(17.5f); - assertEquals(17.5f, sheet.getDefaultRowHeightInPoints(), 0F); - assertEquals((short)(17.5f*20), sheet.getDefaultRowHeight()); - - workbook.close(); - } - - /** cell with formula becomes null on cloning a sheet*/ - @Test - public void bug35084() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet s = wb.createSheet("Sheet1"); - Row r = s.createRow(0); - r.createCell(0).setCellValue(1); - r.createCell(1).setCellFormula("A1*2"); - Sheet s1 = wb.cloneSheet(0); - r = s1.getRow(0); - assertEquals("double", r.getCell(0).getNumericCellValue(), 1, 0); // sanity check - assertNotNull(r.getCell(1)); - assertEquals("formula", r.getCell(1).getCellFormula(), "A1*2"); - wb.close(); - } - - /** test that new default column styles get applied */ - @Test - public void defaultColumnStyle() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - CellStyle style = wb.createCellStyle(); - Sheet sheet = wb.createSheet(); - sheet.setDefaultColumnStyle(0, style); - assertNotNull(sheet.getColumnStyle(0)); - assertEquals(style.getIndex(), sheet.getColumnStyle(0).getIndex()); - - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - CellStyle style2 = cell.getCellStyle(); - assertNotNull(style2); - assertEquals("style should match", style.getIndex(), style2.getIndex()); - wb.close(); - } - - @Test - public void outlineProperties() throws IOException { - Workbook wb1 = _testDataProvider.createWorkbook(); - - Sheet sheet = wb1.createSheet(); - - //TODO defaults are different in HSSF and XSSF - //assertTrue(sheet.getRowSumsBelow()); - //assertTrue(sheet.getRowSumsRight()); - - sheet.setRowSumsBelow(false); - sheet.setRowSumsRight(false); - - assertFalse(sheet.getRowSumsBelow()); - assertFalse(sheet.getRowSumsRight()); - - sheet.setRowSumsBelow(true); - sheet.setRowSumsRight(true); - - assertTrue(sheet.getRowSumsBelow()); - assertTrue(sheet.getRowSumsRight()); - - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - wb1.close(); - sheet = wb2.getSheetAt(0); - assertTrue(sheet.getRowSumsBelow()); - assertTrue(sheet.getRowSumsRight()); - wb2.close(); - } - - /** - * Test basic display and print properties - */ - @Test - public void sheetProperties() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet(); - - assertFalse(sheet.getHorizontallyCenter()); - sheet.setHorizontallyCenter(true); - assertTrue(sheet.getHorizontallyCenter()); - sheet.setHorizontallyCenter(false); - assertFalse(sheet.getHorizontallyCenter()); - - assertFalse(sheet.getVerticallyCenter()); - sheet.setVerticallyCenter(true); - assertTrue(sheet.getVerticallyCenter()); - sheet.setVerticallyCenter(false); - assertFalse(sheet.getVerticallyCenter()); - - assertFalse(sheet.isPrintGridlines()); - sheet.setPrintGridlines(true); - assertTrue(sheet.isPrintGridlines()); - - assertFalse(sheet.isPrintRowAndColumnHeadings()); - sheet.setPrintRowAndColumnHeadings(true); - assertTrue(sheet.isPrintRowAndColumnHeadings()); - - assertFalse(sheet.isDisplayFormulas()); - sheet.setDisplayFormulas(true); - assertTrue(sheet.isDisplayFormulas()); - - assertTrue(sheet.isDisplayGridlines()); - sheet.setDisplayGridlines(false); - assertFalse(sheet.isDisplayGridlines()); - - //TODO: default "guts" is different in HSSF and XSSF - //assertTrue(sheet.getDisplayGuts()); - sheet.setDisplayGuts(false); - assertFalse(sheet.getDisplayGuts()); - - assertTrue(sheet.isDisplayRowColHeadings()); - sheet.setDisplayRowColHeadings(false); - assertFalse(sheet.isDisplayRowColHeadings()); - - //TODO: default "autobreaks" is different in HSSF and XSSF - //assertTrue(sheet.getAutobreaks()); - sheet.setAutobreaks(false); - assertFalse(sheet.getAutobreaks()); - - assertFalse(sheet.getScenarioProtect()); - - //TODO: default "fit-to-page" is different in HSSF and XSSF - //assertFalse(sheet.getFitToPage()); - sheet.setFitToPage(true); - assertTrue(sheet.getFitToPage()); - sheet.setFitToPage(false); - assertFalse(sheet.getFitToPage()); - - wb.close(); - } - - public void baseTestGetSetMargin(double[] defaultMargins) throws IOException { - double marginLeft = defaultMargins[0]; - double marginRight = defaultMargins[1]; - double marginTop = defaultMargins[2]; - double marginBottom = defaultMargins[3]; - //double marginHeader = defaultMargins[4]; - //double marginFooter = defaultMargins[5]; - - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet("Sheet 1"); - assertEquals(marginLeft, sheet.getMargin(Sheet.LeftMargin), 0.0); - sheet.setMargin(Sheet.LeftMargin, 10.0); - //left margin is custom, all others are default - assertEquals(10.0, sheet.getMargin(Sheet.LeftMargin), 0.0); - assertEquals(marginRight, sheet.getMargin(Sheet.RightMargin), 0.0); - assertEquals(marginTop, sheet.getMargin(Sheet.TopMargin), 0.0); - assertEquals(marginBottom, sheet.getMargin(Sheet.BottomMargin), 0.0); - sheet.setMargin(Sheet.RightMargin, 11.0); - assertEquals(11.0, sheet.getMargin(Sheet.RightMargin), 0.0); - sheet.setMargin(Sheet.TopMargin, 12.0); - assertEquals(12.0, sheet.getMargin(Sheet.TopMargin), 0.0); - sheet.setMargin(Sheet.BottomMargin, 13.0); - assertEquals(13.0, sheet.getMargin(Sheet.BottomMargin), 0.0); - - sheet.setMargin(Sheet.FooterMargin, 5.6); - assertEquals(5.6, sheet.getMargin(Sheet.FooterMargin), 0.0); - sheet.setMargin(Sheet.HeaderMargin, 11.5); - assertEquals(11.5, sheet.getMargin(Sheet.HeaderMargin), 0.0); - - // incorrect margin constant - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Unknown margin constant: 65"); - sheet.setMargin((short) 65, 15); - - workbook.close(); - } - - @Test - public void rowBreaks() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet(); - //Sheet#getRowBreaks() returns an empty array if no row breaks are defined - assertNotNull(sheet.getRowBreaks()); - assertEquals(0, sheet.getRowBreaks().length); - - sheet.setRowBreak(1); - assertEquals(1, sheet.getRowBreaks().length); - sheet.setRowBreak(15); - assertEquals(2, sheet.getRowBreaks().length); - assertEquals(1, sheet.getRowBreaks()[0]); - assertEquals(15, sheet.getRowBreaks()[1]); - sheet.setRowBreak(1); - assertEquals(2, sheet.getRowBreaks().length); - assertTrue(sheet.isRowBroken(1)); - assertTrue(sheet.isRowBroken(15)); - - //now remove the created breaks - sheet.removeRowBreak(1); - assertEquals(1, sheet.getRowBreaks().length); - sheet.removeRowBreak(15); - assertEquals(0, sheet.getRowBreaks().length); - - assertFalse(sheet.isRowBroken(1)); - assertFalse(sheet.isRowBroken(15)); - - workbook.close(); - } - - @Test - public void columnBreaks() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet(); - assertNotNull(sheet.getColumnBreaks()); - assertEquals(0, sheet.getColumnBreaks().length); - - assertFalse(sheet.isColumnBroken(0)); - - sheet.setColumnBreak(11); - assertNotNull(sheet.getColumnBreaks()); - assertEquals(11, sheet.getColumnBreaks()[0]); - sheet.setColumnBreak(12); - assertEquals(2, sheet.getColumnBreaks().length); - assertTrue(sheet.isColumnBroken(11)); - assertTrue(sheet.isColumnBroken(12)); - - sheet.removeColumnBreak((short) 11); - assertEquals(1, sheet.getColumnBreaks().length); - sheet.removeColumnBreak((short) 15); //remove non-existing - assertEquals(1, sheet.getColumnBreaks().length); - sheet.removeColumnBreak((short) 12); - assertEquals(0, sheet.getColumnBreaks().length); - - assertFalse(sheet.isColumnBroken(11)); - assertFalse(sheet.isColumnBroken(12)); - workbook.close(); - } - - @Test - public void getFirstLastRowNum() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet("Sheet 1"); - sheet.createRow(9); - sheet.createRow(0); - sheet.createRow(1); - assertEquals(0, sheet.getFirstRowNum()); - assertEquals(9, sheet.getLastRowNum()); - workbook.close(); - } - - @Test - public void getFooter() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet("Sheet 1"); - assertNotNull(sheet.getFooter()); - sheet.getFooter().setCenter("test center footer"); - assertEquals("test center footer", sheet.getFooter().getCenter()); - workbook.close(); - } - - @Test - public void getSetColumnHidden() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet("Sheet 1"); - sheet.setColumnHidden(2, true); - assertTrue(sheet.isColumnHidden(2)); - workbook.close(); - } - - @Test - public void protectSheet() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet(); - assertFalse(sheet.getProtect()); - sheet.protectSheet("Test"); - assertTrue(sheet.getProtect()); - sheet.protectSheet(null); - assertFalse(sheet.getProtect()); - wb.close(); - } - - @Test - public void createFreezePane() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - // create a workbook - Sheet sheet = wb.createSheet(); - assertNull(sheet.getPaneInformation()); - sheet.createFreezePane(0, 0); - // still null - assertNull(sheet.getPaneInformation()); - - sheet.createFreezePane(2, 3); - - PaneInformation info = sheet.getPaneInformation(); - - - assertEquals(PaneInformation.PANE_LOWER_RIGHT, info.getActivePane()); - assertEquals(3, info.getHorizontalSplitPosition()); - assertEquals(3, info.getHorizontalSplitTopRow()); - assertEquals(2, info.getVerticalSplitLeftColumn()); - assertEquals(2, info.getVerticalSplitPosition()); - - sheet.createFreezePane(0, 0); - // If both colSplit and rowSplit are zero then the existing freeze pane is removed - assertNull(sheet.getPaneInformation()); - - sheet.createFreezePane(0, 3); - - info = sheet.getPaneInformation(); - - assertEquals(PaneInformation.PANE_LOWER_LEFT, info.getActivePane()); - assertEquals(3, info.getHorizontalSplitPosition()); - assertEquals(3, info.getHorizontalSplitTopRow()); - assertEquals(0, info.getVerticalSplitLeftColumn()); - assertEquals(0, info.getVerticalSplitPosition()); - - sheet.createFreezePane(3, 0); - - info = sheet.getPaneInformation(); - - assertEquals(PaneInformation.PANE_UPPER_RIGHT, info.getActivePane()); - assertEquals(0, info.getHorizontalSplitPosition()); - assertEquals(0, info.getHorizontalSplitTopRow()); - assertEquals(3, info.getVerticalSplitLeftColumn()); - assertEquals(3, info.getVerticalSplitPosition()); - - sheet.createFreezePane(0, 0); - // If both colSplit and rowSplit are zero then the existing freeze pane is removed - assertNull(sheet.getPaneInformation()); - - wb.close(); - } - - - @Test - public void getRepeatingRowsAndColumns() throws IOException { - Workbook wb = _testDataProvider.openSampleWorkbook( - "RepeatingRowsCols." - + _testDataProvider.getStandardFileNameExtension()); - - checkRepeatingRowsAndColumns(wb.getSheetAt(0), null, null); - checkRepeatingRowsAndColumns(wb.getSheetAt(1), "1:1", null); - checkRepeatingRowsAndColumns(wb.getSheetAt(2), null, "A:A"); - checkRepeatingRowsAndColumns(wb.getSheetAt(3), "2:3", "A:B"); - wb.close(); - } - - - @Test - public void setRepeatingRowsAndColumnsBug47294() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet1 = wb.createSheet(); - sheet1.setRepeatingRows(CellRangeAddress.valueOf("1:4")); - assertEquals("1:4", sheet1.getRepeatingRows().formatAsString()); - - //must handle sheets with quotas, see Bugzilla #47294 - Sheet sheet2 = wb.createSheet("My' Sheet"); - sheet2.setRepeatingRows(CellRangeAddress.valueOf("1:4")); - assertEquals("1:4", sheet2.getRepeatingRows().formatAsString()); - wb.close(); - } - - @Test - public void setRepeatingRowsAndColumns() throws IOException { - Workbook wb1 = _testDataProvider.createWorkbook(); - Sheet sheet1 = wb1.createSheet("Sheet1"); - Sheet sheet2 = wb1.createSheet("Sheet2"); - Sheet sheet3 = wb1.createSheet("Sheet3"); - - checkRepeatingRowsAndColumns(sheet1, null, null); - - sheet1.setRepeatingRows(CellRangeAddress.valueOf("4:5")); - sheet2.setRepeatingColumns(CellRangeAddress.valueOf("A:C")); - sheet3.setRepeatingRows(CellRangeAddress.valueOf("1:4")); - sheet3.setRepeatingColumns(CellRangeAddress.valueOf("A:A")); - - checkRepeatingRowsAndColumns(sheet1, "4:5", null); - checkRepeatingRowsAndColumns(sheet2, null, "A:C"); - checkRepeatingRowsAndColumns(sheet3, "1:4", "A:A"); - - // write out, read back, and test refrain... - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - wb1.close(); - sheet1 = wb2.getSheetAt(0); - sheet2 = wb2.getSheetAt(1); - sheet3 = wb2.getSheetAt(2); - - checkRepeatingRowsAndColumns(sheet1, "4:5", null); - checkRepeatingRowsAndColumns(sheet2, null, "A:C"); - checkRepeatingRowsAndColumns(sheet3, "1:4", "A:A"); - - // check removing repeating rows and columns - sheet3.setRepeatingRows(null); - checkRepeatingRowsAndColumns(sheet3, null, "A:A"); - - sheet3.setRepeatingColumns(null); - checkRepeatingRowsAndColumns(sheet3, null, null); - wb2.close(); - } - - private void checkRepeatingRowsAndColumns( - Sheet s, String expectedRows, String expectedCols) { - if (expectedRows == null) { - assertNull(s.getRepeatingRows()); - } else { - assertEquals(expectedRows, s.getRepeatingRows().formatAsString()); - } - if (expectedCols == null) { - assertNull(s.getRepeatingColumns()); - } else { - assertEquals(expectedCols, s.getRepeatingColumns().formatAsString()); - } - } - - @Test - public void baseZoom() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet(); - - // here we can only verify that setting some zoom values works, range-checking is different between the implementations - sheet.setZoom(75); - wb.close(); - } - - @Test - public void baseShowInPane() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet(); - sheet.showInPane(2, 3); - wb.close(); - } - - @Test - public void bug55723() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet(); - - CellRangeAddress range = CellRangeAddress.valueOf("A:B"); - AutoFilter filter = sheet.setAutoFilter(range); - assertNotNull(filter); - // there seems to be currently no generic way to check the setting... - - range = CellRangeAddress.valueOf("B:C"); - filter = sheet.setAutoFilter(range); - assertNotNull(filter); - // there seems to be currently no generic way to check the setting... - wb.close(); - } - - @Test - public void bug55723_Rows() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet(); - - CellRangeAddress range = CellRangeAddress.valueOf("A4:B55000"); - AutoFilter filter = sheet.setAutoFilter(range); - assertNotNull(filter); - - wb.close(); - } - - @Test - public void bug55723d_RowsOver65k() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet(); - - CellRangeAddress range = CellRangeAddress.valueOf("A4:B75000"); - AutoFilter filter = sheet.setAutoFilter(range); - assertNotNull(filter); - - wb.close(); - } - - /** - * XSSFSheet autoSizeColumn() on empty RichTextString fails - */ - @Test - public void bug48325() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet("Test"); - trackColumnsForAutoSizingIfSXSSF(sheet); - CreationHelper factory = wb.getCreationHelper(); - - Row row = sheet.createRow(0); - Cell cell = row.createCell(0); - - Font font = wb.createFont(); - RichTextString rts = factory.createRichTextString(""); - rts.applyFont(font); - cell.setCellValue(rts); - - sheet.autoSizeColumn(0); - - assertNotNull(_testDataProvider.writeOutAndReadBack(wb)); - - wb.close(); - } - - @Test - public void getCellComment() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet(); - Drawing dg = sheet.createDrawingPatriarch(); - Comment comment = dg.createCellComment(workbook.getCreationHelper().createClientAnchor()); - Cell cell = sheet.createRow(9).createCell(2); - comment.setAuthor("test C10 author"); - cell.setCellComment(comment); - - CellAddress ref = new CellAddress(9, 2); - assertNotNull(sheet.getCellComment(ref)); - assertEquals("test C10 author", sheet.getCellComment(ref).getAuthor()); - - assertNotNull(_testDataProvider.writeOutAndReadBack(workbook)); - - workbook.close(); - } - - - @Test - public void getCellComments() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet("TEST"); - - // a sheet with no cell comments should return an empty map (not null or raise NPE). - assertEquals(Collections.emptyMap(), sheet.getCellComments()); - - Drawing dg = sheet.createDrawingPatriarch(); - ClientAnchor anchor = workbook.getCreationHelper().createClientAnchor(); - - int nRows = 5; - int nCols = 6; - - for (int r=0; r=0; c--) { - // When the comment box is visible, have it show in a 1x3 space - anchor.setCol1(c); - anchor.setCol2(c); - anchor.setRow1(r); - anchor.setRow2(r); - - // Create the comment and set the text-author - Comment comment = dg.createCellComment(anchor); - Cell cell = sheet.getRow(r).createCell(c); - comment.setAuthor("Author " + r); - RichTextString text = workbook.getCreationHelper().createRichTextString("Test comment at row=" + r + ", column=" + c); - comment.setString(text); - - // Assign the comment to the cell - cell.setCellComment(comment); - } - } - - Workbook wb = _testDataProvider.writeOutAndReadBack(workbook); - Sheet sh = wb.getSheet("TEST"); - Map cellComments = sh.getCellComments(); - assertEquals(nRows*nCols, cellComments.size()); - - for (Entry e : cellComments.entrySet()) { - CellAddress ref = e.getKey(); - Comment aComment = e.getValue(); - assertEquals("Author " + ref.getRow(), aComment.getAuthor()); - String text = "Test comment at row=" + ref.getRow() + ", column=" + ref.getColumn(); - assertEquals(text, aComment.getString().getString()); - } - - workbook.close(); - wb.close(); - } - - @Test - public void getHyperlink() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - Hyperlink hyperlink = workbook.getCreationHelper().createHyperlink(HyperlinkType.URL); - hyperlink.setAddress("https://poi.apache.org/"); - - Sheet sheet = workbook.createSheet(); - Cell cell = sheet.createRow(5).createCell(1); - - assertEquals("list size before add", 0, sheet.getHyperlinkList().size()); - cell.setHyperlink(hyperlink); - assertEquals("list size after add", 1, sheet.getHyperlinkList().size()); - - assertEquals("list", hyperlink, sheet.getHyperlinkList().get(0)); - CellAddress B6 = new CellAddress(5, 1); - assertEquals("row, col", hyperlink, sheet.getHyperlink(5, 1)); - assertEquals("addr", hyperlink, sheet.getHyperlink(B6)); - assertEquals("no hyperlink at A1", null, sheet.getHyperlink(CellAddress.A1)); - - workbook.close(); - } - - @Test - public void removeAllHyperlinks() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - Hyperlink hyperlink = workbook.getCreationHelper().createHyperlink(HyperlinkType.URL); - hyperlink.setAddress("https://poi.apache.org/"); - Sheet sheet = workbook.createSheet(); - Cell cell = sheet.createRow(5).createCell(1); - cell.setHyperlink(hyperlink); - - assertEquals(1, workbook.getSheetAt(0).getHyperlinkList().size()); - // Save a workbook with a hyperlink - Workbook workbook2 = _testDataProvider.writeOutAndReadBack(workbook); - assertEquals(1, workbook2.getSheetAt(0).getHyperlinkList().size()); - - // Remove all hyperlinks from a saved workbook - workbook2.getSheetAt(0).getRow(5).getCell(1).removeHyperlink(); - assertEquals(0, workbook2.getSheetAt(0).getHyperlinkList().size()); - - // Verify that hyperlink was removed from workbook after writing out - Workbook workbook3 = _testDataProvider.writeOutAndReadBack(workbook2); - assertEquals(0, workbook3.getSheetAt(0).getHyperlinkList().size()); - } - - - @Test - public void newMergedRegionAt() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet(); - CellRangeAddress region = CellRangeAddress.valueOf("B2:D4"); - sheet.addMergedRegion(region); - assertEquals("B2:D4", sheet.getMergedRegion(0).formatAsString()); - assertEquals(1, sheet.getNumMergedRegions()); - - assertNotNull(_testDataProvider.writeOutAndReadBack(workbook)); - - workbook.close(); - } - - @Test - public void showInPaneManyRowsBug55248() throws IOException { - Workbook wb1 = _testDataProvider.createWorkbook(); - Sheet sheet = wb1.createSheet("Sheet 1"); - - sheet.showInPane(0, 0); - - for(int i = ROW_COUNT/2;i < ROW_COUNT;i++) { - sheet.createRow(i); - sheet.showInPane(i, 0); - // this one fails: sheet.showInPane((short)i, 0); - } - - int i = 0; - sheet.showInPane(i, i); - - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - checkRowCount(wb2); - - wb2.close(); - wb1.close(); - } - - private void checkRowCount(Workbook wb) { - assertNotNull(wb); - final Sheet sh = wb.getSheet("Sheet 1"); - assertNotNull(sh); - assertEquals(ROW_COUNT-1, sh.getLastRowNum()); - } - - - @Test - public void testRightToLeft() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet(); - - assertFalse(sheet.isRightToLeft()); - sheet.setRightToLeft(true); - assertTrue(sheet.isRightToLeft()); - sheet.setRightToLeft(false); - assertFalse(sheet.isRightToLeft()); - - wb.close(); - } - - @Test - public void testNoMergedRegionsIsEmptyList() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet(); - assertTrue(sheet.getMergedRegions().isEmpty()); - wb.close(); - } - - /** - * Tests that the setAsActiveCell and getActiveCell function pairs work together - */ - @Test - public void setActiveCell() throws IOException { - Workbook wb1 = _testDataProvider.createWorkbook(); - Sheet sheet = wb1.createSheet(); - CellAddress B42 = new CellAddress("B42"); - - // active cell behavior is undefined if not set. - // HSSFSheet defaults to A1 active cell, while XSSFSheet defaults to null. - if (sheet.getActiveCell() != null && !sheet.getActiveCell().equals(CellAddress.A1)) { - fail("If not set, active cell should default to null or A1"); - } - - sheet.setActiveCell(B42); - - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - - assertEquals(B42, sheet.getActiveCell()); - - wb1.close(); - wb2.close(); - } - - - @Test - public void autoSizeDate() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet s = wb.createSheet("Sheet1"); - Row r = s.createRow(0); - r.createCell(0).setCellValue(1); - r.createCell(1).setCellValue(123456); - - // for the streaming-variant we need to enable autosize-tracking to make it work - trackColumnsForAutoSizingIfSXSSF(s); - - // Will be sized fairly small - s.autoSizeColumn((short)0); - s.autoSizeColumn((short)1); - - // Size ranges due to different fonts on different machines - assertBetween("Single number column width", s.getColumnWidth(0), 350, 570); - assertBetween("6 digit number column width", s.getColumnWidth(1), 1500, 2100); - - // Set a date format - CellStyle cs = wb.createCellStyle(); - DataFormat f = wb.createDataFormat(); - cs.setDataFormat(f.getFormat("yyyy-mm-dd MMMM hh:mm:ss")); - r.getCell(0).setCellStyle(cs); - r.getCell(1).setCellStyle(cs); - - assertTrue(DateUtil.isCellDateFormatted(r.getCell(0))); - assertTrue(DateUtil.isCellDateFormatted(r.getCell(1))); - - // Should get much bigger now - s.autoSizeColumn((short)0); - s.autoSizeColumn((short)1); - - assertBetween("Date column width", s.getColumnWidth(0), 4750, 7300); - assertBetween("Date column width", s.getColumnWidth(1), 4750, 7300); - - wb.close(); - } -} diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetAutosizeColumn.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetAutosizeColumn.java deleted file mode 100644 index 92248698f..000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetAutosizeColumn.java +++ /dev/null @@ -1,366 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.util.Calendar; -import java.util.Locale; - -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.util.JvmBugs; -import org.apache.poi.util.LocaleUtil; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; - -/** - * Common superclass for testing automatic sizing of sheet columns - * - * @author Yegor Kozlov - */ -public abstract class BaseTestSheetAutosizeColumn { - - private final ITestDataProvider _testDataProvider; - - private static Locale userLocale; - - @BeforeClass - public static void initLocale() { - userLocale = LocaleUtil.getUserLocale(); - LocaleUtil.setUserLocale(Locale.ROOT); - } - - @AfterClass - public static void resetLocale() { - LocaleUtil.setUserLocale(userLocale); - } - - protected BaseTestSheetAutosizeColumn(ITestDataProvider testDataProvider) { - _testDataProvider = testDataProvider; - } - - protected void trackColumnsForAutoSizingIfSXSSF(Sheet sheet) { - // do nothing for Sheet base class. This will be overridden for SXSSFSheets. - } - - @Test - public void numericCells() throws Exception { - Workbook workbook = _testDataProvider.createWorkbook(); - fixFonts(workbook); - DataFormat df = workbook.getCreationHelper().createDataFormat(); - Sheet sheet = workbook.createSheet(); - trackColumnsForAutoSizingIfSXSSF(sheet); - - Row row = sheet.createRow(0); - row.createCell(0).setCellValue(0); // getCachedFormulaResult() returns 0 for not evaluated formula cells - row.createCell(1).setCellValue(10); - row.createCell(2).setCellValue("10"); - row.createCell(3).setCellFormula("(A1+B1)*1.0"); // a formula that returns '10' - - Cell cell4 = row.createCell(4); // numeric cell with a custom style - CellStyle style4 = workbook.createCellStyle(); - style4.setDataFormat(df.getFormat("0.0000")); - cell4.setCellStyle(style4); - cell4.setCellValue(10); // formatted as '10.0000' - - row.createCell(5).setCellValue("10.0000"); - - // autosize not-evaluated cells, formula cells are sized as if the result is 0 - for (int i = 0; i < 6; i++) sheet.autoSizeColumn(i); - - assertTrue(sheet.getColumnWidth(0) < sheet.getColumnWidth(1)); // width of '0' is less then width of '10' - assertEquals(sheet.getColumnWidth(1), sheet.getColumnWidth(2)); // 10 and '10' should be sized equally - assertEquals(sheet.getColumnWidth(3), sheet.getColumnWidth(0)); // formula result is unknown, the width is calculated for '0' - assertEquals(sheet.getColumnWidth(4), sheet.getColumnWidth(5)); // 10.0000 and '10.0000' - - // evaluate formulas and re-autosize - evaluateWorkbook(workbook); - - for (int i = 0; i < 6; i++) sheet.autoSizeColumn(i); - - assertTrue(sheet.getColumnWidth(0) < sheet.getColumnWidth(1)); // width of '0' is less then width of '10' - assertEquals(sheet.getColumnWidth(1), sheet.getColumnWidth(2)); // columns 1, 2 and 3 should have the same width - assertEquals(sheet.getColumnWidth(2), sheet.getColumnWidth(3)); // columns 1, 2 and 3 should have the same width - assertEquals(sheet.getColumnWidth(4), sheet.getColumnWidth(5)); // 10.0000 and '10.0000' - - workbook.close(); - } - - @Test - public void booleanCells() throws Exception { - Workbook workbook = _testDataProvider.createWorkbook(); - fixFonts(workbook); - Sheet sheet = workbook.createSheet(); - trackColumnsForAutoSizingIfSXSSF(sheet); - - Row row = sheet.createRow(0); - row.createCell(0).setCellValue(0); // getCachedFormulaResult() returns 0 for not evaluated formula cells - row.createCell(1).setCellValue(true); - row.createCell(2).setCellValue("TRUE"); - row.createCell(3).setCellFormula("1 > 0"); // a formula that returns true - - // autosize not-evaluated cells, formula cells are sized as if the result is 0 - for (int i = 0; i < 4; i++) sheet.autoSizeColumn(i); - - assertTrue(sheet.getColumnWidth(1) > sheet.getColumnWidth(0)); // 'true' is wider than '0' - assertEquals(sheet.getColumnWidth(1), sheet.getColumnWidth(2)); // 10 and '10' should be sized equally - assertEquals(sheet.getColumnWidth(3), sheet.getColumnWidth(0)); // formula result is unknown, the width is calculated for '0' - - // evaluate formulas and re-autosize - evaluateWorkbook(workbook); - - for (int i = 0; i < 4; i++) sheet.autoSizeColumn(i); - - assertTrue(sheet.getColumnWidth(1) > sheet.getColumnWidth(0)); // 'true' is wider than '0' - assertEquals(sheet.getColumnWidth(1), sheet.getColumnWidth(2)); // columns 1, 2 and 3 should have the same width - assertEquals(sheet.getColumnWidth(2), sheet.getColumnWidth(3)); // columns 1, 2 and 3 should have the same width - - workbook.close(); - } - - @Test - public void dateCells() throws Exception { - Workbook workbook = _testDataProvider.createWorkbook(); - fixFonts(workbook); - Sheet sheet = workbook.createSheet(); - trackColumnsForAutoSizingIfSXSSF(sheet); - DataFormat df = workbook.getCreationHelper().createDataFormat(); - - CellStyle style1 = workbook.createCellStyle(); - style1.setDataFormat(df.getFormat("m")); - - CellStyle style3 = workbook.createCellStyle(); - style3.setDataFormat(df.getFormat("mmm")); - - CellStyle style5 = workbook.createCellStyle(); //rotated text - style5.setDataFormat(df.getFormat("mmm/dd/yyyy")); - - Calendar calendar = LocaleUtil.getLocaleCalendar(2010, 0, 1); // Jan 1 2010 - - Row row = sheet.createRow(0); - row.createCell(0).setCellValue(DateUtil.getJavaDate(0)); //default date - - Cell cell1 = row.createCell(1); - cell1.setCellValue(calendar); - cell1.setCellStyle(style1); - row.createCell(2).setCellValue("1"); // column 1 should be sized as '1' - - Cell cell3 = row.createCell(3); - cell3.setCellValue(calendar); - cell3.setCellStyle(style3); - row.createCell(4).setCellValue("Jan"); - - Cell cell5 = row.createCell(5); - cell5.setCellValue(calendar); - cell5.setCellStyle(style5); - row.createCell(6).setCellValue("Jan/01/2010"); - - Cell cell7 = row.createCell(7); - cell7.setCellFormula("DATE(2010,1,1)"); - cell7.setCellStyle(style3); // should be sized as 'Jan' - - // autosize not-evaluated cells, formula cells are sized as if the result is 0 - for (int i = 0; i < 8; i++) sheet.autoSizeColumn(i); - - assertEquals(sheet.getColumnWidth(2), sheet.getColumnWidth(1)); // date formatted as 'm' - assertTrue(sheet.getColumnWidth(3) > sheet.getColumnWidth(1)); // 'mmm' is wider than 'm' - assertEquals(sheet.getColumnWidth(4), sheet.getColumnWidth(3)); // date formatted as 'mmm' - assertTrue(sheet.getColumnWidth(5) > sheet.getColumnWidth(3)); // 'mmm/dd/yyyy' is wider than 'mmm' - assertEquals(sheet.getColumnWidth(6), sheet.getColumnWidth(5)); // date formatted as 'mmm/dd/yyyy' - - // YK: width of not-evaluated formulas that return data is not determined - // POI seems to conevert '0' to Excel date which is the beginng of the Excel's date system - - // evaluate formulas and re-autosize - evaluateWorkbook(workbook); - - for (int i = 0; i < 8; i++) sheet.autoSizeColumn(i); - - assertEquals(sheet.getColumnWidth(2), sheet.getColumnWidth(1)); // date formatted as 'm' - assertTrue(sheet.getColumnWidth(3) > sheet.getColumnWidth(1)); // 'mmm' is wider than 'm' - assertEquals(sheet.getColumnWidth(4), sheet.getColumnWidth(3)); // date formatted as 'mmm' - assertTrue(sheet.getColumnWidth(5) > sheet.getColumnWidth(3)); // 'mmm/dd/yyyy' is wider than 'mmm' - assertEquals(sheet.getColumnWidth(6), sheet.getColumnWidth(5)); // date formatted as 'mmm/dd/yyyy' - assertEquals(sheet.getColumnWidth(4), sheet.getColumnWidth(7)); // date formula formatted as 'mmm' - - workbook.close(); - } - - @Test - public void stringCells() throws Exception { - Workbook workbook = _testDataProvider.createWorkbook(); - fixFonts(workbook); - Sheet sheet = workbook.createSheet(); - trackColumnsForAutoSizingIfSXSSF(sheet); - Row row = sheet.createRow(0); - - Font defaultFont = workbook.getFontAt((short)0); - - CellStyle style1 = workbook.createCellStyle(); - Font font1 = workbook.createFont(); - font1.setFontHeight((short)(2*defaultFont.getFontHeight())); - style1.setFont(font1); - - row.createCell(0).setCellValue("x"); - row.createCell(1).setCellValue("xxxx"); - row.createCell(2).setCellValue("xxxxxxxxxxxx"); - row.createCell(3).setCellValue("Apache\nSoftware Foundation"); // the text is splitted into two lines - row.createCell(4).setCellValue("Software Foundation"); - - Cell cell5 = row.createCell(5); - cell5.setCellValue("Software Foundation"); - cell5.setCellStyle(style1); // same as in column 4 but the font is twice larger than the default font - - for (int i = 0; i < 10; i++) sheet.autoSizeColumn(i); - - assertTrue(2*sheet.getColumnWidth(0) < sheet.getColumnWidth(1)); // width is roughly proportional to the number of characters - assertTrue(2*sheet.getColumnWidth(1) < sheet.getColumnWidth(2)); - assertEquals(sheet.getColumnWidth(4), sheet.getColumnWidth(3)); - boolean ignoreFontSizeX2 = JvmBugs.hasLineBreakMeasurerBug(); - assertTrue(ignoreFontSizeX2 || sheet.getColumnWidth(5) > sheet.getColumnWidth(4)); //larger font results in a wider column width - - workbook.close(); - } - - @Test - public void rotatedText() throws Exception { - Workbook workbook = _testDataProvider.createWorkbook(); - fixFonts(workbook); - Sheet sheet = workbook.createSheet(); - trackColumnsForAutoSizingIfSXSSF(sheet); - Row row = sheet.createRow(0); - - CellStyle style1 = workbook.createCellStyle(); - style1.setRotation((short)90); - - Cell cell0 = row.createCell(0); - cell0.setCellValue("Apache Software Foundation"); - cell0.setCellStyle(style1); - - Cell cell1 = row.createCell(1); - cell1.setCellValue("Apache Software Foundation"); - - for (int i = 0; i < 2; i++) sheet.autoSizeColumn(i); - - int w0 = sheet.getColumnWidth(0); - int w1 = sheet.getColumnWidth(1); - - assertTrue(w0*5 < w1); // rotated text occupies at least five times less horizontal space than normal text - - workbook.close(); - } - - @Test - public void mergedCells() throws Exception { - Workbook workbook = _testDataProvider.createWorkbook(); - fixFonts(workbook); - Sheet sheet = workbook.createSheet(); - trackColumnsForAutoSizingIfSXSSF(sheet); - - Row row = sheet.createRow(0); - sheet.addMergedRegion(CellRangeAddress.valueOf("A1:B1")); - - Cell cell0 = row.createCell(0); - cell0.setCellValue("Apache Software Foundation"); - - int defaulWidth = sheet.getColumnWidth(0); - sheet.autoSizeColumn(0); - // column is unchanged if merged regions are ignored (Excel like behavior) - assertEquals(defaulWidth, sheet.getColumnWidth(0)); - - sheet.autoSizeColumn(0, true); - assertTrue(sheet.getColumnWidth(0) > defaulWidth); - - workbook.close(); - } - - - /** - * Auto-Sizing a column needs to work when we have rows - * passed the 32767 boundary. See bug #48079 - */ - @Test - public void largeRowNumbers() throws Exception { - Workbook workbook = _testDataProvider.createWorkbook(); - fixFonts(workbook); - Sheet sheet = workbook.createSheet(); - trackColumnsForAutoSizingIfSXSSF(sheet); - - Row r0 = sheet.createRow(0); - r0.createCell(0).setCellValue("I am ROW 0"); - Row r200 = sheet.createRow(200); - r200.createCell(0).setCellValue("I am ROW 200"); - - // This should work fine - sheet.autoSizeColumn(0); - - // Get close to 32767 - Row r32765 = sheet.createRow(32765); - r32765.createCell(0).setCellValue("Nearly there..."); - sheet.autoSizeColumn(0); - - // To it - Row r32767 = sheet.createRow(32767); - r32767.createCell(0).setCellValue("At the boundary"); - sheet.autoSizeColumn(0); - - // And passed it - Row r32768 = sheet.createRow(32768); - r32768.createCell(0).setCellValue("Passed"); - Row r32769 = sheet.createRow(32769); - r32769.createCell(0).setCellValue("More Passed"); - sheet.autoSizeColumn(0); - - // Long way passed - Row r60708 = sheet.createRow(60708); - r60708.createCell(0).setCellValue("Near the end"); - sheet.autoSizeColumn(0); - - workbook.close(); - } - - // TODO should we have this stuff in the FormulaEvaluator? - private void evaluateWorkbook(Workbook workbook){ - FormulaEvaluator eval = workbook.getCreationHelper().createFormulaEvaluator(); - for(int i=0; i < workbook.getNumberOfSheets(); i++) { - Sheet sheet = workbook.getSheetAt(i); - for (Row r : sheet) { - for (Cell c : r) { - if (c.getCellTypeEnum() == CellType.FORMULA){ - eval.evaluateFormulaCellEnum(c); - } - } - } - } - } - - protected static void fixFonts(Workbook workbook) { - if (!JvmBugs.hasLineBreakMeasurerBug()) return; - for (int i=workbook.getNumberOfFonts()-1; i>=0; i--) { - Font f = workbook.getFontAt((short)0); - if ("Calibri".equals(f.getFontName())) { - f.setFontName("Lucida Sans"); - } else if ("Cambria".equals(f.getFontName())) { - f.setFontName("Lucida Bright"); - } - } - } -} \ No newline at end of file diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetHiding.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetHiding.java deleted file mode 100644 index d7fe79c98..000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetHiding.java +++ /dev/null @@ -1,204 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.IOException; - -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.util.Removal; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public abstract class BaseTestSheetHiding { - - protected final ITestDataProvider _testDataProvider; - protected Workbook wbH; - protected Workbook wbU; - - private final String _file1, _file2; - - /** - * @param testDataProvider an object that provides test data in HSSF / specific way - */ - protected BaseTestSheetHiding(ITestDataProvider testDataProvider, - String file1, String file2) { - _testDataProvider = testDataProvider; - _file1 = file1; - _file2 = file2; - } - - @Before - public void setUp() { - wbH = _testDataProvider.openSampleWorkbook(_file1); - wbU = _testDataProvider.openSampleWorkbook(_file2); - } - - @After - public void teadDown() throws IOException { - wbH.close(); - wbU.close(); - } - - /** - * @deprecated 3.16 beta 2. Use {@link #testSheetVisibility()} instead. - * - * @throws IOException - */ - @Removal(version="3.18") - @Deprecated - @Test - public final void testSheetHiddenOld() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - wb.createSheet("MySheet"); - - assertFalse(wb.isSheetHidden(0)); - assertFalse(wb.isSheetVeryHidden(0)); - - wb.setSheetHidden(0, Workbook.SHEET_STATE_HIDDEN); - assertTrue(wb.isSheetHidden(0)); - assertFalse(wb.isSheetVeryHidden(0)); - - wb.setSheetHidden(0, Workbook.SHEET_STATE_VERY_HIDDEN); - assertFalse(wb.isSheetHidden(0)); - assertTrue(wb.isSheetVeryHidden(0)); - - wb.setSheetHidden(0, Workbook.SHEET_STATE_VISIBLE); - assertFalse(wb.isSheetHidden(0)); - assertFalse(wb.isSheetVeryHidden(0)); - - try { - wb.setSheetHidden(0, -1); - fail("expectd exception"); - } catch (IllegalArgumentException e){ - // ok - } - try { - wb.setSheetHidden(0, 3); - fail("expectd exception"); - } catch (IllegalArgumentException e){ - // ok - } - - wb.close(); - } - - @Test - public final void testSheetVisibility() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - wb.createSheet("MySheet"); - - assertFalse(wb.isSheetHidden(0)); - assertFalse(wb.isSheetVeryHidden(0)); - assertEquals(SheetVisibility.VISIBLE, wb.getSheetVisibility(0)); - - wb.setSheetVisibility(0, SheetVisibility.HIDDEN); - assertTrue(wb.isSheetHidden(0)); - assertFalse(wb.isSheetVeryHidden(0)); - assertEquals(SheetVisibility.HIDDEN, wb.getSheetVisibility(0)); - - wb.setSheetVisibility(0, SheetVisibility.VERY_HIDDEN); - assertFalse(wb.isSheetHidden(0)); - assertTrue(wb.isSheetVeryHidden(0)); - assertEquals(SheetVisibility.VERY_HIDDEN, wb.getSheetVisibility(0)); - - wb.setSheetVisibility(0, SheetVisibility.VISIBLE); - assertFalse(wb.isSheetHidden(0)); - assertFalse(wb.isSheetVeryHidden(0)); - assertEquals(SheetVisibility.VISIBLE, wb.getSheetVisibility(0)); - - wb.close(); - } - - /** - * Test that we get the right number of sheets, - * with the right text on them, no matter what - * the hidden flags are - */ - @Test - public void testTextSheets() { - // Both should have two sheets - assertEquals(2, wbH.getNumberOfSheets()); - assertEquals(2, wbU.getNumberOfSheets()); - - // All sheets should have one row - assertEquals(0, wbH.getSheetAt(0).getLastRowNum()); - assertEquals(0, wbH.getSheetAt(1).getLastRowNum()); - assertEquals(0, wbU.getSheetAt(0).getLastRowNum()); - assertEquals(0, wbU.getSheetAt(1).getLastRowNum()); - - // All rows should have one column - assertEquals(1, wbH.getSheetAt(0).getRow(0).getLastCellNum()); - assertEquals(1, wbH.getSheetAt(1).getRow(0).getLastCellNum()); - assertEquals(1, wbU.getSheetAt(0).getRow(0).getLastCellNum()); - assertEquals(1, wbU.getSheetAt(1).getRow(0).getLastCellNum()); - - // Text should be sheet based - assertEquals("Sheet1A1", wbH.getSheetAt(0).getRow(0).getCell(0).getRichStringCellValue().getString()); - assertEquals("Sheet2A1", wbH.getSheetAt(1).getRow(0).getCell(0).getRichStringCellValue().getString()); - assertEquals("Sheet1A1", wbU.getSheetAt(0).getRow(0).getCell(0).getRichStringCellValue().getString()); - assertEquals("Sheet2A1", wbU.getSheetAt(1).getRow(0).getCell(0).getRichStringCellValue().getString()); - } - - /** - * Check that we can get and set the hidden flags - * as expected - */ - @Test - public void testHideUnHideFlags() { - assertTrue(wbH.isSheetHidden(0)); - assertFalse(wbH.isSheetHidden(1)); - assertFalse(wbU.isSheetHidden(0)); - assertFalse(wbU.isSheetHidden(1)); - } - - /** - * Turn the sheet with none hidden into the one with - * one hidden - */ - @Test - public void testHide() throws IOException { - wbU.setSheetHidden(0, true); - assertTrue(wbU.isSheetHidden(0)); - assertFalse(wbU.isSheetHidden(1)); - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wbU); - assertTrue(wb2.isSheetHidden(0)); - assertFalse(wb2.isSheetHidden(1)); - wb2.close(); - } - - /** - * Turn the sheet with one hidden into the one with - * none hidden - */ - @Test - public void testUnHide() throws IOException { - wbH.setSheetHidden(0, false); - assertFalse(wbH.isSheetHidden(0)); - assertFalse(wbH.isSheetHidden(1)); - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wbH); - assertFalse(wb2.isSheetHidden(0)); - assertFalse(wb2.isSheetHidden(1)); - wb2.close(); - } -} \ No newline at end of file diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetShiftRows.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetShiftRows.java deleted file mode 100644 index 556e89b43..000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetShiftRows.java +++ /dev/null @@ -1,717 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import static org.apache.poi.POITestCase.skipTest; -import static org.apache.poi.POITestCase.testPassesNow; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.junit.Assume.assumeTrue; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import org.apache.poi.common.usermodel.HyperlinkType; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.ss.util.CellAddress; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.CellReference; -import org.junit.Ignore; -import org.junit.Test; - -/** - * Tests row shifting capabilities. - * - * @author Shawn Laubach (slaubach at apache dot com) - * @author Toshiaki Kamoshida (kamoshida.toshiaki at future dot co dot jp) - */ -public abstract class BaseTestSheetShiftRows { - - private final ITestDataProvider _testDataProvider; - - protected BaseTestSheetShiftRows(ITestDataProvider testDataProvider) { - _testDataProvider = testDataProvider; - } - - /** - * Tests the shiftRows function. Does three different shifts. - * After each shift, writes the workbook to file and reads back to - * check. This ensures that if some changes code that breaks - * writing or what not, they realize it. - */ - @Test - public final void testShiftRows() throws IOException { - // Read initial file in - String sampleName = "SimpleMultiCell." + _testDataProvider.getStandardFileNameExtension(); - Workbook wb1 = _testDataProvider.openSampleWorkbook(sampleName); - Sheet s = wb1.getSheetAt( 0 ); - - // Shift the second row down 1 and write to temp file - s.shiftRows( 1, 1, 1 ); - - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - wb1.close(); - - // Read from temp file and check the number of cells in each - // row (in original file each row was unique) - s = wb2.getSheetAt( 0 ); - - assertEquals(s.getRow(0).getPhysicalNumberOfCells(), 1); - confirmEmptyRow(s, 1); - assertEquals(s.getRow(2).getPhysicalNumberOfCells(), 2); - assertEquals(s.getRow(3).getPhysicalNumberOfCells(), 4); - assertEquals(s.getRow(4).getPhysicalNumberOfCells(), 5); - - // Shift rows 1-3 down 3 in the current one. This tests when - // 1 row is blank. Write to a another temp file - s.shiftRows( 0, 2, 3 ); - Workbook wb3 = _testDataProvider.writeOutAndReadBack(wb2); - wb2.close(); - - // Read and ensure things are where they should be - s = wb3.getSheetAt(0); - confirmEmptyRow(s, 0); - confirmEmptyRow(s, 1); - confirmEmptyRow(s, 2); - assertEquals(s.getRow(3).getPhysicalNumberOfCells(), 1); - confirmEmptyRow(s, 4); - assertEquals(s.getRow(5).getPhysicalNumberOfCells(), 2); - - wb3.close(); - - // Read the first file again - Workbook wb4 = _testDataProvider.openSampleWorkbook(sampleName); - s = wb4.getSheetAt( 0 ); - - // Shift rows 3 and 4 up and write to temp file - s.shiftRows( 2, 3, -2 ); - Workbook wb5 = _testDataProvider.writeOutAndReadBack(wb4); - wb4.close(); - s = wb5.getSheetAt( 0 ); - assertEquals(s.getRow(0).getPhysicalNumberOfCells(), 3); - assertEquals(s.getRow(1).getPhysicalNumberOfCells(), 4); - confirmEmptyRow(s, 2); - confirmEmptyRow(s, 3); - assertEquals(s.getRow(4).getPhysicalNumberOfCells(), 5); - wb5.close(); - } - private static void confirmEmptyRow(Sheet s, int rowIx) { - Row row = s.getRow(rowIx); - assertTrue(row == null || row.getPhysicalNumberOfCells() == 0); - } - - /** - * Tests when rows are null. - */ - @Test - public final void testShiftRow() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet s = wb.createSheet(); - s.createRow(0).createCell(0).setCellValue("TEST1"); - s.createRow(3).createCell(0).setCellValue("TEST2"); - s.shiftRows(0,4,1); - wb.close(); - } - - /** - * When shifting rows, the page breaks should go with it - */ - @Test - public void testShiftRowBreaks() throws IOException { // TODO - enable XSSF test - Workbook wb = _testDataProvider.createWorkbook(); - Sheet s = wb.createSheet(); - Row row = s.createRow(4); - row.createCell(0).setCellValue("test"); - s.setRowBreak(4); - - s.shiftRows(4, 4, 2); - assertTrue("Row number 6 should have a pagebreak", s.isRowBroken(6)); - wb.close(); - } - - @Test - public void testShiftWithComments() throws IOException { - Workbook wb1 = _testDataProvider.openSampleWorkbook("comments." + _testDataProvider.getStandardFileNameExtension()); - - Sheet sheet = wb1.getSheet("Sheet1"); - assertEquals(3, sheet.getLastRowNum()); - - // Verify comments are in the position expected - assertNotNull(sheet.getCellComment(new CellAddress(0,0))); - assertNull(sheet.getCellComment(new CellAddress(1,0))); - assertNotNull(sheet.getCellComment(new CellAddress(2,0))); - assertNotNull(sheet.getCellComment(new CellAddress(3,0))); - - String comment1 = sheet.getCellComment(new CellAddress(0,0)).getString().getString(); - assertEquals(comment1,"comment top row1 (index0)\n"); - String comment3 = sheet.getCellComment(new CellAddress(2,0)).getString().getString(); - assertEquals(comment3,"comment top row3 (index2)\n"); - String comment4 = sheet.getCellComment(new CellAddress(3,0)).getString().getString(); - assertEquals(comment4,"comment top row4 (index3)\n"); - - //Workbook wbBack = _testDataProvider.writeOutAndReadBack(wb); - - // Shifting all but first line down to test comments shifting - sheet.shiftRows(1, sheet.getLastRowNum(), 1, true, true); - - // Test that comments were shifted as expected - assertEquals(4, sheet.getLastRowNum()); - assertNotNull(sheet.getCellComment(new CellAddress(0,0))); - assertNull(sheet.getCellComment(new CellAddress(1,0))); - assertNull(sheet.getCellComment(new CellAddress(2,0))); - assertNotNull(sheet.getCellComment(new CellAddress(3,0))); - assertNotNull(sheet.getCellComment(new CellAddress(4,0))); - - String comment1_shifted = sheet.getCellComment(new CellAddress(0,0)).getString().getString(); - assertEquals(comment1,comment1_shifted); - String comment3_shifted = sheet.getCellComment(new CellAddress(3,0)).getString().getString(); - assertEquals(comment3,comment3_shifted); - String comment4_shifted = sheet.getCellComment(new CellAddress(4,0)).getString().getString(); - assertEquals(comment4,comment4_shifted); - - // Write out and read back in again - // Ensure that the changes were persisted - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - wb1.close(); - - sheet = wb2.getSheet("Sheet1"); - assertEquals(4, sheet.getLastRowNum()); - - // Verify comments are in the position expected after the shift - assertNotNull(sheet.getCellComment(new CellAddress(0,0))); - assertNull(sheet.getCellComment(new CellAddress(1,0))); - assertNull(sheet.getCellComment(new CellAddress(2,0))); - assertNotNull(sheet.getCellComment(new CellAddress(3,0))); - assertNotNull(sheet.getCellComment(new CellAddress(4,0))); - - comment1_shifted = sheet.getCellComment(new CellAddress(0,0)).getString().getString(); - assertEquals(comment1,comment1_shifted); - comment3_shifted = sheet.getCellComment(new CellAddress(3,0)).getString().getString(); - assertEquals(comment3,comment3_shifted); - comment4_shifted = sheet.getCellComment(new CellAddress(4,0)).getString().getString(); - assertEquals(comment4,comment4_shifted); - - // Shifting back up again, now two rows - sheet.shiftRows(2, sheet.getLastRowNum(), -2, true, true); - - // TODO: it seems HSSFSheet does not correctly remove comments from rows that are overwritten - // by shifting rows... - if(!(wb2 instanceof HSSFWorkbook)) { - assertEquals(2, sheet.getLastRowNum()); - - // Verify comments are in the position expected - assertNull("Had: " + (sheet.getCellComment(new CellAddress(0,0)) == null ? "null" : sheet.getCellComment(new CellAddress(0,0)).getString()), - sheet.getCellComment(new CellAddress(0,0))); - assertNotNull(sheet.getCellComment(new CellAddress(1,0))); - assertNotNull(sheet.getCellComment(new CellAddress(2,0))); - } - - comment1 = sheet.getCellComment(new CellAddress(1,0)).getString().getString(); - assertEquals(comment1,"comment top row3 (index2)\n"); - String comment2 = sheet.getCellComment(new CellAddress(2,0)).getString().getString(); - assertEquals(comment2,"comment top row4 (index3)\n"); - - wb2.close(); - } - - @Test - public final void testShiftWithNames() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet1 = wb.createSheet("Sheet1"); - wb.createSheet("Sheet2"); - Row row = sheet1.createRow(0); - row.createCell(0).setCellValue(1.1); - row.createCell(1).setCellValue(2.2); - - Name name1 = wb.createName(); - name1.setNameName("name1"); - name1.setRefersToFormula("Sheet1!$A$1+Sheet1!$B$1"); - - Name name2 = wb.createName(); - name2.setNameName("name2"); - name2.setRefersToFormula("Sheet1!$A$1"); - - //refers to A1 but on Sheet2. Should stay unaffected. - Name name3 = wb.createName(); - name3.setNameName("name3"); - name3.setRefersToFormula("Sheet2!$A$1"); - - //The scope of this one is Sheet2. Should stay unaffected. - Name name4 = wb.createName(); - name4.setNameName("name4"); - name4.setRefersToFormula("A1"); - name4.setSheetIndex(1); - - sheet1.shiftRows(0, 1, 2); //shift down the top row on Sheet1. - name1 = wb.getName("name1"); - assertEquals("Sheet1!$A$3+Sheet1!$B$3", name1.getRefersToFormula()); - - name2 = wb.getName("name2"); - assertEquals("Sheet1!$A$3", name2.getRefersToFormula()); - - //name3 and name4 refer to Sheet2 and should not be affected - name3 = wb.getName("name3"); - assertEquals("Sheet2!$A$1", name3.getRefersToFormula()); - - name4 = wb.getName("name4"); - assertEquals("A1", name4.getRefersToFormula()); - - wb.close(); - } - - @Test - public final void testShiftWithMergedRegions() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet(); - Row row = sheet.createRow(0); - row.createCell(0).setCellValue(1.1); - row.createCell(1).setCellValue(2.2); - CellRangeAddress region = new CellRangeAddress(0, 0, 0, 2); - assertEquals("A1:C1", region.formatAsString()); - - sheet.addMergedRegion(region); - - sheet.shiftRows(0, 1, 2); - region = sheet.getMergedRegion(0); - assertEquals("A3:C3", region.formatAsString()); - wb.close(); - } - - //@Ignore("bug 56454: Incorrectly handles merged regions that do not contain column 0") - @Test - public final void shiftWithMergedRegions_bug56454() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet(); - // populate sheet cells - for (int i = 0; i < 10; i++) { - Row row = sheet.createRow(i); - - for (int j = 0; j < 10; j++) { - Cell cell = row.createCell(j, CellType.STRING); - cell.setCellValue(i + "x" + j); - } - } - - CellRangeAddress A4_B7 = CellRangeAddress.valueOf("A4:B7"); - CellRangeAddress C4_D7 = CellRangeAddress.valueOf("C4:D7"); - - sheet.addMergedRegion(A4_B7); - sheet.addMergedRegion(C4_D7); - - assumeTrue(sheet.getLastRowNum() > 8); - - // Insert a row in the middle of both merged regions. - sheet.shiftRows(4, sheet.getLastRowNum(), 1); - - // all regions should still start at row 3, and elongate by 1 row - List expectedMergedRegions = new ArrayList(); - CellRangeAddress A4_B8 = CellRangeAddress.valueOf("A4:B8"); //A4:B7 should be elongated by 1 row - CellRangeAddress C4_D8 = CellRangeAddress.valueOf("C4:D8"); //C4:B7 should be elongated by 1 row - expectedMergedRegions.add(A4_B8); - expectedMergedRegions.add(C4_D8); - - // This test is written as expected-to-fail and should be rewritten - // as expected-to-pass when the bug is fixed. - // FIXME: remove try, catch, and testPassesNow, skipTest when test passes - try { - assertEquals(expectedMergedRegions, sheet.getMergedRegions()); - testPassesNow(56454); - } catch (AssertionError e) { - skipTest(e); - } - wb.close(); - } - - - - /** - * See bug #34023 - */ - @Test - public final void testShiftWithFormulas() throws IOException { - Workbook wb = _testDataProvider.openSampleWorkbook("ForShifting." + _testDataProvider.getStandardFileNameExtension()); - - Sheet sheet = wb.getSheet("Sheet1"); - assertEquals(20, sheet.getLastRowNum()); - - confirmRow(sheet, 0, 1, 171, 1, "ROW(D1)", "100+B1", "COUNT(D1:E1)"); - confirmRow(sheet, 1, 2, 172, 1, "ROW(D2)", "100+B2", "COUNT(D2:E2)"); - confirmRow(sheet, 2, 3, 173, 1, "ROW(D3)", "100+B3", "COUNT(D3:E3)"); - - confirmCell(sheet, 6, 1, 271, "200+B1"); - confirmCell(sheet, 7, 1, 272, "200+B2"); - confirmCell(sheet, 8, 1, 273, "200+B3"); - - confirmCell(sheet, 14, 0, 0.0, "A12"); // the cell referred to by this formula will be replaced - - // ----------- - // Row index 1 -> 11 (row "2" -> row "12") - sheet.shiftRows(1, 1, 10); - - // Now check what sheet looks like after move - - // no changes on row "1" - confirmRow(sheet, 0, 1, 171, 1, "ROW(D1)", "100+B1", "COUNT(D1:E1)"); - - // row "2" is now empty - confirmEmptyRow(sheet, 1); - - // Row "2" moved to row "12", and the formula has been updated. - // note however that the cached formula result (2) has not been updated. (POI differs from Excel here) - confirmRow(sheet, 11, 2, 172, 1, "ROW(D12)", "100+B12", "COUNT(D12:E12)"); - - // no changes on row "3" - confirmRow(sheet, 2, 3, 173, 1, "ROW(D3)", "100+B3", "COUNT(D3:E3)"); - - - confirmCell(sheet, 14, 0, 0.0, "#REF!"); - - - // Formulas on rows that weren't shifted: - confirmCell(sheet, 6, 1, 271, "200+B1"); - confirmCell(sheet, 7, 1, 272, "200+B12"); // this one moved - confirmCell(sheet, 8, 1, 273, "200+B3"); - - // check formulas on other sheets - Sheet sheet2 = wb.getSheet("Sheet2"); - confirmCell(sheet2, 0, 0, 371, "300+Sheet1!B1"); - confirmCell(sheet2, 1, 0, 372, "300+Sheet1!B12"); - confirmCell(sheet2, 2, 0, 373, "300+Sheet1!B3"); - - confirmCell(sheet2, 11, 0, 300, "300+Sheet1!#REF!"); - - - // Note - named ranges formulas have not been updated - wb.close(); - } - - private static void confirmRow(Sheet sheet, int rowIx, double valA, double valB, double valC, - String formulaA, String formulaB, String formulaC) { - confirmCell(sheet, rowIx, 4, valA, formulaA); - confirmCell(sheet, rowIx, 5, valB, formulaB); - confirmCell(sheet, rowIx, 6, valC, formulaC); - } - - private static void confirmCell(Sheet sheet, int rowIx, int colIx, - double expectedValue, String expectedFormula) { - Cell cell = sheet.getRow(rowIx).getCell(colIx); - assertEquals(expectedValue, cell.getNumericCellValue(), 0.0); - assertEquals(expectedFormula, cell.getCellFormula()); - } - - @Test - public final void testShiftSharedFormulasBug54206() throws IOException { - Workbook wb = _testDataProvider.openSampleWorkbook("54206." + _testDataProvider.getStandardFileNameExtension()); - - Sheet sheet = wb.getSheetAt(0); - assertEquals("SUMIF($B$19:$B$82,$B4,G$19:G$82)", sheet.getRow(3).getCell(6).getCellFormula()); - assertEquals("SUMIF($B$19:$B$82,$B4,H$19:H$82)", sheet.getRow(3).getCell(7).getCellFormula()); - assertEquals("SUMIF($B$19:$B$82,$B4,I$19:I$82)", sheet.getRow(3).getCell(8).getCellFormula()); - - assertEquals("SUMIF($B$19:$B$82,$B15,G$19:G$82)", sheet.getRow(14).getCell(6).getCellFormula()); - assertEquals("SUMIF($B$19:$B$82,$B15,H$19:H$82)", sheet.getRow(14).getCell(7).getCellFormula()); - assertEquals("SUMIF($B$19:$B$82,$B15,I$19:I$82)", sheet.getRow(14).getCell(8).getCellFormula()); - - // now the whole block G4L:15 - for(int i = 3; i <= 14; i++){ - for(int j = 6; j <= 8; j++){ - String col = CellReference.convertNumToColString(j); - String expectedFormula = "SUMIF($B$19:$B$82,$B"+(i+1)+","+col+"$19:"+col+"$82)"; - assertEquals(expectedFormula, sheet.getRow(i).getCell(j).getCellFormula()); - } - } - - assertEquals("SUM(G24:I24)", sheet.getRow(23).getCell(9).getCellFormula()); - assertEquals("SUM(G25:I25)", sheet.getRow(24).getCell(9).getCellFormula()); - assertEquals("SUM(G26:I26)", sheet.getRow(25).getCell(9).getCellFormula()); - - sheet.shiftRows(24, sheet.getLastRowNum(), 4, true, false); - - assertEquals("SUMIF($B$19:$B$86,$B4,G$19:G$86)", sheet.getRow(3).getCell(6).getCellFormula()); - assertEquals("SUMIF($B$19:$B$86,$B4,H$19:H$86)", sheet.getRow(3).getCell(7).getCellFormula()); - assertEquals("SUMIF($B$19:$B$86,$B4,I$19:I$86)", sheet.getRow(3).getCell(8).getCellFormula()); - - assertEquals("SUMIF($B$19:$B$86,$B15,G$19:G$86)", sheet.getRow(14).getCell(6).getCellFormula()); - assertEquals("SUMIF($B$19:$B$86,$B15,H$19:H$86)", sheet.getRow(14).getCell(7).getCellFormula()); - assertEquals("SUMIF($B$19:$B$86,$B15,I$19:I$86)", sheet.getRow(14).getCell(8).getCellFormula()); - - // now the whole block G4L:15 - for(int i = 3; i <= 14; i++){ - for(int j = 6; j <= 8; j++){ - String col = CellReference.convertNumToColString(j); - String expectedFormula = "SUMIF($B$19:$B$86,$B"+(i+1)+","+col+"$19:"+col+"$86)"; - assertEquals(expectedFormula, sheet.getRow(i).getCell(j).getCellFormula()); - } - } - - assertEquals("SUM(G24:I24)", sheet.getRow(23).getCell(9).getCellFormula()); - - // shifted rows - assertTrue( sheet.getRow(24) == null || sheet.getRow(24).getCell(9) == null); - assertTrue( sheet.getRow(25) == null || sheet.getRow(25).getCell(9) == null); - assertTrue( sheet.getRow(26) == null || sheet.getRow(26).getCell(9) == null); - assertTrue( sheet.getRow(27) == null || sheet.getRow(27).getCell(9) == null); - - assertEquals("SUM(G29:I29)", sheet.getRow(28).getCell(9).getCellFormula()); - assertEquals("SUM(G30:I30)", sheet.getRow(29).getCell(9).getCellFormula()); - wb.close(); - } - - @Test - public void testBug55280() throws IOException { - Workbook w = _testDataProvider.createWorkbook(); - Sheet s = w.createSheet(); - for (int row = 0; row < 5000; ++row) - s.addMergedRegion(new CellRangeAddress(row, row, 0, 3)); - - s.shiftRows(0, 4999, 1); // takes a long time... - w.close(); - } - - @Test - public void test47169() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet(); - sheet.createRow(30); - sheet.shiftRows(29, 29, 1, true, true); - sheet.createRow(30); - - wb.close(); - } - - /** - * Unified test for: - * bug 46742: XSSFSheet.shiftRows should shift hyperlinks - * bug 52903: HSSFSheet.shiftRows should shift hyperlinks - * - * @throws IOException - */ - @Test - public void testBug46742_52903_shiftHyperlinks() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet("test"); - Row row = sheet.createRow(0); - - // How to create hyperlinks - // https://poi.apache.org/spreadsheet/quick-guide.html#Hyperlinks - CreationHelper helper = wb.getCreationHelper(); - CellStyle hlinkStyle = wb.createCellStyle(); - Font hlinkFont = wb.createFont(); - hlinkFont.setUnderline(Font.U_SINGLE); - hlinkFont.setColor(IndexedColors.BLUE.getIndex()); - hlinkStyle.setFont(hlinkFont); - - // 3D relative document link - // CellAddress=A1, shifted to A4 - Cell cell = row.createCell(0); - cell.setCellStyle(hlinkStyle); - createHyperlink(helper, cell, HyperlinkType.DOCUMENT, "test!E1"); - - // URL - cell = row.createCell(1); - // CellAddress=B1, shifted to B4 - cell.setCellStyle(hlinkStyle); - createHyperlink(helper, cell, HyperlinkType.URL, "http://poi.apache.org/"); - - // row0 will be shifted on top of row1, so this URL should be removed from the workbook - Row overwrittenRow = sheet.createRow(3); - cell = overwrittenRow.createCell(2); - // CellAddress=C4, will be overwritten (deleted) - cell.setCellStyle(hlinkStyle); - createHyperlink(helper, cell, HyperlinkType.EMAIL, "mailto:poi@apache.org"); - - // hyperlinks on this row are unaffected by the row shifting, so the hyperlinks should not move - Row unaffectedRow = sheet.createRow(20); - cell = unaffectedRow.createCell(3); - // CellAddress=D21, will be unaffected - cell.setCellStyle(hlinkStyle); - createHyperlink(helper, cell, HyperlinkType.FILE, "54524.xlsx"); - - cell = wb.createSheet("other").createRow(0).createCell(0); - // CellAddress=Other!A1, will be unaffected - cell.setCellStyle(hlinkStyle); - createHyperlink(helper, cell, HyperlinkType.URL, "http://apache.org/"); - - int startRow = 0; - int endRow = 0; - int n = 3; - sheet.shiftRows(startRow, endRow, n); - - Workbook read = _testDataProvider.writeOutAndReadBack(wb); - wb.close(); - - Sheet sh = read.getSheet("test"); - - Row shiftedRow = sh.getRow(3); - - // document link anchored on a shifted cell should be moved - // Note that hyperlinks do not track what they point to, so this hyperlink should still refer to test!E1 - verifyHyperlink(shiftedRow.getCell(0), HyperlinkType.DOCUMENT, "test!E1"); - - // URL, EMAIL, and FILE links anchored on a shifted cell should be moved - verifyHyperlink(shiftedRow.getCell(1), HyperlinkType.URL, "http://poi.apache.org/"); - - // Make sure hyperlinks were moved and not copied - assertNull("Document hyperlink should be moved, not copied", sh.getHyperlink(0, 0)); - assertNull("URL hyperlink should be moved, not copied", sh.getHyperlink(0, 1)); - - // Make sure hyperlink in overwritten row is deleted - assertEquals(3, sh.getHyperlinkList().size()); - CellAddress unexpectedLinkAddress = new CellAddress("C4"); - for (Hyperlink link : sh.getHyperlinkList()) { - final CellAddress linkAddress = new CellAddress(link.getFirstRow(), link.getFirstColumn()); - if (linkAddress.equals(unexpectedLinkAddress)) { - fail("Row 4, including the hyperlink at C4, should have " + - "been deleted when Row 1 was shifted on top of it."); - } - } - - // Make sure unaffected rows are not shifted - Cell unaffectedCell = sh.getRow(20).getCell(3); - assertTrue(cellHasHyperlink(unaffectedCell)); - verifyHyperlink(unaffectedCell, HyperlinkType.FILE, "54524.xlsx"); - - // Make sure cells on other sheets are not affected - unaffectedCell = read.getSheet("other").getRow(0).getCell(0); - assertTrue(cellHasHyperlink(unaffectedCell)); - verifyHyperlink(unaffectedCell, HyperlinkType.URL, "http://apache.org/"); - - read.close(); - } - - //@Ignore("bug 56454: Incorrectly handles merged regions that do not contain column 0") - @Test - public void shiftRowsWithMergedRegionsThatDoNotContainColumnZero() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet("test"); - - // populate sheet cells - for (int i = 0; i < 10; i++) { - Row row = sheet.createRow(i); - for (int j = 0; j < 12; j++) { - Cell cell = row.createCell(j); - cell.setCellValue(i + "x" + j); - } - } - - CellRangeAddress A4_B7 = new CellRangeAddress(3, 6, 0, 1); - CellRangeAddress C5_D7 = new CellRangeAddress(4, 6, 2, 3); - - sheet.addMergedRegion(A4_B7); - sheet.addMergedRegion(C5_D7); - - // A4:B7 will elongate vertically - // C5:D7 will be shifted down with same size - sheet.shiftRows(4, sheet.getLastRowNum(), 1); - - // This test is written as expected-to-fail and should be rewritten - // as expected-to-pass when the bug is fixed. - // FIXME: remove try, catch, and testPassesNow, skipTest when test passes - try { - assertEquals(2, sheet.getNumMergedRegions()); - assertEquals(CellRangeAddress.valueOf("A4:B8"), sheet.getMergedRegion(0)); - assertEquals(CellRangeAddress.valueOf("C5:D8"), sheet.getMergedRegion(1)); - testPassesNow(56454); - } catch (AssertionError e) { - skipTest(e); - } - - wb.close(); - } - - @Test - public void shiftMergedRowsToMergedRowsUp() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet("test"); - populateSheetCells(sheet); - - - CellRangeAddress A1_E1 = new CellRangeAddress(0, 0, 0, 4); - CellRangeAddress A2_C2 = new CellRangeAddress(1, 1, 0, 2); - - sheet.addMergedRegion(A1_E1); - sheet.addMergedRegion(A2_C2); - - // A1:E1 should be removed - // A2:C2 will be A1:C1 - sheet.shiftRows(1, sheet.getLastRowNum(), -1); - - assertEquals(1, sheet.getNumMergedRegions()); - assertEquals(CellRangeAddress.valueOf("A1:C1"), sheet.getMergedRegion(0)); - - wb.close(); - } - - private void populateSheetCells(Sheet sheet) { - // populate sheet cells - for (int i = 0; i < 2; i++) { - Row row = sheet.createRow(i); - for (int j = 0; j < 5; j++) { - Cell cell = row.createCell(j); - cell.setCellValue(i + "x" + j); - } - } - } - - @Test - public void shiftMergedRowsToMergedRowsDown() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet("test"); - - // populate sheet cells - populateSheetCells(sheet); - - CellRangeAddress A1_E1 = new CellRangeAddress(0, 0, 0, 4); - CellRangeAddress A2_C2 = new CellRangeAddress(1, 1, 0, 2); - - sheet.addMergedRegion(A1_E1); - sheet.addMergedRegion(A2_C2); - - // A1:E1 should be moved to A2:E2 - // A2:C2 will be removed - sheet.shiftRows(0, 0, 1); - - assertEquals(1, sheet.getNumMergedRegions()); - assertEquals(CellRangeAddress.valueOf("A2:E2"), sheet.getMergedRegion(0)); - - wb.close(); - } - - private void createHyperlink(CreationHelper helper, Cell cell, HyperlinkType linkType, String ref) { - cell.setCellValue(ref); - Hyperlink link = helper.createHyperlink(linkType); - link.setAddress(ref); - cell.setHyperlink(link); - } - - private void verifyHyperlink(Cell cell, HyperlinkType linkType, String ref) { - assertTrue(cellHasHyperlink(cell)); - Hyperlink link = cell.getHyperlink(); - assertEquals(linkType, link.getTypeEnum()); - assertEquals(ref, link.getAddress()); - } - - private boolean cellHasHyperlink(Cell cell) { - return (cell != null) && (cell.getHyperlink() != null); - } -} diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetUpdateArrayFormulas.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetUpdateArrayFormulas.java deleted file mode 100644 index bbd95cccd..000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestSheetUpdateArrayFormulas.java +++ /dev/null @@ -1,610 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assume.assumeTrue; -import static org.junit.Assert.fail; - -import java.io.IOException; -import java.util.Arrays; - -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.ss.formula.FormulaParseException; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.CellReference; -import org.junit.Ignore; -import org.junit.Test; - -/** - * Common superclass for testing usermodel API for array formulas.
    - * Formula evaluation is not tested here. - * - * @author Yegor Kozlov - * @author Josh Micich - */ -public abstract class BaseTestSheetUpdateArrayFormulas { - protected final ITestDataProvider _testDataProvider; - - protected BaseTestSheetUpdateArrayFormulas(ITestDataProvider testDataProvider) { - _testDataProvider = testDataProvider; - } - - @Test - public final void testAutoCreateOtherCells() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet("Sheet1"); - - Row row1 = sheet.createRow(0); - Cell cellA1 = row1.createCell(0); - Cell cellB1 = row1.createCell(1); - String formula = "42"; - sheet.setArrayFormula(formula, CellRangeAddress.valueOf("A1:B2")); - - assertEquals(formula, cellA1.getCellFormula()); - assertEquals(formula, cellB1.getCellFormula()); - Row row2 = sheet.getRow(1); - assertNotNull(row2); - assertEquals(formula, row2.getCell(0).getCellFormula()); - assertEquals(formula, row2.getCell(1).getCellFormula()); - - workbook.close(); - } - /** - * Set single-cell array formula - */ - @Test - public final void testSetArrayFormula_singleCell() throws IOException { - Cell[] cells; - - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet(); - Cell cell = sheet.createRow(0).createCell(0); - assertFalse(cell.isPartOfArrayFormulaGroup()); - try { - cell.getArrayFormulaRange(); - fail("expected exception"); - } catch (IllegalStateException e){ - assertEquals("Cell A1 is not part of an array formula.", e.getMessage()); - } - - // row 3 does not yet exist - assertNull(sheet.getRow(2)); - CellRangeAddress range = new CellRangeAddress(2, 2, 2, 2); - cells = sheet.setArrayFormula("SUM(C11:C12*D11:D12)", range).getFlattenedCells(); - assertEquals(1, cells.length); - // sheet.setArrayFormula creates rows and cells for the designated range - assertNotNull(sheet.getRow(2)); - cell = sheet.getRow(2).getCell(2); - assertNotNull(cell); - - assertTrue(cell.isPartOfArrayFormulaGroup()); - //retrieve the range and check it is the same - assertEquals(range.formatAsString(), cell.getArrayFormulaRange().formatAsString()); - //check the formula - assertEquals("SUM(C11:C12*D11:D12)", cell.getCellFormula()); - - workbook.close(); - } - - /** - * Set multi-cell array formula - */ - @Test - public final void testSetArrayFormula_multiCell() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet(); - - // multi-cell formula - // rows 3-5 don't exist yet - assertNull(sheet.getRow(3)); - assertNull(sheet.getRow(4)); - assertNull(sheet.getRow(5)); - - CellRangeAddress range = CellRangeAddress.valueOf("C4:C6"); - Cell[] cells = sheet.setArrayFormula("SUM(A1:A3*B1:B3)", range).getFlattenedCells(); - assertEquals(3, cells.length); - - // sheet.setArrayFormula creates rows and cells for the designated range - assertSame(cells[0], sheet.getRow(3).getCell(2)); - assertSame(cells[1], sheet.getRow(4).getCell(2)); - assertSame(cells[2], sheet.getRow(5).getCell(2)); - - for(Cell acell : cells){ - assertTrue(acell.isPartOfArrayFormulaGroup()); - assertEquals(CellType.FORMULA, acell.getCellTypeEnum()); - assertEquals("SUM(A1:A3*B1:B3)", acell.getCellFormula()); - //retrieve the range and check it is the same - assertEquals(range.formatAsString(), acell.getArrayFormulaRange().formatAsString()); - } - - workbook.close(); - } - - /** - * Passing an incorrect formula to sheet.setArrayFormula - * should throw FormulaParseException - */ - @Test - public final void testSetArrayFormula_incorrectFormula() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet(); - - try { - sheet.setArrayFormula("incorrect-formula(C11_C12*D11_D12)", - new CellRangeAddress(10, 10, 10, 10)); - fail("expected exception"); - } catch (FormulaParseException e){ - //expected exception - } - - workbook.close(); - } - - /** - * Calls of cell.getArrayFormulaRange and sheet.removeArrayFormula - * on a not-array-formula cell throw IllegalStateException - */ - @Test - public final void testArrayFormulas_illegalCalls() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet(); - - Cell cell = sheet.createRow(0).createCell(0); - assertFalse(cell.isPartOfArrayFormulaGroup()); - try { - cell.getArrayFormulaRange(); - fail("expected exception"); - } catch (IllegalStateException e){ - assertEquals("Cell A1 is not part of an array formula.", e.getMessage()); - } - - try { - sheet.removeArrayFormula(cell); - fail("expected exception"); - } catch (IllegalArgumentException e){ - assertEquals("Cell A1 is not part of an array formula.", e.getMessage()); - } - - workbook.close(); - } - - /** - * create and remove array formulas - */ - @Test - public final void testRemoveArrayFormula() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet(); - - CellRangeAddress range = new CellRangeAddress(3, 5, 2, 2); - assertEquals("C4:C6", range.formatAsString()); - CellRange cr = sheet.setArrayFormula("SUM(A1:A3*B1:B3)", range); - assertEquals(3, cr.size()); - - // remove the formula cells in C4:C6 - CellRange dcells = sheet.removeArrayFormula(cr.getTopLeftCell()); - // removeArrayFormula should return the same cells as setArrayFormula - assertArrayEquals(cr.getFlattenedCells(), dcells.getFlattenedCells()); - - for(Cell acell : cr){ - assertFalse(acell.isPartOfArrayFormulaGroup()); - assertEquals(CellType.BLANK, acell.getCellTypeEnum()); - } - - // cells C4:C6 are not included in array formula, - // invocation of sheet.removeArrayFormula on any of them throws IllegalArgumentException - for(Cell acell : cr){ - try { - sheet.removeArrayFormula(acell); - fail("expected exception"); - } catch (IllegalArgumentException e){ - String ref = new CellReference(acell).formatAsString(); - assertEquals("Cell "+ref+" is not part of an array formula.", e.getMessage()); - } - } - - workbook.close(); - } - - /** - * Test that when reading a workbook from input stream, array formulas are recognized - */ - @Test - public final void testReadArrayFormula() throws IOException { - Cell[] cells; - - Workbook workbook1 = _testDataProvider.createWorkbook(); - Sheet sheet1 = workbook1.createSheet(); - cells = sheet1.setArrayFormula("SUM(A1:A3*B1:B3)", CellRangeAddress.valueOf("C4:C6")).getFlattenedCells(); - assertEquals(3, cells.length); - - cells = sheet1.setArrayFormula("MAX(A1:A3*B1:B3)", CellRangeAddress.valueOf("A4:A6")).getFlattenedCells(); - assertEquals(3, cells.length); - - Sheet sheet2 = workbook1.createSheet(); - cells = sheet2.setArrayFormula("MIN(A1:A3*B1:B3)", CellRangeAddress.valueOf("D2:D4")).getFlattenedCells(); - assertEquals(3, cells.length); - - Workbook workbook2 = _testDataProvider.writeOutAndReadBack(workbook1); - workbook1.close(); - sheet1 = workbook2.getSheetAt(0); - for(int rownum=3; rownum <= 5; rownum++) { - Cell cell1 = sheet1.getRow(rownum).getCell(2); - assertTrue( cell1.isPartOfArrayFormulaGroup()); - - Cell cell2 = sheet1.getRow(rownum).getCell(0); - assertTrue( cell2.isPartOfArrayFormulaGroup()); - } - - sheet2 = workbook2.getSheetAt(1); - for(int rownum=1; rownum <= 3; rownum++) { - Cell cell1 = sheet2.getRow(rownum).getCell(3); - assertTrue( cell1.isPartOfArrayFormulaGroup()); - } - - workbook2.close(); - } - - /** - * Test that we can set pre-calculated formula result for array formulas - */ - @Test - public void testModifyArrayCells_setFormulaResult() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet(); - - //single-cell array formula - CellRange srange = - sheet.setArrayFormula("SUM(A4:A6,B4:B6)", CellRangeAddress.valueOf("B5")); - Cell scell = srange.getTopLeftCell(); - assertEquals(CellType.FORMULA, scell.getCellTypeEnum()); - assertEquals(0.0, scell.getNumericCellValue(), 0); - scell.setCellValue(1.1); - assertEquals(1.1, scell.getNumericCellValue(), 0); - - //multi-cell array formula - CellRange mrange = - sheet.setArrayFormula("A1:A3*B1:B3", CellRangeAddress.valueOf("C1:C3")); - for(Cell mcell : mrange){ - assertEquals(CellType.FORMULA, mcell.getCellTypeEnum()); - assertEquals(0.0, mcell.getNumericCellValue(), 0); - double fmlaResult = 1.2; - mcell.setCellValue(fmlaResult); - assertEquals(fmlaResult, mcell.getNumericCellValue(), 0); - } - workbook.close(); - } - - @Test - public void testModifyArrayCells_setCellType() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet(); - - // single-cell array formulas behave just like normal cells - - // changing cell type removes the array formula and associated cached result - CellRange srange = - sheet.setArrayFormula("SUM(A4:A6,B4:B6)", CellRangeAddress.valueOf("B5")); - Cell scell = srange.getTopLeftCell(); - assertEquals(CellType.FORMULA, scell.getCellTypeEnum()); - assertEquals(0.0, scell.getNumericCellValue(), 0); - scell.setCellType(CellType.STRING); - assertEquals(CellType.STRING, scell.getCellTypeEnum()); - scell.setCellValue("string cell"); - assertEquals("string cell", scell.getStringCellValue()); - - //once you create a multi-cell array formula, you cannot change the type of its cells - CellRange mrange = - sheet.setArrayFormula("A1:A3*B1:B3", CellRangeAddress.valueOf("C1:C3")); - for(Cell mcell : mrange){ - try { - assertEquals(CellType.FORMULA, mcell.getCellTypeEnum()); - mcell.setCellType(CellType.NUMERIC); - fail("expected exception"); - } catch (IllegalStateException e){ - CellReference ref = new CellReference(mcell); - String msg = "Cell "+ref.formatAsString()+" is part of a multi-cell array formula. You cannot change part of an array."; - assertEquals(msg, e.getMessage()); - } - // a failed invocation of Cell.setCellType leaves the cell - // in the state that it was in prior to the invocation - assertEquals(CellType.FORMULA, mcell.getCellTypeEnum()); - assertTrue(mcell.isPartOfArrayFormulaGroup()); - } - workbook.close(); - } - - @Test - public void testModifyArrayCells_setCellFormula() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet(); - - CellRange srange = - sheet.setArrayFormula("SUM(A4:A6,B4:B6)", CellRangeAddress.valueOf("B5")); - Cell scell = srange.getTopLeftCell(); - assertEquals("SUM(A4:A6,B4:B6)", scell.getCellFormula()); - assertEquals(CellType.FORMULA, scell.getCellTypeEnum()); - assertTrue(scell.isPartOfArrayFormulaGroup()); - scell.setCellFormula("SUM(A4,A6)"); - //we are now a normal formula cell - assertEquals("SUM(A4,A6)", scell.getCellFormula()); - assertFalse(scell.isPartOfArrayFormulaGroup()); - assertEquals(CellType.FORMULA, scell.getCellTypeEnum()); - //check that setting formula result works - assertEquals(0.0, scell.getNumericCellValue(), 0); - scell.setCellValue(33.0); - assertEquals(33.0, scell.getNumericCellValue(), 0); - - //multi-cell array formula - CellRange mrange = - sheet.setArrayFormula("A1:A3*B1:B3", CellRangeAddress.valueOf("C1:C3")); - for(Cell mcell : mrange){ - //we cannot set individual formulas for cells included in an array formula - try { - assertEquals("A1:A3*B1:B3", mcell.getCellFormula()); - mcell.setCellFormula("A1+A2"); - fail("expected exception"); - } catch (IllegalStateException e){ - CellReference ref = new CellReference(mcell); - String msg = "Cell "+ref.formatAsString()+" is part of a multi-cell array formula. You cannot change part of an array."; - assertEquals(msg, e.getMessage()); - } - // a failed invocation of Cell.setCellFormula leaves the cell - // in the state that it was in prior to the invocation - assertEquals("A1:A3*B1:B3", mcell.getCellFormula()); - assertTrue(mcell.isPartOfArrayFormulaGroup()); - } - workbook.close(); - } - - @Test - public void testModifyArrayCells_removeCell() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet(); - - //single-cell array formulas behave just like normal cells - CellRangeAddress cra = CellRangeAddress.valueOf("B5"); - CellRange srange = - sheet.setArrayFormula("SUM(A4:A6,B4:B6)", cra); - Cell scell = srange.getTopLeftCell(); - - Row srow = sheet.getRow(cra.getFirstRow()); - assertSame(srow, scell.getRow()); - srow.removeCell(scell); - assertNull(srow.getCell(cra.getFirstColumn())); - - //re-create the removed cell - scell = srow.createCell(cra.getFirstColumn()); - assertEquals(CellType.BLANK, scell.getCellTypeEnum()); - assertFalse(scell.isPartOfArrayFormulaGroup()); - - //we cannot remove cells included in a multi-cell array formula - CellRange mrange = - sheet.setArrayFormula("A1:A3*B1:B3", CellRangeAddress.valueOf("C1:C3")); - for(Cell mcell : mrange){ - int columnIndex = mcell.getColumnIndex(); - Row mrow = mcell.getRow(); - try { - mrow.removeCell(mcell); - fail("expected exception"); - } catch (IllegalStateException e){ - CellReference ref = new CellReference(mcell); - String msg = "Cell "+ref.formatAsString()+" is part of a multi-cell array formula. You cannot change part of an array."; - assertEquals(msg, e.getMessage()); - } - // a failed invocation of Row.removeCell leaves the row - // in the state that it was in prior to the invocation - assertSame(mcell, mrow.getCell(columnIndex)); - assertTrue(mcell.isPartOfArrayFormulaGroup()); - assertEquals(CellType.FORMULA, mcell.getCellTypeEnum()); - } - - workbook.close(); - } - - @Test - public void testModifyArrayCells_removeRow() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet(); - - //single-cell array formulas behave just like normal cells - CellRangeAddress cra = CellRangeAddress.valueOf("B5"); - CellRange srange = - sheet.setArrayFormula("SUM(A4:A6,B4:B6)", cra); - Cell scell = srange.getTopLeftCell(); - assertEquals(CellType.FORMULA, scell.getCellTypeEnum()); - - Row srow = scell.getRow(); - assertSame(srow, sheet.getRow(cra.getFirstRow())); - sheet.removeRow(srow); - assertNull(sheet.getRow(cra.getFirstRow())); - - //re-create the removed row and cell - scell = sheet.createRow(cra.getFirstRow()).createCell(cra.getFirstColumn()); - assertEquals(CellType.BLANK, scell.getCellTypeEnum()); - assertFalse(scell.isPartOfArrayFormulaGroup()); - - //we cannot remove rows with cells included in a multi-cell array formula - CellRange mrange = - sheet.setArrayFormula("A1:A3*B1:B3", CellRangeAddress.valueOf("C1:C3")); - for(Cell mcell : mrange){ - int columnIndex = mcell.getColumnIndex(); - Row mrow = mcell.getRow(); - try { - sheet.removeRow(mrow); - fail("expected exception"); - } catch (IllegalStateException e){ - // String msg = "Row[rownum="+mrow.getRowNum()+"] contains cell(s) included in a multi-cell array formula. You cannot change part of an array."; - // assertEquals(msg, e.getMessage()); - } - // a failed invocation of Row.removeCell leaves the row - // in the state that it was in prior to the invocation - assertSame(mrow, sheet.getRow(mrow.getRowNum())); - assertSame(mcell, mrow.getCell(columnIndex)); - assertTrue(mcell.isPartOfArrayFormulaGroup()); - assertEquals(CellType.FORMULA, mcell.getCellTypeEnum()); - } - - workbook.close(); - } - - @Test - public void testModifyArrayCells_mergeCellsSingle() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet(); - assertEquals(0, sheet.getNumMergedRegions()); - - //single-cell array formulas behave just like normal cells - CellRange srange = - sheet.setArrayFormula("SUM(A4:A6,B4:B6)", CellRangeAddress.valueOf("B5")); - Cell scell = srange.getTopLeftCell(); - sheet.addMergedRegion(CellRangeAddress.valueOf("B5:C6")); - //we are still an array formula - assertEquals(CellType.FORMULA, scell.getCellTypeEnum()); - assertTrue(scell.isPartOfArrayFormulaGroup()); - assertEquals(1, sheet.getNumMergedRegions()); - - workbook.close(); - } - - @Test - public void testModifyArrayCells_mergeCellsMulti() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet(); - int expectedNumMergedRegions = 0; - assertEquals(expectedNumMergedRegions, sheet.getNumMergedRegions()); - - // we cannot merge cells included in an array formula - sheet.setArrayFormula("A1:A4*B1:B4", CellRangeAddress.valueOf("C2:F5")); - for (String ref : Arrays.asList( - "C2:F5", // identity - "D3:E4", "B1:G6", // contains - "B1:C2", "F1:G2", "F5:G6", "B5:C6", // 1x1 corner intersection - "B1:C6", "B1:G2", "F1:G6", "B5:G6", // 1-row/1-column intersection - "B1:D3", "E1:G3", "E4:G6", "B4:D6", // 2x2 corner intersection - "B1:D6", "B1:G3", "E1:G6", "B4:G6" // 2-row/2-column intersection - )) { - CellRangeAddress cra = CellRangeAddress.valueOf(ref); - try { - sheet.addMergedRegion(cra); - fail("expected exception with ref " + ref); - } catch (IllegalStateException e) { - String msg = "The range "+cra.formatAsString()+" intersects with a multi-cell array formula. You cannot merge cells of an array."; - assertEquals(msg, e.getMessage()); - } - } - //the number of merged regions remains the same - assertEquals(expectedNumMergedRegions, sheet.getNumMergedRegions()); - - // we can merge non-intersecting cells - for (String ref : Arrays.asList( - "C1:F1", //above - "G2:G5", //right - "C6:F6", //bottom - "B2:B5", "H7:J9")) { - CellRangeAddress cra = CellRangeAddress.valueOf(ref); - try { - sheet.addMergedRegion(cra); - expectedNumMergedRegions++; - assertEquals(expectedNumMergedRegions, sheet.getNumMergedRegions()); - } catch (IllegalStateException e) { - fail("did not expect exception with ref: " + ref + "\n" + e.getMessage()); - } - } - - workbook.close(); - } - - @Test - public void testModifyArrayCells_shiftRows() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet(); - - //single-cell array formulas behave just like normal cells - we can change the cell type - CellRange srange = - sheet.setArrayFormula("SUM(A4:A6,B4:B6)", CellRangeAddress.valueOf("B5")); - Cell scell = srange.getTopLeftCell(); - assertEquals("SUM(A4:A6,B4:B6)", scell.getCellFormula()); - sheet.shiftRows(0, 0, 1); - sheet.shiftRows(0, 1, 1); - - //we cannot set individual formulas for cells included in an array formula - sheet.setArrayFormula("A1:A3*B1:B3", CellRangeAddress.valueOf("C1:C3")); - - try { - sheet.shiftRows(0, 0, 1); - fail("expected exception"); - } catch (IllegalStateException e){ - String msg = "Row[rownum=0] contains cell(s) included in a multi-cell array formula. You cannot change part of an array."; - assertEquals(msg, e.getMessage()); - } - /* - TODO: enable shifting the whole array - - sheet.shiftRows(0, 2, 1); - //the array C1:C3 is now C2:C4 - CellRangeAddress cra = CellRangeAddress.valueOf("C2:C4"); - for(Cell mcell : mrange){ - //TODO define equals and hashcode for CellRangeAddress - assertEquals(cra.formatAsString(), mcell.getArrayFormulaRange().formatAsString()); - assertEquals("A2:A4*B2:B4", mcell.getCellFormula()); - assertTrue(mcell.isPartOfArrayFormulaGroup()); - assertEquals(CellType.FORMULA, mcell.getCellTypeEnum()); - } - - */ - workbook.close(); - } - - @Ignore - @Test - public void shouldNotBeAbleToCreateArrayFormulaOnPreexistingMergedRegion() throws IOException { - /* - * m = merged region - * f = array formula - * fm = cell belongs to a merged region and an array formula (illegal, that's what this tests for) - * - * A B C - * 1 f f - * 2 fm fm - * 3 f f - */ - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet(); - - CellRangeAddress mergedRegion = CellRangeAddress.valueOf("B2:C2"); - sheet.addMergedRegion(mergedRegion); - CellRangeAddress arrayFormula = CellRangeAddress.valueOf("C1:C3"); - assumeTrue(mergedRegion.intersects(arrayFormula)); - assumeTrue(arrayFormula.intersects(mergedRegion)); - try { - sheet.setArrayFormula("SUM(A1:A3)", arrayFormula); - fail("expected exception: should not be able to create an array formula that intersects with a merged region"); - } catch (IllegalStateException e) { - // expected - } - - workbook.close(); - } -} diff --git a/src/testcases/org/apache/poi/ss/usermodel/BaseTestWorkbook.java b/src/testcases/org/apache/poi/ss/usermodel/BaseTestWorkbook.java deleted file mode 100644 index 9222f6043..000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/BaseTestWorkbook.java +++ /dev/null @@ -1,957 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.util.ConcurrentModificationException; -import java.util.Iterator; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.ss.usermodel.ClientAnchor.AnchorType; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.util.NullOutputStream; -import org.apache.poi.util.TempFile; -import org.junit.Test; - -public abstract class BaseTestWorkbook { - - protected final ITestDataProvider _testDataProvider; - - protected BaseTestWorkbook(ITestDataProvider testDataProvider) { - _testDataProvider = testDataProvider; - } - - @Test - public void sheetIterator_forEach() throws IOException { - final Workbook wb = _testDataProvider.createWorkbook(); - wb.createSheet("Sheet0"); - wb.createSheet("Sheet1"); - wb.createSheet("Sheet2"); - int i = 0; - for (Sheet sh : wb) { - assertEquals("Sheet"+i, sh.getSheetName()); - i++; - } - wb.close(); - } - - /** - * Expected ConcurrentModificationException: - * should not be able to advance an iterator when the - * underlying data has been reordered - */ - @Test(expected=ConcurrentModificationException.class) - public void sheetIterator_sheetsReordered() throws IOException { - final Workbook wb = _testDataProvider.createWorkbook(); - wb.createSheet("Sheet0"); - wb.createSheet("Sheet1"); - wb.createSheet("Sheet2"); - - Iterator it = wb.sheetIterator(); - it.next(); - wb.setSheetOrder("Sheet2", 1); - - // Iterator order should be fixed when iterator is created - try { - assertEquals("Sheet1", it.next().getSheetName()); - } finally { - wb.close(); - } - } - - /** - * Expected ConcurrentModificationException: - * should not be able to advance an iterator when the - * underlying data has been reordered - */ - @Test(expected=ConcurrentModificationException.class) - public void sheetIterator_sheetRemoved() throws IOException { - final Workbook wb = _testDataProvider.createWorkbook(); - wb.createSheet("Sheet0"); - wb.createSheet("Sheet1"); - wb.createSheet("Sheet2"); - - Iterator it = wb.sheetIterator(); - wb.removeSheetAt(1); - - // Iterator order should be fixed when iterator is created - try { - it.next(); - } finally { - wb.close(); - } - } - - /** - * Expected UnsupportedOperationException: - * should not be able to remove sheets from the sheet iterator - */ - @Test(expected=UnsupportedOperationException.class) - public void sheetIterator_remove() throws IOException { - final Workbook wb = _testDataProvider.createWorkbook(); - wb.createSheet("Sheet0"); - - Iterator it = wb.sheetIterator(); - it.next(); //Sheet0 - try { - it.remove(); - } finally { - wb.close(); - } - } - - - @Test - public void createSheet() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - assertEquals(0, wb.getNumberOfSheets()); - - //getting a sheet by invalid index or non-existing name - assertNull(wb.getSheet("Sheet1")); - try { - wb.getSheetAt(0); - fail("should have thrown exceptiuon due to invalid sheet index"); - } catch (IllegalArgumentException e) { - // expected during successful test - // no negative index in the range message - assertFalse(e.getMessage().contains("-1")); - } - - Sheet sheet0 = wb.createSheet(); - Sheet sheet1 = wb.createSheet(); - assertEquals("Sheet0", sheet0.getSheetName()); - assertEquals("Sheet1", sheet1.getSheetName()); - assertEquals(2, wb.getNumberOfSheets()); - - //fetching sheets by name is case-insensitive - Sheet originalSheet = wb.createSheet("Sheet3"); - Sheet fetchedSheet = wb.getSheet("sheet3"); - if (fetchedSheet == null) { - fail("Identified bug 44892"); - } - assertEquals("Sheet3", fetchedSheet.getSheetName()); - assertEquals(3, wb.getNumberOfSheets()); - assertSame(originalSheet, fetchedSheet); - try { - wb.createSheet("sHeeT3"); - fail("should have thrown exceptiuon due to duplicate sheet name"); - } catch (IllegalArgumentException e) { - // expected during successful test - assertEquals("The workbook already contains a sheet named 'sHeeT3'", e.getMessage()); - } - - //names cannot be blank or contain any of /\*?[] - String[] invalidNames = {"", "Sheet/", "Sheet\\", - "Sheet?", "Sheet*", "Sheet[", "Sheet]", "'Sheet'", - "My:Sheet"}; - for (String sheetName : invalidNames) { - try { - wb.createSheet(sheetName); - fail("should have thrown exception due to invalid sheet name: " + sheetName); - } catch (IllegalArgumentException e) { - // expected during successful test - } - } - //still have 3 sheets - assertEquals(3, wb.getNumberOfSheets()); - - //change the name of the 3rd sheet - wb.setSheetName(2, "I changed!"); - - //try to assign an invalid name to the 2nd sheet - try { - wb.setSheetName(1, "[I'm invalid]"); - fail("should have thrown exceptiuon due to invalid sheet name"); - } catch (IllegalArgumentException e) { - // expected during successful test - } - - //try to assign an invalid name to the 2nd sheet - try { - wb.createSheet(null); - fail("should have thrown exceptiuon due to invalid sheet name"); - } catch (IllegalArgumentException e) { - // expected during successful test - } - - try { - wb.setSheetName(2, null); - - fail("should have thrown exceptiuon due to invalid sheet name"); - } catch (IllegalArgumentException e) { - // expected during successful test - } - - //check - assertEquals(0, wb.getSheetIndex("sheet0")); - assertEquals(1, wb.getSheetIndex("sheet1")); - assertEquals(2, wb.getSheetIndex("I changed!")); - - assertSame(sheet0, wb.getSheet("sheet0")); - assertSame(sheet1, wb.getSheet("sheet1")); - assertSame(originalSheet, wb.getSheet("I changed!")); - assertNull(wb.getSheet("unknown")); - - //serialize and read again - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb); - wb.close(); - assertEquals(3, wb2.getNumberOfSheets()); - assertEquals(0, wb2.getSheetIndex("sheet0")); - assertEquals(1, wb2.getSheetIndex("sheet1")); - assertEquals(2, wb2.getSheetIndex("I changed!")); - wb2.close(); - } - - /** - * POI allows creating sheets with names longer than 31 characters. - * - * Excel opens files with long sheet names without error or warning. - * However, long sheet names are silently truncated to 31 chars. In order to - * avoid funny duplicate sheet name errors, POI enforces uniqueness on only the first 31 chars. - * but for the purpose of uniqueness long sheet names are silently truncated to 31 chars. - */ - @Test - public void createSheetWithLongNames() throws IOException { - Workbook wb1 = _testDataProvider.createWorkbook(); - - String sheetName1 = "My very long sheet name which is longer than 31 chars"; - String truncatedSheetName1 = sheetName1.substring(0, 31); - Sheet sh1 = wb1.createSheet(sheetName1); - assertEquals(truncatedSheetName1, sh1.getSheetName()); - assertSame(sh1, wb1.getSheet(truncatedSheetName1)); - // now via wb.setSheetName - wb1.setSheetName(0, sheetName1); - assertEquals(truncatedSheetName1, sh1.getSheetName()); - assertSame(sh1, wb1.getSheet(truncatedSheetName1)); - - String sheetName2 = "My very long sheet name which is longer than 31 chars " + - "and sheetName2.substring(0, 31) == sheetName1.substring(0, 31)"; - try { - /*Sheet sh2 =*/ wb1.createSheet(sheetName2); - fail("expected exception"); - } catch (IllegalArgumentException e) { - // expected during successful test - assertEquals("The workbook already contains a sheet named 'My very long sheet name which is longer than 31 chars and sheetName2.substring(0, 31) == sheetName1.substring(0, 31)'", e.getMessage()); - } - - String sheetName3 = "POI allows creating sheets with names longer than 31 characters"; - String truncatedSheetName3 = sheetName3.substring(0, 31); - Sheet sh3 = wb1.createSheet(sheetName3); - assertEquals(truncatedSheetName3, sh3.getSheetName()); - assertSame(sh3, wb1.getSheet(truncatedSheetName3)); - - //serialize and read again - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - wb1.close(); - assertEquals(2, wb2.getNumberOfSheets()); - assertEquals(0, wb2.getSheetIndex(truncatedSheetName1)); - assertEquals(1, wb2.getSheetIndex(truncatedSheetName3)); - wb2.close(); - } - - @Test - public void removeSheetAt() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - try { - workbook.createSheet("sheet1"); - workbook.createSheet("sheet2"); - workbook.createSheet("sheet3"); - assertEquals(3, workbook.getNumberOfSheets()); - - assertEquals(0, workbook.getActiveSheetIndex()); - - workbook.removeSheetAt(1); - assertEquals(2, workbook.getNumberOfSheets()); - assertEquals("sheet3", workbook.getSheetName(1)); - assertEquals(0, workbook.getActiveSheetIndex()); - - workbook.removeSheetAt(0); - assertEquals(1, workbook.getNumberOfSheets()); - assertEquals("sheet3", workbook.getSheetName(0)); - assertEquals(0, workbook.getActiveSheetIndex()); - - workbook.removeSheetAt(0); - assertEquals(0, workbook.getNumberOfSheets()); - assertEquals(0, workbook.getActiveSheetIndex()); - - //re-create the sheets - workbook.createSheet("sheet1"); - workbook.createSheet("sheet2"); - workbook.createSheet("sheet3"); - workbook.createSheet("sheet4"); - assertEquals(4, workbook.getNumberOfSheets()); - - assertEquals(0, workbook.getActiveSheetIndex()); - workbook.setActiveSheet(2); - assertEquals(2, workbook.getActiveSheetIndex()); - - workbook.removeSheetAt(2); - assertEquals(2, workbook.getActiveSheetIndex()); - - workbook.removeSheetAt(1); - assertEquals(1, workbook.getActiveSheetIndex()); - - workbook.removeSheetAt(0); - assertEquals(0, workbook.getActiveSheetIndex()); - - workbook.removeSheetAt(0); - assertEquals(0, workbook.getActiveSheetIndex()); - } finally { - workbook.close(); - } - } - - @Test - public void defaultValues() throws IOException { - Workbook b = _testDataProvider.createWorkbook(); - assertEquals(0, b.getActiveSheetIndex()); - assertEquals(0, b.getFirstVisibleTab()); - assertEquals(0, b.getNumberOfNames()); - assertEquals(0, b.getNumberOfSheets()); - b.close(); - } - - @Test - public void sheetSelection() throws IOException { - Workbook b = _testDataProvider.createWorkbook(); - b.createSheet("Sheet One"); - b.createSheet("Sheet Two"); - b.setActiveSheet(1); - b.setSelectedTab(1); - b.setFirstVisibleTab(1); - assertEquals(1, b.getActiveSheetIndex()); - assertEquals(1, b.getFirstVisibleTab()); - b.close(); - } - - @Test - public void printArea() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet1 = workbook.createSheet("Test Print Area"); - String sheetName1 = sheet1.getSheetName(); - - // workbook.setPrintArea(0, reference); - workbook.setPrintArea(0, 1, 5, 4, 9); - String retrievedPrintArea = workbook.getPrintArea(0); - assertEquals("'" + sheetName1 + "'!$B$5:$F$10", retrievedPrintArea); - - String reference = "$A$1:$B$1"; - workbook.setPrintArea(0, reference); - retrievedPrintArea = workbook.getPrintArea(0); - assertEquals("'" + sheetName1 + "'!" + reference, retrievedPrintArea); - - workbook.removePrintArea(0); - assertNull(workbook.getPrintArea(0)); - workbook.close(); - } - - @Test - public void getSetActiveSheet() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - assertEquals(0, workbook.getActiveSheetIndex()); - - workbook.createSheet("sheet1"); - workbook.createSheet("sheet2"); - workbook.createSheet("sheet3"); - // set second sheet - workbook.setActiveSheet(1); - // test if second sheet is set up - assertEquals(1, workbook.getActiveSheetIndex()); - - workbook.setActiveSheet(0); - // test if second sheet is set up - assertEquals(0, workbook.getActiveSheetIndex()); - workbook.close(); - } - - @Test - public void setSheetOrder() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - - for (int i=0; i < 10; i++) { - wb.createSheet("Sheet " + i); - } - - // Check the initial order - assertEquals(0, wb.getSheetIndex("Sheet 0")); - assertEquals(1, wb.getSheetIndex("Sheet 1")); - assertEquals(2, wb.getSheetIndex("Sheet 2")); - assertEquals(3, wb.getSheetIndex("Sheet 3")); - assertEquals(4, wb.getSheetIndex("Sheet 4")); - assertEquals(5, wb.getSheetIndex("Sheet 5")); - assertEquals(6, wb.getSheetIndex("Sheet 6")); - assertEquals(7, wb.getSheetIndex("Sheet 7")); - assertEquals(8, wb.getSheetIndex("Sheet 8")); - assertEquals(9, wb.getSheetIndex("Sheet 9")); - - // check active sheet - assertEquals(0, wb.getActiveSheetIndex()); - - // Change - wb.setSheetOrder("Sheet 6", 0); - assertEquals(1, wb.getActiveSheetIndex()); - wb.setSheetOrder("Sheet 3", 7); - wb.setSheetOrder("Sheet 1", 9); - - // now the first sheet is at index 1 - assertEquals(1, wb.getActiveSheetIndex()); - - // Check they're currently right - assertEquals(0, wb.getSheetIndex("Sheet 6")); - assertEquals(1, wb.getSheetIndex("Sheet 0")); - assertEquals(2, wb.getSheetIndex("Sheet 2")); - assertEquals(3, wb.getSheetIndex("Sheet 4")); - assertEquals(4, wb.getSheetIndex("Sheet 5")); - assertEquals(5, wb.getSheetIndex("Sheet 7")); - assertEquals(6, wb.getSheetIndex("Sheet 3")); - assertEquals(7, wb.getSheetIndex("Sheet 8")); - assertEquals(8, wb.getSheetIndex("Sheet 9")); - assertEquals(9, wb.getSheetIndex("Sheet 1")); - - Workbook wbr = _testDataProvider.writeOutAndReadBack(wb); - wb.close(); - - assertEquals(0, wbr.getSheetIndex("Sheet 6")); - assertEquals(1, wbr.getSheetIndex("Sheet 0")); - assertEquals(2, wbr.getSheetIndex("Sheet 2")); - assertEquals(3, wbr.getSheetIndex("Sheet 4")); - assertEquals(4, wbr.getSheetIndex("Sheet 5")); - assertEquals(5, wbr.getSheetIndex("Sheet 7")); - assertEquals(6, wbr.getSheetIndex("Sheet 3")); - assertEquals(7, wbr.getSheetIndex("Sheet 8")); - assertEquals(8, wbr.getSheetIndex("Sheet 9")); - assertEquals(9, wbr.getSheetIndex("Sheet 1")); - - assertEquals(1, wb.getActiveSheetIndex()); - - // Now get the index by the sheet, not the name - for(int i=0; i<10; i++) { - Sheet s = wbr.getSheetAt(i); - assertEquals(i, wbr.getSheetIndex(s)); - } - - wbr.close(); - } - - @Test - public void cloneSheet() throws IOException { - Workbook book = _testDataProvider.createWorkbook(); - Sheet sheet = book.createSheet("TEST"); - sheet.createRow(0).createCell(0).setCellValue("Test"); - sheet.createRow(1).createCell(0).setCellValue(36.6); - sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, 2)); - sheet.addMergedRegion(new CellRangeAddress(2, 3, 0, 2)); - assertTrue(sheet.isSelected()); - - Sheet clonedSheet = book.cloneSheet(0); - assertEquals("TEST (2)", clonedSheet.getSheetName()); - assertEquals(2, clonedSheet.getPhysicalNumberOfRows()); - assertEquals(2, clonedSheet.getNumMergedRegions()); - assertFalse(clonedSheet.isSelected()); - - //cloned sheet is a deep copy, adding rows or merged regions in the original does not affect the clone - sheet.createRow(2).createCell(0).setCellValue(1); - sheet.addMergedRegion(new CellRangeAddress(4, 5, 0, 2)); - assertEquals(2, clonedSheet.getPhysicalNumberOfRows()); - assertEquals(2, clonedSheet.getNumMergedRegions()); - - clonedSheet.createRow(2).createCell(0).setCellValue(1); - clonedSheet.addMergedRegion(new CellRangeAddress(6, 7, 0, 2)); - assertEquals(3, clonedSheet.getPhysicalNumberOfRows()); - assertEquals(3, clonedSheet.getNumMergedRegions()); - book.close(); - } - - @Test - public void parentReferences() throws IOException { - Workbook wb1 = _testDataProvider.createWorkbook(); - Sheet sheet = wb1.createSheet(); - assertSame(wb1, sheet.getWorkbook()); - - Row row = sheet.createRow(0); - assertSame(sheet, row.getSheet()); - - Cell cell = row.createCell(1); - assertSame(sheet, cell.getSheet()); - assertSame(row, cell.getRow()); - - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - wb1.close(); - sheet = wb2.getSheetAt(0); - assertSame(wb2, sheet.getWorkbook()); - - row = sheet.getRow(0); - assertSame(sheet, row.getSheet()); - - cell = row.getCell(1); - assertSame(sheet, cell.getSheet()); - assertSame(row, cell.getRow()); - wb2.close(); - } - - - /** - * Test to validate that replacement for removed setRepeatingRowsAnsColumns() methods - * is still working correctly - */ - @Test - public void setRepeatingRowsAnsColumns() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - - CellRangeAddress cra = new CellRangeAddress(0, 3, 0, 0); - String expRows = "1:4", expCols = "A:A"; - - - Sheet sheet1 = wb.createSheet(); - sheet1.setRepeatingRows(cra); - sheet1.setRepeatingColumns(cra); - assertEquals(expRows, sheet1.getRepeatingRows().formatAsString()); - assertEquals(expCols, sheet1.getRepeatingColumns().formatAsString()); - - //must handle sheets with quotas, see Bugzilla #47294 - Sheet sheet2 = wb.createSheet("My' Sheet"); - sheet2.setRepeatingRows(cra); - sheet2.setRepeatingColumns(cra); - assertEquals(expRows, sheet2.getRepeatingRows().formatAsString()); - assertEquals(expCols, sheet2.getRepeatingColumns().formatAsString()); - wb.close(); - } - - /** - * Tests that all of the unicode capable string fields can be set, written and then read back - */ - @Test - public void unicodeInAll() throws IOException { - Workbook wb1 = _testDataProvider.createWorkbook(); - CreationHelper factory = wb1.getCreationHelper(); - //Create a unicode dataformat (contains euro symbol) - DataFormat df = wb1.createDataFormat(); - final String formatStr = "_([$\u20ac-2]\\\\\\ * #,##0.00_);_([$\u20ac-2]\\\\\\ * \\\\\\(#,##0.00\\\\\\);_([$\u20ac-2]\\\\\\ *\\\"\\-\\\\\"??_);_(@_)"; - short fmt = df.getFormat(formatStr); - - //Create a unicode sheet name (euro symbol) - Sheet s = wb1.createSheet("\u20ac"); - - //Set a unicode header (you guessed it the euro symbol) - Header h = s.getHeader(); - h.setCenter("\u20ac"); - h.setLeft("\u20ac"); - h.setRight("\u20ac"); - - //Set a unicode footer - Footer f = s.getFooter(); - f.setCenter("\u20ac"); - f.setLeft("\u20ac"); - f.setRight("\u20ac"); - - Row r = s.createRow(0); - Cell c = r.createCell(1); - c.setCellValue(12.34); - c.getCellStyle().setDataFormat(fmt); - - /*Cell c2 =*/ r.createCell(2); // TODO - c2 unused but changing next line ('c'->'c2') causes test to fail - c.setCellValue(factory.createRichTextString("\u20ac")); - - Cell c3 = r.createCell(3); - String formulaString = "TEXT(12.34,\"\u20ac###,##\")"; - c3.setCellFormula(formulaString); - - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - wb1.close(); - - //Test the sheetname - s = wb2.getSheet("\u20ac"); - assertNotNull(s); - - //Test the header - h = s.getHeader(); - assertEquals(h.getCenter(), "\u20ac"); - assertEquals(h.getLeft(), "\u20ac"); - assertEquals(h.getRight(), "\u20ac"); - - //Test the footer - f = s.getFooter(); - assertEquals(f.getCenter(), "\u20ac"); - assertEquals(f.getLeft(), "\u20ac"); - assertEquals(f.getRight(), "\u20ac"); - - //Test the dataformat - r = s.getRow(0); - c = r.getCell(1); - df = wb2.createDataFormat(); - assertEquals(formatStr, df.getFormat(c.getCellStyle().getDataFormat())); - - //Test the cell string value - /*c2 =*/ r.getCell(2); - assertEquals(c.getRichStringCellValue().getString(), "\u20ac"); - - //Test the cell formula - c3 = r.getCell(3); - assertEquals(c3.getCellFormula(), formulaString); - wb2.close(); - } - - private Workbook newSetSheetNameTestingWorkbook() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sh1 = wb.createSheet("Worksheet"); - Sheet sh2 = wb.createSheet("Testing 47100"); - Sheet sh3 = wb.createSheet("To be renamed"); - - Name name1 = wb.createName(); - name1.setNameName("sale_1"); - name1.setRefersToFormula("Worksheet!$A$1"); - - Name name2 = wb.createName(); - name2.setNameName("sale_2"); - name2.setRefersToFormula("'Testing 47100'!$A$1"); - - Name name3 = wb.createName(); - name3.setNameName("sale_3"); - name3.setRefersToFormula("'Testing 47100'!$B$1"); - - Name name4 = wb.createName(); - name4.setNameName("sale_4"); - name4.setRefersToFormula("'To be renamed'!$A$3"); - - sh1.createRow(0).createCell(0).setCellFormula("SUM('Testing 47100'!A1:C1)"); - sh1.createRow(1).createCell(0).setCellFormula("SUM('Testing 47100'!A1:C1,'To be renamed'!A1:A5)"); - sh1.createRow(2).createCell(0).setCellFormula("sale_2+sale_3+'Testing 47100'!C1"); - - sh2.createRow(0).createCell(0).setCellValue(1); - sh2.getRow(0).createCell(1).setCellValue(2); - sh2.getRow(0).createCell(2).setCellValue(3); - - sh3.createRow(0).createCell(0).setCellValue(1); - sh3.createRow(1).createCell(0).setCellValue(2); - sh3.createRow(2).createCell(0).setCellValue(3); - sh3.createRow(3).createCell(0).setCellValue(4); - sh3.createRow(4).createCell(0).setCellValue(5); - sh3.createRow(5).createCell(0).setCellFormula("sale_3"); - sh3.createRow(6).createCell(0).setCellFormula("'Testing 47100'!C1"); - - return wb; - } - - /** - * Ensure that Workbook#setSheetName updates all dependent formulas and named ranges - * - * @see Bugzilla 47100 - */ - @Test - public void setSheetName() throws IOException { - - Workbook wb1 = newSetSheetNameTestingWorkbook(); - - Sheet sh1 = wb1.getSheetAt(0); - - Name sale_2 = wb1.getNameAt(1); - Name sale_3 = wb1.getNameAt(2); - Name sale_4 = wb1.getNameAt(3); - - assertEquals("sale_2", sale_2.getNameName()); - assertEquals("'Testing 47100'!$A$1", sale_2.getRefersToFormula()); - assertEquals("sale_3", sale_3.getNameName()); - assertEquals("'Testing 47100'!$B$1", sale_3.getRefersToFormula()); - assertEquals("sale_4", sale_4.getNameName()); - assertEquals("'To be renamed'!$A$3", sale_4.getRefersToFormula()); - - FormulaEvaluator evaluator = wb1.getCreationHelper().createFormulaEvaluator(); - - Cell cell0 = sh1.getRow(0).getCell(0); - Cell cell1 = sh1.getRow(1).getCell(0); - Cell cell2 = sh1.getRow(2).getCell(0); - - assertEquals("SUM('Testing 47100'!A1:C1)", cell0.getCellFormula()); - assertEquals("SUM('Testing 47100'!A1:C1,'To be renamed'!A1:A5)", cell1.getCellFormula()); - assertEquals("sale_2+sale_3+'Testing 47100'!C1", cell2.getCellFormula()); - - assertEquals(6.0, evaluator.evaluate(cell0).getNumberValue(), 0); - assertEquals(21.0, evaluator.evaluate(cell1).getNumberValue(), 0); - assertEquals(6.0, evaluator.evaluate(cell2).getNumberValue(), 0); - - wb1.setSheetName(1, "47100 - First"); - wb1.setSheetName(2, "47100 - Second"); - - assertEquals("sale_2", sale_2.getNameName()); - assertEquals("'47100 - First'!$A$1", sale_2.getRefersToFormula()); - assertEquals("sale_3", sale_3.getNameName()); - assertEquals("'47100 - First'!$B$1", sale_3.getRefersToFormula()); - assertEquals("sale_4", sale_4.getNameName()); - assertEquals("'47100 - Second'!$A$3", sale_4.getRefersToFormula()); - - assertEquals("SUM('47100 - First'!A1:C1)", cell0.getCellFormula()); - assertEquals("SUM('47100 - First'!A1:C1,'47100 - Second'!A1:A5)", cell1.getCellFormula()); - assertEquals("sale_2+sale_3+'47100 - First'!C1", cell2.getCellFormula()); - - evaluator.clearAllCachedResultValues(); - assertEquals(6.0, evaluator.evaluate(cell0).getNumberValue(), 0); - assertEquals(21.0, evaluator.evaluate(cell1).getNumberValue(), 0); - assertEquals(6.0, evaluator.evaluate(cell2).getNumberValue(), 0); - - Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1); - wb1.close(); - - sh1 = wb2.getSheetAt(0); - - sale_2 = wb2.getNameAt(1); - sale_3 = wb2.getNameAt(2); - sale_4 = wb2.getNameAt(3); - - cell0 = sh1.getRow(0).getCell(0); - cell1 = sh1.getRow(1).getCell(0); - cell2 = sh1.getRow(2).getCell(0); - - assertEquals("sale_2", sale_2.getNameName()); - assertEquals("'47100 - First'!$A$1", sale_2.getRefersToFormula()); - assertEquals("sale_3", sale_3.getNameName()); - assertEquals("'47100 - First'!$B$1", sale_3.getRefersToFormula()); - assertEquals("sale_4", sale_4.getNameName()); - assertEquals("'47100 - Second'!$A$3", sale_4.getRefersToFormula()); - - assertEquals("SUM('47100 - First'!A1:C1)", cell0.getCellFormula()); - assertEquals("SUM('47100 - First'!A1:C1,'47100 - Second'!A1:A5)", cell1.getCellFormula()); - assertEquals("sale_2+sale_3+'47100 - First'!C1", cell2.getCellFormula()); - - evaluator = wb2.getCreationHelper().createFormulaEvaluator(); - assertEquals(6.0, evaluator.evaluate(cell0).getNumberValue(), 0); - assertEquals(21.0, evaluator.evaluate(cell1).getNumberValue(), 0); - assertEquals(6.0, evaluator.evaluate(cell2).getNumberValue(), 0); - wb2.close(); - } - - protected void changeSheetNameWithSharedFormulas(String sampleFile) throws IOException { - Workbook wb = _testDataProvider.openSampleWorkbook(sampleFile); - - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - - Sheet sheet = wb.getSheetAt(0); - - for (int rownum = 1; rownum <= 40; rownum++) { - Cell cellA = sheet.getRow(1).getCell(0); - Cell cellB = sheet.getRow(1).getCell(1); - - assertEquals(cellB.getStringCellValue(), evaluator.evaluate(cellA).getStringValue()); - } - - wb.setSheetName(0, "Renamed by POI"); - evaluator.clearAllCachedResultValues(); - - for (int rownum = 1; rownum <= 40; rownum++) { - Cell cellA = sheet.getRow(1).getCell(0); - Cell cellB = sheet.getRow(1).getCell(1); - - assertEquals(cellB.getStringCellValue(), evaluator.evaluate(cellA).getStringValue()); - } - wb.close(); - } - - protected void assertSheetOrder(Workbook wb, String... sheets) { - StringBuilder sheetNames = new StringBuilder(); - for(int i = 0;i < wb.getNumberOfSheets();i++) { - sheetNames.append(wb.getSheetAt(i).getSheetName()).append(","); - } - assertEquals("Had: " + sheetNames.toString(), - sheets.length, wb.getNumberOfSheets()); - for(int i = 0;i < wb.getNumberOfSheets();i++) { - assertEquals("Had: " + sheetNames.toString(), - sheets[i], wb.getSheetAt(i).getSheetName()); - } - } - - @Test - public void test58499() throws IOException { - Workbook workbook = _testDataProvider.createWorkbook(); - Sheet sheet = workbook.createSheet(); - for (int i = 0; i < 900; i++) { - Row r = sheet.createRow(i); - Cell c = r.createCell(0); - CellStyle cs = workbook.createCellStyle(); - c.setCellStyle(cs); - c.setCellValue("AAA"); - } - OutputStream os = new NullOutputStream(); - try { - workbook.write(os); - } finally { - os.close(); - } - //workbook.dispose(); - workbook.close(); - } - - - @Test - public void windowOneDefaults() throws IOException { - Workbook b = _testDataProvider.createWorkbook(); - try { - assertEquals(b.getActiveSheetIndex(), 0); - assertEquals(b.getFirstVisibleTab(), 0); - } catch (NullPointerException npe) { - fail("WindowOneRecord in Workbook is probably not initialized"); - } - - b.close(); - } - - @Test - public void getSpreadsheetVersion() throws IOException { - final Workbook wb = _testDataProvider.createWorkbook(); - assertEquals(_testDataProvider.getSpreadsheetVersion(), wb.getSpreadsheetVersion()); - wb.close(); - } - - /* FIXME copied from {@link org.apache.poi.ss.TestWorkbookFactory} */ - protected static void assertCloseDoesNotModifyFile(String filename, Workbook wb) throws IOException { - final byte[] before = HSSFTestDataSamples.getTestDataFileContent(filename); - wb.close(); - final byte[] after = HSSFTestDataSamples.getTestDataFileContent(filename); - assertArrayEquals(filename + " sample file was modified as a result of closing the workbook", - before, after); - } - - @Test - public void sheetClone() throws IOException { - // First up, try a simple file - final Workbook b = _testDataProvider.createWorkbook(); - assertEquals(0, b.getNumberOfSheets()); - b.createSheet("Sheet One"); - b.createSheet("Sheet Two"); - - assertEquals(2, b.getNumberOfSheets()); - b.cloneSheet(0); - assertEquals(3, b.getNumberOfSheets()); - - // Now try a problem one with drawing records in it - Workbook bBack = HSSFTestDataSamples.openSampleWorkbook("SheetWithDrawing.xls"); - assertEquals(1, bBack.getNumberOfSheets()); - bBack.cloneSheet(0); - assertEquals(2, bBack.getNumberOfSheets()); - - bBack.close(); - b.close(); - } - - @Test - public void getSheetIndex() throws IOException { - final Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet1 = wb.createSheet("Sheet1"); - Sheet sheet2 = wb.createSheet("Sheet2"); - Sheet sheet3 = wb.createSheet("Sheet3"); - Sheet sheet4 = wb.createSheet("Sheet4"); - - assertEquals(0, wb.getSheetIndex(sheet1)); - assertEquals(1, wb.getSheetIndex(sheet2)); - assertEquals(2, wb.getSheetIndex(sheet3)); - assertEquals(3, wb.getSheetIndex(sheet4)); - - // remove sheets - wb.removeSheetAt(0); - wb.removeSheetAt(2); - - // ensure that sheets are moved up and removed sheets are not found any more - assertEquals(-1, wb.getSheetIndex(sheet1)); - assertEquals(0, wb.getSheetIndex(sheet2)); - assertEquals(1, wb.getSheetIndex(sheet3)); - assertEquals(-1, wb.getSheetIndex(sheet4)); - - wb.close(); - } - - @Test - public void addSheetTwice() throws IOException { - final Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet1 = wb.createSheet("Sheet1"); - assertNotNull(sheet1); - try { - wb.createSheet("Sheet1"); - fail("Should fail if we add the same sheet twice"); - } catch (IllegalArgumentException e) { - assertTrue(e.getMessage(), e.getMessage().contains("already contains a sheet named 'Sheet1'")); - } - - wb.close(); - } - - // bug 51233 and 55075: correctly size image if added to a row with a custom height - @Test - public void createDrawing() throws Exception { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sheet = wb.createSheet("Main Sheet"); - Row row0 = sheet.createRow(0); - Row row1 = sheet.createRow(1); - row1.createCell(0); - row0.createCell(1); - row1.createCell(0); - row1.createCell(1); - - byte[] pictureData = _testDataProvider.getTestDataFileContent("logoKarmokar4.png"); - - int handle = wb.addPicture(pictureData, Workbook.PICTURE_TYPE_PNG); - Drawing drawing = sheet.createDrawingPatriarch(); - CreationHelper helper = wb.getCreationHelper(); - ClientAnchor anchor = helper.createClientAnchor(); - anchor.setAnchorType(AnchorType.DONT_MOVE_AND_RESIZE); - anchor.setCol1(0); - anchor.setRow1(0); - Picture picture = drawing.createPicture(anchor, handle); - - row0.setHeightInPoints(144); - // set a column width so that XSSF and SXSSF have the same width (default widths may be different otherwise) - sheet.setColumnWidth(0, 100*256); - picture.resize(); - - // The actual dimensions don't matter as much as having XSSF and SXSSF produce the same size drawings - - // Check drawing height - assertEquals(0, anchor.getRow1()); - assertEquals(0, anchor.getRow2()); - assertEquals(0, anchor.getDy1()); - assertEquals(1609725, anchor.getDy2()); //HSSF: 225 - - // Check drawing width - assertEquals(0, anchor.getCol1()); - assertEquals(0, anchor.getCol2()); - assertEquals(0, anchor.getDx1()); - assertEquals(1114425, anchor.getDx2()); //HSSF: 171 - - final boolean writeOut = false; - if (writeOut) { - String ext = "." + _testDataProvider.getStandardFileNameExtension(); - String prefix = wb.getClass().getName() + "-createDrawing"; - File f = TempFile.createTempFile(prefix, ext); - FileOutputStream out = new FileOutputStream(f); - wb.write(out); - out.close(); - } - wb.close(); - } - -} diff --git a/src/testcases/org/apache/poi/ss/usermodel/TestDataFormatter.java b/src/testcases/org/apache/poi/ss/usermodel/TestDataFormatter.java deleted file mode 100644 index 4b196316e..000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/TestDataFormatter.java +++ /dev/null @@ -1,844 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - - 2012 - Alfresco Software, Ltd. - Alfresco Software has modified source of this file - The details of changes as svn diff can be found in svn at location root/projects/3rd-party/src -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.IOException; -import java.text.DateFormat; -import java.util.Calendar; -import java.util.Date; -import java.util.Locale; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.hssf.usermodel.TestHSSFDataFormatter; -import org.apache.poi.ss.format.CellFormat; -import org.apache.poi.ss.format.CellFormatResult; -import org.apache.poi.ss.util.CellReference; -import org.apache.poi.ss.util.NumberToTextConverter; -import org.apache.poi.util.LocaleUtil; -import org.apache.poi.util.SuppressForbidden; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; - -/** - * Tests of {@link DataFormatter} - * - * See {@link TestHSSFDataFormatter} too for - * more tests. - */ -public class TestDataFormatter { - private static final double _15_MINUTES = 0.041666667; - - @BeforeClass - @SuppressForbidden - public static void setUpClass() { - // some pre-checks to hunt for a problem in the Maven build - // these checks ensure that the correct locale is set, so a failure here - // usually indicates an invalid locale during test-execution - - assertFalse(DateUtil.isADateFormat(-1, "_-* #,##0.00_-;-* #,##0.00_-;_-* \"-\"??_-;_-@_-")); - Locale ul = LocaleUtil.getUserLocale(); - assertTrue(Locale.ROOT.equals(ul) || Locale.getDefault().equals(ul)); - final String textValue = NumberToTextConverter.toText(1234.56); - assertEquals(-1, textValue.indexOf('E')); - Object cellValueO = Double.valueOf(1234.56); - - /*CellFormat cellFormat = new CellFormat("_-* #,##0.00_-;-* #,##0.00_-;_-* \"-\"??_-;_-@_-"); - CellFormatResult result = cellFormat.apply(cellValueO); - assertEquals(" 1,234.56 ", result.text);*/ - - CellFormat cfmt = CellFormat.getInstance("_-* #,##0.00_-;-* #,##0.00_-;_-* \"-\"??_-;_-@_-"); - CellFormatResult result = cfmt.apply(cellValueO); - assertEquals("This failure can indicate that the wrong locale is used during test-execution, ensure you run with english/US via -Duser.language=en -Duser.country=US", - " 1,234.56 ", result.text); - } - - /** - * Test that we use the specified locale when deciding - * how to format normal numbers - */ - @Test - public void testLocale() { - DataFormatter dfUS = new DataFormatter(Locale.US); - DataFormatter dfFR = new DataFormatter(Locale.FRENCH); - - assertEquals("1234", dfUS.formatRawCellContents(1234, -1, "@")); - assertEquals("1234", dfFR.formatRawCellContents(1234, -1, "@")); - - assertEquals("12.34", dfUS.formatRawCellContents(12.34, -1, "@")); - assertEquals("12,34", dfFR.formatRawCellContents(12.34, -1, "@")); - } - - /** - * At the moment, we don't decode the locale strings into - * a specific locale, but we should format things as if - * the locale (eg '[$-1010409]') isn't there - */ - @Test - public void testLocaleBasedFormats() { - DataFormatter dfUS = new DataFormatter(Locale.US); - - // Standard formats - assertEquals("63", dfUS.formatRawCellContents(63.0, -1, "[$-1010409]General")); - assertEquals("63", dfUS.formatRawCellContents(63.0, -1, "[$-1010409]@")); - - // Regular numeric style formats - assertEquals("63", dfUS.formatRawCellContents(63.0, -1, "[$-1010409]##")); - assertEquals("63", dfUS.formatRawCellContents(63.0, -1, "[$-1010409]00")); - - } - - - /** - * Test that we use the specified locale when deciding - * how to format normal numbers - */ - @Test - public void testGrouping() { - DataFormatter dfUS = new DataFormatter(Locale.US); - DataFormatter dfDE = new DataFormatter(Locale.GERMAN); - - assertEquals("1,234.57", dfUS.formatRawCellContents(1234.567, -1, "#,##0.00")); - assertEquals("1'234.57", dfUS.formatRawCellContents(1234.567, -1, "#'##0.00")); - assertEquals("1 234.57", dfUS.formatRawCellContents(1234.567, -1, "# ##0.00")); - - assertEquals("1.234,57", dfDE.formatRawCellContents(1234.567, -1, "#,##0.00")); - assertEquals("1'234,57", dfDE.formatRawCellContents(1234.567, -1, "#'##0.00")); - assertEquals("1 234,57", dfDE.formatRawCellContents(1234.567, -1, "# ##0.00")); - } - - /** - * Ensure that colours get correctly - * zapped from within the format strings - */ - @Test - public void testColours() { - DataFormatter dfUS = new DataFormatter(Locale.US); - - String[] formats = { - "##.##", - "[WHITE]##.##", - "[BLACK]##.##;[RED]-##.##", - "[COLOR11]##.##;[COLOR 43]-##.00", - }; - for (String format : formats) { - assertEquals( - "Wrong format for: " + format, - "12.34", - dfUS.formatRawCellContents(12.343, -1, format) - ); - assertEquals( - "Wrong format for: " + format, - "-12.34", - dfUS.formatRawCellContents(-12.343, -1, format) - ); - } - - // Ensure that random square brackets remain - assertEquals("12.34[a]", dfUS.formatRawCellContents(12.343, -1, "##.##[a]")); - assertEquals("[ab]12.34[x]", dfUS.formatRawCellContents(12.343, -1, "[ab]##.##[x]")); - } - - @Test - public void testColoursAndBrackets() { - DataFormatter dfUS = new DataFormatter(Locale.US); - - // Without currency symbols - String[] formats = { "#,##0.00;[Blue](#,##0.00)" }; - for (String format : formats) { - assertEquals( - "Wrong format for: " + format, - "12.34", - dfUS.formatRawCellContents(12.343, -1, format) - ); - assertEquals( - "Wrong format for: " + format, - "(12.34)", - dfUS.formatRawCellContents(-12.343, -1, format) - ); - } - - // With - formats = new String[] { "$#,##0.00;[Red]($#,##0.00)" }; - for (String format : formats) { - assertEquals( - "Wrong format for: " + format, - "$12.34", - dfUS.formatRawCellContents(12.343, -1, format) - ); - assertEquals( - "Wrong format for: " + format, - "($12.34)", - dfUS.formatRawCellContents(-12.343, -1, format) - ); - } - } - - /** - * Test how we handle negative and zeros. - * Note - some tests are disabled as DecimalFormat - * and Excel differ, and workarounds are not - * yet in place for all of these - */ - @Test - public void testNegativeZero() { - DataFormatter dfUS = new DataFormatter(Locale.US); - - String all2dp = "00.00"; - String alln1dp = "(00.0)"; - String p1dp_n1dp = "00.0;(00.0)"; - String p2dp_n1dp = "00.00;(00.0)"; - String p2dp_n1dp_z0 = "00.00;(00.0);0"; - String all2dpTSP = "00.00_x"; - String p2dp_n2dpTSP = "00.00_x;(00.00)_x"; - //String p2dp_n1dpTSP = "00.00_x;(00.0)_x"; - - assertEquals("12.34", dfUS.formatRawCellContents(12.343, -1, all2dp)); - assertEquals("12.34", dfUS.formatRawCellContents(12.343, -1, p2dp_n1dp)); - assertEquals("12.34", dfUS.formatRawCellContents(12.343, -1, p2dp_n1dp_z0)); - - assertEquals("(12.3)", dfUS.formatRawCellContents(12.343, -1, alln1dp)); - assertEquals("-(12.3)", dfUS.formatRawCellContents(-12.343, -1, alln1dp)); - assertEquals("12.3", dfUS.formatRawCellContents(12.343, -1, p1dp_n1dp)); - assertEquals("(12.3)", dfUS.formatRawCellContents(-12.343, -1, p1dp_n1dp)); - - assertEquals("-12.34", dfUS.formatRawCellContents(-12.343, -1, all2dp)); - // TODO - fix case of negative subpattern differing from the - // positive one by more than just the prefix+suffix, which - // is all DecimalFormat supports... -// assertEquals("(12.3)", dfUS.formatRawCellContents(-12.343, -1, p2dp_n1dp)); -// assertEquals("(12.3)", dfUS.formatRawCellContents(-12.343, -1, p2dp_n1dp_z0)); - - assertEquals("00.00", dfUS.formatRawCellContents(0, -1, all2dp)); - assertEquals("00.00", dfUS.formatRawCellContents(0, -1, p2dp_n1dp)); - assertEquals("0", dfUS.formatRawCellContents(0, -1, p2dp_n1dp_z0)); - - // Spaces are skipped - assertEquals("12.34", dfUS.formatRawCellContents(12.343, -1, all2dpTSP)); - assertEquals("12.34", dfUS.formatRawCellContents(12.343, -1, p2dp_n2dpTSP)); - assertEquals("(12.34)", dfUS.formatRawCellContents(-12.343, -1, p2dp_n2dpTSP)); -// assertEquals("12.34", dfUS.formatRawCellContents(12.343, -1, p2dp_n1dpTSP)); -// assertEquals("(12.3)", dfUS.formatRawCellContents(-12.343, -1, p2dp_n1dpTSP)); - } - - /** - * Test that we correctly handle fractions in the - * format string, eg # #/# - */ - @Test - public void testFractions() { - DataFormatter dfUS = new DataFormatter(Locale.US); - - // Excel often prefers "# #/#" - assertEquals("321 1/3", dfUS.formatRawCellContents(321.321, -1, "# #/#")); - assertEquals("321 26/81", dfUS.formatRawCellContents(321.321, -1, "# #/##")); - assertEquals("26027/81", dfUS.formatRawCellContents(321.321, -1, "#/##")); - - // OOo seems to like the "# ?/?" form - assertEquals("321 1/3", dfUS.formatRawCellContents(321.321, -1, "# ?/?")); - assertEquals("321 26/81", dfUS.formatRawCellContents(321.321, -1, "# ?/??")); - assertEquals("26027/81", dfUS.formatRawCellContents(321.321, -1, "?/??")); - - // p;n;z;s parts - assertEquals("321 1/3", dfUS.formatRawCellContents(321.321, -1, "# #/#;# ##/#;0;xxx")); - assertEquals("321 1/3", dfUS.formatRawCellContents(-321.321, -1, "# #/#;# ##/#;0;xxx")); // Note the lack of - sign! - assertEquals("0", dfUS.formatRawCellContents(0, -1, "# #/#;# ##/#;0;xxx")); -// assertEquals(".", dfUS.formatRawCellContents(0, -1, "# #/#;# ##/#;#.#;xxx")); // Currently shows as 0. not . - - // Custom formats with text - assertEquals("+ve", dfUS.formatRawCellContents(1, -1, "+ve;-ve;zero;xxx")); - assertEquals("-ve", dfUS.formatRawCellContents(-1, -1, "-ve;-ve;zero;xxx")); - assertEquals("zero", dfUS.formatRawCellContents(0, -1, "zero;-ve;zero;xxx")); - - // Custom formats - check text is stripped, including multiple spaces - assertEquals("321 1/3", dfUS.formatRawCellContents(321.321, -1, "# #/#")); - assertEquals("321 1/3", dfUS.formatRawCellContents(321.321, -1, "#\" \" #/#")); - assertEquals("321 1/3", dfUS.formatRawCellContents(321.321, -1, "#\"FRED\" #/#")); - assertEquals("321 1/3", dfUS.formatRawCellContents(321.321, -1, "#\\ #/#")); - assertEquals("321 1/3", dfUS.formatRawCellContents(321.321, -1, "# \\q#/#")); - - // Cases that were very slow - assertEquals("321 1/3", dfUS.formatRawCellContents(321.321, -1, "0\" \"?/?;?/?")); // 0" "?/?;?/? - length of -ve part was used - assertEquals("321 1/3", dfUS.formatRawCellContents(321.321, -1, "0 \"#\"\\#\\#?/?")); // 0 "#"\#\#?/? - length of text was used - - assertEquals("321 295/919", dfUS.formatRawCellContents(321.321, -1, "# #/###")); - assertEquals("321 321/1000", dfUS.formatRawCellContents(321.321, -1, "# #/####")); // Code limits to #### as that is as slow as we want to get - assertEquals("321 321/1000", dfUS.formatRawCellContents(321.321, -1, "# #/##########")); - - // Not a valid fraction formats (too many #/# or ?/?) - hence the strange expected results -/* - assertEquals("321 / ?/?", dfUS.formatRawCellContents(321.321, -1, "# #/# ?/?")); - assertEquals("321 / /", dfUS.formatRawCellContents(321.321, -1, "# #/# #/#")); - assertEquals("321 ?/? ?/?", dfUS.formatRawCellContents(321.321, -1, "# ?/? ?/?")); - assertEquals("321 ?/? / /", dfUS.formatRawCellContents(321.321, -1, "# ?/? #/# #/#")); -*/ - - //Bug54686 patch sets default behavior of # #/## if there is a failure to parse - assertEquals("321 1/3", dfUS.formatRawCellContents(321.321, -1, "# #/# ?/?")); - assertEquals("321 1/3", dfUS.formatRawCellContents(321.321, -1, "# #/# #/#")); - assertEquals("321 1/3", dfUS.formatRawCellContents(321.321, -1, "# ?/? ?/?")); - assertEquals("321 1/3", dfUS.formatRawCellContents(321.321, -1, "# ?/? #/# #/#")); - - // Where +ve has a fraction, but -ve doesn't, we currently show both - assertEquals("123 1/3", dfUS.formatRawCellContents( 123.321, -1, "0 ?/?;0")); - //assertEquals("123", dfUS.formatRawCellContents(-123.321, -1, "0 ?/?;0")); - - //Bug54868 patch has a hit on the first string before the ";" - assertEquals("-123 1/3", dfUS.formatRawCellContents(-123.321, -1, "0 ?/?;0")); - - //Bug53150 formatting a whole number with fractions should just give the number - assertEquals("1", dfUS.formatRawCellContents(1.0, -1, "# #/#")); - assertEquals("11", dfUS.formatRawCellContents(11.0, -1, "# #/#")); - } - - /** - * Test that _x (blank with the space taken by "x") - * and *x (fill to the column width with "x"s) are - * correctly ignored by us. - */ - @Test - public void testPaddingSpaces() { - DataFormatter dfUS = new DataFormatter(Locale.US); - assertEquals("12.34", dfUS.formatRawCellContents(12.343, -1, "##.##_ ")); - assertEquals("12.34", dfUS.formatRawCellContents(12.343, -1, "##.##_1")); - assertEquals("12.34", dfUS.formatRawCellContents(12.343, -1, "##.##_)")); - assertEquals("12.34", dfUS.formatRawCellContents(12.343, -1, "_-##.##")); - - assertEquals("12.34", dfUS.formatRawCellContents(12.343, -1, "##.##* ")); - assertEquals("12.34", dfUS.formatRawCellContents(12.343, -1, "##.##*1")); - assertEquals("12.34", dfUS.formatRawCellContents(12.343, -1, "##.##*)")); - assertEquals("12.34", dfUS.formatRawCellContents(12.343, -1, "*-##.##")); - } - - /** - * DataFormatter is the CSV mode preserves spaces - */ - @Test - public void testPaddingSpacesCSV() { - DataFormatter dfUS = new DataFormatter(Locale.US, true); - assertEquals("12.34 ", dfUS.formatRawCellContents(12.343, -1, "##.##_ ")); - assertEquals("-12.34 ", dfUS.formatRawCellContents(-12.343, -1, "##.##_ ")); - assertEquals(". ", dfUS.formatRawCellContents(0.0, -1, "##.##_ ")); - assertEquals("12.34 ", dfUS.formatRawCellContents(12.343, -1, "##.##_1")); - assertEquals("-12.34 ", dfUS.formatRawCellContents(-12.343, -1, "##.##_1")); - assertEquals(". ", dfUS.formatRawCellContents(0.0, -1, "##.##_1")); - assertEquals("12.34 ", dfUS.formatRawCellContents(12.343, -1, "##.##_)")); - assertEquals("-12.34 ", dfUS.formatRawCellContents(-12.343, -1, "##.##_)")); - assertEquals(". ", dfUS.formatRawCellContents(0.0, -1, "##.##_)")); - assertEquals(" 12.34", dfUS.formatRawCellContents(12.343, -1, "_-##.##")); - assertEquals("- 12.34", dfUS.formatRawCellContents(-12.343, -1, "_-##.##")); - assertEquals(" .", dfUS.formatRawCellContents(0.0, -1, "_-##.##")); - - assertEquals("12.34", dfUS.formatRawCellContents(12.343, -1, "##.##* ")); - assertEquals("-12.34", dfUS.formatRawCellContents(-12.343, -1, "##.##* ")); - assertEquals(".", dfUS.formatRawCellContents(0.0, -1, "##.##* ")); - assertEquals("12.34", dfUS.formatRawCellContents(12.343, -1, "##.##*1")); - assertEquals("-12.34", dfUS.formatRawCellContents(-12.343, -1, "##.##*1")); - assertEquals(".", dfUS.formatRawCellContents(0.0, -1, "##.##*1")); - assertEquals("12.34", dfUS.formatRawCellContents(12.343, -1, "##.##*)")); - assertEquals("-12.34", dfUS.formatRawCellContents(-12.343, -1, "##.##*)")); - assertEquals(".", dfUS.formatRawCellContents(0.0, -1, "##.##*)")); - assertEquals("12.34", dfUS.formatRawCellContents(12.343, -1, "*-##.##")); - assertEquals("-12.34", dfUS.formatRawCellContents(-12.343, -1, "*-##.##")); - assertEquals(".", dfUS.formatRawCellContents(0.0, -1, "*-##.##")); - } - - /** - * Test that the special Excel month format MMMMM - * gets turned into the first letter of the month - */ - @Test - public void testMMMMM() { - DataFormatter dfUS = new DataFormatter(Locale.US); - - Calendar c = LocaleUtil.getLocaleCalendar(2010, 5, 1, 2, 0, 0); - - assertEquals("2010-J-1 2:00:00", dfUS.formatRawCellContents( - DateUtil.getExcelDate(c, false), -1, "YYYY-MMMMM-D h:mm:ss" - )); - } - - /** - * Tests that we do AM/PM handling properly - */ - @Test - public void testAMPM() { - DataFormatter dfUS = new DataFormatter(Locale.US); - - assertEquals("06:00", dfUS.formatRawCellContents(0.25, -1, "hh:mm")); - assertEquals("18:00", dfUS.formatRawCellContents(0.75, -1, "hh:mm")); - - assertEquals("06:00 AM", dfUS.formatRawCellContents(0.25, -1, "hh:mm AM/PM")); - assertEquals("06:00 PM", dfUS.formatRawCellContents(0.75, -1, "hh:mm AM/PM")); - - assertEquals("1904-01-01 06:00:00 AM", dfUS.formatRawCellContents(0.25, -1, "yyyy-mm-dd hh:mm:ss AM/PM", true)); - assertEquals("1904-01-01 06:00:00 PM", dfUS.formatRawCellContents(0.75, -1, "yyyy-mm-dd hh:mm:ss AM/PM", true)); - } - - /** - * Test that we can handle elapsed time, - * eg formatting 1 day 4 hours as 28 hours - */ - @Test - public void testElapsedTime() { - DataFormatter dfUS = new DataFormatter(Locale.US); - - double hour = 1.0/24.0; - - assertEquals("01:00", dfUS.formatRawCellContents(1*hour, -1, "hh:mm")); - assertEquals("05:00", dfUS.formatRawCellContents(5*hour, -1, "hh:mm")); - assertEquals("20:00", dfUS.formatRawCellContents(20*hour, -1, "hh:mm")); - assertEquals("23:00", dfUS.formatRawCellContents(23*hour, -1, "hh:mm")); - assertEquals("00:00", dfUS.formatRawCellContents(24*hour, -1, "hh:mm")); - assertEquals("02:00", dfUS.formatRawCellContents(26*hour, -1, "hh:mm")); - assertEquals("20:00", dfUS.formatRawCellContents(44*hour, -1, "hh:mm")); - assertEquals("02:00", dfUS.formatRawCellContents(50*hour, -1, "hh:mm")); - - assertEquals("01:00", dfUS.formatRawCellContents(1*hour, -1, "[hh]:mm")); - assertEquals("05:00", dfUS.formatRawCellContents(5*hour, -1, "[hh]:mm")); - assertEquals("20:00", dfUS.formatRawCellContents(20*hour, -1, "[hh]:mm")); - assertEquals("23:00", dfUS.formatRawCellContents(23*hour, -1, "[hh]:mm")); - assertEquals("24:00", dfUS.formatRawCellContents(24*hour, -1, "[hh]:mm")); - assertEquals("26:00", dfUS.formatRawCellContents(26*hour, -1, "[hh]:mm")); - assertEquals("44:00", dfUS.formatRawCellContents(44*hour, -1, "[hh]:mm")); - assertEquals("50:00", dfUS.formatRawCellContents(50*hour, -1, "[hh]:mm")); - - assertEquals("01", dfUS.formatRawCellContents(1*hour, -1, "[hh]")); - assertEquals("05", dfUS.formatRawCellContents(5*hour, -1, "[hh]")); - assertEquals("20", dfUS.formatRawCellContents(20*hour, -1, "[hh]")); - assertEquals("23", dfUS.formatRawCellContents(23*hour, -1, "[hh]")); - assertEquals("24", dfUS.formatRawCellContents(24*hour, -1, "[hh]")); - assertEquals("26", dfUS.formatRawCellContents(26*hour, -1, "[hh]")); - assertEquals("44", dfUS.formatRawCellContents(44*hour, -1, "[hh]")); - assertEquals("50", dfUS.formatRawCellContents(50*hour, -1, "[hh]")); - - double minute = 1.0/24.0/60.0; - assertEquals("01:00", dfUS.formatRawCellContents(1*minute, -1, "[mm]:ss")); - assertEquals("05:00", dfUS.formatRawCellContents(5*minute, -1, "[mm]:ss")); - assertEquals("20:00", dfUS.formatRawCellContents(20*minute, -1, "[mm]:ss")); - assertEquals("23:00", dfUS.formatRawCellContents(23*minute, -1, "[mm]:ss")); - assertEquals("24:00", dfUS.formatRawCellContents(24*minute, -1, "[mm]:ss")); - assertEquals("26:00", dfUS.formatRawCellContents(26*minute, -1, "[mm]:ss")); - assertEquals("44:00", dfUS.formatRawCellContents(44*minute, -1, "[mm]:ss")); - assertEquals("50:00", dfUS.formatRawCellContents(50*minute, -1, "[mm]:ss")); - assertEquals("59:00", dfUS.formatRawCellContents(59*minute, -1, "[mm]:ss")); - assertEquals("60:00", dfUS.formatRawCellContents(60*minute, -1, "[mm]:ss")); - assertEquals("61:00", dfUS.formatRawCellContents(61*minute, -1, "[mm]:ss")); - assertEquals("119:00", dfUS.formatRawCellContents(119*minute, -1, "[mm]:ss")); - assertEquals("120:00", dfUS.formatRawCellContents(120*minute, -1, "[mm]:ss")); - assertEquals("121:00", dfUS.formatRawCellContents(121*minute, -1, "[mm]:ss")); - - assertEquals("01", dfUS.formatRawCellContents(1*minute, -1, "[mm]")); - assertEquals("05", dfUS.formatRawCellContents(5*minute, -1, "[mm]")); - assertEquals("20", dfUS.formatRawCellContents(20*minute, -1, "[mm]")); - assertEquals("23", dfUS.formatRawCellContents(23*minute, -1, "[mm]")); - assertEquals("24", dfUS.formatRawCellContents(24*minute, -1, "[mm]")); - assertEquals("26", dfUS.formatRawCellContents(26*minute, -1, "[mm]")); - assertEquals("44", dfUS.formatRawCellContents(44*minute, -1, "[mm]")); - assertEquals("50", dfUS.formatRawCellContents(50*minute, -1, "[mm]")); - assertEquals("59", dfUS.formatRawCellContents(59*minute, -1, "[mm]")); - assertEquals("60", dfUS.formatRawCellContents(60*minute, -1, "[mm]")); - assertEquals("61", dfUS.formatRawCellContents(61*minute, -1, "[mm]")); - assertEquals("119", dfUS.formatRawCellContents(119*minute, -1, "[mm]")); - assertEquals("120", dfUS.formatRawCellContents(120*minute, -1, "[mm]")); - assertEquals("121", dfUS.formatRawCellContents(121*minute, -1, "[mm]")); - - double second = 1.0/24.0/60.0/60.0; - assertEquals("86400", dfUS.formatRawCellContents(86400*second, -1, "[ss]")); - assertEquals("01", dfUS.formatRawCellContents(1*second, -1, "[ss]")); - assertEquals("05", dfUS.formatRawCellContents(5*second, -1, "[ss]")); - assertEquals("20", dfUS.formatRawCellContents(20*second, -1, "[ss]")); - assertEquals("23", dfUS.formatRawCellContents(23*second, -1, "[ss]")); - assertEquals("24", dfUS.formatRawCellContents(24*second, -1, "[ss]")); - assertEquals("26", dfUS.formatRawCellContents(26*second, -1, "[ss]")); - assertEquals("44", dfUS.formatRawCellContents(44*second, -1, "[ss]")); - assertEquals("50", dfUS.formatRawCellContents(50*second, -1, "[ss]")); - assertEquals("59", dfUS.formatRawCellContents(59*second, -1, "[ss]")); - assertEquals("60", dfUS.formatRawCellContents(60*second, -1, "[ss]")); - assertEquals("61", dfUS.formatRawCellContents(61*second, -1, "[ss]")); - assertEquals("119", dfUS.formatRawCellContents(119*second, -1, "[ss]")); - assertEquals("120", dfUS.formatRawCellContents(120*second, -1, "[ss]")); - assertEquals("121", dfUS.formatRawCellContents(121*second, -1, "[ss]")); - - boolean jdk_1_5 = System.getProperty("java.vm.version").startsWith("1.5"); - if(!jdk_1_5) { - // YK: the tests below were written under JDK 1.6 and assume that - // the rounding mode in the underlying decimal formatters is HALF_UP - // It is not so JDK 1.5 where the default rounding mode is HALV_EVEN and cannot be changed. - - assertEquals("27:18:08", dfUS.formatRawCellContents(1.1376, -1, "[h]:mm:ss")); - assertEquals("28:48:00", dfUS.formatRawCellContents(1.2, -1, "[h]:mm:ss")); - assertEquals("29:31:12", dfUS.formatRawCellContents(1.23, -1, "[h]:mm:ss")); - assertEquals("31:26:24", dfUS.formatRawCellContents(1.31, -1, "[h]:mm:ss")); - - assertEquals("27:18:08", dfUS.formatRawCellContents(1.1376, -1, "[hh]:mm:ss")); - assertEquals("28:48:00", dfUS.formatRawCellContents(1.2, -1, "[hh]:mm:ss")); - assertEquals("29:31:12", dfUS.formatRawCellContents(1.23, -1, "[hh]:mm:ss")); - assertEquals("31:26:24", dfUS.formatRawCellContents(1.31, -1, "[hh]:mm:ss")); - - assertEquals("57:07.2", dfUS.formatRawCellContents(.123, -1, "mm:ss.0;@")); - assertEquals("57:41.8", dfUS.formatRawCellContents(.1234, -1, "mm:ss.0;@")); - assertEquals("57:41.76", dfUS.formatRawCellContents(.1234, -1, "mm:ss.00;@")); - assertEquals("57:41.760", dfUS.formatRawCellContents(.1234, -1, "mm:ss.000;@")); - assertEquals("24:00.0", dfUS.formatRawCellContents(123456.6, -1, "mm:ss.0")); - } - } - - @Test - public void testDateWindowing() { - DataFormatter dfUS = new DataFormatter(Locale.US); - - assertEquals("1899-12-31 00:00:00", dfUS.formatRawCellContents(0.0, -1, "yyyy-mm-dd hh:mm:ss")); - assertEquals("1899-12-31 00:00:00", dfUS.formatRawCellContents(0.0, -1, "yyyy-mm-dd hh:mm:ss", false)); - assertEquals("1904-01-01 00:00:00", dfUS.formatRawCellContents(0.0, -1, "yyyy-mm-dd hh:mm:ss", true)); - } - - @Test - public void testScientificNotation() { - DataFormatter dfUS = new DataFormatter(Locale.US); - - assertEquals("1.23E+01", dfUS.formatRawCellContents(12.343, -1, "0.00E+00")); - assertEquals("-1.23E+01", dfUS.formatRawCellContents(-12.343, -1, "0.00E+00")); - assertEquals("0.00E+00", dfUS.formatRawCellContents(0.0, -1, "0.00E+00")); - } - - @Test - public void testInvalidDate() { - DataFormatter df1 = new DataFormatter(Locale.US); - assertEquals("-1.0", df1.formatRawCellContents(-1, -1, "mm/dd/yyyy")); - - DataFormatter df2 = new DataFormatter(Locale.US, true); - assertEquals("###############################################################################################################################################################################################################################################################", - df2.formatRawCellContents(-1, -1, "mm/dd/yyyy")); - } - - @Test - public void testEscapes() { - DataFormatter dfUS = new DataFormatter(Locale.US); - - assertEquals("1901-01-01", dfUS.formatRawCellContents(367.0, -1, "yyyy-mm-dd")); - assertEquals("1901-01-01", dfUS.formatRawCellContents(367.0, -1, "yyyy\\-mm\\-dd")); - - assertEquals("1901.01.01", dfUS.formatRawCellContents(367.0, -1, "yyyy.mm.dd")); - assertEquals("1901.01.01", dfUS.formatRawCellContents(367.0, -1, "yyyy\\.mm\\.dd")); - - assertEquals("1901/01/01", dfUS.formatRawCellContents(367.0, -1, "yyyy/mm/dd")); - assertEquals("1901/01/01", dfUS.formatRawCellContents(367.0, -1, "yyyy\\/mm\\/dd")); - } - - @Test - public void testFormatsWithPadding() { - DataFormatter dfUS = new DataFormatter(Locale.US, true); - - // These request space-padding, based on the cell width - // There should always be one space after, variable (non-zero) amount before - // Because the Cell Width isn't available, this gets emulated with - // 4 leading spaces, or a minus then 3 leading spaces - // This isn't all that consistent, but it's the best we can really manage... - assertEquals(" 1,234.56 ", dfUS.formatRawCellContents( 1234.56, -1, "_-* #,##0.00_-;-* #,##0.00_-;_-* \"-\"??_-;_-@_-")); - assertEquals("- 1,234.56 ", dfUS.formatRawCellContents(-1234.56, -1, "_-* #,##0.00_-;-* #,##0.00_-;_-* \"-\"??_-;_-@_-")); - assertEquals(" 12.34 ", dfUS.formatRawCellContents( 12.34, -1, "_-* #,##0.00_-;-* #,##0.00_-;_-* \"-\"??_-;_-@_-")); - assertEquals("- 12.34 ", dfUS.formatRawCellContents(-12.34, -1, "_-* #,##0.00_-;-* #,##0.00_-;_-* \"-\"??_-;_-@_-")); - - assertEquals(" 0.10 ", dfUS.formatRawCellContents( 0.1, -1, "_-* #,##0.00_-;-* #,##0.00_-;_-* \"-\"??_-;_-@_-")); - assertEquals("- 0.10 ", dfUS.formatRawCellContents(-0.1, -1, "_-* #,##0.00_-;-* #,##0.00_-;_-* \"-\"??_-;_-@_-")); - // TODO Fix this, we are randomly adding a 0 at the end that shouldn't be there - //assertEquals(" - ", dfUS.formatRawCellContents(0.0, -1, "_-* #,##0.00_-;-* #,##0.00_-;_-* \"-\"??_-;_-@_-")); - - assertEquals(" $ 1.10 ", dfUS.formatRawCellContents( 1.1, -1, "_-$* #,##0.00_-;-$* #,##0.00_-;_-$* \"-\"??_-;_-@_-")); - assertEquals("-$ 1.10 ", dfUS.formatRawCellContents(-1.1, -1, "_-$* #,##0.00_-;-$* #,##0.00_-;_-$* \"-\"??_-;_-@_-")); - // TODO Fix this, we are randomly adding a 0 at the end that shouldn't be there - //assertEquals(" $ - ", dfUS.formatRawCellContents( 0.0, -1, "_-$* #,##0.00_-;-$* #,##0.00_-;_-$* \"-\"??_-;_-@_-")); - } - - @Test - public void testErrors() throws IOException { - DataFormatter dfUS = new DataFormatter(Locale.US, true); - - // Create a spreadsheet with some formula errors in it - Workbook wb = new HSSFWorkbook(); - try { - Sheet s = wb.createSheet(); - Row r = s.createRow(0); - Cell c = r.createCell(0, CellType.ERROR); - - c.setCellErrorValue(FormulaError.DIV0.getCode()); - assertEquals(FormulaError.DIV0.getString(), dfUS.formatCellValue(c)); - - c.setCellErrorValue(FormulaError.REF.getCode()); - assertEquals(FormulaError.REF.getString(), dfUS.formatCellValue(c)); - } finally { - wb.close(); - } - } - - @Test - public void testBoolean() throws IOException { - DataFormatter formatter = new DataFormatter(); - - // Create a spreadsheet with some TRUE/FALSE boolean values in it - Workbook wb = new HSSFWorkbook(); - try { - Sheet s = wb.createSheet(); - Row r = s.createRow(0); - Cell c = r.createCell(0); - - c.setCellValue(true); - assertEquals("TRUE", formatter.formatCellValue(c)); - - c.setCellValue(false); - assertEquals("FALSE", formatter.formatCellValue(c)); - } finally { - wb.close(); - } - } - - /** - * While we don't currently support using a locale code at - * the start of a format string to format it differently, we - * should at least handle it as it if wasn't there - */ - @Test - public void testDatesWithLocales() { - DataFormatter dfUS = new DataFormatter(Locale.US, true); - - String dateFormatEnglish = "[$-409]mmmm dd yyyy h:mm AM/PM"; - String dateFormatChinese = "[$-804]mmmm dd yyyy h:mm AM/PM"; - - // Check we format the English one correctly - double date = 26995.477777777778; - assertEquals( - "November 27 1973 11:28 AM", - dfUS.formatRawCellContents(date, -1, dateFormatEnglish) - ); - - // Check that, in the absence of locale support, we handle - // the Chinese one the same as the English one - assertEquals( - "November 27 1973 11:28 AM", - dfUS.formatRawCellContents(date, -1, dateFormatChinese) - ); - } - - /** - * TODO Fix these so that they work - */ - @Test - @Ignore - public void testCustomFormats() { - DataFormatter dfUS = new DataFormatter(Locale.US, true); - String fmt; - - fmt = "\"At\" H:MM AM/PM \"on\" DDDD MMMM D\",\" YYYY"; - assertEquals( - "At 4:20 AM on Thursday May 17, 2007", - dfUS.formatRawCellContents(39219.1805636921, -1, fmt) - ); - - fmt = "0 \"dollars and\" .00 \"cents\""; - assertEquals("19 dollars and .99 cents", dfUS.formatRawCellContents(19.99, -1, fmt)); - } - - /** - * ExcelStyleDateFormatter should work for Milliseconds too - */ - @Test - public void testExcelStyleDateFormatterStringOnMillis() { - // Test directly with the .000 style - DateFormat formatter1 = new ExcelStyleDateFormatter("ss.000"); - - assertEquals("00.001", formatter1.format(new Date(1L))); - assertEquals("00.010", formatter1.format(new Date(10L))); - assertEquals("00.100", formatter1.format(new Date(100L))); - assertEquals("01.000", formatter1.format(new Date(1000L))); - assertEquals("01.001", formatter1.format(new Date(1001L))); - assertEquals("10.000", formatter1.format(new Date(10000L))); - assertEquals("10.001", formatter1.format(new Date(10001L))); - - // Test directly with the .SSS style - DateFormat formatter2 = new ExcelStyleDateFormatter("ss.SSS"); - - assertEquals("00.001", formatter2.format(new Date(1L))); - assertEquals("00.010", formatter2.format(new Date(10L))); - assertEquals("00.100", formatter2.format(new Date(100L))); - assertEquals("01.000", formatter2.format(new Date(1000L))); - assertEquals("01.001", formatter2.format(new Date(1001L))); - assertEquals("10.000", formatter2.format(new Date(10000L))); - assertEquals("10.001", formatter2.format(new Date(10001L))); - - - // Test via DataFormatter - DataFormatter dfUS = new DataFormatter(Locale.US, true); - assertEquals("01.010", dfUS.formatRawCellContents(0.0000116898, -1, "ss.000")); - } - - @Test - public void testBug54786() { - DataFormatter formatter = new DataFormatter(); - String format = "[h]\"\"h\"\" m\"\"m\"\""; - assertTrue(DateUtil.isADateFormat(-1,format)); - assertTrue(DateUtil.isValidExcelDate(_15_MINUTES)); - - assertEquals("1h 0m", formatter.formatRawCellContents(_15_MINUTES, -1, format, false)); - assertEquals("0.041666667", formatter.formatRawCellContents(_15_MINUTES, -1, "[h]'h'", false)); - assertEquals("1h 0m\"", formatter.formatRawCellContents(_15_MINUTES, -1, "[h]\"\"h\"\" m\"\"m\"\"\"", false)); - assertEquals("1h", formatter.formatRawCellContents(_15_MINUTES, -1, "[h]\"\"h\"\"", false)); - assertEquals("h1", formatter.formatRawCellContents(_15_MINUTES, -1, "\"\"h\"\"[h]", false)); - assertEquals("h1", formatter.formatRawCellContents(_15_MINUTES, -1, "\"\"h\"\"h", false)); - assertEquals(" 60", formatter.formatRawCellContents(_15_MINUTES, -1, " [m]", false)); - assertEquals("h60", formatter.formatRawCellContents(_15_MINUTES, -1, "\"\"h\"\"[m]", false)); - assertEquals("m1", formatter.formatRawCellContents(_15_MINUTES, -1, "\"\"m\"\"h", false)); - - try { - assertEquals("1h 0m\"", formatter.formatRawCellContents(_15_MINUTES, -1, "[h]\"\"h\"\" m\"\"m\"\"\"\"", false)); - fail("Catches exception because of invalid format, i.e. trailing quoting"); - } catch (IllegalArgumentException e) { - assertTrue(e.getMessage().contains("Cannot format given Object as a Number")); - } - } - - @Test - public void testIsADateFormat() { - // first check some cases that should not be a date, also call multiple times to ensure the cache is used - assertFalse(DateUtil.isADateFormat(-1, null)); - assertFalse(DateUtil.isADateFormat(-1, null)); - assertFalse(DateUtil.isADateFormat(123, null)); - assertFalse(DateUtil.isADateFormat(123, "")); - assertFalse(DateUtil.isADateFormat(124, "")); - assertFalse(DateUtil.isADateFormat(-1, "")); - assertFalse(DateUtil.isADateFormat(-1, "")); - assertFalse(DateUtil.isADateFormat(-1, "nodateformat")); - - // then also do the same for some valid date formats - assertTrue(DateUtil.isADateFormat(0x0e, null)); - assertTrue(DateUtil.isADateFormat(0x2f, null)); - assertTrue(DateUtil.isADateFormat(-1, "yyyy")); - assertTrue(DateUtil.isADateFormat(-1, "yyyy")); - assertTrue(DateUtil.isADateFormat(-1, "dd/mm/yy;[red]dd/mm/yy")); - assertTrue(DateUtil.isADateFormat(-1, "dd/mm/yy;[red]dd/mm/yy")); - assertTrue(DateUtil.isADateFormat(-1, "[h]")); - } - - - @Test - public void testLargeNumbersAndENotation() throws IOException{ - assertFormatsTo("1E+86", 99999999999999999999999999999999999999999999999999999999999999999999999999999999999999d); - assertFormatsTo("1E-84", 0.000000000000000000000000000000000000000000000000000000000000000000000000000000000001d); - // Smallest double - assertFormatsTo("1E-323", 0.00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001d); - - // "up to 11 numeric characters, with the decimal point counting as a numeric character" - // https://support.microsoft.com/en-us/kb/65903 - assertFormatsTo( "12345678911", 12345678911d); - assertFormatsTo( "1.23457E+11", 123456789112d); // 12th digit of integer -> scientific - assertFormatsTo( "-12345678911", -12345678911d); - assertFormatsTo( "-1.23457E+11", -123456789112d); - assertFormatsTo( "0.1", 0.1); - assertFormatsTo( "0.000000001", 0.000000001); - assertFormatsTo( "1E-10", 0.0000000001); // 12th digit - assertFormatsTo( "-0.000000001", -0.000000001); - assertFormatsTo( "-1E-10", -0.0000000001); - assertFormatsTo( "123.4567892", 123.45678919); // excess decimals are simply rounded away - assertFormatsTo("-123.4567892", -123.45678919); - assertFormatsTo( "1.234567893", 1.2345678925); // rounding mode is half-up - assertFormatsTo("-1.234567893", -1.2345678925); - assertFormatsTo( "1.23457E+19", 12345650000000000000d); - assertFormatsTo("-1.23457E+19", -12345650000000000000d); - assertFormatsTo( "1.23457E-19", 0.0000000000000000001234565d); - assertFormatsTo("-1.23457E-19", -0.0000000000000000001234565d); - assertFormatsTo( "1.000000001", 1.000000001); - assertFormatsTo( "1", 1.0000000001); - assertFormatsTo( "1234.567891", 1234.567891123456789d); - assertFormatsTo( "1234567.891", 1234567.891123456789d); - assertFormatsTo( "12345678912", 12345678911.63456789d); // integer portion uses all 11 digits - assertFormatsTo( "12345678913", 12345678912.5d); // half-up here too - assertFormatsTo("-12345678913", -12345678912.5d); - assertFormatsTo( "1.23457E+11", 123456789112.3456789d); - } - - private static void assertFormatsTo(String expected, double input) throws IOException { - Workbook wb = new HSSFWorkbook(); - try { - Sheet s1 = wb.createSheet(); - Row row = s1.createRow(0); - Cell rawValue = row.createCell(0); - rawValue.setCellValue(input); - CellStyle newStyle = wb.createCellStyle(); - DataFormat dataFormat = wb.createDataFormat(); - newStyle.setDataFormat(dataFormat.getFormat("General")); - String actual = new DataFormatter().formatCellValue(rawValue); - assertEquals(expected, actual); - } - finally { - wb.close(); - } - } - - @Test - public void testFormulaEvaluation() throws IOException { - Workbook wb = HSSFTestDataSamples.openSampleWorkbook("FormulaEvalTestData.xls"); - - CellReference ref = new CellReference("D47"); - - Cell cell = wb.getSheetAt(0).getRow(ref.getRow()).getCell(ref.getCol()); - //noinspection deprecation - assertEquals(CellType.FORMULA, cell.getCellTypeEnum()); - assertEquals("G9:K9 I7:I12", cell.getCellFormula()); - - DataFormatter formatter = new DataFormatter(); - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - assertEquals("5.6789", formatter.formatCellValue(cell, evaluator)); - - wb.close(); - } - - /** - * bug 60031: DataFormatter parses months incorrectly when put at the end of date segment - */ - @Test - public void testBug60031() { - // 23-08-2016 08:51:01 which is 42605.368761574071 as double was parsed - // with format "yyyy-dd-MM HH:mm:ss" into "2016-23-51 08:51:01". - DataFormatter dfUS = new DataFormatter(Locale.US); - assertEquals("2016-23-08 08:51:01", dfUS.formatRawCellContents(42605.368761574071, -1, "yyyy-dd-MM HH:mm:ss")); - assertEquals("2016-23 08:51:01 08", dfUS.formatRawCellContents(42605.368761574071, -1, "yyyy-dd HH:mm:ss MM")); - assertEquals("2017-12-01 January 09:54:33", dfUS.formatRawCellContents(42747.412892397523, -1, "yyyy-dd-MM MMMM HH:mm:ss")); - assertEquals("08", dfUS.formatRawCellContents(42605.368761574071, -1, "MM")); - assertEquals("01", dfUS.formatRawCellContents(42605.368761574071, -1, "ss")); - - // From Excel help: - /* - The "m" or "mm" code must appear immediately after the "h" or"hh" - code or immediately before the "ss" code; otherwise, Microsoft - Excel displays the month instead of minutes." - */ - assertEquals("08", dfUS.formatRawCellContents(42605.368761574071, -1, "mm")); - assertEquals("08:51", dfUS.formatRawCellContents(42605.368761574071, -1, "hh:mm")); - assertEquals("51:01", dfUS.formatRawCellContents(42605.368761574071, -1, "mm:ss")); - } -} diff --git a/src/testcases/org/apache/poi/ss/usermodel/TestDateUtil.java b/src/testcases/org/apache/poi/ss/usermodel/TestDateUtil.java deleted file mode 100644 index 40dfd698f..000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/TestDateUtil.java +++ /dev/null @@ -1,126 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.util.Calendar; -import java.util.Date; -import java.util.TimeZone; - -import org.apache.poi.util.LocaleUtil; -import org.junit.Test; - -public class TestDateUtil { - - @Test - public void getJavaDate_InvalidValue() { - double dateValue = -1; - TimeZone tz = LocaleUtil.getUserTimeZone(); - boolean use1904windowing = false; - boolean roundSeconds = false; - - assertEquals(null, DateUtil.getJavaDate(dateValue)); - assertEquals(null, DateUtil.getJavaDate(dateValue, tz)); - assertEquals(null, DateUtil.getJavaDate(dateValue, use1904windowing)); - assertEquals(null, DateUtil.getJavaDate(dateValue, use1904windowing, tz)); - assertEquals(null, DateUtil.getJavaDate(dateValue, use1904windowing, tz, roundSeconds)); - } - - @Test - public void getJavaDate_ValidValue() { - double dateValue = 0; - TimeZone tz = LocaleUtil.getUserTimeZone(); - boolean use1904windowing = false; - boolean roundSeconds = false; - - Calendar calendar = LocaleUtil.getLocaleCalendar(1900, 0, 0); - Date date = calendar.getTime(); - - assertEquals(date, DateUtil.getJavaDate(dateValue)); - assertEquals(date, DateUtil.getJavaDate(dateValue, tz)); - assertEquals(date, DateUtil.getJavaDate(dateValue, use1904windowing)); - assertEquals(date, DateUtil.getJavaDate(dateValue, use1904windowing, tz)); - assertEquals(date, DateUtil.getJavaDate(dateValue, use1904windowing, tz, roundSeconds)); - } - - @Test - public void getJavaCalendar_InvalidValue() { - double dateValue = -1; - TimeZone tz = LocaleUtil.getUserTimeZone(); - boolean use1904windowing = false; - boolean roundSeconds = false; - - assertEquals(null, DateUtil.getJavaCalendar(dateValue)); - assertEquals(null, DateUtil.getJavaCalendar(dateValue, use1904windowing)); - assertEquals(null, DateUtil.getJavaCalendar(dateValue, use1904windowing, tz)); - assertEquals(null, DateUtil.getJavaCalendar(dateValue, use1904windowing, tz, roundSeconds)); - } - - @Test - public void getJavaCalendar_ValidValue() { - double dateValue = 0; - TimeZone tz = LocaleUtil.getUserTimeZone(); - boolean use1904windowing = false; - boolean roundSeconds = false; - - Calendar expCal = LocaleUtil.getLocaleCalendar(1900, 0, 0); - - Calendar actCal[] = { - DateUtil.getJavaCalendar(dateValue), - DateUtil.getJavaCalendar(dateValue, use1904windowing), - DateUtil.getJavaCalendar(dateValue, use1904windowing, tz), - DateUtil.getJavaCalendar(dateValue, use1904windowing, tz, roundSeconds) - }; - assertEquals(expCal, actCal[0]); - assertEquals(expCal, actCal[1]); - assertEquals(expCal, actCal[2]); - assertEquals(expCal, actCal[3]); - } - - @Test - public void isADateFormat() { - // Cell content 2016-12-8 as an example - // Cell show "12/8/2016" - assertTrue(DateUtil.isADateFormat(14, "m/d/yy")); - // Cell show "Thursday, December 8, 2016" - assertTrue(DateUtil.isADateFormat(182, "[$-F800]dddd\\,\\ mmmm\\ dd\\,\\ yyyy")); - // Cell show "12/8" - assertTrue(DateUtil.isADateFormat(183, "m/d;@")); - // Cell show "12/08/16" - assertTrue(DateUtil.isADateFormat(184, "mm/dd/yy;@")); - // Cell show "8-Dec-16" - assertTrue(DateUtil.isADateFormat(185, "[$-409]d\\-mmm\\-yy;@")); - // Cell show "D-16" - assertTrue(DateUtil.isADateFormat(186, "[$-409]mmmmm\\-yy;@")); - - // Cell show "2016年12月8日" - assertTrue(DateUtil.isADateFormat(165, "yyyy\"\u5e74\"m\"\u6708\"d\"\u65e5\";@")); - // Cell show "2016年12月" - assertTrue(DateUtil.isADateFormat(164, "yyyy\"\u5e74\"m\"\u6708\";@")); - // Cell show "12月8日" - assertTrue(DateUtil.isADateFormat(168, "m\"\u6708\"d\"\u65e5\";@")); - // Cell show "十二月八日" - assertTrue(DateUtil.isADateFormat(181, "[DBNum1][$-404]m\"\u6708\"d\"\u65e5\";@")); - // Cell show "贰零壹陆年壹拾贰月捌日" - assertTrue(DateUtil.isADateFormat(177, "[DBNum2][$-804]yyyy\"\u5e74\"m\"\u6708\"d\"\u65e5\";@")); - // Cell show "2016年12月8日" - assertTrue(DateUtil.isADateFormat(178, "[DBNum3][$-804]yyyy\"\u5e74\"m\"\u6708\"d\"\u65e5\";@")); - } -} diff --git a/src/testcases/org/apache/poi/ss/usermodel/TestExcelStyleDateFormatter.java b/src/testcases/org/apache/poi/ss/usermodel/TestExcelStyleDateFormatter.java deleted file mode 100644 index af5baf2fb..000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/TestExcelStyleDateFormatter.java +++ /dev/null @@ -1,160 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import java.text.DateFormatSymbols; -import java.text.FieldPosition; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Arrays; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import org.apache.poi.util.LocaleUtil; -import org.junit.Test; - -public class TestExcelStyleDateFormatter { - private static final String EXCEL_DATE_FORMAT = "MMMMM"; - - /** - * [Bug 60369] Month format 'MMMMM' issue with TEXT-formula and Java 8 - */ - @Test - public void test60369() throws ParseException { - // Setting up the locale to be tested together with a list of asserted unicode-formatted results and put them in a map. - Locale germanLocale = Locale.GERMAN; - List germanResultList = Arrays.asList("\u004a", "\u0046", "\u004d", "\u0041", "\u004d", - "\u004a", "\u004a", "\u0041", "\u0053", "\u004f", "\u004e", "\u0044"); - - Locale russianLocale = new Locale("ru", "RU"); - List russianResultList = Arrays.asList("\u044f", "\u0444", "\u043c", "\u0430", "\u043c", - "\u0438", "\u0438", "\u0430", "\u0441", "\u043e", "\u043d", "\u0434"); - - Locale austrianLocale = new Locale("de", "AT"); - List austrianResultList = Arrays.asList("\u004a", "\u0046", "\u004d", "\u0041", "\u004d", - "\u004a", "\u004a", "\u0041", "\u0053", "\u004f", "\u004e", "\u0044"); - - Locale englishLocale = Locale.UK; - List englishResultList = Arrays.asList("\u004a", "\u0046", "\u004d", "\u0041", "\u004d", - "\u004a", "\u004a", "\u0041", "\u0053", "\u004f", "\u004e", "\u0044"); - - Locale frenchLocale = Locale.FRENCH; - List frenchResultList = Arrays.asList("\u006a", "\u0066", "\u006d", "\u0061", "\u006d", - "\u006a", "\u006a", "\u0061", "\u0073", "\u006f", "\u006e", "\u0064"); - - Locale chineseLocale = Locale.CHINESE; - List chineseResultList = Arrays.asList("\u4e00", "\u4e8c", "\u4e09", "\u56db", "\u4e94", - "\u516d", "\u4e03", "\u516b", "\u4e5d", "\u5341", "\u5341", "\u5341"); - - Locale turkishLocale = new Locale("tr", "TR"); - List turkishResultList = Arrays.asList("\u004f", "\u015e", "\u004d", "\u004e", "\u004d", - "\u0048", "\u0054", "\u0041", "\u0045", "\u0045", "\u004b", "\u0041"); - - Locale hungarianLocale = new Locale("hu", "HU"); - List hungarianResultList = Arrays.asList("\u006a", "\u0066", "\u006d", "\u00e1", "\u006d", - "\u006a", "\u006a", "\u0061", "\u0073", "\u006f", "\u006e", "\u0064"); - - Locale indianLocale = new Locale("en", "IN"); - List indianResultList = Arrays.asList("\u004a", "\u0046", "\u004d", "\u0041", "\u004d", - "\u004a", "\u004a", "\u0041", "\u0053", "\u004f", "\u004e", "\u0044"); - - Locale indonesianLocale = new Locale("in", "ID"); - List indonesianResultList = Arrays.asList("\u004a", "\u0046", "\u004d", "\u0041", "\u004d", - "\u004a", "\u004a", "\u0041", "\u0053", "\u004f", "\u004e", "\u0044"); - - - Map> testMap = new HashMap>(); - testMap.put(germanLocale, germanResultList); - testMap.put(russianLocale, russianResultList); - testMap.put(austrianLocale, austrianResultList); - testMap.put(englishLocale, englishResultList); - testMap.put(frenchLocale, frenchResultList); - testMap.put(chineseLocale, chineseResultList); - testMap.put(turkishLocale, turkishResultList); - testMap.put(hungarianLocale, hungarianResultList); - testMap.put(indianLocale, indianResultList); - testMap.put(indonesianLocale, indonesianResultList); - - // We have to set up dates as well. - SimpleDateFormat testDateFormat = new SimpleDateFormat("dd.MM.yyyy", Locale.ROOT); - List testDates = Arrays.asList( - testDateFormat.parse("12.01.1980"), - testDateFormat.parse("11.02.1995"), - testDateFormat.parse("10.03.2045"), - testDateFormat.parse("09.04.2016"), - testDateFormat.parse("08.05.2017"), - testDateFormat.parse("07.06.1945"), - testDateFormat.parse("06.07.1998"), - testDateFormat.parse("05.08.2099"), - testDateFormat.parse("04.09.1988"), - testDateFormat.parse("03.10.2023"), - testDateFormat.parse("02.11.1978"), - testDateFormat.parse("01.12.1890")); - - // Let's iterate over the test setup. - for (Locale locale : testMap.keySet()) { - //System.err.println("Locale: " + locale); - ExcelStyleDateFormatter formatter = new ExcelStyleDateFormatter(EXCEL_DATE_FORMAT, new DateFormatSymbols(locale)); - for (int i = 0; i < 12; i++) { - // Call the method to be tested! - String result = - formatter.format(testDates.get(i), - new StringBuffer(), - new FieldPosition(java.text.DateFormat.MONTH_FIELD)).toString(); - //System.err.println(result + " - " + getUnicode(result.charAt(0))); - assertEquals(getUnicode(testMap.get(locale).get(i).charAt(0)), getUnicode(result.charAt(0))); - } - } - } - - private String getUnicode(char c) { - return "\\u" + Integer.toHexString(c | 0x10000).substring(1); - } - - @Test - public void testConstruct() { - assertNotNull(new ExcelStyleDateFormatter(EXCEL_DATE_FORMAT, LocaleUtil.getUserLocale())); - assertNotNull(new ExcelStyleDateFormatter(EXCEL_DATE_FORMAT)); - } - - @Test - public void testWithLocale() throws ParseException { - Locale before = LocaleUtil.getUserLocale(); - try { - LocaleUtil.setUserLocale(Locale.GERMAN); - String dateStr = new ExcelStyleDateFormatter(EXCEL_DATE_FORMAT).format( - new SimpleDateFormat("yyyy-MM-dd", Locale.ROOT).parse("2016-03-26")); - assertEquals("M", dateStr); - } finally { - LocaleUtil.setUserLocale(before); - } - } - - @Test - public void testWithPattern() throws ParseException { - String dateStr = new ExcelStyleDateFormatter("yyyy|" + EXCEL_DATE_FORMAT + "|").format( - new SimpleDateFormat("yyyy-MM-dd", Locale.ROOT).parse("2016-03-26")); - assertEquals("2016|M|", dateStr); - } -} diff --git a/src/testcases/org/apache/poi/ss/usermodel/TestFractionFormat.java b/src/testcases/org/apache/poi/ss/usermodel/TestFractionFormat.java deleted file mode 100644 index e99c3fe69..000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/TestFractionFormat.java +++ /dev/null @@ -1,84 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import static org.junit.Assert.assertEquals; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStreamReader; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.ss.usermodel.Row.MissingCellPolicy; -import org.apache.poi.util.LocaleUtil; -import org.junit.Test; - -/** - * Tests for the Fraction Formatting part of DataFormatter. - * Largely taken from bug #54686 - */ -public final class TestFractionFormat { - @Test - public void testSingle() throws Exception { - FractionFormat f = new FractionFormat("", "##"); - double val = 321.321; - String ret = f.format(val); - assertEquals("26027/81", ret); - } - - @Test - public void testTruthFile() throws Exception { - File truthFile = HSSFTestDataSamples.getSampleFile("54686_fraction_formats.txt"); - BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(truthFile), LocaleUtil.CHARSET_1252)); - Workbook wb = HSSFTestDataSamples.openSampleWorkbook("54686_fraction_formats.xls"); - Sheet sheet = wb.getSheetAt(0); - DataFormatter formatter = new DataFormatter(); - FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); - - // Skip over the header row - String truthLine = reader.readLine(); - String[] headers = truthLine.split("\t"); - truthLine = reader.readLine(); - - for (int i = 1; i < sheet.getLastRowNum() && truthLine != null; i++){ - Row r = sheet.getRow(i); - String[] truths = truthLine.split("\t"); - // Intentionally ignore the last column (tika-1132), for now - for (short j = 3; j < 12; j++){ - Cell cell = r.getCell(j, MissingCellPolicy.CREATE_NULL_AS_BLANK); - String formatted = clean(formatter.formatCellValue(cell, evaluator)); - if (truths.length <= j){ - continue; - } - - String truth = clean(truths[j]); - String testKey = truths[0]+":"+truths[1]+":"+headers[j]; - assertEquals(testKey, truth, formatted); - } - truthLine = reader.readLine(); - } - wb.close(); - reader.close(); - } - - private String clean(String s){ - s = s.trim().replaceAll(" +", " ").replaceAll("- +", "-"); - return s; - } -} diff --git a/src/testcases/org/apache/poi/ss/usermodel/TestHSSFBorderStyle.java b/src/testcases/org/apache/poi/ss/usermodel/TestHSSFBorderStyle.java deleted file mode 100644 index 721464573..000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/TestHSSFBorderStyle.java +++ /dev/null @@ -1,30 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import org.apache.poi.hssf.HSSFITestDataProvider; - -/** - * @author Yegor Kozlov - */ -public final class TestHSSFBorderStyle extends BaseTestBorderStyle { - - public TestHSSFBorderStyle() { - super(HSSFITestDataProvider.instance); - } -} \ No newline at end of file diff --git a/src/testcases/org/apache/poi/ss/usermodel/TestIndexedColors.java b/src/testcases/org/apache/poi/ss/usermodel/TestIndexedColors.java deleted file mode 100644 index 5ca6621e7..000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/TestIndexedColors.java +++ /dev/null @@ -1,56 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -import org.junit.Test; - -/** - * @author Yegor Kozlov - */ -public final class TestIndexedColors { - - @Test - public void fromInt() { - int[] illegalIndices = { -1, 0, 27, 65 }; - for (int index : illegalIndices) { - try { - IndexedColors.fromInt(index); - fail("Expected IllegalArgumentException: " + index); - } - catch (final IllegalArgumentException e) { - // expected - } - } - assertEquals(IndexedColors.BLACK, IndexedColors.fromInt(8)); - assertEquals(IndexedColors.GOLD, IndexedColors.fromInt(51)); - assertEquals(IndexedColors.AUTOMATIC, IndexedColors.fromInt(64)); - } - - @Test - public void getIndex() { - assertEquals(51, IndexedColors.GOLD.getIndex()); - } - - @Test - public void index() { - assertEquals(51, IndexedColors.GOLD.index); - } -} \ No newline at end of file diff --git a/src/testcases/org/apache/poi/ss/usermodel/charts/TestDataSources.java b/src/testcases/org/apache/poi/ss/usermodel/charts/TestDataSources.java deleted file mode 100644 index 6bf355128..000000000 --- a/src/testcases/org/apache/poi/ss/usermodel/charts/TestDataSources.java +++ /dev/null @@ -1,136 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.ss.usermodel.charts; - -import junit.framework.TestCase; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.SheetBuilder; - -/** - * Tests for {@link org.apache.poi.ss.usermodel.charts.DataSources}. - * - * @author Roman Kashitsyn - */ -public class TestDataSources extends TestCase { - - private static final Object[][] numericCells = { - {0.0, 1.0, 2.0, 3.0, 4.0}, - {0.0, "=B1*2", "=C1*2", "=D1*2", "=E1*2"} - }; - - private static final Object[][] stringCells = { - { 1, 2, 3, 4, 5}, - {"A", "B", "C", "D", "E"} - }; - - private static final Object[][] mixedCells = { - {1.0, "2.0", 3.0, "4.0", 5.0, "6.0"} - }; - - public void testNumericArrayDataSource() { - Double[] doubles = new Double[]{1.0, 2.0, 3.0, 4.0, 5.0}; - ChartDataSource doubleDataSource = DataSources.fromArray(doubles); - assertTrue(doubleDataSource.isNumeric()); - assertFalse(doubleDataSource.isReference()); - assertDataSourceIsEqualToArray(doubleDataSource, doubles); - } - - public void testStringArrayDataSource() { - String[] strings = new String[]{"one", "two", "three", "four", "five"}; - ChartDataSource stringDataSource = DataSources.fromArray(strings); - assertFalse(stringDataSource.isNumeric()); - assertFalse(stringDataSource.isReference()); - assertDataSourceIsEqualToArray(stringDataSource, strings); - } - - public void testNumericCellDataSource() { - Workbook wb = new HSSFWorkbook(); - Sheet sheet = new SheetBuilder(wb, numericCells).build(); - CellRangeAddress numCellRange = CellRangeAddress.valueOf("A2:E2"); - ChartDataSource numDataSource = DataSources.fromNumericCellRange(sheet, numCellRange); - assertTrue(numDataSource.isReference()); - assertTrue(numDataSource.isNumeric()); - assertEquals(numericCells[0].length, numDataSource.getPointCount()); - for (int i = 0; i < numericCells[0].length; ++i) { - assertEquals(((Number) numericCells[0][i]).doubleValue() * 2, - numDataSource.getPointAt(i).doubleValue(), 0.00001); - } - } - - public void testStringCellDataSource() { - Workbook wb = new HSSFWorkbook(); - Sheet sheet = new SheetBuilder(wb, stringCells).build(); - CellRangeAddress numCellRange = CellRangeAddress.valueOf("A2:E2"); - ChartDataSource numDataSource = DataSources.fromStringCellRange(sheet, numCellRange); - assertTrue(numDataSource.isReference()); - assertFalse(numDataSource.isNumeric()); - assertEquals(numericCells[0].length, numDataSource.getPointCount()); - for (int i = 0; i < stringCells[1].length; ++i) { - assertEquals(stringCells[1][i], numDataSource.getPointAt(i)); - } - } - - public void testMixedCellDataSource() { - Workbook wb = new HSSFWorkbook(); - Sheet sheet = new SheetBuilder(wb, mixedCells).build(); - CellRangeAddress mixedCellRange = CellRangeAddress.valueOf("A1:F1"); - ChartDataSource strDataSource = DataSources.fromStringCellRange(sheet, mixedCellRange); - ChartDataSource numDataSource = DataSources.fromNumericCellRange(sheet, mixedCellRange); - for (int i = 0; i < mixedCells[0].length; ++i) { - if (i % 2 == 0) { - assertNull(strDataSource.getPointAt(i)); - assertEquals(((Number) mixedCells[0][i]).doubleValue(), - numDataSource.getPointAt(i).doubleValue(), 0.00001); - } else { - assertNull(numDataSource.getPointAt(i)); - assertEquals(mixedCells[0][i], strDataSource.getPointAt(i)); - } - } - } - - public void testIOBExceptionOnInvalidIndex() { - Workbook wb = new HSSFWorkbook(); - Sheet sheet = new SheetBuilder(wb, numericCells).build(); - CellRangeAddress rangeAddress = CellRangeAddress.valueOf("A2:E2"); - ChartDataSource numDataSource = DataSources.fromNumericCellRange(sheet, rangeAddress); - IndexOutOfBoundsException exception = null; - try { - numDataSource.getPointAt(-1); - } catch (IndexOutOfBoundsException e) { - exception = e; - } - assertNotNull(exception); - - exception = null; - try { - numDataSource.getPointAt(numDataSource.getPointCount()); - } catch (IndexOutOfBoundsException e) { - exception = e; - } - assertNotNull(exception); - } - - private void assertDataSourceIsEqualToArray(ChartDataSource ds, T[] array) { - assertEquals(ds.getPointCount(), array.length); - for (int i = 0; i < array.length; ++i) { - assertEquals(ds.getPointAt(i), array[i]); - } - } -} diff --git a/src/testcases/org/apache/poi/ss/util/AllSSUtilTests.java b/src/testcases/org/apache/poi/ss/util/AllSSUtilTests.java deleted file mode 100644 index 569fadce7..000000000 --- a/src/testcases/org/apache/poi/ss/util/AllSSUtilTests.java +++ /dev/null @@ -1,41 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.util; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -/** - * Test suite for org.apache.poi.ss.util - * - * @author Josh Micich - */ -@RunWith(Suite.class) -@Suite.SuiteClasses({ - TestAreaReference.class, - //TestCellRangeAddress.class, //converted to junit4 - //TestCellReference.class, //converted to junit4 - TestDateFormatConverter.class, - TestExpandedDouble.class, - TestNumberComparer.class, - TestNumberToTextConverter.class, - TestSheetBuilder.class, - TestSheetUtil.class, - TestWorkbookUtil.class -}) -public class AllSSUtilTests { -} diff --git a/src/testcases/org/apache/poi/ss/util/BaseTestCellUtil.java b/src/testcases/org/apache/poi/ss/util/BaseTestCellUtil.java deleted file mode 100644 index ac88fdad4..000000000 --- a/src/testcases/org/apache/poi/ss/util/BaseTestCellUtil.java +++ /dev/null @@ -1,416 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - ==================================================================== */ - -package org.apache.poi.ss.util; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.fail; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -import org.apache.poi.ss.ITestDataProvider; -import org.apache.poi.ss.usermodel.BorderStyle; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.FillPatternType; -import org.apache.poi.ss.usermodel.Font; -import org.apache.poi.ss.usermodel.HorizontalAlignment; -import org.apache.poi.ss.usermodel.IndexedColors; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.VerticalAlignment; -import org.apache.poi.ss.usermodel.Workbook; -import org.junit.Test; - -/** - * Tests Spreadsheet CellUtil - * - * @see org.apache.poi.ss.util.CellUtil - */ -public class BaseTestCellUtil { - protected final ITestDataProvider _testDataProvider; - - protected BaseTestCellUtil(ITestDataProvider testDataProvider) { - _testDataProvider = testDataProvider; - } - - @Test - public void setCellStyleProperty() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet s = wb.createSheet(); - Row r = s.createRow(0); - Cell c = r.createCell(0); - - // Add a border should create a new style - int styCnt1 = wb.getNumCellStyles(); - CellUtil.setCellStyleProperty(c, CellUtil.BORDER_BOTTOM, BorderStyle.THIN); - int styCnt2 = wb.getNumCellStyles(); - assertEquals(styCnt1+1, styCnt2); - - // Add same border to another cell, should not create another style - c = r.createCell(1); - CellUtil.setCellStyleProperty(c, CellUtil.BORDER_BOTTOM, BorderStyle.THIN); - int styCnt3 = wb.getNumCellStyles(); - assertEquals(styCnt2, styCnt3); - - wb.close(); - } - - @Test(expected=RuntimeException.class) - public void setCellStylePropertyWithInvalidValue() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - try { - Sheet s = wb.createSheet(); - Row r = s.createRow(0); - Cell c = r.createCell(0); - - // An invalid BorderStyle constant - CellUtil.setCellStyleProperty(c, CellUtil.BORDER_BOTTOM, 42); - } finally { - wb.close(); - } - } - - @Test() - public void setCellStylePropertyBorderWithShortAndEnum() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet s = wb.createSheet(); - Row r = s.createRow(0); - Cell c = r.createCell(0); - - // A valid BorderStyle constant, as a Short - CellUtil.setCellStyleProperty(c, CellUtil.BORDER_BOTTOM, BorderStyle.DASH_DOT.getCode()); - assertEquals(BorderStyle.DASH_DOT, c.getCellStyle().getBorderBottomEnum()); - - // A valid BorderStyle constant, as an Enum - CellUtil.setCellStyleProperty(c, CellUtil.BORDER_TOP, BorderStyle.MEDIUM_DASH_DOT); - assertEquals(BorderStyle.MEDIUM_DASH_DOT, c.getCellStyle().getBorderTopEnum()); - - wb.close(); - } - - @Test - public void setCellStyleProperties() throws IOException { - System.out.println("setCellStyleProps start"); - Workbook wb = _testDataProvider.createWorkbook(); - Sheet s = wb.createSheet(); - Row r = s.createRow(0); - Cell c = r.createCell(0); - - // Add multiple border properties to cell should create a single new style - int styCnt1 = wb.getNumCellStyles(); - Map props = new HashMap(); - props.put(CellUtil.BORDER_TOP, BorderStyle.THIN); - props.put(CellUtil.BORDER_BOTTOM, BorderStyle.THIN); - props.put(CellUtil.BORDER_LEFT, BorderStyle.THIN); - props.put(CellUtil.BORDER_RIGHT, BorderStyle.THIN); - props.put(CellUtil.ALIGNMENT, HorizontalAlignment.CENTER.getCode()); // try it both with a Short (deprecated) - props.put(CellUtil.VERTICAL_ALIGNMENT, VerticalAlignment.CENTER); // and with an enum - CellUtil.setCellStyleProperties(c, props); - int styCnt2 = wb.getNumCellStyles(); - assertEquals("Only one additional style should have been created", styCnt1 + 1, styCnt2); - - // Add same border another to same cell, should not create another style - c = r.createCell(1); - CellUtil.setCellStyleProperties(c, props); - int styCnt3 = wb.getNumCellStyles(); - System.out.println("setCellStyleProps nearing end"); - assertEquals("No additional styles should have been created", styCnt2, styCnt3); - - wb.close(); - - } - - @Test - public void getRow() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sh = wb.createSheet(); - Row row1 = sh.createRow(0); - - // Get row that already exists - Row r1 = CellUtil.getRow(0, sh); - assertNotNull(r1); - assertSame("An existing row should not be recreated", row1, r1); - - // Get row that does not exist yet - assertNotNull(CellUtil.getRow(1, sh)); - - wb.close(); - } - - @Test - public void getCell() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sh = wb.createSheet(); - Row row = sh.createRow(0); - Cell A1 = row.createCell(0); - - // Get cell that already exists - Cell a1 = CellUtil.getCell(row, 0); - assertNotNull(a1); - assertSame("An existing cell should not be recreated", A1, a1); - - // Get cell that does not exist yet - assertNotNull(CellUtil.getCell(row, 1)); - - wb.close(); - } - - @Test - public void createCell() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sh = wb.createSheet(); - Row row = sh.createRow(0); - - CellStyle style = wb.createCellStyle(); - style.setWrapText(true); - - // calling createCell on a non-existing cell should create a cell and set the cell value and style. - Cell F1 = CellUtil.createCell(row, 5, "Cell Value", style); - - assertSame(row.getCell(5), F1); - assertEquals("Cell Value", F1.getStringCellValue()); - assertEquals(style, F1.getCellStyle()); - // should be assertSame, but a new HSSFCellStyle is returned for each getCellStyle() call. - // HSSFCellStyle wraps an underlying style record, and the underlying - // style record is the same between multiple getCellStyle() calls. - - // calling createCell on an existing cell should return the existing cell and modify the cell value and style. - Cell f1 = CellUtil.createCell(row, 5, "Overwritten cell value", null); - assertSame(row.getCell(5), f1); - assertSame(F1, f1); - assertEquals("Overwritten cell value", f1.getStringCellValue()); - assertEquals("Overwritten cell value", F1.getStringCellValue()); - assertEquals("cell style should be unchanged with createCell(..., null)", style, f1.getCellStyle()); - assertEquals("cell style should be unchanged with createCell(..., null)", style, F1.getCellStyle()); - - // test createCell(row, column, value) (no CellStyle) - f1 = CellUtil.createCell(row, 5, "Overwritten cell with default style"); - assertSame(F1, f1); - - wb.close(); - - } - - /** - * @deprecated by {@link #setAlignmentEnum()} - * - * @throws IOException - * - */ - @Deprecated - @SuppressWarnings("deprecated") - @Test - public void setAlignment() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sh = wb.createSheet(); - Row row = sh.createRow(0); - Cell A1 = row.createCell(0); - Cell B1 = row.createCell(1); - - // Assumptions - assertEquals(A1.getCellStyle(), B1.getCellStyle()); - // should be assertSame, but a new HSSFCellStyle is returned for each getCellStyle() call. - // HSSFCellStyle wraps an underlying style record, and the underlying - // style record is the same between multiple getCellStyle() calls. - assertEquals(CellStyle.ALIGN_GENERAL, A1.getCellStyle().getAlignment()); - assertEquals(CellStyle.ALIGN_GENERAL, B1.getCellStyle().getAlignment()); - - // get/set alignment modifies the cell's style - CellUtil.setAlignment(A1, null, CellStyle.ALIGN_RIGHT); - assertEquals(CellStyle.ALIGN_RIGHT, A1.getCellStyle().getAlignment()); - - // get/set alignment doesn't affect the style of cells with - // the same style prior to modifying the style - assertNotEquals(A1.getCellStyle(), B1.getCellStyle()); - assertEquals(CellStyle.ALIGN_GENERAL, B1.getCellStyle().getAlignment()); - - wb.close(); - } - - @Test - public void setAlignmentEnum() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sh = wb.createSheet(); - Row row = sh.createRow(0); - Cell A1 = row.createCell(0); - Cell B1 = row.createCell(1); - - // Assumptions - assertEquals(A1.getCellStyle(), B1.getCellStyle()); - // should be assertSame, but a new HSSFCellStyle is returned for each getCellStyle() call. - // HSSFCellStyle wraps an underlying style record, and the underlying - // style record is the same between multiple getCellStyle() calls. - assertEquals(HorizontalAlignment.GENERAL, A1.getCellStyle().getAlignmentEnum()); - assertEquals(HorizontalAlignment.GENERAL, B1.getCellStyle().getAlignmentEnum()); - - // get/set alignment modifies the cell's style - CellUtil.setAlignment(A1, HorizontalAlignment.RIGHT); - assertEquals(HorizontalAlignment.RIGHT, A1.getCellStyle().getAlignmentEnum()); - - // get/set alignment doesn't affect the style of cells with - // the same style prior to modifying the style - assertNotEquals(A1.getCellStyle(), B1.getCellStyle()); - assertEquals(HorizontalAlignment.GENERAL, B1.getCellStyle().getAlignmentEnum()); - - wb.close(); - } - - @Test - public void setVerticalAlignmentEnum() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sh = wb.createSheet(); - Row row = sh.createRow(0); - Cell A1 = row.createCell(0); - Cell B1 = row.createCell(1); - - // Assumptions - assertEquals(A1.getCellStyle(), B1.getCellStyle()); - // should be assertSame, but a new HSSFCellStyle is returned for each getCellStyle() call. - // HSSFCellStyle wraps an underlying style record, and the underlying - // style record is the same between multiple getCellStyle() calls. - assertEquals(VerticalAlignment.BOTTOM, A1.getCellStyle().getVerticalAlignmentEnum()); - assertEquals(VerticalAlignment.BOTTOM, B1.getCellStyle().getVerticalAlignmentEnum()); - - // get/set alignment modifies the cell's style - CellUtil.setVerticalAlignment(A1, VerticalAlignment.TOP); - assertEquals(VerticalAlignment.TOP, A1.getCellStyle().getVerticalAlignmentEnum()); - - // get/set alignment doesn't affect the style of cells with - // the same style prior to modifying the style - assertNotEquals(A1.getCellStyle(), B1.getCellStyle()); - assertEquals(VerticalAlignment.BOTTOM, B1.getCellStyle().getVerticalAlignmentEnum()); - - wb.close(); - } - - @Test - public void setFont() throws IOException { - Workbook wb = _testDataProvider.createWorkbook(); - Sheet sh = wb.createSheet(); - Row row = sh.createRow(0); - Cell A1 = row.createCell(0); - Cell B1 = row.createCell(1); - final short defaultFontIndex = 0; - Font font = wb.createFont(); - font.setItalic(true); - final short customFontIndex = font.getIndex(); - - // Assumptions - assertNotEquals(defaultFontIndex, customFontIndex); - assertEquals(A1.getCellStyle(), B1.getCellStyle()); - // should be assertSame, but a new HSSFCellStyle is returned for each getCellStyle() call. - // HSSFCellStyle wraps an underlying style record, and the underlying - // style record is the same between multiple getCellStyle() calls. - assertEquals(defaultFontIndex, A1.getCellStyle().getFontIndex()); - assertEquals(defaultFontIndex, B1.getCellStyle().getFontIndex()); - - // get/set alignment modifies the cell's style - CellUtil.setFont(A1, font); - assertEquals(customFontIndex, A1.getCellStyle().getFontIndex()); - - // get/set alignment doesn't affect the style of cells with - // the same style prior to modifying the style - assertNotEquals(A1.getCellStyle(), B1.getCellStyle()); - assertEquals(defaultFontIndex, B1.getCellStyle().getFontIndex()); - - wb.close(); - } - - @Test - public void setFontFromDifferentWorkbook() throws IOException { - Workbook wb1 = _testDataProvider.createWorkbook(); - Workbook wb2 = _testDataProvider.createWorkbook(); - Font font1 = wb1.createFont(); - Font font2 = wb2.createFont(); - // do something to make font1 and font2 different - // so they are not same or equal. - font1.setItalic(true); - Cell A1 = wb1.createSheet().createRow(0).createCell(0); - - // okay - CellUtil.setFont(A1, font1); - - // font belongs to different workbook - try { - CellUtil.setFont(A1, font2); - fail("setFont not allowed if font belongs to a different workbook"); - } catch (final IllegalArgumentException e) { - // one specific message is expected - if (!e.getMessage().startsWith("Font does not belong to this workbook")) { - throw e; - } - } finally { - wb1.close(); - wb2.close(); - } - } - - /** - * bug 55555 - * @deprecated Replaced by {@link #setFillForegroundColorBeforeFillBackgroundColorEnum()} - * @since POI 3.15 beta 3 - */ - @Deprecated - // bug 55555 - @Test - public void setFillForegroundColorBeforeFillBackgroundColor() throws IOException { - Workbook wb1 = _testDataProvider.createWorkbook(); - Cell A1 = wb1.createSheet().createRow(0).createCell(0); - Map properties = new HashMap(); - // FIXME: Use FillPatternType.BRICKS enum - properties.put(CellUtil.FILL_PATTERN, CellStyle.BRICKS); - properties.put(CellUtil.FILL_FOREGROUND_COLOR, IndexedColors.BLUE.index); - properties.put(CellUtil.FILL_BACKGROUND_COLOR, IndexedColors.RED.index); - - CellUtil.setCellStyleProperties(A1, properties); - CellStyle style = A1.getCellStyle(); - // FIXME: Use FillPatternType.BRICKS enum - assertEquals("fill pattern", CellStyle.BRICKS, style.getFillPattern()); - assertEquals("fill foreground color", IndexedColors.BLUE, IndexedColors.fromInt(style.getFillForegroundColor())); - assertEquals("fill background color", IndexedColors.RED, IndexedColors.fromInt(style.getFillBackgroundColor())); - wb1.close(); - } - /** - * bug 55555 - * @since POI 3.15 beta 3 - */ - @Test - public void setFillForegroundColorBeforeFillBackgroundColorEnum() throws IOException { - Workbook wb1 = _testDataProvider.createWorkbook(); - Cell A1 = wb1.createSheet().createRow(0).createCell(0); - Map properties = new HashMap(); - // FIXME: Use FillPatternType.BRICKS enum - properties.put(CellUtil.FILL_PATTERN, FillPatternType.BRICKS); - properties.put(CellUtil.FILL_FOREGROUND_COLOR, IndexedColors.BLUE.index); - properties.put(CellUtil.FILL_BACKGROUND_COLOR, IndexedColors.RED.index); - - CellUtil.setCellStyleProperties(A1, properties); - CellStyle style = A1.getCellStyle(); - // FIXME: Use FillPatternType.BRICKS enum - assertEquals("fill pattern", FillPatternType.BRICKS, style.getFillPatternEnum()); - assertEquals("fill foreground color", IndexedColors.BLUE, IndexedColors.fromInt(style.getFillForegroundColor())); - assertEquals("fill background color", IndexedColors.RED, IndexedColors.fromInt(style.getFillBackgroundColor())); - - wb1.close(); - } -} diff --git a/src/testcases/org/apache/poi/ss/util/NumberComparingSpreadsheetGenerator.java b/src/testcases/org/apache/poi/ss/util/NumberComparingSpreadsheetGenerator.java deleted file mode 100644 index 01bca5725..000000000 --- a/src/testcases/org/apache/poi/ss/util/NumberComparingSpreadsheetGenerator.java +++ /dev/null @@ -1,152 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.util; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFCellStyle; -import org.apache.poi.hssf.usermodel.HSSFFont; -import org.apache.poi.hssf.usermodel.HSSFRichTextString; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.util.NumberComparisonExamples.ComparisonExample; -import org.apache.poi.util.HexDump; - -/** - * Creates a spreadsheet that checks Excel's comparison of various IEEE double values. - * The class {@link NumberComparisonExamples} contains specific comparison examples - * (along with their expected results) that get encoded into rows of the spreadsheet. - * Each example is checked with a formula (in column I) that displays either "OK" or - * "ERROR" depending on whether actual results match those expected. - * - * @author Josh Micich - */ -public class NumberComparingSpreadsheetGenerator { - - private static final class SheetWriter { - - private final HSSFSheet _sheet; - private int _rowIndex; - - public SheetWriter(HSSFWorkbook wb) { - HSSFSheet sheet = wb.createSheet("Sheet1"); - - writeHeaderRow(wb, sheet); - _sheet = sheet; - _rowIndex = 1; - } - - public void addTestRow(double a, double b, int expResult) { - writeDataRow(_sheet, _rowIndex++, a, b, expResult); - } - } - - private static void writeHeaderCell(HSSFRow row, int i, String text, HSSFCellStyle style) { - HSSFCell cell = row.createCell(i); - cell.setCellValue(new HSSFRichTextString(text)); - cell.setCellStyle(style); - } - static void writeHeaderRow(HSSFWorkbook wb, HSSFSheet sheet) { - sheet.setColumnWidth(0, 6000); - sheet.setColumnWidth(1, 6000); - sheet.setColumnWidth(2, 3600); - sheet.setColumnWidth(3, 3600); - sheet.setColumnWidth(4, 2400); - sheet.setColumnWidth(5, 2400); - sheet.setColumnWidth(6, 2400); - sheet.setColumnWidth(7, 2400); - sheet.setColumnWidth(8, 2400); - HSSFRow row = sheet.createRow(0); - HSSFCellStyle style = wb.createCellStyle(); - HSSFFont font = wb.createFont(); - font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); - style.setFont(font); - writeHeaderCell(row, 0, "Raw Long Bits A", style); - writeHeaderCell(row, 1, "Raw Long Bits B", style); - writeHeaderCell(row, 2, "Value A", style); - writeHeaderCell(row, 3, "Value B", style); - writeHeaderCell(row, 4, "Exp Cmp", style); - writeHeaderCell(row, 5, "LT", style); - writeHeaderCell(row, 6, "EQ", style); - writeHeaderCell(row, 7, "GT", style); - writeHeaderCell(row, 8, "Check", style); - } - /** - * Fills a spreadsheet row with one comparison example. The two numeric values are written to - * columns C and D. Columns (F, G and H) respectively get formulas ("v0v1"), - * which will be evaluated by Excel. Column D gets the expected comparison result. Column I - * gets a formula to check that Excel's comparison results match that predicted in column D. - * - * @param v0 the first value to be compared - * @param v1 the second value to be compared - * @param expRes expected comparison result (-1, 0, or +1) - */ - static void writeDataRow(HSSFSheet sheet, int rowIx, double v0, double v1, int expRes) { - HSSFRow row = sheet.createRow(rowIx); - - int rowNum = rowIx + 1; - - - row.createCell(0).setCellValue(formatDoubleAsHex(v0)); - row.createCell(1).setCellValue(formatDoubleAsHex(v1)); - row.createCell(2).setCellValue(v0); - row.createCell(3).setCellValue(v1); - row.createCell(4).setCellValue(expRes < 0 ? "LT" : expRes > 0 ? "GT" : "EQ"); - row.createCell(5).setCellFormula("C" + rowNum + "<" + "D" + rowNum); - row.createCell(6).setCellFormula("C" + rowNum + "=" + "D" + rowNum); - row.createCell(7).setCellFormula("C" + rowNum + ">" + "D" + rowNum); - // TODO - bug elsewhere in POI - something wrong with encoding of NOT() function - String frm = "if(or(" + - "and(E#='LT', F# , G#=FALSE, H#=FALSE)," + - "and(E#='EQ', F#=FALSE, G# , H#=FALSE)," + - "and(E#='GT', F#=FALSE, G#=FALSE, H# )" + - "), 'OK', 'error')" ; - row.createCell(8).setCellFormula(frm.replaceAll("#", String.valueOf(rowNum)).replace('\'', '"')); - } - - private static String formatDoubleAsHex(double d) { - long l = Double.doubleToLongBits(d); - return HexDump.longToHex(l)+'L'; - } - - public static void main(String[] args) { - - HSSFWorkbook wb = new HSSFWorkbook(); - SheetWriter sw = new SheetWriter(wb); - ComparisonExample[] ces = NumberComparisonExamples.getComparisonExamples(); - for (ComparisonExample ce : ces) { - sw.addTestRow(ce.getA(), ce.getB(), ce.getExpectedResult()); - } - - - File outputFile = new File("ExcelNumberCompare.xls"); - - try { - FileOutputStream os = new FileOutputStream(outputFile); - wb.write(os); - os.close(); - } catch (IOException e) { - throw new RuntimeException(e); - } - System.out.println("Finished writing '" + outputFile.getAbsolutePath() + "'"); - } -} diff --git a/src/testcases/org/apache/poi/ss/util/NumberComparisonExamples.java b/src/testcases/org/apache/poi/ss/util/NumberComparisonExamples.java deleted file mode 100644 index 265e40d8c..000000000 --- a/src/testcases/org/apache/poi/ss/util/NumberComparisonExamples.java +++ /dev/null @@ -1,182 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.util; - -import java.util.ArrayList; -import java.util.List; - -/** - * Contains specific examples of double value pairs and their comparison result according to Excel. - * - * @author Josh Micich - */ -final class NumberComparisonExamples { - - private NumberComparisonExamples() { - // no instances of this class - } - - /** - * represents one comparison test case - */ - public static final class ComparisonExample { - private final long _rawBitsA; - private final long _rawBitsB; - private final int _expectedResult; - - public ComparisonExample(long rawBitsA, long rawBitsB, int expectedResult) { - _rawBitsA = rawBitsA; - _rawBitsB = rawBitsB; - _expectedResult = expectedResult; - } - - public double getA() { - return Double.longBitsToDouble(_rawBitsA); - } - public double getB() { - return Double.longBitsToDouble(_rawBitsB); - } - public double getNegA() { - return -Double.longBitsToDouble(_rawBitsA); - } - public double getNegB() { - return -Double.longBitsToDouble(_rawBitsB); - } - public int getExpectedResult() { - return _expectedResult; - } - } - - private static final ComparisonExample[] examples = initExamples(); - - private static ComparisonExample[] initExamples() { - - List temp = new ArrayList(); - - addStepTransition(temp, 0x4010000000000005L); - addStepTransition(temp, 0x4010000000000010L); - addStepTransition(temp, 0x401000000000001CL); - - addStepTransition(temp, 0x403CE0FFFFFFFFF1L); - - addStepTransition(temp, 0x5010000000000006L); - addStepTransition(temp, 0x5010000000000010L); - addStepTransition(temp, 0x501000000000001AL); - - addStepTransition(temp, 0x544CE6345CF32018L); - addStepTransition(temp, 0x544CE6345CF3205AL); - addStepTransition(temp, 0x544CE6345CF3209CL); - addStepTransition(temp, 0x544CE6345CF320DEL); - - addStepTransition(temp, 0x54B250001000101DL); - addStepTransition(temp, 0x54B2500010001050L); - addStepTransition(temp, 0x54B2500010001083L); - - addStepTransition(temp, 0x6230100010001000L); - addStepTransition(temp, 0x6230100010001005L); - addStepTransition(temp, 0x623010001000100AL); - - addStepTransition(temp, 0x7F50300020001011L); - addStepTransition(temp, 0x7F5030002000102BL); - addStepTransition(temp, 0x7F50300020001044L); - - - addStepTransition(temp, 0x2B2BFFFF1000102AL); - addStepTransition(temp, 0x2B2BFFFF10001079L); - addStepTransition(temp, 0x2B2BFFFF100010C8L); - - addStepTransition(temp, 0x2B2BFF001000102DL); - addStepTransition(temp, 0x2B2BFF0010001035L); - addStepTransition(temp, 0x2B2BFF001000103DL); - - addStepTransition(temp, 0x2B61800040002024L); - addStepTransition(temp, 0x2B61800040002055L); - addStepTransition(temp, 0x2B61800040002086L); - - - addStepTransition(temp, 0x008000000000000BL); - // just outside 'subnormal' range - addStepTransition(temp, 0x0010000000000007L); - addStepTransition(temp, 0x001000000000001BL); - addStepTransition(temp, 0x001000000000002FL); - - for(ComparisonExample ce : new ComparisonExample[] { - // negative, and exponents differ by more than 1 - ce(0xBF30000000000000L, 0xBE60000000000000L, -1), - - // negative zero *is* less than positive zero, but not easy to get out of calculations - ce(0x0000000000000000L, 0x8000000000000000L, +1), - // subnormal numbers compare without rounding for some reason - ce(0x0000000000000000L, 0x0000000000000001L, -1), - ce(0x0008000000000000L, 0x0008000000000001L, -1), - ce(0x000FFFFFFFFFFFFFL, 0x000FFFFFFFFFFFFEL, +1), - ce(0x000FFFFFFFFFFFFBL, 0x000FFFFFFFFFFFFCL, -1), - ce(0x000FFFFFFFFFFFFBL, 0x000FFFFFFFFFFFFEL, -1), - - // across subnormal threshold (some mistakes when close) - ce(0x000FFFFFFFFFFFFFL, 0x0010000000000000L, +1), - ce(0x000FFFFFFFFFFFFBL, 0x0010000000000007L, +1), - ce(0x000FFFFFFFFFFFFAL, 0x0010000000000007L, 0), - - // when a bit further apart - normal results - ce(0x000FFFFFFFFFFFF9L, 0x0010000000000007L, -1), - ce(0x000FFFFFFFFFFFFAL, 0x0010000000000008L, -1), - ce(0x000FFFFFFFFFFFFBL, 0x0010000000000008L, -1), - }) { - temp.add(ce); - } - - ComparisonExample[] result = new ComparisonExample[temp.size()]; - temp.toArray(result); - return result; - } - - private static ComparisonExample ce(long rawBitsA, long rawBitsB, int expectedResult) { - return new ComparisonExample(rawBitsA, rawBitsB, expectedResult); - } - - private static void addStepTransition(List temp, long rawBits) { - for(ComparisonExample ce : new ComparisonExample[] { - ce(rawBits-1, rawBits+0, 0), - ce(rawBits+0, rawBits+1, -1), - ce(rawBits+1, rawBits+2, 0), - }) { - temp.add(ce); - } - - } - - public static ComparisonExample[] getComparisonExamples() { - return examples.clone(); - } - - public static ComparisonExample[] getComparisonExamples2() { - ComparisonExample[] result = examples.clone(); - - for (int i = 0; i < result.length; i++) { - int ha = ("a"+i).hashCode(); - double a = ha * Math.pow(0.75, ha % 100); - int hb = ("b"+i).hashCode(); - double b = hb * Math.pow(0.75, hb % 100); - - result[i] = new ComparisonExample(Double.doubleToLongBits(a), Double.doubleToLongBits(b), Double.compare(a, b)); - } - - return result; - } -} diff --git a/src/testcases/org/apache/poi/ss/util/NumberRenderingSpreadsheetGenerator.java b/src/testcases/org/apache/poi/ss/util/NumberRenderingSpreadsheetGenerator.java deleted file mode 100644 index 0961134e6..000000000 --- a/src/testcases/org/apache/poi/ss/util/NumberRenderingSpreadsheetGenerator.java +++ /dev/null @@ -1,250 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.ss.util; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.DataInputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFCellStyle; -import org.apache.poi.hssf.usermodel.HSSFFont; -import org.apache.poi.hssf.usermodel.HSSFRichTextString; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.util.NumberToTextConversionExamples.ExampleConversion; -import org.apache.poi.util.HexDump; -import org.apache.poi.util.HexRead; - -/** - * Creates a spreadsheet that demonstrates Excel's rendering of various IEEE double values. - * - * @author Josh Micich - */ -public class NumberRenderingSpreadsheetGenerator { - - private static final class SheetWriter { - - private final HSSFSheet _sheet; - private int _rowIndex; - private final List _replacementNaNs; - - public SheetWriter(HSSFWorkbook wb) { - HSSFSheet sheet = wb.createSheet("Sheet1"); - - writeHeaderRow(wb, sheet); - _sheet = sheet; - _rowIndex = 1; - _replacementNaNs = new ArrayList(); - } - - public void addTestRow(long rawBits, String expectedExcelRendering) { - writeDataRow(_sheet, _rowIndex++, rawBits, expectedExcelRendering); - if(Double.isNaN(Double.longBitsToDouble(rawBits))) { - _replacementNaNs.add(Long.valueOf(rawBits)); - } - } - - public long[] getReplacementNaNs() { - int nRepls = _replacementNaNs.size(); - long[] result = new long[nRepls]; - for (int i = 0; i < nRepls; i++) { - result[i] = _replacementNaNs.get(i).longValue(); - } - return result; - } - - } - /** 0x7ff8000000000000 encoded in little endian order */ - private static final byte[] JAVA_NAN_BYTES = HexRead.readFromString("00 00 00 00 00 00 F8 7F"); - - private static void writeHeaderCell(HSSFRow row, int i, String text, HSSFCellStyle style) { - HSSFCell cell = row.createCell(i); - cell.setCellValue(new HSSFRichTextString(text)); - cell.setCellStyle(style); - } - static void writeHeaderRow(HSSFWorkbook wb, HSSFSheet sheet) { - sheet.setColumnWidth(0, 3000); - sheet.setColumnWidth(1, 6000); - sheet.setColumnWidth(2, 6000); - sheet.setColumnWidth(3, 6000); - sheet.setColumnWidth(4, 6000); - sheet.setColumnWidth(5, 1600); - sheet.setColumnWidth(6, 20000); - HSSFRow row = sheet.createRow(0); - HSSFCellStyle style = wb.createCellStyle(); - HSSFFont font = wb.createFont(); - font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); - style.setFont(font); - writeHeaderCell(row, 0, "Value", style); - writeHeaderCell(row, 1, "Raw Long Bits", style); - writeHeaderCell(row, 2, "JDK Double Rendering", style); - writeHeaderCell(row, 3, "Actual Rendering", style); - writeHeaderCell(row, 4, "Expected Rendering", style); - writeHeaderCell(row, 5, "Match", style); - writeHeaderCell(row, 6, "Java Metadata", style); - } - static void writeDataRow(HSSFSheet sheet, int rowIx, long rawLongBits, String expectedExcelRendering) { - double d = Double.longBitsToDouble(rawLongBits); - HSSFRow row = sheet.createRow(rowIx); - - int rowNum = rowIx + 1; - String cel0ref = "A" + rowNum; - String rawBitsText = formatLongAsHex(rawLongBits); - String jmExpr = "'ec(" + rawBitsText + ", ''\" & C" + rowNum + " & \"'', ''\" & D" + rowNum + " & \"''),'"; - - // The 'Match' column will contain 'OK' if the metadata (from NumberToTextConversionExamples) - // matches Excel's rendering. - String matchExpr = "if(D" + rowNum + "=E" + rowNum + ", \"OK\", \"ERROR\")"; - - row.createCell(0).setCellValue(d); - row.createCell(1).setCellValue(new HSSFRichTextString(rawBitsText)); - row.createCell(2).setCellValue(new HSSFRichTextString(Double.toString(d))); - row.createCell(3).setCellFormula("\"\" & " + cel0ref); - row.createCell(4).setCellValue(new HSSFRichTextString(expectedExcelRendering)); - row.createCell(5).setCellFormula(matchExpr); - row.createCell(6).setCellFormula(jmExpr.replaceAll("'", "\"")); - -// if (false) { -// // for observing arithmetic near numeric range boundaries -// row.createCell(7).setCellFormula(cel0ref + " * 1.0001"); -// row.createCell(8).setCellFormula(cel0ref + " / 1.0001"); -// } - } - - private static String formatLongAsHex(long l) { - StringBuilder sb = new StringBuilder(20); - sb.append(HexDump.longToHex(l)).append('L'); - return sb.toString(); - } - - public static void main(String[] args) { - writeJavaDoc(); - - HSSFWorkbook wb = new HSSFWorkbook(); - SheetWriter sw = new SheetWriter(wb); - - ExampleConversion[] exampleValues = NumberToTextConversionExamples.getExampleConversions(); - for (ExampleConversion example : exampleValues) { - sw.addTestRow(example.getRawDoubleBits(), example.getExcelRendering()); - } - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - try { - wb.write(baos); - } catch (IOException e) { - throw new RuntimeException(e); - } - byte[] fileContent = baos.toByteArray(); - replaceNaNs(fileContent, sw.getReplacementNaNs()); - - - File outputFile = new File("ExcelNumberRendering.xls"); - - try { - FileOutputStream os = new FileOutputStream(outputFile); - os.write(fileContent); - os.close(); - } catch (IOException e) { - throw new RuntimeException(e); - } - System.out.println("Finished writing '" + outputFile.getAbsolutePath() + "'"); - } - - public static void writeJavaDoc() { - - ExampleConversion[] exampleConversions = NumberToTextConversionExamples.getExampleConversions(); - for (ExampleConversion ec : exampleConversions) { - String line = " *

    - * Addresses Bug #16411 - */ - @Test - public void testNamedReadModify() throws Exception { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("namedinput.xls"); - - HSSFName name = wb.getNameAt(0); - String sheetName = wb.getSheetName(0); - - assertEquals(sheetName+"!$A$1:$D$10", name.getRefersToFormula()); - - name = wb.getNameAt(1); - String newReference = sheetName +"!$A$1:$C$36"; - - name.setRefersToFormula(newReference); - assertEquals(newReference, name.getRefersToFormula()); - - wb.close(); - } - - /** - * Test to see if the print area can be retrieved from an excel created file - */ - @Test - public void testPrintAreaFileRead() throws Exception { - HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook("SimpleWithPrintArea.xls"); - - String sheetName = workbook.getSheetName(0); - String reference = sheetName+"!$A$1:$C$5"; - - assertEquals(reference, workbook.getPrintArea(0)); - workbook.close(); - } - - @SuppressWarnings("deprecation") - @Test - public void testDeletedReference() throws Exception { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("24207.xls"); - assertEquals(2, wb.getNumberOfNames()); - - HSSFName name1 = wb.getNameAt(0); - assertEquals("a", name1.getNameName()); - assertEquals("Sheet1!$A$1", name1.getRefersToFormula()); - new AreaReference(name1.getRefersToFormula()); - assertTrue("Successfully constructed first reference", true); - - HSSFName name2 = wb.getNameAt(1); - assertEquals("b", name2.getNameName()); - assertEquals("Sheet1!#REF!", name2.getRefersToFormula()); - assertTrue(name2.isDeleted()); - try { - new AreaReference(name2.getRefersToFormula()); - fail("attempt to supply an invalid reference to AreaReference constructor results in exception"); - } catch (IllegalArgumentException e) { // TODO - use a stronger typed exception for this condition - // expected during successful test - } - wb.close(); - } - - /** - * When setting A1 type of references with HSSFName.setRefersToFormula - * must set the type of operands to Ptg.CLASS_REF, - * otherwise created named don't appear in the drop-down to the left of formula bar in Excel - */ - @Test - public void testTypeOfRootPtg() throws Exception { - HSSFWorkbook wb = new HSSFWorkbook(); - wb.createSheet("CSCO"); - - Ptg[] ptgs = HSSFFormulaParser.parse("CSCO!$E$71", wb, FormulaType.NAMEDRANGE, 0); - for (Ptg ptg : ptgs) { - assertEquals('R', ptg.getRVAType()); - } - wb.close(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFOptimiser.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFOptimiser.java deleted file mode 100644 index acb4974c1..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFOptimiser.java +++ /dev/null @@ -1,315 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ -package org.apache.poi.hssf.usermodel; - -import org.apache.poi.ss.usermodel.BorderStyle; - -import junit.framework.TestCase; - -public final class TestHSSFOptimiser extends TestCase { - public void testDoesNoHarmIfNothingToDo() { - HSSFWorkbook wb = new HSSFWorkbook(); - - // New files start with 4 built in fonts, and 21 built in styles - assertEquals(4, wb.getNumberOfFonts()); - assertEquals(21, wb.getNumCellStyles()); - - // Create a test font and style, and use them - HSSFFont f = wb.createFont(); - f.setFontName("Testing"); - HSSFCellStyle s = wb.createCellStyle(); - s.setFont(f); - - HSSFSheet sheet = wb.createSheet(); - HSSFRow row = sheet.createRow(0); - row.createCell(0).setCellStyle(s); - - // Should have one more than the default of each - assertEquals(5, wb.getNumberOfFonts()); - assertEquals(22, wb.getNumCellStyles()); - - // Optimise fonts - HSSFOptimiser.optimiseFonts(wb); - - assertEquals(5, wb.getNumberOfFonts()); - assertEquals(22, wb.getNumCellStyles()); - - assertEquals(f, s.getFont(wb)); - - // Optimise styles - HSSFOptimiser.optimiseCellStyles(wb); - - assertEquals(5, wb.getNumberOfFonts()); - assertEquals(22, wb.getNumCellStyles()); - - assertEquals(f, s.getFont(wb)); - } - - public void testOptimiseFonts() { - HSSFWorkbook wb = new HSSFWorkbook(); - - // Add 6 fonts, some duplicates - HSSFFont f1 = wb.createFont(); - f1.setFontHeight((short) 11); - f1.setFontName("Testing"); - - HSSFFont f2 = wb.createFont(); - f2.setFontHeight((short) 22); - f2.setFontName("Also Testing"); - - HSSFFont f3 = wb.createFont(); - f3.setFontHeight((short) 33); - f3.setFontName("Unique"); - - HSSFFont f4 = wb.createFont(); - f4.setFontHeight((short) 11); - f4.setFontName("Testing"); - - HSSFFont f5 = wb.createFont(); - f5.setFontHeight((short) 22); - f5.setFontName("Also Testing"); - - HSSFFont f6 = wb.createFont(); - f6.setFontHeight((short) 66); - f6.setFontName("Also Unique"); - - // Use all three of the four in cell styles - assertEquals(21, wb.getNumCellStyles()); - - HSSFCellStyle cs1 = wb.createCellStyle(); - cs1.setFont(f1); - assertEquals(5, cs1.getFontIndex()); - - HSSFCellStyle cs2 = wb.createCellStyle(); - cs2.setFont(f4); - assertEquals(8, cs2.getFontIndex()); - - HSSFCellStyle cs3 = wb.createCellStyle(); - cs3.setFont(f5); - assertEquals(9, cs3.getFontIndex()); - - HSSFCellStyle cs4 = wb.createCellStyle(); - cs4.setFont(f6); - assertEquals(10, cs4.getFontIndex()); - - assertEquals(25, wb.getNumCellStyles()); - - // And three in rich text - HSSFSheet s = wb.createSheet(); - HSSFRow r = s.createRow(0); - - HSSFRichTextString rtr1 = new HSSFRichTextString("Test"); - rtr1.applyFont(0, 2, f1); - rtr1.applyFont(3, 4, f2); - r.createCell(0).setCellValue(rtr1); - - HSSFRichTextString rtr2 = new HSSFRichTextString("AlsoTest"); - rtr2.applyFont(0, 2, f3); - rtr2.applyFont(3, 5, f5); - rtr2.applyFont(6, 8, f6); - r.createCell(1).setCellValue(rtr2); - - // Check what we have now - assertEquals(10, wb.getNumberOfFonts()); - assertEquals(25, wb.getNumCellStyles()); - - // Optimise - HSSFOptimiser.optimiseFonts(wb); - - // Check font count - assertEquals(8, wb.getNumberOfFonts()); - assertEquals(25, wb.getNumCellStyles()); - - // Check font use in cell styles - assertEquals(5, cs1.getFontIndex()); - assertEquals(5, cs2.getFontIndex()); // duplicate of 1 - assertEquals(6, cs3.getFontIndex()); // duplicate of 2 - assertEquals(8, cs4.getFontIndex()); // two have gone - - // And in rich text - - // RTR 1 had f1 and f2, unchanged - assertEquals(5, r.getCell(0).getRichStringCellValue().getFontAtIndex(0)); - assertEquals(5, r.getCell(0).getRichStringCellValue().getFontAtIndex(1)); - assertEquals(6, r.getCell(0).getRichStringCellValue().getFontAtIndex(3)); - assertEquals(6, r.getCell(0).getRichStringCellValue().getFontAtIndex(4)); - - // RTR 2 had f3 (unchanged), f5 (=f2) and f6 (moved down) - assertEquals(7, r.getCell(1).getRichStringCellValue().getFontAtIndex(0)); - assertEquals(7, r.getCell(1).getRichStringCellValue().getFontAtIndex(1)); - assertEquals(6, r.getCell(1).getRichStringCellValue().getFontAtIndex(3)); - assertEquals(6, r.getCell(1).getRichStringCellValue().getFontAtIndex(4)); - assertEquals(8, r.getCell(1).getRichStringCellValue().getFontAtIndex(6)); - assertEquals(8, r.getCell(1).getRichStringCellValue().getFontAtIndex(7)); - } - - public void testOptimiseStyles() { - HSSFWorkbook wb = new HSSFWorkbook(); - - // Two fonts - assertEquals(4, wb.getNumberOfFonts()); - - HSSFFont f1 = wb.createFont(); - f1.setFontHeight((short) 11); - f1.setFontName("Testing"); - - HSSFFont f2 = wb.createFont(); - f2.setFontHeight((short) 22); - f2.setFontName("Also Testing"); - - assertEquals(6, wb.getNumberOfFonts()); - - // Several styles - assertEquals(21, wb.getNumCellStyles()); - - HSSFCellStyle cs1 = wb.createCellStyle(); - cs1.setFont(f1); - - HSSFCellStyle cs2 = wb.createCellStyle(); - cs2.setFont(f2); - - HSSFCellStyle cs3 = wb.createCellStyle(); - cs3.setFont(f1); - - HSSFCellStyle cs4 = wb.createCellStyle(); - cs4.setFont(f1); - cs4.setAlignment((short) 22); - - HSSFCellStyle cs5 = wb.createCellStyle(); - cs5.setFont(f2); - cs5.setAlignment((short) 111); - - HSSFCellStyle cs6 = wb.createCellStyle(); - cs6.setFont(f2); - - assertEquals(27, wb.getNumCellStyles()); - - // Use them - HSSFSheet s = wb.createSheet(); - HSSFRow r = s.createRow(0); - - r.createCell(0).setCellStyle(cs1); - r.createCell(1).setCellStyle(cs2); - r.createCell(2).setCellStyle(cs3); - r.createCell(3).setCellStyle(cs4); - r.createCell(4).setCellStyle(cs5); - r.createCell(5).setCellStyle(cs6); - r.createCell(6).setCellStyle(cs1); - r.createCell(7).setCellStyle(cs2); - - assertEquals(21, r.getCell(0).getCellValueRecord().getXFIndex()); - assertEquals(26, r.getCell(5).getCellValueRecord().getXFIndex()); - assertEquals(21, r.getCell(6).getCellValueRecord().getXFIndex()); - - // Optimise - HSSFOptimiser.optimiseCellStyles(wb); - - // Check - assertEquals(6, wb.getNumberOfFonts()); - assertEquals(25, wb.getNumCellStyles()); - - // cs1 -> 21 - assertEquals(21, r.getCell(0).getCellValueRecord().getXFIndex()); - // cs2 -> 22 - assertEquals(22, r.getCell(1).getCellValueRecord().getXFIndex()); - assertEquals(22, r.getCell(1).getCellStyle().getFont(wb).getFontHeight()); - // cs3 = cs1 -> 21 - assertEquals(21, r.getCell(2).getCellValueRecord().getXFIndex()); - // cs4 --> 24 -> 23 - assertEquals(23, r.getCell(3).getCellValueRecord().getXFIndex()); - // cs5 --> 25 -> 24 - assertEquals(24, r.getCell(4).getCellValueRecord().getXFIndex()); - // cs6 = cs2 -> 22 - assertEquals(22, r.getCell(5).getCellValueRecord().getXFIndex()); - // cs1 -> 21 - assertEquals(21, r.getCell(6).getCellValueRecord().getXFIndex()); - // cs2 -> 22 - assertEquals(22, r.getCell(7).getCellValueRecord().getXFIndex()); - - - // Add a new duplicate, and two that aren't used - HSSFCellStyle csD = wb.createCellStyle(); - csD.setFont(f1); - r.createCell(8).setCellStyle(csD); - - HSSFFont f3 = wb.createFont(); - f3.setFontHeight((short) 23); - f3.setFontName("Testing 3"); - HSSFFont f4 = wb.createFont(); - f4.setFontHeight((short) 24); - f4.setFontName("Testing 4"); - - HSSFCellStyle csU1 = wb.createCellStyle(); - csU1.setFont(f3); - HSSFCellStyle csU2 = wb.createCellStyle(); - csU2.setFont(f4); - - // Check before the optimise - assertEquals(8, wb.getNumberOfFonts()); - assertEquals(28, wb.getNumCellStyles()); - - // Optimise, should remove the two un-used ones and the one duplicate - HSSFOptimiser.optimiseCellStyles(wb); - - // Check - assertEquals(8, wb.getNumberOfFonts()); - assertEquals(25, wb.getNumCellStyles()); - - // csD -> cs1 -> 21 - assertEquals(21, r.getCell(8).getCellValueRecord().getXFIndex()); - } - - public void testOptimiseStylesCheckActualStyles() { - HSSFWorkbook wb = new HSSFWorkbook(); - - // Several styles - assertEquals(21, wb.getNumCellStyles()); - - HSSFCellStyle cs1 = wb.createCellStyle(); - cs1.setBorderBottom(BorderStyle.THICK); - - HSSFCellStyle cs2 = wb.createCellStyle(); - cs2.setBorderBottom(BorderStyle.DASH_DOT); - - HSSFCellStyle cs3 = wb.createCellStyle(); // = cs1 - cs3.setBorderBottom(BorderStyle.THICK); - - assertEquals(24, wb.getNumCellStyles()); - - // Use them - HSSFSheet s = wb.createSheet(); - HSSFRow r = s.createRow(0); - - r.createCell(0).setCellStyle(cs1); - r.createCell(1).setCellStyle(cs2); - r.createCell(2).setCellStyle(cs3); - - assertEquals(21, r.getCell(0).getCellValueRecord().getXFIndex()); - assertEquals(22, r.getCell(1).getCellValueRecord().getXFIndex()); - assertEquals(23, r.getCell(2).getCellValueRecord().getXFIndex()); - - // Optimise - HSSFOptimiser.optimiseCellStyles(wb); - - // Check - assertEquals(23, wb.getNumCellStyles()); - - assertEquals(BorderStyle.THICK, r.getCell(0).getCellStyle().getBorderBottomEnum()); - assertEquals(BorderStyle.DASH_DOT, r.getCell(1).getCellStyle().getBorderBottomEnum()); - assertEquals(BorderStyle.THICK, r.getCell(2).getCellStyle().getBorderBottomEnum()); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPalette.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPalette.java deleted file mode 100644 index f2f572458..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPalette.java +++ /dev/null @@ -1,322 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; - -import java.awt.Color; -import java.io.IOException; -import java.util.Iterator; -import java.util.Map; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.record.PaletteRecord; -import org.apache.poi.hssf.util.HSSFColor; -import org.apache.poi.hssf.util.HSSFColor.HSSFColorPredefined; -import org.apache.poi.ss.usermodel.FillPatternType; -import org.apache.poi.ss.usermodel.Font; -import org.junit.Before; -import org.junit.Test; - -public final class TestHSSFPalette { - private PaletteRecord _palette; - private HSSFPalette _hssfPalette; - - - @Before - public void setUp() { - _palette = new PaletteRecord(); - _hssfPalette = new HSSFPalette(_palette); - } - - /** - * Verifies that a custom palette can be created, saved, and reloaded - */ - @Test - public void testCustomPalette() { - //reading sample xls - HSSFWorkbook book = HSSFTestDataSamples.openSampleWorkbook("Simple.xls"); - - //creating custom palette - HSSFPalette palette = book.getCustomPalette(); - palette.setColorAtIndex((short) 0x12, (byte) 101, (byte) 230, (byte) 100); - palette.setColorAtIndex((short) 0x3b, (byte) 0, (byte) 255, (byte) 52); - - //writing to disk; reading in and verifying palette - book = HSSFTestDataSamples.writeOutAndReadBack(book); - - palette = book.getCustomPalette(); - HSSFColor color = palette.getColor(HSSFColorPredefined.CORAL.getIndex()); //unmodified - assertNotNull("Unexpected null in custom palette (unmodified index)", color); - short[] expectedRGB = HSSFColorPredefined.CORAL.getTriplet(); - short[] actualRGB = color.getTriplet(); - String msg = "Expected palette position to remain unmodified"; - assertEquals(msg, expectedRGB[0], actualRGB[0]); - assertEquals(msg, expectedRGB[1], actualRGB[1]); - assertEquals(msg, expectedRGB[2], actualRGB[2]); - - color = palette.getColor((short) 0x12); - assertNotNull("Unexpected null in custom palette (modified)", color); - actualRGB = color.getTriplet(); - msg = "Expected palette modification to be preserved across save"; - assertEquals(msg, (short) 101, actualRGB[0]); - assertEquals(msg, (short) 230, actualRGB[1]); - assertEquals(msg, (short) 100, actualRGB[2]); - } - - /** - * Uses the palette from cell stylings - */ - @Test - public void testPaletteFromCellColours() { - HSSFWorkbook book = HSSFTestDataSamples.openSampleWorkbook("SimpleWithColours.xls"); - - HSSFPalette p = book.getCustomPalette(); - - HSSFCell cellA = book.getSheetAt(0).getRow(0).getCell(0); - HSSFCell cellB = book.getSheetAt(0).getRow(1).getCell(0); - HSSFCell cellC = book.getSheetAt(0).getRow(2).getCell(0); - HSSFCell cellD = book.getSheetAt(0).getRow(3).getCell(0); - HSSFCell cellE = book.getSheetAt(0).getRow(4).getCell(0); - - // Plain - assertEquals("I'm plain", cellA.getStringCellValue()); - assertEquals(64, cellA.getCellStyle().getFillForegroundColor()); - assertEquals(64, cellA.getCellStyle().getFillBackgroundColor()); - assertEquals(Font.COLOR_NORMAL, cellA.getCellStyle().getFont(book).getColor()); - assertEquals(FillPatternType.NO_FILL, cellA.getCellStyle().getFillPatternEnum()); - assertEquals("0:0:0", p.getColor((short)64).getHexString()); - assertEquals(null, p.getColor((short)32767)); - - // Red - assertEquals("I'm red", cellB.getStringCellValue()); - assertEquals(64, cellB.getCellStyle().getFillForegroundColor()); - assertEquals(64, cellB.getCellStyle().getFillBackgroundColor()); - assertEquals(10, cellB.getCellStyle().getFont(book).getColor()); - assertEquals(FillPatternType.NO_FILL, cellB.getCellStyle().getFillPatternEnum()); - assertEquals("0:0:0", p.getColor((short)64).getHexString()); - assertEquals("FFFF:0:0", p.getColor((short)10).getHexString()); - - // Red + green bg - assertEquals("I'm red with a green bg", cellC.getStringCellValue()); - assertEquals(11, cellC.getCellStyle().getFillForegroundColor()); - assertEquals(64, cellC.getCellStyle().getFillBackgroundColor()); - assertEquals(10, cellC.getCellStyle().getFont(book).getColor()); - assertEquals(FillPatternType.SOLID_FOREGROUND, cellC.getCellStyle().getFillPatternEnum()); - assertEquals("0:FFFF:0", p.getColor((short)11).getHexString()); - assertEquals("FFFF:0:0", p.getColor((short)10).getHexString()); - - // Pink with yellow - assertEquals("I'm pink with a yellow pattern (none)", cellD.getStringCellValue()); - assertEquals(13, cellD.getCellStyle().getFillForegroundColor()); - assertEquals(64, cellD.getCellStyle().getFillBackgroundColor()); - assertEquals(14, cellD.getCellStyle().getFont(book).getColor()); - assertEquals(FillPatternType.NO_FILL, cellD.getCellStyle().getFillPatternEnum()); - assertEquals("FFFF:FFFF:0", p.getColor((short)13).getHexString()); - assertEquals("FFFF:0:FFFF", p.getColor((short)14).getHexString()); - - // Pink with yellow - full - assertEquals("I'm pink with a yellow pattern (full)", cellE.getStringCellValue()); - assertEquals(13, cellE.getCellStyle().getFillForegroundColor()); - assertEquals(64, cellE.getCellStyle().getFillBackgroundColor()); - assertEquals(14, cellE.getCellStyle().getFont(book).getColor()); - assertEquals(FillPatternType.NO_FILL, cellE.getCellStyle().getFillPatternEnum()); - assertEquals("FFFF:FFFF:0", p.getColor((short)13).getHexString()); - assertEquals("FFFF:0:FFFF", p.getColor((short)14).getHexString()); - } - - @Test - public void testFindSimilar() throws IOException { - HSSFWorkbook book = new HSSFWorkbook(); - HSSFPalette p = book.getCustomPalette(); - - /* first test the defaults */ - assertArrayEquals( - new short[] {(short) 255, (short) 255, (short) 0}, // not [204, 255, 255] - p.findSimilarColor((byte) 204, (byte) 255, (byte) 0).getTriplet() - ); - - assertArrayEquals( - new short[] {(short) 153, (short) 204, (short) 0}, // not [128, 0, 0] - p.findSimilarColor((byte) 128, (byte) 255, (byte) 0).getTriplet() - ); - - assertArrayEquals( - new short[] {(short) 0, (short) 255, (short) 0}, // not [0, 51, 102] - p.findSimilarColor((byte) 0, (byte) 255, (byte) 102).getTriplet() - ); - - assertArrayEquals( - new short[] {(short) 0, (short) 102, (short) 204}, // not [255, 102, 0] - p.findSimilarColor((byte) 0, (byte) 102, (byte) 255).getTriplet() - ); - - assertArrayEquals( - new short[] {(short) 255, (short) 0, (short) 255}, // not [128, 0, 0] - p.findSimilarColor((byte) 128, (byte) 0, (byte) 255).getTriplet() - ); - - assertArrayEquals( - new short[] {(short) 255, (short) 0, (short) 255}, // not [255, 255, 153] - p.findSimilarColor((byte) 255, (byte) 0, (byte) 153).getTriplet() - ); - - - // Add a few edge colours in - p.setColorAtIndex((short)8, (byte)-1, (byte)0, (byte)0); - p.setColorAtIndex((short)9, (byte)0, (byte)-1, (byte)0); - p.setColorAtIndex((short)10, (byte)0, (byte)0, (byte)-1); - - // And some near a few of them - p.setColorAtIndex((short)11, (byte)-1, (byte)2, (byte)2); - p.setColorAtIndex((short)12, (byte)-2, (byte)2, (byte)10); - p.setColorAtIndex((short)13, (byte)-4, (byte)0, (byte)0); - p.setColorAtIndex((short)14, (byte)-8, (byte)0, (byte)0); - - assertEquals( - "FFFF:0:0", p.getColor((short)8).getHexString() - ); - - // Now check we get the right stuff back - assertEquals( - p.getColor((short)8).getHexString(), - p.findSimilarColor((byte)-1, (byte)0, (byte)0).getHexString() - ); - assertEquals( - p.getColor((short)8).getHexString(), - p.findSimilarColor((byte)-2, (byte)0, (byte)0).getHexString() - ); - assertEquals( - p.getColor((short)8).getHexString(), - p.findSimilarColor((byte)-1, (byte)1, (byte)0).getHexString() - ); - assertEquals( - p.getColor((short)11).getHexString(), - p.findSimilarColor((byte)-1, (byte)2, (byte)1).getHexString() - ); - assertEquals( - p.getColor((short)12).getHexString(), - p.findSimilarColor((byte)-1, (byte)2, (byte)10).getHexString() - ); - - // And with ints not bytes - assertEquals( - p.getColor((short)11).getHexString(), - p.findSimilarColor(255, 2, 1).getHexString() - ); - assertEquals( - p.getColor((short)12).getHexString(), - p.findSimilarColor(255, 2, 10).getHexString() - ); - - book.close(); - } - - /** - * Verifies that the generated gnumeric-format string values match the - * hardcoded values in the HSSFColor default color palette - */ - @Test - public void testGnumericStrings() { - compareToDefaults(new ColorComparator() { - @Override - public void compare(HSSFColor expected, HSSFColor palette) - { - assertEquals(expected.getHexString(), palette.getHexString()); - } - }); - } - - /** - * Verifies that the palette handles invalid palette indexes - */ - @Test - public void testBadIndexes() { - //too small - _hssfPalette.setColorAtIndex((short) 2, (byte) 255, (byte) 255, (byte) 255); - //too large - _hssfPalette.setColorAtIndex((short) 0x45, (byte) 255, (byte) 255, (byte) 255); - - //should still match defaults; - compareToDefaults(new ColorComparator() { - @Override - public void compare(HSSFColor expected, HSSFColor palette) - { - short[] s1 = expected.getTriplet(); - short[] s2 = palette.getTriplet(); - assertEquals(s1[0], s2[0]); - assertEquals(s1[1], s2[1]); - assertEquals(s1[2], s2[2]); - } - }); - } - - private void compareToDefaults(ColorComparator c) { - Map colors = HSSFColor.getIndexHash(); - Iterator it = colors.keySet().iterator(); - while (it.hasNext()) - { - Number index = it.next(); - HSSFColor expectedColor = colors.get(index); - HSSFColor paletteColor = _hssfPalette.getColor(index.shortValue()); - c.compare(expectedColor, paletteColor); - } - } - - @Test - public void testAddColor() { - try - { - _hssfPalette.addColor((byte)10,(byte)10,(byte)10); - fail(); - } catch (RuntimeException e) { - // Failing because by default there are no colours left in the palette. - } - } - - private static interface ColorComparator { - void compare(HSSFColor expected, HSSFColor palette); - } - - @Test - public void test48403() throws Exception { - HSSFWorkbook wb = new HSSFWorkbook(); - - Color color = Color.decode("#006B6B"); - HSSFPalette palette = wb.getCustomPalette(); - - HSSFColor hssfColor = palette.findColor((byte) color.getRed(), - (byte) color.getGreen(), (byte) color.getBlue()); - assertNull(hssfColor); - - palette.setColorAtIndex( - (short) (PaletteRecord.STANDARD_PALETTE_SIZE - 1), - (byte) color.getRed(), (byte) color.getGreen(), - (byte) color.getBlue()); - hssfColor = palette.getColor((short) (PaletteRecord.STANDARD_PALETTE_SIZE - 1)); - assertNotNull(hssfColor); - assertEquals(55, hssfColor.getIndex()); - assertArrayEquals(new short[] {0, 107, 107}, hssfColor.getTriplet()); - - wb.close(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPatriarch.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPatriarch.java deleted file mode 100644 index e3428cc92..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPatriarch.java +++ /dev/null @@ -1,69 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.ss.usermodel.ClientAnchor.AnchorType; - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - -/** - * @author Josh Micich - */ -public final class TestHSSFPatriarch extends TestCase { - - public void testBasic() { - - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet(); - - HSSFPatriarch patr = sheet.createDrawingPatriarch(); - assertNotNull(patr); - - // assert something more interesting - } - - public void test44916() { - - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet(); - - // 1. Create drawing patriarch - HSSFPatriarch patr = sheet.createDrawingPatriarch(); - - // 2. Try to re-get the patriarch - HSSFPatriarch existingPatr; - try { - existingPatr = sheet.getDrawingPatriarch(); - } catch (NullPointerException e) { - throw new AssertionFailedError("Identified bug 44916"); - } - - // 3. Use patriarch - HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 600, 245, (short) 1, 1, (short) 1, 2); - anchor.setAnchorType(AnchorType.DONT_MOVE_AND_RESIZE); - byte[] pictureData = HSSFTestDataSamples.getTestDataFileContent("logoKarmokar4.png"); - int idx1 = wb.addPicture(pictureData, HSSFWorkbook.PICTURE_TYPE_PNG); - patr.createPicture(anchor, idx1); - - // 4. Try to re-use patriarch later - existingPatr = sheet.getDrawingPatriarch(); - assertNotNull(existingPatr); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPicture.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPicture.java deleted file mode 100644 index 09387f5f7..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPicture.java +++ /dev/null @@ -1,295 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; - -import java.io.IOException; -import java.util.List; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.ddf.EscherBSERecord; -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.model.InternalSheet; -import org.apache.poi.ss.usermodel.BaseTestPicture; -import org.apache.poi.ss.usermodel.ClientAnchor; -import org.apache.poi.ss.usermodel.CreationHelper; -import org.apache.poi.ss.usermodel.PictureData; -import org.apache.poi.ss.usermodel.Workbook; -import org.junit.Test; - -/** - * Test HSSFPicture. - * - * @author Yegor Kozlov (yegor at apache.org) - */ -public final class TestHSSFPicture extends BaseTestPicture { - - public TestHSSFPicture() { - super(HSSFITestDataProvider.instance); - } - - @Test - public void resize() throws Exception { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("resize_compare.xls"); - HSSFPatriarch dp = wb.getSheetAt(0).createDrawingPatriarch(); - List pics = dp.getChildren(); - HSSFPicture inpPic = (HSSFPicture)pics.get(0); - HSSFPicture cmpPic = (HSSFPicture)pics.get(1); - - baseTestResize(inpPic, cmpPic, 2.0, 2.0); - wb.close(); - } - - /** - * Bug # 45829 reported ArithmeticException (/ by zero) when resizing png with zero DPI. - */ - @Test - public void bug45829() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sh1 = wb.createSheet(); - HSSFPatriarch p1 = sh1.createDrawingPatriarch(); - - byte[] pictureData = HSSFTestDataSamples.getTestDataFileContent("45829.png"); - int idx1 = wb.addPicture( pictureData, HSSFWorkbook.PICTURE_TYPE_PNG ); - HSSFPicture pic = p1.createPicture(new HSSFClientAnchor(), idx1); - pic.resize(); - - wb.close(); - } - - - @SuppressWarnings("resource") - @Test - public void addPictures() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - - HSSFSheet sh = wb.createSheet("Pictures"); - HSSFPatriarch dr = sh.createDrawingPatriarch(); - assertEquals(0, dr.getChildren().size()); - HSSFClientAnchor anchor = wb.getCreationHelper().createClientAnchor(); - - //register a picture - byte[] data1 = new byte[]{1, 2, 3}; - int idx1 = wb.addPicture(data1, Workbook.PICTURE_TYPE_JPEG); - assertEquals(1, idx1); - HSSFPicture p1 = dr.createPicture(anchor, idx1); - assertArrayEquals(data1, p1.getPictureData().getData()); - - // register another one - byte[] data2 = new byte[]{4, 5, 6}; - int idx2 = wb.addPicture(data2, Workbook.PICTURE_TYPE_JPEG); - assertEquals(2, idx2); - HSSFPicture p2 = dr.createPicture(anchor, idx2); - assertEquals(2, dr.getChildren().size()); - assertArrayEquals(data2, p2.getPictureData().getData()); - - // confirm that HSSFPatriarch.getChildren() returns two picture shapes - assertArrayEquals(data1, ((HSSFPicture)dr.getChildren().get(0)).getPictureData().getData()); - assertArrayEquals(data2, ((HSSFPicture)dr.getChildren().get(1)).getPictureData().getData()); - - // write, read back and verify that our pictures are there - wb = HSSFTestDataSamples.writeOutAndReadBack(wb); - List lst2 = wb.getAllPictures(); - assertEquals(2, lst2.size()); - assertArrayEquals(data1, lst2.get(0).getData()); - assertArrayEquals(data2, lst2.get(1).getData()); - - // confirm that the pictures are in the Sheet's drawing - sh = wb.getSheet("Pictures"); - dr = sh.createDrawingPatriarch(); - assertEquals(2, dr.getChildren().size()); - assertArrayEquals(data1, ((HSSFPicture)dr.getChildren().get(0)).getPictureData().getData()); - assertArrayEquals(data2, ((HSSFPicture)dr.getChildren().get(1)).getPictureData().getData()); - - // add a third picture - byte[] data3 = new byte[]{7, 8, 9}; - // picture index must increment across write-read - int idx3 = wb.addPicture(data3, Workbook.PICTURE_TYPE_JPEG); - assertEquals(3, idx3); - HSSFPicture p3 = dr.createPicture(anchor, idx3); - assertArrayEquals(data3, p3.getPictureData().getData()); - assertEquals(3, dr.getChildren().size()); - assertArrayEquals(data1, ((HSSFPicture)dr.getChildren().get(0)).getPictureData().getData()); - assertArrayEquals(data2, ((HSSFPicture)dr.getChildren().get(1)).getPictureData().getData()); - assertArrayEquals(data3, ((HSSFPicture)dr.getChildren().get(2)).getPictureData().getData()); - - // write and read again - wb = HSSFTestDataSamples.writeOutAndReadBack(wb); - List lst3 = wb.getAllPictures(); - // all three should be there - assertEquals(3, lst3.size()); - assertArrayEquals(data1, lst3.get(0).getData()); - assertArrayEquals(data2, lst3.get(1).getData()); - assertArrayEquals(data3, lst3.get(2).getData()); - - sh = wb.getSheet("Pictures"); - dr = sh.createDrawingPatriarch(); - assertEquals(3, dr.getChildren().size()); - - // forth picture - byte[] data4 = new byte[]{10, 11, 12}; - int idx4 = wb.addPicture(data4, Workbook.PICTURE_TYPE_JPEG); - assertEquals(4, idx4); - dr.createPicture(anchor, idx4); - assertEquals(4, dr.getChildren().size()); - assertArrayEquals(data1, ((HSSFPicture)dr.getChildren().get(0)).getPictureData().getData()); - assertArrayEquals(data2, ((HSSFPicture)dr.getChildren().get(1)).getPictureData().getData()); - assertArrayEquals(data3, ((HSSFPicture)dr.getChildren().get(2)).getPictureData().getData()); - assertArrayEquals(data4, ((HSSFPicture)dr.getChildren().get(3)).getPictureData().getData()); - - wb = HSSFTestDataSamples.writeOutAndReadBack(wb); - List lst4 = wb.getAllPictures(); - assertEquals(4, lst4.size()); - assertArrayEquals(data1, lst4.get(0).getData()); - assertArrayEquals(data2, lst4.get(1).getData()); - assertArrayEquals(data3, lst4.get(2).getData()); - assertArrayEquals(data4, lst4.get(3).getData()); - sh = wb.getSheet("Pictures"); - dr = sh.createDrawingPatriarch(); - assertEquals(4, dr.getChildren().size()); - assertArrayEquals(data1, ((HSSFPicture)dr.getChildren().get(0)).getPictureData().getData()); - assertArrayEquals(data2, ((HSSFPicture)dr.getChildren().get(1)).getPictureData().getData()); - assertArrayEquals(data3, ((HSSFPicture)dr.getChildren().get(2)).getPictureData().getData()); - assertArrayEquals(data4, ((HSSFPicture)dr.getChildren().get(3)).getPictureData().getData()); - - wb.close(); - } - - @SuppressWarnings("unused") - @Test - public void bsePictureRef() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - - HSSFSheet sh = wb.createSheet("Pictures"); - HSSFPatriarch dr = sh.createDrawingPatriarch(); - HSSFClientAnchor anchor = new HSSFClientAnchor(); - - InternalSheet ish = HSSFTestHelper.getSheetForTest(sh); - - //register a picture - byte[] data1 = new byte[]{1, 2, 3}; - int idx1 = wb.addPicture(data1, Workbook.PICTURE_TYPE_JPEG); - assertEquals(1, idx1); - HSSFPicture p1 = dr.createPicture(anchor, idx1); - - EscherBSERecord bse = wb.getWorkbook().getBSERecord(idx1); - - assertEquals(bse.getRef(), 1); - dr.createPicture(new HSSFClientAnchor(), idx1); - assertEquals(bse.getRef(), 2); - - HSSFShapeGroup gr = dr.createGroup(new HSSFClientAnchor()); - gr.createPicture(new HSSFChildAnchor(), idx1); - assertEquals(bse.getRef(), 3); - - wb.close(); - } - - @Test - public void readExistingImage(){ - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("drawings.xls"); - HSSFSheet sheet = wb.getSheet("picture"); - HSSFPatriarch drawing = sheet.getDrawingPatriarch(); - assertEquals(1, drawing.getChildren().size()); - - HSSFPicture picture = (HSSFPicture) drawing.getChildren().get(0); - assertEquals(picture.getFileName(), "test"); - } - - @SuppressWarnings("resource") - @Test - public void setGetProperties() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - - HSSFSheet sh = wb.createSheet("Pictures"); - HSSFPatriarch dr = sh.createDrawingPatriarch(); - HSSFClientAnchor anchor = new HSSFClientAnchor(); - - //register a picture - byte[] data1 = new byte[]{1, 2, 3}; - int idx1 = wb.addPicture(data1, Workbook.PICTURE_TYPE_JPEG); - HSSFPicture p1 = dr.createPicture(anchor, idx1); - - assertEquals(p1.getFileName(), ""); - p1.setFileName("aaa"); - assertEquals(p1.getFileName(), "aaa"); - - wb = HSSFTestDataSamples.writeOutAndReadBack(wb); - sh = wb.getSheet("Pictures"); - dr = sh.getDrawingPatriarch(); - - p1 = (HSSFPicture) dr.getChildren().get(0); - assertEquals(p1.getFileName(), "aaa"); - wb.close(); - } - - @SuppressWarnings("resource") - @Test - public void bug49658() throws IOException { - // test if inserted EscherMetafileBlip will be read again - HSSFWorkbook wb = new HSSFWorkbook(); - - byte pictureDataEmf[] = POIDataSamples.getDocumentInstance().readFile("vector_image.emf"); - int indexEmf = wb.addPicture(pictureDataEmf, HSSFWorkbook.PICTURE_TYPE_EMF); - byte pictureDataPng[] = POIDataSamples.getSpreadSheetInstance().readFile("logoKarmokar4.png"); - int indexPng = wb.addPicture(pictureDataPng, HSSFWorkbook.PICTURE_TYPE_PNG); - byte pictureDataWmf[] = POIDataSamples.getSlideShowInstance().readFile("santa.wmf"); - int indexWmf = wb.addPicture(pictureDataWmf, HSSFWorkbook.PICTURE_TYPE_WMF); - - HSSFSheet sheet = wb.createSheet(); - HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); - CreationHelper ch = wb.getCreationHelper(); - - ClientAnchor anchor = ch.createClientAnchor(); - anchor.setCol1(2); - anchor.setCol2(5); - anchor.setRow1(1); - anchor.setRow2(6); - patriarch.createPicture(anchor, indexEmf); - - anchor = ch.createClientAnchor(); - anchor.setCol1(2); - anchor.setCol2(5); - anchor.setRow1(10); - anchor.setRow2(16); - patriarch.createPicture(anchor, indexPng); - - anchor = ch.createClientAnchor(); - anchor.setCol1(6); - anchor.setCol2(9); - anchor.setRow1(1); - anchor.setRow2(6); - patriarch.createPicture(anchor, indexWmf); - - - wb = HSSFTestDataSamples.writeOutAndReadBack(wb); - byte pictureDataOut[] = wb.getAllPictures().get(0).getData(); - assertArrayEquals(pictureDataEmf, pictureDataOut); - - byte wmfNoHeader[] = new byte[pictureDataWmf.length-22]; - System.arraycopy(pictureDataWmf, 22, wmfNoHeader, 0, pictureDataWmf.length-22); - pictureDataOut = wb.getAllPictures().get(2).getData(); - assertArrayEquals(wmfNoHeader, pictureDataOut); - - wb.close(); - } - -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPictureData.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPictureData.java deleted file mode 100644 index 6c6631a9b..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFPictureData.java +++ /dev/null @@ -1,107 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import java.awt.image.BufferedImage; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.util.List; - -import javax.imageio.ImageIO; - -import junit.framework.TestCase; - -import org.apache.poi.hssf.HSSFTestDataSamples; - -/** - * Test HSSFPictureData. - * The code to retrieve images from a workbook provided by Trejkaz (trejkaz at trypticon dot org) in Bug 41223. - * - * @author Yegor Kozlov (yegor at apache dot org) - * @author Trejkaz (trejkaz at trypticon dot org) - */ -public final class TestHSSFPictureData extends TestCase{ - - - public void testPictures() throws IOException { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("SimpleWithImages.xls"); - - @SuppressWarnings("unchecked") // TODO - add getFormat() to interface PictureData and genericise wb.getAllPictures() - List lst = (List)(List)wb.getAllPictures(); - //assertEquals(2, lst.size()); - - for (final HSSFPictureData pict : lst) { - String ext = pict.suggestFileExtension(); - byte[] data = pict.getData(); - if (ext.equals("jpeg")){ - //try to read image data using javax.imageio.* (JDK 1.4+) - BufferedImage jpg = ImageIO.read(new ByteArrayInputStream(data)); - assertNotNull(jpg); - assertEquals(192, jpg.getWidth()); - assertEquals(176, jpg.getHeight()); - assertEquals(HSSFWorkbook.PICTURE_TYPE_JPEG, pict.getFormat()); - assertEquals("image/jpeg", pict.getMimeType()); - } else if (ext.equals("png")){ - //try to read image data using javax.imageio.* (JDK 1.4+) - BufferedImage png = ImageIO.read(new ByteArrayInputStream(data)); - assertNotNull(png); - assertEquals(300, png.getWidth()); - assertEquals(300, png.getHeight()); - assertEquals(HSSFWorkbook.PICTURE_TYPE_PNG, pict.getFormat()); - assertEquals("image/png", pict.getMimeType()); - } else { - //TODO: test code for PICT, WMF and EMF - } - } - } - - public void testMacPicture() throws IOException { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("53446.xls"); - - @SuppressWarnings("unchecked") - List lst = (List)(List)wb.getAllPictures(); - assertEquals(1, lst.size()); - - HSSFPictureData pict = lst.get(0); - String ext = pict.suggestFileExtension(); - if (!ext.equals("png")) { - fail("Expected a PNG."); - } - - //try to read image data using javax.imageio.* (JDK 1.4+) - byte[] data = pict.getData(); - BufferedImage png = ImageIO.read(new ByteArrayInputStream(data)); - assertNotNull(png); - assertEquals(78, png.getWidth()); - assertEquals(76, png.getHeight()); - assertEquals(HSSFWorkbook.PICTURE_TYPE_PNG, pict.getFormat()); - assertEquals("image/png", pict.getMimeType()); - } - - public void testNotNullPictures() throws IOException { - - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("SheetWithDrawing.xls"); - - @SuppressWarnings("unchecked") // TODO - add getFormat() to interface PictureData and genericise wb.getAllPictures() - List lst = (List)(List)wb.getAllPictures(); - for(HSSFPictureData pict : lst){ - assertNotNull(pict); - } - } - -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFRichTextString.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFRichTextString.java deleted file mode 100644 index 8ce707d9a..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFRichTextString.java +++ /dev/null @@ -1,129 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import junit.framework.TestCase; - -public final class TestHSSFRichTextString extends TestCase { - public void testApplyFont() { - - HSSFRichTextString r = new HSSFRichTextString("testing"); - assertEquals(0,r.numFormattingRuns()); - r.applyFont(2,4, new HSSFFont((short)1, null)); - assertEquals(2,r.numFormattingRuns()); - assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(0)); - assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(1)); - assertEquals(1, r.getFontAtIndex(2)); - assertEquals(1, r.getFontAtIndex(3)); - assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(4)); - assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(5)); - assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(6)); - - r.applyFont(6,7, new HSSFFont((short)2, null)); - assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(0)); - assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(1)); - assertEquals(1, r.getFontAtIndex(2)); - assertEquals(1, r.getFontAtIndex(3)); - assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(4)); - assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(5)); - assertEquals(2, r.getFontAtIndex(6)); - - r.applyFont(HSSFRichTextString.NO_FONT); - assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(0)); - assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(1)); - assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(2)); - assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(3)); - assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(4)); - assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(5)); - - r.applyFont(new HSSFFont((short)1, null)); - assertEquals(1, r.getFontAtIndex(0)); - assertEquals(1, r.getFontAtIndex(1)); - assertEquals(1, r.getFontAtIndex(2)); - assertEquals(1, r.getFontAtIndex(3)); - assertEquals(1, r.getFontAtIndex(4)); - assertEquals(1, r.getFontAtIndex(5)); - assertEquals(1, r.getFontAtIndex(6)); - - } - - public void testClearFormatting() { - - HSSFRichTextString r = new HSSFRichTextString("testing"); - assertEquals(0, r.numFormattingRuns()); - r.applyFont(2, 4, new HSSFFont( (short) 1, null)); - assertEquals(2, r.numFormattingRuns()); - r.clearFormatting(); - assertEquals(0, r.numFormattingRuns()); - } - - - /** - * Test case proposed in Bug 40520: formated twice => will format whole String - */ - public void test40520_1() { - - short font = 3; - - HSSFRichTextString r = new HSSFRichTextString("f0_123456789012345678901234567890123456789012345678901234567890"); - - r.applyFont(0,7,font); - r.applyFont(5,9,font); - - for(int i=0; i < 7; i++) assertEquals(font, r.getFontAtIndex(i)); - for(int i=5; i < 9; i++) assertEquals(font, r.getFontAtIndex(i)); - for(int i=9; i < r.length(); i++) assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(i)); - } - - /** - * Test case proposed in Bug 40520: overlapped range => will format whole String - */ - public void test40520_2() { - - short font = 3; - HSSFRichTextString r = new HSSFRichTextString("f0_123456789012345678901234567890123456789012345678901234567890"); - - r.applyFont(0,2,font); - for(int i=0; i < 2; i++) assertEquals(font, r.getFontAtIndex(i)); - for(int i=2; i < r.length(); i++) assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(i)); - - r.applyFont(0,2,font); - for(int i=0; i < 2; i++) assertEquals(font, r.getFontAtIndex(i)); - for(int i=2; i < r.length(); i++) assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(i)); - } - - /** - * Test case proposed in Bug 40520: formated twice => will format whole String - */ - public void test40520_3() { - - short font = 3; - HSSFRichTextString r = new HSSFRichTextString("f0_123456789012345678901234567890123456789012345678901234567890"); - - // wrong order => will format 0-6 - r.applyFont(0,2,font); - r.applyFont(5,7,font); - r.applyFont(0,2,font); - - r.applyFont(0,2,font); - for(int i=0; i < 2; i++) assertEquals(font, r.getFontAtIndex(i)); - for(int i=2; i < 5; i++) assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(i)); - for(int i=5; i < 7; i++) assertEquals(font, r.getFontAtIndex(i)); - for(int i=7; i < r.length(); i++) assertEquals(HSSFRichTextString.NO_FONT, r.getFontAtIndex(i)); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFRow.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFRow.java deleted file mode 100644 index 53d799e95..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFRow.java +++ /dev/null @@ -1,163 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import java.io.IOException; - -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.hssf.record.BlankRecord; -import org.apache.poi.hssf.record.RowRecord; -import org.apache.poi.ss.SpreadsheetVersion; -import org.apache.poi.ss.usermodel.BaseTestRow; -import org.junit.Test; - -import static org.junit.Assert.*; - -/** - * Test HSSFRow is okay. - * - * @author Glen Stampoultzis (glens at apache.org) - */ -public final class TestHSSFRow extends BaseTestRow { - - public TestHSSFRow() { - super(HSSFITestDataProvider.instance); - } - - @Test - public void testRowBounds() throws IOException { - baseTestRowBounds(SpreadsheetVersion.EXCEL97.getLastRowIndex()); - } - - @Test - public void testCellBounds() throws IOException { - baseTestCellBounds(SpreadsheetVersion.EXCEL97.getLastColumnIndex()); - } - - @Test - public void testLastAndFirstColumns_bug46654() throws IOException { - int ROW_IX = 10; - int COL_IX = 3; - HSSFWorkbook workbook = new HSSFWorkbook(); - HSSFSheet sheet = workbook.createSheet("Sheet1"); - RowRecord rowRec = new RowRecord(ROW_IX); - rowRec.setFirstCol((short)2); - rowRec.setLastCol((short)5); - - BlankRecord br = new BlankRecord(); - br.setRow(ROW_IX); - br.setColumn((short)COL_IX); - - sheet.getSheet().addValueRecord(ROW_IX, br); - HSSFRow row = new HSSFRow(workbook, sheet, rowRec); - HSSFCell cell = row.createCellFromRecord(br); - - if (row.getFirstCellNum() == 2 && row.getLastCellNum() == 5) { - fail("Identified bug 46654a"); - } - assertEquals(COL_IX, row.getFirstCellNum()); - assertEquals(COL_IX + 1, row.getLastCellNum()); - row.removeCell(cell); - assertEquals(-1, row.getFirstCellNum()); - assertEquals(-1, row.getLastCellNum()); - - workbook.close(); - } - - @Test - public void testMoveCell() throws IOException { - HSSFWorkbook workbook = new HSSFWorkbook(); - HSSFSheet sheet = workbook.createSheet(); - HSSFRow row = sheet.createRow(0); - HSSFRow rowB = sheet.createRow(1); - - HSSFCell cellA2 = rowB.createCell(0); - assertEquals(0, rowB.getFirstCellNum()); - assertEquals(0, rowB.getFirstCellNum()); - - assertEquals(-1, row.getLastCellNum()); - assertEquals(-1, row.getFirstCellNum()); - HSSFCell cellB2 = row.createCell(1); - row.createCell(2); // C2 - row.createCell(3); // D2 - - assertEquals(1, row.getFirstCellNum()); - assertEquals(4, row.getLastCellNum()); - - // Try to move to somewhere else that's used - try { - row.moveCell(cellB2, (short)3); - fail("IllegalArgumentException should have been thrown"); - } catch(IllegalArgumentException e) { - // expected during successful test - } - - // Try to move one off a different row - try { - row.moveCell(cellA2, (short)3); - fail("IllegalArgumentException should have been thrown"); - } catch(IllegalArgumentException e) { - // expected during successful test - } - - // Move somewhere spare - assertNotNull(row.getCell(1)); - row.moveCell(cellB2, (short)5); - assertNull(row.getCell(1)); - assertNotNull(row.getCell(5)); - - assertEquals(5, cellB2.getColumnIndex()); - assertEquals(2, row.getFirstCellNum()); - assertEquals(6, row.getLastCellNum()); - - workbook.close(); - } - - @Override - @Test - public void testRowHeight() throws IOException{ - HSSFWorkbook workbook = new HSSFWorkbook(); - HSSFSheet sheet = workbook.createSheet(); - HSSFRow row = sheet.createRow(0); - - assertEquals(row.getHeight(), sheet.getDefaultRowHeight()); - assertFalse(row.getRowRecord().getBadFontHeight()); - - row.setHeight((short) 123); - assertEquals(123, row.getHeight()); - assertTrue(row.getRowRecord().getBadFontHeight()); - - row.setHeight((short) -1); - assertEquals(row.getHeight(), sheet.getDefaultRowHeight()); - assertFalse(row.getRowRecord().getBadFontHeight()); - - row.setHeight((short) 123); - assertEquals(123, row.getHeight()); - assertTrue(row.getRowRecord().getBadFontHeight()); - - row.setHeightInPoints(-1); - assertEquals(row.getHeight(), sheet.getDefaultRowHeight()); - assertFalse(row.getRowRecord().getBadFontHeight()); - - row.setHeightInPoints(432); - assertEquals(432*20, row.getHeight()); - assertTrue(row.getRowRecord().getBadFontHeight()); - - workbook.close(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheet.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheet.java deleted file mode 100644 index 57938d8cf..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheet.java +++ /dev/null @@ -1,1192 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.apache.poi.POITestCase.assertBetween; - -import java.io.IOException; -import java.util.List; - -import org.apache.poi.ddf.EscherDgRecord; -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.model.DrawingManager2; -import org.apache.poi.hssf.model.InternalSheet; -import org.apache.poi.hssf.model.InternalWorkbook; -import org.apache.poi.hssf.record.AutoFilterInfoRecord; -import org.apache.poi.hssf.record.CommonObjectDataSubRecord; -import org.apache.poi.hssf.record.DimensionsRecord; -import org.apache.poi.hssf.record.FtCblsSubRecord; -import org.apache.poi.hssf.record.GridsetRecord; -import org.apache.poi.hssf.record.HCenterRecord; -import org.apache.poi.hssf.record.LbsDataSubRecord; -import org.apache.poi.hssf.record.NameRecord; -import org.apache.poi.hssf.record.ObjRecord; -import org.apache.poi.hssf.record.ObjectProtectRecord; -import org.apache.poi.hssf.record.PasswordRecord; -import org.apache.poi.hssf.record.ProtectRecord; -import org.apache.poi.hssf.record.Record; -import org.apache.poi.hssf.record.SCLRecord; -import org.apache.poi.hssf.record.ScenarioProtectRecord; -import org.apache.poi.hssf.record.SubRecord; -import org.apache.poi.hssf.record.VCenterRecord; -import org.apache.poi.hssf.record.WSBoolRecord; -import org.apache.poi.hssf.record.WindowTwoRecord; -import org.apache.poi.hssf.record.aggregates.WorksheetProtectionBlock; -import org.apache.poi.hssf.usermodel.RecordInspector.RecordCollector; -import org.apache.poi.ss.formula.ptg.Area3DPtg; -import org.apache.poi.ss.formula.ptg.Ptg; -import org.apache.poi.ss.usermodel.*; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.CellRangeAddressList; -import org.junit.Test; - -/** - * Tests HSSFSheet. This test case is very incomplete at the moment. - * - * - * @author Glen Stampoultzis (glens at apache.org) - * @author Andrew C. Oliver (acoliver apache org) - */ -public final class TestHSSFSheet extends BaseTestSheet { - - public TestHSSFSheet() { - super(HSSFITestDataProvider.instance); - } - - /** - * Test for Bugzilla #29747. - * Moved from TestHSSFWorkbook#testSetRepeatingRowsAndColumns(). - */ - @Test - public void setRepeatingRowsAndColumnsBug29747() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - wb.createSheet(); - wb.createSheet(); - HSSFSheet sheet2 = wb.createSheet(); - sheet2.setRepeatingRows(CellRangeAddress.valueOf("1:2")); - NameRecord nameRecord = wb.getWorkbook().getNameRecord(0); - assertEquals(3, nameRecord.getSheetNumber()); - wb.close(); - } - - - @Test - public void getSetMargin() throws IOException { - baseTestGetSetMargin(new double[]{0.75, 0.75, 1.0, 1.0, 0.3, 0.3}); - } - - /** - * Test the gridset field gets set as expected. - */ - @Test - public void backupRecord() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet s = wb.createSheet(); - GridsetRecord gridsetRec = s.getSheet().getGridsetRecord(); - assertTrue(gridsetRec.getGridset()); - s.setGridsPrinted(true); - assertFalse(gridsetRec.getGridset()); - wb.close(); - } - - /** - * Test vertically centered output. - */ - @Test - public void verticallyCenter() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet s = wb.createSheet(); - VCenterRecord record = s.getSheet().getPageSettings().getVCenter(); - - assertFalse(record.getVCenter()); - assertFalse(s.getVerticallyCenter()); - s.setVerticallyCenter(true); - assertTrue(record.getVCenter()); - assertTrue(s.getVerticallyCenter()); - - wb.close(); - } - - /** - * Test horizontally centered output. - */ - @Test - public void horizontallyCenter() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet s = wb.createSheet(); - HCenterRecord record = s.getSheet().getPageSettings().getHCenter(); - - assertFalse(record.getHCenter()); - assertFalse(s.getHorizontallyCenter()); - s.setHorizontallyCenter(true); - assertTrue(record.getHCenter()); - assertTrue(s.getHorizontallyCenter()); - - wb.close(); - } - - - /** - * Test WSBboolRecord fields get set in the user model. - */ - @Test - public void wsBool() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet s = wb.createSheet(); - WSBoolRecord record = - (WSBoolRecord) s.getSheet().findFirstRecordBySid(WSBoolRecord.sid); - - // Check defaults - assertTrue(record.getAlternateExpression()); - assertTrue(record.getAlternateFormula()); - assertFalse(record.getAutobreaks()); - assertFalse(record.getDialog()); - assertFalse(record.getDisplayGuts()); - assertTrue(record.getFitToPage()); - assertFalse(record.getRowSumsBelow()); - assertFalse(record.getRowSumsRight()); - - // Alter - s.setAlternativeExpression(false); - s.setAlternativeFormula(false); - s.setAutobreaks(true); - s.setDialog(true); - s.setDisplayGuts(true); - s.setFitToPage(false); - s.setRowSumsBelow(true); - s.setRowSumsRight(true); - - // Check - assertTrue(record.getAlternateExpression()); //sheet.setRowSumsBelow alters this field too - assertFalse(record.getAlternateFormula()); - assertTrue(record.getAutobreaks()); - assertTrue(record.getDialog()); - assertTrue(record.getDisplayGuts()); - assertFalse(record.getFitToPage()); - assertTrue(record.getRowSumsBelow()); - assertTrue(record.getRowSumsRight()); - assertTrue(s.getAlternateExpression()); - assertFalse(s.getAlternateFormula()); - assertTrue(s.getAutobreaks()); - assertTrue(s.getDialog()); - assertTrue(s.getDisplayGuts()); - assertFalse(s.getFitToPage()); - assertTrue(s.getRowSumsBelow()); - assertTrue(s.getRowSumsRight()); - - wb.close(); - } - - /** - * Setting landscape and portrait stuff on existing sheets - */ - @Test - public void printSetupLandscapeExisting() throws IOException { - HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("SimpleWithPageBreaks.xls"); - - assertEquals(3, wb1.getNumberOfSheets()); - - HSSFSheet sheetL = wb1.getSheetAt(0); - HSSFSheet sheetPM = wb1.getSheetAt(1); - HSSFSheet sheetLS = wb1.getSheetAt(2); - - // Check two aspects of the print setup - assertFalse(sheetL.getPrintSetup().getLandscape()); - assertTrue(sheetPM.getPrintSetup().getLandscape()); - assertTrue(sheetLS.getPrintSetup().getLandscape()); - assertEquals(1, sheetL.getPrintSetup().getCopies()); - assertEquals(1, sheetPM.getPrintSetup().getCopies()); - assertEquals(1, sheetLS.getPrintSetup().getCopies()); - - // Change one on each - sheetL.getPrintSetup().setLandscape(true); - sheetPM.getPrintSetup().setLandscape(false); - sheetPM.getPrintSetup().setCopies((short)3); - - // Check taken - assertTrue(sheetL.getPrintSetup().getLandscape()); - assertFalse(sheetPM.getPrintSetup().getLandscape()); - assertTrue(sheetLS.getPrintSetup().getLandscape()); - assertEquals(1, sheetL.getPrintSetup().getCopies()); - assertEquals(3, sheetPM.getPrintSetup().getCopies()); - assertEquals(1, sheetLS.getPrintSetup().getCopies()); - - // Save and re-load, and check still there - Workbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - - sheetL = wb1.getSheetAt(0); - sheetPM = wb1.getSheetAt(1); - sheetLS = wb1.getSheetAt(2); - - assertTrue(sheetL.getPrintSetup().getLandscape()); - assertFalse(sheetPM.getPrintSetup().getLandscape()); - assertTrue(sheetLS.getPrintSetup().getLandscape()); - assertEquals(1, sheetL.getPrintSetup().getCopies()); - assertEquals(3, sheetPM.getPrintSetup().getCopies()); - assertEquals(1, sheetLS.getPrintSetup().getCopies()); - - wb2.close(); - } - - @Test - public void groupRows() throws IOException { - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet s = wb1.createSheet(); - HSSFRow r1 = s.createRow(0); - HSSFRow r2 = s.createRow(1); - HSSFRow r3 = s.createRow(2); - HSSFRow r4 = s.createRow(3); - HSSFRow r5 = s.createRow(4); - - assertEquals(0, r1.getOutlineLevel()); - assertEquals(0, r2.getOutlineLevel()); - assertEquals(0, r3.getOutlineLevel()); - assertEquals(0, r4.getOutlineLevel()); - assertEquals(0, r5.getOutlineLevel()); - - s.groupRow(2,3); - - assertEquals(0, r1.getOutlineLevel()); - assertEquals(0, r2.getOutlineLevel()); - assertEquals(1, r3.getOutlineLevel()); - assertEquals(1, r4.getOutlineLevel()); - assertEquals(0, r5.getOutlineLevel()); - - // Save and re-open - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - - s = wb2.getSheetAt(0); - r1 = s.getRow(0); - r2 = s.getRow(1); - r3 = s.getRow(2); - r4 = s.getRow(3); - r5 = s.getRow(4); - - assertEquals(0, r1.getOutlineLevel()); - assertEquals(0, r2.getOutlineLevel()); - assertEquals(1, r3.getOutlineLevel()); - assertEquals(1, r4.getOutlineLevel()); - assertEquals(0, r5.getOutlineLevel()); - wb2.close(); - } - - @Test - public void groupRowsExisting() throws IOException { - HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("NoGutsRecords.xls"); - - HSSFSheet s = wb1.getSheetAt(0); - HSSFRow r1 = s.getRow(0); - HSSFRow r2 = s.getRow(1); - HSSFRow r3 = s.getRow(2); - HSSFRow r4 = s.getRow(3); - HSSFRow r5 = s.getRow(4); - HSSFRow r6 = s.getRow(5); - - assertEquals(0, r1.getOutlineLevel()); - assertEquals(0, r2.getOutlineLevel()); - assertEquals(0, r3.getOutlineLevel()); - assertEquals(0, r4.getOutlineLevel()); - assertEquals(0, r5.getOutlineLevel()); - assertEquals(0, r6.getOutlineLevel()); - - // This used to complain about lacking guts records - s.groupRow(2, 4); - - assertEquals(0, r1.getOutlineLevel()); - assertEquals(0, r2.getOutlineLevel()); - assertEquals(1, r3.getOutlineLevel()); - assertEquals(1, r4.getOutlineLevel()); - assertEquals(1, r5.getOutlineLevel()); - assertEquals(0, r6.getOutlineLevel()); - - // Save and re-open - HSSFWorkbook wb2 = null; - try { - wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - } catch (OutOfMemoryError e) { - fail("Identified bug 39903"); - } - - s = wb2.getSheetAt(0); - r1 = s.getRow(0); - r2 = s.getRow(1); - r3 = s.getRow(2); - r4 = s.getRow(3); - r5 = s.getRow(4); - r6 = s.getRow(5); - - assertEquals(0, r1.getOutlineLevel()); - assertEquals(0, r2.getOutlineLevel()); - assertEquals(1, r3.getOutlineLevel()); - assertEquals(1, r4.getOutlineLevel()); - assertEquals(1, r5.getOutlineLevel()); - assertEquals(0, r6.getOutlineLevel()); - - wb2.close(); - wb1.close(); - } - - @Test - public void createDrawings() throws IOException { - HSSFWorkbook workbook = new HSSFWorkbook(); - HSSFSheet sheet = workbook.createSheet(); - HSSFPatriarch p1 = sheet.createDrawingPatriarch(); - HSSFPatriarch p2 = sheet.createDrawingPatriarch(); - assertSame(p1, p2); - workbook.close(); - } - - @Test - public void getDrawings() throws IOException { - HSSFWorkbook wb1c = HSSFTestDataSamples.openSampleWorkbook("WithChart.xls"); - HSSFWorkbook wb2c = HSSFTestDataSamples.openSampleWorkbook("WithTwoCharts.xls"); - - // 1 chart sheet -> data on 1st, chart on 2nd - assertNotNull(wb1c.getSheetAt(0).getDrawingPatriarch()); - assertSame(wb1c.getSheetAt(0).getDrawingPatriarch(), wb1c.getSheetAt(0).getDrawingPatriarch()); - assertNotNull(wb1c.getSheetAt(1).getDrawingPatriarch()); - assertSame(wb1c.getSheetAt(1).getDrawingPatriarch(), wb1c.getSheetAt(1).getDrawingPatriarch()); - assertFalse(wb1c.getSheetAt(0).getDrawingPatriarch().containsChart()); - assertTrue(wb1c.getSheetAt(1).getDrawingPatriarch().containsChart()); - - // 2 chart sheet -> data on 1st, chart on 2nd+3rd - assertNotNull(wb2c.getSheetAt(0).getDrawingPatriarch()); - assertNotNull(wb2c.getSheetAt(1).getDrawingPatriarch()); - assertNotNull(wb2c.getSheetAt(2).getDrawingPatriarch()); - assertFalse(wb2c.getSheetAt(0).getDrawingPatriarch().containsChart()); - assertTrue(wb2c.getSheetAt(1).getDrawingPatriarch().containsChart()); - assertTrue(wb2c.getSheetAt(2).getDrawingPatriarch().containsChart()); - wb2c.close(); - wb1c.close(); - } - - /** - * Test that the ProtectRecord is included when creating or cloning a sheet - */ - @Test - public void cloneWithProtect() throws IOException { - String passwordA = "secrect"; - int expectedHashA = -6810; - String passwordB = "admin"; - int expectedHashB = -14556; - HSSFWorkbook workbook = new HSSFWorkbook(); - HSSFSheet hssfSheet = workbook.createSheet(); - assertFalse(hssfSheet.getObjectProtect()); - hssfSheet.protectSheet(passwordA); - assertTrue(hssfSheet.getObjectProtect()); - assertEquals(expectedHashA, hssfSheet.getPassword()); - - assertEquals(expectedHashA, hssfSheet.getSheet().getProtectionBlock().getPasswordHash()); - - // Clone the sheet, and make sure the password hash is preserved - HSSFSheet sheet2 = workbook.cloneSheet(0); - assertTrue(hssfSheet.getObjectProtect()); - assertEquals(expectedHashA, sheet2.getSheet().getProtectionBlock().getPasswordHash()); - - // change the password on the first sheet - hssfSheet.protectSheet(passwordB); - assertTrue(hssfSheet.getObjectProtect()); - assertEquals(expectedHashB, hssfSheet.getSheet().getProtectionBlock().getPasswordHash()); - assertEquals(expectedHashB, hssfSheet.getPassword()); - // but the cloned sheet's password should remain unchanged - assertEquals(expectedHashA, sheet2.getSheet().getProtectionBlock().getPasswordHash()); - workbook.close(); - } - - @Test - public void protectSheetA() throws IOException { - int expectedHash = (short)0xfef1; - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet s = wb.createSheet(); - s.protectSheet("abcdefghij"); - WorksheetProtectionBlock pb = s.getSheet().getProtectionBlock(); - assertTrue("protection should be on", pb.isSheetProtected()); - assertTrue("object protection should be on",pb.isObjectProtected()); - assertTrue("scenario protection should be on",pb.isScenarioProtected()); - assertEquals("well known value for top secret hash should be "+Integer.toHexString(expectedHash).substring(4), expectedHash, pb.getPasswordHash()); - wb.close(); - } - - /** - * {@link PasswordRecord} belongs with the rest of the Worksheet Protection Block - * (which should be before {@link DimensionsRecord}). - */ - @Test - public void protectSheetRecordOrder_bug47363a() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet s = wb.createSheet(); - s.protectSheet("secret"); - RecordCollector rc = new RecordCollector(); - s.getSheet().visitContainedRecords(rc, 0); - Record[] recs = rc.getRecords(); - int nRecs = recs.length; - if (recs[nRecs-2] instanceof PasswordRecord && recs[nRecs-5] instanceof DimensionsRecord) { - fail("Identified bug 47363a - PASSWORD after DIMENSION"); - } - // Check that protection block is together, and before DIMENSION - confirmRecordClass(recs, nRecs-4, DimensionsRecord.class); - confirmRecordClass(recs, nRecs-9, ProtectRecord.class); - confirmRecordClass(recs, nRecs-8, ObjectProtectRecord.class); - confirmRecordClass(recs, nRecs-7, ScenarioProtectRecord.class); - confirmRecordClass(recs, nRecs-6, PasswordRecord.class); - - wb.close(); - } - - private static void confirmRecordClass(Record[] recs, int index, Class cls) { - if (recs.length <= index) { - fail("Expected (" + cls.getName() + ") at index " - + index + " but array length is " + recs.length + "."); - } - assertEquals(cls, recs[index].getClass()); - } - - /** - * There should be no problem with adding data validations after sheet protection - */ - @Test - public void dvProtectionOrder_bug47363b() throws IOException { - HSSFWorkbook workbook = new HSSFWorkbook(); - HSSFSheet sheet = workbook.createSheet("Sheet1"); - sheet.protectSheet("secret"); - - DataValidationHelper dataValidationHelper = sheet.getDataValidationHelper(); - DataValidationConstraint dvc = dataValidationHelper.createIntegerConstraint(DataValidationConstraint.OperatorType.BETWEEN, "10", "100"); - CellRangeAddressList numericCellAddressList = new CellRangeAddressList(0, 0, 1, 1); - DataValidation dv = dataValidationHelper.createValidation(dvc,numericCellAddressList); - try { - sheet.addValidationData(dv); - } catch (IllegalStateException e) { - String expMsg = "Unexpected (org.apache.poi.hssf.record.PasswordRecord) while looking for DV Table insert pos"; - if (expMsg.equals(e.getMessage())) { - fail("Identified bug 47363b"); - } - workbook.close(); - throw e; - } - RecordCollector rc; - rc = new RecordCollector(); - sheet.getSheet().visitContainedRecords(rc, 0); - int nRecsWithProtection = rc.getRecords().length; - - sheet.protectSheet(null); - rc = new RecordCollector(); - sheet.getSheet().visitContainedRecords(rc, 0); - int nRecsWithoutProtection = rc.getRecords().length; - - assertEquals(4, nRecsWithProtection - nRecsWithoutProtection); - - workbook.close(); - } - - @SuppressWarnings("deprecation") - @Test - public void zoom() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet(); - assertEquals(-1, sheet.getSheet().findFirstRecordLocBySid(SCLRecord.sid)); - sheet.setZoom(75); - assertTrue(sheet.getSheet().findFirstRecordLocBySid(SCLRecord.sid) > 0); - SCLRecord sclRecord = (SCLRecord) sheet.getSheet().findFirstRecordBySid(SCLRecord.sid); - assertEquals(75, 100*sclRecord.getNumerator()/sclRecord.getDenominator()); - - int sclLoc = sheet.getSheet().findFirstRecordLocBySid(SCLRecord.sid); - int window2Loc = sheet.getSheet().findFirstRecordLocBySid(WindowTwoRecord.sid); - assertTrue(sclLoc == window2Loc + 1); - - // verify limits - try { - sheet.setZoom(0); - fail("Should catch Exception here"); - } catch (IllegalArgumentException e) { - assertEquals("Numerator must be greater than 0 and less than 65536", e.getMessage()); - } - try { - sheet.setZoom(65536); - fail("Should catch Exception here"); - } catch (IllegalArgumentException e) { - assertEquals("Numerator must be greater than 0 and less than 65536", e.getMessage()); - } - try { - sheet.setZoom(2, 0); - fail("Should catch Exception here"); - } catch (IllegalArgumentException e) { - assertEquals("Denominator must be greater than 0 and less than 65536", e.getMessage()); - } - try { - sheet.setZoom(2, 65536); - fail("Should catch Exception here"); - } catch (IllegalArgumentException e) { - assertEquals("Denominator must be greater than 0 and less than 65536", e.getMessage()); - } - - wb.close(); - } - - - /** - * When removing one merged region, it would break - * Make sure the excel file loads work - */ - @Test - public void pageBreakFiles() throws IOException { - HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("SimpleWithPageBreaks.xls"); - - HSSFSheet sheet = wb1.getSheetAt(0); - assertNotNull(sheet); - - assertEquals("1 row page break", 1, sheet.getRowBreaks().length); - assertEquals("1 column page break", 1, sheet.getColumnBreaks().length); - - assertTrue("No row page break", sheet.isRowBroken(22)); - assertTrue("No column page break", sheet.isColumnBroken((short)4)); - - sheet.setRowBreak(10); - sheet.setColumnBreak((short)13); - - assertEquals("row breaks number", 2, sheet.getRowBreaks().length); - assertEquals("column breaks number", 2, sheet.getColumnBreaks().length); - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sheet = wb2.getSheetAt(0); - - assertTrue("No row page break", sheet.isRowBroken(22)); - assertTrue("No column page break", sheet.isColumnBroken((short)4)); - - assertEquals("row breaks number", 2, sheet.getRowBreaks().length); - assertEquals("column breaks number", 2, sheet.getColumnBreaks().length); - - wb2.close(); - } - - @Test - public void dbcsName () throws IOException { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("DBCSSheetName.xls"); - wb.getSheetAt(1); - assertEquals ("DBCS Sheet Name 2", wb.getSheetName(1),"\u090f\u0915" ); - assertEquals("DBCS Sheet Name 1", wb.getSheetName(0),"\u091c\u093e"); - wb.close(); - } - - /** - * Testing newly added method that exposes the WINDOW2.toprow - * parameter to allow setting the toprow in the visible view - * of the sheet when it is first opened. - */ - @Test - public void topRow() throws IOException { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("SimpleWithPageBreaks.xls"); - - HSSFSheet sheet = wb.getSheetAt(0); - assertNotNull(sheet); - - short toprow = (short) 100; - short leftcol = (short) 50; - sheet.showInPane(toprow,leftcol); - assertEquals("HSSFSheet.getTopRow()", toprow, sheet.getTopRow()); - assertEquals("HSSFSheet.getLeftCol()", leftcol, sheet.getLeftCol()); - - wb.close(); - } - - @Test - public void addEmptyRow() throws IOException { - //try to add 5 empty rows to a new sheet - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet sheet = wb1.createSheet(); - for (int i = 0; i < 5; i++) { - sheet.createRow(i); - } - - HSSFTestDataSamples.writeOutAndReadBack(wb1).close(); - wb1.close(); - - //try adding empty rows in an existing worksheet - HSSFWorkbook wb2 = HSSFTestDataSamples.openSampleWorkbook("Simple.xls"); - - sheet = wb2.getSheetAt(0); - for (int i = 3; i < 10; i++) sheet.createRow(i); - - HSSFTestDataSamples.writeOutAndReadBack(wb2).close(); - wb2.close(); - } - - @Test - public void autoSizeColumn() throws IOException { - HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("43902.xls"); - String sheetName = "my sheet"; - HSSFSheet sheet = wb1.getSheet(sheetName); - - // Can't use literal numbers for column sizes, as - // will come out with different values on different - // machines based on the fonts available. - // So, we use ranges, which are pretty large, but - // thankfully don't overlap! - int minWithRow1And2 = 6400; - int maxWithRow1And2 = 7800; - int minWithRow1Only = 2750; - int maxWithRow1Only = 3400; - - // autoSize the first column and check its size before the merged region (1,0,1,1) is set: - // it has to be based on the 2nd row width - sheet.autoSizeColumn((short)0); - assertTrue("Column autosized with only one row: wrong width", sheet.getColumnWidth(0) >= minWithRow1And2); - assertTrue("Column autosized with only one row: wrong width", sheet.getColumnWidth(0) <= maxWithRow1And2); - - //create a region over the 2nd row and auto size the first column - sheet.addMergedRegion(new CellRangeAddress(1,1,0,1)); - assertNotNull(sheet.getMergedRegion(0)); - sheet.autoSizeColumn((short)0); - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - - // check that the autoSized column width has ignored the 2nd row - // because it is included in a merged region (Excel like behavior) - HSSFSheet sheet2 = wb2.getSheet(sheetName); - assertTrue(sheet2.getColumnWidth(0) >= minWithRow1Only); - assertTrue(sheet2.getColumnWidth(0) <= maxWithRow1Only); - - // remove the 2nd row merged region and check that the 2nd row value is used to the autoSizeColumn width - sheet2.removeMergedRegion(1); - sheet2.autoSizeColumn((short)0); - HSSFWorkbook wb3 = HSSFTestDataSamples.writeOutAndReadBack(wb2); - HSSFSheet sheet3 = wb3.getSheet(sheetName); - assertTrue(sheet3.getColumnWidth(0) >= minWithRow1And2); - assertTrue(sheet3.getColumnWidth(0) <= maxWithRow1And2); - - wb3.close(); - wb2.close(); - wb1.close(); - } - - /** - * Setting ForceFormulaRecalculation on sheets - */ - @Test - public void forceRecalculation() throws IOException { - HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("UncalcedRecord.xls"); - - HSSFSheet sheet = wb1.getSheetAt(0); - HSSFSheet sheet2 = wb1.getSheetAt(0); - HSSFRow row = sheet.getRow(0); - row.createCell(0).setCellValue(5); - row.createCell(1).setCellValue(8); - assertFalse(sheet.getForceFormulaRecalculation()); - assertFalse(sheet2.getForceFormulaRecalculation()); - - // Save and manually verify that on column C we have 0, value in template - HSSFTestDataSamples.writeOutAndReadBack(wb1).close(); - sheet.setForceFormulaRecalculation(true); - assertTrue(sheet.getForceFormulaRecalculation()); - - // Save and manually verify that on column C we have now 13, calculated value - // Try it can be opened - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - - // And check correct sheet settings found - sheet = wb2.getSheetAt(0); - sheet2 = wb2.getSheetAt(1); - assertTrue(sheet.getForceFormulaRecalculation()); - assertFalse(sheet2.getForceFormulaRecalculation()); - - // Now turn if back off again - sheet.setForceFormulaRecalculation(false); - - HSSFWorkbook wb3 = HSSFTestDataSamples.writeOutAndReadBack(wb2); - wb2.close(); - - assertFalse(wb3.getSheetAt(0).getForceFormulaRecalculation()); - assertFalse(wb3.getSheetAt(1).getForceFormulaRecalculation()); - assertFalse(wb3.getSheetAt(2).getForceFormulaRecalculation()); - - // Now add a new sheet, and check things work - // with old ones unset, new one set - HSSFSheet s4 = wb3.createSheet(); - s4.setForceFormulaRecalculation(true); - - assertFalse(sheet.getForceFormulaRecalculation()); - assertFalse(sheet2.getForceFormulaRecalculation()); - assertTrue(s4.getForceFormulaRecalculation()); - - HSSFWorkbook wb4 = HSSFTestDataSamples.writeOutAndReadBack(wb3); - wb3.close(); - - assertFalse(wb4.getSheetAt(0).getForceFormulaRecalculation()); - assertFalse(wb4.getSheetAt(1).getForceFormulaRecalculation()); - assertFalse(wb4.getSheetAt(2).getForceFormulaRecalculation()); - assertTrue(wb4.getSheetAt(3).getForceFormulaRecalculation()); - wb4.close(); - } - - @Test - public void columnWidthA() throws IOException { - //check we can correctly read column widths from a reference workbook - HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("colwidth.xls"); - - //reference values - int[] ref = {365, 548, 731, 914, 1097, 1280, 1462, 1645, 1828, 2011, 2194, 2377, 2560, 2742, 2925, 3108, 3291, 3474, 3657}; - - HSSFSheet sh = wb1.getSheetAt(0); - for (char i = 'A'; i <= 'S'; i++) { - int idx = i - 'A'; - int w = sh.getColumnWidth(idx); - assertEquals(ref[idx], w); - } - - //the second sheet doesn't have overridden column widths - sh = wb1.getSheetAt(1); - int def_width = sh.getDefaultColumnWidth(); - for (char i = 'A'; i <= 'S'; i++) { - int idx = i - 'A'; - int w = sh.getColumnWidth(idx); - //getDefaultColumnWidth returns width measured in characters - //getColumnWidth returns width measured in 1/256th units - assertEquals(def_width*256, w); - } - wb1.close(); - - //test new workbook - HSSFWorkbook wb2 = new HSSFWorkbook(); - sh = wb2.createSheet(); - sh.setDefaultColumnWidth(10); - assertEquals(10, sh.getDefaultColumnWidth()); - assertEquals(256*10, sh.getColumnWidth(0)); - assertEquals(256*10, sh.getColumnWidth(1)); - assertEquals(256*10, sh.getColumnWidth(2)); - for (char i = 'D'; i <= 'F'; i++) { - short w = (256*12); - sh.setColumnWidth(i, w); - assertEquals(w, sh.getColumnWidth(i)); - } - - //serialize and read again - HSSFWorkbook wb3 = HSSFTestDataSamples.writeOutAndReadBack(wb2); - wb2.close(); - - sh = wb3.getSheetAt(0); - assertEquals(10, sh.getDefaultColumnWidth()); - //columns A-C have default width - assertEquals(256*10, sh.getColumnWidth(0)); - assertEquals(256*10, sh.getColumnWidth(1)); - assertEquals(256*10, sh.getColumnWidth(2)); - //columns D-F have custom width - for (char i = 'D'; i <= 'F'; i++) { - short w = (256*12); - assertEquals(w, sh.getColumnWidth(i)); - } - - // check for 16-bit signed/unsigned error: - sh.setColumnWidth(0, 40000); - assertEquals(40000, sh.getColumnWidth(0)); - wb3.close(); - } - - - @Test - public void defaultColumnWidth() throws IOException { - HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook( "12843-1.xls" ); - HSSFSheet sheet = wb1.getSheetAt( 7 ); - // shall not be NPE - assertEquals(8, sheet.getDefaultColumnWidth()); - assertEquals(8*256, sheet.getColumnWidth(0)); - - assertEquals(0xFF, sheet.getDefaultRowHeight()); - - wb1.close(); - - HSSFWorkbook wb2 = HSSFTestDataSamples.openSampleWorkbook( "34775.xls" ); - // second and third sheets miss DefaultColWidthRecord - for(int i = 1; i <= 2; i++){ - int dw = wb2.getSheetAt( i ).getDefaultColumnWidth(); - assertEquals(8, dw); - int cw = wb2.getSheetAt( i ).getColumnWidth(0); - assertEquals(8*256, cw); - - assertEquals(0xFF, sheet.getDefaultRowHeight()); - } - wb2.close(); - } - - /** - * Some utilities write Excel files without the ROW records. - * Excel, ooo, and google docs are OK with this. - * Now POI is too. - */ - @Test - public void missingRowRecords_bug41187() throws IOException { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("ex41187-19267.xls"); - - HSSFSheet sheet = wb.getSheetAt(0); - HSSFRow row = sheet.getRow(0); - assertNotNull("Identified bug 41187 a", row); - - assertNotEquals("Identified bug 41187 b", (short)0, row.getHeight()); - - assertEquals("Hi Excel!", row.getCell(0).getRichStringCellValue().getString()); - // check row height for 'default' flag - assertEquals((short)0xFF, row.getHeight()); - - HSSFTestDataSamples.writeOutAndReadBack(wb).close(); - - wb.close(); - } - - /** - * If we clone a sheet containing drawings, - * we must allocate a new ID of the drawing group and re-create shape IDs - * - * See bug #45720. - */ - @Test - public void cloneSheetWithDrawings() throws IOException { - HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("45720.xls"); - - HSSFSheet sheet1 = wb1.getSheetAt(0); - - wb1.getWorkbook().findDrawingGroup(); - DrawingManager2 dm1 = wb1.getWorkbook().getDrawingManager(); - - wb1.cloneSheet(0); - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - - wb2.getWorkbook().findDrawingGroup(); - DrawingManager2 dm2 = wb2.getWorkbook().getDrawingManager(); - - //check EscherDggRecord - a workbook-level registry of drawing objects - assertEquals(dm1.getDgg().getMaxDrawingGroupId() + 1, dm2.getDgg().getMaxDrawingGroupId()); - - HSSFSheet sheet2 = wb2.getSheetAt(1); - - //check that id of the drawing group was updated - EscherDgRecord dg1 = (EscherDgRecord)sheet1.getDrawingPatriarch().getBoundAggregate().findFirstWithId(EscherDgRecord.RECORD_ID); - EscherDgRecord dg2 = (EscherDgRecord)sheet2.getDrawingPatriarch().getBoundAggregate().findFirstWithId(EscherDgRecord.RECORD_ID); - int dg_id_1 = dg1.getOptions() >> 4; - int dg_id_2 = dg2.getOptions() >> 4; - assertEquals(dg_id_1 + 1, dg_id_2); - - //TODO: check shapeId in the cloned sheet - wb2.close(); - } - - /** - * POI now (Sep 2008) allows sheet names longer than 31 chars (for other apps besides Excel). - * Since Excel silently truncates to 31, make sure that POI enforces uniqueness on the first - * 31 chars. - */ - @Test - public void longSheetNames() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - final String SAME_PREFIX = "A123456789B123456789C123456789"; // 30 chars - - wb.createSheet(SAME_PREFIX + "Dxxxx"); - try { - wb.createSheet(SAME_PREFIX + "Dyyyy"); // identical up to the 32nd char - fail("Expected exception not thrown"); - } catch (IllegalArgumentException e) { - assertEquals("The workbook already contains a sheet named 'A123456789B123456789C123456789Dyyyy'", e.getMessage()); - } - wb.createSheet(SAME_PREFIX + "Exxxx"); // OK - differs in the 31st char - wb.close(); - } - - /** - * Tests that we can read existing column styles - */ - @Test - public void readColumnStyles() throws IOException { - HSSFWorkbook wbNone = HSSFTestDataSamples.openSampleWorkbook("ColumnStyleNone.xls"); - HSSFWorkbook wbSimple = HSSFTestDataSamples.openSampleWorkbook("ColumnStyle1dp.xls"); - HSSFWorkbook wbComplex = HSSFTestDataSamples.openSampleWorkbook("ColumnStyle1dpColoured.xls"); - - // Presence / absence checks - assertNull(wbNone.getSheetAt(0).getColumnStyle(0)); - assertNull(wbNone.getSheetAt(0).getColumnStyle(1)); - - assertNull(wbSimple.getSheetAt(0).getColumnStyle(0)); - assertNotNull(wbSimple.getSheetAt(0).getColumnStyle(1)); - - assertNull(wbComplex.getSheetAt(0).getColumnStyle(0)); - assertNotNull(wbComplex.getSheetAt(0).getColumnStyle(1)); - - // Details checks - HSSFCellStyle bs = wbSimple.getSheetAt(0).getColumnStyle(1); - assertEquals(62, bs.getIndex()); - assertEquals("#,##0.0_ ;\\-#,##0.0\\ ", bs.getDataFormatString()); - assertEquals("Calibri", bs.getFont(wbSimple).getFontName()); - assertEquals(11*20, bs.getFont(wbSimple).getFontHeight()); - assertEquals(8, bs.getFont(wbSimple).getColor()); - assertFalse(bs.getFont(wbSimple).getItalic()); - assertEquals(HSSFFont.BOLDWEIGHT_NORMAL, bs.getFont(wbSimple).getBoldweight()); - - - HSSFCellStyle cs = wbComplex.getSheetAt(0).getColumnStyle(1); - assertEquals(62, cs.getIndex()); - assertEquals("#,##0.0_ ;\\-#,##0.0\\ ", cs.getDataFormatString()); - assertEquals("Arial", cs.getFont(wbComplex).getFontName()); - assertEquals(8*20, cs.getFont(wbComplex).getFontHeight()); - assertEquals(10, cs.getFont(wbComplex).getColor()); - assertFalse(cs.getFont(wbComplex).getItalic()); - assertTrue(cs.getFont(wbComplex).getBold()); - - wbComplex.close(); - wbSimple.close(); - wbNone.close(); - } - - /** - * Tests the arabic setting - */ - @Test - public void arabic() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet s = wb.createSheet(); - - assertFalse(s.isRightToLeft()); - s.setRightToLeft(true); - assertTrue(s.isRightToLeft()); - wb.close(); - } - - @Test - public void autoFilter() throws IOException { - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet sh = wb1.createSheet(); - InternalWorkbook iwb = wb1.getWorkbook(); - InternalSheet ish = sh.getSheet(); - - assertNull( iwb.getSpecificBuiltinRecord(NameRecord.BUILTIN_FILTER_DB, 1) ); - assertNull( ish.findFirstRecordBySid(AutoFilterInfoRecord.sid) ); - - CellRangeAddress range = CellRangeAddress.valueOf("A1:B10"); - sh.setAutoFilter(range); - - NameRecord name = iwb.getSpecificBuiltinRecord(NameRecord.BUILTIN_FILTER_DB, 1); - assertNotNull( name ); - - // The built-in name for auto-filter must consist of a single Area3d Ptg. - Ptg[] ptg = name.getNameDefinition(); - assertEquals("The built-in name for auto-filter must consist of a single Area3d Ptg", 1, ptg.length); - assertTrue("The built-in name for auto-filter must consist of a single Area3d Ptg", ptg[0] instanceof Area3DPtg); - - Area3DPtg aref = (Area3DPtg)ptg[0]; - assertEquals(range.getFirstColumn(), aref.getFirstColumn()); - assertEquals(range.getFirstRow(), aref.getFirstRow()); - assertEquals(range.getLastColumn(), aref.getLastColumn()); - assertEquals(range.getLastRow(), aref.getLastRow()); - - // verify AutoFilterInfoRecord - AutoFilterInfoRecord afilter = (AutoFilterInfoRecord)ish.findFirstRecordBySid(AutoFilterInfoRecord.sid); - assertNotNull(afilter ); - assertEquals(2, afilter.getNumEntries()); //filter covers two columns - - HSSFPatriarch dr = sh.getDrawingPatriarch(); - assertNotNull(dr); - HSSFSimpleShape comboBoxShape = (HSSFSimpleShape)dr.getChildren().get(0); - assertEquals(comboBoxShape.getShapeType(), HSSFSimpleShape.OBJECT_TYPE_COMBO_BOX); - - assertNull( ish.findFirstRecordBySid(ObjRecord.sid) ); // ObjRecord will appear after serializetion - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sh = wb2.getSheetAt(0); - ish = sh.getSheet(); - ObjRecord objRecord = (ObjRecord)ish.findFirstRecordBySid(ObjRecord.sid); - List subRecords = objRecord.getSubRecords(); - assertEquals(3, subRecords.size()); - assertTrue(subRecords.get(0) instanceof CommonObjectDataSubRecord ); - assertTrue(subRecords.get(1) instanceof FtCblsSubRecord ); // must be present, see Bug 51481 - assertTrue(subRecords.get(2) instanceof LbsDataSubRecord ); - wb2.close(); - } - - @Test - public void getSetColumnHiddenShort() throws IOException { - Workbook workbook = new HSSFWorkbook(); - Sheet sheet = workbook.createSheet("Sheet 1"); - sheet.setColumnHidden((short)2, true); - assertTrue(sheet.isColumnHidden((short)2)); - workbook.close(); - } - - @Test - public void columnWidthShort() throws IOException { - HSSFWorkbook wb1 = new HSSFWorkbook(); - Sheet sheet = wb1.createSheet(); - - //default column width measured in characters - sheet.setDefaultColumnWidth((short)10); - assertEquals(10, sheet.getDefaultColumnWidth()); - //columns A-C have default width - assertEquals(256*10, sheet.getColumnWidth((short)0)); - assertEquals(256*10, sheet.getColumnWidth((short)1)); - assertEquals(256*10, sheet.getColumnWidth((short)2)); - - //set custom width for D-F - for (char i = 'D'; i <= 'F'; i++) { - //Sheet#setColumnWidth accepts the width in units of 1/256th of a character width - int w = 256*12; - sheet.setColumnWidth((short)i, w); - assertEquals(w, sheet.getColumnWidth((short)i)); - } - //reset the default column width, columns A-C change, D-F still have custom width - sheet.setDefaultColumnWidth((short)20); - assertEquals(20, sheet.getDefaultColumnWidth()); - assertEquals(256*20, sheet.getColumnWidth((short)0)); - assertEquals(256*20, sheet.getColumnWidth((short)1)); - assertEquals(256*20, sheet.getColumnWidth((short)2)); - for (char i = 'D'; i <= 'F'; i++) { - int w = 256*12; - assertEquals(w, sheet.getColumnWidth((short)i)); - } - - // check for 16-bit signed/unsigned error: - sheet.setColumnWidth((short)10, 40000); - assertEquals(40000, sheet.getColumnWidth((short)10)); - - //The maximum column width for an individual cell is 255 characters - try { - sheet.setColumnWidth((short)9, 256*256); - fail("expected exception"); - } catch(IllegalArgumentException e){ - assertEquals("The maximum column width for an individual cell is 255 characters.", e.getMessage()); - } - - //serialize and read again - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - - sheet = wb2.getSheetAt(0); - assertEquals(20, sheet.getDefaultColumnWidth()); - //columns A-C have default width - assertEquals(256*20, sheet.getColumnWidth((short)0)); - assertEquals(256*20, sheet.getColumnWidth((short)1)); - assertEquals(256*20, sheet.getColumnWidth((short)2)); - //columns D-F have custom width - for (char i = 'D'; i <= 'F'; i++) { - short w = (256*12); - assertEquals(w, sheet.getColumnWidth((short)i)); - } - assertEquals(40000, sheet.getColumnWidth((short)10)); - - wb2.close(); - } - - @Test - public void showInPane() throws IOException { - Workbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - sheet.showInPane(2, 3); - - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Maximum row number is 65535"); - sheet.showInPane(Integer.MAX_VALUE, 3); - wb.close(); - } - - @Test - public void drawingRecords() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet(); - - /* TODO: NPE? - sheet.dumpDrawingRecords(false); - sheet.dumpDrawingRecords(true);*/ - assertNull(sheet.getDrawingEscherAggregate()); - wb.close(); - } - - @Test - public void bug55723b() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - Sheet sheet = wb.createSheet(); - - // stored with a special name - assertNull(wb.getWorkbook().getSpecificBuiltinRecord(NameRecord.BUILTIN_FILTER_DB, 1)); - - CellRangeAddress range = CellRangeAddress.valueOf("A:B"); - AutoFilter filter = sheet.setAutoFilter(range); - assertNotNull(filter); - - // stored with a special name - NameRecord record = wb.getWorkbook().getSpecificBuiltinRecord(NameRecord.BUILTIN_FILTER_DB, 1); - assertNotNull(record); - wb.close(); - } - - @Test - public void test58746() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - - HSSFSheet first = wb.createSheet("first"); - first.createRow(0).createCell(0).setCellValue(1); - - HSSFSheet second = wb.createSheet("second"); - second.createRow(0).createCell(0).setCellValue(2); - - HSSFSheet third = wb.createSheet("third"); - HSSFRow row = third.createRow(0); - row.createCell(0).setCellFormula("first!A1"); - row.createCell(1).setCellFormula("second!A1"); - - // re-order for sheet "third" - wb.setSheetOrder("third", 0); - - // verify results - assertEquals("third", wb.getSheetAt(0).getSheetName()); - assertEquals("first", wb.getSheetAt(1).getSheetName()); - assertEquals("second", wb.getSheetAt(2).getSheetName()); - - assertEquals("first!A1", wb.getSheetAt(0).getRow(0).getCell(0).getCellFormula()); - assertEquals("second!A1", wb.getSheetAt(0).getRow(0).getCell(1).getCellFormula()); - - wb.close(); - } - - @Test - public void bug59135() throws IOException { - HSSFWorkbook wb1 = new HSSFWorkbook(); - wb1.createSheet().protectSheet("1111.2222.3333.1234"); - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - - assertEquals((short)0xb86b, wb2.getSheetAt(0).getPassword()); - wb2.close(); - - HSSFWorkbook wb3 = new HSSFWorkbook(); - wb3.createSheet().protectSheet("1111.2222.3333.12345"); - HSSFWorkbook wb4 = HSSFTestDataSamples.writeOutAndReadBack(wb3); - wb3.close(); - - assertEquals((short)0xbecc, wb4.getSheetAt(0).getPassword()); - wb4.close(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheetAutosizeColumn.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheetAutosizeColumn.java deleted file mode 100644 index 7538d4acb..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheetAutosizeColumn.java +++ /dev/null @@ -1,34 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.ss.usermodel.*; - -/** - * Test auto-sizing columns in HSSF - * - * @author Yegor Kozlov - */ -public final class TestHSSFSheetAutosizeColumn extends BaseTestSheetAutosizeColumn { - - public TestHSSFSheetAutosizeColumn() { - super(HSSFITestDataProvider.instance); - } - -} \ No newline at end of file diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheetShiftRows.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheetShiftRows.java deleted file mode 100644 index 8c4c08d4f..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheetShiftRows.java +++ /dev/null @@ -1,31 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.ss.usermodel.BaseTestSheetShiftRows; - -/** - * @author Yegor Kozlov - */ -public final class TestHSSFSheetShiftRows extends BaseTestSheetShiftRows { - - public TestHSSFSheetShiftRows() { - super(HSSFITestDataProvider.instance); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheetUpdateArrayFormulas.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheetUpdateArrayFormulas.java deleted file mode 100644 index dfa2bae70..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheetUpdateArrayFormulas.java +++ /dev/null @@ -1,133 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.IOException; - -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.hssf.record.ArrayRecord; -import org.apache.poi.hssf.record.FormulaRecord; -import org.apache.poi.hssf.record.Record; -import org.apache.poi.hssf.record.aggregates.FormulaRecordAggregate; -import org.apache.poi.hssf.record.aggregates.RowRecordsAggregate; -import org.apache.poi.hssf.record.aggregates.SharedValueManager; -import org.apache.poi.hssf.record.aggregates.TestSharedValueManager; -import org.apache.poi.ss.usermodel.BaseTestSheetUpdateArrayFormulas; -import org.apache.poi.ss.usermodel.CellRange; -import org.apache.poi.ss.util.CellRangeAddress; -import org.junit.Test; - -/** - * Test array formulas in HSSF - * - * @author Yegor Kozlov - * @author Josh Micich - */ -public final class TestHSSFSheetUpdateArrayFormulas extends BaseTestSheetUpdateArrayFormulas { - - public TestHSSFSheetUpdateArrayFormulas() { - super(HSSFITestDataProvider.instance); - } - - // Test methods common with XSSF are in superclass - // Local methods here test HSSF-specific details of updating array formulas - @Test - public void testHSSFSetArrayFormula_singleCell() throws IOException { - HSSFWorkbook workbook = new HSSFWorkbook(); - HSSFSheet sheet = workbook.createSheet("Sheet1"); - - CellRangeAddress range = new CellRangeAddress(2, 2, 2, 2); - HSSFCell[] cells = sheet.setArrayFormula("SUM(C11:C12*D11:D12)", range).getFlattenedCells(); - assertEquals(1, cells.length); - - // sheet.setArrayFormula creates rows and cells for the designated range - assertNotNull(sheet.getRow(2)); - HSSFCell cell = sheet.getRow(2).getCell(2); - assertNotNull(cell); - - assertTrue(cell.isPartOfArrayFormulaGroup()); - //retrieve the range and check it is the same - assertEquals(range.formatAsString(), cell.getArrayFormulaRange().formatAsString()); - - FormulaRecordAggregate agg = (FormulaRecordAggregate)cell.getCellValueRecord(); - assertEquals(range.formatAsString(), agg.getArrayFormulaRange().formatAsString()); - assertTrue(agg.isPartOfArrayFormula()); - - workbook.close(); - } - - /** - * Makes sure the internal state of HSSFSheet is consistent after removing array formulas - */ - @Test - public void testAddRemoveArrayFormulas_recordUpdates() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet s = wb.createSheet("Sheet1"); - - CellRange cr = s.setArrayFormula("123", CellRangeAddress.valueOf("B5:C6")); - Record[] recs; - int ix; - recs = RecordInspector.getRecords(s, 0); - ix = findRecordOfType(recs, ArrayRecord.class, 0); - confirmRecordClass(recs, ix-1, FormulaRecord.class); - confirmRecordClass(recs, ix+1, FormulaRecord.class); - confirmRecordClass(recs, ix+2, FormulaRecord.class); - confirmRecordClass(recs, ix+3, FormulaRecord.class); - // just one array record - assertTrue(findRecordOfType(recs, ArrayRecord.class, ix+1) < 0); - - s.removeArrayFormula(cr.getTopLeftCell()); - - // Make sure the array formula has been removed properly - - recs = RecordInspector.getRecords(s, 0); - assertTrue(findRecordOfType(recs, ArrayRecord.class, 0) < 0); - assertTrue(findRecordOfType(recs, FormulaRecord.class, 0) < 0); - RowRecordsAggregate rra = s.getSheet().getRowsAggregate(); - SharedValueManager svm = TestSharedValueManager.extractFromRRA(rra); - if (svm.getArrayRecord(4, 1) != null) { - fail("Array record was not cleaned up properly."); - } - - wb.close(); - } - - private static void confirmRecordClass(Record[] recs, int index, Class cls) { - if (recs.length <= index) { - fail("Expected (" + cls.getName() + ") at index " - + index + " but array length is " + recs.length + "."); - } - assertEquals(cls, recs[index].getClass()); - } - /** - * @return -1 if not found - */ - private static int findRecordOfType(Record[] recs, Class type, int fromIndex) { - for (int i=fromIndex; iHSSFTextbox. - * - * @author Yegor Kozlov (yegor at apache.org) - */ -public final class TestHSSFTextbox extends TestCase{ - - /** - * Test that accessors to horizontal and vertical alignment work properly - */ - public void testAlignment() { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sh1 = wb.createSheet(); - HSSFPatriarch patriarch = sh1.createDrawingPatriarch(); - - HSSFTextbox textbox = patriarch.createTextbox(new HSSFClientAnchor(0, 0, 0, 0, (short) 1, 1, (short) 6, 4)); - HSSFRichTextString str = new HSSFRichTextString("Hello, World"); - textbox.setString(str); - textbox.setHorizontalAlignment(HSSFTextbox.HORIZONTAL_ALIGNMENT_CENTERED); - textbox.setVerticalAlignment(HSSFTextbox.VERTICAL_ALIGNMENT_CENTER); - - assertEquals(HSSFTextbox.HORIZONTAL_ALIGNMENT_CENTERED, textbox.getHorizontalAlignment()); - assertEquals(HSSFTextbox.VERTICAL_ALIGNMENT_CENTER, textbox.getVerticalAlignment()); - } - - /** - * Excel requires at least one format run in HSSFTextbox. - * When inserting text make sure that if font is not set we must set the default one. - */ - public void testSetDeafultTextFormat() { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet(); - HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); - - HSSFTextbox textbox1 = patriarch.createTextbox(new HSSFClientAnchor(0,0,0,0,(short)1,1,(short)3,3)); - HSSFRichTextString rt1 = new HSSFRichTextString("Hello, World!"); - assertEquals(0, rt1.numFormattingRuns()); - textbox1.setString(rt1); - - HSSFRichTextString rt2 = textbox1.getString(); - assertEquals(1, rt2.numFormattingRuns()); - assertEquals(HSSFRichTextString.NO_FONT, rt2.getFontOfFormattingRun(0)); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFWorkbook.java b/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFWorkbook.java deleted file mode 100644 index 55e1d77db..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestHSSFWorkbook.java +++ /dev/null @@ -1,1327 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.apache.poi.POITestCase.assertContains; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import junit.framework.AssertionFailedError; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.ddf.EscherBSERecord; -import org.apache.poi.hpsf.ClassID; -import org.apache.poi.hssf.HSSFITestDataProvider; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.OldExcelFormatException; -import org.apache.poi.hssf.model.HSSFFormulaParser; -import org.apache.poi.hssf.model.InternalSheet; -import org.apache.poi.hssf.model.InternalWorkbook; -import org.apache.poi.hssf.record.CFRuleRecord; -import org.apache.poi.hssf.record.NameRecord; -import org.apache.poi.hssf.record.Record; -import org.apache.poi.hssf.record.RecordBase; -import org.apache.poi.hssf.record.WindowOneRecord; -import org.apache.poi.poifs.filesystem.DirectoryEntry; -import org.apache.poi.poifs.filesystem.DirectoryNode; -import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; -import org.apache.poi.poifs.filesystem.OPOIFSFileSystem; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.ss.formula.ptg.Area3DPtg; -import org.apache.poi.ss.usermodel.BaseTestWorkbook; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.ConditionalFormatting; -import org.apache.poi.ss.usermodel.ConditionalFormattingRule; -import org.apache.poi.ss.usermodel.Name; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.SheetConditionalFormatting; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.util.IOUtils; -import org.apache.poi.util.LittleEndian; -import org.apache.poi.util.RecordFormatException; -import org.apache.poi.util.TempFile; -import org.junit.Ignore; -import org.junit.Test; - -/** - * Tests for {@link HSSFWorkbook} - */ -public final class TestHSSFWorkbook extends BaseTestWorkbook { - private static final HSSFITestDataProvider _testDataProvider = HSSFITestDataProvider.instance; - - public TestHSSFWorkbook() { - super(_testDataProvider); - } - - /** - * gives test code access to the {@link InternalWorkbook} within {@link HSSFWorkbook} - */ - public static InternalWorkbook getInternalWorkbook(HSSFWorkbook wb) { - return wb.getWorkbook(); - } - - /** - * Tests for {@link HSSFWorkbook#isHidden()} etc - * @throws IOException - */ - @Test - public void hidden() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - - WindowOneRecord w1 = wb.getWorkbook().getWindowOne(); - - assertEquals(false, wb.isHidden()); - assertEquals(false, w1.getHidden()); - - wb.setHidden(true); - assertEquals(true, wb.isHidden()); - assertEquals(true, w1.getHidden()); - - HSSFWorkbook wbBack = HSSFTestDataSamples.writeOutAndReadBack(wb); - w1 = wbBack.getWorkbook().getWindowOne(); - - wbBack.setHidden(true); - assertEquals(true, wbBack.isHidden()); - assertEquals(true, w1.getHidden()); - - wbBack.setHidden(false); - assertEquals(false, wbBack.isHidden()); - assertEquals(false, w1.getHidden()); - - wbBack.close(); - wb.close(); - } - - @Test - public void readWriteWithCharts() throws IOException { - Sheet s; - - // Single chart, two sheets - HSSFWorkbook b1 = HSSFTestDataSamples.openSampleWorkbook("44010-SingleChart.xls"); - assertEquals(2, b1.getNumberOfSheets()); - assertEquals("Graph2", b1.getSheetName(1)); - s = b1.getSheetAt(1); - assertEquals(0, s.getFirstRowNum()); - assertEquals(8, s.getLastRowNum()); - - // Has chart on 1st sheet?? - // FIXME - assertNotNull(b1.getSheetAt(0).getDrawingPatriarch()); - assertNull(b1.getSheetAt(1).getDrawingPatriarch()); - assertFalse(b1.getSheetAt(0).getDrawingPatriarch().containsChart()); - b1.close(); - - // We've now called getDrawingPatriarch() so - // everything will be all screwy - // So, start again - HSSFWorkbook b2 = HSSFTestDataSamples.openSampleWorkbook("44010-SingleChart.xls"); - - HSSFWorkbook b3 = HSSFTestDataSamples.writeOutAndReadBack(b2); - b2.close(); - - assertEquals(2, b3.getNumberOfSheets()); - s = b3.getSheetAt(1); - assertEquals(0, s.getFirstRowNum()); - assertEquals(8, s.getLastRowNum()); - b3.close(); - - // Two charts, three sheets - HSSFWorkbook b4 = HSSFTestDataSamples.openSampleWorkbook("44010-TwoCharts.xls"); - assertEquals(3, b4.getNumberOfSheets()); - - s = b4.getSheetAt(1); - assertEquals(0, s.getFirstRowNum()); - assertEquals(8, s.getLastRowNum()); - s = b4.getSheetAt(2); - assertEquals(0, s.getFirstRowNum()); - assertEquals(8, s.getLastRowNum()); - - // Has chart on 1st sheet?? - // FIXME - assertNotNull(b4.getSheetAt(0).getDrawingPatriarch()); - assertNull(b4.getSheetAt(1).getDrawingPatriarch()); - assertNull(b4.getSheetAt(2).getDrawingPatriarch()); - assertFalse(b4.getSheetAt(0).getDrawingPatriarch().containsChart()); - b4.close(); - - // We've now called getDrawingPatriarch() so - // everything will be all screwy - // So, start again - HSSFWorkbook b5 = HSSFTestDataSamples.openSampleWorkbook("44010-TwoCharts.xls"); - - Workbook b6 = HSSFTestDataSamples.writeOutAndReadBack(b5); - b5.close(); - assertEquals(3, b6.getNumberOfSheets()); - - s = b6.getSheetAt(1); - assertEquals(0, s.getFirstRowNum()); - assertEquals(8, s.getLastRowNum()); - s = b6.getSheetAt(2); - assertEquals(0, s.getFirstRowNum()); - assertEquals(8, s.getLastRowNum()); - b6.close(); - } - - @Test - public void selectedSheet_bug44523() throws IOException { - HSSFWorkbook wb=new HSSFWorkbook(); - HSSFSheet sheet1 = wb.createSheet("Sheet1"); - HSSFSheet sheet2 = wb.createSheet("Sheet2"); - HSSFSheet sheet3 = wb.createSheet("Sheet3"); - HSSFSheet sheet4 = wb.createSheet("Sheet4"); - - confirmActiveSelected(sheet1, true); - confirmActiveSelected(sheet2, false); - confirmActiveSelected(sheet3, false); - confirmActiveSelected(sheet4, false); - - wb.setSelectedTab(1); - - // Demonstrate bug 44525: - // Well... not quite, since isActive + isSelected were also added in the same bug fix - assertFalse("Identified bug 44523 a", sheet1.isSelected()); - wb.setActiveSheet(1); - assertFalse("Identified bug 44523 b", sheet1.isActive()); - - confirmActiveSelected(sheet1, false); - confirmActiveSelected(sheet2, true); - confirmActiveSelected(sheet3, false); - confirmActiveSelected(sheet4, false); - - wb.close(); - } - - private static List arrayToList(int[] array) { - List list = new ArrayList(array.length); - for ( Integer element : array ) { - list.add(element); - } - return list; - } - - private static void assertCollectionsEquals(Collection expected, Collection actual) { - assertEquals("size", expected.size(), actual.size()); - for (int e : expected) { - assertTrue(actual.contains(e)); - } - for (int a : actual) { - assertTrue(expected.contains(a)); - } - } - - @Test - public void selectMultiple() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet0 = wb.createSheet("Sheet0"); - HSSFSheet sheet1 = wb.createSheet("Sheet1"); - HSSFSheet sheet2 = wb.createSheet("Sheet2"); - HSSFSheet sheet3 = wb.createSheet("Sheet3"); - HSSFSheet sheet4 = wb.createSheet("Sheet4"); - HSSFSheet sheet5 = wb.createSheet("Sheet5"); - - - List selected = arrayToList(new int[] { 0, 2, 3 }); - wb.setSelectedTabs(selected); - - assertCollectionsEquals(selected, wb.getSelectedTabs()); - assertEquals(true, sheet0.isSelected()); - assertEquals(false, sheet1.isSelected()); - assertEquals(true, sheet2.isSelected()); - assertEquals(true, sheet3.isSelected()); - assertEquals(false, sheet4.isSelected()); - assertEquals(false, sheet5.isSelected()); - - selected = arrayToList(new int[] { 1, 3, 5 }); - wb.setSelectedTabs(selected); - - // previous selection should be cleared - assertCollectionsEquals(selected, wb.getSelectedTabs()); - assertEquals(false, sheet0.isSelected()); - assertEquals(true, sheet1.isSelected()); - assertEquals(false, sheet2.isSelected()); - assertEquals(true, sheet3.isSelected()); - assertEquals(false, sheet4.isSelected()); - assertEquals(true, sheet5.isSelected()); - - assertEquals(true, sheet0.isActive()); - assertEquals(false, sheet2.isActive()); - wb.setActiveSheet(2); - assertEquals(false, sheet0.isActive()); - assertEquals(true, sheet2.isActive()); - - /*{ // helpful if viewing this workbook in excel: - sheet0.createRow(0).createCell(0).setCellValue(new HSSFRichTextString("Sheet0")); - sheet1.createRow(0).createCell(0).setCellValue(new HSSFRichTextString("Sheet1")); - sheet2.createRow(0).createCell(0).setCellValue(new HSSFRichTextString("Sheet2")); - sheet3.createRow(0).createCell(0).setCellValue(new HSSFRichTextString("Sheet3")); - - try { - File fOut = TempFile.createTempFile("sheetMultiSelect", ".xls"); - FileOutputStream os = new FileOutputStream(fOut); - wb.write(os); - os.close(); - } catch (IOException e) { - throw new RuntimeException(e); - } - }*/ - - wb.close(); - } - - - @Test - public void activeSheetAfterDelete_bug40414() throws IOException { - HSSFWorkbook wb=new HSSFWorkbook(); - HSSFSheet sheet0 = wb.createSheet("Sheet0"); - HSSFSheet sheet1 = wb.createSheet("Sheet1"); - HSSFSheet sheet2 = wb.createSheet("Sheet2"); - HSSFSheet sheet3 = wb.createSheet("Sheet3"); - HSSFSheet sheet4 = wb.createSheet("Sheet4"); - - // confirm default activation/selection - confirmActiveSelected(sheet0, true); - confirmActiveSelected(sheet1, false); - confirmActiveSelected(sheet2, false); - confirmActiveSelected(sheet3, false); - confirmActiveSelected(sheet4, false); - - wb.setActiveSheet(3); - wb.setSelectedTab(3); - - confirmActiveSelected(sheet0, false); - confirmActiveSelected(sheet1, false); - confirmActiveSelected(sheet2, false); - confirmActiveSelected(sheet3, true); - confirmActiveSelected(sheet4, false); - - wb.removeSheetAt(3); - // after removing the only active/selected sheet, another should be active/selected in its place - assertTrue("identified bug 40414 a", sheet4.isSelected()); - assertTrue("identified bug 40414 b", sheet4.isActive()); - - confirmActiveSelected(sheet0, false); - confirmActiveSelected(sheet1, false); - confirmActiveSelected(sheet2, false); - confirmActiveSelected(sheet4, true); - - sheet3 = sheet4; // re-align local vars in this test case - - // Some more cases of removing sheets - - // Starting with a multiple selection, and different active sheet - wb.setSelectedTabs(new int[] { 1, 3, }); - wb.setActiveSheet(2); - confirmActiveSelected(sheet0, false, false); - confirmActiveSelected(sheet1, false, true); - confirmActiveSelected(sheet2, true, false); - confirmActiveSelected(sheet3, false, true); - - // removing a sheet that is not active, and not the only selected sheet - wb.removeSheetAt(3); - confirmActiveSelected(sheet0, false, false); - confirmActiveSelected(sheet1, false, true); - confirmActiveSelected(sheet2, true, false); - - // removing the only selected sheet - wb.removeSheetAt(1); - confirmActiveSelected(sheet0, false, false); - confirmActiveSelected(sheet2, true, true); - - // The last remaining sheet should always be active+selected - wb.removeSheetAt(1); - confirmActiveSelected(sheet0, true, true); - - wb.close(); - } - - private static void confirmActiveSelected(HSSFSheet sheet, boolean expected) { - confirmActiveSelected(sheet, expected, expected); - } - - - private static void confirmActiveSelected(HSSFSheet sheet, - boolean expectedActive, boolean expectedSelected) { - assertEquals("active", expectedActive, sheet.isActive()); - assertEquals("selected", expectedSelected, sheet.isSelected()); - } - - /** - * If Sheet.getSize() returns a different result to Sheet.serialize(), this will cause the BOF - * records to be written with invalid offset indexes. Excel does not like this, and such - * errors are particularly hard to track down. This test ensures that HSSFWorkbook throws - * a specific exception as soon as the situation is detected. See bugzilla 45066 - * @throws IOException - */ - @Test - public void sheetSerializeSizeMismatch_bug45066() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - InternalSheet sheet = wb.createSheet("Sheet1").getSheet(); - List sheetRecords = sheet.getRecords(); - // one way (of many) to cause the discrepancy is with a badly behaved record: - sheetRecords.add(new BadlyBehavedRecord()); - // There is also much logic inside Sheet that (if buggy) might also cause the discrepancy - try { - wb.getBytes(); - fail("Identified bug 45066 a"); - } catch (IllegalStateException e) { - // Expected badly behaved sheet record to cause exception - assertTrue(e.getMessage().startsWith("Actual serialized sheet size")); - } - - wb.close(); - } - - /** - * Checks that us and HSSFName play nicely with named ranges - * that point to deleted sheets - */ - @Test - public void namesToDeleteSheets() throws IOException { - HSSFWorkbook b = HSSFTestDataSamples.openSampleWorkbook("30978-deleted.xls"); - assertEquals(3, b.getNumberOfNames()); - - // Sheet 2 is deleted - assertEquals("Sheet1", b.getSheetName(0)); - assertEquals("Sheet3", b.getSheetName(1)); - - Area3DPtg ptg; - NameRecord nr; - HSSFName n; - - /* ======= Name pointing to deleted sheet ====== */ - - // First at low level - nr = b.getWorkbook().getNameRecord(0); - assertEquals("On2", nr.getNameText()); - assertEquals(0, nr.getSheetNumber()); - assertEquals(1, nr.getExternSheetNumber()); - assertEquals(1, nr.getNameDefinition().length); - - ptg = (Area3DPtg)nr.getNameDefinition()[0]; - assertEquals(1, ptg.getExternSheetIndex()); - assertEquals(0, ptg.getFirstColumn()); - assertEquals(0, ptg.getFirstRow()); - assertEquals(0, ptg.getLastColumn()); - assertEquals(2, ptg.getLastRow()); - - // Now at high level - n = b.getNameAt(0); - assertEquals("On2", n.getNameName()); - assertEquals("", n.getSheetName()); - assertEquals("#REF!$A$1:$A$3", n.getRefersToFormula()); - - - /* ======= Name pointing to 1st sheet ====== */ - - // First at low level - nr = b.getWorkbook().getNameRecord(1); - assertEquals("OnOne", nr.getNameText()); - assertEquals(0, nr.getSheetNumber()); - assertEquals(0, nr.getExternSheetNumber()); - assertEquals(1, nr.getNameDefinition().length); - - ptg = (Area3DPtg)nr.getNameDefinition()[0]; - assertEquals(0, ptg.getExternSheetIndex()); - assertEquals(0, ptg.getFirstColumn()); - assertEquals(2, ptg.getFirstRow()); - assertEquals(0, ptg.getLastColumn()); - assertEquals(3, ptg.getLastRow()); - - // Now at high level - n = b.getNameAt(1); - assertEquals("OnOne", n.getNameName()); - assertEquals("Sheet1", n.getSheetName()); - assertEquals("Sheet1!$A$3:$A$4", n.getRefersToFormula()); - - - /* ======= Name pointing to 3rd sheet ====== */ - - // First at low level - nr = b.getWorkbook().getNameRecord(2); - assertEquals("OnSheet3", nr.getNameText()); - assertEquals(0, nr.getSheetNumber()); - assertEquals(2, nr.getExternSheetNumber()); - assertEquals(1, nr.getNameDefinition().length); - - ptg = (Area3DPtg)nr.getNameDefinition()[0]; - assertEquals(2, ptg.getExternSheetIndex()); - assertEquals(0, ptg.getFirstColumn()); - assertEquals(0, ptg.getFirstRow()); - assertEquals(0, ptg.getLastColumn()); - assertEquals(1, ptg.getLastRow()); - - // Now at high level - n = b.getNameAt(2); - assertEquals("OnSheet3", n.getNameName()); - assertEquals("Sheet3", n.getSheetName()); - assertEquals("Sheet3!$A$1:$A$2", n.getRefersToFormula()); - - b.close(); - } - - /** - * result returned by getRecordSize() differs from result returned by serialize() - */ - private static final class BadlyBehavedRecord extends Record { - public BadlyBehavedRecord() { - // - } - @Override - public short getSid() { - return 0x777; - } - @Override - public int serialize(int offset, byte[] data) { - return 4; - } - @Override - public int getRecordSize() { - return 8; - } - } - - /** - * The sample file provided with bug 45582 seems to have one extra byte after the EOFRecord - */ - @Test - public void extraDataAfterEOFRecord() { - try { - HSSFTestDataSamples.openSampleWorkbook("ex45582-22397.xls"); - } catch (RecordFormatException e) { - if (e.getCause() instanceof LittleEndian.BufferUnderrunException) { - throw new AssertionFailedError("Identified bug 45582"); - } - } - } - - /** - * Test to make sure that NameRecord.getSheetNumber() is interpreted as a - * 1-based sheet tab index (not a 1-based extern sheet index) - */ - @Test - public void findBuiltInNameRecord() throws IOException { - // testRRaC has multiple (3) built-in name records - // The second print titles name record has getSheetNumber()==4 - HSSFWorkbook wb1 = HSSFTestDataSamples.openSampleWorkbook("testRRaC.xls"); - NameRecord nr; - assertEquals(3, wb1.getWorkbook().getNumNames()); - nr = wb1.getWorkbook().getNameRecord(2); - // TODO - render full row and full column refs properly - assertEquals("Sheet2!$A$1:$IV$1", HSSFFormulaParser.toFormulaString(wb1, nr.getNameDefinition())); // 1:1 - - try { - wb1.getSheetAt(3).setRepeatingRows(CellRangeAddress.valueOf("9:12")); - wb1.getSheetAt(3).setRepeatingColumns(CellRangeAddress.valueOf("E:F")); - } catch (RuntimeException e) { - if (e.getMessage().equals("Builtin (7) already exists for sheet (4)")) { - // there was a problem in the code which locates the existing print titles name record - fail("Identified bug 45720b"); - } - wb1.close(); - throw e; - } - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - assertEquals(3, wb2.getWorkbook().getNumNames()); - nr = wb2.getWorkbook().getNameRecord(2); - assertEquals("Sheet2!E:F,Sheet2!$A$9:$IV$12", HSSFFormulaParser.toFormulaString(wb2, nr.getNameDefinition())); // E:F,9:12 - wb2.close(); - } - - /** - * Test that the storage clsid property is preserved - */ - @Test - public void bug47920() throws IOException { - POIFSFileSystem fs1 = new POIFSFileSystem(POIDataSamples.getSpreadSheetInstance().openResourceAsStream("47920.xls")); - HSSFWorkbook wb = new HSSFWorkbook(fs1); - ClassID clsid1 = fs1.getRoot().getStorageClsid(); - - ByteArrayOutputStream out = new ByteArrayOutputStream(4096); - wb.write(out); - byte[] bytes = out.toByteArray(); - POIFSFileSystem fs2 = new POIFSFileSystem(new ByteArrayInputStream(bytes)); - ClassID clsid2 = fs2.getRoot().getStorageClsid(); - - assertTrue(clsid1.equals(clsid2)); - - fs2.close(); - wb.close(); - fs1.close(); - } - - /** - * If we try to open an old (pre-97) workbook, we get a helpful - * Exception give to explain what we've done wrong - */ - @Test - public void helpfulExceptionOnOldFiles() throws Exception { - InputStream excel4 = POIDataSamples.getSpreadSheetInstance().openResourceAsStream("testEXCEL_4.xls"); - try { - new HSSFWorkbook(excel4).close(); - fail("Shouldn't be able to load an Excel 4 file"); - } catch (OldExcelFormatException e) { - assertContains(e.getMessage(), "BIFF4"); - } - excel4.close(); - - InputStream excel5 = POIDataSamples.getSpreadSheetInstance().openResourceAsStream("testEXCEL_5.xls"); - try { - new HSSFWorkbook(excel5).close(); - fail("Shouldn't be able to load an Excel 5 file"); - } catch (OldExcelFormatException e) { - assertContains(e.getMessage(), "BIFF5"); - } - excel5.close(); - - InputStream excel95 = POIDataSamples.getSpreadSheetInstance().openResourceAsStream("testEXCEL_95.xls"); - try { - new HSSFWorkbook(excel95).close(); - fail("Shouldn't be able to load an Excel 95 file"); - } catch (OldExcelFormatException e) { - assertContains(e.getMessage(), "BIFF5"); - } - excel95.close(); - } - - /** - * Tests that we can work with both {@link POIFSFileSystem} - * and {@link NPOIFSFileSystem} - */ - @Test - public void differentPOIFS() throws Exception { - // Open the two filesystems - DirectoryNode[] files = new DirectoryNode[2]; - POIFSFileSystem poifsFileSystem = new POIFSFileSystem(HSSFTestDataSamples.openSampleFileStream("Simple.xls")); - try { - files[0] = poifsFileSystem.getRoot(); - NPOIFSFileSystem npoifsFileSystem = new NPOIFSFileSystem(HSSFTestDataSamples.getSampleFile("Simple.xls")); - try { - files[1] = npoifsFileSystem.getRoot(); - - // Open without preserving nodes - for(DirectoryNode dir : files) { - HSSFWorkbook workbook = new HSSFWorkbook(dir, false); - HSSFSheet sheet = workbook.getSheetAt(0); - HSSFCell cell = sheet.getRow(0).getCell(0); - assertEquals("replaceMe", cell .getRichStringCellValue().getString()); - - workbook.close(); - } - - // Now re-check with preserving - for(DirectoryNode dir : files) { - HSSFWorkbook workbook = new HSSFWorkbook(dir, true); - HSSFSheet sheet = workbook.getSheetAt(0); - HSSFCell cell = sheet.getRow(0).getCell(0); - assertEquals("replaceMe", cell .getRichStringCellValue().getString()); - - workbook.close(); - } - } finally { - npoifsFileSystem.close(); - } - } finally { - poifsFileSystem.close(); - } - } - - @Test - public void wordDocEmbeddedInXls() throws IOException { - // Open the two filesystems - DirectoryNode[] files = new DirectoryNode[2]; - POIFSFileSystem poifsFileSystem = new POIFSFileSystem(HSSFTestDataSamples.openSampleFileStream("WithEmbeddedObjects.xls")); - try { - files[0] = poifsFileSystem.getRoot(); - NPOIFSFileSystem npoifsFileSystem = new NPOIFSFileSystem(HSSFTestDataSamples.getSampleFile("WithEmbeddedObjects.xls")); - try { - files[1] = npoifsFileSystem.getRoot(); - - // Check the embedded parts - for(DirectoryNode root : files) { - HSSFWorkbook hw = new HSSFWorkbook(root, true); - List objects = hw.getAllEmbeddedObjects(); - boolean found = false; - for (HSSFObjectData embeddedObject : objects) { - if (embeddedObject.hasDirectoryEntry()) { - DirectoryEntry dir = embeddedObject.getDirectory(); - if (dir instanceof DirectoryNode) { - DirectoryNode dNode = (DirectoryNode) dir; - if (hasEntry(dNode, "WordDocument")) { - found = true; - } - } - } - } - assertTrue(found); - - hw.close(); - } - } finally { - npoifsFileSystem.close(); - } - } finally { - poifsFileSystem.close(); - } - } - - /** - * Checks that we can open a workbook with NPOIFS, and write it out - * again (via POIFS) and have it be valid - * @throws IOException - */ - @Test - public void writeWorkbookFromNPOIFS() throws IOException { - InputStream is = HSSFTestDataSamples.openSampleFileStream("WithEmbeddedObjects.xls"); - try { - NPOIFSFileSystem fs = new NPOIFSFileSystem(is); - try { - // Start as NPOIFS - HSSFWorkbook wb = new HSSFWorkbook(fs.getRoot(), true); - assertEquals(3, wb.getNumberOfSheets()); - assertEquals("Root xls", wb.getSheetAt(0).getRow(0).getCell(0).getStringCellValue()); - - // Will switch to POIFS - HSSFWorkbook wbBack = HSSFTestDataSamples.writeOutAndReadBack(wb); - assertEquals(3, wbBack.getNumberOfSheets()); - assertEquals("Root xls", wbBack.getSheetAt(0).getRow(0).getCell(0).getStringCellValue()); - wbBack.close(); - - wb.close(); - } finally { - fs.close(); - } - } finally { - is.close(); - } - } - - @Test - public void cellStylesLimit() throws IOException { - Workbook wb = new HSSFWorkbook(); - int numBuiltInStyles = wb.getNumCellStyles(); - int MAX_STYLES = 4030; - int limit = MAX_STYLES - numBuiltInStyles; - for(int i=0; i < limit; i++){ - /* HSSFCellStyle style =*/ wb.createCellStyle(); - } - - assertEquals(MAX_STYLES, wb.getNumCellStyles()); - try { - /*HSSFCellStyle style =*/ wb.createCellStyle(); - fail("expected exception"); - } catch (IllegalStateException e){ - assertEquals("The maximum number of cell styles was exceeded. " + - "You can define up to 4000 styles in a .xls workbook", e.getMessage()); - } - assertEquals(MAX_STYLES, wb.getNumCellStyles()); - - wb.close(); - } - - @Test - public void setSheetOrderHSSF() throws IOException{ - Workbook wb = new HSSFWorkbook(); - Sheet s1 = wb.createSheet("first sheet"); - Sheet s2 = wb.createSheet("other sheet"); - - Name name1 = wb.createName(); - name1.setNameName("name1"); - name1.setRefersToFormula("'first sheet'!D1"); - - Name name2 = wb.createName(); - name2.setNameName("name2"); - name2.setRefersToFormula("'other sheet'!C1"); - - - Row s1r1 = s1.createRow(2); - Cell c1 = s1r1.createCell(3); - c1.setCellValue(30); - Cell c2 = s1r1.createCell(2); - c2.setCellFormula("SUM('other sheet'!C1,'first sheet'!C1)"); - - Row s2r1 = s2.createRow(0); - Cell c3 = s2r1.createCell(1); - c3.setCellFormula("'first sheet'!D3"); - Cell c4 = s2r1.createCell(2); - c4.setCellFormula("'other sheet'!D3"); - - // conditional formatting - SheetConditionalFormatting sheetCF = s1.getSheetConditionalFormatting(); - - ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule( - CFRuleRecord.ComparisonOperator.BETWEEN, "'first sheet'!D1", "'other sheet'!D1"); - - ConditionalFormattingRule [] cfRules = { rule1 }; - - CellRangeAddress[] regions = { - new CellRangeAddress(2, 4, 0, 0), // A3:A5 - }; - sheetCF.addConditionalFormatting(regions, cfRules); - - wb.setSheetOrder("other sheet", 0); - - // names - assertEquals("'first sheet'!D1", wb.getName("name1").getRefersToFormula()); - assertEquals("'other sheet'!C1", wb.getName("name2").getRefersToFormula()); - - // cells - assertEquals("SUM('other sheet'!C1,'first sheet'!C1)", c2.getCellFormula()); - assertEquals("'first sheet'!D3", c3.getCellFormula()); - assertEquals("'other sheet'!D3", c4.getCellFormula()); - - // conditional formatting - ConditionalFormatting cf = sheetCF.getConditionalFormattingAt(0); - assertEquals("'first sheet'!D1", cf.getRule(0).getFormula1()); - assertEquals("'other sheet'!D1", cf.getRule(0).getFormula2()); - - wb.close(); - } - - private boolean hasEntry(DirectoryNode dirNode, String entryName) { - try { - dirNode.getEntry(entryName); - return true; - } catch (FileNotFoundException e) { - return false; - } - } - - @Test - public void clonePictures() throws IOException { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("SimpleWithImages.xls"); - InternalWorkbook iwb = wb.getWorkbook(); - iwb.findDrawingGroup(); - - for(int pictureIndex=1; pictureIndex <= 4; pictureIndex++){ - EscherBSERecord bse = iwb.getBSERecord(pictureIndex); - assertEquals(1, bse.getRef()); - } - - wb.cloneSheet(0); - for(int pictureIndex=1; pictureIndex <= 4; pictureIndex++){ - EscherBSERecord bse = iwb.getBSERecord(pictureIndex); - assertEquals(2, bse.getRef()); - } - - wb.cloneSheet(0); - for(int pictureIndex=1; pictureIndex <= 4; pictureIndex++){ - EscherBSERecord bse = iwb.getBSERecord(pictureIndex); - assertEquals(3, bse.getRef()); - } - - wb.close(); - } - - @Test - public void changeSheetNameWithSharedFormulas() throws IOException { - changeSheetNameWithSharedFormulas("shared_formulas.xls"); - } - - // Should throw exception about invalid POIFSFileSystem - @Test(expected=IllegalArgumentException.class) - public void emptyDirectoryNode() throws IOException { - POIFSFileSystem fs = new POIFSFileSystem(); - try { - new HSSFWorkbook(fs).close(); - } finally { - fs.close(); - } - } - - @Test - public void selectedSheetShort() throws IOException { - HSSFWorkbook wb=new HSSFWorkbook(); - - HSSFSheet sheet1 = wb.createSheet("Sheet1"); - HSSFSheet sheet2 = wb.createSheet("Sheet2"); - HSSFSheet sheet3 = wb.createSheet("Sheet3"); - HSSFSheet sheet4 = wb.createSheet("Sheet4"); - - confirmActiveSelected(sheet1, true); - confirmActiveSelected(sheet2, false); - confirmActiveSelected(sheet3, false); - confirmActiveSelected(sheet4, false); - - wb.setSelectedTab((short)1); - - // Demonstrate bug 44525: - // Well... not quite, since isActive + isSelected were also added in the same bug fix - assertFalse("Identified bug 44523 a", sheet1.isSelected()); - wb.setActiveSheet(1); - assertFalse("Identified bug 44523 b", sheet1.isActive()); - - confirmActiveSelected(sheet1, false); - confirmActiveSelected(sheet2, true); - confirmActiveSelected(sheet3, false); - confirmActiveSelected(sheet4, false); - - assertEquals(0, wb.getFirstVisibleTab()); - wb.setFirstVisibleTab((short)2); - assertEquals(2, wb.getFirstVisibleTab()); - - wb.close(); - } - - @Test - public void names() throws IOException { - HSSFWorkbook wb=new HSSFWorkbook(); - - try { - wb.getNameAt(0); - fail("Fails without any defined names"); - } catch (IllegalStateException e) { - assertTrue(e.getMessage(), e.getMessage().contains("no defined names")); - } - - HSSFName name = wb.createName(); - assertNotNull(name); - - assertNull(wb.getName("somename")); - - name.setNameName("myname"); - assertNotNull(wb.getName("myname")); - - assertEquals(0, wb.getNameIndex(name)); - assertEquals(0, wb.getNameIndex("myname")); - - try { - wb.getNameAt(5); - fail("Fails without any defined names"); - } catch (IllegalArgumentException e) { - assertTrue(e.getMessage(), e.getMessage().contains("outside the allowable range")); - } - - try { - wb.getNameAt(-3); - fail("Fails without any defined names"); - } catch (IllegalArgumentException e) { - assertTrue(e.getMessage(), e.getMessage().contains("outside the allowable range")); - } - - wb.close(); - } - - @Test - public void testMethods() throws IOException { - HSSFWorkbook wb=new HSSFWorkbook(); - wb.insertChartRecord(); - //wb.dumpDrawingGroupRecords(true); - //wb.dumpDrawingGroupRecords(false); - - wb.close(); - } - - @Test - public void writeProtection() throws IOException { - HSSFWorkbook wb=new HSSFWorkbook(); - - assertFalse(wb.isWriteProtected()); - - wb.writeProtectWorkbook("mypassword", "myuser"); - assertTrue(wb.isWriteProtected()); - -// OutputStream os = new FileOutputStream("/tmp/protected.xls"); -// try { -// wb.write(os); -// } finally { -// os.close(); -// } - - wb.unwriteProtectWorkbook(); - assertFalse(wb.isWriteProtected()); - - wb.close(); - } - - @Test - public void bug50298() throws Exception { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("50298.xls"); - - assertSheetOrder(wb, "Invoice", "Invoice1", "Digest", "Deferred", "Received"); - - HSSFSheet sheet = wb.cloneSheet(0); - - assertSheetOrder(wb, "Invoice", "Invoice1", "Digest", "Deferred", "Received", "Invoice (2)"); - - wb.setSheetName(wb.getSheetIndex(sheet), "copy"); - - assertSheetOrder(wb, "Invoice", "Invoice1", "Digest", "Deferred", "Received", "copy"); - - wb.setSheetOrder("copy", 0); - - assertSheetOrder(wb, "copy", "Invoice", "Invoice1", "Digest", "Deferred", "Received"); - - wb.removeSheetAt(0); - - assertSheetOrder(wb, "Invoice", "Invoice1", "Digest", "Deferred", "Received"); - - // check that the overall workbook serializes with its correct size - int expected = wb.getWorkbook().getSize(); - int written = wb.getWorkbook().serialize(0, new byte[expected*2]); - - assertEquals("Did not have the expected size when writing the workbook: written: " + written + ", but expected: " + expected, - expected, written); - - HSSFWorkbook read = HSSFTestDataSamples.writeOutAndReadBack(wb); - assertSheetOrder(read, "Invoice", "Invoice1", "Digest", "Deferred", "Received"); - read.close(); - wb.close(); - } - - @Test - public void bug50298a() throws Exception { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("50298.xls"); - - assertSheetOrder(wb, "Invoice", "Invoice1", "Digest", "Deferred", "Received"); - - HSSFSheet sheet = wb.cloneSheet(0); - - assertSheetOrder(wb, "Invoice", "Invoice1", "Digest", "Deferred", "Received", "Invoice (2)"); - - wb.setSheetName(wb.getSheetIndex(sheet), "copy"); - - assertSheetOrder(wb, "Invoice", "Invoice1", "Digest", "Deferred", "Received", "copy"); - - wb.setSheetOrder("copy", 0); - - assertSheetOrder(wb, "copy", "Invoice", "Invoice1", "Digest", "Deferred", "Received"); - - wb.removeSheetAt(0); - - assertSheetOrder(wb, "Invoice", "Invoice1", "Digest", "Deferred", "Received"); - - wb.removeSheetAt(1); - - assertSheetOrder(wb, "Invoice", "Digest", "Deferred", "Received"); - - wb.setSheetOrder("Digest", 3); - - assertSheetOrder(wb, "Invoice", "Deferred", "Received", "Digest"); - - // check that the overall workbook serializes with its correct size - int expected = wb.getWorkbook().getSize(); - int written = wb.getWorkbook().serialize(0, new byte[expected*2]); - - assertEquals("Did not have the expected size when writing the workbook: written: " + written + ", but expected: " + expected, - expected, written); - - HSSFWorkbook read = HSSFTestDataSamples.writeOutAndReadBack(wb); - assertSheetOrder(read, "Invoice", "Deferred", "Received", "Digest"); - read.close(); - wb.close(); - } - - @Test - public void bug54500() throws Exception { - String nameName = "AName"; - String sheetName = "ASheet"; - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("54500.xls"); - - assertSheetOrder(wb, "Sheet1", "Sheet2", "Sheet3"); - - wb.createSheet(sheetName); - - assertSheetOrder(wb, "Sheet1", "Sheet2", "Sheet3", "ASheet"); - - Name n = wb.createName(); - n.setNameName(nameName); - n.setSheetIndex(3); - n.setRefersToFormula(sheetName + "!A1"); - - assertSheetOrder(wb, "Sheet1", "Sheet2", "Sheet3", "ASheet"); - final HSSFName name = wb.getName(nameName); - assertNotNull(name); - assertEquals("ASheet!A1", name.getRefersToFormula()); - - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - wb.write(stream); - - assertSheetOrder(wb, "Sheet1", "Sheet2", "Sheet3", "ASheet"); - assertEquals("ASheet!A1", name.getRefersToFormula()); - - wb.removeSheetAt(1); - - assertSheetOrder(wb, "Sheet1", "Sheet3", "ASheet"); - assertEquals("ASheet!A1", name.getRefersToFormula()); - - ByteArrayOutputStream stream2 = new ByteArrayOutputStream(); - wb.write(stream2); - - assertSheetOrder(wb, "Sheet1", "Sheet3", "ASheet"); - assertEquals("ASheet!A1", name.getRefersToFormula()); - - HSSFWorkbook wb2 = new HSSFWorkbook(new ByteArrayInputStream(stream.toByteArray())); - expectName(wb2, nameName, "ASheet!A1"); - HSSFWorkbook wb3 = new HSSFWorkbook(new ByteArrayInputStream(stream2.toByteArray())); - expectName(wb3, nameName, "ASheet!A1"); - wb3.close(); - wb2.close(); - wb.close(); - } - - private void expectName(HSSFWorkbook wb, String name, String expect) { - final HSSFName hssfName = wb.getName(name); - assertNotNull(hssfName); - assertEquals(expect, hssfName.getRefersToFormula()); - } - - @Test - public void test49423() throws Exception - { - HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook("49423.xls"); - - boolean found = false; - int numSheets = workbook.getNumberOfSheets(); - for (int i = 0; i < numSheets; i++) { - HSSFSheet sheet = workbook.getSheetAt(i); - List shapes = sheet.getDrawingPatriarch().getChildren(); - for(HSSFShape shape : shapes){ - HSSFAnchor anchor = shape.getAnchor(); - - if(anchor instanceof HSSFClientAnchor){ - // absolute coordinates - HSSFClientAnchor clientAnchor = (HSSFClientAnchor)anchor; - assertNotNull(clientAnchor); - //System.out.println(clientAnchor.getRow1() + "," + clientAnchor.getRow2()); - found = true; - } else if (anchor instanceof HSSFChildAnchor){ - // shape is grouped and the anchor is expressed in the coordinate system of the group - HSSFChildAnchor childAnchor = (HSSFChildAnchor)anchor; - assertNotNull(childAnchor); - //System.out.println(childAnchor.getDy1() + "," + childAnchor.getDy2()); - found = true; - } - } - } - - assertTrue("Should find some images via Client or Child anchors, but did not find any at all", found); - workbook.close(); - } - - @Test - public void testRewriteFileBug58480() throws IOException { - final File file = TempFile.createTempFile("TestHSSFWorkbook", ".xls"); - - try { - // create new workbook - { - final Workbook workbook = new HSSFWorkbook(); - final Sheet sheet = workbook.createSheet("foo"); - final Row row = sheet.createRow(1); - row.createCell(1).setCellValue("bar"); - - writeAndCloseWorkbook(workbook, file); - } - - // edit the workbook - { - NPOIFSFileSystem fs = new NPOIFSFileSystem(file, false); - try { - DirectoryNode root = fs.getRoot(); - final Workbook workbook = new HSSFWorkbook(root, true); - final Sheet sheet = workbook.getSheet("foo"); - sheet.getRow(1).createCell(2).setCellValue("baz"); - - writeAndCloseWorkbook(workbook, file); - } finally { - fs.close(); - } - } - } finally { - assertTrue(file.exists()); - assertTrue(file.delete()); - } - } - - private void writeAndCloseWorkbook(Workbook workbook, File file) - throws IOException { - final ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); - workbook.write(bytesOut); - workbook.close(); - - final byte[] byteArray = bytesOut.toByteArray(); - bytesOut.close(); - - final FileOutputStream fileOut = new FileOutputStream(file); - fileOut.write(byteArray); - fileOut.close(); - - } - - @Test - public void closeDoesNotModifyWorkbook() throws IOException { - final String filename = "SampleSS.xls"; - final File file = POIDataSamples.getSpreadSheetInstance().getFile(filename); - Workbook wb; - - // File via POIFileStream (java.io) - wb = new HSSFWorkbook(new POIFSFileSystem(file)); - assertCloseDoesNotModifyFile(filename, wb); - - // File via NPOIFileStream (java.nio) - wb = new HSSFWorkbook(new NPOIFSFileSystem(file)); - assertCloseDoesNotModifyFile(filename, wb); - - // InputStream - wb = new HSSFWorkbook(new FileInputStream(file)); - assertCloseDoesNotModifyFile(filename, wb); - } - - @Test - public void setSheetOrderToEnd() throws Exception { - final HSSFWorkbook workbook = new HSSFWorkbook(); - workbook.createSheet("A"); - try { - for (int i = 0; i < 2 * workbook.getInternalWorkbook().getRecords().size(); i++) { - workbook.setSheetOrder("A", 0); - } - } catch (Exception e) { - throw new Exception("Moving a sheet to the end should not throw an exception, but threw ", e); - } - } - - @Test - public void invalidInPlaceWrite() throws Exception { - HSSFWorkbook wb; - - // Can't work for new files - wb = new HSSFWorkbook(); - try { - wb.write(); - fail("Shouldn't work for new files"); - } catch (IllegalStateException e) { - // expected here - } - wb.close(); - - // Can't work for InputStream opened files - wb = new HSSFWorkbook( - POIDataSamples.getSpreadSheetInstance().openResourceAsStream("SampleSS.xls")); - try { - wb.write(); - fail("Shouldn't work for InputStream"); - } catch (IllegalStateException e) { - // expected here - } - wb.close(); - - // Can't work for OPOIFS - OPOIFSFileSystem ofs = new OPOIFSFileSystem( - POIDataSamples.getSpreadSheetInstance().openResourceAsStream("SampleSS.xls")); - wb = new HSSFWorkbook(ofs.getRoot(), true); - try { - wb.write(); - fail("Shouldn't work for OPOIFSFileSystem"); - } catch (IllegalStateException e) { - // expected here - } - wb.close(); - - // Can't work for Read-Only files - NPOIFSFileSystem fs = new NPOIFSFileSystem( - POIDataSamples.getSpreadSheetInstance().getFile("SampleSS.xls"), true); - wb = new HSSFWorkbook(fs); - try { - wb.write(); - fail("Shouldn't work for Read Only"); - } catch (IllegalStateException e) { - // expected here - } - wb.close(); - } - - @Test - public void inPlaceWrite() throws Exception { - // Setup as a copy of a known-good file - final File file = TempFile.createTempFile("TestHSSFWorkbook", ".xls"); - InputStream inputStream = POIDataSamples.getSpreadSheetInstance().openResourceAsStream("SampleSS.xls"); - try { - FileOutputStream outputStream = new FileOutputStream(file); - try { - IOUtils.copy(inputStream, outputStream); - } finally { - outputStream.close(); - } - } finally { - inputStream.close(); - } - - // Open from the temp file in read-write mode - HSSFWorkbook wb = new HSSFWorkbook(new NPOIFSFileSystem(file, false)); - assertEquals(3, wb.getNumberOfSheets()); - - // Change - wb.removeSheetAt(2); - wb.removeSheetAt(1); - wb.getSheetAt(0).getRow(0).getCell(0).setCellValue("Changed!"); - - // Save in-place, close, re-open and check - wb.write(); - wb.close(); - - wb = new HSSFWorkbook(new NPOIFSFileSystem(file)); - assertEquals(1, wb.getNumberOfSheets()); - assertEquals("Changed!", wb.getSheetAt(0).getRow(0).getCell(0).toString()); - - wb.close(); - } - - @Test - public void testWriteToNewFile() throws Exception { - // Open from a Stream - HSSFWorkbook wb = new HSSFWorkbook( - POIDataSamples.getSpreadSheetInstance().openResourceAsStream("SampleSS.xls")); - - // Save to a new temp file - final File file = TempFile.createTempFile("TestHSSFWorkbook", ".xls"); - wb.write(file); - wb.close(); - - // Read and check - wb = new HSSFWorkbook(new NPOIFSFileSystem(file)); - assertEquals(3, wb.getNumberOfSheets()); - wb.close(); - } - - @Ignore - @Test - @Override - public void createDrawing() throws Exception { - super.createDrawing(); - // the dimensions for this image are different than for XSSF and SXSSF - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestNonStandardWorkbookStreamNames.java b/src/testcases/org/apache/poi/hssf/usermodel/TestNonStandardWorkbookStreamNames.java deleted file mode 100644 index 1a695407b..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestNonStandardWorkbookStreamNames.java +++ /dev/null @@ -1,154 +0,0 @@ -/* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -package org.apache.poi.hssf.usermodel; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.FileNotFoundException; -import java.io.InputStream; - -import junit.framework.TestCase; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; - -/** - * Tests for how HSSFWorkbook behaves with XLS files - * with a WORKBOOK or BOOK directory entry (instead of - * the more usual, Workbook) - */ -public final class TestNonStandardWorkbookStreamNames extends TestCase { - private final String xlsA = "WORKBOOK_in_capitals.xls"; - private final String xlsB = "BOOK_in_capitals.xls"; - - /** - * Test that we can open a file with WORKBOOK - */ - public void testOpenWORKBOOK() throws Exception { - InputStream is = HSSFTestDataSamples.openSampleFileStream(xlsA); - - POIFSFileSystem fs = new POIFSFileSystem(is); - - // Ensure that we have a WORKBOOK entry - fs.getRoot().getEntry("WORKBOOK"); - // And a summary - fs.getRoot().getEntry("\005SummaryInformation"); - assertTrue(true); - - // But not a Workbook one - try { - fs.getRoot().getEntry("Workbook"); - fail(); - } catch(FileNotFoundException e) {} - - // Try to open the workbook - HSSFWorkbook wb = new HSSFWorkbook(fs); - } - - /** - * Test that we can open a file with BOOK - */ - public void testOpenBOOK() throws Exception { - InputStream is = HSSFTestDataSamples.openSampleFileStream(xlsB); - - POIFSFileSystem fs = new POIFSFileSystem(is); - - // Ensure that we have a BOOK entry - fs.getRoot().getEntry("BOOK"); - assertTrue(true); - - // But not a Workbook one - try { - fs.getRoot().getEntry("Workbook"); - fail(); - } catch(FileNotFoundException e) {} - // And not a Summary one - try { - fs.getRoot().getEntry("\005SummaryInformation"); - fail(); - } catch(FileNotFoundException e) {} - - // Try to open the workbook - HSSFWorkbook wb = new HSSFWorkbook(fs); - } - - /** - * Test that when we write out, we go back to the correct case - */ - public void testWrite() throws Exception { - for (String file : new String[] {xlsA, xlsB}) { - InputStream is = HSSFTestDataSamples.openSampleFileStream(file); - POIFSFileSystem fs = new POIFSFileSystem(is); - - // Open the workbook, not preserving nodes - HSSFWorkbook wb = new HSSFWorkbook(fs); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - wb.write(out); - - // Check now - ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); - POIFSFileSystem fs2 = new POIFSFileSystem(in); - - // Check that we have the new entries - fs2.getRoot().getEntry("Workbook"); - try { - fs2.getRoot().getEntry("BOOK"); - fail(); - } catch(FileNotFoundException e) {} - try { - fs2.getRoot().getEntry("WORKBOOK"); - fail(); - } catch(FileNotFoundException e) {} - - // And it can be opened - HSSFWorkbook wb2 = new HSSFWorkbook(fs2); - } - } - - /** - * Test that when we write out preserving nodes, we go back to the - * correct case - */ - public void testWritePreserve() throws Exception { - InputStream is = HSSFTestDataSamples.openSampleFileStream(xlsA); - POIFSFileSystem fs = new POIFSFileSystem(is); - - // Open the workbook, not preserving nodes - HSSFWorkbook wb = new HSSFWorkbook(fs,true); - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - wb.write(out); - - // Check now - ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); - POIFSFileSystem fs2 = new POIFSFileSystem(in); - - // Check that we have the new entries - fs2.getRoot().getEntry("Workbook"); - try { - fs2.getRoot().getEntry("WORKBOOK"); - fail(); - } catch(FileNotFoundException e) {} - - // As we preserved, should also have a few other streams - fs2.getRoot().getEntry("\005SummaryInformation"); - - // And it can be opened - HSSFWorkbook wb2 = new HSSFWorkbook(fs2); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestOLE2Embeding.java b/src/testcases/org/apache/poi/hssf/usermodel/TestOLE2Embeding.java deleted file mode 100644 index fea681e74..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestOLE2Embeding.java +++ /dev/null @@ -1,171 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.List; - -import org.apache.poi.POIDataSamples; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.poifs.filesystem.DirectoryNode; -import org.apache.poi.poifs.filesystem.Ole10Native; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.ss.usermodel.ClientAnchor.AnchorType; -import org.apache.poi.ss.usermodel.CreationHelper; -import org.apache.poi.util.LocaleUtil; -import org.junit.Test; - -/** - * - */ -public final class TestOLE2Embeding { - - @Test - public void testEmbeding() throws Exception { - // This used to break, until bug #43116 was fixed - HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook("ole2-embedding.xls"); - - // Check we can get at the Escher layer still - workbook.getAllPictures(); - - workbook.close(); - } - - @Test - public void testEmbeddedObjects() throws Exception { - HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook("ole2-embedding.xls"); - - List objects = workbook.getAllEmbeddedObjects(); - assertEquals("Wrong number of objects", 2, objects.size()); - assertEquals("Wrong name for first object", "MBD06CAB431", - objects.get(0).getDirectory().getName()); - assertEquals("Wrong name for second object", "MBD06CAC85A", - objects.get(1).getDirectory().getName()); - - workbook.close(); - } - - @Test - public void testReallyEmbedSomething() throws Exception { - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet sheet = wb1.createSheet(); - HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); - - byte[] pictureData = HSSFTestDataSamples.getTestDataFileContent("logoKarmokar4.png"); - byte[] picturePPT = POIDataSamples.getSlideShowInstance().readFile("clock.jpg"); - int imgIdx = wb1.addPicture(pictureData, HSSFWorkbook.PICTURE_TYPE_PNG); - POIFSFileSystem pptPoifs = getSamplePPT(); - int pptIdx = wb1.addOlePackage(pptPoifs, "Sample-PPT", "sample.ppt", "sample.ppt"); - POIFSFileSystem xlsPoifs = getSampleXLS(); - int imgPPT = wb1.addPicture(picturePPT, HSSFWorkbook.PICTURE_TYPE_JPEG); - int xlsIdx = wb1.addOlePackage(xlsPoifs, "Sample-XLS", "sample.xls", "sample.xls"); - int txtIdx = wb1.addOlePackage(getSampleTXT(), "Sample-TXT", "sample.txt", "sample.txt"); - - int rowoffset = 5; - int coloffset = 5; - - CreationHelper ch = wb1.getCreationHelper(); - HSSFClientAnchor anchor = (HSSFClientAnchor)ch.createClientAnchor(); - anchor.setAnchor((short)(2+coloffset), 1+rowoffset, 0, 0, (short)(3+coloffset), 5+rowoffset, 0, 0); - anchor.setAnchorType(AnchorType.DONT_MOVE_AND_RESIZE); - - patriarch.createObjectData(anchor, pptIdx, imgPPT); - - anchor = (HSSFClientAnchor)ch.createClientAnchor(); - anchor.setAnchor((short)(5+coloffset), 1+rowoffset, 0, 0, (short)(6+coloffset), 5+rowoffset, 0, 0); - anchor.setAnchorType(AnchorType.DONT_MOVE_AND_RESIZE); - - patriarch.createObjectData(anchor, xlsIdx, imgIdx); - - anchor = (HSSFClientAnchor)ch.createClientAnchor(); - anchor.setAnchor((short)(3+coloffset), 10+rowoffset, 0, 0, (short)(5+coloffset), 11+rowoffset, 0, 0); - anchor.setAnchorType(AnchorType.DONT_MOVE_AND_RESIZE); - - patriarch.createObjectData(anchor, txtIdx, imgIdx); - - anchor = (HSSFClientAnchor)ch.createClientAnchor(); - anchor.setAnchor((short)(1+coloffset), -2+rowoffset, 0, 0, (short)(7+coloffset), 14+rowoffset, 0, 0); - anchor.setAnchorType(AnchorType.DONT_MOVE_AND_RESIZE); - - HSSFSimpleShape circle = patriarch.createSimpleShape(anchor); - circle.setShapeType(HSSFSimpleShape.OBJECT_TYPE_OVAL); - circle.setNoFill(true); - -// if (false) { -// FileOutputStream fos = new FileOutputStream("embed.xls"); -// wb.write(fos); -// fos.close(); -// } - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - HSSFObjectData od = wb2.getAllEmbeddedObjects().get(0); - Ole10Native ole10 = Ole10Native.createFromEmbeddedOleObject((DirectoryNode)od.getDirectory()); - bos.reset(); - pptPoifs.writeFilesystem(bos); - assertArrayEquals(ole10.getDataBuffer(), bos.toByteArray()); - - od = wb2.getAllEmbeddedObjects().get(1); - ole10 = Ole10Native.createFromEmbeddedOleObject((DirectoryNode)od.getDirectory()); - bos.reset(); - xlsPoifs.writeFilesystem(bos); - assertArrayEquals(ole10.getDataBuffer(), bos.toByteArray()); - - od = wb2.getAllEmbeddedObjects().get(2); - ole10 = Ole10Native.createFromEmbeddedOleObject((DirectoryNode)od.getDirectory()); - assertArrayEquals(ole10.getDataBuffer(), getSampleTXT()); - - xlsPoifs.close(); - pptPoifs.close(); - wb2.close(); - } - - static POIFSFileSystem getSamplePPT() throws IOException { - // scratchpad classes are not available, so we use something pre-cooked - InputStream is = POIDataSamples.getSlideShowInstance().openResourceAsStream("with_textbox.ppt"); - POIFSFileSystem poifs = new POIFSFileSystem(is); - is.close(); - - return poifs; - } - - static POIFSFileSystem getSampleXLS() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sheet = wb.createSheet(); - sheet.createRow(5).createCell(2).setCellValue("yo dawg i herd you like embeddet objekts, so we put a ole in your ole so you can save a file while you save a file"); - - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - wb.write(bos); - wb.close(); - POIFSFileSystem poifs = new POIFSFileSystem(new ByteArrayInputStream(bos.toByteArray())); - - return poifs; - } - - static byte[] getSampleTXT() { - return "All your base are belong to us".getBytes(LocaleUtil.CHARSET_1252); - } -} \ No newline at end of file diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestPOIFSProperties.java b/src/testcases/org/apache/poi/hssf/usermodel/TestPOIFSProperties.java deleted file mode 100644 index 13ee6dd16..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestPOIFSProperties.java +++ /dev/null @@ -1,95 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.Assert.assertEquals; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.InputStream; - -import org.apache.poi.hpsf.PropertySetFactory; -import org.apache.poi.hpsf.SummaryInformation; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.junit.Test; - -/** - * Old-style setting of POIFS properties doesn't work with POI 3.0.2 - */ -public class TestPOIFSProperties { - - private static final String title = "Testing POIFS properties"; - - @Test - public void testFail() throws Exception { - InputStream is = HSSFTestDataSamples.openSampleFileStream("Simple.xls"); - POIFSFileSystem fs = new POIFSFileSystem(is); - is.close(); - - HSSFWorkbook wb = new HSSFWorkbook(fs); - - //set POIFS properties after constructing HSSFWorkbook - //(a piece of code that used to work up to POI 3.0.2) - SummaryInformation summary1 = (SummaryInformation)PropertySetFactory.create(fs.createDocumentInputStream(SummaryInformation.DEFAULT_STREAM_NAME)); - summary1.setTitle(title); - //write the modified property back to POIFS - fs.getRoot().getEntry(SummaryInformation.DEFAULT_STREAM_NAME).delete(); - fs.createDocument(summary1.toInputStream(), SummaryInformation.DEFAULT_STREAM_NAME); - - //save the workbook and read the property - ByteArrayOutputStream out = new ByteArrayOutputStream(); - wb.write(out); - out.close(); - wb.close(); - - POIFSFileSystem fs2 = new POIFSFileSystem(new ByteArrayInputStream(out.toByteArray())); - SummaryInformation summary2 = (SummaryInformation)PropertySetFactory.create(fs2.createDocumentInputStream(SummaryInformation.DEFAULT_STREAM_NAME)); - - //failing assertion - assertEquals(title, summary2.getTitle()); - fs2.close(); - } - - @Test - public void testOK() throws Exception { - InputStream is = HSSFTestDataSamples.openSampleFileStream("Simple.xls"); - POIFSFileSystem fs = new POIFSFileSystem(is); - is.close(); - - //set POIFS properties before constructing HSSFWorkbook - SummaryInformation summary1 = (SummaryInformation)PropertySetFactory.create(fs.createDocumentInputStream(SummaryInformation.DEFAULT_STREAM_NAME)); - summary1.setTitle(title); - - fs.getRoot().getEntry(SummaryInformation.DEFAULT_STREAM_NAME).delete(); - fs.createDocument(summary1.toInputStream(), SummaryInformation.DEFAULT_STREAM_NAME); - - HSSFWorkbook wb = new HSSFWorkbook(fs); - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - wb.write(out); - out.close(); - wb.close(); - - //read the property - POIFSFileSystem fs2 = new POIFSFileSystem(new ByteArrayInputStream(out.toByteArray())); - SummaryInformation summary2 = (SummaryInformation)PropertySetFactory.create(fs2.createDocumentInputStream(SummaryInformation.DEFAULT_STREAM_NAME)); - assertEquals(title, summary2.getTitle()); - fs2.close(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestPatriarch.java b/src/testcases/org/apache/poi/hssf/usermodel/TestPatriarch.java deleted file mode 100644 index d7ce83306..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestPatriarch.java +++ /dev/null @@ -1,57 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import junit.framework.TestCase; -import org.apache.poi.ddf.EscherDgRecord; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.record.EscherAggregate; - -/** - * @author Evgeniy Berlog - * @date 01.08.12 - */ -public class TestPatriarch extends TestCase { - - public void testGetPatriarch(){ - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sh = wb.createSheet(); - assertNull(sh.getDrawingPatriarch()); - - HSSFPatriarch patriarch = sh.createDrawingPatriarch(); - assertNotNull(patriarch); - patriarch.createSimpleShape(new HSSFClientAnchor()); - patriarch.createSimpleShape(new HSSFClientAnchor()); - - assertSame(patriarch, sh.getDrawingPatriarch()); - - EscherAggregate agg = patriarch.getBoundAggregate(); - - EscherDgRecord dg = agg.getEscherContainer().getChildById(EscherDgRecord.RECORD_ID); - int lastId = dg.getLastMSOSPID(); - - assertSame(patriarch, sh.createDrawingPatriarch()); - - wb = HSSFTestDataSamples.writeOutAndReadBack(wb); - sh = wb.getSheetAt(0); - patriarch = sh.createDrawingPatriarch(); - dg = patriarch.getBoundAggregate().getEscherContainer().getChildById(EscherDgRecord.RECORD_ID); - - assertEquals(lastId, dg.getLastMSOSPID()); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestPolygon.java b/src/testcases/org/apache/poi/hssf/usermodel/TestPolygon.java deleted file mode 100644 index 1e250bdfd..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestPolygon.java +++ /dev/null @@ -1,276 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.apache.poi.poifs.storage.RawDataUtil.decompress; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; - -import org.apache.poi.ddf.EscherArrayProperty; -import org.apache.poi.ddf.EscherProperties; -import org.apache.poi.ddf.EscherSpRecord; -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.record.ObjRecord; -import org.junit.Test; - -public class TestPolygon { - @Test - public void testResultEqualsToAbstractShape() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sh = wb.createSheet(); - HSSFPatriarch patriarch = sh.createDrawingPatriarch(); - - HSSFPolygon polygon = patriarch.createPolygon(new HSSFClientAnchor()); - polygon.setPolygonDrawArea( 100, 100 ); - polygon.setPoints( new int[]{0, 90, 50}, new int[]{5, 5, 44} ); - polygon.setShapeId(1024); - - assertEquals(polygon.getEscherContainer().getChildRecords().size(), 4); - - //sp record - byte[] expected = decompress("H4sIAAAAAAAAAGNi4PrAwQAELEDMxcAAAAU6ZlwQAAAA"); - byte[] actual = polygon.getEscherContainer().getChild(0).serialize(); - - assertEquals(expected.length, actual.length); - assertArrayEquals(expected, actual); - - expected = decompress("H4sIAAAAAAAAAGNgEPggxIANAABK4+laGgAAAA=="); - actual = polygon.getEscherContainer().getChild(2).serialize(); - - assertEquals(expected.length, actual.length); - assertArrayEquals(expected, actual); - - expected = decompress("H4sIAAAAAAAAAGNgEPzAAAQACl6c5QgAAAA="); - actual = polygon.getEscherContainer().getChild(3).serialize(); - - assertEquals(expected.length, actual.length); - assertArrayEquals(expected, actual); - - ObjRecord obj = polygon.getObjRecord(); - - expected = decompress("H4sIAAAAAAAAAItlkGIQZRBikGNgYBBMYEADAOAV/ZkeAAAA"); - actual = obj.serialize(); - - assertEquals(expected.length, actual.length); - assertArrayEquals(expected, actual); - - wb.close(); - } - - @Test - public void testPolygonPoints() throws IOException { - HSSFWorkbook wb = new HSSFWorkbook(); - HSSFSheet sh = wb.createSheet(); - HSSFPatriarch patriarch = sh.createDrawingPatriarch(); - - HSSFPolygon polygon = patriarch.createPolygon(new HSSFClientAnchor()); - polygon.setPolygonDrawArea( 100, 100 ); - polygon.setPoints( new int[]{0, 90, 50, 90}, new int[]{5, 5, 44, 88} ); - - EscherArrayProperty verticesProp1 = polygon.getOptRecord().lookup(EscherProperties.GEOMETRY__VERTICES); - - String expected = - ""+ - "[00, 00, 05, 00]"+ - "[5A, 00, 05, 00]"+ - "[32, 00, 2C, 00]"+ - "[5A, 00, 58, 00]"+ - "[00, 00, 05, 00]"+ - ""; - String actual = verticesProp1.toXml("").replaceAll("[\r\n\t]",""); - - assertEquals(verticesProp1.getNumberOfElementsInArray(), 5); - assertEquals(expected, actual); - - polygon.setPoints(new int[]{1,2,3}, new int[] {4,5,6}); - assertArrayEquals(polygon.getXPoints(), new int[]{1, 2, 3}); - assertArrayEquals(polygon.getYPoints(), new int[]{4, 5, 6}); - - verticesProp1 = polygon.getOptRecord().lookup(EscherProperties.GEOMETRY__VERTICES); - - expected = - "" + - "[01, 00, 04, 00]" + - "[02, 00, 05, 00]" + - "[03, 00, 06, 00]" + - "[01, 00, 04, 00]" + - ""; - actual = verticesProp1.toXml("").replaceAll("[\r\n\t]",""); - - assertEquals(verticesProp1.getNumberOfElementsInArray(), 4); - assertEquals(expected, actual); - - wb.close(); - } - - @Test - public void testSetGetProperties() throws IOException { - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet sh = wb1.createSheet(); - HSSFPatriarch patriarch = sh.createDrawingPatriarch(); - - HSSFPolygon polygon = patriarch.createPolygon(new HSSFClientAnchor()); - polygon.setPolygonDrawArea( 102, 101 ); - polygon.setPoints( new int[]{1,2,3}, new int[]{4,5,6} ); - - assertArrayEquals(polygon.getXPoints(), new int[]{1,2,3}); - assertArrayEquals(polygon.getYPoints(), new int[]{4, 5, 6}); - assertEquals(polygon.getDrawAreaHeight(), 101); - assertEquals(polygon.getDrawAreaWidth(), 102); - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sh = wb2.getSheetAt(0); - patriarch = sh.getDrawingPatriarch(); - - polygon = (HSSFPolygon) patriarch.getChildren().get(0); - assertArrayEquals(polygon.getXPoints(), new int[]{1, 2, 3}); - assertArrayEquals(polygon.getYPoints(), new int[]{4, 5, 6}); - assertEquals(polygon.getDrawAreaHeight(), 101); - assertEquals(polygon.getDrawAreaWidth(), 102); - - polygon.setPolygonDrawArea( 1021, 1011 ); - polygon.setPoints( new int[]{11,21,31}, new int[]{41,51,61} ); - - assertArrayEquals(polygon.getXPoints(), new int[]{11, 21, 31}); - assertArrayEquals(polygon.getYPoints(), new int[]{41, 51, 61}); - assertEquals(polygon.getDrawAreaHeight(), 1011); - assertEquals(polygon.getDrawAreaWidth(), 1021); - - HSSFWorkbook wb3 = HSSFTestDataSamples.writeOutAndReadBack(wb2); - wb2.close(); - sh = wb3.getSheetAt(0); - patriarch = sh.getDrawingPatriarch(); - - polygon = (HSSFPolygon) patriarch.getChildren().get(0); - - assertArrayEquals(polygon.getXPoints(), new int[]{11, 21, 31}); - assertArrayEquals(polygon.getYPoints(), new int[]{41, 51, 61}); - assertEquals(polygon.getDrawAreaHeight(), 1011); - assertEquals(polygon.getDrawAreaWidth(), 1021); - - wb3.close(); - } - - @Test - public void testAddToExistingFile() throws IOException { - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet sh = wb1.createSheet(); - HSSFPatriarch patriarch = sh.createDrawingPatriarch(); - - HSSFPolygon polygon = patriarch.createPolygon(new HSSFClientAnchor()); - polygon.setPolygonDrawArea( 102, 101 ); - polygon.setPoints( new int[]{1,2,3}, new int[]{4,5,6} ); - - HSSFPolygon polygon1 = patriarch.createPolygon(new HSSFClientAnchor()); - polygon1.setPolygonDrawArea( 103, 104 ); - polygon1.setPoints( new int[]{11,12,13}, new int[]{14,15,16} ); - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sh = wb2.getSheetAt(0); - patriarch = sh.getDrawingPatriarch(); - - assertEquals(patriarch.getChildren().size(), 2); - - HSSFPolygon polygon2 = patriarch.createPolygon(new HSSFClientAnchor()); - polygon2.setPolygonDrawArea( 203, 204 ); - polygon2.setPoints( new int[]{21,22,23}, new int[]{24,25,26} ); - - HSSFWorkbook wb3 = HSSFTestDataSamples.writeOutAndReadBack(wb2); - wb2.close(); - sh = wb3.getSheetAt(0); - patriarch = sh.getDrawingPatriarch(); - - assertEquals(patriarch.getChildren().size(), 3); - - polygon = (HSSFPolygon) patriarch.getChildren().get(0); - polygon1 = (HSSFPolygon) patriarch.getChildren().get(1); - polygon2 = (HSSFPolygon) patriarch.getChildren().get(2); - - assertArrayEquals(polygon.getXPoints(), new int[]{1, 2, 3}); - assertArrayEquals(polygon.getYPoints(), new int[]{4,5,6}); - assertEquals(polygon.getDrawAreaHeight(), 101); - assertEquals(polygon.getDrawAreaWidth(), 102); - - assertArrayEquals(polygon1.getXPoints(), new int[]{11,12,13}); - assertArrayEquals(polygon1.getYPoints(), new int[]{14,15,16}); - assertEquals(polygon1.getDrawAreaHeight(), 104); - assertEquals(polygon1.getDrawAreaWidth(), 103); - - assertArrayEquals(polygon2.getXPoints(), new int[]{21,22,23}); - assertArrayEquals(polygon2.getYPoints(), new int[]{24,25,26}); - assertEquals(polygon2.getDrawAreaHeight(), 204); - assertEquals(polygon2.getDrawAreaWidth(), 203); - - wb3.close(); - } - - @Test - public void testExistingFile() throws IOException { - HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("drawings.xls"); - HSSFSheet sheet = wb.getSheet("polygon"); - HSSFPatriarch drawing = sheet.getDrawingPatriarch(); - assertEquals(1, drawing.getChildren().size()); - - HSSFPolygon polygon = (HSSFPolygon) drawing.getChildren().get(0); - assertEquals(polygon.getDrawAreaHeight(), 2466975); - assertEquals(polygon.getDrawAreaWidth(), 3686175); - assertArrayEquals(polygon.getXPoints(), new int[]{0, 0, 31479, 16159, 19676, 20502}); - assertArrayEquals(polygon.getYPoints(), new int[]{0, 0, 36, 56, 34, 18}); - - wb.close(); - } - - @Test - public void testPolygonType() throws IOException { - HSSFWorkbook wb1 = new HSSFWorkbook(); - HSSFSheet sh = wb1.createSheet(); - HSSFPatriarch patriarch = sh.createDrawingPatriarch(); - - HSSFPolygon polygon = patriarch.createPolygon(new HSSFClientAnchor()); - polygon.setPolygonDrawArea( 102, 101 ); - polygon.setPoints( new int[]{1,2,3}, new int[]{4,5,6} ); - - HSSFWorkbook wb2 = HSSFTestDataSamples.writeOutAndReadBack(wb1); - wb1.close(); - sh = wb2.getSheetAt(0); - patriarch = sh.getDrawingPatriarch(); - - HSSFPolygon polygon1 = patriarch.createPolygon(new HSSFClientAnchor()); - polygon1.setPolygonDrawArea( 102, 101 ); - polygon1.setPoints( new int[]{1,2,3}, new int[]{4,5,6} ); - - EscherSpRecord spRecord = polygon1.getEscherContainer().getChildById(EscherSpRecord.RECORD_ID); - - spRecord.setShapeType((short)77/**RANDOM**/); - - HSSFWorkbook wb3 = HSSFTestDataSamples.writeOutAndReadBack(wb2); - wb2.close(); - sh = wb3.getSheetAt(0); - patriarch = sh.getDrawingPatriarch(); - - assertEquals(patriarch.getChildren().size(), 2); - assertTrue(patriarch.getChildren().get(0) instanceof HSSFPolygon); - assertTrue(patriarch.getChildren().get(1) instanceof HSSFPolygon); - wb3.close(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestReadWriteChart.java b/src/testcases/org/apache/poi/hssf/usermodel/TestReadWriteChart.java deleted file mode 100644 index 57be4a6d6..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestReadWriteChart.java +++ /dev/null @@ -1,66 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.util.Calendar; -import java.util.Date; -import java.util.List; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.hssf.model.InternalSheet; -import org.apache.poi.hssf.record.BOFRecord; -import org.apache.poi.hssf.record.EOFRecord; -import org.apache.poi.hssf.record.RecordBase; -import org.apache.poi.util.LocaleUtil; -import org.junit.Test; - -/** - * @author Glen Stampoultzis (glens at apache.org) - */ -public final class TestReadWriteChart { - - /** - * In the presence of a chart we need to make sure BOF/EOF records still exist. - */ - @Test - public void testBOFandEOFRecords() throws Exception { - HSSFWorkbook workbook = HSSFTestDataSamples.openSampleWorkbook("SimpleChart.xls"); - HSSFSheet sheet = workbook.getSheetAt(0); - HSSFRow firstRow = sheet.getRow(0); - HSSFCell firstCell = firstRow.getCell(0); - - //System.out.println("first assertion for date"); - Calendar calExp = LocaleUtil.getLocaleCalendar(2000, 0, 1, 10, 51, 2); - Date dateAct = HSSFDateUtil.getJavaDate(firstCell.getNumericCellValue(), false); - assertEquals(calExp.getTime(), dateAct); - HSSFRow row = sheet.createRow(15); - HSSFCell cell = row.createCell(1); - - cell.setCellValue(22); - InternalSheet newSheet = workbook.getSheetAt(0).getSheet(); - List records = newSheet.getRecords(); - - assertTrue(records.get(0) instanceof BOFRecord); - assertTrue(records.get(records.size() - 1) instanceof EOFRecord); - - workbook.close(); - } -} diff --git a/src/testcases/org/apache/poi/hssf/usermodel/TestRowStyle.java b/src/testcases/org/apache/poi/hssf/usermodel/TestRowStyle.java deleted file mode 100644 index 35519d36c..000000000 --- a/src/testcases/org/apache/poi/hssf/usermodel/TestRowStyle.java +++ /dev/null @@ -1,171 +0,0 @@ -/* ==================================================================== - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -==================================================================== */ - -package org.apache.poi.hssf.usermodel; - -import junit.framework.TestCase; - -import org.apache.poi.hssf.HSSFTestDataSamples; -import org.apache.poi.ss.usermodel.BorderStyle; - -/** - * Class to test row styling functionality - * - * @author Amol S. Deshmukh < amolweb at ya hoo dot com > - */ -public final class TestRowStyle extends TestCase { - - /** - * TEST NAME: Test Write Sheet Font

  • " - + formatLongAsHex(ec.getRawDoubleBits()) - + "" + Double.toString(ec.getDoubleValue()) - + "" + ec.getExcelRendering() + "
    - - - - - - - - -
    NameSizeOffsetDescriptionDefault Value
    - - -

    - - - - - - - - - - - - - - - diff --git a/src/types/styles/hdftype_test.xsl b/src/types/styles/hdftype_test.xsl deleted file mode 100644 index d95c81bb3..000000000 --- a/src/types/styles/hdftype_test.xsl +++ /dev/null @@ -1,96 +0,0 @@ - - - - - - - -package ; - - -import junit.framework.TestCase; - -/** - * Tests the serialization and deserialization of the Type - * class works correctly. Test data taken directly from a real - * Excel file. - * - - */ -public class TestType - extends TestCase -{ - byte[] data = new byte[] { - // PASTE DATA HERE - }; - - public TestType(String name) - { - super(name); - } - - public void testLoad() - throws Exception - { - - Type type = new Type((short), (short)data.length, data); - assertEquals( XXX, type.get()); - - - - assertEquals( XXX, type.getSize() ); - - type.validateSid((short)); - } - - public void testStore() - { - Type type = new Type(); - type.set( XXXX ); - - - - byte [] typeBytes = type.serialize(); - assertEquals(typeBytes.length - 4, data.length); - for (int i = 0; i < data.length; i++) - assertEquals("At offset " + i, data[i], typeBytes[i+4]); - } -} - - - - * @author - - - - assertEquals( XXX, type.is() ); - - - - - type.set( XXX ); - - - - diff --git a/test-data/ddf/47143.dat b/test-data/ddf/47143.dat deleted file mode 100644 index 0745ce1b9..000000000 Binary files a/test-data/ddf/47143.dat and /dev/null differ diff --git a/test-data/ddf/Container.dat b/test-data/ddf/Container.dat deleted file mode 100644 index c1b544777..000000000 Binary files a/test-data/ddf/Container.dat and /dev/null differ diff --git a/test-data/diagram/44501.vsd b/test-data/diagram/44501.vsd deleted file mode 100644 index 51de23a32..000000000 Binary files a/test-data/diagram/44501.vsd and /dev/null differ diff --git a/test-data/diagram/44501a.vsd b/test-data/diagram/44501a.vsd deleted file mode 100644 index 7d9a3cefc..000000000 Binary files a/test-data/diagram/44501a.vsd and /dev/null differ diff --git a/test-data/diagram/44501b.vsd b/test-data/diagram/44501b.vsd deleted file mode 100644 index c8bd7a190..000000000 Binary files a/test-data/diagram/44501b.vsd and /dev/null differ diff --git a/test-data/diagram/44501c.vsd b/test-data/diagram/44501c.vsd deleted file mode 100644 index 51de23a32..000000000 Binary files a/test-data/diagram/44501c.vsd and /dev/null differ diff --git a/test-data/diagram/44501d.vsd b/test-data/diagram/44501d.vsd deleted file mode 100644 index 2c1632eba..000000000 Binary files a/test-data/diagram/44501d.vsd and /dev/null differ diff --git a/test-data/diagram/44501e.vsd b/test-data/diagram/44501e.vsd deleted file mode 100644 index 3ca555230..000000000 Binary files a/test-data/diagram/44501e.vsd and /dev/null differ diff --git a/test-data/diagram/44594-2.vsd b/test-data/diagram/44594-2.vsd deleted file mode 100644 index a597a0d93..000000000 Binary files a/test-data/diagram/44594-2.vsd and /dev/null differ diff --git a/test-data/diagram/44594.vsd b/test-data/diagram/44594.vsd deleted file mode 100644 index abed78b4d..000000000 Binary files a/test-data/diagram/44594.vsd and /dev/null differ diff --git a/test-data/diagram/60489.vsdx b/test-data/diagram/60489.vsdx deleted file mode 100644 index 659ecdd58..000000000 Binary files a/test-data/diagram/60489.vsdx and /dev/null differ diff --git a/test-data/diagram/NegativeChunkLength.vsd b/test-data/diagram/NegativeChunkLength.vsd deleted file mode 100644 index 58378bdcc..000000000 Binary files a/test-data/diagram/NegativeChunkLength.vsd and /dev/null differ diff --git a/test-data/diagram/NegativeChunkLength2.vsd b/test-data/diagram/NegativeChunkLength2.vsd deleted file mode 100644 index 3ca555230..000000000 Binary files a/test-data/diagram/NegativeChunkLength2.vsd and /dev/null differ diff --git a/test-data/diagram/ShortChunk1.vsd b/test-data/diagram/ShortChunk1.vsd deleted file mode 100644 index 2c1632eba..000000000 Binary files a/test-data/diagram/ShortChunk1.vsd and /dev/null differ diff --git a/test-data/diagram/ShortChunk2.vsd b/test-data/diagram/ShortChunk2.vsd deleted file mode 100644 index 7d9a3cefc..000000000 Binary files a/test-data/diagram/ShortChunk2.vsd and /dev/null differ diff --git a/test-data/diagram/ShortChunk3.vsd b/test-data/diagram/ShortChunk3.vsd deleted file mode 100644 index c8bd7a190..000000000 Binary files a/test-data/diagram/ShortChunk3.vsd and /dev/null differ diff --git a/test-data/diagram/SimpleMacro.vba b/test-data/diagram/SimpleMacro.vba deleted file mode 100644 index 7fcf1fdb4..000000000 --- a/test-data/diagram/SimpleMacro.vba +++ /dev/null @@ -1,12 +0,0 @@ -Sub TestMacro() -' -' TestMacro Macro -' This is a test macro -' - -' - With ActiveDocument.Pages(1).Shapes(1) - .Text = "This is a macro vector graphics drawing" - End With -End Sub - diff --git a/test-data/diagram/SimpleMacro.vsd b/test-data/diagram/SimpleMacro.vsd deleted file mode 100644 index df3f427ae..000000000 Binary files a/test-data/diagram/SimpleMacro.vsd and /dev/null differ diff --git a/test-data/diagram/SimpleMacro.vsdm b/test-data/diagram/SimpleMacro.vsdm deleted file mode 100644 index 6dc8784ac..000000000 Binary files a/test-data/diagram/SimpleMacro.vsdm and /dev/null differ diff --git a/test-data/diagram/Test_Visio-Some_Random_Text.vsd b/test-data/diagram/Test_Visio-Some_Random_Text.vsd deleted file mode 100644 index d699e1112..000000000 Binary files a/test-data/diagram/Test_Visio-Some_Random_Text.vsd and /dev/null differ diff --git a/test-data/diagram/test.vsdx b/test-data/diagram/test.vsdx deleted file mode 100644 index 1fa690356..000000000 Binary files a/test-data/diagram/test.vsdx and /dev/null differ diff --git a/test-data/diagram/test_text_extraction.vsdx b/test-data/diagram/test_text_extraction.vsdx deleted file mode 100644 index 39b640177..000000000 Binary files a/test-data/diagram/test_text_extraction.vsdx and /dev/null differ diff --git a/test-data/diagram/v5_Connection_Types.vsd b/test-data/diagram/v5_Connection_Types.vsd deleted file mode 100644 index 8c55e3e92..000000000 Binary files a/test-data/diagram/v5_Connection_Types.vsd and /dev/null differ diff --git a/test-data/diagram/v6-non-utf16le.vsd b/test-data/diagram/v6-non-utf16le.vsd deleted file mode 100644 index 8d4fdb89f..000000000 Binary files a/test-data/diagram/v6-non-utf16le.vsd and /dev/null differ diff --git a/test-data/diagram/visio_with_embeded.vsd b/test-data/diagram/visio_with_embeded.vsd deleted file mode 100644 index 91c306fe1..000000000 Binary files a/test-data/diagram/visio_with_embeded.vsd and /dev/null differ diff --git a/test-data/document/45690.docm b/test-data/document/45690.docm deleted file mode 100644 index 5f38e9f51..000000000 Binary files a/test-data/document/45690.docm and /dev/null differ diff --git a/test-data/document/47304.doc b/test-data/document/47304.doc deleted file mode 100644 index d59d8d7ee..000000000 Binary files a/test-data/document/47304.doc and /dev/null differ diff --git a/test-data/document/51921-Word-Crash067.doc b/test-data/document/51921-Word-Crash067.doc deleted file mode 100644 index dc8bfff27..000000000 Binary files a/test-data/document/51921-Word-Crash067.doc and /dev/null differ diff --git a/test-data/document/51921-Word-Crash067.docx b/test-data/document/51921-Word-Crash067.docx deleted file mode 100644 index 12c27c85e..000000000 Binary files a/test-data/document/51921-Word-Crash067.docx and /dev/null differ diff --git a/test-data/document/52117.doc b/test-data/document/52117.doc deleted file mode 100644 index 4f966c01c..000000000 Binary files a/test-data/document/52117.doc and /dev/null differ diff --git a/test-data/document/52288.docx b/test-data/document/52288.docx deleted file mode 100644 index 0eb23b0d4..000000000 Binary files a/test-data/document/52288.docx and /dev/null differ diff --git a/test-data/document/52420.doc b/test-data/document/52420.doc deleted file mode 100644 index f059d2aca..000000000 Binary files a/test-data/document/52420.doc and /dev/null differ diff --git a/test-data/document/52449.docx b/test-data/document/52449.docx deleted file mode 100644 index f294b85db..000000000 Binary files a/test-data/document/52449.docx and /dev/null differ diff --git a/test-data/document/53379.doc b/test-data/document/53379.doc deleted file mode 100644 index 5f1b3bde4..000000000 Binary files a/test-data/document/53379.doc and /dev/null differ diff --git a/test-data/document/53446.doc b/test-data/document/53446.doc deleted file mode 100644 index 4844cc937..000000000 Binary files a/test-data/document/53446.doc and /dev/null differ diff --git a/test-data/document/55733.docx b/test-data/document/55733.docx deleted file mode 100644 index 521f50ee8..000000000 Binary files a/test-data/document/55733.docx and /dev/null differ diff --git a/test-data/document/56392.docx b/test-data/document/56392.docx deleted file mode 100644 index 89a71aed2..000000000 Binary files a/test-data/document/56392.docx and /dev/null differ diff --git a/test-data/document/56880.doc b/test-data/document/56880.doc deleted file mode 100644 index 6aad5f480..000000000 Binary files a/test-data/document/56880.doc and /dev/null differ diff --git a/test-data/document/57312.docx b/test-data/document/57312.docx deleted file mode 100644 index 322759739..000000000 Binary files a/test-data/document/57312.docx and /dev/null differ diff --git a/test-data/document/57603-seven_columns.doc b/test-data/document/57603-seven_columns.doc deleted file mode 100644 index dff48ea46..000000000 Binary files a/test-data/document/57603-seven_columns.doc and /dev/null differ diff --git a/test-data/document/57843.doc b/test-data/document/57843.doc deleted file mode 100644 index 57be6c6ed..000000000 Binary files a/test-data/document/57843.doc and /dev/null differ diff --git a/test-data/document/58067.docx b/test-data/document/58067.docx deleted file mode 100644 index ede9abbe5..000000000 Binary files a/test-data/document/58067.docx and /dev/null differ diff --git a/test-data/document/58618.docx b/test-data/document/58618.docx deleted file mode 100644 index 5a779391e..000000000 Binary files a/test-data/document/58618.docx and /dev/null differ diff --git a/test-data/document/58804.doc b/test-data/document/58804.doc deleted file mode 100644 index 64612730e..000000000 Binary files a/test-data/document/58804.doc and /dev/null differ diff --git a/test-data/document/58804_1.doc b/test-data/document/58804_1.doc deleted file mode 100644 index c79207974..000000000 Binary files a/test-data/document/58804_1.doc and /dev/null differ diff --git a/test-data/document/59030.docx b/test-data/document/59030.docx deleted file mode 100644 index cf40dd221..000000000 Binary files a/test-data/document/59030.docx and /dev/null differ diff --git a/test-data/document/59378.docx b/test-data/document/59378.docx deleted file mode 100644 index f3939ade5..000000000 Binary files a/test-data/document/59378.docx and /dev/null differ diff --git a/test-data/document/60158.docm b/test-data/document/60158.docm deleted file mode 100644 index 2b7908fe3..000000000 Binary files a/test-data/document/60158.docm and /dev/null differ diff --git a/test-data/document/60293.docx b/test-data/document/60293.docx deleted file mode 100644 index 02dcabc9c..000000000 Binary files a/test-data/document/60293.docx and /dev/null differ diff --git a/test-data/document/60329.docx b/test-data/document/60329.docx deleted file mode 100644 index c0bb15ca0..000000000 Binary files a/test-data/document/60329.docx and /dev/null differ diff --git a/test-data/document/AIOOB-Tap.doc b/test-data/document/AIOOB-Tap.doc deleted file mode 100644 index bfd5906ca..000000000 Binary files a/test-data/document/AIOOB-Tap.doc and /dev/null differ diff --git a/test-data/document/Bug28627.doc b/test-data/document/Bug28627.doc deleted file mode 100644 index 91b031d1d..000000000 Binary files a/test-data/document/Bug28627.doc and /dev/null differ diff --git a/test-data/document/Bug33519.doc b/test-data/document/Bug33519.doc deleted file mode 100644 index b51fc0b5e..000000000 Binary files a/test-data/document/Bug33519.doc and /dev/null differ diff --git a/test-data/document/Bug34898.doc b/test-data/document/Bug34898.doc deleted file mode 100644 index fbe49d0a1..000000000 Binary files a/test-data/document/Bug34898.doc and /dev/null differ diff --git a/test-data/document/Bug41898.doc b/test-data/document/Bug41898.doc deleted file mode 100644 index a475813c8..000000000 Binary files a/test-data/document/Bug41898.doc and /dev/null differ diff --git a/test-data/document/Bug44292.doc b/test-data/document/Bug44292.doc deleted file mode 100644 index fd7ca6cc3..000000000 Binary files a/test-data/document/Bug44292.doc and /dev/null differ diff --git a/test-data/document/Bug44431.doc b/test-data/document/Bug44431.doc deleted file mode 100644 index c4b371c5b..000000000 Binary files a/test-data/document/Bug44431.doc and /dev/null differ diff --git a/test-data/document/Bug44603.doc b/test-data/document/Bug44603.doc deleted file mode 100644 index 00312ae1e..000000000 Binary files a/test-data/document/Bug44603.doc and /dev/null differ diff --git a/test-data/document/Bug45269.doc b/test-data/document/Bug45269.doc deleted file mode 100644 index aea4ff93d..000000000 Binary files a/test-data/document/Bug45269.doc and /dev/null differ diff --git a/test-data/document/Bug45473.doc b/test-data/document/Bug45473.doc deleted file mode 100644 index 395e9004e..000000000 Binary files a/test-data/document/Bug45473.doc and /dev/null differ diff --git a/test-data/document/Bug45877.doc b/test-data/document/Bug45877.doc deleted file mode 100644 index af2d6eda1..000000000 Binary files a/test-data/document/Bug45877.doc and /dev/null differ diff --git a/test-data/document/Bug46220.doc b/test-data/document/Bug46220.doc deleted file mode 100644 index 3af65fd26..000000000 Binary files a/test-data/document/Bug46220.doc and /dev/null differ diff --git a/test-data/document/Bug46610_1.doc b/test-data/document/Bug46610_1.doc deleted file mode 100644 index 4291d9c1d..000000000 Binary files a/test-data/document/Bug46610_1.doc and /dev/null differ diff --git a/test-data/document/Bug46610_2.doc b/test-data/document/Bug46610_2.doc deleted file mode 100644 index be9083140..000000000 Binary files a/test-data/document/Bug46610_2.doc and /dev/null differ diff --git a/test-data/document/Bug46610_3.doc b/test-data/document/Bug46610_3.doc deleted file mode 100644 index 72d60df92..000000000 Binary files a/test-data/document/Bug46610_3.doc and /dev/null differ diff --git a/test-data/document/Bug46817.doc b/test-data/document/Bug46817.doc deleted file mode 100644 index 1574e6e30..000000000 Binary files a/test-data/document/Bug46817.doc and /dev/null differ diff --git a/test-data/document/Bug47286.doc b/test-data/document/Bug47286.doc deleted file mode 100644 index 96b88c526..000000000 Binary files a/test-data/document/Bug47286.doc and /dev/null differ diff --git a/test-data/document/Bug47287.doc b/test-data/document/Bug47287.doc deleted file mode 100644 index 96b88c526..000000000 Binary files a/test-data/document/Bug47287.doc and /dev/null differ diff --git a/test-data/document/Bug47731.doc b/test-data/document/Bug47731.doc deleted file mode 100644 index c8cd88d25..000000000 Binary files a/test-data/document/Bug47731.doc and /dev/null differ diff --git a/test-data/document/Bug47742-text.txt b/test-data/document/Bug47742-text.txt deleted file mode 100644 index 7b027123d..000000000 --- a/test-data/document/Bug47742-text.txt +++ /dev/null @@ -1,35 +0,0 @@ -{0>Der Aaa Satz.<}0{>The Aaa phrase.<0} {0>Der Bbb Satz.<}0{>The Bbb phrase.<0} {0>Der Ccc Satz.<}0{>The Ccc phrase.<0} {0>Der Ddd Satz.<}0{>The Ddd phrase.<0} -{0>Der Eee Satz.<}0{>The Eee phrase.<0} {0>Der Fff Satz.<}0{>The Fff phrase.<0} -{0>Der Ggg Satz .<}0{>The Ggg phrase .<0} -{0>Der Gggggg Satz .<}0{>The Gggggg phrase .<0} -{0>Ein Zeil -enumbruch mittendrin.<}0{>A soft -return in the center.<0} -{0>Ein Satz -mit soft return.<}0{>A sentence -with soft return.<0} - -{0>Ein-Strich.<}0{>One-hyphen.<0} -{0>Die G-20 Staaten.<}0{>The G-20 states.<0} -{0>Ein—Geviertstrich hier.<}0{>An—EMdash here.<0} -{0>Ein/Schrägstrich hier.<}0{>A/slash here.<0} -{0>Senkrechter|Strich hier.<}0{>Vertical|line here.<0} -{0>Umgekehrter\Schrägstrich hier.<}0{>A\backslash here.<0} -{0>C'est la vie.<}0{>Such is life.<0} -{0>Das sind 10'000 Euros.<}0{>These are 10'000 Euros.<0} -{0>Eine Komma,Trennung hier.<}0{>A comma,separation here.<0} -{0>Eine Semikolon;Trennung hier.<}0{>A semicolon;separation here.<0} -{0>Das sind 77,mehr hier.<}0{>There are 77,more here.<0} -{0>Das ist sein (Netto)Gehalt<}0{>This is his (net)salary.<0} -{0>Das sind 50$ hier.<}0{>That is 50$ here.<0} -{0>Das sind 3%Rabatt.<}0{>That is 3% discount.<0} -{0>Es sind 25°C heute.<}0{>It is 25°C today.<0} -{0>Es gilt YenIt is YenKeine Trennung® bei Sonderzeichen.<}0{>No separation® here..<0} -{0>Ich zahle 7 Euro.<}0{>I pay 7 Euros.<0} -{0>Die Disk ist 6 min lang.<}0{>The disk is 6 min long.<0} -{0>Ein Satz, mit Komma.<}0{>A sentence, with comma.<0} -{0>Ein Hochkomma hier.<}0{>An apostrophe here.<0} -{0>Ein Satz mit verschiedenen Pausen.<}0{>A sentence with different blanks.<0} -{0>Ein Satz mit geschützten Pausen.<}0{>A sentence with non-breaking blanks.<0} -{0>Ein Satz mit speziellen  Pausen.<}0{>A sentence with special  blanks.<0} diff --git a/test-data/document/Bug47742.doc b/test-data/document/Bug47742.doc deleted file mode 100644 index be3959afd..000000000 Binary files a/test-data/document/Bug47742.doc and /dev/null differ diff --git a/test-data/document/Bug47958.doc b/test-data/document/Bug47958.doc deleted file mode 100644 index c621b36c3..000000000 Binary files a/test-data/document/Bug47958.doc and /dev/null differ diff --git a/test-data/document/Bug48065.doc b/test-data/document/Bug48065.doc deleted file mode 100644 index 8dce3dbdf..000000000 Binary files a/test-data/document/Bug48065.doc and /dev/null differ diff --git a/test-data/document/Bug48075.doc b/test-data/document/Bug48075.doc deleted file mode 100644 index 386b5305b..000000000 Binary files a/test-data/document/Bug48075.doc and /dev/null differ diff --git a/test-data/document/Bug49820.doc b/test-data/document/Bug49820.doc deleted file mode 100644 index b3a4aea3f..000000000 Binary files a/test-data/document/Bug49820.doc and /dev/null differ diff --git a/test-data/document/Bug49908.doc b/test-data/document/Bug49908.doc deleted file mode 100644 index 6a89732e7..000000000 Binary files a/test-data/document/Bug49908.doc and /dev/null differ diff --git a/test-data/document/Bug49919.doc b/test-data/document/Bug49919.doc deleted file mode 100644 index 656872c94..000000000 Binary files a/test-data/document/Bug49919.doc and /dev/null differ diff --git a/test-data/document/Bug49933.doc b/test-data/document/Bug49933.doc deleted file mode 100644 index 7db961b63..000000000 Binary files a/test-data/document/Bug49933.doc and /dev/null differ diff --git a/test-data/document/Bug50075.doc b/test-data/document/Bug50075.doc deleted file mode 100644 index 15303a46f..000000000 Binary files a/test-data/document/Bug50075.doc and /dev/null differ diff --git a/test-data/document/Bug50936_1.doc b/test-data/document/Bug50936_1.doc deleted file mode 100644 index 3a700adb7..000000000 Binary files a/test-data/document/Bug50936_1.doc and /dev/null differ diff --git a/test-data/document/Bug50936_2.doc b/test-data/document/Bug50936_2.doc deleted file mode 100644 index d153eef3a..000000000 Binary files a/test-data/document/Bug50936_2.doc and /dev/null differ diff --git a/test-data/document/Bug50936_3.doc b/test-data/document/Bug50936_3.doc deleted file mode 100644 index 7a644b7e1..000000000 Binary files a/test-data/document/Bug50936_3.doc and /dev/null differ diff --git a/test-data/document/Bug50955.doc b/test-data/document/Bug50955.doc deleted file mode 100644 index 9154c4f82..000000000 Binary files a/test-data/document/Bug50955.doc and /dev/null differ diff --git a/test-data/document/Bug51170.docx b/test-data/document/Bug51170.docx deleted file mode 100644 index c712cdc20..000000000 Binary files a/test-data/document/Bug51170.docx and /dev/null differ diff --git a/test-data/document/Bug51604.doc b/test-data/document/Bug51604.doc deleted file mode 100644 index c843fb4a3..000000000 Binary files a/test-data/document/Bug51604.doc and /dev/null differ diff --git a/test-data/document/Bug51686.doc b/test-data/document/Bug51686.doc deleted file mode 100644 index c1f4f3d0b..000000000 Binary files a/test-data/document/Bug51686.doc and /dev/null differ diff --git a/test-data/document/Bug51834.doc b/test-data/document/Bug51834.doc deleted file mode 100644 index c1628251d..000000000 Binary files a/test-data/document/Bug51834.doc and /dev/null differ diff --git a/test-data/document/Bug51890.doc b/test-data/document/Bug51890.doc deleted file mode 100644 index 82701bdd2..000000000 Binary files a/test-data/document/Bug51890.doc and /dev/null differ diff --git a/test-data/document/Bug51944.doc b/test-data/document/Bug51944.doc deleted file mode 100644 index 2598dc10c..000000000 Binary files a/test-data/document/Bug51944.doc and /dev/null differ diff --git a/test-data/document/Bug52032_1.doc b/test-data/document/Bug52032_1.doc deleted file mode 100644 index adfa972ad..000000000 Binary files a/test-data/document/Bug52032_1.doc and /dev/null differ diff --git a/test-data/document/Bug52032_2.doc b/test-data/document/Bug52032_2.doc deleted file mode 100644 index cc0ede165..000000000 Binary files a/test-data/document/Bug52032_2.doc and /dev/null differ diff --git a/test-data/document/Bug52032_3.doc b/test-data/document/Bug52032_3.doc deleted file mode 100644 index c91d240bf..000000000 Binary files a/test-data/document/Bug52032_3.doc and /dev/null differ diff --git a/test-data/document/Bug52311.doc b/test-data/document/Bug52311.doc deleted file mode 100644 index 16f55688a..000000000 Binary files a/test-data/document/Bug52311.doc and /dev/null differ diff --git a/test-data/document/Bug52583.doc b/test-data/document/Bug52583.doc deleted file mode 100644 index b6e8646e6..000000000 Binary files a/test-data/document/Bug52583.doc and /dev/null differ diff --git a/test-data/document/Bug53182.doc b/test-data/document/Bug53182.doc deleted file mode 100644 index c627d0263..000000000 Binary files a/test-data/document/Bug53182.doc and /dev/null differ diff --git a/test-data/document/Bug53380_1.doc b/test-data/document/Bug53380_1.doc deleted file mode 100644 index 4233ac1e8..000000000 Binary files a/test-data/document/Bug53380_1.doc and /dev/null differ diff --git a/test-data/document/Bug53380_2.doc b/test-data/document/Bug53380_2.doc deleted file mode 100644 index 1dd3daa18..000000000 Binary files a/test-data/document/Bug53380_2.doc and /dev/null differ diff --git a/test-data/document/Bug53380_3.doc b/test-data/document/Bug53380_3.doc deleted file mode 100644 index 5f1b3bde4..000000000 Binary files a/test-data/document/Bug53380_3.doc and /dev/null differ diff --git a/test-data/document/Bug53380_4.doc b/test-data/document/Bug53380_4.doc deleted file mode 100644 index dc33d898b..000000000 Binary files a/test-data/document/Bug53380_4.doc and /dev/null differ diff --git a/test-data/document/Bug53453Section.doc b/test-data/document/Bug53453Section.doc deleted file mode 100644 index 23275b6d8..000000000 Binary files a/test-data/document/Bug53453Section.doc and /dev/null differ diff --git a/test-data/document/Bug54771a.docx b/test-data/document/Bug54771a.docx deleted file mode 100644 index 19bbbd1a4..000000000 Binary files a/test-data/document/Bug54771a.docx and /dev/null differ diff --git a/test-data/document/Bug54771b.docx b/test-data/document/Bug54771b.docx deleted file mode 100644 index f9850bb55..000000000 Binary files a/test-data/document/Bug54771b.docx and /dev/null differ diff --git a/test-data/document/Bug54849.docx b/test-data/document/Bug54849.docx deleted file mode 100644 index 836c14706..000000000 Binary files a/test-data/document/Bug54849.docx and /dev/null differ diff --git a/test-data/document/Bug55142.docx b/test-data/document/Bug55142.docx deleted file mode 100644 index 1ae2adafe..000000000 Binary files a/test-data/document/Bug55142.docx and /dev/null differ diff --git a/test-data/document/Bug60337.docx b/test-data/document/Bug60337.docx deleted file mode 100644 index 06d0339fc..000000000 Binary files a/test-data/document/Bug60337.docx and /dev/null differ diff --git a/test-data/document/Bug60341.docx b/test-data/document/Bug60341.docx deleted file mode 100644 index d97ebdce7..000000000 Binary files a/test-data/document/Bug60341.docx and /dev/null differ diff --git a/test-data/document/Bug60936.doc b/test-data/document/Bug60936.doc deleted file mode 100644 index e7e397d56..000000000 Binary files a/test-data/document/Bug60936.doc and /dev/null differ diff --git a/test-data/document/Bug60942.doc b/test-data/document/Bug60942.doc deleted file mode 100644 index fe64e67bc..000000000 Binary files a/test-data/document/Bug60942.doc and /dev/null differ diff --git a/test-data/document/Bug60942b.doc b/test-data/document/Bug60942b.doc deleted file mode 100644 index 7ca3b9839..000000000 Binary files a/test-data/document/Bug60942b.doc and /dev/null differ diff --git a/test-data/document/ComplexNumberedLists.docx b/test-data/document/ComplexNumberedLists.docx deleted file mode 100644 index b4409c9d1..000000000 Binary files a/test-data/document/ComplexNumberedLists.docx and /dev/null differ diff --git a/test-data/document/DiffFirstPageHeadFoot.doc b/test-data/document/DiffFirstPageHeadFoot.doc deleted file mode 100644 index 397aa2f99..000000000 Binary files a/test-data/document/DiffFirstPageHeadFoot.doc and /dev/null differ diff --git a/test-data/document/DiffFirstPageHeadFoot.docx b/test-data/document/DiffFirstPageHeadFoot.docx deleted file mode 100644 index d631c77e5..000000000 Binary files a/test-data/document/DiffFirstPageHeadFoot.docx and /dev/null differ diff --git a/test-data/document/EmbeddedDocument.docx b/test-data/document/EmbeddedDocument.docx deleted file mode 100644 index 1cb35a5cf..000000000 Binary files a/test-data/document/EmbeddedDocument.docx and /dev/null differ diff --git a/test-data/document/EmptyDocumentWithHeaderFooter.docx b/test-data/document/EmptyDocumentWithHeaderFooter.docx deleted file mode 100644 index f5af23000..000000000 Binary files a/test-data/document/EmptyDocumentWithHeaderFooter.docx and /dev/null differ diff --git a/test-data/document/EnforcedWith.docx b/test-data/document/EnforcedWith.docx deleted file mode 100644 index c50e35859..000000000 Binary files a/test-data/document/EnforcedWith.docx and /dev/null differ diff --git a/test-data/document/ExternalEntityInText.docx b/test-data/document/ExternalEntityInText.docx deleted file mode 100644 index 0b47852de..000000000 Binary files a/test-data/document/ExternalEntityInText.docx and /dev/null differ diff --git a/test-data/document/FancyFoot.doc b/test-data/document/FancyFoot.doc deleted file mode 100644 index 5d3e66245..000000000 Binary files a/test-data/document/FancyFoot.doc and /dev/null differ diff --git a/test-data/document/FancyFoot.docx b/test-data/document/FancyFoot.docx deleted file mode 100644 index 3e571b39d..000000000 Binary files a/test-data/document/FancyFoot.docx and /dev/null differ diff --git a/test-data/document/FieldCodes.docx b/test-data/document/FieldCodes.docx deleted file mode 100644 index 3db97f5ce..000000000 Binary files a/test-data/document/FieldCodes.docx and /dev/null differ diff --git a/test-data/document/FldSimple.docx b/test-data/document/FldSimple.docx deleted file mode 100644 index 029016ce0..000000000 Binary files a/test-data/document/FldSimple.docx and /dev/null differ diff --git a/test-data/document/FloatingPictures.doc b/test-data/document/FloatingPictures.doc deleted file mode 100644 index 15b06cf3f..000000000 Binary files a/test-data/document/FloatingPictures.doc and /dev/null differ diff --git a/test-data/document/GaiaTest.doc b/test-data/document/GaiaTest.doc deleted file mode 100644 index 4e7f07bdb..000000000 Binary files a/test-data/document/GaiaTest.doc and /dev/null differ diff --git a/test-data/document/GaiaTestImg.png b/test-data/document/GaiaTestImg.png deleted file mode 100644 index 1ebd99139..000000000 Binary files a/test-data/document/GaiaTestImg.png and /dev/null differ diff --git a/test-data/document/HeaderFooterProblematic.doc b/test-data/document/HeaderFooterProblematic.doc deleted file mode 100644 index a4d9d303d..000000000 Binary files a/test-data/document/HeaderFooterProblematic.doc and /dev/null differ diff --git a/test-data/document/HeaderFooterUnicode.doc b/test-data/document/HeaderFooterUnicode.doc deleted file mode 100644 index 1b517f6a2..000000000 Binary files a/test-data/document/HeaderFooterUnicode.doc and /dev/null differ diff --git a/test-data/document/HeaderFooterUnicode.docx b/test-data/document/HeaderFooterUnicode.docx deleted file mode 100644 index 643967c5e..000000000 Binary files a/test-data/document/HeaderFooterUnicode.docx and /dev/null differ diff --git a/test-data/document/HeaderWithMacros.doc b/test-data/document/HeaderWithMacros.doc deleted file mode 100644 index 934970f58..000000000 Binary files a/test-data/document/HeaderWithMacros.doc and /dev/null differ diff --git a/test-data/document/Headers.docx b/test-data/document/Headers.docx deleted file mode 100644 index ab1ec0288..000000000 Binary files a/test-data/document/Headers.docx and /dev/null differ diff --git a/test-data/document/IllustrativeCases.docx b/test-data/document/IllustrativeCases.docx deleted file mode 100644 index 29dacb652..000000000 Binary files a/test-data/document/IllustrativeCases.docx and /dev/null differ diff --git a/test-data/document/ListEntryNoListTable.doc b/test-data/document/ListEntryNoListTable.doc deleted file mode 100644 index 939f5a4a9..000000000 Binary files a/test-data/document/ListEntryNoListTable.doc and /dev/null differ diff --git a/test-data/document/Lists.doc b/test-data/document/Lists.doc deleted file mode 100644 index 80201eef1..000000000 Binary files a/test-data/document/Lists.doc and /dev/null differ diff --git a/test-data/document/MarkAuthorsTable.doc b/test-data/document/MarkAuthorsTable.doc deleted file mode 100644 index acafa3aa4..000000000 Binary files a/test-data/document/MarkAuthorsTable.doc and /dev/null differ diff --git a/test-data/document/NoHeadFoot.doc b/test-data/document/NoHeadFoot.doc deleted file mode 100644 index 8c95f4725..000000000 Binary files a/test-data/document/NoHeadFoot.doc and /dev/null differ diff --git a/test-data/document/NoHeadFoot.docx b/test-data/document/NoHeadFoot.docx deleted file mode 100644 index 7af2a1458..000000000 Binary files a/test-data/document/NoHeadFoot.docx and /dev/null differ diff --git a/test-data/document/Numbering.docx b/test-data/document/Numbering.docx deleted file mode 100644 index d5605c9f7..000000000 Binary files a/test-data/document/Numbering.docx and /dev/null differ diff --git a/test-data/document/NumberingWOverrides.docx b/test-data/document/NumberingWOverrides.docx deleted file mode 100644 index 48a7e2c25..000000000 Binary files a/test-data/document/NumberingWOverrides.docx and /dev/null differ diff --git a/test-data/document/PageSpecificHeadFoot.doc b/test-data/document/PageSpecificHeadFoot.doc deleted file mode 100644 index 26866afae..000000000 Binary files a/test-data/document/PageSpecificHeadFoot.doc and /dev/null differ diff --git a/test-data/document/PageSpecificHeadFoot.docx b/test-data/document/PageSpecificHeadFoot.docx deleted file mode 100644 index 13097b990..000000000 Binary files a/test-data/document/PageSpecificHeadFoot.docx and /dev/null differ diff --git a/test-data/document/PasswordProtected.doc b/test-data/document/PasswordProtected.doc deleted file mode 100644 index 0d6c16906..000000000 Binary files a/test-data/document/PasswordProtected.doc and /dev/null differ diff --git a/test-data/document/Picture_Alternative_Text.doc b/test-data/document/Picture_Alternative_Text.doc deleted file mode 100644 index 55bf875d0..000000000 Binary files a/test-data/document/Picture_Alternative_Text.doc and /dev/null differ diff --git a/test-data/document/PngPicture.doc b/test-data/document/PngPicture.doc deleted file mode 100644 index 4d8c41792..000000000 Binary files a/test-data/document/PngPicture.doc and /dev/null differ diff --git a/test-data/document/ProblemExtracting.doc b/test-data/document/ProblemExtracting.doc deleted file mode 100644 index b98008943..000000000 Binary files a/test-data/document/ProblemExtracting.doc and /dev/null differ diff --git a/test-data/document/SampleDoc.doc b/test-data/document/SampleDoc.doc deleted file mode 100644 index e82c7def3..000000000 Binary files a/test-data/document/SampleDoc.doc and /dev/null differ diff --git a/test-data/document/SampleDoc.docx b/test-data/document/SampleDoc.docx deleted file mode 100644 index a43c77ae2..000000000 Binary files a/test-data/document/SampleDoc.docx and /dev/null differ diff --git a/test-data/document/SampleDoc.txt b/test-data/document/SampleDoc.txt deleted file mode 100644 index 6b5fd4655..000000000 --- a/test-data/document/SampleDoc.txt +++ /dev/null @@ -1,14 +0,0 @@ -Author = Nick Burch -Title = Test Document -Subject = This is a sample document -Keywords = Testing Sample -Comments = This document is used for testing text and metadata extraction - - -I am a test document -This is page 1 -I am Calibri (Body) in font size 11 -  -This is page two -It’s Arial Black in 16 point -It’s also in blue diff --git a/test-data/document/SimpleHeadThreeColFoot.doc b/test-data/document/SimpleHeadThreeColFoot.doc deleted file mode 100644 index 2f8daec63..000000000 Binary files a/test-data/document/SimpleHeadThreeColFoot.doc and /dev/null differ diff --git a/test-data/document/SimpleHeadThreeColFoot.docx b/test-data/document/SimpleHeadThreeColFoot.docx deleted file mode 100644 index fb17df23a..000000000 Binary files a/test-data/document/SimpleHeadThreeColFoot.docx and /dev/null differ diff --git a/test-data/document/SimpleMacro.doc b/test-data/document/SimpleMacro.doc deleted file mode 100644 index a6311b3c9..000000000 Binary files a/test-data/document/SimpleMacro.doc and /dev/null differ diff --git a/test-data/document/SimpleMacro.docm b/test-data/document/SimpleMacro.docm deleted file mode 100644 index 123b8157f..000000000 Binary files a/test-data/document/SimpleMacro.docm and /dev/null differ diff --git a/test-data/document/SimpleMacro.vba b/test-data/document/SimpleMacro.vba deleted file mode 100644 index 684420c27..000000000 --- a/test-data/document/SimpleMacro.vba +++ /dev/null @@ -1,10 +0,0 @@ -Sub TestMacro() -' -' TestMacro Macro -' This is a test macro -' - -' - ActiveDocument.Paragraphs(1).Range.Text = "This is a macro word processing document" -End Sub - diff --git a/test-data/document/Styles.docx b/test-data/document/Styles.docx deleted file mode 100644 index 27f66f48b..000000000 Binary files a/test-data/document/Styles.docx and /dev/null differ diff --git a/test-data/document/TestDocument.docx b/test-data/document/TestDocument.docx deleted file mode 100644 index d87a542ec..000000000 Binary files a/test-data/document/TestDocument.docx and /dev/null differ diff --git a/test-data/document/TestPoiXMLDocumentCorePropertiesGetKeywords.docx b/test-data/document/TestPoiXMLDocumentCorePropertiesGetKeywords.docx deleted file mode 100644 index ee3847991..000000000 Binary files a/test-data/document/TestPoiXMLDocumentCorePropertiesGetKeywords.docx and /dev/null differ diff --git a/test-data/document/TestTableCellAlign.docx b/test-data/document/TestTableCellAlign.docx deleted file mode 100644 index cf40dd221..000000000 Binary files a/test-data/document/TestTableCellAlign.docx and /dev/null differ diff --git a/test-data/document/ThreeColFoot.doc b/test-data/document/ThreeColFoot.doc deleted file mode 100644 index d0d6daf77..000000000 Binary files a/test-data/document/ThreeColFoot.doc and /dev/null differ diff --git a/test-data/document/ThreeColFoot.docx b/test-data/document/ThreeColFoot.docx deleted file mode 100644 index b01e35636..000000000 Binary files a/test-data/document/ThreeColFoot.docx and /dev/null differ diff --git a/test-data/document/ThreeColHead.doc b/test-data/document/ThreeColHead.doc deleted file mode 100644 index 1a49b962a..000000000 Binary files a/test-data/document/ThreeColHead.doc and /dev/null differ diff --git a/test-data/document/ThreeColHead.docx b/test-data/document/ThreeColHead.docx deleted file mode 100644 index 448d046d3..000000000 Binary files a/test-data/document/ThreeColHead.docx and /dev/null differ diff --git a/test-data/document/ThreeColHeadFoot.doc b/test-data/document/ThreeColHeadFoot.doc deleted file mode 100644 index 67e77de80..000000000 Binary files a/test-data/document/ThreeColHeadFoot.doc and /dev/null differ diff --git a/test-data/document/ThreeColHeadFoot.docx b/test-data/document/ThreeColHeadFoot.docx deleted file mode 100644 index 51602ccfe..000000000 Binary files a/test-data/document/ThreeColHeadFoot.docx and /dev/null differ diff --git a/test-data/document/Tika-792.docx b/test-data/document/Tika-792.docx deleted file mode 100644 index e8ddc0b1d..000000000 Binary files a/test-data/document/Tika-792.docx and /dev/null differ diff --git a/test-data/document/VariousPictures.docx b/test-data/document/VariousPictures.docx deleted file mode 100644 index 2ab9a1645..000000000 Binary files a/test-data/document/VariousPictures.docx and /dev/null differ diff --git a/test-data/document/WithArtShapes.doc b/test-data/document/WithArtShapes.doc deleted file mode 100644 index 27793c37a..000000000 Binary files a/test-data/document/WithArtShapes.doc and /dev/null differ diff --git a/test-data/document/WithGIF.docx b/test-data/document/WithGIF.docx deleted file mode 100644 index 8af42d588..000000000 Binary files a/test-data/document/WithGIF.docx and /dev/null differ diff --git a/test-data/document/WithTabs.docx b/test-data/document/WithTabs.docx deleted file mode 100644 index e9b3a7a1d..000000000 Binary files a/test-data/document/WithTabs.docx and /dev/null differ diff --git a/test-data/document/Word6.doc b/test-data/document/Word6.doc deleted file mode 100644 index a614a0783..000000000 Binary files a/test-data/document/Word6.doc and /dev/null differ diff --git a/test-data/document/Word6_sections.doc b/test-data/document/Word6_sections.doc deleted file mode 100644 index e7ac98935..000000000 Binary files a/test-data/document/Word6_sections.doc and /dev/null differ diff --git a/test-data/document/Word6_sections2.doc b/test-data/document/Word6_sections2.doc deleted file mode 100644 index d07da5bc1..000000000 Binary files a/test-data/document/Word6_sections2.doc and /dev/null differ diff --git a/test-data/document/Word95.doc b/test-data/document/Word95.doc deleted file mode 100644 index a214f2925..000000000 Binary files a/test-data/document/Word95.doc and /dev/null differ diff --git a/test-data/document/WordWithAttachments.docx b/test-data/document/WordWithAttachments.docx deleted file mode 100644 index ebefabc44..000000000 Binary files a/test-data/document/WordWithAttachments.docx and /dev/null differ diff --git a/test-data/document/abstract1.jpg b/test-data/document/abstract1.jpg deleted file mode 100644 index 2c61df9d6..000000000 Binary files a/test-data/document/abstract1.jpg and /dev/null differ diff --git a/test-data/document/abstract2.jpg b/test-data/document/abstract2.jpg deleted file mode 100644 index 598fbf685..000000000 Binary files a/test-data/document/abstract2.jpg and /dev/null differ diff --git a/test-data/document/abstract3.jpg b/test-data/document/abstract3.jpg deleted file mode 100644 index 178af68a6..000000000 Binary files a/test-data/document/abstract3.jpg and /dev/null differ diff --git a/test-data/document/abstract4.jpg b/test-data/document/abstract4.jpg deleted file mode 100644 index bb34774f6..000000000 Binary files a/test-data/document/abstract4.jpg and /dev/null differ diff --git a/test-data/document/au.edu.utas.www___data_assets_word_doc_0003_154335_International-Travel-Approval-Request-Form.doc b/test-data/document/au.edu.utas.www___data_assets_word_doc_0003_154335_International-Travel-Approval-Request-Form.doc deleted file mode 100644 index 82d00415e..000000000 Binary files a/test-data/document/au.edu.utas.www___data_assets_word_doc_0003_154335_International-Travel-Approval-Request-Form.doc and /dev/null differ diff --git a/test-data/document/bookmarks.docx b/test-data/document/bookmarks.docx deleted file mode 100644 index b7816e70c..000000000 Binary files a/test-data/document/bookmarks.docx and /dev/null differ diff --git a/test-data/document/bug53475-password-is-pass.docx b/test-data/document/bug53475-password-is-pass.docx deleted file mode 100644 index b969da60f..000000000 Binary files a/test-data/document/bug53475-password-is-pass.docx and /dev/null differ diff --git a/test-data/document/bug53475-password-is-solrcell.docx b/test-data/document/bug53475-password-is-solrcell.docx deleted file mode 100644 index 2723d5654..000000000 Binary files a/test-data/document/bug53475-password-is-solrcell.docx and /dev/null differ diff --git a/test-data/document/bug56075-changeTracking_off.docx b/test-data/document/bug56075-changeTracking_off.docx deleted file mode 100644 index a92202d22..000000000 Binary files a/test-data/document/bug56075-changeTracking_off.docx and /dev/null differ diff --git a/test-data/document/bug56075-changeTracking_on.docx b/test-data/document/bug56075-changeTracking_on.docx deleted file mode 100644 index 401af507f..000000000 Binary files a/test-data/document/bug56075-changeTracking_on.docx and /dev/null differ diff --git a/test-data/document/bug56076.docx b/test-data/document/bug56076.docx deleted file mode 100644 index a1ba93e3a..000000000 Binary files a/test-data/document/bug56076.docx and /dev/null differ diff --git a/test-data/document/bug57031.docx b/test-data/document/bug57031.docx deleted file mode 100644 index 6a1230e6f..000000000 Binary files a/test-data/document/bug57031.docx and /dev/null differ diff --git a/test-data/document/bug59058.docx b/test-data/document/bug59058.docx deleted file mode 100644 index 08808daec..000000000 Binary files a/test-data/document/bug59058.docx and /dev/null differ diff --git a/test-data/document/ca.kwsymphony.www_education_School_Concert_Seat_Booking_Form_2011-12.doc b/test-data/document/ca.kwsymphony.www_education_School_Concert_Seat_Booking_Form_2011-12.doc deleted file mode 100755 index 97edf5116..000000000 Binary files a/test-data/document/ca.kwsymphony.www_education_School_Concert_Seat_Booking_Form_2011-12.doc and /dev/null differ diff --git a/test-data/document/cap.stanford.edu_profiles_viewbiosketch_facultyid=4009&name=m_maciver.doc b/test-data/document/cap.stanford.edu_profiles_viewbiosketch_facultyid=4009&name=m_maciver.doc deleted file mode 100644 index 643d8224a..000000000 Binary files a/test-data/document/cap.stanford.edu_profiles_viewbiosketch_facultyid=4009&name=m_maciver.doc and /dev/null differ diff --git a/test-data/document/checkboxes.docx b/test-data/document/checkboxes.docx deleted file mode 100644 index c35b71598..000000000 Binary files a/test-data/document/checkboxes.docx and /dev/null differ diff --git a/test-data/document/cpansearch.perl.org_src_tobyink_acme-rundoc-0.001_word-lib_hello_world.docm b/test-data/document/cpansearch.perl.org_src_tobyink_acme-rundoc-0.001_word-lib_hello_world.docm deleted file mode 100644 index 8aa4522c4..000000000 Binary files a/test-data/document/cpansearch.perl.org_src_tobyink_acme-rundoc-0.001_word-lib_hello_world.docm and /dev/null differ diff --git a/test-data/document/delins.docx b/test-data/document/delins.docx deleted file mode 100644 index b53069135..000000000 Binary files a/test-data/document/delins.docx and /dev/null differ diff --git a/test-data/document/documentProperties.doc b/test-data/document/documentProperties.doc deleted file mode 100644 index 09730cb36..000000000 Binary files a/test-data/document/documentProperties.doc and /dev/null differ diff --git a/test-data/document/documentProperties.docx b/test-data/document/documentProperties.docx deleted file mode 100644 index 4ec577ee9..000000000 Binary files a/test-data/document/documentProperties.docx and /dev/null differ diff --git a/test-data/document/documentProtection_comments_no_password.docx b/test-data/document/documentProtection_comments_no_password.docx deleted file mode 100644 index 5cc800e36..000000000 Binary files a/test-data/document/documentProtection_comments_no_password.docx and /dev/null differ diff --git a/test-data/document/documentProtection_forms_no_password.docx b/test-data/document/documentProtection_forms_no_password.docx deleted file mode 100644 index 8d31026b4..000000000 Binary files a/test-data/document/documentProtection_forms_no_password.docx and /dev/null differ diff --git a/test-data/document/documentProtection_no_protection.docx b/test-data/document/documentProtection_no_protection.docx deleted file mode 100644 index fc1089e39..000000000 Binary files a/test-data/document/documentProtection_no_protection.docx and /dev/null differ diff --git a/test-data/document/documentProtection_no_protection_tag_existing.docx b/test-data/document/documentProtection_no_protection_tag_existing.docx deleted file mode 100644 index 2c655b6b1..000000000 Binary files a/test-data/document/documentProtection_no_protection_tag_existing.docx and /dev/null differ diff --git a/test-data/document/documentProtection_readonly_no_password.docx b/test-data/document/documentProtection_readonly_no_password.docx deleted file mode 100644 index 1ec7063ab..000000000 Binary files a/test-data/document/documentProtection_readonly_no_password.docx and /dev/null differ diff --git a/test-data/document/documentProtection_trackedChanges_no_password.docx b/test-data/document/documentProtection_trackedChanges_no_password.docx deleted file mode 100644 index 8531573c0..000000000 Binary files a/test-data/document/documentProtection_trackedChanges_no_password.docx and /dev/null differ diff --git a/test-data/document/drawing.docx b/test-data/document/drawing.docx deleted file mode 100644 index 23546b7f2..000000000 Binary files a/test-data/document/drawing.docx and /dev/null differ diff --git a/test-data/document/empty.doc b/test-data/document/empty.doc deleted file mode 100644 index ceb841ce6..000000000 Binary files a/test-data/document/empty.doc and /dev/null differ diff --git a/test-data/document/endingnote.doc b/test-data/document/endingnote.doc deleted file mode 100644 index 92c6780d1..000000000 Binary files a/test-data/document/endingnote.doc and /dev/null differ diff --git a/test-data/document/endnotes.docx b/test-data/document/endnotes.docx deleted file mode 100644 index a5db3492c..000000000 Binary files a/test-data/document/endnotes.docx and /dev/null differ diff --git a/test-data/document/equation.doc b/test-data/document/equation.doc deleted file mode 100644 index e1bda06de..000000000 Binary files a/test-data/document/equation.doc and /dev/null differ diff --git a/test-data/document/footnote.doc b/test-data/document/footnote.doc deleted file mode 100644 index 5e11a4437..000000000 Binary files a/test-data/document/footnote.doc and /dev/null differ diff --git a/test-data/document/footnotes.docx b/test-data/document/footnotes.docx deleted file mode 100644 index db4386c09..000000000 Binary files a/test-data/document/footnotes.docx and /dev/null differ diff --git a/test-data/document/form_footnotes.docx b/test-data/document/form_footnotes.docx deleted file mode 100644 index 70abb60c9..000000000 Binary files a/test-data/document/form_footnotes.docx and /dev/null differ diff --git a/test-data/document/headerFooter.docx b/test-data/document/headerFooter.docx deleted file mode 100644 index 87a86c302..000000000 Binary files a/test-data/document/headerFooter.docx and /dev/null differ diff --git a/test-data/document/headerPic.docx b/test-data/document/headerPic.docx deleted file mode 100644 index 01072e547..000000000 Binary files a/test-data/document/headerPic.docx and /dev/null differ diff --git a/test-data/document/header_image.doc b/test-data/document/header_image.doc deleted file mode 100644 index 23444cdc1..000000000 Binary files a/test-data/document/header_image.doc and /dev/null differ diff --git a/test-data/document/heading123.docx b/test-data/document/heading123.docx deleted file mode 100644 index cf6118339..000000000 Binary files a/test-data/document/heading123.docx and /dev/null differ diff --git a/test-data/document/hyperlink.doc b/test-data/document/hyperlink.doc deleted file mode 100644 index 5e64b25b2..000000000 Binary files a/test-data/document/hyperlink.doc and /dev/null differ diff --git a/test-data/document/innertable.doc b/test-data/document/innertable.doc deleted file mode 100644 index e437a5fd1..000000000 Binary files a/test-data/document/innertable.doc and /dev/null differ diff --git a/test-data/document/issue_51265_1.docx b/test-data/document/issue_51265_1.docx deleted file mode 100644 index a18f6fb67..000000000 Binary files a/test-data/document/issue_51265_1.docx and /dev/null differ diff --git a/test-data/document/issue_51265_2.docx b/test-data/document/issue_51265_2.docx deleted file mode 100644 index b528d7d2b..000000000 Binary files a/test-data/document/issue_51265_2.docx and /dev/null differ diff --git a/test-data/document/issue_51265_3.docx b/test-data/document/issue_51265_3.docx deleted file mode 100644 index 721d9d4aa..000000000 Binary files a/test-data/document/issue_51265_3.docx and /dev/null differ diff --git a/test-data/document/lists-margins.doc b/test-data/document/lists-margins.doc deleted file mode 100644 index 348a926f0..000000000 Binary files a/test-data/document/lists-margins.doc and /dev/null differ diff --git a/test-data/document/nature1.gif b/test-data/document/nature1.gif deleted file mode 100644 index 838e05199..000000000 Binary files a/test-data/document/nature1.gif and /dev/null differ diff --git a/test-data/document/nature1.jpg b/test-data/document/nature1.jpg deleted file mode 100644 index e461fd91b..000000000 Binary files a/test-data/document/nature1.jpg and /dev/null differ diff --git a/test-data/document/nature1.png b/test-data/document/nature1.png deleted file mode 100644 index ba5b10ac5..000000000 Binary files a/test-data/document/nature1.png and /dev/null differ diff --git a/test-data/document/nature2.jpg b/test-data/document/nature2.jpg deleted file mode 100644 index 9fcbf4d2d..000000000 Binary files a/test-data/document/nature2.jpg and /dev/null differ diff --git a/test-data/document/nature3.jpg b/test-data/document/nature3.jpg deleted file mode 100644 index 034799830..000000000 Binary files a/test-data/document/nature3.jpg and /dev/null differ diff --git a/test-data/document/nature4.jpg b/test-data/document/nature4.jpg deleted file mode 100644 index 5d344cc9d..000000000 Binary files a/test-data/document/nature4.jpg and /dev/null differ diff --git a/test-data/document/o_kurs.doc b/test-data/document/o_kurs.doc deleted file mode 100644 index caab02ae9..000000000 Binary files a/test-data/document/o_kurs.doc and /dev/null differ diff --git a/test-data/document/ob_is.doc b/test-data/document/ob_is.doc deleted file mode 100644 index 798a09467..000000000 Binary files a/test-data/document/ob_is.doc and /dev/null differ diff --git a/test-data/document/page-break-before.doc b/test-data/document/page-break-before.doc deleted file mode 100644 index dddc5b5a3..000000000 Binary files a/test-data/document/page-break-before.doc and /dev/null differ diff --git a/test-data/document/page-break.doc b/test-data/document/page-break.doc deleted file mode 100644 index a54f2abb0..000000000 Binary files a/test-data/document/page-break.doc and /dev/null differ diff --git a/test-data/document/pageref.doc b/test-data/document/pageref.doc deleted file mode 100644 index c8a697727..000000000 Binary files a/test-data/document/pageref.doc and /dev/null differ diff --git a/test-data/document/parentinvguid.doc b/test-data/document/parentinvguid.doc deleted file mode 100644 index f27cf3ee6..000000000 Binary files a/test-data/document/parentinvguid.doc and /dev/null differ diff --git a/test-data/document/picture.doc b/test-data/document/picture.doc deleted file mode 100644 index c48038d6b..000000000 Binary files a/test-data/document/picture.doc and /dev/null differ diff --git a/test-data/document/pictures_escher.doc b/test-data/document/pictures_escher.doc deleted file mode 100644 index 4870bc7ab..000000000 Binary files a/test-data/document/pictures_escher.doc and /dev/null differ diff --git a/test-data/document/protected_sample.docx b/test-data/document/protected_sample.docx deleted file mode 100644 index e6b5e0bfc..000000000 Binary files a/test-data/document/protected_sample.docx and /dev/null differ diff --git a/test-data/document/rasp.doc b/test-data/document/rasp.doc deleted file mode 100644 index df39b696b..000000000 Binary files a/test-data/document/rasp.doc and /dev/null differ diff --git a/test-data/document/sample.docx b/test-data/document/sample.docx deleted file mode 100644 index 8dd04bcdb..000000000 Binary files a/test-data/document/sample.docx and /dev/null differ diff --git a/test-data/document/saved-by-table.doc b/test-data/document/saved-by-table.doc deleted file mode 100644 index c3ea6bc86..000000000 Binary files a/test-data/document/saved-by-table.doc and /dev/null differ diff --git a/test-data/document/simple-list.doc b/test-data/document/simple-list.doc deleted file mode 100644 index 75ed42e07..000000000 Binary files a/test-data/document/simple-list.doc and /dev/null differ diff --git a/test-data/document/simple-table.doc b/test-data/document/simple-table.doc deleted file mode 100644 index 6453e45b4..000000000 Binary files a/test-data/document/simple-table.doc and /dev/null differ diff --git a/test-data/document/simple-table2.doc b/test-data/document/simple-table2.doc deleted file mode 100644 index 1a5ff5f71..000000000 Binary files a/test-data/document/simple-table2.doc and /dev/null differ diff --git a/test-data/document/simple.doc b/test-data/document/simple.doc deleted file mode 100644 index ac0384ac2..000000000 Binary files a/test-data/document/simple.doc and /dev/null differ diff --git a/test-data/document/simple_image.jpg b/test-data/document/simple_image.jpg deleted file mode 100644 index af68bcabf..000000000 Binary files a/test-data/document/simple_image.jpg and /dev/null differ diff --git a/test-data/document/simple_image.png b/test-data/document/simple_image.png deleted file mode 100644 index a9120d70d..000000000 Binary files a/test-data/document/simple_image.png and /dev/null differ diff --git a/test-data/document/smarttag-snippet.docx b/test-data/document/smarttag-snippet.docx deleted file mode 100644 index 2c54f18d0..000000000 Binary files a/test-data/document/smarttag-snippet.docx and /dev/null differ diff --git a/test-data/document/table-merges.doc b/test-data/document/table-merges.doc deleted file mode 100644 index 77822acd1..000000000 Binary files a/test-data/document/table-merges.doc and /dev/null differ diff --git a/test-data/document/table_footnotes.docx b/test-data/document/table_footnotes.docx deleted file mode 100644 index f4d0b2bd0..000000000 Binary files a/test-data/document/table_footnotes.docx and /dev/null differ diff --git a/test-data/document/test-fields.doc b/test-data/document/test-fields.doc deleted file mode 100644 index 2a6c51642..000000000 Binary files a/test-data/document/test-fields.doc and /dev/null differ diff --git a/test-data/document/test.doc b/test-data/document/test.doc deleted file mode 100644 index c183d57dd..000000000 Binary files a/test-data/document/test.doc and /dev/null differ diff --git a/test-data/document/test.dotx b/test-data/document/test.dotx deleted file mode 100644 index 0b74e3932..000000000 Binary files a/test-data/document/test.dotx and /dev/null differ diff --git a/test-data/document/test2.doc b/test-data/document/test2.doc deleted file mode 100644 index 06921df39..000000000 Binary files a/test-data/document/test2.doc and /dev/null differ diff --git a/test-data/document/testCroppedPictures.doc b/test-data/document/testCroppedPictures.doc deleted file mode 100644 index 2f8b5622c..000000000 Binary files a/test-data/document/testCroppedPictures.doc and /dev/null differ diff --git a/test-data/document/testException2.doc-2.wmf b/test-data/document/testException2.doc-2.wmf deleted file mode 100644 index 914563bf2..000000000 Binary files a/test-data/document/testException2.doc-2.wmf and /dev/null differ diff --git a/test-data/document/testPictures.doc b/test-data/document/testPictures.doc deleted file mode 100644 index d031993cd..000000000 Binary files a/test-data/document/testPictures.doc and /dev/null differ diff --git a/test-data/document/testRangeDelete.doc b/test-data/document/testRangeDelete.doc deleted file mode 100644 index 896108397..000000000 Binary files a/test-data/document/testRangeDelete.doc and /dev/null differ diff --git a/test-data/document/testRangeInsertion.doc b/test-data/document/testRangeInsertion.doc deleted file mode 100644 index 322431c27..000000000 Binary files a/test-data/document/testRangeInsertion.doc and /dev/null differ diff --git a/test-data/document/testRangeReplacement.doc b/test-data/document/testRangeReplacement.doc deleted file mode 100644 index 949980d4e..000000000 Binary files a/test-data/document/testRangeReplacement.doc and /dev/null differ diff --git a/test-data/document/two_images.doc b/test-data/document/two_images.doc deleted file mode 100644 index f94867d22..000000000 Binary files a/test-data/document/two_images.doc and /dev/null differ diff --git a/test-data/document/vector_image.doc b/test-data/document/vector_image.doc deleted file mode 100644 index 892247188..000000000 Binary files a/test-data/document/vector_image.doc and /dev/null differ diff --git a/test-data/document/vector_image.emf b/test-data/document/vector_image.emf deleted file mode 100644 index ccd53057d..000000000 Binary files a/test-data/document/vector_image.emf and /dev/null differ diff --git a/test-data/document/watermark.doc b/test-data/document/watermark.doc deleted file mode 100644 index 7e9d5868f..000000000 Binary files a/test-data/document/watermark.doc and /dev/null differ diff --git a/test-data/document/word95err.doc b/test-data/document/word95err.doc deleted file mode 100644 index 7db961b63..000000000 Binary files a/test-data/document/word95err.doc and /dev/null differ diff --git a/test-data/document/word_with_embeded.doc b/test-data/document/word_with_embeded.doc deleted file mode 100644 index 36417221d..000000000 Binary files a/test-data/document/word_with_embeded.doc and /dev/null differ diff --git a/test-data/document/word_with_embeded_ooxml.doc b/test-data/document/word_with_embeded_ooxml.doc deleted file mode 100644 index f25cacf91..000000000 Binary files a/test-data/document/word_with_embeded_ooxml.doc and /dev/null differ diff --git a/test-data/document/zero-length.docx b/test-data/document/zero-length.docx deleted file mode 100644 index eb34b47b1..000000000 Binary files a/test-data/document/zero-length.docx and /dev/null differ diff --git a/test-data/hmef/bug52400-winmail-simple.dat b/test-data/hmef/bug52400-winmail-simple.dat deleted file mode 100644 index cb9f5f5c9..000000000 Binary files a/test-data/hmef/bug52400-winmail-simple.dat and /dev/null differ diff --git a/test-data/hmef/bug52400-winmail-with-attachments.dat b/test-data/hmef/bug52400-winmail-with-attachments.dat deleted file mode 100644 index 9f18a8a90..000000000 Binary files a/test-data/hmef/bug52400-winmail-with-attachments.dat and /dev/null differ diff --git a/test-data/hmef/quick-contents/message.rtf b/test-data/hmef/quick-contents/message.rtf deleted file mode 100644 index abbdc5433..000000000 --- a/test-data/hmef/quick-contents/message.rtf +++ /dev/null @@ -1,6 +0,0 @@ -{\rtf1\adeflang1025\ansi\ansicpg1252\uc1\adeff31507\deff0\stshfdbch31506\stshfloch31506\stshfhich31506\stshfbi31507\deflang2057\deflangfe2057\themelang2057\themelangfe0\themelangcs0{\fonttbl{\f0\fbidi \froman\fcharset0\fprq2{\*\panose 02020603050405020304}Times New Roman;}{\f34\fbidi \froman\fcharset1\fprq2{\*\panose 02040503050406030204}Cambria Math;}{\f37\fbidi \fswiss\fcharset0\fprq2{\*\panose 020f0502020204030204}Calibri;}{\f31500\fbidi \froman\fcharset0\fprq2{\*\panose 02020603050405020304}Times New Roman;}{\f31501\fbidi \froman\fcharset0\fprq2{\*\panose 02020603050405020304}Times New Roman;}{\f31502\fbidi \froman\fcharset0\fprq2{\*\panose 02040503050406030204}Cambria;}{\f31503\fbidi \froman\fcharset0\fprq2{\*\panose 02020603050405020304}Times New Roman;}{\f31504\fbidi \froman\fcharset0\fprq2{\*\panose 02020603050405020304}Times New Roman;}{\f31505\fbidi \froman\fcharset0\fprq2{\*\panose 02020603050405020304}Times New Roman;}{\f31506\fbidi \fswiss\fcharset0\fprq2{\*\panose 020f0502020204030204}Calibri;}{\f31507\fbidi \froman\fcharset0\fprq2{\*\panose 02020603050405020304}Times New Roman;}{\f41\fbidi \froman\fcharset238\fprq2 Times New Roman CE;}{\f42\fbidi \froman\fcharset204\fprq2 Times New Roman Cyr;}{\f44\fbidi \froman\fcharset161\fprq2 Times New Roman Greek;}{\f45\fbidi \froman\fcharset162\fprq2 Times New Roman Tur;}{\f46\fbidi \froman\fcharset177\fprq2 Times New Roman (Hebrew);}{\f47\fbidi \froman\fcharset178\fprq2 Times New Roman (Arabic);}{\f48\fbidi \froman\fcharset186\fprq2 Times New Roman Baltic;}{\f49\fbidi \froman\fcharset163\fprq2 Times New Roman (Vietnamese);}{\f411\fbidi \fswiss\fcharset238\fprq2 Calibri CE;}{\f412\fbidi \fswiss\fcharset204\fprq2 Calibri Cyr;}{\f414\fbidi \fswiss\fcharset161\fprq2 Calibri Greek;}{\f415\fbidi \fswiss\fcharset162\fprq2 Calibri Tur;}{\f418\fbidi \fswiss\fcharset186\fprq2 Calibri Baltic;}{\f419\fbidi \fswiss\fcharset163\fprq2 Calibri (Vietnamese);}{\f31508\fbidi \froman\fcharset238\fprq2 Times New Roman CE;}{\f31509\fbidi \froman\fcharset204\fprq2 Times New Roman Cyr;}{\f31511\fbidi \froman\fcharset161\fprq2 Times New Roman Greek;}{\f31512\fbidi \froman\fcharset162\fprq2 Times New Roman Tur;}{\f31513\fbidi \froman\fcharset177\fprq2 Times New Roman (Hebrew);}{\f31514\fbidi \froman\fcharset178\fprq2 Times New Roman (Arabic);}{\f31515\fbidi \froman\fcharset186\fprq2 Times New Roman Baltic;}{\f31516\fbidi \froman\fcharset163\fprq2 Times New Roman (Vietnamese);}{\f31518\fbidi \froman\fcharset238\fprq2 Times New Roman CE;}{\f31519\fbidi \froman\fcharset204\fprq2 Times New Roman Cyr;}{\f31521\fbidi \froman\fcharset161\fprq2 Times New Roman Greek;}{\f31522\fbidi \froman\fcharset162\fprq2 Times New Roman Tur;}{\f31523\fbidi \froman\fcharset177\fprq2 Times New Roman (Hebrew);}{\f31524\fbidi \froman\fcharset178\fprq2 Times New Roman (Arabic);}{\f31525\fbidi \froman\fcharset186\fprq2 Times New Roman Baltic;}{\f31526\fbidi \froman\fcharset163\fprq2 Times New Roman (Vietnamese);}{\f31528\fbidi \froman\fcharset238\fprq2 Cambria CE;}{\f31529\fbidi \froman\fcharset204\fprq2 Cambria Cyr;}{\f31531\fbidi \froman\fcharset161\fprq2 Cambria Greek;}{\f31532\fbidi \froman\fcharset162\fprq2 Cambria Tur;}{\f31535\fbidi \froman\fcharset186\fprq2 Cambria Baltic;}{\f31536\fbidi \froman\fcharset163\fprq2 Cambria (Vietnamese);}{\f31538\fbidi \froman\fcharset238\fprq2 Times New Roman CE;}{\f31539\fbidi \froman\fcharset204\fprq2 Times New Roman Cyr;}{\f31541\fbidi \froman\fcharset161\fprq2 Times New Roman Greek;}{\f31542\fbidi \froman\fcharset162\fprq2 Times New Roman Tur;}{\f31543\fbidi \froman\fcharset177\fprq2 Times New Roman (Hebrew);}{\f31544\fbidi \froman\fcharset178\fprq2 Times New Roman (Arabic);}{\f31545\fbidi \froman\fcharset186\fprq2 Times New Roman Baltic;}{\f31546\fbidi \froman\fcharset163\fprq2 Times New Roman (Vietnamese);}{\f31548\fbidi \froman\fcharset238\fprq2 Times New Roman CE;}{\f31549\fbidi \froman\fcharset204\fprq2 Times New Roman Cyr;}{\f31551\fbidi \froman\fcharset161\fprq2 Times New Roman Greek;}{\f31552\fbidi \froman\fcharset162\fprq2 Times New Roman Tur;}{\f31553\fbidi \froman\fcharset177\fprq2 Times New Roman (Hebrew);}{\f31554\fbidi \froman\fcharset178\fprq2 Times New Roman (Arabic);}{\f31555\fbidi \froman\fcharset186\fprq2 Times New Roman Baltic;}{\f31556\fbidi \froman\fcharset163\fprq2 Times New Roman (Vietnamese);}{\f31558\fbidi \froman\fcharset238\fprq2 Times New Roman CE;}{\f31559\fbidi \froman\fcharset204\fprq2 Times New Roman Cyr;}{\f31561\fbidi \froman\fcharset161\fprq2 Times New Roman Greek;}{\f31562\fbidi \froman\fcharset162\fprq2 Times New Roman Tur;}{\f31563\fbidi \froman\fcharset177\fprq2 Times New Roman (Hebrew);}{\f31564\fbidi \froman\fcharset178\fprq2 Times New Roman (Arabic);}{\f31565\fbidi \froman\fcharset186\fprq2 Times New Roman Baltic;}{\f31566\fbidi \froman\fcharset163\fprq2 Times New Roman (Vietnamese);}{\f31568\fbidi \fswiss\fcharset238\fprq2 Calibri CE;}{\f31569\fbidi \fswiss\fcharset204\fprq2 Calibri Cyr;}{\f31571\fbidi \fswiss\fcharset161\fprq2 Calibri Greek;}{\f31572\fbidi \fswiss\fcharset162\fprq2 Calibri Tur;}{\f31575\fbidi \fswiss\fcharset186\fprq2 Calibri Baltic;}{\f31576\fbidi \fswiss\fcharset163\fprq2 Calibri (Vietnamese);}{\f31578\fbidi \froman\fcharset238\fprq2 Times New Roman CE;}{\f31579\fbidi \froman\fcharset204\fprq2 Times New Roman Cyr;}{\f31581\fbidi \froman\fcharset161\fprq2 Times New Roman Greek;}{\f31582\fbidi \froman\fcharset162\fprq2 Times New Roman Tur;}{\f31583\fbidi \froman\fcharset177\fprq2 Times New Roman (Hebrew);}{\f31584\fbidi \froman\fcharset178\fprq2 Times New Roman (Arabic);}{\f31585\fbidi \froman\fcharset186\fprq2 Times New Roman Baltic;}{\f31586\fbidi \froman\fcharset163\fprq2 Times New Roman (Vietnamese);}}{\colortbl;\red0\green0\blue0;\red0\green0\blue255;\red0\green255\blue255;\red0\green255\blue0;\red255\green0\blue255;\red255\green0\blue0;\red255\green255\blue0;\red255\green255\blue255;\red0\green0\blue128;\red0\green128\blue128;\red0\green128\blue0;\red128\green0\blue128;\red128\green0\blue0;\red128\green128\blue0;\red128\green128\blue128;\red192\green192\blue192;\red0\green0\blue255;\red128\green0\blue128;}{\*\defchp \f31506\fs22\lang2057\langfe1033\langfenp1033 }{\*\defpap \ql \li0\ri0\widctlpar\wrapdefault\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0 }\noqfpromote {\stylesheet{\ql \li0\ri0\widctlpar\wrapdefault\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0 \rtlch\fcs1 \af31507\afs22\alang1025 \ltrch\fcs0 \f31506\fs22\lang2057\langfe1033\cgrid\langnp2057\langfenp1033 \snext0 \sqformat \spriority0 \styrsid6847920 Normal;}{\*\cs10 \additive \ssemihidden \sunhideused \spriority1 Default Paragraph Font;}{\*\ts11\tsrowd\trftsWidthB3\trpaddl108\trpaddr108\trpaddfl3\trpaddft3\trpaddfb3\trpaddfr3\tblind0\tblindtype3\tscellwidthfts0\tsvertalt\tsbrdrt\tsbrdrl\tsbrdrb\tsbrdrr\tsbrdrdgl\tsbrdrdgr\tsbrdrh\tsbrdrv \ql \li0\ri0\widctlpar\wrapdefault\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0 \rtlch\fcs1 \af31507\afs22\alang1025 \ltrch\fcs0 \f31506\fs22\lang2057\langfe1033\cgrid\langnp2057\langfenp1033 \snext11 \ssemihidden \sunhideused \sqformat Normal Table;}{\*\cs15 \additive \rtlch\fcs1 \af0 \ltrch\fcs0 \ul\cf17 \sbasedon10 \ssemihidden \sunhideused \styrsid8740586 Hyperlink;}{\*\cs16 \additive \rtlch\fcs1 \af0 \ltrch\fcs0 \ul\cf18 \sbasedon10 \ssemihidden \sunhideused \styrsid8740586 FollowedHyperlink;}{\*\cs17 \additive \rtlch\fcs1 \af31507\afs22 \ltrch\fcs0 \f31506\fs22\cf0 \sbasedon10 \ssemihidden \spriority0 \spersonal \scompose \styrsid8740586 EmailStyle17;}}{\*\revtbl {Unknown;}}{\*\rsidtbl \rsid6847920\rsid8740586}{\mmathPr\mmathFont34\mbrkBin0\mbrkBinSub0\msmallFrac0\mdispDef1\mlMargin0\mrMargin0\mdefJc1\mwrapIndent1440\mintLim0\mnaryLim1}{\*\xmlnstbl {\xmlns1 http://schemas.microsoft.com/office/word/2003/wordml}}\paperw12240\paperh15840\margl1440\margr1440\margt1440\margb1440\gutter0\ltrsect \widowctrl\ftnbj\aenddoc\trackmoves1\trackformatting1\donotembedsysfont1\relyonvml0\donotembedlingdata0\grfdocevents0\validatexml1\showplaceholdtext0\ignoremixedcontent0\saveinvalidxml0\showxmlerrors1\noxlattoyen\expshrtn\noultrlspc\dntblnsbdb\nospaceforul\formshade\horzdoc\dgmargin\dghspace180\dgvspace180\dghorigin150\dgvorigin0\dghshow1\dgvshow1\jexpand\viewkind5\viewscale100\pgbrdrhead\pgbrdrfoot\splytwnine\ftnlytwnine\htmautsp\nolnhtadjtbl\useltbaln\alntblind\lytcalctblwd\lyttblrtgr\lnbrkrule\nobrkwrptbl\snaptogridincell\allowfieldendsel\wrppunct\asianbrkrule\newtblstyruls\nogrowautofit\usenormstyforlist\noindnmbrts\felnbrelev\nocxsptable\indrlsweleven\noafcnsttbl\afelev\utinl\hwelev\spltpgpar\notcvasp\notbrkcnstfrctbl\notvatxbx\krnprsnet\cachedcolbal \nouicompat \fet0{\*\wgrffmtfilter 2450}\nofeaturethrottle1\ilfomacatclnup0\ltrpar \sectd \ltrsect\linex0\endnhere\sectdefaultcl\sftnbj {\*\pnseclvl1\pnucrm\pnstart1\pnindent720\pnhang {\pntxta .}}{\*\pnseclvl2\pnucltr\pnstart1\pnindent720\pnhang {\pntxta .}}{\*\pnseclvl3\pndec\pnstart1\pnindent720\pnhang {\pntxta .}}{\*\pnseclvl4\pnlcltr\pnstart1\pnindent720\pnhang {\pntxta )}}{\*\pnseclvl5\pndec\pnstart1\pnindent720\pnhang {\pntxtb (}{\pntxta )}}{\*\pnseclvl6\pnlcltr\pnstart1\pnindent720\pnhang {\pntxtb (}{\pntxta )}}{\*\pnseclvl7\pnlcrm\pnstart1\pnindent720\pnhang {\pntxtb (}{\pntxta )}}{\*\pnseclvl8\pnlcltr\pnstart1\pnindent720\pnhang {\pntxtb (}{\pntxta )}}{\*\pnseclvl9\pnlcrm\pnstart1\pnindent720\pnhang {\pntxtb (}{\pntxta )}}\pard\plain \ltrpar\ql \li0\ri0\widctlpar\wrapdefault\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0\pararsid8740586 \rtlch\fcs1 \af31507\afs22\alang1025 \ltrch\fcs0 \f31506\fs22\lang2057\langfe1033\cgrid\langnp2057\langfenp1033 {\rtlch\fcs1 \af31507 \ltrch\fcs0 \b\cf0\insrsid8740586\charrsid8740586 These are five files. -\par }{\rtlch\fcs1 \af31507 \ltrch\fcs0 \cf0\insrsid8740586 -\par -\par }{\pard\plain \ltrpar\ql \li0\ri0\widctlpar\wrapdefault\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0\pararsid8740586 \rtlch\fcs1 \af31507\afs22\alang1025 \ltrch\fcs0 \f31506\fs22\lang2057\langfe1033\cgrid\langnp2057\langfenp1033\insrsid8740586 {{\objattph {\rtlch\fcs1 \af31507 \ltrch\fcs0 \cf0\insrsid8740586 }}}}\sectd \ltrsect\linex0\endnhere\sectdefaultcl\sftnbj {\pard\plain \ltrpar\ql \li0\ri0\widctlpar\wrapdefault\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0\pararsid8740586 \rtlch\fcs1 \af31507\afs22\alang1025 \ltrch\fcs0 \f31506\fs22\lang2057\langfe1033\cgrid\langnp2057\langfenp1033\insrsid8740586 {{\objattph {\rtlch\fcs1 \af31507 \ltrch\fcs0 \cf0\insrsid8740586 }}}}\sectd \ltrsect\linex0\endnhere\sectdefaultcl\sftnbj {\pard\plain \ltrpar\ql \li0\ri0\widctlpar\wrapdefault\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0\pararsid8740586 \rtlch\fcs1 \af31507\afs22\alang1025 \ltrch\fcs0 \f31506\fs22\lang2057\langfe1033\cgrid\langnp2057\langfenp1033\insrsid8740586 {{\objattph {\rtlch\fcs1 \af31507 \ltrch\fcs0 \cf0\insrsid8740586 }}}}\sectd \ltrsect\linex0\endnhere\sectdefaultcl\sftnbj {\rtlch\fcs1 \af31507 \ltrch\fcs0 \cf0\insrsid8740586 -\par Five files from }{\rtlch\fcs1 \af31507 \ltrch\fcs0 \cf6\insrsid8740586\charrsid8740586 Hell}{\rtlch\fcs1 \af31507 \ltrch\fcs0 \cf0\insrsid8740586 !}{\rtlch\fcs1 \af31507 \ltrch\fcs0 \cf0\insrsid8740586 (Well Outlook actually)}{\pard\plain \ltrpar\ql \li0\ri0\widctlpar\wrapdefault\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0\pararsid8740586 \rtlch\fcs1 \af31507\afs22\alang1025 \ltrch\fcs0 \f31506\fs22\lang2057\langfe1033\cgrid\langnp2057\langfenp1033\insrsid8740586 {{\objattph {\rtlch\fcs1 \af31507 \ltrch\fcs0 \cf0\insrsid8740586 }}}}\sectd \ltrsect\linex0\endnhere\sectdefaultcl\sftnbj {\pard\plain \ltrpar\ql \li0\ri0\widctlpar\wrapdefault\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0\pararsid8740586 \rtlch\fcs1 \af31507\afs22\alang1025 \ltrch\fcs0 \f31506\fs22\lang2057\langfe1033\cgrid\langnp2057\langfenp1033\insrsid8740586 {{\objattph {\rtlch\fcs1 \af31507 \ltrch\fcs0 \cf0\insrsid8740586 }}}}\sectd \ltrsect\linex0\endnhere\sectdefaultcl\sftnbj {\rtlch\fcs1 \af31507 \ltrch\fcs0 \cf0\insrsid8740586\charrsid8740586 -\par }{\*\latentstyles\lsdstimax267\lsdlockeddef0\lsdsemihiddendef1\lsdunhideuseddef1\lsdqformatdef0\lsdprioritydef99{\lsdlockedexcept \lsdsemihidden0 \lsdunhideused0 \lsdqformat1 \lsdpriority0 \lsdlocked0 Normal;\lsdsemihidden0 \lsdunhideused0 \lsdqformat1 \lsdpriority9 \lsdlocked0 heading 1;\lsdqformat1 \lsdpriority9 \lsdlocked0 heading 2;\lsdqformat1 \lsdpriority9 \lsdlocked0 heading 3;\lsdqformat1 \lsdpriority9 \lsdlocked0 heading 4;\lsdqformat1 \lsdpriority9 \lsdlocked0 heading 5;\lsdqformat1 \lsdpriority9 \lsdlocked0 heading 6;\lsdqformat1 \lsdpriority9 \lsdlocked0 heading 7;\lsdqformat1 \lsdpriority9 \lsdlocked0 heading 8;\lsdqformat1 \lsdpriority9 \lsdlocked0 heading 9;\lsdpriority39 \lsdlocked0 toc 1;\lsdpriority39 \lsdlocked0 toc 2;\lsdpriority39 \lsdlocked0 toc 3;\lsdpriority39 \lsdlocked0 toc 4;\lsdpriority39 \lsdlocked0 toc 5;\lsdpriority39 \lsdlocked0 toc 6;\lsdpriority39 \lsdlocked0 toc 7;\lsdpriority39 \lsdlocked0 toc 8;\lsdpriority39 \lsdlocked0 toc 9;\lsdqformat1 \lsdpriority35 \lsdlocked0 caption;\lsdsemihidden0 \lsdunhideused0 \lsdqformat1 \lsdpriority10 \lsdlocked0 Title;\lsdpriority1 \lsdlocked0 Default Paragraph Font;\lsdsemihidden0 \lsdunhideused0 \lsdqformat1 \lsdpriority11 \lsdlocked0 Subtitle;\lsdsemihidden0 \lsdunhideused0 \lsdqformat1 \lsdpriority22 \lsdlocked0 Strong;\lsdsemihidden0 \lsdunhideused0 \lsdqformat1 \lsdpriority20 \lsdlocked0 Emphasis;\lsdsemihidden0 \lsdunhideused0 \lsdpriority59 \lsdlocked0 Table Grid;\lsdunhideused0 \lsdlocked0 Placeholder Text;\lsdsemihidden0 \lsdunhideused0 \lsdqformat1 \lsdpriority1 \lsdlocked0 No Spacing;\lsdsemihidden0 \lsdunhideused0 \lsdpriority60 \lsdlocked0 Light Shading;\lsdsemihidden0 \lsdunhideused0 \lsdpriority61 \lsdlocked0 Light List;\lsdsemihidden0 \lsdunhideused0 \lsdpriority62 \lsdlocked0 Light Grid;\lsdsemihidden0 \lsdunhideused0 \lsdpriority63 \lsdlocked0 Medium Shading 1;\lsdsemihidden0 \lsdunhideused0 \lsdpriority64 \lsdlocked0 Medium Shading 2;\lsdsemihidden0 \lsdunhideused0 \lsdpriority65 \lsdlocked0 Medium List 1;\lsdsemihidden0 \lsdunhideused0 \lsdpriority66 \lsdlocked0 Medium List 2;\lsdsemihidden0 \lsdunhideused0 \lsdpriority67 \lsdlocked0 Medium Grid 1;\lsdsemihidden0 \lsdunhideused0 \lsdpriority68 \lsdlocked0 Medium Grid 2;\lsdsemihidden0 \lsdunhideused0 \lsdpriority69 \lsdlocked0 Medium Grid 3;\lsdsemihidden0 \lsdunhideused0 \lsdpriority70 \lsdlocked0 Dark List;\lsdsemihidden0 \lsdunhideused0 \lsdpriority71 \lsdlocked0 Colorful Shading;\lsdsemihidden0 \lsdunhideused0 \lsdpriority72 \lsdlocked0 Colorful List;\lsdsemihidden0 \lsdunhideused0 \lsdpriority73 \lsdlocked0 Colorful Grid;\lsdsemihidden0 \lsdunhideused0 \lsdpriority60 \lsdlocked0 Light Shading Accent 1;\lsdsemihidden0 \lsdunhideused0 \lsdpriority61 \lsdlocked0 Light List Accent 1;\lsdsemihidden0 \lsdunhideused0 \lsdpriority62 \lsdlocked0 Light Grid Accent 1;\lsdsemihidden0 \lsdunhideused0 \lsdpriority63 \lsdlocked0 Medium Shading 1 Accent 1;\lsdsemihidden0 \lsdunhideused0 \lsdpriority64 \lsdlocked0 Medium Shading 2 Accent 1;\lsdsemihidden0 \lsdunhideused0 \lsdpriority65 \lsdlocked0 Medium List 1 Accent 1;\lsdunhideused0 \lsdlocked0 Revision;\lsdsemihidden0 \lsdunhideused0 \lsdqformat1 \lsdpriority34 \lsdlocked0 List Paragraph;\lsdsemihidden0 \lsdunhideused0 \lsdqformat1 \lsdpriority29 \lsdlocked0 Quote;\lsdsemihidden0 \lsdunhideused0 \lsdqformat1 \lsdpriority30 \lsdlocked0 Intense Quote;\lsdsemihidden0 \lsdunhideused0 \lsdpriority66 \lsdlocked0 Medium List 2 Accent 1;\lsdsemihidden0 \lsdunhideused0 \lsdpriority67 \lsdlocked0 Medium Grid 1 Accent 1;\lsdsemihidden0 \lsdunhideused0 \lsdpriority68 \lsdlocked0 Medium Grid 2 Accent 1;\lsdsemihidden0 \lsdunhideused0 \lsdpriority69 \lsdlocked0 Medium Grid 3 Accent 1;\lsdsemihidden0 \lsdunhideused0 \lsdpriority70 \lsdlocked0 Dark List Accent 1;\lsdsemihidden0 \lsdunhideused0 \lsdpriority71 \lsdlocked0 Colorful Shading Accent 1;\lsdsemihidden0 \lsdunhideused0 \lsdpriority72 \lsdlocked0 Colorful List Accent 1;\lsdsemihidden0 \lsdunhideused0 \lsdpriority73 \lsdlocked0 Colorful Grid Accent 1;\lsdsemihidden0 \lsdunhideused0 \lsdpriority60 \lsdlocked0 Light Shading Accent 2;\lsdsemihidden0 \lsdunhideused0 \lsdpriority61 \lsdlocked0 Light List Accent 2;\lsdsemihidden0 \lsdunhideused0 \lsdpriority62 \lsdlocked0 Light Grid Accent 2;\lsdsemihidden0 \lsdunhideused0 \lsdpriority63 \lsdlocked0 Medium Shading 1 Accent 2;\lsdsemihidden0 \lsdunhideused0 \lsdpriority64 \lsdlocked0 Medium Shading 2 Accent 2;\lsdsemihidden0 \lsdunhideused0 \lsdpriority65 \lsdlocked0 Medium List 1 Accent 2;\lsdsemihidden0 \lsdunhideused0 \lsdpriority66 \lsdlocked0 Medium List 2 Accent 2;\lsdsemihidden0 \lsdunhideused0 \lsdpriority67 \lsdlocked0 Medium Grid 1 Accent 2;\lsdsemihidden0 \lsdunhideused0 \lsdpriority68 \lsdlocked0 Medium Grid 2 Accent 2;\lsdsemihidden0 \lsdunhideused0 \lsdpriority69 \lsdlocked0 Medium Grid 3 Accent 2;\lsdsemihidden0 \lsdunhideused0 \lsdpriority70 \lsdlocked0 Dark List Accent 2;\lsdsemihidden0 \lsdunhideused0 \lsdpriority71 \lsdlocked0 Colorful Shading Accent 2;\lsdsemihidden0 \lsdunhideused0 \lsdpriority72 \lsdlocked0 Colorful List Accent 2;\lsdsemihidden0 \lsdunhideused0 \lsdpriority73 \lsdlocked0 Colorful Grid Accent 2;\lsdsemihidden0 \lsdunhideused0 \lsdpriority60 \lsdlocked0 Light Shading Accent 3;\lsdsemihidden0 \lsdunhideused0 \lsdpriority61 \lsdlocked0 Light List Accent 3;\lsdsemihidden0 \lsdunhideused0 \lsdpriority62 \lsdlocked0 Light Grid Accent 3;\lsdsemihidden0 \lsdunhideused0 \lsdpriority63 \lsdlocked0 Medium Shading 1 Accent 3;\lsdsemihidden0 \lsdunhideused0 \lsdpriority64 \lsdlocked0 Medium Shading 2 Accent 3;\lsdsemihidden0 \lsdunhideused0 \lsdpriority65 \lsdlocked0 Medium List 1 Accent 3;\lsdsemihidden0 \lsdunhideused0 \lsdpriority66 \lsdlocked0 Medium List 2 Accent 3;\lsdsemihidden0 \lsdunhideused0 \lsdpriority67 \lsdlocked0 Medium Grid 1 Accent 3;\lsdsemihidden0 \lsdunhideused0 \lsdpriority68 \lsdlocked0 Medium Grid 2 Accent 3;\lsdsemihidden0 \lsdunhideused0 \lsdpriority69 \lsdlocked0 Medium Grid 3 Accent 3;\lsdsemihidden0 \lsdunhideused0 \lsdpriority70 \lsdlocked0 Dark List Accent 3;\lsdsemihidden0 \lsdunhideused0 \lsdpriority71 \lsdlocked0 Colorful Shading Accent 3;\lsdsemihidden0 \lsdunhideused0 \lsdpriority72 \lsdlocked0 Colorful List Accent 3;\lsdsemihidden0 \lsdunhideused0 \lsdpriority73 \lsdlocked0 Colorful Grid Accent 3;\lsdsemihidden0 \lsdunhideused0 \lsdpriority60 \lsdlocked0 Light Shading Accent 4;\lsdsemihidden0 \lsdunhideused0 \lsdpriority61 \lsdlocked0 Light List Accent 4;\lsdsemihidden0 \lsdunhideused0 \lsdpriority62 \lsdlocked0 Light Grid Accent 4;\lsdsemihidden0 \lsdunhideused0 \lsdpriority63 \lsdlocked0 Medium Shading 1 Accent 4;\lsdsemihidden0 \lsdunhideused0 \lsdpriority64 \lsdlocked0 Medium Shading 2 Accent 4;\lsdsemihidden0 \lsdunhideused0 \lsdpriority65 \lsdlocked0 Medium List 1 Accent 4;\lsdsemihidden0 \lsdunhideused0 \lsdpriority66 \lsdlocked0 Medium List 2 Accent 4;\lsdsemihidden0 \lsdunhideused0 \lsdpriority67 \lsdlocked0 Medium Grid 1 Accent 4;\lsdsemihidden0 \lsdunhideused0 \lsdpriority68 \lsdlocked0 Medium Grid 2 Accent 4;\lsdsemihidden0 \lsdunhideused0 \lsdpriority69 \lsdlocked0 Medium Grid 3 Accent 4;\lsdsemihidden0 \lsdunhideused0 \lsdpriority70 \lsdlocked0 Dark List Accent 4;\lsdsemihidden0 \lsdunhideused0 \lsdpriority71 \lsdlocked0 Colorful Shading Accent 4;\lsdsemihidden0 \lsdunhideused0 \lsdpriority72 \lsdlocked0 Colorful List Accent 4;\lsdsemihidden0 \lsdunhideused0 \lsdpriority73 \lsdlocked0 Colorful Grid Accent 4;\lsdsemihidden0 \lsdunhideused0 \lsdpriority60 \lsdlocked0 Light Shading Accent 5;\lsdsemihidden0 \lsdunhideused0 \lsdpriority61 \lsdlocked0 Light List Accent 5;\lsdsemihidden0 \lsdunhideused0 \lsdpriority62 \lsdlocked0 Light Grid Accent 5;\lsdsemihidden0 \lsdunhideused0 \lsdpriority63 \lsdlocked0 Medium Shading 1 Accent 5;\lsdsemihidden0 \lsdunhideused0 \lsdpriority64 \lsdlocked0 Medium Shading 2 Accent 5;\lsdsemihidden0 \lsdunhideused0 \lsdpriority65 \lsdlocked0 Medium List 1 Accent 5;\lsdsemihidden0 \lsdunhideused0 \lsdpriority66 \lsdlocked0 Medium List 2 Accent 5;\lsdsemihidden0 \lsdunhideused0 \lsdpriority67 \lsdlocked0 Medium Grid 1 Accent 5;\lsdsemihidden0 \lsdunhideused0 \lsdpriority68 \lsdlocked0 Medium Grid 2 Accent 5;\lsdsemihidden0 \lsdunhideused0 \lsdpriority69 \lsdlocked0 Medium Grid 3 Accent 5;\lsdsemihidden0 \lsdunhideused0 \lsdpriority70 \lsdlocked0 Dark List Accent 5;\lsdsemihidden0 \lsdunhideused0 \lsdpriority71 \lsdlocked0 Colorful Shading Accent 5;\lsdsemihidden0 \lsdunhideused0 \lsdpriority72 \lsdlocked0 Colorful List Accent 5;\lsdsemihidden0 \lsdunhideused0 \lsdpriority73 \lsdlocked0 Colorful Grid Accent 5;\lsdsemihidden0 \lsdunhideused0 \lsdpriority60 \lsdlocked0 Light Shading Accent 6;\lsdsemihidden0 \lsdunhideused0 \lsdpriority61 \lsdlocked0 Light List Accent 6;\lsdsemihidden0 \lsdunhideused0 \lsdpriority62 \lsdlocked0 Light Grid Accent 6;\lsdsemihidden0 \lsdunhideused0 \lsdpriority63 \lsdlocked0 Medium Shading 1 Accent 6;\lsdsemihidden0 \lsdunhideused0 \lsdpriority64 \lsdlocked0 Medium Shading 2 Accent 6;\lsdsemihidden0 \lsdunhideused0 \lsdpriority65 \lsdlocked0 Medium List 1 Accent 6;\lsdsemihidden0 \lsdunhideused0 \lsdpriority66 \lsdlocked0 Medium List 2 Accent 6;\lsdsemihidden0 \lsdunhideused0 \lsdpriority67 \lsdlocked0 Medium Grid 1 Accent 6;\lsdsemihidden0 \lsdunhideused0 \lsdpriority68 \lsdlocked0 Medium Grid 2 Accent 6;\lsdsemihidden0 \lsdunhideused0 \lsdpriority69 \lsdlocked0 Medium Grid 3 Accent 6;\lsdsemihidden0 \lsdunhideused0 \lsdpriority70 \lsdlocked0 Dark List Accent 6;\lsdsemihidden0 \lsdunhideused0 \lsdpriority71 \lsdlocked0 Colorful Shading Accent 6;\lsdsemihidden0 \lsdunhideused0 \lsdpriority72 \lsdlocked0 Colorful List Accent 6;\lsdsemihidden0 \lsdunhideused0 \lsdpriority73 \lsdlocked0 Colorful Grid Accent 6;\lsdsemihidden0 \lsdunhideused0 \lsdqformat1 \lsdpriority19 \lsdlocked0 Subtle Emphasis;\lsdsemihidden0 \lsdunhideused0 \lsdqformat1 \lsdpriority21 \lsdlocked0 Intense Emphasis;\lsdsemihidden0 \lsdunhideused0 \lsdqformat1 \lsdpriority31 \lsdlocked0 Subtle Reference;\lsdsemihidden0 \lsdunhideused0 \lsdqformat1 \lsdpriority32 \lsdlocked0 Intense Reference;\lsdsemihidden0 \lsdunhideused0 \lsdqformat1 \lsdpriority33 \lsdlocked0 Book Title;\lsdpriority37 \lsdlocked0 Bibliography;\lsdqformat1 \lsdpriority39 \lsdlocked0 TOC Heading;}}{\*\datastore 0105000002000000180000004d73786d6c322e534158584d4c5265616465722e352e3000000000000000000000060000d0cf11e0a1b11ae1000000000000000000000000000000003e000300feff090006000000000000000000000001000000010000000000000000100000feffffff00000000feffffff0000000000000000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffdfffffffeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff52006f006f007400200045006e00740072007900000000000000000000000000000000000000000000000000000000000000000000000000000000000000000016000500ffffffffffffffffffffffffec69d9888b8b3d4c859eaf6cd158be0f000000000000000000000000700a60dc669ccb01feffffff00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ffffffffffffffffffffffff0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ffffffffffffffffffffffff0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ffffffffffffffffffffffff0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000105000000000000}} \ No newline at end of file diff --git a/test-data/hmef/quick-contents/quick.doc b/test-data/hmef/quick-contents/quick.doc deleted file mode 100644 index eb307fb21..000000000 Binary files a/test-data/hmef/quick-contents/quick.doc and /dev/null differ diff --git a/test-data/hmef/quick-contents/quick.html b/test-data/hmef/quick-contents/quick.html deleted file mode 100644 index 76c633d74..000000000 --- a/test-data/hmef/quick-contents/quick.html +++ /dev/null @@ -1,17 +0,0 @@ - - - - - The quick brown fox jumps over the lazy dog - - - - - - - -The quick brown fox jumps over the lazy dog - - - - diff --git a/test-data/hmef/quick-contents/quick.pdf b/test-data/hmef/quick-contents/quick.pdf deleted file mode 100644 index f7a1883f0..000000000 Binary files a/test-data/hmef/quick-contents/quick.pdf and /dev/null differ diff --git a/test-data/hmef/quick-contents/quick.txt b/test-data/hmef/quick-contents/quick.txt deleted file mode 100644 index f89201fc8..000000000 --- a/test-data/hmef/quick-contents/quick.txt +++ /dev/null @@ -1,7 +0,0 @@ -The quick brown fox jumps over the lazy dog - -Le renard brun rapide saute par-dessus le chien paresseux - -Der schnelle braune Fuchs springt über den faulen Hund - -براون وكس السريع يقفز فوق الكلب كسالي \ No newline at end of file diff --git a/test-data/hmef/quick-contents/quick.xml b/test-data/hmef/quick-contents/quick.xml deleted file mode 100644 index 3c9c602a9..000000000 --- a/test-data/hmef/quick-contents/quick.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - The quick brown fox jumps over the lazy dog - \ No newline at end of file diff --git a/test-data/hmef/quick-winmail.dat b/test-data/hmef/quick-winmail.dat deleted file mode 100644 index 4cdaa368b..000000000 Binary files a/test-data/hmef/quick-winmail.dat and /dev/null differ diff --git a/test-data/hmef/winmail-sample1.dat b/test-data/hmef/winmail-sample1.dat deleted file mode 100644 index b9f629502..000000000 Binary files a/test-data/hmef/winmail-sample1.dat and /dev/null differ diff --git a/test-data/hpsf/Test0313rur.adm b/test-data/hpsf/Test0313rur.adm deleted file mode 100644 index 1e1f9547b..000000000 Binary files a/test-data/hpsf/Test0313rur.adm and /dev/null differ diff --git a/test-data/hpsf/TestBug44375.xls b/test-data/hpsf/TestBug44375.xls deleted file mode 100644 index 0ebd76293..000000000 Binary files a/test-data/hpsf/TestBug44375.xls and /dev/null differ diff --git a/test-data/hpsf/TestChineseProperties.doc b/test-data/hpsf/TestChineseProperties.doc deleted file mode 100644 index fd2b478e4..000000000 Binary files a/test-data/hpsf/TestChineseProperties.doc and /dev/null differ diff --git a/test-data/hpsf/TestCorel.shw b/test-data/hpsf/TestCorel.shw deleted file mode 100644 index e0af1945e..000000000 Binary files a/test-data/hpsf/TestCorel.shw and /dev/null differ diff --git a/test-data/hpsf/TestEditTime.doc b/test-data/hpsf/TestEditTime.doc deleted file mode 100644 index 8b30417de..000000000 Binary files a/test-data/hpsf/TestEditTime.doc and /dev/null differ diff --git a/test-data/hpsf/TestGermanWord90.doc b/test-data/hpsf/TestGermanWord90.doc deleted file mode 100644 index 63bbed326..000000000 Binary files a/test-data/hpsf/TestGermanWord90.doc and /dev/null differ diff --git a/test-data/hpsf/TestMickey.doc b/test-data/hpsf/TestMickey.doc deleted file mode 100644 index f62ade316..000000000 Binary files a/test-data/hpsf/TestMickey.doc and /dev/null differ diff --git a/test-data/hpsf/TestNon4ByteBoundary.doc b/test-data/hpsf/TestNon4ByteBoundary.doc deleted file mode 100644 index 4ecb2215b..000000000 Binary files a/test-data/hpsf/TestNon4ByteBoundary.doc and /dev/null differ diff --git a/test-data/hpsf/TestRobert_Flaherty.doc b/test-data/hpsf/TestRobert_Flaherty.doc deleted file mode 100644 index ee3e14296..000000000 Binary files a/test-data/hpsf/TestRobert_Flaherty.doc and /dev/null differ diff --git a/test-data/hpsf/TestSectionDictionary.doc b/test-data/hpsf/TestSectionDictionary.doc deleted file mode 100644 index 6114a7657..000000000 Binary files a/test-data/hpsf/TestSectionDictionary.doc and /dev/null differ diff --git a/test-data/hpsf/TestShiftJIS.doc b/test-data/hpsf/TestShiftJIS.doc deleted file mode 100644 index f8516d3a7..000000000 Binary files a/test-data/hpsf/TestShiftJIS.doc and /dev/null differ diff --git a/test-data/hpsf/TestSolidWorks.sldprt b/test-data/hpsf/TestSolidWorks.sldprt deleted file mode 100644 index a7962b369..000000000 Binary files a/test-data/hpsf/TestSolidWorks.sldprt and /dev/null differ diff --git a/test-data/hpsf/TestThumbnail.xls b/test-data/hpsf/TestThumbnail.xls deleted file mode 100644 index 69cca038e..000000000 Binary files a/test-data/hpsf/TestThumbnail.xls and /dev/null differ diff --git a/test-data/hpsf/TestUnicode.xls b/test-data/hpsf/TestUnicode.xls deleted file mode 100644 index 30c8f3c1c..000000000 Binary files a/test-data/hpsf/TestUnicode.xls and /dev/null differ diff --git a/test-data/hpsf/TestVisioWithCodepage.vsd b/test-data/hpsf/TestVisioWithCodepage.vsd deleted file mode 100644 index d699e1112..000000000 Binary files a/test-data/hpsf/TestVisioWithCodepage.vsd and /dev/null differ diff --git a/test-data/hpsf/TestWriteWellKnown.doc b/test-data/hpsf/TestWriteWellKnown.doc deleted file mode 100644 index d3a043304..000000000 Binary files a/test-data/hpsf/TestWriteWellKnown.doc and /dev/null differ diff --git a/test-data/hpsf/TestZeroLengthCodePage.mpp b/test-data/hpsf/TestZeroLengthCodePage.mpp deleted file mode 100644 index 4820ab766..000000000 Binary files a/test-data/hpsf/TestZeroLengthCodePage.mpp and /dev/null differ diff --git a/test-data/hpsf/Test_Humor-Generation.ppt b/test-data/hpsf/Test_Humor-Generation.ppt deleted file mode 100644 index 740883247..000000000 Binary files a/test-data/hpsf/Test_Humor-Generation.ppt and /dev/null differ diff --git a/test-data/hsmf/51873.msg b/test-data/hsmf/51873.msg deleted file mode 100644 index 28a0a57db..000000000 Binary files a/test-data/hsmf/51873.msg and /dev/null differ diff --git a/test-data/hsmf/53784_fails.msg b/test-data/hsmf/53784_fails.msg deleted file mode 100644 index 9fb20e9aa..000000000 Binary files a/test-data/hsmf/53784_fails.msg and /dev/null differ diff --git a/test-data/hsmf/53784_succeeds.msg b/test-data/hsmf/53784_succeeds.msg deleted file mode 100644 index 451a9821e..000000000 Binary files a/test-data/hsmf/53784_succeeds.msg and /dev/null differ diff --git a/test-data/hsmf/58214_extracted_attachment.msg b/test-data/hsmf/58214_extracted_attachment.msg deleted file mode 100644 index a321ed5af..000000000 Binary files a/test-data/hsmf/58214_extracted_attachment.msg and /dev/null differ diff --git a/test-data/hsmf/58214_with_attachment.msg b/test-data/hsmf/58214_with_attachment.msg deleted file mode 100644 index d0e11f6b8..000000000 Binary files a/test-data/hsmf/58214_with_attachment.msg and /dev/null differ diff --git a/test-data/hsmf/attachment_msg_inlineImg.msg b/test-data/hsmf/attachment_msg_inlineImg.msg deleted file mode 100644 index ee7abdfc0..000000000 Binary files a/test-data/hsmf/attachment_msg_inlineImg.msg and /dev/null differ diff --git a/test-data/hsmf/attachment_msg_pdf.msg b/test-data/hsmf/attachment_msg_pdf.msg deleted file mode 100644 index 35b66e111..000000000 Binary files a/test-data/hsmf/attachment_msg_pdf.msg and /dev/null differ diff --git a/test-data/hsmf/attachment_test_msg.msg b/test-data/hsmf/attachment_test_msg.msg deleted file mode 100644 index ea82d915e..000000000 Binary files a/test-data/hsmf/attachment_test_msg.msg and /dev/null differ diff --git a/test-data/hsmf/blank.msg b/test-data/hsmf/blank.msg deleted file mode 100644 index 0bdb81240..000000000 Binary files a/test-data/hsmf/blank.msg and /dev/null differ diff --git a/test-data/hsmf/chinese-traditional.msg b/test-data/hsmf/chinese-traditional.msg deleted file mode 100644 index c2b84c097..000000000 Binary files a/test-data/hsmf/chinese-traditional.msg and /dev/null differ diff --git a/test-data/hsmf/cyrillic_message.msg b/test-data/hsmf/cyrillic_message.msg deleted file mode 100644 index d0fc8ec6f..000000000 Binary files a/test-data/hsmf/cyrillic_message.msg and /dev/null differ diff --git a/test-data/hsmf/example_received_regular.msg b/test-data/hsmf/example_received_regular.msg deleted file mode 100644 index 57c66b084..000000000 Binary files a/test-data/hsmf/example_received_regular.msg and /dev/null differ diff --git a/test-data/hsmf/example_received_unicode.msg b/test-data/hsmf/example_received_unicode.msg deleted file mode 100644 index 08256f922..000000000 Binary files a/test-data/hsmf/example_received_unicode.msg and /dev/null differ diff --git a/test-data/hsmf/example_sent_regular.msg b/test-data/hsmf/example_sent_regular.msg deleted file mode 100644 index 0c1c3f6da..000000000 Binary files a/test-data/hsmf/example_sent_regular.msg and /dev/null differ diff --git a/test-data/hsmf/example_sent_unicode.msg b/test-data/hsmf/example_sent_unicode.msg deleted file mode 100644 index 76aa32434..000000000 Binary files a/test-data/hsmf/example_sent_unicode.msg and /dev/null differ diff --git a/test-data/hsmf/logsat.com_signatures_valid.msg b/test-data/hsmf/logsat.com_signatures_valid.msg deleted file mode 100644 index a07432510..000000000 Binary files a/test-data/hsmf/logsat.com_signatures_valid.msg and /dev/null differ diff --git a/test-data/hsmf/message_1979.msg b/test-data/hsmf/message_1979.msg deleted file mode 100644 index 10083c8e4..000000000 Binary files a/test-data/hsmf/message_1979.msg and /dev/null differ diff --git a/test-data/hsmf/message_1980.msg b/test-data/hsmf/message_1980.msg deleted file mode 100644 index bb295404d..000000000 Binary files a/test-data/hsmf/message_1980.msg and /dev/null differ diff --git a/test-data/hsmf/message_1981.msg b/test-data/hsmf/message_1981.msg deleted file mode 100644 index 6833d5434..000000000 Binary files a/test-data/hsmf/message_1981.msg and /dev/null differ diff --git a/test-data/hsmf/message_extra_hyphen_submission_chunk.msg b/test-data/hsmf/message_extra_hyphen_submission_chunk.msg deleted file mode 100644 index 3bcb8d363..000000000 Binary files a/test-data/hsmf/message_extra_hyphen_submission_chunk.msg and /dev/null differ diff --git a/test-data/hsmf/message_normal_submission_chunk.msg b/test-data/hsmf/message_normal_submission_chunk.msg deleted file mode 100644 index bb15d2746..000000000 Binary files a/test-data/hsmf/message_normal_submission_chunk.msg and /dev/null differ diff --git a/test-data/hsmf/msgClassAppointment.msg b/test-data/hsmf/msgClassAppointment.msg deleted file mode 100644 index c124d31d8..000000000 Binary files a/test-data/hsmf/msgClassAppointment.msg and /dev/null differ diff --git a/test-data/hsmf/msgClassContact.msg b/test-data/hsmf/msgClassContact.msg deleted file mode 100644 index d925f3d70..000000000 Binary files a/test-data/hsmf/msgClassContact.msg and /dev/null differ diff --git a/test-data/hsmf/msgClassPost.msg b/test-data/hsmf/msgClassPost.msg deleted file mode 100644 index 3dffd09e7..000000000 Binary files a/test-data/hsmf/msgClassPost.msg and /dev/null differ diff --git a/test-data/hsmf/msgClassStickyNote.msg b/test-data/hsmf/msgClassStickyNote.msg deleted file mode 100644 index 13873a1e4..000000000 Binary files a/test-data/hsmf/msgClassStickyNote.msg and /dev/null differ diff --git a/test-data/hsmf/msgClassTask.msg b/test-data/hsmf/msgClassTask.msg deleted file mode 100644 index a2ac9f8c0..000000000 Binary files a/test-data/hsmf/msgClassTask.msg and /dev/null differ diff --git a/test-data/hsmf/no_recipient_address.msg b/test-data/hsmf/no_recipient_address.msg deleted file mode 100644 index e88d503fe..000000000 Binary files a/test-data/hsmf/no_recipient_address.msg and /dev/null differ diff --git a/test-data/hsmf/outlook_30_msg.msg b/test-data/hsmf/outlook_30_msg.msg deleted file mode 100644 index 0a585699a..000000000 Binary files a/test-data/hsmf/outlook_30_msg.msg and /dev/null differ diff --git a/test-data/hsmf/quick.msg b/test-data/hsmf/quick.msg deleted file mode 100644 index 05326d2c8..000000000 Binary files a/test-data/hsmf/quick.msg and /dev/null differ diff --git a/test-data/hsmf/simple_test_msg.msg b/test-data/hsmf/simple_test_msg.msg deleted file mode 100644 index 731fecc23..000000000 Binary files a/test-data/hsmf/simple_test_msg.msg and /dev/null differ diff --git a/test-data/openxml4j/50154.xlsx b/test-data/openxml4j/50154.xlsx deleted file mode 100644 index 7637fb37b..000000000 Binary files a/test-data/openxml4j/50154.xlsx and /dev/null differ diff --git a/test-data/openxml4j/51444.xlsx b/test-data/openxml4j/51444.xlsx deleted file mode 100644 index 5047dbf44..000000000 Binary files a/test-data/openxml4j/51444.xlsx and /dev/null differ diff --git a/test-data/openxml4j/53282.xlsx b/test-data/openxml4j/53282.xlsx deleted file mode 100644 index 6d8830348..000000000 Binary files a/test-data/openxml4j/53282.xlsx and /dev/null differ diff --git a/test-data/openxml4j/ContentTypeHasEntities.ooxml b/test-data/openxml4j/ContentTypeHasEntities.ooxml deleted file mode 100644 index 9581a2e77..000000000 Binary files a/test-data/openxml4j/ContentTypeHasEntities.ooxml and /dev/null differ diff --git a/test-data/openxml4j/ContentTypeHasParameters.ooxml b/test-data/openxml4j/ContentTypeHasParameters.ooxml deleted file mode 100644 index b4410b009..000000000 Binary files a/test-data/openxml4j/ContentTypeHasParameters.ooxml and /dev/null differ diff --git a/test-data/openxml4j/CorePropertiesHasEntities.ooxml b/test-data/openxml4j/CorePropertiesHasEntities.ooxml deleted file mode 100644 index bdd884b0f..000000000 Binary files a/test-data/openxml4j/CorePropertiesHasEntities.ooxml and /dev/null differ diff --git a/test-data/openxml4j/ExcelWithHyperlinks.xlsx b/test-data/openxml4j/ExcelWithHyperlinks.xlsx deleted file mode 100644 index ba5ed27d2..000000000 Binary files a/test-data/openxml4j/ExcelWithHyperlinks.xlsx and /dev/null differ diff --git a/test-data/openxml4j/MultipleCoreProperties.docx b/test-data/openxml4j/MultipleCoreProperties.docx deleted file mode 100644 index 4c19ae77a..000000000 Binary files a/test-data/openxml4j/MultipleCoreProperties.docx and /dev/null differ diff --git a/test-data/openxml4j/OPCCompliance_CoreProperties_AlternateTimezones.docx b/test-data/openxml4j/OPCCompliance_CoreProperties_AlternateTimezones.docx deleted file mode 100644 index b2a941853..000000000 Binary files a/test-data/openxml4j/OPCCompliance_CoreProperties_AlternateTimezones.docx and /dev/null differ diff --git a/test-data/openxml4j/OPCCompliance_CoreProperties_DCTermsNamespaceLimitedUseFAIL.docx b/test-data/openxml4j/OPCCompliance_CoreProperties_DCTermsNamespaceLimitedUseFAIL.docx deleted file mode 100644 index 89533f031..000000000 Binary files a/test-data/openxml4j/OPCCompliance_CoreProperties_DCTermsNamespaceLimitedUseFAIL.docx and /dev/null differ diff --git a/test-data/openxml4j/OPCCompliance_CoreProperties_DoNotUseCompatibilityMarkupFAIL.docx b/test-data/openxml4j/OPCCompliance_CoreProperties_DoNotUseCompatibilityMarkupFAIL.docx deleted file mode 100644 index 63555e47d..000000000 Binary files a/test-data/openxml4j/OPCCompliance_CoreProperties_DoNotUseCompatibilityMarkupFAIL.docx and /dev/null differ diff --git a/test-data/openxml4j/OPCCompliance_CoreProperties_LimitedXSITypeAttribute_NotPresentFAIL.docx b/test-data/openxml4j/OPCCompliance_CoreProperties_LimitedXSITypeAttribute_NotPresentFAIL.docx deleted file mode 100644 index 304e5ce28..000000000 Binary files a/test-data/openxml4j/OPCCompliance_CoreProperties_LimitedXSITypeAttribute_NotPresentFAIL.docx and /dev/null differ diff --git a/test-data/openxml4j/OPCCompliance_CoreProperties_LimitedXSITypeAttribute_PresentWithUnauthorizedValueFAIL.docx b/test-data/openxml4j/OPCCompliance_CoreProperties_LimitedXSITypeAttribute_PresentWithUnauthorizedValueFAIL.docx deleted file mode 100644 index 7b4f765e6..000000000 Binary files a/test-data/openxml4j/OPCCompliance_CoreProperties_LimitedXSITypeAttribute_PresentWithUnauthorizedValueFAIL.docx and /dev/null differ diff --git a/test-data/openxml4j/OPCCompliance_CoreProperties_OnlyOneCorePropertiesPart.docx b/test-data/openxml4j/OPCCompliance_CoreProperties_OnlyOneCorePropertiesPart.docx deleted file mode 100644 index 7a63ee15d..000000000 Binary files a/test-data/openxml4j/OPCCompliance_CoreProperties_OnlyOneCorePropertiesPart.docx and /dev/null differ diff --git a/test-data/openxml4j/OPCCompliance_CoreProperties_OnlyOneCorePropertiesPartFAIL.docx b/test-data/openxml4j/OPCCompliance_CoreProperties_OnlyOneCorePropertiesPartFAIL.docx deleted file mode 100644 index 3ee9fc333..000000000 Binary files a/test-data/openxml4j/OPCCompliance_CoreProperties_OnlyOneCorePropertiesPartFAIL.docx and /dev/null differ diff --git a/test-data/openxml4j/OPCCompliance_CoreProperties_SUCCESS.docx b/test-data/openxml4j/OPCCompliance_CoreProperties_SUCCESS.docx deleted file mode 100644 index 7a63ee15d..000000000 Binary files a/test-data/openxml4j/OPCCompliance_CoreProperties_SUCCESS.docx and /dev/null differ diff --git a/test-data/openxml4j/OPCCompliance_CoreProperties_UnauthorizedXMLLangAttributeFAIL.docx b/test-data/openxml4j/OPCCompliance_CoreProperties_UnauthorizedXMLLangAttributeFAIL.docx deleted file mode 100644 index 3984aeafc..000000000 Binary files a/test-data/openxml4j/OPCCompliance_CoreProperties_UnauthorizedXMLLangAttributeFAIL.docx and /dev/null differ diff --git a/test-data/openxml4j/OPCCompliance_DerivedPartNameFAIL.docx b/test-data/openxml4j/OPCCompliance_DerivedPartNameFAIL.docx deleted file mode 100644 index 8ccfb6155..000000000 Binary files a/test-data/openxml4j/OPCCompliance_DerivedPartNameFAIL.docx and /dev/null differ diff --git a/test-data/openxml4j/OPCCompliance_NoCoreProperties.xlsx b/test-data/openxml4j/OPCCompliance_NoCoreProperties.xlsx deleted file mode 100644 index fa1049c68..000000000 Binary files a/test-data/openxml4j/OPCCompliance_NoCoreProperties.xlsx and /dev/null differ diff --git a/test-data/openxml4j/PackageRelsHasEntities.ooxml b/test-data/openxml4j/PackageRelsHasEntities.ooxml deleted file mode 100644 index 505fdce52..000000000 Binary files a/test-data/openxml4j/PackageRelsHasEntities.ooxml and /dev/null differ diff --git a/test-data/openxml4j/TestCreatePackageOUTPUT.docx b/test-data/openxml4j/TestCreatePackageOUTPUT.docx deleted file mode 100644 index dfcacc55e..000000000 Binary files a/test-data/openxml4j/TestCreatePackageOUTPUT.docx and /dev/null differ diff --git a/test-data/openxml4j/TestOpenPackageINPUT.docx b/test-data/openxml4j/TestOpenPackageINPUT.docx deleted file mode 100644 index dc105f004..000000000 Binary files a/test-data/openxml4j/TestOpenPackageINPUT.docx and /dev/null differ diff --git a/test-data/openxml4j/TestOpenPackageOUTPUT.docx b/test-data/openxml4j/TestOpenPackageOUTPUT.docx deleted file mode 100644 index 1e0996fd4..000000000 Binary files a/test-data/openxml4j/TestOpenPackageOUTPUT.docx and /dev/null differ diff --git a/test-data/openxml4j/TestPackageCommon.docx b/test-data/openxml4j/TestPackageCommon.docx deleted file mode 100644 index 771cd1814..000000000 Binary files a/test-data/openxml4j/TestPackageCommon.docx and /dev/null differ diff --git a/test-data/openxml4j/TestPackageCoreProperiesGetters.docx b/test-data/openxml4j/TestPackageCoreProperiesGetters.docx deleted file mode 100644 index 2d8bb359b..000000000 Binary files a/test-data/openxml4j/TestPackageCoreProperiesGetters.docx and /dev/null differ diff --git a/test-data/openxml4j/TestPackageCoreProperiesSetters.docx b/test-data/openxml4j/TestPackageCoreProperiesSetters.docx deleted file mode 100644 index 2d8bb359b..000000000 Binary files a/test-data/openxml4j/TestPackageCoreProperiesSetters.docx and /dev/null differ diff --git a/test-data/openxml4j/TestPackageThumbnail.docx b/test-data/openxml4j/TestPackageThumbnail.docx deleted file mode 100644 index ccc990df3..000000000 Binary files a/test-data/openxml4j/TestPackageThumbnail.docx and /dev/null differ diff --git a/test-data/openxml4j/at.pzp.www_uploads_media_PP_Scheinecker-jdk6error.pptx b/test-data/openxml4j/at.pzp.www_uploads_media_PP_Scheinecker-jdk6error.pptx deleted file mode 100644 index 7f9ff0c6f..000000000 Binary files a/test-data/openxml4j/at.pzp.www_uploads_media_PP_Scheinecker-jdk6error.pptx and /dev/null differ diff --git a/test-data/openxml4j/bug-60626.vml b/test-data/openxml4j/bug-60626.vml deleted file mode 100644 index c5fb390a7..000000000 --- a/test-data/openxml4j/bug-60626.vml +++ /dev/null @@ -1,658 +0,0 @@ - - - - - - - - - - - - - 1, 2, 23, 2, 1, 199, 24, 0 - False - False - Risikodaten!$AF$48 - 0 - 0 - 3 - 1 - 1 - 16 - Risikodaten!$AG$44:$AG$47 - 4 - - Single - Normal - Combo - 8 - - - - - -
    -
    - - - - 20, 14, 15, 2, 21, 1, 16, 5 - False - False - Center - $U$16 - - -
    - - - -
    -
    - - - - 20, 14, 11, 0, 20, 37, 12, 4 - False - False - Center - 1 - Risikodaten!E16 - - -
    - - - - - - 1, 2, 24, 0, 1, 199, 24, 19 - False - False - Antrag!$Y$65 - 0 - 0 - 1 - 1 - 1 - 16 - Antrag!$Z$63:$Z$64 - 2 - - Single - Normal - Combo - 8 - - - - - - - 21, 4, 7, 11, 23, 28, 8, 14 - False - Risikodaten!$AF$22 - 0 - 0 - 0 - 1 - 3 - 16 - Risikodaten!$AG$19:$AG$21 - 2 - - Single - Normal - Combo - 8 - - - - - -
    -
    - - - - 20, 14, 13, 3, 20, 34, 14, 0 - False - False - Center - 1 - Risikodaten!$J$13 - - -
    - - - -
    -
    - - - - 20, 14, 14, 3, 20, 34, 15, 0 - False - False - Center - Risikodaten!$J$14 - - -
    - - - -
    -
    - - - - 20, 14, 12, 3, 20, 34, 13, 0 - False - False - Center - 1 - Risikodaten!$J$12 - - -
    - - - -
    -
    - - - - 20, 14, 9, 2, 20, 34, 9, 17 - False - False - Center - Risikodaten!$J$9 - - -
    - - - -
    -
    - - - - 25, 70, 24, 0, 26, 19, 24, 15 - False - False - Center - Risikodaten!$AD$8 - - -
    - - - - - 24, 55, 0, 9, 27, 70, 2, 13 - False - Vermittler!$B$2 - Vermittler!$M$6:$N$206 - Pict - - - - - - - -
    Ausblenden
    -

    -
    -
    - - - 9, 12, 25, 9, 9, 88, 25, 25 - False - False - [0]!Ausblenden_Allianz - Center - Center - -
    - - - -
    Ausblenden
    -

    -
    -
    - - - 7, 12, 25, 9, 7, 88, 25, 25 - False - False - [0]!Ausblenden_Generali - Center - Center - -
    - - - -
    Ausblenden
    -

    -
    -
    - - - 5, 13, 25, 9, 5, 89, 25, 25 - False - False - [0]!Ausblenden_Donau - Center - Center - -
    - - - -
    Ausblenden
    -

    -
    -
    - - - 11, 11, 25, 9, 11, 87, 25, 25 - False - False - [0]!Ausblenden_AragSE - Center - Center - -
    - - - -
    Ausblenden
    -

    -
    -
    - - - 13, 12, 25, 9, 13, 88, 25, 25 - False - False - [0]!Ausblenden_HDI - Center - Center - -
    - - - -
    Ausblenden
    -

    -
    -
    - - - 15, 12, 25, 9, 15, 88, 25, 25 - False - False - [0]!Ausblenden_Zürich - Center - Center - -
    - - - -
    Ausblenden
    -

    -
    -
    - - - 17, 12, 25, 9, 17, 88, 25, 25 - False - False - [0]!Ausblenden_Uniqa - Center - Center - -
    - - - -
    Ausblenden
    -

    -
    -
    - - - 3, 11, 25, 4, 3, 85, 25, 19 - False - False - [0]!Ausblenden_VU_bisher - Center - Center - -
    - - - -
    erh.NL
    -
    - - - - 21, 2, 19, 14, 22, 2, 20, 11 - False - False - Center - 1 - Risikodaten!Y20 - - -
    - - - -
    erh.NL
    -
    - - - - 22, 2, 19, 14, 22, 68, 20, 11 - False - False - Center - 1 - Risikodaten!Z20 - - -
    - - - -
    erh.NL
    -
    - - - - 23, 2, 19, 14, 23, 68, 20, 11 - False - False - Center - 1 - Risikodaten!AA20 - - -
    - - - -
    erh.NL
    -
    - - - - 24, 2, 19, 14, 24, 68, 20, 11 - False - False - Center - 1 - Risikodaten!AB20 - - -
    - - - -
    erh.NL
    -
    - - - - 25, 2, 19, 14, 25, 68, 20, 11 - False - False - Center - 1 - Risikodaten!AC20 - - -
    - - - -
    erh.NL
    -
    - - - - 26, 2, 19, 14, 26, 68, 20, 11 - False - False - Center - 1 - Risikodaten!AD20 - - -
    - - - -
    erh.NL
    -
    - - - - 27, 2, 19, 14, 27, 68, 20, 11 - False - False - Center - 1 - Risikodaten!AE20 - - -
    - - - - -
    -
    - - - - 20, 13, 1, 1, 20, 33, 1, 15 - False - False - [0]!Anzeige_Deckung - Center - 1 - Risikodaten!$I$8 - - -
    - - - - -
    -
    - - - - 20, 13, 2, 1, 20, 33, 2, 16 - False - False - [0]!Anzeige_Deckung - Center - 1 - Risikodaten!$I22 - - -
    - - - - -
    -
    - - - - 20, 13, 3, 1, 20, 33, 3, 16 - False - False - [0]!Anzeige_Deckung - Center - Risikodaten!$I$29 - - -
    - - - - - - - - - - - - - - - - - - - - - - - 1, 1, 5, 9, 13, 23, 13, 2 - Antrag!$B$7:$K$13 - Pict - - - - - - - - - 1, 2, 0, 1, 13, 23, 3, 10 - $DO$1:$DZ$3 - Pict - - -
    \ No newline at end of file diff --git a/test-data/openxml4j/dcterms_bug_56479.zip b/test-data/openxml4j/dcterms_bug_56479.zip deleted file mode 100644 index bce201972..000000000 Binary files a/test-data/openxml4j/dcterms_bug_56479.zip and /dev/null differ diff --git a/test-data/openxml4j/invalid.xlsx b/test-data/openxml4j/invalid.xlsx deleted file mode 100644 index 15cb0ecb3..000000000 Binary files a/test-data/openxml4j/invalid.xlsx and /dev/null differ diff --git a/test-data/openxml4j/sample.docx b/test-data/openxml4j/sample.docx deleted file mode 100644 index 8e7752143..000000000 Binary files a/test-data/openxml4j/sample.docx and /dev/null differ diff --git a/test-data/openxml4j/sample.xlsx b/test-data/openxml4j/sample.xlsx deleted file mode 100644 index a275cf417..000000000 Binary files a/test-data/openxml4j/sample.xlsx and /dev/null differ diff --git a/test-data/openxml4j/thumbnail.jpg b/test-data/openxml4j/thumbnail.jpg deleted file mode 100644 index 511996002..000000000 Binary files a/test-data/openxml4j/thumbnail.jpg and /dev/null differ diff --git a/test-data/poifs/20-Force-on-a-current-S00.doc b/test-data/poifs/20-Force-on-a-current-S00.doc deleted file mode 100644 index 3ad75ebc0..000000000 Binary files a/test-data/poifs/20-Force-on-a-current-S00.doc and /dev/null differ diff --git a/test-data/poifs/60256.bin b/test-data/poifs/60256.bin deleted file mode 100644 index 1fed50b1b..000000000 Binary files a/test-data/poifs/60256.bin and /dev/null differ diff --git a/test-data/poifs/60320-protected.xlsx b/test-data/poifs/60320-protected.xlsx deleted file mode 100644 index 71c6b4cbe..000000000 Binary files a/test-data/poifs/60320-protected.xlsx and /dev/null differ diff --git a/test-data/poifs/BlockSize4096.zvi b/test-data/poifs/BlockSize4096.zvi deleted file mode 100644 index 6379a042e..000000000 Binary files a/test-data/poifs/BlockSize4096.zvi and /dev/null differ diff --git a/test-data/poifs/BlockSize512.zvi b/test-data/poifs/BlockSize512.zvi deleted file mode 100644 index 3a6be2f8d..000000000 Binary files a/test-data/poifs/BlockSize512.zvi and /dev/null differ diff --git a/test-data/poifs/Notes.ole2 b/test-data/poifs/Notes.ole2 deleted file mode 100644 index 9aaed99d3..000000000 Binary files a/test-data/poifs/Notes.ole2 and /dev/null differ diff --git a/test-data/poifs/ReferencesInvalidSectors.mpp b/test-data/poifs/ReferencesInvalidSectors.mpp deleted file mode 100644 index 583a0a119..000000000 Binary files a/test-data/poifs/ReferencesInvalidSectors.mpp and /dev/null differ diff --git a/test-data/poifs/ShortLastBlock.qwp b/test-data/poifs/ShortLastBlock.qwp deleted file mode 100644 index b278d06c2..000000000 Binary files a/test-data/poifs/ShortLastBlock.qwp and /dev/null differ diff --git a/test-data/poifs/ShortLastBlock.wps b/test-data/poifs/ShortLastBlock.wps deleted file mode 100644 index 1b1a627a9..000000000 Binary files a/test-data/poifs/ShortLastBlock.wps and /dev/null differ diff --git a/test-data/poifs/extenxls_pwd123.xlsx b/test-data/poifs/extenxls_pwd123.xlsx deleted file mode 100644 index a6ae896f9..000000000 Binary files a/test-data/poifs/extenxls_pwd123.xlsx and /dev/null differ diff --git a/test-data/poifs/multimedia.doc b/test-data/poifs/multimedia.doc deleted file mode 100644 index 51b356d4a..000000000 Binary files a/test-data/poifs/multimedia.doc and /dev/null differ diff --git a/test-data/poifs/oleObject1.bin b/test-data/poifs/oleObject1.bin deleted file mode 100644 index fc4630296..000000000 Binary files a/test-data/poifs/oleObject1.bin and /dev/null differ diff --git a/test-data/poifs/only-zero-byte-streams.ole2 b/test-data/poifs/only-zero-byte-streams.ole2 deleted file mode 100644 index c1b842987..000000000 Binary files a/test-data/poifs/only-zero-byte-streams.ole2 and /dev/null differ diff --git a/test-data/poifs/poitest.pfx b/test-data/poifs/poitest.pfx deleted file mode 100644 index 14be4d0a6..000000000 Binary files a/test-data/poifs/poitest.pfx and /dev/null differ diff --git a/test-data/poifs/protect.xlsx b/test-data/poifs/protect.xlsx deleted file mode 100644 index 1767b1437..000000000 Binary files a/test-data/poifs/protect.xlsx and /dev/null differ diff --git a/test-data/poifs/protected_agile.docx b/test-data/poifs/protected_agile.docx deleted file mode 100644 index a7de3ebe4..000000000 Binary files a/test-data/poifs/protected_agile.docx and /dev/null differ diff --git a/test-data/poifs/protected_sha512.xlsx b/test-data/poifs/protected_sha512.xlsx deleted file mode 100644 index 1f0ea828b..000000000 Binary files a/test-data/poifs/protected_sha512.xlsx and /dev/null differ diff --git a/test-data/poifs/unknown_properties.msg b/test-data/poifs/unknown_properties.msg deleted file mode 100644 index 2c76df98e..000000000 Binary files a/test-data/poifs/unknown_properties.msg and /dev/null differ diff --git a/test-data/publisher/51318.pub b/test-data/publisher/51318.pub deleted file mode 100644 index 728811c92..000000000 Binary files a/test-data/publisher/51318.pub and /dev/null differ diff --git a/test-data/publisher/LinkAt0And10.pub b/test-data/publisher/LinkAt0And10.pub deleted file mode 100644 index c4459fb83..000000000 Binary files a/test-data/publisher/LinkAt0And10.pub and /dev/null differ diff --git a/test-data/publisher/LinkAt10.pub b/test-data/publisher/LinkAt10.pub deleted file mode 100644 index 89c4a4427..000000000 Binary files a/test-data/publisher/LinkAt10.pub and /dev/null differ diff --git a/test-data/publisher/LinkAt10And20And30.pub b/test-data/publisher/LinkAt10And20And30.pub deleted file mode 100644 index 5f7f747d5..000000000 Binary files a/test-data/publisher/LinkAt10And20And30.pub and /dev/null differ diff --git a/test-data/publisher/LinkAt10And20And30And40.pub b/test-data/publisher/LinkAt10And20And30And40.pub deleted file mode 100644 index d19ddc46a..000000000 Binary files a/test-data/publisher/LinkAt10And20And30And40.pub and /dev/null differ diff --git a/test-data/publisher/LinkAt10Longer.pub b/test-data/publisher/LinkAt10Longer.pub deleted file mode 100644 index 8a3dcc277..000000000 Binary files a/test-data/publisher/LinkAt10Longer.pub and /dev/null differ diff --git a/test-data/publisher/LinkAt20.pub b/test-data/publisher/LinkAt20.pub deleted file mode 100644 index 091a38c71..000000000 Binary files a/test-data/publisher/LinkAt20.pub and /dev/null differ diff --git a/test-data/publisher/Sample.pub b/test-data/publisher/Sample.pub deleted file mode 100644 index b87016831..000000000 Binary files a/test-data/publisher/Sample.pub and /dev/null differ diff --git a/test-data/publisher/Sample.txt b/test-data/publisher/Sample.txt deleted file mode 100644 index 279395e5d..000000000 --- a/test-data/publisher/Sample.txt +++ /dev/null @@ -1,29 +0,0 @@ -This is some text on the first page -It’s in times new roman, font size 10, all normal - - -This is in bold and italic -It’s Arial, 20 point font -It’s in the second textbox on the first page - - -This is the second page - -It is also times new roman, 10 point - - -Table on page 2 Top right -P2 table left P2 table right -Bottom Left Bottom Right - - -This text is on page two -This is a link to Apache POI -More normal text -Link to a file - - -More text, more hyperlinks -email link -Final hyperlink -Within doc to page 1 diff --git a/test-data/publisher/Sample2.pub b/test-data/publisher/Sample2.pub deleted file mode 100644 index 610362c47..000000000 Binary files a/test-data/publisher/Sample2.pub and /dev/null differ diff --git a/test-data/publisher/Sample2.txt b/test-data/publisher/Sample2.txt deleted file mode 100644 index f8a68bb64..000000000 --- a/test-data/publisher/Sample2.txt +++ /dev/null @@ -1,34 +0,0 @@ -This is some text on the first page -It’s in times new roman, font size 10, all normal - -We’ve added some more text in here, to push all the offsets about a bit. - - - -This is in bold and italic -It’s Arial, 20 point font -It’s in the second textbox on the first page - -Ditto with more text in here. - - -This is the second page - -It is also times new roman, 10 point - - -Table on page 2 Top right -P2 table left P2 table right -Bottom Left Bottom Right - - -This text is on page two -This is a link to Apache POI -More normal text -Link to a file - - -More text, more hyperlinks -email link -Final hyperlink -Within doc to page 1 diff --git a/test-data/publisher/Sample2000.pub b/test-data/publisher/Sample2000.pub deleted file mode 100644 index 2c6174e5e..000000000 Binary files a/test-data/publisher/Sample2000.pub and /dev/null differ diff --git a/test-data/publisher/Sample2_2010.pub b/test-data/publisher/Sample2_2010.pub deleted file mode 100644 index 74f456605..000000000 Binary files a/test-data/publisher/Sample2_2010.pub and /dev/null differ diff --git a/test-data/publisher/Sample3.pub b/test-data/publisher/Sample3.pub deleted file mode 100644 index 4f19bec93..000000000 Binary files a/test-data/publisher/Sample3.pub and /dev/null differ diff --git a/test-data/publisher/Sample3.txt b/test-data/publisher/Sample3.txt deleted file mode 100644 index c2d791b9a..000000000 --- a/test-data/publisher/Sample3.txt +++ /dev/null @@ -1,29 +0,0 @@ -This is some text on the first page -It’s in times new roman, font size 10, all normal - - -This is in bold and italic -It’s Arial, 20 point font -It’s in the second textbox on the first page - - -This is the second page12345678 - -It is also times new roman, 10 point - - -Table on page 2 Top right -P2 table left P2 table right -Bottom Left Bottom Right - - -This text is on page two -This is a link to Apache POI -More normal text -Link to a file - - -More text, more hyperlinks -email link -Final hyperlink -Within doc to page 1 diff --git a/test-data/publisher/Sample3_2010.pub b/test-data/publisher/Sample3_2010.pub deleted file mode 100644 index d2982c06b..000000000 Binary files a/test-data/publisher/Sample3_2010.pub and /dev/null differ diff --git a/test-data/publisher/Sample4.pub b/test-data/publisher/Sample4.pub deleted file mode 100644 index 445df85f0..000000000 Binary files a/test-data/publisher/Sample4.pub and /dev/null differ diff --git a/test-data/publisher/Sample4.txt b/test-data/publisher/Sample4.txt deleted file mode 100644 index 279395e5d..000000000 --- a/test-data/publisher/Sample4.txt +++ /dev/null @@ -1,29 +0,0 @@ -This is some text on the first page -It’s in times new roman, font size 10, all normal - - -This is in bold and italic -It’s Arial, 20 point font -It’s in the second textbox on the first page - - -This is the second page - -It is also times new roman, 10 point - - -Table on page 2 Top right -P2 table left P2 table right -Bottom Left Bottom Right - - -This text is on page two -This is a link to Apache POI -More normal text -Link to a file - - -More text, more hyperlinks -email link -Final hyperlink -Within doc to page 1 diff --git a/test-data/publisher/Sample4_2010.pub b/test-data/publisher/Sample4_2010.pub deleted file mode 100644 index dd6c25b17..000000000 Binary files a/test-data/publisher/Sample4_2010.pub and /dev/null differ diff --git a/test-data/publisher/Sample98.pub b/test-data/publisher/Sample98.pub deleted file mode 100644 index 8adffda77..000000000 Binary files a/test-data/publisher/Sample98.pub and /dev/null differ diff --git a/test-data/publisher/SampleBrochure.pub b/test-data/publisher/SampleBrochure.pub deleted file mode 100644 index 00deec14d..000000000 Binary files a/test-data/publisher/SampleBrochure.pub and /dev/null differ diff --git a/test-data/publisher/SampleNewsletter.pub b/test-data/publisher/SampleNewsletter.pub deleted file mode 100644 index 94900925a..000000000 Binary files a/test-data/publisher/SampleNewsletter.pub and /dev/null differ diff --git a/test-data/publisher/Sample_2010.pub b/test-data/publisher/Sample_2010.pub deleted file mode 100644 index ace154071..000000000 Binary files a/test-data/publisher/Sample_2010.pub and /dev/null differ diff --git a/test-data/publisher/Simple.pub b/test-data/publisher/Simple.pub deleted file mode 100644 index 2397b9d01..000000000 Binary files a/test-data/publisher/Simple.pub and /dev/null differ diff --git a/test-data/slideshow/2411-Performance_Up.pptx b/test-data/slideshow/2411-Performance_Up.pptx deleted file mode 100644 index 46fe3972c..000000000 Binary files a/test-data/slideshow/2411-Performance_Up.pptx and /dev/null differ diff --git a/test-data/slideshow/37625.ppt b/test-data/slideshow/37625.ppt deleted file mode 100644 index d15779867..000000000 Binary files a/test-data/slideshow/37625.ppt and /dev/null differ diff --git a/test-data/slideshow/38256.ppt b/test-data/slideshow/38256.ppt deleted file mode 100644 index a0883bda0..000000000 Binary files a/test-data/slideshow/38256.ppt and /dev/null differ diff --git a/test-data/slideshow/41071.ppt b/test-data/slideshow/41071.ppt deleted file mode 100644 index 4a443025e..000000000 Binary files a/test-data/slideshow/41071.ppt and /dev/null differ diff --git a/test-data/slideshow/41246-1.ppt b/test-data/slideshow/41246-1.ppt deleted file mode 100644 index b78519189..000000000 Binary files a/test-data/slideshow/41246-1.ppt and /dev/null differ diff --git a/test-data/slideshow/41246-2.ppt b/test-data/slideshow/41246-2.ppt deleted file mode 100644 index 1b1a9630b..000000000 Binary files a/test-data/slideshow/41246-2.ppt and /dev/null differ diff --git a/test-data/slideshow/41384.ppt b/test-data/slideshow/41384.ppt deleted file mode 100644 index 7a206ecdd..000000000 Binary files a/test-data/slideshow/41384.ppt and /dev/null differ diff --git a/test-data/slideshow/42474-1.ppt b/test-data/slideshow/42474-1.ppt deleted file mode 100644 index 15b654d26..000000000 Binary files a/test-data/slideshow/42474-1.ppt and /dev/null differ diff --git a/test-data/slideshow/42474-2.ppt b/test-data/slideshow/42474-2.ppt deleted file mode 100644 index 5c6f8ca90..000000000 Binary files a/test-data/slideshow/42474-2.ppt and /dev/null differ diff --git a/test-data/slideshow/42485.ppt b/test-data/slideshow/42485.ppt deleted file mode 100644 index e9e3dda1e..000000000 Binary files a/test-data/slideshow/42485.ppt and /dev/null differ diff --git a/test-data/slideshow/42486.ppt b/test-data/slideshow/42486.ppt deleted file mode 100644 index af45163c5..000000000 Binary files a/test-data/slideshow/42486.ppt and /dev/null differ diff --git a/test-data/slideshow/42520.ppt b/test-data/slideshow/42520.ppt deleted file mode 100644 index 15bcf6410..000000000 Binary files a/test-data/slideshow/42520.ppt and /dev/null differ diff --git a/test-data/slideshow/43781.ppt b/test-data/slideshow/43781.ppt deleted file mode 100644 index ddea91fe8..000000000 Binary files a/test-data/slideshow/43781.ppt and /dev/null differ diff --git a/test-data/slideshow/44296.ppt b/test-data/slideshow/44296.ppt deleted file mode 100644 index 1e0529db1..000000000 Binary files a/test-data/slideshow/44296.ppt and /dev/null differ diff --git a/test-data/slideshow/44770.ppt b/test-data/slideshow/44770.ppt deleted file mode 100644 index d7ae12b56..000000000 Binary files a/test-data/slideshow/44770.ppt and /dev/null differ diff --git a/test-data/slideshow/45537_Footer.ppt b/test-data/slideshow/45537_Footer.ppt deleted file mode 100644 index f358b14e9..000000000 Binary files a/test-data/slideshow/45537_Footer.ppt and /dev/null differ diff --git a/test-data/slideshow/45537_Header.ppt b/test-data/slideshow/45537_Header.ppt deleted file mode 100644 index e09d7752b..000000000 Binary files a/test-data/slideshow/45537_Header.ppt and /dev/null differ diff --git a/test-data/slideshow/45541_Footer.pptx b/test-data/slideshow/45541_Footer.pptx deleted file mode 100644 index 84e3f47cd..000000000 Binary files a/test-data/slideshow/45541_Footer.pptx and /dev/null differ diff --git a/test-data/slideshow/45541_Header.pptx b/test-data/slideshow/45541_Header.pptx deleted file mode 100644 index fe7b7a114..000000000 Binary files a/test-data/slideshow/45541_Header.pptx and /dev/null differ diff --git a/test-data/slideshow/45543.ppt b/test-data/slideshow/45543.ppt deleted file mode 100644 index d5b04f8d5..000000000 Binary files a/test-data/slideshow/45543.ppt and /dev/null differ diff --git a/test-data/slideshow/45545_Comment.pptx b/test-data/slideshow/45545_Comment.pptx deleted file mode 100644 index ce34eeac3..000000000 Binary files a/test-data/slideshow/45545_Comment.pptx and /dev/null differ diff --git a/test-data/slideshow/45776.ppt b/test-data/slideshow/45776.ppt deleted file mode 100644 index 637b06ec3..000000000 Binary files a/test-data/slideshow/45776.ppt and /dev/null differ diff --git a/test-data/slideshow/47261.ppt b/test-data/slideshow/47261.ppt deleted file mode 100644 index 7a26a7981..000000000 Binary files a/test-data/slideshow/47261.ppt and /dev/null differ diff --git a/test-data/slideshow/49386-null_dates.pptx b/test-data/slideshow/49386-null_dates.pptx deleted file mode 100644 index 77fc378ce..000000000 Binary files a/test-data/slideshow/49386-null_dates.pptx and /dev/null differ diff --git a/test-data/slideshow/49541_symbol_map.ppt b/test-data/slideshow/49541_symbol_map.ppt deleted file mode 100644 index 781049290..000000000 Binary files a/test-data/slideshow/49541_symbol_map.ppt and /dev/null differ diff --git a/test-data/slideshow/49648.ppt b/test-data/slideshow/49648.ppt deleted file mode 100644 index 841b904a1..000000000 Binary files a/test-data/slideshow/49648.ppt and /dev/null differ diff --git a/test-data/slideshow/51187.pptx b/test-data/slideshow/51187.pptx deleted file mode 100644 index 25816d5ad..000000000 Binary files a/test-data/slideshow/51187.pptx and /dev/null differ diff --git a/test-data/slideshow/51731.ppt b/test-data/slideshow/51731.ppt deleted file mode 100644 index 07d690481..000000000 Binary files a/test-data/slideshow/51731.ppt and /dev/null differ diff --git a/test-data/slideshow/52244.ppt b/test-data/slideshow/52244.ppt deleted file mode 100644 index aaf384360..000000000 Binary files a/test-data/slideshow/52244.ppt and /dev/null differ diff --git a/test-data/slideshow/52599.ppt b/test-data/slideshow/52599.ppt deleted file mode 100644 index a1c2e8d06..000000000 Binary files a/test-data/slideshow/52599.ppt and /dev/null differ diff --git a/test-data/slideshow/53446.ppt b/test-data/slideshow/53446.ppt deleted file mode 100644 index 55333fc35..000000000 Binary files a/test-data/slideshow/53446.ppt and /dev/null differ diff --git a/test-data/slideshow/54111.ppt b/test-data/slideshow/54111.ppt deleted file mode 100644 index 048bfb621..000000000 Binary files a/test-data/slideshow/54111.ppt and /dev/null differ diff --git a/test-data/slideshow/54332a.ppt b/test-data/slideshow/54332a.ppt deleted file mode 100644 index ebdedf5e3..000000000 Binary files a/test-data/slideshow/54332a.ppt and /dev/null differ diff --git a/test-data/slideshow/54332b.ppt b/test-data/slideshow/54332b.ppt deleted file mode 100644 index 41f20fa55..000000000 Binary files a/test-data/slideshow/54332b.ppt and /dev/null differ diff --git a/test-data/slideshow/54541_cropped_bitmap.ppt b/test-data/slideshow/54541_cropped_bitmap.ppt deleted file mode 100644 index 3c631a16f..000000000 Binary files a/test-data/slideshow/54541_cropped_bitmap.ppt and /dev/null differ diff --git a/test-data/slideshow/54541_cropped_bitmap2.ppt b/test-data/slideshow/54541_cropped_bitmap2.ppt deleted file mode 100644 index 3d79dbd33..000000000 Binary files a/test-data/slideshow/54541_cropped_bitmap2.ppt and /dev/null differ diff --git a/test-data/slideshow/54542_cropped_bitmap.pptx b/test-data/slideshow/54542_cropped_bitmap.pptx deleted file mode 100644 index b8d960c00..000000000 Binary files a/test-data/slideshow/54542_cropped_bitmap.pptx and /dev/null differ diff --git a/test-data/slideshow/54722.ppt b/test-data/slideshow/54722.ppt deleted file mode 100644 index c62a60b2e..000000000 Binary files a/test-data/slideshow/54722.ppt and /dev/null differ diff --git a/test-data/slideshow/54880_chinese.ppt b/test-data/slideshow/54880_chinese.ppt deleted file mode 100644 index b9830f523..000000000 Binary files a/test-data/slideshow/54880_chinese.ppt and /dev/null differ diff --git a/test-data/slideshow/56260.ppt b/test-data/slideshow/56260.ppt deleted file mode 100644 index 6c2c0d9a7..000000000 Binary files a/test-data/slideshow/56260.ppt and /dev/null differ diff --git a/test-data/slideshow/56812.pptx b/test-data/slideshow/56812.pptx deleted file mode 100644 index 2fa070ad1..000000000 Binary files a/test-data/slideshow/56812.pptx and /dev/null differ diff --git a/test-data/slideshow/57272_corrupted_usereditatom.ppt b/test-data/slideshow/57272_corrupted_usereditatom.ppt deleted file mode 100644 index b811d6b04..000000000 Binary files a/test-data/slideshow/57272_corrupted_usereditatom.ppt and /dev/null differ diff --git a/test-data/slideshow/59302.ppt b/test-data/slideshow/59302.ppt deleted file mode 100644 index bd53fe44d..000000000 Binary files a/test-data/slideshow/59302.ppt and /dev/null differ diff --git a/test-data/slideshow/60003.ppt b/test-data/slideshow/60003.ppt deleted file mode 100644 index 1a4cd2f48..000000000 Binary files a/test-data/slideshow/60003.ppt and /dev/null differ diff --git a/test-data/slideshow/60042.pptx b/test-data/slideshow/60042.pptx deleted file mode 100644 index b22e3d67d..000000000 Binary files a/test-data/slideshow/60042.pptx and /dev/null differ diff --git a/test-data/slideshow/60294.ppt b/test-data/slideshow/60294.ppt deleted file mode 100644 index ebcae6265..000000000 Binary files a/test-data/slideshow/60294.ppt and /dev/null differ diff --git a/test-data/slideshow/60810.pptx b/test-data/slideshow/60810.pptx deleted file mode 100644 index 3e4e22be5..000000000 Binary files a/test-data/slideshow/60810.pptx and /dev/null differ diff --git a/test-data/slideshow/KEY02.pptx b/test-data/slideshow/KEY02.pptx deleted file mode 100644 index 142c6dd27..000000000 Binary files a/test-data/slideshow/KEY02.pptx and /dev/null differ diff --git a/test-data/slideshow/OverlappingRelations.pptx b/test-data/slideshow/OverlappingRelations.pptx deleted file mode 100644 index 7551630bd..000000000 Binary files a/test-data/slideshow/OverlappingRelations.pptx and /dev/null differ diff --git a/test-data/slideshow/PPT95.ppt b/test-data/slideshow/PPT95.ppt deleted file mode 100644 index 3f338d433..000000000 Binary files a/test-data/slideshow/PPT95.ppt and /dev/null differ diff --git a/test-data/slideshow/PPTWithAttachments.pptm b/test-data/slideshow/PPTWithAttachments.pptm deleted file mode 100644 index 00b148da1..000000000 Binary files a/test-data/slideshow/PPTWithAttachments.pptm and /dev/null differ diff --git a/test-data/slideshow/ParagraphStylesShorterThanCharStyles.ppt b/test-data/slideshow/ParagraphStylesShorterThanCharStyles.ppt deleted file mode 100644 index 19a8a75a5..000000000 Binary files a/test-data/slideshow/ParagraphStylesShorterThanCharStyles.ppt and /dev/null differ diff --git a/test-data/slideshow/Password_Protected-56-hello.ppt b/test-data/slideshow/Password_Protected-56-hello.ppt deleted file mode 100644 index d1e5d6617..000000000 Binary files a/test-data/slideshow/Password_Protected-56-hello.ppt and /dev/null differ diff --git a/test-data/slideshow/Password_Protected-hello.ppt b/test-data/slideshow/Password_Protected-hello.ppt deleted file mode 100644 index 3bbab4d5c..000000000 Binary files a/test-data/slideshow/Password_Protected-hello.ppt and /dev/null differ diff --git a/test-data/slideshow/Password_Protected-np-hello.ppt b/test-data/slideshow/Password_Protected-np-hello.ppt deleted file mode 100644 index 863418373..000000000 Binary files a/test-data/slideshow/Password_Protected-np-hello.ppt and /dev/null differ diff --git a/test-data/slideshow/PictureTypeZero.ppt b/test-data/slideshow/PictureTypeZero.ppt deleted file mode 100644 index 66b4e50c0..000000000 Binary files a/test-data/slideshow/PictureTypeZero.ppt and /dev/null differ diff --git a/test-data/slideshow/SampleShow.ppt b/test-data/slideshow/SampleShow.ppt deleted file mode 100644 index 81b99e100..000000000 Binary files a/test-data/slideshow/SampleShow.ppt and /dev/null differ diff --git a/test-data/slideshow/SampleShow.pptx b/test-data/slideshow/SampleShow.pptx deleted file mode 100644 index e5237f4c1..000000000 Binary files a/test-data/slideshow/SampleShow.pptx and /dev/null differ diff --git a/test-data/slideshow/SampleShow.txt b/test-data/slideshow/SampleShow.txt deleted file mode 100644 index ccfe4d271..000000000 --- a/test-data/slideshow/SampleShow.txt +++ /dev/null @@ -1,26 +0,0 @@ -Author = Nick Burch -Title = SlideShow Sample -Subject = A sample slideshow -Keywords = Sample Testing -Comments = This is a sample slideshow, for use with testing etc - -(Slide 1) -Title of the first slide - -Subtitle of the first slide - -This bit is in italic green - -(Notes 1) -I am the notes of the first slide - -(Slide 2) -This is the second slide - -* It has bullet points on it -* They’re fun, aren’t they? -* Especially in a different font like Arial Black at 16 point! - -(Notes 2) -These are the notes of the 2nd slide -THIS LINE IS BOLD diff --git a/test-data/slideshow/SimpleMacro.ppt b/test-data/slideshow/SimpleMacro.ppt deleted file mode 100644 index 228ebe968..000000000 Binary files a/test-data/slideshow/SimpleMacro.ppt and /dev/null differ diff --git a/test-data/slideshow/SimpleMacro.pptm b/test-data/slideshow/SimpleMacro.pptm deleted file mode 100644 index d39de5c80..000000000 Binary files a/test-data/slideshow/SimpleMacro.pptm and /dev/null differ diff --git a/test-data/slideshow/SimpleMacro.vba b/test-data/slideshow/SimpleMacro.vba deleted file mode 100644 index 2f26227e1..000000000 --- a/test-data/slideshow/SimpleMacro.vba +++ /dev/null @@ -1,14 +0,0 @@ -Sub TestMacro() -' -' TestMacro Macro -' This is a test macro -' - -' - With ActivePresentation.Slides(1).Shapes(1) - .Title.TextFrame.TextRange.Text = "This is a macro slideshow" - End With - With ActivePresentation.Slides(1).Shapes(2) - .Title.TextFrame.TextRange.Text = "subtitle" - EndWith -End Sub diff --git a/test-data/slideshow/Single_Coloured_Page.ppt b/test-data/slideshow/Single_Coloured_Page.ppt deleted file mode 100644 index 455502512..000000000 Binary files a/test-data/slideshow/Single_Coloured_Page.ppt and /dev/null differ diff --git a/test-data/slideshow/Single_Coloured_Page_With_Fonts_and_Alignments.ppt b/test-data/slideshow/Single_Coloured_Page_With_Fonts_and_Alignments.ppt deleted file mode 100644 index a177642c9..000000000 Binary files a/test-data/slideshow/Single_Coloured_Page_With_Fonts_and_Alignments.ppt and /dev/null differ diff --git a/test-data/slideshow/WithComments.ppt b/test-data/slideshow/WithComments.ppt deleted file mode 100644 index 2b5f8642e..000000000 Binary files a/test-data/slideshow/WithComments.ppt and /dev/null differ diff --git a/test-data/slideshow/WithLinks.ppt b/test-data/slideshow/WithLinks.ppt deleted file mode 100644 index 80d2e6dbb..000000000 Binary files a/test-data/slideshow/WithLinks.ppt and /dev/null differ diff --git a/test-data/slideshow/WithMacros.ppt b/test-data/slideshow/WithMacros.ppt deleted file mode 100644 index 1c7223153..000000000 Binary files a/test-data/slideshow/WithMacros.ppt and /dev/null differ diff --git a/test-data/slideshow/WithMaster.ppt b/test-data/slideshow/WithMaster.ppt deleted file mode 100644 index 84a6d0451..000000000 Binary files a/test-data/slideshow/WithMaster.ppt and /dev/null differ diff --git a/test-data/slideshow/WithMaster.pptx b/test-data/slideshow/WithMaster.pptx deleted file mode 100644 index a746e103f..000000000 Binary files a/test-data/slideshow/WithMaster.pptx and /dev/null differ diff --git a/test-data/slideshow/aascu.org_workarea_downloadasset.aspx_id=5864.pptx b/test-data/slideshow/aascu.org_workarea_downloadasset.aspx_id=5864.pptx deleted file mode 100644 index 05c30aae3..000000000 Binary files a/test-data/slideshow/aascu.org_workarea_downloadasset.aspx_id=5864.pptx and /dev/null differ diff --git a/test-data/slideshow/ae.ac.uaeu.faculty_nafaachbili_GeomLec1.pptx b/test-data/slideshow/ae.ac.uaeu.faculty_nafaachbili_GeomLec1.pptx deleted file mode 100644 index ca9d7919c..000000000 Binary files a/test-data/slideshow/ae.ac.uaeu.faculty_nafaachbili_GeomLec1.pptx and /dev/null differ diff --git a/test-data/slideshow/alterman_security.ppt b/test-data/slideshow/alterman_security.ppt deleted file mode 100644 index 72c226133..000000000 Binary files a/test-data/slideshow/alterman_security.ppt and /dev/null differ diff --git a/test-data/slideshow/alterman_security.pptx b/test-data/slideshow/alterman_security.pptx deleted file mode 100644 index e9869b9c2..000000000 Binary files a/test-data/slideshow/alterman_security.pptx and /dev/null differ diff --git a/test-data/slideshow/at.ecodesign.www_downloads_Vertiefungsvortrag_elektronik.pptx b/test-data/slideshow/at.ecodesign.www_downloads_Vertiefungsvortrag_elektronik.pptx deleted file mode 100644 index 057886216..000000000 Binary files a/test-data/slideshow/at.ecodesign.www_downloads_Vertiefungsvortrag_elektronik.pptx and /dev/null differ diff --git a/test-data/slideshow/au.asn.aes.www_conferences_2011_presentations_Fri_20Room4Level4_20930_20Maloney.pptx b/test-data/slideshow/au.asn.aes.www_conferences_2011_presentations_Fri_20Room4Level4_20930_20Maloney.pptx deleted file mode 100644 index e287ffe0e..000000000 Binary files a/test-data/slideshow/au.asn.aes.www_conferences_2011_presentations_Fri_20Room4Level4_20930_20Maloney.pptx and /dev/null differ diff --git a/test-data/slideshow/backgrounds.ppt b/test-data/slideshow/backgrounds.ppt deleted file mode 100644 index 591efafef..000000000 Binary files a/test-data/slideshow/backgrounds.ppt and /dev/null differ diff --git a/test-data/slideshow/backgrounds.pptx b/test-data/slideshow/backgrounds.pptx deleted file mode 100644 index 1ce0557fb..000000000 Binary files a/test-data/slideshow/backgrounds.pptx and /dev/null differ diff --git a/test-data/slideshow/badzip.ppt b/test-data/slideshow/badzip.ppt deleted file mode 100644 index c8ff00e04..000000000 Binary files a/test-data/slideshow/badzip.ppt and /dev/null differ diff --git a/test-data/slideshow/basic_test_ppt_file.ppt b/test-data/slideshow/basic_test_ppt_file.ppt deleted file mode 100644 index af16393f4..000000000 Binary files a/test-data/slideshow/basic_test_ppt_file.ppt and /dev/null differ diff --git a/test-data/slideshow/br.com.diversas.palestras_Nelson_20-_20Temas_20Diversos_20XXXVI_pmrg_462538ba7a204-programa_alianca_12-04-2007.ppt b/test-data/slideshow/br.com.diversas.palestras_Nelson_20-_20Temas_20Diversos_20XXXVI_pmrg_462538ba7a204-programa_alianca_12-04-2007.ppt deleted file mode 100644 index ead1b4927..000000000 Binary files a/test-data/slideshow/br.com.diversas.palestras_Nelson_20-_20Temas_20Diversos_20XXXVI_pmrg_462538ba7a204-programa_alianca_12-04-2007.ppt and /dev/null differ diff --git a/test-data/slideshow/br.com.tvcamboriu.www_pps_Pensar_5b1_5d.ppt b/test-data/slideshow/br.com.tvcamboriu.www_pps_Pensar_5b1_5d.ppt deleted file mode 100644 index b3f01ed28..000000000 Binary files a/test-data/slideshow/br.com.tvcamboriu.www_pps_Pensar_5b1_5d.ppt and /dev/null differ diff --git a/test-data/slideshow/bug-41015.ppt b/test-data/slideshow/bug-41015.ppt deleted file mode 100644 index b804a6021..000000000 Binary files a/test-data/slideshow/bug-41015.ppt and /dev/null differ diff --git a/test-data/slideshow/bug45088.ppt b/test-data/slideshow/bug45088.ppt deleted file mode 100644 index e4be0f3f9..000000000 Binary files a/test-data/slideshow/bug45088.ppt and /dev/null differ diff --git a/test-data/slideshow/bug45124.ppt b/test-data/slideshow/bug45124.ppt deleted file mode 100644 index 2fd87b15e..000000000 Binary files a/test-data/slideshow/bug45124.ppt and /dev/null differ diff --git a/test-data/slideshow/bug45908.ppt b/test-data/slideshow/bug45908.ppt deleted file mode 100644 index 2bd1b1d7e..000000000 Binary files a/test-data/slideshow/bug45908.ppt and /dev/null differ diff --git a/test-data/slideshow/bug46441.ppt b/test-data/slideshow/bug46441.ppt deleted file mode 100644 index a7a019c96..000000000 Binary files a/test-data/slideshow/bug46441.ppt and /dev/null differ diff --git a/test-data/slideshow/bug47261.ppt b/test-data/slideshow/bug47261.ppt deleted file mode 100644 index cece730aa..000000000 Binary files a/test-data/slideshow/bug47261.ppt and /dev/null differ diff --git a/test-data/slideshow/bug52297.ppt b/test-data/slideshow/bug52297.ppt deleted file mode 100644 index 79fd609b8..000000000 Binary files a/test-data/slideshow/bug52297.ppt and /dev/null differ diff --git a/test-data/slideshow/bug53192.ppt b/test-data/slideshow/bug53192.ppt deleted file mode 100644 index 54797b5aa..000000000 Binary files a/test-data/slideshow/bug53192.ppt and /dev/null differ diff --git a/test-data/slideshow/bug54570.pptx b/test-data/slideshow/bug54570.pptx deleted file mode 100644 index a5547e9c5..000000000 Binary files a/test-data/slideshow/bug54570.pptx and /dev/null differ diff --git a/test-data/slideshow/bug55030.ppt b/test-data/slideshow/bug55030.ppt deleted file mode 100644 index 1f2f22b00..000000000 Binary files a/test-data/slideshow/bug55030.ppt and /dev/null differ diff --git a/test-data/slideshow/bug55732.ppt b/test-data/slideshow/bug55732.ppt deleted file mode 100644 index c0f84ac67..000000000 Binary files a/test-data/slideshow/bug55732.ppt and /dev/null differ diff --git a/test-data/slideshow/bug55902-mixedChars.png b/test-data/slideshow/bug55902-mixedChars.png deleted file mode 100644 index 4b17565a6..000000000 Binary files a/test-data/slideshow/bug55902-mixedChars.png and /dev/null differ diff --git a/test-data/slideshow/bug55902-mixedFontChineseCharacters.ppt b/test-data/slideshow/bug55902-mixedFontChineseCharacters.ppt deleted file mode 100644 index 4524e361a..000000000 Binary files a/test-data/slideshow/bug55902-mixedFontChineseCharacters.ppt and /dev/null differ diff --git a/test-data/slideshow/bug56240.ppt b/test-data/slideshow/bug56240.ppt deleted file mode 100644 index 908f2ccb0..000000000 Binary files a/test-data/slideshow/bug56240.ppt and /dev/null differ diff --git a/test-data/slideshow/bug57820-initTableNullRefrenceException.ppt b/test-data/slideshow/bug57820-initTableNullRefrenceException.ppt deleted file mode 100644 index e7525f945..000000000 Binary files a/test-data/slideshow/bug57820-initTableNullRefrenceException.ppt and /dev/null differ diff --git a/test-data/slideshow/bug58144-headers-footers-2003.ppt b/test-data/slideshow/bug58144-headers-footers-2003.ppt deleted file mode 100644 index 78915e8c2..000000000 Binary files a/test-data/slideshow/bug58144-headers-footers-2003.ppt and /dev/null differ diff --git a/test-data/slideshow/bug58144-headers-footers-2007.ppt b/test-data/slideshow/bug58144-headers-footers-2007.ppt deleted file mode 100644 index 2c22eaa6a..000000000 Binary files a/test-data/slideshow/bug58144-headers-footers-2007.ppt and /dev/null differ diff --git a/test-data/slideshow/bug58144-headers-footers-2007.pptx b/test-data/slideshow/bug58144-headers-footers-2007.pptx deleted file mode 100644 index 461f0c5d4..000000000 Binary files a/test-data/slideshow/bug58144-headers-footers-2007.pptx and /dev/null differ diff --git a/test-data/slideshow/bug58159_headers-and-footers.ppt b/test-data/slideshow/bug58159_headers-and-footers.ppt deleted file mode 100644 index 2bc6b7061..000000000 Binary files a/test-data/slideshow/bug58159_headers-and-footers.ppt and /dev/null differ diff --git a/test-data/slideshow/bug58516.ppt b/test-data/slideshow/bug58516.ppt deleted file mode 100644 index b1cb7cd19..000000000 Binary files a/test-data/slideshow/bug58516.ppt and /dev/null differ diff --git a/test-data/slideshow/bug58718_008495.ppt b/test-data/slideshow/bug58718_008495.ppt deleted file mode 100644 index 9d9009a86..000000000 Binary files a/test-data/slideshow/bug58718_008495.ppt and /dev/null differ diff --git a/test-data/slideshow/bug58718_008524.ppt b/test-data/slideshow/bug58718_008524.ppt deleted file mode 100644 index 96eddb772..000000000 Binary files a/test-data/slideshow/bug58718_008524.ppt and /dev/null differ diff --git a/test-data/slideshow/bug58718_008558.ppt b/test-data/slideshow/bug58718_008558.ppt deleted file mode 100644 index c8a6d5279..000000000 Binary files a/test-data/slideshow/bug58718_008558.ppt and /dev/null differ diff --git a/test-data/slideshow/bug58718_349008.ppt b/test-data/slideshow/bug58718_349008.ppt deleted file mode 100644 index 41d9759b1..000000000 Binary files a/test-data/slideshow/bug58718_349008.ppt and /dev/null differ diff --git a/test-data/slideshow/bug58733_671884.ppt b/test-data/slideshow/bug58733_671884.ppt deleted file mode 100644 index 08c46e055..000000000 Binary files a/test-data/slideshow/bug58733_671884.ppt and /dev/null differ diff --git a/test-data/slideshow/bug59273.potx b/test-data/slideshow/bug59273.potx deleted file mode 100644 index 72815da71..000000000 Binary files a/test-data/slideshow/bug59273.potx and /dev/null differ diff --git a/test-data/slideshow/bug60345_Jankovic_final_Retreat_2002.ppt b/test-data/slideshow/bug60345_Jankovic_final_Retreat_2002.ppt deleted file mode 100644 index 5bb52fc5d..000000000 Binary files a/test-data/slideshow/bug60345_Jankovic_final_Retreat_2002.ppt and /dev/null differ diff --git a/test-data/slideshow/bug60345_paperfigures.ppt b/test-data/slideshow/bug60345_paperfigures.ppt deleted file mode 100644 index 6a0455631..000000000 Binary files a/test-data/slideshow/bug60345_paperfigures.ppt and /dev/null differ diff --git a/test-data/slideshow/bug60345_suba.ppt b/test-data/slideshow/bug60345_suba.ppt deleted file mode 100644 index 9ffea08ae..000000000 Binary files a/test-data/slideshow/bug60345_suba.ppt and /dev/null differ diff --git a/test-data/slideshow/bug60715.pptx b/test-data/slideshow/bug60715.pptx deleted file mode 100644 index 16f018a0b..000000000 Binary files a/test-data/slideshow/bug60715.pptx and /dev/null differ diff --git a/test-data/slideshow/bullets.ppt b/test-data/slideshow/bullets.ppt deleted file mode 100644 index be2f8bba9..000000000 Binary files a/test-data/slideshow/bullets.ppt and /dev/null differ diff --git a/test-data/slideshow/clock.dib b/test-data/slideshow/clock.dib deleted file mode 100644 index e9c6e7223..000000000 Binary files a/test-data/slideshow/clock.dib and /dev/null differ diff --git a/test-data/slideshow/clock.jpg b/test-data/slideshow/clock.jpg deleted file mode 100644 index 5f05e42ea..000000000 Binary files a/test-data/slideshow/clock.jpg and /dev/null differ diff --git a/test-data/slideshow/cow.pict b/test-data/slideshow/cow.pict deleted file mode 100644 index 71b81d254..000000000 Binary files a/test-data/slideshow/cow.pict and /dev/null differ diff --git a/test-data/slideshow/cryptoapi-proc2356.ppt b/test-data/slideshow/cryptoapi-proc2356.ppt deleted file mode 100644 index bccc45dea..000000000 Binary files a/test-data/slideshow/cryptoapi-proc2356.ppt and /dev/null differ diff --git a/test-data/slideshow/empty.ppt b/test-data/slideshow/empty.ppt deleted file mode 100644 index 20d2398e3..000000000 Binary files a/test-data/slideshow/empty.ppt and /dev/null differ diff --git a/test-data/slideshow/empty_textbox.ppt b/test-data/slideshow/empty_textbox.ppt deleted file mode 100644 index 403b2861e..000000000 Binary files a/test-data/slideshow/empty_textbox.ppt and /dev/null differ diff --git a/test-data/slideshow/headers_footers.ppt b/test-data/slideshow/headers_footers.ppt deleted file mode 100644 index 891d73f95..000000000 Binary files a/test-data/slideshow/headers_footers.ppt and /dev/null differ diff --git a/test-data/slideshow/headers_footers_2007.ppt b/test-data/slideshow/headers_footers_2007.ppt deleted file mode 100644 index 51b2c53b6..000000000 Binary files a/test-data/slideshow/headers_footers_2007.ppt and /dev/null differ diff --git a/test-data/slideshow/iisd_report.ppt b/test-data/slideshow/iisd_report.ppt deleted file mode 100644 index 976fa94b6..000000000 Binary files a/test-data/slideshow/iisd_report.ppt and /dev/null differ diff --git a/test-data/slideshow/incorrect_slide_order.ppt b/test-data/slideshow/incorrect_slide_order.ppt deleted file mode 100644 index 6aead5df9..000000000 Binary files a/test-data/slideshow/incorrect_slide_order.ppt and /dev/null differ diff --git a/test-data/slideshow/layouts.pptx b/test-data/slideshow/layouts.pptx deleted file mode 100644 index 9087579a0..000000000 Binary files a/test-data/slideshow/layouts.pptx and /dev/null differ diff --git a/test-data/slideshow/master_text.ppt b/test-data/slideshow/master_text.ppt deleted file mode 100644 index cdcf4bc00..000000000 Binary files a/test-data/slideshow/master_text.ppt and /dev/null differ diff --git a/test-data/slideshow/missing_core_records.ppt b/test-data/slideshow/missing_core_records.ppt deleted file mode 100644 index 67325ebcf..000000000 Binary files a/test-data/slideshow/missing_core_records.ppt and /dev/null differ diff --git a/test-data/slideshow/next_test_ppt_file.ppt b/test-data/slideshow/next_test_ppt_file.ppt deleted file mode 100644 index 69b2c4787..000000000 Binary files a/test-data/slideshow/next_test_ppt_file.ppt and /dev/null differ diff --git a/test-data/slideshow/numbers.ppt b/test-data/slideshow/numbers.ppt deleted file mode 100644 index 970c3d75b..000000000 Binary files a/test-data/slideshow/numbers.ppt and /dev/null differ diff --git a/test-data/slideshow/numbers2.ppt b/test-data/slideshow/numbers2.ppt deleted file mode 100644 index 839cadd60..000000000 Binary files a/test-data/slideshow/numbers2.ppt and /dev/null differ diff --git a/test-data/slideshow/numbers3.ppt b/test-data/slideshow/numbers3.ppt deleted file mode 100644 index d76df104e..000000000 Binary files a/test-data/slideshow/numbers3.ppt and /dev/null differ diff --git a/test-data/slideshow/ole2-embedding-2003.ppt b/test-data/slideshow/ole2-embedding-2003.ppt deleted file mode 100644 index 506888fdb..000000000 Binary files a/test-data/slideshow/ole2-embedding-2003.ppt and /dev/null differ diff --git a/test-data/slideshow/painting.png b/test-data/slideshow/painting.png deleted file mode 100644 index 28f123300..000000000 Binary files a/test-data/slideshow/painting.png and /dev/null differ diff --git a/test-data/slideshow/pictures.ppt b/test-data/slideshow/pictures.ppt deleted file mode 100644 index 9f6ce6dea..000000000 Binary files a/test-data/slideshow/pictures.ppt and /dev/null differ diff --git a/test-data/slideshow/pie-chart.pptx b/test-data/slideshow/pie-chart.pptx deleted file mode 100644 index 33d28e154..000000000 Binary files a/test-data/slideshow/pie-chart.pptx and /dev/null differ diff --git a/test-data/slideshow/ppt_with_embeded.ppt b/test-data/slideshow/ppt_with_embeded.ppt deleted file mode 100644 index 588dcefe9..000000000 Binary files a/test-data/slideshow/ppt_with_embeded.ppt and /dev/null differ diff --git a/test-data/slideshow/ppt_with_png.ppt b/test-data/slideshow/ppt_with_png.ppt deleted file mode 100644 index 0e0ac673a..000000000 Binary files a/test-data/slideshow/ppt_with_png.ppt and /dev/null differ diff --git a/test-data/slideshow/pptx2svg.pptx b/test-data/slideshow/pptx2svg.pptx deleted file mode 100644 index 2f9a3515c..000000000 Binary files a/test-data/slideshow/pptx2svg.pptx and /dev/null differ diff --git a/test-data/slideshow/pptx2svg.svg b/test-data/slideshow/pptx2svg.svg deleted file mode 100644 index 9ea363691..000000000 --- a/test-data/slideshow/pptx2svg.svg +++ /dev/null @@ -1,94 +0,0 @@ - - - - - - - - - - - - - - -Paragraphs and Rich Formatting - - - -The Paragraphs and Rich Formatting portion of the DrawingML framework stores text -and related formatting information for a text body contained within a shape. -Formatting for text within a shape can be broken down into three levels of precision, -namely body, paragraph, and run formatting properties. - -Body Formatting - - - -Being the highest level of formatting available within a shape, the body properties allow for the -manipulation of the text area as a whole. This means that all paragraphs and runs of text for the shape -in question would be encompassed within here and, therefore, follow the text body style defined here. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -POI - - - - - - - - - - - - - - - - - - - - - diff --git a/test-data/slideshow/prProps.pptx b/test-data/slideshow/prProps.pptx deleted file mode 100644 index 2829fcaec..000000000 Binary files a/test-data/slideshow/prProps.pptx and /dev/null differ diff --git a/test-data/slideshow/present1.pptx b/test-data/slideshow/present1.pptx deleted file mode 100644 index c7f4c9f62..000000000 Binary files a/test-data/slideshow/present1.pptx and /dev/null differ diff --git a/test-data/slideshow/ringin.wav b/test-data/slideshow/ringin.wav deleted file mode 100644 index f8d4292d0..000000000 Binary files a/test-data/slideshow/ringin.wav and /dev/null differ diff --git a/test-data/slideshow/sample.pptx b/test-data/slideshow/sample.pptx deleted file mode 100644 index fbd540c1e..000000000 Binary files a/test-data/slideshow/sample.pptx and /dev/null differ diff --git a/test-data/slideshow/sample_pptx_grouping_issues.pptx b/test-data/slideshow/sample_pptx_grouping_issues.pptx deleted file mode 100644 index bf0c70253..000000000 Binary files a/test-data/slideshow/sample_pptx_grouping_issues.pptx and /dev/null differ diff --git a/test-data/slideshow/santa.wmf b/test-data/slideshow/santa.wmf deleted file mode 100644 index 20993ba95..000000000 Binary files a/test-data/slideshow/santa.wmf and /dev/null differ diff --git a/test-data/slideshow/sci_cec.dib b/test-data/slideshow/sci_cec.dib deleted file mode 100644 index 61bfb6254..000000000 Binary files a/test-data/slideshow/sci_cec.dib and /dev/null differ diff --git a/test-data/slideshow/shapes.pptx b/test-data/slideshow/shapes.pptx deleted file mode 100644 index 9d1500d6c..000000000 Binary files a/test-data/slideshow/shapes.pptx and /dev/null differ diff --git a/test-data/slideshow/slide_master.ppt b/test-data/slideshow/slide_master.ppt deleted file mode 100644 index 0889a5d64..000000000 Binary files a/test-data/slideshow/slide_master.ppt and /dev/null differ diff --git a/test-data/slideshow/sound.ppt b/test-data/slideshow/sound.ppt deleted file mode 100644 index 2d1316acf..000000000 Binary files a/test-data/slideshow/sound.ppt and /dev/null differ diff --git a/test-data/slideshow/table_test.ppt b/test-data/slideshow/table_test.ppt deleted file mode 100644 index d1c688a3a..000000000 Binary files a/test-data/slideshow/table_test.ppt and /dev/null differ diff --git a/test-data/slideshow/table_test.pptx b/test-data/slideshow/table_test.pptx deleted file mode 100644 index 451a6dce7..000000000 Binary files a/test-data/slideshow/table_test.pptx and /dev/null differ diff --git a/test-data/slideshow/table_test2.pptx b/test-data/slideshow/table_test2.pptx deleted file mode 100644 index 625071782..000000000 Binary files a/test-data/slideshow/table_test2.pptx and /dev/null differ diff --git a/test-data/slideshow/testPPT.ppsm b/test-data/slideshow/testPPT.ppsm deleted file mode 100644 index 6ba1432c8..000000000 Binary files a/test-data/slideshow/testPPT.ppsm and /dev/null differ diff --git a/test-data/slideshow/testPPT.ppsx b/test-data/slideshow/testPPT.ppsx deleted file mode 100644 index 814ec0e31..000000000 Binary files a/test-data/slideshow/testPPT.ppsx and /dev/null differ diff --git a/test-data/slideshow/testPPT.pptm b/test-data/slideshow/testPPT.pptm deleted file mode 100644 index e8fe1626d..000000000 Binary files a/test-data/slideshow/testPPT.pptm and /dev/null differ diff --git a/test-data/slideshow/testPPT.pptx b/test-data/slideshow/testPPT.pptx deleted file mode 100644 index 38bc6a233..000000000 Binary files a/test-data/slideshow/testPPT.pptx and /dev/null differ diff --git a/test-data/slideshow/testPPT.thmx b/test-data/slideshow/testPPT.thmx deleted file mode 100644 index 914408818..000000000 Binary files a/test-data/slideshow/testPPT.thmx and /dev/null differ diff --git a/test-data/slideshow/testPPT.xps b/test-data/slideshow/testPPT.xps deleted file mode 100644 index 678033a61..000000000 Binary files a/test-data/slideshow/testPPT.xps and /dev/null differ diff --git a/test-data/slideshow/testtiff.tif b/test-data/slideshow/testtiff.tif deleted file mode 100644 index 99e6bdeb7..000000000 Binary files a/test-data/slideshow/testtiff.tif and /dev/null differ diff --git a/test-data/slideshow/text-margins.ppt b/test-data/slideshow/text-margins.ppt deleted file mode 100644 index cf539aea7..000000000 Binary files a/test-data/slideshow/text-margins.ppt and /dev/null differ diff --git a/test-data/slideshow/text_shapes.ppt b/test-data/slideshow/text_shapes.ppt deleted file mode 100644 index c36183ac3..000000000 Binary files a/test-data/slideshow/text_shapes.ppt and /dev/null differ diff --git a/test-data/slideshow/themes.pptx b/test-data/slideshow/themes.pptx deleted file mode 100644 index 5f2e751a7..000000000 Binary files a/test-data/slideshow/themes.pptx and /dev/null differ diff --git a/test-data/slideshow/tomcat.png b/test-data/slideshow/tomcat.png deleted file mode 100644 index b10c6b75f..000000000 Binary files a/test-data/slideshow/tomcat.png and /dev/null differ diff --git a/test-data/slideshow/with_japanese.pptx b/test-data/slideshow/with_japanese.pptx deleted file mode 100644 index 432a8061a..000000000 Binary files a/test-data/slideshow/with_japanese.pptx and /dev/null differ diff --git a/test-data/slideshow/with_textbox.ppt b/test-data/slideshow/with_textbox.ppt deleted file mode 100644 index d79584f6b..000000000 Binary files a/test-data/slideshow/with_textbox.ppt and /dev/null differ diff --git a/test-data/slideshow/wrench.emf b/test-data/slideshow/wrench.emf deleted file mode 100644 index 80016074b..000000000 Binary files a/test-data/slideshow/wrench.emf and /dev/null differ diff --git a/test-data/spreadsheet/12561-1.xls b/test-data/spreadsheet/12561-1.xls deleted file mode 100644 index 40b7276cb..000000000 Binary files a/test-data/spreadsheet/12561-1.xls and /dev/null differ diff --git a/test-data/spreadsheet/12561-2.xls b/test-data/spreadsheet/12561-2.xls deleted file mode 100644 index bb360c1ab..000000000 Binary files a/test-data/spreadsheet/12561-2.xls and /dev/null differ diff --git a/test-data/spreadsheet/12843-1.xls b/test-data/spreadsheet/12843-1.xls deleted file mode 100644 index 0ef5df426..000000000 Binary files a/test-data/spreadsheet/12843-1.xls and /dev/null differ diff --git a/test-data/spreadsheet/12843-2.xls b/test-data/spreadsheet/12843-2.xls deleted file mode 100644 index beff64650..000000000 Binary files a/test-data/spreadsheet/12843-2.xls and /dev/null differ diff --git a/test-data/spreadsheet/13224.xls b/test-data/spreadsheet/13224.xls deleted file mode 100644 index 81f69d333..000000000 Binary files a/test-data/spreadsheet/13224.xls and /dev/null differ diff --git a/test-data/spreadsheet/13796.xls b/test-data/spreadsheet/13796.xls deleted file mode 100644 index efae53f48..000000000 Binary files a/test-data/spreadsheet/13796.xls and /dev/null differ diff --git a/test-data/spreadsheet/14330-1.xls b/test-data/spreadsheet/14330-1.xls deleted file mode 100644 index 6fd2d9524..000000000 Binary files a/test-data/spreadsheet/14330-1.xls and /dev/null differ diff --git a/test-data/spreadsheet/14330-2.xls b/test-data/spreadsheet/14330-2.xls deleted file mode 100644 index 8e56a6df3..000000000 Binary files a/test-data/spreadsheet/14330-2.xls and /dev/null differ diff --git a/test-data/spreadsheet/14460.xls b/test-data/spreadsheet/14460.xls deleted file mode 100644 index 284d68461..000000000 Binary files a/test-data/spreadsheet/14460.xls and /dev/null differ diff --git a/test-data/spreadsheet/15228.xls b/test-data/spreadsheet/15228.xls deleted file mode 100644 index 3b26ed1e9..000000000 Binary files a/test-data/spreadsheet/15228.xls and /dev/null differ diff --git a/test-data/spreadsheet/15375.xls b/test-data/spreadsheet/15375.xls deleted file mode 100644 index 99ab193be..000000000 Binary files a/test-data/spreadsheet/15375.xls and /dev/null differ diff --git a/test-data/spreadsheet/15556.xls b/test-data/spreadsheet/15556.xls deleted file mode 100644 index 82b48a55b..000000000 Binary files a/test-data/spreadsheet/15556.xls and /dev/null differ diff --git a/test-data/spreadsheet/15573.xls b/test-data/spreadsheet/15573.xls deleted file mode 100644 index 172f25503..000000000 Binary files a/test-data/spreadsheet/15573.xls and /dev/null differ diff --git a/test-data/spreadsheet/1900DateWindowing.xls b/test-data/spreadsheet/1900DateWindowing.xls deleted file mode 100644 index 94fe5c1be..000000000 Binary files a/test-data/spreadsheet/1900DateWindowing.xls and /dev/null differ diff --git a/test-data/spreadsheet/1904DateWindowing.xls b/test-data/spreadsheet/1904DateWindowing.xls deleted file mode 100644 index 8c0dba1d7..000000000 Binary files a/test-data/spreadsheet/1904DateWindowing.xls and /dev/null differ diff --git a/test-data/spreadsheet/19599-1.xls b/test-data/spreadsheet/19599-1.xls deleted file mode 100644 index 4ce27d1fb..000000000 Binary files a/test-data/spreadsheet/19599-1.xls and /dev/null differ diff --git a/test-data/spreadsheet/19599-2.xls b/test-data/spreadsheet/19599-2.xls deleted file mode 100644 index 17f45839d..000000000 Binary files a/test-data/spreadsheet/19599-2.xls and /dev/null differ diff --git a/test-data/spreadsheet/22742.xls b/test-data/spreadsheet/22742.xls deleted file mode 100644 index cd367ca9b..000000000 Binary files a/test-data/spreadsheet/22742.xls and /dev/null differ diff --git a/test-data/spreadsheet/24207.xls b/test-data/spreadsheet/24207.xls deleted file mode 100644 index eca56425e..000000000 Binary files a/test-data/spreadsheet/24207.xls and /dev/null differ diff --git a/test-data/spreadsheet/24215.xls b/test-data/spreadsheet/24215.xls deleted file mode 100644 index bcbbe6312..000000000 Binary files a/test-data/spreadsheet/24215.xls and /dev/null differ diff --git a/test-data/spreadsheet/25183.xls b/test-data/spreadsheet/25183.xls deleted file mode 100644 index 635a64987..000000000 Binary files a/test-data/spreadsheet/25183.xls and /dev/null differ diff --git a/test-data/spreadsheet/25695.xls b/test-data/spreadsheet/25695.xls deleted file mode 100644 index 08b503566..000000000 Binary files a/test-data/spreadsheet/25695.xls and /dev/null differ diff --git a/test-data/spreadsheet/26100.xls b/test-data/spreadsheet/26100.xls deleted file mode 100644 index 802cf8960..000000000 Binary files a/test-data/spreadsheet/26100.xls and /dev/null differ diff --git a/test-data/spreadsheet/27272_1.xls b/test-data/spreadsheet/27272_1.xls deleted file mode 100644 index 1715db85d..000000000 Binary files a/test-data/spreadsheet/27272_1.xls and /dev/null differ diff --git a/test-data/spreadsheet/27272_2.xls b/test-data/spreadsheet/27272_2.xls deleted file mode 100644 index 3e69928d5..000000000 Binary files a/test-data/spreadsheet/27272_2.xls and /dev/null differ diff --git a/test-data/spreadsheet/27349-vlookupAcrossSheets.xls b/test-data/spreadsheet/27349-vlookupAcrossSheets.xls deleted file mode 100644 index c21d434a7..000000000 Binary files a/test-data/spreadsheet/27349-vlookupAcrossSheets.xls and /dev/null differ diff --git a/test-data/spreadsheet/27364.xls b/test-data/spreadsheet/27364.xls deleted file mode 100644 index 73aa3fa2f..000000000 Binary files a/test-data/spreadsheet/27364.xls and /dev/null differ diff --git a/test-data/spreadsheet/27394.xls b/test-data/spreadsheet/27394.xls deleted file mode 100644 index e9ba1cc9b..000000000 Binary files a/test-data/spreadsheet/27394.xls and /dev/null differ diff --git a/test-data/spreadsheet/27852.xls b/test-data/spreadsheet/27852.xls deleted file mode 100644 index b4b0a4c6c..000000000 Binary files a/test-data/spreadsheet/27852.xls and /dev/null differ diff --git a/test-data/spreadsheet/27933.xls b/test-data/spreadsheet/27933.xls deleted file mode 100644 index 79722370b..000000000 Binary files a/test-data/spreadsheet/27933.xls and /dev/null differ diff --git a/test-data/spreadsheet/28772.xls b/test-data/spreadsheet/28772.xls deleted file mode 100644 index a5190de64..000000000 Binary files a/test-data/spreadsheet/28772.xls and /dev/null differ diff --git a/test-data/spreadsheet/28774.xls b/test-data/spreadsheet/28774.xls deleted file mode 100644 index 476f3bafe..000000000 Binary files a/test-data/spreadsheet/28774.xls and /dev/null differ diff --git a/test-data/spreadsheet/29675.xls b/test-data/spreadsheet/29675.xls deleted file mode 100644 index a80df1ffb..000000000 Binary files a/test-data/spreadsheet/29675.xls and /dev/null differ diff --git a/test-data/spreadsheet/29942.xls b/test-data/spreadsheet/29942.xls deleted file mode 100644 index 9fac290a0..000000000 Binary files a/test-data/spreadsheet/29942.xls and /dev/null differ diff --git a/test-data/spreadsheet/29982.xls b/test-data/spreadsheet/29982.xls deleted file mode 100644 index 8430ff72b..000000000 Binary files a/test-data/spreadsheet/29982.xls and /dev/null differ diff --git a/test-data/spreadsheet/30070.xls b/test-data/spreadsheet/30070.xls deleted file mode 100644 index 5ae668583..000000000 Binary files a/test-data/spreadsheet/30070.xls and /dev/null differ diff --git a/test-data/spreadsheet/30540.xls b/test-data/spreadsheet/30540.xls deleted file mode 100644 index bf91e1bb1..000000000 Binary files a/test-data/spreadsheet/30540.xls and /dev/null differ diff --git a/test-data/spreadsheet/30978-alt.xls b/test-data/spreadsheet/30978-alt.xls deleted file mode 100644 index c59158288..000000000 Binary files a/test-data/spreadsheet/30978-alt.xls and /dev/null differ diff --git a/test-data/spreadsheet/30978-deleted.xls b/test-data/spreadsheet/30978-deleted.xls deleted file mode 100644 index 0a2cabedc..000000000 Binary files a/test-data/spreadsheet/30978-deleted.xls and /dev/null differ diff --git a/test-data/spreadsheet/31661.xls b/test-data/spreadsheet/31661.xls deleted file mode 100644 index 79050b432..000000000 Binary files a/test-data/spreadsheet/31661.xls and /dev/null differ diff --git a/test-data/spreadsheet/31749.xls b/test-data/spreadsheet/31749.xls deleted file mode 100644 index 6962a0923..000000000 Binary files a/test-data/spreadsheet/31749.xls and /dev/null differ diff --git a/test-data/spreadsheet/31979.xls b/test-data/spreadsheet/31979.xls deleted file mode 100644 index a0c743d28..000000000 Binary files a/test-data/spreadsheet/31979.xls and /dev/null differ diff --git a/test-data/spreadsheet/32822.xls b/test-data/spreadsheet/32822.xls deleted file mode 100644 index b95a5fc7e..000000000 Binary files a/test-data/spreadsheet/32822.xls and /dev/null differ diff --git a/test-data/spreadsheet/33082.xls b/test-data/spreadsheet/33082.xls deleted file mode 100644 index 74a2df4de..000000000 Binary files a/test-data/spreadsheet/33082.xls and /dev/null differ diff --git a/test-data/spreadsheet/34775.xls b/test-data/spreadsheet/34775.xls deleted file mode 100644 index 9ad8f2383..000000000 Binary files a/test-data/spreadsheet/34775.xls and /dev/null differ diff --git a/test-data/spreadsheet/35564.xls b/test-data/spreadsheet/35564.xls deleted file mode 100644 index db18e0187..000000000 Binary files a/test-data/spreadsheet/35564.xls and /dev/null differ diff --git a/test-data/spreadsheet/35565.xls b/test-data/spreadsheet/35565.xls deleted file mode 100644 index ee97f0a36..000000000 Binary files a/test-data/spreadsheet/35565.xls and /dev/null differ diff --git a/test-data/spreadsheet/35897-type4.xls b/test-data/spreadsheet/35897-type4.xls deleted file mode 100644 index c3eadbbc5..000000000 Binary files a/test-data/spreadsheet/35897-type4.xls and /dev/null differ diff --git a/test-data/spreadsheet/36947.xls b/test-data/spreadsheet/36947.xls deleted file mode 100644 index 4c7bde6c2..000000000 Binary files a/test-data/spreadsheet/36947.xls and /dev/null differ diff --git a/test-data/spreadsheet/37376.xls b/test-data/spreadsheet/37376.xls deleted file mode 100644 index 59176a66e..000000000 Binary files a/test-data/spreadsheet/37376.xls and /dev/null differ diff --git a/test-data/spreadsheet/37630.xls b/test-data/spreadsheet/37630.xls deleted file mode 100644 index ad2b0ef50..000000000 Binary files a/test-data/spreadsheet/37630.xls and /dev/null differ diff --git a/test-data/spreadsheet/37684-1.xls b/test-data/spreadsheet/37684-1.xls deleted file mode 100644 index a59769eb3..000000000 Binary files a/test-data/spreadsheet/37684-1.xls and /dev/null differ diff --git a/test-data/spreadsheet/37684-2.xls b/test-data/spreadsheet/37684-2.xls deleted file mode 100644 index b17d0fa22..000000000 Binary files a/test-data/spreadsheet/37684-2.xls and /dev/null differ diff --git a/test-data/spreadsheet/37684.xls b/test-data/spreadsheet/37684.xls deleted file mode 100644 index 3aecf073c..000000000 Binary files a/test-data/spreadsheet/37684.xls and /dev/null differ diff --git a/test-data/spreadsheet/39234.xls b/test-data/spreadsheet/39234.xls deleted file mode 100644 index 20fc9a001..000000000 Binary files a/test-data/spreadsheet/39234.xls and /dev/null differ diff --git a/test-data/spreadsheet/39512.xls b/test-data/spreadsheet/39512.xls deleted file mode 100644 index 44cf5718e..000000000 Binary files a/test-data/spreadsheet/39512.xls and /dev/null differ diff --git a/test-data/spreadsheet/39634.xls b/test-data/spreadsheet/39634.xls deleted file mode 100644 index 0f76bffe4..000000000 Binary files a/test-data/spreadsheet/39634.xls and /dev/null differ diff --git a/test-data/spreadsheet/3dFormulas.xls b/test-data/spreadsheet/3dFormulas.xls deleted file mode 100644 index 82519ed83..000000000 Binary files a/test-data/spreadsheet/3dFormulas.xls and /dev/null differ diff --git a/test-data/spreadsheet/40285.xls b/test-data/spreadsheet/40285.xls deleted file mode 100644 index 077e1c834..000000000 Binary files a/test-data/spreadsheet/40285.xls and /dev/null differ diff --git a/test-data/spreadsheet/41139.xls b/test-data/spreadsheet/41139.xls deleted file mode 100644 index e4925fe2d..000000000 Binary files a/test-data/spreadsheet/41139.xls and /dev/null differ diff --git a/test-data/spreadsheet/41546.xls b/test-data/spreadsheet/41546.xls deleted file mode 100644 index 1332f3eef..000000000 Binary files a/test-data/spreadsheet/41546.xls and /dev/null differ diff --git a/test-data/spreadsheet/42016.xls b/test-data/spreadsheet/42016.xls deleted file mode 100644 index 4cbdab7d2..000000000 Binary files a/test-data/spreadsheet/42016.xls and /dev/null differ diff --git a/test-data/spreadsheet/42464-ExpPtg-bad.xls b/test-data/spreadsheet/42464-ExpPtg-bad.xls deleted file mode 100644 index 54a7edb40..000000000 Binary files a/test-data/spreadsheet/42464-ExpPtg-bad.xls and /dev/null differ diff --git a/test-data/spreadsheet/42464-ExpPtg-ok.xls b/test-data/spreadsheet/42464-ExpPtg-ok.xls deleted file mode 100644 index 5ae84bc90..000000000 Binary files a/test-data/spreadsheet/42464-ExpPtg-ok.xls and /dev/null differ diff --git a/test-data/spreadsheet/42726.xls b/test-data/spreadsheet/42726.xls deleted file mode 100644 index e492c5d3d..000000000 Binary files a/test-data/spreadsheet/42726.xls and /dev/null differ diff --git a/test-data/spreadsheet/42844.xls b/test-data/spreadsheet/42844.xls deleted file mode 100644 index 50bb5a85b..000000000 Binary files a/test-data/spreadsheet/42844.xls and /dev/null differ diff --git a/test-data/spreadsheet/43251.xls b/test-data/spreadsheet/43251.xls deleted file mode 100644 index abc476ab0..000000000 Binary files a/test-data/spreadsheet/43251.xls and /dev/null differ diff --git a/test-data/spreadsheet/43493.xls b/test-data/spreadsheet/43493.xls deleted file mode 100644 index 2a02f3d74..000000000 Binary files a/test-data/spreadsheet/43493.xls and /dev/null differ diff --git a/test-data/spreadsheet/43623.xls b/test-data/spreadsheet/43623.xls deleted file mode 100644 index 401cb2a88..000000000 Binary files a/test-data/spreadsheet/43623.xls and /dev/null differ diff --git a/test-data/spreadsheet/43902.xls b/test-data/spreadsheet/43902.xls deleted file mode 100644 index a67720d6c..000000000 Binary files a/test-data/spreadsheet/43902.xls and /dev/null differ diff --git a/test-data/spreadsheet/44010-SingleChart.xls b/test-data/spreadsheet/44010-SingleChart.xls deleted file mode 100644 index fe0df2750..000000000 Binary files a/test-data/spreadsheet/44010-SingleChart.xls and /dev/null differ diff --git a/test-data/spreadsheet/44010-TwoCharts.xls b/test-data/spreadsheet/44010-TwoCharts.xls deleted file mode 100644 index 4a61523fe..000000000 Binary files a/test-data/spreadsheet/44010-TwoCharts.xls and /dev/null differ diff --git a/test-data/spreadsheet/44167.xls b/test-data/spreadsheet/44167.xls deleted file mode 100644 index c5470210d..000000000 Binary files a/test-data/spreadsheet/44167.xls and /dev/null differ diff --git a/test-data/spreadsheet/44200.xls b/test-data/spreadsheet/44200.xls deleted file mode 100644 index 691afedb8..000000000 Binary files a/test-data/spreadsheet/44200.xls and /dev/null differ diff --git a/test-data/spreadsheet/44201.xls b/test-data/spreadsheet/44201.xls deleted file mode 100644 index 593d5aa18..000000000 Binary files a/test-data/spreadsheet/44201.xls and /dev/null differ diff --git a/test-data/spreadsheet/44235.xls b/test-data/spreadsheet/44235.xls deleted file mode 100644 index 39b76588a..000000000 Binary files a/test-data/spreadsheet/44235.xls and /dev/null differ diff --git a/test-data/spreadsheet/44297.xls b/test-data/spreadsheet/44297.xls deleted file mode 100644 index bc65efd4e..000000000 Binary files a/test-data/spreadsheet/44297.xls and /dev/null differ diff --git a/test-data/spreadsheet/44593.xls b/test-data/spreadsheet/44593.xls deleted file mode 100644 index 84d131144..000000000 Binary files a/test-data/spreadsheet/44593.xls and /dev/null differ diff --git a/test-data/spreadsheet/44636.xls b/test-data/spreadsheet/44636.xls deleted file mode 100644 index 3108a620b..000000000 Binary files a/test-data/spreadsheet/44636.xls and /dev/null differ diff --git a/test-data/spreadsheet/44643.xls b/test-data/spreadsheet/44643.xls deleted file mode 100644 index 7ae507186..000000000 Binary files a/test-data/spreadsheet/44643.xls and /dev/null differ diff --git a/test-data/spreadsheet/44693.xls b/test-data/spreadsheet/44693.xls deleted file mode 100644 index dd954c63d..000000000 Binary files a/test-data/spreadsheet/44693.xls and /dev/null differ diff --git a/test-data/spreadsheet/44840.xls b/test-data/spreadsheet/44840.xls deleted file mode 100644 index 66dd9185e..000000000 Binary files a/test-data/spreadsheet/44840.xls and /dev/null differ diff --git a/test-data/spreadsheet/44861.xls b/test-data/spreadsheet/44861.xls deleted file mode 100644 index bab82b313..000000000 Binary files a/test-data/spreadsheet/44861.xls and /dev/null differ diff --git a/test-data/spreadsheet/44891.xls b/test-data/spreadsheet/44891.xls deleted file mode 100644 index 30082aa8f..000000000 Binary files a/test-data/spreadsheet/44891.xls and /dev/null differ diff --git a/test-data/spreadsheet/44958.xls b/test-data/spreadsheet/44958.xls deleted file mode 100644 index c16701118..000000000 Binary files a/test-data/spreadsheet/44958.xls and /dev/null differ diff --git a/test-data/spreadsheet/44958_1.xls b/test-data/spreadsheet/44958_1.xls deleted file mode 100644 index c407c2f10..000000000 Binary files a/test-data/spreadsheet/44958_1.xls and /dev/null differ diff --git a/test-data/spreadsheet/45129.xls b/test-data/spreadsheet/45129.xls deleted file mode 100644 index c3c3a8af2..000000000 Binary files a/test-data/spreadsheet/45129.xls and /dev/null differ diff --git a/test-data/spreadsheet/45290.xls b/test-data/spreadsheet/45290.xls deleted file mode 100644 index dd064497a..000000000 Binary files a/test-data/spreadsheet/45290.xls and /dev/null differ diff --git a/test-data/spreadsheet/45322.xls b/test-data/spreadsheet/45322.xls deleted file mode 100644 index 711721400..000000000 Binary files a/test-data/spreadsheet/45322.xls and /dev/null differ diff --git a/test-data/spreadsheet/45365-2.xls b/test-data/spreadsheet/45365-2.xls deleted file mode 100644 index b5e66c1d7..000000000 Binary files a/test-data/spreadsheet/45365-2.xls and /dev/null differ diff --git a/test-data/spreadsheet/45365.xls b/test-data/spreadsheet/45365.xls deleted file mode 100644 index fbf1d97c5..000000000 Binary files a/test-data/spreadsheet/45365.xls and /dev/null differ diff --git a/test-data/spreadsheet/45430.xlsx b/test-data/spreadsheet/45430.xlsx deleted file mode 100644 index 48af3f9ce..000000000 Binary files a/test-data/spreadsheet/45430.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/45431.xlsm b/test-data/spreadsheet/45431.xlsm deleted file mode 100644 index fabbd0df3..000000000 Binary files a/test-data/spreadsheet/45431.xlsm and /dev/null differ diff --git a/test-data/spreadsheet/45492.xls b/test-data/spreadsheet/45492.xls deleted file mode 100644 index 7e044e897..000000000 Binary files a/test-data/spreadsheet/45492.xls and /dev/null differ diff --git a/test-data/spreadsheet/45538_classic_Footer.xls b/test-data/spreadsheet/45538_classic_Footer.xls deleted file mode 100644 index 2ab1d241c..000000000 Binary files a/test-data/spreadsheet/45538_classic_Footer.xls and /dev/null differ diff --git a/test-data/spreadsheet/45538_classic_Header.xls b/test-data/spreadsheet/45538_classic_Header.xls deleted file mode 100644 index fe67b84f8..000000000 Binary files a/test-data/spreadsheet/45538_classic_Header.xls and /dev/null differ diff --git a/test-data/spreadsheet/45538_form_Footer.xls b/test-data/spreadsheet/45538_form_Footer.xls deleted file mode 100644 index 6d1731d6a..000000000 Binary files a/test-data/spreadsheet/45538_form_Footer.xls and /dev/null differ diff --git a/test-data/spreadsheet/45538_form_Header.xls b/test-data/spreadsheet/45538_form_Header.xls deleted file mode 100644 index c2a28219c..000000000 Binary files a/test-data/spreadsheet/45538_form_Header.xls and /dev/null differ diff --git a/test-data/spreadsheet/45540_classic_Footer.xlsx b/test-data/spreadsheet/45540_classic_Footer.xlsx deleted file mode 100644 index dda1c10fb..000000000 Binary files a/test-data/spreadsheet/45540_classic_Footer.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/45540_classic_Header.xlsx b/test-data/spreadsheet/45540_classic_Header.xlsx deleted file mode 100644 index b01180bf5..000000000 Binary files a/test-data/spreadsheet/45540_classic_Header.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/45540_form_Footer.xlsx b/test-data/spreadsheet/45540_form_Footer.xlsx deleted file mode 100644 index c14dcbf24..000000000 Binary files a/test-data/spreadsheet/45540_form_Footer.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/45540_form_Header.xlsx b/test-data/spreadsheet/45540_form_Header.xlsx deleted file mode 100644 index 13df68631..000000000 Binary files a/test-data/spreadsheet/45540_form_Header.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/45544.xlsx b/test-data/spreadsheet/45544.xlsx deleted file mode 100644 index 2390e6d9a..000000000 Binary files a/test-data/spreadsheet/45544.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/45565.xls b/test-data/spreadsheet/45565.xls deleted file mode 100644 index 7facba52b..000000000 Binary files a/test-data/spreadsheet/45565.xls and /dev/null differ diff --git a/test-data/spreadsheet/45672.xls b/test-data/spreadsheet/45672.xls deleted file mode 100644 index 752ce5da0..000000000 Binary files a/test-data/spreadsheet/45672.xls and /dev/null differ diff --git a/test-data/spreadsheet/45720.xls b/test-data/spreadsheet/45720.xls deleted file mode 100644 index 9c6c484d6..000000000 Binary files a/test-data/spreadsheet/45720.xls and /dev/null differ diff --git a/test-data/spreadsheet/45761.xls b/test-data/spreadsheet/45761.xls deleted file mode 100644 index ee44612c4..000000000 Binary files a/test-data/spreadsheet/45761.xls and /dev/null differ diff --git a/test-data/spreadsheet/45784.xls b/test-data/spreadsheet/45784.xls deleted file mode 100644 index f0d25fddf..000000000 Binary files a/test-data/spreadsheet/45784.xls and /dev/null differ diff --git a/test-data/spreadsheet/45829.png b/test-data/spreadsheet/45829.png deleted file mode 100644 index eccaf30b2..000000000 Binary files a/test-data/spreadsheet/45829.png and /dev/null differ diff --git a/test-data/spreadsheet/46136-NoWarnings.xls b/test-data/spreadsheet/46136-NoWarnings.xls deleted file mode 100644 index 3a67049ae..000000000 Binary files a/test-data/spreadsheet/46136-NoWarnings.xls and /dev/null differ diff --git a/test-data/spreadsheet/46136-WithWarnings.xls b/test-data/spreadsheet/46136-WithWarnings.xls deleted file mode 100644 index c943b8259..000000000 Binary files a/test-data/spreadsheet/46136-WithWarnings.xls and /dev/null differ diff --git a/test-data/spreadsheet/46137.xls b/test-data/spreadsheet/46137.xls deleted file mode 100644 index 5fc399dd6..000000000 Binary files a/test-data/spreadsheet/46137.xls and /dev/null differ diff --git a/test-data/spreadsheet/46250.xls b/test-data/spreadsheet/46250.xls deleted file mode 100644 index 7260bf3c6..000000000 Binary files a/test-data/spreadsheet/46250.xls and /dev/null differ diff --git a/test-data/spreadsheet/46368.xls b/test-data/spreadsheet/46368.xls deleted file mode 100644 index d421e77de..000000000 Binary files a/test-data/spreadsheet/46368.xls and /dev/null differ diff --git a/test-data/spreadsheet/46445.xls b/test-data/spreadsheet/46445.xls deleted file mode 100644 index 30aaf343a..000000000 Binary files a/test-data/spreadsheet/46445.xls and /dev/null differ diff --git a/test-data/spreadsheet/46515.xls b/test-data/spreadsheet/46515.xls deleted file mode 100644 index 01c1dfe51..000000000 Binary files a/test-data/spreadsheet/46515.xls and /dev/null differ diff --git a/test-data/spreadsheet/46535.xlsx b/test-data/spreadsheet/46535.xlsx deleted file mode 100644 index 555145b07..000000000 Binary files a/test-data/spreadsheet/46535.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/46536.xlsx b/test-data/spreadsheet/46536.xlsx deleted file mode 100644 index 9b625bf36..000000000 Binary files a/test-data/spreadsheet/46536.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/46670_http.xls b/test-data/spreadsheet/46670_http.xls deleted file mode 100644 index 789284d61..000000000 Binary files a/test-data/spreadsheet/46670_http.xls and /dev/null differ diff --git a/test-data/spreadsheet/46670_local.xls b/test-data/spreadsheet/46670_local.xls deleted file mode 100644 index 0d73e63c6..000000000 Binary files a/test-data/spreadsheet/46670_local.xls and /dev/null differ diff --git a/test-data/spreadsheet/46670_ref_airline.xls b/test-data/spreadsheet/46670_ref_airline.xls deleted file mode 100644 index b0db5c935..000000000 Binary files a/test-data/spreadsheet/46670_ref_airline.xls and /dev/null differ diff --git a/test-data/spreadsheet/46904.xls b/test-data/spreadsheet/46904.xls deleted file mode 100644 index 5720672dd..000000000 Binary files a/test-data/spreadsheet/46904.xls and /dev/null differ diff --git a/test-data/spreadsheet/47026.xlsm b/test-data/spreadsheet/47026.xlsm deleted file mode 100644 index 77e4eb97f..000000000 Binary files a/test-data/spreadsheet/47026.xlsm and /dev/null differ diff --git a/test-data/spreadsheet/47034.xls b/test-data/spreadsheet/47034.xls deleted file mode 100644 index 81c5849e9..000000000 Binary files a/test-data/spreadsheet/47034.xls and /dev/null differ diff --git a/test-data/spreadsheet/47089.xlsm b/test-data/spreadsheet/47089.xlsm deleted file mode 100644 index 698f79b43..000000000 Binary files a/test-data/spreadsheet/47089.xlsm and /dev/null differ diff --git a/test-data/spreadsheet/47090.xlsx b/test-data/spreadsheet/47090.xlsx deleted file mode 100644 index c52ed666a..000000000 Binary files a/test-data/spreadsheet/47090.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/47154.xls b/test-data/spreadsheet/47154.xls deleted file mode 100644 index 2840cc61b..000000000 Binary files a/test-data/spreadsheet/47154.xls and /dev/null differ diff --git a/test-data/spreadsheet/47245_test.xls b/test-data/spreadsheet/47245_test.xls deleted file mode 100644 index 2e30bd5ec..000000000 Binary files a/test-data/spreadsheet/47245_test.xls and /dev/null differ diff --git a/test-data/spreadsheet/47251.xls b/test-data/spreadsheet/47251.xls deleted file mode 100644 index e498c2be0..000000000 Binary files a/test-data/spreadsheet/47251.xls and /dev/null differ diff --git a/test-data/spreadsheet/47251_1.xls b/test-data/spreadsheet/47251_1.xls deleted file mode 100644 index 7192fed26..000000000 Binary files a/test-data/spreadsheet/47251_1.xls and /dev/null differ diff --git a/test-data/spreadsheet/47504.xlsx b/test-data/spreadsheet/47504.xlsx deleted file mode 100644 index 8805a78ac..000000000 Binary files a/test-data/spreadsheet/47504.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/47668.xlsx b/test-data/spreadsheet/47668.xlsx deleted file mode 100644 index 74a073ff0..000000000 Binary files a/test-data/spreadsheet/47668.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/47701.xls b/test-data/spreadsheet/47701.xls deleted file mode 100644 index f6cf8a2d7..000000000 Binary files a/test-data/spreadsheet/47701.xls and /dev/null differ diff --git a/test-data/spreadsheet/47737.xlsx b/test-data/spreadsheet/47737.xlsx deleted file mode 100644 index 5737a595c..000000000 Binary files a/test-data/spreadsheet/47737.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/47804.xlsx b/test-data/spreadsheet/47804.xlsx deleted file mode 100644 index 7e1434628..000000000 Binary files a/test-data/spreadsheet/47804.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/47813.xlsx b/test-data/spreadsheet/47813.xlsx deleted file mode 100644 index 5ab22e304..000000000 Binary files a/test-data/spreadsheet/47813.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/47847.xls b/test-data/spreadsheet/47847.xls deleted file mode 100644 index 4a7a631d4..000000000 Binary files a/test-data/spreadsheet/47847.xls and /dev/null differ diff --git a/test-data/spreadsheet/47862.xlsx b/test-data/spreadsheet/47862.xlsx deleted file mode 100644 index d5d19c8ca..000000000 Binary files a/test-data/spreadsheet/47862.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/47889.xlsx b/test-data/spreadsheet/47889.xlsx deleted file mode 100644 index d4b23abc2..000000000 Binary files a/test-data/spreadsheet/47889.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/47920.xls b/test-data/spreadsheet/47920.xls deleted file mode 100644 index c01eabf85..000000000 Binary files a/test-data/spreadsheet/47920.xls and /dev/null differ diff --git a/test-data/spreadsheet/47924.xls b/test-data/spreadsheet/47924.xls deleted file mode 100644 index 287f17b6e..000000000 Binary files a/test-data/spreadsheet/47924.xls and /dev/null differ diff --git a/test-data/spreadsheet/48026.xls b/test-data/spreadsheet/48026.xls deleted file mode 100644 index 7463f753d..000000000 Binary files a/test-data/spreadsheet/48026.xls and /dev/null differ diff --git a/test-data/spreadsheet/48180.xls b/test-data/spreadsheet/48180.xls deleted file mode 100644 index be72749be..000000000 Binary files a/test-data/spreadsheet/48180.xls and /dev/null differ diff --git a/test-data/spreadsheet/48325.xls b/test-data/spreadsheet/48325.xls deleted file mode 100644 index 8b8c926fa..000000000 Binary files a/test-data/spreadsheet/48325.xls and /dev/null differ diff --git a/test-data/spreadsheet/48495.xlsx b/test-data/spreadsheet/48495.xlsx deleted file mode 100644 index 73bc28b8e..000000000 Binary files a/test-data/spreadsheet/48495.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/48539.xlsx b/test-data/spreadsheet/48539.xlsx deleted file mode 100644 index 848382d72..000000000 Binary files a/test-data/spreadsheet/48539.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/48703.xls b/test-data/spreadsheet/48703.xls deleted file mode 100644 index 95f19eb0f..000000000 Binary files a/test-data/spreadsheet/48703.xls and /dev/null differ diff --git a/test-data/spreadsheet/48703.xlsx b/test-data/spreadsheet/48703.xlsx deleted file mode 100644 index 258995345..000000000 Binary files a/test-data/spreadsheet/48703.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/48779.xlsx b/test-data/spreadsheet/48779.xlsx deleted file mode 100644 index 513230eab..000000000 Binary files a/test-data/spreadsheet/48779.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/48923.xlsx b/test-data/spreadsheet/48923.xlsx deleted file mode 100644 index 34aba5902..000000000 Binary files a/test-data/spreadsheet/48923.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/48936-strings.txt b/test-data/spreadsheet/48936-strings.txt deleted file mode 100644 index 2ceefe386..000000000 --- a/test-data/spreadsheet/48936-strings.txt +++ /dev/null @@ -1,81 +0,0 @@ -[IntegrityCheck-ERROR[MALE[50.0 < x < 199.0], FEMALE[50.0 < x < 199.0]], IntegrityCheck-WARNING[MALE[61.0 < x < 126.0], FEMALE[47.0 < x < 119.0]]] -Computing[($1 + $2 + $3)/3,[Instrument[BloodPressure, RES_FIRST_DIASTOLIC_BP], Instrument[BloodPressure, RES_SEC_DIASTOLIC_BP], Instrument[BloodPressure, RES_THIRD_DIASTOLIC_BP]]] -COMPUTED -BloodPressure -BloodPressure -Average Pulse Rate -Moyenne des lectures de pouls -Computing[($1 + $2 + $3)/3,[Instrument[BloodPressure, RES_FIRST_PULSE_RATE], Instrument[BloodPressure, RES_SEC_PULSE_RATE], Instrument[BloodPressure, RES_THIRD_PULSE_RATE]]] -COMPUTED -BloodPressure -BloodPressure -Average Systolic Blood Pressure -Pression artérielle systolique moyenne -Computing[($1 + $2 + $3)/3,[Instrument[BloodPressure, RES_FIRST_SYSTOLIC_BP], Instrument[BloodPressure, RES_SEC_SYSTOLIC_BP], Instrument[BloodPressure, RES_THIRD_SYSTOLIC_BP]]] -COMPUTED -BloodPressure -BloodPressure -BloodPressure -BloodPressure -BloodPressure -BloodPressure -BloodPressure -BloodPressure -BloodPressure -Armband size used -Taille du brassard utilisé -MANUAL -Small -Petit -Medium -Moyen -Large -Grand -Extra Large -Très grand -BloodPressure -BloodPressure -Arm suggested to be used for measurement -Bras suggéré pour la mesure -Variable[Onyx.CIPreliminaryQuestionnaire.BP_ARM_CHOSEN] -AUTOMATIC -false -BloodPressure -BloodPressure -What arm was actually used for the measurements? -Quel bras a été utilisé pour les mesures? -MANUAL -Left -Gauche -Right -Droit -BloodPressure -BloodPressure -Circumference of upper arm at midpoint -Circonférence du haut du bras -[IntegrityCheck-ERROR[MALE[17.0 < x < 50.0], FEMALE[17.0 < x < 50.0]]] -MANUAL -BloodPressure -BloodPressure -Diastolic Blood Pressure reading (1) -Lecture de la pression artérielle diastolique (1) -[IntegrityCheck-ERROR[MALE[30 < x < 200 || ], FEMALE[30 < x < 200 || ]], IntegrityCheck-WARNING[MALE[51 < x < 96 || ], FEMALE[51 < x < 96 || ]], IntegrityCheck-ERROR[x < RES_FIRST_SYSTOLIC_BP]] -MANUAL -BloodPressure -BloodPressure -Pulse Rate reading (1) -Lecture de pouls (1) -[IntegrityCheck-ERROR[MALE[30 < x < 200 || ], FEMALE[30 < x < 200 || ]], IntegrityCheck-WARNING[MALE[40 < x < 100 || ], FEMALE[40 < x < 100 || ]]] -MANUAL -BloodPressure -BloodPressure -Systolic Blood Pressure reading (1) -Lecture de la pression artérielle systolique (1) -[IntegrityCheck-ERROR[MALE[30 < x < 300 || ], FEMALE[30 < x < 300 || ]], IntegrityCheck-WARNING[MALE[77 < x < 192 || ], FEMALE[77 < x < 192 || ]]] -MANUAL -BloodPressure -BloodPressure -Diastolic Blood Pressure reading (2) -Lecture de la pression artérielle diastolique (2) -[IntegrityCheck-ERROR[MALE[30 < x < 200 || ], FEMALE[30 < x < 200 || ]], IntegrityCheck-WARNING[MALE[51 < x < 96 || ], FEMALE[51 < x < 96 || ]], IntegrityCheck-ERROR[x < RES_SEC_SYSTOLIC_BP]] - diff --git a/test-data/spreadsheet/48962.xlsx b/test-data/spreadsheet/48962.xlsx deleted file mode 100644 index 7d14f77f0..000000000 Binary files a/test-data/spreadsheet/48962.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/48968.xls b/test-data/spreadsheet/48968.xls deleted file mode 100644 index bbafffe9c..000000000 Binary files a/test-data/spreadsheet/48968.xls and /dev/null differ diff --git a/test-data/spreadsheet/49096.xls b/test-data/spreadsheet/49096.xls deleted file mode 100644 index 4c1e817b2..000000000 Binary files a/test-data/spreadsheet/49096.xls and /dev/null differ diff --git a/test-data/spreadsheet/49156.xlsx b/test-data/spreadsheet/49156.xlsx deleted file mode 100644 index ca41dc6bb..000000000 Binary files a/test-data/spreadsheet/49156.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/49185.xls b/test-data/spreadsheet/49185.xls deleted file mode 100644 index f40a83789..000000000 Binary files a/test-data/spreadsheet/49185.xls and /dev/null differ diff --git a/test-data/spreadsheet/49219.xls b/test-data/spreadsheet/49219.xls deleted file mode 100644 index 68605ea48..000000000 Binary files a/test-data/spreadsheet/49219.xls and /dev/null differ diff --git a/test-data/spreadsheet/49237.xls b/test-data/spreadsheet/49237.xls deleted file mode 100644 index bb525fda2..000000000 Binary files a/test-data/spreadsheet/49237.xls and /dev/null differ diff --git a/test-data/spreadsheet/49273.xlsx b/test-data/spreadsheet/49273.xlsx deleted file mode 100644 index ad1ad278d..000000000 Binary files a/test-data/spreadsheet/49273.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/49325.xlsx b/test-data/spreadsheet/49325.xlsx deleted file mode 100644 index adcba90b7..000000000 Binary files a/test-data/spreadsheet/49325.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/49423.xls b/test-data/spreadsheet/49423.xls deleted file mode 100644 index 3d8524cba..000000000 Binary files a/test-data/spreadsheet/49423.xls and /dev/null differ diff --git a/test-data/spreadsheet/49524.xls b/test-data/spreadsheet/49524.xls deleted file mode 100644 index ca9dde2d7..000000000 Binary files a/test-data/spreadsheet/49524.xls and /dev/null differ diff --git a/test-data/spreadsheet/49529.xls b/test-data/spreadsheet/49529.xls deleted file mode 100644 index 1989a6a1d..000000000 Binary files a/test-data/spreadsheet/49529.xls and /dev/null differ diff --git a/test-data/spreadsheet/49581.xls b/test-data/spreadsheet/49581.xls deleted file mode 100644 index d7fbf13b8..000000000 Binary files a/test-data/spreadsheet/49581.xls and /dev/null differ diff --git a/test-data/spreadsheet/49609.xlsx b/test-data/spreadsheet/49609.xlsx deleted file mode 100644 index 03d9d12ca..000000000 Binary files a/test-data/spreadsheet/49609.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/49612.xls b/test-data/spreadsheet/49612.xls deleted file mode 100644 index c31b62a13..000000000 Binary files a/test-data/spreadsheet/49612.xls and /dev/null differ diff --git a/test-data/spreadsheet/49751.xls b/test-data/spreadsheet/49751.xls deleted file mode 100644 index 09eaede14..000000000 Binary files a/test-data/spreadsheet/49751.xls and /dev/null differ diff --git a/test-data/spreadsheet/49761.xls b/test-data/spreadsheet/49761.xls deleted file mode 100644 index 948a0d117..000000000 Binary files a/test-data/spreadsheet/49761.xls and /dev/null differ diff --git a/test-data/spreadsheet/49783.xlsx b/test-data/spreadsheet/49783.xlsx deleted file mode 100644 index 09cda15b4..000000000 Binary files a/test-data/spreadsheet/49783.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/49872.xlsx b/test-data/spreadsheet/49872.xlsx deleted file mode 100644 index 04b72a857..000000000 Binary files a/test-data/spreadsheet/49872.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/49896.xls b/test-data/spreadsheet/49896.xls deleted file mode 100644 index 908340b81..000000000 Binary files a/test-data/spreadsheet/49896.xls and /dev/null differ diff --git a/test-data/spreadsheet/49928.xls b/test-data/spreadsheet/49928.xls deleted file mode 100644 index d7249e7bd..000000000 Binary files a/test-data/spreadsheet/49928.xls and /dev/null differ diff --git a/test-data/spreadsheet/49928.xlsx b/test-data/spreadsheet/49928.xlsx deleted file mode 100644 index 6a49ae3a7..000000000 Binary files a/test-data/spreadsheet/49928.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/49931.xls b/test-data/spreadsheet/49931.xls deleted file mode 100644 index 0ec10b0ba..000000000 Binary files a/test-data/spreadsheet/49931.xls and /dev/null differ diff --git a/test-data/spreadsheet/49966.xlsx b/test-data/spreadsheet/49966.xlsx deleted file mode 100644 index 9ccea41a8..000000000 Binary files a/test-data/spreadsheet/49966.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/50020.xls b/test-data/spreadsheet/50020.xls deleted file mode 100644 index 9f4001ef2..000000000 Binary files a/test-data/spreadsheet/50020.xls and /dev/null differ diff --git a/test-data/spreadsheet/50096.xlsx b/test-data/spreadsheet/50096.xlsx deleted file mode 100644 index b88784282..000000000 Binary files a/test-data/spreadsheet/50096.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/50298.xls b/test-data/spreadsheet/50298.xls deleted file mode 100644 index 99eb7643e..000000000 Binary files a/test-data/spreadsheet/50298.xls and /dev/null differ diff --git a/test-data/spreadsheet/50299.xlsx b/test-data/spreadsheet/50299.xlsx deleted file mode 100644 index 7a1acf3b1..000000000 Binary files a/test-data/spreadsheet/50299.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/50426.xls b/test-data/spreadsheet/50426.xls deleted file mode 100644 index 1a807f854..000000000 Binary files a/test-data/spreadsheet/50426.xls and /dev/null differ diff --git a/test-data/spreadsheet/50755_workday_formula_example.xlsx b/test-data/spreadsheet/50755_workday_formula_example.xlsx deleted file mode 100644 index c3ad479b5..000000000 Binary files a/test-data/spreadsheet/50755_workday_formula_example.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/50756.xls b/test-data/spreadsheet/50756.xls deleted file mode 100644 index f7e595dbf..000000000 Binary files a/test-data/spreadsheet/50756.xls and /dev/null differ diff --git a/test-data/spreadsheet/50779_1.xls b/test-data/spreadsheet/50779_1.xls deleted file mode 100644 index 17d32ece8..000000000 Binary files a/test-data/spreadsheet/50779_1.xls and /dev/null differ diff --git a/test-data/spreadsheet/50779_2.xls b/test-data/spreadsheet/50779_2.xls deleted file mode 100644 index ee29d0bc5..000000000 Binary files a/test-data/spreadsheet/50779_2.xls and /dev/null differ diff --git a/test-data/spreadsheet/50784-font_theme_colours.xlsx b/test-data/spreadsheet/50784-font_theme_colours.xlsx deleted file mode 100644 index 72e2dbbf1..000000000 Binary files a/test-data/spreadsheet/50784-font_theme_colours.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/50786-indexed_colours.xlsx b/test-data/spreadsheet/50786-indexed_colours.xlsx deleted file mode 100644 index df8bab6cd..000000000 Binary files a/test-data/spreadsheet/50786-indexed_colours.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/50795.xlsx b/test-data/spreadsheet/50795.xlsx deleted file mode 100644 index a58aeec7c..000000000 Binary files a/test-data/spreadsheet/50795.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/50833.xls b/test-data/spreadsheet/50833.xls deleted file mode 100644 index 00227789e..000000000 Binary files a/test-data/spreadsheet/50833.xls and /dev/null differ diff --git a/test-data/spreadsheet/50846-border_colours.xlsx b/test-data/spreadsheet/50846-border_colours.xlsx deleted file mode 100644 index 49ec5320f..000000000 Binary files a/test-data/spreadsheet/50846-border_colours.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/50867_with_table.xlsx b/test-data/spreadsheet/50867_with_table.xlsx deleted file mode 100644 index b42d6e496..000000000 Binary files a/test-data/spreadsheet/50867_with_table.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/50939.xls b/test-data/spreadsheet/50939.xls deleted file mode 100644 index bcc2068bb..000000000 Binary files a/test-data/spreadsheet/50939.xls and /dev/null differ diff --git a/test-data/spreadsheet/51143.xls b/test-data/spreadsheet/51143.xls deleted file mode 100644 index a89a10980..000000000 Binary files a/test-data/spreadsheet/51143.xls and /dev/null differ diff --git a/test-data/spreadsheet/51222.xlsx b/test-data/spreadsheet/51222.xlsx deleted file mode 100644 index 562154caf..000000000 Binary files a/test-data/spreadsheet/51222.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/51461.xls b/test-data/spreadsheet/51461.xls deleted file mode 100644 index 0f6c1bdfb..000000000 Binary files a/test-data/spreadsheet/51461.xls and /dev/null differ diff --git a/test-data/spreadsheet/51470.xlsx b/test-data/spreadsheet/51470.xlsx deleted file mode 100644 index 01768afde..000000000 Binary files a/test-data/spreadsheet/51470.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/51498.xls b/test-data/spreadsheet/51498.xls deleted file mode 100644 index b5d2d6599..000000000 Binary files a/test-data/spreadsheet/51498.xls and /dev/null differ diff --git a/test-data/spreadsheet/51519.xlsb b/test-data/spreadsheet/51519.xlsb deleted file mode 100644 index 54876cdb9..000000000 Binary files a/test-data/spreadsheet/51519.xlsb and /dev/null differ diff --git a/test-data/spreadsheet/51519.xlsx b/test-data/spreadsheet/51519.xlsx deleted file mode 100644 index ba56dc610..000000000 Binary files a/test-data/spreadsheet/51519.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/51535.xls b/test-data/spreadsheet/51535.xls deleted file mode 100644 index ab73352b8..000000000 Binary files a/test-data/spreadsheet/51535.xls and /dev/null differ diff --git a/test-data/spreadsheet/51585.xlsx b/test-data/spreadsheet/51585.xlsx deleted file mode 100644 index 479c8dbdc..000000000 Binary files a/test-data/spreadsheet/51585.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/51626.xlsx b/test-data/spreadsheet/51626.xlsx deleted file mode 100644 index 6a5e3ffa9..000000000 Binary files a/test-data/spreadsheet/51626.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/51626_contact.xlsx b/test-data/spreadsheet/51626_contact.xlsx deleted file mode 100644 index a3e4e5b7e..000000000 Binary files a/test-data/spreadsheet/51626_contact.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/51670.xls b/test-data/spreadsheet/51670.xls deleted file mode 100644 index e7c929d9e..000000000 Binary files a/test-data/spreadsheet/51670.xls and /dev/null differ diff --git a/test-data/spreadsheet/51675.xls b/test-data/spreadsheet/51675.xls deleted file mode 100644 index 78df32cb9..000000000 Binary files a/test-data/spreadsheet/51675.xls and /dev/null differ diff --git a/test-data/spreadsheet/51710.xlsx b/test-data/spreadsheet/51710.xlsx deleted file mode 100644 index 772395b4a..000000000 Binary files a/test-data/spreadsheet/51710.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/51832.xls b/test-data/spreadsheet/51832.xls deleted file mode 100644 index 8b38bffe8..000000000 Binary files a/test-data/spreadsheet/51832.xls and /dev/null differ diff --git a/test-data/spreadsheet/51850.xlsx b/test-data/spreadsheet/51850.xlsx deleted file mode 100644 index c04129afe..000000000 Binary files a/test-data/spreadsheet/51850.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/51963.xlsx b/test-data/spreadsheet/51963.xlsx deleted file mode 100644 index 154c75418..000000000 Binary files a/test-data/spreadsheet/51963.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/51998.xlsx b/test-data/spreadsheet/51998.xlsx deleted file mode 100644 index 835ba631c..000000000 Binary files a/test-data/spreadsheet/51998.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/52348.xlsx b/test-data/spreadsheet/52348.xlsx deleted file mode 100644 index 356490d8d..000000000 Binary files a/test-data/spreadsheet/52348.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/52425.xlsx b/test-data/spreadsheet/52425.xlsx deleted file mode 100644 index 0659822f6..000000000 Binary files a/test-data/spreadsheet/52425.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/52527.xls b/test-data/spreadsheet/52527.xls deleted file mode 100644 index b20d7d71e..000000000 Binary files a/test-data/spreadsheet/52527.xls and /dev/null differ diff --git a/test-data/spreadsheet/52575_main.xls b/test-data/spreadsheet/52575_main.xls deleted file mode 100644 index fbcf0dd65..000000000 Binary files a/test-data/spreadsheet/52575_main.xls and /dev/null differ diff --git a/test-data/spreadsheet/52575_main.xlsx b/test-data/spreadsheet/52575_main.xlsx deleted file mode 100644 index bec34c254..000000000 Binary files a/test-data/spreadsheet/52575_main.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/52575_source.xls b/test-data/spreadsheet/52575_source.xls deleted file mode 100644 index b75c14222..000000000 Binary files a/test-data/spreadsheet/52575_source.xls and /dev/null differ diff --git a/test-data/spreadsheet/52716.xlsx b/test-data/spreadsheet/52716.xlsx deleted file mode 100644 index ba4f120c7..000000000 Binary files a/test-data/spreadsheet/52716.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/53101.xlsx b/test-data/spreadsheet/53101.xlsx deleted file mode 100644 index e52f42433..000000000 Binary files a/test-data/spreadsheet/53101.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/53105.xlsx b/test-data/spreadsheet/53105.xlsx deleted file mode 100644 index 80ec056e4..000000000 Binary files a/test-data/spreadsheet/53105.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/53109.xls b/test-data/spreadsheet/53109.xls deleted file mode 100644 index 08b4dfeec..000000000 Binary files a/test-data/spreadsheet/53109.xls and /dev/null differ diff --git a/test-data/spreadsheet/53282.xlsx b/test-data/spreadsheet/53282.xlsx deleted file mode 100644 index 6d8830348..000000000 Binary files a/test-data/spreadsheet/53282.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/53282b.xlsx b/test-data/spreadsheet/53282b.xlsx deleted file mode 100644 index 3ad5ad865..000000000 Binary files a/test-data/spreadsheet/53282b.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/53404.xls b/test-data/spreadsheet/53404.xls deleted file mode 100644 index d436e1e86..000000000 Binary files a/test-data/spreadsheet/53404.xls and /dev/null differ diff --git a/test-data/spreadsheet/53433.xls b/test-data/spreadsheet/53433.xls deleted file mode 100644 index c31c3a877..000000000 Binary files a/test-data/spreadsheet/53433.xls and /dev/null differ diff --git a/test-data/spreadsheet/53446.xls b/test-data/spreadsheet/53446.xls deleted file mode 100644 index b33bd7aec..000000000 Binary files a/test-data/spreadsheet/53446.xls and /dev/null differ diff --git a/test-data/spreadsheet/53568.xlsx b/test-data/spreadsheet/53568.xlsx deleted file mode 100644 index 082333b5b..000000000 Binary files a/test-data/spreadsheet/53568.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/53588.xls b/test-data/spreadsheet/53588.xls deleted file mode 100644 index 716305b54..000000000 Binary files a/test-data/spreadsheet/53588.xls and /dev/null differ diff --git a/test-data/spreadsheet/53691.xls b/test-data/spreadsheet/53691.xls deleted file mode 100644 index 5c20dc54e..000000000 Binary files a/test-data/spreadsheet/53691.xls and /dev/null differ diff --git a/test-data/spreadsheet/53734.xlsx b/test-data/spreadsheet/53734.xlsx deleted file mode 100644 index 58aa49913..000000000 Binary files a/test-data/spreadsheet/53734.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/53798.xlsx b/test-data/spreadsheet/53798.xlsx deleted file mode 100644 index f273308ec..000000000 Binary files a/test-data/spreadsheet/53798.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/53798_shiftNegative_TMPL.xls b/test-data/spreadsheet/53798_shiftNegative_TMPL.xls deleted file mode 100644 index 1f9f48f42..000000000 Binary files a/test-data/spreadsheet/53798_shiftNegative_TMPL.xls and /dev/null differ diff --git a/test-data/spreadsheet/53798_shiftNegative_TMPL.xlsx b/test-data/spreadsheet/53798_shiftNegative_TMPL.xlsx deleted file mode 100644 index f273308ec..000000000 Binary files a/test-data/spreadsheet/53798_shiftNegative_TMPL.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/53972.xls b/test-data/spreadsheet/53972.xls deleted file mode 100644 index 5fd0ec91e..000000000 Binary files a/test-data/spreadsheet/53972.xls and /dev/null differ diff --git a/test-data/spreadsheet/53984.xls b/test-data/spreadsheet/53984.xls deleted file mode 100644 index 07d3e8337..000000000 Binary files a/test-data/spreadsheet/53984.xls and /dev/null differ diff --git a/test-data/spreadsheet/54016.xls b/test-data/spreadsheet/54016.xls deleted file mode 100644 index 4148ca790..000000000 Binary files a/test-data/spreadsheet/54016.xls and /dev/null differ diff --git a/test-data/spreadsheet/54034.xlsx b/test-data/spreadsheet/54034.xlsx deleted file mode 100644 index 2ae2bebef..000000000 Binary files a/test-data/spreadsheet/54034.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/54071.xlsx b/test-data/spreadsheet/54071.xlsx deleted file mode 100644 index be3a3e9b3..000000000 Binary files a/test-data/spreadsheet/54071.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/54084 - Greek - beyond BMP.txt b/test-data/spreadsheet/54084 - Greek - beyond BMP.txt deleted file mode 100644 index 11523527b..000000000 --- a/test-data/spreadsheet/54084 - Greek - beyond BMP.txt +++ /dev/null @@ -1 +0,0 @@ -𝝊𝝋𝝌𝝍𝝎𝝏𝝐𝝑𝝒𝝓𝝔𝝕𝝖𝝗𝝘𝝙𝝚𝝛𝝜𝝝𝝞𝝟𝝠𝝡𝝢𝝣𝝤𝝥𝝦𝝧𝝨𝝩𝝪𝝫𝝬𝝭𝝮𝝯𝝰𝝱𝝲𝝳𝝴𝝵𝝶𝝷𝝸𝝹𝝺 diff --git a/test-data/spreadsheet/54084 - Greek - beyond BMP.xlsx b/test-data/spreadsheet/54084 - Greek - beyond BMP.xlsx deleted file mode 100644 index bc2772286..000000000 Binary files a/test-data/spreadsheet/54084 - Greek - beyond BMP.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/54206.xls b/test-data/spreadsheet/54206.xls deleted file mode 100644 index 24da03b37..000000000 Binary files a/test-data/spreadsheet/54206.xls and /dev/null differ diff --git a/test-data/spreadsheet/54206.xlsx b/test-data/spreadsheet/54206.xlsx deleted file mode 100644 index bd8be74a0..000000000 Binary files a/test-data/spreadsheet/54206.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/54288-ref.xlsx b/test-data/spreadsheet/54288-ref.xlsx deleted file mode 100644 index eb2f8396c..000000000 Binary files a/test-data/spreadsheet/54288-ref.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/54288.xlsx b/test-data/spreadsheet/54288.xlsx deleted file mode 100644 index fed0b4bed..000000000 Binary files a/test-data/spreadsheet/54288.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/54399.xlsx b/test-data/spreadsheet/54399.xlsx deleted file mode 100644 index 1aefbac59..000000000 Binary files a/test-data/spreadsheet/54399.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/54436.xlsx b/test-data/spreadsheet/54436.xlsx deleted file mode 100644 index 4f113b8b7..000000000 Binary files a/test-data/spreadsheet/54436.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/54500.xls b/test-data/spreadsheet/54500.xls deleted file mode 100644 index 0cd18b51d..000000000 Binary files a/test-data/spreadsheet/54500.xls and /dev/null differ diff --git a/test-data/spreadsheet/54524.xlsx b/test-data/spreadsheet/54524.xlsx deleted file mode 100644 index 5a16447e0..000000000 Binary files a/test-data/spreadsheet/54524.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/54607.xlsx b/test-data/spreadsheet/54607.xlsx deleted file mode 100644 index bdfe143bb..000000000 Binary files a/test-data/spreadsheet/54607.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/54686_fraction_formats.txt b/test-data/spreadsheet/54686_fraction_formats.txt deleted file mode 100644 index 0de773efb..000000000 --- a/test-data/spreadsheet/54686_fraction_formats.txt +++ /dev/null @@ -1,374 +0,0 @@ -Numerator Denominator Double 1Digit 2Digit 3Digit Half Quarter Eight Sixteenth Tenth 100th Tika-1132 -4051 8750153 0.000462963 0 0 0 0 0 0 0 0 0 4051/8750153 --105 100 -1.05 -1 -1 1/20 -1 1/20 -1 -1 -1 -1 1/16 -1 1/10 -1 5/100 -1 1/20 --104 100 -1.04 -1 -1 1/25 -1 1/25 -1 -1 -1 -1 1/16 -1 -1 4/100 -1 1/25 --103 100 -1.03 -1 -1 1/33 -1 3/100 -1 -1 -1 -1 -1 -1 3/100 -1 3/100 --102 100 -1.02 -1 -1 1/50 -1 1/50 -1 -1 -1 -1 -1 -1 2/100 -1 1/50 --101 100 -1.01 -1 -1 1/99 -1 1/100 -1 -1 -1 -1 -1 -1 1/100 -1 1/100 --100 100 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 --99 100 -0.99 -1 - 98/99 - 99/100 -1 -1 -1 -1 -1 - 99/100 - 99/100 --98 100 -0.98 -1 - 49/50 - 49/50 -1 -1 -1 -1 -1 - 98/100 - 49/50 --97 100 -0.97 -1 - 32/33 - 97/100 -1 -1 -1 -1 -1 - 97/100 - 97/100 --96 100 -0.96 -1 - 24/25 - 24/25 -1 -1 -1 - 15/16 -1 - 96/100 - 24/25 --95 100 -0.95 -1 - 19/20 - 19/20 -1 -1 -1 - 15/16 -1 - 95/100 - 19/20 --94 100 -0.94 -1 - 47/50 - 47/50 -1 -1 -1 - 15/16 - 9/10 - 94/100 - 47/50 --93 100 -0.93 -1 - 40/43 - 93/100 -1 -1 - 7/8 - 15/16 - 9/10 - 93/100 - 93/100 --92 100 -0.92 -1 - 23/25 - 23/25 -1 -1 - 7/8 - 15/16 - 9/10 - 92/100 - 23/25 --91 100 -0.91 -1 - 81/89 - 91/100 -1 -1 - 7/8 - 15/16 - 9/10 - 91/100 - 91/100 --90 100 -0.9 - 8/9 - 9/10 - 9/10 -1 -1 - 7/8 - 14/16 - 9/10 - 90/100 - 9/10 --89 100 -0.89 - 8/9 - 8/9 - 89/100 -1 -1 - 7/8 - 14/16 - 9/10 - 89/100 - 89/100 --88 100 -0.88 - 7/8 - 22/25 - 22/25 -1 -1 - 7/8 - 14/16 - 9/10 - 88/100 - 22/25 --87 100 -0.87 - 7/8 - 67/77 - 87/100 -1 - 3/4 - 7/8 - 14/16 - 9/10 - 87/100 - 87/100 --86 100 -0.86 - 6/7 - 43/50 - 43/50 -1 - 3/4 - 7/8 - 14/16 - 9/10 - 86/100 - 43/50 --85 100 -0.85 - 6/7 - 17/20 - 17/20 -1 - 3/4 - 7/8 - 14/16 - 9/10 - 85/100 - 17/20 --84 100 -0.84 - 5/6 - 21/25 - 21/25 -1 - 3/4 - 7/8 - 13/16 - 8/10 - 84/100 - 21/25 --83 100 -0.83 - 5/6 - 39/47 - 83/100 -1 - 3/4 - 7/8 - 13/16 - 8/10 - 83/100 - 83/100 --82 100 -0.82 - 5/6 - 41/50 - 41/50 -1 - 3/4 - 7/8 - 13/16 - 8/10 - 82/100 - 41/50 --81 100 -0.81 - 4/5 - 64/79 - 81/100 -1 - 3/4 - 6/8 - 13/16 - 8/10 - 81/100 - 81/100 --80 100 -0.8 - 4/5 - 4/5 - 4/5 -1 - 3/4 - 6/8 - 13/16 - 8/10 - 80/100 - 4/5 --79 100 -0.79 - 4/5 - 64/81 - 79/100 -1 - 3/4 - 6/8 - 13/16 - 8/10 - 79/100 - 79/100 --78 100 -0.78 - 7/9 - 39/50 - 39/50 -1 - 3/4 - 6/8 - 12/16 - 8/10 - 78/100 - 39/50 --77 100 -0.77 - 7/9 - 67/87 - 77/100 -1 - 3/4 - 6/8 - 12/16 - 8/10 - 77/100 - 77/100 --76 100 -0.76 - 3/4 - 19/25 - 19/25 -1 - 3/4 - 6/8 - 12/16 - 8/10 - 76/100 - 19/25 --75 100 -0.75 - 3/4 - 3/4 - 3/4 -1 - 3/4 - 6/8 - 12/16 - 8/10 - 75/100 - 3/4 --74 100 -0.74 - 3/4 - 37/50 - 37/50 - 1/2 - 3/4 - 6/8 - 12/16 - 7/10 - 74/100 - 37/50 --73 100 -0.73 - 3/4 - 46/63 - 73/100 - 1/2 - 3/4 - 6/8 - 12/16 - 7/10 - 73/100 - 73/100 --72 100 -0.72 - 5/7 - 18/25 - 18/25 - 1/2 - 3/4 - 6/8 - 12/16 - 7/10 - 72/100 - 18/25 --71 100 -0.71 - 5/7 - 22/31 - 71/100 - 1/2 - 3/4 - 6/8 - 11/16 - 7/10 - 71/100 - 71/100 --70 100 -0.7 - 2/3 - 7/10 - 7/10 - 1/2 - 3/4 - 6/8 - 11/16 - 7/10 - 70/100 - 7/10 --69 100 -0.69 - 2/3 - 20/29 - 69/100 - 1/2 - 3/4 - 6/8 - 11/16 - 7/10 - 69/100 - 69/100 --68 100 -0.68 - 2/3 - 17/25 - 17/25 - 1/2 - 3/4 - 5/8 - 11/16 - 7/10 - 68/100 - 17/25 --67 100 -0.67 - 2/3 - 65/97 - 67/100 - 1/2 - 3/4 - 5/8 - 11/16 - 7/10 - 67/100 - 67/100 --66 100 -0.66 - 2/3 - 33/50 - 33/50 - 1/2 - 3/4 - 5/8 - 11/16 - 7/10 - 66/100 - 33/50 --65 100 -0.65 - 2/3 - 13/20 - 13/20 - 1/2 - 3/4 - 5/8 - 10/16 - 7/10 - 65/100 - 13/20 --64 100 -0.64 - 2/3 - 16/25 - 16/25 - 1/2 - 3/4 - 5/8 - 10/16 - 6/10 - 64/100 - 16/25 --63 100 -0.63 - 5/8 - 46/73 - 63/100 - 1/2 - 3/4 - 5/8 - 10/16 - 6/10 - 63/100 - 63/100 --62 100 -0.62 - 5/8 - 31/50 - 31/50 - 1/2 - 2/4 - 5/8 - 10/16 - 6/10 - 62/100 - 31/50 --61 100 -0.61 - 3/5 - 36/59 - 61/100 - 1/2 - 2/4 - 5/8 - 10/16 - 6/10 - 61/100 - 61/100 --60 100 -0.6 - 3/5 - 3/5 - 3/5 - 1/2 - 2/4 - 5/8 - 10/16 - 6/10 - 60/100 - 3/5 --59 100 -0.59 - 3/5 - 23/39 - 59/100 - 1/2 - 2/4 - 5/8 - 9/16 - 6/10 - 59/100 - 59/100 --58 100 -0.58 - 4/7 - 29/50 - 29/50 - 1/2 - 2/4 - 5/8 - 9/16 - 6/10 - 58/100 - 29/50 --57 100 -0.57 - 4/7 - 53/93 - 57/100 - 1/2 - 2/4 - 5/8 - 9/16 - 6/10 - 57/100 - 57/100 --56 100 -0.56 - 5/9 - 14/25 - 14/25 - 1/2 - 2/4 - 4/8 - 9/16 - 6/10 - 56/100 - 14/25 --55 100 -0.55 - 5/9 - 11/20 - 11/20 - 1/2 - 2/4 - 4/8 - 9/16 - 6/10 - 55/100 - 11/20 --54 100 -0.54 - 1/2 - 27/50 - 27/50 - 1/2 - 2/4 - 4/8 - 9/16 - 5/10 - 54/100 - 27/50 --53 100 -0.53 - 1/2 - 44/83 - 53/100 - 1/2 - 2/4 - 4/8 - 8/16 - 5/10 - 53/100 - 53/100 --52 100 -0.52 - 1/2 - 13/25 - 13/25 - 1/2 - 2/4 - 4/8 - 8/16 - 5/10 - 52/100 - 13/25 --51 100 -0.51 - 1/2 - 25/49 - 51/100 - 1/2 - 2/4 - 4/8 - 8/16 - 5/10 - 51/100 - 51/100 --50 100 -0.5 - 1/2 - 1/2 - 1/2 - 1/2 - 2/4 - 4/8 - 8/16 - 5/10 - 50/100 - 1/2 --49 100 -0.49 - 1/2 - 24/49 - 49/100 - 1/2 - 2/4 - 4/8 - 8/16 - 5/10 - 49/100 - 49/100 --48 100 -0.48 - 1/2 - 12/25 - 12/25 - 1/2 - 2/4 - 4/8 - 8/16 - 5/10 - 48/100 - 12/25 --47 100 -0.47 - 1/2 - 8/17 - 47/100 - 1/2 - 2/4 - 4/8 - 8/16 - 5/10 - 47/100 - 47/100 --46 100 -0.46 - 1/2 - 23/50 - 23/50 - 1/2 - 2/4 - 4/8 - 7/16 - 5/10 - 46/100 - 23/50 --45 100 -0.45 - 4/9 - 9/20 - 9/20 - 1/2 - 2/4 - 4/8 - 7/16 - 5/10 - 45/100 - 9/20 --44 100 -0.44 - 4/9 - 11/25 - 11/25 - 1/2 - 2/4 - 4/8 - 7/16 - 4/10 - 44/100 - 11/25 --43 100 -0.43 - 3/7 - 3/7 - 43/100 - 1/2 - 2/4 - 3/8 - 7/16 - 4/10 - 43/100 - 43/100 --42 100 -0.42 - 3/7 - 21/50 - 21/50 - 1/2 - 2/4 - 3/8 - 7/16 - 4/10 - 42/100 - 21/50 --41 100 -0.41 - 2/5 - 16/39 - 41/100 - 1/2 - 2/4 - 3/8 - 7/16 - 4/10 - 41/100 - 41/100 --40 100 -0.4 - 2/5 - 2/5 - 2/5 - 1/2 - 2/4 - 3/8 - 6/16 - 4/10 - 40/100 - 2/5 --39 100 -0.39 - 2/5 - 16/41 - 39/100 - 1/2 - 2/4 - 3/8 - 6/16 - 4/10 - 39/100 - 39/100 --38 100 -0.38 - 3/8 - 19/50 - 19/50 - 1/2 - 2/4 - 3/8 - 6/16 - 4/10 - 38/100 - 19/50 --37 100 -0.37 - 3/8 - 10/27 - 37/100 - 1/2 - 1/4 - 3/8 - 6/16 - 4/10 - 37/100 - 37/100 --36 100 -0.36 - 1/3 - 9/25 - 9/25 - 1/2 - 1/4 - 3/8 - 6/16 - 4/10 - 36/100 - 9/25 --35 100 -0.35 - 1/3 - 7/20 - 7/20 - 1/2 - 1/4 - 3/8 - 6/16 - 4/10 - 35/100 - 7/20 --34 100 -0.34 - 1/3 - 17/50 - 17/50 - 1/2 - 1/4 - 3/8 - 5/16 - 3/10 - 34/100 - 17/50 --33 100 -0.33 - 1/3 - 1/3 - 33/100 - 1/2 - 1/4 - 3/8 - 5/16 - 3/10 - 33/100 - 33/100 --32 100 -0.32 - 1/3 - 8/25 - 8/25 - 1/2 - 1/4 - 3/8 - 5/16 - 3/10 - 32/100 - 8/25 --31 100 -0.31 - 1/3 - 22/71 - 31/100 - 1/2 - 1/4 - 2/8 - 5/16 - 3/10 - 31/100 - 31/100 --30 100 -0.3 - 2/7 - 3/10 - 3/10 - 1/2 - 1/4 - 2/8 - 5/16 - 3/10 - 30/100 - 3/10 --29 100 -0.29 - 2/7 - 20/69 - 29/100 - 1/2 - 1/4 - 2/8 - 5/16 - 3/10 - 29/100 - 29/100 --28 100 -0.28 - 2/7 - 7/25 - 7/25 - 1/2 - 1/4 - 2/8 - 4/16 - 3/10 - 28/100 - 7/25 --27 100 -0.27 - 1/4 - 10/37 - 27/100 - 1/2 - 1/4 - 2/8 - 4/16 - 3/10 - 27/100 - 27/100 --26 100 -0.26 - 1/4 - 13/50 - 13/50 - 1/2 - 1/4 - 2/8 - 4/16 - 3/10 - 26/100 - 13/50 --25 100 -0.25 - 1/4 - 1/4 - 1/4 - 1/2 - 1/4 - 2/8 - 4/16 - 3/10 - 25/100 - 1/4 --24 100 -0.24 - 1/4 - 6/25 - 6/25 -0 - 1/4 - 2/8 - 4/16 - 2/10 - 24/100 - 6/25 --23 100 -0.23 - 2/9 - 3/13 - 23/100 -0 - 1/4 - 2/8 - 4/16 - 2/10 - 23/100 - 23/100 --22 100 -0.22 - 2/9 - 11/50 - 11/50 -0 - 1/4 - 2/8 - 4/16 - 2/10 - 22/100 - 11/50 --21 100 -0.21 - 1/5 - 17/81 - 21/100 -0 - 1/4 - 2/8 - 3/16 - 2/10 - 21/100 - 21/100 --20 100 -0.2 - 1/5 - 1/5 - 1/5 -0 - 1/4 - 2/8 - 3/16 - 2/10 - 20/100 - 1/5 --19 100 -0.19 - 1/5 - 15/79 - 19/100 -0 - 1/4 - 2/8 - 3/16 - 2/10 - 19/100 - 19/100 --18 100 -0.18 - 1/6 - 9/50 - 9/50 -0 - 1/4 - 1/8 - 3/16 - 2/10 - 18/100 - 9/50 --17 100 -0.17 - 1/6 - 8/47 - 17/100 -0 - 1/4 - 1/8 - 3/16 - 2/10 - 17/100 - 17/100 --16 100 -0.16 - 1/6 - 4/25 - 4/25 -0 - 1/4 - 1/8 - 3/16 - 2/10 - 16/100 - 4/25 --15 100 -0.15 - 1/7 - 3/20 - 3/20 -0 - 1/4 - 1/8 - 2/16 - 2/10 - 15/100 - 3/20 --14 100 -0.14 - 1/7 - 7/50 - 7/50 -0 - 1/4 - 1/8 - 2/16 - 1/10 - 14/100 - 7/50 --13 100 -0.13 - 1/8 - 3/23 - 13/100 -0 - 1/4 - 1/8 - 2/16 - 1/10 - 13/100 - 13/100 --12 100 -0.12 - 1/8 - 3/25 - 3/25 -0 -0 - 1/8 - 2/16 - 1/10 - 12/100 - 3/25 --11 100 -0.11 - 1/9 - 10/91 - 11/100 -0 -0 - 1/8 - 2/16 - 1/10 - 11/100 - 11/100 --10 100 -0.1 -0 - 1/10 - 1/10 -0 -0 - 1/8 - 2/16 - 1/10 - 10/100 - 1/10 --9 100 -0.09 -0 - 1/11 - 9/100 -0 -0 - 1/8 - 1/16 - 1/10 - 9/100 - 9/100 --8 100 -0.08 -0 - 2/25 - 2/25 -0 -0 - 1/8 - 1/16 - 1/10 - 8/100 - 2/25 --7 100 -0.07 -0 - 4/57 - 7/100 -0 -0 - 1/8 - 1/16 - 1/10 - 7/100 - 7/100 --6 100 -0.06 -0 - 3/50 - 3/50 -0 -0 -0 - 1/16 - 1/10 - 6/100 - 3/50 --5 100 -0.05 -0 - 1/20 - 1/20 -0 -0 -0 - 1/16 - 1/10 - 5/100 - 1/20 --4 100 -0.04 -0 - 1/25 - 1/25 -0 -0 -0 - 1/16 -0 - 4/100 - 1/25 --3 100 -0.03 -0 - 2/67 - 3/100 -0 -0 -0 -0 -0 - 3/100 - 3/100 --2 100 -0.02 -0 - 1/50 - 1/50 -0 -0 -0 -0 -0 - 2/100 - 1/50 --1 100 -0.01 -0 -0 - 1/100 -0 -0 -0 -0 -0 - 1/100 - 1/100 -0 100 0 0 0 0 0 0 0 0 0 0 0 -1 100 0.01 0 0 1/100 0 0 0 0 0 1/100 1/100 -2 100 0.02 0 1/50 1/50 0 0 0 0 0 2/100 1/50 -3 100 0.03 0 2/67 3/100 0 0 0 0 0 3/100 3/100 -4 100 0.04 0 1/25 1/25 0 0 0 1/16 0 4/100 1/25 -5 100 0.05 0 1/20 1/20 0 0 0 1/16 1/10 5/100 1/20 -6 100 0.06 0 3/50 3/50 0 0 0 1/16 1/10 6/100 3/50 -7 100 0.07 0 4/57 7/100 0 0 1/8 1/16 1/10 7/100 7/100 -8 100 0.08 0 2/25 2/25 0 0 1/8 1/16 1/10 8/100 2/25 -9 100 0.09 0 1/11 9/100 0 0 1/8 1/16 1/10 9/100 9/100 -10 100 0.1 0 1/10 1/10 0 0 1/8 2/16 1/10 10/100 1/10 -11 100 0.11 1/9 10/91 11/100 0 0 1/8 2/16 1/10 11/100 11/100 -12 100 0.12 1/8 3/25 3/25 0 0 1/8 2/16 1/10 12/100 3/25 -13 100 0.13 1/8 3/23 13/100 0 1/4 1/8 2/16 1/10 13/100 13/100 -14 100 0.14 1/7 7/50 7/50 0 1/4 1/8 2/16 1/10 14/100 7/50 -15 100 0.15 1/7 3/20 3/20 0 1/4 1/8 2/16 2/10 15/100 3/20 -16 100 0.16 1/6 4/25 4/25 0 1/4 1/8 3/16 2/10 16/100 4/25 -17 100 0.17 1/6 8/47 17/100 0 1/4 1/8 3/16 2/10 17/100 17/100 -18 100 0.18 1/6 9/50 9/50 0 1/4 1/8 3/16 2/10 18/100 9/50 -19 100 0.19 1/5 15/79 19/100 0 1/4 2/8 3/16 2/10 19/100 19/100 -20 100 0.2 1/5 1/5 1/5 0 1/4 2/8 3/16 2/10 20/100 1/5 -21 100 0.21 1/5 17/81 21/100 0 1/4 2/8 3/16 2/10 21/100 21/100 -22 100 0.22 2/9 11/50 11/50 0 1/4 2/8 4/16 2/10 22/100 11/50 -23 100 0.23 2/9 3/13 23/100 0 1/4 2/8 4/16 2/10 23/100 23/100 -24 100 0.24 1/4 6/25 6/25 0 1/4 2/8 4/16 2/10 24/100 6/25 -25 100 0.25 1/4 1/4 1/4 1/2 1/4 2/8 4/16 3/10 25/100 1/4 -26 100 0.26 1/4 13/50 13/50 1/2 1/4 2/8 4/16 3/10 26/100 13/50 -27 100 0.27 1/4 10/37 27/100 1/2 1/4 2/8 4/16 3/10 27/100 27/100 -28 100 0.28 2/7 7/25 7/25 1/2 1/4 2/8 4/16 3/10 28/100 7/25 -29 100 0.29 2/7 20/69 29/100 1/2 1/4 2/8 5/16 3/10 29/100 29/100 -30 100 0.3 2/7 3/10 3/10 1/2 1/4 2/8 5/16 3/10 30/100 3/10 -31 100 0.31 1/3 22/71 31/100 1/2 1/4 2/8 5/16 3/10 31/100 31/100 -32 100 0.32 1/3 8/25 8/25 1/2 1/4 3/8 5/16 3/10 32/100 8/25 -33 100 0.33 1/3 1/3 33/100 1/2 1/4 3/8 5/16 3/10 33/100 33/100 -34 100 0.34 1/3 17/50 17/50 1/2 1/4 3/8 5/16 3/10 34/100 17/50 -35 100 0.35 1/3 7/20 7/20 1/2 1/4 3/8 6/16 4/10 35/100 7/20 -36 100 0.36 1/3 9/25 9/25 1/2 1/4 3/8 6/16 4/10 36/100 9/25 -37 100 0.37 3/8 10/27 37/100 1/2 1/4 3/8 6/16 4/10 37/100 37/100 -38 100 0.38 3/8 19/50 19/50 1/2 2/4 3/8 6/16 4/10 38/100 19/50 -39 100 0.39 2/5 16/41 39/100 1/2 2/4 3/8 6/16 4/10 39/100 39/100 -40 100 0.4 2/5 2/5 2/5 1/2 2/4 3/8 6/16 4/10 40/100 2/5 -41 100 0.41 2/5 16/39 41/100 1/2 2/4 3/8 7/16 4/10 41/100 41/100 -42 100 0.42 3/7 21/50 21/50 1/2 2/4 3/8 7/16 4/10 42/100 21/50 -43 100 0.43 3/7 3/7 43/100 1/2 2/4 3/8 7/16 4/10 43/100 43/100 -44 100 0.44 4/9 11/25 11/25 1/2 2/4 4/8 7/16 4/10 44/100 11/25 -45 100 0.45 4/9 9/20 9/20 1/2 2/4 4/8 7/16 5/10 45/100 9/20 -46 100 0.46 1/2 23/50 23/50 1/2 2/4 4/8 7/16 5/10 46/100 23/50 -47 100 0.47 1/2 8/17 47/100 1/2 2/4 4/8 8/16 5/10 47/100 47/100 -48 100 0.48 1/2 12/25 12/25 1/2 2/4 4/8 8/16 5/10 48/100 12/25 -49 100 0.49 1/2 24/49 49/100 1/2 2/4 4/8 8/16 5/10 49/100 49/100 -50 100 0.5 1/2 1/2 1/2 1/2 2/4 4/8 8/16 5/10 50/100 1/2 -51 100 0.51 1/2 25/49 51/100 1/2 2/4 4/8 8/16 5/10 51/100 51/100 -52 100 0.52 1/2 13/25 13/25 1/2 2/4 4/8 8/16 5/10 52/100 13/25 -53 100 0.53 1/2 44/83 53/100 1/2 2/4 4/8 8/16 5/10 53/100 53/100 -54 100 0.54 1/2 27/50 27/50 1/2 2/4 4/8 9/16 5/10 54/100 27/50 -55 100 0.55 5/9 11/20 11/20 1/2 2/4 4/8 9/16 6/10 55/100 11/20 -56 100 0.56 5/9 14/25 14/25 1/2 2/4 4/8 9/16 6/10 56/100 14/25 -57 100 0.57 4/7 53/93 57/100 1/2 2/4 5/8 9/16 6/10 57/100 57/100 -58 100 0.58 4/7 29/50 29/50 1/2 2/4 5/8 9/16 6/10 58/100 29/50 -59 100 0.59 3/5 23/39 59/100 1/2 2/4 5/8 9/16 6/10 59/100 59/100 -60 100 0.6 3/5 3/5 3/5 1/2 2/4 5/8 10/16 6/10 60/100 3/5 -61 100 0.61 3/5 36/59 61/100 1/2 2/4 5/8 10/16 6/10 61/100 61/100 -62 100 0.62 5/8 31/50 31/50 1/2 2/4 5/8 10/16 6/10 62/100 31/50 -63 100 0.63 5/8 46/73 63/100 1/2 3/4 5/8 10/16 6/10 63/100 63/100 -64 100 0.64 2/3 16/25 16/25 1/2 3/4 5/8 10/16 6/10 64/100 16/25 -65 100 0.65 2/3 13/20 13/20 1/2 3/4 5/8 10/16 7/10 65/100 13/20 -66 100 0.66 2/3 33/50 33/50 1/2 3/4 5/8 11/16 7/10 66/100 33/50 -67 100 0.67 2/3 65/97 67/100 1/2 3/4 5/8 11/16 7/10 67/100 67/100 -68 100 0.68 2/3 17/25 17/25 1/2 3/4 5/8 11/16 7/10 68/100 17/25 -69 100 0.69 2/3 20/29 69/100 1/2 3/4 6/8 11/16 7/10 69/100 69/100 -70 100 0.7 2/3 7/10 7/10 1/2 3/4 6/8 11/16 7/10 70/100 7/10 -71 100 0.71 5/7 22/31 71/100 1/2 3/4 6/8 11/16 7/10 71/100 71/100 -72 100 0.72 5/7 18/25 18/25 1/2 3/4 6/8 12/16 7/10 72/100 18/25 -73 100 0.73 3/4 46/63 73/100 1/2 3/4 6/8 12/16 7/10 73/100 73/100 -74 100 0.74 3/4 37/50 37/50 1/2 3/4 6/8 12/16 7/10 74/100 37/50 -75 100 0.75 3/4 3/4 3/4 1 3/4 6/8 12/16 8/10 75/100 3/4 -76 100 0.76 3/4 19/25 19/25 1 3/4 6/8 12/16 8/10 76/100 19/25 -77 100 0.77 7/9 67/87 77/100 1 3/4 6/8 12/16 8/10 77/100 77/100 -78 100 0.78 7/9 39/50 39/50 1 3/4 6/8 12/16 8/10 78/100 39/50 -79 100 0.79 4/5 64/81 79/100 1 3/4 6/8 13/16 8/10 79/100 79/100 -80 100 0.8 4/5 4/5 4/5 1 3/4 6/8 13/16 8/10 80/100 4/5 -81 100 0.81 4/5 64/79 81/100 1 3/4 6/8 13/16 8/10 81/100 81/100 -82 100 0.82 5/6 41/50 41/50 1 3/4 7/8 13/16 8/10 82/100 41/50 -83 100 0.83 5/6 39/47 83/100 1 3/4 7/8 13/16 8/10 83/100 83/100 -84 100 0.84 5/6 21/25 21/25 1 3/4 7/8 13/16 8/10 84/100 21/25 -85 100 0.85 6/7 17/20 17/20 1 3/4 7/8 14/16 9/10 85/100 17/20 -86 100 0.86 6/7 43/50 43/50 1 3/4 7/8 14/16 9/10 86/100 43/50 -87 100 0.87 7/8 67/77 87/100 1 3/4 7/8 14/16 9/10 87/100 87/100 -88 100 0.88 7/8 22/25 22/25 1 1 7/8 14/16 9/10 88/100 22/25 -89 100 0.89 8/9 8/9 89/100 1 1 7/8 14/16 9/10 89/100 89/100 -90 100 0.9 8/9 9/10 9/10 1 1 7/8 14/16 9/10 90/100 9/10 -91 100 0.91 1 81/89 91/100 1 1 7/8 15/16 9/10 91/100 91/100 -92 100 0.92 1 23/25 23/25 1 1 7/8 15/16 9/10 92/100 23/25 -93 100 0.93 1 40/43 93/100 1 1 7/8 15/16 9/10 93/100 93/100 -94 100 0.94 1 47/50 47/50 1 1 1 15/16 9/10 94/100 47/50 -95 100 0.95 1 19/20 19/20 1 1 1 15/16 1 95/100 19/20 -96 100 0.96 1 24/25 24/25 1 1 1 15/16 1 96/100 24/25 -97 100 0.97 1 32/33 97/100 1 1 1 1 1 97/100 97/100 -98 100 0.98 1 49/50 49/50 1 1 1 1 1 98/100 49/50 -99 100 0.99 1 98/99 99/100 1 1 1 1 1 99/100 99/100 -100 100 1 1 1 1 1 1 1 1 1 1 1 -101 100 1.01 1 1 1/99 1 1/100 1 1 1 1 1 1 1/100 1 1/100 -102 100 1.02 1 1 1/50 1 1/50 1 1 1 1 1 1 2/100 1 1/50 -103 100 1.03 1 1 1/33 1 3/100 1 1 1 1 1 1 3/100 1 3/100 -104 100 1.04 1 1 1/25 1 1/25 1 1 1 1 1/16 1 1 4/100 1 1/25 -105 100 1.05 1 1 1/20 1 1/20 1 1 1 1 1/16 1 1/10 1 5/100 1 1/20 -106 100 1.06 1 1 3/50 1 3/50 1 1 1 1 1/16 1 1/10 1 6/100 1 3/50 -107 100 1.07 1 1 4/57 1 7/100 1 1 1 1/8 1 1/16 1 1/10 1 7/100 1 7/100 -108 100 1.08 1 1 2/25 1 2/25 1 1 1 1/8 1 1/16 1 1/10 1 8/100 1 2/25 -109 100 1.09 1 1 1/11 1 9/100 1 1 1 1/8 1 1/16 1 1/10 1 9/100 1 9/100 -110 100 1.1 1 1/9 1 1/10 1 1/10 1 1 1 1/8 1 2/16 1 1/10 1 10/100 1 1/10 -111 100 1.11 1 1/9 1 1/9 1 11/100 1 1 1 1/8 1 2/16 1 1/10 1 11/100 1 11/100 -112 100 1.12 1 1/8 1 3/25 1 3/25 1 1 1 1/8 1 2/16 1 1/10 1 12/100 1 3/25 -113 100 1.13 1 1/8 1 10/77 1 13/100 1 1 1/4 1 1/8 1 2/16 1 1/10 1 13/100 1 13/100 -114 100 1.14 1 1/7 1 7/50 1 7/50 1 1 1/4 1 1/8 1 2/16 1 1/10 1 14/100 1 7/50 -115 100 1.15 1 1/7 1 3/20 1 3/20 1 1 1/4 1 1/8 1 2/16 1 1/10 1 15/100 1 3/20 -116 100 1.16 1 1/6 1 4/25 1 4/25 1 1 1/4 1 1/8 1 3/16 1 2/10 1 16/100 1 4/25 -117 100 1.17 1 1/6 1 9/53 1 17/100 1 1 1/4 1 1/8 1 3/16 1 2/10 1 17/100 1 17/100 -118 100 1.18 1 1/6 1 9/50 1 9/50 1 1 1/4 1 1/8 1 3/16 1 2/10 1 18/100 1 9/50 -119 100 1.19 1 1/5 1 15/79 1 19/100 1 1 1/4 1 2/8 1 3/16 1 2/10 1 19/100 1 19/100 -120 100 1.2 1 1/5 1 1/5 1 1/5 1 1 1/4 1 2/8 1 3/16 1 2/10 1 20/100 1 1/5 -121 100 1.21 1 1/5 1 17/81 1 21/100 1 1 1/4 1 2/8 1 3/16 1 2/10 1 21/100 1 21/100 -122 100 1.22 1 2/9 1 11/50 1 11/50 1 1 1/4 1 2/8 1 4/16 1 2/10 1 22/100 1 11/50 -123 100 1.23 1 2/9 1 20/87 1 23/100 1 1 1/4 1 2/8 1 4/16 1 2/10 1 23/100 1 23/100 -124 100 1.24 1 1/4 1 6/25 1 6/25 1 1 1/4 1 2/8 1 4/16 1 2/10 1 24/100 1 6/25 -125 100 1.25 1 1/4 1 1/4 1 1/4 1 1/2 1 1/4 1 2/8 1 4/16 1 3/10 1 25/100 1 1/4 -126 100 1.26 1 1/4 1 13/50 1 13/50 1 1/2 1 1/4 1 2/8 1 4/16 1 3/10 1 26/100 1 13/50 -127 100 1.27 1 1/4 1 10/37 1 27/100 1 1/2 1 1/4 1 2/8 1 4/16 1 3/10 1 27/100 1 27/100 --103 201 -0.512437811 - 1/2 - 41/80 - 103/201 - 1/2 - 2/4 - 4/8 - 8/16 - 5/10 - 51/100 - 103/201 --100 201 -0.497512438 - 1/2 - 1/2 - 100/201 - 1/2 - 2/4 - 4/8 - 8/16 - 5/10 - 50/100 - 100/201 --97 201 -0.482587065 - 1/2 - 14/29 - 97/201 - 1/2 - 2/4 - 4/8 - 8/16 - 5/10 - 48/100 - 97/201 --94 201 -0.467661692 - 1/2 - 29/62 - 94/201 - 1/2 - 2/4 - 4/8 - 7/16 - 5/10 - 47/100 - 94/201 --91 201 -0.452736318 - 4/9 - 24/53 - 91/201 - 1/2 - 2/4 - 4/8 - 7/16 - 5/10 - 45/100 - 91/201 --88 201 -0.437810945 - 4/9 - 7/16 - 88/201 - 1/2 - 2/4 - 4/8 - 7/16 - 4/10 - 44/100 - 88/201 --85 201 -0.422885572 - 3/7 - 11/26 - 85/201 - 1/2 - 2/4 - 3/8 - 7/16 - 4/10 - 42/100 - 85/201 --82 201 -0.407960199 - 2/5 - 31/76 - 82/201 - 1/2 - 2/4 - 3/8 - 7/16 - 4/10 - 41/100 - 82/201 --79 201 -0.393034826 - 2/5 - 11/28 - 79/201 - 1/2 - 2/4 - 3/8 - 6/16 - 4/10 - 39/100 - 79/201 --76 201 -0.378109453 - 3/8 - 31/82 - 76/201 - 1/2 - 2/4 - 3/8 - 6/16 - 4/10 - 38/100 - 76/201 --73 201 -0.36318408 - 1/3 - 4/11 - 73/201 - 1/2 - 1/4 - 3/8 - 6/16 - 4/10 - 36/100 - 73/201 --70 201 -0.348258706 - 1/3 - 31/89 - 70/201 - 1/2 - 1/4 - 3/8 - 6/16 - 3/10 - 35/100 - 70/201 --67 201 -0.333333333 - 1/3 - 1/3 - 1/3 - 1/2 - 1/4 - 3/8 - 5/16 - 3/10 - 33/100 - 1/3 --64 201 -0.31840796 - 1/3 - 7/22 - 64/201 - 1/2 - 1/4 - 3/8 - 5/16 - 3/10 - 32/100 - 64/201 --61 201 -0.303482587 - 1/3 - 17/56 - 61/201 - 1/2 - 1/4 - 2/8 - 5/16 - 3/10 - 30/100 - 61/201 --58 201 -0.288557214 - 2/7 - 15/52 - 58/201 - 1/2 - 1/4 - 2/8 - 5/16 - 3/10 - 29/100 - 58/201 --55 201 -0.273631841 - 2/7 - 26/95 - 55/201 - 1/2 - 1/4 - 2/8 - 4/16 - 3/10 - 27/100 - 55/201 --52 201 -0.258706468 - 1/4 - 15/58 - 52/201 - 1/2 - 1/4 - 2/8 - 4/16 - 3/10 - 26/100 - 52/201 --49 201 -0.243781095 - 1/4 - 10/41 - 49/201 -0 - 1/4 - 2/8 - 4/16 - 2/10 - 24/100 - 49/201 --46 201 -0.228855721 - 2/9 - 19/83 - 46/201 -0 - 1/4 - 2/8 - 4/16 - 2/10 - 23/100 - 46/201 --43 201 -0.213930348 - 1/5 - 3/14 - 43/201 -0 - 1/4 - 2/8 - 3/16 - 2/10 - 21/100 - 43/201 --40 201 -0.199004975 - 1/5 - 1/5 - 40/201 -0 - 1/4 - 2/8 - 3/16 - 2/10 - 20/100 - 40/201 --37 201 -0.184079602 - 1/5 - 7/38 - 37/201 -0 - 1/4 - 1/8 - 3/16 - 2/10 - 18/100 - 37/201 --34 201 -0.169154229 - 1/6 - 11/65 - 34/201 -0 - 1/4 - 1/8 - 3/16 - 2/10 - 17/100 - 34/201 --31 201 -0.154228856 - 1/6 - 2/13 - 31/201 -0 - 1/4 - 1/8 - 2/16 - 2/10 - 15/100 - 31/201 --28 201 -0.139303483 - 1/7 - 11/79 - 28/201 -0 - 1/4 - 1/8 - 2/16 - 1/10 - 14/100 - 28/201 --25 201 -0.124378109 - 1/8 - 1/8 - 25/201 -0 -0 - 1/8 - 2/16 - 1/10 - 12/100 - 25/201 --22 201 -0.109452736 - 1/9 - 7/64 - 22/201 -0 -0 - 1/8 - 2/16 - 1/10 - 11/100 - 22/201 --19 201 -0.094527363 -0 - 7/74 - 19/201 -0 -0 - 1/8 - 2/16 - 1/10 - 9/100 - 19/201 --16 201 -0.07960199 -0 - 7/88 - 16/201 -0 -0 - 1/8 - 1/16 - 1/10 - 8/100 - 16/201 --13 201 -0.064676617 -0 - 2/31 - 13/201 -0 -0 - 1/8 - 1/16 - 1/10 - 6/100 - 13/201 --10 201 -0.049751244 -0 - 1/20 - 10/201 -0 -0 -0 - 1/16 -0 - 5/100 - 10/201 --7 201 -0.034825871 -0 - 3/86 - 7/201 -0 -0 -0 - 1/16 -0 - 3/100 - 7/201 --4 201 -0.019900498 -0 - 1/50 - 4/201 -0 -0 -0 -0 -0 - 2/100 - 4/201 --1 201 -0.004975124 -0 -0 - 1/201 -0 -0 -0 -0 -0 -0 - 1/201 -2 201 0.009950249 0 0 2/201 0 0 0 0 0 1/100 2/201 -5 201 0.024875622 0 1/40 5/201 0 0 0 0 0 2/100 5/201 -8 201 0.039800995 0 1/25 8/201 0 0 0 1/16 0 4/100 8/201 -11 201 0.054726368 0 4/73 11/201 0 0 0 1/16 1/10 5/100 11/201 -14 201 0.069651741 0 3/43 14/201 0 0 1/8 1/16 1/10 7/100 14/201 -17 201 0.084577114 0 6/71 17/201 0 0 1/8 1/16 1/10 8/100 17/201 -20 201 0.099502488 0 1/10 20/201 0 0 1/8 2/16 1/10 10/100 20/201 -23 201 0.114427861 1/9 4/35 23/201 0 0 1/8 2/16 1/10 11/100 23/201 -26 201 0.129353234 1/8 11/85 26/201 0 1/4 1/8 2/16 1/10 13/100 26/201 -29 201 0.144278607 1/7 14/97 29/201 0 1/4 1/8 2/16 1/10 14/100 29/201 -32 201 0.15920398 1/6 7/44 32/201 0 1/4 1/8 3/16 2/10 16/100 32/201 -35 201 0.174129353 1/6 4/23 35/201 0 1/4 1/8 3/16 2/10 17/100 35/201 -38 201 0.189054726 1/5 7/37 38/201 0 1/4 2/8 3/16 2/10 19/100 38/201 -41 201 0.2039801 1/5 10/49 41/201 0 1/4 2/8 3/16 2/10 20/100 41/201 -44 201 0.218905473 2/9 7/32 44/201 0 1/4 2/8 4/16 2/10 22/100 44/201 -47 201 0.233830846 1/4 18/77 47/201 0 1/4 2/8 4/16 2/10 23/100 47/201 -50 201 0.248756219 1/4 1/4 50/201 0 1/4 2/8 4/16 2/10 25/100 50/201 -53 201 0.263681592 1/4 24/91 53/201 1/2 1/4 2/8 4/16 3/10 26/100 53/201 -56 201 0.278606965 2/7 17/61 56/201 1/2 1/4 2/8 4/16 3/10 28/100 56/201 -59 201 0.293532338 2/7 27/92 59/201 1/2 1/4 2/8 5/16 3/10 29/100 59/201 -62 201 0.308457711 1/3 29/94 62/201 1/2 1/4 2/8 5/16 3/10 31/100 62/201 -65 201 0.323383085 1/3 11/34 65/201 1/2 1/4 3/8 5/16 3/10 32/100 65/201 -68 201 0.338308458 1/3 23/68 68/201 1/2 1/4 3/8 5/16 3/10 34/100 68/201 -71 201 0.353233831 1/3 6/17 71/201 1/2 1/4 3/8 6/16 4/10 35/100 71/201 -74 201 0.368159204 3/8 7/19 74/201 1/2 1/4 3/8 6/16 4/10 37/100 74/201 -77 201 0.383084577 3/8 18/47 77/201 1/2 2/4 3/8 6/16 4/10 38/100 77/201 -80 201 0.39800995 2/5 39/98 80/201 1/2 2/4 3/8 6/16 4/10 40/100 80/201 -83 201 0.412935323 2/5 19/46 83/201 1/2 2/4 3/8 7/16 4/10 41/100 83/201 -86 201 0.427860697 3/7 3/7 86/201 1/2 2/4 3/8 7/16 4/10 43/100 86/201 -89 201 0.44278607 4/9 31/70 89/201 1/2 2/4 4/8 7/16 4/10 44/100 89/201 -92 201 0.457711443 1/2 27/59 92/201 1/2 2/4 4/8 7/16 5/10 46/100 92/201 -95 201 0.472636816 1/2 26/55 95/201 1/2 2/4 4/8 8/16 5/10 47/100 95/201 -98 201 0.487562189 1/2 39/80 98/201 1/2 2/4 4/8 8/16 5/10 49/100 98/201 -101 201 0.502487562 1/2 1/2 101/201 1/2 2/4 4/8 8/16 5/10 50/100 101/201 -104 201 0.517412935 1/2 15/29 104/201 1/2 2/4 4/8 8/16 5/10 52/100 104/201 -107 201 0.532338308 1/2 33/62 107/201 1/2 2/4 4/8 9/16 5/10 53/100 107/201 -110 201 0.547263682 5/9 29/53 110/201 1/2 2/4 4/8 9/16 5/10 55/100 110/201 -113 201 0.562189055 5/9 9/16 113/201 1/2 2/4 4/8 9/16 6/10 56/100 113/201 -116 201 0.577114428 4/7 15/26 116/201 1/2 2/4 5/8 9/16 6/10 58/100 116/201 -119 201 0.592039801 3/5 45/76 119/201 1/2 2/4 5/8 9/16 6/10 59/100 119/201 -122 201 0.606965174 3/5 17/28 122/201 1/2 2/4 5/8 10/16 6/10 61/100 122/201 -125 201 0.621890547 5/8 51/82 125/201 1/2 2/4 5/8 10/16 6/10 62/100 125/201 -128 201 0.63681592 2/3 7/11 128/201 1/2 3/4 5/8 10/16 6/10 64/100 128/201 -131 201 0.651741294 2/3 58/89 131/201 1/2 3/4 5/8 10/16 7/10 65/100 131/201 -134 201 0.666666667 2/3 2/3 2/3 1/2 3/4 5/8 11/16 7/10 67/100 2/3 -137 201 0.68159204 2/3 15/22 137/201 1/2 3/4 5/8 11/16 7/10 68/100 137/201 -140 201 0.696517413 2/3 39/56 140/201 1/2 3/4 6/8 11/16 7/10 70/100 140/201 -143 201 0.711442786 5/7 37/52 143/201 1/2 3/4 6/8 11/16 7/10 71/100 143/201 -146 201 0.726368159 5/7 69/95 146/201 1/2 3/4 6/8 12/16 7/10 73/100 146/201 -149 201 0.741293532 3/4 43/58 149/201 1/2 3/4 6/8 12/16 7/10 74/100 149/201 -152 201 0.756218905 3/4 31/41 152/201 1 3/4 6/8 12/16 8/10 76/100 152/201 -155 201 0.771144279 7/9 64/83 155/201 1 3/4 6/8 12/16 8/10 77/100 155/201 -158 201 0.786069652 4/5 11/14 158/201 1 3/4 6/8 13/16 8/10 79/100 158/201 -161 201 0.800995025 4/5 4/5 161/201 1 3/4 6/8 13/16 8/10 80/100 161/201 -164 201 0.815920398 4/5 31/38 164/201 1 3/4 7/8 13/16 8/10 82/100 164/201 -167 201 0.830845771 5/6 54/65 167/201 1 3/4 7/8 13/16 8/10 83/100 167/201 -170 201 0.845771144 5/6 11/13 170/201 1 3/4 7/8 14/16 8/10 85/100 170/201 -173 201 0.860696517 6/7 68/79 173/201 1 3/4 7/8 14/16 9/10 86/100 173/201 -176 201 0.875621891 7/8 7/8 176/201 1 1 7/8 14/16 9/10 88/100 176/201 -179 201 0.890547264 8/9 57/64 179/201 1 1 7/8 14/16 9/10 89/100 179/201 -182 201 0.905472637 1 67/74 182/201 1 1 7/8 14/16 9/10 91/100 182/201 -185 201 0.92039801 1 81/88 185/201 1 1 7/8 15/16 9/10 92/100 185/201 -188 201 0.935323383 1 29/31 188/201 1 1 7/8 15/16 9/10 94/100 188/201 -191 201 0.950248756 1 19/20 191/201 1 1 1 15/16 1 95/100 191/201 -194 201 0.965174129 1 83/86 194/201 1 1 1 15/16 1 97/100 194/201 -197 201 0.980099502 1 49/50 197/201 1 1 1 1 1 98/100 197/201 -200 201 0.995024876 1 1 200/201 1 1 1 1 1 1 200/201 -203 201 1.009950249 1 1 1 2/201 1 1 1 1 1 1 1/100 1 2/201 -206 201 1.024875622 1 1 1/40 1 5/201 1 1 1 1 1 1 2/100 1 5/201 -209 201 1.039800995 1 1 1/25 1 8/201 1 1 1 1 1/16 1 1 4/100 1 8/201 -212 201 1.054726368 1 1 4/73 1 11/201 1 1 1 1 1/16 1 1/10 1 5/100 1 11/201 -215 201 1.069651741 1 1 3/43 1 14/201 1 1 1 1/8 1 1/16 1 1/10 1 7/100 1 14/201 -218 201 1.084577114 1 1 6/71 1 17/201 1 1 1 1/8 1 1/16 1 1/10 1 8/100 1 17/201 -221 201 1.099502488 1 1 1/10 1 20/201 1 1 1 1/8 1 2/16 1 1/10 1 10/100 1 20/201 -224 201 1.114427861 1 1/9 1 4/35 1 23/201 1 1 1 1/8 1 2/16 1 1/10 1 11/100 1 23/201 -227 201 1.129353234 1 1/8 1 11/85 1 26/201 1 1 1/4 1 1/8 1 2/16 1 1/10 1 13/100 1 26/201 -230 201 1.144278607 1 1/7 1 14/97 1 29/201 1 1 1/4 1 1/8 1 2/16 1 1/10 1 14/100 1 29/201 -233 201 1.15920398 1 1/6 1 7/44 1 32/201 1 1 1/4 1 1/8 1 3/16 1 2/10 1 16/100 1 32/201 -236 201 1.174129353 1 1/6 1 4/23 1 35/201 1 1 1/4 1 1/8 1 3/16 1 2/10 1 17/100 1 35/201 -239 201 1.189054726 1 1/5 1 7/37 1 38/201 1 1 1/4 1 2/8 1 3/16 1 2/10 1 19/100 1 38/201 -242 201 1.2039801 1 1/5 1 10/49 1 41/201 1 1 1/4 1 2/8 1 3/16 1 2/10 1 20/100 1 41/201 -245 201 1.218905473 1 2/9 1 7/32 1 44/201 1 1 1/4 1 2/8 1 4/16 1 2/10 1 22/100 1 44/201 -248 201 1.233830846 1 1/4 1 18/77 1 47/201 1 1 1/4 1 2/8 1 4/16 1 2/10 1 23/100 1 47/201 -251 201 1.248756219 1 1/4 1 1/4 1 50/201 1 1 1/4 1 2/8 1 4/16 1 2/10 1 25/100 1 50/201 -254 201 1.263681592 1 1/4 1 24/91 1 53/201 1 1/2 1 1/4 1 2/8 1 4/16 1 3/10 1 26/100 1 53/201 - - - - - - - - - - - - - - - - - - - diff --git a/test-data/spreadsheet/54686_fraction_formats.xls b/test-data/spreadsheet/54686_fraction_formats.xls deleted file mode 100644 index d802995b1..000000000 Binary files a/test-data/spreadsheet/54686_fraction_formats.xls and /dev/null differ diff --git a/test-data/spreadsheet/54764-2.xlsx b/test-data/spreadsheet/54764-2.xlsx deleted file mode 100644 index 0d942ca8d..000000000 Binary files a/test-data/spreadsheet/54764-2.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/54764.xlsx b/test-data/spreadsheet/54764.xlsx deleted file mode 100644 index 938245b61..000000000 Binary files a/test-data/spreadsheet/54764.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/55341_CellStyleBorder.xls b/test-data/spreadsheet/55341_CellStyleBorder.xls deleted file mode 100644 index 6de09bc32..000000000 Binary files a/test-data/spreadsheet/55341_CellStyleBorder.xls and /dev/null differ diff --git a/test-data/spreadsheet/55406_Conditional_formatting_sample.xlsx b/test-data/spreadsheet/55406_Conditional_formatting_sample.xlsx deleted file mode 100644 index dc3e96d62..000000000 Binary files a/test-data/spreadsheet/55406_Conditional_formatting_sample.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/55640.xlsx b/test-data/spreadsheet/55640.xlsx deleted file mode 100644 index d353bb380..000000000 Binary files a/test-data/spreadsheet/55640.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/55668.xls b/test-data/spreadsheet/55668.xls deleted file mode 100644 index 8aa8f5042..000000000 Binary files a/test-data/spreadsheet/55668.xls and /dev/null differ diff --git a/test-data/spreadsheet/55745.xlsx b/test-data/spreadsheet/55745.xlsx deleted file mode 100644 index 5726e741a..000000000 Binary files a/test-data/spreadsheet/55745.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/55850.xlsx b/test-data/spreadsheet/55850.xlsx deleted file mode 100644 index ea8dc0e39..000000000 Binary files a/test-data/spreadsheet/55850.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/55864.xlsx b/test-data/spreadsheet/55864.xlsx deleted file mode 100644 index 51c9d53ca..000000000 Binary files a/test-data/spreadsheet/55864.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/55906-MultiSheetRefs.xls b/test-data/spreadsheet/55906-MultiSheetRefs.xls deleted file mode 100644 index c31728d82..000000000 Binary files a/test-data/spreadsheet/55906-MultiSheetRefs.xls and /dev/null differ diff --git a/test-data/spreadsheet/55906-MultiSheetRefs.xlsx b/test-data/spreadsheet/55906-MultiSheetRefs.xlsx deleted file mode 100644 index 4099796fc..000000000 Binary files a/test-data/spreadsheet/55906-MultiSheetRefs.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/55923.xlsx b/test-data/spreadsheet/55923.xlsx deleted file mode 100644 index fbcb7bdcf..000000000 Binary files a/test-data/spreadsheet/55923.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/55924.xlsx b/test-data/spreadsheet/55924.xlsx deleted file mode 100644 index 2ce091a7c..000000000 Binary files a/test-data/spreadsheet/55924.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/55926.xlsx b/test-data/spreadsheet/55926.xlsx deleted file mode 100644 index 23907c1d5..000000000 Binary files a/test-data/spreadsheet/55926.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/55927.xlsx b/test-data/spreadsheet/55927.xlsx deleted file mode 100644 index 62fd046f5..000000000 Binary files a/test-data/spreadsheet/55927.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/55982.xls b/test-data/spreadsheet/55982.xls deleted file mode 100644 index 2e09ddb53..000000000 Binary files a/test-data/spreadsheet/55982.xls and /dev/null differ diff --git a/test-data/spreadsheet/56011.xlsx b/test-data/spreadsheet/56011.xlsx deleted file mode 100644 index 7b5f70eba..000000000 Binary files a/test-data/spreadsheet/56011.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/56017.xlsx b/test-data/spreadsheet/56017.xlsx deleted file mode 100644 index f3ddf3cf5..000000000 Binary files a/test-data/spreadsheet/56017.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/56169.xlsx b/test-data/spreadsheet/56169.xlsx deleted file mode 100644 index 98b8788de..000000000 Binary files a/test-data/spreadsheet/56169.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/56170.xlsx b/test-data/spreadsheet/56170.xlsx deleted file mode 100644 index f80e386cc..000000000 Binary files a/test-data/spreadsheet/56170.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/56274.xlsx b/test-data/spreadsheet/56274.xlsx deleted file mode 100644 index 8c3573adb..000000000 Binary files a/test-data/spreadsheet/56274.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/56278.xlsx b/test-data/spreadsheet/56278.xlsx deleted file mode 100644 index f71085120..000000000 Binary files a/test-data/spreadsheet/56278.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/56295.xlsx b/test-data/spreadsheet/56295.xlsx deleted file mode 100644 index d929d99a1..000000000 Binary files a/test-data/spreadsheet/56295.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/56315.xlsx b/test-data/spreadsheet/56315.xlsx deleted file mode 100644 index 10e167ae6..000000000 Binary files a/test-data/spreadsheet/56315.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/56325.xls b/test-data/spreadsheet/56325.xls deleted file mode 100644 index 38b0e4abb..000000000 Binary files a/test-data/spreadsheet/56325.xls and /dev/null differ diff --git a/test-data/spreadsheet/56325a.xls b/test-data/spreadsheet/56325a.xls deleted file mode 100644 index a1e52cb5d..000000000 Binary files a/test-data/spreadsheet/56325a.xls and /dev/null differ diff --git a/test-data/spreadsheet/56420.xlsx b/test-data/spreadsheet/56420.xlsx deleted file mode 100644 index bd1ceff96..000000000 Binary files a/test-data/spreadsheet/56420.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/56450.xls b/test-data/spreadsheet/56450.xls deleted file mode 100644 index 66798a8b4..000000000 Binary files a/test-data/spreadsheet/56450.xls and /dev/null differ diff --git a/test-data/spreadsheet/56482.xls b/test-data/spreadsheet/56482.xls deleted file mode 100644 index 466aa19de..000000000 Binary files a/test-data/spreadsheet/56482.xls and /dev/null differ diff --git a/test-data/spreadsheet/56502.xlsx b/test-data/spreadsheet/56502.xlsx deleted file mode 100644 index 72bd17333..000000000 Binary files a/test-data/spreadsheet/56502.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/56511.xlsx b/test-data/spreadsheet/56511.xlsx deleted file mode 100644 index 1369584af..000000000 Binary files a/test-data/spreadsheet/56511.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/56514.xlsx b/test-data/spreadsheet/56514.xlsx deleted file mode 100644 index 29163a5fe..000000000 Binary files a/test-data/spreadsheet/56514.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/56563a.xls b/test-data/spreadsheet/56563a.xls deleted file mode 100644 index 7fb4aa4d5..000000000 Binary files a/test-data/spreadsheet/56563a.xls and /dev/null differ diff --git a/test-data/spreadsheet/56563b.xls b/test-data/spreadsheet/56563b.xls deleted file mode 100644 index 7fb4aa4d5..000000000 Binary files a/test-data/spreadsheet/56563b.xls and /dev/null differ diff --git a/test-data/spreadsheet/56574.xlsx b/test-data/spreadsheet/56574.xlsx deleted file mode 100644 index 9cce54cc8..000000000 Binary files a/test-data/spreadsheet/56574.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/56644.xlsx b/test-data/spreadsheet/56644.xlsx deleted file mode 100644 index f82be1792..000000000 Binary files a/test-data/spreadsheet/56644.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/56688_1.xlsx b/test-data/spreadsheet/56688_1.xlsx deleted file mode 100644 index 4246e9679..000000000 Binary files a/test-data/spreadsheet/56688_1.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/56688_2.xlsx b/test-data/spreadsheet/56688_2.xlsx deleted file mode 100644 index 24098bd51..000000000 Binary files a/test-data/spreadsheet/56688_2.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/56688_3.xlsx b/test-data/spreadsheet/56688_3.xlsx deleted file mode 100644 index 9a707618a..000000000 Binary files a/test-data/spreadsheet/56688_3.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/56688_4.xlsx b/test-data/spreadsheet/56688_4.xlsx deleted file mode 100644 index 5aeb4ee4b..000000000 Binary files a/test-data/spreadsheet/56688_4.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/56702.xlsx b/test-data/spreadsheet/56702.xlsx deleted file mode 100644 index c17a0bca8..000000000 Binary files a/test-data/spreadsheet/56702.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/56730.xlsx b/test-data/spreadsheet/56730.xlsx deleted file mode 100644 index 9883de4f6..000000000 Binary files a/test-data/spreadsheet/56730.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/56737.xls b/test-data/spreadsheet/56737.xls deleted file mode 100644 index 59ab233a0..000000000 Binary files a/test-data/spreadsheet/56737.xls and /dev/null differ diff --git a/test-data/spreadsheet/56737.xlsx b/test-data/spreadsheet/56737.xlsx deleted file mode 100644 index 3783483ef..000000000 Binary files a/test-data/spreadsheet/56737.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/56822-Countifs.xlsx b/test-data/spreadsheet/56822-Countifs.xlsx deleted file mode 100644 index 8444d198c..000000000 Binary files a/test-data/spreadsheet/56822-Countifs.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/56957.xlsx b/test-data/spreadsheet/56957.xlsx deleted file mode 100644 index b58aa62db..000000000 Binary files a/test-data/spreadsheet/56957.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/57003-FixedFunctionTestCaseData.xls b/test-data/spreadsheet/57003-FixedFunctionTestCaseData.xls deleted file mode 100644 index bd8b4ba4d..000000000 Binary files a/test-data/spreadsheet/57003-FixedFunctionTestCaseData.xls and /dev/null differ diff --git a/test-data/spreadsheet/57074.xls b/test-data/spreadsheet/57074.xls deleted file mode 100644 index c29485a27..000000000 Binary files a/test-data/spreadsheet/57074.xls and /dev/null differ diff --git a/test-data/spreadsheet/57163.xls b/test-data/spreadsheet/57163.xls deleted file mode 100644 index 402c954e1..000000000 Binary files a/test-data/spreadsheet/57163.xls and /dev/null differ diff --git a/test-data/spreadsheet/57171_57163_57165.xlsx b/test-data/spreadsheet/57171_57163_57165.xlsx deleted file mode 100644 index 5d94a476c..000000000 Binary files a/test-data/spreadsheet/57171_57163_57165.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/57176.xlsx b/test-data/spreadsheet/57176.xlsx deleted file mode 100644 index cd7dd84cc..000000000 Binary files a/test-data/spreadsheet/57176.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/57181.xlsm b/test-data/spreadsheet/57181.xlsm deleted file mode 100644 index 3583a71a5..000000000 Binary files a/test-data/spreadsheet/57181.xlsm and /dev/null differ diff --git a/test-data/spreadsheet/57196.xlsx b/test-data/spreadsheet/57196.xlsx deleted file mode 100644 index ed2b65e34..000000000 Binary files a/test-data/spreadsheet/57196.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/57231_MixedGasReport.xls b/test-data/spreadsheet/57231_MixedGasReport.xls deleted file mode 100644 index d4a526c58..000000000 Binary files a/test-data/spreadsheet/57231_MixedGasReport.xls and /dev/null differ diff --git a/test-data/spreadsheet/57236.xlsx b/test-data/spreadsheet/57236.xlsx deleted file mode 100644 index 656884784..000000000 Binary files a/test-data/spreadsheet/57236.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/57362.xlsx b/test-data/spreadsheet/57362.xlsx deleted file mode 100644 index ec2be3823..000000000 Binary files a/test-data/spreadsheet/57362.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/57423.xlsx b/test-data/spreadsheet/57423.xlsx deleted file mode 100644 index 54c65be52..000000000 Binary files a/test-data/spreadsheet/57423.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/57456.xls b/test-data/spreadsheet/57456.xls deleted file mode 100644 index 86fde8587..000000000 Binary files a/test-data/spreadsheet/57456.xls and /dev/null differ diff --git a/test-data/spreadsheet/57482-OnlyNumeric.xlsx b/test-data/spreadsheet/57482-OnlyNumeric.xlsx deleted file mode 100644 index c905891a7..000000000 Binary files a/test-data/spreadsheet/57482-OnlyNumeric.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/57523.xlsx b/test-data/spreadsheet/57523.xlsx deleted file mode 100644 index 99fe81d4d..000000000 Binary files a/test-data/spreadsheet/57523.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/57535.xlsx b/test-data/spreadsheet/57535.xlsx deleted file mode 100644 index 897ef71ab..000000000 Binary files a/test-data/spreadsheet/57535.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/57798.xls b/test-data/spreadsheet/57798.xls deleted file mode 100644 index 6f66799f3..000000000 Binary files a/test-data/spreadsheet/57798.xls and /dev/null differ diff --git a/test-data/spreadsheet/57798.xlsx b/test-data/spreadsheet/57798.xlsx deleted file mode 100644 index 415e450ef..000000000 Binary files a/test-data/spreadsheet/57798.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/57826.xlsx b/test-data/spreadsheet/57826.xlsx deleted file mode 100644 index ccf2dc38f..000000000 Binary files a/test-data/spreadsheet/57826.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/57828.xlsx b/test-data/spreadsheet/57828.xlsx deleted file mode 100644 index c750a0944..000000000 Binary files a/test-data/spreadsheet/57828.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/57838.xlsx b/test-data/spreadsheet/57838.xlsx deleted file mode 100644 index 59366d044..000000000 Binary files a/test-data/spreadsheet/57838.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/57890.xlsx b/test-data/spreadsheet/57890.xlsx deleted file mode 100644 index 91c751baa..000000000 Binary files a/test-data/spreadsheet/57890.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/57893-many-merges.xlsx b/test-data/spreadsheet/57893-many-merges.xlsx deleted file mode 100644 index 572dfec27..000000000 Binary files a/test-data/spreadsheet/57893-many-merges.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/57914.xlsx b/test-data/spreadsheet/57914.xlsx deleted file mode 100644 index 2477fa838..000000000 Binary files a/test-data/spreadsheet/57914.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/57925.xls b/test-data/spreadsheet/57925.xls deleted file mode 100644 index ef13551ff..000000000 Binary files a/test-data/spreadsheet/57925.xls and /dev/null differ diff --git a/test-data/spreadsheet/58315.xlsx b/test-data/spreadsheet/58315.xlsx deleted file mode 100644 index 0da751ed6..000000000 Binary files a/test-data/spreadsheet/58315.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/58325_db.xlsx b/test-data/spreadsheet/58325_db.xlsx deleted file mode 100644 index 8b85089c8..000000000 Binary files a/test-data/spreadsheet/58325_db.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/58325_lt.xlsx b/test-data/spreadsheet/58325_lt.xlsx deleted file mode 100644 index 342ad0388..000000000 Binary files a/test-data/spreadsheet/58325_lt.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/58616.xlsx b/test-data/spreadsheet/58616.xlsx deleted file mode 100644 index 9ab573927..000000000 Binary files a/test-data/spreadsheet/58616.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/58648.xlsx b/test-data/spreadsheet/58648.xlsx deleted file mode 100644 index 9f2f7bf47..000000000 Binary files a/test-data/spreadsheet/58648.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/58731.xlsx b/test-data/spreadsheet/58731.xlsx deleted file mode 100644 index 80e22f3d1..000000000 Binary files a/test-data/spreadsheet/58731.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/58747.xlsx b/test-data/spreadsheet/58747.xlsx deleted file mode 100644 index 2bfec8a55..000000000 Binary files a/test-data/spreadsheet/58747.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/58760.xlsx b/test-data/spreadsheet/58760.xlsx deleted file mode 100644 index 9795f8c48..000000000 Binary files a/test-data/spreadsheet/58760.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/59021.xlsx b/test-data/spreadsheet/59021.xlsx deleted file mode 100644 index 0f485d270..000000000 Binary files a/test-data/spreadsheet/59021.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/59026.xlsx b/test-data/spreadsheet/59026.xlsx deleted file mode 100644 index 29c8c2dc6..000000000 Binary files a/test-data/spreadsheet/59026.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/59074.xls b/test-data/spreadsheet/59074.xls deleted file mode 100644 index 2b0a2d841..000000000 Binary files a/test-data/spreadsheet/59074.xls and /dev/null differ diff --git a/test-data/spreadsheet/59106.xlsx b/test-data/spreadsheet/59106.xlsx deleted file mode 100644 index e47845ad6..000000000 Binary files a/test-data/spreadsheet/59106.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/59132.xlsx b/test-data/spreadsheet/59132.xlsx deleted file mode 100644 index 7fa2bdd41..000000000 Binary files a/test-data/spreadsheet/59132.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/59264.xls b/test-data/spreadsheet/59264.xls deleted file mode 100644 index dcbaf2bb6..000000000 Binary files a/test-data/spreadsheet/59264.xls and /dev/null differ diff --git a/test-data/spreadsheet/59264.xlsx b/test-data/spreadsheet/59264.xlsx deleted file mode 100644 index be0a4d05e..000000000 Binary files a/test-data/spreadsheet/59264.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/59687.xlsx b/test-data/spreadsheet/59687.xlsx deleted file mode 100644 index 8ce567fab..000000000 Binary files a/test-data/spreadsheet/59687.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/59736.xlsx b/test-data/spreadsheet/59736.xlsx deleted file mode 100644 index 1f29d54c5..000000000 Binary files a/test-data/spreadsheet/59736.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/59746_NoRowNums.xlsx b/test-data/spreadsheet/59746_NoRowNums.xlsx deleted file mode 100644 index 72c26e9c5..000000000 Binary files a/test-data/spreadsheet/59746_NoRowNums.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/59775.xlsx b/test-data/spreadsheet/59775.xlsx deleted file mode 100644 index 03238bd2a..000000000 Binary files a/test-data/spreadsheet/59775.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/59830.xls b/test-data/spreadsheet/59830.xls deleted file mode 100644 index 592d9ba69..000000000 Binary files a/test-data/spreadsheet/59830.xls and /dev/null differ diff --git a/test-data/spreadsheet/59858.xls b/test-data/spreadsheet/59858.xls deleted file mode 100644 index 4f66c6d90..000000000 Binary files a/test-data/spreadsheet/59858.xls and /dev/null differ diff --git a/test-data/spreadsheet/60255_extra_drawingparts.xlsx b/test-data/spreadsheet/60255_extra_drawingparts.xlsx deleted file mode 100644 index bc4865c47..000000000 Binary files a/test-data/spreadsheet/60255_extra_drawingparts.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/60273.xls b/test-data/spreadsheet/60273.xls deleted file mode 100644 index 07933cff6..000000000 Binary files a/test-data/spreadsheet/60273.xls and /dev/null differ diff --git a/test-data/spreadsheet/60284.xls b/test-data/spreadsheet/60284.xls deleted file mode 100644 index 7e0f9fb83..000000000 Binary files a/test-data/spreadsheet/60284.xls and /dev/null differ diff --git a/test-data/spreadsheet/60289.xlsx b/test-data/spreadsheet/60289.xlsx deleted file mode 100644 index 2d1b50817..000000000 Binary files a/test-data/spreadsheet/60289.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/60512.xlsm b/test-data/spreadsheet/60512.xlsm deleted file mode 100644 index 7c38c6d27..000000000 Binary files a/test-data/spreadsheet/60512.xlsm and /dev/null differ diff --git a/test-data/spreadsheet/60825.xlsx b/test-data/spreadsheet/60825.xlsx deleted file mode 100644 index ffcfe08e6..000000000 Binary files a/test-data/spreadsheet/60825.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/AbnormalSharedFormulaFlag.xls b/test-data/spreadsheet/AbnormalSharedFormulaFlag.xls deleted file mode 100644 index 788865b3b..000000000 Binary files a/test-data/spreadsheet/AbnormalSharedFormulaFlag.xls and /dev/null differ diff --git a/test-data/spreadsheet/AreaErrPtg.xls b/test-data/spreadsheet/AreaErrPtg.xls deleted file mode 100644 index ce863b8f6..000000000 Binary files a/test-data/spreadsheet/AreaErrPtg.xls and /dev/null differ diff --git a/test-data/spreadsheet/AverageTaxRates.xlsx b/test-data/spreadsheet/AverageTaxRates.xlsx deleted file mode 100644 index fee8059e2..000000000 Binary files a/test-data/spreadsheet/AverageTaxRates.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/BOOK_in_capitals.xls b/test-data/spreadsheet/BOOK_in_capitals.xls deleted file mode 100644 index 002d0cac2..000000000 Binary files a/test-data/spreadsheet/BOOK_in_capitals.xls and /dev/null differ diff --git a/test-data/spreadsheet/Basic_Expense_Template_2011.xls b/test-data/spreadsheet/Basic_Expense_Template_2011.xls deleted file mode 100644 index 5df7ae3c9..000000000 Binary files a/test-data/spreadsheet/Basic_Expense_Template_2011.xls and /dev/null differ diff --git a/test-data/spreadsheet/BigSSTRecord b/test-data/spreadsheet/BigSSTRecord deleted file mode 100644 index 6cebff51b..000000000 --- a/test-data/spreadsheet/BigSSTRecord +++ /dev/null @@ -1,516 +0,0 @@ -FC 00 20 -20 B8 05 00 00 B0 02 00 00 0C 00 00 4D 61 6E 75 -66 61 63 74 75 72 65 72 0B 00 00 50 61 72 74 20 -4E 75 6D 62 65 72 05 00 00 53 63 61 6C 65 04 00 -00 54 79 70 65 04 00 00 4E 61 6D 65 08 00 00 43 -6F 6D 6D 65 6E 74 73 08 00 00 41 4D 54 2D 45 52 -54 4C 07 00 00 48 6F 74 20 52 6F 64 10 00 00 33 -32 20 46 6F 72 64 20 52 6F 61 64 73 74 65 72 08 -00 00 4D 6F 6E 6F 67 72 61 6D 08 00 00 53 68 6F -77 20 52 6F 64 07 00 00 48 61 6E 67 6D 61 6E 11 -00 00 50 65 74 65 72 62 69 6C 74 20 57 72 65 63 -6B 65 72 15 00 00 45 61 73 74 65 72 6E 20 41 69 -72 6C 69 6E 65 73 20 44 43 2D 33 11 00 00 4D 61 -73 65 72 61 74 69 20 4D 65 72 61 6B 20 53 53 1A -00 00 44 6F 75 67 6C 61 73 20 50 2D 37 30 20 4E -69 67 68 74 20 46 69 67 68 74 65 72 17 00 00 35 -35 20 43 68 65 76 79 20 53 74 72 65 65 74 20 4D -61 63 68 69 6E 65 0C 00 00 54 77 65 65 64 79 20 -50 69 65 20 32 13 00 00 48 75 65 79 20 52 65 73 -63 75 65 20 43 68 6F 70 70 65 72 10 00 00 4D 61 -7A 64 61 20 4D 58 2D 35 20 4D 69 61 74 61 0A 00 -00 53 70 6F 72 74 73 20 43 61 72 05 00 00 54 72 -75 63 6B 06 00 00 52 6F 63 6B 65 74 09 00 00 50 -61 72 74 73 20 4B 69 74 0E 00 00 43 69 76 69 6C -69 61 6E 20 50 6C 61 6E 65 0E 00 00 4D 69 6C 69 -74 61 72 79 20 50 6C 61 6E 65 0F 00 00 53 63 69 -65 6E 63 65 20 46 69 63 74 69 6F 6E 1A 00 00 44 -6F 6E 20 47 61 72 6C 69 74 73 20 57 79 6E 6E 27 -73 20 43 68 61 72 67 65 72 19 00 00 44 6F 6E 20 -47 61 72 6C 69 74 73 20 57 79 6E 6E 27 73 20 4A -61 6D 6D 65 72 1A 00 00 50 61 63 6B 61 72 64 20 -42 6F 61 74 74 61 69 6C 20 53 70 65 65 64 73 74 -65 72 0E 00 00 52 65 76 65 6C 6C 20 47 65 72 6D -61 6E 79 05 00 00 30 34 31 34 36 04 00 00 31 2F -32 34 04 00 00 31 2F 37 32 0E 00 00 4D 65 20 32 -36 32 20 41 2D 31 61 2F 55 33 09 00 00 53 54 43 -20 53 74 61 72 74 04 00 00 34 63 2D 39 05 00 00 -31 2F 32 38 38 0C 00 00 50 72 6F 74 6F 6E 2D 4B -20 4D 69 72 04 00 00 34 63 2D 37 0E 00 00 50 72 -6F 74 6F 6E 2D 4B 20 41 73 74 72 61 05 00 00 34 -63 2D 31 37 0E 00 00 50 72 6F 74 6F 6E 2D 4B 20 -5A 61 72 79 61 13 00 00 41 63 63 75 72 61 74 65 -20 4D 69 6E 69 61 74 75 72 65 73 04 00 00 33 34 -32 30 04 00 00 31 2F 34 38 0F 00 00 53 42 44 2D -31 20 44 61 75 6E 74 6C 65 73 73 1B 00 00 77 2F -56 65 72 6C 69 6E 64 65 6E 20 31 33 37 38 20 44 -65 74 61 69 6C 20 53 65 74 04 00 00 38 32 38 33 -0C 00 00 54 72 6F 75 62 6C 65 6D 61 6B 65 72 04 -00 00 32 37 33 37 0E 00 00 44 61 79 74 6F 6E 61 -20 53 70 69 64 65 72 04 00 00 38 31 32 36 04 00 -00 31 2F 32 35 06 00 00 48 65 6C 6C 65 72 05 00 -00 38 30 34 34 33 05 00 00 31 2F 31 34 34 12 00 -00 42 72 65 69 74 6C 69 6E 20 4F 72 62 69 74 65 -72 20 33 0F 00 00 53 68 61 6E 67 68 61 69 20 44 -72 61 67 6F 6E 04 00 00 31 39 39 38 04 00 00 31 -2F 39 36 0F 00 00 41 72 69 61 6E 65 20 35 20 52 -6F 63 6B 65 74 0F 00 00 52 65 76 65 6C 6C 2D 4D -6F 6E 6F 67 72 61 6D 07 00 00 38 35 2D 35 39 33 -34 0F 00 00 50 42 59 2D 35 41 20 43 61 74 61 6C -69 6E 61 0A 00 00 50 72 6F 4D 6F 64 65 6C 65 72 -07 00 00 47 6C 65 6E 63 6F 65 05 00 00 30 35 32 -30 32 04 00 00 31 2F 33 35 16 00 00 50 69 61 73 -65 63 6B 69 20 5A 56 2D 38 50 20 41 69 72 67 65 -65 70 08 00 00 48 61 73 65 67 61 77 61 05 00 00 -30 39 31 36 39 20 00 00 53 42 44 2D 33 20 44 61 -75 6E 74 6C 65 73 73 20 27 55 53 53 20 45 6E 74 -65 72 70 72 69 73 65 27 0C 00 00 53 69 6C 76 65 -72 20 43 6C 6F 75 64 06 00 00 53 43 34 38 30 31 -19 00 00 53 75 70 65 72 6D 61 72 69 6E 65 20 53 -70 69 74 65 66 75 6C 20 46 2E 31 34 06 00 00 52 -65 76 65 6C 6C 07 00 00 38 35 2D 31 36 35 34 0D -00 00 50 2D 35 31 42 20 4D 75 73 74 61 6E 67 09 -00 00 50 72 6F 46 69 6E 69 73 68 06 00 00 44 72 -61 67 6F 6E 04 00 00 35 39 30 31 0B 00 00 46 6F -6B 6B 65 72 20 44 72 2E 31 07 00 00 49 74 61 6C -65 72 69 03 00 00 38 34 36 25 00 00 43 2D 31 33 -30 4A 20 48 65 72 63 75 6C 65 73 20 48 65 61 76 -79 20 54 72 61 6E 73 70 6F 72 74 20 50 6C 61 6E -65 04 00 00 37 36 31 30 15 00 00 46 65 72 72 61 -72 69 20 46 35 30 20 42 61 72 63 68 65 74 74 61 -03 00 00 41 4D 54 08 00 00 54 33 37 34 2D 32 32 -35 0D 00 00 43 6F 72 76 61 69 72 20 4D 6F 6E 7A -61 04 00 00 35 30 30 33 0B 00 00 4D 63 4C 61 72 -65 6E 20 4D 38 42 0D 00 00 52 65 76 65 6C 6C 20 -4C 6F 64 65 6C 61 05 00 00 48 2D 32 36 33 03 00 -00 75 6E 6B 23 00 00 42 6F 65 69 6E 67 20 53 53 -54 20 50 61 6E 41 6D 20 43 6C 69 70 70 65 72 20 -53 75 70 65 72 73 6F 6E 69 63 05 00 00 30 35 39 -30 39 05 00 00 31 2F 33 30 30 1D 00 00 4E 75 63 -6C 65 61 72 20 50 6F 77 65 72 65 64 20 53 70 61 -63 65 20 53 74 61 74 69 6F 6E 04 00 00 38 37 36 -34 06 00 00 31 2F 32 35 30 30 19 00 00 53 74 61 -72 20 54 72 65 6B 20 44 65 65 70 20 53 70 61 63 -65 20 4E 69 6E 65 23 00 00 46 69 62 65 72 2D 6F -70 74 69 63 20 4C 69 67 68 74 69 6E 67 2C 20 73 -6B 69 6C 6C 20 6C 65 76 65 6C 20 33 0D 00 00 53 -6B 69 6C 6C 20 6C 65 76 65 6C 20 33 04 00 00 38 -31 35 38 16 00 00 42 6C 75 65 70 72 69 6E 74 65 -72 20 50 61 72 74 73 20 50 61 63 6B 13 00 00 45 -6E 67 69 6E 65 73 20 61 6E 64 20 67 72 69 6C 6C -65 73 05 00 00 33 30 30 33 37 05 00 00 31 2F 32 -30 30 1E 00 00 4D 61 6E 20 49 6E 20 53 70 61 63 -65 20 52 6F 63 6B 65 74 20 43 6F 6C 6C 65 63 74 -69 6F 6E 53 00 00 4D 65 72 63 75 72 79 20 41 74 -6C 61 73 2C 20 4D 65 72 63 75 72 79 20 52 65 64 -73 74 6F 6E 65 2C 20 47 65 6D 69 6E 69 20 54 69 -74 61 6E 20 49 49 2C 20 53 61 74 75 72 6E 20 31 -42 20 41 70 6F 6C 6C 6F 2C 20 53 61 74 75 72 6E -20 56 20 41 70 6F 6C 6C 6F 04 00 00 35 30 38 33 -04 00 00 31 2F 33 32 11 00 00 41 70 6F 6C 6C 6F -20 53 70 61 63 65 63 72 61 66 74 09 00 00 4D 69 -6E 69 63 72 61 66 74 05 00 00 31 31 32 32 30 04 -00 00 31 2F 31 36 24 00 00 31 39 35 35 20 4D 65 -72 63 65 64 65 73 20 33 30 30 53 4C 20 22 47 75 -6C 6C 77 69 6E 67 22 20 43 6F 75 70 65 07 00 00 -38 35 2D 36 38 35 39 24 00 00 4D 75 73 74 61 6E -67 20 4D 75 73 63 6C 65 20 54 72 69 6F 20 27 36 -30 73 2C 20 27 37 30 73 2C 20 27 38 30 73 35 00 -00 31 39 36 34 20 31 2F 32 20 43 6F 6E 76 65 72 -74 69 62 6C 65 2C 20 31 39 37 30 20 42 6F 73 73 -20 33 30 32 2C 20 31 39 38 39 20 43 6F 6E 76 65 -72 74 69 62 6C 65 06 00 00 54 61 6D 69 79 61 05 -00 00 32 34 31 37 30 0A 00 00 4D 6F 72 67 61 6E -20 34 2F 34 07 00 00 38 35 2D 32 34 39 31 11 00 -00 36 37 20 43 6F 72 76 65 74 74 65 20 43 6F 75 -70 65 07 00 00 38 35 2D 32 35 33 34 0F 00 00 53 -68 65 6C 62 79 20 53 65 72 69 65 73 20 31 03 00 -00 35 36 32 11 00 00 41 73 74 6F 6E 20 4D 61 72 -74 69 6E 20 44 42 20 34 05 00 00 30 37 33 32 30 -13 00 00 50 6F 72 73 63 68 65 20 39 31 31 20 43 -61 72 72 65 72 61 07 00 00 54 65 73 74 6F 72 73 -03 00 00 33 38 36 04 00 00 32 39 37 32 16 00 00 -4D 65 72 63 65 64 65 73 20 33 30 30 20 53 4C 52 -20 22 37 32 32 22 08 00 00 4C 69 6E 64 62 65 72 -67 05 00 00 37 30 39 35 36 19 00 00 48 65 6C 6C -63 61 74 73 20 76 73 2E 20 42 65 74 74 79 20 42 -6F 6D 62 65 72 0C 00 00 48 65 6C 6C 63 61 74 20 -6F 6E 6C 79 05 00 00 30 34 36 30 39 18 00 00 45 -6B 72 61 6E 6F 70 6C 61 6E 20 41 2D 39 30 20 4F -72 6C 6A 6F 6E 6F 6B 05 00 00 31 31 36 32 36 18 -00 00 47 72 75 6D 6D 61 6E 20 58 46 35 46 2D 31 -20 53 6B 79 72 6F 63 6B 65 74 04 00 00 35 34 32 -30 0E 00 00 48 61 77 6B 65 72 20 48 61 72 72 69 -65 72 05 00 00 41 56 2D 38 41 06 00 00 65 64 75 -61 72 64 04 00 00 38 30 36 31 0F 00 00 50 2D 34 -30 30 20 41 69 72 61 63 6F 62 72 61 0B 00 00 43 -7A 65 63 68 20 4D 6F 64 65 6C 04 00 00 34 38 30 -36 16 00 00 43 75 72 74 69 73 73 20 58 50 2D 35 -35 20 41 73 63 65 6E 64 65 72 05 00 00 36 31 30 -37 34 14 00 00 44 6F 72 6E 69 65 72 20 44 6F 33 -33 35 41 20 50 66 69 65 6C 13 00 00 4B 79 75 73 -68 75 20 4A 37 57 31 20 53 68 69 6E 64 65 6E 0D -00 00 50 6C 61 6E 65 74 20 4D 6F 64 65 6C 73 03 -00 00 30 34 33 0F 00 00 48 65 6E 73 63 68 65 6C -20 48 73 20 50 38 37 05 00 00 52 65 73 69 6E 0D -00 00 53 70 65 63 69 61 6C 20 48 6F 62 62 79 08 -00 00 53 48 20 34 38 30 30 33 16 00 00 4D 63 44 -6F 6E 6E 65 6C 6C 20 58 46 2D 38 35 20 47 6F 62 -6C 69 6E 2A 00 00 4D 65 73 73 65 72 73 63 68 6D -69 74 74 20 42 66 31 30 39 45 20 27 42 75 6C 67 -61 72 69 61 6E 20 41 69 72 20 46 6F 72 63 65 27 -05 00 00 30 34 32 30 36 2D 00 00 41 69 72 62 75 -73 20 53 75 70 65 72 20 54 72 61 6E 73 70 6F 72 -74 65 72 20 41 33 30 30 2D 36 30 30 20 53 54 20 -22 42 65 6C 75 67 61 22 05 00 00 33 30 30 38 37 -0C 00 00 33 39 20 57 61 67 6F 6E 20 52 6F 64 04 -00 00 37 31 32 31 1A 00 00 31 39 33 32 20 46 6F -72 64 20 48 69 67 68 62 6F 79 20 52 6F 61 64 73 -74 65 72 2E 00 00 4C 69 6E 63 6F 6C 6E 20 4D 69 -6E 74 20 55 6C 74 72 61 20 4D 65 74 61 6C 20 53 -65 72 69 65 73 2C 20 53 6B 69 6C 6C 20 6C 65 76 -65 6C 20 33 0C 00 00 50 6F 6C 61 72 20 4C 69 67 -68 74 73 04 00 00 35 30 31 34 21 00 00 43 61 72 -6C 20 43 61 73 70 65 72 27 73 20 55 6E 64 65 72 -74 61 6B 65 72 20 44 72 61 67 73 74 65 72 07 00 -00 38 35 2D 32 35 39 32 20 00 00 33 39 20 43 68 -65 76 79 20 53 65 64 61 6E 20 44 65 6C 69 76 65 -72 79 20 4C 6F 77 72 69 64 65 72 07 00 00 38 35 -2D 35 39 30 34 12 00 00 4E 41 53 41 20 53 70 61 -63 65 20 53 68 75 74 74 6C 65 04 00 00 32 34 30 -30 1C 00 00 31 39 32 36 20 4D 61 63 6B 20 42 75 -6C 6C 64 6F 67 20 44 75 6D 70 20 54 72 75 63 6B -05 00 00 43 31 31 32 38 13 00 00 32 33 20 54 20 -52 6F 61 64 73 74 65 72 20 46 72 61 6D 65 05 00 -00 33 31 32 31 36 11 00 00 44 6F 64 67 65 20 56 -69 70 65 72 20 52 54 2D 31 30 07 00 00 50 72 6F -53 68 6F 70 04 00 00 32 33 30 31 05 00 00 31 31 -32 31 32 26 00 00 31 39 33 35 20 4D 6F 72 67 61 -6E 20 53 75 70 65 72 20 53 70 6F 72 74 73 20 54 -68 72 65 65 20 57 68 65 65 6C 65 72 0C 00 00 47 -75 6E 7A 65 20 53 61 6E 67 79 6F 13 00 00 54 72 -69 75 6D 70 68 20 54 52 32 20 4C 65 20 4D 61 6E -73 07 00 00 38 35 2D 31 39 31 31 0F 00 00 33 34 -20 46 6F 72 64 20 48 69 67 68 62 6F 79 17 00 00 -57 68 65 65 6C 73 20 6F 66 20 46 69 72 65 20 53 -6E 61 70 54 69 74 65 06 00 00 4A 6F 2D 48 61 6E -06 00 00 47 43 2D 33 30 30 20 00 00 43 68 72 79 -73 6C 65 72 20 43 6F 72 70 6F 72 61 74 69 6F 6E -20 54 75 72 62 69 6E 65 20 43 61 72 09 00 00 48 -31 32 38 35 3A 31 39 38 2B 00 00 54 6F 6D 6D 79 -20 49 76 6F 27 73 20 46 6F 75 72 20 45 6E 67 69 -6E 65 20 44 72 61 67 73 74 65 72 20 22 53 68 6F -77 62 6F 61 74 22 09 00 00 48 31 32 32 34 3A 32 -30 30 17 00 00 32 32 20 4A 52 20 52 6F 61 64 73 -74 65 72 20 44 72 61 67 73 74 65 72 0F 00 00 32 -20 63 6F 6D 70 6C 65 74 65 20 63 61 72 73 04 00 -00 36 34 33 35 04 00 00 36 34 33 38 07 00 00 38 -35 2D 37 36 36 38 0F 00 00 34 31 20 43 68 65 76 -79 20 50 69 63 6B 75 70 04 00 00 36 35 38 35 17 -00 00 42 61 62 79 6C 6F 6E 20 35 20 53 74 61 72 -66 75 72 79 20 4D 6B 2E 31 1C 00 00 4D 65 73 73 -65 72 73 63 68 6D 69 74 74 20 42 66 31 30 39 45 -20 47 61 6C 6C 61 6E 64 05 00 00 36 31 30 36 37 -1B 00 00 42 72 69 73 74 6F 6C 20 42 65 61 75 66 -69 67 68 74 65 72 20 54 46 2E 4D 6B 2E 58 12 00 -00 48 65 6E 73 63 68 65 6C 20 48 73 20 31 32 39 -42 2D 32 04 00 00 33 34 31 39 0D 00 00 50 2D 35 -31 43 20 4D 75 73 74 61 6E 67 07 00 00 38 35 2D -35 35 30 39 1B 00 00 48 65 69 6E 6B 65 6C 20 48 -65 31 31 31 20 47 65 72 6D 61 6E 20 42 6F 6D 62 -65 72 11 00 00 41 63 61 64 65 6D 79 20 4D 69 6E -69 63 72 61 66 74 04 00 00 32 31 34 35 1E 00 00 -4C 6F 63 6B 68 65 65 64 20 50 2D 33 38 4D 20 4E -69 67 68 74 20 4C 69 67 68 74 6E 69 6E 67 07 00 -00 38 35 2D 30 31 33 35 11 00 00 4F 53 32 55 2D -33 20 4B 69 6E 67 66 69 73 68 65 72 3B 00 00 41 -69 63 68 69 20 42 37 41 32 20 41 74 74 61 63 6B -20 42 6F 6D 62 65 72 20 20 52 79 75 73 65 69 20 -4B 61 69 20 28 47 72 61 63 65 29 20 27 46 6F 6C -64 69 6E 67 20 57 69 6E 67 27 15 00 00 58 46 35 -55 2D 31 20 46 6C 79 69 6E 67 20 50 61 6E 63 61 -6B 65 04 00 00 36 37 35 37 07 00 00 49 63 65 20 -27 54 27 07 00 00 38 35 2D 35 31 30 32 04 00 00 -53 68 69 70 15 00 00 55 2E 53 2E 53 2E 20 4E 6F -72 74 68 20 43 61 72 6F 6C 69 6E 61 0E 00 00 50 -61 72 74 73 20 62 79 20 50 61 72 6B 73 04 00 00 -31 30 30 34 0F 00 00 44 69 73 74 72 69 62 75 74 -6F 72 20 4B 69 74 12 00 00 50 53 46 20 4D 6F 64 -65 6C 20 53 75 70 70 6C 69 65 73 07 00 00 45 4B -44 31 30 30 30 1B 00 00 4D 6F 64 65 6C 20 43 61 -72 20 45 6E 67 69 6E 65 20 44 65 74 61 69 6C 20 -4B 69 74 04 00 00 38 34 33 35 1F 00 00 43 75 73 -74 6F 6D 20 26 20 43 6F 6D 70 65 74 69 74 69 6F -6E 20 50 61 72 74 73 20 50 61 63 6B 04 00 00 54 -36 34 32 27 00 00 22 57 69 6E 6E 69 65 20 4D 61 -65 22 20 57 69 6C 65 79 20 50 6F 73 74 27 73 20 -4C 6F 63 6B 68 65 65 64 20 56 65 67 61 06 00 00 -41 69 72 66 69 78 05 00 00 30 34 31 37 36 0C 00 -00 44 48 20 43 6F 6D 65 74 20 34 20 42 07 00 00 -38 35 2D 34 31 36 32 1B 00 00 4F 72 61 6E 67 65 -20 43 72 61 74 65 20 27 33 32 20 46 6F 72 64 20 -53 65 64 61 6E 06 00 00 38 36 30 35 50 4F 14 00 -00 46 69 61 74 20 44 6F 75 62 6C 65 20 44 72 61 -67 73 74 65 72 0B 00 00 42 6C 75 65 70 72 69 6E -74 65 72 06 00 00 48 2D 31 33 32 31 0C 00 00 47 -72 61 6E 20 54 75 72 69 73 6D 6F 07 00 00 38 35 -2D 37 36 33 37 15 00 00 33 31 20 46 6F 72 64 20 -4D 6F 64 65 6C 20 41 20 57 6F 6F 64 79 03 00 00 -4D 50 43 07 00 00 32 30 30 2D 32 30 30 16 00 00 -47 61 6E 67 62 75 73 74 65 72 73 20 32 38 20 4C -69 6E 63 6F 6C 6E 07 00 00 38 35 2D 32 35 36 39 -19 00 00 43 68 65 76 79 20 53 2D 31 30 20 4C 6F -77 72 69 64 65 72 20 33 27 6E 20 31 04 00 00 32 -32 31 31 04 00 00 35 35 30 35 1C 00 00 48 6F 72 -74 65 6E 20 48 6F 20 32 32 39 41 2D 31 20 46 6C -79 69 6E 67 20 57 69 6E 67 05 00 00 30 35 32 30 -31 1C 00 00 4D 63 44 6F 6E 6E 65 6C 6C 20 58 56 -2D 31 20 43 6F 6E 76 65 72 74 69 70 6C 61 6E 65 -07 00 00 38 35 2D 35 38 31 30 0F 00 00 53 52 2D -37 31 20 42 6C 61 63 6B 62 69 72 64 04 00 00 34 -35 32 32 19 00 00 4D 65 73 73 65 72 73 63 68 6D -69 74 74 20 42 66 2D 31 30 39 20 47 2D 31 30 16 -00 00 50 72 65 6D 69 75 6D 2C 20 73 6B 69 6C 6C -20 6C 65 76 65 6C 20 34 04 00 00 38 36 34 36 0B -00 00 48 6F 62 62 79 20 43 72 61 66 74 06 00 00 -48 43 31 35 34 39 16 00 00 56 61 6D 70 69 72 65 -20 46 33 20 4A 65 74 20 46 69 67 68 74 65 72 04 -00 00 33 34 30 31 0B 00 00 41 2D 33 36 20 41 70 -61 63 68 65 05 00 00 30 34 33 33 35 15 00 00 42 -6C 6F 68 6D 20 26 20 56 6F 73 73 20 42 56 20 50 -2D 31 39 34 09 00 00 30 31 33 30 4D 30 31 30 30 -34 00 00 43 6F 72 64 20 50 68 61 65 74 6F 6E 20 -53 65 64 61 6E 20 31 39 33 37 20 38 31 32 20 53 -75 70 65 72 63 68 61 72 67 65 64 20 43 6F 6E 76 -65 72 74 69 62 6C 65 07 00 00 38 35 2D 32 35 37 -39 15 00 00 56 57 20 42 65 65 74 6C 65 20 43 6F -6E 76 65 72 74 69 62 6C 65 04 00 00 37 34 33 38 -10 00 00 42 4D 57 20 5A 2D 31 20 52 6F 61 64 73 -74 65 72 04 00 00 36 31 34 38 0B 00 00 44 69 61 -62 6C 6F 20 41 65 72 6F 0B 00 00 55 6E 69 6F 6E -20 4D 6F 64 65 6C 2B 00 00 50 65 74 65 20 42 72 -6F 63 6B 27 73 20 53 43 43 41 20 43 68 61 6D 70 -69 6F 6E 20 42 52 45 2F 44 61 74 73 75 6E 20 32 -34 30 2D 5A 05 00 00 32 34 31 32 39 0D 00 00 4A -61 67 75 61 72 20 58 4A 20 32 32 30 05 00 00 30 -33 31 30 31 13 00 00 53 70 69 72 69 74 20 6F 66 -20 53 74 2E 20 4C 6F 75 69 73 05 00 00 30 36 31 -37 31 15 00 00 4F 72 69 6F 6E 20 32 30 30 31 20 -53 70 61 63 65 63 72 61 66 74 04 00 00 38 37 36 -36 05 00 00 31 2F 36 35 30 18 00 00 53 74 61 72 -20 54 72 65 6B 20 55 2E 53 2E 53 2E 20 52 65 6C -69 61 6E 74 07 00 00 38 35 2D 31 38 33 35 15 00 -00 4E 41 53 41 2F 4D 63 44 6F 6E 6E 65 6C 6C 20 -47 65 6D 69 6E 69 04 00 00 31 39 39 37 24 00 00 -43 68 61 6E 67 20 5A 68 65 6E 67 20 32 20 28 43 -5A 2D 32 45 29 20 4C 61 75 6E 63 68 20 56 65 68 -69 63 6C 65 05 00 00 31 31 32 31 30 04 00 00 31 -2F 32 30 13 00 00 4D 61 6B 6F 20 53 68 61 72 6B -20 53 68 6F 77 20 43 61 72 08 00 00 44 72 61 67 -73 74 65 72 08 00 00 4C 6F 77 72 69 64 65 72 04 -00 00 36 30 36 36 2F 00 00 57 69 6C 64 20 57 69 -6C 6C 69 65 20 42 6F 72 73 63 68 20 22 57 69 6E -67 65 64 20 45 78 70 72 65 73 73 22 20 41 6C 74 -65 72 65 64 20 52 6F 64 04 00 00 36 31 38 32 0F -00 00 31 39 33 33 20 57 69 6C 6C 79 73 20 56 61 -6E 07 00 00 38 35 2D 30 35 34 30 34 00 00 49 6E -61 75 67 75 72 61 6C 20 4D 41 54 43 4F 20 54 6F -6F 6C 73 20 53 75 70 65 72 6E 61 74 69 6F 6E 61 -6C 73 20 4E 69 74 72 6F 20 46 75 6E 6E 79 20 43 -61 72 04 00 00 36 33 35 35 1E 00 00 31 39 35 37 -20 43 68 65 76 72 6F 6C 65 74 20 43 6F 72 76 65 -74 74 65 20 47 61 73 73 65 72 07 00 00 38 35 2D -37 36 37 35 04 00 00 50 43 36 31 2A 00 00 47 72 -65 65 6E 20 48 6F 72 6E 65 74 20 46 6F 72 64 20 -22 54 22 20 53 68 6F 77 20 61 6E 64 20 47 6F 20 -52 6F 61 64 73 74 65 72 04 00 00 38 32 31 35 18 -00 00 31 39 34 30 20 46 6F 72 64 20 53 65 64 61 -6E 20 44 65 6C 69 76 65 72 79 07 00 00 38 35 2D -37 36 32 38 16 00 00 33 37 20 46 6F 72 64 20 50 -61 6E 65 6C 20 44 65 6C 69 76 65 72 79 04 00 00 -31 32 39 34 10 00 00 47 79 70 73 79 20 44 75 6E -65 20 42 75 67 67 79 06 00 00 48 2D 31 32 33 31 -23 00 00 43 68 72 79 73 6C 65 72 20 4E 65 77 20 -59 6F 72 6B 65 72 20 43 75 73 74 6F 6D 69 7A 69 -6E 67 20 4B 69 74 05 00 00 33 30 30 38 31 0E 00 -00 36 32 20 54 68 75 6E 64 65 72 62 69 72 64 04 -00 00 36 38 39 39 11 00 00 31 39 33 32 20 46 6F -72 64 20 50 68 61 65 74 6F 6E 05 00 00 33 30 32 -37 30 0D 00 00 31 39 36 38 20 50 6C 79 6D 6F 75 -74 68 04 00 00 38 38 34 32 17 00 00 47 72 75 6D -6D 61 6E 20 46 37 46 2D 33 4E 20 54 69 67 65 72 -63 61 74 04 00 00 48 32 34 34 14 00 00 4D 61 72 -74 69 6E 20 50 36 4D 20 53 65 61 6D 61 73 74 65 -72 04 00 00 35 35 30 30 0E 00 00 42 2D 32 35 48 -20 4D 69 74 63 68 65 6C 6C 04 00 00 33 34 30 32 -0D 00 00 50 2D 35 31 41 20 4D 75 73 74 61 6E 67 -04 00 00 36 34 32 31 3E 00 00 44 61 6D 62 75 73 -74 65 72 20 47 72 61 6E 64 20 53 6C 61 6D 20 42 -6F 6D 62 65 72 20 4C 61 6E 63 61 73 74 65 72 20 -42 49 20 53 70 65 63 69 61 6C 20 32 32 30 30 30 -6C 62 2E 20 42 6F 6D 62 05 00 00 31 34 34 34 33 -1E 00 00 4C 6F 63 6B 68 65 65 64 20 53 75 70 65 -72 2D 47 20 43 6F 6E 73 74 65 6C 6C 61 74 69 6F -6E 04 00 00 35 36 31 30 13 00 00 57 69 6C 6C 69 -61 6D 73 20 42 72 6F 73 2E 20 49 6E 63 2E 07 00 -00 34 38 2D 33 31 39 31 10 00 00 43 6F 72 62 65 -6E 20 53 75 70 65 72 2D 41 63 65 05 00 00 30 35 -30 30 32 10 00 00 52 65 74 72 69 65 76 65 72 20 -52 6F 63 6B 65 74 03 00 00 43 61 72 04 00 00 38 -35 38 38 1D 00 00 50 6C 79 6D 6F 75 74 68 20 50 -72 6F 77 6C 65 72 20 77 69 74 68 20 54 72 61 69 -6C 65 72 04 00 00 35 30 30 31 14 00 00 43 6F 72 -76 65 74 74 65 20 47 72 61 6E 64 20 53 70 6F 72 -74 04 00 00 37 31 30 38 1D 00 00 43 6F 72 76 65 -74 74 65 20 49 6E 64 79 20 22 44 72 65 61 6D 20 -4D 61 63 68 69 6E 65 22 04 00 00 38 30 35 39 0C -00 00 54 68 65 20 4D 75 6E 73 74 65 72 73 20 00 -00 42 6C 75 65 70 72 69 6E 74 65 72 3B 20 4D 75 -6E 73 74 65 72 73 20 4B 6F 61 63 68 20 6F 6E 6C -79 07 00 00 38 35 2D 34 31 36 36 05 00 00 43 6F -75 6E 74 3C 00 00 77 2F 43 75 74 74 69 6E 67 20 -45 64 67 65 20 43 45 43 34 38 30 38 36 20 48 65 -31 31 31 5A 20 22 5A 77 69 6C 6C 69 6E 67 22 20 -6B 69 74 2C 20 73 6B 69 6C 6C 20 6C 65 76 65 6C -20 33 07 00 00 38 35 2D 37 36 36 36 23 00 00 43 -75 73 74 6F 6D 20 53 69 6C 76 65 72 61 64 6F 20 -61 6E 64 20 57 61 76 65 72 69 64 65 72 20 42 6F -61 74 07 00 00 38 35 2D 36 38 35 38 16 00 00 53 -6E 61 6B 65 20 26 20 4D 6F 6E 67 6F 6F 73 65 20 -43 6F 6D 62 6F 07 00 00 38 35 2D 34 31 35 39 24 -00 00 4A 6F 65 20 41 6D 61 74 6F 20 53 75 70 65 -72 6D 61 6E 20 54 6F 70 20 46 75 65 6C 20 44 72 -61 67 73 74 65 72 04 00 00 37 35 34 31 0D 00 00 -53 6B 69 6C 6C 20 6C 65 76 65 6C 20 35 09 00 00 -48 38 32 35 2D 31 30 44 30 28 00 00 43 6F 63 61 -20 43 6F 6C 61 20 46 6F 72 64 20 4C 6F 75 69 73 -76 69 6C 6C 65 20 44 65 6C 69 76 65 72 79 20 54 -72 75 63 6B 07 00 00 38 35 2D 32 31 35 36 04 00 -00 32 39 35 34 0B 00 00 50 6F 72 73 63 68 65 20 -39 30 34 04 00 00 32 39 33 35 25 00 00 4C 61 6D -62 6F 72 67 68 69 6E 69 20 43 6F 75 6E 74 61 63 -68 20 32 35 74 68 20 41 6E 6E 69 76 65 72 73 61 -72 79 07 00 00 38 35 2D 37 36 31 36 1F 00 00 41 -6D 65 72 69 63 61 6E 20 49 6E 74 65 72 6E 61 74 -69 6F 6E 61 6C 20 44 72 61 67 73 74 65 72 07 00 -00 38 35 2D 35 32 34 31 0D 00 00 50 2D 35 31 44 -20 4D 75 73 74 61 6E 67 07 00 00 38 35 2D 35 37 -31 30 11 00 00 52 42 2D 33 36 48 20 50 65 61 63 -65 6D 61 6B 65 72 05 00 00 30 35 31 30 34 14 00 -00 52 65 70 75 62 6C 69 63 20 52 43 2E 33 20 53 -65 61 62 65 65 05 00 00 50 41 31 35 32 05 00 00 -36 31 30 36 36 25 00 00 44 65 48 61 76 69 6C 6C -61 6E 64 20 4D 6F 73 71 75 69 74 6F 20 42 20 4D -6B 2E 49 56 2F 50 52 20 4D 6B 2E 49 56 07 00 00 -38 35 2D 37 35 34 36 10 00 00 50 2D 36 31 20 42 -6C 61 63 6B 20 57 69 64 6F 77 07 00 00 38 35 2D -36 36 35 32 25 00 00 42 2D 31 37 46 20 46 6C 79 -69 6E 67 20 46 6F 72 74 72 65 73 73 20 22 4D 65 -6D 70 68 69 73 20 42 65 6C 6C 65 22 04 00 00 37 -35 30 30 0D 00 00 47 61 74 65 73 20 4C 65 61 72 -6A 65 74 03 00 00 35 31 39 15 00 00 47 72 75 6D -6D 61 6E 20 46 38 46 2D 32 20 42 65 61 72 63 61 -74 04 00 00 37 35 32 33 12 00 00 46 2D 31 30 34 -43 20 53 74 61 72 66 69 67 68 74 65 72 05 00 00 -36 31 30 37 30 15 00 00 56 6F 75 67 68 74 20 46 -34 55 2D 31 41 20 43 6F 72 73 61 69 72 07 00 00 -38 35 2D 37 36 36 34 19 00 00 42 61 6C 64 77 69 -6E 2D 4D 6F 74 69 6F 6E 20 44 72 61 67 20 43 6F -62 72 61 04 00 00 38 34 35 35 14 00 00 35 37 20 -43 68 65 76 72 6F 6C 65 74 20 42 65 6C 20 41 69 -72 16 00 00 50 72 6F 53 68 6F 70 2C 20 73 6B 69 -6C 6C 20 6C 65 76 65 6C 20 33 05 00 00 33 30 30 -35 32 0D 00 00 34 31 20 46 6F 72 64 20 57 6F 6F -64 79 07 00 00 38 35 2D 32 35 35 37 19 00 00 36 -30 20 43 68 65 76 79 20 48 61 72 64 74 6F 70 20 -4C 6F 77 72 69 64 65 72 07 00 00 38 35 2D 37 36 -33 38 09 00 00 41 65 72 6F 76 65 74 74 65 07 00 -00 38 35 2D 30 30 39 34 1B 00 00 4C 69 27 6C 20 -43 6F 66 66 69 6E 20 43 75 73 74 6F 6D 20 53 68 -6F 77 20 52 6F 64 04 00 00 38 32 39 30 0A 00 00 -53 27 43 6F 6F 6C 20 42 75 73 07 00 00 38 35 2D -32 35 39 37 12 00 00 53 74 72 65 65 74 20 46 69 -67 68 74 65 72 20 54 77 6F 04 00 00 37 36 30 39 -12 00 00 54 68 61 6D 65 73 20 50 61 6E 65 6C 20 -54 72 75 63 6B 07 00 00 38 35 2D 37 36 30 36 15 -00 00 44 61 6E 20 46 69 6E 6B 27 73 20 53 70 65 -65 64 77 61 67 6F 6E 05 00 00 30 35 35 30 35 1A -00 00 4D 61 72 74 69 6E 20 4D 2D 31 33 30 20 43 -68 69 6E 61 20 43 6C 69 70 70 65 72 07 00 00 38 -35 2D 30 30 31 35 0E 00 00 46 6F 72 64 20 54 72 -69 2D 4D 6F 74 6F 72 04 00 00 50 41 33 30 1A 00 -00 57 72 69 67 68 74 20 42 72 6F 74 68 65 72 73 -20 4B 69 74 74 79 20 48 61 77 6B 07 00 00 38 35 -2D 35 30 38 31 13 00 00 46 69 72 73 74 20 4C 75 -6E 61 72 20 4C 61 6E 64 69 6E 67 07 00 00 38 35 -2D 35 38 33 39 18 00 00 4D 65 73 73 65 72 73 63 -68 6D 69 74 74 20 42 66 20 31 31 30 20 47 2D 32 -04 00 00 43 48 34 31 04 00 00 4A 30 30 34 05 00 -00 4A 54 31 32 33 04 00 00 4A 54 32 32 04 00 00 -4A 54 37 31 04 00 00 53 50 36 33 04 00 00 42 54 -31 36 0C 00 00 4F 56 2D 31 42 20 4D 6F 68 61 77 -6B 03 00 00 30 36 38 0B 00 00 56 2D 32 32 20 4F -73 70 72 65 79 04 00 00 38 36 31 35 13 00 00 58 -2F 59 42 2D 33 35 20 46 6C 79 69 6E 67 20 57 69 -6E 67 05 00 00 31 31 32 30 38 1B 00 00 31 39 33 -33 20 43 61 64 69 6C 6C 61 63 20 56 2D 31 36 20 -54 6F 77 6E 20 43 61 72 04 00 00 36 36 31 38 27 -00 00 53 74 61 72 20 54 72 65 6B 20 33 20 50 69 -65 63 65 20 55 2E 53 2E 53 2E 20 45 6E 74 65 72 -70 72 69 73 65 20 53 65 74 12 00 00 4D 69 73 73 -69 6E 67 20 54 56 20 76 65 72 73 69 6F 6E 04 00 -00 38 39 31 35 0E 00 00 53 74 61 72 20 44 65 73 -74 72 6F 79 65 72 04 00 00 38 31 39 33 0A 00 00 -44 65 61 74 68 20 53 74 61 72 08 00 00 53 6E 61 -70 54 69 74 65 07 00 00 38 35 2D 33 36 32 31 07 -00 00 38 35 2D 33 36 32 32 17 00 00 42 61 62 79 -6C 6F 6E 20 35 20 53 70 61 63 65 20 53 74 61 74 -69 6F 6E 04 00 00 36 38 35 38 1F 00 00 53 74 61 -72 20 54 72 65 6B 20 33 20 50 69 65 63 65 20 41 -64 76 65 72 73 61 72 79 20 53 65 74 04 00 00 38 -37 36 32 06 00 00 31 2F 31 30 30 30 29 00 00 53 -74 61 72 20 54 72 65 6B 20 47 65 6E 65 72 61 74 -69 6F 6E 73 20 55 2E 53 2E 53 2E 20 45 6E 74 65 -72 70 72 69 73 65 20 42 04 00 00 38 38 38 33 03 -00 00 31 2F 34 05 00 00 4F 74 68 65 72 12 00 00 -56 69 73 69 62 6C 65 20 56 2D 38 20 45 6E 67 69 -6E 65 04 00 00 37 31 32 30 1C 00 00 31 39 36 39 -20 50 6F 6E 74 69 61 63 20 47 54 4F 20 22 54 68 -65 20 4A 75 64 67 65 22 09 00 00 31 2F 32 34 2D -31 2F 32 35 05 00 00 31 2F 31 33 30 05 00 00 31 -2F 35 37 30 05 00 00 54 6F 20 64 6F 33 00 00 47 -75 73 20 47 72 69 73 73 6F 6D 20 4D 65 6D 6F 72 -69 61 6C 20 43 6F 6D 62 6F 20 77 2F 54 77 6F 20 -43 6F 6C 6C 65 63 74 6F 72 73 20 50 61 74 63 68 -65 73 09 00 00 46 69 72 65 20 49 72 6F 6E 0C 00 -00 77 2F 64 65 74 61 69 6C 20 73 65 74 2C 00 00 -77 2F 64 65 74 61 69 6C 20 73 65 74 20 61 6E 64 -20 69 6E 74 65 72 69 6F 72 20 73 65 74 2C 20 72 -65 73 69 6E 20 65 6E 67 69 6E 65 73 03 00 00 49 -43 4D 0E 00 00 53 70 69 74 66 69 72 65 20 4D 6B -2E 49 58 1A 00 00 4D 65 73 73 65 72 73 63 68 6D -69 74 74 20 4D 65 20 34 31 30 42 2D 32 2F 55 34 -0A 00 00 4D 6F 64 65 6C 63 72 61 66 74 12 00 00 -46 2D 38 32 42 20 54 77 69 6E 20 4D 75 73 74 61 -6E 67 1F 00 00 31 39 35 33 20 53 74 75 64 65 62 -61 6B 65 72 20 53 74 61 72 6C 69 6E 65 72 20 43 -6F 75 70 65 04 00 00 32 34 33 36 0E 00 00 42 75 -67 61 74 74 69 20 45 42 20 31 31 30 2D 00 00 53 -74 61 72 20 54 72 65 6B 20 4B 6C 69 6E 67 6F 6E -20 42 69 72 64 20 6F 66 20 50 72 65 79 20 46 6C -69 67 68 74 20 44 69 73 70 6C 61 79 16 00 00 50 -6F 72 73 63 68 65 20 39 31 31 20 53 6C 61 6E 74 -20 4E 6F 73 65 05 00 00 36 31 30 37 33 25 00 00 -44 6F 75 67 6C 61 73 20 41 2D 31 4A 20 53 6B 79 -72 61 69 64 65 72 20 55 2E 53 2E 20 41 69 72 20 -46 6F 72 63 65 04 00 00 36 33 33 39 04 00 00 36 -39 35 35 04 00 00 37 35 33 30 06 00 00 34 38 2D -30 32 30 05 00 00 31 2F 34 35 30 0F 00 00 55 2E -53 2E 53 2E 20 4D 69 73 73 6F 75 72 69 05 00 00 -36 31 30 35 37 15 00 00 48 65 69 6E 6B 65 6C 20 -48 65 32 31 39 20 41 2D 37 20 55 48 55 05 00 00 -36 31 30 34 31 05 00 00 31 31 36 32 34 32 00 00 -43 6F 6E 73 6F 6C 69 64 61 74 65 64 20 42 2D 32 -34 4A 20 4C 69 62 65 72 61 74 6F 72 20 54 68 65 -20 44 72 61 67 6F 6E 20 26 20 48 69 73 20 54 61 -69 diff --git a/test-data/spreadsheet/BigSSTRecord2 b/test-data/spreadsheet/BigSSTRecord2 deleted file mode 100644 index 88697cddf..000000000 --- a/test-data/spreadsheet/BigSSTRecord2 +++ /dev/null @@ -1,515 +0,0 @@ - FC 00 1F 20 B2 6B 02 00 81 14 00 00 18 00 00 - 46 61 63 2E 20 43 61 73 75 61 6C 74 79 20 4D 61 - 6E 61 67 65 72 20 47 43 04 00 00 35 33 36 39 17 - 00 00 44 69 73 74 72 69 62 75 74 69 6F 6E 20 43 - 6F 6E 73 75 6C 74 61 6E 74 04 00 00 35 33 37 39 - 11 00 00 47 72 6C 2E 20 57 6F 72 6B 73 74 61 74 - 69 6F 6E 73 04 00 00 35 33 38 32 04 00 00 35 33 - 38 37 04 00 00 35 33 38 38 13 00 00 47 72 6C 2E - 20 47 72 6F 75 70 20 41 63 63 6F 75 6E 74 73 04 - 00 00 35 34 33 34 04 00 00 35 34 33 35 0C 00 00 - 54 4C 20 54 65 6C 65 6D 61 74 69 6B 04 00 00 35 - 34 33 37 04 00 00 35 34 34 33 14 00 00 42 75 66 - 66 65 74 6D 69 74 61 72 62 65 69 74 65 72 2F 69 - 6E 04 00 00 35 34 34 36 04 00 00 35 34 36 32 12 - 00 00 54 65 61 6D 6C 65 61 64 65 72 20 4C 69 62 - 72 61 72 79 04 00 00 35 34 36 35 04 00 00 35 34 - 36 37 04 00 00 35 34 36 39 11 00 00 4C 65 69 74 - 65 72 20 46 61 68 72 64 69 65 6E 73 74 04 00 00 - 35 34 38 37 04 00 00 35 34 39 32 04 00 00 35 34 - 39 33 03 00 00 41 55 44 04 00 00 35 35 30 36 04 - 00 00 35 35 30 39 19 00 00 48 65 61 64 20 6F 66 - 20 41 70 70 6C 2E 20 44 65 76 65 6C 6F 70 6D 65 - 6E 74 04 00 00 35 35 31 31 04 00 00 35 35 31 33 - 04 00 00 35 35 33 32 04 00 00 35 35 33 37 04 00 - 00 35 35 35 34 04 00 00 35 35 35 35 16 00 00 54 - 65 61 6D 6C 65 69 74 65 72 69 6E 20 43 61 66 65 - 74 65 72 69 61 04 00 00 35 35 35 37 14 00 00 50 - 72 6F 6A 65 6B 74 6D 69 74 61 72 62 65 69 74 65 - 72 69 6E 04 00 00 35 35 36 33 04 00 00 35 35 37 - 39 04 00 00 35 35 38 39 15 00 00 45 78 70 65 72 - 74 65 20 54 72 6F 70 2E 20 5A 79 6B 6C 6F 6E 65 - 04 00 00 35 35 39 38 11 00 00 45 69 6E 6B 61 75 - 66 73 61 73 73 69 73 74 65 6E 74 04 00 00 35 36 - 30 36 04 00 00 35 36 33 38 04 00 00 35 36 34 32 - 04 00 00 35 36 36 33 04 00 00 35 36 36 34 13 00 - 00 48 65 61 64 20 6F 66 20 4C 41 2F 4C 45 2F 4C - 4E 20 4F 50 04 00 00 35 36 37 35 04 00 00 35 36 - 37 39 04 00 00 35 36 38 30 04 00 00 35 36 38 32 - 04 00 00 35 36 38 38 0A 00 00 54 65 61 6D 6C 65 - 61 64 65 72 03 00 00 47 42 50 04 00 00 35 36 39 - 33 04 00 00 35 36 39 35 04 00 00 35 36 39 36 04 - 00 00 35 36 39 38 09 00 00 53 75 70 70 6F 72 74 - 65 72 04 00 00 35 36 39 39 04 00 00 35 37 30 36 - 13 00 00 48 65 61 64 20 6F 66 20 4C 41 2F 4C 45 - 2F 4C 4E 20 48 52 04 00 00 35 37 30 37 13 00 00 - 4B 6E 6F 77 6C 65 64 67 65 20 4E 65 74 77 6F 72 - 6B 65 72 04 00 00 35 37 30 38 0E 00 00 52 69 73 - 69 6B 6F 65 78 70 65 72 74 69 6E 04 00 00 35 37 - 31 30 04 00 00 35 37 31 39 04 00 00 35 37 32 33 - 18 00 00 47 72 6C 2E 20 43 65 6E 74 72 2E 20 4F - 70 65 72 2E 20 53 79 73 74 65 6D 04 00 00 35 37 - 33 31 04 00 00 35 37 33 34 18 00 00 48 65 61 64 - 20 4D 65 64 69 61 4E 65 74 77 2E 61 74 20 52 FC - 73 63 68 2E 04 00 00 35 37 33 38 04 00 00 35 37 - 35 31 04 00 00 35 37 35 39 04 00 00 35 37 36 30 - 04 00 00 35 37 36 35 04 00 00 35 37 36 36 02 00 - 00 42 4D 08 00 00 48 61 6D 69 6C 74 6F 6E 04 00 - 00 35 37 37 35 04 00 00 35 37 37 36 04 00 00 35 - 37 38 31 04 00 00 35 37 38 35 14 00 00 55 6E 64 - 65 72 77 72 69 74 69 6E 67 20 53 75 70 70 6F 72 - 74 04 00 00 35 37 38 37 16 00 00 54 65 61 6D 6C - 65 69 74 65 72 20 65 78 74 2E 20 4B 75 72 69 65 - 72 04 00 00 35 37 39 31 04 00 00 35 38 31 31 04 - 00 00 35 38 32 30 04 00 00 35 38 32 32 04 00 00 - 35 38 33 32 04 00 00 35 38 35 30 14 00 00 50 72 - 6F 6A 65 6B 74 6C 65 69 74 65 72 20 50 20 2B 20 - 45 52 04 00 00 35 38 35 31 04 00 00 35 38 35 37 - 04 00 00 35 38 35 38 04 00 00 35 38 38 30 19 00 - 00 48 65 61 64 20 43 6F 72 70 2E 4C 65 61 72 6E - 2E 61 74 20 52 FC 73 63 68 2E 04 00 00 35 38 38 - 31 04 00 00 35 38 38 35 0E 00 00 4C 65 69 74 65 - 72 20 48 52 20 53 52 47 53 04 00 00 35 38 39 33 - 02 00 00 42 45 04 00 00 35 38 39 36 04 00 00 35 - 39 30 30 15 00 00 48 65 61 64 20 6F 66 20 44 69 - 76 69 73 69 6F 6E 61 6C 20 49 54 04 00 00 35 39 - 31 34 14 00 00 43 6F 6D 70 65 6E 73 61 74 69 6F - 6E 20 4D 61 6E 61 67 65 72 04 00 00 35 39 31 35 - 04 00 00 35 39 31 39 04 00 00 35 39 32 30 03 00 - 00 4E 5A 44 04 00 00 35 39 32 33 04 00 00 35 39 - 33 34 04 00 00 35 39 33 37 04 00 00 35 39 34 32 - 04 00 00 35 39 34 33 12 00 00 53 65 72 76 69 63 - 65 2D 53 70 65 7A 69 61 6C 69 73 74 04 00 00 35 - 39 34 38 04 00 00 35 39 35 32 04 00 00 35 39 35 - 36 04 00 00 35 39 35 37 04 00 00 35 39 35 38 17 - 00 00 47 72 6C 2E 20 53 74 6F 72 61 67 65 20 4D - 61 6E 61 67 65 6D 65 6E 74 04 00 00 35 39 36 34 - 02 00 00 42 41 04 00 00 35 39 36 35 04 00 00 35 - 39 37 35 04 00 00 35 39 37 36 04 00 00 35 39 37 - 39 0F 00 00 52 65 63 68 74 73 6B 6F 6E 73 75 6C - 65 6E 74 04 00 00 35 39 38 31 16 00 00 45 6E 67 - 6C 69 73 63 68 2D 55 65 62 65 72 73 65 74 7A 65 - 72 69 6E 04 00 00 35 39 39 34 18 00 00 48 65 61 - 64 20 47 50 4D 20 4D 61 72 69 6E 65 2F 41 76 69 - 61 74 69 6F 6E 04 00 00 36 30 30 32 0D 00 00 4B - 65 6C 6C 65 72 6D 65 69 73 74 65 72 04 00 00 36 - 30 30 34 04 00 00 36 30 31 33 19 00 00 44 6F 63 - 75 6D 65 6E 74 20 4D 67 6D 74 2E 20 43 6F 6E 73 - 75 6C 74 61 6E 74 04 00 00 36 30 31 35 04 00 00 - 36 30 32 30 04 00 00 36 30 32 36 04 00 00 36 30 - 33 30 02 00 00 52 36 04 00 00 36 30 33 31 17 00 - 00 48 61 75 73 77 69 72 74 73 63 68 61 66 74 73 - 6C 65 69 74 65 72 69 6E 04 00 00 36 30 33 33 04 - 00 00 36 30 35 33 0A 00 00 46 61 68 72 64 69 65 - 6E 73 74 04 00 00 36 30 35 37 04 00 00 36 30 36 - 39 17 00 00 47 72 75 70 70 65 6E 6C 65 69 74 65 - 72 69 6E 20 53 75 70 70 6F 72 74 04 00 00 36 30 - 38 38 19 00 00 49 74 61 6C 69 65 6E 69 73 63 68 - 2D 55 65 62 65 72 73 65 74 7A 65 72 69 6E 02 00 - 00 48 4B 04 00 00 36 30 39 31 04 00 00 36 31 31 - 32 04 00 00 36 31 31 37 04 00 00 36 31 32 31 10 - 00 00 54 65 61 6D 6C 65 69 74 65 72 20 50 4D 2F - 46 4D 04 00 00 36 31 32 37 04 00 00 36 31 33 34 - 04 00 00 36 31 34 36 0B 00 00 54 65 6C 65 6D 61 - 74 69 6B 65 72 04 00 00 36 31 35 36 19 00 00 44 - 69 76 2E 20 46 69 6E 61 6E 63 69 61 6C 20 43 6F - 6E 74 72 6F 6C 6C 65 72 04 00 00 36 31 35 38 0B - 00 00 55 53 4D 20 4D 6F 6E 74 65 75 72 04 00 00 - 36 31 36 32 0A 00 00 49 54 2D 41 75 64 69 74 6F - 72 04 00 00 36 31 36 34 04 00 00 36 31 36 35 04 - 00 00 36 31 36 37 04 00 00 36 31 36 38 04 00 00 - 36 31 37 30 04 00 00 36 31 37 32 17 00 00 4C 65 - 69 74 65 72 20 47 61 73 74 72 6F 6E 6F 6D 69 65 - 62 65 74 72 2E 04 00 00 36 31 38 38 02 00 00 54 - 58 04 00 00 36 31 38 39 16 00 00 50 72 6F 64 75 - 63 74 20 54 61 78 20 53 70 65 63 69 61 6C 69 73 - 74 04 00 00 36 31 39 36 0A 00 00 43 46 4F 20 4F - 66 66 69 63 65 02 00 00 53 50 04 00 00 36 32 30 - 33 14 00 00 41 73 73 69 73 74 65 6E 74 69 6E 20 - 55 2E 20 42 72 65 6D 69 04 00 00 36 32 30 37 04 - 00 00 36 32 31 31 10 00 00 47 72 6F 75 70 20 41 - 63 63 6F 75 6E 74 61 6E 74 04 00 00 36 32 31 35 - 19 00 00 4C 65 69 74 65 72 20 54 65 6C 65 63 6F - 6D 6D 75 6E 69 63 61 74 69 6F 6E 73 04 00 00 36 - 32 32 35 04 00 00 36 32 33 32 04 00 00 36 32 35 - 30 06 00 00 4D 6F 73 63 6F 77 04 00 00 36 32 35 - 35 04 00 00 36 32 36 31 04 00 00 36 32 36 35 04 - 00 00 36 32 36 37 12 00 00 41 62 74 65 69 6C 75 - 6E 67 73 6C 65 69 74 65 72 69 6E 04 00 00 36 32 - 36 38 0F 00 00 53 70 6F 72 74 61 6E 6C 61 67 65 - 77 61 72 74 04 00 00 36 32 37 31 04 00 00 36 32 - 37 32 15 00 00 50 75 62 6C 69 73 68 69 6E 67 20 - 43 6F 6E 73 75 6C 74 61 6E 74 04 00 00 36 32 37 - 39 04 00 00 36 32 38 30 15 00 00 53 61 63 68 62 - 65 61 72 62 2E 20 4B 61 73 73 65 20 53 6F 6F 64 - 04 00 00 36 33 32 34 12 00 00 50 72 6F 64 75 63 - 74 20 53 70 65 63 69 61 6C 69 73 74 04 00 00 36 - 33 33 39 04 00 00 36 33 34 34 0F 00 00 50 72 6F - 67 72 61 6D 20 4D 61 6E 61 67 65 72 04 00 00 36 - 33 34 36 04 00 00 36 33 34 37 12 00 00 45 6E 67 - 6C 69 73 63 68 FC 62 65 72 73 65 74 7A 65 72 04 - 00 00 36 33 34 39 19 00 00 53 65 63 74 69 6F 6E - 20 48 65 61 64 20 43 6F 6E 74 72 2E 20 50 72 6F - 6A 2E 04 00 00 36 33 35 30 10 00 00 52 65 73 65 - 61 72 63 68 20 4D 61 6E 61 67 65 72 04 00 00 36 - 33 36 38 0C 00 00 44 61 74 61 20 4D 61 6E 61 67 - 65 72 04 00 00 36 33 36 39 04 00 00 36 33 37 32 - 19 00 00 42 65 74 72 69 65 62 73 74 65 63 68 6E - 69 6B 65 72 20 45 6C 65 6B 74 72 6F 04 00 00 36 - 33 37 34 04 00 00 36 33 37 35 04 00 00 36 33 39 - 39 11 00 00 44 65 73 69 67 6E 20 43 6F 6E 73 75 - 6C 74 61 6E 74 04 00 00 36 34 30 30 04 00 00 36 - 34 30 32 04 00 00 36 34 30 34 13 00 00 41 63 74 - 75 61 72 69 61 6C 20 41 73 73 69 73 74 61 6E 74 - 04 00 00 36 34 30 35 04 00 00 36 34 30 36 04 00 - 00 36 34 30 37 04 00 00 36 34 30 38 04 00 00 36 - 34 31 32 04 00 00 36 34 31 33 04 00 00 36 34 31 - 34 04 00 00 36 34 32 33 04 00 00 36 34 32 34 13 - 00 00 57 65 62 20 50 72 6F 6A 65 63 74 20 4D 61 - 6E 61 67 65 72 04 00 00 36 34 32 38 04 00 00 36 - 34 34 32 04 00 00 36 34 35 33 19 00 00 53 61 63 - 68 62 65 61 72 62 65 69 74 65 72 69 6E 20 43 61 - 73 75 61 6C 74 79 04 00 00 36 34 36 32 15 00 00 - 48 65 61 64 20 6F 66 20 42 61 6C 61 6E 63 65 20 - 53 68 65 65 74 04 00 00 36 34 37 33 10 00 00 41 - 63 63 6F 75 6E 74 20 4D 67 72 20 55 53 4C 4C 04 - 00 00 36 34 37 34 18 00 00 48 65 61 64 20 6F 66 - 20 45 61 72 74 68 71 75 61 6B 65 20 47 72 6F 75 - 70 04 00 00 36 34 37 36 04 00 00 36 34 38 30 0C - 00 00 4C 65 69 74 65 72 69 6E 20 47 4E 53 04 00 - 00 36 34 38 36 17 00 00 4B 6F 6D 6D 75 6E 69 6B - 61 74 69 6F 6E 73 62 65 72 61 74 65 72 69 6E 04 - 00 00 36 34 39 33 0E 00 00 46 26 42 20 4B 6F 6E - 74 72 6F 6C 6C 65 72 04 00 00 36 34 39 36 16 00 - 00 4C 65 69 74 65 72 69 6E 20 43 61 66 65 74 65 - 72 69 61 20 42 36 36 04 00 00 36 34 39 38 09 00 - 00 41 73 73 69 73 74 61 6E 74 04 00 00 36 35 30 - 30 04 00 00 36 35 30 38 04 00 00 36 35 30 39 04 - 00 00 36 35 31 30 04 00 00 36 35 32 33 04 00 00 - 36 35 33 31 14 00 00 53 74 76 2E 20 43 68 65 66 - 20 64 65 20 53 65 72 76 69 63 65 04 00 00 36 35 - 33 32 04 00 00 36 35 33 33 04 00 00 36 35 33 35 - 12 00 00 42 65 74 72 69 65 62 73 61 6C 6C 72 6F - 75 6E 64 65 72 04 00 00 36 35 34 32 14 00 00 45 - 6C 65 63 74 72 6F 6E 69 63 20 50 75 62 6C 69 73 - 68 65 72 04 00 00 36 35 35 32 18 00 00 54 72 65 - 61 74 79 20 55 57 20 50 72 6F 70 2E 2F 43 61 73 - 75 61 6C 74 79 04 00 00 36 35 35 37 04 00 00 36 - 35 36 33 13 00 00 54 65 61 6D 6C 65 69 74 65 72 - 20 4D 61 74 65 72 69 61 6C 04 00 00 36 35 36 36 - 04 00 00 36 35 37 38 10 00 00 53 74 72 61 74 65 - 67 79 20 41 6E 61 6C 79 73 74 02 00 00 46 47 04 - 00 00 36 35 37 39 18 00 00 48 65 61 64 20 6F 66 - 20 50 72 6F 63 65 73 73 20 50 6C 61 6E 26 4D 67 - 74 04 00 00 36 36 31 33 16 00 00 49 6E 74 65 72 - 6E 61 74 69 6F 6E 61 6C 20 41 73 73 69 67 6E 65 - 65 04 00 00 36 36 32 31 04 00 00 36 36 32 36 04 - 00 00 36 36 32 37 0D 00 00 45 76 65 6E 74 20 4D - 61 6E 61 67 65 72 04 00 00 36 36 32 39 04 00 00 - 36 36 33 32 04 00 00 36 36 33 37 15 00 00 44 65 - 70 75 74 79 20 48 65 61 64 20 6F 66 20 45 76 65 - 6E 74 73 04 00 00 36 36 33 39 19 00 00 48 65 61 - 64 20 6F 66 20 43 65 6E 74 72 65 20 52 FC 73 63 - 68 6C 69 6B 6F 6E 04 00 00 36 36 34 34 11 00 00 - 53 65 6E 69 6F 72 20 43 6F 6E 74 72 6F 6C 6C 65 - 72 02 00 00 43 4D 04 00 00 36 36 34 38 12 00 00 - 47 6C 6F 62 61 6C 20 49 47 50 20 4D 61 6E 61 67 - 65 72 04 00 00 36 36 35 33 17 00 00 4C 65 69 74 - 65 72 20 4C 6F 74 75 73 20 4E 6F 74 65 73 20 47 - 4E 4E 4F 04 00 00 36 36 35 37 04 00 00 36 36 36 - 31 16 00 00 50 72 6F 6A 65 63 74 20 4D 61 6E 61 - 67 65 72 20 4D 61 67 6E 75 6D 04 00 00 36 36 36 - 37 04 00 00 36 36 37 35 04 00 00 36 36 38 33 04 - 00 00 36 36 38 35 17 00 00 4F 72 67 61 6E 69 73 - 61 74 69 6F 6E 73 2D 41 73 73 69 73 74 65 6E 74 - 04 00 00 36 36 38 36 04 00 00 36 36 39 32 14 00 - 00 50 65 72 73 6F 6E 61 6C 65 6E 74 77 69 63 6B - 6C 65 72 69 6E 04 00 00 36 36 39 33 04 00 00 36 - 36 39 34 19 00 00 53 61 63 68 62 2E 45 69 6E 6B - 61 75 66 2F 42 75 63 68 68 61 6C 74 75 6E 67 04 - 00 00 36 36 39 37 16 00 00 47 72 6C 2E 20 44 42 - 20 41 64 6D 69 6E 69 73 74 72 61 74 69 6F 6E 04 - 00 00 36 37 30 31 04 00 00 36 37 30 32 04 00 00 - 36 37 30 36 04 00 00 36 37 31 34 04 00 00 36 37 - 32 31 04 00 00 36 37 33 31 04 00 00 36 37 33 33 - 04 00 00 36 37 33 34 04 00 00 36 37 34 33 04 00 - 00 36 37 34 35 0A 00 00 50 52 2D 42 65 72 61 74 - 65 72 04 00 00 36 37 34 36 04 00 00 36 37 34 38 - 04 00 00 36 37 35 31 17 00 00 53 70 65 63 69 61 - 6C 69 73 74 20 52 65 74 72 6F 2F 43 52 45 53 54 - 41 04 00 00 36 37 35 33 17 00 00 53 65 6E 69 6F - 72 20 43 6F 72 70 2E 20 41 63 63 6F 75 6E 74 61 - 6E 74 04 00 00 36 37 35 38 04 00 00 36 37 36 33 - 18 00 00 5A 65 69 74 73 63 68 72 69 66 74 65 6E - 76 65 72 77 61 6C 74 65 72 69 6E 01 00 00 43 04 - 00 00 36 37 36 36 04 00 00 36 37 36 38 14 00 00 - 43 6F 6D 70 65 6E 73 61 74 69 6F 6E 20 53 75 70 - 70 6F 72 74 04 00 00 36 37 37 30 0A 00 00 54 65 - 61 6D 6C 65 69 74 65 72 04 00 00 36 37 37 32 16 - 00 00 49 6E 66 6F 72 6D 61 74 69 6F 6E 20 53 70 - 65 63 69 61 6C 69 73 74 04 00 00 36 37 37 33 15 - 00 00 48 65 61 64 20 6F 66 20 53 79 73 74 65 6D - 73 20 47 72 6F 75 70 04 00 00 36 37 37 34 04 00 - 00 36 37 37 35 04 00 00 36 37 38 32 15 00 00 46 - 61 63 68 72 65 66 65 72 65 6E 74 69 6E 20 55 6D - 77 65 6C 74 04 00 00 36 37 38 34 02 00 00 52 53 - 04 00 00 36 37 38 36 02 00 00 4B 52 05 00 00 53 - 65 6F 75 6C 04 00 00 36 37 38 38 04 00 00 36 37 - 39 38 0F 00 00 43 68 65 66 20 64 65 20 53 65 72 - 76 69 63 65 04 00 00 36 38 30 38 04 00 00 36 38 - 31 30 18 00 00 48 65 61 64 20 6F 66 20 52 69 73 - 6B 20 43 6F 6E 74 72 6F 6C 6C 69 6E 67 04 00 00 - 36 38 32 36 0F 00 00 53 74 65 75 65 72 6B 6F 6E - 73 75 6C 65 6E 74 04 00 00 36 38 32 38 15 00 00 - 54 65 61 6D 6C 65 69 74 65 72 20 50 E2 74 69 73 - 73 65 72 69 65 04 00 00 36 38 33 31 0B 00 00 53 - 65 6B 72 65 74 61 72 69 61 74 04 00 00 36 38 35 - 30 04 00 00 36 38 35 32 04 00 00 36 38 35 35 04 - 00 00 36 38 36 36 04 00 00 36 38 37 35 04 00 00 - 36 38 37 36 04 00 00 36 38 37 37 04 00 00 44 61 - 74 65 04 00 00 44 65 70 74 04 00 00 43 69 74 79 - 04 00 00 55 6E 69 74 07 00 00 53 75 62 55 6E 69 - 74 03 00 00 49 44 32 05 00 00 50 68 6F 6E 65 04 - 00 00 4E 61 6D 65 09 00 00 46 69 72 73 74 4E 61 - 6D 65 06 00 00 4F 6C 64 4A 6F 62 08 00 00 4A 6F - 62 44 65 73 63 72 06 00 00 53 74 61 74 75 73 05 - 00 00 53 74 61 74 33 05 00 00 53 74 61 74 34 06 - 00 00 44 65 67 72 65 65 08 00 00 50 6F 73 69 74 - 69 6F 6E 08 00 00 45 78 70 65 6E 73 65 73 09 00 - 00 45 78 70 65 6E 73 65 73 32 09 00 00 45 78 70 - 65 6E 73 65 73 34 09 00 00 45 78 70 65 6E 73 65 - 73 33 09 00 00 45 78 70 65 6E 73 65 73 35 09 00 - 00 45 78 70 65 6E 73 65 73 36 09 00 00 45 78 70 - 65 6E 73 65 73 37 05 00 00 4C 65 76 65 6C 06 00 - 00 52 65 70 6F 72 74 05 00 00 47 72 6F 75 70 04 - 00 00 50 6F 6F 6C 05 00 00 44 4B 65 79 50 05 00 - 00 44 4D 44 50 4D 08 00 00 42 65 6E 67 61 6C 69 - 78 07 00 00 54 65 6E 61 6C 69 78 0B 00 00 33 32 - 34 2D 54 65 6E 61 6C 69 78 06 00 00 48 61 6E 6E - 69 78 05 00 00 31 30 39 33 30 04 00 00 32 38 39 - 37 04 00 00 38 39 31 37 04 00 00 33 31 35 33 04 - 00 00 38 37 33 36 04 00 00 34 33 32 33 05 00 00 - 31 31 35 37 35 04 00 00 37 31 35 34 04 00 00 33 - 38 35 38 04 00 00 33 32 35 34 04 00 00 39 37 30 - 39 04 00 00 37 33 36 39 04 00 00 34 31 39 35 04 - 00 00 39 37 30 37 04 00 00 36 38 31 37 04 00 00 - 35 35 34 34 08 00 00 53 61 6E 74 69 61 67 6F 04 - 00 00 34 32 30 33 05 00 00 31 30 38 34 37 05 00 - 00 31 31 36 35 36 05 00 00 31 33 30 31 34 04 00 - 00 31 39 30 36 04 00 00 35 35 39 34 04 00 00 35 - 32 32 31 04 00 00 38 36 38 31 04 00 00 38 31 37 - 38 04 00 00 36 31 38 30 05 00 00 31 31 32 39 39 - 04 00 00 39 33 33 33 05 00 00 31 32 33 31 35 05 - 00 00 31 31 30 34 35 05 00 00 31 32 32 32 37 01 - 00 00 49 04 00 00 33 36 39 31 04 00 00 37 30 33 - 34 04 00 00 32 31 30 37 04 00 00 35 32 30 35 04 - 00 00 36 30 35 35 04 00 00 34 36 30 30 04 00 00 - 36 38 39 39 04 00 00 36 39 30 35 05 00 00 31 32 - 31 34 30 04 00 00 37 36 35 35 05 00 00 38 30 30 - 39 37 04 00 00 34 32 37 32 05 00 00 31 30 38 37 - 36 04 00 00 37 33 38 35 04 00 00 34 31 30 31 04 - 00 00 38 32 32 35 04 00 00 32 34 37 31 04 00 00 - 35 31 37 35 04 00 00 38 36 34 31 05 00 00 31 32 - 33 32 31 05 00 00 31 32 38 39 32 04 00 00 37 36 - 38 37 04 00 00 37 32 37 37 04 00 00 37 31 34 37 - 05 00 00 31 30 32 39 34 04 00 00 35 31 31 37 05 - 00 00 31 30 30 30 32 04 00 00 37 37 38 30 04 00 - 00 36 34 38 32 05 00 00 38 30 32 35 30 08 00 00 - 41 63 74 75 61 72 79 2C 05 00 00 31 31 37 39 35 - 05 00 00 31 31 37 32 31 05 00 00 31 31 39 38 32 - 05 00 00 31 33 30 33 31 04 00 00 38 32 33 32 04 - 00 00 35 34 36 38 04 00 00 39 33 33 37 04 00 00 - 36 38 37 38 05 00 00 31 31 39 36 36 04 00 00 37 - 37 34 34 05 00 00 31 31 30 37 36 05 00 00 31 32 - 39 31 32 04 00 00 37 39 35 33 05 00 00 31 32 32 - 36 35 04 00 00 36 35 36 34 04 00 00 38 32 33 36 - 04 00 00 37 30 33 38 04 00 00 33 36 33 33 04 00 - 00 38 36 34 32 04 00 00 35 34 38 36 04 00 00 33 - 39 37 39 04 00 00 35 39 32 37 04 00 00 35 34 31 - 35 05 00 00 31 32 31 35 34 03 00 00 35 36 35 13 - 00 00 4C 61 74 69 6E 20 41 6D 65 72 69 63 61 20 - 53 6F 75 74 68 0E 00 00 43 6F 6C 6F 6D 62 69 61 - 20 26 20 4F 53 41 02 00 00 35 35 11 00 00 50 72 - 6F 64 75 63 74 20 45 78 65 63 75 74 69 76 65 02 - 00 00 53 48 02 00 00 4C 59 02 00 00 34 36 0F 00 - 00 48 65 61 64 20 4C 41 20 41 63 61 64 65 6D 79 - 07 00 00 54 72 61 69 6E 65 72 02 00 00 53 45 02 - 00 00 50 50 03 00 00 50 4C 4E 02 00 00 34 32 11 - 00 00 54 72 65 61 74 79 20 53 70 65 63 69 61 6C - 69 73 74 04 00 00 31 31 31 35 13 00 00 55 6E 64 - 65 72 77 72 69 74 69 6E 67 20 54 72 65 61 74 79 - 02 00 00 53 41 02 00 00 4D 45 04 00 00 31 35 33 - 30 04 00 00 31 35 35 37 14 00 00 52 65 6C 61 74 - 69 6F 6E 73 68 69 70 20 4D 61 6E 61 67 65 72 04 - 00 00 31 35 37 36 04 00 00 31 38 32 31 0F 00 00 - 48 65 61 64 20 43 6F 72 70 6F 72 61 74 65 73 0A - 00 00 41 63 63 6F 75 6E 74 69 6E 67 04 00 00 32 - 30 34 39 14 00 00 50 6C 61 6E 6E 69 6E 67 20 43 - 6F 6F 72 64 69 6E 61 74 6F 72 02 00 00 54 44 04 - 00 00 32 31 35 30 0F 00 00 48 65 61 64 20 43 4F - 43 20 4D 61 72 69 6E 65 04 00 00 32 31 35 36 10 - 00 00 4D 61 72 6B 65 74 20 45 78 65 63 75 74 69 - 76 65 04 00 00 32 35 37 32 18 00 00 48 65 61 64 - 20 6F 66 20 46 61 63 75 6C 74 61 74 69 76 65 20 - 44 65 73 6B 0C 00 00 41 64 52 20 43 61 73 75 61 - 6C 74 79 04 00 00 32 38 34 32 0C 00 00 55 57 20 - 54 72 65 61 74 79 20 45 4E 02 00 00 53 4B 04 00 - 00 33 30 38 32 18 00 00 44 69 76 69 73 69 6F 6E - 61 6C 20 43 6F 6D 6D 75 6E 69 63 61 74 69 6F 6E - 02 00 00 50 43 04 00 00 33 30 38 30 19 00 00 48 - 65 61 64 20 43 65 6E 74 65 72 20 6F 66 20 43 6F - 6D 70 2E 20 50 72 6F 70 0E 00 00 4C 6F 63 61 6C - 20 53 65 72 76 69 63 65 73 19 00 00 43 6C 69 65 - 6E 74 20 4D 61 6E 61 67 65 72 20 43 6F 72 70 6F - 72 61 74 65 73 04 00 00 33 34 30 39 18 00 00 55 - 6E 64 65 72 77 72 69 74 69 6E 67 20 45 6E 67 69 - 6E 65 65 72 69 6E 67 04 00 00 33 34 36 32 17 00 - 00 48 65 61 64 20 6F 66 20 42 55 53 20 50 72 6F - 6A 65 63 74 73 20 5A 48 04 00 00 33 34 33 34 19 - 00 00 48 65 61 64 20 43 65 6E 74 65 72 20 6F 66 - 20 43 6F 6D 70 2E 20 43 61 73 2E 04 00 00 33 37 - 38 31 18 00 00 48 65 61 64 20 4D 61 72 6B 65 74 - 69 6E 67 20 26 20 52 65 6C 2E 20 5A 48 04 00 00 - 33 39 32 31 11 00 00 41 63 63 6F 75 6E 74 20 45 - 78 65 63 75 74 69 76 65 04 00 00 33 39 37 31 04 - 00 00 34 31 31 31 04 00 00 34 31 36 33 13 00 00 - 52 65 6C 61 74 69 6F 6E 20 4D 61 6E 61 67 65 72 - 20 55 53 04 00 00 34 30 38 33 0B 00 00 55 57 20 - 50 72 6F 70 65 72 74 79 04 00 00 34 33 34 30 04 - 00 00 34 34 37 38 16 00 00 43 65 6E 74 65 72 20 - 6F 66 20 43 6F 6D 70 2E 20 4D 61 72 69 6E 65 04 - 00 00 34 35 37 38 15 00 00 55 57 20 53 75 70 70 - 6F 72 74 20 43 6F 72 70 6F 72 61 74 65 73 04 00 - 00 34 35 38 31 18 00 00 43 65 6E 74 65 72 20 6F - 66 20 43 6F 6D 70 2E 20 43 61 73 75 61 6C 74 79 - 04 00 00 34 39 33 37 14 00 00 41 73 73 69 73 74 - 61 6E 74 20 43 6F 72 70 6F 72 61 74 65 73 0C 00 - 00 43 6F 75 6E 74 72 79 20 48 65 61 64 04 00 00 - 35 33 31 36 17 00 00 48 65 61 64 20 43 65 6E 74 - 65 72 20 6F 66 20 43 6F 6D 70 2E 20 45 4E 04 00 - 00 35 33 39 35 16 00 00 41 73 73 2E 20 50 72 6F - 64 75 63 74 20 45 78 65 63 75 74 69 76 65 04 00 - 00 35 36 31 39 12 00 00 50 72 6F 6A 65 63 74 20 - 4C 65 61 64 65 72 20 42 55 53 04 00 00 35 35 37 - 31 18 00 00 43 65 6E 74 65 72 20 6F 66 20 43 6F - 6D 70 2E 20 50 72 6F 70 65 72 74 79 04 00 00 35 - 36 33 33 17 00 00 48 65 61 64 20 4D 61 6E 61 67 - 65 6D 65 6E 74 20 53 75 70 70 6F 72 74 04 00 00 - 35 37 35 32 10 00 00 48 65 61 64 20 54 72 65 61 - 74 79 20 44 65 73 6B 04 00 00 35 36 39 31 19 00 - 00 44 65 70 2E 48 65 61 64 20 43 65 6E 74 65 72 - 20 43 6F 6D 70 2E 43 61 73 2E 04 00 00 35 38 36 - 34 04 00 00 35 39 32 34 0F 00 00 50 72 6F 64 75 - 63 74 20 53 75 70 70 6F 72 74 04 00 00 35 39 34 - 30 19 00 00 44 65 70 2E 48 65 61 64 20 43 65 6E - 74 65 72 20 43 6F 6D 70 2E 45 6E 67 2E 04 00 00 - 36 30 31 30 04 00 00 36 30 34 35 18 00 00 48 65 - 61 64 20 43 6F 43 20 53 74 72 75 63 74 2E 20 46 - 69 6E 61 6E 63 65 04 00 00 36 31 34 39 04 00 00 - 36 31 36 36 13 00 00 48 65 61 64 20 6F 66 20 43 - 6F 43 20 61 67 72 6F 20 4C 41 04 00 00 36 33 33 - 31 04 00 00 36 36 32 34 13 00 00 50 72 6F 64 75 - 63 74 20 44 65 76 65 6C 6F 70 6D 65 6E 74 04 00 - 00 36 35 33 37 04 00 00 36 38 30 36 04 00 00 36 - 39 33 38 15 00 00 55 57 20 53 74 72 75 63 74 75 - 72 65 73 20 46 69 6E 61 6E 63 65 04 00 00 37 30 - 37 33 0F 00 00 52 75 6E 2D 4F 66 66 20 41 6C 69 - 61 6E 7A 61 04 00 00 37 30 39 30 15 00 00 4A 75 - 6E 69 6F 72 20 43 6C 69 65 6E 74 20 4D 61 6E 61 - 67 65 72 04 00 00 37 34 33 37 0B 00 00 33 32 34 - 2C 20 42 6F 67 6F 74 61 04 00 00 37 35 32 39 10 - 00 00 53 70 65 63 69 61 6C 20 50 72 6F 6A 65 63 - 74 73 04 00 00 37 36 33 31 16 00 00 4F 70 65 72 - 61 74 69 6F 6E 73 20 4D 61 6E 61 67 65 72 20 44 - 55 4F 04 00 00 38 34 32 33 04 00 00 38 34 36 35 - 04 00 00 38 35 30 36 0F 00 00 54 72 61 69 6E 65 - 72 20 53 69 63 73 2F 6E 74 04 00 00 38 36 30 36 - 04 00 00 38 35 31 30 04 00 00 39 32 30 39 05 00 - 00 31 30 31 38 36 05 00 00 31 30 35 38 33 10 00 - 00 54 72 61 69 6E 69 6E 67 20 4D 61 6E 61 67 65 - 72 05 00 00 31 30 35 38 36 03 00 00 32 38 38 05 - 00 00 31 30 37 34 37 14 00 00 48 65 61 64 20 44 - 69 76 2E 20 49 54 20 55 6E 69 74 20 5A 48 03 00 - 00 49 4C 53 05 00 00 31 30 39 34 34 15 00 00 48 - 65 61 64 20 53 70 65 63 69 61 6C 20 50 72 6F 6A - 65 63 74 73 04 00 00 37 30 37 37 05 00 00 31 30 - 39 38 36 03 00 00 45 45 4B 05 00 00 31 31 32 39 - 37 14 00 00 48 52 20 26 53 65 72 76 69 63 65 73 - 20 4D 61 6E 61 67 65 72 10 00 00 41 64 52 20 41 - 6C 67 6F 64 F3 6E 2F 41 67 72 6F 05 00 00 31 31 - 37 32 37 11 00 00 43 6C 61 69 6D 73 20 44 65 73 - 6B 2F 4C 65 67 61 6C 11 00 00 54 65 63 68 6E 69 - 63 61 6C 20 4D 61 6E 61 67 65 72 03 00 00 32 38 - 39 13 00 00 43 6C 69 65 6E 74 20 54 65 61 6D 20 - 53 75 70 70 6F 72 74 06 00 00 41 64 52 20 58 4C - 05 00 00 31 31 38 37 31 0C 00 00 41 64 52 20 50 - 72 6F 70 65 72 74 79 05 00 00 31 32 36 30 30 06 - 00 00 4D 61 64 72 69 64 07 00 00 31 34 38 36 33 - 39 35 07 00 00 36 35 30 36 33 33 31 06 00 00 42 - 65 6A 69 6E 67 0C 00 00 42 75 65 6E 6F 73 20 41 - 69 72 65 73 07 00 00 43 6F 6C 6F 67 6E 65 08 00 - 00 42 72 75 73 73 65 6C 73 02 00 00 56 45 07 00 - 00 43 61 72 61 63 61 73 02 00 00 50 4C 06 00 00 - 57 61 72 73 61 77 02 00 00 4A 50 05 00 00 54 6F - 6B 79 6F 04 00 00 52 6F 6D 65 05 00 00 31 32 36 - 30 31 19 00 00 48 65 61 64 20 6F 66 20 4C 69 66 - 65 26 48 65 61 6C 74 68 20 49 6E 64 69 61 16 00 - 00 41 73 73 69 73 74 65 6E 74 69 6E 20 4C 65 69 - 74 65 72 20 43 43 43 02 00 00 33 35 10 00 00 41 - 72 63 68 69 76 73 70 65 7A 69 61 6C 69 73 74 02 - 00 00 32 2B 02 00 00 33 2D 02 00 00 34 2D 12 00 - 00 41 72 63 68 69 76 73 70 65 7A 69 61 6C 69 73 - 74 69 6E 02 00 00 33 2B 02 00 00 48 43 0F 00 00 - 4D 69 74 67 6C 69 65 64 20 64 65 72 20 47 4C 13 - 00 00 41 64 76 65 72 74 69 73 69 6E 67 20 4D 61 - 6E 61 67 65 72 02 00 00 32 35 0C 00 00 50 34 30 - 30 20 53 75 70 70 6F 72 74 12 00 00 49 6E 74 65 - 72 6E 61 74 2E 20 54 72 61 6E 73 66 65 72 01 00 - 00 47 19 00 00 44 65 70 2E 43 68 69 65 66 45 78 - 65 63 75 74 69 76 65 4F 66 66 69 63 65 72 10 00 - 00 50 72 E4 73 69 64 65 6E 74 20 64 65 72 20 47 - 4C 0D 00 00 47 72 75 70 70 65 6E 6C 65 69 74 65 - 72 02 00 00 43 59 15 00 00 46 FC 68 72 75 6E 67 - 73 75 6E 74 65 72 73 74 FC 74 7A 75 6E 67 0C 00 - 00 43 49 2D 41 73 73 69 73 74 61 6E 74 06 00 00 - 32 30 30 30 30 39 03 00 00 37 32 30 10 00 00 48 - 65 61 64 20 6F 66 20 47 72 6F 75 70 20 49 41 02 - 00 00 53 54 19 00 00 49 6E 74 65 72 6E 2E 47 72 - 61 64 75 61 74 65 20 50 72 6F 67 2E 4D 67 74 2E - 18 00 00 53 79 73 74 65 6D 76 65 72 61 6E 74 77 - 6F 72 74 6C 2E 20 50 49 4C 41 53 00 00 00 0A 00 - 00 33 35 33 2D 59 54 38 31 33 30 19 00 00 50 72 - 69 63 69 6E 67 20 41 63 74 75 61 72 69 61 6C 20 - 41 6E 61 6C 79 73 74 19 00 00 54 65 63 68 6E 69 - 63 61 6C 20 43 6C 61 69 6D 73 20 43 6F 6E 73 75 - 6C 74 2E 18 00 00 47 72 75 70 70 65 6E 6C 65 69 - 74 65 72 69 6E 20 43 61 73 75 61 6C 74 79 19 00 - 00 41 73 73 69 73 74 61 6E 74 20 47 72 6F 75 70 - 20 50 4D 20 4D 61 72 69 6E 65 0E 00 00 44 65 62 - 74 20 43 6F 6C 6C 65 63 74 6F 72 10 00 00 45 78 - 70 65 72 74 65 20 45 72 64 62 65 62 65 6E 15 00 - 00 47 72 6F 75 70 20 4C 69 61 69 73 6F 6E 20 4F - 66 66 69 63 65 72 15 00 00 48 65 61 64 20 41 75 - 64 69 74 2F 49 6E 73 70 65 63 74 69 6F 6E 18 00 - 00 48 65 61 64 20 6F 66 20 43 6C 61 69 6D 73 20 - 26 20 43 2E 20 4D 67 74 2E 08 00 00 42 65 72 6D - 75 64 61 73 04 00 00 4E 45 49 4E 1C 00 00 53 65 - 63 72 65 74 61 72 79 20 69 6E 20 4E 65 77 20 59 - 6F 72 6B 20 4F 66 66 69 63 65 02 00 00 31 32 01 - 00 00 31 03 00 00 32 32 30 02 00 00 31 30 15 00 - 00 54 65 6C 65 6D 61 74 69 6B 2D 53 75 70 70 6F - 72 74 65 72 69 6E 13 00 00 54 4C 20 54 65 6C 65 - 6D 61 74 69 6B 73 75 70 70 6F 72 74 19 00 00 55 - 53 20 47 41 41 50 2D 50 72 6F 6A 65 6B 74 6C 65 - 69 74 65 72 20 53 52 5A 02 00 00 32 2D 09 00 00 - 41 73 73 69 73 74 65 6E 74 0D 00 00 42 57 20 45 - 78 70 65 72 74 65 20 43 4F 19 00 00 52 61 74 69 - 6E 67 20 41 67 65 6E 63 79 20 43 6F 6F 72 64 69 - 6E 61 74 6F 72 0F 00 00 50 72 6F 6A 65 6B 74 6C - 65 69 74 65 72 69 6E 14 00 00 53 65 6E 69 6F 72 - 20 41 63 63 6F 75 6E 74 61 6E 74 20 51 41 14 00 - 00 53 65 6E 69 6F 72 20 4C 65 67 61 6C 20 41 64 - 76 69 73 65 72 16 00 00 53 65 6E 69 6F 72 20 50 - 72 6F 6A 65 63 74 20 4D 61 6E 61 67 65 72 13 00 - 00 41 73 73 69 73 74 61 6E 74 20 55 57 20 4D 61 - 72 69 6E 65 diff --git a/test-data/spreadsheet/BigSSTRecord2CR1 b/test-data/spreadsheet/BigSSTRecord2CR1 deleted file mode 100644 index 359e3b4a3..000000000 --- a/test-data/spreadsheet/BigSSTRecord2CR1 +++ /dev/null @@ -1,514 +0,0 @@ - 3C 00 18 20 10 00 00 42 75 73 69 6E - 65 73 73 20 53 75 70 70 6F 72 74 03 00 00 49 45 - 50 15 00 00 43 6F 75 6E 74 72 79 20 48 65 61 64 - 20 43 6F 6C 6F 6D 62 69 61 03 00 00 59 45 53 02 - 00 00 43 31 01 00 00 59 04 00 00 31 2E 30 30 02 - 00 00 43 34 02 00 00 43 35 01 00 00 20 02 00 00 - 43 37 02 00 00 43 38 02 00 00 43 39 03 00 00 43 - 31 30 03 00 00 43 31 31 13 00 00 4D 61 72 69 6E - 65 20 52 69 73 6B 20 41 6E 61 6C 79 73 74 03 00 - 00 43 31 32 03 00 00 43 31 33 03 00 00 43 31 34 - 03 00 00 43 31 35 03 00 00 43 31 36 03 00 00 43 - 31 37 03 00 00 43 31 38 03 00 00 43 32 30 03 00 - 00 43 32 31 03 00 00 43 32 32 03 00 00 43 32 33 - 03 00 00 43 32 34 03 00 00 43 32 35 03 00 00 43 - 32 36 03 00 00 43 32 37 12 00 00 54 65 63 68 6E - 69 63 61 6C 20 44 69 72 65 63 74 6F 72 03 00 00 - 43 32 38 03 00 00 43 32 39 03 00 00 43 33 30 03 - 00 00 43 33 31 09 00 00 35 2F 30 33 2F 31 39 36 - 31 03 00 00 43 33 32 03 00 00 43 33 33 03 00 00 - 43 33 34 03 00 00 43 33 35 03 00 00 43 33 36 03 - 00 00 43 33 37 03 00 00 43 33 38 03 00 00 43 33 - 39 03 00 00 43 34 30 03 00 00 43 34 31 0A 00 00 - 31 30 2E 31 32 2E 31 39 35 31 0A 00 00 31 35 2E - 30 31 2E 31 39 39 36 01 00 00 66 0A 00 00 32 37 - 2E 30 31 2E 31 39 35 33 0A 00 00 30 39 2E 30 35 - 2E 31 39 39 35 01 00 00 6D 0A 00 00 30 36 2E 30 - 34 2E 31 39 36 37 0A 00 00 30 31 2E 30 31 2E 31 - 39 39 39 0A 00 00 31 37 2E 30 38 2E 31 39 35 35 - 0A 00 00 30 31 2E 31 32 2E 31 39 39 35 0A 00 00 - 32 30 2E 30 31 2E 31 39 37 33 0A 00 00 31 35 2E - 30 39 2E 31 39 39 37 0A 00 00 30 34 2E 31 31 2E - 31 39 35 39 0A 00 00 30 38 2E 31 31 2E 31 39 39 - 36 01 00 00 35 0A 00 00 31 35 2E 30 36 2E 31 39 - 37 31 0A 00 00 30 31 2E 30 39 2E 31 39 39 39 0A - 00 00 32 30 2E 30 38 2E 31 39 37 30 0A 00 00 32 - 38 2E 30 38 2E 31 39 39 35 0A 00 00 31 30 2E 30 - 39 2E 31 39 35 35 0A 00 00 30 31 2E 30 38 2E 32 - 30 30 30 0A 00 00 31 38 2E 30 38 2E 31 39 36 35 - 0A 00 00 32 32 2E 30 37 2E 31 39 39 32 0A 00 00 - 32 34 2E 30 39 2E 31 39 35 36 0A 00 00 32 30 2E - 31 30 2E 31 39 39 37 16 00 00 48 52 20 26 20 4C - 6F 67 69 73 74 69 63 73 20 4D 61 6E 61 67 65 72 - 0A 00 00 32 38 2E 30 37 2E 31 39 36 33 0A 00 00 - 30 31 2E 31 30 2E 31 39 39 39 04 00 00 33 35 35 - 35 04 00 00 33 35 35 36 04 00 00 33 35 37 32 19 - 00 00 53 65 6E 2E 20 4C 65 67 61 6C 20 43 6C 61 - 69 6D 73 20 43 6F 75 6E 73 65 6C 04 00 00 33 35 - 37 33 0F 00 00 53 70 65 7A 69 61 6C 61 75 66 67 - 61 62 65 6E 04 00 00 33 35 38 37 04 00 00 33 36 - 31 34 19 00 00 43 6F 6D 6D 75 6E 69 63 61 74 69 - 6F 6E 73 20 43 6F 6E 73 75 6C 74 61 6E 74 04 00 - 00 33 36 32 31 04 00 00 33 36 32 32 14 00 00 47 - 72 6C 2E 20 4B 6F 70 69 65 72 7A 65 6E 74 72 61 - 6C 65 6E 04 00 00 33 36 32 38 04 00 00 33 36 33 - 35 11 00 00 48 65 61 64 20 6F 66 20 49 41 20 5A - 75 72 69 63 68 04 00 00 33 36 33 36 0D 00 00 47 - 72 6C 2E 20 48 61 72 64 77 61 72 65 04 00 00 33 - 36 34 39 0D 00 00 44 6F 63 75 6D 65 6E 74 61 6C - 69 73 74 04 00 00 33 36 37 31 11 00 00 43 6F 72 - 70 6F 72 61 74 65 20 41 63 74 75 61 72 79 04 00 - 00 33 36 37 36 0D 00 00 48 65 61 64 20 6F 66 20 - 4C 45 2F 41 53 04 00 00 33 36 37 39 04 00 00 33 - 36 38 39 04 00 00 33 37 31 31 15 00 00 53 70 65 - 7A 69 61 6C 69 73 74 20 50 75 62 6C 69 73 68 69 - 6E 67 04 00 00 33 37 31 33 04 00 00 33 37 31 34 - 04 00 00 33 37 32 32 04 00 00 33 37 32 39 19 00 - 00 4C 65 69 74 65 72 20 50 6C 61 74 66 6F 72 6D - 20 45 6E 67 69 6E 65 65 72 2E 04 00 00 33 37 33 - 30 13 00 00 4D 61 6E 2E 20 41 64 6D 69 6E 69 73 - 74 72 61 74 69 6F 6E 04 00 00 33 37 33 36 17 00 - 00 48 65 61 64 20 6F 66 20 4C 6F 67 2E 20 4F 70 - 65 72 61 74 69 6F 6E 73 04 00 00 33 37 34 30 04 - 00 00 33 37 34 33 17 00 00 55 6E 64 65 72 77 72 - 69 74 69 6E 67 20 43 6F 6E 73 75 6C 74 61 6E 74 - 04 00 00 33 37 34 38 04 00 00 33 37 35 31 04 00 - 00 33 37 36 32 04 00 00 33 37 36 34 06 00 00 42 - 6F 67 6F 74 61 01 00 00 52 04 00 00 33 37 36 35 - 0D 00 00 52 65 67 69 6F 6E 61 6C 20 48 65 61 64 - 04 00 00 33 37 36 38 10 00 00 55 6E 64 65 72 77 - 72 69 74 65 72 20 41 67 72 6F 04 00 00 33 37 38 - 33 04 00 00 33 37 38 38 11 00 00 42 65 74 72 69 - 65 62 73 73 63 68 72 65 69 6E 65 72 04 00 00 33 - 37 39 33 19 00 00 53 65 6E 2E 20 47 72 6F 75 70 - 77 61 72 65 20 43 6F 6E 73 75 6C 74 61 6E 74 04 - 00 00 33 37 39 38 12 00 00 46 61 63 68 62 65 72 - 65 69 63 68 73 6C 65 69 74 65 72 04 00 00 33 38 - 30 30 0C 00 00 42 75 63 68 68 61 6C 74 65 72 69 - 6E 04 00 00 33 38 30 37 19 00 00 47 72 75 70 70 - 65 6E 6C 65 69 74 65 72 20 45 6E 74 77 69 63 6B - 6C 75 6E 67 04 00 00 33 38 31 31 0D 00 00 44 61 - 74 65 6E 74 79 70 69 73 74 69 6E 04 00 00 33 38 - 31 38 19 00 00 48 61 75 73 77 69 72 74 73 63 68 - 61 66 74 73 6D 69 74 61 72 62 65 69 74 2E 04 00 - 00 33 38 32 35 04 00 00 33 38 32 36 17 00 00 48 - 65 61 64 20 6F 66 20 47 72 6F 75 70 20 50 4D 20 - 43 72 65 64 69 74 04 00 00 33 38 32 38 0F 00 00 - 4D 65 64 69 63 61 6C 20 4F 66 66 69 63 65 72 04 - 00 00 33 38 35 31 04 00 00 33 38 35 32 04 00 00 - 33 38 37 30 04 00 00 33 38 37 36 19 00 00 4D 61 - 6E 2E 20 4C 65 67 61 6C 20 43 6C 61 69 6D 73 20 - 43 6F 75 6E 73 65 6C 04 00 00 33 38 38 36 04 00 - 00 33 38 38 37 0C 00 00 50 52 2D 42 65 72 61 74 - 65 72 69 6E 04 00 00 33 38 38 38 17 00 00 54 65 - 61 6D 6C 65 69 74 65 72 20 41 75 73 67 61 6E 67 - 73 70 6F 73 74 04 00 00 33 38 38 39 08 00 00 48 - 61 75 73 77 61 72 74 04 00 00 33 38 39 38 10 00 - 00 42 75 73 69 6E 65 73 73 20 41 6E 61 6C 79 73 - 74 04 00 00 33 38 39 39 19 00 00 53 65 63 74 2E - 20 48 65 61 64 20 49 6E 76 2E 20 52 65 6C 61 74 - 69 6F 6E 73 04 00 00 33 39 30 37 17 00 00 47 72 - 6C 2E 20 52 5A 20 50 6C 61 6E 2E 2F 53 74 65 75 - 65 72 75 6E 67 04 00 00 33 39 32 38 17 00 00 47 - 72 6C 2E 20 57 6F 72 6B 73 74 61 74 69 6F 6E 20 - 45 6E 67 69 6E 2E 04 00 00 33 39 33 35 02 00 00 - 43 50 04 00 00 33 39 33 36 11 00 00 47 72 6C 2E - 20 46 6C 75 74 2F 53 79 73 74 65 6D 65 04 00 00 - 33 39 35 32 04 00 00 33 39 35 35 04 00 00 33 39 - 36 39 04 00 00 33 39 37 37 13 00 00 42 4C 20 44 - 61 74 61 62 61 73 65 20 53 79 73 74 65 6D 73 04 - 00 00 33 39 38 30 04 00 00 33 39 38 33 04 00 00 - 33 39 38 36 04 00 00 33 39 38 39 04 00 00 33 39 - 39 30 14 00 00 47 72 6F 75 70 77 61 72 65 20 43 - 6F 6E 73 75 6C 74 61 6E 74 04 00 00 34 30 31 31 - 04 00 00 34 30 31 32 04 00 00 34 30 31 38 04 00 - 00 34 30 32 35 04 00 00 34 30 33 30 19 00 00 4F - 70 65 72 61 74 72 69 63 65 20 4B 6F 70 69 65 72 - 7A 65 6E 74 72 61 6C 65 04 00 00 34 30 33 31 0E - 00 00 55 6D 7A 75 67 73 66 61 63 68 6D 61 6E 6E - 04 00 00 34 30 33 35 04 00 00 34 30 33 37 04 00 - 00 34 30 33 39 04 00 00 34 30 34 32 04 00 00 34 - 30 35 32 04 00 00 34 30 35 38 04 00 00 34 30 35 - 39 04 00 00 34 30 36 34 18 00 00 48 65 61 64 20 - 6F 66 20 53 75 70 70 6F 72 74 20 53 65 72 76 69 - 63 65 73 04 00 00 34 30 38 30 15 00 00 53 61 63 - 68 62 65 61 72 62 65 69 74 65 72 69 6E 20 46 69 - 62 75 04 00 00 34 30 38 31 04 00 00 34 30 38 32 - 17 00 00 4D 69 74 61 72 62 2E 20 53 69 63 68 65 - 72 68 65 69 74 73 6C 6F 67 65 02 00 00 49 43 04 - 00 00 34 30 38 36 04 00 00 34 30 39 36 04 00 00 - 34 31 30 35 04 00 00 34 31 30 36 04 00 00 34 31 - 30 38 13 00 00 53 75 70 70 6F 72 74 65 72 20 48 - 65 6C 70 20 44 65 73 6B 04 00 00 34 31 32 30 0D - 00 00 57 65 62 2D 50 75 62 6C 69 73 68 65 72 05 - 00 00 31 31 36 39 35 01 00 00 4B 05 00 00 31 31 - 36 39 36 05 00 00 31 31 36 39 37 05 00 00 31 31 - 37 30 32 05 00 00 31 31 37 31 30 05 00 00 31 31 - 37 31 31 11 00 00 53 6F 66 74 77 61 72 65 20 45 - 6E 67 69 6E 65 65 72 05 00 00 31 31 37 31 32 05 - 00 00 31 31 37 32 34 05 00 00 31 31 37 33 30 19 - 00 00 50 72 6F 6A 65 63 74 6D 61 6E 61 67 65 72 - 20 52 FC 73 63 68 6C 69 6B 6F 6E 05 00 00 31 31 - 37 33 31 05 00 00 31 31 37 33 32 05 00 00 31 31 - 37 34 30 05 00 00 31 31 37 34 31 05 00 00 31 31 - 37 34 34 19 00 00 48 65 61 64 20 4F 70 65 72 61 - 74 69 6F 6E 73 20 52 FC 73 63 68 6C 69 6B 2E 05 - 00 00 31 31 37 34 35 14 00 00 47 72 6C 2E 20 43 - 6F 73 74 20 41 63 63 6F 75 6E 74 69 6E 67 05 00 - 00 31 31 37 34 37 05 00 00 31 31 37 35 31 05 00 - 00 31 31 37 35 38 05 00 00 31 31 37 36 37 05 00 - 00 31 31 37 37 33 05 00 00 31 31 37 37 37 05 00 - 00 31 31 37 37 38 16 00 00 54 4C 20 52 61 75 6D - 62 65 77 69 72 74 73 63 68 61 66 74 75 6E 67 05 - 00 00 31 31 37 38 34 05 00 00 31 31 37 38 37 05 - 00 00 31 31 37 39 34 05 00 00 31 31 37 39 39 05 - 00 00 31 31 38 30 30 05 00 00 31 31 38 30 31 05 - 00 00 31 31 38 30 32 05 00 00 31 31 38 30 33 05 - 00 00 31 31 38 30 34 05 00 00 31 31 38 31 39 05 - 00 00 31 31 38 32 31 05 00 00 31 31 38 33 38 05 - 00 00 31 31 38 35 32 17 00 00 4A 75 6E 69 6F 72 - 20 42 75 73 69 6E 65 73 73 20 41 6E 61 6C 79 73 - 74 05 00 00 31 31 38 35 35 18 00 00 48 65 61 64 - 20 6F 66 20 52 69 73 6B 20 4D 65 61 73 2E 20 4D - 65 74 68 2E 05 00 00 31 31 38 35 36 14 00 00 47 - 49 53 2F 46 6C 6F 6F 64 20 53 70 65 63 69 61 6C - 69 73 74 05 00 00 31 31 38 35 38 05 00 00 31 31 - 38 36 32 10 00 00 46 6C 6F 6F 64 20 53 70 65 63 - 69 61 6C 69 73 74 05 00 00 31 31 38 38 38 05 00 - 00 31 31 38 39 34 05 00 00 31 31 38 39 39 05 00 - 00 31 31 39 31 30 0D 00 00 48 65 61 64 20 6F 66 - 20 4C 4E 2F 4E 4F 05 00 00 31 31 39 31 36 05 00 - 00 31 31 39 32 33 05 00 00 31 31 39 33 31 05 00 - 00 31 31 39 33 32 05 00 00 31 31 39 33 33 05 00 - 00 31 31 39 34 36 05 00 00 31 31 39 35 30 09 00 - 00 50 61 74 69 73 73 69 65 72 05 00 00 31 31 39 - 35 31 05 00 00 31 31 39 35 36 19 00 00 42 72 61 - 6E 64 4D 61 6E 61 67 65 72 20 43 6F 72 70 2E 43 - 6F 6D 6D 75 6E 2E 05 00 00 31 31 39 36 37 15 00 - 00 45 78 65 63 75 74 69 76 65 2D 48 6F 75 73 65 - 6B 65 65 70 65 72 05 00 00 31 31 39 36 39 19 00 - 00 52 65 73 74 2E 2B 42 61 6E 71 75 65 74 20 53 - 65 72 76 69 63 65 20 4D 67 72 05 00 00 31 31 39 - 37 30 05 00 00 31 31 39 37 31 05 00 00 31 31 39 - 37 38 05 00 00 31 31 39 38 37 14 00 00 53 61 63 - 68 62 65 61 72 62 65 69 74 65 72 20 4B 61 73 73 - 65 05 00 00 31 31 39 39 35 05 00 00 31 31 39 39 - 36 13 00 00 45 78 65 63 75 74 69 76 65 20 41 73 - 73 69 73 74 61 6E 74 05 00 00 31 32 30 30 30 04 - 00 00 34 35 36 34 04 00 00 34 35 37 31 04 00 00 - 34 35 37 36 04 00 00 34 35 39 32 0F 00 00 45 78 - 74 65 72 6E 65 72 20 4B 75 72 69 65 72 01 00 00 - 48 04 00 00 34 35 39 35 04 00 00 34 36 30 34 04 - 00 00 34 36 30 38 0F 00 00 52 75 6E 2D 6F 66 66 - 20 4D 61 6E 61 67 65 72 04 00 00 34 36 31 38 04 - 00 00 34 36 34 31 04 00 00 34 37 32 37 10 00 00 - 4D 69 74 61 72 62 65 69 74 65 72 49 6E 20 52 57 - 04 00 00 34 37 32 38 04 00 00 34 38 36 35 04 00 - 00 34 39 31 31 16 00 00 53 70 65 7A 2E 20 45 72 - 64 62 65 62 65 6E 2F 53 79 73 74 65 6D 65 04 00 - 00 34 39 33 33 04 00 00 34 39 33 34 04 00 00 34 - 39 33 35 04 00 00 34 39 33 38 04 00 00 34 39 35 - 31 13 00 00 54 4C 20 53 69 63 68 65 72 68 65 69 - 74 73 6C 6F 67 65 6E 04 00 00 34 39 35 38 04 00 - 00 34 39 37 30 14 00 00 53 70 61 6E 69 73 63 68 - FC 62 65 72 73 65 74 7A 65 72 69 6E 04 00 00 34 - 39 37 32 16 00 00 44 65 70 75 74 79 20 47 50 4D - 20 45 6E 67 69 6E 65 65 72 69 6E 67 04 00 00 34 - 39 39 36 14 00 00 53 65 72 76 69 63 65 6D 69 74 - 61 72 62 65 69 74 65 72 69 6E 04 00 00 35 30 30 - 34 11 00 00 46 69 6E 61 6E 63 69 61 6C 20 4F 66 - 66 69 63 65 72 04 00 00 35 30 30 39 04 00 00 35 - 30 31 32 02 00 00 4A 4B 04 00 00 35 30 32 34 19 - 00 00 48 65 61 64 20 4D 61 72 6B 65 74 2E 26 41 - 63 74 2E 20 53 75 70 70 6F 72 74 04 00 00 35 30 - 32 36 17 00 00 55 57 20 46 61 63 75 6C 74 61 74 - 69 76 65 20 43 61 73 75 61 6C 74 79 04 00 00 35 - 30 33 31 17 00 00 54 65 61 6D 6C 65 69 74 65 72 - 20 45 69 6E 67 61 6E 67 73 70 6F 73 74 04 00 00 - 35 30 33 39 04 00 00 35 30 35 34 04 00 00 35 30 - 36 30 16 00 00 44 69 76 2E 20 4F 70 2E 20 4F 66 - 66 69 63 65 72 20 28 44 4F 4F 29 04 00 00 35 30 - 36 38 18 00 00 42 4C 20 47 72 6F 75 70 20 4F 66 - 66 69 63 65 20 53 65 72 76 69 63 65 73 04 00 00 - 35 30 37 35 18 00 00 43 6F 2D 65 64 69 74 6F 72 - 20 61 6E 64 20 64 61 74 61 20 73 70 65 63 2E 04 - 00 00 35 30 38 39 0A 00 00 41 63 63 6F 75 6E 74 - 61 6E 74 04 00 00 35 31 31 36 14 00 00 4D 61 6E - 61 67 65 6D 65 6E 74 20 41 73 73 69 73 74 61 6E - 74 04 00 00 35 31 33 34 12 00 00 52 69 73 69 6B - 6F 73 70 65 7A 69 61 6C 69 73 74 69 6E 04 00 00 - 35 31 34 37 04 00 00 35 31 36 35 0C 00 00 46 61 - 63 68 2D 45 78 70 65 72 74 65 04 00 00 35 31 38 - 31 04 00 00 35 31 38 36 13 00 00 50 72 6F 6A 65 - 63 74 20 43 6F 6F 72 64 69 6E 61 74 6F 72 04 00 - 00 35 32 30 37 04 00 00 35 32 30 39 11 00 00 52 - 65 63 68 74 73 6B 6F 6E 73 75 6C 65 6E 74 69 6E - 04 00 00 35 32 31 35 04 00 00 35 32 31 39 04 00 - 00 35 32 34 33 15 00 00 47 72 61 64 2E 44 65 76 - 65 6C 2E 4D 67 72 2E 52 FC 73 63 68 2E 04 00 00 - 35 32 35 31 19 00 00 53 79 73 74 65 6D 65 6E 74 - 77 69 63 6B 6C 65 72 20 46 61 63 68 61 62 74 2E - 04 00 00 35 32 35 32 14 00 00 41 64 6D 69 6E 2E - 20 4D 69 74 61 72 62 65 69 74 65 72 69 6E 04 00 - 00 35 32 36 33 0E 00 00 52 65 69 73 65 62 65 72 - 61 74 65 72 69 6E 04 00 00 35 32 36 35 13 00 00 - 54 72 61 69 6E 69 6E 67 20 43 6F 6E 73 75 6C 74 - 61 6E 74 04 00 00 35 32 36 37 18 00 00 49 6E 66 - 6F 72 6D 61 74 69 6F 6E 73 73 70 65 7A 69 61 6C - 69 73 74 69 6E 04 00 00 35 32 37 32 19 00 00 48 - 65 61 64 20 6F 66 20 45 63 6F 6E 6F 6D 69 63 20 - 52 65 73 65 61 72 63 68 04 00 00 35 32 38 32 11 - 00 00 43 6C 69 65 6E 74 20 4D 61 6E 61 67 65 6D - 65 6E 74 04 00 00 35 32 38 33 04 00 00 35 32 39 - 32 0C 00 00 52 65 69 73 65 62 65 72 61 74 65 72 - 04 00 00 35 32 39 33 17 00 00 48 75 6D 61 6E 20 - 52 65 73 6F 75 72 63 65 73 20 53 75 70 70 6F 72 - 74 04 00 00 35 32 39 35 13 00 00 45 78 65 63 75 - 74 69 76 65 20 53 65 63 72 65 74 61 72 79 04 00 - 00 35 32 39 38 04 00 00 35 32 39 39 04 00 00 35 - 33 30 33 14 00 00 54 65 61 6D 6C 65 69 74 65 72 - 20 52 E9 63 2E 20 45 6E 67 65 04 00 00 35 33 30 - 38 0B 00 00 41 73 73 69 73 74 65 6E 74 69 6E 04 - 00 00 35 33 30 39 0D 00 00 50 6F 73 74 61 73 73 - 69 73 74 65 6E 74 04 00 00 35 33 32 34 04 00 00 - 35 33 33 31 04 00 00 35 33 34 31 13 00 00 44 65 - 70 2E 20 48 65 61 64 20 53 65 63 72 65 74 61 72 - 79 04 00 00 35 33 34 35 04 00 00 35 33 35 31 04 - 00 00 35 33 35 33 0A 00 00 35 30 39 2D 33 34 35 - 30 33 64 09 00 00 35 30 39 2D 33 34 35 30 33 09 - 00 00 35 30 39 2D 33 34 35 30 34 09 00 00 35 30 - 39 2D 33 34 35 30 35 09 00 00 35 30 39 2D 33 34 - 35 30 36 09 00 00 35 30 39 2D 33 34 35 30 37 09 - 00 00 35 30 39 2D 33 34 35 30 38 09 00 00 35 30 - 39 2D 33 34 35 30 39 09 00 00 35 30 39 2D 33 34 - 35 31 30 09 00 00 35 30 39 2D 33 34 35 31 31 09 - 00 00 35 30 39 2D 33 34 35 31 32 09 00 00 35 30 - 39 2D 33 34 35 31 33 09 00 00 35 30 39 2D 33 34 - 35 31 34 09 00 00 35 30 39 2D 33 34 35 31 35 09 - 00 00 35 30 39 2D 33 34 35 31 36 09 00 00 35 30 - 39 2D 33 34 35 31 37 09 00 00 35 30 39 2D 33 34 - 35 31 38 09 00 00 35 30 39 2D 33 34 35 31 39 09 - 00 00 35 30 39 2D 33 34 35 32 30 09 00 00 35 30 - 39 2D 33 34 35 32 31 09 00 00 35 30 39 2D 33 34 - 35 32 32 09 00 00 35 30 39 2D 33 34 35 32 33 09 - 00 00 35 30 39 2D 33 34 35 32 34 09 00 00 35 30 - 39 2D 33 34 35 32 35 09 00 00 35 30 39 2D 33 34 - 35 32 36 09 00 00 35 30 39 2D 33 34 35 32 37 09 - 00 00 35 30 39 2D 33 34 35 32 38 09 00 00 35 30 - 39 2D 33 34 35 32 39 09 00 00 35 30 39 2D 33 34 - 35 33 30 09 00 00 35 30 39 2D 33 34 35 33 31 09 - 00 00 35 30 39 2D 33 34 35 33 32 09 00 00 35 30 - 39 2D 33 34 35 33 33 09 00 00 35 30 39 2D 33 34 - 35 33 34 09 00 00 35 30 39 2D 33 34 35 33 35 09 - 00 00 35 30 39 2D 33 34 35 33 36 09 00 00 35 30 - 39 2D 33 34 35 33 37 09 00 00 35 30 39 2D 33 34 - 35 33 38 09 00 00 35 30 39 2D 33 34 35 33 39 09 - 00 00 35 30 39 2D 33 34 35 34 30 09 00 00 35 30 - 39 2D 33 34 35 34 31 09 00 00 35 30 39 2D 33 34 - 35 34 32 09 00 00 35 30 39 2D 33 34 35 34 33 09 - 00 00 35 30 39 2D 33 34 35 34 34 09 00 00 35 30 - 39 2D 33 34 35 34 35 09 00 00 35 30 39 2D 33 34 - 35 34 36 09 00 00 35 30 39 2D 33 34 35 34 37 09 - 00 00 35 30 39 2D 33 34 35 34 38 09 00 00 35 30 - 39 2D 33 34 35 34 39 09 00 00 35 30 39 2D 33 34 - 35 35 30 09 00 00 35 30 39 2D 33 34 35 35 31 09 - 00 00 35 30 39 2D 33 34 35 35 32 09 00 00 35 30 - 39 2D 33 34 35 35 33 09 00 00 35 30 39 2D 33 34 - 35 35 34 09 00 00 35 30 39 2D 33 34 35 35 35 09 - 00 00 35 30 39 2D 33 34 35 35 36 09 00 00 35 30 - 39 2D 33 34 35 35 37 09 00 00 35 30 39 2D 33 34 - 35 35 38 09 00 00 35 30 39 2D 33 34 35 35 39 09 - 00 00 35 30 39 2D 33 34 35 36 30 09 00 00 35 30 - 39 2D 33 34 35 36 31 09 00 00 35 30 39 2D 33 34 - 35 36 32 09 00 00 35 30 39 2D 33 34 35 36 33 09 - 00 00 35 30 39 2D 33 34 35 36 34 09 00 00 35 30 - 39 2D 33 34 35 36 35 09 00 00 35 30 39 2D 33 34 - 35 36 36 09 00 00 35 30 39 2D 33 34 35 36 37 09 - 00 00 35 30 39 2D 33 34 35 36 38 09 00 00 35 30 - 39 2D 33 34 35 36 39 09 00 00 35 30 39 2D 33 34 - 35 37 30 09 00 00 35 30 39 2D 33 34 35 37 31 09 - 00 00 35 30 39 2D 33 34 35 37 32 09 00 00 35 30 - 39 2D 33 34 35 37 33 09 00 00 35 30 39 2D 33 34 - 35 37 34 09 00 00 35 30 39 2D 33 34 35 37 35 09 - 00 00 35 30 39 2D 33 34 35 37 36 09 00 00 35 30 - 39 2D 33 34 35 37 37 09 00 00 35 30 39 2D 33 34 - 35 37 38 09 00 00 35 30 39 2D 33 34 35 37 39 09 - 00 00 35 30 39 2D 33 34 35 38 30 09 00 00 35 30 - 39 2D 33 34 35 38 31 09 00 00 35 30 39 2D 33 34 - 35 38 32 09 00 00 35 30 39 2D 33 34 35 38 33 09 - 00 00 35 30 39 2D 33 34 35 38 34 09 00 00 35 30 - 39 2D 33 34 35 38 35 09 00 00 35 30 39 2D 33 34 - 35 38 36 09 00 00 35 30 39 2D 33 34 35 38 37 09 - 00 00 35 30 39 2D 33 34 35 38 38 09 00 00 35 30 - 39 2D 33 34 35 38 39 09 00 00 35 30 39 2D 33 34 - 35 39 30 09 00 00 35 30 39 2D 33 34 35 39 31 09 - 00 00 35 30 39 2D 33 34 35 39 32 09 00 00 35 30 - 39 2D 33 34 35 39 33 09 00 00 35 30 39 2D 33 34 - 35 39 34 09 00 00 35 30 39 2D 33 34 35 39 35 09 - 00 00 35 30 39 2D 33 34 35 39 36 09 00 00 35 30 - 39 2D 33 34 35 39 37 09 00 00 35 30 39 2D 33 34 - 35 39 38 09 00 00 35 30 39 2D 33 34 35 39 39 09 - 00 00 35 30 39 2D 33 34 36 30 30 09 00 00 35 30 - 39 2D 33 34 36 30 31 09 00 00 35 30 39 2D 33 34 - 36 30 32 09 00 00 35 30 39 2D 33 34 36 30 33 09 - 00 00 35 30 39 2D 33 34 36 30 34 09 00 00 35 30 - 39 2D 33 34 36 30 35 09 00 00 35 30 39 2D 33 34 - 36 30 36 09 00 00 35 30 39 2D 33 34 36 30 37 09 - 00 00 35 30 39 2D 33 34 36 30 38 09 00 00 35 30 - 39 2D 33 34 36 30 39 09 00 00 35 30 39 2D 33 34 - 36 31 30 09 00 00 35 30 39 2D 33 34 36 31 31 09 - 00 00 35 30 39 2D 33 34 36 31 32 09 00 00 35 30 - 39 2D 33 34 36 31 33 09 00 00 35 30 39 2D 33 34 - 36 31 34 09 00 00 35 30 39 2D 33 34 36 31 35 09 - 00 00 35 30 39 2D 33 34 36 31 36 09 00 00 35 30 - 39 2D 33 34 36 31 37 09 00 00 35 30 39 2D 33 34 - 36 31 38 09 00 00 35 30 39 2D 33 34 36 31 39 09 - 00 00 35 30 39 2D 33 34 36 32 30 09 00 00 35 30 - 39 2D 33 34 36 32 31 09 00 00 35 30 39 2D 33 34 - 36 32 32 09 00 00 35 30 39 2D 33 34 36 32 33 09 - 00 00 35 30 39 2D 33 34 36 32 34 09 00 00 35 30 - 39 2D 33 34 36 32 35 09 00 00 35 30 39 2D 33 34 - 36 32 36 09 00 00 35 30 39 2D 33 34 36 32 37 09 - 00 00 35 30 39 2D 33 34 36 32 38 09 00 00 35 30 - 39 2D 33 34 36 32 39 09 00 00 35 30 39 2D 33 34 - 36 33 30 09 00 00 35 30 39 2D 33 34 36 33 31 09 - 00 00 35 30 39 2D 33 34 36 33 32 09 00 00 35 30 - 39 2D 33 34 36 33 33 09 00 00 35 30 39 2D 33 34 - 36 33 34 09 00 00 35 30 39 2D 33 34 36 33 35 09 - 00 00 35 30 39 2D 33 34 36 33 36 09 00 00 35 30 - 39 2D 33 34 36 33 37 09 00 00 35 30 39 2D 33 34 - 36 33 38 09 00 00 35 30 39 2D 33 34 36 33 39 09 - 00 00 35 30 39 2D 33 34 36 34 30 09 00 00 35 30 - 39 2D 33 34 36 34 31 09 00 00 35 30 39 2D 33 34 - 36 34 32 09 00 00 35 30 39 2D 33 34 36 34 33 09 - 00 00 35 30 39 2D 33 34 36 34 34 09 00 00 35 30 - 39 2D 33 34 36 34 35 09 00 00 35 30 39 2D 33 34 - 36 34 36 09 00 00 35 30 39 2D 33 34 36 34 37 09 - 00 00 35 30 39 2D 33 34 36 34 38 09 00 00 35 30 - 39 2D 33 34 36 34 39 09 00 00 35 30 39 2D 33 34 - 36 35 30 09 00 00 35 30 39 2D 33 34 36 35 31 09 - 00 00 35 30 39 2D 33 34 36 35 32 09 00 00 35 30 - 39 2D 33 34 36 35 33 09 00 00 35 30 39 2D 33 34 - 36 35 34 03 00 00 73 64 66 0D 00 00 6D 79 20 73 - 75 70 65 72 76 69 73 6F 72 01 00 00 3F 08 00 00 - 78 78 78 79 79 79 32 33 0E 00 00 34 31 20 31 20 - 78 78 78 20 39 39 20 39 39 08 00 00 75 6E 68 6B - 6E 6F 77 6E 05 00 00 68 65 75 74 65 0A 00 00 74 - 68 69 73 20 6D 6F 6E 74 68 11 00 00 6D 79 20 72 - 65 70 6F 72 74 69 6E 67 20 75 6E 69 74 05 00 00 - 49 74 61 6C 79 0C 00 00 75 73 64 20 33 33 33 33 - 33 2C 33 34 13 00 00 75 73 64 20 33 33 33 34 20 - 2B 20 47 50 44 20 33 33 34 35 06 00 00 6B 65 69 - 6E 65 72 07 00 00 33 31 2E 32 2E 36 33 03 00 00 - 20 43 48 04 00 00 38 34 38 31 04 00 00 38 34 38 - 34 04 00 00 38 34 39 31 04 00 00 38 34 39 33 02 - 00 00 53 56 04 00 00 38 34 39 34 19 00 00 44 65 - 70 2E 48 65 61 64 20 6F 66 20 49 6E 74 65 72 6C - 69 6E 65 20 4D 67 74 04 00 00 38 35 30 30 04 00 - 00 38 35 30 35 04 00 00 38 35 31 33 04 00 00 38 - 35 31 34 04 00 00 38 35 31 37 04 00 00 38 35 31 - 38 04 00 00 38 35 32 38 04 00 00 38 35 32 39 04 - 00 00 38 35 33 30 04 00 00 38 35 33 33 04 00 00 - 38 35 33 34 04 00 00 38 35 34 31 04 00 00 38 35 - 34 33 04 00 00 38 35 34 35 15 00 00 53 70 65 63 - 69 61 6C 69 73 74 20 65 2D 43 6F 6D 6D 65 72 63 - 65 04 00 00 38 35 34 36 17 00 00 46 61 63 68 72 - 65 66 65 72 65 6E 74 69 6E 20 43 61 73 75 61 6C - 74 79 04 00 00 38 35 34 38 03 00 00 5A 57 44 04 - 00 00 38 35 35 30 04 00 00 38 35 35 32 14 00 00 - 46 69 6E 61 6E 63 69 61 6C 20 41 63 63 6F 75 6E - 74 61 6E 74 04 00 00 38 35 35 36 04 00 00 38 35 - 35 38 04 00 00 38 35 36 33 04 00 00 38 35 37 36 - 03 00 00 49 54 4C 04 00 00 38 35 38 32 04 00 00 - 38 35 38 37 13 00 00 53 70 65 7A 69 61 6C 69 73 - 74 20 45 72 64 62 65 62 65 6E 03 00 00 45 53 50 - 04 00 00 38 35 39 37 04 00 00 38 36 30 32 03 00 - 00 46 52 46 04 00 00 38 36 30 37 04 00 00 38 36 - 30 38 04 00 00 38 36 31 36 03 00 00 43 4E 59 04 - 00 00 38 36 32 30 03 00 00 48 4B 44 04 00 00 38 - 36 32 32 04 00 00 38 36 32 37 12 00 00 65 2D 61 - 6C 6C 69 61 6E 63 65 20 6D 61 6E 61 67 65 72 03 - 00 00 4B 52 57 04 00 00 38 36 33 33 04 00 00 38 - 36 33 38 0D 00 00 48 65 61 64 20 6F 66 20 4C 45 - 2F 42 49 04 00 00 38 36 34 30 04 00 00 38 36 34 - 35 03 00 00 54 57 44 04 00 00 38 36 34 36 04 00 - 00 38 36 36 33 13 00 00 50 72 6F 6A 65 6B 74 2D - 41 73 73 69 73 74 65 6E 74 69 6E 04 00 00 38 36 - 36 34 04 00 00 38 36 36 36 04 00 00 38 36 36 39 - 04 00 00 38 36 37 37 0F 00 00 4C 69 66 65 20 4D - 61 6E 61 67 65 72 20 48 4B 04 00 00 38 36 38 32 - 18 00 00 4D 65 6D 62 65 72 20 45 78 65 63 75 74 - 69 76 65 20 54 65 61 6D 20 45 55 02 00 00 4C 4C - 04 00 00 38 36 39 36 0B 00 00 4B 56 2D 4C 65 68 - 72 6C 69 6E 67 04 00 00 38 36 39 37 04 00 00 38 - 36 39 39 04 00 00 38 37 30 30 04 00 00 38 37 30 - 31 03 00 00 44 45 4D 04 00 00 38 37 30 32 04 00 - 00 38 37 30 34 04 00 00 38 37 30 35 03 00 00 43 - 4F 50 04 00 00 38 37 30 36 04 00 00 38 37 30 37 - 04 00 00 38 37 31 30 04 00 00 38 37 31 32 0F 00 - 00 4D 65 64 69 61 20 41 73 73 69 73 74 61 6E 74 - 04 00 00 38 37 31 36 04 00 00 38 37 31 37 13 00 - 00 48 65 61 64 20 6F 66 20 4C 41 2F 4C 45 2F 4C - 4E 20 49 54 03 00 00 42 45 46 04 00 00 38 37 32 - 31 13 00 00 4C 65 69 74 65 72 20 52 65 63 68 74 - 73 64 69 65 6E 73 74 04 00 00 38 37 32 37 04 00 - 00 38 37 32 38 04 00 00 38 37 34 32 03 00 00 56 - 45 42 04 00 00 38 37 34 33 04 00 00 38 37 34 34 - 04 00 00 38 37 35 39 16 00 00 53 70 65 7A 69 61 - 6C 69 73 74 20 53 74 75 72 6D 2F 4D 65 74 65 6F - 04 00 00 38 37 36 30 04 00 00 38 37 36 32 04 00 - 00 38 37 36 38 04 00 00 38 37 37 35 04 00 00 38 - 37 37 39 04 00 00 38 37 38 36 19 00 00 48 65 61 - 64 20 4D 65 64 65 78 20 4D 6F 6E 69 74 6F 72 69 - 6E 67 55 6E 69 74 04 00 00 38 37 38 37 17 00 00 - 48 65 61 64 20 52 69 73 6B 20 4D 67 6D 74 20 26 - 20 4D 61 67 6E 75 6D 04 00 00 38 38 31 37 04 00 - 00 38 38 32 33 04 00 00 38 38 33 34 04 00 00 38 - 38 33 38 04 00 00 38 38 33 39 04 00 00 38 38 35 - 34 16 00 00 48 65 61 64 20 6F 66 20 47 6C 6F 62 - 61 6C 20 43 6C 69 65 6E 74 73 04 00 00 38 38 36 - 34 04 00 00 38 38 36 35 04 00 00 38 38 36 38 19 - 00 00 43 6C 61 69 6D 73 2F 50 6F 72 74 66 6F 6C - 69 6F 20 41 73 73 2E 4D 61 6E 2E 04 00 00 38 38 - 37 38 14 00 00 54 65 61 6D 6C 65 69 74 65 72 69 - 6E 20 53 65 72 76 69 63 65 04 00 00 38 38 39 32 - 04 00 00 38 38 39 33 19 00 00 47 72 6C 2E 20 54 - 65 6C 65 6D 61 74 69 6B 2F 41 56 2D 54 65 63 68 - 6E 69 6B 04 00 00 38 38 39 34 0D 00 00 54 65 6C - 65 6D 61 74 69 6B 65 72 69 6E 04 00 00 38 38 39 - 37 04 00 00 38 39 30 30 13 00 00 50 72 6F 67 72 - 61 6D 20 43 6F 6F 72 64 69 6E 61 74 6F 72 04 00 - 00 38 39 30 35 03 00 00 52 55 52 04 00 00 38 39 - 30 37 10 00 00 47 65 62 E4 75 64 65 74 65 63 68 - 6E 69 6B 65 72 04 00 00 38 39 31 30 04 00 00 38 - 39 31 32 15 00 00 53 74 6F 72 61 67 65 20 41 64 - 6D 69 6E 69 73 74 72 61 74 6F 72 04 00 00 38 39 - 32 35 04 00 00 38 39 33 37 14 00 00 52 65 67 69 - 6F 6E 61 6C 20 49 47 50 20 4D 61 6E 61 67 65 72 - 04 00 00 38 39 33 38 04 00 00 38 39 34 31 04 00 - 00 38 39 34 33 04 00 00 38 39 34 35 04 00 00 38 - 39 34 38 04 00 00 38 39 35 38 04 00 00 38 39 36 - 33 07 00 00 41 75 64 69 74 6F 72 04 00 00 38 39 - 36 34 04 00 00 39 30 38 30 18 00 00 49 6E 76 2E - 20 50 72 6F 66 2E 2F 4C 65 67 61 6C 20 43 6F 75 - 6E 73 65 6C 04 00 00 39 30 38 31 04 00 00 39 30 - 38 35 04 00 00 39 31 30 37 0F 00 00 50 61 79 72 - 6F 6C 6C 20 53 75 70 70 6F 72 74 04 00 00 39 31 - 31 34 11 00 00 41 73 73 69 73 74 61 6E 74 20 41 - 63 74 75 61 72 79 03 00 00 35 38 34 04 00 00 39 - 31 31 38 04 00 00 39 31 32 31 04 00 00 39 31 34 - 35 16 00 00 41 73 73 2E 20 46 69 6E 61 6E 63 69 - 61 6C 20 4F 66 66 69 63 65 72 04 00 00 39 31 34 - 36 0C 00 00 4B 6F 63 68 6C 65 68 72 6C 69 6E 67 - 04 00 00 39 31 34 37 04 00 00 39 31 34 38 04 00 - 00 39 31 34 39 04 00 00 39 31 35 35 04 00 00 39 - 31 35 39 04 00 00 39 31 37 31 04 00 00 39 31 37 - 35 18 00 00 53 70 65 63 69 61 6C 20 41 73 73 69 - 67 2E 26 4C 6F 67 69 73 74 69 63 73 04 00 00 39 - 31 38 35 04 00 00 39 31 38 36 04 00 00 39 31 38 - 39 04 00 00 39 32 30 35 04 00 00 39 32 30 37 19 - 00 00 44 65 70 75 74 79 20 43 68 69 65 66 20 4D - 65 64 69 63 61 6C 20 4F 66 66 2E 04 00 00 39 32 - 35 35 16 00 00 48 65 61 64 20 6F 66 20 49 6E 74 - 65 72 6C 69 6E 65 20 4D 67 74 2E 04 00 00 39 33 - 30 33 04 00 00 39 33 31 37 04 00 00 39 33 32 35 diff --git a/test-data/spreadsheet/BigSSTRecord2CR2 b/test-data/spreadsheet/BigSSTRecord2CR2 deleted file mode 100644 index 05aa7e9dc..000000000 --- a/test-data/spreadsheet/BigSSTRecord2CR2 +++ /dev/null @@ -1,515 +0,0 @@ - 3C 00 20 20 04 00 00 39 33 34 35 04 00 00 39 33 - 35 39 10 00 00 48 65 61 64 20 6F 66 20 49 41 20 - 4D 67 6D 74 2E 04 00 00 39 34 33 31 04 00 00 39 - 34 34 35 0A 00 00 49 54 20 53 75 70 70 6F 72 74 - 04 00 00 39 34 34 39 04 00 00 39 34 36 37 04 00 - 00 39 34 38 35 04 00 00 39 34 38 37 19 00 00 47 - 72 6C 2E 20 46 69 6E 61 6E 63 69 61 6C 20 41 63 - 63 6F 75 6E 74 69 6E 67 04 00 00 39 34 38 39 04 - 00 00 39 35 30 31 04 00 00 39 35 30 33 04 00 00 - 39 35 30 39 11 00 00 54 65 61 6D 6C 65 69 74 65 - 72 20 55 6D 7A FC 67 65 04 00 00 39 35 31 33 04 - 00 00 39 35 32 37 04 00 00 39 35 35 35 04 00 00 - 39 35 37 31 04 00 00 39 35 37 33 04 00 00 39 35 - 39 39 04 00 00 39 36 30 37 04 00 00 39 36 35 37 - 19 00 00 50 6F 72 74 75 67 69 65 73 69 73 63 68 - FC 62 65 72 73 65 74 7A 65 72 69 6E 04 00 00 39 - 36 35 39 0B 00 00 50 52 2D 52 65 64 61 6B 74 6F - 72 04 00 00 39 36 38 37 18 00 00 55 6D 77 65 6C - 74 73 63 68 75 74 7A 62 65 61 75 66 74 72 61 67 - 74 65 72 04 00 00 39 37 30 35 19 00 00 48 65 61 - 64 20 54 65 63 68 6E 2E 20 53 75 70 70 6F 72 74 - 20 4C 41 2F 49 54 04 00 00 39 37 31 33 04 00 00 - 39 37 32 33 16 00 00 48 65 61 6C 74 68 20 43 61 - 72 65 20 53 70 65 63 69 61 6C 69 73 74 04 00 00 - 39 37 33 31 04 00 00 39 37 34 39 0C 00 00 52 69 - 73 6B 20 41 6E 61 6C 79 73 74 04 00 00 39 37 35 - 35 04 00 00 39 37 35 39 04 00 00 39 37 36 33 04 - 00 00 39 38 32 35 14 00 00 4D 61 72 6B 65 74 69 - 6E 67 20 52 FC 73 63 68 6C 69 6B 6F 6E 04 00 00 - 39 38 33 35 16 00 00 46 69 6E 61 6E 63 2E 53 6F - 6C 75 74 69 6F 6E 73 20 43 6F 6E 73 2E 04 00 00 - 39 38 33 39 04 00 00 39 38 36 35 04 00 00 39 38 - 36 39 19 00 00 50 72 6F 6A 65 6B 74 6C 2E 20 46 - 69 6E 2E 20 41 63 63 6F 75 6E 74 69 6E 67 04 00 - 00 39 38 38 33 13 00 00 48 52 2D 4D 49 53 20 55 - 73 65 72 20 53 75 70 70 6F 72 74 04 00 00 39 38 - 38 35 12 00 00 48 65 61 64 20 6F 66 20 43 6C 61 - 69 6D 73 20 4D 67 74 04 00 00 39 38 38 37 04 00 - 00 39 38 39 39 03 00 00 50 4C 5A 04 00 00 39 39 - 31 33 04 00 00 39 39 32 30 03 00 00 53 47 44 04 - 00 00 39 39 32 32 04 00 00 39 39 33 30 04 00 00 - 39 39 35 31 0E 00 00 4D 44 2D 41 73 73 69 73 74 - 65 6E 74 69 6E 04 00 00 39 39 35 33 04 00 00 39 - 39 36 31 19 00 00 47 72 6F 75 70 20 50 72 6F 64 - 2E 4D 61 6E 61 67 2E 43 61 73 75 61 6C 74 79 0D - 00 00 4E 65 77 20 59 6F 72 6B 2C 20 55 53 41 04 - 00 00 39 39 36 33 04 00 00 39 39 37 33 04 00 00 - 39 39 37 35 04 00 00 39 39 38 36 05 00 00 31 30 - 30 31 38 05 00 00 31 30 30 32 34 05 00 00 31 30 - 30 32 36 05 00 00 31 30 30 32 39 05 00 00 31 30 - 30 33 31 05 00 00 31 30 30 34 33 19 00 00 50 72 - 6F 6A 27 6D 69 74 61 72 62 65 69 74 65 72 20 46 - 61 63 68 61 62 74 2E 05 00 00 31 30 30 34 37 05 - 00 00 31 30 30 35 39 05 00 00 31 30 30 36 33 05 - 00 00 31 30 30 36 39 05 00 00 31 30 30 37 31 03 - 00 00 4A 50 59 05 00 00 31 30 30 37 33 05 00 00 - 31 30 30 37 35 19 00 00 47 72 75 70 70 65 6E 6C - 65 69 74 65 72 20 50 6F 73 74 64 69 65 6E 73 74 - 65 05 00 00 31 30 30 38 31 14 00 00 54 4C 20 47 - 65 62 E4 75 64 65 6D 61 6E 61 67 65 6D 65 6E 74 - 05 00 00 31 30 30 38 33 11 00 00 43 6C 61 69 6D - 73 20 43 6F 6E 73 75 6C 74 61 6E 74 05 00 00 31 - 30 30 39 31 05 00 00 31 30 30 39 35 05 00 00 31 - 30 30 39 39 05 00 00 31 30 31 37 32 12 00 00 47 - 72 75 70 70 65 6E 6C 65 69 74 65 72 20 46 69 62 - 75 05 00 00 31 30 31 38 32 05 00 00 31 30 31 38 - 38 05 00 00 31 30 31 39 34 12 00 00 45 69 6E 72 - 69 63 68 74 75 6E 67 73 70 6C 61 6E 65 72 05 00 - 00 31 30 31 39 36 05 00 00 31 30 32 30 30 05 00 - 00 31 30 32 30 34 0D 00 00 49 47 50 20 41 73 73 - 6F 63 69 61 74 65 05 00 00 31 30 32 33 36 0F 00 - 00 50 72 6F 6A 65 63 74 20 4F 66 66 69 63 65 72 - 05 00 00 31 30 32 36 30 05 00 00 31 30 32 36 32 - 03 00 00 4E 4C 47 05 00 00 31 30 32 38 30 05 00 - 00 31 30 32 39 38 05 00 00 31 30 33 32 38 05 00 - 00 31 30 33 33 34 0E 00 00 44 65 70 75 74 79 20 - 48 65 61 64 20 43 58 05 00 00 31 30 33 33 38 05 - 00 00 31 30 33 35 30 05 00 00 31 30 33 37 30 05 - 00 00 31 30 33 37 34 13 00 00 4C 65 69 74 65 72 - 20 45 69 6E 6B 61 75 66 20 53 52 47 53 05 00 00 - 31 30 33 39 32 15 00 00 41 62 74 65 69 6C 75 6E - 67 73 2D 53 65 6B 72 65 74 E4 72 69 6E 05 00 00 - 31 30 33 39 34 05 00 00 31 30 33 39 36 05 00 00 - 31 30 33 39 38 15 00 00 41 63 63 6F 75 6E 74 61 - 6E 74 20 47 72 6F 75 70 20 52 65 70 2E 05 00 00 - 31 30 34 30 30 05 00 00 31 30 34 33 31 05 00 00 - 31 30 35 30 37 05 00 00 31 30 35 32 37 05 00 00 - 31 30 35 35 32 05 00 00 31 30 35 35 36 05 00 00 - 31 30 35 35 37 18 00 00 43 68 69 65 66 20 41 63 - 63 6F 75 6E 74 69 6E 67 20 4F 66 66 69 63 65 72 - 12 00 00 4D 61 6E 2E 20 4C 65 67 61 6C 20 43 6F - 75 6E 73 65 6C 04 00 00 34 31 33 32 11 00 00 50 - 4C 20 4B 6F 6E 73 6F 6C 69 64 69 65 72 75 6E 67 - 04 00 00 34 31 33 33 04 00 00 34 31 33 34 17 00 - 00 48 75 6D 61 6E 20 52 65 73 6F 75 72 63 65 73 - 20 4D 61 6E 61 67 65 72 04 00 00 34 31 35 30 04 - 00 00 34 31 35 37 04 00 00 34 31 36 37 13 00 00 - 53 65 6E 2E 20 46 69 6E 61 6E 63 69 61 6C 20 41 - 63 63 2E 04 00 00 34 32 30 35 04 00 00 34 32 30 - 38 13 00 00 53 65 63 72 65 74 61 72 79 2F 41 73 - 73 69 73 74 61 6E 74 04 00 00 34 32 31 39 04 00 - 00 34 32 32 37 04 00 00 34 32 32 39 10 00 00 43 - 6F 6D 6D 2E 20 53 70 65 63 69 61 6C 69 73 74 04 - 00 00 34 32 33 36 19 00 00 44 65 70 2E 48 65 61 - 64 20 52 4E 2F 48 65 61 64 20 43 61 74 53 75 70 - 70 2E 04 00 00 34 32 33 38 04 00 00 34 32 34 32 - 04 00 00 34 32 34 37 04 00 00 34 32 35 35 04 00 - 00 34 32 36 32 11 00 00 44 65 70 75 74 79 20 48 - 65 61 64 20 6F 66 20 49 46 04 00 00 34 32 36 39 - 16 00 00 53 65 72 76 69 63 65 66 61 63 68 6D 69 - 74 61 72 62 65 69 74 65 72 04 00 00 34 32 37 37 - 09 00 00 43 68 61 75 66 66 65 75 72 04 00 00 34 - 32 38 33 0E 00 00 52 E9 63 65 70 74 69 6F 6E 69 - 73 74 69 6E 04 00 00 34 32 38 34 02 00 00 4D 4D - 04 00 00 34 32 38 39 13 00 00 53 65 6E 69 6F 72 - 20 52 69 73 6B 20 41 6E 61 6C 79 73 74 04 00 00 - 34 33 30 36 04 00 00 34 33 30 39 19 00 00 48 65 - 61 64 20 6F 66 20 43 6F 6E 74 72 61 63 74 20 53 - 65 72 76 69 63 65 73 04 00 00 34 33 31 36 15 00 - 00 43 6F 6D 6D 2E 20 41 73 73 2E 20 52 FC 73 63 - 68 6C 69 6B 6F 6E 04 00 00 34 33 33 31 04 00 00 - 34 33 33 32 18 00 00 47 72 6F 75 70 20 43 6F 6D - 70 6C 69 61 6E 63 65 20 4F 66 66 69 63 65 72 04 - 00 00 34 33 34 32 02 00 00 56 4F 04 00 00 34 33 - 34 35 10 00 00 53 65 6E 69 6F 72 20 45 63 6F 6E - 6F 6D 69 73 74 04 00 00 34 33 34 36 16 00 00 47 - 72 6C 2E 20 47 65 6E 65 72 61 6C 20 4C 65 64 67 - 65 72 20 5A 48 04 00 00 34 33 34 39 04 00 00 34 - 33 35 32 10 00 00 4D 65 64 69 61 20 43 6F 6E 73 - 75 6C 74 61 6E 74 04 00 00 34 33 35 39 14 00 00 - 47 72 61 66 69 73 63 68 65 20 53 61 63 68 62 65 - 61 72 62 2E 02 00 00 4C 48 04 00 00 34 33 36 32 - 14 00 00 50 72 6F 6A 65 63 74 73 20 53 52 41 20 - 48 6F 6C 64 69 6E 67 04 00 00 34 33 36 39 04 00 - 00 34 33 38 34 0D 00 00 41 63 63 6F 75 6E 74 69 - 6E 67 20 50 56 04 00 00 34 33 39 39 04 00 00 34 - 34 30 32 04 00 00 34 34 31 31 01 00 00 44 04 00 - 00 34 34 32 32 04 00 00 34 34 32 39 04 00 00 34 - 34 35 36 04 00 00 34 34 35 37 12 00 00 54 65 63 - 68 6E 2E 20 4D 69 74 61 72 62 65 69 74 65 72 04 - 00 00 34 34 35 38 16 00 00 54 65 61 6D 6C 65 69 - 74 65 72 20 53 70 6F 72 74 61 6E 6C 61 67 65 04 - 00 00 34 34 36 32 16 00 00 54 65 61 6D 6C 65 69 - 74 65 72 69 6E 20 52 E9 63 65 70 74 69 6F 6E 04 - 00 00 34 34 36 34 04 00 00 34 34 36 39 04 00 00 - 34 34 37 39 15 00 00 47 72 6C 2E 20 42 65 74 72 - 69 65 62 20 41 64 6C 69 73 77 69 6C 04 00 00 34 - 34 38 30 04 00 00 34 34 38 31 11 00 00 54 4C 20 - 42 65 74 72 69 65 62 73 64 69 65 6E 73 74 04 00 - 00 34 34 38 32 12 00 00 42 65 74 72 69 65 62 73 - 65 6C 65 6B 74 72 69 6B 65 72 04 00 00 34 34 39 - 32 11 00 00 45 78 65 63 75 74 69 76 65 20 53 75 - 70 70 6F 72 74 04 00 00 34 35 33 35 04 00 00 34 - 35 34 30 04 00 00 34 35 36 30 19 00 00 4C 65 61 - 72 6E 69 6E 67 26 44 65 76 65 6C 6F 70 2E 20 4D - 61 6E 61 67 65 72 06 00 00 6D 79 6E 61 6D 65 0B - 00 00 6D 79 66 69 72 73 74 6E 61 6D 65 04 00 00 - 37 38 37 35 19 00 00 53 65 6D 69 6E 61 72 20 26 - 20 54 72 61 69 6E 69 6E 67 20 43 6F 6F 72 64 2E - 04 00 00 37 38 37 37 19 00 00 47 72 6F 75 70 20 - 4D 61 6E 61 67 65 6D 65 6E 74 20 44 65 76 65 6C - 6F 70 2E 03 00 00 31 33 37 04 00 00 37 38 38 38 - 04 00 00 37 38 39 37 03 00 00 5A 41 52 04 00 00 - 37 39 31 32 18 00 00 48 65 61 64 20 6F 66 20 49 - 6E 66 6F 72 6D 61 74 69 6F 6E 20 4D 67 6D 74 04 - 00 00 37 39 31 35 04 00 00 37 39 31 39 04 00 00 - 37 39 34 36 04 00 00 37 39 35 32 04 00 00 37 39 - 36 36 04 00 00 37 39 39 36 04 00 00 38 30 30 32 - 04 00 00 38 30 30 36 04 00 00 38 30 30 37 04 00 - 00 38 30 31 30 04 00 00 38 30 33 33 04 00 00 38 - 30 33 38 0B 00 00 54 65 72 6D 69 6E 6F 6C 6F 67 - 65 04 00 00 38 30 34 32 04 00 00 38 30 34 34 04 - 00 00 38 30 35 32 04 00 00 38 30 35 33 04 00 00 - 38 30 35 39 04 00 00 38 30 36 35 0B 00 00 56 52 - 2D 53 65 6B 72 65 74 E4 72 04 00 00 38 30 38 32 - 04 00 00 38 30 38 35 04 00 00 38 30 38 36 19 00 - 00 50 6F 72 74 75 67 69 65 73 69 73 63 68 2D 55 - 65 62 65 72 73 65 74 7A 65 72 04 00 00 38 30 38 - 38 04 00 00 38 30 39 35 12 00 00 4F 70 65 72 61 - 74 69 6F 6E 73 20 4D 61 6E 61 67 65 72 04 00 00 - 38 31 30 31 18 00 00 47 72 6C 2E 20 52 61 75 6D - 62 65 77 69 72 74 73 63 68 61 66 74 75 6E 67 04 - 00 00 38 31 30 34 04 00 00 38 31 30 35 04 00 00 - 38 31 30 37 13 00 00 48 65 61 64 20 6F 66 20 46 - 6C 6F 6F 64 20 47 72 6F 75 70 04 00 00 38 31 30 - 38 04 00 00 38 31 31 33 04 00 00 38 31 31 37 04 - 00 00 38 31 31 38 03 00 00 35 33 30 04 00 00 38 - 31 32 32 11 00 00 54 65 63 68 6E 69 63 61 6C 20 - 53 75 70 70 6F 72 74 04 00 00 38 31 33 39 04 00 - 00 38 31 34 33 04 00 00 38 31 34 35 19 00 00 48 - 65 61 64 20 6F 66 20 52 69 73 63 20 52 65 70 2F - 53 74 65 65 72 69 6E 67 04 00 00 38 31 34 37 04 - 00 00 38 31 34 38 04 00 00 38 31 34 39 04 00 00 - 38 31 35 30 04 00 00 38 31 35 34 04 00 00 38 31 - 35 39 0D 00 00 43 6C 61 69 6D 73 20 45 78 70 65 - 72 74 04 00 00 38 31 37 30 04 00 00 38 31 38 37 - 18 00 00 48 65 61 64 20 6F 66 20 48 52 20 53 79 - 73 74 65 6D 73 26 43 6F 6D 70 2E 04 00 00 38 31 - 39 34 04 00 00 38 31 39 35 0C 00 00 49 54 2D 53 - 75 70 70 6F 72 74 65 72 04 00 00 38 31 39 37 04 - 00 00 38 31 39 38 0F 00 00 52 69 73 69 6B 6F 69 - 6E 67 65 6E 69 65 75 72 04 00 00 38 32 30 39 04 - 00 00 38 32 31 35 04 00 00 38 32 31 36 0D 00 00 - 49 54 2D 53 70 65 63 69 61 6C 69 73 74 04 00 00 - 38 32 32 37 18 00 00 53 61 63 68 62 2E 4B 75 6E - 64 65 6E 67 65 73 63 68 2E 2F 50 75 62 6C 2E 04 - 00 00 38 32 33 30 04 00 00 38 32 33 34 04 00 00 - 38 32 33 37 04 00 00 38 32 33 39 07 00 00 43 6F - 75 6E 74 72 79 08 00 00 44 69 76 69 73 69 6F 6E - 0B 00 00 44 61 74 65 4F 66 42 69 72 74 68 0B 00 - 00 44 61 74 65 4F 66 45 6E 74 72 79 03 00 00 53 - 65 78 08 00 00 46 75 6E 63 74 69 6F 6E 0A 00 00 - 53 75 70 65 72 76 69 73 6F 72 08 00 00 43 75 72 - 72 65 6E 63 79 03 00 00 33 32 34 02 00 00 43 48 - 06 00 00 5A 75 72 69 63 68 01 00 00 50 02 00 00 - 49 53 02 00 00 43 53 03 00 00 32 39 32 01 00 00 - 4D 11 00 00 47 72 6C 2E 20 41 63 63 65 73 73 20 - 4D 67 6D 74 2E 02 00 00 4E 6F 03 00 00 55 53 44 - 01 00 00 30 02 00 00 50 45 03 00 00 32 39 38 16 - 00 00 53 65 6E 69 6F 72 20 53 79 73 74 65 6D 20 - 45 6E 67 69 6E 65 65 72 03 00 00 32 39 39 18 00 - 00 4D 65 6D 62 65 72 20 45 78 65 63 75 74 69 76 - 65 20 54 65 61 6D 20 49 54 01 00 00 4F 02 00 00 - 52 47 02 00 00 54 54 03 00 00 33 31 32 0F 00 00 - 54 65 6D 70 6F 72 61 72 79 20 73 74 61 66 66 01 - 00 00 51 02 00 00 42 4F 01 00 00 32 17 00 00 47 - 72 6F 75 70 20 4E 6F 6E 20 4C 69 66 65 20 52 65 - 69 6E 73 75 72 2E 02 00 00 36 31 10 00 00 41 73 - 73 69 73 74 65 6E 74 20 64 65 72 20 47 4C 01 00 - 00 4A 02 00 00 46 52 02 00 00 52 41 02 00 00 38 - 31 0E 00 00 53 65 6B 74 69 6F 6E 73 6C 65 69 74 - 65 72 02 00 00 48 53 02 00 00 43 4F 03 00 00 31 - 30 39 0F 00 00 50 61 79 72 6F 6C 6C 20 4D 61 6E - 61 67 65 72 03 00 00 31 34 30 02 00 00 49 45 03 - 00 00 31 34 37 14 00 00 50 72 6F 6A 65 6B 74 2D - 42 65 61 75 66 74 72 61 67 74 65 72 02 00 00 52 - 50 03 00 00 31 34 38 19 00 00 48 65 61 64 20 6F - 66 20 47 72 6F 75 70 20 50 4D 20 50 72 6F 70 65 - 72 74 79 02 00 00 52 54 03 00 00 31 34 39 17 00 - 00 53 65 6E 2E 20 50 72 6F 64 75 63 74 20 53 70 - 65 63 69 61 6C 69 73 74 03 00 00 31 35 33 0B 00 - 00 44 65 70 75 74 79 20 48 65 61 64 02 00 00 52 - 4C 02 00 00 47 43 03 00 00 31 37 35 18 00 00 47 - 72 70 20 43 6C 61 69 6D 73 20 26 20 43 6F 6E 74 - 72 20 43 6F 6F 72 64 02 00 00 44 52 03 00 00 31 - 37 37 12 00 00 47 72 6F 75 70 20 44 61 74 61 20 - 4F 66 66 69 63 65 72 02 00 00 52 4E 02 00 00 52 - 45 03 00 00 31 38 34 13 00 00 4C 65 69 74 65 72 - 20 52 65 74 72 6F 2F 43 52 45 53 54 41 01 00 00 - 46 02 00 00 4C 41 02 00 00 49 54 03 00 00 32 36 - 32 17 00 00 53 65 6E 69 6F 72 20 41 70 70 6C 69 - 63 2E 20 45 6E 67 69 6E 65 65 72 02 00 00 46 44 - 03 00 00 32 36 35 03 00 00 32 36 37 02 00 00 4F - 50 03 00 00 32 36 38 12 00 00 50 72 6F 64 75 63 - 74 69 6F 6E 20 50 6C 61 6E 6E 65 72 03 00 00 4D - 58 4E 02 00 00 4D 53 03 00 00 32 36 39 0F 00 00 - 53 79 73 74 65 6D 20 45 6E 67 69 6E 65 65 72 03 - 00 00 32 37 35 0D 00 00 49 54 2D 43 6F 6E 73 75 - 6C 74 61 6E 74 03 00 00 32 38 30 02 00 00 49 4D - 03 00 00 32 38 31 03 00 00 42 52 4C 03 00 00 32 - 38 36 0F 00 00 53 79 73 74 65 6D 20 42 65 74 72 - 65 75 65 72 12 00 00 47 72 6C 2E 20 53 79 73 74 - 65 6D 20 43 6F 6E 74 72 2E 03 00 00 33 32 36 02 - 00 00 43 52 03 00 00 33 33 35 17 00 00 41 63 63 - 6F 75 6E 74 61 6E 74 20 53 75 62 73 69 64 69 61 - 72 69 65 73 02 00 00 4C 4F 03 00 00 33 33 39 0E - 00 00 41 4C 2D 41 73 73 69 73 74 65 6E 74 69 6E - 02 00 00 43 44 03 00 00 33 34 30 15 00 00 43 6F - 6E 73 75 6C 74 61 6E 74 20 4F 72 67 2E 20 54 6F - 6F 6C 73 03 00 00 33 34 34 02 00 00 44 45 03 00 - 00 33 36 30 19 00 00 42 65 61 75 66 74 72 61 67 - 74 65 72 20 4A 75 6E 69 6F 72 20 50 6F 77 65 72 - 03 00 00 33 36 35 02 00 00 49 44 03 00 00 33 36 - 37 0A 00 00 53 65 6B 72 65 74 E4 72 69 6E 02 00 - 00 42 4C 03 00 00 33 37 35 17 00 00 42 65 74 72 - 69 65 62 73 74 65 63 68 6E 69 6B 65 72 20 48 4C - 4B 4B 53 03 00 00 33 39 35 19 00 00 47 72 6C 2E - 53 74 61 62 73 74 65 6C 6C 65 20 53 69 63 68 65 - 72 68 65 69 74 03 00 00 33 39 37 0F 00 00 50 6F - 73 74 61 73 73 69 73 74 65 6E 74 69 6E 03 00 00 - 34 32 34 02 00 00 52 42 03 00 00 34 33 32 03 00 - 00 34 35 36 19 00 00 48 65 61 64 20 6F 66 20 49 - 6E 64 69 61 2F 4D 69 64 64 6C 65 20 45 61 73 74 - 02 00 00 42 53 03 00 00 34 36 32 0D 00 00 48 65 - 61 64 20 6F 66 20 4C 41 2F 42 53 02 00 00 4C 45 - 02 00 00 41 53 03 00 00 34 36 33 09 00 00 53 65 - 63 72 65 74 61 72 79 03 00 00 34 37 34 19 00 00 - 41 64 6D 69 6E 69 73 74 72 61 74 69 6F 6E 20 53 - 75 70 65 72 76 69 73 6F 72 02 00 00 4C 4E 03 00 - 00 34 38 30 03 00 00 34 38 35 19 00 00 53 65 6E - 2E 20 55 6E 64 65 72 77 72 69 74 69 6E 67 20 43 - 6F 6E 73 75 6C 74 03 00 00 43 4F 42 03 00 00 34 - 38 36 02 00 00 46 53 03 00 00 34 38 37 19 00 00 - 48 65 61 64 20 6F 66 20 46 69 6E 61 6E 63 2E 20 - 53 6F 6C 75 74 69 6F 6E 73 03 00 00 35 30 36 03 - 00 00 35 31 33 02 00 00 4E 4F 03 00 00 35 36 38 - 16 00 00 53 65 6E 69 6F 72 20 41 63 63 6F 75 6E - 74 20 4D 61 6E 61 67 65 72 02 00 00 52 52 02 00 - 00 52 4F 03 00 00 35 37 34 16 00 00 41 73 73 2E - 20 4F 70 65 72 61 74 69 6F 6E 73 20 43 6F 6F 72 - 64 2E 03 00 00 35 37 39 03 00 00 36 30 30 03 00 - 00 36 30 35 19 00 00 42 75 73 69 6E 65 73 73 20 - 43 6F 6E 74 69 6E 75 69 74 79 20 4D 67 6D 74 2E - 03 00 00 36 30 37 03 00 00 36 30 39 11 00 00 52 - 65 70 6F 72 74 69 6E 67 20 53 75 70 70 6F 72 74 - 01 00 00 4C 03 00 00 36 31 35 18 00 00 55 57 20 - 4D 61 6E 61 67 65 72 20 46 61 63 2E 20 43 61 73 - 75 61 6C 74 79 03 00 00 59 65 73 03 00 00 36 31 - 39 19 00 00 48 65 61 64 20 6F 66 20 4D 65 64 69 - 63 6F 2D 41 63 74 2E 20 53 65 72 76 2E 02 00 00 - 43 41 03 00 00 36 32 34 17 00 00 48 65 61 64 20 - 52 65 63 6F 72 64 73 20 4D 61 6E 61 67 65 6D 65 - 6E 74 04 00 00 32 30 34 34 02 00 00 52 43 03 00 - 00 36 33 33 16 00 00 47 72 75 70 70 65 6E 6C 65 - 69 74 65 72 20 43 61 73 75 61 6C 74 79 04 00 00 - 53 49 54 43 03 00 00 36 33 38 0B 00 00 4C 65 69 - 74 65 72 20 53 49 54 43 03 00 00 36 34 31 10 00 - 00 41 62 74 65 69 6C 75 6E 67 73 6C 65 69 74 65 - 72 03 00 00 36 38 35 0E 00 00 4C 65 69 74 65 72 - 20 53 74 61 62 20 4C 4F 02 00 00 4C 54 03 00 00 - 37 30 30 16 00 00 41 64 6D 69 6E 69 73 74 72 61 - 74 69 6F 6E 20 53 75 70 70 6F 72 74 03 00 00 37 - 31 35 0D 00 00 54 4C 20 48 61 75 73 64 69 65 6E - 73 74 03 00 00 37 33 31 11 00 00 53 79 73 74 65 - 6D 20 43 6F 6E 74 72 6F 6C 6C 65 72 02 00 00 47 - 53 02 00 00 4B 48 03 00 00 37 34 33 14 00 00 4B - FC 63 68 65 6E 6D 69 74 61 72 62 65 69 74 65 72 - 2F 69 6E 03 00 00 37 34 35 19 00 00 54 65 61 6D - 6C 65 69 74 65 72 69 6E 20 4B 75 72 69 65 72 64 - 69 65 6E 73 74 03 00 00 37 35 37 04 00 00 4B 6F - 63 68 03 00 00 37 36 31 18 00 00 53 65 72 76 69 - 63 65 66 61 63 68 6D 69 74 61 72 62 65 69 74 65 - 72 69 6E 03 00 00 37 39 33 19 00 00 52 6F 6F 6D - 73 65 72 76 69 63 65 6D 69 74 61 72 62 65 69 74 - 65 72 2F 69 6E 03 00 00 38 39 36 03 00 00 39 31 - 30 0D 00 00 41 4C 2D 53 65 6B 72 65 74 E4 72 69 - 6E 03 00 00 39 32 37 10 00 00 53 61 63 68 62 65 - 61 72 62 65 69 74 65 72 69 6E 03 00 00 39 33 37 - 13 00 00 4C 65 69 74 65 72 20 47 65 67 65 6E 61 - 6C 69 6D 65 6E 74 03 00 00 39 37 36 17 00 00 50 - 4C 20 49 6E 66 72 61 73 74 72 75 63 74 75 72 65 - 20 50 72 6F 6A 2E 02 00 00 49 50 03 00 00 39 37 - 37 03 00 00 39 38 32 11 00 00 47 72 6C 2E 20 42 - 65 74 72 69 65 62 20 45 6E 67 65 04 00 00 31 30 - 31 33 10 00 00 54 72 61 69 6E 69 6E 67 20 4F 66 - 66 69 63 65 72 04 00 00 31 30 33 32 04 00 00 31 - 30 34 34 18 00 00 4C 65 69 74 65 72 20 42 65 74 - 72 69 65 62 2F 45 72 68 61 6C 74 75 6E 67 04 00 - 00 31 30 34 35 26 00 00 4D 65 6D 62 65 72 20 6F - 66 20 74 68 65 20 50 4F 49 2D 48 53 53 46 20 45 - 78 65 63 75 74 69 76 65 20 42 6F 61 72 64 04 00 - 00 31 30 35 37 04 00 00 31 30 36 32 1E 00 00 44 - 65 70 75 74 79 20 43 68 69 65 66 20 45 78 65 63 - 75 74 69 76 65 20 4F 66 66 69 63 65 72 04 00 00 - 31 30 38 30 15 00 00 4C 65 69 74 65 72 20 41 6B - 74 69 65 6E 72 65 67 69 73 74 65 72 04 00 00 31 - 30 38 31 02 00 00 46 4D 04 00 00 31 30 38 32 07 - 00 00 41 63 74 75 61 72 79 02 00 00 53 46 04 00 - 00 31 30 39 37 12 00 00 48 65 61 64 20 44 69 76 - 69 73 69 6F 6E 61 6C 20 48 52 04 00 00 31 30 39 - 39 19 00 00 48 65 61 64 20 6F 66 20 47 72 6F 75 - 70 20 50 4D 20 43 61 73 75 61 6C 74 79 02 00 00 - 49 4C 04 00 00 31 31 31 37 13 00 00 41 75 73 73 - 65 6E 73 74 65 6C 6C 65 6E 6C 65 69 74 65 72 04 - 00 00 31 34 34 38 04 00 00 31 34 35 36 0D 00 00 - 41 64 6D 69 6E 69 73 74 72 61 74 6F 72 04 00 00 - 31 34 36 30 0E 00 00 53 61 63 68 62 65 61 72 62 - 65 69 74 65 72 04 00 00 31 34 36 36 02 00 00 47 - 52 04 00 00 31 34 37 36 19 00 00 53 65 6B 74 69 - 6F 6E 73 6C 2E 20 47 72 70 2E 20 52 65 70 6F 72 - 74 69 6E 67 03 00 00 43 48 46 04 00 00 31 34 38 - 34 02 00 00 53 55 04 00 00 31 34 39 30 12 00 00 - 50 6C 61 6E 65 72 2F 4B 6F 6F 72 64 69 6E 61 74 - 6F 72 04 00 00 31 34 39 39 11 00 00 4C 65 69 74 - 65 72 20 4F 70 65 72 61 74 69 6F 6E 73 04 00 00 - 31 35 30 37 04 00 00 31 35 32 35 16 00 00 53 79 - 73 74 65 6D 20 50 72 6F 7A 65 73 73 20 4D 61 6E - 61 67 65 72 04 00 00 31 35 34 31 02 00 00 52 59 - 02 00 00 52 4D 04 00 00 31 35 35 30 19 00 00 48 - 65 61 64 20 6F 66 20 52 69 73 6B 20 4D 67 74 20 - 53 65 72 76 69 63 65 73 02 00 00 54 43 04 00 00 - 31 35 35 32 04 00 00 31 35 37 32 12 00 00 55 73 - 65 72 20 41 64 6D 69 6E 69 73 74 72 61 74 6F 72 - 02 00 00 46 41 04 00 00 31 35 37 34 16 00 00 53 - 61 63 68 62 65 61 72 62 65 69 74 65 72 69 6E 20 - 4B 61 73 73 65 04 00 00 31 35 39 39 04 00 00 31 - 36 31 31 04 00 00 31 36 32 32 18 00 00 4D 65 6D - 62 65 72 20 6F 66 20 4C 26 48 20 45 78 65 63 2E - 42 6F 61 72 64 02 00 00 44 4D 04 00 00 31 36 32 - 33 12 00 00 47 72 6C 2E 20 44 72 75 63 6B 76 6F - 72 73 74 75 66 65 02 00 00 49 4F 04 00 00 31 36 - 36 39 17 00 00 4B 6F 6E 7A 65 72 6E 2D 49 6E 66 - 6F 72 6D 2E 20 45 69 6E 6B 61 75 66 02 00 00 47 - 41 04 00 00 31 36 37 30 04 00 00 31 36 38 35 14 - 00 00 47 72 75 70 70 65 6E 6C 65 69 74 65 72 69 - 6E 20 46 69 62 75 04 00 00 31 37 30 32 04 00 00 - 31 37 30 39 04 00 00 31 37 32 35 14 00 00 46 61 - 63 68 73 70 65 7A 69 61 6C 69 73 74 20 52 65 74 - 72 6F 03 00 00 41 52 53 04 00 00 31 37 33 36 19 - 00 00 4D 61 6E 61 67 65 72 20 54 72 61 69 6E 69 - 6E 67 26 44 65 76 65 6C 6F 70 6D 04 00 00 31 37 - 34 39 0F 00 00 50 72 6F 6A 65 63 74 20 4D 61 6E - 61 67 65 72 04 00 00 31 37 35 39 04 00 00 31 37 - 37 32 17 00 00 4F 70 65 72 61 74 6F 72 20 4B 6F - 70 69 65 72 7A 65 6E 74 72 61 6C 65 04 00 00 31 - 37 38 38 04 00 00 31 38 30 32 02 00 00 43 4C 04 - 00 00 31 38 30 33 11 00 00 54 65 61 6D 20 4C 65 - 61 64 65 72 20 4B 56 2F 55 56 04 00 00 31 38 33 - 38 0D 00 00 50 72 6F 6A 65 6B 74 6C 65 69 74 65 - 72 02 00 00 49 52 04 00 00 31 38 35 36 04 00 00 - 31 38 36 37 13 00 00 53 61 63 68 62 65 61 72 62 - 65 69 74 65 72 69 6E 20 50 56 04 00 00 31 38 36 - 38 19 00 00 54 65 61 6D 6C 65 69 74 65 72 20 47 - 65 62 E4 75 64 65 74 65 63 68 6E 69 6B 04 00 00 - 31 38 39 31 18 00 00 42 65 72 65 69 63 68 73 6C - 65 69 74 65 72 20 52 65 70 6F 72 74 69 6E 67 02 - 00 00 4C 43 04 00 00 31 39 30 30 12 00 00 53 65 - 6E 2E 20 4C 65 67 61 6C 20 43 6F 75 6E 73 65 6C - 04 00 00 31 39 30 34 04 00 00 31 39 30 35 0D 00 - 00 52 61 75 6D 70 66 6C 65 67 65 72 69 6E 04 00 - 00 31 39 32 34 04 00 00 31 39 33 36 0A 00 00 49 - 6E 73 74 72 75 63 74 6F 72 04 00 00 31 39 33 39 - 19 00 00 4D 61 6E 61 67 65 72 20 54 72 61 69 6E - 69 6E 67 20 43 6F 6E 63 65 70 74 73 01 00 00 57 - 02 00 00 50 49 04 00 00 31 39 34 32 11 00 00 50 - 6F 72 74 66 6F 6C 69 6F 20 4D 61 6E 61 67 65 72 - 04 00 00 31 39 35 31 0C 00 00 43 61 73 68 20 4D - 61 6E 61 67 65 72 04 00 00 31 39 35 34 04 00 00 - 31 39 36 36 04 00 00 31 39 38 32 13 00 00 50 72 - 6F 64 75 63 74 73 2F 47 75 69 64 65 6C 69 6E 65 - 73 04 00 00 31 39 39 30 04 00 00 31 39 39 36 04 - 00 00 32 30 30 36 11 00 00 45 78 70 65 72 74 65 - 20 4B 61 74 61 6B 75 6D 75 6C 04 00 00 32 30 33 - 32 17 00 00 54 65 61 6D 6C 65 69 74 65 72 20 42 - 75 63 68 62 69 6E 64 65 72 65 69 04 00 00 32 30 - 33 34 16 00 00 50 72 6F 6A 65 6B 74 6C 65 69 74 - 65 72 20 46 61 63 68 61 62 74 2E 02 00 00 43 43 - 19 00 00 48 65 61 64 20 4D 65 64 69 61 20 43 6F - 6D 6D 75 6E 69 63 61 74 69 6F 6E 73 04 00 00 32 - 30 36 30 02 00 00 52 58 02 00 00 41 4C 04 00 00 - 32 30 36 31 18 00 00 48 65 61 64 20 6F 66 20 43 - 49 52 4D 26 52 65 69 6E 2E 20 53 75 70 70 2E 04 - 00 00 32 30 36 33 04 00 00 32 30 36 37 19 00 00 - 4C 65 69 74 65 72 20 42 65 74 72 69 65 62 73 6C - 69 65 67 65 6E 73 63 68 2E 02 00 00 49 58 04 00 - 00 32 30 37 31 04 00 00 32 30 37 37 15 00 00 49 - 6E 66 6F 72 6D 61 74 69 6B 20 43 6F 6E 73 75 6C - 74 61 6E 74 04 00 00 32 30 38 30 13 00 00 53 65 - 63 72 65 74 61 72 79 20 44 69 76 2E 20 48 65 61 - 64 03 00 00 43 41 44 02 00 00 44 4F 04 00 00 32 - 30 38 32 19 00 00 48 65 61 64 20 44 69 73 63 6F - 6E 74 69 6E 75 65 64 20 4F 70 65 72 61 74 2E 04 - 00 00 32 30 38 37 04 00 00 32 30 39 31 04 00 00 - 32 31 31 32 04 00 00 32 31 33 38 17 00 00 53 65 - 6E 69 6F 72 20 42 75 73 69 6E 65 73 73 20 41 6E - 61 6C 79 73 74 04 00 00 32 31 34 33 04 00 00 32 - 31 34 39 17 00 00 52 65 67 69 6F 6E 61 6C 20 4D - 61 6E 61 67 65 72 20 4C 26 48 20 4C 54 04 00 00 - 32 31 39 39 0E 00 00 43 6C 69 65 6E 74 20 4D 61 - 6E 61 67 65 72 04 00 00 32 32 31 31 18 00 00 4C - 65 69 74 65 72 20 43 75 73 74 6F 6D 65 72 20 53 - 65 72 76 69 63 65 73 04 00 00 32 32 31 34 04 00 - 00 32 32 32 30 19 00 00 48 52 2D 4D 49 53 2D 26 - 20 50 34 30 30 2D 41 70 70 6C 69 63 61 74 69 6F - 6E 04 00 00 32 32 32 37 13 00 00 54 65 63 68 6E - 69 63 61 6C 20 53 75 70 70 6F 72 74 65 72 04 00 - 00 32 32 35 30 19 00 00 54 72 61 69 6E 69 6E 67 - 2D 20 26 20 50 72 6F 6A 65 63 74 6D 61 6E 61 67 - 2E 04 00 00 32 32 35 31 19 00 00 44 65 70 2E 48 - 65 61 64 20 6F 66 20 47 72 6F 75 70 20 50 4D 20 - 50 72 6F 70 04 00 00 32 32 35 33 13 00 00 47 72 - 6C 2E 20 47 6C 6F 62 61 6C 20 53 75 70 70 6F 72 - 74 04 00 00 32 32 39 35 11 00 00 54 4C 20 48 61 - 75 73 77 69 72 74 73 63 68 61 66 74 04 00 00 32 - 32 39 36 04 00 00 32 33 30 32 04 00 00 32 33 31 - 38 0D 00 00 52 69 73 69 6B 6F 65 78 70 65 72 74 - 65 04 00 00 32 33 32 33 04 00 00 32 33 32 35 04 - 00 00 32 33 33 32 04 00 00 32 33 34 31 19 00 00 - 41 63 63 6F 75 6E 74 61 6E 74 20 53 70 65 63 69 - 61 6C 20 42 75 73 69 6E 2E 04 00 00 32 33 37 37 - 11 00 00 50 72 6F 6A 65 6B 74 6C 65 69 74 65 72 - 20 4D 49 50 04 00 00 32 33 38 36 19 00 00 53 65 - 6E 2E 43 6C 61 69 6D 73 20 49 6E 66 2E 53 70 65 - 63 69 61 6C 69 73 74 04 00 00 32 34 32 37 16 00 - 00 47 72 6C 2E 20 49 6E 73 74 61 6C 6C 2E 20 53 - 65 72 76 69 63 65 73 04 00 00 32 34 33 36 17 00 - 00 48 65 61 64 20 6F 66 20 43 6C 61 69 6D 73 20 - 53 65 72 76 69 63 65 73 04 00 00 32 34 35 33 16 - 00 00 42 4C 20 47 72 6F 75 70 20 44 61 74 61 20 - 53 65 72 76 69 63 65 73 04 00 00 32 34 35 36 04 - 00 00 32 34 36 39 19 00 00 47 72 61 66 69 73 63 - 68 65 72 20 53 61 63 68 62 65 61 72 62 65 69 74 - 65 72 04 00 00 32 34 38 31 16 00 00 55 57 2F 50 - 72 6F 64 75 63 74 20 63 6F 6E 74 72 6F 6C 6C 69 - 6E 67 02 00 00 49 55 04 00 00 32 34 39 39 14 00 - 00 41 70 70 6C 69 63 61 74 69 6F 6E 20 45 6E 67 - 69 6E 65 65 72 04 00 00 32 35 32 32 04 00 00 32 - 35 34 30 0B 00 00 55 6E 64 65 72 77 72 69 74 65 - 72 04 00 00 32 35 34 35 04 00 00 32 35 36 34 04 - 00 00 32 35 36 35 04 00 00 32 35 36 36 04 00 00 - 32 35 37 33 04 00 00 32 35 38 30 15 00 00 46 61 - 63 68 72 65 66 65 72 65 6E 74 20 43 61 73 75 61 - 6C 74 79 02 00 00 43 42 04 00 00 32 35 38 31 10 - 00 00 49 6E 74 2E 20 41 73 73 69 67 6E 6D 65 6E - 74 73 04 00 00 32 35 38 39 02 00 00 54 55 04 00 - 00 32 36 30 38 04 00 00 32 36 31 30 17 00 00 4C - 65 69 74 65 72 69 6E 20 41 64 6D 69 6E 69 73 74 - 72 61 74 69 6F 6E 04 00 00 32 36 33 32 04 00 00 - 32 36 34 34 19 00 00 53 74 76 2E 20 4C 65 69 74 - 65 72 20 41 6B 74 69 65 6E 72 65 67 69 73 74 2E - 04 00 00 32 36 34 35 04 00 00 32 36 35 33 19 00 - 00 47 72 75 70 70 65 6E 6C 65 69 74 65 72 20 52 - 65 69 73 65 64 69 65 6E 73 74 04 00 00 32 36 37 - 31 18 00 00 50 72 6F 6A 65 6B 74 6C 65 69 74 65 - 72 69 6E 20 diff --git a/test-data/spreadsheet/BigSSTRecord2CR3 b/test-data/spreadsheet/BigSSTRecord2CR3 deleted file mode 100644 index 461dfae5e..000000000 --- a/test-data/spreadsheet/BigSSTRecord2CR3 +++ /dev/null @@ -1,515 +0,0 @@ - 3C 00 1C 20 00 46 61 63 68 61 62 74 - 2E 04 00 00 32 36 37 33 12 00 00 53 65 72 76 69 - 63 65 6D 69 74 61 72 62 65 69 74 65 72 04 00 00 - 32 36 37 34 04 00 00 32 36 38 34 04 00 00 32 37 - 31 31 18 00 00 4C 65 69 74 65 72 20 55 73 65 72 - 20 54 72 61 69 6E 2E 20 53 65 72 76 2E 04 00 00 - 32 37 31 37 0E 00 00 54 65 6C 65 6F 70 65 72 61 - 74 72 69 63 65 04 00 00 32 37 31 39 04 00 00 32 - 37 33 31 19 00 00 48 65 61 64 20 6F 66 20 52 65 - 69 6E 73 75 72 61 6E 63 65 20 54 6F 6F 6C 73 04 - 00 00 32 37 33 32 12 00 00 50 72 6F 64 75 63 74 - 20 43 6F 6E 74 72 6F 6C 6C 65 72 04 00 00 32 37 - 34 33 04 00 00 32 37 35 35 12 00 00 4F 70 65 72 - 61 74 69 6F 6E 73 20 4F 66 66 69 63 65 72 04 00 - 00 32 37 36 31 18 00 00 47 72 6C 2E 20 53 79 73 - 74 65 6D 20 41 64 6D 69 6E 69 73 74 72 61 74 2E - 02 00 00 52 4B 04 00 00 32 37 36 38 16 00 00 48 - 65 61 64 20 6F 66 20 43 6F 6D 6D 75 6E 69 63 61 - 74 69 6F 6E 73 04 00 00 32 37 36 39 04 00 00 32 - 37 37 32 04 00 00 32 37 37 37 04 00 00 32 37 38 - 33 0D 00 00 47 4C 2D 53 65 6B 72 65 74 E4 72 69 - 6E 04 00 00 32 37 38 34 04 00 00 32 37 38 37 19 - 00 00 47 72 6C 2E 20 4E 57 20 52 65 73 65 61 72 - 63 68 2F 44 65 76 65 6C 6F 70 6D 04 00 00 32 37 - 38 38 04 00 00 32 37 38 39 13 00 00 52 65 69 6E - 73 75 72 61 6E 63 65 20 41 6E 61 6C 79 73 74 04 - 00 00 32 38 30 37 11 00 00 44 65 70 75 74 79 20 - 48 65 61 64 20 6F 66 20 43 41 04 00 00 32 38 31 - 37 18 00 00 46 69 6E 2E 20 4D 61 72 6B 65 74 20 - 52 69 73 6B 20 41 6E 61 6C 79 73 74 04 00 00 32 - 38 31 38 19 00 00 44 65 70 2E 20 48 65 61 64 20 - 54 65 63 68 6E 2E 20 54 72 61 69 6E 69 6E 67 04 - 00 00 32 38 32 36 02 00 00 50 4F 04 00 00 32 38 - 32 39 18 00 00 50 72 6F 6A 65 63 74 20 4D 67 6D - 74 2E 20 43 6F 6E 73 75 6C 74 61 6E 74 04 00 00 - 32 38 33 35 0C 00 00 52 E9 63 65 70 74 69 6F 6E - 69 73 74 04 00 00 32 38 33 36 04 00 00 32 38 33 - 37 13 00 00 53 74 76 2E 20 53 65 6B 74 69 6F 6E - 73 6C 65 69 74 65 72 04 00 00 32 38 34 37 14 00 - 00 54 65 63 68 6E 69 63 61 6C 20 41 63 63 6F 75 - 6E 74 61 6E 74 02 00 00 52 55 04 00 00 32 38 35 - 32 0E 00 00 43 68 69 65 66 20 45 6E 67 69 6E 65 - 65 72 04 00 00 32 38 35 34 19 00 00 48 65 61 64 - 20 6F 66 20 47 72 6F 75 70 20 50 4D 20 45 6E 67 - 69 6E 65 65 2E 04 00 00 32 38 36 33 19 00 00 54 - 4C 20 48 61 75 73 2D 20 26 20 42 65 74 72 69 65 - 62 73 64 69 65 6E 73 74 04 00 00 32 38 39 32 0C - 00 00 41 56 2D 54 65 63 68 6E 69 6B 65 72 04 00 - 00 32 38 39 39 0F 00 00 42 65 74 72 69 65 62 73 - 67 E4 72 74 6E 65 72 04 00 00 32 39 32 35 19 00 - 00 48 65 61 64 20 6F 66 20 4C 65 67 61 6C 26 43 - 6C 61 69 6D 73 20 53 65 72 76 02 00 00 43 58 04 - 00 00 32 39 32 39 0E 00 00 48 65 61 64 20 6F 66 - 20 45 76 65 6E 74 73 04 00 00 32 39 33 31 0A 00 - 00 43 6F 6E 74 72 6F 6C 6C 65 72 04 00 00 32 39 - 33 32 04 00 00 32 39 33 33 04 00 00 32 39 34 30 - 14 00 00 50 4C 20 52 56 2D 54 65 63 68 6E 2E 20 - 53 79 73 74 65 6D 65 04 00 00 32 39 34 31 0C 00 - 00 4C 65 69 74 65 72 20 4B 61 73 73 65 04 00 00 - 32 39 35 38 02 00 00 48 52 04 00 00 32 39 36 35 - 19 00 00 48 75 6D 61 6E 20 52 65 73 6F 75 72 63 - 65 73 20 41 73 73 69 73 74 61 6E 74 04 00 00 32 - 39 36 38 19 00 00 48 65 61 64 20 4D 61 72 6B 65 - 74 69 6E 67 20 52 FC 73 63 68 6C 69 6B 6F 6E 04 - 00 00 32 39 37 33 14 00 00 43 6F 75 72 73 65 20 - 41 64 6D 69 6E 69 73 74 72 61 74 6F 72 04 00 00 - 32 39 38 31 13 00 00 4D 61 72 6B 65 74 69 6E 67 - 20 41 73 73 69 73 74 61 6E 74 02 00 00 44 43 04 - 00 00 32 39 38 34 0E 00 00 42 65 72 65 69 63 68 - 73 6C 65 69 74 65 72 04 00 00 32 39 38 38 15 00 - 00 53 65 6E 69 6F 72 20 52 65 69 6E 73 2E 20 41 - 6E 61 6C 79 73 74 04 00 00 32 39 39 37 12 00 00 - 50 72 6F 6A 65 63 74 20 4C 65 61 64 65 72 20 46 - 53 41 04 00 00 32 39 39 38 04 00 00 33 30 30 31 - 04 00 00 33 30 31 32 0E 00 00 54 65 61 6D 20 4C - 65 61 64 65 72 20 46 54 01 00 00 42 04 00 00 33 - 30 35 32 15 00 00 47 72 6C 2E 20 43 6F 72 70 6F - 72 61 74 65 20 44 65 73 69 67 6E 04 00 00 33 30 - 35 38 17 00 00 55 57 20 46 61 63 75 6C 74 61 74 - 69 76 65 20 50 72 6F 70 65 72 74 79 04 00 00 33 - 30 36 32 02 00 00 46 43 04 00 00 33 30 37 37 0B - 00 00 48 65 61 64 20 6F 66 20 43 4F 43 04 00 00 - 33 30 39 31 04 00 00 33 31 30 34 0F 00 00 47 65 - 73 63 68 E4 66 74 73 6C 65 69 74 65 72 04 00 00 - 33 31 31 35 04 00 00 33 31 33 34 04 00 00 33 31 - 33 37 19 00 00 53 65 6E 2E 41 63 63 6F 75 6E 74 - 61 6E 74 20 47 72 6F 75 70 20 52 65 70 2E 04 00 - 00 33 31 33 38 10 00 00 53 65 6B 74 69 6F 6E 73 - 6C 65 69 74 65 72 69 6E 04 00 00 33 31 34 37 04 - 00 00 33 31 35 35 04 00 00 33 31 35 36 19 00 00 - 48 65 61 64 20 6F 66 20 55 57 2F 50 72 6F 64 75 - 63 74 20 43 6F 6E 74 72 2E 04 00 00 33 31 37 34 - 04 00 00 33 31 38 37 04 00 00 33 31 39 37 02 00 - 00 49 42 04 00 00 33 32 32 34 02 00 00 49 46 04 - 00 00 33 32 32 36 17 00 00 49 6E 66 6F 72 6D 61 - 74 69 6F 6E 73 2D 53 70 65 7A 69 61 6C 69 73 74 - 04 00 00 33 32 32 38 12 00 00 50 6C 61 6E 6E 65 - 72 2F 43 6F 6E 74 72 6F 6C 6C 65 72 04 00 00 33 - 32 33 37 10 00 00 41 64 6D 69 6E 2E 20 41 73 73 - 69 73 74 61 6E 74 04 00 00 33 32 35 39 0F 00 00 - 43 6F 6F 72 64 69 6E 61 74 6F 72 20 42 43 4D 04 - 00 00 33 32 36 30 18 00 00 50 72 6F 70 65 72 74 - 79 20 50 72 6F 64 75 63 74 20 4D 61 6E 61 67 65 - 72 04 00 00 33 32 36 37 0B 00 00 43 4F 43 20 4D - 61 6E 61 67 65 72 04 00 00 33 32 39 37 16 00 00 - 4C 65 69 74 65 72 20 49 6E 66 6F 72 6D 61 74 69 - 6B 20 53 74 61 62 04 00 00 33 33 30 34 19 00 00 - 41 73 73 69 73 74 61 6E 74 20 41 63 63 6F 75 6E - 74 20 4D 61 6E 61 67 65 72 04 00 00 33 33 30 36 - 13 00 00 47 72 6C 2E 20 55 73 65 72 20 48 65 6C - 70 20 44 65 73 6B 04 00 00 33 33 31 36 04 00 00 - 33 33 32 33 04 00 00 33 33 32 36 04 00 00 33 33 - 32 37 0F 00 00 41 63 63 6F 75 6E 74 20 4D 61 6E - 61 67 65 72 04 00 00 33 33 32 38 04 00 00 33 33 - 33 33 01 00 00 45 04 00 00 33 33 34 32 18 00 00 - 48 65 61 64 20 6F 66 20 50 72 6F 64 2E 2F 47 75 - 69 64 65 6C 69 6E 65 73 04 00 00 33 33 34 39 04 - 00 00 33 33 35 30 04 00 00 33 33 35 31 04 00 00 - 33 33 35 34 14 00 00 45 69 6E 72 69 63 68 74 75 - 6E 67 73 70 6C 61 6E 65 72 69 6E 04 00 00 33 33 - 36 30 02 00 00 42 49 04 00 00 33 33 36 32 04 00 - 00 33 33 37 36 04 00 00 33 33 37 39 04 00 00 33 - 33 38 31 04 00 00 33 34 32 31 14 00 00 48 65 61 - 64 20 6F 66 20 50 72 69 63 69 6E 67 2F 44 61 74 - 61 04 00 00 33 34 36 34 19 00 00 48 65 61 64 20 - 47 72 70 2E 20 4D 61 72 6B 65 74 43 6F 6D 6D 75 - 6E 69 63 2E 04 00 00 33 34 36 38 04 00 00 33 34 - 36 39 19 00 00 42 4C 20 44 61 74 61 20 43 6F 6D - 6D 75 6E 69 63 2E 20 53 79 73 74 65 6D 73 04 00 - 00 33 34 37 31 16 00 00 4C 69 6E 67 65 72 69 65 - 6D 69 74 61 72 62 65 69 74 65 72 2F 69 6E 04 00 - 00 33 34 38 35 16 00 00 53 61 63 68 62 65 61 72 - 62 2E 20 50 6F 73 74 64 69 65 6E 73 74 65 04 00 - 00 33 34 38 38 11 00 00 43 6C 61 69 6D 73 20 4D - 61 6E 61 67 65 6D 65 6E 74 04 00 00 33 34 39 30 - 17 00 00 54 65 63 68 6E 69 73 63 68 65 72 20 4D - 69 74 61 72 62 65 69 74 65 72 04 00 00 33 34 39 - 31 0D 00 00 42 65 74 72 69 65 62 73 6D 61 6C 65 - 72 04 00 00 33 35 30 36 04 00 00 33 35 30 37 04 - 00 00 33 35 31 31 17 00 00 43 68 69 65 66 20 45 - 78 65 63 75 74 69 76 65 20 4F 66 66 69 63 65 72 - 04 00 00 33 35 32 30 04 00 00 33 35 32 38 11 00 - 00 42 65 74 72 69 65 62 73 74 65 63 68 6E 69 6B - 65 72 04 00 00 33 35 33 30 04 00 00 33 35 33 32 - 02 00 00 49 41 04 00 00 33 35 34 30 0E 00 00 53 - 65 6E 69 6F 72 20 41 75 64 69 74 6F 72 04 00 00 - 33 35 34 33 12 00 00 50 72 6F 6A 65 6B 74 6D 69 - 74 61 72 62 65 69 74 65 72 04 00 00 33 35 34 36 - 05 00 00 38 30 34 33 30 20 00 00 52 65 73 65 61 - 72 63 68 20 49 6E 66 6F 72 6D 61 74 69 6F 6E 20 - 53 70 65 63 69 61 6C 69 73 74 2C 05 00 00 31 30 - 38 34 35 1E 00 00 47 72 6F 75 70 20 43 6C 61 69 - 6D 73 20 61 6E 64 20 43 6F 6E 74 72 61 63 74 20 - 4D 61 6E 61 05 00 00 31 31 31 34 33 05 00 00 38 - 31 38 31 39 12 00 00 52 65 73 65 61 72 63 68 20 - 41 73 73 69 73 74 61 6E 74 05 00 00 38 30 32 33 - 36 17 00 00 49 6E 66 6F 72 6D 61 74 69 6F 6E 20 - 53 70 65 63 69 61 6C 69 73 74 2C 05 00 00 31 32 - 34 31 37 03 00 00 33 35 33 02 00 00 53 47 09 00 - 00 53 69 6E 67 61 70 6F 72 65 03 00 00 31 35 30 - 15 00 00 47 65 6E 65 72 61 6C 20 41 64 6D 69 6E - 69 73 74 72 61 74 6F 72 03 00 00 31 35 31 09 00 - 00 4D 65 73 73 65 6E 67 65 72 02 00 00 41 4F 02 - 00 00 54 52 02 00 00 37 33 19 00 00 4D 67 72 20 - 54 72 61 69 6E 2E 20 26 20 43 6C 69 65 6E 74 20 - 53 65 72 76 2E 02 00 00 41 43 02 00 00 4D 41 04 - 00 00 31 37 39 31 12 00 00 4D 61 72 69 6E 65 20 - 55 6E 64 65 72 77 72 69 74 65 72 02 00 00 54 57 - 06 00 00 54 61 69 70 65 69 03 00 00 32 32 35 06 - 00 00 44 72 69 76 65 72 02 00 00 4D 59 0C 00 00 - 4B 75 61 6C 61 20 4C 75 6D 70 75 72 03 00 00 33 - 34 36 12 00 00 41 63 63 6F 75 6E 74 73 20 45 78 - 65 63 75 74 69 76 65 02 00 00 41 4B 04 00 00 38 - 34 38 37 02 00 00 50 48 06 00 00 4D 61 6E 69 6C - 61 03 00 00 33 36 39 17 00 00 45 6E 67 69 6E 65 - 65 72 69 6E 67 20 55 6E 64 65 72 77 72 69 74 65 - 72 04 00 00 39 33 37 39 18 00 00 41 63 74 75 61 - 72 2E 20 26 20 50 72 6F 64 2E 20 43 6F 6E 74 72 - 6F 6C 2E 04 00 00 36 30 35 31 05 00 00 31 32 31 - 39 37 19 00 00 53 65 6E 69 6F 72 20 45 6E 65 72 - 67 79 20 55 6E 64 65 72 77 72 69 74 65 72 04 00 - 00 36 33 36 33 0E 00 00 45 6E 67 69 6E 65 65 72 - 69 6E 67 20 55 57 05 00 00 31 30 35 31 35 15 00 - 00 50 72 6F 70 65 72 74 79 20 55 6E 74 65 72 77 - 72 69 74 69 6E 67 04 00 00 38 35 39 30 17 00 00 - 4F 70 65 72 61 74 69 6F 6E 61 6C 20 43 6F 6E 74 - 72 6F 6C 6C 69 6E 67 02 00 00 45 54 04 00 00 32 - 38 31 32 03 00 00 34 38 39 14 00 00 50 72 6F 70 - 65 72 74 79 20 55 6E 64 65 72 77 72 69 74 65 72 - 04 00 00 33 38 38 30 04 00 00 33 32 30 32 18 00 - 00 48 65 61 64 20 44 43 45 4F 2F 43 6F 6D 6D 75 - 6E 69 63 61 74 69 6F 6E 73 04 00 00 35 37 35 33 - 19 00 00 43 61 73 75 61 6C 74 79 20 55 6E 64 65 - 72 77 72 69 74 69 6E 67 20 4D 67 72 04 00 00 36 - 35 31 32 17 00 00 44 69 76 69 73 69 6F 6E 61 6C - 20 43 6F 73 74 20 4D 61 6E 61 67 65 72 04 00 00 - 31 38 38 33 18 00 00 54 72 61 69 6E 2E 20 26 20 - 43 6C 69 65 6E 74 20 53 65 72 76 69 63 65 73 02 - 00 00 44 50 04 00 00 37 35 39 30 13 00 00 44 69 - 76 69 73 69 6F 6E 61 6C 20 50 6C 61 6E 6E 69 6E - 67 05 00 00 31 31 38 36 37 14 00 00 43 61 73 75 - 61 6C 74 79 20 55 6E 64 65 72 77 72 69 74 65 72 - 04 00 00 33 39 31 39 0D 00 00 44 69 76 69 73 69 - 6F 6E 61 6C 20 49 54 03 00 00 33 37 30 10 00 00 - 4D 65 73 73 65 6E 67 65 72 2F 44 72 69 76 65 72 - 03 00 00 35 37 31 04 00 00 38 36 31 34 19 00 00 - 4D 67 72 20 41 63 74 2E 20 26 20 50 72 6F 64 2E - 20 43 6F 6E 74 72 6F 6C 2E 03 00 00 33 37 31 18 - 00 00 41 64 6D 69 6E 69 73 74 72 61 74 69 76 65 - 20 41 73 73 69 73 74 61 6E 74 03 00 00 34 39 36 - 15 00 00 44 65 70 75 74 79 20 43 6C 69 65 6E 74 - 20 4D 61 6E 61 67 65 72 03 00 00 32 35 37 14 00 - 00 54 72 65 61 74 79 20 41 64 6D 69 6E 69 73 74 - 72 61 74 6F 72 03 00 00 31 35 35 1D 00 00 54 65 - 63 68 6E 2E 20 41 63 63 6F 75 6E 74 73 20 41 64 - 6D 69 6E 69 73 74 72 61 74 6F 72 02 00 00 54 48 - 07 00 00 42 61 6E 67 6B 6F 6B 0D 00 00 52 69 73 - 6B 20 45 6E 67 69 6E 65 65 72 03 00 00 35 36 36 - 14 00 00 46 69 6E 61 6E 63 69 61 6C 20 43 6F 6E - 74 72 6F 6C 6C 65 72 03 00 00 34 39 39 1D 00 00 - 43 6C 69 65 6E 74 20 4D 67 6D 74 26 46 69 6E 61 - 6E 63 69 61 6C 20 41 64 69 73 6F 72 79 03 00 00 - 33 30 39 14 00 00 53 65 6E 69 6F 72 20 52 69 73 - 6B 20 45 6E 67 69 6E 65 65 72 05 00 00 31 30 32 - 31 30 02 00 00 43 4E 07 00 00 42 65 69 6A 69 6E - 67 03 00 00 31 35 37 1D 00 00 53 65 63 72 65 74 - 61 72 79 20 74 6F 20 43 68 69 65 66 20 52 65 70 - 72 65 73 65 6E 74 2E 03 00 00 32 32 39 03 00 00 - 35 39 35 14 00 00 43 68 69 65 66 20 52 65 70 72 - 65 73 65 6E 74 61 74 69 76 65 03 00 00 32 32 38 - 12 00 00 54 72 65 61 74 79 20 55 6E 64 65 72 77 - 72 69 74 65 72 03 00 00 32 39 34 0E 00 00 43 6C - 61 69 6D 73 20 4D 61 6E 61 67 65 72 03 00 00 35 - 33 36 10 00 00 48 52 20 41 64 6D 69 6E 69 73 74 - 72 61 74 6F 72 14 00 00 4F 66 66 69 63 65 20 41 - 64 6D 69 6E 69 73 74 72 61 74 6F 72 03 00 00 35 - 37 32 03 00 00 31 35 39 1E 00 00 41 73 73 6F 63 - 69 61 74 65 2C 20 43 6F 72 70 6F 72 61 74 65 20 - 44 65 76 65 6C 6F 70 6D 2E 03 00 00 35 31 35 03 - 00 00 33 34 38 1C 00 00 41 73 73 69 73 74 61 6E - 74 20 74 6F 20 43 6C 69 65 6E 74 20 4D 67 74 20 - 54 65 61 6D 03 00 00 31 36 31 1A 00 00 52 65 67 - 69 6F 6E 61 6C 20 4D 61 72 69 6E 65 20 55 57 20 - 4D 61 6E 61 67 65 72 03 00 00 31 36 32 03 00 00 - 32 33 32 10 00 00 4F 66 66 69 63 65 20 41 73 73 - 69 73 74 61 6E 74 03 00 00 31 36 34 1A 00 00 43 - 6C 69 65 6E 74 20 43 6F 6F 72 64 69 6E 61 74 69 - 6F 6E 20 41 64 6D 69 6E 2E 03 00 00 32 33 33 19 - 00 00 41 73 73 74 2E 20 4D 61 6E 61 67 65 72 20 - 45 6E 67 69 6E 65 65 72 69 6E 67 04 00 00 38 35 - 35 35 03 00 00 31 36 35 1B 00 00 43 6C 69 65 6E - 74 20 52 65 6C 61 74 69 6F 6E 73 68 69 70 20 4D - 61 6E 61 67 65 72 03 00 00 31 36 37 1C 00 00 43 - 6C 69 65 6E 74 20 53 75 70 70 6F 72 74 20 41 64 - 6D 69 6E 69 73 74 72 61 74 6F 72 03 00 00 31 36 - 36 19 00 00 46 69 6E 61 6E 63 69 61 6C 20 41 63 - 63 6F 75 6E 74 73 20 41 64 6D 69 6E 2E 03 00 00 - 32 39 35 14 00 00 41 73 73 69 73 74 61 6E 74 20 - 41 63 63 6F 75 6E 74 61 6E 74 03 00 00 32 39 37 - 0F 00 00 45 44 50 20 43 6F 6F 72 64 69 6E 61 74 - 6F 72 08 00 00 53 68 61 6E 67 68 61 69 03 00 00 - 31 34 34 1A 00 00 52 65 70 72 65 73 65 6E 74 61 - 74 69 76 65 20 45 6E 67 69 6E 65 65 72 69 6E 67 - 03 00 00 33 37 33 1D 00 00 52 69 73 6B 20 45 6E - 67 69 6E 65 65 72 20 2F 49 54 20 43 6F 6F 72 64 - 69 6E 61 74 6F 72 03 00 00 33 37 34 14 00 00 41 - 63 63 6F 75 6E 74 69 6E 67 20 41 73 73 69 73 74 - 61 6E 74 03 00 00 35 34 33 04 00 00 38 36 30 33 - 03 00 00 31 32 35 16 00 00 52 65 69 6E 73 75 72 - 61 6E 63 65 20 41 63 63 6F 75 6E 74 61 6E 74 02 - 00 00 45 4E 04 00 00 37 36 33 39 04 00 00 36 36 - 38 34 18 00 00 4D 67 72 20 4F 70 65 72 61 74 69 - 6F 6E 61 6C 20 43 6F 6E 74 72 6F 6C 2E 04 00 00 - 32 34 33 33 04 00 00 31 38 33 34 19 00 00 4C 6F - 63 61 6C 20 4F 66 66 69 63 65 73 20 43 6F 6F 72 - 64 69 6E 61 74 6F 72 04 00 00 38 36 35 36 15 00 - 00 53 74 72 61 74 65 67 69 63 20 43 6F 6E 74 72 - 6F 6C 6C 69 6E 67 02 00 00 41 45 05 00 00 31 32 - 35 34 36 04 00 00 32 31 33 34 05 00 00 31 30 38 - 39 35 04 00 00 38 35 30 33 05 00 00 31 31 37 36 - 32 1B 00 00 48 65 61 64 20 46 61 63 2E 50 72 6F - 70 2E 47 72 65 61 74 65 72 20 43 68 69 6E 61 03 - 00 00 35 38 37 1C 00 00 41 73 73 74 2E 4D 67 72 - 2E 20 54 6F 20 43 6C 69 65 6E 74 20 4D 67 74 20 - 54 65 61 6D 03 00 00 35 36 37 17 00 00 48 65 61 - 64 20 6F 66 20 52 69 73 6B 20 4D 61 6E 61 67 65 - 6D 65 6E 74 04 00 00 38 35 39 32 03 00 00 31 34 - 36 03 00 00 35 38 33 1D 00 00 52 65 70 72 65 73 - 65 6E 74 61 74 69 76 65 26 43 6C 69 65 6E 74 20 - 4D 61 6E 61 67 65 72 02 00 00 41 58 04 00 00 33 - 35 32 32 15 00 00 48 65 61 64 20 50 65 72 66 6F - 72 6D 61 6E 63 65 20 54 65 61 6D 02 00 00 41 4A - 05 00 00 31 31 32 31 37 0A 00 00 33 32 34 2C 20 - 54 6F 6B 79 6F 03 00 00 31 36 38 0E 00 00 52 65 - 70 72 65 73 65 6E 74 61 74 69 76 65 04 00 00 38 - 36 33 36 03 00 00 35 30 31 1C 00 00 41 73 73 6F - 63 69 61 74 65 2C 20 43 6F 72 70 2E 20 44 65 76 - 65 6C 6F 70 6D 65 6E 74 04 00 00 35 39 32 39 04 - 00 00 38 35 39 31 04 00 00 35 38 35 39 04 00 00 - 35 38 30 39 05 00 00 31 32 35 34 38 15 00 00 43 - 61 73 75 61 6C 74 79 20 55 6E 64 65 72 77 72 69 - 74 69 6E 67 04 00 00 33 33 35 35 04 00 00 38 36 - 37 30 16 00 00 45 6E 67 69 6E 65 65 72 69 6E 67 - 20 55 57 20 4D 61 6E 61 67 65 72 04 00 00 37 32 - 32 36 04 00 00 35 34 38 31 13 00 00 42 55 53 20 - 50 72 6F 63 65 73 73 20 4D 61 6E 61 67 65 72 03 - 00 00 35 30 30 0D 00 00 43 6C 65 61 6E 69 6E 67 - 20 41 6D 61 68 03 00 00 33 35 30 03 00 00 33 30 - 33 10 00 00 43 6C 61 69 6D 73 20 41 73 73 69 73 - 74 61 6E 74 03 00 00 32 33 37 03 00 00 32 33 38 - 03 00 00 35 38 36 04 00 00 35 39 32 35 04 00 00 - 36 36 31 32 04 00 00 38 35 33 38 04 00 00 38 34 - 34 33 04 00 00 35 36 38 36 03 00 00 33 35 32 10 - 00 00 44 72 69 76 65 72 2F 4D 65 73 73 65 6E 67 - 65 72 04 00 00 36 37 35 32 12 00 00 4D 61 6E 61 - 67 65 72 20 4A 61 70 61 6E 20 44 65 73 6B 04 00 - 00 31 37 38 39 19 00 00 50 72 6F 70 65 72 74 79 - 20 55 6E 64 65 72 77 72 69 74 69 6E 67 20 4D 67 - 72 04 00 00 38 34 34 37 02 00 00 41 44 04 00 00 - 36 33 30 34 08 00 00 41 72 74 20 44 65 73 6B 04 - 00 00 31 39 30 32 04 00 00 36 30 37 35 03 00 00 - 33 32 30 16 00 00 52 65 63 65 70 74 69 6F 6E 69 - 73 74 2F 53 65 63 72 65 74 61 72 79 03 00 00 31 - 33 36 1A 00 00 48 65 61 64 20 4E 6F 6E 2D 4C 69 - 66 65 20 52 2F 49 20 53 65 72 76 69 63 65 73 03 - 00 00 31 33 39 1D 00 00 53 65 6E 69 6F 72 20 41 - 64 76 69 73 6F 72 20 4E 4C 20 52 49 20 53 65 72 - 76 69 63 65 73 03 00 00 31 33 38 10 00 00 4F 66 - 66 69 63 65 20 4D 67 6D 74 20 26 20 48 52 17 00 - 00 4E 4C 20 52 65 69 6E 73 75 72 61 6E 63 65 20 - 53 65 72 76 69 63 65 73 03 00 00 32 32 34 0F 00 - 00 47 65 6E 65 72 61 6C 20 4D 61 6E 61 67 65 72 - 03 00 00 31 37 38 1E 00 00 4D 67 6D 74 26 53 74 - 61 66 66 20 53 65 72 76 69 63 65 73 20 41 64 6D - 69 6E 69 73 74 72 2E 16 00 00 41 63 63 6F 75 6E - 74 73 20 41 64 6D 69 6E 69 73 74 72 61 74 6F 72 - 03 00 00 33 37 39 15 00 00 48 65 61 64 20 48 52 - 20 47 72 65 61 74 65 72 20 43 68 69 6E 61 04 00 - 00 32 35 36 30 03 00 00 31 38 31 14 00 00 48 65 - 61 64 20 6F 66 20 43 4D 20 49 6E 64 6F 6E 65 73 - 69 61 04 00 00 38 36 37 38 15 00 00 4D 61 6E 61 - 67 65 72 20 44 69 76 69 73 69 6F 6E 61 6C 20 49 - 54 04 00 00 34 31 32 32 03 00 00 33 33 31 02 00 - 00 49 4E 09 00 00 42 61 6E 67 61 6C 6F 72 65 03 - 00 00 35 37 33 13 00 00 54 65 61 6D 20 53 65 72 - 76 69 63 65 20 43 65 6E 74 65 72 04 00 00 35 39 - 30 31 04 00 00 38 35 32 36 03 00 00 35 38 32 17 - 00 00 48 65 61 64 20 6F 66 20 54 72 65 61 74 79 - 20 50 72 6F 70 65 72 74 79 03 00 00 35 30 33 03 - 00 00 33 31 31 03 00 00 35 32 38 03 00 00 33 38 - 35 19 00 00 45 6E 67 69 6E 65 65 72 69 6E 67 20 - 41 64 6D 69 6E 69 73 74 72 61 74 6F 72 03 00 00 - 33 31 33 1A 00 00 55 6E 64 65 72 77 72 69 74 69 - 6E 67 20 41 64 6D 69 6E 69 73 74 72 61 74 6F 72 - 03 00 00 35 37 30 17 00 00 53 65 6E 69 6F 72 20 - 55 2F 57 20 46 61 63 20 43 61 73 75 61 6C 74 79 - 17 00 00 46 61 63 75 6C 74 61 74 69 76 65 20 55 - 6E 64 65 72 77 72 69 74 65 72 03 00 00 33 31 35 - 1B 00 00 43 61 73 75 61 6C 74 79 20 54 72 65 61 - 74 79 20 55 6E 64 65 72 77 72 69 74 65 72 03 00 - 00 35 32 36 0A 00 00 48 52 20 4D 61 6E 61 67 65 - 72 03 00 00 31 38 33 03 00 00 35 37 38 03 00 00 - 33 35 34 07 00 00 4D 61 6E 61 67 65 72 03 00 00 - 32 33 39 03 00 00 35 35 36 18 00 00 53 65 6E 69 - 6F 72 20 55 57 2C 20 46 61 63 2E 20 50 72 6F 70 - 65 72 74 79 03 00 00 33 31 39 14 00 00 41 73 73 - 74 2E 20 45 6E 67 69 6E 65 65 72 69 6E 67 20 55 - 57 03 00 00 35 34 38 1A 00 00 54 72 61 69 6E 65 - 65 20 4D 61 72 69 6E 65 20 55 6E 64 65 72 77 72 - 69 74 65 72 03 00 00 33 35 35 03 00 00 31 38 38 - 15 00 00 49 54 20 53 75 70 70 6F 72 74 20 53 70 - 65 63 69 61 6C 69 73 74 03 00 00 31 39 30 03 00 - 00 32 34 30 19 00 00 46 61 63 2E 20 50 72 6F 70 - 65 72 74 79 20 55 6E 64 65 72 77 72 69 74 65 72 - 03 00 00 35 35 35 13 00 00 4D 61 72 69 6E 65 20 - 48 75 6C 6C 20 4D 61 6E 61 67 65 72 04 00 00 35 - 39 33 38 03 00 00 33 35 36 03 00 00 33 35 37 03 - 00 00 35 38 31 0C 00 00 52 65 63 65 70 74 69 6F - 6E 69 73 74 04 00 00 38 34 35 37 03 00 00 35 37 - 36 19 00 00 48 52 20 4D 61 6E 61 67 65 72 2C 20 - 53 65 61 20 45 61 73 74 20 41 73 69 61 06 00 00 - 4D 75 6D 62 61 69 03 00 00 33 38 30 1B 00 00 45 - 6E 67 69 6E 65 65 72 69 6E 67 20 4C 69 61 69 73 - 6F 6E 20 4D 61 6E 61 67 65 72 03 00 00 33 35 38 - 0E 00 00 53 65 6E 69 6F 72 20 4D 61 6E 61 67 65 - 72 04 00 00 38 34 35 38 04 00 00 38 34 35 39 03 - 00 00 31 32 36 13 00 00 54 65 63 68 6E 69 63 61 - 6C 20 41 73 73 69 73 74 61 6E 74 04 00 00 34 34 - 31 37 10 00 00 4E 6F 6E 2D 4C 69 66 65 20 4D 61 - 6E 61 67 65 72 04 00 00 39 37 32 39 04 00 00 38 - 35 37 39 04 00 00 32 37 33 38 03 00 00 31 39 35 - 1B 00 00 48 65 61 64 20 6F 66 20 43 6C 69 65 6E - 74 20 43 6F 6F 72 64 69 6E 61 74 69 6F 6E 03 00 - 00 31 32 37 16 00 00 53 65 63 72 65 74 61 72 79 - 2F 52 65 63 65 70 74 69 6F 6E 69 73 74 04 00 00 - 31 39 34 37 04 00 00 33 38 36 36 03 00 00 32 37 - 34 03 00 00 36 38 36 03 00 00 31 39 37 1C 00 00 - 54 65 63 68 6E 2E 41 63 63 6F 75 6E 74 73 20 41 - 64 6D 69 6E 69 73 74 72 61 74 6F 72 04 00 00 33 - 32 36 36 04 00 00 38 35 39 35 04 00 00 35 35 37 - 37 04 00 00 32 31 36 35 13 00 00 4D 61 6E 61 67 - 65 72 20 4B 6F 72 65 61 6E 20 44 65 73 6B 04 00 - 00 38 34 32 31 03 00 00 36 30 36 04 00 00 38 36 - 38 30 03 00 00 31 39 39 03 00 00 35 33 35 16 00 - 00 55 6E 64 65 72 77 72 69 74 69 6E 67 20 41 73 - 73 69 73 74 61 6E 74 03 00 00 35 35 39 04 00 00 - 38 35 31 31 03 00 00 32 30 30 12 00 00 43 6C 69 - 65 6E 74 20 43 6F 6F 72 64 69 6E 61 74 6F 72 04 - 00 00 35 32 32 32 04 00 00 38 35 38 33 03 00 00 - 34 39 37 14 00 00 4D 61 6E 61 67 65 72 20 55 6E - 64 65 72 77 72 69 74 69 6E 67 04 00 00 35 39 36 - 38 14 00 00 42 55 53 20 54 72 61 69 6E 69 6E 67 - 20 4D 61 6E 61 67 65 72 03 00 00 35 37 35 1A 00 - 00 52 65 67 69 6F 6E 61 6C 20 50 72 6F 70 65 72 - 74 79 20 46 61 63 2E 4D 67 72 2E 03 00 00 32 30 - 33 1B 00 00 44 65 70 75 74 79 20 48 65 61 64 20 - 45 4E 20 55 6E 64 65 72 77 72 69 74 69 6E 67 03 - 00 00 35 34 36 19 00 00 46 61 63 75 6C 74 61 74 - 69 76 65 20 41 64 6D 69 6E 69 73 74 72 61 74 6F - 72 04 00 00 36 36 32 32 05 00 00 31 32 35 35 39 - 05 00 00 31 32 30 38 38 03 00 00 35 31 36 04 00 - 00 32 38 39 30 15 00 00 49 6E 74 65 72 6E 61 74 - 69 6F 6E 61 6C 20 53 75 70 70 6F 72 74 03 00 00 - 34 39 35 18 00 00 50 72 6F 70 65 72 74 79 20 4C - 69 61 69 73 6F 6E 20 4D 61 6E 61 67 65 72 04 00 - 00 36 34 35 37 18 00 00 45 6E 67 69 6E 65 65 72 - 69 6E 67 20 55 6E 64 65 72 77 72 69 74 69 6E 67 - 04 00 00 34 30 32 34 03 00 00 31 36 33 12 00 00 - 48 65 61 64 20 4C 6F 63 61 6C 20 4F 66 66 69 63 - 65 73 04 00 00 34 38 35 39 16 00 00 4C 6F 74 75 - 73 20 4E 6F 74 65 73 20 45 6E 74 77 69 63 6B 6C - 65 72 04 00 00 38 35 34 32 04 00 00 38 35 32 37 - 04 00 00 38 35 33 36 04 00 00 36 35 35 33 04 00 - 00 32 34 35 31 14 00 00 44 65 70 61 72 74 6D 65 - 6E 74 20 53 65 63 72 65 74 61 72 79 03 00 00 39 - 36 35 04 00 00 38 36 36 37 10 00 00 52 65 73 65 - 61 72 63 68 20 26 20 43 6F 6D 6D 2E 04 00 00 38 - 34 37 38 04 00 00 31 38 34 34 03 00 00 33 34 32 - 10 00 00 41 63 63 6F 75 6E 74 73 20 4D 61 6E 61 - 67 65 72 03 00 00 35 33 34 10 00 00 46 61 63 2E - 20 50 72 6F 70 65 72 74 79 20 55 57 03 00 00 32 - 34 31 07 00 00 54 72 61 69 6E 65 65 03 00 00 32 - 34 32 03 00 00 35 32 35 13 00 00 41 63 63 6F 75 - 6E 74 20 55 6E 64 65 72 77 72 69 74 65 72 0A 00 - 00 32 36 2E 30 39 2E 31 39 37 38 0A 00 00 31 35 - 2E 30 36 2E 31 39 39 38 0A 00 00 30 31 2E 30 31 - 2E 31 39 35 34 0A 00 00 31 39 2E 30 39 2E 31 39 - 37 37 0A 00 00 32 30 2E 30 35 2E 31 39 35 31 0A - 00 00 30 31 2E 30 38 2E 31 39 39 38 0A 00 00 33 - 31 2E 31 30 2E 31 39 36 38 0A 00 00 30 34 2E 30 - 39 2E 31 39 36 34 0A 00 00 31 30 2E 30 37 2E 32 - 30 30 30 0A 00 00 32 39 2E 30 38 2E 31 39 36 38 - 0A 00 00 30 31 2E 31 30 2E 31 39 39 36 14 00 00 - 53 65 6E 6F 69 72 20 52 69 73 6B 20 45 6E 67 69 - 6E 65 65 72 0A 00 00 30 33 2E 31 30 2E 31 39 37 - 30 0A 00 00 30 31 2E 30 33 2E 31 39 39 38 0A 00 - 00 31 34 2E 30 33 2E 31 39 37 31 17 00 00 49 54 - 20 53 65 63 75 72 69 74 79 20 43 6F 6F 72 64 69 - 6E 61 74 6F 72 19 00 00 53 65 6E 2E 20 49 54 20 - 53 65 63 75 72 2E 20 50 72 6F 6A 2E 20 4D 67 72 - 2E 11 00 00 46 69 6E 61 6E 7A 2D 53 70 65 7A 69 - 61 6C 69 73 74 16 00 00 47 72 6F 75 70 20 43 6F - 6D 70 65 6E 73 61 74 69 6F 6E 20 4D 67 72 12 00 - 00 43 6F 6E 66 65 72 65 6E 63 65 20 4D 61 6E 61 - 67 65 72 12 00 00 44 65 70 75 74 79 20 48 65 61 - 64 20 6F 66 20 54 41 41 19 00 00 53 65 6E 2E 20 - 56 69 63 65 20 50 72 65 73 69 64 65 6E 74 20 52 - 65 69 6E 2E 0F 00 00 48 65 61 64 20 6F 66 20 52 - 26 52 20 48 55 42 0C 00 00 4D 61 6E 68 61 74 74 - 61 6E 20 4E 59 0A 00 00 48 61 75 73 77 61 72 74 - 69 6E 03 00 00 4C 58 32 14 00 00 42 65 72 65 69 - 63 68 73 70 65 72 73 6F 6E 61 6C 63 68 65 66 06 - 00 00 45 78 74 65 72 6E 19 00 00 48 65 61 64 20 - 6F 66 20 52 65 69 6E 73 2E 4C 69 61 62 69 6C 69 - 74 2E 2C 44 01 00 00 56 02 00 00 4E 4C 18 00 00 - 53 65 6E 69 6F 72 20 43 6C 61 69 6D 73 20 43 6F - 6E 73 75 6C 74 61 6E 74 08 00 00 44 69 72 65 63 - 74 6F 72 07 00 00 42 45 52 4D 55 44 41 0A 00 00 - 53 74 72 75 63 74 75 72 65 72 0A 00 00 4F 70 65 - 72 61 74 69 6F 6E 73 06 00 00 32 30 30 31 30 36 - 02 00 00 42 52 09 00 00 53 61 6F 20 50 61 75 6C - 6F 0A 00 00 30 39 2E 30 35 2E 31 39 37 36 0A 00 - 00 31 34 2E 30 38 2E 31 39 36 37 0A 00 00 30 31 - 2E 30 37 2E 31 39 39 35 0A 00 00 32 35 2E 30 33 - 2E 31 39 37 32 0A 00 00 30 33 2E 30 31 2E 32 30 - 30 30 0A 00 00 32 31 2E 30 34 2E 31 39 37 30 0A - 00 00 30 39 2E 30 35 2E 31 39 36 32 0A 00 00 30 - 32 2E 30 39 2E 31 39 39 36 0A 00 00 31 35 2E 30 - 34 2E 31 39 37 31 0A 00 00 32 37 2E 31 30 2E 31 - 39 39 37 0A 00 00 32 32 2E 31 30 2E 31 39 36 38 - 0A 00 00 32 36 2E 30 35 2E 31 39 39 33 0A 00 00 - 30 32 2E 30 33 2E 31 39 35 38 0A 00 00 30 31 2E - 30 33 2E 31 39 38 34 0A 00 00 31 36 2E 30 35 2E - 31 39 35 36 0A 00 00 32 38 2E 30 38 2E 31 39 36 - 37 0A 00 00 32 30 2E 30 33 2E 31 39 36 32 0A 00 - 00 30 31 2E 30 33 2E 31 39 39 36 0A 00 00 30 35 - 2E 30 32 2E 31 39 36 38 0A 00 00 30 35 2E 31 32 - 2E 31 39 36 38 0A 00 00 31 30 2E 30 34 2E 31 39 - 39 35 0A 00 00 30 34 2E 30 31 2E 31 39 37 33 0A - 00 00 32 39 2E 30 37 2E 31 39 35 39 0A 00 00 32 - 34 2E 30 36 2E 31 39 36 30 0A 00 00 31 32 2E 30 - 33 2E 31 39 36 39 1C 00 00 50 65 72 73 6F 6E 61 - 6C 20 41 73 73 74 2E 20 74 6F 20 43 68 69 65 66 - 20 52 65 70 2E 0A 00 00 31 33 2E 30 38 2E 31 39 - 37 34 0A 00 00 30 31 2E 30 36 2E 32 30 30 30 0A - 00 00 30 33 2E 30 38 2E 31 39 34 39 0A 00 00 30 - 31 2E 30 33 2E 31 39 39 32 0A 00 00 32 36 2E 30 - 31 2E 31 39 36 32 0A 00 00 32 37 2E 30 39 2E 31 - 39 38 34 0A 00 00 30 34 2E 30 33 2E 31 39 35 34 - 03 00 00 4E 2F 41 0A 00 00 32 32 2E 30 33 2E 31 - 39 36 34 0A 00 00 30 31 2E 30 37 2E 31 39 39 39 - 0A 00 00 30 36 2E 30 36 2E 31 39 37 32 0A 00 00 - 32 39 2E 30 39 2E 31 39 35 39 0A 00 00 31 36 2E - 30 31 2E 31 39 39 31 0A 00 00 32 38 2E 31 32 2E - 31 39 36 30 diff --git a/test-data/spreadsheet/BigSSTRecord2CR4 b/test-data/spreadsheet/BigSSTRecord2CR4 deleted file mode 100644 index f8fd5342a..000000000 --- a/test-data/spreadsheet/BigSSTRecord2CR4 +++ /dev/null @@ -1,515 +0,0 @@ - 3C 00 20 20 0A 00 00 32 34 2E 30 36 - 2E 31 39 39 36 0A 00 00 31 36 2E 30 32 2E 31 39 - 35 33 0A 00 00 32 33 2E 30 32 2E 31 39 37 33 0A - 00 00 31 35 2E 30 39 2E 31 39 36 38 0A 00 00 32 - 35 2E 30 38 2E 31 39 39 37 0A 00 00 32 36 2E 30 - 39 2E 31 39 36 30 0A 00 00 30 32 2E 30 31 2E 32 - 30 30 30 0A 00 00 32 33 2E 31 30 2E 31 39 36 39 - 0A 00 00 32 32 2E 30 32 2E 31 39 34 39 0A 00 00 - 30 38 2E 31 32 2E 31 39 36 35 0A 00 00 30 32 2E - 30 38 2E 31 39 39 39 0A 00 00 30 39 2E 30 31 2E - 31 39 37 33 0A 00 00 30 31 2E 30 32 2E 32 30 30 - 30 0A 00 00 30 38 2E 31 32 2E 31 39 35 37 0A 00 - 00 32 33 2E 30 33 2E 31 39 37 33 02 00 00 32 33 - 10 00 00 48 F4 74 65 73 73 65 20 61 63 63 75 65 - 75 69 6C 02 00 00 34 34 0D 00 00 43 6F 6D 6D 75 - 6E 69 63 61 74 69 6F 6E 1B 00 00 52 65 73 70 2E - 73 75 70 70 6F 72 74 20 74 65 63 68 6E 2E 20 49 - 6E 66 6F 72 6D 2E 02 00 00 36 32 1B 00 00 52 65 - 73 70 6F 6E 73 69 62 6C 65 20 22 73 70 65 63 69 - 61 6C 20 6C 69 6E 65 73 22 08 00 00 36 30 33 2D - 32 30 30 33 08 00 00 36 30 33 2D 32 30 30 34 08 - 00 00 36 30 33 2D 32 30 30 35 08 00 00 36 30 33 - 2D 32 30 30 38 08 00 00 36 30 33 2D 32 30 30 39 - 08 00 00 36 30 33 2D 32 30 31 30 02 00 00 50 33 - 14 00 00 55 57 20 50 72 6F 70 65 72 74 79 2F 43 - 61 73 75 61 6C 74 79 03 00 00 54 4E 44 0C 00 00 - 44 65 61 6C 20 4D 61 6E 61 67 65 72 13 00 00 55 - 57 20 53 75 70 70 6F 72 74 20 46 61 6B 20 53 61 - 63 68 02 00 00 53 33 17 00 00 52 2F 49 20 50 72 - 6F 64 75 63 74 20 43 6F 6E 74 72 6F 6C 6C 69 6E - 67 19 00 00 55 6E 64 65 72 77 72 69 74 69 6E 67 - 20 53 75 70 70 2E 20 4D 61 72 69 6E 65 19 00 00 - 48 65 61 64 20 49 6E 74 65 72 6E 2E 20 43 6C 69 - 65 6E 74 73 20 55 6E 69 74 19 00 00 53 65 6E 2E - 46 69 6E 61 6E 63 2E 53 6F 6C 75 74 69 6F 6E 73 - 20 43 6F 6E 73 13 00 00 54 61 63 74 69 63 61 6C - 20 41 6C 6C 6F 63 61 74 69 6F 6E 18 00 00 44 65 - 70 2E 48 65 61 64 20 54 65 63 68 6E 2E 49 6E 66 - 72 61 73 74 72 2E 18 00 00 44 69 76 69 73 69 6F - 6E 61 6C 20 43 6F 6D 6D 2E 20 4F 66 66 69 63 65 - 72 19 00 00 44 65 70 75 74 79 20 48 65 61 64 20 - 42 75 73 2E 20 54 72 61 69 6E 69 6E 67 0F 00 00 - 43 61 73 68 20 4D 61 6E 61 67 65 6D 65 6E 74 18 - 00 00 50 45 4B 41 2F 50 34 30 30 2F 48 52 2D 4D - 49 53 20 41 70 70 6C 69 63 2E 0B 00 00 48 65 61 - 64 20 6F 66 20 4B 4E 43 15 00 00 53 70 65 7A 69 - 61 6C 69 73 74 20 52 56 2D 54 65 63 68 6E 69 6B - 19 00 00 43 6F 72 70 2E 20 49 64 65 6E 74 69 74 - 79 20 53 70 65 63 69 61 6C 69 73 74 14 00 00 48 - 65 61 64 20 43 61 73 68 20 4D 61 6E 61 67 65 6D - 65 6E 74 16 00 00 49 54 20 53 65 63 75 72 69 74 - 79 20 43 6F 6E 73 75 6C 74 61 6E 74 17 00 00 55 - 6E 64 65 72 77 72 69 74 65 72 20 54 72 65 61 74 - 79 20 44 65 73 6B 11 00 00 50 72 6F 6A 65 6B 74 - 2D 41 73 73 69 73 74 65 6E 74 11 00 00 50 6F 72 - 74 61 6C 20 43 6F 6E 73 75 6C 74 61 6E 74 10 00 - 00 53 65 6E 2E 20 55 57 20 50 72 6F 70 65 72 74 - 79 11 00 00 54 65 61 6D 20 53 65 63 72 65 74 61 - 72 79 20 52 42 19 00 00 47 72 70 2E 20 53 65 63 - 75 72 69 74 79 26 53 61 66 65 74 79 20 4D 67 72 - 2E 19 00 00 4A 75 6E 69 6F 72 20 49 6E 76 65 73 - 74 2E 20 43 6F 6E 74 72 6F 6C 6C 65 72 16 00 00 - 65 2D 6D 61 72 6B 65 74 73 20 69 6E 74 65 6C 6C - 69 67 65 6E 63 65 0F 00 00 41 72 63 68 69 76 65 - 20 4D 61 6E 61 67 65 72 19 00 00 41 73 73 69 73 - 74 2E 20 74 6F 20 48 65 61 64 20 4D 61 72 6B 65 - 74 69 6E 67 06 00 00 4B F6 63 68 69 6E 18 00 00 - 41 73 73 69 73 74 61 6E 74 20 74 6F 20 48 65 61 - 64 20 47 72 70 20 50 4D 14 00 00 48 6F 74 65 6C - 66 61 63 68 61 73 73 69 73 74 65 6E 74 69 6E 19 - 00 00 48 65 61 64 20 42 65 73 74 20 50 72 61 63 - 74 69 63 65 26 41 75 64 69 74 73 18 00 00 4B 6F - 6D 6D 75 6E 69 6B 61 74 69 6F 6E 73 73 70 65 7A - 69 61 6C 69 73 74 18 00 00 53 65 6E 2E 20 49 6E - 76 65 73 74 6D 2E 20 43 6F 6E 74 72 6F 6C 6C 65 - 72 0A 00 00 50 4D 4F 20 45 75 72 6F 70 65 17 00 - 00 53 70 65 63 69 61 6C 20 50 72 6F 6A 65 63 74 - 20 4D 61 6E 61 67 65 72 18 00 00 53 65 6E 69 6F - 72 20 46 69 6E 61 6E 63 69 61 6C 20 4F 66 66 69 - 63 65 72 15 00 00 49 6E 76 65 73 74 6D 65 6E 74 - 20 41 63 63 6F 75 6E 74 69 6E 67 19 00 00 48 65 - 61 64 20 6F 66 20 42 75 73 69 6E 65 73 73 20 54 - 72 61 69 6E 69 6E 67 14 00 00 41 73 73 2E 20 41 - 63 63 6F 75 6E 74 20 4D 61 6E 61 67 65 72 02 00 - 00 44 42 17 00 00 4C 65 69 74 65 72 69 6E 20 45 - 72 77 65 72 62 20 2F 20 52 65 63 68 74 18 00 00 - 44 65 70 2E 20 47 72 6F 75 70 20 43 6C 61 69 6D - 73 20 43 6F 6F 72 64 2E 17 00 00 4D 61 6E 61 67 - 65 72 20 53 79 73 74 65 6D 20 53 65 72 76 69 63 - 65 73 16 00 00 4D 65 6D 62 65 72 20 42 55 53 20 - 50 65 72 66 6F 72 6D 61 6E 63 65 14 00 00 49 6E - 76 65 73 74 6D 65 6E 74 20 52 65 70 6F 72 74 69 - 6E 67 19 00 00 53 65 6E 2E 20 49 54 20 53 65 63 - 75 72 69 74 79 20 43 6F 6E 73 75 6C 74 2E 17 00 - 00 53 61 63 68 62 65 61 72 62 2E 20 45 72 77 65 - 72 62 26 52 65 63 68 74 19 00 00 53 65 6E 2E 20 - 41 63 63 6F 75 6E 74 61 6E 74 2F 43 6F 6E 74 72 - 6F 6C 6C 2E 10 00 00 43 6F 6D 6D 2E 20 43 6F 6E - 73 75 6C 74 61 6E 74 17 00 00 4C 69 65 67 65 6E - 73 63 68 61 66 74 65 6E 76 65 72 77 61 6C 74 65 - 72 10 00 00 41 64 6D 69 6E 2E 20 50 72 75 64 65 - 6E 74 69 61 02 00 00 47 50 0B 00 00 43 75 72 61 - 74 6F 72 73 68 69 70 19 00 00 48 65 61 64 20 6F - 66 20 57 6F 72 6B 73 74 2E 20 49 6E 66 72 61 73 - 74 72 2E 18 00 00 4D 67 72 2E 20 44 61 74 61 20 - 43 61 70 74 2E 26 54 61 78 6F 6E 6F 6D 79 19 00 - 00 54 65 61 6D 6C 65 69 74 65 72 20 54 65 63 68 - 6E 2E 20 53 75 70 70 6F 72 74 19 00 00 48 65 61 - 64 20 53 52 20 54 65 63 68 6E 6F 6C 6F 67 79 20 - 53 74 61 6E 64 2E 12 00 00 43 6F 6D 6D 2E 20 41 - 73 73 2E 20 52 FC 73 63 68 6C 2E 0D 00 00 4C 6F - 63 61 6C 20 4F 66 66 69 63 65 72 06 00 00 4C 54 - 50 52 20 44 12 00 00 53 74 76 2E 20 47 72 75 70 - 70 65 6E 6C 65 69 74 65 72 06 00 00 4C 54 50 52 - 20 45 06 00 00 4C 54 50 52 20 47 06 00 00 4C 54 - 50 52 20 49 06 00 00 4C 54 50 52 20 46 06 00 00 - 4C 54 50 52 20 41 09 00 00 52 65 70 6F 72 74 69 - 6E 67 19 00 00 47 72 6F 75 70 20 49 54 20 53 65 - 63 75 72 69 74 79 20 4F 66 66 69 63 65 72 06 00 - 00 4C 54 50 52 20 48 18 00 00 4C 65 69 74 65 72 - 20 48 79 70 6F 74 68 65 6B 65 6E 2F 41 64 6D 69 - 6E 2E 06 00 00 4C 54 50 52 20 43 19 00 00 53 61 - 63 68 62 65 61 72 62 65 69 74 65 72 69 6E 20 48 - 79 70 6F 74 68 65 6B 11 00 00 41 73 73 69 73 74 - 61 6E 74 20 43 4C 4F 2F 43 43 4F 18 00 00 50 72 - 6F 6A 2E 20 4D 61 6E 61 67 65 72 20 53 70 6F 6E - 73 6F 72 69 6E 67 0A 00 00 4C 65 69 74 65 72 20 - 42 61 75 11 00 00 48 65 61 64 20 6F 66 20 54 65 - 6C 65 70 68 6F 6E 79 18 00 00 53 65 6E 69 6F 72 - 20 49 6E 66 6F 72 6D 61 74 69 6F 6E 20 53 70 65 - 63 2E 18 00 00 41 73 73 2E 20 54 61 63 74 69 63 - 61 6C 20 41 6C 6C 6F 63 61 74 69 6F 6E 12 00 00 - 50 72 6F 6A 65 63 74 20 4D 61 6E 61 67 65 6D 65 - 6E 74 19 00 00 48 65 61 64 20 49 6E 76 2E 46 75 - 6E 64 73 2F 4F 70 65 72 61 74 69 6F 6E 73 18 00 - 00 46 69 6E 61 6E 63 2E 20 4F 66 66 2E 20 73 77 - 69 66 74 72 65 2E 63 6F 6D 19 00 00 4C 65 61 72 - 6E 69 6E 67 43 6F 6F 72 64 69 6E 61 74 6F 72 20 - 5A 4F 52 52 4F 17 00 00 48 65 61 64 20 43 4D 53 - 20 43 6C 65 61 72 69 6E 67 20 48 6F 75 73 65 18 - 00 00 45 6E 67 69 6E 65 65 72 69 6E 67 20 55 57 - 20 41 73 73 69 73 74 61 6E 74 15 00 00 50 72 6F - 70 65 72 74 79 20 50 72 6F 64 75 63 74 20 4D 67 - 72 2E 06 00 00 4C 54 50 52 20 42 0E 00 00 48 65 - 61 64 20 50 72 75 64 65 6E 74 69 61 02 00 00 44 - 57 19 00 00 48 65 61 64 20 44 61 74 61 20 57 61 - 72 65 68 6F 75 73 65 20 53 65 72 76 2E 02 00 00 - 47 45 19 00 00 48 65 61 64 20 43 6F 6E 74 72 6F - 6C 6C 69 6E 67 20 50 72 6F 6A 65 63 74 73 16 00 - 00 50 6F 72 74 61 6C 20 43 6F 6E 74 65 6E 74 20 - 4D 61 6E 61 67 65 72 02 00 00 20 35 02 00 00 20 - 34 25 00 00 41 73 73 69 73 74 61 6E 74 65 20 64 - E9 70 61 72 74 65 6D 65 6E 74 20 74 72 61 69 74 - E9 20 6E 6F 6E 20 76 69 65 03 00 00 43 34 32 03 - 00 00 43 34 33 03 00 00 43 34 34 03 00 00 43 34 - 35 03 00 00 43 34 36 0D 00 00 52 75 6E 4F 66 66 - 20 52 65 61 63 6F 6C 03 00 00 43 34 37 03 00 00 - 43 34 38 03 00 00 43 34 39 03 00 00 43 35 30 12 - 00 00 43 6C 61 69 6D 73 20 4D 61 6E 61 67 65 72 - 20 53 45 41 0F 00 00 50 72 6F 63 65 73 73 20 41 - 6E 61 6C 79 73 74 0B 00 00 54 65 61 6D 20 4C 65 - 61 64 65 72 18 00 00 43 61 73 75 61 6C 74 79 20 - 4C 69 61 69 73 6F 6E 20 4D 61 6E 61 67 65 72 17 - 00 00 48 75 6D 61 6E 20 52 65 73 6F 75 72 63 65 - 73 20 4F 66 66 69 63 65 72 0F 00 00 46 61 63 20 - 55 6E 64 65 72 77 72 69 74 65 72 13 00 00 48 65 - 61 64 20 4F 70 65 72 61 74 69 6F 6E 73 20 53 53 - 43 1A 00 00 43 61 73 75 61 6C 74 79 20 54 72 65 - 61 74 79 20 55 57 20 4D 61 6E 61 67 65 72 0A 00 - 00 4D 61 6E 61 67 65 72 2D 49 54 1F 00 00 46 61 - 63 75 6C 74 61 74 69 76 65 20 55 57 20 53 75 70 - 70 6F 72 74 20 43 61 73 75 61 6C 74 79 1B 00 00 - 48 65 61 64 20 4C 65 61 72 6E 69 6E 67 20 26 20 - 44 65 76 65 6C 6F 70 6D 65 6E 74 22 00 00 48 65 - 61 64 20 6F 66 20 46 61 63 20 50 72 6F 70 65 72 - 74 79 20 26 20 45 6E 67 69 6E 65 65 72 69 6E 67 - 12 00 00 41 63 63 6F 75 6E 74 69 6E 67 20 4D 61 - 6E 61 67 65 72 05 00 00 37 30 32 34 31 29 00 00 - 48 65 61 64 20 6F 66 20 41 6D 65 72 69 63 61 73 - 20 44 69 76 69 73 69 6F 6E 20 48 75 6D 61 6E 20 - 52 65 73 6F 75 72 63 65 73 02 00 00 30 39 05 00 - 00 38 30 33 38 33 07 00 00 41 6E 61 6C 79 73 74 - 03 00 00 31 31 30 05 00 00 33 32 34 35 31 1E 00 - 00 47 72 6F 75 70 20 50 72 6F 64 75 63 74 20 4D - 61 6E 61 67 65 72 20 43 61 73 75 61 6C 74 79 02 - 00 00 30 31 05 00 00 38 31 34 38 39 13 00 00 46 - 69 6E 61 6E 63 69 61 6C 20 41 6E 61 6C 79 73 74 - 20 31 03 00 00 31 32 30 05 00 00 38 30 35 30 30 - 09 00 00 50 72 69 6E 63 69 70 61 6C 02 00 00 30 - 34 18 00 00 48 65 61 64 20 49 6E 76 65 73 74 6D - 65 6E 74 20 41 63 63 6F 75 6E 74 2E 14 00 00 50 - 6F 72 74 66 6F 6C 69 6F 20 4D 61 6E 61 67 65 6D - 65 6E 74 19 00 00 41 73 73 2E 49 6E 76 65 73 74 - 6F 72 20 52 65 6C 61 74 69 6F 6E 20 4D 67 72 19 - 00 00 45 6C 65 63 74 72 6F 6E 69 63 20 52 69 73 - 6B 20 45 78 63 68 61 6E 67 65 73 09 00 00 54 4C - 20 42 75 66 66 65 74 14 00 00 4C 65 61 72 6E 69 - 6E 67 20 43 6F 6F 72 64 69 6E 61 74 6F 72 18 00 - 00 54 65 63 68 6E 69 63 61 6C 20 49 6E 66 72 61 - 73 74 72 75 63 74 75 72 65 19 00 00 48 65 61 64 - 20 54 65 63 68 6E 2E 49 6E 66 72 61 73 74 72 75 - 63 74 75 72 65 19 00 00 49 55 46 20 43 6F 6D 6D - 75 6E 69 63 61 74 69 6F 6E 20 4D 61 6E 61 67 65 - 72 12 00 00 43 46 4F 20 42 75 73 69 6E 65 73 73 - 20 47 72 6F 75 70 16 00 00 54 4C 20 45 69 6E 72 - 69 63 68 74 75 6E 67 73 70 6C 61 6E 75 6E 67 15 - 00 00 49 6E 76 65 73 74 6D 65 6E 74 20 43 6F 6E - 74 72 6F 6C 6C 65 72 18 00 00 48 65 61 64 20 6F - 66 20 4C 69 62 72 61 72 79 20 53 65 72 76 69 63 - 65 73 0C 00 00 52 69 73 6B 20 4D 61 6E 61 67 65 - 72 19 00 00 46 75 6E 63 74 69 6F 6E 61 6C 20 44 - 65 73 69 67 6E 20 41 6E 61 6C 79 73 74 16 00 00 - 41 73 73 69 73 74 61 6E 74 20 52 69 73 6B 20 4D - 61 6E 61 67 65 72 04 00 00 36 38 38 30 13 00 00 - 53 61 63 68 62 65 61 72 62 65 69 74 65 72 20 46 - 69 62 75 04 00 00 36 38 38 37 08 00 00 45 6E 67 - 69 6E 65 65 72 04 00 00 36 38 39 32 04 00 00 36 - 38 39 36 04 00 00 36 39 30 39 0C 00 00 50 72 69 - 63 69 6E 67 2F 44 61 74 61 04 00 00 36 39 31 31 - 0E 00 00 43 41 44 2D 53 70 65 7A 69 61 6C 69 73 - 74 04 00 00 36 39 31 34 04 00 00 36 39 32 33 17 - 00 00 47 72 6C 2E 20 42 65 74 72 69 65 62 20 4D - 79 74 68 65 6E 71 75 61 69 04 00 00 36 39 32 38 - 0D 00 00 48 65 61 64 20 6F 66 20 4C 45 2F 4C 54 - 04 00 00 36 39 33 35 04 00 00 36 39 33 39 14 00 - 00 54 65 63 68 6E 69 73 63 68 65 72 20 5A 65 69 - 63 68 6E 65 72 04 00 00 36 39 34 33 04 00 00 36 - 39 35 36 13 00 00 46 61 63 68 72 65 66 65 72 65 - 6E 74 20 55 6D 77 65 6C 74 04 00 00 36 39 35 37 - 04 00 00 36 39 36 36 18 00 00 42 65 61 75 66 74 - 72 61 67 74 65 20 4A 75 6E 69 6F 72 20 50 6F 77 - 65 72 04 00 00 36 39 37 31 04 00 00 36 39 39 34 - 04 00 00 37 30 30 33 04 00 00 37 30 30 37 17 00 - 00 48 65 61 64 20 43 6F 72 70 6F 72 61 74 65 20 - 44 65 76 65 6C 6F 70 2E 04 00 00 37 30 30 38 14 - 00 00 4C 65 69 74 65 6E 64 65 72 20 4B FC 63 68 - 65 6E 63 68 65 66 04 00 00 37 30 30 39 17 00 00 - 54 4C 20 45 6C 65 6B 74 72 6F 20 26 20 47 65 62 - 2E 74 65 63 68 6E 2E 04 00 00 37 30 31 31 0F 00 - 00 53 74 76 2E 20 4B FC 63 68 65 6E 63 68 65 66 - 04 00 00 37 30 31 34 04 00 00 37 30 32 33 04 00 - 00 37 30 32 34 04 00 00 37 30 32 37 04 00 00 37 - 30 35 31 18 00 00 53 65 6E 2E 20 43 72 65 64 69 - 74 20 52 69 73 6B 20 4D 61 6E 61 67 65 72 04 00 - 00 37 30 35 32 04 00 00 37 30 35 37 12 00 00 50 - 72 6F 6A 65 63 74 20 53 70 65 63 69 61 6C 69 73 - 74 04 00 00 37 30 36 32 04 00 00 37 30 36 36 18 - 00 00 48 65 61 64 20 6F 66 20 4D 65 64 69 63 61 - 6C 20 53 65 72 76 69 63 65 73 04 00 00 37 30 36 - 39 04 00 00 37 30 38 33 04 00 00 37 30 38 34 0A - 00 00 43 49 2D 4D 61 6E 61 67 65 72 04 00 00 37 - 30 38 36 13 00 00 47 72 6F 75 70 20 48 52 20 43 - 6F 6E 74 72 6F 6C 6C 65 72 04 00 00 37 30 39 31 - 04 00 00 37 30 39 32 15 00 00 47 72 6C 2E 20 53 - 70 65 63 69 61 6C 20 42 75 73 69 6E 65 73 73 04 - 00 00 37 30 39 33 04 00 00 37 30 39 35 04 00 00 - 37 30 39 37 18 00 00 42 75 73 69 6E 65 73 73 20 - 41 70 70 6C 2E 20 41 72 63 68 69 74 65 63 74 04 - 00 00 37 31 30 30 04 00 00 37 31 30 32 12 00 00 - 4D 61 6E 61 67 65 6D 65 6E 74 20 53 75 70 70 6F - 72 74 04 00 00 37 31 32 30 04 00 00 37 31 32 35 - 04 00 00 37 31 32 38 04 00 00 37 31 32 39 04 00 - 00 37 31 33 33 04 00 00 37 31 34 30 04 00 00 37 - 31 34 33 08 00 00 41 6B 74 75 61 72 69 6E 04 00 - 00 37 31 35 31 04 00 00 37 31 35 37 16 00 00 41 - 73 73 69 73 74 61 6E 74 20 74 6F 20 55 6E 69 74 - 20 48 65 61 64 04 00 00 37 31 36 30 04 00 00 37 - 31 36 36 10 00 00 53 65 63 72 65 74 61 72 79 20 - 74 6F 20 44 4F 4F 04 00 00 37 31 37 36 04 00 00 - 37 31 38 30 15 00 00 47 72 75 70 70 65 6E 6C 65 - 69 74 65 72 20 53 75 70 70 6F 72 74 04 00 00 37 - 31 38 31 18 00 00 48 65 61 64 20 6F 66 20 48 6F - 74 65 6C 20 4F 70 65 72 61 74 69 6F 6E 73 04 00 - 00 37 31 38 32 02 00 00 55 53 08 00 00 4E 65 77 - 20 59 6F 72 6B 04 00 00 37 32 31 30 04 00 00 37 - 32 31 33 04 00 00 37 32 36 37 04 00 00 37 32 37 - 33 19 00 00 53 65 63 74 69 6F 6E 20 48 65 61 64 - 20 53 70 65 63 69 61 6C 20 41 73 73 2E 04 00 00 - 37 32 38 30 19 00 00 48 65 61 64 20 53 74 72 61 - 74 2E 20 50 6C 61 6E 6E 2E 26 20 50 72 6F 6A 2E - 04 00 00 37 32 38 34 04 00 00 37 33 31 38 04 00 - 00 37 33 31 39 04 00 00 37 33 32 32 04 00 00 37 - 33 32 33 04 00 00 37 33 33 31 04 00 00 37 33 33 - 34 03 00 00 47 49 41 04 00 00 37 33 33 38 19 00 - 00 47 49 41 20 4F 66 66 69 63 65 26 43 6F 6D 6D - 75 6E 69 63 61 74 69 6F 6E 73 04 00 00 37 33 33 - 39 0B 00 00 4F 72 67 61 6E 69 73 61 74 6F 72 04 - 00 00 37 33 34 31 06 00 00 41 6B 74 75 61 72 04 - 00 00 37 33 34 35 04 00 00 37 33 34 39 04 00 00 - 37 33 36 30 04 00 00 37 33 36 31 04 00 00 37 33 - 36 32 04 00 00 37 33 36 33 04 00 00 37 33 36 37 - 04 00 00 37 33 37 37 04 00 00 37 33 37 38 15 00 - 00 41 75 73 62 69 6C 64 75 6E 67 73 73 61 63 68 - 62 65 61 72 62 2E 04 00 00 37 33 39 30 04 00 00 - 37 33 39 32 04 00 00 37 34 32 30 04 00 00 37 34 - 33 35 04 00 00 37 34 34 32 04 00 00 37 34 35 35 - 11 00 00 54 4C 20 45 6C 65 6B 74 72 6F 74 65 63 - 68 6E 69 6B 04 00 00 37 34 36 30 04 00 00 37 34 - 36 31 04 00 00 37 34 37 39 04 00 00 37 34 39 32 - 04 00 00 37 34 39 35 04 00 00 37 34 39 36 17 00 - 00 55 65 62 65 72 73 65 74 7A 2E 2F 54 65 72 6D - 69 6E 6F 6C 6F 67 69 6E 04 00 00 37 35 30 30 0D - 00 00 4C 65 67 61 6C 20 43 6F 75 6E 73 65 6C 04 - 00 00 37 35 30 33 04 00 00 37 35 31 30 13 00 00 - 53 61 63 68 62 65 61 72 62 2E 20 47 72 6F 75 70 - 20 50 4D 02 00 00 43 55 04 00 00 37 35 33 39 11 - 00 00 54 61 74 65 6E 20 73 74 61 74 74 20 57 6F - 72 74 65 04 00 00 37 35 34 32 14 00 00 53 65 6E - 69 6F 72 20 41 75 64 69 74 20 4D 61 6E 61 67 65 - 72 04 00 00 37 35 34 37 04 00 00 37 35 34 39 04 - 00 00 37 35 35 38 04 00 00 37 35 36 32 12 00 00 - 50 72 6F 6A 65 63 74 20 43 6F 6E 73 75 6C 74 61 - 6E 74 04 00 00 37 35 36 35 0C 00 00 43 6F 6D 6D - 69 73 2D 4B FC 63 68 65 04 00 00 37 35 36 38 04 - 00 00 37 35 37 31 04 00 00 37 35 37 33 13 00 00 - 53 61 63 68 62 65 61 72 62 65 69 74 65 72 20 42 - 65 62 75 04 00 00 37 35 37 34 19 00 00 53 61 63 - 68 62 65 61 72 62 2E 20 52 65 63 68 6E 75 6E 67 - 73 77 65 73 65 6E 04 00 00 37 35 37 37 04 00 00 - 37 35 38 31 13 00 00 48 65 61 64 20 6F 66 20 4C - 41 2F 4C 45 2F 4C 4E 20 46 4D 04 00 00 37 35 39 - 32 04 00 00 37 35 39 33 04 00 00 37 35 39 39 04 - 00 00 37 36 30 31 04 00 00 37 36 32 31 04 00 00 - 37 36 32 36 04 00 00 37 36 32 39 11 00 00 41 63 - 74 75 61 72 69 61 6C 20 41 6E 61 6C 79 73 74 04 - 00 00 37 36 34 31 04 00 00 37 36 34 37 04 00 00 - 37 36 34 38 09 00 00 45 63 6F 6E 6F 6D 69 73 74 - 04 00 00 37 36 34 39 04 00 00 37 36 35 30 04 00 - 00 37 36 35 32 0E 00 00 50 72 6F 6A 65 6B 74 6D - 61 6E 61 67 65 72 04 00 00 37 36 35 39 04 00 00 - 37 36 36 30 12 00 00 4B 6F 6E 7A 65 72 6E 6B 6F - 6F 72 64 69 6E 61 74 6F 72 04 00 00 37 36 36 31 - 04 00 00 37 36 36 33 04 00 00 37 36 38 31 04 00 - 00 37 36 38 36 04 00 00 37 36 38 38 04 00 00 37 - 36 39 30 04 00 00 37 36 39 32 04 00 00 37 36 39 - 37 04 00 00 37 37 30 38 18 00 00 4D 65 6D 62 65 - 72 20 6F 66 20 45 78 65 63 75 74 69 76 65 20 54 - 65 61 6D 04 00 00 37 37 31 33 0E 00 00 49 6E 6E - 65 6E 61 72 63 68 69 74 65 6B 74 04 00 00 37 37 - 32 33 0E 00 00 53 65 6E 69 6F 72 20 41 63 74 75 - 61 72 79 04 00 00 37 37 33 31 04 00 00 37 37 34 - 35 04 00 00 37 37 35 33 04 00 00 37 37 35 36 04 - 00 00 37 37 37 37 04 00 00 37 37 37 38 04 00 00 - 37 37 38 33 04 00 00 37 37 38 37 12 00 00 48 65 - 61 64 20 6F 66 20 44 65 70 61 72 74 6D 65 6E 74 - 04 00 00 37 37 38 39 04 00 00 37 37 39 38 04 00 - 00 37 38 31 38 04 00 00 37 38 33 35 04 00 00 37 - 38 33 36 04 00 00 37 38 37 30 04 00 00 37 38 37 - 32 1A 00 00 54 4C 20 4D 61 72 69 6E 65 20 55 57 - 20 47 72 65 61 74 65 72 20 43 68 69 6E 61 03 00 - 00 32 30 39 12 00 00 50 65 72 73 6F 6E 61 6C 20 - 41 73 73 69 73 74 61 6E 74 03 00 00 32 31 30 18 - 00 00 48 65 61 64 20 4D 67 6D 74 26 20 46 69 6E - 2E 20 53 65 72 76 69 63 65 73 04 00 00 38 35 33 - 37 13 00 00 44 61 74 61 20 49 54 2D 4B 6F 6F 72 - 64 69 6E 61 74 6F 72 03 00 00 34 39 38 05 00 00 - 31 30 35 32 33 05 00 00 31 30 31 36 34 04 00 00 - 38 36 33 31 03 00 00 32 34 34 03 00 00 32 34 35 - 04 00 00 38 36 30 34 04 00 00 36 35 36 39 10 00 - 00 50 72 69 63 69 70 61 6C 20 4F 66 66 69 63 65 - 72 04 00 00 38 36 30 31 05 00 00 31 30 34 32 39 - 03 00 00 31 32 34 04 00 00 35 38 36 32 05 00 00 - 31 31 30 32 37 03 00 00 35 36 32 03 00 00 35 30 - 32 04 00 00 33 39 33 32 04 00 00 38 39 32 39 14 - 00 00 48 65 61 64 20 48 75 6D 61 6E 20 52 65 73 - 6F 75 72 63 65 73 05 00 00 31 31 38 33 33 04 00 - 00 35 31 36 38 04 00 00 38 35 37 37 04 00 00 38 - 36 37 33 03 00 00 33 33 38 03 00 00 33 33 37 14 - 00 00 53 65 6E 69 6F 72 20 41 64 6D 69 6E 69 73 - 74 72 61 74 6F 72 04 00 00 38 36 38 33 03 00 00 - 32 34 37 1C 00 00 4D 61 6E 61 67 65 72 20 4E 6F - 6E 2D 4C 69 66 65 20 52 65 69 6E 73 75 72 61 6E - 63 65 04 00 00 37 30 32 30 04 00 00 33 38 36 34 - 03 00 00 33 38 38 1A 00 00 48 65 61 64 20 6F 66 - 20 46 69 6E 61 6E 63 69 61 6C 20 41 64 76 69 73 - 6F 72 79 03 00 00 32 31 32 1D 00 00 41 73 73 74 - 2E 20 74 6F 20 43 68 69 65 66 20 52 65 70 72 65 - 73 65 6E 74 61 74 69 76 65 05 00 00 31 30 30 37 - 39 03 00 00 32 31 39 1A 00 00 43 6F 6E 74 72 6F - 6C 6C 65 72 2C 20 52 65 69 6E 73 2E 41 63 63 6F - 75 6E 74 73 03 00 00 33 36 36 03 00 00 31 33 35 - 03 00 00 35 33 39 03 00 00 35 30 39 1D 00 00 48 - 65 61 64 20 6F 66 20 43 6F 72 70 6F 72 61 74 65 - 20 44 65 76 65 6C 6F 70 6D 65 6E 74 03 00 00 31 - 34 35 17 00 00 52 65 70 72 65 73 65 6E 74 61 74 - 69 76 65 20 50 72 6F 70 65 72 74 79 03 00 00 35 - 32 32 0E 00 00 4D 61 72 69 6E 65 20 4D 61 6E 61 - 67 65 72 03 00 00 35 32 31 04 00 00 33 37 35 38 - 04 00 00 36 39 37 36 04 00 00 36 31 35 30 04 00 - 00 39 31 35 34 19 00 00 48 65 61 64 20 52 65 69 - 6E 73 75 72 61 6E 63 65 20 41 63 63 6F 75 6E 74 - 2E 02 00 00 45 53 02 00 00 53 4F 04 00 00 32 39 - 33 34 10 00 00 55 6E 64 65 72 77 72 69 74 65 72 - 20 53 6F 52 69 02 00 00 45 59 04 00 00 32 39 36 - 37 12 00 00 41 64 6D 69 6E 69 73 74 72 61 74 69 - 6F 6E 20 53 53 43 02 00 00 45 50 02 00 00 50 31 - 04 00 00 32 39 38 36 18 00 00 55 57 20 53 75 70 - 70 6F 72 74 20 46 61 63 2E 20 50 72 6F 70 65 72 - 74 79 04 00 00 33 30 35 35 0D 00 00 53 65 63 72 - 65 74 61 72 79 20 53 53 43 04 00 00 33 30 38 31 - 02 00 00 43 33 04 00 00 33 31 30 32 04 00 00 33 - 31 30 33 04 00 00 33 31 30 37 02 00 00 45 4F 04 - 00 00 33 31 31 31 04 00 00 33 31 31 32 02 00 00 - 45 45 04 00 00 33 31 31 36 18 00 00 48 65 61 64 - 20 41 70 70 6C 69 63 61 74 69 6F 6E 20 53 75 70 - 70 6F 72 74 02 00 00 45 44 04 00 00 33 31 31 37 - 04 00 00 33 31 33 31 13 00 00 42 75 73 69 6E 65 - 73 73 20 45 78 70 65 72 74 20 53 53 43 04 00 00 - 33 31 33 33 02 00 00 53 31 04 00 00 33 31 34 34 - 11 00 00 55 6E 64 65 72 77 72 69 74 65 72 20 53 - 57 49 46 54 02 00 00 45 47 04 00 00 33 31 34 38 - 11 00 00 46 69 6E 61 6E 63 69 61 6C 20 41 6E 61 - 6C 79 73 74 04 00 00 38 32 34 30 10 00 00 4C 65 - 67 61 6C 20 43 6F 6E 73 75 6C 74 61 6E 74 04 00 - 00 38 32 34 38 04 00 00 38 32 35 32 04 00 00 38 - 32 35 35 04 00 00 38 32 36 30 04 00 00 38 32 36 - 39 18 00 00 41 73 73 2E 20 53 74 61 62 73 73 74 - 2E 20 53 69 63 68 65 72 68 65 69 74 04 00 00 38 - 32 37 32 04 00 00 38 32 37 35 04 00 00 38 32 37 - 39 16 00 00 46 FC 68 72 75 6E 67 73 61 73 73 69 - 73 74 65 6E 74 69 6E 20 43 43 04 00 00 38 32 38 - 36 19 00 00 53 65 6B 72 65 74 61 72 69 61 74 73 - 6D 69 74 61 72 62 65 69 74 65 72 49 6E 04 00 00 - 38 33 30 38 04 00 00 38 33 33 30 04 00 00 38 33 - 33 35 04 00 00 38 33 33 39 04 00 00 38 33 34 34 - 17 00 00 48 65 61 64 20 6F 66 20 41 63 74 75 61 - 72 69 61 6C 20 50 72 6F 6A 2E 04 00 00 38 33 35 - 34 04 00 00 38 33 35 37 04 00 00 38 33 37 38 04 - 00 00 38 33 38 34 04 00 00 38 33 38 36 04 00 00 - 38 33 38 37 04 00 00 38 33 38 38 04 00 00 38 33 - 39 30 04 00 00 38 34 30 32 04 00 00 38 34 30 35 - 10 00 00 4B 6F 6F 72 64 69 6E 61 74 69 6F 6E 20 - 54 43 45 04 00 00 38 34 30 38 11 00 00 53 65 6E - 69 6F 72 20 41 63 63 6F 75 6E 74 61 6E 74 04 00 - 00 38 34 30 39 15 00 00 41 63 74 75 61 72 69 61 - 6C 20 44 65 76 65 6C 6F 70 6D 65 6E 74 04 00 00 - 38 34 31 37 04 00 00 38 34 32 32 04 00 00 38 34 - 32 35 04 00 00 38 34 32 36 14 00 00 4C 65 69 74 - 65 72 69 6E 20 53 65 6B 72 65 74 61 72 69 61 74 - 04 00 00 38 34 32 38 04 00 00 38 34 33 32 04 00 - 00 38 34 33 36 04 00 00 38 34 33 38 04 00 00 38 - 34 33 39 04 00 00 38 34 34 34 04 00 00 38 34 35 - 30 04 00 00 38 34 35 32 04 00 00 38 34 36 39 04 - 00 00 38 34 37 30 04 00 00 38 34 37 33 04 00 00 - 38 34 37 37 05 00 00 31 31 30 33 37 05 00 00 31 - 31 33 33 33 05 00 00 31 31 36 35 32 05 00 00 31 - 31 36 39 38 05 00 00 31 31 38 36 39 05 00 00 31 - 31 39 36 30 05 00 00 31 31 39 36 34 05 00 00 31 - 31 39 37 34 05 00 00 31 32 30 31 37 05 00 00 31 - 32 30 35 33 05 00 00 31 32 31 38 32 05 00 00 31 - 32 32 39 36 05 00 00 31 32 33 30 30 05 00 00 31 - 32 33 31 32 05 00 00 31 32 36 34 33 05 00 00 31 - 32 36 37 37 05 00 00 31 32 36 38 34 05 00 00 31 - 32 37 32 34 05 00 00 31 32 37 37 38 05 00 00 31 - 32 38 34 37 05 00 00 31 32 38 38 30 05 00 00 31 - 32 39 36 32 05 00 00 31 32 39 37 39 05 00 00 31 - 33 30 30 31 05 00 00 31 33 30 32 34 05 00 00 31 - 33 30 36 33 05 00 00 31 33 30 37 39 05 00 00 31 - 33 31 34 30 05 00 00 31 33 31 34 34 05 00 00 31 - 33 31 34 35 04 00 00 33 37 39 32 04 00 00 35 34 - 35 35 14 00 00 50 72 6F 64 75 63 74 20 4D 61 6E - 61 67 65 72 20 53 61 63 68 04 00 00 35 35 38 36 - 04 00 00 35 36 36 39 04 00 00 37 34 37 38 03 00 - 00 31 30 30 0F 00 00 46 65 6D 6D 65 20 64 65 20 - 6D E9 6E 61 67 65 02 00 00 31 31 13 00 00 47 65 - 73 74 69 6F 6E 20 69 6E 66 6F 72 6D 61 74 69 6F - 6E 02 00 00 31 34 0C 00 00 44 69 72 65 63 74 65 - 75 72 20 52 48 02 00 00 31 35 12 00 00 73 6F 75 - 73 63 2E 46 61 63 20 64 6F 6D 6D 61 67 65 73 02 - 00 00 31 38 14 00 00 44 E9 6C E9 67 75 E9 20 73 - 6F 75 73 63 72 69 70 74 69 6F 6E 02 00 00 32 32 - 0F 00 00 48 F4 74 65 73 73 65 20 61 63 63 65 75 - 69 6C 0A 00 00 73 65 63 72 E9 74 61 69 72 65 02 - 00 00 32 38 02 00 00 32 39 16 00 00 67 65 73 74 - 69 6F 6E 6E 61 69 72 65 20 63 6F 6D 70 74 61 62 - 6C 65 01 00 00 33 20 00 00 52 65 73 70 6F 6E 73 - 69 62 6C 65 20 67 65 73 74 69 6F 6E 20 64 75 20 - 70 65 72 73 6F 6E 6E 65 6C 02 00 00 33 30 16 00 - 00 47 65 73 74 69 6F 6E 6E 61 69 72 65 20 63 6F - 6D 70 74 61 62 6C 65 1E 00 00 52 65 73 70 6F 6E - 73 69 62 6C 65 20 72 69 73 71 75 65 73 20 74 65 - 63 68 6E 69 71 75 65 73 02 00 00 33 34 09 00 00 - 43 6F 6D 70 74 61 62 6C 65 02 00 00 33 36 02 00 - 00 33 38 1D 00 00 52 65 73 70 2E 73 6F 75 73 63 - 2E 72 69 73 71 75 65 73 20 74 65 63 68 6E 69 71 - 75 65 73 02 00 00 33 39 17 00 00 54 65 63 68 6E - 2E 73 65 72 76 69 63 65 73 20 67 E9 6E E9 72 61 - 75 78 17 00 00 52 65 73 70 6F 6E 73 69 62 6C 65 - 20 42 61 63 6B 20 6F 66 66 69 63 65 17 00 00 52 - 65 73 70 6F 6E 73 69 62 6C 65 20 62 75 72 65 61 - 75 74 69 71 75 65 02 00 00 34 33 02 00 00 34 37 - 16 00 00 41 73 73 69 73 74 61 6E 74 65 20 64 65 - 20 73 65 63 74 69 6F 6E 73 19 00 00 41 6E 61 6C - 79 73 74 65 20 72 E9 67 6C 65 75 72 20 73 69 6E - 73 69 74 72 65 02 00 00 35 33 02 00 00 35 34 02 - 00 00 35 39 17 00 00 53 65 63 72 E9 74 61 69 72 - 65 20 64 65 20 44 69 72 65 63 74 69 6F 6E 01 00 - 00 36 17 00 00 52 65 73 70 2E 53 69 6E 69 73 74 - 72 65 20 6A 75 72 69 64 69 71 75 65 02 00 00 36 - 33 02 00 00 36 38 15 00 00 53 6F 75 73 63 72 2E - 74 72 61 69 74 E9 73 20 6A 75 6E 69 6F 72 02 00 - 00 37 32 18 00 00 41 73 73 69 73 74 61 6E 74 20 - 73 6F 75 73 63 2E 20 54 72 61 69 74 E9 73 02 00 - 00 37 36 0C 00 00 53 6F 75 73 63 2E 46 61 63 20 - 52 43 02 00 00 37 37 0E 00 00 52 65 73 70 6F 6E - 73 69 62 6C 65 20 52 48 02 00 00 37 38 1F 00 00 - 22 52 65 73 70 6F 6E 73 69 62 6C 65 20 22 22 73 - 70 65 63 69 61 6C 20 6C 69 6E 65 73 22 22 22 15 - 00 00 53 6F 75 73 63 72 69 70 74 65 75 72 73 20 - 74 72 61 69 74 E9 73 1E 00 00 41 64 6D 69 6E 69 - 73 74 72 61 74 65 75 72 20 73 79 73 74 E8 6D 65 - 20 72 E9 73 65 61 75 78 04 00 00 53 52 49 53 0E - 00 00 43 6C 61 69 6D 73 20 73 75 70 70 6F 72 74 - 15 00 00 41 63 63 6F 75 6E 74 61 6E 74 2F 20 48 - 52 20 61 64 6D 69 6E 2E diff --git a/test-data/spreadsheet/BigSSTRecord2CR5 b/test-data/spreadsheet/BigSSTRecord2CR5 deleted file mode 100644 index e1105745b..000000000 --- a/test-data/spreadsheet/BigSSTRecord2CR5 +++ /dev/null @@ -1,515 +0,0 @@ - 3C 00 18 20 15 00 00 53 - 65 63 72 65 74 61 72 79 2F 66 61 63 2F 61 64 6D - 6E 69 73 2E 02 00 00 43 45 17 00 00 43 6C 69 65 - 6E 74 20 52 65 6C 61 74 69 6F 6E 20 4D 61 6E 61 - 67 65 72 02 00 00 4D 4E 04 00 00 38 37 39 36 04 - 00 00 53 52 4E 4D 02 00 00 4D 55 02 00 00 50 52 - 05 00 00 31 32 30 31 31 02 00 00 4D 47 05 00 00 - 31 31 36 31 30 05 00 00 31 30 34 38 33 02 00 00 - 53 43 05 00 00 31 30 32 31 32 02 00 00 4C 55 04 - 00 00 33 36 32 34 08 00 00 53 52 4E 4D 2C 20 41 - 44 02 00 00 4D 57 04 00 00 37 30 33 33 05 00 00 - 31 32 37 34 30 05 00 00 31 31 35 33 38 02 00 00 - 4D 50 02 00 00 4D 46 05 00 00 31 31 34 37 32 04 - 00 00 32 37 30 38 04 00 00 38 32 34 39 02 00 00 - 4D 54 04 00 00 35 39 38 32 04 00 00 36 39 33 36 - 04 00 00 35 34 31 32 04 00 00 35 38 33 37 07 00 - 00 53 52 4E 4D 2C 20 44 02 00 00 41 52 04 00 00 - 37 33 34 32 05 00 00 31 32 39 33 33 04 00 00 36 - 30 36 32 04 00 00 37 38 35 39 19 00 00 41 73 73 - 65 74 20 26 20 4C 69 61 62 69 6C 69 74 79 20 4D - 61 6E 61 67 65 72 19 00 00 48 65 61 64 20 6F 66 - 20 47 72 6F 75 70 77 61 72 65 26 50 6F 72 74 61 - 6C 73 0F 00 00 48 65 61 64 20 43 49 4F 20 4F 66 - 66 69 63 65 19 00 00 53 65 6E 69 6F 72 20 50 72 - 6F 63 75 72 65 6D 65 6E 74 20 4F 66 66 69 63 2E - 02 00 00 53 44 18 00 00 48 65 61 64 20 6F 66 20 - 53 65 72 76 65 72 20 45 6E 67 69 6E 65 65 72 2E - 13 00 00 43 4D 53 20 44 61 74 61 20 43 6F 6E 73 - 75 6C 74 61 6E 74 15 00 00 44 65 70 75 74 79 20 - 50 6F 72 74 61 6C 20 4D 61 6E 61 67 65 72 0B 00 - 00 54 61 78 20 43 6F 75 6E 73 65 6C 02 00 00 4E - 52 14 00 00 48 65 61 64 20 6F 66 20 41 70 70 2E - 20 49 6E 74 65 67 72 2E 13 00 00 48 65 61 64 20 - 49 54 20 49 6E 76 65 73 74 6D 65 6E 74 73 09 00 - 00 50 72 75 64 65 6E 74 69 61 04 00 00 38 31 39 - 39 04 00 00 33 31 39 30 05 00 00 31 33 30 39 36 - 04 00 00 38 32 34 37 02 00 00 55 54 04 00 00 35 - 32 35 36 04 00 00 35 32 33 36 05 00 00 31 31 30 - 31 36 04 00 00 34 36 30 32 04 00 00 34 36 30 36 - 05 00 00 31 31 38 32 36 05 00 00 31 31 35 36 31 - 04 00 00 32 34 34 38 05 00 00 31 32 32 31 32 04 - 00 00 36 39 33 37 05 00 00 31 30 31 36 32 05 00 - 00 31 32 34 31 34 04 00 00 38 31 38 35 04 00 00 - 36 39 30 33 04 00 00 33 37 31 36 04 00 00 37 30 - 32 39 04 00 00 36 35 36 35 05 00 00 31 32 39 38 - 35 05 00 00 31 31 31 33 30 04 00 00 32 39 30 35 - 04 00 00 38 34 32 34 04 00 00 34 39 35 36 04 00 - 00 35 34 39 36 04 00 00 32 34 35 34 05 00 00 31 - 32 30 32 32 04 00 00 32 31 38 32 04 00 00 37 37 - 38 31 04 00 00 37 34 33 38 04 00 00 37 32 35 31 - 05 00 00 31 31 31 32 38 05 00 00 31 30 32 30 38 - 05 00 00 31 30 36 38 32 04 00 00 36 39 30 36 04 - 00 00 35 32 33 39 04 00 00 38 38 36 31 05 00 00 - 31 31 30 34 33 05 00 00 31 31 37 32 32 04 00 00 - 36 32 38 36 02 00 00 4C 49 04 00 00 37 31 39 36 - 04 00 00 33 31 39 31 04 00 00 34 33 38 30 04 00 - 00 36 30 38 33 04 00 00 38 35 37 35 04 00 00 36 - 38 33 32 04 00 00 33 39 31 35 03 00 00 31 31 33 - 05 00 00 31 32 39 30 31 05 00 00 31 31 35 32 38 - 04 00 00 35 30 36 39 05 00 00 31 32 38 35 35 05 - 00 00 31 32 31 33 30 04 00 00 36 34 35 35 04 00 - 00 34 39 34 31 04 00 00 33 35 32 35 02 00 00 54 - 45 04 00 00 37 30 33 32 04 00 00 35 32 39 37 05 - 00 00 31 30 32 39 32 04 00 00 39 37 39 31 05 00 - 00 31 30 35 31 39 04 00 00 31 35 30 30 04 00 00 - 33 35 37 34 04 00 00 31 39 32 36 04 00 00 33 35 - 36 33 04 00 00 33 39 35 33 05 00 00 31 31 33 32 - 37 05 00 00 31 32 38 33 36 04 00 00 35 35 33 31 - 04 00 00 36 32 37 37 04 00 00 38 39 33 31 04 00 - 00 35 37 33 30 05 00 00 38 30 33 36 31 15 00 00 - 50 6F 73 69 74 69 6F 6E 20 4E 6F 74 20 44 65 66 - 69 6E 65 64 2C 03 00 00 35 34 32 04 00 00 33 35 - 31 37 05 00 00 31 30 35 36 31 05 00 00 31 30 35 - 36 32 05 00 00 31 30 35 36 33 05 00 00 31 30 35 - 36 38 05 00 00 31 30 35 37 37 05 00 00 31 30 35 - 38 30 11 00 00 4C 65 69 74 65 72 20 50 43 20 53 - 75 70 70 6F 72 74 05 00 00 31 30 35 38 31 05 00 - 00 31 30 35 38 35 05 00 00 31 30 35 38 39 05 00 - 00 31 30 36 30 36 05 00 00 31 30 36 31 33 13 00 - 00 43 72 65 64 69 74 20 52 69 73 6B 20 41 6E 61 - 6C 79 73 74 05 00 00 31 30 36 31 35 05 00 00 31 - 30 36 31 37 15 00 00 45 78 70 65 72 74 65 20 4E - 61 74 75 72 67 65 66 61 68 72 65 6E 05 00 00 31 - 30 36 31 38 05 00 00 31 30 36 32 35 05 00 00 31 - 30 36 32 36 05 00 00 31 30 36 33 34 05 00 00 31 - 30 36 33 39 0C 00 00 41 73 73 69 73 74 61 6E 74 - 20 43 58 05 00 00 31 30 36 35 37 05 00 00 31 30 - 36 37 35 0E 00 00 4C 65 69 74 65 72 20 53 75 70 - 70 6F 72 74 05 00 00 31 30 36 37 36 05 00 00 31 - 30 36 38 37 05 00 00 31 30 36 39 32 05 00 00 31 - 30 37 30 34 10 00 00 53 70 65 7A 69 61 6C 69 73 - 74 69 6E 20 47 49 53 05 00 00 31 30 37 33 30 05 - 00 00 31 30 37 33 33 05 00 00 31 30 37 34 33 16 - 00 00 48 65 61 64 20 41 70 70 6C 2E 20 44 65 76 - 65 6C 6F 70 6D 65 6E 74 05 00 00 31 30 37 34 36 - 19 00 00 55 6E 69 76 65 72 73 2E 52 65 6C 61 74 - 69 6F 6E 73 20 4D 61 6E 61 67 65 72 05 00 00 31 - 30 37 34 39 05 00 00 31 30 37 36 38 0A 00 00 48 - 65 61 64 20 6F 66 20 49 46 05 00 00 31 30 37 37 - 39 0E 00 00 54 65 61 6D 20 4C 65 61 64 65 72 20 - 50 56 05 00 00 31 30 37 39 37 05 00 00 31 30 38 - 30 33 05 00 00 31 30 38 30 36 05 00 00 31 30 38 - 30 38 05 00 00 31 30 38 31 34 05 00 00 31 30 38 - 32 31 05 00 00 31 30 38 32 35 11 00 00 54 4C 20 - 52 65 63 68 6E 75 6E 67 73 77 65 73 65 6E 05 00 - 00 31 30 38 32 37 0A 00 00 50 43 20 53 75 70 70 - 6F 72 74 05 00 00 31 30 38 32 38 15 00 00 4C 65 - 69 74 65 72 20 53 70 72 61 63 68 65 6E 64 69 65 - 6E 73 74 05 00 00 31 30 38 33 30 15 00 00 53 65 - 6B 72 65 74 E4 72 69 6E 2F 53 61 63 68 62 65 61 - 72 62 2E 05 00 00 31 30 38 33 34 05 00 00 31 30 - 38 33 35 02 00 00 46 49 05 00 00 31 30 38 33 36 - 05 00 00 31 30 38 34 30 05 00 00 31 30 38 34 36 - 05 00 00 31 30 38 36 31 05 00 00 31 30 38 36 32 - 12 00 00 41 75 64 69 74 20 26 20 49 6E 73 70 65 - 63 74 69 6F 6E 05 00 00 31 30 38 36 33 05 00 00 - 31 30 38 37 31 05 00 00 31 30 38 38 33 05 00 00 - 31 30 38 39 30 05 00 00 31 30 38 39 33 17 00 00 - 41 73 73 69 73 74 61 6E 74 20 74 6F 20 44 65 70 - 74 2E 20 48 65 61 64 05 00 00 31 30 38 39 39 05 - 00 00 31 30 39 30 33 05 00 00 31 30 39 30 35 05 - 00 00 31 30 39 31 33 19 00 00 47 72 6C 2E 20 47 - 72 61 66 69 73 63 68 65 20 50 72 6F 64 75 6B 74 - 69 6F 6E 05 00 00 31 30 39 31 35 05 00 00 31 30 - 39 31 38 05 00 00 31 30 39 32 30 05 00 00 31 30 - 39 32 33 05 00 00 31 30 39 32 34 05 00 00 31 30 - 39 33 39 05 00 00 31 30 39 34 32 05 00 00 31 30 - 39 34 33 05 00 00 31 30 39 35 31 05 00 00 31 30 - 39 35 35 05 00 00 31 30 39 35 37 13 00 00 54 65 - 61 6D 6C 65 61 64 65 72 20 52 65 73 65 61 72 63 - 68 05 00 00 31 30 39 36 32 05 00 00 31 30 39 37 - 30 05 00 00 31 30 39 37 34 05 00 00 31 30 39 37 - 35 05 00 00 31 30 39 37 36 05 00 00 31 30 39 38 - 38 05 00 00 31 30 39 39 36 05 00 00 31 31 30 30 - 33 05 00 00 31 31 30 30 34 02 00 00 4D 44 05 00 - 00 31 31 30 30 38 12 00 00 48 65 61 64 20 44 69 - 76 69 73 69 6F 6E 61 6C 20 4D 44 05 00 00 31 31 - 30 30 39 05 00 00 31 31 30 31 32 05 00 00 31 31 - 30 31 33 05 00 00 31 31 30 31 34 16 00 00 47 72 - 75 70 70 65 6E 6C 65 69 74 65 72 20 4D 61 74 65 - 72 69 61 6C 05 00 00 31 31 30 32 33 02 00 00 4B - 42 05 00 00 31 31 30 32 38 0E 00 00 4B 42 4D 2D - 50 72 61 6B 74 69 6B 61 6E 74 05 00 00 31 31 30 - 32 39 10 00 00 4B 42 4D 2D 50 72 61 6B 74 69 6B - 61 6E 74 69 6E 05 00 00 31 31 30 33 30 05 00 00 - 31 31 30 33 31 05 00 00 31 31 30 33 33 05 00 00 - 31 31 30 33 34 05 00 00 31 31 30 33 35 19 00 00 - 55 57 20 4D 67 20 54 72 65 61 74 79 20 50 72 6F - 70 2E 20 26 20 43 61 73 2E 05 00 00 31 31 30 33 - 36 05 00 00 31 31 30 33 38 05 00 00 31 31 30 33 - 39 17 00 00 55 53 20 47 41 41 50 20 52 65 70 6F - 72 74 2E 20 4D 61 6E 61 67 65 72 05 00 00 31 31 - 30 34 30 19 00 00 50 72 6F 63 65 73 73 20 4D 61 - 6E 61 67 2E 20 46 69 6E 26 43 6F 6E 74 72 2E 05 - 00 00 31 31 30 34 34 14 00 00 4C 65 67 61 6C 20 - 43 6C 61 69 6D 73 20 43 6F 75 6E 73 65 6C 05 00 - 00 31 31 30 35 31 05 00 00 31 31 30 35 37 05 00 - 00 31 31 30 36 32 05 00 00 31 31 30 37 30 05 00 - 00 31 31 30 37 32 05 00 00 31 31 30 37 37 05 00 - 00 31 31 30 37 38 05 00 00 31 31 30 38 30 05 00 - 00 31 31 30 38 31 19 00 00 54 65 61 6D 6C 65 69 - 74 65 72 69 6E 20 53 65 6B 72 65 74 2E 2F 56 65 - 72 77 05 00 00 31 31 30 38 32 0E 00 00 53 65 6E - 69 6F 72 20 41 6E 61 6C 79 73 74 02 00 00 47 4F - 05 00 00 31 31 30 38 36 05 00 00 31 31 30 38 37 - 05 00 00 31 31 30 38 38 05 00 00 31 31 30 38 39 - 15 00 00 53 74 76 2E 20 42 65 74 72 69 65 62 73 - 6C 65 69 74 65 72 69 6E 05 00 00 31 31 30 39 30 - 05 00 00 31 31 30 39 31 05 00 00 31 31 30 39 34 - 05 00 00 31 31 30 39 36 05 00 00 31 31 30 39 38 - 05 00 00 31 31 30 39 39 05 00 00 31 31 31 30 30 - 05 00 00 31 31 31 30 31 05 00 00 31 31 31 30 32 - 05 00 00 31 31 31 30 33 05 00 00 31 31 31 30 39 - 05 00 00 31 31 31 33 33 05 00 00 31 31 31 33 35 - 05 00 00 31 31 31 33 38 0A 00 00 4B FC 63 68 65 - 6E 63 68 65 66 05 00 00 31 31 31 33 39 05 00 00 - 31 31 31 34 32 05 00 00 31 31 31 34 34 05 00 00 - 31 31 31 34 35 05 00 00 31 31 31 34 36 16 00 00 - 48 65 61 64 20 6F 66 20 54 65 63 68 2E 20 54 72 - 61 69 6E 69 6E 67 05 00 00 31 31 31 34 37 19 00 - 00 42 65 74 72 69 65 62 73 6C 65 69 74 65 72 69 - 6E 20 52 65 73 74 2E 20 47 4F 05 00 00 31 31 31 - 35 33 05 00 00 31 31 31 35 35 19 00 00 54 65 6C - 65 6D 61 74 69 6B 20 53 79 73 74 65 6D 69 6E 67 - 65 6E 69 65 75 72 05 00 00 31 31 31 35 38 05 00 - 00 31 31 31 36 30 05 00 00 31 31 31 36 35 05 00 - 00 31 31 31 36 37 05 00 00 31 31 31 36 38 05 00 - 00 31 31 31 36 39 05 00 00 31 31 31 37 30 17 00 - 00 48 6F 74 65 6C 66 61 63 68 61 73 73 69 73 74 - 65 6E 74 69 6E 20 4C 4C 05 00 00 31 31 31 37 31 - 05 00 00 31 31 31 37 32 05 00 00 31 31 31 37 33 - 05 00 00 31 31 31 37 34 05 00 00 31 31 31 37 35 - 05 00 00 31 31 31 37 36 05 00 00 31 31 31 37 37 - 05 00 00 31 31 31 37 38 05 00 00 31 31 31 37 39 - 05 00 00 31 31 31 38 30 05 00 00 31 31 31 38 31 - 05 00 00 31 31 31 38 32 05 00 00 31 31 31 38 33 - 05 00 00 31 31 31 38 34 05 00 00 31 31 31 38 35 - 05 00 00 31 31 31 38 37 05 00 00 31 31 31 38 38 - 05 00 00 31 31 31 39 31 05 00 00 31 31 31 39 33 - 05 00 00 31 31 31 39 34 17 00 00 42 65 74 72 69 - 65 62 73 6C 65 69 74 65 72 20 52 65 73 74 2E 20 - 54 55 05 00 00 31 31 31 39 35 05 00 00 31 31 31 - 39 36 05 00 00 31 31 31 39 37 05 00 00 31 31 31 - 39 38 05 00 00 31 31 31 39 39 05 00 00 31 31 32 - 30 30 05 00 00 31 31 32 30 31 05 00 00 31 31 32 - 30 32 05 00 00 31 31 32 30 34 05 00 00 31 31 32 - 30 35 05 00 00 31 31 32 30 36 05 00 00 31 31 32 - 30 37 05 00 00 31 31 32 30 39 05 00 00 31 31 32 - 31 38 14 00 00 49 2D 26 20 44 2D 41 73 73 69 73 - 74 65 6E 74 69 6E 20 4C 4C 05 00 00 31 31 32 31 - 39 12 00 00 50 65 72 73 6F 6E 61 6C 65 6E 74 77 - 69 63 6B 6C 65 72 05 00 00 31 31 32 34 33 05 00 - 00 31 31 32 34 35 05 00 00 31 31 32 34 38 05 00 - 00 31 31 32 34 39 05 00 00 31 31 32 35 30 05 00 - 00 31 31 32 35 39 05 00 00 31 31 32 36 33 05 00 - 00 31 31 32 36 36 19 00 00 53 65 6E 69 6F 72 20 - 41 63 63 6F 75 6E 74 2E 20 43 6F 6E 73 6F 6C 69 - 64 2E 05 00 00 31 31 32 37 31 05 00 00 31 31 32 - 37 32 05 00 00 31 31 32 39 30 05 00 00 31 31 32 - 39 31 05 00 00 31 31 32 39 32 05 00 00 31 31 32 - 39 33 05 00 00 31 31 33 30 36 05 00 00 31 31 33 - 30 38 05 00 00 31 31 33 33 30 05 00 00 31 31 33 - 33 34 05 00 00 31 31 33 33 35 05 00 00 31 31 33 - 34 33 14 00 00 42 65 74 72 69 65 62 73 70 72 61 - 6B 74 69 6B 65 72 2D 4C 4C 05 00 00 31 31 33 35 - 31 16 00 00 4D 69 74 61 72 62 2E 20 57 61 72 65 - 6E 6B 6F 6E 74 72 6F 6C 6C 65 05 00 00 31 31 33 - 35 35 05 00 00 31 31 33 35 38 05 00 00 31 31 33 - 36 34 17 00 00 4C 65 69 74 65 72 69 6E 20 52 65 - 70 72 E4 73 65 6E 74 61 74 69 6F 6E 05 00 00 31 - 31 33 36 38 11 00 00 4A 75 6E 69 6F 72 20 41 63 - 63 6F 75 6E 74 61 6E 74 05 00 00 31 31 33 37 30 - 05 00 00 31 31 33 37 34 05 00 00 31 31 33 37 38 - 14 00 00 46 72 61 6E 7A 2E 20 55 65 62 65 72 73 - 65 74 7A 65 72 69 6E 05 00 00 31 31 33 38 30 14 - 00 00 43 46 4F 20 42 65 72 6D 75 64 61 20 42 72 - 61 6E 63 68 65 73 05 00 00 31 31 33 38 37 0A 00 - 00 33 32 34 2C 20 53 65 6F 75 6C 05 00 00 31 31 - 33 39 39 18 00 00 54 65 61 6D 6C 65 69 74 65 72 - 49 6E 20 53 65 6B 72 65 74 61 72 69 61 74 05 00 - 00 31 31 34 32 35 05 00 00 31 31 34 32 38 05 00 - 00 31 31 34 33 39 05 00 00 31 31 34 34 30 05 00 - 00 31 31 34 34 32 05 00 00 31 31 34 34 34 05 00 - 00 31 31 34 34 39 17 00 00 48 65 61 64 20 6F 66 - 20 50 72 69 63 69 6E 67 20 43 6F 6E 74 72 6F 6C - 05 00 00 31 31 34 36 33 05 00 00 31 31 34 36 34 - 18 00 00 42 61 75 6C 65 69 74 65 72 2F 43 41 44 - 20 53 70 65 7A 69 61 6C 69 73 74 05 00 00 31 31 - 34 36 35 05 00 00 31 31 34 36 37 05 00 00 31 31 - 34 37 39 05 00 00 31 31 34 38 39 0D 00 00 54 4C - 20 41 56 2D 54 65 63 68 6E 69 6B 05 00 00 31 31 - 35 30 33 05 00 00 31 31 35 32 31 05 00 00 31 31 - 35 33 31 05 00 00 31 31 35 33 39 05 00 00 31 31 - 35 34 31 05 00 00 31 31 35 34 37 05 00 00 31 31 - 35 34 39 05 00 00 31 31 35 37 39 05 00 00 31 31 - 35 39 33 15 00 00 48 52 2D 4D 49 53 2D 50 72 6F - 6A 65 63 74 6D 61 6E 61 67 65 72 05 00 00 31 31 - 35 39 38 05 00 00 31 31 36 32 33 17 00 00 48 52 - 20 50 72 6F 63 65 73 73 65 73 20 26 20 50 72 6F - 6A 65 63 74 73 05 00 00 31 31 36 32 38 05 00 00 - 31 31 36 33 39 05 00 00 31 31 36 35 31 19 00 00 - 46 72 6F 6E 74 20 4F 66 66 69 63 65 20 26 20 45 - 76 65 6E 74 73 20 4D 67 72 05 00 00 31 31 36 35 - 37 05 00 00 31 31 36 36 38 05 00 00 31 31 36 36 - 39 05 00 00 31 31 36 37 31 05 00 00 31 31 36 37 - 39 05 00 00 31 31 36 38 31 12 00 00 54 65 61 6D - 6C 65 69 74 65 72 20 45 6C 65 6B 74 72 6F 05 00 - 00 31 31 36 38 34 05 00 00 31 31 36 38 36 05 00 - 00 31 31 36 38 37 05 00 00 31 31 36 38 38 05 00 - 00 31 30 35 39 33 05 00 00 31 31 35 36 39 05 00 - 00 31 31 35 33 30 02 00 00 4C 53 04 00 00 34 33 - 32 37 04 00 00 36 39 34 37 05 00 00 31 32 31 34 - 31 05 00 00 31 31 30 37 34 04 00 00 39 35 36 33 - 05 00 00 31 30 38 33 37 04 00 00 38 33 38 31 05 - 00 00 31 30 31 39 38 05 00 00 31 31 30 35 36 09 - 00 00 53 52 4E 4D 2C 20 44 2F 50 05 00 00 31 31 - 30 30 32 04 00 00 34 32 32 33 04 00 00 37 32 37 - 30 02 00 00 53 4E 04 00 00 38 38 31 38 05 00 00 - 31 31 33 34 38 04 00 00 37 31 36 37 04 00 00 35 - 39 39 30 04 00 00 36 32 35 32 02 00 00 50 42 05 - 00 00 31 30 39 31 36 05 00 00 31 30 39 39 30 04 - 00 00 37 32 32 35 04 00 00 35 35 31 35 04 00 00 - 33 33 38 32 05 00 00 31 30 39 30 32 05 00 00 31 - 32 33 38 34 04 00 00 39 37 38 35 04 00 00 35 30 - 31 34 04 00 00 33 33 30 37 07 00 00 42 65 72 6D - 75 64 61 05 00 00 46 41 4C 53 45 04 00 00 39 35 - 30 37 04 00 00 35 31 30 39 04 00 00 36 31 38 32 - 04 00 00 36 32 32 39 04 00 00 33 36 37 35 04 00 - 00 39 38 36 33 05 00 00 31 31 39 34 34 04 00 00 - 38 31 36 38 04 00 00 38 37 31 35 04 00 00 37 31 - 37 38 05 00 00 31 32 37 39 35 04 00 00 36 36 39 - 31 04 00 00 36 31 34 35 04 00 00 36 39 39 32 05 - 00 00 31 31 30 37 35 04 00 00 39 37 34 33 04 00 - 00 36 30 35 30 04 00 00 38 36 36 35 04 00 00 33 - 39 37 38 04 00 00 34 30 35 36 05 00 00 31 30 33 - 30 38 04 00 00 34 36 31 39 04 00 00 33 32 37 31 - 05 00 00 31 30 37 35 35 04 00 00 38 32 38 31 05 - 00 00 31 32 30 39 35 05 00 00 31 32 33 38 31 05 - 00 00 31 30 39 32 31 05 00 00 31 30 39 33 36 04 - 00 00 36 38 34 31 04 00 00 33 39 30 35 04 00 00 - 33 32 32 39 04 00 00 37 35 38 32 05 00 00 31 31 - 35 33 32 04 00 00 36 37 32 39 05 00 00 31 32 30 - 30 31 05 00 00 31 32 30 30 35 05 00 00 31 32 30 - 31 32 05 00 00 31 32 30 31 33 05 00 00 31 32 30 - 32 31 05 00 00 31 32 30 32 35 05 00 00 31 32 30 - 32 36 05 00 00 31 32 30 33 31 05 00 00 31 32 30 - 34 39 05 00 00 31 32 30 36 30 05 00 00 31 32 30 - 36 31 05 00 00 31 32 30 36 32 05 00 00 31 32 30 - 37 38 05 00 00 31 32 30 38 31 05 00 00 31 32 30 - 38 35 15 00 00 53 61 63 68 62 65 61 72 62 65 69 - 74 65 72 69 6E 20 42 65 62 75 05 00 00 31 32 30 - 38 36 05 00 00 31 32 30 38 37 05 00 00 31 32 30 - 38 39 05 00 00 31 32 30 39 32 18 00 00 41 73 73 - 69 73 74 65 6E 74 69 6E 20 56 52 2D 50 72 E4 73 - 69 64 65 6E 74 05 00 00 31 32 30 39 34 05 00 00 - 31 32 30 39 38 05 00 00 31 32 30 39 39 05 00 00 - 31 32 31 30 30 05 00 00 31 32 31 30 37 05 00 00 - 31 32 31 30 39 05 00 00 31 32 31 31 30 05 00 00 - 31 32 31 32 31 05 00 00 31 32 31 32 32 02 00 00 - 41 50 05 00 00 31 32 31 32 38 05 00 00 31 32 31 - 32 39 05 00 00 31 32 31 33 31 16 00 00 41 64 76 - 65 72 74 69 73 69 6E 67 20 53 70 65 63 69 61 6C - 69 73 74 05 00 00 31 32 31 33 33 05 00 00 31 32 - 31 33 37 05 00 00 31 32 31 33 38 05 00 00 31 32 - 31 35 38 05 00 00 31 32 31 36 31 05 00 00 31 32 - 31 36 32 05 00 00 31 32 31 36 33 05 00 00 31 32 - 31 36 35 05 00 00 31 32 31 38 31 05 00 00 31 32 - 31 38 34 05 00 00 31 32 31 38 39 05 00 00 31 32 - 31 39 30 05 00 00 31 32 31 39 31 05 00 00 31 32 - 31 39 38 05 00 00 31 32 32 30 31 05 00 00 31 32 - 32 30 38 12 00 00 4B 69 6F 73 6B 6D 69 74 61 72 - 62 65 69 74 65 72 69 6E 05 00 00 31 32 32 31 30 - 15 00 00 4F 70 65 72 61 74 69 6F 6E 73 20 4D 61 - 6E 61 67 65 72 20 43 58 05 00 00 31 32 32 31 36 - 0A 00 00 48 65 61 64 20 6F 66 20 43 50 11 00 00 - 4D 61 6E 68 61 74 74 61 6E 20 4E 59 2C 20 55 53 - 41 05 00 00 31 32 32 31 38 05 00 00 31 32 32 32 - 31 02 00 00 41 41 05 00 00 31 32 32 32 33 05 00 - 00 31 32 32 32 39 05 00 00 31 32 32 33 31 05 00 - 00 31 32 32 33 34 05 00 00 31 32 32 34 37 05 00 - 00 31 32 32 35 31 05 00 00 31 32 32 36 37 05 00 - 00 31 32 32 37 38 11 00 00 4A 75 6E 69 6F 72 20 - 43 6F 6E 74 72 6F 6C 6C 65 72 05 00 00 31 32 32 - 38 33 05 00 00 31 32 32 39 30 05 00 00 31 32 32 - 39 31 05 00 00 31 32 33 30 33 05 00 00 31 32 33 - 30 35 05 00 00 31 32 33 31 33 09 00 00 41 73 73 - 6F 63 69 61 74 65 05 00 00 31 32 33 31 34 05 00 - 00 31 32 33 32 32 15 00 00 4C 65 69 74 65 72 20 - 53 79 73 74 65 6D 2D 54 65 63 68 6E 69 6B 05 00 - 00 31 32 33 32 33 19 00 00 41 72 63 68 69 76 65 - 20 26 20 52 65 63 6F 72 64 73 20 4D 61 6E 61 67 - 65 72 05 00 00 31 32 33 32 34 05 00 00 31 32 33 - 32 37 05 00 00 31 32 33 33 36 05 00 00 31 32 33 - 33 37 05 00 00 31 32 33 33 38 05 00 00 31 32 33 - 34 36 05 00 00 31 32 33 34 37 05 00 00 31 32 33 - 36 30 05 00 00 31 32 33 36 37 05 00 00 31 32 33 - 37 37 05 00 00 31 32 33 38 33 05 00 00 31 32 34 - 31 36 16 00 00 48 65 61 64 20 6F 66 20 47 72 6F - 75 70 20 52 65 73 65 72 76 65 73 05 00 00 31 32 - 34 32 37 12 00 00 46 FC 68 72 75 6E 67 73 2D 41 - 73 73 69 73 74 65 6E 74 05 00 00 31 32 34 34 34 - 05 00 00 31 32 34 35 30 05 00 00 31 32 34 35 31 - 05 00 00 31 32 34 35 33 05 00 00 31 32 34 35 39 - 19 00 00 53 74 76 2E 20 48 61 75 73 77 69 72 74 - 73 63 68 2E 4C 65 69 74 65 72 69 6E 05 00 00 31 - 32 34 36 30 02 00 00 48 4D 05 00 00 31 32 34 36 - 31 10 00 00 48 4D 53 2D 50 72 61 6B 74 69 6B 61 - 6E 74 69 6E 05 00 00 31 32 34 36 32 0E 00 00 48 - 4D 53 2D 50 72 61 6B 74 69 6B 61 6E 74 05 00 00 - 31 32 34 36 33 05 00 00 31 32 34 36 34 05 00 00 - 31 32 34 36 35 05 00 00 31 32 34 36 37 05 00 00 - 31 32 34 36 38 05 00 00 31 32 34 36 39 13 00 00 - 53 65 72 76 69 63 65 66 61 63 68 6C 65 68 72 6C - 69 6E 67 05 00 00 31 32 34 37 30 05 00 00 31 32 - 34 37 31 05 00 00 31 32 34 37 32 05 00 00 31 32 - 34 37 34 05 00 00 31 32 34 37 35 05 00 00 31 32 - 34 37 36 05 00 00 31 32 34 37 37 05 00 00 31 32 - 34 37 38 05 00 00 31 32 34 38 30 05 00 00 31 32 - 34 38 31 05 00 00 31 32 34 38 33 05 00 00 31 32 - 34 38 34 05 00 00 31 32 34 38 35 05 00 00 31 32 - 34 38 36 05 00 00 31 32 34 38 37 05 00 00 31 32 - 34 38 38 05 00 00 31 32 34 38 39 05 00 00 31 32 - 34 39 30 05 00 00 31 32 34 39 31 05 00 00 31 32 - 34 39 32 05 00 00 31 32 34 39 33 05 00 00 31 32 - 35 30 30 17 00 00 42 65 74 72 69 65 62 73 6C 65 - 69 74 65 72 20 52 65 73 74 2E 20 4B 48 05 00 00 - 31 32 35 30 31 05 00 00 31 32 35 30 32 11 00 00 - 48 61 75 73 77 69 72 74 73 63 68 61 66 74 73 6D - 2E 05 00 00 31 32 35 30 36 05 00 00 31 32 35 30 - 37 05 00 00 31 32 35 31 31 05 00 00 31 32 35 31 - 33 05 00 00 31 32 35 31 36 17 00 00 53 65 6E 69 - 6F 72 20 4D 65 64 69 61 20 43 6F 6E 73 75 6C 74 - 61 6E 74 05 00 00 31 32 35 31 37 05 00 00 31 32 - 35 31 38 05 00 00 31 32 35 31 39 19 00 00 4C 65 - 69 74 65 72 20 4C 61 67 65 72 62 65 77 69 72 74 - 73 63 68 61 66 74 2E 05 00 00 31 32 35 32 30 0D - 00 00 4E 69 67 68 74 20 41 75 64 69 74 6F 72 05 - 00 00 31 32 35 32 36 13 00 00 4C 65 69 74 65 72 - 20 4A 75 6E 69 6F 72 20 50 6F 77 65 72 05 00 00 - 31 32 35 33 32 05 00 00 31 32 35 33 33 05 00 00 - 31 32 35 33 36 05 00 00 31 32 35 33 37 17 00 00 - 41 73 73 69 73 74 61 6E 74 20 6F 66 20 44 65 70 - 61 72 74 6D 65 6E 74 05 00 00 31 32 35 33 38 05 - 00 00 31 32 35 34 30 05 00 00 31 32 35 34 35 05 - 00 00 31 32 35 35 31 05 00 00 31 32 35 35 32 05 - 00 00 31 32 35 36 32 15 00 00 41 75 64 69 6F 2D - 56 69 64 65 6F 20 53 75 70 70 6F 72 74 65 72 05 - 00 00 31 32 35 36 34 0E 00 00 43 68 65 66 20 64 - 65 20 50 61 72 74 69 65 05 00 00 31 32 35 36 38 - 05 00 00 31 32 35 37 31 05 00 00 31 32 35 37 32 - 13 00 00 53 74 76 2E 20 42 65 74 72 69 65 62 73 - 6C 65 69 74 65 72 05 00 00 31 32 35 37 35 05 00 - 00 31 32 35 37 36 05 00 00 31 32 35 37 37 05 00 - 00 31 32 35 37 38 05 00 00 31 32 35 38 30 11 00 - 00 53 6F 63 69 61 6C 20 43 6F 6E 73 75 6C 74 61 - 6E 74 05 00 00 31 32 35 38 31 05 00 00 31 32 35 - 38 33 14 00 00 54 65 61 6D 6C 2E 20 52 E9 63 2E - 20 41 64 6C 69 73 77 69 6C 05 00 00 31 32 35 38 - 39 05 00 00 31 32 35 39 31 05 00 00 31 32 36 30 - 35 05 00 00 31 32 36 30 36 05 00 00 31 32 36 30 - 39 0B 00 00 43 68 65 66 20 64 65 20 42 61 72 05 - 00 00 31 32 36 31 32 19 00 00 48 65 61 64 20 43 - 6F 72 53 70 6F 6E 73 26 50 75 62 6C 41 66 66 61 - 69 72 73 05 00 00 31 32 36 32 34 05 00 00 31 32 - 36 33 33 05 00 00 31 32 36 34 34 05 00 00 31 32 - 36 35 39 05 00 00 31 32 36 36 31 05 00 00 31 32 - 36 36 33 05 00 00 31 32 36 36 34 05 00 00 31 32 - 36 36 37 05 00 00 31 32 36 36 38 05 00 00 31 32 - 36 37 38 05 00 00 31 32 36 38 30 05 00 00 31 32 - 36 38 31 05 00 00 31 32 36 38 32 05 00 00 31 32 - 36 38 33 13 00 00 53 69 63 68 65 72 68 65 69 74 - 73 66 61 63 68 6D 61 6E 6E 05 00 00 31 32 36 39 - 34 05 00 00 31 32 36 39 35 05 00 00 31 32 36 39 - 36 11 00 00 53 61 63 68 62 65 61 72 62 65 69 74 - 65 72 20 50 56 05 00 00 31 32 36 39 37 05 00 00 - 31 32 37 30 31 05 00 00 31 32 37 31 32 05 00 00 - 31 32 37 31 39 05 00 00 31 32 37 32 30 05 00 00 - 31 32 37 32 33 05 00 00 31 32 37 32 38 05 00 00 - 31 32 37 33 39 05 00 00 31 32 37 34 31 0A 00 00 - 41 6C 6C 72 6F 75 6E 64 65 72 05 00 00 31 32 37 - 34 32 05 00 00 31 32 37 34 39 16 00 00 4D 67 72 - 20 4B 6E 6F 77 6C 65 64 67 65 20 4E 65 74 77 6F - 72 6B 73 05 00 00 31 32 37 35 31 05 00 00 31 32 - 37 36 35 05 00 00 31 32 37 36 36 05 00 00 31 32 - 37 36 39 05 00 00 31 32 37 37 30 08 00 00 4F 70 - 65 72 61 74 6F 72 05 00 00 31 32 37 38 34 16 00 - 00 41 73 73 69 73 74 61 6E 74 20 4A 75 6E 69 6F - 72 20 50 6F 77 65 72 05 00 00 31 32 37 38 35 15 - 00 00 4D 75 6C 74 69 6D 65 64 69 61 20 53 70 65 - 63 69 61 6C 69 73 74 05 00 00 31 32 37 38 37 05 - 00 00 31 32 37 39 30 0C 00 00 33 32 34 2C 20 42 - 65 69 6A 69 6E 67 05 00 00 31 32 37 39 32 05 00 - 00 31 32 37 39 34 05 00 00 31 32 37 39 38 05 00 - 00 31 32 37 39 39 05 00 00 31 32 38 30 31 05 00 - 00 31 32 38 30 32 05 00 00 31 32 38 30 33 05 00 - 00 31 32 38 30 37 05 00 00 31 32 38 31 30 05 00 - 00 31 32 38 31 31 05 00 00 31 32 38 31 33 05 00 - 00 31 32 38 31 36 05 00 00 31 32 38 31 37 05 00 - 00 31 32 38 31 38 05 00 00 31 32 38 31 39 05 00 - 00 31 32 38 32 30 05 00 00 31 32 38 32 32 05 00 - 00 31 32 38 32 33 05 00 00 31 32 38 32 35 05 00 - 00 31 32 38 32 36 19 00 00 48 65 61 64 20 50 72 - 6F 63 65 73 73 26 50 65 72 66 6F 72 6D 2E 4D 67 - 74 2E 05 00 00 31 32 38 32 38 05 00 00 31 32 38 - 33 30 05 00 00 31 32 38 33 31 05 00 00 31 32 38 - 33 33 05 00 00 31 32 38 33 35 05 00 00 31 32 38 - 33 37 05 00 00 31 32 38 33 38 05 00 00 31 32 38 - 33 39 05 00 00 31 32 38 34 31 05 00 00 31 32 38 - 34 33 05 00 00 31 32 38 35 33 05 00 00 31 32 38 - 35 38 05 00 00 31 32 38 35 39 05 00 00 31 32 38 - 36 31 05 00 00 31 32 38 37 31 05 00 00 31 32 38 - 37 39 05 00 00 31 32 38 38 31 05 00 00 31 32 38 - 38 32 05 00 00 31 32 38 38 33 05 00 00 31 32 38 - 38 34 05 00 00 31 32 38 38 35 05 00 00 31 32 38 - 38 37 05 00 00 31 32 38 39 30 05 00 00 31 32 39 - 30 33 05 00 00 31 32 39 30 34 05 00 00 31 32 39 - 30 35 05 00 00 31 32 39 31 37 10 00 00 47 72 6F - 75 70 20 43 6F 6E 74 72 6F 6C 6C 65 72 05 00 00 - 31 32 39 32 32 05 00 00 31 32 39 32 35 05 00 00 - 31 32 39 32 36 19 00 00 49 6E 74 65 72 6E 61 74 - 69 6F 6E 61 6C 20 54 61 78 20 43 6F 75 6E 73 65 - 6C 05 00 00 31 32 39 35 31 05 00 00 31 32 39 35 - 33 05 00 00 31 32 39 35 36 05 00 00 31 32 39 35 - 38 19 00 00 4A 75 6E 2E 20 41 70 70 6C 69 63 61 - 74 69 6F 6E 20 45 6E 67 69 6E 65 65 72 05 00 00 - 31 32 39 36 38 05 00 00 31 32 39 37 33 05 00 00 - 31 32 39 37 34 05 00 00 31 32 39 38 31 05 00 00 - 31 32 39 39 39 05 00 00 31 33 30 30 30 05 00 00 - 31 33 30 30 33 05 00 00 31 33 30 30 34 05 00 00 - 31 33 30 31 39 05 00 00 31 33 30 32 39 05 00 00 - 31 33 30 33 32 05 00 00 31 33 30 33 34 05 00 00 - 31 33 30 34 31 05 00 00 31 33 30 36 31 05 00 00 - 31 33 30 36 34 05 00 00 31 33 30 36 35 05 00 00 - 31 33 30 38 35 05 00 00 31 33 30 38 36 05 00 00 - 31 33 31 30 31 05 00 00 31 33 31 33 30 05 00 00 - 31 33 31 33 37 05 00 00 31 33 31 34 31 02 00 00 - 4E 59 05 00 00 38 30 30 31 36 1C 00 00 48 65 61 - 64 20 6F 66 20 45 63 6F 6E 6F 6D 69 63 20 52 65 - 73 65 61 72 63 68 20 4E 59 05 00 00 38 30 31 35 - 39 05 00 00 38 30 32 36 35 05 00 00 38 30 35 36 - 39 05 00 00 38 30 31 36 34 26 00 00 48 65 61 64 - 20 6F 66 20 4B 6E 6F 77 6C 65 64 67 65 20 26 20 - 49 6E 66 6F 72 6D 61 74 69 6F 6E 20 4D 67 6E 74 - 2E 2C 06 00 00 41 72 6D 6F 6E 6B 19 00 00 48 65 - 61 64 20 6F 66 20 55 6E 64 65 72 77 72 69 74 69 - 6E 67 20 53 65 72 76 19 00 00 48 65 61 64 20 6F - 66 20 53 74 72 61 74 2E 26 20 44 65 76 2E 20 55 - 6E 69 74 08 00 00 33 32 34 2D 53 6F 75 6C 05 00 - 00 4C 45 47 41 4C 04 00 00 4C 45 31 31 05 00 00 - 38 30 33 35 39 0F 00 00 47 65 6E 65 72 61 6C 20 - 43 6F 75 6E 73 65 6C 03 00 00 30 30 31 09 00 00 - 42 72 75 78 65 6C 6C 65 73 10 00 00 4D 65 64 65 - 78 20 53 70 65 63 69 61 6C 69 73 74 02 00 00 4D - 4F 02 00 00 54 4F 02 00 00 50 46 06 00 00 4C 30 - 30 35 38 32 diff --git a/test-data/spreadsheet/BigSSTRecord2CR6 b/test-data/spreadsheet/BigSSTRecord2CR6 deleted file mode 100644 index a937fe447..000000000 --- a/test-data/spreadsheet/BigSSTRecord2CR6 +++ /dev/null @@ -1,515 +0,0 @@ - 3C 00 1A 20 02 00 00 53 4C 02 00 00 - 5A 48 02 00 00 46 50 02 00 00 44 44 02 00 00 49 - 5A 12 00 00 43 75 73 74 6F 64 79 20 4D 61 6E 61 - 67 65 6D 65 6E 74 13 00 00 55 73 65 72 20 53 75 - 70 70 6F 72 74 20 48 69 50 6F 72 74 19 00 00 48 - 65 61 64 20 49 6E 76 65 73 74 6D 65 6E 74 20 43 - 65 6E 74 65 72 20 5A 48 0E 00 00 41 64 6D 69 6E - 69 73 74 72 61 74 69 6F 6E 16 00 00 44 65 70 75 - 74 79 20 44 65 70 61 72 74 6D 65 6E 74 20 48 65 - 61 64 02 00 00 49 47 14 00 00 55 6E 64 65 72 77 - 72 69 74 69 6E 67 20 4D 61 6E 61 67 65 72 11 00 - 00 48 65 61 64 20 46 69 78 65 64 20 49 6E 63 6F - 6D 65 02 00 00 57 49 02 00 00 46 4E 02 00 00 4C - 46 16 00 00 48 65 61 64 20 49 6E 76 65 73 74 6D - 65 6E 74 20 41 64 6D 69 6E 2E 02 00 00 54 41 18 - 00 00 48 65 61 64 20 54 61 63 74 69 63 61 6C 20 - 41 6C 6C 6F 63 61 74 69 6F 6E 18 00 00 4F 70 65 - 72 61 74 69 6F 6E 73 20 26 20 54 61 78 20 4F 66 - 66 69 63 65 72 02 00 00 41 4D 12 00 00 53 65 6E - 69 6F 72 20 43 61 73 75 61 6C 74 79 20 55 57 02 - 00 00 45 51 16 00 00 44 69 76 2E 20 46 69 6E 61 - 6E 63 69 61 6C 20 4F 66 66 69 63 65 72 02 00 00 - 49 49 18 00 00 41 73 73 69 73 74 65 6E 74 69 6E - 20 4C 49 2D 56 65 72 77 61 6C 74 65 72 0C 00 00 - 53 65 63 74 69 6F 6E 20 48 65 61 64 02 00 00 50 - 56 02 00 00 44 55 11 00 00 4C 65 69 74 65 72 20 - 48 79 70 6F 74 68 65 6B 65 6E 19 00 00 48 65 61 - 64 20 53 65 63 74 6F 72 20 53 74 72 61 74 2E 20 - 45 75 72 6F 70 65 0D 00 00 48 65 61 64 20 45 71 - 75 69 74 69 65 73 19 00 00 4C 69 65 67 65 6E 73 - 63 68 61 66 74 65 6E 76 65 72 77 61 6C 74 65 72 - 69 6E 19 00 00 44 65 70 75 74 79 20 48 65 61 64 - 20 49 6E 76 65 73 74 2E 41 64 6D 69 6E 2E 14 00 - 00 4C 65 69 74 65 72 20 4C 49 2D 56 65 72 77 61 - 6C 74 75 6E 67 04 00 00 38 36 37 31 03 00 00 35 - 36 39 03 00 00 31 33 30 04 00 00 31 37 34 30 03 - 00 00 32 30 36 0A 00 00 49 54 20 4D 61 6E 61 67 - 65 72 03 00 00 35 34 31 0C 00 00 49 54 20 45 78 - 65 63 75 74 69 76 65 0E 00 00 4F 66 66 69 63 65 - 20 4D 61 6E 61 67 65 72 04 00 00 35 37 30 32 04 - 00 00 38 35 36 32 18 00 00 4D 67 72 20 52 65 73 - 65 61 72 63 68 20 26 20 43 6F 6D 6D 75 6E 69 63 - 2E 04 00 00 38 35 36 39 04 00 00 36 35 32 31 04 - 00 00 39 31 36 31 03 00 00 35 39 37 04 00 00 32 - 30 34 31 03 00 00 33 36 33 1A 00 00 52 65 63 65 - 70 74 69 6F 6E 69 73 74 2F 54 65 6C 65 70 68 6F - 6E 65 20 4F 70 2E 03 00 00 33 36 34 04 00 00 36 - 30 35 32 0F 00 00 48 75 6D 61 6E 20 52 65 73 6F - 75 72 63 65 73 03 00 00 31 32 38 03 00 00 31 30 - 34 1E 00 00 47 65 6E 65 72 61 6C 20 4D 67 72 20 - 4E 6F 6E 2D 4C 69 66 65 20 28 53 69 6E 67 61 70 - 2E 29 03 00 00 34 39 31 0A 00 00 30 33 2E 30 38 - 2E 31 39 39 38 0A 00 00 31 36 2E 30 38 2E 31 39 - 36 34 0A 00 00 30 31 2E 30 37 2E 31 39 39 38 0A - 00 00 32 34 2E 30 31 2E 31 39 35 36 0A 00 00 30 - 31 2E 30 37 2E 31 39 39 36 0A 00 00 30 34 2E 30 - 36 2E 31 39 36 32 0A 00 00 30 36 2E 30 33 2E 32 - 30 30 30 0A 00 00 31 36 2E 30 36 2E 31 39 36 35 - 0A 00 00 31 35 2E 30 38 2E 32 30 30 30 0A 00 00 - 31 37 2E 30 37 2E 31 39 37 31 0A 00 00 30 31 2E - 30 32 2E 31 39 39 39 0A 00 00 30 35 2E 31 32 2E - 31 39 37 32 0A 00 00 30 32 2E 30 32 2E 32 30 30 - 30 0A 00 00 32 33 2E 30 31 2E 31 39 37 35 0A 00 - 00 30 31 2E 30 39 2E 31 39 39 37 0A 00 00 32 30 - 2E 30 36 2E 31 39 36 39 0A 00 00 30 32 2E 30 36 - 2E 31 39 39 37 0A 00 00 32 31 2E 30 32 2E 31 39 - 37 35 0A 00 00 31 31 2E 30 38 2E 31 39 39 37 0A - 00 00 30 31 2E 30 39 2E 31 39 37 33 0A 00 00 30 - 32 2E 30 35 2E 31 39 37 32 0A 00 00 30 31 2E 30 - 39 2E 31 39 39 35 15 00 00 45 6E 67 69 6E 65 65 - 72 69 6E 67 20 41 73 73 69 73 74 61 6E 74 0A 00 - 00 32 36 2E 30 38 2E 31 39 38 30 0A 00 00 31 39 - 2E 31 30 2E 31 39 39 38 0A 00 00 31 35 2E 30 36 - 2E 31 39 36 30 0A 00 00 30 31 2E 30 34 2E 31 39 - 39 36 0A 00 00 31 39 2E 31 32 2E 31 39 36 34 0A - 00 00 32 37 2E 31 30 2E 31 39 36 36 0A 00 00 32 - 37 2E 30 38 2E 31 39 37 34 0A 00 00 31 30 2E 30 - 37 2E 31 39 39 35 0A 00 00 33 30 2E 31 31 2E 31 - 39 37 30 0A 00 00 31 38 2E 30 33 2E 31 39 39 36 - 0A 00 00 31 37 2E 31 30 2E 31 39 34 38 0A 00 00 - 30 31 2E 30 31 2E 31 39 37 30 0A 00 00 30 36 2E - 31 30 2E 31 39 36 35 0A 00 00 32 36 2E 30 39 2E - 31 39 35 36 0A 00 00 30 33 2E 31 31 2E 31 39 39 - 33 0A 00 00 31 30 2E 30 37 2E 31 39 37 30 0A 00 - 00 30 31 2E 30 32 2E 31 39 39 38 0A 00 00 32 37 - 2E 30 32 2E 31 39 35 39 0A 00 00 30 31 2E 30 36 - 2E 31 39 39 36 0A 00 00 31 30 2E 30 32 2E 31 39 - 36 36 0A 00 00 31 38 2E 31 31 2E 31 39 39 36 27 - 00 00 43 6C 69 65 6E 74 20 4D 61 6E 61 67 65 72 - 2F 50 72 6F 70 65 72 74 79 20 50 72 6F 64 75 63 - 74 20 4D 61 6E 61 67 65 72 0A 00 00 30 31 2E 31 - 30 2E 31 39 36 32 0A 00 00 31 36 2E 31 30 2E 31 - 39 39 32 03 00 00 4D 59 52 03 00 00 50 48 50 0A - 00 00 32 38 2E 30 38 2E 31 39 35 34 0A 00 00 31 - 38 2E 30 31 2E 31 39 39 39 0A 00 00 32 35 2E 30 - 35 2E 31 39 37 34 1C 00 00 41 73 73 74 2E 4D 67 - 72 2E 20 54 6F 20 43 6C 69 65 6E 74 20 4D 67 72 - 20 54 65 61 6D 0A 00 00 30 39 2E 30 33 2E 31 39 - 35 35 0A 00 00 30 31 2E 30 37 2E 32 30 30 30 0A - 00 00 30 33 2E 30 33 2E 31 39 35 36 0A 00 00 31 - 32 2E 30 32 2E 31 39 39 36 0A 00 00 30 31 2E 30 - 39 2E 32 30 30 30 03 00 00 32 35 36 0A 00 00 32 - 31 2E 31 31 2E 31 39 35 39 0A 00 00 32 36 2E 30 - 39 2E 31 39 36 35 0A 00 00 30 31 2E 31 31 2E 31 - 39 39 38 02 00 00 6E 6F 0A 00 00 31 33 2E 30 39 - 2E 31 39 36 39 1C 00 00 41 73 73 6F 63 69 61 74 - 65 20 46 69 6E 61 6E 63 69 61 6C 20 41 64 76 69 - 73 6F 72 79 03 00 00 79 65 73 0A 00 00 30 35 2E - 31 32 2E 31 39 35 36 0A 00 00 31 32 2E 30 39 2E - 31 39 38 34 1A 00 00 53 65 6E 69 6F 72 20 4D 61 - 6E 61 67 65 72 20 45 6E 67 69 6E 65 65 72 69 6E - 67 0A 00 00 30 39 2E 30 38 2E 31 39 36 30 03 00 - 00 54 48 42 0A 00 00 32 34 2E 30 32 2E 31 39 35 - 34 0A 00 00 30 31 2E 30 36 2E 31 39 39 38 0A 00 - 00 30 38 2E 30 33 2E 31 39 36 39 0A 00 00 31 34 - 2E 30 34 2E 31 39 39 37 0A 00 00 32 31 2E 30 38 - 2E 31 39 36 37 0A 00 00 30 37 2E 30 37 2E 31 39 - 39 37 0A 00 00 33 30 2E 31 31 2E 31 39 36 30 0A - 00 00 30 32 2E 30 35 2E 31 39 39 37 0A 00 00 32 - 39 2E 30 37 2E 31 39 35 35 0A 00 00 30 33 2E 30 - 33 2E 31 39 39 37 0A 00 00 32 35 2E 30 35 2E 31 - 39 35 37 0A 00 00 30 31 2E 30 39 2E 31 39 39 36 - 0A 00 00 31 38 2E 30 31 2E 31 39 34 32 0A 00 00 - 30 31 2E 30 33 2E 31 39 39 39 0A 00 00 32 32 2E - 30 36 2E 31 39 36 38 0A 00 00 30 31 2E 31 32 2E - 31 39 39 38 0A 00 00 30 33 2E 30 35 2E 31 39 36 - 39 0A 00 00 30 31 2E 30 35 2E 31 39 39 38 0A 00 - 00 32 32 2E 30 38 2E 31 39 35 37 0A 00 00 31 35 - 2E 30 37 2E 31 39 38 35 0A 00 00 32 32 2E 30 35 - 2E 31 39 36 36 0A 00 00 30 38 2E 30 32 2E 31 39 - 39 36 0A 00 00 32 31 2E 31 32 2E 31 39 37 37 0A - 00 00 30 33 2E 30 34 2E 31 39 35 36 0A 00 00 31 - 32 2E 30 31 2E 31 39 39 36 0A 00 00 30 38 2E 30 - 37 2E 31 39 36 30 0A 00 00 30 31 2E 30 34 2E 31 - 39 39 39 0A 00 00 30 36 2E 30 31 2E 31 39 36 33 - 0A 00 00 30 31 2E 31 30 2E 31 39 39 38 0A 00 00 - 30 34 2E 30 35 2E 31 39 35 35 0A 00 00 32 33 2E - 30 39 2E 31 39 39 36 0A 00 00 32 33 2E 30 39 2E - 31 39 37 30 0A 00 00 30 39 2E 30 33 2E 31 39 36 - 37 0A 00 00 30 36 2E 30 39 2E 32 30 30 30 0A 00 - 00 31 33 2E 30 39 2E 31 39 35 32 0A 00 00 31 37 - 2E 30 31 2E 32 30 30 30 0A 00 00 31 31 2E 30 39 - 2E 31 39 36 31 0A 00 00 30 33 2E 31 31 2E 31 39 - 39 39 0A 00 00 31 39 2E 30 32 2E 31 39 36 32 0A - 00 00 30 31 2E 30 31 2E 31 39 39 36 0A 00 00 32 - 33 2E 30 37 2E 31 39 36 30 0A 00 00 32 31 2E 30 - 32 2E 32 30 30 30 0A 00 00 31 32 2E 31 31 2E 31 - 39 36 39 0A 00 00 32 34 2E 30 35 2E 31 39 39 39 - 0A 00 00 30 38 2E 31 32 2E 31 39 36 31 0A 00 00 - 30 31 2E 30 34 2E 31 39 39 37 0A 00 00 30 34 2E - 30 34 2E 31 39 36 34 12 00 00 53 65 6E 69 6F 72 - 20 55 6E 64 65 72 77 72 69 74 65 72 0A 00 00 32 - 33 2E 30 32 2E 31 39 36 35 0A 00 00 31 38 2E 30 - 39 2E 31 39 36 39 0A 00 00 30 31 2E 30 34 2E 31 - 39 39 38 0A 00 00 31 31 2E 30 33 2E 31 39 35 32 - 0A 00 00 31 37 2E 31 30 2E 31 39 37 34 0A 00 00 - 30 33 2E 30 37 2E 31 39 39 35 0A 00 00 30 32 2E - 30 34 2E 31 39 36 38 0A 00 00 31 34 2E 30 32 2E - 32 30 30 30 0A 00 00 31 34 2E 30 33 2E 31 39 36 - 31 0A 00 00 31 37 2E 30 36 2E 31 39 39 36 0A 00 - 00 33 31 2E 30 38 2E 31 39 36 35 0A 00 00 31 37 - 2E 30 32 2E 31 39 39 37 0A 00 00 30 35 2E 30 37 - 2E 31 39 36 36 0A 00 00 32 30 2E 30 33 2E 32 30 - 30 30 16 00 00 41 64 6D 69 6E 69 73 74 72 61 74 - 69 76 65 20 4F 66 66 69 63 65 72 0A 00 00 31 33 - 2E 30 36 2E 31 39 37 32 0A 00 00 33 31 2E 30 35 - 2E 32 30 30 30 0A 00 00 32 31 2E 30 33 2E 31 39 - 37 39 0A 00 00 30 32 2E 30 35 2E 32 30 30 30 0A - 00 00 32 33 2E 31 31 2E 31 39 36 38 0A 00 00 31 - 34 2E 30 32 2E 31 39 37 30 0A 00 00 31 30 2E 30 - 38 2E 31 39 39 38 0A 00 00 30 36 2E 30 39 2E 31 - 39 36 32 0A 00 00 30 33 2E 31 31 2E 31 39 39 37 - 0A 00 00 31 34 2E 30 36 2E 31 39 36 37 0A 00 00 - 31 36 2E 30 36 2E 31 39 39 37 0A 00 00 30 37 2E - 30 33 2E 31 39 36 35 0A 00 00 30 38 2E 30 35 2E - 31 39 39 36 0A 00 00 31 36 2E 30 33 2E 31 39 36 - 34 0A 00 00 32 39 2E 30 35 2E 32 30 30 30 0A 00 - 00 31 39 2E 30 38 2E 31 39 37 32 0A 00 00 32 37 - 2E 30 35 2E 31 39 37 30 0A 00 00 31 35 2E 31 31 - 2E 31 39 39 36 0A 00 00 31 36 2E 30 32 2E 31 39 - 37 31 0A 00 00 31 37 2E 31 30 2E 31 39 36 37 0A - 00 00 32 35 2E 30 38 2E 32 30 30 30 0A 00 00 32 - 33 2E 30 36 2E 31 39 36 36 0A 00 00 31 33 2E 30 - 38 2E 31 39 35 35 0A 00 00 32 30 2E 31 31 2E 31 - 39 36 32 0A 00 00 31 35 2E 30 35 2E 31 39 38 39 - 0A 00 00 32 35 2E 31 31 2E 31 39 36 39 0A 00 00 - 30 32 2E 30 31 2E 31 39 39 37 0A 00 00 31 33 2E - 31 31 2E 31 39 34 36 0A 00 00 30 31 2E 30 31 2E - 31 39 37 37 0F 00 00 52 65 6B 72 2E 2F 42 65 74 - 72 65 75 75 6E 67 0A 00 00 32 35 2E 30 32 2E 31 - 39 36 31 0A 00 00 30 31 2E 30 35 2E 31 39 39 33 - 0A 00 00 31 38 2E 31 31 2E 31 39 37 35 0A 00 00 - 33 30 2E 30 39 2E 31 39 37 32 0A 00 00 31 38 2E - 31 32 2E 31 39 39 37 0A 00 00 33 31 2E 30 38 2E - 31 39 35 38 17 00 00 45 6E 67 69 6E 65 65 72 69 - 6E 67 20 43 6F 6F 72 64 69 6E 61 74 6F 72 0A 00 - 00 31 31 2E 30 34 2E 31 39 36 30 0A 00 00 30 31 - 2E 30 31 2E 31 39 39 37 0A 00 00 30 37 2E 30 35 - 2E 31 39 38 30 0A 00 00 31 39 2E 30 36 2E 32 30 - 30 30 0A 00 00 33 30 2E 30 35 2E 31 39 36 38 0A - 00 00 30 37 2E 30 36 2E 31 39 36 36 0A 00 00 30 - 31 2E 31 31 2E 31 39 39 39 0A 00 00 32 36 2E 30 - 33 2E 31 39 36 34 0A 00 00 31 34 2E 30 38 2E 32 - 30 30 30 0A 00 00 32 37 2E 30 33 2E 31 39 35 39 - 0A 00 00 31 30 2E 30 35 2E 31 39 37 33 03 00 00 - 49 4E 52 0A 00 00 30 37 2E 30 33 2E 31 39 36 37 - 0A 00 00 30 34 2E 30 38 2E 31 39 37 36 0A 00 00 - 32 37 2E 31 32 2E 31 39 36 30 0A 00 00 30 31 2E - 31 30 2E 31 39 39 35 0A 00 00 31 31 2E 30 31 2E - 31 39 34 38 0A 00 00 30 32 2E 30 34 2E 31 39 39 - 37 0A 00 00 33 30 2E 30 37 2E 31 39 37 35 0A 00 - 00 31 39 2E 31 32 2E 31 39 36 39 0A 00 00 30 31 - 2E 30 33 2E 32 30 30 30 0A 00 00 30 33 2E 30 33 - 2E 31 39 36 38 0A 00 00 30 32 2E 30 37 2E 31 39 - 37 34 02 00 00 53 57 04 00 00 33 31 35 38 04 00 - 00 33 31 39 32 10 00 00 55 57 20 4D 61 6E 61 67 - 65 72 20 53 57 49 46 54 04 00 00 33 32 32 30 02 - 00 00 53 32 04 00 00 33 32 34 31 04 00 00 33 32 - 34 32 04 00 00 33 32 37 33 13 00 00 54 72 65 61 - 74 79 20 55 57 20 53 75 70 70 2E 20 50 2F 43 04 - 00 00 33 32 38 34 04 00 00 33 32 38 38 0F 00 00 - 54 65 61 6D 20 4C 65 61 64 65 72 20 53 53 43 04 - 00 00 33 33 30 35 16 00 00 55 57 20 46 69 6E 61 - 6E 63 69 61 6C 20 53 6F 6C 75 74 69 6F 6E 73 04 - 00 00 33 33 35 36 04 00 00 33 33 35 39 0C 00 00 - 48 65 61 64 20 53 49 43 53 2F 6E 74 02 00 00 43 - 32 04 00 00 33 33 36 38 13 00 00 55 6E 64 65 72 - 77 72 69 74 65 72 20 46 61 6B 20 48 55 4B 02 00 - 00 44 4E 04 00 00 33 33 37 37 13 00 00 44 65 61 - 6C 20 4B 6F 6F 72 64 69 6E 61 74 6F 72 2F 55 57 - 04 00 00 33 33 38 30 12 00 00 55 6E 64 65 72 77 - 72 69 74 65 72 20 44 45 53 49 47 4E 04 00 00 33 - 33 38 39 14 00 00 4B 6E 6F 77 6C 65 64 67 65 20 - 45 78 70 65 72 74 20 53 53 43 04 00 00 33 34 30 - 35 04 00 00 33 34 31 33 04 00 00 33 34 31 35 04 - 00 00 33 34 32 33 02 00 00 45 57 04 00 00 33 34 - 34 33 16 00 00 45 6E 67 69 6E 65 65 72 69 6E 67 - 20 55 57 20 53 75 70 70 6F 72 74 04 00 00 33 34 - 35 34 04 00 00 33 34 36 31 02 00 00 45 42 04 00 - 00 33 34 38 30 04 00 00 33 35 30 38 10 00 00 53 - 65 63 74 69 6F 6E 20 48 65 61 64 20 53 53 43 04 - 00 00 33 35 32 39 04 00 00 33 35 34 37 16 00 00 - 42 75 73 69 6E 65 73 73 20 41 73 73 69 73 74 61 - 6E 74 20 53 53 43 04 00 00 33 35 35 34 04 00 00 - 33 35 36 36 02 00 00 50 34 04 00 00 33 36 31 36 - 10 00 00 55 57 20 46 61 63 2E 20 50 72 6F 70 65 - 72 74 79 04 00 00 33 36 34 31 04 00 00 33 36 35 - 34 04 00 00 33 36 39 35 04 00 00 33 37 38 36 18 - 00 00 55 57 20 4D 61 6E 61 67 65 72 20 46 61 63 - 2E 20 50 72 6F 70 65 72 74 79 04 00 00 33 38 31 - 39 04 00 00 33 38 33 33 18 00 00 55 57 20 53 75 - 70 70 6F 72 74 20 46 61 63 2E 20 43 61 73 75 61 - 6C 74 79 02 00 00 45 43 04 00 00 33 38 36 30 04 - 00 00 33 38 37 34 02 00 00 50 36 04 00 00 33 39 - 35 36 10 00 00 55 6E 64 65 72 77 72 69 74 65 72 - 20 53 61 63 68 04 00 00 33 39 38 38 16 00 00 41 - 64 6D 69 6E 69 73 74 72 61 74 69 6F 6E 20 46 61 - 6B 20 48 55 4B 04 00 00 33 39 39 36 02 00 00 4E - 45 04 00 00 34 30 32 39 12 00 00 4E 75 63 6C 65 - 61 72 20 55 57 20 53 75 70 70 6F 72 74 04 00 00 - 34 30 34 36 04 00 00 34 30 38 34 04 00 00 34 30 - 38 39 04 00 00 34 30 39 32 04 00 00 34 30 39 37 - 04 00 00 34 31 33 36 04 00 00 34 31 37 32 04 00 - 00 34 32 33 30 04 00 00 34 32 35 31 04 00 00 34 - 32 39 30 0A 00 00 55 57 20 53 75 70 70 6F 72 74 - 04 00 00 34 33 38 35 15 00 00 4D 61 6E 61 67 65 - 72 20 41 63 74 2E 20 53 65 72 76 69 63 65 73 04 - 00 00 34 34 30 33 04 00 00 34 34 31 34 04 00 00 - 34 34 33 38 04 00 00 34 34 34 33 04 00 00 34 34 - 37 32 04 00 00 34 34 37 34 04 00 00 34 35 31 31 - 04 00 00 34 35 33 32 04 00 00 34 35 34 36 02 00 - 00 54 50 04 00 00 34 35 37 34 04 00 00 34 35 38 - 30 04 00 00 34 36 30 39 04 00 00 34 36 33 32 04 - 00 00 34 36 33 35 0E 00 00 53 49 43 53 6E 74 20 - 50 72 6F 6A 65 6B 74 04 00 00 34 39 34 33 02 00 - 00 45 48 04 00 00 34 39 35 37 04 00 00 34 39 35 - 39 04 00 00 35 30 31 30 04 00 00 35 30 32 30 04 - 00 00 35 30 32 32 04 00 00 35 30 36 31 04 00 00 - 35 30 38 33 04 00 00 35 31 31 35 04 00 00 35 31 - 33 35 04 00 00 35 31 38 32 04 00 00 35 31 38 34 - 0E 00 00 48 52 20 43 6F 6E 74 72 6F 6C 6C 69 6E - 67 04 00 00 35 31 39 35 04 00 00 35 32 32 33 04 - 00 00 35 32 36 30 15 00 00 47 6C 6F 62 61 6C 20 - 43 6C 69 65 6E 74 20 4D 61 6E 61 67 65 72 04 00 - 00 35 32 36 34 04 00 00 35 32 37 30 04 00 00 35 - 32 39 34 04 00 00 35 33 30 37 19 00 00 43 6C 69 - 65 6E 74 20 4D 61 6E 61 67 65 6D 65 6E 74 20 53 - 75 70 70 6F 72 74 04 00 00 35 33 31 32 02 00 00 - 4D 4C 04 00 00 35 33 31 38 0F 00 00 45 76 65 6E - 74 20 4D 61 72 6B 65 74 69 6E 67 04 00 00 35 33 - 32 32 14 00 00 55 6E 64 65 72 77 72 69 74 65 72 - 20 46 61 6B 20 53 61 63 68 04 00 00 35 33 32 37 - 04 00 00 35 33 33 33 04 00 00 35 33 35 37 04 00 - 00 35 33 35 38 04 00 00 35 34 32 35 18 00 00 4D - 67 72 20 42 55 53 20 50 65 72 66 6F 72 6D 61 6E - 63 65 20 54 65 61 6D 04 00 00 35 35 30 34 04 00 - 00 35 35 38 34 10 00 00 41 73 73 69 73 74 61 6E - 74 20 44 4F 4F 20 45 55 04 00 00 35 35 39 37 04 - 00 00 35 36 30 35 04 00 00 35 36 30 38 04 00 00 - 35 36 31 37 04 00 00 35 36 32 33 04 00 00 35 36 - 38 31 0F 00 00 48 65 61 64 20 50 43 20 53 75 70 - 70 6F 72 74 04 00 00 35 37 30 31 04 00 00 35 37 - 30 34 04 00 00 35 37 32 31 14 00 00 52 65 6C 61 - 74 69 6F 6E 20 4D 61 6E 61 67 65 72 20 53 53 43 - 04 00 00 35 37 33 36 04 00 00 35 37 34 38 04 00 - 00 35 37 35 34 04 00 00 35 37 35 35 17 00 00 50 - 72 6F 6A 65 63 74 20 4D 62 72 20 73 77 69 66 74 - 72 65 2E 63 6F 6D 04 00 00 35 37 35 36 04 00 00 - 35 37 36 32 0F 00 00 44 65 70 75 74 79 20 48 65 - 61 64 20 53 53 43 04 00 00 35 37 38 30 04 00 00 - 35 37 38 34 04 00 00 35 37 38 36 04 00 00 35 38 - 31 35 04 00 00 35 38 32 31 04 00 00 35 38 34 30 - 04 00 00 35 39 32 31 04 00 00 35 39 33 30 04 00 - 00 35 39 33 32 12 00 00 4E 75 63 6C 65 61 72 20 - 55 57 20 4D 61 6E 61 67 65 72 04 00 00 35 39 34 - 36 04 00 00 35 39 34 39 04 00 00 35 39 35 34 04 - 00 00 35 39 35 39 04 00 00 35 39 36 32 04 00 00 - 35 39 38 34 04 00 00 36 30 37 34 04 00 00 36 31 - 31 30 04 00 00 36 31 31 33 04 00 00 36 31 32 36 - 04 00 00 36 31 38 31 17 00 00 50 72 6F 6A 65 63 - 74 20 4D 67 72 20 73 77 69 66 74 72 65 2E 63 6F - 6D 04 00 00 36 31 38 37 04 00 00 36 32 31 39 19 - 00 00 48 65 61 64 20 6F 66 20 44 69 76 2E 20 45 - 78 65 63 2E 20 4F 66 66 69 63 65 04 00 00 36 33 - 30 31 04 00 00 36 33 35 38 04 00 00 36 34 34 31 - 04 00 00 36 34 35 39 04 00 00 36 35 31 34 04 00 - 00 36 35 32 37 04 00 00 36 35 33 30 13 00 00 4D - 61 72 69 6E 65 20 55 6E 64 65 72 77 72 69 74 69 - 6E 67 04 00 00 36 35 33 38 04 00 00 36 36 34 35 - 04 00 00 36 36 35 38 04 00 00 36 36 36 35 04 00 - 00 36 36 39 39 04 00 00 36 37 33 37 15 00 00 41 - 70 70 6C 69 63 61 74 69 6F 6E 20 53 75 70 70 6F - 72 74 65 72 04 00 00 36 37 34 30 04 00 00 36 37 - 34 39 04 00 00 36 37 35 30 0B 00 00 54 72 61 69 - 6E 65 72 20 53 53 43 04 00 00 36 37 39 30 04 00 - 00 36 38 30 35 04 00 00 36 38 31 38 19 00 00 48 - 65 61 64 20 49 6E 64 69 76 69 64 75 61 6C 20 52 - 65 70 6F 72 74 69 6E 67 04 00 00 36 38 36 39 04 - 00 00 36 38 37 31 04 00 00 36 38 38 32 04 00 00 - 36 38 38 33 04 00 00 36 38 38 35 04 00 00 36 39 - 34 34 04 00 00 36 39 34 36 04 00 00 36 39 35 30 - 04 00 00 37 30 31 30 04 00 00 37 30 32 32 04 00 - 00 37 30 32 35 04 00 00 37 30 32 36 04 00 00 37 - 30 37 38 04 00 00 37 30 38 37 04 00 00 37 31 30 - 36 04 00 00 37 31 31 38 04 00 00 37 31 31 39 12 - 00 00 41 63 74 75 61 72 69 61 6C 20 53 65 72 76 - 69 63 65 73 04 00 00 37 31 33 36 04 00 00 37 31 - 36 32 04 00 00 37 31 37 39 04 00 00 37 32 36 39 - 04 00 00 37 33 34 38 04 00 00 37 34 30 39 04 00 - 00 37 34 31 38 04 00 00 37 34 31 39 15 00 00 4D - 67 72 20 49 54 20 49 6E 66 72 61 73 74 72 75 63 - 74 75 72 65 04 00 00 37 34 37 37 04 00 00 37 35 - 30 31 04 00 00 37 35 37 35 04 00 00 37 35 37 36 - 04 00 00 37 35 39 35 04 00 00 37 36 30 32 04 00 - 00 37 36 30 36 04 00 00 37 39 34 32 04 00 00 37 - 39 37 32 04 00 00 37 39 39 31 04 00 00 38 30 30 - 39 04 00 00 38 30 32 30 04 00 00 38 30 32 39 04 - 00 00 38 30 33 34 04 00 00 38 30 33 37 14 00 00 - 52 65 70 6F 72 74 69 6E 67 20 53 70 65 63 69 61 - 6C 69 73 74 04 00 00 38 30 35 36 14 00 00 53 65 - 6B 72 65 74 61 72 69 61 74 20 4F 70 65 72 2E 20 - 45 55 04 00 00 38 30 36 37 04 00 00 38 30 38 31 - 04 00 00 38 31 31 31 04 00 00 38 31 33 36 15 00 - 00 41 73 73 69 73 74 61 6E 74 20 74 6F 20 48 65 - 61 64 20 53 53 43 04 00 00 38 32 31 39 04 00 00 - 38 32 39 38 04 00 00 38 33 31 39 04 00 00 38 33 - 34 32 04 00 00 38 33 36 33 04 00 00 38 34 30 33 - 04 00 00 38 34 30 34 04 00 00 38 34 30 36 04 00 - 00 38 34 31 32 04 00 00 38 34 31 33 04 00 00 38 - 34 31 34 04 00 00 38 34 31 35 11 00 00 53 65 6E - 69 6F 72 20 55 57 20 46 61 6B 20 48 55 4B 04 00 - 00 38 34 32 39 04 00 00 38 34 33 31 04 00 00 38 - 34 33 33 04 00 00 38 34 33 37 04 00 00 38 34 34 - 30 04 00 00 38 34 35 31 04 00 00 38 34 35 35 04 - 00 00 38 34 36 36 04 00 00 38 34 36 37 04 00 00 - 38 34 36 38 04 00 00 38 34 37 34 04 00 00 38 34 - 38 30 04 00 00 38 34 38 38 04 00 00 38 34 38 39 - 04 00 00 38 34 39 36 12 00 00 50 72 6F 6A 65 6B - 74 20 53 70 65 7A 69 61 6C 69 73 74 04 00 00 38 - 35 30 34 04 00 00 38 35 30 37 04 00 00 38 35 30 - 38 04 00 00 38 35 31 35 04 00 00 38 35 31 39 04 - 00 00 38 35 32 30 04 00 00 38 35 32 33 04 00 00 - 38 35 33 39 04 00 00 38 35 35 33 04 00 00 38 35 - 36 30 04 00 00 38 35 36 34 04 00 00 38 35 36 35 - 18 00 00 43 6C 69 65 6E 74 20 4D 61 6E 61 67 65 - 6D 65 6E 74 20 4D 65 6D 62 65 72 04 00 00 38 35 - 36 36 04 00 00 38 35 36 37 04 00 00 38 35 36 38 - 04 00 00 38 35 37 32 04 00 00 38 35 37 34 04 00 - 00 38 35 38 30 04 00 00 38 35 38 31 04 00 00 38 - 35 38 34 04 00 00 38 35 38 35 04 00 00 38 35 39 - 36 04 00 00 38 36 30 30 04 00 00 38 36 32 34 04 - 00 00 38 36 32 38 04 00 00 38 36 33 39 16 00 00 - 55 57 20 4D 61 6E 61 67 65 72 20 73 77 69 66 74 - 72 65 2E 63 6F 6D 04 00 00 38 36 34 33 04 00 00 - 38 36 35 37 19 00 00 48 65 61 64 20 6F 66 20 50 - 6C 61 6E 2E 26 43 6F 6E 74 72 6F 6C 6C 69 6E 67 - 04 00 00 38 37 31 33 10 00 00 55 57 20 46 61 63 - 2E 20 43 61 73 75 61 6C 74 79 04 00 00 38 37 33 - 39 04 00 00 38 37 34 35 04 00 00 38 37 35 30 19 - 00 00 55 57 20 4D 61 6E 61 67 65 72 20 46 69 6E - 61 6E 63 69 61 6C 20 53 6F 6C 2E 04 00 00 38 37 - 35 33 04 00 00 38 37 36 33 04 00 00 38 38 30 30 - 19 00 00 49 54 20 4D 67 72 20 42 75 73 2E 20 45 - 78 65 63 2E 20 53 79 73 74 65 6D 73 04 00 00 38 - 38 39 38 04 00 00 38 39 32 30 04 00 00 39 31 31 - 36 04 00 00 39 31 32 30 04 00 00 39 31 32 36 04 - 00 00 39 31 35 37 04 00 00 39 31 35 38 04 00 00 - 39 31 37 39 04 00 00 39 33 30 37 04 00 00 39 33 - 32 37 04 00 00 39 33 39 39 04 00 00 39 34 39 35 - 04 00 00 39 34 39 37 04 00 00 39 35 33 33 04 00 - 00 39 36 31 33 04 00 00 39 36 35 31 04 00 00 39 - 37 35 31 05 00 00 31 30 30 35 37 05 00 00 31 30 - 32 31 34 05 00 00 31 30 32 32 36 05 00 00 31 30 - 32 32 38 05 00 00 31 30 32 33 32 05 00 00 31 30 - 32 33 38 05 00 00 31 30 32 34 34 05 00 00 31 30 - 32 34 38 05 00 00 31 30 32 35 30 05 00 00 31 30 - 32 38 34 05 00 00 31 30 33 37 38 05 00 00 31 30 - 34 31 31 05 00 00 31 30 34 35 33 05 00 00 31 30 - 34 38 31 05 00 00 31 30 35 33 33 05 00 00 31 30 - 35 36 37 16 00 00 48 65 61 64 20 49 6E 74 65 72 - 6E 61 74 2E 20 53 75 70 70 6F 72 74 05 00 00 31 - 30 35 38 34 19 00 00 49 54 20 48 65 61 64 20 5A - 48 20 26 20 4C 6F 63 2E 20 4F 66 66 69 63 65 73 - 05 00 00 31 30 36 30 30 05 00 00 31 30 36 30 37 - 05 00 00 31 30 36 30 38 05 00 00 31 30 36 30 39 - 05 00 00 31 30 36 31 30 05 00 00 31 30 36 31 36 - 05 00 00 31 30 36 32 34 05 00 00 31 30 37 30 31 - 05 00 00 31 30 37 33 34 05 00 00 31 30 37 33 35 - 02 00 00 41 47 05 00 00 31 30 37 34 38 05 00 00 - 31 30 38 36 30 16 00 00 49 54 20 4D 61 6E 61 67 - 65 72 20 73 77 69 66 74 72 65 2E 63 6F 6D 05 00 - 00 31 30 38 39 38 05 00 00 31 30 39 38 39 05 00 - 00 31 30 39 39 31 05 00 00 31 31 31 30 36 0F 00 - 00 43 6F 73 74 20 43 6F 6E 74 72 6F 6C 6C 65 72 - 05 00 00 31 31 31 33 37 05 00 00 31 31 31 34 31 - 19 00 00 53 61 63 68 62 65 61 72 62 2E 44 69 76 - 2E 45 78 65 63 2E 4F 66 66 69 63 65 05 00 00 31 - 31 31 35 34 05 00 00 31 31 32 33 34 05 00 00 31 - 31 32 33 37 05 00 00 31 31 32 37 35 05 00 00 31 - 31 32 37 36 05 00 00 31 31 33 30 39 05 00 00 31 - 31 33 37 33 05 00 00 31 31 33 39 36 05 00 00 31 - 31 35 32 33 05 00 00 31 31 36 37 34 05 00 00 31 - 31 36 39 39 05 00 00 31 31 37 32 33 05 00 00 31 - 31 37 33 33 05 00 00 31 31 37 34 38 05 00 00 31 - 31 37 37 36 05 00 00 31 31 37 38 32 05 00 00 31 - 31 38 31 38 05 00 00 31 31 38 32 37 05 00 00 31 - 31 38 33 35 05 00 00 31 31 38 38 32 05 00 00 31 - 31 39 33 35 05 00 00 31 31 39 33 36 05 00 00 31 - 31 39 34 39 05 00 00 31 32 30 30 38 05 00 00 31 - 32 30 32 34 05 00 00 31 32 30 38 34 05 00 00 31 - 32 31 33 34 05 00 00 31 32 31 35 36 05 00 00 31 - 32 31 38 35 05 00 00 31 32 32 31 31 05 00 00 31 - 32 32 38 37 05 00 00 31 32 33 31 39 05 00 00 31 - 32 33 36 34 05 00 00 31 32 33 39 30 05 00 00 31 - 32 34 34 39 02 00 00 50 4D 05 00 00 31 32 34 35 - 37 0F 00 00 48 65 61 64 20 50 4D 4F 20 45 75 72 - 6F 70 65 01 00 00 34 02 00 00 32 34 02 00 00 32 - 37 02 00 00 34 31 01 00 00 41 02 00 00 35 31 02 - 00 00 36 30 02 00 00 36 35 02 00 00 37 31 02 00 - 00 38 30 02 00 00 38 38 02 00 00 39 39 19 00 00 - 43 6C 69 65 6E 74 20 4D 67 72 20 47 6C 6F 62 61 - 6C 20 43 6C 69 65 6E 74 73 03 00 00 31 31 38 03 - 00 00 31 32 39 03 00 00 31 33 32 16 00 00 43 6C - 61 69 6D 73 20 4D 67 72 20 73 77 69 66 74 72 65 - 2E 63 6F 6D 03 00 00 31 37 30 03 00 00 31 37 33 - 11 00 00 4D 61 6E 61 67 65 72 20 4D 61 72 69 6E - 65 20 55 57 03 00 00 31 38 39 11 00 00 55 57 20 - 4D 61 6E 61 67 65 72 20 44 45 53 49 47 4E 03 00 - 00 36 37 38 15 00 00 55 6E 64 65 72 77 72 69 74 - 65 72 20 44 E9 63 65 6E 6E 61 6C 65 03 00 00 38 - 39 32 03 00 00 39 32 38 03 00 00 39 33 38 03 00 - 00 39 37 33 03 00 00 39 37 39 04 00 00 31 30 33 - 30 04 00 00 31 30 37 30 0F 00 00 53 6F 52 69 20 - 55 57 20 4D 61 6E 61 67 65 72 04 00 00 31 31 31 - 38 04 00 00 31 34 37 35 04 00 00 31 35 30 31 04 - 00 00 31 35 32 31 04 00 00 31 35 35 38 04 00 00 - 31 35 39 32 04 00 00 31 36 30 30 04 00 00 31 36 - 31 30 04 00 00 31 36 32 39 04 00 00 31 36 35 35 - 04 00 00 31 37 30 30 16 00 00 48 65 61 64 20 6F - 66 20 44 69 76 2E 20 48 52 20 5A FC 72 69 63 68 - 04 00 00 31 37 31 39 04 00 00 31 37 36 34 04 00 - 00 31 37 37 34 04 00 00 31 38 30 34 04 00 00 31 - 38 36 36 04 00 00 31 39 30 31 04 00 00 31 39 33 - 37 04 00 00 32 30 30 35 04 00 00 32 30 34 38 04 - 00 00 32 30 37 34 04 00 00 32 31 30 32 04 00 00 - 32 31 33 37 04 00 00 32 31 36 37 04 00 00 32 31 - 38 31 04 00 00 32 32 31 30 04 00 00 32 32 34 34 - 04 00 00 32 32 37 32 04 00 00 32 32 38 30 04 00 - 00 32 33 31 32 04 00 00 32 33 32 36 17 00 00 44 - 69 76 2E 20 4F 70 65 72 61 74 2E 20 4F 66 66 69 - 63 65 72 20 45 55 04 00 00 32 33 36 34 04 00 00 - 32 33 39 30 04 00 00 32 34 31 30 04 00 00 32 34 - 32 38 04 00 00 32 34 33 31 04 00 00 32 34 35 35 - 12 00 00 48 65 61 64 20 6F 66 20 53 53 43 20 5A - 75 72 69 63 68 04 00 00 32 36 30 33 04 00 00 32 - 36 32 35 04 00 00 32 36 37 32 04 00 00 32 36 39 - 37 04 00 00 32 37 33 33 18 00 00 49 6E 6E 6F 76 - 61 74 69 6F 6E 2F 4B 6E 6F 77 6C 65 64 67 65 20 - 4D 67 72 04 00 00 32 37 33 39 04 00 00 32 37 38 - 36 04 00 00 32 38 30 38 0B 00 00 53 74 61 62 73 - 6C 65 69 74 65 72 04 00 00 32 38 31 31 17 00 00 - 48 65 61 64 20 6F 66 20 4D 61 72 6B 65 74 69 6E - 67 20 53 20 26 20 4C 04 00 00 32 38 31 36 17 00 - 00 49 54 20 4D 67 72 20 52 65 69 6E 73 75 72 2E - 20 53 79 73 74 65 6D 73 04 00 00 32 38 32 30 04 - 00 00 32 38 37 33 05 00 00 31 32 35 30 34 05 00 - 00 31 32 35 33 34 05 00 00 31 32 35 34 33 05 00 - 00 31 32 35 36 36 05 00 00 31 32 35 39 38 05 00 - 00 31 32 36 31 31 05 00 00 31 32 36 33 35 05 00 - 00 31 32 36 35 38 05 00 00 31 32 36 36 36 01 00 - 00 4E 05 00 00 31 32 36 37 36 05 00 00 31 32 37 - 33 36 05 00 00 31 32 37 36 38 05 00 00 31 32 38 - 30 35 05 00 00 31 32 38 32 34 05 00 00 31 32 38 - 35 30 05 00 00 31 32 39 33 31 05 00 00 31 33 30 - 30 32 diff --git a/test-data/spreadsheet/BigSSTRecord2CR7 b/test-data/spreadsheet/BigSSTRecord2CR7 deleted file mode 100644 index 571474ebd..000000000 --- a/test-data/spreadsheet/BigSSTRecord2CR7 +++ /dev/null @@ -1,105 +0,0 @@ - 3C 00 86 06 05 00 00 31 33 30 37 30 05 00 - 00 31 32 35 36 37 0F 00 00 4B 56 2D 50 72 61 6B - 74 69 6B 61 6E 74 69 6E 02 00 00 33 32 04 00 00 - 35 38 37 32 04 00 00 38 34 39 35 05 00 00 31 30 - 34 39 39 05 00 00 31 30 35 30 31 05 00 00 31 30 - 35 30 33 05 00 00 31 30 35 30 35 05 00 00 31 30 - 36 38 39 05 00 00 31 30 36 39 31 05 00 00 31 30 - 37 35 32 05 00 00 31 30 38 35 33 05 00 00 31 30 - 38 35 34 05 00 00 31 30 38 35 36 05 00 00 31 30 - 38 35 37 05 00 00 31 30 38 38 30 16 00 00 50 72 - 6F 6A 65 63 74 20 4F 66 66 69 63 65 20 4D 61 6E - 61 67 65 72 13 00 00 43 68 69 65 66 20 4C 65 67 - 61 6C 20 4F 66 66 69 63 65 72 18 00 00 53 65 63 - 74 6F 72 20 53 74 72 61 74 65 67 69 73 74 20 45 - 75 72 6F 70 65 12 00 00 48 65 61 64 20 6F 66 20 - 41 75 74 6F 6D 61 74 69 6F 6E 17 00 00 48 65 61 - 64 20 46 75 6E 64 20 6F 66 20 46 75 6E 64 73 20 - 55 6E 69 74 0C 00 00 43 4D 20 41 73 73 69 73 74 - 61 6E 74 18 00 00 48 65 61 64 20 48 75 6D 61 6E - 20 52 65 73 6F 75 72 63 65 73 20 53 52 49 14 00 - 00 51 75 61 6E 74 69 74 61 74 69 76 65 20 41 6E - 61 6C 79 73 74 12 00 00 55 6D 77 65 6C 74 62 65 - 61 75 66 74 72 61 67 74 65 72 12 00 00 54 68 69 - 72 64 20 79 65 61 72 20 41 6E 61 6C 79 73 74 17 - 00 00 48 65 61 64 20 43 75 73 74 6F 64 79 20 4D - 61 6E 61 67 65 6D 65 6E 74 0E 00 00 56 69 63 65 - 20 50 72 65 73 69 64 65 6E 74 11 00 00 50 72 6F - 6A 65 6B 74 6C 65 69 74 65 72 20 52 53 41 0D 00 - 00 50 72 6F 67 72 61 6D 6D 69 65 72 65 72 19 00 - 00 44 65 70 2E 48 65 61 64 20 46 69 6E 61 6E 63 - 2E 20 41 63 63 6F 75 6E 74 2E 19 00 00 53 65 6E - 69 6F 72 20 49 6E 66 6F 72 6D 2E 20 53 70 65 63 - 69 61 6C 69 73 74 14 00 00 48 65 61 64 20 43 6C - 69 65 6E 74 20 52 65 6C 61 74 69 6F 6E 0A 00 00 - 43 6F 6E 73 75 6C 74 61 6E 74 15 00 00 48 65 61 - 64 20 42 75 73 69 6E 65 73 73 20 41 6E 61 6C 79 - 73 74 18 00 00 48 65 61 64 20 43 6C 69 65 6E 74 - 20 4D 67 6D 74 20 53 79 73 74 65 6D 73 15 00 00 - 48 65 61 64 20 4B 6E 6F 77 6C 2E 26 49 6E 66 2E - 20 4D 67 6D 74 19 00 00 4C 65 69 74 65 72 20 42 - 75 63 68 68 2F 42 65 72 69 63 68 74 65 72 73 74 - 2E 19 00 00 50 72 6F 6A 2E 4D 67 72 2E 20 43 65 - 6E 74 72 65 20 6F 66 20 43 6F 6D 70 2E 19 00 00 - 41 73 73 2E 20 47 72 70 2E 20 43 6F 6D 70 6C 69 - 61 6E 63 65 20 4F 66 66 2E 10 00 00 48 65 61 64 - 20 6F 66 20 52 65 73 65 61 72 63 68 12 00 00 53 - 6F 66 74 77 61 72 65 20 41 72 63 68 69 74 65 63 - 74 13 00 00 48 65 61 64 20 6F 66 20 49 54 20 54 - 72 61 69 6E 69 6E 67 19 00 00 4F 70 65 72 61 74 - 69 76 65 72 20 42 65 74 72 69 65 62 73 6C 65 69 - 74 65 72 12 00 00 41 64 6D 69 6E 2E 20 4D 69 74 - 61 72 62 65 69 74 65 72 02 00 00 47 57 16 00 00 - 54 65 61 6D 6C 2E 20 43 6F 73 74 20 41 63 63 6F - 75 6E 74 69 6E 67 18 00 00 48 65 61 64 20 52 65 - 67 69 6F 6E 61 6C 20 50 4D 4F 20 5A 75 72 69 63 - 68 04 00 00 35 37 34 34 04 00 00 36 33 30 37 05 - 00 00 31 30 39 30 31 04 00 00 36 34 35 31 04 00 - 00 34 35 30 30 05 00 00 31 31 36 34 37 05 00 00 - 31 32 37 30 30 04 00 00 33 38 34 30 04 00 00 36 - 37 39 33 05 00 00 31 32 39 30 36 04 00 00 35 33 - 32 36 04 00 00 36 38 35 33 05 00 00 31 32 38 35 - 34 04 00 00 35 35 38 31 05 00 00 31 32 39 36 35 - 04 00 00 33 30 38 37 04 00 00 34 33 36 31 04 00 - 00 33 39 37 30 04 00 00 35 32 38 39 04 00 00 38 - 35 38 38 05 00 00 31 30 36 39 30 05 00 00 31 33 - 31 34 37 04 00 00 36 39 38 34 05 00 00 31 31 31 - 33 31 04 00 00 36 38 32 30 04 00 00 34 33 35 36 - 04 00 00 35 35 38 32 04 00 00 33 30 31 34 04 00 - 00 31 34 34 33 04 00 00 35 32 38 36 04 00 00 37 - 32 32 37 05 00 00 31 31 39 37 32 04 00 00 34 35 - 35 34 04 00 00 34 32 36 35 04 00 00 33 36 35 36 - 04 00 00 38 30 37 31 03 00 00 32 39 30 04 00 00 - 35 39 31 38 04 00 00 36 39 33 31 04 00 00 35 36 - 33 30 04 00 00 36 35 34 30 04 00 00 38 34 35 34 - 04 00 00 38 30 36 31 04 00 00 35 30 31 35 05 00 - 00 34 32 31 30 34 0C 00 00 55 6E 64 65 72 77 72 - 69 74 65 72 2C 04 00 00 37 32 35 36 04 00 00 37 - 36 37 34 04 00 00 37 37 38 36 04 00 00 38 37 31 - 34 04 00 00 38 37 31 39 04 00 00 36 33 36 35 04 - 00 00 38 39 35 37 04 00 00 32 37 31 38 04 00 00 - 36 32 39 31 05 00 00 31 31 39 34 37 04 00 00 33 - 30 33 33 04 00 00 38 34 36 30 04 00 00 36 32 36 - 36 04 00 00 33 32 39 39 04 00 00 37 38 38 39 04 - 00 00 32 37 33 30 05 00 00 31 31 33 38 31 05 00 - 00 31 30 36 34 38 04 00 00 37 33 37 33 04 00 00 - 35 30 35 30 04 00 00 38 36 31 39 04 00 00 37 31 - 34 36 04 00 00 34 33 31 33 04 00 00 35 38 33 35 - 04 00 00 38 37 35 38 04 00 00 37 30 37 31 05 00 - 00 31 33 30 36 36 04 00 00 37 37 36 35 04 00 00 - 34 34 36 38 05 00 00 31 31 38 36 31 04 00 00 35 - 38 39 34 04 00 00 32 34 33 38 04 00 00 33 31 38 - 38 04 00 00 34 32 35 37 03 00 00 31 35 38 04 00 - 00 39 32 34 39 12 00 00 41 73 73 6F 63 69 61 74 - 65 20 44 69 72 65 63 74 6F 72 03 00 00 36 31 36 - 05 00 00 31 31 30 36 34 04 00 00 34 36 32 36 04 - 00 00 36 33 31 37 05 00 00 31 31 35 35 33 05 00 - 00 31 31 32 39 38 04 00 00 32 32 35 34 04 00 00 - 39 35 33 31 04 00 00 38 33 31 38 02 00 00 34 35 - 04 00 00 35 34 33 30 04 00 00 37 30 37 36 04 00 - 00 36 38 36 34 05 00 00 31 32 34 35 38 04 00 00 - 35 34 38 35 05 00 00 38 30 30 39 33 04 00 00 35 - 39 37 31 04 00 00 36 34 37 32 04 00 00 36 36 31 - 39 05 00 00 31 31 34 31 30 04 00 00 35 32 39 36 - 04 00 00 38 36 33 30 04 00 00 38 30 32 38 04 00 - 00 31 38 32 36 04 00 00 36 38 35 31 diff --git a/test-data/spreadsheet/BigSSTRecordCR b/test-data/spreadsheet/BigSSTRecordCR deleted file mode 100644 index c35783de8..000000000 --- a/test-data/spreadsheet/BigSSTRecordCR +++ /dev/null @@ -1,225 +0,0 @@ -3C 00 FD 0D 00 6C 05 00 00 47 2D 35 31 35 04 -00 00 32 37 38 38 04 00 00 32 32 34 38 04 00 00 -34 38 30 37 03 00 00 32 32 37 13 00 00 50 6C 79 -6D 6F 75 74 68 20 50 54 20 43 72 75 69 73 65 72 -18 00 00 53 74 61 72 20 54 72 65 6B 20 53 70 61 -63 65 20 53 68 69 70 20 53 65 74 3B 00 00 54 4F -53 20 45 6E 74 65 72 70 72 69 73 65 2C 20 4B 6C -69 6E 67 6F 6E 20 42 61 74 74 6C 65 63 72 75 69 -73 65 72 2C 20 52 6F 6D 75 6C 61 6E 20 42 69 72 -64 20 6F 66 20 50 72 65 79 14 00 00 46 6F 63 6B -65 2D 57 75 6C 66 20 46 77 31 39 30 20 44 2D 39 -05 00 00 32 34 32 32 38 12 00 00 46 65 72 72 61 -72 69 20 33 36 30 20 4D 6F 64 65 6E 61 07 00 00 -38 35 2D 35 36 30 37 0D 00 00 43 2D 34 37 20 53 -6B 79 74 72 61 69 6E 11 00 00 43 6C 61 73 73 69 -63 20 41 69 72 66 72 61 6D 65 73 03 00 00 34 33 -39 15 00 00 42 72 69 73 74 6F 6C 20 42 6C 65 6E -68 65 69 6D 20 4D 6B 20 49 19 00 00 46 69 6E 6E -69 73 68 2F 59 75 67 6F 73 6C 61 76 20 6D 61 72 -6B 69 6E 67 73 05 00 00 35 31 30 33 38 0F 00 00 -4A 75 6E 6B 65 72 73 20 4A 75 38 37 47 2D 32 16 -00 00 22 53 75 70 65 72 20 44 65 74 61 69 6C 20 -47 75 6E 20 50 6F 64 22 05 00 00 35 31 30 34 30 -0C 00 00 54 79 70 68 6F 6F 6E 20 4D 2E 49 42 0E -00 00 22 53 75 70 65 72 20 44 65 74 61 69 6C 22 -05 00 00 34 38 30 36 31 04 00 00 36 36 37 37 04 -00 00 5A 30 30 35 09 00 00 4D 6F 74 6F 72 69 7A -65 64 07 00 00 38 35 2D 35 38 34 31 39 00 00 77 -2F 56 65 72 6C 69 6E 64 65 6E 20 64 65 74 61 69 -6C 20 73 65 74 20 31 34 37 34 20 61 6E 64 20 54 -72 75 65 20 44 65 74 61 69 6C 73 20 77 68 65 65 -6C 73 20 34 38 30 31 37 45 00 00 77 2F 57 61 72 -72 69 6F 72 20 57 41 20 57 31 30 30 31 20 44 4F -2D 33 33 35 20 22 50 66 69 65 6C 22 20 44 65 74 -61 69 6C 20 53 65 74 2C 20 61 6C 73 6F 20 56 65 -72 6C 69 6E 64 65 6E 20 73 65 74 20 31 36 32 39 -04 00 00 36 37 39 30 0D 00 00 43 75 72 74 69 73 -73 20 50 2D 33 36 41 36 00 00 77 2F 20 53 71 75 -61 64 72 6F 6E 20 63 61 6E 6F 70 79 20 61 6E 64 -20 52 61 72 65 70 6C 61 6E 65 73 20 59 50 2D 33 -37 20 63 6F 6E 76 65 72 73 69 6F 6E 20 6B 69 74 -07 00 00 38 35 2D 37 36 33 33 15 00 00 56 6F 6C -6B 73 77 61 67 65 6E 20 56 61 6E 20 43 61 6D 70 -65 72 04 00 00 38 32 34 38 0F 00 00 48 61 72 64 -20 48 61 74 20 48 61 75 6C 65 72 04 00 00 38 37 -38 39 1A 00 01 43 00 75 00 74 00 2D 00 41 00 77 -00 61 00 79 00 20 00 4D 00 69 00 6C 00 6C 00 65 -00 6E 00 69 00 75 00 6D 00 20 00 46 00 61 00 6C -00 63 00 6F 00 6E 00 22 21 05 00 00 36 31 30 33 -31 20 00 00 55 2E 53 2E 20 4E 61 76 79 20 42 72 -65 77 73 74 65 72 20 46 32 41 2D 32 20 42 75 66 -66 61 6C 6F 05 00 00 36 30 37 34 30 1D 00 00 55 -2E 53 2E 41 2E 46 2E 20 42 65 6C 6C 20 58 2D 31 -20 4D 61 63 68 20 42 75 73 74 65 72 05 00 00 36 -31 30 34 35 21 00 00 48 79 61 6B 75 73 68 69 6B -69 20 53 68 69 74 65 69 20 49 49 49 20 52 65 63 -6F 6E 20 50 6C 61 6E 65 05 00 00 36 31 30 34 37 -1E 00 00 4E 6F 72 74 68 20 41 6D 65 72 69 63 61 -6E 20 52 41 46 20 4D 75 73 74 61 6E 67 20 49 49 -49 07 00 00 38 35 2D 32 35 37 32 14 00 00 41 63 -75 72 61 20 49 6E 74 65 67 72 61 20 54 79 70 65 -20 52 07 00 00 38 35 2D 32 34 38 39 10 00 00 35 -36 20 43 68 65 76 79 AE 20 4E 6F 6D 61 64 AE 04 -00 00 32 32 36 39 10 00 00 43 6F 72 76 65 74 74 -65 20 41 6D 65 72 69 63 61 03 00 00 31 30 34 1F -00 00 4D 65 73 73 65 72 73 63 68 6D 69 74 74 20 -4D 65 2D 33 32 31 20 44 2D 31 20 47 69 67 61 6E -74 05 00 00 36 31 30 34 38 0F 00 00 44 65 77 6F -69 74 69 6E 65 20 44 2E 35 32 30 07 00 00 38 35 -2D 31 36 35 36 4B 00 00 77 2F 69 6E 74 65 72 69 -6F 72 20 61 6E 64 20 65 78 74 65 72 69 6F 72 20 -64 65 74 61 69 6C 20 73 65 74 73 2C 20 65 6E 67 -69 6E 65 73 2C 20 77 68 65 65 6C 20 73 65 74 2C -20 61 6E 64 20 6E 65 77 20 64 65 63 61 6C 73 2C -20 43 44 04 00 00 4A 54 33 31 0D 00 00 50 2D 35 -31 4B 20 4D 75 73 74 61 6E 67 12 00 00 46 6F 63 -6B 65 2D 57 75 6C 66 65 20 46 77 31 39 30 46 04 -00 00 37 31 33 36 1F 00 00 48 6F 74 20 52 6F 64 -20 43 75 73 74 6F 6D 20 4D 6F 64 65 6C 20 27 41 -27 20 50 69 63 6B 75 70 04 00 00 32 37 35 30 19 -00 00 32 39 20 46 6F 72 64 20 50 69 63 6B 75 70 -20 53 74 72 65 65 74 20 52 6F 64 09 00 00 45 53 -43 69 2F 45 52 54 4C 04 00 00 34 31 30 31 12 00 -00 43 75 72 74 69 73 73 20 50 2D 33 36 41 20 48 -61 77 6B 04 00 00 38 30 32 38 16 00 00 31 39 35 -37 20 46 6F 72 64 20 46 61 69 72 6C 61 6E 65 20 -35 30 30 08 00 00 4D 50 43 2F 45 52 54 4C 04 00 -00 36 32 32 31 0E 00 00 44 65 6F 72 61 20 53 68 -6F 77 20 43 61 72 04 00 00 34 38 30 33 1E 00 00 -42 65 6C 6C 20 58 50 2D 37 37 20 4C 69 67 68 74 -77 65 69 67 68 74 20 46 69 67 68 74 65 72 04 00 -00 4A 54 37 35 0E 00 00 46 34 55 2D 35 4E 20 43 -6F 72 73 61 69 72 04 00 00 38 36 31 39 1A 00 00 -4E 6F 72 74 68 72 6F 70 20 59 42 2D 34 39 20 46 -6C 79 69 6E 67 20 57 69 6E 67 04 00 00 38 31 32 -35 04 00 00 42 6F 61 74 1B 00 00 33 20 69 6E 20 -31 20 43 75 73 74 6F 6D 69 7A 69 6E 67 20 42 6F -61 74 20 4B 69 74 04 00 00 32 32 37 38 0E 00 00 -43 69 74 61 74 69 6F 6E 20 54 75 72 62 6F 05 00 -00 34 38 30 33 31 1A 00 00 59 61 6B 2D 37 41 20 -57 57 49 49 20 53 6F 76 69 65 74 20 46 69 67 68 -74 65 72 03 00 00 38 36 31 15 00 00 46 6F 63 6B -65 20 57 75 6C 66 20 54 41 2D 31 35 32 20 48 2D -31 11 00 00 77 2F 4D 6F 73 6B 69 74 20 65 78 68 -61 75 73 74 73 06 00 00 46 75 6A 69 6D 69 16 00 -00 46 6F 63 6B 65 2D 57 75 6C 66 20 46 77 31 39 -30 41 36 2D 3E 41 39 14 00 00 77 2F 54 72 75 65 -20 44 65 74 61 69 6C 20 77 68 65 65 6C 73 06 00 -00 52 55 31 30 30 32 05 00 00 4D 43 2D 30 35 0A -00 00 56 6F 6C 6B 73 77 61 67 65 6E 1C 00 00 53 -74 6F 63 6B 20 6F 72 20 41 41 2F 41 6C 74 65 72 -65 64 20 56 57 20 43 6F 75 70 65 07 00 00 38 35 -2D 35 35 31 30 0D 00 00 42 2D 32 36 20 4D 61 72 -61 75 64 65 72 2C 00 00 53 70 65 63 69 61 6C 20 -45 64 69 74 69 6F 6E 20 77 2F 72 65 73 69 6E 20 -70 61 72 74 73 3B 20 73 6B 69 6C 6C 20 6C 65 76 -65 6C 20 33 06 00 00 4D 65 20 33 30 39 04 00 00 -38 35 38 35 19 00 00 45 6C 65 63 74 72 6F 6E 69 -63 20 58 2D 57 69 6E 67 20 46 69 67 68 74 65 72 -04 00 00 38 30 33 36 0D 00 00 50 2D 34 30 4E 20 -57 61 72 68 61 77 6B 09 00 00 50 72 6F 66 69 70 -61 63 6B 06 00 00 48 2D 31 32 31 37 15 00 00 41 -75 73 74 69 6E 20 48 65 61 6C 65 79 20 31 30 30 -2D 53 69 78 03 00 00 32 31 32 11 00 00 54 68 75 -6E 64 65 72 62 6F 6C 74 20 50 2D 34 37 44 03 00 -00 32 31 35 0D 00 00 46 38 46 2D 32 20 42 65 61 -72 63 61 74 03 00 00 4D 50 4D 05 00 00 34 38 30 -32 38 13 00 00 46 6F 63 6B 65 2D 57 75 6C 66 20 -46 77 20 31 39 30 20 53 2F 00 00 45 78 70 65 72 -74 20 53 65 72 69 65 73 3B 20 77 69 74 68 20 72 -65 73 69 6E 20 61 6E 64 20 70 68 6F 74 6F 2D 65 -74 63 68 20 64 65 74 61 69 6C 07 00 00 38 35 2D -35 37 30 36 12 00 00 42 2D 32 39 20 53 75 70 65 -72 66 6F 72 74 72 65 73 73 16 00 00 77 2F 45 2D -5A 20 6D 61 73 6B 20 63 61 6E 6F 70 79 20 6D 61 -73 6B 20 00 00 77 2F 64 65 74 61 69 6C 20 73 65 -74 20 61 6E 64 20 4D 6F 73 6B 69 74 20 65 78 68 -61 75 73 74 73 33 00 00 53 6B 69 6C 6C 20 6C 65 -76 65 6C 20 33 2C 20 77 69 74 68 20 72 65 73 69 -6E 20 65 6E 67 69 6E 65 20 28 45 6E 67 69 6E 65 -73 20 26 20 54 68 69 6E 67 73 29 05 00 00 34 38 -30 33 34 13 00 00 46 6F 63 6B 65 2D 57 75 6C 66 -20 46 77 20 31 38 39 20 41 05 00 00 32 34 30 34 -36 17 00 00 4C 6F 74 75 73 20 53 75 70 65 72 20 -37 20 53 65 72 69 65 73 20 49 49 04 00 00 33 34 -33 31 10 00 00 42 2D 32 35 43 2F 44 20 4D 69 74 -63 68 65 6C 6C 09 00 00 54 72 69 6D 61 73 74 65 -72 22 00 00 46 6F 63 6B 65 2D 57 75 6C 66 20 46 -77 31 39 30 41 2D 38 2F 52 31 31 20 4E 61 63 68 -74 6A 61 67 65 72 05 00 00 34 38 30 30 31 16 00 -00 4D 65 73 73 65 72 73 63 68 6D 69 74 74 20 42 -66 31 30 39 4B 2D 34 12 00 00 77 2F 72 65 73 69 -6E 20 64 65 74 61 69 6C 20 73 65 74 04 00 00 32 -37 34 31 18 00 00 46 6F 72 64 20 53 74 72 65 65 -74 20 22 54 22 20 52 6F 61 64 73 74 65 72 04 00 -00 30 31 39 34 0E 00 00 54 68 65 20 53 70 61 63 -65 20 54 61 78 69 02 00 00 4A 31 17 00 00 4D 65 -73 73 65 72 73 63 68 6D 69 74 74 20 42 66 31 30 -39 20 45 2D 33 1F 00 00 77 2F 56 65 72 6C 69 6E -64 65 6E 20 73 75 70 65 72 2D 74 65 63 68 20 6B -69 74 20 23 33 38 34 07 00 00 38 35 2D 32 35 31 -37 27 00 00 31 31 20 53 74 65 76 65 20 4B 69 6E -73 65 72 20 51 75 61 6B 65 72 20 53 74 61 74 65 -20 53 70 72 69 6E 74 20 43 61 72 07 00 00 38 35 -2D 37 33 31 30 03 00 00 31 2F 38 0A 00 00 4D 6F -74 6F 72 63 79 63 6C 65 21 00 01 58 00 4C 00 22 -21 20 00 31 00 32 00 30 00 30 00 20 00 53 00 70 -00 6F 00 72 00 74 00 73 00 74 00 65 00 72 00 28 -00 52 00 29 00 20 00 31 00 32 00 30 00 30 00 20 -00 43 00 75 00 73 00 74 00 6F 00 6D 00 04 00 00 -36 31 33 35 1A 00 00 36 32 20 50 6F 6E 74 69 61 -63 20 43 61 74 61 6C 69 6E 61 20 43 75 73 74 6F -6D 03 00 00 39 31 32 0D 00 00 43 75 72 74 69 73 -73 20 52 61 63 65 72 05 00 00 33 31 32 32 30 16 -00 00 32 39 20 46 6F 72 64 20 57 6F 6F 64 79 20 -2F 20 50 69 63 6B 75 70 0B 00 00 52 2E 20 56 2E -20 52 65 73 69 6E 19 00 00 46 6F 63 6B 65 20 57 -75 6C 66 20 54 61 20 31 35 32 43 2D 30 20 28 56 -37 29 07 00 00 38 35 2D 37 36 37 39 2B 00 00 36 -34 20 46 6F 72 64 20 46 61 69 72 6C 61 6E 65 20 -54 68 75 6E 64 65 72 62 6F 6C 74 20 53 74 72 65 -65 74 20 4D 61 63 68 69 6E 65 04 00 00 38 32 30 -37 21 00 00 31 39 36 37 20 43 68 65 76 72 6F 6C -65 74 20 49 6D 70 61 6C 61 20 53 75 70 65 72 20 -53 70 6F 72 74 07 00 00 38 35 2D 31 39 31 34 13 -00 00 43 68 72 79 73 6C 65 72 20 50 54 20 43 72 -75 69 73 65 72 05 00 00 36 31 30 35 34 11 00 00 -41 69 63 68 69 20 4D 36 41 31 20 53 65 69 72 65 -6E 07 00 00 38 35 2D 32 31 34 34 0B 00 01 4B 00 -69 00 6C 00 6C 00 65 00 72 00 20 00 42 00 65 00 -65 00 22 21 1A 00 01 42 00 6C 00 61 00 63 00 6B -00 20 00 54 00 6F 00 70 00 20 00 57 00 61 00 72 -00 72 00 69 00 6F 00 72 00 73 00 22 21 20 00 73 -00 65 00 72 00 69 00 65 00 73 00 05 00 00 33 30 -30 38 39 16 00 00 33 32 20 46 6F 72 64 20 50 68 -61 6E 74 6F 6D 20 56 69 63 6B 69 65 07 00 00 38 -35 2D 34 31 35 31 18 00 00 54 6F 6E 79 20 4E 61 -6E 63 79 27 73 20 52 65 76 65 6C 6C 6C 69 6E 65 -72 07 00 00 38 35 2D 35 38 33 34 0E 00 00 46 2D -31 31 37 41 20 53 74 65 61 6C 74 68 24 00 00 53 -6B 69 6C 6C 20 6C 65 76 65 6C 20 33 2C 20 77 69 -74 68 20 70 68 6F 74 6F 2D 65 74 63 68 20 70 61 -72 74 73 04 00 00 35 36 30 38 0F 00 00 42 2D 32 -34 4A 20 4C 69 62 65 72 61 74 6F 72 04 00 00 4D -41 2D 37 04 00 00 4D 41 2D 33 1B 00 00 48 65 69 -6E 6B 65 6C 20 48 65 31 36 32 41 2D 32 20 56 6F -6C 6B 73 6A 61 67 65 72 05 00 00 33 30 32 37 33 -0C 00 00 41 4D 54 20 41 6D 74 72 6F 6E 69 63 04 -00 00 37 38 30 33 14 00 00 54 42 4D 2D 33 2F 54 -42 46 2D 31 43 20 41 76 65 6E 67 65 72 13 00 00 -77 2F 41 65 72 6F 6D 61 73 74 65 72 20 64 65 63 -61 6C 73 04 00 00 37 38 30 36 1B 00 00 53 42 44 -2D 33 2F 53 42 44 2D 34 2F 53 42 44 2D 35 20 44 -61 75 6E 74 6C 65 73 73 05 00 00 36 31 30 37 31 -20 00 00 46 61 69 72 65 79 20 53 77 6F 72 64 66 -69 73 68 20 4D 6B 2E 49 20 46 6C 6F 61 74 70 6C -61 6E 65 04 00 00 37 35 37 35 10 00 00 44 65 76 -61 73 74 61 74 6F 72 20 54 42 44 2D 31 04 00 00 -32 31 37 39 12 00 00 50 2D 32 36 41 2F 43 20 50 -65 61 73 68 6F 6F 74 65 72 06 00 00 34 35 34 3A -34 39 09 00 00 43 61 72 61 76 65 6C 6C 65 03 00 -00 35 30 36 0D 00 00 4F 56 2D 31 30 41 20 42 72 -6F 6E 63 6F 07 00 00 38 35 2D 35 39 32 39 11 00 -00 50 2D 34 37 4E 20 54 68 75 6E 64 65 72 62 6F -6C 74 diff --git a/test-data/spreadsheet/Booleans.xlsx b/test-data/spreadsheet/Booleans.xlsx deleted file mode 100644 index 752834611..000000000 Binary files a/test-data/spreadsheet/Booleans.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/BrNotClosed.xlsx b/test-data/spreadsheet/BrNotClosed.xlsx deleted file mode 100644 index fdb501a01..000000000 Binary files a/test-data/spreadsheet/BrNotClosed.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/CodeFunctionTestCaseData.xls b/test-data/spreadsheet/CodeFunctionTestCaseData.xls deleted file mode 100644 index 1d31768e1..000000000 Binary files a/test-data/spreadsheet/CodeFunctionTestCaseData.xls and /dev/null differ diff --git a/test-data/spreadsheet/ColumnStyle1dp.xls b/test-data/spreadsheet/ColumnStyle1dp.xls deleted file mode 100644 index 1318b0fa5..000000000 Binary files a/test-data/spreadsheet/ColumnStyle1dp.xls and /dev/null differ diff --git a/test-data/spreadsheet/ColumnStyle1dpColoured.xls b/test-data/spreadsheet/ColumnStyle1dpColoured.xls deleted file mode 100644 index 25dd8de6d..000000000 Binary files a/test-data/spreadsheet/ColumnStyle1dpColoured.xls and /dev/null differ diff --git a/test-data/spreadsheet/ColumnStyleNone.xls b/test-data/spreadsheet/ColumnStyleNone.xls deleted file mode 100644 index 3f0128aad..000000000 Binary files a/test-data/spreadsheet/ColumnStyleNone.xls and /dev/null differ diff --git a/test-data/spreadsheet/ComplexFunctionTestCaseData.xls b/test-data/spreadsheet/ComplexFunctionTestCaseData.xls deleted file mode 100644 index 0d72e7d14..000000000 Binary files a/test-data/spreadsheet/ComplexFunctionTestCaseData.xls and /dev/null differ diff --git a/test-data/spreadsheet/ConditionalFormattingSamples.xls b/test-data/spreadsheet/ConditionalFormattingSamples.xls deleted file mode 100644 index 9b24b857a..000000000 Binary files a/test-data/spreadsheet/ConditionalFormattingSamples.xls and /dev/null differ diff --git a/test-data/spreadsheet/ConditionalFormattingSamples.xlsx b/test-data/spreadsheet/ConditionalFormattingSamples.xlsx deleted file mode 100644 index afaa40aa9..000000000 Binary files a/test-data/spreadsheet/ConditionalFormattingSamples.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/ContinueRecordProblem.xls b/test-data/spreadsheet/ContinueRecordProblem.xls deleted file mode 100644 index c74b864f7..000000000 Binary files a/test-data/spreadsheet/ContinueRecordProblem.xls and /dev/null differ diff --git a/test-data/spreadsheet/CustomXMLMapping-singleattributenamespace.xlsx b/test-data/spreadsheet/CustomXMLMapping-singleattributenamespace.xlsx deleted file mode 100644 index 635dea78f..000000000 Binary files a/test-data/spreadsheet/CustomXMLMapping-singleattributenamespace.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/CustomXMLMappings-complex-type.xlsx b/test-data/spreadsheet/CustomXMLMappings-complex-type.xlsx deleted file mode 100644 index 0d6d8d009..000000000 Binary files a/test-data/spreadsheet/CustomXMLMappings-complex-type.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/CustomXMLMappings.xlsx b/test-data/spreadsheet/CustomXMLMappings.xlsx deleted file mode 100644 index 32a5573c2..000000000 Binary files a/test-data/spreadsheet/CustomXMLMappings.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/CustomXmlMappings-inverse-order.xlsx b/test-data/spreadsheet/CustomXmlMappings-inverse-order.xlsx deleted file mode 100644 index f3acef335..000000000 Binary files a/test-data/spreadsheet/CustomXmlMappings-inverse-order.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/DBCSHeader.xls b/test-data/spreadsheet/DBCSHeader.xls deleted file mode 100644 index d97daf1ed..000000000 Binary files a/test-data/spreadsheet/DBCSHeader.xls and /dev/null differ diff --git a/test-data/spreadsheet/DBCSSheetName.xls b/test-data/spreadsheet/DBCSSheetName.xls deleted file mode 100644 index 17aa94475..000000000 Binary files a/test-data/spreadsheet/DBCSSheetName.xls and /dev/null differ diff --git a/test-data/spreadsheet/DGet.xls b/test-data/spreadsheet/DGet.xls deleted file mode 100644 index 49514d20f..000000000 Binary files a/test-data/spreadsheet/DGet.xls and /dev/null differ diff --git a/test-data/spreadsheet/DStar.xls b/test-data/spreadsheet/DStar.xls deleted file mode 100644 index 0c8926142..000000000 Binary files a/test-data/spreadsheet/DStar.xls and /dev/null differ diff --git a/test-data/spreadsheet/DataTableCities.xlsx b/test-data/spreadsheet/DataTableCities.xlsx deleted file mode 100644 index ca2f66573..000000000 Binary files a/test-data/spreadsheet/DataTableCities.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/DataValidationEvaluations.xlsx b/test-data/spreadsheet/DataValidationEvaluations.xlsx deleted file mode 100644 index 5bf8872bf..000000000 Binary files a/test-data/spreadsheet/DataValidationEvaluations.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/DataValidations-49244.xlsx b/test-data/spreadsheet/DataValidations-49244.xlsx deleted file mode 100644 index ee3f6ef96..000000000 Binary files a/test-data/spreadsheet/DataValidations-49244.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/DateFormatTests.xlsx b/test-data/spreadsheet/DateFormatTests.xlsx deleted file mode 100644 index c6048309b..000000000 Binary files a/test-data/spreadsheet/DateFormatTests.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/DateFormats.xls b/test-data/spreadsheet/DateFormats.xls deleted file mode 100644 index 6b2c3480b..000000000 Binary files a/test-data/spreadsheet/DateFormats.xls and /dev/null differ diff --git a/test-data/spreadsheet/DeltaFunctionTestCaseData.xls b/test-data/spreadsheet/DeltaFunctionTestCaseData.xls deleted file mode 100644 index e66e96cc6..000000000 Binary files a/test-data/spreadsheet/DeltaFunctionTestCaseData.xls and /dev/null differ diff --git a/test-data/spreadsheet/DrawingAndComments.xls b/test-data/spreadsheet/DrawingAndComments.xls deleted file mode 100644 index 8be6c9e52..000000000 Binary files a/test-data/spreadsheet/DrawingAndComments.xls and /dev/null differ diff --git a/test-data/spreadsheet/DrawingContinue.xls b/test-data/spreadsheet/DrawingContinue.xls deleted file mode 100644 index 131c18cc9..000000000 Binary files a/test-data/spreadsheet/DrawingContinue.xls and /dev/null differ diff --git a/test-data/spreadsheet/ElapsedFormatTests.xlsx b/test-data/spreadsheet/ElapsedFormatTests.xlsx deleted file mode 100644 index 95a093e8d..000000000 Binary files a/test-data/spreadsheet/ElapsedFormatTests.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/EmbeddedChartHeaderTest.xls b/test-data/spreadsheet/EmbeddedChartHeaderTest.xls deleted file mode 100644 index af0cb2276..000000000 Binary files a/test-data/spreadsheet/EmbeddedChartHeaderTest.xls and /dev/null differ diff --git a/test-data/spreadsheet/Employee.xls b/test-data/spreadsheet/Employee.xls deleted file mode 100644 index bb9be26b9..000000000 Binary files a/test-data/spreadsheet/Employee.xls and /dev/null differ diff --git a/test-data/spreadsheet/ErrPtg.xls b/test-data/spreadsheet/ErrPtg.xls deleted file mode 100644 index 50035994a..000000000 Binary files a/test-data/spreadsheet/ErrPtg.xls and /dev/null differ diff --git a/test-data/spreadsheet/ExcelTables.xlsx b/test-data/spreadsheet/ExcelTables.xlsx deleted file mode 100644 index 6d9544687..000000000 Binary files a/test-data/spreadsheet/ExcelTables.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/ExcelWithAttachments.xlsm b/test-data/spreadsheet/ExcelWithAttachments.xlsm deleted file mode 100644 index cb3e56442..000000000 Binary files a/test-data/spreadsheet/ExcelWithAttachments.xlsm and /dev/null differ diff --git a/test-data/spreadsheet/FactDoubleFunctionTestCaseData.xls b/test-data/spreadsheet/FactDoubleFunctionTestCaseData.xls deleted file mode 100644 index 885acc157..000000000 Binary files a/test-data/spreadsheet/FactDoubleFunctionTestCaseData.xls and /dev/null differ diff --git a/test-data/spreadsheet/ForShifting.xls b/test-data/spreadsheet/ForShifting.xls deleted file mode 100644 index 7cb3ebd7d..000000000 Binary files a/test-data/spreadsheet/ForShifting.xls and /dev/null differ diff --git a/test-data/spreadsheet/ForShifting.xlsx b/test-data/spreadsheet/ForShifting.xlsx deleted file mode 100644 index f05923b2f..000000000 Binary files a/test-data/spreadsheet/ForShifting.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/FormatChoiceTests.xls b/test-data/spreadsheet/FormatChoiceTests.xls deleted file mode 100644 index 181676383..000000000 Binary files a/test-data/spreadsheet/FormatChoiceTests.xls and /dev/null differ diff --git a/test-data/spreadsheet/FormatChoiceTests.xlsx b/test-data/spreadsheet/FormatChoiceTests.xlsx deleted file mode 100644 index 64b5a1670..000000000 Binary files a/test-data/spreadsheet/FormatChoiceTests.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/FormatConditionTests.xlsx b/test-data/spreadsheet/FormatConditionTests.xlsx deleted file mode 100644 index 22622586f..000000000 Binary files a/test-data/spreadsheet/FormatConditionTests.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/FormatKM.xls b/test-data/spreadsheet/FormatKM.xls deleted file mode 100644 index 79eaff6e3..000000000 Binary files a/test-data/spreadsheet/FormatKM.xls and /dev/null differ diff --git a/test-data/spreadsheet/FormatKM.xlsx b/test-data/spreadsheet/FormatKM.xlsx deleted file mode 100644 index c37c76bd7..000000000 Binary files a/test-data/spreadsheet/FormatKM.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/Formatting.xls b/test-data/spreadsheet/Formatting.xls deleted file mode 100644 index b8354173e..000000000 Binary files a/test-data/spreadsheet/Formatting.xls and /dev/null differ diff --git a/test-data/spreadsheet/Formatting.xlsx b/test-data/spreadsheet/Formatting.xlsx deleted file mode 100644 index b1f2e26a0..000000000 Binary files a/test-data/spreadsheet/Formatting.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/FormulaEvalTestData.xls b/test-data/spreadsheet/FormulaEvalTestData.xls deleted file mode 100644 index b9165649c..000000000 Binary files a/test-data/spreadsheet/FormulaEvalTestData.xls and /dev/null differ diff --git a/test-data/spreadsheet/FormulaEvalTestData_Copy.xlsx b/test-data/spreadsheet/FormulaEvalTestData_Copy.xlsx deleted file mode 100644 index d9dfac62b..000000000 Binary files a/test-data/spreadsheet/FormulaEvalTestData_Copy.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/FormulaRefs.xls b/test-data/spreadsheet/FormulaRefs.xls deleted file mode 100644 index 72da5473e..000000000 Binary files a/test-data/spreadsheet/FormulaRefs.xls and /dev/null differ diff --git a/test-data/spreadsheet/FormulaSheetRange.xls b/test-data/spreadsheet/FormulaSheetRange.xls deleted file mode 100644 index bbac5f239..000000000 Binary files a/test-data/spreadsheet/FormulaSheetRange.xls and /dev/null differ diff --git a/test-data/spreadsheet/FormulaSheetRange.xlsx b/test-data/spreadsheet/FormulaSheetRange.xlsx deleted file mode 100644 index 3da4eb1f8..000000000 Binary files a/test-data/spreadsheet/FormulaSheetRange.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/GeneralFormatTests.xlsx b/test-data/spreadsheet/GeneralFormatTests.xlsx deleted file mode 100644 index 4f34dada2..000000000 Binary files a/test-data/spreadsheet/GeneralFormatTests.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/GroupTest.xlsx b/test-data/spreadsheet/GroupTest.xlsx deleted file mode 100644 index 5feb37e88..000000000 Binary files a/test-data/spreadsheet/GroupTest.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/HyperlinksOnManySheets.xls b/test-data/spreadsheet/HyperlinksOnManySheets.xls deleted file mode 100644 index 1884e57c5..000000000 Binary files a/test-data/spreadsheet/HyperlinksOnManySheets.xls and /dev/null differ diff --git a/test-data/spreadsheet/IfFormulaTest.xls b/test-data/spreadsheet/IfFormulaTest.xls deleted file mode 100644 index d307bee12..000000000 Binary files a/test-data/spreadsheet/IfFormulaTest.xls and /dev/null differ diff --git a/test-data/spreadsheet/ImRealFunctionTestCaseData.xls b/test-data/spreadsheet/ImRealFunctionTestCaseData.xls deleted file mode 100644 index 449e4cd2c..000000000 Binary files a/test-data/spreadsheet/ImRealFunctionTestCaseData.xls and /dev/null differ diff --git a/test-data/spreadsheet/ImaginaryFunctionTestCaseData.xls b/test-data/spreadsheet/ImaginaryFunctionTestCaseData.xls deleted file mode 100644 index ce079f320..000000000 Binary files a/test-data/spreadsheet/ImaginaryFunctionTestCaseData.xls and /dev/null differ diff --git a/test-data/spreadsheet/IndexFunctionTestCaseData.xls b/test-data/spreadsheet/IndexFunctionTestCaseData.xls deleted file mode 100644 index 64df3ecd8..000000000 Binary files a/test-data/spreadsheet/IndexFunctionTestCaseData.xls and /dev/null differ diff --git a/test-data/spreadsheet/IndirectFunctionTestCaseData.xls b/test-data/spreadsheet/IndirectFunctionTestCaseData.xls deleted file mode 100644 index c7f7173ec..000000000 Binary files a/test-data/spreadsheet/IndirectFunctionTestCaseData.xls and /dev/null differ diff --git a/test-data/spreadsheet/InlineStrings.xlsx b/test-data/spreadsheet/InlineStrings.xlsx deleted file mode 100644 index 05db0f9d4..000000000 Binary files a/test-data/spreadsheet/InlineStrings.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/Intersection-52111-xssf.xlsx b/test-data/spreadsheet/Intersection-52111-xssf.xlsx deleted file mode 100644 index 1ff058385..000000000 Binary files a/test-data/spreadsheet/Intersection-52111-xssf.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/Intersection-52111.xls b/test-data/spreadsheet/Intersection-52111.xls deleted file mode 100644 index dd33ffe5a..000000000 Binary files a/test-data/spreadsheet/Intersection-52111.xls and /dev/null differ diff --git a/test-data/spreadsheet/IntersectionPtg.xls b/test-data/spreadsheet/IntersectionPtg.xls deleted file mode 100644 index 74b87db3c..000000000 Binary files a/test-data/spreadsheet/IntersectionPtg.xls and /dev/null differ diff --git a/test-data/spreadsheet/IrrNpvTestCaseData.xls b/test-data/spreadsheet/IrrNpvTestCaseData.xls deleted file mode 100644 index 667493b46..000000000 Binary files a/test-data/spreadsheet/IrrNpvTestCaseData.xls and /dev/null differ diff --git a/test-data/spreadsheet/LookupFunctionsTestCaseData.xls b/test-data/spreadsheet/LookupFunctionsTestCaseData.xls deleted file mode 100644 index 56b6f12a0..000000000 Binary files a/test-data/spreadsheet/LookupFunctionsTestCaseData.xls and /dev/null differ diff --git a/test-data/spreadsheet/MRExtraLines.xls b/test-data/spreadsheet/MRExtraLines.xls deleted file mode 100644 index e82e4f6f4..000000000 Binary files a/test-data/spreadsheet/MRExtraLines.xls and /dev/null differ diff --git a/test-data/spreadsheet/MatchFunctionTestCaseData.xls b/test-data/spreadsheet/MatchFunctionTestCaseData.xls deleted file mode 100644 index 0b98a1771..000000000 Binary files a/test-data/spreadsheet/MatchFunctionTestCaseData.xls and /dev/null differ diff --git a/test-data/spreadsheet/MissingBits.xls b/test-data/spreadsheet/MissingBits.xls deleted file mode 100644 index 4dba467a4..000000000 Binary files a/test-data/spreadsheet/MissingBits.xls and /dev/null differ diff --git a/test-data/spreadsheet/NewStyleConditionalFormattings.xls b/test-data/spreadsheet/NewStyleConditionalFormattings.xls deleted file mode 100644 index fdb241b01..000000000 Binary files a/test-data/spreadsheet/NewStyleConditionalFormattings.xls and /dev/null differ diff --git a/test-data/spreadsheet/NewStyleConditionalFormattings.xlsx b/test-data/spreadsheet/NewStyleConditionalFormattings.xlsx deleted file mode 100644 index 93c034f0b..000000000 Binary files a/test-data/spreadsheet/NewStyleConditionalFormattings.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/NewlineInFormulas.xlsx b/test-data/spreadsheet/NewlineInFormulas.xlsx deleted file mode 100644 index 18dec0aa5..000000000 Binary files a/test-data/spreadsheet/NewlineInFormulas.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/NoGutsRecords.xls b/test-data/spreadsheet/NoGutsRecords.xls deleted file mode 100644 index c4340f6b8..000000000 Binary files a/test-data/spreadsheet/NoGutsRecords.xls and /dev/null differ diff --git a/test-data/spreadsheet/NumberFormatApproxTests.xlsx b/test-data/spreadsheet/NumberFormatApproxTests.xlsx deleted file mode 100644 index db40604b4..000000000 Binary files a/test-data/spreadsheet/NumberFormatApproxTests.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/NumberFormatTests.xlsx b/test-data/spreadsheet/NumberFormatTests.xlsx deleted file mode 100644 index 709a11ea6..000000000 Binary files a/test-data/spreadsheet/NumberFormatTests.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/OddStyleRecord.xls b/test-data/spreadsheet/OddStyleRecord.xls deleted file mode 100644 index dcaa79b5e..000000000 Binary files a/test-data/spreadsheet/OddStyleRecord.xls and /dev/null differ diff --git a/test-data/spreadsheet/PercentPtg.xls b/test-data/spreadsheet/PercentPtg.xls deleted file mode 100644 index 42414766c..000000000 Binary files a/test-data/spreadsheet/PercentPtg.xls and /dev/null differ diff --git a/test-data/spreadsheet/QuotientFunctionTestCaseData.xls b/test-data/spreadsheet/QuotientFunctionTestCaseData.xls deleted file mode 100644 index 729e77485..000000000 Binary files a/test-data/spreadsheet/QuotientFunctionTestCaseData.xls and /dev/null differ diff --git a/test-data/spreadsheet/RangePtg.xls b/test-data/spreadsheet/RangePtg.xls deleted file mode 100644 index 889dd0071..000000000 Binary files a/test-data/spreadsheet/RangePtg.xls and /dev/null differ diff --git a/test-data/spreadsheet/ReadOnlyRecommended.xls b/test-data/spreadsheet/ReadOnlyRecommended.xls deleted file mode 100644 index d479b94f6..000000000 Binary files a/test-data/spreadsheet/ReadOnlyRecommended.xls and /dev/null differ diff --git a/test-data/spreadsheet/ReferencePtg.xls b/test-data/spreadsheet/ReferencePtg.xls deleted file mode 100644 index d415034d1..000000000 Binary files a/test-data/spreadsheet/ReferencePtg.xls and /dev/null differ diff --git a/test-data/spreadsheet/RepeatingRowsCols.xls b/test-data/spreadsheet/RepeatingRowsCols.xls deleted file mode 100644 index 95f4e5019..000000000 Binary files a/test-data/spreadsheet/RepeatingRowsCols.xls and /dev/null differ diff --git a/test-data/spreadsheet/RepeatingRowsCols.xlsx b/test-data/spreadsheet/RepeatingRowsCols.xlsx deleted file mode 100644 index a8a5edf7d..000000000 Binary files a/test-data/spreadsheet/RepeatingRowsCols.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/ReptFunctionTestCaseData.xls b/test-data/spreadsheet/ReptFunctionTestCaseData.xls deleted file mode 100644 index 572f7d4bb..000000000 Binary files a/test-data/spreadsheet/ReptFunctionTestCaseData.xls and /dev/null differ diff --git a/test-data/spreadsheet/RomanFunctionTestCaseData.xls b/test-data/spreadsheet/RomanFunctionTestCaseData.xls deleted file mode 100644 index f630275f7..000000000 Binary files a/test-data/spreadsheet/RomanFunctionTestCaseData.xls and /dev/null differ diff --git a/test-data/spreadsheet/SampleSS.ods b/test-data/spreadsheet/SampleSS.ods deleted file mode 100644 index 549ae96af..000000000 Binary files a/test-data/spreadsheet/SampleSS.ods and /dev/null differ diff --git a/test-data/spreadsheet/SampleSS.strict.xlsx b/test-data/spreadsheet/SampleSS.strict.xlsx deleted file mode 100644 index 6bf19368e..000000000 Binary files a/test-data/spreadsheet/SampleSS.strict.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/SampleSS.txt b/test-data/spreadsheet/SampleSS.txt deleted file mode 100644 index b1dc6b63b..000000000 --- a/test-data/spreadsheet/SampleSS.txt +++ /dev/null @@ -1,21 +0,0 @@ -Author = Nick Burch -Title = Sample Spreadsheet -Subject = Spreadsheet for testing -Keywords = Testing Sample Formulas -Comments = This is a sample spreadsheet, for use when testing things - -(First Sheet) -Test spreadsheet -2nd row 2nd row 2nd column - -This one is red - -(Sheet Number 2) -Start of 2nd sheet -Sheet 2 row 2 - -I'm in bold blue, on a yellow background - -cb=1 cb=10 cb=2 cb=sum -1 10 2 =SUM(A7:C7) - diff --git a/test-data/spreadsheet/SampleSS.xls b/test-data/spreadsheet/SampleSS.xls deleted file mode 100644 index 771aacf91..000000000 Binary files a/test-data/spreadsheet/SampleSS.xls and /dev/null differ diff --git a/test-data/spreadsheet/SampleSS.xlsx b/test-data/spreadsheet/SampleSS.xlsx deleted file mode 100644 index b94809ebc..000000000 Binary files a/test-data/spreadsheet/SampleSS.xlsx and /dev/null differ diff --git a/test-data/spreadsheet/SampleSS.xml b/test-data/spreadsheet/SampleSS.xml deleted file mode 100644 index 45cd58cec..000000000 --- a/test-data/spreadsheet/SampleSS.xml +++ /dev/null @@ -1,142 +0,0 @@ - - - - - Sample Spreadsheet - Spreadsheet for testing - Nick Burch - Testing Sample Formulas - This is a sample spreadsheet, for use when testing things - Nick Burch - 2008-01-04T11:51:36Z - 2008-01-04T11:56:04Z - 14.00 - - - - - - 5580 - 11295 - 360 - 60 - 1 - False - False - - - - - - - - - - Test spreadsheet - - - 2nd row - 2nd row 2nd column - - - This one is red - -
    - - -
    -